[
  {
    "path": ".github/CODESTYLE.md",
    "content": "# WRF-Hydro Fortran Conventions Guide\n\n# Fortran standard\nNew code contributions should be written to at least\n[Fortran 2003 standard](https://gcc.gnu.org/wiki/GFortranStandards#Fortran_2003).\n\n# Source Code Formatting\n* Max line length 100 characters. All wrapped code statements shall at least be indented one\n  additional level beyond the previous level.\n* Do NOT use tab characters.\n* Indentation: 3 spaces (no tabs) for all control below the subroutine/function level (indenting\n  less often saves a lot of space). Tightly nested do loops can be exceptions. Put comments at same\n  indentation level as the code which it is commenting.\n\n\n```fortran\nmodule my_module\ninteger :: local_var\n!==================================================================================================\nsubroutine foo\nimplicit none\n!no indent until control units, line breaks between units\n\ndo i=1,2     ! white space in-line not crucial for readability as in long subroutine calls\n   count=i\nend do ! i=1,2\n\ndo i=1,2\n   do j=i,(i*2)\n      count = i + j\n   end do ! j=i,(i*2)\nend do ! i=1,2\n\ndo i=1,2\ndo j=i,(i*2)    ! control structure is compact, easy to perceive without indentations\n      count = i + j\nend do ! j=i,(i*2)\nend do ! i=1,2\n\nend subroutine foo\n\nend module my_module\n```\n\n* Generally use lower case except for where emphasis is needed.\n* Camel case, vs underscores\n    * firstLowerCamelCase: use most generally\n    * FirstUpperCamelCase: Classes\n    * lowecase_underscore_separated: use for mouldes, subroutines, functions\n    * UPPERCASE_UNDERSCORE_SEPARATED: constants\n\n* Line up related pieces of syntax (readability when there are repeated elements, ability to count\n  the position of arguments), including end-of-line characters.\n\n```fortran\n# WRONG\nfoo=function(apple, banana, corn, &\n      durian, eggplant, fig)\n\n# CORRECT\nfoo=function(apple,  banana,   corn, &\n             durian, eggplant, fig    )\n```\n\n* Place the same number of arguments on each line except the last for countability/position\n  matching.\n\n```fortran\n# WRONG\nfoo=function(a,b,c = 1)\n# CORRECT\nfoo = function(a, b, c=1)\n```\n\n* Horizontal white space: enhances readability, esp w respect to function/subroutine arguments.\n  Whitespace helps identify separate things.\n* Vertical white space:\n  * No vertical white space: Used to group closely-related lines of code.\n  * Single vertical white space: Separate less-related lines of code. After control structures.\n  * Two vertical white spaces: only used to emphasize separation between functions, subroutines and\n    occasionally large code blocks.\n* Control structures identified against their opening statement.\n  * #ifdef:  When nested.\n  * If, do, while, case: Best practice: All the time. Required: when spanning more than one page of\n    vertical space.\n\n```fortran\n#ifdef HYDRO_D\n#ifdef OBSCURE_THING\n…\n#endif /* HYDRO_D */\n#endif /* OBSCURE_THING */\n\n\nif(a .eq. 100) then\n…..\nendif ! if(a .eq. 100)\n\nor\n\nif(a .eq. 100) then  !! a .eq. 100 block\n…\nendif  !! a .eq. 100 block\n```\n\n* Comment blocks above every unit (module, subtroutine, function), with the following form. This\n  should be the NCO standard template.\n\n```fortran\n!===================================================================================================\n! Subroutine Name:\n!   subroutine read_nudging_last_obs\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   does some fancy thing\n! History Log:\n!   02/03/16 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes: Needs better error handling...\n```\n\n\n* Allocate/deallocate statements do NOT span multiple lines. This is so grep can reveal all\n  allocation/deallocation pairs.\n\n```fortran\n# WRONG\nallocate(foo, &\n         bar)\n# CORRECT\nallocate(foo)\nallocate(bar)\nallocate(foo, bar)\n```\n\n# Naming\n## Source file names\n* The name of the source file or script shall represent its purpose. All of the functions in a file\n  shall have a common purpose.\n* Source file names SHALL NOT include spaces nor colons (‘:’) nor any other special\n  characters.\n* End in the `.Fxx` extension, with `xx` corresponding to the fortran standard, e.g. `.F90`\n* Filenames shall use the `lowercase_underscore_separated.Fxx` convention.\n\n## Output file names\n* Source file names SHALL NOT include spaces nor colons (`:`) nor any other special\n  characters.\n\n## Variable names\n* Variable names shall convey their intended use to other developers who did not author the code.\n  This eliminates need for inline comments that describe variables.\n  * DO NOT strive to much for shortening of variable names, prefer meaningful name: local\n    shortening is often possible with the associate construct.\n* Comments/descriptions on variables:\n  * All variables in argument lists will be described in the definition using FORD syntax.\n  * Derived type arguments only need documented in bulk, their individual components only need\n    defined where the derived type is defined.\n  * Variable descriptions will not be redundant with the variable name\n  * Descriptions will describe the physical quantity\n  * Descriptions will include units.\n* Variable names shall contain a noun.\n* Exception: when widely accepted equations have simple variable names. (e.g. `F=m*a`)\n* Loop counters should typically have names.\n* Loop counters should NOT be single letters. Simply doubling the letter makes it easier to search\n  for the use (and possibly replace).\n* Conventions for special kinds of variables:\n  * Accumulation variables: “acc” prefix, e.g.\n  * MPI global variables\n  * prognostic vs diagnostic variables\n  * logical variables must be named to reflect the state they are used to convey, most with the\n    verb to be, e.g. :\n    * `lib_is_initialized` vs `lib_init`\n    * `obj_has_parent` vs `obj_parent`\n\n## Function/Subroutine Names\n* Function names shall contain at least one verb, e.g. `get_name`, `parse_control_string`.\n* Function names shall convey their intended use to other developers who did not author the code.\n* Follow the `lowercase_underscore_separated` convention.\n\n## Constant names\n* Name all constants: Numbers should not be used in the code except in variable definitions.\n* All constants are defined as parameters.\n* Exceptions: should be rare and clearly typed (float, double, etc).\n* Constants follow the `UPPERCASE_UNDERSCORE SEPARATED` convention for naming.\n* Constant names shall describe what the contained value represents within context, e.g.\n  `NO_DATA_VALUE`, `PLANCK_LENGTH`, `HIGH_TEMPERATURE_THRESHOLD`, etc.\n\n# Documenting in the source\n* Code documentation should be a primary source of overall documentation. By following simple\n  practices, such documentation can be extracted to live separately if needed. But keeping it close\n  as possible to the source maintains consistency and improves communication among developers: all\n  you need is the source to understand the code (not other random documents)\n* Write code that documents itself. Try to make code as clear as possible (“self-documenting”) to\n  avoid use of comments and redundancy between the two which needs synchronized or is confusingly\n  out of sync. Writing self-documenting code includes using variable names with obvious meaning and\n  documenting ambiguities in variable names when they exist. Minimize commenting “what” (repeating\n  the code with comments) but do it when it is necessary for interpretation.\n* Document why (not what). Algorithmic choices are often the hardest thing to perceive, not\n  function calls on variables.\n* Indent comments to the indentation level of the code which is being commented.\n* Comments shall be written in English with good spelling, punctuation, and grammar.\n* Documentation shall be placed in the code and [FORD](https://github.com/cmacmackin/ford) will be\n  used to generate documentation.\n* TODO: Comments used to remind developers of future or unfinished actions in source code shall\n  begin with “TODO FML” (first middle last initials, as available), and describe the action to be\n  taken. TODO comments shall also list a specific date or event by which the TODO action will be\n  completed.\n\n```fortran\n! TODO JLM : Rename the variable foo to discharge. Target Date: 12/25/20\n\n! TODO JLM : Rename the variable foo to discharge.\n! TODO JLM : Target Date: 12/25/20\n```\n\n* DEPRECATED: Flagging deprecated code sections shall be done in the following way for automated\n  removal at end-of-version code release.\n\n```fortran\n!DEPRECATED >>>\n!code\n!code\n!<<< DEPRECATED\n```\n\n# File header comments\n* Each source file shall contain one file header comment.\n* File header comments shall contain the following:\n  * A concise description of the collective purpose of file contents.\n      * Exception: When a file contains only one class or function definition, this description\n        shall simply state the file is an implementation or definition file for class/function\n        `<name>`. The class or function description will be written into the class or function\n        header comment.\n* Organization name: National Center for Atmospheric Research\n* Current maintainer\n* Author names. Multiple authors should be listed when more than one developer has worked on a\n  source file over time.\n\n```fortran\n! module_super_foo.F\n! Purpose: This module file contains the derived type and\n!          methods for the super_foo class.\n! National Center for Atmospheric Research\n! Responsible: James L McCreight <jamesmcc>ucar<edu>\n! Authors: James McCreight, Logan Karsten, Wei Yu\n```\n\n# Module/Subroutines/Function Usage\n* Always use modules.\n* Intent: all arguments should be given an intent (in,out, inout),\n* Each argument is defined on its own line. Document details in- or below- line using\n  [FORD](https://github.com/cmacmackin/ford/wiki/Writing-Documentation) conventions.\n  * FORD will ignore a normal comments preceded with a single exclamation mark (!) However,\n    comments with two exclamation marks (!!) are interpreted as documentation and will be captured\n    for inclusion in the FORD output. By default, FORD documentation comes after whatever it is\n    that you are documenting, either at the end of the line or on a subsequent line.\n  * For longer blocks of documentation, it can be inconvenient to continually type the \"docmark\" =\n    ‘!!’. For such situations, the docmark_alt (set to * by default) may be used in the first line\n    of the documentation comment. Any immediately following lines containing only a comment will\n    then be included in the block of documentation, without needing the \"docmark\".\n\n    Example:\n```fortran\nsubroutine feed_pets(cats, dogs, food, angry)\n    !! Feeds your cats and dogs, if enough food is available. If not enough\n    !! food is available, some of your pets will get angry.\n\n    ! Arguments\n    integer, intent(in)  :: cats\n    !! The number of cats to keep track of.\n    integer, intent(in)  :: dogs\n    !! The number of dogs to keep track of.\n    real, intent(inout)  :: food\n    !! The amount of pet food (in kilograms) which you have on hand.\n    integer, intent(out) :: angry\n    !! The number of pets angry because they weren't fed.\n\n    !...\n    return\nend subroutine feed_pets\n```\n\n* Avoid “side effects” (return values are the only thing modified: files are not created,\n  module/global variables are not changed, etc). Use pure functions?\n* `implicit none` for all program units\n* Use `use, only:` as much as possible.\n* Restrict number of passed variables per line in the function/subroutine definition/call to 4 max.\n  Line up variables vertically for ease of reading and counting. Match the call layout to the\n  definition layout.\n* Have a local variables section separate from passed variables\n\n```fortran\n# WRONG\nsome_function(a,b,c,d,e,f,g,h &\n,i,j,k,l)\nreal :: a,b,c,d,e,f\nIngeter :: localVar\nReal, intent(in) :: h,i,j,k,l\n\ncall some_function(a,b,c,d &\n,e,f &\ng,h,i,j,k,l)\n\n# CORRECT\nsome_function(a, b, c, d &\n             ,e, f, g, h &\n             ,i, j, k, l )\nUse module_great_stuff: only, shiny_object, rad_tool\nImplicit none\nreal, intent(in)  :: a !! acceleration   (m/s2)\nreal, intent(in)  :: b !! brownian coeff (-)\nreal, intent(out) :: c !! celerity       (m/s)\n… (etc) …\nreal, intent(in)  :: l !! lousy variable (kgmsK)\n\n!! Local variables\ninteger :: localVar\n\ncall some_function(a, b, c, d &\n                  ,e, f, g, h &\n                  ,i, j, k, l )\n```\n\n# Variable Scoping and Definition\n* Minimize global data.\n* Global data should be limited to constants as much as possible.\n* Define and use global type parameters.\n* Make all derived type components private.\n\n# Run-time error messages\n* Must indicate the function/routine in which they occur.\n* Should be informative.\n\n\n# Compiler warning messages\n* Compilers generally issue two types of messages: warnings and errors. Extent of compiler warning\n  messages can typically be tuned with a compiler option. Compiler warnings normally do not stop\n  the compile process, but can still result in run-time problems. Compiler errors do stop the\n  compile process, forcing the developer to fix the problem and recompile. STANDARD:\n* When available, compiler options should be set to produce the maximum number of warning messages.\n* Compiler and linker warnings shall be treated as errors and fixed.\n\n# Other general guidelines\n* Code should always be written with cleanliness and clarity in mind. Algorithm implementations\n  should not be unnecessarily complicated without significant performance gains over simpler\n  alternatives.\n* Structured programming - do NOT use GOTO\n* Related resources\n  * http://research.metoffice.gov.uk/research/nwp/numerical/fortran90/f90_standards.html\n  * https://github.com/szaghi/zen-of-fortran#standard\n  * http://www.fortran.com/Fortran_Style.pdf\n"
  },
  {
    "path": ".github/CONTRIBUTING.md",
    "content": "# Contributing to WRF-Hydro®\nAll bug reports, bug fixes, code, and documentation contributions are welcome and encouraged.\nHowever, guidelines need to be established and followed to ensure that community contributions can\nbe effectively incorporated.\n\nPlease read the following guidelines carefully before contributing.\n\n# Guidelines\n\n**Failure to adhere to the following guidelines may result in your contributions being permanently\nrejected if they are unable to be merged.**\n\nAll contributions must be made through the\n[NCAR/wrf_hydro_nwm_public](https://github.com/NCAR/wrf_hydro_nwm_public) GitHub page.\nContributions submitted via email or help desk will not be processed.\n\n## Bug reports, feature requests, and documentation suggestions\nAll bug reports, feature requests, and documentation suggestions should be submitted via [GitHub\nissues](https://github.com/NCAR/wrf_hydro_nwm_public/issues). Before submitting your issue, please\nsearch for a few keywords related to your issue in the open and closed issues to discover if your\nissue has already been logged and/or resolved. An issue template has been provided to assist with\nsubmitting bug reports. For more information on using GitHub issues, please see\nhttps://help.github.com/articles/about-issues/.\n\n### Bug reports\nPlease use the supplied issue template when submitting bug reports. This will help ensure that your\nbug is described in sufficient detail. You can read more on how to construct an\nappropriate bug report here: https://stackoverflow.com/help/mcve\n\n### Feature requests\nPlease follow similar guidelines when suggesting new features as you would for reporting bugs. Be\nspecific and detail the added value of your suggested feature.\n\n### Documentation suggestions\nAll technical documentation for the WRF-Hydro model will eventually be formatted as markdown, which\nwill greatly simplify updates and changes in the future. In the meantime, please reference the\ndocument title, page number and quote the line or section for suggesting changes to the\ndocumentation.\n\n## Code contributions\nAll code development contributions will be made via [forks](https://help.github.com/articles/about-forks/)\nand [pull requests](https://help.github.com/articles/about-pull-requests/). If you are\nunfamiliar with GitHub, forks, or pull requests, see [collaborating with issues and pull\nrequests](https://help.github.com/categories/collaborating-with-issues-and-pull-requests/) for guidance.\n\n### WRF-Hydro Fortran code style standards\nPlease see our Fortran [code style guidelines](CODESTYLE.md)\n\n### Universal guidelines\n\n* All code contributions must be made through GitHub following specific guidelines listed below.\n* All contributions must be made in an open, and public way via the GitHub repository. There will\n  be no embargo period for code contributions.\n* All contributions must be able to be merged without conflict. It is the responsibility of the\n  contributor to resolve any merge conflicts **prior** to submitting a pull request.\n* All contributions must pass relevant automated testing procedures. These tests are executed\n  automatically when you submit your pull request.\n* Be respectful when giving and receiving feedback on contributions or issues (see our community [code of conduct](../CODE_OF_CONDUCT.md).\n\n### Pull requests\n\n#### Contributor responsibility\nPull requests will only be accepted if they follow the best practices described below. Not\nfollowing best practices described below is grounds for rejection of pull requests and may result\nin excessive manual work for contributors. It is the contributors’ responsibility to know and\nfollow best git practices.\n\n#### Commits: practices & messages\nLearning to use commits wisely and “atomically” is the foundation for success. As users gain\nfamiliarity with basics of how git works and the merging practices we are using. The next level of\nsophistication is interaction with the git log. Reading logs is greatly facilitated by writing good\nlogs, or “commit messages”. The following webpage gives a crash course on how to write good commit\nmessages: https://chris.beams.io/posts/git-commit/\n\n#### Frequency\nPull requests should happen with high enough frequency to minimize the scope of the code review.\nCommits which do not changes answers (pass regression testing) MUST be kept separate from commits\nwhich do change answers even when the work is on the same feature or bug. The portion of the code\nwhich changes the answer must be isolated as much as possible into its own pull request.\n\n### Types of code contributions\n#### Bug fixes\nAll bug fixes must address a specific [GitHub\nissue](https://github.com/NCAR/wrf_hydro_nwm_public/issues). Only issues labeled with [\"community\ndev\"](https://github.com/NCAR/wrf_hydro_nwm_public/labels/community%20dev) are open to community\ncontributions. The majority of issues will be open to community contributions, but some cases may\nrequire more careful handling. Issues without the \"community dev\" label are either still being\ninvestigated, are of broad scope, or involve changes to code that is actively being developed internally.\n\nAll code changes to address issues must be submitted using a pull request, and the corresponding\nissue number must be referenced in the pull request. For more information on referencing issues,\nsee [issues and keywords](https://help.github.com/articles/closing-issues-using-keywords/).\n\n#### New features\nCode contributions for minor model enhancements or new features follow a similar pattern to bug\nfixes. The proposed feature must be submitted as a GitHub issue and all discussions regarding the\nnew feature should reside in the issue thread. Additionally, work should not begin on the new\nfeature until the issue has been tagged with \"community dev\".\n\nDepending on the scope of the new feature, a WRF-Hydro core contributor may suggest you create a\n[branch](https://help.github.com/articles/about-branches/) to hold all development for the new\nfeature.\n\n#### Research development\nLarger-scale research development, e.g. model coupling, must be coordinated with a WRF-Hydro team\nmember prior to beginning work. This type of development may impact other community projects and\nrequires more careful governance to help steer the direction of model development and maximize\nharmony among the various NCAR, NOAA, and WRF-Hydro community research efforts.\n\n### Checklist for new feature contributions\n#### You should have the following to submit a new feature contribution to the WRF-Hydro code base:\n1. A WRF-Hydro team point of contact (POC). Early in your development process, it is always a good idea\nto reach out to the WRF-Hydro team and find a good POC for your new feature. This person will help\nkeep you informed of new developments as they may relate to your feature, advise you on which branches\nto keep current with (if other than main), and provide pointers on requirements.\n2. New feature code integrated in with the latest WRF-Hydro main branch (or other as advised by your\nWRF-Hydro POC). This merged code should exist in your own fork, but can be in your own main branch or\na separate feature branch.\n   * *TIP #1*: It is always a good strategy to pull the latest WRF-Hydro main code into your branch\nfairly often throughout your development cycle. Leaving months of code changes to merge at the end of\nyour development cycle can result in lots of merge conflicts, time-consuming manual edits, and higher\npotential for making errors.\n   * *TIP #2*: New code should follow the\n[WRF-Hydro code contribution guidelines](https://github.com/NCAR/wrf_hydro_nwm_public/blob/main/.github/CONTRIBUTING.md).\n3. Documentation for your new feature. This should include (1) a simple summary in the release notes\n(added to [NEWS.md](https://github.com/NCAR/wrf_hydro_nwm_public/blob/main/NEWS.md)), and (2) a\ndetailed description of the new feature suitable to be included within the\n[WRF-Hydro Technical Description](https://ral.ucar.edu/sites/default/files/public/projects/wrf_hydro/technical-description-user-guide/wrf-hydro-v5.1.1-technical-description.pdf),\nincluded as a new markdown document in the\n[Doc](https://github.com/NCAR/wrf_hydro_nwm_public/tree/main/trunk/NDHMS/Doc)\nfolder.\n4. An updated\n[standalone test case](https://ral.ucar.edu/projects/wrf_hydro/testcases) demonstrating how\nyour new feature works, based on one of the existing WRF-Hydro test cases (e.g., Croton). If you cannot\nadapt an existing test case and need to create something new, please consult with your POC. The test\ncase should include:\n   * Domain and parameter files\n   * Namelists\n   * Example forcings if needed (idealized forcing use is OK)\n   * Test case documentation\n5. Testing - you must clearly demonstrate that your new feature:\n   * Does no harm to the existing code (e.g., produces identical solutions EXCEPT when the new feature is\nactivated by a namelist or parameter setting).\n   * Fixes a documented issue (reference existing issue in the\n[WRF-Hydro GitHub issue tracking](https://github.com/NCAR/wrf_hydro_nwm_public/issues) - this could also be a feature request).\n   * If model performance is improved, for example through more efficient IO, memory utilization, or other\nsoftware-specific improvements, it must be demonstrable and measurable.\n   * *TIP*: All pull requests go through automated CI testing, but for a new feature it is important to do\nthorough testing ahead of time so you have a good sense of the model impacts and can explain/justify them.\nDo not wait until automated CI testing to test your new feature.\n6. A pull request from a branch on your fork to the WRF-Hydro main branch (or other as advised by your\nWRF-Hydro POC). Make sure to also follow the specific\n[WRF-Hydro pull request guidelines](https://github.com/NCAR/wrf_hydro_nwm_public/blob/main/.github/PULL_REQUEST_TEMPLATE.md).\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Configure '....'\n3. Run '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "TYPE: choose one of [bug fix, enhancement, new feature, feature removed, no impact, text only]\n\nKEYWORDS: approximately 3 to 6 words (more is always better) related to your commit, separated by commas\n\nSOURCE: Developer's name and affiliation\n\nDESCRIPTION OF CHANGES: One or more paragraphs describing problem, solution, and required changes.\n\nISSUE: The GitHub Issue that this PR addresses. For issue number 123, it would be `Fixes #123`\n\nTESTS CONDUCTED: Explicitly state if regression, integration, or unit tests were run before submitting.\n\nNOTES: Optional, as appropriate. Delete if not used.\n\n<!--\nITEMS THAT MIGHT BE USEFUL TO CONSIDER\n - Closes issue #xxxx\n - Tests added (unit tests and/or regression/integration tests)\n - Backwards compatible\n - Documentation included\n - Short description in the Development section of `NEWS.md`\n--->\n"
  },
  {
    "path": ".github/workflows/test-pr.yml",
    "content": "name: build\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\n  # Allows you to run this workflow manually from the Actions tab\n  workflow_dispatch:\n    inputs:\n      pr:\n        description: \"PR to test\"\n        required: true\n\njobs:\n  Model_Testing:\n    if: github.repository == 'NCAR/wrf_hydro_nwm_public'\n    strategy:\n      fail-fast: false\n      max-parallel: 4\n      matrix:\n        configuration: [nwm_ana, nwm_long_range, gridded, reach, reach_lakes]\n    runs-on: ubuntu-latest\n\n    env:\n      MPI_HOME: /usr/share/miniconda\n      NETCDF: /usr/share/miniconda\n      NETCDF_INCLUDES: /usr/share/miniconda/include\n      NETCDF_LIBRARIES: /usr/share/miniconda/lib\n\n\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/setup-python@v5\n        with:\n          python-version: '3.11'\n\n      - name: Checkout candidate (pull request / push)\n        if: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }}\n        uses: actions/checkout@v4\n        with:\n          path: candidate\n\n      - name: Checkout candidate (manual)\n        if: ${{ github.event_name == 'workflow_dispatch' }}\n        env:\n          GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}\n        run: gh repo clone ${{ github.repository }} candidate && cd candidate && gh pr checkout -R ${{ github.repository }} ${{ github.event.inputs.pr }}\n\n      - name: Checkout reference (pull request)\n        if: ${{ github.event_name == 'pull_request' }}\n        uses: actions/checkout@v4\n        with:\n          ref: ${{ github.event.pull_request.base.ref }}\n          path: reference\n\n      - name: Checkout reference (push)\n        if: ${{ github.event_name == 'push' }}\n        uses: actions/checkout@v4\n        with:\n          ref: ${{ github.event.before }}\n          path: reference\n\n      - name: Checkout reference (manual)\n        if: ${{ github.event_name == 'workflow_dispatch' }}\n        env:\n          GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}\n        run: gh repo clone ${{ github.repository }} reference && cd reference && git checkout origin/$(gh pr view ${{ github.event.inputs.pr }} --json baseRefName --jq '.baseRefName')\n\n      - name: Install dependencies with apt-get\n        run: |\n          sudo apt-get update \\\n            && sudo apt-get install -yq --no-install-recommends \\\n            wget \\\n            curl \\\n            bzip2 \\\n            ca-certificates \\\n            libhdf5-dev \\\n            gfortran \\\n            g++ \\\n            m4 \\\n            make \\\n            libswitch-perl \\\n            git \\\n            bc \\\n            openmpi-bin openmpi-common libopenmpi-dev \\\n            libxml2-dev \\\n            libnetcdf-dev \\\n            libnetcdff-dev\n\n      - name: Install dependencies with pip\n        run: |\n          python3 -m pip install matplotlib numpy xarray dask netCDF4 pygithub\n\n      - name: Compile reference\n        run: |\n          cd $GITHUB_WORKSPACE/reference\n          cmake -B build\n          make -C build -j\n\n      - name: Compile candidate\n        run: |\n          cd $GITHUB_WORKSPACE/candidate\n          cmake -B build\n          make -C build -j\n\n      - name: Run reference model\n        run: |\n          cd $GITHUB_WORKSPACE/reference/build/Run\n          make run-croton-${{ matrix.configuration }}\n\n      - name: Run candidate model\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          make run-croton-${{ matrix.configuration }}\n\n      - name: generic - Compare HYDRO_RST.* output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          for file in output_${{ matrix.configuration }}/HYDRO_RST.*; do\\\n            python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n          done\n      - name: generic - Compare RESTART.* output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          for file in output_${{ matrix.configuration }}/RESTART.*; do\\\n            python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n          done\n      - name: generic - Compare last *.CHANOBS_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.CHANOBS_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n      - name: generic - Compare last *.CHRTOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.CHRTOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n      - name: generic - Compare last *.LSMOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.LSMOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n\n      - name: generic - Compare last *.RTOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.RTOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n\n      - name: generic - Compare output with compare_output\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          mkdir output_diff\n          python -c \\\n          \"import sys; \\\n          sys.path.append('${GITHUB_WORKSPACE}/candidate/tests/utils'); \\\n          import compare_output; \\\n          from pathlib import Path; \\\n          compare_output.plot_diffs('${GITHUB_WORKSPACE}/candidate/build/Run/output_diff', \\\n            '${GITHUB_WORKSPACE}/candidate/build/Run/output_${{ matrix.configuration }}/', \\\n            '${GITHUB_WORKSPACE}/reference/build/Run/output_${{ matrix.configuration }}/', \\\n            '${{ matrix.configuration }}')\"\n\n      - name: generic - Copy test results from container\n        if: ${{ always() }}\n        run: |\n          mkdir -p $GITHUB_WORKSPACE/test_report\n          cp -r $GITHUB_WORKSPACE/candidate/build/Run/output_diff/diff_plots/* $GITHUB_WORKSPACE/test_report/\n\n      - name: generic - Attach diff plots to PR\n        if: ${{ failure() }}\n        shell: bash\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/tests/local/utils\n          bash attach_all_plots.bash $(jq --raw-output .pull_request.number \"$GITHUB_EVENT_PATH\") ${{ matrix.configuration }} generic\n\n      - name: generic - Archive test results to GitHub\n        if: ${{ failure() }}\n        uses: actions/upload-artifact@v4\n        with:\n          name: test-reports\n          path: |\n            ${{ github.workspace }}/test_report/*\n\n\n      # n-cores test\n      - name: Run parallel candidate model\n        run: |\n          rm -r $GITHUB_WORKSPACE/test_report/\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          make clean\n          make run-croton-${{ matrix.configuration }}-parallel\n\n      - name: n-cores - Compare HYDRO_RST.* output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          for file in output_${{ matrix.configuration }}/HYDRO_RST.*; do\\\n            python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n          done\n      - name: n-cores - Compare RESTART.* output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          for file in output_${{ matrix.configuration }}/RESTART.*; do\\\n            python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n          done\n      - name: n-cores - Compare last *.CHANOBS_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.CHANOBS_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n      - name: n-cores - Compare last *.CHRTOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.CHRTOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n      - name: n-cores - Compare last *.LSMOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.LSMOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n\n      - name: n-cores - Compare last *.RTOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.RTOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n\n      - name: n-cores - Compare output with compare_output\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          rm -rf output_diff\n          mkdir output_diff\n          python -c \\\n          \"import sys; \\\n          sys.path.append('${GITHUB_WORKSPACE}/candidate/tests/utils'); \\\n          import compare_output; \\\n          from pathlib import Path; \\\n          compare_output.plot_diffs('${GITHUB_WORKSPACE}/candidate/build/Run/output_diff', \\\n            '${GITHUB_WORKSPACE}/candidate/build/Run/output_${{ matrix.configuration }}/', \\\n            '${GITHUB_WORKSPACE}/reference/build/Run/output_${{ matrix.configuration }}/', \\\n            '${{ matrix.configuration }}')\"\n\n      - name: n-cores - Copy test results from container\n        if: ${{ always() }}\n        run: |\n          mkdir -p $GITHUB_WORKSPACE/test_report\n          cp -r $GITHUB_WORKSPACE/candidate/build/Run/output_diff/diff_plots/* $GITHUB_WORKSPACE/test_report/\n\n      - name: n-cores - Attach diff plots to PR\n        if: ${{ failure() }}\n        shell: bash\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/tests/local/utils\n          bash attach_all_plots.bash $(jq --raw-output .pull_request.number \"$GITHUB_EVENT_PATH\") ${{ matrix.configuration }} n-cores\n\n      - name: n-cores - Archive test results to GitHub\n        if: ${{ failure() }}\n        uses: actions/upload-artifact@v4\n        with:\n          name: test-reports\n          path: |\n            ${{ github.workspace }}/test_report/*\n\n\n      # Testing perfect restart, not cleaning candidate model output\n      - name: Setup and run candidate model perfect restart startup\n        run: |\n          rm -r $GITHUB_WORKSPACE/test_report/\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          sed -i 's|RESTART_FILENAME_REQUESTED = \"RESTART/RESTART.2011082600_DOMAIN1\"|RESTART_FILENAME_REQUESTED = \"./RESTART.2011090100_DOMAIN1\"|' namelist.hrldas\n          sed -i 's/KDAY = 7/KDAY = 1/' namelist.hrldas\n          rm output_${{ matrix.configuration }}/RESTART.2011090200_DOMAIN1\n          rm output_${{ matrix.configuration }}/HYDRO_RST.2011-09-02_00:00_DOMAIN1\n          make run-croton-${{ matrix.configuration }}-parallel\n\n      - name: restart - Compare HYDRO_RST.* output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          for file in output_${{ matrix.configuration }}/HYDRO_RST.2011-09-02_00:00_DOMAIN1; do\\\n            python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n          done\n      - name: restart - Compare RESTART.* output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          for file in output_${{ matrix.configuration }}/RESTART.2011090200_DOMAIN1; do\\\n            python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n          done\n      - name: restart - Compare last *.CHANOBS_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.CHANOBS_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n      - name: restart - Compare last *.CHRTOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.CHRTOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n      - name: restart - Compare last *.LSMOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.LSMOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n\n      - name: restart - Compare last *.RTOUT_DOMAIN1 output with xrcmp\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          file=$(ls -t output_${{ matrix.configuration }}/*.RTOUT_DOMAIN1 | head -n 1)\n          python ${GITHUB_WORKSPACE}/candidate/tests/utils/xrcmp.py \\\n              --candidate $file \\\n              --reference $GITHUB_WORKSPACE/reference/build/Run/$file \\\n              --log_file $file_diff.txt \\\n              --n_cores 1; \\\n\n      - name: restart - Compare output with compare_output\n        if: ${{ always() }}\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/build/Run\n          rm -rf output_diff\n          mkdir output_diff\n          python -c \\\n          \"import sys; \\\n          sys.path.append('${GITHUB_WORKSPACE}/candidate/tests/utils'); \\\n          import compare_output; \\\n          from pathlib import Path; \\\n          compare_output.plot_diffs('${GITHUB_WORKSPACE}/candidate/build/Run/output_diff', \\\n            '${GITHUB_WORKSPACE}/candidate/build/Run/output_${{ matrix.configuration }}/', \\\n            '${GITHUB_WORKSPACE}/reference/build/Run/output_${{ matrix.configuration }}/', \\\n            '${{ matrix.configuration }}')\"\n\n      - name: restart - Copy test results from container\n        if: ${{ always() }}\n        run: |\n          mkdir -p $GITHUB_WORKSPACE/test_report\n          cp -r $GITHUB_WORKSPACE/candidate/build/Run/output_diff/diff_plots/* $GITHUB_WORKSPACE/test_report/\n\n      - name: restart - Attach diff plots to PR\n        if: ${{ failure() }}\n        shell: bash\n        run: |\n          cd $GITHUB_WORKSPACE/candidate/tests/local/utils\n          bash attach_all_plots.bash $(jq --raw-output .pull_request.number \"$GITHUB_EVENT_PATH\") ${{ matrix.configuration }} perfect-restart\n\n      - name: restart - Archive test results to GitHub\n        if: ${{ failure() }}\n        uses: actions/upload-artifact@v4\n        with:\n          name: test-reports\n          path: |\n            ${{ github.workspace }}/test_report/*\n"
  },
  {
    "path": ".gitignore",
    "content": "*.o\n*.so\n*.so.*\n*.mod\n*.lst\n*~\nMakefile.comm\ndocs/_build/\nsrc/lib/*\nsrc/macros\nsrc/HRLDAS/user_build_options\n*exe\n/.project\nsrc/Run\nsrc/Run/\nsrc/setEnvar.sh\nsrc/Makefile.comm\nsrc/Land_models/NoahMP/user_build_options\nsrc/Land_models/Noah/user_build_options\nsrc/LandModel\nsrc/LandModel_cpl\nsrc/Land_models/NoahMP/MPP\nbuild/\nREADME.md\n/.idea\n*__pycache__*\n*pytest_cache*\n*.log\ncompile_options.sh\n.DS_Store\n.venv\n.vscode\n"
  },
  {
    "path": ".readthedocs.yaml",
    "content": "# Read the Docs configuration file for Sphinx projects\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details\n\n# Required\nversion: 2\n\n# Set the OS, Python version and other tools you might need\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \"3.11\"\n    # You can also specify other tool versions:\n    # nodejs: \"20\"\n    # rust: \"1.70\"\n    # golang: \"1.20\"\n\n# Build documentation in the \"docs/\" directory with Sphinx\nsphinx:\n  configuration: docs/userguide/conf.py\n  # You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs\n  # builder: \"dirhtml\"\n  # Fail on all warnings to avoid broken references\n  # fail_on_warning: true\n\n# Optionally build your docs in additional formats such as PDF and ePub\nformats:\n    - pdf\n#    - epub\n\n# Optional but recommended, declare the Python requirements required\n# to build your documentation\n# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html\npython:\n   install:\n   - requirements: docs/requirements.txt\n"
  },
  {
    "path": "CITATION.cff",
    "content": "authors:\n  - family-names: Gochis\n    given-names: David\n    orcid: 0000-0001-8668-4850\n    # origin: technical doc\n  - family-names: Barlage\n    given-names: Michael\n    # orcid:\n    # origin: technical doc\n  - family-names: Cabell\n    given-names: Ryan\n    orcid: 0000-0002-3623-5130\n    # origin: technical doc\n  - family-names: Casali\n    given-names: Matthew\n    # orcid: 0000-0001-6939-0332\n    # origin: technical doc\n  # - family-names:\n    # given-names: champham\n    # orcid:\n    # origin: github\n  - family-names: Dugger\n    given-names: Aubrey\n    orcid: 0000-0001-8250-4218\n    # origin: technical doc\n  - family-names: Eidhammer\n    given-names: Trude\n    orcid: 0000-0003-2281-9351\n    # origin: github\n  - family-names: Enzminger\n    given-names: Tom\n    orcid: 0000-0001-5072-3854\n    # origin: technical doc\n  - family-names: FitzGerald\n    given-names: Katelyn\n    orcid: 0000-0003-4184-1917\n    # origin: technical doc\n  - family-names: Felfelani\n    given-names: Farshid\n    orcid: 0000-0003-1360-5095\n    # origin: technical doc\n  - family-names: Gaydos\n    given-names: Andy\n    # origin: technical doc\n  - family-names: Mazrooei\n    given-names: Amir\n    orcid: 0000-0001-9171-9595\n    # origin: technical doc\n  - family-names: McAllister\n    given-names: Molly\n    # orcid:\n    # origin: technical doc\n  - family-names: McCreight\n    given-names: James\n    orcid: 0000-0001-6018-425X\n    # origin: technical doc\n  - family-names: McCluskey\n    given-names: Alyssa\n    # orcid:\n    # origin: technical doc\n  - family-names: Omani\n    given-names: Nina\n    # orcid:\n    # origin: technical doc\n  - family-names: RafieeiNasab\n    given-names: Arezoo\n    # github-names: arezoorn\n    orcid: 0000-0001-8557-107X\n    # origin: technical doc\n  - family-names: Rasmussen\n    given-names: Soren\n    #github-names: scrasmussen\n    orcid: 0000-0003-3899-1463\n    # origin: github\n  - family-names: Read\n    given-names: Laura\n    orcid: 0000-0003-3476-1249\n    # origin: technical doc\n  - family-names: Sampson\n    given-names: Kevin\n    orcid: 0000-0002-5537-7775\n    # origin: technical doc\n  - family-names: Srivastava\n    given-names: Ishita\n    orcid: 0009-0002-4060-6659\n    # origin: technical doc\n  - family-names: Yates\n    given-names: David\n    orcid: 0000-0002-0688-3460\n    # origin: technical doc\n  - family-names: Zhang\n    given-names: Yongxin\n    orcid: 0000-0001-6321-1276\n    # origin: technical doc\n  - family-names: Yu\n    given-names: Wei\n    # github-names:\n    # orcid:\n    # origin:\n  - family-names: Karsten\n    given-names: Logan\n    # github-names: logankarsten\n    # orcid:\n    # origin: github\n  - family-names: Dunlap\n    given-names: Rocky\n    # orcid:\n    # origin: github\n  - family-names: Fanfarillo\n    given-names: Alessandro\n    orcid: 0000-0003-3487-7452\n    # origin: github\n  - family-names: Fersch\n    given-names: Benjamin\n    # orcid:\n    # origin: github\n  - family-names: Heldmyer\n    given-names: Aaron\n    # github: aheldmyer\n    orcid: 0000-0001-8608-4927\n    # origin: github\n  - family-names: Johnson\n    given-names: Donald\n    # github-names: donaldwj\n    # orcid:\n    # origin: github\n  - family-names: Lahmers\n    given-names: Tim\n    # orcid:\n    # origin: github\n  - family-names: Mattern\n    given-names: David\n    # orcid:\n    # origin: github\n  # - family-names:\n    # given-names: Nels\n    # orcid:\n    # origin: github\n  - family-names: Rosen\n    given-names: Dan\n    # orcid:\n    # origin: github\n  - family-names: Valayamkunnath\n    given-names: Prasanth\n    orcid: 0000-0003-2270-0780\n    # origin: github\n\ncff-version: 1.2.0\ndate-released: \"2025-03-14\"\ntitle: \"WRF-Hydro\"\nrepository-code: \"https://github.com/NCAR/wrf_hydro_nwm_public\"\nversion: 5.4.0\nurl: \"https://ral.ucar.edu/projects/wrf_hydro\"\nkeywords:\n  - \"hydrologic model\"\n  - \"hydrology\"\n  - \"hydrometeorology\"\nlicense-url: \"https://github.com/NCAR/wrf_hydro_nwm_public/blob/main/LICENSE.txt\"\nidentifiers:\n  - description: \"This is the archived snapshot of all versions of WRF-Hydro\"\n    type: doi\n    value: 10.5281/zenodo.3625237\n  - description: \"This is the archived snapshot of version v5.4.0 of WRF-Hydro\"\n    type: doi\n    value: 10.5281/zenodo.15040873\n  - description: \"This is the archived snapshot of version v5.3.0 of WRF-Hydro\"\n    type: doi\n    value: 10.5281/zenodo.5773161\n  - description: \"This is the archived snapshot of version v5.2.0 of WRF-Hydro\"\n    type: doi\n    value: 10.5281/zenodo.4479912\n  - description: \"This is the archived snapshot of version v5.1.2 of WRF-Hydro\"\n    type: doi\n    value: 10.5281/zenodo.3678643\n  - description: \"This is the archived snapshot of version v5.1.1 of WRF-Hydro\"\n    type: doi\n    value: 10.5281/zenodo.3625238\nmessage: \"Please cite this software using the metadata from this file.\"\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "cmake_minimum_required (VERSION 3.12)\ncmake_policy(SET CMP0074 NEW) # use xxxx_ROOT env vars\nif (NOT CMAKE_BUILD_TYPE)\n        set(CMAKE_BUILD_TYPE \"Release\")\nendif()\n\n\n# set project name and version numbers\nproject (WRF_Hydro LANGUAGES Fortran C)\nset (WRF_Hydro_VERSION_MAJOR 5)\nset (WRF_Hydro_VERSION_MINOR 4)\nset (WRF_Hydro_VERSION_PATCH 0)\nset (National_Water_Model_VERSION_MAJOR 3)\nset (National_Water_Model_VERSION_MINOR 1)\nset (National_Water_Model_VERSION_PATCH beta)\n\n# set cmake to work with MPI Fortran\nfind_package(MPI REQUIRED)\nadd_compile_options(${MPI_Fortran_COMPILE_FLAGS})\ninclude_directories(${MPI_Fortran_INCLUDE_PATH})\nlink_directories(${MPI_Fortran_LIBRARIES})\nset(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)\nset(CMAKE_SKIP_BUILD_RPATH  FALSE)\nset(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)\n\n# enable ctests\nenable_testing()\n\n#message(\"-- MPI Include directories: \" ${MPI_INCLUDE_PATH} )\n#message(\"-- MPI C COMPILER : \" ${MPI_C_COMPILER} )\n#message(\"-- MPI CXX COMPILER : \" ${MPI_CXX_COMPILER} )\n#message(\"-- MPI Fortran COMPILER : \" ${MPI_Fortran_COMPILER} )\n#message(\"-- MPI COMPILE FLAGS : \" ${MPI_COMPILE_FLAGS} )\n#message(\"-- MPI LINK FLAGS : \" ${MPI_LINK_FLAGS} )\n#message(\"-- MPI Fortran LINK FLAGS : \" ${MPI_Fortran_LINK_FLAGS} )\n#message(\"-- MPI Fortran LINK LIBRARIES : \" ${MPI_Fortran_LIBRARIES} )\n#message(\"-- MPI LIBRARY : \" ${MPI_LIBRARY} )\n#message(\"-- MPI EXTRA LIBRARY : \" ${MPI_EXTRA_LIBRARY} )\n#message(\"-- MPI LIBRARIES : \" ${MPI_LIBRARIES} )\n\n# netcdf does not have a built in package locator so add custom module directory\n# that contains FindNetCDF.cmake\nset(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/src/cmake-modules)\n\n# try to find the installed NETCDF library\nif (NOT TARGET netCDF::netcdff AND TARGET NetCDF::NetCDF_Fortran)\n   add_library(netCDF::netcdff ALIAS NetCDF::NetCDF_Fortran)\nendif()\n\nif (NOT TARGET netCDF::netcdff)\n   set(NETCDF_F90 \"YES\")\n   set(NETCDF_F77 \"YES\")\n   find_package(NetCDF REQUIRED)\n   message(\"-- NetCDF Include Dir(s): ${NETCDF_INCLUDES_F77} ${NETCDF_INCLUDES_F90}\")\nendif()\n\n# set user controled enviorment variables\nset(HYDRO_LSM $ENV{HYDRO_LSM} CACHE STRING \"Name of the Land Surface Model to Use\")\n\n# set enviorment variables if they have not been set\nif (\"${HYDRO_LSM}\" STREQUAL \"\")\n        set(HYDRO_LSM \"NoahMP\")\n        message(\"-- Setting LSM to: NoahMP\")\nendif()\n\n# get the variables defined by setEnvar.sh\nset(WRF_HYDRO $ENV{WRF_HYDRO} CACHE STRING \"WRF environment variable. Always set to 1 for WRF-Hydro\")\nset(HYDRO_D $ENV{HYDRO_D} CACHE STRING \"Print additional debug information in WRF-Hydro\")\nset(WRF_HYDRO_RAPID $ENV{WRF_HYDRO_RAPID} CACHE STRING \"WRF-Hydro coupling to RAPID routing model 0=off 1=on\")\nset(SPATIAL_SOIL $ENV{SPATIAL_SOIL} CACHE STRING \"Spatially distributed soil parameters for NoahMP 0=off 1=on\")\nset(WRFIO_NCD_LARGE_FILE_SUPPORT $ENV{WRFIO_NCD_LARGE_FILE_SUPPORT} CACHE STRING \"Large netCDF file support 0=off, 1=on\")\nset(NCEP_WCOSS $ENV{NCEP_WCOSS} CACHE STRING \"WCOSS file units 0=off 1=on\")\nset(NWM_META $ENV{NWM_META} CACHE STRING \"NWM output metadata 0=off 1=on\")\nset(WRF_HYDRO_NUDGING $ENV{WRF_HYDRO_NUDGING} CACHE STRING \"Streamflow nudging 0=off 1=on\")\nset(OUTPUT_CHAN_CONN $ENV{OUTPUT_CHAN_CONN} CACHE STRING \"Output channel connections\")\nset(PRECIP_DOUBLE $ENV{PRECIP_DOUBLE} CACHE STRING \"Precipitation as double\")\nset(WRF_HYDRO_NUOPC $ENV{WRF_HYDRO_NUOPC} CACHE STRING \"NUOPC library 0=off 1=on\")\n\n#set default values for env variables\nif (WRF_HYDRO STREQUAL \"\")\n        set(WRF_HYDRO \"1\" CACHE STRING \"WRF environment variable. Always set to 1 for WRF-Hydro\" FORCE)\nendif()\n\nif (HYDRO_D STREQUAL \"\")\n        if (CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n                set(HYDRO_D \"1\" CACHE STRING \"Print additonal debug information in WRF-Hydro\" FORCE)\n        else()\n                set(HYDRO_D \"0\" CACHE STRING \"Print additonal debug information in WRF-Hydro\" FORCE)\n        endif()\nendif()\n\nif (WRF_HYDRO_RAPID STREQUAL \"\")\n        set(WRF_HYDRO_RAPID \"0\" CACHE STRING \"WRF-Hydro coupling to RAPID routing model 0=off 1=on\" FORCE)\nendif()\n\nif (SPATIAL_SOIL STREQUAL \"\")\n        set(SPATIAL_SOIL \"0\" CACHE STRING \"Spatially distributed soil parameters for NoahMP 0=off 1=on\" FORCE)\nendif()\n\nif (WRFIO_NCD_LARGE_FILE_SUPPORT STREQUAL \"\")\n        set(WRFIO_NCD_LARGE_FILE_SUPPORT \"0\" CACHE STRING \"Large netCDF file support 0=off, 1=on\" FORCE)\nendif()\n\nif (NCEP_WCOSS STREQUAL \"\")\n        set(NCEP_WCOSS \"0\" CACHE STRING \"WCOSS file units 0=off, 1=on\" FORCE)\nendif()\n\nif (NWM_META STREQUAL \"\")\n        set(NWM_META \"0\" CACHE STRING \"NWM output metadata 0=off, 1=on\" FORCE)\nendif()\n\nif (WRF_HYDRO_NUDGING STREQUAL \"\")\n        set(WRF_HYDRO_NUDGING \"0\" CACHE STRING \"Streamflow nudging 0=off, 1=on\" FORCE)\nendif()\n\nif (OUTPUT_CHAN_CONN STREQUAL \"\")\n        set(OUTPUT_CHAN_CONN \"0\" CACHE STRING \"Output channel connections\" FORCE)\nendif()\n\nif (PRECIP_DOUBLE STREQUAL \"\")\n        set(PRECIP_DOUBLE \"0\" CACHE STRING \"Precipitation as double\" FORCE)\nendif()\n\nif (WRF_HYDRO_NUOPC STREQUAL \"\")\n        set(WRF_HYDRO_NUOPC \"0\" CACHE STRING \"NUOPC library 0=off, 1=on\" FORCE)\nendif()\n\n# add preprocessor defines using env variables\n\nmessage(\"=============================================================\")\nmessage(\"-- Start of WRF-Hydro Env VARIABLES\" )\n\n#always use -DMPP_LAND\nadd_definitions(-DMPP_LAND)\n\n# set -DWRF_HYDRO from env\nmessage(\"WRF_HYDRO = \" ${WRF_HYDRO} )\nif (WRF_HYDRO STREQUAL \"1\" )\n        add_definitions(-DWRF_HYDRO)\nendif()\n\n#set -DHYDRO_D from env\nmessage(\"HYDRO_D = \" ${HYDRO_D} )\nif (HYDRO_D STREQUAL \"1\" )\n        add_definitions(-DHYDRO_D)\nendif()\n\n# set -DWRF_HYDRO_RAPID from env\nif (WRF_HYDRO_RAPID STREQUAL \"1\" )\n        message(\"WRF_HYDRO_RAPID = \" ${WRF_HYDRO_RAPID} )\n        add_definitions(-DWRF_HYDRO_RAPID)\nendif()\n\n#set -DSPATIAL_SOIL from env\nmessage(\"SPATIAL_SOIL = \" ${SPATIAL_SOIL} )\nif (SPATIAL_SOIL STREQUAL \"1\" )\n        add_definitions(-DSPATIAL_SOIL)\nendif()\n\n#set -DWRFIO_NCD_LARGE_FILE_SUPPORT from env\nmessage(\"WRFIO_NCD_LARGE_FILE_SUPPORT = \" ${WRFIO_NCD_LARGE_FILE_SUPPORT} )\nif(WRFIO_NCD_LARGE_FILE_SUPPORT STREQUAL \"1\" )\n        add_definitions(-DWRFIO_NCD_LARGE_FILE_SUPPORT)\nendif()\n\n#set -DNCEP_WCOSS from env\nmessage(\"NCEP_WCOSS = \" ${NCEP_WCOSS} )\nif (NCEP_WCOSS STREQUAL \"1\" )\n        add_definitions(-DNCEP_WCOSS)\nendif()\n\n#set -DNWM_META from env\nmessage(\"NWM_META = \" ${NWM_META} )\nif (NWM_META STREQUAL \"1\" )\n        add_definitions(-DNWM_META)\nendif()\n\n#set -DWRF_HYDRO_NUDGING from env\nmessage(\"WRF_HYDRO_NUDGING = \" ${WRF_HYDRO_NUDGING} )\nif (WRF_HYDRO_NUDGING STREQUAL \"1\" )\n        add_definitions(-DWRF_HYDRO_NUDGING)\nendif()\n\n#set -DOUTPUT_CHAN_CONN from env\nif (OUTPUT_CHAN_CONN STREQUAL \"1\" )\n        message(\"OUTPUT_CHAN_CONN = \" ${OUTPUT_CHAN_CONN} )\n        add_definitions(-DOUTPUT_CHAN_CONN)\n        # requires nudging io module\n        set(WRF_HYDRO_NUDGING_IO \"1\")\nendif()\n\n#set -DPRECIP_DOUBLE from env\nmessage(\"PRECIP_DOUBLE = \" ${PRECIP_DOUBLE} )\nif (PRECIP_DOUBLE STREQUAL \"1\" )\n        add_definitions(-DPRECIP_DOUBLE)\nendif()\n\n#set -DWRF_HYDRO_NUOPC from env\nmessage(\"WRF_HYDRO_NUOPC = \" ${WRF_HYDRO_NUOPC} )\nif (WRF_HYDRO_NUOPC STREQUAL \"1\" )\n        add_definitions(-DWRF_HYDRO_NUOPC)\nendif()\n\noption(BUILD_CROCUS \"Build Crocus\" ON)\noption(WRF_HYDRO_CREATE_EXE_SYMLINK \"Create symlink wrfhydro.exe -> wrfhydro\" ON)\nmessage(\"WRF_HYDRO_CREATE_EXE_SYMLINK = \" ${WRF_HYDRO_CREATE_EXE_SYMLINK} )\n\nmessage(\"=============================================================\")\n\n#set compile flags based on compiler id\nif (CMAKE_Fortran_COMPILER_ID MATCHES \"GNU.*\")\n        # set compile flags for gfortran\n        message( \"-- Using gfortran\")\n        set(CMAKE_Fortran_FLAGS \"-cpp -w -ffree-form -ffree-line-length-none -fconvert=big-endian -frecord-marker=4\")\n        if (CMAKE_Fortran_COMPILER_VERSION VERSION_GREATER_EQUAL 9)\n                set(CMAKE_Fortran_FLAGS \"${CMAKE_Fortran_FLAGS} -fallow-argument-mismatch\")\n        endif()\n        set(CMAKE_Fortran_FLAGS_RELEASE \"-O2\")\n        set(CMAKE_Fortran_FLAGS_DEBUG   \"-O0 -g -fbacktrace\")\nelseif (CMAKE_Fortran_COMPILER_ID MATCHES \"Intel.*\")\n        # set compile flags for ifort\n        message( \"-- Using ifort\")\n        set(CMAKE_Fortran_FLAGS \"-fpp -w -ftz -align all -fno-alias -fp-model precise -FR -convert big_endian\")\n        set(CMAKE_Fortran_FLAGS_RELEASE \"-O2 -march=core-avx2\")\n        set(CMAKE_Fortran_FLAGS_DEBUG   \"-O0 -g -traceback\")\nelseif ((CMAKE_Fortran_COMPILER_ID MATCHES \"PGI.*\") OR (CMAKE_Fortran_COMPILER_ID MATCHES \"NVHPC.*\"))\n        message(\"-- Using NVHPC / PGI\")\n        set(CMAKE_Fortran_FLAGS \"-Mpreprocess -Mfree -byteswapio -Kieee \")\n        set(CMAKE_Fortran_FLAGS_RELEASE \"-O2\")\n        set(CMAKE_Fortran_FLAGS_DEBUG   \"-O0 -g -traceback\")\nelseif ((CMAKE_Fortran_COMPILER_ID MATCHES \"Cray*\"))\n        message(\"-- Using Cray\")\n        set(CMAKE_Fortran_FLAGS \"-eZ -ffree -ef -h alias=none -h fp1 -hbyteswapio\")\n        set(CMAKE_Fortran_FLAGS_RELEASE \"-O3 -G2\")\n        set(CMAKE_Fortran_FLAGS_DEBUG   \"-O0 -G0\") # -traceback\")\nelse()\n        message(\"CMAKE_Fortran_COMPILER full path: \" ${CMAKE_Fortran_COMPILER})\n        message(\"Fortran compiler: \" ${Fortran_COMPILER_NAME})\n        message(\"No optimized Fortran compiler flags are known, we just try -O2...\")\n        set(CMAKE_Fortran_FLAGS \"-cpp\")\n        set(CMAKE_Fortran_FLAGS_RELEASE \"-O2\")\n        set(CMAKE_Fortran_FLAGS_DEBUG   \"-O0 -g\")\nendif()\nmessage(\"-- CMAKE_Fortran_COMPILER full path: \" ${CMAKE_Fortran_COMPILER})\n\n#set output directories for libraries binaries and fortran .mod files\nset(CMAKE_BINARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)\nset(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)\nset(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)\nset(CMAKE_Fortran_MODULE_DIRECTORY ${PROJECT_BINARY_DIR}/mods)\n\n#add common include directores need in the build\ninclude_directories(AFTER ${PROJECT_BINARY_DIR}/mods)\ninclude_directories(AFTER ${MPI_INCLUDE_PATH})\n# include_directories(AFTER ${NETCDF_INCLUDES})  # NOTE: We don't need the C include for netCDF\ninclude_directories(AFTER ${NETCDF_INCLUDES_F77})\ninclude_directories(AFTER ${NETCDF_INCLUDES_F90})\ninclude_directories(AFTER ${PROJECT_SOURCE_DIR}/src/Data_Rec)\n\nadd_subdirectory(\"src\")\nadd_subdirectory(\"tests/ctests\")\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Code of Conduct\n\n## Our Pledge\nWe, as contributors, creators, stewards, and maintainers of WRF-Hydro® pledge to make participation in our software, system or hardware project and community a safe, productive, welcoming and inclusive experience for everyone. All participants are required to abide by this Code of Conduct. This includes respectful treatment of everyone regardless of age, body size, disability, ethnicity, gender identity or expression, level of experience, nationality, political affiliation, veteran status, pregnancy, genetic information, physical appearance, race, religion, or sexual orientation, as well as any other characteristic protected under applicable US federal or state law.\n\n## Our Standards \nExamples of behavior that contribute to creating a positive environment include:\n* All participants are treated with respect and consideration, valuing a diversity of views and opinions\n* Be considerate, respectful, and collaborative\n* Communicate openly with respect for others, critiquing ideas rather than individuals and gracefully accepting criticism\n* Acknowledging the contributions of others\n* Avoid personal attacks directed toward other participants\n* Be mindful of your surroundings and of your fellow participants\n* Alert UCAR staff and suppliers/vendors if you notice a dangerous situation or someone in distress\n* Respect the rules and policies of the project and venue\n\nExamples of unacceptable behavior by participants include:\n* Harassment, intimidation, or discrimination in any form\n* Physical, verbal, or written abuse by anyone to anyone, including repeated use of pronouns other than those requested\n* Unwelcome sexual attention or advances\n* Personal attacks directed at other guests, members, participants, etc.\n* Publishing others' private information such as a physical or electronic address, without explicit permission\n* Alarming, intimidating, threatening, or hostile comments or conduct\n* Inappropriate use of nudity and/or sexual images\n* Threatening or stalking anyone, including a participant\n* Other conduct which could reasonably be considered inappropriate in a professional setting\n\n## Scope\nThis Code of Conduct applies to all spaces managed by the project whether they be physical, online or face-to-face. This includes project code, code repository, associated web pages, documentation, mailing lists, project websites and wiki pages, issue tracker, meetings, telecon, events, project social media accounts, and any other forums created by the project team which the community uses for communication. In addition, violations of this Code of Conduct outside these spaces may affect a person's ability to participate within them. Representation of a project may be further defined and clarified by project maintainers.\n\n## Community Responsibilities\nEveryone in the community is empowered to respond to people who are showing unacceptable behavior. They can talk to them privately or publicly. Anyone requested to stop unacceptable behavior is expected to comply immediately. If the behavior continues concerns may be brought to the project administrators or to any other party listed in the *Reporting* section below.\n\n## Project Administrator Responsibilities\nProject administrators are responsible for clarifying the standards of acceptable behavior and are encouraged to model appropriate behavior and provide support when people in the community point out inappropriate behavior. Project administrator(s) are normally the ones that would be tasked to carry out the actions in the *Consequences* section below.\n\nProject administrators are also expected to keep this *Code of Conduct* updated with the main one housed at UCAR as listed below in the *Attribution* section.\n\n## Reporting\nInstances of unacceptable behavior can be brought to the attention of the [project administrator(s)](https://ral.ucar.edu/projects/wrf_hydro/team) who may take any action as outlined in the *Consequences* section below. However, making a report to a project administrator is not considered an 'official report' to UCAR.\n\nInstances of unacceptable behavior may also be reported directly to UCAR via [UCAR's Harassment Reporting and Complaint Procedure](https://operations.ucar.edu/procedures/hr/harassment-reporting-and-complaint-procedure) or anonymously through [UCAR's EthicsPoint Hotline](https://www.ucar.edu/who-we-are/ethics). \n\nComplaints received by UCAR will be handled pursuant to the procedures outlined in UCAR's Harassment Reporting and Complaint Procedure. Complaints to UCAR will be held as confidential as practicable under the circumstances, and retaliation against a person who initiates a complaint or an inquiry about inappropriate behavior will not be tolerated.\n\nAny contributor can use these reporting methods even if they are not directly affiliated with UCAR. For more information, view the [Frequently Asked Questions (FAQ)](https://operations.ucar.edu/procedures/hr/reporting-faqs) page for reporting.\n\n## Consequences\nUpon receipt of a complaint, the project administrator(s) may take any action deemed necessary and appropriate under the circumstances. Such action can include things such as: removing, editing, or rejecting comments, commits, code, wiki edits, email, issues, and other contributions that are not aligned to this Code of Conduct, or banning temporarily or permanently any contributor for other behaviors that are deemed inappropriate, threatening, offensive, or harmful. Project administrators also have the right to report violations to UCAR HR and/or UCAR's Office of Diversity, Equity, and Inclusion (ODEI) as well as a participant's home institution and/or law enforcement. In the event an incident is reported to UCAR, UCAR will follow its [Harassment Reporting and Complaint Procedure](https://operations.ucar.edu/procedures/hr/harassment-reporting-and-complaint-procedure).\n\n## Process for Changes\nAll UCAR-managed projects are required to adopt this Contributor Code of Conduct. Adoption is assumed even if not expressly stated in the repository. Projects should fill in sections where prompted with project-specific information, including, project name, email addresses, adoption date, etc. There is one section below marked \"optional\", which may not apply to a given project.\n\nProjects that adopt this Code of Conduct need to stay up to date with UCAR's Contributor Code of Conduct, linked in the *Attribution* section below. Projects can make limited substantive changes to the Code of Conduct; however, the changes must be limited in scope and may not contradict the UCAR Contributor Code of Conduct.\n\n## Attribution\nThis Code of Conduct was originally adapted from the Contributor Covenant, version 1.4.1. We then aligned it with the UCAR Participant Code of Conduct, which also borrows from the American Geophysical Union (AGU) Code of Conduct. The UCAR Participant Code of Conduct applies to both UCAR employees, as well as participants in activities run by UCAR. We modified the Scope section with the Django Project description. The original version of this for all software projects that have strong management from UCAR or UCAR staff is available on the UCAR website at https://www.ucar.edu/who-we-are/ethics-integrity/codes-conduct/contributors (the date that it was adopted by this project was 10 July 2019). When responding to complaints, UCAR HR and ODEI will do so based on the latest published version. Therefore, any project-specific changes should follow the Process for Changes section above.\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS AND CONDITIONS:\n\n1. License. Subject to these terms and conditions, University Corporation for Atmospheric Research (UCAR)\ngrants you a non-exclusive, royalty-free license to use, create derivative works, publish, distribute,\ndisseminate, transfer, modify, revise and copy the WRF-Hydro® software, in both object and source code\n(the \"Software\"). You shall not sell, license or transfer for a fee the Software, or any work that in any\nmanner contains the Software.\n\n2. Disclaimer of Warranty on Software. Use of the Software is at your sole risk. The Software is provided\n\"AS IS\" and without warranty of any kind and UCAR EXPRESSLY DISCLAIMS ALL WARRANTIES AND/OR CONDITIONS OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTIES OR CONDITIONS OF TITLE,\nNON-INFRINGEMENT OF A THIRD PARTY?S INTELLECTUAL PROPERTY, MERCHANTABILITY OR SATISFACTORY QUALITY AND\nFITNESS FOR A PARTICULAR PURPOSE. THE PARTIES EXPRESSLY DISCLAIM THAT THE UNIFORM COMPUTER INFORMATION\nTRANSACTIONS ACT (UCITA) APPLIES TO OR GOVERNS THIS AGREEMENT. No oral or written information or advice\ngiven by UCAR or a UCAR authorized representative shall create a warranty or in any way increase the scope\nof this warranty. Should the Software prove defective, you (and neither UCAR nor any UCAR representative)\nassume the cost of all necessary correction.\n\n3. Limitation of Liability. UNDER NO CIRCUMSTANCES, INCLUDING NEGLIGENCE, SHALL UCAR BE LIABLE FOR ANY\nDIRECT, INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES INCLUDING LOST REVENUE, PROFIT OR DATA,\nWHETHER IN AN ACTION IN CONTRACT OR TORT ARISING OUT OF OR RELATING TO THE USE OF OR INABILITY TO USE THE\nSOFTWARE, EVEN IF UCAR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n4. Compliance with Law. All Software and any technical data delivered under this Agreement are subject to\nU.S. export control laws and may be subject to export or import regulations in other countries. You agree\nto comply strictly with all applicable laws and regulations in connection with use and distribution of the\nSoftware, including export control laws, and you acknowledge that you have responsibility to obtain any\nrequired license to export, re-export, or import as may be required.\n\n5. No Endorsement/No Support. The names UCAR/NCAR, National Center for Atmospheric Research and the\nUniversity Corporation for Atmospheric Research may not be used in any advertising or publicity to endorse\nor promote any products or commercial entity unless specific written permission is obtained from UCAR. The\nSoftware is provided without any support or maintenance, and without any obligation to provide you with\nmodifications, improvements, enhancements, or updates of the Software.\n\n6. Controlling Law and Severability. This Agreement shall be governed by the laws of the United States and the\nState of Colorado. If for any reason a court of competent jurisdiction finds any provision, or portion\nthereof, to be unenforceable, the remainder of this Agreement shall continue in full force and effect. This\nAgreement shall not be governed by the United Nations Convention on Contracts for the International Sale of\nGoods, the application of which is hereby expressly excluded.\n\n7. Termination. Your rights under this Agreement will terminate automatically without notice from UCAR if you\nfail to comply with any term(s) of this Agreement. You may terminate this Agreement at any time by destroying\nthe Software and any related documentation and any complete or partial copies thereof. Upon termination, all\nrights granted under this Agreement shall terminate. The following provisions shall survive termination:\nSections 2, 3, 6 and 9.\n\n8. Complete Agreement. This Agreement constitutes the entire agreement between the parties with respect to the\nuse of the Software and supersedes all prior or contemporaneous understandings regarding such subject matter. \nNo amendment to or modification of this Agreement will be binding unless in a writing and signed by UCAR.\n\n9. Notices and Additional Terms. Copyright in Software is held by UCAR. You must include, with each copy of the\nSoftware and associated documentation, a copy of this Agreement and the following notice: \n\n\"The source of this material is the Research Applications Laboratory at the National Center for Atmospheric\nResearch, a program of the University Corporation for Atmospheric Research (UCAR) pursuant to a Cooperative\nAgreement with the National Science Foundation; ©2007 University Corporation for Atmospheric Research. All\nRights Reserved.\" \n\nThe following notice shall be displayed on any scholarly works associated with, related to or derived from\nthe Software: \n\n\"The WRF-Hydro modeling system was developed at the National Center for Atmospheric Research (NCAR) through\ngrants from the National Aeronautics and Space Administration (NASA) and the National Oceanic and Atmospheric\nAdministration (NOAA). NCAR is sponsored by the United States National Science Foundation.\"\n\nBY USING OR DOWNLOADING THIS SOFTWARE, YOU AGREE TO BE BOUND BY THE TERMS AND CONDITIONS OF THIS AGREEMENT.\n"
  },
  {
    "path": "NEWS.md",
    "content": "# WRF-Hydro® v5.4.0 Release Notes\n\nPlease note that starting with WRF-Hydro v5.4, CMake is the preferred\nbuild system. The legacy configure/compile scripts are still present,\nbut should be considered deprecated and will not be supported in\nfuture releases.\n\nWRF-Hydro model documentation has been migrated from individual Word and\nPDF files to an online documentation system that will be hosted alongside\nthe model code in the GitHub repository. Please see the docs/ directory for\nmore details and view the documentation on the web at:\n\nhttps://wrf-hydro.readthedocs.io/en/latest\n\nFor specific updates, reference the PRs listed in the following sections:\n\n## Model Improvements\n  - PR#756: Add initial support for gage-assisted diversions in channel\n    routing, which requires a new optional Diversion netCDF parameter file.\n    This also adds a C compiler dependency\n  - PR#725: `lake_option` added to `&hydro_namelist` to override lake physics\n    options (or turn off lakes completely). Reservoir options have been moved\n    to a new, separate `&reservoir_nlist` namelist\n  - PR#743: liquid water fraction (or snow) added as optional forcing input variables\n    Forcing variables names can now be supplied as namelist inputs\n  - PR#782: documentation converted to readthedocs, also PR#786, PR#785,\n    PR#774, PR#789, PR#795, PR#796, PR#792, PR#799, PR#798, PR#791, PR#799,\n    PR#798, PR#797, PR#805, PR#804, PR#809, PR#810\n\n## Bugfixes:\n  - PR#803, PR#808: `lake_option` bugfixes\n  - PR#813: Finding NetCDF fix for new Derecho environment\n  - PR#811: Adding routing diversion Makefiles\n  - PR#785: Support Fedora MPI environmental variables for NetCDF\n  - PR#752: LSM accumulations not reset if `RSTRT_SWC` equals `no reset`\n  - PR#729: Crocus glacier arrays changed to `optional` from `allocatable`\n  - Bugfixes: CMake nudging parallel build\n\n## General cleanup and misc.\n  - PR#802: increment version numbers\n  - PR#794: input namelists and parametere tables\n  - PR#790: PR template updates\n  - PR#764: adding deprecation warning to configure build, CMake preferred\n  - PR#739: general CMake improvements, tabs to spaces\n  - PR#720: header info from files removed\n  - PR#724: redundant return statements removed\n  - PR#723: MPI case style fixed\n  - PR#733: .F -> .F90 file renaming\n  - PR#717: Added citation file"
  },
  {
    "path": "docs/BUILD.rst",
    "content": "Build\n===========\n\n\nRequirements\n~~~~~~~~~~~~\n\n+------------+---------+\n|Compiler    | Version |\n+============+=========+\n| GNU        | 11+     |\n+------------+---------+\n| Intel      | 2023+   |\n+------------+---------+\n| NVidia     | 23+     |\n+------------+---------+\n| Cray       | 15+     |\n+------------+---------+\n\n+--------------------+---------+\n| Libraries/Software | Version |\n+====================+=========+\n| MPI                | 3.x+    |\n+--------------------+---------+\n| Fortran NetCDF     | 4.4+    |\n+--------------------+---------+\n| CMake              | 3.12+   |\n+--------------------+---------+\n\nNote: Supported compiler versions are chosen based on long-term support (LTS) status, ensuring they continue to receive security and bug fixes.\n\nInstall dependencies for Debain/Ubuntu\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n.. code-block:: bash\n\n    $ apt install -y git cmake libnetcdff-dev mpi-default-dev\n\n\nInstall/activate dependencies for Red Hat/Fedora\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n.. code-block:: bash\n\n    $ dnf install -y git cmake netcdf-fortran-mpich-devel\n    <log out and back in to activate environment modules>\n    $ module load mpi\n\n\nCMake Build\n~~~~~~~~~~~\n\n.. code-block:: bash\n\n    $ mkdir build\n    $ cd build\n    $ cmake ..\n    $ make -j 4\n\nThe executables, namelists and tables are now in the ``build/Run`` directory.\nTestcases with domain setups can be found `here <https://ral.ucar.edu/projects/wrf_hydro/testcases>`_.\nTo build with additional functionality, enter ``cmake .. -DFOO=1`` where the\navailable options are described in the following table.\n\n+------------------------------------+-------------------------------------------------------------------------------+\n| CMake WRF-Hydro Specific Options   | Functionality                                                                 |\n+====================================+===============================================================================+\n| ``-DWRF_HYDRO=1``                  | Default: turn on WRF-Hydro                                                    |\n+------------------------------------+-------------------------------------------------------------------------------+\n| ``-DHYDRO_D=1``                    | Enhanced diagnostic output for debugging                                      |\n+------------------------------------+-------------------------------------------------------------------------------+\n| ``-DSPATIAL_SOIL=1``               | Spatially distributed parameters for NoahMP                                   |\n+------------------------------------+-------------------------------------------------------------------------------+\n| ``-DWRF_HYDRO_NUDGING=1``          | Enable the streamflow nudging routines for Muskingum-Cunge Routing            |\n+------------------------------------+-------------------------------------------------------------------------------+\n| ``-DNWM_META=1``                   | Output NWM Metadata                                                           |\n+------------------------------------+-------------------------------------------------------------------------------+\n| ``-DPRECIP_DOUBLE=1``              | Double precipitation from hydro forcing                                       |\n+------------------------------------+-------------------------------------------------------------------------------+\n| ``-DNCEP_WCOSS=1``                 | Do not use unless working on the WCOSS machines                               |\n+------------------------------------+-------------------------------------------------------------------------------+\n\n+------------------------------------+-------------------------------------------------------------------------------+\n| Unsupported Functionality          |                                                                               |\n+====================================+===============================================================================+\n| ``-DWRF_HYDRO_NUOPC=1``            | Coupling with NUOPC, this option is not currently supported                   |\n+------------------------------------+-------------------------------------------------------------------------------+\n\n\nCMake Testcase\n~~~~~~~~~~~~~~\n\nTo download and setup the Croton testcase in ``build/Run`` use one of the\nfollowing commands.\nThe first time the ``croton.tar.gz`` file will be downloaded, extracted, and configured.\nFuture commands will reconfigure the ``Run`` directory.\n\n+---------------------------------+\n| Make Command                    |\n+=================================+\n| make croton                     |\n+---------------------------------+\n| make croton-gridded             |\n+---------------------------------+\n| make croton-gridded-no-lakes    |\n+---------------------------------+\n| make croton-nwm                 |\n+---------------------------------+\n| make croton-nwm_ana             |\n+---------------------------------+\n| make croton-nwm_longe_range     |\n+---------------------------------+\n| make croton-reach               |\n+---------------------------------+\n| make croton-reach-lakes         |\n+---------------------------------+\n"
  },
  {
    "path": "docs/Makefile",
    "content": "SOURCEDIR = userguide/\nBUILDDIR = _build/html\n\n# List all source files to track dependencies\nSOURCE_FILES = $(shell find . -name '*.rst' -o -name '*.rest' -o -name '*.py' -o -name '*.css')\n\nall: build\n\nbuild: $(BUILDDIR)/index.html\n\n$(BUILDDIR)/index.html: $(SOURCE_FILES)\n\t@echo \"Building readthedocs documentation\"\n\tsphinx-build -b html $(SOURCEDIR) $(BUILDDIR)\n\t@echo \"Open $(BUILDDIR)/index.html to preview readthedocs documentation\"\n\nopen: build\n\topen $(BUILDDIR)/index.html\n\nclean:\n\trm -rf _build\n"
  },
  {
    "path": "docs/requirements.txt",
    "content": "sphinx_rtd_theme\n"
  },
  {
    "path": "docs/userguide/_static/ug_theme.css",
    "content": ".wy-nav-content {\n    max-width: 1000px !important;\n}\n\n.center {\n    text-align: center;\n}\n\n.underline {\n    text-decoration: underline;\n}\n\n.filename {\n    font-family: Courier, \"Courier New\", monospace;\n    white-space: pre-wrap;\n}\n\n.program {\n    font-family: Courier, \"Courier New\", monospace;\n    white-space: pre-wrap;\n    color: greenyellow;\n    background-color: black;\n    padding-left: 5px;\n    padding-right: 5px;\n}\n\n.wy-table-responsive table td, .wy-table-responsive table th {\n    white-space: normal;\n}"
  },
  {
    "path": "docs/userguide/appendices.rest",
    "content": ".. vim: syntax=rst\n.. include:: meta.rest\n.. role:: raw-html(raw)\n   :format: html\n\nAPPENDICES\n==========\n\nThis section contains supplementary information.\n\n.. _section-a1:\n\nA1. Standalone (Uncoupled) WRF-Hydro Test Case User Guide\n---------------------------------------------------------\n\nPurpose\n^^^^^^^\n\nThis example test case is meant to orient you to running the\nWRF-Hydro modelling system using prepared geographical inputs, and\nprepared forcing data for a specific region (domain). We provide\nbaseline instructions to test that your WRF-Hydro executable was\ncompiled correctly and is able to run on your system. Please see the\nReadme.txt file provided with the test case for specific file\ndescriptions and a regional description.\n\nThis test case provides example namelists and prepared geographical\ninput files for three routing configurations. While the step-by-step\nwalkthrough instructions here guide you through running the Gridded\nconfiguration we suggest that you explore the other routing\nconfigurations and related namelists for reference.\n\nFor further information on the WRF-Hydro modeling system and possible\ntraining opportunities, please visit https://ral.ucar.edu/projects/wrf_hydro.\n\nRequirements\n^^^^^^^^^^^^\n\n- WRF-Hydro source code:\n   - https://github.com/NCAR/wrf_hydro_nwm_public.git\n   - ``git clone`` into directory where you will be running this case\n\n- An official WRF-Hydro example test case:\n   -  Download from: https://ral.ucar.edu/projects/wrf_hydro/testcases\n   -  or from release assets at: https://github.com/NCAR/wrf_hydro_nwm_public/releases\n\n- All system libraries needed by the WRF-Hydro modeling system can be found\n  in the :ref:`build instructions <section-2.8>`.\n\nStep-by-step walkthrough\n^^^^^^^^^^^^^^^^^^^^^^^^\n**Directory structure setup**:\n\nWe will organize all files and folders under a common top-level\ndirectory to simplify commands in this walkthrough. All paths mentioned\nin this walkthrough will be relative to this top-level directory. For\nexample, :file:`/home/user/project_directory/example_case/` will be referred to\nas :file:`example_case/`.\n\n#. Open a terminal window\n\n#. Create a top-level directory that will hold all subdirectories and\n   files used for this walkthrough. Hereafter referred to as the\n   ‘project directory’.\n\n#. Copy the uncompressed WRF-Hydro source code into the project\n   directory created in step 2.\n\n#. Copy the example case directory into\n   the project directory as well.\n\n#. An example of your project directory structure using the Croton, NY\n   example test case would look like the following:\n\n.. code-block:: console\n\n   project_directory/\n     ├──wrf_hydro_nwm_public/\n     |      ├──src/\n     |\n     ├──example_case/\n             ├──Gridded_no_lakes/\n             ├──Gridded/\n             ├──NWM/\n             ├──Reach/\n             ├──ReachLakes/\n             ├──FORCING/\n             ├──supplemental/\n             ├──Readme.txt\n\nCompiling the Code\n^^^^^^^^^^^^^^^^^^\n\nIf you have not built WRF-Hydro before on your current system, please follow the\ninstructions in the :ref:`build instructions <section-2.8>` to ensure you have all\nthe necessary library dependencies available. If you have already built WRF-Hydro,\nyou can skip to step \"CMake Build\", repeated here:\n\n.. code-block::  bash\n\n    $ cd project_directory/wrf_hydro_nwm_public  # project_directory/ from above\n    $ mkdir build\n    $ cd build\n    $ cmake -DHYDRO_D=1 [-DWRF_HYDRO_NUDGING=1] ..   # include -DWRF_HYDRO_NUDGING=1 if you want to use the NWM test case\n    $ make -j 4\n\nThe executables, namelists and tables will be created in the ``build/Run`` directory.\n\nRunning a WRF-Hydro Simulation\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIn this section we will use our compiled WRF-Hydro model and an\nexample test case to run a WRF-Hydro simulation. This walkthrough is\nusing the Croton, NY example test case. After extracting the Croton tarball\ndetails on the domain and time period of the simulation are provided in the\n:file:`example_case/Readme.txt` file.\n\n1. First we need to copy the TBL and executable files in the\n   :file:`wrf_hydro_nwm_public*/src/build/Run`\n   directory to the directory\n   containing the domain and forcing files. For the WRF-Hydro Gridded\n   configuration, these files are located in the directory\n   :file:`example_case/Gridded`.\n\n   Copy the :file:`*.TBL` files to the example configuration directory:\n\n      | *(from your project directory)*\n      | :code:`cp wrf_hydro_nwm_public*/build/Run/\\*.TBL example_case/Gridded`\n\n   Copy the :file:`wrf_hydro` file:\n\n      :code:`cp wrf_hydro_nwm_public*/build/Run/wrf_hydro example_case/Gridded`\n\n   .. note:: There are other configuration subfolders with the names such as :file:`Gridded`, :file:`nwm`, and\n      :file:`Reach`. These folders contain prepared files for other configurations of WRF-Hydro. They are found\n      under the :file:`src/template/` directory. Information\n      regarding physics options and routing configurations can be found in the main body of the *WRF-Hydro*\n      v\\ |version_short| *Technical Description*. Also, note that there is only one :file:`FORCING/` directory.\n      The same forcing data can be used for all configurations.\n\n2. Next, we need to link our forcing data to the :file:`Gridded/` directory.\n\n   From the :file:`example_case/Gridded directory`, create a symlink:\n\n      :code:`ln -s ../FORCING .`\n\n   Your project directory should now have the following\n   directory structure and files:\n\n   .. code-block:: console\n\n      project_directory/\n      ├──wrf_hydro_nwm_public/\n      |      ├──src/\n      |      ├──build/\n      |\n      ├──example_case/\n               ├──Gridded/\n                  ├──FORCING/\n                  ├──DOMAIN/\n                  ├──RESTART/\n                  ├──referenceSim/\n                  ├──CHANPARM.TBL\n                  ├──GENPARM.TBL\n                  ├──HYDRO.TBL\n                  ├──MPTABLE.TBL\n                  ├──SOILPARM.TBL\n                  ├──hydro.namelist\n                  ├──namelist.hydrodas\n                  ├──wrf_hydro\n\n3. Now we will run the simulation. Note that there are many options\n   and filepaths that need to be set in the two namelist files\n   :file:`hydro.namelist` and :file:`namelist.hrldas`. However, for this\n   walkthrough these files have been prepared for you.\n\n   Before running the model, ensure you are in the :file:`example_case/Gridded`\n   directory.\n\n   We will now run the model using :command:`mpirun` with 2 cores. This command may\n   differ depending on your system configuration, but here is an example\n   of what this might look like:\n\n   .. code-block:: bash\n\n      mpirun -np 2 ./wrf_hydro\n\n4. If your simulation ran successfully, there should now be a large\n   number of output files. Descriptions of the output files and their contents\n   can be found in :ref:`Appendix A19 <section-a19>`. There are also two\n   important files for determining the success or failure of the run,\n   :file:`diag_hydro.00000` and :file:`diag_hydro.00001`. These :file:`diag_hydro`\n   files contain logs and diagnostics on the simulation run, and one file is\n   produced per core used in the run. Since we ran using 2 cores, we\n   have 2 :file:`diag_hydro` files.\n\n   You can check that your simulation ran successfully by examining the\n   last line of the diag files, which should read:\n\n   .. code-block:: console\n\n      The model finished successfully........\n\n   If this line is not present, the simulation did not finish\n   successfully.\n\n5. You can check the validity of your simulation results by comparing\n   the restart files produced during your model run with the restart\n   files included in the :file:`example_case/Gridded/referenceSim` directory.\n   The restart files contain all the model states and thus provide a\n   simple means for testing if two simulations produced the same\n   results.\n\n.. note:: Our current example test cases have only been run and tested with\n   the Noah-MP land surface model. For information regarding running\n   WRF-Hydro with Noah please see :ref:`Appendix A3 <section-a3>`.\n\n\n.. _section-a2:\n\nA2. Coupled WRF | WRF-Hydro Test Case User Guide\n------------------------------------------------\n\nPurpose\n^^^^^^^\n\nThis test case for the coupled WRF | WRF-Hydro modeling system is meant to\norient you to running the modeling system using prepared geographical inputs\nfor WRF-Hydro and sample initial and boundary conditions for WRF. Note that\nsome of the initial and boundary conditions for this test case have been\nmodified in order to produce a hydrologic response over a very limited spatial\ndomain. Results generated from this test case should not be interpreted as a\nreal simulation and users should consult the WRF and WPS documentation for\nbest practices with respect to domain and model configuration. The purpose of\nthis test case is to provide baseline instructions and a computationally\ntractable test case for users to familiarize themselves with the modeling\nsystem and help ensure the modeling system is running properly on their\nsystems. Please see the README.txt file provided with the test case for a more\ndetailed description of the contents.\n\nFor a detailed technical description of WRF-Hydro and instructions on how to run WRF |\nWRF-Hydro in coupled mode see the `WRF-Hydro Technical Description\ndocumentation <https://wrf-hydro.readthedocs.io/>`_ and How\nto Run WRF-Hydro V5 in Coupled Mode user guide available from\nhttps://ral.ucar.edu/projects/wrf_hydro.\n\nFor further information regarding the WRF model and the WRF Preprocessing System (WPS)\nsee the WRF Users’ Guide located here:\nhttp://www2.mmm.ucar.edu/wrf/users/docs/user_guide_v4/contents.html\n\nRequirements\n^^^^^^^^^^^^\n\n- WRF-Hydro source code: https://github.com/NCAR/wrf_hydro_nwm_public.git\n   - Git clone into directory where you will be running this case\n- Download WRF and WPS source code:\n   - WRF: https://github.com/wrf-model/WRF\n   - WPS: https://github.com/wrf-model/WPS\n- WPS geographic data\n  http://www2.mmm.ucar.edu/wrf/src/wps_files/geog_high_res_mandatory.tar.gz\n- An official WRF-Hydro coupled test case:\n  https://ral.ucar.edu/projects/wrf_hydro/testcases\n- All system libraries needed by the WRF-Hydro modelling system can be found\n  in the How To Build & Run WRF-Hydro V5 in Standalone Mode user guide and the\n  FAQ web page located at https://ral.ucar.edu/projects/wrf_hydro\n- All system libraries needed by the WRF modeling system and WPS can be found\n  in the WRF User’s Guide located here:\n  http://www2.mmm.ucar.edu/wrf/users/docs/user_guide_v4/contents.html\n\n\nStep-by-step walkthrough\n^^^^^^^^^^^^^^^^^^^^^^^^\n**Directory structure setup**:\nWe will organize all files and folders under a common top-level directory to\nsimplify commands in this walkthrough. All paths mentioned in this walkthrough\nwill be relative to this top-level directory. For example,\n/home/user/project_directory/example_case_coupled/ will be referred to as\nexample_case_coupled/. The following steps walk you through how to setup your\nproject directory.\n\n1. Open a terminal window\n2. Create a top-level directory that will hold all subdirectories and files\n   used for this walkthrough. Hereafter referred to as the ‘project\n   directory’.\n3. Git clone WRF-Hydro, WRF, and WPS into project directory created in step 2.\n   Here are examples of possible commands to use, modify as needed:\n\n.. code-block:: console\n\n  git clone https://github.com/NCAR/wrf_hydro_nwm_public.git\n  git clone --recurse-submodule --branch v4.7.1 https://github.com/wrf-model/WRF.git\n  git clone --branch v4.6.0 https://github.com/wrf-model/WPS.git\n\n\n4. Download and extract testcase and geographic data.\n\n.. code-block:: console\n\n  # download and extract files\n  wget https://github.com/NCAR/wrf_hydro_nwm_public/releases/download/v5.4.0/front_range_CO_example_testcase_coupled.tar.gz\n  tar zxf front_range_CO_example_testcase_coupled.tar.gz\n\n  # Note this geog data is currently broken, Derecho users should skip this\n  # step and in namelists.wps set\n  # geog_data_path = '/glade/work/wrfhelp/WPS_GEOG/',\n  wget http://www2.mmm.ucar.edu/wrf/src/wps_files/geog_high_res_mandatory.tar.gz\n  tar zxf geog_high_res_mandatory.tar.gz\n\n\n\n5. Move the newly extracted geographic data into the WPS directory.\n\n.. code-block:: console\n\n  # create directory and move geopgraphic data\n  mkdir -p run/WPS\n  mv WPS_GEOG/ run/WPS/geog\n\n\n6. Your project directory structure will look like the following:\n\n.. code-block:: console\n\n   project_directory/\n   ├──run/\n   │   ├──WPS/\n   │   └──WRF/\n   ├──wrf_hydro_nwm_public*/\n   │   └──src/\n   ├──WRF/\n   ├──WPS/\n   │   ├──geogrid/\n   │   ├──metgrid/\n   │   ├──ungrib/\n   │   └──geog/\n   └──example_case_coupled/\n       ├──WRF_FORCING/\n       └──DOMAIN/\n\n\nCompiling the Code\n^^^^^^^^^^^^^^^^^^\n\nThis section will walk you through compiling the coupled WRF | WRF-Hydro\nmodeling system and the WRF Preprocessing System (WPS) utilities\n\n**Compiling the coupled WRF | WRF-Hydro modeling system**\n\n1. Navigate to the WRF source code directory at WRF\n\n.. code-block:: console\n\n  cd WRF\n\n2. Remove the old WRF-Hydro source code contained within this directory and replace it\nwith the updated version you just downloaded\n\n.. code-block:: console\n\n  rm -r hydro\n  cp -r ../wrf_hydro*/src hydro\n\n3.  Load appropriate modules on Derecho, the following is an example for GNU compilers.\n\n.. code-block:: console\n\n  module purge\n  module load ncarenv gcc ncarcompilers cray-mpich craype netcdf cmake\n\n4. Configure and compile WRF\n\n.. warning::\n   **On Derecho, use the legacy configure method. CMake has known issues with the coupled case.**\n   **Use the legacy configure method for building both WRF and WPS**\n\n\n4a. Configure and compile WRF: CMake\n\n.. code-block:: console\n\n      # CMake option to turn on WRF-Hydro nudging `-DWRF_HYDRO_NUDGING=1`\n      ./configure_new -x -p gfortran/gcc -- -DWRF_CORE=ARW -DWRF_NESTING=BASIC -DENABLE_HYDRO=ON -DWRF_CASE=EM_REAL\n      ./compile_new -j4\n\n\n4b. Configure and compile WRF: Old Method\n\n\n.. code-block:: console\n\n  # Load environement variables from WRF directory\n  source hydro/template/setEnvar.sh\n\n  # Export paths necessary for WRF to find the right libraries on Derecho\n  export Jasper_ROOT=/glade/u/home/wrfhelp/UNGRIB_LIBRARIES/\n\n  # Configure WRF\n  # On Derecho,\n  #   For GNU (dmpar) and basic nesting\n  #     1. enter `printf '34\\n1\\n' | ./configure` or option 34 and 1\n  #   For IFX (dmpar) and basic nesting\n  #     1. enter `printf '78\\n1\\n' | ./configure` or option 78 and 1\n  #     2. Login node does not have enough memory to compile succesfully with ifx.\n  #        User can use interactive node with extra memory, mem=50GB works\n  ./configure\n  ./compile -j 4 em_real &> compile.log\n  # the binaries will be in the run directory\n\n\n**Compiling the WRF Preprocessing System (WPS)**\n\n1. Navigate to the WPS source code directory at WPS\n\n\n2. Configure and compile the WPS. Note that grib2 data is used in the example\n   and the Jasper environmental variables need to be set.\n\n2a. Configure and compile WPS: CMake\n\nNote: CMakeLists.txt line 164 in the top directory of WPS will need to be changed to\n\n.. code-block:: console\n\n  add_compile_definitions(\n                          ${WPS_DEFINITIONS_LIST}\n                          ${WPS_UNDEFINITIONS_LIST}\n                          USE_JPEG2000\n                          USE_PNG\n                          )\n\nNow configure with\n\n.. code-block:: console\n\n  ./configure_new -x -p gfortran -- -DBUILD_EXTERNALS=ON\n  ./compile_new -j 4 &> compile.log\n\n\n2b. Configure and compile WPS: old Method\n\n\n.. code-block:: console\n\n  # Select option 2 and --build-grib2-libs. Option 2 is Linux x86_64, gfortran\n  #   (dmpar) or select th dmpar option for compiler of choice\n  # The user can also enter printf '2\\n' | ./configure --build-grib2-libs to pass the arguments\n  export Jasper_ROOT=/glade/u/home/wrfhelp/UNGRIB_LIBRARIES/\n  ./configure --build-grib2-libs\n  ./compile geogrid -j 4\n  ./compile ungrib -j 4\n  ./compile metgrid -j 4\n\ncheck the compile log for errors.\n\n\nRunning the WRF Preprocessing System (WPS)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. figure:: media/wps_program_flow.png\n   :align: center\n\n   Image from `WPS Userguide <https://www2.mmm.ucar.edu/wrf/users/wrf_users_guide/build/html/wps.html>`_.\n\n\nIn this section we will use the compiled WRF Preprocessing System (WPS)\nutilities along with a namelist file ( namelist.wps ) and meteorological\nforcing data from the coupled test case to generate geogrid and metgrid files\nfor the two model domains (note that the inner nest, or domain 2, is where\nWRF-Hydro will run).\n\n**Running the geogrid utility**\n\n1. Create a run directory for WPS within your project directory\n\n.. code-block:: console\n\n  mkdir -p run/WPS\n  cd run/WPS\n\n\n2. Now copy the required files for the WPS geogrid utility into your ``run/WPS``\n   directory\n\n.. code-block:: console\n\n  cp ../../WPS/geogrid/GEOGRID.TBL .\n  cp ../../example_case_coupled/namelist.wps .\n\n  # for new CMake install method\n  cp ../../WPS/install/bin/geogrid.exe .\n\n  # or if the older method was used to build\n  cp ../../WPS/geogrid.exe .\n\n\n\nEdit the paths within this namelist as appropriate for your system\n\n3. Edit the path to geographic data in your ``namelist.wps`` file so that\n   ``geog_data_path`` points to the correct path.\n\n.. code-block:: console\n\n  geog_data_path = '/glade/work/wrfhelp/WPS_GEOG/',\n  # or geog, note though this is currently not working\n  geog_data_path = 'geog',\n\n\n4. Run the geogrid utility\n\n.. code-block:: console\n\n  mpiexec -np 2 ./geogrid.exe &> geogrid.log\n\n\n**Running the ungrib utility**\n\nThe ungrib utility takes meteorological forcing data to be used for simulation\ninitial and boundary conditions and converts the files to an intermediate file\nformat used by the metgrid utility. Make sure modules are loaded from previous\nsteps.\n\n\n1. Now copy the additional required files for the WPS ungrib utility into your\n   ``run/WPS`` directory\n\n.. code-block:: console\n\n  cd run/WPS\n  cp ../../WPS/link_grib.csh .\n\n  # for new cmake build method\n  cp ../../WPS/install/bin/ungrib.exe .\n\n  # or if the older method was used to build\n  cp ../../WPS/ungrib.exe .\n\n\n2. Next copy over the necessary variable table for your forcing data\n\n.. code-block:: console\n\n  cp ../../WPS/ungrib/Variable_Tables/Vtable.NAM Vtable\n\n\n3. Then link your forcing data from the test case to the run directory (this\n   script will also rename the files to those expected for the ungrib utility)\n\n.. code-block:: console\n\n  ./link_grib.csh ../../example_case_coupled/WRF_FORCING/*\n\n\n4. Next run the ungrib utility\n\n.. code-block:: console\n\n  mpiexec -np 2 ./ungrib.exe &> ungrib.log\n\n\n**Running the metgrid utility**\n\nThe metgrid utility does some interpolation of meteorological forcing data to\nthe model domain creating metgrid files to be used as input to the WRF real\nutility.\n\n1. Now copy additional the required files for the WPS metgrid utility into\n   your ``run/WPS`` directory\n\n.. code-block:: console\n\n  cp ../../WPS/metgrid/METGRID.TBL .\n\n  # for newer CMake build method\n  cp ../../WPS/install/bin/metgrid.exe .\n\n  # or if the older method was used to build\n  cp ../../WPS/metgrid.exe .\n\n\n2. Next run the metgrid utility\n\n.. code-block:: console\n\n  mpiexec -np 2 ./metgrid.exe &> metgrid.log\n\n\nRunning a coupled WRF | WRF-Hydro simulation\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIn this section we will use our compiled coupled WRF | WRF-Hydro model to run\na simulation. This walkthrough uses the Front Range coupled example test\ncase. Details on the domain and time period of the simulation are provided in\nthe example_case_coupled/README.txt file.\n\n**Setting up your run directory**\n\nFirst we will create a run directory and copy over or link the required files.\n\n1. Create a run directory for WRF by copying over the run directory from where\n   it was compiled\n\n.. code-block:: console\n\n  cd project_directory\n  # run directory should exist at this point\n  cp -RL WRF/run run/WRF\n  cd run/WRF\n\n\n2. Copy over parameter tables for WRF-Hydro\n\n.. code-block:: console\n\n  cp ../../WRF/hydro/template/HYDRO/*TBL .\n  # cp ../../WRF/hydro/template/NoahMP/run/*.TBL .\n  # cp ../../WRF/install/test/em_real/*.TBL .\n\n3. Copy over the namelists for real / wrf (namelist.input) and the hydro components\n(hydro.namelist) from the example case\n\n.. code-block:: console\n\n  cp ../../example_case_coupled/namelist.input .\n  cp ../../example_case_coupled/hydro.namelist .\n  cp ../../WRF/hydro/template/NoahMP/namelist.hrldas .\n  cp -r ../../example_case_coupled/DOMAIN/ .\n  cp ../../WRF/run/CAMtr_volume_mixing_ratio .\n  cp ../../WRF/phys/noahmp/parameters/MPTABLE.TBL .\n\n\n4. Link the geogrid and metgrid files we just generated from the WPS utilities\n\n.. code-block:: console\n\n  ln -sf ../WPS/met_em* .\n  ln -sf ../WPS/geo_em* .\n  ln -sf ../../WRF/run/RRTM_DATA .\n\n\n4. Copy executable files\n\n.. code-block:: console\n\n  # location for the CMake build, older method will have these files in the WRF/run directory\n  cp ../../WRF/install/bin/real real.exe\n  cp ../../WRF/install/bin/wrf wrf.exe\n\n\n**Running the real utility**\n\nThe WRF real utility creates the wrfinput* and wrfbdy* initial and boundary\ncondition files to be used as input for the coupled simulation.\n\n1. Execute real using the proper syntax for your system (example below)\n   and pipe the output to a log file.\n\n.. code-block:: console\n\n  mpirun -np 2 ./real.exe &> real.log\n\n2. Next review the rsl.out.* and rsl.error.* files for possible errors and\n   check to make sure the wrfinput* and wrfbdy* files have been created.\n\n.. code-block:: console\n\n  tail rsl.error.* -n 1\n\n**Running the coupled model**\n\nNow we will run the coupled model (all included in the wrf binary) using\nthe wrfinput* and wrfbdy* files as initial and boundary conditions and the\nmodel physics and other options selected in the namelist.input and\nhydro.namelist files.\n\n1. Execute wrf using the proper syntax for your system (example below) and\n   pipe the output to a log file.\n\n.. code-block:: console\n\n  mpirun -np 2 ./wrf.exe &> wrf.log\n\n2. If your simulation ran successfully, there should now be a large number of\n   output files. Descriptions of the output files can be found in the\n   WRF-Hydro V5 Technical Description at (\n   https://ral.ucar.edu/projects/wrf_hydro ) and the WRF User’s Guide found\n   here ( http://www2.mmm.ucar.edu/wrf/users/docs/user_guide_v4/contents.html\n   ). You will also want to review the rsl.out.* and rsl.error.* files for\n   possible error messages.\n\n\n\n.. _section-a3:\n\nA3. Exceptions for Running WRF-Hydro with the Noah LSM\n------------------------------------------------------\n\nSupport for the Noah Land Surface Model (LSM) within WRF-Hydro is\ncurrently frozen at Noah version 3.6, development to use the\n`refactored NoahMP <https://github.com/NCAR/noahmp>`_ as a submodule\nis under way. Since the Noah LSM is not under\nactive development by the community, WRF-Hydro is continuing to support\nNoah in deprecated mode only. Some new model features, such as the\nimproved output routines, have not been setup to be backward compatible\nwith Noah. Noah users should follow the guidelines below for adapting\nthe WRF-Hydro workflow to work with Noah:\n\n-  **LSM initialization:** The simple wrfinput.nc initialization file\n   created by the create_Wrfinput.R script does not currently include\n   all of the fields required by the Noah LSM. Therefore, Noah users\n   should use the WRF real utility to create a wrfinput_d0x file.\n   Refer to the WRF documentation and user guides for information on how\n   to do this.\n\n-  **Time-varying vegetation specifications:** While the Noah LSM will\n   be properly initialized with green vegetation fraction from the\n   wrfinput file, there is currently no automated method to update this\n   field over time (e.g., seasonally based on climatology). Therefore,\n   Noah users will need to provide these time-varying fields in the\n   model input forcing files (e.g., LDASIN).\n\n-  **Spatially varying parameters**: Spatially varying soil and\n   vegetation parameters (e.g., soil_properties.nc) are not supported in\n   Noah.\n\n-  **Model outputs:** The updated output routines have not been adapted\n   to work with Noah. Therefore, Noah users should always use\n   io_form_outputs = 0 to activate the deprecated output routines.\n   Scale/offset and compression options, CF compliance, augmented\n   spatial metadata, etc. are not available in this deprecated mode.\n\n.. _section-a4:\n\nA4. Noah `namelist.hrldas` File with Description of Options\n-----------------------------------------------------------\n\nBelow is an annotated namelist.hrldas file for running with the Noah\nland surface model. Notes and descriptions are indicated with <--\n\n.. code-block:: fortran\n\n   &NOAHLSM_OFFLINE\n   HRLDAS_CONSTANTS_FILE = \"./DOMAIN/wrfinput_d01\" !!<-- Path to wrfinput file containing initialization data\n                                                   ! for the LSM. This is required even for a warm start\n                                                   ! where a restart file is provided.\n\n   INDIR = \"./FORCING\" !<-- Path to atmospheric forcing data directory.\n   OUTDIR = \"./\" !<-- Generally leave this as-is (output goes to base run directory);\n                 ! redirected output only applies to LSM output files and can cause\n                 ! issues when running coupled to WRF-Hydro.\n   START_YEAR = 2013 !<-- Simulation start year\n   START_MONTH = 09 !<-- Simulation start month\n   START_DAY = 01 !<-- Simulation start day\n   START_HOUR = 00 !<-- Simulation start hour\n   START_MIN = 00 !<-- Simulation start min\n   RESTART_FILENAME_REQUESTED = \"RESTART.2013090100_DOMAIN1\" !<-- Path to LSM restart file if using; this contains a\n                                                             ! \"warm\" model state from a previous model run.\n                                                             ! Comment out if not a restart simulation.\n\n   ! Specification of simulation length in days hours\n   KHOUR = 24 !<-- Number of hours for simulation;\n\n   ! Timesteps in units of seconds\n   FORCING_TIMESTEP = 3600 !<-- Timestep for forcing input data (in seconds)\n   NOAH_TIMESTEP = 3600 !<-- Timestep the LSM to cycle (in seconds)\n   OUTPUT_TIMESTEP = 86400 !<-- Timestep for LSM outputs, LDASOUT (in seconds)\n\n   ! Land surface model restart file write frequency\n   RESTART_FREQUENCY_HOURS = 6 !<-- Timestep for LSM restart files to be generated (in hours). A value of -99999\n                               ! will simply output restarts on the start of each month, useful for longer\n                               ! model runs. Restart files are generally quite large, so be cognizant of\n                               ! storage space and runtime impacts when specifying.\n   ! Split output after split_output_count output times.\n   SPLIT_OUTPUT_COUNT = 1 !<-- Number of timesteps to put in a single output file. This option\n                          ! must be 1 for NWM output configurations.\n\n   ! Soil layer specification\n   NSOIL=4 !<-- Number of soil layers\n   ZSOIL(1) = 0.10 !<-- Thickness of top soil layer (m)\n   ZSOIL(2) = 0.30 !<-- Thickness of second soil layer (m)\n   ZSOIL(3) = 0.60 !<-- Thickness of third soil layer (m)\n   ZSOIL(4) = 1.00 !<-- Thickness of bottom soil layer (m)\n\n   ! Forcing data measurement heights\n   ZLVL = 2.0 !<-- Height of input temperature and humidity measurement/estimate\n   ZLVL_WIND = 10.0 !<-- Height of input wind speed measurement/estimate\n\n   IZ0TLND = 0 !<-- Switch to control land thermal roughness length. Option 0 is the default,\n               ! non-vegetation dependent value and option 1 introduces a vegetation dependence.\n   SFCDIF_OPTION = 0 !<-- Option to use the newer, option 1, or older,\n   option 0, SFCDIF routine. The default value is 0.\n   UPDATE_SNOW_FROM_FORCING = .FALSE. !<-- Option to activate or deactivate updating the snow­cover\n                                      ! fields from available analyses. The default option is true.\n\n   ! -------- Section: Select atmospheric forcing input file format, FORC_TYP -------- !\n   ! Specification of forcing data: 1=HRLDAS-hr format, 2=HRLDAS-min format,\n   ! 3=WRF,4=Idealized, 5=Ideal w/ Spec.Precip.,\n   ! 6=HRLDAS-hrly fomat w/ Spec. Precip, 7=WRF w/ Spec. Precip\n   FORC_TYP = 3\n   /\n\n.. _section-a5:\n\nA5. Noah-MP `namelist.hrldas` File with Description of Options\n--------------------------------------------------------------\n\nBelow is an annotated namelist.hrldas file for running with the Noah-MP\nland surface model. Do note that the file says ``&NOAHLSM_OFFLINE``\nhowever it is for use with the Noah-MP LSM. This namelist statement\nhappens to be hardcoded and thus not easily changed. Notes and\ndescriptions are indicated with <-- after sections\nbeing described. See the official HRLDAS namelist description here:\nhttps://github.com/NCAR/hrldas-release/blob/release/HRLDAS/run/README.namelist\n\n.. code-block:: fortran\n\n   &NOAHLSM_OFFLINE\n   HRLDAS_SETUP_FILE = \"./DOMAIN/wrfinput_d01\" !<-- Path to wrfinput file containing initialization\n                                               ! data for the LSM. This is required even for a warm\n                                               ! start where a restart file is provided.\n   INDIR = \"./FORCING\" !<-- Path to atmospheric forcing data directory.\n\n   SPATIAL_FILENAME = \"./DOMAIN/soil_properties.nc\" !<-- Path to optional 2d/3d soil and vegetation\n                                                    ! parameter file. If you are using this option,\n                                                    ! you must also use a binary compiled with\n                                                    ! SPATIAL_SOIL=1. If using the traditional\n                                                    ! parameter lookup tables, compile with\n                                                    ! SPATIAL_SOIL=0 and comment out this option.\n   OUTDIR = \"./\" !<-- Generally leave this as-is (output goes to base run directory); redirected\n                 ! output only applies to LSM output files\n                 ! and can cause issues when running coupled to WRF-Hydro.\n   START_YEAR = 2013 !<-- Simulation start year\n   START_MONTH = 09 !<-- Simulation start month\n   START_DAY = 12 !<-- Simulation start day\n   START_HOUR = 04 !<-- Simulation start hour\n   START_MIN = 00 !<-- Simulation start min\n   RESTART_FILENAME_REQUESTED = \"RESTART.2013091204_DOMAIN1\" !<-- Path to LSM restart file if using;\n                                                             ! this contains a \"warm\" model state\n                                                             ! from a previous model run. Comment out\n                                                             ! if not a restart simulation.\n   ! Specification of simulation length in days OR hours\n   KHOUR = 24 !<-- Number of hours for simulation\n\n   ! -------- Following Section: Noah-MP physics options -------- !\n\n   ! Physics options (see the documentation for details)\n\n   DYNAMIC_VEG_OPTION = 4 !<-- options for dynamic vegetation:\n                      !   1 -> off (use table LAI; use FVEG = SHDFAC from input)\n                      !   2 -> on  (together with OPT_CRS = 1)\n                      !   3 -> off (use table LAI; calculate FVEG)\n                      ! **4 -> off (use table LAI; use maximum vegetation fraction)\n                      ! **5 -> on  (use maximum vegetation fraction)\n                      !   6 -> on  (use FVEG = SHDFAC from input)\n                      !   7 -> off (use input LAI; use FVEG = SHDFAC from input)\n                      !   8 -> off (use input LAI; calculate FVEG)\n                      !   9 -> off (use input LAI; use maximum vegetation fraction)\n\n   CANOPY_STOMATAL_RESISTANCE_OPTION = 1 !<-- options for canopy stomatal resistance\n                      ! **1 -> Ball-Berry\n                      !   2 -> Jarvis\n\n   BTR_OPTION = 1 !<-- options for soil moisture factor for stomatal resistance\n                      ! **1 -> Noah (soil moisture)\n                      !   2 -> CLM  (matric potential)\n                      !   3 -> SSiB (matric potential)\n\n   RUNOFF_OPTION = 3 !<-- options for runoff and groundwater\n                      !   1 -> TOPMODEL with groundwater (Niu et al. 2007 JGR)\n                      !   2 -> TOPMODEL with an equilibrium water table (Niu et al. 2005 JGR)\n                      ! **3 -> original surface and subsurface runoff (free drainage)\n                      !   4 -> BATS surface and subsurface runoff (free drainage)\n                      !   5 -> Miguez-Macho&Fan groundwater scheme (Miguez-Macho et al. 2007 JGR;\n                      !                   Fan et al. 2007 JGR) [NOT YET SUPPORTED WITH WRF-HYDRO]\n                      !   7 -> Xinanjiang runoff scheme\n\n\n   SURFACE_DRAG_OPTION = 1 !<-- options for surface layer drag coeff (CH & CM)\n                      ! **1 -> M-O\n                      !   2 -> original Noah (Chen97)\n\n   FROZEN_SOIL_OPTION = 1 !<-- options for frozen soil permeability\n                      ! **1 -> linear effects, more permeable (Niu and Yang, 2006, JHM)\n                      !   2 -> nonlinear effects, less permeable (old)\n\n   SUPERCOOLED_WATER_OPTION = 1 !<-- options for supercooled liquid water (or ice fraction)\n                      ! **1 -> no iteration (Niu and Yang, 2006 JHM)\n                      !   2 -> Koren's iteration\n\n   RADIATIVE_TRANSFER_OPTION = 3 !<-- options for radiation transfer\n                      !   1 -> modified two-stream (gap = F(solar angle, 3D structure ...)<1-FVEG)\n                      !   2 -> two-stream applied to grid-cell (gap = 0)\n                      ! **3 -> two-stream applied to vegetated fraction (gap=1-FVEG)\n\n   SNOW_ALBEDO_OPTION = 1 !<-- options for ground snow surface albedo\n                      ! **1 -> BATS\n                      !   2 -> CLASS\n\n   PCP_PARTITION_OPTION = 1 !<-- options for partitioning  precipitation into rainfall & snowfall\n                      ! **1 -> Jordan (1991)\n                      !   2 -> BATS: when SFCTMP<TFRZ+2.2\n                      !   3 -> SFCTMP < TFRZ\n                      !   4 -> Use WRF microphysics output\n\n   TBOT_OPTION = 2 !<-- options for lower boundary condition of soil temperature\n                      !   1 -> zero heat flux from bottom (ZBOT and TBOT not used)\n                      ! **2 -> TBOT at ZBOT (8m) read from a file (original Noah)\n\n   TEMP_TIME_SCHEME_OPTION = 3 !<-- options for snow/soil temperature time scheme (only layer 1)\n                      !   1 -> semi-implicit; flux top boundary condition\n                      !   2 -> full implicit (original Noah); temperature top boundary condition\n                      ! **3 -> same as 1, but FSNO for TS calculation (generally improves snow; v3.7)\n\n   GLACIER_OPTION = 2 !<-- options for glacier treatment\n                       !   1 -> include phase change of ice\n                       ! **2 -> ice treatment more like original Noah (slab)\n\n   SURFACE_RESISTANCE_OPTION = 4 !<-- options for surface resistent to evaporation/sublimation\n                      !   1 -> Sakaguchi and Zeng, 2009\n                      !   2 -> Sellers (1992)\n                      !   3 -> adjusted Sellers to decrease RSURF for wet soil\n                      ! **4 -> option 1 for non-snow; rsurf = rsurf_snow for snow (set in MPTABLE); AD v3.8\n\n   IMPERV_OPTION = 9 !<-- options for impervious adjustment for surface runoff partitioning\n                      !   0 -> none\n                      !   1 -> adjust based on impervious fraction\n                      !   2 -> adjust based on effective impervious fraction from Alley & Veenhuis\n                      ! **9 -> original formulation (varies based on runoff option)\n\n   ! Timesteps in units of seconds\n   FORCING_TIMESTEP = 3600 !<-- Timestep for forcing input data (in seconds)\n   NOAH_TIMESTEP = 3600 !<-- Timestep the LSM to cycle (in seconds)\n   OUTPUT_TIMESTEP = 86400 !<-- Timestep for LSM outputs, LDASOUT (in seconds)\n\n   ! Land surface model restart file write frequency\n   RESTART_FREQUENCY_HOURS = 2 !<-- Timestep for LSM restart files to be generated (in hours).\n                               ! A value of -99999 will simply output restarts on the start of\n                               ! each month, useful for longer model runs. Restart files are\n                               ! generally quite large, so be cognizant of storage space and\n                               ! runtime impacts when specifying.\n   ! Split output after split_output_count output times.\n   SPLIT_OUTPUT_COUNT = 1 !<-- Number of timesteps to put in a single\n   output file. This option must be 1 for NWM output configurations.\n\n   ! Soil layer specification\n   NSOIL=4 !<-- Number of soil layers\n   soil_thick_input(1) = 0.10 !<-- Thickness of top soil layer (m)\n   soil_thick_input(2) = 0.30 !<-- Thickness of second soil layer (m)\n   soil_thick_input(3) = 0.60 !<-- Thickness of third soil layer (m)\n   soil_thick_input(4) = 1.00 !<-- Thickness of bottom soil layer (m)\n\n   ! Forcing data measurement height for winds, temp, humidity\n   ZLVL = 10.0 !<-- Height of input wind speed\n\n   ! -------- Following Section: Restart IO file formats -------- !\n\n   ! Options to specify whether restart files (both read in and output)\n   ! should be in binary or netCDF format. Generally recommend using\n   ! netCDF format (option 0) for both.\n\n   ! Restart file format options\n   rst_bi_in = 0  !<-- 0: use netcdf input restart file 1: use parallel io for reading multiple\n                  ! restart files (1 per core)\n   rst_bi_out = 0 !<-- 0: use netcdf output restart file 1: use parallel io for outputting multiple\n                  ! restart files (1 per core)\n\n   ! -------- Optional forcing variable names -------- !\n   ! These can be left out of the namelist and will default to the values below,\n   ! so only need to be specified if using alternative names.\n\n   ! Forcing input variable names\n   forcing_name_T = \"T2D\"        !<-- variable name for air temperature\n   forcing_name_Q = \"Q2D\"        !<-- variable name for humidity\n   forcing_name_U = \"U2D\"        !<-- variable name for u-component of wind speed\n   forcing_name_V = \"V2D\"        !<-- variable name for v-component of wind speed\n   forcing_name_P = \"PSFC\"       !<-- variable name for surface pressure\n   forcing_name_LW = \"LWDOWN\"    !<-- variable name for downward longwave radiation\n   forcing_name_SW = \"SWDOWN\"    !<-- variable name for downward shortwave radiation\n   forcing_name_PR = \"RAINRATE\"  !<-- variable name for precipitation rate\n   ! Optional way to supply liquid or snow fraction of precipitation, e.g., if provided\n   ! by an atmospheric model. Otherwise the land model will estimate this.\n   ! NOTE: You can provide either frozen fraction or liquid fraction (no need to provide both).\n   forcing_name_SN = \"\"          !<-- variable name for frozen fraction of precipitation\n   forcing_name_LF = \"LQFRAC\"    !<-- variable name for liquid fraction of precipitation\n\n   /\n\n   &WRF_HYDRO_OFFLINE\n\n   ! Specification of forcing data: 1=HRLDAS-hr format, 2=HRLDAS-min format,\n   ! 3=WRF, 4=Idealized, 5=Ideal w/ Spec.Precip.,\n   ! 6=HRLDAS-hrly fomat w/ Spec. Precip, 7=WRF w/ Spec.Precip\n   FORC_TYP = 1\n\n   /\n\n   ! -------- Optional settings for the Crocus snow model -------- !\n   ! These options can be excluded if not using the Crocus snow/glacier model.\n\n   &CROCUS_nlist\n   crocus_opt = 0   !<--  0 means the Crocus model is off (default)\n                    !     1 means the Crocus model is on\n   act_lev = 40     !<--  Specify the number of layers the Crocus snow model will resolve.\n                    !     More layers will require more memory and may slow performance.\n                    !     20-40 normal range, 1-50 acceptable\n\n   /\n\n.. _section-a6:\n\nA6. WRF-Hydro `hydro.namelist` File with Description of Options\n---------------------------------------------------------------\n\nBelow is an annotated hydro.namelist file. Annotations follow what is\nbeing described, indicated with <-- and blue text. Note that\nannotations describing options are meant to accompany the commented\ndescription in the namelist which precedes the option.\n\n.. _hydro-namelist:\n\n.. code-block:: fortran\n\n   &HYDRO_nlist\n   !!!! --------------- SYSTEM COUPLING -------------- !!!!\n   ! Specify what is being coupled: 1=HRLDAS (offline Noah-LSM),\n   ! 2=WRF, 3=NASA/LIS, 4=CLM\n   sys_cpl = 1 !<-- For offline runs, including Noah and Noah-MP, this will be option 1.\n\n   !!!! ----------- MODEL INPUT DATA FILES ----------- !!!!\n   ! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\n   GEO_STATIC_FLNM = \"./DOMAIN/geo_em.d01.nc\" !<-- Path to the “GEOGRID” file which contains base\n                                              ! information on the LSM grid (this file is generally\n                                              ! created via WPS in the model preprocessing steps).\n\n   ! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\n   GEO_FINEGRID_FLNM = \"./DOMAIN/Fulldom_hires.nc\" !<-- Path to the “routing stack” which contains\n                                                   ! base information on the high-resolution routing\n                                                   ! grid. This file is generally created via the\n                                                   ! GIS pre-processing tools.\n\n   ! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n   ! If you specify a filename and the file does not exist, it will\n   ! be created for you.\n   HYDROTBL_F = \"./DOMAIN/hydro2dtbl.nc\" !<-- Path to the 2d hydro parameters file. If this file\n                                         ! does not exist, it will be created for you based on\n                                         ! HYDRO.TBL and the soil and land class grids found in the\n                                         ! GEOGRID netCDF file\n\n   ! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\n   LAND_SPATIAL_META_FLNM = \"./DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata.nc\" !<-- Path to the geospatial\n                                                ! metadata file for your domain. This file is required\n                                                ! if using any of the io_form_outputs options (i.e.,\n                                                ! io_form_outputs > 0). This file is generally created\n                                                ! via the GIS pre-processing tools.\n\n   ! Specify the name of the restart file if starting from restart...comment out with '!' if not...\n   RESTART_FILE = 'HYDRO_RST.2013-09-12_04:00_DOMAIN3' !<-- Path to hydro restart file; this contains\n                                                       ! a \"warm\" model state from a previous model run.\n\n   !!!! ------------- MODEL SETUP OPTIONS ------------ !!!!\n   ! Specify the domain or nest number identifier...(integer)\n   IGRID = 1 !<-- Domain ID number. This comes from the WRF coupling framework and is intended to\n             ! specify which nested domain you are running. For standalone runs, this is not relevant\n             ! HOWEVER this ID must match the number specified after DOMAIN in your forcing file names\n             ! (e.g., the \"1\" in \"2013091200.LDASIN_DOMAIN1\").\n\n   ! Specify the restart file write frequency in minutes\n   ! A value of -99999 will output restarts on the first day of the month only.\n   rst_dt = 120 !<-- Specify how often hydro restart files should be generated, in minutes. This should\n                ! generally track your LSM restart file frequency (as specified in namelist.hrldas).\n                ! A value of -99999 will simply output restarts on the start of each month, useful for\n                ! longer model runs. Hydro restart files are generally quite large, so be cognizant of\n                ! storage space and runtime impacts.\n\n   ! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n   ! NOTE: Only turn this option on if overland or subsurface routing is active!\n   rst_typ = 1 !<-- Specify whether or not to use the soil conditions (soil moisture and ponded water)\n               ! from the high-resolution hydro restart file, if \"warm\" starting the model with a\n               ! provided HYDRO_RST file. If this option is 0, the LSM restart states will be used\n               ! instead. IMPORTANT: If you are NOT running with terrain routing turned on, do not set\n               ! this option to 1 as it may bring in invalid values.\n\n   ! Restart file format control !<-- Options to whether restart files (input and output separately)\n                                 ! should be in binary or netCDF format. Generally recommend to use\n                                 ! netCDF format (option 0) for both.\n   rst_bi_in = 0 !0: use netCDF input restart file (default) 1: use parallel io for reading multiple\n                 ! restart files, 1 per core\n   rst_bi_out = 0 !0: use netCDF output restart file (default) 1: use parallel io for outputting multiple\n                  ! restart files, 1 per core\n\n   ! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\n   RSTRT_SWC = 0 !<-- Specify whether or not to reset any accumulated output variables to 0 (option 1)\n                 ! or to continue accumulating from the values in the hydro restart file (option 0).\n                 ! Note that this only applies to the hydrologic model outputs; the LSM outputs will\n                 ! always continue to accumulate from the LSM restart file.\n\n   ! Specify baseflow/bucket model initialization (0=cold start from table, 1=restart file)\n   GW_RESTART = 1 !<-- Specify whether to initialize the groundwater bucket states from the hydro\n                  ! restart file (option 1) or \"cold\" start the bucket states from the parameter\n                  ! table, GWBUCKPARM.nc.\n\n   !!!! ------------ MODEL OUTPUT CONTROL ------------ !!!!\n   ! Specify the output file write frequency...(minutes)\n   out_dt = 60 !<-- Timestep for hydro model outputs, in minutes. This covers all output options\n               ! listed below (CHRTOUT, GWOUT, RTOUT, LAKEOUT, etc.) so be cognizant of impacts\n               ! on disk space and runtime when specifying.\n\n   ! Specify the number of output times to be contained within each output history file...(integer)\n   ! Currently only 1 and 0 are valid options. 1 will output a single file per timestep.\n   ! 0 will output the CHANOBS file only as a single file over the run duration; other\n   ! files will be one file per timestep.\n   SPLIT_OUTPUT_COUNT = 1 !<-- Number of timesteps to put in a single output file.\n                        ! 1 = one file per timestep\n                        ! 0 = same as option 1 but there will be one file for the\n                        !     full run duration for CHANOBS only\n\n   ! Specify the minimum stream order to output to netCDF point file (integer)\n   ! Note: lower value of stream order produces more output.\n   order_to_write = 4 !<-- Lowest stream order to include in output files. Selecting 1 gives\n                      ! you output for every reach/channel cell, selecting a higher order number\n                      ! gives you fewer channel output elements.\n\n   ! Flag to turn on/off new I/O routines:\n   ! 0 = deprecated output routines (only use when running with the Noah LSM),\n   ! 1 = with scale/offset/compression,\n   ! 2 = with scale/offset/NO compression,\n   ! 3 = compression only,\n   ! 4 = no scale/offset/compression (default)\n   io_form_outputs = 1 !<-- Specify which output option to use (NOTE: option 0 is the only\n                     ! supported option when running with the original Noah LSM)\n\n   ! Realtime run configuration option:\n   ! 0=all (default), 1=analysis, 2=short-range, 3=medium-range,\n   ! 4=long-range, 5=retrospective,\n   ! 6=diagnostic (includes all of 1-4 outputs combined)\n   io_config_outputs = 1 !<-- Specify which configuration of output variables to generate\n                         ! (NOTE: not active when io_form_outputs=0)\n\n   ! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\n   t0OutputFlag = 1 !<-- Select whether or not to create outputs at the initial timestep.\n\n   ! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n   ! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n   ! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n   ! 2=channel+bucket fluxes (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n   ! 3=channel accumulations (accSfcLatRunoff, accBucket) *NOT TESTED*\n   output_channelBucket_influx = 0 !<-- Select which additional channel and groundwater bucket\n                                   ! outputs will be generated. These additional variables can\n                                   ! be used to drive the channel-only model.\n\n   ! Output netCDF file control - specify which outputs to generate for the run.\n\n   CHRTOUT_DOMAIN = 1 !<-- Channel output variables (streamflow, velocity, head, etc.) as a netCDF\n                      ! point timeseries output at all channel points (1d) 0 = no output, 1 = output\n\n   CHANOBS_DOMAIN = 0 !<-- NetCDF point timeseries at forecast points or gage points (defined in\n                      ! Route_Link.nc) 0 = no output, 1 = output\n\n   CHRTOUT_GRID = 0 !<-- NetCDF grid of channel streamflow values (2d) 0 = no output, 1 = output\n                    ! NOTE: Not available with reach-based routing\n\n   LSMOUT_DOMAIN = 0 !<-- NetCDF grid of variables passed between LSM and routing components (2d)\n                     ! (generally used for diagnostics only)\n                     ! 0 = no output, 1 = output NOTE: No scale_factor/add_offset available\n\n   RTOUT_DOMAIN = 1 !<-- NetCDF grid of terrain routing variables on routing grid (2d)\n                  ! 0 = no output, 1 = output\n\n   output_gw = 1 !<-- NetCDF groundwater output, 0 = no output, 1 = output\n                 ! Groundwater bucket outputs [level, inflow, outflow]\n\n   outlake = 1 !<-- NetCDF grid of lake values (1d) 0 = no output, 1 = output !\n               ! Lake output variables (if lakes are included in the domain) [level, inflow, outflow]\n\n   frxst_pts_out = 0 !<-- ASCII text file of streamflow at forecast points or gage points\n                     ! (defined in Route_Link.nc),  0 = no output, 1 = output\n\n   !!!! ---- PHYSICS OPTIONS AND RELATED SETTINGS ---- !!!!\n\n   ! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n   ! Notes: In the current version of WRF-Hydro these must be the same as in the namelist.input file.\n   ! Future versions may permit this to be different.\n   NSOIL=4 !<-- Number of soil layers\n   ZSOIL8(1) = -0.10 !<-- Depth of bottom boundary of top soil layer in meters\n   ZSOIL8(2) = -0.40 !<-- Depth of bottom of second soil layer in meters (note that this is specified\n                     ! differently than the namelist.hrldas; this is total depth from the surface\n                       instead of thickness)\n   ZSOIL8(3) = -1.00 !<-- Depth of bottom of third soil layer in meters (note that this is specified\n                     ! differently than the namelist.hrldas; this is total depth from the surface\n                       instead of thickness)\n   ZSOIL8(4) = -2.00 !<-- Depth of bottom of fourth (last) soil layer in meters (note that this is\n                     ! specified differently than the namelist.hrldas; this is total depth from the\n                       surface instead of thickness)\n\n   ! Specify the grid spacing of the terrain routing grid (meters)\n   DXRT = 100.0 !<-- Resolution of the high-res routing grid\n   ! Specify the integer multiple between the land model grid and the terrain routing grid (integer)\n   AGGFACTRT = 10 !<-- Aggregation factor between the high-res routing grid and the LSM grid;\n                  ! e.g., a 100-m routing grid resolution and a 1km LSM grid resolution would\n                  ! be AGGFACTRT = 10.\n\n   ! Specify the channel routing model timestep (seconds)\n   DTRT_CH = 10 !<-- Timestep for the channel routing module to cycle, in seconds; model runtime\n                ! will be sensitive to this timestep, so choose something appropriate for your\n                ! domain resolution (finer resolutions generally require finer timesteps).\n   ! Specify the terrain routing model timestep (seconds)\n   DTRT_TER = 10 !<-- Timestep for the terrain routing module to cycle, in seconds; model runtime\n                 ! will be sensitive to this timestep, so choose something appropriate for your\n                 ! domain resolution (finer resolutions generally require finer timesteps).\n\n   ! Switch to activate subsurface routing...(0=no, 1=yes)\n   SUBRTSWCRT = 1 !<-- Turn on/off subsurface routing module.\n   ! Switch to activate surface overland flow routing...(0=no, 1=yes)\n   OVRTSWCRT = 1 !<-- Turn on/off overland routing module.\n\n   ! Specify overland flow routing option:\n   ! 1=Seepest Descent (D8) 2=CASC2D (not active)\n   ! NOTE: Currently subsurface flow is only steepest descent\n   rt_option = 1 !<-- For both terrain routing modules, specify whether flow should follow the\n                 ! steepest path (option 1) or multi-directional (option 2).\n                 ! Option 2 is currently unsupported.\n\n   ! Specify whether to adjust overland flow parameters based on imperviousness\n   imperv_adj = 0 !<-- When overland routing is active and an imperviousness grid is\n                  !    provided in Fulldom_hires.nc, you can use this option to reduce\n                  !    the overland roughness and maximum retention depth based on the\n                  !    impervious fraction.\n                  ! 0 = no adjustment, 1 = activate parameter adjustments\n\n\n   ! Switch to activate channel routing...(0=no, 1=yes)\n   CHANRTSWCRT = 1 !<-- Turn on/off channel routing module.\n\n   ! Specify channel routing option:\n   ! 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\n   channel_option = 3 !<-- If channel routing module is active, select which physics option to use.\n\n   ! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\n   route_link_f = \"./DOMAIN/Route_Link.nc\" !<-- If using one of the reach-based channel routing\n                                           ! options (channel_option = 1 or 2), specify the path\n                                           ! to the Route_Link.nc file, which provides the\n                                           ! channel-reach parameters.\n\n   ! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n   ! This option is currently only supported if using reach-basedrouting with UDMP=1.\n   compound_channel = .FALSE. !<-- Turn on or off the compound channel formulation.\n                              !    This option only works with Muskingum-Cunge reach-based\n                              !    routing with UDMP=1. This option also requires additional\n                              !    parameters in the routelink file.\n\n   ! Switch to activate channel-loss option (0=no, 1=yes) [Requires Kchan in RouteLink]\n   ! channel_loss_option = 0 !<-- Turn on or off channel loss. Note that the channel loss\n                             !    scheme currently only works for Muskingum-Cunge reach-based\n                             !    channel routing. Also note that activating channel loss will\n                             !    create a sink in the model, so the water budget will not close.\n                             !    By default this option is off.\n\n   ! Lake / Reservoir options (0=lakes off, 1=level pool (typical default),\n   !                           2=passthrough, 3=reservoir DA [see &reservoir_nlist below])\n   lake_option = 1 !<-- Set the lake/reservoir option. Note that different options may\n                   !    require different domain/parameter/input files. Option 0 (lakes off)\n                   !    will not generate reasonable results for gridded channel routing\n                   !    domains where lake cells mask out channel cells.\n\n   ! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\"). Note: REQUIRED if lakes are on.\n   route_lake_f = \"./DOMAIN/LAKEPARM.nc\" !<-- If lakes are active, specify the path to the lake\n                                         !    parameter file, which provides the lake parameters.\n\n   ! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through,\n   ! 4=exp. bucket with area normalized parameters)\n   ! Option 4 is currently only supported if using reach-based routing with UDMP=1.\n   GWBASESWCRT = 1 !<-- Turn on/off the ground water bucket module. Option 1 activates the\n                   ! exponential bucket model, Option 2 bypasses the bucket model and dumps all\n                   ! flow from the bottom of the soil column directly into the channel, and\n                   ! Option 4 is a variation of the exponential bucket model (option 1) where\n                   ! the coefficient is scaled by catchment area and only works for UDMP=1.\n                   ! Option 0 creates a sink at the bottom of the soil column (water draining from\n                   ! the bottom of the soil column leaves the system, so note that this option will\n                   ! not have water balance closure).\n\n   ! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\").\n   ! NOTE: Only required if baseflow model is active (1 or 2) and UDMP_OPT=0.\n   gwbasmskfil = \"./DOMAIN/GWBASINS.nc\" !<-- For configurations where the bucket or pass-through\n                                        ! groundwater modules are active, provide the path to the\n                                        ! 2d netCDF file (LSM grid resolution) that maps the\n                                        ! groundwater basin IDs. Bucket parameters will be specified\n                                        ! through the GWBUCKPARM.nc file, whose IDs should match\n                                        ! those in the groundwater basin mask file.\n\n   ! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\n   GWBUCKPARM_file = \"./DOMAIN/GWBUCKPARM.nc\" !<-- For configurations where the groundwater bucket\n                                              ! model is active, specify the path to the bucket\n                                              ! parameter file, which provides bucket parameters\n                                              ! by catchment.\n\n   ! User defined mapping, such NHDPlus: 0=no (default), 1=yes\n   UDMP_OPT = 0 !<-- If 1, this tells the model to use a \"user-defined mapping\" scheme to translate\n                ! between terrain and groundwater flow and reaches, e.g., NHDPlus.\n\n   ! If user-define mapping is on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\n   !udmap_file = \"./DOMAIN/spatialweights.nc\" !<-- If UDMP_OPT=1 (user defined mapping is active),\n                                              ! provide the path to the required spatial weights\n                                              ! file, which maps between grid cells and catchments.\n\n   / !<-- End of hydro namelist HYDRO_nlist\n\n   &NUDGING_nlist !<-- Start of separate namelist for nudging, only used if the model is compiled\n                  ! with the compile-time option WRF_HYDRO_NUDGING=1. Ignored otherwise.\n\n   ! Path to the \"timeslice\" observation files.\n   timeSlicePath = \"./nudgingTimeSliceObs/\" !<-- Path to a directory containing nuding “time slice”\n                                            ! observation files. There are no requirements on the\n                                            ! existence of files in the directory, but the directory\n                                            ! itself must exist if specified.\n   nudgingParamFile = \"DOMAIN/nudgingParams.nc\" !<-- Path to the required nudging parameter file.\n   ! Nudging restart file. nudgingLastObsFile defaults to '', which will look for\n   ! nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc *AT THE INITALIZATION TIME OF THE RUN*. Set to a missing\n   ! file to use no restart.\n   !nudgingLastObsFile = '/a/nonexistent/file/gives/nudging/cold/start' !<-- Optional path to an\n                                                                        ! optional nudging restart\n                                                                        ! file. See comments above.\n   ! Parallel input of nudging timeslice observation files?\n   readTimesliceParallel = .TRUE. !<-- Can read the observation files in parallel (on different cores)\n                                  ! for quicker run speeds.\n\n   ! temporalPersistence defaults to true, only runs if necessary params present.\n   temporalPersistence = .FALSE. !<-- This option uses the expCoeff\n                                 ! parameter for persisting observations\n\n   ! The total number of last (obs, modeled) pairs to save in nudgingLastObs for removal of bias.\n   ! This is the maximum array length. (This option is active when persistBias=FALSE)\n   ! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\n   nLastObs = 960 !<-- The maximum trailing window size for calculating bias correction.\n\n   ! If using temporalPersistence the last observation persists by default. This option instead\n   ! persists the bias after the last observation.\n   persistBias = .FALSE. !<-- Apply bias correction as observations move into the past?\n                         ! AnA (FALSE) vs Forecast (TRUE) bias persistence.\n\n   ! If persistBias: Does the window for calculating the bias end at model init time (=t0)?\n   ! FALSE = window ends at model time (moving),\n   ! TRUE = window ends at init=t0(fcst) time.\n   ! (If commented out, Default=FALSE)\n   ! Note: Perfect restart tests require this option to be .FALSE.\n   biasWindowBeforeT0 = .FALSE. !<-- Is the bias window shifting with\n                                ! model integration?\n\n   ! If persistBias: Only use this many last (obs, modeled) pairs.\n   ! (If Commented out, Default=-1*nLastObs)\n   ! > 0: apply an age-based filter, units=hours.\n   ! = 0: apply no additional filter, use all available/usable obs.\n   ! < 0: apply an count-based filter, units=count\n   maxAgePairsBiasPersist = -960\n\n   ! If persistBias: The minimum number of last (obs, modeled) pairs, with age less\n   ! than maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\n   minNumPairsBiasPersist = 8\n\n   ! If persistBias: give more weight to observations closer in time? (default=FALSE)\n   invDistTimeWeightBias = .TRUE. !<-- The exact form of this\n                                  ! weighting is currently hard-coded.\n\n   ! If persistBias: \"No constructive interference in bias correction?\", reduce the bias\n   ! adjustment when the model and the bias adjustment have the same sign relative to the\n   ! modeled flow at t0? (default=FALSE)\n   ! Note: Perfect restart tests require this option to be .FALSE.\n   noConstInterfBias = .FALSE. !<-- Tactical response to phase errors.\n   /\n\n.. _section-a7:\n\nA7. Static input files for WRF-Hydro\n-------------------------------------\n\nThe WRF-Hydro model requires several static input files to define the spatial domain and\nits parameters. These include two files in common with the WRF Model, :file:`geo_em.d01.nc`\nand :file:`wrfinput.d01.nc`, as well as the WRF-Hydro  routing domain file :file:`Fulldom_hires.nc`.\n\nThe variables in these netCDF files are listed in the tables below:\n\n   .. csv-table:: :file:`geo_em.d{X}.nc` `\\qquad` *geo_em*\n      :file: input-tables/geo_em.tsv\n      :delim: tab\n      :header-rows: 1\n\n   \\\n\n\n   .. csv-table:: :file:`wrfinput.d{X}.nc` `\\qquad` *WRFINPUT*\n      :file: input-tables/wrfinput.tsv\n      :delim: tab\n      :header-rows: 1\n\n   \\\n\n\n   .. csv-table:: :file:`Fulldom_hires.nc` `\\qquad` *Fulldom_Hires*\n      :file: input-tables/Fulldom_hires.tsv\n      :delim: tab\n      :header-rows: 1\n\n.. _section-a8:\n\nA8. Noah land surface model parameter tables\n--------------------------------------------\n\nThe Noah land surface model requires three parameter table files denoted\nby the file suffix TBL. The variables contained within these files are\ndescribed in the tables below.\n\nPlease refer to the Noah land surface model documentation\n(https://ral.ucar.edu/sites/default/files/public/product-tool/unified-noah-lsm/Noah_LSM_USERGUIDE_2.7.1.pdf)\nfor additional information.\n\n`GENPARM.TBL` - This file contains global parameters for the Noah land surface model.\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +--------------------+-------------------------------------------------+\n   | **Variable name**  | **Description**                                 |\n   +====================+=================================================+\n   | SLOPE_DATA         | Linear reservoir coefficient                    |\n   +--------------------+-------------------------------------------------+\n   | SBETA_DATA         | Parameter used to calculate vegetation effect   |\n   |                    | on soil heat                                    |\n   +--------------------+-------------------------------------------------+\n   | FXEXP_DAT          | Soil evaporation exponent used in DEVAP         |\n   +--------------------+-------------------------------------------------+\n   | CSOIL_DATA         | Soil heat capacity [:math:`J/m^3/K`]            |\n   +--------------------+-------------------------------------------------+\n   | SALP_DATA          | Shape parameter of distribution function of     |\n   |                    | snow cover                                      |\n   +--------------------+-------------------------------------------------+\n   | REFDK_DATA         | Parameter in the surface runoff                 |\n   |                    | parameterization                                |\n   +--------------------+-------------------------------------------------+\n   | REFKDT_DATA        | Parameter in the surface runoff                 |\n   |                    | parameterization                                |\n   +--------------------+-------------------------------------------------+\n   | FRZK_DATA          | Frozen ground parameter                         |\n   +--------------------+-------------------------------------------------+\n   | ZBOT_DATA          | Depth of lower boundary soil temperature        |\n   |                    | [:math:`m`]                                     |\n   +--------------------+-------------------------------------------------+\n   | CZIL_DATA          | Parameter used in the calculation of the        |\n   |                    | roughness length for heat                       |\n   +--------------------+-------------------------------------------------+\n   | SMLOW_DATA         | Soil moisture wilt, soil moisture reference     |\n   |                    | parameter                                       |\n   +--------------------+-------------------------------------------------+\n   | SMHIGH_DATA        | Soil moisture wilt, soil moisture reference     |\n   |                    | parameter                                       |\n   +--------------------+-------------------------------------------------+\n   | LVCOEF_DATA        | Parameter in the snow albedo formulation        |\n   +--------------------+-------------------------------------------------+\n\n| `SOILPARM.TBL` - This file contains parameters that are assigned based\n upon soil classification.\n| *All parameters are a function of soil class.*\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +-------------+--------------------------------------------------------+\n   | **Variable  | **Description**                                        |\n   | name**      |                                                        |\n   +=============+========================================================+\n   | BB          | B parameter                                            |\n   +-------------+--------------------------------------------------------+\n   | DRYSMC      | Dry soil moisture threshold at which direct            |\n   |             | evaporation from top soil layer ends                   |\n   +-------------+--------------------------------------------------------+\n   | F11         | Soil thermal diffusivity/conductivity coefficient      |\n   +-------------+--------------------------------------------------------+\n   | MAXSMC      | Saturation soil moisture content (i.e. porosity)       |\n   +-------------+--------------------------------------------------------+\n   | REFSMC      | Reference soil moisture (field capacity), where        |\n   |             | transpiration begins to stress                         |\n   +-------------+--------------------------------------------------------+\n   | SATPSI      | Saturation soil matric potential                       |\n   +-------------+--------------------------------------------------------+\n   | SATDK       | Saturation soil conductivity                           |\n   +-------------+--------------------------------------------------------+\n   | SATDW       | Saturation soil diffusivity                            |\n   +-------------+--------------------------------------------------------+\n   | WLTSMC      | Wilting point soil moisture                            |\n   +-------------+--------------------------------------------------------+\n   | QTZ         | Soil quartz content                                    |\n   +-------------+--------------------------------------------------------+\n\n| `VEGPARM.TBL` - This file contains parameters that a function of land cover type.\n| *All parameters are a function of land cover type.*\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +-------------------+---------------------------------------------------------+\n   | **Variable name** | **Description**                                         |\n   +===================+=========================================================+\n   | SHDFAC            | Green vegetation fraction                               |\n   +-------------------+---------------------------------------------------------+\n   | NROOT             | Number of soil layers (from the top) reached by         |\n   |                   | vegetation roots                                        |\n   +-------------------+---------------------------------------------------------+\n   | RS                | Minimum stomatal resistance [`s/m`]                     |\n   +-------------------+---------------------------------------------------------+\n   | RGL               | Parameter used in radiation stress function             |\n   +-------------------+---------------------------------------------------------+\n   | HS                | Parameter used in vapor pressure deficit function       |\n   +-------------------+---------------------------------------------------------+\n   | SNUP              | Threshold water-equivalent snow depth [m] that implies  |\n   |                   | 100% snow cover                                         |\n   +-------------------+---------------------------------------------------------+\n   | MAXALB            | Upper bound on maximum albedo over deep snow [`\\%`]     |\n   +-------------------+---------------------------------------------------------+\n   | LAIMIN            | Minimum leaf area index through the year                |\n   |                   | [dimensionless]                                         |\n   +-------------------+---------------------------------------------------------+\n   | LAIMAX            | Maximum leaf area index through the year                |\n   |                   | [dimensionless]                                         |\n   +-------------------+---------------------------------------------------------+\n   | EMISSMIN          | Minimum background emissivity through the year          |\n   |                   | [fraction 0.0 to 1.0]                                   |\n   +-------------------+---------------------------------------------------------+\n   | EMISSMAX          | Maximum background emissivity through the year          |\n   |                   | [fraction 0.0 to 1.0]                                   |\n   +-------------------+---------------------------------------------------------+\n   | ALBEDOMIN         | Minimum background albedo through the year [fraction    |\n   |                   | 0.0 to 1.0]                                             |\n   +-------------------+---------------------------------------------------------+\n   | ALBEDOMAX         | Maximum background albedo through the year [fraction    |\n   |                   | 0.0 to 1.0]                                             |\n   +-------------------+---------------------------------------------------------+\n   | Z0MIN             | Minimum background roughness length through the year    |\n   |                   | [`m`]                                                   |\n   +-------------------+---------------------------------------------------------+\n   | Z0MAX             | Maximum background roughness length through the year    |\n   |                   | [`m`]                                                   |\n   +-------------------+---------------------------------------------------------+\n   | TOPT_DATA         | Optimum transpiration air temperature [`K`]             |\n   +-------------------+---------------------------------------------------------+\n   | CMCMAX_DATA       | Maximum canopy water capacity [volumetric fraction]     |\n   |                   |                                                         |\n   +-------------------+---------------------------------------------------------+\n   | CFACTR_DATA       | Parameter used in the canopy interception calculation   |\n   |                   | [dimensionless]                                         |\n   +-------------------+---------------------------------------------------------+\n   | RSMAX_DATA        | Maximal stomatal resistance [`s/m`]                     |\n   +-------------------+---------------------------------------------------------+\n   | BARE              | The land-use category representing bare ground (used to |\n   |                   | set the vegetation fraction to zero) [land-use category |\n   |                   | index]                                                  |\n   +-------------------+---------------------------------------------------------+\n   | NATURAL           | The land-use category representative of the non-urban   |\n   |                   | portion of urban land-use points [land-use category     |\n   |                   | index]                                                  |\n   +-------------------+---------------------------------------------------------+\n\n.. _section-a9:\n\nA9. Noah-MP land surface model parameter tables\n-----------------------------------------------\n\nThe Noah-MP land surface model requires three parameter table files\ndenoted by the file suffix TBL. The variables contained within these\nfiles are described in the tables below.\n\nAs part of the work conducted for the National Water Model\nimplementation, the ability to specify a number of these land surface\nmodel parameters spatially on a two or three dimensional grid was\nintroduced. This is done through the use of the compile time option\n``SPATIAL_SOIL`` and the specification of a netCDF format parameter file\nwith the default filename soil_properties.nc. A list of the variables\ncontained in this file is included in a table below as well.\n\n`GENPARM.TBL` This file contains global parameters for the Noah-MP\nland surface model.\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +---------------+------------------------------------------------------+\n   | **Variable    | **Description**                                      |\n   | name**        |                                                      |\n   +===============+======================================================+\n   | SLOPE_DATA    | Linear reservoir coefficient                         |\n   +---------------+------------------------------------------------------+\n   | SBETA_DATA    | Parameter used to calculate vegetation effect on     |\n   |               | soil heat                                            |\n   +---------------+------------------------------------------------------+\n   | FXEXP_DAT     | Soil evaporation exponent used in DEVAP              |\n   +---------------+------------------------------------------------------+\n   | CSOIL_DATA    | Soil heat capacity [:math:`J/m^3/K`]                 |\n   +---------------+------------------------------------------------------+\n   | SALP_DATA     | Shape parameter of distribution function of snow     |\n   |               | cover                                                |\n   +---------------+------------------------------------------------------+\n   | REFDK_DATA    | Parameter in the surface runoff parameterization     |\n   +---------------+------------------------------------------------------+\n   | REFKDT_DATA   | Parameter in the surface runoff parameterization     |\n   +---------------+------------------------------------------------------+\n   | FRZK_DATA     | Frozen ground parameter                              |\n   +---------------+------------------------------------------------------+\n   | ZBOT_DATA     | Depth of lower boundary soil temperature [:math:`m`] |\n   +---------------+------------------------------------------------------+\n   | CZIL_DATA     | Parameter used in the calculation of the roughness   |\n   |               | length for heat                                      |\n   +---------------+------------------------------------------------------+\n   | SMLOW_DATA    | Soil moisture wilt, soil moisture reference          |\n   |               | parameter                                            |\n   +---------------+------------------------------------------------------+\n   | SMHIGH_DATA   | Soil moisture wilt, soil moisture reference          |\n   |               | parameter                                            |\n   +---------------+------------------------------------------------------+\n   | LVCOEF_DATA   | Parameter in the snow albedo formulation             |\n   +---------------+------------------------------------------------------+\n\n`SOILPARM.TBL` - This file contains parameters that are assigned based\non soil classification.\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +--------------+-------------------------------------------------------+\n   | **Variable   | **Description**                                       |\n   | name**       |                                                       |\n   +==============+=======================================================+\n   | BB           | B parameter                                           |\n   +--------------+-------------------------------------------------------+\n   | DRYSMC       | Dry soil moisture threshold at which direct           |\n   |              | evaporation from top soil layer ends                  |\n   +--------------+-------------------------------------------------------+\n   | F11          | Soil thermal diffusivity/conductivity coefficient     |\n   +--------------+-------------------------------------------------------+\n   | MAXSMC       | Saturation soil moisture content (i.e. porosity)      |\n   +--------------+-------------------------------------------------------+\n   | REFSMC       | Reference soil moisture (field capacity), where       |\n   |              | transpiration begins to stress                        |\n   +--------------+-------------------------------------------------------+\n   | SATPSI       | Saturation soil matric potential                      |\n   +--------------+-------------------------------------------------------+\n   | SATDK        | Saturation soil conductivity                          |\n   +--------------+-------------------------------------------------------+\n   | SATDW        | Saturation soil diffusivity                           |\n   +--------------+-------------------------------------------------------+\n   | WLTSMC       | Wilting point soil moisture                           |\n   +--------------+-------------------------------------------------------+\n   | QTZ          | Soil quartz content                                   |\n   +--------------+-------------------------------------------------------+\n   | AXAJ         | Tension water distribution inflection parameter       |\n   +--------------+-------------------------------------------------------+\n   | BXAJ         | Tension water distribution shape parameter            |\n   +--------------+-------------------------------------------------------+\n   | XXAJ         | Free water distribution shape parameter               |\n   +--------------+-------------------------------------------------------+\n\n`MPTABLE.TBL` - This file contains parameters that are a function of\nland cover type.\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +-------------------------+--------------------------------------------+\n   | **Variable name**       | **Description**                            |\n   +=========================+============================================+\n   | VEG_DATASET_DESCRIPTION | Land cover classification dataset          |\n   +-------------------------+--------------------------------------------+\n   | NVEG                    | Number of land cover categories            |\n   +-------------------------+--------------------------------------------+\n   | ISURBAN                 | Land cover category for urban              |\n   +-------------------------+--------------------------------------------+\n   | ISWATER                 | Land cover category for water              |\n   +-------------------------+--------------------------------------------+\n   | ISBARREN                | Land cover category for barren             |\n   +-------------------------+--------------------------------------------+\n   | ISICE                   | Land cover category for ice                |\n   +-------------------------+--------------------------------------------+\n   | EBLFOREST               | Land cover category for evergreen          |\n   |                         | broadleaf forest                           |\n   +-------------------------+--------------------------------------------+\n   | .. centered:: *Parameters below are a function of land cover type*   |\n   +-------------------------+--------------------------------------------+\n   | CH2OP                   | Maximum intercepted H\\ :sub:`2`\\O per unit |\n   |                         | LAI + SAI [:math:`mm`]                     |\n   +-------------------------+--------------------------------------------+\n   | DLEAF                   | Characteristic leaf dimension [:math:`m`]  |\n   +-------------------------+--------------------------------------------+\n   | Z0MVT                   | Momentum roughness length [:math:`m`]      |\n   +-------------------------+--------------------------------------------+\n   | HVT                     | Top of canopy [:math:`m`]                  |\n   +-------------------------+--------------------------------------------+\n   | HVB                     | Bottom of canopy [:math:`m`]               |\n   +-------------------------+--------------------------------------------+\n   | DEN                     | Tree density [:math:`trunks/m^2`\\]         |\n   +-------------------------+--------------------------------------------+\n   | RC                      | Tree crown radius [:math:`m`]              |\n   +-------------------------+--------------------------------------------+\n   | MFSNO                   | Snowmelt m parameter                       |\n   +-------------------------+--------------------------------------------+\n   | RHOS_VIS                | Monthly stem area index (SAI), one-sided   |\n   +-------------------------+--------------------------------------------+\n   | RHOS_NIR                | Monthly leaf area index (LAI), one-sided   |\n   +-------------------------+--------------------------------------------+\n   | TAUL_VIS                | Leaf transmittance, visible                |\n   +-------------------------+--------------------------------------------+\n   | TAUL_NIR                | Leaf transmittance, near infrared          |\n   +-------------------------+--------------------------------------------+\n   | TAUS_VIS                | Stem transmittance, visible                |\n   +-------------------------+--------------------------------------------+\n   | TAUS_NIR                | Stem transmittance, near infrared          |\n   +-------------------------+--------------------------------------------+\n   | XL                      | Leaf / stem orientation index              |\n   +-------------------------+--------------------------------------------+\n   | CWPVT                   | Canopy wind parameter                      |\n   +-------------------------+--------------------------------------------+\n   | C3PSN                   | Photosynthetic pathway [c4 = 0. \\| c3 =    |\n   |                         | 1.]                                        |\n   +-------------------------+--------------------------------------------+\n   | KC25                    | CO2 Michaelis-Menten constant              |\n   |                         | at 25°C [:math:`Pa`]                       |\n   +-------------------------+--------------------------------------------+\n   | AKC                     | Q10 for KC25                               |\n   +-------------------------+--------------------------------------------+\n   | KO25                    | O2 Michaelis-Menten constant               |\n   |                         | at 25°C [:math:`Pa`]                       |\n   +-------------------------+--------------------------------------------+\n   | AKO                     | Q10 for KO25                               |\n   +-------------------------+--------------------------------------------+\n   | AVCMX                   | Q10 for VCMX25                             |\n   +-------------------------+--------------------------------------------+\n   | AQE                     | Q10 for QE25                               |\n   +-------------------------+--------------------------------------------+\n   | LTOVRC                  | Leaf turnover [:math:`1/s`]                |\n   +-------------------------+--------------------------------------------+\n   | DILEFC                  | Coefficient for leaf stress death          |\n   |                         | [:math:`1/s`]                              |\n   +-------------------------+--------------------------------------------+\n   | DILEFW                  | Coefficient for leaf stress death          |\n   |                         | [:math:`1/s`]                              |\n   +-------------------------+--------------------------------------------+\n   | RMF25                   | Leaf maintenance respiration at 25°C       |\n   |                         | [:math:`umol\\ CO_{2}/m^2/s`]               |\n   +-------------------------+--------------------------------------------+\n   | SLA                     | Single-side leaf area [:math:`m2/kg`]      |\n   +-------------------------+--------------------------------------------+\n   | FRAGR                   | Fraction of growth respiration             |\n   +-------------------------+--------------------------------------------+\n   | TMIN                    | Minimum temperature for photosynthesis     |\n   |                         | [:math:`K`]                                |\n   +-------------------------+--------------------------------------------+\n   | VCMX25                  | maximum rate of carboxylation at 25°C      |\n   |                         | [:math:`umol\\ CO_{2}/m^2/s`]               |\n   +-------------------------+--------------------------------------------+\n   | TDLEF                   | Characteristic temperature for leaf        |\n   |                         | freezing [:math:`K`]                       |\n   +-------------------------+--------------------------------------------+\n   | BP                      | Minimum leaf conductance                   |\n   |                         | [:math:`umol\\ /m^2/s`]                     |\n   +-------------------------+--------------------------------------------+\n   | MP                      | Slope of conductance to photosynthesis     |\n   |                         | relationship                               |\n   +-------------------------+--------------------------------------------+\n   | QE25                    | Quantum efficiency at 25°C                 |\n   |                         | [:math:`umol\\ CO_{2} / umol\\ photon`]      |\n   +-------------------------+--------------------------------------------+\n   | RMS25                   | Stem maintenance respiration at 25°C       |\n   |                         | [:math:`umol\\ CO_{2}/kg_{bio}/s`]          |\n   +-------------------------+--------------------------------------------+\n   | RMR25                   | Root maintenance respiration at 25°C       |\n   |                         | [:math:`umol\\ CO_{2}/kg_{bio}/s`]          |\n   +-------------------------+--------------------------------------------+\n   | ARM                     | Q10 for maintenance respiration            |\n   +-------------------------+--------------------------------------------+\n   | FOLNMX                  | Foliage nitrogen concentration when        |\n   |                         | :math:`f(n)=1` [:math:`\\%`]                |\n   +-------------------------+--------------------------------------------+\n   | WRRAT                   | Wood to non-wood ratio                     |\n   +-------------------------+--------------------------------------------+\n   | MRP                     | Microbial respiration parameter            |\n   |                         | [:math:`umol\\ CO_{2}/kg_{C}/s`]            |\n   +-------------------------+--------------------------------------------+\n   | NROOT                   | Number of soil layers with root present    |\n   +-------------------------+--------------------------------------------+\n   | RGL                     | Parameter used in radiation stress         |\n   |                         | function                                   |\n   +-------------------------+--------------------------------------------+\n   | RS                      | Stomatal resistance [:math:`s/m`]          |\n   +-------------------------+--------------------------------------------+\n   | HS                      | Parameter used in vapor pressure deficit   |\n   |                         | function                                   |\n   +-------------------------+--------------------------------------------+\n   | TOPT                    | Optimum transpiration air temperature [K]  |\n   +-------------------------+--------------------------------------------+\n   | RSMAX                   | Maximal stomatal resistance                |\n   |                         | [:math:`s m-1`]                            |\n   +-------------------------+--------------------------------------------+\n   | SAI                     | Steam area index                           |\n   +-------------------------+--------------------------------------------+\n   | LAI                     | Leaf area index                            |\n   +-------------------------+--------------------------------------------+\n   | SLAREA                  | (not used in Noah-MP as configured in      |\n   |                         | WRF-Hydro)                                 |\n   +-------------------------+--------------------------------------------+\n   | EPS1                    | (not used in Noah-MP as configured in      |\n   |                         | WRF-Hydro)                                 |\n   +-------------------------+--------------------------------------------+\n   | EPS2                    | (not used in Noah-MP as configured in      |\n   |                         | WRF-Hydro)                                 |\n   +-------------------------+--------------------------------------------+\n   | EPS3                    | (not used in Noah-MP as configured in      |\n   |                         | WRF-Hydro)                                 |\n   +-------------------------+--------------------------------------------+\n   | EPS4                    | (not used in Noah-MP as configured in      |\n   |                         | WRF-Hydro)                                 |\n   +-------------------------+--------------------------------------------+\n   | EPS5                    | (not used in Noah-MP as configured in      |\n   |                         | WRF-Hydro)                                 |\n   +-------------------------+--------------------------------------------+\n   | .. centered:: *Parameters below are a function of soil color index*  |\n   +-------------------------+--------------------------------------------+\n   | ALBSAT_VIS              | Saturated soil albedos for visible         |\n   +-------------------------+--------------------------------------------+\n   | ALBSAT_NIR              | Saturated soil albedos for near infrared   |\n   +-------------------------+--------------------------------------------+\n   | ALBDRY_VIS              | Dry soil albedos for visible               |\n   +-------------------------+--------------------------------------------+\n   | ALBDRY_NIR              | Dry soil albedos for near infrared         |\n   +-------------------------+--------------------------------------------+\n   | .. centered::  *Parameters below are global*                         |\n   +-------------------------+--------------------------------------------+\n   | ALBICE                  | Albedo land ice (visible and near          |\n   |                         | infrared)                                  |\n   +-------------------------+--------------------------------------------+\n   | ALBLAK                  | Albedo frozen lakes (visible and near      |\n   |                         | infrared)                                  |\n   +-------------------------+--------------------------------------------+\n   | OMEGAS                  | Two-stream parameter for snow              |\n   +-------------------------+--------------------------------------------+\n   | BETADS                  | Two-stream parameter for snow              |\n   +-------------------------+--------------------------------------------+\n   | BETAIS                  | Two-stream parameter for snow              |\n   +-------------------------+--------------------------------------------+\n   | EG                      | Emissivity soil surface (soil and lake)    |\n   +-------------------------+--------------------------------------------+\n   | CO2                     | CO\\ :sub:`2` partial pressure              |\n   +-------------------------+--------------------------------------------+\n   | O2                      | O\\ :sub:`2` partial pressure               |\n   +-------------------------+--------------------------------------------+\n   | TIMEAN                  | Grid cell mean topographic index [global   |\n   |                         | mean]                                      |\n   +-------------------------+--------------------------------------------+\n   | FSATMX                  | Maximum surface saturated fraction [global |\n   |                         | mean]                                      |\n   +-------------------------+--------------------------------------------+\n   | Z0SNO                   | Snow surface roughness length [:math:`m`]  |\n   +-------------------------+--------------------------------------------+\n   | SSI                     | Liquid water holding capacity for snowpack |\n   |                         | [:math:`m^3/m^3`]                          |\n   +-------------------------+--------------------------------------------+\n   | SWEMX                   | New snow mass to fully cover old snow      |\n   |                         | [:math:`mm`]                               |\n   +-------------------------+--------------------------------------------+\n   | TAU0                    | Tau0 from Yang97 eqn. 10a                  |\n   +-------------------------+--------------------------------------------+\n   | GRAIN_GROWTH            | Growth from vapor diffusion Yang97         |\n   |                         | eqn. 10b                                   |\n   +-------------------------+--------------------------------------------+\n   | EXTRA_GROWTH            | Extra growth near freezing Yang97          |\n   |                         | eqn. 10c                                   |\n   +-------------------------+--------------------------------------------+\n   | DIRT_SOOT               | Dirt and soot term Yang97 eqn. 10d         |\n   +-------------------------+--------------------------------------------+\n   | BATS_COSZ               | Zenith angle snow albedo                   |\n   |                         | adjustment; b in Yang97 eqn. 15            |\n   +-------------------------+--------------------------------------------+\n   | BATS_VIS_NEW            | New snow visible albedo                    |\n   +-------------------------+--------------------------------------------+\n   | BATS_NIR_NEW            | New snow NIR albedo                        |\n   +-------------------------+--------------------------------------------+\n   | BATS_VIS_AGE            | Age factor for diffuse visible snow        |\n   |                         | albedo Yang97 eqn. 17                      |\n   +-------------------------+--------------------------------------------+\n   | BATS_NIR_AGE            | Age factor for diffuse NIR snow            |\n   |                         | albedo Yang97 eqn. 18                      |\n   +-------------------------+--------------------------------------------+\n   | BATS_VIS_DIR            | Cosz factor for direct visible snow        |\n   |                         | albedo Yang97 eqn. 15                      |\n   +-------------------------+--------------------------------------------+\n   | BATS_NIR_DIR            | Cosz factor for direct NIR snow            |\n   |                         | albedo Yang97 eqn. 16                      |\n   +-------------------------+--------------------------------------------+\n   | RSURF_SNOW              | Surface resistance for snow [:math:`s/m`]  |\n   +-------------------------+--------------------------------------------+\n   | RSURF_EXP               | Exponent in the shape parameter for        |\n   |                         | soil resistance option 1                   |\n   +-------------------------+--------------------------------------------+\n   | IMPERV_URBAN            | impervious fraction to use for urban       |\n   |                         | type cells [0-1]                           |\n   +-------------------------+--------------------------------------------+\n   | SCAMAX                  | maximum fractional snow covered area [0-1] |\n   +-------------------------+--------------------------------------------+\n   | SWE_LIMIT               | maximum SWE limit [mm]                     |\n   +-------------------------+--------------------------------------------+\n\n`soil\\_properties.nc` [optional]\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +------------+----------------------------------------------------------+\n   | **Variable | **Description**                                          |\n   | name**     |                                                          |\n   +============+==========================================================+\n   | bexp       | Beta parameter                                           |\n   +------------+----------------------------------------------------------+\n   | cwpvt      | Empirical canopy wind parameter                          |\n   +------------+----------------------------------------------------------+\n   | dksat      | Saturated soil hydraulic conductivity                    |\n   +------------+----------------------------------------------------------+\n   | dwsat      | Saturated soil hydraulic diffusivity                     |\n   +------------+----------------------------------------------------------+\n   | hvt        | Top of vegetation canopy [:math:`m`]                     |\n   +------------+----------------------------------------------------------+\n   | mfsno      | Snowmelt m parameter                                     |\n   +------------+----------------------------------------------------------+\n   | mp         | Slope of conductance to photosynthesis relationship      |\n   +------------+----------------------------------------------------------+\n   | psisat     | Saturated soil matric potential                          |\n   +------------+----------------------------------------------------------+\n   | quartz     | Soil quartz content                                      |\n   +------------+----------------------------------------------------------+\n   | refdk      | Parameter in the surface runoff parameterization         |\n   +------------+----------------------------------------------------------+\n   | refkdt     | Parameter in the surface runoff parameterization         |\n   +------------+----------------------------------------------------------+\n   | rsurf_exp  | Exponent in the shape parameter for soil                 |\n   |            | resistance option 1                                      |\n   +------------+----------------------------------------------------------+\n   | slope      | Slope index                                              |\n   +------------+----------------------------------------------------------+\n   | smcdry     | Dry soil moisture threshold where direction evaporation  |\n   |            | from the top layer ends                                  |\n   +------------+----------------------------------------------------------+\n   | smcmax     | Saturated value of soil moisture [volumetric]            |\n   +------------+----------------------------------------------------------+\n   | smcref     | Reference soil moisture (field capacity) [volumetric]    |\n   +------------+----------------------------------------------------------+\n   | smcwlt     | Wilting point soil moisture [volumetric]                 |\n   +------------+----------------------------------------------------------+\n   | vcmx25     | Maximum rate of carboxylation at 25°C                    |\n   |            | [:math:`umol\\ CO_{2}/m^2/s`]                             |\n   +------------+----------------------------------------------------------+\n   | AXAJ       | Tension water distribution inflection parameter          |\n   +------------+----------------------------------------------------------+\n   | BXAJ       | Tension water distribution shape parameter               |\n   +------------+----------------------------------------------------------+\n   | XXAJ       | Free water distribution shape parameter                  |\n   +------------+----------------------------------------------------------+\n   | rsurfsnow  | Surface resistance for snow [s/m]                        |\n   +------------+----------------------------------------------------------+\n   | scamax     | Maximum fractional snow covered area [0-1]               |\n   +------------+----------------------------------------------------------+\n   | snowretfac | Snowpack water release timescale factor [1/s]            |\n   +------------+----------------------------------------------------------+\n   | ssi        | Liquid water holding capacity for snowpack               |\n   |            | [:math:`m^3/m^3`]                                        |\n   +------------+----------------------------------------------------------+\n   | tau0       | Snow albedo decay timescale parameter [s]                |\n   +------------+----------------------------------------------------------+\n   | imperv     | Impervious fraction (optional) [0-1]                     |\n   +------------+----------------------------------------------------------+\n\n\n\n.. _section-a10:\n\nA10. Terrain routing parameter files\n------------------------------------\n\nParameters for the lateral routing component of WRF-Hydro are specified\nvia either the `HYDRO.TBL` file or the `hydro2dtbl.nc` file. Variables\nwithin these files are described in the tables below.\n\n`HYDRO.TBL`\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +--------------------+------------------------------------------------------+\n   | **Variable name**  | **Description**                                      |\n   +====================+======================================================+\n   | .. centered:: *The parameter below is a function of land cover type*      |\n   +--------------------+------------------------------------------------------+\n   | SFC_ROUGH          | Overland flow roughness coefficient                  |\n   +--------------------+------------------------------------------------------+\n   | .. centered:: *The parameters below are a function of soil class*         |\n   +--------------------+------------------------------------------------------+\n   | SATDK              | Saturated soil hydraulic conductivity [:math:`m/s`]  |\n   +--------------------+------------------------------------------------------+\n   | MAXSMC             | Maximum volumetric soil moisture                     |\n   |                    | [:math:`m^3/m^3`]                                    |\n   +--------------------+------------------------------------------------------+\n   | REFSMC             | Reference volumetric soil moisture                   |\n   |                    | [:math:`m^3/m^3`]                                    |\n   +--------------------+------------------------------------------------------+\n   | WLTSMC             | Wilting point volumetric soil moisture               |\n   |                    | [:math:`m^3/m^3`]                                    |\n   +--------------------+------------------------------------------------------+\n   | QTZ                | Quartz fraction of the soil                          |\n   +--------------------+------------------------------------------------------+\n\n`hydro2dtbl.nc`\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +-----------------------+----------------------------------------------+\n   | **Variable name**     | **Description**                              |\n   +=======================+==============================================+\n   | SMCMAX1               | Maximum volumetric soil moisture             |\n   |                       | [:math:`m^3/m^3`]                            |\n   +-----------------------+----------------------------------------------+\n   | SMCREF1               | Reference volumetric soil moisture           |\n   |                       | [:math:`m^3/m^3`]                            |\n   +-----------------------+----------------------------------------------+\n   | SMCWLT1               | Wilting point volumetric soil moisture       |\n   |                       | [:math:`m^3/m^3`]                            |\n   +-----------------------+----------------------------------------------+\n   | OV_ROUGH2D            | Overland flow roughness coefficient          |\n   +-----------------------+----------------------------------------------+\n   | LKSAT                 | Lateral saturated soil hydraulic             |\n   |                       | conductivity [:math:`m/s`]                   |\n   +-----------------------+----------------------------------------------+\n   | NEXP                  | Exponent in the decay function for lateral   |\n   |                       | Ksat over depth                              |\n   +-----------------------+----------------------------------------------+\n\n\n.. _section-a11:\n\nA11. Channel routing parameter tables (`CHANPARM.TBL` and `Route\\_Link.nc`)\n---------------------------------------------------------------------------\n\nVariables of the the channel routing parameter tables are described in\nthe tables below.\n\n| `CHANPARM.TBL`\n| *All parameters are a function of Strahler stream order*\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +----------------------+---------------------------------------------------+\n   | **Variable name**    | **Description**                                   |\n   +======================+===================================================+\n   | Bw                   | Channel bottom width [:math:`m`]                  |\n   +----------------------+---------------------------------------------------+\n   | HLINK                | Initial depth of water in the channel [:math:`m`] |\n   +----------------------+---------------------------------------------------+\n   | ChSSlp               | Channel side slope [:math:`m/m`]                  |\n   +----------------------+---------------------------------------------------+\n   | MannN                | Manning’s roughness coefficient                   |\n   +----------------------+---------------------------------------------------+\n\n| `Route\\_Link.nc`\n| *All parameters are specified per stream specified per stream segment (i.e. link)*\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +----------------------+-----------------------------------------------+\n   | **Variable name**    | **Description**                               |\n   +======================+===============================================+\n   | BtmWdth              | Channel bottom width [:math:`m`]              |\n   +----------------------+-----------------------------------------------+\n   | ChSlp                | Channel side slope [:math:`m/m`]              |\n   +----------------------+-----------------------------------------------+\n   | Kchan                | Channel conductivity [:math:`mm/hr`]          |\n   +----------------------+-----------------------------------------------+\n   | Length               | Stream segment length [:math:`m`]             |\n   +----------------------+-----------------------------------------------+\n   | MusK                 | Muskingum routing time [:math:`s`]            |\n   +----------------------+-----------------------------------------------+\n   | MusX                 | Muskingum weighting coefficient               |\n   +----------------------+-----------------------------------------------+\n   | NHDWaterbodyComID    | ComID of an associated water body if any      |\n   +----------------------+-----------------------------------------------+\n   | Qi                   | Initial flow in link [:math:`m^3/s`]          |\n   +----------------------+-----------------------------------------------+\n   | So                   | Slope [:math:`m/m`]                           |\n   +----------------------+-----------------------------------------------+\n   | alt                  | Elevation from the NAD88 datum at start node  |\n   |                      | [:math:`m`]                                   |\n   +----------------------+-----------------------------------------------+\n   | ascendingIndex       | Index to user for sorting IDs - *only in NWM  |\n   |                      | files*                                        |\n   +----------------------+-----------------------------------------------+\n   | from                 | From Link ID                                  |\n   +----------------------+-----------------------------------------------+\n   | gages                | Identifier for stream gage at this location   |\n   +----------------------+-----------------------------------------------+\n   | lat                  | Latitude of the segment midpoint *[degrees    |\n   |                      | north]*                                       |\n   +----------------------+-----------------------------------------------+\n   | link                 | Link ID                                       |\n   +----------------------+-----------------------------------------------+\n   | lon                  | Longitude of the segment midpoint *[degrees   |\n   |                      | east]*                                        |\n   +----------------------+-----------------------------------------------+\n   | n                    | Manning's roughness                           |\n   +----------------------+-----------------------------------------------+\n   | nCC                  | Compound Channel Manning's roughness          |\n   +----------------------+-----------------------------------------------+\n   | order                | Strahler stream order                         |\n   +----------------------+-----------------------------------------------+\n   | to                   | To Link ID                                    |\n   +----------------------+-----------------------------------------------+\n   | time                 | Time of measurement                           |\n   +----------------------+-----------------------------------------------+\n   | TopWdth              | Top Width [m]                                 |\n   +----------------------+-----------------------------------------------+\n   | TopWdthCC            | Compound Channel Top Width [m]                |\n   +----------------------+-----------------------------------------------+\n\n.. _section-a12:\n\nA12. Groundwater input and parameter files\n------------------------------------------\n\nThe contents of the groundwater input and parameter files are described\nin the tables below.\n\n`GWBASINS.nc`\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +----------------------+-----------------------------------------------+\n   | **Variable name**    | **Description**                               |\n   +======================+===============================================+\n   | y                    | projection y coordinate                       |\n   +----------------------+-----------------------------------------------+\n   | x                    | projection x coordinate                       |\n   +----------------------+-----------------------------------------------+\n   | crs                  | coordinate reference system definition        |\n   +----------------------+-----------------------------------------------+\n   | BASIN                | groundwater basin ID                          |\n   +----------------------+-----------------------------------------------+\n\n`GWBUCKPARM.nc`\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +-----------------------+----------------------------------------------+\n   | **Variable name**     | **Description**                              |\n   +=======================+==============================================+\n   | Basin                 | Basin monotonic ID (1...n)                   |\n   +-----------------------+----------------------------------------------+\n   | Coeff                 | Coefficient                                  |\n   +-----------------------+----------------------------------------------+\n   | Expon                 | Exponent                                     |\n   +-----------------------+----------------------------------------------+\n   | Zmax                  | Zmax                                         |\n   +-----------------------+----------------------------------------------+\n   | Zinit                 | Zinit                                        |\n   +-----------------------+----------------------------------------------+\n   | Area_sqkm             | Basin area [:math:`km^2`]                    |\n   +-----------------------+----------------------------------------------+\n   | ComID                 | NHDCatchment FEATUREID (NHDFlowline ComID)   |\n   +-----------------------+----------------------------------------------+\n   | Loss                  | Fraction of bucket output lost               |\n   +-----------------------+----------------------------------------------+\n\n.. _section-a13:\n\nA13. Spatial weights input file variable description\n----------------------------------------------------\n\nThe contents of the `spatialweights.nc` file is described in the table\nbelow.\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +--------------+---------------------------------------------+---------------+\n   | **Variable   | **Description**                             | **Dimension** |\n   | name**       |                                             |               |\n   +==============+=============================================+===============+\n   | polyid       | ID of polygon                               | polyid        |\n   +--------------+---------------------------------------------+---------------+\n   | IDmask       | Polygon ID (polyid) associated with each    | data          |\n   |              | record)                                     |               |\n   +--------------+---------------------------------------------+---------------+\n   | overlaps     | Number of intersecting polygons             | polyid        |\n   +--------------+---------------------------------------------+---------------+\n   | weight       | Fraction of intersecting polygon(polyid)    | data          |\n   |              | intersected by poly2                        |               |\n   +--------------+---------------------------------------------+---------------+\n   | regridweight | Fraction of intersecting                    | data          |\n   |              | polyid(overlapper) intersected by           |               |\n   |              | polygon(polyid)                             |               |\n   +--------------+---------------------------------------------+---------------+\n   | i_index      | Index in the x dimension of the raster      | data          |\n   |              | grid *(starting with 1,1 in the LL corner)* |               |\n   +--------------+---------------------------------------------+---------------+\n   | j_index      | Index in the y dimension of the raster      | data          |\n   |              | grid *(starting with 1,1 in the LL corner)* |               |\n   +--------------+---------------------------------------------+---------------+\n\n.. _section-a14:\n\nA14. Lake and reservoir parameter tables (`LAKEPARM.nc`)\n--------------------------------------------------------\n\nVariables within the `LAKEPARM.nc` file are described in the tables below.\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +--------------------+-------------------------------------------------+\n   | **Variable name**  | **Description**                                 |\n   +====================+=================================================+\n   | lake_id            | Lake index (consecutively from 1 to n # of      |\n   |                    | lakes)                                          |\n   +--------------------+-------------------------------------------------+\n   | LkArea             | Area [:math:`m^2`]                              |\n   +--------------------+-------------------------------------------------+\n   | LkMxE              | Elevation of maximum lake height [:math:`m`,    |\n   |                    | AMSL]                                           |\n   +--------------------+-------------------------------------------------+\n   | WeirC              | Weir coefficient (ranges from zero to one)      |\n   +--------------------+-------------------------------------------------+\n   | WeirL              | Weir length [:math:`m`]                         |\n   +--------------------+-------------------------------------------------+\n   | WeirE              | Weir elevation [:math:`m`, AMSL]                |\n   +--------------------+-------------------------------------------------+\n   | OrificeC           | Orifice coefficient (ranges from zero to one)   |\n   +--------------------+-------------------------------------------------+\n   | OrificeA           | Orifice area [:math:`m^2`]                      |\n   +--------------------+-------------------------------------------------+\n   | OrificeE           | Orifice elevation [:math:`m`, AMSL]             |\n   +--------------------+-------------------------------------------------+\n   | Dam_Length         | Dam length as a multiplier on WeirL [multiplier]|\n   +--------------------+-------------------------------------------------+\n   | lat                | Latitude *[decimal degrees north]*              |\n   +--------------------+-------------------------------------------------+\n   | lon                | Longitude *[decimal degrees east]*              |\n   +--------------------+-------------------------------------------------+\n   | time               | time                                            |\n   +--------------------+-------------------------------------------------+\n   | ascendingIndex     | Index to use for sorting IDs (ascending)        |\n   +--------------------+-------------------------------------------------+\n   | ifd                | Initial fraction water depth                    |\n   +--------------------+-------------------------------------------------+\n   | crs                | CRS definition                                  |\n   +--------------------+-------------------------------------------------+\n\n.. _section-a15:\n\nA15. Restart Files Overview\n---------------------------\n\n**Cold start versus warm start model simulations:**\n\nWhen one start the model as a `cold start` (meaning that it is starting with the default values at the very\nbeginning), it takes time for the model to warm up and reach an equilibrium state. For example, consider\nsimulating streamflow values for a stream which has a base flow of at least 10 cms during the year, and you\nhave a `cold start`. The default values of the streamflow might be zeros at the start of the modeling. It then\ntakes time for the simulated streamflow within the model to reach the 10 cms. In contrast, a `warm start` is\nwhen the model simulation begins with the simulated values of a given time step (starting time step) from a\nprevious run. This eliminates the processing time the model would take to reach an equilibrium state.\nDepending on which variable of the model you are looking at, the time required to reach to the warm state may\ndiffer. For example, groundwater requires a longer time period to reach to equilibrium.\n\n**How to do a warm start simulations with WRF-Hydro?**\n\nWRF-Hydro model outputs two set of model restart files (:file:`RESTART.YYYYmmddHH_DOMAIN` and\n:file:`HYDRO_RST.YYYY-mm-dd_HH:MM_DOMAIN1`) which store the model states at a specified time and\ncould be used to start the model from that point in time. :file:`RESTART.YYYYmmddHH_DOMAIN` stores the\nstate variables reqiured for restarting LSM and :file:`HYDRO_RST.YYYY-mm-dd_HH:MM_DOMAIN`\nstores the state variables required to resume the hydro components of the WRF-Hydro model.\n\nTo warm start the LSM part of the model, specify path to the restart file in the :file:`namelist.hrldas`\nusing `RESTART\\_FILENAME\\_REQUESTED` option.\nTo warm start the HYDRO part of the model, specify the path to the `HYDRO\\_RST` file in\nthe :file:`hydro.namelist` using the option `RESTART\\_FILE`, and also set the `gw\\_restart` option to 1.\nIf the path to the files are left empty or commented out, it means the model simulation is cold started.\n\n\nOne could control the frequency of outputting restart files using the options `RESTART\\_FREQUENCY\\_HOURS`\nand `rst\\_dt` in the :file:`namelist.hrldas` and :file:`hydro.namelist`, respectively. If these options are set\nto -9999, model outputs restart files once a month. Restart files are large in size, and therefore user\nneeds to be cautious of how frequently it outputs the restart files.\n\n.. figure:: media/restarts.png\n   :align: center\n\n   **Figure A15.** Overview of restart files for the various model physics\n   components.\n\nA15.1 RESTART_MP File Variable Table\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. note::\n   Noah-MP restarts are written in ``subroutine lsm_restart()`` in :file:`module_NoahMP_hrldas_driver.F`.\n   Noah-MP variables are defined in ``subroutine noahmplsm()`` in :file:`module_sf_noahmpdrv.F`\n\n`RESTART\\_MP` file variable descriptions\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +-------------+-------------------------------------------+------------------+\n   | **Variable  | **Description**                           | **Units**        |\n   | name**      |                                           |                  |\n   +=============+===========================================+==================+\n   | ACCPRCP     | Accumulated precipitation                 | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | ACCECAN     | Accumulated canopy evaporation            | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | ACCEDIR     | Accumulated direct soil evaporation       | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | ACCETRAN    | Accumulated transpiration                 | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | ACMELT      | accumulated melting water out of snow     | :math:`mm`       |\n   |             | bottom                                    |                  |\n   +-------------+-------------------------------------------+------------------+\n   | ACSNOW      | accumulated snowfall on grid              | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | ALBOLD      | snow albedo at last time step (-)         |                  |\n   +-------------+-------------------------------------------+------------------+\n   | AREAXY      | (in the file but not used by the model)   |                  |\n   +-------------+-------------------------------------------+------------------+\n   | CANICE      | Canopy ice water content /                | :math:`mm`       |\n   |             | canopy-intercepted ice                    |                  |\n   +-------------+-------------------------------------------+------------------+\n   | CANLIQ      | Canopy liquid water content /             | :math:`mm`       |\n   |             | canopy-intercepted liquid water           |                  |\n   +-------------+-------------------------------------------+------------------+\n   | CH          | Sensible heat exchange coefficient        |                  |\n   +-------------+-------------------------------------------+------------------+\n   | CM          | Momentum drag coefficient                 |                  |\n   +-------------+-------------------------------------------+------------------+\n   | DEEPRECHXY  | soil moisture below the bottom of the     | :math:`m^3/m^3`  |\n   |             | column                                    |                  |\n   +-------------+-------------------------------------------+------------------+\n   | EAH         | canopy air vapor pressure                 | :math:`Pa`       |\n   +-------------+-------------------------------------------+------------------+\n   | EQZWT       | (in the file but not used by the model)   |                  |\n   +-------------+-------------------------------------------+------------------+\n   | FASTCP      | short-lived carbon in shallow soil        | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | FDEPTHXY    | (in the file but not used by the model)   |                  |\n   +-------------+-------------------------------------------+------------------+\n   | FWET        | Wetted or snowed fraction of canopy       | :math:`fraction` |\n   +-------------+-------------------------------------------+------------------+\n   | GVFMAX      | annual maximum in vegetation fraction     |                  |\n   +-------------+-------------------------------------------+------------------+\n   | GVFMIN      | annual minimum in vegetation fraction     |                  |\n   +-------------+-------------------------------------------+------------------+\n   | ISNOW       | Number of snow layers                     | :math:`count`    |\n   +-------------+-------------------------------------------+------------------+\n   | LAI         | leaf area index                           |                  |\n   +-------------+-------------------------------------------+------------------+\n   | LFMASS      | Leaf mass                                 | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | PEXPXY      | (in the file but not used by the model)   |                  |\n   +-------------+-------------------------------------------+------------------+\n   | QRFSXY      | Stem mass                                 | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | QRFXY       | (in the file but not used by the model)   |                  |\n   +-------------+-------------------------------------------+------------------+\n   | QSFC        | bulk surface specific humidity            |                  |\n   +-------------+-------------------------------------------+------------------+\n   | QSLATXY     | Stable carbon in deep soil                | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | QSNOW       | snowfall rate on the ground               | :math:`mm/s`     |\n   +-------------+-------------------------------------------+------------------+\n   | QSPRINGSXY  | Mass of wood and woody roots              | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | QSPRINGXY   | (in the file by not used by the model)    |                  |\n   +-------------+-------------------------------------------+------------------+\n   | RECHXY      | recharge to the water table (diagnostic)  | :math:`m^3/m^3`  |\n   +-------------+-------------------------------------------+------------------+\n   | RIVERBEDXY  | (in the file but not used by the model)   |                  |\n   +-------------+-------------------------------------------+------------------+\n   | RIVERCONDXY | (in the file but not used by the model)   |                  |\n   +-------------+-------------------------------------------+------------------+\n   | RTMASS      | mass of fine roots                        | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | SAI         | stem area index                           |                  |\n   +-------------+-------------------------------------------+------------------+\n   | SFCRUNOFF   | Accumulatetd surface runoff               | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | SH2O        | volumetric liquid soil moisture           | :math:`m^3/m^3`  |\n   +-------------+-------------------------------------------+------------------+\n   | SMC         | Volumetric Soil Moisture                  | :math:`m^3/m^3`  |\n   +-------------+-------------------------------------------+------------------+\n   | SMCWTDXY    | soil moisture below the bottom of the     | :math:`m^3/m^3`  |\n   |             | column                                    |                  |\n   +-------------+-------------------------------------------+------------------+\n   | SMOISEQ     | volumetric soil moisture                  | :math:`m^3/m^3`  |\n   +-------------+-------------------------------------------+------------------+\n   | SNEQV       | Snow water equivalent                     | :math:`kg/m^2`   |\n   +-------------+-------------------------------------------+------------------+\n   | SNEQVO      | snow mass at last time step               | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | SNICE       | snow layer ice                            | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | SNLIQ       | Snow layer liquid water                   | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | SNOWH       | Snow depth                                | :math:`m`        |\n   +-------------+-------------------------------------------+------------------+\n   | SNOW_T      | snow temperature                          | :math:`K`        |\n   +-------------+-------------------------------------------+------------------+\n   | SOIL_T      | Soil Temperature on NSOIL layers          | :math:`K`        |\n   +-------------+-------------------------------------------+------------------+\n   | STBLCP      | Stable carbon in deep soil                | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | STMASS      | stem mass                                 | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | TAH         | Canopy Air Temperature                    | :math:`K`        |\n   +-------------+-------------------------------------------+------------------+\n   | TAUSS       | snow age factor                           |                  |\n   +-------------+-------------------------------------------+------------------+\n   | TG          | Ground Temperature                        | :math:`K`        |\n   +-------------+-------------------------------------------+------------------+\n   | TV          | Canopy Temperature                        | :math:`K`        |\n   +-------------+-------------------------------------------+------------------+\n   | UDRUNOFF    | Accumulated underground runoff\"           | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | WA          | Water in aquifer relative to reference    | :math:`kg/m^2`   |\n   |             | level                                     |                  |\n   +-------------+-------------------------------------------+------------------+\n   | WOOD        | Mass of wood and woody roots              | :math:`g/m^2`    |\n   +-------------+-------------------------------------------+------------------+\n   | WSLAKE      | lake water storage                        | :math:`mm`       |\n   +-------------+-------------------------------------------+------------------+\n   | WT          | Water in aquifer and saturated soil       | :math:`kg/m^2`   |\n   +-------------+-------------------------------------------+------------------+\n   | ZSNSO       | Snow layer depths from snow surface       | :math:`m`        |\n   +-------------+-------------------------------------------+------------------+\n   | ZWT         | water table depth                         | :math:`m`        |\n   +-------------+-------------------------------------------+------------------+\n   | VEGFRA      | Vegetation fraction                       |                  |\n   +-------------+-------------------------------------------+------------------+\n\n\n\n.. _section-a15.2:\n\nA15.2 HYDRO_RST File Variable Table\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. note::\n   The variables are written to the `HYDRO\\_RST` file in the subroutine of\n   ``RESTART_OUT_nc`` in the :file:`Routing/module_HYDRO_io.F90`. The tables below\n   contain all the information on the dimensions and variables in the Hydro\n   RESTART file (`HYDRO\\_RST`).\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +---------------+-----------------------------+---------------------------+\n   | **Dimension** | **Description**             | **It is written**         |\n   +===============+=============================+===========================+\n   | depth         | Number of soil layers       |                           |\n   +---------------+-----------------------------+---------------------------+\n   | ix            | Number of columns in the    |                           |\n   |               | coarse grid (LSM)           |                           |\n   +---------------+-----------------------------+---------------------------+\n   | iy            | Number of rows in the       |                           |\n   |               | coarse grid (LSM)           |                           |\n   +---------------+-----------------------------+---------------------------+\n   | ixrt          | Number of columns in the    |                           |\n   |               | fine grid (hydro)           |                           |\n   +---------------+-----------------------------+---------------------------+\n   | iyrt          | Number of rows in the fine  |                           |\n   |               | grid (hydro)                |                           |\n   +---------------+-----------------------------+---------------------------+\n   | links         | Number of links/reaches     |                           |\n   +---------------+-----------------------------+---------------------------+\n   | basns         | Number of basins for the    | Only if ``GWBASESWCRT=1`` |\n   |               | groundwater/baseflow        | in the `hydro.namelist`   |\n   |               | modeling                    |                           |\n   +---------------+-----------------------------+---------------------------+\n   | lakes         | Number of lakes             | Only if the lake          |\n   |               |                             | routing is turned on      |\n   +---------------+-----------------------------+---------------------------+\n\n.. table::\n   :width: 90%\n   :align: center\n\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | **Variable   | **Description**               | **# Dimensions | **Resolution** | **Units**       |\n   | name**       |                               | (not           |                |                 |\n   |              |                               | including      |                |                 |\n   |              |                               | time)**        |                |                 |\n   +==============+===============================+================+================+=================+\n   | cvol         | volume of stream in cell      | 1              | fine/link      | :math:`m^3`     |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | hlink        | stream stage                  | 1              | fine/link      | :math:`m`       |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | infxsrt      | infiltration excess water     | 2              | coarse         | :math:`mm`      |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | infxswgt     | weights for disaggregation of | 2              | fine           | \\-              |\n   |              | infxsrt                       |                |                |                 |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | qbdryrt      | accumulated value of the      | 2              | fine           | :math:`mm`      |\n   |              | boundary flux                 |                |                |                 |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | qlink1       | stream flow in to cell/reach  | 1              | fine/link      | :math:`m^3/s`   |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | qlink2       | stream flow out of cell/reach | 1              | fine/link      | :math:`m^3/s`   |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | qstrmvolrt   | Accumulated depth of stream   | 2              | fine           | :math:`mm`      |\n   |              | channel inflow                |                |                |                 |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | sfcheadrt    | surface head on the coarse    | 2              | coarse         | :math:`mm`      |\n   |              | grid                          |                |                |                 |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | sfcheadsubrt | surface head on the routing   | 2              | fine           | :math:`mm`      |\n   |              | grid                          |                |                |                 |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | sh2owgt      | weights for disaggregation of | 3              | fine           | \\-              |\n   |              | total soil moisture (smc)     |                |                |                 |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | sh2ox        | liquid soil moisture          | 3              | coarse         | :math:`m^3/m^3` |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | smc          | total liq+ice soil moisture.  | 3              | coarse         | :math:`m^3/m^3` |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | soldrain     | soil drainage                 | 2              | coarse         | :math:`mm`      |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | stc          | soil temperature              | 3              | coarse         | :math:`K`       |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | lake_inflort | lake inflow                   | 2              | fine           | :math:`mm`      |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | resht        | water surface elevation       | 1              | link           | :math:`m`       |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | qlakeo       | outflow from lake used in     | 1              | link           | :math:`m^3/s`   |\n   |              | diffusion scheme              |                |                |                 |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | qlakei       | lake inflow                   | numLakes       | link           | :math:`m^3/s`   |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n   | z_gwsubbas   | depth in ground water bucket  | 1              | link           | :math:`m`       |\n   +--------------+-------------------------------+----------------+----------------+-----------------+\n\n\n.. _section-a16:\n\nA16. Streamflow Nudging\n-----------------------\n\nBelow is an example netCDF header nudging time slice\nobservation file containing 2 gages. The command :program:`ncdump -h` was used to\nproduce this header information.\n\n::\n\n   netcdf 2013-06-01_21:45:00.15min.usgsTimeSlice {\n   dimensions:\n      stationIdStrLen = 15 ;\n      stationIdInd = UNLIMITED ; // (2 currently)\n      timeStrLen = 19 ;\n   variables:\n      char stationId(stationIdInd, stationIdStrLen) ;\n         stationId:long_name = \"USGS station identifier of length 15\" ;\n      char time(stationIdInd, timeStrLen) ;\n         time:units = \"UTC\" ;\n         time:long_name = \"YYYY-MM-DD_HH:mm:ss UTC\" ;\n      float discharge(stationIdInd) ;\n         discharge:units = \"m^3/s\" ;\n         discharge:long_name = \"Discharge.cubic_meters_per_second\" ;\n      short discharge_quality(stationIdInd) ;\n         discharge_quality:units = \"-\" ;\n         discharge_quality:long_name = \"Discharge quality 0 to 100 to be scaled by 100.\" ;\n      float queryTime(stationIdInd) ;\n         queryTime:units = \"seconds since 1970-01-01 00:00:00 local TZ\" ;\n   // global attributes:\n         :fileUpdateTimeUTC = \"2017-08-25_17:24:22\" ;\n         :sliceCenterTimeUTC = \"2013-06-01_21:45:00\" ;\n         :sliceTimeResolutionMinutes = \"15\" ;\n   }\n\nBelow is an example `nudgingParams.nc` file containing\nparameters for 3 gages. The command :program:`ncdump -h` was used to create this\nheader information.\n\n::\n\n   netcdf nudgingParams {\n   dimensions:\n      stationIdInd = UNLIMITED ; // (3 currently)\n      monthInd = 12 ;\n      threshCatInd = 2 ;\n      threshInd = 1 ;\n      stationIdStrLen = 15 ;\n   variables:\n      float G(stationIdInd) ;\n         G:units = \"-\" ;\n         G:long_name = \"Amplitude of nudging\" ;\n      float R(stationIdInd) ;\n         R:units = \"meters\" ;\n         R:long_name = \"Radius of influence in meters\" ;\n      float expCoeff(stationIdInd, monthInd, threshCatInd) ;\n         expCoeff:units = \"minutes\" ;\n         expCoeff:long_name = \"Coefficient b in denominator e^(-dt/b)\" ;\n      float qThresh(stationIdInd, monthInd, threshInd) ;\n         qThresh:units = \"m^3/s\" ;\n         qThresh:long_name = \"Discharge threshold category\" ;\n      char stationId(stationIdInd, stationIdStrLen) ;\n         stationId:units = \"-\" ;\n         stationId:long_name = \"USGS station identifer\" ;\n      float tau(stationIdInd) ;\n         tau:units = \"minutes\" ;\n         tau:long_name = \"Time tapering parameter half window size in minutes\" ;\n   }\n\n.. _section-a17:\n\nA17. National Water Model (NWM) Configuration\n---------------------------------------------\n\nThe community WRF-Hydro modeling system is currently the underlying modeling\narchitecture for the NOAA National Water Model. This means that the community\nWRF-Hydro model code is configurable into the National Water Model\nconfigurations that run in operations at the National Center for\nEnvironmental Prediction (NCEP).\n\n.. pull-quote::\n\n   “\\ *The NWM is an hourly cycling uncoupled analysis and forecast system\n   that provides streamflow for 2.7 million river reaches and other\n   hydrologic information on 1km and 250m grids. The model provides\n   complementary hydrologic guidance at current NWS River Forecast Center\n   (RFC) river forecast locations and significantly expanded guidance\n   coverage and type in underserved locations.*\n\n   *The NWM ingests forcing from a variety of sources including Multi-Radar\n   Multi-Sensor (MRMS) radar-gauge observed precipitation data and\n   High-Resolution Rapid Refresh (HRRR), Rapid Refresh (RAP), Global\n   Forecast System (GFS) and Climate Forecast System (CFS) Numerical\n   Weather Prediction (NWP) forecast data. USGS real-time streamflow\n   observations are assimilated and all NWM configurations benefit from the\n   inclusion of ~5500 reservoirs. The core of the NWM system is the\n   National Center for Atmospheric Research (NCAR)-supported community\n   Weather Research and Forecasting (WRF)-Hydro hydrologic model. WRF-Hydro\n   is configured to use the Noah Multi-Parameterization (Noah-MP) Land Surface Model (LSM) to simulate land\n   surface processes. Separate water routing modules perform diffusive wave\n   surface routing and saturated subsurface flow routing on a 250m grid,\n   and Muskingum-Cunge channel routing down NHDPlusV2 stream reaches. River\n   analyses and forecasts are provided across a domain encompassing the\n   continental U.S. and hydrologically-contributing areas, while land\n   surface output is available on a larger domain that extends beyond the\n   continental U.S. into Canada and Mexico (roughly from latitude 19N to\n   58N). In addition, NWM forcing datasets are provided on this domain at a\n   resolution of 1km.*\\ ”\n\n.. centered:: *Excerpt from NOUS41 KWBC 061735 PNSWSH NWS Office of Science and Technology Integration*\n\nNewer versions of the National Water Model were extended to Hawaii, Puerto Rico and the U.S. Virgin Islands, and South-Central Alaska.\n\nA17.1 Operational NWM\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFor more information regarding the operational configuration, input, and\noutput data of the National Water Model see the Office of Water\nPrediction website: http://water.noaa.gov/about/nwm and the Open Commons\nConsortium Environmental Data Commons website:\nhttp://edc.occ-data.org/nwm/.\n\nThere are different NWM configurations that run operationally. The full\nlist of the configurations and their specifics can be found at\n\n-  https://water.noaa.gov/about/nwm\n\nThe latest NWM configuration and files can be found on the NOAA NCEP site:\n\n-  https://www.nco.ncep.noaa.gov/pmb/codes/nwprod/\n   (scroll to the nwm.vX folder)\n\nNamelists for different operational configurations can be found on the NOAA NCEP site, for example:\n\n-  NWMv3.0 CONUS Analysis & Assimilation cycle:\n   https://www.nco.ncep.noaa.gov/pmb/codes/nwprod/nwm.v3.0.12/parm/analysis_assim/\n\n-  NWMv3.0 South-Central Alaska Medium-Range Forecast cycle:\n   https://www.nco.ncep.noaa.gov/pmb/codes/nwprod/nwm.v3.0.12/parm/ak_medium_range/\n\n-  NWMv3.0 Hawaii Short-Range Forecast cycle:\n   https://www.nco.ncep.noaa.gov/pmb/codes/nwprod/nwm.v3.0.12/parm/hi_short_range/\n\n-  NWMv3.0 Puerto Rico & U.S. Virgin Islands Short-Range Forecast cycle:\n   https://www.nco.ncep.noaa.gov/pmb/codes/nwprod/nwm.v3.0.12/parm/pr_short_range/\n\n\nAn archive of National Water Model operational outputs can be found on Google Cloud:\n\n-  https://console.cloud.google.com/storage/browser/national-water-model/\n\n\nA17.2 NWM Retrospectives\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIn addition to the operational model outputs, we also produce long-term (20-40 year)\nretrospectives for most versions of the National Water Model.\n\n\nThe National Water Model Retrospectives can be found on AWS and Google Cloud:\n\n-  https://registry.opendata.aws/nwm-archive/\n\n-  https://console.cloud.google.com/storage/browser/national-water-model-v3-0\n\n\n.. _section-a18:\n\nA18. The Crocus Glacier Model\n-----------------------------\n\nCrocus is an energy and mass transfer snowpack model, initially developed for\navalanche forecasting (*Brun et al., 1989, 1992*). The version that was\nimplemented into the French SURFEX model V8.0 (*Vionnet et al., 2012*) is being\nused here. This version has several updates from older versions of Crocus, such\nas the impacts of wind drift.\n\nThe Crocus snowpack model is a multilayered, physically based snow model that\nexplicitly calculates snow grain properties in each snow layer and how these\nproperties change over time. The grain properties of dendricity, sphericity and\nsize are prognosed in Crocus through metamorphism, compaction and impacts of\nwind drift. Furthermore, the snow albedo is calculated based on the snow grain\nproperties from the top 3cm of the snowpack (*Vionnet et al., 2012*) and is\ncalculated in three spectral bands (0.3-0.8, 0.8-1.5 and 1.5-2.5 `\\mu m`).\nImpurities in aging snow are parameterized in the UV and visible spectral band\n(0.3-0.8 `\\mu m`) from the age of the snow, with a time constant of 60 days. See\n*Vionnet et al. (2012)* for a detailed description of the albedo calculations.\nThe albedo over ice is constant in all spectral bands and is 0.38, 0.23 and\n0.08 for the spectral bands 0.3-0.8, 0.8-1.5 and 1.5-2.5 `\\mu m`. The sensible and\nlatent heat are parameterized with an effective roughness length over snow and\nice (see *Vionnet et al. (2012)* for further details).\n\nIn the Crocus model, it is possible to divide the snow into a user-defined\nmaximum numbers of dynamically evolving layers. As new snow is accumulated, a\nnew active layer is added. As different snow layers become similar (based upon\nthe number of user-set layers, the thickness of the snow layers and the snow\ngrain characteristics), these snow layers will merge into single snow layers.\n\nThe Crocus module is added to the Noah-MP land surface model in WRF-Hydro to\nact as a glacier mass balance model (*Eidhammer et al. 2021*). Over designated\nglacier grid points, the Crocus snow model represents both snow and ice, while\noutside of the designated glacier grid points, the regular three-layer snow\nmodel in Noah-MP is used. Since the current Crocus implementation in WRF-Hydro\nonly acts over designated glacier grid points, we follow *Gerbaux et al. (2005)*\nand assume that the temperatures at the bottom of the glacier and the ground\nbelow are both at `0^\\circ C`. Note that we have not yet incorporated\nfluxes between the glacier and the ground below; thus, there is a constant\ntemperature boundary condition.\n\nBoth Crocus and Noah-MP (for the non-glacier grid points) output runoff from\nsnowmelt (and precipitation). This runoff is provided to the terrain routing\nmodels in WRF-Hydro.\n\nNote that the implementation of Crocus as a glacier mass balance model does not\naddress glacier movement (i.e., plastic flow) nor lateral wind (re)distribution\nof snow. However, there are two options for including impacts on the snow due\nto wind. One of the options impacts the snow density during blowing snow events\n(*Brun et al., 1997*). This option is important in polar environments (*Brun et\nal., 1997*). The other option is the sublimation due to snow drift, which was\nimplemented by *Vionnet et al. (2012)* and which is in the Crocus version that\nis used in this study.\n\nAs implemented, if the glacier completely melts over a user-defined glacier\ngrid point, the original Noah-MP module is used from this point on. Therefore,\nas currently implemented, the glacier cannot grow horizontally in extent; it\ncan only decrease in extent, as no dynamic response of the ice mass is included\nin the model. Over short model time periods, the lack of increase in glacier\nextent might impact a few grid points at the edges of the glacier. However,\ngiven the expected increase in temperature in the future, we do not expect that\nlimiting glacier horizontal growth will have a major impact over most studied\nglaciers as most are likely to decrease in mass and extent.\n\n.. rubric:: Running WRF-Hydro / Glacier\n\nBelow is a description on how to run with Crocus as a glacier model. There are\nonly a few namelist options that needs to be added in :file:`namelist.hrldas`:\n\n.. code-block:: fortran\n\n   &CROCUS_nlist\n   crocus_opt = 1      ! 0 model is off, 1 model is on\n   act_lev = 40        ! 1-50, 20-40 normal options\n   /\n\nThe initialization file wrfinput needs two additional fields to be defined:\n\n   |   ``glacier``\n   |   ``glacier_thickness``\n\nThe field ``glacier`` should have the value of 1 over glacier gridpoints. The\n``glacier`` field can be provided by the user, or the user can use the glacier\ncategory from ``IVGTYP``.\n\nHere is an example how to generate initial glacier fields for an “ideal”\nsimulation, with homogeneous glacier thickness layer. In this case,\n``IVGTYP=24`` represents glaciers:\n\n.. code-block:: bash\n\n   ncap2 -O -s 'glacier=IVGTYP' wrfinput.nc wrfinput.nc\n   ncap2 -O -s 'where(glacier!=24) glacier=0' wrfinput.nc wrfinput.nc\n   ncap2 -O -s 'where(glacier==24) glacier=1' wrfinput.nc wrfinput.nc\n\nTo create a 300 m thick glacier:\n\n.. code-block:: bash\n\n   ncap2 -O -s 'glacier_thickness=glacier*300' wrfinput.nc wrfinput.nc\n\nAt initialization, it is assumed that the glacier consists of only ice, and the\ndensity is that of pure ice (`900 \\frac{kg}{m^3}`). Within the user-defined maximum\nlayers (``act_lev``) the glacier is initialized with all the layers having the same\nassumed density and snow grain properties. As new snow accumulates during the\nsimulations, the layers representing the glacier will start to merge since all\nlayers contain the initialized ice.\n\n.. rubric:: Crocus outputs\n\n.. table::\n   :width: 90%\n   :align: center\n   :name: table-a16\n\n   +--------------+-----------+----------------------------------------------+--------------------+\n   |              | Dimension | Explanation                                  | Units              |\n   +==============+===========+==============================================+====================+\n   | PSNOWSWE     | 3D        | Snow water equivalent                        | `kg/m^2`           |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWTEMP    | 3D        | Glacier temperature                          | `K`                |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWALB     | 2D        | Albedo                                       | `-`                |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWTHRUFAL | 2D        | Accumulated surface runoff                   | `kg/m^2`           |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWHEIGHT  | 2D        | Total glacier thickness                      | `m`                |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWTOTSWE  | 2D        | Total glacier snow water equivalent          | `kg/m^2`           |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWGRAN1   | 3D        | Snow grain parameter 1                       | `-`                |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWGRAN2   | 3D        | Snow grain parameter 2                       | `-`                |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWDZ      | 3D        | Thickness of snow/ice layers                 | `m`                |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWHIST    | 3D        | Snow grain historical parameter              | `-`                |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWLIQ     | 3D        | Liquid content                               | `kg/m^2`           |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | PSNOWRHO     | 3D        | Snow/ice density                             | `kg/m^3`           |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | FLOW_ICE     | 2D        | Accumulated surface runoff from ice surface  | `kg/m^2` (or `mm`) |\n   +--------------+-----------+----------------------------------------------+--------------------+\n   | FLOW_SNOW    | 2D        | Accumulated surface runoff from snow surface | `kg/m^2` (or `mm`) |\n   +--------------+-----------+----------------------------------------------+--------------------+\n\n.. note::\n   Note on other WRF-Hydro outputs: The following outputs are informed\n   from both Noah-MP and Crocus. Over glacier gridpoints, the outputs\n   are informed from Crocus: ``ACCET``, ``ALBEDO``, ``SNOWEQV``, ``SNOWH``\n   and ``ACSNOWM``.\n\n   Currently there are no namelist options to change parameter values.\n   Several important parameters that can be modified can be found in:\n   :file:`src/Land_models/NoahMP/phys/surfex/modd_snow_par.F90`\n\n   Surface runoff is assigned to ``FLOW_ICE`` when the top active layer at the\n   specific grid point has a density of 850 kg/m3, while surface runoff is\n   assigned to ``FLOW_SNOW`` when the top active layer has a density equal to\n   or less than 850 kg/m3. The sum of ``FLOW_ICE`` and ``FLOW_SNOW`` is equal\n   to ``PSNOWTHRUFAL``. Note that runoff from precipitation is included in\n   surface runoff, thus ``FLOW_SNOW`` and ``FLOW_ICE`` cannot be used directly\n   as indication if melt is from the ice part of the glacier or snow part of\n   the glacier.\n\n\n.. _section-a19:\n\nA19. Model Output Variables\n---------------------------------------------\n\nA19.1. Land surface model output variables\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   :file:`{YYYYMMDDHHMM}.LDASOUT_DOMAIN{X}`\n\n   .. csv-table:: LDASOUT\n      :file: output-tables/LDASOUT_DOMAIN.csv\n      :header-rows: 1\n\nA19.2. Land surface diagnostic output variables\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   :file:`{YYYYMMDDHHMM}.LSMOUT_DOMAIN{X}`\n\n   .. csv-table:: LSMOUT\n      :file: output-tables/LSMOUT.csv\n      :header-rows: 1\n\nA19.3. Streamflow output variables at all channel reaches/cells\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   :file:`{YYYYMMDDHHMM}.CHRTOUT_DOMAIN{X}`\n\n   .. csv-table:: CHRTOUT\n      :file: output-tables/CHRTOUT_DOMAIN.csv\n      :header-rows: 1\n\nA19.4. Streamflow output variables at forecast points or gage reaches/cells\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   :file:`{YYYYMMDDHHMM}.CHANOBS_DOMAIN{X}`\n\n   .. csv-table:: CHANOBS_DOMAIN\n      :file: output-tables/CHANOBS_DOMAIN.csv\n      :header-rows: 1\n\nA19.5. Streamflow output variables on the 2D high resolution routing grid\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   :file:`{YYYYMMDDHHMM}.CHRTOUT_GRID{X}`\n\n   .. csv-table:: CHRTOUT_GRID\n      :file: output-tables/CHRTOUT_GRID.csv\n      :header-rows: 1\n\nA19.6. Terrain routing variables on the 2D high resolution routing grid\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   :file:`{YYYYMMDDHHMM}.RTOUT_DOMAIN{X}`\n\n   .. csv-table:: RTOUT\n      :file: output-tables/RTOUT_DOMAIN.csv\n      :header-rows: 1\n\nA19.7. Lake output variables\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   :file:`{YYYYMMDDHHMM}.LAKEOUT_DOMAIN{X}`\n\n   .. csv-table:: LAKEOUT\n      :file: output-tables/LAKEOUT_DOMAIN.csv\n      :header-rows: 1\n\nA19.8. Ground water output variables\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   :file:`{YYYYMMDDHHMM}.GWOUT_DOMAIN{X}`\n\n   .. csv-table:: GWOUT\n      :file: output-tables/GWOUT_DOMAIN.csv\n      :header-rows: 1\n"
  },
  {
    "path": "docs/userguide/conf.py",
    "content": "project = 'WRF-Hydro Modeling System'\nauthor = 'WRF-Hydro Team'\ncopyright = '2024, '+author\nversion = 'v5.4.0'\nrelease = '5.4.0'\ntry:\n    import sphinx_rtd_theme\n    extensions = [\n        'sphinx_rtd_theme',\n    ]\n    # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n    html_theme = 'sphinx_rtd_theme'\n    html_theme_options = {\n        'navigation_depth': -1\n    }\nexcept:\n    print(\"Warning: sphinx_rtd_theme not installed, using default theme\")\n    pass\nhtml_static_path = ['_static']\nhtml_css_files = ['ug_theme.css']\nnumfig_secnum_depth = 2\n\n#these are enforced by rstdoc, but keep them for sphinx-build\nnumfig = 0\nsmartquotes = 0\nsource_suffix = '.rest'\ntemplates_path = []\nlanguage = 'en'\nhighlight_language = \"none\"\ndefault_role = 'math'\npygments_style = 'sphinx'\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\nmaster_doc = 'index'\n"
  },
  {
    "path": "docs/userguide/index.rest",
    "content": ".. vim: syntax=rst\n.. include:: meta.rest\n\n.. image:: media/wrfhydro-banner.png\n    :align: center\n\n=========================================================\nThe NCAR WRF-Hydro® Modeling System Technical Description\n=========================================================\n.. rst-class:: center\n\n    | Version |version_long|\n    |\n    | Originally Created:\n    | April 14, 2013\n    |\n    | Updated:\n    | January 17, 2025\n\nUntil further notice, please cite the WRF-Hydro® modeling system as\nfollows:\n\nGochis, D.J., M. Barlage, R. Cabell, M. Casali, E. Dougherty, A. Dugger, T. Eidhammer, T. Enzminger,\nK. FitzGerald, F. Felfelani, A. Gaydos, L. Karsten, A. Mazrooei, M. McAllister, J. McCreight, A. McCluskey,\nN. Omani, A. RafieeiNasab, S. Rasmussen, L. Read, K. Sampson, I. Srivastava, D. Yates, W. Yu, and\nY. Zhang (2025).\n*The WRF-Hydro® Modeling System Technical Description,* (Version 5.4).\ndoi:`10.5281/zenodo.15040873`\nNCAR Technical Note. Available online at:\nhttps://wrf-hydro.readthedocs.io/en/latest/\n\n\n.. rubric:: Links:\n\n- `Project Website <https://ral.ucar.edu/projects/wrf_hydro>`_\n- `GitHub Repository <https://github.com/NCAR/wrf_hydro_nwm_public>`_\n\n.. rubric:: FORWARD\n\nThis Technical Description describes the WRF-Hydro® model coupling\narchitecture and physics options, released in Version 5.4 in January 2025.\nAs the WRF-Hydro® modeling system is developed further, this document\nwill be continuously enhanced and updated. Please send feedback to\nwrfhydro@ucar.edu.\n\n.. rubric:: Prepared by:\n\nDavid Gochis, Michael Barlage, Ryan Cabell, Matt Casali, Erin Dougherty, Aubrey Dugger, Trude\nEidhammer, Tom Enzminger, Katelyn FitzGerald, Farshid Felfelani, Andy Gaydos, Amir Mazrooei, Molly McAllister,\nJames McCreight, Alyssa McCluskey, Nina Omani, Arezoo RafieeiNasab, Soren Rasmussen, Laura Read, Kevin Sampson,\nIshita Srivastava, David Yates, and Yongxin Zhang\n\n.. rubric:: Special Acknowledgments:\n\nDevelopment of the NCAR WRF-Hydro system has been significantly enhanced\nthrough numerous collaborations. The following persons are graciously\nthanked for their contributions to this effort:\n\n- John McHenry and Carlie Coats, Baron Advanced Meteorological Services\n\n- Martyn Clark, Fei Chen, Cenlin He, Prasanth Valayamkunnath, Dan Rosen, Rocky Dunlap,\n  Alessandro Fanfarillo, National Center for Atmospheric Research\n\n- Zong-Liang Yang, Cedric David, Peirong Lin and David Maidment of the\n  University of Texas at Austin\n\n- Harald Kunstmann, Benjamin Fersch and Thomas Rummler of Karlsruhe\n  Institute of Technology, Garmisch-Partenkirchen, Germany\n\n- Alfonso Senatore, University of Calabria, Cosenza, Italy\n\n- Brian Cosgrove, Ed Clark, Fernando Salas, Trey Flowers, Zhengtao Cui, Xia Feng, Nels Frazier,\n  James Halgren, Don Johnson, Yuqiong Liu, Dave Mattern, Fred Ogden, Cham Phan, Mehdi Rezaeianzadeh,\n  and Tom Graziano of the National Oceanic and Atmospheric Administration Office of Water Prediction\n\n- Ismail Yucel, Middle East Technical University, Ankara, Turkey\n\n- Erick Fredj, The Jerusalem College of Technology, Jerusalem, Israel\n\n- Amir Givati, Surface water and Hydrometeorology Department, Israeli\n  Hydrological Service, Jerusalem.\n\n- Antonio Parodi, Fondazione CIMA - Centro Internazionale in Monitoraggio\n  Ambientale, Savona, Italy\n\n- Blair Greimann, Sedimentation and Hydraulics section, U.S. Bureau of\n  Reclamation\n\n- Z George Xue and Dongxiao Yin, Louisiana State University\n\n- Tim Lahmers and Sujay Kumar, NASA Goddard Space Flight Center\n\nFunding support for the development and application of the WRF-Hydro®\nmodeling system has been provided by:\n\n- The National Science Foundation National Center for Atmospheric\n  Research\n\n- The U.S. National Weather Service\n\n- The Colorado Water Conservation Board\n\n- Baron Advanced Meteorological Services\n\n- National Aeronautics and Space Administration (NASA)\n\n- National Oceanic and Atmospheric Administration (NOAA) Office of Water\n  Prediction (OWP)\n\n- U.S. Geological Survey (USGS) Water Mission Area\n\n\n.. toctree::\n    :hidden:\n\n    Preface / Acknowledgements <self>\n    introduction\n    model-code-config\n    model-physics\n    nudging\n    model-inputs-preproc\n    model-outputs\n    references\n    appendices\n"
  },
  {
    "path": "docs/userguide/input-tables/Fulldom_hires.tsv",
    "content": "VariableName\tDimensions\tDescription\tUnits\tNotes\r\nTOPOGRAPHY\tRouting grid\tTerrain grid or Digital Elevation Model (DEM).\tm\r\nFLOWDIRECTION\tRouting grid\tFlow direction grid, which explicitly defines flow directions along the channel network in gridded routing. This variable dictates where water flows into channels from the land surface as well as in the channel.\tcategorical\r\nFLOWACC\tRouting grid\tNumber of upstream cells that drain into each cell.\tcount\r\nCHANNELGRID\tRouting grid\tChannel network grid identifying the location of stream channel grid cells (-9999=no channel, -1=deactivated channel, 0=active channel)\tcategorical\r\nSTREAMORDER\tRouting grid\tStrahler stream order grid identifying the stream order for all channel pixels within the channel network.\tcategorical\r\nLKSATFAC\tRouting grid\tMultiplier on saturated hydraulic conductivity in lateral flow direction.\tdimensionless\r\nRETDEPRTFAC\tRouting grid\tMultiplier on maximum retention depth before flow is routed as overland flow.\tdimensionless\r\nOVROUGHRTFAC\tRouting grid\tMultiplier on Manning's roughness for overland flow.\tdimensionless\r\nfrxst_pts\tRouting grid\tPrescribed forecast points\tindex\r\nbasn_msk\tRouting grid\tPrescribed basin masks\tindex\r\nLAKEGRID\tRouting grid\tPrescribed lakes\tindex\r\nlanduse\tRouting grid\tLand use from geogrid regridded to the high-res routing grid\tcategorical"
  },
  {
    "path": "docs/userguide/input-tables/geo_em.tsv",
    "content": "VariableName\tDimensions\tDescription\tUnits\tNotes\r\nLU_INDEX\tLSM grid\tLand cover type\tCategorical\tHydro routing code uses this variable to define land cover type. The classification scheme is determined by the global attribute MMINLU and ISURBAN, ISWATER, and ISOILWATER are used to define special types. See MPTABLE.TBL for NoahMP-supported land cover classification schemes.\r\nSCT_DOM\tLSM grid\tDominant top layer soil texture class\tCategorical\tHydro routing code uses this variable to define soil type (texture class). Currently there is only one texture class defined per cell (not variable with depth). See SOILPARM.TBL for the supported texture classes.\r\nHGT_M\tLSM grid\tElevation\tm\tNot used by the model but useful for reference."
  },
  {
    "path": "docs/userguide/input-tables/wrfinput.tsv",
    "content": "VariableName\tDimensions\tDescription\tUnits\tNotes\r\nSMOIS\tLSM grid, soil layers\tInitial volumetric soil moisture content\tm3/m3\r\nTSLB\tLSM grid, soil layers\tInitial soil temperature\tK\r\nSNOW\tLSM grid\tInitial snow water equivalent\tmm (kg/m2)\r\nCANWAT\tLSM grid\tInitial canopy water storage\tmm (kg/m2)\r\nTSK\tLSM grid\tInitial surface temperature\tK\tUsed to initialize model temperatures other than soil, e.g., canopy leaf and air temperature\r\nLAI\tLSM grid\tInitial leaf area index\tm2/m2\tOnly used by certain NoahMP settings\r\nIVGTYP\tLSM grid\tLand cover type\tCategorical\tLSM uses this variable to define land cover type. The classification scheme is determined by the global attribute MMINLU and ISURBAN, ISWATER, and ISICE are used to define special types. See MPTABLE.TBL for NoahMP-supported land cover classification schemes.\r\nISLTYP\tLSM grid\tSoil texture class\tCategorical\tLSM uses this variable to define soil type (texture class). Currently there is only one texture class defined per cell (not variable with depth). See SOILPARM.TBL for the supported texture classes.\r\nTMN\tLSM grid\tConstant deep ­soil temperature\tK\tUsed as fixed lower boundary temperature for TBOT_OPTION=2\r\nSHDMAX\tLSM grid\tMaximum annual vegetation fraction\t% (0-100)\tOnly used by certain NoahMP settings\r\nSHDMIN\tLSM grid\tMinimum annual vegetation fraction\t% (0-100)\tOnly used by certain NoahMP settings\r\nSEAICE\tLSM grid\tPresence of sea ice\tfraction\tSet to 0; if >0, model will skip execution\r\nXLAND\tLSM grid\tLand/water mask (1=land, 2=water)\tcategorical\tSet to 1 for land points; if =2, model will skip execution\r\nHGT\tLSM grid\tElevation\tm\tNot used by the model but useful for reference."
  },
  {
    "path": "docs/userguide/introduction.rest",
    "content": ".. vim: syntax=rst\n.. include:: meta.rest\n\n1. Introduction\n===============\n\nThe purpose of this technical note is to describe the physical\nparameterizations, numerical implementation, coding conventions and\nsoftware architecture for the NCAR Weather Research and Forecasting\nmodel (WRF) hydrological modeling system, hereafter referred to as\nWRF-Hydro. The system is intended to be flexible and extensible and\nusers are encouraged to develop, add and improve components to meet\ntheir application needs.\n\nIt is critical to understand that like the WRF atmospheric modeling\nsystem, the WRF-Hydro modeling system is not a singular 'model' per se\nbut instead it is a modeling architecture that facilitates coupling of\nmultiple alternative hydrological process representations. There are\nnumerous (over 100) different configuration permutations possible in\nWRF-Hydro Version |version_short|. Users need to become familiar with the concepts\nbehind the processes within the various model options in order to\noptimally tailor the system for their particular research and\napplication activities.\n\n1.1 Brief History\n-----------------\n\nThe WRF-Hydro modeling system provides a means to couple hydrological\nmodel components to atmospheric models and other Earth System modeling\narchitectures. The system is intended to be extensible and is built upon\na modular Modern Fortran architecture. The code has also been parallelized\nfor distributed memory parallel computing applications. Numerous options\nfor terrestrial hydrologic routing physics are contained within Version\n|version_short| of WRF-Hydro but users are encouraged to add additional components\nto meet their research and application needs. The initial version of\nWRF-Hydro (originally called 'Noah-distributed' in 2003) included a\ndistributed, 3-dimensional, variably-saturated surface and subsurface\nflow model previously referred to as 'Noah-distributed' for the\nunderlying land surface model upon which the original code was based.\nInitially, the implementation of terrain routing and, subsequently,\nchannel and reservoir routing functions into the 1-dimensional Noah land\nsurface model was motivated by the need to account for increased\ncomplexity in land surface states and fluxes and to provide\nphysically-consistent land surface flux and stream channel discharge\ninformation for hydrometeorological applications. The original\nimplementation of the surface overland flow and subsurface saturated\nflow modules into the Noah land surface model are described by Gochis\nand Chen (2003). In that work, a simple subgrid\ndisaggregation-aggregation procedure was employed as a means of mapping\nland surface hydrological conditions from a “coarsely” resolved land\nsurface model grid to a much more finely resolved terrain routing grid\ncapable of adequately resolving the dominant local landscape gradient\nfeatures responsible for the gravitational redistribution of terrestrial\nmoisture. Since then numerous improvements to the Noah-distributed model\nhave occurred including optional selection for 2-dimensional (in `x` and\n`y`) or 1-dimensional (“steepest descent” or so-called “D8” methodologies)\nterrain routing, a 1-dimensional, grid-based, hydraulic routing model, a\nreservoir routing model, 2 reach-based hydrologic channel routing\nmodels, and a simple empirical baseflow estimation routine. In 2004, the\nentire modeling system, then referred to as the NCAR WRF-Hydro\nhydrological modeling extension package was coupled to the Weather\nResearch and Forecasting (WRF) mesoscale meteorological model (*Skamarock\net al., 2005*) thereby permitting a physics-based, fully coupled land\nsurface hydrology-regional atmospheric modeling capability for use in\nhydrometeorological and hydroclimatological research and applications.\nThe code has since been fully parallelized for high-performance\ncomputing applications. During late 2011 and 2012, the WRF-Hydro code\nunderwent a major reconfiguration of its coding structures to facilitate\ngreater and easier extensibility and upgradability with respect to the\nWRF model, other hydrological modeling components, and other Earth\nsystem modeling frameworks. Additional changes to the\ndirectory structure occurred during 2014-2015 to accommodate the\ncoupling with the new Noah-MP land modeling system. Between 2015-2018,\nnew capabilities were added to permit more generalized, user-defined\nmapping onto irregular objects, such as catchments or hydrologic\nresponse units. During 2018-2022, some of the modules underwent\na code refactoring and automated testing capabilities were added.\nIn 2024, the directory structure was again updated for consistency with modern\nsoftware design practices and this user guide was ported to an interactive\nonline format. As additional changes and enhancements to WRF-Hydro \noccur they will be documented in future versions of this document.\n\n1.2 Model Description\n------------------------\n\nWRF-Hydro has been developed to facilitate improved representations of\nterrestrial hydrologic processes related to the spatial redistribution\nof surface, subsurface and channel waters across the land surface and to\nfacilitate coupling of hydrologic models with atmospheric models.\nSwitch-activated modules in WRF-Hydro enable treatment of terrestrial\nhydrological physics, which have either been created or have been\nadapted from existing distributed hydrological models. The conceptual\narchitecture for WRF-Hydro is shown in Figures 1.1 and 1.2 where\nWRF-Hydro exists as a coupling architecture (blue box) or “middle-ware”\nlayer between weather and climate models and terrestrial hydrologic\nmodels and land data assimilation systems. WRF-Hydro can also operate in\na standalone mode as a traditional land surface hydrologic modeling\nsystem.\n\n.. _figure-1.1:\n.. figure:: media/conceptual_diagram_wrfhydro.png\n   :align: center\n   :scale: 80%\n\n   **Figure 1.1.** Generalized conceptual schematic of the WRF-Hydro\n   architecture showing various categories of model components.\n\n.. figure:: media/coupling_schematic.png\n   :align: center\n   :scale: 80%\n\n   **Figure 1.2.** Model schematic illustrating where many existing\n   atmosphere, land surface and hydrological model components *could* fit\n   into the WRF-Hydro architecture. NOTE: Not all of these models are\n   currently coupled into WRF-Hydro at this time. This schematic is meant\n   to be illustrative. Components which are coupled have an asterisk (\\*)\n   by their name.\n\nWRF-Hydro is designed to enable improved simulation of land surface\nhydrology and energy states and fluxes at a fairly high spatial\nresolution (typically 1 km or less) using a variety of physics-based and\nconceptual approaches. As such, it is intended to be used as either a\nland surface model in both standalone (“uncoupled” or “offline”) mode\nand fully-coupled (to an atmospheric model) mode. Both time-evolving\n“forcing” and static input datasets are required for model operation.\nThe exact specification of both forcing and static data depends greatly\non the selection of model physics and component options to be used. The\nprincipal model physics options in WRF-Hydro include:\n\n-  1-dimensional (vertical) land surface parameterization\n\n-  surface overland flow\n\n-  saturated subsurface flow\n\n-  channel routing\n\n-  reservoir routing\n\n-  conceptual/empirical baseflow\n\nBoth the Noah land surface and Noah-MP land surface model options are\navailable for use in the current version of the WRF-Hydro. The rest of\nthis document will focus on their implementation. Future versions will\ninclude other land surface model options.\n\nLike nearly all current land surface models, the Noah and Noah-MP land\nsurface parameterizations require a few basic meteorological forcing\nvariables. Required meteorological forcing variables are listed in Table\n1.1.\n\n.. table:: **Table 1.1** Required input meteorological forcing variables for the\n           Noah and Noah-MP LSMs\n   :width: 90%\n   :align: center\n\n   +----------------------------------------+-----------+\n   | **Variable**                           | **Units** |\n   +========================================+===========+\n   | Incoming shortwave radiation           | `W/m^2`   |\n   +----------------------------------------+-----------+\n   | Incoming longwave radiation            | `W/m^2`   |\n   +----------------------------------------+-----------+\n   | Specific humidity                      | `kg/kg`   |\n   +----------------------------------------+-----------+\n   | Air temperature                        | `K`       |\n   +----------------------------------------+-----------+\n   | Surface pressure                       | `Pa`      |\n   +----------------------------------------+-----------+\n   | Near surface wind in the u - component | `m/s`     |\n   +----------------------------------------+-----------+\n   | Near surface wind in the v-component   | `m/s`     |\n   +----------------------------------------+-----------+\n   | Liquid water precipitation rate        | `mm/s`    |\n   +----------------------------------------+-----------+\n\n*[Different land surface models may require other or additional forcing\nvariables or the specification of forcing variables in different units.]*\n\nWhen coupled to the WRF regional atmospheric model the meteorological\nforcing data is provided by the atmospheric model with a frequency\ndictated by the land surface model time-step specified in WRF. When run\nin a standalone mode, meteorological forcing data must be provided as\ngridded input time series. Further details on the preparation of forcing\ndata for standalone WRF-Hydro execution is provided in :ref:`section-5.7`\n\nExternal, third party, Geographic Information System (GIS) tools are\nused to delineate a stream channel network, open water (i.e., lake,\nreservoir, and ocean) grid cells and groundwater/baseflow basins. Water\nfeatures are mapped onto the high-resolution terrain-routing grid and\npost-hoc consistency checks are performed to ensure consistency between\nthe coarse-resolution Noah/Noah-MP land model grid and the fine-resolution \nterrain and channel routing grid.\n\nThe WRF-Hydro model components calculate fluxes of energy and moisture\neither back to the atmosphere or also, in the case of moisture fluxes,\nto stream and river channels and through reservoirs. Depending on the\nphysics options selected, the primary output variables include but are\nnot limited to those in the table below. Output variables and options\nare discussed in detail in :ref:`section-6.0`\n\n.. table:: **Table 1.2** Primary Output data from WRF-Hydro\n   :width: 90%\n   :align: center\n\n   +-----------------------------------------------------------+------------+\n   | **Variable**                                              | **Units**  |\n   +===========================================================+============+\n   | Surface latent heat flux                                  | `W/m^2`    |\n   +-----------------------------------------------------------+------------+\n   | Surface sensible heat flux                                | `W/m^2`    |\n   +-----------------------------------------------------------+------------+\n   | Ground heat flux                                          | `W/m^2`    |\n   +-----------------------------------------------------------+------------+\n   | Ground surface and/or canopy skin temperature             | `K`        |\n   +-----------------------------------------------------------+------------+\n   | Surface evaporation components (soil evaporation,         | `kg/m^2/s` |\n   | transpiration, canopy water evaporation, snow sublimation |            |\n   | and ponded water evaporation)                             |            |\n   +-----------------------------------------------------------+------------+\n   | Soil moisture                                             | `m^3/m^3`  |\n   +-----------------------------------------------------------+------------+\n   | Soil temperature                                          | `K`        |\n   +-----------------------------------------------------------+------------+\n   | Deep soil drainage                                        | `mm`       |\n   +-----------------------------------------------------------+------------+\n   | Surface runoff                                            | `mm`       |\n   +-----------------------------------------------------------+------------+\n   | Canopy moisture content                                   | `mm`       |\n   +-----------------------------------------------------------+------------+\n   | Snow depth                                                | `m`        |\n   +-----------------------------------------------------------+------------+\n   | Snow liquid water equivalent                              | `mm`       |\n   +-----------------------------------------------------------+------------+\n   | Stream channel inflow (optional with terrain routing)     | `mm`       |\n   +-----------------------------------------------------------+------------+\n   | Channel flow rate (optional with channel routing)         | `m^3/s`    |\n   +-----------------------------------------------------------+------------+\n   | Channel flow depth (optional with channel routing)        | `mm`       |\n   +-----------------------------------------------------------+------------+\n   | Reservoir height and discharge (optional with channel and | `m` and    |\n   | reservoir routing)                                        | `m^3/s`    |\n   +-----------------------------------------------------------+------------+\n\nWRF-Hydro has been developed for Linux-based operating systems including\nsmall local clusters and high-performance computing systems.\nAdditionally, the model code has also been ported to a selection of\nvirtual machine environments (e.g. \"containers\") to enable the use of\nsmall domain cases on many common desktop computing platforms (e.g.\nWindows and MacOS) and in the cloud. The parallel computing schema is provided in\n:ref:`section-2.3`. WRF-Hydro utilizes a combination of netCDF and flat\nASCII file formats.\n\nThe majority of input and output is handled using the netCDF data format\nand the netCDF library is a requirement for running the model. Details on the\nsoftware requirements are available online on the FAQs page of the\nwebsite as well as in the *How To Build & Run WRF-Hydro V5 in Standalone\nMode* document also available from\nhttps://ral.ucar.edu/projects/wrf_hydro.\n\nWRF-Hydro is typically set up as a computationally-intensive modeling\nsystem. Simple small domains (e.g. 16 `km^2`) can be configured to\nrun on a desktop platform. Large-domain model runs can require hundreds\nor thousands of processors. We recommend beginning with an example “test\ncase” we supply at the WRF-Hydro website\nhttps://ral.ucar.edu/projects/wrf_hydro before moving to your region of\ninterest, particularly if your region or domain is reasonably large.\n"
  },
  {
    "path": "docs/userguide/meta.rest",
    "content": ".. |version_short| replace:: 5.4\n.. |version_long| replace:: 5.4.0\n\n.. role:: center\n    :class: center\n\n.. role:: underline\n    :class: underline\n\n.. role:: file\n    :class: filename\n\n.. role:: program\n    :class: program\n\n.. role:: output\n    :class: filename"
  },
  {
    "path": "docs/userguide/model-code-config.rest",
    "content": ".. vim: syntax=rst\n.. include:: meta.rest\n\n2. Model Code and Configuration Description\n===========================================\n\nThis chapter presents the technical description of the WRF-Hydro model\ncode. The chapter is divided into the following sections:\n\n2.1 Brief Code Overview\n-----------------------\n\nWRF-Hydro is written in a modularized, modern Fortran coding structure whose\nrouting physics modules are switch-activated through a model namelist\nfile called :ref:`hydro.namelist <hydro-namelist>`. The code has been\nparallelized for execution on high-performance, parallel computing\narchitectures including Linux operating system commodity clusters and\nmulti-processor desktops as well as multiple supercomputers. More detailed model\nrequirements depend on the choice of model driver, described in the next section.\n\n2.2 Driver Level Description\n----------------------------\n\nWRF-Hydro is essentially a group of modules and functions which handle\nthe communication of information between atmosphere components (such as\nWRF, CESM or prescribed meteorological analyses) and sets of land\nsurface hydrology components. From a coding perspective the WRF-hydro\nsystem can be called from an existing architecture such as the WRF\nmodel, the CESM, NASA LIS, etc. or can run in a standalone mode with its\nown driver which has adapted part of the NCAR High Resolution Land Data\nAssimilation System (HRLDAS). Each new coupling effort requires some\nbasic modifications to a general set of functions to manage the\ncoupling. In WRF-Hydro, each new system that WRF-Hydro is coupled into\ngets assigned to a directory indicating the name of the coupling\ncomponent WRF-Hydro is coupled to. For instance, the code which handles\nthe coupling to the WRF model is contained in the :file:`WRF_cpl/` directory in\nthe WRF-Hydro system. Similarly, the code which handles the coupling to\nthe offline Noah land surface modeling system is contained within the\n:file:`Noah_cpl/` directory and so on. Description of each directory is\nprovided in :ref:`section-2.4`.\n\nThe coupling structure is illustrated here, briefly, in terms of the\ncoupling of WRF-Hydro into the WRF model. A similar approach is used for\ncoupling the WRF-Hydro extension package into other modeling systems or\nfor coupling other modeling systems into WRF-Hydro.\n\n    *Example:* For coupled WRF/WRF-Hydro runs the WRF-Hydro components are\n    compiled as a single library function call with the WRF system. As such,\n    a single executable is created upon compilation (:program:`wrf`). As\n    illustrated in :ref:`Figure 2.1 <figure2.1>`, WRF-hydro is called directly\n    from WRF in the WRF surface driver module (:file:`phys/module_surface_driver.F90`).\n    The code that manages the communication is the :file:`WRF_drv_Hydro.F90`\n    interface module that is contained within the :file:`WRF_cpl/` directory.\n    The :file:`WRF_drv_Hydro.F90` interface module is the specific instance of\n    a 'General WRF-Hydro Coupling Interface' for the WRF model which passes data,\n    grid and time information between WRF and WRF-Hydro. Components within\n    WRF-Hydro then manage the dynamic regridding “data mapping” and sub-component\n    routing functions (e.g. surface, subsurface and/or channel routing) within\n    WRF-Hydro (see :ref:`Fig. 1.1 <figure-1.1>` for an illustration of components\n    contained within WRF-Hydro).\n\nUpon completion of the user-specified routing functions, WRF-Hydro will\nremap the data back to the WRF model grid and then pass the necessary\nvariables back to the WRF model through the :file:`WRF_drv_Hydro.F90` interface\nmodule. Therefore, the key component of the WRF-Hydro system is the\nproper construction of the :file:`WRF_cpl_Hydro` interface module (or more\ngenerally :file:`{XXX}_cpl_Hydro`). Users wishing to couple new modules to\nWRF-Hydro will need to create a unique “General WRF-Hydro Coupling\nInterface” for their components. Some additional examples of this\ninterface module are available upon request for users to build new\ncoupling components. This simple coupling interface is similar in\nstructure to other general model coupling interfaces such as those\nwithin the Earth System Modeling Framework (ESMF) or the Community\nSurface Dynamics Modeling System (CSDMS).\n\n.. _figure2.1:\n.. figure:: media/wrf_coupling.png\n    :align: center\n\n    **Figure 2.1** Schematic illustrating the coupling and calling structure\n    of WRF-Hydro from the WRF Model.\n\nThe model code has been compiled using the Intel :program:`ifort` compiler and\nthe freely-available GNU Fortran compiler :program:`gfortran` for use with\nUnix-type operating systems on desktops, clusters, and supercomputing\nsystems. Because the WRF-Hydro modeling system relies on netCDF input and\noutput file conventions, netCDF Fortran libraries must be installed and\nproperly compiled on the system upon which WRF-Hydro is to be executed.\nNot doing so will result in numerous error messages such as :code:`*…undefined\nreference to netCDF library …*`  or similar messages upon compilation.\nFor further installation requirements see the FAQs page of the website\nas well asin the *How To Build & Run WRF-Hydro v5 in Standalone Mode* document\nalso available from https://ral.ucar.edu/projects/wrf_hydro.\n\n.. _section-2.3:\n\n2.3 Parallelization strategy\n----------------------------\n\nParallelization of the WRF-Hydro code utilizes geographic domain\ndecomposition and 'halo' array passing structures similar to those used\nin the WRF atmospheric model (:ref:`Figures 2.2 <figure2.2>` and :ref:`2.3 <figure2.3>`).\nMessage passing between processors is accomplished using MPI protocols. Therefore the\nrelevant MPI libraries must be installed and properly compiled on the\nsystem upon which WRF-Hydro is to be executed in parallel mode.\nCurrently sequential compile is not supported so MPI libraries are\nrequired even if running over a single core.\n\n.. figure:: media/gridded_decomp.png\n    :align: center\n    :name: figure2.2\n\n    **Figure 2.2** Schematic of parallel domain decomposition scheme in\n    WRF-Hydro. Boundary or 'halo' arrays in which memory is shared between\n    processors (P1 and P2) are shaded in purple.\n\n.. figure:: media/channel_decomp.png\n    :align: center\n    :name: figure2.3\n\n    **Figure 2.3** Schematic of parallel domain decomposition scheme in\n    WRF-Hydro as applied to channel routing. Channel elements (stars) are\n    communicated at boundaries via ‘halo’ arrays in which memory is shared\n    between processors (P1 and P2). Black and red stars indicate overlapping\n    channel elements used in the diffusive wave solver.\n\n.. _section-2.4:\n\n2.4 Directory Structures\n------------------------\n\nThe top-level directory structure of the code is provided below as\nnested under the :file:`wrf_hydro_nwm_public` root directory and the\nsubdirectory structures are described thereafter. The tables below provide\nbrief descriptions of the file contents of each directory where the model code\nresides.\n\n.. default-role:: file\n\n.. table:: **Table 2.1** Description of the file contents of each directory\n           where the model *code* resides\n   :align: center\n   :width: 90%\n   :name: table-2.1\n\n   +-------------------------+--------------------------------------------------+\n   | **File/directory name** | **Description**                                  |\n   |                         |                                                  |\n   +=========================+==================================================+\n   | Main code files and directories (under version control in                  |\n   | a GitHub repository):                                                      |\n   +-------------------------+--------------------------------------------------+\n   | :underline:`Top-Level Files and Directories:`                              |\n   +-------------------------+--------------------------------------------------+\n   | `CMakeLists.txt`        | Top-level CMake build script used to compile     |\n   |                         | the WRF-Hydro model                              |\n   +-------------------------+--------------------------------------------------+\n   | `docs/`                 | Pointer to location of full documentation (i.e.  |\n   |                         | this document).                                  |\n   +-------------------------+--------------------------------------------------+\n   | `tests/`                | Scripts and data used to test the model          |\n   +-------------------------+--------------------------------------------------+\n   | `src/`                  | WRF-Hydro Model source code                      |\n   +-------------------------+--------------------------------------------------+\n   | :underline:`Source code directories under \\`src/\\`:`                       |\n   +-------------------------+--------------------------------------------------+\n   | `CPL/Noah_cpl/`         | Contains the WRF-Hydro coupling interface for    |\n   |                         | coupling WRF-Hydro components with the           |\n   |                         | standalone (offline) Noah land surface model     |\n   |                         | data assimilation and forecasting system         |\n   +-------------------------+--------------------------------------------------+\n   | `CPL/NoahMP_cpl/`       | Contains the WRF-Hydro coupling interface for    |\n   |                         | coupling WRF-Hydro components with the           |\n   |                         | standalone (offline) Noah-MP land surface model  |\n   |                         | data assimilation and forecasting system         |\n   +-------------------------+--------------------------------------------------+\n   | `CPL/WRF_cpl/`          | Contains the WRF-Hydro coupling interface for    |\n   |                         | coupling WRF-Hydro components with the WRF       |\n   |                         | system                                           |\n   +-------------------------+--------------------------------------------------+\n   | `CPL/CLM_cpl/`  ,       | Work in progress for ongoing coupling work.      |\n   | `CPL/LIS_cpl/`  ,       | Only NUOPC is actively supported.                |\n   | `CPL/NUOPC_cpl/`        |                                                  |\n   +-------------------------+--------------------------------------------------+\n   | `Data_Rec/`             | Contains some data declaration modules           |\n   +-------------------------+--------------------------------------------------+\n   | `Debug_Utilities/`      | Utilities for debugging                          |\n   +-------------------------+--------------------------------------------------+\n   | `deprecated/`           | Contains files not currently used                |\n   +-------------------------+--------------------------------------------------+\n   | `HYDRO_drv/`            | Contains the high-level WRF-Hydro component      |\n   |                         | driver: `module_HYDRO_drv.F90`                   |\n   +-------------------------+--------------------------------------------------+\n   | `Land_models/Noah/`     | Contains the Noah land surface model driver for  |\n   |                         | standalone or uncoupled applications             |\n   +-------------------------+--------------------------------------------------+\n   | `Land_models/NoahMP/`   | Contains the Noah-MP land surface model driver   |\n   |                         | for standalone or uncoupled applications         |\n   +-------------------------+--------------------------------------------------+\n   | `MPP/`                  | Contains MPI parallelization routines and        |\n   |                         | functions                                        |\n   +-------------------------+--------------------------------------------------+\n   | `nudging/`              | Contains nudging data assimilation routines and  |\n   |                         | functions                                        |\n   +-------------------------+--------------------------------------------------+\n   | `Rapid_routing/`        | Contains the files necessary for RAPID routing   |\n   |                         | model coupling. Unsupported as version of RAPID  |\n   |                         | is out of date.                                  |\n   +-------------------------+--------------------------------------------------+\n   | `Routing/`              | Contains modules and drivers related to specific |\n   |                         | routing processes in WRF-Hydro                   |\n   +-------------------------+--------------------------------------------------+\n   | `template/`             | Contains example namelist files for Noah,        |\n   |                         | Noah-MP and the WRF-Hydro modules (HYDRO).       |\n   |                         | Default and example parameter tables are also    |\n   |                         | included for HYDRO. Note: Parameter tables for   |\n   |                         | Noah and Noah-MP are stored within the           |\n   |                         | :file:`Land_models` directory.                   |\n   +-------------------------+--------------------------------------------------+\n   | `utils/`                | internal model versioning                        |\n   +-------------------------+--------------------------------------------------+\n   | :underline:`Files:`                                                        |\n   +-------------------------+--------------------------------------------------+\n   | `docs/BUILD.md`         | WRF-Hydro build instructions for the standalone  |\n   |                         | model                                            |\n   +-------------------------+--------------------------------------------------+\n   | `wrf_hydro_config`      | Configure script for coupled WRF \\| WRF-Hydro    |\n   |                         | configuration                                    |\n   +-------------------------+--------------------------------------------------+\n   | `\\*.json`               | JSON files used for testing                      |\n   +-------------------------+--------------------------------------------------+\n   | Local files and directories created by CMake in the build directory        |\n   | (not part of the  version controlled repository):                          |\n   +-------------------------+--------------------------------------------------+\n   | :underline:`Directories:`                                                  |\n   +-------------------------+--------------------------------------------------+\n   | `lib/`                  | Directory where compiled libraries are written   |\n   +-------------------------+--------------------------------------------------+\n   | `mods/`                 | Directory where compiled `.mod`` files are       |\n   |                         | written upon compilation                         |\n   +-------------------------+--------------------------------------------------+\n   | `Run/`                  | Directory where model executable, example        |\n   |                         | parameter tables, and example namelist files     |\n   |                         | for the compiled model configuration will be     |\n   |                         | populated. These files will be overwritten on    |\n   |                         | compile. It is recommended the user copy the     |\n   |                         | contents of this directory into an alternate     |\n   |                         | location, separate from the code, to execute     |\n   |                         | model runs.                                      |\n   +-------------------------+--------------------------------------------------+\n\n.. table:: **Table 2.2** Modules within the :file:`Routing/` directory which relate to\n           routing processes in WRF-Hydro\n   :width: 90%\n   :align: center\n   :name: table-2.2\n\n   +--------------------------------------+-------------------------------------------------+\n   | **File/directory name**              | **Description**                                 |\n   |                                      |                                                 |\n   +======================================+=================================================+\n   | `Overland/`                          | Directory containing overland routing modules   |\n   +--------------------------------------+-------------------------------------------------+\n   | `Makefile`                           | Makefile for WRF-Hydro component                |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_channel_routing.F90`         | Module containing WRF-Hydro channel routing     |\n   |                                      | components                                      |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_date_utilities_rt.F90`       | Module containing various date/time utilities   |\n   |                                      | for routing routines                            |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_GW_baseflow.F90`             | Module containing model physics for simple      |\n   |                                      | baseflow model                                  |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_HYDRO_io.F90`                | Module containing WRF-Hydro input and (some)    |\n   |                                      | output functions                                |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_HYDRO_utils.F90`             | Module containing several WRF-Hydro utilities   |\n   |                                      |                                                 |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_lsm_forcing.F90`             | Module containing the options for reading in    |\n   |                                      | different forcing data types                    |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_noah_chan_param_init_rt.F90` | Module containing routines to initialize        |\n   |                                      | WRF-Hydro routing grids                         |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_NWM_io.F90`                  | Module containing output routines to produce    |\n   |                                      | CF-compliant desired output files.              |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_NWM_io_dict.F90`             | Dictionary to support CF-compliant output       |\n   |                                      | routines.                                       |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_RT.F90`                      | Module containing the calls to all the          |\n   |                                      | WRF-Hydro routing initialization                |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_UDMAP.F90`                   | Module for the user-defined mapping             |\n   |                                      | capabilities, currently used for NWM            |\n   |                                      | configuration (NHDPlus network)                 |\n   +--------------------------------------+-------------------------------------------------+\n   | `Noah_distr_routing.F90`             | Module containing overland flow and subsurface  |\n   |                                      | physics routines and grid disaggregation        |\n   |                                      | routine                                         |\n   +--------------------------------------+-------------------------------------------------+\n   | `module_gw_gw2d.F90`                 | Module containing routines for the experimental |\n   |                                      | 2D groundwater model                            |\n   +--------------------------------------+-------------------------------------------------+\n\n.. default-role::\n\n2.5 Model Sequence of Operations\n--------------------------------\n\nThe basic structure and sequencing of WRF-Hydro are diagrammatically\nillustrated in :ref:`Figure 2.4 <figure2.4>` management, initialization,\nI/O and model completion) is handled by the WRF-Hydro system unless\nWRF-Hydro is coupled into, and beneath, a different modeling architecture.\nThe WRF-Hydro system can either call an independent land model driver such\nas the NCAR High Resolution Land Data Assimilation System (HRLDAS) for\nboth Noah and Noah-MP land surface models to execute column land surface\nphysics or be called by a different modeling architecture such as WRF,\nthe NCAR CESM, or the NASA LIS. When run in a standalone or “uncoupled”\nmode, WRF-Hydro must read in the meteorological forcing data necessary to\nperform land surfac model calculations and it contains the necessary\nroutines to do this. When run in a coupled mode with WRF or another larger\narchitecture, WRF-Hydro receives meteorological forcing or land surface\nstates and fluxes from the parent architecture. The basic execution\nprocess is as follows:\n\n   1.  Upon initialization static land surface physiographic data are read\n       into the WRF-Hydro system and the model domain and computational\n       arrays are established.\n\n   2.  Depending on whether or not WRF-Hydro is run offline as a standalone\n       system or whether it is coupled into another architecture, either\n       forcing data is read in or land surface states and fluxes are passed\n       in.\n\n   3.  For offline simulations which require land model execution, the\n       gridded column land surface model is executed.\n\n   4.  If routing is activated and there is a difference between the land\n       model grid and the routing grid, land surface states and fluxes are\n       then disaggregated to the high-resolution terrain routing grids.\n\n   5.  If activated, sub-surface routing physics are executed.\n\n   6.  If activated, surface routing physics are executed.\n\n   7.  If activated, the conceptual base flow model is executed.\n\n   8.  If activated, channel and reservoir routing components are executed.\n       Streamflow nudging is currently available to be applied within the\n       Muskingum-Cunge routing call.\n\n   9.  Updated land surface states and fluxes are then aggregated from the\n       high-resolution terrain routing grid to the land surface model grid\n       (if routing is activated and there is a difference between the land\n       model grid and the routing grid).\n\n   10. Results from these integrations are then written to the model output\n       files and restart files or, in the case of a coupled WRF/WRF-Hydro\n       simulation, passed back to the WRF model.\n\nAs illustrated at the bottom of the :ref:`Figure 2.4 <figure2.4>`\ncomponent with `NCAR’s DART <https://www.image.ucar.edu/DAReS/DART/>`__\n(https://www.image.ucar.edu/DAReS/DART/) has been developed. This\ncurrently only works with WRF-Hydro in standalone mode. DART updates\nWRF-Hydro states independently of model time integration.\n\n.. _figure2.4:\n.. figure:: media/modular_calling.png\n    :align: center\n\n    **Figure 2.4** Modular calling structure of WRF-Hydro.\n\n2.6 WRF-Hydro compile-time options\n----------------------------------\n\nCompile time options are choices about the model structure which are\ndetermined when the model is compiled. Compile time choices select a\nWRF-Hydro instance from some of the options illustrated in\n:ref:`Figure 2.4. <figure2.4>` Compile time options fall into two\ncategories: 1) the selected model driver, and 2) the compile options\nfor the choice of driver. In this guide we limit the description of\nmodel drivers to WRF, Noah, and Noah-MP. Configuring, compiling, and\nrunning WRF-Hydro in standalone mode is described in detail in the\n*How To Build & Run WRF-Hydro V5 in Standalone Mode* document available\nfrom https://ral.ucar.edu/projects/wrf_hydro.\n\nCompile-time options are listed during the CMake build configuration\nprocess. These options are passed to CMake as environment variables\nusing ``-D[OPTION]=[0|1]`` syntax. Those options/variables are listed\nbelow along with a description of what each option does:\n\n.. parsed-literal::\n\n   ===================================================================\n   -- Start of WRF-Hydro Env VARIABLES\n   WRF_HYDRO = 1                        *Always set to 1 for WRF-Hydro*\n\n   HYDRO_D = 0                *Set to 1 for enhanced diagnostic output*\n\n   SPATIAL_SOIL = 1               *Set to 1 to allow NoahMP LSM to use*\n                                    *spatially distributed parameter*\n                                  *vs. a table based on soil class and*\n                                                  *land use categories*\n\n   WRFIO_NCD_LARGE_FILE_SUPPORT = 0               *Set to 1 if using a*\n                                          *WRF/WRF-Hydro coupled build*\n\n   NCEP_WCOSS = 0                  *Set to 1 if compile for NOAA WCOSS*\n\n   NWM_META = 0        *Set to 1 if using NWM-style metadata in output*\n\n   WRF_HYDRO_NUDGING = 0         *Set to 1 if using streamflow nudging*\n\n   PRECIP_DOUBLE = 0                  *Set to 1 to double all incoming*\n                              *precipitation (for debug purposes only)*\n\n   WRF_HYDRO_NUOPC = 0             *Set to 1 when using NUOPC coupling*\n   ===================================================================\n\n.. _section-2.7:\n\n2.7 WRF-Hydro run time options\n------------------------------------\n\nThere are two namelist files that users must edit in order to\nsuccessfully execute the WRF-Hydro system in a standalone mode or\n“uncoupled” to WRF. One of these namelist files is the hydro.namelist\nfile and in it are the various settings for operating all of the routing\ncomponents of the WRF-Hydro system. The hydro.namelist file is\ninternally commented so that it should be clear as to what is needed for\neach setting. A full annotated example of the hydro.namelist file is\nprovided in :ref:`section-a6`.\n\nThe second namelist is the namelist which specifies the land surface\nmodel options to be used. This namelist can change depending on which\nland model is to be used in conjunction with the WRF-Hydro routing\ncomponents. For example, a user would use one namelist when running the\nNoah land surface model coupled to WRF-Hydro but that user would need to\nuse a different namelist file when running the CLM model, the Noah-MP\nmodel or NASA LIS model coupled to WRF-Hydro. The reason for this is\nWRF-Hydro is intended to be *minimally-invasive* to other land surface\nmodels or land model driver structures and not require significant\nchanges to those systems. This minimal invasiveness facilitates easier\ncoupling with new systems and helps facilitate easy supportability and\nversion control with those systems. When the standalone WRF-Hydro model\nis compiled the appropriate namelist.hrldas template file is copied over\nto the Run directory based upon the specified land surface model.\n\nIn WRF-Hydro v\\ |version_short|, Noah and Noah-MP land surface models are the main\nland surface model options when WRF-Hydro is run in standalone mode.\nBoth Noah and Noah-MP use a namelist file called namelist.hrldas, which,\nas noted above, will contain different settings for the two different\nland surface models. For a run where WRF-Hydro is coupled to the WRF\nmodel, the WRF model input file namelist.input becomes the second\nnamelist file. Full annotated example namelist.hrldas files for Noah and\nNoah-MP are provided in :ref:`section-a4` and :ref:`section-a5`.\n\n.. _section-2.8:\n\n2.8 Build Instructions\n------------------------------------\n.. include:: ../BUILD.rst\n   :start-line: 2\n"
  },
  {
    "path": "docs/userguide/model-inputs-preproc.rest",
    "content": ".. vim: syntax=rst\n.. include:: meta.rest\n\n5. Model inputs and preprocessing\n=================================\n\nThis chapter describes WRF-Hydro input and parameter file requirements\nand the preprocessing tools used to generate them.\n\n5.1 Overview of model inputs\n----------------------------\n\n.. _figure-5.1:\n.. figure:: media/physics-inputs.png\n   :align: center\n   :figwidth: 90%\n\n   **Figure 5.1** WRF-Hydro input and parameter files organized by model\n   physics component. See the Key for files specific to a certain land\n   model or channel configuration.\n\nWRF-Hydro requires a number of input files describing the model domain,\nparameters, initial conditions, and when run in a standalone\nconfiguration meteorological forcing files. A full list of these files\nbroken up by model physics component is shown in :ref:`Figure 5.1 <figure-5.1>`.\nNote that the set of files required to run WRF-Hydro varies depending upon\nmodel configuration. For example, different land surface models and model\nphysics components may require different parameter and input files.\n\nWhile some parameter files and templates are included with the model\nsource code, most must be generated by the user. We provide a number of\nscripts and preprocessing utilities on the WRF-Hydro website\n(https://ral.ucar.edu/projects/wrf_hydro/pre-processing-tools) in order to aid in this\nprocess. These include NCAR Command Language (NCL) scripts to regrid\nforcing data from commonly used data sources, R scripts to generate\nparameter and model initialization files, and a set of Python based\nArcGIS pre-processing tools. The specific utilities used to generate\ndifferent files are listed in :ref:`Table 5.1 <table-5.1>`. Users\nshould be aware that these tools do not support all potential datasets\nand use cases and that the use of default parameters will often result\nin suboptimal model performance. More details regarding the pre-processing\nutilities, file requirements, and descriptions follow.\n\nIn addition to the ArcGIS pre-processing tools, the WRF-Hydro group has also\ndeveloped a set of open-source, Python-based preprocessing tools. These tools\nreplicate existing capabilities and operate within the same software\nenvironments as WRF-Hydro. Built with Python 3 and libraries such as\nWhitebox Tools, NumPy, and GDAL, users can configure their environments\nusing Anaconda, Miniconda, or custom setups. This initiative responds to user\ndemand for an open-source option, ensuring portability and multi-platform\nsupport while offering efficient, parallelized geoprocessing. All underlying\nlibraries are open-source, eliminating proprietary licensing restrictions.\nFor more information, please visit:\nhttps://ral.ucar.edu/dataset/open-source-wrf-hydro-gis-pre-processing-tools-beta.\n\n5.2 Domain processing and description of surface physiographic input files\n--------------------------------------------------------------------------\n\nThis subsection describes the process of defining the WRF-Hydro model\ndomain, generating model initial conditions, and deriving geospatial\ninput and parameter files via the WRF-Hydro GIS pre-processing tools. As\nnoted in the previous section a number of scripts and utilities have\nbeen developed to facilitate the creation of these files. Additionally,\nwe rely on a utility within the Weather Research and Forecasting (WRF)\nmodel preprocessing system (WPS) called GEOGRID to define the land\nsurface model grid and relevant geospatial data and produce the\nresulting :file:`geo_em.d0{x}.nc` file hereafter referred to as a “geogrid”\nfile. This geogrid file is then used as input to the ArcGIS preprocessing\ntools, along with external datasets such as high resolution topographic\ndata, which generate the high resolution routing grid and all surface\nphysiographic input data files required by the model. The geogrid file\nis also passed to utilities in order to generate land surface model\ninitial condition files.\n\n5.2.1 Defining the model domain\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe data required to define the domain and geospatial attributes of a\nspatially-distributed, or gridded, 1-dimensional (vertical) land surface\nmodel (LSM) are specified in a geogrid (:file:`geo_em.d0{x}.nc`) netCDF file.\nThis file is generated by the :program:`GEOGRID` utility in the `WRF preprocessing system (WPS)\n<https://ral.ucar.edu/sites/default/files/public/Lesson-wps.html>`_.\nWPS is a preprocessing system that prepares both land surface and\natmospheric data for use in the model. The GEOGRID component of WPS\nautomates the procedure of defining in space, georeferencing and\nattributing most of the land surface parameter data required to execute\nboth the Noah and Noah-MP land surface models. GEOGRID interpolates land\nsurface terrain, soils and vegetation data from standard, readily\navailable data products. These data are distributed as a geographical\ninput data package via the WRF website. Complete documentation and user\ninstructions for use of the WPS system are provided online by NCAR and\nare updated regularly and, thus, are not discussed in great detail here.\nThis :file:`geo_em.d0{x}.nc` file is also required as input to other WRF-Hydro\npreprocessing utilities.\n\n5.2.2 Initial land surface conditions\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nInitial conditions for the land surface, such as soil moisture, soil\ntemperature, and snow states, are prescribed via the :file:`wrfinput_d0x.nc`\nfile. This netCDF file can be generated one of two ways, through the\n:program:`real.exe` program within WRF or via an R script (:file:`create_wrfinput.R`)\ndistributed on the `WRF-Hydro website <https://ral.ucar.edu/projects/wrf_hydro/pre-processing-tools>`_.\nWhen created using the real.exe program in WRF,\ninitial conditions are pulled from existing reanalysis\nor realtime products (see WRF documentation for data and system\nrequirements). This will typically result in more realistic initial\nmodel states. However, the process is somewhat involved and requires the\nuser to obtain additional external datasets.\n\nThe R script will create a simplified version of the :file:`wrfinput_d0x.nc`\nfile including all necessary fields for the\nNoah-MP land surface model, but with spatially uniform initial conditions\nthat are prescribed within the script and requires only the geogrid file\n:file:`geo_em.d0{x}.nc` as input. Step-wise instructions and detailed\nrequirements are included in the documentation distributed with the script.\nUsers should be aware that the model will likely require additional spin-up\ntime when initialized from this file.\n\n5.2.3 Generating hydrologic routing input files via the WRF-Hydro GIS pre-processing tools\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA suite of Python based utilities, the *WRF-Hydro GIS Pre-processing\nToolkit*, have been developed to facilitate the process of deriving\nWRF-Hydro input and parameter files from commonly available geospatial\ndata products, such as hydrologically processed digital elevation\nmodels. A large number of the hydro input and parameter files described\nin :ref:`Table 5.1 <table-5.1>` can be generated by these tools as well\nas a geospatial metadata file to support georeferencing of WRF-Hydro model\noutput files and relevant shapefiles to aid in visualizing the model\ncomponents. The WRF-Hydro GIS pre-processing tools are developed to\nfunction as an additional ArcToolbox within the Esri ArcGIS software.\nSpecific operating system and software requirements are addressed in the\nfull *WRF-Hydro GIS Pre-processing Toolkit* `documentation\n<https://github.com/NCAR/wrf_hydro_arcgis_preprocessor/releases/download/5.2.0/WRFHydro_GIS_Preprocessor_v5_2_0.pdf>`_.\n\nThe minimum input data requirements for the pre-processing tools are the\ngeogrid file :file:`geo_em.d0x.nc` and a hydrologically conditioned digital\nelevation model covering the full extent of the domain of interest. From\nthese datasets the terrain routing files (e.g. :file:`Fulldom_hires.nc`, :file:`hydro2dtbl.nc`)\nand channel routing files (e.g. :file:`Route_Link.nc`) can be created (see Appendices :ref:`A7 <section-a7>`,\n:ref:`A10 <section-a10>`, and :ref:`A11 <section-a11>`).\n\nA ``.txt`` or ``.csv`` file with stream gage locations can optionally\nbe supplied, allowing the user to demarcate these locations in the model input files\nand optionally produce time series outputs (e.g. :file:`*CHANOBS_DOMAIN{x}`) for only these locations.\nThis text file denoting the location of stream gages or \"forecast points\"\ncan also be used to generate groundwater input files. Effectively\ngroundwater basins are delineated above each of these locations and\ndefault parameters will be assigned to a parameter file that can also be\ngenerated using this tool. More details are available in the *WRF-Hydro GIS Pre-processing Toolkit* `documentation\n<https://github.com/NCAR/wrf_hydro_arcgis_preprocessor/releases/download/5.2.0/WRFHydro_GIS_Preprocessor_v5_2_0.pdf>`_.\n\nLake and reservoir component input files also require a supplementary\ninput file. A shapefile containing polygons defining the extent of each\nlake must be provided as input. From this file and the processed digital\nelevation model a number of parameters are derived for each lake\n(however, note that other parameters are only assigned a global default\nvalue). More details about this process and the contents of the input\nand parameter files can be found in Appendix :ref:`A14 <section-a14>`\nand the full *WRF-Hydro GIS Pre-processing Toolkit* `documentation\n<https://github.com/NCAR/wrf_hydro_arcgis_preprocessor/releases/download/5.2.0/WRFHydro_GIS_Preprocessor_v5_2_0.pdf>`_.\n\nThe *WRF-Hydro GIS Pre-processing Toolkit* will also produce a geospatial\nmetadata file (e.g. :file:`GEOGRID_LDASOUT_Spatial_Metadata.nc`) for the land surface\nmodel grid (as defined by the geogrid file :file:`geo_em.d0{x}.nc`). This file contains\nprojection and coordinate information for the land surface model grid.\nWhile this file is an optional input to WRF-Hydro, in combination with\nthe new file output routines in version 5.0 of WRF-Hydro this file will\nallow for the creation of CF (Climate and Forecast metadata convention)\ncompliant output files. This allows for files to be more easily viewed\nin GIS systems (e.g. ArcGIS and QGIS) as well as other visualization\nsoftware. Additional documentation for this toolkit including step by\nstep instructions and detailed requirements is provided on the WRF-Hydro\nwebsite.\n\nRequirements for the hydro components of the model (i.e. those not\ndirectly associated with the land surface model or data assimilation)\nare described in the model physics :ref:`Section\n3 <section-3>` and in :ref:`Table 5.1 <table-5.1>`.\n\n.. table:: **Table 5.1** Input and parameter files for hydro components of\n           WRF-Hydro.\n   :width: 90%\n   :align: center\n   :name: table-5.1\n\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | **Filename**              | **Description**     | **Source**                       | **Required** |\n   +===========================+=====================+==================================+==============+\n   | :file:`Fulldom_hires.nc`  | High resolution     | WRF-Hydro GIS                    | Yes          |\n   |                           | full domain file.   | pre-processing                   |              |\n   |                           | Includes all fields | toolkit                          |              |\n   |                           | specified on the    |                                  |              |\n   |                           | routing grid.       |                                  |              |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`Route_Link.nc`     | Channel reach       | WRF-Hydro GIS                    | When reach   |\n   |                           | parameters (ComID,  | pre-processing                   | based        |\n   |                           | gage ID, bottom     | toolkit                          | routing is   |\n   |                           | width, slope,       |                                  | used         |\n   |                           | roughness, order,   |                                  | (including   |\n   |                           | etc.)               |                                  | user defined |\n   |                           |                     |                                  | mapping)     |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`GWBASINS.nc`       | 2D file defining    | WRF-Hydro GIS                    | When the     |\n   |                           | the locations of    | pre-processing                   | baseflow     |\n   |                           | groundwater basins  | toolkit                          | bucket model |\n   |                           | on a grid           |                                  | is turned on |\n   |                           |                     |                                  | and user     |\n   |                           |                     |                                  | defined      |\n   |                           |                     |                                  | mapping is   |\n   |                           |                     |                                  | off          |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`GWBUCKPARM.nc`     | Groundwater         | WRF-Hydro GIS                    | When the     |\n   |                           | parameter table     | pre-processing                   | baseflow     |\n   |                           | containing bucket   | toolkit                          | bucket model |\n   |                           | model parameters    |                                  | is turned on |\n   |                           | for each basin      |                                  |              |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`LAKEPARM.nc`       | Lake parameter      | WRF-Hydro GIS                    | When lake    |\n   |                           | table containing    | pre-processing                   | and          |\n   |                           | lake model          | toolkit                          | reservoir    |\n   |                           | parameters for each |                                  | routing is   |\n   |                           | catchment           |                                  | turned on    |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`hydro2dtbl.nc`     | Spatially           | :file:`create_SoilProperties.R`  | When using   |\n   |                           | distributed netCDF  | script                           | spatially    |\n   |                           | version of          |                                  | distributed  |\n   |                           | :file:`HYDRO.TBL`   | (will also be automatically      | terrain      |\n   |                           |                     | generated by WRF-Hydro)          | routing      |\n   |                           |                     |                                  | parameters   |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`HYDRO.TBL`         | Parameter table for | :file:`template/HYDRO`           | Yes          |\n   |                           | lateral flow        | directory in the                 |              |\n   |                           | routing within      | model code                       |              |\n   |                           | WRF-Hydro. In the   |                                  |              |\n   |                           | :file:`HYDRO.TBL`   |                                  |              |\n   |                           | file parameters are |                                  |              |\n   |                           | specified by land   |                                  |              |\n   |                           | cover type or soil  |                                  |              |\n   |                           | category            |                                  |              |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`HYDRO_MODIS.TBL`   | Version of          | :file:`template/HYDRO`           | Replacement  |\n   |                           | :file:`HYDRO.TBL`   | directory in the                 | for          |\n   |                           | using MODIS land    | model code                       | |HYDRO.TBL|  |\n   |                           | use categories      |                                  | when using   |\n   |                           | rather than USGS.   |                                  | MODIS land   |\n   |                           | (Change name to     |                                  | use          |\n   |                           | :file:`HYDRO.TBL`   |                                  | categories   |\n   |                           | for use.)           |                                  |              |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`CHANPARM.TBL`      | Parameters for      | :file:`template/HYDRO`           | When gridded |\n   |                           | gridded channel     | directory in the                 | routing is   |\n   |                           | routing scheme.     | model code                       | used         |\n   |                           | Parameters are      |                                  |              |\n   |                           | specified by        |                                  |              |\n   |                           | Strahler stream     |                                  |              |\n   |                           | order               |                                  |              |\n   +---------------------------+---------------------+----------------------------------+--------------+\n   | :file:`spatialweights.nc` | Spatial weight file | distributed with NWM domain      | When using   |\n   |                           | used to map fluxes  | files                            | user defined |\n   |                           | to catchment        |                                  | mapping      |\n   |                           | objects             |                                  |              |\n   +---------------------------+---------------------+----------------------------------+--------------+\n.. |HYDRO.TBL| replace:: :file:`HYDRO.TBL`\n\n.. _section-5.3:\n\n5.3 Description of land surface model and lateral routing parameter files\n-------------------------------------------------------------------------\n\nParameters for the Noah and Noah-MP land surface models as well as for\nthe lateral routing component are specified via a collection of text\nfiles (i.e. parameter tables) denoted by the file suffix ``.TBL``.\nDefault parameter tables for the Noah and Noah-MP models are included in\nthe WRF-Hydro source code within the directory structure for their\nrespective land model and the appropriate files are automatically moved\nto the Run directory upon building the model.\n\nThe Noah land surface model requires three parameter table files, outlined\nin :ref:`Table 5.2 <table-5.2>`. The first of these is the general parameter\ntable or :file:`GENPARM.TBL`. This file contains a number of global parameters\nfor the Noah land surface model. The next is the vegetation parameter table or\n:file:`VEGPARM.TBL`. This file contains parameters that are a function\nof land cover type. The final table is the soil parameter table or\n:file:`SOILPARM.TBL`. This parameter table contains parameters that are\nassigned based upon the soil classification. The variables contained\nwithin these files are described in the Appendix :ref:`A8 <section-a8>`.\n\n.. table:: **Table 5.2** Parameter tables for the Noah land surface model. These\n           parameter tables can be found within the land surface model source code\n           :file:`Run/` directory and will be copied over the the WRF-Hydro Run\n           directory when the compile script for this LSM is run.\n   :align: center\n   :width: 90%\n   :name: table-5.2\n\n   .. default-role:: file\n\n   +---------------+-------------------------------------------+----------------+\n   | **Filename**  | **Description**                           | **Required**   |\n   +===============+===========================================+================+\n   | GENPARM.TBL   | Miscellaneous model parameters that are   | Yes            |\n   |               | applied globally                          |                |\n   +---------------+-------------------------------------------+----------------+\n   | VEGPARM.TBL   | Vegetation parameters indexed by land use | Yes            |\n   |               | / land cover categories                   |                |\n   +---------------+-------------------------------------------+----------------+\n   | SOILPARM.TBL  | Soil parameters indexed by soil texture   | Yes            |\n   |               | classes                                   |                |\n   +---------------+-------------------------------------------+----------------+\n\n   .. default-role::\n\nThe Noah-MP land surface model also requires three parameter table files, outlined\nin :ref:`Table 5.3 <table-5.3>`. The first of these is the general parameter\ntable or :file:`GENPARM.TBL`. This file contains a number of global parameters\nfor the Noah-MP land surface model. The next table is the\n:file:`MPTABLE.TBL`. This file contains parameters that are a function\nof land cover type. The last one is the soil parameter table or\n:file:`SOILPARM.TBL`. This parameter table contains parameters that are\nassigned based upon the soil classification.  The variables contained within these files are\ndescribed in Appendix :ref:`A9 <section-a9>`.\n\nAs part of work conducted for the National Water Model implementation,\nthe ability to specify a number of these land surface model parameters\nspatially on a two or three dimensional grid was introduced. This is\ndone through the use of the compile time option ``SPATIAL_SOIL`` and the\nspecification of a netCDF format parameter file with the default\nfilename :file:`soil_properties.nc`. A list of the variables contained in\nthis file is included in Appendix :ref:`A9 <section-a9>`.\n\n.. table:: **Table 5.3** Parameter tables for the Noah-MP land surface model. These\n            parameter tables can be found within the land surface model source code\n            Run directory and will be copied over to the WRF-Hydro Run directory\n            when the compile script for this LSM is run.\n   :name: table-5.3\n   :align: center\n   :width: 90%\n\n   .. default-role:: file\n\n   +----------------------+---------------------------------------------+----------------+\n   | **Filename**         | **Description**                             | **Required**   |\n   +======================+=============================================+================+\n   | `GENPARM.TBL`        | Miscellaneous model parameters that are     | Yes            |\n   |                      | applied globally                            |                |\n   +----------------------+---------------------------------------------+----------------+\n   | `MPTABLE.TBL`        | Vegetation parameters indexed by land use / | Yes            |\n   |                      | land cover categories                       |                |\n   +----------------------+---------------------------------------------+----------------+\n   | `SOILPARM.TBL`       | Soil parameters indexed by soil texture     | Yes            |\n   |                      | classes                                     |                |\n   +----------------------+---------------------------------------------+----------------+\n   | `soil_properties.nc` | NetCDF file with spatially distributed land | No             |\n   |                      | surface model parameters used when          |                |\n   |                      | WRF-Hydro is compiled with SPATIAL_SOIL=1.  |                |\n   |                      | This allows the user to specify parameters  |                |\n   |                      | on the model grid rather than as a single   |                |\n   |                      | value or function of soil or land cover     |                |\n   |                      | type.                                       |                |\n   |                      |                                             |                |\n   |                      | This file is created by the                 |                |\n   |                      | :file:`create_SoilProperties.R` script      |                |\n   +----------------------+---------------------------------------------+----------------+\n\n   .. default-role:: file\n\n\nParameters for the lateral routing component of WRF-Hydro are specified\nin a similar way via the :file:`HYDRO.TBL` file or the :file:`hydro2dtbl.nc`\nfile. This file is also distributed with the WRF-Hydro source code in the\n:file:`templates/HYDRO` directory and is copied over to the :file:`Run` directory\nupon building the model. There is also an additional :file:`HYDRO_MODIS.TBL`\nfile for those using the MODIS land cover classification scheme.\n\nThe :file:`HYDRO.TBL` parameter table file contains 2 parts. The first part\ncontains the Manning's roughness coefficients for overland flow as a\nfunction of the USGS vegetation types as that data is used in the Noah\nland surface model. The roughness values are strictly indexed to the\nUSGS vegetation classes so that if one wanted to use a different\nvegetation index dataset (e.g. the MODIS/IGBP option in the Noah land\nsurface model) a user would need to remap these roughness values to\nthose new vegetation indices. Users can alter the values of overland\nflow roughness here for a given vegetation type. However, users may also\n'scale' these initial values of roughness by changing the gridded values\nof the overland flow roughness scaling factor (``OVROUGHRTFAC``) that are\ncontained within the high resolution routing data netCDF file (e.g., :file:`Fulldom_hires{x}.nc`).\nBecause hydrological models are often calibrated over a particular region or\nwatershed as opposed to a specific vegetation type it is recommended\nthat users modify the ``OVROUGHRTFAC`` scaling factor as opposed to altering\nthe roughness values in :file:`HYDRO.TBL`.\n\nThe second part of the :file:`HYDRO.TBL` parameter table contains several soil\nhydraulic parameters that are classified as functions of soil type.\nThese soil parameters are copied from the :file:`SOILPARM.TBL` parameter table\nfrom the Noah land surface model. They are provided in :file:`HYDRO.TBL` to\nallow the user to modify those parameters as needed during model\ncalibration activities without modifying the :file:`SOILPARM.TBL` file and thus\nis just done for convenience. In effect, when routing options in\nWRF-Hydro are activated the code will read the soil hydraulic parameters\nfrom :file:`HYDRO.TBL`. If the Noah land surface model is executed within WRF-Hydro\nwithout any of the routing options activated, the code will simply use the\nparameter values specified in :file:`HYDRO.TBL`.\n\nThe file :file:`hydro2dtbl.nc` is a spatially distributed netCDF file version of the\n:file:`HYDRO.TBL` parameter table. This netCDF file can be created via the\n:file:`create_SoilProperties.R` script distributed on the WRF-Hydro website\n(https://ral.ucar.edu/projects/wrf_hydro) or will automatically be\ngenerated by the model from the :file:`HYDRO.TBL` if the filename specified in\nthe :file:`hydro.namelist` does not already exist. See Appendix\n:ref:`A10 <section-a10>` for further explanation of the variables in the\n:file:`HYDRO.TBL` and :file:`hydro2dtbl.nc` files.\n\n5.3.1 Spatially distributed parameter files\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs of version 5.0 of WRF-Hydro we now allow for the specification of a\nnumber of spatially distributed land surface model and / or lateral\nrouting parameters in netCDF input files :file:`soil_properties.nc` and\n:file:`hydro2dtbl.nc`. This option was implemented as part of work conducted\nfor the National Water Model and allows the user to specify parameters on\nthe model grid rather than as a single value or function of soil or land\ncover type. The files can be generated via an R script provided on our\nwebsite (:file:`create_SoilProperties.R`) and are described in more detail in\nAppendices :ref:`A9 <section-a9>` and :ref:`A10 <section-a10>`. In order for the\nmodel to read in the :file:`soil_properties.nc` file the ``SPATIAL_SOIL`` environment\nvariable must be set to 1 at compile time. This option gives users more\nflexibility in the specification of land surface model parameters and is\nparticularly useful in the context of calibration and parameter\nregionalization.\n\n.. _section-5.4:\n\n5.4 Description of channel routing parameter files\n--------------------------------------------------\n\nChannel parameters for WRF-Hydro are specified in one of two files. If\nthe model is configured using gridded channel routing these parameters\nwill be stored in :file:`CHANPARM.TBL`. If the model is configured using reach-based\nrouting (including the NWM configuration) the parameters and\nchannel geometry are specified within the :file:`Route_Link.nc` file generated\nby the *WRF-Hydro GIS Pre-processing Toolkit*. Variables of the\n:file:`CHANPARM.TBL` and :file:`Route_Link.nc` files are described in Appendix\n:ref:`A11 <section-a11>`.\n\nIt is important to keep in mind that there is large uncertainty\nassociated with these parameters. Therefore, model calibration is almost\nalways warranted. Also, because fully-distributed estimates of flow\ndepth (``HLINK`` in :file:`CHANPARM.TBL`) are not available for model initialization,\nit is almost always necessary to use a small initial value of ``HLINK`` and let the model\ncome to its own equilibrium (i.e. “spin-up”) after several hours of\nintegration. The necessary time required to spin up the channel network\nis a direct function of how dense and long your channel network is.\nLarger, more dense networks will take substantially longer to spin up.\nEstimates of total travel time from the furthest channel element to the\nbasin outline are a reasonable initial approximation of the time it will\ntake to spin up the channel elements.\n\n.. _section-5.5:\n\n5.5 Description of groundwater input and parameter files\n--------------------------------------------------------\n\nDepending upon the choice of channel configuration, groundwater input and\nparameter files are specified in slightly different ways. For the\nNational Water Model (NWM) implementation of the model - where user\ndefined mapping is active - the :file:`spatialweights.nc` file is used to map\ngridded fluxes to the appropriate catchments, the spatial unit of the\nNWM groundwater bucket model. In other configurations of the model where\nuser defined mapping is not used, grid-based groundwater basins are\ndefined in a :file:`GWBASINS.nc` netCDF file. The contents of these files are\ndescribed in Appendix :ref:`A12 <section-a12>`.\n\nGroundwater bucket model parameters are assigned via the :file:`GWBUCKPARM.nc`\nfile for all configurations. The contents of these files are also\nsummarized in Appendix :ref:`A12 <section-a12>` and like the\ngroundwater basins files these files are produced by the *WRF-Hydro GIS\nPre-processing Toolkit*. Note that global default parameters are\nprescribed when these files are generated so user adjustments and/or\ncalibration are recommended.\n\n.. _section-5.6:\n\n5.6 Description of lake and reservoir parameter tables\n------------------------------------------------------\n\nLake parameter values are specified for each one of the lake objects.\nTypically, baseline parameters are derived within the high-resolution\nterrain preprocessing stages described above using tools such as ArcGIS\n(e.g. ``LkArea``, ``LkMxE`` in the file :file:`LAKEPARM.nc`).\nValues for the weir and orifice coefficients and\nsizes can be drawn from standard engineering hydraulics textbooks (e.g.\n*Chow et al., 1957*) and calibrated based on lake level performance. Weir\nparameters are specified for reservoir “overflow” or “spill” and orifice\nparameters are specified for design operations. The behavior of the\nreservoir to store and release water is highly dependent on these\nparameters and therefore it is highly recommended that the user modify\nthis file with their own set of parameters beyond the default given in\nthe *WRF-Hydro GIS Pre-processing Toolkit*. See Appendix\n:ref:`A14 <section-a14>` for descriptions of the variables within the\n:file:`LAKEPARM.nc` file.\n\n.. _section-5.7:\n\n5.7 Specification of meteorological forcing data\n------------------------------------------------\n\nModern land surface hydrology models, including WRF-Hydro, require\nmeteorological forcing data to simulate land-atmosphere exchanges and\nterrestrial hydrologic processes when uncoupled to atmospheric modeling\nsystems. Most land models require a similar set of input variables with\nsome variation in terms of the units, spectral bandwidths of radiation,\nhandling of precipitation phase, etc. Most commonly these variables\ninclude: incoming short and longwave radiation, humidity, temperature,\npressure, wind speed and precipitation rate and type. The required variables for the\nNoah and Noah-MP land surface models supported in version 5.x of\nWRF-Hydro are listed in :ref:`Table 5.4 <table-5.4>`. These variables'\nnames, units, and several of the forcing data file format options described\nbelow are borrowed from the High-Resolution Land Data Assimilation System\n(`HRLDAS <https://ral.ucar.edu/solutions/products/high-resolution-land-data-assimilation-system-hrldas>`__),\nan offline driver for Noah land surface models. When WRF-Hydro is\ncoupled into other modeling architectures such as the NASA Land\nInformation System (LIS), these systems will set the requirements for\nthe forcing data.\n\n.. table:: **Table 5.4** Input forcing data for the Noah and Noah-MP land surface\n   models\n   :width: 90%\n   :align: center\n   :name: table-5.4\n\n   +-----------------+------------------------------------+---------------+\n   | **Variable      | **Description**                    | **Units**     |\n   | name**          |                                    |               |\n   +=================+====================================+===============+\n   | ``SWDOWN``      | Incoming shortwave radiation       | `W/m^2`       |\n   +-----------------+------------------------------------+---------------+\n   | ``LWDOWN``      | Incoming longwave radiation        | `W/m^2`       |\n   +-----------------+------------------------------------+---------------+\n   | ``Q2D``         | Specific humidity                  | `kg/kg`       |\n   +-----------------+------------------------------------+---------------+\n   | ``T2D``         | Air temperature                    | `K`           |\n   +-----------------+------------------------------------+---------------+\n   | ``PSFC``        | Surface pressure                   | `Pa`          |\n   +-----------------+------------------------------------+---------------+\n   | ``U2D``         | Near surface wind in the           | `m/s`         |\n   |                 | `u`-component                      |               |\n   +-----------------+------------------------------------+---------------+\n   | ``V2D``         | Near surface wind in the           | `m/s`         |\n   |                 | `v`-component                      |               |\n   +-----------------+------------------------------------+---------------+\n   | ``RAINRATE``    | Precipitation rate                 | `mm/s` *or*   |\n   |                 |                                    | `kg/m^2`      |\n   +-----------------+------------------------------------+---------------+\n   | ``LQFRAC``      | Precipitation type                 | `unitless`    |\n   | (optional)      | i.e., liquid water fraction (0-1)  |               |\n   +-----------------+------------------------------------+---------------+\n\nHere we simply describe the requirements and options that are available\nin the standalone version of WRF-Hydro. Presently, there are 9 forcing\ndata input types in WRF-Hydro. Because it is untenable to support a\nlarge variety of input file formats and data types within the model,\nWRF-Hydro requires that most processing of forcing data be handled\nexternal to the model (i.e. as a “pre-process”) and that users put their\nforcing data into one of the required formats. This includes performing\ntasks like, gridding of station observations, making sure forcing data\nis gridded to match the domain grid and has the correct variable names\nand units (see :ref:`Table 5.4 <table-5.4>`), reformatting data into the\nprescribed netCDF format, etc. Note that The WRF-Hydro code will not\nremap or spatially-subset the forcing data in any way. To facilitate these pre-processing activities\nwe have developed `WRF-Hydro Forcing Engine <https://github.com/NCAR/WrfHydroForcing>`_\nand numerous scripts which can be executed to help in the forcing data preparation process.\nThese scripts along with sample data files are distributed on the WRF-Hydro website.\n\nThe input forcing data type is specified in the land surface model\nnamelist file :file:`namelist.hrldas` by modifying the ``FORC_TYP`` namelist\noption. Model forcing type namelist options are specified and described as follows,\nSee Appendices :ref:`A4 <section-a4>` and :ref:`A5 <section-a5>`\nfor more details.\n\n:\n\n   # 1 = HRLDAS-hr format\n   # 2 = HRLDAS-min format\n   # 3 = WRF output\n   # 4 = Idealized\n   # 5 = Idealized with specified precipitation\n   # 6 = HRLDAS-hr format with specified precipitation\n   # 7 = WRF output with specified precipitation\n   FORC_TYP = 1\n\n.. rubric:: 1 - HRLDAS hourly format input files:\n\nThis option requires meteorological forcing data to be provided in the HRLDAS\nhourly forcing data format. Scripts provided on the WRF-Hydro website will\ngenerate files in this format. Forcing files in this format can also be found\nin the example cases. In this format, gridded forcing data for all\nmeteorological forcing variables with the names and units shown in :ref:`Table\n5.4 <table-5.4>` are included in a single netCDF file for each time step. The\nforcing data grids must match the model grid specified in the :file:`geo_em.d0{x}.nc`\n“geogrid” file. Filenames must conform to the following convention:\n:file:`YYYYMMDDHH.LDASIN_DOMAIN{X}`\n\n.. rubric:: 2 - HRLDAS minute format input files:\n\nThis option requires meteorological forcing data to be provided in the HRLDAS\nminute forcing data format. Like the HRLDAS hourly format, this standard is\nborrowed from the HRLDAS modeling system. However, this format allows for the\nspecification of forcing data at more frequent time intervals (up to\nevery minute as specified by the forcing time step in the\n:file:`namelist.hrldas` file). In this format, gridded forcing data for all\nmeteorological forcing variables with the names and units shown in :ref:`Table\n5.4 <table-5.4>` are included in a single netCDF file for each time step. The forcing\ndata grids must match the model grid specified in the :file:`geo_em.d0{x}.nc`\nfile. Filenames must conform to the following convention:\n:file:`YYYYMMDDHHmm.LDASIN_DOMAIN{X}`\n\n.. rubric:: 3 - WRF output files as input to WRF-Hydro:\n\nThis option allows for meteorological forcing data to be read directly from a\nWRF model output file “wrfout” file so long as the WRF model grid is the same as\nthat for WRF-Hydro. The WRF-Hydro code will not remap or spatially-subset the\ndata in any way. All necessary fields are available in a default WRF output\nfile but users should verify their existence if modifications have been made.\nThese files must be written with only a single time step per file and retain\nthe default filenames. The file naming convention for the wrfout file is\n:file:`wrfout_d0{x}_YYYY-MM-DD_HH:MM:SS`.\n\n.. rubric:: 4 - Idealized forcing:\n\nThis option requires no input files. Instead a simple rainfall event is\nprescribed (i.e. “hardcoded”) in the model. This event is a spatially uniform\n25.4 `mm/hr` (1 `in/hr`) for 1 hour duration over the first hour of the model\nsimulation. The remainder of the forcing variables are set to have either\nconstant values (in space and time) or, in the case of temperature and\nradiation variables, a fixed diurnal cycle (see :ref:`Table 5.5 <table-5.5>`).\nThis option is primarily used for simple testing of the model and is convenient\nfor checking whether or not components besides the forcing data are properly\nbeing read into the model and working. Future versions of WRF-Hydro will allow\nthe user to specify values for the precipitation event and the other meteorological\nvariables. Note that this forcing type requires the user-specified\n``FORCING_TIMESTEP`` namelist parameter to be set to 3600 (1 hr) in the\n:file:`namelist.hrldas` file.\n\n.. table:: **Table 5.5.** Description of idealized forcing\n   :align: center\n   :width: 90%\n   :name: table-5.5\n\n   +--------------+--------------------------+------------------------------+\n   | **Variable   | **Prescribed value or    | **Timing**                   |\n   | name**       | range of values**        |                              |\n   +==============+==========================+==============================+\n   | ``SWDOWN``   | 0 - 900 [`W/m^2`]        | Diurnal cycle                |\n   +--------------+--------------------------+------------------------------+\n   | ``LWDOWN``   | 375 - 425                | Diurnal cycle                |\n   |              | [`W/m^2`]                |                              |\n   +--------------+--------------------------+------------------------------+\n   | ``Q2D``      | 0.01 [`kg/kg`]           | Constant                     |\n   +--------------+--------------------------+------------------------------+\n   | ``T2D``      | 287 - 293 [`K`]          | Diurnal cycle                |\n   +--------------+--------------------------+------------------------------+\n   | ``PSFC``     | 100,000 [`Pa`]           | Constant                     |\n   +--------------+--------------------------+------------------------------+\n   | ``U2D``      | 1.0 [`m/s`]              | Constant                     |\n   +--------------+--------------------------+------------------------------+\n   | ``V2D``      | 1.0 [`m/s`]              | Constant                     |\n   +--------------+--------------------------+------------------------------+\n   | ``RAINRATE`` | 25.4 [`mm/s` or          | For first hourly time step   |\n   |              | `kg/m^2`]                | and zero thereafter          |\n   +--------------+--------------------------+------------------------------+\n\n.. rubric:: 5 - Idealized forcing with specified precipitation:\n\nThis option is identical to forcing type 4 with the exception that the\nWRF-Hydro system will look for user provided supplementary precipitation\nfiles. These supplementary precipitation files are netCDF files containing a\nsingle gridded field with either the name ``precip`` and units of `mm` or\n``precip_rate`` with unit a unit of `mm/s`. When using this forcing type,\nthe WRF-Hydro system will look for a new precipitation input file based\non the user-specified ``FORCING_TIMESTEP`` namelist option set in the\n:file:`namelist.hrldas` file. Scripts provided on the WRF-Hydro website will\ngenerate files in this format (specifically the MRMS regridding\nscripts). Forcing files in this format can also be found in the example\ntest cases. Filenames for supplemental precipitation files must conform\nto this convention: :file:`{YYYYMMDDHHMM}.PRECIP_FORCING.nc`.\n\n.. rubric:: 6 - HRLDAS hourly format input files with specified\n   precipitation:\n\nThis option is identical to forcing type 1 with the exception that the\nWRF-Hydro system will also look for user provided supplementary precipitation\nfiles. These supplementary precipitation files are netCDF files containing a\nsingle gridded field with either the name ``precip`` and units of `mm` or\n``precip_rate`` with unit a unit of `mm/s`. When using this forcing type, the\nWRF-Hydro system will look for a new precipitation input file based on the\nuser-specified ``FORCING_TIMESTEP`` namelist option set in the\n:file:`namelist.hrldas` file. Scripts provided on the WRF-Hydro website will\ngenerate files in this format (specifically the MRMS regridding scripts).\nForcing files in this format can also be found in the example test cases.\nFilenames for supplemental precipitation files must conform to this\nconvention: :file:`{YYYYMMDDHHMM}.PRECIP_FORCING.nc`.\n\nThis option is useful when combining atmospheric analyses from\nreanalysis products or other models with a separate analysis of\nprecipitation (e.g. a gridded gauge product, radar QPE, nowcasts,\nsatellite QPE, etc). The model reads in the meteorological forcing data\nfields on each hour and then holds those values constant for the entire\nhour. Precipitation can be read in more frequently based on the\nuser-specified ``FORCING_TIMESTEP`` namelist parameter in the\n:file:`namelist.hrldas` file. For example, the user can have 'hourly'\nmeteorology with '5-minute' precipitation analyses.\n\n.. rubric:: 7 - WRF output files as input to WRF-Hydro with specified\n   precipitation:\n\nThis option is identical to forcing type 3 with the exception that the\nWRF-Hydro system will also look for user provided supplementary precipitation\nfiles. These supplementary precipitation files are netCDF files containing a\nsingle gridded field with either the name ``precip`` and units of `mm` or\n``precip_rate`` with unit a unit of `mm/s`. When using this forcing type, the\nWRF-Hydro system will look for a new precipitation input file based on the\nuser-specified ``FORCING_TIMESTEP`` namelist option set in the\n:file:`namelist.hrldas` file. Scripts provided on the WRF-Hydro website will\ngenerate files in this format (e.g., MRMS regridding scripts).\nForcing files in this format can also be found in the example test cases.\nFilenames for supplemental precipitation files must conform to this\nconvention: :file:`{YYYYMMDDHHMM}.PRECIP_FORCING.nc`.\n\nThis option is useful when combining forcing data from WRF with a\nseparate analysis of precipitation (e.g. a gridded gauge product, radar\nQPE, nowcasts, satellite QPE, etc). The model reads in the\nmeteorological forcing data fields from the WRF output file and then\nholds those values constant until the next file is available.\nPrecipitation can be read in more frequently based on the user-specified\n``FORCING_TIMESTEP`` namelist parameter in the :file:`namelist.hrldas` file. For\nexample, the user can have 'hourly' meteorology with '5-minute'\nprecipitation analyses.\n"
  },
  {
    "path": "docs/userguide/model-outputs.rest",
    "content": ".. vim: syntax=rst\n.. include:: meta.rest\n\n.. _section-6.0:\n\n6. Description of Output Files from WRF-Hydro\n=============================================\n\nThis chapter describes the output files from Version 5.x of WRF-Hydro.\n\nThe user has several options to allow flexibility when outputting from\nthe WRF-Hydro modeling system. All of the options to control outputs are\nlocated in the hydro.namelist file that the user edits prior to running a\nsimulation. Prior to turning specific file options on, there are a few\nhigh-level namelist options (flags) that help control the quantity of\nvariables each file will produce, along with some flexibility on the level\nof compression files contain.\n\n   .. rubric:: ``io_form_outputs``:\n\n   This flag directs the output to utilize optional internal netCDF compression\n   and the use of optional scale_factor/add_offset attributes to pack variables\n   from floating point to integer. However, the user also has the flexibility\n   to turn these optional features off. For additional information on these\n   “packing” attributes, consult the netCDF documentation for a more in-depth\n   explanation\n   (http://www.unidata.ucar.edu/software/netcdf/docs/index.html). It should\n   be noted that the use of internal compression adds time to output files\n   being produced. This may become costly for large-scale modeling\n   applications. Tests have indicated a cost of 15-25% additional time\n   spent producing output variables when internal netCDF compression is\n   utilized, depending on the number of output files being produced.\n   However, without the use of compression, it is possible file sizes could\n   become large depending on the application. It is also important to note\n   that a value of ``0`` will result in the code deferring to old output\n   routines used in version 3.0 of WRF-Hydro. For these outputs, the user\n   is encouraged to read the documentation for that version of the code.\n   The following values for the ``io_form_outputs`` option are available:\n\n      ``0`` - Defer to old output routines for version 3.0 of WRF-Hydro\n      (NOTE:this is the ONLY option that is supported when running with\n      the Noah LSM)\n\n      ``1`` - Utilize internal netCDF compression in conjunction with\n      scale_factor/add_offset byte packing\n\n      ``2`` - Utilize scale_factor/add_offset byte packing without internal\n      netCDF compression\n\n      ``3`` - Utilize internal netCDF compression without\n      scale_factor/add_offset byte packing.\n\n      ``4`` - No internal netCDF compression and no scale_factor/add_offset\n      byte packing.\n\n   .. rubric:: ``io_config_outputs``:\n\n   This flag offers different sets of output variables for each file. This\n   offers the user some flexibility to the number of output variables being\n   produced. *NOTE*: This flag has no effect when ``io_form_outputs = 0``.\n\n   .. rubric:: ``t0OutputFlag``:\n\n   This flag controls if output files are produced on the initial timestep\n   of the model simulation. It is important to note that some variables are\n   initialized to missing values and may translate to missing values in the\n   output files for the initial time step. However, these files may offer\n   useful information to the user for diagnosing purposes.\n\n   .. rubric:: ``output_channelBucket_influx``:\n\n   This flag controls the creation of output variables specific to running\n   a channel-only configuration of the model. These variables provide useful\n   information on flow coming into channel links located in the simulation\n   domain, which can be used for diagnosing purposes. *Note*: this value must\n   be zero for running a gridded channel routing configuration of the model.\n\nAn overview of available model output files is shown in :ref:`Figure 6.1 <figure-6.1>`.\nFor a detailed table of each variable contained within each output file, see :ref:`A17 <section-a17>`.\nThere is no optimal combination of namelist options to use\nfor outputs. Flexibility was given to the user as end applications will\nvary from one user to another. While a combination of many output\nvariables with compression may work for a one-time model simulation,\nhaving fewer variables with less time spent on compression may be more\nsuitable for a user that is operations driven. Future code upgrades will\nallow further flexibility on the exact variables to output for each\nfile.\n\n.. figure:: media/wrfhydro-outputs.png\n   :name: figure-6.1\n   :figwidth: 90%\n   :width: 90%\n   :align: center\n\n   **Figure 6.1** WRF-Hydro output files organized by model physics\n   component. See the Key for files specific to a certain channel\n   configuration.\n\nPlease note a proper land spatial metadata file is highly encouraged\nwhen producing land surface output from the simulations. This file is\nspecified by the ``LAND_SPATIAL_META_FLNM`` option in the hydro.namelist\nfile. This file contains several geospatial variables and attributes\nwhich are translated to output files that meet CF compliance\n(http://cfconventions.org/). This file can be created using the\n*WRF-Hydro GIS Pre-processing Toolkit* associated with this release. For\ngridded output files, coordinate variable data and attributes are used\nfrom the spatial metadata file for the output variables. Additionally,\ngeospatial attributes, which can help the user display data in GIS\napplications are located within the metadata file. These attributes\ntranslate to the output files during the output creation process. For\nthe 2D high resolution routing output files (``RT_DOMAIN``, ``CHRTOUT_GRID``),\ngeospatial attributes and coordinate variables are translated from the\nFulldom_hires.nc file if they are detected. For point output files\n(``CHRTOUT_GRID``, ``CHANOBS_DOMAIN``, ``LAKEOUT_DOMAIN``), the geospatial\nattributes and coordinate variables have been hard-coded to be latitude\nand longitude for this version of the code.\n\nEach output file will potentially contain some set of attributes and\nvariables that contain temporal and geospatial information useful to the\nuser. Again, it is worth noting that the lack of a land spatial metadata\nfile, or proper attributes in the :file:`Fulldom_hires.nc` file will result\nin a less comprehensive output file in terms of metadata. Each output file\nwill contain a time dimension and variable that specifies the number of\ntimesteps located in the output file, along with a numeric value for\neach timestep in the form of minutes since EPOCH. A ``reference_time``\ndimension (usually 1 in dimension size) and variable exist. This\nvariable will contain the model initialization in minutes since EPOCH.\n\nGridded output files will contain an `x` and `y` coordinate dimension and\nvariable that will contain the center-point coordinate values for either\nthe routing grid, or land surface grid in the model projected space. For\nexample, on a Lambert Conformal modeling domain, these values would be\nin meters. Gridded output files will also contain a ``CRS`` variable,\nwhich contains useful geospatial metadata attributes about the modeling\ndomain. Output files for points, river channel links, or lakes will\ncontain latitude, longitude, and elevation variables to offer metadata\nabout each location in the output file.\n\nAdditionally, output files at points will contain a feature_id variable\nthat will list either a global ID value associated with that point, or a\npredefined ID value extracted from an input file. For example, with 2D\ngridded channel routing, each channel pixel cell has an ID value that\nranges from `1-n` where `n` is the global number of channel pixel cells.\nHowever, with reach-based routing, each channel reach may have a\npredefined link ID value specified via the :file:`Route_Link.nc` file. All files\ncontain ``model_initialization_time`` and ``model_output_valid_time`` character\nattributes to offer additional time information about the output file.\nFor files that were produced with ``io_form_outputs`` options of ``1`` or ``2``,\nstandard netCDF variable attributes ``scale_factor`` and ``add_offset`` are\npresent to help users and netCDF APIs unpack integer data back to\nfloating point for visualization and analysis. For a more in-depth\ndescription of netCDF CF compliant output, please visit\nhttp://cfconventions.org.\n\nTwo output files that do not necessarily follow the above mentioned\nformat will be the groundwater output (``GWOUT_DOMAIN``) file and\n:file:`frxst_pts_out.txt` text file. Groundwater output are representative of a\nspatial region, as opposed to points or fixed pixel cells. Future code\nupgrades will attempt to incorporate additional spatial information\nabout groundwater buckets. The :file:`frxst_pts_out.txt` text file is a simple\nASCII text file, not netCDF.\n\nThe following output files are available to the user, depending on their\nrun configuration:\n\n   1. Land surface model output\n\n   2. Land surface diagnostic output\n\n   3. Streamflow output at all channel reaches/cells\n\n   4. Streamflow output at forecast points or gage reaches/cells\n\n   5. Streamflow on the 2D high resolution routing grid (gridded channel\n      routing only)\n\n   6. Terrain routing variables on the 2D high resolution routing grid\n\n   7. Lake output variables\n\n   8. Ground water output variables\n\n   9. A text file of streamflow output at either forecast points or gage\n      locations (:file:`frxst_pts_out.txt`)\n\nThe output files will be described below.\n\nFile naming convention of output files: ``YYYY`` = year, ``MM`` = month,\n``DD`` = day, ``HH`` = hour, ``MM`` = minutes, ``DOMAINX`` = the domain\nnumber that is specified in the hydro.namelist input file (also matches\nthe domain number of the geogrid input file)\n\n.. rubric:: 1. Land surface model output\n\n\\\n   :file:`{YYYYMMDDHHMM}.LDASOUT_DOMAIN{X}`\n\n   For this output file, land surface model variables are written to a\n   multi-dimensional netCDF file. Output is produced on the land surface\n   grid, most variables coming directly from the land surface model. The `x`\n   and `y` dimensions of the output file match those of the geogrid input\n   file and the land spatial metadata file. The ``soil_layers_stag`` and\n   ``snow_layers`` dimensions specify the number of soil and snow layers\n   being produced by the land surface model. The names and definitions for\n   each output variable in the LSM output file are generally consistent\n   with those output from standard Noah or Noah-MP LSM coupled to WRF. The\n   output frequency of this file is dictated ``OUTPUT_TIMESTEP`` specified in\n   :file:`namelist.hrldas`.\n\n.. rubric:: 2. Land surface diagnostic output\n\n\\\n   :file:`{YYYYMMDDHHMM}.LSMOUT_DOMAIN{X}`\n\n   Variables for this output file will not change with varying values of\n   ``io_config_outputs`` as there is a limited set of land surface states\n   produced for this output file. In general, the user will not desire this\n   output file as the regular land surface output files contain a larger\n   amount of land surface output. However, for examining model state and\n   flux passing between the LSM and the routing routines, this file could\n   contain potentially valuable information that would assist in those\n   efforts. Some of these states include soil moisture, soil temperature,\n   infiltration excess, and surface head. Like the land surface output\n   files, output variables in this output file will match the land surface\n   grid. The output frequency of this file is dictated by ``OUTPUT_TIMESTEP``\n   specified in :file:`namelist.hrldas`.\n\n.. rubric:: 3. Streamflow output at all channel reaches/cells\n\n\\\n   :file:`{YYYYMMDDHHMM}.CHRTOUT_DOMAIN{X}`\n\n   The ``CHRTOUT_DOMAIN`` option in the :file:`hydro.namelist` is used to\n   activate this output. This output file will produce a set of streamflow\n   (and related) variables for each channel location in the modeling domain.\n   For 2D gridded routing on the channel network, this is every pixel cell\n   on the high-resolution modeling domain classified as a channel pixel cell.\n   Forreach-based routing, this is every channel reach defined in the\n   :file:`Route_Link.nc` file. If the user desires to limit the number of\n   streamflow points, the ``order_to_write`` option in :file:`hydro.namelist`\n   will reduce the number of points based on the Strahler order number.\n   Otherwise, all points will be outputted to the file. Each file will\n   contain a ``latitude``, ``longitude``, ``elevation``, and ``order`` variable\n   to describe basic information on each channel point. The ``CRS`` projection\n   variable has been hard-coded (as it is with all other point output\n   files) as the coordinate variables for point files are in\n   latitude/longitude.\n\n.. rubric:: 4. Streamflow output at forecast points or gage reaches/cells\n\n\\\n   :file:`{YYYYMMDDHHMM}.CHANOBS_DOMAIN{X}`\n\n   The ``CHANOBS_DOMAIN`` option in the hydro.namelist is used to activate this\n   output. This output file is very similar to the regular streamflow\n   output file format. The key difference is output only occurs at\n   predefined forecast points or gage locations. For 2D gridded channel\n   routing, the user defines forecast points during the setup of their\n   modeling domain. Under this configuration, streamflow will be produced\n   at those points. It is worth noting output points can be constrained by\n   the ``order_to_write`` as they are in the regular streamflow output files.\n   For reach-based routing, it is possible to create outputs at a set of\n   predefined gage points in the :file:`Route_Link.nc` file. Within the\n   :file:`Route_Link.nc` file, a variable called ``gages`` of type character will\n   need to be created by the user containing a string for each channel\n   reach that contains a gage. This variable is of length ``feature_id`` (see\n   description of the Route_Link.nc file in Appendix :ref:`A9 <section-a9>`),\n   and size 15. If a channel reach does not contain a gage, the string\n   stays empty. For example, ``\"               \"`` would represent a channel\n   reach with no gage, and ``\"       07124000\"`` would contain a gage labeled\n   “07124000”. It is up to the user to create this variable and populate it with\n   character strings if there is a desire to connect gage locations to channel\n   reaches. If no locations are found, the output code will simply bypass\n   creating this output file. Like the other point files, similar\n   geospatial information will be placed into the output files.\n\n.. rubric:: 5. Streamflow on the 2D high resolution routing grid\n\n\\\n   :file:`{YYYYMMDDHHMM}.CHRTOUT_GRID{X}`\n\n   The ``CHRTOUT_GRID`` option in the :file:`hydro.namelist` is used to activate this\n   output. This output file is a 2D file created from streamflow with 2D gridded\n   channel routing. Currently, this file is not available for reach-based\n   routing as channel routing does not occur on the channel grid. Output\n   occurs on the high resolution channel routing grid, which means file\n   sizes may be large depending on the size of your domain. In addition to\n   geospatial metadata and coordinate variables, an ``index`` variable is\n   created on the 2D grid producing a global index value for each channel\n   pixel cell on the grid. The main motivation behind creating this file is\n   for easy spatial visualization of the streamflow occurring across the\n   modeling domain.\n\n.. rubric:: 6. Terrain routing variables on the 2D high resolution routing grid\n\n\\\n   :file:`{YYYYMMDDHHMM}.RTOUT_DOMAIN{X}`\n\n   The ``RTOUT_DOMAIN`` option in the :file:`hydro.namelist` is used to activate this\n   output. This output file is a 2D file created on the high resolution routing\n   grid. The primary variables created for this file are overland and\n   subsurface routing components that may be of interest to the user. The\n   format is very similar to the 2D streamflow file. Due to the shear size\n   of these data layers, care should be used in deciding when to output\n   high-resolution terrain data.\n\n.. rubric:: 7. Lake output variables\n\n\\\n   :file:`{YYYYMMDDHHMM}.LAKEOUT_DOMAIN{X}`\n\n   The ``outlake`` option in the :file:`hydro.namelist` will activate this output.\n   This file is a point output file containing lake/reservoir inflow,\n   outflow and elevation values for each lake/reservoir object created in\n   the modeling domain. The format follows that of the other point output\n   files in terms of geospatial metadata. If no lake/reservoir objects were\n   created in the modeling domain, no output will be created.\n\n.. rubric:: 8. Ground water output variables\n\n\\\n   :file:`{YYYYMMDDHHMM}.GWOUT_DOMAIN{X}`\n\n   The ``output_gw`` option in the :file:`hydro.namelist` will activate this output.\n   When groundwater buckets are activated in the model simulations, it is\n   possible to output bucket inflow/outflow/depth states via netCDF files.\n   One important note to reiterate for these output files is that they will\n   not contain the same geospatial metadata as other point files. Each\n   element in the output array represents a spatial groundwater bucket that\n   covers a region that is neither a single pixel cell or point on the\n   modeling domain. For these reasons, this is the only netCDF output file\n   that will not contain full geospatial metadata and coordinate variables.\n\n.. rubric:: 9. :file:`frxst_pts_out.txt`\n\n\\\n   The ``frxst_pts_out`` option in the :file:`hydro.namelist` will activate this\n   output. The forecast points text file is a unique output file that distills\n   modeled streamflow and stage down to a simple text file with the\n   following columns:\n\n      -  column 1 : time (in seconds) into simulation\n\n      -  column 2 : date and time as YYYY-MM-DD_HH:MM:SS\n\n      -  column 3 : station number index (same as ``feature_id`` in netCDF files)\n\n      -  column 4 : station longitude (in decimal degrees)\n\n      -  column 5 : station latitude (in decimal degrees)\n\n      -  column 6 : streamflow discharge (in cubic meters per second)\n\n      -  column 7 : streamflow discharge (in cubic feet per second)\n\n      -  column 8 : flow depth/river stage (in meters above channel bottom)\n\n                    *Note*: Column 8 is not active for reach-based routing.\n\n   Each row in the text file is representative of a predefined forecast\n   point (2D gridded channel routing only) or a gage point (reach-based\n   routing). It is worth noting that the number of points will be reduced\n   (as with CHANOBS and CHRTOUT) if the user specifies a higher\n   ``order_to_write`` namelist option.\n\nOnce output files are generated, the user should inspect the files using\nthe :program:`ncdump` netCDF utility for displaying the contents of a netCDF\nfile. With the exception of groundwater output files, the forecast\npoints text file, and any files generated using ``io_form_outputs`` of 0,\nthe user should see some baseline variables and attributes. A ``crs``\nvariable will be present indicating the projection coordinate system for\nthe output files. If these files are missing in the 2D files, it is\npossible the Fulldom_hires.nc or land spatial metadata file does not\ncontain the necessary ``crs`` variable. The same logic can be applied to\nthe ``x`` and ``y`` coordinate variables in the 2D output files. The\nomission of these indicates they were not present in the input files\nprior to running the model. For additional help indicating potential\nissues with the output code, please inspect the standard output from the\nmodel. Specifically, look for any \":output:`WARNING`\" messages that may indicate\nwhy files have not appeared or metadata is missing. For example,\n\":output:`WARNING: Unable to locate the crs variable. No crs variable or \\\nattributes will be created.`\" would indicate the model was unable to locate\nthe ``crs`` variable in one of the input files.\n\n\n.. note::\n   **Additional Notes:**\n\n   -  The output descriptions above may not be fully accurate when running\n      with the Noah LSM, which is not actively in development and we\n      therefore support only in a deprecated state. New and improved output\n      routines (e.g., with CF compliance, scale/offset/compression options,\n      augmented metadata) only work with the Noah-MP LSM, while the Noah\n      LSM relies on deprecated output routines. See Appendix\n      :ref:`A2 <section-a2>` for more details on running with the Noah LSM.\n\n   -  For proper QGIS display of the 2D variables, the user will need to\n      rename netCDF output files to include a “.nc” at the end as some\n      versions of QGIS struggle to properly read in information from a\n      netCDF file without this extension. Future upgrades will\n      automatically add this file extension into the filenames.\n"
  },
  {
    "path": "docs/userguide/model-physics.rest",
    "content": ".. vim: syntax=rst\n.. include:: meta.rest\n\n.. _section-3:\n\n3. Model Physics Description\n============================\n\nThis chapter describes the physics behind each of the modules in Version\n|version_short| of WRF-Hydro and the associated namelist options which are\nspecified at “run time”.\n\n3.1 Physics Overview\n--------------------\n\n.. _figure3.1:\n.. figure:: media/wrf-hydro-components.png\n   :align: center\n\n   **Figure 3.1.** Conceptual diagram of WRF-Hydro physics components and\n   relative outputs.\n\nFirst, the 1-dimensional (1D) column land surface model calculates the\nvertical fluxes of energy (sensible and latent heat, net radiation) and\nmoisture (canopy interception, infiltration, infiltration-excess, deep\npercolation) and soil thermal and moisture states. Infiltration excess,\nponded water depth and soil moisture are subsequently disaggregated from\nthe 1D LSM grid, typically of 1-4 km spatial resolution, to a\nhigh-resolution, typically 30-100 m, routing grid using a time-step\nweighted method *(Gochis and Chen, 2003)* and are passed to the subsurface\nand overland flow terrain-routing modules. In typical U.S. applications,\nland cover classifications for the 1D LSMs are provided by the USGS\n24-type Land Use Land Cover product or MODIS Modified IGBP 20-category\nland cover product (see WRF/WPS documentation); soil classifications are\nprovided by the 1-km STATSGO database *(Miller and White, 1998)*; and soil\nhydraulic parameters that are mapped to the STATSGO soil classes are\nspecified by the soil analysis of *Cosby et al. (1984)*. Other land cover\nand soil type classification datasets can be used with WRF-Hydro but\nusers are responsible for mapping those categories back to the same\ncategories as used in the USGS or MODIS land cover and STATSGO soil type\ndatasets. The WRF model pre-processing system (WPS) also provides a\nfairly comprehensive database of land surface data that can be used to\nset up the Noah and Noah-MP land surface models. It is possible to use\nother land cover and soils datasets, and more recently, data from the USGS\nNational Land Cover Dataset (NLCD) and international soils datasets have\nbeen integrated into WRF-Hydro.\n\nThen, subsurface lateral flow in WRF-Hydro is calculated prior to the\nrouting of overland flow to allow exfiltration from fully saturated grid\ncells to be added to the infiltration excess calculated by the LSM. The\nmethod used to calculate the lateral flux of the saturated portion of\nthe soil column is that of *Wigmosta et al. (1994)* and *Wigmosta and\nLettenmaier (1999)*, implemented in the Distributed Hydrology Soil\nVegetation Model (DHSVM). It calculates a quasi-3D flow, which includes\nthe effects of topography, saturated soil depth, and depth-varying\nsaturated hydraulic conductivity values. Hydraulic gradients are\napproximated as the slope of the water table between adjacent grid cells\nin either the steepest descent or in both `x`- and `y`-directions. The flux\nof water from one cell to its down-gradient neighbor on each time-step\nis approximated as a steady-state solution. The subsurface flux occurs\non the coarse grid of the LSM while overland flow occurs on the fine\ngrid.\n\nNext, WRF-Hydro calculates the water table depth according to the depth\nof the top of the saturated soil layer that is nearest to the surface.\nTypically, a minimum of four soil layers are used in a 2-meter soil\ncolumn used in WRF-Hydro but this is not a strict requirement.\nAdditional discretization permits improved resolution of a time-varying\nwater table height and users may vary the number and thickness of soil\nlayers in the model namelist described in the Appendices :ref:`section-a3`,\n:ref:`section-a4`, and :ref:`section-a5`.\n\nThen, overland flow is defined. The fully unsteady, spatially explicit,\ndiffusive wave formulation of *Julien et al. (1995-CASC2D)* with later\nmodification by *Ogden (1997)* is the current option for representing\noverland flow, which is calculated when the depth of water on a model\ngrid cell exceeds a specified retention depth. The diffusive wave\nequation accounts for backwater effects and allows for flow on adverse\nslopes *(Ogden, 1997)*. As in *Julien et al. (1995)*, the continuity\nequation for an overland flood wave is combined with the diffusive wave\nformulation of the momentum equation. Manning's equation is used as the\nresistance formulation for momentum and requires specification of an\noverland flow roughness parameter. Values of the overland flow roughness\ncoefficient used in WRF-Hydro were obtained from *Vieux (2001)* and were\nmapped to the existing land cover classifications provided by the USGS\n24-type land-cover product of *Loveland et al. (1995)* and the MODIS\n20-type land cover product, which are the same land cover classification\ndatasets used in the 1D Noah/Noah-MP LSMs.\n\nAdditional modules have also been implemented to represent stream\nchannel flow processes, lakes and reservoirs, and stream baseflow. In\nWRF-Hydro v\\ |version_short| inflow into the stream network and lake and\nreservoir objects is a one-way process. Overland flow reaching grid cells\nidentified as 'channel' grid cells pass a portion of the surface water\nin excess of the local ponded water retention depth to the channel\nmodel. This current formulation implies that stream and lake inflow from\nthe land surface is always positive to the stream or lake element. There\nis an optional channel loss formulation *(Lahmers et al. 2019)* where water\ncan seep from the channel; note that this water becomes a sink term and is\nnot returned to the soil or baseflow. Currently there are no channel or\nlake loss functions where water can move\nfrom channels or lakes back to the landscape. Channel flow in WRF-Hydro\nis represented by one of a few different user-selected methodologies\ndescribed below. Water passing into and through lakes and reservoirs is\nrouted using a simple level pool routing scheme. Baseflow to the stream\nnetwork is represented using a conceptual catchment storage-discharge\nbucket model formulation (discussed below) which obtains “drainage” flow\nfrom the spatially-distributed landscape. Discharge from buckets is\ninput directly into the stream using an empirically-derived\nstorage-discharge relationship. If overland flow is active, the only\nwater flowing into the buckets comes from soil drainage. This is because\nthe overland flow scheme will pass water directly to the channel model.\nIf overland flow is switched off and channel routing is still active,\nthen surface infiltration excess water from the land model is collected\nover the pre-defined catchment and passed into the bucket as well. Each\nof these process options are enabled through the specification of\noptions in the model namelist file.\n\n3.2 Land model description: The community Noah and Noah-MP land surface models\n-------------------------------------------------------------------------------\n\n.. note::\n   As of this writing, only the Noah and Noah-MP land surface\n   models are supported within WRF-Hydro. CLM coupling is currently\n   out-of-date and is not formally supported but is in the process of\n   being updated. The NASA Land Information System (LIS) has been coupled\n   with WRF-Hydro through the NUOPC framework and is supported under\n   the `NASA Land Coupler <https://github.com/NASA-LIS/NASA-Land-Coupler>`_.\n\n3.2.1 Noah Land Surface Model (deprecated support only)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe Noah land surface model is a community, 1-dimensional land surface\nmodel that simulates soil moisture (both liquid and frozen), soil\ntemperature, skin temperature, snowpack depth, snowpack water\nequivalent, canopy water content and the energy flux and water flux\nterms at the Earth's surface *(Mitchell et al., 2002; Ek et al., 2003)*.\nThe model has a long heritage, with legacy versions extensively tested\nand validated, most notably within the Project for Intercomparison of\nLand surface Parameterizations (PILPS), the Global Soil Wetness Project\n*(Dirmeyer et al. 1999)*, and the Distributed Model Intercomparison\nProject *(Smith, 2002)*. *Mahrt and Pan (1984)* and *Pan and Mahrt (1987)*\ndeveloped the earliest predecessor to Noah at Oregon State University\n(OSU) during the mid-1980's. The original OSU model calculated sensible\nand latent heat flux using a two-layer soil model and a simplified plant\ncanopy model. Development and implementation of the Noah land model\nhas been sustained through the community participation\nof various agency modeling groups and the university community (e.g.\n*Chen et al., 2005*). *Ek et al. (2003)* detail the numerous changes that\nhave evolved since its inception including, a four layer soil\nrepresentation (with soil layer thicknesses of 0.1, 0.3, 0.6 and 1.0 m),\nmodifications to the canopy conductance formulation *(Chen et al., 1996)*,\nbare soil evaporation and vegetation phenology *(Betts et al., 1997)*,\nsurface runoff and infiltration *(Schaake et al., 1996)*, thermal\nroughness length treatment in the surface layer exchange coefficients\n*(Chen et al., 1997a)* and frozen soil processes *(Koren et al., 1999)*.\nMore recently refinements to the snow-surface energy budget calculation\n*(Ek et al., 2003)* and seasonal variability of the surface emissivity\n*(Tewari et al., 2005)* have been implemented.\n\nThe Noah land surface model has been tested extensively in both offline\n(e.g., *Chen et al., 1996, 1997*; *Chen and Mitchell, 1999*; *Wood et al.,\n1998*; *Bowling et al., 2003*) and coupled (e.g. *Chen et el., 1997*, *Chen\nand Dudhia, 2001*, *Yucel et al., 1998*; *Angevine and Mitchell, 2001*; and\n*Marshall et al., 2002*) modes. The most recent version of Noah is\ncurrently one of the operational LSM's participating in the interagency\nNASA-NCEP real-time Land Data Assimilation System (LDAS, 2003, *Mitchell\net al., 2004* for details). Gridded versions of the Noah model are\ncurrently coupled to real-time weather forecasting models such as the\nNational Center for Environmental Prediction (NCEP) North American Model\n(NAM), and the community WRF model. Users are referred to *Ek et al.\n(2003)* and earlier works for more detailed descriptions of the\n1-dimensional land surface model physics of the Noah LSM.\n\n.. note::\n   Support for the Noah Land Surface Model within WRF-Hydro is currently\n   frozen at Noah version 3.6. Since the Noah LSM is not under active\n   development by the community, WRF-Hydro is continuing to support Noah in\n   deprecated mode only. Some new model features, such as the improved\n   output routines, have not been setup to be backward compatible with Noah.\n   Noah users should follow the guidelines in Appendix :ref:`A2 <section-a2>`\n   for adapting the WRF-Hydro workflow to work with Noah.\n\n3.2.2 Noah-MP Land Surface Model (recommended)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nNoah-MP is a land surface model (LSM) using multiple options for key\nland-atmosphere interaction processes (*Niu et al., 2011*). Noah-MP was\ndeveloped to improve upon some of the limitations of the Noah LSM (*Koren\net al., 1999; Ek et al., 2003*). Specifically, Noah-MP contains a\nseparate vegetation canopy defined by a canopy top and bottom, crown\nradius, and leaves with prescribed dimensions, orientation, density, and\nradiometric properties. The canopy employs a two-stream radiation\ntransfer approach along with shading effects necessary to achieve proper\nsurface energy and water transfer processes including under-canopy snow\nprocesses (*Dickinson, 1983; Niu and Yang, 2004*). Noah-MP contains a\nmulti-layer snow pack with liquid water storage and melt/refreeze\ncapability and a snow-interception model describing loading/unloading,\nmelt/refreeze capability, and sublimation of canopy-intercepted snow\n(*Yang and Niu 2003; Niu and Yang 2004*). Multiple options are available\nfor surface water infiltration and runoff and groundwater transfer and\nstorage including water table depth to an unconfined aquifer (*Niu et\nal., 2007*) as well as options for different snow processes such as snow\nalbedo.\n\nThe Noah-MP land surface model can be executed by prescribing both the\nhorizontal and vertical density of vegetation using either ground- or\nsatellite-based observations. Another available option is for prognostic\nvegetation growth that combines a Ball-Berry photosynthesis-based\nstomatal resistance (*Ball et al., 1987*) with a dynamic vegetation model\n(*Dickinson et al. 1998*) that allocates carbon to various parts of\nvegetation (leaf, stem, wood and root) and soil carbon pools (fast and\nslow). The model is capable of distinguishing between `C_3` and\n`C_4` photosynthesis pathways and defines vegetation-specific\nparameters for plant photosynthesis and respiration.\n\nIn addition to the three-layer snow model in NoahMP, WRF-Hydro also supports\noptionally running the Crocus snowpack model within NoahMP for glacial\nrepresentation. For details on using this option, please see\n:ref:`Appendix 16 <section-a16>`.\n\nThe Noah-MP version in WRF-Hydro also includes an option for adjusting\ninfiltration vs. surface runoff partitioning as a function of impervious\nsurface cover. The default Noah-MP behavior is to set a very narrow range\nof soil water holding capacity for cells classified as urban. This has the\neffect of generating more runoff, but also results in very wet cells\nthat may or may not be appropriate for your application. The new physics setting\n(``IMPERV_OPTION`` in :file:`namelist.hrldas`) includes 4 options:\n\n-  Option 0 (no adjustment): Urban cells will be treated the same as all other\n   cells and will use the provided soil and surface parameters to calculate partitoning\n   between infiltration and surface runoff.\n\n-  Option 1 (total): If spatially distributed parameters are active (``SPATIAL_SOIL=1`` on\n   code compile), the model will expect an impervious fraction grid (``imperv``) to be\n   included in the soil_properties.nc file. The model will use this fractional value\n   to automatically partition that fraction (``imperv``) of effective precipitation\n   reaching the surface to direct surface runoff. The rest (1-``imperv``) will be available\n   for infiltration. If spatially distributed parameters are not active (``SPATIAL_SOIL=0``\n   on code compile), the model will use the ``IMPERV_URBAN`` value from :file:`MPTABLE.TBL` for\n   impervious fraction for all urban cells.\n\n-  Option 2 (Alley&Veenhuis): Similar to Option 1, with the modification that the\n   provided impervious fraction will be adjusted to account for local capture of some\n   runoff to adjacent green spaces. This adjustment uses an empirical formulation\n   derived in Alley & Veenhuis (1983, https://doi.org/10.1061/(ASCE)0733-9429(1983)109:2(313) ).\n   In the future we plan to test options that derive an adjustment factor based on\n   impervious connectivity or other local (sub-grid) conditions.\n\n-  Option 9 (original formulation): This reverts back to the original Noah-MP configuration\n   where soil water holding capacity is adjusted for urban cells and impervious fraction is not used.\n\n\n.. note::\n   The Noah-MP code within WRF-Hydro has some additional features that were added\n   specifically for WRF-Hydro hydrologic applications, such as spatially distributed\n   parameters and impervious surface runoff treatment, so it does not exactly track\n   the Noah-MP standalone code releases. Standalone Noah-MP model code was recently\n   modernized for modularity and accessibility (*He et al. 2023*). Support for this\n   refactored version of the Noah-MP model is currently in development and will be\n   included in a future WRF-Hydro release.\n\n3.3 Spatial Transformations\n---------------------------\n\nThe WRF-Hydro system has the ability to execute a number of physical\nprocess executions (e.g. column physics, routing processes, reservoir\nfluxes) on different spatial frameworks (e.g. regular grids, catchments,\nriver channel vectors, reservoir polygons, etc). This means that spatial\ntransformations between differing spatial elements has become a critical\npart of the overall modeling process. Starting in v5.0 of WRF-Hydro,\nincreased support has been developed to aid in the mapping between\ndiffering spatial frameworks. Section 3.3.1 describes the spatial\ntransformation process which relies on regular, rectilinear grid-to-grid\nmapping using a simplified integer linear multiple\naggregation/disaggregation scheme. This basic scheme has been utilized\nin WRF-Hydro since its creation as it was described in *Gochis and Chen, 2003*.\n\nSection 3.3.2 describes new spatial transformation methods that have been\ndeveloped and are currently supported in v5.0 and beyond and, more\nspecifically, in the NOAA National Water Model (NWM). Those user-defined\ntransformations rely on the pre-processing development and specification\nof interpolation or mapping weights which must be read into the model.\nAs development continues future versions will provide more options and\nflexibility for spatial transformations using similar user-defined methodologies.\n\n.. _section-5:\n\n3.3.1 Subgrid disaggregation-aggregation\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis section details the implementation of a subgrid\naggregation/disaggregation scheme in WRF-Hydro. The\ndisaggregation-aggregation routines are activated when routing of either\noverland flow or subsurface flow is active and the specified routing\ngrid increment is different from that of the land surface model grid.\nRouting in WRF-Hydro is “switch-activated” through the declaration of\nparameter options in the primary model namelist file hydro.namelist\nwhich are described in Appendix :ref:`section-a5`\n\nIn WRF-Hydro subgrid aggregation/disaggregation is used to represent\noverland and subsurface flow processes on grid scales much finer than\nthe native land surface model grid. Hence, only routing is represented\nwithin a subgrid framework. It is possible to run both the land surface\nmodel and the routing model components on the same grid. This\neffectively means that the aggregation factor between the grids has a\nvalue of 1.0. This following section describes the\naggregation/disaggregation methodology in the context of a “subgrid”\nrouting implementation.\n\nIn WRF-Hydro the routing portions of the code have been structured so\nthat it is simple to perform both surface and subsurface routing\ncalculations on grid cells that potentially differ from the native land\nsurface model grid sizes provided that each land surface model grid cell\nis divided into integer portions for routing. Hence routing calculations\ncan be performed on comparatively high-resolution land surfaces (e.g., a\n25 `m` digital elevation model) while the native land surface model can be\nrun at much larger (e.g., 1 `km`) grid sizes. (In this example, the\ninteger multiple of disaggregation in this example would be equal to\n40.) This capability adds considerable flexibility in the implementation\nof WRF-Hydro. However, it is well recognized that surface hydrological\nresponses exhibit strongly scale-dependent behavior such that\nsimulations at different scales, run with the same model forcing, may\nyield quite different results.\n\nThe aggregation/disaggregation routines are currently activated by\nspecifying either the overland flow or subsurface flow routing options\nin the model namelist file and prescribing terrain grid domain file\ndimensions (``IXRT``, ``JXRT``) which differ from the land surface model domain\nfile dimensions (``IX``, ``JX``). Additionally, the model sub-grid size (``DXRT``),\nthe routing time-step (``DTRT``), and the integer divisor (``AGGFACTRT``), which\ndetermines how the aggregation/disaggregation routines will divide up a\nnative model grid square, all need to be specified in the model\n`hydro.namelist` file.\n\nIf ``IXRT=IX``, ``JXRT=JX`` and ``AGGFACTRT=1`` the aggregation/disaggregation\nschemes will be activated but will not yield any effective changes in\nthe model resolution between the land surface model grid and the terrain\nrouting grid. Specifying different values for ``IXRT``, ``JXRT`` and ``AGGFACTRT≠1``\nwill yield effective changes in model resolution between the land model\nand terrain routing grids. As described in the Surface Overland Flow\nRouting section `3.5 <#surface-overland-flow-routing>`__, ``DXRT`` and ``DTRT``\nmust always be specified in accordance with the routing grid even if\nthey are the same as the native land surface model grid.\n\nThe disaggregation/aggregation routines are implemented in WRF-Hydro as\ntwo separate spatial loops that are executed after the main land surface\nmodel loop. The disaggregation loop is run prior to routing of saturated\nsubsurface and surface water. The main purpose of the disaggregation\nloop is to divide up specific hydrologic state variables from the land\nsurface model grid square into integer portions as specified by\n``AGGFACTRT``. An example disaggregation (where ``AGGFACTRT=4``) is given in\nFigure 3.2.\n\n.. _figure3.2:\n.. figure:: media/aggfactr.png\n   :align: center\n   :scale: 50%\n\n   **Figure 3.2** Example of the routing sub-grid implementation within the\n   regular land surface model grid for an aggregation factor = 4.\n\nFour model variables are required to be disaggregated for higher\nresolution routing calculations:\n\n   `SMCMAX` - maximum soil moisture content for each soil type\n\n   `SMCREF` - reference soil moisture content (field capacity) for each soil\n   type\n\n   `INFXS` - infiltration excess\n\n   `LKSAT` - lateral saturated conductivity for each soil type\n\n   `SMC` - soil moisture content for each soil layer\n\nIn the model code, fine-grid values bearing the same name as these with\nan “RT” extension are created for each native land surface model grid\ncell (e.g. ``INFXSRT`` vs ``INFXS``).\n\nTo preserve the structure of the spatial variability of soil moisture\ncontent on the sub-grid from one model time step to the next, simple,\nlinear sub-grid weighting factors are assigned. These values indicate\nthe fraction of the total land surface model grid value that is\npartitioned to each sub-grid pixel. After disaggregation, the routing\nschemes are executed using the fine-grid values.\n\nFollowing execution of the routing schemes the fine-grid values are\naggregated back to the native land surface model grid. The aggregation\nprocedure used is a simple linear average of the fine-grid components.\nFor example the aggregation of surface head (``SFHEAD``) from the fine grid\nto the native land surface model grid would be:\n\n.. rst-class:: center\n\n   :math:`{SFHEAD}_{i,j}\\  = \\ \\frac{\\Sigma\\Sigma\\ {SFHEADRT}_{irt,jrt}}{AGGFACTRT^2}`\n   (3.0)\n\nwhere, `i_{rt}` and `j_{rt}` are the indices of all of the grid\ncells residing within the native land model grid cell `i`,\\ `j`. The following\nvariables are aggregated and, where applicable, update land surface\nmodel variable values:\n\n   | SFHEAD - surface head (or, equivalently, depth of ponded water)\n   | SMC - soil moisture content for each soil layer\n\nThese updated values are then used on the next iteration of the land\nsurface model.\n\n3.3.2 User-Defined Mapping\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe emergence of hydrologic models, like WRF-Hydro, that are capable of\nrunning on gridded as well as vector-based processing units requires\ngeneric tools for processing input and output data as well as methods\nfor transferring data between models. Such a spatial transformation is\ncurrently utilized when mapping between model grids and catchments in\nthe WRF-Hydro/National Water Model (NWM) system. In the NWM, selected\nmodel fluxes are mapped from WRF-Hydro model grids onto the NHDPlus\ncatchment polygon and river vector network framework. The GIS\npre-processing framework described here allows for fairly generalized\ngeometric relationships between features to be characterized and for\nparameters to be summarized for any discrete unit of geography.\n\n3.3.3 Data Remapping for Hydrological Applications\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA common task in hydrologic modeling is to regrid or aggregate data from\none unit of analysis to another. Frequently, atmospheric model data\nvariables such as temperature and precipitation may be produced on a\nrectilinear model grid while the hydrologic unit of analysis may be a\ncatchment Hydrologic Response Unit (cHRU), defined using a closed\npolygon and derived from a hydrography dataset or terrain processing\napplication. Often, cHRU-level parameters must be derived from data on a\ngrid. Depending on the difference between the scale of the gridded and\nfeature data, simple interpolation schemes such as nearest neighbor may\nintroduce significant error when estimating data at the cHRU scale.\nOther GIS analysis methods such as zonal statistics require resampling\nof the gridded and/or feature data and limited control over the common\nanalysis grid resolution, which may also introduce significant error.\nArea-weighted grid statistics provide a robust and potentially\nconservative method for transferring data from one or multiple features\nto another. In the case of runoff calculated from a land surface model\ngrid, the runoff should be conservatively transferred between the grid\nand the cHRU, such that the runoff volume is conserved.\n\nThe correspondence between polygons and grid cells need only be\ngenerated once for any grid/polygon collection. The correspondence file\nthat is output from the tool stores all necessary information for\ntranslating data between the datasets in either direction.\n\nThere are a variety of useful regridding and spatial analysis tools\navailable for use in the hydrologic and atmospheric sciences. Many\nregridding utilities exist that are able to either characterize and\nstore the relationship between grid features and polygons or perform\nregridding from one grid to another. The Earth System Modeling Framework\n(ESMF) offers high performance computing (HPC) software for building and\ncoupling weather, climate, and related models. ESMF provides the\n:program:`ESMF_RegridWeightGen` utility for parallel generation of interpolation\nweights between two grid files in netCDF format. These utilities will\nwork for structured (rectilinear) and unstructured grids. The :program:`ESMF_RegridWeightGen`\ntool since can be accessed through python (through ESMPy) and the NCAR\nCommand Language (NCL, deprecated). Another commonly used tool in the atmospheric sciences\nare the Climate Data Operators (CDO), which offer 1\\ :sup:`st` and 2\\ :sup:`nd`\\-\norder conservative regridding (:program:`remapcon`, :program:`remapcon2`) and regrid weight\ngeneration (:program:`gencon`, :program:`gencon2`) based on the work of *Jones (1999)*. All of\nthe above-mentioned utilities require SCRIP grid description files to\nperform the remapping. The SCRIP standard format for correspondence\nstores geometry information for regridding, while the tools mentioned\nhere store just the spatial weights. Thus, WRF-Hydro spatial\ncorrespondence files are more generic, with compact file sizes, and may\nbe used for non-gridded data.\n\nThe WRF-Hydro geospatial pre-processing toolkit includes a script that\nquantifies the polygon to polygon correspondence between\ngeometries in two separate features (grid cells represented by polygons\nand basins represented by polygons). This correspondence is stored in a\nnetCDF format file that contains the spatial weights and identification\nof all polygons from one input shapefile that intersect each polygon in\nanother input shapefile. The storage of correspondence information\nbetween one dataset and another allows for many types of regridding and\nspatial interpolation between the spatial datasets. This file needs only\nto be derived once between any two sets of polygons, and the\ncorrespondence file can be used to regrid variables between those\nspatial datasets. This is useful if multiple variables must be\nregridded, or a single variable across many timesteps. As long as the\ngrids do not change in space or time, the relationship between all\nfeatures will remain constant, and the correspondence file may be used\nto regrid data between them.\n\nThere are uses for this utility that range outside of the hydrological\nsciences, and this utility may be of broader interest to the geospatial\ncommunity. Although interpolation packages exist, this method allows for\nstorage of the correspondence information for future use in a small-file\nsize. Users wanting to create custom spatial weight interpolation files\nfor WRF-Hydro need to refer to the *WRF-Hydro GIS Pre-processing\nToolkit* and documentation. For reference, variable descriptions of the\ncontents of the spatial weights file is located in :ref:`section-a13`.\n\n.. _figure3.3:\n.. figure:: media/user-defined-mapping.png\n   :align: center\n   :scale: 90%\n\n   **Figure 3.3.** An illustration of implementing user-defined mapping to\n   translate from gridded fluxes and states to aggregated catchment fluxes\n   and states, which can be passed into, for example, vector-based channel\n   routing modules.\n\n3.4 Subsurface Routing\n----------------------\n\nSubsurface lateral flow is calculated prior to the routing of overland\nflow. This is because exfiltration from a supersaturated soil column is\nadded to infiltration excess from the land surface model, which\nultimately updates the value of surface head prior to routing of\noverland flow. A supersaturated soil column is defined as a soil column\nthat possesses a positive subsurface moisture flux which when added to\nthe existing soil water content is in excess of the total soil water\nholding capacity of the entire soil column. Figure 3.4 illustrates the\nlateral flux and exfiltration processes in WRF-Hydro.\n\nIn the current default implementation of WRF-Hydro with the Noah and\nNoah-MP land surface models, there are four soil layers. The depth of\nthe soil layers in WRF-Hydro can be manually specified in the model\nnamelist file under the ``ZSOIL`` variable. Users must be aware that, in\nthe present version of WRF-Hydro, total soil column depth and individual\nsoil layer thicknesses are constant throughout the entire model domain.\nFuture versions under development are relaxing this constraint. However,\nthe model is capable of using a different distribution of soil column\nlayer depths and these simply need to be specified in the model namelist\nfile. Assuming a 2-m soil profile the default soil layer depths (and\nassociated water table depths) are specified in Table 3.1.\n\n.. table::  **Table 3.1: Depths of 4 soil layers in WRF-Hydro**\n   :align: center\n\n   +-------------+-------------------------+-----------------------------+\n   | **Layer**   | **Soil Thickness (mm)** | **Z (depth to top of layer) |\n   |             |                         | (mm)**                      |\n   +=============+=========================+=============================+\n   | 1           | 100                     | 0                           |\n   +-------------+-------------------------+-----------------------------+\n   | 2           | 300                     | 100                         |\n   +-------------+-------------------------+-----------------------------+\n   | 3           | 600                     | 400                         |\n   +-------------+-------------------------+-----------------------------+\n   | 4           | 1000                    | 1000                        |\n   +-------------+-------------------------+-----------------------------+\n\n.. _figure3.4:\n.. figure:: media/subsurface-flow.png\n   :align: center\n   :scale: 50%\n\n   **Figure 3.4** Conceptualization of saturated subsurface flow\n   components.\n\nThe method used to calculate the lateral flow of saturated soil moisture\nemploys a quasi three-dimensional flow representation, which include the\neffects of topography, saturated soil depth (in this case layers), and\nsaturated hydraulic conductivity. Hydraulic gradients are approximated\nas the slope of the water table between adjacent grid cells in the x-\nand y-directions or in an eight direction (D8) steepest descent\nmethodology that is specified by the user in the model namelist. In each\ncell, the flux of water from one cell to its down-gradient neighbor on\neach timestep is approximated as a steady-state solution. The looping\nstructure through the model grid performs flux calculations separately\nin the x- and y-directions for the 2-dimensional routing option or\nsimply along the steepest D8 pathway.\n\nUsing Dupuit-Forchheimer assumptions the rate of saturated subsurface\nflow at time `t` can be calculated as:\n\n.. _eqn3.1:\n.. rst-class:: center\n.. math::\n\n   {q}_{i,j} &= - T_{i,j}\\beta_{i,j}w_{i,j}\\ when\\ \\beta_{i,j}\\  < \\ 0 \\\\\n             &= 0\\ when\\ \\beta_{i,j} > = 0\n\n   (3.1)\n\nwhere, `q_{i,j}` is the flow rate from cell `(i,j)`, `T_{i,j}` is the\ntransmissivity of cell `(i,j)`, `\\beta_{i,j}` is the water table slope and\n`w_{i,j}` is the width of the cell which is fixed for a regular grid.\n`\\beta_{i,j}` is calculated as the difference in water table depths between\ntwo adjacent grid cells divided by the grid spacing. The method by which\nthe water table depth is determined is provided below. Transmissivity is\na power law function of saturated hydraulic conductivity (`Ksat_{i,j}`)\nand soil thickness (`D_{i,j}`) given by:\n\n.. _eqn3.2:\n.. rst-class:: center\n.. math::\n\n   T_{i,j} &= \\frac{{Ksat}_{i,j}D_{i,j}} {n_{i,j}} \\left( 1 - \\frac{z_{i,j}}{D_{i,j}} \\right)^{n_{i,j}}\\ when\\ z_{i,j} < = D_{i,j} \\\\\n           &= 0\\ when\\ z_{i,j} > D_{i,j}\n\n   (3.2)\n\nwhere, `z_{i,j}` is the depth to the water table. `n_{i,j}` in :ref:`Eq. (3.2) <eqn3.2>`\nis defined as the local power law exponent and is a tunable parameter that\ndictates the rate of decay of `Ksat_{i,j}` with depth (`n_{i,j}` has a default value of 1.0\nor can be specified as \"NEXP\" in hydro2dtbl.nc). When :ref:`Eq. (3.2) <eqn3.2>` is\nsubstituted into :ref:`Eq. (3.1) <eqn3.1>` the flow rate from cell `(i,j)`\nto its neighbor in the `x`-direction can be expressed as:\n\n.. _eqn3.3:\n.. rst-class:: center\n.. math::\n\n   q_{x(i,j)} = \\gamma_{x(i,j)} h_{i,j}\\ when\\ \\beta_{x(i,j)} < 0\n\n   (3.3)\n\nwhere,\n\n.. _eqn3.4:\n.. rst-class:: center\n.. math::\n\n   \\gamma_{x(i,j)} = - \\left( \\frac{w_{i,j}{Ksat}_{i,j}D_{i,j}}{n_{i,j}} \\right)\\beta_{x(i,j)}\n\n   (3.4)\n\n.. _eqn3.5:\n.. rst-class:: center\n.. math::\n\n   h_{i,j} = \\left( 1-\\frac{z_{i,j}}{D_{i,j}} \\right)\n\n   (3.5)\n\nThis calculation is repeated for the y-direction when using the\ntwo-dimensional routing method. The net lateral flow of saturated\nsubsurface moisture (`Q_{net}`) for cell `(i,j)` then becomes:\n\n.. _eqn3.6:\n.. rst-class:: center\n.. math::\n\n   Q_{net(i,j)} = h_{i,j} \\sum_x{\\gamma_{x(i,j)}} + h_{i,j} \\sum_y{\\gamma_{y(i,j)}}\n\n   (3.6)\n\nThe mass balance for each cell on a model time step (`\\Delta t`) can then be\ncalculated in terms of the change in depth to the water table (`\\Delta z`):\n\n.. _eqn3.7:\n.. rst-class:: center\n.. math::\n\n   \\Delta z = \\frac{1}{\\phi_{(i,j)}} \\left[ \\frac{Q_{net(i,j)}}{A} - R_{(i,j)} \\right] \\Delta t\n\n   (3.7)\n\nwhere, `\\phi` is the soil porosity, `R` is the soil column recharge rate\nfrom infiltration or deep subsurface injection and *A* is the grid cell\narea. In WRF-Hydro, `R`, is implicitly accounted for during the land\nsurface model integration as infiltration and subsequent soil moisture\nincrease. Assuming there is no deep soil injection of moisture (i.e.\npressure driven flow from below the lowest soil layer), `R`, in\nWRF-Hydro is set equal to 0.\n\nThe methodology outlined in Equations :ref:`3.2 <eqn3.2>` thru :ref:`3.7 <eqn3.7>`\nhas no explicit information on soil layer structure, as the method treats\nthe soil as a single homogeneous column (with an assumed exponential decay of\nsaturated hydraulic conductivity). Therefore, changes in water table\ndepth (`\\Delta z`) need to be remapped to the land surface model soil layers.\nWRF-Hydro specifies the water table depth according to the depth of the\ntop of the highest (i.e. nearest to the surface) saturated layer. The\nresidual saturated water above the uppermost, saturated soil layer is\nthen added to the overall soil water content of the overlying\nunsaturated layer. This computational structure requires accounting\nsteps to be performed prior to calculating `Q_{net}`.\n\nGiven the timescale for groundwater movement and limitations in the\nmodel structure there is significant uncertainty in the time it takes to\nproperly spin-up groundwater systems. The main things to consider\ninclude 1) the specified depth of soil and number and thickness of the\nsoil vertical layers and 2) the prescription of the model bottom\nboundary condition. Typically, for simulations with deep soil profiles\n(e.g. > 10 `m`) the bottom boundary condition is set to a ‘no-flow’\nboundary (``SLOPE_DATA = 0.0`` in the :file:`GENPARM.TBL` parameter file\nor ``slope = 0.0`` in the :file:`soil_properties.nc` spatially distributed\nparameter file). See Appendices :ref:`section-a6` and :ref:`section-a7` for a\ndescription of :file:`GENPARM.TBL` and :file:`soil_properties.nc`.\n\n.. note::\n   Currently subsurface routing is only supported in the steepest slope (D8) formulation.\n   The 2-dimensional solution will be reactivated in a future release.\n\n.. rubric:: Relevant code modules:\n\n:file:`Routing/Noah_distr_routing_subsurface.F90`\n\n.. rubric:: Relevant namelist options:\n\n:file:`hydro.namelist`:\n\n-  ``SUBRTSWCRT`` - Switch to activate subsurface flow routing.\n\n-  ``DXRT`` - Specification of the routing grid cell spacing\n\n-  ``AGGFACTR`` - Subgrid aggregation factor, defined as the ratio of the\n   subgrid resolution to the native land model resolution\n\n:file:`namelist.hrldas`:\n\n-  ``NOAH_TIMESTEP`` - Subsurface routing operates on the LSM timestep\n\n.. rubric:: Relevant domain and parameter files/variables:\n\n-  ``TOPOGRAPHY`` in :file:`Fulldom_hires.nc` - Terrain grid or Digital Elevation\n   Model (DEM). Note: this grid may be provided at resolutions equal to\n   or finer than the native land model resolution.\n\n-  ``LKSATFAC`` in :file:`Fulldom_hires.nc` - Multiplier on saturated hydraulic\n   conductivity in lateral flow direction.\n\n-  ``SATDK``, ``SMCMAX``, ``SMCREF`` in :file:`HYDRO.TBL` or :file:`hydro2dtbl.nc` - Soil properties\n   (saturated hydraulic conductivity, porosity, field capacity) used in\n   lateral flow routing.\n\n-  ``NEXP`` in :file:`hydro2dtbl.nc` - Local power law exponent that\n   dictates the rate of decay of saturated hydraulic conductivity with depth.\n\n.. _section-3.5:\n\n3.5 Surface Overland Flow Routing\n---------------------------------\n\nOverland flow in WRF-Hydro is calculated using a fully-unsteady,\nexplicit, finite-difference, diffusive wave formulation similar to that\nof *Julien et al. (1995)* and *Ogden et al. (1997)*. The diffusive wave\nequation, while slightly more complicated, is, under some conditions,\nsuperior to the simpler and more traditionally used kinematic wave\nequation, because it accounts for backwater effects and allows for flow\non adverse slopes. The overland flow routine described below can be\nimplemented in either a 2-dimensional (x and y direction) or 1-dimension\n(steepest descent or “D8”) method. While the 2-dimensional method may\nprovide a more accurate depiction of water movement across some complex\nsurfaces it is more expensive in terms of computational time compared\nwith the 1-dimensional method. While the physics of both methods are\nidentical we have presented the formulation of the flow in equation form\nbelow using the 2-dimensional methodology.\n\n.. figure:: media/overland-flow.png\n   :align: center\n   :scale: 50%\n\n   **Figure 3.5:** Conceptual representation of terrain elements. Flow is\n   routed across terrain elements until it intersects a “channel” grid cell\n   indicated by the blue line where it becomes “in-flow” to the stream\n   channel network.\n\nThe diffusive wave formulation is a simplification of the more general\nSt. Venant equations of continuity and momentum for a shallow water\nwave. The two-dimensional continuity equation for a flood wave flowing\nover the land surface is:\n\n.. _eqn3.8:\n.. rst-class:: center\n.. math::\n\n   \\frac{\\partial h}{\\partial t} + \\frac{\\partial q_x}{\\partial x} + \\frac{\\partial q_y}{\\partial x} = i_e\n\n   (3.8)\n\nwhere, `h` is the surface flow depth; `q_x` and `q_y` are the unit\ndischarges in the `x`- and `y`-directions, respectively; and `i_e` is the\ninfiltration excess. The momentum equation used in the diffusive wave\nformulation for the `x`-dimension is:\n\n.. _eqn3.9:\n.. rst-class:: center\n.. math::\n\n   S_{fx} = S_{ox} - \\frac{\\partial h}{\\partial x}\n\n   (3.9)\n\nwhere, `S_fx` is the friction slope (or slope of the energy grade line)\nin the x-direction, `S_ox` is the terrain slope in the `x`-direction and\n`\\partial h/\\partial x` is the change in depth of the water surface above the land\nsurface in the `x`-direction.\n\nIn the 2-dimensional option, flow across the terrain grid is calculated\nfirst in the `x`- then in the `y`-direction. In order to solve :ref:`Eq. 3.8 <eqn3.8>`\nvalues for `q_x` and `q_y` are required. In most hydrological models\nthey are typically calculated by the use of a resistance equation such\nas Manning's equation or the Chezy equation, which incorporates the\nexpression for momentum losses given in :ref:`Eq. 3.9 <eqn3.9>`.\nIn WRF-Hydro, a form of Manning's equation is implemented:\n\n.. _eqn3.10:\n.. rst-class:: center\n.. math::\n\n   q_x = \\alpha_x h^\\beta\n\n   (3.10)\n\nwhere,\n\n.. _eqn3.11:\n.. rst-class:: center\n.. math::\n\n   \\alpha_x = \\frac{S_{fx}^{1/2}}{n_{OV}}; \\qquad \\beta = \\frac{5}{3}\n\n   (3.11)\n\nwhere, `n_{OV}` is the roughness coefficient of the land surface and is a\ntunable parameter and `\\beta` is a unit-dependent coefficient expressed here\nfor SI units.\n\nThe overland flow formulation has been used effectively at fine terrain\nscales ranging from 30-300 `m`. There has not been rigorous testing to\ndate, in WRF-Hydro, at larger length-scales (> 300 `m`). This is due to\nthe fact that typical overland flood waves possess length scales much\nsmaller than 1 `km`. Micro-topography can also influence the behavior of a\nflood wave. Correspondingly, at larger grid sizes (e.g. > 300 `m`) there\nwill be poor resolution of the flood wave and the small-scale features\nthat affect it. Also, at coarser resolutions, terrain slopes between\ngrid cells are lower due to an effective smoothing of topography as grid\nsize resolution is decreased. Each of these features will degrade the\nperformance of dynamic flood wave models to accurately simulate overland\nflow processes. Hence, it is generally considered that finer resolutions\nyield superior results.\n\nThe selected model time step is directly tied to the grid resolution. In\norder to prevent numerical diffusion of a simulated flood wave (where\nnumerical diffusion is the artificial dissipation and dispersion of a\nflood wave) a proper time step must be selected to match the selected\ngrid size. This match is dependent upon the assumed wave speed or\ncelerity (`c`). The Courant Number, `C_n = c(\\Delta t/\\Delta x)`, should be\nclose to 1.0 in order to prevent numerical diffusion. The value of the\n`C_n` also affects the stability of the routing routine such that\nvalues of `C_n` should always be less than 1.0. Therefore the\nfollowing model time steps are suggested as a function of model grid\nsize as shown in Table 3.2.\n\n.. table::\n   **Table 3.2:** Suggested routing time steps for various grid spacings\n   :align: center\n   :width: 50%\n\n   +---------+---------+\n   | X (`m`) | T (`s`) |\n   +=========+=========+\n   | 30      | 2       |\n   +---------+---------+\n   | 100     | 6       |\n   +---------+---------+\n   | 250     | 15      |\n   +---------+---------+\n   | 500     | 30      |\n   +---------+---------+\n\n\nWRF-Hydro also includes an impervious surface adjustment option for overland routing. If this\nscheme is activated (``imperv_adj = 0`` in :file:`hydro.namelist`) then the overland roughness\nManning's coefficient and maximum retention depth are adjusted based on the impervious fraction\nprovided as ``IMPERVFRAC`` in :file:`Fulldom_hires.nc`. Specifically, maximum retention depth\nis multiplied by (1 - ``IMPERVFRAC``) (so smaller values for higher imperviousness). Manning's\nroughness for overland routing is scaled based on a linear weighting of smoothness\n(1/roughness, see Liong et al. 1989) and assuming a roughness of 0.02 for impervious and native\ncell roughness for pervious:\n\nOVROUGHRT = 1 / ((1/0.02)*impervfrac + (1/OVROUGHRT)*(1-impervfrac))\n\n\n.. rubric:: Relevant code modules:\n\n:file:`Routing/Noah_distr_routing_overland.F90`\n\n.. rubric:: Relevant namelist options:\n\n`hydro.namelist`:\n\n-  ``OVRTSWCRT`` - Switch to activate overland flow routing.\n\n-  ``DXRT`` - Specification of the routing grid cell spacing\n\n-  ``AGGFACTR`` - Subgrid aggregation factor, defined as the ratio of the\n   subgrid resolution to the native land model resolution\n\n-  ``DTRT_TER`` - Overland routing grid time step\n\n-  ``rt_option`` - Overland flow routing option (steepest descent or 2-dimensional)\n\n.. rubric:: Relevant domain and parameter files/variables:\n\n-  ``TOPOGRAPHY`` in :file:`Fulldom_hires.nc` - Terrain grid or Digital Elevation\n   Model (DEM). Note: this grid may be provided at resolutions equal to\n   or finer than the native land model resolution.\n\n-  ``RETDEPRTFAC`` in :file:`Fulldom_hires.nc` - Multiplier on maximum retention\n   depth before flow is routed as overland flow.\n\n-  ``OVROUGHRTFAC`` in :file:`Fulldom_hires.nc` - Multiplier on Manning's roughness\n   for overland flow.\n\n-  ``OV_ROUGH`` in :file:`HYDRO.TBL` or ``OV_ROUGH2D`` in\n   :file:`hydro2dtbl.nc` - Manning's roughness for overland flow (by\n   default a function of land use type).\n\n\n.. _section-3.6:\n\n3.6 Channel Routing\n----------------------------\n\nThere are multiple channel routing algorithms available in version |version_short|\nof WRF-Hydro. These algorithms operate either on the resolution of the\nfine grid (gridded routing) or on a vectorized network of channel\nreaches (linked routing, also referred to as reach-based routing), which\nmaps the fine grid to the vector network (:ref:`Figure 3.6 <figure3.6>`).\nThe following section describes the routing methods and their\nimplementation in the WRF-Hydro model code.\n\nIn general, inflow to the channel is based on a mass balance\ncalculation, where the channel routes water when the ponded water depth\n(or surface head, `SFCHEADRT`) of the channel grid cells exceeds a\npredefined retention depth (`RETDEPRT`). As described in `Section\n3.5 <#surface-overland-flow-routing>`__, the depth of surface head on\nany grid cell is a combination of the local infiltration excess, the\namount of water flowing onto the grid cell from overland flow, and\nexfiltration from groundwater flow. The quantity of surface head in\nexcess of the retention depth is accumulated as stream channel inflow\nand is effectively “discharged” to the channel routing routine\n(described below). In the current code, `RETDEPRT` is hard-coded to\n5mm for channel pixels to encourage more local infiltration near the\nriver channel leading to wetter soils that better emulate riparian\nconditions. Values of “channel inflow” are accumulated on the channel\ngrid and can be output for visualization and analysis\n(see :ref:`Section 6 <section-6.0>` for a description of model outputs).\n\n.. _figure3.6:\n.. figure:: media/channel-routing-grid-link.png\n   :align: center\n\n   **Figure 3.6** Channel routing via the high resolution grid (left) or on\n   a vector/link network (right).\n\nThe channel routing module :file:`module_channel_routing.F90` allows for the\none-dimensional, distributed routing of streamflow across the domain. An\noptional, switch-activated, level-pool lake/reservoir algorithm is also\navailable and is described below in Sections :ref:`3.7 <section-3.7>`\nand :ref:`3.8 <section-3.8>`. Within each channel grid cell there is an\nassumed channel reach of trapezoidal geometry as depicted in Figure 3.7.\nChannel parameters side slope (`z`), bottom width (`B_w`) and roughness (`n`)\nare currently prescribed as functions of Strahler stream order for defaults.\nDetails on how each routing method reads these parameters are specified\nin the subsections below.\n\n.. _figure3.7:\n.. figure:: media/channel-terms.png\n   :align: center\n   :figwidth: image\n\n   **Figure 3.7** Schematic of Channel Routing Terms\n\n.. table::\n   :align: center\n\n   +---------------------------------+------------------+\n   | Channel Slope                   | `S_o`            |\n   +---------------------------------+------------------+\n   | Channel Length                  | `\\Delta x` (`m`) |\n   +---------------------------------+------------------+\n   | Channel side slope              | `z` (`m`)        |\n   +---------------------------------+------------------+\n   | Constant bottom width           | `B_w` (`m`)      |\n   +---------------------------------+------------------+\n   | Manning's roughness coefficient | (`n`)            |\n   +---------------------------------+------------------+\n\nAs discussed above, channel elements receive lateral inflow from\noverland flow. There is currently no overbank flow back to the\nfine-grid, so flow into the channel model is effectively one-way.\nTherefore, WRF-Hydro does not explicitly represent inundation areas from\noverbank flow from the channel back to the terrain. This will be an\nupcoming enhancement, though currently there are methods for\npost-processing an inundation surface. Uncertainties in channel geometry\nparameters and the lack of an overbank flow representation result in a\nmeasure of uncertainty for users wishing to compare model flood\ninundation versus those from observations. It is strongly recommended\nthat users compare model versus observed streamflow discharge values and\nuse observed stage-discharge relationships or “rating curves” when\nwishing to relate modeled/predicted streamflow values to actual river\nlevels and potential inundation areas.\n\n.. rubric:: Relevant code modules:\n\n:file:`Routing/module_channel_routing.F90`\n\n.. rubric::  Relevant namelist options for gridded and reach-based routing:\n\n`hydro.namelist`:\n\n-  ``CHANRTSWCRT`` - Switch to activate channel routing.\n\n-  ``channel_option`` - Specification of the type of channel routing to\n   activate\n\n-  ``DTRT_CH`` - Channel routing time step, applies to both gridded and\n   reach-based channel routing methods\n\n-  ``route_link_f`` (optional) - a :file:`Route_Link.nc` file is required for\n   reach-based routing methods. Example header in :ref:`Appendix A9 <section-a9>`.\n\n3.6.1. Gridded Routing using Diffusive Wave\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nChannel flow down through the gridded channel network is performed using\nan explicit, one-dimensional, variable time-stepping diffusive wave\nformulation. As mentioned above the diffusive wave formulation is a\nsimplification of the more general St. Venant equations for shallow\nwater wave flow. Similarly, for channel routing, the mass and momentum\ncontinuity equations are given as:\n\n   Continuity:\n\n.. math::\n   \\frac{\\partial A}{\\partial t} + \\frac{\\partial Q}{\\partial x} = q_{lat}\n   \\qquad (3.12)\n\n\\\n   Momentum:\n\n.. math::\n   \\frac{\\partial Q}{\\partial t} + \\frac{\\partial(\\beta Q^2 / A)}{\\partial x} +\n   gA\\frac{\\partial Z}{\\partial x} = -gAS_f\n   \\qquad (3.13)\n\nWhere `t` is the time, `x` is the streamwise coordinate, `A` is\nin the flow area of the cross section, and `q_{lat}` is the lateral\ninflow rate into the channel. In the momentum equation, `Q` is the flow\nrate, `\\beta` is a momentum correction coefficient, `Z` is the water surface\nelevation, `g` is gravity and `S_f` is the friction slope which is\ncomputed as:\n\n.. math::\n   S_f = \\left( \\frac{Q}{K} \\right)^2\n   \\qquad (3.14)\n\nwhere `K` is the conveyance, computed from the Manning's equation:\n\n.. math::\n   K = \\frac{C_m}{n} AR^{2/3}\n   \\qquad (3.15)\n\nwhere `n` is the Manning's roughness coefficient, `A` is the\ncross-sectional area, `R` is the hydraulic radius (`A/P`), `P` is the\nwetted perimeter, and `C_m` is dimensional constant (1.486 for English\nunits or 1.0 for SI units).\n\nIgnoring the convective term, the second term in the momentum equation\ngives the diffusive wave approximation of open channel flow. The\nmomentum equation then simplifies to:\n\n.. math::\n   Q = -SIGN \\left( \\frac{\\partial Z}{\\partial x} \\right) K \\sqrt{\\left| \\frac{\\partial z}{\\partial x}\\right |}\n   \\qquad (3.16)\n\nwhere the substitution for friction slope has been made and the `SIGN`\nfunction is `1` for `\\partial Z / \\partial x > 0` and `-1` for `\\partial Z / \\partial x < 0`.\n\nThe numerical solution is obtained by discretizing the continuity\nequation over a raster cell as:\n\n.. math::\n   A^{n+1} - A^n = \\frac{\\Delta t}{\\Delta x} \\left( Q^n_{i+\\frac{1}{2}} - Q^n_{i-\\frac{1}{2}} \\right)\n   + \\Delta tq^n_{lat}\n   \\qquad (3.17)\n\nwhere `Q^n_{i+\\frac{1}{2}}` is the flux across the cell face between point `i` and\n`i+1`, and is computed as:\n\n.. math::\n   Q^n_{i+\\frac{1}{2}} = -SIGN\\left(\\Delta Z^n_{i+1}\\right) K_{i+\\frac{1}{2}}\n   \\sqrt{\\frac{\\left|\\Delta Z^n_{i+1}\\right|}{\\Delta x}}\n   \\qquad (3.18)\n\nwhere:\n\n.. math::\n   \\Delta Z^n_{i+1} = Z^n_{i+1} - Z^i &\\qquad (3.19) \\\\\n   K^n_{i+\\frac{1}{2}} = \\frac{1}{2} \\left( 1 + SIGN\\left(\\Delta Z^n_{i+1}\\right)\\right) K_i\n   + \\left( 1- SIGN\\left( \\Delta Z^n_{i+1} \\right)\\right) K_{i+1} &\\qquad (3.20)\n\nA first-order, Newton-Raphson (N-R) solver is used to integrate the\ndiffusive wave flow equations. Under certain streamflow conditions (e.g.\ntypically low gradient channel reaches) the first-order solver method\ncan produce some instabilities resulting in numerical oscillations in\ncalculated streamflow values. To address this issue, higher order solver\nmethods will be implemented in future versions of WRF-Hydro.\n\nUnlike typical overland flow flood waves which have very shallow flow\ndepths, on the order of millimeters or less, channel flood waves have\nappreciably greater flow depths and wave amplitudes, which can\npotentially result in strong momentum gradients and strong accelerations\nof the propagating wave. To properly characterize the dynamic\npropagation of such highly variable flood waves it is often necessary to\ndecrease model time-steps in order to satisfy Courant conditions.\nTherefore WRF-Hydro utilizes variable time-stepping in the diffusive\nwave channel routing module in order to satisfy Courant constraints and\navoid numerical dispersion and instabilities in the solutions. The\ninitial value of the channel routing time-step is set equal to ``DTRT_CH``\n(which should be estimated based on the grid cell size, as for overland routing).\nIf, during model integration the N-R convergence criteria for\nupstream-downstream streamflow discharge values is not met, the channel\nrouting time-step is decreased by a factor of one-half and the N-R\nsolver is called again.\n\nIt is important to note that the use of variable time-stepping can\naffect model computational performance resulting in slower solution\ntimes for rapidly evolving streamflow conditions such as those occurring\nduring significant flood events. Therefore, selection of the time-step\ndecrease factor (default value set to 0.5) and the N-R convergence\ncriteria can each affect model computational performance.\n\nUncertainty in channel routing parameters can also impact the accuracy\nof the model solution which implies that model calibration is often\nrequired upon implementation in a new domain. Presently, all of the\nchannel routing parameters are prescribed as functions of stream order\nin a channel routing parameter table :file:`CHANPARM.TBL`. The structure of this\nfile is described in detail in Appendix :ref:`A9 <section-a9>`.\nIt should be noted that prescription of channel flow parameters as\nfunctions of stream order is likely to be a valid assumption over\nrelatively small catchments and not over large regions.\n\n.. _section-3.6.2:\n\n3.6.2. Reach Routing using Muskingum and Muskingum-Cunge\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe gridded catchment and drainage network of the land surface model\n(Noah/Noah-MP LSM) are mapped to the one-dimensional vectorized channel\nnetwork, with a unique set of channel properties defined as constant for\neach reach. The flow out of each channel reach is determined based on\nflow hydraulics, channel storage and the lateral inflow contribution\nfrom each grid cell that is mapped to the individual reach element. Since\nreach lengths are not constant, the number of contributing grid cells to\nthe reach depend on the reach length (:ref:`Figure 3.6 <figure3.6>`).\nFlow is assumed always upstream-to-downstream, and channel junctions\naccommodate the merging of flows through the reach network. The simultaneous\ntransformation of the often complex drainage network, source areas, and\nchannel flow hydrographs in these large, complex networks necessitates\na practical and efficient solution to the routing problem (*Brunner and\nGorbrecht, 1991*).\n\nOn the reach network, WRF-Hydro makes use of a fairly standard\nimplementation of the Muskingum-Cunge (MC) method of hydrograph routing\nwhich makes use of time varying parameter estimates. The scheme is a\npractical approach to characterize watershed runoff characteristics over\nlarge network, large watershed flow integration. But as a\none-dimensional explicit scheme, it does not allow for backwater or\nlocalized effects. Channel flows are routed upstream to downstream in a\ncascade routing manner (*Gunner and Gorbetch, 1991*) with the assumption\nthat there are negligible backwater effects. The MC routing scheme\nrelates inflow and outflow using a storage relationship, where:\n\n.. math::\n   S = K[XI + (1-X) Q] \\qquad (3.21)\n\nwhere X is a weighting factor with a range of` 0 ≤ X ≤ 0.5`, where `X`\nrange from `0` for reservoir-type storage, while an advancing floodwave\nproduces a wedge of storage and thus a value of `X` greater than `0` (*Chow\net al., 1982*). The finite difference formulation of the storage\nrelationship results in the Muskingum Equation,\n\n.. math::\n   Q_{d}^{c} = \\ C1{\\ Q}_{u}^{p}\\  + \\ C2\\ Q_{u}^{c}\\  + \\ {C3Q}_{d}^{p}\\  + \\left( \\frac{\\ q_{l}\\ dt}{D} \\right)\n   \\qquad (3.22)\n\nwhere `D = K(1-X)+ dt/2` and is the wedge storage contribution from\nlateral inflow in the reach. The subscript are `u` and `d` are the\nupstream and downstream nodes of each reach, respectively; and the `p`\nand `c` superscript are the previous and current time step,\nrespectively.\n\n.. _figure3.8:\n.. figure:: media/channel-props.svg\n   :align: center\n   :scale: 150%\n\n   **Figure 3.8** Channel Properties\n\nStatic hydraulic properties are used to describe the properties of each\nchannel reach, with each being assumed trapezoidal and include bottom\nwidth (`B_w``), channel length (`dx`), channel top width before bankfull\n(`Tw`), Manning's roughness coefficient (`n`), channel side slope (`z`,\nin meters), and the longitudinal slope of the channel (`So`). If a user\nis running the model with reach-based routing (``channel_option`` =\n``1`` or ``2``), the `B_w` , `n`, and `z` parameters can be modified\nthrough the :file:`Route_Link.nc` file. Note: the :file:`CHANPARM.TBL`\nfile will not be used in this configuration.\n\nSimulated state variables include estimate of mean water depth in the\nchannel (`h`), steady-state velocity (`v`) and flow rate (`q`) in the\nreach at the current timestep. An initial depth estimate is made based\non the depth from the previous time step. Time varying properties\ninclude the hydraulic area, `Area = (B_w*h*z)*h; (3.23)`, the wetted\nperimeter `W_p= (B_w + 2 * \\sqrt{1+z^2}); (3.24)`, and the hydraulic radius,\n`R=Area/W_p; (3.25)`. With an initial estimate of water depth in the channel,\nthe wave celerity for the trapezoidal channel is estimated as:\n\n.. math::\n   Ck = \\sqrt{\\frac{So}{n}} \\frac{5}{3}R^{\\frac{2}{3}} -\n   \\frac{2}{3}R^{\\frac{5}{3}}*\\left(2*\\sqrt{\\frac{1+z^2}{B_w + 2hz}}\\right)\n   \\qquad (3.26)\n\nWave celerity is used to estimate the MC routing parameters, where *K=*\n*dx/c\\ k* (3.27) is the time required for an incremental flood wave to\npropagate through the channel reach, and the storage shape weighting\nfactor is given as, *X* =\n:math:`\\frac{1}{2}\\left( 1 - \\frac{Q}{(Tw{\\ c}_{k}\\ So\\ dx} \\right)` ,\n(3.28) where *Q* is the estimated discharge, *T\\ w* is the water surface\nwidth, *S\\ o* is the channel slope and *dx* is the channel length.\n\n.. rubric:: Relevant domain and parameter files/variables:\n\n-  ``TOPOGRAPHY`` in :file:`Fulldom_hires.nc` - Terrain grid or Digital Elevation\n   Model (DEM). Note: this grid may be provided at resolutions equal to\n   or finer than the native land model resolution.\n\n-  ``CHANNELGRID`` in :file:`Fulldom_hires.nc` - Channel network grid identifying\n   the location of stream channel grid cells\n\n-  ``STREAMORDER`` in :file:`Fulldom_hires.nc` - Strahler stream order grid\n   identifying the stream order for all channel pixels within the\n   channel network.\n\n-  ``FLOWDIRECTION`` in :file:`Fulldom_hires.nc` - Flow direction grid, which\n   explicitly defines flow directions along the channel network in\n   gridded routing. This variable dictates where water flows into\n   channels from the land surface as well as in the channel. This should\n   not be modified independently because it is tied to the DEM.\n\n-  ``frxst_pts`` (optional) in :file:`Fulldom_hires.nc` - Forecast point grid, which\n   specified selected channel pixels for which channel discharge and\n   flow depth are to be output within a netcdf point file (CHANOBS)\n   and/or an ASCII timeseries file (frxstpts_out.txt).\n\n-  :file:`CHANPARM.TBL` text or :file:`Route_Link.nc` netcdf file - Specifies channel\n   parameters by stream order (:file:`CHANPARM.TBL`, for gridded channel\n   routing) or individual reaches (``route_link_f``, for reach-based routing\n   methods)\n\n.. note:: Reach-based routing is highly sensitive to time step.\n\n3.6.3 Compound Channel (limited configuration)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn order to represent a simplification of the behavior of a flood wave\nwhen it exceeds the channel bank, a compound channel formulation was\nadded to WRF-Hydro. This option is currently only available when\n``channel_option=2`` and ``udmp=1`` (so using user-defined mapping with\nthe Muskingum-Cunge reach-based channel routing scheme).\nA visual representation is shown in Figure 3.9. When the depth of the\nflow exceeds bankfull (`d > d_b`), then the wave celerity is given\nas the weighted celerity of the trapezoidal flow and the overbank\nportion of flow. This weighting is based on the cross-sectional area of\neach, and allows water to enter the conceptual compound channel, where\nthe Manning's coefficient of the compound channel portion, `n_{cc}`,\nis assumed rougher than the channel `n` by an unknown factor,\n`n_{cc}`. Based on a set of sensitivity experiments described in\n*Read et al., (2023)*, the default value is\n`n_{cc}=2n`, such that the floodplain roughness is twice that of\nthe channel. The introduction of compound channel requires values for\nthree more parameters: bankfull depth (`d_b`), top widths of the\ntrapezoid and the compound channel, `T_w` and `T_{w\\_cc},`\nrespectively. These parameters, in addition to `n_{cc}`, are defined\nin the Route_Link.nc file. The default values were\ndetermined using a published equation from\n*Blackburn-Lynch et al., 2017*, who gathered regional USGS estimations of\nchannel parameters and developed coefficients to describe the\nrelationship of drainage area (`DA`) to `T_w` and to channel area\n(`A`). The aggregated CONUS equation is: `T_w = 2.44(DA)^{0.34}`\nand `A = 0.75(DA)^{0.53}`. Given these, `d_b` is determined\nusing the standard equation for a trapezoid. As a default value,\n`T_{w\\_cc}` is a multiplier on `T_w`. Sensitivity experiments\npresented in *Read et al. (2023)* found that `T_{w\\_cc}=3*T_w`\nyielded the best streamflow performance, all else being equal.\n\n.. _figure3.9:\n.. figure:: media/trapezoid-compound-channel.png\n   :align: center\n   :scale: 50%\n\n   **Figure 3.9** Cross-sectional schematic of trapezoidal channel and compound\n   channel in National Water Model, where the dashed lines represent roughness\n   of the channel n, and of the compound channel, `n_{cc}`\n\n.. note:: The compound channel option is currently only available when\n   ``channel_option=2`` and ``udmp=1`` (so using user-defined mapping with\n   the Muskingum-Cunge reach-based channel routing scheme).\n\n.. _section-3.7:\n\n3.7 Lake and Reservoir Routing Description\n------------------------------------------\n\nA simple mass balance, level-pool lake/reservoir routing module allows\nfor an estimate of the inline impact of small and large reservoirs on\nhydrologic response. A lake/reservoir or series of lakes/reservoirs are\nidentified in the channel routing network, and lake/reservoir storage\nand outflow are estimated using a level-pool routing scheme. The only\nconceptual difference between lakes and reservoirs as represented in\nWRF-Hydro is that reservoirs contain both orifice and weir outlets for\nreservoir discharge while lakes only contain weirs. Note that the user\nmust adjust these parameters accordingly - the model makes no other\ndistinction between a reservoir and a lake.\n\nFluxes into a lake/reservoir object occur through the channel network\nand when surface overland flow intersects a lake object (in the gridded\nchannel routing configuration only). Fluxes from\nlake/reservoir objects are made only through the channel network and no\nfluxes from lake/reservoir objects to the atmosphere or the land surface\nare currently represented (i.e. there is currently no lake evaporation\nor subsurface exchange between the land surface and lakes and\nreservoirs). The Level Pool scheme tracks water elevation changes over\ntime, `h(t)` where water from the reservoir can exit either through weir\noverflow (`Q_w`) and/or a gate-controlled flow (`Q_o`), where\nthese outflows are functions of the water elevation and spillway\nparameters. Weir flow is given as `Q_w(t) = C_wLh^{\\frac{3}{2}}; (3.29)`\nwhen `h>h_{max}` or `Q_w(t) = 0.0` when `h≤h_{max}` where, `h_{max}` is\nthe maximum height before the weir begins to spill (`m`), `C_w` is a weir\ncoefficient, and `L` is the length of the weir (`m`). Orifice flow is\ngiven as `Q_o(t) = C_oO_a\\sqrt{2gh}; (3.30)` where `C_o` is the orifice\ncoefficient, `O_a` is the orifice area (`m^2`), and `g` is the\nacceleration of gravity (`m/s^2`). In addition, the level pool scheme\nis designed to track each reservoir's surface area, `S_a` (`km^2`) as\na function of water depth and the area at full storage, `A_s`\n(`km^2`). Presently, a lake/reservoir object is assumed to have\nvertical side walls, such that the surface area is always constant.\n\n.. _figure-3.10:\n.. figure:: media/level-pool.png\n   :align: center\n   :scale: 40%\n.. rst-class:: center\n.. math::\n\n   S_a(t) &= f(h, A_s) \\\\\n   Q_t(t) &= f(h)\n\n.. rst-class:: center\n\n   **Figure 3.10** Schematic of Level Pool Routing\n\nThe lake/reservoir parameters listed below are required for level-pool\nrouting and are defined in the :file:`LAKEPARM.nc` parameter file. The GIS\npre-processing tool can make this file and the model will\nread it as specified in the :file:`hydro.namelist` file.\n\n   -  Weir and Orifice Coefficients, `Cw`, `Co` in equations above or ``WeirC``, ``OrificeC`` in :file:`LAKEPARM.nc`\n   -  Weir Length (`m`), `L` in equations above or ``WeirL`` in :file:`LAKEPARM.nc`\n   -  Weir Elevation (`m`), ``WeirE`` in :file:`LAKEPARM.nc`\n   -  Orifice Area (`m^2`), `O_a` in equations above or ``OrificeA`` in :file:`LAKEPARM.nc`\n   -  Orifice Elevation (`m`), ``OrificeE`` in :file:`LAKEPARM.nc`\n   -  Reservoir Area (`km^2`), `A_s` in equations above or ``LkArea`` in :file:`LAKEPARM.nc`\n   -  Maximum reservoir height at full storage (`m`), `h_{max}` in equations above or ``LkMxE`` in :file:`LAKEPARM.nc`\n   -  Dam length specified as a multiplier on weir length (`dimensionless`), `Dam_Length` in :file:`LAKEPARM.nc`\n\nFor the gridded channel routing option, the lake/reservoir routing options\nrequire lake objects to be defined and properly indexed as a data\nfield in the high resolution terrain routing :file:`Fulldom_hires.nc`\nfile. If lake/reservoir objects are present in the\nlake grid (and also within the channel network) then level-pool routing through\nthose objects will occur if ``CHANRTSWCRT = 1`` (channel is active), ``channel_option\n= 3`` (gridded routing), and ``lake_option = 1`` (level pool) in :file:`hydro.namelist`.\n\nFor reach-based channel routing options, the lake/reservoir routing options\nrequire lake objects to be defined  and properly indexed as waterbody  objects\nin the :file:`Route_Link.nc` file.\nIf lake/reservoir objects are present in the\n:file:`Route_Link.nc` file then level-pool routing through\nthose objects will occur if ``CHANRTSWCRT = 1`` (channel is active), ``channel_option\n= 1 or 2`` (reach routing), and ``lake_option = 1`` (level pool) in :file:`hydro.namelist`.\n\nThe ``lake_option`` in :file:`hydro.namelist` can also be used to turn off lake/reservoir\nrouting completely (``lake_option = 0``), set the waterbodies to simply pass water through\nfrom inflow to outflow with no storage or delay (``lake_option = 2``), or activate data\nassimilation (specific to the NOAA National Water Model and not currently\nsupported outside of that configuration).\n\nThere are several special requirements for the\nlake and channel files when lakes/reservoirs are to be\nrepresented and these are discussed in Sections :ref:`5.4 <section-5.4>`\nand :ref:`5.6 <section-5.6>`.\n\n.. rubric:: Relevant code modules:\n\n:file:`Routing/module_channel_routing.F90`\n\n:file:`Routing/Reservoirs/Level_Pool/module_levelpool.F90`\n\n.. rubric:: Relevant namelist options:\n\n:file:`hydro.namelist`:\n\n-  ``lake_option`` - Option to specify lake/reservoir routing behavior\n   (0=lakes off, 1=level pool, 2=passthrough, 3=reservoir DA).\n-  ``route_lake_f`` - Path to lake parameter file to support\n   level-pool reservoir routing methods.\n\n.. note:: As mentioned in the paragraph above, if in the\n   GIS-Preprocessing the user created a “gridded” routing stack for\n   ``channel_option = 3`` (i.e. did *not* select to create a\n   Route_Link.nc file for ``channel_option=1`` or ``=2``) AND specified\n   a lake file (user provided a reservoir/lake input file), then\n   the :file:`Fulldom_hires.nc` file will populate the ``LAKEGRID`` variable.\n   For this case, the user **must** specify the route_lake_f file.\n   To turn lakes “off” with ``channel_option=3``, create another set\n   of :file:`Fulldom_hires.nc` (“domain”) files without a reservoir input\n   file specified.\n\n.. rubric:: Relevant domain and parameter files/variables:\n\n-  ``CHANNELGRID`` in :file:`Fulldom_hires.nc` - Channel network grid identifying\n   the location of stream channel grid cells\n\n-  ``LAKEGRID`` in :file:`Fulldom_hires.nc` (optional) - Specifies lake locations on\n   the channel grid (for gridded channel routing methods, i.e.\n   ``channel_option=3``).\n\n-  :file:`Route_Link.nc` netCDF file (optional) - Specifies lake associations\n   with channel reaches.\n\n-  :file:`LAKEPARM.nc` netCDF file - Specifies lake parameters for each lake\n   object specified.\n\n.. _section-3.8:\n\n3.8 Conceptual base flow model description\n------------------------------------------\n\nAquifer processes contributing baseflow often operate at depths well\nbelow ground surface. As such, there are often conceptual shortcomings\nin current land surface models in their representation of groundwater\nprocesses. Because these processes contribute to streamflow (typically\nas “baseflow”) a parameterization is often used in order to simulate\ntotal streamflow values that are comparable with observed streamflow\nfrom gauging stations. Therefore, a switch-activated baseflow module\n:file:`Routing/module_GW_baseflow.F90` has been created which conceptually\n(i.e. *not* physically-explicit) represents baseflow contributions to\nstreamflow. This model option is particularly useful when WRF-Hydro is\nused for long-term streamflow simulation/prediction and baseflow or\n“low flow” processes must be properly accounted for. Besides potential\ncalibration of the land surface model parameters the conceptual baseflow\nmodel does not directly impact the performance of the land surface model\nscheme. The new baseflow module is linked to WRF-Hydro through the\ndischarge of “deep drainage” from the land surface soil column (sometimes\nreferred to as “underground runoff”).\n\nThe baseflow parameterization in WRF-Hydro uses spatially-aggregated\ndrainage from the soil profile as recharge to a conceptual groundwater\nreservoir (:ref:`Fig. 3.10 <figure-3.10>`). The unit of spatial\naggregation is often taken to be that of a catchment or sub-basin within\na watershed. Each sub-basin has a groundwater reservoir “bucket” with a\nconceptual depth and associated conceptual volumetric capacity. The\nreservoir operates as a simple bucket where outflow (= “baseflow” or\n“stream inflow”) is estimated using an empirically-derived function of\nrecharge. The functional type and parameters are determined empirically\nfrom offline tests using an estimation of baseflow from stream gauge\nobservations and model-derived estimates of bucket recharge provided by\nWRF-Hydro. Presently, WRF-Hydro uses either a direct output-equals-input\n(\"pass-through\") relationship or an exponential storage-discharge function\nfor estimating the bucket discharge as a function of a conceptual depth\nof water in the bucket (\"exponential bucket\"). Note that, because this is\na highly conceptualized formulation, the depth of water in the bucket in\nno way infers the actual depth of water in a real aquifer system.\nHowever, the volume of water that exists in the bucket needs to be\ntracked in order to maintain mass conservation. Estimated baseflow\ndischarged from the bucket model is then combined with lateral inflow\nfrom overland routing (if active) and input directly into the stream\nnetwork as channel inflow, as referred to above in Section\n:ref:`3.5 <section-3.5>`. Presently, the total basin\nbaseflow flux to the stream network is equally distributed among all\nchannel pixels within a basin for gridded channel routing options or\ndumped into the top of the reach to be routed downstream for reach-based\nmethods. Lacking more specific information on regional groundwater\nbasins, the groundwater/baseflow basins in WRF-Hydro are often assumed\nto match those of the surface topography. However, this is not a strict\nrequirement. Buckets can be derived in a number of ways such as where\ntrue aquifers are defined or from a third-party hydrographic\ndataset such as the USGS NHDPlus or Hydrosheds.\n\n.. _figure-3.11:\n.. figure:: media/groundwater.svg\n   :align: center\n   :width: 70%\n\n   **Figure 3.11** Hypothetical map of groundwater/baseflow sub-basins\n   within a watershed and conceptualization of baseflow “bucket”\n   parameterization in WRF-Hydro.\n\n\\\n      | `z = z_{previous} + \\frac{Q_{in}*dt}{A}; \\qquad (3.40)`\n      |\n      | **if** `z > z_{max}` :\n      |    `z_{spill} = z - z_{max}`\n      |    `z = z_{max}`\n      |    `Q_{spill} = \\frac{A*z_{spill}}{dt}`\n      |\n      | **else** :\n      |    `Q_{spill} = 0`\n      |\n      | `Q_{exp} = C(e^{E\\frac{z}{zmax}}-1)`\n      | `Q_{out} = Q_{spill} + Q_{exp}`\n      | `z = z - \\frac{Q_{exp}*dt}{A}`\n      |\n      | **where** :\n      |    `Q_{in}` is the inflow to the bucket aggregated from the bottom of the LSM in `m^3/s`\n      |    `z` is the height of the water level in the bucket in `mm`\n      |    `z_{max}` is the total height of the bucket in `mm`\n      |    `A` is the area of the catchment or groundwater basin in `m^2`\n      |    `E` is a unitless parameter\n      |    `C` is a parameter with units of `m^3/s`\n\nA groundwater/baseflow bucket model parameter file (:file:`GWBUCKPARM.nc`)\nspecifies the empirical parameters governing the behavior of the bucket\nmodel parameterization for each groundwater/baseflow basin specified\nwithin the model domain. These files are created by the WRF-Hydro GIS\nPreprocessing System and documented in :ref:`Appendix 10 <section-a10>`.\nThe parameters include: the bucket model coefficient, the bucket model\nexponent, the initial depth of water in the bucket model, and the maximum\nstorage in the bucket before \"spilling\" occurs.\n\nIt is important to remember that a simple bucket model is a highly\nabstracted and conceptualized representation of groundwater processes\nand therefore the depth of water values in the bucket and the parameters\nthemselves have no real physical basis. As mentioned above, initial\nvalues of the groundwater bucket model parameters are typically derived\nanalytically or \\'offline\\' from WRF-Hydro and then are fine-tuned through\nmodel calibration.\n\nThere are 4 options available for the conceptual baseflow model, as specified\nin ``GWBASESWCRT`` in :file:`hydro.namelist`. The conceptual baseflow model\ncan be turned off (``GWBASESWCRT = 0``), which means water draining from the soil column in the land\nsurface model will become a sink term (this water will not be returned to the channel\nand will be a loss from the system). The exponential bucket model can be activated\n(``GWBASESWCRT = 1``), as described above. Water draining from the land model soil\ncolumn can be placed directly into the channel with no additional storage/attenuation\n(``GWBASESWCRT = 2``). For configurations using user-defined mapping to specify\ncatchment boundaries (``UDMP_OPT = 1``), there is a modified version of the\nexponential bucket model (``GWBASESWCRT = 4``) that adjusts the `C` parameter above\nbased on the area of the catchment.\n\n.. rubric:: Relevant code modules:\n\n:file:`Routing/module_GW_baseflow.F90`\n\n.. rubric:: Relevant namelist options:\n\n:file:`hydro.namelist`:\n\n-  ``GWBASESWCRT`` - Switch to activate groundwater bucket module.\n\n-  ``GWBUCKPARM_file`` - Path to groundwater bucket parameter file.\n\n-  ``gwbasmskfil`` (optional) - Path to netcdf groundwater basin mask file\n   if using an explicit groundwater basin 2d grid.\n\n-  ``UDMP_OPT`` (optional) - Switch to activate user-defined mapping between\n   land surface model grid and conceptual basins.\n\n-  ``udmap_file`` (optional) - If user-defined mapping is active, path to\n   spatial-weights file.\n\n.. rubric:: Relevant domain and parameter files/variables:\n\n-  :file:`GWBUCKPARM.nc` netCDF file - Specifies the parameters for each\n   groundwater bucket/basin. More information regarding the groundwater\n   bucket model parameters is provided in :ref:`Section 5.5 <section-5.5>` and\n   :ref:`Appendix 10 <section-a10>`.\n\n-  :file:`GWBASINS.nc` netCDF file - The 2d grid of groundwater basin IDs.\n\n-  :file:`spatialweights.nc` - netCDF file specifying the weights to map\n   between the land surface grid and the pre-defined groundwater basin\n   boundaries.\n"
  },
  {
    "path": "docs/userguide/nudging.rest",
    "content": ".. vim: syntax=rst\n.. include:: meta.rest\n\n4. Streamflow Nudging Data Assimilation\n=======================================\n\nThis chapter describes streamflow nudging and data assimilation in\nVersion 5.0 and beyond of WRF-Hydro. Streamflow nudging was introduced\nin v1.1 of the National Water Model (NWM). The community WRF-Hydro model\nsource code and the NWM source code have merged as of Version 5.0 of\nWRF-Hydro. See Appendix :ref:`A14 <section-a14>` for more\ninformation on the NWM.\n\n4.1 Streamflow Nudging Data Assimilation Overview\n-------------------------------------------------\n\nFor the National Water Model (NWM), a simple nudging data assimilation\n(DA) scheme has been developed to correct modeled stream flows to (or\ntowards) observed values. The capability is only currently supported\nunder the NWM configuration, but could be extended to NCAR reach-based\nrouting, and potentially other kinds of routing, in the future.\nSpecifically, the nudging capability introduces an interface for stream\ndischarge observations to be applied to the Muskingum-Cunge streamflow\nrouting solution.\n\n.. _section-4.2:\n\n4.2 Nudging Formulation\n-----------------------\n\nThere are several motivations for performing DA. For the NWM analysis\nand assimilation cycle, the motivation is to improve model simulation\nand forecast initial conditions. Nudging is a simple and computationally\ninexpensive method of data assimilation where an observed state is\ninserted into the model with some uncertainty. When the observed value\nis inserted into the model without uncertainty, the method is referred\nto as “direct insertion”.\n\nNudging works well locally to observations, both in space and time. Away\nfrom observations, in space and time, the method has limited success.\nFor example, our application applies nudging data assimilation on a\nchannel network with the advantage that the corrections are propagated\ndownstream with the network flow. However, if no spatial or temporal\nsmoothing of the corrections are included with the nudging method,\nupstream errors soon propagate past observed points when in the forecast\n(away from the observations, into the future). Various assumptions can\nbe made to smooth the nudge (or correction) in space and/or time but\nthese are highly parameterized and require tuning. In the NWM we have\navoided spatial smoothing and have opted to pursue a very limited\ntemporal-interpolation approach.\n\nThe basic nudging equation solves `e_j`, the nudge, `e`, on a spatial\nelement `j`,\n\n.. _equation-4.1:\n.. rst-class:: center\n.. math::\n   e_{j} = \\frac{\\sum_{n=1}^{N_j} q_{n}*w_{n}^{2}(j,t)*(Q_{n} - {\\widehat{Q}}_{n})}{\\sum_{n=1}^{N_j} w_{n}^{2}(j,t)}\n    \\qquad (4.1)\n\nThe numerator is the sum, over the `N_j` observations affecting element\n`j`, of the product of each observations' quality coefficient, `q_n`,\nthe model error, :math:`Q_{n} - {\\widehat{Q}}_{n}`, and the squared\nweights. The weights is where most of the action happens.\n\nThe weights determine how the nudge is interpolated in both space and\ntime (`j,t`). The weights term `w_n(j,t)` in the above equation is\nsolved for observation `n` as a function of both space, `j`, and time,\n`t`. It is expressed as the product of separate spatial and temporal\nweight terms:\n\n.. _equation-4.2:\n.. rst-class:: center\n.. math::\n    w_{n}(j,t) = w_{n_{s}}(j)\\ *\\ w_{n_{t}}(t,j)\n    \\qquad (4.2)\n\nThe temporal weight term takes the following piecewise form in our\napplication:\n\n.. _equation-4.3:\n.. rst-class:: center\n.. math::\n    w_{n_t}(t,j) = \\begin{cases}\n    10^{10} * (1/10)^{\\frac{\\left| t-\\widehat{t} \\right|}{tau_j / 10}} &:\\text{if} \\ \\left| t-\\widehat{t} \\right| \\leq tau_j \\\\\n    e^{-a_j*(t-\\widehat{t})} &:\\text{if} \\ \\left| t-\\widehat{t} \\right| \\gt tau_j\n    \\end{cases} \\qquad (4.3)\n\nThe spatial weight term is of the following form:\n\n.. _equation-4.4:\n.. rst-class:: center\n.. math::\n    w_{n_s} = \\begin{cases}\n    \\frac{R_{n}^2 - d_{jn}^{2}}{R_{n}^2 + d_{jn}^2} &: \\text{if} R_n > d_{jn} \\\\\n    0 &: \\text{otherwise}\n    \\end{cases} \\qquad (4.4)\n\n\nThe parameters specified in version 1.2 of the NWM (equivalent to this\nWRF-Hydro version 5) are:\n\n.. rst-class:: center\n\n    | *tau = 15 minutes*\n    | *a = 120 minutes*\n    | *R = 0.25 meters*\n\nfor all gages (all `j`) in CONUS (the parameter files are discussed\nbelow). The very short `R` means that nudging is applied locally, only\nto the reach where the observation is associated. There is currently no\nspatial smoothing. This is partly because spatial smoothing is assumed\nto be computationally intensive and has not been completely implemented.\nThe `tau = 15` means that within 15 minutes of an observation we are\nheavily weighting the observation and `a = 120` means that nudging to\nthe observation relaxes with e-folding time of two hours moving away\nfrom the observation.\n\nThe Muskingum-Cunge equation in :ref:`Section 3.6.2 <section-3.6.2>` has the form:\n\n.. _equation-4.5:\n.. rst-class:: center\n.. math::\n   Q_{d}^{c} = C1{\\,Q}_{u}^{p} + C2\\,Q_{u}^{c} + {C3\\,Q}_{d}^{p} + \\left( \\frac{q_{l}\\,dt}{D} \\right)\n   \\qquad (4.5)\n\nIn v1.0 of the NWM, nudging was applied into this equation in the\nfollowing manner\n\n.. _equation-4.6:\n.. rst-class:: center\n.. math::\n   Q_{d}^{c} = C1{\\,Q}_{u}^{p} + C2\\,Q_{u}^{c} + {C3\\,(Q}_{d}^{p} + N_{d}^{p}) + \\left( \\frac{q_{l}\\,dt}{D} \\right)\n   \\qquad (4.6)\n\nwhere the discharge solution (`Q`) at the current time (`c`) at the\ndownstream (`d`) reach was solved by applying the nudge from the\nprevious timestep (`N_{d}^{p}`) to adjust the discharge of\ndownstream reach at the previous (`p`) time. Experiments indicated\nundesirable side effects of introducing a discontinuity (the previous\nnudge) in discharge between the upstream (`u`) link and the downstream\n(`d`) link in this solution. With v1.2 of the NWM (equivalent to v5.0\nWRF-Hydro), the equation was modified to include the nudge in the\nupstream terms of the solution as well, at both the previous and current\ntimes:\n\n.. _equation-4.7:\n.. rst-class:: center\n.. math::\n    Q_{d}^{c} = C1{(Q}_{u}^{p} + N_{d}^{p}) + C2{(Q}_{u}^{c} + N_{d}^{p}) + {C3(Q}_{d}^{p} + N_{d}^{p}) + \\left( \\frac{q_{l}\\,dt}{D} \\right)\n    \\qquad (4.7)\n\nThis is the form of the equation currently used for nudging which aims\nto reduce the discontinuity in space between the upstream and downstream\nreaches. Experiments revealed that this formulation, significantly\nreduced the difference between modeled and observed discharge and hence\nthe nudging magnitudes (over long time series of assimilated\nobservations). Note that the nudge is only applied to the upstream reach\nduring the solution of the downstream reach and is not applied in the\noutput values of the upstream reach.\n\nThis change in the nudging formulation also promotes the previous\ndownstream nudge to a prognostic variable. Whereas\n`Q_{d}^{p} + N_{d}^{p}` was simply the previous downstream\nstreamflow value after the nudge (already a prognostic model variable),\nadding the previous downstream nudge to the upstream solutions requires\nhaving the previous nudge available. Therefore, the previous downstream\nnudge values gets written to the nudgingLastObs files (described in\n:ref:`Section 4.3 <section-4.3>`), which are the restart files for\nthe nudging routine.\n\nThere are a variety of experimental nudging options and features in the\nnudging section of the :file:`hydro.namelist` which are incomplete or unused at\nthis time. There are also nudging features used in a limited capacity by\nthe NWM which are not described here. As development of these options\nevolves, they will be documented in future versions of WRF-Hydro.\n\n.. _section-4.3:\n\n4.3 Nudging Workflow\n--------------------\n\nFigure 4.1 provides an overview of the nuding workflow at the file\nlevel. Descriptions are provided for each of the files shown in the\ndiagram.\n\n.. figure:: media/nudging-workflow.svg\n   :align: center\n   :scale: 125%\n\n   **Figure 4.1:** The nudging workflow at the file level.\n\n4.3.1 Input Files\n~~~~~~~~~~~~~~~~~\n\n.. rubric:: Discharge observations and :file:`nudgingTimeSliceObs/` :\n\nDischarge observations from the real world enter the WRF-Hydro system through the\n:file:`nugingTimeSliceObs/` directory.\n\nThe individual observation files used for streamflow nudging are stored\nin this directory, each with the the following naming convention\n:file:`YYYY-mm-dd_HH:MM:SS.RRmin.usgsTimeSlice.ncdf`.\n\nThe first part of the filename, ``YYYY-mm-dd_HH:MM:SS``, identifies the\ncenter of the “slice of time” in which observations are found (from year\ndown to second). ``RR`` indicates the resolution, or total width of the time\nslice. Currently this resolution is a **hard-coded** parameter in the model.\nIt is set to 15 minutes as this is the most common reporting frequency\nfor USGS gages in the USA. The ``usgsTimeSlice`` part of the filename is\nfixed and is legacy of the fact that these files were originally\ndesigned for USGS observations. However, any discharge observations can\nbe placed into this format.\n\nThe format of a an example timeslice observation file is given by an\n:program:`ncdump -h` in :ref:`Appendix A14 <section-a14>`. Of the three-dimensional variables,\ntwo are character lengths and only the ``stationIdInd`` dimension is\nvariable (unlimited). The ``stationIdInd`` variable has dimensions of the\nnumber of individual stream gages contained in the file by the fixed\nwidth of the strings (``stationIdStrLen=15``). The variable metadata\ndescribes the contents. The ``stationId`` variable is the “USGS station\nidentifier of length 15”. While the character type of the variable and\nthe length of 15 are both fixed, identifiers are not limited to those\nused by the USGS. Custom identifiers can be used and are described later\nin this section when the gages variable in the :file:`Route_Link.nc` file is\ndescribed. The variable ``discharge_quality`` is simply a multiplier. This\nvalue is stored as a short integer for space concerns and only takes\nvalues from zero to one hundred. Internally in the model, this variable\nis scaled by 100 and used as a floating point variable between zero and\none. The ``queryTime`` variable is not used by the model and is optional. It\nmay be useful in situations when the files are updated in real-time.\nSimilarly, the metadata field ``fileUpdateTimeUTC`` can be useful but is not\nrequired by the model. The remaining two metadata fields are both\nrequired by the model: ``sliceCenterTimeUTC`` and ``sliceTimeResolutionMinutes``\nensure that the file and the model are operating under the same time\nlocation and resolution assumptions. An example of generating timeslice\nfiles from USGS observations using the R language is given in the help\nfor the rwrfhydro function :command:`WriteNcTimeSlice`.\n\n.. rubric:: :file:`hydro.namelist`:\n\nWhen WRF-Hydro is compiled with nudging on, the :file:`hydro.namelist`\nfile is required to contain ``&NUDGING_nlist``. The nudging namelist is\nfound at the bottom of the :file:`hydro.namelist` file either in the :file:`Run/`\ndirectory after compilation or in the :file:`template/HYDRO/` directory.\nThe namelist governs the run-time options to the nudging code. These run-time\noptions are detailed in :ref:`Section 4.5 <section-4.5>` below and in\n:ref:`Appendix A5 <section-a5>`.\n\n.. rubric:: :file:`Route_Link.nc`:\n\nCollocation of streamflow gages and reach elements is achieved\nby the gages field in the :file:`Route_Link.nc` file (see Sections\n:ref:`3.6 <section-3.6>` and :ref:`5.4 <section-5.4>`). Each reach\nelement may have a single gage identified with it as specific by a\nfixed-width 15 character string in the gages field. A blank entry\nindicates no gage is present on the reach. The gages field in\n:file:`Route_Link.nc` tells the nudging module where to apply the observed\nvalues to the stream network. Gages which appear in the observation\nfiles but not in the :file:`Route_Link.nc` file do not cause a problem, they are\nsimply skipped and their identifiers collected and printed to the file\n:file:`NWIS_gages_not_in_RLAndParams.txt` file, described later. The number of\nnon-blank routelink gages must match the number of gages supplied in the\nnudging parameters file, described next.\n\n.. rubric:: :file:`nudgingParams.nc`:\n\nAppendix :ref:`A14 <section-a14>` shows\nthe structure of the :file:`nudgingParams.nc` file for a small domain. Some\nof the parameters in the file are explained in detail in Section\n:ref:`4.2 <section-4.2>` and some are placeholders for capabilities\nwhich have not been developed.\n\n4.3.2 Output Files\n~~~~~~~~~~~~~~~~~~\n\nWhen the code is compiled with the nudging compile-time option on (see\nnext section), four types of output files contain nudging information.\nSome files are different than when compiled without nudging while other\nfiles are unique outputs for the nuding option.\n\n.. rubric:: :file:`YYYYmmddHHMM.CHRTOUT_DOMAIN1`:\n\nThe nudging code affects the values written to the “CHRTOUT” files.\nIf valid observations are available, the (modeled) streamflow variable is\nchanged by the assimilated observations. When the model is compiled to enable\nnudging, the variable ``nudge`` also appears in the file. The nudge value is\ncalculated as in Section :ref:`4.2 <section-4.2>`.\n\n.. rubric:: :file:`nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc`:\n\nThese files are unique to the nudging compile and are the restart files\nfor the nudging component of the model. A restart file is not required,\nnudging can be run from a cold start. This file can contain multiple variables,\nonly the ``nudge`` variable is described in this documentation.\n\n.. rubric:: :file:`NWIS_gages_not_in_RLAndParams.txt`:\n\nThese files are unique to nudging and report the unique gages found in the\nobservation time slice files which were not present in the :file:`Route_Link.nc`\nfile. These are gages which may have the opportunity to be assimilated (provided\nthey could be located in the domain). There is only one such file per run, written\nat the end of the run.\n\n.. rubric:: Standard output and :file:`hydro_diag.*` files:\n\nThe nudging routines write various messages. The ultimate destination of these\ncan be compiler dependent. The nudging code aims to preface all its messages with ``Ndg:``\nand all its warnings with ``Ndg: WARNING:``.\n\n4.4 Nudging compile-time option\n-------------------------------\n\nThe nuding capability is only available when the code is compiled with\nthe environment variable set:\n\n``WRF_HYDRO_NUDGING=1``\n\n.. _section-4.5:\n\n4.5 Nudging run-time options\n----------------------------\n\n:ref:`Appendix A5 <section-a5>` presents an annotated :file:`hydro.namelist`\nfile. There are two Fortran namelists contained within that file. The nudging\nrun-time options are contained the ``NUDGING_nlist`` which is the second namelist\nin the document. Only some run time options listed in the namelist are\ndocumented at this time.\n\n+-----------------------------------+---------------------------------------+\n| **Documented/Supported Options**  | **Undocumented/Unsupported Options**  |\n+===================================+=======================================+\n| ``timeSlicePath``                 | ``nLastObs``                          |\n|                                   |                                       |\n| ``nudgingParamFile``              | ``persistBias``                       |\n|                                   |                                       |\n| ``nudgingLastObsFile``            | ``biasWindowBeforeT0``                |\n|                                   |                                       |\n| ``readTimesliceParallel``         | ``maxAgePairsBiasPersist``            |\n|                                   |                                       |\n| ``temporalPersistence``           | ``minNumPairsBiasPersist``            |\n|                                   |                                       |\n|                                   | ``invDistTimeWeightBias``             |\n|                                   |                                       |\n|                                   | ``noConstInterfBias``                 |\n+-----------------------------------+---------------------------------------+\n\nDetails on the meaning and usage of the options are given in\n:ref:`Appendix A5 <section-a5>`, in both the comments which are part of the namelist\nitself and by the blue annotations added to the namelists. The supported options\nare fairly straight forward in their usage. It is worth noting that the\nspecfication of the :file:`nudgingLastObsFile` does not behave the same way as\nthe specification of the LSM or hydro restart files. The unsupported\nnudging options have to do with mostly experimental methods for forecast\nbias correction which have been investigated.\n"
  },
  {
    "path": "docs/userguide/output-tables/CHANOBS_DOMAIN.csv",
    "content": "Variable Name,Long Name,Description,Units,IO_ConfigOutputs_0,IO_ConfigOutputs_1,IO_ConfigOutputs_2,IO_ConfigOutputs_3,IO_ConfigOutputs_4,IO_ConfigOutputs_5,IO_ConfigOutputs_6,Min,Max,Scale,Offset,Fill\r\ntime,valid output time,Valid output time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nreference_time,model initialization time,Model initialization time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nfeature_id,Reach ID,Unique reach or channel cell ID,-,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nlatitude,Feature latitude,Station latitude,decimal degrees,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nlongitude,Feature longitude,Station longitude,decimal degrees,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\norder,Streamflow Order,Strahler stream order for output reach or cell,-,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nelevation,Feature Elevation,Elevation for output reach or cell,m,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nstreamflow,River Flow,Streamflow,m3 s-1,Yes,Yes,Yes,Yes,Yes,Yes,Yes,0,500000,0.01,0,-9999\r\n"
  },
  {
    "path": "docs/userguide/output-tables/CHRTOUT_DOMAIN.csv",
    "content": "Variable Name,Long Name,Description,Units,IO_ConfigOutputs_0,IO_ConfigOutputs_1,IO_ConfigOutputs_2,IO_ConfigOutputs_3,IO_ConfigOutputs_4,IO_ConfigOutputs_5,IO_ConfigOutputs_6,Min,Max,Scale,Offset,Fill,Special Notes\r\ntime,valid output time,Valid output time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A,\r\nreference_time,model initialization time,Model initialization time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A,\r\nfeature_id,Reach ID,Unique reach or channel cell ID,-,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A,\r\nlatitude,Feature latitude,Station latitude,decimal degrees,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A,\r\nlongitude,Feature Longitude,Station longitude,decimal degrees,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A,\r\norder,Streamflow order,Strahler stream order for output reach or cell,-,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A,\r\nelevation,Feature Elevation,Elevation for output reach or cell,m,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A,\r\nstreamflow,River Flow,Streamflow,m3 s-1,Yes,Yes,Yes,Yes,Yes,Yes,Yes,0,500000,0.01,0,-9999,\r\nnudge,Amount of stream flow alteration,Streamflow nudge value (only if nudging DA is active),m3 s-1,No,No,No,No,No,No,No,-500000,500000,0.01,0,-9999,Values only when nudging DA is active\r\nq_lateral,Runoff into channel reach,Lateral flow into channel reach or cell,m3 s-1,Yes,No,No,No,No,Yes,Yes,0,500000,0.1,0,-9999,\r\nvelocity,River Velocity,Channel velocity,m s-1,Yes,Yes,Yes,Yes,Yes,Yes,Yes,0,500000,0.01,0,-9999,\r\nhead,River Stage,River stage (gridded channel only),m,Yes,No,No,No,No,No,No,0,500000,0.01,0,-9999,\r\nqSfcLatRunoff,Runoff from terrain routing,Flux from terrain routing,m3 s-1,No,No,No,No,No,No,No,0,500000,0.001,0,-9999,Only available for UDMP_OPT=1\r\nqBucket,Flux from gw bucket,Flux from groundwater buckets,m3 s-1,No,No,No,No,No,No,No,0,500000,0.001,0,-9999,Only available for UDMP_OPT=1\r\nqBtmVertRunoff,Runoff from bottom of soil to bucket,Flux from bottom of soil column into groundwater buckets,m3,No,No,No,No,No,No,No,0,500000,0.001,0,-9999,Only available for UDMP_OPT=1\r\nAccSfcLatRunoff,Accumulated runoff from terrain routing,Accumulated flux from terrain routing,m3,No,No,No,No,No,No,No,0,500000,0.01,0,-9999,Only available for UDMP_OPT=1\r\naccBucket,Accumulated runoff from gw bucket,Accumulated flux from groundwater buckets,m3,No,No,No,No,No,No,No,0,500000,0.01,0,-9999,Only available for UDMP_OPT=1\r\n"
  },
  {
    "path": "docs/userguide/output-tables/CHRTOUT_GRID.csv",
    "content": "Variable Name,Long Name,Description,Units,IO_ConfigOutputs_0,IO_ConfigOutputs_1,IO_ConfigOutputs_2,IO_ConfigOutputs_3,IO_ConfigOutputs_4,IO_ConfigOutputs_5,IO_ConfigOutputs_6,Min,Max,Scale,Offset,Fill\r\ntime,valid output time,Valid output time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nreference_time,model initialization time,Model initialization time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nx,x coordinate of projection,x coordinate (in native projection),native projection units,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\ny,y coordinate of projection,y coordinate (in native projection),native projection units,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nIndex,Stream cell index value,Stream cell index value,-,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nstreamflow,River Flow,Streamflow,m3 s-1,Yes,Yes,Yes,Yes,Yes,Yes,Yes,0,500000,0.1,0,-9999\r\n"
  },
  {
    "path": "docs/userguide/output-tables/GWOUT_DOMAIN.csv",
    "content": "Variable Name,Long Name,Description,Units,IO_ConfigOutputs_0,IO_ConfigOutputs_1,IO_ConfigOutputs_2,IO_ConfigOutputs_3,IO_ConfigOutputs_4,IO_ConfigOutputs_5,IO_ConfigOutputs_6,Min,Max,Scale,Offset,Fill\r\ntime,valid output time,Valid output time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nreference_time,model initialization time,Model initialization time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nfeature_id,Groundwater Bucket ID,Unique groundwater bucket ID,-,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\ninflow,Bucket Inflow,Total groundwater bucket inflow,m3 s-1,Yes,Yes,Yes,Yes,Yes,Yes,Yes,-10000,10000,0.01,0,-9999\r\noutflow,Bucket Outflow,Total groundwater bucket outflow,m3 s-1,Yes,Yes,Yes,Yes,Yes,Yes,Yes,-10000,10000,0.01,0,-9999\r\ndepth,Bucket Depth,Groundwater bucket water level,mm,Yes,Yes,Yes,Yes,Yes,Yes,Yes,-10000,10000,0.1,0,-9999\r\n"
  },
  {
    "path": "docs/userguide/output-tables/LAKEOUT_DOMAIN.csv",
    "content": "Variable Name,Long Name,Description,Units,IO_ConfigOutputs_0,IO_ConfigOutputs_1,IO_ConfigOutputs_2,IO_ConfigOutputs_3,IO_ConfigOutputs_4,IO_ConfigOutputs_5,IO_ConfigOutputs_6,Min,Max,Scale,Offset,Fill\r\ntime,valid output time,Valid output time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nreference_time,model initialization time,Model initialization time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nfeature_id,Lake COMMON ID,Unique lake ID,-,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nlatitude,Lake latitude,Lake latitude,decimal degrees,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nlongitude,Lake longitude,Lake longitude,decimal degrees,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nwater_sfc_elev,Water Surface Elevation,Water surface elevation above sea level,m,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\ninflow,Lake Inflow,Total inflow into waterbody,m3 s-1,Yes,Yes,Yes,Yes,Yes,Yes,Yes,-10000,10000,0.01,0,-9999\r\noutflow,Lake Outflow,Outflow from waterbody outlet,m3 s-1,Yes,Yes,Yes,Yes,Yes,Yes,Yes,-10000,10000,0.01,0,-9999\r\n"
  },
  {
    "path": "docs/userguide/output-tables/LDASOUT_DOMAIN.csv",
    "content": "Variable Name,Long Name,Description,Units,IO_ConfigOutputs_0,IO_ConfigOutputs_1,IO_ConfigOutputs_2,IO_ConfigOutputs_3,IO_ConfigOutputs_4,IO_ConfigOutputs_5,IO_ConfigOutputs_6,Min,Max,Scale,Offset,Fill\r\ntime,valid output time,Valid output time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nreference_time,model initialization time,Model initialization time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nx,x coordinate of projection,x coordinate (in native projection),native projection units,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\ny,y coordinate of projection,x coordinate (in native projection),native projection units,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nIVGTYP,Dominant vegetation category,Dominant vegetation category,category,Yes,No,No,No,No,No,No,0,100,1,0,-9999\r\nISLTYP,Dominant soil category,Dominant soil category,category,Yes,No,No,No,No,No,No,0,100,1,0,-9999\r\nFVEG,Green Vegetation Fraction,Fraction of surface covered by vegetation,fraction,Yes,No,No,No,No,No,No,0,1,0.01,0,-9999\r\nLAI,Leaf area index,Leaf area index,m2 m-2,Yes,No,No,No,No,No,No,0,20,0.1,0,-9999\r\nSAI,Stem area index,Stem area index,m2 m-2,Yes,No,No,No,No,No,No,0,20,0.1,0,-9999\r\nSWFORC,Shortwave forcing,Shortwave radiation forcing,W m-2,Yes,No,No,No,No,No,No,-1000,3000,0.1,0,-9999\r\nCOSZ,Cosine of zenith angle,Cosine of zenith angle,-,Yes,No,No,No,No,No,No,-1,1,0.01,0,-9999\r\nLWFORC,Longwave forcing,Longwave radiation forcing,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nRAINRATE,Precipitation rate,Precipitation in model timestep,mm s-1,Yes,No,No,No,No,No,No,0,100,0.000001,0,-9999\r\nEMISS,Grid emissivity,Emissivity: grid-average,-,Yes,No,No,No,No,No,No,0,1,0.01,0,-9999\r\nFSA,Total absorbed SW radiation,Total absorbed SW radiation,W m-2,Yes,No,No,Yes,No,Yes,Yes,-1500,1500,0.1,0,-9999\r\nFIRA,Total net LW radiation to atmosphere,Total net LW radiation (+ to atmosphere),W m-2,Yes,No,No,Yes,No,Yes,Yes,-1500,1500,0.1,0,-9999\r\nGRDFLX,Heat flux into the soil,Ground heat flux: grid-average (+ to soil),W m-2,Yes,No,No,Yes,No,No,Yes,-1500,1500,0.1,0,-9999\r\nHFX,Total sensible heat to the atmosphere,Sensible heat flux: grid-average (+ to atmosphere),W m-2,Yes,No,No,Yes,No,Yes,Yes,-1500,1500,0.1,0,-9999\r\nLH,Total latent heat to the atmosphere,Latent heat flux: grid-average (+ to atmosphere),W m-2,Yes,No,No,Yes,No,Yes,Yes,-1500,1500,0.1,0,-9999\r\nECAN,Canopy water evaporation rate,Canopy water evaporation rate,kg m-2 s-1,Yes,No,No,No,No,No,No,-100,100,0.000001,0,-9999\r\nEDIR,Direct from soil evaporation rate,Direct soil evaporation rate,kg m-2 s-1,Yes,No,No,No,No,No,No,-100,100,0.000001,0,-9999\r\nALBEDO,Surface albedo,Total-grid surface albedo,-,Yes,No,No,No,No,No,No,0,1,0.01,0,-9999\r\nETRAN,Transpiration rate,Transpiration rate,kg m-2 s-1,Yes,No,No,No,No,No,No,-100,100,0.000001,0,-9999\r\nUGDRNOFF,Accumulated underground runoff,Underground runoff: accumulated,mm,Yes,No,No,Yes,Yes,Yes,Yes,-100,100000,0.01,0,-9999\r\nSFCRNOFF,Accumulated surface runoff,Surface runoff: accumulated,mm,Yes,No,No,No,Yes,Yes,Yes,0,100000,0.001,0,-9999\r\nCANLIQ,Canopy liquid water content,Canopy liquid water content,mm,Yes,No,No,No,No,No,No,-5,30000,0.01,0,-9999\r\nCANICE,Canopy ice water content,Canopy ice water content,mm,Yes,No,No,No,No,No,No,-5,30000,0.01,0,-9999\r\nZWT,Depth to the water table,Depth to water table,m,Yes,No,No,No,No,No,No,0,10,0.00001,0,-9999\r\nWA,Water in aquifer,Water in aquifer relative to reference level,kg m-2,Yes,No,No,No,No,No,No,0,10000,0.01,0,-9999\r\nWT,Water in aquifer and saturated soil,Water in aquifer and saturated soil,kg m-2,Yes,No,No,No,No,No,No,0,10000,0.01,0,-9999\r\nACCPRCP,Accumulated precip,Accumulated precipitation,mm,Yes,No,No,No,No,No,No,0,1000000,0.01,0,-9999\r\nACCECAN,Accumulated canopy water,Accumulated canopy evaporation,mm,Yes,No,No,Yes,No,No,Yes,-100,1000000,0.01,0,-9999\r\nACCEDIR,Accumulated direct soil evap,Accumulated direct soil evaporation,mm,Yes,No,No,Yes,No,No,Yes,-100,1000000,0.01,0,-9999\r\nACCETRAN,Accumulated transpiration,Accumulated transpiration,mm,Yes,No,No,Yes,No,No,Yes,-100,1000000,0.01,0,-9999\r\nSAV,Solar radiative heat flux aborbed by vegetation,Solar radiation absorbed: vegetation canopy,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nTR,Transpiration heat,Transpiration heat flux,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nEVC,Canopy evap heat,Latent heat flux: leaf to canopy air,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nIRC,Canopy net LW rad,Net emitted LW radiation: canopy,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nSHC,Canopy sensible heat,Sensible heat flux: leaf to canopy air,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nIRG,Ground net LW rad,Net emitted LW radiation: below-canopy ground,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nSHG,Ground sensible heat,Sensible heat flux: below-canopy ground to canopy air,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nEVG,Ground evap heat,Latent heat flux: below-canopy ground to canopy air,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nGHV,Ground heat flux + to soil vegetated,Ground heat flux: vegetated fraction (+ to soil),W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nSAG,Solar radiative heat flux absorved by ground,Solar radiation absorbed: ground surface,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nIRB,Net LW rad to atm bare,Net emitted LW radiation: bare ground,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nSHB,Sensible heat atm bare,Sensible heat flux: bare ground to atmosphere,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nEVB,Evaporation heat to atm bare,Latent heat flux: bare ground to atmosphere,W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nGHB,Ground heat flux + to soil bare,Ground heat flux: bare ground fraction (+ to soil),W m-2,Yes,No,No,No,No,No,No,-1500,1500,0.1,0,-9999\r\nTRAD,Surface radiative temperature,Surface radiative temperature: grid,K,Yes,No,No,Yes,No,Yes,Yes,0,400,0.1,0,-9999\r\nTG,Ground temperature,Ground temperature: grid-average,K,Yes,No,No,No,No,No,No,0,400,0.1,0,-9999\r\nTV,Vegetation temperature,Vegetation leaf temperature,K,Yes,No,No,No,No,No,No,0,400,0.1,0,-9999\r\nTAH,Canopy air temperature,Canopy air temperature,K,Yes,No,No,No,No,No,No,0,400,0.1,0,-9999\r\nTGV,Ground surface Temp vegetated,Ground temperature: vegetated ground,K,Yes,No,No,No,No,No,No,0,400,0.1,0,-9999\r\nTGB,Ground surface Temp bare,Ground temperature: bare ground,K,Yes,No,No,No,No,No,No,0,400,0.1,0,-9999\r\nT2MV,2m Air Temp vegetated,Air temperature @ 2m: vegetated ground,K,Yes,No,No,No,No,No,No,0,400,0.1,0,-9999\r\nT2MB,2m Air Temp bare,Air temperature @ 2m: bare ground,K,Yes,No,No,No,No,No,No,0,400,0.1,0,-9999\r\nQ2MV,2m mixing ratio vegetated,Mixing ratio @ 2m: vegetated ground,kg/kg,Yes,No,No,No,No,No,No,0,1,0.0001,0,-9999\r\nQ2MB,2m mixing ratio bare,Mixing ratio @ 2m: bare ground,kg/kg,Yes,No,No,No,No,No,No,0,1,0.0001,0,-9999\r\nEAH,Canopy air vapor pressure,Canopy air vapor pressure,Pa,Yes,No,No,No,No,No,No,-1000,100000,0.1,0,-9999\r\nFWET,Wetted or snowed fraction of canopy,Fraction of canopy covered by liquid or frozen water,fraction,Yes,No,No,No,No,No,No,0,1,0.01,0,-9999\r\nZSNSO_SN,Snow layer depths from snow surface,Snow and soil interface depths (from snow surface),m,Yes,No,No,No,No,No,No,-100,100,0.00001,0,-9999\r\nSNICE,Snow layer ice,Snow layer ice,mm,Yes,No,No,No,No,No,No,0,100000,0.01,0,-9999\r\nSNLIQ,Snow layer liquid water,Snow layer liquid water,mm,Yes,No,No,Yes,No,No,Yes,0,100000,0.01,0,-9999\r\nSOIL_T,soil temperature,Soil temperature,K,Yes,No,No,Yes,No,No,Yes,0,400,0.1,0,-9999\r\nSOIL_W,liquid volumetric soil moisture,Volumetric soil moisture: liquid,m3 m-3,Yes,No,No,No,No,Yes,Yes,0,1,0.01,0,-9999\r\nSNOW_T,snow temperature,Snow temperature,K,Yes,No,No,No,No,No,No,0,400,0.1,0,-9999\r\nSOIL_M,volumetric soil moisture,Volumetric soil moisture,m3 m-3,Yes,No,No,Yes,No,Yes,Yes,0,1,0.01,0,-9999\r\nSNOWH,Snow depth,Snow depth,m,Yes,Yes,Yes,Yes,No,Yes,Yes,0,100,0.0001,0,-9999\r\nSNEQV,Snow water equivalent,Snow water equivalent,kg m-2,Yes,Yes,Yes,Yes,Yes,Yes,Yes,0,100000,0.1,0,-9999\r\nQSNOW,Snowfall rate,Snowfall rate at ground surface,mm s-1,Yes,No,No,No,No,No,No,0,100,0.000001,0,-9999\r\nISNOW,Number of snow layers,Number of active snow layers,count,Yes,No,No,Yes,No,No,Yes,0,10,1,0,-9999\r\nFSNO,Snow-cover fraction on the ground,Fraction of surface covered by snow,fraction,Yes,Yes,Yes,Yes,No,Yes,Yes,0,1,0.001,0,-9999\r\nACSNOW,accumulated snow fall,Accumulated snow fall,mm,Yes,No,No,No,No,No,No,0,100000,0.01,0,-9999\r\nACSNOM,accumulated melting water out of snow bottom,Accumulated melting water out of snow bottom,mm,Yes,No,No,Yes,Yes,No,Yes,0,100000,0.01,0,-9999\r\nCM,Momentum drag coefficient,Exchange coefficient: grid-average,-,Yes,No,No,No,No,No,No,-5,5,0.00001,0,-9999\r\nCH,Sensible heat exchange coefficient,Exchange coefficient: grid-average,-,Yes,No,No,No,No,No,No,-5,5,0.00001,0,-9999\r\nCHV,Exchange coefficient vegetated,Exchange coefficient: vegetation-atmosphere,m s-1,Yes,No,No,No,No,No,No,-5,5,0.00001,0,-9999\r\nCHB,Exchange coefficient bare,Exchange coefficient: bare ground,m s-1,Yes,No,No,No,No,No,No,-5,5,0.00001,0,-9999\r\nCHLEAF,Exchange coefficient leaf,Exchange coefficient: leaf surface,m s-1,Yes,No,No,No,No,No,No,-5,5,0.00001,0,-9999\r\nCHUC,Exchange coefficient bare,Exchange coefficient: below-canopy,m s-1,Yes,No,No,No,No,No,No,-5,5,0.00001,0,-9999\r\nCHV2,Exchange coefficient 2-meter vegetated,Exchange coefficient: vegetation-atmosphere @ 2-meters,m s-1,Yes,No,No,No,No,No,No,-5,5,0.00001,0,-9999\r\nCHB2,Exchange coefficient 2-meter bare,Exchange coefficient: bare ground @ 2-meters,m s-1,Yes,No,No,No,No,No,No,-5,5,0.00001,0,-9999\r\nLFMASS,Leaf mass,Leaf carbon mass,g C m-2,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nRTMASS,Mass of fine roots,Root carbon mass,g C m-2,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nSTMASS,Stem mass,Stem carbon mass,g C m-2,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nWOOD,Mass of wood and woody roots,Wood and woody roots carbon mass,g C m-2,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nSTBLCP,Stable carbon in deep soil,Stable carbon in deep soil,g C m-2,Yes,No,No,No,No,No,No,0,5000,0.01,0,-9999\r\nFASTCP,Short-lived carbon in shallow soil,Short-lived carbon in shallow soil,g C m-2,Yes,No,No,No,No,No,No,0,5000,0.01,0,-9999\r\nNEE,Net ecosystem exchange,Net ecosystem exchange,g m-2 s-1 CO2,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nGPP,Net instantaneous assimilation,Net instantaneous carbon assimilation,g m-2 s-1 C,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nNPP,Net primary productivity,Net primary productivity,g m-2 s-1 C,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nPSN,Total photosynthesis,Total photosynthesis,umol CO2 m-2 s-1,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nAPAR,Photosynthesis active energy by canopy,Absorbed photosynthetically active radiation,W m-2,Yes,No,No,No,No,No,No,0,1000,0.01,0,-9999\r\nACCET,Accumulated total ET,Accumulated total evapotranspiration,mm,Yes,Yes,Yes,Yes,Yes,Yes,Yes,-1000,1000000,0.01,0,-9999\r\nCANWAT,Total canopy water (liquid + ice),Total canopy water (liquid + ice),mm,Yes,No,No,Yes,Yes,No,Yes,-5,30000,0.01,0,-9999\r\nSOILICE,fraction of soil moisture that is ice,Fraction of soil moisture that is ice,fraction,Yes,No,No,Yes,No,No,Yes,0,1,0.01,0,-9999\r\nSOILSAT_TOP,fraction of soil saturation (top 2 layers),Fraction of soil saturation (top 2 layers),fraction,Yes,Yes,Yes,Yes,Yes,No,Yes,0,1,0.001,0,-9999\r\nSOILSAT,fraction of soil saturation (column integrated),Fraction of soil saturation (column integrated),fraction,Yes,No,No,No,Yes,No,Yes,0,1,0.001,0,-9999\r\nSNOWT_AVG,average snow temperature (by layer mass),Average snow temperature (by layer mass),K,Yes,Yes,Yes,Yes,No,No,Yes,0,400,0.1,0,-9999\r\nALBSND,snowpack albedo (direct),Snowpack albedo (direct),-,Yes,No,No ,No,No,Yes,Yes,0,1,0.01,0,-9999\r\nALBSNI,snowpack albedo (diffuse),Snowpack albedo (diffuse),-,Yes,No,No,No,No ,Yes,Yes,0,1,0.01,0,-9999\r\n"
  },
  {
    "path": "docs/userguide/output-tables/LSMOUT.csv",
    "content": "Variable Name,Long Name,Description,Units,IO_ConfigOutputs_0,IO_ConfigOutputs_1,IO_ConfigOutputs_2,IO_ConfigOutputs_3,IO_ConfigOutputs_4,IO_ConfigOutputs_5,IO_ConfigOutputs_6,,\r\ntime,valid output time,Valid output time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nreference_time,model initialization time,Model initialization time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nx,x coordinate of projection,x coordinate (in native projection),native projection units,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\ny,y coordinate of projection,x coordinate (in native projection),native projection units,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nstc1,Soil temperature in the top layer,Soil temperature in the top layer,K,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsmc1,Soil moisture in the top layer,Volumetric soil moisture in the top layer,m3 m-3,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsh2ox1,Volumetric soil moisture in the top layer,Liquid water in the top layer,m3 m-3,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nstc2,Soil temperature in the second layer,Soil temperature in the second layer,K,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsmc2,Soil moisture in the second layer,Volumetric soil moisture in the second layer,m3 m-3,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsh2ox2,Volumetric soil moisture in the second layer,Liquid water in the second layer,m3 m-3,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nstc3,Soil temperature in the third layer,Soil temperature in the third layer,K,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsmc3,Soil moisture in the third layer,Volumetric soil moisture in the third layer,m3 m-3,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsh2ox3,Volumetric soil moisture in the third layer,Liquid water in the third layer,m3 m-3,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nstc4,Soil temperature in the fourth layer,Soil temperature in the bottom layer,K,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsmc4,Soil moisture content in the fourth layer,Volumetric soil moisture in the bottom layer,m3 m-3,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsh2ox4,Volumetric soil moisture in the fourth layer,Liquid water in the bottom layer,m3 m-3,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\ninfxsrt,Infiltration excess,Infiltration excess (from LSM),mm,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\nsfcheadrt,Surface head,Surface head (from HYDRO),mm,Yes,Yes,Yes,Yes,Yes,Yes,Yes,,\r\n"
  },
  {
    "path": "docs/userguide/output-tables/RTOUT_DOMAIN.csv",
    "content": "Variable Name,Long Name,Description,Units,IO_ConfigOutputs_0,IO_ConfigOutputs_1,IO_ConfigOutputs_2,IO_ConfigOutputs_3,IO_ConfigOutputs_4,IO_ConfigOutputs_5,IO_ConfigOutputs_6,Min,Max,Scale,Offset,Fill\r\ntime,valid output time,Valid output time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nreference_time,model initialization time,Model initialization time,minutes since 1970-01-01 00:00:00 UTC,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nx,x coordinate of projection,x coordinate (in native projection),native projection units,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\ny,y coordinate of projection,x coordinate (in native projection),native projection units,Yes,Yes,Yes,Yes,Yes,Yes,Yes,N/A,N/A,N/A,N/A,N/A\r\nSOIL_M,volumetric soil moisture,Volumetric soil moisture,m3 m-3,Yes,No,No,No,No,No,No,0,1,0.01,0,-9999\r\nzwattablrt,water table depth,Depth to saturated layers (=2m when no saturation; =0 when fully saturated),m,Yes,Yes,Yes,Yes,Yes,Yes,Yes,0,10,0.1,0,-9999\r\nsfcheadsubrt,surface head,Instantaneous value of depth of ponded water on surface,mm,Yes,Yes,Yes,Yes,Yes,Yes,Yes,0,1000000,1,0,-9999\r\nQSTRMVOLRT,channel inflow,Accumulated depth of stream channel inflow,mm,Yes,No,No,No,No,No,No,0,1000,1,0,-9999\r\nQBDRYRT,accumulated value of the boundary flux,Accumulated flow volume routed outside of the domain from the boundary cells,mm,Yes,No,No,No,No,No,No,0,1000,1,0,-9999\r\n"
  },
  {
    "path": "docs/userguide/references.rest",
    "content": ".. vim: syntax=rst\n\nREFERENCES\n==========\n\nBelow are cited references in an alphabetical listing by author.\n\nBall, J. T., I. E. Woodrow, and J. A. Berry (1987), A model predicting\nstomatal conductance and its contribution to the control of\nphotosynthesis under different environmental conditions, in Process in\nPhotosynthesis Research, vol. 1, edited by J. Biggins, pp. 221–234,\nMartinus Nijhoff, Dordrecht, Netherlands.\n\nBowling, L.C., D.P. Lettenmaier, B. Nijssen, L.P. Graham and\nco-authors, 2003: Simulation of high latitude hydrological processes in\nthe Torne-Kalix basin: PILPS Phase 2(c) 1: Experiment description and\nsummary intercomparisons. Global and Planet. Change\n\nBrun, E., Martin, E., Simon, V., Gendre, C., and Coléou, C.: An energy and\nmass model of snow cover suitable for operational avalanche forecasting, J.\nGlaciol., 35, 333-342, https://doi.org/10.3189/S0022143000009254, 1989.\n\nBrun, E., David, P., Sudul, M., and Brunot, G.: A numer- ical model to simulate\nsnow-cover stratigraphy for operational avalanche forecasting, J. Glaciol., 38,\n13-22, https://doi.org/10.3189/S0022143000009552, 1992.\n\nBrun, E., Martin, E., and Spiridonov, V.: Coupling a multi- layered snow model\nwith a GCM, Ann. Glaciol., 25, 66-72,\nhttps://doi.org/10.3189/S0260305500013811, 1997.\n\nBryan, F. O., B. G. Kauffman, W. G. Large, and P. R. Gent (1996). The\nNCAR CSM flux coupler, NCAR Tech. Note 424, 50 pp. [Available from NCAR,\nBoulder, CO 80307]\n\nChen, F., K.E. Mitchell, J. Schaake, Y. Xue, H.-L. Pan, V. Koren,\nQ.Y. Duan, M. Ek and A. Betts, 1996: Modeling of land-surface\nevaporation by four schemes and comparison with FIFE observations. J.\nGeophys. Res., 101, 7251-7268.\n\nChen, F., Z. Janic and K.E. Mitchell, 1997: Impact of atmospheric\nsurface-layer parameterizations in the new land-surface scheme of the\nNCEP mesoscale Eta model. Bound.-Layer Meteorol., 85, 391-421.\n\nChen, F. and K.E. Mitchell, 1999: Using the GEWEX/ISLSCP forcing\ndata to simulate global soil moisture fields and hydrological cycle for\n1987-1988, J. Meteorol. Soc. Japan, 77, 167-182.\n\nDickinson, R. E., M. Shaikh, R. Bryant, and L. Graumlich (1998),\nInteractive canopies for a climate model, J. Clim., 11, 2823-2836,\ndoi:10.1175/1520-0442.\n\nDirmeyer, P.A., A.J. Dolman, N. Sato, 1999: The pilot phase of\nthe Global Soil Wetness Project. Bull. Am. Meteorol. Soc., 80(5),\n851-878.\n\nEidhammer, T., A. Booth, S. Decker, L. Li, M. Barlage., D. Gochis., R.\nRasmussen, K. Melvold., A. Nesje and S Sobolowski (2021), Mass balance and\nhydrological modeling of the Hardangerjøkulen ice cap in south-central Norway,\nHydrol. Earth Syst. Sci. 25, 4275-4297,\nhttps://doi.org/10.5194/hess-25-4275-2021.\n\nEk, M.B., K.E. Mitchell, Y. Lin, E. Rogers, P. Grunmann, V.\nKoren, G. Gayno, and J.D. Tarpley, 2003: Implementation of Noah land\nsurface model advances in the NCEP operational mesoscale Eta model.\nSubmitted to J. Geophys. Res., Aug., 2003.\n\nGerbaux, M., Genthon, C., Etchevers, P., Vincent, C., and Dedieu, J.: Surface\nmass balance of glacier in the French Alps: Dis- tributed modeling sensitivity\nto climate change, J. Glaciol., 175, 561-572,\nhttps://doi.org/10.3189/172756505781829133, 2005.\n\nGochis, D.J. and F. Chen, 2003: Hydrological enhancements to the\ncommunity Noah land surface model. NCAR Technical Note, NCAR/TN-454+STR,\n68 pgs.\n\nJones, P. W. (1999). First- and Second-Order Conservative Remapping\nSchemes for Grids in Spherical Coordinates, Monthly Weather Review,\nVolume 127, 2204-2210.\n\nJulien, P.Y., B. Saghafian and F.L. Ogden, 1995: Raster-based\nhydrological modeling of spatially-varied surface runoff. Water Resour.\nBull., AWRA, 31(3), 523-536.\n\nKoren, V., J.C. Schaake, K.E. Mitchell, Q.Y. Duan, F. Chen and J.\nBaker, 1999: A parameterization of snowpack and frozen ground intended for\nNCEP weather and climate models. J. Geophys. Res., 104(D16),\n19,569-19,585.\n\nLDAS, 2003: Land Data Assimilation Systems (LDAS). World Wide Web\nHomepage. Available online at: http://ldas.gsfc.nasa.gov/\n\nMahrt, L. and H.-L. Pan, 1984: A two-layer model of soil\nhydrology. Bound.-Layer Meteorol., 29, 1-20, 1984.\n\nNiu, G.-Y., et al. (2011), The community Noah land surface model with\nmultiparameterization options (Noah-MP): 1. Model description and\nevaluation with local-scale measurements, J. Geophys. Res. 116, D12109,\ndoi: 10.1029/2010JD015139.\n\nNiu, G.-Y., and Z.-L. Yang (2004), The effects of canopy processes on\nsnow surface energy and mass balances, J. Geophys. Res., 109, D23111,\ndoi:10.1029/2004JD004884.\n\nNiu, G.-Y., Z.-L. Yang, R. E. Dickinson, L. E. Gulden, and H. Su (2007),\nDevelopment of a simple groundwater model for use in climate models and\nevaluation with Gravity Recovery and Climate Experiment data, J.\nGeophys. Res., 112, D07103, doi:10.1029/2006JD007522.\n\nOgden, F.L., 1997: CASC2D Reference Manual. Dept. of Civil and\nEvniron. Eng. U-37, U. Connecticut, 106 pp.\n\nPan, H.-L. and L. Mahrt, 1987: Interaction between soil hydrology\nand boundary-layer development, Bound.-Layer Meteorol., 38, 185-202.\n\nSkamarock, W. C., J. B. Klemp, J. Dudhia, D. O. Gill, D. M.\nBarker, W. Wang, and J. G. Powers, 2005: A Description of the Advanced\nResearch WRF Version 2. NCAR Technical Note NCAR/TN-468+STR,\ndoi:10.5065/D6DZ069T.\n\nVionnet, V., Brun, E., Morin, S., Boone, A., Faroux, S., Le Moigne, P., Martin,\nE., and Willemet, J.-M.: The detailed snowpack scheme Crocus and its\nimplementation in SURFEX v7.2, Geosci. Model Dev., 5, 773-791,\nhttps://doi.org/10.5194/gmd-5-773- 2012, 2012.\n\nWigmosta, M.S. L.W. Vail and D.P. Lettenmaier, 1994: A\ndistributed hydrology-vegetation model for complex terrain. Water\nResour. Res., 30(6), 1665-1679.\n\nWigmosta, M.S. and D.P. Lettenmaier, 1999: A comparison of\nsimplified methods for routing topographically driven subsurface flow.\nWater Resour. Res., 35(1), 255-264.\n\nWood, E.F., D.P. Lettenmaier, X. Kian, D. Lohmann, A. Boone, S.\nChang, F.Chen, Y. Dai, R.E. Dickinson, Q. Duan, M. Ek, Y.M. Gusev, F.\nHabets, P. Irannejad, R. Koster, K.E. Mitchell, O.N. Nasonova, J.\nNoilhan, J. Schaake, A. Schlosser, Y. Shao, A.B. Shmakin, D. Verseghy,\nK. Warrach, P. Wetzel, Y. Xue, Z.-L. Yang, and Q.-C. Zeng, 1998: The\nproject for intercomparison of land-surface parameterization schemes\n(PILPS) phase 2(c) Red-Arkansas river basin experiment: 1. Experiment\ndescription and summary intercomparisons, Global Planet. Change, 19,\n115-135.\n\nYang, Z.-L., and G.-Y. Niu (2003), The versatile integrator of surface\nand atmosphere processes (VISA) part I: Model description, Global\nPlanet. Change, 38, 175–189, doi:10.1016/S0921-8181(03)00028-6.\n\nESMF (Earth System Modeling Framework)\nhttps://www.earthsystemcog.org/projects/esmf/\n\nUSGS Global Land Cover Characterization\nhttps://www.usgs.gov/centers/eros/science/usgs-eros-archive-landcover-products-global-land-cover-characterization-glcc-0?qt-science_center_objects=0#qt-science_center_objectsTableLegend:Appendix3\nhttps://edcftp.cr.usgs.gov/project/glcc/globdoc2_0.html#app3\n\nIGBP_MODIS_BU+tundra Landcover Class Legend\n\nftp://ftp.emc.ncep.noaa.gov/mmb/gcp/ldas/noahlsm/README\n\nNCL (NCAR Command Language) https://www.ncl.ucar.edu/\n\nCDO (Climate Data Operators) https://code.mpimet.mpg.de/projects/cdo/\n"
  },
  {
    "path": "src/.nwm_version",
    "content": "v3.1\n"
  },
  {
    "path": "src/.version",
    "content": "v5.4.0\n"
  },
  {
    "path": "src/CMakeLists.txt",
    "content": "if(${PROJECT_NAME} STREQUAL \"WRF\")\n        # additions that WRF-Hydro's top CMakeLists.txt handles\n        add_compile_options( \"${PROJECT_COMPILE_OPTIONS}\" )\n        add_compile_definitions( \"${PROJECT_COMPILE_DEFINITIONS}\" )\n        set(CMAKE_Fortran_MODULE_DIRECTORY ${PROJECT_BINARY_DIR}/hydro/mods)\n        add_definitions(-DMPP_LAND)\n        if (WRF_HYDRO_NUDGING STREQUAL \"1\")\n                add_definitions(-DWRF_HYDRO_NUDGING=1)\n        endif()\nendif()\n\n\n# build the various sup-projects\nadd_subdirectory(\"MPP\")\nadd_subdirectory(\"utils\")\nadd_subdirectory(\"IO\")\nadd_subdirectory(\"OrchestratorLayer\")\nadd_subdirectory(\"Debug_Utilities\")\nadd_subdirectory(\"Routing/Overland\")\nadd_subdirectory(\"Routing/Subsurface\")\nadd_subdirectory(\"Routing/Reservoirs\")\nadd_subdirectory(\"Routing/Diversions\")\nadd_subdirectory(\"Data_Rec\")\nadd_subdirectory(\"Routing\")\nadd_subdirectory(\"HYDRO_drv\")\nif(${PROJECT_NAME} STREQUAL \"WRF\")\n        add_subdirectory(\"CPL/WRF_cpl\")\nendif()\n\nif (WRF_HYDRO_NUDGING_IO STREQUAL \"1\" OR\n    WRF_HYDRO_NUDGING STREQUAL \"1\")\n        add_subdirectory(\"nudging/io\")\n        add_dependencies(hydro_routing hydro_nudging_io)\nendif()\n\nif (WRF_HYDRO_NUDGING STREQUAL \"1\")\n        add_subdirectory(\"nudging\")\n        add_dependencies(hydro_routing hydro_nudging)\n        add_dependencies(hydro_driver hydro_nudging)\nendif()\n\nif (WRF_HYDRO_NUOPC STREQUAL \"1\")\n        add_subdirectory(\"CPL/NUOPC_cpl\")\nendif()\n\n# add module dependencies\nadd_dependencies(hydro_debug_utils hydro_mpp)\nadd_dependencies(hydro_utils hydro_mpp)\nadd_dependencies(hydro_orchestrator hydro_netcdf_layer)\n\nadd_dependencies(hydro_routing\n        hydro_mpp\n        hydro_routing_overland\n        hydro_routing_subsurface\n        hydro_routing_reservoirs\n        hydro_routing_reservoirs_levelpool\n        hydro_routing_reservoirs_hybrid\n        hydro_utils\n)\n\nadd_dependencies(hydro_routing_reservoirs_hybrid hydro_routing_reservoirs_levelpool)\nadd_dependencies(hydro_routing_overland hydro_mpp)\n\n# currently unused Routing/Groundwater directory\n# add_subdirectory(\"Routing/Groundwater\")\n# add_dependencies(hydro_routing\n#         hydro_routing_groundwater\n#         hydro_routing_groundwater_bucket\n#         hydro_routing_groundwater_nhd\n#         hydro_routing_groundwater_simple\n# )\n# add_dependencies(hydro_routing_groundwater hydro_mpp)\n# add_dependencies(hydro_routing_groundwater_bucket hydro_routing_groundwater)\n# add_dependencies(hydro_routing_groundwater_simple\n#         hydro_routing_groundwater\n#         hydro_routing_groundwater_bucket\n# )\n# add_dependencies(hydro_routing_groundwater_nhd\n#         hydro_routing_groundwater\n#         hydro_routing_groundwater_bucket\n# )\n\nadd_dependencies(hydro_driver\n        hydro_routing\n        hydro_debug_utils\n)\n\nadd_dependencies(hydro_data_rec\n        hydro_routing_overland\n        hydro_routing_subsurface\n        hydro_routing_reservoirs\n)\n\nif (HYDRO_LSM MATCHES \"NoahMP\")\n        message(\"-- Building NoahMP LSM\")\n        add_subdirectory(\"Land_models/NoahMP\")\n\n        add_subdirectory(\"CPL/NoahMP_cpl\")\n        add_dependencies(hydro_noahmp_cpl hydro_routing)\n        add_dependencies(hydro_noahmp_cpl hydro_mpp )\n        add_dependencies(hydro_noahmp_cpl hydro_driver )\n\n        add_executable(wrfhydro\n                Land_models/NoahMP/IO_code/main_hrldas_driver.F\n                Land_models/NoahMP/IO_code/module_hrldas_netcdf_io.F\n                Land_models/NoahMP/IO_code/module_NoahMP_hrldas_driver.F\n        )\n\n        target_include_directories(wrfhydro BEFORE PUBLIC ${PROJECT_BINARY_DIR}/mods)\n\n        target_link_libraries(wrfhydro\n                hydro_utils\n                hydro_mpp\n                hydro_debug_utils\n                hydro_routing_overland\n                hydro_routing_subsurface\n                hydro_data_rec\n                hydro_routing\n                hydro_routing_reservoirs_levelpool\n                hydro_routing_reservoirs_hybrid\n                hydro_routing_reservoirs_rfc\n                hydro_routing_reservoirs\n                hydro_driver\n                noahmp_util\n                noahmp_phys\n                noahmp_data\n                hydro_noahmp_cpl\n                ${NETCDF_LIBRARIES}\n                # hydro_routing_groundwater\n                # hydro_routing_groundwater_bucket\n                # hydro_routing_groundwater_nhd\n                # hydro_routing_groundwater_simple\n        )\n\n        if (WRF_HYDRO_NUDGING_IO STREQUAL \"1\")\n          target_link_libraries(wrfhydro hydro_nudging_io)\n          add_dependencies(wrfhydro hydro_nudging_io)\n        endif()\n\n        if (WRF_HYDRO_NUDGING STREQUAL \"1\")\n                target_link_libraries(wrfhydro hydro_nudging)\n                target_link_libraries(wrfhydro hydro_routing_diversions)\n                add_dependencies(wrfhydro hydro_nudging)\n                add_dependencies(wrfhydro hydro_routing_diversions)\n        endif()\n\n        # bash commands to copy namelists to the Run directory\n        set(BASH_CP_HRLDAS_NML \"if [[ ! -f ${CMAKE_BINARY_DIR}/Run/namelist.hrldas ]]\\; then cp ${PROJECT_SOURCE_DIR}/src/template/NoahMP/namelist.hrldas ${CMAKE_BINARY_DIR}/Run \\; fi\\;\")\n        set(BASH_CP_HYDRO_NML \"if [[ ! -f ${CMAKE_BINARY_DIR}/Run/hydro.namelist ]]\\; then cp ${PROJECT_SOURCE_DIR}/src/template/HYDRO/hydro.namelist ${CMAKE_BINARY_DIR}/Run \\; fi\\;\")\n\n        add_custom_command(TARGET wrfhydro POST_BUILD\n                COMMAND mkdir -p ${CMAKE_BINARY_DIR}/Run\n                COMMAND cp ${PROJECT_SOURCE_DIR}/tests/ctests/run_dir_makefile.mk ${CMAKE_BINARY_DIR}/Run/Makefile\n                # copy tables\n                COMMAND cp ${PROJECT_SOURCE_DIR}/src/template/HYDRO/CHANPARM.TBL ${CMAKE_BINARY_DIR}/Run\n                COMMAND cp ${PROJECT_SOURCE_DIR}/src/template/HYDRO/HYDRO.TBL ${CMAKE_BINARY_DIR}/Run\n                COMMAND cp ${PROJECT_SOURCE_DIR}/src/Land_models/NoahMP/run/*.TBL ${CMAKE_BINARY_DIR}/Run\n                # copy namelists\n                COMMAND bash -c \"${BASH_CP_HRLDAS_NML}\"\n                COMMAND bash -c \"${BASH_CP_HYDRO_NML}\"\n                # copy and setup executables\n                COMMAND rm -f ${CMAKE_BINARY_DIR}/Run/wrf_hydro\n                COMMAND rm -f ${CMAKE_BINARY_DIR}/Run/wrf_hydro_NoahMP\n                COMMAND cp ${PROJECT_BINARY_DIR}/src/wrfhydro ${CMAKE_BINARY_DIR}/Run/wrf_hydro\n                COMMAND ln -sf ${CMAKE_BINARY_DIR}/Run/wrf_hydro ${CMAKE_BINARY_DIR}/Run/wrf_hydro_NoahMP\n                COMMAND rm ${PROJECT_BINARY_DIR}/src/wrfhydro\n        )\n        if(WRF_HYDRO_CREATE_EXE_SYMLINK)\n                add_custom_command(TARGET wrfhydro POST_BUILD\n                        COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_BINARY_DIR}/Run/wrf_hydro ${CMAKE_BINARY_DIR}/Run/wrf_hydro.exe\n                )\n        endif()\n\nelseif (HYDRO_LSM MATCHES \"Noah\")\n        message(\"-- Building Noah LSM\")\n        add_subdirectory(\"Land_models/Noah\")\n        add_subdirectory(\"CPL/Noah_cpl\")\n\n        add_dependencies(hydro_noah_cpl hydro_routing)\n        add_dependencies(hydro_noah_cpl hydro_mpp )\n        add_dependencies(hydro_noah_cpl hydro_driver )\n\n        add_executable(wrfhydro\n                Land_models/Noah/IO_code/module_hrldas_netcdf_io.F\n                Land_models/Noah/IO_code/Noah_hrldas_driver.F\n        )\n\n        target_include_directories(wrfhydro BEFORE PUBLIC ${PROJECT_BINARY_DIR}/mods)\n\n        target_link_libraries(wrfhydro\n                hydro_utils\n                hydro_mpp\n                hydro_debug_utils\n                hydro_routing_overland\n                hydro_routing_subsurface\n                hydro_data_rec\n                hydro_routing\n                hydro_driver\n                hydro_routing_reservoirs_levelpool\n                hydro_routing_reservoirs_hybrid\n                hydro_routing_reservoirs_rfc\n                hydro_routing_reservoirs\n                noah_util\n                noah\n                hydro_noah_cpl\n                ${NETCDF_LIBRARIES}\n                ${MPI_Fortran_LIBRARIES}\n                # hydro_routing_groundwater\n                # hydro_routing_groundwater_bucket\n                # hydro_routing_groundwater_nhd\n                # hydro_routing_groundwater_simple\n        )\n\n        if (WRF_HYDRO_NUDGING STREQUAL \"1\")\n                target_link_libraries(wrfhydro hydro_nudging)\n                add_dependencies(wrfhydro hydro_nudging)\n        endif()\n\n        add_custom_command(TARGET wrfhydro POST_BUILD\n                COMMAND mkdir -p ${CMAKE_BINARY_DIR}/Run\n                COMMAND rm -f ${CMAKE_BINARY_DIR}/Run/*\n                COMMAND cp ${PROJECT_BINARY_DIR}/src/wrfhydro ${CMAKE_BINARY_DIR}/Run/wrf_hydro_Noah\n                COMMAND cp ${PROJECT_SOURCE_DIR}/src/template/Noah/* ${CMAKE_BINARY_DIR}/Run\n                COMMAND cp ${PROJECT_SOURCE_DIR}/src/template/HYDRO/CHANPARM.TBL ${CMAKE_BINARY_DIR}/Run\n                COMMAND cp ${PROJECT_SOURCE_DIR}/src/template/HYDRO/hydro.namelist ${CMAKE_BINARY_DIR}/Run\n                COMMAND cp ${PROJECT_SOURCE_DIR}/src/template/HYDRO/HYDRO.TBL ${CMAKE_BINARY_DIR}/Run\n                COMMAND cp ${PROJECT_SOURCE_DIR}/src/Land_models/Noah/Run/*.TBL ${CMAKE_BINARY_DIR}/Run\n                COMMAND ln -sf ${CMAKE_BINARY_DIR}/Run/wrf_hydro_Noah ${CMAKE_BINARY_DIR}/Run/wrf_hydro\n                COMMAND ln -sf ${CMAKE_BINARY_DIR}/Run/wrf_hydro_Noah ${CMAKE_BINARY_DIR}/Run/wrf_hydro.exe\n                COMMAND rm ${PROJECT_BINARY_DIR}/src/wrfhydro\n        )\n\nelseif(${PROJECT_NAME} STREQUAL \"WRF\")\n        add_library(wrfhydro INTERFACE)\n        target_link_libraries(wrfhydro INTERFACE\n                hydro_utils\n                hydro_mpp\n                hydro_debug_utils\n                hydro_routing_overland\n                hydro_routing_subsurface\n                hydro_data_rec\n                hydro_routing\n                hydro_routing_reservoirs_levelpool\n                hydro_routing_reservoirs_hybrid\n                hydro_routing_reservoirs_rfc\n                hydro_routing_reservoirs\n                hydro_wrf_cpl\n                hydro_orchestrator\n                hydro_netcdf_layer\n                hydro_driver\n        )\nelse()\n        message(\"Unknown land surface model:\" ${HYDRO_LSM} )\nendif()\n"
  },
  {
    "path": "src/CPL/CLM_cpl/Makefile",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\nCLMOBJPATH = /d1/weiyu/scratch/merra_boulder\n\nCLM_MOD = -I $(CLMOBJPATH)/lnd/obj -I $(CLMOBJPATH)/lib/include\n\ninclude ../../macros\n\nMODFLAG =       -I./ -I ../../MPP -I ../../mod\n\nOBJS = \\\n\tmodule_clm_HYDRO.o \\\n\tclm_drv_HYDRO.o    \nall:\t$(OBJS) \n\n.F.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -I$(NETCDFINC) -o $(@) $(F90FLAGS) $(MODFLAG) -I ../../mod $(CLM_MOD) $(*).F\n\t@echo \"\"\n\tar -r ../../lib/libHYDRO.a $(@)\n\n#\n# Dependencies:\n#\n\nclean:\n\trm -f *.o *.mod *.stb *~ \n\tcd ../..; make -f Makefile.comm clean\n"
  },
  {
    "path": "src/CPL/CLM_cpl/Makefile.cpl",
    "content": "# Makefile \n\nall:\n\t(cd ../../; make -f Makefile.comm)\n\t(make)\n\nclean:\n\t(cd ../../; make -f Makefile.comm clean)\n"
  },
  {
    "path": "src/CPL/CLM_cpl/bat2.csh",
    "content": "#!/bin/csh -f\nmake -f Makefile.cpl\n\nrm -f /d1/weiyu/scratch/merra_boulder/run/ccsm.exe\ncd /d1/weiyu/scratch/merra_boulder/ccsm/obj\n\nmpif90 -o /d1/weiyu/scratch/merra_boulder/run/ccsm.exe ccsm_comp_mod.o ccsm_driver.o map_atmatm_mct.o map_atmice_mct.o map_atmlnd_mct.o map_atmocn_mct.o map_glcglc_mct.o map_iceice_mct.o map_iceocn_mct.o map_lndlnd_mct.o map_ocnocn_mct.o map_rofocn_mct.o map_rofrof_mct.o map_snoglc_mct.o map_snosno_mct.o mrg_x2a_mct.o mrg_x2g_mct.o mrg_x2i_mct.o mrg_x2l_mct.o mrg_x2o_mct.o mrg_x2s_mct.o seq_avdata_mod.o seq_diag_mct.o seq_domain_mct.o seq_flux_mct.o seq_frac_mct.o seq_hist_mod.o seq_rearr_mod.o seq_rest_mod.o -L/d1/weiyu/scratch/merra_boulder/lib -latm -llnd -lice -locn -lglc -L/d1/weiyu/scratch/merra_boulder/lib -lcsm_share -lmct -lmpeu -lpio  -L/home/weiyu/netcdf/lib -lnetcdf -lnetcdff -L /raid/weiyu/LIS_trunk2/p61_NDHMS/routing/ndhms_wrf_hydro/src/lib -lHYDRO\n"
  },
  {
    "path": "src/CPL/CLM_cpl/cesm_cpl_compiling.csh",
    "content": "#!/bin/csh -f\ncd /raid/weiyu/scratch/clm4_ndhms/ccsm/obj\n\nmpif90 -o /d1/weiyu/scratch/clm4_ndhms/run/ccsm.exe ccsm_comp_mod.o ccsm_driver.o map_atmatm_mct.o map_atmice_mct.o map_atmlnd_mct.o map_atmocn_mct.o map_glcglc_mct.o map_iceice_mct.o map_iceocn_mct.o map_lndlnd_mct.o map_ocnocn_mct.o map_rofocn_mct.o map_rofrof_mct.o map_snoglc_mct.o map_snosno_mct.o mrg_x2a_mct.o mrg_x2g_mct.o mrg_x2i_mct.o mrg_x2l_mct.o mrg_x2o_mct.o mrg_x2s_mct.o seq_avdata_mod.o seq_diag_mct.o seq_domain_mct.o seq_flux_mct.o seq_frac_mct.o seq_hist_mod.o seq_rearr_mod.o seq_rest_mod.o -L/d1/weiyu/scratch/clm4_ndhms/lib -latm -llnd -lice -locn -lglc -L/d1/weiyu/scratch/clm4_ndhms/lib -lcsm_share -lmct -lmpeu -lpio  -L/home/weiyu/netcdf/lib -lnetcdf -lnetcdff -L /d1/weiyu/LISv6.1/src/routing/NCAR_router/lib -lland -lNDHMS\n"
  },
  {
    "path": "src/CPL/CLM_cpl/clm_drv_HYDRO.F",
    "content": "subroutine clm_drv_HYDRO()\n  use module_clm_HYDRO, only: clm_cpl_HYDRO\n  implicit none\n  call clm_cpl_HYDRO()\nend subroutine clm_drv_HYDRO\n"
  },
  {
    "path": "src/CPL/CLM_cpl/module_clm_HYDRO.F",
    "content": "\nmodule module_CLM_HYDRO\n    use domainMod        , only : ldomain\n    use clmtype   , only : clm3\n    use clm_varpar   , only : nlevgrnd\n    use decompMod    , only : get_proc_bounds, get_proc_global\n    use clm_varcon  , only : zsoi\n    use subgridAveMod, only: l2g_1d\n    use subgridAveMod, only: c2g_1d, c2g_2d\n\n\n! NDHMS  module\n     use module_mpp_land, only: global_nx, global_ny, decompose_data_real, &\n                 write_io_real, my_id\n    use module_hydro_stop, only: HYDRO_stop\n    use module_HYDRO_drv, only: HYDRO_ini, HYDRO_exe\n\n    implicit none\n    integer begg, endg\n    integer :: numg, numl, numc, nump\n    INTEGER, PARAMETER :: double=8\n    real(kind=double), pointer :: r2p(:,:) , r1p(:)\n\n    integer ::  begl, endl, begc, endc, begp, endp\n    real(kind=double), allocatable, dimension(:) :: clm_g1d\n    real(kind=double), allocatable, dimension(:,:) :: clm_g2d\n\n    real, allocatable, dimension(:,:) :: vg_test\n\n\n\nCONTAINS\n\n    subroutine clm_cpl_HYDRO()\n\n       use module_rt_data, only:  rt_domain\n       use module_CPL_LAND, only: CPL_LAND_INIT, cpl_outdate\n       use module_mpp_land\n       use config_base, only: nlst\n\n        implicit none\n        integer k, ix,jx, nn\n\n        integer ::  did\n\n        integer ntime, wrf_ix,wrf_jx\n        real cpl_land_dt\n\n        integer :: i,j\n        integer clm_lev\n\n!output flux and state variable\n\n        did = 1\n\n        call get_cpl_date(cpl_land_dt)\n\n#ifdef HYDRO_D\n        write(6,*) \"cpl_land_dt = \",cpl_land_dt\n#endif\n\n        ntime = 1\n\n        if(.not. RT_DOMAIN(did)%initialized) then\n\n\n\n\n            call HYDRO_ini(ntime,did,1,1)\n\n            if(nlst(did)%sys_cpl .ne. 4) then\n               write(6,*) \"FATAL ERROR: sys_cpl should be 4.\"\n               call hydro_stop(\"In module_clm_HYDRO.F clm_cpl_HYDRO() - \"// &\n                               \"sys_cpl should be 4.  Check hydro.namelist file\")\n            endif\n\n            RT_DOMAIN(did)%initialized = .true.\n            nlst(did)%dt = cpl_land_dt\n            nlst(did)%startdate(1:19) = cpl_outdate(1:19)\n            nlst(did)%olddate(1:19) = cpl_outdate(1:19)\n        endif\n\n        if(nlst(did)%rtFlag .eq. 0) return\n\n        ix = rt_domain(did)%ix\n        jx = rt_domain(did)%jx\n\n        ! get the initial data from CLM\n            call get_proc_global(numg, numl, numc, nump)\n\n            call get_proc_bounds(begg, endg, begl, endl, begc, endc, begp, endp)\n#ifdef HYDRO_D\n            write(6,*) \"begg, endg, \", begg, endg\n            write(6,*) \"begl, endl, \", begl, endl\n            write(6,*) \"begc, endc, \", begc, endc\n            write(6,*) \"begp, endp, \", begp, endp\n#endif\n\n!            call get_proc_bounds( begg=begg, endg=endg )\n            nn = endg - begg + 1\n\n            allocate(clm_g1d(endg-begg + 1))\n            allocate(clm_g2d(endg-begg+1, nlevgrnd) )\n\n\n\n\n\n            r1p => clm3%g%l%c%cwf%qflx_surf\n            call c2g_1d(begc, endc, begl, endl, begg, endg, r1p(begc:endc), clm_g1d, &\n                'urbanf', 'unity')\n            call clm2ND2d(clm_g1d,nn,RT_DOMAIN(did)%INFXSRT,ix,jx)\n\n#ifdef HYDRO_D\n            write(6,*) \"finish qflx_surf\"\n\n#endif\n\n            r1p => clm3%g%l%c%cwf%qflx_drain\n            call c2g_1d(begc, endc, begl, endl, begg, endg, r1p(begc:endc), clm_g1d, &\n                'urbanf', 'unity')\n            call clm2ND2d(clm_g1d,nn,RT_DOMAIN(did)%SOLDRAIN,ix,jx)\n\n\n#ifdef HYDRO_D\n            write(6,*) \"finish qflx_drain \"\n#endif\n            r2p =>clm3%g%l%c%ces%t_soisno\n                call c2g_2d(begc, endc, begl, endl, begg, endg, nlevgrnd, r2p(begc:endc,1:nlevgrnd), clm_g2d, &\n                'urbanh', 'unity')\n            call clm2ND3d (clm_g2d,nn,nlevgrnd,zsoi(1:nlevgrnd), &\n                      ix,jx, nlst(did)%nsoil,abs(rt_domain(did)%subsurface%properties%zsoil(1:nlst(did)%nsoil)),&\n                      RT_DOMAIN(did)%STC)\n\n#ifdef HYDRO_D\n            write(6,*) \"finish t_soisno   \"\n#endif\n\n            r2p => clm3%g%l%c%cws%h2osoi_vol\n                call c2g_2d(begc, endc, begl, endl, begg, endg, nlevgrnd, r2p(begc:endc,1:nlevgrnd), clm_g2d, &\n                'urbanh', 'unity')\n            call clm2ND3d (clm_g2d,nn,nlevgrnd,zsoi(1:nlevgrnd), &\n                     ix,jx, nlst(did)%nsoil,abs(rt_domain(did)%subsurface%properties%zsoil(1:nlst(did)%nsoil)),&\n                     RT_DOMAIN(did)%SMC)\n#ifdef HYDRO_D\n            write(6,*) \"finish h2osoi_vol \"\n\n#endif\n\n            r2p => clm3%g%l%c%cws%h2osoi_liq\n            call c2g_2d(begc, endc, begl, endl, begg, endg, nlevgrnd, r2p(begc:endc,1:nlevgrnd), clm_g2d, &\n                'urbanh', 'unity')\n            call clm2ND3d (clm_g2d, nn,nlevgrnd,zsoi(1:nlevgrnd), &\n                     ix,jx, nlst(did)%nsoil,abs(rt_domain(did)%subsurface%properties%zsoil(1:nlst(did)%nsoil)),&\n                     RT_DOMAIN(did)%SH2OX)\n            RT_DOMAIN(did)%SH2OX =  RT_DOMAIN(did)%SH2OX /1000.\n #ifdef HYDRO_D\n            write(6,*) \"finish h2osoi_liq \"\n\n            write(6,*) \"before call HYDRO_exe\"\n\n#endif\n\n\n            call HYDRO_exe(did)\n\n#ifdef HYDRO_D\n            write(6,*) \"after call HYDRO_exe\"\n\n#endif\n! add for update the CLM state variable.\n\n           clm_lev = 10\n\n            r2p =>clm3%g%l%c%ces%t_soisno\n            call Toclm3d (clm_g2d,nn,clm_lev,zsoi(1:clm_lev), &\n                     ix,jx, nlst(did)%nsoil,abs(rt_domain(did)%subsurface%properties%zsoil(1:nlst(did)%nsoil)),&\n                     RT_DOMAIN(did)%STC)\n            call g2c_2d(begc, endc, begl, endl, begg, endg,clm_lev,r2p(begc:endc,1:clm_lev), clm_g2d, &\n                'urbanh', 'unity')\n\n\n\n\n            r2p => clm3%g%l%c%cws%h2osoi_vol\n            call Toclm3d (clm_g2d,nn,clm_lev,zsoi(1:clm_lev), &\n                     ix,jx, nlst(did)%nsoil,abs(rt_domain(did)%subsurface%properties%zsoil(1:nlst(did)%nsoil)), &\n                     RT_DOMAIN(did)%SMC)\n            call g2c_2d_tmp(begc, endc, begl, endl, begg, endg,clm_lev,r2p(begc:endc,1:clm_lev), clm_g2d, &\n                'urbanh', 'unity', 0.01, 10.)\n\n\n\n            r2p => clm3%g%l%c%cws%h2osoi_liq\n            call Toclm3d(clm_g2d,nn,clm_lev,zsoi(1:clm_lev), &\n                     ix,jx, nlst(did)%nsoil,abs(rt_domain(did)%subsurface%properties%zsoil(1:nlst(did)%nsoil)),&\n                     RT_DOMAIN(did)%SH2OX*1000)\n            call g2c_2d_tmp(begc, endc, begl, endl, begg, endg,clm_lev,r2p(begc:endc,1:clm_lev), clm_g2d, &\n                'urbanh', 'unity',0.01, 10.)\n\n\n\n\n     ! 2d variable\n     !      t_soisno\n     ! 3 d variable\n     deallocate(clm_g1d)\n     deallocate(clm_g2d)\n#ifdef HYDRO_D\n            write(6,*) \"end of drive ndhms\"\n#endif\n\n     end subroutine clm_cpl_HYDRO\n\n      subroutine Toclm3d (v1d_out,nn,kk1,z1_in,ix,jx,kk2,z2,v2_in)\n        implicit none\n          integer :: nn,ix,jx, kk2, kk1\n          integer :: k\n          real:: v2_in(ix,jx,kk2)\n          real:: v1(ix,jx,kk1)\n          real, dimension(kk2) :: z2\n          REAL (KIND=double),dimension(nn,kk1):: v1d_out\n          REAL (KIND=double),dimension(kk1):: z1_in\n          REAL ,dimension(kk1):: z1\n\n          z1 = z1_in\n\n! v1 is the out from interp3D\n             call Interp3D (z2,v2_in,kk2,z1,v1,ix,jx,kk1)\n\n\n\n             do k = 1, kk1\n                call Toclm2d(v1(:,:,k),ix,jx,v1d_out(:,k),nn)\n             end do\n\n      end subroutine Toclm3d\n\n      subroutine Toclm2d(v1,ix,jx,v1d_out,nn)\n         use module_mpp_land, only: my_id,IO_id,mpp_land_bcast_real\n         implicit none\n         integer ix,jx, nn\n         real v1(ix,jx)\n         REAL (KIND=double),dimension(nn) :: v1d_out\n         real, dimension(global_nx*global_ny)::vg\n         real, dimension(global_nx,global_ny)::vg2d\n\n\n            call write_io_real(v1,vg2d)\n\n            vg = 0.0\n            if(my_id .eq. IO_id) then\n                call TO1d(vg2d,vg,global_nx,global_ny)\n            end if\n\n#ifdef HYDRO_D\n            write(6,*) \"before scatter_1d_r\"\n\n#endif\n\n            call scatter_1d_r(v1d_out,nn,vg,global_nx*global_ny)\n\n#ifdef HYDRO_D\n            write(6,*) \"after scatter_1d_r\"\n\n#endif\n      end subroutine Toclm2d\n\n      subroutine TO1d(vg2d,v1d,nx,ny)\n         implicit none\n         integer nx,ny, n, i,j\n         real vg2d(nx,ny)\n         real v1d(nx*ny)\n             do j = 1,ny\n             do i = 1,nx\n                n = (j-1)*nx + i\n                v1d(n) = vg2d(i,j)\n             enddo\n             enddo\n      end subroutine TO1d\n\n      subroutine clm2ND3d (v1d_in,nn,kk1,z1_in,ix,jx,kk2,z2,vout)\n        implicit none\n          integer :: nn,kk1,ix,jx,kk2\n          integer :: k\n          real:: vout(ix,jx,kk2)\n          real:: v1(ix,jx,kk1)\n          real(kind=double),dimension(nn,kk1):: v1d_in\n          real(kind=double), dimension(kk1) :: z1_in\n          real, dimension(kk1) :: z1\n          real, dimension(kk2) :: z2\n\n\n          z1 = z1_in\n\n          do k = 1, kk1\n             call clm2ND2d(v1d_in(:,k),nn,v1(:,:,k),ix,jx)\n          end do\n             call Interp3D (z1(1:kk1),v1,kk1,z2(1:kk2),vout,ix,jx,kk2)\n\n      end subroutine clm2ND3d\n\n      subroutine clm2ND2d (v1d_in,nn,vout,ix,jx)\n          use clmtype, only: grlnd\n          use module_mpp_land, only: my_id,IO_id,mpp_land_bcast_real\n          implicit none\n          integer :: ix,jx,nn, n\n          real vout(ix,jx)\n          integer :: i,j,gni,gnj\n!         ! real, allocatable, dimension(:)  :: g1d\n          real(kind=double), dimension(global_nx*global_ny)  :: g1d\n          real v2d_g(global_nx,global_ny)\n          real(kind=double),dimension(nn) ::  v1d_in\n\n\n          gni = global_nx\n          gnj = global_ny\n!     gather 1d global array\n\n          if(endg .gt. gni*gnj) then\n            write(6,*) \"WARNING: endg > gni*gnj\", endg, gni*gnj\n            ! need to stop\n          endif\n          call gather_1d_real(v1d_in,nn,g1d,gni*gnj)\n!  transfer 1d   to 2d\n\n          if(my_id.eq.IO_id) then\n             do j = 1,gnj\n             do i = 1,gni\n                n = (j-1)*gni + i\n                v2d_g(i,j) = g1d(n)\n             enddo\n             enddo\n          endif\n\n!         if(my_id .eq. 0) then\n!            call output_nc(v2d_g,gni,gnj, \"test\", \"test.nc\")\n!         endif\n\n! domain decomposition\n          call decompose_data_real(v2d_g,vout)\n\n      end subroutine clm2ND2d\n\n      subroutine Interp3D (z1,v1,kk1,z,vout,ix,jx,kk)\n!  input: z1,v1,kk1,z,ix,jx,kk\n!  output: vout\n!  interpolate based on soil layer: z1 and z\n!  z :  soil layer of output variable.\n!  z1: array of soil layers of input variable.\n         implicit none\n         integer:: i,j,k\n         integer:: kk1, ix,jx,kk\n         real :: z1(kk1), z(kk), v1(ix,jx,kk1),vout(ix,jx,kk)\n\n!        write(6,*) \"k, kk1 \", k, kk1\n!        write(6,*) \"z1(kk1), z(k) \", z1(kk1), z(k)\n\n         do j = 1, jx\n            do i = 1, ix\n              do k = 1, kk\n!                call interpLayer(abs(Z1),v1(i,j,1:kk1),kk1,abs( Z(k) ),vout(i,j,k))\n                call interpLayer(Z1(1:kk1),v1(i,j,1:kk1),kk1,Z(k),vout(i,j,k))\n              end do\n            end do\n         end do\n      end subroutine Interp3D\n\n      subroutine interpLayer(inZ,inV,inK,outZ,outV)\n         implicit none\n         integer:: k, k1, k2\n         integer :: inK\n         real:: inV(inK),inZ(inK)\n         real:: outV, outZ, w1, w2\n\n         if(outZ .le. inZ(1)) then\n             if(inZ(2) .eq. inZ(1)) then\n                write(6,*) \"FATAL ERROR: inZ(2)=inZ(1) \", inZ(2),inZ(1)\n               !stop 99\n               stop(\"In module_clm_HYDRO.F interpLayer() - inZ(2)=inZ(1)\")\n             end if\n             w1 = (inZ(2)-outZ)/(inZ(2)-inZ(1))\n             w2 = (inZ(1)-outZ)/(inZ(2)-inZ(1))\n             outV = inV(1)*w1-inV(2)*w2\n             return\n         elseif(outZ .ge. inZ(inK)) then\n             if(inZ(inK-1) .eq. inZ(inK)) then\n                write(6,*) \"FATAL ERROR: inZ(inK-1)=inZ(inK) \", inZ(inK-1),inZ(inK)\n                !stop 99\n                stop(\"FATAL ERROR: In module_clm_HYDRO.F interpLayer() - inZ(inK-1)=inZ(inK)\")\n             end if\n             w1 = (outZ-inZ(inK-1))/(inZ(inK)-inZ(inK-1))\n             w2 = (outZ-inZ(inK))  /(inZ(inK)-inZ(inK-1))\n             outV = inV(inK)*w1 -inV(inK-1)* w2\n             return\n         else\n            do k = 2, inK\n             if((inZ(k) .ge. outZ).and.(inZ(k-1) .le. outZ) ) then\n                k1  = k-1\n                k2 = k\n             if(inZ(k1) .eq. inZ(k2)) then\n                write(6,*) \"FATAL ERROR: inZ(k1)=inZ(k2) \", inZ(k1),inZ(k2)\n                !stop 99\n                stop(\"FATAL ERROR: In module_clm_HYDRO.F interpLayer()- inZ(k1)=inZ(k2)\")\n             end if\n                w1 = (outZ-inZ(k1))/(inZ(k2)-inZ(k1))\n                w2 = (inZ(k2)-outZ)/(inZ(k2)-inZ(k1))\n                outV = inV(k2)*w1 + inV(k1)*w2\n                return\n             end if\n            end do\n         endif\n      end subroutine interpLayer\n\n    subroutine get_cpl_date(cpl_land_dt)\n      use clm_time_manager, only : get_step_size, get_curr_date\n      use module_CPL_LAND, only: cpl_outdate\n      implicit none\n      integer :: yr, mo, da, hr, mn, ss , sec\n      real :: cpl_land_dt\n      integer cmdate\n\n      cpl_land_dt  = 1.0* get_step_size()\n\n      call get_curr_date(yr, mo, da, sec)\n\n\n      hr = sec/3600\n\n      sec = mod(sec,3600)\n      mn = sec/60\n\n      ss = mod(sec,60)\n\n      if(yr .lt. 1000) yr = 2000+yr\n      write(cpl_outdate(1:4),'(I4)') yr\n\n      if(mo .lt. 10 ) then\n         write(cpl_outdate(5:7),'(\"-0\",I1)') mo\n      else\n         write(cpl_outdate(5:7),'(\"-\",I2)') mo\n      endif\n\n      if(da .lt. 10 ) then\n         write(cpl_outdate(8:10),'(\"-0\",I1)') da\n      else\n         write(cpl_outdate(8:10),'(\"-\",I2)') da\n      endif\n\n      if(hr .lt. 10 ) then\n         write(cpl_outdate(11:13),'(\"_0\",I1)') hr\n      else\n         write(cpl_outdate(11:13),'(\"_\",I2)') hr\n      endif\n\n      if(mn .lt. 10 ) then\n         write(cpl_outdate(14:16),'(\":0\",I1)') mn\n      else\n         write(cpl_outdate(14:16),'(\":\",I2)') mn\n      endif\n\n      if(ss .lt. 10 ) then\n         write(cpl_outdate(17:19),'(\":0\",I1)') ss\n      else\n         write(cpl_outdate(17:19),'(\":\",I2)') ss\n      endif\n\n\n\n!      write(cpl_outdate,'(I4,\"-\",I2,\"-\",I2,\"_\",I2,\":\",I2,\":\",I2)' )     &\n!            yr, mo, da, hr, mn, ss\n\n#ifdef HYDRO_D\n      write(6,*) \"cpl_outdate = \",cpl_outdate\n\n#endif\n    end subroutine get_cpl_date\n\n!    transfer the grid column to gridcell.\n  subroutine g2c_1d(lbc, ubc, lbl, ubl, lbg, ubg, carr, garr, &\n       c2l_scale_type, l2g_scale_type)\n!\n! !DESCRIPTION:\n! Perfrom subgrid-average from columns to gridcells.\n! Averaging is only done for points that are not equal to \"spval\".\n!\n! !ARGUMENTS:\n     use clm_varcon, only : spval, isturb,  icol_roof, icol_sunwall, icol_shadewall, &\n                         icol_road_perv, icol_road_imperv\n     use clm_varctl, only : iulog\n\n\n    implicit none\n    integer , intent(in)  :: lbc, ubc              ! beginning and ending column indices\n    integer , intent(in)  :: lbl, ubl              ! beginning and ending landunit indices\n    integer , intent(in)  :: lbg, ubg              ! beginning and ending landunit indices\n    real(kind=double), intent(out)  :: carr(lbc:ubc)         ! output column array\n    real(kind=double), intent(in) :: garr(lbg:ubg)         ! input  gridcell array\n    character(len=*), intent(in) :: c2l_scale_type ! scale factor type for averaging\n    character(len=*), intent(in) :: l2g_scale_type ! scale factor type for averaging\n!\n! !REVISION HISTORY:\n! Created by Mariana Vertenstein 12/03\n!\n!\n! !LOCAL VARIABLES:\n!EOP\n    integer  :: ci,c,l,g,index         ! indices\n    integer  :: max_col_per_gcell      ! max columns per gridcell; on the fly\n    logical  :: found                  ! temporary for error check\n    real(kind=double) :: scale_c2l(lbc:ubc)     ! scale factor\n    real(kind=double) :: scale_l2g(lbl:ubl)     ! scale factor\n    real(kind=double) :: sumwt(lbg:ubg)         ! sum of weights\n    real(kind=double), pointer :: wtgcell(:)    ! weight of columns relative to gridcells\n    integer , pointer :: clandunit(:)  ! landunit of corresponding column\n    integer , pointer :: cgridcell(:)  ! gridcell of corresponding column\n    integer , pointer :: ncolumns(:)   ! number of columns in gridcell\n    integer , pointer :: coli(:)       ! initial column index in gridcell\n    integer , pointer :: ctype(:)      ! column type\n    integer , pointer :: ltype(:)      ! landunit type\n    real(kind=double), pointer :: canyon_hwr(:) ! urban canyon height to width ratio\n    integer :: gcount(lbg:ubg)\n!------------------------------------------------------------------------\n\n\n    ctype      => clm3%g%l%c%itype\n    ltype      => clm3%g%l%itype\n    canyon_hwr => clm3%g%l%canyon_hwr\n    wtgcell    => clm3%g%l%c%wtgcell\n    clandunit  => clm3%g%l%c%landunit\n    cgridcell  => clm3%g%l%c%gridcell\n    ncolumns   => clm3%g%ncolumns\n    coli       => clm3%g%coli\n\n    if (l2g_scale_type == 'unity') then\n       do l = lbl,ubl\n          scale_l2g(l) = 1.0\n       end do\n    end if\n\n    if (c2l_scale_type == 'unity') then\n       do c = lbc,ubc\n          scale_c2l(c) = 1.0\n       end do\n    else if (c2l_scale_type == 'urbanf') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = 3.0 * canyon_hwr(l)\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = 3.0 * canyon_hwr(l)\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = 3.0\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = 1.0\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    else if (c2l_scale_type == 'urbans') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = (3.0 * canyon_hwr(l)) / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = (3.0 * canyon_hwr(l)) / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = 3.0 / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = 1.0\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    else if (c2l_scale_type == 'urbanh') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = spval\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    end if\n\n    sumwt(:) = 0.\n    gcount(:) = 0\n    do c = lbc,ubc\n          if (carr(c) /= spval .and. scale_c2l(c) /= spval) then\n             l = clandunit(c)\n             g = cgridcell(c)\n             if(wtgcell(c) .ne. 0) then\n                carr(c) = garr(g)\n             endif\n          end if\n    end do\n    end subroutine g2c_1d\n\n    subroutine gather_1d_real(l1d,lnn,g1d,gnn)\n       use spmdGathScatMod\n       use clmtype   , only : grlnd, nameg\n\n       implicit none\n       integer lnn, gnn\n       real(kind=double),dimension(lnn) :: l1d\n       real(kind=double),dimension(gnn) :: g1d\n       real(kind=double), pointer :: lp_yw(:), gp_yw(:)\n\n       allocate(lp_yw(lnn) )\n       allocate(gp_yw(gnn) )\n       lp_yw = l1d\n\n\n       call gather_data_to_master(lp_yw,gp_yw,grlnd)\n\n       g1d = gp_yw\n       deallocate(lp_yw)\n       deallocate(gp_yw)\n    end subroutine gather_1d_real\n\n    subroutine scatter_1d_r(l1d,lnn,g1d,gnn)\n       use spmdGathScatMod, only: scatter_1darray_real\n       use clmtype   , only : grlnd, nameg\n\n       implicit none\n       integer lnn, gnn\n       real(kind=double),dimension(lnn) :: l1d\n       real,dimension(gnn) :: g1d\n       real(kind=double), pointer :: lp_yw(:), gp_yw(:)\n\n\n\n\n       allocate(lp_yw(begg:endg) )\n       allocate(gp_yw(gnn) )\n\n\n       gp_yw(:) = g1d(:)\n\n\n!      call scatter_data_from_master(lp, gp, grlnd)\n\n       call scatter_1darray_real(lp_yw, gp_yw, grlnd)\n\n\n       l1d = lp_yw(begg:endg)\n\n       deallocate(lp_yw)\n       deallocate(gp_yw)\n    end subroutine scatter_1d_r\n\n      subroutine output_nc(array,idim,jdim, var_name, file_name)\n      implicit none\n#include <netcdf.inc>\n          integer idim,jdim\n          real array(idim,jdim)\n          integer dim(2)\n          character(len=*) file_name,var_name\n          integer   iret,ncid,varid,idim_id,jdim_id\n          integer i,j\n          iret = nf_create(trim(file_name), 0, ncid)\n          iret = nf_def_dim(ncid, \"idim\", idim,idim_id)\n          iret = nf_def_dim(ncid, \"jdim\", jdim,jdim_id)\n          dim(1)=idim_id\n          dim(2)=jdim_id\n          iret = nf_put_att_real(ncid, NF_GLOBAL,  &\n                \"missing_value\", NF_FLOAT, 1, -1.E33)\n\n          iret = nf_def_var(ncid,var_name,NF_FLOAT,2,dim,varid)\n          iret = nf_enddef(ncid)\n\n!   output\n          iret = nf_inq_varid(ncid,var_name,varid)\n          iret = nf_put_var_real(ncid,varid,array)\n          iret=nf_close(ncid)\n      end subroutine output_nc\n\n  subroutine g2c_2d(lbc, ubc, lbl, ubl, lbg, ubg, num2d, carr, garr, &\n       c2l_scale_type, l2g_scale_type)\n!\n! !DESCRIPTION:\n! Perfrom subgrid-average from columns to gridcells.\n! Averaging is only done for points that are not equal to \"spval\".\n!\n     use clm_varcon, only : spval, isturb,  icol_roof, icol_sunwall, icol_shadewall, &\n                         icol_road_perv, icol_road_imperv\n     use clm_varctl, only : iulog\n! !ARGUMENTS:\n    implicit none\n    integer , intent(in)  :: lbc, ubc              ! beginning and ending column indices\n    integer , intent(in)  :: lbl, ubl              ! beginning and ending landunit indices\n    integer , intent(in)  :: lbg, ubg              ! beginning and ending gridcell indices\n    integer , intent(in)  :: num2d                 ! size of second dimension\n    real(kind=double), intent(inout)  :: carr(lbc:ubc,num2d)   ! input column array\n    real(kind=double), intent(in) :: garr(lbg:ubg,num2d)   ! output gridcell array\n    character(len=*), intent(in) :: c2l_scale_type ! scale factor type for averaging\n    character(len=*), intent(in) :: l2g_scale_type ! scale factor type for averaging\n\n    real(kind=double) :: yw_r\n!\n! !REVISION HISTORY:\n! Created by Mariana Vertenstein 12/03\n!\n!\n! !LOCAL VARIABLES:\n!EOP\n    integer  :: j,ci,c,g,l,index       ! indices\n    integer  :: max_col_per_gcell      ! max columns per gridcell; on the fly\n    logical  :: found                  ! temporary for error check\n    real(kind=double) :: scale_c2l(lbc:ubc)     ! scale factor\n    real(kind=double) :: scale_l2g(lbl:ubl)     ! scale factor\n    real(kind=double) :: sumwt(lbg:ubg)         ! sum of weights\n    real(kind=double), pointer :: wtgcell(:)    ! weight of columns relative to gridcells\n    integer , pointer :: clandunit(:)  ! landunit of corresponding column\n    integer , pointer :: cgridcell(:)  ! gridcell of corresponding column\n    integer , pointer :: ncolumns(:)   ! number of columns in gridcell\n    integer , pointer :: coli(:)       ! initial column index in gridcell\n    integer , pointer :: ctype(:)      ! column type\n    integer , pointer :: ltype(:)      ! landunit type\n    real(kind=double), pointer :: canyon_hwr(:) ! urban canyon height to width ratio\n    real :: w_yw\n!------------------------------------------------------------------------\n\n    ctype      => clm3%g%l%c%itype\n    ltype      => clm3%g%l%itype\n    canyon_hwr => clm3%g%l%canyon_hwr\n    wtgcell    => clm3%g%l%c%wtgcell\n    clandunit  => clm3%g%l%c%landunit\n    cgridcell  => clm3%g%l%c%gridcell\n    ncolumns   => clm3%g%ncolumns\n    coli       => clm3%g%coli\n\n    if (l2g_scale_type == 'unity') then\n       do l = lbl,ubl\n          scale_l2g(l) = 1.0\n       end do\n    else\n       write(iulog,*)'WARNING: In module_clm_HYDRO.F c2g_2d() - '// &\n                     'scale type ',l2g_scale_type,' not supported'\n    end if\n    if (c2l_scale_type == 'unity') then\n       do c = lbc,ubc\n          scale_c2l(c) = 1.0\n       end do\n    else if (c2l_scale_type == 'urbanf') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = 3.0 * canyon_hwr(l)\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = 3.0 * canyon_hwr(l)\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = 3.0\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = 1.0\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    else if (c2l_scale_type == 'urbans') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = (3.0 * canyon_hwr(l)) / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = (3.0 * canyon_hwr(l)) / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = 3.0 / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = 1.0\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    else if (c2l_scale_type == 'urbanh') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = spval\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    else\n      write(iulog,*) 'WARNING: In module_clm_HYDRO.F c2g_2d()- '// &\n                     'scale type ',c2l_scale_type,' not supported'\n    end if\n\n    do j = 1,num2d\n       sumwt(:) = 0.\n       do c = lbc,ubc\n          if (wtgcell(c) /= 0) then\n             if (carr(c,j) /= spval .and. scale_c2l(c) /= spval) then\n                l = clandunit(c)\n                g = cgridcell(c)\n                sumwt(g) = sumwt(g) + wtgcell(c)\n             end if\n          end if\n       end do\n       do c = lbc,ubc\n          if (wtgcell(c) /= 0) then\n             if (carr(c,j) /= spval .and. scale_c2l(c) /= spval) then\n                l = clandunit(c)\n                g = cgridcell(c)\n                   !garr(g,j) = garr(g,j) + carr(c,j) * scale_c2l(c) * scale_l2g(l) * wtgcell(c)\n                   !w_yw = scale_c2l(c) * scale_l2g(l) * wtgcell(c)\n                   w_yw = scale_c2l(c) * scale_l2g(l)\n                   if(w_yw .ne. 0) then\n                      ! carr(c,j) =  garr(g,j) / w_yw *sumwt(g)\n                      yw_r = garr(g,j) / w_yw\n                      if(abs(yw_r - carr(c,j)) .lt. 400 .and. yw_r .ne. 0 ) then\n                         carr(c,j) =  garr(g,j) / w_yw\n                      endif\n                   endif\n            end if\n          end if\n       end do\n    end do\n\n  end subroutine g2c_2d\n\n  subroutine g2c_2d_tmp(lbc, ubc, lbl, ubl, lbg, ubg, num2d, carr, garr, &\n       c2l_scale_type, l2g_scale_type, minv, maxv)\n!\n! !DESCRIPTION:\n! Perfrom subgrid-average from columns to gridcells.\n! Averaging is only done for points that are not equal to \"spval\".\n!\n     use clm_varcon, only : spval, isturb,  icol_roof, icol_sunwall, icol_shadewall, &\n                         icol_road_perv, icol_road_imperv\n     use clm_varctl, only : iulog\n! !ARGUMENTS:\n    implicit none\n    integer , intent(in)  :: lbc, ubc              ! beginning and ending column indices\n    integer , intent(in)  :: lbl, ubl              ! beginning and ending landunit indices\n    integer , intent(in)  :: lbg, ubg              ! beginning and ending gridcell indices\n    integer , intent(in)  :: num2d                 ! size of second dimension\n    real(kind=double), intent(inout)  :: carr(lbc:ubc,num2d)   ! input column array\n    real(kind=double), intent(in) :: garr(lbg:ubg,num2d)   ! output gridcell array\n    character(len=*), intent(in) :: c2l_scale_type ! scale factor type for averaging\n    character(len=*), intent(in) :: l2g_scale_type ! scale factor type for averaging\n\n    real(kind=double) :: yw_r\n    real :: minv, maxv\n!\n! !REVISION HISTORY:\n! Created by Mariana Vertenstein 12/03\n!\n!\n! !LOCAL VARIABLES:\n!EOP\n    integer  :: j,ci,c,g,l,index       ! indices\n    integer  :: max_col_per_gcell      ! max columns per gridcell; on the fly\n    logical  :: found                  ! temporary for error check\n    real(kind=double) :: scale_c2l(lbc:ubc)     ! scale factor\n    real(kind=double) :: scale_l2g(lbl:ubl)     ! scale factor\n    real(kind=double) :: sumwt(lbg:ubg)         ! sum of weights\n    real(kind=double), pointer :: wtgcell(:)    ! weight of columns relative to gridcells\n    integer , pointer :: clandunit(:)  ! landunit of corresponding column\n    integer , pointer :: cgridcell(:)  ! gridcell of corresponding column\n    integer , pointer :: ncolumns(:)   ! number of columns in gridcell\n    integer , pointer :: coli(:)       ! initial column index in gridcell\n    integer , pointer :: ctype(:)      ! column type\n    integer , pointer :: ltype(:)      ! landunit type\n    real(kind=double), pointer :: canyon_hwr(:) ! urban canyon height to width ratio\n    real :: w_yw\n!------------------------------------------------------------------------\n\n    ctype      => clm3%g%l%c%itype\n    ltype      => clm3%g%l%itype\n    canyon_hwr => clm3%g%l%canyon_hwr\n    wtgcell    => clm3%g%l%c%wtgcell\n    clandunit  => clm3%g%l%c%landunit\n    cgridcell  => clm3%g%l%c%gridcell\n    ncolumns   => clm3%g%ncolumns\n    coli       => clm3%g%coli\n\n    if (l2g_scale_type == 'unity') then\n       do l = lbl,ubl\n          scale_l2g(l) = 1.0\n       end do\n    else\n      write(iulog,*) 'WARNING: In module_clm_HYDRO.F g2c_2d_tmp - '// &\n                     'scale type ',l2g_scale_type,' not supported'\n    end if\n    if (c2l_scale_type == 'unity') then\n       do c = lbc,ubc\n          scale_c2l(c) = 1.0\n       end do\n    else if (c2l_scale_type == 'urbanf') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = 3.0 * canyon_hwr(l)\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = 3.0 * canyon_hwr(l)\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = 3.0\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = 1.0\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    else if (c2l_scale_type == 'urbans') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = (3.0 * canyon_hwr(l)) / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = (3.0 * canyon_hwr(l)) / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = 3.0 / (2.*canyon_hwr(l) + 1.)\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = 1.0\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    else if (c2l_scale_type == 'urbanh') then\n       do c = lbc,ubc\n          l = clandunit(c)\n          if (ltype(l) == isturb) then\n             if (ctype(c) == icol_sunwall) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_shadewall) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_road_perv .or. ctype(c) == icol_road_imperv) then\n                scale_c2l(c) = spval\n             else if (ctype(c) == icol_roof) then\n                scale_c2l(c) = spval\n             end if\n          else\n             scale_c2l(c) = 1.0\n          end if\n       end do\n    else\n      write(iulog,*) 'WARNING: In module_clm_HYDRO.F g2c_2d_tmp() - '// &\n                      'scale type ',c2l_scale_type,' not supported'\n    end if\n\n    do j = 1,num2d\n       sumwt(:) = 0.\n       do c = lbc,ubc\n          if (wtgcell(c) /= 0) then\n             if (carr(c,j) /= spval .and. scale_c2l(c) /= spval) then\n                l = clandunit(c)\n                g = cgridcell(c)\n                sumwt(g) = sumwt(g) + wtgcell(c)\n             end if\n          end if\n       end do\n       do c = lbc,ubc\n          if (wtgcell(c) /= 0) then\n             if (carr(c,j) /= spval .and. scale_c2l(c) /= spval) then\n                    l = clandunit(c)\n                    g = cgridcell(c)\n                    !garr(g,j) = garr(g,j) + carr(c,j) * scale_c2l(c) * scale_l2g(l) * wtgcell(c)\n                    !w_yw = scale_c2l(c) * scale_l2g(l) * wtgcell(c)\n                    w_yw = scale_c2l(c) * scale_l2g(l)\n                    if(w_yw .ne. 0) then\n                    if(abs(garr(g,j)) .gt. minv .and. abs(garr(g,j)) .lt. maxv) then\n                       ! carr(c,j) =  garr(g,j) / w_yw *sumwt(g)\n                             yw_r =  garr(g,j) / w_yw\n                             if(yw_r .gt. 0) then\n                                carr(c,j) =  garr(g,j) / w_yw\n                             endif\n                    endif\n                    endif\n             end if\n          end if\n       end do\n    end do\n\n  end subroutine g2c_2d_tmp\nend module module_clm_HYDRO\n"
  },
  {
    "path": "src/CPL/LIS_cpl/Makefile",
    "content": "# Makefile \n#\n\n.SUFFIXES:\n.SUFFIXES: .o .F\nLIS_ROOT = ../../../..\n\nLIS_MOD = -I ../../mod -I$(LIS_ROOT)/make\ninclude $(LIS_ROOT)/make/configure.lis\ninclude ../../macros\n\nMODFLAG =       -I./ -I ../../MPP -I ../../mod\n\nOBJS = \\\n\tmodule_lis_HYDRO.o\\\n\tlis_drv_HYDRO.o\nall:\t$(OBJS) \n\n.F.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -I$(NETCDFINC) -o $(@) $(F90FLAGS) $(MODFLAG) -I../../mod $(LIS_MOD) -I$(MOD_ESMF) $(*).F\n\t@echo \"\"\n\tar -r ../../lib/libHYDRO.a $(@)\n\n#\n# Dependencies:\n#\n\nclean:\n\trm -f *.o *.mod *.stb *~ \n"
  },
  {
    "path": "src/CPL/LIS_cpl/Makefile.cpl",
    "content": "# Makefile \n\nall:\n\t(cd ../../; make -f Makefile.comm)\n\t(make)\n\nclean:\n\t(make clean)\n\t(cd ../../; make -f Makefile.comm clean)\n"
  },
  {
    "path": "src/CPL/LIS_cpl/lis_drv_HYDRO.F",
    "content": "\n!2345678\n       subroutine lis_drv_HYDRO(n)\n          use module_lis_HYDRO, only: lis_cpl_HYDRO\n          implicit none\n          integer n\n#ifdef HYDRO_D\n          write(6,*) \"calling lis_cpl_HYDRO \"\n#endif\n!         stop 888\n          call lis_cpl_HYDRO(n)\n       end subroutine lis_drv_HYDRO\n"
  },
  {
    "path": "src/CPL/LIS_cpl/module_lis_HYDRO.F",
    "content": "\nmodule module_lis_HYDRO\n    use noah271_lsmMod, only : noah271_struc\n!   use LIS_coreMod, only : LIS_rc, LIS_domain, LIS_masterproc, &\n!         LIS_ews_ind, LIS_ewe_ind, LIS_nss_ind, LIS_nse_ind\n    use LIS_coreMod\n!    use LIS_historyMod, only: LIS_gather_gridded_output, lis_gather_tiled_vector_output\n\n! use HYDRO module\n       use module_hydro_stop, only: HYDRO_stop\n       use module_rt_data, only:  rt_domain\n       use module_CPL_LAND, only: CPL_LAND_INIT, cpl_outdate\n       use module_mpp_land\n       use config_base, only : nlst\n       use module_HYDRO_drv, only: HYDRO_ini, HYDRO_exe\n\n!!! temp use\n       use module_yw, only: SFHEAD1RT,INFXS1RT, soldrain\n    contains\n\n    subroutine lis_cpl_HYDRO(n)\n\n\n\n        implicit none\n        integer n, k, ix,jx\n\n        integer ::  did, its,ite,jts,jte, ierr\n\n        integer ntime, wrf_ix,wrf_jx\n        logical mpi_inited\n\n!output flux and state variable\n\n        integer :: i,j, kz\n\n\n        did = 1\n\n        ntime = 1\n\n!           write(6,*) \"yyyywww step 2, n =\", n\n!           write(6,*) \"npesx, npesy\",LIS_rc%npesx, LIS_rc%npesy\n\n      if(.not. RT_DOMAIN(did)%initialized) then\n\n!!! get soil layers from lis\n!!! ++++++++++++++\n        nlst(did)%nsoil = noah271_struc(n)%nslay\n#ifdef MPP_LAND\n        call mpp_land_bcast_int1(nlst(did)%nsoil)\n#endif\n        if(nlst(did)%nsoil < 1) then\n           write(6,*) \"FATAL ERROR: nsoil is less than 1\"\n           call hydro_stop(\"In module_lis_HYDRO.F module_lis_HYDRO() - nsoil is less than 1\")\n        endif\n        allocate(nlst(did)%zsoil8(nlst(did)%nsoil))\n        nlst(did)%zsoil8(1) = -noah271_struc(n)%lyrthk(1)\n        DO KZ = 2,nlst(did)%nsoil\n           nlst(did)%zsoil8(KZ) = -noah271_struc(n)%lyrthk(KZ)+nlst(did)%zsoil8(KZ-1)\n        END DO\n!!! ----------\n#ifdef HYDRO_D\n        write(6,*) \"zsoil8 = \",nlst(did)%zsoil8\n\n#endif\n\n        call MPI_Initialized( mpi_inited, ierr )\n        if ( .NOT. mpi_inited ) then\n           call MPI_Init( ierr )  ! stand alone land model.\n           if (ierr /= MPI_SUCCESS) stop \"MPI_INIT\"\n           call MPI_Comm_dup(MPI_COMM_WORLD, HYDRO_COMM_WORLD, ierr)\n           if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_DUP\"\n        endif\n        call MPI_Comm_rank( HYDRO_COMM_WORLD, my_id, ierr )\n        call MPI_Comm_size( HYDRO_COMM_WORLD, numprocs, ierr )\n      endif\n\n        if(nlst(did)%rtFlag .eq. 0) return\n\n        write(cpl_outdate(1:5),'(I4,\"-\")') LIS_rc%yr\n\n        if(LIS_rc%mo .lt. 10) then\n           write(cpl_outdate(6:8),'(\"0\",I1,\"-\")') LIS_rc%mo\n        else\n           write(cpl_outdate(6:8),'(I2,\"-\")') LIS_rc%mo\n        endif\n\n        if(LIS_rc%da .lt. 10) then\n           write(cpl_outdate(9:11),'(\"0\",I1,\"_\")') LIS_rc%da\n        else\n           write(cpl_outdate(9:11),'(I2,\"_\")') LIS_rc%da\n        endif\n\n        if(LIS_rc%hr .lt. 10) then\n           write(cpl_outdate(12:14),'(\"0\",I1,\":\")') LIS_rc%hr\n        else\n           write(cpl_outdate(12:14),'(I2,\":\")') LIS_rc%hr\n        endif\n\n        if(LIS_rc%mn .lt. 10) then\n           write(cpl_outdate(15:17),'(\"0\",I1,\":\")') LIS_rc%mn\n        else\n           write(cpl_outdate(15:17),'(I2,\":\")') LIS_rc%mn\n        endif\n\n        if(LIS_rc%ss .lt. 10) then\n           write(cpl_outdate(18:19),'(\"0\",I1)') LIS_rc%ss\n        else\n           write(cpl_outdate(18:19),'(I2)') LIS_rc%ss\n        endif\n\n\n            nlst(did)%olddate(1:19) = cpl_outdate(1:19)\n\n\n            jx = LIS_rc%lnr(n)\n            ix = LIS_rc%lnc(n)\n            its = LIS_ews_ind(LIS_rc%nnest,my_id+1)\n            ite = LIS_ewe_ind(LIS_rc%nnest,my_id+1)\n            jts = LIS_nss_ind(LIS_rc%nnest,my_id+1)\n            jte = LIS_nse_ind(LIS_rc%nnest,my_id+1)\n\n!           write(6,*) \"LIS_ews_ind\",LIS_ews_ind\n!           write(6,*) \"LIS_ewe_ind\",LIS_ewe_ind\n!           write(6,*) \"LIS_nss_ind\",LIS_nss_ind\n!           write(6,*) \"LIS_nse_ind\",LIS_nse_ind\n\n        if(.not. RT_DOMAIN(did)%initialized) then\n!           write(6,*) \"yyyywww step 3\"\n#ifdef HYDRO_D\n            write(6,*) \"ix,jx, cpl_land_dt\",ix,jx, LIS_rc%ts\n\n!           write(6,*) \"yyyywww step 4 before HYDRO_ini= \"\n            write(6,*) \"its,ite,jts,jte\", its,ite,jts,jte\n            write(6,*) \"noah271_struc(n)%nslay=\", noah271_struc(n)%nslay\n            write(6,*) \"noah271_struc(n)%lyrthk=\", noah271_struc(n)%lyrthk\n\n#endif\n            nlst(did)%startdate(1:19) = cpl_outdate(1:19)\n\n            call CPL_LAND_INIT(its,ite,jts,jte)\n\n\n!           write(6,*) \"yyyywww step 4 before HYDRO_ini= \"\n!           write(6,*) \"its,ite,jts,jte\", its,ite,jts,jte\n\n            call HYDRO_ini(ntime,did=did,ix0=1,jx0=1)\n\n            if(nlst(did)%sys_cpl .ne. 3) then\n               write(6,*) \"FATAL ERROR: sys_cpl should be 3.\"\n               call hydro_stop(\"In module_lis_HYDRO.F lis_cpl_HYDRO() - \"// &\n                               \"sys_cpl should be 3. Check hydro.namelist file\")\n            endif\n!           write(6,*) \"yyyywww step 5 my_id= \", my_id\n\n            nlst(did)%dt = LIS_rc%ts\n\n!         write(6,*) \"LIS_rc%gnc(n),LIS_rc%gnr(n),LIS_rc%glbnch_red(n)\", &\n!                LIS_rc%gnc(n),LIS_rc%gnr(n),LIS_rc%glbnch_red(n)\n\n!         write(6,*) \"LIS_rc%nch =\", LIS_rc%nch(n)\n!         write(6,*) \"size(noah271_struc(n)%noah%cmc)\" , size(noah271_struc(n)%noah%cmc)\n\n!         write(6,*) \"LIS_nss_halo_ind,LIS_nse_halo_ind\", LIS_nss_halo_ind,LIS_nse_halo_ind\n!         write(6,*) \"LIS_ews_halo_ind,LIS_ewe_halo_ind\",LIS_ews_halo_ind,LIS_ewe_halo_ind\n\n!            nlst(did)%startdate(1:19) = cpl_outdate(1:19)\n\n          RT_DOMAIN(did)%initialized = .true.\n        endif\n\n\n!       write(6,*) \"before call lis2HYDRO\"\n\n!       write(6,*) \"size(noah271_struc(n)%noah%smc(1)),n,ix,jx\" , size(noah271_struc(n)%noah%smc(1)),n,ix,jx\n!       write(6,*) \"nlst(did)%nsoil = \", nlst(did)%nsoil\n\n            ! get the initial data from LIS\n            do k = 1 , nlst(did)%nsoil\n                call lis2HYDRO(RT_DOMAIN(did)%SMC(:,:,k),noah271_struc(n)%noah%smc(k),size(noah271_struc(n)%noah%smc(k)),n,ix,jx)\n                call lis2HYDRO(RT_DOMAIN(did)%stc(:,:,k),noah271_struc(n)%noah%stc(k),size(noah271_struc(n)%noah%stc(k)), n,ix,jx)\n                call lis2HYDRO(RT_DOMAIN(did)%SH2OX(:,:,k),noah271_struc(n)%noah%sh2o(k),size(noah271_struc(n)%noah%sh2o(k)),n,ix,jx)\n            enddo\n\n#ifdef HYDRO_D\n        write(6,*) \"NDHMS lis date \", LIS_rc%yr, LIS_rc%mo, LIS_rc%da, LIS_rc%hr, LIS_rc%mn, LIS_rc%ss\n#endif\n!       write(11,*) \"RT_DOMAIN(did)%stc\",RT_DOMAIN(did)%stc(:,:,1)\n!       write(12,*) \"noah271_struc(n)%noah%stc(1)\",noah271_struc(n)%noah%stc(1)\n!       call land_finish()\n\n        call lis2HYDRO(RT_DOMAIN(did)%infxsrt(:,:),INFXS1RT,size(INFXS1RT),n,ix,jx)\n        call lis2HYDRO(RT_DOMAIN(did)%soldrain(:,:),SOLDRAIN,size(SOLDRAIN),n,ix,jx)\n\n\n        call HYDRO_exe(did)\n\n! add for update the land surface model state variable.\n     ! 3 d variable\n        do k = 1 , nlst(did)%nsoil\n             call HYDRO2lis_2d(RT_DOMAIN(did)%SMC(:,:,k),noah271_struc(n)%noah%smc(k),size(noah271_struc(n)%noah%smc(k)),n,ix,jx)\n             call HYDRO2lis_2d(RT_DOMAIN(did)%stc(:,:,k),noah271_struc(n)%noah%stc(k),size(noah271_struc(n)%noah%stc(k)),n,ix,jx)\n             call HYDRO2lis_2d(RT_DOMAIN(did)%SH2OX(:,:,k),noah271_struc(n)%noah%sh2o(k),size(noah271_struc(n)%noah%sh2o(k)),n,ix,jx)\n        end do\n\n        call HYDRO2lis_2d(rt_domain(did)%overland%control%surface_water_head_lsm(:,:),SFHEAD1RT,size(SFHEAD1RT),n,ix,jx)\n\n     return\n     end subroutine lis_cpl_HYDRO\n\n     subroutine HYDRO2lis_2d(var,v1d,size1,n,ix,jx)\n        implicit none\n        integer :: n, ix, jx, i, r,c, size1\n        real, dimension(ix,jx) :: var\n        real, dimension(jx,ix) :: tmpVar\n        real ::  v1d (size1)\n\n!        call LIS_gather_gridded_output(n, p1,tmpVar)\n          do r=1,jx\n             do c=1,ix\n                if(LIS_domain(n)%gindex(c,r).ne.-1) then\n                   v1d(LIS_domain(n)%gindex(c,r)) = var(c,r)\n                endif\n             enddo\n          enddo\n\n     end subroutine HYDRO2lis_2d\n\n     subroutine lis2HYDRO(var,v1d,size1,n,ix,jx)\n        implicit none\n        integer  n, ix,jx, r,c, size1\n        real, dimension(ix,jx) :: var\n!       real, dimension(jx,ix) :: tmpVar\n        real ::  v1d (size1)\n\n\n!       do i = 1, ix\n!          tmpVar(:,i) = Var(i,:)\n!       end do\n!       call LIS_gather_tiled_vector_output(n,v1d,tmpVar)\n\n          do r=1,jx\n             do c=1,ix\n                if(LIS_domain(n)%gindex(c,r).ne.-1) then\n                   var(c,r) = v1d(LIS_domain(n)%gindex(c,r))\n                endif\n             enddo\n          enddo\n\n      end subroutine  lis2HYDRO\n\nend module module_lis_HYDRO\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/.gitignore",
    "content": "*.a\n*.mk\n*.mod\n*.o\nVERSION\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/CMakeLists.txt",
    "content": "### Library Prerequisites\nif (NOT TARGET esmf)\n  find_package(ESMF MODULE REQUIRED)\nendif (NOT TARGET esmf)\n\n### Library Files\nlist(APPEND wrfhydro_nuopc_files\n  WRFHydro_NUOPC_Cap.F90\n  WRFHydro_NUOPC_Gluecode.F90\n  WRFHydro_NUOPC_Fields.F90\n  WRFHydro_NUOPC_Flags.F90\n  WRFHydro_ESMF_Extensions.F90\n)\n\n### Library Dependencies\nlist(APPEND wrfhydro_nuopc_deps\n  hydro_routing\n  hydro_mpp\n  hydro_driver\n  hydro_orchestrator\n)\n\nlist(APPEND wrfhydro_nuopc_linklibs\n  hydro_utils\n  hydro_mpp\n  hydro_debug_utils\n  hydro_routing_overland\n  hydro_routing_subsurface\n  hydro_data_rec\n  hydro_routing\n  hydro_routing_diversions\n  fortglob\n  hydro_routing_reservoirs_levelpool\n  hydro_routing_reservoirs_hybrid\n  hydro_routing_reservoirs_rfc\n  hydro_routing_reservoirs\n  hydro_driver\n  hydro_orchestrator\n  hydro_netcdf_layer\n)\nif (WRF_HYDRO_NUDGING STREQUAL \"1\")\n  list(APPEND wrfhydro_nuopc_linklibs\n    hydro_nudging\n  )\nendif (WRF_HYDRO_NUDGING STREQUAL \"1\")\n\n\n### New Library: wrfhydro_nuopc\nadd_library(wrfhydro_nuopc STATIC ${wrfhydro_nuopc_files})\nadd_dependencies(wrfhydro_nuopc ${wrfhydro_nuopc_deps})\ntarget_link_libraries(wrfhydro_nuopc PUBLIC ${wrfhydro_nuopc_linklibs})\ntarget_link_libraries(wrfhydro_nuopc PUBLIC esmf)\ntarget_link_libraries(wrfhydro_nuopc PUBLIC ${NETCDF_LIBRARIES})\n\n### Library Installation\ninstall(TARGETS wrfhydro_nuopc ${wrfhydro_nuopc_linklibs}\n  EXPORT  wrfhydro-config\n  LIBRARY DESTINATION lib\n)\ninstall(DIRECTORY ${CMAKE_Fortran_MODULE_DIRECTORY}\n  DESTINATION ${CMAKE_INSTALL_PREFIX}/WRFHYDRO\n)\ninstall(EXPORT wrfhydro-config\n  DESTINATION lib/cmake\n)\n\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/Doxyfile",
    "content": "# Doxyfile 1.8.12\n\n# This file describes the settings to be used by the documentation system\n# doxygen (www.doxygen.org) for a project.\n#\n# All text after a double hash (##) is considered a comment and is placed in\n# front of the TAG it is preceding.\n#\n# All text after a single hash (#) is considered a comment and will be ignored.\n# The format is:\n# TAG = value [value, ...]\n# For lists, items can also be appended using:\n# TAG += value [value, ...]\n# Values that contain spaces should be placed between quotes (\\\" \\\").\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\n\n# This tag specifies the encoding used for all characters in the config file\n# that follow. The default is UTF-8 which is also the encoding used for all text\n# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv\n# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv\n# for the list of possible encodings.\n# The default value is: UTF-8.\n\nDOXYFILE_ENCODING      = UTF-8\n\n# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by\n# double-quotes, unless you are using Doxywizard) that should identify the\n# project for which the documentation is generated. This name is used in the\n# title of most generated pages and in a few other places.\n# The default value is: My Project.\n\nPROJECT_NAME           = \"WRF-Hydro NUOPC Cap\"\n\n# The PROJECT_NUMBER tag can be used to enter a project or revision number. This\n# could be handy for archiving the generated documentation or if some version\n# control system is used.\n\nPROJECT_NUMBER         =\n\n# Using the PROJECT_BRIEF tag one can provide an optional one line description\n# for a project that appears at the top of each page and should give viewer a\n# quick idea about the purpose of the project. Keep the description short.\n\nPROJECT_BRIEF          =\n\n# With the PROJECT_LOGO tag one can specify a logo or an icon that is included\n# in the documentation. The maximum height of the logo should not exceed 55\n# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy\n# the logo to the output directory.\n\nPROJECT_LOGO           =\n\n# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path\n# into which the generated documentation will be written. If a relative path is\n# entered, it will be relative to the location where doxygen was started. If\n# left blank the current directory will be used.\n\nOUTPUT_DIRECTORY       = docs\n\n# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-\n# directories (in 2 levels) under the output directory of each output format and\n# will distribute the generated files over these directories. Enabling this\n# option can be useful when feeding doxygen a huge amount of source files, where\n# putting all generated files in the same directory would otherwise causes\n# performance problems for the file system.\n# The default value is: NO.\n\nCREATE_SUBDIRS         = NO\n\n# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII\n# characters to appear in the names of generated files. If set to NO, non-ASCII\n# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode\n# U+3044.\n# The default value is: NO.\n\nALLOW_UNICODE_NAMES    = NO\n\n# The OUTPUT_LANGUAGE tag is used to specify the language in which all\n# documentation generated by doxygen is written. Doxygen will use this\n# information to generate all constant output in the proper language.\n# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,\n# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),\n# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,\n# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),\n# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,\n# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,\n# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,\n# Ukrainian and Vietnamese.\n# The default value is: English.\n\nOUTPUT_LANGUAGE        = English\n\n# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member\n# descriptions after the members that are listed in the file and class\n# documentation (similar to Javadoc). Set to NO to disable this.\n# The default value is: YES.\n\nBRIEF_MEMBER_DESC      = YES\n\n# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief\n# description of a member or function before the detailed description\n#\n# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the\n# brief descriptions will be completely suppressed.\n# The default value is: YES.\n\nREPEAT_BRIEF           = YES\n\n# This tag implements a quasi-intelligent brief description abbreviator that is\n# used to form the text in various listings. Each string in this list, if found\n# as the leading text of the brief description, will be stripped from the text\n# and the result, after processing the whole list, is used as the annotated\n# text. Otherwise, the brief description is used as-is. If left blank, the\n# following values are used ($name is automatically replaced with the name of\n# the entity):The $name class, The $name widget, The $name file, is, provides,\n# specifies, contains, represents, a, an and the.\n\nABBREVIATE_BRIEF       = \"The $name class\" \\\n                         \"The $name widget\" \\\n                         \"The $name file\" \\\n                         is \\\n                         provides \\\n                         specifies \\\n                         contains \\\n                         represents \\\n                         a \\\n                         an \\\n                         the\n\n# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then\n# doxygen will generate a detailed section even if there is only a brief\n# description.\n# The default value is: NO.\n\nALWAYS_DETAILED_SEC    = NO\n\n# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all\n# inherited members of a class in the documentation of that class as if those\n# members were ordinary class members. Constructors, destructors and assignment\n# operators of the base classes will not be shown.\n# The default value is: NO.\n\nINLINE_INHERITED_MEMB  = NO\n\n# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path\n# before files name in the file list and in the header files. If set to NO the\n# shortest path that makes the file name unique will be used\n# The default value is: YES.\n\nFULL_PATH_NAMES        = YES\n\n# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.\n# Stripping is only done if one of the specified strings matches the left-hand\n# part of the path. The tag can be used to show relative paths in the file list.\n# If left blank the directory from which doxygen is run is used as the path to\n# strip.\n#\n# Note that you can specify absolute paths here, but also relative paths, which\n# will be relative from the directory where doxygen is started.\n# This tag requires that the tag FULL_PATH_NAMES is set to YES.\n\nSTRIP_FROM_PATH        =\n\n# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the\n# path mentioned in the documentation of a class, which tells the reader which\n# header file to include in order to use a class. If left blank only the name of\n# the header file containing the class definition is used. Otherwise one should\n# specify the list of include paths that are normally passed to the compiler\n# using the -I flag.\n\nSTRIP_FROM_INC_PATH    =\n\n# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but\n# less readable) file names. This can be useful is your file systems doesn't\n# support long names like on DOS, Mac, or CD-ROM.\n# The default value is: NO.\n\nSHORT_NAMES            = NO\n\n# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the\n# first line (until the first dot) of a Javadoc-style comment as the brief\n# description. If set to NO, the Javadoc-style will behave just like regular Qt-\n# style comments (thus requiring an explicit @brief command for a brief\n# description.)\n# The default value is: NO.\n\nJAVADOC_AUTOBRIEF      = NO\n\n# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first\n# line (until the first dot) of a Qt-style comment as the brief description. If\n# set to NO, the Qt-style will behave just like regular Qt-style comments (thus\n# requiring an explicit \\brief command for a brief description.)\n# The default value is: NO.\n\nQT_AUTOBRIEF           = NO\n\n# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a\n# multi-line C++ special comment block (i.e. a block of //! or /// comments) as\n# a brief description. This used to be the default behavior. The new default is\n# to treat a multi-line C++ comment block as a detailed description. Set this\n# tag to YES if you prefer the old behavior instead.\n#\n# Note that setting this tag to YES also means that rational rose comments are\n# not recognized any more.\n# The default value is: NO.\n\nMULTILINE_CPP_IS_BRIEF = NO\n\n# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the\n# documentation from any documented member that it re-implements.\n# The default value is: YES.\n\nINHERIT_DOCS           = YES\n\n# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new\n# page for each member. If set to NO, the documentation of a member will be part\n# of the file/class/namespace that contains it.\n# The default value is: NO.\n\nSEPARATE_MEMBER_PAGES  = NO\n\n# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen\n# uses this value to replace tabs by spaces in code fragments.\n# Minimum value: 1, maximum value: 16, default value: 4.\n\nTAB_SIZE               = 4\n\n# This tag can be used to specify a number of aliases that act as commands in\n# the documentation. An alias has the form:\n# name=value\n# For example adding\n# \"sideeffect=@par Side Effects:\\n\"\n# will allow you to put the command \\sideeffect (or @sideeffect) in the\n# documentation, which will result in a user-defined paragraph with heading\n# \"Side Effects:\". You can put \\n's in the value part of an alias to insert\n# newlines.\n\nALIASES                =\n\n# This tag can be used to specify a number of word-keyword mappings (TCL only).\n# A mapping has the form \"name=value\". For example adding \"class=itcl::class\"\n# will allow you to use the command class in the itcl::class meaning.\n\nTCL_SUBST              =\n\n# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources\n# only. Doxygen will then generate output that is more tailored for C. For\n# instance, some of the names that are used will be different. The list of all\n# members will be omitted, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_FOR_C  = NO\n\n# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or\n# Python sources only. Doxygen will then generate output that is more tailored\n# for that language. For instance, namespaces will be presented as packages,\n# qualified scopes will look different, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_JAVA   = NO\n\n# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran\n# sources. Doxygen will then generate output that is tailored for Fortran.\n# The default value is: NO.\n\nOPTIMIZE_FOR_FORTRAN   = YES\n\n# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL\n# sources. Doxygen will then generate output that is tailored for VHDL.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_VHDL   = NO\n\n# Doxygen selects the parser to use depending on the extension of the files it\n# parses. With this tag you can assign which parser to use for a given\n# extension. Doxygen has a built-in mapping, but you can override or extend it\n# using this tag. The format is ext=language, where ext is a file extension, and\n# language is one of the parsers supported by doxygen: IDL, Java, Javascript,\n# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:\n# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:\n# Fortran. In the later case the parser tries to guess whether the code is fixed\n# or free formatted code, this is the default for Fortran type files), VHDL. For\n# instance to make doxygen treat .inc files as Fortran files (default is PHP),\n# and .f files as C (default is Fortran), use: inc=Fortran f=C.\n#\n# Note: For files without extension you can use no_extension as a placeholder.\n#\n# Note that for custom extensions you also need to set FILE_PATTERNS otherwise\n# the files are not read by doxygen.\n\nEXTENSION_MAPPING      =\n\n# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments\n# according to the Markdown format, which allows for more readable\n# documentation. See http://daringfireball.net/projects/markdown/ for details.\n# The output of markdown processing is further processed by doxygen, so you can\n# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in\n# case of backward compatibilities issues.\n# The default value is: YES.\n\nMARKDOWN_SUPPORT       = YES\n\n# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up\n# to that level are automatically included in the table of contents, even if\n# they do not have an id attribute.\n# Note: This feature currently applies only to Markdown headings.\n# Minimum value: 0, maximum value: 99, default value: 0.\n# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.\n\nTOC_INCLUDE_HEADINGS   = 0\n\n# When enabled doxygen tries to link words that correspond to documented\n# classes, or namespaces to their corresponding documentation. Such a link can\n# be prevented in individual cases by putting a % sign in front of the word or\n# globally by setting AUTOLINK_SUPPORT to NO.\n# The default value is: YES.\n\nAUTOLINK_SUPPORT       = YES\n\n# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want\n# to include (a tag file for) the STL sources as input, then you should set this\n# tag to YES in order to let doxygen match functions declarations and\n# definitions whose arguments contain STL classes (e.g. func(std::string);\n# versus func(std::string) {}). This also make the inheritance and collaboration\n# diagrams that involve STL classes more complete and accurate.\n# The default value is: NO.\n\nBUILTIN_STL_SUPPORT    = NO\n\n# If you use Microsoft's C++/CLI language, you should set this option to YES to\n# enable parsing support.\n# The default value is: NO.\n\nCPP_CLI_SUPPORT        = NO\n\n# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:\n# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen\n# will parse them like normal C++ but will assume all classes use public instead\n# of private inheritance when no explicit protection keyword is present.\n# The default value is: NO.\n\nSIP_SUPPORT            = NO\n\n# For Microsoft's IDL there are propget and propput attributes to indicate\n# getter and setter methods for a property. Setting this option to YES will make\n# doxygen to replace the get and set methods by a property in the documentation.\n# This will only work if the methods are indeed getting or setting a simple\n# type. If this is not the case, or you want to show the methods anyway, you\n# should set this option to NO.\n# The default value is: YES.\n\nIDL_PROPERTY_SUPPORT   = YES\n\n# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC\n# tag is set to YES then doxygen will reuse the documentation of the first\n# member in the group (if any) for the other members of the group. By default\n# all members of a group must be documented explicitly.\n# The default value is: NO.\n\nDISTRIBUTE_GROUP_DOC   = NO\n\n# If one adds a struct or class to a group and this option is enabled, then also\n# any nested class or struct is added to the same group. By default this option\n# is disabled and one has to add nested compounds explicitly via \\ingroup.\n# The default value is: NO.\n\nGROUP_NESTED_COMPOUNDS = NO\n\n# Set the SUBGROUPING tag to YES to allow class member groups of the same type\n# (for instance a group of public functions) to be put as a subgroup of that\n# type (e.g. under the Public Functions section). Set it to NO to prevent\n# subgrouping. Alternatively, this can be done per class using the\n# \\nosubgrouping command.\n# The default value is: YES.\n\nSUBGROUPING            = YES\n\n# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions\n# are shown inside the group in which they are included (e.g. using \\ingroup)\n# instead of on a separate page (for HTML and Man pages) or section (for LaTeX\n# and RTF).\n#\n# Note that this feature does not work in combination with\n# SEPARATE_MEMBER_PAGES.\n# The default value is: NO.\n\nINLINE_GROUPED_CLASSES = NO\n\n# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions\n# with only public data fields or simple typedef fields will be shown inline in\n# the documentation of the scope in which they are defined (i.e. file,\n# namespace, or group documentation), provided this scope is documented. If set\n# to NO, structs, classes, and unions are shown on a separate page (for HTML and\n# Man pages) or section (for LaTeX and RTF).\n# The default value is: NO.\n\nINLINE_SIMPLE_STRUCTS  = NO\n\n# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or\n# enum is documented as struct, union, or enum with the name of the typedef. So\n# typedef struct TypeS {} TypeT, will appear in the documentation as a struct\n# with name TypeT. When disabled the typedef will appear as a member of a file,\n# namespace, or class. And the struct will be named TypeS. This can typically be\n# useful for C code in case the coding convention dictates that all compound\n# types are typedef'ed and only the typedef is referenced, never the tag name.\n# The default value is: NO.\n\nTYPEDEF_HIDES_STRUCT   = NO\n\n# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This\n# cache is used to resolve symbols given their name and scope. Since this can be\n# an expensive process and often the same symbol appears multiple times in the\n# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small\n# doxygen will become slower. If the cache is too large, memory is wasted. The\n# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range\n# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536\n# symbols. At the end of a run doxygen will report the cache usage and suggest\n# the optimal cache size from a speed point of view.\n# Minimum value: 0, maximum value: 9, default value: 0.\n\nLOOKUP_CACHE_SIZE      = 0\n\n#---------------------------------------------------------------------------\n# Build related configuration options\n#---------------------------------------------------------------------------\n\n# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in\n# documentation are documented, even if no documentation was available. Private\n# class members and static file members will be hidden unless the\n# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.\n# Note: This will also disable the warnings about undocumented members that are\n# normally produced when WARNINGS is set to YES.\n# The default value is: NO.\n\nEXTRACT_ALL            = YES\n\n# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will\n# be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIVATE        = YES\n\n# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal\n# scope will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PACKAGE        = YES\n\n# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be\n# included in the documentation.\n# The default value is: NO.\n\nEXTRACT_STATIC         = NO\n\n# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined\n# locally in source files will be included in the documentation. If set to NO,\n# only classes defined in header files are included. Does not have any effect\n# for Java sources.\n# The default value is: YES.\n\nEXTRACT_LOCAL_CLASSES  = YES\n\n# This flag is only useful for Objective-C code. If set to YES, local methods,\n# which are defined in the implementation section but not in the interface are\n# included in the documentation. If set to NO, only methods in the interface are\n# included.\n# The default value is: NO.\n\nEXTRACT_LOCAL_METHODS  = NO\n\n# If this flag is set to YES, the members of anonymous namespaces will be\n# extracted and appear in the documentation as a namespace called\n# 'anonymous_namespace{file}', where file will be replaced with the base name of\n# the file that contains the anonymous namespace. By default anonymous namespace\n# are hidden.\n# The default value is: NO.\n\nEXTRACT_ANON_NSPACES   = NO\n\n# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all\n# undocumented members inside documented classes or files. If set to NO these\n# members will be included in the various overviews, but no documentation\n# section is generated. This option has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_MEMBERS     = NO\n\n# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all\n# undocumented classes that are normally visible in the class hierarchy. If set\n# to NO, these classes will be included in the various overviews. This option\n# has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_CLASSES     = NO\n\n# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend\n# (class|struct|union) declarations. If set to NO, these declarations will be\n# included in the documentation.\n# The default value is: NO.\n\nHIDE_FRIEND_COMPOUNDS  = NO\n\n# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any\n# documentation blocks found inside the body of a function. If set to NO, these\n# blocks will be appended to the function's detailed documentation block.\n# The default value is: NO.\n\nHIDE_IN_BODY_DOCS      = NO\n\n# The INTERNAL_DOCS tag determines if documentation that is typed after a\n# \\internal command is included. If the tag is set to NO then the documentation\n# will be excluded. Set it to YES to include the internal documentation.\n# The default value is: NO.\n\nINTERNAL_DOCS          = NO\n\n# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file\n# names in lower-case letters. If set to YES, upper-case letters are also\n# allowed. This is useful if you have classes or files whose names only differ\n# in case and if your file system supports case sensitive file names. Windows\n# and Mac users are advised to set this option to NO.\n# The default value is: system dependent.\n\nCASE_SENSE_NAMES       = YES\n\n# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with\n# their full class and namespace scopes in the documentation. If set to YES, the\n# scope will be hidden.\n# The default value is: NO.\n\nHIDE_SCOPE_NAMES       = NO\n\n# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will\n# append additional text to a page's title, such as Class Reference. If set to\n# YES the compound reference will be hidden.\n# The default value is: NO.\n\nHIDE_COMPOUND_REFERENCE= NO\n\n# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of\n# the files that are included by a file in the documentation of that file.\n# The default value is: YES.\n\nSHOW_INCLUDE_FILES     = YES\n\n# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each\n# grouped member an include statement to the documentation, telling the reader\n# which file to include in order to use the member.\n# The default value is: NO.\n\nSHOW_GROUPED_MEMB_INC  = NO\n\n# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include\n# files with double quotes in the documentation rather than with sharp brackets.\n# The default value is: NO.\n\nFORCE_LOCAL_INCLUDES   = NO\n\n# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the\n# documentation for inline members.\n# The default value is: YES.\n\nINLINE_INFO            = YES\n\n# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the\n# (detailed) documentation of file and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order.\n# The default value is: YES.\n\nSORT_MEMBER_DOCS       = YES\n\n# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief\n# descriptions of file, namespace and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order. Note that\n# this will also influence the order of the classes in the class list.\n# The default value is: NO.\n\nSORT_BRIEF_DOCS        = NO\n\n# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the\n# (brief and detailed) documentation of class members so that constructors and\n# destructors are listed first. If set to NO the constructors will appear in the\n# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.\n# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief\n# member documentation.\n# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting\n# detailed member documentation.\n# The default value is: NO.\n\nSORT_MEMBERS_CTORS_1ST = NO\n\n# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy\n# of group names into alphabetical order. If set to NO the group names will\n# appear in their defined order.\n# The default value is: NO.\n\nSORT_GROUP_NAMES       = NO\n\n# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by\n# fully-qualified names, including namespaces. If set to NO, the class list will\n# be sorted only by class name, not including the namespace part.\n# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.\n# Note: This option applies only to the class list, not to the alphabetical\n# list.\n# The default value is: NO.\n\nSORT_BY_SCOPE_NAME     = NO\n\n# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper\n# type resolution of all parameters of a function it will reject a match between\n# the prototype and the implementation of a member function even if there is\n# only one candidate or it is obvious which candidate to choose by doing a\n# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still\n# accept a match between prototype and implementation in such cases.\n# The default value is: NO.\n\nSTRICT_PROTO_MATCHING  = NO\n\n# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo\n# list. This list is created by putting \\todo commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TODOLIST      = YES\n\n# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test\n# list. This list is created by putting \\test commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TESTLIST      = YES\n\n# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug\n# list. This list is created by putting \\bug commands in the documentation.\n# The default value is: YES.\n\nGENERATE_BUGLIST       = YES\n\n# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)\n# the deprecated list. This list is created by putting \\deprecated commands in\n# the documentation.\n# The default value is: YES.\n\nGENERATE_DEPRECATEDLIST= YES\n\n# The ENABLED_SECTIONS tag can be used to enable conditional documentation\n# sections, marked by \\if <section_label> ... \\endif and \\cond <section_label>\n# ... \\endcond blocks.\n\nENABLED_SECTIONS       =\n\n# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the\n# initial value of a variable or macro / define can have for it to appear in the\n# documentation. If the initializer consists of more lines than specified here\n# it will be hidden. Use a value of 0 to hide initializers completely. The\n# appearance of the value of individual variables and macros / defines can be\n# controlled using \\showinitializer or \\hideinitializer command in the\n# documentation regardless of this setting.\n# Minimum value: 0, maximum value: 10000, default value: 30.\n\nMAX_INITIALIZER_LINES  = 30\n\n# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at\n# the bottom of the documentation of classes and structs. If set to YES, the\n# list will mention the files that were used to generate the documentation.\n# The default value is: YES.\n\nSHOW_USED_FILES        = YES\n\n# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This\n# will remove the Files entry from the Quick Index and from the Folder Tree View\n# (if specified).\n# The default value is: YES.\n\nSHOW_FILES             = YES\n\n# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces\n# page. This will remove the Namespaces entry from the Quick Index and from the\n# Folder Tree View (if specified).\n# The default value is: YES.\n\nSHOW_NAMESPACES        = YES\n\n# The FILE_VERSION_FILTER tag can be used to specify a program or script that\n# doxygen should invoke to get the current version for each file (typically from\n# the version control system). Doxygen will invoke the program by executing (via\n# popen()) the command command input-file, where command is the value of the\n# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided\n# by doxygen. Whatever the program writes to standard output is used as the file\n# version. For an example see the documentation.\n\nFILE_VERSION_FILTER    =\n\n# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed\n# by doxygen. The layout file controls the global structure of the generated\n# output files in an output format independent way. To create the layout file\n# that represents doxygen's defaults, run doxygen with the -l option. You can\n# optionally specify a file name after the option, if omitted DoxygenLayout.xml\n# will be used as the name of the layout file.\n#\n# Note that if you run doxygen from a directory containing a file called\n# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE\n# tag is left empty.\n\nLAYOUT_FILE            =\n\n# The CITE_BIB_FILES tag can be used to specify one or more bib files containing\n# the reference definitions. This must be a list of .bib files. The .bib\n# extension is automatically appended if omitted. This requires the bibtex tool\n# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.\n# For LaTeX the style of the bibliography can be controlled using\n# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the\n# search path. See also \\cite for info how to create references.\n\nCITE_BIB_FILES         =\n\n#---------------------------------------------------------------------------\n# Configuration options related to warning and progress messages\n#---------------------------------------------------------------------------\n\n# The QUIET tag can be used to turn on/off the messages that are generated to\n# standard output by doxygen. If QUIET is set to YES this implies that the\n# messages are off.\n# The default value is: NO.\n\nQUIET                  = NO\n\n# The WARNINGS tag can be used to turn on/off the warning messages that are\n# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES\n# this implies that the warnings are on.\n#\n# Tip: Turn warnings on while writing the documentation.\n# The default value is: YES.\n\nWARNINGS               = YES\n\n# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate\n# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag\n# will automatically be disabled.\n# The default value is: YES.\n\nWARN_IF_UNDOCUMENTED   = YES\n\n# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for\n# potential errors in the documentation, such as not documenting some parameters\n# in a documented function, or documenting parameters that don't exist or using\n# markup commands wrongly.\n# The default value is: YES.\n\nWARN_IF_DOC_ERROR      = YES\n\n# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that\n# are documented, but have no documentation for their parameters or return\n# value. If set to NO, doxygen will only warn about wrong or incomplete\n# parameter documentation, but not about the absence of documentation.\n# The default value is: NO.\n\nWARN_NO_PARAMDOC       = NO\n\n# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when\n# a warning is encountered.\n# The default value is: NO.\n\nWARN_AS_ERROR          = NO\n\n# The WARN_FORMAT tag determines the format of the warning messages that doxygen\n# can produce. The string should contain the $file, $line, and $text tags, which\n# will be replaced by the file and line number from which the warning originated\n# and the warning text. Optionally the format may contain $version, which will\n# be replaced by the version of the file (if it could be obtained via\n# FILE_VERSION_FILTER)\n# The default value is: $file:$line: $text.\n\nWARN_FORMAT            = \"$file:$line: $text\"\n\n# The WARN_LOGFILE tag can be used to specify a file to which warning and error\n# messages should be written. If left blank the output is written to standard\n# error (stderr).\n\nWARN_LOGFILE           =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the input files\n#---------------------------------------------------------------------------\n\n# The INPUT tag is used to specify the files and/or directories that contain\n# documented source files. You may enter file names like myfile.cpp or\n# directories like /usr/src/myproject. Separate the files or directories with\n# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING\n# Note: If this tag is empty the current directory is searched.\n\nINPUT                  =\n\n# This tag can be used to specify the character encoding of the source files\n# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses\n# libiconv (or the iconv built into libc) for the transcoding. See the libiconv\n# documentation (see: http://www.gnu.org/software/libiconv) for the list of\n# possible encodings.\n# The default value is: UTF-8.\n\nINPUT_ENCODING         = UTF-8\n\n# If the value of the INPUT tag contains directories, you can use the\n# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and\n# *.h) to filter out the source-files in the directories.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# read by doxygen.\n#\n# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,\n# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,\n# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,\n# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,\n# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf.\n\nFILE_PATTERNS          = *.c \\\n                         *.cc \\\n                         *.cxx \\\n                         *.cpp \\\n                         *.c++ \\\n                         *.java \\\n                         *.ii \\\n                         *.ixx \\\n                         *.ipp \\\n                         *.i++ \\\n                         *.inl \\\n                         *.idl \\\n                         *.ddl \\\n                         *.odl \\\n                         *.h \\\n                         *.hh \\\n                         *.hxx \\\n                         *.hpp \\\n                         *.h++ \\\n                         *.cs \\\n                         *.d \\\n                         *.php \\\n                         *.php4 \\\n                         *.php5 \\\n                         *.phtml \\\n                         *.inc \\\n                         *.m \\\n                         *.markdown \\\n                         *.mm \\\n                         *.dox \\\n                         *.py \\\n                         *.pyw \\\n                         *.f90 \\\n\t\t\t *.F90 \\\n                         *.f95 \\\n                         *.f03 \\\n                         *.f08 \\\n                         *.f \\\n                         *.for \\\n                         *.tcl \\\n                         *.vhd \\\n                         *.vhdl \\\n                         *.ucf \\\n                         *.qsf\n\n# The RECURSIVE tag can be used to specify whether or not subdirectories should\n# be searched for input files as well.\n# The default value is: NO.\n\nRECURSIVE              = NO\n\n# The EXCLUDE tag can be used to specify files and/or directories that should be\n# excluded from the INPUT source files. This way you can easily exclude a\n# subdirectory from a directory tree whose root is specified with the INPUT tag.\n#\n# Note that relative paths are relative to the directory from which doxygen is\n# run.\n\nEXCLUDE                =\n\n# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or\n# directories that are symbolic links (a Unix file system feature) are excluded\n# from the input.\n# The default value is: NO.\n\nEXCLUDE_SYMLINKS       = NO\n\n# If the value of the INPUT tag contains directories, you can use the\n# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude\n# certain files from those directories.\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories for example use the pattern */test/*\n\nEXCLUDE_PATTERNS       =\n\n# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names\n# (namespaces, classes, functions, etc.) that should be excluded from the\n# output. The symbol name can be a fully qualified name, a word, or if the\n# wildcard * is used, a substring. Examples: ANamespace, AClass,\n# AClass::ANamespace, ANamespace::*Test\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories use the pattern */test/*\n\nEXCLUDE_SYMBOLS        =\n\n# The EXAMPLE_PATH tag can be used to specify one or more files or directories\n# that contain example code fragments that are included (see the \\include\n# command).\n\nEXAMPLE_PATH           =\n\n# If the value of the EXAMPLE_PATH tag contains directories, you can use the\n# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and\n# *.h) to filter out the source-files in the directories. If left blank all\n# files are included.\n\nEXAMPLE_PATTERNS       = *\n\n# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be\n# searched for input files to be used with the \\include or \\dontinclude commands\n# irrespective of the value of the RECURSIVE tag.\n# The default value is: NO.\n\nEXAMPLE_RECURSIVE      = NO\n\n# The IMAGE_PATH tag can be used to specify one or more files or directories\n# that contain images that are to be included in the documentation (see the\n# \\image command).\n\nIMAGE_PATH             = docimages\n\n# The INPUT_FILTER tag can be used to specify a program that doxygen should\n# invoke to filter for each input file. Doxygen will invoke the filter program\n# by executing (via popen()) the command:\n#\n# <filter> <input-file>\n#\n# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the\n# name of an input file. Doxygen will then use the output that the filter\n# program writes to standard output. If FILTER_PATTERNS is specified, this tag\n# will be ignored.\n#\n# Note that the filter must not add or remove lines; it is applied before the\n# code is scanned, but not when the output code is generated. If lines are added\n# or removed, the anchors will not be placed correctly.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by doxygen.\n\nINPUT_FILTER           =\n\n# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern\n# basis. Doxygen will compare the file name with each pattern and apply the\n# filter if there is a match. The filters are a list of the form: pattern=filter\n# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how\n# filters are used. If the FILTER_PATTERNS tag is empty or if none of the\n# patterns match the file name, INPUT_FILTER is applied.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by doxygen.\n\nFILTER_PATTERNS        =\n\n# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using\n# INPUT_FILTER) will also be used to filter the input files that are used for\n# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).\n# The default value is: NO.\n\nFILTER_SOURCE_FILES    = NO\n\n# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file\n# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and\n# it is also possible to disable source filtering for a specific pattern using\n# *.ext= (so without naming a filter).\n# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.\n\nFILTER_SOURCE_PATTERNS =\n\n# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that\n# is part of the input, its contents will be placed on the main page\n# (index.html). This can be useful if you have a project on for instance GitHub\n# and want to reuse the introduction page also for the doxygen output.\n\nUSE_MDFILE_AS_MAINPAGE =\n\n#---------------------------------------------------------------------------\n# Configuration options related to source browsing\n#---------------------------------------------------------------------------\n\n# If the SOURCE_BROWSER tag is set to YES then a list of source files will be\n# generated. Documented entities will be cross-referenced with these sources.\n#\n# Note: To get rid of all source code in the generated output, make sure that\n# also VERBATIM_HEADERS is set to NO.\n# The default value is: NO.\n\nSOURCE_BROWSER         = NO\n\n# Setting the INLINE_SOURCES tag to YES will include the body of functions,\n# classes and enums directly into the documentation.\n# The default value is: NO.\n\nINLINE_SOURCES         = NO\n\n# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any\n# special comment blocks from generated source code fragments. Normal C, C++ and\n# Fortran comments will always remain visible.\n# The default value is: YES.\n\nSTRIP_CODE_COMMENTS    = YES\n\n# If the REFERENCED_BY_RELATION tag is set to YES then for each documented\n# function all documented functions referencing it will be listed.\n# The default value is: NO.\n\nREFERENCED_BY_RELATION = NO\n\n# If the REFERENCES_RELATION tag is set to YES then for each documented function\n# all documented entities called/used by that function will be listed.\n# The default value is: NO.\n\nREFERENCES_RELATION    = NO\n\n# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set\n# to YES then the hyperlinks from functions in REFERENCES_RELATION and\n# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will\n# link to the documentation.\n# The default value is: YES.\n\nREFERENCES_LINK_SOURCE = YES\n\n# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the\n# source code will show a tooltip with additional information such as prototype,\n# brief description and links to the definition and documentation. Since this\n# will make the HTML file larger and loading of large files a bit slower, you\n# can opt to disable this feature.\n# The default value is: YES.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nSOURCE_TOOLTIPS        = YES\n\n# If the USE_HTAGS tag is set to YES then the references to source code will\n# point to the HTML generated by the htags(1) tool instead of doxygen built-in\n# source browser. The htags tool is part of GNU's global source tagging system\n# (see http://www.gnu.org/software/global/global.html). You will need version\n# 4.8.6 or higher.\n#\n# To use it do the following:\n# - Install the latest version of global\n# - Enable SOURCE_BROWSER and USE_HTAGS in the config file\n# - Make sure the INPUT points to the root of the source tree\n# - Run doxygen as normal\n#\n# Doxygen will invoke htags (and that will in turn invoke gtags), so these\n# tools must be available from the command line (i.e. in the search path).\n#\n# The result: instead of the source browser generated by doxygen, the links to\n# source code will now point to the output of htags.\n# The default value is: NO.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nUSE_HTAGS              = NO\n\n# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a\n# verbatim copy of the header file for each class for which an include is\n# specified. Set to NO to disable this.\n# See also: Section \\class.\n# The default value is: YES.\n\nVERBATIM_HEADERS       = YES\n\n# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the\n# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the\n# cost of reduced performance. This can be particularly helpful with template\n# rich C++ code for which doxygen's built-in parser lacks the necessary type\n# information.\n# Note: The availability of this option depends on whether or not doxygen was\n# generated with the -Duse-libclang=ON option for CMake.\n# The default value is: NO.\n\nCLANG_ASSISTED_PARSING = NO\n\n# If clang assisted parsing is enabled you can provide the compiler with command\n# line options that you would normally use when invoking the compiler. Note that\n# the include paths will already be set by doxygen for the files and directories\n# specified with INPUT and INCLUDE_PATH.\n# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.\n\nCLANG_OPTIONS          =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the alphabetical class index\n#---------------------------------------------------------------------------\n\n# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all\n# compounds will be generated. Enable this if the project contains a lot of\n# classes, structs, unions or interfaces.\n# The default value is: YES.\n\nALPHABETICAL_INDEX     = YES\n\n# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in\n# which the alphabetical index list will be split.\n# Minimum value: 1, maximum value: 20, default value: 5.\n# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.\n\nCOLS_IN_ALPHA_INDEX    = 5\n\n# In case all classes in a project start with a common prefix, all classes will\n# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag\n# can be used to specify a prefix (or a list of prefixes) that should be ignored\n# while generating the index headers.\n# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.\n\nIGNORE_PREFIX          =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the HTML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output\n# The default value is: YES.\n\nGENERATE_HTML          = YES\n\n# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_OUTPUT            = html\n\n# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each\n# generated HTML page (for example: .htm, .php, .asp).\n# The default value is: .html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FILE_EXTENSION    = .html\n\n# The HTML_HEADER tag can be used to specify a user-defined HTML header file for\n# each generated HTML page. If the tag is left blank doxygen will generate a\n# standard header.\n#\n# To get valid HTML the header file that includes any scripts and style sheets\n# that doxygen needs, which is dependent on the configuration options used (e.g.\n# the setting GENERATE_TREEVIEW). It is highly recommended to start with a\n# default header using\n# doxygen -w html new_header.html new_footer.html new_stylesheet.css\n# YourConfigFile\n# and then modify the file new_header.html. See also section \"Doxygen usage\"\n# for information on how to generate the default header that doxygen normally\n# uses.\n# Note: The header is subject to change so you typically have to regenerate the\n# default header when upgrading to a newer version of doxygen. For a description\n# of the possible markers and block names see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_HEADER            =\n\n# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each\n# generated HTML page. If the tag is left blank doxygen will generate a standard\n# footer. See HTML_HEADER for more information on how to generate a default\n# footer and what special commands can be used inside the footer. See also\n# section \"Doxygen usage\" for information on how to generate the default footer\n# that doxygen normally uses.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FOOTER            =\n\n# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style\n# sheet that is used by each HTML page. It can be used to fine-tune the look of\n# the HTML output. If left blank doxygen will generate a default style sheet.\n# See also section \"Doxygen usage\" for information on how to generate the style\n# sheet that doxygen normally uses.\n# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as\n# it is more robust and this tag (HTML_STYLESHEET) will in the future become\n# obsolete.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_STYLESHEET        =\n\n# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# cascading style sheets that are included after the standard style sheets\n# created by doxygen. Using this option one can overrule certain style aspects.\n# This is preferred over using HTML_STYLESHEET since it does not replace the\n# standard style sheet and is therefore more robust against future updates.\n# Doxygen will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list). For an example see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_STYLESHEET  =\n\n# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the HTML output directory. Note\n# that these files will be copied to the base HTML output directory. Use the\n# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these\n# files. In the HTML_STYLESHEET file, use the file name only. Also note that the\n# files will be copied as-is; there are no commands or markers available.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_FILES       =\n\n# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen\n# will adjust the colors in the style sheet and background images according to\n# this color. Hue is specified as an angle on a colorwheel, see\n# http://en.wikipedia.org/wiki/Hue for more information. For instance the value\n# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300\n# purple, and 360 is red again.\n# Minimum value: 0, maximum value: 359, default value: 220.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_HUE    = 220\n\n# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors\n# in the HTML output. For a value of 0 the output will use grayscales only. A\n# value of 255 will produce the most vivid colors.\n# Minimum value: 0, maximum value: 255, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_SAT    = 100\n\n# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the\n# luminance component of the colors in the HTML output. Values below 100\n# gradually make the output lighter, whereas values above 100 make the output\n# darker. The value divided by 100 is the actual gamma applied, so 80 represents\n# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not\n# change the gamma.\n# Minimum value: 40, maximum value: 240, default value: 80.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_GAMMA  = 80\n\n# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML\n# page will contain the date and time when the page was generated. Setting this\n# to YES can help to show when doxygen was last run and thus if the\n# documentation is up to date.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_TIMESTAMP         = NO\n\n# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML\n# documentation will contain sections that can be hidden and shown after the\n# page has loaded.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_SECTIONS  = NO\n\n# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries\n# shown in the various tree structured indices initially; the user can expand\n# and collapse entries dynamically later on. Doxygen will expand the tree to\n# such a level that at most the specified number of entries are visible (unless\n# a fully collapsed tree already exceeds this amount). So setting the number of\n# entries 1 will produce a full collapsed tree by default. 0 is a special value\n# representing an infinite number of entries and will result in a full expanded\n# tree by default.\n# Minimum value: 0, maximum value: 9999, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_INDEX_NUM_ENTRIES = 100\n\n# If the GENERATE_DOCSET tag is set to YES, additional index files will be\n# generated that can be used as input for Apple's Xcode 3 integrated development\n# environment (see: http://developer.apple.com/tools/xcode/), introduced with\n# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a\n# Makefile in the HTML output directory. Running make will produce the docset in\n# that directory and running make install will install the docset in\n# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at\n# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html\n# for more information.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_DOCSET        = NO\n\n# This tag determines the name of the docset feed. A documentation feed provides\n# an umbrella under which multiple documentation sets from a single provider\n# (such as a company or product suite) can be grouped.\n# The default value is: Doxygen generated docs.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_FEEDNAME        = \"Doxygen generated docs\"\n\n# This tag specifies a string that should uniquely identify the documentation\n# set bundle. This should be a reverse domain-name style string, e.g.\n# com.mycompany.MyDocSet. Doxygen will append .docset to the name.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_BUNDLE_ID       = org.doxygen.Project\n\n# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify\n# the documentation publisher. This should be a reverse domain-name style\n# string, e.g. com.mycompany.MyDocSet.documentation.\n# The default value is: org.doxygen.Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_ID    = org.doxygen.Publisher\n\n# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.\n# The default value is: Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_NAME  = Publisher\n\n# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three\n# additional HTML index files: index.hhp, index.hhc, and index.hhk. The\n# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop\n# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on\n# Windows.\n#\n# The HTML Help Workshop contains a compiler that can convert all HTML output\n# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML\n# files are now used as the Windows 98 help format, and will replace the old\n# Windows help format (.hlp) on all Windows platforms in the future. Compressed\n# HTML files also contain an index, a table of contents, and you can search for\n# words in the documentation. The HTML workshop also contains a viewer for\n# compressed HTML files.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_HTMLHELP      = NO\n\n# The CHM_FILE tag can be used to specify the file name of the resulting .chm\n# file. You can add a path in front of the file if the result should not be\n# written to the html output directory.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_FILE               =\n\n# The HHC_LOCATION tag can be used to specify the location (absolute path\n# including file name) of the HTML help compiler (hhc.exe). If non-empty,\n# doxygen will try to run the HTML help compiler on the generated index.hhp.\n# The file has to be specified with full path.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nHHC_LOCATION           =\n\n# The GENERATE_CHI flag controls if a separate .chi index file is generated\n# (YES) or that it should be included in the master .chm file (NO).\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nGENERATE_CHI           = NO\n\n# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)\n# and project file content.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_INDEX_ENCODING     =\n\n# The BINARY_TOC flag controls whether a binary table of contents is generated\n# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it\n# enables the Previous and Next buttons.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nBINARY_TOC             = NO\n\n# The TOC_EXPAND flag can be set to YES to add extra items for group members to\n# the table of contents of the HTML help documentation and to the tree view.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nTOC_EXPAND             = NO\n\n# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and\n# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that\n# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help\n# (.qch) of the generated HTML documentation.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_QHP           = NO\n\n# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify\n# the file name of the resulting .qch file. The path specified is relative to\n# the HTML output folder.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQCH_FILE               =\n\n# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help\n# Project output. For more information please see Qt Help Project / Namespace\n# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_NAMESPACE          = org.doxygen.Project\n\n# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt\n# Help Project output. For more information please see Qt Help Project / Virtual\n# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-\n# folders).\n# The default value is: doc.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_VIRTUAL_FOLDER     = doc\n\n# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom\n# filter to add. For more information please see Qt Help Project / Custom\n# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-\n# filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_NAME   =\n\n# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the\n# custom filter to add. For more information please see Qt Help Project / Custom\n# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-\n# filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_ATTRS  =\n\n# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this\n# project's filter section matches. Qt Help Project / Filter Attributes (see:\n# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_SECT_FILTER_ATTRS  =\n\n# The QHG_LOCATION tag can be used to specify the location of Qt's\n# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the\n# generated .qhp file.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHG_LOCATION           =\n\n# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be\n# generated, together with the HTML files, they form an Eclipse help plugin. To\n# install this plugin and make it available under the help contents menu in\n# Eclipse, the contents of the directory containing the HTML and XML files needs\n# to be copied into the plugins directory of eclipse. The name of the directory\n# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.\n# After copying Eclipse needs to be restarted before the help appears.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_ECLIPSEHELP   = NO\n\n# A unique identifier for the Eclipse help plugin. When installing the plugin\n# the directory name containing the HTML and XML files should also have this\n# name. Each documentation set should have its own identifier.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.\n\nECLIPSE_DOC_ID         = org.doxygen.Project\n\n# If you want full control over the layout of the generated HTML pages it might\n# be necessary to disable the index and replace it with your own. The\n# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top\n# of each HTML page. A value of NO enables the index and the value YES disables\n# it. Since the tabs in the index contain the same information as the navigation\n# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nDISABLE_INDEX          = NO\n\n# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index\n# structure should be generated to display hierarchical information. If the tag\n# value is set to YES, a side panel will be generated containing a tree-like\n# index structure (just like the one that is generated for HTML Help). For this\n# to work a browser that supports JavaScript, DHTML, CSS and frames is required\n# (i.e. any modern browser). Windows users are probably better off using the\n# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can\n# further fine-tune the look of the index. As an example, the default style\n# sheet generated by doxygen has an example that shows how to put an image at\n# the root of the tree instead of the PROJECT_NAME. Since the tree basically has\n# the same information as the tab index, you could consider setting\n# DISABLE_INDEX to YES when enabling this option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_TREEVIEW      = NO\n\n# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that\n# doxygen will group on one line in the generated HTML documentation.\n#\n# Note that a value of 0 will completely suppress the enum values from appearing\n# in the overview section.\n# Minimum value: 0, maximum value: 20, default value: 4.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nENUM_VALUES_PER_LINE   = 4\n\n# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used\n# to set the initial width (in pixels) of the frame in which the tree is shown.\n# Minimum value: 0, maximum value: 1500, default value: 250.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nTREEVIEW_WIDTH         = 250\n\n# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to\n# external symbols imported via tag files in a separate window.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nEXT_LINKS_IN_WINDOW    = NO\n\n# Use this tag to change the font size of LaTeX formulas included as images in\n# the HTML documentation. When you change the font size after a successful\n# doxygen run you need to manually remove any form_*.png images from the HTML\n# output directory to force them to be regenerated.\n# Minimum value: 8, maximum value: 50, default value: 10.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_FONTSIZE       = 10\n\n# Use the FORMULA_TRANPARENT tag to determine whether or not the images\n# generated for formulas are transparent PNGs. Transparent PNGs are not\n# supported properly for IE 6.0, but are supported on all modern browsers.\n#\n# Note that when changing this option you need to delete any form_*.png files in\n# the HTML output directory before the changes have effect.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_TRANSPARENT    = YES\n\n# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see\n# http://www.mathjax.org) which uses client side Javascript for the rendering\n# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX\n# installed or if you want to formulas look prettier in the HTML output. When\n# enabled you may also need to install MathJax separately and configure the path\n# to it using the MATHJAX_RELPATH option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nUSE_MATHJAX            = NO\n\n# When MathJax is enabled you can set the default output format to be used for\n# the MathJax output. See the MathJax site (see:\n# http://docs.mathjax.org/en/latest/output.html) for more details.\n# Possible values are: HTML-CSS (which is slower, but has the best\n# compatibility), NativeMML (i.e. MathML) and SVG.\n# The default value is: HTML-CSS.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_FORMAT         = HTML-CSS\n\n# When MathJax is enabled you need to specify the location relative to the HTML\n# output directory using the MATHJAX_RELPATH option. The destination directory\n# should contain the MathJax.js script. For instance, if the mathjax directory\n# is located at the same level as the HTML output directory, then\n# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax\n# Content Delivery Network so you can quickly see the result without installing\n# MathJax. However, it is strongly recommended to install a local copy of\n# MathJax from http://www.mathjax.org before deployment.\n# The default value is: http://cdn.mathjax.org/mathjax/latest.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest\n\n# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax\n# extension names that should be enabled during MathJax rendering. For example\n# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_EXTENSIONS     =\n\n# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces\n# of code that will be used on startup of the MathJax code. See the MathJax site\n# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an\n# example see the documentation.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_CODEFILE       =\n\n# When the SEARCHENGINE tag is enabled doxygen will generate a search box for\n# the HTML output. The underlying search engine uses javascript and DHTML and\n# should work on any modern browser. Note that when using HTML help\n# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)\n# there is already a search function so this one should typically be disabled.\n# For large projects the javascript based search engine can be slow, then\n# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to\n# search using the keyboard; to jump to the search box use <access key> + S\n# (what the <access key> is depends on the OS and browser, but it is typically\n# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down\n# key> to jump into the search results window, the results can be navigated\n# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel\n# the search. The filter options can be selected when the cursor is inside the\n# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>\n# to select a filter and <Enter> or <escape> to activate or cancel the filter\n# option.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nSEARCHENGINE           = YES\n\n# When the SERVER_BASED_SEARCH tag is enabled the search engine will be\n# implemented using a web server instead of a web client using Javascript. There\n# are two flavors of web server based searching depending on the EXTERNAL_SEARCH\n# setting. When disabled, doxygen will generate a PHP script for searching and\n# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing\n# and searching needs to be provided by external tools. See the section\n# \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSERVER_BASED_SEARCH    = NO\n\n# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP\n# script for searching. Instead the search results are written to an XML file\n# which needs to be processed by an external indexer. Doxygen will invoke an\n# external search engine pointed to by the SEARCHENGINE_URL option to obtain the\n# search results.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see: http://xapian.org/).\n#\n# See the section \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH        = NO\n\n# The SEARCHENGINE_URL should point to a search engine hosted by a web server\n# which will return the search results when EXTERNAL_SEARCH is enabled.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see: http://xapian.org/). See the section \"External Indexing and\n# Searching\" for details.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHENGINE_URL       =\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed\n# search data is written to a file for indexing by an external tool. With the\n# SEARCHDATA_FILE tag the name of this file can be specified.\n# The default file is: searchdata.xml.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHDATA_FILE        = searchdata.xml\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the\n# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is\n# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple\n# projects and redirect the results back to the right project.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH_ID     =\n\n# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen\n# projects other than the one defined by this configuration file, but that are\n# all added to the same external search index. Each project needs to have a\n# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of\n# to a relative location where the documentation can be found. The format is:\n# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTRA_SEARCH_MAPPINGS  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the LaTeX output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.\n# The default value is: YES.\n\nGENERATE_LATEX         = YES\n\n# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: latex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_OUTPUT           = latex\n\n# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be\n# invoked.\n#\n# Note that when enabling USE_PDFLATEX this option is only used for generating\n# bitmaps for formulas in the HTML output, but not in the Makefile that is\n# written to the output directory.\n# The default file is: latex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_CMD_NAME         = latex\n\n# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate\n# index for LaTeX.\n# The default file is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nMAKEINDEX_CMD_NAME     = makeindex\n\n# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nCOMPACT_LATEX          = NO\n\n# The PAPER_TYPE tag can be used to set the paper type that is used by the\n# printer.\n# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x\n# 14 inches) and executive (7.25 x 10.5 inches).\n# The default value is: a4.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPAPER_TYPE             = a4\n\n# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names\n# that should be included in the LaTeX output. The package can be specified just\n# by its name or with the correct syntax as to be used with the LaTeX\n# \\usepackage command. To get the times font for instance you can specify :\n# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}\n# To use the option intlimits with the amsmath package you can specify:\n# EXTRA_PACKAGES=[intlimits]{amsmath}\n# If left blank no extra packages will be included.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nEXTRA_PACKAGES         = {amsmath}\n\n# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the\n# generated LaTeX document. The header should contain everything until the first\n# chapter. If it is left blank doxygen will generate a standard header. See\n# section \"Doxygen usage\" for information on how to let doxygen write the\n# default header to a separate file.\n#\n# Note: Only use a user-defined header if you know what you are doing! The\n# following commands have a special meaning inside the header: $title,\n# $datetime, $date, $doxygenversion, $projectname, $projectnumber,\n# $projectbrief, $projectlogo. Doxygen will replace $title with the empty\n# string, for the replacement values of the other commands the user is referred\n# to HTML_HEADER.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HEADER           =\n\n# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the\n# generated LaTeX document. The footer should contain everything after the last\n# chapter. If it is left blank doxygen will generate a standard footer. See\n# LATEX_HEADER for more information on how to generate a default footer and what\n# special commands can be used inside the footer.\n#\n# Note: Only use a user-defined footer if you know what you are doing!\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_FOOTER           =\n\n# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# LaTeX style sheets that are included after the standard style sheets created\n# by doxygen. Using this option one can overrule certain style aspects. Doxygen\n# will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list).\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_STYLESHEET =\n\n# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the LATEX_OUTPUT output\n# directory. Note that the files will be copied as-is; there are no commands or\n# markers available.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_FILES      =\n\n# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is\n# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will\n# contain links (just like the HTML output) instead of page references. This\n# makes the output suitable for online browsing using a PDF viewer.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPDF_HYPERLINKS         = YES\n\n# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate\n# the PDF file directly from the LaTeX files. Set this option to YES, to get a\n# higher quality PDF documentation.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nUSE_PDFLATEX           = YES\n\n# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode\n# command to the generated LaTeX files. This will instruct LaTeX to keep running\n# if errors occur, instead of asking the user for help. This option is also used\n# when generating formulas in HTML.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BATCHMODE        = NO\n\n# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the\n# index chapters (such as File Index, Compound Index, etc.) in the output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HIDE_INDICES     = NO\n\n# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source\n# code with syntax highlighting in the LaTeX output.\n#\n# Note that which sources are shown also depends on other settings such as\n# SOURCE_BROWSER.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_SOURCE_CODE      = NO\n\n# The LATEX_BIB_STYLE tag can be used to specify the style to use for the\n# bibliography, e.g. plainnat, or ieeetr. See\n# http://en.wikipedia.org/wiki/BibTeX and \\cite for more info.\n# The default value is: plain.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BIB_STYLE        = plain\n\n# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated\n# page will contain the date and time when the page was generated. Setting this\n# to NO can help when comparing the output of multiple runs.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_TIMESTAMP        = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the RTF output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The\n# RTF output is optimized for Word 97 and may not look too pretty with other RTF\n# readers/editors.\n# The default value is: NO.\n\nGENERATE_RTF           = NO\n\n# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: rtf.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_OUTPUT             = rtf\n\n# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nCOMPACT_RTF            = NO\n\n# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will\n# contain hyperlink fields. The RTF file will contain links (just like the HTML\n# output) instead of page references. This makes the output suitable for online\n# browsing using Word or some other Word compatible readers that support those\n# fields.\n#\n# Note: WordPad (write) and others do not support links.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_HYPERLINKS         = NO\n\n# Load stylesheet definitions from file. Syntax is similar to doxygen's config\n# file, i.e. a series of assignments. You only have to provide replacements,\n# missing definitions are set to their default value.\n#\n# See also section \"Doxygen usage\" for information on how to generate the\n# default style sheet that doxygen normally uses.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_STYLESHEET_FILE    =\n\n# Set optional variables used in the generation of an RTF document. Syntax is\n# similar to doxygen's config file. A template extensions file can be generated\n# using doxygen -e rtf extensionFile.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_EXTENSIONS_FILE    =\n\n# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code\n# with syntax highlighting in the RTF output.\n#\n# Note that which sources are shown also depends on other settings such as\n# SOURCE_BROWSER.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_SOURCE_CODE        = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the man page output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for\n# classes and files.\n# The default value is: NO.\n\nGENERATE_MAN           = NO\n\n# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it. A directory man3 will be created inside the directory specified by\n# MAN_OUTPUT.\n# The default directory is: man.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_OUTPUT             = man\n\n# The MAN_EXTENSION tag determines the extension that is added to the generated\n# man pages. In case the manual section does not start with a number, the number\n# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is\n# optional.\n# The default value is: .3.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_EXTENSION          = .3\n\n# The MAN_SUBDIR tag determines the name of the directory created within\n# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by\n# MAN_EXTENSION with the initial . removed.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_SUBDIR             =\n\n# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it\n# will generate one additional man file for each entity documented in the real\n# man page(s). These additional files only source the real man page, but without\n# them the man command would be unable to find the correct page.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_LINKS              = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the XML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that\n# captures the structure of the code including all documentation.\n# The default value is: NO.\n\nGENERATE_XML           = NO\n\n# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: xml.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_OUTPUT             = xml\n\n# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program\n# listings (including syntax highlighting and cross-referencing information) to\n# the XML output. Note that enabling this will significantly increase the size\n# of the XML output.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_PROGRAMLISTING     = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to the DOCBOOK output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files\n# that can be used to generate PDF.\n# The default value is: NO.\n\nGENERATE_DOCBOOK       = NO\n\n# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in\n# front of it.\n# The default directory is: docbook.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_OUTPUT         = docbook\n\n# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the\n# program listings (including syntax highlighting and cross-referencing\n# information) to the DOCBOOK output. Note that enabling this will significantly\n# increase the size of the DOCBOOK output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_PROGRAMLISTING = NO\n\n#---------------------------------------------------------------------------\n# Configuration options for the AutoGen Definitions output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an\n# AutoGen Definitions (see http://autogen.sf.net) file that captures the\n# structure of the code including all documentation. Note that this feature is\n# still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_AUTOGEN_DEF   = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the Perl module output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module\n# file that captures the structure of the code including all documentation.\n#\n# Note that this feature is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_PERLMOD       = NO\n\n# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary\n# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI\n# output from the Perl module output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_LATEX          = NO\n\n# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely\n# formatted so it can be parsed by a human reader. This is useful if you want to\n# understand what is going on. On the other hand, if this tag is set to NO, the\n# size of the Perl module output will be much smaller and Perl will parse it\n# just the same.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_PRETTY         = YES\n\n# The names of the make variables in the generated doxyrules.make file are\n# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful\n# so different doxyrules.make files included by the same Makefile don't\n# overwrite each other's variables.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_MAKEVAR_PREFIX =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the preprocessor\n#---------------------------------------------------------------------------\n\n# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all\n# C-preprocessor directives found in the sources and include files.\n# The default value is: YES.\n\nENABLE_PREPROCESSING   = YES\n\n# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names\n# in the source code. If set to NO, only conditional compilation will be\n# performed. Macro expansion can be done in a controlled way by setting\n# EXPAND_ONLY_PREDEF to YES.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nMACRO_EXPANSION        = NO\n\n# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then\n# the macro expansion is limited to the macros specified with the PREDEFINED and\n# EXPAND_AS_DEFINED tags.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_ONLY_PREDEF     = NO\n\n# If the SEARCH_INCLUDES tag is set to YES, the include files in the\n# INCLUDE_PATH will be searched if a #include is found.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSEARCH_INCLUDES        = YES\n\n# The INCLUDE_PATH tag can be used to specify one or more directories that\n# contain include files that are not input files but should be processed by the\n# preprocessor.\n# This tag requires that the tag SEARCH_INCLUDES is set to YES.\n\nINCLUDE_PATH           =\n\n# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard\n# patterns (like *.h and *.hpp) to filter out the header-files in the\n# directories. If left blank, the patterns specified with FILE_PATTERNS will be\n# used.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nINCLUDE_FILE_PATTERNS  =\n\n# The PREDEFINED tag can be used to specify one or more macro names that are\n# defined before the preprocessor is started (similar to the -D option of e.g.\n# gcc). The argument of the tag is a list of macros of the form: name or\n# name=definition (no spaces). If the definition and the \"=\" are omitted, \"=1\"\n# is assumed. To prevent a macro definition from being undefined via #undef or\n# recursively expanded use the := operator instead of the = operator.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nPREDEFINED             =\n\n# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this\n# tag can be used to specify a list of macro names that should be expanded. The\n# macro definition that is found in the sources will be used. Use the PREDEFINED\n# tag if you want to use a different macro definition that overrules the\n# definition found in the source code.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_AS_DEFINED      =\n\n# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will\n# remove all references to function-like macros that are alone on a line, have\n# an all uppercase name, and do not end with a semicolon. Such function macros\n# are typically used for boiler-plate code, and will confuse the parser if not\n# removed.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSKIP_FUNCTION_MACROS   = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to external references\n#---------------------------------------------------------------------------\n\n# The TAGFILES tag can be used to specify one or more tag files. For each tag\n# file the location of the external documentation should be added. The format of\n# a tag file without this location is as follows:\n# TAGFILES = file1 file2 ...\n# Adding location for the tag files is done as follows:\n# TAGFILES = file1=loc1 \"file2 = loc2\" ...\n# where loc1 and loc2 can be relative or absolute paths or URLs. See the\n# section \"Linking to external documentation\" for more information about the use\n# of tag files.\n# Note: Each tag file must have a unique name (where the name does NOT include\n# the path). If a tag file is not located in the directory in which doxygen is\n# run, you must also specify the path to the tagfile here.\n\nTAGFILES               =\n\n# When a file name is specified after GENERATE_TAGFILE, doxygen will create a\n# tag file that is based on the input files it reads. See section \"Linking to\n# external documentation\" for more information about the usage of tag files.\n\nGENERATE_TAGFILE       =\n\n# If the ALLEXTERNALS tag is set to YES, all external class will be listed in\n# the class index. If set to NO, only the inherited external classes will be\n# listed.\n# The default value is: NO.\n\nALLEXTERNALS           = NO\n\n# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed\n# in the modules index. If set to NO, only the current project's groups will be\n# listed.\n# The default value is: YES.\n\nEXTERNAL_GROUPS        = YES\n\n# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in\n# the related pages index. If set to NO, only the current project's pages will\n# be listed.\n# The default value is: YES.\n\nEXTERNAL_PAGES         = YES\n\n# The PERL_PATH should be the absolute path and name of the perl script\n# interpreter (i.e. the result of 'which perl').\n# The default file (with absolute path) is: /usr/bin/perl.\n\nPERL_PATH              = /usr/bin/perl\n\n#---------------------------------------------------------------------------\n# Configuration options related to the dot tool\n#---------------------------------------------------------------------------\n\n# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram\n# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to\n# NO turns the diagrams off. Note that this option also works with HAVE_DOT\n# disabled, but it is recommended to install and use dot, since it yields more\n# powerful graphs.\n# The default value is: YES.\n\nCLASS_DIAGRAMS         = YES\n\n# You can define message sequence charts within doxygen comments using the \\msc\n# command. Doxygen will then run the mscgen tool (see:\n# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the\n# documentation. The MSCGEN_PATH tag allows you to specify the directory where\n# the mscgen tool resides. If left empty the tool is assumed to be found in the\n# default search path.\n\nMSCGEN_PATH            =\n\n# You can include diagrams made with dia in doxygen documentation. Doxygen will\n# then run dia to produce the diagram and insert it in the documentation. The\n# DIA_PATH tag allows you to specify the directory where the dia binary resides.\n# If left empty dia is assumed to be found in the default search path.\n\nDIA_PATH               =\n\n# If set to YES the inheritance and collaboration graphs will hide inheritance\n# and usage relations if the target is undocumented or is not a class.\n# The default value is: YES.\n\nHIDE_UNDOC_RELATIONS   = YES\n\n# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is\n# available from the path. This tool is part of Graphviz (see:\n# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent\n# Bell Labs. The other options in this section have no effect if this option is\n# set to NO\n# The default value is: NO.\n\nHAVE_DOT               = NO\n\n# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed\n# to run in parallel. When set to 0 doxygen will base this on the number of\n# processors available in the system. You can set it explicitly to a value\n# larger than 0 to get control over the balance between CPU load and processing\n# speed.\n# Minimum value: 0, maximum value: 32, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_NUM_THREADS        = 0\n\n# When you want a differently looking font in the dot files that doxygen\n# generates you can specify the font name using DOT_FONTNAME. You need to make\n# sure dot is able to find the font, which can be done by putting it in a\n# standard location or by setting the DOTFONTPATH environment variable or by\n# setting DOT_FONTPATH to the directory containing the font.\n# The default value is: Helvetica.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTNAME           = Helvetica\n\n# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of\n# dot graphs.\n# Minimum value: 4, maximum value: 24, default value: 10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTSIZE           = 10\n\n# By default doxygen will tell dot to use the default font as specified with\n# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set\n# the path where dot can find it using this tag.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTPATH           =\n\n# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for\n# each documented class showing the direct and indirect inheritance relations.\n# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCLASS_GRAPH            = YES\n\n# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a\n# graph for each documented class showing the direct and indirect implementation\n# dependencies (inheritance, containment, and class references variables) of the\n# class with other documented classes.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCOLLABORATION_GRAPH    = YES\n\n# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for\n# groups, showing the direct groups dependencies.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGROUP_GRAPHS           = YES\n\n# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and\n# collaboration diagrams in a style similar to the OMG's Unified Modeling\n# Language.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nUML_LOOK               = NO\n\n# If the UML_LOOK tag is enabled, the fields and methods are shown inside the\n# class node. If there are many fields or methods and many nodes the graph may\n# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the\n# number of items for each type to make the size more manageable. Set this to 0\n# for no limit. Note that the threshold may be exceeded by 50% before the limit\n# is enforced. So when you set the threshold to 10, up to 15 fields may appear,\n# but if the number exceeds 15, the total amount of fields shown is limited to\n# 10.\n# Minimum value: 0, maximum value: 100, default value: 10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nUML_LIMIT_NUM_FIELDS   = 10\n\n# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and\n# collaboration graphs will show the relations between templates and their\n# instances.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nTEMPLATE_RELATIONS     = NO\n\n# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to\n# YES then doxygen will generate a graph for each documented file showing the\n# direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDE_GRAPH          = YES\n\n# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are\n# set to YES then doxygen will generate a graph for each documented file showing\n# the direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDED_BY_GRAPH      = YES\n\n# If the CALL_GRAPH tag is set to YES then doxygen will generate a call\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable call graphs for selected\n# functions only using the \\callgraph command. Disabling a call graph can be\n# accomplished by means of the command \\hidecallgraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALL_GRAPH             = NO\n\n# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable caller graphs for selected\n# functions only using the \\callergraph command. Disabling a caller graph can be\n# accomplished by means of the command \\hidecallergraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALLER_GRAPH           = NO\n\n# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical\n# hierarchy of all classes instead of a textual one.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGRAPHICAL_HIERARCHY    = YES\n\n# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the\n# dependencies a directory has on other directories in a graphical way. The\n# dependency relations are determined by the #include relations between the\n# files in the directories.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDIRECTORY_GRAPH        = YES\n\n# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images\n# generated by dot. For an explanation of the image formats see the section\n# output formats in the documentation of the dot tool (Graphviz (see:\n# http://www.graphviz.org/)).\n# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order\n# to make the SVG files visible in IE 9+ (other browsers do not have this\n# requirement).\n# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,\n# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and\n# png:gdiplus:gdiplus.\n# The default value is: png.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_IMAGE_FORMAT       = png\n\n# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to\n# enable generation of interactive SVG images that allow zooming and panning.\n#\n# Note that this requires a modern browser other than Internet Explorer. Tested\n# and working are Firefox, Chrome, Safari, and Opera.\n# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make\n# the SVG files visible. Older versions of IE do not have SVG support.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINTERACTIVE_SVG        = NO\n\n# The DOT_PATH tag can be used to specify the path where the dot tool can be\n# found. If left blank, it is assumed the dot tool can be found in the path.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_PATH               =\n\n# The DOTFILE_DIRS tag can be used to specify one or more directories that\n# contain dot files that are included in the documentation (see the \\dotfile\n# command).\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOTFILE_DIRS           =\n\n# The MSCFILE_DIRS tag can be used to specify one or more directories that\n# contain msc files that are included in the documentation (see the \\mscfile\n# command).\n\nMSCFILE_DIRS           =\n\n# The DIAFILE_DIRS tag can be used to specify one or more directories that\n# contain dia files that are included in the documentation (see the \\diafile\n# command).\n\nDIAFILE_DIRS           =\n\n# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the\n# path where java can find the plantuml.jar file. If left blank, it is assumed\n# PlantUML is not used or called during a preprocessing step. Doxygen will\n# generate a warning when it encounters a \\startuml command in this case and\n# will not generate output for the diagram.\n\nPLANTUML_JAR_PATH      =\n\n# When using plantuml, the specified paths are searched for files specified by\n# the !include statement in a plantuml block.\n\nPLANTUML_INCLUDE_PATH  =\n\n# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes\n# that will be shown in the graph. If the number of nodes in a graph becomes\n# larger than this value, doxygen will truncate the graph, which is visualized\n# by representing a node as a red box. Note that doxygen if the number of direct\n# children of the root node in a graph is already larger than\n# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that\n# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.\n# Minimum value: 0, maximum value: 10000, default value: 50.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_GRAPH_MAX_NODES    = 50\n\n# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs\n# generated by dot. A depth value of 3 means that only nodes reachable from the\n# root by following a path via at most 3 edges will be shown. Nodes that lay\n# further from the root node will be omitted. Note that setting this option to 1\n# or 2 may greatly reduce the computation time needed for large code bases. Also\n# note that the size of a graph can be further restricted by\n# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.\n# Minimum value: 0, maximum value: 1000, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nMAX_DOT_GRAPH_DEPTH    = 0\n\n# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent\n# background. This is disabled by default, because dot on Windows does not seem\n# to support this out of the box.\n#\n# Warning: Depending on the platform used, enabling this option may lead to\n# badly anti-aliased labels on the edges of a graph (i.e. they become hard to\n# read).\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_TRANSPARENT        = NO\n\n# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output\n# files in one run (i.e. multiple -o and -T options on the command line). This\n# makes dot run faster, but since only newer versions of dot (>1.8.10) support\n# this, this feature is disabled by default.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_MULTI_TARGETS      = NO\n\n# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page\n# explaining the meaning of the various boxes and arrows in the dot generated\n# graphs.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGENERATE_LEGEND        = YES\n\n# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot\n# files that are used to generate the various graphs.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_CLEANUP            = YES\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/Makefile",
    "content": "#\n# --- WRF-HYDRO makefile\n# --- Requires ESMVv7+\n# --- WRF-HYDRO ESMF component.\n#\n\n# ###############\n# Local Variables\n# ###############\n\nHR    := ========================================\nHR    := $(HR)$(HR)\nCOMMA := ,\nDIR   := $(CURDIR)\n\n# ###########################\n# Include ESMFMKFILE fragment\n# ###########################\n\nifneq ($(origin ESMFMKFILE), environment)\n$(error Environment variable ESMFMKFILE was not set.)\nendif\ninclude $(ESMFMKFILE)\n\n# #########################\n# Determine Build Precision\n# #########################\n\nifeq ($(BUILD_PREC),r4)\noverride ESMF_F90COMPILECPPFLAGS += -DREAL4\nelse ifeq ($(BUILD_PREC),r8)\noverride ESMF_F90COMPILECPPFLAGS += -DREAL8\nelse\noverride ESMF_F90COMPILECPPFLAGS += -DREAL4\nendif\n\n# #################################\n# Compile with Debugging Directives\n# #################################\n\nifeq ($(DEBUG),on)\noverride ESMF_F90COMPILECPPFLAGS += -DDEBUG\noverride ESMF_CXXCOMPILECPPFLAGS += -DDEBUG\nendif\n\nifdef DBGBUILD\nESMF_F90COMPILEOPTS += -g -traceback\nESMF_CXXCOMPILEOPTS += -g -traceback\nendif\n\n# ###########################\n# Determine Installation Path\n# ###########################\n\nifndef DESTDIR\nDESTDIR  := $(DIR)\nendif\n\nifndef INSTDIR\nINSTDIR  := WRFHYDRO_$(shell date '+%Y-%m-%d-%H-%M-%S')\nendif\n\nifndef INSTPATH\nINSTPATH := $(abspath $(DESTDIR)/$(INSTDIR))\nendif\n\n# ###############\n# Model Variables\n# ###############\n\nifndef WRFHYDRO_DIR\nMODEL_RDIR   := $(abspath $(DIR)/../../../..)\nelse\nMODEL_RDIR   := $(abspath $(WRFHYDRO_DIR))\nendif\nMODEL_DIR    := $(abspath $(MODEL_RDIR)/src)\nMODEL_MKDIR  := $(abspath $(MODEL_DIR))\nMODEL_LIBDIR := $(abspath $(MODEL_DIR)/lib)\nMODEL_MODDIR := $(abspath $(MODEL_DIR)/mod)\nMODEL_MPPDIR := $(abspath $(MODEL_DIR)/MPP)\nMODEL_RTGDIR := $(abspath $(MODEL_DIR)/Routing)\n\nMODEL_MK     := $(abspath $(MODEL_MKDIR)/Makefile.comm)\nMODEL_MKINC  := $(abspath $(MODEL_DIR)/macros)\nMODEL_LIB    := $(abspath $(MODEL_LIBDIR)/libHYDRO.a)\n\nMODEL_MODS   := $(abspath $(MODEL_MPPDIR)/module_mpp_land.mod)\nMODEL_MODS   += $(abspath $(MODEL_MPPDIR)/module_cpl_land.mod)\nMODEL_MODS   += $(abspath $(MODEL_MODDIR)/module_hydro_drv.mod)\nMODEL_MODS   += $(abspath $(MODEL_MODDIR)/module_rt_data.mod)\nMODEL_MODS   += $(abspath $(MODEL_MODDIR)/module_namelist.mod)\nMODEL_MODS   += $(abspath $(MODEL_MODDIR)/module_hydro_io.mod)\nMODEL_MODS   += $(abspath $(MODEL_MODDIR)/module_lsm_forcing.mod)\nMODEL_MODS   += $(abspath $(MODEL_RTGDIR)/Overland/overland_data.mod)\nMODEL_MODS   += $(abspath $(MODEL_RTGDIR)/Overland/overland_control.mod)\n\nMODEL_FILES  := $(MODEL_LIB) $(MODEL_MODS)\n\n# #############\n# Cap Variables\n# #############\n\nCAP_DIR       := $(abspath $(DIR))\nCAP_LIB       := libwrfhydro_nuopc.a\nCAP_DEP_FRONT := wrfhydro_nuopc\nCAP_VERS      := VERSION\nCAP_MK        := wrfhydro.mk\n\nCAP_OBJS      := WRFHydro_NUOPC_Cap.o\nCAP_OBJS      += WRFHydro_NUOPC_Gluecode.o\nCAP_OBJS      += WRFHydro_NUOPC_Fields.o\nCAP_OBJS      += WRFHydro_NUOPC_Flags.o\nCAP_OBJS      += WRFHydro_ESMF_Extensions.o\n\nCAP_MODS      := wrfhydro_nuopc.mod\nCAP_MODS      += wrfhydro_nuopc_gluecode.mod\nCAP_MODS      += wrfhydro_nuopc_fields.mod\nCAP_MODS      += wrfhydro_nuopc_flags.mod\nCAP_MODS      += wrfhydro_esmf_extensions.mod\n\nCAP_FILES     := $(CAP_OBJS) $(CAP_MODS) $(CAP_LIB) $(CAP_VERS) $(CAP_MK)\n\n# ###############################\n# Include Model Makefile Fragment\n# ###############################\n\ninclude $(MODEL_MKINC)\noverride ESMF_F90COMPILEPATHS    += -I$(MODEL_MODDIR)\noverride ESMF_F90COMPILEPATHS    += -I$(MODEL_MPPDIR)\noverride ESMF_F90COMPILECPPFLAGS += $(HYDRO_D)\n\n# #######################\n# Primary Makefile Target\n# #######################\n.PHONY: nuopc nuopcinstall nuopcdistclean nuopcclean install_mk\n\nnuopc: $(CAP_FILES)\n\nnuopcinstall: $(CAP_LIB) $(CAP_MODS) $(CAP_VERS) \\\n $(addprefix $(INSTPATH)/,$(CAP_LIB)) \\\n $(addprefix $(INSTPATH)/,$(CAP_MODS)) \\\n $(addprefix $(INSTPATH)/,$(CAP_VERS)) \\\n install_mk\n\n# ############\n# Dependencies\n# ############\n\nWRFHydro_NUOPC_Cap.o: WRFHydro_NUOPC_Macros.h \\\n WRFHydro_NUOPC_Gluecode.o WRFHydro_NUOPC_Fields.o \\\n WRFHydro_NUOPC_Flags.o WRFHydro_ESMF_Extensions.o\nWRFHydro_NUOPC_Gluecode.o: WRFHydro_NUOPC_Macros.h \\\n WRFHydro_NUOPC_Fields.o WRFHydro_NUOPC_Flags.o \\\n WRFHydro_ESMF_Extensions.o $(MODEL_MODS)\nWRFHydro_NUOPC_Fields.o: WRFHydro_NUOPC_Macros.h \\\n WRFHydro_NUOPC_Flags.o WRFHydro_ESMF_Extensions.o \\\n $(MODEL_MODS)\n\nwrfhydro_nuopc.mod: WRFHydro_NUOPC_Cap.o\nwrfhydro_nuopc_gluecode.mod: WRFHydro_NUOPC_Gluecode.o\nwrfhydro_nuopc_fields.mod: WRFHydro_NUOPC_Fields.o\nwrfhydro_nuopc_flags.mod: WRFHydro_NUOPC_Flags.o\nwrfhydro_esmf_extensions.mod: WRFHydro_ESMF_Extensions.o\n\n# ###############\n# Build Model\n# ###############\n\nbuild_model:\n\t@echo $(HR)\n\t@echo \"Building Model...\"\n\t@echo \"\"\n\t$(call checkdir, $(MODEL_DIR))\n\tmkdir -p $(MODEL_LIBDIR)\n\tmkdir -p $(MODEL_MODDIR)\n\tmake -C $(MODEL_DIR) -f $(MODEL_MK)\n\n$(MODEL_MODS): build_model\n\n$(MODEL_LIB): build_model\n\n# ##############\n# Build Settings\n# ##############\n\n.SUFFIXES:\n.SUFFIXES: .c .C .f90 .F90 .F .f\n\n.F:\n\t@echo \"Must have an explicit rule for\" $*\n.f:\n\t@echo \"Must have an explicit rule for\" $*\n.C:\n\t@echo \"Must have an explicit rule for\" $*\n.c:\n\t@echo \"Must have an explicit rule for\" $*\n\n%.o : %.f90\n\t@echo $(HR)\n\t@echo \"Compiling $@...\"\n\t@echo\n\t$(ESMF_F90COMPILER) -c $(ESMF_F90COMPILEOPTS) $(ESMF_F90COMPILEPATHS) $(ESMF_F90COMPILEFREENOCPP) $<\n\n%.o : %.F90\n\t@echo $(HR)\n\t@echo \"Compiling $@...\"\n\t@echo\n\t$(ESMF_F90COMPILER) -c $(ESMF_F90COMPILEOPTS) $(ESMF_F90COMPILEPATHS) $(ESMF_F90COMPILEFREECPP) $(ESMF_F90COMPILECPPFLAGS) -DESMF_VERSION_MAJOR=$(ESMF_VERSION_MAJOR) $<\n\n# #####################\n# Build NUOPC Component\n# #####################\n\n$(CAP_LIB): $(MODEL_LIB) $(CAP_OBJS)\n\t@echo $(HR)\n\t@echo \"Creating static library $@...\"\n\t@echo\n\t$(call checkfile, $(MODEL_LIB))\n\tcp $(MODEL_LIB) $@\n\tar cr $@ $(CAP_OBJS)\n\n$(CAP_VERS):\n\t@echo $(HR)\n\t@echo \"Generating Version Information\"\n\t@echo\nifneq (,$(wildcard $(MODEL_RDIR)/.git))\n\t@echo \"# NUOPC Cap Revision #\" > $(CAP_VERS)\n\t@git log . | grep -m 1 \"commit \" >> $(CAP_VERS)\n\t@git log . | grep -m 1 \"Author: \" >> $(CAP_VERS)\n\t@git log . | grep -m 1 \"Date: \" >> $(CAP_VERS)\n\t@echo >> $(CAP_VERS)\n\t@echo \"# Model Revision     #\" >> $(CAP_VERS)\n\t@git log $(MODEL_RDIR) | grep -m 1 \"commit \" >> $(CAP_VERS)\n\t@git log $(MODEL_RDIR) | grep -m 1 \"Author: \" >> $(CAP_VERS)\n\t@git log $(MODEL_RDIR) | grep -m 1 \"Date: \" >> $(CAP_VERS)\n\t@echo >> $(CAP_VERS)\nelse ifneq (,$(wildcard $(MODEL_RDIR)/.svn))\n\t@echo \"# NUOPC Cap Revision #\" > $(CAP_VERS)\n\t@svn info . | grep URL >> $(CAP_VERS)\n\t@svn info . | grep \"Last Changed Rev\" >> $(CAP_VERS)\n\t@echo >> $(CAP_VERS)\n\t@echo \"# Model Revision     #\" >> $(CAP_VERS)\n\t@svn info $(MODEL_RDIR) | grep URL >> $(CAP_VERS)\n\t@svn info $(MODEL_RDIR) | grep \"Last Changed Rev\" >> $(CAP_VERS)\n\t@echo >> $(CAP_VERS)\nelse\n\t@echo \"# Version Information Not Found\" > $(CAP_VERS)\nendif\n\n$(CAP_MK):\n\t@echo $(HR)\n\t@echo \"Generating NUOPC Makefile Fragment\"\n\t@echo\n\t@echo \"# ESMF self-describing build dependency makefile fragment\" > $(CAP_MK)\n\t@echo \"\" >> $(CAP_MK)\n\t@echo \"ESMF_DEP_FRONT     = $(CAP_DEP_FRONT)\" >> $(CAP_MK)\n\t@echo \"ESMF_DEP_INCPATH   = $(CAP_DIR)\" >> $(CAP_MK)\n\t@echo \"ESMF_DEP_CMPL_OBJS = \" >> $(CAP_MK)\n\t@echo \"ESMF_DEP_LINK_OBJS = $(CAP_DIR)/$(CAP_LIB)\" >> $(CAP_MK)\n\t@echo \"ESMF_DEP_SHRD_PATH = \" >> $(CAP_MK)\n\t@echo \"ESMF_DEP_SHRD_LIBS = \" >> $(CAP_MK)\n\n# -----------------------------------------------------------------------------\n# Install Library, Modules, and Makefile Fragment\n# -----------------------------------------------------------------------------\n\n$(INSTPATH)/%: %\n\t@echo $(HR)\n\t@echo \"Installing $(notdir $@)\"\n\t@echo\n\t@mkdir -p $(INSTPATH)\n\t@cp $(notdir $@) $@\n\ninstall_mk:\n\t@echo $(HR)\n\t@echo \"Installing NUOPC Makefile Fragment\"\n\t@echo\n\t@mkdir -p $(INSTPATH)\n\t@echo \"# ESMF self-describing build dependency makefile fragment\" > $(INSTPATH)/$(CAP_MK)\n\t@echo \"\" >> $(INSTPATH)/$(CAP_MK)\n\t@echo \"ESMF_DEP_FRONT     = $(CAP_DEP_FRONT)\" >> $(INSTPATH)/$(CAP_MK)\n\t@echo \"ESMF_DEP_INCPATH   = $(INSTPATH)\" >> $(INSTPATH)/$(CAP_MK)\n\t@echo \"ESMF_DEP_CMPL_OBJS = \" >> $(INSTPATH)/$(CAP_MK)\n\t@echo \"ESMF_DEP_LINK_OBJS = $(INSTPATH)/$(CAP_LIB)\" >> $(INSTPATH)/$(CAP_MK)\n\t@echo \"ESMF_DEP_SHRD_PATH = \" >> $(INSTPATH)/$(CAP_MK)\n\t@echo \"ESMF_DEP_SHRD_LIBS = \" >> $(INSTPATH)/$(CAP_MK)\n\n# ###########\n# Check Build\n# ###########\n\ndefine checkfile\n\t@if [ ! -e $(1) ]; then \\\n\techo \"File is missing:$(1)\"; \\\n\texit 1; fi;\n\nendef # blank line in checkfile is required\n\ndefine checkdir\n\t@if [ ! -d $(1) ]; then \\\n\techo \"Directory is missing:$(1)\"; \\\n\texit 1; fi;\nendef # blank line in checkdir is required\n\ncheck: check_esmf check_model check_cap\n\n# ##################\n# Check ESMF Version\n# ##################\n\ncheck_esmf:\n\t@echo $(HR)\n\t@echo \"Checking ESMFMKFILE file...\"\n\t@echo\n\t@echo \"ESMFMKFILE=$(ESMFMKFILE)\"\n\t@if [ \"$(ESMF_VERSION_MAJOR)\" -lt 7 ]; then \\\n\techo \"Please use ESMF version 7+\"; \\\n\texit 1; fi;\n\t@echo \"ESMF Version=$(ESMF_VERSION_STRING)\"\n\n# ###########\n# Check Model\n# ###########\n\ncheck_model:\n\t@echo $(HR)\n\t@echo \"Checking for Model files...\"\n\t@echo\n\t$(foreach FILENAME, $(MODEL_FILES), $(call checkfile, $(FILENAME)))\n\n# #########\n# Check Cap\n# #########\n\ncheck_cap:\n\t@echo $(HR)\n\t@echo \"Checking for WRF-Hydro NUOPC files...\"\n\t@echo\n\t$(foreach FILENAME, $(CAP_FILES), $(call checkfile, $(FILENAME)))\n\n# ###################\n# Clean Cap and Model\n# ###################\n\nnuopcdistclean: nuopcclean\n\t@echo $(HR)\n\t@echo \"Cleaning Model build...\"\n\t@echo \"\"\n\t$(call checkdir, $(MODEL_DIR))\n\tmake -C $(MODEL_DIR) -f $(MODEL_MK) clean\n\n# #########\n# Clean Cap\n# #########\n\nnuopcclean:\n\t@echo $(HR)\n\t@echo \"Cleaning Cap build...\"\n\t@echo\n\trm -f $(CAP_FILES)\n\n# ------------------------------------------------------------------------------\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/WRFHydro_ESMF_Extensions.F90",
    "content": "!=========================================================================================\n! WRFHYDRO ESMF Extensions Module\n!=========================================================================================\n! CONFIGURATION IDENTIFICATION $HeadURL$\n! CONFIGURATION IDENTIFICATION @(#)$Id$\n!=========================================================================================\n\n! ESMF macros for logging\n#define FILENAME \"WRFHydro_ESMF_Extensions.F90\"\n#define CONTEXT  line=__LINE__,file=FILENAME,method=METHOD\n#define PASSTHRU msg=ESMF_LOGERR_PASSTHRU,CONTEXT\n\n! Define ESMF real kind to match WRFHYDRO single/double precision\n#if defined(SINGLE)\n#define ESMF_KIND_RX ESMF_KIND_R4\n#define ESMF_TYPEKIND_RX ESMF_TYPEKIND_R4\n#else\n#define ESMF_KIND_RX ESMF_KIND_R8\n#define ESMF_TYPEKIND_RX ESMF_TYPEKIND_R8\n#endif\n\n! Macros for debugging\n#define DEBUG_ESMF_IMPORT___disabled\n#define DEBUG_ESMF_EXPORT___disabled\n\n!=========================================================================================\n! WRFHYDRO ESMF Extensions Module\n!=========================================================================================\nmodule WRFHydro_ESMF_Extensions\n\n  use ESMF\n  use NUOPC\n  use NETCDF\n\n  implicit none\n\n  private\n\n  public :: WRFHYDRO_ESMF_GridWrite\n  public :: WRFHYDRO_ESMF_MAPPRESET_GLOBAL\n  public :: WRFHYDRO_ESMF_MAPPRESET_CONUS\n  public :: WRFHYDRO_ESMF_MAPPRESET_IRENE\n  public :: WRFHYDRO_ESMF_MAPPRESET_FRONTRANGE\n  public :: WRFHYDRO_ESMF_NetcdfReadIXJX\n  public :: WRFHYDRO_ESMF_NetcdfIsPresent\n  public :: WRFHYDRO_ESMF_LogStateList\n  public :: WRFHYDRO_ESMF_LogState\n  public :: WRFHYDRO_ESMF_LogFieldConnections\n  public :: WRFHYDRO_ESMF_LogGrid\n  public :: WRFHYDRO_ESMF_LogFieldList\n  public :: WRFHYDRO_ESMF_LogField\n  public :: WRFHYDRO_ESMF_LogFieldLclVal\n  public :: WRFHYDRO_ESMF_LogArrayLclVal\n  public :: WRFHYDRO_ESMF_LogFarrayLclVal\n  public :: WRFHYDRO_ESMF_LogCplList\n  public :: WRFHYDRO_ESMF_ChDir\n\n\n!==============================================================================\n!\n! INTERFACE BLOCKS\n!\n!==============================================================================\n\n  interface WRFHYDRO_ESMF_GridWrite\n    module procedure WRFHYDRO_ESMF_GridWrite_coords\n    module procedure WRFHYDRO_ESMF_GridWrite_preset\n    module procedure WRFHYDRO_ESMF_GridWrite_default\n  end interface\n\n  interface WRFHYDRO_ESMF_NclScriptWrite\n    module procedure WRFHYDRO_ESMF_NclScriptWrite_coords\n    module procedure WRFHYDRO_ESMF_NclScriptWrite_preset\n    module procedure WRFHYDRO_ESMF_NclScriptWrite_default\n  end interface\n\n  interface WRFHYDRO_ESMF_FerretScriptWrite\n    module procedure WRFHYDRO_ESMF_FerretScriptWrite_coords\n    module procedure WRFHYDRO_ESMF_FerretScriptWrite_preset\n    module procedure WRFHYDRO_ESMF_FerretScriptWrite_default\n  end interface\n\n  interface WRFHYDRO_ESMF_NetcdfReadIXJX\n    module procedure WRFHYDRO_ESMF_NetcdfReadIXJX_Field\n    module procedure WRFHYDRO_ESMF_NetcdfReadIXJX_Array\n    module procedure WRFHYDRO_ESMF_NetcdfReadIXJX_I4\n    module procedure WRFHYDRO_ESMF_NetcdfReadIXJX_I8\n    module procedure WRFHYDRO_ESMF_NetcdfReadIXJX_R4\n    module procedure WRFHYDRO_ESMF_NetcdfReadIXJX_R8\n  end interface\n\n  interface WRFHYDRO_ESMF_LogFarrayLclVal\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_I41D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_I42D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_I43D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_I81D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_I82D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_I83D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_R41D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_R42D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_R43D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_R81D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_R82D\n    module procedure WRFHYDRO_ESMF_LogFarrayLclVal_R83D\n  end interface\n\n  interface\n    integer function local_chdir(path) bind(C, name=\"chdir\")\n      use iso_c_binding\n      character(c_char) :: path(*)\n    end function\n  end interface\n\n!==============================================================================\n!\n! DERIVED TYPES\n!\n!==============================================================================\n\n  type MapDesc\n    character(len=16) :: name\n    logical           :: global\n    real              :: minLat\n    real              :: maxLat\n    real              :: minLon\n    real              :: maxLon\n  endtype MapDesc\n\n\n!==============================================================================\n!\n! PRESET VALUES\n!\n!==============================================================================\n\n  type(MapDesc),parameter :: &\n    WRFHYDRO_ESMF_MAPPRESET_GLOBAL = MapDesc(\"GLOBAL\",.TRUE.,-90.0,90.0,-180.0,-180.0), &\n    WRFHYDRO_ESMF_MAPPRESET_CONUS = MapDesc(\"CONUS\",.FALSE.,18.0,49.0,235.0,298.0), &\n    WRFHYDRO_ESMF_MAPPRESET_IRENE = MapDesc(\"IRENE\",.FALSE.,10.0,60.0,240.0,320.0), &\n    WRFHYDRO_ESMF_MAPPRESET_FRONTRANGE = MapDesc(\"FRONTRANGE\",.FALSE.,38.5,41.0,-107.0,-103.5)\n  character(len=*),parameter :: NUOPC_COPY_FWD = 'from ESMF_Array to FORTRAN array'\n  character(len=*),parameter :: NUOPC_COPY_BWD = 'from FORTRAN array to ESMF_Array'\n\n\ncontains\n\n  !-----------------------------------------------------------------------------\n#define METHOD \"WRFHYDRO_ESMF_GridWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_GridWrite - Write Grid data to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_GridWrite\n  subroutine WRFHYDRO_ESMF_GridWrite_coords(grid, nclScript, mapName, minCoords, &\n    maxCoords, fileName, overwrite, status, timeslice, iofmt, relaxedflag, rc)\n! ! ARGUMENTS\n    type(ESMF_Grid),            intent(in)            :: grid\n    logical,                    intent(in)            :: nclScript\n    character(len=*),           intent(in)            :: mapName\n    real,                       intent(in)            :: minCoords(2)\n    real,                       intent(in)            :: maxCoords(2)\n    character(len=*),           intent(in),  optional :: fileName\n    logical,                    intent(in),  optional :: overwrite\n    type(ESMF_FileStatus_Flag), intent(in),  optional :: status\n    integer,                    intent(in),  optional :: timeslice\n    type(ESMF_IOFmt_Flag),      intent(in),  optional :: iofmt\n    logical,                    intent(in),  optional :: relaxedflag\n    integer,                    intent(out), optional :: rc\n! !DESCRIPTION:\n!   Write the data in {\\tt grid} to {\\tt file} if supported by the\n!   {\\tt iofmt}.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[grid]\n!     The {\\tt ESMF\\_Grid} object whose data is to be written.\n!   \\item[{[nclScript]}]\n!     If {\\tt .true.} then NUOPC will write an NCL script that can be used to\n!     generate grid graphics. Default is {\\tt .false.}.\n!   \\item[{[mapName]}]\n!     Map name to be written to NCL script.\n!   \\item[{[minCoords]}]\n!     Minimum map coordinates to be written to NCL script.\n!   \\item[{[maxCoords]}]\n!     Maximum map coordinates to be written to NCL script.\n!   \\item[fileName]\n!     The name of the file to write to. If not present then the file will\n!     be written to the grid's name.\n!   \\item[{[overwrite]}]\n!      A logical flag, the default is .false., i.e., existing Field data may\n!      {\\em not} be overwritten. If .true., the\n!      data corresponding to each field's name will be\n!      be overwritten. If the {\\tt timeslice} option is given, only data for\n!      the given timeslice may be overwritten.\n!      Note that it is always an error to attempt to overwrite a NetCDF\n!      variable with data which has a different shape.\n!   \\item[{[status]}]\n!      The file status. Valid options are {\\tt ESMF\\_FILESTATUS\\_NEW},\n!      {\\tt ESMF\\_FILESTATUS\\_OLD}, {\\tt ESMF\\_FILESTATUS\\_REPLACE}, and\n!      {\\tt ESMF\\_FILESTATUS\\_UNKNOWN} (default).\n!   \\item[{[timeslice]}]\n!     Time slice counter. Must be positive. The behavior of this\n!     option may depend on the setting of the {\\tt overwrite} flag:\n!     \\begin{description}\n!     \\item[{\\tt overwrite = .false.}:]\\ If the timeslice value is\n!     less than the maximum time already in the file, the write will fail.\n!     \\item[{\\tt overwrite = .true.}:]\\ Any positive timeslice value is valid.\n!     \\end{description}\n!     By default, i.e. by omitting the {\\tt timeslice} argument, no\n!     provisions for time slicing are made in the output file,\n!     however, if the file already contains a time axis for the variable,\n!     a timeslice one greater than the maximum will be written.\n!   \\item[{[iofmt]}]\n!    The IO format.  Valid options are  {\\tt ESMF\\_IOFMT\\_BIN} and\n!    {\\tt ESMF\\_IOFMT\\_NETCDF}. If not present, file names with a {\\tt .bin}\n!    extension will use {\\tt ESMF\\_IOFMT\\_BIN}, and file names with a {\\tt .nc}\n!    extension will use {\\tt ESMF\\_IOFMT\\_NETCDF}.  Other files default to\n!    {\\tt ESMF\\_IOFMT\\_NETCDF}.\n!   \\item[{[relaxedflag]}]\n!     If {\\tt .true.}, then no error is returned even if the call cannot write\n!     the file due to library limitations. Default is {\\tt .false.}.\n!   \\item[{[rc]}]\n!     Return code; equals {\\tt ESMF\\_SUCCESS} if there are no errors.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    type(MapDesc)  :: map\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    map = MapDesc(trim(mapName),.FALSE., &\n      minCoords(2),maxCoords(2),minCoords(1),maxCoords(1))\n\n    call WRFHYDRO_ESMF_GridWrite(grid, fileName=fileName, overwrite=overwrite, &\n      status=status, timeslice=timeslice, iofmt=iofmt, &\n      relaxedflag=relaxedflag, nclScript=nclScript, map=map, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_GridWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_GridWrite - Write Grid data to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_GridWrite\n  subroutine WRFHYDRO_ESMF_GridWrite_preset(grid, nclScript, mapPreset, &\n    fileName, overwrite, status, timeslice, iofmt, relaxedflag, rc)\n! ! ARGUMENTS\n    type(ESMF_Grid),            intent(in)            :: grid\n    logical,                    intent(in)            :: nclScript\n    character(len=*),           intent(in)            :: mapPreset\n    character(len=*),           intent(in),  optional :: fileName\n    logical,                    intent(in),  optional :: overwrite\n    type(ESMF_FileStatus_Flag), intent(in),  optional :: status\n    integer,                    intent(in),  optional :: timeslice\n    type(ESMF_IOFmt_Flag),      intent(in),  optional :: iofmt\n    logical,                    intent(in),  optional :: relaxedflag\n    integer,                    intent(out), optional :: rc\n! !DESCRIPTION:\n!   Write the data in {\\tt grid} to {\\tt file} if supported by the\n!   {\\tt iofmt}.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[grid]\n!     The {\\tt ESMF\\_Grid} object whose data is to be written.\n!   \\item[{[nclScript]}]\n!     If {\\tt .true.} then NUOPC will write an NCL script that can be used to\n!     generate grid graphics. Default is {\\tt .false.}.\n!   \\item[{[mapPreset]}]\n!     Map preset to use when writting NCL script.\n!   \\item[fileName]\n!     The name of the file to write to. If not present then the file will\n!     be written to the grid's name.\n!   \\item[{[overwrite]}]\n!      A logical flag, the default is .false., i.e., existing Field data may\n!      {\\em not} be overwritten. If .true., the\n!      data corresponding to each field's name will be\n!      be overwritten. If the {\\tt timeslice} option is given, only data for\n!      the given timeslice may be overwritten.\n!      Note that it is always an error to attempt to overwrite a NetCDF\n!      variable with data which has a different shape.\n!   \\item[{[status]}]\n!      The file status. Valid options are {\\tt ESMF\\_FILESTATUS\\_NEW},\n!      {\\tt ESMF\\_FILESTATUS\\_OLD}, {\\tt ESMF\\_FILESTATUS\\_REPLACE}, and\n!      {\\tt ESMF\\_FILESTATUS\\_UNKNOWN} (default).\n!   \\item[{[timeslice]}]\n!     Time slice counter. Must be positive. The behavior of this\n!     option may depend on the setting of the {\\tt overwrite} flag:\n!     \\begin{description}\n!     \\item[{\\tt overwrite = .false.}:]\\ If the timeslice value is\n!     less than the maximum time already in the file, the write will fail.\n!     \\item[{\\tt overwrite = .true.}:]\\ Any positive timeslice value is valid.\n!     \\end{description}\n!     By default, i.e. by omitting the {\\tt timeslice} argument, no\n!     provisions for time slicing are made in the output file,\n!     however, if the file already contains a time axis for the variable,\n!     a timeslice one greater than the maximum will be written.\n!   \\item[{[iofmt]}]\n!    The IO format.  Valid options are  {\\tt ESMF\\_IOFMT\\_BIN} and\n!    {\\tt ESMF\\_IOFMT\\_NETCDF}. If not present, file names with a {\\tt .bin}\n!    extension will use {\\tt ESMF\\_IOFMT\\_BIN}, and file names with a {\\tt .nc}\n!    extension will use {\\tt ESMF\\_IOFMT\\_NETCDF}.  Other files default to\n!    {\\tt ESMF\\_IOFMT\\_NETCDF}.\n!   \\item[{[relaxedflag]}]\n!     If {\\tt .true.}, then no error is returned even if the call cannot write\n!     the file due to library limitations. Default is {\\tt .false.}.\n!   \\item[{[rc]}]\n!     Return code; equals {\\tt ESMF\\_SUCCESS} if there are no errors.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! no local variables\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    select case (trim(mapPreset))\n      case ('global','GLOBAL','Global')\n        call WRFHYDRO_ESMF_GridWrite(grid, fileName=fileName, overwrite=overwrite, &\n          timeslice=timeslice, iofmt=iofmt, relaxedflag=relaxedflag, &\n          nclScript=nclScript, map=WRFHYDRO_ESMF_MAPPRESET_GLOBAL, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('conus','CONUS','Conus')\n        call WRFHYDRO_ESMF_GridWrite(grid, fileName=fileName, overwrite=overwrite, &\n          timeslice=timeslice, iofmt=iofmt, relaxedflag=relaxedflag, &\n          nclScript=nclScript, map=WRFHYDRO_ESMF_MAPPRESET_CONUS, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('irene','IRENE','Irene')\n        call WRFHYDRO_ESMF_GridWrite(grid, fileName=fileName, overwrite=overwrite, &\n          timeslice=timeslice, iofmt=iofmt, relaxedflag=relaxedflag, &\n          nclScript=nclScript, map=WRFHYDRO_ESMF_MAPPRESET_IRENE, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('frontrange','FRONTRANGE','FrontRange')\n        call WRFHYDRO_ESMF_GridWrite(grid, fileName=fileName, overwrite=overwrite, &\n          timeslice=timeslice, iofmt=iofmt, relaxedflag=relaxedflag, &\n          nclScript=nclScript, map=WRFHYDRO_ESMF_MAPPRESET_FRONTRANGE, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case default\n        call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_VALUE,   &\n          msg=\"Unknown map preset value \"//trim(mapPreset)//\".\", &\n          CONTEXT, rcToReturn=rc)\n        return\n    endselect\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_GridWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_GridWrite - Write Grid data to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_GridWrite\n  subroutine WRFHYDRO_ESMF_GridWrite_default(grid, fileName, overwrite, status, &\n    timeslice, iofmt, relaxedflag, nclScript, map, rc)\n! ! ARGUMENTS\n    type(ESMF_Grid),            intent(in)            :: grid\n    character(len=*),           intent(in),  optional :: fileName\n    logical,                    intent(in),  optional :: overwrite\n    type(ESMF_FileStatus_Flag), intent(in),  optional :: status\n    integer,                    intent(in),  optional :: timeslice\n    type(ESMF_IOFmt_Flag),      intent(in),  optional :: iofmt\n    logical,                    intent(in),  optional :: relaxedflag\n    logical,                    intent(in),  optional :: nclScript\n    type(MapDesc),              intent(in),  optional :: map\n    integer,                    intent(out), optional :: rc\n! !DESCRIPTION:\n!   Write the data in {\\tt grid} to {\\tt file} if supported by the\n!   {\\tt iofmt}.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[field]\n!     The {\\tt ESMF\\_Field} object whose data is to be written.\n!   \\item[fileName]\n!     The name of the file to write to. If not present then the file will\n!     be written to the grid's name.\n!   \\item[{[overwrite]}]\n!      A logical flag, the default is .false., i.e., existing Field data may\n!      {\\em not} be overwritten. If .true., the\n!      data corresponding to each field's name will be\n!      be overwritten. If the {\\tt timeslice} option is given, only data for\n!      the given timeslice may be overwritten.\n!      Note that it is always an error to attempt to overwrite a NetCDF\n!      variable with data which has a different shape.\n!   \\item[{[status]}]\n!      The file status. Valid options are {\\tt ESMF\\_FILESTATUS\\_NEW},\n!      {\\tt ESMF\\_FILESTATUS\\_OLD}, {\\tt ESMF\\_FILESTATUS\\_REPLACE}, and\n!      {\\tt ESMF\\_FILESTATUS\\_UNKNOWN} (default).\n!   \\item[{[timeslice]}]\n!     Time slice counter. Must be positive. The behavior of this\n!     option may depend on the setting of the {\\tt overwrite} flag:\n!     \\begin{description}\n!     \\item[{\\tt overwrite = .false.}:]\\ If the timeslice value is\n!     less than the maximum time already in the file, the write will fail.\n!     \\item[{\\tt overwrite = .true.}:]\\ Any positive timeslice value is valid.\n!     \\end{description}\n!     By default, i.e. by omitting the {\\tt timeslice} argument, no\n!     provisions for time slicing are made in the output file,\n!     however, if the file already contains a time axis for the variable,\n!     a timeslice one greater than the maximum will be written.\n!   \\item[{[iofmt]}]\n!    The IO format.  Valid options are  {\\tt ESMF\\_IOFMT\\_BIN} and\n!    {\\tt ESMF\\_IOFMT\\_NETCDF}. If not present, file names with a {\\tt .bin}\n!    extension will use {\\tt ESMF\\_IOFMT\\_BIN}, and file names with a {\\tt .nc}\n!    extension will use {\\tt ESMF\\_IOFMT\\_NETCDF}.  Other files default to\n!    {\\tt ESMF\\_IOFMT\\_NETCDF}.\n!   \\item[{[relaxedflag]}]\n!     If {\\tt .true.}, then no error is returned even if the call cannot write\n!     the file due to library limitations. Default is {\\tt .false.}.\n!   \\item[{[nclScript]}]\n!     If {\\tt .true.} then NUOPC will write an NCL script that can be used to\n!     generate grid graphics. Default is {\\tt .false.}.\n!   \\item[{[map]}]\n!     Derived type including the map name and boundary coordinates.\n!   \\item[{[rc]}]\n!     Return code; equals {\\tt ESMF\\_SUCCESS} if there are no errors.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    logical                 :: ioCapable\n    logical                 :: doItFlag\n    character(len=64)       :: lfileName\n    character(len=64)       :: gridName\n    type(ESMF_Array)        :: array\n    type(ESMF_ArrayBundle)  :: arraybundle\n    logical                 :: isPresent\n    integer                 :: dimCount\n    integer                 :: dimIndex\n    integer,allocatable     :: coordDimCount(:)\n    integer                 :: coordDimMax\n    integer                 :: stat\n    logical                 :: lnclScript\n    logical                 :: hasCorners\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    ioCapable = (ESMF_IO_PIO_PRESENT .and. &\n      (ESMF_IO_NETCDF_PRESENT .or. ESMF_IO_PNETCDF_PRESENT))\n\n    doItFlag = .true. ! default\n    if (present(relaxedFlag)) then\n      doItFlag = .not.relaxedflag .or. (relaxedflag.and.ioCapable)\n    endif\n\n    if (doItFlag) then\n\n      if (present(fileName)) then\n        lfileName = trim(fileName)\n      else\n        call ESMF_GridGet(grid, name=gridName, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        lfileName = trim(gridName)//\".nc\"\n      endif\n\n      arraybundle = ESMF_ArrayBundleCreate(rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n      ! -- centers --\n\n      call ESMF_GridGetCoord(grid, staggerLoc=ESMF_STAGGERLOC_CENTER, &\n        isPresent=isPresent, rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      if (isPresent) then\n        call ESMF_GridGetCoord(grid, coordDim=1, &\n          staggerLoc=ESMF_STAGGERLOC_CENTER, array=array, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_ArraySet(array, name=\"lon_center\", rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_ArrayBundleAdd(arraybundle,(/array/),rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_GridGetCoord(grid, coordDim=2, &\n          staggerLoc=ESMF_STAGGERLOC_CENTER, array=array, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_ArraySet(array, name=\"lat_center\", rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_ArrayBundleAdd(arraybundle,(/array/),rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      endif\n\n      ! -- corners --\n\n      call ESMF_GridGetCoord(grid, staggerLoc=ESMF_STAGGERLOC_CORNER, &\n        isPresent=hasCorners, rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      if (hasCorners) then\n        call ESMF_GridGetCoord(grid, coordDim=1, &\n          staggerLoc=ESMF_STAGGERLOC_CORNER, array=array, rc=rc)\n        if (.not. ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) then\n          call ESMF_ArraySet(array, name=\"lon_corner\", rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n          call ESMF_ArrayBundleAdd(arraybundle,(/array/),rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        endif\n        call ESMF_GridGetCoord(grid, coordDim=2, &\n          staggerLoc=ESMF_STAGGERLOC_CORNER, array=array, rc=rc)\n        if (.not. ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) then\n          call ESMF_ArraySet(array, name=\"lat_corner\", rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n          call ESMF_ArrayBundleAdd(arraybundle,(/array/),rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        endif\n      endif\n\n      ! -- mask --\n\n      call ESMF_GridGetItem(grid, itemflag=ESMF_GRIDITEM_MASK, &\n        staggerLoc=ESMF_STAGGERLOC_CENTER, isPresent=isPresent, rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      if (isPresent) then\n        call ESMF_GridGetItem(grid, staggerLoc=ESMF_STAGGERLOC_CENTER, &\n          itemflag=ESMF_GRIDITEM_MASK, array=array, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_ArraySet(array, name=\"mask\", rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_ArrayBundleAdd(arraybundle,(/array/),rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      endif\n\n      ! -- area --\n\n      call ESMF_GridGetItem(grid, itemflag=ESMF_GRIDITEM_AREA, &\n        staggerLoc=ESMF_STAGGERLOC_CENTER, isPresent=isPresent, rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      if (isPresent) then\n        call ESMF_GridGetItem(grid, staggerLoc=ESMF_STAGGERLOC_CENTER, &\n          itemflag=ESMF_GRIDITEM_AREA, array=array, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_ArraySet(array, name=\"area\", rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call ESMF_ArrayBundleAdd(arraybundle,(/array/),rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      endif\n\n      call ESMF_ArrayBundleWrite(arraybundle, &\n        fileName=trim(lfileName),rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n      call ESMF_ArrayBundleDestroy(arraybundle,rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n      if (present(nclScript)) then\n        lnclScript = nclScript\n      else\n        lnclScript = .FALSE.\n      endif\n\n      if (lnclScript) then\n        call ESMF_GridGet(grid,dimCount=dimCount,rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n        ! allocate coordDim info accord. to dimCount and tileCount\n        allocate(coordDimCount(dimCount), stat=stat)\n        if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n          msg=\"Allocation of coordinate dimensions memory failed.\", &\n          CONTEXT, rcToReturn=rc)) return  ! bail out\n\n        ! get coordDim info\n        call ESMF_GridGet(grid, coordDimCount=coordDimCount, &\n          rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n        coordDimMax = 0\n        do dimIndex=1,dimCount\n          coordDimMax = MAX(coordDimMax,coordDimCount(dimIndex))\n        enddo\n\n        ! deallocate coordDim info accord. to dimCount and tileCount\n        deallocate(coordDimCount, stat=stat)\n        if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n          msg=\"Deallocation of coordinate dimensions memory failed.\", &\n          CONTEXT, rcToReturn=rc)) return  ! bail out\n\n        if (coordDimMax == 1) then\n          call WRFHYDRO_ESMF_NclScriptWrite(gridFile=lfileName, map=map, &\n            uniformRect=.TRUE., writeCorners=hasCorners, rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        else\n          call WRFHYDRO_ESMF_NclScriptWrite(gridFile=lfileName, map=map, &\n            writeCorners=hasCorners, rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        endif\n      endif\n    endif\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NclScriptWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NclScriptWrite_coords - Write NCL Script to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NclScriptWrite\n  subroutine WRFHYDRO_ESMF_NclScriptWrite_coords(gridFile,mapName,minCoords,maxCoords, &\n  title,nclFile,uniformRect,writeCorners,rc)\n! ! ARGUMENTS\n    character(len=*),intent(in)          :: gridFile\n    character(len=*),intent(in)          :: mapName\n    real,intent(in)                      :: minCoords(2)\n    real,intent(in)                      :: maxCoords(2)\n    character(len=*),intent(in),optional :: title\n    character(len=*),intent(in),optional :: nclFile\n    logical,intent(in),optional          :: uniformRect\n    logical,intent(in),optional          :: writeCorners\n    integer,intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Write NCL script that can be used to generate NCL grid visual.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[gridFile]\n!     NetCDF grid file name used plot data on coordinates.\n!   \\item[mapName]\n!     Map name.\n!   \\item[minCoords]\n!     Minimum coordinate limits for plot.\n!   \\item[maxCoords]\n!     Maximum coordinate limits for plot.\n!   \\item[title]\n!     Grid plot title.\n!   \\item[nclFile]\n!     NCL script file name\n!   \\item[uniformRect]\n!     Repeat coordinates for uniform rectangular grids.\n!   \\item[writeCorners]\n!     Plot corners.  Default plot center coordinates.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    type(MapDesc)  :: map\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    map = MapDesc(trim(mapName),.FALSE., &\n      minCoords(2),maxCoords(2),minCoords(1),maxCoords(1))\n\n    call WRFHYDRO_ESMF_NclScriptWrite(gridFile, map=map, title=title, &\n      nclFile=nclFile, uniformRect=uniformRect, writeCorners=writeCorners, &\n      rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NclScriptWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NclScriptWrite_preset - Write NCL Script to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NclScriptWrite\n  subroutine WRFHYDRO_ESMF_NclScriptWrite_preset(gridFile,mapPreset, &\n  title,nclFile,uniformRect,writeCorners,rc)\n! ! ARGUMENTS\n    character(len=*),intent(in)          :: gridFile\n    character(len=*),intent(in)          :: mapPreset\n    character(len=*),intent(in),optional :: title\n    character(len=*),intent(in),optional :: nclFile\n    logical,intent(in),optional          :: uniformRect\n    logical,intent(in),optional          :: writeCorners\n    integer,intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Write NCL script that can be used to generate NCL grid visual.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[gridFile]\n!     NetCDF grid file name used plot data on coordinates.\n!   \\item[mapPreset]\n!     Preset coordinate limits.\n!   \\item[title]\n!     Grid plot title.\n!   \\item[nclFile]\n!     NCL script file name\n!   \\item[uniformRect]\n!     Repeat coordinates for uniform rectangular grids.\n!   \\item[writeCorners]\n!     Plot corners.  Default plot center coordinates.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    select case (trim(mapPreset))\n      case ('global','GLOBAL','Global')\n        call WRFHYDRO_ESMF_NclScriptWrite(gridFile, &\n          map=WRFHYDRO_ESMF_MAPPRESET_GLOBAL, title=title, nclFile=nclFile, &\n          uniformRect=uniformRect, writeCorners=writeCorners, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('conus','CONUS','Conus')\n        call WRFHYDRO_ESMF_NclScriptWrite(gridFile, &\n          map=WRFHYDRO_ESMF_MAPPRESET_CONUS, title=title, nclFile=nclFile, &\n          uniformRect=uniformRect, writeCorners=writeCorners, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('irene','IRENE','Irene')\n        call WRFHYDRO_ESMF_NclScriptWrite(gridFile, &\n          map=WRFHYDRO_ESMF_MAPPRESET_IRENE, title=title, nclFile=nclFile, &\n          uniformRect=uniformRect, writeCorners=writeCorners, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('frontrange','FRONTRANGE','FrontRange')\n        call WRFHYDRO_ESMF_NclScriptWrite(gridFile, &\n          map=WRFHYDRO_ESMF_MAPPRESET_FRONTRANGE, title=title, nclFile=nclFile, &\n          uniformRect=uniformRect, writeCorners=writeCorners, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case default\n        call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_VALUE,   &\n          msg=\"Unknown map preset value \"//trim(mapPreset)//\".\", &\n          CONTEXT, rcToReturn=rc)\n        return\n    endselect\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NclScriptWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NclScriptWrite_default - Write NCL Script to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NclScriptWrite\n  subroutine WRFHYDRO_ESMF_NclScriptWrite_default(gridFile, map, title, &\n    nclFile, uniformRect, writeCorners, rc)\n! ! ARGUMENTS\n    character(len=*),intent(in)          :: gridFile\n    type(MapDesc),intent(in)             :: map\n    character(len=*),intent(in),optional :: title\n    character(len=*),intent(in),optional :: nclFile\n    logical,intent(in),optional          :: uniformRect\n    logical,intent(in),optional          :: writeCorners\n    integer,intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Write NCL script that can be used to generate NCL grid visual.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[gridFile]\n!     NetCDF grid file name used plot data on coordinates.\n!   \\item[map]\n!     Coordinate limits.\n!   \\item[title]\n!     Grid plot title.\n!   \\item[nclFile]\n!     NCL script file name\n!   \\item[uniformRect]\n!     Repeat coordinates for uniform rectangular grids.\n!   \\item[writeCorners]\n!     Plot corners.  Default plot center coordinates.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    type(ESMF_VM)                   :: vm\n    integer                         :: lpe\n    character(len=64)               :: ltitle\n    character(len=64)               :: lnclFile\n    character(len=64)               :: fileBase\n    logical                         :: luniformRect\n    logical                         :: lcorners\n    integer                         :: markExt\n    integer                         :: fUnit\n    integer                         :: stat\n    character(len=10)               :: varlat\n    character(len=10)               :: varlon\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    ! Get current VM and pet number\n    call ESMF_VMGetCurrent(vm, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    call ESMF_VMGet(vm, localPet=lpe, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    if (lpe /= 0) return\n\n    markExt = index(gridFile,\".\",back=.TRUE.)\n    if (markExt > 1) then\n      fileBase = gridFile(1:markExt-1)\n    elseif (markExt == 1) then\n      fileBase = \"grid\"\n    elseif (len(trim(gridFile)) > 0) then\n      fileBase = trim(gridFile)\n    else\n      fileBase = \"grid\"\n    endif\n\n    if (present(nclFile)) then\n      lnclFile = trim(nclFile)\n    else\n      lnclFile = trim(fileBase)//\".ncl\"\n    endif\n\n    if (present(title)) then\n      ltitle = trim(title)\n    else\n      ltitle = trim(fileBase)//\" \"//trim(map%name)\n    endif\n\n    if (present(uniformRect)) then\n      luniformRect = uniformRect\n    else\n      luniformRect = .FALSE.\n    endif\n\n    if (present(writeCorners)) then\n      lcorners = writeCorners\n    else\n      lcorners = .FALSE.\n    endif\n\n    if (lcorners) then\n      varlat = 'lat_corner'\n      varlon = 'lon_corner'\n    else\n      varlat = 'lat_center'\n      varlon = 'lon_center'\n    endif\n\n    call ESMF_UtilIOUnitGet(fUnit, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n    open (fUnit,file=trim(lnclFile),action=\"write\", &\n      status=\"new\",iostat=stat)\n    if (stat /= 0) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_OPEN,   &\n        msg=\"Cound not open \"//trim(lnclFile)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    write (fUnit,\"(A)\") '; NUOPC_FileWriteMapNCL used to generate this file'\n    write (fUnit,\"(A)\") '; execute ncl <this file> to generate grid png file'\n    write (fUnit,\"(A)\") 'begin'\n    write (fUnit,\"(A)\") '  in = addfile(\"'//trim(gridFile)//'\",\"r\")'\n    write (fUnit,\"(A)\") '  wks = gsn_open_wks(\"png\",\"'//trim(fileBase)//'\")'\n    write (fUnit,\"(A)\") '  res              = True'\n    write (fUnit,\"(A)\") '  res@gsnMaximize  = True'\n    write (fUnit,\"(A)\") '  res@gsnDraw      = False'\n    write (fUnit,\"(A)\") '  res@gsnFrame     = False'\n    write (fUnit,\"(A)\") '  res@tiMainString = \"'//trim(ltitle)//'\"'\n    write (fUnit,\"(A)\") '  res@pmTickMarkDisplayMode = \"Always\"'\n    write (fUnit,\"(A)\") '; '//trim(map%name)//' Map Grid'\n    if (.NOT. map%global) then\n      write (fUnit,\"(A,F0.3)\") &\n        '  res@mpMinLatF    = ',map%minLat\n      write (fUnit,\"(A,F0.3)\") &\n        '  res@mpMaxLatF    = ',map%maxLat\n      write (fUnit,\"(A,F0.3)\") &\n        '  res@mpMinLonF    = ',map%minLon\n      write (fUnit,\"(A,F0.3)\") &\n        '  res@mpMaxLonF    = ',map%maxLon\n    endif\n    write (fUnit,\"(A)\") '  map = gsn_csm_map_ce(wks,res)'\n    write (fUnit,\"(A)\") '  hgt = in->lon_center(:,:)'\n    write (fUnit,\"(A)\") '  dimlon = getfilevardimsizes(in,\"'//trim(varlon)//'\")'\n    write (fUnit,\"(A)\") '  dimlat = getfilevardimsizes(in,\"'//trim(varlat)//'\")'\n    if (luniformRect) then\n      write (fUnit,\"(A)\") '  hgt@lat2d = conform_dims((/dimlon(0),dimlat(1)/),'// &\n        'in->'//trim(varlat)//'(:,0),1)'\n      write (fUnit,\"(A)\") '  hgt@lon2d = conform_dims((/dimlon(0),dimlat(1)/),'// &\n        'in->'//trim(varlon)//'(0,:),0)'\n    else\n      write (fUnit,\"(A)\") '  hgt@lat2d = in->'//trim(varlat)//'(:,:)'\n      write (fUnit,\"(A)\") '  hgt@lon2d = in->'//trim(varlon)//'(:,:)'\n    endif\n    write (fUnit,\"(A)\") '  pres                   = True'\n    if (lcorners) then\n      write (fUnit,\"(A)\") '  pres@gsnCoordsAsLines  = True'\n    else\n      write (fUnit,\"(A)\") '  pres@gsnCoordsAsLines  = False'\n      write (fUnit,\"(A)\") '  if (dimlon(0)*dimlat(1) .gt. 99) then'\n      write (fUnit,\"(A)\") '    pres@gsMarkerIndex = 1'\n      write (fUnit,\"(A)\") '  end if'\n    endif\n    write (fUnit,\"(A)\") '  gsn_coordinates(wks,map,hgt,pres)'\n    write (fUnit,\"(A)\") 'end'\n\n    close (fUnit,iostat=stat)\n    if (stat /= 0) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_CLOSE,   &\n        msg=\"Cound not close \"//trim(lnclFile)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_FerretScriptWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_FerretScriptWrite_coords - Write Ferret Script to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_FerretScriptWrite\n  subroutine WRFHYDRO_ESMF_FerretScriptWrite_coords(varName, dataFile, &\n    gridFile, slices, mapName, minCoords, maxCoords, scale, jnlFile, &\n    uniformRect,rc)\n! ! ARGUMENTS\n    character(len=*),intent(in)          :: varName\n    character(len=*),intent(in)          :: dataFile\n    character(len=*),intent(in)          :: gridFile\n    integer,intent(in)                   :: slices(:)\n    character(len=*),intent(in)          :: mapName\n    real,intent(in)                      :: minCoords(2)\n    real,intent(in)                      :: maxCoords(2)\n    real,intent(in),optional             :: scale(3)\n    character(len=*),intent(in),optional :: jnlFile\n    logical,intent(in),optional          :: uniformRect\n    integer,intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Write Ferret script that can be used to generate Ferret field visual.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[varName]\n!     NetCDF variable name in dataFile.\n!   \\item[dataFile]\n!     NetCDF field data file name.\n!   \\item[gridFile]\n!     NetCDF grid file name used plot data on coordinates.\n!   \\item[slices]\n!     Array of slice numbers to for which to create plots.\n!   \\item[mapName]\n!     Map name used to create map description.\n!   \\item[minCoords]\n!     Minimum coordinates used to plot data.\n!   \\item[maxCoords]\n!     Maximum coordinates used to plot data.\n!   \\item[scale]\n!     Field data scale (/ minimum value, maximum value, step size /)\n!   \\item[jnlFile]\n!     Output script filename.\n!   \\item[uniformRect]\n!     Repeat coordinates for uniform rectangular grids.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    type(MapDesc)  :: map\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    map = MapDesc(trim(mapName),.FALSE., &\n      minCoords(2),maxCoords(2),minCoords(1),maxCoords(1))\n\n    call WRFHYDRO_ESMF_FerretScriptWrite(varName,dataFile,gridFile,slices, &\n      map=map,scale=scale,jnlFile=jnlFile, uniformRect=uniformRect,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_FerretScriptWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_FerretScriptWrite_preset - Write Ferret Script to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_FerretScriptWrite\n  subroutine WRFHYDRO_ESMF_FerretScriptWrite_preset(varName, dataFile, &\n    gridFile, slices, mapPreset, scale, jnlFile, &\n    uniformRect,rc)\n! ! ARGUMENTS\n    character(len=*),intent(in)          :: varName\n    character(len=*),intent(in)          :: dataFile\n    character(len=*),intent(in)          :: gridFile\n    integer,intent(in)                   :: slices(:)\n    character(len=*),intent(in)          :: mapPreset\n    real,intent(in),optional             :: scale(3)\n    character(len=*),intent(in),optional :: jnlFile\n    logical,intent(in),optional          :: uniformRect\n    integer,intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Write Ferret script that can be used to generate Ferret field visual.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[varName]\n!     NetCDF variable name in dataFile.\n!   \\item[dataFile]\n!     NetCDF field data file name.\n!   \\item[gridFile]\n!     NetCDF grid file name used plot data on coordinates.\n!   \\item[slices]\n!     Array of slice numbers to for which to create plots.\n!   \\item[mapPreset]\n!     Map preset to use to define coordinate limits.\n!   \\item[scale]\n!     Field data scale (/ minimum value, maximum value, step size /)\n!   \\item[jnlFile]\n!     Output script filename.\n!   \\item[uniformRect]\n!     Repeat coordinates for uniform rectangular grids.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    select case (trim(mapPreset))\n      case ('global','GLOBAL','Global')\n        call WRFHYDRO_ESMF_FerretScriptWrite(varName, dataFile, gridFile, slices, &\n          map=WRFHYDRO_ESMF_MAPPRESET_GLOBAL, scale=scale, jnlFile=jnlFile, &\n          uniformRect=uniformRect, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('conus','CONUS','Conus')\n        call WRFHYDRO_ESMF_FerretScriptWrite(varName, dataFile, gridFile, slices, &\n          map=WRFHYDRO_ESMF_MAPPRESET_CONUS, scale=scale, jnlFile=jnlFile, &\n          uniformRect=uniformRect, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('irene','IRENE','Irene')\n        call WRFHYDRO_ESMF_FerretScriptWrite(varName, dataFile, gridFile, slices, &\n          map=WRFHYDRO_ESMF_MAPPRESET_IRENE, scale=scale, jnlFile=jnlFile, &\n          uniformRect=uniformRect, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case ('frontrange','FRONTRANGE','FrontRange')\n        call WRFHYDRO_ESMF_FerretScriptWrite(varName, dataFile, gridFile, slices, &\n          map=WRFHYDRO_ESMF_MAPPRESET_FRONTRANGE, scale=scale, jnlFile=jnlFile, &\n          uniformRect=uniformRect, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      case default\n        call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_VALUE,   &\n          msg=\"Unknown map preset value \"//trim(mapPreset)//\".\", &\n          CONTEXT, rcToReturn=rc)\n        return\n    endselect\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_FerretScriptWrite\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_FerretScriptWrite_default - Write Ferret Script to file\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_FerretScriptWrite\n  subroutine WRFHYDRO_ESMF_FerretScriptWrite_default(varName, dataFile, gridFile, &\n    slices, map, scale, jnlFile, uniformRect, rc)\n! ! ARGUMENTS\n    character(len=*),intent(in)          :: varName\n    character(len=*),intent(in)          :: dataFile\n    character(len=*),intent(in)          :: gridFile\n    integer,intent(in)                   :: slices(:)\n    type(MapDesc),intent(in)             :: map\n    real,intent(in),optional             :: scale(3)\n    character(len=*),intent(in),optional :: jnlFile\n    logical,intent(in),optional          :: uniformRect\n    integer,intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Write Ferret script that can be used to generate Ferret field visual.\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\item[varName]\n!     NetCDF variable name in dataFile.\n!   \\item[dataFile]\n!     NetCDF field data file name.\n!   \\item[gridFile]\n!     NetCDF grid file name used plot data on coordinates.\n!   \\item[slices]\n!     Array of slice numbers to for which to create plots.\n!   \\item[map]\n!     Coordinate limits.\n!   \\item[scale]\n!     Field data scale (/ minimum value, maximum value, step size /)\n!   \\item[jnlFile]\n!     Output script filename.\n!   \\item[uniformRect]\n!     Repeat coordinates for uniform rectangular grids.\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    type(ESMF_VM)                   :: vm\n    integer                         :: lpe\n    character(len=64)               :: ljnlFile\n    logical                         :: luniformRect\n    character(len=64)               :: fileBase\n    character(len=64)               :: limits\n    character(len=64)               :: levels\n    character(len=64)               :: latlon\n    integer                         :: markExt\n    integer                         :: sIndex\n    integer                         :: fUnit\n    integer                         :: stat\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    ! Get current VM and pet number\n    call ESMF_VMGetCurrent(vm, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    call ESMF_VMGet(vm, localPet=lpe, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    if (lpe /= 0) return\n\n    markExt = index(dataFile,\".\",back=.TRUE.)\n    if (markExt > 1) then\n      fileBase = dataFile(1:markExt-1)\n    elseif (markExt == 1) then\n      fileBase = \"data\"\n    elseif (len(trim(dataFile)) > 0) then\n      fileBase = trim(dataFile)\n    else\n      fileBase = \"data\"\n    endif\n\n    if (present(jnlFile)) then\n      ljnlFile = trim(jnlFile)\n    else\n      ljnlFile = trim(fileBase)//\".jnl\"\n    endif\n\n    if (present(uniformRect)) then\n      luniformRect = uniformRect\n    else\n      luniformRect = .FALSE.\n    endif\n\n    if (map%global) then\n      limits = ''\n    else\n      write (limits,\"(2(A,F0.3,A,F0.3))\") &\n        '/vlimits=',map%minLat,':',map%maxLat, &\n        '/hlimits=',map%minLon,':',map%maxLon\n    endif\n\n    if (luniformRect) then\n      latlon = ',lon_center[d=2,j=1:1],lat_center[d=2,i=1:1]'\n    else\n      latlon = ',lon_center[d=2],lat_center[d=2]'\n    endif\n\n    if (present(scale)) then\n      write (levels,\"(A,F0.3,A,F0.3,A,F0.3,A)\") &\n        '/levels=(',scale(1),',',scale(2),',',scale(3),')'\n    else\n      levels = ''\n    endif\n\n    call ESMF_UtilIOUnitGet(fUnit, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n    open (fUnit,file=trim(ljnlFile),action=\"write\", &\n      status=\"new\",iostat=stat)\n    if (stat /= 0) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_OPEN,   &\n        msg=\"Cound not open \"//trim(ljnlFile)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    write (fUnit,\"(A)\") ' ! NUOPC_FileWriteJNL used to generate this file'\n    write (fUnit,\"(A)\") ' ! execute ferret -script <this file> to '\n    write (fUnit,\"(A)\") ' ! generate data gif file for each slice listed'\n    write (fUnit,\"(A)\") ''\n    write (fUnit,\"(A,A)\") 'use ',trim(dataFile)\n    write (fUnit,\"(A,A)\") 'use ',trim(gridFile)\n    write (fUnit,\"(A,A)\") ''\n\n    do sIndex=1,size(slices)\n      write (fUnit,\"((A,I0),A,A,(A,A,A),A)\") &\n        'shade/k=',slices(sIndex), &\n        trim(limits), &\n        trim(levels), &\n        ' ',trim(varName),'[d=1]', &\n        trim(latlon)\n      write (fUnit,\"(A,(A,A,I0,A))\") 'FRAME/FILE=', &\n        trim(fileBase),'_',slices(sIndex),'.gif'\n      write (fUnit,\"(A)\") ''\n    enddo\n\n    write (fUnit,\"(A)\") 'exit'\n\n    close (fUnit,iostat=stat)\n    if (stat /= 0) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_CLOSE,   &\n        msg=\"Cound not close \"//trim(ljnlFile)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NetcdfIsPresent\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NetcdfIsPresent - Check NetCDF file for varname\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NetcdfIsPresent\n  function WRFHYDRO_ESMF_NetcdfIsPresent(varname,filename,rc)\n! ! RETURN VALUE\n    logical :: WRFHYDRO_ESMF_NetcdfIsPresent\n! ! ARGUMENTS\n    character(len=*), intent(in)          :: varname\n    character(len=*), intent(in)          :: filename\n    integer, intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Check NetCDF file for varname\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    integer                               :: stat\n    integer                               :: varid\n    integer                               :: ncid\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    stat = nf90_open(filename,nf90_NoWrite,ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_OPEN,   &\n        msg=\"Error opening NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inq_varid(ncid,varname,varid)\n    if(stat == nf90_NoErr) then\n      WRFHYDRO_ESMF_NetcdfIsPresent = .TRUE.\n    elseif(stat == nf90_eNotVar) then\n      WRFHYDRO_ESMF_NetcdfIsPresent = .FALSE.\n    else\n      WRFHYDRO_ESMF_NetcdfIsPresent = .FALSE.\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_close(ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_CLOSE,   &\n        msg=\"Error closing NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n  end function\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NetcdfReadIXJX_Field\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NetcdfReadIXJX_Field - Read NetCDF var into ESMF field\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NetcdfReadIXJX\n  subroutine WRFHYDRO_ESMF_NetcdfReadIXJX_Field(varname,filename,start,field,rc)\n! ! ARGUMENTS\n    character(len=*), intent(in)          :: varname\n    character(len=*), intent(in)          :: filename\n    integer,intent(in)                    :: start(2)\n    type(ESMF_Field),intent(inout)        :: field\n    integer, intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Read NetCDF variable into ESMF field\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    type(ESMF_Array)                      :: array\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    call ESMF_FieldGet(field,array=array,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    call WRFHYDRO_ESMF_NetcdfReadIXJX(varname,filename,start,array=array,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NetcdfReadIXJX_Array\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NetcdfReadIXJX_Array - Read NetCDF var into ESMF array\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NetcdfReadIXJX\n  subroutine WRFHYDRO_ESMF_NetcdfReadIXJX_Array(varname,filename,start,array,rc)\n! ! ARGUMENTS\n    character(len=*), intent(in)          :: varname\n    character(len=*), intent(in)          :: filename\n    integer,intent(in)                    :: start(2)\n    type(ESMF_Array),intent(inout)        :: array\n    integer, intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Read NetCDF var into ESMF array\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    integer(ESMF_KIND_I4),pointer :: farray_I42D(:,:)\n    integer(ESMF_KIND_I8),pointer :: farray_I82D(:,:)\n    real(ESMF_KIND_R4),pointer    :: farray_R42D(:,:)\n    real(ESMF_KIND_R8),pointer    :: farray_R82D(:,:)\n    type(ESMF_TypeKind_Flag)      :: typekind\n    integer                       :: rank\n    integer                       :: localDeCount\n    integer                       :: deIndex\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    call ESMF_ArrayGet(array,typekind=typekind,rank=rank,localDeCount=localDeCount,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    if (rank == 2) then\n      if (typekind == ESMF_TYPEKIND_I4) then\n        do deIndex=0,localDeCount-1\n          call ESMF_ArrayGet(array,farrayPtr=farray_I42D,localDe=deIndex,rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n          call WRFHYDRO_ESMF_NetcdfReadIXJX(varname,filename,start,farray=farray_I42D, rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        enddo\n      elseif (typekind == ESMF_TYPEKIND_I8) then\n        do deIndex=0,localDeCount-1\n          call ESMF_ArrayGet(array,farrayPtr=farray_I82D,localDe=deIndex,rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n          call WRFHYDRO_ESMF_NetcdfReadIXJX(varname,filename,start,farray=farray_I82D, rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        enddo\n      elseif (typekind == ESMF_TYPEKIND_R4) then\n        do deIndex=0,localDeCount-1\n          call ESMF_ArrayGet(array,farrayPtr=farray_R42D,localDe=deIndex,rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n          call WRFHYDRO_ESMF_NetcdfReadIXJX(varname,filename,start,farray=farray_R42D, rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        enddo\n      elseif (typekind == ESMF_TYPEKIND_R8) then\n        do deIndex=0,localDeCount-1\n          call ESMF_ArrayGet(array,farrayPtr=farray_R82D,localDe=deIndex,rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n          call WRFHYDRO_ESMF_NetcdfReadIXJX(varname,filename,start,farray=farray_R82D, rc=rc)\n          if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        enddo\n      else\n        call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_RANK,   &\n          msg=\"Cannot read NetCDF because typekind is not supported\", &\n          CONTEXT, rcToReturn=rc)\n        return\n      endif\n    else\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_RANK,   &\n        msg=\"Cannot read NetCDF because rank is not supported\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NetcdfReadIXJX_I4\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NetcdfReadIXJX_I4 - Read NetCDF variable into I4 array\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NetcdfReadIXJX\n  subroutine WRFHYDRO_ESMF_NetcdfReadIXJX_I4(varname,filename,start,farray,rc)\n! ! ARGUMENTS\n    character(len=*), intent(in)          :: varname\n    character(len=*), intent(in)          :: filename\n    integer,intent(in)                    :: start(2)\n    integer(ESMF_KIND_I4),intent(inout)   :: farray(:,:)\n    integer, intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Read NetCDF variable into I4 array\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    integer                               :: stat\n    integer                               :: varid\n    integer, dimension(nf90_max_var_dims) :: dimIDs\n    integer                               :: dimCnt(2)\n    integer                               :: ncid\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    stat = nf90_open(filename,nf90_NoWrite,ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_OPEN,   &\n        msg=\"Error opening NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inq_varid(ncid,varname,varid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    ! How big is the netCDF variable, that is, what are the lengths of\n    !   its constituent dimensions?\n    stat = nf90_inquire_variable(ncid, varid, dimids = dimIDs)\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error locating variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inquire_dimension(ncid, dimIDs(1), len = dimCnt(1))\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable dim1 \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inquire_dimension(ncid, dimIDs(2), len = dimCnt(2))\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable dim2 \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    if ((start(1)+size(farray,1)-1 > dimCnt(1)) .OR. &\n    (start(2)+size(farray,2)-1 > dimCnt(2))) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_SIZE,   &\n        msg=\"Error FORTRAN array size mismatch \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_get_var(ncid, varid, values=farray, start=(/start(1),start(2)/), &\n      count=(/size(farray,1),size(farray,2)/))\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable values \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_close(ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_CLOSE,   &\n        msg=\"Error closing NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NetcdfReadIXJX_I8\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NetcdfReadIXJX_I8 - Read NetCDF variable into I8 array\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NetcdfReadIXJX\n  subroutine WRFHYDRO_ESMF_NetcdfReadIXJX_I8(varname,filename,start,farray,rc)\n! ! ARGUMENTS\n    character(len=*), intent(in)          :: varname\n    character(len=*), intent(in)          :: filename\n    integer,intent(in)                    :: start(2)\n    integer(ESMF_KIND_I8),intent(inout)   :: farray(:,:)\n    integer, intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Read NetCDF variable into I8 array\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    integer                               :: stat\n    integer                               :: varid\n    integer, dimension(nf90_max_var_dims) :: dimIDs\n    integer                               :: dimCnt(2)\n    integer                               :: ncid\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    stat = nf90_open(filename,nf90_NoWrite,ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_OPEN,   &\n        msg=\"Error opening NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inq_varid(ncid,varname,varid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    ! How big is the netCDF variable, that is, what are the lengths of\n    !   its constituent dimensions?\n    stat = nf90_inquire_variable(ncid, varid, dimids = dimIDs)\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error loacating variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inquire_dimension(ncid, dimIDs(1), len = dimCnt(1))\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable dim1 \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inquire_dimension(ncid, dimIDs(2), len = dimCnt(2))\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable dim2 \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    if ((start(1)+size(farray,1)-1 > dimCnt(1)) .OR. &\n    (start(2)+size(farray,2)-1 > dimCnt(2))) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_SIZE,   &\n        msg=\"Error FORTRAN array size mismatch \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_get_var(ncid, varid, values=farray, start=(/start(1),start(2)/), &\n      count=(/size(farray,1),size(farray,2)/))\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable values \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_close(ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_CLOSE,   &\n        msg=\"Error closing NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NetcdfReadIXJX_R4\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NetcdfReadIXJX_R4 - Read NetCDF variable into R4 array\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NetcdfReadIXJX\n  subroutine WRFHYDRO_ESMF_NetcdfReadIXJX_R4(varname,filename,start,farray,rc)\n! ! ARGUMENTS\n    character(len=*), intent(in)          :: varname\n    character(len=*), intent(in)          :: filename\n    integer,intent(in)                    :: start(2)\n    real(ESMF_KIND_R4),intent(inout)      :: farray(:,:)\n    integer, intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Read NetCDF variable into R4 array\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    integer                               :: stat\n    integer                               :: varid\n    integer, dimension(nf90_max_var_dims) :: dimIDs\n    integer                               :: dimCnt(2)\n    integer                               :: ncid\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    stat = nf90_open(filename,nf90_NoWrite,ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_OPEN,   &\n        msg=\"Error opening NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inq_varid(ncid,varname,varid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    ! How big is the netCDF variable, that is, what are the lengths of\n    !   its constituent dimensions?\n    stat = nf90_inquire_variable(ncid, varid, dimids = dimIDs)\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error loacating variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inquire_dimension(ncid, dimIDs(1), len = dimCnt(1))\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable dim1 \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inquire_dimension(ncid, dimIDs(2), len = dimCnt(2))\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable dim2 \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    if ((start(1)+size(farray,1)-1 > dimCnt(1)) .OR. &\n    (start(2)+size(farray,2)-1 > dimCnt(2))) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_SIZE,   &\n        msg=\"Error FORTRAN array size mismatch \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_get_var(ncid, varid, values=farray, start=(/start(1),start(2)/), &\n      count=(/size(farray,1),size(farray,2)/))\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable values \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_close(ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_CLOSE,   &\n        msg=\"Error closing NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_NetcdfReadIXJX_R8\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_NetcdfReadIXJX_R8 - Read NetCDF variable into R8 array\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_NetcdfReadIXJX\n  subroutine WRFHYDRO_ESMF_NetcdfReadIXJX_R8(varname,filename,start,farray,rc)\n! ! ARGUMENTS\n    character(len=*), intent(in)          :: varname\n    character(len=*), intent(in)          :: filename\n    integer,intent(in)                    :: start(2)\n    real(ESMF_KIND_R8),intent(inout)      :: farray(:,:)\n    integer, intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Read NetCDF variable into R8 array\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    integer                               :: stat\n    integer                               :: varid\n    integer, dimension(nf90_max_var_dims) :: dimIDs\n    integer                               :: dimCnt(2)\n    integer                               :: ncid\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    stat = nf90_open(filename,nf90_NoWrite,ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_OPEN,   &\n        msg=\"Error opening NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inq_varid(ncid,varname,varid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    ! How big is the netCDF variable, that is, what are the lengths of\n    !   its constituent dimensions?\n    stat = nf90_inquire_variable(ncid, varid, dimids = dimIDs)\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error loacating variable \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inquire_dimension(ncid, dimIDs(1), len = dimCnt(1))\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable dim1 \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_inquire_dimension(ncid, dimIDs(2), len = dimCnt(2))\n    if(stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable dim2 \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    if ((start(1)+size(farray,1)-1 > dimCnt(1)) .OR. &\n    (start(2)+size(farray,2)-1 > dimCnt(2))) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_SIZE,   &\n        msg=\"Error FORTRAN array size mismatch \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_get_var(ncid, varid, values=farray, start=(/start(1),start(2)/), &\n      count=(/size(farray,1),size(farray,2)/))\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_READ,   &\n        msg=\"Error reading variable values \"//trim(varname)// &\n          \" in \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n    stat = nf90_close(ncid)\n    if (stat /= nf90_NoErr) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_FILE_CLOSE,   &\n        msg=\"Error closing NetCDF file \"//trim(filename)//\".\", &\n        CONTEXT, rcToReturn=rc)\n      return\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogStateList\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogStateList - Write ESMF state information to PET Logs\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogStateList\n  subroutine WRFHYDRO_ESMF_LogStateList(stateList,nestedFlag,label,rc)\n! ! ARGUMENTS\n    type(ESMF_State),intent(in)          :: stateList(:)\n    logical,intent(in),optional          :: nestedFlag\n    character(len=*),intent(in),optional :: label\n    integer, intent(out),optional        :: rc\n! !DESCRIPTION:\n!   Write ESMF state information to PET Logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64) :: llabel\n    integer           :: sIndex\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      llabel = 'WRFHYDRO_ESMF_LogStateList'\n    endif\n\n    do sIndex=1, size(stateList)\n      call WRFHYDRO_ESMF_LogState(stateList(sIndex),nestedFlag,label,rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n    enddo\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogState\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogState - Write ESMF state information to PET Logs\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogState\n  subroutine WRFHYDRO_ESMF_LogState(state,nestedFlag,label,fvalues,rc)\n! ! ARGUMENTS\n    type(ESMF_State),intent(in)  :: state\n    logical,intent(in),optional  :: nestedFlag\n    character(len=*),optional    :: label\n    logical,intent(in),optional  :: fvalues\n    integer,intent(out),optional :: rc\n! !DESCRIPTION:\n!   Write ESMF state information to PET Logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)                     :: llabel\n    logical                               :: lfvalues\n    integer                               :: stat\n    integer                               :: itemCount\n    character(len=64),allocatable         :: itemNameList(:)\n    type(ESMF_StateItem_Flag),allocatable :: itemTypeList(:)\n    type(ESMF_Field)                      :: field\n    character(len=64)                     :: stateName\n    character(len=12)                     :: itemTypeStr\n    integer                               :: iIndex\n    character(len=ESMF_MAXSTR)            :: logMsg\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      llabel = 'WRFHYDRO_ESMF_LogState'\n    endif\n\n    if (present(fvalues)) then\n      lfvalues = fvalues\n    else\n      lfvalues = .FALSE.\n    endif\n\n    call ESMF_StateGet(state, nestedFlag=nestedFlag, &\n      itemCount=itemCount, name=stateName, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    if (itemCount > 0 ) then\n\n      allocate(itemNameList(itemCount),itemTypeList(itemCount),stat=stat)\n      if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n        msg=\"Allocation of item list memory failed.\", &\n        CONTEXT, rcToReturn=rc)) return  ! bail out\n\n      call ESMF_StateGet(state, nestedFlag=nestedFlag, &\n        itemNameList=itemNameList,itemTypeList=itemTypeList, rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n      do iIndex=1, itemCount\n\n        if (itemTypeList(iIndex) == ESMF_STATEITEM_ARRAY) then\n          itemTypeStr = 'ARRAY'\n        elseif (itemTypeList(iIndex) == ESMF_STATEITEM_ARRAYBUNDLE) then\n          itemTypeStr = 'ARRAYBUNDLE'\n        elseif (itemTypeList(iIndex) == ESMF_STATEITEM_FIELD) then\n          itemTypeStr = 'FIELD'\n        elseif (itemTypeList(iIndex) == ESMF_STATEITEM_FIELDBUNDLE) then\n          itemTypeStr = 'FIELDBUNDLE'\n        elseif (itemTypeList(iIndex) == ESMF_STATEITEM_ROUTEHANDLE) then\n          itemTypeStr = 'ROUTEHANDLE'\n        elseif (itemTypeList(iIndex) == ESMF_STATEITEM_STATE) then\n          itemTypeStr = 'STATE'\n        else\n          itemTypeStr = 'UNKNOWN'\n        endif\n\n        write (logMsg,\"(A,A,(A,I0,A,I0,A),A)\") trim(llabel)//\": \", &\n          trim(stateName), &\n          \" StateItem(\",iIndex,\" of \",itemCount,\") \", &\n          trim(itemNameList(iIndex))//\"[\"//trim(itemTypeStr)//\"]\"\n        call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n      enddo\n\n      deallocate(itemNameList,itemTypeList,stat=stat)\n      if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n        msg=\"Deallocation of item list memory failed.\", &\n        CONTEXT, rcToReturn=rc)) return  ! bail out\n\n    else\n      write (logMsg,\"(A,A)\") trim(llabel)//\": \", &\n        trim(stateName)//\" is empty.\"\n      call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFieldConnections\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFieldConnections - Write ESMF state connection to logs\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFieldConnections\n  subroutine WRFHYDRO_ESMF_LogFieldConnections(state,nestedFlag,label,rc)\n! ! ARGUMENTS\n    type(ESMF_State), intent(in)            :: state\n    logical, intent(in), optional           :: nestedFlag\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write ESMF state connection to PET logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)                       :: llabel\n    character(len=64), allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable  :: itemTypeList(:)\n    character(len=32)                       :: stateName\n    integer                                 :: iIndex, itemCount\n    integer                                 :: stat\n    character(len=ESMF_MAXSTR)              :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    call ESMF_StateGet(state, itemCount=itemCount, &\n      nestedFlag=nestedFlag,name=stateName,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    if(present(label)) then\n      llabel = trim(label)\n    else\n      llabel = 'WRFHYDRO_ESMF_LogFieldConnections '//trim(stateName)\n    endif\n\n    call ESMF_StateGet(state, itemCount=itemCount, &\n      nestedFlag=nestedFlag,name=stateName,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    allocate(itemNameList(itemCount),itemTypeList(itemCount),stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of item name and type list memory failed.\", &\n      CONTEXT, rcToReturn=rc)) return  ! bail out\n\n    call ESMF_StateGet(state, itemNameList=itemNameList, &\n      itemTypeList=itemTypeList, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    do iIndex=1, itemCount\n      if (itemTypeList(iIndex) /= ESMF_STATEITEM_FIELD) then\n        write (logMsg,\"(A,A)\") trim(llabel)//\": \", &\n          trim(itemNameList(iIndex))//\" is not a field.\"\n      elseif (NUOPC_IsConnected(state, fieldName=itemNameList(iIndex))) then\n        write (logMsg,\"(A,A)\") trim(llabel)//\": \", &\n          trim(itemNameList(iIndex))//\" is connected.\"\n      else\n        write (logMsg,\"(A,A)\") trim(llabel)//\": \", &\n          trim(itemNameList(iIndex))//\" is not connected.\"\n      endif\n      call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n    enddo\n\n    deallocate(itemNameList,itemTypeList,stat=stat)\n    if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n      msg=\"Deallocation of item name and type list memory failed.\", &\n      CONTEXT, rcToReturn=rc)) return  ! bail out\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogGrid\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogGrid - Write ESMF grid information to PET logs\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogGrid\n  subroutine WRFHYDRO_ESMF_LogGrid(grid,label,rc)\n! ! ARGUMENTS\n    type(ESMF_Grid), intent(in)            :: grid\n    character(len=*), intent(in), optional :: label\n    integer, intent(out), optional         :: rc\n! !DESCRIPTION:\n!   Write ESMF grid information to PET logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)           :: llabel\n    character(len=64)           :: gridName\n    type(ESMF_DistGrid)         :: distgrid\n    character(len=64)           :: transferAction\n    integer                     :: localDeCount\n    integer                     :: dimCount, tileCount\n    integer                     :: dimIndex, tileIndex\n    integer,allocatable         :: coordDimCount(:)\n    integer                     :: coordDimMax\n    integer,allocatable         :: minIndexPTile(:,:), maxIndexPTile(:,:)\n    integer                     :: stat\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if (present(rc)) rc = ESMF_SUCCESS\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      llabel = 'WRFHYDRO_ESMF_LogGrid'\n    endif\n\n    ! access localDeCount to show this is a real Grid\n    call ESMF_GridGet(grid, name=gridName, &\n      localDeCount=localDeCount, distgrid=distgrid, &\n      dimCount=dimCount,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    ! allocate coordDim info accord. to dimCount and tileCount\n    allocate(coordDimCount(dimCount), &\n      stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of coordinate dimensions memory failed.\", &\n      CONTEXT, rcToReturn=rc)) return  ! bail out\n\n    ! get coordDim info\n    call ESMF_GridGet(grid, coordDimCount=coordDimCount, &\n      rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    coordDimMax = 0\n    do dimIndex=1,dimCount\n      coordDimMax = MAX(coordDimMax,coordDimCount(dimIndex))\n    enddo\n\n    if (coordDimMax == 1) then\n      write (logMsg,\"(A,A,A)\") trim(llabel)//\": \", &\n        trim(gridName), &\n        \" is a rectilinear grid with 1D coordinates in each dimension.\"\n      call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    endif\n\n    deallocate(coordDimCount, &\n      stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Dellocation of coordinate dimensions memory failed.\", &\n      CONTEXT, rcToReturn=rc)) return  ! bail out\n\n    write (logMsg,\"(A,A,(A,I0))\") trim(llabel)//\": \", &\n      trim(gridName), &\n      \" local decomposition count=\",localDeCount\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n    ! get dimCount and tileCount\n    call ESMF_DistGridGet(distgrid, dimCount=dimCount, tileCount=tileCount, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    write (logMsg,\"(A,A,(A,I0))\") trim(llabel)//\": \", &\n      trim(gridName), &\n      \" dimension count=\",dimCount\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A,(A,I0))\") trim(llabel)//\": \", &\n      trim(gridName), &\n      \" tile count=\",tileCount\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n    ! allocate minIndexPTile and maxIndexPTile accord. to dimCount and tileCount\n    allocate(minIndexPTile(dimCount, tileCount), &\n      maxIndexPTile(dimCount, tileCount),stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of index array memory failed.\", &\n      CONTEXT, rcToReturn=rc)) return  ! bail out\n\n    ! get minIndex and maxIndex arrays\n    call ESMF_DistGridGet(distgrid, minIndexPTile=minIndexPTile, &\n       maxIndexPTile=maxIndexPTile, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    do tileIndex=1,tileCount\n    do dimIndex=1,dimCount\n      write (logMsg,\"(A,A,A,4(I0,A))\") trim(llabel)//\": \", &\n        trim(gridName), &\n        \" (tile,dim,minIndexPTile,maxIndexPTile)=(\", &\n        tileIndex,\",\",dimIndex,\",\", &\n        minIndexPTile(dimIndex,tileIndex),\",\", &\n        maxIndexPTile(dimIndex,tileIndex),\")\"\n      call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    enddo\n    enddo\n\n    deallocate(minIndexPTile, maxIndexPTile,stat=stat)\n    if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n      msg=\"Deallocation of index array memory failed.\", &\n      CONTEXT, rcToReturn=rc)) return  ! bail out\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFieldList\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFieldList - Write ESMF field information to PET logs\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFieldList\n  subroutine WRFHYDRO_ESMF_LogFieldList(fieldList,label,rc)\n! ! ARGUMENTS\n    type(ESMF_Field),intent(in)          :: fieldList(:)\n    character(len=*),intent(in),optional :: label\n    integer,intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Write ESMF field information to PET logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64) :: llabel\n    integer           :: fIndex\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      llabel = 'WRFHYDRO_ESMF_LogFieldList'\n    endif\n\n    do fIndex=1,size(fieldList)\n      call WRFHYDRO_ESMF_LogField(fieldList(fIndex),llabel,rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n    enddo\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogField\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogField - Write ESMF field information to PET logs\n! !INTERFACE:\n  ! call using generic interface: ??\n  subroutine WRFHYDRO_ESMF_LogField(field,label,rc)\n! ! ARGUMENTS\n    type(ESMF_Field)                     :: field\n    character(len=*),intent(in),optional :: label\n    integer,intent(out),optional         :: rc\n! !DESCRIPTION:\n!   Write ESMF field information to PET logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)            :: llabel\n    character(ESMF_MAXSTR)       :: logMsg\n    integer                      :: stat\n    type(ESMF_FieldStatus_Flag)  :: fieldStatus\n    character(len=10)            :: fieldStatusStr\n    character(ESMF_MAXSTR)       :: fieldName\n    type(ESMF_GeomType_Flag)     :: fieldGeomtype\n    character(len=10)            :: fieldGeomtypeStr\n    character(len=64)            :: fieldConsumerConn\n    character(len=64)            :: fieldTransferOffer\n    character(len=64)            :: fieldTransferAction\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      llabel = 'WRFHYDRO_ESMF_LogField'\n    endif\n\n    call ESMF_FieldGet(field,status=fieldStatus,name=fieldName,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    if (fieldStatus == ESMF_FIELDSTATUS_EMPTY) then\n      fieldStatusStr = 'EMPTY'\n    elseif (fieldStatus == ESMF_FIELDSTATUS_GRIDSET) then\n      fieldStatusStr = 'GRIDSET'\n    elseif (fieldStatus == ESMF_FIELDSTATUS_COMPLETE) then\n      fieldStatusStr = 'COMPLETE'\n    else\n      fieldStatusStr = 'UNKNOWN'\n    endif\n\n    if (fieldStatus == ESMF_FIELDSTATUS_COMPLETE .OR. &\n    fieldStatus == ESMF_FIELDSTATUS_GRIDSET ) then\n      call ESMF_FieldGet(field, geomtype=fieldGeomtype,rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      if (fieldGeomtype == ESMF_GEOMTYPE_GRID) then\n        fieldGeomtypeStr = 'GRID'\n      elseif (fieldGeomtype == ESMF_GEOMTYPE_MESH) then\n        fieldGeomtypeStr = 'MESH'\n      elseif (fieldGeomtype == ESMF_GEOMTYPE_XGRID) then\n        fieldGeomtypeStr = 'XGRID'\n      elseif (fieldGeomtype == ESMF_GEOMTYPE_LOCSTREAM) then\n        fieldGeomtypeStr = 'LOCSTREAM'\n      else\n        fieldGeomtypeStr = 'UNKNOWN'\n      endif\n    else\n      fieldGeomtypeStr = 'NOTSET'\n    endif\n\n    call NUOPC_GetAttribute(field, name=\"ConsumerConnection\", &\n      value=fieldConsumerConn, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    call NUOPC_GetAttribute(field, name=\"TransferOfferGeomObject\", &\n      value=fieldTransferOffer, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    call NUOPC_GetAttribute(field, name=\"TransferActionGeomObject\", &\n      value=fieldTransferAction, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    write (logMsg,\"(A,A,(2A))\") trim(llabel)//\": \", &\n      trim(fieldName), &\n      \" status=\",trim(fieldStatusStr)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A,(2A))\") trim(llabel)//\": \", &\n      trim(fieldName), &\n      \" geomtype=\",trim(fieldGeomtypeStr)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A,(2A))\") trim(llabel)//\": \", &\n      trim(fieldName), &\n      \" consumerconn=\",trim(fieldConsumerConn)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A,2(2A))\") trim(llabel)//\": \", &\n      trim(fieldName), &\n      \" transferOffer=\",trim(fieldTransferOffer), &\n      \" transferAction=\",trim(fieldTransferAction)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFieldLclVal\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFieldLclVal - Write ESMF field local vals to PET logs\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFieldLclVal\n  subroutine WRFHYDRO_ESMF_LogFieldLclVal(field, label, rc)\n! ! ARGUMENTS\n    type(ESMF_Field), intent(in)            :: field\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write ESMF field local vals to PET logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    type(ESMF_Array)  :: array\n    character(len=64) :: llabel\n    character(len=64) :: fieldName\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      llabel = \"WRFHYDRO_ESMF_LogFieldLclVal\"\n    endif\n\n    call ESMF_FieldGet(field,array=array,name=fieldName,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    call WRFHYDRO_ESMF_LogArrayLclVal(array,fieldName=fieldName,label=llabel,rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogArrayLclVal\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogArrayLclVal - Write ESMF array local vals to PET logs\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogArrayLclVal\n  subroutine WRFHYDRO_ESMF_LogArrayLclVal(array, fieldName, label, rc)\n! ! ARGUMENTS\n    type(ESMF_Array), intent(in)            :: array\n    character(len=*), intent(in), optional  :: fieldName\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write ESMF array local vals to PET logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)             :: llabel\n    type(ESMF_TypeKind_Flag)      :: typekind\n    integer                       :: rank\n    integer(ESMF_KIND_I4),pointer :: dataPtr_I4_1D(:)\n    integer(ESMF_KIND_I4),pointer :: dataPtr_I4_2D(:,:)\n    integer(ESMF_KIND_I4),pointer :: dataPtr_I4_3D(:,:,:)\n    integer(ESMF_KIND_I8),pointer :: dataPtr_I8_1D(:)\n    integer(ESMF_KIND_I8),pointer :: dataPtr_I8_2D(:,:)\n    integer(ESMF_KIND_I8),pointer :: dataPtr_I8_3D(:,:,:)\n    real(ESMF_KIND_R4),pointer    :: dataPtr_R4_1D(:)\n    real(ESMF_KIND_R4),pointer    :: dataPtr_R4_2D(:,:)\n    real(ESMF_KIND_R4),pointer    :: dataPtr_R4_3D(:,:,:)\n    real(ESMF_KIND_R8),pointer    :: dataPtr_R8_1D(:,:)\n    real(ESMF_KIND_R8),pointer    :: dataPtr_R8_2D(:,:)\n    real(ESMF_KIND_R8),pointer    :: dataPtr_R8_3D(:,:,:)\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      llabel = \"WRFHYDRO_ESMF_LogArrayLclVal\"\n    endif\n\n    call ESMF_ArrayGet(array, typekind=typekind,rank=rank, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    if (typekind == ESMF_TYPEKIND_I4) then\n      if (rank == 1) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_I4_1D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_I4_1D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      elseif (rank == 2) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_I4_2D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_I4_2D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      elseif (rank == 3) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_I4_3D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_I4_3D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      else\n        call ESMF_LogWrite(trim(llabel)//\" rank out of log utility range.\", &\n          ESMF_LOGMSG_INFO)\n      endif\n    elseif (typekind == ESMF_TYPEKIND_I8) then\n      if (rank == 1) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_I8_1D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_I8_1D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      elseif (rank == 2) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_I8_2D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_I8_2D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      elseif (rank == 3) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_I8_3D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_I8_3D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      else\n        call ESMF_LogWrite(trim(llabel)//\" rank out of log uttility range.\", &\n          ESMF_LOGMSG_INFO)\n      endif\n    elseif (typekind == ESMF_TYPEKIND_R4) then\n      if (rank == 1) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_R4_1D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_R4_1D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      elseif (rank == 2) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_R4_2D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_R4_2D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      elseif (rank == 3) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_R4_3D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_R4_3D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      else\n        call ESMF_LogWrite(trim(llabel)//\" rank out of log utility range.\", &\n          ESMF_LOGMSG_INFO)\n      endif\n    elseif (typekind == ESMF_TYPEKIND_R8) then\n      if (rank == 1) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_R8_1D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_R8_1D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      elseif (rank == 2) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_R8_2D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_R8_2D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      elseif (rank == 3) then\n        call ESMF_ArrayGet(array, farrayPtr=dataPtr_R8_3D, rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n        call WRFHYDRO_ESMF_LogFarrayLclVal(dataPtr_R8_3D, fieldName=fieldName, &\n          label=trim(llabel), rc=rc)\n        if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n      else\n        call ESMF_LogWrite(trim(llabel)//\" rank out of log utility range.\", &\n          ESMF_LOGMSG_INFO)\n      endif\n    else\n      call ESMF_LogWrite(trim(llabel)//\" typekind out of log utility range.\", &\n        ESMF_LOGMSG_INFO)\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_I41D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_I41D - Write I41D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_I41D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    integer(ESMF_KIND_I4),intent(in)           :: farray(:)\n    character(len=*), intent(in), optional     :: fieldName\n    character(len=*), intent(in), optional     :: label\n    integer, intent(out), optional             :: rc\n! !DESCRIPTION:\n!   Write I41D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_I42D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_I42D - Write I42D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_I42D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    integer(ESMF_KIND_I4),intent(in)           :: farray(:,:)\n    character(len=*), intent(in), optional     :: fieldName\n    character(len=*), intent(in), optional     :: label\n    integer, intent(out), optional             :: rc\n! !DESCRIPTION:\n!   Write I42D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_I43D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_I43D - Write I43D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_I43D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    integer(ESMF_KIND_I4),intent(in)           :: farray(:,:,:)\n    character(len=*), intent(in), optional     :: fieldName\n    character(len=*), intent(in), optional     :: label\n    integer, intent(out), optional             :: rc\n! !DESCRIPTION:\n!   Write I43D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_I81D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_I81D - Write I81D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_I81D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    integer(ESMF_KIND_I8),intent(in)           :: farray(:)\n    character(len=*), intent(in), optional     :: fieldName\n    character(len=*), intent(in), optional     :: label\n    integer, intent(out), optional             :: rc\n! !DESCRIPTION:\n!   Write I81D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_I82D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_I82D - Write I82D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_I82D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    integer(ESMF_KIND_I8),intent(in)           :: farray(:,:)\n    character(len=*), intent(in), optional     :: fieldName\n    character(len=*), intent(in), optional     :: label\n    integer, intent(out), optional             :: rc\n! !DESCRIPTION:\n!   Write I82D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_I83D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_I83D - Write I83D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_I83D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    integer(ESMF_KIND_I8),intent(in)           :: farray(:,:,:)\n    character(len=*), intent(in), optional     :: fieldName\n    character(len=*), intent(in), optional     :: label\n    integer, intent(out), optional             :: rc\n! !DESCRIPTION:\n!   Write I83D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_R41D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_R41D - Write R41D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_R41D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    real(ESMF_KIND_R4),intent(in)           :: farray(:)\n    character(len=*), intent(in), optional  :: fieldName\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write R41D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_R42D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_R42D - Write R42D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_R42D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    real(ESMF_KIND_R4),intent(in)           :: farray(:,:)\n    character(len=*), intent(in), optional  :: fieldName\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write R41D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_R43D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_R43D - Write R43D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_R43D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    real(ESMF_KIND_R4),intent(in)           :: farray(:,:,:)\n    character(len=*), intent(in), optional  :: fieldName\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write R43D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_R81D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_R81D - Write R81D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_R81D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    real(ESMF_KIND_R8),intent(in)           :: farray(:)\n    character(len=*), intent(in), optional  :: fieldName\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write R81D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_R82D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_R82D - Write R82D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_R82D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    real(ESMF_KIND_R8),intent(in)           :: farray(:,:)\n    character(len=*), intent(in), optional  :: fieldName\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write R81D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogFarrayLclVal_R83D\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogFarrayLclVal_R83D - Write R83D array local vals to log\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogFarrayLclVal\n  subroutine WRFHYDRO_ESMF_LogFarrayLclVal_R83D(farray, fieldName, label, rc)\n! ! ARGUMENTS\n    real(ESMF_KIND_R8),intent(in)           :: farray(:,:,:)\n    character(len=*), intent(in), optional  :: fieldName\n    character(len=*), intent(in), optional  :: label\n    integer, intent(out), optional          :: rc\n! !DESCRIPTION:\n!   Write R83D array local vals to log\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)          :: llabel\n    character(len=ESMF_MAXSTR)  :: logMsg\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      if (present(fieldName)) then\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"//\" \"//trim(fieldName)\n      else\n        llabel = \"WRFHYDRO_ESMF_LogFarrayLclVal\"\n      endif\n    endif\n\n    write(logMsg,'(A,A,3(F0.3,A))') trim(llabel), &\n      \" MinVal=\",minval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" MaxVal=\",maxval(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(A,(A,F0.3))') trim(llabel), &\n      \" Sum=\",sum(farray)\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_LogCplList\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_LogCplList - Write ESMF CplList to PET logs\n! !INTERFACE:\n  ! call using generic interface: WRFHYDRO_ESMF_LogCplList\n  subroutine WRFHYDRO_ESMF_LogCplList(cplcomp,label,rc)\n! ! ARGUMENTS\n    type(ESMF_CplComp),intent(in)        :: cplcomp\n    character(len=*),intent(in),optional :: label\n    integer, intent(out),optional        :: rc\n! !DESCRIPTION:\n!   Write ESMF CplList to PET logs\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    character(len=64)                   :: llabel\n    character(ESMF_MAXSTR), allocatable :: cplList(:)\n    integer                             :: cplListSize\n    integer                             :: cIndex\n    integer                             :: stat\n    character(len=64)                   :: name\n    character(ESMF_MAXSTR)              :: logMsg\n\n    if (present(rc)) rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      llabel = trim(label)\n    else\n      llabel = 'WRFHYDRO_ESMF_LogCplList'\n    endif\n\n    ! query the CplComp for info\n    call ESMF_CplCompGet(cplcomp, name=name, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    ! get the CplList Attribute\n    call NUOPC_CompAttributeGet(cplcomp, name=\"CplList\", &\n      itemCount=cplListSize, rc=rc)\n    if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n\n    if (cplListSize>0) then\n      allocate(cplList(cplListSize), stat=stat)\n      if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n        msg=\"Allocation of internal CplList memory failed.\", &\n        CONTEXT, rcToReturn=rc)) return  ! bail out\n      call NUOPC_CompAttributeGet(cplcomp, name=\"CplList\", valueList=cplList, &\n        rc=rc)\n      if (ESMF_LogFoundError(rcToCheck=rc, PASSTHRU)) return  ! bail out\n   else\n     write (logMsg,\"(A,A,A)\") trim(llabel)//\": \", &\n       trim(name), &\n       \" CplList is empty.\"\n     call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n   endif\n\n    ! main loop over all entries in the cplList\n    do cIndex=1, cplListSize\n      write (logMsg,\"(A,A,(A,I0,A,I0,A),A)\") trim(llabel)//\": \", &\n        trim(name), &\n        \" CplListItem(\",cIndex, \" of \", cplListSize, \")=\", &\n        trim(cplList(cIndex))\n      call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    enddo\n\n    ! clean-up\n    if (cplListSize>0) then\n      deallocate(cplList,stat=stat)\n      if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n        msg=\"Deallocation of internal CplList memory failed.\", &\n        CONTEXT, rcToReturn=rc)) return  ! bail out\n    endif\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\n#define METHOD \"WRFHYDRO_ESMF_ChDir\"\n!BOP\n! !IROUTINE: WRFHYDRO_ESMF_ChDir - Change working directory\n! !INTERFACE:\n  ! call using: WRFHYDRO_ESMF_ChDir\n  subroutine WRFHYDRO_ESMF_ChDir(path,rc)\n! ! USES\n    use iso_c_binding\n! ! ARGUMENTS\n    character(*), intent(in)       :: path\n    integer, intent(out), optional :: rc\n! !DESCRIPTION:\n!   Change working directory\n!\n!   The arguments are:\n!   \\begin{description}\n!   \\end{description}\n!\n!EOP\n  !-----------------------------------------------------------------------------\n    ! local variables\n    integer :: stat\n\n    stat = local_chdir(path//c_null_char)\n    if (stat /= 0) then\n      call ESMF_LogSetError(rcToCheck=ESMF_RC_ARG_BAD,   &\n        msg=\"WRFHYDRO_ESMF_ChDir failed changing to \"//trim(path), &\n        CONTEXT, rcToReturn=stat)\n    else\n      stat = ESMF_SUCCESS\n    endif\n    if (present(rc)) rc = stat\n\n  end subroutine\n#undef METHOD\n\n  !-----------------------------------------------------------------------------\n\nend module WRFHydro_ESMF_Extensions\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/WRFHydro_NUOPC_Cap.F90",
    "content": "!>\n!! @mainpage NCAR's WRF-Hydro NUOPC Cap\n!! @author Daniel Rosen (daniel.rosen@noaa.gov)\n!! @author ESMF Support (esmf_support@ucar.edu)\n!! @date 03/14/2017 WRF-Hydro NUOPC Cap Added to GitHub\n!! @date 03/17/2017 Documentation Added\n!!\n!! @tableofcontents\n!!\n!! @section Overview Overview\n!!\n!! The Weather Research and Forecasting Hydrological (WRF-Hydro) model is a\n!! hydrometerological forecasting model developed and maintained by the\n!! National Center for Atmospheric Research (NCAR). The WRF-Hydro cap wraps\n!! the WRF-Hydro model with NUOPC compliant interfaces. The result is a\n!! WRF-Hydro model capable of coupling with other models using National\n!! Unified Operational Prediction Capability (NUOPC).\n!!\n!! This page documents the technical design of the specialized NUOPC model and\n!! the WRF-Hydro gluecode. For generic NUOPC model documentation please see\n!! the NUOPC reference manual: https://www.earthsystemcog.org/projects/nuopc/refmans.\n!!\n!!\n!! @section NuopcSpecialization NUOPC Model Specialized Entry Points\n!!\n!! This cap specializes the cap configuration, initialization, advertised\n!! fields, realized fields, data initialization, clock, run, and finalize.\n!!\n!! @subsection SetServices Set Services (Register Subroutines)\n!!\n!! Table summarizing the NUOPC specialized subroutines registered during\n!! [SetServices] (@ref WRFHYDRO_NUOPC::SetServices).  The \"Phase\" column says\n!! whether the subroutine is called during the initialization, run, or\n!! finalize part of the coupled system run.\n!!\n!! Phase  |     Cap Subroutine                                | Description\n!! -------|---------------------------------------------------|-------------------------------------------------------------\n!! Init   | [InitializeP0] (@ref WRFHYDRO_NUOPC::InitializeP0)     | Set the Initialize Phase Definition (IPD). Configure model\n!! Init   | [InitializeP1] (@ref WRFHYDRO_NUOPC::InitializeP1)     | Initialize model.  Advertize import and export fields\n!! Init   | [InitializeP3] (@ref WRFHYDRO_NUOPC::InitializeP3)     | Realize import and export fields\n!! Init   | [DataInitialize] (@ref WRFHYDRO_NUOPC::DataInitialize) | Initialize import and export data\n!! Init   | [SetClock] (@ref WRFHYDRO_NUOPC::SetClock)             | Set model clock during initialization\n!! Run    | [CheckImport] (@ref WRFHYDRO_NUOPC::CheckImport)       | Check timestamp on import data.\n!! Run    | [ModelAdvance] (@ref WRFHYDRO_NUOPC::ModelAdvance)     | Advances the model by a timestep\n!! Final  | [ModelFinalize] (@ref WRFHYDRO_NUOPC::ModelFinalize)   | Releases memory\n!!\n!!\n!! @section Initialize Initialize\n!!\n!! Description of the initialization phases and internal model calls.\n!! - [InitializeP0] (@ref WRFHYDRO_NUOPC::InitializeP0)\n!! - [InitializeP1] (@ref WRFHYDRO_NUOPC::InitializeP1)\n!! - [InitializeP3] (@ref WRFHYDRO_NUOPC::InitializeP3)\n!! - [DataInitialize] (@ref WRFHYDRO_NUOPC::DataInitialize)\n!! - [SetClock] (@ref WRFHYDRO_NUOPC::SetClock)\n!!\n!! @subsection InitializeP0 InitializeP0\n!!\n!! During initialize phase 0 the runtime configuration is read in from model\n!! attributes and the initialization phase definition version is set to\n!! IPDv03.\n!!\n!! @subsection InitializeP1 InitializeP1\n!!\n!! During initialize phase 1 the model is initialized and the import and\n!! export fields are advertised in a state labeled with the domain ID.\n!!\n!! @subsection InitializeP3 InitializeP3\n!!\n!! During initialize phase 3 import and export fields are realized if they are\n!! connected through NUOPC. Realized fields are created on the WRF-Hydro grid.\n!!\n!! @subsection DataInitialize DataInitialize\n!!\n!! During data initialize this cap checks the timestamp of all import fields\n!! dependent on a coupled model.  Once all dependent import fields have been\n!! initialized this cap is marked initalized.\n!!\n!! @subsection SetClock SetClock\n!!\n!! During set clock the cap creates a new clock using the timestep configured\n!! in te WRF-Hydro configuration file. The restart write time step is also\n!! created and the restart write time accumulation tracker is reset to zero.\n!!\n!!\n!! @section Run Run\n!!\n!! Description of the run phase(s) and internal model calls.\n!! - [CheckImport] (@ref WRFHYDRO_NUOPC::CheckImport)\n!! - [ModelAdvance] (@ref WRFHYDRO_NUOPC::ModelAdvance)\n!!\n!! @subsection CheckImport CheckImport\n!!\n!! During check import the import data is checked to verify that it is at\n!! the beginning or end of the timestep.\n!!\n!! @subsection ModelAdvance ModelAdvance\n!!\n!! Calls WRF-Hydro advance for the configured domain.\n!!\n!!\n!! @section Finalize Finalize\n!!\n!! Description of the finalize phase and internal model calls.\n!! - [ModelFinalize] (@ref WRFHYDRO_NUOPC::ModelFinalize)\n!!\n!! @subsection ModelFinalize ModelFinalize\n!!\n!! During model finalize WRF-Hydro finalize subroutines are called and memory\n!! allocated during cap initialization is released.\n!!\n!!\n!! @section ModelConfiguration Model Configuration\n!!\n!! Custom model attributes are used to configure the model.\n!!\n!! Attribute          | Default         | Description\n!! -------------------|------------------|-----------------------------------------------------------------------------------\n!! Verbosity          | 0                | String, converted into an integer. Bit 16: LIS cap information will be logged.\n!! Diagnostic         | 0                | String, converted into an integer. Bit 16: LIS cap diagnostics will be written.\n!! realize_all_export | false            | Realize all export fields including non connected fields.\n!! config_file        | hydro.namelist   | Override the WRF-Hydro configuration file.\n!! das_config_file    | namelist.hrldas  | Override the WRF-Hydro DAS configuration file.\n!! time_step          | 0                | Override the WRF-Hydro time step. Value 0: Does not override time step.\n!! forcings_directory | WRFHYDRO_FORCING | Override the WRF-Hydro forcings directory.\n!! domain_id          | 1                | Set the WRF-Hydro domain identifier.\n!! nest_to_nest       | false            | Turn on nest to nest coupling. Each nest will be identified with an integer.\n!! import_dependency  | false            | Data initialization will loop until all import field dependencies are satisfied.\n!! output_directory   | [CNAME]_OUTPUT   | Configure the WRF-Hydro Cap output directory.\n!! multi_instance_hyd | false            | Run multiple instances of WRF-Hydro, each in a different directory.\n!!\n!!\n!! @section ModelFields Model Fields\n!!\n!! The following tables list the import and export fields.\n!!\n!! @subsection ImportFields Import Fields\n!!\n!! Import fields are listed in the import_list parameter.\n!!\n!! Standard Name  | Units  | Model Variable  | Description                                | Notes\n!! ---------------|--------|-----------------|--------------------------------------------|--------------------------------------\n!! dummy_field_1  | Pa     | forcing_1       | field description for first import field   | |\n!! dummy_field_2  | kg     | forcing_2       | field description for second import field  | |\n!! dummy_field_3  | W m-2  | forcing_3       | field description for third import field   | field notes\n!!\n!! @subsection ExportField Export Fields\n!!\n!! Export fields are listed in the export_list parameter.\n!!\n!! Standard Name  | Units   | Model Variable  | Description                               | Notes\n!! ---------------|---------|-----------------|-------------------------------------------|---------------------------\n!! dummy_field_1  | m       | output_1        | field description for first export field  | field notes\n!! dummy_field_2  | kg      | output_2        | field description for second export field | |\n!! dummy_field_3  | m s-1   | output_3        | field description for third export field  | field notes\n!!\n!!\n!! @section MemoryManagement Memory Management\n!!\n!! Model configuration is stored in a custom internal state data type. A\n!! pointer to the custom internal state data type is stored in the component.\n!!\n!! The cap allocates new memory for each field.  This will be updated so that\n!! NUOPC fields directly access the WRF-Hydro field memory.\n!!\n!! @section IO Input and Output\n!!\n!! Cap diagnostic output is written to the ESMF PET Logs. Cap diagnostic\n!! output can be increased or decreased by setting the Verbosity attribute.\n!!\n!! NUOPC state restart write files are written depending on the\n!! RestartInterval attribute. If set to 0 then NUOPC state restart write files\n!! will never be written.\n!!\n!! WRF-Hydro diagnostics output is written to standard out. To increase the\n!! diagnostic output compile WRF-Hydro with -DHYDRO_D.\n!!\n!! WRF-Hydro writes several output files.  Please see the\n!! [WRF-Hydro documentation] (https://www.ral.ucar.edu/projects/wrf_hydro).\n!!\n!! @section Dependencies Dependencies\n!!\n!! Dependencies\n!! - [ESMF v7.0.0+] (https://www.earthsystemcog.org/projects/esmf/)\n!! - [NetCDF v4.3.0+] (http://www.unidata.ucar.edu/software/netcdf/docs/)\n!! - [NetCDF FORTRAN] (http://www.unidata.ucar.edu/software/netcdf/docs/building_netcdf_fortran.html)\n!!\n!! @subsection ESMF ESMF\n!!\n!! See the [ESMF User's Guide]\n!! (http://www.earthsystemmodeling.org/esmf_releases/public/last/ESMF_usrdoc).\n!!\n!! @section BuildingAndInstalling Building and Installing\n!!\n!! Environment Variables\n!! - ESMFMKFILE\n!!\n!! NUOPC Makefile Targets\n!! - nuopc\n!! - nuopcinstall\n!! - nuopcclean\n!!\n!! The build system in [Makefile] (@ref Makefile) wraps the WRF-Hydro build\n!! system and adds the nuopc, nuopcinstall, and nuopcclean targets. Before\n!! building make sure to configure the internal model.\n!!\n!! To build and install into the current directory run:\n!!    $ make nuopc\n!!\n!! To install into an alternative directory run:\n!!    $ make nuopcinstall DESTDIR=<INSTALL_DIR> INSTDIR=<SUBDIR>\n!!\n!! To build with debugging information run:\n!!    $ make nuopc DEBUG=on\n!!\n!! @section Repository\n!! The WRF-Hydro NUOPC cap is maintained in a GitHub repository:\n!! https://github.com/NESII/wrfhydro_cap\n!!\n!! @section References\n!!\n!! - [WRF-Hydro] (https://www.ral.ucar.edu/projects/wrf_hydro)\n!! - [ESPS] (https://www.earthsystemcog.org/projects/esps)\n!! - [ESMF] (https://www.earthsystemcog.org/projects/esmf)\n!! - [NUOPC] (https://www.earthsystemcog.org/projects/nuopc/)\n\n#define FILENAME \"WRFHydro_NUOPC_Cap.F90\"\n#define MODNAME \"WRFHydro_NUOPC\"\n#include \"WRFHydro_NUOPC_Macros.h\"\n\nmodule WRFHydro_NUOPC\n  use ESMF\n  use NUOPC\n  use NUOPC_Model, &\n    model_routine_SS        => SetServices, &\n    model_label_DataInitialize => label_DataInitialize, &\n    model_label_SetClock    => label_SetClock, &\n    model_label_CheckImport => label_CheckImport, &\n    model_label_Advance     => label_Advance, &\n    model_label_Finalize    => label_Finalize\n  use WRFHYDRO_NUOPC_Gluecode\n  use WRFHYDRO_NUOPC_Fields\n  use WRFHYDRO_NUOPC_Flags\n  use WRFHydro_ESMF_Extensions\n\n  implicit none\n\n  private\n\n  public SetServices\n\n  CHARACTER(LEN=*), PARAMETER :: label_InternalState = 'InternalState'\n\n  type type_InternalStateStruct\n    logical                  :: realizeAllImport = .FALSE.\n    logical                  :: realizeAllExport = .FALSE.\n    character(len=64)        :: configFile       = 'hydro.namelist'\n    character(len=64)        :: dasConfigFile    = 'namelist.hrldas'\n    integer                  :: timeStepInt      = 0\n    character(len=128)       :: forcingDir       = 'WRFHYDRO_FORCING'\n    integer                  :: did              = 1\n    logical                  :: nestToNest       = .FALSE.\n    type(memory_flag)        :: memr_import      = MEMORY_POINTER\n    type(memory_flag)        :: memr_export      = MEMORY_POINTER\n    type(fillv_flag)         :: init_import      = FILLV_MODEL\n    type(fillv_flag)         :: init_export      = FILLV_MODEL\n    type(checkclock_flag)    :: chck_import      = CHECKCLOCK_CURRT\n    type(missingval_flag)    :: misg_import      = MISSINGVAL_FAIL\n    logical                  :: reset_import     = .FALSE.\n    character(len=128)       :: dirOutput        = \"./HYD_OUTPUT\"\n    character(len=128)       :: dirInput         = \"./HYD_INPUT\"\n    logical                  :: writeRestart     = .FALSE.\n    logical                  :: multiInstance    = .FALSE.\n    character                :: hgrid            = '0'\n    integer                  :: nnests           = 1\n    type (ESMF_Clock)        :: clock(1)\n    type (ESMF_TimeInterval) :: stepTimer(1)\n    type(ESMF_State)         :: NStateImp(1)\n    type(ESMF_State)         :: NStateExp(1)\n    logical                  :: lsm_forcings(1)  = .FALSE.\n  endtype\n\n  type type_InternalState\n    type(type_InternalStateStruct), pointer :: wrap\n  end type\n\n  !-----------------------------------------------------------------------------\n  contains\n  !-----------------------------------------------------------------------------\n\n  subroutine SetServices(gcomp, rc)\n    type(ESMF_GridComp)  :: gcomp\n    integer, intent(out) :: rc\n\n    ! local variables\n    integer                    :: stat\n    type(type_InternalState)   :: is\n\n    rc = ESMF_SUCCESS\n\n    ! allocate memory for this internal state and set it in the component\n    allocate(is%wrap, stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg='WRFHYDRO: Allocation of internal state memory failed.', &\n      file=FILENAME, rcToReturn=rc)) return ! bail out\n    call ESMF_UserCompSetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! the NUOPC model component will register the generic methods\n    call NUOPC_CompDerive(gcomp, model_routine_SS, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! switching to IPD versions\n    call ESMF_GridCompSetEntryPoint(gcomp, ESMF_METHOD_INITIALIZE, &\n      userRoutine=InitializeP0, phase=0, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! set entry point for methods that require specific implementation\n    call NUOPC_CompSetEntryPoint(gcomp, ESMF_METHOD_INITIALIZE, &\n      phaseLabelList=(/\"IPDv03p1\"/), userRoutine=InitializeP1, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    call NUOPC_CompSetEntryPoint(gcomp, ESMF_METHOD_INITIALIZE, &\n      phaseLabelList=(/\"IPDv03p3\"/), userRoutine=InitializeP3, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! attach specializing method(s)\n    call NUOPC_CompSpecialize(gcomp, specLabel=model_label_DataInitialize, &\n       specRoutine=DataInitialize, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call NUOPC_CompSpecialize(gcomp, speclabel=model_label_SetClock, &\n      specRoutine=SetClock, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_MethodRemove(gcomp, label=model_label_CheckImport, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail ou\n    call NUOPC_CompSpecialize(gcomp, specLabel=model_label_CheckImport, &\n       specRoutine=CheckImport, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail ou\n    call NUOPC_CompSpecialize(gcomp, speclabel=model_label_Advance, &\n      specRoutine=ModelAdvance, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call NUOPC_CompSpecialize(gcomp, specLabel=model_label_Finalize, &\n      specRoutine=ModelFinalize, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n  subroutine InitializeP0(gcomp, importState, exportState, clock, rc)\n    type(ESMF_GridComp)   :: gcomp\n    type(ESMF_State)      :: importState, exportState\n    type(ESMF_Clock)      :: clock\n    integer, intent(out)  :: rc\n\n    ! local variables\n    character(32)              :: cname\n    character(*), parameter    :: rname=\"InitializeP0\"\n    integer                    :: verbosity, diagnostic\n    character(len=64)          :: value\n    type(type_InternalState)   :: is\n    integer                    :: stat\n\n    rc = ESMF_SUCCESS\n\n    ! Query component for name, verbosity, and diagnostic values\n!    call NUOPC_CompGet(gcomp, name=name, verbosity=verbosity, &\n!      diagnostic=diagnostic, rc=rc)\n    call ESMF_GridCompGet(gcomp, name=cname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Diagnostic\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    diagnostic = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Verbosity\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    verbosity = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query Component for its internal State\n    nullify(is%wrap)\n    call ESMF_UserCompGetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! Switch to IPDv03 by filtering all other phaseMap entries\n    call NUOPC_CompFilterPhaseMap(gcomp, ESMF_METHOD_INITIALIZE, &\n      acceptStringList=(/\"IPDv03p\"/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    call WRFHydro_AttributeGet(rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! change directory for multiple instances\n    if (is%wrap%multiInstance) then\n      if (btest(verbosity,16)) then\n        call ESMF_LogWrite(trim(cname)//\": Change working directory\", &\n          ESMF_LOGMSG_INFO)\n      endif\n      call WRFHYDRO_ESMF_ChDir(trim(cname),rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    ! prepare diagnostics folder\n    if (btest(diagnostic,16) .OR. is%wrap%writeRestart) then\n      call ESMF_UtilIOMkDir(pathName=trim(is%wrap%dirOutput), &\n        relaxedFlag=.true., rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    contains ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n    subroutine WRFHydro_AttributeGet(rc)\n      integer, intent(out)  :: rc\n\n      ! local variables\n      logical                    :: configIsPresent\n      type(ESMF_Config)          :: config\n      type(NUOPC_FreeFormat)     :: attrFF\n      character(32)              :: atName\n      logical                    :: atPres\n      character(32)              :: atVal\n      character(ESMF_MAXSTR)     :: logMsg\n\n      ! check gcomp for config\n      call ESMF_GridCompGet(gcomp, configIsPresent=configIsPresent, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n      if (configIsPresent) then\n        ! read and ingest free format component attributes\n        call ESMF_GridCompGet(gcomp, config=config, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        attrFF = NUOPC_FreeFormatCreate(config, &\n          label=trim(cname)//\"_attributes::\", relaxedflag=.true., rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call NUOPC_CompAttributeIngest(gcomp, attrFF, addFlag=.true., rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call NUOPC_FreeFormatDestroy(attrFF, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n\n      ! Realize all import fields\n      atName=\"realize_all_import\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        atVal = ESMF_UtilStringUpperCase(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%realizeAllImport = (trim(atVal)==\"TRUE\")\n      endif\n\n      ! Realize all export fields\n      atName=\"realize_all_export\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        atVal = ESMF_UtilStringUpperCase(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%realizeAllExport = (trim(atVal)==\"TRUE\")\n      endif\n\n      ! Determine hydro configuration filename\n      atName=\"config_file\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%configFile = atVal\n      endif\n\n      ! Determine DAS configuration filename\n      atName=\"das_config_file\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%dasConfigFile = atVal\n      endif\n\n      ! Time Step\n      atName=\"time_step\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        read (atVal,*,iostat=stat) is%wrap%timeStepInt\n        if (stat /= 0) then\n          call ESMF_LogSetError(ESMF_FAILURE, &\n            msg=\"Cannot convert \"//trim(atVal)//\" to integer.\", &\n            line=__LINE__,file=__FILE__,rcToReturn=rc)\n          return  ! bail out\n        endif\n      endif\n\n      ! Forcing Directory\n      atName=\"forcings_directory\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%forcingDir = trim(atVal)\n      endif\n\n      ! Determine Domain ID\n      atName=\"did\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%did = ESMF_UtilString2Int(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n\n      ! Connect Nest to Nest\n      atName=\"nest_to_nest\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        atVal = ESMF_UtilStringUpperCase(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%nestToNest = (trim(atVal)==\"TRUE\")\n      endif\n\n      ! import data memory type\n      atName=\"field_memory_import\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%memr_import = atVal\n      endif\n\n      ! export data memory type\n      atName=\"field_memory_export\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%memr_export = atVal\n      endif\n\n      ! import data initialization type\n      atName=\"initialize_import\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%init_import = atVal\n      endif\n\n      ! backwards compatible setting (overrides initialize_import)\n      atName=\"import_dependency\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        atVal = ESMF_UtilStringUpperCase(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        if (trim(atVal)==\"TRUE\") is%wrap%init_import = FILLV_DEPENDENCY\n      endif\n\n      ! export data initialization type\n      atName=\"initialize_export\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%init_export = atVal\n      endif\n\n      ! backwards compatible setting (overrides initialize_export)\n      atName=\"read_restart\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        atVal = ESMF_UtilStringUpperCase(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        if (trim(atVal)==\"TRUE\") is%wrap%init_export = FILLV_FILE\n      endif\n\n      ! Get check import\n      atName=\"check_import\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%chck_import = atVal\n      endif\n\n      ! Get missing import handler\n      atName=\"missing_import\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%misg_import = atVal\n      endif\n\n      ! Get reset import handler\n      atName=\"reset_import\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        atVal = ESMF_UtilStringUpperCase(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%reset_import = (trim(atVal)==\"TRUE\")\n      endif\n\n      ! Get component output directory\n      atName=\"output_directory\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%dirOutput = trim(atVal)\n      endif\n\n      ! Get component input directory\n      atName=\"input_directory\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%dirInput = trim(atVal)\n      endif\n\n      ! Write cap restart state\n      atName=\"write_restart\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        atVal = ESMF_UtilStringUpperCase(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%writeRestart = (trim(atVal)==\"TRUE\")\n      endif\n\n      ! Determine Import Dependency\n      atName=\"multi_instance_hyd\"\n      call NUOPC_CompAttributeGet(gcomp, name=atName, isPresent=atPres, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (atPres) then\n        call NUOPC_CompAttributeGet(gcomp, name=atName, value=atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        atVal = ESMF_UtilStringUpperCase(atVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        is%wrap%multiInstance = (trim(atVal)==\"TRUE\")\n      endif\n\n      if (btest(verbosity,16)) then\n        call ESMF_LogWrite(trim(cname)//\": Settings\",ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,I0))\") trim(cname)//\": \", &\n          \"Verbosity              = \",verbosity\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,I0))\") trim(cname)//\": \", &\n          \"Diagnostic             = \",diagnostic\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,L1))\") trim(cname)//\": \", &\n          \"Realze All Imports     = \",is%wrap%realizeAllImport\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,L1))\") trim(cname)//\": \", &\n          \"Realze All Exports     = \",is%wrap%realizeAllExport\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Config File            = \",trim(is%wrap%configFile)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"DAS Config File        = \",trim(is%wrap%dasConfigFile)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,I0))\") trim(cname)//\": \", &\n          \"Time Step Config       = \",is%wrap%timeStepInt\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Forcing Directory      = \",trim(is%wrap%forcingDir)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,I0))\") trim(cname)//\": \", &\n          \"Domain ID              = \",is%wrap%did\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,L1))\") trim(cname)//\": \", &\n          \"Nest To Nest           = \",is%wrap%nestToNest\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        atVal = is%wrap%memr_import\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Field Memory Import    = \",trim(atVal)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        atVal = is%wrap%memr_export\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Field Memory Export    = \",trim(atVal)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        atVal = is%wrap%init_import\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Initialize Import      = \",trim(atVal)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        atVal = is%wrap%init_export\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Initialize Export      = \",trim(atVal)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        atVal = is%wrap%chck_import\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Check Imports          = \",trim(atVal)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        atVal = is%wrap%misg_import\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Missing Imports        = \",trim(atVal)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,L1))\") trim(cname)//': ', &\n          \"Reset Import           = \",is%wrap%reset_import\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Output Directory       = \",trim(is%wrap%dirOutput)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n          \"Input Directory        = \",trim(is%wrap%dirInput)\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,L1))\") trim(cname)//': ', &\n          \"Write Restart          = \",is%wrap%writeRestart\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n        write (logMsg, \"(A,(A,L1))\") trim(cname)//': ', &\n          \"Multiple Instances     = \",is%wrap%multiInstance\n        call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n      endif\n\n    end subroutine\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n  subroutine InitializeP1(gcomp, importState, exportState, clock, rc)\n    type(ESMF_GridComp)  :: gcomp\n    type(ESMF_State)     :: importState, exportState\n    type(ESMF_Clock)     :: clock\n    integer, intent(out) :: rc\n\n    ! local variables\n    character(32)               :: cname\n    character(*), parameter     :: rname=\"InitializeP1\"\n    integer                     :: verbosity, diagnostic\n    character(len=64)           :: value\n    type(type_InternalState)    :: is\n    type(ESMF_VM)               :: vm\n    integer                     :: fIndex\n    character(len=9)            :: nStr\n\n    rc = ESMF_SUCCESS\n\n    ! Query component for name, verbosity, and diagnostic values\n!    call NUOPC_CompGet(gcomp, name=name, verbosity=verbosity, &\n!      diagnostic=diagnostic, rc=rc)\n    call ESMF_GridCompGet(gcomp, name=cname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Diagnostic\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    diagnostic = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Verbosity\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    verbosity = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query Component for its internal State\n    nullify(is%wrap)\n    call ESMF_UserCompGetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! initialize wrfhydro\n    call ESMF_GridCompGet(gcomp, vm=vm, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    call wrfhydro_nuopc_ini(is%wrap%did,vm,clock,is%wrap%forcingDir,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    ! get hgrid for domain id\n    call WRFHYDRO_get_hgrid(is%wrap%did,is%wrap%hgrid,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    ! add namespace\n    if(.NOT.is%wrap%nestToNest) then\n      is%wrap%NStateImp(1) = importState\n      is%wrap%NStateExp(1) = exportState\n    else\n      write (nStr,\"(I0)\") is%wrap%did\n      call NUOPC_AddNestedState(importState, &\n        CplSet=trim(is%wrap%hgrid), &\n        nestedStateName=\"NestedStateImp_N\"//trim(nStr), &\n        nestedState=is%wrap%NStateImp(1), rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      call NUOPC_AddNestedState(exportState, &\n        CplSet=trim(is%wrap%hgrid), &\n        nestedStateName=\"NestedStateExp_N\"//trim(nStr), &\n        nestedState=is%wrap%NStateExp(1), rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    call field_dictionary_add(fieldList=cap_fld_list, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    !!\n    !! advertise import and export fields\n    !!\n    call field_advertise(fieldList=cap_fld_list, &\n      importState=is%wrap%NStateImp(1), &\n      exportState=is%wrap%NStateExp(1), &\n      rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    if (btest(verbosity,16)) call field_advertise_log(cap_fld_list,cname,rc=rc)\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n  subroutine InitializeP3(gcomp, importState, exportState, clock, rc)\n    type(ESMF_GridComp)         :: gcomp\n    type(ESMF_State)            :: importState, exportState\n    type(ESMF_Clock)            :: clock\n    integer, intent(out)        :: rc\n\n    ! local variables\n    character(32)              :: cname\n    character(*), parameter    :: rname=\"InitializeP3\"\n    integer                    :: verbosity, diagnostic\n    character(len=64)          :: value\n    type(type_InternalState)   :: is\n    type(ESMF_Grid)            :: WRFHYDRO_Grid\n    type(ESMF_Field)           :: field\n    logical                    :: importConnected, exportConnected\n    integer                    :: fIndex\n    character(len=9)           :: nStr\n\n    rc = ESMF_SUCCESS\n\n    ! Query component for name, verbosity, and diagnostic values\n!    call NUOPC_CompGet(gcomp, name=name, verbosity=verbosity, &\n!      diagnostic=diagnostic, rc=rc)\n    call ESMF_GridCompGet(gcomp, name=cname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Diagnostic\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    diagnostic = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Verbosity\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    verbosity = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query Component for its internal State\n    nullify(is%wrap)\n    call ESMF_UserCompGetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    write (nStr,\"(I0)\") is%wrap%did\n\n    ! call gluecode to create grid\n    WRFHYDRO_Grid = WRFHYDRO_GridCreate(is%wrap%did,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    if (btest(verbosity,16)) then\n      call WRFHYDRO_ESMF_LogGrid(WRFHYDRO_Grid, &\n        trim(cname)//\"_\"//rname//\"_D\"//trim(nStr),rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    ! Write grid to NetCDF file.\n    if (btest(diagnostic,16)) then\n      call WRFHYDRO_ESMF_GridWrite(WRFHYDRO_Grid, &\n        trim(is%wrap%dirOutput)//\"/diag_\"//trim(cname)//\"_\"// &\n        rname//'_grid_D'//trim(nStr)//\".nc\", rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    call field_realize(fieldList=cap_fld_list, &\n      importState=is%wrap%NStateImp(1), &\n      exportState=is%wrap%NStateExp(1), &\n      grid=WRFHYDRO_grid, did=is%wrap%did, &\n      realizeAllImport=is%wrap%realizeAllImport, &\n      realizeAllExport=is%wrap%realizeAllExport, &\n      memr_import=is%wrap%memr_import, &\n      memr_export=is%wrap%memr_export, &\n      rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    is%wrap%lsm_forcings(1) = check_lsm_forcings(is%wrap%NStateImp(1),rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    if (btest(verbosity,16)) call field_realize_log(cap_fld_list,cname,rc=rc)\n    if (btest(verbosity,16)) call LogMode()\n\n    contains ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n    !---------------------------------------------------------------------------\n\n    subroutine LogMode()\n      ! local variables\n      character(ESMF_MAXSTR)     :: logMsg\n      character(len=64)          :: modeStr\n\n      if(is%wrap%lsm_forcings(1)) then\n        modeStr = \"WRFHYDRO_Coupled\"\n      else\n        modeStr = \"WRFHYDRO_Offline\"\n      endif\n      write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n        \"Mode = \",trim(modeStr)\n      call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n\n    end subroutine\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n  subroutine DataInitialize(gcomp, rc)\n    type(ESMF_GridComp)  :: gcomp\n    integer, intent(out) :: rc\n\n    ! local variables\n    character(32)                          :: cname\n    character(*), parameter                :: rname=\"DataInitialize\"\n    integer                                :: verbosity, diagnostic\n    character(len=64)                      :: value\n    type(type_InternalState)               :: is\n    type(ESMF_Clock)                       :: modelClock\n    type(ESMF_Time)                        :: currTime\n    type(ESMF_Time)                        :: invalidTime\n    character(len=32)                      :: currTimeStr\n    character(len=9)                       :: nStr\n    logical                                :: importCurrent\n    logical                                :: importUpdated\n    logical                                :: exportUpdated\n    character(len=32)                      :: initTypeStr\n    logical                                :: mdlRestart\n    integer                                :: stat\n\n    rc = ESMF_SUCCESS\n\n    ! Query component for name, verbosity, and diagnostic values\n!    call NUOPC_CompGet(gcomp, name=name, verbosity=verbosity, &\n!      diagnostic=diagnostic, rc=rc)\n    call ESMF_GridCompGet(gcomp, name=cname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Diagnostic\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    diagnostic = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Verbosity\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    verbosity = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query Component for its internal State\n    nullify(is%wrap)\n    call ESMF_UserCompGetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query the Component for its clock\n    call NUOPC_ModelGet(gcomp, modelClock=modelClock, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! set up invalid time (by convention)\n    call ESMF_TimeSet(invalidTime, yy=99999999, mm=01, dd=01, &\n      h=00, m=00, s=00, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! get the current time out of the clock\n    call ESMF_ClockGet(modelClock, currTime=currTime, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_TimeGet(currTime, timeString=currTimeStr, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    write (nStr,\"(I0)\") is%wrap%did\n\n    ! initialize import state\n    if (is%wrap%init_import.eq.FILLV_MISSING) then\n      call state_fill_uniform(is%wrap%NStateImp(1), &\n        fillValue=ESMF_MISSING_VALUE, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      call NUOPC_SetTimestamp(is%wrap%NStateImp(1), time=invalidTime, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      importUpdated = .TRUE.\n    elseif (is%wrap%init_import.eq.FILLV_ZERO) then\n      call state_fill_uniform(is%wrap%NStateImp(1), &\n        fillValue=0.0_ESMF_KIND_R8, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      call NUOPC_SetTimestamp(is%wrap%NStateImp(1), time=invalidTime, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      importUpdated = .TRUE.\n    elseif (is%wrap%init_import.eq.FILLV_DEPENDENCY) then\n      importCurrent = NUOPC_IsAtTime(is%wrap%NStateImp(1), &\n        time=currTime, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (importCurrent) then\n        call ESMF_LogWrite( &\n          trim(cname)//': '//rname//' Initialize-Data-Dependency SATISFIED!!! Nest='//trim(nStr), &\n          ESMF_LOGMSG_INFO)\n        importUpdated = .TRUE.\n      else\n        call ESMF_LogWrite( &\n          trim(cname)//': '//rname//' Initialize-Data-Dependency NOT YET SATISFIED!!! Nest='//trim(nStr), &\n          ESMF_LOGMSG_INFO)\n        importUpdated = .FALSE.\n      endif\n    elseif (is%wrap%init_import.eq.FILLV_PRESCRIBE) then\n      call state_fill_prescribe(is%wrap%NStateImp(1), &\n        fieldList=cap_fld_list, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      importUpdated = .TRUE.\n    elseif (is%wrap%init_import.eq.FILLV_FILE) then\n      call state_fill_file(is%wrap%NStateImp(1), &\n        filePrefix=trim(is%wrap%dirInput)//\"/restart_\"//trim(cname)// &\n          \"_imp_D\"//trim(nStr)//\"_\"//trim(currTimeStr), rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      call NUOPC_SetTimestamp(is%wrap%NStateImp(1), time=currTime, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      importUpdated = .TRUE.\n    elseif (is%wrap%init_import.eq.FILLV_MODEL) then\n      if (is%wrap%memr_import.eq.MEMORY_COPY) then\n        call state_copy_frhyd(is%wrap%NStateImp(1), is%wrap%did, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n      call WRFHYDRO_get_restart(is%wrap%did, restart=mdlRestart, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (mdlRestart) then\n        call NUOPC_SetTimestamp(is%wrap%NStateImp(1), time=currTime, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      else\n        call NUOPC_SetTimestamp(is%wrap%NStateImp(1), time=invalidTime, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n      importUpdated = .TRUE.\n    else\n      initTypeStr = is%wrap%init_import\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=\"Import data initialize routine unknown \"//trim(initTypeStr), &\n        line=__LINE__,file=__FILE__,rcToReturn=rc)\n      return  ! bail out\n      importUpdated = .FALSE.\n    endif\n\n    ! initialize export state\n    if (is%wrap%init_export.eq.FILLV_MISSING) then\n      call state_fill_uniform(is%wrap%NStateExp(1), &\n        fillValue=ESMF_MISSING_VALUE, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      call NUOPC_SetTimestamp(is%wrap%NStateExp(1), time=invalidTime, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      exportUpdated = .TRUE.\n    elseif (is%wrap%init_export.eq.FILLV_ZERO) then\n      call state_fill_uniform(is%wrap%NStateExp(1), &\n        fillValue=0.0_ESMF_KIND_R8, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      call NUOPC_SetTimestamp(is%wrap%NStateExp(1), time=invalidTime, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      exportUpdated = .TRUE.\n    elseif (is%wrap%init_export.eq.FILLV_PRESCRIBE) then\n      call state_fill_prescribe(is%wrap%NStateExp(1), &\n        fieldList=cap_fld_list, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      exportUpdated = .TRUE.\n    elseif (is%wrap%init_export.eq.FILLV_FILE) then\n      call state_fill_file(is%wrap%NStateExp(1), &\n        filePrefix=trim(is%wrap%dirInput)//\"/restart_\"//trim(cname)// &\n          \"_exp_D\"//trim(nStr)//\"_\"//trim(currTimeStr), rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      call NUOPC_SetTimestamp(is%wrap%NStateExp(1), time=currTime, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      exportUpdated = .TRUE.\n    elseif (is%wrap%init_export.eq.FILLV_MODEL) then\n      if (is%wrap%memr_export.eq.MEMORY_COPY) then\n        call state_copy_frhyd(is%wrap%NStateExp(1), is%wrap%did, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n      call WRFHYDRO_get_restart(is%wrap%did, restart=mdlRestart, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (mdlRestart) then\n        call NUOPC_SetTimestamp(is%wrap%NStateExp(1), time=currTime, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      else\n        call NUOPC_SetTimestamp(is%wrap%NStateExp(1), time=invalidTime, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n      exportUpdated = .TRUE.\n    else\n      initTypeStr = is%wrap%init_export\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=\"Export data initialize routine unknown \"//trim(initTypeStr), &\n        line=__LINE__,file=__FILE__,rcToReturn=rc)\n      return  ! bail out\n      exportUpdated = .FALSE.\n    endif\n\n    ! set InitializeDataComplete Attribute to \"true\", indicating to the\n    ! generic code that all inter-model data dependencies are satisfied\n    if (importUpdated.AND.exportUpdated) then\n      call NUOPC_CompAttributeSet(gcomp, name=\"InitializeDataComplete\", value=\"true\", rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      ! Write initialization files\n      if (btest(diagnostic,16)) then\n        call NUOPC_Write(is%wrap%NStateImp(1), &\n          fileNamePrefix=trim(is%wrap%dirOutput)//\"/diag_\"//trim(cname)//\"_\"// &\n            rname//\"_imp_D\"//trim(nStr)//\"_\"//trim(currTimeStr)//\"_\", &\n          overwrite=.true., status=ESMF_FILESTATUS_REPLACE, timeslice=1, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call NUOPC_Write(is%wrap%NStateExp(1), &\n          fileNamePrefix=trim(is%wrap%dirOutput)//\"/diag_\"//trim(cname)//\"_\"// &\n            rname//\"_exp_D\"//trim(nStr)//\"_\"//trim(currTimeStr)//\"_\", &\n          overwrite=.true., status=ESMF_FILESTATUS_REPLACE, timeslice=1, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n    endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n  subroutine SetClock(gcomp, rc)\n    type(ESMF_GridComp)  :: gcomp\n    integer, intent(out) :: rc\n\n    ! local variables\n    character(32)              :: cname\n    character(*), parameter    :: rname=\"SetClock\"\n    integer                    :: verbosity, diagnostic\n    character(len=64)          :: value\n    type(type_InternalState)   :: is\n    integer                    :: dt\n    type(ESMF_Clock)           :: modelClock\n    type(ESMF_TimeInterval)    :: timeStep\n\n    rc = ESMF_SUCCESS\n\n    ! Query component for name, verbosity, and diagnostic values\n!    call NUOPC_CompGet(gcomp, name=name, verbosity=verbosity, &\n!      diagnostic=diagnostic, rc=rc)\n    call ESMF_GridCompGet(gcomp, name=cname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Diagnostic\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    diagnostic = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Verbosity\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    verbosity = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query Component for its internal State\n    nullify(is%wrap)\n    call ESMF_UserCompGetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query the Component for its clock\n    call NUOPC_ModelGet(gcomp, modelClock=modelClock, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query the clock for its timestep\n    call ESMF_ClockGet(modelClock, timeStep=timeStep, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query the timestep for seconds\n    call ESMF_TimeIntervalGet(timestep,s=dt,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! override timestep\n    if (is%wrap%timeStepInt /= 0) then\n      call ESMF_TimeIntervalSet(timestep, &\n        s=is%wrap%timeStepInt, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      call WRFHYDRO_set_timestep(is%wrap%did,real(is%wrap%timeStepInt),rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      call ESMF_ClockSet(modelClock, timeStep=timeStep, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    else\n      call WRFHYDRO_set_timestep(is%wrap%did,real(dt),rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    call NUOPC_CompSetClock(gcomp, modelClock, timeStep, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    is%wrap%clock(1) = modelClock\n\n    ! Reset Timers\n    call ESMF_TimeIntervalSet(is%wrap%stepTimer(1), &\n      s_r8=0._ESMF_KIND_R8, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    if (btest(verbosity,16)) call LogClock()\n\n    contains ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n    subroutine LogClock()\n      ! local variables\n      character(ESMF_MAXSTR)     :: logMsg\n      type(ESMF_Time)            :: currTime\n      type(ESMF_TimeInterval)    :: timestep\n      character(len=64)          :: currTimeStr\n      character(len=64)          :: timestepStr\n\n      if (ESMF_ClockIsCreated(is%wrap%clock(1))) then\n        call ESMF_ClockGet(is%wrap%clock(1), &\n          currTime=currTime,timeStep=timestep,rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call ESMF_TimeGet(currTime, &\n          timeString=currTimeStr,rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call ESMF_TimeIntervalGet(timestep, &\n          timeString=timestepStr,rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      else\n        currTimeStr = \"(not_created)\"\n        timestepStr = \"(not_created)\"\n      endif\n\n      write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n        \"Current Time = \",trim(currTimeStr)\n      call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n      write (logMsg, \"(A,(A,A))\") trim(cname)//\": \", &\n        \"Time Step    = \",trim(timestepStr)\n      call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n\n    end subroutine\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\nsubroutine CheckImport(gcomp, rc)\n    type(ESMF_GridComp) :: gcomp\n    integer,intent(out) :: rc\n\n    ! local variables\n    character(32)               :: cname\n    character(*), parameter     :: rname=\"CheckImport\"\n    integer                     :: verbosity, diagnostic\n    character(len=64)           :: value\n    type(type_InternalState)    :: is\n    integer                     :: nIndex\n    character(len=10)           :: sStr\n    type(ESMF_Clock)            :: modelClock\n    type(ESMF_Time)             :: modelCurrTime\n    logical                     :: allCurrTime\n\n    rc = ESMF_SUCCESS\n\n    ! Query component for name, verbosity, and diagnostic values\n!    call NUOPC_CompGet(gcomp, name=name, verbosity=verbosity, &\n!      diagnostic=diagnostic, rc=rc)\n    call ESMF_GridCompGet(gcomp, name=cname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Diagnostic\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    diagnostic = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Verbosity\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    verbosity = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query Component for its internal State\n    nullify(is%wrap)\n    call ESMF_UserCompGetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query the Component for its clock\n    call NUOPC_ModelGet(gcomp, modelClock=modelClock, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! get the curr time out of the clock\n    call ESMF_ClockGet(modelClock, currTime=modelCurrTime, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! check that Fields in the importState show correct timestamp\n\n    allCurrTime = NUOPC_IsAtTime(is%wrap%NStateImp(1), modelCurrTime, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    if (.not.allCurrTime) then\n      call ESMF_LogWrite(trim(cname)//\": NUOPC INCOMPATIBILITY DETECTED: \"// &\n        \"Import Fields not at correct time\", &\n        ESMF_LOGMSG_WARNING)\n    endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n  subroutine ModelAdvance(gcomp, rc)\n    type(ESMF_GridComp)  :: gcomp\n    integer, intent(out) :: rc\n\n    ! local variables\n    character(32)               :: cname\n    character(*), parameter     :: rname=\"ModelAdvance\"\n    integer                     :: verbosity, diagnostic\n    character(len=64)           :: value\n    type(type_InternalState)    :: is\n    character(len=10)           :: sStr\n    type(ESMF_Clock)            :: modelClock\n    type(ESMF_State)            :: importState, exportState\n    type(ESMF_Time)             :: currTime, advEndTime\n    character(len=32)           :: currTimeStr, advEndTimeStr\n    type(ESMF_TimeInterval)     :: timeStep\n    character(len=9)            :: nStr\n    character(len=16)           :: misgValTypeStr\n\n    rc = ESMF_SUCCESS\n\n    ! Query component for name, verbosity, and diagnostic values\n!    call NUOPC_CompGet(gcomp, name=name, verbosity=verbosity, &\n!      diagnostic=diagnostic, rc=rc)\n    call ESMF_GridCompGet(gcomp, name=cname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Diagnostic\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    diagnostic = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Verbosity\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    verbosity = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query component for its internal State\n    nullify(is%wrap)\n    call ESMF_UserCompGetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query the component for its clock, importState, and exportState\n    call NUOPC_ModelGet(gcomp, &\n      modelClock=modelClock, &\n      importState=importState, &\n      exportState=exportState, &\n      rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query the clock for its current time and timestep\n    call ESMF_ClockGet(modelClock, &\n      currTime=currTime, timeStep=timeStep, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    advEndTime = currTime + timeStep\n    call ESMF_TimeGet(currTime, timeString=currTimeStr, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_TimeGet(advEndTime, timeString=advEndTimeStr, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    write (nStr,\"(I0)\") is%wrap%did\n\n    ! Write import files\n    if (btest(diagnostic,16)) then\n      call NUOPC_Write(is%wrap%NStateImp(1), &\n        fileNamePrefix=trim(is%wrap%dirOutput)//\"/diag_\"//trim(cname)//\"_\"// &\n          rname//\"_imp_D\"//trim(nStr)//\"_\"//trim(currTimeStr)//\"_\", &\n        overwrite=.true., status=ESMF_FILESTATUS_REPLACE, timeslice=1, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    if (is%wrap%memr_import.eq.MEMORY_COPY) then\n      call state_copy_tohyd(is%wrap%NStateImp(1), is%wrap%did, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    if (is%wrap%misg_import.eq.MISSINGVAL_FAIL) then\n      call state_check_missing(is%wrap%NStateImp(1), did=is%wrap%did, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    elseif (is%wrap%misg_import.eq.MISSINGVAL_PRESCRIBE) then\n      call state_prescribe_missing(is%wrap%NStateImp(1), did=is%wrap%did, &\n        fieldList=cap_fld_list, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    elseif (is%wrap%misg_import.eq.MISSINGVAL_IGNORE) then\n!     DO NOTHING\n    else\n      misgValTypeStr = is%wrap%misg_import\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=\"Unknown missing value handler \"//trim(misgValTypeStr), &\n        line=__LINE__,file=__FILE__,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n    if (btest(diagnostic,16)) then\n      call model_debug(is%wrap%NStateImp(1), did=is%wrap%did, &\n        memflg=is%wrap%memr_import, &\n        filePrefix=trim(is%wrap%dirOutput)//\"/wrfhydro_\"// &\n          rname//\"_imp_D\"//trim(nStr)//\"_\"//trim(currTimeStr)//\"_\", rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    is%wrap%stepTimer(1) = is%wrap%stepTimer(1) + timeStep\n\n    call ESMF_ClockGet(is%wrap%clock(1),timeStep=timestep,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    do while (is%wrap%stepTimer(1) >= timestep)\n      ! call wrfhydro advance\n      if (btest(verbosity,16)) then\n        call LogAdvance(nIndex=1,nStr=nStr)\n      endif\n      call wrfhydro_nuopc_run(is%wrap%did,is%wrap%lsm_forcings(1), &\n        is%wrap%clock(1),is%wrap%NStateImp(1),is%wrap%NStateExp(1),rc)\n      if(ESMF_STDERRORCHECK(rc)) return ! bail out\n      call ESMF_ClockAdvance(is%wrap%clock(1),rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      is%wrap%stepTimer(1) = &\n        is%wrap%stepTimer(1) - timestep\n    enddo\n\n    if (is%wrap%memr_export.eq.MEMORY_COPY) then\n      call state_copy_frhyd(is%wrap%NStateExp(1), is%wrap%did, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    if (is%wrap%reset_import) then\n      if ((is%wrap%memr_import.eq.MEMORY_POINTER) .AND. &\n          (is%wrap%memr_export.eq.MEMORY_POINTER)) then\n        call ESMF_LogSetError(ESMF_FAILURE, &\n          msg=\"Cannot reset import field if pointer is shared with export.\", &\n          line=__LINE__,file=__FILE__,rcToReturn=rc)\n        return  ! bail out\n      else\n        call state_fill_uniform(is%wrap%NStateImp(1), &\n          fillValue=ESMF_MISSING_VALUE, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n      endif\n    endif\n\n    ! Write export files\n    if (btest(diagnostic,16)) then\n      call NUOPC_Write(is%wrap%NStateExp(1), &\n        fileNamePrefix=trim(is%wrap%dirOutput)//\"/diag_\"//trim(cname)//\"_\"// &\n          rname//\"_exp_D\"//trim(nStr)//\"_\"//trim(advEndTimeStr)//\"_\", &\n        overwrite=.true., status=ESMF_FILESTATUS_REPLACE, timeslice=1, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    contains ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n    subroutine LogAdvance(nIndex,nStr)\n      integer                    :: nIndex\n      character(len=9)           :: nStr\n      ! local variables\n      character(ESMF_MAXSTR)     :: logMsg\n      character(len=32)          :: nModeStr\n      type(ESMF_Time)            :: nestCurrTime\n      type(ESMF_TimeInterval)    :: nestTimestep\n      character(len=32)          :: nCurrTimeStr\n      character(len=32)          :: nTimeStepStr\n\n      call ESMF_LogWrite(trim(cname)//': '//rname//&\n        ' Advancing Nest='//trim(nStr),ESMF_LOGMSG_INFO)\n\n      if (is%wrap%lsm_forcings(nIndex)) then\n        nModeStr = \"WRFHYDRO_Coupled\"\n      else\n        nModeStr = \"WRFHYDRO_Offline\"\n      endif\n\n      write (logMsg, \"(A,(A,A,A),(A,A))\") trim(cname)//': ', &\n        'Nest(',trim(nStr),') ', &\n        'Mode = ',trim(nModeStr)\n      call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n\n      if (ESMF_ClockIsCreated(is%wrap%clock(nIndex))) then\n        call ESMF_ClockGet(is%wrap%clock(nIndex), &\n          currTime=nestCurrTime,timeStep=nestTimestep,rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call ESMF_TimeGet(nestCurrTime, &\n          timeString=nCurrTimeStr,rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call ESMF_TimeIntervalGet(nestTimestep, &\n          timeString=nTimeStepStr,rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      else\n        nCurrTimeStr = \"(not_created)\"\n        nTimestepStr = \"(not_created)\"\n      endif\n      write (logMsg, \"(A,(A,A,A),(A,A))\") trim(cname)//\": \", &\n        \"Nest(\",trim(nStr),\") \", &\n        \"Current Time = \",trim(nCurrTimeStr)\n      call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n      write (logMsg, \"(A,(A,A,A),(A,A))\") trim(cname)//\": \", &\n        \"Nest(\",trim(nStr),\") \", &\n        \"Time Step    = \",trim(nTimestepStr)\n      call ESMF_LogWrite(trim(logMsg),ESMF_LOGMSG_INFO)\n\n    end subroutine\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n  subroutine ModelFinalize(gcomp,rc)\n    type(ESMF_GridComp)  :: gcomp\n    integer, intent(out) :: rc\n\n    ! Local Variables\n    character(32)              :: cname\n    character(*), parameter    :: rname=\"ModelFinalize\"\n    integer                    :: verbosity, diagnostic\n    character(len=64)          :: value\n    type(type_InternalState)   :: is\n    integer                    :: stat\n    type(ESMF_Clock)           :: modelClock\n    type(ESMF_Time)            :: currTime\n    character(len=32)          :: currTimeStr\n    character(len=9)           :: nStr\n\n    rc = ESMF_SUCCESS\n\n    ! Query component for name, verbosity, and diagnostic values\n!    call NUOPC_CompGet(gcomp, name=name, verbosity=verbosity, &\n!      diagnostic=diagnostic, rc=rc)\n    call ESMF_GridCompGet(gcomp, name=cname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Diagnostic\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    diagnostic = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_AttributeGet(gcomp, name=\"Verbosity\", value=value, &\n      defaultValue=\"0\", convention=\"NUOPC\", purpose=\"Instance\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    verbosity = ESMF_UtilString2Int(value, &\n      specialStringList=(/\"min\",\"max\",\"bit16\",\"maxplus\"/), &\n      specialValueList=(/0,65535,65536,131071/), rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query Component for its internal State\n    nullify(is%wrap)\n    call ESMF_UserCompGetInternalState(gcomp, label_InternalState, is, rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    ! query the Component for its clock\n    call NUOPC_ModelGet(gcomp, modelClock=modelClock, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    call ESMF_ClockGet(modelClock, currTime=currTime, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    call ESMF_TimeGet(currTime, timeString=currTimeStr, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    write (nStr,\"(I0)\") is%wrap%did\n\n    ! Write export file\n    if (is%wrap%writeRestart) then\n      call NUOPC_Write(is%wrap%NStateExp(1), &\n        fileNamePrefix=trim(is%wrap%dirOutput)//\"/restart_\"//trim(cname)// &\n          \"_exp_D\"//trim(nStr)//\"_\"//trim(currTimeStr)//\"_\", &\n          overwrite=.true., status=ESMF_FILESTATUS_REPLACE, timeslice=1, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    endif\n\n    call wrfhydro_nuopc_fin(is%wrap%did,rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    deallocate(is%wrap, stat=stat)\n    if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n      msg='WRFHYDRO: Deallocation of internal state memory failed.', &\n      file=FILENAME,rcToReturn=rc)) return ! bail out\n\n  end subroutine\n\nend module\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/WRFHydro_NUOPC_Fields.F90",
    "content": "#define FILENAME \"WRFHydro_NUOPC_Fields.F90\"\n#define MODNAME \"wrfhydro_nuopc_fields\"\n#include \"WRFHydro_NUOPC_Macros.h\"\n\nmodule wrfhydro_nuopc_fields\n! !MODULE: wrfhydro_nuopc_fields\n!\n! !DESCRIPTION:\n!   This module connects NUOPC field information for WRFHYDRO\n!\n! !REVISION HISTORY:\n!  21Jul23    Dan Rosen  Initial Specification\n!\n! !USES:\n  use ESMF\n  use NUOPC\n  use WRFHydro_ESMF_Extensions\n  use WRFHydro_NUOPC_Flags\n  use config_base,      only: nlst\n  use module_rt_data,   only: rt_domain\n  use overland_data,    only: overland_struct\n  use overland_control, only: overland_control_struct\n\n  implicit none\n\n  private\n\n  type cap_fld_type\n    sequence\n    character(len=64)           :: sd_name   = \"dummy\" ! standard name\n    character(len=64)           :: st_name   = \"dummy\" ! state name\n    character(len=64)           :: units     = \"-\"     ! units\n    logical                     :: ad_import = .FALSE. ! advertise import\n    logical                     :: ad_export = .FALSE. ! advertise export\n    real(ESMF_KIND_R8)          :: vl_fillv  = ESMF_MISSING_VALUE ! default\n    logical                     :: rl_import = .FALSE. ! realize import\n    logical                     :: rl_export = .FALSE. ! realize export\n  end type cap_fld_type\n\n  type(cap_fld_type),target,dimension(20) :: cap_fld_list = (/          &\n    cap_fld_type(\"inst_total_soil_moisture_content        \",\"smc     \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"inst_soil_moisture_content              \",\"slc     \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"inst_soil_temperature                   \",\"stc     \", &\n                 \"K     \",.TRUE. ,.FALSE.,288.d0),                      &\n    cap_fld_type(\"liquid_fraction_of_soil_moisture_layer_1\",\"sh2ox1  \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"liquid_fraction_of_soil_moisture_layer_2\",\"sh2ox2  \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"liquid_fraction_of_soil_moisture_layer_3\",\"sh2ox3  \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"liquid_fraction_of_soil_moisture_layer_4\",\"sh2ox4  \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"soil_moisture_fraction_layer_1          \",\"smc1    \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"soil_moisture_fraction_layer_2          \",\"smc2    \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"soil_moisture_fraction_layer_3          \",\"smc3    \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"soil_moisture_fraction_layer_4          \",\"smc4    \", &\n                 \"m3 m-3\",.TRUE. ,.TRUE. ,0.20d0),                      &\n    cap_fld_type(\"soil_temperature_layer_1                \",\"stc1    \", &\n                 \"K     \",.TRUE. ,.FALSE.,288.d0),                      &\n    cap_fld_type(\"soil_temperature_layer_2                \",\"stc2    \", &\n                 \"K     \",.TRUE. ,.FALSE.,288.d0),                      &\n    cap_fld_type(\"soil_temperature_layer_3                \",\"stc3    \", &\n                 \"K     \",.TRUE. ,.FALSE.,288.d0),                      &\n    cap_fld_type(\"soil_temperature_layer_4                \",\"stc4    \", &\n                 \"K     \",.TRUE. ,.FALSE.,288.d0),                      &\n    cap_fld_type(\"soil_porosity                           \",\"smcmax1 \", &\n                 \"1     \",.FALSE.,.FALSE.,0.45d0),                      &\n    cap_fld_type(\"vegetation_type                         \",\"vegtyp  \", &\n                 \"1     \",.FALSE.,.FALSE.,16.0d0),                      &\n    cap_fld_type(\"surface_water_depth                     \",\"sfchead \", &\n                 \"mm    \",.FALSE.,.TRUE. ,0.00d0),                      &\n    cap_fld_type(\"time_step_infiltration_excess           \",\"infxsrt \", &\n                 \"mm    \",.TRUE. ,.FALSE.,0.00d0),                      &\n    cap_fld_type(\"soil_column_drainage                    \",\"soldrain\", &\n                 \"mm    \",.TRUE. ,.FALSE.,0.00d0)                       &\n    /)\n\n  public cap_fld_list\n  public field_dictionary_add\n  public field_create\n  public field_realize\n  public field_advertise\n  public check_lsm_forcings\n  public field_advertise_log\n  public field_realize_log\n  public read_impexp_config_flnm\n  public field_find_standardname\n  public field_find_statename\n  public state_fill_uniform\n  public state_fill_prescribe\n  public state_fill_file\n  public state_copy_tohyd\n  public state_copy_frhyd\n  public state_check_missing\n  public state_prescribe_missing\n  public model_debug\n\n  !-----------------------------------------------------------------------------\n  contains\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"field_dictionary_add\"\n  subroutine field_dictionary_add(fieldList, rc)\n    type(cap_fld_type), intent(in) :: fieldList(:)\n    integer, intent(out)           :: rc\n    ! local variables\n    integer :: n\n    logical :: isPresent\n\n    rc = ESMF_SUCCESS\n\n    do n=lbound(fieldList,1),ubound(fieldList,1)\n      isPresent = NUOPC_FieldDictionaryHasEntry( &\n        fieldList(n)%sd_name, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (.not.isPresent) then\n        call NUOPC_FieldDictionaryAddEntry( &\n          StandardName=trim(fieldList(n)%sd_name), &\n          canonicalUnits=trim(fieldList(n)%units), &\n          rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      end if\n    end do\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"field_realize\"\n  subroutine field_realize(fieldList, importState, exportState, grid, &\n  did, realizeAllImport, realizeAllExport, memr_import, memr_export, rc)\n    type(cap_fld_type), intent(inout) :: fieldList(:)\n    type(ESMF_State), intent(inout)   :: importState\n    type(ESMF_State), intent(inout)   :: exportState\n    type(ESMF_Grid), intent(in)       :: grid\n    integer, intent(in)               :: did\n    logical, intent(in)               :: realizeAllImport\n    logical, intent(in)               :: realizeAllExport\n    type(memory_flag)                 :: memr_import\n    type(memory_flag)                 :: memr_export\n    integer, intent(out)              :: rc\n    ! local variables\n    integer :: n\n    logical :: realizeImport\n    logical :: realizeExport\n    type(ESMF_Field) :: field_import\n    type(ESMF_Field) :: field_export\n\n    rc = ESMF_SUCCESS\n\n    do n=lbound(fieldList,1),ubound(fieldList,1)\n      ! check realize import\n      if (fieldList(n)%ad_import) then\n        if (realizeAllImport) then\n          realizeImport = .true.\n        else\n          realizeImport = NUOPC_IsConnected(importState, &\n            fieldName=trim(fieldList(n)%st_name),rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        end if\n      else\n        realizeImport = .false.\n      end if\n      ! create import field\n      if ( realizeImport ) then\n        field_import=field_create(fld_name=fieldList(n)%st_name, &\n          grid=grid, did=did, memflg=memr_import, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call NUOPC_Realize(importState, field=field_import, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        fieldList(n)%rl_import = .true.\n      else\n        call ESMF_StateRemove(importState, (/fieldList(n)%st_name/), &\n          relaxedflag=.true., rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        fieldList(n)%rl_import = .false.\n      end if\n\n      ! check realize export\n      if (fieldList(n)%ad_export) then\n        if (realizeAllExport) then\n          realizeExport = .true.\n        else\n          realizeExport = NUOPC_IsConnected(exportState, &\n            fieldName=trim(fieldList(n)%st_name),rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        end if\n      else\n        realizeExport = .false.\n      end if\n      ! create export field\n      if( realizeExport ) then\n        field_export=field_create(fld_name=fieldList(n)%st_name, &\n          grid=grid, did=did, memflg=memr_export, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        call NUOPC_Realize(exportState, field=field_export, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        fieldList(n)%rl_export = .true.\n      else\n        call ESMF_StateRemove(exportState, (/fieldList(n)%st_name/), &\n          relaxedflag=.true., rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n        fieldList(n)%rl_export = .false.\n      end if\n    end do\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"lsm_forcings\"\n\n  function check_lsm_forcings(importState,rc)\n    ! RETURN\n    logical :: check_lsm_forcings\n    ! ARGUMENTS\n    type(ESMF_State), intent(in) :: importState\n    integer, intent(out)         :: rc\n    ! LOCAL VARIABLES\n    integer                    :: fieldIndex\n    type(ESMF_StateItem_Flag)  :: itemType\n    integer                    :: s_smc, s_smc1, s_smc2, s_smc3, s_smc4\n    integer                    :: s_slc, s_slc1, s_slc2, s_slc3, s_slc4\n    integer                    :: s_stc, s_stc1, s_stc2, s_stc3, s_stc4\n    integer                    :: s_infxsrt\n    integer                    :: s_soldrain\n    logical                    :: c_smc\n    logical                    :: c_slc\n    logical                    :: c_stc\n    logical                    :: c_infxsrt\n    logical                    :: c_soldrain\n\n    ! total soil moisture content\n    call ESMF_StateGet(importState,itemSearch=\"smc\", itemCount=s_smc, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"smc1\",itemCount=s_smc1,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"smc2\",itemCount=s_smc2,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"smc3\",itemCount=s_smc3,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"smc4\",itemCount=s_smc4,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    if (s_smc.gt.0) then\n      c_smc = NUOPC_IsConnected(importState, fieldName=\"smc\")\n    elseif ((s_smc1.gt.0) .and. (s_smc2.gt.0) .and. &\n            (s_smc3.gt.0) .and. (s_smc4.gt.0)) then\n      c_smc = (NUOPC_IsConnected(importState, fieldName=\"smc1\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"smc2\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"smc3\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"smc4\"))\n    else\n      c_smc = .false.\n    endif\n\n    ! liquid soil moisture content\n    call ESMF_StateGet(importState,itemSearch=\"slc\", itemCount=s_slc, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"sh2ox1\",itemCount=s_slc1,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"sh2ox2\",itemCount=s_slc2,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"sh2ox3\",itemCount=s_slc3,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"sh2ox4\",itemCount=s_slc4,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    if (s_slc.gt.0) then\n      c_slc = NUOPC_IsConnected(importState, fieldName=\"slc\")\n    elseif ((s_slc1.gt.0) .and. (s_slc2.gt.0) .and. &\n            (s_slc3.gt.0) .and. (s_slc4.gt.0)) then\n      c_slc = (NUOPC_IsConnected(importState, fieldName=\"sh2ox1\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"sh2ox2\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"sh2ox3\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"sh2ox4\"))\n    else\n      c_slc = .false.\n    endif\n\n    ! soil temperature\n    call ESMF_StateGet(importState,itemSearch=\"stc\", itemCount=s_stc, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"stc1\",itemCount=s_stc1,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"stc2\",itemCount=s_stc2,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"stc3\",itemCount=s_stc3,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_StateGet(importState,itemSearch=\"stc4\",itemCount=s_stc4,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    if (s_stc.gt.0) then\n      c_stc = NUOPC_IsConnected(importState, fieldName=\"stc\")\n    elseif ((s_stc1.gt.0) .and. (s_stc2.gt.0) .and. &\n            (s_stc3.gt.0) .and. (s_stc4.gt.0)) then\n      c_stc = (NUOPC_IsConnected(importState, fieldName=\"stc1\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"stc2\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"stc3\") .and. &\n               NUOPC_IsConnected(importState, fieldName=\"stc4\"))\n    else\n      c_stc = .false.\n    endif\n\n    ! infiltration excess\n    call ESMF_StateGet(importState,itemSearch=\"infxsrt\",itemCount=s_infxsrt,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    if (s_infxsrt.gt.0) then\n      c_infxsrt = NUOPC_IsConnected(importState, fieldName=\"infxsrt\")\n    else\n      c_infxsrt = .false.\n    endif\n\n    ! soil drainage\n    call ESMF_StateGet(importState,itemSearch=\"soldrain\",itemCount=s_soldrain,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    if (s_soldrain.gt.0) then\n      c_soldrain = NUOPC_IsConnected(importState, fieldName=\"soldrain\")\n    else\n      c_soldrain = .false.\n    endif\n\n    check_lsm_forcings = c_smc .and. c_slc .and. c_stc .and. &\n                         c_infxsrt .and. c_soldrain\n\n  end function\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"field_advertise\"\n  subroutine field_advertise(fieldList, importState, exportState, &\n  transferOffer, rc)\n    type(cap_fld_type), intent(in)    :: fieldList(:)\n    type(ESMF_State), intent(inout)   :: importState\n    type(ESMF_State), intent(inout)   :: exportState\n    character(*), intent(in),optional :: transferOffer\n    integer, intent(out)              :: rc\n    ! local variables\n    integer :: n\n\n    rc = ESMF_SUCCESS\n\n    do n=lbound(fieldList,1),ubound(fieldList,1)\n      if (fieldList(n)%ad_import) then\n        call NUOPC_Advertise(importState, &\n          StandardName=fieldList(n)%sd_name, &\n          Units=fieldList(n)%units, &\n          TransferOfferGeomObject=transferOffer, &\n          name=fieldList(n)%st_name, &\n          rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      end if\n      if (fieldList(n)%ad_export) then\n        call NUOPC_Advertise(exportState, &\n          StandardName=fieldList(n)%sd_name, &\n          Units=fieldList(n)%units, &\n          TransferOfferGeomObject=transferOffer, &\n          name=fieldList(n)%st_name, &\n          rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      end if\n    end do\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"field_advertise_log\"\n  subroutine field_advertise_log(fieldList, cname, rc)\n    type(cap_fld_type), intent(in) :: fieldList(:)\n    character(*), intent(in)       :: cname\n    integer, intent(out)           :: rc\n    ! local variables\n    integer                    :: cntImp\n    integer                    :: cntExp\n    integer                    :: n\n    character(32)              :: label\n    character(ESMF_MAXSTR)     :: logMsg\n\n    rc = ESMF_SUCCESS\n\n    label = trim(cname)\n\n    ! count advertised import and export fields\n    cntImp = 0\n    cntExp = 0\n    do n = lbound(fieldList,1), ubound(fieldList,1)\n      if (fieldList(n)%ad_import) cntImp = cntImp + 1\n      if (fieldList(n)%ad_export) cntExp = cntExp + 1\n    enddo\n\n    ! log advertised import fields\n    write(logMsg,'(a,a,i0,a)') trim(label)//': ', &\n      'List of advertised import fields(',cntImp,'):'\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(a,a5,a,a16,a,a)') trim(label)//': ', &\n      'index',' ','name',' ','standardName'\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    cntImp = 0\n    do n=lbound(fieldList,1), ubound(fieldList,1)\n      if (.NOT.fieldList(n)%ad_import) cycle\n      cntImp = cntImp + 1\n      write(logMsg,'(a,i5,a,a16,a,a)') trim(label)//': ', &\n        cntImp,' ',trim(fieldList(n)%st_name), &\n        ' ',trim(fieldList(n)%sd_name)\n      call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    enddo\n\n    ! log advertised export fields\n    write(logMsg,'(a,a,i0,a)') trim(label)//': ', &\n      'List of advertised export fields(',cntExp,'):'\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(a,a5,a,a16,a,a)') trim(label)//': ', &\n      'index',' ','name',' ','standardName'\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    cntExp = 0\n    do n=lbound(fieldList,1), ubound(fieldList,1)\n      if (.NOT.fieldList(n)%ad_export) cycle\n      cntExp = cntExp + 1\n      write(logMsg,'(a,i5,a,a16,a,a)') trim(label)//': ', &\n        cntExp,' ',trim(fieldList(n)%st_name), &\n        ' ',trim(fieldList(n)%sd_name)\n      call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    enddo\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"field_realize_log\"\n  subroutine field_realize_log(fieldList, cname, rc)\n    type(cap_fld_type), intent(in) :: fieldList(:)\n    character(*), intent(in)       :: cname\n    integer, intent(out)           :: rc\n    ! local variables\n    integer                    :: cntImp\n    integer                    :: cntExp\n    integer                    :: n\n    character(32)              :: label\n    character(ESMF_MAXSTR)     :: logMsg\n\n    rc = ESMF_SUCCESS\n\n    label = trim(cname)\n\n    ! count realized import and export fields\n    cntImp = 0\n    cntExp = 0\n    do n = lbound(fieldList,1), ubound(fieldList,1)\n      if (fieldList(n)%rl_import) cntImp = cntImp + 1\n      if (fieldList(n)%rl_export) cntExp = cntExp + 1\n    enddo\n\n    ! log realized import fields\n    write(logMsg,'(a,a,i0,a)') trim(label)//': ', &\n      'List of realized import fields(',cntImp,'):'\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(a,a5,a,a16,a,a)') trim(label)//': ', &\n      'index',' ','name',' ','standardName'\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    cntImp = 0\n    do n=lbound(fieldList,1), ubound(fieldList,1)\n      if (.NOT.fieldList(n)%rl_import) cycle\n      cntImp = cntImp + 1\n      write(logMsg,'(a,i5,a,a16,a,a)') trim(label)//': ', &\n        cntImp,' ',trim(fieldList(n)%st_name), &\n        ' ',trim(fieldList(n)%sd_name)\n      call ESMF_LogWrite(trim(LogMsg), ESMF_LOGMSG_INFO)\n    enddo\n\n    ! log realized export fields\n    write(logMsg,'(a,a,i0,a)') trim(label)//': ', &\n      'List of realized export fields(',cntExp,'):'\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    write(logMsg,'(a,a5,a,a16,a,a)') trim(label)//': ', &\n      'index',' ','name',' ','standardName'\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    cntExp = 0\n    do n=lbound(fieldList,1), ubound(fieldList,1)\n      if (.NOT.fieldList(n)%rl_export) cycle\n      cntExp = cntExp + 1\n      write(logMsg,'(a,i5,a,a16,a,a)') trim(label)//': ', &\n        cntExp,' ',trim(fieldList(n)%st_name), &\n        ' ',trim(fieldList(n)%sd_name)\n      call ESMF_LogWrite(trim(LogMsg), ESMF_LOGMSG_INFO)\n    enddo\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"read_impexp_config_flnm\"\n  subroutine read_impexp_config_flnm(fname, fieldList, rc)\n    character(len=30),intent(in)     :: fname\n    type(cap_fld_type),intent(inout) :: fieldList(:)\n    integer,intent(out)              :: rc\n\n    ! local variables\n    type(ESMF_Config)                  :: fieldsConfig\n    type(NUOPC_FreeFormat)             :: attrFF\n    integer                            :: lineCount\n    integer                            :: tokenCount\n    character(len=NUOPC_FreeFormatLen),allocatable :: tokenList(:)\n    integer                            :: i,j\n    integer                            :: stat\n\n    rc = ESMF_SUCCESS\n\n!   load fname into fieldsConfig\n    fieldsConfig = ESMF_ConfigCreate(rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_ConfigLoadFile(fieldsConfig, fname, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n!   read export fields from config\n    attrFF = NUOPC_FreeFormatCreate(fieldsConfig, &\n      label=\"hyd_fields\", rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call NUOPC_FreeFormatGet(attrFF, lineCount=lineCount, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    do i=1, lineCount\n      call NUOPC_FreeFormatGetLine(attrFF, line=i, &\n        tokenCount=tokenCount, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      if (.not.((tokenCount.eq.5).or.(tokenCount.eq.6))) then\n        call ESMF_LogSetError(ESMF_FAILURE, &\n          msg=\"Malformed ocn_export_fields item FORMAT=\"// &\n            \"'STATE_NAME' 'STANDARD_NAME' 'UNITS' 'IMPORT' 'EXPORT' \"// &\n!            \"['FILLVAL'] \"// &\n            \"in file: \"//trim(fname), &\n          CONTEXT, rcToReturn=rc)\n        return ! bail out\n      endif\n      allocate(tokenList(tokenCount))\n      call NUOPC_FreeFormatGetLine(attrFF, line=i, tokenList=tokenList, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      call field_find_statename(fieldList, tokenList(1), location=j, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      fieldList(j)%st_name=tokenList(1)\n      fieldList(j)%sd_name=tokenList(2)\n      fieldList(j)%units=tokenList(3)\n      tokenList(4) = ESMF_UtilStringUpperCase(tokenList(4), rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      fieldList(j)%ad_import=((tokenList(4).eq.\".TRUE.\") .or. &\n                         (tokenList(4).eq.\"TRUE\"))\n      tokenList(5) = ESMF_UtilStringUpperCase(tokenList(5), rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      fieldList(j)%ad_export=((tokenList(5).eq.\".TRUE.\") .or. &\n                         (tokenList(5).eq.\"TRUE\"))\n      if (tokenCount.eq.6) then\n        fieldList(j)%vl_fillv = ESMF_UtilString2Real(tokenList(6), rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n      deallocate(tokenList)\n    enddo\n\n!   cleanup\n    call NUOPC_FreeFormatDestroy(attrFF, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    call ESMF_ConfigDestroy(fieldsConfig, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n  end subroutine read_impexp_config_flnm\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"field_find_standardname\"\n  subroutine field_find_standardname(fieldList, standardName, location, &\n  fillValue, rc)\n    type(cap_fld_type), intent(in)          :: fieldList(:)\n    character(len=64), intent(in)           :: standardName\n    integer, intent(out), optional          :: location\n    real(ESMF_KIND_R8),intent(out),optional :: fillValue\n    integer, intent(out)                    :: rc\n    ! local variables\n    integer :: n\n\n    rc = ESMF_RC_NOT_FOUND\n\n    if (present(location)) location = lbound(fieldList,1) - 1\n    if (present(fillValue)) fillValue = ESMF_MISSING_VALUE\n\n    do n=lbound(fieldList,1),ubound(fieldList,1)\n      if (fieldList(n)%sd_name .eq. standardName) then\n        if (present(location)) location = n\n        if (present(fillValue)) fillValue = fieldList(n)%vl_fillv\n        rc = ESMF_SUCCESS\n        return\n      end if\n    end do\n\n    if (ESMF_LogFoundError(rcToCheck=rc, &\n      msg=\"Field not found in fieldList \"//trim(standardName), &\n      line=__LINE__, &\n      file=__FILE__)) &\n      return  ! bail out\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"field_find_statename\"\n  subroutine field_find_statename(fieldList, stateName, location, &\n  fillValue, rc)\n    type(cap_fld_type), intent(in)          :: fieldList(:)\n    character(len=64), intent(in)           :: stateName\n    integer, intent(out), optional          :: location\n    real(ESMF_KIND_R8),intent(out),optional :: fillValue\n    integer, intent(out)                    :: rc\n    ! local variables\n    integer :: n\n\n    rc = ESMF_RC_NOT_FOUND\n\n    if (present(location)) location = lbound(fieldList,1) - 1\n    if (present(fillValue)) fillValue = ESMF_MISSING_VALUE\n\n    do n=lbound(fieldList,1),ubound(fieldList,1)\n      if (fieldList(n)%st_name .eq. stateName) then\n        if (present(location)) location = n\n        if (present(fillValue)) fillValue = fieldList(n)%vl_fillv\n        rc = ESMF_SUCCESS\n        return\n      end if\n    end do\n\n    if (ESMF_LogFoundError(rcToCheck=rc, &\n      msg=\"Field not found in fieldList \"//trim(stateName), &\n      line=__LINE__, &\n      file=__FILE__)) &\n      return  ! bail out\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"field_create\"\n  function field_create(fld_name,grid,did,memflg,rc)\n    ! return value\n    type(ESMF_Field) :: field_create\n    ! arguments\n    character(*), intent(in)      :: fld_name\n    type(ESMF_Grid), intent(in)   :: grid\n    integer, intent(in)           :: did\n    type(memory_flag), intent(in) :: memflg\n    integer,          intent(out) :: rc\n    ! local variables\n    character(len=16)       :: cmemflg\n\n\n    rc = ESMF_SUCCESS\n\n    if (memflg .eq. MEMORY_POINTER) then\n      select case (trim(fld_name))\n        case ('smc')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%smc(:,:,:), gridToFieldMap=(/1,2/), &\n            ungriddedLBound=(/1/), ungriddedUBound=(/nlst(did)%nsoil/), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('slc')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%sh2ox(:,:,:), gridToFieldMap=(/1,2/), &\n            ungriddedLBound=(/1/), ungriddedUBound=(/nlst(did)%nsoil/), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('stc')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%stc(:,:,:), gridToFieldMap=(/1,2/), &\n            ungriddedLBound=(/1/), ungriddedUBound=(/nlst(did)%nsoil/), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('sh2ox1')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%sh2ox(:,:,1), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('sh2ox2')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%sh2ox(:,:,2), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('sh2ox3')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%sh2ox(:,:,3), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('sh2ox4')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%sh2ox(:,:,4), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('smc1')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%smc(:,:,1), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('smc2')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%smc(:,:,2), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('smc3')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%smc(:,:,3), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('smc4')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%smc(:,:,4), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('smcmax1')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%smcmax1, &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('stc1')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%stc(:,:,1), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('stc2')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%stc(:,:,2), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('stc3')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%stc(:,:,3), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('stc4')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%stc(:,:,4), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('vegtyp')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%vegtyp, &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('sfchead')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%overland%control%surface_water_head_lsm, &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case ('infxsrt')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%infxsrt, &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n        case ('soldrain')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            farray=rt_domain(did)%soldrain, &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n        case default\n          call ESMF_LogSetError(ESMF_FAILURE, &\n            msg=METHOD//\": Field hookup missing: \"//trim(fld_name), &\n            file=FILENAME,rcToReturn=rc)\n          return  ! bail out\n      end select\n    elseif (memflg .eq. MEMORY_COPY) then\n      select case (trim(fld_name))\n        case ('smc','slc','stc')\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            typekind=ESMF_TYPEKIND_FIELD, gridToFieldMap=(/1,2/), &\n            ungriddedLBound=(/1/), ungriddedUBound=(/nlst(did)%nsoil/), &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if(ESMF_STDERRORCHECK(rc)) return ! bail out\n        case default\n          field_create = ESMF_FieldCreate(name=fld_name, grid=grid, &\n            typekind=ESMF_TYPEKIND_FIELD, &\n            indexflag=ESMF_INDEX_DELOCAL, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n      end select\n      call ESMF_FieldFill(field_create, dataFillScheme=\"const\", &\n        const1=ESMF_MISSING_VALUE, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n    else\n      cmemflg = memflg\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=METHOD//\": Field memory flag unknown: \"//trim(cmemflg), &\n        file=FILENAME,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n  end function\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"state_fill_uniform\"\n  subroutine state_fill_uniform(state, fillValue, rc)\n    type(ESMF_State), intent(inout)        :: state\n    real(ESMF_KIND_R8), intent(in)         :: fillValue\n    integer, intent(out)                   :: rc\n    ! local variables\n    integer                                :: n\n    integer                                :: itemCount\n    character(len=64),allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable :: itemTypeList(:)\n    type(ESMF_Field)                       :: field\n    integer                                :: stat\n\n    rc = ESMF_SUCCESS\n\n    call ESMF_StateGet(state,itemCount=itemCount, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(itemNameList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item name memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    allocate(itemTypeList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item type memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n\n    call ESMF_StateGet(state,itemNameList=itemNameList, &\n      itemTypeList=itemTypeList,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    do n=1, itemCount\n      if (itemTypeList(n) == ESMF_STATEITEM_FIELD) then\n        call ESMF_StateGet(state, field=field, &\n          itemName=itemNameList(n),rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call ESMF_FieldFill(field, dataFillScheme=\"const\", &\n          const1=fillValue, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call NUOPC_SetAttribute(field, name=\"Updated\", value=\"true\", rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n    enddo\n\n    deallocate(itemNameList)\n    deallocate(itemTypeList)\n\n  end subroutine state_fill_uniform\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"state_fill_prescribe\"\n  subroutine state_fill_prescribe(state, fieldList, rc)\n    type(ESMF_State), intent(inout)        :: state\n    type(cap_fld_type), intent(in)         :: fieldList(:)\n    integer, intent(out)                   :: rc\n    ! local variables\n    integer                                :: n\n    integer                                :: itemCount\n    character(len=64),allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable :: itemTypeList(:)\n    type(ESMF_Field)                       :: field\n    real(ESMF_KIND_R8)                     :: filVal\n    integer                                :: stat\n\n    rc = ESMF_SUCCESS\n\n    call ESMF_StateGet(state,itemCount=itemCount, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(itemNameList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item name memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    allocate(itemTypeList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item type memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n\n    call ESMF_StateGet(state,itemNameList=itemNameList, &\n      itemTypeList=itemTypeList,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    do n=1, itemCount\n      if (itemTypeList(n) == ESMF_STATEITEM_FIELD) then\n        call field_find_statename(fieldList, &\n          stateName=itemNameList(n), fillValue=filVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call ESMF_StateGet(state, field=field, &\n          itemName=itemNameList(n),rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call ESMF_FieldFill(field, dataFillScheme=\"const\", &\n          const1=filVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call NUOPC_SetAttribute(field, name=\"Updated\", value=\"true\", rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n    enddo\n\n    deallocate(itemNameList)\n    deallocate(itemTypeList)\n\n  end subroutine state_fill_prescribe\n\n !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"state_fill_file\"\n  subroutine state_fill_file(state, filePrefix, rc)\n    type(ESMF_State), intent(inout) :: state\n    character(len=*), intent(in)    :: filePrefix\n    integer, intent(out)            :: rc\n    ! local variables\n    integer                                :: n\n    integer                                :: itemCount\n    character(len=64),allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable :: itemTypeList(:)\n    type(ESMF_Field)                       :: field\n    character(len=64)                      :: fldName\n    integer                                :: stat\n\n    rc = ESMF_SUCCESS\n\n    call ESMF_StateGet(state,itemCount=itemCount, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(itemNameList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item name memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    allocate(itemTypeList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item type memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n\n    call ESMF_StateGet(state,itemNameList=itemNameList, &\n      itemTypeList=itemTypeList,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    do n=1, itemCount\n      if ( itemTypeList(n) == ESMF_STATEITEM_FIELD) then\n        call ESMF_StateGet(state,field=field, &\n          itemName=itemNameList(n),rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call NUOPC_GetAttribute(field, name=\"StandardName\", &\n          value=fldName, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call ESMF_FieldRead(field, variableName=trim(fldName), &\n          fileName=trim(filePrefix)//\"_\"//trim(itemNameList(n))//\".nc\", &\n          iofmt=ESMF_IOFMT_NETCDF, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call NUOPC_SetAttribute(field, name=\"Updated\", value=\"true\", rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n      endif\n    enddo\n\n    deallocate(itemNameList)\n    deallocate(itemTypeList)\n\n  end subroutine state_fill_file\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"state_copy_tohyd\"\n  subroutine state_copy_tohyd(state, did, rc)\n    type(ESMF_State), intent(inout) :: state\n    integer, intent(in)             :: did\n    integer, intent(out)            :: rc\n    ! local variables\n    integer                                :: n\n    integer                                :: itemCount\n    character(len=64),allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable :: itemTypeList(:)\n    type(ESMF_Field)                       :: field\n    integer                                :: dimCount\n    real(ESMF_KIND_FIELD), pointer         :: farrayPtr2d(:,:)\n    real(ESMF_KIND_FIELD), pointer         :: farrayPtr3d(:,:,:)\n    integer                                :: stat\n\n    rc = ESMF_SUCCESS\n\n    call ESMF_StateGet(state,itemCount=itemCount, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(itemNameList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item name memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    allocate(itemTypeList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item type memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n\n    call ESMF_StateGet(state,itemNameList=itemNameList, &\n      itemTypeList=itemTypeList,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    do n=1, itemCount\n      if (itemTypeList(n) == ESMF_STATEITEM_FIELD) then\n        call ESMF_StateGet(state, field=field, &\n          itemName=itemNameList(n),rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call ESMF_FieldGet(field, dimCount=dimCount, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        if (dimCount .eq. 2) then\n          call ESMF_FieldGet(field, farrayPtr=farrayPtr2d, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n        elseif (dimCount .eq. 3) then\n          call ESMF_FieldGet(field, farrayPtr=farrayPtr3d, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n        else\n          call ESMF_LogSetError(ESMF_FAILURE, &\n            msg=METHOD//\": dimCount is not supported.\", &\n            file=FILENAME,rcToReturn=rc)\n          return  ! bail out\n        endif\n        select case (ItemNameList(n))\n          case ('smc')\n            rt_domain(did)%smc = farrayPtr3d\n          case ('slc')\n            rt_domain(did)%sh2ox = farrayPtr3d\n          case ('stc')\n            rt_domain(did)%stc = farrayPtr3d\n          case ('sh2ox1')\n            rt_domain(did)%sh2ox(:,:,1) = farrayPtr2d\n          case ('sh2ox2')\n            rt_domain(did)%sh2ox(:,:,2) = farrayPtr2d\n          case ('sh2ox3')\n            rt_domain(did)%sh2ox(:,:,3) = farrayPtr2d\n          case ('sh2ox4')\n            rt_domain(did)%sh2ox(:,:,4) = farrayPtr2d\n          case ('smc1')\n            rt_domain(did)%smc(:,:,1) = farrayPtr2d\n          case ('smc2')\n            rt_domain(did)%smc(:,:,2) = farrayPtr2d\n          case ('smc3')\n            rt_domain(did)%smc(:,:,3) = farrayPtr2d\n          case ('smc4')\n            rt_domain(did)%smc(:,:,4) = farrayPtr2d\n          case ('smcmax1')\n            rt_domain(did)%smcmax1 = farrayPtr2d\n          case ('stc1')\n            rt_domain(did)%stc(:,:,1) = farrayPtr2d\n          case ('stc2')\n            rt_domain(did)%stc(:,:,2) = farrayPtr2d\n          case ('stc3')\n            rt_domain(did)%stc(:,:,3) = farrayPtr2d\n          case ('stc4')\n            rt_domain(did)%stc(:,:,4) = farrayPtr2d\n          case ('vegtyp')\n            rt_domain(did)%vegtyp = farrayPtr2d\n          case ('sfchead')\n            rt_domain(did)%overland%control%surface_water_head_lsm = &\n              farrayPtr2d\n          case ('infxsrt')\n            rt_domain(did)%infxsrt = farrayPtr2d\n          case ('soldrain')\n            rt_domain(did)%soldrain = farrayPtr2d\n          case default\n            call ESMF_LogSetError(ESMF_FAILURE, &\n              msg=METHOD//\": Field hookup missing: \"//trim(itemNameList(n)), &\n              file=FILENAME,rcToReturn=rc)\n            return  ! bail out\n        endselect\n      endif\n    enddo\n\n    deallocate(itemNameList)\n    deallocate(itemTypeList)\n\n  end subroutine state_copy_tohyd\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"state_copy_frhyd\"\n  subroutine state_copy_frhyd(state, did, rc)\n    type(ESMF_State), intent(inout)         :: state\n    integer, intent(in)                     :: did\n    integer, intent(out)                    :: rc\n    ! local variables\n    integer                                :: n\n    integer                                :: itemCount\n    character(len=64),allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable :: itemTypeList(:)\n    type(ESMF_Field)                       :: field\n    integer                                :: dimCount\n    real(ESMF_KIND_FIELD), pointer         :: farrayPtr2d(:,:)\n    real(ESMF_KIND_FIELD), pointer         :: farrayPtr3d(:,:,:)\n    integer                                :: stat\n    character(len=16)                      :: cmissingv_flag\n\n    rc = ESMF_SUCCESS\n\n    call ESMF_StateGet(state,itemCount=itemCount, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(itemNameList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item name memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    allocate(itemTypeList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item type memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n\n    call ESMF_StateGet(state,itemNameList=itemNameList, &\n      itemTypeList=itemTypeList,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    do n=1, itemCount\n      if (itemTypeList(n) == ESMF_STATEITEM_FIELD) then\n        call ESMF_StateGet(state, field=field, &\n          itemName=itemNameList(n),rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        call ESMF_FieldGet(field, dimCount=dimCount, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        if (dimCount .eq. 2) then\n          call ESMF_FieldGet(field, farrayPtr=farrayPtr2d, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n        elseif (dimCount .eq. 3) then\n          call ESMF_FieldGet(field, farrayPtr=farrayPtr3d, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n        else\n          call ESMF_LogSetError(ESMF_FAILURE, &\n            msg=METHOD//\": dimCount is not supported.\", &\n            file=FILENAME,rcToReturn=rc)\n          return  ! bail out\n        endif\n        select case (ItemNameList(n))\n          case ('smc')\n            farrayPtr3d = rt_domain(did)%smc\n          case ('slc')\n            farrayPtr3d = rt_domain(did)%sh2ox\n          case ('stc')\n            farrayPtr3d = rt_domain(did)%stc\n          case ('sh2ox1')\n            farrayPtr2d = rt_domain(did)%sh2ox(:,:,1)\n          case ('sh2ox2')\n            farrayPtr2d = rt_domain(did)%sh2ox(:,:,2)\n          case ('sh2ox3')\n            farrayPtr2d = rt_domain(did)%sh2ox(:,:,3)\n          case ('sh2ox4')\n            farrayPtr2d = rt_domain(did)%sh2ox(:,:,4)\n          case ('smc1')\n            farrayPtr2d = rt_domain(did)%smc(:,:,1)\n          case ('smc2')\n            farrayPtr2d = rt_domain(did)%smc(:,:,2)\n          case ('smc3')\n            farrayPtr2d = rt_domain(did)%smc(:,:,3)\n          case ('smc4')\n            farrayPtr2d = rt_domain(did)%smc(:,:,4)\n          case ('smcmax1')\n            farrayPtr2d = rt_domain(did)%smcmax1\n          case ('stc1')\n            farrayPtr2d = rt_domain(did)%stc(:,:,1)\n          case ('stc2')\n            farrayPtr2d = rt_domain(did)%stc(:,:,2)\n          case ('stc3')\n            farrayPtr2d = rt_domain(did)%stc(:,:,3)\n          case ('stc4')\n            farrayPtr2d = rt_domain(did)%stc(:,:,4)\n          case ('vegtyp')\n            farrayPtr2d = rt_domain(did)%vegtyp\n          case ('sfchead')\n            farrayPtr2d = rt_domain(did)%overland%control%surface_water_head_lsm\n          case ('infxsrt')\n            farrayPtr2d = rt_domain(did)%infxsrt\n          case ('soldrain')\n            farrayPtr2d = rt_domain(did)%soldrain\n          case default\n            call ESMF_LogSetError(ESMF_FAILURE, &\n              msg=METHOD//\": Field hookup missing: \"//trim(itemNameList(n)), &\n              file=FILENAME,rcToReturn=rc)\n            return  ! bail out\n        end select\n      endif\n    enddo\n\n    deallocate(itemNameList)\n    deallocate(itemTypeList)\n\n  end subroutine state_copy_frhyd\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"state_check_missing\"\n  subroutine state_check_missing(state, did, rc)\n    type(ESMF_State), intent(inout)   :: state\n    integer, intent(in)               :: did\n    integer, intent(out)              :: rc\n    ! local variables\n    integer                                :: n\n    integer                                :: itemCount\n    character(len=64),allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable :: itemTypeList(:)\n    real(ESMF_KIND_R8), parameter          :: chkVal = real(ESMF_MISSING_VALUE)\n    logical                                :: missng\n    integer                                :: stat\n\n    rc = ESMF_SUCCESS\n\n    call ESMF_StateGet(state,itemCount=itemCount, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(itemNameList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item name memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    allocate(itemTypeList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item type memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    call ESMF_StateGet(state,itemNameList=itemNameList, &\n      itemTypeList=itemTypeList,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    do n=1, itemCount\n      if (itemTypeList(n) == ESMF_STATEITEM_FIELD) then\n        missng = .FALSE.\n        select case (ItemNameList(n))\n          case ('smc')\n            missng = any(rt_domain(did)%smc.eq.chkVal)\n          case ('slc')\n            missng = any(rt_domain(did)%sh2ox.eq.chkVal)\n          case ('stc')\n            missng = any(rt_domain(did)%stc.eq.chkVal)\n          case ('sh2ox1')\n            missng = any(rt_domain(did)%sh2ox(:,:,1).eq.chkVal)\n          case ('sh2ox2')\n            missng = any(rt_domain(did)%sh2ox(:,:,2).eq.chkVal)\n          case ('sh2ox3')\n            missng = any(rt_domain(did)%sh2ox(:,:,3).eq.chkVal)\n          case ('sh2ox4')\n            missng = any(rt_domain(did)%sh2ox(:,:,4).eq.chkVal)\n          case ('smc1')\n            missng = any(rt_domain(did)%smc(:,:,1).eq.chkVal)\n          case ('smc2')\n            missng = any(rt_domain(did)%smc(:,:,2).eq.chkVal)\n          case ('smc3')\n            missng = any(rt_domain(did)%smc(:,:,3).eq.chkVal)\n          case ('smc4')\n            missng = any(rt_domain(did)%smc(:,:,4).eq.chkVal)\n          case ('smcmax1')\n            missng = any(rt_domain(did)%smcmax1.eq.chkVal)\n          case ('stc1')\n            missng = any(rt_domain(did)%stc(:,:,1).eq.chkVal)\n          case ('stc2')\n            missng = any(rt_domain(did)%stc(:,:,2).eq.chkVal)\n          case ('stc3')\n            missng = any(rt_domain(did)%stc(:,:,3).eq.chkVal)\n          case ('stc4')\n            missng = any(rt_domain(did)%stc(:,:,4).eq.chkVal)\n          case ('vegtyp')\n            missng = any(rt_domain(did)%vegtyp.eq.chkVal)\n          case ('sfchead')\n            missng = any(rt_domain(did)%overland%control%surface_water_head_lsm &\n              .eq.chkVal)\n          case ('infxsrt')\n            missng = any(rt_domain(did)%infxsrt.eq.chkVal)\n          case ('soldrain')\n            missng = any(rt_domain(did)%soldrain.eq.chkVal)\n          case default\n            call ESMF_LogSetError(ESMF_FAILURE, &\n              msg=METHOD//\": Field hookup missing: \"//trim(itemNameList(n)), &\n              file=FILENAME,rcToReturn=rc)\n            return  ! bail out\n        endselect\n        if (missng) then\n          call ESMF_LogSetError(ESMF_FAILURE, &\n            msg=METHOD//\": Missing value: \"//trim(itemNameList(n)), &\n            file=FILENAME,rcToReturn=rc)\n          return  ! bail out\n        endif\n      endif\n    enddo\n    deallocate(itemNameList)\n    deallocate(itemTypeList)\n\n  end subroutine state_check_missing\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"state_prescribe_missing\"\n  subroutine state_prescribe_missing(state, did, fieldList, rc)\n    type(ESMF_State), intent(inout)   :: state\n    integer, intent(in)               :: did\n    type(cap_fld_type), intent(in)    :: fieldList(:)\n    integer, intent(out)              :: rc\n    ! local variables\n    integer                                :: n\n    integer                                :: itemCount\n    character(len=64),allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable :: itemTypeList(:)\n    real(ESMF_KIND_R8), parameter          :: chkVal = real(ESMF_MISSING_VALUE)\n    real(ESMF_KIND_R8)                     :: filVal\n    integer                                :: stat\n\n    rc = ESMF_SUCCESS\n\n    call ESMF_StateGet(state,itemCount=itemCount, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(itemNameList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item name memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    allocate(itemTypeList(itemCount), stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=\"Allocation of state item type memory failed.\", &\n      line=__LINE__, file=__FILE__)) return  ! bail out\n    call ESMF_StateGet(state,itemNameList=itemNameList, &\n      itemTypeList=itemTypeList,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    do n=1, itemCount\n      if (itemTypeList(n) == ESMF_STATEITEM_FIELD) then\n        call field_find_statename(fieldList, &\n          stateName=itemNameList(n), fillValue=filVal, rc=rc)\n        if (ESMF_STDERRORCHECK(rc)) return\n        select case (itemNameList(n))\n          case ('smc')\n            where (rt_domain(did)%smc.eq.chkVal) &\n              rt_domain(did)%smc = filVal\n          case ('slc')\n            where (rt_domain(did)%sh2ox.eq.chkVal) &\n              rt_domain(did)%sh2ox = filVal\n          case ('stc')\n            where (rt_domain(did)%stc.eq.chkVal) &\n              rt_domain(did)%stc = filVal\n          case ('sh2ox1')\n            where (rt_domain(did)%sh2ox(:,:,1).eq.chkVal) &\n              rt_domain(did)%sh2ox(:,:,1) = filVal\n          case ('sh2ox2')\n            where (rt_domain(did)%sh2ox(:,:,2).eq.chkVal) &\n              rt_domain(did)%sh2ox(:,:,2) = filVal\n          case ('sh2ox3')\n            where (rt_domain(did)%sh2ox(:,:,3).eq.chkVal) &\n              rt_domain(did)%sh2ox(:,:,3) = filVal\n          case ('sh2ox4')\n            where (rt_domain(did)%sh2ox(:,:,4).eq.chkVal) &\n              rt_domain(did)%sh2ox(:,:,4) = filVal\n          case ('smc1')\n            where (rt_domain(did)%smc(:,:,1).eq.chkVal) &\n              rt_domain(did)%smc(:,:,1) = filVal\n          case ('smc2')\n            where (rt_domain(did)%smc(:,:,2).eq.chkVal) &\n              rt_domain(did)%smc(:,:,2) = filVal\n          case ('smc3')\n            where (rt_domain(did)%smc(:,:,3).eq.chkVal) &\n              rt_domain(did)%smc(:,:,3) = filVal\n          case ('smc4')\n            where (rt_domain(did)%smc(:,:,4).eq.chkVal) &\n              rt_domain(did)%smc(:,:,4) = filVal\n          case ('smcmax1')\n            where (rt_domain(did)%smcmax1.eq.chkVal) &\n              rt_domain(did)%smcmax1 = filVal\n          case ('stc1')\n            where (rt_domain(did)%stc(:,:,1).eq.chkVal) &\n              rt_domain(did)%stc(:,:,1) = filVal\n          case ('stc2')\n            where (rt_domain(did)%stc(:,:,2).eq.chkVal) &\n              rt_domain(did)%stc(:,:,2) = filVal\n          case ('stc3')\n            where (rt_domain(did)%stc(:,:,3).eq.chkVal) &\n              rt_domain(did)%stc(:,:,3) = filVal\n          case ('stc4')\n            where (rt_domain(did)%stc(:,:,4).eq.chkVal) &\n              rt_domain(did)%stc(:,:,4) = filVal\n          case ('vegtyp')\n            where (rt_domain(did)%vegtyp.eq.chkVal) &\n              rt_domain(did)%vegtyp = filVal\n          case ('sfchead')\n            where (rt_domain(did)%overland%control%surface_water_head_lsm &\n              .eq.chkVal) &\n              rt_domain(did)%overland%control%surface_water_head_lsm = filVal\n          case ('infxsrt')\n            where (rt_domain(did)%infxsrt.eq.chkVal) &\n              rt_domain(did)%infxsrt = filVal\n          case ('soldrain')\n            where (rt_domain(did)%soldrain.eq.chkVal) &\n              rt_domain(did)%soldrain = filVal\n          case default\n            call ESMF_LogSetError(ESMF_FAILURE, &\n              msg=METHOD//\": Field hookup missing: \"//trim(itemNameList(n)), &\n              file=FILENAME,rcToReturn=rc)\n            return  ! bail out\n        end select\n      endif\n    enddo\n\n    deallocate(itemNameList)\n    deallocate(itemTypeList)\n\n  end subroutine state_prescribe_missing\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"model_debug\"\n  subroutine model_debug(state, did, memflg, filePrefix, rc)\n    type(ESMF_State), intent(inout)   :: state\n    integer, intent(in)               :: did\n    type(memory_flag)                 :: memflg\n    character(len=*)                  :: filePrefix\n    integer, intent(out)              :: rc\n    ! local variables\n    integer                                :: n\n    integer                                :: itemCount\n    character(len=64),allocatable          :: itemNameList(:)\n    type(ESMF_StateItem_Flag), allocatable :: itemTypeList(:)\n    type(ESMF_Field)                       :: cpyfield, outfield\n    type(ESMF_Grid)                        :: grid\n    integer                                :: stat\n    character(len=16)                      :: cmemflg\n\n    rc = ESMF_SUCCESS\n\n    if (memflg .eq. MEMORY_POINTER) then\n      call NUOPC_Write(state, &\n        fileNamePrefix=filePrefix, overwrite=.true., &\n        status=ESMF_FILESTATUS_REPLACE, timeslice=1, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    elseif(memflg .eq. MEMORY_COPY) then\n      call ESMF_StateGet(state,itemCount=itemCount, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return ! bail out\n\n      allocate(itemNameList(itemCount), stat=stat)\n      if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n        msg=\"Allocation of state item name memory failed.\", &\n        line=__LINE__, file=__FILE__)) return  ! bail out\n      allocate(itemTypeList(itemCount), stat=stat)\n      if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n        msg=\"Allocation of state item type memory failed.\", &\n        line=__LINE__, file=__FILE__)) return  ! bail out\n      call ESMF_StateGet(state,itemNameList=itemNameList, &\n        itemTypeList=itemTypeList,rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n\n      do n=1, itemCount\n        if (itemTypeList(n) == ESMF_STATEITEM_FIELD) then\n          call ESMF_StateGet(state, field=cpyfield, &\n            itemName=itemNameList(n),rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n          call ESMF_FieldGet(cpyfield, grid=grid, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n          outfield = field_create(itemNameList(n), grid=grid, did=did, &\n            memflg=MEMORY_POINTER, rc=rc)\n          call ESMF_FieldWrite(outfield, variableName=itemNameList(n), &\n            fileName=trim(filePrefix)//\"_\"//trim(itemNameList(n))//\".nc\", &\n            iofmt=ESMF_IOFMT_NETCDF, rc=rc)\n          call ESMF_FieldDestroy(outfield, rc=rc)\n          if (ESMF_STDERRORCHECK(rc)) return\n        endif\n      enddo\n      deallocate(itemNameList)\n      deallocate(itemTypeList)\n    else\n      cmemflg = memflg\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=METHOD//\": Field memory flag unknown: \"//trim(cmemflg), &\n        file=FILENAME,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n  end subroutine model_debug\n\n  !-----------------------------------------------------------------------------\n\n\nend module wrfhydro_nuopc_fields\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/WRFHydro_NUOPC_Flags.F90",
    "content": "#define FILENAME \"WRFHydro_NUOPC_Flags.F90\"\n#define MODNAME \"wrfhydro_nuopc_flags\"\n#include \"WRFHydro_NUOPC_Macros.h\"\n\nmodule wrfhydro_nuopc_flags\n! !MODULE: wrfhydro_nuopc_flags\n!\n! !DESCRIPTION:\n!   This module controls WRFHYDRO configuration flags for NUOPC cap\n!\n! !REVISION HISTORY:\n!  21Sep23    Dan Rosen  Initial Specification\n!\n! !USES:\n  use ESMF, only: ESMF_UtilStringUpperCase, ESMF_SUCCESS\n\n  implicit none\n\n  private\n\n  type memory_flag\n    sequence\n    private\n      integer :: mem\n  end type memory_flag\n\n  type(memory_flag), parameter ::     &\n    MEMORY_ERROR   = memory_flag(-1), &\n    MEMORY_POINTER = memory_flag(0),  &\n    MEMORY_COPY    = memory_flag(1)\n\n  type fillv_flag\n    sequence\n    private\n      integer :: fillv\n  end type fillv_flag\n\n  type(fillv_flag), parameter ::       &\n    FILLV_ERROR      = fillv_flag(-1), &\n    FILLV_MISSING    = fillv_flag(0),  &\n    FILLV_ZERO       = fillv_flag(1),  &\n    FILLV_PRESCRIBE  = fillv_flag(2),  &\n    FILLV_MODEL      = fillv_flag(3),  &\n    FILLV_DEPENDENCY = fillv_flag(4),  &\n    FILLV_FILE       = fillv_flag(5)\n\n  type checkclock_flag\n    sequence\n    private\n      integer :: checkclock\n  end type checkclock_flag\n\n  type(checkclock_flag), parameter ::       &\n    CHECKCLOCK_ERROR = checkclock_flag(-1), &\n    CHECKCLOCK_CURRT = checkclock_flag(0),  &\n    CHECKCLOCK_NEXTT = checkclock_flag(1),  &\n    CHECKCLOCK_NONE  = checkclock_flag(2)\n\n  type missingval_flag\n    sequence\n    private\n      integer :: missingval\n  end type missingval_flag\n\n  type(missingval_flag), parameter ::           &\n    MISSINGVAL_ERROR     = missingval_flag(-1), &\n    MISSINGVAL_IGNORE    = missingval_flag(0),  &\n    MISSINGVAL_FAIL      = missingval_flag(1),  &\n    MISSINGVAL_PRESCRIBE = missingval_flag(2)\n\n  public memory_flag\n  public fillv_flag\n  public checkclock_flag\n  public missingval_flag\n  public MEMORY_ERROR\n  public MEMORY_COPY\n  public MEMORY_POINTER\n  public FILLV_ERROR\n  public FILLV_ZERO\n  public FILLV_MISSING\n  public FILLV_PRESCRIBE\n  public FILLV_MODEL\n  public FILLV_DEPENDENCY\n  public FILLV_FILE\n  public CHECKCLOCK_ERROR\n  public CHECKCLOCK_CURRT\n  public CHECKCLOCK_NEXTT\n  public CHECKCLOCK_NONE\n  public MISSINGVAL_ERROR\n  public MISSINGVAL_IGNORE\n  public MISSINGVAL_FAIL\n  public MISSINGVAL_PRESCRIBE\n\n  public operator(==), assignment(=)\n\n  interface operator (==)\n    module procedure memory_eq\n    module procedure fillv_eq\n    module procedure checkclock_eq\n    module procedure missingval_eq\n  end interface\n\n  interface assignment (=)\n    module procedure memory_toString\n    module procedure memory_frString\n    module procedure fillv_toString\n    module procedure fillv_frString\n    module procedure checkclock_toString\n    module procedure checkclock_frString\n    module procedure missingval_toString\n    module procedure missingval_frString\n  end interface\n\n  !-----------------------------------------------------------------------------\n  contains\n  !-----------------------------------------------------------------------------\n\n  function memory_eq(val1, val2)\n    logical memory_eq\n    type(memory_flag), intent(in) :: val1, val2\n    memory_eq = (val1%mem == val2%mem)\n  end function memory_eq\n\n  !-----------------------------------------------------------------------------\n  subroutine memory_toString(string, val)\n    character(len=*), intent(out) :: string\n    type(memory_flag), intent(in) :: val\n    if (val == MEMORY_COPY) then\n      write(string,'(a)') 'MEMORY_COPY'\n    elseif (val == MEMORY_POINTER) then\n      write(string,'(a)') 'MEMORY_POINTER'\n    else\n      write(string,'(a)') 'MEMORY_ERROR'\n    endif\n  end subroutine memory_toString\n\n  !-----------------------------------------------------------------------------\n\n  subroutine memory_frString(val, string)\n    type(memory_flag), intent(out) :: val\n    character(len=*), intent(in) :: string\n    character(len=16) :: ustring\n    integer :: rc\n    ustring = ESMF_UtilStringUpperCase(string, rc=rc)\n    if (rc .ne. ESMF_SUCCESS) then\n      val = MEMORY_ERROR\n    elseif (ustring .eq. 'MEMORY_COPY') then\n      val = MEMORY_COPY\n    elseif (ustring .eq. 'MEMORY_POINTER') then\n      val = MEMORY_POINTER\n    else\n      val = MEMORY_ERROR\n    endif\n  end subroutine memory_frString\n\n  !-----------------------------------------------------------------------------\n\n  function fillv_eq(val1, val2)\n    logical fillv_eq\n    type(fillv_flag), intent(in) :: val1, val2\n    fillv_eq = (val1%fillv == val2%fillv)\n  end function fillv_eq\n\n  !-----------------------------------------------------------------------------\n\n  subroutine fillv_toString(string, val)\n    character(len=*), intent(out) :: string\n    type(fillv_flag), intent(in) :: val\n    if (val == FILLV_ZERO) then\n      write(string,'(a)') 'FILLV_ZERO'\n    elseif (val == FILLV_MISSING) then\n      write(string,'(a)') 'FILLV_MISSING'\n    elseif (val == FILLV_PRESCRIBE) then\n      write(string,'(a)') 'FILLV_PRESCRIBE'\n    elseif (val == FILLV_MODEL) then\n      write(string,'(a)') 'FILLV_MODEL'\n    elseif (val == FILLV_DEPENDENCY) then\n      write(string,'(a)') 'FILLV_DEPENDENCY'\n    elseif (val == FILLV_FILE) then\n      write(string,'(a)') 'FILLV_FILE'\n    else\n      write(string,'(a)') 'FILLV_ERROR'\n    endif\n  end subroutine fillv_toString\n\n  !-----------------------------------------------------------------------------\n\n  subroutine fillv_frString(val, string)\n    type(fillv_flag), intent(out) :: val\n    character(len=*), intent(in) :: string\n    character(len=16) :: ustring\n    integer :: rc\n    ustring = ESMF_UtilStringUpperCase(string, rc=rc)\n    if (rc .ne. ESMF_SUCCESS) then\n      val = FILLV_ERROR\n    elseif (ustring .eq. 'FILLV_ZERO') then\n      val = FILLV_ZERO\n    elseif (ustring .eq. 'FILLV_MISSING') then\n      val = FILLV_MISSING\n    elseif (ustring .eq. 'FILLV_PRESCRIBE') then\n      val = FILLV_PRESCRIBE\n    elseif (ustring .eq. 'FILLV_MODEL') then\n      val = FILLV_MODEL\n    elseif (ustring .eq. 'FILLV_DEPENDENCY') then\n      val = FILLV_DEPENDENCY\n    elseif (ustring .eq. 'FILLV_FILE') then\n      val = FILLV_FILE\n    else\n      val = FILLV_ERROR\n    endif\n  end subroutine fillv_frString\n\n  !-----------------------------------------------------------------------------\n\n  function checkclock_eq(val1, val2)\n    logical checkclock_eq\n    type(checkclock_flag), intent(in) :: val1, val2\n    checkclock_eq = (val1%checkclock == val2%checkclock)\n  end function checkclock_eq\n\n  !-----------------------------------------------------------------------------\n\n  subroutine checkclock_toString(string, val)\n    character(len=*), intent(out) :: string\n    type(checkclock_flag), intent(in) :: val\n    if (val == CHECKCLOCK_CURRT) then\n      write(string,'(a)') 'CHECKCLOCK_CURRT'\n    elseif (val == CHECKCLOCK_NEXTT) then\n      write(string,'(a)') 'CHECKCLOCK_NEXTT'\n    elseif (val == CHECKCLOCK_NONE) then\n      write(string,'(a)') 'CHECKCLOCK_NONE'\n    else\n      write(string,'(a)') 'CHECKCLOCK_ERROR'\n    endif\n  end subroutine checkclock_toString\n\n  !-----------------------------------------------------------------------------\n\n  subroutine checkclock_frString(val, string)\n    type(checkclock_flag), intent(out) :: val\n    character(len=*), intent(in) :: string\n    character(len=16) :: ustring\n    integer :: rc\n    ustring = ESMF_UtilStringUpperCase(string, rc=rc)\n    if (rc .ne. ESMF_SUCCESS) then\n      val = CHECKCLOCK_ERROR\n    elseif (ustring .eq. 'CHECKCLOCK_CURRT') then\n      val = CHECKCLOCK_CURRT\n    elseif (ustring .eq. 'CHECKCLOCK_NEXTT') then\n      val = CHECKCLOCK_NEXTT\n    elseif (ustring .eq. 'CHECKCLOCK_NONE') then\n      val = CHECKCLOCK_NONE\n    else\n      val = CHECKCLOCK_ERROR\n    endif\n  end subroutine checkclock_frString\n\n  !-----------------------------------------------------------------------------\n\n  function missingval_eq(val1, val2)\n    logical missingval_eq\n    type(missingval_flag), intent(in) :: val1, val2\n    missingval_eq = (val1%missingval == val2%missingval)\n  end function missingval_eq\n\n  !-----------------------------------------------------------------------------\n\n  subroutine missingval_toString(string, val)\n    character(len=*), intent(out) :: string\n    type(missingval_flag), intent(in) :: val\n    if (val == MISSINGVAL_IGNORE) then\n      write(string,'(a)') 'MISSINGVAL_IGNORE'\n    elseif (val == MISSINGVAL_FAIL) then\n      write(string,'(a)') 'MISSINGVAL_FAIL'\n    elseif (val == MISSINGVAL_PRESCRIBE) then\n      write(string,'(a)') 'MISSINGVAL_PRESCRIBE'\n    else\n      write(string,'(a)') 'MISSINGVAL_ERROR'\n    endif\n  end subroutine missingval_toString\n\n  !-----------------------------------------------------------------------------\n\n  subroutine missingval_frString(val, string)\n    type(missingval_flag), intent(out) :: val\n    character(len=*), intent(in) :: string\n    character(len=20) :: ustring\n    integer :: rc\n    ustring = ESMF_UtilStringUpperCase(string, rc=rc)\n    if (rc .ne. ESMF_SUCCESS) then\n      val = MISSINGVAL_ERROR\n    elseif (ustring .eq. 'MISSINGVAL_IGNORE') then\n      val = MISSINGVAL_IGNORE\n    elseif (ustring .eq. 'MISSINGVAL_FAIL') then\n      val = MISSINGVAL_FAIL\n    elseif (ustring .eq. 'MISSINGVAL_PRESCRIBE') then\n      val = MISSINGVAL_PRESCRIBE\n    else\n      val = MISSINGVAL_ERROR\n    endif\n  end subroutine missingval_frString\n\n  !-----------------------------------------------------------------------------\n\nend module\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/WRFHydro_NUOPC_Gluecode.F90",
    "content": "#define FILENAME \"WRFHydro_NUOPC_Gluecode\"\n#define MODNAME \"WRFHydro_NUOPC_Gluecode.F90\"\n#include \"WRFHydro_NUOPC_Macros.h\"\n\nmodule wrfhydro_nuopc_gluecode\n! !MODULE: wrfhydro_nuopc_gluecode\n!\n! !DESCRIPTION:\n!   This module connects NUOPC initialize, advance,\n!   and finalize to WRFHYDRO.\n!\n! !REVISION HISTORY:\n!  13Oct15    Dan Rosen  Initial Specification\n!\n! !USES:\n  use ESMF\n  use NUOPC\n  use WRFHydro_ESMF_Extensions\n  use module_mpp_land, only: &\n    HYDRO_COMM_WORLD, &\n    numprocs, &\n    global_nx, &\n    global_ny, &\n    startx, &\n    starty, &\n    local_nx_size, &\n    local_ny_size, &\n    log_map2d, &\n    mpp_land_par_ini, &\n    decompose_data_real, &\n    write_io_real, my_id, &\n    mpp_land_bcast_real1, &\n    IO_id, &\n    mpp_land_bcast_real, &\n    mpp_land_bcast_int1, &\n    MPP_LAND_INIT\n  use module_HYDRO_drv, only: &\n    HYDRO_ini, &\n    HYDRO_exe\n  use module_HYDRO_io, only: &\n    get_file_dimension\n  use module_CPL_LAND, only: &\n    CPL_LAND_INIT, &\n    cpl_outdate\n  use module_rt_data, only: &\n    rt_domain\n  use module_lsm_forcing, only: &\n    read_ldasout\n  use config_base, only: &\n    nlst, &\n    init_namelist_rt_field\n  use orchestrator_base\n  use wrfhydro_nuopc_fields\n  use wrfhydro_nuopc_flags\n\n  implicit none\n\n  private\n\n  public :: wrfhydro_nuopc_ini\n  public :: wrfhydro_nuopc_run\n  public :: wrfhydro_nuopc_fin\n  public :: WRFHYDRO_GridCreate\n  public :: WRFHYDRO_get_timestep\n  public :: WRFHYDRO_set_timestep\n  public :: WRFHYDRO_get_hgrid\n  public :: WRFHYDRO_get_restart\n\n  ! PARAMETERS\n  character(len=ESMF_MAXSTR) :: indir = 'WRFHYDRO_FORCING'\n  integer                    :: num_nests = UNINITIALIZED\n  integer                    :: num_tiles\n  integer                    :: nx_global(1)\n  integer                    :: ny_global(1)\n  integer                    :: x_start\n  integer                    :: x_end\n  integer                    :: y_start\n  integer                    :: y_end\n  integer                    :: nx_local\n  integer                    :: ny_local\n  integer                    :: sf_surface_physics = UNINITIALIZED\n\n  ! added to consider the adaptive time step from driver.\n  real                  :: dt0 = UNINITIALIZED\n  real                  :: dtrt_ter0 = UNINITIALIZED\n  real                  :: dtrt_ch0 = UNINITIALIZED\n  integer               :: dt_factor0 = UNINITIALIZED\n  integer               :: dt_factor = UNINITIALIZED\n  ! added for check soil moisture and soiltype\n  integer               :: checkSOIL_flag = UNINITIALIZED\n  ! added to track the driver clock\n  character(len=19)     :: startTimeStr = \"0000-00-00_00:00:00\"\n\n  type(ESMF_DistGrid)   :: WRFHYDRO_DistGrid ! One DistGrid created with ConfigFile dimensions\n  character(len=512)  :: logMsg\n\n  !-----------------------------------------------------------------------------\n  ! Model Glue Code\n  !-----------------------------------------------------------------------------\ncontains\n\n#undef METHOD\n#define METHOD \"wrfhydro_nuopc_ini\"\n\n  subroutine wrfhydro_nuopc_ini(did,vm,clock,forcingDir,rc)\n    integer, intent(in)                     :: did\n    type(ESMF_VM),intent(in)                :: vm\n    type(ESMF_Clock),intent(in)             :: clock\n    character(len=*)                        :: forcingDir\n    integer, intent(out)                    :: rc\n\n    ! local variables\n    integer                     :: localPet\n    integer                     :: stat\n    integer, allocatable        :: deBlockList(:,:,:)\n    type(ESMF_DistGridConnection), allocatable :: connectionList(:)\n    integer                     :: i\n    type(ESMF_Time)             :: startTime\n    type(ESMF_TimeInterval)     :: timeStep\n    real(ESMF_KIND_R8)          :: dt\n#ifdef DEBUG\n    character(ESMF_MAXSTR)      :: logMsg\n#endif\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    ! Set mpiCommunicator for WRFHYDRO\n    call ESMF_VMGet(vm, localPet=localPet, &\n      mpiCommunicator=HYDRO_COMM_WORLD, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    ! Set focing directory\n    indir=forcingDir\n\n    ! Get the models timestep\n    call ESMF_ClockGet(clock,timestep=timestep,startTime=startTime,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n    call ESMF_TimeIntervalGet(timestep,s_r8=dt,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n    call WRFHYDRO_TimeToString(startTime,timestr=startTimeStr,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    call orchestrator%init()\n\n    ! Set default namelist values\n    read (startTimeStr(1:4),\"(I)\")   nlst(did)%START_YEAR\n    read (startTimeStr(6:7),\"(I)\")   nlst(did)%START_MONTH\n    read (startTimeStr(9:10),\"(I)\")  nlst(did)%START_DAY\n    read (startTimeStr(12:13),\"(I)\") nlst(did)%START_HOUR\n    read (startTimeStr(15:16),\"(I)\") nlst(did)%START_MIN\n    nlst(did)%startdate(1:19) = startTimeStr(1:19)\n    nlst(did)%olddate(1:19)   = startTimeStr(1:19)\n    nlst(did)%dt = dt\n    cpl_outdate = startTimeStr(1:19)\n    nlst(did)%nsoil=4\n    allocate(nlst(did)%zsoil8(4),stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=METHOD//': Allocation of model soil depths memory failed.', &\n      file=FILENAME, rcToReturn=rc)) return ! bail out\n    nlst(did)%zsoil8(1:4)=(/-0.1,-0.4,-1.0,-2.0/)\n    nlst(did)%geo_static_flnm = \"geo_em.d01.nc\"\n    nlst(did)%geo_finegrid_flnm = \"fulldom_hires_hydrofile.d01.nc\"\n    nlst(did)%sys_cpl = 2\n    nlst(did)%IGRID = did\n    write(nlst(did)%hgrid,'(I1)') did\n\n    if(nlst(did)%dt .le. 0) then\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=METHOD//\": Timestep less than 1 is not supported!\", &\n        file=FILENAME,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n!    ! Read information from hydro.namelist config file\n     call init_namelist_rt_field(did)\n\n#if DEBUG\n    call WRFHYDRO_nlstLog(did,MODNAME,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n#endif\n\n    if(nlst(did)%nsoil .gt. 4) then\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=METHOD//\": Maximum soil levels supported is 4.\", &\n        file=FILENAME,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n    call get_file_dimension(fileName=nlst(did)%geo_static_flnm,&\n      ix=nx_global(1),jx=ny_global(1))\n    call MPP_LAND_INIT(nx_global(1),ny_global(1))\n\n#ifdef DEBUG\n    write (logMsg,\"(A,2(I0,A))\") MODNAME//\": Global Dimensions = (\", &\n      nx_global(1),\",\",ny_global(1),\")\"\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n#endif\n\n    call log_map2d()\n\n    call ESMF_VMBroadcast(vm, nx_global, count=1, rootPet=IO_id, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n    call ESMF_VMBroadcast(vm, ny_global, count=1, rootPet=IO_id, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    rt_domain(did)%ix = nx_global(1)\n    rt_domain(did)%jx = ny_global(1)\n\n    call MPP_LAND_PAR_INI(1,rt_domain(did)%ix,rt_domain(did)%jx,&\n         nlst(did)%AGGFACTRT)\n\n    call ESMF_VMBroadcast(vm, startx, count=numprocs, rootPet=IO_id, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n    call ESMF_VMBroadcast(vm, starty, count=numprocs, rootPet=IO_id, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n    call ESMF_VMBroadcast(vm, local_nx_size, count=numprocs, rootPet=IO_id, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n    call ESMF_VMBroadcast(vm, local_ny_size, count=numprocs, rootPet=IO_id, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(deBlockList(2,2,numprocs))\n    do i = 1, numprocs\n      deBlockList(:,1,i) = (/startx(i),starty(i)/)\n      deBlockList(:,2,i) = (/startx(i)+local_nx_size(i)-1, &\n                             starty(i)+local_ny_size(i)-1/)\n!      write (logMsg,\"(A,I0,A,4(I0,A))\") MODNAME//\": deBlockList \", i, \" = (\", &\n!        deBlockList(1,1,i),\":\",deBlockList(1,2,i),\",\", &\n!        deBlockList(2,1,i),\":\",deBlockList(2,2,i),\")\"\n!      call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n    enddo\n\n!    allocate(connectionList(1),stat=stat)\n!    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n!      msg=METHOD//': Allocation of connection list memory failed.', &\n!      file=FILENAME, rcToReturn=rc)) return ! bail out\n!    call ESMF_DistGridConnectionSet(connectionList(1), tileIndexA=1, &\n!      tileIndexB=1, positionVector=(/nx_global(1), 0/), rc=rc)\n!    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n\n    ! Create DistGrid based on WRFHDYRO Config NX,NY\n    WRFHYDRO_distgrid = ESMF_DistGridCreate( &\n      minIndex=(/1,1/), maxIndex=(/nx_global(1),ny_global(1)/), &\n!     indexflag = ESMF_INDEX_DELOCAL, &\n     deBlockList=deBlockList, &\n!     deLabelList=deLabelList, &\n!     delayout=delayout, &\n!     connectionList=connectionList, &\n      rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    deallocate(deBlockList)\n\n!   deallocate(connectionList,stat=stat)\n!   if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n!     msg=METHOD//': Deallocation of connection list memory failed.', &\n!     file=FILENAME,rcToReturn=rc)) return ! bail out\n\n    ! Get the Local Decomp Incides\n    call set_local_indices(rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": Enter CPL_LAND_INIT\", ESMF_LOGMSG_INFO)\n#endif\n    ! Initialize the internal Land <-> Hydro Coupling\n    call CPL_LAND_INIT(x_start, x_end, y_start, y_end)\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": Exit CPL_LAND_INIT\", ESMF_LOGMSG_INFO)\n#endif\n\n    ! Routing timestep set in HYDRO_ini\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": Enter HYDRO_ini\", ESMF_LOGMSG_INFO)\n#endif\n\n    if(sf_surface_physics .eq. 5) then\n      ! clm4\n      ! Use wrfinput vegetation type and soil type\n      call HYDRO_ini(ntime=1,did=did,ix0=1,jx0=1)\n    else\n      ! Use wrfinput vegetation type and soil type\n      call HYDRO_ini(ntime=1,did=did,ix0=nx_local,jx0=ny_local)\n    endif\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": Exit HYDRO_ini\", ESMF_LOGMSG_INFO)\n    call WRFHYDRO_domainLog(did,MODNAME,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n#endif\n\n    ! Override the clock configuration in hyro.namelist\n    read (startTimeStr(1:4),\"(I)\")   nlst(did)%START_YEAR\n    read (startTimeStr(6:7),\"(I)\")   nlst(did)%START_MONTH\n    read (startTimeStr(9:10),\"(I)\")  nlst(did)%START_DAY\n    read (startTimeStr(12:13),\"(I)\") nlst(did)%START_HOUR\n    read (startTimeStr(15:16),\"(I)\") nlst(did)%START_MIN\n    nlst(did)%startdate(1:19) = startTimeStr(1:19)\n    nlst(did)%olddate(1:19)   = startTimeStr(1:19)\n    nlst(did)%dt = dt\n    nlst(did)%nsoil=4\n    cpl_outdate = startTimeStr(1:19)\n\n    if(nlst(did)%dt .le. 0) then\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=METHOD//\": Timestep less than 1 is not supported!\", &\n        file=FILENAME,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n    ! Adjust the routing timestep and factor\n    ! At this point the coupling driver timestep is unknown\n    ! and uses WRFHYDRO Config as best guess\n    if(nlst(did)%dtrt_ter .ge. nlst(did)%dt) then\n       nlst(did)%dtrt_ter = nlst(did)%dt\n       dt_factor0 = 1\n    else\n       dt_factor = nlst(did)%dt/nlst(did)%dtrt_ter\n       if (dt_factor*nlst(did)%dtrt_ter .lt. nlst(did)%dt) &\n         nlst(did)%dtrt_ter = nlst(did)%dt/dt_factor\n       dt_factor0 = dt_factor\n    endif\n\n    if(nlst(did)%dtrt_ch .ge. nlst(did)%dt) then\n      nlst(did)%dtrt_ch = nlst(did)%dt\n      dt_factor0 = 1\n    else\n      dt_factor = nlst(did)%dt/nlst(did)%dtrt_ch\n      if(dt_factor*nlst(did)%dtrt_ch .lt. nlst(did)%dt) &\n        nlst(did)%dtrt_ch = nlst(did)%dt/dt_factor\n      dt_factor0 = dt_factor\n    endif\n\n    dt0 = nlst(did)%dt\n    dtrt_ter0 = nlst(did)%dtrt_ter\n    dtrt_ch0 = nlst(did)%dtrt_ch\n\n    RT_DOMAIN(did)%initialized = .true.\n\n    num_nests = num_nests + 1\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"wrfhydro_nuopc_run\"\n\n  subroutine wrfhydro_nuopc_run(did,lsm_forcings,clock,importState,&\n  exportState,rc)\n    integer, intent(in)                     :: did\n    logical, intent(in)                     :: lsm_forcings\n    type(ESMF_Clock),intent(in)             :: clock\n    type(ESMF_State),intent(inout)          :: importState\n    type(ESMF_State),intent(inout)          :: exportState\n    integer, intent(out)                    :: rc\n\n    ! local variables\n    type(ESMF_TimeInterval)     :: timeStep\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    if(.not. RT_DOMAIN(did)%initialized) then\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=\"WRHYDRO: Model has not been initialized!\", &\n        file=FILENAME,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n    call ESMF_ClockGet(clock, timeStep=timeStep, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    call WRFHYDRO_ClockToString(clock,timestr=cpl_outdate,rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n    nlst(did)%olddate(1:19) = cpl_outdate(1:19) ! Current time is the\n\n    nlst(did)%dt = WRFHYDRO_TimeIntervalGetReal(timeInterval=timeStep,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    if(nlst(did)%dt .le. 0) then\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=METHOD//\": Timestep less than 1 is not supported!\", &\n        file=FILENAME,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n    if((dt_factor0*nlst(did)%dtrt_ter) .ne. nlst(did)%dt) then   ! NUOPC driver time step changed.\n      call ESMF_LogWrite(METHOD//\": Driver timestep changed.\",ESMF_LOGMSG_INFO)\n      if(dtrt_ter0 .ge. nlst(did)%dt) then\n        nlst(did)%dtrt_ter = nlst(did)%dt\n        dt_factor0 = 1\n      else\n        dt_factor = nlst(did)%dt / dtrt_ter0\n        if(dt_factor*dtrt_ter0 .lt. nlst(did)%dt) &\n          nlst(did)%dtrt_ter = nlst(did)%dt / dt_factor\n        dt_factor0 = dt_factor\n      endif\n    endif\n\n    if((dt_factor0*nlst(did)%dtrt_ch) .ne. nlst(did)%dt) then   ! NUOPD driver time step changed.\n      call ESMF_LogWrite(METHOD//\": Driver timestep changed.\",ESMF_LOGMSG_INFO)\n      if(dtrt_ch0 .ge. nlst(did)%dt) then\n        nlst(did)%dtrt_ch = nlst(did)%dt\n        dt_factor0 = 1\n      else\n        dt_factor = nlst(did)%dt / dtrt_ch0\n        if(dt_factor*dtrt_ch0 .lt. nlst(did)%dt) &\n          nlst(did)%dtrt_ch = nlst(did)%dt / dt_factor\n        dt_factor0 = dt_factor\n      endif\n    endif\n\n    if(nlst(did)%SUBRTSWCRT .eq.0  .and. &\n      nlst(did)%OVRTSWCRT .eq. 0 .and. &\n      nlst(did)%GWBASESWCRT .eq. 0) then\n       call ESMF_LogWrite(METHOD//\": SUBRTSWCRT,OVRTSWCRT,GWBASESWCRT are zero!\", &\n            ESMF_LOGMSG_WARNING)\n      !call ESMF_LogSetError(ESMF_FAILURE, &\n      !  msg=METHOD//\": SUBRTSWCRT,OVRTSWCRT,GWBASESWCRT are zero!\", &\n      !  file=FILENAME,rcToReturn=rc)\n      !return  ! bail out\n    endif\n\n    if((.not. RT_DOMAIN(did)%initialized) .and. (nlst(did)%rst_typ .eq. 1) ) then\n      call ESMF_LogWrite(METHOD//\": Restart initial data from offline file.\", &\n        ESMF_LOGMSG_INFO)\n    else\n      if (.not. lsm_forcings) then\n        call read_ldasout(olddate=nlst(did)%olddate(1:19), &\n          hgrid=nlst(did)%hgrid, &\n          indir=trim(indir), dt=nlst(did)%dt, &\n          ix=rt_domain(did)%ix,jx=rt_domain(did)%jx, &\n          infxsrt=rt_domain(did)%infxsrt,soldrain=rt_domain(did)%soldrain)\n      endif\n    endif\n\n    ! Call the WRF-HYDRO run routine\n    call HYDRO_exe(did=did)\n\n    ! provide groundwater soil flux to WRF for fully coupled simulations (FERSCH 09/2014)\n    !if(nlst(did)%GWBASESWCRT .eq. 3 ) then\n      !Wei Yu: comment the following two lines. Not ready\n    !yw     qsgw(x_start(1):x_end(1),y_start(1):y_end(1)) = gw2d(did)%qsgw\n    !yw     config_flags%gwsoilcpl = nlst(did)%gwsoilcpl\n    !end if\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"wrfhydro_nuopc_fin\"\n\n  subroutine wrfhydro_nuopc_fin(did,rc)\n    ! ARGUMENTES\n    integer, intent(inout)      :: did\n    integer, intent(out)        :: rc\n\n    ! LOCAL VARIABLES\n    integer                     :: stat\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    ! WRF-Hydro finish routine cannot be called because it stops MPI\n\n!    DCR - Turned off to let the model deallocate memory\n!    deallocate(nlst(did)%zsoil8)\n!    if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n!      msg=METHOD//': Deallocation of model soil depth memory failed.', &\n!      file=FILENAME,rcToReturn=rc)) return ! bail out\n\n    RT_DOMAIN(did)%initialized = .false.\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_GridCreate\"\n\n  function WRFHYDRO_GridCreate(did,rc)\n    ! RETURN VALUE\n    type(ESMF_Grid) :: WRFHYDRO_GridCreate\n    ! ARGUMENTS\n    integer, intent(in)                     :: did\n    integer, intent(out)                    :: rc\n    ! LOCAL VARIABLES\n    integer                     :: stat\n    real                        :: min_lat, max_lat, min_lon, max_lon\n    real, allocatable           :: latitude(:,:), longitude(:,:)\n    integer, allocatable        :: mask(:,:)\n    integer                     :: lbnd(2),ubnd(2)\n    real(ESMF_KIND_COORD), pointer :: coordXcenter(:,:)\n    real(ESMF_KIND_COORD), pointer :: coordYcenter(:,:)\n    real(ESMF_KIND_COORD), pointer :: coordXcorner(:,:)\n    real(ESMF_KIND_COORD), pointer :: coordYcorner(:,:)\n    integer(ESMF_KIND_I4), pointer :: gridmask(:,:)\n    integer                     :: i,j, i1,j1\n    character(len=16)           :: xlat_corner_name, xlon_corner_name\n#ifdef DEBUG\n    character(ESMF_MAXSTR)      :: logMsg\n#endif\n\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    WRFHYDRO_GridCreate = ESMF_GridCreate(name='WRFHYDRO_Grid_'//trim(nlst(did)%hgrid), &\n      distgrid=WRFHYDRO_DistGrid, coordSys = ESMF_COORDSYS_SPH_DEG, &\n      coordTypeKind=ESMF_TYPEKIND_COORD, &\n!      gridEdgeLWidth=(/0,0/), gridEdgeUWidth=(/0,1/), &\n      rc = rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    ! CENTERS\n\n    ! Get Local Latitude (lat)\n    allocate(latitude(nx_local,ny_local),stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=METHOD//': Allocation of latitude memory failed.', &\n      file=FILENAME, rcToReturn=rc)) return ! bail out\n    call WRFHYDRO_ESMF_NetcdfReadIXJX(\"XLAT_M\",nlst(did)%geo_static_flnm, &\n      (/x_start,y_start/),latitude,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    ! Get Local Longitude (lon)\n    allocate(longitude(nx_local,ny_local),stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=METHOD//': Allocation of longitude memory failed.', &\n      file=FILENAME, rcToReturn=rc)) return ! bail out\n    call WRFHYDRO_ESMF_NetcdfReadIXJX(\"XLONG_M\",nlst(did)%geo_static_flnm, &\n      (/x_start,y_start/),longitude,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n#ifdef DEBUG\n    ! Print Local Lat Lon Lower Left / Upper Right Centers\n    write(logMsg,\"(A,4(F0.3,A))\") MODNAME//\": Center Coordinates = (\", &\n      longitude(1,1),\":\",longitude(nx_local,ny_local),\",\", &\n      latitude(1,1),\":\",latitude(nx_local,ny_local),\")\"\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n#endif\n\n    ! Add Center Coordinates to Grid\n    call ESMF_GridAddCoord(WRFHYDRO_GridCreate, staggerLoc=ESMF_STAGGERLOC_CENTER, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    call ESMF_GridGetCoord(WRFHYDRO_GridCreate, coordDim=1, localDE=0, &\n      staggerloc=ESMF_STAGGERLOC_CENTER, &\n      computationalLBound=lbnd, computationalUBound=ubnd, &\n      farrayPtr=coordXcenter, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n    call ESMF_GridGetCoord(WRFHYDRO_GridCreate, coordDim=2, localDE=0, &\n      staggerloc=ESMF_STAGGERLOC_CENTER, farrayPtr=coordYcenter, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    do j = lbnd(2),ubnd(2)\n    do i = lbnd(1),ubnd(1)\n      coordXcenter(i,j) = longitude(i,j)\n      coordYcenter(i,j) = latitude(i,j)\n    enddo\n    enddo\n\n    deallocate(latitude,longitude,stat=stat)\n    if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n      msg=METHOD//': Deallocation of longitude and latitude memory failed.', &\n      file=FILENAME,rcToReturn=rc)) return ! bail out\n\n    ! Get Local Mask\n    allocate(mask(nx_local,ny_local),stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=METHOD//': Allocation of mask memory failed.', &\n      file=FILENAME, rcToReturn=rc)) return ! bail out\n    call WRFHYDRO_ESMF_NetcdfReadIXJX(\"LANDMASK\",nlst(did)%geo_static_flnm, &\n      (/x_start,y_start/),mask,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    ! Add Grid Mask\n    call ESMF_GridAddItem(WRFHYDRO_GridCreate, itemFlag=ESMF_GRIDITEM_MASK, &\n      staggerLoc=ESMF_STAGGERLOC_CENTER, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n    ! Get pointer to Grid Mask array\n    call ESMF_GridGetItem(WRFHYDRO_GridCreate, itemflag=ESMF_GRIDITEM_MASK, &\n      localDE=0, &\n      staggerloc=ESMF_STAGGERLOC_CENTER, &\n      farrayPtr=gridmask, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return  ! bail out\n\n    do j = lbnd(2),ubnd(2)\n    do i = lbnd(1),ubnd(1)\n      gridmask(i,j) = mask(i,j)\n      gridmask(i,j) = mask(i,j)\n    enddo\n    enddo\n\n    deallocate(mask,stat=stat)\n    if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n      msg=METHOD//': Deallocation of mask memory failed.', &\n      file=FILENAME,rcToReturn=rc)) return ! bail out\n\n    ! CORNERS\n    ! The original WPS implementation used the _CORNER names\n    ! but it was then changes to the _C names.  Support both\n    ! options.\n    if (WRFHYDRO_ESMF_NetcdfIsPresent(\"XLAT_CORNER\",nlst(did)%geo_static_flnm) .AND. &\n         WRFHYDRO_ESMF_NetcdfIsPresent(\"XLONG_CORNER\",nlst(did)%geo_static_flnm)) then\n       xlat_corner_name = \"XLAT_CORNER\"\n       xlon_corner_name = \"XLONG_CORNER\"\n    else if (WRFHYDRO_ESMF_NetcdfIsPresent(\"XLAT_C\",nlst(did)%geo_static_flnm) .AND. &\n         WRFHYDRO_ESMF_NetcdfIsPresent(\"XLONG_C\",nlst(did)%geo_static_flnm)) then\n       xlat_corner_name = \"XLAT_C\"\n       xlon_corner_name = \"XLONG_C\"\n    else\n       xlat_corner_name = \"\"\n       xlon_corner_name = \"\"\n    endif\n\n    if (trim(xlat_corner_name) /= \"\") then\n      ! Get Local Latitude (lat)\n      allocate(latitude(nx_local+1,ny_local+1),stat=stat)\n      if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n        msg=METHOD//': Allocation of corner latitude memory failed.', &\n        file=FILENAME, rcToReturn=rc)) return ! bail out\n      call WRFHYDRO_ESMF_NetcdfReadIXJX(trim(xlat_corner_name),nlst(did)%geo_static_flnm, &\n        (/x_start,y_start/),latitude,rc=rc)\n      if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n      ! Get Local Longitude (lon)\n      allocate(longitude(nx_local+1,ny_local+1),stat=stat)\n      if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n       msg=METHOD//': Allocation of corner longitude memory failed.', &\n       file=FILENAME, rcToReturn=rc)) return ! bail out\n      call WRFHYDRO_ESMF_NetcdfReadIXJX(trim(xlon_corner_name),nlst(did)%geo_static_flnm, &\n        (/x_start,y_start/),longitude,rc=rc)\n      if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n#ifdef DEBUG\n      ! Print Local Lat Lon Lower Left / Upper Right Corners\n      write(logMsg,\"(A,4(F0.3,A))\") MODNAME//\": Corner Coordinates = (\", &\n        longitude(1,1),\":\",longitude(nx_local+1,ny_local+1),\",\", &\n        latitude(1,1),\":\",latitude(nx_local+1,ny_local+1),\")\"\n      call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n#endif\n\n      ! Add Corner Coordinates to Grid\n      call ESMF_GridAddCoord(WRFHYDRO_GridCreate, staggerLoc=ESMF_STAGGERLOC_CORNER, rc=rc)\n      if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n      call ESMF_GridGetCoord(WRFHYDRO_GridCreate, coordDim=1, localDE=0, &\n        staggerloc=ESMF_STAGGERLOC_CORNER, &\n        computationalLBound=lbnd, computationalUBound=ubnd, &\n        farrayPtr=coordXcorner, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n      call ESMF_GridGetCoord(WRFHYDRO_GridCreate, coordDim=2, localDE=0, &\n        staggerloc=ESMF_STAGGERLOC_CORNER, farrayPtr=coordYcorner, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n\n      do j = lbnd(2),ubnd(2)\n      do i = lbnd(1),ubnd(1)\n        coordXcorner(i,j) = longitude(i,j)\n        coordYcorner(i,j) = latitude(i,j)\n      enddo\n      enddo\n\n      deallocate(latitude,longitude,stat=stat)\n      if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n        msg=METHOD//': Deallocation of corner longitude and latitude memory failed.', &\n        file=FILENAME,rcToReturn=rc)) return ! bail out\n\n      call add_area(WRFHYDRO_GridCreate, rc=rc)\n      if (ESMF_STDERRORCHECK(rc)) return\n\n    else\n#ifdef DEBUG\n      ! Warning no corners in domain file\n      call ESMF_LogWrite(MODNAME//\": No Corner Coordinates.\", ESMF_LOGMSG_WARNING)\n#endif\n    endif\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end function\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"add_area\"\n\n  subroutine add_area(grid,rc)\n    type(ESMF_Grid), intent(inout)          :: grid\n    integer, intent(out)                    :: rc\n\n    ! Local Variables\n    integer(ESMF_KIND_I4), PARAMETER :: R = 6376000 ! metres\n    type(ESMF_Field)                 :: fieldArea\n    type(ESMF_Array)                 :: areaArray\n    integer                          :: i,j\n    integer                          :: lbnd(2),ubnd(2)\n    real(ESMF_KIND_R8), pointer      :: radianarea(:,:)\n    real(ESMF_KIND_R8), pointer      :: gridarea(:,:)\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    fieldArea = ESMF_FieldCreate(grid=grid, typekind=ESMF_TYPEKIND_R8, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    call ESMF_FieldRegridGetArea(fieldArea, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    call ESMF_FieldGet(fieldArea, localDE=0, &\n      farrayPtr=radianarea, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    call ESMF_GridAddItem(grid, itemFlag=ESMF_GRIDITEM_AREA, itemTypeKind=ESMF_TYPEKIND_R8, &\n      staggerLoc=ESMF_STAGGERLOC_CENTER, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n    call ESMF_GridGetItem(grid, itemflag=ESMF_GRIDITEM_AREA, localDE=0, &\n      staggerloc=ESMF_STAGGERLOC_CENTER, &\n      computationalLBound=lbnd, computationalUBound=ubnd, &\n      farrayPtr=gridarea, rc=rc)\n    if (ESMF_STDERRORCHECK(rc)) return\n\n     do j = lbnd(2),ubnd(2)\n     do i = lbnd(1),ubnd(1)\n       gridarea(i,j) = radianarea(i,j) * R * R\n     enddo\n     enddo\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"set_local_indices\"\n\n  subroutine set_local_indices(rc)\n    ! ARGUMENTS\n    integer, intent(out)                    :: rc\n\n    ! LOCAL VARIABLES\n    integer                     :: stat\n    type(ESMF_VM)               :: currentVM\n    integer                     :: localPet\n    integer                     :: petCount\n    type(ESMF_DELayout)         :: delayout\n    integer, allocatable        :: dimExtent(:,:)\n    integer, allocatable        :: iIndexList(:), jIndexList(:)\n#ifdef DEBUG\n    character(ESMF_MAXSTR)      :: logMsg\n#endif\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    !! Get VM Info to see if this will give me the PET info I need\n    call ESMF_VMGetCurrent(currentVM, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n    call ESMF_VMGet(currentVM, localPet=localPet, petCount=petCount, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    !! Get the grid distribution for this pet\n    allocate(dimExtent(2, 0:(petCount - 1)),stat=stat) ! (dimCount, deCount)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=METHOD//': Allocation of indexCountPDe memory failed.', &\n      file=FILENAME, rcToReturn=rc)) return ! bail out\n    call ESMF_DistGridGet(WRFHYDRO_DistGrid, delayout=delayout, &\n      indexCountPDe=dimExtent, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(iIndexList(dimExtent(1, localPet)),stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=METHOD//': Allocation of iIndexList memory failed.', &\n      file=FILENAME, rcToReturn=rc)) return ! bail out\n    call ESMF_DistGridGet(WRFHYDRO_DistGrid, localDe=0, dim=1, &\n      indexList=iIndexList, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    allocate(jIndexList(dimExtent(2, localPet)),stat=stat)\n    if (ESMF_LogFoundAllocError(statusToCheck=stat, &\n      msg=METHOD//': Allocation of jIndexList memory failed.', &\n      file=FILENAME, rcToReturn=rc)) return ! bail out\n    call ESMF_DistGridGet(WRFHYDRO_DistGrid, localDe=0, dim=2, &\n      indexList=jIndexList, rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    x_start = minVal(iIndexList)\n    x_end   = maxVal(iIndexList)\n    y_start = minVal(jIndexList)\n    y_end   = maxVal(jIndexList)\n\n    nx_local = x_end - x_start + 1\n    ny_local = y_end - y_start + 1\n\n#ifdef DEBUG\n    write (logMsg,\"(A,6(I0,A))\") MODNAME//\": Local Indices = (\", &\n      x_start,\":\",x_end,\",\",y_start,\":\",y_end,\") Local Size = (\", &\n      nx_local,\"x\",ny_local,\")\"\n    call ESMF_LogWrite(trim(logMsg), ESMF_LOGMSG_INFO)\n#endif\n\n    deallocate(iIndexList,jIndexList,stat=stat)\n    if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n      msg=METHOD//': Deallocation of IndexList memory failed.', &\n      file=FILENAME,rcToReturn=rc)) return ! bail out\n\n    deallocate(dimExtent,stat=stat)\n    if (ESMF_LogFoundDeallocError(statusToCheck=stat, &\n      msg=METHOD//': Deallocation of indexCountPDeo memory failed.', &\n      file=FILENAME,rcToReturn=rc)) return ! bail out\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_get_timestep\"\n\n  function WRFHYDRO_get_timestep(did,rc)\n    ! RETURN VALUE\n    real :: WRFHYDRO_get_timestep\n    ! ARGUMENTS\n    integer, intent(in)         :: did\n    integer, intent(out)        :: rc\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    WRFHYDRO_get_timestep = nlst(did)%dt\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end function\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_set_timestep\"\n\n  subroutine WRFHYDRO_set_timestep(did,dt,rc)\n    ! ARGUMENTS\n    integer, intent(in)           :: did\n    real                          :: dt\n    integer, intent(out)          :: rc\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    nlst(did)%dt = dt\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_get_hgrid\"\n\n  subroutine WRFHYDRO_get_hgrid(did,hgrid,rc)\n    ! ARGUMENTS\n    integer, intent(in)         :: did\n    character, intent(out)      :: hgrid\n    integer, intent(out)        :: rc\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    hgrid = nlst(did)%hgrid\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_get_restart\"\n\n  subroutine WRFHYDRO_get_restart(did,restart,rc)\n    ! ARGUMENTS\n    integer, intent(in)         :: did\n    logical, intent(out)        :: restart\n    integer, intent(out)        :: rc\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    if (nlst(did)%rst_typ .eq. 0) then\n      restart = .FALSE.\n    else\n      restart = .TRUE.\n    endif\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n  ! Conversion Utilities\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_ClockToString\"\n\n  subroutine WRFHYDRO_ClockToString(clock, timestr, rc)\n    ! ARGUMENTS\n    type(ESMF_Clock)                :: clock\n    integer, intent(out),optional   :: rc\n    character (len=*), intent(out)  :: timestr\n\n    ! LOCAL VARIABLES\n    type(ESMF_Time)            :: currTime\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    if(present(rc)) rc = ESMF_SUCCESS  ! Initialize\n\n    ! Get the current time from the clock\n    call ESMF_ClockGet(clock=clock,currTime=currTime,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    call WRFHYDRO_TimeToString(currTime,timestr,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n!-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_TimeToString\"\n\n  subroutine WRFHYDRO_TimeToString(time, timestr, rc)\n    ! ARGUMENTS\n    type(ESMF_Time)                 :: time\n    integer, intent(out),optional   :: rc\n    character (len=*), intent(out)  :: timestr\n\n    ! LOCAL VARIABLES\n    character (len=256)        :: tmpstr = ''\n    integer                    :: strlen\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    if(present(rc)) rc = ESMF_SUCCESS  ! Initialize\n\n    timestr = '' ! clear string\n\n    if (len(timestr) < 19) then\n      call ESMF_LogSetError(ESMF_FAILURE, &\n        msg=METHOD//\": Time string is too short!\", &\n        file=FILENAME,rcToReturn=rc)\n      return  ! bail out\n    endif\n\n    CALL ESMF_TimeGet(time,timeString=tmpstr,rc=rc )\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n\n    strlen = min(len(timestr),len_trim(tmpstr))\n    timestr(1:strlen) = tmpstr(1:strlen)\n    timestr(11:11) = '_'\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_TimeIntervalGetReal\"\n\n  function WRFHYDRO_TimeIntervalGetReal(timeInterval,rc)\n    ! RETURN VALUE:\n    real                                :: WRFHYDRO_TimeIntervalGetReal\n    ! ARGUMENTS\n    type(ESMF_TimeInterval),intent(in)  :: timeInterval\n    integer, intent(out), optional      :: rc\n\n    ! LOCAL VARIABLES\n    real(ESMF_KIND_R8)                  :: s_r8\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    if(present(rc)) rc = ESMF_SUCCESS\n\n    WRFHYDRO_TimeIntervalGetReal = -9999\n\n    call ESMF_TimeIntervalGet(timeInterval,s_r8=s_r8,rc=rc)\n    if(ESMF_STDERRORCHECK(rc)) return ! bail out\n    WRFHYDRO_TimeIntervalGetReal = s_r8\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end function\n\n  !-----------------------------------------------------------------------------\n  ! Log Utilities\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_nlstLog\"\n\n  subroutine WRFHYDRO_nlstLog(did,label,rc)\n    ! ARGUMENTS\n    integer,intent(in)                   :: did\n    character(len=*),intent(in),optional :: label\n    integer,intent(out)                  :: rc\n\n    ! LOCAL VARIABLES\n    integer                     :: layerIndex\n    character(len=64)           :: l_label\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      l_label = label\n    else\n      l_label = METHOD\n    endif\n\n    write (logMsg,\"(A,I0)\") \": Domain ID      = \",did\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n\n    write (logMsg,\"(A,5(I0,A))\") \": Start Date     = \", &\n      nlst(did)%START_YEAR,\"-\",nlst(did)%START_MONTH,\"-\", &\n      nlst(did)%START_DAY,\"_\",nlst(did)%START_HOUR,\":\", &\n      nlst(did)%START_MIN\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,F0.3)\") \": Timestep       = \",nlst(did)%dt\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,F0.3)\") \": Output Step    = \",nlst(did)%out_dt\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,F0.3)\") \": Restart Step   = \",nlst(did)%rst_dt\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,F0.3)\") \": Ter Routing Step   = \",nlst(did)%dtrt_ter\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,F0.3)\") \": Ch Routing Step   = \",nlst(did)%dtrt_ch\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n\n    write (logMsg,\"(A,I0)\") \": Grid ID        = \",nlst(did)%igrid\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A)\") \": Hydro Grid     = \",nlst(did)%hgrid\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A)\") \": Geo Grid File  = \",nlst(did)%geo_static_flnm\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A)\") \": Fine Grid File = \",nlst(did)%geo_finegrid_flnm\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A)\") \": GW Basin File  = \",nlst(did)%gwbasmskfil\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n\n    write (logMsg,\"(A,I0)\") \": Restart Type   = \",nlst(did)%rst_typ\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,A)\") \": Restart file   = \",nlst(did)%restart_file\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Coupling       = \",nlst(did)%sys_cpl\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n\n    write (logMsg,\"(A,I0)\") \": Channel RT     = \",nlst(did)%CHANRTSWCRT\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Subsurface RT  = \",nlst(did)%SUBRTSWCRT\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Overland RT    = \",nlst(did)%OVRTSWCRT\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": GW Baseflow RT = \",nlst(did)%GWBASESWCRT\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Routing Option = \",nlst(did)%RT_OPTION\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Channel Option = \",nlst(did)%channel_option\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Aggr Factor    = \",nlst(did)%AGGFACTRT\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": GW Restart     = \",nlst(did)%GW_RESTART\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": SWC Restart    = \",nlst(did)%RSTRT_SWC\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n\n    write (logMsg,\"(A,I0)\") \": Soil Layers    = \",nlst(did)%nsoil\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    do layerIndex=1,nlst(did)%nsoil\n      write (logMsg,\"(A,I0,A,F0.3)\") \": Soil layer depth (\", &\n        layerIndex,\") = \",nlst(did)%ZSOIL8(layerIndex)\n      call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    enddo\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\n#undef METHOD\n#define METHOD \"WRFHYDRO_domainLog\"\n\n  subroutine WRFHYDRO_domainLog(did,label,rc)\n    ! ARGUMENTS\n    integer,intent(in)                   :: did\n    character(len=*),intent(in),optional :: label\n    integer,intent(out)                  :: rc\n\n    ! LOCAL VARIABLES\n    character(len=64)           :: l_label\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": entered \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n    rc = ESMF_SUCCESS\n\n    if (present(label)) then\n      l_label = label\n    else\n      l_label = METHOD\n    endif\n\n    write (logMsg,\"(A,I0)\") \": Domain ID      = \",did\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n\n    write (logMsg,\"(A,L1)\") \": Domain Init    = \",rt_domain(did)%initialized\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Domain IX      = \",rt_domain(did)%IX\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Domain JX      = \",rt_domain(did)%JX\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Domain IXRT    = \",rt_domain(did)%IXRT\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Domain JXRT    = \",rt_domain(did)%JXRT\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Domain Forc    = \",rt_domain(did)%FORC_TYP\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Max Links      = \",rt_domain(did)%NLINKS\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Num Lakes      = \",rt_domain(did)%NLAKES\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n    write (logMsg,\"(A,I0)\") \": Num Basins     = \",rt_domain(did)%numbasns\n    call ESMF_LogWrite(trim(l_label)//logMsg,ESMF_LOGMSG_INFO)\n\n#ifdef DEBUG\n    call ESMF_LogWrite(MODNAME//\": leaving \"//METHOD, ESMF_LOGMSG_INFO)\n#endif\n\n  end subroutine\n\n  !-----------------------------------------------------------------------------\n\nend module\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/WRFHydro_NUOPC_Macros.h",
    "content": "!-------------------------------------------------------------------------------\n! NUOPC CPP Macros\n!-------------------------------------------------------------------------------\n#ifndef FILENAME\n#define FILENAME __FILE__\n#endif\n#define CONTEXT  line=__LINE__,file=FILENAME\n#define PASSTHRU msg=ESMF_LOGERR_PASSTHRU,CONTEXT\n#define ESMF_STDERRORCHECK(rc) ESMF_LogFoundError(rcToCheck=rc,msg=ESMF_LOGERR_PASSTHRU,line=__LINE__,file=__FILE__)\n\n!-------------------------------------------------------------------------------\n! Define ESMF real kind to match Appplications single/double precision\n!-------------------------------------------------------------------------------\n#if defined(REAL4)\n#define ESMF_KIND_FIELD ESMF_KIND_R4\n#define ESMF_KIND_COORD ESMF_KIND_R4\n#define ESMF_TYPEKIND_FIELD ESMF_TYPEKIND_R4\n#define ESMF_TYPEKIND_COORD ESMF_TYPEKIND_R4\n#elif defined(REAL8)\n#define ESMF_KIND_FIELD ESMF_KIND_R8\n#define ESMF_KIND_COORD ESMF_KIND_R8\n#define ESMF_TYPEKIND_FIELD ESMF_TYPEKIND_R8\n#define ESMF_TYPEKIND_COORD ESMF_TYPEKIND_R8\n#else\n#define ESMF_KIND_FIELD ESMF_KIND_R4\n#define ESMF_KIND_COORD ESMF_KIND_R8\n#define ESMF_TYPEKIND_FIELD ESMF_TYPEKIND_R4\n#define ESMF_TYPEKIND_COORD ESMF_TYPEKIND_R8\n#endif\n\n!-------------------------------------------------------------------------------\n! Define Missing Value\n!-------------------------------------------------------------------------------\n\n#define ESMF_MISSING_VALUE 9.99e20_ESMF_KIND_R8\n#define UNINITIALIZED -9999\n\n!-------------------------------------------------------------------------------\n! Define Output Levels\n!-------------------------------------------------------------------------------\n\n#define VERBOSITY_LV0 0\n#define VERBOSITY_LV1 1\n#define VERBOSITY_LV2 255\n#define VERBOSITY_LV3 1023\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/analysis/ferret_NUOPC_import.jnl",
    "content": " ! FERRET v6.96 Script\n ! >ferret -gif -script ferret_NUOPC_import.jnl [Grid File] [Restart File]\n ! Author: Daniel Rosen\n ! Organization: NESII/CIRES/NOAA\n ! Email: daniel.rosen@noaa.gov\n ! Date: 2017-02-27\n\nCANCEL MODE LOGO\n\nSAY *** Generating NUOPC restart SHADE plots ***\nSAY \n\n! Load grid file and compute output file label\nUSE $1\nSET VARIABLE/TITLE=\"Longitude\" lon_center[d=1]; \\\nSET VARIABLE/TITLE=\"Latitude\" lat_center[d=1]; \\\n\n! Load file and compute output file prefix and plot label prefix\nUSE $2\nDEFINE SYMBOL filename `\"$2\"`\nDEFINE SYMBOL cindex `STRINDEX(\"($filename)\",\"_\")`\nDEFINE SYMBOL rindex `STRINDEX(\"($filename)\",\"_RSTRT_\")`\nDEFINE SYMBOL gindex `STRINDEX(\"($filename)\",\"_DEBUG_\")`\nDEFINE SYMBOL iindex `STRINDEX(\"($filename)\",\"_IMP_\")`\nDEFINE SYMBOL eindex `STRINDEX(\"($filename)\",\"_EXP_\")`\nDEFINE SYMBOL tindex `STRRINDEX(\"($filename)\",\":\")`\nDEFINE SYMBOL dindex `STRRINDEX(\"($filename)\",\"_D\")`\nDEFINE SYMBOL xindex `STRRINDEX(\"($filename)\",\".nc\")`\nDEFINE SYMBOL comp `SUBSTRING(\"($filename)\",1,($cindex)-1)`\nDEFINE SYMBOL datetime `SUBSTRING(\"($filename)\",($tindex)-16,19)`\nDEFINE SYMBOL domain `SUBSTRING(\"($filename)\",($dindex)+1,($xindex)-($dindex)-1)`\nIF `($rindex) GT 0` THEN\n DEFINE SYMBOL lmode Restart\n DEFINE SYMBOL fmode RST\nELIF `($gindex) GT 0` THEN\n DEFINE SYMBOL lmode Debug\n DEFINE SYMBOL fmode DBG\nENDIF\nIF `($iindex) GT 0` THEN\n DEFINE SYMBOL lstate Import\n DEFINE SYMBOL fstate IMP\nELIF `($eindex) GT 0` THEN\n DEFINE SYMBOL lstate Export\n DEFINE SYMBOL fstate EXP\nENDIF\n\nDEFINE SYMBOL fprefix plot_($fmode)_($domain)_($comp)_($fstate)_($datetime)\nDEFINE SYMBOL lprefix ($lmode) ($domain) ($comp) ($lstate) ($datetime)\n\n! Print datasets\nSHOW DATA/BRIEF\n\n! Define single level variables\nLET fnames = {                              \\\n\"surface_runoff_amount\",                    \\\n\"subsurface_runoff_amount\",                 \\\n\"soil_moisture_fraction_layer_1\",           \\\n\"soil_moisture_fraction_layer_2\",           \\\n\"soil_moisture_fraction_layer_3\",           \\\n\"soil_moisture_fraction_layer_4\",           \\\n\"liquid_fraction_of_soil_moisture_layer_1\", \\\n\"liquid_fraction_of_soil_moisture_layer_2\", \\\n\"liquid_fraction_of_soil_moisture_layer_3\", \\\n\"liquid_fraction_of_soil_moisture_layer_4\", \\\n\"soil_temperature_layer_1\",                 \\\n\"soil_temperature_layer_2\",                 \\\n\"soil_temperature_layer_3\",                 \\\n\"soil_temperature_layer_4\"                  \\\n}\n\n! Define single level variable titles\nLET ftitles = {                    \\\n\"Surface Runoff\",                  \\\n\"Subsurface Runoff\",               \\\n\"Soil Moisture Content LV1\",       \\\n\"Soil Moisture Content LV2\",       \\\n\"Soil Moisture Content LV3\",       \\\n\"Soil Moisture Content LV4\",       \\\n\"Fraction of Liquid Moisture LV1\", \\\n\"Fraction of Liquid Moisture LV2\", \\\n\"Fraction of Liquid Moisture LV3\", \\\n\"Fraction of Liquid Moisture LV4\", \\\n\"Soil Temperature LV1\",            \\\n\"Soil Temperature LV2\",            \\\n\"Soil Temperature LV3\",            \\\n\"Soil Temperature LV4\"             \\\n}\n\n! Define single level forcing variable scales\nLET fminvals  = { 0,        0,        0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   260, 260, 260, 260 }\nLET fmaxvals  = { 0.000100, 0.000100, 0.42,  0.42,  0.42,  0.42,  0.42,  0.42,  0.42,  0.42,  320, 320, 320, 320 }\nLET fstepvals = { 0.000002, 0.000001, 0.007, 0.007, 0.007, 0.007, 0.007, 0.007, 0.007, 0.007, 1,   1,   1,   1   }\nLET fminoutlr = { 0,        0,        0,     0,     0,     0,     0,     0,     0,     0,     250, 250, 250, 250 } \nLET fmaxoutlr = { 0.01,     0.001,    1,     1,     1,     1,     1,     1,     1,     1,     350, 350, 350, 350 }\n\n! Create SHADE plots for single level forcing variables\nSAY\nSAY *** Plotting single level forcing variables ***\nREPEAT/RANGE=1:`fnames,return=isize`/NAME=vctr ( \\\nDEFINE SYMBOL vindex `vctr`; \\\nDEFINE SYMBOL vtitle `ftitles[i=($vindex)]`  ; \\\nDEFINE SYMBOL vname  `fnames[i=($vindex)]`   ; \\\nDEFINE SYMBOL vmin   `fminvals[i=($vindex)]` ; \\\nDEFINE SYMBOL vmax   `fmaxvals[i=($vindex)]` ; \\\nDEFINE SYMBOL vstep  `fstepvals[i=($vindex)]`; \\\nDEFINE SYMBOL vmnol  `fminoutlr[i=($vindex)]`; \\\nDEFINE SYMBOL vmxol  `fmaxoutlr[i=($vindex)]`; \\\nSET VARIABLE/BAD=-9999/TITLE=\"($vtitle)\" ($vname)[d=2]; \\\nSAY ($vtitle) (outliers,min,max,outliers)=\\\n(($vmnol),($vmin),($vmax),($vmxol)); \\\nSHADE/LEVELS=\"(($vmnol))(($vmin),($vmax),($vstep))(($vmxol))\"/\\\nKEY=CONTINUOUS/TITLE=\"($lprefix) ($vtitle)\" \\\n($vname)[d=2], lon_center[d=1], lat_center[d=1]; \\\nFRAME/FILE=($fprefix)_($vname).gif \\\n)\n\n! Create compressed tar archive of all .gif files\nSAY\nSAY *** Creating plots.tar.gz archive ***\nSPAWN tar -czf plots.tar.gz *.gif\n\nSAY\n\nexit\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/analysis/ferret_NUOPC_mask.jnl",
    "content": " ! FERRET v6.96 Script\n ! >ferret -gif -script ferret_NUOPC_mask.jnl [Grid File]\n ! Author: Daniel Rosen\n ! Organization: NESII/CIRES/NOAA\n ! Email: daniel.rosen@noaa.gov\n ! Date: 2017-02-27\n\nCANCEL MODE LOGO\n\nSAY *** Generating NUOPC Grid Mask SHADE plots ***\nSAY\n\n! Load grid file and compute output file label\nUSE $1\nSET VARIABLE/TITLE=\"Longitude\" lon_center[d=1]\nSET VARIABLE/TITLE=\"Latitude\" lat_center[d=1]\nSET VARIABLE/TITLE=\"Mask\" mask[d=1]\n\nDEFINE SYMBOL gname `\"$1\"`\nDEFINE SYMBOL fnlen `STRLEN(\"($gname)\")`\nDEFINE SYMBOL ext `STRRINDEX(\"($gname)\",\".nc\")`\nDEFINE SYMBOL flabel `SUBSTRING(\"($gname)\",1,($ext)-1)`\n\n! Print datasets\nSHOW DATA/BRIEF\n\nSHADE/LEVELS=\"(-1,5,1)\"/\\\nKEY=CENTERLAB/TITLE=\"NUOPC ($flabel) Mask\" \\\nmask[d=1], lon_center[d=1], lat_center[d=1]; \\\nFRAME/FILE=plot_($flabel)_mask.gif\n\nSAY\n\nexit\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/analysis/grid_NUOPC_CONUS.ncl",
    "content": ";--------------------------------------------------\n; Output Grid on CONUS Map\n;--------------------------------------------------\n\n;--------------------------------------------------\n;\n; These files are loaded by default in NCL V6.2.0 and newer\n; load \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl\"\n; load \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl\"\n\nbegin\n;---Read netCDF file\n  file_suffix = get_file_suffix(grid,0)\n  print (\"Grid File=\"+grid)\n  print (\"Output File=\"+file_suffix@fBase+\"_CONUS.png\")\n\n  in   = addfile(grid,\"r\")\n\n;---Start the graphics.\n  wks = gsn_open_wks(\"png\",file_suffix@fBase+\"_CONUS\")      ; send graphics to PNG file\n\n  res               = True                        ; plot mods desired\n\n  res@gsnMaximize   = True                        ; maximize plot size\n  res@gsnDraw       = False                       ; don't draw yet\n  res@gsnFrame      = False                       ; don't advance frame\n  res@tiMainString  = str_sub_str(file_suffix@fBase+\"_CONUS\",\"_\",\" \")\n\n  res@pmTickMarkDisplayMode = \"Always\"            ; nice tickmark labels\n\n  res@mpMinLatF     =   18.0                      ; map area\n  res@mpMaxLatF     =   49.0                      ; latitudes\n  res@mpMinLonF     = -125.0                      ; and\n  res@mpMaxLonF     =  -62.5                      ; longitudes\n\n;---Create map (don't draw it yet)\n  map = gsn_csm_map_ce(wks,res)\n\n;---Load coordinates.\n  hgt       = in->lon_center(:,:)\n  hgt@lat2d = in->lat_center(:,:)\n  hgt@lon2d = in->lon_center(:,:)\n\n;---Call function to attach lat/lon lines. Only use every third line.\n  pres                   = True\n  pres@gsnCoordsAsLines  = True                   ; Default is points\n  gsn_coordinates(wks,map,hgt,pres)\nend\n"
  },
  {
    "path": "src/CPL/NUOPC_cpl/analysis/grid_NUOPC_Global.ncl",
    "content": ";--------------------------------------------------\n; Output Grid on Global Map\n;--------------------------------------------------\n\n;--------------------------------------------------\n;\n; These files are loaded by default in NCL V6.2.0 and newer\n; load \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl\"\n; load \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl\"\n\nbegin\n;---Read netCDF file\n  file_suffix = get_file_suffix(grid,0)\n  print (\"Grid File=\"+grid)\n  print (\"Output File=\"+file_suffix@fBase+\"_CONUS.png\")\n\n  in   = addfile(grid,\"r\")\n\n;---Start the graphics.\n  wks = gsn_open_wks(\"png\",file_suffix@fBase)      ; send graphics to PNG file\n\n  res               = True                        ; plot mods desired\n\n  res@gsnMaximize   = True                        ; maximize plot size\n  res@gsnDraw       = False                       ; don't draw yet\n  res@gsnFrame      = False                       ; don't advance frame\n  res@tiMainString  = str_sub_str(file_suffix@fBase,\"_\",\" \")\n\n  res@pmTickMarkDisplayMode = \"Always\"            ; nice tickmark labels\n\n;---Create map (don't draw it yet)\n  map = gsn_csm_map_ce(wks,res)\n\n;---Load coordinates.\n  hgt       = in->lon_center(:,:)\n  hgt@lat2d = in->lat_center(:,:)\n  hgt@lon2d = in->lon_center(:,:)\n\n;---Call function to attach lat/lon lines. Only use every third line.\n  pres                   = True\n  pres@gsnCoordsAsLines  = True                   ; Default is points\n  gsn_coordinates(wks,map,hgt,pres)\nend\n"
  },
  {
    "path": "src/CPL/NoahMP_cpl/CMakeLists.txt",
    "content": "add_library(hydro_noahmp_cpl STATIC\n        module_hrldas_HYDRO.F\n        hrldas_drv_HYDRO.F\n)\n\ntarget_link_libraries(hydro_noahmp_cpl PUBLIC hydro_mpp)\ntarget_link_libraries(hydro_noahmp_cpl PUBLIC hydro_utils)\ntarget_link_libraries(hydro_noahmp_cpl PUBLIC hydro_routing_overland)\ntarget_link_libraries(hydro_noahmp_cpl PUBLIC hydro_routing_subsurface)\n#target_link_libraries(hydro_noahmp_cpl PUBLIC hydro_routing_groundwater)\n#target_link_libraries(hydro_noahmp_cpl PUBLIC hydro_routing_groundwater_bucket)\n#target_link_libraries(hydro_noahmp_cpl PUBLIC hydro_routing_groundwater_nhd)\n#target_link_libraries(hydro_noahmp_cpl PUBLIC hydro_routing_groundwater_simple)\ntarget_link_libraries(hydro_noahmp_cpl PUBLIC hydro_data_rec)\ntarget_link_libraries(hydro_noahmp_cpl PUBLIC hydro_routing)\n"
  },
  {
    "path": "src/CPL/NoahMP_cpl/Makefile",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\n\n\ninclude ../../macros\n\nMODFLAG =       -I./ -I ../../MPP -I ../../mod\n\nOBJS = \\\n\tmodule_hrldas_HYDRO.o \\\n\thrldas_drv_HYDRO.o    \nall:\t$(OBJS) \n\n.F.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -o $(@) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) $(*).F\n\t@echo \"\"\n\tar -r ../../lib/libHYDRO.a $(@)\n\tcp *.mod ../../mod\n\n#\n# Dependencies:\n#\nmodule_hrldas_HYDRO.o: ../../Data_Rec/module_RT_data.o ../../Data_Rec/module_namelist.o ../../HYDRO_drv/module_HYDRO_drv.o\n\nhrldas_drv_HYDRO.o: module_hrldas_HYDRO.o ../../Data_Rec/module_namelist.o ../../Routing/module_lsm_forcing.o\n\n\nclean:\n\trm -f *.o *.mod *.stb *~ Noah_hrldas_beta\n"
  },
  {
    "path": "src/CPL/NoahMP_cpl/hrldas_drv_HYDRO.F",
    "content": "\n!2345678\n\n       subroutine hrldas_drv_HYDRO(STC_io,SMC_io,SH2OX_io,infxsrt,sfcheadrt,soldrain,ii,jj,kk)\n          use module_hrldas_HYDRO, only: hrldas_cpl_HYDRO\n          implicit none\n          integer:: ii,jj,kk, k\n\n          real,dimension(ii,jj,kk) :: STC,SMC,SH2OX\n          real,dimension(ii,kk,jj) :: STC_io,SMC_io,SH2OX_io\n          real,dimension(ii,jj) ::infxsrt,sfcheadrt, soldrain\n\n          do k = 1, kk\n              STC(:,:,k) = STC_io(:,k,:)\n              SMC(:,:,k) = SMC_io(:,k,:)\n              SH2OX(:,:,k) = SH2OX_io(:,k,:)\n          end do\n\n          call hrldas_cpl_HYDRO(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk)\n\n          do k = 1, kk\n               STC_io(:,k,:) = STC(:,:,k)\n               SMC_io(:,k,:) = SMC(:,:,k)\n               SH2OX_io(:,k,:) = SH2OX(:,:,k)\n          end do\n\n       end subroutine hrldas_drv_HYDRO\n\n       subroutine hrldas_drv_HYDRO_ini(STC_io,SMC_io,SH2OX_io,infxsrt,sfcheadrt,soldrain,ii,jj,kk,kt,dt,olddate,zsoil)\n          use module_hrldas_HYDRO, only: hrldas_cpl_HYDRO_ini, open_print_mpp\n          implicit none\n          integer:: ii,jj,kk, kt, k\n          character(len=*) :: olddate\n          real :: dt\n          real,dimension(ii,jj,kk) :: STC,SMC,SH2OX\n          real,dimension(ii,kk,jj) :: STC_io,SMC_io,SH2OX_io\n          real,dimension(ii,jj) ::infxsrt,sfcheadrt, soldrain\n          real, dimension(kk) :: zsoil\n          do k = 1, kk\n              STC(:,:,k) = STC_io(:,k,:)\n              SMC(:,:,k) = SMC_io(:,k,:)\n              SH2OX(:,:,k) = SH2OX_io(:,k,:)\n          end do\n             call hrldas_cpl_HYDRO_ini(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk,kt,dt,olddate,zsoil)\n\n           do k = 1, kk\n               STC_io(:,k,:) = STC(:,:,k)\n               SMC_io(:,k,:) = SMC(:,:,k)\n               SH2OX_io(:,k,:) = SH2OX(:,:,k)\n           end do\n\n             call open_print_mpp(6)\n       end subroutine hrldas_drv_HYDRO_ini\n\n       subroutine HYDRO_frocing_drv (indir,forc_typ, snow_assim,olddate,     &\n          ixs, ixe,jxs,jxe,                       &\n          forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n          forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n          T2,Q2X,U,V,PRES,XLONG,SHORT,PRCP1,lai,SNOWBL,fpar,snodep, kt, FORCING_TIMESTEP,pcp_old)\n\n         use module_lsm_forcing, only: read_hydro_forcing\n         use config_base, only: nlst\n         implicit none\n         integer did, ixs,ixe,jxs,jxe\n         integer ix,jx, kt\n         character(len=19) :: olddate\n         character(len=*) :: indir\n         character(len=256), intent(in)  :: forcing_name_T\n         character(len=256), intent(in)  :: forcing_name_Q\n         character(len=256), intent(in)  :: forcing_name_U\n         character(len=256), intent(in)  :: forcing_name_V\n         character(len=256), intent(in)  :: forcing_name_P\n         character(len=256), intent(in)  :: forcing_name_LW\n         character(len=256), intent(in)  :: forcing_name_SW\n         character(len=256), intent(in)  :: forcing_name_PR\n         character(len=256), intent(in)  :: forcing_name_SN\n         character(len=256), intent(in)  :: forcing_name_LF\n         real, dimension(ixs:ixe,jxs:jxe):: T2,Q2X,U,V,PRES,XLONG,SHORT,PRCP1, &\n                 lai, snowbl, fpar, snodep, pcp_old\n         integer :: forc_typ, snow_assim, FORCING_TIMESTEP\n\n         ix = ixe-ixs+1\n         jx = jxe-jxs+1\n         did = 1\n\n         call read_hydro_forcing( &\n            indir, olddate, &\n            nlst(did)%hgrid,&\n            ix,jx,forc_typ,snow_assim,  &\n            forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n            forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n            T2,q2x,u,v,pres,xlong,short,prcp1,&\n            lai,snowbl,fpar,snodep,FORCING_TIMESTEP*1.0,kt, pcp_old)\n       end subroutine HYDRO_frocing_drv\n\n       subroutine get_greenfrac(inFile,greenfrac, idim, jdim, olddate,SHDMAX)\n         use config_base, only: nlst\n          implicit none\n          character(len=*) :: olddate, inFile\n          integer :: idim, jdim\n          real, dimension(idim,jdim),intent(out):: greenfrac\n          real, dimension(idim,jdim),intent(out):: SHDMAX\n          integer:: mm, dd, did\n          integer :: months\n          months = 12\n          did = 1\n          read(olddate(6:7),*) mm\n          read(olddate(9:10),*) dd\n\t  !call get_greenfrac_netcdf(inFile,greenfrac,idim, jdim, months,mm,dd)\n\t  !SHDMAX = maxval(greenfrac)\n\t  !AD_CHANGE: Old get_greenfrac routine was grabbing max across spatial domain.\n\t  !\t      Updated to new routine that grabs maximum for each cell across time series.\n\t  call get_maxgreenfrac_netcdf(inFile,greenfrac,idim, jdim, months)\n          SHDMAX = greenfrac\n       end subroutine get_greenfrac\n\n#ifdef MPP_LAND\n       subroutine get_greenfrac_mpp(inFile,greenfrac, idim, jdim, olddate,SHDMAX)\n          use module_mpp_land, only:global_nx, global_ny, my_id, io_id, decompose_data_real\n          implicit none\n          character(len=*) :: olddate, inFile\n          integer, intent(in) :: idim, jdim\n          real, dimension(idim,jdim), intent(out):: greenfrac,SHDMAX\n          real, dimension(global_nx,global_ny):: ggreenfrac,gSHDMAX\n          if(my_id .eq. io_id) then\n                call get_greenfrac(inFile,ggreenfrac, global_nx, global_ny, olddate,gSHDMAX)\n          endif\n          call decompose_data_real( ggreenfrac, greenfrac)\n          call decompose_data_real( gSHDMAX, SHDMAX)\n       end subroutine get_greenfrac_mpp\n#endif\n\n      subroutine get_greenfrac_netcdf(fileName,array3, idim, jdim, ldim,mm,dd)\n          use netcdf\n          use module_hydro_stop, only:HYDRO_stop\n          implicit none\n          character(len=*) :: fileName\n          integer, intent(in) :: mm,dd\n          integer, intent(in) :: idim, jdim, ldim\n          real, dimension(idim,jdim) :: array\n          real, dimension(idim,jdim) :: array2\n          real, dimension(idim,jdim) :: diff\n          real, dimension(idim,jdim), intent(out) :: array3\n          integer :: iret, varid, ncid\n          real, dimension(idim,jdim,ldim) :: xtmp\n          integer, dimension(1) :: mp\n          integer :: i, j, mm2,daytot\n          real :: ddfrac\n          character(len=24), parameter :: name = \"GREENFRAC\"\n\n!          units = \"fraction\"\n\n          iret = nf90_open(trim(fileName), NF90_NOWRITE, ncid)\n          if(iret /= 0) then\n              write(6,*) \"FATAL ERROR: failed to open file in get_greenfrac: \", trim(fileName)\n              call hydro_stop(\"In hrldas_drv_HYDRO.F get_greenfrac_netcdf() - \"// &\n                              \"Failed to open file.\")\n          endif\n\n          iret = nf90_inq_varid(ncid,  trim(name),  varid)\n          if (iret /= 0) then\n             print*, 'name = \"', trim(name)//'\"'\n             print*, \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_greenfrac_netcdf:  nf90_inq_varid\"\n             call hydro_stop(\"In hrldas_drv_HYDRO.F get_greenfrac_netcdf() - \"// &\n                             \"Failed to call nf90_inq_varid.\")\n          endif\n\n          iret = nf90_get_var(ncid, varid, xtmp)\n          if (iret /= 0) then\n\n             print*, 'name = \"', trim(name)//'\"'\n             print*, \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_greenfrac_netcdf:  nf90_get_var\"\n             call hydro_stop(\"In hrldas_drv_HYDRO.F get_greenfrac_netcdf() - \"// &\n                             \"Faile to call nf90_get_var\")\n          endif\n\n\n          if (mm.lt.12) then\n            mm2 = mm+1\n          else\n            mm2 = 1\n                end if\n\n          !DJG_DES Set up dates for daily interpolation...\n                if (mm.eq.1.OR.mm.eq.3.OR.mm.eq.5.OR.mm.eq.7.OR.mm.eq.8.OR.mm.eq.10.OR.mm.eq.12) then\n                   daytot = 31\n                else if (mm.eq.4.OR.mm.eq.6.OR.mm.eq.9.OR.mm.eq.11) then\n                   daytot = 30\n                else if (mm.eq.2) then\n                   daytot = 28\n                end if\n                ddfrac = float(dd)/float(daytot)\n                if (ddfrac.gt.1.0) ddfrac = 1.0   ! Assumes Feb. 29th change is same as Feb 28th\n\n#ifdef HYDRO_D\n               print *,\"DJG_DES Made it past netcdf read...month = \",mm,mm2,dd,daytot,ddfrac\n#endif\n\n          do i = 1, idim\n             do j = 1, jdim\n                array(i,j) = xtmp(i,j,mm)   !GREENFRAC in geogrid in units of fraction from month 1\n                array2(i,j) = xtmp(i,j,mm2)   !GREENFRAC in geogrid in units of fraction from month 1\n                diff(i,j) = array2(i,j) - array(i,j)\n                array3(i,j) = array(i,j) + ddfrac * diff(i,j)\n             enddo\n          enddo\n          iret=nf90_close(ncid)\n      end subroutine get_greenfrac_netcdf\n\n        subroutine get_maxgreenfrac_netcdf(fileName, array3, idim, jdim, ldim)\n          use netcdf\n          use module_hydro_stop, only:HYDRO_stop\n          implicit none\n          character(len=*) :: fileName\n          integer, intent(in) :: idim, jdim, ldim\n          real, dimension(idim,jdim), intent(out) :: array3\n          integer :: iret, varid, ncid\n          real, dimension(idim,jdim,ldim) :: xtmp\n          character(len=24), parameter :: name = \"GREENFRAC\"\n\n!          units = \"fraction\"\n\n          iret = nf90_open(trim(fileName), NF90_NOWRITE, ncid)\n          if(iret /= 0) then\n              write(6,*) \"FATAL ERROR: failed to open file in get_maxgreenfrac: \", trim(fileName)\n              call hydro_stop(\"In hrldas_drv_HYDRO.F get_maxgreenfrac_netcdf() - \"// &\n                              \"Failed to open file.\")\n          endif\n\n          iret = nf90_inq_varid(ncid,  trim(name),  varid)\n          if (iret /= 0) then\n             print*, 'name = \"', trim(name)//'\"'\n             print*, \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_maxgreenfrac_netcdf:  nf90_inq_varid\"\n             call hydro_stop(\"In hrldas_drv_HYDRO.F get_maxgreenfrac_netcdf() - \"// &\n                             \"Faile to call nf90_inq_varid.\")\n          endif\n\n          iret = nf90_get_var(ncid, varid, xtmp)\n          if (iret /= 0) then\n\n             print*, 'name = \"', trim(name)//'\"'\n             print*, \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_maxgreenfrac_netcdf:  nf90_get_var\"\n             call hydro_stop(\"In hrldas_drv_HYDRO.F get_maxgreenfrac_netcdf() - \"// &\n                             \"Failed to call lnf90_get_var.\")\n          endif\n\n          array3 = maxval(xtmp,3)\n          iret=nf90_close(ncid)\n      end subroutine get_maxgreenfrac_netcdf\n\n      subroutine HYDRO_HRLDAS_ini(fileName,ix,jx, nsoil,smc_io,stc_io,sh2ox_io, cmc, t1, weasd, &\n            snodep,lai, fpar, vegtyp,FNDSNOWH)\n      ! read the field from wrfinput or output file\n          use netcdf\n          use module_hydro_stop, only:HYDRO_stop\n          implicit none\n          character(len=*) fileName\n          integer :: ix,jx , nsoil, i, j, k\n          integer :: iret, ncid, ierr, varid\n          real,dimension(ix,jx,nsoil):: smc,stc,sh2ox\n          real,dimension(ix,nsoil,jx):: smc_io,stc_io,sh2ox_io\n          real,dimension(ix,jx):: cmc, t1, weasd, snodep, lai, fpar\n          integer, dimension(ix,jx) ::    vegtyp\n          logical :: FNDSNOWH\n!yw          real, dimension(50) :: shdtbl\n!yw          data shdtbl /0.1,0.8,0.8,0.8,0.8,0.8,0.8,0.7,0.7,0.5,  &\n!yw              0.8,0.7,0.95,0.7,0.8,0,0.6,0.6,0.1, &\n!yw              0.6,0.6,0.6,0.3,0,0.5,0,0,           &\n!yw              0,0,0,0,0,0,0,0,0,0,0,0,0,          &\n!yw              0,0,0,0,0,0,0,0,0,0/\n\n\n          iret = nf90_open(trim(fileName), NF90_NOWRITE, ncid)\n          if(iret /= 0) then\n              write(6,*) \"FATAL ERROR: failed to open file in HYDRO_HRLDAS_ini: \", trim(fileName)\n              call hydro_stop(\"In hrldas_drv_HYDRO.F HYDRO_HRLDAS_ini() - \"// &\n                              \"Failed to open wrf input/output file.\")\n          else\n#ifdef HYDRO_D\n              write(6,*) \"initialization from the file  : \", trim(fileName)\n\n#endif\n          endif\n\n           iret = nf90_inq_varid(ncid,\"VEGFRA\",  varid)\n           if (iret == 0) then\n              iret = nf90_get_var(ncid, varid, fpar)\n              if(maxval(fpar) .gt. 10 .and. (maxval(fpar) .lt. 1000) ) fpar = fpar/100.\n           endif\n\n\n          iret = nf90_inq_varid(ncid,\"LAI\",  varid)\n          if (iret == 0) iret = nf90_get_var(ncid, varid, lai)\n\n          iret = nf90_inq_varid(ncid,\"SNOWH\",  varid)\n          if (iret == 0) then\n#ifdef HYDRO_D\n             print*, \"read snowh for initialization ....\"\n#endif\n             iret = nf90_get_var(ncid, varid, snodep)\n             FNDSNOWH = .true.\n          else\n             FNDSNOWH   = .false.\n          endif\n\n          iret = nf90_inq_varid(ncid,\"SNOW\",  varid)\n          if (iret == 0) then\n#ifdef HYDRO_D\n             print*, \"read snow for initialization ....\"\n#endif\n             iret = nf90_get_var(ncid, varid, weasd)\n          endif\n\n\n          iret = nf90_inq_varid(ncid,\"TSK\",  varid)\n          if (iret == 0) iret = nf90_get_var(ncid, varid, t1)\n\n          iret = nf90_inq_varid(ncid,\"CANWAT\",  varid)\n          if (iret == 0) iret = nf90_get_var(ncid, varid, cmc)\n\n          iret = nf90_inq_varid(ncid,\"SMOIS\",  varid)\n          if (iret == 0) iret = nf90_get_var(ncid, varid, smc)\n\n          iret = nf90_inq_varid(ncid,\"TSLB\",  varid)\n          if (iret == 0) iret = nf90_get_var(ncid, varid, stc)\n\n          iret = nf90_inq_varid(ncid,\"SH2O\",  varid)\n          if (iret == 0) iret = nf90_get_var(ncid, varid, sh2ox)\n\n          iret=nf90_close(ncid)\n\n!yw    added for\n!yw          where(sh2ox == 0) sh2ox = smc\n\n          do k = 1, nsoil\n              STC_io(:,k,:) = STC(:,:,k)\n              SMC_io(:,k,:) = SMC(:,:,k)\n              SH2OX_io(:,k,:) = SH2OX(:,:,k)\n          end do\n       end subroutine HYDRO_HRLDAS_ini\n\n#ifdef MPP_LAND\n      subroutine HYDRO_HRLDAS_ini_mpp(fileName,ix,jx, nsoil,smc_io,stc_io,sh2ox_io, cmc, t1, weasd, &\n                                snodep,lai, fpar, vegtyp,FNDSNOWH)\n          use module_mpp_land, only:global_nx, global_ny, my_id, io_id, decompose_data_real, &\n                     decompose_data_int, mpp_land_bcast, write_io_real,write_io_int\n          implicit none\n          character(len=*) fileName\n          integer :: ix,jx , nsoil, i, j, k\n          integer :: iret, ncid, ierr, varid\n          real,dimension(ix,nsoil,jx):: smc_io,stc_io,sh2ox_io\n          real,dimension(ix,jx):: cmc, t1, weasd, snodep, lai, fpar\n          integer, dimension(ix,jx) ::    vegtyp\n          logical :: FNDSNOWH\n\n          real,dimension(global_nx,nsoil,global_ny):: gsmc_io,gstc_io,gsh2ox_io\n          real,dimension(global_nx,global_ny):: gcmc, gt1, gweasd, gsnodep, glai, gfpar\n          integer, dimension(global_nx,global_ny) ::    gvegtyp\n\n          call write_io_real(snodep,gsnodep)\n          call write_io_real(lai,   glai   )\n          call write_io_real(fpar, gfpar  )\n          call write_io_int(vegtyp, gvegtyp)\n          call write_io_real(cmc, gcmc  )\n          call write_io_real(t1, gt1  )\n          call write_io_real(weasd, gweasd  )\n\n          if(my_id .eq. io_id) then\n          call HYDRO_HRLDAS_ini(fileName,global_nx,global_ny, nsoil,gsmc_io,gstc_io,gsh2ox_io, gcmc, gt1, gweasd, &\n               gsnodep,glai, gfpar, gvegtyp,FNDSNOWH)\n          endif\n\n\n          call mpp_land_bcast(FNDSNOWH)\n          do k = 1, nsoil\n              call decompose_data_real(gsmc_io(:,k,:),smc_io(:,k,:))\n              call decompose_data_real(gstc_io(:,k,:),stc_io(:,k,:))\n              call decompose_data_real(gsh2ox_io(:,k,:),sh2ox_io(:,k,:))\n          end do\n\n          call decompose_data_real(gcmc, cmc)\n          call decompose_data_real(gt1, t1)\n          call decompose_data_real(gweasd, weasd)\n          call decompose_data_real(gsnodep, snodep)\n          call decompose_data_real(glai, lai)\n          call decompose_data_real(gfpar, fpar)\n          call decompose_data_int(gvegtyp,vegtyp)\n\n      end subroutine HYDRO_HRLDAS_ini_mpp\n#endif\n      subroutine get_iocflag(did, iocflag)\n        use config_base, only: nlst\n         implicit none\n         integer :: did, iocflag\n         iocflag = nlst(did)%io_config_outputs\n      end subroutine get_iocflag\n\n      subroutine get_rstrt_swc(did, restart_flag)\n         use config_base, only: nlst\n         implicit none\n         integer, intent(in)  :: did\n         integer, intent(out) :: restart_flag\n         restart_flag = nlst(did)%RSTRT_SWC\n      end subroutine\n\n      subroutine get_t0OutputFlag(did, t0OutputFlag)\n        use config_base, only: nlst\n         implicit none\n         integer :: did, t0OutputFlag\n         t0OutputFlag = nlst(did)%t0OutputFlag\n      end subroutine get_t0OutputFlag\n\n\n      subroutine getNameList(varName,pVar)\n        use config_base, only: nlst\n          implicit none\n          integer :: pVar\n          integer :: did\n          character(len=*) :: varName\n          did = 1\n          if(varName .eq. \"GWSPINCYCLES\") then\n               pVar = nlst(did)%gwSpinCycles\n          elseif(varName .eq. \"GWBASESWCRT\") then\n               pVar = nlst(did)%GWBASESWCRT\n          elseif(varName .eq. \"GWSOILCPL\") then\n               pVar = nlst(did)%gwsoilcpl\n          elseif(varName .eq. \"channel_only\") then\n               pVar = nlst(did)%channel_only\n          elseif(varName .eq. \"channelBucket_only\") then\n               pVar = nlst(did)%channelBucket_only\n          elseif(varName .eq. \"igrid\") then\n               pVar = nlst(did)%igrid\n          else\n               pVar = 0\n          endif\n     end subroutine getNameList\n\n      subroutine updateNameList(varName,pVarIn)\n        use config_base, only: nlst\n#ifdef MPP_LAND\n          use module_mpp_land, only: mpp_land_bcast_int1\n#endif\n          implicit none\n          integer :: did\n          character (len=*) :: varName\n          integer :: pVar, pVarIn\n          pVar = pVarIn\n          did = 1\n          if(varName .eq. \"channel_only\") then\n#ifdef MPP_LAND\n             call mpp_land_bcast_int1(pVar)\n#endif\n             nlst(did)%channel_only = pVar\n          endif\n          if(varName .eq. \"channelBucket_only\") then\n#ifdef MPP_LAND\n             call mpp_land_bcast_int1(pVar)\n#endif\n             nlst(did)%channelBucket_only = pVar\n          endif\n\n     end subroutine updateNameList\n"
  },
  {
    "path": "src/CPL/NoahMP_cpl/module_hrldas_HYDRO.F",
    "content": "\nmodule module_HRLDAS_HYDRO\n\n! NDHMS  module\n#ifdef MPP_LAND\n    use module_mpp_land, only: global_nx, global_ny, decompose_data_real, &\n                 write_io_real, my_id, mpp_land_bcast_real1, IO_id, &\n                 mpp_land_bcast_int1, mpp_land_sync\n#endif\n    use module_HYDRO_drv, only: HYDRO_ini, HYDRO_exe, HYDRO_rst_out\n    use module_rt_data, only:  rt_domain\n    use config_base, only: nlst\n    use module_gw_gw2d_data, only: gw2d\n    use module_hydro_stop, only:HYDRO_stop\n\n    implicit none\n    integer begg, endg\n    integer :: numg, numl, numc, nump\n    INTEGER, PARAMETER :: double=8\n    real(kind=double), pointer :: r2p(:,:) , r1p(:)\n\n    integer ::  begl, endl, begc, endc, begp, endp\n\n    real, allocatable, dimension(:,:) :: vg_test\n    integer :: nn\n    integer :: open_unit_status\n\n#ifdef WRF_HYDRO_RAPID\n     real :: timeAcc1 = 0\n     real :: timeAcc2 = 0\n     integer :: clock_count_1 = 0\n     integer :: clock_count_2 = 0\n     integer :: clock_count_3 = 0\n     integer :: clock_rate    = 0\n#endif\n\n\n\n\nCONTAINS\n\n    subroutine hrldas_cpl_HYDRO(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk)\n\n!---lpr added 2015-07-30---------\n#ifdef WRF_HYDRO_RAPID\n    use hrldas_RAPID_wrapper, only: hrldas_RAPID_ini,hrldas_RAPID_exe\n#endif\n!---lpr add end-----------------\n\n\n       implicit none\n\n       integer ii,jj,kk\n       integer k, gwsoilcpl\n       real,dimension(ii,jj,kk) :: STC,SMC,SH2OX\n       real,dimension(ii,jj) ::infxsrt,sfcheadrt, soldrain, qsgw\n\n!lpr add 2014-06-24\n#ifdef WRF_HYDRO_RAPID\n#ifdef MPP_LAND\n        real, dimension(global_nx,global_ny) :: g_runoff\n#endif\n        real, dimension(ii,jj) :: runoff\n#endif\n!lpr add end\n        integer ::  did\n\n        integer ntime\n\n        integer :: i,j\n\n        real*8 :: t1, t2, dact\n        save dact\n\n\n!output flux and state variable\n\n        did = 1\n\n\n        if(nlst(did)%rtFlag .eq. 0) return\n!--------LPR add 2014-06-24---------------------------\n!    it is rapid model\n#ifdef WRF_HYDRO_RAPID\n\n        if(nlst(did)%channel_option .eq. 4) then\n                !write(83,*) infxsrt\n                runoff  = infxsrt + soldrain\n\n\t\t!---MPI debug information-------\n                !write(60+my_id,*) \"before hrldas_RAPID_ini step 1\"\n                !call flush(60+my_id)\n\n                call hrldas_RAPID_ini(ntime)\n\n                call system_clock(count=clock_count_1, count_rate=clock_rate)\n\n                !write(60+my_id,*) \"after hrldas_RAPID_ini step 2\"\n                !call flush(60+my_id)\n#ifdef MPP_LAND\n                call write_io_real(runoff,g_runoff)\n\n                !write(60+my_id,*) \"before hrldas_RAPID_exe step 3\"\n                !call flush(60+my_id)\n\n                call mpp_land_sync()\n                call system_clock(count=clock_count_2, count_rate=clock_rate)\n                call hrldas_RAPID_exe(g_runoff,global_nx,global_ny)\n                call mpp_land_sync()\n                !write(60+my_id,*) \"after hrldas_RAPID_exe step 4\"\n                !call flush(60+my_id)\n\n#else\n                call hrldas_RAPID_exe(runoff,ii,jj)\n#endif\n\n                call system_clock(count=clock_count_3, count_rate=clock_rate)\n                timeAcc2 = timeAcc2+ float(clock_count_3-clock_count_2)/float(clock_rate)\n                timeAcc1 = timeAcc1+ float(clock_count_3-clock_count_1)/float(clock_rate)\n                write(6,*) \"Timing (accumulated time for Rapid) :\",timeAcc1, timeAcc2\n\n\n                sfcheadrt = 0.0\n\n\n                return\n        endif\n#endif\n!--------LPR add end----------------------------------\n\n\n\n\n!        write(6,*) \"nlst_rt(did)%CHANRTSWCRT nlst_rt(did)%SUBRTSWCRT  nlst_rt(did)%OVRTSWCRT =\", &\n!                 nlst_rt(did)%CHANRTSWCRT, nlst_rt(did)%SUBRTSWCRT,  nlst_rt(did)%OVRTSWCRT\n\n        IF (nlst(did)%GWBASESWCRT                 .eq. 0 &\n               .and. nlst(did)%SUBRTSWCRT         .eq. 0 &\n               .and. nlst(did)%OVRTSWCRT          .eq. 0 &\n               .and. nlst(did)%channel_only       .eq. 0 &\n               .and. nlst(did)%channelBucket_only .eq. 0  ) return\n\n\n        if(nlst(did)%channel_only       .eq. 0 .and. &\n           nlst(did)%channelBucket_only .eq. 0        ) then\n           ! decompose the hrldas 1-d data into routing domain\n           RT_DOMAIN(did)%STC = STC\n           RT_DOMAIN(did)%SMC = SMC\n           RT_DOMAIN(did)%SH2OX = SH2OX\n           RT_DOMAIN(did)%infxsrt = infxsrt\n           RT_DOMAIN(did)%soldrain = soldrain\n        end if\n\n           if(nlst(did)%GWBASESWCRT == 3) gw2d(did)%qsgw = qsgw\n\n#ifdef MPP_LAND\n        if(my_id .eq. IO_id) then\n           call  time_seconds(t1)\n        endif\n#endif\n\n        ntime = 1\n\n        call HYDRO_exe(did)\n\n#ifdef MPP_LAND\n        if(my_id .eq. IO_id) then\n           call  time_seconds(t2)\n           dact = dact + t2 - t1\n#ifdef HYDRO_D\n           write(6,*) \"accumulated time (s): \",dact\n#endif\n        endif\n#endif\n\n        if(nlst(did)%channel_only       .eq. 0 .and. &\n           nlst(did)%channelBucket_only .eq. 0        ) then\n           ! add for update the HRLDAS state variable.\n           STC = rt_domain(did)%STC\n           SMC = rt_domain(did)%SMC\n           SH2OX = rt_domain(did)%SH2OX\n           sfcheadrt = rt_domain(did)%overland%control%surface_water_head_lsm\n        end if\n        if(nlst(did)%GWBASESWCRT == 3)  qsgw = gw2d(did)%qsgw\n\n!? not sure for the following\n!           grid%xice(its:ite,jts:jte) = rt_domain(did)%sice\n\n\n     end subroutine hrldas_cpl_HYDRO\n\n    subroutine hrldas_cpl_HYDRO_ini(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk,kt,dt, olddate,zsoil)\n\n\n       implicit none\n\n       integer ii,jj,kk\n       integer k, kt\n       real :: dt\n       real,dimension(ii,jj,kk) :: STC,SMC,SH2OX\n       real,dimension(ii,jj) ::infxsrt,sfcheadrt, soldrain\n       real, dimension(kk) :: zsoil\n       character(len = *) :: olddate\n\n        integer ::  did\n\n        integer ntime\n\n        integer :: i,j\n\n!output flux and state variable\n\n        did = 1\n\n\n\n        if(.not. RT_DOMAIN(did)%initialized) then\n           nlst(did)%dt = dt\n           nlst(did)%olddate(1:19) = olddate(1:19)\n           nlst(did)%startdate(1:19) = olddate(1:19)\n\n           nlst(did)%nsoil = kk\n#ifdef MPP_LAND\n           call mpp_land_bcast_int1(nlst(did)%nsoil)\n#endif\n           allocate(nlst(did)%zsoil8(nlst(did)%nsoil))\n           nlst(did)%zsoil8(1:nlst(did)%nsoil) = zsoil(1:nlst(did)%nsoil)\n\n\n           call HYDRO_ini(ntime,did,ix0=1,jx0=1)\n\n           if(nlst(did)%sys_cpl .ne. 1) then\n              call hydro_stop(\"In module_hrldas_HYDRO.F hrldas_cpl_HYDRO_ini()\"// &\n                   \" - sys_cpl should be 1. Check hydro.namelist file.\")\n           endif\n\n           RT_DOMAIN(did)%initialized = .true.\n\n#ifdef WRF_HYDRO_RAPID\n!--------LPR add 2014-06-24---------------------------\n           if(nlst(did)%rtFlag .eq. 0) return\n!  it  is rapid model.\n           return\n        endif ! if(.not. RT_DOMAIN(did)%initialized) then\n!--------LPR add 2014-06-24---------------------------\n#endif\n\n          if (nlst(did)%GWBASESWCRT .eq. 0 &\n               .and. nlst(did)%SUBRTSWCRT .eq.0  &\n               .and. nlst(did)%OVRTSWCRT .eq. 0 ) return\n\n#ifdef MPP_LAND\n          call mpp_land_bcast_real1(nlst(did)%dt)\n#endif\n          sfcheadrt = rt_domain(did)%overland%control%surface_water_head_lsm\n          infxsrt = rt_domain(did)%infxsrt\n          if(nlst(did)%rst_typ .eq. 1) then\n             STC = rt_domain(did)%STC\n             SMC = rt_domain(did)%SMC\n             SH2OX = rt_domain(did)%SH2OX\n          else\n             if(nlst(did)%sys_cpl .eq. 1) then\n                where( abs(STC) .gt. 500) stc = 282\n                where( abs(SMC) .gt. 500) SMC = 0.25\n                where( abs(SH2OX) .gt. 500) SH2OX = 0.25\n             endif\n          endif\n       endif  ! if(.not. RT_DOMAIN(did)%initialized) then\n\n     end subroutine hrldas_cpl_HYDRO_ini\n\n     subroutine open_print_mpp(iunit)\n       implicit none\n       integer iunit\n       character(len=48) fileout\n!#ifdef NCEP_WCOSS\n       character(len=32) diag_prefix\n       integer len, status\n!#endif\n\n       if(open_unit_status == 999) return\n       open_unit_status = 999\n\n#ifdef NCEP_WCOSS\n       CALL GET_ENVIRONMENT_VARIABLE('FORT78',diag_prefix, len, status, .true.)\n       if (status .ge. 2) then\n          write (*,*) 'get_environment_variable failed: status = ', status\n          call hydro_stop(\"In module_hrldas_HYDRO.F open_print_mpp() - \"// &\n                          \"GET_ENVIRONMENT_VARIABLE(FORT78) Failed.\")\n       end if\n       if (status .eq. 1) then\n          write (*,*) 'env var does not exist'\n          call hydro_stop(\"In module_hrldas_HYDRO.F open_print_mpp() - \"// &\n                          \"FORT78 environment variable does not exist.\")\n\n       end if\n       if (status .eq. -1) then\n          write (*,*) 'env var length = ', len, ' truncated to 32'\n          len = 32\n       end if\n       if (len .eq. 0) then\n         write (*,*) 'env var exists  but has no value'\n         call hydro_stop(\"In module_hrldas_HYDRO.F open_print_mpp() - \"// &\n                         \"FORT78 environment variable exists but has no value.\")\n       end if\n#else\n       diag_prefix = 'diag_hydro.'\n#endif\n\n#ifdef MPP_LAND\n       write(fileout,'(a11,i0.5)') TRIM(diag_prefix),my_id\n#else\n       write(fileout,'(a11,i0.5)') TRIM(diag_prefix),0\n#endif\n       open(iunit,file=fileout,form=\"formatted\")\n     endsubroutine open_print_mpp\nend module module_HRLDAS_HYDRO\n"
  },
  {
    "path": "src/CPL/Noah_cpl/Makefile",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\n\n\ninclude ../../macros\n\nMODFLAG =       -I./ -I ../../MPP -I ../../mod\n\nOBJS = \\\n\tmodule_hrldas_HYDRO.o \\\n\thrldas_drv_HYDRO.o    \nall:\t$(OBJS) \n\n.F.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -o $(@) $(F90FLAGS) $(MODFLAG) -I$(NETCDF_INC) $(*).F\n\t@echo \"\"\n\tar -r ../../lib/libHYDRO.a $(@)\n\n#\n# Dependencies:\n#\nmodule_hrldas_HYDRO.o: ../../Data_Rec/module_RT_data.o ../../Data_Rec/module_namelist.o ../../HYDRO_drv/module_HYDRO_drv.o\n\nhrldas_drv_HYDRO.o: module_hrldas_HYDRO.o ../../Data_Rec/module_namelist.o ../../Routing/module_lsm_forcing.o\n\n\nclean:\n\trm -f *.o *.mod *.stb *~ Noah_hrldas_beta\n"
  },
  {
    "path": "src/CPL/Noah_cpl/hrldas_drv_HYDRO.F",
    "content": "\n!2345678\n       subroutine hrldas_drv_HYDRO(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk, qsgw)\n          use module_hrldas_HYDRO, only: hrldas_cpl_HYDRO\n          implicit none\n          integer:: ii,jj,kk\n          real,dimension(ii,jj,kk) :: STC,SMC,SH2OX\n          real,dimension(ii,jj) ::infxsrt,sfcheadrt, soldrain, qsgw\n\n          call hrldas_cpl_HYDRO(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk, qsgw)  \n       end subroutine hrldas_drv_HYDRO\n\n       subroutine hrldas_drv_HYDRO_ini(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk,kt,dt,olddate,zsoil)\n          use module_hrldas_HYDRO, only: hrldas_cpl_HYDRO_ini, open_print_mpp\n          implicit none\n          integer:: ii,jj,kk, kt\n          character(len=*) :: olddate\n          real :: dt\n          real,dimension(ii,jj,kk) :: STC,SMC,SH2OX\n          real,dimension(ii,jj) ::infxsrt,sfcheadrt, soldrain\n          real, dimension(kk) :: zsoil\n             call hrldas_cpl_HYDRO_ini(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk,kt,dt,olddate,zsoil)  \n#ifdef NCEP_WCOSS\n             call open_print_mpp(78)\n#else\n             call open_print_mpp(6)\n#endif\n       end subroutine hrldas_drv_HYDRO_ini\n\n       subroutine HYDRO_forcing_drv (indir,forc_typ, snow_assim,olddate,     &\n          ixs, ixe,jxs,jxe,                       &\n          T2,Q2X,U,V,PRES,XLONG,SHORT,PRCP1,lai,fpar,snodep, kt,FORCING_TIMESTEP,prcp_old)\n\n         use module_lsm_forcing, only: read_hydro_forcing, read_hydro_forcing_seq\n         use config_base, only: nlst\n         use module_hydro_stop, only: HYDRO_stop\n\n         implicit none\n         integer did, ixs,ixe,jxs,jxe\n         integer ix,jx, kt\n         character(len=19) :: olddate\n         character(len=*) :: indir\n         real, dimension(ixs:ixe,jxs:jxe):: T2,Q2X,U,V,PRES,XLONG,SHORT,PRCP1, &\n                 lai, fpar,snodep  ,prcp_old\n         integer :: forc_typ, snow_assim, FORCING_TIMESTEP\n\n         ix = ixe-ixs+1\n         jx = jxe-jxs+1\n         did = 1\n!yw          call read_hydro_forcing( &\n         call read_hydro_forcing_seq( &\n            indir, olddate, &\n            nlst(did)%hgrid,&\n            ix,jx,forc_typ,snow_assim,  &\n            T2,q2x,u,v,pres,xlong,short,prcp1,&\n            lai,fpar,snodep,FORCING_TIMESTEP*1.0,kt ,prcp_old)\n       end subroutine HYDRO_forcing_drv\n\n       subroutine get_greenfrac(inFile,greenfrac, idim, jdim, olddate)\n          use config_base, only: nlst\n          implicit none\n          character(len=*) :: olddate, inFile\n          integer :: idim, jdim\n          real, dimension(idim,jdim):: greenfrac\n          integer:: mm, dd, did\n          integer :: months\n          months = 12\n          did = 1\n          read(olddate(6:7),*) mm\n          read(olddate(9:10),*) dd\n          call get_greenfrac_netcdf(inFile,greenfrac,idim, jdim, months,mm,dd) \n       end subroutine get_greenfrac\n\n\n      subroutine get_greenfrac_netcdf(fileName,array3, idim, jdim, ldim,mm,dd)\n          use module_hydro_stop, only: HYDRO_stop\n          implicit none\n#         include \"netcdf.inc\"\n          character(len=*) :: fileName\n          integer, intent(in) :: mm,dd\n          integer, intent(in) :: idim, jdim, ldim\n          real, dimension(idim,jdim) :: array\n          real, dimension(idim,jdim) :: array2\n          real, dimension(idim,jdim) :: diff\n          real, dimension(idim,jdim), intent(out) :: array3\n          integer :: iret, varid, ncid\n          real, dimension(idim,jdim,ldim) :: xtmp\n          integer, dimension(1) :: mp\n          integer :: i, j, mm2,daytot\n          real :: ddfrac\n          character(len=24), parameter :: name = \"GREENFRAC\"\n\n!          units = \"fraction\"\n\n          iret = nf_open(trim(fileName), NF_NOWRITE, ncid)\n          if(iret /= 0) then\n              write(6,*) \"FATAL ERROR: failed to open file in get_greenfrac: \", trim(fileName)\n              call hydro_stop(\"In hrldas_drv_HYDRO.F get_greenfrac_netcdf() - failed to open file\") \n          endif\n\n          iret = nf_inq_varid(ncid,  trim(name),  varid)\n          if (iret /= 0) then\n             print*, 'name = \"', trim(name)//'\"'\n             print*, \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_greenfrac_netcdf:  nf_inq_varid\"\n             call hydro_stop(\"In hrldas_drv_HYDRO.F get_greenfrac_netcdf() - nf_inq_varid problem\")\n          endif\n\n          iret = nf_get_var_real(ncid, varid, xtmp)\n          if (iret /= 0) then\n\n             print*, 'name = \"', trim(name)//'\"'\n             print*, \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_greenfrac_netcdf:  nf_get_var_real\"\n             call hydro_stop(\"In hrldas_drv_HYDRO.F get_greenfrac_netcdf() - nf_get_var_real problem\")\n          endif\n\n\n          if (mm.lt.12) then\n            mm2 = mm+1\n          else\n            mm2 = 1\n                end if\n\n          !DJG_DES Set up dates for daily interpolation...\n                if (mm.eq.1.OR.mm.eq.3.OR.mm.eq.5.OR.mm.eq.7.OR.mm.eq.8.OR.mm.eq.10.OR.mm.eq.12) then\n                   daytot = 31\n                else if (mm.eq.4.OR.mm.eq.6.OR.mm.eq.9.OR.mm.eq.11) then \n                   daytot = 30\n                else if (mm.eq.2) then\n                   daytot = 28\n                end if\n                ddfrac = float(dd)/float(daytot)\n                if (ddfrac.gt.1.0) ddfrac = 1.0   ! Assumes Feb. 29th change is same as Feb 28th\n\n#ifdef HYDRO_D\n               print *,\"DJG_DES Made it past netcdf read...month = \",mm,mm2,dd,daytot,ddfrac\n#endif\n\n          do i = 1, idim\n             do j = 1, jdim\n                array(i,j) = xtmp(i,j,mm)   !GREENFRAC in geogrid in units of fraction from month 1\n                array2(i,j) = xtmp(i,j,mm2)   !GREENFRAC in geogrid in units of fraction from month 1\n                diff(i,j) = array2(i,j) - array(i,j)\n                array3(i,j) = array(i,j) + ddfrac * diff(i,j)\n             enddo\n          enddo\n          iret=nf_close(ncid)\n      end subroutine get_greenfrac_netcdf\n\n\n      subroutine HYDRO_HRLDAS_ini(fileName,ix,jx, nsoil,smc,stc,sh2ox, cmc, t1, weasd, &\n            snodep,lai, fpar, vegtyp,SHDMIN,SHDMAX,FNDSNOWH)\n          use module_hydro_stop, only: HYDRO_stop\n          ! read the field from wrfinput or output file\n          implicit none\n#         include \"netcdf.inc\"\n          character(len=*) fileName\n          integer :: ix,jx , nsoil, i, j\n          integer :: iret, ncid, ierr, varid\n          real,dimension(ix,jx,nsoil):: smc,stc,sh2ox\n          real,dimension(ix,jx):: cmc, t1, weasd, snodep, lai, fpar ,SHDMIN,SHDMAX\n          integer, dimension(ix,jx) ::    vegtyp\n          logical :: FNDSNOWH\n!yw          real, dimension(50) :: shdtbl\n!yw          data shdtbl /0.1,0.8,0.8,0.8,0.8,0.8,0.8,0.7,0.7,0.5,  &\n!yw              0.8,0.7,0.95,0.7,0.8,0,0.6,0.6,0.1, &\n!yw              0.6,0.6,0.6,0.3,0,0.5,0,0,           &\n!yw              0,0,0,0,0,0,0,0,0,0,0,0,0,          &\n!yw              0,0,0,0,0,0,0,0,0,0/\n\n\n          iret = nf_open(trim(fileName), NF_NOWRITE, ncid)\n          if(iret /= 0) then\n              write(6,*) \"FATAL ERROR: failed to open file in HYDRO_HRLDAS_ini: \", trim(fileName)\n              call hydro_stop('In hrldas_drv_HYDRO.F HYDRO_HRLDAS_ini() - failed to open file.')\n          else\n#ifdef HYDRO_D\n              write(6,*) \"initialization from the file  : \", trim(fileName)\n\n#endif\n          endif\n\n           iret = nf_inq_varid(ncid,\"VEGFRA\",  varid)\n           if (iret == 0) then\n               iret = nf_get_var_real(ncid, varid, fpar)\n               if(maxval(fpar) .gt. 10 .and. (maxval(fpar) .lt. 1000)) fpar = fpar/100.\n           endif\n\n           iret = nf_inq_varid(ncid,\"SHDMIN\",  varid)\n           if (iret == 0) then\n               iret = nf_get_var_real(ncid, varid, SHDMIN)\n               if(maxval(SHDMIN) .gt. 10 .and. (maxval(SHDMIN) .lt. 1000)) SHDMIN = SHDMIN / 100.\n           endif\n\n\n           iret = nf_inq_varid(ncid,\"SHDMAX\",  varid)\n           if (iret == 0) then\n              iret = nf_get_var_real(ncid, varid, SHDMAX)\n               if(maxval(SHDMAX) .gt. 10 .and. (maxval(SHDMAX) .lt. 1000)) SHDMAX = SHDMAX / 100.\n           endif\n\n!yw\n!yw           do j = 1, jx\n!yw              do i = 1, ix\n!yw                  fpar(i,j) = shdtbl(vegtyp(i,j))\n!yw              end do\n!yw           end do\n!yw\n\n\n          iret = nf_inq_varid(ncid,\"LAI\",  varid)\n          if (iret == 0) iret = nf_get_var_real(ncid, varid, lai)\n\n          iret = nf_inq_varid(ncid,\"SNOWH\",  varid)\n          if (iret == 0) then\n#ifdef HYDRO_D\n             print*, \"read snowh for initialization ....\"\n#endif\n             iret = nf_get_var_real(ncid, varid, snodep)\n             FNDSNOWH = .true.\n          else\n             FNDSNOWH = .false.\n          endif\n\n          iret = nf_inq_varid(ncid,\"SNOW\",  varid)\n          if (iret == 0) then\n#ifdef HYDRO_D\n             print*, \"read snow for initialization ....\"\n#endif\n             iret = nf_get_var_real(ncid, varid, weasd)\n             weasd = weasd * 1.0E-3    ! transfer the unit from mm to m\n          endif\n\n\n!         where(snodep < weasd) snodep = weasd * 10\n!            write(6,*) \"SNOW(20,1)=\",weasd(20,1)\n!            write(6,*) \"SNOWH(20,1)=\",snodep(20,1)\n\n          iret = nf_inq_varid(ncid,\"TSK\",  varid)\n          if (iret == 0) iret = nf_get_var_real(ncid, varid, t1)\n\n          iret = nf_inq_varid(ncid,\"CANWAT\",  varid)\n          if (iret == 0) iret = nf_get_var_real(ncid, varid, cmc)\n\n          iret = nf_inq_varid(ncid,\"SMOIS\",  varid)\n          if (iret == 0) iret = nf_get_var_real(ncid, varid, smc)\n\n          iret = nf_inq_varid(ncid,\"TSLB\",  varid)\n          if (iret == 0) iret = nf_get_var_real(ncid, varid, stc)\n\n          iret = nf_inq_varid(ncid,\"SH2O\",  varid)\n          if (iret == 0) iret = nf_get_var_real(ncid, varid, sh2ox)\n\n          iret=nf_close(ncid)\n\n!yw    added for\n             where( abs(t1) .gt. 500) t1 = 282\n             where( abs(stc) .gt. 500) stc = 282\n             where( abs(SMC) .gt. 1) SMC = 0.25\n             where(sh2ox == 0) sh2ox = smc\n             where( abs(SH2OX) .gt. 500) SH2OX = 0.25\n\n\n\n       end subroutine HYDRO_HRLDAS_ini\n\n       subroutine getHydroNameList(varName,pVar)\n          use module_hrldas_HYDRO, only: getNameList\n          implicit none\n          integer ::  pVar\n          character(len=*)  ::varName\n          call getNameList(varName,pVar)\n       end subroutine getHydroNameList\n"
  },
  {
    "path": "src/CPL/Noah_cpl/module_hrldas_HYDRO.F",
    "content": "\nmodule module_HRLDAS_HYDRO\n\n! NDHMS  module\n#ifdef MPP_LAND\n    use module_mpp_land, only: global_nx, global_ny, decompose_data_real, &\n                 write_io_real, my_id, mpp_land_bcast_real1, IO_id, &\n                 mpp_land_bcast_int1, mpp_land_sync, MPP_LAND_INIT\n    use MODULE_CPL_LAND, only: HYDRO_COMM_WORLD\n    use module_hydro_stop, only: HYDRO_stop\n#endif\n    use module_HYDRO_drv, only: HYDRO_ini, HYDRO_exe, HYDRO_rst_out\n    use module_rt_data, only:  rt_domain\n    use config_base, only: nlst\n    use module_gw_gw2d_data, only: gw2d\n\n    implicit none\n    integer begg, endg\n    integer :: numg, numl, numc, nump\n    INTEGER, PARAMETER :: double=8\n    real(kind=double), pointer :: r2p(:,:) , r1p(:)\n\n    integer ::  begl, endl, begc, endc, begp, endp\n\n    real, allocatable, dimension(:,:) :: vg_test\n    integer :: nn\n    integer :: open_unit_status\n\n\n\nCONTAINS\n\n    subroutine hrldas_cpl_HYDRO(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk, qsgw)\n\n\n       implicit none\n\n       integer ii,jj,kk\n       integer k\n       real,dimension(ii,jj,kk) :: STC,SMC,SH2OX\n       real,dimension(ii,jj) ::infxsrt,sfcheadrt, soldrain, qsgw\n\n        integer ::  did\n\n        integer ntime\n\n        integer :: i,j\n\n        real*8 :: t1, t2, dact\n        integer :: clock_count_1, clock_count_2, clock_rate\n        save dact\n\n\n!output flux and state variable\n\n        did = 1\n\n        if (nlst(did)%rtFlag .eq. 0) return\n\n!        write(6,*) \"nlst_rt(did)%CHANRTSWCRT nlst_rt(did)%SUBRTSWCRT  nlst_rt(did)%OVRTSWCRT =\", &\n!                 nlst_rt(did)%CHANRTSWCRT, nlst_rt(did)%SUBRTSWCRT,  nlst_rt(did)%OVRTSWCRT\n\n        IF (nlst(did)%GWBASESWCRT .eq. 0 &\n               .and. nlst(did)%SUBRTSWCRT .eq.0  &\n               .and. nlst(did)%OVRTSWCRT .eq. 0 ) return\n\n\n\n! decompose the hrldas 1-d data into routing domain\n#ifdef MPP_LAND\n        do k = 1, kk\n           call decompose_data_real(STC(:,:,k),RT_DOMAIN(did)%STC(:,:,k))\n           call decompose_data_real(SMC(:,:,k),RT_DOMAIN(did)%SMC(:,:,k))\n           call decompose_data_real(SH2OX(:,:,k),RT_DOMAIN(did)%SH2OX(:,:,k))\n        end do\n        call decompose_data_real(infxsrt,RT_DOMAIN(did)%infxsrt)\n        call decompose_data_real(soldrain,RT_DOMAIN(did)%soldrain)\n\n\tif(nlst(did)%GWBASESWCRT == 3)&\n        call decompose_data_real(qsgw,gw2d(did)%qsgw)\n#else\n        RT_DOMAIN(did)%STC = STC\n        RT_DOMAIN(did)%SMC = SMC\n        RT_DOMAIN(did)%SH2OX = SH2OX\n        RT_DOMAIN(did)%infxsrt = infxsrt\n        RT_DOMAIN(did)%soldrain = soldrain\n        if(nlst(did)%GWBASESWCRT == 3) &\n\t  gw2d(did)%qsgw = qsgw\n#endif\n\n#ifdef MPP_LAND\n#ifdef HYDRO_D\n        if(my_id .eq. IO_id) then\n           call system_clock(count=clock_count_1, count_rate=clock_rate)\n        endif\n#endif\n#endif\n\n        ntime = 1\n\n        call HYDRO_exe(did)\n#ifdef MPP_LAND\n#ifdef HYDRO_D\n           call mpp_land_sync()\n        if(my_id .eq. IO_id) then\n           call system_clock(count=clock_count_2, count_rate=clock_rate)\n           dact = dact + float(clock_count_2-clock_count_1)/float(clock_rate)\n           write(6,*) \"timing: \", float(clock_count_2-clock_count_1)/float(clock_rate), &\n                 \"accumulated time (s): \",dact\n        endif\n#endif\n#endif\n\n! add for update the HRLDAS state variable.\n#ifdef MPP_LAND\n        do k = 1, kk\n           call write_io_real(rt_domain(did)%STC(:,:,k),STC(:,:,k))\n           call write_io_real(rt_domain(did)%SMC(:,:,k),SMC(:,:,k))\n           call write_io_real(rt_domain(did)%SH2OX(:,:,k),SH2OX(:,:,k))\n        end do\n         call write_io_real(rt_domain(did)%overland%control%surface_water_head_lsm,sfcheadrt)\n\tif(nlst(did)%GWBASESWCRT == 3)&\n         call write_io_real(gw2d(did)%qsgw,qsgw)\n#else\n        STC = rt_domain(did)%STC\n        SMC = rt_domain(did)%SMC\n        SH2OX = rt_domain(did)%SH2OX\n        sfcheadrt = rt_domain(did)%overland%control%surface_water_head_lsm\n\tif(nlst(did)%GWBASESWCRT == 3)&\n        qsgw = gw2d(did)%qsgw\n#endif\n\n!? not sure for the following\n!           grid%xice(its:ite,jts:jte) = rt_domain(did)%sice\n\n     end subroutine hrldas_cpl_HYDRO\n\n    subroutine hrldas_cpl_HYDRO_ini(STC,SMC,SH2OX,infxsrt,sfcheadrt,soldrain,ii,jj,kk,kt,dt, olddate,zsoil)\n\n\n       implicit none\n\n       integer ii,jj,kk\n       integer k, kt\n       real :: dt\n       real,dimension(ii,jj,kk) :: STC,SMC,SH2OX\n       real,dimension(ii,jj) ::infxsrt,sfcheadrt, soldrain\n       real, dimension(kk) :: zsoil\n       character(len = 19) :: olddate\n\n        integer ::  did\n\n        integer ntime\n\n        integer :: i,j\n\n!output flux and state variable\n\n        did = 1\n\n\n        if(.not. RT_DOMAIN(did)%initialized) then\n           call MPP_LAND_INIT()\n           nlst(did)%dt = dt\n           nlst(did)%olddate(1:19) = olddate(1:19)\n           nlst(did)%startdate(1:19) = olddate(1:19)\n\n           nlst(did)%nsoil = kk\n#ifdef MPP_LAND\n           call mpp_land_bcast_int1(nlst(did)%nsoil)\n#endif\n           allocate(nlst(did)%zsoil8(nlst(did)%nsoil))\n           nlst(did)%zsoil8(1:nlst(did)%nsoil) = zsoil(1:nlst(did)%nsoil)\n\n\n           call HYDRO_ini(ntime,did,ix0=1,jx0=1)\n\n           if(nlst(did)%rtFlag .eq. 0) return\n\n            if(nlst(did)%sys_cpl .ne. 1) then\n               write(6,*) \"FATAL ERROR: sys_cpl should be 1.\"\n                call hydro_stop(\"In module_hrldas_HYDRO.F hrldas_cpl_HYDRO_ini()\"// &\n                                           \" - sys_cpl should be 1. Check hydro.namelist file.\")\n            endif\n\n           RT_DOMAIN(did)%initialized = .true.\n\n           IF (nlst(did)%GWBASESWCRT .eq. 0 &\n               .and. nlst(did)%SUBRTSWCRT .eq.0  &\n               .and. nlst(did)%OVRTSWCRT .eq. 0 ) return\n\n#ifdef MPP_LAND\n           call mpp_land_bcast_real1(nlst(did)%dt)\n           call write_io_real(rt_domain(did)%overland%control%surface_water_head_lsm,sfcheadrt)\n           call write_io_real(rt_domain(did)%infxsrt, infxsrt)\n!          call write_io_real(rt_domain(did)%soldrain,soldrain)\n           if(nlst(did)%rst_typ .eq. 1) then\n              do k = 1, kk\n                 call write_io_real(rt_domain(did)%STC(:,:,k),STC(:,:,k))\n                 call write_io_real(rt_domain(did)%SMC(:,:,k),SMC(:,:,k))\n                 call write_io_real(rt_domain(did)%SH2OX(:,:,k),SH2OX(:,:,k))\n              end do\n           else\n              if(nlst(did)%sys_cpl .eq. 1) then\n                 where( abs(STC) .gt. 500) stc = 282\n                 where( abs(SMC) .gt. 500) SMC = 0.25\n                 where( abs(SH2OX) .gt. 500) SH2OX = 0.25\n\n                 where( abs(SH2OX) .eq. 1) SH2OX = 0.25\n                 where( abs(SMC) .eq. 1) SMC = 0.25\n                 where( SH2OX .le. 0.0001) SH2OX = 0.25\n                 where( SMC .le. 0.0001) SMC = 0.25\n              endif\n           endif\n#else\n           sfcheadrt = rt_domain(did)%overland%control%surface_water_head_lsm\n           infxsrt = rt_domain(did)%infxsrt\n           if(nlst(did)%rst_typ .eq. 1) then\n              STC = rt_domain(did)%STC\n              SMC = rt_domain(did)%SMC\n              SH2OX = rt_domain(did)%SH2OX\n           else\n              if(nlst(did)%sys_cpl .eq. 1) then\n                 where( abs(STC) .gt. 500) stc = 282\n                 where( abs(SMC) .gt. 500) SMC = 0.25\n                 where( abs(SH2OX) .gt. 500) SH2OX = 0.25\n\n                 where( abs(SH2OX) .eq. 1) SH2OX = 0.25\n                 where( abs(SMC) .eq. 1) SMC = 0.25\n              endif\n           endif\n#endif\n        endif\n\n     end subroutine hrldas_cpl_HYDRO_ini\n\n     subroutine open_print_mpp(iunit)\n       implicit none\n       integer iunit\n       character(len=16) fileout\n       character(len=32) diag_prefix\n#ifdef NCEP_WCOSS\n       integer len, status\n#endif\n\n       if(open_unit_status == 999) return\n       open_unit_status = 999\n\n\n#ifdef NCEP_WCOSS\n       CALL GET_ENVIRONMENT_VARIABLE('FORT78',diag_prefix, len, status, .true.)\n       if (status .ge. 2) then\n          write (*,*) 'FATAL ERROR: In module_hrldas_HYDRO.F open_print_mpp() - '// &\n                      'get_environment_variable failed: status = ', status\n          stop\n       end if\n       if (status .eq. 1) then\n          write (*,*) 'FATAL ERROR: In module_hrldas_HYDRO.F open_print_mpp() - '// &\n                      'env var does not exist'\n          stop\n       end if\n       if (status .eq. -1) then\n          write (*,*) 'env var length = ', len, ' truncated to 32'\n          len = 32\n       end if\n       if (len .eq. 0) then\n         write (*,*) 'FATAL ERROR: In module_hrldas_HYDRO.F open_print_mpp() - '// &\n                     'env var exists  but has no value'\n         stop\n       end if\n#else\n       diag_prefix = 'diag_hydro.'\n#endif\n\n#ifdef MPP_LAND\n       write(fileout,'(a11,i0.5)') TRIM(diag_prefix),my_id\n#else\n       write(fileout,'(a11,i0.5)') TRIM(diag_prefix),0\n#endif\n       open(iunit,file=fileout,form=\"formatted\")\n     end subroutine open_print_mpp\n\n     subroutine getNameList(varName,pVar)\n          implicit none\n          integer :: pVar\n          integer :: did\n          character(len=*) :: varName\n          did = 1\n          if(varName .eq. \"GWSPINCYCLES\") then\n               pVar = nlst(did)%gwSpinCycles\n          elseif(varName .eq. \"GWBASESWCRT\") then\n               pVar = nlst(did)%GWBASESWCRT\n          elseif(varName .eq. \"GWSOILCPL\") then\n               pVar = nlst(did)%gwsoilcpl\n          else\n               pVar = 0\n          endif\n     end subroutine getNameList\nend module module_HRLDAS_HYDRO\n"
  },
  {
    "path": "src/CPL/WRF_cpl/CMakeLists.txt",
    "content": "add_library(hydro_wrf_cpl STATIC\n        wrf_drv_HYDRO.F90\n        module_wrf_HYDRO.F90\n)\n\nadd_dependencies(hydro_wrf_cpl\n        hydro_mpp\n        hydro_utils\n        hydro_debug_utils\n        hydro_data_rec\n        hydro_driver\n        hydro_orchestrator\n        ${PROJECT_NAME}_Core\n        MPI::MPI_Fortran\n)\n\ntarget_link_libraries(hydro_wrf_cpl PRIVATE hydro_driver)\n\ntarget_include_directories(hydro_wrf_cpl\n        PRIVATE\n        $<TARGET_PROPERTY:${PROJECT_NAME}_Core,Fortran_MODULE_DIRECTORY>\n        $<TARGET_PROPERTY:esmf_time_f90,Fortran_MODULE_DIRECTORY>\n)\n\ntarget_include_directories(hydro_wrf_cpl PUBLIC\n        ${MPI_Fortran_MODULE_DIR}\n)\n"
  },
  {
    "path": "src/CPL/WRF_cpl/Makefile",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\n\n\ninclude ../../macros\n\nMODFLAG =       -I./ -I ../../MPP -I ../../mod \n\nWRF_ROOT = ../../..\nOBJS = \\\n\tmodule_wrf_HYDRO.o \\\n\twrf_drv_HYDRO.o    \nall:\t$(OBJS) \n\n.F90.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -I$(NETCDFINC) -o $(@) $(F90FLAGS) $(MODFLAG) -I$(WRF_ROOT)/frame -I$(WRF_ROOT)/main -I$(WRF_ROOT)/external/esmf_time_f90 $(*).F90\n\t@echo \"\"\n\tar -r ../../lib/libHYDRO.a $(@)\n\n#\n# Dependencies:\n#\nmodule_wrf_HYDRO.o: ../../Data_Rec/module_RT_data.o ../../Data_Rec/module_namelist.o ../../HYDRO_drv/module_HYDRO_drv.o\n\nwrf_drv_HYDRO.o: module_wrf_HYDRO.o\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/CPL/WRF_cpl/Makefile.cpl",
    "content": "# Makefile \n\nall:\n\t(cd ../../; make -f Makefile.comm BASIC)\n\t(make)\n\nclean:\n\t(make clean)\n\t(cd ../../; make -f Makefile.comm clean)\n"
  },
  {
    "path": "src/CPL/WRF_cpl/module_wrf_HYDRO.F90",
    "content": "\nmodule module_WRF_HYDRO\n\n#ifdef MPP_LAND\n    use mpi\n    use module_mpp_land, only: global_nx, global_ny, decompose_data_real, &\n                 write_io_real, my_id, mpp_land_bcast_real1, IO_id, &\n                mpp_land_bcast_real, mpp_land_bcast_int1, mpp_land_init\n    use module_CPL_LAND, only: CPL_LAND_INIT, cpl_outdate, HYDRO_COMM_WORLD\n    use module_hydro_stop, only: HYDRO_stop\n#endif\n    use module_HYDRO_drv, only: HYDRO_ini, HYDRO_exe\n\n    use module_rt_data, only:  rt_domain\n    use module_gw_gw2d_data, only:  gw2d\n    use module_CPL_LAND, only: CPL_LAND_INIT, cpl_outdate\n    use config_base, only: nlst\n    USE module_domain, ONLY : domain, domain_clock_get\n    USE module_configure, ONLY : grid_config_rec_type\n    !yw USE module_configure, only : config_flags\n    USE module_configure, only: model_config_rec\n\n\n    implicit none\n\n    !yw   added for check soil moisture and soiltype\n    integer ::  checkSOIL_flag\n\n#ifndef MPP_LAND\n    character(len=19) :: cpl_outdate\n#endif\n!\n! added to consider the adaptive time step from WRF model.\n    real    :: dtrt_ter0  , dtrt_ch0\n    integer ::  mm0\n\n\n\n\nCONTAINS\n\n!wrf_cpl_HYDRO will not call the off-line lsm\n!ywGW subroutine wrf_cpl_HYDRO(HYDRO_dt,grid, config_flags, its,ite,jts,jte)\n    subroutine wrf_cpl_HYDRO(HYDRO_dt,grid,its,ite,jts,jte)\n\n       implicit none\n       TYPE ( domain ), INTENT(INOUT) :: grid\n!ywGW       TYPE ( grid_config_rec_type ), INTENT(IN) :: config_flags\n       integer its, ite, jts, jte, ij\n       real :: HYDRO_dt\n\n\n        integer k, ix,jx, mm, nn\n\n        integer ::  did\n\n        integer ntime\n\n        integer :: i,j\n\n        integer :: ierr\n\n!output flux and state variable\n\n        did = 1\n\n\n        ix = ite - its + 1\n        jx = jte - jts + 1\n\n        if(HYDRO_dt .le. 0) then\n             write(6,*) \"WARNING: HYDRO_dt <= 0 from land input. set it to be 1 seconds.\"\n             HYDRO_dt = 1\n        endif\n\n        ntime = 1\n\n\n            nlst(did)%dt = HYDRO_dt\n\n\n        if(.not. RT_DOMAIN(did)%initialized) then\n           !yw nlst_rt(did)%nsoil = config_flags%num_soil_layers\n           !nlst_rt(did)%nsoil = model_config_rec%num_metgrid_soil_levels\n           nlst(did)%nsoil = grid%num_soil_layers\n\n\n#ifdef MPP_LAND\n           call MPI_Comm_dup(MPI_COMM_WORLD, HYDRO_COMM_WORLD, ierr)\n           call MPP_LAND_INIT(grid%e_we - grid%s_we - 1, grid%e_sn - grid%s_sn - 1)\n\n           call mpp_land_bcast_int1 (nlst(did)%nsoil)\n#endif\n           allocate(nlst(did)%zsoil8(nlst(did)%nsoil))\n           if(grid%zs(1) <  0) then\n              nlst(did)%zsoil8(1:nlst(did)%nsoil) = grid%zs(1:nlst(did)%nsoil)\n           else\n              nlst(did)%zsoil8(1:nlst(did)%nsoil) = -1*grid%zs(1:nlst(did)%nsoil)\n           endif\n\n            CALL domain_clock_get( grid, current_timestr=cpl_outdate)\n            nlst(did)%startdate(1:19) = cpl_outdate(1:19)\n            nlst(did)%olddate(1:19) = cpl_outdate(1:19)\n\n\n#ifdef MPP_LAND\n            call CPL_LAND_INIT(its,ite,jts,jte)\n#endif\n\n#ifdef HYDRO_D\n               write(6,*) \"sf_surface_physics is \", grid%sf_surface_physics\n#endif\n\n           if(grid%sf_surface_physics .eq. 5) then\n                ! clm4\n               call HYDRO_ini(ntime,did=did,ix0=1,jx0=1)\n           else\n               call HYDRO_ini(ntime,did,ix0=ix,jx0=jx,vegtyp=grid%IVGTYP(its:ite,jts:jte),soltyp=grid%isltyp(its:ite,jts:jte))\n           endif\n\n\n\n            if(nlst(did)%sys_cpl .ne. 2) then\n               call hydro_stop(\"In module_wrf_HYDRO.F wrf_cpl_HYDRO() - \"// &\n                               \"sys_cpl should be 2.  Check hydro.namelist file.\")\n            endif\n\n\n            nlst(did)%startdate(1:19) = cpl_outdate(1:19)\n            nlst(did)%olddate(1:19) = cpl_outdate(1:19)\n\n            nlst(did)%dt = HYDRO_dt\n            if(nlst(did)%dtrt_ter .ge. HYDRO_dt) then\n               nlst(did)%dtrt_ter = HYDRO_dt\n               mm0 = 1\n            else\n               mm = HYDRO_dt/nlst(did)%dtrt_ter\n               if(mm*nlst(did)%dtrt_ter.lt. HYDRO_dt) nlst(did)%dtrt_ter = HYDRO_dt/mm\n               mm0 = mm\n            endif\n\n            dtrt_ter0 = nlst(did)%dtrt_ter\n\n            if(nlst(did)%dtrt_ch .ge. HYDRO_dt) then\n               nlst(did)%dtrt_ch = HYDRO_dt\n               mm0 = 1\n            else\n               mm = HYDRO_dt/nlst(did)%dtrt_ch\n               if(mm*nlst(did)%dtrt_ch.lt. HYDRO_dt) nlst(did)%dtrt_ch = HYDRO_dt/mm\n               mm0 = mm\n            endif\n\n            dtrt_ch0 = nlst(did)%dtrt_ch\n        endif\n\n            if((mm0*nlst(did)%dtrt_ter) .ne. HYDRO_dt) then   ! WRF model time step changed.\n               if(dtrt_ter0 .ge. HYDRO_dt) then\n                  nlst(did)%dtrt_ter = HYDRO_dt\n                  mm0 = 1\n               else\n                  mm = HYDRO_dt/dtrt_ter0\n                  if(mm*dtrt_ter0 .lt. HYDRO_dt) nlst(did)%dtrt_ter = HYDRO_dt/mm\n                  mm0 = mm\n               endif\n            endif\n\n            if((mm0*nlst(did)%dtrt_ch) .ne. HYDRO_dt) then   ! WRF model time step changed.\n               if(dtrt_ch0 .ge. HYDRO_dt) then\n                  nlst(did)%dtrt_ch = HYDRO_dt\n                  mm0 = 1\n               else\n                  mm = HYDRO_dt/dtrt_ch0\n                  if(mm*dtrt_ch0 .lt. HYDRO_dt) nlst(did)%dtrt_ch = HYDRO_dt/mm\n                  mm0 = mm\n               endif\n            endif\n\n#ifdef HYDRO_D\n        write(6,*) \"mm, nlst(did)%dt = \",mm, nlst(did)%dt\n#endif\n\n        if(nlst(did)%rtFlag .eq. 0) return\n\n\n        nn = nlst(did)%nsoil\n\n        ! get the data from WRF\n\n\n\n       if((.not. RT_DOMAIN(did)%initialized) .and. (nlst(did)%rst_typ .eq. 1) ) then\n#ifdef HYDRO_D\n           write(6,*) \"restart initial data from offline file\"\n#endif\n       else\n            do k = 1, nlst(did)%nsoil\n                RT_DOMAIN(did)%STC(:,:,k) = grid%TSLB(its:ite,k,jts:jte)\n                RT_DOMAIN(did)%smc(:,:,k) = grid%smois(its:ite,k,jts:jte)\n                RT_DOMAIN(did)%sh2ox(:,:,k) = grid%sh2o(its:ite,k,jts:jte)\n            end do\n            rt_domain(did)%infxsrt = grid%infxsrt(its:ite,jts:jte)\n            rt_domain(did)%soldrain = grid%soldrain(its:ite,jts:jte)\n       endif\n\n            call HYDRO_exe(did)\n\n\n! add for update the WRF state variable.\n            do k = 1, nlst(did)%nsoil\n                ! grid%TSLB(its:ite,k,jts:jte) = RT_DOMAIN(did)%STC(:,:,k)\n                grid%smois(its:ite,k,jts:jte) = RT_DOMAIN(did)%smc(:,:,k)\n                grid%sh2o(its:ite,k,jts:jte) = RT_DOMAIN(did)%sh2ox(:,:,k)\n            end do\n\n! update WRF variable after running routing model.\n            grid%sfcheadrt(its:ite,jts:jte) = rt_domain(did)%overland%control%surface_water_head_lsm\n\n! provide groundwater soil flux to WRF for fully coupled simulations (FERSCH 09/2014)\n            if(nlst(did)%GWBASESWCRT .eq. 3 ) then\n!Wei Yu: comment the following two lines. Not ready for WRF3.7 release\n!yw             grid%qsgw(its:ite,jts:jte) = gw2d(did)%qsgw\n!yw             config_flags%gwsoilcpl = nlst_rt(did)%gwsoilcpl\n            end if\n\n!yw not sure for the following\n!           grid%xice(its:ite,jts:jte) = rt_domain(did)%sice\n\n            RT_DOMAIN(did)%initialized = .true.\n     end subroutine wrf_cpl_HYDRO\n\n\n\n\n\n!program drive rtland\n! This subroutine will be used if the 4-layer Noah lsm is not used.\n      subroutine wrf2lsm (z1,v1,kk1,z,vout,ix,jx,kk,vegtyp)\n!  input: z1,v1,kk1,z,ix,jx,kk\n!  output: vout\n!  interpolate based on soil layer: z1 and z\n!  z :  soil layer of output variable.\n!  z1: array of soil layers of input variable.\n         implicit none\n         integer:: i,j,k\n         integer:: kk1, ix,jx,kk, vegtyp(ix,jx)\n         real :: z1(kk1), z(kk), v1(ix,kk1,jx),vout(ix,jx,kk)\n\n\n         do j = 1, jx\n            do i = 1, ix\n                do k = 1, kk\n                  call interpLayer(Z1,v1(i,1:kk1,j),kk1,Z(k),vout(i,j,k))\n                end do\n            end do\n         end do\n      end subroutine wrf2lsm\n\n! This subroutine will be used if the 4-layer Noah lsm is not used.\n      subroutine lsm2wrf (z1,v1,kk1,z,vout,ix,jx,kk,vegtyp)\n!  input: z1,v1,kk1,z,ix,jx,kk\n!  output: vout\n!  interpolate based on soil layer: z1 and z\n!  z :  soil layer of output variable.\n!  z1: array of soil layers of input variable.\n         implicit none\n         integer:: i,j,k\n         integer:: kk1, ix,jx,kk, vegtyp(ix,jx)\n         real :: z1(kk1), z(kk), v1(ix,jx,kk1),vout(ix,kk,jx)\n\n\n         do j = 1, jx\n            do i = 1, ix\n                 do k = 1, kk\n                    call interpLayer(Z1,v1(i,j,1:kk1),kk1,Z(k),vout(i,k,j))\n                 end do\n            end do\n         end do\n      end subroutine lsm2wrf\n\n      subroutine interpLayer(inZ,inV,inK,outZ,outV)\n         implicit none\n         integer:: k, k1, k2\n         integer :: inK\n         real:: inV(inK),inZ(inK)\n         real:: outV, outZ, w1, w2\n\n         if(outZ .le. inZ(1)) then\n             w1 = (inZ(2)-outZ)/(inZ(2)-inZ(1))\n             w2 = (inZ(1)-outZ)/(inZ(2)-inZ(1))\n             outV = inV(1)*w1-inV(2)*w2\n             return\n         elseif(outZ .ge. inZ(inK)) then\n             w1 = (outZ-inZ(inK-1))/(inZ(inK)-inZ(inK-1))\n             w2 = (outZ-inZ(inK))  /(inZ(inK)-inZ(inK-1))\n             outV = inV(inK)*w1 -inV(inK-1)* w2\n             return\n         else\n            do k = 2, inK\n             if((inZ(k) .ge. outZ).and.(inZ(k-1) .le. outZ) ) then\n                k1  = k-1\n                k2 = k\n                w1 = (outZ-inZ(k1))/(inZ(k2)-inZ(k1))\n                w2 = (inZ(k2)-outZ)/(inZ(k2)-inZ(k1))\n                outV = inV(k2)*w1 + inV(k1)*w2\n                return\n             end if\n            end do\n         endif\n      end subroutine interpLayer\n\n      subroutine lsm_wrf_input(did,vegtyp,soltyp,ix,jx)\n         implicit none\n         integer did, leng\n         parameter(leng=100)\n         integer :: i,j, nn, ix,jx\n         integer, dimension(ix,jx) :: soltyp, vegtyp\n         real, dimension(leng) :: xdum1, MAXSMC,refsmc,wltsmc\n\n\n         where(soltyp == 14) VEGTYP = 16\n         where(VEGTYP == 16 ) soltyp = 14\n\n         RT_DOMAIN(did)%VEGTYP = vegtyp\n\n!      input OV_ROUGH from OVROUGH.TBL\n#ifdef MPP_LAND\n       if(my_id .eq. IO_id) then\n#endif\n\n#ifndef NCEP_WCOSS\n       open(71,file=\"HYDRO.TBL\", form=\"formatted\")\n!read OV_ROUGH first\n          read(71,*) nn\n          read(71,*)\n          do i = 1, nn\n             read(71,*) RT_DOMAIN(did)%OV_ROUGH(i)\n          end do\n!read parameter for LKSAT\n          read(71,*) nn\n          read(71,*)\n          do i = 1, nn\n             read(71,*) xdum1(i), MAXSMC(i),refsmc(i),wltsmc(i)\n          end do\n       close(71)\n\n#else\n      open(13, form=\"formatted\")\n!read OV_ROUGH first\n          read(13,*) nn\n          read(13,*)\n          do i = 1, nn\n             read(13,*) RT_DOMAIN(did)%OV_ROUGH(i)\n          end do\n!read parameter for LKSAT\n          read(13,*) nn\n          read(13,*)\n          do i = 1, nn\n             read(13,*) xdum1(i), MAXSMC(i),refsmc(i),wltsmc(i)\n          end do\n       close(13)\n#endif\n#ifdef MPP_LAND\n       endif\n       call mpp_land_bcast_real(leng,RT_DOMAIN(did)%OV_ROUGH)\n       call mpp_land_bcast_real(leng,xdum1)\n       call mpp_land_bcast_real(leng,MAXSMC)\n       call mpp_land_bcast_real(leng,refsmc)\n       call mpp_land_bcast_real(leng,wltsmc)\n#endif\n\n       rt_domain(did)%lksat = 0.0\n       do j = 1, RT_DOMAIN(did)%jx\n             do i = 1, RT_DOMAIN(did)%ix\n                rt_domain(did)%lksat(i,j) = xdum1(soltyp(i,j) ) * 1000.0\n                IF(rt_domain(did)%VEGTYP(i,j) == 1 ) THEN   ! urban\n                    rt_domain(did)%SMCMAX1(i,j) = 0.45\n                    rt_domain(did)%SMCREF1(i,j) = 0.42\n                    rt_domain(did)%SMCWLT1(i,j) = 0.40\n                else\n                    rt_domain(did)%SMCMAX1(i,j) = MAXSMC(soltyp(I,J))\n                    rt_domain(did)%SMCREF1(i,j) = refsmc(soltyp(I,J))\n                    rt_domain(did)%SMCWLT1(i,j) = wltsmc(soltyp(I,J))\n                ENDIF\n             end do\n       end do\n\n\n      end subroutine lsm_wrf_input\n\n      subroutine  checkSoil(did)\n          implicit none\n          integer :: did\n          where(rt_domain(did)%smc(:,:,1) <=0) RT_DOMAIN(did)%VEGTYP = 16\n          where(rt_domain(did)%sh2ox(:,:,1) <=0) RT_DOMAIN(did)%VEGTYP = 16\n          where(rt_domain(did)%smc(:,:,1) >=100) RT_DOMAIN(did)%VEGTYP = 16\n          where(rt_domain(did)%sh2ox(:,:,1) >=100) RT_DOMAIN(did)%VEGTYP = 16\n      end subroutine checkSoil\n\nend module module_wrf_HYDRO\n"
  },
  {
    "path": "src/CPL/WRF_cpl/module_wrf_HYDRO_downscale.F90",
    "content": "\nmodule module_WRF_HYDRO\n\n#ifdef MPP_LAND\n    use module_mpp_land, only: global_nx, global_ny, decompose_data_real, &\n                 write_io_real, my_id, mpp_land_bcast_real1, IO_id, &\n                mpp_land_bcast_real, mpp_land_bcast_int1\n#endif\n    use module_HYDRO_drv, only: HYDRO_ini, HYDRO_exe\n\n    use module_rt_data, only:  rt_domain\n    use module_CPL_LAND, only: cpl_outdate\n    use config_base, only: nlst\n    USE module_domain, ONLY : domain, domain_clock_get\n\n    implicit none\n\n    !yw   added for check soil moisture and soiltype\n    integer ::  checkSOIL_flag\n\n!\n! added to consider the adaptive time step from WRF model.\n    real    :: dtrt0\n    integer ::  mm0, itime\n\n\n\n\nCONTAINS\n\n!wrf_cpl_HYDRO_finescale will not call the off-line lsm\n    subroutine wrf_cpl_HYDRO_finescale(HYDRO_dt,grid,its,ite,jts,jte)\n       use module_NoahMP_hrldas_driver, only: noah_timestep , land_driver_ini\n       implicit none\n       TYPE ( domain ), INTENT(INOUT) :: grid\n       integer its, ite, jts, jte, ij\n       real :: HYDRO_dt\n\n\n        integer k, ix,jx, mm\n\n        integer ::  did\n\n        integer ntime\n\n        integer :: i,j\n\n\n!output flux and state variable\n\n        did = 1\n        ix = ite - its + 1\n        jx = jte - jts + 1\n\n        if(HYDRO_dt .le. 0) then\n             write(6,*) \"Warning: HYDRO_dt <= 0 from land input. set it to be 1 seconds.\"\n             HYDRO_dt = 1\n        endif\n\n        ntime = 1\n\n\n            nlst(did)%dt = HYDRO_dt\n\n        itime = itime + 1\n        if(.not. RT_DOMAIN(did)%initialized) then\n           itime = 1\n\n           nlst(did)%nsoil = grid%num_soil_layers\n\n#ifdef MPP_LAND\n           call mpp_land_bcast_int1 (nlst(did)%nsoil)\n#endif\n           allocate(nlst(did)%zsoil8(nlst(did)%nsoil))\n           if(grid%zs(1) <  0) then\n              nlst(did)%zsoil8(1:nlst(did)%nsoil) = grid%zs(1:nlst(did)%nsoil)\n           else\n              nlst(did)%zsoil8(1:nlst(did)%nsoil) = -1*grid%zs(1:nlst(did)%nsoil)\n           endif\n\n            CALL domain_clock_get( grid, current_timestr=cpl_outdate)\n            nlst(did)%startdate(1:19) = cpl_outdate(1:19)\n            nlst(did)%olddate(1:19) = cpl_outdate(1:19)\n\n!yw continue\n\n            call land_driver_ini(nn,its,ite,jts,jte)\n\n#ifdef HYDRO_D\n               write(6,*) \"sf_surface_physics is \", grid%sf_surface_physics\n#endif\n            nlst(did)%startdate(1:19) = cpl_outdate(1:19)\n            nlst(did)%olddate(1:19) = cpl_outdate(1:19)\n\n            nlst(did)%dt = HYDRO_dt\n            noah_timestep = nlst(did)%dt\n\n            if(nlst(did)%dtrt .lt. HYDRO_dt) then\n               nlst(did)%dtrt = HYDRO_dt\n               mm0 = 1\n            else\n               mm = HYDRO_dt/nlst(did)%dtrt\n               if(mm*nlst(did)%dtrt .lt. HYDRO_dt) nlst(did)%dtrt = HYDRO_dt/mm\n               mm0 = mm\n            endif\n\n            dtrt0 = nlst(did)%dtrt\n        endif\n\n            if((mm0*nlst(did)%dtrt) .ne. HYDRO_dt) then   ! WRF model time step changed.\n               if(dtrt0 .lt. HYDRO_dt) then\n                  nlst(did)%dtrt = HYDRO_dt\n                  mm0 = 1\n               else\n                  mm = HYDRO_dt/dtrt0\n                  if(mm*dtrt0 .lt. HYDRO_dt) nlst(did)%dtrt = HYDRO_dt/mm\n                  mm0 = mm\n               endif\n            endif\n\n#ifdef HYDRO_D\n        write(6,*) \"mm, nlst(did)%dt = \",mm, nlst(did)%dt\n#endif\n\n! get forcing data from WRF\n         call wrf2l_finemesh(grid,its,ite,jts,jte)\n\n         call HYDRO_land_finemesh_exe(itime)\n\n         call l_finemesh2wrf(grid)\n\n         RT_DOMAIN(did)%initialized = .true.\n\n     end subroutine wrf_cpl_HYDRO_finescale\n\n! get the forcing data from WRF\nsubroutine wrf2l_finemesh(,its,ite,jts,jte, T_PHY0,U_PHY0,V_PHY0,p_hyd_w0,RAINBL0,QV_CURR0,LAI0,VEGFRA0, &\n          emiss0, albedo0   )\n       use module_NoahMP_hrldas_driver, only: P8W, T_PHY, U_PHY, V_PHY, QV_CURR, RAINBL_tmp, LAI, VEGFRA, finemesh,finemesh_factor, &\n              emiss,albedo\n\n       implicit none\n       real, domain(:,:),INTENT(IN) :: T_PHY0,U_PHY0,V_PHY0,p_hyd_w0,RAINBL0,QV_CURR0,LAI0,VEGFRA0, &\n             emiss0, albedo0, TSK0,HFX0, QFX0,LH0,GRDFLX0,SMSTAV0,SMSTOT0,SFCRUNOFF0, UDRUNOFF0, SNOWC0, SMOIS0, SH2O0, &\n             TSLB0, SNOW0,SNOWH0,CANWAT0,ACSNOM0,ACSNOW0,QSFC0,ISNOWXY0,TVXY0,TGXY0,CANICEXY0,CANLIQXY0,EAHXY0,TAHXY0,CMXY0, &\n             CHXY0,FWETXY0,SNEQVOXY0,ALBOLDXY0,QSNOWXY0,WSLAKEXY0,ZWTXY0,WAXY0,WTXY0,TSNOXY0,ZSNSOXY0,SNICEXY0,SNLIQXY0, &\n             LFMASSXY0,RTMASSXY0,STMASSXY0,WOODXY0,STBLCPXY0,FASTCPXY0,XLAIXY0,XSAIXY0,TAUSSXY0,SMOISEQ0,SMCWTDXY0,DEEPRECHXY0, &\n             RECHXY0, &\n\n       integer, intent(in):: its,ite,jts,jte\n       call wrf2finegrid(T_PHY0(its:ite,jts:jte), T_PHY(:,1,:),ite-its+1,jte-jts+1,finemesh_factor)\n       call wrf2finegrid(U_PHY0(its:ite,jts:jte), U_PHY(:,1,:),ite-its+1,jte-jts+1,finemesh_factor)\n       call wrf2finegrid(V_PHY0(its:ite,jts:jte), V_PHY(:,1,:),ite-its+1,jte-jts+1,finemesh_factor)\n       call wrf2finegrid(p_hyd_w0(its:ite,jts:jte), P8W(:,1,:),ite-its+1,jte-jts+1,finemesh_factor)\n       call wrf2finegrid(RAINBL0(its:ite,jts:jte), RAINBL_tmp,ite-its+1,jte-jts+1,finemesh_factor)\n       call wrf2finegrid(QV_CURR0(its:ite,jts:jte), QV_CURR(:,1,:),ite-its+1,jte-jts+1,finemesh_factor)\n!  update some varialbes.\n       if(finemesh .ne. 1) then   ! update the LAI and VEGFRA for each time step. Note: this is from the WRF grid.\n           call wrf2finegrid(albedo0(its:ite,jts:jte), albedo)\n           call wrf2finegrid(emiss0(its:ite,jts:jte), emiss)\n           call wrf2finegrid(LAI0(its:ite,jts:jte), LAI)\n           call wrf2finegrid(VEGFRA0(its:ite,jts:jte), VEGFRA)\n       endif\nend subroutine wrf2l_finemesh\n\nsubroutine l_finemesh2wrf(T_PHY0,U_PHY0,V_PHY0,p_hyd_w0,RAINBL0,QV_CURR0,LAI0,VEGFRA0,its,ite,jts,jte)\n   use module_NoahMP_hrldas_driver, only: P8W, T_PHY, U_PHY, V_PHY, QV_CURR, RAINBL_tmp, LAI, VEGFRA, finemesh,finemesh_factor\n   implicit none\n!variable for output only\n   real,dimension(:,:), intent(out)::   T2MVXY0,T2MBXY0,Q2MVXY0,Q2MBXY0,TRADXY0,NEEXY0,GPPXY0,NPPXY0,FVEGXY0,RUNSFXY0,  &\n             RUNSBXY0,ECANXY0,EDIRXY0,ETRANXY0,FSAXY0,&\n             FIRAXY0,APARXY0,PSNXY0,SAVXY0,SAGXY0,RSSUNXY0,RSSHAXY0,BGAPXY0,WGAPXY0,TGVXY0,TGBXY0,CHVXY0,CHBXY0,SHGXY0,SHCXY0,SHBXY0, &\n             EVGXY0,EVBXY0,GHVXY0,GHBXY0,IRGXY0,IRCXY0,IRBXY0,TRXY0,EVCXY0,CHLEAFXY0,CHUCXY0,CHV2XY0,CHB2XY0\n\n         call finegrid2wrf(T2MVXY,T2MVXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(T2MBXY,tt0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(FVEGXY,FVEGXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(Q2MVXY,Q2MVXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(Q2MBXY,Q2MBXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n      if(finemesh .ne. 1) then\n         call finegrid2wrf(TRADXY,TRADXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(NEEXY,NEEXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(GPPXY,GPPXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(NPPXY,NPPXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(RUNSFXY,RUNSFXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(RUNSBXY,RUNSBXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(ECANXY,ECANXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(EDIRXY,EDIRXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(ETRANXY,ETRANXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(FSAXY,FSAXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(FIRAXY,FIRAXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(APARXY,APARXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(PSNXY,PSNXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(SAVXY,SAVXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(SAGXY,SAGXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(RSSUNXY,RSSUNXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(RSSHAXY,RSSHAXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(BGAPXY,BGAPXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(WGAPXY,WGAPXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(TGVXY,TGVXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n\n         call finegrid2wrf(TGBXY,TGBXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(CHVXY,CHVXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(CHBXY,CHBXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(SHGXY,SHGXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(SHCXY,SHCXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(SHBXY,SHBXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(EVGXY,EVGXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(EVBXY,EVBXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(GHVXY,GHVXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(GHBXY,GHBXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(IRGXY,IRGXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(IRCXY,IRCXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(IRBXY,IRBXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(TRXY,TRXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(EVCXY,EVCXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(CHLEAFXY,CHLEAFXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(CHUCXY,CHUCXY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(CHV2XY,CHV2XY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n         call finegrid2wrf(CHB2XY,CHB2XY0(its:ite,jts:jte),ite-its+1,jte-jts+1,finemesh_factor)\n      endif\nend subroutine l_finemesh2wrf\n\nsubroutine wrf2finegrid(wrfGrid,fineGrid,ix,jx,AGGFACTRT)\n   implicit none\n   real, dimension(:,:), intent(in)::wrfGrid\n   real, dimension(:,:), intent(out)::fineGrid\n   integer:: i,j,ii,jj,ix,jx, AGGFACTRT\n   do j = 1, jx\n      do i = 1, ix\n              do ii       =AGGFACTRT-1,0,-1\n              do jj       =AGGFACTRT-1,0,-1\n                  IXXRT=I*AGGFACTRT-ii\n                  JYYRT=J*AGGFACTRT-jj\n                  fineGrid(ixxrt,jyyrt) = wrfGrid(i,j)\n              enddo\n              enddo\n      enddo ! end do loop for ix\n   enddo ! end do loop for jx\nend subroutine wrf2finegrid\n\nsubroutine finegrid2wrf(fineGrid,wrfGrid,ix,jx,AGGFACTRT)\n   implicit none\n   real, dimension(:,:), intent(out)::wrfGrid\n   real, dimension(:,:), intent(in)::fineGrid\n   integer:: i,j,ii,jj,ix,jx, AGGFACTRT\n   do j = 1, jx\n      do i = 1, ix\n              wrfGrid(k,j) = 0.0\n              do ii       =AGGFACTRT-1,0,-1\n              do jj       =AGGFACTRT-1,0,-1\n                  IXXRT=I*AGGFACTRT-ii\n                  JYYRT=J*AGGFACTRT-jj\n                  wrfGrid(i,j) = wrfGrid(i,j) + fineGrid(ixxrt,jyyrt)\n              enddo\n              enddo\n              wrfGrid(i,j) = wrfGrid(i,j) / (AGGFACTRT*AGGFACTRT)\n      enddo ! end do loop for ix\n   enddo ! end do loop for jx\nend subroutine finegrid2wrf\n\n\n\n!program drive rtland\n! This subroutine will be used if the 4-layer Noah lsm is not used.\n      subroutine wrf2lsm (z1,v1,kk1,z,vout,ix,jx,kk,vegtyp)\n!  input: z1,v1,kk1,z,ix,jx,kk\n!  output: vout\n!  interpolate based on soil layer: z1 and z\n!  z :  soil layer of output variable.\n!  z1: array of soil layers of input variable.\n         implicit none\n         integer:: i,j,k\n         integer:: kk1, ix,jx,kk, vegtyp(ix,jx)\n         real :: z1(kk1), z(kk), v1(ix,kk1,jx),vout(ix,jx,kk)\n\n\n         do j = 1, jx\n            do i = 1, ix\n                do k = 1, kk\n                  call interpLayer(Z1,v1(i,1:kk1,j),kk1,Z(k),vout(i,j,k)) \n                end do\n            end do\n         end do\n      end subroutine wrf2lsm\n\n! This subroutine will be used if the 4-layer Noah lsm is not used.\n      subroutine lsm2wrf (z1,v1,kk1,z,vout,ix,jx,kk,vegtyp)\n!  input: z1,v1,kk1,z,ix,jx,kk\n!  output: vout\n!  interpolate based on soil layer: z1 and z\n!  z :  soil layer of output variable.\n!  z1: array of soil layers of input variable.\n         implicit none\n         integer:: i,j,k\n         integer:: kk1, ix,jx,kk, vegtyp(ix,jx)\n         real :: z1(kk1), z(kk), v1(ix,jx,kk1),vout(ix,kk,jx)\n\n\n         do j = 1, jx\n            do i = 1, ix\n                 do k = 1, kk\n                    call interpLayer(Z1,v1(i,j,1:kk1),kk1,Z(k),vout(i,k,j)) \n                 end do\n            end do\n         end do\n      end subroutine lsm2wrf\n\n      subroutine interpLayer(inZ,inV,inK,outZ,outV)\n         implicit none\n         integer:: k, k1, k2\n         integer :: inK\n         real:: inV(inK),inZ(inK)\n         real:: outV, outZ, w1, w2\n\n         if(outZ .le. inZ(1)) then\n             w1 = (inZ(2)-outZ)/(inZ(2)-inZ(1))\n             w2 = (inZ(1)-outZ)/(inZ(2)-inZ(1))\n             outV = inV(1)*w1-inV(2)*w2\n             return\n         elseif(outZ .ge. inZ(inK)) then\n             w1 = (outZ-inZ(inK-1))/(inZ(inK)-inZ(inK-1))\n             w2 = (outZ-inZ(inK))  /(inZ(inK)-inZ(inK-1))\n             outV = inV(inK)*w1 -inV(inK-1)* w2\n             return\n         else\n            do k = 2, inK\n             if((inZ(k) .ge. outZ).and.(inZ(k-1) .le. outZ) ) then\n                k1  = k-1\n                k2 = k\n                w1 = (outZ-inZ(k1))/(inZ(k2)-inZ(k1))\n                w2 = (inZ(k2)-outZ)/(inZ(k2)-inZ(k1))\n                outV = inV(k2)*w1 + inV(k1)*w2\n                return\n             end if\n            end do\n         endif\n      end subroutine interpLayer\n\n      subroutine lsm_wrf_input(did,vegtyp,soltyp,ix,jx)\n         implicit none\n         integer did, leng\n         parameter(leng=100)\n         integer :: i,j, nn, ix,jx\n         integer, dimension(ix,jx) :: soltyp, vegtyp\n         real, dimension(leng) :: xdum1, MAXSMC,refsmc,wltsmc\n\n\n         where(soltyp == 14) VEGTYP = 16\n         where(VEGTYP == 16 ) soltyp = 14\n\n         RT_DOMAIN(did)%VEGTYP = vegtyp\n\n!      input OV_ROUGH from OVROUGH.TBL\n#ifdef MPP_LAND\n       if(my_id .eq. IO_id) then\n#endif\n\n#ifndef NCEP_WCOSS\n       open(71,file=\"HYDRO.TBL\", form=\"formatted\")\n!read OV_ROUGH first\n          read(71,*) nn\n          read(71,*)\n          do i = 1, nn\n             read(71,*) RT_DOMAIN(did)%OV_ROUGH(i)\n          end do\n!read parameter for LKSAT\n          read(71,*) nn\n          read(71,*)\n          do i = 1, nn\n             read(71,*) xdum1(i), MAXSMC(i),refsmc(i),wltsmc(i)\n          end do\n       close(71)\n#else\n\n       open(13, form=\"formatted\")\n!read OV_ROUGH first\n          read(13,*) nn\n          read(13,*)\n          do i = 1, nn\n             read(13,*) RT_DOMAIN(did)%OV_ROUGH(i)\n          end do\n!read parameter for LKSAT\n          read(13,*) nn\n          read(13,*)\n          do i = 1, nn\n             read(13,*) xdum1(i), MAXSMC(i),refsmc(i),wltsmc(i)\n          end do\n       close(13)\n#endif\n\n#ifdef MPP_LAND\n       endif\n       call mpp_land_bcast_real(leng,RT_DOMAIN(did)%OV_ROUGH)\n       call mpp_land_bcast_real(leng,xdum1)\n       call mpp_land_bcast_real(leng,MAXSMC)\n       call mpp_land_bcast_real(leng,refsmc)\n       call mpp_land_bcast_real(leng,wltsmc)\n#endif\n\n       rt_domain(did)%lksat = 0.0\n       do j = 1, RT_DOMAIN(did)%jx\n             do i = 1, RT_DOMAIN(did)%ix\n                rt_domain(did)%lksat(i,j) = xdum1(soltyp(i,j) ) * 1000.0\n                IF(rt_domain(did)%VEGTYP(i,j) == 1 ) THEN   ! urban\n                    rt_domain(did)%SMCMAX1(i,j) = 0.45\n                    rt_domain(did)%SMCREF1(i,j) = 0.42\n                    rt_domain(did)%SMCWLT1(i,j) = 0.40\n                else\n                    rt_domain(did)%SMCMAX1(i,j) = MAXSMC(soltyp(I,J))\n                    rt_domain(did)%SMCREF1(i,j) = refsmc(soltyp(I,J))\n                    rt_domain(did)%SMCWLT1(i,j) = wltsmc(soltyp(I,J))\n                ENDIF\n             end do\n       end do\n\n      end subroutine lsm_wrf_input\n\nend module module_wrf_HYDRO\n"
  },
  {
    "path": "src/CPL/WRF_cpl/wrf_drv_HYDRO.F90",
    "content": "\n!2345678\n!ywGW       subroutine wrf_drv_HYDRO(HYDRO_dt,grid, config_flags, its,ite,jts,jte)\n       subroutine wrf_drv_HYDRO(HYDRO_dt,grid, its,ite,jts,jte)\n          use module_wrf_HYDRO, only: wrf_cpl_HYDRO\n          USE module_domain, ONLY : domain\n          USE module_configure, ONLY : grid_config_rec_type\n       implicit none\n          integer:: its,ite,jts,jte\n          real :: HYDRO_dt\n          TYPE ( domain ), INTENT(INOUT) :: grid\n!ywGW          TYPE ( grid_config_rec_type ), INTENT(IN) :: config_flags\n          TYPE ( grid_config_rec_type ) :: config_flags\n!         return\n\n          if(grid%num_nests .lt. 1) then\n\n!ywGW             call wrf_cpl_HYDRO(HYDRO_dt, grid, config_flags, its,ite,jts,jte)  \n             call wrf_cpl_HYDRO(HYDRO_dt, grid, its,ite,jts,jte)\n\n          endif\n       end subroutine wrf_drv_HYDRO\n\n\n       subroutine wrf_drv_HYDRO_ini(grid,its,ite,jts,jte)\n          use module_wrf_HYDRO, only: wrf_cpl_HYDRO\n          USE module_domain, ONLY : domain\n          implicit none\n           integer:: its,ite,jts,jte\n          TYPE ( domain ), INTENT(INOUT) :: grid\n\n          if(grid%num_nests .lt. 1) then\n!            call wrf_cpl_HYDRO_ini(grid,its,ite,jts,jte)\n          endif\n\n       end subroutine wrf_drv_HYDRO_ini\n"
  },
  {
    "path": "src/Data_Rec/CMakeLists.txt",
    "content": "add_library(hydro_data_rec STATIC\n        module_gw_gw2d_data.F90\n        module_rt_inc.F90\n        module_namelist_inc.F90\n        module_RT_data.F90\n        module_namelist.F90\n)\ntarget_link_libraries(hydro_data_rec PRIVATE hydro_mpp)\n"
  },
  {
    "path": "src/Data_Rec/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nOBJS = \\\n\tmodule_namelist_inc.o \\\n\tmodule_namelist.o \\\n\tmodule_rt_inc.o\t\\\n\tmodule_RT_data.o \\\n\tmodule_gw_gw2d_data.o\n\nall:\t$(OBJS)\n\n.F90.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -I$(NETCDFINC) -o $(@) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I../mod $(*).F90\n\t@echo \"\"\n\tar -r ../lib/libHYDRO.a $(@)\n\tcp *.mod ../mod\n\n# Dependencies:\n#\nmodule_namelist.o: module_namelist_inc.o\nmodule_RT_data.o: module_rt_inc.o\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Data_Rec/module_RT_data.F90",
    "content": "Module module_RT_data\n   use module_rt_inc, only: rt_field\n   implicit none\n\n   integer, parameter :: max_domain=5\n   ! define Routing data\n   type ( rt_field ), dimension (max_domain) :: RT_DOMAIN\n   save RT_DOMAIN\n   integer :: cur_did\nend module module_RT_data\n"
  },
  {
    "path": "src/Data_Rec/module_gw_gw2d_data.F90",
    "content": "\nmodule module_gw_gw2d_data\n   implicit none\n   integer, parameter :: max_domain=5\n\n   type gw_field\n      integer :: ix, jx\n      integer :: allo_status = -99\n\n      real :: dx, dt\n\n      integer, allocatable, dimension(:,:) ::  ltype     ! land-sfc type\n      real,    allocatable, dimension(:,:) ::  &\n           elev,           &  ! elev/bathymetry of sfc rel to sl (m)\n           bot,            &  ! elev. aquifer bottom rel to sl (m)\n           hycond,         &  ! hydraulic conductivity (m/s per m/m)\n           poros,          &  ! porosity (m3/m3)\n           compres,        &  ! compressibility (1/Pa)\n           ho                 ! head at start of timestep (m)\n\n      real,    allocatable, dimension(:,:) ::  &\n           h,              &  ! head, after ghmcompute (m)\n           convgw,         &  ! convergence due to gw flow (m/s)\n           excess             ! surface exceeding groundwater (mm)\n\n      real,    allocatable, dimension(:,:) ::  &\n           qdarcyRT,       &  ! approximated flux between soil and groundwater for coupled simulations on routing grid\n           qsgwrt,         &  ! flux between soil and groundwater for coupled simulations on routing grid\n           qsgw,           &  ! flux between soil and groundwater for coupled simulations on lsm grid\n           qgw_chanrt         ! flux between groundwater and channel\n\n      real  :: ebot, eocn\n      integer ::istep = 0\n\n      integer :: its, ite, jts, jte\n   end type gw_field\n\n   type (gw_field) :: gw2d(max_domain)\n   save gw2d\nend module module_gw_gw2d_data\n"
  },
  {
    "path": "src/Data_Rec/module_namelist.F90",
    "content": "module module_namelist\n\n#ifdef MPP_LAND\n          USE module_mpp_land\n#endif\n\n    use module_hydro_stop, only: HYDRO_stop\n    use module_namelist_inc, only: namelist_rt_field\n    implicit none\n    integer, parameter :: max_domain=5\n    type(namelist_rt_field) , dimension(max_domain) :: nlst_rt\n    save nlst_rt\n\ncontains\n\n    subroutine read_rt_nlst(nlst)\n          implicit none\n\n          TYPE(namelist_rt_field) nlst\n\n          integer ierr\n          integer:: RT_OPTION, CHANRTSWCRT, channel_option, &\n                    SUBRTSWCRT,OVRTSWCRT,AGGFACTRT, &\n                    GWBASESWCRT,  GW_RESTART,RSTRT_SWC,TERADJ_SOLAR, &\n                    sys_cpl, rst_typ, rst_bi_in, rst_bi_out, &\n                    gwChanCondSw, GwPreCycles, GwSpinCycles, GwPreDiagInterval, gwsoilcpl, &\n                    UDMP_OPT, io_form_outputs, bucket_loss, imperv_adj\n          real:: DTRT_TER,DTRT_CH,dxrt, gwChanCondConstIn, gwChanCondConstOut, gwIhShift\n          character(len=256) :: route_topo_f=\"\"\n          character(len=256) :: route_chan_f=\"\"\n          character(len=256) :: route_link_f=\"\"\n          logical            :: compound_channel\n          character(len=256) :: route_lake_f=\"\"\n          character(len=256) :: route_direction_f=\"\"\n          character(len=256) :: route_order_f=\"\"\n          character(len=256) :: diversions_file=\"\"\n          logical            :: reservoir_persistence_usgs\n          logical            :: reservoir_persistence_usace\n          character(len=256) :: reservoir_parameter_file=\"\"\n          character(len=256) :: reservoir_usgs_timeslice_path = \"\"\n          character(len=256) :: reservoir_usace_timeslice_path = \"\"\n          integer            :: reservoir_observation_lookback_hours\n          integer            :: reservoir_observation_update_time_interval_seconds\n          logical            :: reservoir_rfc_forecasts\n          character(len=256) :: reservoir_rfc_forecasts_time_series_path=\"\"\n          integer            :: reservoir_rfc_forecasts_lookback_hours\n          logical            :: reservoir_type_specified\n          character(len=256) :: gwbasmskfil =\"\"\n          character(len=256) :: gwstrmfil =\"\"\n          character(len=256) :: geo_finegrid_flnm =\"\"\n          character(len=256) :: udmap_file =\"\"\n          character(len=256) :: GWBUCKPARM_file = \"\"\n          integer :: reservoir_data_ingest ! STUB FOR USE OF REALTIME RESERVOIR DISCHARGE DATA. CURRENTLY NOT IN USE.\n       integer :: SOLVEG_INITSWC\n       real*8 :: out_dt, rst_dt\n       character(len=256)  :: RESTART_FILE = \"\"\n       character(len=256)  :: hydrotbl_f   = \"\"\n       logical            :: GwPreDiag, GwSpinUp\n       integer            :: split_output_count, order_to_write\n       integer :: igrid, io_config_outputs, t0OutputFlag, output_channelBucket_influx\n       character(len=256) :: geo_static_flnm = \"\"\n       character(len=1024) :: land_spatial_meta_flnm = \"\"\n       integer  :: DEEPGWSPIN\n\n       integer :: i\n\n\n          integer ::CHRTOUT_DOMAIN           ! Netcdf point timeseries output at all channel points\n          integer ::CHRTOUT_GRID                ! Netcdf grid of channel streamflow values\n          integer ::LSMOUT_DOMAIN              ! Netcdf grid of variables passed between LSM and routing components\n          integer ::RTOUT_DOMAIN                ! Netcdf grid of terrain routing variables on routing grid\n          integer  :: output_gw\n          integer  :: outlake\n          integer :: frxst_pts_out            ! ASCII text file of streamflow at forecast points\n          integer :: CHANOBS_DOMAIN           ! NetCDF point timeseries output at forecast points.\n\n\n!!! add the following two dummy variables\n       integer  :: NSOIL\n       real :: ZSOIL8(8)\n\n       logical            :: dir_e\n       character(len=1024) :: reservoir_obs_dir\n#ifdef WRF_HYDRO_NUDGING\n       character(len=256) :: nudgingParamFile\n       character(len=256) :: netwkReExFile\n       logical            :: readTimesliceParallel\n       logical            :: temporalPersistence\n       logical            :: persistBias\n       logical            :: biasWindowBeforeT0\n       character(len=256) :: nudgingLastObsFile\n       character(len=256) :: timeSlicePath\n       integer            :: nLastObs\n       integer            :: minNumPairsBiasPersist\n       integer            :: maxAgePairsBiasPersist\n       logical            :: invDistTimeWeightBias\n       logical            :: noConstInterfBias\n#endif\n\n       namelist /HYDRO_nlist/ NSOIL, ZSOIL8,&\n            RESTART_FILE,SPLIT_OUTPUT_COUNT,IGRID,&\n            geo_static_flnm, &\n            land_spatial_meta_flnm, &\n            out_dt, rst_dt, &\n            DEEPGWSPIN, SOLVEG_INITSWC, &\n            RT_OPTION, CHANRTSWCRT, channel_option, &\n                    SUBRTSWCRT,OVRTSWCRT,AGGFACTRT, dtrt_ter,dtrt_ch,dxrt,&\n                    GwSpinCycles, GwPreCycles, GwSpinUp, GwPreDiag, GwPreDiagInterval, gwIhShift, &\n                    GWBASESWCRT, gwChanCondSw, gwChanCondConstIn, gwChanCondConstOut, &\n                    route_topo_f,route_chan_f,route_link_f, compound_channel, route_lake_f, diversions_file, &\n                    reservoir_persistence_usgs, reservoir_persistence_usace, reservoir_parameter_file, reservoir_usgs_timeslice_path, &\n                    reservoir_usace_timeslice_path, reservoir_observation_lookback_hours, reservoir_observation_update_time_interval_seconds, &\n                    reservoir_rfc_forecasts,  reservoir_rfc_forecasts_time_series_path, reservoir_rfc_forecasts_lookback_hours, &\n                    reservoir_type_specified, route_direction_f,route_order_f, gwbasmskfil, geo_finegrid_flnm, gwstrmfil, &\n                    GW_RESTART,RSTRT_SWC,TERADJ_SOLAR, sys_cpl, &\n                    order_to_write , rst_typ, rst_bi_in, rst_bi_out, gwsoilcpl, &\n                    CHRTOUT_DOMAIN,CHANOBS_DOMAIN,CHRTOUT_GRID,LSMOUT_DOMAIN,&\n                    RTOUT_DOMAIN, output_gw, outlake, &\n                    frxst_pts_out, udmap_file, UDMP_OPT, GWBUCKPARM_file, bucket_loss, &\n                    io_config_outputs, io_form_outputs, hydrotbl_f, t0OutputFlag, output_channelBucket_influx, imperv_adj\n\n#ifdef WRF_HYDRO_NUDGING\n   namelist /NUDGING_nlist/ nudgingParamFile,       netwkReExFile,          &\n                            readTimesliceParallel,  temporalPersistence,    &\n                            persistBias,            nudgingLastObsFile,     &\n                            timeSlicePath,          nLastObs,               &\n                            minNumPairsBiasPersist, maxAgePairsBiasPersist, &\n                            biasWindowBeforeT0,     invDistTimeWeightBias,  &\n                            noConstInterfBias\n#endif\n\n   !! ---- End definitions ----\n\n   ! Default values for HYDRO_nlist\n   UDMP_OPT = 0\n   rst_bi_in = 0\n   rst_bi_out = 0\n   io_config_outputs = 0\n   io_form_outputs = 0\n   frxst_pts_out = 0\n   CHANOBS_DOMAIN = 0\n   t0OutputFlag = 1\n   output_channelBucket_influx = 0\n   TERADJ_SOLAR = 0\n   reservoir_data_ingest = 0 ! STUB FOR USE OF REALTIME RESERVOIR DISCHARGE DATA. CURRENTLY NOT IN USE.\n   compound_channel = .FALSE.\n   bucket_loss = 0\n   reservoir_persistence_usgs = .FALSE.\n   reservoir_persistence_usace = .FALSE.\n   reservoir_observation_lookback_hours = 18\n   reservoir_observation_update_time_interval_seconds = 86400\n   reservoir_rfc_forecasts = .FALSE.\n   reservoir_rfc_forecasts_lookback_hours = 24\n   reservoir_type_specified = .FALSE.\n   imperv_adj = 0\n\n#ifdef WRF_HYDRO_NUDGING\n   ! Default values for NUDGING_nlist\n   nudgingParamFile = \"DOMAIN/nudgingParams.nc\"\n   netwkReExFile    = \"DOMAIN/netwkReExFile.nc\"\n   readTimesliceParallel  = .true.\n   temporalPersistence    = .true.\n   persistBias            = .false.\n   biasWindowBeforeT0     = .false.\n   nudgingLastObsFile     = \"\"\n   timeSlicePath          = \"./nudgingTimeSliceObs/\"\n   nLastObs               = 960\n   minNumPairsBiasPersist = 8\n   maxAgePairsBiasPersist = -99999\n   invDistTimeWeightBias  = .false.\n   noConstInterfBias      = .false.\n#endif\n\n#ifdef MPP_LAND\n       if(IO_id .eq. my_id) then\n#endif\n#ifndef NCEP_WCOSS\n          open(12, file=\"hydro.namelist\", form=\"FORMATTED\")\n#else\n          open(12, form=\"FORMATTED\")\n#endif\n          read(12, HYDRO_nlist, iostat=ierr)\n          if(ierr .ne. 0) call hydro_stop(\"HYDRO_nlst namelist error in read_rt_nlst\")\n\n#ifdef WRF_HYDRO_NUDGING\n          read(12, NUDGING_nlist, iostat=ierr)\n          if(ierr .ne. 0) call hydro_stop(\"NUDGING_nlst namelist error in read_rt_nlst\")\n          !! Conditional default values for nuding_nlist\n          if(maxAgePairsBiasPersist .eq. -99999) maxAgePairsBiasPersist = -1*nLastObs\n#endif\n          close(12)\n\n#ifdef MPP_LAND\n       endif\n#endif\n\n! ADCHANGE: move these checks to more universal namelist checks...\n   if ( io_config_outputs .eq. 4 ) RTOUT_DOMAIN = 0\n\n   if(output_channelBucket_influx .ne. 0) then\n      if(nlst%dt .ne. out_dt*60) &\n           call hydro_stop(\"read_rt_nlst:: output_channelBucket_influx =! 0 inconsistent with out_dt and NOAH_TIMESTEP choices.\")\n      if(output_channelBucket_influx .eq. 2 .and. GWBASESWCRT .ne. 1 .and. GWBASESWCRT .ne. 2 .and. GWBASESWCRT .ne. 4) &\n           call hydro_stop(\"read_rt_nlst:: output_channelBucket_influx = 2 but GWBASESWCRT != 1 or 2 or 4.\")\n   end if\n\n   if(CHANRTSWCRT .eq. 0 .and. channel_option .lt. 3) channel_option = 3\n\n#ifdef MPP_LAND\n!  call mpp_land_bcast_real1(DT)\n  call mpp_land_bcast_int1(SPLIT_OUTPUT_COUNT)\n  call mpp_land_bcast_int1(IGRID)\n  call mpp_land_bcast_int1(io_config_outputs)\n  call mpp_land_bcast_int1(io_form_outputs)\n  call mpp_land_bcast_int1(t0OutputFlag)\n  call mpp_land_bcast_int1(output_channelBucket_influx)\n  call mpp_land_bcast_real1_double(out_dt)\n  call mpp_land_bcast_real1_double(rst_dt)\n  call mpp_land_bcast_int1(DEEPGWSPIN)\n  call mpp_land_bcast_int1(SOLVEG_INITSWC)\n#endif\n\n\n#ifdef MPP_LAND\n      call mpp_land_bcast_int1(nlst%NSOIL)\n      do i = 1, nlst%NSOIL\n        call mpp_land_bcast_real1(nlst%ZSOIL8(i))\n      end do\n#ifdef HYDRO_D\n      write(6,*) \"nlst%NSOIL = \", nlst%NSOIL\n      write(6,*) \"nlst%ZSOIL8 = \",nlst%ZSOIL8\n#endif\n#endif\n\n  !  nlst%DT = DT !!JLM: Note that %dt is set in the Land/WRF initialization,\n  !               !!JLM: e.g. CPL/NoahMP_cpl/module_hrldas_HYDRO.F:hrldas_cpl_HYDRO_ini\n  nlst%RESTART_FILE = RESTART_FILE\n  nlst%hydrotbl_f = trim(hydrotbl_f)\n  nlst%SPLIT_OUTPUT_COUNT = SPLIT_OUTPUT_COUNT\n  nlst%IGRID = IGRID\n  nlst%io_config_outputs = io_config_outputs\n  nlst%io_form_outputs = io_form_outputs\n  nlst%t0OutputFlag = t0OutputFlag\n  nlst%output_channelBucket_influx = output_channelBucket_influx\n  nlst%geo_static_flnm = geo_static_flnm\n  nlst%land_spatial_meta_flnm = land_spatial_meta_flnm\n  nlst%out_dt = out_dt\n  nlst%rst_dt = rst_dt\n  nlst%DEEPGWSPIN = DEEPGWSPIN\n  nlst%SOLVEG_INITSWC = SOLVEG_INITSWC\n  nlst%reservoir_obs_dir = \"testDirectory\"\n  nlst%diversions_file = diversions_file\n  nlst%reservoir_persistence_usgs = reservoir_persistence_usgs\n  nlst%reservoir_persistence_usace = reservoir_persistence_usace\n  nlst%reservoir_parameter_file = reservoir_parameter_file\n  nlst%reservoir_usgs_timeslice_path = reservoir_usgs_timeslice_path\n  nlst%reservoir_usace_timeslice_path = reservoir_usace_timeslice_path\n  nlst%reservoir_observation_lookback_hours = reservoir_observation_lookback_hours\n  nlst%reservoir_observation_update_time_interval_seconds = reservoir_observation_update_time_interval_seconds\n  nlst%reservoir_rfc_forecasts = reservoir_rfc_forecasts\n  nlst%reservoir_rfc_forecasts_time_series_path = reservoir_rfc_forecasts_time_series_path\n  nlst%reservoir_rfc_forecasts_lookback_hours = reservoir_rfc_forecasts_lookback_hours\n\n  if (reservoir_persistence_usgs .or. reservoir_persistence_usace .or. reservoir_rfc_forecasts) then\n    reservoir_type_specified = .TRUE.\n  end if\n\n  nlst%reservoir_type_specified = reservoir_type_specified\n\n#ifdef MPP_LAND\n  call mpp_land_bcast_char(256,nlst%RESTART_FILE)\n  call mpp_land_bcast_char(256,nlst%hydrotbl_f)\n  call mpp_land_bcast_char(1024,nlst%reservoir_obs_dir)\n  call mpp_land_bcast_log1(nlst%reservoir_persistence_usgs)\n  call mpp_land_bcast_log1(nlst%reservoir_persistence_usace)\n  call mpp_land_bcast_char(256,nlst%reservoir_parameter_file )\n  call mpp_land_bcast_char(256,nlst%reservoir_usgs_timeslice_path)\n  call mpp_land_bcast_char(256,nlst%reservoir_usace_timeslice_path)\n  call mpp_land_bcast_int1(nlst%reservoir_observation_lookback_hours)\n  call mpp_land_bcast_int1(nlst%reservoir_observation_update_time_interval_seconds)\n  call mpp_land_bcast_log1(nlst%reservoir_rfc_forecasts)\n  call mpp_land_bcast_char(256,nlst%reservoir_rfc_forecasts_time_series_path)\n  call mpp_land_bcast_int1(nlst%reservoir_rfc_forecasts_lookback_hours)\n  call mpp_land_bcast_log1(nlst%reservoir_type_specified)\n#endif\n\n  write(nlst%hgrid,'(I1)') igrid\n\n\n  if(RESTART_FILE .eq. \"\") rst_typ = 0\n\n  if(rst_bi_out .eq. 1) then\n! This part works for intel not pgi\n!     inquire(directory='restart', exist=dir_e)\n      inquire(file='restart/.', exist=dir_e)\n      if(.not. dir_e) then\n         call system('mkdir restart')\n      endif\n  endif\n\n\n#ifdef MPP_LAND\n  !bcast namelist variable.\n  call mpp_land_bcast_int1(rt_option)\n  call mpp_land_bcast_int1(CHANRTSWCRT)\n  call mpp_land_bcast_int1(channel_option)\n  call mpp_land_bcast_int1(SUBRTSWCRT)\n  call mpp_land_bcast_int1(OVRTSWCRT)\n  call mpp_land_bcast_int1(AGGFACTRT)\n  call mpp_land_bcast_real1(DTRT_TER)\n  call mpp_land_bcast_real1(DTRT_CH)\n  call mpp_land_bcast_real1(DXRT)\n  call mpp_land_bcast_real1(gwChanCondConstIn)\n  call mpp_land_bcast_real1(gwChanCondConstOut)\n  call mpp_land_bcast_real1(gwIhShift)\n  call mpp_land_bcast_int1(GWBASESWCRT)\n  call mpp_land_bcast_int1(GWSOILCPL)\n  call mpp_land_bcast_int1(bucket_loss)\n  call mpp_land_bcast_int1(gwChanCondSw)\n  call mpp_land_bcast_int1(GwSpinCycles)\n  call mpp_land_bcast_int1(GwPreCycles)\n  call mpp_land_bcast_log1(GwPreDiag)\n  call mpp_land_bcast_log1(GwSpinUp)\n  call mpp_land_bcast_int1(GwPreDiagInterval)\n  call mpp_land_bcast_int1(GW_RESTART)\n  call mpp_land_bcast_int1(RSTRT_SWC  )\n  call mpp_land_bcast_int1(TERADJ_SOLAR)\n  call mpp_land_bcast_int1(sys_cpl)\n  call mpp_land_bcast_int1(rst_typ)\n  call mpp_land_bcast_int1(rst_bi_in)\n  call mpp_land_bcast_int1(rst_bi_out)\n  call mpp_land_bcast_int1(order_to_write)\n  call mpp_land_bcast_int1(CHRTOUT_DOMAIN)\n  call mpp_land_bcast_int1(CHANOBS_DOMAIN)\n  call mpp_land_bcast_int1(output_gw)\n  call mpp_land_bcast_int1(outlake)\n  call mpp_land_bcast_int1(frxst_pts_out)\n  call mpp_land_bcast_int1(CHRTOUT_GRID)\n  call mpp_land_bcast_int1(LSMOUT_DOMAIN)\n  call mpp_land_bcast_int1(RTOUT_DOMAIN)\n  call mpp_land_bcast_int1(UDMP_OPT)\n  call mpp_land_bcast_int1(reservoir_data_ingest)\n  call mpp_land_bcast_int1(imperv_adj)\n#ifdef WRF_HYDRO_NUDGING\n  call mpp_land_bcast_char(256, nudgingParamFile  )\n  call mpp_land_bcast_char(256, netwkReExFile     )\n  call mpp_land_bcast_char(256, nudgingLastObsFile)\n  call mpp_land_bcast_log1(readTimesliceParallel)\n  call mpp_land_bcast_log1(temporalPersistence)\n  call mpp_land_bcast_log1(persistBias)\n  call mpp_land_bcast_log1(biasWindowBeforeT0)\n  call mpp_land_bcast_char(256, timeSlicePath)\n  call mpp_land_bcast_int1(nLastObs)\n  call mpp_land_bcast_int1(minNumPairsBiasPersist)\n  call mpp_land_bcast_int1(maxAgePairsBiasPersist)\n  call mpp_land_bcast_log1(invDistTimeWeightBias)\n  call mpp_land_bcast_log1(noConstInterfBias)\n#endif\n#endif /* MPP_LAND */\n\n\n\n! run Rapid\n    if(channel_option .eq. 4) then\n       CHANRTSWCRT = 0\n       OVRTSWCRT = 0\n       SUBRTSWCRT = 0\n    endif\n\n    nlst%CHRTOUT_DOMAIN = CHRTOUT_DOMAIN\n    nlst%CHANOBS_DOMAIN = CHANOBS_DOMAIN\n    nlst%output_gw      = output_gw\n    nlst%outlake      = outlake\n    nlst%frxst_pts_out = frxst_pts_out\n    nlst%CHRTOUT_GRID = CHRTOUT_GRID\n    nlst%LSMOUT_DOMAIN = LSMOUT_DOMAIN\n    nlst%RTOUT_DOMAIN = RTOUT_DOMAIN\n    nlst%RT_OPTION = RT_OPTION\n    nlst%CHANRTSWCRT = CHANRTSWCRT\n    nlst%GW_RESTART  = GW_RESTART\n    nlst%RSTRT_SWC   = RSTRT_SWC\n    nlst%channel_option = channel_option\n    nlst%DTRT_TER   = DTRT_TER\n    nlst%DTRT_CH   = DTRT_CH\n    nlst%DTCT      = DTRT_CH   ! small time step for grid based channel routing\n\n#ifdef MPP_LAND\n  if(my_id .eq. IO_id) then\n#endif\n    if(nlst%DT .lt. DTRT_CH) then\n          print*, \"nlst%DT,  DTRT_CH = \",nlst%DT,  DTRT_CH\n          print*, \"reset DTRT_CH=nlst%DT \"\n          DTRT_CH=nlst%DT\n    endif\n    if(nlst%DT .lt. DTRT_TER) then\n          print*, \"nlst%DT,  DTRT_TER = \",nlst%DT,  DTRT_TER\n          print*, \"reset DTRT_TER=nlst%DT \"\n          DTRT_TER=nlst%DT\n    endif\n    if(nlst%DT/DTRT_TER .ne. real(int(nlst%DT) / int(DTRT_TER)) ) then\n         print*, \"nlst%DT,  DTRT_TER = \",nlst%DT,  DTRT_TER\n         call hydro_stop(\"module_namelist: DT not a multiple of DTRT_TER\")\n    endif\n    if(nlst%DT/DTRT_CH .ne. real(int(nlst%DT) / int(DTRT_CH)) ) then\n         print*, \"nlst%DT,  DTRT_CH = \",nlst%DT,  DTRT_CH\n         call hydro_stop(\"module_namelist: DT not a multiple of DTRT_CH\")\n    endif\n#ifdef MPP_LAND\n  endif\n#endif\n\n    nlst%SUBRTSWCRT = SUBRTSWCRT\n    nlst%OVRTSWCRT = OVRTSWCRT\n    nlst%dxrt0 = dxrt\n    nlst%AGGFACTRT = AGGFACTRT\n    nlst%GWBASESWCRT = GWBASESWCRT\n    nlst%bucket_loss = bucket_loss\n    nlst%GWSOILCPL= GWSOILCPL\n    nlst%gwChanCondSw = gwChanCondSw\n    nlst%gwChanCondConstIn = gwChanCondConstIn\n    nlst%gwChanCondConstOut = gwChanCondConstOut\n    nlst%gwIhShift = gwIhShift\n    nlst%GwSpinCycles = GwSpinCycles\n    nlst%GwPreCycles = GwPreCycles\n    nlst%GwPreDiag = GwPreDiag\n    nlst%GwSpinUp = GwSpinUp\n    nlst%GwPreDiagInterval = GwPreDiagInterval\n    nlst%TERADJ_SOLAR = TERADJ_SOLAR\n    nlst%sys_cpl = sys_cpl\n    nlst%rst_typ = rst_typ\n    nlst%rst_bi_in = rst_bi_in\n    nlst%rst_bi_out = rst_bi_out\n    nlst%order_to_write = order_to_write\n    nlst%compound_channel = compound_channel\n    nlst%imperv_adj = imperv_adj\n\n! files\n    nlst%route_topo_f   =  route_topo_f\n    nlst%route_chan_f = route_chan_f\n    nlst%route_link_f = route_link_f\n    nlst%route_lake_f =route_lake_f\n    nlst%route_direction_f =  route_direction_f\n    nlst%route_order_f =  route_order_f\n    nlst%gwbasmskfil =  gwbasmskfil\n    nlst%gwstrmfil =  gwstrmfil\n    nlst%geo_finegrid_flnm =  geo_finegrid_flnm\n    nlst%udmap_file =  udmap_file\n    nlst%UDMP_OPT = UDMP_OPT\n    nlst%GWBUCKPARM_file =  GWBUCKPARM_file\n    nlst%reservoir_data_ingest = 0 ! STUB FOR USE OF REALTIME RESERVOIR DISCHARGE DATA. CURRENTLY NOT IN USE.\n    nlst%reservoir_obs_dir = 'testDirectory'\n#ifdef WRF_HYDRO_NUDGING\n    nlst%nudgingParamFile       = nudgingParamFile\n    nlst%netWkReExFile          = netWkReExFile\n    nlst%readTimesliceParallel  = readTimesliceParallel\n    nlst%temporalPersistence    = temporalPersistence\n    nlst%persistBias            = persistBias\n    nlst%biasWindowBeforeT0     = biasWindowBeforeT0\n    nlst%nudgingLastObsFile     = nudgingLastObsFile\n    nlst%timeSlicePath          = timeSlicePath\n    nlst%nLastObs               = nLastObs\n    nlst%minNumPairsBiasPersist = minNumPairsBiasPersist\n    nlst%maxAgePairsBiasPersist = maxAgePairsBiasPersist\n    nlst%invDistTimeWeightBias  = invDistTimeWeightBias\n    nlst%noConstInterfBias      = noConstInterfBias\n#endif\n\n#ifdef MPP_LAND\n  if(my_id .eq. IO_id) then\n#endif\n#ifdef HYDRO_D\n     write(6,*) \"output of the namelist file \"\n    write(6,*) \"nlst%udmap_file \", trim(nlst%udmap_file)\n    write(6,*) \"nlst%UDMP_OPT \", nlst%UDMP_OPT\n    write(6,*) \" nlst%RT_OPTION \", RT_OPTION\n    write(6,*) \" nlst%CHANRTSWCRT \", CHANRTSWCRT\n    write(6,*) \" nlst%GW_RESTART  \", GW_RESTART\n    write(6,*) \" nlst%RSTRT_SWC   \", RSTRT_SWC\n    write(6,*) \" nlst%channel_option \", channel_option\n    write(6,*) \" nlst%DTRT_TER   \", DTRT_TER\n    write(6,*) \" nlst%DTRT_CH   \", DTRT_CH\n    write(6,*) \" nlst%SUBRTSWCRT \", SUBRTSWCRT\n    write(6,*) \" nlst%OVRTSWCRT \", OVRTSWCRT\n    write(6,*) \" nlst%dxrt0 \", dxrt\n    write(6,*) \" nlst%AGGFACTRT \", AGGFACTRT\n    write(6,*) \" nlst%GWBASESWCRT \", GWBASESWCRT\n    write(6,*) \" nlst%GWSOILCPL \", GWSOILCPL\n    write(6,*) \" nlst%gwChanCondSw \", gwChanCondSw\n    write(6,*) \" nlst%gwChanCondConstIn \", gwChanCondConstIn\n    write(6,*) \" nlst%gwChanCondConstOut \", gwChanCondConstOut\n    write(6,*) \" nlst%gwIhShift \", gwIhShift\n    write(6,*) \" nlst%GwSpinCycles \", GwSpinCycles\n    write(6,*) \" nlst%GwPreDiag \", GwPreDiag\n    write(6,*) \" nlst%GwPreDiagInterval \", GwPreDiagInterval\n    write(6,*) \" nlst%TERADJ_SOLAR \", TERADJ_SOLAR\n    write(6,*) \" nlst%sys_cpl \", sys_cpl\n    write(6,*) \" nlst%rst_typ \", rst_typ\n    write(6,*) \" nlst%order_to_write \", order_to_write\n    write(6,*) \" nlst%route_topo_f   \",  route_topo_f\n    write(6,*) \" nlst%route_chan_f \", route_chan_f\n    write(6,*) \" nlst%route_link_f \", route_link_f\n    write(6,*) \" nlst%compound_channel \", compound_channel\n    write(6,*) \" nlst%route_lake_f \",route_lake_f\n    write(6,*) \" nlst%reservoir_parameter_file \", reservoir_parameter_file\n    write(6,*) \" nlst%reservoir_usgs_timeslice_path \", reservoir_usgs_timeslice_path\n    write(6,*) \" nlst%reservoir_usace_timeslice_path \", reservoir_usace_timeslice_path\n    write(6,*) \" nlst%reservoir_observation_lookback_hours \", nlst%reservoir_observation_lookback_hours\n    write(6,*) \" nlst%reservoir_observation_update_time_interval_seconds \", nlst%reservoir_observation_update_time_interval_seconds\n    write(6,*) \" nlst%reservoir_rfc_forecasts \", reservoir_rfc_forecasts\n    write(6,*) \" nlst%reservoir_rfc_forecasts_time_series_path \", reservoir_rfc_forecasts_time_series_path\n    write(6,*) \" nlst%reservoir_rfc_forecasts_lookback_hours \", reservoir_rfc_forecasts_lookback_hours\n    write(6,*) \" nlst%route_direction_f \",  route_direction_f\n    write(6,*) \" nlst%route_order_f \",  route_order_f\n    write(6,*) \" nlst%gwbasmskfil \",  gwbasmskfil\n    write(6,*) \" nlst%bucket_loss \", bucket_loss\n    write(6,*) \" nlst%gwstrmfil \",  gwstrmfil\n    write(6,*) \" nlst%geo_finegrid_flnm \",  geo_finegrid_flnm\n    write(6,*) \" nlst%reservoir_data_ingest \", reservoir_data_ingest\n    write(6,*) \" nlst%imperv_adj \", imperv_adj\n#ifdef WRF_HYDRO_NUDGING\n    write(6,*) \" nlst%nudgingParamFile      \",  trim(nudgingParamFile)\n    write(6,*) \" nlst%netWkReExFile         \",  trim(netWkReExFile)\n    write(6,*) \" nlst%readTimesliceParallel \",  readTimesliceParallel\n    write(6,*) \" nlst%temporalPersistence   \",  temporalPersistence\n    write(6,*) \" nlst%persistBias           \",  persistBias\n    write(6,*) \" nlst%biasWindowBeforeT0    \",  biasWindowBeforeT0\n    write(6,*) \" nlst%nudgingLastObsFile    \",  trim(nudgingLastObsFile)\n    write(6,*) \" timeSlicePath              \",  trim(timeSlicePath)\n    write(6,*) \" nLastObs                   \",  nLastObs\n    write(6,*) \" minNumPairsBiasPersist     \",  minNumPairsBiasPersist\n    write(6,*) \" maxAgePairsBiasPersist     \",  maxAgePairsBiasPersist\n    write(6,*) \" invDistTimeWeightBias      \",  invDistTimeWeightBias\n    write(6,*) \" noConstInterfBias          \",  noConstInterfBias\n#endif\n#endif /* HYDRO_D */\n#ifdef MPP_LAND\n  endif\n#endif\n\n#ifdef MPP_LAND\n  !bcast other  variable.\n      call mpp_land_bcast_real1(nlst%dt)\n#endif\n\n! LRK - Add checking subroutine for hydro.namelist options\n#ifdef MPP_LAND\n       if(IO_id .eq. my_id) then\n#endif\n          call rt_nlst_check(nlst)\n#ifdef MPP_LAND\n       endif\n#endif\n\n! derive rtFlag\n      nlst%rtFlag = 1\n      if(channel_option .eq. 4) nlst%rtFlag = 0\n!      if(CHANRTSWCRT .eq. 0 .and.  SUBRTSWCRT .eq. 0 .and. OVRTSWCRT .eq. 0 .and. GWBASESWCRT .eq. 0) nlst%rtFlag = 0\n      if(SUBRTSWCRT .eq. 0 .and. OVRTSWCRT .eq. 0 .and. GWBASESWCRT .eq. 0) nlst%rtFlag = 0\n    end subroutine read_rt_nlst\n\nsubroutine rt_nlst_check(nlst)\n   ! Subroutine to check namelist options specified by the user.\n   implicit none\n\n   type(namelist_rt_field) nlst\n\n   ! Local variables\n   logical :: fileExists = .false.\n   integer :: i\n\n   ! Go through and make some logical checks for each hydro.namelist option.\n   ! Some of these checks will depend on specific options chosen by the user.\n\n   if( (nlst%sys_cpl .lt. 1) .or. (nlst%sys_cpl .gt. 4) ) then\n      call hydro_stop(\"hydro.namelist ERROR: Invalid sys_cpl value specified.\")\n   endif\n   if(len(trim(nlst%geo_static_flnm)) .eq. 0) then\n      call hydro_stop(\"hydro.namelist ERROR: Please specify a GEO_STATIC_FLNM file.\")\n   else\n      inquire(file=trim(nlst%geo_static_flnm),exist=fileExists)\n      if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: GEO_STATIC_FLNM not found.')\n   endif\n   if(len(trim(nlst%geo_finegrid_flnm)) .eq. 0) then\n      call hydro_stop(\"hydro.namelist ERROR: Please specify a GEO_FINEGRID_FLNM file.\")\n   else\n      inquire(file=trim(nlst%geo_finegrid_flnm),exist=fileExists)\n      if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: GEO_FINEGRID_FLNM not found.')\n   endif\n   !if(len(trim(nlst%land_spatial_meta_flnm)) .eq. 0) then\n   !   call hydro_stop(\"hydro.namelist ERROR: Please specify a LAND_SPATIAL_META_FLNM file.\")\n   !else\n   !   inquire(file=trim(nlst%land_spatial_meta_flnm),exist=fileExists)\n   !   if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: LAND_SPATIAL_META_FLNM not found.')\n   !endif\n   if(len(trim(nlst%RESTART_FILE)) .ne. 0) then\n      inquire(file=trim(nlst%RESTART_FILE),exist=fileExists)\n      if (.not. fileExists) call hydro_stop('hydro.namelist ERROR:= Hydro RESTART_FILE not found.')\n   endif\n   if(nlst%igrid .le. 0) call hydro_stop('hydro.namelist ERROR: Invalid IGRID specified.')\n   if(nlst%out_dt .le. 0) call hydro_stop('hydro_namelist ERROR: Invalid out_dt specified.')\n   if( (nlst%split_output_count .lt. 0 ) .or. (nlst%split_output_count .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid SPLIT_OUTPUT_COUNT specified')\n   endif\n   if( (nlst%rst_typ .lt. 0 ) .or. (nlst%rst_typ .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid rst_typ specified')\n   endif\n   if( (nlst%rst_bi_in .lt. 0 ) .or. (nlst%rst_bi_in .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid rst_bi_in specified')\n   endif\n   if( (nlst%rst_bi_out .lt. 0 ) .or. (nlst%rst_bi_out .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid rst_bi_out specified')\n   endif\n   if( (nlst%RSTRT_SWC .lt. 0 ) .or. (nlst%RSTRT_SWC .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid RSTRT_SWC specified')\n   endif\n   if( (nlst%GW_RESTART .lt. 0 ) .or. (nlst%GW_RESTART .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid GW_RESTART specified')\n   endif\n   if( (nlst%order_to_write .lt. 1 ) .or. (nlst%order_to_write .gt. 12) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid order_to_write specified')\n   endif\n   if( (nlst%io_form_outputs .lt. 0 ) .or. (nlst%io_form_outputs .gt. 4) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid io_form_outputs specified')\n   endif\n   if( (nlst%io_config_outputs .lt. 0 ) .or. (nlst%io_config_outputs .gt. 6) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid io_config_outputs specified')\n   endif\n   if( (nlst%t0OutputFlag .lt. 0 ) .or. (nlst%t0OutputFlag .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid t0OutputFlag specified')\n   endif\n   if( (nlst%output_channelBucket_influx .lt. 0 ) .or. (nlst%output_channelBucket_influx .gt. 3) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid output_channelBucket_influx specified')\n   endif\n   if( (nlst%CHRTOUT_DOMAIN .lt. 0 ) .or. (nlst%CHRTOUT_DOMAIN .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid CHRTOUT_DOMAIN specified')\n   endif\n   if( (nlst%CHANOBS_DOMAIN .lt. 0 ) .or. (nlst%CHANOBS_DOMAIN .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid CHANOBS_DOMAIN specified')\n   endif\n   if( (nlst%CHRTOUT_GRID .lt. 0 ) .or. (nlst%CHRTOUT_GRID .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid CHRTOUT_GRID specified')\n   endif\n   if( (nlst%LSMOUT_DOMAIN .lt. 0 ) .or. (nlst%LSMOUT_DOMAIN .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid LSMOUT_DOMAIN specified')\n   endif\n   if( (nlst%RTOUT_DOMAIN .lt. 0 ) .or. (nlst%RTOUT_DOMAIN .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid RTOUT_DOMAIN specified')\n   endif\n   if( (nlst%output_gw .lt. 0 ) .or. (nlst%output_gw .gt. 2) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid output_gw specified')\n   endif\n   if( (nlst%outlake .lt. 0 ) .or. (nlst%outlake .gt. 2) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid outlake specified')\n   endif\n   if( (nlst%frxst_pts_out .lt. 0 ) .or. (nlst%frxst_pts_out .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid frxst_pts_out specified')\n   endif\n   if(nlst%TERADJ_SOLAR .ne. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid TERADJ_SOLAR specified')\n   endif\n\n   ! The default value of nsoil == -999. When channel-only is used,\n   ! nsoil ==  -999999. In the case of channel-only, skip following block of code.\n   if(nlst%NSOIL .le. 0 .and. nlst%NSOIL .ne. -999999) then\n      call hydro_stop('hydro.namelist ERROR: Invalid NSOIL specified.')\n   endif\n   do i = 1,nlst%NSOIL\n      if(nlst%ZSOIL8(i) .gt. 0) then\n          call hydro_stop('hydro.namelist ERROR: Invalid ZSOIL layer depth specified.')\n      endif\n      if(i .gt. 1) then\n         if(nlst%ZSOIL8(i) .ge. nlst%ZSOIL8(i-1)) then\n            call hydro_stop('hydro.namelist ERROR: Invalid ZSOIL layer depth specified.')\n         endif\n      endif\n   end do\n\n   if(nlst%dxrt0 .le. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid DXRT specified.')\n   endif\n   if(nlst%AGGFACTRT .le. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid AGGFACTRT specified.')\n   endif\n   if(nlst%DTRT_CH .le. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid DTRT_CH specified.')\n   endif\n   if(nlst%DTRT_TER .le. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid DTRT_TER specified.')\n   endif\n   if( (nlst%SUBRTSWCRT .lt. 0 ) .or. (nlst%SUBRTSWCRT .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid SUBRTSWCRT specified')\n   endif\n   if( (nlst%OVRTSWCRT .lt. 0 ) .or. (nlst%OVRTSWCRT .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid OVRTSWCRT specified')\n   endif\n   if( (nlst%OVRTSWCRT .eq. 1 ) .or. (nlst%SUBRTSWCRT .eq. 1) ) then\n      if( (nlst%rt_option .lt. 1 ) .or. (nlst%rt_option .gt. 2) ) then\n      !if(nlst%rt_option .ne. 1) then\n         call hydro_stop('hydro.namelist ERROR: Invalid rt_option specified')\n      endif\n   endif\n   if( (nlst%CHANRTSWCRT .lt. 0 ) .or. (nlst%CHANRTSWCRT .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid CHANRTSWCRT specified')\n   endif\n   if(nlst%CHANRTSWCRT .eq. 1) then\n      if ( nlst%channel_option .eq. 5 ) then\n         nlst%channel_option = 2\n         nlst%channel_bypass = .TRUE.\n      endif\n      if( (nlst%channel_option .lt. 1 ) .or. (nlst%channel_option .gt. 3) ) then\n         call hydro_stop('hydro.namelist ERROR: Invalid channel_option specified')\n      endif\n   endif\n   if( (nlst%CHANRTSWCRT .eq. 1) .and. (nlst%channel_option .lt. 3) ) then\n      if(len(trim(nlst%route_link_f)) .eq. 0) then\n         call hydro_stop(\"hydro.namelist ERROR: Please specify a route_link_f file.\")\n      else\n         inquire(file=trim(nlst%route_link_f),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: route_link_f not found.')\n      endif\n   endif\n   if( (nlst%bucket_loss .lt. 0 ) .or. (nlst%bucket_loss .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid bucket_loss specified')\n   endif\n   if( (nlst%bucket_loss .eq. 1 ) .and. (nlst%UDMP_OPT .ne. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Bucket loss only available when UDMP=1')\n   endif\n   if( (nlst%GWBASESWCRT .lt. 0 ) .or. (nlst%GWBASESWCRT .gt. 4) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid GWBASESWCRT specified')\n   endif\n   if( (nlst%GWBASESWCRT .eq. 1 ) .or. (nlst%GWBASESWCRT .eq. 4) ) then\n      if(len(trim(nlst%GWBUCKPARM_file)) .eq. 0) then\n         call hydro_stop(\"hydro.namelist ERROR: Please specify a GWBUCKPARM_file file.\")\n      else\n         inquire(file=trim(nlst%GWBUCKPARM_file),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: GWBUCKPARM_file not found.')\n      endif\n   endif\n   if( (nlst%GWBASESWCRT .gt. 0) .and. (nlst%UDMP_OPT .ne. 1) ) then\n      if(len(trim(nlst%gwbasmskfil)) .eq. 0) then\n         call hydro_stop(\"hydro.namelist ERROR: Please specify a gwbasmskfil file.\")\n      else\n         inquire(file=trim(nlst%gwbasmskfil),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: gwbasmskfil not found.')\n      endif\n   endif\n   if( (nlst%UDMP_OPT .lt. 0 ) .or. (nlst%UDMP_OPT .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid UDMP_OPT specified')\n   endif\n   if(nlst%UDMP_OPT .gt. 0) then\n      if(len(trim(nlst%udmap_file)) .eq. 0) then\n         call hydro_stop(\"hydro.namelist ERROR: Please specify a udmap_file file.\")\n      else\n         inquire(file=trim(nlst%udmap_file),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: udmap_file not found.')\n      endif\n   endif\n   if( (nlst%UDMP_OPT .eq. 1) .and. (nlst%CHANRTSWCRT .eq. 0) ) then\n         call hydro_stop('hydro.namelist ERROR: User-defined mapping requires channel routing on.')\n   endif\n   if(nlst%outlake .ne. 0) then\n      if(len(trim(nlst%route_lake_f)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a route_lake_f to ouptut and run lakes.')\n      endif\n   endif\n   if(len(trim(nlst%route_lake_f)) .ne. 0) then\n      inquire(file=trim(nlst%route_lake_f),exist=fileExists)\n      if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: route_lake_f not found.')\n   endif\n   if( (nlst%imperv_adj .lt. 0 ) .or. (nlst%imperv_adj .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid imperv_adj specified')\n   endif\n   ! Only allow lakes to be ran with gridded routing or NWM routing\n   if(len(trim(nlst%route_lake_f)) .ne. 0) then\n      if(nlst%channel_option .ne. 3) then\n         if(nlst%UDMP_OPT .ne. 1) then\n            call hydro_stop('hydro.namelist ERROR: Currently lakes only work with gridded channel routing or UDMP=1. Please change your namelist settings.')\n         endif\n      endif\n   endif\n\n   if((nlst%channel_option .eq. 3) .and. (nlst%compound_channel)) then\n      call hydro_stop(\"Compound channel option not available for diffusive wave routing. \")\n   end if\n\n   if(nlst%reservoir_type_specified) then\n      if(len(trim(nlst%reservoir_parameter_file)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_parameter_file for &\n         inputs to reservoirs that are not level pool type.')\n      endif\n      if(len(trim(nlst%reservoir_parameter_file)) .ne. 0) then\n         inquire(file=trim(nlst%reservoir_parameter_file),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: reservoir_parameter_file not found.')\n      endif\n   end if\n\n   if(nlst%reservoir_persistence_usgs) then\n      if(len(trim(nlst%reservoir_usgs_timeslice_path)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_usgs timeslice_path for reservoir USGS persistence capability.')\n      endif\n      if(len(trim(nlst%reservoir_parameter_file)) .ne. 0) then\n        inquire(file=trim(nlst%reservoir_parameter_file),exist=fileExists)\n        if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: reservoir_parameter_file not found.')\n      endif\n    end if\n\n   if(nlst%reservoir_persistence_usace) then\n      if(len(trim(nlst%reservoir_usace_timeslice_path)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_usace_timeslice_path for reservoir USACE persistence capability.')\n      endif\n      if(len(trim(nlst%reservoir_parameter_file)) .ne. 0) then\n        inquire(file=trim(nlst%reservoir_parameter_file),exist=fileExists)\n        if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: reservoir_parameter_file not found.')\n      endif\n    end if\n\n   if(nlst%reservoir_rfc_forecasts) then\n      if(len(trim(nlst%reservoir_parameter_file)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_parameter_file for inputs to rfc forecast type reservoirs.')\n      endif\n      if(len(trim(nlst%reservoir_rfc_forecasts_time_series_path)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_rfc_forecasts_time_series_path for reservoir rfc forecast capability.')\n      endif\n      if(len(trim(nlst%reservoir_parameter_file)) .ne. 0) then\n        inquire(file=trim(nlst%reservoir_parameter_file),exist=fileExists)\n        if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: reservoir_parameter_file not found.')\n      endif\n   end if\n\nend subroutine rt_nlst_check\n\nend module module_namelist\n"
  },
  {
    "path": "src/Data_Rec/module_namelist_inc.F90",
    "content": "module module_namelist_inc\n   implicit none\n   type namelist_rt_field\n       integer :: nsoil, SOLVEG_INITSWC\n       real,allocatable,dimension(:) :: ZSOIL8\n       real*8 :: out_dt, rst_dt\n       real   :: dt  !! dt is NOAH_TIMESTEP\n       integer :: START_YEAR, START_MONTH, START_DAY, START_HOUR, START_MIN\n       character(len=256)  :: restart_file = \"\"\n       integer            :: split_output_count\n       integer :: igrid\n       integer :: rst_bi_in   ! used for parallel io with large restart file.\n       integer :: rst_bi_out   ! used for parallel io with large restart file.\n                           ! each process will output the restart tile.\n       character(len=256) :: geo_static_flnm = \"\"\n       character(len=1024) :: land_spatial_meta_flnm = \"\"\n       integer  :: DEEPGWSPIN\n       integer ::  order_to_write, rst_typ\n       character(len=256)  :: upmap_file = \"\"    ! user defined mapping file for NHDPLUS\n       character(len=256)  :: hydrotbl_f = \"\"    ! hydrotbl file\n\n!      additional character\n       character :: hgrid\n       character(len=19) :: olddate=\"123456\"\n       character(len=19) :: startdate=\"123456\"\n       character(len=19) :: sincedate=\"123456\"\n\n       integer :: io_config_outputs  ! used for NCEP REALTIME OUTPUT\n       integer :: io_form_outputs ! Flag to turn specify level of internal compression\n       integer :: t0OutputFlag\n       integer :: channel_only, channelBucket_only\n       integer :: output_channelBucket_influx ! used for FORCE_TYPE 9 and 10\n\n          integer:: RT_OPTION, CHANRTSWCRT, channel_option, &\n                  SUBRTSWCRT, OVRTSWCRT, AGGFACTRT, &\n                  GWBASESWCRT, GW_RESTART,RSTRT_SWC,TERADJ_SOLAR, &\n                  sys_cpl, gwChanCondSw, GwPreCycles, GwSpinCycles, GwPreDiagInterval, &\n                  gwsoilcpl, UDMP_OPT, bucket_loss, imperv_adj\n          logical:: GwPreDiag, GwSpinUp\n          real:: DTRT_TER,DTRT_CH, DTCT, dxrt0,  gwChanCondConstIn, gwChanCondConstOut, gwIhShift\n          character(len=256) :: route_topo_f=\"\"\n          character(len=256) :: route_chan_f=\"\"\n          character(len=256) :: route_link_f=\"\"\n          character(len=256) :: route_lake_f=\"\"\n          character(len=256) :: diversions_file=\"\"\n          logical            :: reservoir_persistence_usgs\n          logical            :: reservoir_persistence_usace\n          character(len=256) :: reservoir_parameter_file=\"\"\n          character(len=256) :: reservoir_usgs_timeslice_path=\"\"\n          character(len=256) :: reservoir_usace_timeslice_path=\"\"\n          integer            :: reservoir_observation_lookback_hours\n          integer            :: reservoir_observation_update_time_interval_seconds\n          logical            :: reservoir_rfc_forecasts\n          character(len=256) :: reservoir_rfc_forecasts_time_series_path=\"\"\n          integer            :: reservoir_rfc_forecasts_lookback_hours\n          logical            :: reservoir_type_specified\n          character(len=256) :: route_direction_f=\"\"\n          character(len=256) :: route_order_f=\"\"\n          character(len=256) :: gwbasmskfil =\"\"\n          character(len=256) :: gwstrmfil =\"\"\n          character(len=256) :: geo_finegrid_flnm =\"\"\n          character(len=256) :: udmap_file =\"\"\n          character(len=256) :: GWBUCKPARM_file = \"\"\n          integer :: reservoir_data_ingest ! STUB FOR USE OF REALTIME RESERVOIR DISCHARGE DATA. CURRENTLY NOT IN USE.\n          character(len=1024) :: reservoir_obs_dir = \"\"\n\n          logical :: compound_channel\n          integer ::frxst_pts_out            ! ASCII point timeseries output at user specified points\n          integer ::CHRTOUT_DOMAIN           ! Netcdf point timeseries output at all channel points\n          integer ::CHRTOUT_GRID                ! Netcdf grid of channel streamflow values\n          integer ::CHANOBS_DOMAIN             ! NetCDF point timeseries of output at forecast/gage points\n          integer ::LSMOUT_DOMAIN              ! Netcdf grid of variables passed between LSM and routing components\n          integer ::RTOUT_DOMAIN                ! Netcdf grid of terrain routing variables on routing grid\n          integer ::output_gw                   ! Netcdf grid of GW\n          integer ::outlake                   ! Netcdf grid of lake\n          integer :: rtFlag\n          integer ::khour\n\n          logical :: channel_bypass = .FALSE.\n\n!#ifdef WRF_HYDRO_NUDGING\n       character(len=256) :: nudgingParamFile\n       character(len=256) :: netwkReExFile\n       logical            :: readTimesliceParallel\n       logical            :: temporalPersistence\n       logical            :: persistBias\n       logical            :: biasWindowBeforeT0\n       character(len=256) :: nudgingLastObsFile\n       integer            :: minNumPairsBiasPersist\n       integer            :: maxAgePairsBiasPersist\n       logical            :: invDistTimeWeightBias\n       logical            :: noConstInterfBias\n       character(len=256) :: timeSlicePath\n       integer            :: nLastObs\n!#endif\n\n\n   end type namelist_rt_field\nend module module_namelist_inc\n"
  },
  {
    "path": "src/Data_Rec/module_rt_inc.F90",
    "content": "module module_rt_inc\n   use overland_data\n   use module_subsurface_data\n   use module_subsurface_static_data\n   use module_subsurface_input\n   use module_subsurface_output\n   use module_reservoir, only: reservoir_container\n   use iso_fortran_env, only: int64\n   implicit none\n\n   TYPE RT_FIELD\n   type (overland_struct) :: overland\n   type (subsurface_struct) :: subsurface\n   type (subsurface_static_interface) :: subsurface_static\n   type (subsurface_input_interface) :: subsurface_input\n   type (subsurface_output_interface) :: subsurface_output\n\n   class (reservoir_container), allocatable, dimension(:) :: reservoirs\n   integer, allocatable, dimension(:) :: reservoir_type ! specifying type of reservoir\n   integer, allocatable, dimension(:) :: final_reservoir_type   ! resolved reservoir type (since it can change)\n   real, allocatable, dimension(:) :: reservoir_assimilated_value ! observation or forecast assimilated to reservoir discharge\n   character(len=256), allocatable, dimension(:) :: reservoir_assimilated_source_file ! source file of assimilated value\n\n   INTEGER :: IX, JX\n   logical :: initialized\n   logical :: restQSTRM\n  REAL    :: DX,GRDAREART,SUBFLORT,WATAVAILRT,QSUBDRYRT\n  !REAL    :: SFHEAD1RT,INFXS1RT,QSTRMVOLTRT,QBDRYTRT,SFHEADRT,ETPND1,INFXSRTOT\n  REAL    :: SFHEAD1RT,INFXS1RT,SFHEADRT,ETPND1,INFXSRTOT\n  !REAL    :: LAKE_INFLOTRT,accsuminfxs,diffsuminfxs,RETDEPFRAC\n  REAL    :: accsuminfxs,diffsuminfxs,RETDEPFRAC\n  REAL    :: VERTKSAT,l3temp,l4temp,l3moist,l4moist,RNOF1TOT,RNOF2TOT,RNOF3TOT\n  INTEGER :: IXRT,JXRT,vegct\n  INTEGER :: AGGFACYRT, AGGFACXRT, KRTel_option, FORC_TYP\n  INTEGER :: SATLYRCHKRT,DT_FRACRT\n  INTEGER ::  LAKE_CT, STRM_CT\n  REAL                                 :: RETDEP_CHAN  ! Channel retention depth\n  INTEGER :: NLINKS  !maximum number of unique links in channel\n  INTEGER :: GNLINKS  !maximum number of unique links in channel for parallel computation\n  INTEGER :: NLAKES !number of lakes modeled\n  INTEGER :: NLINKSL !maximum number of links using linked routing\n  INTEGER :: MAXORDER !maximum stream order\n  integer :: timestep_flag    ! 1 cold start run else continue run\n\n  INTEGER :: GNLINKSL, linklsS, linklsE , nlinksize  !## for reach based channel routing\n\n  INTEGER :: iswater     !id for water in vegtyp\n  INTEGER :: islake      !id for lake in vegtyp\n  INTEGER :: isurban     !id for urban in vegtyp\n  INTEGER :: isoilwater  !id for water in soiltyp\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!DJG   VARIABLES FOR ROUTING\n  !INTEGER, allocatable, DIMENSION(:,:)      :: CH_NETRT !-- keeps track of the 0-1 channel network ! moved to overland%streams_and_lakes\n  INTEGER(kind=int64), allocatable, DIMENSION(:,:)      :: CH_LNKRT !-- linked routing grid (should combine with CH_NETRT.. redundant Gochis!)\n\n\n  INTEGER(kind=int64), allocatable, DIMENSION(:,:)      :: CH_NETLNK, GCH_NETLNK !-- assigns a unique value to each channel gridpoint, called links\n  REAL,    allocatable, DIMENSION(:,:)      :: LATVAL,LONVAL !-- lat lon\n  REAL,    allocatable, DIMENSION(:,:)      :: TERRAIN\n  REAL,    allocatable, DIMENSION(:,:)      :: landRunOff   ! used for NHDPLUS only\n  REAL, allocatable,    DIMENSION(:)        :: CHLAT,CHLON   !  channel lat and lon\n  ! INTEGER, allocatable, DIMENSION(:,:)    :: LAKE_MSKRT, BASIN_MSK,LAK_1K\n  INTEGER, allocatable, DIMENSION(:,:)      :: LAK_1K\n  INTEGER, allocatable, DIMENSION(:,:)      :: g_LAK_1K\n  ! REAL,    allocatable, DIMENSION(:,:)      :: ELRT,SOXRT,SOYRT,OVROUGHRT,RETDEPRT, QSUBBDRYTRT\n  !REAL :: QSUBBDRYTRT    ! QSUBBDRYTRT moved to subsurface io module\n  !REAL,    allocatable, DIMENSION(:,:)      :: ELRT,SOXRT,SOYRT,OVROUGHRT,RETDEPRT\n  REAL,    allocatable, DIMENSION(:,:)      :: ELRT\n  !REAL,    allocatable, DIMENSION(:,:,:)    :: SO8RT\n  INTEGER,    allocatable, DIMENSION(:,:,:) ::  SO8LD_D ! SO8RT_D moved to overland properties module\n  REAL,    allocatable, DIMENSION(:,:)      :: SO8LD_Vmax\n  REAL   Vmax\n  !REAL,    allocatable, DIMENSION(:,:)      :: LKSATRT !  LKSATRT moved to subsurface properties module\n  !REAL,    allocatable, DIMENSION(:,:)      :: SFCHEADRT,INFXSRT,LKSAT  ! SFCHEAD moved to overland control module\n  REAL,    allocatable, DIMENSION(:,:)      :: INFXSRT,LKSAT,LKSATRT\n  !REAL,    allocatable, DIMENSION(:,:)      :: SFCHEADSUBRT,INFXSUBRT,LKSATFAC  ! SFCHEADSUBRT, INFXSUBRT moved to overland control module\n  REAL,    allocatable, DIMENSION(:,:)      :: LKSATFAC\n  REAL,    allocatable, DIMENSION(:,:)      :: IMPERVFRAC\n  !REAL,    allocatable, DIMENSION(:,:)      :: SOLDEPRT ! QSUBRT, QSUBBDRYRT moved to subsurface io module, SOLDEPRT, ZWATTABLRT move to susurface properties\n  REAL,    allocatable, DIMENSION(:,:)      :: SUB_RESID\n  REAL,    allocatable, DIMENSION(:,:)      :: q_sfcflx_x,q_sfcflx_y\n  INTEGER,    allocatable, DIMENSION(:)      :: map_l2g, map_g2l\n\n  INTEGER :: nToInd\n  INTEGER,    allocatable, DIMENSION(:)      :: toNodeInd\n  INTEGER(kind=int64),    allocatable, DIMENSION(:,:)      :: gtoNode\n\n! temp arrary cwatavail\n  !real, allocatable, DIMENSION(:,:,:)      :: SMCREFRT  ! SMCREFRT moved to subsurface grid_transform module\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!DJG   VARIABLES FOR GW/Baseflow\n  INTEGER :: numbasns\n  INTEGER :: gnumbasns\n  integer(kind=int64), allocatable, dimension(:)     :: basnsInd ! basin index for tile\n  INTEGER, allocatable, DIMENSION(:,:)   :: GWSUBBASMSK  !GW basin mask grid\n  REAL,    allocatable, DIMENSION(:,:)   :: qinflowbase  !strm inflow/baseflow from GW\n  REAL,    allocatable, DIMENSION(:,:)   :: SOLDRAIN     !time-step drainage\n  INTEGER, allocatable, DIMENSION(:,:)   :: gw_strm_msk  !GW basin mask grid\n  INTEGER, allocatable, DIMENSION(:,:)   :: gw_strm_msk_lind  !GW basin mask grid tile maping index\n  REAL,    allocatable, DIMENSION(:)     :: z_gwsubbas   !depth in GW bucket\n  REAL,    allocatable, DIMENSION(:)     :: qin_gwsubbas !flow to GW bucket\n  REAL,    allocatable, DIMENSION(:)     :: qout_gwsubbas!flow from GW bucket\n  REAL,    allocatable, DIMENSION(:)     :: qloss_gwsubbas   !flow from GW bucket\n  REAL,    allocatable, DIMENSION(:)     :: gwbas_pix_ct !ct of strm pixels in\n  REAL,    allocatable, DIMENSION(:)     :: basns_area   !basin area\n  REAL,    allocatable, DIMENSION(:)     :: node_area   !nodes area\n\n  REAL,    allocatable, DIMENSION(:)     :: z_q_bas_parm     !GW bucket parameters\n  INTEGER, allocatable, DIMENSION(:)     :: nhdBuckMask      !GW bucket mask for NHDPLUS\n  INTEGER, allocatable, DIMENSION(:)     :: ct2_bas          !ct of land pixels in basin\n  REAL,    allocatable, DIMENSION(:)     :: bas_pcp      !sub-basin avg'd pcp\n  INTEGER                                :: bas\n  INTEGER, allocatable, DIMENSION(:)        :: bas_id\n  CHARACTER(len=19)                      :: header\n  CHARACTER(len=1)                       :: jnk\n  REAL, allocatable, DIMENSION(:)        :: gw_buck_coeff    !GW bucket model coefficient\n  REAL, allocatable, DIMENSION(:)        :: gw_buck_exp      !GW bucket model exponent\n  REAL, allocatable, DIMENSION(:)        :: gw_buck_loss     !GW bucket model loss fraction\n  REAL, allocatable, DIMENSION(:)        :: z_max            !Height of GW bucket\n!DJG Switch for Deep Sat GW Init:\n  INTEGER                                :: DEEPGWSPIN  !Switch to setup deep GW spinp\n!BF Variables for gw2d\n  integer, allocatable, dimension(:,:)      :: soiltyp, soiltypRT\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!DJG,DNY   VARIABLES FOR CHANNEL ROUTING\n!-- channel params\n  INTEGER(kind=int64), allocatable, DIMENSION(:)   :: LINK       !channel link\n  INTEGER(kind=int64), allocatable, DIMENSION(:)   :: TO_NODE    !link's to node\n  INTEGER(kind=int64), allocatable, DIMENSION(:)   :: FROM_NODE  !link's from node\n  INTEGER, allocatable, DIMENSION(:)   :: ORDER      !link's order\n  INTEGER, allocatable, DIMENSION(:)   :: STRMFRXSTPTS      !frxst point flag\n  CHARACTER(len=15), allocatable, DIMENSION(:) :: gages\n  !                                                    123456789012345\n  CHARACTER(len=15)                     :: gageMiss = '               '\n!  CHARACTER(len=15)                     :: gageMiss = '          -9999'\n\n  INTEGER, allocatable, DIMENSION(:)   :: TYPEL       !type of link Muskingum: 0 strm 1 lake\n                                                      !-- Diffusion: 0 edge or pour; 1 interior; 2 lake\n  INTEGER, allocatable, DIMENSION(:)   :: TYPEN      !type of link 0 strm 1 lake\n  REAL, allocatable, DIMENSION(:)      :: QLAKEI      !lake inflow in difussion scheme\n  REAL, allocatable, DIMENSION(:)      :: QLAKEO      !lake outflow in difussion scheme\n  INTEGER(kind=int64), allocatable, DIMENSION(:)   :: LAKENODE   !which nodes flow into which lakes\n  integer(kind=int64), allocatable, dimension(:)   :: LINKID     ! id of links on linked routing\n  REAL, allocatable, DIMENSION(:)      :: CVOL       ! channel volume\n  INTEGER(kind=int64), allocatable, DIMENSION(:,:)   :: pnode    !parent nodes : start from 2\n  integer :: maxv_p              ! array size for  second column of the pnode\n\n  REAL, allocatable, DIMENSION(:)      :: MUSK, MUSX !muskingum params\n  REAL, allocatable, DIMENSION(:)      :: CHANLEN    !link length\n  REAL, allocatable, DIMENSION(:)      :: MannN      !mannings N\n  REAL, allocatable, DIMENSION(:)      :: So     !link slope and channel conductivity (m/s)\n  REAL, allocatable, DIMENSION(:)      :: Channk ! channel infiltration parameter\n  REAL, allocatable, DIMENSION(:)      :: ChSSlp ! channel side slope\n  REAL, allocatable, DIMENSION(:)      :: Bw     ! Bottom width of channel\n  REAL, allocatable, DIMENSION(:)      :: Tw     ! top width of channel\n  REAL, allocatable, DIMENSION(:)      :: Tw_CC  ! top width of the (CC) compound channel\n  REAL, allocatable, DIMENSION(:)      :: n_CC   ! mannings N of (CC) compound channel\n  REAL, allocatable, DIMENSION(:,:)    :: QLINK      !flow in link\n  integer, allocatable, DIMENSION(:)   :: ascendIndex !sorting of routelink\n#ifdef WRF_HYDRO_NUDGING\n  REAL, allocatable, DIMENSION(:)      :: nudge      !difference between modeled and DA adj link flow\n#endif\n  REAL, allocatable, DIMENSION(:)      :: HLINK      !head in link\n  REAL, allocatable, DIMENSION(:)      :: ZELEV      !elevation of nodes for channel\n  INTEGER, allocatable, DIMENSION(:)   :: CHANXI,CHANYJ !map chan to fine grid\n  REAL,  DIMENSION(50)     :: BOTWID,CHANN_K,TOPWID,HLINK_INIT,CHAN_SS,CHMann !Channel parms from table\n  REAL,  DIMENSION(50)     :: TOPWIDCC, NCC  !topwidth and mannings n of compund\n\n  ! VARIABLES FOR  RESERVOIRS\n  REAL, allocatable, DIMENSION(:)      :: RESHT  !reservoir height\n!-- lake params\n  integer(kind=int64), allocatable, dimension(:) :: LAKEIDA     !id of lakes in routlink file\n  integer(kind=int64), allocatable, dimension(:) :: LAKEIDM     !id of LAKES Modeled in LAKEPARM.nc or tbl\n  REAL, allocatable, DIMENSION(:)    :: HRZAREA    !horizontal extent of lake, km^2\n  REAL, allocatable, DIMENSION(:)    :: WEIRL      !overtop weir length (m)\n  REAL, allocatable, DIMENSION(:)    :: DAML      !overtop weir length (m)\n  REAL, allocatable, DIMENSION(:)    :: ORIFICEC   !coefficient of orifice\n  REAL, allocatable, DIMENSION(:)    :: ORIFICEA   !orifice opening area (m^2)\n  REAL, allocatable, DIMENSION(:)    :: ORIFICEE   !orifice elevation (m)\n  REAL, allocatable, DIMENSION(:)    :: LATLAKE, LONLAKE,ELEVLAKE ! lake info\n\n  INTEGER, allocatable, DIMENSION(:) :: LAKEIDX ! integer index for lakes, mapped to linkid\n\n!!! accumulated variables for reach beased rt\n  Real*8, allocatable, DIMENSION(:)  :: accSfcLatRunoff, accBucket\n  REAL  , allocatable, DIMENSION(:)  ::   qSfcLatRunoff,   qBucket, qBtmVertRunoff\n  REAL, allocatable, DIMENSION(:)    :: accLndRunOff, accQLateral, accStrmvolrt\n  !REAL, allocatable, DIMENSION(:)    :: qqLndRunOff, qqStrmvolrt, qqBucket\n  REAL, allocatable, DIMENSION(:)    :: QLateral, velocity, qloss\n\n#ifdef MPP_LAND\n  INTEGER, allocatable, DIMENSION(:)    :: lake_index,nlinks_index\n  INTEGER(kind=int64), allocatable, DIMENSION(:,:)  :: Link_location\n  integer(kind=int64), allocatable, dimension(:)  :: LLINKID\n  integer mpp_nlinks, yw_mpp_nlinks, LNLINKSL\n#endif\n  INTEGER(kind=int64), allocatable, DIMENSION(:,:)      :: CH_LNKRT_SL !-- reach based links used for mapping\n\n\n  REAL,    allocatable, DIMENSION(:,:)      :: OVROUGHRTFAC,RETDEPRTFAC\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!DJG   VARIABLES FOR AGGREGATION/DISAGGREGATION\n  REAL,    allocatable, DIMENSION(:,:,:)   :: SH2OWGT,SICE ! SMCRT, SMCMAXRT, SMCWLTRT moved to subsurface grid transform module\n  REAL,    allocatable, DIMENSION(:,:)     :: INFXSAGGRT\n  !REAL,    allocatable, DIMENSION(:,:)     :: DHRT,QSTRMVOLRT,QBDRYRT,LAKE_INFLORT ! dhrt and qbdryrt moved to overland control qstrmvolrt and lake_inflrt moved to overland stream and lakes\n  REAL,    allocatable, DIMENSION(:,:)     :: QSTRMVOLRT_TS,LAKE_INFLORT_TS\n  REAL,    allocatable, DIMENSION(:,:)     :: QSTRMVOLRT_ACC, LAKE_INFLORT_DUM\n  REAL,    allocatable, DIMENSION(:,:)       :: INFXSWGT, ywtmp\n  REAL,    allocatable, DIMENSION(:)       :: SMCAGGRT,STCAGGRT,SH2OAGGRT\n  REAL    :: INFXSAGG1RT,SFCHEADAGG1RT,SFCHEADAGGRT\n  !REAL,    allocatable, DIMENSION(:,:,:)       :: dist  ! 8 direction of distance moved to overland properties\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!DJG   VARIABLES FOR ONLINE MASS BALANCE CALCULATION\n  REAL(KIND=8)    :: DCMC,DSWE,DACRAIN,DSFCEVP,DCANEVP,DEDIR,DETT,DEPND,DESNO,DSFCRNFF\n  REAL(KIND=8)    :: RESID,SUMEVP,DUG1RNFF,DUG2RNFF,DETP ! DSMCTOT, SMCTOT1, SMCTOT2 moved to overland mass balance\n  REAL(KIND=8)    :: suminfxs2,dprcp_ts ! suminfxsrt, suminfxs1 moved to overland mass balance\n  REAL(KIND=8)    :: CHAN_IN1,CHAN_IN2,LAKE_IN1,LAKE_IN2,zzz, CHAN_STOR,CHAN_OUT\n  REAL(KIND=8)    :: CHAN_INV,LAKE_INV  !-channel and lake inflow in volume\n  REAL(KIND=8)    :: DQBDRY\n  REAL    :: QSTRMVOLTRT1,LAKE_INFLOTRT1,QBDRYTOT1,LSMVOL\n  REAL(KIND=8),    allocatable, DIMENSION(:)   :: DSMC,SMCRTCHK\n  REAL(KIND=8),    allocatable, DIMENSION(:,:)  :: CMC_INIT,SWE_INIT\n!  REAL(KIND=8),    allocatable, DIMENSION(:,:,:) :: SMC_INIT\n  REAL(KIND=8)            :: SMC_INIT,SMC_FINAL,resid2,resid1\n  REAL(KIND=8)            :: chcksm1,chcksm2,CMC1,CMC2,prcp_in,ETATOT,dsmctot_av\n\n  integer :: g_ixrt,g_jxrt,flag\n  integer :: allo_status = -99\n  integer iywtmp\n\n\n!-- lake params\n  REAL, allocatable, DIMENSION(:)    :: LAKEMAXH   !maximum depth (m)\n  REAL, allocatable, DIMENSION(:)    :: WEIRC      !coeff of overtop weir\n  REAL, allocatable, DIMENSION(:)    :: WEIRH      !depth of Lake coef\n\n\n\n\n!DJG Modified namelist for routing and agg. variables\n  real Z_tmp\n\n  !!! define land surface grid variables\n      REAL,    allocatable, DIMENSION(:,:,:) :: SMC,STC,SH2OX\n      REAL,    allocatable, DIMENSION(:,:)   :: SMCMAX1,SMCWLT1,SMCREF1\n      INTEGER, allocatable, DIMENSION(:,:)   :: VEGTYP\n      REAL, allocatable, DIMENSION(:,:)      :: OV_ROUGH2d\n      !REAL,    allocatable, DIMENSION(:)   :: SLDPTH\n      REAL,    allocatable, DIMENSION(:,:)   :: NEXP\n\n!!! define constant/parameter\n    real ::   ov_rough(50)!, ZSOIL(100) ! ZSOIL moved to subsurface properties module\n!  out_counts: couput counts for current run.\n!  his_out_counts: used for channel routing output and  special for restart.\n!  his_out_counts = previous run + out_counts\n    integer :: out_counts, rst_counts, his_out_counts\n\n    REAL,    allocatable, DIMENSION(:,:)   :: lat_lsm, lon_lsm\n    REAL,    allocatable, DIMENSION(:,:,:) :: dist_lsm\n\n   END TYPE RT_FIELD\nend module module_rt_inc\n"
  },
  {
    "path": "src/Debug_Utilities/CMakeLists.txt",
    "content": "# build the version static library\nadd_library(hydro_debug_utils STATIC\n        debug_dump_variable.F90\n)\ntarget_link_libraries(hydro_debug_utils PRIVATE hydro_mpp)\n"
  },
  {
    "path": "src/Debug_Utilities/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nOBJS = \\\n\tdebug_dump_variable.o\n\nall:\t$(OBJS)\n\n.F90.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -I$(NETCDFINC) -o $(@) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I../mod $(*).F90\n\t@echo \"\"\n\tar -r ../lib/libHYDRO.a $(@)\n\tcp *.mod ../mod\n\n# Dependencies:\n#\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Debug_Utilities/debug_dump_variable.F90",
    "content": "module debug_dump_variable\n#ifdef MPP_LAND\n    use module_mpp_land\n#endif\n\n    implicit none\n\n    contains\n\n    ! output a land surface dimensioned array to a test file for comparison\n\n    subroutine dump_float_2d(target_array, filepath)\n        implicit none\n        ! the array to be written to file\n        real, allocatable, dimension(:,:), intent(in) :: target_array\n\n        ! the location to write the file\n        character(len=*), intent(in) :: filepath\n\n#ifdef MPP_LAND\n    real, dimension(global_rt_nx,global_rt_ny) :: out_buffer\n\n        ! if we are in an mpi enviorment what needs to be done depends of if\n        ! this process is the IO process\n        ! if we are not the IO process write_IO_real will send data to the IO process\n        ! if we are the IO process write_IO_RT_real will return the global array for this\n        ! variable\n\n        call write_IO_RT_real(target_array,out_buffer)\n        if ( my_id .eq. IO_id ) then\n            call debug_write_float_to_file(out_buffer,filepath)\n        end if\n#else\n        call debug_write_float_to_file(target_array, filepath)\n#endif\n\n    end subroutine dump_float_2d\n\n    ! output a routing dimensioned array to a test file for comparison\n\n    subroutine dump_float_2d_rt(target_array, filepath)\n        implicit none\n        ! the array to be written to file\n        real, allocatable, dimension(:,:), intent(in) :: target_array\n\n        ! the location to write the file\n        character(len=*), intent(in) :: filepath\n\n#ifdef MPP_LAND\n    real, dimension(global_rt_nx,global_rt_ny) :: out_buffer\n\n        ! if we are in an mpi enviorment what needs to be done depends of if\n        ! this process is the IO process\n        ! if we are not the IO process write_IO_RT_real will send data to the IO process\n        ! if we are the IO process write_IO_RT_real will return the global array for this\n        ! variable\n\n        call write_IO_real(target_array,out_buffer)\n        if ( my_id .eq. IO_id ) then\n            call debug_write_float_to_file(out_buffer,filepath)\n        end if\n#else\n        call debug_write_float_to_file(target_array, filepath)\n#endif\n\n    end subroutine dump_float_2d_rt\n\n    subroutine debug_write_float_to_file(target_array, filepath)\n        ! parameters\n        real, dimension(:,:) :: target_array\n        character(len=*) :: filepath\n\n        ! local variables\n        integer :: nx\n        integer :: ny\n\n        integer :: x_pos, y_pos\n\n        nx = size(target_array,1)\n        ny = size(target_array,2)\n\n        ! open the file for writing\n        open(unit=237, file=filepath, form='formatted', status=\"replace\", action=\"write\")\n\n        ! write the array to the file\n        do y_pos = 1, ny\n            do x_pos = 1, nx\n                write(237,'(F12.5,4X)',advance='no') target_array(x_pos,y_pos)\n            end do\n            write(237,*) '' ! write the end line\n        end do\n\n        close(237)\n\n    end subroutine\n\n\n\nend module debug_dump_variable\n"
  },
  {
    "path": "src/Doc/link_to_documentation.txt",
    "content": "A technical description and user's guide can be found at:\nhttps://ral.ucar.edu/projects/wrf_hydro\n"
  },
  {
    "path": "src/HYDRO_drv/CMakeLists.txt",
    "content": "# build the version static library\nadd_library(hydro_driver STATIC\n        module_HYDRO_drv.F90\n)\n\ntarget_link_libraries(hydro_driver PUBLIC\n        hydro_mpp\n        hydro_data_rec\n        hydro_routing\n        hydro_debug_utils\n        netCDF::netcdff\n)\n\nif(WRF_HYDRO_NUDGING STREQUAL \"1\")\n        target_link_libraries(hydro_driver PUBLIC hydro_nudging)\nendif()\n"
  },
  {
    "path": "src/HYDRO_drv/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nOBJS = \\\n\tmodule_HYDRO_drv.o\nall:\t$(OBJS)\n\n.F90.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -o $(@) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) -I../mod $(*).F90\n\t@echo \"\"\n\tar -r ../lib/libHYDRO.a $(@)\n\tcp *.mod ../mod\n\n#\n# Dependencies:\n#\nmodule_HYDRO_drv.o: ../Data_Rec/module_namelist.o ../Data_Rec/module_RT_data.o ../Data_Rec/module_gw_gw2d_data.o \\\n        ../Routing/module_GW_baseflow.o ../Routing/module_HYDRO_utils.o ../Routing/module_HYDRO_io.o ../Routing/module_RT.o\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/HYDRO_drv/module_HYDRO_drv.F90",
    "content": "module module_HYDRO_drv\n#ifdef MPP_LAND\n    use module_HYDRO_io, only:  output_rt, mpp_output_chrt, mpp_output_lakes, mpp_output_chrtgrd, &\n        restart_out_bi, restart_in_bi, mpp_output_chrt2, mpp_output_lakes2, &\n        hdtbl_in_nc, hdtbl_out\n   USE module_mpp_land\n#else\n    use module_HYDRO_io, only:  output_rt, output_chrt, output_chrt2, output_lakes\n#endif\n    use module_NWM_io, only: output_chrt_NWM, output_rt_NWM, output_lakes_NWM,&\n        output_chrtout_grd_NWM, output_lsmOut_NWM, &\n        output_frxstPts, output_chanObs_NWM, output_gw_NWM\n    use module_HYDRO_io, only: sub_output_gw, restart_out_nc, restart_in_nc,  &\n        get_file_dimension , get_file_globalatts, get2d_lsm_real, get2d_lsm_vegtyp, get2d_lsm_soltyp, &\n        output_lsm,  output_GW_Diag\n    use module_HYDRO_io, only : output_lakes2\n    use module_rt_data, only: rt_domain\n    use module_GW_baseflow\n    use module_gw_gw2d\n    use module_gw_gw2d_data, only: gw2d\n    use module_channel_routing, only: drive_channel, drive_channel_rsl\n    use orchestrator_base\n    use config_base, only: nlst, noah_lsm\n    use module_routing, only: getChanDim, landrt_ini\n    use module_HYDRO_utils\n    use module_lsm_forcing, only: geth_newdate\n#ifdef WRF_HYDRO_NUDGING\n    use module_stream_nudging,  only: init_stream_nudging\n#endif\n    use module_hydro_stop, only: HYDRO_stop\n    use module_UDMAP, only: get_basn_area_nhd\n    use module_channel_diversions, only: init_diversions\n    use netcdf\n\n    implicit none\n\n\n#ifdef HYDRO_D\n    real :: timeOr = 0\n    real :: timeSr = 0\n    real :: timeCr = 0\n    real :: timeGW = 0\n    integer :: clock_count_1 = 0\n    integer :: clock_count_2 = 0\n    integer :: clock_rate    = 0\n#endif\n    integer :: rtout_factor  = 0\n\n    integer, parameter :: r4 = selected_real_kind(4)\n    real,    parameter :: zeroFlt=0.0000000000000000000_r4\n    integer, parameter :: r8 = selected_real_kind(8)\n    real*8,  parameter :: zeroDbl=0.0000000000000000000_r8\n\ncontains\n    subroutine HYDRO_rst_out(did)\n#ifdef WRF_HYDRO_NUDGING\n        use module_stream_nudging, only: output_nudging_last_obs\n#endif\n        implicit none\n        integer:: rst_out\n        integer did, outflag\n        character(len=19) out_date\n#ifdef MPP_LAND\n        character(len=19) str_tmp\n#endif\n        rst_out = -99\n#ifdef MPP_LAND\n        if(IO_id .eq. my_id) then\n#endif\n            if(nlst(did)%dt .gt. nlst(did)%rst_dt*60) then\n                call geth_newdate(out_date, nlst(did)%startdate, nint(nlst(did)%dt*rt_domain(did)%rst_counts))\n            else\n                call geth_newdate(out_date, nlst(did)%startdate, nint(nlst(did)%rst_dt*60*rt_domain(did)%rst_counts))\n            endif\n            if ( (nlst(did)%rst_dt .gt. 0) .and. (out_date(1:19) == nlst(did)%olddate(1:19)) ) then\n                rst_out = 99\n                rt_domain(did)%rst_counts = rt_domain(did)%rst_counts + 1\n            endif\n! restart every month automatically.\n            if ( (nlst(did)%olddate(9:10) == \"01\") .and. (nlst(did)%olddate(12:13) == \"00\") .and. &\n                (nlst(did)%olddate(15:16) == \"00\").and. (nlst(did)%olddate(18:19) == \"00\") .and. &\n                (nlst(did)%rst_dt .le. 0)  ) then\n                if(nlst(did)%startdate(1:16) .ne. nlst(did)%olddate(1:16) ) then\n                    rst_out = 99\n                endif\n            endif\n\n#ifdef MPP_LAND\n        endif\n        call mpp_land_bcast_int1(rst_out)\n#endif\n        if(rst_out .gt. 0) then\n            write(6,*) \"yw check output restart at \",nlst(did)%olddate(1:16)\n#ifdef MPP_LAND\n            if(nlst(did)%rst_bi_out .eq. 1) then\n                if(my_id .lt. 10) then\n                    write(str_tmp,'(I1)') my_id\n                else if(my_id .lt. 100) then\n                    write(str_tmp,'(I2)') my_id\n                else if(my_id .lt. 1000) then\n                    write(str_tmp,'(I3)') my_id\n                else if(my_id .lt. 10000) then\n                    write(str_tmp,'(I4)') my_id\n                else if(my_id .lt. 100000) then\n                    write(str_tmp,'(I5)') my_id\n                else\n                    continue\n                endif\n                call mpp_land_bcast_char(16,nlst(did)%olddate(1:16))\n                call   RESTART_OUT_bi(trim(\"HYDRO_RST.\"//nlst(did)%olddate(1:16)   &\n                    //\"_DOMAIN\"//trim(nlst(did)%hgrid)//\".\"//trim(str_tmp)),  did)\n            else\n#endif\n                call   RESTART_OUT_nc(trim(\"HYDRO_RST.\"//nlst(did)%olddate(1:16)   &\n                    //\"_DOMAIN\"//trim(nlst(did)%hgrid)),  did)\n#ifdef MPP_LAND\n            endif\n#endif\n\n#ifdef WRF_HYDRO_NUDGING\n            call output_nudging_last_obs\n#endif\n        endif\n\n\n    end subroutine HYDRO_rst_out\n\n    subroutine HYDRO_out(did, rstflag)\n\n        implicit none\n        integer did, outflag, rtflag, iniflag\n        integer rstflag\n        character(len=19) out_date\n        integer :: Kt, ounit, i\n        real, dimension(RT_DOMAIN(did)%NLINKS,2) :: str_out\n        real, dimension(RT_DOMAIN(did)%NLINKS) :: vel_out\n\n!    real, dimension(RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx):: soilmx_tmp, &\n!           runoff1x_tmp, runoff2x_tmp, runoff3x_tmp,etax_tmp, &\n!           EDIRX_tmp,ECX_tmp,ETTX_tmp,RCX_tmp,HX_tmp,acrain_tmp, &\n!           ACSNOM_tmp, esnow2d_tmp, drip2d_tmp,dewfall_tmp, fpar_tmp, &\n!           qfx_tmp, prcp_out_tmp, etpndx_tmp\n\n        outflag = -99\n\n#ifdef MPP_LAND\n        if(IO_id .eq. my_id) then\n#endif\n            if(nlst(did)%olddate(1:19) .eq. nlst(did)%startdate(1:19) .and. rt_domain(did)%his_out_counts .eq. 0) then\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                write(6,*) \"output hydrology at time : \",nlst(did)%olddate(1:19), rt_domain(did)%his_out_counts\n#else\n                write(78,*) \"output hydrology at time : \",nlst(did)%olddate(1:19), rt_domain(did)%his_out_counts\n#endif\n#endif\n                outflag = 99\n            else\n                if(nlst(did)%dt .gt. nlst(did)%out_dt*60) then\n                    call geth_newdate(out_date, nlst(did)%startdate, nint(nlst(did)%dt*rt_domain(did)%out_counts))\n                else\n                    call geth_newdate(out_date, nlst(did)%startdate, nint(nlst(did)%out_dt*60*rt_domain(did)%out_counts))\n                endif\n                if ( out_date(1:19) == nlst(did)%olddate(1:19) ) then\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                    write(6,*) \"output hydrology at time : \",nlst(did)%olddate(1:19)\n#else\n                    write(78,*) \"output hydrology at time : \",nlst(did)%olddate(1:19)\n#endif\n#endif\n                    outflag = 99\n                endif\n            endif\n#ifdef MPP_LAND\n        endif\n        call mpp_land_bcast_int1(outflag)\n#endif\n\n        if (rstflag .eq. 1) call HYDRO_rst_out(did)\n\n        if (outflag .lt. 0) return\n\n        rt_domain(did)%out_counts = rt_domain(did)%out_counts + 1\n        rt_domain(did)%his_out_counts = rt_domain(did)%his_out_counts + 1\n\n        if(nlst(did)%out_dt*60 .gt. nlst(did)%DT) then\n            kt = rt_domain(did)%his_out_counts*nlst(did)%out_dt*60/nlst(did)%DT\n        else\n            kt = rt_domain(did)%his_out_counts\n        endif\n\n! jump the ouput for the initial time when it has restart file from routing.\n        rtflag = -99\n        iniflag = -99\n#ifdef MPP_LAND\n        if(IO_id .eq. my_id) then\n#endif\n!       if ( (trim(nlst_rt(did)%restart_file) /= \"\") .and. ( nlst_rt(did)%startdate(1:19) == nlst_rt(did)%olddate(1:19) ) ) then\n            !#ifndef NCEP_WCOSS\n            !             print*, \"yyyywww restart_file = \", trim(nlst_rt(did)%restart_file)\n            !#else\n            !             write(78,*) \"yyyywww restart_file = \", trim(nlst_rt(did)%restart_file)\n            !#endif\n            if ( nlst(did)%startdate(1:19) == nlst(did)%olddate(1:19) ) iniflag = 1\n            if ( (trim(nlst(did)%restart_file) /= \"\") .and. ( nlst(did)%startdate(1:19) == nlst(did)%olddate(1:19) ) ) rtflag = 1\n!       endif\n#ifdef MPP_LAND\n        endif\n        call mpp_land_bcast_int1(rtflag)\n        call mpp_land_bcast_int1(iniflag)\n#endif\n\n\n!yw keep the initial time otuput for debug\n        if(rtflag == 1) then\n            rt_domain(did)%restQSTRM = .false.   !!! do not reset QSTRM.. at initial time.\n            if(nlst(did)%t0OutputFlag .eq. 0) return\n        endif\n\n        if (iniflag == 1) then\n            if(nlst(did)%t0OutputFlag .eq. 0) return\n        endif\n\n        if(nlst(did)%channel_only .eq. 0 .and. nlst(did)%channelBucket_only .eq. 0) then\n            if(nlst(did)%LSMOUT_DOMAIN .eq. 1)  then\n                if(nlst(did)%io_form_outputs .eq. 0) then\n                    call output_lsm(trim(nlst(did)%olddate(1:4)//nlst(did)%olddate(6:7)//nlst(did)%olddate(9:10)  &\n                        //nlst(did)%olddate(12:13)//nlst(did)%olddate(15:16)//  &\n                        \".LSMOUT_DOMAIN\"//trim(nlst(did)%hgrid)),     &\n                        did)\n                else\n                    call output_lsmOut_NWM(did)\n                endif\n            endif\n        end if\n\n        if(nlst(did)%SUBRTSWCRT         .gt. 0 .or. &\n            nlst(did)%OVRTSWCRT          .gt. 0 .or. &\n            nlst(did)%GWBASESWCRT        .gt. 0 .or. &\n            nlst(did)%CHANRTSWCRT        .gt. 0 .or. &\n            nlst(did)%channel_only       .gt. 0 .or. &\n            nlst(did)%channelBucket_only .gt. 0      ) then\n\n\n            if(nlst(did)%RTOUT_DOMAIN       .eq. 1 .and. &\n                nlst(did)%channel_only       .eq. 0 .and. &\n                nlst(did)%channelBucket_only .eq. 0       ) then\n                if(mod(rtout_factor,3) .eq. 2 .or. &\n                    nlst(did)%io_config_outputs .ne. 5 .and. &\n                    nlst(did)%io_config_outputs .ne. 3) then\n! Output gridded routing variables on National Water Model\n! high-res routing grid\n                    if(nlst(did)%io_form_outputs .ne. 0) then\n                        call output_rt_NWM(did,nlst(did)%igrid)\n                    else\n                        call output_rt(    &\n                            nlst(did)%igrid, nlst(did)%split_output_count, &\n                            RT_DOMAIN(did)%ixrt, RT_DOMAIN(did)%jxrt, &\n                            nlst(did)%nsoil, &\n!                  nlst_rt(did)%startdate, nlst_rt(did)%olddate,\n!                  rt_domain(did)%subsurface%state%qsubrt,&\n                            nlst(did)%sincedate, nlst(did)%olddate, rt_domain(did)%subsurface%state%qsubrt,&\n                            rt_domain(did)%subsurface%properties%zwattablrt,RT_DOMAIN(did)%subsurface%grid_transform%smcrt,&\n                            RT_DOMAIN(did)%SUB_RESID,       &\n                            RT_DOMAIN(did)%q_sfcflx_x,RT_DOMAIN(did)%q_sfcflx_y,&\n                            rt_domain(did)%overland%properties%surface_slope_x,rt_domain(did)%overland%properties%surface_slope_y,&\n                            RT_DOMAIN(did)%QSTRMVOLRT_ACC,rt_domain(did)%overland%control%surface_water_head_routing, &\n                            nlst(did)%geo_finegrid_flnm,nlst(did)%DT,&\n                            rt_domain(did)%subsurface%properties%sldpth,RT_DOMAIN(did)%LATVAL,&\n                            RT_DOMAIN(did)%LONVAL,rt_domain(did)%overland%properties%distance_to_neighbor,nlst(did)%RTOUT_DOMAIN,&\n                            rt_domain(did)%overland%control%boundary_flux, &\n                            nlst(did)%io_config_outputs &\n                            )\n                    endif ! End check for io_form_outputs value\n                endif ! End check for rtout_factor\n                rtout_factor = rtout_factor + 1\n            endif\n!! JLM disable GW output for NWM. Bring this line back when runtime output options avail.\n!! JLM This seems like a more logical place?\n            if(nlst(did)%io_form_outputs .ne. 0) then\n                if(nlst(did)%GWBASESWCRT .ne. 0) then\n                    if(nlst(did)%channel_only .eq. 0) then\n                        if(nlst(did)%output_gw .ne. 0) then\n                            call output_gw_NWM(did,nlst(did)%igrid)\n                        endif\n                    endif\n                endif\n            else\n                if((nlst(did)%GWBASESWCRT .eq. 1) .or. (nlst(did)%GWBASESWCRT .ge. 4)) then\n                    if(nlst(did)%channel_only .eq. 0) then\n                        if(nlst(did)%output_gw  .eq. 1) call output_GW_Diag(did)\n                    endif\n                end if\n            endif\n\n\n            if(nlst(did)%GWBASESWCRT .eq. 3) then\n\n                if(nlst(did)%output_gw  .eq. 1)  &\n                    call sub_output_gw(    &\n                    nlst(did)%igrid, nlst(did)%split_output_count, &\n                    RT_DOMAIN(did)%ixrt, RT_DOMAIN(did)%jxrt,          &\n                    nlst(did)%nsoil,                               &\n!               nlst(did)%startdate, nlst(did)%olddate,    &\n                    nlst(did)%sincedate, nlst(did)%olddate,    &\n                    gw2d(did)%h, rt_domain(did)%subsurface%grid_transform%smcrt,                   &\n                    gw2d(did)%convgw, gw2d(did)%excess,                  &\n                    gw2d(did)%qsgwrt, gw2d(did)%qgw_chanrt,              &\n                    nlst(did)%geo_finegrid_flnm,nlst(did)%DT, &\n                    rt_domain(did)%subsurface%properties%sldpth,RT_DOMAIN(did)%LATVAL,       &\n                    RT_DOMAIN(did)%LONVAL,rt_domain(did)%overland%properties%distance_to_neighbor,           &\n                    nlst(did)%output_gw)\n\n            endif\n! BF end gw2d output section\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n            write(6,*) \"before call output_chrt\"\n            call flush(6)\n#else\n            write(78,*) \"before call output_chrt\"\n#endif\n#endif\n\n            if (nlst(did)%CHANRTSWCRT.eq.1.or.nlst(did)%CHANRTSWCRT.eq.2) then\n\n!ADCHANGE: Change values for within lake reaches to NA\n                str_out = RT_DOMAIN(did)%QLINK\n                vel_out = RT_DOMAIN(did)%velocity\n\n                if (RT_DOMAIN(did)%NLAKES .gt. 0)  then\n                    do i=1,RT_DOMAIN(did)%NLINKS\n                        if (RT_DOMAIN(did)%TYPEL(i) .eq. 2) then\n                            str_out(i,1) = -9.E15\n                            vel_out(i) = -9.E15\n                        endif\n                    end do\n                endif\n!ADCHANGE: End\n\n                if(nlst(did)%io_form_outputs .ne. 0) then\n! Call National Water Model output routine for output on NHD forecast points.\n                    if(nlst(did)%CHRTOUT_DOMAIN .ne. 0) then\n                        call output_chrt_NWM(did)\n                    endif\n! Call the subroutine to output frxstPts.\n                    if(nlst(did)%frxst_pts_out .ne. 0) then\n                        call output_frxstPts(did)\n                    endif\n! Call the subroutine to output CHANOBS\n                    if(nlst(did)%CHANOBS_DOMAIN .ne. 0) then\n                        call output_chanObs_NWM(did)\n                    endif\n                else\n! Call traditional output routines\n!ADCHANGE: We suspect this routine is broken so default is now output_chrtout2\n!             if(nlst_rt(did)%CHRTOUT_DOMAIN  .eq. 1)  then\n!#ifdef MPP_LAND\n!                 call mpp_output_chrt( &\n!                      rt_domain(did)%gnlinks,rt_domain(did)%gnlinksl,rt_domain(did)%map_l2g, &\n!#else\n!                 call output_chrt(  &\n!#endif\n!                   nlst_rt(did)%igrid, nlst_rt(did)%split_output_count, &\n!                   RT_DOMAIN(did)%NLINKS,RT_DOMAIN(did)%ORDER, &\n!                   nlst_rt(did)%sincedate,nlst_rt(did)%olddate,RT_DOMAIN(did)%CHLON,&\n!                   RT_DOMAIN(did)%CHLAT,                                      &\n!                   RT_DOMAIN(did)%HLINK, RT_DOMAIN(did)%ZELEV,                &\n!                   !RT_DOMAIN(did)%QLINK,nlst_rt(did)%DT,Kt,                   &\n!                   str_out, nlst_rt(did)%DT,Kt,                   &\n!                   RT_DOMAIN(did)%STRMFRXSTPTS,nlst_rt(did)%order_to_write,   &\n!                   RT_DOMAIN(did)%NLINKSL,nlst_rt(did)%channel_option,        &\n!                   rt_domain(did)%gages, rt_domain(did)%gageMiss,             &\n!                   nlst_rt(did)%dt                                            &\n!#ifdef WRF_HYDRO_NUDGING\n!                   , RT_DOMAIN(did)%nudge                                     &\n!#endif\n!                   , RT_DOMAIN(did)%accSfcLatRunoff, RT_DOMAIN(did)%accBucket &\n!                   , RT_DOMAIN(did)%qSfcLatRunoff,   RT_DOMAIN(did)%qBucket   &\n!                   , RT_DOMAIN(did)%qin_gwsubbas                              &\n!                   , nlst_rt(did)%UDMP_OPT                                    &\n!                   )\n!              else\n                    if(nlst(did)%CHRTOUT_DOMAIN  .gt. 0)  then\n#ifdef MPP_LAND\n                        call mpp_output_chrt2(&\n                            rt_domain(did)%gnlinks,rt_domain(did)%gnlinksl,rt_domain(did)%map_l2g, &\n#else\n                            call output_chrt2(  &\n#endif\n                            nlst(did)%igrid, nlst(did)%split_output_count, &\n                            RT_DOMAIN(did)%NLINKS,RT_DOMAIN(did)%ORDER,          &\n                            nlst(did)%sincedate,nlst(did)%olddate,         &\n                            RT_DOMAIN(did)%CHLON, RT_DOMAIN(did)%CHLAT,          &\n                            RT_DOMAIN(did)%HLINK, RT_DOMAIN(did)%ZELEV,          &\n!RT_DOMAIN(did)%QLINK,nlst_rt(did)%DT,Kt,             &\n                            str_out, nlst(did)%DT,Kt,                         &\n                            RT_DOMAIN(did)%NLINKSL,nlst(did)%channel_option,  &\n                            rt_domain(did)%linkid                                &\n#ifdef WRF_HYDRO_NUDGING\n                            , RT_DOMAIN(did)%nudge &\n#endif\n!, RT_DOMAIN(did)%QLateral, nlst_rt(did)%io_config_outputs,\n!RT_DOMAIN(did)%velocity &\n                            , RT_DOMAIN(did)%QLateral, nlst(did)%io_config_outputs, vel_out &\n                            , RT_DOMAIN(did)%accSfcLatRunoff, RT_DOMAIN(did)%accBucket &\n                            , RT_DOMAIN(did)%qSfcLatRunoff,   RT_DOMAIN(did)%qBucket &\n                            , RT_DOMAIN(did)%qin_gwsubbas,    nlst(did)%UDMP_OPT &\n                            )\n                    endif\n\n                endif\n            endif ! End of checking for io_form_outputs flag value\n\n#ifdef MPP_LAND\n            if(nlst(did)%CHRTOUT_GRID  .eq. 1)  then\n                if(nlst(did)%io_form_outputs .eq. 0) then\n                    call mpp_output_chrtgrd(nlst(did)%igrid, nlst(did)%split_output_count, &\n                        RT_DOMAIN(did)%ixrt,RT_DOMAIN(did)%jxrt, RT_DOMAIN(did)%NLINKS,   &\n                        RT_DOMAIN(did)%GCH_NETLNK, &\n                        nlst(did)%startdate, nlst(did)%olddate, &\n!RT_DOMAIN(did)%qlink, nlst_rt(did)%dt, nlst_rt(did)%geo_finegrid_flnm,   &\n                        str_out, nlst(did)%dt, nlst(did)%geo_finegrid_flnm,   &\n                        RT_DOMAIN(did)%gnlinks,RT_DOMAIN(did)%map_l2g,                   &\n                        RT_DOMAIN(did)%g_ixrt,RT_DOMAIN(did)%g_jxrt )\n#endif\n                else\n                    call output_chrtout_grd_NWM(did,nlst(did)%igrid)\n                endif\n            endif\n            if (RT_DOMAIN(did)%NLAKES.gt.0)  then\n                if(nlst(did)%io_form_outputs .ne. 0) then\n! Output lakes in NWM format\n                    if(nlst(did)%outlake .ne. 0) then\n                        call output_lakes_NWM(did,nlst(did)%igrid)\n                    endif\n                else\n                    if(nlst(did)%outlake .eq. 1) then\n#ifdef MPP_LAND\n                        call mpp_output_lakes( RT_DOMAIN(did)%lake_index, &\n#else\n                            call output_lakes(  &\n#endif\n                            nlst(did)%igrid, nlst(did)%split_output_count, &\n                            RT_DOMAIN(did)%NLAKES, &\n                            trim(nlst(did)%sincedate), trim(nlst(did)%olddate), &\n                            RT_DOMAIN(did)%LATLAKE,RT_DOMAIN(did)%LONLAKE, &\n                            RT_DOMAIN(did)%ELEVLAKE,RT_DOMAIN(did)%QLAKEI, &\n                            RT_DOMAIN(did)%QLAKEO, &\n                            RT_DOMAIN(did)%RESHT,nlst(did)%DT,Kt)\n                    endif\n                    if(nlst(did)%outlake .eq. 2) then\n#ifdef MPP_LAND\n                        call mpp_output_lakes2( RT_DOMAIN(did)%lake_index, &\n#else\n                            call output_lakes2(  &\n#endif\n                            nlst(did)%igrid, nlst(did)%split_output_count, &\n                            RT_DOMAIN(did)%NLAKES, &\n                            trim(nlst(did)%sincedate), trim(nlst(did)%olddate), &\n                            RT_DOMAIN(did)%LATLAKE,RT_DOMAIN(did)%LONLAKE, &\n                            RT_DOMAIN(did)%ELEVLAKE,RT_DOMAIN(did)%QLAKEI, &\n                            RT_DOMAIN(did)%QLAKEO, &\n                            RT_DOMAIN(did)%RESHT,nlst(did)%DT,Kt,RT_DOMAIN(did)%LAKEIDM)\n                    endif\n\n                endif ! end of check for io_form_outputs value\n            endif   ! end if block of rNLAKES .gt. 0\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n            write(6,*) \"end calling output functions\"\n#else\n            write(78,*) \"end calling output functions\"\n#endif\n#endif\n\n        endif  ! end of routing switch\n\n\n    end subroutine HYDRO_out\n\n\n    subroutine HYDRO_rst_in(did)\n        integer :: did\n        integer:: flag\n\n\n\n        flag = -1\n#ifdef MPP_LAND\n        if(my_id.eq.IO_id) then\n#endif\n            if (trim(nlst(did)%restart_file) /= \"\") then\n                flag = 99\n                rt_domain(did)%timestep_flag = 99   ! continue run\n            endif\n#ifdef MPP_LAND\n        endif\n        call mpp_land_bcast_int1(flag)\n#endif\n\n        nlst(did)%sincedate = nlst(did)%startdate\n\n        if (flag.eq.99) then\n\n#ifdef MPP_LAND\n            if(my_id.eq.IO_id) then\n#endif\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                write(6,*) \"*** read restart data: \",trim(nlst(did)%restart_file)\n#else\n                write(78,*) \"*** read restart data: \",trim(nlst(did)%restart_file)\n#endif\n#endif\n#ifdef MPP_LAND\n            endif\n#endif\n\n#ifdef MPP_LAND\n            if(nlst(did)%rst_bi_in .eq. 1) then\n                call RESTART_IN_bi(trim(nlst(did)%restart_file), did)\n            else\n#endif\n                call RESTART_IN_nc(trim(nlst(did)%restart_file), did)\n#ifdef MPP_LAND\n            endif\n#endif\n\n!yw  if (trim(nlst_rt(did)%restart_file) /= \"\") then\n!yw          nlst_rt(did)%restart_file = \"\"\n!yw  endif\n\n        endif\n    end subroutine HYDRO_rst_in\n\n    subroutine HYDRO_time_adv(did)\n        implicit none\n        character(len = 19) :: newdate\n        integer did\n\n#ifdef MPP_LAND\n        if(IO_id.eq.my_id) then\n#endif\n            call geth_newdate(newdate, nlst(did)%olddate, nint( nlst(did)%dt))\n            nlst(did)%olddate = newdate\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n            write(6,*) \"current time is \",newdate\n#else\n            write(78,*) \"current time is \",newdate\n#endif\n#endif\n#ifdef MPP_LAND\n        endif\n#endif\n    end subroutine HYDRO_time_adv\n\n    subroutine HYDRO_exe(did)\n\n\n        implicit none\n        integer:: did\n        integer:: rst_out\n\n!       call HYDRO_out(did)\n\n\n! running land surface model\n! cpl: 0--offline run;\n!      1-- coupling with WRF but running offline lsm;\n!      2-- coupling with WRF but do not run offline lsm\n!      3-- coupling with LIS and do not run offline lsm\n!      4:  coupling with CLM\n!          if(nlst_rt(did)%SYS_CPL .eq. 0 .or. nlst_rt(did)%SYS_CPL .eq. 1 )then\n!                  call drive_noahLSF(did,kt)\n!          else\n!              ! does not run the NOAH LASF model, only read the parameter\n!              call read_land_par(did,lsm(did)%ix,lsm(did)%jx)\n!          endif\n\n\n        if (nlst(did)%GWBASESWCRT        .ne. 0 .or. &\n            nlst(did)%SUBRTSWCRT         .ne. 0 .or. &\n            nlst(did)%OVRTSWCRT          .ne. 0 .or. &\n            nlst(did)%channel_only       .ne. 0 .or. &\n            nlst(did)%channelBucket_only .ne. 0      ) then\n\n! step 1) disaggregate specific fields from LSM to Hydro grid\n            if(nlst(did)%channel_only .eq. 0 .and. nlst(did)%channelBucket_only .eq. 0) then\n\n                RT_DOMAIN(did)%overland%streams_and_lakes%surface_water_to_channel = zeroFlt\n                RT_DOMAIN(did)%LAKE_INFLORT_DUM = rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake\n\n                if(nlst(did)%SUBRTSWCRT .ne. 0 .or. nlst(did)%OVRTSWCRT .ne. 0) then\n                    call disaggregateDomain_drv(did)\n                endif\n                if(nlst(did)%OVRTSWCRT .eq. 0) then\n                    if(nlst(did)%UDMP_OPT .eq. 1) then\n                        call RunOffDisag(RT_DOMAIN(did)%INFXSRT, RT_DOMAIN(did)%landRunOff,        &\n                            rt_domain(did)%dist_lsm(:,:,9),rt_domain(did)%overland%properties%distance_to_neighbor(:,:,9), &\n                            RT_DOMAIN(did)%INFXSWGT, nlst(did)%AGGFACTRT, RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx)\n                    endif\n                endif\n\n#ifdef HYDRO_D\n                call system_clock(count=clock_count_1, count_rate=clock_rate)\n#endif\n            endif !! channel_only & channelBucket_only == 0\n\n\n! step 2)\n            if(nlst(did)%channel_only .eq. 0 .and. nlst(did)%channelBucket_only .eq. 0) then\n                if(nlst(did)%SUBRTSWCRT .ne.0) then\n                    call SubsurfaceRouting_drv(did)\n                endif\n#ifdef HYDRO_D\n                call system_clock(count=clock_count_2, count_rate=clock_rate)\n                timeSr = timeSr     + float(clock_count_2-clock_count_1)/float(clock_rate)\n#ifndef NCEP_WCOSS\n                write(6,*) \"Timing: Subsurface Routing  accumulated time--\", timeSr\n#else\n                write(78,*) \"Timing: Subsurface Routing  accumulated time--\", timeSr\n#endif\n#endif\n            end if !! channel_only & channelBucket_only == 0\n\n\n! step 3) todo split\n            if(nlst(did)%channel_only .eq. 0 .and. nlst(did)%channelBucket_only .eq. 0) then\n#ifdef HYDRO_D\n                call system_clock(count=clock_count_1, count_rate=clock_rate)\n#endif\n                if(nlst(did)%OVRTSWCRT .ne. 0) then\n                    call OverlandRouting_drv(did)\n                else\n!ADCHANGE: Updating landRunoff instead of surface_water_head_routing. This now allows\n!          landRunoff to include both infxsrt from the LSM and exfiltration (if subsfc\n!          is active) and prevents surface_water_head_routing from inadvertently being\n!          passed back to the LSM.\n                    if (nlst(did)%UDMP_OPT .eq. 1) then\n! If subsurface is on, we update landRunOff to include the updated term w/ exfiltration.\n! If subsurface is off, landRunOff does not change from original value so we leave as-is.\n                        if (nlst(did)%SUBRTSWCRT .ne. 0) then\n                            rt_domain(did)%landRunOff = rt_domain(did)%overland%control%infiltration_excess\n                        endif\n                    else\n! If overland is off and subsurface is on, we need to update INFXSRT (LSM grid)\n! since that is what gets fed through the buckets into the channels. So we aggregate\n! the high-res infiltration_excess back to coarse grid.\n                        if (nlst(did)%SUBRTSWCRT .ne. 0) then\n                            call RunoffAggregate(rt_domain(did)%overland%control%infiltration_excess, &\n                                rt_domain(did)%INFXSRT, nlst(did)%AGGFACTRT, &\n                                rt_domain(did)%ix, rt_domain(did)%jx)\n                        endif\n                    endif\n! In either case, if overland is off we need to zero-out surface_water_head since this\n! water is being scraped into channel and should NOT be passed back to the LSM.\n                    rt_domain(did)%overland%control%infiltration_excess = 0.\n                    rt_domain(did)%overland%control%surface_water_head_routing = 0.\n                endif\n#ifdef HYDRO_D\n                call system_clock(count=clock_count_2, count_rate=clock_rate)\n                timeOr = timeOr     + float(clock_count_2-clock_count_1)/float(clock_rate)\n#ifndef NCEP_WCOSS\n                write(6,*) \"Timing: Overland Routing  accumulated time--\", timeOr\n#else\n                write(78,*) \"Timing: Overland Routing  accumulated time--\", timeOr\n#endif\n#endif\n\n                RT_DOMAIN(did)%QSTRMVOLRT_TS = rt_domain(did)%overland%streams_and_lakes%surface_water_to_channel\n                RT_DOMAIN(did)%QSTRMVOLRT_ACC = RT_DOMAIN(did)%QSTRMVOLRT_ACC + RT_DOMAIN(did)%QSTRMVOLRT_TS\n\n                RT_DOMAIN(did)%LAKE_INFLORT_TS = rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake-RT_DOMAIN(did)%LAKE_INFLORT_DUM\n\n#ifdef HYDRO_D\n                call system_clock(count=clock_count_1, count_rate=clock_rate)\n#endif\n            end if !! channel_only & channelBucket_only == 0\n\n\n! step 4) baseflow or groundwater physics\n!! channelBucket_only can be anything: the only time you dont run this is if channel_only=1\n            if(nlst(did)%channel_only .eq. 0) then\n                if (nlst(did)%GWBASESWCRT .gt. 0) then\n                    call driveGwBaseflow(did)\n                endif\n#ifdef HYDRO_D\n                call system_clock(count=clock_count_2, count_rate=clock_rate)\n                timeGw = timeGw     + float(clock_count_2-clock_count_1)/float(clock_rate)\n#ifndef NCEP_WCOSS\n                write(6,*) \"Timing: GwBaseflow  accumulated time--\", timeGw\n#else\n                write(78,*) \"Timing: GwBaseflow  accumulated time--\", timeGw\n#endif\n#endif\n#ifdef HYDRO_D\n                call system_clock(count=clock_count_1, count_rate=clock_rate)\n#endif\n            end if !! channel_only == 0\n\n! step 5) river channel physics\n            call driveChannelRouting(did)\n#ifdef HYDRO_D\n            call system_clock(count=clock_count_2, count_rate=clock_rate)\n            timeCr = timeCr     + float(clock_count_2-clock_count_1)/float(clock_rate)\n#ifndef NCEP_WCOSS\n            write(6,*) \"Timing: Channel Routing  accumulated time--\", timeCr\n#else\n            write(78,*) \"Timing: Channel Routing  accumulated time--\", timeCr\n#endif\n#endif\n\n!! if not channel_only\n            if(nlst(did)%channel_only .eq. 0 .and. nlst(did)%channelBucket_only .eq. 0) then\n\n! step 6) aggregate specific fields from Hydro to LSM grid\n                if (nlst(did)%SUBRTSWCRT .ne.0  .or. nlst(did)%OVRTSWCRT .ne. 0 ) then\n                    call aggregateDomain(did)\n                endif\n\n            end if !! channel_only & channelBucket_only == 0\n\n        end if\n\n\n!yw  if (nlst_rt(did)%sys_cpl .eq. 2) then\n! advance to next time step\n!          call HYDRO_time_adv(did)\n! output for history\n!          call HYDRO_out(did)\n!yw  endif\n        call HYDRO_time_adv(did)\n        call HYDRO_out(did, 1)\n\n\n!           write(90 + my_id,*) \"finish calling hydro_exe\"\n!           call flush(90+my_id)\n!          call mpp_land_sync()\n\n\n\n!! Under channel-only, these variables are not allocated\n        if(allocated(RT_DOMAIN(did)%SOLDRAIN)) RT_DOMAIN(did)%SOLDRAIN = 0\n        if(allocated(rt_domain(did)%subsurface%state%qsubrt))   RT_DOMAIN(did)%subsurface%state%qsubrt   = 0\n\n\n\n    end subroutine HYDRO_exe\n\n\n\n!----------------------------------------------------\n    subroutine driveGwBaseflow(did)\n\n        implicit none\n        integer, intent(in) :: did\n\n        integer :: i, jj, ii\n\n!------------------------------------------------------------------\n!DJG Begin GW/Baseflow Routines\n!-------------------------------------------------------------------\n\n        if (nlst(did)%GWBASESWCRT.ge.1) then     ! Switch to activate/specify GW/Baseflow\n\n!  IF (nlst(did)%GWBASESWCRT.GE.1000) THEN     ! Switch to activate/specify GW/Baseflow\n\n            if (nlst(did)%GWBASESWCRT.eq.1 .or. nlst(did)%GWBASESWCRT.eq.2 .or. nlst(did)%GWBASESWCRT.ge.4) then   ! Call simple bucket baseflow scheme\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                write(6,*) \"*****yw******start simp_gw_buck \"\n#else\n                write(78,*) \"*****yw******start simp_gw_buck \"\n#endif\n#endif\n\n                if(nlst(did)%UDMP_OPT .eq. 1) then\n                    call simp_gw_buck_nhd(                                             &\n                        RT_DOMAIN(did)%ix,            RT_DOMAIN(did)%jx,              &\n                        RT_DOMAIN(did)%ixrt,          RT_DOMAIN(did)%jxrt,            &\n                        RT_DOMAIN(did)%numbasns,      nlst(did)%AGGFACTRT,         &\n                        nlst(did)%DT,              RT_DOMAIN(did)%INFXSWGT,        &\n                        RT_DOMAIN(did)%INFXSRT,       RT_DOMAIN(did)%SOLDRAIN,        &\n                        rt_domain(did)%overland%properties%distance_to_neighbor(:,:,9),   rt_domain(did)%dist_lsm(:,:,9), &\n                        RT_DOMAIN(did)%gw_buck_coeff, RT_DOMAIN(did)%gw_buck_exp,     &\n                        RT_DOMAIN(did)%gw_buck_loss,                                  &\n                        RT_DOMAIN(did)%z_max,         RT_DOMAIN(did)%z_gwsubbas,      &\n                        RT_DOMAIN(did)%qout_gwsubbas, RT_DOMAIN(did)%qin_gwsubbas,    &\n                        RT_DOMAIN(did)%qloss_gwsubbas,                                &\n                        nlst(did)%GWBASESWCRT,     nlst(did)%OVRTSWCRT,         &\n#ifdef MPP_LAND\n                        RT_DOMAIN(did)%LNLINKSL,                                      &\n#else\n                        RT_DOMAIN(did)%numbasns,                                      &\n#endif\n                        rt_domain(did)%basns_area,                                    &\n                        rt_domain(did)%nhdBuckMask,   nlst(did)%bucket_loss,       &\n                        nlst(did)%channelBucket_only )\n\n                else\n                    call simp_gw_buck(RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx,RT_DOMAIN(did)%ixrt,&\n                        RT_DOMAIN(did)%jxrt,RT_DOMAIN(did)%numbasns,RT_DOMAIN(did)%gnumbasns,&\n                        RT_DOMAIN(did)%basns_area,&\n                        RT_DOMAIN(did)%basnsInd, RT_DOMAIN(did)%gw_strm_msk_lind,             &\n                        RT_DOMAIN(did)%gwsubbasmsk, RT_DOMAIN(did)%INFXSRT, &\n                        RT_DOMAIN(did)%SOLDRAIN, &\n                        RT_DOMAIN(did)%z_gwsubbas,&\n                        RT_DOMAIN(did)%qin_gwsubbas,RT_DOMAIN(did)%qout_gwsubbas,&\n                        RT_DOMAIN(did)%qinflowbase,&\n                        RT_DOMAIN(did)%gw_strm_msk,RT_DOMAIN(did)%gwbas_pix_ct, &\n                        rt_domain(did)%overland%properties%distance_to_neighbor,nlst(did)%DT,&\n                        RT_DOMAIN(did)%gw_buck_coeff,RT_DOMAIN(did)%gw_buck_exp, &\n                        RT_DOMAIN(did)%z_max,&\n                        nlst(did)%GWBASESWCRT,nlst(did)%OVRTSWCRT)\n                endif\n\n!! JLM: There's *perhaps* a better location for this output above.\n!! If above is better, remove this when runtime output options are avail.\n!#ifndef HYDRO_REALTIME\n!        call output_GW_Diag(did)\n!#endif\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                write(6,*) \"*****yw******end simp_gw_buck \"\n#else\n                write(78,*) \"*****yw******end simp_gw_buck \"\n#endif\n#endif\n\n!!!For parameter setup runs output the percolation for each basin,\n!!!otherwise comment out this output...\n            else if (nlst(did)%gwBaseSwCRT .eq. 3) then\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                write(6,*) \"*****bf******start 2d_gw_model \"\n#else\n                write(78,*) \"*****bf******start 2d_gw_model \"\n#endif\n#endif\n\n! \t   compute qsgwrt  between lsm and gw with namelist selected coupling method\n! \t   qsgwrt is defined on the routing grid  and needs to be aggregated for SFLX\n                if (nlst(did)%gwsoilcpl .GT. 0) THEN\n\n                    call gwSoilFlux(did)\n\n                end if\n\n                gw2d(did)%excess = 0.\n\n                call gwstep(gw2d(did)%ix, gw2d(did)%jx, gw2d(did)%dx, &\n                    gw2d(did)%ltype, gw2d(did)%elev, gw2d(did)%bot, &\n                    gw2d(did)%hycond, gw2d(did)%poros, gw2d(did)%compres, &\n                    gw2d(did)%ho, gw2d(did)%h, gw2d(did)%convgw, &\n                    gw2d(did)%excess, &\n                    gw2d(did)%ebot, gw2d(did)%eocn, gw2d(did)%dt, &\n                    gw2d(did)%istep)\n\n                gw2d(did)%ho = gw2d(did)%h\n\n! put surface exceeding groundwater to surface routing inflow\n                rt_domain(did)%overland%control%surface_water_head_routing = rt_domain(did)%overland%control%surface_water_head_routing &\n                    + gw2d(did)%excess*1000. ! convert to mm\n\n! aggregate  qsgw from routing to lsm grid\n                call aggregateQsgw(did)\n\n                gw2d(did)%istep =  gw2d(did)%istep + 1\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                write(6,*) \"*****bf******end 2d_gw_model \"\n#else\n                write(78,*) \"*****bf******end 2d_gw_model \"\n#endif\n#endif\n\n            end if\n\n        end if    !DJG (End if for RTE SWC activation)\n!------------------------------------------------------------------\n!DJG End GW/Baseflow Routines\n!-------------------------------------------------------------------\n    end subroutine driveGwBaseflow\n\n\n\n\n!-------------------------------------------\n    subroutine driveChannelRouting(did)\n\n        implicit none\n        integer, intent(in) :: did\n\n!-------------------------------------------------------------------\n!-------------------------------------------------------------------\n!DJG,DNY  Begin Channel and Lake Routing Routines\n!-------------------------------------------------------------------\n\n        if (nlst(did)%CHANRTSWCRT.eq.1 .or. nlst(did)%CHANRTSWCRT.eq.2) then\n\n            if(nlst(did)%UDMP_OPT .eq. 1) then\n!!! for user defined Reach based Routing method.\n\n                call drive_CHANNEL_RSL(did, nlst(did)%UDMP_OPT,RT_DOMAIN(did)%timestep_flag, RT_DOMAIN(did)%IXRT,RT_DOMAIN(did)%JXRT,  &\n                    RT_DOMAIN(did)%LAKE_INFLORT_TS, RT_DOMAIN(did)%QSTRMVOLRT_TS, RT_DOMAIN(did)%TO_NODE, RT_DOMAIN(did)%FROM_NODE, &\n                    RT_DOMAIN(did)%TYPEL, RT_DOMAIN(did)%ORDER, RT_DOMAIN(did)%MAXORDER,   RT_DOMAIN(did)%CH_LNKRT, &\n                    rt_domain(did)%overland%streams_and_lakes%lake_mask, nlst(did)%DT, nlst(did)%DTCT, nlst(did)%DTRT_CH, &\n                    RT_DOMAIN(did)%MUSK, RT_DOMAIN(did)%MUSX, RT_DOMAIN(did)%QLINK, &\n                    RT_DOMAIN(did)%CHANLEN, RT_DOMAIN(did)%MannN, RT_DOMAIN(did)%So, RT_DOMAIN(did)%ChSSlp,RT_DOMAIN(did)%Bw, &\n                    RT_DOMAIN(did)%Tw,  RT_DOMAIN(did)%Tw_CC, RT_DOMAIN(did)%n_CC, &\n                    RT_DOMAIN(did)%ChannK,&\n                    RT_DOMAIN(did)%RESHT, &\n                    RT_DOMAIN(did)%CVOL, RT_DOMAIN(did)%QLAKEI, &\n                    RT_DOMAIN(did)%QLAKEO, RT_DOMAIN(did)%LAKENODE, &\n                    RT_DOMAIN(did)%QINFLOWBASE, RT_DOMAIN(did)%CHANXI, RT_DOMAIN(did)%CHANYJ, nlst(did)%channel_option,  &\n                    RT_DOMAIN(did)%nlinks, RT_DOMAIN(did)%NLINKSL, RT_DOMAIN(did)%LINKID, RT_DOMAIN(did)%node_area,         &\n                    RT_DOMAIN(did)%qout_gwsubbas, &\n                    RT_DOMAIN(did)%LAKEIDA, RT_DOMAIN(did)%LAKEIDM, RT_DOMAIN(did)%NLAKES, RT_DOMAIN(did)%LAKEIDX   &\n#ifdef MPP_LAND\n                    , RT_DOMAIN(did)%nlinks_index, RT_DOMAIN(did)%mpp_nlinks, RT_DOMAIN(did)%yw_mpp_nlinks  &\n                    , RT_DOMAIN(did)%LNLINKSL   &\n                    , RT_DOMAIN(did)%gtoNode, RT_DOMAIN(did)%toNodeInd, RT_DOMAIN(did)%nToInd      &\n#endif\n                    , RT_DOMAIN(did)%CH_LNKRT_SL, RT_DOMAIN(did)%landRunOff   &\n#ifdef WRF_HYDRO_NUDGING\n                    , RT_DOMAIN(did)%nudge &\n#endif\n                    , rt_domain(did)%accSfcLatRunoff,    rt_domain(did)%accBucket &\n                    , rt_domain(did)%qSfcLatRunoff,        rt_domain(did)%qBucket &\n                    , rt_domain(did)%QLateral,            rt_domain(did)%velocity &\n                    ,                                     rt_domain(did)%qloss    &\n                    ,                                     RT_DOMAIN(did)%HLINK    &\n                    , rt_domain(did)%nlinksize,            nlst(did)%OVRTSWCRT &\n                    ,                                     nlst(did)%SUBRTSWCRT &\n                    , nlst(did)%channel_only , nlst(did)%channelBucket_only &\n                    , nlst(did)%channel_bypass )\n\n            else\n\n                call drive_CHANNEL(did, RT_DOMAIN(did)%latval,RT_DOMAIN(did)%lonval, &\n                    RT_DOMAIN(did)%timestep_flag,RT_DOMAIN(did)%IXRT,RT_DOMAIN(did)%JXRT, &\n                    nlst(did)%SUBRTSWCRT, rt_domain(did)%subsurface%state%qsubrt, &\n                    RT_DOMAIN(did)%LAKE_INFLORT_TS, RT_DOMAIN(did)%QSTRMVOLRT_TS,&\n                    RT_DOMAIN(did)%TO_NODE, RT_DOMAIN(did)%FROM_NODE, RT_DOMAIN(did)%TYPEL,&\n                    RT_DOMAIN(did)%ORDER, RT_DOMAIN(did)%MAXORDER, RT_DOMAIN(did)%NLINKS,&\n                    RT_DOMAIN(did)%CH_NETLNK, rt_domain(did)%overland%streams_and_lakes%ch_netrt,RT_DOMAIN(did)%CH_LNKRT,&\n                    rt_domain(did)%overland%streams_and_lakes%lake_mask, nlst(did)%DT, nlst(did)%DTCT, nlst(did)%DTRT_CH,&\n                    RT_DOMAIN(did)%MUSK, RT_DOMAIN(did)%MUSX,  RT_DOMAIN(did)%QLINK, &\n                    RT_DOMAIN(did)%QLateral, &\n                    RT_DOMAIN(did)%HLINK, RT_DOMAIN(did)%ELRT,RT_DOMAIN(did)%CHANLEN,&\n                    RT_DOMAIN(did)%MannN,RT_DOMAIN(did)%So, RT_DOMAIN(did)%ChSSlp, &\n                    RT_DOMAIN(did)%Bw,RT_DOMAIN(did)%Tw,RT_DOMAIN(did)%Tw_CC, RT_DOMAIN(did)%n_CC, &\n                    RT_DOMAIN(did)%ChannK, &\n                    RT_DOMAIN(did)%RESHT, &\n                    RT_DOMAIN(did)%HRZAREA, RT_DOMAIN(did)%LAKEMAXH, &\n                    RT_DOMAIN(did)%WEIRH, RT_DOMAIN(did)%WEIRC, RT_DOMAIN(did)%WEIRL, &\n                    RT_DOMAIN(did)%ORIFICEC, RT_DOMAIN(did)%ORIFICEA, RT_DOMAIN(did)%ORIFICEE, &\n                    RT_DOMAIN(did)%ZELEV, RT_DOMAIN(did)%CVOL, &\n                    RT_DOMAIN(did)%NLAKES, RT_DOMAIN(did)%QLAKEI, RT_DOMAIN(did)%QLAKEO,&\n                    RT_DOMAIN(did)%LAKENODE, rt_domain(did)%overland%properties%distance_to_neighbor, &\n                    RT_DOMAIN(did)%QINFLOWBASE, RT_DOMAIN(did)%CHANXI, &\n                    RT_DOMAIN(did)%CHANYJ, nlst(did)%channel_option, &\n                    RT_DOMAIN(did)%RETDEP_CHAN, RT_DOMAIN(did)%NLINKSL, RT_DOMAIN(did)%LINKID, &\n                    RT_DOMAIN(did)%node_area, RT_DOMAIN(did)%LAKEIDX  &\n#ifdef MPP_LAND\n                    ,RT_DOMAIN(did)%lake_index,RT_DOMAIN(did)%link_location,&\n                    RT_DOMAIN(did)%mpp_nlinks,RT_DOMAIN(did)%nlinks_index, &\n                    RT_DOMAIN(did)%yw_mpp_nlinks,  &\n                    RT_DOMAIN(did)%LNLINKSL, RT_DOMAIN(did)%LLINKID, &\n                    rt_domain(did)%gtoNode, rt_domain(did)%toNodeInd,rt_domain(did)%nToInd  &\n#endif\n                    , rt_domain(did)%CH_LNKRT_SL,   &\n                    nlst(did)%GwBaseSwCRT, gw2d(did)%ho, gw2d(did)%qgw_chanrt, &\n                    nlst(did)%gwChanCondSw, nlst(did)%gwChanCondConstIn, &\n                    nlst(did)%gwChanCondConstOut, rt_domain(did)%velocity, rt_domain(did)%qloss &\n                    )\n            endif\n\n            if((nlst(did)%gwBaseSwCRT == 3) .and. (nlst(did)%gwChanCondSw .eq. 1)) then\n\n! add/rm channel-aquifer exchange contribution\n\n                gw2d(did)%ho =  gw2d(did)%ho  &\n                    +(((gw2d(did)%qgw_chanrt*(-1)) * gw2d(did)%dt / gw2d(did)%dx**2) &\n                    /  gw2d(did)%poros)\n\n            endif\n        endif\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        write(6,*) \"*****yw******end drive_CHANNEL \"\n#else\n        write(78,*) \"*****yw******end drive_CHANNEL \"\n#endif\n#endif\n\n    end subroutine driveChannelRouting\n\n\n\n!------------------------------------------------\n    subroutine aggregateDomain(did)\n\n#ifdef MPP_LAND\n        use module_mpp_land, only:  sum_real1, my_id, io_id, numprocs\n#endif\n\n        implicit none\n        integer, intent(in) :: did\n\n        integer :: i, j, krt, ixxrt, jyyrt, &\n            AGGFACYRT, AGGFACXRT\n\n#ifdef HYDRO_D\n! ADCHANGE: Water balance variables\n        integer :: kk\n        real    :: smcrttot1,smctot2,sicetot2\n        real    :: suminfxsrt1,suminfxs2\n#endif\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        print *, \"Beginning Aggregation...\"\n#else\n        write(78,*) \"Beginning Aggregation...\"\n#endif\n#endif\n\n#ifdef HYDRO_D\n! ADCHANGE: START Initial water balance variables\n! ALL VARS in MM\n        suminfxsrt1 = 0.\n        smcrttot1 = 0.\n        do i=1,RT_DOMAIN(did)%IXRT\n            do j=1,RT_DOMAIN(did)%JXRT\n                suminfxsrt1 = suminfxsrt1 + rt_domain(did)%overland%control%surface_water_head_routing(I,J) &\n                    / float(RT_DOMAIN(did)%IXRT * RT_DOMAIN(did)%JXRT)\n                do kk=1,nlst(did)%NSOIL\n                    smcrttot1 = smcrttot1 + rt_domain(did)%subsurface%grid_transform%smcrt(I,J,KK)*RT_DOMAIN(did)%subsurface%properties%sldpth(KK)*1000. &\n                        / float(RT_DOMAIN(did)%IXRT * RT_DOMAIN(did)%JXRT)\n                end do\n            end do\n        end do\n#ifdef MPP_LAND\n! not tested\n        CALL sum_real1(suminfxsrt1)\n        CALL sum_real1(smcrttot1)\n        suminfxsrt1 = suminfxsrt1/float(numprocs)\n        smcrttot1 = smcrttot1/float(numprocs)\n#endif\n! END Initial water balance variables\n#endif\n\n        do J=1,RT_DOMAIN(did)%JX\n            do I=1,RT_DOMAIN(did)%IX\n\n                RT_DOMAIN(did)%SFCHEADAGGRT = 0.\n!DJG Subgrid weighting edit...\n                RT_DOMAIN(did)%LSMVOL=0.\n                do KRT=1,nlst(did)%NSOIL\n!                SMCAGGRT(KRT) = 0.\n                    RT_DOMAIN(did)%SH2OAGGRT(KRT) = 0.\n                end do\n\n\n                do AGGFACYRT=nlst(did)%AGGFACTRT-1,0,-1\n                    do AGGFACXRT=nlst(did)%AGGFACTRT-1,0,-1\n\n\n                        IXXRT=I*nlst(did)%AGGFACTRT-AGGFACXRT\n                        JYYRT=J*nlst(did)%AGGFACTRT-AGGFACYRT\n#ifdef MPP_LAND\n                        if(left_id.ge.0) IXXRT=IXXRT+1\n                        if(down_id.ge.0) JYYRT=JYYRT+1\n#else\n!yw ????\n!       IXXRT=IXXRT+1\n!       JYYRT=JYYRT+1\n#endif\n\n!State Variables\n                        RT_DOMAIN(did)%SFCHEADAGGRT = RT_DOMAIN(did)%SFCHEADAGGRT &\n                            + rt_domain(did)%overland%control%surface_water_head_routing(IXXRT,JYYRT)\n!DJG Subgrid weighting edit...\n                        RT_DOMAIN(did)%LSMVOL = RT_DOMAIN(did)%LSMVOL &\n                            + rt_domain(did)%overland%control%surface_water_head_routing(IXXRT,JYYRT) &\n                            * rt_domain(did)%overland%properties%distance_to_neighbor(IXXRT,JYYRT,9)\n\n                        do KRT=1,nlst(did)%NSOIL\n!DJG               SMCAGGRT(KRT)=SMCAGGRT(KRT)+SMCRT(IXXRT,JYYRT,KRT)\n                            RT_DOMAIN(did)%SH2OAGGRT(KRT) = RT_DOMAIN(did)%SH2OAGGRT(KRT) &\n                                + rt_domain(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT)\n                        end do\n\n                    end do\n                end do\n\n\n\n                rt_domain(did)%overland%control%surface_water_head_lsm(I,J) = RT_DOMAIN(did)%SFCHEADAGGRT &\n                    / (nlst(did)%AGGFACTRT**2)\n\n                do KRT=1,nlst(did)%NSOIL\n!DJG              SMC(I,J,KRT)=SMCAGGRT(KRT)/(AGGFACTRT**2)\n                    RT_DOMAIN(did)%SH2OX(I,J,KRT) = RT_DOMAIN(did)%SH2OAGGRT(KRT) &\n                        / (nlst(did)%AGGFACTRT**2)\n                end do\n\n\n\n!DJG Calculate subgrid weighting array...\n\n                do AGGFACYRT=nlst(did)%AGGFACTRT-1,0,-1\n                    do AGGFACXRT=nlst(did)%AGGFACTRT-1,0,-1\n                        IXXRT=I*nlst(did)%AGGFACTRT-AGGFACXRT\n                        JYYRT=J*nlst(did)%AGGFACTRT-AGGFACYRT\n#ifdef MPP_LAND\n                        if(left_id.ge.0) IXXRT=IXXRT+1\n                        if(down_id.ge.0) JYYRT=JYYRT+1\n#else\n!yw ???\n!       IXXRT=IXXRT+1\n!       JYYRT=JYYRT+1\n#endif\n                        if (RT_DOMAIN(did)%LSMVOL.gt.0.) then\n                            RT_DOMAIN(did)%INFXSWGT(IXXRT,JYYRT) &\n                                = rt_domain(did)%overland%control%surface_water_head_routing(IXXRT,JYYRT) &\n                                * rt_domain(did)%overland%properties%distance_to_neighbor(IXXRT,JYYRT,9) &\n                                / RT_DOMAIN(did)%LSMVOL\n                        else\n                            RT_DOMAIN(did)%INFXSWGT(IXXRT,JYYRT) &\n                                = 1./FLOAT(nlst(did)%AGGFACTRT**2)\n                        end if\n\n                        do KRT=1,nlst(did)%NSOIL\n\n!!!yw added for debug\n                            if(rt_domain(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT) .lt. 0) then\n#ifndef NCEP_WCOSS\n                                print*, \"Error negative SMCRT\", rt_domain(did)%SH2OWGT(IXXRT,JYYRT,KRT), RT_DOMAIN(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),RT_DOMAIN(did)%SH2OX(I,J,KRT)\n#else\n                                write(78,*) \"WARNING: negative SMCRT\", rt_domain(did)%SH2OWGT(IXXRT,JYYRT,KRT), RT_DOMAIN(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),RT_DOMAIN(did)%SH2OX(I,J,KRT)\n#endif\n                            endif\n                            if(RT_DOMAIN(did)%SH2OWGT(IXXRT,JYYRT,KRT) .lt. 0) then\n#ifndef NCEP_WCOSS\n                                print *, \"Error negative SH2OWGT\", rt_domain(did)%SH2OWGT(IXXRT,JYYRT,KRT), RT_DOMAIN(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),RT_DOMAIN(did)%SH2OX(I,J,KRT)\n#else\n                                write(78,*) \"WARNING: negative SH2OWGT\", rt_domain(did)%SH2OWGT(IXXRT,JYYRT,KRT), RT_DOMAIN(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),RT_DOMAIN(did)%SH2OX(I,J,KRT)\n#endif\n                            endif\n\n                            IF ( (rt_domain(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT) - &\n                                rt_domain(did)%subsurface%grid_transform%smcmaxrt(IXXRT,JYYRT,KRT)) .GT. 0.000001 ) THEN\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                                print *, \"SMCMAX exceeded upon aggregation...\", &\n                                    rt_domain(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),  &\n                                    rt_domain(did)%subsurface%grid_transform%smcmaxrt(IXXRT,JYYRT,KRT)\n#else\n                                write(78,*) \"FATAL ERROR: SMCMAX exceeded upon aggregation...\", &\n                                    rt_domain(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),  &\n                                    rt_domain(did)%subsurface%grid_transform%smcmaxrt(IXXRT,JYYRT,KRT)\n#endif\n#endif\n                                call hydro_stop(\"In module_HYDRO_drv.F aggregateDomain() - \"// &\n                                    \"SMCMAX exceeded upon aggregation.\")\n                            END IF\n                            IF(RT_DOMAIN(did)%SH2OX(I,J,KRT).LT.0.) THEN\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n                                print *, \"Erroneous value of SH2O...\", &\n                                    RT_DOMAIN(did)%SH2OX(I,J,KRT),I,J,KRT\n                                print *, \"Error negative SH2OX\", rt_domain(did)%SH2OWGT(IXXRT,JYYRT,KRT), RT_DOMAIN(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),RT_DOMAIN(did)%SH2OX(I,J,KRT)\n#else\n                                write(78,*) \"Erroneous value of SH2O...\", &\n                                    RT_DOMAIN(did)%SH2OX(I,J,KRT),I,J,KRT\n                                write(78,*) \"FATAL ERROR: negative SH2OX\", rt_domain(did)%SH2OWGT(IXXRT,JYYRT,KRT), RT_DOMAIN(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),RT_DOMAIN(did)%SH2OX(I,J,KRT)\n#endif\n#endif\n                                call hydro_stop(\"In module_HYDRO_drv.F aggregateDomain() \"// &\n                                    \"- Error negative SH2OX\")\n                            END IF\n\n                            IF ( RT_DOMAIN(did)%SH2OX(I,J,KRT) .gt. 0 ) THEN\n                                RT_DOMAIN(did)%SH2OWGT(IXXRT,JYYRT,KRT) &\n                                    = rt_domain(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT) &\n                                    / RT_DOMAIN(did)%SH2OX(I,J,KRT)\n                            ELSE\n#ifdef HYDRO_D\n                                print *, \"Error zero SH2OX\", rt_domain(did)%SH2OWGT(IXXRT,JYYRT,KRT), RT_DOMAIN(did)%subsurface%grid_transform%smcrt(IXXRT,JYYRT,KRT),RT_DOMAIN(did)%SH2OX(I,J,KRT)\n#endif\n                                RT_DOMAIN(did)%SH2OWGT(IXXRT,JYYRT,KRT) = 0.0\n                            ENDIF\n!?yw\n                            RT_DOMAIN(did)%SH2OWGT(IXXRT,JYYRT,KRT) = max(1.0E-05, RT_DOMAIN(did)%SH2OWGT(IXXRT,JYYRT,KRT))\n                        end do\n\n                    end do\n                end do\n\n            end do\n        end do\n\n\n#ifdef MPP_LAND\n        call MPP_LAND_COM_REAL(RT_DOMAIN(did)%INFXSWGT, &\n            RT_DOMAIN(did)%IXRT,    &\n            RT_DOMAIN(did)%JXRT, 99)\n\n        do i = 1, nlst(did)%NSOIL\n            call MPP_LAND_COM_REAL(RT_DOMAIN(did)%SH2OWGT(:,:,i), &\n                RT_DOMAIN(did)%IXRT, &\n                RT_DOMAIN(did)%JXRT, 99)\n        end do\n#endif\n\n!DJG Update SMC with SICE (unchanged) and new value of SH2O from routing...\n        RT_DOMAIN(did)%SMC = RT_DOMAIN(did)%SH2OX + RT_DOMAIN(did)%SICE\n\n#ifdef HYDRO_D\n! ADCHANGE: START Final water balance variables\n! ALL VARS in MM\n        suminfxs2 = 0.\n        smctot2 = 0.\n        sicetot2 = 0.\n        do i=1,RT_DOMAIN(did)%IX\n            do j=1,RT_DOMAIN(did)%JX\n                suminfxs2 = suminfxs2 + rt_domain(did)%overland%control%surface_water_head_lsm(I,J) &\n                    / float(RT_DOMAIN(did)%IX * RT_DOMAIN(did)%JX)\n                do kk=1,nlst(did)%NSOIL\n                    smctot2 = smctot2 + rt_domain(did)%SMC(I,J,KK)*RT_DOMAIN(did)%subsurface%properties%sldpth(KK)*1000. &\n                        / float(RT_DOMAIN(did)%IX * RT_DOMAIN(did)%JX)\n                    sicetot2 = sicetot2 + rt_domain(did)%SICE(I,J,KK)*RT_DOMAIN(did)%subsurface%properties%sldpth(KK)*1000. &\n                        / float(RT_DOMAIN(did)%IX * RT_DOMAIN(did)%JX)\n                end do\n            end do\n        end do\n\n#ifdef MPP_LAND\n! not tested\n        CALL sum_real1(suminfxs2)\n        CALL sum_real1(smctot2)\n        CALL sum_real1(sicetot2)\n        suminfxs2 = suminfxs2/float(numprocs)\n        smctot2 = smctot2/float(numprocs)\n        sicetot2 = sicetot2/float(numprocs)\n#endif\n\n#ifdef MPP_LAND\n        if (my_id .eq. IO_id) then\n#endif\n            print *, \"Agg Mass Bal: \"\n            print *, \"WB_AGG!InfxsDiff\", suminfxs2-suminfxsrt1\n            print *, \"WB_AGG!Infxs1\", suminfxsrt1\n            print *, \"WB_AGG!Infxs2\", suminfxs2\n            print *, \"WB_AGG!SMCDiff\", smctot2-smcrttot1-sicetot2\n            print *, \"WB_AGG!SMC1\", smcrttot1\n            print *, \"WB_AGG!SMC2\", smctot2\n            print *, \"WB_AGG!SICE2\", sicetot2\n            print *, \"WB_AGG!Residual\", (suminfxs2-suminfxsrt1) + &\n                (smctot2-smcrttot1-sicetot2)\n#ifdef MPP_LAND\n        endif\n#endif\n! END Final water balance variables\n#endif\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        print *, \"Finished Aggregation...\"\n#else\n        write(78,*) \"Finished Aggregation...\"\n#endif\n#endif\n\n\n    end subroutine aggregateDomain\n\n    subroutine RunOffDisag(runoff1x_in, runoff1x, area_lsm,cellArea, infxswgt, AGGFACTRT, ix,jx)\n        implicit none\n        real, dimension(:,:) :: runoff1x_in, runoff1x, area_lsm, cellArea, infxswgt\n        integer :: i,j,ix,jx,AGGFACYRT, AGGFACXRT, AGGFACTRT, IXXRT, JYYRT\n\n        do J=1,JX\n            do I=1,IX\n                do AGGFACYRT=AGGFACTRT-1,0,-1\n                    do AGGFACXRT=AGGFACTRT-1,0,-1\n                        IXXRT=I*AGGFACTRT-AGGFACXRT\n                        JYYRT=J*AGGFACTRT-AGGFACYRT\n#ifdef MPP_LAND\n                        if(left_id.ge.0) IXXRT=IXXRT+1\n                        if(down_id.ge.0) JYYRT=JYYRT+1\n#endif\n!DJG Implement subgrid weighting routine...\n                        if( (runoff1x_in(i,j) .lt. 0) .or. (runoff1x_in(i,j) .gt. 1000) ) then\n                            runoff1x(IXXRT,JYYRT) = 0\n                        else\n                            runoff1x(IXXRT,JYYRT)=runoff1x_in(i,j)*area_lsm(I,J)     &\n                                *INFXSWGT(IXXRT,JYYRT)/cellArea(IXXRT,JYYRT)\n                        endif\n\n                    enddo\n                enddo\n            enddo\n        enddo\n\n    end subroutine RunOffDisag\n\n\n! This routine was extracted from the aggregateDomain routine above to do simple depth aggregation.\n! There might be a simpler way.\n    subroutine RunoffAggregate(runoff_in, runoff_out, aggfactrt, ix, jx)\n        implicit none\n! Input variables\n        integer, intent(in) :: aggfactrt, ix, jx\n        real, intent(in), dimension(:,:) :: runoff_in\n        real, intent(inout), dimension(:,:) :: runoff_out\n! Local variables\n        integer :: i, j, aggfacyrt, aggfacxrt, ixxrt, jyyrt\n        real :: runoffagg\n        do j=1,jx\n            do i=1,ix\n                runoffagg = 0.\n                do aggfacyrt=aggfactrt-1,0,-1\n                    do aggfacxrt=aggfactrt-1,0,-1\n                        ixxrt = i * aggfactrt - aggfacxrt\n                        jyyrt = j * aggfactrt - aggfacyrt\n#ifdef MPP_LAND\n                        if(left_id.ge.0) ixxrt = ixxrt+1\n                        if(down_id.ge.0) jyyrt = jyyrt+1\n#endif\n                        runoffagg = runoffagg + runoff_in(ixxrt,jyyrt)\n                    end do\n                end do\n                runoff_out(i,j) = runoffagg / (aggfactrt**2)\n            end do\n        end do\n    end subroutine RunoffAggregate\n\n    subroutine HYDRO_ini(ntime, did,ix0,jx0, vegtyp,soltyp)\n        implicit none\n        integer ntime, did\n        integer rst_out, ix,jx\n!        integer, OPTIONAL:: ix0,jx0\n        integer:: ix0,jx0\n        integer, dimension(ix0,jx0),optional :: vegtyp, soltyp\n        integer            :: iret, ncid, ascIndId\n\n\n\n! read the namelist\n! the lsm namelist will be read by rtland sequentially again.\n!call read_rt_nlst(nlst(did) )\n\n! Some field of this structure are already initialized by the CPL component (e.g. DT)\n        call orchestrator%config%init_nlst(did)\n\n        if(nlst(did)%rtFlag .eq. 0) return\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n! get the dimension\n        call get_file_dimension(trim(nlst(did)%geo_static_flnm), ix,jx)\n\n\n#ifdef MPP_LAND\n\n        if (nlst(did)%sys_cpl .eq. 1 .or. nlst(did)%sys_cpl .eq. 4) then\n!sys_cpl: 1-- coupling with HRLDAS but running offline lsm;\n!         2-- coupling with WRF but do not run offline lsm\n!         3-- coupling with LIS and do not run offline lsm\n!         4:  coupling with CLM\n\n! create 2 dimensiaon logical mapping of the CPUs for coupling with CLM or HRLDAS.\n            call log_map2d()\n\n            global_nx = ix  ! get from land model\n            global_ny = jx  ! get from land model\n\n            call mpp_land_bcast_int1(global_nx)\n            call mpp_land_bcast_int1(global_ny)\n\n!!! temp set global_nx to ix\n            rt_domain(did)%ix = global_nx\n            rt_domain(did)%jx = global_ny\n\n! over write the ix and jx\n            call MPP_LAND_PAR_INI(1,rt_domain(did)%ix,rt_domain(did)%jx,&\n                nlst(did)%AGGFACTRT)\n        else\n!  coupled with WRF, LIS\n            numprocs = node_info(1,1)\n\n            call wrf_LAND_set_INIT(node_info,numprocs,nlst(did)%AGGFACTRT)\n\n            rt_domain(did)%ix = local_nx\n            rt_domain(did)%jx = local_ny\n        endif\n\n\n        rt_domain(did)%g_IXRT=global_rt_nx\n        rt_domain(did)%g_JXRT=global_rt_ny\n        rt_domain(did)%ixrt = local_rt_nx\n        rt_domain(did)%jxrt = local_rt_ny\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        write(6,*) \"rt_domain(did)%g_IXRT, rt_domain(did)%g_JXRT, rt_domain(did)%ixrt, rt_domain(did)%jxrt\"\n        write(6,*)  rt_domain(did)%g_IXRT, rt_domain(did)%g_JXRT, rt_domain(did)%ixrt, rt_domain(did)%jxrt\n        write(6,*) \"rt_domain(did)%ix, rt_domain(did)%jx \"\n        write(6,*) rt_domain(did)%ix, rt_domain(did)%jx\n        write(6,*) \"global_nx, global_ny, local_nx, local_ny\"\n        write(6,*) global_nx, global_ny, local_nx, local_ny\n#else\n        write(78,*) \"rt_domain(did)%g_IXRT, rt_domain(did)%g_JXRT, rt_domain(did)%ixrt, rt_domain(did)%jxrt\"\n        write(78,*)  rt_domain(did)%g_IXRT, rt_domain(did)%g_JXRT, rt_domain(did)%ixrt, rt_domain(did)%jxrt\n        write(78,*) \"rt_domain(did)%ix, rt_domain(did)%jx \"\n        write(78,*) rt_domain(did)%ix, rt_domain(did)%jx\n        write(78,*) \"global_nx, global_ny, local_nx, local_ny\"\n        write(78,*) global_nx, global_ny, local_nx, local_ny\n#endif\n#endif\n#else\n! sequential\n        rt_domain(did)%ix = ix\n        rt_domain(did)%jx = jx\n        rt_domain(did)%ixrt = ix*nlst(did)%AGGFACTRT\n        rt_domain(did)%jxrt = jx*nlst(did)%AGGFACTRT\n#endif\n\n\n!      allocate rt arrays\n\n\n        call getChanDim(did)\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        write(6,*) \"finish getChanDim \"\n#else\n        write(78,*) \"finish getChanDim \"\n#endif\n#endif\n\n! ADCHANGE: get global attributes\n! need to set these after getChanDim since it allocates rt_domain vals to 0\n        call get_file_globalatts(trim(nlst(did)%geo_static_flnm), &\n            rt_domain(did)%iswater, rt_domain(did)%islake, rt_domain(did)%isurban, rt_domain(did)%isoilwater)\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        write(6,*) \"hydro_ini: rt_domain(did)%iswater, rt_domain(did)%islake, rt_domain(did)%isurban, rt_domain(did)%isoilwater\"\n        write(6,*) rt_domain(did)%iswater, rt_domain(did)%islake, rt_domain(did)%isurban, rt_domain(did)%isoilwater\n#endif\n#endif\n\n        if(nlst(did)%GWBASESWCRT .eq. 3 ) then\n            call gw2d_allocate(did,&\n                rt_domain(did)%ixrt,&\n                rt_domain(did)%jxrt,&\n                nlst(did)%nsoil)\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n            write(6,*) \"finish gw2d_allocate\"\n#else\n            write(78,*) \"finish gw2d_allocate\"\n#endif\n#endif\n        endif\n\n! calculate the distance between grids for routing.\n! decompose the land parameter/data\n\n\n!      ix0= rt_domain(did)%ix\n!      jx0= rt_domain(did)%jx\n        if(nlst(did)%channel_only .eq. 0 .and. nlst(did)%channelBucket_only .eq. 0) then\n            if(present(vegtyp)) then\n                call lsm_input(did,ix0=ix0,jx0=jx0,vegtyp0=vegtyp,soltyp0=soltyp)\n            else\n                call lsm_input(did,ix0=ix0,jx0=jx0)\n            endif\n        endif\n\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        write(6,*) \"finish decomposion\"\n#else\n        write(78,*) \"finish decomposion\"\n#endif\n#endif\n\n        if((nlst(did)%channel_only .eq. 1 .or. nlst(did)%channelBucket_only .eq. 1) .and. &\n            nlst(1)%io_form_outputs .ne. 0) then\n!! This is the \"decoder ring\" for reading channel-only forcing from io_form_outputs=1,2 CHRTOUT files.\n!! Only needed on io_id\n            if(my_id .eq. io_id) then\n                allocate(rt_domain(did)%ascendIndex(rt_domain(did)%gnlinksl))\n                iret = nf90_open(trim(nlst(1)%route_link_f),NF90_NOWRITE,ncid=ncid)\n!if(iret .ne. 0) call hdyro_stop\n                if(iret .ne. 0) call hydro_stop('ERROR: Unable to open RouteLink file for index extraction')\n                iret = nf90_inq_varid(ncid,'ascendingIndex',ascIndId)\n                if(iret .ne. 0) call hydro_stop('ERROR: Unable to find ascendingIndex from RouteLink file.')\n                iret = nf90_get_var(ncid,ascIndId,rt_domain(did)%ascendIndex)\n                if(iret .ne. 0) call hydro_stop('ERROR: Unable to extract ascendingIndex from RouteLink file.')\n                iret = nf90_close(ncid)\n                if(iret .ne. 0) call hydro_stop('ERROR: Unable to close RouteLink file.')\n            else\n                allocate(rt_domain(did)%ascendIndex(1))\n                rt_domain(did)%ascendIndex(1)=-9\n            endif\n        endif\n\n\n        call get_dist_lsm(did) !! always needed (channel_only and channelBucket_only)\n        if(nlst(did)%channel_only .ne. 1)  call get_dist_lrt(did) !! needed forchannelBucket_only\n\n! rt model initilization\n        call LandRT_ini(did)\n\n        if(nlst(did)%GWBASESWCRT .eq. 3 ) then\n\n            call gw2d_ini(did,&\n                nlst(did)%dt,&\n                nlst(did)%dxrt0)\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n            write(6,*) \"finish gw2d_ini\"\n#else\n            write(78,*) \"finish gw2d_ini\"\n#endif\n#endif\n        endif\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        write(6,*) \"finish LandRT_ini\"\n#else\n        write(78,*) \"finish LandRT_ini\"\n#endif\n#endif\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n        if(nlst(did)%channel_only .eq. 0 .and. nlst(did)%channelBucket_only .eq. 0) then\n\n            if (nlst(did)%TERADJ_SOLAR.eq.1 .and. nlst(did)%CHANRTSWCRT.ne.2) then   ! Perform ter rain adjustment of incoming solar\n#ifdef MPP_LAND\n                call MPP_seq_land_SO8(rt_domain(did)%SO8LD_D,rt_domain(did)%SO8LD_Vmax,&\n                    rt_domain(did)%TERRAIN, rt_domain(did)%dist_lsm,&\n                    rt_domain(did)%ix,rt_domain(did)%jx,global_nx,global_ny)\n#else\n                call seq_land_SO8(rt_domain(did)%SO8LD_D,rt_domain(did)%SO8LD_Vmax,&\n                    rt_domain(did)%TERRAIN,rt_domain(did)%dist_lsm,&\n                    rt_domain(did)%ix,rt_domain(did)%jx)\n#endif\n            endif\n        endif\n\n        if (nlst(did)%GWBASESWCRT .gt. 0) then\n            if(nlst(did)%UDMP_OPT .eq. 1) then\n                call get_basn_area_nhd(rt_domain(did)%basns_area)\n            else\n                call get_basn_area(did)\n            endif\n        endif\n\n        if (nlst(did)%CHANRTSWCRT.eq.1 .or. nlst(did)%CHANRTSWCRT .eq. 2 ) then\n            call get_node_area(did)\n        endif\n\n\n#ifdef WRF_HYDRO_NUDGING\n        if(nlst(did)%CHANRTSWCRT .ne. 0) call init_stream_nudging\n#endif\n\n!#ifdef WRF_HYDRO_DIVERSIONS\n! TODO: should this check to make sure we have nudging on too? [RC]\n        call init_diversions(nlst(did)%diversions_file, nlst(did)%timeSlicePath)\n!#endif\n\n\n!    if (trim(nlst_rt(did)%restart_file) == \"\") then\n! output at the initial time\n!        call HYDRO_out(did)\n!        return\n!    endif\n\n! restart the file\n\n! jummp the initial time output\n!        rt_domain(did)%out_counts = rt_domain(did)%out_counts + 1\n!        rt_domain(did)%his_out_counts = rt_domain(did)%his_out_counts + 1\n\n\n        call HYDRO_rst_in(did)\n!#ifdef HYDRO_REALTIME\n        if (trim(nlst(did)%restart_file) == \"\") then\n            call HYDRO_out(did, 0)\n        else\n            call HYDRO_out(did, 1)\n        endif\n!! JLM: This is only currently part 1/2 of a better accumulation tracking strategy.\n!! The parts:\n!! 1) (this) zero accumulations on restart/init after any t=0 outputs are written.\n!! 2) introduce a variable in the output files which indicates if accumulations are\n!!    reset after this output.\n!! Here we move zeroing to after AFTER outputing the accumulations at the initial time.\n!! This was previously done in HYDRO_rst_in and so output accumulations at time\n!! zero were getting zeroed and then writtent to file, which looses information.\n!! Note that nlst_rt(did)%rstrt_swc is not changed at any point in between here and the rst_in.\n        if(nlst(did)%rstrt_swc.eq.1) then  !Switch for reset of restart accum vars...\n            print *, \"Resetting RESTART Accumulation Variables to 0...\",nlst(did)%rstrt_swc\n! Under channel-only , these first three variables are not allocated.\n            if(allocated(rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake))    rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake = zeroFlt\n            if(allocated(rt_domain(did)%QSTRMVOLRT_ACC))  rt_domain(did)%QSTRMVOLRT_ACC   = zeroFlt\n! These variables are optionally allocated, if their output is requested.\n            if(allocated(rt_domain(did)%accSfcLatRunoff)) rt_domain(did)%accSfcLatRunoff = zeroDbl\n            if(allocated(rt_domain(did)%accBucket))       rt_domain(did)%accBucket    = zeroDbl\n        end if\n\n    end subroutine HYDRO_ini\n\n    subroutine lsm_input(did,ix0,jx0,vegtyp0,soltyp0)\n        implicit none\n        integer did, leng, ncid, ierr_flg\n        parameter(leng=100)\n        integer :: i,j, nn\n        integer, allocatable, dimension(:,:) :: soltyp\n        real, dimension(leng) :: xdum1, MAXSMC,refsmc,wltsmc\n\n        integer :: ix0,jx0\n        integer, dimension(ix0,jx0),OPTIONAL :: vegtyp0, soltyp0\n        integer :: iret, istmp\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n        write(6,*) RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx\n#else\n        write(78,*) RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx\n#endif\n#endif\n\n        allocate(soltyp(RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx) )\n\n        soltyp = 0\n        call get2d_lsm_soltyp(soltyp,RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx,trim(nlst(did)%geo_static_flnm))\n\n\n        call get2d_lsm_real(\"HGT\",RT_DOMAIN(did)%TERRAIN,RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx,trim(nlst(did)%geo_static_flnm))\n\n        call get2d_lsm_real(\"XLAT\",RT_DOMAIN(did)%lat_lsm,RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx,trim(nlst(did)%geo_static_flnm))\n        call get2d_lsm_real(\"XLONG\",RT_DOMAIN(did)%lon_lsm,RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx,trim(nlst(did)%geo_static_flnm))\n        call get2d_lsm_vegtyp(RT_DOMAIN(did)%VEGTYP,RT_DOMAIN(did)%ix,RT_DOMAIN(did)%jx,trim(nlst(did)%geo_static_flnm))\n\n\n        if(nlst(did)%sys_cpl .eq. 2 ) then\n! coupling with WRF\n            if(present(soltyp0) ) then\n                where(VEGTYP0 == rt_domain(did)%iswater .or. VEGTYP0 == rt_domain(did)%islake) soltyp0 = rt_domain(did)%isoilwater\n                where(soltyp0 == rt_domain(did)%isoilwater) VEGTYP0 = rt_domain(did)%iswater\n                soltyp = soltyp0\n                RT_DOMAIN(did)%VEGTYP = VEGTYP0\n            endif\n        endif\n\n        where(RT_DOMAIN(did)%VEGTYP == rt_domain(did)%iswater .or. RT_DOMAIN(did)%VEGTYP == rt_domain(did)%islake) soltyp = rt_domain(did)%isoilwater\n        where(soltyp == rt_domain(did)%isoilwater) RT_DOMAIN(did)%VEGTYP = rt_domain(did)%iswater\n\n! LKSAT,\n! temporary set\n        RT_DOMAIN(did)%SMCRTCHK = 0\n        RT_DOMAIN(did)%SMCAGGRT = 0\n        RT_DOMAIN(did)%STCAGGRT = 0\n        RT_DOMAIN(did)%SH2OAGGRT = 0\n\n\n        rt_domain(did)%subsurface%properties%zsoil(1:nlst(did)%nsoil) = nlst(did)%zsoil8(1:nlst(did)%nsoil)\n\n        rt_domain(did)%subsurface%properties%sldpth(1) = abs( RT_DOMAIN(did)%subsurface%properties%zsoil(1) )\n        do i = 2, nlst(did)%nsoil\n            rt_domain(did)%subsurface%properties%sldpth(i) = RT_DOMAIN(did)%subsurface%properties%zsoil(i-1)-RT_DOMAIN(did)%subsurface%properties%zsoil(i)\n        enddo\n        rt_domain(did)%subsurface%properties%soldeprt = -1.0*RT_DOMAIN(did)%subsurface%properties%zsoil(nlst(did)%NSOIL)\n\n        ierr_flg = 99\n        if(trim(nlst(did)%hydrotbl_f) == \"\") then\n            call hydro_stop(\"FATAL ERROR: hydrotbl_f is empty. Please input a netcdf file. \")\n        endif\n\n#ifdef MPP_LAND\n        if(my_id .eq. IO_id) then\n#endif\n            ierr_flg = nf90_open(trim(nlst(did)%hydrotbl_f), nf90_NOWRITE, ncid)\n#ifdef MPP_LAND\n        endif\n        call mpp_land_bcast_int1(ierr_flg)\n#endif\n        if( ierr_flg .ne. 0) then\n! input from HYDRO.tbl FILE\n!      input OV_ROUGH from OVROUGH.TBL\n#ifdef MPP_LAND\n            if(my_id .eq. IO_id) then\n#endif\n\n#ifndef NCEP_WCOSS\n                open(71,file=\"HYDRO.TBL\", form=\"formatted\")\n!read OV_ROUGH first\n                read(71,*) nn\n                read(71,*)\n                do i = 1, nn\n                    read(71,*) RT_DOMAIN(did)%OV_ROUGH(i)\n                end do\n!read parameter for LKSAT\n                read(71,*) nn\n                read(71,*)\n                do i = 1, nn\n                    read(71,*) xdum1(i), MAXSMC(i),refsmc(i),wltsmc(i)\n                end do\n                close(71)\n#else\n                open(13, form=\"formatted\")\n!read OV_ROUGH first\n                read(13,*) nn\n                read(13,*)\n                do i = 1, nn\n                    read(13,*) RT_DOMAIN(did)%OV_ROUGH(i)\n                end do\n!read parameter for LKSAT\n                read(13,*) nn\n                read(13,*)\n                do i = 1, nn\n                    read(13,*) xdum1(i), MAXSMC(i),refsmc(i),wltsmc(i)\n                end do\n                close(13)\n#endif\n\n#ifdef MPP_LAND\n            endif\n            call mpp_land_bcast_real(leng,RT_DOMAIN(did)%OV_ROUGH)\n            call mpp_land_bcast_real(leng,xdum1)\n            call mpp_land_bcast_real(leng,MAXSMC)\n            call mpp_land_bcast_real(leng,refsmc)\n            call mpp_land_bcast_real(leng,wltsmc)\n#endif\n\n            rt_domain(did)%lksat = 0.0\n            do j = 1, RT_DOMAIN(did)%jx\n                do i = 1, RT_DOMAIN(did)%ix\n!yw rt_domain(did)%lksat(i,j) = xdum1(soltyp(i,j) ) * 1000.0\n                    rt_domain(did)%lksat(i,j) = xdum1(soltyp(i,j) )\n                    rt_domain(did)%SMCMAX1(i,j) = MAXSMC(soltyp(I,J))\n                    rt_domain(did)%SMCREF1(i,j) = refsmc(soltyp(I,J))\n                    rt_domain(did)%SMCWLT1(i,j) = wltsmc(soltyp(I,J))\n!ADCHANGE: Add some sanity checks in case calibration knocks the order of these out of sequence.\n!The min diffs were pulled from the existing HYDRO.TBL defaults.\n!Currently water is 0, so enforcing 0 as the absolute min.\n                    rt_domain(did)%SMCMAX1(i,j) = min(rt_domain(did)%SMCMAX1(i,j), 1.0)\n                    rt_domain(did)%SMCREF1(i,j) = max(min(rt_domain(did)%SMCREF1(i,j), rt_domain(did)%SMCMAX1(i,j) - 0.01), 0.0)\n                    rt_domain(did)%SMCWLT1(i,j) = max(min(rt_domain(did)%SMCWLT1(i,j), rt_domain(did)%SMCREF1(i,j) - 0.01), 0.0)\n                    IF(rt_domain(did)%VEGTYP(i,j) > 0 ) THEN   ! created 2d ov_rough\n                        rt_domain(did)%OV_ROUGH2d(i,j) = RT_DOMAIN(did)%OV_ROUGH(rt_domain(did)%VEGTYP(I,J))\n                    endif\n                end do\n            end do\n\n            call hdtbl_out(did)\n        else\n! input from HYDRO.TBL.nc file\n            print*, \"reading from hydrotbl_f(HYDRO.TBL.nc)  file ....\"\n            call hdtbl_in_nc(did)\n            if (noah_lsm%imperv_option .eq. 9) then\n!ADCHANGE: For consistency, mirror urban and param value checks used in table read\n                where (rt_domain(did)%VEGTYP == rt_domain(did)%isurban)\n                    rt_domain(did)%SMCMAX1 = 0.45\n                    rt_domain(did)%SMCREF1 = 0.42\n                    rt_domain(did)%SMCWLT1 = 0.40\n                endwhere\n            endif\n            where (rt_domain(did)%SMCMAX1 .gt. 1.0) rt_domain(did)%SMCMAX1 = 1.0\n            rt_domain(did)%SMCREF1 = max(min(rt_domain(did)%SMCREF1, rt_domain(did)%SMCMAX1 - 0.01), 0.0)\n            rt_domain(did)%SMCWLT1 = max(min(rt_domain(did)%SMCWLT1, rt_domain(did)%SMCREF1 - 0.01), 0.0)\n        endif\n\n        rt_domain(did)%soiltyp = soltyp\n\n        if(allocated(soltyp)) deallocate(soltyp)\n    end subroutine lsm_input\n\n    subroutine HYDRO_finish()\n#ifdef MPP_LAND\n        use module_mpp_land\n#endif\n#ifdef WRF_HYDRO_NUDGING\n        use module_stream_nudging,  only: finish_stream_nudging\n#endif\n\n        integer :: ierr\n\n#ifdef WRF_HYDRO_NUDGING\n        call finish_stream_nudging()\n#endif\n#ifndef NCEP_WCOSS\n        print*, \"The model finished successfully.......\"\n#else\n        write(78,*) \"The model finished successfully.......\"\n#endif\n#ifdef MPP_LAND\n#ifndef NCEP_WCOSS\n        call flush(6)\n#else\n        call flush(78)\n        close(78)\n#endif\n        call mpp_land_sync()\n        call MPI_Finalize(ierr)\n        stop\n#else\n\n#ifndef WRF_HYDRO_NUDGING\n        stop  !!JLM want to time at the top NoahMP level.\n#endif\n\n#endif\n        return\n    end subroutine HYDRO_finish\n\nend module module_HYDRO_drv\n"
  },
  {
    "path": "src/IO/CMakeLists.txt",
    "content": "# build the orchestrator static library\nadd_library(hydro_netcdf_layer STATIC\n        netcdf_layer.F90\n)\n\ntarget_link_libraries(hydro_netcdf_layer\n        PUBLIC\n        MPI::MPI_Fortran\n        netCDF::netcdff\n)\n"
  },
  {
    "path": "src/IO/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nOBJS = \\\n\tnetcdf_layer.o\nall:\t$(OBJS)\n\n.F90.o:\n\t@echo \"\"\n# $(CPP) $(CPPFLAGS) -I$(NETCDFINC) $(*).F > $(*).f\n#\t$(COMPILER90) -o $(@) $(F90FLAGS) $(MODFLAG) -I../mod $(*).f\n\t$(COMPILER90) -o $(@) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) -I../mod $(*).F90\n#\t$(RMD) $(*).f\n\t@echo \"\"\n\tar -r ../lib/libHYDRO.a $(@)\n\tcp *.mod ../mod\n\n#\n# Dependencies:\n#\n#module_HYDRO_drv.o: ../Data_Rec/module_namelist.o ../Data_Rec/module_RT_data.o ../Data_Rec/module_gw_gw2d_data.o \\\n#         ../Routing/module_GW_baseflow.o ../Routing/module_HYDRO_utils.o ../Routing/module_HYDRO_io.o ../Routing/module_RT.o\n\nclean:\n\trm -f *.o *.mod *.stb *~ *.f\n"
  },
  {
    "path": "src/IO/netcdf_layer.F90",
    "content": "module netcdf_layer_base\n  use netcdf\n  use mpi\n  implicit none\n\n  type, abstract :: NetCDF_layer_\n     procedure (nf90_open), pointer, nopass :: open_file    ! => nf90_open\n     procedure (nf90_def_dim), pointer, nopass :: def_dim !=> nf90_def_dim\n     procedure (nf90_inq_varid), pointer, nopass :: inq_varid !=> nf90_inq_varid\n     procedure (nf90_close), pointer, nopass :: close_file !=> nf90_close\n\n     procedure (integer), pointer, nopass :: put_var !=> nf_put_var\n     procedure (integer), pointer, nopass :: get_var !=> nf_get_var\n     procedure (integer), pointer, nopass :: put_att !=> nf_put_att\n     procedure (integer), pointer, nopass :: def_var !=> nf_def_var\n   contains\n     procedure (create_file_signature), pass(object), deferred :: create_file\n  end type NetCDF_layer_\n\n  integer, external :: nf_put_att\n  integer, external :: nf_def_var\n  integer, external :: nf_put_var\n  integer, external :: nf_get_var\n\n  abstract interface\n\n     function create_file_signature(object, path, cmode, initialsize, chunksize, ncid) result(res)\n       import NetCDF_layer_\n       class(NetCDF_layer_), intent(in   ) :: object\n       character (len = *), intent(in   ) :: path\n       integer,             intent(in   ) :: cmode\n       integer, optional,   intent(in   ) :: initialsize\n       integer, optional,   intent(inout) :: chunksize\n       integer,             intent(  out) :: ncid\n       integer                            :: res\n     end function create_file_signature\n\n  end interface\n\n  type, extends(NetCDF_layer_) :: NetCDF_serial_\n   contains\n     procedure, pass(object) :: create_file => create_file_serial\n  end type NetCDF_serial_\n\n  type, extends(NetCDF_layer_) :: NetCDF_parallel_\n     integer :: MPI_Communicator\n     integer :: default_info = MPI_INFO_NULL\n   contains\n     procedure, pass(object) :: create_file => create_file_parallel\n  end type NetCDF_parallel_\n\ncontains\n\n  function create_file_serial (object, path, cmode, initialsize, chunksize, ncid) result(res)\n    class(NetCDF_serial_),  intent(in) :: object\n    character (len = *), intent(in   ) :: path\n    integer,             intent(in   ) :: cmode\n    integer, optional,   intent(in   ) :: initialsize\n    integer, optional,   intent(inout) :: chunksize\n    integer,             intent(  out) :: ncid\n    integer                            :: res\n\n    res = nf90_create(path = path, cmode = cmode, ncid = ncid)\n\n  end function create_file_serial\n\n  function create_file_parallel(object, path, cmode, initialsize, chunksize, ncid) result(res)\n    class(NetCDF_parallel_),intent(in) :: object\n    character (len = *), intent(in   ) :: path\n    integer,             intent(in   ) :: cmode\n    integer, optional,   intent(in   ) :: initialsize\n    integer, optional,   intent(inout) :: chunksize\n    integer,             intent(  out) :: ncid\n    integer                            :: res\n\n    res = nf90_create(path = path, cmode = cmode, ncid = ncid, &\n         &  comm = object%mpi_communicator, info = object%default_info)\n\n  end function create_file_parallel\n\nend module netcdf_layer_base\n"
  },
  {
    "path": "src/Land_models/Noah/CHANGES",
    "content": "2007-06-05:\n   * Utility_programs/gribextract.c\n       - Print warnings to stderr (not stdout).\n\n2007-06-06\n   * Utility_programs/hrldas_extract_point.F\n       - New program to print out data at a given point\n   * Utility_programs/Makefile\n       - Added a basic make capability for all the utility programs\n\n2007-06-07\n   * HRLDAS_COLLECT_DATA/consolidate_grib.F\n   * HRLDAS_COLLECT_DATA/lib/rif_module.F\n       - Code clean-up\n       - Passed information regarding soil layers of GRIB data to\n         the NetCDF LDASIN file.\n\n2007-06-08\n   * HRLDAS_COLLECT_DATA:\n       - Code clean-up:  removed dead code; removed dead source\n         code files; removed duplicate subroutines; consistent use \n         of error_handler routine for NetCDF error flags;  removed \n         references to wrfsi static files (replaced with references \n         to geo_em files where appropriate).\n\n2007-06-11\n   * HRLDAS_COLLECT_DATA:\n\n       - Modified consolidate_grib to fill in the VEGFRA field over\n         water points with a smooth extrapolation.  This will allow\n         use of LDASIN files generated with either USGS or MODIS\n         land-use fields to be used in an HRLDAS job using either USGS\n         or MODIS land-use fields, with only minor differences at\n         points where one dataset has water and the other has land.\n\n         This also involves reading the ISWATER flag so\n         consolidate_grib knows where the water is.\n\n2007-06-14\n   * IO_code/Noah_hrldas_driver.F\n       - Corrected a problem adjusting LW radiation by emissivity,\n         which was being performed before emissivity was calculated.\n\n   * IO_code/Noah_hrldas_driver.F\n       - In the case of UCM, reset vegtyp before the call to HRLDAS,\n         so that REDPRM does not get confused by the additional urban \n         categories.  This is already done before SFLX, but we need\n         to do it before REDPRM as well.\n\n   * IO_code/Noah_hrldas_driver.F IO_code/module_hrldas_netcdf_io.F\n       - Restart files now written in NetCDF format.   The code for\n         reading (not writing) the old-formatted files is still there,\n         just not activated (it's ifdef'd out).  If somebody really \n         wants to try to read the old files, they can try activating\n         the old code, but I don't want to support this.\n\n       - Added an error-handler routine for the NetCDF error flags.\n         Not used consistently yet, but it's a start.\n\n   * Run/MODI.TBL \n\n     - Added commas to one of the columns that was missing commas.  No\n       functionality changes, but now consistent with the rest of the \n       table.\n\n     - Modified the Wooded Tundra and Mixed Tundra LAI values.  What was\n       originally in the MODI.TBL was a random guess, but I found some\n       data tables from Max Planck Institute reports and a FUMAPEX\n       report, which were pretty consistent with one another.  \"Wooded\n       Tundra\" and \"Barren Tundra\" were in those tables.  I changed\n       the wooded tundra values to be similar to those reports, and\n       mixed tundra to be about halfway between the reported barren\n       tundra and wooded tundra values.\n\n       Those are the only categories that I've had the chance to\n       find numbers based on something other than a guess.\n\n       These tables continue to be provisionary, until we can come\n       to some consensus as to reasonable values for all categories.\n       \n2007-06-15\n   * Utility_programs/hrldas_extract_point.F\n       - Corrected the no-data flag for longitude input from -1.25 to -1.E25.\n       - Slightly saner printout\n\n2007-06-20\n   * HRLDAS_COLLECT_DATA/consolidate_grib.F\n   * HRLDAS_COLLECT_DATA/module_geo_em.F \n   * HRLDAS_COLLECT_DATA/module_wrfinputfile.F \n   * HRLDAS_COLLECT_DATA/read_wrfinput.F \n\n      - Check for consistency in landuse dataset (USGS or MODIS) between\n        geo_em files and wrfinput files, in program consolidate_grib.\n\n   * HRLDAS_COLLECT_DATA/consolidate_grib.F\n   * IO_code/module_hrldas_netcdf_io.F\n   * IO_code/Noah_hrldas_driver.F\n\n      - Make a global attribute \"TITLE\" in all our NetCDF files so that\n        in the future we can check on version consistency between\n        consolidate_grib.exe and Noah_hrldas_beta and restarts.\n\n        All I have to do is remember to update the version identifiers\n        at the appropriate release time.\n\n2007-06-21\n   * HRLDAS_COLLECT_DATA/consolidate_grib.F\n   * IO_code/Noah_hrldas_driver.F\n   * IO_code/module_hrldas_netcdf_io.F\n\n      - added MMINLU attribute to all NetCDF output files, \n        presently for the user's edification, but eventually\n        we can make consistency checks as necessary.\n\n      - Pull the version number out of LDASIN files.\n\n      - A little cleanup (using error_handler routine) for module_hrldas_netcdf_io.F\n\n2007-06-22\n\n   * Shifted over to a subversion (SVN) repository.\n\n2007-07-06\n\n   * IO_code/module_hrldas_netcdf_io.F\n       - Read the right variable names on restart with urban option.\n\n   * IO_code/Noah_hrldas_driver.F\n   * HRLDAS_COLLECT_DATA/consolidate_grib.F\n      - Identify output files as coming from version \"v20070706\".\n\n2007-07-12\n\n  * IO_code/module_hrldas_netcdf_io.F\n       - There was a problem with RESTART files created for Urban Canopy Model\n         jobs.  One of the fields was not being written out, and a few other\n         2-d fields were identified as 3-d fields.  Correct this, and put in \n         some version checks to prevent users from trying to use old, wrong\n         RESTART files.\n\n   * IO_code/Noah_hrldas_driver.F, HRLDAS_COLLECT_DATA/consolidate_grib.F\n      - Identify output files as coming from version \"v20070712\".\n\n\n2007-07-13\n\n  * IO_code/module_hrldas_netcdf_io.F\n       - Purely a cosmetic change.  Use a dummy array when converting CMC from\n         m to mm upon output.  This was motivated to clear warning messages \n         from the ifort-compiled code.  Again, no change in results, purely \n         cosmetic.\n\n  * IO_code/Noah_hrldas_driver.F\n       - Pass ISURBAN into subroutine urban_var_init, so that the reference to \n         hard-coded urban category 1 can be replaced by reference to ISURBAN.\n\n  * Noah/module_sf_urban.F\n       - Add ISURBAN to the argument list of urban_var_init.  Changed a hard-coded\n         reference to urban category 1 to ISURBAN.\n\n   * IO_code/Noah_hrldas_driver.F, HRLDAS_COLLECT_DATA/consolidate_grib.F\n      - Identify code and output files as version \"v20070713\".\n\n2007-07-13 (b)\n\n   * IO_code/Noah_hrldas_driver.F\n        - Change the printout if the default output point happens to be over \n          water.  In this situation, do not try to print out a sample soil \n          temperature value\n\n2007-07-24\n\n   *  Utility_programs/modify_wrfinput.F\n   \t- Changed Roof, Wall and Road temperatures (TR, TB, TG)\n\t  consistent with the WRF Registry.EM.\n\n\n2007-08-17\n   * HRLDAS_COLLECT_DATA/module_geo_em.F\n        - Slightly more informative and consistent error messages \n          for NetCDF attribute reads.\n\n2007-08-23\n   * HRLDAS_COLLECT_DATA/lib/gribcode.F\n        - Change some print statements to write statements\n        - Prevent a call to gbytes requesting 0 bytes of data.\n\n   * IO_code/Noah_hrldas_driver.F IO_code/module_hrldas_netcdf_io.F\n     Noah/module_sf_noahlsm.F Utility_routines/module_Noahlsm_utility.F\n        - HRLDAS using first (pre-)release of \"unified\" noahlsm.\n\n2007-09-13\n   * HRLDAS_COLLECT_DATA/consolidate_grib.F\n        - Added a nearest-neighbor interpolation for precip (subroutine call \n          commented out for now, but available for single point usage).\n\n2007-09-13\n   * IO_code/Noah_hrldas_driver.F\n        - Commented out some code that has no effect.\n\n...\nAnd lots of changes thereafter.  See svn logs for details.\n...\n\n2008-03-21\n   * Noah/module_sf_noahlsm.F\n        - Updated to latest module_sf_noahlsm.F, which takes a background \n\t  emissivity value and applies snow-cover effects to compute an\n          emissivity value.\n   * IO_code/Noah_hrldas_driver.F\n        - Use the latest module_sf_noahlsm.F code, which takes a background \n\t  emissivity value and applies snow-cover effects to compute an\n          emissivity value.\n\n2008-03-21.b\n   * Noah/module_sf_noahlsm.F\n        - Added code (from NCEP) to alleviate the 2 delta-t problem\n          we've seen with shallow layers when we get heavy precipitation \n          and wet soil layers.  This is currently dangerously broken code, \n          as it basically hard-wires table lookup values based on magic \n          values for SMCMAX.  But it's what we've got at the moment.\n\n2008-03-25\n   * Noah/module_sf_noahlsm.F\n        - Test the Carlson-Boland exchange coefficient calculations from\n          Mukul and Jimy\n\n\n2008-04-10\n   * Noah/module_sf_noahlsm.F\n        - Slight change to the Carlson-Boland calculation introduced\n          on 2008-03-25\n\n2008-04-23\n   * HRLDAS_COLLECT_DATA/consolidate_grib.F\n        - The new PGF compilers had a problem with some statements (a \n          minval and a maxval).  Found an easy workaround.\n\n2008-04-25:\n   * Noah/module_sf_noahlsm.F\n        - Modified a hard-coded dimension [GX(7)] in module_sf_noahlsm.F \n          to be more general [GX(NSOIL)].  Eventually, this (or a similar)\n          change should go into \"official\" Noah LSM.\n\n2008-04-25:\n   * IO_code/Noah_hrldas_driver.F\n   * IO_code/module_hrldas_netcdf_io.F\n   * Run/namelist.hrldas\n         - Introduced the option for timesteps at higher frequency than the\n           forcing data are available.  Temporal interpolation is performed\n           between the available forcing files.  Many changes involved:\n             - Complete overhaul of subroutine READFORC_HRLDAS\n             - Several new subroutines in module_hrldas_netcdf_io.F\n             - Namelist changes -- NOAH_TIMESTEP, FORCING_TIMESTEP, and\n               OUTPUT_TIMESTEP\n             - History filename name changes necessary, because we may have\n               output frequencies greater than one hour\n\n2008-04-25:\n   * Run/namelist.hrldas\n          - Namelist cleanup:  Removed unused \"Z\" from the namelist\n   * IO_code/Noah_hrldas_driver.F\n   * IO_code/module_hrldas_netcdf_io.F\n          - Namelist cleanup\n          - Added some error messages for namelist problems\n          - Check namelist settings for sane values\n          - Set some default values for some namelist variables\n   * Run/README.namelist\n          - Added this text file, some documentation for people wondering\n            about the namelist options.\n\n2008-04-25:\n   * Run/USGS.TBL\n           - Modified some of the MIN/MAX LAI values, making some better \n             guesses, from some suggested values from NCEP.\n\n2008-04-25:\n   * HRLDAS_USERS_GUIDE.pdf\n\t   - Added this file, some documentation for users.\n\n2008-05-07:\n   * Noah/module_sf_noahlsm.F\n           - The experimental code (NCEP's FAC2MIT, and our test of a\n             C/B formulation) are now deactivated by default for\n             HRLDAS.  The code is still there (and can be activated by\n             #defines if a user really wants to try).\n\n   * HRLDAS_COLLECT_DATA/run\n           - Removed files \"collect_data.csh\" and \"namelist.template\",\n             which were set up for special circumstances, but now \n             merely serve to confuse people.\n\n   * HRLDAS_COLLECT_DATA/run/README.namelist\n           - Added some text documentation for the \n             consolidate_grib.exe namelist.input file.\n\n   * HRLDAS_COLLECT_DATA/run/namelist.example.simple\n   * HRLDAS_COLLECT_DATA/run/namelist.example.complex\n           - Added a couple of example namelist files for \n             the consolidate_grib.exe program.\n\n2008-07-02\n   * HRLDAS_COLLECT_DATA/lib/module_grib1.F\n           - Allocatable array IX in GRIB1_SGUP_NOBITMAP was causing some \n             problems on the IBM.  The IBM wanted us to make sure it \n             was deallocated.  But I've changed the array to be a \n             variable-length dummy array, to avoid the explicit \n             allocate/deallocate statements for IX.\n             \n   * HRLDAS_COLLECT_DATA/lib/decode_jpeg2000.c\n           - The IBM had a problem with the Jasper library routine \n             jas_image_decode.  Changed things to use Jasper library routine \n             jpc_decode (and use jas_image_readcmpt instead of \n             jas_image_readcmpt2) to get things working on the IBM.\n\n   * user_build_options\n           - Removed the \"traditional\" option for the IBM CPP compiler.\n           - Changed the default, sample library and include file\n             directory names. \n\n2008-08-21\n\n   * Run/Noah_hrldas_driver.F\n           - In computing SOLNET for input to SFLX, use the albedo as \n             remembered from the previous timestep.\n           - Get rid of the \"ALBED\" variable, no longer used.\n           - Do not set \"ALBEDO\" in Noah_hrldas_driver, because it\n             gets set in SFLX.\n           - Update the version string\n\n   * HRLDAS_COLLECT_DATA/consolidate_grib.F\n           - Update the version string\n\n   * Noah/module_sf_noahlsm.F\n           - Update the code to be consistent with the new \n             WRF release WRFV3.0.1.  The only change of any\n             impact is to set ETP if (ETA==0).\n2008-08-22\n\n   * Noah/module_sf_urban.F\n           - Update to WRFV3.0.1 version (just a couple of comment corrections).\n\n2009-04-30\n\n   - Updating to version 3.1 (consistent with WRF release)\n\n      Noah LSM version 3.1 has a number of changes as compared to version 3.0.       \n      Changes include:                                                               \n                                                                                     \n      -------------------------------------------------------------------------------\n      Capability to use MODIS land-use dataset for vegetation categories.  This      \n      entailed many changes to make the land-use dataset flexible throughout WRF.    \n          * Added \"NATURAL\" category to VEGPARM.TBL, for the land-use category       \n            to use for the non-urban parts of urban points.  Previously hard-coded as\n            category 10 in the Noah driver.                                          \n          * String length for strings describing land-use data sets and soil-category\n            data sets has been increased from 4 characters to 256 characters.  This  \n            allows for more descriptive names for land-use and soil-category data    \n            sets.                                                                    \n          * The ISURBAN argument has been added to SFLX.  ISURBAN holds the index    \n            number for the land-use category corresponding to urban points.  All     \n            checks on the hard-coded USGS urban category 1 have been changed to      \n            test on the value of ISURBAN.  ISURBAN now gets passed around to several \n            subroutines below SFLX.                                                  \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Snow albedo treatment following Livneh.  This is a major modification to       \n      subroutine ALCALC.                                                             \n         * New argument to SFLX:  SNOTIME1 holds the age of the snow on the ground,  \n           in seconds. (In-code documentation still needed for this.)                \n         * Albedo over snow now depends on the age of the snow on the ground.  Ground\n           covered with new, fresh snow may have a high albedo; as the snow ages, the\n           albedo is reduced.                                                        \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Option for 2d LAI map to be used in Noah ....                                  \n         * New argument to SFLX:  RDLAI2D                                            \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      File \"urban_param.tbl\" has been renamed to \"URBPARM.TBL\", to be consistent with\n      the rest of the tables.                                                        \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      BUGFIX:  In subroutine SRT, infiltration calculation takes into account the    \n      time step in setting INFMAX = MIN (INFMAX,PX/DT).  Older code did not have the \n      \"/DX\" term.                                                                    \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Glacial Ice ....  Some fairly significant changes to the treatment, here.      \n         * The meaning of the ICE flag variable in SFLX has been changed.  Now,      \n           the settings are ICE=1 for a sea-ice point, and ICE=-1 for a glacial land \n           point, and ICE=0 for a non-glacial land point.                            \n         * Glacial land points and sea-ice points have smil moisture set to 1.0.     \n           (Both total and liquid values.  Should liquid part be set to 0.0?)        \n         * At glacial land points and seaice points, snow density is set to 0.2      \n           for cold permanent ice or new dry snow.                                   \n         * snow-cover fraction is unlimited over glacial land points.                \n         * Albedo of sea-ice is hard-coded to 0.80; emissivity is hard-coded to      \n           0.98.  This is probably not good.  In reality, the Arctic and the         \n           Antarctic behave quite differently, and each has its own annual trend.    \n         * Thermal conductivity over sea ice or glacial land points is set to the    \n           snow conductivity value.                                                  \n         * Subroutine HRTICE is modified to manage subsurface temperature tendency   \n           for both sea ice and glacial land points.  Diffusivities and heat         \n           capacities are ajusted depending on whether its a glacial point or a      \n           sea-ice point.                                                            \n         * Call to SMFLX is skipped for sea-ice points or glacial land points.       \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Subroutine SNOPAC:  Potential evapotranspiration (ETP) depends on Richardson   \n      Number (RIBB) -- to handle stable regimes a little better.                     \n         * New argument to SFXL:  RIBB (In-code documentation still needed for this) \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Background (i.e., snow-free) albedo, background emissivity, background         \n      roughness-length, and Leaf Area Index are computed in SFLX, by scaling between \n      climatological minimum and maximum values based on land-use category (new      \n      VEGPARM.TBL), according to where an instantaneous green vegetation fraction    \n      falls between a climatological minimum and maximum for GVF.  Values for        \n      background emissivity (EMBRD), Leaf-area index (XLAI), background albedo (ALB),\n      and background roughness length (Z0BRD) are computed in SFLX just after the    \n      call to REDPRM.                                                                \n         * USEMONALB now has to be passed into SFLX.                                 \n         * New arrays defined:  LAIMINTBL, LAIMAXTBL;  Remove LAITBL.                \n         * New arrays defined:  ALBEDOMINTBL, ALBEDOMAXTBL; remove ALBTBL.           \n         * New arrays defined:  Z0MINTBL, Z0MAXTBL; remove Z0TBL                     \n         * New arrays defined:  EMISSMINTBL, EMISSMAXTBL                             \n         * Subroutine REDPRM now returns LAIMIN, LAIMAX, ALBEDOMIN, ALBEDOMAX,       \n           EMISSMIN, EMISSMAX, Z0MIN, Z0MAX, EMISSMIN, EMISSMAX.  Removed from REDPRM\n           are Z0BRD, XLAI, and ALB.                                                 \n         * The scaling is not applied for albedo if namelist option USEMONALB is set \n           to .true.                                                                 \n         * The scaling is not applied for LAI if namelist option RDLAI2D is set to   \n           .true.                                                                    \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Subroutine SFLX:  If the surface is largely snow covered (more than 97%), use  \n      the snow diffusivity. (BPRC)                                                   \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Subroutine PENMAN:                                                             \n      Scale latent heat used between snow-covered (latent heat of sublimation) and   \n      snow-free (latent heat of vaporization) regions.  For glacial land or sea ice  \n      regions, use latent heat of vaporization if Skin temperature T1 is greater than\n      freezing                                                                       \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      BUGFIX:  The code to determine whether the soil-moisture tendency will be      \n      solved with the single-step or the two-step process had some wrong unit        \n      conversions which meant that the two-step process would be used only in        \n      extremely heavy rainfall situations.  New code corrects this.  Also adds the   \n      (FAC2 > FLIMIT) test.                                                          \n         * Subroutine FAC2MIT added, making FLIMIT dependent on hard-coded SMCMAX    \n           values.  If SOILPARM.TBL is changed, this will break FAC2MIT.             \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Limit the depth of the snow layer in computing soil heat flux (BPRC)           \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Over sea-ice points and glacial land points, limit the depth of the snow layer \n      in computing soil heat flux (BPRC)                                             \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Test on some trace value of snow, instead of zero value, for computing snow    \n      density.  This may prevent some crazy values caused by a division by something \n      near to zero. (BPRC) (SNEQV)                                                   \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Subroutine WDFCND:  Computation of FACTR1 modified, and the maximum value for  \n      FACTR1 is limited:  FACTR1 cannot exceed FACTR2.                               \n                --- What are FACTR1 and FACTR2?                                      \n                --- What's a good generic way do describe this change?               \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Runoff updated over non-glacial land points. (RUNOFF3,RUNOFF2 setting in SFLX?)\n      Over glacial land or sea ice, runoff goes directly to surface runoff RUNOFF1.  \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Adjustment in NOPAC of ETA setting if ETP <= 0.                                \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      The \"LOCAL\" variable (for REDPRM settings) no longer used.                     \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      FLX3 initialized to zero in the case of shallow snow which sublimates.         \n      -------------------------------------------------------------------------------\n      -------------------------------------------------------------------------------\n      Subroutine TRANSP:  Dimension for GX no longer hard-coded.                     \n      -------------------------------------------------------------------------------\n\n2010-05-12\n\n     - Updating to version 3.2 (consistent with WRF release)\n\n     -------------------------------------------------------------------------------\n     -------------------------------------------------------------------------------\n     Changes to HRLDAS_COLLECT_DATA:\n\n        * The namelist file name may (optionally) be specified on the\n          command-line to consolidate_grib.exe, rather than always be\n          assumed to be \"namelist.input\".\n\n        * The namelist option \"full_ic_frq\" takes on a new meaning if the\n          user sets the value to -1: The full initial conditions will never\n          be computed.\n\n        * A limit to the solar zenith angle is applied, in an attempt to\n          prevent the subroutine RESCALE_SW_TIME_OFFSET from producing\n          bizarrely high values.\n\n        * A namelist option (logical RESCALE_SHORTWAVE) to turn on and off\n          the subroutine RESCALE_SW_TIME_OFFSET has been introduced.\n\n        * Transitioned to the WRF module_llxy.F map routines.  This allows\n          for a greater variety of map projections, and makes for greater\n          consistency between WRF and HRLDAS map computations.\n\n     -------------------------------------------------------------------------------\n     -------------------------------------------------------------------------------\n\n     Changes to Noah_hrldas_beta:\n\n        * Parallelized:\n\n              - Uses MPICH.\n\n              - Needs to be activated at compile time, in the\n                user_build_options file.\n\n              - Requires NetCDF4 and HDF5 libraries (and dependencies\n                of these libraries) built with the parallel\n                capabilities.  See documentation for these libraries\n                for details: http://www.unidata.ucar.edu/software/netcdf\n                and http://www.hdfgroup.org/HDF5\n\n              - Files are not compatible with pre-NetCDF4 programs and\n                utilities.\n  \n        * Introduce an updated SFCDIF routine, with namelist option SFCDIF_OPTION\n\n              - The routine SFCDIF_OFF had diverged from what was\n                currently being used in WRF.  We went back to WRF,\n                pulled out the MYJSFC SFCDIF subroutine, and adapted\n                this back to HRLDAS.  This routine is now available as\n                subroutine SFCDIF_MYJ, and may be activated by\n                namelist option SFCDIF_OPTION=1.  The original\n                SFCDIF_OFF is still available, selected with\n                SFCDIF_OPTION=0.\n\n        * CZIL choices, with namelist option IZ0TLND\n\n              - New namelist option IZ0TLND.  With IZ0TLND=0, CZIL is a\n                constant, set from the GENPARM.TBL.  With IZ0TLND=1, CZIL\n                is set as a function of the vegetation category's\n                roughness length.\n\n\n        * Specify restart files by name, rather than by date.  This allows\n          for different file names, and for the full path name to be\n          specified in the namelist.  The string \"<LATEST>\" in the requested\n          restart file name will be replaced by the date (YYYYMMDDHH)\n          of the latest available restart file matching the rest of\n          the specified file name.\n\n        * Add OUTDIR namelist option, to direct output (including restart\n          files) the specified directory\n\n        * Add namelist option UPDATE_SNOW_FROM_FORCING to control\n          whether snow is updated from the forcing files during\n          integration.\n\n        * Overhaul of output procedures, allows for easier tuning by\n          the user.  Adding or removing variables from the output\n          files is now simply a matter of adding or removing a small\n          subroutine call for each variable.\n\n        * Added the energy budget residual calculation.  Output as 2d\n          array NOAHRES.\n\n        * Correct frequency for creating the restart files.\n\n     -------------------------------------------------------------------------------\n     -------------------------------------------------------------------------------\n\n     Changes to Noah LSM version 3.2 since version 3.1\n\n        * Z0 for snow cover\n\n            - Roughness length Z0 over snow-covered surfaces has been modified\n              (subroutine SNOWZ0) to account for the accumulation of snow\n              burying the surface features which contribute to roughness.\n\n              An \"effective\" roughness length for the snow-covered surface is\n              computed, Z0EFF.  For deep snow, Z0EFF is set to 0.001 (deep snow\n              covering the roughness features of the surface).  For shallower\n              snow, Z0EFF is set to the snow-free roughness length, Z0BRD,\n              reduced by SNOWH/7.\n\n              To account for fractional snow cover, the final Z0 term is\n              computed as a weighted average between the snow-free Z0BRD value\n              and the effective snow albedo, Z0EFF.\n\n        * LVCOEF:\n\n            - The surface albedo in the presence of snowcover (subroutine\n              ALCALC) is computed following Livneh.  In version 3.2, this has\n              been implemented with a user-definable coefficient, LVCOEF, set\n              in file GENPARM.TBL.  LVCOEF should range between zero and one.\n\n              The Livneh scheme boosts the snow albedo toward 85%, then reduces\n              it according to the age of the snow.  LVCOEF controls how much\n              the albedo is boosted toward 85%.  A default value LVCOEF=0.5\n              will have the same results as in version 3.1, i.e., an average of\n              the input SNOALB (which tends to range from around 50% to around\n              75%) and 85%.  Values lower than 0.5 will tune this more toward\n              the incoming SNOALB (and ultimately lower albedos).  Values\n              greater than 0.5 will tune this more toward 85% (and ultimately\n              higher albedos).\n\n        * SMAV:\n\n            - SMAV: Soil moisture availability at each soil layer, computed as a\n              fraction between the wilting point SMCWLT (SMAV=0.0) and\n              saturation soil moisture SMCMAX (SMAV=1.0).  No effect on model\n              results.  Diagnostic field output in WRF as \"SMCREL: Relative soil\n              moisture\".\n\n        * FLX1:\n\n            - The FLX1 term needs to account for the exchange of heat required\n              to change the temperature of falling precipitation from air\n              temperature to skin temperature.  This exchange is considered in\n              computing fluxes and skin temperature, but for rain events, was\n              not included in the budget term FLX1.  So the energy budget would\n              show large residual values for rain events.  This correction has\n              no effect on the model integration, but will make the budget\n              calculations which use FLX1 more accurate.\n\n        * DTOT:\n\n            - Polar modification: over sea/land ice points, DTOT is limited so\n              as not to effectively shut off heat exchange between soil (i.e.,\n              ice) layers and the surface.  In SNOPAC, this limit was applied\n              regardless of surface type (ice or land).  In Version 3.2, this\n              has been corrected to apply only to sea/land ice points.  Could\n              have some effect on results in areas of deep snow.\n\n        * RC:\n\n            - Canopy Resistance, RC, normally set in the call to subroutine\n              CANRES, is set to zero if CANRES is not called because SHDFAC is\n              0.  This change should have no effect on model integration, but\n              since RC is an output variable, this change insures that the field\n              is initialized where there is no vegetation.\n\n     -------------------------------------------------------------------------------\n     -------------------------------------------------------------------------------\n\n     Changes to Single-Layer Urban Canopy Model for version 3.2\n\n        * Revised URBPARM.TBL:\n\n            - Specification of the morphology of the urban canyon is\n              recast in more physically and geometrically meaningful\n              terms.\n\n        * Replaced subroutine MOS with SFCDIF_URB, derived from the\n          WRF SFCDIF routine.  This entails 4 more 2d arrays for \n\t  CMR, CHR, CMS, CHS, which are updated during integration.\n\n        * Use Akanda approach for ZT.  Adds a coefficient, AKANDA_URBAN,\n          to URBPARM.TBL\n\n        * Other changes (arrays, URBPARM.TBL entries) related to\n          compatibility with other Urban Canopy Models available in\n          WRF, but not directly relavant to the Single-Layer UCM used\n          in HRLDAS.\n\n     -------------------------------------------------------------------------------\n     -------------------------------------------------------------------------------\n\n-------------------------------------------------------------------------------\n2011-04-25\n-------------------------------------------------------------------------------\n\n   * module_sf_noahlsm.F\n\n       - Apply DF1 conductivity change only for permanent land ice, \n         not for both land ice and sea ice.\n\n       - SHDFAC becomes INTENT (INOUT) in subroutine REDPRM, because\n         some compilers can be very disturbed if an INTENT(OUT) variable\n         is not necessarily set in the subroutine.\n\n   * module_model_constants.F\n\n       - update source code to match WRFv3.3 release.\n\n   * Noah_hrldas_driver.F, module_sfcdif_wrf.F, namelist.hrldas\n\n       - Allow for different levels of wind and temperature forcing.\n\n   * module_grib1.F\n\n       - Recognize Time Range Indicator 10, and handle the field\n         encoded in two bytes.\n"
  },
  {
    "path": "src/Land_models/Noah/CMakeLists.txt",
    "content": "add_subdirectory(\"Noah\")\nadd_subdirectory(\"Utility_routines\")\n\n\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/Makefile",
    "content": "SHELL=/bin/sh\n.SUFFIXES:\t\n.SUFFIXES:\t.F .o .exe\nOBJS=\tmodule_plot2d_graphics.o \\\n\tmodule_2ddata.o \\\n\tkwm_date_utilities.o \\\n\tkwm_string_utilities.o \\\n\tllxy_generic.o \\\n\tlccone.o \\\n\tplt2d.o\n\n\n#F90=\tifort\n#FFLAGS=-free\n\nF90=\tpgf90\nFFLAGS=-Mfree \nLIBS2 = -L${PGI}/linux86/5.2/lib -lpgftnrtl -lpgc \n\nRM = \trm -f\nNCARGLIBS=\t-L/usr/local/ncarg/lib -L/usr/X11R6/lib \\\n\t\t-lncarg -lncarg_gks -lncarg_c -lX11 -lXext \\\n\t\t-L/usr/lib/gcc/i386-redhat-linux/3.4.6 -lg2c\n#\t        -L/usr/lib/gcc-lib/i386-linux/3.0.4 -lg2c\n\nCMD=\tplt2d.exe\n\n\n# Lines from here on down should not need to be changed.  They are the\n# actual rules which make uses to build $(CMD).\n#\n\nall:\t$(CMD)\n\n.F.o:\n\t@echo \"\"\n\t$(F90) $(CPPINVOKE) $(CPPFLAGS) -c -I$(NETCDF)/include $(FFLAGS) $(MODDIR) $(*).F\n\n$(CMD):\t$(OBJS)\n\t$(F90) -o $(@) -I$(NETCDF)/include $(FFLAGS) $(OBJS) \\\n\t$(LIBS2) -L$(NETCDF)/lib -lnetcdf $(NCARGLIBS) -L/scholar/kmanning/TESTN4/HDF5/lib -lhdf5_hl -lhdf5 -lz\n\nclean:\n\t$(RM) *.o *~ *.exe *.mod\n#\nmodule_2ddata.o:\tkwm_string_utilities.o\nmodule_plot2d_graphics.o:\tmodule_2ddata.o\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/kwm_date_utilities.F",
    "content": "module kwm_date_utilities\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n!  From old date ('YYYY-MM-DD HH:MM:SS.ffff') and\n!  delta-time, compute the new date.\n\n!  on entry     -  odate  -  the old hdate.\n!                  idt    -  the change in time\n\n!  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n\n!  Local Variables\n\n!  yrold    -  indicates the year associated with \"odate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scold    -  indicates the second associated with \"odate\"\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n\n!  mday     -  a list assigning the number of days in each month\n\n!  i        -  loop counter\n!  nday     -  the integer number of days represented by \"idt\"\n!  nhour    -  the integer number of hours in \"idt\" after taking out\n!              all the whole days\n!  nmin     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days and whole hours.\n!  nsec     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days, whole hours, and whole minutes.\n\n    integer :: nlen, olen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n\n    logical :: punctuated\n    logical :: idtdy, idthr, idtmin, idtsec, idtfrac\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n!  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    olen = len(odate)\n    if (punctuated) then\n       if (olen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n    endif\n\n!  Use internal READ statements to convert the CHARACTER string\n!  date into INTEGER components.\n\n    idtdy   = .FALSE.\n    idthr   = .FALSE.\n    idtmin  = .FALSE.\n    idtsec  = .FALSE.\n    idtfrac = .FALSE.\n    read(odate(1:4),  '(i4)') yrold\n    if (punctuated) then\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.13) then\n          idthr = .TRUE.\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             idtmin = .TRUE.\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                idtsec = .TRUE.\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   idtfrac = .TRUE.\n                   read(odate(21:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    else ! Not punctuated\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.10) then\n          idthr = .TRUE.\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             idtmin = .TRUE.\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                idtsec = .TRUE.\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   idtfrac = .TRUE.\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n!  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n!  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n!  Check that the fractional part  of ODATE makes sense.\n\n!KWM      IF ((scold.GT.59).or.(scold.LT.0)) THEN\n!KWM         WRITE(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n!KWM         opass = .FALSE.\n!KWM      END IF\n\n    if (.not.opass) then\n       write(*,*) 'FATAL ERROR: In kwm_date_utilities.F geth_newdate() - Crazy ODATE: ', odate(1:olen), olen\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n\n!  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (idtfrac) then !idt should be in fractions of seconds\n       if (punctuated) then\n          ifrc = olen-14\n       else\n          ifrc = olen-20\n       endif\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (idtsec) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (idtmin) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (idthr) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (idtdy) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''FATAL ERROR: In kwm_date_utilities.F geth_newdate() - Strange length for ODATE: '', i3)') &\n            olen\n       write(*,*) odate(1:olen)\n       call abort()\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n!  Now construct the new mdate\n\n    nlen = LEN(ndate)\n\n    if (punctuated) then\n\n       if (nlen.gt.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:19)//'.'//hfrc(31-nlen:10)\n\n       else if (nlen.eq.19.or.nlen.eq.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n          if (nlen.eq.20) ndate = ndate(1:19)//'.'\n\n       else if (nlen.eq.16) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (nlen.eq.13) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n       if (olen.ge.11) ndate(11:11) = sp\n\n    else\n\n       if (nlen.gt.20) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:18)//hfrc(31-nlen:10)\n\n       else if (nlen.eq.14) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n14        format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.12) then\n          write(ndate,12) yrnew, monew, dynew, hrnew, minew\n12        format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,210) yrnew, monew, dynew, hrnew\n210       format(i4,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.8) then\n          write(ndate,8) yrnew, monew, dynew\n8         format(i4,i2.2,i2.2)\n\n       else\n          stop \"FATAL ERROR: In kwm_date_utilities.F geth_newdate() - DATELEN PROBLEM\"\n       end if\n    endif\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n    implicit none\n\n!  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n!  compute the time difference.\n\n!  on entry     -  newdate  -  the new hdate.\n!                  olddate  -  the old hdate.\n\n!  on exit      -  idt    -  the change in time.\n!                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n!  Local Variables\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  yrold    -  indicates the year associated with \"odate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n!  scold    -  indicates the second associated with \"odate\"\n!  i        -  loop counter\n!  mday     -  a list assigning the number of days in each month\n\n! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    character (len=24) :: tdate\n    integer :: olen, nlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), i, newdys, olddys\n    logical :: npass, opass\n    integer :: isign\n    integer :: ifrc\n\n    logical :: punctuated\n\n    olen = len(olddate)\n    nlen = len(newdate)\n    if (nlen.ne.olen) then\n       write(*,'(\"FATAL ERROR: In kwm_date_utilities.F geth_idts() - NLEN /= OLEN: \", A, 3x, A)') newdate(1:nlen), olddate(1:olen)\n       call abort\n    endif\n\n    if (olddate.gt.newdate) then\n       isign = -1\n\n       ifrc = olen\n       olen = nlen\n       nlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       isign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n\n!  Break down old and new hdates into parts\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(odate(1:4),  '(i4)') yrold\n    read(ndate(1:4),  '(i4)') yrnew\n\n    if (punctuated) then\n\n!  Break down old hdate into parts\n\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       if (olen.ge.13) then\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   if (olen.eq.21) then\n                      read(odate(21:21),'(i1)') frold\n                   else if (olen.eq.22) then\n                      read(odate(21:22),'(i2)') frold\n                   else if (olen.eq.23) then\n                      read(odate(21:23),'(i3)') frold\n                   else if (olen.eq.24) then\n                      read(odate(21:24),'(i4)') frold\n                   endif\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(6:7),  '(i2)') monew\n       read(ndate(9:10), '(i2)') dynew\n       if (nlen.ge.13) then\n          read(ndate(12:13),'(i2)') hrnew\n          if (nlen.ge.16) then\n             read(ndate(15:16),'(i2)') minew\n             if (nlen.ge.19) then\n                read(ndate(18:19),'(i2)') scnew\n                if (nlen.gt.20) then\n                   read(ndate(21:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    else\n\n!  Break down old hdate into parts\n\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       if (olen.ge.10) then\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(5:6),  '(i2)') monew\n       read(ndate(7:8), '(i2)') dynew\n       if (nlen.ge.10) then\n          read(ndate(9:10),'(i2)') hrnew\n          if (nlen.ge.12) then\n             read(ndate(11:12),'(i2)') minew\n             if (nlen.ge.14) then\n                read(ndate(13:14),'(i2)') scnew\n                if (nlen.ge.15) then\n                   read(ndate(15:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n!  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n       print*, 'GETH_IDTS:  Month of NDATE = ', monew\n       npass = .false.\n    end if\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n       opass = .false.\n    end if\n\n!  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    endif\n\n!  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    end if\n\n!  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n       npass = .false.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n       opass = .false.\n    end if\n\n!  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n       npass = .false.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n       opass = .false.\n    end if\n\n!  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n       npass = .false.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'FATAL ERROR: In kwm_data_utilities.F geth_idts() - Screwy NDATE: ', ndate(1:nlen)\n       call abort()\n    end if\n\n    if (.not. opass) then\n       print*, 'FATAL ERROR: In kwm_data_utilities.F geth_idts() - Screwy ODATE: ', odate(1:olen)\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n!  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n!  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n!  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (punctuated) then\n       if (olen.gt.10) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.13) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.16) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.20) then\n                   ifrc = olen-20\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    else\n       if (olen.gt.8) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.10) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.12) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.14) then\n                   ifrc = olen-14\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    endif\n\n    if (isign .eq. -1) then\n       idt = idt * isign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n!\n! Compute the number of days in February for the given year.\n!\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n!\n! Compute the number of days in the month of given date hdate.\n!\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    if (hdate(5:5) == \"-\") then\n       read(hdate(1:7), '(I4,1x,I2)') year, month\n    else\n       read(hdate(1:6), '(I4,I2)') year, month\n    endif\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\nend module kwm_date_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/kwm_string_utilities.F",
    "content": "module kwm_string_utilities\n\ncontains\n\n  subroutine strrep(string, rep1, rep2)\n    ! In string 1, replace expression rep1 with expression rep2.\n    ! if rep2 is shorter than rep1, fill the end of the string\n    ! with blanks\n\n    implicit none\n    character(len=*) :: string, rep1, rep2\n    integer :: idx, inlen, len1, len2\n\n    do\n       inlen = len(string)\n       len1 = len(rep1)\n       len2 = len(rep2)\n       idx = index(string, rep1)-1\n\n       if (idx == -1) then\n          return\n       else\n          string = string(1:idx)// rep2 // &\n               string((idx+len1+1):inlen) // &\n               \"                                                    \"\n       endif\n    enddo\n\n  end subroutine strrep\n\n\n  character(len=1024) function unblank(string) result(return_string)\n    ! Remove blanks (and tabs [char(9)] from string\n    implicit none\n    character(len=*), intent(in) :: string\n    integer :: i, j,  lenstr\n\n    return_string = \"\"\n\n    if ( verify(string,\" \"//char(9)) == 0 ) then\n       stop 'String is all blanks.'\n    endif\n\n    j = 0\n    do i = 1, len(string)\n       if ((string(i:i).ne.' ').and.(string(i:i).ne.char(9))) then\n          j = j + 1\n          return_string(j:j) = string(i:i)\n       endif\n    enddo\n\n  end function unblank\n\n!KWM  character function upcase(h)\n!KWM    implicit none\n!KWM    character :: h\n!KWM\n!KWM    if ((ichar(h).ge.96) .and. (ichar(h).le.123)) then\n!KWM       upcase = char(ichar(h)-32)\n!KWM    else\n!KWM       upcase = h\n!KWM    endif\n!KWM\n!KWM  end function upcase\n\n  character(len=256) function upcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \"\"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.96) .and. (ichar(h(i:i)).le.123)) then\n          return_string(i:i) = char(ichar(h(i:i))-32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function upcase\n\n!KWM  character function downcase(h)\n!KWM    implicit none\n!KWM    character h\n!KWM\n!KWM    if ((ichar(h).ge.65) .and. (ichar(h).le.90)) then\n!KWM       downcase = char(ichar(h)+32)\n!KWM    else\n!KWM       downcase = h\n!KWM    endif\n!KWM  end function downcase\n\n  character(len=256) function downcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \"\"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.65) .and. (ichar(h(i:i)).le.90)) then\n          return_string(i:i) = char(ichar(h(i:i))+32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function downcase\n\n\nend module kwm_string_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/lccone.F",
    "content": "subroutine lccone (fsplat,ssplat,sign,confac)\n  real, parameter :: conv=0.01745329251994\n  integer :: sign\n  real :: fsplat,ssplat,confac\n  if (abs(fsplat-ssplat).lt.1.E-2) then\n     confac = sin(fsplat*conv)\n  else\n     confac = log10(cos(fsplat*conv))-log10(cos(ssplat*conv))\n     confac = confac/(log10(tan((45.-float(sign)*fsplat/2.)*conv))-&\n          log10(tan((45.-float(sign)*ssplat/2.)*conv)))\n  endif\nend subroutine lccone\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/llxy_generic.F",
    "content": "subroutine lltoxy_generic (xlat,xlon,x,y,&\n     project,dskm,reflat,reflon,refx,refy,&\n     cenlon,truelat1,truelat2)\n\n!*****************************************************************************!\n!  Notes    - Modeled after XYTOLL in the plots.o library                     !\n!*****************************************************************************!\n\n  implicit none\n\n! Input: ---------------------------------------------------------------------!\n\n  real ::             xlat       ! latitude of the point of interest.\n  real ::             xlon       ! longitude of the point of interest.\n  character(LEN=2) :: project    ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n  real ::             dskm         ! grid distance in km\n  real ::             reflat\n  real ::             reflon\n  real ::             refx\n  real ::             refy\n  real ::             cenlon     ! Grid ratio with respect to MOAD\n  real ::             truelat1   ! True latitude 1, closest to equator\n  real ::             truelat2   ! True latitude 2, closest to pole\n\n! Output: --------------------------------------------------------------------!\n\n  real ::             x          ! x location of the given (lat,lon) point\n  real ::             y          ! y location of the given (lat,lon) point\n\n!  Parameters: ---------------------------------------------------------------!\n\n  real, parameter :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter :: piovr2 = pi/2.\n!  real, parameter :: re = 6370.949     ! the radius of the earth in km\n  real, parameter :: re = 6371.2       ! the radius of the earth in km\n  real, parameter :: ce = 2.*pi*re     ! the circumference of the earth in km\n  real, parameter :: degrad = pi/180.\n\n!  Real variables: -----------------------------------------------------------!\n\n  real          :: flat1\n  real          :: confac            ! cone factor\n  real          :: rcln              ! center longitude in radians  (local)\n  real          :: dj                ! distance from pole to point  (local)\n  real          :: di                ! distance from the central\n                                     !  meridian to the point        (local)\n  real          :: bm                ! calculation variable         (local)\n\n  real :: rflt, rfln, rlat, rlon, diovrdj, disdjs, ri, rj\n  real :: ct1, st1, tt1, drp\n  real :: isn, pi2\n  real :: londiff\n\n!****************************  subroutine begin  *****************************!\n\n\n  rlat =  xlat * degrad\n  rlon =  xlon * degrad\n  rcln = cenlon * degrad\n  flat1 = truelat1 * degrad\n  rflt = reflat * degrad\n  rfln = reflon * degrad\n\n  if ((xlon - cenlon) < -180) then\n     londiff = ((xlon-cenlon)+360.)*degrad\n  else if ((xlon - cenlon) > 180) then\n     londiff = ((xlon-cenlon)-360.)*degrad\n  else\n     londiff = (xlon-cenlon)*degrad\n  endif\n\n\n  if (project(1:2) .eq. 'ME') then\n\n     ct1 = re*cos(flat1)\n     dj = ct1 * log(tan (0.5*(rlat + piovr2)))\n     di = ct1 * (rlon - rfln)\n     y = refy +(dj + ct1 * log(cos(rflt)/(1 + sin(rflt))))/dskm\n     x = refx + di/dskm\n\n  else if (project(1:2) .eq. 'CE') then\n\n!KWM     dj = re*(rlat-rflt)\n!KWM     di = re*(rlon-rfln)\n!KWM     y = refy + dj/dskm\n!KWM     x = refx + di/dskm\n\n     ! NOTE:  Cylindrical Equidistant grid increment expressed in terms\n     ! of thousandths of degrees!\n     !  Calculate the distance from the horizontal axis to (J,I)\n     dj = xlat-reflat\n     di = xlon-reflon\n     y = refy + (dj/dskm)\n     x = refx + (di/dskm)\n\n  else if (project(1:2) .eq. 'LC') then\n\n     isn = sign(1.0, truelat2)\n     pi2 = piovr2*isn\n\n     call lccone(truelat1,truelat2,int(sign(1.0, truelat2)),confac)\n     tt1 = tan((pi2 - flat1)*0.5) ! Tangent Term 1.\n     st1 = sin (pi2 - flat1) * re/(confac*dskm)     ! Sine Term 1.\n     bm =  tan((pi2 - rlat)*0.5)\n     if ((rlon-rcln) > pi) then\n        diovrdj = -tan(((rlon-rcln)-2.*pi)*confac)\n     elseif ((rlon-rcln) < -pi) then\n        diovrdj = -tan(((rlon-rcln)+2.*pi)*confac)\n     else\n        diovrdj = -tan((rlon-rcln)*confac)\n     endif\n     disdjs = ( (bm/tt1)**confac * st1)**2\n     ! Dj: y distance (km) from pole to given x/y point.\n     dj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n     ! Di: x distance (km) from central longitude to given x/y point.\n     di = dj * diovrdj\n\n     bm = tan((pi2-rflt)*0.5)\n     if ((rfln-rcln) > pi) then\n        diovrdj = -tan(((rfln-rcln)-2.*pi)*confac)\n     else if ((rfln-rcln) < -pi) then\n        diovrdj = -tan(((rfln-rcln)+2.*pi)*confac)\n     else\n        diovrdj = -tan((rfln - rcln)*confac)\n     endif\n     disdjs = ( (bm/tt1)**confac * st1)**2\n     ! Rj: y distance (km) from pole to reference point.\n     rj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n     ! Ri: x distance (km) from central longitude to reference x/y point.\n     ri = rj * diovrdj\n     y = refy + isn*(dj - rj)\n     x = refx + (di - ri)\n\n  else if (project(1:2) .eq. 'ST') then\n\n     isn = sign(1.0, truelat1)\n     pi2 = piovr2*isn\n\n     diovrdj = -tan(rfln-rcln)\n     bm = (re/dskm)*tan(0.5*(pi2-rflt))\n     disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n     ! RJ:  Distance from pole to reference latitude along the center lon\n     rj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rfln-rcln))\n     ! RI:  Distance from center reference to requested point rlat, rlon.\n     ri = rj * diovrdj\n     diovrdj = -tan(rlon-rcln)\n     bm = (re/dskm)*tan(0.5*(pi2-rlat))\n     disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n     dj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rlon-rcln))\n     di = dj * diovrdj\n     y = refy + isn*(dj-rj)\n     x = refx + (di-ri)\n  endif\n\n!*****************************  Subroutine End  ******************************!\n\nend subroutine lltoxy_generic\n\nsubroutine xytoll_generic (x,y,xlat,xlon,&\n     project,dskm,reflat,reflon,refx,refy,&\n     cenlon, truelat1,truelat2)\n\n!*****************************************************************************!\n!  xytoll                                                                     !\n!  Purpose  - To  transform  mesoscale grid point coordinates (x,y) into      !\n!             latitude and longitude coordinates.                             !\n!                                                                             !\n!  On entry - X  and  Y are an ordered pair representing a grid point in  the !\n!             mesoscale grid.                                                 !\n!                                                                             !\n!  On exit  - XLAT, XLON contain  the latitude and longitude respectively     !\n!             that resulted from the transformation.                          !\n!                                                                             !\n!*****************************************************************************!\n  implicit none\n\n! Input\n  real ::             x         ! x (i) coordinate of point of interest\n  real ::             y         ! y (j) coordinate of point of interest\n  character(LEN=2) :: project   ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n  real ::             dskm      ! grid distance in km\n  real ::             reflat    ! latitude of the reference point\n  real ::             reflon    ! longitude of the reference point\n  real ::             refx\n  real ::             refy\n  real ::             cenlon    ! longitude of the center of the projection\n  real ::             truelat1  ! True latitude 1.\n  real ::             truelat2  ! True latitude 2.\n\n! Output\n  real ::             xlat      ! latitude of point (x,y)\n  real ::             xlon      ! longitude of point (x,y)\n\n! Parameters\n\n  real, parameter :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter :: piovr2 = pi/2.\n  real, parameter :: twopi  = pi*2.\n!  real, parameter :: re = 6370.949     ! the radius of the earth in km\n  real, parameter :: re = 6371.2\n  real, parameter :: degrad = pi/180.\n\n!  Real variables\n\n  real ::            confac           ! cone factor\n  real ::            rfln             ! reference longitude in radians  (local)\n  real ::            rflt             ! reference latitude in radians   (local)\n  real ::            rcln             ! center longitude in radians  (local)\n  real ::            dj, drp, djj     ! distance from the central\n!                                       meridian to the point        (local)\n  real ::            di,dii           ! distance from pole to point  (local)\n  real ::            bm               ! calculation variable         (local)\n  real ::            flat1\n  real ::            ct1, tt1, tt2, pi2\n  integer :: isn\n!****************************  subroutine begin  *****************************!\n\n  rflt = reflat * degrad\n  rfln = reflon * degrad\n  rcln = cenlon * degrad\n  flat1 = truelat1 * degrad\n\n!  If the projection is mercator ('ME') then ...\n\n  if (project(1:2) .eq. 'ME') then\n     di = (x-refx) * dskm\n     !  Calculate the distance the point in question is from the pole\n     dj = -re * cos(flat1)*log(cos(rflt)/(1 + sin(rflt))) + &\n          (y - refy) * dskm\n     !  Calculate the latitude desired in radians\n     xlat = 2.0 * atan(exp(dj/(re*cos(flat1)))) - piovr2\n     !  Calculate the longitude desired in radians\n     xlon = rfln + di/(re*cos(flat1))\n\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n\n! If the projection is cylindrical equidistant ('CE') then ...\n  else if (project(1:2) .eq. 'CE') then\n     ! NOTE:  Cylindrical Equidistant grid increment expressed in terms\n     ! of thousandths of degrees!\n     di = (x-refx) * dskm\n     !  Calculate the distance from the horizontal axis to (J,I)\n     dj = (y-refy) * dskm\n     !  Determine the shift north-south\n     xlat = reflat + dj\n     !  Determine the shift east-west\n     xlon = reflon + di\n\n! If the projection is lambert conic conformal ('LC') then ...\n  else if (project(1:2) .eq. 'LC') then\n\n     isn = sign(1.0, truelat2)\n     pi2 = piovr2*isn\n\n     call lccone(truelat1,truelat2,isn,confac)\n\n     tt1 = tan((pi2 - flat1)*0.5)    ! Tangent Term 1.\n     tt2 = tan((pi2 - rflt  )*0.5)    ! Tangent Term 2.\n     ct1 = -cos(flat1) * re/confac   ! cosine Term 1.\n\n     ! Calculate the (projected) distance from the pole to\n     ! the reference lat/lon.\n     drp = ct1 * (tt2/tt1)**confac\n     ! Now from the pole to the reference y along the center lon.\n     djj = drp * cos((rcln-rfln)*confac)\n\n     ! Now from the pole to the requested y along the center lon.\n     dj = djj + isn * ((y-refy)*dskm)\n     ! Now the (projected) distance from center longitude to reference x\n     dii = drp*sin((rcln-rfln)*confac)\n     ! And now from center longitude to requested X\n     di = dii + ((x-refx)*dskm)\n     !  Calculate the Big Messy equation\n     bm = tt1 * (sqrt(di**2+dj**2) /  abs(ct1))**(1.0/confac)\n     !  Calculate the desired latitude in radians\n     xlat = pi2 - 2.0*atan(bm)\n     !  Calculate the desired longitude in radians\n     xlon = rcln + (1.0/confac) * atan2(di,-dj)\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n\n!  If the projection is polar stereographic ('ST') then ...\n\n  else if (project(1:2) .eq. 'ST') then\n\n     isn = sign(1.0, truelat1)\n     pi2 = piovr2*isn\n\n\n!  Calculate the (projected) y-distance I,J lies from the pole\n\n     drp = -re*cos(rflt) * (1.0 + cos(pi2-flat1)) / (1.0 + cos(pi2-rflt))\n     djj = drp * cos(rcln-rfln)\n     dj = djj + isn*( (y-refy) * dskm )\n     dii = drp * sin(rcln-rfln)\n     di = dii + ((x-refx)*dskm)\n     ! Calculate the Big Messy quantity as would be done for LC\n     ! projections.  This quantity is different in value, same\n     ! in purpose of BM above\n     bm = (1.0/re) * sqrt(di*di + dj*dj) / (1.0 + cos(pi2-flat1))\n     !  Calculate the desired latitude in radians\n     xlat = pi2 - isn*2.0 * atan(bm)\n     !  Calculate the desired longitude in radians\n     xlon = rcln + atan2(di,-dj)\n\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n  else\n     print*, 'Unrecognized project:  ', project\n     stop\n  end if\n\n!  Make sure no values are greater than 180 degrees and none\n!  are less than -180 degrees\n\n  if (xlon .gt. 180.0)  xlon = xlon - 360.0\n  if (xlon .lt. -180.0) xlon = xlon + 360.0\n\n!*****************************  Subroutine End  ******************************!\n\nend subroutine xytoll_generic\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/module_2ddata.F",
    "content": "module module_2ddata\n\n  interface get_field\n     module procedure get_field_2d ! , get_field_3d\n  end interface\n\n  type fieldinfo_type\n     character(len=256) :: name\n     character(len=256) :: units\n     character(len=256) :: desc\n     character(len=10)  :: date\n     integer :: level\n  end type fieldinfo_type\n  type(fieldinfo_type) :: fieldinfo\n\n  type gridinfo_type\n     integer :: iproj\n     integer :: idim, jdim\n     real :: lat1, lon1, xlonc, dxm, truelat1, truelat2\n  end type gridinfo_type\n\ncontains\n\n  subroutine error_handler(status, failure, success)\n    use netcdf\n    !\n    ! Check the error flag from a NetCDF function call, and print appropriate\n    ! error message.\n    !\n    implicit none\n    integer,                    intent(in) :: status\n    character(len=*), optional, intent(in) :: failure\n    character(len=*), optional, intent(in) :: success\n\n    if (status .ne. NF90_NOERR) then\n       if (present(failure)) then\n          write(*,'(/,\" ***** \", A)') failure\n       endif\n       write(*,'(\" ***** \",A,/)') nf90_strerror(status)\n       stop 'Stopped'\n    endif\n\n    if (present(success)) then\n       write(*,'(A)') success\n    endif\n\n  end subroutine error_handler\n\n\n!\n!#############################################################################################################\n!\n\n  subroutine get_field_2d(flnm_template, nowdate, fldname, fldptr, gridinfo, level)\n    use netcdf\n    use kwm_string_utilities\n    implicit none\n\n    character(len=*), intent(in) :: flnm_template\n    character(len=*), intent(in) :: nowdate\n    character(len=*), intent(in) :: fldname\n    real, pointer, dimension(:,:) :: fldptr\n    type(gridinfo_type), intent(out) :: gridinfo\n    integer,          intent(in) :: level\n\n    character(len=256) :: flnm\n    integer :: ierr, ncid, varid, dimid, i\n    integer :: ndims\n    integer, dimension(NF90_MAX_VAR_DIMS) :: dimids\n    integer :: soillayers_dimid\n    logical :: threed\n\n    flnm = flnm_template\n    call strrep(flnm, \"<yyyymmddhh>\", nowdate)\n    call strrep(flnm, \"<hh>\", nowdate(9:10))\n\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    call error_handler(ierr, \"Problem opening file '\"//trim(flnm)//\"'\")\n\n    call get_gridinfo(ncid, gridinfo%iproj, gridinfo%lat1, gridinfo%lon1, &\n         gridinfo%xlonc, gridinfo%dxm, gridinfo%truelat1, gridinfo%truelat2, &\n         gridinfo%idim, gridinfo%jdim)\n\n    ierr = nf90_inq_varid(ncid, fldname, varid)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n! Find information about the dimensions of this variable, so we can determine whether\n! we're looking at a 2-d field or a 3-d field (not counting the time dimension).\n\n    ierr = nf90_inq_dimid(ncid, \"soil_layers_stag\", soillayers_dimid)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    ierr = nf90_inquire_variable(ncid, varid, ndims=ndims, dimids=dimids)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n! If the <dimids> array contains an element equal to <soillayers_dimid>, then\n! this is a 3-d dataset.\n\n    if (any(dimids(1:ndims)==soillayers_dimid)) then\n       threed = .TRUE.\n    else\n       threed = .FALSE.\n    endif\n\n! So let's get the field\n\n    allocate(fldptr(gridinfo%idim,gridinfo%jdim))\n\n    if (threed) then\n       ierr = nf90_get_var(ncid, varid, fldptr, start = (/1,1,level/), &\n            count=(/gridinfo%idim, gridinfo%jdim,1/) )\n       fieldinfo%level = level\n    else\n       ierr = nf90_get_var(ncid, varid, fldptr)\n    endif\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n! And get the units string\n\n    fieldinfo%units = \" \"\n    ierr = nf90_get_att(ncid, varid, \"units\", fieldinfo%units)\n    call error_handler(ierr, 'Attribute \"units\"')\n    do i = 1, len(fieldinfo%units)\n       if (ichar(fieldinfo%units(i:i)) == 0) fieldinfo%units(i:i) = \" \"\n    enddo\n\n! And get the description string.\n\n    fieldinfo%desc = \" \"\n    ierr = nf90_get_att(ncid, varid, \"description\", fieldinfo%desc)\n    call error_handler(ierr, \"Attribute 'Description'\")\n    do i = 1, len(fieldinfo%desc)\n       if (ichar(fieldinfo%desc(i:i)) == 0) fieldinfo%desc(i:i) = \" \"\n    enddo\n\n    fieldinfo%name = fldname\n    fieldinfo%date = nowdate\n\n  end subroutine get_field_2d\n\n!\n!#############################################################################################################\n!\n\n  subroutine get_gridinfo(ncid, iproj, lat1, lon1, xlonc, dxm, truelat1, truelat2, idim, jdim)\n    use netcdf\n    implicit none\n    integer, intent(in) :: ncid\n    integer, intent(out) :: iproj\n    integer, intent(out) :: idim, jdim\n    real, intent(out) :: lat1, lon1, xlonc, dxm, truelat1, truelat2\n\n    integer :: ierr, dimid\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", iproj)\n    call error_handler(ierr, \"Attribute 'MAP_PROJ'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LAT1\", lat1)\n    call error_handler(ierr, \"Attribute 'LAT1'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LON1\", lon1)\n    call error_handler(ierr, \"Attribute 'LON1'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"DX\", dxm)\n    call error_handler(ierr, \"Attribute 'DX'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n    call error_handler(ierr, \"Attribute 'TRUELAT1'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n    call error_handler(ierr, \"Attribute 'TRUELAT2'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", xlonc)\n    call error_handler(ierr, \"Attribute 'STAND_LON'\")\n\n    ierr = nf90_inq_dimid(ncid, \"west_east\", dimid)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    ierr = nf90_inquire_dimension(ncid, dimid, len=idim)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    ierr = nf90_inq_dimid(ncid, \"south_north\", dimid)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    ierr = nf90_inquire_dimension(ncid, dimid, len=jdim)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n  end subroutine get_gridinfo\n\n!\n!#############################################################################################################\n!\n\nend module module_2ddata\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/module_plot2d_graphics.F",
    "content": "module module_plot2d_graphics\n  use module_2ddata\n\n  type plt2d_parameters_type\n     real :: contour_minimum\n     real :: contour_maximum\n     real :: contour_interval\n     character(len=1024) :: color_table\n     character(len=10) :: plot_type\n     logical :: diff\n  end type plt2d_parameters_type\n\n  type(plt2d_parameters_type) :: plt2d_parameter\n\n  type named_color\n     character(len=20) :: name\n     real :: r\n     real :: g\n     real :: b\n  end type named_color\n\n  logical :: mapped = .FALSE.\n\n\ncontains\n\n  subroutine draw_field(fld, idim, jdim, gridinfo)\n    implicit none\n\n    integer, intent(in) :: idim, jdim\n    real, dimension(idim,jdim), intent(in) :: fld\n    type(gridinfo_type), intent(in) :: gridinfo\n\n    if (plt2d_parameter%plot_type == \"fillcell\") then\n       call fillcell(fld, idim, jdim, gridinfo)\n    else if (plt2d_parameter%plot_type == \"contour\") then\n       call plotfld(fld, idim, jdim, gridinfo)\n    else if (plt2d_parameter%plot_type == \"confill\") then\n       call fillfld(fld, idim, jdim, gridinfo)\n    else\n       call plotfld(fld, idim, jdim, gridinfo)\n    endif\n\n    call annotate()\n\n    call frame()\n\n  end subroutine draw_field\n\n  subroutine annotate\n    implicit none\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n    character(len=256) :: txt\n    call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n    call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n    ! call gscr(1, 1, 0., 0., 0.)\n    call pcseti(\"CC\", 1)\n\n    if ( (fieldinfo%name == \"SOIL_M\") .or. (fieldinfo%name == \"SOIL_T\") .or. &\n         (fieldinfo%name == \"SOIL_W\")) then\n       write(txt, '(A, \" -- Level \", I2)') trim(fieldinfo%name), fieldinfo%level\n    else\n       txt = trim(fieldinfo%name)\n    endif\n    write(*,'(3x,\"Field = \", A)') trim(txt)\n    call pchiqu(0.5*(xl+xr), 0.5*(1+xt), trim(txt), 0.015, 0., 0.)\n    txt = trim(fieldinfo%desc)//\"   (\"//trim(fieldinfo%units)//\")\"\n    call pchiqu(0.5*(xl+xr), 0.5*(1+xt)-0.03, trim(txt), 0.013, 0., 0.)\n\n    call pchiqu(xl, 0.5*(1+xt), fieldinfo%date, 0.015, 0., -1.)\n\n    call set(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n  end subroutine annotate\n\n!=============================================================================================\n\n  subroutine plotfld(fld, idim, jdim, gridinfo)\n    implicit none\n\n    integer, intent(in) :: idim, jdim\n    real, dimension(idim,jdim), intent(in) :: fld\n    type(gridinfo_type), intent(in) :: gridinfo\n\n    integer, parameter :: lwrk = 800000, liwk = 2000000\n    real, dimension(lwrk) :: rwrk\n    integer, dimension(liwk) :: iwrk\n\n    if (.not. mapped) then\n       mapped = .TRUE.\n       call gflas1(0)\n       call plotmap(gridinfo)\n       call gflas2\n    endif\n\n    call cpseti(\"SET\", 0)\n    call cpseti(\"CLS\", 1)\n    call cpsetr(\"CIS\", plt2d_parameter%contour_interval)\n    call cpsetr(\"CMN\", plt2d_parameter%contour_minimum)\n    call cpsetr(\"CMX\", plt2d_parameter%contour_maximum)\n\n    call cpsetr(\"SPV\", -1.E33)\n    call cprect(fld,idim,idim,jdim,rwrk,lwrk,iwrk,liwk)\n    call cplbdr(fld, rwrk, iwrk)\n    call cpcldr(fld, rwrk, iwrk)\n\n    call gflas3(0)\n\n  end subroutine plotfld\n\n!=============================================================================================\n\n  subroutine fillfld(fld, idim, jdim, gridinfo)\n    implicit none\n\n    integer, intent(in) :: idim, jdim\n    real, dimension(idim,jdim), intent(in) :: fld\n    type(gridinfo_type), intent(in) :: gridinfo\n\n    integer, parameter :: lwrk = 800000, liwk = 2000000\n    real, dimension(lwrk) :: rwrk\n    integer, dimension(liwk) :: iwrk\n\n    integer, parameter :: niam = 10000000\n    integer, parameter :: ncs = 10000000\n    integer, dimension(niam) :: iam\n    real,    dimension(niam) :: xcs, ycs\n    integer, dimension(5000)  :: iaia, igia\n\n    integer :: ncl\n    real :: cint, cmin, cmax\n    integer :: ncon, i, j, icol, labelint\n\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n\n    cmin = plt2d_parameter%contour_minimum\n    cmax = plt2d_parameter%contour_maximum\n    cint = plt2d_parameter%contour_interval\n\n    if (.not. mapped) then\n       mapped = .TRUE.\n       call gflas1(0)\n       call plotmap(gridinfo)\n       call gflas2\n    endif\n\n    call cpseti(\"SET\", 0)\n    call cpseti(\"CLS\", 1)\n    call cpsetr(\"CIS\", plt2d_parameter%contour_interval)\n    call cpsetr(\"CMN\", plt2d_parameter%contour_minimum)\n    call cpsetr(\"CMX\", plt2d_parameter%contour_maximum)\n\n    call cpsetr(\"SPV\", -1.E33)\n    call cprect(fld,idim,idim,jdim,rwrk,lwrk,iwrk,liwk)\n\n    call arinam(iam,niam) ! Initialize the area map\n    call cpclam(fld,rwrk,iwrk,iam)  ! put cont. lines in area map\n    call cpgeti(\"NCL\", ncl)\n    ! print*, 'ncl = ', ncl\n    call dfclrsa(ncl-1)\n    call arscam(iam,xcs,ycs,ncs,iaia,igia,5000,cpcolr)\n\n    !call cplbdr(fld, rwrk, iwrk)\n    !call cpcldr(fld, rwrk, iwrk)\n\n\n    call gflas3(0)\n\n    ! Add a color bar\n\n    call colorbar(ncl-1, cmin, cmax)\n  end subroutine fillfld\n\n  subroutine colorbar(ncon, cmin, cmax)\n    implicit none\n    integer, intent(in) :: ncon\n    real, intent(in) :: cmin, cmax\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml, labelint, i\n\n    real :: barxmin\n    real :: barxmax\n    real :: barymin\n    real :: barymax\n    real :: yvalmn, yvalmx\n    character(len=64) :: txt\n\n    call pcseti(\"CC\", 1)\n\n    call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n    call set(0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1)\n\n    barxmin = xr+0.02\n    barxmax = xr+0.06\n    barymin = xb;\n    barymax = xt;\n    ! print*, 'cmin, cmax, cint = ', cmin, cmax, cint\n    ! print*,' ncon = ', ncon\n    labelint = (ncon/30)+1\n\n    do i = 0, ncon-1\n       yvalmn = barymin + (barymax-barymin)*float(i)/float(ncon)\n       yvalmx = barymin + (barymax-barymin)*float(i+1)/float(ncon)\n       call fillbox(barxmin, barxmax, yvalmn, yvalmx, i+2)\n       if (mod(i,labelint)==0) then\n          write(txt, '(G12.4)') cmin + (cmax-cmin)*float(i)/float(ncon)\n          call pchiqu(barxmax, yvalmn, trim(txt), 0.010, 0., -1.)\n       endif\n    enddo\n    write(txt, '(G12.4)') cmax\n    call pchiqu(barxmax, barymax, trim(txt), 0.010, 0., -1.)\n\n    call line(barxmin, barymin, barxmin, barymax)\n    call line(barxmin, barymax, barxmax, barymax)\n    call line(barxmax, barymax, barxmax, barymin)\n    call line(barxmax, barymin, barxmin, barymin)\n\n    call set(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n  end subroutine colorbar\n\n!=============================================================================================\n\n  subroutine fillcell(fld, idim, jdim, gridinfo)\n    implicit none\n\n    integer, intent(in) :: idim, jdim\n    real, dimension(idim,jdim), intent(in) :: fld\n    type(gridinfo_type), intent(in) :: gridinfo\n\n    real :: cint, cmin, cmax\n    integer :: ncon, i, j, icol\n\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n\n    real :: barxmin\n    real :: barxmax\n    real :: barymin\n    real :: barymax\n    real :: yvalmn, yvalmx\n    character(len=64) :: txt\n    integer :: labelint\n\n    if (.not. mapped) then\n       mapped = .TRUE.\n       call gflas1(0)\n       call plotmap(gridinfo)\n       call gflas2\n    endif\n\n    cint = plt2d_parameter%contour_interval\n    cmin = plt2d_parameter%contour_minimum\n    cmax = plt2d_parameter%contour_maximum\n    ! maxf = maxval(fld, mask=(fld/=-1.E33))\n    ! minf = minval(fld, mask=(fld/=-1.E33))\n\n    ! Find contour minimum, contour maximum as an integer number of\n    ! contour_intervals from zero\n\n    ncon = (cmax-cmin)/cint\n    call dfclrsa(ncon)\n\n    do i = 1, idim\n       do j = 1, jdim\n          if (fld(i,j) > -1.E32) then\n             if (fld(i,j) >= cmax) then\n                icol = ncon+1\n             elseif (fld(i,j) <= cmin) then\n                icol = 2\n             else\n                icol = (fld(i,j)-cmin)/cint + 2\n             endif\n             call ngsquares((/float(i)/),(/float(j)/), 1, 1., icol)\n          endif\n       enddo\n    enddo\n\n    call gflas3(0)\n\n    call colorbar(ncon, cmin, cmax)\n\n  end subroutine fillcell\n\n!=============================================================================================\n\n  subroutine cpcolr (xcra,ycra,ncra,iaia,igia,naia)\n    !\n    !   This is a user-supplied areas subroutine which allows the user\n    !   to color areas in a particular way.\n    !\n    implicit none\n    integer, intent(in) :: naia, ncra\n    real   , intent(in), dimension(ncra) :: xcra, ycra\n    integer, intent(in), dimension(naia) :: iaia, igia\n\n    integer :: ifll, i\n    !\n    !   Assume polygon will be filled until we find otherwise.\n    !\n    ifll=1\n    !\n    !   If any area identifier is negative, don't fill the polygon\n    !\n    do i=1,naia\n       if (iaia(i).lt.0.) then\n          ifll=0\n       endif\n    enddo\n    !\n    !   Otherwise, fill the polygon in the color implied by its area\n    !   identifier relative to edge group 3 (the contour-line group).\n    !\n    if (ifll.ne.0) then\n       ifll=0\n       do i=1,naia\n          if (igia(i) == 3) then\n             ifll=iaia(i)\n          endif\n       enddo\n       !\n       !      Note that if icoindcp(ifll) is negative, that means this\n       !      polygon should remain transparent (i.e. not filled).\n       !\n       if (ifll.ge.1) then\n#ifdef dead\n          if (ifll.le.nconarea.and.icoindcp(ifll).ge.0) then\n             call gsfaci(icoindcp(ifll))\n#else\n!             print*,' fill color ', ifll\n             call gsfaci(ifll)\n#endif\n             call gfa (ncra-1,xcra,ycra)\n#ifdef dead\n          else\n             write(*, '(\"ifll = \",I)') ifll\n             write(*, '(\"icoindcp(ifll) = \",I)') icoindcp(ifll)\n             stop \"Transparent problem.  Fix it?\"\n          endif\n#endif\n       endif\n    endif\n\n  end subroutine cpcolr\n\n!=============================================================================================\n\n  subroutine dfclrsa(n)\n    implicit none\n    integer, intent(in) :: n\n    integer :: i, indx, m\n    real, dimension(0:255) :: xval, yval\n    character(len=24), dimension(0:255) :: colname\n    type(named_color) :: cb, ct\n    integer :: ncols\n    real :: z, fr\n\n    xval = -99999.\n    i = 1\n    m = 0\n    do\n       indx = index(plt2d_parameter%color_table(i:), \",\")\n       if (indx <= 0) then\n          colname((m-1)/2) = trim(plt2d_parameter%color_table(i:))\n          exit\n       endif\n       indx = indx + i\n       if (mod(m,2)==0) then\n          read(plt2d_parameter%color_table(i:indx-2),*) xval(m/2)\n       else\n          colname((m-1)/2) = plt2d_parameter%color_table(i:indx-2)\n       endif\n       i = indx\n       m = m + 1\n    enddo\n    ncols = (m/2)+1\n\n    ! Define <n> color levels from our set of <ncols> colors.\n    ! Map our <ncols> xval values to our <n> integer values.\n\n    do i = 0, ncols-1\n       ! yval(i) = (xval(i)/xval(ncols-1))*(n-1)\n       yval(i) = (xval(i)-xval(0)) / (xval(ncols-1)-xval(0)) * (n-1)\n       ! print*, xval(i), trim(colname(i)), yval(i)\n    enddo\n\n    do i = 0, n-1\n       ! Search for the bracketing colors\n       do m = 1, ncols-1\n          if ( (i >= yval(m-1)) .and. (i <= yval(m)) ) then\n             ! print*, i, m, yval(m-1), yval(m)\n             cb = get_x11_color(colname(m-1))\n             ct = get_x11_color(colname(m))\n             !z = (float(i)/float(n-1))*xval(ncols-1)\n             !fr = (z-(xval(m-1)))/(xval(m)-xval(m-1))\n             z = xval(0) + (float(i)/float(n-1))*(xval(ncols-1)-xval(0))\n             fr = (z-(xval(m-1)))/(xval(m)-xval(m-1))\n             ! print*, i, z, (m-1), fr\n\n             call gscr(1, i+2, &\n                  (ct%r*fr)+(cb%r*(1-fr)), &\n                  (ct%g*fr)+(cb%g*(1-fr)), &\n                  (ct%b*fr)+(cb%b*(1-fr)) )\n             if (m==ncols-1) then\n                call gscr(1, i+3, &\n                     (ct%r*fr)+(cb%r*(1-fr)), &\n                     (ct%g*fr)+(cb%g*(1-fr)), &\n                     (ct%b*fr)+(cb%b*(1-fr)) )\n             endif\n             exit\n          endif\n       enddo\n\n       !call gscr(1, i+2, float(i)/float(n-1), float(i)/float(n-1), float(i)/float(n-1))\n       !call gscr(1, i+2, float(i)/float(n-1), float(i)/float(n-1), float(i)/float(n-1))\n    enddo\n\n  end subroutine dfclrsa\n\n!=============================================================================================\n\n  type(named_color) function get_x11_color(name) result (c)\n    use kwm_string_utilities\n    implicit none\n    character(len=*) :: name\n    integer :: r, g, b, i\n    character(len=20) :: cname\n\n    logical, save :: already_read = .FALSE.\n    integer :: ierr, idx\n    character(len=80) :: string, stringname\n    integer, parameter :: iunit = 22\n\n    real, dimension(2500), save :: readlist_r, readlist_g, readlist_b\n    character(len=64), dimension(2500), save :: readlist_name\n    integer, save :: readlist_count = 0\n\n    if (name(1:1) == \"#\") then\n       read(name(2:7), '(Z2,Z2,Z2)') r,g,b\n       c = named_color(trim(name), float(r)/255., float(g)/255., float(b)/255.)\n       return\n    else if ((name(1:2) == \"Ox\") .or. (name(1:2) == \"0x\")) then\n       read(name(3:8), '(Z2,Z2,Z2)') r,g,b\n       c = named_color(trim(name), float(r)/255., float(g)/255., float(b)/255.)\n       return\n    endif\n\n    if (.not. already_read) then\n       already_read = .TRUE.\n       open(iunit, file=\"/usr/lib/X11/rgb.txt\", form='formatted', &\n            status='old', action='read', iostat=ierr)\n       if (ierr /= 0) then\n          open(iunit, file=\"/usr/share/X11/rgb.txt\", form='formatted', &\n               status='old', action='read', iostat=ierr)\n          if (ierr /= 0) then\n             stop \"color table not found in /usr/lib/X11/rgb.txt or /usr/share/X11/rgb.txt\"\n          endif\n       endif\n       do\n\n          read(iunit, '(A)', iostat=ierr) string\n          if (ierr /= 0) exit\n          if (string(1:1) == \"!\") cycle\n\n          stringname = \" \"\n          read(string, *) r, g, b\n          ! Find the index of the first alphabetical character\n          idx = verify(string, \" 0123456789\"//char(9)) ! char(9) is tab\n          stringname = trim(string(idx:))\n          stringname = downcase(trim(stringname))\n          stringname = unblank(trim(stringname))\n\n          readlist_count = readlist_count + 1\n          readlist_r(readlist_count) = float(r)/255.\n          readlist_g(readlist_count) = float(g)/255.\n          readlist_b(readlist_count) = float(b)/255.\n          readlist_name(readlist_count) = stringname\n\n       enddo\n\n       close(iunit)\n    endif\n\n    ! Search through readlist for name\n    do i = 1, readlist_count\n       if (name == readlist_name(i)) then\n          cname = name\n          c = named_color(cname, readlist_r(i), readlist_g(i), readlist_b(i))\n          return\n       endif\n    enddo\n\n    write(*, '(\"color not found: \", A)') trim(name)\n\n  end function get_x11_color\n\n!=============================================================================================\n\n  subroutine init_ncargks(new_cgm_name)\n! Starts off the NCAR Graphics package.\n! Opens workstation 1 as a CGM workstation.\n! Opens workstation 2 as a WISS.\n! Defines a couple of colors, and sets a couple of NCAR Graphics parameters\n!\n! If you want the gmeta file to be called something other than \"gmeta\",\n! give this subroutine the optional argument.\n    implicit none\n    character(len=*), optional, intent(in) :: new_cgm_name\n    character(len=80) :: newname\n    character(len=1) :: hdum\n\n    call gopks(6,0)\n\n    if (present(new_cgm_name)) then\n       newname = trim(new_cgm_name)\n       call gesc(-1391, 1, newname, 1, 1, hdum)\n    endif\n\n    call gopwk(1,119,1)\n    call gopwk(2,120,3)\n    call gacwk(1)\n    call gacwk(2)\n\n    ! call define_color(\"white\")\n    ! call define_color(\"black\")\n    call gscr(1, 0, 1., 1., 1.) ! White\n    call gscr(1, 1, 0., 0., 0.) ! Black\n    call pcseti(\"FN\", 21)\n    call pcsetc(\"FC\", \"~\")\n  end subroutine init_ncargks\n\n  subroutine close_ncargks\n    implicit none\n    call gdawk(1)\n    call gdawk(2)\n    call gclwk(1)\n    call gclwk(2)\n    call gclks\n  end subroutine close_ncargks\n\n  subroutine ngsquares(x,y,ndim,xs,icol)\n!\n! Draw filled squares at specified x-y coordinates\n!\n    implicit none\n\n! Input:\n    integer, intent(in) :: ndim   ! Number of filled squares to draw.\n\n    real, intent(in), dimension(ndim) :: x, y ! x-y coordinates of the centers\n    !  of the squares\n\n    integer, intent(in) :: icol   ! Color index of the color to use.\n    real, intent(in) :: xs        ! Size to draw the squares.\n\n! Local:\n    integer, parameter :: nra = 4\n    integer, parameter :: nim = 2\n    integer, parameter :: nnd = nra+2*nim\n    integer, parameter :: nst = nra+nim\n\n    real, dimension(nst) :: dst\n    real, dimension(nnd) :: ind\n    real, dimension(nra) :: x4, y4\n    real :: sz\n    integer :: i\n\n    sz = xs * 0.5 ! Each side is (1/2)* xs away from the center.\n\n    do i = 1, ndim\n       x4(1) = x(i) - sz\n       x4(2) = x4(1)\n       x4(3) = x(i) + sz\n       x4(4) = x4(3)\n\n       y4(1) = y(i) - sz\n       y4(2) = y(i) + sz\n       y4(3) = y4(2)\n       y4(4) = y4(1)\n\n       call sfsgfa(x4, y4, nra, dst, nst, ind, nnd, icol)\n    enddo\n  end subroutine ngsquares\n\n  subroutine fillbox(xmin,xmax,ymin,ymax,icol)\n!\n! Draw filled box\n!\n    implicit none\n\n! Input:\n\n    real, intent(in) :: xmin, xmax, ymin, ymax\n    integer, intent(in) :: icol   ! Color index of the color to use.\n\n! Local:\n    integer, parameter :: nra = 4\n    integer, parameter :: nim = 2\n    integer, parameter :: nnd = nra+2*nim\n    integer, parameter :: nst = nra+nim\n\n    real, dimension(nst) :: dst\n    real, dimension(nnd) :: ind\n    real, dimension(nra) :: x4, y4\n    real :: sz\n    integer :: i\n\n    x4(1:2) = xmin\n    x4(3:4) = xmax\n    y4(1) = ymin\n    y4(2:3) = ymax\n    y4(4) = ymin\n\n    call sfsgfa(x4, y4, nra, dst, nst, ind, nnd, icol)\n  end subroutine fillbox\n\n\n  subroutine plotmap(gridinfo)\n    implicit none\n    type(gridinfo_type), intent(in) :: gridinfo\n    real :: plm1, plm2, plm3, plm4\n    character(len=2), parameter, dimension(3) :: project = (/\"LC\", \"ST\", \"ME\"/)\n    integer :: ierr\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n\n    call xytoll_generic(1.0, 1.0, plm1, plm2,  &\n         project(gridinfo%iproj), gridinfo%dxm*0.001, gridinfo%lat1, gridinfo%lon1, 1.5, 1.5, &\n         gridinfo%xlonc, gridinfo%truelat1, gridinfo%truelat2)\n\n    call xytoll_generic(real(gridinfo%idim), real(gridinfo%jdim), plm3, plm4,  &\n         project(gridinfo%iproj), gridinfo%dxm*0.001, gridinfo%lat1, gridinfo%lon1, 1.5, 1.5, &\n         gridinfo%xlonc, gridinfo%truelat1, gridinfo%truelat2)\n\n    call mappos(0.05, 0.85, 0.05, 0.85)\n\n    if (project(gridinfo%iproj) == \"LC\") then\n       ! Lambert Conformal\n       call supmap(3, gridinfo%truelat1, gridinfo%xlonc, gridinfo%truelat2, &\n            plm1, plm2, plm3, plm4, 2, 0, 4, 0, ierr)\n    else\n       write(*,'(\"Subroutine plotmap:  Unrecognized map projection: \",A)') project(gridinfo%iproj)\n       stop\n    endif\n\n    call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n    call set(xl, xr, xb, xt, 1.0, float(gridinfo%idim), 1.0, float(gridinfo%jdim), ml)\n\n\n  end subroutine plotmap\n\n\n\n\nend module module_plot2d_graphics\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/namelist.plt2d",
    "content": "#\n# Possible values for plot_type:\n#\n#      plot_type = \"contour\"  :: Plain contour plot\n#      plot_type = \"confill\"  :: color-filled contour plot   (Very slow for large grids)\n#      plot_type = \"fillcell\" :: color-filled grid-cells     (Recommended for large grids)\n#\n# Color specification\n#      For the color table, colors listed in the file \"/usr/lib/X11/rgb.txt\" may be used.\n#      In addition, colors may be specified as triplets of hexidecimal two-digit values \n#      of red, green, and blue:  \"0x<rr><gg><bb>\" or \"#<rr><gg><bb>\"\n#       e.g.: \"#A405BF\" or \"0xFF00BB\"\n#\n\n\n\n&file_info\n!  ldasout_flnm_template = \"/mmmtmp/kmanning/RunNoSat/<yyyymmddhh>.LDASOUT_DOMAIN1\"\n!  diff_flnm_template    = \"/mmmtmp/kmanning/RunNoSat/<yyyymmddhh>.LDASOUT_DOMAIN1\"\n!  ldasout_flnm_template = \"/scholar2/kmanning/VERY_TEMPORARY_HRLDAS/Run_3.2/<yyyymmddhh>.LDASOUT_DOMAIN1\"\n!  diff_flnm_template    = \"/scholar/kmanning/more_hrldas/hrldas-v3.1/Run/<yyyymmddhh>.LDASOUT_DOMAIN1\"\n!  ldasout_flnm_template  = \"/scholar/kmanning/more_hrldas/hrldas-v3.1/Run/<yyyymmddhh>.LDASOUT_DOMAIN1\"\n!  ldasout_flnm_template = \"/scholar2/kmanning/VERY_TEMPORARY_HRLDAS/Run_3.2/m01.avg.h<hh>.nc\"\n!  diff_flnm_template = \"/scholar/kmanning/more_hrldas/hrldas-v3.1/Run/m01.avg.h<hh>.nc\"\n! ldasout_flnm_template = \"/scholar2/kmanning/VERY_TEMPORARY_HRLDAS/Run_3.2/m01.avg.h<hh>.nc\"\n! ldasout_flnm_template = \"/scholar/kmanning/more_hrldas/hrldas-v3.1/Run/m01.avg.h<hh>.nc\"\n\n!  ldasout_flnm_template = \"/scholar/kmanning/more_hrldas/devel-3.2/Run/smallgrid_Jun_avg_hr<hh>.nc\"\n!  diff_flnm_template =   \"/scholar/kmanning/more_hrldas/hrldas-v3.1/Run/smallgrid_Jun_avg_hr<hh>.nc\"\n\n!  ldasout_flnm_template =    \"/scholar/kmanning/more_hrldas/devel-3.2/Run/reference_parallel_bugfix-dtot/avg_200201_<hh>Z.nc\"\n!  diff_flnm_template = \"/scholar/kmanning/more_hrldas/devel-3.2/Run/reference_parallel/avg_200201_<hh>Z.nc\"\n\n!  ldasout_flnm_template = \"/scholar/kmanning/more_hrldas/devel-3.2/Run/reference_parallel_bugfix-dtot_z0snow_sfcdif1/avg_200206_<hh>Z.nc\"\n!  diff_flnm_template    = \"/scholar/kmanning/more_hrldas/devel-3.2/Run/reference_parallel_bugfix-dtot_z0snow/avg_200206_<hh>Z.nc\"\n\n!   ldasout_flnm_template = \"/scholar/kmanning/more_hrldas/devel-3.2/Run/reference_parallel_bugfix-dtot_z0snow_sfcdif1_iz0tlnd1/avg_200206_<hh>Z.nc\"\n!   diff_flnm_template    = \"/scholar/kmanning/more_hrldas/devel-3.2/Run/reference_parallel_bugfix-dtot_z0snow_sfcdif1/avg_200206_<hh>Z.nc\"\n\n  ldasout_flnm_template = \"/scholar/kmanning/more_hrldas/devel-3.2/Run/reference_parallel_bugfix-dtot_z0snow_sfcdif1/avg_200206_<hh>Z.nc\"\n  diff_flnm_template    = \"/scholar/kmanning/more_hrldas/devel-3.2/Run/reference_parallel_bugfix-dtot_z0snow/avg_200206_<hh>Z.nc\"\n  \n  plot_startdate = \"2002060100\"\n  plot_enddate   = \"2002060121\"\n  plot_interval  = 3\n/\n\n! &plot_info\n  fldname = \"SNODEP\", \n  plot_type = \"fillcell\"  \n  contour_minimum = 0.0\n  contour_maximum = 0.5\n  contour_interval = 0.02\n  color_table=\"0,white,0.1,brown,0.2,green,0.3,blue,0.4,red,0.5,magenta\"\n/ \n\n! &plot_info\n   fldname = \"HFX\", \n   plot_type = \"fillcell\"  \n   contour_minimum = -250.0\n   contour_maximum = 600.0\n   contour_interval = 10.0\n   color_table=\"-250,blue,-10,white,10,white,200,0xDD0022,600,magenta\"\n / \n\n! &plot_info\n   fldname = \"QFX\", \n   plot_type = \"fillcell\"  \n   contour_minimum = -250.0\n   contour_maximum = 600.0\n   contour_interval = 10.0\n   color_table=\"-250,blue,-10,white,10,white,200,0xDD0022,600,magenta\"\n / \n\n! &plot_info\n   fldname = \"GRDFLX\", \n   plot_type = \"fillcell\"  \n   contour_minimum = -250.0\n   contour_maximum = 600.0\n   contour_interval = 10.0\n   color_table=\"-250,blue,-10,white,10,white,200,0xDD0022,600,magenta\"\n / \n\n&plot_info\n   fldname = \"HFX\", \n   plot_type = \"fillcell\"  \n   contour_minimum = -20.0\n   contour_maximum =  20.0\n   contour_interval = 0.5\n   color_table=\"-20.0,blue,-10.0,green,-0.5,white,0.5,white,10.0,0xDD0022,20.0,magenta\"\n / \n\n&plot_info\n   fldname = \"QFX\", \n   plot_type = \"fillcell\"  \n / \n\n&plot_info\n   fldname = \"GRDFLX\", \n   plot_type = \"fillcell\"  \n   contour_minimum = -10.0\n   contour_maximum =  10.0\n   contour_interval = 0.25\n   color_table=\"-10,blue,-50,green,-0.25,white,0.25,white,5,0xDD0022,10,magenta\"\n / \n\n! &plot_info\n   fldname = \"VEGFRA\", \n   plot_type = \"fillcell\"  \n   contour_minimum = 0.0\n   contour_maximum = 1.0\n   contour_interval = 0.01\n   color_table=\"0.0,white,0.33,brown,0.66,yellow,1.0,green4\"\n / \n\n! &plot_info\n   fldname = \"XLAI\", \n   plot_type = \"fillcell\"  \n   contour_minimum = 0.0\n   contour_maximum = 6.0\n   contour_interval = 0.06\n   color_table=\"0,white,2.0,brown,4.0,yellow,6.0,green4\"\n / \n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 1\n  plot_type = \"fillcell\"  \n  contour_minimum = 255.0\n  contour_maximum = 305.0\n  contour_interval = 0.25\n  color_table=\"255,magenta,260,cyan,267.5,#0000AA,275,white,282.5,#CC8899,290,green,297.5,red,305,magenta\"\n/ \n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 2\n  plot_type = \"fillcell\"  \n  contour_minimum = 260.0\n  contour_maximum = 305.0\n  contour_interval = 0.25\n  color_table=\"260,cyan,267.5,#0000AA,275,white,282.5,#CC8899,290,green,297.5,red,305,magenta\"\n/ \n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 3\n  plot_type = \"fillcell\"  \n  contour_minimum = 260.0\n  contour_maximum = 305.0\n  contour_interval = 0.25\n  color_table=\"260,cyan,267.5,#0000AA,275,white,282.5,#CC8899,290,green,297.5,red,305,magenta\"\n/ \n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 4\n  plot_type = \"fillcell\"  \n  contour_minimum = 260.0\n  contour_maximum = 305.0\n  contour_interval = 0.25\n  color_table=\"260,cyan,267.5,#0000AA,275,white,282.5,#CC8899,290,green,297.5,red,305,magenta\"\n  !color_table=\"270,cyan,277.5,#0000AA,285,white,292.5,#CC8899,300,green,307.5,red,315,magenta\"\n/ \n\n&plot_info\n  fldname = \"SOIL_T\", soil_level = 1\n  plot_type = \"fillcell\"  \n  contour_minimum = -2.0\n  contour_maximum = 2.0\n  contour_interval = 0.05\n  color_table=\"-2,blue,-1,green,-0.05,white,0.05,white,1,0xCC8899,2,red\"\n/ \n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 1\n  plot_type = \"fillcell\"  \n  contour_minimum = -6.0\n  contour_maximum = 6.0\n  contour_interval = 0.5\n  color_table=\"-6,blue,-3,green,-0.5,white,0.5,white,3,0xCC8899,6,red\"\n/ \n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 2\n  plot_type = \"fillcell\"  \n  contour_minimum = -12.0\n  contour_maximum = 12.0\n  contour_interval = 0.5\n  color_table=\"-12,blue,-6,green,-0.5,white,0.5,white,6,0xCC8899,12,red\"\n/\n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 3\n  plot_type = \"fillcell\"  \n  contour_minimum = -10.0\n  contour_maximum = 10.0\n  contour_interval = 0.5\n  color_table=\"-10,blue,-5,green,-0.5,white,0.5,white,5,0xCC8899,10,red\"\n/\n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 4\n  plot_type = \"fillcell\"  \n  contour_minimum = -8.0\n  contour_maximum = 8.0\n  contour_interval = 0.25\n  color_table=\"-8,blue,-4,green,-0.25,white,0.25,white,4,0xCC8899,8,red\"\n/ \n\n\n! &plot_info\n  fldname = \"SOIL_T\", soil_level = 1\n  plot_type = \"fillcell\"  \n  contour_minimum = -5.0\n  contour_maximum = 5.0\n  contour_interval = 0.20\n  color_table=\"-5,blue,-2,green,-0.2,white,0.2,white,2,0xCC8899,5,red\"\n/ \n\n&plot_info\n  fldname = \"SOIL_T\", soil_level = 2\n  plot_type = \"fillcell\"  \n/\n\n&plot_info\n  fldname = \"SOIL_T\", soil_level = 3\n  plot_type = \"fillcell\"  \n/\n\n&plot_info\n  fldname = \"SOIL_T\", soil_level = 4\n  plot_type = \"fillcell\"  \n/ \n\n! &plot_info\n  fldname = \"SOIL_M\", soil_level=1,\n  plot_type = \"fillcell\"  \n  contour_minimum = 0.0\n  contour_maximum = 0.4\n  contour_interval = 0.00625\n  color_table=\"0.00,white,0.10,brown,0.20,yellow,0.30,green,0.40,blue\"\n/\n\n! &plot_info\n  fldname = \"SOIL_M\", soil_level=2,\n  plot_type = \"fillcell\"  \n  contour_minimum = 0.0\n  contour_maximum = 0.4\n  contour_interval = 0.00625\n  color_table=\"0.00,white,0.10,brown,0.20,yellow,0.30,green,0.40,blue\"\n/\n\n! &plot_info\n  fldname = \"SOIL_M\", soil_level=3,\n  plot_type = \"fillcell\"  \n  contour_minimum = 0.0\n  contour_maximum = 0.4\n  contour_interval = 0.00625\n  color_table=\"0.00,white,0.10,brown,0.20,yellow,0.30,green,0.40,blue\"\n/\n\n! &plot_info\n  fldname = \"SOIL_M\", soil_level=4,\n  plot_type = \"fillcell\"  \n  contour_minimum = 0.0\n  contour_maximum = 0.4\n  contour_interval = 0.00625\n  color_table=\"0.00,white,0.10,brown,0.20,yellow,0.30,green,0.40,blue\"\n/\n\n&plot_info\n  fldname = \"SOIL_M\", soil_level=1,\n  plot_type = \"fillcell\"  \n  contour_minimum = -0.1\n  contour_maximum = 0.1\n  contour_interval = 0.005\n  color_table=\"-0.1,brown,-0.05,yellow2,-0.005,white,0.005,white,0.05,green,0.1,blue\"\n/\n\n&plot_info\n  fldname = \"SOIL_M\", soil_level=2,\n  plot_type = \"fillcell\"  \n/\n\n&plot_info\n  fldname = \"SOIL_M\", soil_level=3,\n  plot_type = \"fillcell\"  \n/\n\n&plot_info\n  fldname = \"SOIL_M\", soil_level=4,\n  plot_type = \"fillcell\"  \n/\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/HORIZ/plt2d.F",
    "content": "!\n! ############################################################################################################\n!\n\nprogram plt2d\n  use module_2ddata\n  use kwm_date_utilities\n  use module_plot2d_graphics\n  implicit none\n\n  character(len=256) :: ldasout_flnm_template\n  character(len=256) :: diff_flnm_template\n  character(len=10) :: plot_startdate\n  character(len=10) :: plot_enddate\n  integer           :: plot_interval\n  character(len=10) :: nowdate\n  character(len=10) :: fldname\n  real, pointer, dimension(:,:) :: fldptr, fldptr2\n  integer :: soil_level\n  type(gridinfo_type) :: gridinfo\n  integer :: ierr\n\n  integer, parameter :: namelist_fortran_unit = 10\n  character(len=256) :: namelist_filename\n  integer, external :: iargc\n\n  print*, 'iargc() = ', iargc()\n  if (iargc() == 1) then\n     call getarg(1, namelist_filename)\n  else\n     namelist_filename = \"namelist.plt2d\"\n  endif\n\n  call read_fileinfo_namelist(namelist_filename, namelist_fortran_unit, &\n       ldasout_flnm_template, diff_flnm_template, plot_startdate, plot_enddate, plot_interval)\n\n  nowdate = plot_startdate\n\n  call init_ncargks()\n\n  do while (nowdate <= plot_enddate)\n     print*, 'Date = ', nowdate\n\n     do\n        call read_plotinfo_namelist(namelist_filename, namelist_fortran_unit, ierr, fldname, soil_level)\n        if (ierr /= 0) exit\n\n        call get_field(trim(ldasout_flnm_template), nowdate, trim(fldname), fldptr, gridinfo, &\n             level=soil_level)\n\n        if (diff_flnm_template /= \"\") then\n           call get_field(trim(diff_flnm_template), nowdate, trim(fldname), fldptr2, gridinfo, &\n                level=soil_level)\n           fldptr = fldptr - fldptr2\n           nullify(fldptr2)\n        endif\n\n        call draw_field(fldptr, gridinfo%idim, gridinfo%jdim, gridinfo)\n        nullify(fldptr)\n\n     enddo\n\n     call geth_newdate(nowdate, nowdate, plot_interval)\n  enddo\n\n  call close_ncargks()\n\nend program plt2d\n\n!\n! ############################################################################################################\n!\n\nsubroutine read_fileinfo_namelist(namelist_filename, namelist_fortran_unit, &\n     ldasout_flnm_template, diff_flnm_template, plot_startdate, plot_enddate, plot_interval)\n  use module_plot2d_graphics\n  implicit none\n  character(len=*), intent(in) :: namelist_filename\n  integer, intent(in) :: namelist_fortran_unit\n  character(len=256)  :: ldasout_flnm_template\n  character(len=256)  :: diff_flnm_template\n  character(len=10)   :: plot_startdate\n  character(len=10)   :: plot_enddate\n  integer             :: plot_interval\n\n  namelist/file_info/ ldasout_flnm_template, plot_startdate, plot_enddate, plot_interval, diff_flnm_template\n\n  plot_interval = 1\n  diff_flnm_template = \"\"\n\n  open(namelist_fortran_unit, file=namelist_filename, status='old', form='formatted', action='read')\n\n  read(namelist_fortran_unit, file_info)\n\nend subroutine read_fileinfo_namelist\n\n!\n! ############################################################################################################\n!\n\nsubroutine read_plotinfo_namelist(namelist_filename, namelist_fortran_unit, ierr, fldname, soil_level)\n  use module_plot2d_graphics\n  implicit none\n  character(len=*), intent(in) :: namelist_filename\n  integer, intent(in) :: namelist_fortran_unit\n  character(len=10)  :: fldname\n  real :: contour_interval\n  real :: contour_minimum\n  real :: contour_maximum\n  character(len=1024) :: color_table\n  character(len=10)   :: plot_type\n  integer :: soil_level\n  logical :: lopen\n  integer, intent(out)  :: ierr\n\n\n  namelist/plot_info/ fldname, soil_level, &\n       contour_interval, contour_minimum, contour_maximum, color_table, plot_type\n\n\n! Default values:\n  soil_level = 1\n  plot_type = \"contour\"\n\n  inquire(namelist_fortran_unit,opened=lopen)\n  if (.not. lopen) then\n     open(namelist_fortran_unit, file=namelist_filename, status='old', form='formatted', action='read')\n  endif\n\n  read(namelist_fortran_unit, plot_info, iostat=ierr)\n  if (ierr/=0) then\n     close(namelist_fortran_unit)\n     return\n  endif\n  ! ldasout_flnm_template = \"/d5/kmanning/HRLDAS/HRLDAS/Run_USWRP_EXP7/<yyyymmddhh>.LDASOUT_DOMAIN2\"\n  ! plot_startdate = \"2002060900\"\n  ! plot_enddate   = \"2002060906\"\n  ! fldname = \"SOIL_M\"\n  plt2d_parameter%contour_interval = contour_interval\n  plt2d_parameter%contour_minimum = contour_minimum\n  plt2d_parameter%contour_maximum = contour_maximum\n  plt2d_parameter%color_table = trim(color_table)\n  plt2d_parameter%plot_type = trim(plot_type)\n\nend subroutine read_plotinfo_namelist\n\n!\n! ############################################################################################################\n!\n!KWM\n!KWMsubroutine plotmap(gridinfo)\n!KWM  use module_2ddata\n!KWM  implicit none\n!KWM  type(gridinfo_type), intent(in) :: gridinfo\n!KWM  real :: plm1, plm2, plm3, plm4\n!KWM  character(len=2), parameter, dimension(3) :: project = (/\"LC\", \"ST\", \"ME\"/)\n!KWM  integer :: ierr\n!KWM  real :: xl, xr, xb, xt, wl, wr, wb, wt\n!KWM  integer :: ml\n!KWM\n!KWM  call xytoll_generic(1.0, 1.0, plm1, plm2,  &\n!KWM       project(gridinfo%iproj), gridinfo%dxm*0.001, gridinfo%lat1, gridinfo%lon1, 1.5, 1.5, &\n!KWM       gridinfo%xlonc, gridinfo%truelat1, gridinfo%truelat2)\n!KWM\n!KWM  call xytoll_generic(real(gridinfo%idim), real(gridinfo%jdim), plm3, plm4,  &\n!KWM       project(gridinfo%iproj), gridinfo%dxm*0.001, gridinfo%lat1, gridinfo%lon1, 1.5, 1.5, &\n!KWM       gridinfo%xlonc, gridinfo%truelat1, gridinfo%truelat2)\n!KWM\n!KWM  if (project(gridinfo%iproj) == \"LC\") then\n!KWM     ! Lambert Conformal\n!KWM     call supmap(3, gridinfo%truelat1, gridinfo%xlonc, gridinfo%truelat2, &\n!KWM          plm1, plm2, plm3, plm4, 2, 0, 4, 0, ierr)\n!KWM  else\n!KWM     write(*,'(\"Unrecognized map projection: \",A)') project(gridinfo%iproj)\n!KWM     stop\n!KWM  endif\n!KWM\n!KWM  call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n!KWM  call set(xl, xr, xb, xt, 1.0, float(gridinfo%idim), 1.0, float(gridinfo%jdim), ml)\n!KWM\n!KWM\n!KWMend subroutine plotmap\n!KWM\n!\n! ############################################################################################################\n!\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/Makefile",
    "content": "SHELL=/bin/sh\n.SUFFIXES:\t\n.SUFFIXES:\t.F .o .exe\nOBJS=\tmodule_plotts_graphics.o \\\n\tmodule_ptdata.o \\\n\tldasout_timeseries.o \\\n\tkwm_date_utilities.o \\\n\tkwm_string_utilities.o \\\n\tllxy_generic.o \\\n\tlccone.o\n\n\nF90=\tifort -warn unused\nFFLAGS=-free\n\n# F90=\tpgf90\n# FFLAGS=-Mfree\n\nRM = \trm -f\nNCARGLIBS=\t-L/usr/local/ncarg/lib -L/usr/X11R6/lib \\\n\t\t-lncarg -lncarg_gks -lncarg_c -lX11 -lXext \\\n\t        -L/usr/lib/gcc/i386-redhat-linux/3.4.6 -lg2c\n\nCMD=\tpltts.exe\n\n\n# Lines from here on down should not need to be changed.  They are the\n# actual rules which make uses to build $(CMD).\n#\n\nall:\t$(CMD)\n\n.F.o:\n\t@echo \"\"\n\t$(F90) $(CPPINVOKE) $(CPPFLAGS) -c -I$(NETCDF)/include $(FFLAGS) $(MODDIR) $(*).F\n\n$(CMD):\t$(OBJS)\n\t$(F90) -o $(@) -I$(NETCDF)/include $(FFLAGS) $(OBJS) \\\n\t-L$(NETCDF)/lib -lnetcdf $(NCARGLIBS) \n\nclean:\n\t$(RM) *.o *~ *.exe *.mod\n#\nmodule_ptdata.o:\tkwm_string_utilities.o\nldasout_timeseries.o:\tkwm_date_utilities.o\nmodule_plotts_graphics.o:\tkwm_string_utilities.o\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/kwm_date_utilities.F",
    "content": "module kwm_date_utilities\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n!  From old date ('YYYY-MM-DD HH:MM:SS.ffff') and\n!  delta-time, compute the new date.\n\n!  on entry     -  odate  -  the old hdate.\n!                  idt    -  the change in time\n\n!  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n\n!  Local Variables\n\n!  yrold    -  indicates the year associated with \"odate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scold    -  indicates the second associated with \"odate\"\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n\n!  mday     -  a list assigning the number of days in each month\n\n!  i        -  loop counter\n!  nday     -  the integer number of days represented by \"idt\"\n!  nhour    -  the integer number of hours in \"idt\" after taking out\n!              all the whole days\n!  nmin     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days and whole hours.\n!  nsec     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days, whole hours, and whole minutes.\n\n    integer :: nlen, olen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n\n    logical :: punctuated\n    logical :: idtdy, idthr, idtmin, idtsec, idtfrac\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n!  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    olen = len(odate)\n    if (punctuated) then\n       if (olen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n    endif\n\n!  Use internal READ statements to convert the CHARACTER string\n!  date into INTEGER components.\n\n    idtdy   = .FALSE.\n    idthr   = .FALSE.\n    idtmin  = .FALSE.\n    idtsec  = .FALSE.\n    idtfrac = .FALSE.\n    read(odate(1:4),  '(i4)') yrold\n    if (punctuated) then\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.13) then\n          idthr = .TRUE.\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             idtmin = .TRUE.\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                idtsec = .TRUE.\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   idtfrac = .TRUE.\n                   read(odate(21:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    else ! Not punctuated\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.10) then\n          idthr = .TRUE.\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             idtmin = .TRUE.\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                idtsec = .TRUE.\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   idtfrac = .TRUE.\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n!  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n!  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n!  Check that the fractional part  of ODATE makes sense.\n\n!KWM      IF ((scold.GT.59).or.(scold.LT.0)) THEN\n!KWM         WRITE(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n!KWM         opass = .FALSE.\n!KWM      END IF\n\n    if (.not.opass) then\n       write(*,*) 'Crazy ODATE: ', odate(1:olen), olen\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n\n!  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (idtfrac) then !idt should be in fractions of seconds\n       if (punctuated) then\n          ifrc = olen-14\n       else\n          ifrc = olen-20\n       endif\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (idtsec) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (idtmin) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (idthr) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (idtdy) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            olen\n       write(*,*) odate(1:olen)\n       call abort()\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n!  Now construct the new mdate\n\n    nlen = LEN(ndate)\n\n    if (punctuated) then\n\n       if (nlen.gt.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:19)//'.'//hfrc(31-nlen:10)\n\n       else if (nlen.eq.19.or.nlen.eq.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n          if (nlen.eq.20) ndate = ndate(1:19)//'.'\n\n       else if (nlen.eq.16) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (nlen.eq.13) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n       if (olen.ge.11) ndate(11:11) = sp\n\n    else\n\n       if (nlen.gt.20) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:18)//hfrc(31-nlen:10)\n\n       else if (nlen.eq.14) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n14        format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.12) then\n          write(ndate,12) yrnew, monew, dynew, hrnew, minew\n12        format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,210) yrnew, monew, dynew, hrnew\n210       format(i4,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.8) then\n          write(ndate,8) yrnew, monew, dynew\n8         format(i4,i2.2,i2.2)\n\n       else\n          stop \"DATELEN PROBLEM\"\n       end if\n    endif\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n    implicit none\n\n!  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n!  compute the time difference.\n\n!  on entry     -  newdate  -  the new hdate.\n!                  olddate  -  the old hdate.\n\n!  on exit      -  idt    -  the change in time.\n!                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n!  Local Variables\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  yrold    -  indicates the year associated with \"odate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n!  scold    -  indicates the second associated with \"odate\"\n!  i        -  loop counter\n!  mday     -  a list assigning the number of days in each month\n\n! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    integer :: olen, nlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), i, newdys, olddys\n    logical :: npass, opass\n    integer :: isign\n    integer :: ifrc\n\n    logical :: punctuated\n\n    olen = len(olddate)\n    nlen = len(newdate)\n    if (nlen.ne.olen) then\n       write(*,'(\"GETH_IDTS: NLEN /= OLEN: \", A, 3x, A)') newdate(1:nlen), olddate(1:olen)\n       call abort\n    endif\n\n    if (olddate.gt.newdate) then\n       isign = -1\n\n       ifrc = olen\n       olen = nlen\n       nlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       isign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n\n!  Break down old and new hdates into parts\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(odate(1:4),  '(i4)') yrold\n    read(ndate(1:4),  '(i4)') yrnew\n\n    if (punctuated) then\n\n!  Break down old hdate into parts\n\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       if (olen.ge.13) then\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   if (olen.eq.21) then\n                      read(odate(21:21),'(i1)') frold\n                   else if (olen.eq.22) then\n                      read(odate(21:22),'(i2)') frold\n                   else if (olen.eq.23) then\n                      read(odate(21:23),'(i3)') frold\n                   else if (olen.eq.24) then\n                      read(odate(21:24),'(i4)') frold\n                   endif\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(6:7),  '(i2)') monew\n       read(ndate(9:10), '(i2)') dynew\n       if (nlen.ge.13) then\n          read(ndate(12:13),'(i2)') hrnew\n          if (nlen.ge.16) then\n             read(ndate(15:16),'(i2)') minew\n             if (nlen.ge.19) then\n                read(ndate(18:19),'(i2)') scnew\n                if (nlen.gt.20) then\n                   read(ndate(21:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    else\n\n!  Break down old hdate into parts\n\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       if (olen.ge.10) then\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(5:6),  '(i2)') monew\n       read(ndate(7:8), '(i2)') dynew\n       if (nlen.ge.10) then\n          read(ndate(9:10),'(i2)') hrnew\n          if (nlen.ge.12) then\n             read(ndate(11:12),'(i2)') minew\n             if (nlen.ge.14) then\n                read(ndate(13:14),'(i2)') scnew\n                if (nlen.ge.15) then\n                   read(ndate(15:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n!  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n       print*, 'GETH_IDTS:  Month of NDATE = ', monew\n       npass = .false.\n    end if\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n       opass = .false.\n    end if\n\n!  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    endif\n\n!  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    end if\n\n!  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n       npass = .false.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n       opass = .false.\n    end if\n\n!  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n       npass = .false.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n       opass = .false.\n    end if\n\n!  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n       npass = .false.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'Screwy NDATE: ', ndate(1:nlen)\n       call abort()\n    end if\n\n    if (.not. opass) then\n       print*, 'Screwy ODATE: ', odate(1:olen)\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n!  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n!  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n!  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (punctuated) then\n       if (olen.gt.10) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.13) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.16) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.20) then\n                   ifrc = olen-20\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    else\n       if (olen.gt.8) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.10) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.12) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.14) then\n                   ifrc = olen-14\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    endif\n\n    if (isign .eq. -1) then\n       idt = idt * isign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n!\n! Compute the number of days in February for the given year.\n!\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n!\n! Compute the number of days in the month of given date hdate.\n!\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    if (hdate(5:5) == \"-\") then\n       read(hdate(1:7), '(I4,1x,I2)') year, month\n    else\n       read(hdate(1:6), '(I4,I2)') year, month\n    endif\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\nend module kwm_date_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/kwm_string_utilities.F",
    "content": "module kwm_string_utilities\n\ncontains\n\n  subroutine strrep(string, rep1, rep2)\n    ! In string 1, replace expression rep1 with expression rep2.\n    ! if rep2 is shorter than rep1, fill the end of the string\n    ! with blanks\n\n    implicit none\n    character(len=*) :: string, rep1, rep2\n    integer :: idx, inlen, len1, len2\n\n    do\n       inlen = len(string)\n       len1 = len(rep1)\n       len2 = len(rep2)\n       idx = index(string, rep1)-1\n\n       if (idx == -1) then\n          return\n       else\n          string = string(1:idx)// rep2 // &\n               string((idx+len1+1):inlen) // &\n               \"                                                    \"\n       endif\n    enddo\n\n  end subroutine strrep\n\n\n  character(len=1024) function unblank(string) result(return_string)\n    ! Remove blanks (and tabs [char(9)] from string\n    implicit none\n    character(len=*), intent(in) :: string\n    integer :: i, j\n\n    return_string = \"\"\n\n    if ( verify(string,\" \"//char(9)) == 0 ) then\n       stop 'String is all blanks.'\n    endif\n\n    j = 0\n    do i = 1, len(string)\n       if ((string(i:i).ne.' ').and.(string(i:i).ne.char(9))) then\n          j = j + 1\n          return_string(j:j) = string(i:i)\n       endif\n    enddo\n\n  end function unblank\n\n!KWM  character function upcase(h)\n!KWM    implicit none\n!KWM    character :: h\n!KWM\n!KWM    if ((ichar(h).ge.96) .and. (ichar(h).le.123)) then\n!KWM       upcase = char(ichar(h)-32)\n!KWM    else\n!KWM       upcase = h\n!KWM    endif\n!KWM\n!KWM  end function upcase\n\n  character(len=256) function upcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \"\"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.96) .and. (ichar(h(i:i)).le.123)) then\n          return_string(i:i) = char(ichar(h(i:i))-32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function upcase\n\n!KWM  character function downcase(h)\n!KWM    implicit none\n!KWM    character h\n!KWM\n!KWM    if ((ichar(h).ge.65) .and. (ichar(h).le.90)) then\n!KWM       downcase = char(ichar(h)+32)\n!KWM    else\n!KWM       downcase = h\n!KWM    endif\n!KWM  end function downcase\n\n  character(len=256) function downcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \"\"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.65) .and. (ichar(h(i:i)).le.90)) then\n          return_string(i:i) = char(ichar(h(i:i))+32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function downcase\n\n\nend module kwm_string_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/lccone.F",
    "content": "subroutine lccone (fsplat,ssplat,sign,confac)\n  real, parameter :: conv=0.01745329251994\n  integer :: sign\n  real :: fsplat,ssplat,confac\n  if (abs(fsplat-ssplat).lt.1.E-2) then\n     confac = sin(fsplat*conv)\n  else\n     confac = log10(cos(fsplat*conv))-log10(cos(ssplat*conv))\n     confac = confac/(log10(tan((45.-float(sign)*fsplat/2.)*conv))-&\n          log10(tan((45.-float(sign)*ssplat/2.)*conv)))\n  endif\nend subroutine lccone\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/ldasout_timeseries.F",
    "content": "program ldasout_timeseries\n  use kwm_date_utilities\n  use module_plotts_graphics\n  use pt_data\n  implicit none\n\n  integer, parameter :: namelist_fortran_unit = 11\n\n  character(len=256) :: ldasout_flnm_template\n  character(len=256) :: diff_flnm_template\n  character(len=10) :: nowdate\n\n  real, allocatable, dimension(:)   :: array\n  real, allocatable, dimension(:)   :: array1\n  integer :: idt, i, ierr\n  integer :: ival, jval\n  logical, dimension(1000) :: Metadata = .FALSE.\n  integer :: loopcount\n\n  call read_fileinfo_namelist(namelist_fortran_unit, ldasout_flnm_template, & \n       diff_flnm_template)\n\n  call init_ncargks(\"test.cgm\")\n\n  loopcount = 0\n  do\n     call read_plotinfo_namelist(namelist_fortran_unit, ierr)\n     if (ierr /= 0) exit\n     loopcount = loopcount + 1\n     print*, 'Fldname = \"'//trim(pltts_parameter%fldname)//'\"'\n\n     call geth_idts(pltts_parameter%enddate, pltts_parameter%startdate, idt)\n     allocate(array (0:idt/pltts_parameter%time_interval))\n     allocate(array1(0:idt/pltts_parameter%time_interval))\n\n     nowdate = pltts_parameter%startdate\n\n     ! print*, 'pltts_parameter = ', pltts_parameter\n     do while (nowdate <= pltts_parameter%enddate)\n\n        call geth_idts(nowdate, pltts_parameter%startdate, i)\n        i = i / pltts_parameter%time_interval\n\n        call get_point_data(trim(pltts_parameter%fldname), pltts_parameter%latitude, pltts_parameter%longitude, &\n             ldasout_flnm_template, nowdate, array(i), pltts_parameter%soil_level, ival, jval)\n\n        if (diff_flnm_template /= \"\") then\n           call get_point_data(trim(pltts_parameter%fldname),pltts_parameter%latitude, pltts_parameter%longitude, & \n                diff_flnm_template, nowdate, array1(i), &\n                pltts_parameter%soil_level, ival, jval)\n           array(i) = array(i) - array1(i)\n        endif\n\n        if (.not. metadata(loopcount)) then\n           metadata(loopcount) = .TRUE.\n           write(100+loopcount,'(\"Info: \", A)')       trim(pltts_parameter%info)\n           write(100+loopcount,'(\"Var:  \", A)')       trim(pltts_parameter%fldname)\n           write(100+loopcount,'(\"Level: \", G20.12)') pltts_parameter%soil_level\n           write(100+loopcount,'(\"Lat: \", G20.12)')   pltts_parameter%latitude\n           write(100+loopcount,'(\"Lon: \", G20.12)')   pltts_parameter%longitude\n           write(100+loopcount,'(\"X: \", G20.12)')     ival\n           write(100+loopcount,'(\"Y: \", G20.12)')     jval\n           write(100+loopcount,'(\"#\")')\n        endif\n        write(100+loopcount,'(A10, G20.12)') nowdate, array(i)\n\n        call geth_newdate(nowdate, nowdate, pltts_parameter%time_interval)\n     enddo\n\n     call pltts(array, 0, idt/pltts_parameter%time_interval)\n\n     deallocate(array)\n     deallocate(array1)\n\n  enddo\n\n  call close_ncargks\n\ncontains\n\n  subroutine pltts(data, lowdim, highdim)\n    integer, intent(in) :: lowdim, highdim\n    real, dimension(lowdim:highdim), intent(in) :: data\n    integer :: intv\n    character(len=10) :: sd, ed\n    character(len=256) :: text\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n    real :: x1\n    integer :: markint, ndays,  nmarks\n    sd = pltts_parameter%startdate\n    ed = pltts_parameter%enddate\n\n    call set(.15, .95, .2, .6, float(lowdim), float(highdim), &\n         pltts_parameter%y_minimum, pltts_parameter%y_maximum, 1)\n    intv = (pltts_parameter%y_maximum-pltts_parameter%y_minimum)/pltts_parameter%y_interval\n    call gasetc(\"XLF\", \"(I0)\")\n    call periml(1,0,intv,0)\n\n    ! print*, 'color = ', trim(pltts_parameter%color), data\n    call gsplci(color_index(trim(pltts_parameter%color)))\n    call frstpt(float(lowdim), data(lowdim))\n    do i = lowdim+1, highdim\n       call vector(float(i), data(i))\n    enddo\n    call plotif(0., 0., 2)\n    call gsplci(color_index(\"black\"))\n\n    !\n    ! And annotate\n    !\n    call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n    call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n\n    call line(0.,0.,0.,1.)\n    call line(0.,1.,1.,1.)\n    call line(1.,1.,1.,0.)\n    call line(1.,0.,0.,0.)\n\n    call pcseti(\"CC\", color_index(trim(pltts_parameter%color)))\n    write (text, '(A, 3x, \"Soil level \", I2)') trim(pltts_parameter%fldname), pltts_parameter%soil_level\n    call pchiqu(0.55, 0.90 - (0.04*pltts_parameter%count), trim(text), 0.018, 0.0, 0.0)\n    call pcseti(\"CC\", color_index(\"black\"))\n\n    call pchiqu(0.55, 0.12, \"From \"//&\n         &sd(1:4)//\"-\"//sd(5:6)//\"-\"//sd(7:8)//\" / \"//sd(9:10)//\" Z  to  \"//&\n         &ed(1:4)//\"-\"//ed(5:6)//\"-\"//ed(7:8)//\" / \"//ed(9:10)//\" Z\", &\n         0.015, 0.0, 0.0)\n\n    ! How many marks do we add?\n    markint = 0\n    nmarks = 1000\n    ndays = (highdim-lowdim) * pltts_parameter%time_interval / 24\n    print*, 'ndays = ', ndays\n    do while (nmarks > 30)\n       markint = markint + 1\n       nmarks = ndays / markint\n    enddo\n\n    print*, 'markint = ', markint\n\n    nmarks = 0\n    do i = lowdim, highdim, 1\n       call geth_newdate(nowdate, pltts_parameter%startdate, i*pltts_parameter%time_interval)\n       if (nowdate(9:10) == \"00\") then\n          if (mod(nmarks,markint) == 0) then\n             x1 = xl + real(i-lowdim)/real(highdim-lowdim)*(xr-xl)\n             call line(x1,xb,x1,xb+0.01)\n          endif\n          if (mod(nmarks,markint*5) == 0) then\n             call line(x1,xb,x1,xb+0.02)\n             if (nmarks == 0) then\n                call pchiqu(x1, xb-0.0225, nowdate(1:4)//\"/~C~\"//nowdate(5:6)//\"-\"//nowdate(7:8), 0.010, 0., 0.)\n             else\n                call pchiqu(x1, xb-0.015, nowdate(5:6)//\"-\"//nowdate(7:8), 0.010, 0., 0.)\n             endif\n          endif\n          nmarks = nmarks + 1\n       endif\n    enddo\n\n    nowdate = pltts_parameter%enddate\n    call pchiqu(xr, xb-0.0225, nowdate(1:4)//\"/~C~\"//nowdate(5:6)//\"-\"//nowdate(7:8), 0.010, 0., 0.)\n\n\n    if (pltts_parameter%callframe) then\n       call frame()\n    endif\n\n  end subroutine pltts\n\n\nend program ldasout_timeseries\n\n!\n! ############################################################################################################\n!\n\nsubroutine read_fileinfo_namelist(namelist_fortran_unit, ldasout_flnm_template, &\n   diff_flnm_template)\n  use module_plotts_graphics\n  implicit none\n  integer, intent(in) :: namelist_fortran_unit\n  character(len=256)  :: ldasout_flnm_template\n  character(len=256)  :: diff_flnm_template\n  character(len=10)   :: plot_startdate\n  character(len=10)   :: plot_enddate\n  integer             :: plot_interval\n\n  namelist/file_info/ ldasout_flnm_template, plot_startdate, plot_enddate, plot_interval, diff_flnm_template\n\n  plot_interval = 1\n  diff_flnm_template = \"\"\n\n  open(namelist_fortran_unit, file=\"namelist.pltts\", status='old', form='formatted', action='read')\n\n  read(namelist_fortran_unit, file_info)\n\n  pltts_parameter%startdate = plot_startdate\n  pltts_parameter%enddate = plot_enddate\n  pltts_parameter%time_interval = plot_interval\n\nend subroutine read_fileinfo_namelist\n\n!\n! ############################################################################################################\n!\n\nsubroutine read_plotinfo_namelist(namelist_fortran_unit, ierr)\n  use module_plotts_graphics\n  implicit none\n  integer, intent(in) :: namelist_fortran_unit\n  character(len=256)  :: fldname\n  character(len=256)  :: info\n  real :: y_interval\n  real :: y_minimum\n  real :: y_maximum\n  character(len=1024) :: color\n  integer :: soil_level\n  real    :: ts_lat, ts_lon\n  logical :: lopen\n  logical :: callframe\n  integer, intent(out)  :: ierr\n\n  namelist/plot_info/ fldname, soil_level, &\n       y_interval, y_minimum, y_maximum, color, ts_lat, ts_lon, callframe, info\n\n! Default values:\n  soil_level = 1\n  ts_lat = -1.E33\n  ts_lon = -1.E33\n  if (pltts_parameter%callframe) then\n     pltts_parameter%count = 0\n  endif\n\n  inquire(namelist_fortran_unit,opened=lopen)\n  if (.not. lopen) then\n     open(namelist_fortran_unit, file=\"namelist.pltts\", status='old', form='formatted', action='read')\n  endif\n\n  read(namelist_fortran_unit, plot_info, iostat=ierr)\n  if (ierr/=0) then\n     print*, 'Read ierr = ', ierr\n     close(namelist_fortran_unit)\n     return\n  endif\n\n  if (ts_lat > -1.E25) then\n     pltts_parameter%latitude = ts_lat\n  endif\n  if (ts_lon > -1.E25) then\n     pltts_parameter%longitude = ts_lon\n  endif\n  pltts_parameter%info = info\n  pltts_parameter%fldname = fldname\n  pltts_parameter%soil_level = soil_level\n  pltts_parameter%y_interval = y_interval\n  pltts_parameter%y_minimum = y_minimum\n  pltts_parameter%y_maximum = y_maximum\n  pltts_parameter%color = trim(color)\n  pltts_parameter%callframe = callframe\n  pltts_parameter%count = pltts_parameter%count + 1\n  print*, 'lat/lon = ', pltts_parameter%latitude, pltts_parameter%longitude\n\nend subroutine read_plotinfo_namelist\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/llxy_generic.F",
    "content": "subroutine lltoxy_generic (xlat,xlon,x,y,&\n     project,dskm,reflat,reflon,refx,refy,&\n     cenlon,truelat1,truelat2)\n\n!*****************************************************************************!\n!  Notes    - Modeled after XYTOLL in the plots.o library                     !\n!*****************************************************************************!\n\n  implicit none\n\n! Input: ---------------------------------------------------------------------!\n\n  real ::             xlat       ! latitude of the point of interest.\n  real ::             xlon       ! longitude of the point of interest.\n  character(LEN=2) :: project    ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n  real ::             dskm         ! grid distance in km\n  real ::             reflat\n  real ::             reflon\n  real ::             refx\n  real ::             refy\n  real ::             cenlon     ! Grid ratio with respect to MOAD\n  real ::             truelat1   ! True latitude 1, closest to equator\n  real ::             truelat2   ! True latitude 2, closest to pole\n\n! Output: --------------------------------------------------------------------!\n\n  real ::             x          ! x location of the given (lat,lon) point\n  real ::             y          ! y location of the given (lat,lon) point\n\n!  Parameters: ---------------------------------------------------------------!\n\n  real, parameter :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter :: piovr2 = pi/2.\n!  real, parameter :: re = 6370.949     ! the radius of the earth in km\n  real, parameter :: re = 6371.2       ! the radius of the earth in km\n  real, parameter :: ce = 2.*pi*re     ! the circumference of the earth in km\n  real, parameter :: degrad = pi/180.\n\n!  Real variables: -----------------------------------------------------------!\n\n  real          :: flat1\n  real          :: confac            ! cone factor\n  real          :: rcln              ! center longitude in radians  (local)\n  real          :: dj                ! distance from pole to point  (local)\n  real          :: di                ! distance from the central\n                                     !  meridian to the point        (local)\n  real          :: bm                ! calculation variable         (local)\n\n  real :: rflt, rfln, rlat, rlon, diovrdj, disdjs, ri, rj\n  real :: ct1, st1, tt1\n  real :: isn, pi2\n  real :: londiff\n\n!****************************  subroutine begin  *****************************!\n\n\n  rlat =  xlat * degrad\n  rlon =  xlon * degrad\n  rcln = cenlon * degrad\n  flat1 = truelat1 * degrad\n  rflt = reflat * degrad\n  rfln = reflon * degrad\n\n  if ((xlon - cenlon) < -180) then\n     londiff = ((xlon-cenlon)+360.)*degrad\n  else if ((xlon - cenlon) > 180) then\n     londiff = ((xlon-cenlon)-360.)*degrad\n  else\n     londiff = (xlon-cenlon)*degrad\n  endif\n\n\n  if (project(1:2) .eq. 'ME') then\n\n     ct1 = re*cos(flat1)\n     dj = ct1 * log(tan (0.5*(rlat + piovr2)))\n     di = ct1 * (rlon - rfln)\n     y = refy +(dj + ct1 * log(cos(rflt)/(1 + sin(rflt))))/dskm\n     x = refx + di/dskm\n\n  else if (project(1:2) .eq. 'CE') then\n\n!KWM     dj = re*(rlat-rflt)\n!KWM     di = re*(rlon-rfln)\n!KWM     y = refy + dj/dskm\n!KWM     x = refx + di/dskm\n\n     ! NOTE:  Cylindrical Equidistant grid increment expressed in terms\n     ! of thousandths of degrees!\n     !  Calculate the distance from the horizontal axis to (J,I)\n     dj = xlat-reflat\n     di = xlon-reflon\n     y = refy + (dj/dskm)\n     x = refx + (di/dskm)\n\n  else if (project(1:2) .eq. 'LC') then\n\n     isn = sign(1.0, truelat2)\n     pi2 = piovr2*isn\n\n     call lccone(truelat1,truelat2,int(sign(1.0, truelat2)),confac)\n     tt1 = tan((pi2 - flat1)*0.5) ! Tangent Term 1.\n     st1 = sin (pi2 - flat1) * re/(confac*dskm)     ! Sine Term 1.\n     bm =  tan((pi2 - rlat)*0.5)\n     if ((rlon-rcln) > pi) then\n        diovrdj = -tan(((rlon-rcln)-2.*pi)*confac)\n     elseif ((rlon-rcln) < -pi) then\n        diovrdj = -tan(((rlon-rcln)+2.*pi)*confac)\n     else\n        diovrdj = -tan((rlon-rcln)*confac)\n     endif\n     disdjs = ( (bm/tt1)**confac * st1)**2\n     ! Dj: y distance (km) from pole to given x/y point.\n     dj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n     ! Di: x distance (km) from central longitude to given x/y point.\n     di = dj * diovrdj\n\n     bm = tan((pi2-rflt)*0.5)\n     if ((rfln-rcln) > pi) then\n        diovrdj = -tan(((rfln-rcln)-2.*pi)*confac)\n     else if ((rfln-rcln) < -pi) then\n        diovrdj = -tan(((rfln-rcln)+2.*pi)*confac)\n     else\n        diovrdj = -tan((rfln - rcln)*confac)\n     endif\n     disdjs = ( (bm/tt1)**confac * st1)**2\n     ! Rj: y distance (km) from pole to reference point.\n     rj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n     ! Ri: x distance (km) from central longitude to reference x/y point.\n     ri = rj * diovrdj\n     y = refy + isn*(dj - rj)\n     x = refx + (di - ri)\n\n  else if (project(1:2) .eq. 'ST') then\n\n     isn = sign(1.0, truelat1)\n     pi2 = piovr2*isn\n\n     diovrdj = -tan(rfln-rcln)\n     bm = (re/dskm)*tan(0.5*(pi2-rflt))\n     disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n     ! RJ:  Distance from pole to reference latitude along the center lon\n     rj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rfln-rcln))\n     ! RI:  Distance from center reference to requested point rlat, rlon.\n     ri = rj * diovrdj\n     diovrdj = -tan(rlon-rcln)\n     bm = (re/dskm)*tan(0.5*(pi2-rlat))\n     disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n     dj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rlon-rcln))\n     di = dj * diovrdj\n     y = refy + isn*(dj-rj)\n     x = refx + (di-ri)\n  endif\n\n!*****************************  Subroutine End  ******************************!\n\nend subroutine lltoxy_generic\n\nsubroutine xytoll_generic (x,y,xlat,xlon,&\n     project,dskm,reflat,reflon,refx,refy,&\n     cenlon, truelat1,truelat2)\n\n!*****************************************************************************!\n!  xytoll                                                                     !\n!  Purpose  - To  transform  mesoscale grid point coordinates (x,y) into      !\n!             latitude and longitude coordinates.                             !\n!                                                                             !\n!  On entry - X  and  Y are an ordered pair representing a grid point in  the !\n!             mesoscale grid.                                                 !\n!                                                                             !\n!  On exit  - XLAT, XLON contain  the latitude and longitude respectively     !\n!             that resulted from the transformation.                          !\n!                                                                             !\n!*****************************************************************************!\n  implicit none\n\n! Input\n  real ::             x         ! x (i) coordinate of point of interest\n  real ::             y         ! y (j) coordinate of point of interest\n  character(LEN=2) :: project   ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n  real ::             dskm      ! grid distance in km\n  real ::             reflat    ! latitude of the reference point\n  real ::             reflon    ! longitude of the reference point\n  real ::             refx\n  real ::             refy\n  real ::             cenlon    ! longitude of the center of the projection\n  real ::             truelat1  ! True latitude 1.\n  real ::             truelat2  ! True latitude 2.\n\n! Output\n  real ::             xlat      ! latitude of point (x,y)\n  real ::             xlon      ! longitude of point (x,y)\n\n! Parameters\n\n  real, parameter :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter :: piovr2 = pi/2.\n  real, parameter :: twopi  = pi*2.\n!  real, parameter :: re = 6370.949     ! the radius of the earth in km\n  real, parameter :: re = 6371.2\n  real, parameter :: degrad = pi/180.\n\n!  Real variables\n\n  real ::            confac           ! cone factor\n  real ::            rfln             ! reference longitude in radians  (local)\n  real ::            rflt             ! reference latitude in radians   (local)\n  real ::            rcln             ! center longitude in radians  (local)\n  real ::            dj, drp, djj     ! distance from the central\n!                                       meridian to the point        (local)\n  real ::            di,dii           ! distance from pole to point  (local)\n  real ::            bm               ! calculation variable         (local)\n  real ::            flat1\n  real ::            ct1, tt1, tt2, pi2\n  integer :: isn\n!****************************  subroutine begin  *****************************!\n\n  rflt = reflat * degrad\n  rfln = reflon * degrad\n  rcln = cenlon * degrad\n  flat1 = truelat1 * degrad\n\n!  If the projection is mercator ('ME') then ...\n\n  if (project(1:2) .eq. 'ME') then\n     di = (x-refx) * dskm\n     !  Calculate the distance the point in question is from the pole\n     dj = -re * cos(flat1)*log(cos(rflt)/(1 + sin(rflt))) + &\n          (y - refy) * dskm\n     !  Calculate the latitude desired in radians\n     xlat = 2.0 * atan(exp(dj/(re*cos(flat1)))) - piovr2\n     !  Calculate the longitude desired in radians\n     xlon = rfln + di/(re*cos(flat1))\n\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n\n! If the projection is cylindrical equidistant ('CE') then ...\n  else if (project(1:2) .eq. 'CE') then\n     ! NOTE:  Cylindrical Equidistant grid increment expressed in terms\n     ! of thousandths of degrees!\n     di = (x-refx) * dskm\n     !  Calculate the distance from the horizontal axis to (J,I)\n     dj = (y-refy) * dskm\n     !  Determine the shift north-south\n     xlat = reflat + dj\n     !  Determine the shift east-west\n     xlon = reflon + di\n\n! If the projection is lambert conic conformal ('LC') then ...\n  else if (project(1:2) .eq. 'LC') then\n\n     isn = sign(1.0, truelat2)\n     pi2 = piovr2*isn\n\n     call lccone(truelat1,truelat2,isn,confac)\n\n     tt1 = tan((pi2 - flat1)*0.5)    ! Tangent Term 1.\n     tt2 = tan((pi2 - rflt  )*0.5)    ! Tangent Term 2.\n     ct1 = -cos(flat1) * re/confac   ! cosine Term 1.\n\n     ! Calculate the (projected) distance from the pole to\n     ! the reference lat/lon.\n     drp = ct1 * (tt2/tt1)**confac\n     ! Now from the pole to the reference y along the center lon.\n     djj = drp * cos((rcln-rfln)*confac)\n\n     ! Now from the pole to the requested y along the center lon.\n     dj = djj + isn * ((y-refy)*dskm)\n     ! Now the (projected) distance from center longitude to reference x\n     dii = drp*sin((rcln-rfln)*confac)\n     ! And now from center longitude to requested X\n     di = dii + ((x-refx)*dskm)\n     !  Calculate the Big Messy equation\n     bm = tt1 * (sqrt(di**2+dj**2) /  abs(ct1))**(1.0/confac)\n     !  Calculate the desired latitude in radians\n     xlat = pi2 - 2.0*atan(bm)\n     !  Calculate the desired longitude in radians\n     xlon = rcln + (1.0/confac) * atan2(di,-dj)\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n\n!  If the projection is polar stereographic ('ST') then ...\n\n  else if (project(1:2) .eq. 'ST') then\n\n     isn = sign(1.0, truelat1)\n     pi2 = piovr2*isn\n\n\n!  Calculate the (projected) y-distance I,J lies from the pole\n\n     drp = -re*cos(rflt) * (1.0 + cos(pi2-flat1)) / (1.0 + cos(pi2-rflt))\n     djj = drp * cos(rcln-rfln)\n     dj = djj + isn*( (y-refy) * dskm )\n     dii = drp * sin(rcln-rfln)\n     di = dii + ((x-refx)*dskm)\n     ! Calculate the Big Messy quantity as would be done for LC\n     ! projections.  This quantity is different in value, same\n     ! in purpose of BM above\n     bm = (1.0/re) * sqrt(di*di + dj*dj) / (1.0 + cos(pi2-flat1))\n     !  Calculate the desired latitude in radians\n     xlat = pi2 - isn*2.0 * atan(bm)\n     !  Calculate the desired longitude in radians\n     xlon = rcln + atan2(di,-dj)\n\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n  else\n     print*, 'Unrecognized project:  ', project\n     stop\n  end if\n\n!  Make sure no values are greater than 180 degrees and none\n!  are less than -180 degrees\n\n  if (xlon .gt. 180.0)  xlon = xlon - 360.0\n  if (xlon .lt. -180.0) xlon = xlon + 360.0\n\n!*****************************  Subroutine End  ******************************!\n\nend subroutine xytoll_generic\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/module_plotts_graphics.F",
    "content": "module module_plotts_graphics\n\n  type pltts_parameter_type\n     character(len=256) :: info\n     character(len=256) :: fldname\n     integer :: soil_level\n     real :: latitude\n     real :: longitude\n     real :: y_interval\n     real :: y_minimum\n     real :: y_maximum\n     character(len=256) :: color\n     logical :: callframe\n     character(len=10) :: startdate\n     character(len=10) :: enddate\n     integer :: time_interval\n     integer :: count\n  end type pltts_parameter_type\n\n  type(pltts_parameter_type) :: pltts_parameter\n\n  type named_color\n     character(len=20) :: name\n     real :: r\n     real :: g\n     real :: b\n  end type named_color\n\n  logical :: mapped = .FALSE.\n\n  integer :: global_ncols\n  type(named_color), dimension(0:255) :: global_colorlist\n\n\ncontains\n\n!=============================================================================================\n\n  integer function color_index(name) result (icol)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer :: i\n\n    if (global_ncols == 0) then\n       global_colorlist(global_ncols) = get_x11_color(name)\n       call gscr(1, global_ncols, &\n            global_colorlist(global_ncols)%r, &\n            global_colorlist(global_ncols)%g, &\n            global_colorlist(global_ncols)%b)\n       icol = global_ncols\n       global_ncols = global_ncols + 1\n       return\n    endif\n\n    do i = 0, global_ncols-1\n       if (name == global_colorlist(i)%name) then\n          icol = i\n          return\n       endif\n    enddo\n\n    if (global_ncols < 256) then\n       global_colorlist(global_ncols) = get_x11_color(name)\n       call gscr(1, global_ncols, &\n            global_colorlist(global_ncols)%r, &\n            global_colorlist(global_ncols)%g, &\n            global_colorlist(global_ncols)%b)\n       icol = global_ncols\n       global_ncols = global_ncols + 1\n       return\n    else\n       stop \"Too many colors.\"\n    endif\n\n  end function color_index\n\n  type(named_color) function get_x11_color(name) result (c)\n    use kwm_string_utilities\n    implicit none\n    character(len=*) :: name\n    integer :: r, g, b, i\n    character(len=20) :: cname\n\n    logical, save :: already_read = .FALSE.\n    integer :: ierr, idx\n    character(len=80) :: string, stringname\n    integer, parameter :: iunit = 22\n\n    real, dimension(2500), save :: readlist_r, readlist_g, readlist_b\n    character(len=64), dimension(2500), save :: readlist_name\n    integer, save :: readlist_count = 0\n\n    if (name(1:1) == \"#\") then\n       read(name(2:7), '(Z2,Z2,Z2)') r,g,b\n       c = named_color(trim(name), float(r)/255., float(g)/255., float(b)/255.)\n       return\n    else if ((name(1:2) == \"Ox\") .or. (name(1:2) == \"0x\")) then\n       read(name(3:8), '(Z2,Z2,Z2)') r,g,b\n       c = named_color(trim(name), float(r)/255., float(g)/255., float(b)/255.)\n       return\n    endif\n\n    if (.not. already_read) then\n       already_read = .TRUE.\n       open(iunit, file=\"/usr/lib/X11/rgb.txt\", form='formatted', &\n            status='old', action='read', iostat=ierr)\n       if (ierr /= 0) then\n          open(iunit, file=\"/usr/share/X11/rgb.txt\", form='formatted', &\n               status='old', action='read', iostat=ierr)\n          if (ierr /= 0) stop \"color table\"\n       endif\n       do\n\n          read(iunit, '(A)', iostat=ierr) string\n          if (ierr /= 0) exit\n          if (string(1:1) == \"!\") cycle\n\n          stringname = \" \"\n          read(string, *) r, g, b\n          ! Find the index of the first alphabetical character\n          idx = verify(string, \" 0123456789\"//char(9)) ! char(9) is tab\n          stringname = trim(string(idx:))\n          stringname = downcase(trim(stringname))\n          stringname = unblank(trim(stringname))\n\n          readlist_count = readlist_count + 1\n          readlist_r(readlist_count) = float(r)/255.\n          readlist_g(readlist_count) = float(g)/255.\n          readlist_b(readlist_count) = float(b)/255.\n          readlist_name(readlist_count) = stringname\n\n       enddo\n\n       close(iunit)\n    endif\n\n    ! Search through readlist for name\n    do i = 1, readlist_count\n       if (name == readlist_name(i)) then\n          cname = name\n          c = named_color(cname, readlist_r(i), readlist_g(i), readlist_b(i))\n          return\n       endif\n    enddo\n\n    write(*, '(\"color not found: \", A)') trim(name)\n\n  end function get_x11_color\n\n!=============================================================================================\n\n  subroutine init_ncargks(new_cgm_name)\n! Starts off the NCAR Graphics package.\n! Opens workstation 1 as a CGM workstation.\n! Opens workstation 2 as a WISS.\n! Defines a couple of colors, and sets a couple of NCAR Graphics parameters\n!\n! If you want the gmeta file to be called something other than \"gmeta\",\n! give this subroutine the optional argument.\n    implicit none\n    character(len=*), optional, intent(in) :: new_cgm_name\n    character(len=80) :: newname\n    character(len=1) :: hdum\n    integer :: icol\n\n    call gopks(6,0)\n\n    if (present(new_cgm_name)) then\n       newname = trim(new_cgm_name)\n       call gesc(-1391, 1, newname, 1, 1, hdum)\n    endif\n\n    call gopwk(1,119,1)\n    call gopwk(2,120,3)\n    call gacwk(1)\n    call gacwk(2)\n    global_ncols = 0\n\n\n    ! call define_color(\"white\")\n    ! call define_color(\"black\")\n    ! call gscr(1, 0, 1., 1., 1.) ! White\n    ! call gscr(1, 1, 0., 0., 0.) ! Black\n    icol = color_index(\"white\")\n    icol = color_index(\"black\")\n    call pcseti(\"FN\", 21)\n    call pcsetc(\"FC\", \"~\")\n  end subroutine init_ncargks\n\n  subroutine close_ncargks\n    implicit none\n    call gdawk(1)\n    call gdawk(2)\n    call gclwk(1)\n    call gclwk(2)\n    call gclks\n  end subroutine close_ncargks\n\nend module module_plotts_graphics\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/module_ptdata.F",
    "content": "module pt_data\n\ncontains\n\n  subroutine get_point_data(fldname, lat, lon, flnm_template, nowdate, &\n       xval, level, iloc_return, jloc_return)\n\n    use netcdf\n    use kwm_string_utilities\n    implicit none\n\n    character(len=*),      intent(in) :: fldname\n    real,                  intent(in) :: lat\n    real,                  intent(in) :: lon\n    character(len=*),      intent(in) :: flnm_template\n    character(len=*),      intent(in) :: nowdate\n    integer,               intent(in) :: level\n    real,                  intent(out) :: xval\n    integer,               intent(out) :: iloc_return, jloc_return\n\n    character(len=256) :: flnm\n    integer :: ierr, ncid\n\n    integer :: iproj = -1\n    real, save :: lat1, lon1, xlonc, dxm, truelat1, truelat2\n    real, save :: xloc, yloc\n    integer, save :: iloc, jloc\n    character(len=2), parameter, dimension(3) :: project = (/\"LC\", \"ST\", \"ME\"/)\n\n    flnm = flnm_template\n    call strrep(flnm, \"<yyyymmddhh>\", nowdate)\n\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    call errhandler(ierr, \"file:  \"//trim(flnm))\n\n    if (iproj < 0) then\n\n       call gridinfo(ncid, iproj, lat1, lon1, xlonc, dxm, truelat1, truelat2)\n\n    endif\n\n!KWM       print*, 'iproj = ', iproj\n!KWM       print*, 'lat1/lon1 = ', lat1, lon1\n!KWM       print*, 'xlonc = ', xlonc\n!KWM       print*, 'dxm = ', dxm\n!KWM       print*, 'truelat1, truelat2 = ', truelat1, truelat2\n\n       call lltoxy_generic(lat, lon, xloc, yloc, &\n            project(iproj), dxm*0.001, lat1, lon1, 1.5, 1.5, &\n            xlonc, truelat1, truelat2)\n\n       iloc = nint(xloc)\n       jloc = nint(yloc)\n       iloc_return = iloc\n       jloc_return = jloc\n\n       ! print*, 'xloc, yloc = ', xloc, yloc, iloc, jloc\n\n\n    call get_value(ncid, trim(fldname), iloc, jloc, level, xval)\n\n    ierr = nf90_close(ncid)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n\n  end subroutine get_point_data\n\n  subroutine get_value(ncid, name, i, j, level, xval)\n    use netcdf\n    implicit none\n    integer, intent(in) :: ncid, i, j\n    character(len=*), intent(in) :: name\n    integer, intent(in) :: level\n    real, intent(out) :: xval\n\n    integer :: varid, ierr, ndims, soillayers_dimid\n    integer, dimension(3) :: nstart\n    integer, dimension(NF90_MAX_VAR_DIMS) :: dimids\n    logical :: threed\n\n    ierr = nf90_inq_varid(ncid, name, varid)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n! Find information about the dimensions of this variable, so we can determine whether\n! we're looking at a 2-d field or a 3-d field (not counting the time dimension).\n\n    ierr = nf90_inq_dimid(ncid, \"soil_layers_stag\", soillayers_dimid)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr)), \"  \", \"soil_layers_stag\"\n       soillayers_dimid = 1\n       ! stop\n    endif\n\n\n    ierr = nf90_inquire_variable(ncid, varid, ndims=ndims, dimids=dimids)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    ! If the <dimids> array contains an element equal to <soillayers_dimid>, then\n    ! this is a 3-d dataset.\n\n    if (any(dimids(1:ndims)==soillayers_dimid)) then\n       threed = .TRUE.\n    else\n       threed = .FALSE.\n    endif\n\n    nstart = (/ i, j, level /)\n\n    ierr = nf90_get_var(ncid, varid, xval, start=nstart)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n  end subroutine get_value\n\n  subroutine get_value_vector(ncid, name, i, j, xval)\n    use netcdf\n    implicit none\n    integer, intent(in) :: ncid, i, j\n    character(len=*), intent(in) :: name\n    real, dimension(4), intent(out) :: xval\n\n    integer :: varid, ierr\n    integer, dimension(3) :: nstart\n    integer, dimension(3) :: ncount\n\n    ierr = nf90_inq_varid(ncid, name, varid)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    nstart = (/ i, j, 1 /)\n\n    ncount = (/ 1, 1, 4 /)\n\n    ierr = nf90_get_var(ncid, varid, xval, start=nstart, count=ncount)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n  end subroutine get_value_vector\n\n  subroutine gridinfo(ncid, iproj, lat1, lon1, xlonc, dxm, truelat1, truelat2)\n    use netcdf\n    implicit none\n    integer, intent(in) :: ncid\n    integer, intent(out) :: iproj\n    real, intent(out) :: lat1, lon1, xlonc, dxm, truelat1, truelat2\n\n    integer :: ierr\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", iproj)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr)), \"  \", \"MAP_PROJ\"\n       stop\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LAT1\", lat1)\n    if (ierr /= NF90_NOERR) then\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LA1\", lat1)\n       if (ierr /= NF90_NOERR) then\n          print *, trim(nf90_strerror(ierr)), \"  \", \"LAT1 or LA1\"\n          stop\n       endif\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LON1\", lon1)\n    if (ierr /= NF90_NOERR) then\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LO1\", lon1)\n       if (ierr /= NF90_NOERR) then\n          print *, trim(nf90_strerror(ierr)), \"  \", \"LON1 or LO1\"\n          stop\n       endif\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"DX\", dxm)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", xlonc)\n    if (ierr /= NF90_NOERR) then\n       print *, trim(nf90_strerror(ierr))\n       stop\n    endif\n\n  end subroutine gridinfo\n\n  subroutine errhandler(ival, str)\n    use netcdf\n    implicit none\n    integer, intent(in) :: ival\n    character(len=*), intent(in), optional :: str\n\n    if (ival == NF90_NOERR) return\n\n    print*, \"------------------------------------------------------------\"\n    print *, trim(nf90_strerror(ival))\n    if (present(str)) print *, str\n    print*, \"------------------------------------------------------------\"\n    stop\n  end subroutine errhandler\n\nend module pt_data\n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/namelist.pltts",
    "content": "\n&file_info\n  ldasout_flnm_template = \"/d5/kmanning/WORKDIR/Run/<yyyymmddhh>.LDASOUT_DOMAIN1\"\n  plot_startdate = \"2002060100\"\n  plot_enddate   = \"2002062000\"\n  plot_interval  = 1\n/\n\n&plot_info\n  ts_lat = 38.32\n  ts_lon = -98.75\n  fldname = \"SOIL_M\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  fldname = \"SOIL_M\", soil_level = 2\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"green\"\n  callframe = .FALSE.\n/ \n\n&plot_info\n  fldname = \"SOIL_M\", soil_level = 3\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"blue\"\n  callframe = .FALSE.\n/ \n\n&plot_info\n  fldname = \"SOIL_M\", soil_level = 4\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"red2\"\n  callframe = .TRUE.\n/ \n\n&plot_info\n  fldname = \"SOIL_T\", soil_level = 1\n  y_minimum = 260.0\n  y_maximum = 310.0\n  y_interval = 5.0\n  color=\"magenta\"\n  callframe = .FALSE.\n/ \n\n&plot_info\n  fldname = \"SOIL_T\", soil_level = 2\n  y_minimum = 260.0\n  y_maximum = 310.0\n  y_interval = 5.0\n  color=\"#FF0000\"\n  callframe = .FALSE.\n/ \n&plot_info\n  fldname = \"SOIL_T\", soil_level = 3\n  y_minimum = 260.0\n  y_maximum = 310.0\n  y_interval = 5.0\n  color=\"#AA0000\"\n  callframe = .FALSE.\n/ \n&plot_info\n  fldname = \"SOIL_T\", soil_level = 4\n  y_minimum = 260.0\n  y_maximum = 310.0\n  y_interval = 5.0\n  color=\"#00AA00\"\n  callframe = .TRUE.\n/ \n\n&plot_info\n  fldname = \"GRDFLX\", \n  y_minimum = -100.0\n  y_maximum = 600.0\n  y_interval = 25.0\n  color=\"blue\"\n  callframe = .TRUE.\n/ \n"
  },
  {
    "path": "src/Land_models/Noah/GRAPHICS/TIME_SERIES/namelist.pltts.sample",
    "content": "\n&file_info\n  ldasout_flnm_template = \"/wig/kmanning/more_hrldas/grib2/redesign/STEP/resetNO/<yyyymmddhh>.LDASIN_DOMAIN1\"\n  plot_startdate = \"2002052000\"\n  plot_enddate   = \"2002052306\"\n  plot_interval  = 1\n/\n\n&plot_info\n  info = \"IHOP Station 1\"\n  ts_lat = 36.4728\n  ts_lon = -100.6179\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  info = \"IHOP Station 2\"\n  ts_lat = 36.6221\n  ts_lon = -100.6270\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  info = \"IHOP Station 3\"\n  ts_lat = 36.8610\n  ts_lon = -100.5945\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  info = \"IHOP Station 4\"\n  ts_lat = 37.3579\n  ts_lon = -98.2446\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  info = \"IHOP Station 5\"\n  ts_lat = 37.3781\n  ts_lon = -98.1636\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  info = \"IHOP Station 6\"\n  ts_lat = 37.3545\n  ts_lon = -97.6533\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  info = \"IHOP Station 7\"\n  ts_lat = 37.3132\n  ts_lon = -96.9387\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  info = \"IHOP Station 8\"\n  ts_lat = 37.4070\n  ts_lon = -96.7656\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n\n&plot_info\n  info = \"IHOP Station 9\"\n  ts_lat = 37.4103\n  ts_lon = -96.5671\n  fldname = \"SWDOWN\", soil_level = 1\n  y_minimum = 0.0\n  y_maximum = 0.4\n  y_interval = 0.125\n  color=\"cyan\"\n  callframe = .FALSE.\n/\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/GRIB_TABLES/GRIB1_PARAMETER_TABLE",
    "content": "001 | Pressure                                                                   | Pa                | PRES\n002 | Pressure reduced to MSL                                                    | Pa                | PRMSL\n003 | Pressure tendency                                                          | Pa s{-1}          | PTEND\n005 | ICAO Standard Atmosphere Reference Hgt                                     | m                 | ICAHT\n006 | Geopotential                                                               | m{2} s{-2}        | GP\n007 | Geopotential height                                                        | gpm               | HGT\n008 | Geometric height                                                           | m                 | DIST\n009 | Standard deviation of height                                               | m                 | HSTDV\n010 | Total ozone                                                                | Dobson            | TOZNE\n011 | Temperature                                                                | K                 | TMP\n012 | Virtual temperature                                                        | K                 | VTMP\n013 | Potential temperature                                                      | K                 | POT\n014 | Pseudo-adiabatic potential temperature or equivalent potential temperature | K                 | EPOT\n015 | Maximum temperature                                                        | K                 | T MAX\n016 | Minimum temperature                                                        | K                 | T MIN\n017 | Dew point temperature                                                      | K                 | DPT\n018 | Dew point depression (or deficit)                                          | K                 | DEPR\n019 | Lapse rate                                                                 | K m{-1}           | LAPR\n020 | Visibility                                                                 | m                 | VIS\n021 | Radar Spectra (1)                                                          | -                 | RDSP1\n022 | Radar Spectra (2)                                                          | -                 | RDSP2\n023 | Radar Spectra (3)                                                          | -                 | RDSP3\n024 | Parcel lifted index (to 500 hPa)                                           | K                 | PLI\n025 | Temperature anomaly                                                        | K                 | TMP A\n026 | Pressure anomaly                                                           | Pa                | PRESA\n027 | Geopotential height anomaly                                                | gpm               | GP A\n028 | Wave Spectra (1)                                                           | -                 | WVSP1\n029 | Wave Spectra (2)                                                           | -                 | WVSP2\n030 | Wave Spectra (3)                                                           | -                 | WVSP3\n031 | Wind direction (from which blowing)                                        | deg true          | WDIR\n032 | Wind speed                                                                 | m s{-1}           | WIND\n033 | u-component of wind                                                        | m s{-1}           | U GRD\n034 | v-component of wind                                                        | m s{-1}           | V GRD\n035 | Stream function                                                            | m{2} s{-1}        | STRM\n036 | Velocity potential                                                         | m{2} s{-1}        | V POT\n037 | Montgomery stream function                                                 | m{2} s{-2}        | MNTSF\n038 | Sigma coord. vertical velocity                                             | s{-1}             | SGCVV\n039 | Pressure Vertical velocity                                                 | Pa s{-1}          | V VEL\n040 | Geometric Vertical velocity                                                | m s{-1}           | DZDT\n041 | Absolute vorticity                                                         | s{-1}             | ABS V\n042 | Absolute divergence                                                        | s{-1}             | ABS D\n043 | Relative vorticity                                                         | s{-1}             | REL V\n044 | Relative divergence                                                        | s{-1}             | REL D\n045 | Vertical u-component shear                                                 | s{-1}             | VUCSH\n046 | Vertical v-component shear                                                 | s{-1}             | VVCSH\n047 | Direction of current                                                       | deg true          | DIR C\n048 | Speed of current                                                           | m s{-1}           | SP C\n049 | u-component of current                                                     | m s{-1}           | UOGRD\n050 | v-component of current                                                     | m s{-1}           | VOGRD\n051 | Specific humidity                                                          | kg kg{-1}         | SPF H\n052 | Relative humidity                                                          | %                 | R H\n053 | Humidity mixing ratio                                                      | kg kg{-1}         | MIXR\n054 | Precipitable water                                                         | kg m{-2}          | P WAT\n055 | Vapor pressure                                                             | Pa                | VAPP\n056 | Saturation deficit                                                         | Pa                | SAT D\n057 | Evaporation                                                                | kg m{-2}          | EVP\n058 | Cloud Ice                                                                  | kg m{-2}          | C ICE\n059 | Precipitation rate                                                         | kg m{-2} s{-1}    | PRATE\n060 | Thunderstorm probability                                                   | %                 | TSTM\n061 | Total precipitation                                                        | kg m{-2}          | A PCP\n062 | Large scale precipitation (non-conv.)                                      | kg m{-2}          | NCPCP\n063 | Convective precipitation                                                   | kg m{-2}          | ACPCP\n064 | Snowfall rate water equivalent                                             | kg m{-2} s{-1}    | SRWEQ\n065 | Water equiv. of accum. snow depth                                          | kg m{-2}          | WEASD\n066 | Snow depth                                                                 | m                 | SNO D\n067 | Mixed layer depth                                                          | m                 | MIXHT\n068 | Transient thermocline depth                                                | m                 | TTHDP\n069 | Main thermocline depth                                                     | m                 | MTHD\n070 | Main thermocline anomaly                                                   | m                 | MTH A\n071 | Total cloud cover                                                          | %                 | T CDC\n072 | Convective cloud cover                                                     | %                 | CDCON\n073 | Low cloud cover                                                            | %                 | L CDC\n074 | Medium cloud cover                                                         | %                 | M CDC\n075 | High cloud cover                                                           | %                 | H CDC\n076 | Cloud water                                                                | kg m{-2}          | C WAT\n077 | Best lifted index (to 500 hPa)                                             | K                 | BLI\n078 | Convective snow                                                            | kg m{-2}          | SNO C\n079 | Large scale snow                                                           | kg m{-2}          | SNO L\n080 | Water Temperature                                                          | K                 | WTMP\n081 | Land-sea mask(land=1;sea=0)                                                | fraction          | LAND\n082 | Deviation of sea level from mean                                           | m                 | DSL M\n083 | Surface roughness                                                          | m                 | SFC R\n084 | Albedo                                                                     | %                 | ALBDO\n085 | Soil temperature                                                           | K                 | TSOIL\n086 | Soil moisture content                                                      | kg m{-2}          | SOIL M\n087 | Vegetation                                                                 | %                 | VEG\n088 | Salinity                                                                   | kg kg{-1}         | SALTY\n089 | Density                                                                    | kg m{-3}          | DEN\n090 | Water runoff                                                               | kg m{-2}          | WATR\n091 | Ice concentration (ice=1;no ice=0)                                         | fraction          | ICE C\n092 | Ice thickness                                                              | m                 | ICETK\n093 | Direction of ice drift                                                     | deg. true         | DICED\n094 | Speed of ice drift                                                         | m s{-1}           | SICED\n095 | u-component of ice drift                                                   | m s{-1}           | U ICE\n096 | v-component of ice drift                                                   | m s{-1}           | V ICE\n097 | Ice growth rate                                                            | m s{-1}           | ICE G\n098 | Ice divergence                                                             | s{-1}             | ICE D\n099 | Snow melt                                                                  | kg m{-2}          | SNO M\n100 | Significant height of combined wind waves and swell                        | m                 | HTSGW\n101 | Direction of wind waves (from which)                                       | deg true          | WVDIR\n102 | Significant height of wind waves                                           | m                 | WVHGT\n103 | Mean period of wind waves                                                  | s                 | WVPER\n104 | Direction of swell waves                                                   | deg true          | SWDIR\n105 | Significant height of swell waves                                          | m                 | SWELL\n106 | Mean period of swell waves                                                 | s                 | SWPER\n107 | Primary wave direction                                                     | deg true          | DIRPW\n108 | Primary wave mean period                                                   | s                 | PERPW\n109 | Secondary wave direction                                                   | deg true          | DIRSW\n110 | Secondary wave mean period                                                 | s                 | PERSW\n111 | Net short-wave radiation (surface)                                         | W m{-2}           | NSWRS\n112 | Net long wave radiation (surface)                                          | W m{-2}           | NLWRS\n113 | Net short-wave radiation (top of atmos.)                                   | W m{-2}           | NSWRT\n114 | Net long wave radiation (top of atmos.)                                    | W m{-2}           | NLWRT\n115 | Long wave radiation                                                        | W m{-2}           | LWAVR\n116 | Short wave radiation                                                       | W m{-2}           | SWAVR\n117 | Global radiation                                                           | W m{-2}           | G RAD\n118 | Brightness temperature                                                     | K                 | BRTMP\n119 | Long-wave radiation                                                        | W/srm{2}          | LWRAD\n120 | Short-wave radiation                                                       | W/srm{2}          | SWRAD\n121 | Latent heat net flux                                                       | W m{-2}           | LHTFL\n122 | Sensible heat net flux                                                     | W m{-2}           | SHTFL\n123 | Boundary layer dissipation                                                 | W m{-2}           | BLYDP\n124 | Momentum flux, u component                                                 | N m{-2}           | U FLX\n125 | Momentum flux, v component                                                 | N m{-2}           | V FLX\n126 | Wind mixing energy                                                         | J                 | WMIXE\n127 | Image data                                                                 | -                 | IMG D\n128 | Mean Sea Level Pressure (Standard Atmosphere Reduction)                    | Pa                | MSLSA\n129 | Mean Sea Level Pressure (MAPS System Reduction)                            | Pa                | MSLMA\n130 | Mean Sea Level Pressure (ETA Model Reduction)                              | Pa                | MSLET\n131 | Surface lifted index                                                       | K                 | LFT X\n132 | Best (4 layer) lifted index                                                | K                 | 4LFTX\n133 | K index                                                                    | K                 | K X\n134 | Sweat index                                                                | K                 | S X\n135 | Horizontal moisture divergence                                             | kg kg{-1} s{-1}   | MCONV\n136 | Vertical speed shear                                                       | 1 s{-1}           | VW SH\n137 | 3-hr pressure tendency (Std. Atmos. Reduction)                             | Pa s{-1}          | TSLSA\n138 | Brunt-Vaisala frequency (squared)                                          | s{-2}             | BVF 2\n139 | Potential vorticity (density weighted)                                     | s{-1} m{-1}       | PV MW\n140 | Categorical rain  (yes=1; no=0)                                            | non-dim           | CRAIN\n141 | Categorical freezing rain  (yes=1; no=0)                                   | non-dim           | CFRZR\n142 | Categorical ice pellets  (yes=1; no=0)                                     | non-dim           | CICEP\n143 | Categorical snow  (yes=1; no=0)                                            | non-dim           | CSNOW\n144 | Volumetric soil moisture content                                           | fraction          | SOILW\n145 | Potential evaporation rate                                                 | W m{-2}           | PEVPR\n146 | Cloud workfunction                                                         | J kg{-1}          | CWORK\n147 | Zonal flux of gravity wave stress                                          | N m{-2}           | U-GWD\n148 | Meridional flux of gravity wave stress                                     | N m{-2}           | V-GWD\n149 | Potential vorticity                                                        | m{2} s{-1} kg{-1} | PV\n150 | Covariance between meridional and zonal components of the wind             | m{2} s{-2}        | COVMZ\n151 | Covariance between temperature and zonal component of the wind             | K m s{-1}         | COVTZ\n152 | Covariance between temperature and meridional component of the wind        | K m s{-1}         | COVTM\n153 | Cloud water                                                                | kg kg{-1}         | CLWMR\n154 | Ozone mixing ratio                                                         | kg kg{-1}         | O3MR\n155 | Ground Heat Flux                                                           | W m{-2}           | GFLUX\n156 | Convective inhibition                                                      | J kg{-1}          | CIN\n157 | Convective Available Potential Energy                                      | J kg{-1}          | CAPE\n158 | Turbulent Kinetic Energy                                                   | J kg{-1}          | TKE\n159 | Condensation pressure of parcel lifted from indicated surface              | Pa                | CONDP\n160 | Clear Sky Upward Solar Flux                                                | W m{-2}           | CSUSF\n161 | Clear Sky Downward Solar Flux                                              | W m{-2}           | CSDSF\n162 | Clear Sky upward long wave flux                                            | W m{-2}           | CSULF\n163 | Clear Sky downward long wave flux                                          | W m{-2}           | CSDLF\n164 | Cloud forcing net solar flux                                               | W m{-2}           | CFNSF\n165 | Cloud forcing net long wave flux                                           | W m{-2}           | CFNLF\n166 | Visible beam downward solar flux                                           | W m{-2}           | VBDSF\n167 | Visible diffuse downward solar flux                                        | W m{-2}           | VDDSF\n168 | Near IR beam downward solar flux                                           | W m{-2}           | NBDSF\n169 | Near IR diffuse downward solar flux                                        | W m{-2}           | NDDSF\n172 | Momentum flux                                                              | N m{-2}           | M FLX\n173 | Mass point model surface                                                   | non-dim           | LMH\n174 | Velocity point model surface                                               | non-dim           | LMV\n175 | Model layer number (from bottom up)                                        | non-dim           | MLYNO\n176 | latitude (-90 to +90)                                                      | deg               | NLAT\n177 | east longitude (0-360)                                                     | deg               | ELON\n181 | x-gradient of log pressure                                                 | m{-1}             | LPS X\n182 | y-gradient of log pressure                                                 | m{-1}             | LPS Y\n183 | x-gradient of height                                                       | m m{-1}           | HGT X\n184 | y-gradient of height                                                       | m m{-1}           | HGT Y\n189 | Virtual potential temperature                                              | K                 | VPTMP\n190 | Storm relative helicity                                                    | m{2} s{-2}        | HLCY\n191 | Probability from ensemble                                                  | numeric           | PROB\n192 | Probability from ensemble normalized with respect to climate expectancy    | numeric           | PROBN\n193 | Probability of precipitation                                               | %                 | POP\n194 | Probability of frozen precipitation                                        | %                 | CPOFP\n195 | Probability of freezing precipitation                                      | %                 | CPOZP\n196 | u-component of storm motion                                                | m s{-1}           | USTM\n197 | v-component of storm motion                                                | m s{-1}           | VSTM\n201 | Ice-free water surface                                                     | %                 | ICWAT\n204 | downward short wave rad. flux                                              | W m{-2}           | DSWRF\n205 | downward long wave rad. flux                                               | W m{-2}           | DLWRF\n206 | Ultra violet index (1 hour integration centered at solar noon)             | J m{-2}           | UVI\n207 | Moisture availability                                                      | %                 | MSTAV\n208 | Exchange coefficient                                                       | kg m{-3} m s{-1}  | SFEXC\n209 | No. of mixed layers next to surface                                        | integer           | MIXLY\n211 | upward short wave rad. flux                                                | W m{-2}           | USWRF\n212 | upward long wave rad. flux                                                 | W m{-2}           | ULWRF\n213 | Amount of non-convective cloud                                             | %                 | CDLYR\n214 | Convective Precipitation rate                                              | kg m{-2} s{-1}    | CPRAT\n215 | Temperature tendency by all physics                                        | K s{-1}           | TTDIA\n216 | Temperature tendency by all radiation                                      | K s{-1}           | TTRAD\n217 | Temperature tendency by non-radiation physics                              | K s{-1}           | TTPHY\n218 | precip.index(0.0-1.00)(see note)                                           | fraction          | PREIX\n219 | Std. dev. of IR T over 1x1 deg area                                        | K                 | TSD1D\n220 | Natural log of surface pressure                                            | ln(kPa)           | NLGSP\n221 | Planetary boundary layer height                                            | m                 | HPBL\n222 | 5-wave geopotential height                                                 | gpm               | 5WAVH\n223 | Plant canopy surface water                                                 | kg m{-2}          | C WAT\n226 | Blackadar's mixing length scale                                            | m                 | BMIXL\n227 | Asymptotic mixing length scale                                             | m                 | AMIXL\n228 | Potential evaporation                                                      | kg m{-2}          | PEVAP\n229 | Snow phase-change heat flux                                                | W m{-2}           | SNOHF\n231 | Convective cloud mass flux                                                 | Pa s{-1}          | MFLUX\n232 | Downward total radiation flux                                              | W m{-2}           | DTRF\n233 | Upward total radiation flux                                                | W m{-2}           | UTRF\n234 | Baseflow-groundwater runoff                                                | kg m{-2}          | BGRUN\n235 | Storm surface runoff                                                       | kg m{-2}          | SSRUN\n237 | Total ozone                                                                | Kg m{-2}          | 03TOT\n238 | Snow cover                                                                 | percent           | SNO C\n239 | Snow temperature                                                           | K                 | SNO T\n241 | Large scale condensat. heat rate                                           | K s{-1}           | LRGHR\n242 | Deep convective heating rate                                               | K s{-1}           | CNVHR\n243 | Deep convective moistening rate                                            | kg kg{-1} s{-1}   | CNVMR\n244 | Shallow convective heating rate                                            | K s{-1}           | SHAHR\n245 | Shallow convective moistening rate                                         | kg kg{-1} s{-1}   | SHAMR\n246 | Vertical diffusion heating rate                                            | K s{-1}           | VDFHR\n247 | Vertical diffusion zonal acceleration                                      | m s{-2}           | VDFUA\n248 | Vertical diffusion meridional accel                                        | m s{-2}           | VDFVA\n249 | Vertical diffusion moistening rate                                         | kg kg{-1} s{-1}   | VDFMR\n250 | Solar radiative heating rate                                               | K s{-1}           | SWHR\n251 | long wave radiative heating rate                                           | K s{-1}           | LWHR\n252 | Drag coefficient                                                           | non-dim           | CD\n253 | Friction velocity                                                          | m s{-1}           | FRICV\n254 | Richardson number                                                          | non-dim           | RI\n255 | Missing                                                                    | missing           | missing\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/GRIB_TABLES/GRIB2_PARAMETER_TABLE",
    "content": "############################################################################################\n+ 0 + 0 + Temperature\n############################################################################################\n  0 | Temperature                           | K\n  1 | Virtual temperature                   | K\n  2 | Potential temperature                 | K\n  3 | Equivalent potential temperature      | K\n  4 | Maximum temperature                   | K   (Deprecated)\n  5 | Minimum temperature                   | K   (Deprecated)\n  6 | Dew point temperature                 | K\n  7 | Dew point depression (or deficit)     | K\n  8 | Lapse rate                            | K m{-1}\n  9 | Temperature anomaly                   | K\n 10 | Latent heat net flux                  | W m{-2}\n 11 | Sensible heat net flux                | W m{-2}\n 12 | Heat index                            | K\n 13 | Wind chill factor                     | K\n 14 | Minumum dew point depression          | K   (Deprecated)\n 15 | Virtual potential temperature         | K\n 16 | Snow phase change heat flux           | W m{-2}\n 17 | Skin temperature                      | K\n255 | Missing                               | Missing\n############################################################################################\n+ 0 + 1 + Moisture\n############################################################################################\n  0 | Specific humidity                                          | kg kg{-1}\n  1 | Relative humidity                                          | %\n  2 | Humidity mixing ratio                                      | kg kg{-1}\n  3 | Precipitable water                                         | kg m{-2}\n  4 | Vapor pressure                                             | Pa\n  5 | Saturation deficit                                         | Pa\n  6 | Evaporation                                                | kg m{-2}\n  7 | Precipitation rate  (Deprecated)                           | kg m{-2} s{-1}\n  8 | Total precipitation (Deprecated)                           | kg m{-2}\n  9 | Large scale precipitation (non-convective) (Deprecated)    | kg m{-2}\n 10 | Convective precipitation (Deprecated)                      | kg m{-2}\n 11 | Snow depth                                                 | m\n 12 | Snowfall rate water equivalent (Deprecated)                | kg m{-2} s{-1}\n 13 | Water equivalent of accumulated snow depth (Deprecated)    | kg m{-2}\n 14 | Convective snow (Deprecated)                               | kg m{-2}\n 15 | Large scale snow (Deprecated)                              | kg m{-2}\n 16 | Snow melt                                                  | kg m{-2}\n 17 | Snow age                                                   | day\n 18 | Absolute humidity                                          | kg m{-3}\n 19 | Precipitation type                                         | Code Table 4.201\n 20 | Integrated liquid water                                    | kg m{-2}\n 21 | Condensate                                                 | kg kg{-1}\n 22 | Cloud mixing ratio                                         | kg kg{-1}\n 23 | Ice water mixing ratio                                     | kg kg{-1}\n 24 | Rain mixing ratio                                          | kg kg{-1}\n 25 | Snow mixing ratio                                          | kg kg{-1}\n 26 | Horizontal moisture convergence                            | kg kg{-1} s{-1}\n 27 | Maximum relative humidity (Deprecated)                     | %\n 28 | Maximum absolute humidity (Deprecated)                     | kg m{-3}\n 29 | Total snowfall (Deprecated)                                | m\n 30 | Precipitable water category                                | Code Table 4.202\n 31 | Hail                                                       | m\n 32 | Graupel (snow pellets)                                     | kg kg{-1}\n 33 | Categorical rain                                           | Code Table 4.222\n 34 | Categorical freezing rain                                  | Code Table 4.222\n 35 | Categorical ice pellets                                    | Code Table 4.222\n 36 | Categorical snow                                           | Code Table 4.222\n 37 | Convective precipitation rate                              | kg m{-2} s{-1}\n 38 | Horizontal moisture divergence                             | kg kg{-1} s{-1}\n 39 | Percent frozen precipitation                               | %\n 40 | Potential evaporation                                      | kg m{-2}\n 41 | Potential evaporation rate                                 | W m{-2}\n 42 | Snow cover                                                 | %\n 43 | Rain fraction of total cloud water                         | Proportion\n 44 | Rime factor                                                | Numeric\n 45 | Total column integrated rain                               | kg m{-2}\n 46 | Total column integrated snow                               | kg m{-2}\n 47 | Large scale water precipitation (non-convective)           | kg m{-2}\n 48 | Convective water precipitation                             | kg m{-2}\n 49 | Total water precipitation                                  | kg m{-2}\n 50 | Total snow precipitation                                   | kg m{-2}\n 51 | Total column water    (vapour + cloud water/ice)           | kg m{-2}\n 52 | Total precipitation rate                                   | kg m{-2} s{-1}\n 53 | Total snowfall rate water equivalent                       | kg m{-2} s{-1}\n 54 | Large scale precipitation rate                             | kg m{-2} s{-1}\n 55 | Convective snowfall rate water equivalent                  | kg m{-2} s{-1}\n 56 | Large scale snowfall rate water equivalent                 | kg m{-2} s{-1}\n 57 | Total snowfall rate                                        | m s{-1}\n 58 | Convective snowfall rate                                   | m s{-1}\n 59 | Large scale snowfall rate                                  | m s{-1}\n 60 | Snow depth water equivalent                                | kg m{-2}\n 61 | Snow density                                               | kg m{-3}\n 62 | Snow evaporation                                           | kg m{-2}\n 64 | Total column integrated water vapour                       | kg m{-2}\n 65 | Rain precipitation rate                                    | kg m{-2} s{-1}\n 66 | Snow precipitation rate                                    | kg m{-2} s{-1}\n 67 | Freezing rain precipitation rate                           | kg m{-2} s{-1}\n 68 | Ice pellets precipitation rate                             | kg m{-2} s{-1}\n192 | Categorical rain                                           | Code Table 4.222\n193 | Categorical freezing rain                                  | Code Table 4.222\n194 | Categorical ice pellets                                    | ???????\n195 | Categorical snow                                           | Code Table 4.222\n196 | Convective precipitation rate                              | kg m{-2} s{-1}\n200 | Potential Evaporation Rate                                 | W m{-2}\n201 | Snow Cover                                                 | %\n202 | Rain Fraction of Total Liquid Water                        | Proportion\n203 | Rime Factor                                                | Numeric\n204 | Total Column Integrated Rain                               | kg m{-2}\n205 | Total column integrated snow                               | kg m{-2}\n209 | Total column-integrated supercooled liquid water           | kg m{-2}\n210 | Total column-integrated melting ice                        | kg m{-2}\n255 | Missing                                                    | Missing\n############################################################################################\n+ 0 + 2 + Momentum\n############################################################################################\n  0 | Wind direction (from which blowing)                        | deg true\n  1 | Wind speed                                                 | m s{-1}\n  2 | u-component of wind                                        | m s{-1}\n  3 | v-component of wind                                        | m s{-1}\n  4 | Stream function                                            | m2 s{-1}\n  5 | Velocity potential                                         | m2 s{-1}\n  6 | Montgomery stream function                                 | m2 s{-2}\n  7 | Sigma coordinate vertical velocity                         | s{-1}\n  8 | Vertical velocity (pressure)                               | Pa s{-1}\n  9 | Vertical velocity (geometric)                              | m s{-1}\n 10 | Absolute vorticity                                         | s{-1}\n 11 | Absolute divergence                                        | s{-1}\n 12 | Relative vorticity                                         | s{-1}\n 13 | Relative divergence                                        | s{-1}\n 14 | Potential vorticity                                        | K m2 kg{-1} s{-1}\n 15 | Vertical u-component shear                                 | s{-1}\n 16 | Vertical v-component shear                                 | s{-1}\n 17 | Momentum flux, u component                                 | N m{-2}\n 18 | Momentum flux, v component                                 | N m{-2}\n 19 | Wind mixing energy                                         | J\n 20 | Boundary layer dissipation                                 | W m{-2}\n 21 | Maximum wind speed (deprecated)                            | m s{-1}\n 22 | Wind speed (gust)                                          | m s{-1}\n 23 | u-component of wind (gust)                                 | m s{-1}\n 24 | v-component of wind (gust)                                 | m s{-1}\n 25 | Vertical speed shear                                       | s{-1}\n 26 | Horizontal momentum flux                                   | N m{-2}\n 27 | U-component storm motion                                   | m s{-1}\n 28 | V-component storm motion                                   | m s{-1}\n 29 | Drag coefficient                                           | Numeric\n 30 | Frictional velocity                                        | m s{-1}\n192 | Vertical speed shear                                       | s{-1}\n194 | U-Component Storm Motion                                   | m s{-1}\n195 | V-Component Storm Motion                                   | m s{-1}\n197 | Frictional Velocity                                        | m s{-1}\n255 | Missing                                                    | Missing\n############################################################################################\n+ 0 + 3 + Mass\n############################################################################################\n  0 | Pressure                                                   | Pa\n  1 | Pressure reduced to MSL                                    | Pa\n  2 | Pressure tendency                                          | Pa s{-1}\n  3 | ICAO Standard Atmosphere Reference Height                  | m\n  4 | Geopotential                                               | m2 s{-2}\n  5 | Geopotential height                                        | gpm\n  6 | Geometric height                                           | m\n  7 | Standard deviation of height                               | m\n  8 | Pressure anomaly                                           | Pa\n  9 | Geopotential height anomaly                                | gpm\n 10 | Density                                                    | kg m{-3}\n 11 | Altimeter setting                                          | Pa\n 12 | Thickness                                                  | m\n 13 | Pressure altitude                                          | m\n 14 | Density altitude                                           | m\n 15 | 5-wave geopotential height                                 | gpm\n 16 | Zonal flux of gravity wave stress                          | N m{-2}\n 17 | Meridional flux of gravity wave stress                     | N m{-2}\n 18 | Planetary boundary layer height                            | m\n 19 | 5-wave geopotential height anomaly                         | gpm\n 20 | Standard deviation of sub-grid scale orography             | m\n 21 | Angle of sub-gridscale orography                           | rad\n 22 | Slope of sub-gridscale orography                           | Numeric\n 23 | Gravity wave dissipation                                   | W m{-2}\n 24 | Anisotropy of sub-gridscale orography                      | Numeric\n192 | MSLP ( Eta Reduction)                                      | Pa\n193 | 5-Wave Geopotential Height                                 | gpm\n194 | Zonal Flux of Gravity Wave Stress                          | N m{-2}\n195 | Meridional Flux of Gravity Wave Stress                     | N m{-2}\n196 | Planetary Boundary Layer Height                            | m\n197 | 5-Wave Geopotential Height Anomaly                         | gpm\n200 | Pressure of level from which parcel was lifted             | Pa\n255 | Missing                                                    | Missing\n############################################################################################\n+ 0 + 4 + Short-wave Radiation\n############################################################################################\n  0 | Net short-wave radiation flux (surface) (Deprecated)             | W m{-2}\n  1 | Net short-wave radiation flux (top of atmosphere) (Deprecated)   | W m{-2}\n  2 | Short wave radiation flux (Deprecated)                           | W m{-2}\n  3 | Global radiation flux                                            | W m{-2}\n  4 | Brightness temperature                                           | K\n  5 | Radiance (with respect to wave number)                           | W m{-1} sr{-1}\n  6 | Radiance (with respect to wave length)                           | W m{-3} sr{-1}\n  7 | Downward short-wave radiation flux                               | W m{-2}\n  8 | Upward short-wave radiation flux                                 | W m{-2}\n  9 | Net short wave radiation flux                                    | W m{-2}\n 10 | Photosynthetically active radiation                              | W m{-2}\n 11 | Net short-wave radiation flux, clear sky                         | W m{-2}\n 12 | Downward UV radiation                                            | W m{-2}\n 50 | UV index (under clear sky)                                       | Numeric\n 51 | UV index                                                         | Numeric\n192 | Downward short-wave radiation flux                               | W m{-2}\n193 | Upward short-wave radiation flux                                 | W m{-2}\n255 | Missing                                                          | Missing\n############################################################################################\n+ 0 + 5 + Long-wave Radiation\n############################################################################################\n  0 | Net long wave radiation flux (surface) (Deprecated)               | W m{-2}\n  1 | Net long wave radiation flux (top of atmosphere) (Deprecated)     | W m{-2}\n  2 | Long wave radiation flux (Deprecated)                             | W m{-2}\n  3 | Downward long-wave radiation flux                                 | W m{-2}\n  4 | Upward long-wave radiation flux                                   | W m{-2}\n  5 | Net long wave radiation flux                                      | W m{-2}\n  6 | Net long-wave radiation flux, clear sky                           | W m{-2}\n192 | Downward long-wave radiation flux                                 | W m{-2}\n193 | Upward long-wave radiation flux                                   | W m{-2}\n255 | Missing                                                           | Missing\n############################################################################################\n+ 0 + 6 + Cloud\n############################################################################################\n 0 | Cloud Ice                                                         | kg m{-2}\n 1 | Total cloud cover                                                 | %\n 2 | Convective cloud cover                                            | %\n 3 | Low cloud cover (Deprecated)                                      | %\n 4 | Medium cloud cover (Deprecated)                                   | %\n 5 | High cloud cover (Deprecated) | %\n 6 | Cloud water | kg m{-2}\n 7 | Cloud amount | %\n 8 | Cloud type | code table (4.203)\n 9 | Thunderstorm maximum tops | m\n10 | Thunderstorm coverage | code table (4.204)\n11 | Cloud base | m\n12 | Cloud top | m\n13 | Ceiling | m\n14 | Non-convective cloud cover | %\n15 | Cloud work function | J kg{-1}\n16 | Convective cloud efficiency | Proportion\n17 | Total condensate | kg kg{-1}\n18 | Total column-integrated cloud water | kg m{-2}\n19 | Total column-integrated cloud ice | kg m{-2}\n20 | Total column-integrated condensate | kg m{-2}\n21 | Ice fraction of total condensate | Proportion\n22 | Cloud cover | %\n23 | Cloud ice mixing ratio | kg kg{-1}\n24 | Sunshine | Numeric\n193 | Cloud Work Function | J kg{-1}\n194 | Convective Cloud Efficiency | Proportion\n196 | Total column-integrated cloud water | kg m{-2}\n197 | Total Column-Integrated Cloud Ice | kg m{-2}\n198 | Total Column-Integrated Condensate | kg m{-2}\n255 | Missing | Missing\n############################################################################################\n+ 0 + 7 + Thermodynamic Stability Indices\n############################################################################################\n 0 | Parcel lifted index (to 500 hPa) | K\n 1 | Best lifted index (to 500 hPa) | K\n 2 | K index | K\n 3 | KO index | K\n 4 | Total totals index | K\n 5 | Sweat index | Numeric\n 6 | Convective available potential energy | J kg{-1}\n 7 | Convective inhibition | J kg{-1}\n 8 | Storm relative helicity | J kg{-1}\n 9 | Energy helicity index | Numeric\n10 | Surface lifted index | K\n11 | Best (4-layer) lifted index | K\n12 | Richardson number | Numeric\n192 | Surface Lifted Index | ???????\n193 | Best (4 layer) Lifted Index | ???????\n255 | Missing | Missing\n############################################################################################\n+ 0 + 13 + Aerosols\n############################################################################################\n 0 | Aerosol type | code table (4.205)\n255 | Missing | Missing\n############################################################################################\n+ 0 + 14 + Trace Gases\n############################################################################################\n 0 | Total ozone | Dobson\n 1 | Ozone mixing ratio | kg kg{-1}\n 2 | Total column integrated ozone | Dobson\n192 | Ozone Mixing Ratio | kg kg{-1}\n255 | Missing | Missing\n############################################################################################\n+ 0 + 15 + Radar\n############################################################################################\n 0 | Base spectrum width | m s{-1}\n 1 | Base reflectivity | dB\n 2 | Base radial velocity | m s{-1}\n 3 | Vertically-integrated liquid | kg m{-1}\n 4 | Layer-maximum base reflectivity | dB\n 5 | Precipitation | kg m{-2}\n 6 | Radar spectra (1) | -\n 7 | Radar spectra (2) | -\n 8 | Radar spectra (3) | -\n255 | Missing | Missing\n############################################################################################\n+ 0 + 16 + Category?\n############################################################################################\n195 | Derived radar reflectivity | dB\n196 | Maximum/Composite radar reflectivity | dB\n############################################################################################\n+ 0 + 18 + Nuclear/radiology\n############################################################################################\n 0 | Air concentration of Caesium 137  | Bq m{-3}\n 1 | Air concentration of Iodine 131  | Bq m{-3}\n 2 | Air concentration of radioactive pollutant | Bq m{-3}\n 3 | Ground deposition of Caesium 137 | Bq m{-2}\n 4 | Ground deposition of Iodine 131 | Bq m{-2}\n 5 | Ground deposition of radioactive pollutant | Bq m{-2}\n 6 | Time-integrated air concentration of caesium pollutant (Deprecated) | Bq s m{-3}\n 7 | Time-integrated air concentration of iodine pollutant (Deprecated) | Bq s m{-3}\n 8 | Time-integrated air concentration of radioactive pollutant (Deprecated) | Bq s m{-3}\n255 | Missing | Missing\n############################################################################################\n+ 0 + 19 + Physical atmospheric properties\n############################################################################################\n 0 | Visibility | m\n 1 | Albedo | %\n 2 | Thunderstorm probability | %\n 3 | mixed layer depth | m\n 4 | Volcanic ash | code table (4.206)\n 5 | Icing top | m\n 6 | Icing base | m\n 7 | Icing | code table (4.207)\n 8 | Turbulence top | m\n 9 | Turbulence base | m\n10 | Turbulence | code table (4.208)\n11 | Turbulent kinetic energy | J kg{-1}\n12 | Planetary boundary layer regime | code table (4.209)\n13 | Contrail intensity | code table (4.210)\n14 | Contrail engine type | code table (4.211)\n15 | Contrail top | m\n16 | Contrail base | m\n17 | Maximum snow albedo (Deprecated) | %\n18 | Snow free albedo | %\n19 | Snow albedo | %\n192 | Maximum snow albedo | %\n193 | Snow free albedo | %\n255 | Missing | Missing\n############################################################################################\n+ 0 + 190 + CCITT IA5 string\n############################################################################################\n 0 | Arbitrary text string | CCITTIA5\n255          | Missing | Missing\n############################################################################################\n+ 0 + 191 + Miscellaneous\n############################################################################################\n 0 | Seconds prior to initial reference time (defined in Section 1) | s\n255          | Missing | Missing\n############################################################################################\n+ 1 + 0 + Hydrology basic products\n############################################################################################\n 0 | Flash flood guidance | kg m{-2}\n 1 | Flash flood runoff | kg m{-2}\n 2 | Remotely sensed snow cover | (code table 4.215)\n 3 | Elevation of snow covered terrain | (code table 4.216)\n 4 | Snow water equivalent percent of normal | %\n 5 | Baseflow-groundwater runoff | kg m{-2}\n 6 | Storm surface runoff | kg m{-2}\n192 | Baseflow-Groundwater Runoff | kg m{-2}\n193 | Storm surface runoff | kg m{-2}\n255 | Missing | Missing\n############################################################################################\n+ 1 + 1 + Hydrology probabilities\n############################################################################################\n 0 | Conditional percent precipitation amount fractile for an overall period | kg m{-2}\n 1 | Percent precipitation in a sub-period of an overall period | %\n 2 | Probability of 0.01 inch of precipitation (POP) | %\n193 | Probability of Frozen Precipitation | %\n255 | Missing | Missing\n############################################################################################\n+ 2 + 0 + Vegetation/Biomass\n############################################################################################\n 0 | Land cover (1=land, 0=sea) | Proportion\n 1 | Surface roughness | m\n 2 | Soil temperature | K\n 3 | Soil moisture content (Deprecated) | kg m{-2}\n 4 | Vegetation | %\n 5 | Water runoff | kg m{-2}\n 6 | Evapotranspiration | kg {-2} s{-1}\n 7 | Model terrain height | m\n 8 | Land use | code table (4.212)\n 9 | Volumetric soil moisture content (Deprecated) (Deprecated) | Proportion\n10 | Ground heat flux (Deprecated) | W m{-2}\n11 | Moisture availability | %\n12 | Exchange coefficient | kg m{-2} s{-1}\n13 | Plant canopy surface water | kg m{-2}\n14 | Blackadar's mixing length scale | m\n15 | Canopy conductance | m s{-1}\n16 | Minimal stomatal resistance | s m{-1}\n17 | Wilting point (Deprecated) | Proportion\n18 | Solar parameter in canopy conductance | Proportion\n19 | Temperature parameter in canopy conductance | Proportion\n20 | Soil moisture parameter in canopy conductance | Proportion\n21 | Humidity parameter in canopy conductance | Proportion\n22 | Soil moisture | kg m{-3}\n23 | Column-integrated soil water | kg m{-2}\n24 | Heat flux | W m{-2}\n25 | Volumetric soil moisture | m3 m{-3}\n26 | Wilting point | kg m{-3}\n27 | Volumetric wilting point | m3 m{-3}\n192 | Volumetric Soil Moisture Content | Proportion\n193 | Ground Heat Flux | W m{-2}\n194 | Moisture Availability | ???????\n195 | Exchange Coefficient | kg m{-2} s{-1}\n196 | Plant Canopy Surface Water | kg m{-2}\n197 | Blackadar's Mixing Length Scale | m\n198 | Vegetation Type | ???????\n199 | Canopy Conductance | m s{-1}\n200 | Minimal Stomatal Resistance | s m{-1}\n201 | Wilting Point | Proportion\n202 | Solar parameter in canopy conductance | Proportion\n203 | Temperature parameter in canopy conductance | Proportion\n204 | Humidity parameter in canopy conductance | Proportion\n205 | Soil moisture parameter in canopy conductance | Proportion\n206 | Rate of water dropping from canopy to ground | kg m{-2} s{-1}\n207 | Ice-free water surface | ???????\n255 | Missing | Missing\n############################################################################################\n+ 2 + 3 + Soil Products\n############################################################################################\n 0 | Soil type | code table (4.213)\n 1 | Upper layer soil temperature (Deprecated) | K\n 2 | Upper layer soil moisture (Deprecated) | kg m{-3}\n 3 | Lower layer soil moisture (Deprecated) | kg m{-3}\n 4 | Bottom layer soil temperature (Deprecated) | K\n 5 | Liquid volumetric soil moisture (non-frozen) (Deprecated) | Proportion\n 6 | Number of soil layers in root zone | Numeric\n 7 | Transpiration stress-onset (soil moisture) (Deprecated)  | Proportion\n 8 | Direct evaporation cease (soil moisture) (Deprecated)  | Proportion\n 9 | Soil porosity (Deprecated) (Deprecated) | Proportion\n10 | Liquid volumetric soil moisture (non-frozen) | m{3} m{-3}\n11 | Volumetric transpiration stress-onset (soil moisture) | m{3} m{-3}\n12 | Transpiration stress-onset (soil moisture) | kg m{-3}\n13 | Volumetric direct evaporation cease (soil moisture) | m{3} m{-3}\n14 | Direct evaporation cease (soil moisture) | kg m{-3}\n15 | Soil porosity | m3 m{-3}\n16 | Volumetric saturation of soil moisture | m{3} m{-3}\n17 | Saturation of soil moisture | kg m{-3}\n192 | Liquid Volumetric Soil Moisture | m{3} m{-3}\n193 | Number of Soil Layers in Root Zone | Numeric\n194 | Surface Slope Type | ???????\n195 | Transpiration Stress-onset (soil moisture) | Proportion\n196 | Direct Evaporation Cease (soil moisture) | Proportion\n197 | Soil Porosity | Proportion\n255 | Missing | Missing\n############################################################################################\n+ 3 + 0 + Image format products\n############################################################################################\n 0 | Scaled radiance | Numeric\n 1 | Scaled albedo | Numeric\n 2 | Scaled brightness temperature | Numeric\n 3 | Scaled precipitable water | Numeric\n 4 | Scaled lifted index | Numeric\n 5 | Scaled cloud top pressure | Numeric\n 6 | Scaled skin temperature | Numeric\n 7 | Cloud mask | Code table 4.217\n 8 | Pixel scene type | Code table 4.218\n 9 | Fire detection indicator | Code table 4.223\n255 | Missing | Missing\n############################################################################################\n+ 3 + 1 + Quantitative products\n############################################################################################\n 0 | Estimated precipitation | kg m{-2}\n 1 | Instantaneous rain rate | kg m{-2} s{-1}\n 2 | Cloud top height | m\n 3 | Cloud top height quality indicator | Code table 4.219\n 4 | Estimated u component of wind | m s{-1}\n 5 | Estimated v component of wind | m s{-1}\n 6 | Number of pixels used | Numeric\n 7 | Solar zenith angle | Degree\n 8 | Relative azimuth angle | Degree\n 9 | Reflectance in 0.6 micron channel | %\n10 | Reflectance in 0.8 micron channel | %\n11 | Reflectance in 1.6 micron channel | %\n12 | Reflectance in 3.9 micron channel | %\n13 | Atmospheric divergence | s{-1}\n255 | Missing | Missing\n############################################################################################\n+ 10 + 0 + Waves\n############################################################################################\n 0 | Wave spectra (1) | -\n 1 | Wave spectra (2) | -\n 2 | Wave spectra (3) | -\n 3 | Significant height of combined wind waves and swell | m\n 4 | Direction of wind waves | Degree true\n 5 | Significant height of wind waves | m\n 6 | Mean period of wind waves | s\n 7 | Direction of swell waves | Degree true\n 8 | Significant height of swell waves | m\n 9 | Mean period of swell waves | s\n10 | Primary wave direction | Degree true\n11 | Primary wave mean period | s\n12 | Secondary wave direction | Degree true\n13 | Secondary wave mean period | s\n255 | Missing | Missing\n############################################################################################\n+ 10 + 1 + Currents\n############################################################################################\n 0 | Current direction | Degree true\n 1 | Current speed | m s{-1}\n 2 | u-component of current | m s{-1}\n 3 | v-component of current | m s{-1}\n255 | Missing | Missing\n############################################################################################\n+ 10 + 2 + Ice\n############################################################################################\n 0 | Ice cover | Proportion\n 1 | Ice thickness | m\n 2 | Direction of ice drift | Degree true\n 3 | Speed of ice drift | m s{-1}\n 4 | u-component of ice drift | m s{-1}\n 5 | v-component of ice drift | m s{-1}\n 6 | Ice growth rate | m s{-1}\n 7 | Ice divergence | s{-1}\n 8 | Ice temperature | K\n255 | Missing | Missing\n############################################################################################\n+ 10 + 3 + Surface Properties\n############################################################################################\n 0 | Water temperature | K\n 1 | Deviation of sea level from mean | m\n255 | Missing | Missing\n############################################################################################\n+ 10 + 4 + Sub-surface Properties\n############################################################################################\n 0 | Main thermocline depth | m\n 1 | Main thermocline anomaly | m\n 2 | Transient thermocline depth | m\n 3 | Salinity | kg kg{-1}\n255 | Missing | Missing\n############################################################################################\n+ 10 + 191 + Miscellaneous\n############################################################################################\n 0 | Seconds prior to initial reference time (defined in Section 1) | s\n255          | Missing | Missing\n############################################################################################\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/Makefile",
    "content": "SHELL=/bin/sh\n.SUFFIXES:\t\n.SUFFIXES:\t.F .c .o .exe\n\ninclude ../user_build_options\n\nOBJS=\tconsolidate_grib.o\n\nCMD=\tconsolidate_grib.exe\n\ndefault:\n\t(cd lib; make)\n\t(make -f Makefile all)\n\nall:\tlib/libsmda.a $(CMD)\n\t(cd lib; make)\n\nlib/libsmda.a:\n\t(cd lib; make)\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(FREESOURCE) $(F90FLAGS) -c $(NETCDFMOD) -I./lib $(MODFLAG)./lib $(*).F\n\n$(CMD):\tlib/libsmda.a $(OBJS)\n\t(cd lib; make)\n\t$(COMPILERF90) -o $(@) -I./lib $(F90FLAGS) $(MODFLAG)./lib $(OBJS) \\\n\t\t-L./lib -lsmda $(NETCDFLIB) $(HDF5LIB) $(BZIP2_LIB) $(LIBJASPER)\n\nclean:\n\t$(RM) *.o *~ *.exe *.mod\n\t(cd lib; make clean)\n#\n\n\n\n\n\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/consolidate_grib.F",
    "content": "program consolidate\n  use module_grib\n  use module_wrfinputfile\n  use module_geo_em\n  use kwm_grid_utilities\n  use kwm_date_utilities\n  use kwm_string_utilities\n  implicit none\n\n  character(len=9), parameter :: version = \"v20110427\"\n\n  character(len=256) :: namelist_file\n  character(len=13) :: date\n\n  type (wrfinput_type) :: wrfinput\n  type (geo_em_type) :: geo_em\n\n\n  integer, parameter :: MAXTEMPLATE = 10\n\n  type DataBuffer\n     character(len=256)                         :: label\n     character(len=256)                         :: units\n     real, pointer,      dimension(:,:)         :: field\n     character(len=19)                          :: hdate ! A punctuated date, out to seconds.\n     character(len=256), dimension(MAXTEMPLATE) :: flnm_template\n     real                                       :: layer1\n     real                                       :: layer2\n     character(len=4)                           :: remap_type\n     integer                                    :: fatality ! How we may or may not handle missing data.\n  end type DataBuffer\n\n  type VtableEntry\n     integer :: g1_parm\n     integer :: g1_levtyp\n     integer :: level1\n     integer :: level2\n     character(len=32) :: name\n     character(len=32) :: units\n     character(len=32) :: desc\n     integer :: g2_discp\n     integer :: g2_cat\n     integer :: g2_parm\n     integer :: g2_levtyp\n  end type VtableEntry\n\n  type(VtableEntry), dimension(64) :: vtable\n  integer :: vtable_count\n\n  type (DataBuffer) :: Tprev, Tcurrent, Tpost\n  type (DataBuffer) :: Qprev, Qcurrent, Qpost\n  type (DataBuffer) :: Uprev, Ucurrent, Upost\n  type (DataBuffer) :: Vprev, Vcurrent, Vpost\n  type (DataBuffer) :: Pprev, Pcurrent, Ppost\n  type (DataBuffer) :: SW1prev, SW1current, SW1post\n  type (DataBuffer) :: SW2prev, SW2current, SW2post\n  type (DataBuffer) :: LWprev, LWcurrent, LWpost\n  type (DataBuffer) :: CANWTprev, CANWTcurrent, CANWTpost\n  type (DataBuffer) :: SKTprev, SKTcurrent, SKTpost\n  type (DataBuffer) :: WEASDprev, WEASDcurrent, WEASDpost\n  type (DataBuffer) :: PCP1prev, PCP1current, PCP1post\n  type (DataBuffer) :: PCP2prev, PCP2current, PCP2post\n  type (DataBuffer), dimension(4) :: STprev, STcurrent, STpost\n  type (DataBuffer), dimension(4) :: SMprev, SMcurrent, SMpost\n  type (DataBuffer) :: Zcurrent\n  type (DataBuffer) :: LANDSEA\n  type (DataBuffer) :: gvfmin\n  type (DataBuffer) :: gvfmax\n  type (DataBuffer) :: vegfra\n  type (DataBuffer) :: z2d\n  integer :: i, j\n  integer :: ierr\n  character(len=1) :: hgrid\n  character(len=8) :: name\n\n  integer :: ncid\n  integer :: ihour\n  integer :: numarg\n#ifndef _GFORTRAN_\n  ! For some reason, gfortran does not like this declared external,\n  ! but everyone else wants it declared external.  So we use #ifndef\n  integer, external :: iargc\n#endif\n\n\n  ! Namelist variables\n  character(len=13) :: startdate ! A punctuated date out to hours\n  character(len=13) :: enddate   ! A punctuated date out to hours\n  character(len=256) :: DataDir\n  character(len=256) :: wrfinput_flnm\n  character(len=256) :: geo_em_flnm\n  integer            :: rainfall_interp ! 0=Nearest Neighbor; 1=more expensive.\n  integer            :: full_ic_frq     ! How frequently (hours) to make full surface initial conditions.\n                                        ! FULL_IC_FRC==0 means do this only at the startdate.\n                                        ! FULL_IC_FRC==-1 means never make full surface initial conditions.\n  logical            :: rescale_shortwave\n  character(len=256), dimension(MAXTEMPLATE) :: Zfile_template         ! source model surface elevation\n  character(len=256), dimension(MAXTEMPLATE) :: Tfile_template         ! T analysis\n  character(len=256), dimension(MAXTEMPLATE) :: Ufile_template         ! U analysis\n  character(len=256), dimension(MAXTEMPLATE) :: Vfile_template         ! V analysis\n  character(len=256), dimension(MAXTEMPLATE) :: Qfile_template         ! Q analysis\n  character(len=256), dimension(MAXTEMPLATE) :: Pfile_template         ! P analysis\n  character(len=256), dimension(MAXTEMPLATE) :: LWfile_template        ! LW forecast\n  character(len=256), dimension(MAXTEMPLATE) :: SWfile_secondary       ! SW forecast\n  character(len=256), dimension(MAXTEMPLATE) :: PCPfile_secondary        ! Precipitation forecast\n  character(len=256), dimension(MAXTEMPLATE) :: SWfile_primary         ! GCIP SW analysis\n\n  character(len=256), dimension(MAXTEMPLATE) :: WEASDfile_template\n  character(len=256), dimension(MAXTEMPLATE) :: CANWTfile_template\n  character(len=256), dimension(MAXTEMPLATE) :: LANDSfile_template\n  character(len=256), dimension(MAXTEMPLATE) :: SKINTfile_template\n  character(len=256), dimension(4,MAXTEMPLATE) :: STfile_template\n  character(len=256), dimension(4,MAXTEMPLATE) :: SMfile_template\n\n  character(len=256), dimension(MAXTEMPLATE) :: PCPfile_primary\n\n\n  namelist /files/ startdate, enddate, &\n       DataDir, full_ic_frq, rainfall_interp, rescale_shortwave, wrfinput_flnm, &\n       geo_em_flnm, Tfile_template, Ufile_template, Vfile_template,             &\n       Pfile_template, Qfile_template, LWfile_template, SWfile_secondary,       &\n       PCPfile_secondary, SWfile_primary, WEASDfile_template,                   &\n       CANWTfile_template, LANDSfile_template, SKINTfile_template,              &\n       STfile_template, SMfile_template, PCPfile_primary, Zfile_template\n\n  full_ic_frq = 0\n  rainfall_interp = 1\n  rescale_shortwave = .FALSE.\n  Zfile_template = \" \"\n  Tfile_template = \" \"\n  Ufile_template = \" \"\n  Vfile_template = \" \"\n  Qfile_template = \" \"\n  Pfile_template = \" \"\n  LWfile_template = \" \"\n  PCPfile_secondary = \" \"\n  SWfile_primary = \" \"\n  SWfile_secondary = \" \"\n  WEASDfile_template = \" \"\n  CANWTfile_template = \" \"\n  LANDSfile_template = \" \"\n  SKINTfile_template = \" \"\n  STfile_template = \" \"\n  SMfile_template = \" \"\n  PCPfile_primary = \" \"\n\n\n!--------------------------------------------------------------------------\n! Read namelist\n!--------------------------------------------------------------------------\n\n  numarg = iargc()\n  if (numarg > 0) then\n     call getarg(1, namelist_file)\n  else\n     namelist_file = \"namelist.input\"\n  endif\n\n  open(12,file=trim(namelist_file), form='formatted', action='read', status='old', iostat=ierr)\n  if (ierr /= 0) then\n     write(*,*)\n     write(*,'(\"  *****  Failure trying to open file ''\", A, \"''\")') trim(namelist_file)\n     write(*,*)\n     write(*,'(\"Program takes an optional command-line argument, the name of the namelist file.\")')\n     if ( numarg > 0 ) then\n        write(*,'(\"In this case, you provided the name ''\", A, \"''\")') trim(namelist_file)\n     endif\n     write(*,*)\n     write(*,'(\"With no command-line argument, program expects the namelist file to be\")')\n     write(*,'(\"called ''namelist.input'', which must be present in the working directory. \")')\n     write(*,*)\n     stop\n  endif\n  read(12,files)\n  close(12)\n\n!--------------------------------------------------------------------------\n! Read Vtable\n!--------------------------------------------------------------------------\n\n  call read_vtable(trim(namelist_file))\n\n!--------------------------------------------------------------------------\n! Begin to fill in our file name template strings\n!--------------------------------------------------------------------------\n\n  do j = 1, maxtemplate\n     call strrep(Zfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(Tfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(Ufile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(Vfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(Qfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(Pfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(LWfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(PCPfile_primary(j), \"<DataDir>\", trim(DataDir))\n     call strrep(PCPfile_secondary(j), \"<DataDir>\", trim(DataDir))\n     call strrep(SWfile_primary(j), \"<DataDir>\", trim(DataDir))\n     call strrep(SWfile_secondary(j), \"<DataDir>\", trim(DataDir))\n     call strrep(WEASDfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(CANWTfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(LANDSfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(SKINTfile_template(j), \"<DataDir>\", trim(DataDir))\n     do i = 1, 4\n        call strrep(STfile_template(i,j), \"<DataDir>\", trim(DataDir))\n        call strrep(SMfile_template(i,j), \"<DataDir>\", trim(DataDir))\n     enddo\n  enddo\n\n!------------------------------------------------------------------------\n! Read the wrfinput file and geo_em file\n!------------------------------------------------------------------------\n\n  call strrep(wrfinput_flnm, \"<DataDir>\", trim(DataDir))\n  write(*,'(A)') 'wrfinput_flnm    = \"'//trim(wrfinput_flnm)//'\"'\n\n  call strrep(geo_em_flnm, \"<DataDir>\", trim(DataDir))\n  write(*,'(A)') 'geo_em_flnm    = \"'//trim(geo_em_flnm)//'\"'\n\n  call read_wrfinput_file(trim(wrfinput_flnm), wrfinput, ierr)\n  if (ierr /= 0) stop \"Problem reading wrfinput file\"\n  write(hgrid,'(I1)') wrfinput%grid_id\n\n  call read_geo_em_file(trim(geo_em_flnm), geo_em, ierr)\n  if (ierr /= 0) stop \"Problem reading geo_em file\"\n\n  nullify(gvfmin%field)\n  nullify(gvfmax%field)\n  nullify(vegfra%field)\n  nullify(z2d%field)\n  allocate(gvfmin%field(wrfinput%idim, wrfinput%jdim))\n  allocate(gvfmax%field(wrfinput%idim, wrfinput%jdim))\n  allocate(vegfra%field(wrfinput%idim, wrfinput%jdim))\n  allocate(z2d%field(wrfinput%idim, wrfinput%jdim))\n\n  gvfmin%field(:,:) = minval(geo_em%veg,3)\n  gvfmax%field(:,:) = maxval(geo_em%veg,3)\n!  where (wrfinput%use == wrfinput%iswater) gvfmin%field=-1.E36\n!  where (wrfinput%use == wrfinput%iswater) gvfmax%field=-1.E36\n  call fillsm(gvfmin%field, (wrfinput%use /= wrfinput%iswater), wrfinput%idim, wrfinput%jdim)\n  call fillsm(gvfmax%field, (wrfinput%use /= wrfinput%iswater), wrfinput%idim, wrfinput%jdim)\n\n  where (gvfmin%field < 0.01) gvfmin%field = 0.01\n  where (gvfmax%field < 0.01) gvfmax%field = 0.01\n  z2d%field    = 2\n\n!--------------------------------------------------------------------------\n! Data buffer structure initializations\n!--------------------------------------------------------------------------\n\n  Zcurrent%label    = \"TERRAIN\"\n  Zcurrent%hdate    = \"0000-00-00_00:00:00\"\n  Zcurrent%flnm_template = Zfile_template\n\n  LANDSEA%label         = \"LANDSEA\"\n  LANDSEA%hdate         = \"0000-00-00_00:00:00\"\n  LANDSEA%flnm_template = LANDSfile_template\n\n  call data_buffer_init(  Tprev,   Tcurrent,   Tpost, Tfile_template,     \"bint\", \"T2D\")\n  call data_buffer_init(  Qprev,   Qcurrent,   Qpost, Qfile_template,     \"bint\", \"Q2D\")\n  call data_buffer_init(  Uprev,   Ucurrent,   Upost, Ufile_template,     \"bint\", \"U2D\")\n  call data_buffer_init(  Vprev,   Vcurrent,   Vpost, Vfile_template,     \"bint\", \"V2D\")\n  call data_buffer_init(  Pprev,   Pcurrent,   Ppost, Pfile_template,     \"bint\", \"PSFC\")\n  call data_buffer_init(PCP1prev, PCP1current, PCP1post, PCPfile_primary, \"4pt\",  \"RAINRATE\", fatality=2)\n  call data_buffer_init(PCP2prev, PCP2current, PCP2post, PCPfile_secondary, \"4pt\", \"RAINRATE\")\n  call data_buffer_init(SW1prev, SW1current, SW1post, SWfile_primary,     \"bint\", \"SWDOWN\",     fatality=2)\n  call data_buffer_init(SW2prev, SW2current, SW2post, SWfile_secondary,   \"bint\", \"SWDOWN\")\n  call data_buffer_init( LWprev,  LWcurrent,  LWpost, LWfile_template,    \"bint\", \"LWDOWN\" )\n  call data_buffer_init(CANWTprev, CANWTcurrent, CANWTpost, CANWTfile_template,  \"4pt\", \"CANWAT\" )\n  call data_buffer_init(  SKTprev,   SKTcurrent,   SKTpost, SKINTfile_template,  \"bint\", \"SKINTEMP\" )\n  call data_buffer_init(WEASDprev, WEASDcurrent, WEASDpost, WEASDfile_template,  \"4pt\",  \"WEASD\" )\n  do i = 1, 4\n     write(name, '(\"STEMP_\",i1)') i\n     call data_buffer_init(  STprev(i),   STcurrent(i),   STpost(i), STfile_template(i,:),  \"bint\", name )\n     write(name, '(\"SMOIS_\",i1)') i\n     call data_buffer_init(  SMprev(i),   SMcurrent(i),   SMpost(i), SMfile_template(i,:),  \"4pt\", name )\n  enddo\n\n  gvfmin%label = \"GVFMIN\"\n  gvfmin%units = \"%\"\n  gvfmin%layer1 = -1.E36\n  gvfmin%layer2 = -1.E36\n\n  gvfmax%label = \"GVFMAX\"\n  gvfmax%units = \"%\"\n  gvfmax%layer1 = -1.E36\n  gvfmax%layer2 = -1.E36\n\n  vegfra%label = \"VEGFRA\"\n  vegfra%units = \"%\"\n  vegfra%layer1 = -1.E36\n  vegfra%layer2 = -1.E36\n\n  z2d%label = \"Z2D\"\n  z2d%units = \"m\"\n  z2d%layer1 = -1.E36\n  z2d%layer2 = -1.E36\n\n!--------------------------------------------------------------------------\n! Loop DATELOOP is the main loop over time.\n!--------------------------------------------------------------------------\n\n  date = startdate\n\n  DATELOOP : do while ( date <= enddate )\n\n     call geth_idts(date(1:13), startdate(1:13), ihour)\n\n     print*, 'Date = ', Date, \"  ihour = \", ihour\n\n     call interpolate_vegetation(date, geo_em, vegfra%field, wrfinput%idim, wrfinput%jdim)\n     call fillsm(vegfra%field, (wrfinput%use /= wrfinput%iswater), wrfinput%idim, wrfinput%jdim)\n\n!     where (wrfinput%use == wrfinput%iswater) vegfra%field=-1.E36\n\n     call process(date, Tcurrent, Tprev, Tpost, wrfinput);\n     call process(date, Qcurrent, Qprev, Qpost, wrfinput);\n     call process(date, Ucurrent, Uprev, Upost, wrfinput);\n     call process(date, Vcurrent, Vprev, Vpost, wrfinput);\n     call process(date, Pcurrent, Pprev, Ppost, wrfinput);\n     call process(date,  SW1current,  SW1prev,  SW1post, wrfinput);\n     call process(date,  SW2current,  SW2prev,  SW2post, wrfinput);\n     call process(date,   LWcurrent,   LWprev,   LWpost, wrfinput);\n     call process(date, PCP1current, PCP1prev, PCP1post, wrfinput);\n     call process(date, PCP2current, PCP2prev, PCP2post, wrfinput);\n\n     if (date(12:13) == \"00\") then\n        call process(date, WEASDcurrent, WEASDprev, WEASDpost, wrfinput);\n     endif\n\n     if ( full_ic_frq > -1 ) then  ! full_ic_frq == -1 turns off extra processing for initial conditions.\n        if ( ( (full_ic_frq>0) .and. (mod(ihour, full_ic_frq)==0) ) .or. ( ihour==0 ) ) then\n\n           call process(date, CANWTcurrent, CANWTprev, CANWTpost, wrfinput);\n           call process(date, SKTcurrent, SKTprev, SKTpost, wrfinput);\n\n           do i = 1, 4\n              call process(date, STcurrent(i), STprev(i), STpost(i), wrfinput);\n              call process(date, SMcurrent(i), SMprev(i), SMpost(i), wrfinput);\n           enddo\n\n        endif\n     endif\n\n     call open_netcdf_for_output( &\n          date(1:4)//date(6:7)//date(9:10)//date(12:13)//\".LDASIN_DOMAIN\"//hgrid, &\n          ncid, version, wrfinput%idim, wrfinput%jdim, wrfinput)\n\n     ! For output, the Tcurrent%field needs to be readjusted to model elevation\n     Tcurrent%field = Tcurrent%field + ( -0.0065 * wrfinput%ter )\n\n     ! Fill in missing areas in PCP1 with data from PCP2\n     where (PCP2current%field <=0) PCP2current%field=0\n     where (PCP1current%field <-1.E25) PCP1current%field=PCP2current%field\n     where (PCP1current%field <=0) PCP1current%field=0\n\n     ! Fill in missing areas in SW1 with data from SW2\n     where (SW2current%field <= 0) SW2current%field = 0\n     where (SW1current%field <= 0) SW1current%field = SW2current%field\n\n     ! If the sun isn't up, there shouldn't be any SW.\n     ! This may be a little extreme (ignores atmospheric refraction effects, e.g.); it \n     ! causes an awfully abrupt terminator.  Will have to consider.\n     call nighttime_SW(SW1current%hdate, SW1current%field, wrfinput%idim, wrfinput%jdim, wrfinput)\n\n     call output_timestring_to_netcdf(ncid, date)\n\n     call output_databuffer(ncid,    Tcurrent)\n     call output_databuffer(ncid,    Qcurrent)\n     call output_databuffer(ncid,    Ucurrent)\n     call output_databuffer(ncid,    Vcurrent)\n     call output_databuffer(ncid,    Pcurrent)\n     call output_databuffer(ncid, PCP1current)\n     call output_databuffer(ncid,  SW1current)\n     call output_databuffer(ncid,   LWcurrent)\n\n     if ( full_ic_frq > -1 ) then  ! full_ic_frq == -1 turns off extra processing for initial conditions.\n        if ( ( (full_ic_frq>0) .and. (mod(ihour, full_ic_frq)==0) ) .or. ( ihour==0 ) ) then\n           ! Might as well deallocate some fields while we're at it.\n           where (CANWTcurrent%field < 0) CANWTcurrent%field = 0\n\n           call output_databuffer(ncid, CANWTcurrent)\n           call output_databuffer(ncid,   SKTcurrent)\n\n           deallocate(CANWTprev%field, stat=ierr)\n           deallocate(CANWTcurrent%field, stat=ierr)\n           deallocate(CANWTpost%field, stat=ierr)\n\n           deallocate(SKTprev%field, stat=ierr)\n           deallocate(SKTcurrent%field, stat=ierr)\n           deallocate(SKTpost%field, stat=ierr)\n\n           do i = 1, 4\n              call output_databuffer(ncid, STcurrent(i))\n              deallocate(STprev(i)%field, stat=ierr)\n              deallocate(STcurrent(i)%field, stat=ierr)\n              deallocate(STpost(i)%field, stat=ierr)\n           enddo\n           do i = 1, 4\n              ! Put a rough maximum on soil moisture, before we write it out.\n              where (SMcurrent(i)%field > 0.36) SMcurrent(i)%field = 0.36\n              call output_databuffer(ncid, SMcurrent(i))\n              deallocate(SMprev(i)%field, stat=ierr)\n              deallocate(SMcurrent(i)%field, stat=ierr)\n              deallocate(SMpost(i)%field, stat=ierr)\n           enddo\n\n        endif\n     endif\n\n     if (date(12:13) == \"00\") then\n        where (WEASDcurrent%field < 0) WEASDcurrent%field = 0\n        call output_databuffer(ncid, WEASDcurrent)\n        call output_databuffer(ncid, vegfra)\n     endif\n\n     if ( full_ic_frq > -1 ) then  ! full_ic_frq == -1 turns off extra processing for initial conditions.\n        if ( ( (full_ic_frq>0) .and. (mod(ihour, full_ic_frq)==0) ) .or. ( ihour==0 ) ) then\n           call output_databuffer(ncid, gvfmin)\n           call output_databuffer(ncid, gvfmax)\n           call output_databuffer(ncid, z2d)\n        endif\n     endif\n\n     ierr = nf90_close(ncid)\n     call error_handler(ierr, \"Problem closing Netcdf file\")\n\n     call geth_newdate(date, date, 1)\n  enddo DATELOOP\n\n\n  ! TEST\n  deallocate(Tprev%field, stat=ierr)\n  deallocate(Tcurrent%field, stat=ierr)\n  deallocate(Tpost%field, stat=ierr)\n\n  deallocate(Qprev%field, stat=ierr)\n  deallocate(Qcurrent%field, stat=ierr)\n  deallocate(Qpost%field, stat=ierr)\n\n  deallocate(Uprev%field, stat=ierr)\n  deallocate(Ucurrent%field, stat=ierr)\n  deallocate(Upost%field, stat=ierr)\n\n  deallocate(Vprev%field, stat=ierr)\n  deallocate(Vcurrent%field, stat=ierr)\n  deallocate(Vpost%field, stat=ierr)\n\n  deallocate(Pprev%field, stat=ierr)\n  deallocate(Pcurrent%field, stat=ierr)\n  deallocate(Ppost%field, stat=ierr)\n\n  deallocate(LWprev%field, stat=ierr)\n  deallocate(LWcurrent%field, stat=ierr)\n  deallocate(LWpost%field, stat=ierr)\n\n  deallocate(SW1prev%field, stat=ierr)\n  deallocate(SW1current%field, stat=ierr)\n  deallocate(SW1post%field, stat=ierr)\n\n  deallocate(SW2prev%field, stat=ierr)\n  deallocate(SW2current%field, stat=ierr)\n  deallocate(SW2post%field, stat=ierr)\n\n  deallocate(PCP1prev%field, stat=ierr)\n  deallocate(PCP1current%field, stat=ierr)\n  deallocate(PCP1post%field, stat=ierr)\n\n  deallocate(PCP2prev%field, stat=ierr)\n  deallocate(PCP2current%field, stat=ierr)\n  deallocate(PCP2post%field, stat=ierr)\n\n  deallocate(WEASDprev%field, stat=ierr)\n  deallocate(WEASDcurrent%field, stat=ierr)\n  deallocate(WEASDpost%field, stat=ierr)\n\n  deallocate(LANDSEA%field, stat=ierr)\n  deallocate(zcurrent%field, stat=ierr)\n  deallocate(gvfmin%field, stat=ierr)\n  deallocate(gvfmax%field, stat=ierr)\n  deallocate(vegfra%field, stat=ierr)\n  deallocate(z2d%field, stat=ierr)\n  deallocate(wrfinput%lat, stat=ierr)\n  deallocate(wrfinput%lon, stat=ierr)\n  deallocate(wrfinput%ter, stat=ierr)\n  deallocate(wrfinput%use, stat=ierr)\n  deallocate(wrfinput%veg, stat=ierr)\n  deallocate(geo_em%veg, stat=ierr)\n\n  call grib2_clear_parameter_table\n\n\ncontains\n\n!==============================================================================\n!==============================================================================\n  subroutine read_vtable(filename)\n    implicit none\n    character(len=*), intent(in) :: filename\n\n    character(len=256) :: string\n    integer :: ierr\n    integer :: jstart, jbar\n    character(len=64) :: val\n    integer :: vcount\n\n    !\n    ! Open the file\n    !\n    open(12, file=filename, status='old', form='formatted', iostat=ierr)\n\n    !\n    ! Scan forward until we find the string <VTABLE>\n    !\n    do\n       read(12, '(A255)', iostat=ierr) string\n       if (ierr /= 0) stop \"Problem searching for <VTABLE>\"\n       if (string == \"<VTABLE>\") exit\n    enddo\n\n    !\n    ! We've found the <VTABLE> marker.  Now read the table information\n    !\n\n    vcount = 0\n    VLOOP : do\n       read(12, '(A255)', iostat=ierr) string\n       if (ierr /= 0) stop \"Problem reading Variable Table\"\n       if (string == \"</VTABLE>\") exit\n       if (string(1:1) == \"-\") cycle\n       if (string(1:1) == \"#\") cycle\n       if (string(1:5) == \"GRIB1\") cycle\n       if (string(1:5) == \"Param\") cycle\n       write(*, '(A)') trim(string)\n\n       jstart = 1\n       vcount = vcount + 1\n       if (vcount > size(vtable)) then\n          write(*,'(/,\" ***** ERROR *****\")')\n          write(*,'(\" *****       Parameterized size of vtable (\",I4,\") is too small.\")') size(vtable)\n          write(*,'(\" *****       Change the dimensions of vtable and recompile.\",/)')\n          stop\n       endif\n\n       BLOOP : do j = 1, 11\n          ! The fields are delimited by '|'\n          jbar = index(string(jstart:255),'|') + jstart - 2\n          val = trim(adjustl(string(jstart:jbar)))\n          jstart = jbar + 2\n          select case (j)\n          case (1)\n             read(val,*,iostat=ierr) vtable(vcount)%g1_parm\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop\n             endif\n          case (2)\n             read(val,*,iostat=ierr) vtable(vcount)%g1_levtyp\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop\n             endif\n          case (3)\n             read(val,*,iostat=ierr) vtable(vcount)%level1\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop\n             endif\n          case (4)\n             if (val == \" \") then\n                vtable(vcount)%level2 = 999\n             else\n                read(val,*,iostat=ierr) vtable(vcount)%level2\n                if (ierr /= 0) then\n                   write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                   stop\n                endif\n             endif\n          case (5)\n             vtable(vcount)%name = val\n          case (6)\n             vtable(vcount)%units = val\n          case (7)\n             vtable(vcount)%desc = val\n          case (8)\n             read(val,*,iostat=ierr) vtable(vcount)%g2_discp\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop\n             endif\n          case (9)\n             read(val,*,iostat=ierr) vtable(vcount)%g2_cat\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop\n             endif\n          case (10)\n             read(val,*,iostat=ierr) vtable(vcount)%g2_parm\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop\n             endif\n          case (11)\n             read(val,*,iostat=ierr) vtable(vcount)%g2_levtyp\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop\n             endif\n          end select\n\n       enddo BLOOP\n\n       ! write(*,'(I4,I4,I4,I4,1x,A,1x,A,1x,A,I4,I4,I4,I4)') vtable(vcount)%g1_parm, vtable(vcount)%g1_levtyp, &\n       !      vtable(vcount)%level1, vtable(vcount)%level2, trim(vtable(vcount)%name), &\n       !      trim(vtable(vcount)%units), trim(vtable(vcount)%desc), vtable(vcount)%g2_discp, &\n       !      vtable(vcount)%g2_cat, vtable(vcount)%g2_parm, vtable(vcount)%g2_levtyp\n\n    enddo VLOOP\n\n    vtable_count = vcount\n\n  end subroutine read_vtable\n\n!==============================================================================\n!==============================================================================\n\n  subroutine data_buffer_init(prev, current, post, file_template, remap_type, label, fatality)\n    implicit none\n    type (DataBuffer) :: prev, current, post\n    character(len=256), dimension(MAXTEMPLATE), intent(in)  :: file_template\n    character(len=*),  intent(in)  :: label\n    character(len=*),  intent(in) :: remap_type\n    integer, optional, intent(in) :: fatality\n    prev%label    = label\n    prev%hdate    = \"0000-00-00_00:00:00\"\n    prev%flnm_template = file_template\n    prev%remap_type = remap_type\n    if (present(fatality)) then\n       prev%fatality=fatality\n    else\n       prev%fatality=0\n    endif\n    current = prev\n    post    = prev\n  end subroutine data_buffer_init\n\n!==============================================================================\n!==============================================================================\n\n  subroutine copy_data_buffer(out, in)\n    !\n    ! Copy the databuffer type from <in> to <out>\n    !\n    ! We do this to be explicit in allocating new memory for\n    ! pointer array <out%field>, and copying the data from\n    ! <in%field> to <out%field> (instead of merely pointing\n    ! <out%field> => <in%field>\n    implicit none\n    type(DataBuffer), intent(out) :: out\n    type(DataBuffer), intent(in)  :: in\n\n\n    out%label = in%label\n    out%units = in%units\n    out%hdate = in%hdate\n    out%flnm_template = in%flnm_template\n    out%layer1 = in%layer1\n    out%layer2 = in%layer2\n    out%remap_type = in%remap_type\n    out%fatality = in%fatality\n\n    if (associated(in%field)) then\n       allocate(out%field(size(in%field,1), size(in%field,2)))\n       out%field = in%field\n    else\n       nullify(out%field)\n    endif\n\n\n  end subroutine copy_data_buffer\n\n!==============================================================================\n!==============================================================================\n\n  subroutine process(input_date, current, prev, post, wrfinput)\n    use module_input_data_structure\n    implicit none\n    character(len=*), intent(in)    :: input_date\n    type(DataBuffer), intent(inout) :: current\n    type(DataBuffer), intent(inout) :: prev\n    type(DataBuffer), intent(inout) :: post\n    type (wrfinput_type), intent(in) :: wrfinput\n\n    type(input_data_type) :: datastruct\n    type(input_data_type) :: Zdatastruct\n    type(input_data_type) :: LANDSEAdatastruct\n    integer :: ierr\n    integer :: idts\n\n    integer :: idim\n    integer :: jdim\n\n    ! The fatality level in the DataBuffer structure indicates what sort\n    ! of errors are fatal and what sort of errors we want to try to\n    ! recover from.\n    !\n    ! fatality==0 means that any problem is a fatal error, and we stop.\n    !\n    ! fatality==2 means that if we cannot find a matching file, and we\n    ! cannot find files from which we may do temporal interpolation, we\n    ! do not stop, but return a missing-data field.  The calling routine\n    ! is responsible for filling in missing data.\n    nullify(datastruct%data)\n    nullify(zdatastruct%data)\n    nullify(LANDSEAdatastruct%data)\n\n    idim = wrfinput%idim\n    jdim = wrfinput%jdim\n\n    current%hdate = input_date(1:13)//\":00:00\"\n\n    if (associated(current%field)) then\n       deallocate(current%field)\n       nullify(current%field)\n    endif\n\n    ! First, check if a post buffer matches the current date.\n    if (post%hdate == current%hdate) then\n       ! The post buffer matches the current date.  This is the data we want.\n\n       call copy_data_buffer(current, post)\n       if (associated(prev%field)) deallocate(prev%field)\n       call copy_data_buffer(prev, post)\n\n       deallocate(post%field)\n       nullify(post%field)\n       post%hdate = \"0000-00-00_00:00:00\"\n       return\n    endif\n\n    ! Next, search for a GRIB file matching the current date.\n\n    call grib_file_search_now(current, datastruct, ierr)\n\n    if (ierr == 0) then\n\n       ! If this is air temperature data, we need to adjust to sea-level:\n       ! This will later be adjusted back to the destination surface elevation.\n       if (current%label == \"T2D\") then\n          ! Get the source model terrain data file.\n          Zcurrent%hdate = current%hdate\n          call grib_file_search_now(Zcurrent, Zdatastruct, ierr)\n          if (ierr /= 0) then\n             stop \"Source model terrain data not found\"\n          endif\n\n          if ( .not. check_if_same_map(datastruct, Zdatastruct) ) then\n             stop \"1) Source model terrain dimensions do not match source model temperature dimensions\"\n          endif\n          datastruct%data = datastruct%data - ( -0.0065 * Zdatastruct%data )\n          deallocate(Zdatastruct%data)\n          nullify(Zdatastruct%data)\n       endif\n\n       ! If this field is soil temperature, fill in some water points\n       ! with a smooth expansion of the land-point data.  We do this\n       ! so that interpolation can be a little more sane.\n       if ( (current%label(1:6) == \"STEMP_\") .or. (current%label(1:6) == \"SMOIS_\") ) then\n          ! Get the source model Land/Sea mask data.\n          LANDSEA%hdate = current%hdate\n          call grib_file_search_now(LANDSEA, LANDSEAdatastruct, ierr)\n          if (ierr /= 0) then\n             stop \"Source model land/sea data not found\"\n          endif\n          call fillsm(datastruct%data, (LANDSEAdatastruct%data /= 0), datastruct%nx, datastruct%ny)\n          deallocate(LANDSEAdatastruct%data)\n          nullify(LANDSEAdatastruct%data)\n       endif\n\n       ! remap the datastruct data to the model grid\n       if (current%label == \"RAINRATE\") then\n          allocate(current%field(idim, jdim))\n          if (rainfall_interp == 0) then\n             call interp_rainfall_nearest_neighbor(datastruct, current%field, wrfinput%idim, wrfinput%jdim, wrfinput)\n          else if (rainfall_interp == 1) then\n             call interp_rainfall(datastruct, current%field, wrfinput%idim, wrfinput%jdim, wrfinput)\n             ! call another_interp_rainfall(datastruct, current%field, wrfinput%idim, wrfinput%jdim, wrfinput)\n          endif\n       else\n          ! This remap function allocates current%field and fills it.\n          call remap(datastruct, wrfinput, current)\n       endif\n       deallocate(datastruct%data)\n       nullify(datastruct%data)\n\n       if ( (current%label(1:6) == \"STEMP_\") .or. (current%label(1:6) == \"SMOIS_\") ) then\n!          where (wrfinput%use == wrfinput%iswater) current%field=-1.E36\n       endif\n\n       ! Make the current data available as previous data, in preparation for the next time step.\n       if (associated(prev%field)) deallocate(prev%field)\n       call copy_data_buffer(prev, current)\n\n       ! Clear post\n       if (associated(post%field)) then\n          deallocate(post%field)\n          nullify(post%field)\n       endif\n       post%hdate = \"0000-00-00_00:00:00\"\n\n       ! We've got the data we wanted, so get out of here.\n       return\n\n    endif\n\n    ! We did not find data.  Let's try to temporally interpolate.\n\n    ! A \"prev\" buffer must exist for us.  Check that.\n\n    if (prev%hdate ==  \"0000-00-00_00:00:00\") then\n\n       if (current%fatality == 2) then\n          allocate(current%field(idim, jdim))\n          current%field = -1.E36\n          write(*,'(13x, \":  Prior data missing for \", A, \".  Returning missing-data field.\")') &\n               trim(current%label)\n          return\n       endif\n\n       write(*,'(\"Field label= \",A)') trim(current%label)\n       write(*,'(\"No previous data.\")')\n       stop\n    endif\n\n    ! The \"prev\" buffer must be recent.  Check that\n    call geth_idts (current%hdate, prev%hdate, idts)\n    if (idts > 43200) then\n\n       if (current%fatality == 2) then\n          allocate(current%field(idim, jdim))\n          current%field = -1.E36\n          if (associated(prev%field)) then\n             deallocate(prev%field)\n             nullify(prev%field)\n          endif\n          prev%hdate = \"0000-00-00_00:00:00\"\n          write(*,'(13x, \":  Prior data is out-of-date for \", A, \".  Returning missing-data field.\")') &\n               trim(current%label)\n          return\n       endif\n\n       write(*,'(\"Previous data is out of date.\")')\n       stop\n    endif\n\n    ! Check for a \"post\" buffer.\n\n    if (post%hdate > current%hdate) then\n       call geth_idts(post%hdate, prev%hdate, idts)\n       if (idts > 43200) then\n\n          if (current%fatality == 2) then\n             allocate(current%field(idim, jdim))\n             current%field = -1.E36\n             if (associated(prev%field)) then\n                deallocate(prev%field)\n                nullify(prev%field)\n             endif\n             prev%hdate = \"0000-00-00_00:00:00\"\n             write(*,'(13x, \":  Time range for interpolation of \", A, \" is too large.  \",&\n                  &\"Returning missing-data field.\")') &\n                  trim(current%label)\n             return\n          endif\n          stop\n       endif\n\n       if (current%label == \"RAINRATE\") then\n          ! Don't temporally interpolate the rain rate.\n          allocate(current%field(size(prev%field,1), size(prev%field,2)))\n          ! Take the \"post\" field, because that field should be the accumulation\n          ! between \"prev\" and \"post\"\n          current%field = post%field\n       else\n          call temporal_interpolation(prev, post, current)\n       endif\n       ! We have the data we want, so we can exit.\n       return\n    endif\n\n    ! No post buffer, so we must read some new data into a post buffer\n\n    call grib_file_search_future(current, post, datastruct, ierr)\n\n    if (ierr /= 0) then\n\n       if (current%fatality == 2) then\n          allocate(current%field(idim, jdim))\n          current%field = -1.E36\n          if (associated(prev%field)) then\n             deallocate(prev%field)\n             nullify(prev%field)\n          endif\n          prev%hdate = \"0000-00-00_00:00:00\"\n          write(*,'(13x, \":  No later data for interpolation of \", A, \".  Returning missing-data field.\")') &\n               trim(current%label)\n          return\n       endif\n\n       write(*,'(\"We could not find later data to interpolate\")')\n       stop\n    endif\n\n    ! If this is air temperature data, we need to adjust to sea-level:\n    ! This will later be adjusted back to the destination surface elevation.\n    if (current%label == \"T2D\") then\n       ! Get the source model terrain data file.\n       Zcurrent%hdate = post%hdate\n       call grib_file_search_now(Zcurrent, Zdatastruct, ierr)\n       if (ierr /= 0) then\n          stop \"Source model terrain data not found\"\n       endif\n       if ( .not. check_if_same_map(datastruct, Zdatastruct) ) then\n          stop \"2) Source model terrain dimensions do not match source model temperature dimensions\"\n       endif\n       datastruct%data = datastruct%data - ( -0.0065 * Zdatastruct%data )\n       deallocate(Zdatastruct%data)\n       nullify(Zdatastruct%data)\n    endif\n\n    ! remap the datastruct data to the model grid\n\n    ! This remap function allocates post%field and fills it.\n    call remap(datastruct, wrfinput, post)\n    deallocate(datastruct%data)\n    nullify(datastruct%data)\n\n    if (current%label == \"RAINRATE\") then\n       ! Don't temporally interpolate the rain rate.\n       ! Simply carry the previous value forward.\n       allocate(current%field(size(prev%field,1), size(prev%field,2)))\n       current%field = post%field\n    else\n       call temporal_interpolation(prev, post, current)\n    endif\n\n    ! We have the data we want, and prev and post are both up-to-date,\n    ! so we can exit.\n\n  end subroutine process\n\n!==============================================================================\n!==============================================================================\n\n  subroutine remap(datastruct, wrfinput, buff)\n    use module_input_data_structure\n    implicit none\n    type(input_data_type), intent(in)  :: datastruct\n    type (wrfinput_type), intent(in) :: wrfinput\n    type(DataBuffer), intent(inout)  :: buff\n\n    integer :: i, j\n    integer :: idim, jdim\n    real, allocatable, dimension(:,:) :: etax, etay\n\n    buff%layer1 = datastruct%layer1\n    buff%layer2 = datastruct%layer2\n\n    idim = wrfinput%idim\n    jdim = wrfinput%jdim\n    allocate(buff%field(idim,jdim))\n    allocate(etax(idim,jdim))\n    allocate(etay(idim,jdim))\n\n    do i = 1, idim\n       do j = 1, jdim\n          call latlon_to_ij(datastruct%proj, wrfinput%lat(i,j), wrfinput%lon(i,j), etax(i,j), etay(i,j))\n          if (buff%remap_type==\"bint\") then\n             buff%field(i,j) = bint_p(datastruct%data, datastruct%nx, datastruct%ny, etax(i,j), etay(i,j))\n          else if (buff%remap_type == \"4pt\") then\n             buff%field(i,j) = four_point_p(datastruct%data, datastruct%nx, datastruct%ny, etax(i,j), etay(i,j))\n          else\n             print*, \"'\"//trim(buff%remap_type)//\"'\"\n             stop \"remap type\"\n          endif\n\n       enddo\n    enddo\n    deallocate(etax)\n    deallocate(etay)\n\n\n  end subroutine remap\n\n!==============================================================================\n!==============================================================================\n\n  subroutine grib_file_search_future(current, post, datastruct, ierr)\n    use module_input_data_structure\n    implicit none\n    type(DataBuffer), intent(inout) :: current\n    type(DataBuffer), intent(inout) :: post\n    type(input_data_type), intent(out) :: datastruct\n    integer, intent(out) :: ierr\n\n    character(len=13) :: kdate\n    integer :: i, j\n    character(len=256) :: flnm\n\n    logical :: lexist\n\n    nullify(datastruct%data)\n\n    ierr = 1\n    kdate = current%hdate(1:13)\n\n    DATE_SEEK_LOOP : do i = 1, 12\n\n       TEMPLATE_LOOP : do j = 1, MAXTEMPLATE\n          if (current%flnm_template(j) /= \" \") then\n             flnm = current%flnm_template(j)\n\n             call fill_template(flnm, kdate)\n\n             write(*,'(A)') \"             \"//\":  Checking for file \"//trim(flnm)\n\n             inquire(file=trim(flnm), exist=lexist)\n             if ( .not. lexist ) then\n                inquire(file=trim(flnm)//\".bz2\", exist=lexist)\n                if (lexist) then\n                   flnm = trim(flnm)//\".bz2\"\n                endif\n             endif\n\n             if (lexist) then\n                write(*,'(A)') \"             \"//\":  Found file \"//trim(flnm)\n                ierr = 0\n                exit DATE_SEEK_LOOP\n             endif\n          endif\n       enddo TEMPLATE_LOOP\n\n       call geth_newdate(kdate, kdate, 1)\n\n    enddo DATE_SEEK_LOOP\n\n    ! If we haven't found any matching data yet, then get out of here.\n    if (ierr == 1) return\n\n    call get_single_datastruct_from_grib(trim(flnm), kdate, datastruct, ierr)\n    post%hdate = kdate//\":00:00\"\n    post%units = datastruct%units\n\n  end subroutine grib_file_search_future\n\n!==============================================================================\n!==============================================================================\n\n  subroutine grib_file_search_now(current, datastruct, ierr)\n    use module_input_data_structure\n    implicit none\n    type(DataBuffer), intent(inout)  :: current\n    type(input_data_type), intent(out) :: datastruct\n    integer, intent(out) :: ierr\n    character(len=256) :: flnm\n    logical :: lexist\n    integer :: j\n    character(len=13) :: kdate\n\n    kdate = current%hdate(1:13)\n\n    nullify(datastruct%data)\n\n    ierr = 1\n\n    TEMPLATE_LOOP : do j = 1, MAXTEMPLATE\n       if (current%flnm_template(j) /= \" \") then\n          flnm = current%flnm_template(j)\n\n          call fill_template(flnm, kdate)\n\n          write(*,'(A)') \"             \"//\":  Checking for file \"//trim(flnm)\n\n          inquire(file=trim(flnm), exist=lexist)\n          if ( .not. lexist ) then\n             inquire(file=trim(flnm)//\".bz2\", exist=lexist)\n             if (lexist) then\n                flnm = trim(flnm)//\".bz2\"\n             endif\n          endif\n\n          if (lexist) then\n             write(*,'(A)') \"             \"//\":  Found file \"//trim(flnm)\n             ierr = 0\n             exit TEMPLATE_LOOP\n          endif\n       endif\n    enddo TEMPLATE_LOOP\n    if (ierr == 1) return\n\n    call get_single_datastruct_from_grib(trim(flnm), kdate, datastruct, ierr)\n    current%units = datastruct%units\n\n    if ( current%label /= datastruct%field ) then\n       write(*,'(/,1x,80(\"*\"))')\n       write(*,'(\" *****  PROBLEM:  Requested field name does not match the name in the Vtable entry.\")')\n       write(*,'(\" ***** \")')\n       write(*,'(\" *****      Requested field name: ''\",A,\"''\")') trim(current%label)\n       write(*,'(\" *****      Field name in the Vtable entry:  ''\",A,\"''\")') trim(datastruct%field)\n       write(*,'(\" ***** \")')\n       write(*,'(\" *****  Please check your VTable entries and filename templates in your namelist\")')\n       write(*,'(\" *****  to be sure you are getting the fields you think you are getting.\")')\n       write(*,'(1x,80(\"*\"),/)')\n       stop\n    endif\n\n  end subroutine grib_file_search_now\n\n!==============================================================================\n!==============================================================================\n\n  subroutine temporal_interpolation(prev, post, current)\n    implicit none\n    type(DataBuffer), intent(in) :: prev\n    type(DataBuffer), intent(in) :: post\n    type(DataBuffer), intent(inout) :: current\n\n    integer :: xdiff\n    integer :: tdiff\n    real    :: fraction\n\n    call geth_idts(current%hdate, prev%hdate, xdiff)\n    call geth_idts(post%hdate, prev%hdate, tdiff)\n\n    fraction = real(xdiff)/real(tdiff)\n\n    allocate(current%field(size(prev%field,1), size(prev%field,2)))\n    current%field = (prev%field)*(1.0-fraction) + (post%field)*(fraction)\n\n!KWM    if (prev%layer1 /= post%layer1) then\n!KWM       print*, 'prev%layer1  = ', prev%layer1\n!KWM       print*, 'post%layer1  = ', post%layer1\n!KWM       stop \"layer1 mismatch\"\n!KWM    endif\n!KWM    if (prev%layer2 /= post%layer2) then\n!KWM       print*, 'prev%layer2  = ', prev%layer2\n!KWM       print*, 'post%layer2  = ', post%layer2\n!KWM       stop \"layer2 mismatch\"\n!KWM    endif\n!KWM    current%layer1 = prev%layer1\n!KWM    current%layer2 = prev%layer2\n\n  end subroutine temporal_interpolation\n\n!==============================================================================\n!==============================================================================\n\n  subroutine output_databuffer(ncid, buff)\n    implicit none\n    integer,              intent(in) :: ncid\n    type (DataBuffer),    intent(in) :: buff\n    ! Wrapper around call to output_to_netcdf\n    call output_to_netcdf(ncid, buff%label, buff%units, buff%field, &\n         size(buff%field,1), size(buff%field,2), buff%layer1, buff%layer2)\n  end subroutine output_databuffer\n\n!==============================================================================\n!==============================================================================\n\n  subroutine get_single_datastruct_from_grib(gribflnm, kdate, datastruct, ierr)\n    use module_grib\n    use kwm_string_utilities\n    use module_input_data_structure\n    implicit none\n    character(len=*), intent(in) :: gribflnm, kdate\n    type(input_data_type), intent(out) :: datastruct\n    integer, intent(out) :: ierr\n\n    character(len=256) :: flnm\n    integer(kind=8) :: gribunit\n    integer :: istat\n\n    !-------------------------------------------------------------------------\n    nullify(datastruct%data)\n\n    flnm = gribflnm\n\n    call fill_template(flnm, kdate)\n\n    ! Open the unit and read the first GRIB record\n    call gribopen(flnm, gribunit, ierr);\n    if (ierr /= 0) then\n       if (ierr == 2) then\n          write(*, '(\"File does not exist: \",A)') trim(flnm)\n       else\n          write(*, '(\"Undetermined problem opening file: \", A)') trim(flnm)\n       endif\n       return\n       stop \"get_single_datastruct_from_grib\"\n    endif\n    if (associated(datastruct%data)) then\n       deallocate(datastruct%data)\n       nullify(datastruct%data)\n    endif\n    call read_grib_unit(gribunit, datastruct, ierr, trim(flnm))\n    if (ierr /= 0) then\n       print*, 'Returning error flag from get_single_datastruct_from_grib (1)'\n       print*, 'gribunit = ', gribunit\n       print*, 'flnm = ', trim(flnm)\n       print*, 'ierr = ', ierr\n       if (associated(datastruct%data)) then\n          deallocate(datastruct%data)\n          nullify(datastruct%data)\n       endif\n       return\n    endif\n    call gribclose(gribunit)\n\n  end subroutine get_single_datastruct_from_grib\n\n!==============================================================================\n!==============================================================================\n\n  subroutine read_grib_unit(nunit, datastruct, ierr, info)\n    use module_grib\n    use module_input_data_structure\n    implicit none\n    integer(kind=8), intent(in) :: nunit\n    type(input_data_type), intent(out) :: datastruct\n    integer :: ierr, i, j\n    real :: rb, xdum\n    real :: oldmax\n    real :: newmax\n    integer :: astat\n    character(len=*), intent(in), optional :: info\n\n    type(GribStruct)  :: grib\n    character(len=64)  :: name\n    character(len=256) :: units\n    character(len=256) :: description\n\n    ! Returned from grib_level_information\n    character(len=256) :: level_type\n    character(len=256) :: level_units\n    real               :: level_value\n    real               :: level2_value\n\n    ! Returned from grib_time_information\n    character(len=19)  :: reference_date\n    character(len=19)  :: valid_date\n    character(len=256) :: process\n    character(len=256) :: processing\n    integer            :: p1_seconds\n    integer            :: p2_seconds\n\n    real, parameter :: grrth = 6370.949\n    real, external  :: tand\n    real, external  :: sind\n    real, external  :: cosd\n\n    !\n    ! Get a grib field, unpacking all header information.\n    !\n    nullify(grib%buffer)\n    nullify(grib%bitmap)\n    nullify(grib%array)\n    nullify(grib%sec7%floated)\n    nullify(datastruct%data)\n\n    call grib_next_field(nunit, grib, ierr)\n    if (ierr /= 0) then\n       write(*, '(\"Returning error from read_grib_unit:  nunit = \", I3, \"  ierr = \", I3)') nunit, ierr\n       if (present(info)) print*, info\n       return\n    endif\n\n    !\n    ! Match the grib record we've just read with one of our grib table entries.\n    !\n    if (grib%edition == 1) then\n       G1SEARCH : do j = 1, vtable_count\n          if ( (grib%g1sec1%parameter == vtable(j)%g1_parm) .and. &\n               (grib%g1sec1%leveltyp  == vtable(j)%g1_levtyp) .and. &\n               (grib%g1sec1%levelval  == vtable(j)%level1) ) then\n             if ( (grib%g1sec1%level2val  == vtable(j)%level2) .or. &\n                  (grib%g1sec1%level2val < -1.E25) .or. &\n                  (vtable(j)%level2 == 999) ) then\n                ! print*, 'Parameter match:  ', &\n                !      grib%g1sec1%parameter, grib%g1sec1%leveltyp, grib%g1sec1%levelval, grib%g1sec1%level2val\n                datastruct%field  = vtable(j)%name\n                write(*, '(A, \"  GRIB Editon 1\")') datastruct%field\n                exit G1SEARCH\n             endif\n          endif\n          if (j == vtable_count) then\n             write(*,'(/,\" ***** ERROR *****\")')\n             write(*,'(\" *****       GRIB Edition 1 data does not match a Vtable entry\")')\n             print*, grib%g1sec1%parameter, grib%g1sec1%leveltyp, grib%g1sec1%levelval, grib%g1sec1%level2val\n             stop \"Edition 1\"\n          endif\n       enddo G1SEARCH\n    else if (grib%edition == 2) then\n       G2SEARCH : do j = 1, vtable_count\n          if ( (grib%discipline == vtable(j)%g2_discp) .and. &\n               (grib%sec4%parameter_category == vtable(j)%g2_cat) .and. &\n               (grib%sec4%parameter_number == vtable(j)%g2_parm) .and. &\n               (grib%sec4%ltype1  == vtable(j)%g2_levtyp) .and. &\n               (grib%sec4%lvalue1  == vtable(j)%level1) ) then\n             if ( (grib%sec4%lvalue2  == vtable(j)%level2) .or. &\n                  (grib%sec4%lvalue2 < -1.E25) .or. &\n                  (vtable(j)%level2 == 999) ) then\n                ! print*, 'Parameter match:  ', &\n                !      grib%discipline, grib%sec4%parameter_category, grib%sec4%ltype1, grib%sec4%lvalue1, grib%sec4%lvalue2\n                datastruct%field  = vtable(j)%name\n                write(*, '(A, \"  GRIB Editon 2\")') datastruct%field\n                exit G2SEARCH\n             endif\n          endif\n          if (j == vtable_count) then\n             write(*,'(/,\" ***** ERROR *****\")')\n             write(*,'(\" *****       GRIB Edition 2 data does not match a Vtable entry\")')\n             print*, grib%discipline, grib%sec4%parameter_category, grib%sec4%parameter_number, &\n                  grib%sec4%ltype1, grib%sec4%lvalue1, grib%sec4%lvalue2\n             stop \"Edition 2\"\n          endif\n       enddo G2SEARCH\n    endif\n\n    call grib_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    datastruct%hdate = valid_date\n\n    datastruct%layer1 = -1.E36\n    datastruct%layer2 = -1.E36\n\n    description = \" \"\n    call grib_parameter_text_information(grib, name, units, description)\n\n    datastruct%desc   = description\n    datastruct%units  = units\n\n    ! print*, 'description = \"' // trim(description) // '\"'\n\n    call grib_level_information(grib, level_type, level_units, level_value, level2_value)\n\n    datastruct%layer1 = level_value\n    datastruct%layer2 = level2_value\n\n    call grib_map_information(grib)\n\n    datastruct%nx = grib%mapinfo%nx\n    datastruct%ny = grib%mapinfo%ny\n\n    call map_init(datastruct%proj)\n!KWM    datastruct%proj%lat1 = grib%mapinfo%lat1\n!KWM    if (grib%mapinfo%lon1 > 180) then\n!KWM       datastruct%proj%lon1 = grib%mapinfo%lon1-360\n!KWM    else\n!KWM       datastruct%startlon = grib%mapinfo%lon1\n!KWM    endif\n\n    if (grib%mapinfo%hproj == \"CE\") then\n\n       call map_set(PROJ_LATLON, datastruct%proj, lat1=grib%mapinfo%lat1, lon1=grib%mapinfo%lon1, &\n            latinc=grib%mapinfo%dy, loninc=grib%mapinfo%dx, knowni=1.0, knownj=1.0)\n\n\n    else if (grib%mapinfo%hproj == \"LC\") then\n\n       call map_set(PROJ_LC, datastruct%proj, lat1=grib%mapinfo%lat1, lon1=grib%mapinfo%lon1, &\n            knowni=1.0, knownj=1.0, truelat1=grib%mapinfo%truelat1, truelat2=grib%mapinfo%truelat2, &\n            stdlon=grib%mapinfo%xlonc, dx=grib%mapinfo%dx*1.E3)\n\n    else if (grib%mapinfo%hproj == \"ST\") then\n\n       call map_set(PROJ_PS, datastruct%proj, lat1=grib%mapinfo%lat1, lon1=grib%mapinfo%lon1, truelat1=grib%mapinfo%truelat1, &\n            knowni=1.0, knownj=1.0, stdlon=grib%mapinfo%xlonc, dx=grib%mapinfo%dx*1.E3)\n\n    else\n\n       write(*,'(\"Unrecognized grib%mapinfo%hproj:  \", A2)') grib%mapinfo%hproj\n       stop\n\n    endif\n\n    if (associated(datastruct%data)) then\n       deallocate(datastruct%data)\n       nullify(datastruct%data)\n    endif\n    allocate(datastruct%data(datastruct%nx,datastruct%ny), stat=astat)\n    if (astat /= 0) stop \"Problem (A) allocating datastruct%data\"\n\n    call gribdata(grib)\n    datastruct%data = grib%array\n    call deallogrib(grib)\n\n    ! If the data are from GCIP SRB archives, they're at 15 minutes off the hour.\n    ! Ignore that 15-minute offset in that case, and put the date right on the hour.\n\n    if (datastruct%field == \"SWDOWN\") then\n       if (rescale_shortwave) then\n          call rescale_sw_time_offset(datastruct)\n       endif\n       datastruct%hdate(15:16) = \"00\"\n       ! TEST:  Set zero data values to missing data for GCIP SW fields\n       ! where (datastruct%data <= 0) datastruct%data = -1.E36\n    endif\n\n!KWM    if (description == \"Plant Canopy Surface Water\") then\n    if (datastruct%field == \"CANWAT\") then\n       ! Convert canwat from kg m{-2} (that is, mm) to m\n       datastruct%data = datastruct%data * 1.E-3\n       datastruct%units = \"m\"\n    endif\n\n    ! print*, 'Description = \"'//trim(description)//'\"'\n    ! if (description == \"Total precipitation\") then\n    if (datastruct%field == \"RAINRATE\") then\n       ! print*, 'datastruct%units = ', datastruct%units\n       ! Convert from kg m{-2} (that is, mm) in <nn> hours to mm s{-1}\n       if ( (datastruct%units == \"kg m{-2}\") .or. (datastruct%units == \"mm\") ) then\n!KWM          print*, 'Time information:  '\n!KWM          print*, '                   Reference Date ' // reference_date\n!KWM          print*, '                   Reference Date ' // valid_date\n!KWM          print*, '                                  ' // trim(process)\n!KWM          print*, '                                  ' // trim(processing)\n!KWM          print*, '                               P1 ', p1_seconds\n!KWM          print*, '                               P2 ', p2_seconds\n          if (processing(1:12) == \"Accumulation\") then\n             oldmax = maxval(datastruct%data, mask=(datastruct%data > -1.E25))\n             write(*,'(13x, \"Maxval adjusted from \", F12.6)', advance=\"no\") oldmax\n             where (datastruct%data > -1.E25)\n                datastruct%data = datastruct%data * (1.0 / float(p2_seconds - p1_seconds))\n             endwhere\n             newmax = maxval(datastruct%data, mask=(datastruct%data > -1.E25))\n             write(*,'(\" to \", F12.6, \":    factor of \", I8)') newmax, NINT(oldmax/newmax)\n             ! Change the units to mm/s, reflecting the rescaling we just did.\n             datastruct%units = \"mm s{-1}\"\n          else\n             stop \"Precip Problem A?\"\n          endif\n       else\n          stop \"Precip Problem B?\"\n       endif\n    endif\n\n  end subroutine read_grib_unit\n\n!==============================================================================\n!==============================================================================\n\n  logical function check_if_same_map(A, B) result (lval)\n    ! Check two DATASTRUCT structures to see if they have the same grid/map.\n    use module_input_data_structure\n    implicit none\n    type(input_data_type), intent(in) :: A\n    type(input_data_type), intent(in) :: B\n\n    lval = .TRUE.\n\n    if (A%proj%code /= B%proj%code)    lval = .FALSE.\n    if (A%nx       /= B%nx)       lval = .FALSE.\n    if (A%ny       /= B%ny)       lval = .FALSE.\n    if (abs(A%proj%lat1 - B%proj%lat1) > 1.E-4) lval = .FALSE.\n    if (abs(A%proj%lon1 - B%proj%lon1) > 1.E-4) lval = .FALSE.\n    if ((A%proj%latinc > -1.E25) .and. (B%proj%latinc > -1.E25)) then\n       if (abs(A%proj%latinc - B%proj%latinc) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%loninc > -1.E25) .and. (B%proj%loninc > -1.E25)) then\n       if (abs(A%proj%loninc - B%proj%loninc) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%dx > -1.E25) .and. (B%proj%dx > -1.E25)) then\n       if (abs(A%proj%dx - B%proj%dx) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%dy > -1.E25) .and. (B%proj%dy > -1.E25)) then\n       if (abs(A%proj%dy - B%proj%dy) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%stdlon > -1.E25) .and. (B%proj%stdlon > -1.E25)) then\n       if (abs(A%proj%stdlon  - B%proj%stdlon) > 1.E-4)   lval = .FALSE.\n    endif\n    if ((A%proj%truelat1 > -1.E25) .and. (B%proj%truelat1 > -1.E25)) then\n       if (abs(A%proj%truelat1 - B%proj%truelat1) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%truelat2 > -1.E25) .and. (B%proj%truelat2 > -1.E25)) then\n       if (abs(A%proj%truelat2 - B%proj%truelat2) > 1.E-4) lval = .FALSE.\n    endif\n\n    if (.not. lval) then\n       write(*, '(\"CHECK_IF_SAME_MAP:\")')\n       write(*, '(\"     proj_code= \", I12, I12)') A%proj%code, B%proj%code\n       write(*, '(\"     nx       = \", I12, I12)') A%nx, B%nx\n       write(*, '(\"     ny       = \", I12, I12)') A%ny, B%ny\n       write(*, '(\"     startlat = \", F20.12, F20.12)') A%proj%lat1, B%proj%lat1\n       write(*, '(\"     startlon = \", F20.12, F20.12)') A%proj%lon1, B%proj%lon1\n       write(*, '(\"     deltalat = \", F20.12, F20.12)') A%proj%latinc, B%proj%latinc\n       write(*, '(\"     deltalon = \", F20.12, F20.12)') A%proj%loninc, B%proj%loninc\n       write(*, '(\"     dx       = \", F20.12, F20.12)') A%proj%dx, B%proj%dx\n       write(*, '(\"     dy       = \", F20.12, F20.12)') A%proj%dy, B%proj%dy\n       write(*, '(\"     xlonc    = \", F20.12, F20.12)') A%proj%stdlon, B%proj%stdlon\n       write(*, '(\"     truelat1 = \", F20.12, F20.12)') A%proj%truelat1, B%proj%truelat1\n       write(*, '(\"     truelat2 = \", F20.12, F20.12)') A%proj%truelat2, B%proj%truelat2\n    endif\n\n  end function check_if_same_map\n\n!==============================================================================\n!==============================================================================\n\nend program consolidate\n\n!==============================================================================\n!==============================================================================\n\nsubroutine interpolate_vegetation(date, geo_em, vegfra, idim, jdim)\n  use module_geo_em\n  implicit none\n  character(len=*),           intent(in)  :: date\n  type (geo_em_type),         intent(in)  :: geo_em\n  integer,                    intent(in)  :: idim, jdim\n  real, dimension(idim,jdim), intent(out) :: vegfra\n\n  integer :: imo\n  integer :: imo2\n  integer :: imody\n  real, allocatable, dimension(:,:) :: xdum, xdum2\n\n  integer, parameter, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n\n  ! Vegetation Fraction field\n\n  read(date(6:10), '(I2,1x,I2)') imo, imody\n\n  if (imody == 15) then\n     vegfra = geo_em%veg(:,:,imo)\n  else if (imody > 15) then\n     allocate(xdum(idim,jdim), xdum2(idim,jdim))\n     xdum  = geo_em%veg(:,:,imo)\n     xdum2 = geo_em%veg(:,:,mod(imo,12)+1)\n     vegfra = xdum + float(imody-15)/float(mday(imo))*(xdum2-xdum)\n     deallocate(xdum, xdum2)\n  else if (imody < 15) then\n     allocate(xdum(idim,jdim), xdum2(idim,jdim))\n     xdum2  = geo_em%veg(:,:,imo)\n     if (imo == 1) then\n        imo2 = 12\n     else\n        imo2 = imo - 1\n     endif\n     xdum   = geo_em%veg(:,:,imo2)\n\n     vegfra = xdum + float(mday(imo2)-(15-imody)) / float(mday(imo2)) &\n          *(xdum2-xdum)\n     deallocate(xdum, xdum2)\n     where (vegfra <= 0) vegfra = 1.E-2 !???\n  endif\nend subroutine interpolate_vegetation\n\n!==============================================================================\n!==============================================================================\n\nsubroutine fill_template(string, date)\n  use kwm_string_utilities\n  use kwm_date_utilities\n  implicit none\n  character(len=*), intent(inout) :: string\n  character(len=*), intent(in)    :: date\n\n  character(len=2)  :: hh\n  character(len=13) :: dd\n  character(len=3)  :: hnn\n  integer           :: nn\n  integer           :: idx\n\n  call strrep(string, \"<YYYY>\", date(1:4))\n  call strrep(string, \"<MM>\",   date(6:7))\n  call strrep(string, \"<DD>\",   date(9:10))\n  call strrep(string, \"<HH>\",   date(12:13))\n  call strrep(string, \"<date>\", date(1:4)//date(6:7)//date(9:10)//date(12:13))\n\n  !\n  ! Build the filenames for analyses in range 0-(minus)12h\n  !\n  if ( index(string, \"<init+12>\") > 0) then\n     hh = date(12:13)\n     if (hh == \"00\") then\n        dd = date\n     elseif (hh <= \"12\") then\n        dd=date(1:11)//\"12\"\n     else\n        dd=date(1:11)//\"00\"\n        call geth_newdate(dd, dd, 24)\n     endif\n     call strrep(string, \"<init+12>\", dd(1:4)//dd(6:7)//dd(9:10)//dd(12:13))\n  endif\n\n!\n!  Build the filenames for forecasts in ranges 0-12h, 12-24h, 24-36h, etc.\n!\n\n  idx = index(string, \"<init-\")\n  if (idx > 0) then\n     hnn = string(idx+5:idx+7)\n     read(hnn,*) nn\n     call geth_newdate(dd, date, (nn+12))\n     hh = dd(12:13)\n     if (hh == \"00\") then\n        call geth_newdate(dd, dd, -12)\n     elseif (hh <= \"12\") then\n        dd=dd(1:11)//\"00\"\n     else\n        dd=dd(1:11)//\"12\"\n     endif\n     call strrep(string, \"<init\"//hnn//\">\", dd(1:4)//dd(6:7)//dd(9:10)//dd(12:13))\n  endif\n\nend subroutine fill_template\n\n!==============================================================================\n!==============================================================================\n\nsubroutine open_netcdf_for_output(output_flnm, ncid, version, ix, jx, wrfinput)\n  use module_geo_em\n  use module_wrfinputfile\n  implicit none\n  character(len=*), intent(in) :: output_flnm\n  character(len=*), intent(in) :: version\n  integer, intent(in) :: ix, jx\n  integer, intent(out) :: ncid\n  type (wrfinput_type), intent(in) :: wrfinput\n\n  integer :: ierr, dimid\n  integer, parameter :: datestrlen = 19\n\n#ifdef _PARALLEL_\n  ierr = nf90_create(trim(output_flnm), NF90_CLOBBER, ncid)\n  call error_handler(ierr, \"Problem nf90_create: \"//trim(output_flnm))\n#else\n  ierr = nf90_create(trim(output_flnm), NF90_WRITE, ncid)\n  call error_handler(ierr, \"Problem nf90_create: \"//trim(output_flnm))\n#endif\n\n  ierr = nf90_def_dim(ncid, \"Time\", NF90_UNLIMITED, dimid)\n  call error_handler(ierr, \"Problem nf90_def_dim Time\")\n\n  ierr = nf90_def_dim(ncid, \"DateStrLen\", datestrlen, dimid)\n  call error_handler(ierr, \"Problem nf90_def_dim DateStrLen\")\n\n  ierr = nf90_def_dim(ncid, \"west_east\", ix, dimid)\n  call error_handler(ierr, \"Problem nf90_def_dim west_east\")\n\n  ierr = nf90_def_dim(ncid, \"south_north\", jx, dimid)\n  call error_handler(ierr, \"Problem nf90_def_dim south_north\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TITLE\", \"OUTPUT FROM CONSOLIDATE_GRIB \"//version)\n  call error_handler(ierr, \"Problem nf90_put_att TITLE\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -1.E36)\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"_FillValue\", -1.E36)\n  call error_handler(ierr, \"Problem nf90_put_att missing_value\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"WEST-EAST_GRID_DIMENSION\", ix+1)\n  call error_handler(ierr, \"Problem nf90_put_att WEST-EAST_GRID_DIMENSION\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"SOUTH-NORTH_GRID_DIMENSION\", jx+1)\n  call error_handler(ierr, \"Problem nf90_put_att SOUTH-NORTH_GRID_DIMENSION\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"DX\", wrfinput%proj%dx)\n  call error_handler(ierr, \"Problem nf90_put_att DX\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"DY\", wrfinput%proj%dy)\n  call error_handler(ierr, \"Problem nf90_put_att DY\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT1\", wrfinput%proj%truelat1)\n  call error_handler(ierr, \"Problem nf90_put_att TRUELAT1\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT2\", wrfinput%proj%truelat2)\n  call error_handler(ierr, \"Problem nf90_put_att TRUELAT2\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LA1\", wrfinput%proj%lat1)\n  call error_handler(ierr, \"Problem nf90_put_att LA1\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LO1\", wrfinput%proj%lon1)\n  call error_handler(ierr, \"Problem nf90_put_att LO1\")\n\n!KWM  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LA2\", wrfinput%la2)\n!KWM  call error_handler(ierr, \"Problem nf90_put_att LA2\")\n\n!KWM  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LO2\", wrfinput%lo2)\n!KWM  call error_handler(ierr, \"Problem nf90_put_att LO2\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"STAND_LON\", wrfinput%proj%stdlon)\n  call error_handler(ierr, \"Problem nf90_put_att STAND_LON\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", wrfinput%proj%code)\n  call error_handler(ierr, \"Problem nf90_put_att MAP_PROJ\")\n\n!\n! Even though the LDASIN files should work whichever landuse_datset\n! is used at the HRLDAS step, it might be good to know which was\n! used for making this dataset:\n!\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"MMINLU\", wrfinput%landuse_dataset)\n  call error_handler(ierr, \"Problem nf90_put_att MMINLU\")\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"Problem exiting define mode\")\nend subroutine open_netcdf_for_output\n\n!==============================================================================\n!==============================================================================\n\nsubroutine output_timestring_to_netcdf(ncid, hdate)\n  ! Write the date/time stamp as a variable to the NetCDF file.\n  use netcdf\n  use module_wrfinputfile\n  implicit none\n  integer,                     intent(in) :: ncid\n  character(len=*),            intent(in) :: hdate\n\n  integer,          parameter                :: DateStrLen = 19\n  character(len=1), dimension(DateStrLen, 1) :: output_hdate\n  integer                                    :: dimid_datestrlen\n  integer                                    :: dimid_time\n  integer                                    :: varid\n  integer                                    :: i\n  integer                                    :: ierr\n\n  output_hdate(:,1) = (/ \"0\",\"0\",\"0\",\"0\",\"-\",\"0\",\"0\",\"-\",\"0\",\"0\",\"_\",\"0\",\"0\",\":\",\"0\",\"0\",\":\",\"0\",\"0\" /)\n  do i = 1, len(hdate)\n     output_hdate(i,1) = hdate(i:i)\n  enddo\n\n  ierr = nf90_inq_dimid(ncid, \"Time\", dimid_time)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem finding dimension 'Time'\")\n\n  ierr = nf90_inq_dimid(ncid, \"DateStrLen\", dimid_datestrlen)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem finding dimension 'DateStrLen'\")\n\n  ierr = nf90_redef(ncid)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem NF90_REDEF\")\n\n  ierr = nf90_def_var(ncid,  \"Times\",  NF90_CHAR, (/dimid_datestrlen,dimid_Time/), varid)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem defining variable 'Times'\")\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem with enddef\")\n\n  ierr = nf90_put_var(ncid, varid, output_hdate, (/1,1/), (/datestrlen,1/))\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem putting variable 'Time'\")\n\nend subroutine output_timestring_to_netcdf\n\n!==============================================================================\n!==============================================================================\n\nsubroutine output_to_netcdf(ncid, name, units, array, idim, jdim, layer1, layer2)\n  use module_wrfinputfile\n  implicit none\n  integer, intent(in) :: ncid\n  character(len=*), intent(in) :: name\n  character(len=*), intent(in) :: units\n  integer, intent(in) :: idim, jdim\n  real, dimension(idim,jdim), intent(in) :: array\n  real, intent(in) :: layer1, layer2\n\n  integer :: varid, ierr\n  integer :: dimid_time, dimid_ix, dimid_jx\n\n  ierr = nf90_inq_dimid(ncid, \"Time\", dimid_time)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'Time'\")\n\n  ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'west_east'\")\n\n  ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'south_north'\")\n\n  ierr = nf90_redef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem NF90_REDEF\")\n\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_Time/), varid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem defining variable \"//trim(name))\n\n  ierr = nf90_put_att(ncid, varid, \"units\", trim(units))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting attribute units: \"//trim(units))\n\n  ! ierr = nf90_put_att(ncid, varid, \"missing_value\", -1.E36)\n  ierr = nf90_put_att(ncid, varid, \"_FillValue\", -1.E36)\n\n\n  if ((layer1 > -1.E25) .and. (layer2 > -1.E25)) then\n\n     ierr = nf90_put_att(ncid, varid, \"layer_top\", layer1)\n     call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting attribute 'layer_top'\")\n\n     ierr = nf90_put_att(ncid, varid, \"layer_bottom\", layer2)\n     call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting attribute 'layer_bottom': \")\n\n  endif\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem with enddef\")\n\n  ierr = nf90_put_var(ncid, varid, array, (/1,1,1/), (/idim,jdim,1/))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting variable \"//trim(name))\n\nend subroutine output_to_netcdf\n\n!==============================================================================\n!==============================================================================\n\nsubroutine fillsm(data, mask, nx, ny)\n  use kwm_grid_utilities\n  implicit none\n  integer,                    intent(in)      :: nx\n  integer,                    intent(in)      :: ny\n  real,    dimension(nx, ny), intent(inout)   :: data\n  logical, dimension(nx, ny), intent(in)      :: mask\n\n  integer :: i, k\n  real, dimension(nx,ny) :: hold\n\n  hold = data\n\n  do i = 1, 100\n     call smt121(data, nx, ny, 5)\n     where(mask)\n        data = hold\n     end where\n  enddo\n\nend subroutine fillsm\n\n!==============================================================================\n!==============================================================================\n\nsubroutine interp_rainfall_nearest_neighbor(datastruct, newarr, mix, mjx, wrfinput)\n  !\n  ! Fill array <newarr> with rainfall data from <datastruct>\n  !\n  use module_input_data_structure\n  use kwm_grid_utilities\n  use module_geo_em\n  use module_wrfinputfile\n  implicit none\n  type(input_data_type) :: datastruct\n  type(wrfinput_type), intent(in) :: wrfinput\n  integer, intent(in) :: mix, mjx\n  real, dimension(mix,mjx) :: newarr\n\n  integer :: ii, jj\n  real    :: x, y\n  integer :: xn, yn\n\n  newarr = 0.0\n\n  !KWM where (datastruct%data < 0) datastruct%data = 0\n  do ii = 1, mix\n     do jj = 1, mjx\n        ! Compute the x/y location in the <datastruct> dataset of the HRLDAS point (ii,jj).\n\n        ! call datastruct_lltoxy(wrfinput%lat(ii,jj), wrfinput%lon(ii,jj), x, y, datastruct)\n        call latlon_to_ij(datastruct%proj, wrfinput%lat(ii,jj), wrfinput%lon(ii,jj), x, y)\n\n        xn = nint(x)\n        yn = nint(y)\n        if ((xn>0).and.(yn>0).and.(xn<=size(datastruct%data,1)).and.(yn<=size(datastruct%data,2))) then\n           newarr(ii,jj) = datastruct%data(xn,yn)\n           !KWM if (newarr(ii,jj) < 0) newarr(ii,jj) = 0\n           if (newarr(ii,jj) < 0) newarr(ii,jj) = -1.E36\n        else\n           newarr(ii,jj) = -1.E36\n        endif\n     enddo\n  enddo\n\nend subroutine interp_rainfall_nearest_neighbor\n\n!==============================================================================\n!==============================================================================\n\nsubroutine interp_rainfall(datastruct, newarr, mix, mjx, wrfinput)\n  ! fill array newarr with rainfall data from datastruct\n  use module_input_data_structure\n!  use v3_module\n  use kwm_grid_utilities\n  use module_geo_em\n  use module_wrfinputfile\n  implicit none\n  type(input_data_type) :: datastruct\n  type(wrfinput_type), intent(in) :: wrfinput\n  integer, intent(in) :: mix, mjx\n  real, dimension(mix,mjx) :: newarr, fcount\n  integer :: i, j\n  real :: xlat, xlon, xx, yy\n  real, parameter :: badval = -1.E30\n  real :: factor\n  integer :: ii, jj, iii, jjj\n  real :: x, y, mx, my, x2, y2\n  ! real, save, allocatable, dimension(:,:) :: mxa, mya\n  real, allocatable, dimension(:,:) :: mxa, mya\n  integer :: astat\n\n!  integer, parameter :: nsub = 50\n!  integer, parameter :: nsub = 15\n!  integer, parameter :: nsub = 8\n!  integer, parameter :: nsub = 4\n\n  integer :: nsub\n\n  ! Select nsub to have at least 10x10 source grid cells\n  ! per destination grid cell.\n  nsub = ceiling(datastruct%proj%dx*1.E-3 * 10.0 / (wrfinput%proj%dx*1.E-3))\n  print*, 'nsub = ', nsub\n\n  newarr = 0.0\n  fcount = 0.0\n\n  ! Take a more expensive approach, assigning portions of rainfall\n  ! field's grid cells to various WRF grid cells as necessary.\n\n  ! We recompute the mapping information every time, in case our source grid has changed.\n\n  ILOOP : do i = 1, datastruct%nx\n     JLOOP : do j = 1, datastruct%ny\n        ! Compute (x,y) in WRF grid of point (gx,gy) in precip grid.\n!KWM        call datastruct_xytoll(float(i), float(j), xlat, xlon, datastruct)\n        call ij_to_latlon(datastruct%proj, float(i), float(j), xlat, xlon)\n        call latlon_to_ij(wrfinput%proj, xlat, xlon, x, y)\n        ! Now X and Y are the x and y coordinates in the WRF\n        ! grid of the RAINFALL point i, j.\n\n        if ((x > -2) .and. (y > -2) .and. (x < mix+2) .and. (y < mjx+2)) then\n\n           do ii = 1, nsub\n              x = float(i) + 0.5 * (1./float(nsub)-1) + float(ii-1)/float(nsub)\n              do jj = 1, nsub\n                 y = float(j) + 0.5 *(1./float(nsub)-1) + float(jj-1)/float(nsub)\n!KWM                 call datastruct_xytoll(x, y, xlat, xlon, datastruct)\n                 call ij_to_latlon(datastruct%proj,x, y, xlat, xlon)\n                 call latlon_to_ij(wrfinput%proj, xlat, xlon, x2, y2)\n\n                 iii = nint(x2)\n                 jjj = nint(y2)\n                 if ((jjj > 0) .and. (iii > 0) .and. (jjj <= mjx) .and. (iii <= mix)) then\n                    if (datastruct%data(i,j) > 0) then\n                       newarr(iii,jjj) = newarr(iii,jjj) + datastruct%data(i,j)\n                    endif\n                    fcount(iii,jjj) = fcount(iii,jjj) + 1.0\n                 endif\n              enddo\n           enddo\n\n        endif\n     enddo JLOOP\n  enddo ILOOP\n\n  where (fcount > 0.0)\n     newarr = newarr / fcount\n  elsewhere\n     newarr = -1.E36\n  end where\n\n  where (newarr < 0)\n!     newarr = 0.0 ! -1.E36\n     newarr = -1.E36\n  end where\n\nend subroutine interp_rainfall\n\n!==============================================================================\n!==============================================================================\n\nsubroutine another_interp_rainfall(datastruct, newarr, mix, mjx, wrfinput)\n  !\n  ! Fill array newarr with rainfall data from datastruct\n  !\n  ! Take an expensive approach, assigning portions of rainfall\n  ! field's grid cells to various WRF grid cells as necessary.\n  !\n  use module_input_data_structure\n  use kwm_grid_utilities\n  use module_geo_em\n  use module_wrfinputfile\n  implicit none\n  type(input_data_type) :: datastruct\n  type(wrfinput_type), intent(in) :: wrfinput\n  integer, intent(in) :: mix, mjx\n  real, dimension(mix,mjx) :: newarr, fcount\n  integer :: i, j\n  real :: xlat, xlon, xx, yy\n  real, parameter :: badval = -1.E30\n  real :: factor\n  integer :: ii, jj, iii, jjj\n  real :: x, y, mx, my\n  real, save, allocatable, dimension(:,:) :: mxa, mya\n  integer :: astat\n\n  ! For high-resolution cases, is this just going to exhaust our memory?\n  real, save, allocatable, dimension(:,:,:,:) :: x2, y2\n\n  integer :: nsub\n\n  ! We need to check datastruct%iproj, datastruct%nx, datastruct%ny, datastruct%proj%lat1, datastruct%startlon\n  ! datastruct%proj%latinc, datastruct%proj%loninc, datastruct%dx, datastruct%dy, datastruct%xlonc, datastruct%truelat1,\n  ! and datastruct%truelat1 to be sure that our datastruct data is not from some different\n  ! grid.\n\n  logical :: samegrid\n  integer, save :: iproj = -9999\n  integer, save :: nx\n  integer, save :: ny\n  real,    save :: startlat\n  real,    save :: startlon\n  real,    save :: deltalat\n  real,    save :: deltalon\n  real,    save :: dx\n  real,    save :: dy\n  real,    save :: xlonc\n  real,    save :: truelat1\n  real,    save :: truelat2\n\n  ! Check the grid info:\n  samegrid = .TRUE.\n  if (iproj    /= datastruct%proj%code)      samegrid=.FALSE.\n  if (nx       /= datastruct%nx)             samegrid=.FALSE.\n  if (ny       /= datastruct%ny)             samegrid=.FALSE.\n  if (startlat /= datastruct%proj%lat1)      samegrid=.FALSE.\n  if (startlon /= datastruct%proj%lon1)      samegrid=.FALSE.\n  if (      dx /= datastruct%proj%dx)        samegrid=.FALSE.\n  if (      dy /= datastruct%proj%dy)        samegrid=.FALSE.\n  if (   xlonc /= datastruct%proj%stdlon)    samegrid=.FALSE.\n  if (truelat1 /= datastruct%proj%truelat1)  samegrid=.FALSE.\n  if (truelat2 /= datastruct%proj%truelat2)  samegrid=.FALSE.\n\n  ! Select nsub to have at least 10x10 source grid cells\n  ! per destination grid cell.\n  ! nsub = ceiling(datastruct%proj%dx * 10.0 / (wrfinput%proj%dx))\n  nsub = ceiling(datastruct%proj%dx * 11.0 / wrfinput%proj%dx)\n\n  newarr = 0.0\n  fcount = 0.0\n\n  if (.not. samegrid) then\n     write(*,'(\"Computing new grid information for rainfall remapping.\")')\n     print*, 'nsub = ', nsub\n     if (allocated(mxa)) deallocate(mxa)\n     if (allocated(mya)) deallocate(mya)\n     if (allocated(x2))  deallocate(x2)\n     if (allocated(y2))  deallocate(y2)\n     ! Save this information:\n     iproj    = datastruct%proj%code\n     nx       = datastruct%nx\n     ny       = datastruct%ny\n     startlat = datastruct%proj%lat1\n     startlon = datastruct%proj%lon1\n     dx       = datastruct%proj%dx\n     dy       = datastruct%proj%dy\n     xlonc    = datastruct%proj%stdlon\n     truelat1 = datastruct%proj%truelat1\n     truelat2 = datastruct%proj%truelat2\n  endif\n\n  if (.not. allocated(mxa)) then\n     allocate(mxa(datastruct%nx,datastruct%ny), stat=astat)\n     if (astat /= 0) stop \"Problem allocating MXA\"\n     allocate(mya(datastruct%nx,datastruct%ny), stat=astat)\n     if (astat /= 0) stop \"Problem allocating MYA\"\n     allocate(x2(datastruct%nx,datastruct%ny,nsub,nsub), stat=astat)\n     if (astat /= 0) stop \"Problem allocating X2\"\n     allocate(y2(datastruct%nx,datastruct%ny,nsub,nsub), stat=astat)\n     if (astat /= 0) stop \"Problem allocating Y2\"\n     ILOOP1 : do i = 1, datastruct%nx\n        JLOOP1 : do j = 1, datastruct%ny\n           ! Compute (x,y) in WRF grid of point (gx,gy) in precip grid.\n           call ij_to_latlon(datastruct%proj, float(i), float(j), xlat, xlon)\n           call latlon_to_ij(wrfinput%proj, xlat, xlon, mxa(i,j), mya(i,j))\n\n           ! Now MX and MY are the x and y coordinates in the WRF\n           ! grid of the RAINFALL point i, j.\n\n        if ((mxa(i,j) > -2) .and. (mya(i,j) > -2) .and. (mxa(i,j) < mix+2) .and. (mya(i,j) < mjx+2)) then\n           do ii = 1, nsub\n              x = float(i) + 0.5 * (1./float(nsub)-1) + float(ii-1)/float(nsub)\n              do jj = 1, nsub\n                 y = float(j) + 0.5 *(1./float(nsub)-1) + float(jj-1)/float(nsub)\n                 call ij_to_latlon(datastruct%proj, x, y, xlat, xlon)\n                 call latlon_to_ij(wrfinput%proj, xlat, xlon, x2(i,j,ii,jj), y2(i,j,ii,jj))\n              enddo\n           enddo\n\n        endif\n\n        enddo JLOOP1\n     enddo ILOOP1\n  endif\n\n  ILOOP : do i = 1, datastruct%nx\n     JLOOP : do j = 1, datastruct%ny\n        ! Find the WRF coordinates of the DATASTRUCT point in question\n        if ((mxa(i,j) > -2) .and. (mya(i,j) > -2) .and. (mxa(i,j) < mix+2) .and. (mya(i,j) < mjx+2)) then\n\n           do ii = 1, nsub\n              do jj = 1, nsub\n                 iii = nint(x2(i,j,ii,jj))\n                 jjj = nint(y2(i,j,ii,jj))\n                 if ((jjj > 0) .and. (iii > 0) .and. (jjj <= mjx) .and. (iii <= mix)) then\n                    ! if (datastruct%data(i,j) >0) then\n                    if (datastruct%data(i,j) >=0) then\n                       newarr(iii,jjj) = newarr(iii,jjj) + datastruct%data(i,j)\n                    endif\n                    fcount(iii,jjj) = fcount(iii,jjj) + 1.0\n                 endif\n              enddo\n           enddo\n        endif\n     enddo JLOOP\n  enddo ILOOP\n\n  where (fcount > 0.0)\n     newarr = newarr / fcount\n  elsewhere\n     newarr = -1.E36\n  end where\n\n  where (newarr < 0)\n!     newarr = 0.0 ! -1.E36\n     newarr = -1.E36\n  end where\n\nend subroutine another_interp_rainfall\n\n!==============================================================================\n!==============================================================================\n\nsubroutine rescale_sw_time_offset(datastruct)\n  use module_input_data_structure\n  use kwm_date_utilities\n  implicit none\n  type(input_data_type), intent(inout) :: datastruct\n\n  integer :: idim\n  integer :: jdim\n\n!KWM  real, parameter :: pi = 3.14159265\n\n  character(len=16) :: nowdate\n  integer :: jday\n  integer :: ihour\n  integer :: iminute\n\n  integer :: i, j\n  real    :: lat, lon\n  real    :: latrad, lonrad\n\n  real :: gg\n  real :: declin\n  real :: tc\n  real :: SHA\n  real :: hour\n  real :: time_of_day\n  real :: time_of_day00\n  real :: cza\n  real :: cza00\n\n  idim = datastruct%nx\n  jdim = datastruct%ny\n\n  ! Get the hour and minute from the date string.\n  read(datastruct%hdate(12:16), '(I2,1x,I2)') ihour, iminute\n  if (iminute == 0) return ! No adjusting of SW data necessary\n\n  ! Find the julian day from the date string.\n  call geth_idts(datastruct%hdate(1:10), datastruct%hdate(1:4)//\"-01-01\", jday)\n  jday = jday + 1\n\n  ! The (GMT) time of day as encoded in the data, hours and fractional minutes.\n  time_of_day = float(ihour) + float(iminute)/60.\n\n  ! The (GMT) time of day, truncated to the hour.\n  time_of_day00 = float(ihour)\n\n  write(*, '(12x,\"SW offset:  Record time:\", F6.3, \";  HRLDAS analysis time:\", F6.3, \";   Time offset (hours):\",  F6.4)') &\n       time_of_day, time_of_day00, time_of_day - time_of_day00\n\n  do i = 1, idim\n     do j = 1, jdim\n\n        ! First, compute the lat/lon at the DATASTRUCT points.\n!KWM        call datastruct_xytoll(float(i), float(j), lat, lon, datastruct)\n        call ij_to_latlon(datastruct%proj, float(i), float(j), lat, lon)\n        latrad = lat*pi/180.\n        lonrad = lon*pi/180.\n\n        call get_declin(jday, time_of_day, latrad, lonrad, declin, sha)\n\n        ! CZA -- Cosine of the solar zenith angle\n        cza = sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA)\n        if (cza < 0.1) cza = 0;\n\n        call get_declin(jday, time_of_day00, latrad, lonrad, declin, sha)\n        cza00 = sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA)\n        if (cza00 < 0) cza00 = 0;\n\n        if (datastruct%data(i,j) > 0) then\n           if (cza < 0.05) then\n              datastruct%data(i,j) = 0.\n           else\n              datastruct%data(i,j) = cza00/cza * datastruct%data(i,j)\n           endif\n        endif\n     enddo\n  enddo\n\nend subroutine rescale_sw_time_offset\n\n!==============================================================================\n!==============================================================================\n\nsubroutine get_declin(jday, gmthour, latrad, lonrad, declin, sha)\n  implicit none\n  integer, intent(in) :: jday\n  real, intent(in) :: gmthour\n  real, intent(in) :: latrad\n  real, intent(in) :: lonrad\n  real, intent(out) :: declin\n  real, intent(out) :: sha\n  ! real, intent(out) :: sza\n\n  real :: gg, tc\n  real, parameter :: pi = 3.14159265\n\n  ! Fractional day of the year, in radians\n  gg = (360./365.25) * (JDAY+gmthour/24.) * pi/180.\n\n  ! Solar declination angle, in radians.\n  DECLIN = 0.006918 - 0.399912*cos(gg) + 0.070257*sin(gg) - 0.006758*cos(2.0*gg) + &\n       0.000907*sin(2.0*gg) - 0.002697*cos(3.0*gg) + 0.00148*sin(3.0*gg)\n\n  ! Time Correction for solar angle, in radians.  Whatever.\n  TC = 0.000075 + 0.001868*cos(gg) - 0.032077*sin(gg) - 0.014615*cos(2.0*gg) - &\n       0.040849*sin(2.0*gg)\n\n  ! Solar Hour Angle, in radians\n  SHA = ((gmthour-12.0)*15.0)*(pi/180.) + lonrad + TC\n  ! SHA = (gmthour*15.0)*(pi/180.) + lonrad + TC\n\n  ! ! Solar Zenith Angle, in radians\n  ! SZA = acos(sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA))\n\n  !  ! Solar Elevation Angle, in radians.\n  !  SEA = (pi/2.)-SZA\n\n  !  ! Azimuth Angle\n  !  AZ = acos((sin(DECLIN)-sin(latrad)*cos(SZA))/(cos(Latrad)*sin(SZA)))\n\nend subroutine get_declin\n\n!==============================================================================\n!==============================================================================\n\nsubroutine nighttime_SW(hdate, field, idim, jdim, wrfinput)\n  ! IDIM and JDIM are the dimensions of FIELD, which should also be the same \n  ! as the WRFINPUT%IDIM and WRFINPUT%JDIM dimensions.\n  use module_wrfinputfile\n  use kwm_date_utilities\n  use kwm_grid_utilities\n  implicit none\n  character(len=*), intent(in) :: hdate\n  integer, intent(in) :: idim, jdim\n  type (wrfinput_type), intent(in) :: wrfinput\n  real, dimension(idim,jdim), intent(inout) :: field\n\n  integer :: i, j, jday, ihour, iminute\n  real :: lat, lon, latrad, lonrad, gmthour\n  real :: declin, sha, cosza\n  real, dimension(idim, jdim) :: maskarray\n  real, dimension(idim, jdim) :: mask2\n\n  integer :: ii, jj, mcount, iiterm\n  integer :: cdist\n  integer :: iimin, iimax, jjmin, jjmax\n  integer, allocatable, dimension(:,:) :: mtx\n\n  call geth_idts(hdate(1:10), hdate(1:4)//\"-01-01\", jday)\n  jday = jday + 1\n  read(hdate(12:16), '(I2,1x,I2)') ihour, iminute\n  gmthour = float(ihour) + float(iminute)/60.\n\n  ! Make a mask array\n  do i = 1, idim\n     do j = 1, jdim\n        latrad = wrfinput%lat(i,j) * rad_per_deg\n        lonrad = wrfinput%lon(i,j) * rad_per_deg\n        call get_declin(jday, gmthour, latrad, lonrad, declin, sha)\n\n        cosza = sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA)\n\n        if (cosza > 0.0) then\n           maskarray(i,j) = 1.0\n        else\n           maskarray(i,j) = 0.0\n        endif\n     enddo\n  enddo\n\n  ! Smooth the mask array a bit, to get us a less abrupt change\n  !        Took this out on 14 Feb 2008.  Kind of a hack.\n  ! call smt121(maskarray, idim, jdim, 10)\n\n  field = field * maskarray\n\nend subroutine nighttime_SW\n\n!==============================================================================\n!==============================================================================\n\nsubroutine close_flnm(flnm)\n  implicit none\n  character(len=*), intent(in) :: flnm\n  integer :: n\n  inquire(file=trim(flnm), number=n)\n  if (n > -1) close(n)\nend subroutine close_flnm\n\n!==============================================================================\n!==============================================================================\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/Makefile",
    "content": "SHELL=/bin/sh\n.SUFFIXES:\t\n.SUFFIXES:\t.F .c .o\n\ninclude ../../user_build_options\n\nOBJS=\tmodule_grib2.o \\\n\tmodule_grib2_tables.o \\\n\ttrig_degrees.o \\\n\tmodule_input_data_structure.o \\\n\targuments_module.o \\\n\tgbytesys.o \\\n\tswap4f.o \\\n\tmodule_llxy.o \\\n\tcio.o \\\n\tkwm_date_utilities.o \\\n\tkwm_grid_utilities.o \\\n\tkwm_timing_utilities.o \\\n\tkwm_string_utilities.o \\\n\tswap4c.o \\\n\tget_unused_unit.o \\\n\tdecode_jpeg2000.o  \\\n\tio_f.o \\\n\tmodule_mapinfo.o \\\n\tmodule_grib1.o \\\n\tmodule_grib.o \\\n\tmodule_grib_common.o \\\n\tmodule_wrfinputfile.o \\\n\tmodule_geo_em.o \n\nCMD=\tlibsmda.a\n\nGRIBCODE_OPT = -DBIT32\nBZIP_CPP = -D_BZIP_$(BZIP2)\n\nall:\t$(CMD)\n\nlibsmda.a:\t$(OBJS)\n\t$(RM) libsmda.a\n\tar q libsmda.a $(OBJS)\n\nswap4c.o:\tswap4c.c\n\t$(CC) -c swap4c.c\n\nio_f.o:\tio_f.c\n\t$(CC) -c $(CCFLAGS) $(BZIP_CPP) $(BZIP2_INCLUDE) io_f.c\n\ndecode_jpeg2000.o:\tdecode_jpeg2000.c\n\t$(CC) -c $(INCJASPER) $(<)\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(GRIBCODE_OPT) $(BZIP_CPP) -c $(FREESOURCE) $(F90FLAGS) $(NETCDFMOD) $(*).F\n\n.c.o:\n\t$(CC) -c $(BZIP_CPP) $(<)\n\nclean:\n\t$(RM) $(OBJS) $(CMD) *.mod *~\n#\nmodule_grib2.o:\tmodule_grib2.F module_grib2_tables.o module_grib1.o module_mapinfo.o kwm_date_utilities.o module_grib_common.o\nmodule_grib1.o: module_grib1.F module_mapinfo.o kwm_date_utilities.o module_grib_common.o\nmodule_grib.o:\tmodule_grib.F module_grib1.o module_grib2.o\nmodule_input_data_structure.o:\tmodule_llxy.o\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/arguments_module.F",
    "content": "module arguments_module\n  implicit none\n  private\n  public :: arg\n  public :: print_help\n  character(len=2400), public :: arguments_help\n\n  logical :: adone = .FALSE.\n  character(len=120), dimension(0:2000) :: harg\n  integer :: numarg\n\n  interface arg\n     module procedure &\n          argi, argndi,&\n          argf,&\n          argl,&\n          argh, argndh, argnd1h,&\n          argsub\n  end interface\n\ncontains\n\n!==============================================================================\n\n  subroutine argi(string, default, ival)\n! Handle the case for optional integer flags,\n! i.e., (FLAG, DEFAULT, VALUE) for integers.\n    implicit none\n    character(len=*) :: string\n    integer :: default\n    integer :: ival\n    integer :: ierr, i, nval\n\n    call initialize\n\n    ival = default\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          read(harg(i+1),*, iostat=ierr) ival\n          if (ierr /= 0) then\n             call print_help\n          endif\n          harg(i:numarg-2) = harg(i+2:numarg)\n          numarg = numarg - 2\n          return\n       endif\n    enddo\n\n    do i = 1, nval\n       if ( (harg(i)(1:len(string)) == string).and.&\n            (scan(harg(i)(len(string)+1:),\"0123456789\") .ne. 0) )then\n          read(harg(i)(len(string)+1:),*, iostat=ierr) ival\n          if (ierr == 0) then\n             harg(i:numarg-1) = harg(i+1:numarg)\n             numarg = numarg - 1\n             return\n          endif\n       endif\n    enddo\n\n  end subroutine argi\n\n!==============================================================================\n\n  subroutine argndi(string, ival)\n! Handle the case of required integer flags,\n! i.e., (FLAG, VALUE) for integers.\n    implicit none\n    character(len=*) :: string\n    integer :: ival\n\n    integer :: ierr, i, nval\n\n    call initialize\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          read(harg(i+1),*) ival\n          harg(i:numarg-2) = harg(i+2:numarg)\n          numarg = numarg - 2\n          return\n       endif\n    enddo\n\n    nval = numarg\n    do i = 1, nval\n\n       if ( (harg(i)(1:len(string)) == string).and.&\n            (scan(harg(i)(len(string)+1:),\"0123456789\") .ne. 0) )then\n          read(harg(i)(len(string)+1:),*, iostat=ierr) ival\n          if (ierr == 0) then\n             harg(i:numarg-1) = harg(i+1:numarg)\n             numarg = numarg - 1\n             return\n          endif\n       endif\n    enddo\n\n    write(*,'(/,\"Argument \", A, \" MUST be present.\",/)') trim(string)\n    call print_help\n  end subroutine argndi\n\n!==============================================================================\n\n  subroutine argf(string, default, xval)\n! Handle the case for optional real flags,\n! i.e., (FLAG, DEFAULT, VALUE) for reals.\n    implicit none\n    character(len=*) :: string\n    real :: default\n    real :: xval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    xval = default\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          read(harg(i+1),*) xval\n          harg(i:numarg-2) = harg(i+2:numarg)\n          numarg = numarg - 2\n          return\n       endif\n    enddo\n\n    nval = numarg\n    do i = 1, nval\n\n       if ( (harg(i)(1:len(string)) == string).and.&\n            (scan(harg(i)(len(string)+1:),\"0123456789\") .ne. 0) )then\n          read(harg(i)(len(string)+1:),*, iostat=ierr) xval\n          if (ierr == 0) then\n             harg(i:numarg-1) = harg(i+1:numarg)\n             numarg = numarg - 1\n             return\n          endif\n       endif\n    enddo\n  end subroutine argf\n\n!==============================================================================\n\n  subroutine argl(string, default, lval)\n! Handle the case of optional logical flags,\n! i.e., (FLAG, DEFAULT, VALUE) for logicals.\n    implicit none\n    character(len=*) :: string\n    logical :: default\n    logical :: lval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    lval = default\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          lval = .not.(default)\n          harg(i:numarg-1) = harg(i+1:numarg)\n          numarg = numarg - 1\n          return\n       endif\n    enddo\n\n  end subroutine argl\n\n!==============================================================================\n\n  subroutine argh(string, default, hval)\n! Handle the case of optional flagged string arguments,\n! i.e., (FLAG, DEFAULT, VALUE) for strings.\n    implicit none\n    character(len=*) :: string\n    character(len=*) :: default\n    character(len=*) :: hval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    hval = default\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          hval = harg(i+1)\n          harg(i:numarg-2) = harg(i+2:numarg)\n          numarg = numarg - 2\n          return\n       endif\n    enddo\n\n    nval = numarg\n    do i = 1, nval\n\n       if (harg(i)(1:len(string)) == string) then\n          hval = harg(i)(len(string)+1:)\n          harg(i:numarg-1) = harg(i+1:numarg)\n          numarg = numarg - 1\n          return\n       endif\n    enddo\n  end subroutine argh\n\n!==============================================================================\n\n  subroutine argndh(string, hval)\n! Handle the case of required flagged string arguments,\n! i.e., (FLAG, VALUE) for strings.\n!    or\n! Handle the case of optional unflagged string arguments.\n! i.e., (DEFAULT, VALUE) for strings.\n\n    implicit none\n    character(len=*) :: string\n    character(len=*) :: hval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    if (string(1:1) .eq. \"-\") then\n! STRING is a flag.\n! Handle the case of required flagged string arguments\n\n       nval = numarg\n       do i = 1, nval\n          if (harg(i) == string) then\n             if (i == numarg) call print_help\n             hval = harg(i+1)\n             if (hval(1:1) == '-') call print_help\n             harg(i:numarg-2) = harg(i+2:numarg)\n             numarg = numarg - 2\n             return\n          endif\n       enddo\n\n       do i = 1, nval\n\n          if (harg(i)(1:len(string)) == string) then\n             hval = harg(i)(len(string)+1:)\n             harg(i:numarg-1) = harg(i+1:numarg)\n             numarg = numarg - 1\n             return\n          endif\n       enddo\n\n       write(*,'(/,\"Argument \", A, \" MUST be present.\",/)') trim(string)\n       call print_help\n    else\n! STRING is a default string value.\n! Handle the case of optional unflagged string arguments.\n\n       if (numarg > 0) then\n          if (harg(1)(1:1) == \"-\") then\n             call print_help\n          else\n             hval = harg(1)\n             harg(1:numarg-1) = harg(2:numarg)\n             numarg = numarg - 1\n          endif\n       else\n          hval = string\n       endif\n    endif\n\n  end subroutine argndh\n\n!==============================================================================\n!KWM\n!KWM  subroutine arg1h(default, hval)\n!KWM! Handle the case of optional unflagged string arguments.\n!KWM    implicit none\n!KWM    character(len=*) :: default\n!KWM    character(len=*) :: hval\n!KWM\n!KWM    integer :: nval, i, ierr\n!KWM\n!KWM    call initialize\n!KWM\n!KWM    if (numarg > 0) then\n!KWM       hval = harg(1)\n!KWM       harg(1:numarg-1) = harg(2:numarg)\n!KWM       numarg = numarg - 1\n!KWM    else\n!KWM       hval = default\n!KWM    endif\n!KWM\n!KWM  end subroutine arg1h\n!KWM\n!==============================================================================\n\n  subroutine argnd1h(hval)\n! Handle the case of required unflagged string arguments.\n    implicit none\n    character(len=*) :: hval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    if (numarg /= 1) then\n       write(*,'(/,\"A final command-line argument MUST be present.\")')\n       call print_help\n    else\n       if (harg(numarg)(1:1) == \"-\") then\n          call print_help\n       else\n          hval = harg(numarg)\n       endif\n    endif\n\n  end subroutine argnd1h\n\n!==============================================================================\n\n  subroutine argsub(string, subr)\n! Handle the case of a subprogram.\n    implicit none\n    character(len=*) :: string\n    integer :: nval, i\n    external subr\n\n    call initialize\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          call subr\n       endif\n    enddo\n\n  end subroutine argsub\n\n!==============================================================================\n\n  subroutine print_help\n    write(*,'(/,\"Usage: \", A, 1x)', advance=\"no\") trim(harg(0))\n    write(*,arguments_help)\n    write(*,'(/)')\n    stop\n  end subroutine print_help\n\n!==============================================================================\n\n  subroutine initialize\n    implicit none\n    integer :: i\n    integer, external :: iargc\n\n    if (.not. adone) then\n       numarg = iargc()\n       do i = 0, numarg\n          call getarg(i, harg(i))\n       enddo\n       adone = .TRUE.\n    endif\n\n  end subroutine initialize\n\n!==============================================================================\n\nend module arguments_module\n\n!KWMprogram test1\n!KWM  use arguments_module\n!KWM  implicit none\n!KWM  integer :: i, j, k\n!KWM  real :: x, y, z\n!KWM  logical :: g, gg\n!KWM  character(len=120) :: h, flnm\n!KWM  arguments_help = '(\"-a i -b b -c c -aa aa -bb bb -cc cc -g -gg -h h flnm\")'\n!KWM  call arg(\"-a\", i)\n!KWM  call arg(\"-b\", 12, k)\n!KWM  call arg(\"-c\", 11, j)\n!KWM  call arg(\"-aa\", 1.10, x)\n!KWM  call arg(\"-bb\", 1.12, y)\n!KWM  call arg(\"-cc\", 1.11, z)\n!KWM  call arg(\"-g\", .TRUE., g)\n!KWM  call arg(\"-gg\", .FALSE., gg)\n!KWM  call arg(\"-h\", \"Whatever\", h)\n!KWM  call arg(flnm)\n!KWM\n!KWM  print*, 'i, j, k = ', i, j, k\n!KWM  print*, 'x, y, z = ', x, y, z\n!KWM  print*, 'g, gg = ', g, gg\n!KWM\n!KWM  print*,' h = ', trim(h)\n!KWM  print*, 'flnm = ', trim(flnm)\n!KWM\n!KWMend program test1\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/cio.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n*/\n\n/*  FILE: cio.c  */\n/*  C functions to write bytes to UNIX files - called from FORTRAN */\n/*  copen\n    bnread\n    bnwrit\n    cclose\n    rewtap\n    eoftap\n    fsftap\n    bsrtap\n    bsrfil */\n/*  870417  */\n\n#if defined(CRAY)\n\n#define copen  COPEN\n#define bnread BNREAD\n#define bnwrit BNWRIT\n#define cclose CCLOSE\n#define rewtap REWTAP\n#define eoftap EOFTAP\n#define bsrtap BSRTAP\n#define bnseek BNSEEK\n#define bsrfil BSRFIL\n#define bsftap BSFTAP\n#define fsftap FSFTAP\n#define catoi  CATOI\n\n#elif defined (__sgi) || defined (__sun) || defined (__alpha) || defined (__linux)\n\n#define copen copen_\n#define cclose cclose_\n#define bnread bnread_\n#define bnwrit bnwrit_\n#define bsrtap bsrtap_\n#define bnseek bnseek_\n#define rewtap rewtap_\n#define eoftap eoftap_\n#define bsrfil bsrfil_\n#define bsftap bsftap_\n#define fsftap fsftap_\n#define catoi  catoi_\n\n#elif defined (IBM) || defined (HP)\n\n#define copen copen\n#define cclose cclose\n#define bnread bnread\n#define bnwrit bnwrit\n#define bsrtap bsrtap\n#define bnseek bnseek\n#define rewtap rewtap\n#define eoftap eoftap\n#define bsrfil bsrfil\n#define bsftap bsftap\n#define fsftap fsftap\n#define catoi  catoi\n\n#endif\n\n#include <stdio.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <unistd.h>\n/* #include <sys/mtio.h> */\n#include <sys/ioctl.h>\n#include <sys/uio.h>\n\n/* ****************************************************************** */\n\ncopen(nunit, name, mode, err, oflag)\n /*\n  * nunit = UNIX file descriptor associated with file named *name*\n  * name  = UNIX file name \n  * mode  = 0 : write only - file will be created if it doesn't exist, \n                           - otherwise will be rewritten\n          = 1 : read only\n          = 2 : read/write\n  * err   = 0 : no error opening file.\n         != 0 : Error opening file\n  * oflag = 0 : no notification if file opened OK \n          = 1 : file name and unit number printed\n  */\n\n#if defined (__sgi) && defined (BIT64)\n    int64_t          *nunit;\n    int64_t          *mode;\n    int64_t          *err;\n    int64_t          *oflag;\n#else\n    int          *nunit;\n    int          *mode;\n    int          *err;\n    int          *oflag;\n#endif\n    char         name[120];\n\n{\n    int             fd, i;\n    char            fname[120];\n    extern int      errno;\t/* I/O error return */\n\n    /* strip trailing blanks and add null character to name */\n    for (i = 0; name[i] != ' ' && name[i] != '\\0' && i < 120; ++i)\n\tfname[i] = name[i];\n    fname[i] = '\\0';\n\n    if (*oflag != 0) {\n\tprintf(\"Copen: File = %s\\n\", fname);\n    }\n\n/* if (*mode == 0)    WRITE ONLY\n   printf (\"UNIX File descriptor: %d\\n\", fd = open (fname, O_WRONLY));\n     printf (\"UNIX File descriptor: %d\\n\", fd = creat (fname, 0777));\n   else if (*mode == 1)   READ ONLY\n     printf (\"UNIX File descriptor: %d\\n\", fd = open (fname, O_RDONLY));\n   else   READ/WRITE\n     printf (\"UNIX File descriptor: %d\\n\", fd = open (fname, O_RDWR));*/\n\n    if (*mode == 0) {\t\t/* WRITE ONLY */\n\tfd = creat(fname, 0777);\n    }\n    else if (*mode == 1) {\t/* READ ONLY */\n\tfd = open(fname, O_RDONLY);\n    }\n    else {\t\t\t/* READ/WRITE */\n\tfd = open(fname, O_RDWR);\n    }\n\n    if (*oflag != 0)\n\tprintf(\"UNIX File descriptor: %d\\n\\n\", fd);\n\n    if (fd == -1) {\t\t/* error opening file */\n\tprintf(\"Error opening '%s'  Error status: %d\\n\", fname, errno);\n\tperror(\"copen.c\");\n\t*err = errno;\n    }\n    else {\n      *err = 0;\n      *nunit = fd;\n    }\n\n    return(0);\n}\n\n/* ****************************************************************** */\nbnseek(fd, bread, mode, iprint)\n\n/*  Move the read/write file pointer\n       fd     : Unix file descriptor.\n       bread  : Number of bytes to move the pointer.\n       mode   : How to move the pointer:\n               = 0 : move the pointer ahead BREAD bytes.\n               < 0 : move the pointer to location BREAD.\n               > 0 : move the pointer to the end + BREAD bytes. (?)\n       iprint : Flag to turn on (iprint = 1)  or off (iprint = 0) print.\n\n   Location 0 [bnseek(fd,0,-1,0)] puts us just before the first byte, \n   so the next bnread will get byte 1.\n*/\n\n    int            *fd, *bread, *mode, *iprint;\n\n{\n    off_t           i, offset;\n    int             how_to_space;\n\n    if (*mode == 0)\n\thow_to_space = SEEK_CUR;\n    else if (*mode < 0)\n\thow_to_space = SEEK_SET;\n    else\n\thow_to_space = SEEK_END;\n\n    offset = *bread;\n    i = lseek(*fd, offset, how_to_space);\n    if (*iprint != 0) \n       printf(\" lseek return=%d, *mode=%d\\n\", i, *mode);\n\n    return(0);\n}\n\n/* ****************************************************************** */\n\nbnread(fd, buf, nbuf, bread, ios, idiag)\n /*\n  * fd = UNIX file descriptor number (NOT a Fortran unit) \n  * buf = area into which to read \n  * nbuf = number of bytes to read from fd \n  * bread = number actually read \n  * ios = error number returned to Fortran: \n          1 = End of File\n          2 = Error in reading\n  * idiag : if non-zero, error and EOF messages will be printed\n  */\n\n#if defined (__sgi) && defined (BIT64)\n    int64_t        *fd, *nbuf, buf[], *bread, *ios, *idiag;\n#else\n    int            *fd, *nbuf, buf[], *bread, *ios, *idiag;\n#endif\n\n{\n    int             bytesread;\n\n    /* printf (\"BNREAD Fd = %d Nbuf = %d\\n\", *fd, *nbuf); */\n    bytesread = read(*fd, buf, *nbuf);\n    /* printf (\"Bytes %d   stat %d\\n\", bytesread, errno);  */\n\n    if (bytesread == -1) {\t/* error reading file */\n\tif (*idiag != 0)\n\t    printf(\"Error reading C unit %d\\n\", *fd);\n\tperror(\"bnread.c\");\n\t*ios = 2;\n\t/*  *ios = errno; */\n    } else if (bytesread == 0) {/* end-of-file on input */\n\tif (*idiag != 0)\n\t    printf(\"End of file on C unit %d\\n\", *fd);\n            *ios = 1; \n\t/*  *ios = errno; */\n    } else {\t\t\t/* read OK */\n\n\t/*\n\t * printf (\"BNREAD - bytes read = %d   Buf = %d %d %d\\n\", bytesread,\n\t * buf[0], buf[1], buf[2]);\n\t */\n\t*ios = 0;\n    };\n\n    *bread = bytesread;\n    return(0);\n}\n\n/* ****************************************************************** */\n\nbnwrit(fd, buf, nbuf, bwritten, err, idiag)\n    int            *fd, *nbuf, buf[], *bwritten, *err, *idiag;\n\n /*\n  * fd = UNIX file descriptor number (NOT a Fortran unit) buf = area from\n  * which to write nbuf = number of bytes to write to fd bwritten = number\n  * actually written err = UNIX error number returned to FORTRAN idiag : if\n  * non-zero, error and EOF messages will be printed\n  */\n\n{\n    int             byteswritten;\n\n    /*\n     * printf (\"BNWRIT Fd = %d Nbuf = %d   Buf = %d %d %d\\n\", fd, *nbuf,\n     * buf[0], buf[1], buf[2]);\n     */\n    byteswritten = write(*fd, buf, *nbuf);\n    /* printf (\"Bytes %d   stat %d\\n\", byteswritten, errno);  */\n\n    *err = 0;\n    if (byteswritten == -1) {\t/* error writing file */\n\tif (*idiag != 0)\n\t    printf(\"Error writing C unit %d\\n\", *fd);\n\tperror(\"bnwrit.c\");\n\t*err = errno;\n    };\n\n    *bwritten = byteswritten;\n    return(0);\n}\n\n/* ****************************************************************** */\n\ncclose(nunit, iprint, err)\n/*\nClose a C (UNIX?) file descriptor:\n  nunit  : (INPUT)  : The C (UNIX?) file descriptor to close.\n  iprint : (INPUT)  : Print flag ( iprint == 0 : no print on successful close)\n                                 ( iprint != 0 : Some printout)\n  err    : (OUTPUT) : Error flag ( err = 0 : Successful close)\n                                 ( err = 1 : Error on close)\n     */\n    int            *nunit, *iprint, *err;\n{\n    extern int      errno;\t/* I/O error return */\n    int             istat;\n\n    if ( *iprint != 0 )\n      printf(\"\\n *** CCLOSE : Closing file descriptor: NUNIT = %d \\n\", *nunit);\n\n    istat = close(*nunit);\n    if (istat == 0) {\n      if ( *iprint != 0 )\n\tprintf(\" *** CCLOSE successful: File descriptor: NUNIT = %d \\n\", *nunit);\n    }\n    else\n      printf(\"CCLOSE error: %d : File descriptor NUNIT = %d \\n\", istat, *nunit);\n\n    *err = istat;\n    return(0);\n}\n\n/* ****************************************************************** */\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/decode_jpeg2000.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n*/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <jasper/jasper.h>\n\n#if defined (CRAY)\n\n#define info_jpeg2000 INFO_JPEG2000\n#define decode_jpeg2000 DECODE_JPEG2000\n\n#elif defined (__sgi) || defined (__sun) || defined (__alpha) || defined (__linux)\n\n#define info_jpeg2000 info_jpeg2000_\n#define decode_jpeg2000 decode_jpeg2000_\n\n#elif defined (IBM) || defined (HP)\n\n#define info_jpeg2000 info_jpeg2000\n#define decode_jpeg2000 decode_jpeg2000\n\n#endif\n\n\nvoid info_jpeg2000(char *buffer, int *length, int *width, int *height, jas_image_t **image, jas_stream_t **instream) {\n  int fmtid;\n  char *opts=0;\n  jas_image_cmpt_t *pcmpt;\n\n  /* Initialize jasper stuff */\n  jas_init();\n\n  /* open the buffer */\n  if ( ! (*instream = jas_stream_memopen(buffer, *length))) {\n    fprintf(stderr, \"cannot open input buffer\\n\");\n    exit(1);\n  }\n\n  /* Get image format */\n  if ((fmtid = jas_image_getfmt(*instream)) < 0) {\n    fprintf(stderr, \"decode_jpeg2000:  unknown image format:  fmtid = %i\\n\", fmtid);\n    return;\n    exit (1);\n  }\n\n  /* Decode the image. */\n\n  if (!(*image = jpc_decode(*instream, opts))) {\n    fprintf(stderr, \"cannot load image\\n\");\n    exit (1);\n  }\n  pcmpt=(*image)->cmpts_[0];\n  *width = pcmpt->width_;\n  *height = pcmpt->height_;\n}\n\n\nvoid decode_jpeg2000(jas_image_t **image, jas_stream_t **instream, int *width, int *height, int *buf) {\n  /* Call info_jpeg2000_ before calling decode_jpeg2000_ */\n  jas_matrix_t *data;\n  jas_image_cmpt_t *pcmpt;\n  int i, j, k, ierr;\n\n  pcmpt=(*image)->cmpts_[0];\n  data=jas_matrix_create(jas_image_height(*image), jas_image_width(*image));\n  jas_image_readcmpt(*image,0,0,0,jas_image_width(*image), jas_image_height(*image), data);\n  k=0;\n  for (i=0;i<pcmpt->height_;i++) {\n    for (j=0;j<pcmpt->width_;j++) {\n      buf[k++]=data->rows_[i][j];\n    }\n  }\n  jas_matrix_destroy(data);\n  ierr=jas_stream_close(*instream);\n  jas_image_destroy(*image);\n\n}\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/gbytesys.F",
    "content": "!-----------------------------------------------------------------------\n!       Choice of computers\n!-----------------------------------------------------------------------\n!\n!                 CRAY XMP,YMP/UNICOS       (#define CRAY)\n!                 VAX/VMS                   (#define VAX)\n!                 Stardent 1500/3000/UNIX   (#define STARDENT)\n!                 IBM RS/6000-AIX           (#define IBM)\n!                 SUN Sparcstation          (#define SUN)\n!                 SGI Silicon Graphics      (#define SGI)\n!                 HP 7xx                    (#define HP)\n!                 DEC ALPHA                 (#define ALPHA)\n! +------------------------------------------------------------------+\n! _                     SYSTEM DEPENDENT ROUTINES                    _\n! _                                                                  _\n! _    This module contains short utility routines that are not      _\n! _ of the FORTRAN 77 standard and may differ from system to system. _\n! _ These include bit manipulation, I/O, JCL calls, and vector       _\n! _ functions.                                                       _\n! +------------------------------------------------------------------+\n! +------------------------------------------------------------------+\n!\n!          DATA SET UTILITY    AT LEVEL 003 AS OF 02/25/92\nSUBROUTINE GBYTE(IN,IOUT,ISKIP,NBYTE)\n!\n! THIS PROGRAM WRITTEN BY.....\n!             DR. ROBERT C. GAMMILL, CONSULTANT\n!             NATIONAL CENTER FOR ATMOSPHERIC RESEARCH\n!             MAY 1972\n!\n!             CHANGES FOR CRAY Y-MP8/832\n!             CRAY CFT77 FORTRAN\n!             JULY 1992, RUSSELL E. JONES\n!             NATIONAL WEATHER SERVICE\n!\n! THIS IS THE FORTRAN VERSION OF GBYTE\n!\n  INTEGER    IN(*)\n  INTEGER    IOUT\n#if defined (CRAY) || defined (BIT64)\n\n  INTEGER    MASKS(64)\n!\n  DATA  NBITSW/64/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 64 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,  &\n       4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,      &\n       1048575, 2097151, 4194303, 8388607, 16777215, 33554431,       &\n       67108863, 134217727, 268435455, 536870911, 1073741823,        &\n       2147483647, 4294967295, 8589934591, 17179869183,              &\n       34359738367, 68719476735, 137438953471, 274877906943,         &\n       549755813887, 1099511627775, 2199023255551, 4398046511103,    &\n       8796093022207, 17592186044415, 35184372088831,                &\n       70368744177663, 140737488355327, 281474976710655,             &\n       562949953421311, 1125899906842623, 2251799813685247,          &\n       4503599627370495, 9007199254740991, 18014398509481983,        &\n       36028797018963967, 72057594037927935, 144115188075855871,     &\n       288230376151711743, 576460752303423487, 1152921504606846975,  &\n       2305843009213693951, 4611686018427387903, 9223372036854775807, &\n       -1/\n#else\n  INTEGER    MASKS(32)\n!\n  DATA  NBITSW/32/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 32 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, &\n       4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,     &\n       1048575, 2097151, 4194303, 8388607, 16777215, 33554431,      &\n       67108863, 134217727, 268435455, 536870911, 1073741823,       &\n       2147483647, -1/\n#endif\n!\n! NBYTE MUST BE LESS THAN OR EQUAL TO NBITSW\n!\n  ICON   = NBITSW - NBYTE\n  IF (ICON.LT.0) RETURN\n  MASK   = MASKS(NBYTE)\n!\n! INDEX TELLS HOW MANY WORDS INTO THE ARRAY 'IN' THE NEXT BYTE APPEARS.\n!\n  INDEX  = ISKIP / NBITSW\n!\n! II TELLS HOW MANY BITS THE BYTE IS FROM THE LEFT SIDE OF THE WORD.\n!\n  II     = MOD(ISKIP,NBITSW)\n!\n! MOVER SPECIFIES HOW FAR TO THE RIGHT NBYTE MUST BE MOVED IN ORDER\n!    TO BE RIGHT ADJUSTED.\n!\n  MOVER = ICON - II\n!\n  IF (MOVER.GT.0) THEN\n     IOUT  = IAND(ISHFT(IN(INDEX+1),-MOVER),MASK)\n!\n! THE BYTE IS SPLIT ACROSS A WORD BREAK.\n!\n  ELSE IF (MOVER.LT.0) THEN\n     MOVEL = - MOVER\n     MOVER = NBITSW - MOVEL\n     IOUT  = IAND(IOR(ISHFT(IN(INDEX+1),MOVEL),    &\n          &          ISHFT(IN(INDEX+2),-MOVER)),MASK)\n!\n! THE BYTE IS ALREADY RIGHT ADJUSTED.\n!\n  ELSE\n     IOUT  = IAND(IN(INDEX+1),MASK)\n  ENDIF\n!\nEND SUBROUTINE GBYTE\n!\n! +------------------------------------------------------------------+\nSUBROUTINE GBYTES(IN,IOUT,ISKIP,NBYTE,NSKIP,N)\n!\n! THIS PROGRAM WRITTEN BY.....\n!             DR. ROBERT C. GAMMILL, CONSULTANT\n!             NATIONAL CENTER FOR ATMOSPHERIC RESEARCH\n!             MAY 1972\n!\n!             CHANGES FOR CRAY Y-MP8/832\n!             CRAY CFT77 FORTRAN\n!             JULY 1992, RUSSELL E. JONES\n!             NATIONAL WEATHER SERVICE\n!\n! THIS IS THE FORTRAN VERSION OF GBYTES.\n!\n  INTEGER    IN(*)\n  INTEGER    IOUT(*)\n#if defined (CRAY) || defined (BIT64)\n!CDIR$ INTEGER=64\n  INTEGER    MASKS(64)\n!\n  DATA  NBITSW/64/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 64 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,     &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,      &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,       &\n       & 2147483647, 4294967295, 8589934591, 17179869183,             &\n       & 34359738367, 68719476735, 137438953471, 274877906943,        &\n       & 549755813887, 1099511627775, 2199023255551, 4398046511103,   &\n       & 8796093022207, 17592186044415, 35184372088831,               &\n       & 70368744177663, 140737488355327, 281474976710655,            &\n       & 562949953421311, 1125899906842623, 2251799813685247,         &\n       & 4503599627370495, 9007199254740991, 18014398509481983,       &\n       & 36028797018963967, 72057594037927935, 144115188075855871,    &\n       & 288230376151711743, 576460752303423487, 1152921504606846975, &\n       & 2305843009213693951, 4611686018427387903, 9223372036854775807, &\n       & -1/\n#else\n  INTEGER    MASKS(32)\n!\n  DATA  NBITSW/32/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 32 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,   &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,       &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,        &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,         &\n       & 2147483647, -1/\n#endif\n!\n! NBYTE MUST BE LESS THAN OR EQUAL TO NBITSW\n!\n  ICON   = NBITSW - NBYTE\n  IF (ICON.LT.0) RETURN\n  MASK   = MASKS(NBYTE)\n!\n! INDEX TELLS HOW MANY WORDS INTO THE ARRAY 'IN' THE NEXT BYTE APPEARS.\n!\n  INDEX  = ISKIP / NBITSW\n!\n! II TELLS HOW MANY BITS THE BYTE IS FROM THE LEFT SIDE OF THE WORD.\n!\n  II     = MOD(ISKIP,NBITSW)\n!\n! ISTEP IS THE DISTANCE IN BITS FROM THE START OF ONE BYTE TO THE NEXT.\n!\n  ISTEP  = NBYTE + NSKIP\n!\n! IWORDS TELLS HOW MANY WORDS TO SKIP FROM ONE BYTE TO THE NEXT.\n!\n  IWORDS = ISTEP / NBITSW\n!\n! IBITS TELLS HOW MANY BITS TO SKIP AFTER SKIPPING IWORDS.\n!\n  IBITS  = MOD(ISTEP,NBITSW)\n!\n  DO I = 1,N\n!\n! MOVER SPECIFIES HOW FAR TO THE RIGHT A BYTE MUST BE MOVED IN ORDER\n!\n!    TO BE RIGHT ADJUSTED.\n!    TO BE RIGHT ADJUSTED.\n!\n     MOVER = ICON - II\n!\n! THE BYTE IS SPLIT ACROSS A WORD BREAK.\n!\n     IF (MOVER.LT.0) THEN\n        MOVEL   = - MOVER\n        MOVER   = NBITSW - MOVEL\n        IOUT(I) = IAND(IOR(ISHFT(IN(INDEX+1),MOVEL),   &\n             &            ISHFT(IN(INDEX+2),-MOVER)),MASK)\n!\n! RIGHT ADJUST THE BYTE.\n!\n     ELSE IF (MOVER.GT.0) THEN\n        IOUT(I) = IAND(ISHFT(IN(INDEX+1),-MOVER),MASK)\n!\n! THE BYTE IS ALREADY RIGHT ADJUSTED.\n!\n     ELSE\n        IOUT(I) = IAND(IN(INDEX+1),MASK)\n     ENDIF\n!\n! INCREMENT II AND INDEX.\n!\n     II    = II + IBITS\n     INDEX = INDEX + IWORDS\n     IF (II.GE.NBITSW) THEN\n        II    = II - NBITSW\n        INDEX = INDEX + 1\n     ENDIF\n!\n  END DO\nEND SUBROUTINE GBYTES\n!\n! +------------------------------------------------------------------+\nSUBROUTINE SBYTE(IOUT,IN,ISKIP,NBYTE)\n! THIS PROGRAM WRITTEN BY.....\n!             DR. ROBERT C. GAMMILL, CONSULTANT\n!             NATIONAL CENTER FOR ATMOSPHERIC RESEARCH\n!             JULY 1972\n! THIS IS THE FORTRAN VERSIONS OF SBYTE.\n!             FORTRAN 90\n!             AUGUST 1990  RUSSELL E. JONES\n!             NATIONAL WEATHER SERVICE\n!\n! USAGE:    CALL SBYTE (PCKD,UNPK,INOFST,NBIT)\n!\n!   INPUT ARGUMENT LIST:\n!     UNPK     -  NBITS OF THE RIGHT SIDE OF UNPK IS MOVED TO\n!                 ARRAY PCKD. INOFST BITS ARE SKIPPED OVER BEFORE\n!                 THE DATA IS MOVED, NBITS ARE STORED.\n!    INOFST    -  A FULLWORD INTEGER SPECIFYING THE INITAL OFFSET\n!                 IN BITS OF THE FIRST BYTE, COUNTED FROM THE\n!                 LEFTMOST BIT IN PCKD.\n!    NBITS     -  A FULLWORD INTEGER SPECIFYING THE NUMBER OF BITS\n!                 IN EACH BYTE TO BE PACKED.  LEGAL BYTE WIDTHS\n!                 ARE IN THE RANGE 1 - 32.\n!   OUTPUT ARGUMENT LIST:\n!    PCKD      -  THE FULLWORD IN MEMORY TO WHICH PACKING IS TO\n!                 BEGIN STARTING AT BIT INOFST. THE INOSTAT BITS\n!                 ARE NOT ALTERED.\n!\n  INTEGER    IN\n  INTEGER    IOUT(*)\n#if defined (CRAY) || defined (BIT64)\n  INTEGER    MASKS(64)\n!\n  DATA  NBITSW/64/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 64 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,   &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,\t      &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,\t      &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,\t      &\n       & 2147483647, 4294967295, 8589934591, 17179869183,\t\t      &\n       & 34359738367, 68719476735, 137438953471, 274877906943,\t      &\n       & 549755813887, 1099511627775, 2199023255551, 4398046511103,     &\n       & 8796093022207, 17592186044415, 35184372088831,\t\t      &\n       & 70368744177663, 140737488355327, 281474976710655,\t      &\n       & 562949953421311, 1125899906842623, 2251799813685247,\t      &\n       & 4503599627370495, 9007199254740991, 18014398509481983,\t      &\n       & 36028797018963967, 72057594037927935, 144115188075855871,      &\n       & 288230376151711743, 576460752303423487, 1152921504606846975,   &\n       & 2305843009213693951, 4611686018427387903, 9223372036854775807, &\n       & -1/\n#else\n  INTEGER    MASKS(32)\n!\n  DATA  NBITSW/32/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 32 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,   &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,       &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,        &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,         &\n       & 2147483647, -1/\n#endif\n!\n! NBYTE MUST BE LESS THAN OR EQUAL TO NBITSW\n!\n  ICON  = NBITSW - NBYTE\n  IF (ICON.LT.0) RETURN\n  MASK  = MASKS(NBYTE)\n!\n! INDEX TELLS HOW MANY WORDS INTO IOUT THE NEXT BYTE IS TO BE STORED.\n!\n  INDEX = ISKIP / NBITSW\n!\n! II TELLS HOW MANY BITS IN FROM THE LEFT SIDE OF THE WORD TO STORE IT.\n!\n  II    = MOD(ISKIP,NBITSW)\n!\n  J     = IAND(MASK,IN)\n  MOVEL = ICON - II\n!\n! BYTE IS TO BE STORED IN MIDDLE OF WORD.  SHIFT LEFT.\n!\n  IF (MOVEL.GT.0) THEN\n     MSK           = ISHFT(MASK,MOVEL)\n     IOUT(INDEX+1) = IOR(IAND(NOT(MSK),IOUT(INDEX+1)),   &\n          &    ISHFT(J,MOVEL))\n!\n! THE BYTE IS TO BE SPLIT ACROSS A WORD BREAK.\n!\n  ELSE IF (MOVEL.LT.0) THEN\n     MSK           = MASKS(NBYTE+MOVEL)\n     IOUT(INDEX+1) = IOR(IAND(NOT(MSK),IOUT(INDEX+1)),    &\n          &    ISHFT(J,MOVEL))\n     ITEMP         = IAND(MASKS(NBITSW+MOVEL),IOUT(INDEX+2))\n     IOUT(INDEX+2) = IOR(ITEMP,ISHFT(J,NBITSW+MOVEL))\n!\n! BYTE IS TO BE STORED RIGHT-ADJUSTED.\n!\n  ELSE\n     IOUT(INDEX+1) = IOR(IAND(NOT(MASK),IOUT(INDEX+1)),J)\n  ENDIF\n!\nEND SUBROUTINE SBYTE\n!\n! +------------------------------------------------------------------+\nSUBROUTINE SBYTES(IOUT,IN,ISKIP,NBYTE,NSKIP,N)\n! THIS PROGRAM WRITTEN BY.....\n!             DR. ROBERT C. GAMMILL, CONSULTANT\n!             NATIONAL CENTER FOR ATMOSPHERIC RESEARCH\n!             JULY 1972\n! THIS IS THE FORTRAN VERSIONS OF SBYTES.\n!\n!             FORTRAN 90\n!             AUGUST 1990  RUSSELL E. JONES\n!             NATIONAL WEATHER SERVICE\n!\n! USAGE:    CALL SBYTES (PCKD,UNPK,INOFST,NBIT, NSKIP,ITER)\n!\n!   INPUT ARGUMENT LIST:\n!     UNPK     -  NBITS OF THE RIGHT SIDE OF EACH WORD OF ARRAY\n!                 UNPK IS MOVED TO ARRAY PCKD. INOFST BITS ARE\n!                 SKIPPED OVER BEFORE THE 1ST DATA IS MOVED, NBITS\n!                 ARE STORED, NSKIP BITS ARE SKIPPED OVER, THE NEXT\n!                 NBITS ARE MOVED,  BIT ARE SKIPPED OVER, ETC. UNTIL\n!                 ITER GROUPS OF BITS ARE PACKED.\n!    INOFST    -  A FULLWORD INTEGER SPECIFYING THE INITAL OFFSET\n!                 IN BITS OF THE FIRST BYTE, COUNTED FROM THE\n!                 LEFTMOST BIT IN PCKD.\n!    NBITS     -  A FULLWORD INTEGER SPECIFYING THE NUMBER OF BITS\n!                 IN EACH BYTE TO BE PACKED.  LEGAL BYTE WIDTHS\n!                 ARE IN THE RANGE 1 - 32.\n!    NSKIP     -  A FULLWORD INTEGER SPECIFYING THE NUMBER OF BITS\n!                 TO SKIP BETWEEN SUCCESSIVE BYTES.  ALL NON-NEGATIVE\n!                 SKIP COUNTS ARE LEGAL.\n!    ITER      -  A FULLWORD INTEGER SPECIFYING THE TOTAL NUMBER OF\n!                 BYTES TO BE PACKED, AS CONTROLLED BY INOFST,\n!                 NBIT AND NSKIP ABOVE.   ALL NON-NEGATIVE ITERATION\n!                 COUNTS ARE LEGAL.\n!\n!   OUTPUT ARGUMENT LIST:\n!    PCKD      -  THE FULLWORD IN MEMORY TO WHICH PACKING IS TO\n!                 BEGIN STARTING AT BIT INOFST. THE INOSTAT BITS\n!                 ARE NOT ALTERED. NSKIP BITS ARE NOT ALTERED.\n!\n  INTEGER    IN(*)\n  INTEGER    IOUT(*)\n#if defined (CRAY) || defined (BIT64)\n  INTEGER    MASKS(64)\n!\n  DATA  NBITSW/64/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 64 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,     &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,\t\t&\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,\t\t&\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,\t\t&\n       & 2147483647, 4294967295, 8589934591, 17179869183,\t\t\t&\n       & 34359738367, 68719476735, 137438953471, 274877906943,\t\t&\n       & 549755813887, 1099511627775, 2199023255551, 4398046511103,\t&\n       & 8796093022207, 17592186044415, 35184372088831,\t\t\t&\n       & 70368744177663, 140737488355327, 281474976710655,\t\t&\n       & 562949953421311, 1125899906842623, 2251799813685247,\t\t&\n       & 4503599627370495, 9007199254740991, 18014398509481983,\t\t&\n       & 36028797018963967, 72057594037927935, 144115188075855871,\t&\n       & 288230376151711743, 576460752303423487, 1152921504606846975,\t&\n       & 2305843009213693951, 4611686018427387903, 9223372036854775807,   &\n       & -1/\n#else\n  INTEGER    MASKS(32)\n!\n  DATA  NBITSW/32/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 32 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,   &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,       &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,        &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,         &\n       & 2147483647, -1/\n#endif\n!\n! NBYTE MUST BE LESS THAN OR EQUAL TO NBITSW\n!\n  ICON = NBITSW - NBYTE\n  IF (ICON.LT.0) RETURN\n  MASK   = MASKS(NBYTE)\n!\n! INDEX TELLS HOW MANY WORDS INTO IOUT THE NEXT BYTE IS TO BE STORED.\n!\n  INDEX  = ISKIP / NBITSW\n!\n! II TELLS HOW MANY BITS IN FROM THE LEFT SIDE OF THE WORD TO STORE IT.\n!\n  II     = MOD(ISKIP,NBITSW)\n!\n! ISTEP IS THE DISTANCE IN BITS FROM ONE BYTE POSITION TO THE NEXT.\n!\n  ISTEP  = NBYTE + NSKIP\n!\n! IWORDS TELLS HOW MANY WORDS TO SKIP FROM ONE BYTE TO THE NEXT.\n!\n  IWORDS = ISTEP / NBITSW\n!\n! IBITS TELLS HOW MANY BITS TO SKIP AFTER SKIPPING IWORDS.\n!\n  IBITS  = MOD(ISTEP,NBITSW)\n!\n  DO I = 1,N\n     J     = IAND(MASK,IN(I))\n     MOVEL = ICON - II\n!\n! BYTE IS TO BE STORED IN MIDDLE OF WORD.  SHIFT LEFT.\n!\n     IF (MOVEL.GT.0) THEN\n        MSK           = ISHFT(MASK,MOVEL)\n        IOUT(INDEX+1) = IOR(IAND(NOT(MSK),IOUT(INDEX+1)),   &\n             &    ISHFT(J,MOVEL))\n!\n! THE BYTE IS TO BE SPLIT ACROSS A WORD BREAK.\n!\n     ELSE IF (MOVEL.LT.0) THEN\n        MSK           = MASKS(NBYTE+MOVEL)\n        IOUT(INDEX+1) = IOR(IAND(NOT(MSK),IOUT(INDEX+1)),    &\n             &    ISHFT(J,MOVEL))\n        ITEMP         = IAND(MASKS(NBITSW+MOVEL),IOUT(INDEX+2))\n        IOUT(INDEX+2) = IOR(ITEMP,ISHFT(J,NBITSW+MOVEL))\n!\n! BYTE IS TO BE STORED RIGHT-ADJUSTED.\n!\n     ELSE\n        IOUT(INDEX+1) = IOR(IAND(NOT(MASK),IOUT(INDEX+1)),J)\n     ENDIF\n!\n     II    = II + IBITS\n     INDEX = INDEX + IWORDS\n     IF (II.GE.NBITSW) THEN\n        II    = II - NBITSW\n        INDEX = INDEX + 1\n     ENDIF\n!\n  END DO\nEND SUBROUTINE SBYTES\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/get_unused_unit.F",
    "content": "integer function get_unused_unit() result(iunit)\n  implicit none\n  integer :: i\n  logical :: used\n\n  do i = 11, 255\n     inquire(unit=i, opened=used)\n     if (.not. used) then\n        iunit = i\n        return\n     endif\n  enddo\n\n  print*, \"GET_UNUSED_UNIT:  \"\n  print*, \"      Problem getting unused unit number.\"\n  call abort()\n\nend function get_unused_unit\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/io_f.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#ifdef _BZIP_YES\n#include <bzlib.h> \n#endif\n\n#if defined (CRAY)\n\n#define c_gribopen C_GRIBOPEN\n#define c_close C_CLOSE\n#define c_writeopen C_WRITEOPEN\n#define io_fread IO_FREAD\n#define io_fwrite IO_FWRITE\n#define io_fseek IO_FSEEK\n#define io_ftell IO_FTELL\n\n#elif defined (__sgi) || defined (__sun) || defined (__alpha) || defined (__linux)\n\n#define c_gribopen c_gribopen_\n#define c_close c_close_\n#define c_writeopen c_writeopen_\n#define io_fread io_fread_\n#define io_fwrite io_fwrite_\n#define io_fseek io_fseek_\n#define io_ftell io_ftell_\n\n#elif defined (IBM) || defined (HP)\n\n#define c_gribopen c_gribopen\n#define c_close c_close\n#define c_writeopen c_writeopen\n#define io_fread io_fread\n#define io_fwrite io_fwrite\n#define io_fseek io_fseek\n#define io_ftell io_ftell\n\n#endif\n\n\nstruct GribFileInfo {\n  FILE *fd;\n  int compression;\n#ifdef _BZIP_YES\n  BZFILE* b;\n#endif\n\n};\n\nvoid c_gribopen(char *filename, struct GribFileInfo **GFPTR, int *ierr) {\n/* \n   Purpose:\n   \n      Open a file for reading.\n\n   Input:\n\n      filename:  The (null-terminated) name of the file to open.\n\n   Output:\n \n      GFPTR:  A pointer to a structure containing various file metadata,\n              including the all important FILE pointer.\n\n      ierr:   An error status flag.  ierr == 0 -- File opened successfully.\n                                     ierr == 1 -- Unsuccessful attempt to open the file\n                                                  (reason for failure undetermined).\n\n   Side effects:\n\n      The file is opened, and the file stream pointer is positioned at\n      the beginning of the file.  A determination is made (based on\n      file suffix) on whether the file is bzip2-compressed or not.  If\n      the file is bzip2-compressed, the file is opened for BZIP2\n      sequential reading.\n\n*/\n\n\n  struct GribFileInfo *lg;\n  \n  /* Allocate space for my new GribFileInfo structure */\n  lg = (struct GribFileInfo*) calloc(1,sizeof(struct GribFileInfo));\n\n  /* Open the file, setting the FILE pointer in my new GribFileInfo structure */\n  lg->fd = fopen(filename, \"r\");\n  if (! lg->fd) {\n    *ierr = 1;\n  }\n  else {\n    *ierr = 0;\n  }\n\n#ifdef _BZIP_YES\n  /* If the file ends in \".bz2\", assume it is a bzip2-compressed file, and */\n  /* initialize things for reading a bzip2-compressed file.                */\n  \n  if (strstr(filename,\".bz2\\0\")) {\n    int bzerror;\n    int verbosity = 1;\n    int small = 0;\n    /*  printf(\"BZIP2 compressed file.\\n\"); */\n    lg->b = BZ2_bzReadOpen( &bzerror, lg->fd, verbosity, small, NULL, 0 );\n    if ( bzerror != BZ_OK ) {\n      BZ2_bzReadClose ( &bzerror, lg->b );\n      printf (\"Problem BZopen.\\n\");\n      exit (1);\n    }\n    lg->compression = 2;\n  }\n  else {\n    lg->compression = 0;\n  }\n#else\n  lg->compression = 0;\n#endif\n\n  /*  printf(\"c_gribopen:  lg->fd = %lu\\n\", lg->fd); */\n  *GFPTR = lg;\n}\n\nvoid c_writeopen(char *filename, struct GribFileInfo **GFPTR) {\n  struct GribFileInfo *lg;\n  lg = (struct GribFileInfo*) calloc(1,sizeof(struct GribFileInfo));\n  lg->fd = fopen(filename, \"w\");\n}\n\nvoid c_close(struct GribFileInfo **GFPTR) {\n  int bzerror;\n  int ierr;\n  switch ((*GFPTR)->compression) {\n  default:\n    printf(\"Unrecognized compression:  %i\\n\",(*GFPTR)->compression);\n    exit (1);\n#ifdef _BZIP_YES\n  case 2:\n    BZ2_bzReadClose ( &bzerror, (*GFPTR)->b );\n    if ( bzerror != BZ_OK ) {\n      printf (\"Problem with call to BZ2_bz_ReadClose.\\n\");\n      exit (1);\n    }\n    fclose((*GFPTR)->fd);\n    free((*GFPTR));\n    break;\n#endif\n  case 0:\n    ierr = fclose((*GFPTR)->fd);\n    if (ierr) {\n      printf(\"close error:  %i\\n\", ierr);\n      exit (1);\n    }\n    free((*GFPTR));\n    break;\n  }\n}\n\nvoid io_fread(struct GribFileInfo **GFPTR, char *buf, int *nread, int *iread, int *ierr) {\n  int read_return;\n  int bzerror;\n  /*  printf(\"io_fread:  GFPTR->fd = %lu\\n\", (*GFPTR)->fd); */\n  \n  switch ((*GFPTR)->compression) {\n  default:\n    printf(\"Unrecognized compression:  %i\\n\",(*GFPTR)->compression);\n    exit (1);\n#ifdef _BZIP_YES\n  case 2:\n    read_return = BZ2_bzRead ( &bzerror, (*GFPTR)->b, buf, *nread );\n    break;\n#endif\n  case 0:\n    read_return = fread(buf, 1, *nread, (*GFPTR)->fd);\n    break;\n  }\n  if (read_return != *nread) {\n    *iread = read_return;\n    *ierr = 1;\n  }\n  else {\n    *ierr = 0;\n    *iread = read_return;\n  }\n  return;\n}\n\nvoid io_fwrite(struct GribFileInfo **GFPTR, char *buf, int *nwrite, int *ierr) {\n\n  int write_return;\n  write_return = fwrite(buf, 1, *nwrite, (*GFPTR)->fd);\n  if (write_return != *nwrite) {\n    *ierr = 1;\n  }\n  else {\n    *ierr = 0;\n  }\n}\n\nvoid io_fseek(struct GribFileInfo **GFPTR, int *nbytes, int *mode) {\n  int iseek;\n  printf(\"No fseek!\\n\");\n  exit (1);\n  switch (*mode) {\n  case 0:\n    iseek = fseek((*GFPTR)->fd, *nbytes, SEEK_CUR);\n    break;\n  case 1:\n    iseek = fseek((*GFPTR)->fd, *nbytes, SEEK_SET);\n    break;\n  case 2:\n    iseek = fseek((*GFPTR)->fd, *nbytes, SEEK_END);\n    break;\n  default:\n    printf(\"io_fseek_:  Unrecognized mode:  %i\\n\", *mode);\n    exit (1);\n  }\n\n  if (iseek != 0) {\n    printf(\"io_fseek_:  Seek problem.\\n\");\n    exit (1);\n  }\n\n}\n\nvoid io_ftell(struct GribFileInfo **GFPTR, long *itell) {\n  *itell = ftell((*GFPTR)->fd);\n  if (itell < 0) {\n    printf(\"io_ftell_:  Problem from ftell.\\n\");\n    exit (1);\n  }\n}\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/kwm_date_utilities.F",
    "content": "module kwm_date_utilities\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n!  From old date ('YYYY-MM-DD HH:MM:SS.ffff') and\n!  delta-time, compute the new date.\n\n!  on entry     -  odate  -  the old hdate.\n!                  idt    -  the change in time\n\n!  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n\n!  Local Variables\n\n!  yrold    -  indicates the year associated with \"odate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scold    -  indicates the second associated with \"odate\"\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n\n!  mday     -  a list assigning the number of days in each month\n\n!  i        -  loop counter\n!  nday     -  the integer number of days represented by \"idt\"\n!  nhour    -  the integer number of hours in \"idt\" after taking out\n!              all the whole days\n!  nmin     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days and whole hours.\n!  nsec     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days, whole hours, and whole minutes.\n\n    integer :: nlen, olen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n\n    logical :: punctuated\n    logical :: idtdy, idthr, idtmin, idtsec, idtfrac\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n!  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    olen = len(odate)\n    if (punctuated) then\n       if (olen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n    endif\n\n!  Use internal READ statements to convert the CHARACTER string\n!  date into INTEGER components.\n\n    idtdy   = .FALSE.\n    idthr   = .FALSE.\n    idtmin  = .FALSE.\n    idtsec  = .FALSE.\n    idtfrac = .FALSE.\n    read(odate(1:4),  '(i4)') yrold\n    if (punctuated) then\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.13) then\n          idthr = .TRUE.\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             idtmin = .TRUE.\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                idtsec = .TRUE.\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   idtfrac = .TRUE.\n                   read(odate(21:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    else ! Not punctuated\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.10) then\n          idthr = .TRUE.\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             idtmin = .TRUE.\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                idtsec = .TRUE.\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   idtfrac = .TRUE.\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n!  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n!  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n!  Check that the fractional part  of ODATE makes sense.\n\n!KWM      IF ((scold.GT.59).or.(scold.LT.0)) THEN\n!KWM         WRITE(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n!KWM         opass = .FALSE.\n!KWM      END IF\n\n    if (.not.opass) then\n       write(*,*) 'Crazy ODATE: ', odate(1:olen), olen\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n\n!  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (idtfrac) then !idt should be in fractions of seconds\n       if (punctuated) then\n          ifrc = olen-14\n       else\n          ifrc = olen-20\n       endif\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (idtsec) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (idtmin) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (idthr) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (idtdy) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            olen\n       write(*,*) odate(1:olen)\n       call abort()\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n!  Now construct the new mdate\n\n    nlen = LEN(ndate)\n\n    if (punctuated) then\n\n       if (nlen.gt.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:19)//'.'//hfrc(31-nlen:10)\n\n       else if (nlen.eq.19.or.nlen.eq.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n          if (nlen.eq.20) ndate = ndate(1:19)//'.'\n\n       else if (nlen.eq.16) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (nlen.eq.13) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n       if (olen.ge.11) ndate(11:11) = sp\n\n    else\n\n       if (nlen.gt.20) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:18)//hfrc(31-nlen:10)\n\n       else if (nlen.eq.14) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n14        format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.12) then\n          write(ndate,12) yrnew, monew, dynew, hrnew, minew\n12        format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,210) yrnew, monew, dynew, hrnew\n210       format(i4,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.8) then\n          write(ndate,8) yrnew, monew, dynew\n8         format(i4,i2.2,i2.2)\n\n       else\n          stop \"DATELEN PROBLEM\"\n       end if\n    endif\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n    implicit none\n\n!  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n!  compute the time difference.\n\n!  on entry     -  newdate  -  the new hdate.\n!                  olddate  -  the old hdate.\n\n!  on exit      -  idt    -  the change in time.\n!                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n!  Local Variables\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  yrold    -  indicates the year associated with \"odate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n!  scold    -  indicates the second associated with \"odate\"\n!  i        -  loop counter\n!  mday     -  a list assigning the number of days in each month\n\n! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    character (len=24) :: tdate\n    integer :: olen, nlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), i, newdys, olddys\n    logical :: npass, opass\n    integer :: isign\n    integer :: ifrc\n\n    logical :: punctuated\n\n    olen = len(olddate)\n    nlen = len(newdate)\n    if (nlen.ne.olen) then\n       write(*,'(\"GETH_IDTS: NLEN /= OLEN: \", A, 3x, A)') newdate(1:nlen), olddate(1:olen)\n       call abort\n    endif\n\n    if (olddate.gt.newdate) then\n       isign = -1\n\n       ifrc = olen\n       olen = nlen\n       nlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       isign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n\n!  Break down old and new hdates into parts\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(odate(1:4),  '(i4)') yrold\n    read(ndate(1:4),  '(i4)') yrnew\n\n    if (punctuated) then\n\n!  Break down old hdate into parts\n\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       if (olen.ge.13) then\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   if (olen.eq.21) then\n                      read(odate(21:21),'(i1)') frold\n                   else if (olen.eq.22) then\n                      read(odate(21:22),'(i2)') frold\n                   else if (olen.eq.23) then\n                      read(odate(21:23),'(i3)') frold\n                   else if (olen.eq.24) then\n                      read(odate(21:24),'(i4)') frold\n                   endif\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(6:7),  '(i2)') monew\n       read(ndate(9:10), '(i2)') dynew\n       if (nlen.ge.13) then\n          read(ndate(12:13),'(i2)') hrnew\n          if (nlen.ge.16) then\n             read(ndate(15:16),'(i2)') minew\n             if (nlen.ge.19) then\n                read(ndate(18:19),'(i2)') scnew\n                if (nlen.gt.20) then\n                   read(ndate(21:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    else\n\n!  Break down old hdate into parts\n\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       if (olen.ge.10) then\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(5:6),  '(i2)') monew\n       read(ndate(7:8), '(i2)') dynew\n       if (nlen.ge.10) then\n          read(ndate(9:10),'(i2)') hrnew\n          if (nlen.ge.12) then\n             read(ndate(11:12),'(i2)') minew\n             if (nlen.ge.14) then\n                read(ndate(13:14),'(i2)') scnew\n                if (nlen.ge.15) then\n                   read(ndate(15:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n!  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n       print*, 'GETH_IDTS:  Month of NDATE = ', monew\n       npass = .false.\n    end if\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n       opass = .false.\n    end if\n\n!  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    endif\n\n!  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    end if\n\n!  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n       npass = .false.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n       opass = .false.\n    end if\n\n!  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n       npass = .false.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n       opass = .false.\n    end if\n\n!  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n       npass = .false.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'Screwy NDATE: ', ndate(1:nlen)\n       call abort()\n    end if\n\n    if (.not. opass) then\n       print*, 'Screwy ODATE: ', odate(1:olen)\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n!  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n!  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n!  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (punctuated) then\n       if (olen.gt.10) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.13) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.16) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.20) then\n                   ifrc = olen-20\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    else\n       if (olen.gt.8) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.10) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.12) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.14) then\n                   ifrc = olen-14\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    endif\n\n    if (isign .eq. -1) then\n       idt = idt * isign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n!\n! Compute the number of days in February for the given year.\n!\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n!\n! Compute the number of days in the month of given date hdate.\n!\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    if (hdate(5:5) == \"-\") then\n       read(hdate(1:7), '(I4,1x,I2)') year, month\n    else\n       read(hdate(1:6), '(I4,I2)') year, month\n    endif\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\nend module kwm_date_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/kwm_grid_utilities.F",
    "content": "module kwm_grid_utilities\n  private :: oned\ncontains\n\n  real function bint(array, ix, jx, x, y) result(val)\n    implicit none\n!\n!  Overlapping parabolic interpolation of array to point x, y.\n!\n    integer, intent(in)                   :: ix, jx\n    real   , intent(in), dimension(ix,jx) :: array\n    real   , intent(in)                   :: x, y\n\n    real, dimension(4,4) :: STL\n    integer :: I, J, K, KK, L, LL\n    real    :: XX, YY, A, B, C, D, E, F, G, H\n\n    if ((X < 2) .or. (Y < 2) .or. (X > IX-1) .or. (Y > JX-1)) then\n       val = -1.E36\n       return\n    endif\n\n    I = int(X)\n    J = int(Y)\n    XX = X-I\n    YY = Y-J\n!    IF(ABS(XX) <= 0.0001 .and. ABS(YY) <= 0.0001) THEN\n!       val = array(i,j)\n!       RETURN\n!    ENDIF\n\n    STL = ARRAY( I-1:I+2 , J-1:J+2 )\n\n    A = ONED(XX,STL(1,1),STL(2,1),STL(3,1),STL(4,1))\n    B = ONED(XX,STL(1,2),STL(2,2),STL(3,2),STL(4,2))\n    C = ONED(XX,STL(1,3),STL(2,3),STL(3,3),STL(4,3))\n    D = ONED(XX,STL(1,4),STL(2,4),STL(3,4),STL(4,4))\n    val = ONED(YY,A,B,C,D)\n\n  end function bint\n\n  real function bint_p(array, ix, jx, x, y) result(val)\n    implicit none\n!\n!  Overlapping parabolic interpolation of array to point x, y.\n!\n    integer, intent(in)                            :: ix, jx\n    real   , pointer, dimension(:,:)               :: array\n    real   , intent(in)                            :: x, y\n\n    real, dimension(4,4) :: STL\n    integer :: I, J, II, JJ, L, LL\n    real    :: XX, YY, A, B, C, D, E, F, G, H\n\n!KWM    if ((X < 1) .or. (Y < 1) .or. (X > IX) .or. (Y > JX)) then\n!KWM       val = -1.E36\n!KWM       return\n!KWM    endif\n\n    I = int(X)\n    J = int(Y)\n    XX = X-I\n    YY = Y-J\n\n!    IF(ABS(XX) <= 0.0001 .and. ABS(YY) <= 0.0001) THEN\n!       val = array(i,j)\n!       RETURN\n!    ENDIF\n\n    do II = -1, 2\n       do JJ = -1, 2\n          if ((I+II<1) .or. (I+II>IX).or. (J+JJ<1) .or. (J+JJ>JX)) then\n             STL(II+2,JJ+2) = -1.E36\n          else\n             STL(II+2,JJ+2) = ARRAY(I+II,J+JJ)\n          endif\n       enddo\n    enddo\n\n    ! STL = ARRAY( I-1:I+2 , J-1:J+2 )\n\n    ! if (ANY(STL<-1.E25)) then\n    !    val = -1.E36\n    !    return\n    ! endif\n\n    ! Corner points missing are OK.  Any other points missing and we have a problem.\n    if ((ANY(STL(:,2:3)<-1.E25)) .or. (ANY(STL(2:3,:)<-1.E25))) then\n       val = -1.E36\n       return\n    endif\n\n!KWM    do JJ = 4, 1, -1\n!KWM       print*, (STL(II,JJ),II=1,4)\n!KWM    enddo\n!KWM    print*, '-----------------------------------'\n\n    A = ONED(XX,STL(1,1),STL(2,1),STL(3,1),STL(4,1))\n    B = ONED(XX,STL(1,2),STL(2,2),STL(3,2),STL(4,2))\n    C = ONED(XX,STL(1,3),STL(2,3),STL(3,3),STL(4,3))\n    D = ONED(XX,STL(1,4),STL(2,4),STL(3,4),STL(4,4))\n    val = ONED(YY,A,B,C,D)\n\n    if (ANY(STL<-1.E25)) then\n\n       E = ONED(YY,STL(1,1),STL(1,2),STL(1,3),STL(1,4))\n       F = ONED(YY,STL(2,1),STL(2,2),STL(2,3),STL(2,4))\n       G = ONED(YY,STL(3,1),STL(3,2),STL(3,3),STL(3,4))\n       H = ONED(YY,STL(4,1),STL(4,2),STL(4,3),STL(4,4))\n       val = 0.5 * (val + ONED(XX,E,F,G,H))\n    endif\n\n    ! Constrain the results to fall between the original min and maximum of the 16 points\n    val = min(val, maxval(STL))\n    val = max(val, minval(STL))\n\n  end function bint_p\n\n  REAL FUNCTION ONED(X,A,B,C,D) result(val)\n    ! Points B and C must have good data.\n    ! Points A and D may have the no-data indication (value less than -1.E25)\n    implicit none\n    real, intent(in) :: X, A, B, C, D\n\n    if (B < -1.E25) stop \"Point B in ONED\"\n    if (C < -1.E25) stop \"Point C in ONED\"\n\n    IF (abs(X) < 1.E-5) then\n       val = B\n    else if (abs(X-1.) < 1.E-5) then\n       val = C\n    else\n\n       if ((A<-1.E25).and.(D<-1.E25)) then\n          ! Points A and D have the no-data flag.\n          val = (B*(1.0-X)) + (C*X)\n       else if (D<-1.E25) then\n          ! No-data flag at point D.  Point A is good (or the previous If-test would have caught it).\n          val = B+X*(0.5*(C-A)+X*(0.5*(C+A)-B))\n       else if (A<-1.E25) then\n          ! No-data flag at point A.  Point D is good (or the earlier If-test would have caught it).\n          val = C+(1.0-X)*(0.5*(B-D)+(1.0-X)*(0.5*(B+D)-C))\n       else\n          ! All four points have good data\n          val = (1.0-X)*(B+X*(0.5*(C-A)+X*(0.5*(C+A)-B)))+X*(C+(1.0-X)*(0.5 &\n               *(B-D)+(1.0-X)*(0.5*(B+D)-C)))\n       endif\n\n    endif\n  END FUNCTION ONED\n\n  real function four_point(array, ix, jx, x, y) result(val)\n\n!*****************************************************************************!\n! Performs a 4-point interpolation to a given (x,y) coordinate in an array.   !\n! The X coordinate corresponds to the first dimension of array ARRAY.         !\n! The Y coordinate corresponds to the second dimension of array ARRAY.        !\n! For points outside the domain, the return value is -1.E36.                  !\n!*****************************************************************************!\n\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, intent(in), dimension(ix,jx) :: array\n    real, intent(in) :: x, y\n\n    integer :: i, j, ip, jp\n    real :: dx, dy, rx, ry\n\n    if (((x-ix)>1.E-4) .or. ((y-jx)>1.E-4) .or. (x < 0.99999) .or. (y < 0.99999)) then\n       if((x-ix)>1.E-5)  print*, 'x, ix = ', x, ix, ((x-ix)>1.E-5), (x-ix)\n       if ( y < 0.99999) print*, 'y = ', y\n       val = -1.E36\n    else\n       i = int(x+1.E-5)\n       j = int(y+1.E-5)\n\n       ! The following MAX test should be safe, since we've already checked\n       ! that we're not too much less than 1.0\n       i = max(i, 1)\n       j = max(j, 1)\n\n       dx = x-i\n       dy = y-j\n       if (dx < 1.E-4) dx = 0.0\n       if (dx > 0.9999) dx = 1.0\n       if (dy < 1.E-4) dy = 0.0\n       if (dy > 0.9999) dy = 1.0\n       rx = 1.0 - dx\n       ry = 1.0 - dy\n\n       ! The following MIN test should be safe, since we've already\n       ip = min(i+1, ix)\n       jp = min(j+1, jx)\n\n       if (ANY(array(i:ip,j:jp)<-1.E25)) then\n          val = -1.E36\n          return\n       endif\n\n\n!KWM       print*, 'ip, jp = ', ip, jp\n!KWM       print*, 'i, j = ', i, j\n!KWM       print*, 'rx, ry, dx, dy = ', rx, ry, dx, dy\n\n       val= array(i ,j )*RY*RX + &\n            array(ip,j )*RY*DX + &\n            array(i ,jp)*DY*RX + &\n            array(ip,jp)*DY*DX\n    endif\n\n  end function four_point\n\n\n\n  real function four_point_p(array, ix, jx, x, y) result(val)\n\n!*****************************************************************************!\n! Performs a 4-point interpolation to a given (x,y) coordinate in an array.   !\n! The X coordinate corresponds to the first dimension of array ARRAY.         !\n! The Y coordinate corresponds to the second dimension of array ARRAY.        !\n! For points outside the domain, the return value is -1.E36.                  !\n!*****************************************************************************!\n\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, pointer, dimension(:,:) :: array\n    real, intent(in) :: x, y\n\n    integer :: i, j\n    real :: dx, dy, rx, ry\n\n    if ((x > ix) .or. (y > jx) .or. (x < 1) .or. (y < 1)) then\n       val = -1.E36\n    else\n       i = int(x)\n       j = int(y)\n       dx = x-i\n       dy = y-j\n       rx = 1.0 - dx\n       ry = 1.0 - dy\n\n       val= array(i  ,j  )*RY*RX + &\n            array(i+1,j  )*RY*DX + &\n            array(i  ,j+1)*DY*RX + &\n            array(i+1,j+1)*DY*DX\n    endif\n\n  end function four_point_p\n\n\n  subroutine smdsm(FLD, ix, jx, npass)\n\n!*****************************************************************************!\n!                                                                             !\n!  Purpose: Smooth the 2-d field FLD with the 2-pass smoother/desmoother      !\n!           Watch it.  All values of FLD are assumed to be valid, that is,    !\n!           no stagger is assumed.                                            !\n!                                                                             !\n!   On Entry:  FLD(IX,JX):  2-d field to be smoothed.                         !\n!              IX, JX    :  Dimensions of 2-d field FLD.                      !\n!              NPASS     :  Optional number of passes of the two-pass smoother!\n!                           (default 1 pass of the two-pass smoother)         !\n!                                                                             !\n!   On Exit:   FLD(IX,JX):  The smoothed 2-d field.                           !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n    INTEGER, intent(in) :: IX, JX\n    REAL, intent(inout), dimension(ix,jx) :: FLD\n    integer, intent(in), optional :: npass\n\n!  XNU(N) : Smoothing coefficient for pass N\n    REAL, parameter, dimension(2) :: XNU = (/ 0.50, -0.52 /)\n    INTEGER :: I, J, N, NP, IND\n    REAL :: ASV, APLUS, CELL\n\n    if (present(npass)) then\n       np = npass\n    else\n       np = 1\n    endif\n\n    NUMPASS : do n = 1, np\n\n       DO IND = 1, 2\n\n!...  FIRST, SMOOTH IN THE IX DIRECTION\n          DO I = 2,IX-1\n             ASV = FLD(I,1)\n             DO J = 2,JX-1\n                APLUS = FLD(I,J+1)\n                CELL = FLD(I,J)\n                FLD(I,J) = FLD(I,J) + XNU(IND)*((ASV + APLUS)/2.0 - FLD(I,J))\n                ASV = CELL\n             ENDDO\n          ENDDO\n\n!...  NOW, SMOOTH IN THE JX DIRECTION\n          DO J = 2,JX-1\n             ASV = FLD(1,J)\n             DO I = 2,IX-1\n                APLUS = FLD(I+1,J)\n                CELL = FLD(I,J)\n                FLD(I,J) = FLD(I,J) + XNU(IND)*((ASV + APLUS)/2.0 - FLD(I,J))\n                ASV = CELL\n             ENDDO\n          ENDDO\n\n       ENDDO\n\n    enddo NUMPASS\n\n  END subroutine smdsm\n\n\n  subroutine smt121(FLD, ix, jx, npass)\n\n!*****************************************************************************!\n!                                                                             !\n!   Purpose :  Performs 1-2-1 smoothing on a 2-d field FLD.                   !\n!              Watch it.  All values of FLD are assumed to be valid, that is, !\n!              no stagger is assumed.                                         !\n!                                                                             !\n!   On entry : FLD(IX,JX): 2-D field to be smoothed.                          !\n!                   IX,JX: The dimensions of the field FLD.                   !\n!                   NPASS: Optional number of passes (default 1).             !\n!                                                                             !\n!   On exit :  FLD(IX,JX): The smoothed field.                                !\n!                                                                             !\n!   The final value at any particular grid point is a weighted sum            !\n!   of that grid point and the eight immediately surrounding points           !\n!   thus:                                                                     !\n!                        1 2 1                                                !\n!                        2 4 2                                                !\n!                        1 2 1                                                !\n!                                                                             !\n!   At edges, we weight thus:                                                 !\n!                        -----                                                !\n!                        2 4 2                                                !\n!                        1 2 1                                                !\n!                                                                             !\n!   At corners, we weight thus:                                               !\n!                        +---                                                 !\n!                        |4 2                                                 !\n!                        |2 1                                                 !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n    integer, intent(in) :: ix, jx\n    REAL, intent(inout), dimension(ix,jx) :: FLD\n    integer, intent(in), optional :: npass\n\n    integer :: i, j, n, np\n    real :: cell, aplus, asv\n\n    if (present(npass)) then\n       np = npass\n    else\n       np = 1\n    endif\n\n\n    NUMPASS : do n = 1, np\n\n       DO I = 1, IX\n          ASV = FLD(I,1)\n          FLD(I,1) = (2.*FLD(I,1) + FLD(I,2))/3.\n          DO J = 2, JX-1\n             APLUS = FLD(I,J+1)\n             CELL = FLD(I,J)\n             FLD(I,J) = 0.5*FLD(I,J) + 0.25*(ASV+APLUS)\n             ASV = CELL\n          ENDDO\n          FLD(I,JX) = (2.*FLD(I,JX) + ASV)/3.\n       ENDDO\n\n       DO J=1,JX\n          ASV = FLD(1,J)\n          FLD(1,J) = (2.*FLD(1,J) + FLD(2,J))/3.\n          DO I=2,IX-1\n             APLUS = FLD(I+1,J)\n             CELL = FLD(I,J)\n             FLD(I,J) = 0.5*FLD(I,J) + 0.25*(ASV+APLUS)\n             ASV = CELL\n          ENDDO\n          FLD(IX,J) = (2.*FLD(IX,J) + ASV)/3.\n       ENDDO\n\n    enddo NUMPASS\n\n  END subroutine smt121\n\n  subroutine gaussian_filter(fld, filt, ix, jx, dxkm, half_width)\n!\n! Implementation of a gaussian filter.\n!\n! Purpose:  Return a smoothed version of array FLD in array FILT.\n!\n    implicit none\n    integer, intent(in) :: ix, jx ! Dimensions of input/output arrays\n    real, intent(in), dimension(ix,jx) :: fld  ! Input array to be filtered.\n    real, intent(out),dimension(ix,jx) :: filt ! Output filtered array.\n    real, intent(in) :: dxkm       ! Grid spacing in km\n    real, intent(in) :: half_width ! Half_Width in km\n\n    real,    parameter :: pi = 3.14159265358979\n    real,    parameter :: twopi = 2.*pi\n\n    integer :: i, j, ii, jj, iii, jjj\n    real :: x, y\n    real :: sigma, sigsq\n    integer :: fsz, hsz\n    real :: cval, eval\n    real, dimension(ix,jx) :: tmp\n    real, allocatable, dimension(:) :: v\n    real, allocatable, dimension(:,:) :: k\n\n    sigma =  (half_width/dxkm)\n    sigsq = sigma*sigma\n    fsz = (nint(8*sigma)*2)-1\n    hsz = (fsz+1)/2\n    allocate(k(fsz,fsz))\n    allocate(v(fsz))\n\n    filt = 0.\n    tmp = 0.\n\n! Compute the kernel\n\n! I'd rather do it in one step, going directly to my vector v,\n! but I don't see how to be able to do that cleanly and still\n! correct for the error (how much the sum differs from 1.0).\n\n! First I compute the two-dimensional kernel array.\n    cval = 1./(twopi*sigsq)\n    do i = 1, fsz\n       x = float(hsz-i)\n       do j = 1, fsz\n          y = float(hsz-j)\n          eval = -((x*x)+(y*y))/(2.*sigsq)\n          k(i,j) = exp(eval)\n       enddo\n    enddo\n    k = k*cval\n! Sum to see how far off of one we are, and divide k/sum\n! to correct for that error (i.e., we want to sum to 1.0)\n    k = k/sum(k)\n\n! Now figure my vector from the corrected kernel array.\n    v = k(1,:) / sqrt(k(1,1))\n\n! Apply the kernel\n\n    do j = 1, jx\n       do i = 1, ix\n          do ii = 1, fsz\n             iii = (i-hsz)+ii\n             if (iii < 1) iii = 1\n             if (iii > ix) iii = ix\n             tmp(i,j) = tmp(i,j) + v(ii)*fld(iii,j)\n          enddo\n       enddo\n    enddo\n\n    do i = 1, ix\n       do j = 1, jx\n          do jj = 1, fsz\n             jjj = (j-hsz)+jj\n             if (jjj < 1) jjj = 1\n             if (jjj > jx) jjj = jx\n             filt(i,j) = filt(i,j) + v(jj)*tmp(i,jjj)\n          enddo\n       enddo\n    enddo\n\n  end subroutine gaussian_filter\n\n  subroutine crs2dot(slab1,slab2,ix,jx)\n\n    ! PURPOSE: Interpolate in horizontal from cross to dot points\n\n    implicit none\n    integer, intent(in) :: ix,jx\n    real, dimension(ix,jx), intent(in)  :: slab1\n    real, dimension(ix,jx), intent(out) :: slab2\n    integer :: ie,je,i,j\n\n    IE=IX-1\n    JE=JX-1\n    DO I=2,IE\n       DO J=2,JE\n          SLAB2(I,J)=0.25*(SLAB1(I,J)+SLAB1(I-1,J)+SLAB1(I,J-1)+SLAB1(I-1,J-1))\n       enddo\n    enddo\n    DO I=2,IE\n       SLAB2(I,1)=0.5*(SLAB1(I,1)+SLAB1(I-1,1))\n       SLAB2(I,JX)=0.5*(SLAB1(I,JE)+SLAB1(I-1,JE))\n    enddo\n    DO J=2,JE\n       SLAB2(1,J)=0.5*(SLAB1(1,J)+SLAB1(1,J-1))\n       SLAB2(IX,J)=0.5*(SLAB1(IE,J)+SLAB1(IE,J-1))\n    enddo\n    SLAB2(1,1)=SLAB1(1,1)\n    SLAB2(1,JX)=SLAB1(1,JE)\n    SLAB2(IX,JX)=SLAB1(IE,JE)\n    SLAB2(IX,1)=SLAB1(IE,1)\n\n  end subroutine crs2dot\n\nend module kwm_grid_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/kwm_string_utilities.F",
    "content": "module kwm_string_utilities\n\ncontains\n\n  subroutine strrep(string, rep1, rep2)\n    ! In string 1, replace expression rep1 with expression rep2.\n    ! if rep2 is shorter than rep1, fill the end of the string\n    ! with blanks\n\n    implicit none\n    character(len=*) :: string, rep1, rep2\n    integer :: idx, inlen, len1, len2\n\n    do\n       inlen = len(string)\n       len1 = len(rep1)\n       len2 = len(rep2)\n       idx = index(string, rep1)-1\n\n       if (idx == -1) then\n          return\n       else\n          string = string(1:idx)// rep2 // &\n               string((idx+len1+1):inlen) // &\n               \"                                                    \"\n       endif\n    enddo\n\n  end subroutine strrep\n\n\n  character(len=1024) function unblank(string) result(return_string)\n    ! Remove blanks (and tabs [char(9)] from string\n    implicit none\n    character(len=*), intent(in) :: string\n    integer :: i, j,  lenstr\n\n    return_string = \" \"\n\n    if ( verify(string,\" \"//char(9)) == 0 ) then\n       stop 'String is all blanks.'\n    endif\n\n    j = 0\n    do i = 1, len(string)\n       if ((string(i:i).ne.' ').and.(string(i:i).ne.char(9))) then\n          j = j + 1\n          return_string(j:j) = string(i:i)\n       endif\n    enddo\n\n  end function unblank\n\n!KWM  character function upcase(h)\n!KWM    implicit none\n!KWM    character :: h\n!KWM\n!KWM    if ((ichar(h).ge.96) .and. (ichar(h).le.123)) then\n!KWM       upcase = char(ichar(h)-32)\n!KWM    else\n!KWM       upcase = h\n!KWM    endif\n!KWM\n!KWM  end function upcase\n\n  character(len=256) function upcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \" \"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.96) .and. (ichar(h(i:i)).le.123)) then\n          return_string(i:i) = char(ichar(h(i:i))-32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function upcase\n\n!KWM  character function downcase(h)\n!KWM    implicit none\n!KWM    character h\n!KWM\n!KWM    if ((ichar(h).ge.65) .and. (ichar(h).le.90)) then\n!KWM       downcase = char(ichar(h)+32)\n!KWM    else\n!KWM       downcase = h\n!KWM    endif\n!KWM  end function downcase\n\n  character(len=256) function downcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \" \"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.65) .and. (ichar(h(i:i)).le.90)) then\n          return_string(i:i) = char(ichar(h(i:i))+32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function downcase\n\n\nend module kwm_string_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/kwm_timing_utilities.F",
    "content": "module kwm_timing_utilities\n  implicit none\n  integer, parameter :: kwm_timing_dimension = 100\n  integer, dimension(kwm_timing_dimension) :: Acount, Asum\n\ncontains\n\n  subroutine timing_start(num)\n    implicit none\n    integer, intent(in) :: num\n    if (num > kwm_timing_dimension) then\n       stop \"TIMING_START PROBLEM.  USE A SMALLER NUM.\"\n    endif\n    call system_clock(Acount(num))\n  end subroutine timing_start\n\n  subroutine timing_end(num, string, ivrb)\n    implicit none\n    integer, intent(in) :: num, ivrb\n    integer :: count_rate, count_max\n    character(len=*), intent(in) :: string\n    integer :: Bcount\n    call system_clock(count=Bcount, count_rate=count_rate, count_max=count_max)\n\n    Asum(num) = Asum(num)+(Bcount-Acount(num))\n    if (ivrb /= 0) then\n       print*,' Timing for '//string//': ', float(Bcount-Acount(num))/float(count_rate), &\n            float(Asum(num))/float(count_rate)\n    endif\n  end subroutine timing_end\n\nend module kwm_timing_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_geo_em.F",
    "content": "module module_geo_em\n!-------------------------------------------------------------\n! At the moment, all that is used from the geo_em file\n! is the array of monthly green vegetation fractions.\n!\n! We also grab projection/grid information, to ensure that\n! the geo_em and wrfinput files are consistent.\n!\n!-------------------------------------------------------------\n  use module_wrfinputfile\n  implicit none\n  ! Define a data structure for WRF geo_em file\n\n  type geo_em_type\n     integer :: idim\n     integer :: jdim\n     integer :: map_proj\n     real    :: Dx\n     real    :: Dy\n     real    :: LoV\n     real    :: Latin1\n     real    :: Latin2\n     real    :: La1\n     real    :: La2\n     real    :: Lo1\n     real    :: Lo2\n     character(len=4) :: landuse_dataset ! \"MODI\" or \"USGS\"\n     real, pointer, dimension(:,:,:) :: veg\n  end type geo_em_type\n\ncontains\n\n  subroutine read_geo_em_file(flnm, geo_em, ierr)\n\n!---------------------------------------------------------------\n!  At the moment, all we need from the geo_em file is the\n!  array of monthly green vegetation fractions.\n!\n!  We also read projection/grid information, to ensure that\n!  the geo_em and wrfinput files are consistent.\n!---------------------------------------------------------------\n\n    implicit none\n\n    character(len=*),   intent(in)  :: flnm\n    type (geo_em_type), intent(out) :: geo_em\n    integer,            intent(out) :: ierr\n    ! Local:\n    integer :: ncid\n    integer :: iret\n    integer :: dimid\n    real, allocatable, dimension(:,:) :: dum2d\n\n\n! Open the NetCDF file.\n    print*, 'flnm = ', flnm\n    iret = nf90_open(flnm, NF90_NOWRITE, ncid)\n    call error_handler(iret, \"Problem reading geo_em file: \"//flnm)\n\n!---------------------------------------------------------------\n!\n! Use the grid and projection information to compare to the\n! wrfinput file that we use, to be sure that we have the\n! same grid in geo_em and wrfinput files.\n!\n! We read the data here, but we make the check elsewhere.\n!\n!---------------------------------------------------------------\n\n! Find out about dimensions in the file.\n\n    iret = nf90_inq_dimid(ncid, \"west_east\", dimid)\n    call error_handler(iret, \"STOP:  Problem finding NetCDF dimension 'west_east'\")\n    iret = nf90_inquire_dimension(ncid, dimid, len=geo_em%idim)\n    call error_handler(iret, \"STOP:  Problem finding NetCDF dimension 'west_east'\")\n\n    iret = nf90_inq_dimid(ncid, \"south_north\", dimid)\n    call error_handler(iret, \"STOP:  Problem finding NetCDF dimension 'south_north'\")\n    iret = nf90_inquire_dimension(ncid, dimid, len=geo_em%jdim)\n    call error_handler(iret, \"STOP:  Problem finding NetCDF dimension 'south_north'\")\n\n    ! Projection information:\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL,\"MAP_PROJ\", geo_em%map_proj)\n    call error_handler(iret, \"STOP:  problem finding NetCDF Global attribute MAP_PROJ\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", geo_em%LoV)\n    call error_handler(iret, \"STOP:  problem finding NetCDF global attribute STAND_LON\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , geo_em%Latin1)\n    call error_handler(iret, \"STOP:  problem finding NetCDF global attribute TRUELAT1\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\" , geo_em%Latin2)\n    call error_handler(iret, \"STOP:  problem finding NetCDF global attribute TRUELAT2\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , geo_em%Dx)\n    call error_handler(iret, \"STOP:  problem finding NetCDF global attribute DX\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"DY\" , geo_em%Dy)\n    call error_handler(iret, \"STOP:  problem finding NetCDF global attribute DY\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"MMINLU\" , geo_em%landuse_dataset)\n    call error_handler(iret, \"STOP:  problem finding NetCDF global attribute MMINLU\")\n\n    allocate(dum2d(geo_em%idim, geo_em%jdim))\n    ! Get Latitudes -- upper-left and lower-right corners\n\n    call get_2d(\"XLAT_M\", ncid, dum2d, geo_em%idim, geo_em%jdim)\n    geo_em%La1 = dum2d(1,1)\n    geo_em%La2 = dum2d(geo_em%idim,geo_em%jdim)\n\n    ! Get Longitude -- upper-left and lower-right corners\n    call get_2d(\"XLONG_M\", ncid, dum2d, geo_em%idim, geo_em%jdim)\n    geo_em%Lo1 = dum2d(1,1)\n    geo_em%Lo2 = dum2d(geo_em%idim,geo_em%jdim)\n\n    deallocate(dum2d)\n\n    !\n    ! Get monthly Greenness Fractions\n    !\n    allocate(geo_em%veg(geo_em%idim, geo_em%jdim, 12))\n    call get_greenness(ncid, geo_em%veg, geo_em%idim, geo_em%jdim, 12)\n\n    ! Close the file and get out of here\n\n    iret = nf90_close(ncid)\n    call error_handler(iret, \"STOP:  Problem closing file??\")\n\n    ierr = 0\n    print*, \"Done with subroutine read_geo_em_file\"\n\n  end subroutine read_geo_em_file\n\n  subroutine get_greenness(ncid, array, idim, jdim, kdim)\n    implicit none\n    integer, intent(in)                          :: ncid\n    integer, intent(in)                          :: idim\n    integer, intent(in)                          :: jdim\n    integer, intent(in)                          :: kdim\n    real, dimension(idim,jdim,kdim), intent(out) :: array\n    ! Local:\n    integer :: ierr\n    integer :: varid\n\n    ierr = nf90_inq_varid(ncid,  \"GREENFRAC\",  varid)\n    call error_handler(ierr, \"STOP:  Problem finding GREENFRAC in geo_em file\")\n\n    ierr = nf90_get_var(ncid, varid, array)\n    call error_handler(ierr, \"STOP:  Problem getting GREENFRAC from geo_em file\")\n\n  end subroutine get_greenness\n\nend module module_geo_em\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_grib.F",
    "content": "module module_grib\n  use module_grib1\n  use module_grib2\n  use module_grib_common\n  implicit none\n\n! Many of these are wrapper functions which call the appropriate GRIB1\n! or GRIB2 routines as necessary.\n\ncontains\n\n\n!=================================================================================\n!=================================================================================\n\n  subroutine gribopen(filename, fd, ierr)\n    implicit none\n    !\n    ! Purpose:\n    !      Open the GRIB2 file for reading, and do a few set-up tasks.\n    !\n    ! Input:\n    !      filename:  Name of the GRIB2 file to open.\n    !\n    ! Output:\n    !      fd:        Integer value for the c pointer to a memory location for \n    !                 a structure containing file information, among which is \n    !                 the FILE pointer.\n    !\n    !      ierr:      An error flag.  ierr == 0 -- File opened successfully.\n    !                                 ierr == 1 -- There was some problem opening the file.\n    !                                 ierr == 2 -- The specified file does not exist.\n    !\n    ! Side effects:\n    !      - File <filename> is opened for reading\n    !      - The file stream pointer for <filename>, contained within structure <fd>,\n    !        is positioned at the beginning of the file.\n    !\n    character(len=*), intent(in)  :: filename\n    integer(kind=8),  intent(out) :: fd\n    integer,          intent(out) :: ierr\n\n    logical :: lexist\n\n    ierr = 0\n\n    ! First check the existence of the file.\n    inquire(file=trim(filename), exist=lexist)\n    if (.not. lexist) then\n       ierr = 2\n       return\n    endif\n\n    call c_gribopen(trim(filename)//char(0), fd, ierr)\n\n  end subroutine gribopen\n\n!=================================================================================\n!=================================================================================\n\n  subroutine gribclose(fd)\n    implicit none\n    integer(kind=8), intent(in) :: fd\n    call c_close(fd)\n  end subroutine gribclose\n\n!=================================================================================\n!=================================================================================\n\n  subroutine getgrib(fd, grib, ierr)\n    implicit none\n    !\n    ! Purpose:\n    !      Read a single grib record, but do no unpacking and no interpretation\n    !      of header information beyond the size and edition nuber from GRIB \n    !      section zero.\n    !\n    integer(kind=8), intent(in)      :: fd\n    type (GribStruct), intent(inout) :: grib\n    integer, intent(out)             :: ierr\n\n    integer :: extra\n    integer :: iloc\n    integer :: iread\n    integer :: seventest\n\n    logical, save                 :: grib1_tables_read = .FALSE.\n    logical, save                 :: grib2_tables_read = .FALSE.\n\n    !\n    ! Position our file pointer at the beginning of the next GRIB record.\n    !\n\n    call findgrib(fd, grib, iloc)\n    if (iloc < 0) then\n       ierr = 1\n       return\n    endif\n\n    ! Read the full grib record.\n    call io_fread(fd, grib%buffer(17:), grib%size-16, iread, ierr)\n    if (iread /= grib%size-16) then\n       iloc = -7\n       return\n    endif\n    if (ierr /= 0) then\n       iloc = -8\n       return\n    endif\n\n    grib%iskip = 0\n\n    extra = 4 - mod(grib%size,4)\n    call swap4f(grib%buffer, grib%size+extra)\n\n    !\n    !  Check the last four bytes\n    !\n    call gbyte(grib%buffer, seventest, (grib%size-4)*8, 32)\n    if (seventest /= string_sevens) then\n       write(*,'(\"Cannot find marker (7777) for end of GRIB record\")')\n       stop \"Problem finding end of GRIB record\"\n    endif\n\n    ! Read grib tables.\n    if (grib%edition == 1) then\n       if (.not. grib1_tables_read) then\n          call grib1_read_parameter_tables()\n          grib1_tables_read = .TRUE.\n       endif\n    else\n       if (.not. grib2_tables_read) then\n          call grib2_read_parameter_tables()\n          grib2_tables_read = .TRUE.\n       endif\n    endif\n\n  end subroutine getgrib\n\n!=================================================================================\n!=================================================================================\n\n  subroutine findgrib(fd, grib, iloc)\n    implicit none\n    ! Purpose:\n    !      Seek in an open GRIB file for the string \"GRIB\", which\n    !      indicates the beginning of a GRIB record.\n    ! Input:\n    !      fd: A file stream pointer to a file opened by subroutine GRIBOPEN\n    !\n    ! Output:\n    !      iloc:  The location (by byte count) in the file stream <fd>\n    !             at the beginning of this particular GRIB record.  Or,\n    !             a negative number indicating a read problem (probably we \n    !             hit the end of the file.\n    !\n    ! Side Effects:\n    !      Position the c file pointer at the beginning of the grib record.\n\n    integer(kind=8), intent(in) :: fd\n    type (GribStruct) :: grib\n    integer, intent(out) :: iloc\n\n    integer :: ierr\n    integer :: iread\n    integer :: itell\n    character(len=4) :: h4\n    character(len=1), dimension(12) :: buf12\n    integer :: extra\n    integer :: i\n\n    call io_fread(fd, h4, 4, iread, ierr)\n\n    if (iread /= 4) then\n       ! Probably, we've hit the end of file without finding a GRIB record\n       iloc = -1\n       return\n    endif\n\n    if (ierr /= 0) then\n       ! Probably, we've hit the end of file without finding a GRIB record\n       iloc = -2\n       return\n    endif\n\n    do while ( h4 /= \"GRIB\")\n       ! Adjust our buffer and read one more byte\n       h4(1:3) = h4(2:4)\n       call io_fread(fd, h4(4:4), 1, iread, ierr)\n       if (iread /= 1) then\n          iloc = -3;\n          return\n       endif\n       if (ierr /= 0) then\n          iloc = -4;\n          return\n       endif\n    enddo\n\n    !\n    !   To have got this far, we must have found the beginning of a GRIB\n    !   record.\n    !\n\n    !\n    ! Read the next 12 bytes to determine GRIB record size\n    !\n\n    call io_fread(fd, buf12, 12, iread, ierr)\n    if (iread /= 12) then\n       iloc = -5\n       return\n    endif\n    if (ierr /= 0) then\n       iloc = -6\n       return\n    endif\n\n    call swap4f(buf12, 12)\n\n    ! Get the grib edition number.\n    call gbyte(buf12, grib%edition, 24, 8)\n    if (grib%edition == 2) then\n       call gbyte(buf12, grib%size, 64, 32)\n    else if (grib%edition == 1) then\n       call gbyte(buf12, grib%size, 0, 24)\n    else\n       write(*, '(\"Grib Edition:  \", I10)') grib%edition\n       stop \"Grib Edition.\"\n    endif\n    ! write(*, '(\"Grib Edition:  \", I10, \"  Record size:  \", I10)') grib%edition, grib%size\n\n    !\n    ! Allocate space for the full grib record.  The \"extra\" space allocated\n    ! insures that we have a multiple of four bytes in our buffer, so the \n    ! byte-swapping will work correctly without out-of-bounds array references.\n    !\n\n    extra = 4 - mod(grib%size,4)\n    allocate(grib%buffer(grib%size + extra), stat=ierr)\n    if (ierr /= 0) then\n       write(*,'(\"Problem allocating buffer for GRIB data in subroutine GETGRIB\")')\n       stop\n    endif\n    do i = 1, 4\n       grib%buffer(i) = h4(i:i)\n    enddo\n    call swap4f(grib%buffer, 4)\n\n    do i = 1, 12\n       grib%buffer(i+4) = buf12(i)\n    enddo\n\n    ! Swap the bytes here, to make things consistent when we read the rest of the buffer.\n    call swap4f(grib%buffer, 16)\n\n    !\n    !  Position the file stream pointer to the beginning of the GRIB record.\n    !\n    ! call io_fseek(fd, -16, 0);\n\n    !\n    ! Find the stream pointer position\n    !\n\n    call io_ftell(fd, itell)\n\n    !\n    !  Return the byte position of the beginning of this GRIB record\n    !\n    iloc = itell\n\n\n  end subroutine findgrib\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_next_field(fd, grib, ierr)\n    implicit none\n    !\n    ! Purpose:\n    !      Unpack the next field in a GRIB file.  The field may already be\n    !      available in <grib%buffer>; if not, we read from the file into \n    !      <grib%buffer>.\n    !\n\n    integer(kind=8), intent(in) :: fd\n    type (GribStruct), intent(inout) :: grib\n    integer, intent(out) :: ierr\n    integer :: iloc\n    integer :: isection\n    integer :: test_sevens\n\n    ierr = 0\n\n    FIELD_LOOP : do\n\n       if ( .not. associated (grib%buffer) ) then\n          ! print*, 'Try to read a new record'\n          ! Get the next complete GRIB record (which may contain more than one field,\n          ! which is why we have the complication of the outer do loop here).\n          call getgrib(fd, grib, ierr)\n          if (ierr /= 0) return\n       else\n          ! See if we're at \"7777\"  If so, deallocate things and read a new record.\n          call gbyte(grib%buffer, test_sevens, grib%iskip, 32)\n          if (test_sevens == string_sevens) then\n             call deallogrib(grib)\n             cycle FIELD_LOOP\n          endif\n       endif\n\n       select case (grib%edition)\n       case default\n\n          write(*, '(\"MODULE_GRIB:  GRIB_NEXT_FIELD:  Unrecognized edition = \", I10)') grib%edition\n          stop\n\n       case (1)\n          ! print*, 'Unpacking section 0'\n\n          ! GRIB Edition 1 is a lot simpler, because we do not pack more than one field\n          ! into a GRIB record.  Just process the whole record and be done with it.\n          call grib1_unpack_sec0(grib%buffer, size(grib%buffer), grib%iskip)\n          call grib1_unpack_sec1(grib%buffer, size(grib%buffer), grib%iskip, grib%g1sec1)\n          if (grib%g1sec1%ifgds) call grib1_unpack_sec2(grib%buffer, size(grib%buffer), grib%iskip, grib%g1sec2)\n          if (grib%g1sec1%ifbms) call grib1_unpack_sec3(grib)\n          call grib1_unpack_sec4(grib%buffer, size(grib%buffer), grib%iskip, grib%g1sec4)\n          ! call grib1_unpack_sec5(grib%buffer, size(grib%buffer), grib%iskip)\n          ! We have unpacked a GRIB record's data field.  Time to return.\n          return\n\n       case (2)\n\n          call unpack_next_grib2_section(isection, grib)\n\n          do while ( isection < 7 )\n             call unpack_next_grib2_section(isection, grib)\n          enddo\n\n          if (isection == 7) then\n             ! We have unpacked a GRIB record's data field.  Time to return.\n             return\n          else if (isection == 8) then\n             call deallogrib(grib)\n          endif\n       end select\n\n    enddo FIELD_LOOP\n\n  end subroutine grib_next_field\n\n!=================================================================================\n!=================================================================================\n\n  subroutine gribdata(grib)\n    ! Unpack the field and put in into the <grib->array> memory.\n    implicit none\n    type (GribStruct), intent(inout) :: grib\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"MODULE_GRIB:  GRIBDATA:  Unrecognized grib%edition\", I10)') grib%edition\n       stop\n    case (1)\n       call grib1_gribdata(grib)\n    case (2)\n       call grib2_gribdata(grib)\n    end select\n\n  end subroutine gribdata\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_parameter_text_information(grib, name, units, description)\n    implicit none\n    type (GribStruct) :: grib\n    character(len=64) :: name\n    character(len=256) :: units\n    character(len=256) :: description\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"MODULE_GRIB:  GRIB_PARAMETER_TEXT_INFORMATION:  Unrecognized grib%edition\", I10)') grib%edition\n       stop\n    case (1)\n       call grib1_parameter_text_information(grib%g1sec1, name, units, description)\n    case (2)\n       call grib2_parameter_text_information(grib, name, units, description)\n    end select\n  end subroutine grib_parameter_text_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_level_information(grib, level_type, level_units, level_value, level2_value)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=256), intent(out) :: level_type\n    character(len=256), intent(out) :: level_units\n    real,               intent(out) :: level_value\n    real,               intent(out) :: level2_value\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"MODULE_GRIB:  GRIB_LEVEL_INFORMATION:  Unrecognized grib%edition\", I10)') grib%edition\n       stop\n    case (1)\n       call grib1_level_information(grib, level_type, level_units, level_value, level2_value)\n    case (2)\n       call grib2_level_information(grib, level_type, level_units, level_value, level2_value)\n    end select\n\n  end subroutine grib_level_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=19), intent(out)  :: reference_date\n    character(len=19), intent(out)  :: valid_date\n    character(len=256), intent(out) :: process\n    character(len=256), intent(out) :: processing\n    integer,            intent(out) :: p1_seconds\n    integer,            intent(out) :: p2_seconds\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"MODULE_GRIB:  GRIB_TIME_INFORMATION:  Unrecognized grib%edition\", I10)') grib%edition\n       stop\n    case (1)\n       call grib1_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    case (2)\n       call grib2_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    end select\n\n  end subroutine grib_time_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_valid_date(grib, validdate)\n    ! Hmmmm.  This could also be a subfunction of unpacking\n    ! GRIB2 section 4 (GRIB1 Section 1), and making <validdate>\n    ! an element of <grib> at the top level\n    implicit none\n    type (GribStruct), intent(in)  :: grib\n    character(len=19), intent(out) :: validdate\n    !\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"MODULE_GRIB:  GRIB_VALID_DATE:  Unrecognized grib%edition\", I10)') grib%edition\n       stop\n    case (1)\n       call grib1_valid_date(grib%g1sec1, validdate)\n    case (2)\n       call grib2_valid_date(grib, validdate)\n    end select\n  end subroutine grib_valid_date\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_map_information(grib)\n    implicit none\n    type(GribStruct), intent(inout) :: grib\n    select case (grib%edition)\n    case default\n       write(*,'(\"MODULE_GRIB:  GRIB_MAP_INFORMATION:  Unrecognized grib%edition\", I10)') grib%edition\n       stop\n    case (1)\n       call grib1_map_information(grib%g1sec2, grib%mapinfo)\n    case (2)\n       call grib2_map_information(grib)\n    end select\n\n  end subroutine grib_map_information\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_grib1.F",
    "content": "module module_grib1\n  use module_mapinfo\n  use kwm_date_utilities\n  use module_grib_common\n  implicit none\n\n  type grib1_parameter_table_entry\n     character(len=256) :: name\n     character(len=64)  :: units\n     character(len=16)  :: abbr\n  end type grib1_parameter_table_entry\n  type(grib1_parameter_table_entry), dimension(1:255) :: grib1_parameter_table\n\n\n\n\ncontains\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_parameter_text_information(sec1, name, units, description)\n    implicit none\n    ! Need to read tables and get information from stored table data\n    type (G1Section1Struct), intent(in)  :: sec1\n    character(len=64),       intent(out) :: name\n    character(len=64),       intent(out) :: units\n    character(len=64),       intent(out) :: description\n\n    name = trim(grib1_parameter_table(sec1%parameter)%abbr)\n    units = trim(grib1_parameter_table(sec1%parameter)%units)\n    description = trim(grib1_parameter_table(sec1%parameter)%name)\n\n  end subroutine grib1_parameter_text_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=19), intent(out)  :: reference_date\n    character(len=19), intent(out)  :: valid_date\n    character(len=256), intent(out) :: process\n    character(len=256), intent(out) :: processing\n    integer,            intent(out) :: p1_seconds\n    integer,            intent(out) :: p2_seconds\n\n    reference_date = grib%g1sec1%hdate\n\n    call grib1_valid_date(grib%g1sec1, valid_date)\n\n    select case (grib%g1sec1%tri) ! Time Range Indicator\n    case default\n       write(process,'(\"MODULE_GRIB1:  GRIB1_TIME_INFORMATION:  Unrecognized GRIB1 Time Range Indicator \", I10)') grib%g1sec1%tri\n       write(processing,'(\"MODULE_GRIB1:  GRIB1_TIME_INFORMATION:  Unrecognized GRIB1 Time Range Indicator \", I10)') grib%g1sec1%tri\n       print*, trim(process)\n       stop\n    case (0)\n       process = \"Forecast product\"\n       processing = \"Forecast product\"\n    case (1,10)\n       process = \"Analysis product\"\n       processing = \"Analysis product\"\n    case (3)\n       process = \"Average product\"\n       processing = \"Average product\"\n    case (4)\n       process = \"Accumulation\"\n       processing = \"Accumulation\"\n    end select\n\n    select case (grib%g1sec1%ftu) ! Forecast Time Units\n    case default\n       write(*,'(\"Unrecognized GRIB1 forecast time units:  \",I10)') grib%g1sec1%ftu\n       stop\n    case (0) ! Minute\n       p1_seconds = grib%g1sec1%p1 * 60\n       p2_seconds = grib%g1sec1%p2 * 60\n    case (1) ! Hour\n       p1_seconds = grib%g1sec1%p1 * 3600\n       p2_seconds = grib%g1sec1%p2 * 3600\n    end select\n\n  end subroutine grib1_time_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_level_information(grib, level_type, level_units, level_value, level2_value)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=256), intent(out) :: level_type\n    character(len=256), intent(out) :: level_units\n    real,               intent(out) :: level_value\n    real,               intent(out) :: level2_value\n\n    level_value = -1.E36\n    level2_value = -1.E36\n    level_units = \" \"\n    select case (grib%g1sec1%leveltyp)\n    case default\n       write(level_type, '(\"Unrecognized level type:  \", I10)') grib%g1sec1%leveltyp\n    case (1)\n       level_type = \"Ground or water surface\"\n    case (2)\n       level_type = \"Cloud base level\"\n    case (3)\n       level_type = \"Cloud top level\"\n    case (4)\n       level_type = \"Level of 0{o} C isotherm\"\n    case (5)\n       level_type = \"Level of adiabatic condensation lifted from surface\"\n    case (6)\n       level_type = \"Maximum wind level\"\n    case (7)\n       level_type = \"Tropopause\"\n    case (8)\n       level_type = \"Nominal top of atmosphere\"\n    case (9)\n       level_type = \"Sea Bottom\"\n    case (20)\n       level_type = \"Isothermal level\"\n       level_units = \"K\"\n       level_value = grib%g1sec1%levelval\n    case (100)\n       level_type = \"Isobaric level\"\n       level_units = \"Pa\"\n       level_value = grib%g1sec1%levelval\n    case (101)\n       level_type = \"Layer between two isobaric levels\"\n       level_units = \"kPa\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (102)\n       level_type = \"Mean Sea Level\"\n       level_units = \"MSL\"\n    case (103)\n       level_type = \"Specified altitude above MSL\"\n       level_units = \"m\"\n       level_value = grib%g1sec1%levelval\n    case (104)\n       level_type = \"Layer between two specified altitudes above MSL\"\n       level_units = \"hm\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (105)\n       level_type = \"Specified height level above ground\"\n       level_units = \"m\"\n       level_value = grib%g1sec1%levelval\n    case (106)\n       level_type = \"Layer between two specified height levels above ground\"\n       level_units = \"hm\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (107)\n       level_type = \"Sigma level\"\n       level_units = \"Sigma value\"\n       level_value = grib%g1sec1%levelval\n    case (108)\n       level_type = \"Layer between two sigma levels\"\n       level_units = \"Sigma value\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (109)\n       level_type = \"Hybrid level\"\n       level_units = \"Level number\"\n       level_value = grib%g1sec1%levelval\n    case (110)\n       level_type = \"Layer between two hybrid levels\"\n       level_units = \"Level number\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (111)\n       level_type = \"Depth below land surface\"\n       level_units = \"m\" ! Original data has cm, we convert to m\n       level_value = grib%g1sec1%levelval * 1.E-2 ! Converted to m\n    case (112)\n       level_type = \"Layer between two depths below land surface\"\n       level_units = \"m\"! Original data has cm, we convert to m\n       level_value = grib%g1sec1%levelval * 1.E-2   ! Converted to m\n       level2_value = grib%g1sec1%level2val * 1.E-2 ! Converted to m\n    case (113)\n       level_type = \"Isentropic level\"\n       level_units = \"K\"\n       level_value = grib%g1sec1%levelval\n    case (114)\n       level_type = \"Layer between two isentropic levels\"\n       level_units = \"K\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (115)\n       level_type = \"Level at specified pressure difference from ground\"\n       level_units = \"hPa\"\n       level_value = grib%g1sec1%levelval\n    case (116)\n       level_type = \"Layer between two levels at specified pressure differences from ground\"\n       level_units = \"hPa\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (117)\n       level_type = \"PV Surface\"\n       level_units = \"10{-6} K m{2} kg{-1} s{-1}\"\n       level_value = grib%g1sec1%levelval\n    case (119)\n       level_type = \"Eta level\"\n       level_units = \"Eta Value\"\n       level_value = grib%g1sec1%levelval\n    case (120)\n       level_type = \"Layer between two Eta levels\"\n       level_units = \"Eta Value\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (200)\n       level_type = \"Entire atmosphere as a single column\"\n    case (204)\n       level_type = \"Highest tropospheric freezing level\"\n    case (209)\n       level_type = \"Boundary-layer cloud bottom level\"\n    case (210)\n       level_type = \"Boundary-layer cloud top level\"\n    case (211)\n       level_type = \"Boundary-layer cloud layer\"\n    case (212)\n       level_type = \"Low cloud bottom level\"\n    case (213)\n       level_type = \"Low cloud top level\"\n    case (214)\n       level_type = \"Low cloud layer\"\n    case (222)\n       level_type = \"Middle cloud bottom level\"\n    case (223)\n       level_type = \"Middle cloud top level\"\n    case (224)\n       level_type = \"Middle cloud layer\"\n    case (232)\n       level_type = \"High cloud bottom level\"\n    case (233)\n       level_type = \"High cloud top level\"\n    case (234)\n       level_type = \"High cloud layer\"\n    case (242)\n       level_type = \"Convective cloud bottom level\"\n    case (243)\n       level_type = \"Convective cloud top level\"\n    case (244)\n       level_type = \"Convective cloud layer\"\n    end select\n\n  end subroutine grib1_level_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec0(buffer, buffsize, iskip)\n    implicit none\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n    iskip = iskip + 8*8\n  end subroutine grib1_unpack_sec0\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec1(buffer, buffsize, iskip, sec1)\n    implicit none\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n    type (G1Section1Struct),               intent(out)   :: sec1\n\n    integer :: yy\n    integer :: century\n    integer :: gdsbms\n\n    sec1%isize      = unpack_unsigned_integer(buffer, 3, iskip)\n    sec1%ptvn       = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%center     = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%process    = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%grid       = unpack_unsigned_integer(buffer, 1, iskip)\n    gdsbms          = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%parameter  = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%leveltyp   = unpack_unsigned_integer(buffer, 1, iskip)\n    select case (sec1%leveltyp)\n    case default\n       sec1%levelval   = unpack_unsigned_integer(buffer, 2, iskip)\n       sec1%level2val  = -1.E36\n    case (107)\n       sec1%levelval   = 1.E-5 * unpack_unsigned_integer(buffer, 2, iskip) ! Sigma value conversion\n       sec1%level2val  = -1.E36\n    case (20)\n       sec1%levelval   = 1.E-2 * unpack_unsigned_integer(buffer, 2, iskip)\n       sec1%level2val  = -1.E36\n    case (108)\n       sec1%levelval   = 1.E-2 * unpack_unsigned_integer(buffer, 1, iskip)\n       sec1%level2val  = 1.E-2 * unpack_unsigned_integer(buffer, 1, iskip)\n    case (119)\n       sec1%levelval   = 1.E-5 * unpack_unsigned_integer(buffer, 2, iskip) ! Eta value conversion\n       sec1%level2val  = -1.E36\n    case (120)\n       sec1%levelval   = 1.E-2 * unpack_unsigned_integer(buffer, 1, iskip) ! Eta value conversion\n       sec1%level2val  = 1.E-2 * unpack_unsigned_integer(buffer, 1, iskip) ! Eta value conversion\n    case (101,102:104,106,110,112,114,116,121,128,141)\n       sec1%levelval   = unpack_unsigned_integer(buffer, 1, iskip)\n       sec1%level2val  = unpack_unsigned_integer(buffer, 1, iskip)\n    end select\n    yy              = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%month      = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%day        = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%hour       = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%minute     = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%ftu        = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%p1         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%p2         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%tri        = unpack_unsigned_integer(buffer, 1, iskip)\n    if ( sec1%tri == 10 ) then\n       ! The P1 value extends over two bytes.  P2 is not in the header.\n       sec1%p1 = ( sec1%p1 * 256 ) + sec1%p2\n       sec1%p2 = 0\n    endif\n    sec1%navg       = unpack_unsigned_integer(buffer, 2, iskip)\n    sec1%nmissavg   = unpack_unsigned_integer(buffer, 1, iskip)\n    century         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%subcenter  = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%decimal_scale_factor  = unpack_signed_integer(buffer, 2, iskip)\n\n    select case (gdsbms)\n    case default\n       write(*,'(\"GRIB1_UNPACK_SEC1:  GRIB1 Section 1:  Unrecognized GDS/BMS flag: \", I10)') gdsbms\n       stop\n    case (0)\n       sec1%ifgds = .FALSE.\n       sec1%ifbms = .FALSE.\n    case (64)\n       sec1%ifgds = .FALSE.\n       sec1%ifbms = .TRUE.\n    case (128)\n       sec1%ifgds = .TRUE.\n       sec1%ifbms = .FALSE.\n    case (192)\n       sec1%ifgds = .TRUE.\n       sec1%ifbms = .TRUE.\n    end select\n\n    if ( yy > 0 ) then\n       sec1%year       = (century-1) * 100 + yy\n    else\n       sec1%year       = century * 100\n    endif\n\n    write(sec1%hdate, '(I4.4,\"-\",I2.2,\"-\",I2.2,\"_\",I2.2,\":\",I2.2,\":\",I2.2)') &\n         sec1%year, sec1%month, sec1%day, sec1%hour, sec1%minute, 00\n\n  end subroutine grib1_unpack_sec1\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec2(buffer, buffsize, iskip, sec2)\n    implicit none\n\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n    type (G1Section2Struct),               intent(inout) :: sec2\n    integer :: idum\n\n    sec2%isize      = unpack_unsigned_integer(buffer, 3, iskip)\n    sec2%nv         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec2%pv         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec2%drt        = unpack_unsigned_integer(buffer, 1, iskip)\n\n    select case (sec2%drt)\n    case (0) ! Lat/Lon grid\n\n       sec2%nx = unpack_unsigned_integer(buffer, 2, iskip)\n       sec2%ny = unpack_unsigned_integer(buffer, 2, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lat1 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lon1 = real(idum)*1.E-3\n       sec2%rac = unpack_unsigned_integer(buffer, 1, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lat2 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lon2 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 2, iskip)\n       sec2%dx = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 2, iskip)\n       sec2%dy = real(idum)*1.E-3\n       sec2%scanning_mode = unpack_unsigned_integer(buffer, 1, iskip)\n\n       if ( btest(sec2%scanning_mode, 7) ) then\n          sec2%i_scan_direction = -1\n       else\n          sec2%i_scan_direction = 1\n       endif\n\n       if ( btest(sec2%scanning_mode, 6) ) then\n          sec2%j_scan_direction = 1\n       else\n          sec2%j_scan_direction = -1\n       endif\n\n       if ( btest(sec2%scanning_mode, 5) ) then\n          sec2%orientation = -1\n       else\n          sec2%orientation = 1\n       endif\n\n       ! Skip those last four bytes:\n       iskip = iskip + (4*8)\n\n       sec2%latin1 = -1.E36\n       sec2%latin2 = -1.E36\n\n    case (3) ! Lambert Conformal grid\n\n       sec2%nx = unpack_unsigned_integer(buffer, 2, iskip)\n       sec2%ny = unpack_unsigned_integer(buffer, 2, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lat1 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lon1 = real(idum)*1.E-3\n       sec2%rac = unpack_unsigned_integer(buffer, 1, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lov = real(idum)*1.E-3\n       idum = unpack_unsigned_integer(buffer, 3, iskip)\n       sec2%dx = real(idum)*1.E-3\n       idum = unpack_unsigned_integer(buffer, 3, iskip)\n       sec2%dy = real(idum)*1.E-3\n       sec2%center = unpack_unsigned_integer(buffer, 1, iskip)\n       sec2%scanning_mode = unpack_unsigned_integer(buffer, 1, iskip)\n\n       if ( btest(sec2%scanning_mode, 7) ) then\n          sec2%i_scan_direction = -1\n       else\n          sec2%i_scan_direction = 1\n       endif\n\n       if ( btest(sec2%scanning_mode, 6) ) then\n          sec2%j_scan_direction = 1\n       else\n          sec2%j_scan_direction = -1\n       endif\n\n       if ( btest(sec2%scanning_mode, 5) ) then\n          sec2%orientation = -1\n       else\n          sec2%orientation = 1\n       endif\n\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%latin1 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%latin2 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%polelat = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%polelon = real(idum)*1.E-3\n       ! Skip those last two bytes:\n       iskip = iskip + 16\n       ! print*, 'nx, ny = ', sec2%nx, sec2%ny\n       ! print*, 'lat1, lon1 = ', sec2%lat1, sec2%lon1\n       ! print*, 'lov, truelat1, truelat2 = ', sec2%lov, sec2%latin1, sec2%latin2\n       ! print*, 'dx, dy = ', sec2%dx, sec2%dy\n\n    case (5) ! Polar Stereographic grid\n\n       sec2%nx = unpack_unsigned_integer(buffer, 2, iskip)\n       sec2%ny = unpack_unsigned_integer(buffer, 2, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lat1 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lon1 = real(idum)*1.E-3\n       sec2%rac = unpack_unsigned_integer(buffer, 1, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lov = real(idum)*1.E-3\n       idum = unpack_unsigned_integer(buffer, 3, iskip)\n       sec2%dx = real(idum) * 1.E-3\n       idum = unpack_unsigned_integer(buffer, 3, iskip)\n       sec2%dy = real(idum) * 1.E-3\n       sec2%center = unpack_unsigned_integer(buffer, 1, iskip)\n       sec2%scanning_mode = unpack_unsigned_integer(buffer, 1, iskip)\n\n       if ( btest(sec2%scanning_mode, 7) ) then\n          sec2%i_scan_direction = -1\n       else\n          sec2%i_scan_direction = 1\n       endif\n\n       if ( btest(sec2%scanning_mode, 6) ) then\n          sec2%j_scan_direction = 1\n       else\n          sec2%j_scan_direction = -1\n       endif\n\n       if ( btest(sec2%scanning_mode, 5) ) then\n          sec2%orientation = -1\n       else\n          sec2%orientation = 1\n       endif\n\n       if (sec2%center==0) then\n          sec2%latin1 = 60.0\n       else\n          sec2%latin1 = -60.0\n       endif\n       sec2%latin2 = -1.E36\n       ! Skip those last four bytes:\n       iskip = iskip + (4*8)\n       ! print*, 'nx, ny = ', sec2%nx, sec2%ny\n       ! print*, 'lat1, lon1 = ', sec2%lat1, sec2%lon1\n       ! print*, 'lov, truelat1, truelat2 = ', sec2%lov, sec2%latin1, sec2%latin2\n       ! print*, 'dx, dy = ', sec2%dx, sec2%dy\n\n    case default\n\n       write(*,'(\"GRIB1_UNPACK_SEC2:  Unrecognized GRIB1 grid type (drt):  \", I10)') sec2%drt\n       stop\n\n    end select\n\n  end subroutine grib1_unpack_sec2\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec3(grib)\n    ! Bit Map Section (bitmap section)\n    implicit none\n    type (GribStruct),                     intent(inout) :: grib\n\n    integer :: bitmap_beginning\n    integer :: bitmap_length\n    integer :: idim, jdim\n\n    grib%g1sec3%isize      = unpack_unsigned_integer(grib%buffer, 3, grib%iskip)\n    grib%g1sec3%nunused    = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%g1sec3%numeric    = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n\n    grib%g1sec3%bitmap_beginning = grib%iskip/8\n    bitmap_length    = grib%g1sec3%isize-6\n\n    ! I may need to reorient the bitmap, too, depending on data ordering....\n    idim = grib%g1sec2%nx\n    jdim = grib%g1sec2%ny\n    allocate(grib%bitmap(idim,jdim))\n    call gbytes(grib%buffer, grib%bitmap, grib%g1sec3%bitmap_beginning*8, 1, 0, idim*jdim)\n\n    ! And skip to the end of the section\n    grib%iskip = grib%iskip + (bitmap_length*8)\n\n  end subroutine grib1_unpack_sec3\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec4(buffer, buffsize, iskip, sec4)\n    implicit none\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n    type (G1Section4Struct),               intent(out)   :: sec4\n\n    integer :: n\n    real    :: xref2\n    integer :: isign, characteristic, mantissa\n\n    sec4%isize      = unpack_unsigned_integer(buffer, 3, iskip)\n\n    do n = 1, 4\n       call gbyte(buffer, sec4%flag(n), iskip, 1)\n       iskip = iskip + 1\n    enddo\n    call gbyte(buffer, sec4%nunused, iskip, 4)\n    iskip = iskip + 4\n\n    sec4%binary_scale_factor  = unpack_signed_integer(buffer, 2, iskip)\n\n    ! Unpack the floating-point number\n    call gbyte(buffer, isign, iskip, 1)\n    iskip = iskip + 1\n    call gbyte(buffer, characteristic, iskip, 7)\n    iskip = iskip + 7\n    call gbyte(buffer, mantissa, iskip, 24)\n    iskip = iskip + 24\n    ! print*, 'isign = ', isign\n    ! print*, 'characteristic = ', characteristic\n    ! print*, 'mantissa = ', mantissa\n    xref2 = real(dble(mantissa) / dble(2**24) * dble(16 ** (characteristic-64)))\n    if (isign==1) xref2 = -xref2\n    ! print*, 'Reference value = ', xref2\n    sec4%reference_value = xref2\n    sec4%nbits = unpack_unsigned_integer(buffer, 1, iskip)\n\n    sec4%start_of_packed_data = iskip/8\n\n    ! Skip to the end of this section\n    iskip = iskip + (sec4%isize-11)*8\n\n  end subroutine grib1_unpack_sec4\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec5(buffer, buffsize, iskip)\n    implicit none\n    ! Real simple.  Just check for the \"7777\" flag which marks the end of the\n    ! GRIB1 record.\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n\n    integer :: test_sevens\n\n    test_sevens = unpack_unsigned_integer(buffer, 4, iskip)\n    if (test_sevens /= string_sevens) then\n       write(*, '(\" MODULE_GRIB1:  GRIB1_UNPACK_SEC5:  Problem:  Lost the way in GRIB1 record.\")')\n       stop\n    endif\n\n  end subroutine grib1_unpack_sec5\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_gribdata(grib)\n    implicit none\n    type (GribStruct)                     :: grib\n    ! real, pointer, dimension(:,:) :: array\n\n    if (grib%g1sec4%flag(1)==0) then\n       ! Grid-point data\n       if (grib%g1sec4%flag(2) == 0) then\n          ! Simple packing\n          if (grib%g1sec4%flag(3)==0) then\n             ! Original field held floating-point values\n             if (grib%g1sec4%flag(4)==0) then\n                ! No additional flags in octet 14\n                allocate(grib%array(grib%mapinfo%nx,grib%mapinfo%ny))\n                if (grib%g1sec1%ifbms) then\n                   call grib1_sgup_bitmap(grib, grib%array, grib%bitmap, grib%mapinfo%nx, grib%mapinfo%ny)\n                else\n                   call grib1_sgup_nobitmap(grib, grib%array, grib%mapinfo%nx, grib%mapinfo%ny)\n                endif\n             else\n                stop \"GRIB1:  Section 4:  Additional flags in octed 14\"\n             endif\n          else\n             stop \"GRIB1:  Section 4:  Original field held integer values.\"\n          endif\n       else\n          stop \"GRIB1:  Section 4:  Complex packing\"\n       endif\n    else\n       stop \"GRIB1:  Section 4:  Spherical Harmonic coefficients\"\n    endif\n\n  end subroutine grib1_gribdata\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_map_information(sec2, mapinfo)\n    implicit none\n    type(G1Section2Struct), intent(in) :: sec2\n    type(MapInfoStruct), intent(out)   :: mapinfo\n    select case (sec2%drt)\n    case default\n       write(*, '(\"Unrecognized GRIB1 grid data representation type:  \", I12)') sec2%drt\n       stop \"GRIB1_MAP_INFORMATION:  Unrecognized grid data representation type.\"\n    case (0) ! Cylindrical Equidistant\n       mapinfo%hproj = \"CE\"\n       mapinfo%supmap_jproj = 8\n       mapinfo%nx   = sec2%nx\n       mapinfo%ny   = sec2%ny\n       mapinfo%dx   = sec2%dx\n       mapinfo%dy   = sec2%dy\n       mapinfo%lat1 = sec2%lat1\n       mapinfo%lon1 = sec2%lon1\n       mapinfo%lat2 = sec2%lat2\n       mapinfo%lon2 = sec2%lon2\n       mapinfo%xlonc    = -1.E33\n       mapinfo%truelat1 = -1.E33\n       mapinfo%truelat2 = -1.E33\n    case (3) ! Lambert Conformal\n       mapinfo%hproj = \"LC\"\n       mapinfo%supmap_jproj = 3\n       mapinfo%nx   = sec2%nx\n       mapinfo%ny   = sec2%ny\n       mapinfo%dx   = sec2%dx\n       mapinfo%dy   = sec2%dy\n       mapinfo%lat1 = sec2%lat1\n       mapinfo%lon1 = sec2%lon1\n       mapinfo%lat2 = -1.E36\n       mapinfo%lon2 = -1.E36\n       mapinfo%xlonc = sec2%lov\n       mapinfo%truelat1 = sec2%latin1\n       mapinfo%truelat2 = sec2%latin2\n    case (5) ! Polar Stereographic\n       mapinfo%hproj = \"ST\"\n       mapinfo%supmap_jproj = 1\n       mapinfo%nx   = sec2%nx\n       mapinfo%ny   = sec2%ny\n       mapinfo%dx   = sec2%dx\n       mapinfo%dy   = sec2%dy\n       mapinfo%lat1 = sec2%lat1\n       mapinfo%lon1 = sec2%lon1\n       mapinfo%lat2 = -1.E36\n       mapinfo%lon2 = -1.E36\n       mapinfo%xlonc = sec2%lov\n       mapinfo%truelat1 = sec2%latin1\n       mapinfo%truelat2 = sec2%latin2\n    end select\n  end subroutine grib1_map_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine GRIB1_SGUP_NOBITMAP(grib, array, idim, jdim)\n    ! GRIB 1 Data unpacking:  Simple grid-point unpacking without a bitmap\n    implicit none\n    type (GribStruct) :: grib\n    integer, intent(in) :: idim, jdim\n    real, dimension(idim*jdim), intent(out) :: array\n\n    integer, dimension(idim*jdim) :: IX\n    double precision :: dfac, bfac\n    integer :: iskip\n\n    integer :: i, j, m, n\n\n    DFAC = 1.0 / (10.D0**(grib%g1sec1%decimal_scale_factor))\n    BFAC = 2.D0**(grib%g1sec4%binary_scale_factor)\n\n! sec4%nbits is the number of bits used per datum.\n! If sec4%nbits = 255, assume they mean sec4%nbits = 0\n\n    if (grib%g1sec4%nbits == 255) grib%g1sec4%nbits = 0\n\n    if (grib%g1sec4%nbits > 0) then\n       call gbytes(grib%buffer, IX, grib%g1sec4%start_of_packed_data*8, grib%g1sec4%nbits, 0, idim*jdim)\n    endif\n\n! If sec4(8) is 0, assume datarray is constant, scaled from the value of sec4%reference_value\n\n    if (grib%g1sec4%nbits == 0) then\n       array = DFAC * grib%g1sec4%reference_value\n    else\n       ! Check point order!!!\n\n       if (grib%g1sec2%orientation == 1) then\n          ! We're good.  Fortran(i,j)\n       elseif (grib%g1sec2%orientation == -1) then\n          write(*,'(\"grib%g1sec2%orientation = \", I12)') grib%g1sec2%orientation\n          stop \"TODO:  GRIB1_SGUP_NOBITMAP:  grib%g1sec2%orientation = -1\"\n       else\n          write(*,'(\"grib%g1sec2%orientation = \", I12)') grib%g1sec2%orientation\n          stop \"TODO:  GRIB1_SGUP_NOBITMAP:  Problem recognizing grib%g1sec2%orientation\"\n       endif\n\n       if (grib%g1sec2%i_scan_direction == 1) then\n          ! We're good.\n       elseif (grib%g1sec2%i_scan_direction == -1) then\n          write(*,'(\"grib%g1sec2%i_scan_direction = \", I12)') grib%g1sec2%i_scan_direction\n          stop \"TODO:  GRIB1_SGUP_NOBITMAP:  grib%g1sec2%i_scan_direction = -1\"\n       else\n          write(*,'(\"grib%g1sec2%i_scan_direction = \", I12)') grib%g1sec2%i_scan_direction\n          stop \"GRIB1_SGUP_NOBITMAP:   Problem recognizing grib%g1sec2%i_scan_direction\"\n       endif\n\n       if (grib%g1sec2%j_scan_direction == 1) then\n          array = DFAC * (dble(grib%g1sec4%reference_value) + (dble(IX)*BFAC))\n       elseif (grib%g1sec2%j_scan_direction == -1) then\n          do j = 1, jdim\n             do i = 1, idim\n                n = (j-1)*idim + i\n                m = (jdim-j)*idim + i\n                array(n) = DFAC * (dble(grib%g1sec4%reference_value) + (dble(IX(m))*BFAC))\n             enddo\n          enddo\n       else\n          write(*,'(\"grib%g1sec2%j_scan_direction = \", I12)') grib%g1sec2%j_scan_direction\n          stop \"GRIB1_SGUP_NOBITMAP:  Problem recognizing grib%g1sec2%j_scan_direction\"\n       endif\n    endif\n\n  end subroutine GRIB1_SGUP_NOBITMAP\n\n!=================================================================================\n!=================================================================================\n\n  subroutine GRIB1_SGUP_BITMAP(grib, array, bitmap, nx, ny)\n    ! Simple grid-point unpacking, with a bitmap.\n    implicit none\n    type (GribStruct)      :: grib\n    integer, intent(in) :: nx, ny\n    real, dimension(nx*ny), intent(out) :: array\n    integer, dimension(nx*ny), intent(in) :: bitmap\n\n    type(G1Section1Struct), pointer :: sec1\n    type(G1Section3Struct), pointer :: sec3\n    type(G1Section4Struct), pointer :: sec4\n\n    integer :: ndat ! Number of data points in the final grid.\n    double precision :: dfac, bfac\n    integer :: iskip, nbm, i, nn\n\n    integer, allocatable, dimension(:) :: bmdat\n\n    array = -1.E30\n\n    ndat = nx * ny\n\n!\n! Compute the parameters involved with packing\n!\n    DFAC = 1.0 / 10.**(grib%g1sec1%decimal_scale_factor)\n    BFAC = 2.**grib%g1sec4%binary_scale_factor\n\n! grib%g1sec4%isize   : The number of bytes in the whole of GRIB Grib%g1section 4.\n! grib%g1sec4%nunused : The number of unused bits at the end of GRIB Section 4.\n! GRIB%G1SEC4%nbits : The number of bits per data value.\n\n\n! 1) There are fewer than NDAT data values, because a bitmap was used.\n!    Compute the number of data values (NBM).  There are 11 extra bytes\n!    in the header section 4.  NBM equals the total number of data bits (not\n!    counting the header bits), minus the number of unused buts, and then\n!    divided by the number of bits per data value.\n\n! If grib%g1sec4%nbits is 0, assume <array> is constant value of DFAC * grib%g1sec4%reference_value\n\n    if (grib%g1sec4%nbits.eq.0) then\n       where(bitmap(1:ndat)==1) array = DFAC * grib%g1sec4%reference_value\n       return\n    endif\n    nbm = ((grib%g1sec4%isize-11)*8-grib%g1sec4%nunused)/grib%g1sec4%nbits\n    allocate(bmdat(nbm))\n    if (nbm /= count(bitmap==1)) then\n       print*, \"NBM, count(bitmap==1):  \", nbm, count(bitmap==1)\n       write(*,'(\"GRIB1_SGUP_BITMAP:  Problem with the number of data values in the bitmap.\")')\n       stop\n    endif\n\n! grib%g1sec4%nbits is the number of bits used per datum value.\n! If grib%g1sec4%nbits = 255, assume they mean grib%g1sec4%nbits = 0\n    if (grib%g1sec4%nbits == 255) grib%g1sec4%nbits = 0\n\n! Read the data from the <buffer> array\n    call gbytes(grib%buffer, bmdat, grib%g1sec4%start_of_packed_data*8, grib%g1sec4%nbits, 0, nbm)\n\n    if (grib%g1sec2%orientation == 1) then\n       ! We're good.  Fortran(i,j)\n    elseif (grib%g1sec2%orientation == -1) then\n       write(*,'(\"grib%g1sec2%orientation = \", I12)') grib%g1sec2%orientation\n       stop \"TODO:  GRIB1_SGUP_BITMAP:  grib%g1sec2%orientation = -1\"\n    else\n       write(*,'(\"grib%g1sec2%orientation = \", I12)') grib%g1sec2%orientation\n       stop \"TODO:  GRIB1_SGUP_BITMAP:  Problem recognizing grib%g1sec2%orientation\"\n    endif\n\n! Check the i scan direction:\n    if (grib%g1sec2%i_scan_direction == 1) then\n       ! We're good.\n    elseif (grib%g1sec2%i_scan_direction == -1) then\n       write(*,'(\"grib%g1sec2%i_scan_direction = \", I12)') grib%g1sec2%i_scan_direction\n       stop \"TODO:  GRIB1_SGUP_BITMAP:  grib%g1sec2%i_scan_direction = -1\"\n    else\n       write(*,'(\"grib%g1sec2%i_scan_direction = \", I12)') grib%g1sec2%i_scan_direction\n       stop \"GRIB1_SGUP_BITMAP:  Problem recognizing grib%g1sec2%i_scan_direction\"\n    endif\n\n! Check the j scan direction:\n    if (grib%g1sec2%j_scan_direction == 1) then\n       ! We're good.\n    elseif (grib%g1sec2%j_scan_direction == -1) then\n       write(*,'(\"grib%g1sec2%j_scan_direction = \", I12)') grib%g1sec2%j_scan_direction\n       stop \"TODO:  GRIB1_SGUP_BITMAP:  grib%g1sec2%j_scan_direction = -1\"\n    else\n       write(*,'(\"grib%g1sec2%j_scan_direction = \", I12)') grib%g1sec2%j_scan_direction\n       stop \"GRIB1_SGUP_BITMAP:  Problem recognizing grib%g1sec2%j_scan_direction\"\n    endif\n\n\n\n! Unpack the data according to packing parameters DFAC, BFAC, and XEC4(1),\n! and masked by the bitmap BITMAP.\n    nn = 0\n    do i = 1, ndat\n       if (bitmap(i)==1) then\n          nn = nn + 1\n          array(i) = DFAC * (dble(grib%g1sec4%reference_value) + (dble(bmdat(nn))*BFAC))\n       endif\n    enddo\n\n! Deallocate the scratch BMDAT array\n    deallocate(bmdat)\n  end subroutine GRIB1_SGUP_BITMAP\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_valid_date(sec1, validdate)\n    implicit none\n    type(G1Section1Struct), intent(in) :: sec1\n    character(len=19), intent(out) :: validdate\n\n    character(len=19) :: refdate\n    integer :: tfac\n\n    refdate = sec1%hdate\n\n    ! Find TFAC, which is a factor to convert the given time offset\n    ! to seconds.\n    select case (sec1%ftu)\n    case (0)\n       tfac = 60\n    case (1)\n       tfac = 3600\n    case (2)\n       tfac = 86400\n    case (10)\n       tfac = 10800\n    case (11)\n       tfac = 21600\n    case (12)\n       tfac = 43200\n    case (254)\n       tfac = 1\n    case default\n       write(*, '(\"Unrecognized GRIB1 Forecast Time Unit: \", I6)') sec1%ftu\n       stop\n    end select\n\n    select case (sec1%tri) ! \"Time Range Indicator\"\n    case default\n       write(*, '(\"Unrecognized GRIB1 Time Range Indicator: \", I6)') sec1%tri\n       stop\n    case (3) ! Average\n       ! Average from (reference_time + p1) to (reference time + p2)\n       call geth_newdate(validdate, refdate, tfac*(sec1%p1+sec1%p2)/2)\n    case(4) ! Accumulation from refdate + P1 to refdate + P2,\n       ! valid at refdate + P2\n       ! call geth_newdate(fdate,     refdate, tfac*sec1(17))\n       call geth_newdate(validdate, refdate, tfac*sec1%p2)\n!       if (present(offset)) then\n!          offset = tfac*(sec1%p2-sec1%p1)\n!       endif\n    case(5) ! Difference, valid at refdate + P2\n       call geth_newdate(validdate, refdate, tfac*sec1%p2)\n    case (0:1,10) ! Product valid at refdate + P1\n       call geth_newdate(validdate, refdate, tfac*sec1%p1)\n    end select\n\n  end subroutine grib1_valid_date\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_read_parameter_tables\n    implicit none\n    character(len=256) :: grib_root\n    character(len=256) :: table_filename\n    integer :: iunit\n    integer :: ierr\n    integer :: p1\n    integer :: p2\n    integer :: p3\n    integer, external :: get_unused_unit\n\n    character(len=200) :: string\n    character(len=256) :: parameter_name\n    character(len=64)  :: parameter_units\n    character(len=8)   :: parameter_abbr\n    integer            :: parameter_index\n\n    call getenv(\"GRIB_ROOT\", grib_root)\n    if (trim(grib_root)==\" \") then\n       write(*,'(\"Not finding environment variable GRIB_ROOT.\")')\n       write(*,'(\"Program does not know where to find GRIB parameter tables\")')\n       stop\n    endif\n    table_filename = trim(grib_root)//\"/GRIB1_PARAMETER_TABLE\"\n\n    iunit = get_unused_unit()\n\n    open(iunit, file=trim(table_filename), status='old', form='formatted', action='read', iostat=ierr)\n    if (ierr /= 0) then\n       write(*,'(/,\" ***** ERROR *****\",/)')\n       write(*,'(\" ***** Problem opening file ''\", A, \"''\")') trim(table_filename)\n       write(*,'(\" ***** Does file exist?  Is file readable?\",/)')\n       stop\n    endif\n\n    READ_TABLE : do\n       read(iunit, '(A200)', iostat=ierr) string\n       if (ierr /= 0) exit READ_TABLE\n       if (string(1:1) == \"#\") cycle READ_TABLE\n\n       p1 = index(string, \"|\") - 1\n       p2 = p1 + index(string(p1+2:), \"|\")\n       p3 = p2 + index(string(p2+2:), \"|\")\n       read(string(1:p1),*) parameter_index\n       parameter_name = trim(adjustl(string(p1+2:p2)))\n       parameter_units = trim(adjustl(string(p2+2:p3)))\n       parameter_abbr = trim(adjustl(string(p3+2:)))\n       ! write(*, '(I3,1x,\"#\",A,\"#\",1x,\"#\",A,\"#\",1x,\"#\",A,\"#\")') parameter_index, trim(parameter_name), trim(parameter_units), trim(parameter_abbr)\n       grib1_parameter_table(parameter_index)%name  = trim(parameter_name)\n       grib1_parameter_table(parameter_index)%units = trim(parameter_units)\n       grib1_parameter_table(parameter_index)%abbr  = trim(parameter_abbr)\n\n    enddo READ_TABLE\n    close(iunit)\n  end subroutine grib1_read_parameter_tables\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib1\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_grib2.F",
    "content": "module module_grib2\n  use module_mapinfo\n  use module_grib2_tables\n  use kwm_date_utilities\n  use module_grib_common\n  implicit none\n\ncontains\n\n!==============================================================================\n!==============================================================================\n  subroutine grib2_gribdata(grib)\n    implicit none\n    type (GribStruct), intent(inout) :: grib\n    ! Reorient data as necessary to put grib%array(1,1) at the lower left corner\n  end subroutine grib2_gribdata\n\n!==============================================================================\n!==============================================================================\n\n  subroutine grib2_valid_date(grib, validdate)\n    ! Hmmmm.  This could also be a subfunction of unpacking\n    ! GRIB2 section 4, and making <validdate> an element of <grib>\n    implicit none\n    type (GribStruct), intent(in)  :: grib\n    character(len=19), intent(out) :: validdate\n    !\n    !Local:\n    character(len=19) :: refdate\n    integer :: fcst_time\n    integer :: time_factor\n\n    refdate = grib%sec1%hdate\n\n    select case (grib%sec1%srt) ! Check the \"significance of reference time\"\n    case default\n       write(*,'(\"Unrecognized ''Significance of Reference Time'' (GRIB2, section 1, octet 12):  \", I10)') grib%sec1%srt\n       stop\n\n    case (0:1)  ! <grib%sec1%hdate> refers to the analysis time(0) or forecast start time (1)\n\n       select case (grib%sec4%product_template_number) ! Check the product template number\n       case default\n          write(*,'(\"Unrecognized Product Definition Template: \", I8)') grib%sec4%product_template_number\n       case (0) ! Analysis or forecast at a point in time\n          fcst_time = grib%sec4%time\n          select case (grib%sec4%time_range_indicator) ! Check the units on the time\n          case default\n             write(*,'(\"Unrecognized time range indicator: \", I8)') grib%sec4%time_range_indicator\n             stop\n          case (0) ! Time in minutes\n             time_factor = 60\n             call geth_newdate(validdate(1:19), refdate(1:19), fcst_time*time_factor)\n          case (1) ! Time in hours\n             time_factor = 3600\n             call geth_newdate(validdate(1:19), refdate(1:19), fcst_time*time_factor)\n          end select\n       end select\n!       case (2)  ! <grib%sec1%hdate> refers to the forecast valid time\n    end select\n  end subroutine grib2_valid_date\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_map_information(grib)\n    implicit none\n    type(GribStruct), intent(inout) :: grib\n\n    select case (grib%sec3%grid_template_number)\n    case default\n       write(*, '(\"Unrecognized GRIB 2 grid template number:  \", I12)') grib%sec3%grid_template_number\n       stop \"GRIB2_MAP_INFORMATION:  Unrecognized grid template number.\"\n    case (0)\n       call print_sec3(grib, 10000)\n       grib%mapinfo%hproj = \"CE\"\n       grib%mapinfo%supmap_jproj = 8\n       grib%mapinfo%nx = grib%sec3%nx\n       grib%mapinfo%ny = grib%sec3%ny\n       grib%mapinfo%dx = grib%sec3%gt_3_0%dx\n       grib%mapinfo%dy = grib%sec3%gt_3_0%dy\n       grib%mapinfo%lat1 = grib%sec3%GT_3_0%la1\n       grib%mapinfo%lon1 = grib%sec3%GT_3_0%lo1\n       grib%mapinfo%xlonc = -1.E33\n       grib%mapinfo%truelat1 = -1.E33\n       grib%mapinfo%truelat1 = -1.E33\n    case (30)\n       grib%mapinfo%hproj = \"LC\"\n       grib%mapinfo%supmap_jproj = 3\n       grib%mapinfo%nx = grib%sec3%nx\n       grib%mapinfo%ny = grib%sec3%ny\n       grib%mapinfo%dx = grib%sec3%GT_3_30%dx\n       grib%mapinfo%dy = grib%sec3%GT_3_30%dy\n       grib%mapinfo%lat1 = grib%sec3%GT_3_30%la1\n       grib%mapinfo%lon1 = grib%sec3%GT_3_30%lo1\n       grib%mapinfo%xlonc = grib%sec3%GT_3_30%lov\n       grib%mapinfo%truelat1 = grib%sec3%GT_3_30%latin1\n       grib%mapinfo%truelat2 = grib%sec3%GT_3_30%latin2\n    end select\n  end subroutine grib2_map_information\n\n\n!=================================================================================\n!=================================================================================\n\n  subroutine fortran_decode_jpeg2000(buffer, buffer_length, decoded)\n    implicit none\n    !\n    ! Purpose:\n    !      Take a character array <buffer> which contains a JPEG2000-encoded field,\n    !      and return the decoded field as an integer array.  This subroutine is \n    !      simply a wrapper for the c code that decodes jpeg2000 streams.\n    !\n    ! Input:\n    !      buffer:        Character buffer which holds the JPEG2000-encoded field.\n    !      buffer_length: Size of character array <buffer>.\n    !\n    ! Output\n    !      decoded:       Pointer to an integer array representing the decoded field.\n    !\n    ! Side Effects:\n    !      Any?  Probably some in the subroutines called from this routine.\n    !\n    integer,                                    intent(in) :: buffer_length\n    character(len=1), dimension(buffer_length), intent(in) :: buffer\n    integer, pointer, dimension(:)                         :: decoded\n\n    ! Local:\n    integer         :: width\n    integer         :: height\n    integer(kind=8) :: image_pointer\n    integer(kind=8) :: stream_pointer\n    integer         :: allocation_status\n\n    call info_jpeg2000(buffer, buffer_length, width, height, image_pointer, stream_pointer)\n\n    allocate(decoded(width*height), stat=allocation_status)\n    if (allocation_status /= 0) then\n       write(*,'(\"Problem allocating space in FORTRAN_DECODE_JPEG2000.\")')\n       stop \"MODULE_GRIB2\"\n    endif\n\n    call decode_jpeg2000(image_pointer, stream_pointer, width, height, decoded)\n\n  end subroutine fortran_decode_jpeg2000\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_parameter_text_information(grib, abbr, units, description)\n    implicit none\n    ! This could really be considered a substep of unpacking section 4.  Let's \n    ! move it there sometime, and create grib%abbr, grib%units, grib%description!\n    type (GribStruct), intent(in)  :: grib\n    character(len=16), intent(out) :: abbr\n    character(len=256), intent(out) :: units\n    character(len=256), intent(out) :: description\n    character(len=256) :: category_name\n\n    call get_parameter_table_information(grib%discipline, &\n         grib%sec4%parameter_category, grib%sec4%parameter_number, &\n         category_name, description, units)\n    abbr = \"ABBR\"\n\n  end subroutine grib2_parameter_text_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    implicit none\n    type (GribStruct), intent(in)   :: grib\n    character(len=19), intent(out)  :: reference_date\n    character(len=19)  :: valid_date\n    character(len=256) :: process\n    character(len=256) :: processing\n    integer, intent(out)            :: p1_seconds\n    integer, intent(out)            :: p2_seconds\n\n    character(len=256) :: text3\n\n    reference_date = grib%sec1%hdate\n\n    select case (grib%sec1%srt)\n    case default\n       write(process,'(\"Unrecognized significance of reference time\")')\n       write(*,'(A)') trim(process)\n    case (0)\n       write(process,'(\"Analysis time:   \", A, 1x, A)') grib%sec1%hdate(1:10), grib%sec1%hdate(12:19)\n    case (1)\n       write(process,'(\"Start of forecast:   \", A, 1x, A)') grib%sec1%hdate(1:10), grib%sec1%hdate(12:19)\n    case (2)\n       write(process,'(\"Verifying time of forecast:   \", A, 1x, A)') grib%sec1%hdate(1:10), grib%sec1%hdate(12:19)\n    case (3)\n       write(process,'(\"Observation time:  \", A, 1x, A)') grib%sec1%hdate(1:10), grib%sec1%hdate(12:19)\n    end select\n\n    processing = \" \"\n    text3 = \" \"\n    select case (grib%sec4%product_template_number)\n    case default\n       write(processing,'(\"Unrecognized Product Definition Template: \", I8)') grib%sec4%product_template_number\n    case (0)\n       select case (grib%sec4%time_range_indicator)\n       case default\n          write(processing,'(\"Unrecognized time range indicator:\", I8)') grib%sec4%time_range_indicator\n          valid_date = \"0000-00-00_00:00:00\"\n          p1_seconds = 0\n          p2_seconds = 0\n       case (0)\n          write(processing,'(\"Forecast time:  \",I8,\" minutes\")') grib%sec4%time\n          p1_seconds = grib%sec4%time*60\n          p2_seconds = 0\n          call geth_newdate(valid_date, grib%sec1%hdate, p1_seconds)\n          write(text3, '(\"Forecast valid time:  \", A, 1x, A)') valid_date(1:10), valid_date(12:19)\n       case (1)\n          write(processing,'(\"Forecast time:  \",I8,\" hours\")') grib%sec4%time\n          p1_seconds = grib%sec4%time*3600\n          p2_seconds = 0\n          call geth_newdate(valid_date, grib%sec1%hdate, p1_seconds)\n          write(text3, '(\"Forecast valid time:  \", A, 1x, A)') valid_date(1:10), valid_date(12:19)\n       case (2)\n          write(processing,'(\"Forecast time:  \",I8,\" days\")') grib%sec4%time\n          p1_seconds = grib%sec4%time*86400\n          p2_seconds = 0\n          call geth_newdate(valid_date, grib%sec1%hdate, p1_seconds)\n          write(text3, '(\"Forecast valid time:  \", A, 1x, A)') valid_date(1:10), valid_date(12:19)\n       case (13)\n          write(processing,'(\"Forecast time:  \",I8,\" seconds\")') grib%sec4%time\n          p1_seconds = grib%sec4%time\n          p2_seconds = 0\n          call geth_newdate(valid_date, grib%sec1%hdate, grib%sec4%time)\n          write(text3, '(\"Forecast valid time:  \", A, 1x, A)') valid_date(1:10), valid_date(12:19)\n\n       end select\n    case (8)\n       select case (grib%sec4%PDT_4_8%statistical_process)\n       case default\n          write(processing, '(\"Unrecognized statistical process: \",I4)') grib%sec4%PDT_4_8%statistical_process\n       case (0)\n          write(processing, '(\"Average over \", I6, 1x, A)') &\n               grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n          write(text3, '(\"from \", A, \" to \", A)') &\n               grib%sec4%PDT_4_8%begin_hdate, grib%sec4%PDT_4_8%end_hdate\n          processing = trim(processing)//\" \"//trim(text3)\n       case (1)\n          write(processing, '(\"Accumulation over \", I6, 1x, A)') &\n               grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n          write(text3, '(\"from \", A, \" to \", A)') &\n               grib%sec4%PDT_4_8%begin_hdate, grib%sec4%PDT_4_8%end_hdate\n          processing = trim(processing)//\" \"//trim(text3)\n          valid_date = grib%sec4%PDT_4_8%end_hdate\n\n          select case (grib%sec4%time_range_indicator)\n          case default\n             write(processing,'(\"Unrecognized time range indicator for accumulation:\", I8)') grib%sec4%time_range_indicator\n             stop\n          case (0)\n             p1_seconds = grib%sec4%time*60\n          case (1)\n             p1_seconds = grib%sec4%time*3600\n          case (2)\n             p1_seconds = grib%sec4%time*86400\n          case (13)\n             p1_seconds = grib%sec4%time\n          end select\n\n          select case (grib%sec4%PDT_4_8%time_range_unit)\n          case default\n             write(processing,'(\"Unrecognized time range unit for accumulation:\", I8)') grib%sec4%PDT_4_8%time_range_unit\n             stop\n          case (0)\n             p2_seconds = p1_seconds + (grib%sec4%PDT_4_8%length_of_time_range) * 60\n          case (1)\n             p2_seconds = p1_seconds + (grib%sec4%PDT_4_8%length_of_time_range) * 3600\n          case (2)\n             p2_seconds = p1_seconds + (grib%sec4%PDT_4_8%length_of_time_range) * 86400\n          case (13)\n             p1_seconds = p1_seconds + (grib%sec4%PDT_4_8%length_of_time_range)\n          end select\n\n       case (2)\n          write(processing, '(\"Maximum in \", I6, 1x, A)') &\n               grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n       case (3)\n          write(processing, '(\"Minimum in \", I6, 1x, A)') &\n               grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n       case (4)\n          write(processing, '(\"Difference over \", I6, 1x, A)') &\n              grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n       end select\n    end select\n  end subroutine grib2_time_information\n\n!=================================================================================\n!=================================================================================\n\n#ifdef _DEAD_\n  subroutine get_grib_bitmap(grib, bitmap)\n    implicit none\n    type (GribStruct), intent(in) :: grib\n    integer, pointer, dimension(:,:) :: bitmap\n\n    if (grib%sec6%bit_map_indicator /= 255) then\n       bitmap => grib%sec6%bitmap\n    else\n       nullify(bitmap)\n    endif\n\n  end subroutine get_grib_bitmap\n#endif\n!=================================================================================\n!=================================================================================\n\n  subroutine get_grib_dimensions(grib, idim, jdim)\n    ! Probably not needed, since we define a mapinfo structure.\n    implicit none\n    type (GribStruct), intent(in)  :: grib\n    integer,           intent(out) :: idim\n    integer,           intent(out) :: jdim\n    idim = grib%sec3%nx\n    jdim = grib%sec3%ny\n  end subroutine get_grib_dimensions\n\n!=================================================================================\n!=================================================================================\n\n  subroutine get_grib_data_array(grib, array)\n    implicit none\n    type (GribStruct), intent(in) :: grib\n    real, pointer, dimension(:,:) :: array\n    array => grib%array\n  end subroutine get_grib_data_array\n\n\n!=================================================================================\n!=================================================================================\n\n  subroutine deallogrib(grib)\n    type (GribStruct) :: grib\n    if (associated(grib%buffer)) then\n       deallocate(grib%buffer)\n       nullify(grib%buffer)\n    endif\n    if (associated(grib%bitmap)) then\n       deallocate(grib%bitmap)\n       nullify(grib%bitmap)\n    endif\n    if (associated(grib%array)) then\n       deallocate(grib%array)\n       nullify(grib%array)\n    endif\n    if (associated(grib%sec7%floated)) then\n       deallocate(grib%sec7%floated)\n       nullify(grib%sec7%floated)\n    endif\n    grib%size = 0\n  end subroutine deallogrib\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_level_information(grib, level_type, level_units, level_value, level2_value)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=256), intent(out) :: level_type\n    character(len=256), intent(out) :: level_units\n    real,               intent(out) :: level_value\n    real,               intent(out) :: level2_value\n\n    level2_value = -1.E36\n    select case (grib%sec4%product_template_number)\n    case default\n       write(*,'(\"MODULE_GRIB2:  GRIB2_LEVEL_INFORMATION:  Unrecognized product_template_number: \", I4)') &\n            grib%sec4%product_template_number\n       stop \"Problem\"\n    case (0)\n       call get_level_string(grib%sec4%ltype1, level_type, level_units)\n       level_value  = grib%sec4%level1\n       if (grib%sec4%ltype2 /= 255) then\n          level2_value = grib%sec4%level2\n       endif\n    case (8)\n       call get_level_string(grib%sec4%ltype1, level_type, level_units)\n       level_value  = grib%sec4%level1\n       if (grib%sec4%ltype2 /= 255) then\n          level2_value = grib%sec4%level2\n       endif\n    end select\n\n    ! write(*,'(\"MODULE_GRIB2:  GRIB2_LEVEL_INFORMATION:  To do.\")')\n    ! stop\n  end subroutine grib2_level_information\n\n!=================================================================================\n!=================================================================================\n\n\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_next_grib2_section(isection, grib)\n\n    !  Returns the section number of the section just unpacked\n    implicit none\n    integer, intent(out) :: isection\n    type(GribStruct), intent(inout) :: grib\n    integer :: iread\n    character(len=4) :: hh\n    integer :: isize\n    integer :: ierr\n    integer :: n\n    integer :: edition\n    integer :: gribsizeA, gribsizeB\n    integer(kind=8) :: gribsize\n    character(len=1), dimension(12) :: buf\n\n    ! Take four bytes:\n\n    isize = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n\n    if (isize == string_grib) then\n       grib%iskip = grib%iskip + 16\n       isection = 0\n       grib%discipline = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       edition    = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       gribsizeA  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       gribsizeB  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       if (gribsizeA /= 0) then\n          stop \"UNPACK_NEXT_GRIB2_SECTION:  Large size.  Despair!\"\n       endif\n       gribsize = gribsizeB\n       return\n    else if (isize == string_sevens) then\n       isection = 8\n       return\n    else\n       isection = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       select case (isection)\n       case (1)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec1(grib);\n          ! call print_sec1(grib, 10000);\n       case (3)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec3(grib);\n          ! call print_sec3(grib, 10000);\n       case (4)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec4(grib);\n          ! call print_sec4(grib);\n       case (5)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec5(grib);\n          ! call print_sec5(grib);\n       case (6)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec6(grib);\n          ! call print_sec6(grib,10000);\n       case (7)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec7(grib);\n          ! call print_sec7(grib);\n       case default\n          write(*,'(\"Section?  \", I10)') isection\n          stop \"Section?\"\n       end select\n    endif\n\n  end subroutine unpack_next_grib2_section\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec1(grib)\n    implicit none\n    type (GribStruct), intent(inout) :: grib\n\n    character(len=8) :: hdate\n    integer :: section\n\n    grib%sec1%size              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section                     = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%center            = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    grib%sec1%subcenter         = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    grib%sec1%mtvn              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%ltvn              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)  \n    grib%sec1%srt               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%year              = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    grib%sec1%month             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%day               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%hour              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%minute            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%second            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%production_status = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%data_type         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)  \n\n    write(grib%sec1%hdate, '(I4.4,\"-\",I2.2,\"-\",I2.2,\"_\",I2.2,\":\",I2.2,\":\",I2.2)') &\n         grib%sec1%year, grib%sec1%month, grib%sec1%day, grib%sec1%hour, grib%sec1%minute, grib%sec1%second\n\n  end subroutine unpack_sec1\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec1(grib, verbosity)\n    implicit none\n    type(GribStruct), intent(in)  :: grib\n    integer,          intent(in)  :: verbosity\n\n    if (verbosity >= 10) then\n       write(*,'(\"Section 1:\")')\n       if (verbosity >= 100) then\n          write(*,'(\"   Length of section:               \",I4)') grib%sec1%size\n          write(*,'(\"   Originating Center:              \",I4)') grib%sec1%center\n          write(*,'(\"   Originating Subcenter:           \",I4)') grib%sec1%subcenter\n          write(*,'(\"   Master Tables Version Number:    \",I4)') grib%sec1%mtvn\n          write(*,'(\"   Local Tables Version Number:     \",I4)') grib%sec1%ltvn\n          write(*,'(\"   Significance of Reference Time:  \",I4,\":  \")', advance=\"no\") grib%sec1%srt\n\n          select case (grib%sec1%srt)\n          case default\n             write( *, '(\"Unrecognized significance of reference time\")' )\n          case (0)\n             write(*,'(\"analysis time.  \", A, 1x, A)')\n          case (1)\n             write(*,'(\"forecast start time.  \", A, 1x, A)')\n          case (2)\n             write(*,'(\"verifying time of forecast.  \", A, 1x, A)')\n          case (3)\n             write(*,'(\"observation time.  \", A, 1x, A)')\n          end select\n\n          if (verbosity >= 500) then\n             write(*,'(\"   Year (Reference Time):           \",I4)') grib%sec1%year\n             write(*,'(\"   Month (Reference Time):          \",I4)') grib%sec1%month\n             write(*,'(\"   Day (Reference Time):            \",I4)') grib%sec1%day\n             write(*,'(\"   Hour (Reference Time):           \",I4)') grib%sec1%hour\n             write(*,'(\"   Minute (Reference Time):         \",I4)') grib%sec1%minute\n             write(*,'(\"   Second (Reference Time):         \",I4)') grib%sec1%second\n          endif\n          write(*,'(\"   Reference Time:                  \",A)') grib%sec1%hdate\n          write(*,'(\"   Production Status:               \",I4)') grib%sec1%production_status\n          write(*,'(\"   Data Type:                       \",I4)') grib%sec1%data_type\n       endif\n\n       !\n       ! Data Type\n       !\n\n       select case (grib%sec1%data_type)\n       case (0)\n          write(*,'(\"  Analysis products\")')\n       case (1)\n          write(*,'(\"  Forecast products\")')\n       case (2)\n          write(*,'(\"  Analysis and Forecast products\")')\n       case (3)\n          write(*,'(\"  Control Forecast products\")')\n       case (4)\n          write(*,'(\"  Perturbed Forecast products\")')\n       case (5)\n          write(*,'(\"  Control and Perturbed Forecast products\")')\n       case (6)\n          write(*,'(\"  Processed satellite observations\")')\n       case (7)\n          write(*,'(\"  Processed radar observations\")')\n       case (8:191)\n          write(*,'(\"   Data Type:                       \",I4)') grib%sec1%data_type\n       case (192:254)\n          write(*,'(\"   Data Type:                       \",I4)') grib%sec1%data_type\n       case (255)\n          write(*,'(\"   Data Type:                       \",I4)') grib%sec1%data_type\n       end select\n\n       !\n       ! Significance of Reference Time\n       !\n       select case (grib%sec1%srt)\n       case (0)\n          write(*,'(\"  Analysis at time \",A)') grib%sec1%hdate\n       case (1)\n          write(*,'(\"  Forecast initialized at time \",A)') grib%sec1%hdate\n       case (2)\n          write(*,'(\"  Forecast verifying at time \",A)') grib%sec1%hdate\n       case (3)\n          write(*,'(\"  Observation time \",A)') grib%sec1%hdate\n       case (4:191)\n          write(*,'(\"  Reference time \",A)') grib%sec1%hdate\n       case (192:254)\n          write(*,'(\"  Reference time \",A)') grib%sec1%hdate\n       case (255)\n          write(*,'(\"  Reference time \",A)') grib%sec1%hdate\n       end select\n\n    endif\n\n  end subroutine print_sec1\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec3(grib)\n    implicit none\n    type(GribStruct), intent(inout), target :: grib\n\n    integer :: section\n    type (Section3Struct), pointer :: sec3\n    type (GT_3_0_Struct),  pointer :: GT_3_0\n    type (GT_3_30_Struct), pointer :: GT_3_30\n\n    integer :: i\n\n    ! Temporary integers to hold\n    integer :: ila1\n    integer :: ilo1\n    integer :: ila2\n    integer :: ilo2\n    integer :: ilad\n    integer :: ilov\n    integer :: iplat\n    integer :: iplon\n    integer :: ilatin1\n    integer :: ilatin2\n    integer :: idi\n    integer :: idj\n\n    sec3 => grib%sec3\n\n    sec3%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n\n    if (section /= 3) then\n       write(*,'(\"Section 3:  We are lost!  \",I4)') section\n       stop \"Problem\"\n    endif\n\n    sec3%grid_definition_source   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    sec3%number_of_data_points    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    sec3%octets_for_optional_list = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    sec3%list_interpretation      = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    sec3%grid_template_number     = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n\n    select case (sec3%grid_template_number)\n    case (0)\n\n       ! Cylindrical Equidistant Grid\n\n       GT_3_0 => sec3%GT_3_0\n\n       Sec3%shape_of_earth                   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_0%scale_factor_of_radius         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_0%scaled_value_of_radius         = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%scale_factor_major_axis        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_0%scaled_value_major_axis        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%scale_factor_minor_axis        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_0%scaled_value_minor_axis        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec3%nx                               = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec3%ny                               = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%basic_angle                    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%subdivisions_of_basic_angle    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       ila1                                  = unpack_signed_integer  (grib%buffer, 4, grib%iskip)\n       ilo1                                  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%resolution_and_component_flags = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       ila2                                  = unpack_signed_integer  (grib%buffer, 4, grib%iskip)\n       ilo2                                  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       idi                                   = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       idj                                   = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       GT_3_0%scanning_mode                  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n\n       GT_3_0%la1 = ila1 * 1.E-6\n       GT_3_0%lo1 = ilo1 * 1.E-6\n       GT_3_0%la2 = ila2 * 1.E-6\n       GT_3_0%lo2 = ilo2 * 1.E-6\n       GT_3_0%dx  = idi  * 1.E-6\n       GT_3_0%dy  = idj  * 1.E-6\n\n       ! 0/1:  I direction increments given?\n       if (btest(GT_3_0%resolution_and_component_flags,5)) then\n          GT_3_0%i_direction_increments_given = 1\n       else\n          GT_3_0%i_direction_increments_given = 0\n       endif\n\n       ! 0/1:  J direction increments given?\n       if (btest(GT_3_0%resolution_and_component_flags,4)) then\n          GT_3_0%j_direction_increments_given = 1\n       else\n          GT_3_0%j_direction_increments_given = 0\n       endif\n\n       ! 0/1:  Earth-relative/Grid-relative winds\n       if (btest(GT_3_0%resolution_and_component_flags,3)) then\n          GT_3_0%winds_grid_relative = 1\n       else\n          GT_3_0%winds_grid_relative = 0\n       endif\n\n       if (btest(GT_3_0%scanning_mode,7)) then\n          GT_3_0%i_scan_direction = -1\n       else\n          GT_3_0%i_scan_direction = 1\n       endif\n\n       if (btest(GT_3_0%scanning_mode,6)) then\n          GT_3_0%j_scan_direction = 1\n       else\n          GT_3_0%j_scan_direction = -1\n       endif\n\n       if (btest(GT_3_0%scanning_mode,5)) then\n          GT_3_0%i_scan_consecutive=0\n       else\n          GT_3_0%i_scan_consecutive=1\n       endif\n\n       if (btest(GT_3_0%scanning_mode,4)) then\n          GT_3_0%boustrophedon=1\n       else\n          GT_3_0%boustrophedon=0\n       endif\n\n       nullify(GT_3_0)\n\n    case (30)\n\n       ! Lambert Conformal Grid\n\n       GT_3_30 => sec3%GT_3_30\n\n       sec3%shape_of_earth                    = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scale_factor_of_radius         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scaled_value_of_radius         = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_30%scale_factor_major_axis        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scaled_value_major_axis        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_30%scale_factor_minor_axis        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scaled_value_minor_axis        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec3%nx                                = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec3%ny                                = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       ila1                                   = unpack_signed_integer  (grib%buffer, 4, grib%iskip)\n       ilo1                                   = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       GT_3_30%resolution_and_component_flags = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       ilad                                   = unpack_signed_integer  (grib%buffer, 4, grib%iskip)     \n       ilov                                   = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       idi                                    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       idj                                    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       GT_3_30%projection_center_flag         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scanning_mode                  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       ilatin1                                = unpack_signed_integer  (grib%buffer, 4, grib%iskip)     \n       ilatin2                                = unpack_signed_integer  (grib%buffer, 4, grib%iskip)     \n       iplat                                  = unpack_signed_integer  (grib%buffer, 4, grib%iskip)     \n       iplon                                  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n\n       GT_3_30%la1            = ila1    * 1.E-6\n       GT_3_30%lo1            = ilo1    * 1.E-6\n       GT_3_30%lad            = ilad    * 1.E-6\n       GT_3_30%lov            = ilov    * 1.E-6\n       GT_3_30%dx             = idi     * 1.E-6\n       GT_3_30%dy             = idj     * 1.E-6\n       GT_3_30%latin1         = ilatin1 * 1.E-6\n       GT_3_30%latin2         = ilatin2 * 1.E-6\n       GT_3_30%pole_latitude  = iplat   * 1.E-6\n       GT_3_30%pole_longitude = iplon   * 1.E-6\n\n       ! 0/1:  I direction increments given?\n       if (btest(GT_3_30%resolution_and_component_flags,5)) then\n          GT_3_30%i_direction_increments_given = 1\n       else\n          GT_3_30%i_direction_increments_given = 0\n       endif\n\n       ! 0/1:  J direction increments given?\n       if (btest(GT_3_30%resolution_and_component_flags,4)) then\n          GT_3_30%j_direction_increments_given = 1\n       else\n          GT_3_30%j_direction_increments_given = 0\n       endif\n\n       ! 0/1:  Earth-relative/Grid-relative winds\n       if (btest(GT_3_30%resolution_and_component_flags,3)) then\n          GT_3_30%winds_grid_relative = 1\n       else\n          GT_3_30%winds_grid_relative = 0\n       endif\n\n       if (btest(GT_3_30%scanning_mode,7)) then\n          GT_3_30%i_scan_direction = -1\n       else\n          GT_3_30%i_scan_direction = 1\n       endif\n\n       if (btest(GT_3_30%scanning_mode,6)) then\n          GT_3_30%j_scan_direction = 1\n       else\n          GT_3_30%j_scan_direction = -1\n       endif\n\n       if (btest(GT_3_30%scanning_mode,5)) then\n          GT_3_30%i_scan_consecutive=0\n       else\n          GT_3_30%i_scan_consecutive=1\n       endif\n\n       if (btest(GT_3_30%scanning_mode,4)) then\n          GT_3_30%boustrophedon=1\n       else\n          GT_3_30%boustrophedon=0\n       endif\n\n\n\n       nullify(GT_3_30)\n\n    case default\n       write(*,'(\"Unknown grid_template_number: \",I4)') sec3%grid_template_number\n       stop \"Problem.\"\n    end select\n\n    nullify(sec3)\n\n  end subroutine unpack_sec3\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec3(grib, verbosity)\n    implicit none\n    type(GribStruct), target, intent(in) ::  grib\n    integer,          intent(in) :: verbosity\n\n    type(Section3Struct), pointer :: sec3\n    sec3 => grib%sec3\n    if (verbosity >= 10) then\n       write(*,'(\"Section 3\")')\n       if (verbosity >= 100) then\n          write(*,'(\"   Length of section:               \",I4)') sec3%size\n          write(*,'(\"   Source of Grid Definition:       \",I4)') sec3%grid_definition_source\n          write(*,'(\"   Number of data points:           \",I8)') sec3%number_of_data_points\n          write(*,'(\"   Octets for optional list:        \",I4)') sec3%octets_for_optional_list\n          write(*,'(\"   Interpretation of optional list: \",I4)') sec3%list_interpretation\n          write(*,'(\"   Grid Definition Template Number: \",I4)') sec3%grid_template_number\n          write(*,'(\"        Shape of earth           : \",I4)') sec3%shape_of_earth\n          select case (sec3%shape_of_earth)\n          case (6)\n             write(*,'(\"         Earth assumed spherical with radius of 6371229.0 m\")')\n          case default\n             write(*,'(\"         Unrecognized shape_of_earth:  \", I4)') sec3%shape_of_earth\n          end select\n          select case (sec3%grid_template_number)\n          case (0)\n             write(*,'(\"  Cylindrical Equidistant Grid:\")')\n             write(*,'(\"     Scale factor of radius:    \",I8)') sec3%GT_3_0%scale_factor_of_radius\n             write(*,'(\"     Scaled value of radius:    \",I8)') sec3%GT_3_0%scaled_value_of_radius\n             write(*,'(\"     Scale factor major axis:   \",I8)') sec3%GT_3_0%scale_factor_major_axis\n             write(*,'(\"     Scaled value major axis:   \",I8)') sec3%GT_3_0%scaled_value_major_axis\n             write(*,'(\"     Scale factor minor axis:   \",I8)') sec3%GT_3_0%scale_factor_minor_axis\n             write(*,'(\"     Scaled value minor axis:   \",I8)') sec3%GT_3_0%scaled_value_minor_axis\n             write(*,'(\"     Ni                         \",I8)') sec3%nx\n             write(*,'(\"     Nj                         \",I8)') sec3%ny\n             write(*,'(\"     basic angle:               \",I8)') sec3%GT_3_0%basic_angle\n             write(*,'(\"     subdivisions of angle:     \",I8)') sec3%GT_3_0%subdivisions_of_basic_angle\n             write(*,'(\"     La1:                       \",F10.6)') sec3%GT_3_0%la1\n             write(*,'(\"     Lo1:                       \",F10.6)') sec3%GT_3_0%lo1\n             write(*,'(\"     Resolution/Component flags \",I4, 1x, B8.8)') sec3%GT_3_0%resolution_and_component_flags, &\n                  sec3%GT_3_0%resolution_and_component_flags\n             if (sec3%GT_3_0%i_direction_increments_given == 1) then\n                write(*,'(\"                 I direction increments given\")')\n             else\n                write(*,'(\"                 I direction increments not given\")')\n             endif\n             if (sec3%GT_3_0%j_direction_increments_given == 1) then\n                write(*,'(\"                 J direction increments given\")')\n             else\n                write(*,'(\"                 J direction increments not given\")')\n             endif\n             if (sec3%GT_3_0%winds_grid_relative == 1) then\n                write(*,'(\"                 Horizontal wind components are grid-relative\")')\n             else\n                write(*,'(\"                 Horizontal wind components are earth-relative\")')\n             endif\n             write(*,'(\"     La2:                       \",F10.6)') sec3%GT_3_0%la2\n             write(*,'(\"     Lo2:                       \",F10.6)') sec3%GT_3_0%lo2\n             write(*,'(\"     Dx :                       \",F10.6)') sec3%GT_3_0%dx\n             write(*,'(\"     Dy:                        \",F10.6)') sec3%GT_3_0%dy\n             write(*,'(\"     Scanning Mode:             \",I4, 1x, B8.8)') sec3%GT_3_0%scanning_mode, sec3%GT_3_0%scanning_mode\n             write(*,'(\"             I scan direction   = \", I4)') sec3%GT_3_0%i_scan_direction\n             write(*,'(\"             J scan direction   = \", I4)') sec3%GT_3_0%j_scan_direction\n             write(*,'(\"             I scan consecutive = \", I4)') sec3%GT_3_0%i_scan_consecutive\n             write(*,'(\"             Boustrophedon      = \", I4)') sec3%GT_3_0%boustrophedon\n          case (30)\n             write(*,'(\"  Lambert Conformal Grid: \")')\n             write(*,'(\"     Scale factor of radius:    \",I8)') sec3%GT_3_30%scale_factor_of_radius\n             write(*,'(\"     Scaled value of radius:    \",I8)') sec3%GT_3_30%scaled_value_of_radius\n             write(*,'(\"     Scale factor major axis:   \",I8)') sec3%GT_3_30%scale_factor_major_axis\n             write(*,'(\"     Scaled value major axis:   \",I8)') sec3%GT_3_30%scaled_value_major_axis\n             write(*,'(\"     Scale factor minor axis:   \",I8)') sec3%GT_3_30%scale_factor_minor_axis\n             write(*,'(\"     Scaled value minor axis:   \",I8)') sec3%GT_3_30%scaled_value_minor_axis\n             write(*,'(\"     Ni                         \",I8)') sec3%nx\n             write(*,'(\"     Nj                         \",I8)') sec3%ny\n             write(*,'(\"     La1:                       \",F10.6)') sec3%GT_3_30%la1\n             write(*,'(\"     Lo1:                       \",F10.6)') sec3%GT_3_30%lo1\n             write(*,'(\"     Resolution/Component flags \",I4,\": \", B8.8)') sec3%GT_3_30%resolution_and_component_flags, &\n                  sec3%GT_3_30%resolution_and_component_flags\n             if (sec3%GT_3_30%i_direction_increments_given == 1) then\n                write(*,'(\"                 I direction increments given\")')\n             else\n                write(*,'(\"                 I direction increments not given\")')\n             endif\n             if (sec3%GT_3_30%j_direction_increments_given == 1) then\n                write(*,'(\"                 J direction increments given\")')\n             else\n                write(*,'(\"                 J direction increments not given\")')\n             endif\n             if (sec3%GT_3_30%winds_grid_relative == 1) then\n                write(*,'(\"                 Horizontal wind components are grid-relative\")')\n             else\n                write(*,'(\"                 Horizontal wind components are earth-relative\")')\n             endif\n             write(*,'(\"     Lad:                       \",F10.6)') sec3%GT_3_30%lad\n             write(*,'(\"     Lov:                       \",F10.6)') sec3%GT_3_30%lov\n             write(*,'(\"     Dx :                       \",F10.6)') sec3%GT_3_30%dx\n             write(*,'(\"     Dy:                        \",F10.6)') sec3%GT_3_30%dy\n             write(*,'(\"     Projection Center Flag     \",I8)') sec3%GT_3_30%projection_center_flag\n             write(*,'(\"     Scanning Mode:             \",I8, \": \", B8.8)') sec3%GT_3_30%scanning_mode, sec3%GT_3_30%scanning_mode\n             write(*,'(\"             I scan direction   = \", I8)') sec3%GT_3_30%i_scan_direction\n             write(*,'(\"             J scan direction   = \", I8)') sec3%GT_3_30%j_scan_direction\n             write(*,'(\"             I scan consecutive = \", I8)') sec3%GT_3_30%i_scan_consecutive\n             write(*,'(\"             Boustrophedon      = \", I8)') sec3%GT_3_30%boustrophedon\n             write(*,'(\"     Latin1:                    \",F10.6)') sec3%GT_3_30%latin1\n             write(*,'(\"     Latin2:                    \",F10.6)') sec3%GT_3_30%latin2\n             write(*,'(\"     Southern Pole Latitude:    \",F10.6)') sec3%GT_3_30%pole_latitude\n             write(*,'(\"     Southern Pole Longitude:   \",F10.6)') sec3%GT_3_30%pole_longitude\n          case default\n             write(*,'(\"Unknown grid_template_number: \",I8)') sec3%grid_template_number\n             stop\n          end select\n       endif\n    endif\n\n  end subroutine print_sec3\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec4(grib)\n    implicit none\n    type (GribStruct), target, intent(inout) :: grib\n    integer :: section\n    type (Section4Struct), pointer :: sec4\n!    type (PDT_4_0_Struct), pointer :: PDT_4_0\n    type (PDT_4_8_Struct), pointer :: PDT_4_8\n\n    integer :: time_conversion_to_seconds\n\n    sec4 => grib%sec4\n\n    sec4%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    if (section /= 4) then\n       write(*,'(\"Section 4:  We are lost!  \", I4)') section\n       stop \"Problem\"\n    endif\n\n    sec4%number_of_coord_values  = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    sec4%product_template_number = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n\n    select case (sec4%product_template_number)\n    case (0)\n\n       ! PDT_4_0 => sec4%PDT_4_0\n\n       sec4%parameter_category                   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%parameter_number                     = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%type_of_generating_process        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%background_process_id             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%generating_process_id             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%data_cutoff_hours                 = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n       sec4%data_cutoff_minutes               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%time_range_indicator              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%time                              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec4%ltype1                            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%lscale1                           = unpack_signed_integer(grib%buffer, 1, grib%iskip)\n       sec4%lvalue1                           = unpack_signed_integer(grib%buffer, 4, grib%iskip)\n       sec4%level1                            = real(sec4%lvalue1) / (10.**real(sec4%lscale1))\n       sec4%ltype2                            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%lscale2                           = unpack_signed_integer(grib%buffer, 1, grib%iskip)\n       sec4%lvalue2                           = unpack_signed_integer(grib%buffer, 4, grib%iskip)\n       sec4%level2                            = real(sec4%lvalue2) / (10.**real(sec4%lscale2))\n\n    case (8)\n\n       PDT_4_8 => sec4%PDT_4_8\n\n       sec4%parameter_category                   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%parameter_number                     = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%type_of_generating_process        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%background_process_id             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%generating_process_id             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%data_cutoff_hours                 = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n       sec4%data_cutoff_minutes               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%time_range_indicator              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%time                              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec4%ltype1                            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%lscale1                           = unpack_signed_integer(grib%buffer, 1, grib%iskip)\n       sec4%lvalue1                           = unpack_signed_integer(grib%buffer, 4, grib%iskip)\n       sec4%level1                            = real(sec4%lvalue1) / (10.**real(sec4%lscale1))\n       sec4%ltype2                            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%lscale2                           = unpack_signed_integer(grib%buffer, 1, grib%iskip)\n       sec4%lvalue2                           = unpack_signed_integer(grib%buffer, 4, grib%iskip)\n       sec4%level2                            = real(sec4%lvalue2) / (10.**real(sec4%lscale2))\n       PDT_4_8%end_year                          = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n       PDT_4_8%end_month                         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%end_day                           = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%end_hour                          = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%end_minute                        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%end_second                        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       select case (sec4%time_range_indicator)\n       case default\n          write(*,'(\"sec4%time_range_indicator = \", I4)') sec4%time_range_indicator\n          stop \"time conversion?\"\n       case (0)\n          time_conversion_to_seconds = 60\n       case (1)\n          time_conversion_to_seconds = 3600\n       case (2)\n          time_conversion_to_seconds = 86400\n       case (13)\n          time_conversion_to_seconds = 1\n       end select\n       call geth_newdate(PDT_4_8%begin_hdate, grib%sec1%hdate, sec4%time*time_conversion_to_seconds)\n       write(PDT_4_8%end_hdate, '(I4.4,2(\"-\",I2.2),\"_\",2(I2.2,\":\"),I2.2)') &\n            PDT_4_8%end_year, PDT_4_8%end_month, PDT_4_8%end_day, PDT_4_8%end_hour, PDT_4_8%end_minute, PDT_4_8%end_second\n       PDT_4_8%number_of_time_range_specifications  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%number_missing                       = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       PDT_4_8%statistical_process                  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%type_of_time_increment               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%time_range_unit                      = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%length_of_time_range                 = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       PDT_4_8%time_increment_unit                  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%time_increment                       = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n\n       if (PDT_4_8%number_of_time_range_specifications > 1) then\n          write(*,'(\"Hmmmm.  number of time range specifications = \", I8)') PDT_4_8%number_of_time_range_specifications\n          stop \"Problem\"\n       endif\n\n    case default\n       write(*,'(\"Unrecognized product_template_number: \", I4)') sec4%product_template_number\n       stop \"Problem\"\n    end select\n\n  end subroutine unpack_sec4\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec4(grib)\n    implicit none\n    type (GribStruct), target, intent(in) :: grib\n    type (Section4Struct), pointer :: sec4\n\n    sec4 => grib%sec4\n\n    write(*,'(\"Section 4\")')\n    write(*,'(\"   Length of section:                   \",I8)') sec4%size\n    write(*,'(\"   Number of Coordinate Values:         \",I8)') sec4%number_of_coord_values\n    write(*,'(\"   Product Definition Template Number:  \",I8)') sec4%product_template_number\n    select case (sec4%product_template_number)\n    case (0)\n       write(*,'(\"  PDT 4.0:  Analysis or fcst at a horiz lvl or lyr at a point in time\")')\n       write(*,'(\"      parameter category:           \",I8)') sec4%parameter_category\n       write(*,'(\"      parameter number:             \",I8)') sec4%parameter_number\n       write(*,'(\"      type of generatiing process:  \",I8)') sec4%type_of_generating_process\n       write(*,'(\"      background process id:        \",I8)') sec4%background_process_id\n       write(*,'(\"      generating process id:        \",I8)') sec4%generating_process_id\n       write(*,'(\"      data cutoff hours:            \",I8)') sec4%data_cutoff_hours\n       write(*,'(\"      data cutoff minutes:          \",I8)') sec4%data_cutoff_minutes\n       write(*,'(\"      Time Range Indicator:         \",I8)') sec4%time_range_indicator\n       write(*,'(\"      time:                         \",I8)') sec4%time\n       write(*,'(\"      type of first fixed surface:  \",I8)') sec4%ltype1\n       write(*,'(\"      scale factor of first surface:  \",I8)') sec4%lscale1\n       write(*,'(\"      scaled value of first surface:  \",I8)') sec4%lvalue1\n       write(*,'(\"      First level                    \",F20.4)') sec4%level1\n       if (sec4%ltype2 /= 255) then\n          write(*,'(\"      type of second fixed surface:  \",I8)') sec4%ltype2\n          write(*,'(\"      scale factor of second surface:  \",I8)') sec4%lscale2\n          write(*,'(\"      scaled value of second surface:  \",I8)') sec4%lvalue2\n          write(*,'(\"      Second level                   \",F8.2)') sec4%level2\n       endif\n    case (8)\n       write(*,'(\"  PDT 4.8:  Average, accumulation ....\")')\n       write(*,'(\"      parameter category:           \",I8)') sec4%parameter_category\n       write(*,'(\"      parameter number:             \",I8)') sec4%parameter_number\n       write(*,'(\"      type of generatiing process:  \",I8)') sec4%type_of_generating_process\n       write(*,'(\"      background process id:        \",I8)') sec4%background_process_id\n       write(*,'(\"      generating process id:        \",I8)') sec4%generating_process_id\n       write(*,'(\"      data cutoff hours:            \",I8)') sec4%data_cutoff_hours\n       write(*,'(\"      data cutoff minutes:          \",I8)') sec4%data_cutoff_minutes\n       write(*,'(\"      Time Range Indicator:         \",I8)') sec4%time_range_indicator\n       write(*,'(\"      time:                         \",I8)') sec4%time\n       write(*,'(\"      type of first fixed surface:  \",I8)') sec4%ltype1\n       write(*,'(\"      scale factor of first surface:  \",I8)') sec4%lscale1\n       write(*,'(\"      scaled value of first surface:  \",I8)') sec4%lvalue1\n       write(*,'(\"      First level                    \",F10.2)') sec4%level1\n       if (sec4%ltype2 /= 255) then\n          write(*,'(\"      type of second fixed surface:  \",I8)') sec4%ltype2\n          write(*,'(\"      scale factor of second surface:  \",I8)') sec4%lscale2\n          write(*,'(\"      scaled value of second surface:  \",I8)') sec4%lvalue2\n          write(*,'(\"      Second level                  \",F10.2)') sec4%level2\n       endif\n       write(*,'(\"      End Year:                        \",I8)') sec4%PDT_4_8%end_year\n       write(*,'(\"      End Month:                       \",I8)') sec4%PDT_4_8%end_month\n       write(*,'(\"      End Day:                         \",I8)') sec4%PDT_4_8%end_day\n       write(*,'(\"      End Hour:                        \",I8)') sec4%PDT_4_8%end_hour\n       write(*,'(\"      End Minute:                      \",I8)') sec4%PDT_4_8%end_minute\n       write(*,'(\"      End Second:                      \",I8)') sec4%PDT_4_8%end_second\n       write(*,'(\"      Ene Hdate:                       \", A)') sec4%PDT_4_8%end_hdate\n       write(*,'(\"      Number of time range specifications: \",I8)') sec4%PDT_4_8%number_of_time_range_specifications\n       write(*,'(\"      Number missing:                  \",I8)') sec4%PDT_4_8%number_missing\n       write(*,'(\"      Statistical Process:              \",I8)') sec4%PDT_4_8%statistical_process\n       write(*,'(\"      Type of time increment:           \",I8)') sec4%PDT_4_8%type_of_time_increment\n       write(*,'(\"      time range unit:                  \",I8)') sec4%PDT_4_8%time_range_unit\n       write(*,'(\"      length of time range:             \",I8)') sec4%PDT_4_8%length_of_time_range\n       write(*,'(\"      time increment unit:              \",I8)') sec4%PDT_4_8%time_increment_unit\n       write(*,'(\"      time increment:                   \",I8)') sec4%PDT_4_8%time_increment\n    case default\n       write(*,'(\"Unrecognized product_template_number: \",I8)') sec4%product_template_number\n       stop \"Problem.\"\n    end select\n  end subroutine print_sec4\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec5(grib)\n    implicit none\n    type (GribStruct), target, intent(inout) :: grib\n    type (Section5Struct), pointer :: sec5\n    integer :: section\n    integer :: isign\n    integer :: iref\n    integer :: iref40\n    real    :: xref40\n    integer :: iref2\n    real    :: xref2\n    equivalence (iref40, xref40)\n    equivalence (iref2, xref2)\n\n    sec5 => grib%sec5\n\n    sec5%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    if (section /= 5) then\n       write(*,'(\"Section 5:  We are lost!  \", I8)') section\n       stop \"Problem\"\n    endif\n\n    sec5%nval                 = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    sec5%data_template_number = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    select case (sec5%data_template_number)\n    case (0)\n       iref = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       write(*, '(\"iref = \", I16)') iref\n\n       sec5%DRT_5_0%binary_scale_factor  = unpack_signed_integer(grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_0%decimal_scale_factor = unpack_signed_integer(grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_0%nbits                = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_0%data_type            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       stop \"Problem\"\n\n    case (2)\n       iref2                             = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%reference_value      = xref2\n       sec5%DRT_5_2%binary_scale_factor  = unpack_signed_integer  (grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_2%decimal_scale_factor = unpack_signed_integer  (grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_2%nbits                = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_2%data_type            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%group_splitting_method = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%missing_value_management = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%substitute1              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%substitute2              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%ng                       = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%widths_reference         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%widths_nbits             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%lengths_reference        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%length_increment         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%length_of_last_group     = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%lengths_nbits            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n\n    case (40)\n\n       iref40 = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec5%DRT_5_40%reference_value = xref40\n\n       sec5%DRT_5_40%binary_scale_factor = unpack_signed_integer(grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_40%decimal_scale_factor = unpack_signed_integer(grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_40%nbits = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_40%data_type = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_40%compression_type = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_40%target_compression_ratio = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    case default\n       write(*,'(\"Unrecognized Data Representation Template Number: \", I8)') sec5%data_template_number\n       stop \"Problem\"\n    end select\n\n  end subroutine unpack_sec5\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec5(grib)\n    implicit none\n    type (GribStruct), target, intent(in) :: grib\n    type (Section5Struct), pointer :: sec5\n    sec5 => grib%sec5\n    write(*,'(\"Section 5\")')\n    write(*,'(\"   Length of section:                   \",I8)') sec5%size\n    write(*,'(\"   Number of data points:               \",I8)') sec5%nval\n    write(*,'(\"   Data Representation Template Number: \",I8)') sec5%data_template_number\n    select case (sec5%data_template_number)\n    case (2)\n\n\n       write(*,'(\"     reference value:               \", G20.8)') sec5%DRT_5_2%reference_value\n       write(*,'(\"     binary scale factor:           \", I8)') sec5%DRT_5_2%binary_scale_factor\n       write(*,'(\"     decimal scale factor           \", I8)') sec5%DRT_5_2%decimal_scale_factor\n       write(*,'(\"     nbits:                         \", I8)') sec5%DRT_5_2%nbits\n       write(*,'(\"     data type:                     \", I8)') sec5%DRT_5_2%data_type\n       write(*,'(\"     group splitting method         \", I8)') sec5%DRT_5_2%group_splitting_method\n       write(*,'(\"     missing value management       \", I8)') sec5%DRT_5_2%missing_value_management\n       write(*,'(\"     primary substitute:            \", I8)') sec5%DRT_5_2%substitute1\n       write(*,'(\"     secondary substitute:          \", I8)') sec5%DRT_5_2%substitute2\n       write(*,'(\"     NG                             \", I8)') sec5%DRT_5_2%ng\n       write(*,'(\"     widths_reference               \", I8)') sec5%DRT_5_2%widths_reference\n       write(*,'(\"     widths_nbits                   \", I8)') sec5%DRT_5_2%widths_nbits\n       write(*,'(\"     lengths_reference              \", I8)') sec5%DRT_5_2%lengths_reference\n       write(*,'(\"     length increment               \", I8)') sec5%DRT_5_2%length_increment\n       write(*,'(\"     last length                    \", I8)') sec5%DRT_5_2%length_of_last_group\n       write(*,'(\"     lengths_nbits                  \", I8)') sec5%DRT_5_2%lengths_nbits\n\n\n    case (40)\n       write(*,'(\"     reference value:               \", G20.8)') sec5%DRT_5_40%reference_value\n       write(*,'(\"     binary scale factor:           \", I8)') sec5%DRT_5_40%binary_scale_factor\n       write(*,'(\"     decimal scale factor:          \", I8)') sec5%DRT_5_40%decimal_scale_factor\n       write(*,'(\"     nbits:                         \", I8)') sec5%DRT_5_40%nbits\n       write(*,'(\"     data type:                     \", I8)') sec5%DRT_5_40%data_type\n       write(*,'(\"     compression type:              \", I8)') sec5%DRT_5_40%compression_type\n       write(*,'(\"     target compression ratio:      \", I8)') sec5%DRT_5_40%target_compression_ratio\n    case default\n       write(*,'(\"Unrecognized Data Representation Template Number: \",I8)') sec5%data_template_number\n       stop \"Problem\"\n    end select\n  end subroutine print_sec5\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec6(grib)\n    implicit none\n    type (GribStruct), target, intent(inout) :: grib\n\n    integer :: section\n    integer :: section_start\n\n    type (Section6Struct), pointer :: sec6\n\n\n    section_start = grib%iskip\n\n    sec6 => grib%sec6\n\n    sec6%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    if (section /= 6) then\n       write(*,'(\"Section 6:  We are lost!  \", I8)') section\n       stop \"Problem\"\n    endif\n\n    sec6%bit_map_indicator = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)  \n    select case (sec6%bit_map_indicator)\n    case default\n       write(*,'(\"Oooooh, bit mapped field:  \",I8)')  sec6%bit_map_indicator\n       stop \"Unrecognized bit_map_indicator\"\n    case (255)\n       ! No bitmap.\n       ! No action needed here.\n    case (254)\n       ! Bitmap previously defined in this GRIB record.\n       ! No action needed here.  The previously-defined bitmap\n       ! should still be stored and used as necessary.\n    case (0)\n       ! write(*,'(\"Read a new bitmap:  \", I8, I8)') sec6%bit_map_indicator, sec6%size-6\n       if (associated(grib%bitmap)) then\n          deallocate(grib%bitmap)\n          nullify(grib%bitmap)\n       endif\n       allocate(grib%bitmap(grib%sec3%nx, grib%sec3%ny))\n       call gbytes(grib%buffer, grib%bitmap, grib%iskip, 1, 0, grib%sec3%number_of_data_points)\n       ! grib%iskip = grib%iskip + grib%sec3%number_of_data_points\n    end select\n\n    ! Position ourselves at the end of the section.\n    grib%iskip = section_start + (sec6%size*8)\n\n  end subroutine unpack_sec6\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec6(grib, verbosity)\n    implicit none\n    type (GribStruct), intent(in), target :: grib\n    integer,           intent(in)         :: verbosity\n\n    type (Section6Struct), pointer :: sec6\n    sec6 => grib%sec6\n    if (verbosity >= 10) then\n       write(*,'(\"Section 6\")')\n       if (verbosity >= 100) then\n          write(*,'(\"   Length of section:                   \",I8)') sec6%size\n          write(*,'(\"   Bit Map Indicator:                   \",I8)') sec6%bit_map_indicator\n          select case (sec6%bit_map_indicator)\n          case default\n             write(*,'(\"Oooooh, bit mapped field:  \",I8)') sec6%bit_map_indicator\n          case (0)\n             write(*,'(\"      A bit map applies and is defined here.\")')\n             ! write(*,'(\"      Bitmap of length: \",I8)') size(sec6%packed_bitmap)\n          case (254)\n             write(*,'(\"      A previously-defined bit map applies.\")')\n          case (255)\n             write(*,'(\"      A bit map does not apply\")')\n          end select\n       endif\n    endif\n  end subroutine print_sec6\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec7(grib)\n    implicit none\n    integer ::  section\n    type (GribStruct), target, intent(inout) :: grib\n    type (Section5Struct), pointer :: sec5\n    type (Section7Struct), pointer :: sec7\n\n    integer, pointer, dimension(:)  :: decoded\n    integer, allocatable, dimension(:) :: group\n    integer :: decoded_length\n    integer :: i\n    integer :: j\n    integer :: k\n    integer :: n\n    integer :: allostat\n    integer ::  ng\n    integer :: nbits\n    integer :: tot\n    integer, allocatable, dimension(:) :: x1\n    integer, allocatable, dimension(:) :: widths\n    integer, allocatable, dimension(:) :: lengths\n    integer, allocatable, dimension(:) :: L\n\n    integer :: sec7_beginning\n\n    sec7_beginning = grib%iskip/8\n\n    sec7 => grib%sec7\n    sec5 => grib%sec5\n\n    sec7%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    if (section /= 7) then\n       write(*,'(\"Section 7:  We are lost!  \", I8)') section\n       stop\n    endif\n\n    select case (sec5%data_template_number)\n    case default\n       write(*, '(\"Unrecognized Data Representation Template Number: \", I8)') sec5%data_template_number\n       stop \"Problem\"\n    case (2)\n       ! Grid-point data -- complex packing\n       ng = sec5%DRT_5_2%ng\n       nbits = sec5%DRT_5_2%nbits\n\n       allocate(x1(ng))\n       call gbytes(grib%buffer, x1, grib%iskip, nbits, 0, ng)\n       grib%iskip = grib%iskip + (nbits*ng)\n\n       ! Make sure we align at a byte boundary\n       if (mod(grib%iskip,8)>0) then\n          grib%iskip = grib%iskip + 8-mod(grib%iskip,8)\n       endif\n\n       allocate(widths(ng))\n       call gbytes(grib%buffer, widths, grib%iskip, sec5%DRT_5_2%widths_nbits, 0, ng)\n       grib%iskip = grib%iskip + (sec5%DRT_5_2%widths_nbits*ng)\n\n       ! Make sure we align at a byte boundary\n       if (mod(grib%iskip,8)>0) then\n          grib%iskip = grib%iskip + 8-mod(grib%iskip,8)\n       endif\n\n       allocate(lengths(ng))\n       call gbytes(grib%buffer, lengths, grib%iskip, sec5%DRT_5_2%lengths_nbits, 0, ng)\n       grib%iskip = grib%iskip + (sec5%DRT_5_2%lengths_nbits *  ng)\n\n       ! Make sure we align at a byte boundary\n       if (mod(grib%iskip,8)>0) then\n          grib%iskip = grib%iskip + 8-mod(grib%iskip,8)\n       endif\n\n       allocate(decoded(sec5%nval))\n       if (associated(sec7%floated)) then\n          deallocate(sec7%floated)\n          nullify(sec7%floated)\n       endif\n       allocate(sec7%floated(sec5%nval))\n       allocate(L(ng))\n       tot = 0\n       j = 1\n       do i = 1, ng\n          L(i) = sec5%DRT_5_2%lengths_reference + lengths(i) * sec5%DRT_5_2%length_increment\n          if (i==ng) L(i) = sec5%DRT_5_2%length_of_last_group\n          tot = tot + (widths(i)*L(i))\n          ! write(*, '(\"i, x1, widths, lengths, L = \", 10I)') i, x1(i), widths(i), lengths(i), L(i), tot, tot/8\n\n          ! For each group <i>, read <L> values of size <widths> bits.\n          if (widths(i) > 0) then\n             call gbytes(grib%buffer, decoded(j), grib%iskip, widths(i), 0, L(i))\n             grib%iskip = grib%iskip + widths(i)*L(i)\n             do k = 0, L(i)-1\n                sec7%floated(j+k) = sec5%DRT_5_2%reference_value + (real(x1(i) + decoded(j+k)) * real(2**sec5%DRT_5_2%binary_scale_factor))\n                sec7%floated(j+k) = sec7%floated(j+k) / real(10**(sec5%DRT_5_2%decimal_scale_factor))\n             enddo\n          endif\n          j = j + L(i)\n       enddo\n       deallocate(x1)\n       deallocate(lengths)\n       deallocate(widths)\n       deallocate(decoded)\n       nullify(decoded)\n       deallocate(L)\n\n    case (40)\n\n       ! Grid-point data -- JPEG 2000\n\n       if (sec5%DRT_5_40%nbits == 0) then\n          if (associated(sec7%floated)) then\n             deallocate(sec7%floated)\n             nullify(sec7%floated)\n          endif\n          allocate(sec7%floated(grib%sec3%nx * grib%sec3%ny), stat=allostat)\n          if (allostat /= 0) stop \"Allocation problem 1\"\n          do i = 1, ( grib%sec3%nx * grib%sec3%ny )\n             sec7%floated(i) = sec5%DRT_5_40%reference_value * (10.0 ** (-sec5%DRT_5_40%decimal_scale_factor))\n          enddo\n\n       else\n\n          ! Hack:  Unswap our previously swapped bytes.\n          ! Need to find a better way of handling swapping\n          call swap4f(grib%buffer, size(grib%buffer))\n\n          grib%iskip = grib%iskip + (sec7%size-5)*8\n\n          ! call fortran_decode_jpeg2000(grib%buffer(6:), sec7%size-5, decoded)\n          call fortran_decode_jpeg2000(grib%buffer(sec7_beginning+6:), sec7%size-5, decoded)\n\n          if (.not. associated(decoded)) then\n             write(*,'(\"Problem decoding jpeg2000.\")')\n             ! stop \"Problem\"\n          else\n             if (associated(sec7%floated)) then\n                deallocate(sec7%floated)\n                nullify(sec7%floated)\n             endif\n             allocate(sec7%floated(size(decoded)))\n             do i=1,  size(decoded)\n                sec7%floated(i) = sec5%DRT_5_40%reference_value + decoded(i) * 2.0 ** real(sec5%DRT_5_40%binary_scale_factor)\n                sec7%floated(i) = sec7%floated(i) * 10.0 ** real(-sec5%DRT_5_40%decimal_scale_factor)\n             enddo\n             deallocate(decoded)\n             nullify(decoded)\n          endif\n          ! Reswap\n          call swap4f(grib%buffer, size(grib%buffer))\n       endif\n\n    end select\n\n    ! Build the full 2-d array, unpacking from the bitmap if necessary\n\n    if (associated(grib%array)) then\n       deallocate(grib%array)\n       nullify(grib%array)\n    endif\n    allocate(grib%array(grib%sec3%nx, grib%sec3%ny))\n    grib%array = 0.0\n\n    if (grib%sec6%bit_map_indicator == 255) then\n       do i = 1, grib%sec3%nx\n          do j = 1, grib%sec3%ny\n             n = (j-1)*grib%sec3%nx + i\n             grib%array(i,j) = sec7%floated(n)\n          enddo\n       enddo\n    else\n       n = 0\n       do j = 1, grib%sec3%ny\n          do i = 1, grib%sec3%nx\n             if (grib%bitmap(i,j)==1) then\n                n = n + 1\n                grib%array(i,j) = sec7%floated(n)\n             endif\n          enddo\n       enddo\n    endif\n\n    ! Position ourselves at the end of the section.\n    grib%iskip = (sec7_beginning + sec7%size) * 8\n  end subroutine unpack_sec7\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec7(grib)\n    implicit none\n    type (GribStruct), target, intent(in) :: grib\n    type (Section7Struct), pointer :: sec7\n    sec7 => grib%sec7\n    write(*,'(\"Section 7\")')\n    write(*,'(\"   Length of section:                   \",I8)') sec7%size\n    if (associated(sec7%floated)) then\n       write(*,'(\"   First value =                        \", F15.8)') sec7%floated(1)\n    endif\n  end subroutine print_sec7\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib2\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_grib2_tables.F",
    "content": "module module_grib2_tables\n\n  type table_entry_struct\n     integer                   :: product_discipline\n     integer                   :: parameter_category\n     integer                   :: parameter_index\n     character(len=256)        :: category_name\n     character(len=256)        :: parameter_name\n     character(len=256)        :: parameter_units\n     type(table_entry_struct), pointer  :: next\n  end type table_entry_struct\n  type(table_entry_struct), target :: table\n\ncontains\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_read_parameter_tables\n    implicit none\n    integer :: iunit\n    character(len=200) :: string\n    integer :: ierr\n    integer, external :: get_unused_unit\n    integer :: p1, p2, p3\n\n    integer            :: product_discipline_index\n    integer            :: parameter_category_index\n    character(len=128) :: parameter_category_name\n\n\n    integer           :: parameter_index\n    character(len=64) :: parameter_name\n    character(len=32) :: parameter_units\n    character(len=256) :: grib_root\n    character(len=256) :: table_filename\n\n    call getenv(\"GRIB_ROOT\", grib_root)\n    if (trim(grib_root)==\" \") then\n       write(*,'(\"Not finding environment variable GRIB_ROOT.\")')\n       write(*,'(\"Program does not know where to find GRIB parameter tables\")')\n       stop\n    endif\n    table_filename = trim(grib_root)//\"/GRIB2_PARAMETER_TABLE\"\n\n    iunit = get_unused_unit()\n    nullify(table%next)\n\n    open(iunit, file=trim(table_filename), status='old', form='formatted', action='read', iostat=ierr)\n    if (ierr /= 0) then\n       write(*,'(/,\" ***** ERROR *****\",/)')\n       write(*,'(\" ***** Problem opening file ''\", A, \"''\")') trim(table_filename)\n       write(*,'(\" ***** Does file exist?  Is file readable?\",/)')\n       stop\n    endif\n\n    READ_TABLE : do\n       read(iunit, '(A200)', iostat=ierr) string\n       if (ierr /= 0) exit READ_TABLE\n       if (string(1:1) == \"#\") cycle READ_TABLE\n       if (string(1:1) == \"+\") then\n          !\n          ! read table header info, separated by '+' signs\n          !\n          p1 = index(string, \"+\")\n          p1 = p1 + 1\n          p2 = p1 + index(string(p1:), \"+\")\n          p3 = p2 + index(string(p2:), \"+\")\n          read(string(p1:p2-2), *) product_discipline_index\n          read(string(p2:p3-2), *) parameter_category_index\n          parameter_category_name = trim(adjustl(string(p3:)))\n       else\n          p1 = index(string, \"|\") - 1\n          p2 = p1 + index(string(p1+2:), \"|\")\n          read(string(1:p1),*) parameter_index\n          parameter_name = trim(adjustl(string(p1+2:p2)))\n          parameter_units = trim(adjustl(string(p2+2:)))\n          ! print*, parameter_index, trim(parameter_name),\" \", trim(parameter_units)\n\n          call add_to_growing_table(product_discipline_index, parameter_category_index, parameter_category_name, &\n               parameter_index, parameter_name, parameter_units)\n\n       endif\n    enddo READ_TABLE\n    close(iunit)\n\n  end subroutine grib2_read_parameter_tables\n\n!=================================================================================\n!=================================================================================\n\n  subroutine add_to_growing_table(pdi, pci, pcn, pi, pn, pu)\n    implicit none\n! Input:\n!       pdi:  Parameter Discipline index number\n!       pci:  Parameter Category index number in discipline <pdi>\n!       pi:   Parameter index number in category <pci> and discipline <pdi>\n!       pcn:  Parameter category name\n!       pn:   Parameter name\n!       pu:   Parameter units\n\n! Input\n    integer, intent(in) :: pdi\n    integer, intent(in) :: pci\n    integer, intent(in) :: pi\n    character(len=*), intent(in) :: pcn\n    character(len=*), intent(in) :: pn\n    character(len=*), intent(in) :: pu\n\n! Local\n    type(table_entry_struct), pointer:: table_pointer\n\n    ! Start us off by pointing to the top of the table.\n    table_pointer => table\n\n    ! Seek for the end of the table.\n    do while (associated(table_pointer%next))\n       table_pointer => table_pointer%next\n    enddo\n\n    ! Now that we're at the end of the table, create a new entry\n    allocate(table_pointer%next)\n    table_pointer => table_pointer%next\n    nullify(table_pointer%next)\n\n    ! Fill our new entry with the information passed into this subroutine\n    table_pointer%product_discipline = pdi\n    table_pointer%parameter_category =   pci\n    table_pointer%parameter_index    =   pi\n    table_pointer%category_name    =   pcn\n    table_pointer%parameter_name     =   pn\n    table_pointer%parameter_units    =   pu\n\n  end subroutine add_to_growing_table\n\n!=================================================================================\n!=================================================================================\n  subroutine grib2_clear_parameter_table\n    implicit none\n\n! Local\n    type(table_entry_struct), pointer:: table_pointer\n    type(table_entry_struct), pointer:: next_pointer\n\n    ! Start us off by pointing to the top of the table.\n    table_pointer => table\n\n    do while ( associated(table_pointer%next) )\n       next_pointer => table_pointer%next\n       if (associated(table_pointer, table)) then\n          table_pointer => next_pointer\n          nullify(next_pointer)\n       else\n          nullify(table_pointer%next)\n          deallocate(table_pointer)\n          table_pointer => next_pointer\n          nullify(next_pointer)\n       endif\n    enddo\n\n    if (associated(table_pointer)) then\n       ! deallocate(table_pointer)\n       nullify(table_pointer)\n    endif\n    if (associated(next_pointer)) then\n       nullify(next_pointer)\n    endif\n\n  end subroutine grib2_clear_parameter_table\n\n!=================================================================================\n!=================================================================================\n\n  subroutine get_parameter_table_information(discipline, category, parameter_index, &\n       category_name, parameter_name, parameter_units)\n    implicit none\n    integer, intent(in) :: discipline, category, parameter_index\n    character(len=256), intent(out) :: category_name, parameter_name, parameter_units\n\n    type(table_entry_struct), pointer:: table_pointer\n    write(category_name, '(\"Discipline: \", I3, \"   Unknown category: \", I3)') discipline, category\n    write(parameter_name, '(\"Unknown parameter: \", I3)') parameter_index\n    parameter_units = \" \"\n\n    table_pointer => table\n    do while (associated(table_pointer%next))\n       table_pointer => table_pointer%next\n       if ( ( table_pointer%product_discipline == discipline ) .and. &\n            ( table_pointer%parameter_category == category ) .and. &\n            ( table_pointer%parameter_index    == parameter_index) ) then\n          ! We found a match\n          category_name = table_pointer%category_name\n          parameter_name = table_pointer%parameter_name\n          parameter_units = table_pointer%parameter_units\n          exit\n       endif\n    enddo\n\n  end subroutine get_parameter_table_information\n\n!=================================================================================\n!=================================================================================\n\n  character(len=32) function interpret_time_unit(i) result(string)\n    implicit none\n    integer, intent(in) :: i\n\n    select case (i)\n    case default\n       write(string, '(\"unrecognized time units: \", I4)') i\n    case (0)\n       string = \"minutes\"\n    case (1)\n       string = \"hours\"\n    case (2)\n       string = \"days\"\n    case (3)\n       string = \"months\"\n    case (4)\n       string = \"years\"\n    case (13)\n       string = \"seconds\"\n    end select\n  end function interpret_time_unit\n\n!=================================================================================\n!=================================================================================\n\n  subroutine get_level_string(surface_type_code, text, units)\n    implicit none\n    integer, intent(in) :: surface_type_code\n    character(len=256), intent(out) :: text\n    character(len=256), intent(out) :: units\n\n    units = \" \"\n    select case (surface_type_code)\n    case default\n       write(text,'(\"Unrecognized type of surface\", I4)') surface_type_code\n    case (1)\n       write(text,'(\"Level:  Ground or water surface\")')\n    case (2)\n       write(text,'(\"Level:  Cloud base level\")')\n    case (3)\n       write(text,'(\"Level:  Cloud top level\")')\n    case (4)\n       write(text,'(\"Level:  0~S~o~N~C isotherm level\")')\n    case (5)\n       write(text,'(\"Level:  Adiabatic lifting condensation level\")')\n    case (6)\n       write(text,'(\"Level:  Maximum wind level\")')\n    case (7)\n       write(text,'(\"Level:  Tropopause\")')\n    case (8)\n       write(text,'(\"Level:  Nominal top of atmosphere\")')\n    case (9)\n       write(text,'(\"Level:  Sea bottom\")')\n    case (20)\n       write(text,'(\"Level:  Isothermal level \")')\n       units = \"K\"\n    case (100)\n       write(text,'(\"Level:  Isobaric surface \")')\n       units = \"Pa\"\n    case (101)\n       write(text,'(\"Level:  Mean sea level\")')\n    case (102)\n       write(text,'(\"Level:  Height MSL \")')\n       units = \"m\"\n    case (103)\n       write(text,'(\"Level:  Height AGL \")')\n       units = \"m\"\n    case (104)\n       write(text,'(\"Level:  Sigma level \")')\n       units = \"sigma value\"\n    case (105)\n       write(text,'(\"Level:  Hybrid level \")')\n    case (106)\n       write(text,'(\"Level:  Depth below land surface \")')\n       units = \"m\"\n    case (107)\n       write(text,'(\"Level:  Isentropic level \")')\n       units = \"K\"\n    case (108)\n       write(text,'(\"Level:  Specified pressure difference from ground \")')\n       units = \"Pa\"\n    case (109)\n       write(text,'(\"Level:  Potential vorticity surface \")')\n       units = \"Kg m{2} kg{-1} s{-1}\"\n    case (111)\n       write(text,'(\"Level:  Eta level \")')\n    case (117)\n       write(text,'(\"Level:  Mixed-layer depth \")')\n       units = \"m\"\n    case (160)\n       write(text,'(\"Level:  Depth below sea-level \")')\n       units = \"m\"\n    end select\n\n  end subroutine get_level_string\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib2_tables\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_grib_common.F",
    "content": "module module_grib_common\n  use module_mapinfo\n  ! Low-level stuff used by both module_grib1 and module_grib2\n  implicit none\n  integer, parameter :: string_sevens = Z\"37373737\" ! Encodes \"7777\", which marks the end of a GRIB record.\n  integer, parameter :: string_grib   = Z\"47524942\" ! Encodes \"GRIB\", which marks the beginning of a GRIB record\n\n  type G1Section1Struct\n     integer :: isize\n     integer :: ptvn\n     integer :: center\n     integer :: process\n     integer :: grid\n     logical :: ifgds\n     logical :: ifbms\n     integer :: parameter\n     integer :: leveltyp\n     real    :: levelval\n     real    :: level2val\n     integer :: year\n     integer :: month\n     integer :: day\n     integer :: hour\n     integer :: minute\n     integer :: ftu\n     integer :: p1\n     integer :: p2\n     integer :: tri\n     integer :: navg\n     integer :: nmissavg\n     integer :: subcenter\n     integer :: decimal_scale_factor\n     character(len=19) :: hdate\n  end type G1Section1Struct\n\n  type G1Section2Struct\n     integer :: isize\n     integer :: nv\n     integer :: pv\n     integer :: drt\n     integer :: nx\n     integer :: ny\n     real    :: lat1\n     real    :: lon1\n     integer :: rac\n     real    :: lat2\n     real    :: lon2\n     real    :: lov\n     real    :: dx\n     real    :: dy\n     integer :: center\n     integer :: scanning_mode\n     integer :: i_scan_direction\n     integer :: j_scan_direction\n     integer :: orientation\n     real    :: latin1\n     real    :: latin2\n     real    :: polelat\n     real    :: polelon\n  end type G1Section2Struct\n\n  type G1Section3Struct\n     integer :: isize\n     integer :: nunused\n     integer :: numeric\n     integer :: bitmap_beginning\n  end type G1Section3Struct\n\n  type G1Section4Struct\n     integer :: isize\n     integer, dimension(4) :: flag\n     integer :: nunused\n     integer :: binary_scale_factor\n     real    :: reference_value\n     integer :: nbits\n     integer :: start_of_packed_data\n  end type G1Section4Struct\n\n  type Section1Struct\n     integer :: size\n     integer :: center\n     integer :: subcenter\n     integer :: mtvn\n     integer :: ltvn\n     integer :: srt\n     integer :: year\n     integer :: month\n     integer :: day\n     integer :: hour\n     integer :: minute\n     integer :: second\n     integer :: production_status\n     integer :: data_type\n     character(len=19) :: hdate\n  end type Section1Struct\n\n  type GT_3_0_Struct\n     integer :: scale_factor_of_radius\n     integer :: scaled_value_of_radius\n     integer :: scale_factor_major_axis\n     integer :: scaled_value_major_axis\n     integer :: scale_factor_minor_axis\n     integer :: scaled_value_minor_axis\n     integer :: basic_angle\n     integer :: subdivisions_of_basic_angle\n     real    :: la1\n     real    :: lo1\n     integer :: resolution_and_component_flags\n     real    :: la2\n     real    :: lo2\n     real    :: dx\n     real    :: dy\n     integer :: scanning_mode\n     integer :: i_direction_increments_given\n     integer :: j_direction_increments_given\n     integer :: winds_grid_relative\n     integer :: i_scan_direction\n     integer :: j_scan_direction\n     integer :: i_scan_consecutive\n     integer :: boustrophedon\n  end type GT_3_0_Struct\n\n  type GT_3_30_Struct\n     integer :: shape_of_earth\n     integer :: scale_factor_of_radius\n     integer :: scaled_value_of_radius\n     integer :: scale_factor_major_axis\n     integer :: scaled_value_major_axis\n     integer :: scale_factor_minor_axis\n     integer :: scaled_value_minor_axis\n     real    :: la1\n     real    :: lo1\n     integer :: resolution_and_component_flags\n     real    :: lad\n     real    :: lov\n     real    :: dx\n     real    :: dy\n     integer :: projection_center_flag\n     integer :: scanning_mode\n     real    :: latin1\n     real    :: latin2\n     real    :: pole_latitude\n     real    :: pole_longitude\n     integer :: i_direction_increments_given\n     integer :: j_direction_increments_given\n     integer :: winds_grid_relative\n     integer :: i_scan_direction\n     integer :: j_scan_direction\n     integer :: i_scan_consecutive\n     integer :: boustrophedon\n  end type GT_3_30_Struct\n\n  type Section3Struct\n     integer :: size\n     integer :: grid_definition_source\n     integer :: number_of_data_points\n     integer :: octets_for_optional_list\n     integer :: list_interpretation\n     integer :: grid_template_number\n     integer :: nx\n     integer :: ny\n     integer :: shape_of_earth\n     type (GT_3_0_Struct) :: GT_3_0\n     type (GT_3_30_Struct) :: GT_3_30\n  end type Section3Struct\n\n!  type PDT_4_0_Struct\n!  end type PDT_4_0_Struct\n\n  type PDT_4_8_Struct\n     integer :: end_year\n     integer :: end_month\n     integer :: end_day\n     integer :: end_hour\n     integer :: end_minute\n     integer :: end_second\n     character(len=19) :: begin_hdate\n     character(len=19) :: end_hdate\n     integer :: number_of_time_range_specifications\n     integer :: number_missing\n     integer :: statistical_process\n     integer :: type_of_time_increment\n     integer :: time_range_unit\n     integer :: length_of_time_range\n     integer :: time_increment_unit\n     integer :: time_increment\n  end type PDT_4_8_Struct\n\n  type Section4Struct\n     integer :: size\n     integer :: number_of_coord_values\n     integer :: product_template_number\n     integer :: parameter_category\n     integer :: parameter_number\n     integer :: type_of_generating_process\n     integer :: background_process_id\n     integer :: generating_process_id\n     integer :: data_cutoff_hours\n     integer :: data_cutoff_minutes\n     integer :: time_range_indicator\n     integer :: time\n     integer :: ltype1\n     integer :: lscale1\n     integer :: lvalue1\n     real    :: level1\n     integer :: ltype2\n     integer :: lscale2\n     integer :: lvalue2\n     real    :: level2\n     ! type (PDT_4_0_Struct) :: PDT_4_0\n     type (PDT_4_8_Struct) :: PDT_4_8\n\n  end type Section4Struct\n\n  type DRT_5_0_Struct\n     integer :: binary_scale_factor\n     integer :: decimal_scale_factor\n     integer :: nbits\n     integer :: data_type\n  end type DRT_5_0_Struct\n\n  type DRT_5_2_Struct\n     real    :: reference_value\n     integer :: binary_scale_factor\n     integer :: decimal_scale_factor\n     integer :: nbits\n     integer :: data_type\n     integer :: group_splitting_method\n     integer :: missing_value_management\n     integer :: substitute1\n     integer :: substitute2\n     integer :: ng\n     integer :: widths_reference\n     integer :: widths_nbits\n     integer :: lengths_reference\n     integer :: length_increment\n     integer :: length_of_last_group\n     integer :: lengths_nbits\n  end type DRT_5_2_Struct\n\n  type DRT_5_40_Struct\n     real :: reference_value\n     integer :: binary_scale_factor\n     integer :: decimal_scale_factor\n     integer :: nbits\n     integer :: data_type\n     integer :: compression_type\n     integer :: target_compression_ratio\n  end type DRT_5_40_Struct\n\n  type Section5Struct\n     integer :: size\n     integer :: nval\n     integer :: data_template_number\n     type (DRT_5_0_Struct) :: DRT_5_0\n     type (DRT_5_2_Struct) :: DRT_5_2\n     type (DRT_5_40_Struct) :: DRT_5_40\n  end type Section5Struct\n\n  type Section6Struct\n     integer :: size\n     integer :: bit_map_indicator\n  end type Section6Struct\n\n  type Section7Struct\n     integer :: size\n     real, pointer, dimension(:)   :: floated\n  end type Section7Struct\n\n  type GribStruct\n     integer :: edition\n     integer :: size\n     character(len=1), pointer, dimension(:)   :: buffer\n     real,             pointer, dimension(:,:) :: array\n     integer,          pointer, dimension(:,:) :: bitmap\n     integer :: iskip\n     integer :: discipline\n\n     type(G1Section1Struct) :: g1sec1\n     type(G1Section2Struct) :: g1sec2\n     type(G1Section3Struct) :: g1sec3\n     type(G1Section4Struct) :: g1sec4\n\n     type(Section1Struct) :: sec1\n     type(Section3Struct) :: sec3\n     type(Section4Struct) :: sec4\n     type(Section5Struct) :: sec5\n     type(Section6Struct) :: sec6\n     type(Section7Struct) :: sec7\n     type(MapInfoStruct)  :: mapinfo\n  end type GribStruct\n\ncontains\n\n!=================================================================================\n!=================================================================================\n\n  integer function unpack_signed_integer(buffer, nbytes, iskip) RESULT (signed_integer)\n    implicit none\n    !\n    ! Purpose:\n    !      From a string of bytes in a buffer array, unpack a stream of bytes into an \n    !      integer variable, with the a priori knowledge that this stream of bytes\n    !      represents a signed integer, the sign indicated by the first bit in the stream. \n    !      The <iskip> indicator is then incremented to refer to the position in the \n    !      <buffer> array at the end of the integer just read.\n    !\n    ! Input:\n    !      buffer:  A buffer array from which we unpack data.\n    !      nbytes:  The number of bytes to read from <buffer> as representing a signed integer\n    !      iskip:   The number of bytes to skip in <buffer> before unpacking <nbytes> of data.\n    !\n    ! Output:\n    !      iskip:   The number of bits in <buffer> up to and including the signed integer \n    !               just read.\n    !\n    ! Return Value:\n    !      The integer unpacked from <buffer>\n    !\n    ! Side effects:\n    !      None\n    !\n    character(len=1), dimension(*), intent(in)    :: buffer\n    integer,                        intent(in)    :: nbytes\n    integer,                        intent(inout) :: iskip\n\n    integer :: isign\n\n    ! Read the first bit, to determine whether this integer is negative (<isign>==1)\n    ! or non-negative (<isign>==0)\n    call gbyte(buffer, isign, iskip, 1)\n\n    ! Read the remaining bits of the integer\n    call gbyte(buffer, signed_integer, iskip+1, (nbytes*8)-1)\n\n    ! Apply the sign we read before to the integer value.\n    if (isign == 1) then\n       signed_integer = -signed_integer\n    endif\n\n    ! Update the <iskip> indicator.\n    iskip = iskip + (nbytes*8)\n\n  end function unpack_signed_integer\n\n!=================================================================================\n!=================================================================================\n\n  integer function unpack_unsigned_integer(buffer, nbytes, iskip) RESULT (unsigned_integer)\n    implicit none\n    !\n    ! Purpose:\n    !      From a string of bytes in a buffer array, unpack a stream of bytes into an \n    !      integer variable, with the a priori knowledge that this stream of bytes\n    !      represents an _unsigned_ integer.  The <iskip> indicator is then incremented \n    !      to refer to the position in the <buffer> array at the end of the integer just read.\n    !\n    ! Input:\n    !      buffer:  A buffer array from which we unpack data.\n    !      nbytes:  The number of bytes to read from <buffer> as representing an unsigned integer\n    !      iskip:   The number of bytes to skip in <buffer> before unpacking <nbytes> of data.\n    !\n    ! Output:\n    !      iskip:   The number of bits in <buffer> up to and including the unsigned integer \n    !               just read.\n    !\n    ! Return Value:\n    !      The integer unpacked from <buffer>\n    !\n    ! Side effects:\n    !      None\n    !\n    character(len=1), dimension(*), intent(in)    :: buffer\n    integer,                        intent(in)    :: nbytes\n    integer,                        intent(inout) :: iskip\n\n    call gbyte(buffer, unsigned_integer, iskip, nbytes*8)\n\n    ! Update the <iskip> indicator.\n    iskip = iskip + (nbytes*8)\n\n  end function unpack_unsigned_integer\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib_common\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_input_data_structure.F",
    "content": "module module_input_data_structure\n  use module_llxy\n  type input_data_type\n     integer                       :: nx     ! Grid Dimension -- X direction\n     integer                       :: ny     ! Grid Dimension -- Y direction\n     type(proj_info)               :: proj   ! Map Projection information\n     character(len=24)             :: hdate  ! Date (YYYY-MM-DD_hh:mm:ss.ffff)\n     character(len=9)              :: field  ! Field name\n     character(len=25)             :: units  ! Field units\n     character(len=46)             :: desc   ! Field description\n     real                          :: layer1 ! Top of a layer definition\n     real                          :: layer2 ! Bottom of a layer definition\n     real, pointer, dimension(:,:) :: data   ! The data array\n  end type input_data_type\n\nend module module_input_data_structure\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_llxy.F",
    "content": "MODULE module_llxy\n\n! Module that defines constants, data structures, and\n! subroutines used to convert grid indices to lat/lon\n! and vice versa.\n!\n! SUPPORTED PROJECTIONS\n! ---------------------\n! Cylindrical Lat/Lon (code = PROJ_LATLON)\n! Mercator (code = PROJ_MERC)\n! Lambert Conformal (code = PROJ_LC)\n! Gaussian (code = PROJ_GAUSS)\n! Polar Stereographic (code = PROJ_PS)\n! Rotated Lat/Lon (code = PROJ_ROTLL)\n!\n! REMARKS\n! -------\n! The routines contained within were adapted from routines\n! obtained from NCEP's w3 library.  The original NCEP routines were less\n! flexible (e.g., polar-stereo routines only supported truelat of 60N/60S)\n! than what we needed, so modifications based on equations in Hoke, Hayes, and\n! Renninger (AFGWC/TN/79-003) were added to improve the flexibility.\n! Additionally, coding was improved to F90 standards and the routines were\n! combined into this module.\n!\n! ASSUMPTIONS\n! -----------\n!  Grid Definition:\n!    For mercator, lambert conformal, and polar-stereographic projections,\n!    the routines within assume the following:\n!\n!       1.  Grid is dimensioned (i,j) where i is the East-West direction,\n!           positive toward the east, and j is the north-south direction,\n!           positive toward the north.\n!       2.  Origin is at (1,1) and is located at the southwest corner,\n!           regardless of hemispere.\n!       3.  Grid spacing (dx) is always positive.\n!       4.  Values of true latitudes must be positive for NH domains\n!           and negative for SH domains.\n!\n!     For the latlon and Gaussian projection, the grid origin may be at any\n!     of the corners, and the deltalat and deltalon values can be signed to\n!     account for this using the following convention:\n!       Origin Location        Deltalat Sign      Deltalon Sign\n!       ---------------        -------------      -------------\n!        SW Corner                  +                   +\n!        NE Corner                  -                   -\n!        NW Corner                  -                   +\n!        SE Corner                  +                   -\n!\n!  Data Definitions:\n!       1. Any arguments that are a latitude value are expressed in\n!          degrees north with a valid range of -90 -> 90\n!       2. Any arguments that are a longitude value are expressed in\n!          degrees east with a valid range of -180 -> 180.\n!       3. Distances are in meters and are always positive.\n!       4. The standard longitude (stdlon) is defined as the longitude\n!          line which is parallel to the grid's y-axis (j-direction), along\n!          which latitude increases (NOT the absolute value of latitude, but\n!          the actual latitude, such that latitude increases continuously\n!          from the south pole to the north pole) as j increases.\n!       5. One true latitude value is required for polar-stereographic and\n!          mercator projections, and defines at which latitude the\n!          grid spacing is true.  For lambert conformal, two true latitude\n!          values must be specified, but may be set equal to each other to\n!          specify a tangent projection instead of a secant projection.\n!\n! USAGE\n! -----\n! To use the routines in this module, the calling routines must have the\n! following statement at the beginning of its declaration block:\n!   USE map_utils\n!\n! The use of the module not only provides access to the necessary routines,\n! but also defines a structure of TYPE (proj_info) that can be used\n! to declare a variable of the same type to hold your map projection\n! information.  It also defines some integer parameters that contain\n! the projection codes so one only has to use those variable names rather\n! than remembering the acutal code when using them.  The basic steps are\n! as follows:\n!\n!   1.  Ensure the \"USE map_utils\" is in your declarations.\n!   2.  Declare the projection information structure as type(proj_info):\n!         TYPE(proj_info) :: proj\n!   3.  Populate your structure by calling the map_set routine:\n!         CALL map_set(code,lat1,lon1,knowni,knownj,dx,stdlon,truelat1,truelat2,proj)\n!       where:\n!         code (input) = one of PROJ_LATLON, PROJ_MERC, PROJ_LC, PROJ_PS,\n!                        PROJ_GAUSS, or PROJ_ROTLL\n!         lat1 (input) = Latitude of grid origin point (i,j)=(1,1)\n!                         (see assumptions!)\n!         lon1 (input) = Longitude of grid origin\n!         knowni (input) = origin point, x-location\n!         knownj (input) = origin point, y-location\n!         dx (input) = grid spacing in meters (ignored for LATLON projections)\n!         stdlon (input) = Standard longitude for PROJ_PS and PROJ_LC,\n!               deltalon (see assumptions) for PROJ_LATLON,\n!               ignored for PROJ_MERC\n!         truelat1 (input) = 1st true latitude for PROJ_PS, PROJ_LC, and\n!                PROJ_MERC, deltalat (see assumptions) for PROJ_LATLON\n!         truelat2 (input) = 2nd true latitude for PROJ_LC,\n!                ignored for all others.\n!         proj (output) = The structure of type (proj_info) that will be fully\n!                populated after this call\n!\n!   4.  Now that the proj structure is populated, you may call either\n!       of the following routines:\n!\n!       latlon_to_ij(proj, lat, lon, i, j)\n!       ij_to_latlon(proj, i, j, lat, lon)\n!\n!       It is incumbent upon the calling routine to determine whether or\n!       not the values returned are within your domain's bounds.  All values\n!       of i, j, lat, and lon are REAL values.\n!\n!\n! REFERENCES\n! ----------\n!  Hoke, Hayes, and Renninger, \"Map Preojections and Grid Systems for\n!       Meteorological Applications.\" AFGWC/TN-79/003(Rev), Air Weather\n!       Service, 1985.\n!\n!  NCAR MM5v3 Modeling System, REGRIDDER program, module_first_guess_map.F\n!  NCEP routines w3fb06, w3fb07, w3fb08, w3fb09, w3fb11, w3fb12\n!\n! HISTORY\n! -------\n! 27 Mar 2001 - Original Version\n!               Brent L. Shaw, NOAA/FSL (CSU/CIRA)\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n   INTEGER, PARAMETER :: HH=4, VV=5\n\n   REAL, PARAMETER :: PI = 3.141592653589793\n   REAL, PARAMETER :: OMEGA_E = 7.292e-5\n\n   REAL, PARAMETER :: DEG_PER_RAD = 180./PI\n   REAL, PARAMETER :: RAD_PER_DEG = PI/180.\n\n   REAL, PARAMETER :: A_WGS84  = 6378137.\n   REAL, PARAMETER :: B_WGS84  = 6356752.314\n   REAL, PARAMETER :: RE_WGS84 = A_WGS84\n   REAL, PARAMETER :: E_WGS84  = 0.081819192\n\n   REAL, PARAMETER :: A_NAD83  = 6378137.\n   REAL, PARAMETER :: RE_NAD83 = A_NAD83\n   REAL, PARAMETER :: E_NAD83  = 0.0818187034\n\n   REAL, PARAMETER :: EARTH_RADIUS_M = 6370000.\n   REAL, PARAMETER :: EARTH_CIRC_M = 2.*PI*EARTH_RADIUS_M\n\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_LATLON = 0\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_LC = 1\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_PS = 2\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_PS_WGS84 = 102\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_MERC = 3\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_GAUSS = 4\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_CYL = 5\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_CASSINI = 6\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_ALBERS_NAD83 = 105\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_ROTLL = 203\n\n   ! Define some private constants\n   INTEGER, PRIVATE, PARAMETER :: HIGH = 8\n\n   TYPE proj_info\n\n      INTEGER          :: code     ! Integer code for projection TYPE\n      INTEGER          :: nlat     ! For Gaussian -- number of latitude points \n                                   !  north of the equator\n      INTEGER          :: nlon     !\n                                   !\n      INTEGER          :: ixdim    ! For Rotated Lat/Lon -- number of mass points\n                                   !  in an odd row\n      INTEGER          :: jydim    ! For Rotated Lat/Lon -- number of rows\n      INTEGER          :: stagger  ! For Rotated Lat/Lon -- mass or velocity grid \n      REAL             :: phi      ! For Rotated Lat/Lon -- domain half-extent in \n                                   !  degrees latitude\n      REAL             :: lambda   ! For Rotated Lat/Lon -- domain half-extend in\n                                   !  degrees longitude\n      REAL             :: lat1     ! SW latitude (1,1) in degrees (-90->90N)\n      REAL             :: lon1     ! SW longitude (1,1) in degrees (-180->180E)\n      REAL             :: lat0     ! For Cassini, latitude of projection pole\n      REAL             :: lon0     ! For Cassini, longitude of projection pole\n      REAL             :: dx       ! Grid spacing in meters at truelats, used\n                                   !  only for ps, lc, and merc projections\n      REAL             :: dy       ! Grid spacing in meters at truelats, used\n                                   !  only for ps, lc, and merc projections\n      REAL             :: latinc   ! Latitude increment for cylindrical lat/lon\n      REAL             :: loninc   ! Longitude increment for cylindrical lat/lon\n                                   !  also the lon increment for Gaussian grid\n      REAL             :: dlat     ! Lat increment for lat/lon grids\n      REAL             :: dlon     ! Lon increment for lat/lon grids\n      REAL             :: stdlon   ! Longitude parallel to y-axis (-180->180E)\n      REAL             :: truelat1 ! First true latitude (all projections)\n      REAL             :: truelat2 ! Second true lat (LC only)\n      REAL             :: hemi     ! 1 for NH, -1 for SH\n      REAL             :: cone     ! Cone factor for LC projections\n      REAL             :: polei    ! Computed i-location of pole point\n      REAL             :: polej    ! Computed j-location of pole point\n      REAL             :: rsw      ! Computed radius to SW corner\n      REAL             :: rebydx   ! Earth radius divided by dx\n      REAL             :: knowni   ! X-location of known lat/lon\n      REAL             :: knownj   ! Y-location of known lat/lon\n      REAL             :: re_m     ! Radius of spherical earth, meters\n      REAL             :: rho0     ! For Albers equal area\n      REAL             :: nc       ! For Albers equal area\n      REAL             :: bigc     ! For Albers equal area\n      LOGICAL          :: init     ! Flag to indicate if this struct is\n                                   !  ready for use\n      LOGICAL          :: wrap     ! For Gaussian -- flag to indicate wrapping \n                                   !  around globe?\n      REAL, POINTER, DIMENSION(:) :: gauss_lat  ! Latitude array for Gaussian grid\n\n   END TYPE proj_info\n\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n CONTAINS\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n   SUBROUTINE map_init(proj)\n      ! Initializes the map projection structure to missing values\n\n      IMPLICIT NONE\n      TYPE(proj_info), INTENT(INOUT)  :: proj\n\n      proj%lat1     = -999.9\n      proj%lon1     = -999.9\n      proj%lat0     = -999.9\n      proj%lon0     = -999.9\n      proj%dx       = -999.9\n      proj%dy       = -999.9\n      proj%latinc   = -999.9\n      proj%loninc   = -999.9\n      proj%stdlon   = -999.9\n      proj%truelat1 = -999.9\n      proj%truelat2 = -999.9\n      proj%phi      = -999.9\n      proj%lambda   = -999.9\n      proj%ixdim    = -999\n      proj%jydim    = -999\n      proj%stagger  = HH\n      proj%nlat     = 0\n      proj%nlon     = 0\n      proj%hemi     = 0.0\n      proj%cone     = -999.9\n      proj%polei    = -999.9\n      proj%polej    = -999.9\n      proj%rsw      = -999.9\n      proj%knowni   = -999.9\n      proj%knownj   = -999.9\n      proj%re_m     = EARTH_RADIUS_M\n      proj%init     = .FALSE.\n      proj%wrap     = .FALSE.\n      proj%rho0     = 0.\n      proj%nc       = 0.\n      proj%bigc     = 0.\n      nullify(proj%gauss_lat)\n\n   END SUBROUTINE map_init\n\n\n   SUBROUTINE map_set(proj_code, proj, lat1, lon1, lat0, lon0, knowni, knownj, dx, latinc, &\n                      loninc, stdlon, truelat1, truelat2, nlat, nlon, ixdim, jydim, &\n                      stagger, phi, lambda, r_earth)\n      ! Given a partially filled proj_info structure, this routine computes\n      ! polei, polej, rsw, and cone (if LC projection) to complete the\n      ! structure.  This allows us to eliminate redundant calculations when\n      ! calling the coordinate conversion routines multiple times for the\n      ! same map.\n      ! This will generally be the first routine called when a user wants\n      ! to be able to use the coordinate conversion routines, and it\n      ! will call the appropriate subroutines based on the\n      ! proj%code which indicates which projection type this is.\n\n      IMPLICIT NONE\n\n      ! Declare arguments\n      INTEGER, INTENT(IN)               :: proj_code\n      INTEGER, INTENT(IN), OPTIONAL     :: nlat\n      INTEGER, INTENT(IN), OPTIONAL     :: nlon\n      INTEGER, INTENT(IN), OPTIONAL     :: ixdim\n      INTEGER, INTENT(IN), OPTIONAL     :: jydim\n      INTEGER, INTENT(IN), OPTIONAL     :: stagger\n      REAL, INTENT(IN), OPTIONAL        :: latinc\n      REAL, INTENT(IN), OPTIONAL        :: loninc\n      REAL, INTENT(IN), OPTIONAL        :: lat1\n      REAL, INTENT(IN), OPTIONAL        :: lon1\n      REAL, INTENT(IN), OPTIONAL        :: lat0\n      REAL, INTENT(IN), OPTIONAL        :: lon0\n      REAL, INTENT(IN), OPTIONAL        :: dx\n      REAL, INTENT(IN), OPTIONAL        :: stdlon\n      REAL, INTENT(IN), OPTIONAL        :: truelat1\n      REAL, INTENT(IN), OPTIONAL        :: truelat2\n      REAL, INTENT(IN), OPTIONAL        :: knowni\n      REAL, INTENT(IN), OPTIONAL        :: knownj\n      REAL, INTENT(IN), OPTIONAL        :: phi\n      REAL, INTENT(IN), OPTIONAL        :: lambda\n      REAL, INTENT(IN), OPTIONAL        :: r_earth\n      TYPE(proj_info), INTENT(OUT)      :: proj\n\n      INTEGER :: iter\n      REAL :: dummy_lon1\n      REAL :: dummy_lon0\n      REAL :: dummy_stdlon\n\n      ! First, verify that mandatory parameters are present for the specified proj_code\n      IF ( proj_code == PROJ_LC ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(truelat2) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, truelat2, lat1, lon1, knowni, knownj, stdlon, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_PS ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, lat1, lon1, knonwi, knownj, stdlon, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_PS_WGS84 ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, lat1, lon1, knonwi, knownj, stdlon, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_ALBERS_NAD83 ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(truelat2) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, truelat2, lat1, lon1, knonwi, knownj, stdlon, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_MERC ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, lat1, lon1, knowni, knownj, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_LATLON ) THEN\n         IF ( .NOT.PRESENT(latinc) .OR. &\n              .NOT.PRESENT(loninc) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' latinc, loninc, knowni, knownj, lat1, lon1'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_CYL ) THEN\n         IF ( .NOT.PRESENT(latinc) .OR. &\n              .NOT.PRESENT(loninc) .OR. &\n              .NOT.PRESENT(stdlon) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' latinc, loninc, stdlon'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_CASSINI ) THEN\n         IF ( .NOT.PRESENT(latinc) .OR. &\n              .NOT.PRESENT(loninc) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(lat0) .OR. &\n              .NOT.PRESENT(lon0) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' latinc, loninc, lat1, lon1, knowni, knownj, lat0, lon0, stdlon'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_GAUSS ) THEN\n         IF ( .NOT.PRESENT(nlat) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(loninc) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' nlat, lat1, lon1, loninc'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_ROTLL ) THEN\n         IF ( .NOT.PRESENT(ixdim) .OR. &\n              .NOT.PRESENT(jydim) .OR. &\n              .NOT.PRESENT(phi) .OR. &\n              .NOT.PRESENT(lambda) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(stagger) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' ixdim, jydim, phi, lambda, lat1, lon1, stagger'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE\n         PRINT '(A,I2)', 'Unknown projection code: ', proj_code\n         STOP 'MAP_INIT'\n      END IF\n\n      ! Check for validity of mandatory variables in proj\n      IF ( PRESENT(lat1) ) THEN\n         IF ( ABS(lat1) .GT. 90. ) THEN\n            PRINT '(A)', 'Latitude of origin corner required as follows:'\n            PRINT '(A)', '    -90N <= lat1 < = 90.N'\n            STOP 'MAP_INIT'\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(lon1) ) THEN\n         dummy_lon1 = lon1\n         IF ( ABS(dummy_lon1) .GT. 180.) THEN\n            iter = 0\n            DO WHILE (ABS(dummy_lon1) > 180. .AND. iter < 10)\n               IF (dummy_lon1 < -180.) dummy_lon1 = dummy_lon1 + 360.\n               IF (dummy_lon1 > 180.) dummy_lon1 = dummy_lon1 - 360.\n               iter = iter + 1\n            END DO\n            IF (abs(dummy_lon1) > 180.) THEN\n               PRINT '(A)', 'Longitude of origin required as follows:'\n               PRINT '(A)', '   -180E <= lon1 <= 180W'\n               STOP 'MAP_INIT'\n            ENDIF\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(lon0) ) THEN\n         dummy_lon0 = lon0\n         IF ( ABS(dummy_lon0) .GT. 180.) THEN\n            iter = 0\n            DO WHILE (ABS(dummy_lon0) > 180. .AND. iter < 10)\n               IF (dummy_lon0 < -180.) dummy_lon0 = dummy_lon0 + 360.\n               IF (dummy_lon0 > 180.) dummy_lon0 = dummy_lon0 - 360.\n               iter = iter + 1\n            END DO\n            IF (abs(dummy_lon0) > 180.) THEN\n               PRINT '(A)', 'Longitude of pole required as follows:'\n               PRINT '(A)', '   -180E <= lon0 <= 180W'\n               STOP 'MAP_INIT'\n            ENDIF\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(dx) ) THEN\n         IF ((dx .LE. 0.).AND.(proj_code .NE. PROJ_LATLON)) THEN\n            PRINT '(A)', 'Require grid spacing (dx) in meters be positive'\n            STOP 'MAP_INIT'\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(stdlon) ) THEN\n         dummy_stdlon = stdlon\n         IF ((ABS(dummy_stdlon) > 180.).AND.(proj_code /= PROJ_MERC)) THEN\n            iter = 0\n            DO WHILE (ABS(dummy_stdlon) > 180. .AND. iter < 10)\n               IF (dummy_stdlon < -180.) dummy_stdlon = dummy_stdlon + 360.\n               IF (dummy_stdlon > 180.) dummy_stdlon = dummy_stdlon - 360.\n               iter = iter + 1\n            END DO\n            IF (abs(dummy_stdlon) > 180.) THEN\n               PRINT '(A)', 'Need orientation longitude (stdlon) as: '\n               PRINT '(A)', '   -180E <= stdlon <= 180W'\n               STOP 'MAP_INIT'\n            ENDIF\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(truelat1) ) THEN\n         IF (ABS(truelat1).GT.90.) THEN\n            PRINT '(A)', 'Set true latitude 1 for all projections'\n            STOP 'MAP_INIT'\n         ENDIF\n      ENDIF\n\n      CALL map_init(proj)\n      proj%code  = proj_code\n      IF ( PRESENT(lat1) )     proj%lat1     = lat1\n      IF ( PRESENT(lon1) )     proj%lon1     = dummy_lon1\n      IF ( PRESENT(lat0) )     proj%lat0     = lat0\n      IF ( PRESENT(lon0) )     proj%lon0     = dummy_lon0\n      IF ( PRESENT(latinc) )   proj%latinc   = latinc\n      IF ( PRESENT(loninc) )   proj%loninc   = loninc\n      IF ( PRESENT(knowni) )   proj%knowni   = knowni\n      IF ( PRESENT(knownj) )   proj%knownj   = knownj\n      IF ( PRESENT(dx) )       proj%dx       = dx\n      IF ( PRESENT(stdlon) )   proj%stdlon   = dummy_stdlon\n      IF ( PRESENT(truelat1) ) proj%truelat1 = truelat1\n      IF ( PRESENT(truelat2) ) proj%truelat2 = truelat2\n      IF ( PRESENT(nlat) )     proj%nlat     = nlat\n      IF ( PRESENT(nlon) )     proj%nlon     = nlon\n      IF ( PRESENT(ixdim) )    proj%ixdim    = ixdim\n      IF ( PRESENT(jydim) )    proj%jydim    = jydim\n      IF ( PRESENT(stagger) )  proj%stagger  = stagger\n      IF ( PRESENT(phi) )      proj%phi      = phi\n      IF ( PRESENT(lambda) )   proj%lambda   = lambda\n      IF ( PRESENT(r_earth) )  proj%re_m     = r_earth\n\n      IF ( PRESENT(dx) ) THEN\n         IF ( (proj_code == PROJ_LC) .OR. (proj_code == PROJ_PS) .OR. &\n              (proj_code == PROJ_PS_WGS84) .OR. (proj_code == PROJ_ALBERS_NAD83) .OR. &\n              (proj_code == PROJ_MERC) ) THEN\n            proj%dx = dx\n            IF (truelat1 .LT. 0.) THEN\n               proj%hemi = -1.0\n            ELSE\n               proj%hemi = 1.0\n            ENDIF\n            proj%rebydx = proj%re_m / dx\n         ENDIF\n      ENDIF\n\n      pick_proj: SELECT CASE(proj%code)\n\n         CASE(PROJ_PS)\n            CALL set_ps(proj)\n\n         CASE(PROJ_PS_WGS84)\n            CALL set_ps_wgs84(proj)\n\n         CASE(PROJ_ALBERS_NAD83)\n            CALL set_albers_nad83(proj)\n\n         CASE(PROJ_LC)\n            IF (ABS(proj%truelat2) .GT. 90.) THEN\n               proj%truelat2=proj%truelat1\n            ENDIF\n            CALL set_lc(proj)\n\n         CASE (PROJ_MERC)\n            CALL set_merc(proj)\n\n         CASE (PROJ_LATLON)\n\n         CASE (PROJ_GAUSS)\n            CALL set_gauss(proj)\n\n         CASE (PROJ_CYL)\n            CALL set_cyl(proj)\n\n         CASE (PROJ_CASSINI)\n            CALL set_cassini(proj)\n\n         CASE (PROJ_ROTLL)\n\n      END SELECT pick_proj\n      proj%init = .TRUE.\n\n      RETURN\n\n   END SUBROUTINE map_set\n\n\n   SUBROUTINE latlon_to_ij(proj, lat, lon, i, j)\n      ! Converts input lat/lon values to the cartesian (i,j) value\n      ! for the given projection.\n\n      IMPLICIT NONE\n      TYPE(proj_info), INTENT(IN)          :: proj\n      REAL, INTENT(IN)                     :: lat\n      REAL, INTENT(IN)                     :: lon\n      REAL, INTENT(OUT)                    :: i\n      REAL, INTENT(OUT)                    :: j\n\n      IF (.NOT.proj%init) THEN\n         PRINT '(A)', 'You have not called map_set for this projection'\n         STOP 'LATLON_TO_IJ'\n      ENDIF\n\n      SELECT CASE(proj%code)\n\n         CASE(PROJ_LATLON)\n            CALL llij_latlon(lat,lon,proj,i,j)\n\n         CASE(PROJ_MERC)\n            CALL llij_merc(lat,lon,proj,i,j)\n\n         CASE(PROJ_PS)\n            CALL llij_ps(lat,lon,proj,i,j)\n\n         CASE(PROJ_PS_WGS84)\n            CALL llij_ps_wgs84(lat,lon,proj,i,j)\n\n         CASE(PROJ_ALBERS_NAD83)\n            CALL llij_albers_nad83(lat,lon,proj,i,j)\n\n         CASE(PROJ_LC)\n            CALL llij_lc(lat,lon,proj,i,j)\n\n         CASE(PROJ_GAUSS)\n            CALL llij_gauss(lat,lon,proj,i,j)\n\n         CASE(PROJ_CYL)\n            CALL llij_cyl(lat,lon,proj,i,j)\n\n         CASE(PROJ_CASSINI)\n            CALL llij_cassini(lat,lon,proj,i,j)\n\n         CASE(PROJ_ROTLL)\n            CALL llij_rotlatlon(lat,lon,proj,i,j)\n\n         CASE DEFAULT\n            PRINT '(A,I2)', 'Unrecognized map projection code: ', proj%code\n            STOP 'LATLON_TO_IJ'\n\n      END SELECT\n\n      RETURN\n\n   END SUBROUTINE latlon_to_ij\n\n\n   SUBROUTINE ij_to_latlon(proj, i, j, lat, lon)\n      ! Computes geographical latitude and longitude for a given (i,j) point\n      ! in a grid with a projection of proj\n\n      IMPLICIT NONE\n      TYPE(proj_info),INTENT(IN)          :: proj\n      REAL, INTENT(IN)                    :: i\n      REAL, INTENT(IN)                    :: j\n      REAL, INTENT(OUT)                   :: lat\n      REAL, INTENT(OUT)                   :: lon\n\n      IF (.NOT.proj%init) THEN\n         PRINT '(A)', 'You have not called map_set for this projection'\n         STOP 'IJ_TO_LATLON'\n      ENDIF\n      SELECT CASE (proj%code)\n\n         CASE (PROJ_LATLON)\n            CALL ijll_latlon(i, j, proj, lat, lon)\n\n         CASE (PROJ_MERC)\n            CALL ijll_merc(i, j, proj, lat, lon)\n\n         CASE (PROJ_PS)\n            CALL ijll_ps(i, j, proj, lat, lon)\n\n         CASE (PROJ_PS_WGS84)\n            CALL ijll_ps_wgs84(i, j, proj, lat, lon)\n\n         CASE (PROJ_ALBERS_NAD83)\n            CALL ijll_albers_nad83(i, j, proj, lat, lon)\n\n         CASE (PROJ_LC)\n            CALL ijll_lc(i, j, proj, lat, lon)\n\n         CASE (PROJ_CYL)\n            CALL ijll_cyl(i, j, proj, lat, lon)\n\n         CASE (PROJ_CASSINI)\n            CALL ijll_cassini(i, j, proj, lat, lon)\n\n         CASE (PROJ_ROTLL)\n            CALL ijll_rotlatlon(i, j, proj, lat, lon)\n\n         CASE DEFAULT\n            PRINT '(A,I2)', 'Unrecognized map projection code: ', proj%code\n            STOP 'IJ_TO_LATLON'\n\n      END SELECT\n      RETURN\n   END SUBROUTINE ij_to_latlon\n\n\n   SUBROUTINE set_ps(proj)\n      ! Initializes a polar-stereographic map projection from the partially\n      ! filled proj structure. This routine computes the radius to the\n      ! southwest corner and computes the i/j location of the pole for use\n      ! in llij_ps and ijll_ps.\n      IMPLICIT NONE\n\n      ! Declare args\n      TYPE(proj_info), INTENT(INOUT)    :: proj\n\n      ! Local vars\n      REAL                              :: ala1\n      REAL                              :: alo1\n      REAL                              :: reflon\n      REAL                              :: scale_top\n\n      ! Executable code\n      reflon = proj%stdlon + 90.\n\n      ! Compute numerator term of map scale factor\n      scale_top = 1. + proj%hemi * SIN(proj%truelat1 * rad_per_deg)\n\n      ! Compute radius to lower-left (SW) corner\n      ala1 = proj%lat1 * rad_per_deg\n      proj%rsw = proj%rebydx*COS(ala1)*scale_top/(1.+proj%hemi*SIN(ala1))\n\n      ! Find the pole point\n      alo1 = (proj%lon1 - reflon) * rad_per_deg\n      proj%polei = proj%knowni - proj%rsw * COS(alo1)\n      proj%polej = proj%knownj - proj%hemi * proj%rsw * SIN(alo1)\n\n      RETURN\n\n   END SUBROUTINE set_ps\n\n\n   SUBROUTINE llij_ps(lat,lon,proj,i,j)\n      ! Given latitude (-90 to 90), longitude (-180 to 180), and the\n      ! standard polar-stereographic projection information via the\n      ! public proj structure, this routine returns the i/j indices which\n      ! if within the domain range from 1->nx and 1->ny, respectively.\n\n      IMPLICIT NONE\n\n      ! Delcare input arguments\n      REAL, INTENT(IN)               :: lat\n      REAL, INTENT(IN)               :: lon\n      TYPE(proj_info),INTENT(IN)     :: proj\n\n      ! Declare output arguments\n      REAL, INTENT(OUT)              :: i !(x-index)\n      REAL, INTENT(OUT)              :: j !(y-index)\n\n      ! Declare local variables\n\n      REAL                           :: reflon\n      REAL                           :: scale_top\n      REAL                           :: ala\n      REAL                           :: alo\n      REAL                           :: rm\n\n      ! BEGIN CODE\n\n      reflon = proj%stdlon + 90.\n\n      ! Compute numerator term of map scale factor\n\n      scale_top = 1. + proj%hemi * SIN(proj%truelat1 * rad_per_deg)\n\n      ! Find radius to desired point\n      ala = lat * rad_per_deg\n      rm = proj%rebydx * COS(ala) * scale_top/(1. + proj%hemi *SIN(ala))\n      alo = (lon - reflon) * rad_per_deg\n      i = proj%polei + rm * COS(alo)\n      j = proj%polej + proj%hemi * rm * SIN(alo)\n\n      RETURN\n\n   END SUBROUTINE llij_ps\n\n\n   SUBROUTINE ijll_ps(i, j, proj, lat, lon)\n\n      ! This is the inverse subroutine of llij_ps.  It returns the\n      ! latitude and longitude of an i/j point given the projection info \n      ! structure.\n\n      IMPLICIT NONE\n\n      ! Declare input arguments\n      REAL, INTENT(IN)                    :: i    ! Column\n      REAL, INTENT(IN)                    :: j    ! Row\n      TYPE (proj_info), INTENT(IN)        :: proj\n\n      ! Declare output arguments\n      REAL, INTENT(OUT)                   :: lat     ! -90 -> 90 north\n      REAL, INTENT(OUT)                   :: lon     ! -180 -> 180 East\n\n      ! Local variables\n      REAL                                :: reflon\n      REAL                                :: scale_top\n      REAL                                :: xx,yy\n      REAL                                :: gi2, r2\n      REAL                                :: arccos\n\n      ! Begin Code\n\n      ! Compute the reference longitude by rotating 90 degrees to the east\n      ! to find the longitude line parallel to the positive x-axis.\n      reflon = proj%stdlon + 90.\n\n      ! Compute numerator term of map scale factor\n      scale_top = 1. + proj%hemi * SIN(proj%truelat1 * rad_per_deg)\n\n      ! Compute radius to point of interest\n      xx = i - proj%polei\n      yy = (j - proj%polej) * proj%hemi\n      r2 = xx**2 + yy**2\n\n      ! Now the magic code\n      IF (r2 .EQ. 0.) THEN\n         lat = proj%hemi * 90.\n         lon = reflon\n      ELSE\n         gi2 = (proj%rebydx * scale_top)**2.\n         lat = deg_per_rad * proj%hemi * ASIN((gi2-r2)/(gi2+r2))\n         arccos = ACOS(xx/SQRT(r2))\n         IF (yy .GT. 0) THEN\n            lon = reflon + deg_per_rad * arccos\n         ELSE\n            lon = reflon - deg_per_rad * arccos\n         ENDIF\n      ENDIF\n\n      ! Convert to a -180 -> 180 East convention\n      IF (lon .GT. 180.) lon = lon - 360.\n      IF (lon .LT. -180.) lon = lon + 360.\n\n      RETURN\n\n   END SUBROUTINE ijll_ps\n\n\n   SUBROUTINE set_ps_wgs84(proj)\n      ! Initializes a polar-stereographic map projection (WGS84 ellipsoid) \n      ! from the partially filled proj structure. This routine computes the \n      ! radius to the southwest corner and computes the i/j location of the \n      ! pole for use in llij_ps and ijll_ps.\n\n      IMPLICIT NONE\n\n      ! Arguments\n      TYPE(proj_info), INTENT(INOUT)    :: proj\n\n      ! Local variables\n      real :: h, mc, tc, t, rho\n\n      h = proj%hemi\n\n      mc = cos(h*proj%truelat1*rad_per_deg)/sqrt(1.0-(E_WGS84*sin(h*proj%truelat1*rad_per_deg))**2.0)\n      tc = sqrt(((1.0-sin(h*proj%truelat1*rad_per_deg))/(1.0+sin(h*proj%truelat1*rad_per_deg)))* &\n                (((1.0+E_WGS84*sin(h*proj%truelat1*rad_per_deg))/(1.0-E_WGS84*sin(h*proj%truelat1*rad_per_deg)))**E_WGS84 ))\n\n      ! Find the i/j location of reference lat/lon with respect to the pole of the projection\n      t = sqrt(((1.0-sin(h*proj%lat1*rad_per_deg))/(1.0+sin(h*proj%lat1*rad_per_deg)))* &\n               (((1.0+E_WGS84*sin(h*proj%lat1*rad_per_deg))/(1.0-E_WGS84*sin(h*proj%lat1*rad_per_deg)) )**E_WGS84 ) )\n      rho = h * (A_WGS84 / proj%dx) * mc * t / tc\n      proj%polei = rho * sin((h*proj%lon1 - h*proj%stdlon)*rad_per_deg)\n      proj%polej = -rho * cos((h*proj%lon1 - h*proj%stdlon)*rad_per_deg)\n\n      RETURN\n\n   END SUBROUTINE set_ps_wgs84\n\n\n   SUBROUTINE llij_ps_wgs84(lat,lon,proj,i,j)\n      ! Given latitude (-90 to 90), longitude (-180 to 180), and the\n      ! standard polar-stereographic projection information via the\n      ! public proj structure, this routine returns the i/j indices which\n      ! if within the domain range from 1->nx and 1->ny, respectively.\n\n      IMPLICIT NONE\n\n      ! Arguments\n      REAL, INTENT(IN)               :: lat\n      REAL, INTENT(IN)               :: lon\n      REAL, INTENT(OUT)              :: i !(x-index)\n      REAL, INTENT(OUT)              :: j !(y-index)\n      TYPE(proj_info),INTENT(IN)     :: proj\n\n      ! Local variables\n      real :: h, mc, tc, t, rho\n\n      h = proj%hemi\n\n      mc = cos(h*proj%truelat1*rad_per_deg)/sqrt(1.0-(E_WGS84*sin(h*proj%truelat1*rad_per_deg))**2.0)\n      tc = sqrt(((1.0-sin(h*proj%truelat1*rad_per_deg))/(1.0+sin(h*proj%truelat1*rad_per_deg)))* &\n                (((1.0+E_WGS84*sin(h*proj%truelat1*rad_per_deg))/(1.0-E_WGS84*sin(h*proj%truelat1*rad_per_deg)))**E_WGS84 ))\n\n      t = sqrt(((1.0-sin(h*lat*rad_per_deg))/(1.0+sin(h*lat*rad_per_deg))) * &\n               (((1.0+E_WGS84*sin(h*lat*rad_per_deg))/(1.0-E_WGS84*sin(h*lat*rad_per_deg)))**E_WGS84))\n\n      ! Find the x/y location of the requested lat/lon with respect to the pole of the projection\n      rho = (A_WGS84 / proj%dx) * mc * t / tc\n      i = h *  rho * sin((h*lon - h*proj%stdlon)*rad_per_deg)\n      j = h *(-rho)* cos((h*lon - h*proj%stdlon)*rad_per_deg)\n\n      ! Get i/j relative to reference i/j\n      i = proj%knowni + (i - proj%polei)\n      j = proj%knownj + (j - proj%polej)\n\n      RETURN\n\n   END SUBROUTINE llij_ps_wgs84\n\n\n   SUBROUTINE ijll_ps_wgs84(i, j, proj, lat, lon)\n\n      ! This is the inverse subroutine of llij_ps.  It returns the\n      ! latitude and longitude of an i/j point given the projection info \n      ! structure.\n\n      implicit none\n\n      ! Arguments\n      REAL, INTENT(IN)                    :: i    ! Column\n      REAL, INTENT(IN)                    :: j    ! Row\n      REAL, INTENT(OUT)                   :: lat     ! -90 -> 90 north\n      REAL, INTENT(OUT)                   :: lon     ! -180 -> 180 East\n      TYPE (proj_info), INTENT(IN)        :: proj\n\n      ! Local variables\n      real :: h, mc, tc, t, rho, x, y\n      real :: chi, a, b, c, d\n\n      h = proj%hemi\n      x = (i - proj%knowni + proj%polei)\n      y = (j - proj%knownj + proj%polej)\n\n      mc = cos(h*proj%truelat1*rad_per_deg)/sqrt(1.0-(E_WGS84*sin(h*proj%truelat1*rad_per_deg))**2.0)\n      tc = sqrt(((1.0-sin(h*proj%truelat1*rad_per_deg))/(1.0+sin(h*proj%truelat1*rad_per_deg))) * &\n                (((1.0+E_WGS84*sin(h*proj%truelat1*rad_per_deg))/(1.0-E_WGS84*sin(h*proj%truelat1*rad_per_deg)))**E_WGS84 ))\n\n      rho = sqrt((x*proj%dx)**2.0 + (y*proj%dx)**2.0)\n      t = rho * tc / (A_WGS84 * mc)\n\n      lon = h*proj%stdlon + h*atan2(h*x,h*(-y))\n\n      chi = PI/2.0-2.0*atan(t)\n      a = 1./2.*E_WGS84**2. + 5./24.*E_WGS84**4. +  1./40.*E_WGS84**6.  +    73./2016.*E_WGS84**8.\n      b =                     7./24.*E_WGS84**4. + 29./120.*E_WGS84**6. + 54113./40320.*E_WGS84**8.\n      c =                                           7./30.*E_WGS84**6.  +    81./280.*E_WGS84**8.\n      d =                                                                  4279./20160.*E_WGS84**8.\n\n      lat = chi + sin(2.*chi)*(a + cos(2.*chi)*(b + cos(2.*chi)*(c + d*cos(2.*chi))))\n      lat = h * lat\n\n      lat = lat*deg_per_rad\n      lon = lon*deg_per_rad\n\n      RETURN\n\n   END SUBROUTINE ijll_ps_wgs84\n\n\n   SUBROUTINE set_albers_nad83(proj)\n      ! Initializes an Albers equal area map projection (NAD83 ellipsoid) \n      ! from the partially filled proj structure. This routine computes the \n      ! radius to the southwest corner and computes the i/j location of the \n      ! pole for use in llij_albers_nad83 and ijll_albers_nad83.\n\n      IMPLICIT NONE\n\n      ! Arguments\n      TYPE(proj_info), INTENT(INOUT)    :: proj\n\n      ! Local variables\n      real :: h, m1, m2, q1, q2, theta, q, sinphi\n\n      h = proj%hemi\n\n      m1 = cos(h*proj%truelat1*rad_per_deg)/sqrt(1.0-(E_NAD83*sin(h*proj%truelat1*rad_per_deg))**2.0)\n      m2 = cos(h*proj%truelat2*rad_per_deg)/sqrt(1.0-(E_NAD83*sin(h*proj%truelat2*rad_per_deg))**2.0)\n\n      sinphi = sin(proj%truelat1*rad_per_deg)\n      q1 = (1.0-E_NAD83**2.0) * &\n           ((sinphi/(1.0-(E_NAD83*sinphi)**2.0)) - 1.0/(2.0*E_NAD83) * log((1.0-E_NAD83*sinphi)/(1.0+E_NAD83*sinphi)))\n\n      sinphi = sin(proj%truelat2*rad_per_deg)\n      q2 = (1.0-E_NAD83**2.0) * &\n           ((sinphi/(1.0-(E_NAD83*sinphi)**2.0)) - 1.0/(2.0*E_NAD83) * log((1.0-E_NAD83*sinphi)/(1.0+E_NAD83*sinphi)))\n\n      if (proj%truelat1 == proj%truelat2) then\n         proj%nc = sin(proj%truelat1*rad_per_deg)\n      else\n         proj%nc = (m1**2.0 - m2**2.0) / (q2 - q1)\n      end if\n\n      proj%bigc = m1**2.0 + proj%nc*q1\n\n      ! Find the i/j location of reference lat/lon with respect to the pole of the projection\n      sinphi = sin(proj%lat1*rad_per_deg)\n      q = (1.0-E_NAD83**2.0) * &\n           ((sinphi/(1.0-(E_NAD83*sinphi)**2.0)) - 1.0/(2.0*E_NAD83) * log((1.0-E_NAD83*sinphi)/(1.0+E_NAD83*sinphi)))\n\n      proj%rho0 = h * (A_NAD83 / proj%dx) * sqrt(proj%bigc - proj%nc * q) / proj%nc \n      theta = proj%nc*(proj%lon1 - proj%stdlon)*rad_per_deg\n\n      proj%polei = proj%rho0 * sin(h*theta)\n      proj%polej = proj%rho0 - proj%rho0 * cos(h*theta)\n\n      RETURN\n\n   END SUBROUTINE set_albers_nad83\n\n\n   SUBROUTINE llij_albers_nad83(lat,lon,proj,i,j)\n      ! Given latitude (-90 to 90), longitude (-180 to 180), and the\n      ! standard projection information via the\n      ! public proj structure, this routine returns the i/j indices which\n      ! if within the domain range from 1->nx and 1->ny, respectively.\n\n      IMPLICIT NONE\n\n      ! Arguments\n      REAL, INTENT(IN)               :: lat\n      REAL, INTENT(IN)               :: lon\n      REAL, INTENT(OUT)              :: i !(x-index)\n      REAL, INTENT(OUT)              :: j !(y-index)\n      TYPE(proj_info),INTENT(IN)     :: proj\n\n      ! Local variables\n      real :: h, q, rho, theta, sinphi\n\n      h = proj%hemi\n\n      sinphi = sin(h*lat*rad_per_deg)\n\n      ! Find the x/y location of the requested lat/lon with respect to the pole of the projection\n      q = (1.0-E_NAD83**2.0) * &\n           ((sinphi/(1.0-(E_NAD83*sinphi)**2.0)) - 1.0/(2.0*E_NAD83) * log((1.0-E_NAD83*sinphi)/(1.0+E_NAD83*sinphi)))\n\n      rho = h * (A_NAD83 / proj%dx) * sqrt(proj%bigc - proj%nc * q) / proj%nc\n      theta = proj%nc * (h*lon - h*proj%stdlon)*rad_per_deg\n\n      i = h*rho*sin(theta)\n      j = h*proj%rho0 - h*rho*cos(theta)\n\n      ! Get i/j relative to reference i/j\n      i = proj%knowni + (i - proj%polei)\n      j = proj%knownj + (j - proj%polej)\n\n      RETURN\n\n   END SUBROUTINE llij_albers_nad83\n\n\n   SUBROUTINE ijll_albers_nad83(i, j, proj, lat, lon)\n\n      ! This is the inverse subroutine of llij_albers_nad83.  It returns the \n      ! latitude and longitude of an i/j point given the projection info \n      ! structure.\n\n      implicit none\n\n      ! Arguments\n      REAL, INTENT(IN)                    :: i    ! Column\n      REAL, INTENT(IN)                    :: j    ! Row\n      REAL, INTENT(OUT)                   :: lat     ! -90 -> 90 north\n      REAL, INTENT(OUT)                   :: lon     ! -180 -> 180 East\n      TYPE (proj_info), INTENT(IN)        :: proj\n\n      ! Local variables\n      real :: h, q, rho, theta, beta, x, y\n      real :: a, b, c\n\n      h = proj%hemi\n\n      x = (i - proj%knowni + proj%polei)\n      y = (j - proj%knownj + proj%polej)\n\n      rho = sqrt(x**2.0 + (proj%rho0 - y)**2.0)\n      theta = atan2(x, proj%rho0-y)\n\n      q = (proj%bigc - (rho*proj%nc*proj%dx/A_NAD83)**2.0) / proj%nc\n\n      beta = asin(q/(1.0 - log((1.0-E_NAD83)/(1.0+E_NAD83))*(1.0-E_NAD83**2.0)/(2.0*E_NAD83)))\n      a = 1./3.*E_NAD83**2. + 31./180.*E_NAD83**4. + 517./5040.*E_NAD83**6.\n      b =                     23./360.*E_NAD83**4. + 251./3780.*E_NAD83**6.\n      c =                                            761./45360.*E_NAD83**6.\n\n      lat = beta + a*sin(2.*beta) + b*sin(4.*beta) + c*sin(6.*beta)\n\n      lat = h*lat*deg_per_rad\n      lon = proj%stdlon + theta*deg_per_rad/proj%nc\n\n      RETURN\n\n   END SUBROUTINE ijll_albers_nad83\n\n\n   SUBROUTINE set_lc(proj)\n      ! Initialize the remaining items in the proj structure for a\n      ! lambert conformal grid.\n\n      IMPLICIT NONE\n\n      TYPE(proj_info), INTENT(INOUT)     :: proj\n\n      REAL                               :: arg\n      REAL                               :: deltalon1\n      REAL                               :: tl1r\n      REAL                               :: ctl1r\n\n      ! Compute cone factor\n      CALL lc_cone(proj%truelat1, proj%truelat2, proj%cone)\n\n      ! Compute longitude differences and ensure we stay out of the\n      ! forbidden \"cut zone\"\n      deltalon1 = proj%lon1 - proj%stdlon\n      IF (deltalon1 .GT. +180.) deltalon1 = deltalon1 - 360.\n      IF (deltalon1 .LT. -180.) deltalon1 = deltalon1 + 360.\n\n      ! Convert truelat1 to radian and compute COS for later use\n      tl1r = proj%truelat1 * rad_per_deg\n      ctl1r = COS(tl1r)\n\n      ! Compute the radius to our known lower-left (SW) corner\n      proj%rsw = proj%rebydx * ctl1r/proj%cone * &\n             (TAN((90.*proj%hemi-proj%lat1)*rad_per_deg/2.) / &\n              TAN((90.*proj%hemi-proj%truelat1)*rad_per_deg/2.))**proj%cone\n\n      ! Find pole point\n      arg = proj%cone*(deltalon1*rad_per_deg)\n      proj%polei = proj%hemi*proj%knowni - proj%hemi * proj%rsw * SIN(arg)\n      proj%polej = proj%hemi*proj%knownj + proj%rsw * COS(arg)\n\n      RETURN\n\n   END SUBROUTINE set_lc\n\n\n   SUBROUTINE lc_cone(truelat1, truelat2, cone)\n\n   ! Subroutine to compute the cone factor of a Lambert Conformal projection\n\n      IMPLICIT NONE\n\n      ! Input Args\n      REAL, INTENT(IN)             :: truelat1  ! (-90 -> 90 degrees N)\n      REAL, INTENT(IN)             :: truelat2  !   \"   \"  \"   \"     \"\n\n      ! Output Args\n      REAL, INTENT(OUT)            :: cone\n\n      ! Locals\n\n      ! BEGIN CODE\n\n      ! First, see if this is a secant or tangent projection.  For tangent\n      ! projections, truelat1 = truelat2 and the cone is tangent to the\n      ! Earth's surface at this latitude.  For secant projections, the cone\n      ! intersects the Earth's surface at each of the distinctly different\n      ! latitudes\n      IF (ABS(truelat1-truelat2) .GT. 0.1) THEN\n         cone = ALOG10(COS(truelat1*rad_per_deg)) - &\n                ALOG10(COS(truelat2*rad_per_deg))\n         cone = cone /(ALOG10(TAN((45.0 - ABS(truelat1)/2.0) * rad_per_deg)) - &\n                ALOG10(TAN((45.0 - ABS(truelat2)/2.0) * rad_per_deg)))        \n      ELSE\n         cone = SIN(ABS(truelat1)*rad_per_deg )\n      ENDIF\n\n      RETURN\n\n   END SUBROUTINE lc_cone\n\n\n   SUBROUTINE ijll_lc( i, j, proj, lat, lon)\n\n   ! Subroutine to convert from the (i,j) cartesian coordinate to the\n   ! geographical latitude and longitude for a Lambert Conformal projection.\n\n   ! History:\n   ! 25 Jul 01: Corrected by B. Shaw, NOAA/FSL\n   !\n      IMPLICIT NONE\n\n      ! Input Args\n      REAL, INTENT(IN)              :: i        ! Cartesian X coordinate\n      REAL, INTENT(IN)              :: j        ! Cartesian Y coordinate\n      TYPE(proj_info),INTENT(IN)    :: proj     ! Projection info structure\n\n      ! Output Args\n      REAL, INTENT(OUT)             :: lat      ! Latitude (-90->90 deg N)\n      REAL, INTENT(OUT)             :: lon      ! Longitude (-180->180 E)\n\n      ! Locals\n      REAL                          :: inew\n      REAL                          :: jnew\n      REAL                          :: r\n      REAL                          :: chi,chi1,chi2\n      REAL                          :: r2\n      REAL                          :: xx\n      REAL                          :: yy\n\n      ! BEGIN CODE\n\n      chi1 = (90. - proj%hemi*proj%truelat1)*rad_per_deg\n      chi2 = (90. - proj%hemi*proj%truelat2)*rad_per_deg\n\n      ! See if we are in the southern hemispere and flip the indices\n      ! if we are.\n      inew = proj%hemi * i\n      jnew = proj%hemi * j\n\n      ! Compute radius**2 to i/j location\n      xx = inew - proj%polei\n      yy = proj%polej - jnew\n      r2 = (xx*xx + yy*yy)\n      r = SQRT(r2)/proj%rebydx\n\n      ! Convert to lat/lon\n      IF (r2 .EQ. 0.) THEN\n         lat = proj%hemi * 90.\n         lon = proj%stdlon\n      ELSE\n\n         ! Longitude\n         lon = proj%stdlon + deg_per_rad * ATAN2(proj%hemi*xx,yy)/proj%cone\n         lon = MOD(lon+360., 360.)\n\n         ! Latitude.  Latitude determined by solving an equation adapted \n         ! from:\n         !  Maling, D.H., 1973: Coordinate Systems and Map Projections\n         ! Equations #20 in Appendix I.\n\n         IF (chi1 .EQ. chi2) THEN\n            chi = 2.0*ATAN( ( r/TAN(chi1) )**(1./proj%cone) * TAN(chi1*0.5) )\n         ELSE\n            chi = 2.0*ATAN( (r*proj%cone/SIN(chi1))**(1./proj%cone) * TAN(chi1*0.5)) \n         ENDIF\n         lat = (90.0-chi*deg_per_rad)*proj%hemi\n\n      ENDIF\n\n      IF (lon .GT. +180.) lon = lon - 360.\n      IF (lon .LT. -180.) lon = lon + 360.\n\n      RETURN\n\n   END SUBROUTINE ijll_lc\n\n\n   SUBROUTINE llij_lc( lat, lon, proj, i, j)\n\n   ! Subroutine to compute the geographical latitude and longitude values\n   ! to the cartesian x/y on a Lambert Conformal projection.\n\n      IMPLICIT NONE\n\n      ! Input Args\n      REAL, INTENT(IN)              :: lat      ! Latitude (-90->90 deg N)\n      REAL, INTENT(IN)              :: lon      ! Longitude (-180->180 E)\n      TYPE(proj_info),INTENT(IN)      :: proj     ! Projection info structure\n\n      ! Output Args\n      REAL, INTENT(OUT)             :: i        ! Cartesian X coordinate\n      REAL, INTENT(OUT)             :: j        ! Cartesian Y coordinate\n\n      ! Locals\n      REAL                          :: arg\n      REAL                          :: deltalon\n      REAL                          :: tl1r\n      REAL                          :: rm\n      REAL                          :: ctl1r\n\n\n      ! BEGIN CODE\n\n      ! Compute deltalon between known longitude and standard lon and ensure\n      ! it is not in the cut zone\n      deltalon = lon - proj%stdlon\n      IF (deltalon .GT. +180.) deltalon = deltalon - 360.\n      IF (deltalon .LT. -180.) deltalon = deltalon + 360.\n\n      ! Convert truelat1 to radian and compute COS for later use\n      tl1r = proj%truelat1 * rad_per_deg\n      ctl1r = COS(tl1r)\n\n      ! Radius to desired point\n      rm = proj%rebydx * ctl1r/proj%cone * &\n           (TAN((90.*proj%hemi-lat)*rad_per_deg/2.) / &\n            TAN((90.*proj%hemi-proj%truelat1)*rad_per_deg/2.))**proj%cone\n\n      arg = proj%cone*(deltalon*rad_per_deg)\n      i = proj%polei + proj%hemi * rm * SIN(arg)\n      j = proj%polej - rm * COS(arg)\n\n      ! Finally, if we are in the southern hemisphere, flip the i/j\n      ! values to a coordinate system where (1,1) is the SW corner\n      ! (what we assume) which is different than the original NCEP\n      ! algorithms which used the NE corner as the origin in the\n      ! southern hemisphere (left-hand vs. right-hand coordinate?)\n      i = proj%hemi * i\n      j = proj%hemi * j\n\n      RETURN\n   END SUBROUTINE llij_lc\n\n\n   SUBROUTINE set_merc(proj)\n\n      ! Sets up the remaining basic elements for the mercator projection\n\n      IMPLICIT NONE\n      TYPE(proj_info), INTENT(INOUT)       :: proj\n      REAL                                 :: clain\n\n\n      !  Preliminary variables\n\n      clain = COS(rad_per_deg*proj%truelat1)\n      proj%dlon = proj%dx / (proj%re_m * clain)\n\n      ! Compute distance from equator to origin, and store in the\n      ! proj%rsw tag.\n\n      proj%rsw = 0.\n      IF (proj%lat1 .NE. 0.) THEN\n         proj%rsw = (ALOG(TAN(0.5*((proj%lat1+90.)*rad_per_deg))))/proj%dlon\n      ENDIF\n\n      RETURN\n\n   END SUBROUTINE set_merc\n\n\n   SUBROUTINE llij_merc(lat, lon, proj, i, j)\n\n      ! Compute i/j coordinate from lat lon for mercator projection\n\n      IMPLICIT NONE\n      REAL, INTENT(IN)              :: lat\n      REAL, INTENT(IN)              :: lon\n      TYPE(proj_info),INTENT(IN)    :: proj\n      REAL,INTENT(OUT)              :: i\n      REAL,INTENT(OUT)              :: j\n      REAL                          :: deltalon\n\n      deltalon = lon - proj%lon1\n      IF (deltalon .LT. -180.) deltalon = deltalon + 360.\n      IF (deltalon .GT. 180.) deltalon = deltalon - 360.\n      i = proj%knowni + (deltalon/(proj%dlon*deg_per_rad))\n      j = proj%knownj + (ALOG(TAN(0.5*((lat + 90.) * rad_per_deg)))) / &\n             proj%dlon - proj%rsw\n\n      RETURN\n\n   END SUBROUTINE llij_merc\n\n\n   SUBROUTINE ijll_merc(i, j, proj, lat, lon)\n\n      ! Compute the lat/lon from i/j for mercator projection\n\n      IMPLICIT NONE\n      REAL,INTENT(IN)               :: i\n      REAL,INTENT(IN)               :: j\n      TYPE(proj_info),INTENT(IN)    :: proj\n      REAL, INTENT(OUT)             :: lat\n      REAL, INTENT(OUT)             :: lon\n\n\n      lat = 2.0*ATAN(EXP(proj%dlon*(proj%rsw + j-proj%knownj)))*deg_per_rad - 90.\n      lon = (i-proj%knowni)*proj%dlon*deg_per_rad + proj%lon1\n      IF (lon.GT.180.) lon = lon - 360.\n      IF (lon.LT.-180.) lon = lon + 360.\n      RETURN\n\n   END SUBROUTINE ijll_merc\n\n\n   SUBROUTINE llij_latlon(lat, lon, proj, i, j)\n\n      ! Compute the i/j location of a lat/lon on a LATLON grid.\n      IMPLICIT NONE\n      REAL, INTENT(IN)             :: lat\n      REAL, INTENT(IN)             :: lon\n      TYPE(proj_info), INTENT(IN)  :: proj\n      REAL, INTENT(OUT)            :: i\n      REAL, INTENT(OUT)            :: j\n\n      REAL                         :: deltalat\n      REAL                         :: deltalon\n\n      ! Compute deltalat and deltalon as the difference between the input \n      ! lat/lon and the origin lat/lon\n      deltalat = lat - proj%lat1\n      deltalon = lon - proj%lon1\n\n      ! Compute i/j\n      i = deltalon/proj%loninc\n      j = deltalat/proj%latinc\n\n      i = i + proj%knowni\n      j = j + proj%knownj\n\n      RETURN\n\n   END SUBROUTINE llij_latlon\n\n\n   SUBROUTINE ijll_latlon(i, j, proj, lat, lon)\n\n      ! Compute the lat/lon location of an i/j on a LATLON grid.\n      IMPLICIT NONE\n      REAL, INTENT(IN)             :: i\n      REAL, INTENT(IN)             :: j\n      TYPE(proj_info), INTENT(IN)  :: proj\n      REAL, INTENT(OUT)            :: lat\n      REAL, INTENT(OUT)            :: lon\n\n      REAL                         :: i_work, j_work\n      REAL                         :: deltalat\n      REAL                         :: deltalon\n\n      i_work = i - proj%knowni\n      j_work = j - proj%knownj\n\n      ! Compute deltalat and deltalon\n      deltalat = j_work*proj%latinc\n      deltalon = i_work*proj%loninc\n\n      lat = proj%lat1 + deltalat\n      lon = proj%lon1 + deltalon\n\n      RETURN\n\n   END SUBROUTINE ijll_latlon\n\n\n   SUBROUTINE set_cyl(proj)\n\n      implicit none\n\n      ! Arguments\n      type(proj_info), intent(inout) :: proj\n\n      proj%hemi = 1.0\n\n   END SUBROUTINE set_cyl\n\n\n   SUBROUTINE llij_cyl(lat, lon, proj, i, j)\n\n      implicit none\n\n      ! Arguments\n      real, intent(in) :: lat, lon\n      real, intent(out) :: i, j\n      type(proj_info), intent(in) :: proj\n\n      ! Local variables\n      real :: deltalat\n      real :: deltalon\n\n      ! Compute deltalat and deltalon as the difference between the input\n      ! lat/lon and the origin lat/lon\n      deltalat = lat - proj%lat1\n!      deltalon = lon - proj%stdlon\n      deltalon = lon - proj%lon1\n\n      if (deltalon <   0.) deltalon = deltalon + 360.\n      if (deltalon > 360.) deltalon = deltalon - 360.\n\n      ! Compute i/j\n      i = deltalon/proj%loninc\n      j = deltalat/proj%latinc\n\n      if (i <= 0.)              i = i + 360./proj%loninc\n      if (i > 360./proj%loninc) i = i - 360./proj%loninc\n\n      i = i + proj%knowni\n      j = j + proj%knownj\n\n   END SUBROUTINE llij_cyl\n\n\n   SUBROUTINE ijll_cyl(i, j, proj, lat, lon)\n\n      implicit none\n\n      ! Arguments\n      real, intent(in) :: i, j\n      real, intent(out) :: lat, lon\n      type(proj_info), intent(in) :: proj\n\n      ! Local variables\n      real :: deltalat\n      real :: deltalon\n      real :: i_work, j_work\n\n      i_work = i - proj%knowni\n      j_work = j - proj%knownj\n\n      if (i_work < 0.)              i_work = i_work + 360./proj%loninc\n      if (i_work >= 360./proj%loninc) i_work = i_work - 360./proj%loninc\n\n      ! Compute deltalat and deltalon\n      deltalat = j_work*proj%latinc\n      deltalon = i_work*proj%loninc\n\n      lat = deltalat + proj%lat1\n!      lon = deltalon + proj%stdlon\n      lon = deltalon + proj%lon1\n\n      if (lon < -180.) lon = lon + 360.\n      if (lon >  180.) lon = lon - 360.\n\n   END SUBROUTINE ijll_cyl\n\n\n   SUBROUTINE set_cassini(proj)\n\n      implicit none\n\n      ! Arguments\n      type(proj_info), intent(inout) :: proj\n\n      ! Local variables\n      real :: comp_lat, comp_lon\n      logical :: global_domain\n\n      proj%hemi = 1.0\n\n      ! Try to determine whether this domain has global coverage\n      if (abs(proj%lat1 - proj%latinc/2. + 90.) < 0.001 .and. &\n          abs(mod(proj%lon1 - proj%loninc/2. - proj%stdlon,360.)) < 0.001) then\n         global_domain = .true.\n      else\n         global_domain = .false.\n      end if\n\n      if (abs(proj%lat0) /= 90. .and. .not.global_domain) then\n         call rotate_coords(proj%lat1,proj%lon1,comp_lat,comp_lon,proj%lat0,proj%lon0,proj%stdlon,-1)\n         proj%lat1 = comp_lat\n         proj%lon1 = comp_lon\n      end if\n\n   END SUBROUTINE set_cassini\n\n\n   SUBROUTINE llij_cassini(lat, lon, proj, i, j)\n\n      implicit none\n\n      ! Arguments\n      real, intent(in) :: lat, lon\n      real, intent(out) :: i, j\n      type(proj_info), intent(in) :: proj\n\n      ! Local variables\n      real :: comp_lat, comp_lon\n\n      ! Convert geographic to computational lat/lon\n      if (abs(proj%lat0) /= 90.) then\n         call rotate_coords(lat,lon,comp_lat,comp_lon,proj%lat0,proj%lon0,proj%stdlon,-1)\n      else\n         comp_lat = lat\n         comp_lon = lon\n      end if\n\n      ! Convert computational lat/lon to i/j\n      call llij_cyl(comp_lat, comp_lon, proj, i, j)\n\n   END SUBROUTINE llij_cassini\n\n\n   SUBROUTINE ijll_cassini(i, j, proj, lat, lon)\n\n      implicit none\n\n      ! Arguments\n      real, intent(in) :: i, j\n      real, intent(out) :: lat, lon\n      type(proj_info), intent(in) :: proj\n\n      ! Local variables\n      real :: comp_lat, comp_lon\n\n      ! Convert i/j to computational lat/lon\n      call ijll_cyl(i, j, proj, comp_lat, comp_lon)\n\n      ! Convert computational to geographic lat/lon\n      if (abs(proj%lat0) /= 90.) then\n         call rotate_coords(comp_lat,comp_lon,lat,lon,proj%lat0,proj%lon0,proj%stdlon,1)\n      else\n         lat = comp_lat\n         lon = comp_lon\n      end if\n\n   END SUBROUTINE ijll_cassini\n\n\n   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \n   ! Purpose: Converts between computational and geographic lat/lon for Cassini\n   !\n   ! Notes: This routine was provided by Bill Skamarock, 2007-03-27\n   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \n   SUBROUTINE rotate_coords(ilat,ilon,olat,olon,lat_np,lon_np,lon_0,direction)\n\n      IMPLICIT NONE\n\n      REAL, INTENT(IN   ) :: ilat, ilon\n      REAL, INTENT(  OUT) :: olat, olon\n      REAL, INTENT(IN   ) :: lat_np, lon_np, lon_0\n      INTEGER, INTENT(IN  ), OPTIONAL :: direction\n      ! >=0, default : computational -> geographical\n      ! < 0          : geographical  -> computational\n\n      REAL :: rlat, rlon\n      REAL :: phi_np, lam_np, lam_0, dlam\n      REAL :: sinphi, cosphi, coslam, sinlam\n\n      ! Convert all angles to radians\n      phi_np = lat_np * rad_per_deg\n      lam_np = lon_np * rad_per_deg\n      lam_0  = lon_0  * rad_per_deg\n      rlat = ilat * rad_per_deg\n      rlon = ilon * rad_per_deg\n\n      IF (PRESENT(direction) .AND. (direction < 0)) THEN\n         ! The equations are exactly the same except for one small difference\n         ! with respect to longitude ...\n         dlam = PI - lam_0\n      ELSE\n         dlam = lam_np\n      END IF\n      sinphi = COS(phi_np)*COS(rlat)*COS(rlon-dlam) + SIN(phi_np)*SIN(rlat)\n      cosphi = SQRT(1.-sinphi*sinphi)\n      coslam = SIN(phi_np)*COS(rlat)*COS(rlon-dlam) - COS(phi_np)*SIN(rlat)\n      sinlam = COS(rlat)*SIN(rlon-dlam)\n      IF ( cosphi /= 0. ) THEN\n         coslam = coslam/cosphi\n         sinlam = sinlam/cosphi\n      END IF\n      olat = deg_per_rad*ASIN(sinphi)\n      olon = deg_per_rad*(ATAN2(sinlam,coslam)-dlam-lam_0+lam_np)\n      ! Both of my F90 text books prefer the DO-EXIT form, and claim it is faster\n      ! when optimization is turned on (as we will always do...)\n      DO\n         IF (olon >= -180.) EXIT\n         olon = olon + 360.\n      END DO\n      DO\n         IF (olon <=  180.) EXIT\n         olon = olon - 360.\n      END DO\n\n   END SUBROUTINE rotate_coords\n\n\n   SUBROUTINE llij_rotlatlon(lat, lon, proj, i_real, j_real)\n\n      IMPLICIT NONE\n\n      ! Arguments\n      REAL, INTENT(IN) :: lat, lon\n      REAL             :: i, j\n      REAL, INTENT(OUT) :: i_real, j_real\n      TYPE (proj_info), INTENT(IN) :: proj\n\n      ! Local variables\n      INTEGER :: ii,imt,jj,jmt,k,krows,ncol,nrow,iri\n      REAL(KIND=HIGH) :: dphd,dlmd !Grid increments, degrees\n      REAL(KIND=HIGH) :: glatd  !Geographic latitude, positive north\n      REAL(KIND=HIGH) :: glond  !Geographic longitude, positive west\n      REAL(KIND=HIGH) :: col,d1,d2,d2r,dlm,dlm1,dlm2,dph,glat,glon,    &\n                         pi,r2d,row,tlat,tlat1,tlat2,              &\n                         tlon,tlon1,tlon2,tph0,tlm0,x,y,z\n\n      glatd = lat\n      glond = -lon\n\n      dphd = proj%phi/REAL((proj%jydim-1)/2)\n      dlmd = proj%lambda/REAL(proj%ixdim-1)\n\n      pi = ACOS(-1.0)\n      d2r = pi/180.\n      r2d = 1./d2r\n\n      imt = 2*proj%ixdim-1\n      jmt = proj%jydim/2+1\n\n      glat = glatd*d2r\n      glon = glond*d2r\n      dph = dphd*d2r\n      dlm = dlmd*d2r\n      tph0 = proj%lat1*d2r\n      tlm0 = -proj%lon1*d2r\n\n      x = COS(tph0)*COS(glat)*COS(glon-tlm0)+SIN(tph0)*SIN(glat)\n      y = -COS(glat)*SIN(glon-tlm0)\n      z = COS(tph0)*SIN(glat)-SIN(tph0)*COS(glat)*COS(glon-tlm0)\n      tlat = r2d*ATAN(z/SQRT(x*x+y*y))\n      tlon = r2d*ATAN(y/x)\n\n      row = tlat/dphd+jmt\n      col = tlon/dlmd+proj%ixdim\n\n      if ( (row - INT(row)) .gt. 0.999) then\n         row = row + 0.0002\n      else if ( (col - INT(col)) .gt. 0.999) then\n         col = col + 0.0002\n      end if\n\n      nrow = INT(row)\n      ncol = INT(col)\n\n!      nrow = NINT(row)\n!      ncol = NINT(col)\n\n      tlat = tlat*d2r\n      tlon = tlon*d2r\n\n\n      IF (proj%stagger == HH) THEN\n\n         IF (mod(nrow,2) .eq. 0) then\n            i_real = col / 2.0\n         ELSE\n            i_real = col / 2.0 + 0.5\n         ENDIF\n         j_real=row\n\n\n         IF ((abs(MOD(nrow,2)) == 1 .AND. abs(MOD(ncol,2)) == 1) .OR. &\n             (MOD(nrow,2) == 0 .AND. MOD(ncol,2) == 0)) THEN\n\n            tlat1 = (nrow-jmt)*dph\n            tlat2 = tlat1+dph\n            tlon1 = (ncol-proj%ixdim)*dlm\n            tlon2 = tlon1+dlm\n\n            dlm1 = tlon-tlon1\n            dlm2 = tlon-tlon2\n            d1 = ACOS(COS(tlat)*COS(tlat1)*COS(dlm1)+SIN(tlat)*SIN(tlat1))\n            d2 = ACOS(COS(tlat)*COS(tlat2)*COS(dlm2)+SIN(tlat)*SIN(tlat2))\n\n            IF (d1 > d2) THEN\n               nrow = nrow+1\n               ncol = ncol+1\n            END IF\n\n         ELSE\n            tlat1 = (nrow+1-jmt)*dph\n            tlat2 = tlat1-dph\n            tlon1 = (ncol-proj%ixdim)*dlm\n            tlon2 = tlon1+dlm\n            dlm1 = tlon-tlon1\n            dlm2 = tlon-tlon2\n            d1 = ACOS(COS(tlat)*COS(tlat1)*COS(dlm1)+SIN(tlat)*SIN(tlat1))\n            d2 = ACOS(COS(tlat)*COS(tlat2)*COS(dlm2)+SIN(tlat)*SIN(tlat2))\n\n            IF (d1 < d2) THEN\n               nrow = nrow+1\n            ELSE\n               ncol = ncol+1\n            END IF\n         END IF\n\n      ELSE IF (proj%stagger == VV) THEN\n\n         IF (mod(nrow,2) .eq. 0) then\n            i_real = col / 2.0 + 0.5\n         ELSE\n            i_real = col / 2.0\n         ENDIF\n         j_real=row\n\n         IF ((MOD(nrow,2) == 0 .AND. abs(MOD(ncol,2)) == 1) .OR. &\n             (abs(MOD(nrow,2)) == 1 .AND. MOD(ncol,2) == 0)) THEN\n            tlat1 = (nrow-jmt)*dph\n            tlat2 = tlat1+dph\n            tlon1 = (ncol-proj%ixdim)*dlm\n            tlon2 = tlon1+dlm\n            dlm1 = tlon-tlon1\n            dlm2 = tlon-tlon2\n            d1 = ACOS(COS(tlat)*COS(tlat1)*COS(dlm1)+SIN(tlat)*SIN(tlat1))\n            d2 = ACOS(COS(tlat)*COS(tlat2)*COS(dlm2)+SIN(tlat)*SIN(tlat2))\n\n            IF (d1 > d2) THEN\n               nrow = nrow+1\n               ncol = ncol+1\n            END IF\n\n         ELSE\n            tlat1 = (nrow+1-jmt)*dph\n            tlat2 = tlat1-dph\n            tlon1 = (ncol-proj%ixdim)*dlm\n            tlon2 = tlon1+dlm\n            dlm1 = tlon-tlon1\n            dlm2 = tlon-tlon2\n            d1 = ACOS(COS(tlat)*COS(tlat1)*COS(dlm1)+SIN(tlat)*SIN(tlat1))\n            d2 = ACOS(COS(tlat)*COS(tlat2)*COS(dlm2)+SIN(tlat)*SIN(tlat2))\n\n            IF (d1 < d2) THEN\n               nrow = nrow+1\n            ELSE\n               ncol = ncol+1\n            END IF\n         END IF\n      END IF\n\n\n!!! Added next line as a Kludge - not yet understood why needed\n      if (ncol .le. 0) ncol=ncol-1\n\n      jj = nrow\n      ii = ncol/2\n\n      IF (proj%stagger == HH) THEN\n         IF (abs(MOD(jj,2)) == 1) ii = ii+1\n      ELSE IF (proj%stagger == VV) THEN\n         IF (MOD(jj,2) == 0) ii=ii+1\n      END IF\n\n      i = REAL(ii)\n      j = REAL(jj)\n\n   END SUBROUTINE llij_rotlatlon\n\n\n   SUBROUTINE ijll_rotlatlon(i, j, proj, lat,lon)\n\n      IMPLICIT NONE\n\n      ! Arguments\n      REAL, INTENT(IN) :: i, j\n      REAL, INTENT(OUT) :: lat, lon\n      TYPE (proj_info), INTENT(IN) :: proj\n\n      ! Local variables\n      INTEGER :: ih,jh\n      INTEGER :: midcol,midrow,ncol,iadd1,iadd2,imt,jh2,knrow,krem,kv,nrow\n      REAL :: i_work, j_work\n      REAL :: dphd,dlmd !Grid increments, degrees\n      REAL(KIND=HIGH) :: arg1,arg2,d2r,fctr,glatr,glatd,glond,pi, &\n              r2d,tlatd,tlond,tlatr,tlonr,tlm0,tph0\n      REAL :: col\n\n      i_work = i\n      j_work = j\n\n      if ( (j - INT(j)) .gt. 0.999) then\n         j_work = j + 0.0002\n      endif\n\n      jh = INT(j_work)\n\n      dphd = proj%phi/REAL((proj%jydim-1)/2)\n      dlmd = proj%lambda/REAL(proj%ixdim-1)\n\n      pi = ACOS(-1.0)\n      d2r = pi/180.\n      r2d = 1./d2r\n      tph0 = proj%lat1*d2r\n      tlm0 = -proj%lon1*d2r\n\n      midrow = (proj%jydim+1)/2\n      midcol = proj%ixdim\n\n      col = 2*i_work-1+abs(MOD(jh+1,2))\n      tlatd = (j_work-midrow)*dphd\n      tlond = (col-midcol)*dlmd\n\n       IF (proj%stagger == VV) THEN\n          if (mod(jh,2) .eq. 0) then\n             tlond = tlond - DLMD\n          else\n             tlond = tlond + DLMD\n          end if\n       END IF\n\n      tlatr = tlatd*d2r\n      tlonr = tlond*d2r\n      arg1 = SIN(tlatr)*COS(tph0)+COS(tlatr)*SIN(tph0)*COS(tlonr)\n      glatr = ASIN(arg1)\n\n      glatd = glatr*r2d\n\n      arg2 = COS(tlatr)*COS(tlonr)/(COS(glatr)*COS(tph0))-TAN(glatr)*TAN(tph0)\n      IF (ABS(arg2) > 1.) arg2 = ABS(arg2)/arg2\n      fctr = 1.\n      IF (tlond > 0.) fctr = -1.\n\n      glond = tlm0*r2d+fctr*ACOS(arg2)*r2d\n\n      lat = glatd\n      lon = -glond\n\n      IF (lon .GT. +180.) lon = lon - 360.\n      IF (lon .LT. -180.) lon = lon + 360.\n\n   END SUBROUTINE ijll_rotlatlon\n\n\n   SUBROUTINE set_gauss(proj)\n\n      IMPLICIT NONE\n\n      ! Argument\n      type (proj_info), intent(inout) :: proj\n\n      !  Initialize the array that will hold the Gaussian latitudes.\n\n      IF ( ASSOCIATED( proj%gauss_lat ) ) THEN\n         DEALLOCATE ( proj%gauss_lat )\n      END IF\n\n      !  Get the needed space for our array.\n\n      ALLOCATE ( proj%gauss_lat(proj%nlat*2) )\n\n      !  Compute the Gaussian latitudes.\n\n      CALL gausll( proj%nlat*2 , proj%gauss_lat )\n\n      !  Now, these could be upside down from what we want, so let's check.\n      !  We take advantage of the equatorial symmetry to remove any sort of\n      !  array re-ordering.\n\n      IF ( ABS(proj%gauss_lat(1) - proj%lat1) .GT. 0.01 ) THEN\n         proj%gauss_lat = -1. * proj%gauss_lat\n      END IF\n\n      !  Just a sanity check.\n\n      IF ( ABS(proj%gauss_lat(1) - proj%lat1) .GT. 0.01 ) THEN\n         PRINT '(A)','Oops, something is not right with the Gaussian latitude computation.'\n         PRINT '(A,F8.3,A)','The input data gave the starting latitude as ',proj%lat1,'.'\n         PRINT '(A,F8.3,A)','This routine computed the starting latitude as +-',ABS(proj%gauss_lat(1)),'.'\n         PRINT '(A,F8.3,A)','The difference is larger than 0.01 degrees, which is not expected.'\n         STOP 'Gaussian_latitude_computation'\n      END IF\n\n   END SUBROUTINE set_gauss\n\n\n   SUBROUTINE gausll ( nlat , lat_sp )\n\n      IMPLICIT NONE\n\n      INTEGER                            :: nlat , i\n      REAL (KIND=HIGH) , PARAMETER       :: pi = 3.141592653589793\n      REAL (KIND=HIGH) , DIMENSION(nlat) :: cosc , gwt , sinc , colat , wos2 , lat\n      REAL             , DIMENSION(nlat) :: lat_sp\n\n      CALL lggaus(nlat, cosc, gwt, sinc, colat, wos2)\n\n      DO i = 1, nlat\n         lat(i) = ACOS(sinc(i)) * 180._HIGH / pi\n         IF (i.gt.nlat/2) lat(i) = -lat(i)\n      END DO\n\n      lat_sp = REAL(lat)\n\n   END SUBROUTINE gausll\n\n\n   SUBROUTINE lggaus( nlat, cosc, gwt, sinc, colat, wos2 )\n\n      IMPLICIT NONE\n\n      !  LGGAUS finds the Gaussian latitudes by finding the roots of the\n      !  ordinary Legendre polynomial of degree NLAT using Newton's\n      !  iteration method.\n\n      !  On entry:\n            integer NLAT ! the number of latitudes (degree of the polynomial)\n\n      !  On exit: for each Gaussian latitude\n      !     COSC   - cos(colatitude) or sin(latitude)\n      !     GWT    - the Gaussian weights\n      !     SINC   - sin(colatitude) or cos(latitude)\n      !     COLAT  - the colatitudes in radians\n      !     WOS2   - Gaussian weight over sin**2(colatitude)\n\n      REAL (KIND=HIGH) , DIMENSION(nlat) :: cosc , gwt , sinc , colat  , wos2 \n      REAL (KIND=HIGH) , PARAMETER       :: pi = 3.141592653589793\n\n      !  Convergence criterion for iteration of cos latitude\n\n      REAL , PARAMETER :: xlim  = 1.0E-14\n\n      INTEGER :: nzero, i, j\n      REAL (KIND=HIGH) :: fi, fi1, a, b, g, gm, gp, gt, delta, c, d\n\n      !  The number of zeros between pole and equator\n\n      nzero = nlat/2\n\n      !  Set first guess for cos(colat)\n\n      DO i=1,nzero\n         cosc(i) = SIN( (i-0.5)*pi/nlat + pi*0.5 )\n      END DO\n\n      !  Constants for determining the derivative of the polynomial\n      fi  = nlat\n      fi1 = fi+1.0\n      a   = fi*fi1 / SQRT(4.0*fi1*fi1-1.0)\n      b   = fi1*fi / SQRT(4.0*fi*fi-1.0)\n\n      !  Loop over latitudes, iterating the search for each root\n\n      DO i=1,nzero\n         j=0\n\n         !  Determine the value of the ordinary Legendre polynomial for\n         !  the current guess root\n\n         DO\n            CALL lgord( g, cosc(i), nlat )\n\n            !  Determine the derivative of the polynomial at this point\n\n            CALL lgord( gm, cosc(i), nlat-1 )\n            CALL lgord( gp, cosc(i), nlat+1 )\n            gt = (cosc(i)*cosc(i)-1.0) / (a*gp-b*gm)\n\n            !  Update the estimate of the root\n\n            delta   = g*gt\n            cosc(i) = cosc(i) - delta\n\n            !  If convergence criterion has not been met, keep trying\n\n            j = j+1\n            IF( ABS(delta).GT.xlim ) CYCLE\n\n            !  Determine the Gaussian weights\n\n            c      = 2.0 *( 1.0-cosc(i)*cosc(i) )\n            CALL lgord( d, cosc(i), nlat-1 )\n            d      = d*d*fi*fi\n            gwt(i) = c *( fi-0.5 ) / d\n            EXIT\n\n         END DO\n\n      END DO\n\n      !  Determine the colatitudes and sin(colat) and weights over sin**2\n\n      DO i=1,nzero\n         colat(i)= ACOS(cosc(i))\n         sinc(i) = SIN(colat(i))\n         wos2(i) = gwt(i) /( sinc(i)*sinc(i) )\n      END DO\n\n      !  If NLAT is odd, set values at the equator\n\n      IF( MOD(nlat,2) .NE. 0 ) THEN\n         i       = nzero+1\n         cosc(i) = 0.0\n         c       = 2.0\n         CALL lgord( d, cosc(i), nlat-1 )\n         d       = d*d*fi*fi\n         gwt(i)  = c *( fi-0.5 ) / d\n         colat(i)= pi*0.5\n         sinc(i) = 1.0\n         wos2(i) = gwt(i)\n      END IF\n\n      !  Determine the southern hemisphere values by symmetry\n\n      DO i=nlat-nzero+1,nlat\n         cosc(i) =-cosc(nlat+1-i)\n         gwt(i)  = gwt(nlat+1-i)\n         colat(i)= pi-colat(nlat+1-i)\n         sinc(i) = sinc(nlat+1-i)\n         wos2(i) = wos2(nlat+1-i)\n      END DO\n\n   END SUBROUTINE lggaus\n\n\n   SUBROUTINE lgord( f, cosc, n )\n\n      IMPLICIT NONE\n\n      !  LGORD calculates the value of an ordinary Legendre polynomial at a\n      !  specific latitude.\n\n      !  On entry:\n      !     cosc - COS(colatitude)\n      !     n      - the degree of the polynomial\n\n      !  On exit:\n      !     f      - the value of the Legendre polynomial of degree N at\n      !              latitude ASIN(cosc)\n\n      REAL (KIND=HIGH) :: s1, c4, a, b, fk, f, cosc, colat, c1, fn, ang\n      INTEGER :: n, k\n\n      !  Determine the colatitude\n\n      colat = ACOS(cosc)\n\n      c1 = SQRT(2.0_HIGH)\n      DO k=1,n\n         c1 = c1 * SQRT( 1.0 - 1.0/(4*k*k) )\n      END DO\n\n      fn = n\n      ang= fn * colat\n      s1 = 0.0\n      c4 = 1.0\n      a  =-1.0\n      b  = 0.0\n      DO k=0,n,2\n         IF (k.eq.n) c4 = 0.5 * c4\n         s1 = s1 + c4 * COS(ang)\n         a  = a + 2.0\n         b  = b + 1.0\n         fk = k\n         ang= colat * (fn-fk-2.0)\n         c4 = ( a * (fn-b+1.0) / ( b * (fn+fn-a) ) ) * c4\n      END DO\n\n      f = s1 * c1\n\n   END SUBROUTINE lgord\n\n\n   SUBROUTINE llij_gauss (lat, lon, proj, i, j)\n\n      IMPLICIT NONE\n\n      REAL    , INTENT(IN)  :: lat, lon\n      REAL    , INTENT(OUT) :: i, j\n      TYPE (proj_info), INTENT(IN) :: proj\n\n      INTEGER :: n , n_low\n      LOGICAL :: found = .FALSE.\n      REAL    :: diff_1 , diff_nlat\n\n      !  The easy one first, get the x location.  The calling routine has already made\n      !  sure that the necessary assumptions concerning the sign of the deltalon and the\n      !  relative east/west'ness of the longitude and the starting longitude are consistent\n      !  to allow this easy computation.\n\n      i = ( lon - proj%lon1 ) / proj%loninc + 1.\n\n      !  Since this is a global data set, we need to be concerned about wrapping the\n      !  fields around the globe.\n\n!      IF      ( ( proj%loninc .GT. 0 ) .AND. &\n!                ( FLOOR((lon-proj%lon1)/proj%loninc) + 1 .GE. proj%ixdim ) .AND. &\n!                ( lon + proj%loninc .GE. proj%lon1 + 360 ) ) THEN\n!! BUG: We may need to set proj%wrap, but proj is intent(in)\n!! WHAT IS THIS USED FOR?\n!!        proj%wrap = .TRUE.\n!         i = proj%ixdim\n!      ELSE IF ( ( proj%loninc .LT. 0 ) .AND. &\n!                ( FLOOR((lon-proj%lon1)/proj%loninc) + 1 .GE. proj%ixdim ) .AND. &\n!                ( lon + proj%loninc .LE. proj%lon1 - 360 ) ) THEN\n! ! BUG: We may need to set proj%wrap, but proj is intent(in)\n! ! WHAT IS THIS USED FOR?\n! !        proj%wrap = .TRUE.\n!         i = proj%ixdim\n!      END IF\n\n      !  Yet another quicky test, can we find bounding values?  If not, then we may be\n      !  dealing with putting data to a polar projection, so just give them them maximal\n      !  value for the location.  This is an OK assumption for the interpolation across the\n      !  top of the pole, given how close the longitude lines are.\n\n      IF ( ABS(lat) .GT. ABS(proj%gauss_lat(1)) ) THEN\n\n         diff_1    = lat - proj%gauss_lat(1)\n         diff_nlat = lat - proj%gauss_lat(proj%nlat*2)\n\n         IF ( ABS(diff_1) .LT. ABS(diff_nlat) ) THEN\n            j = 1\n         ELSE\n            j = proj%nlat*2\n         END IF\n\n      !  If the latitude is between the two bounding values, we have to search and interpolate.\n\n      ELSE\n\n         DO n = 1 , proj%nlat*2 -1\n            IF ( ( proj%gauss_lat(n) - lat ) * ( proj%gauss_lat(n+1) - lat ) .LE. 0 ) THEN\n               found = .TRUE.\n               n_low = n\n               EXIT\n            END IF\n         END DO\n\n         !  Everything still OK?\n\n         IF ( .NOT. found ) THEN\n            PRINT '(A)','Troubles in river city.  No bounding values of latitude found in the Gaussian routines.'\n            STOP 'Gee_no_bounding_lats_Gaussian'\n         END IF\n\n         j = ( ( proj%gauss_lat(n_low) - lat                     ) * ( n_low + 1 ) + &\n               ( lat                   - proj%gauss_lat(n_low+1) ) * ( n_low     ) ) / &\n               ( proj%gauss_lat(n_low) - proj%gauss_lat(n_low+1) )\n\n      END IF\n\n   END SUBROUTINE llij_gauss\n\nEND MODULE module_llxy\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_mapinfo.F",
    "content": "module module_mapinfo\n\n  implicit none\n\n  type MapInfoStruct\n     character(len=2) :: hproj         ! Two-character abbreviation identifying map projection\n     integer          :: supmap_jproj  ! Integer as used in NCAR-Graphics subroutine SUPMAP to identify map projection\n     integer          :: nx\n     integer          :: ny\n     real             :: dx            ! Grid spacing in km or degrees as appropriate\n     real             :: dy            ! Grid spacing in km or degrees as appropriate\n     real             :: lat1          ! We need to make this a reference latitude?\n     real             :: lon1          ! We need to make this a reference longitude?\n     real             :: lat2          ! For Cylindrical Equidistant grids\n     real             :: lon2          ! For Cylindrical Equidistant grids\n     real             :: xlonc\n     real             :: truelat1\n     real             :: truelat2\n  end type MapInfoStruct\n\ncontains\n  subroutine print_mapinfo(mapinfo)\n    implicit none\n    type (MapInfoStruct), intent(in) ::  mapinfo\n    write(*,'(\"MAPINFO:  \")')\n    write(*,'(4x, \"       HPROJ = \", A2)') mapinfo%hproj\n    write(*,'(4x, \"SUPMAP_JPROJ = \", I2)') mapinfo%supmap_jproj\n    write(*,'(4x, \"          NX = \", I6)') mapinfo%nx\n    write(*,'(4x, \"          NY = \", I6)') mapinfo%ny\n    write(*,'(4x, \"          DX = \", F12.4)') mapinfo%dx\n    write(*,'(4x, \"          DY = \", F12.4)') mapinfo%dy\n    write(*,'(4x, \"        LAT1 = \", F12.4)') mapinfo%lat1\n    write(*,'(4x, \"        LON1 = \", F12.4)') mapinfo%lon1\n    if ( mapinfo%lat2 > -1.E25)     write(*,'(4x, \"        LAT2 = \", F12.4)') mapinfo%lat2\n    if ( mapinfo%lon2 > -1.E25)     write(*,'(4x, \"        LON2 = \", F12.4)') mapinfo%lon2\n    if ( mapinfo%xlonc > -1.E25)    write(*,'(4x, \"       XLONC = \", F12.4)') mapinfo%xlonc\n    if ( mapinfo%truelat1 > -1.E25) write(*,'(4x, \"    TRUELAT1 = \", F12.4)') mapinfo%truelat1\n    if ( mapinfo%truelat2 > -1.E25) write(*,'(4x, \"    TRUELAT2 = \", F12.4)') mapinfo%truelat2\n  end subroutine print_mapinfo\n\nend module module_mapinfo\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/module_wrfinputfile.F",
    "content": "module module_wrfinputfile\n  use netcdf\n  use module_llxy\n  implicit none\n  ! Define a data structure for wrfinput file\n\n  type wrfinput_type\n     type(proj_info) :: proj\n     integer :: grid_id\n     integer :: idim\n     integer :: jdim\n\n     character(len=256) :: landuse_dataset  ! \"MODIFIED_IGBP_MODIS_NOAH\" or \"USGS\"\n     integer :: iswater\n     !\n     ! Some 2d arrays of grid/geographical information:\n     !\n     real, pointer, dimension(:,:)   :: lat    ! Grid point latitudes\n     real, pointer, dimension(:,:)   :: lon    ! Grid point longitudes\n     real, pointer, dimension(:,:)   :: ter    ! Terrain field\n     real, pointer, dimension(:,:)   :: use    ! Land-use (vegetation) field\n!KWM     real, pointer, dimension(:,:)   :: tmn    ! Deep-soil temperature field\n     real, pointer, dimension(:,:,:) :: veg    ! 12-month Green Vegetation Fraction climatology\n  end type wrfinput_type\n\ncontains\n\n  subroutine read_wrfinput_file(flnm, wrfinput, ierr)\n    !\n    ! Reads the wrfinput file identified by <flnm>, and fills out\n    ! the <wrfinput> structure with the appropriate values.\n    !\n    implicit none\n\n    character(len=*),     intent(in)  :: flnm\n    type (wrfinput_type), intent(out) :: wrfinput\n    integer, intent(out)              :: ierr\n    ! Local:\n    integer                           :: ncid\n    integer                           :: iret\n    integer                           :: dimid\n    integer                           :: map_proj\n    real                              :: truelat1\n    real                              :: truelat2\n    real                              :: stdlon\n    real                              :: dx\n    real                              :: latinc\n    real                              :: loninc\n    real                              :: la1\n    real                              :: lo1\n    real                              :: pole_lat\n    real                              :: pole_lon\n\n! Open the NetCDF file.\n    iret = nf90_open(flnm, NF90_NOWRITE, ncid)\n    call error_handler(iret, \"Problem with wrfinput file: \"//flnm)\n\n! Find out about dimensions in the file.\n\n    iret = nf90_inq_dimid(ncid, \"west_east\", dimid)\n    call error_handler(iret, \"STOP:  Problem finding west_east dimension\")\n    iret = nf90_inquire_dimension(ncid, dimid, len=wrfinput%idim)\n    call error_handler(iret, \"STOP:  Problem finding west_east dimension\")\n\n    iret = nf90_inq_dimid(ncid, \"south_north\", dimid)\n    call error_handler(iret, \"STOP:  Problem finding south_north dimension\")\n    iret = nf90_inquire_dimension(ncid, dimid, len=wrfinput%jdim)\n    call error_handler(iret, \"STOP:  Problem finding south_north dimension\")\n\n    ! Grid id.  Check for the string \"GRID_ID\" or the string \"grid_id\"\n    iret = nf90_get_att(ncid, NF90_GLOBAL,\"GRID_ID\", wrfinput%grid_id)\n    if (iret /= 0) then\n       iret = nf90_get_att(ncid, NF90_GLOBAL,\"grid_id\", wrfinput%grid_id)\n       call error_handler(iret, \"STOP:  nf90_get_att:  'grid_id' or 'GRID_ID' not found.\")\n    endif\n\n    ! Get Latitude\n    allocate(wrfinput%lat(wrfinput%idim, wrfinput%jdim))\n    call get_2d(\"XLAT\", ncid, wrfinput%lat, wrfinput%idim, wrfinput%jdim)\n    la1 = wrfinput%lat(1,1)\n\n    ! Get Longitude\n    allocate(wrfinput%lon(wrfinput%idim, wrfinput%jdim))\n    call get_2d(\"XLONG\", ncid, wrfinput%lon, wrfinput%idim, wrfinput%jdim)\n    lo1 = wrfinput%lon(1,1)\n\n    ! Get Terrain\n    allocate(wrfinput%ter(wrfinput%idim, wrfinput%jdim))\n    call get_2d(\"HGT\", ncid, wrfinput%ter, wrfinput%idim, wrfinput%jdim)\n\n    ! Get Land Use categories\n    allocate(wrfinput%use(wrfinput%idim, wrfinput%jdim))\n    call get_2d(\"IVGTYP\", ncid, wrfinput%use, wrfinput%idim, wrfinput%jdim)\n\n!KWM  ! Get deep soil Temperature field\n!KWM  allocate(wrfinput%tmn(wrfinput%idim, wrfinput%jdim))\n!KWM  call get_2d(\"TMN\", ncid, wrfinput%tmn, wrfinput%idim, wrfinput%jdim)\n\n    ! Projection information:\n\n    call map_init(wrfinput%proj)\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL,\"MAP_PROJ\", map_proj)\n    call error_handler(iret, \"STOP:  nf90_get_att:  map projection problem\")\n\n    if (map_proj == PROJ_LC) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\" , truelat2)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT2\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_LC, wrfinput%proj, lat1=la1, lon1=lo1, knowni=1.0, knownj=1.0, &\n            truelat1=truelat1, truelat2=truelat2, stdlon=stdlon, dx=dx)\n\n    else if (map_proj == PROJ_PS) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_PS, wrfinput%proj, lat1=la1, lon1=lo1, truelat1=truelat1, &\n            knowni=1.0, knownj=1.0, stdlon=stdlon, dx=dx)\n\n    else if (map_proj == PROJ_MERC) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_MERC, wrfinput%proj, lat1=la1, lon1=lo1, knowni=1.0, knownj=1.0, &\n            truelat1=truelat1, dx=dx)\n\n    else if (map_proj == PROJ_CASSINI) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"POLE_LAT\" , pole_lat)\n       call error_handler(iret, \"STOP:  nf90_get_att:  POLE_LAT\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"POLE_LON\" , pole_lon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  POLE_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       ! For Cassini projection, module_llxy assumes a spherical earth\n       ! with circumference EARTH_CIRC_M\n       latinc = 360.0*dx/EARTH_CIRC_M\n       loninc = 360.0*dx/EARTH_CIRC_M\n\n       call map_set(PROJ_CASSINI, wrfinput%proj, lat1=la1, lon1=lo1, latinc=latinc, loninc=loninc, &\n            knowni=1.0, knownj=1.0, lat0=pole_lat, lon0=pole_lon, stdlon=stdlon)\n\n    else if (map_proj == PROJ_LATLON) then\n       stop \"PROJ_LATLON is not a valid map projection for WRF.\"\n\n       ! iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       ! call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       ! For lat/lon projection, module_llxy assumes a spherical earth\n       ! with circumference EARTH_CIRC_M\n       ! latinc = 360.0*dx/EARTH_CIRC_M\n       ! loninc = 360.0*dx/EARTH_CIRC_M\n\n       ! call map_set(PROJ_LATLON, wrfinput%proj, lat1=la1, lon1=lo1, &\n       !      latinc=latinc, loninc=loninc, knowni=1.0, knownj=1.0)\n\n    else if (map_proj == PROJ_PS_WGS84) then\n       stop \"PROJ_PS_WGS84 is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_PS_WGS84, wrfinput%proj, lat1=wrfinput%la1, lon1=wrfinput%lo1, knowni=1.0, knownj=1.0, &\n       !     stdlon=wrfinput%lov, dx=wrfinput%dx)\n    else if (map_proj == PROJ_GAUSS) then\n       stop \"PROJ_GAUSS is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_GAUSS, wrfinput%proj, lat1=, lon1=, nlat=, loninc=)\n    else if (map_proj == PROJ_CYL) then\n       stop \"PROJ_CYL is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_CYL, wrfinput%proj, latinc=, loninc=, stdlon=)\n    else if (map_proj == PROJ_ALBERS_NAD83) then\n       stop \"PROJ_ALBERS_NAD83 is not a valid map projection for WRF.\"\n       !call map_set(PROJ_ALBERS_NAD83, wrfinput%proj, lat1=, lon1=, knowni=, knownj=, truelat1=, truelat2=, stdlon=, dx=)\n    else if (map_proj == PROJ_ROTLL) then\n       stop \"PROJ_ROTLL is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_ROTLL, wrfinput%proj, lat1=wrfinput%lat1, lon1=wrfinput%lon1, ixdim=, jydim=, phi=, lambda=)\n    else\n       write(*,'(\"Unknown wrfinput map projection:  map_proj = \", I10)') map_proj\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"ISWATER\" , wrfinput%iswater)\n    call error_handler(iret, \"STOP:  nf90_get_att:  ISWATER\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"MMINLU\" , wrfinput%landuse_dataset)\n    call error_handler(iret, \"STOP:  nf90_get_att:  MMINLU\")\n\n    ! Close the file and get out of here\n\n    iret = nf90_close(ncid)\n    call error_handler(iret, \"STOP:  Problem closing file??\")\n\n    ierr = 0\n    print*, \"Done with subroutine read_wrfinput_file\"\n\n  end subroutine read_wrfinput_file\n\n  subroutine get_2d(name, ncid, array, idim, jdim)\n    !\n    ! From the NetCDF unit <ncid>, read the variable named <name> with\n    ! dimensions <idim> and <jdim>, filling the pre-dimensioned array <array>\n    !\n    implicit none\n    character(len=*),           intent(in)  :: name\n    integer,                    intent(in)  :: ncid\n    integer,                    intent(in)  :: idim\n    integer,                    intent(in)  :: jdim\n    real, dimension(idim,jdim), intent(out) :: array\n    ! Local:\n    integer                                 :: ierr\n    integer                                 :: varid\n\n    ierr = nf90_inq_varid(ncid,  name,  varid)\n    ! If the variable is \"XLAT\", and \"XLAT\" is not found, look for \"XLAT_M\"\n    ! If the variable is \"XLAT_M\", and \"XLAT_M\" is not found, look for \"XLAT\"\n    ! If the variable is \"XLONG\", and \"XLONG\" is not found, look for \"XLONG_M\"\n    ! If the variable is \"XLONG_M\", and \"XLONG_M\" is not found, look for \"XLONG\"\n    if (name == \"XLAT\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLAT_M\",  varid)\n       endif\n    else if (name == \"XLAT_M\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLAT\",  varid)\n       endif\n    else  if (name == \"XLONG\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLONG_M\",  varid)\n       endif\n    else if (name == \"XLONG_M\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLONG\",  varid)\n       endif\n    endif\n    call error_handler(ierr, \"STOP:  READ_WRFINPUT: Problem finding variable '\"//trim(name)//\"' in wrfinput file.\")\n\n\n    ierr = nf90_get_var(ncid, varid, array)\n    call error_handler(ierr, \"STOP:  READ_WRFINPUT:  Problem retrieving variable '\"//trim(name)//\"' from wrfinput file.\")\n\n  end subroutine get_2d\n\n\n  subroutine error_handler(status, failure, success)\n    !\n    ! Check the error flag from a NetCDF function call, and print appropriate\n    ! error message.\n    !\n    implicit none\n    integer,                    intent(in) :: status\n    character(len=*), optional, intent(in) :: failure\n    character(len=*), optional, intent(in) :: success\n\n    if (status .ne. NF90_NOERR) then\n       if (present(failure)) then\n          write(*,'(/,\" ***** \", A)') failure\n       endif\n       write(*,'(\" ***** \",A,/)') nf90_strerror(status)\n       stop 'Stopped'\n    endif\n\n    if (present(success)) then\n       write(*,'(A)') success\n    endif\n\n  end subroutine error_handler\n\n\nend module module_wrfinputfile\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/swap4c.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n \n*/\nvoid swap4c(char i[], int n) {\n  int j;\n  int m;\n  char hold;\n\n  for (m=0; m<n; m+=4){\n    hold =i[m+0];\n    i[m+0]=i[m+3];\n    i[m+3]=hold;\n\n    hold =i[m+1];\n    i[m+1]=i[m+2];\n    i[m+2]=hold;\n    \n  }\n}\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/swap4f.F",
    "content": "subroutine swap4f(in,nn)\n#if defined (__alpha) || defined (__linux) || defined (__G95__)\n! swaps bytes in groups of 4 to compensate for byte swapping within\n!    words which occurs on DEC machines.\n  implicit none\n  integer, intent(in) :: nn ! number of bytes to be swapped\n  logical*1 , dimension(nn) , intent(inout) :: in  ! Array to be swapped\n#if defined (BIT32)\n  integer, parameter :: nbytes=4\n#elif defined (BIT64)\n  integer, parameter :: nbytes=8\n#else\n  \"Please use the CPP option -BIT32 or -BIT64\"\n#endif\n\n  logical*1, dimension(nbytes) :: ia\n  integer :: i\n  do i=1,nn,nbytes\n     ia = in(i+(nbytes-1):i:-1)\n     in(i:i+(nbytes-1)) = ia\n  enddo\n\n#endif\nend\n!KWM -------------------------------------------------------------------------\n!KWM -------------------------------------------------------------------------\n!KWM -------------------------------------------------------------------------\n!KWM\n!KWM    Here are the original swap routines.  I use only SWAP4.  I modified\n!KWM    SWAP4 to use the same array on input and output, rather than make a\n!KWM    new output array IO.  I keep these around just for reference.\n!KWM\n!KWM -------------------------------------------------------------------------\n!KWM -------------------------------------------------------------------------\n!KWM -------------------------------------------------------------------------\n!KWM\n!KWM\tsubroutine swap4(in,io,nn)\n!KWM#if defined (DEC) || defined (ALPHA)\n!KWM! swaps bytes in groups of 4 to compensate for byte swapping within\n!KWM!    words which occurs on DEC (VAX) and PC machines.\n!KWM!\n!KWM! in - input array to be swapped\n!KWM! io - ouput array with bytes swapped\n!KWM! nn - number of bytes to be swapped\n!KWM\tlogical*1   in(1),io(1),ih\n!KWM!       character*1 in(1),io(1),ih             ! Cray CF90 (Version 3.0.1.3)\n!KWM!          Use character*1 instead of logical*1 when compling on a Cray\n!KWM\tdo 10 i=1,nn,4\n!KWM\tih=in(i)\n!KWM\tio(i)=in(i+3)\n!KWM\tio(i+3)=ih\n!KWM\tih=in(i+1)\n!KWM\tio(i+1)=in(i+2)\n!KWM\tio(i+2)=ih\n!KWM   10\tcontinue\n!KWM\treturn\n!KWM#endif\n!KWM\tend\n!KWM\tsubroutine swap2(in,io,nn)\n!KWM#if defined (DEC) || defined (ALPHA)\n!KWM! swaps bytes in groups of 2 to compensate for byte swapping within\n!KWM!    words which occurs on DEC (VAX) and PC machines.\n!KWM!\n!KWM! in - input array to be swapped\n!KWM! io - ouput array with bytes swapped\n!KWM! nn - number of bytes to be swapped\n!KWM\tlogical*1   in(1),io(1),ih\n!KWM!       character*1 in(1),io(1),ih             ! Cray CF90 (Version 3.0.1.3)\n!KWM!          Use character*1 instead of logical*1 when compling on a Cray\n!KWM\tdo 10 i=1,nn,2\n!KWM\tih=in(i)\n!KWM\tio(i)=in(i+1)\n!KWM\tio(i+1)=ih\n!KWM   10\tcontinue\n!KWM\treturn\n!KWM#endif\n!KWM\tend\n!KWM\n!KWM\tsubroutine filt(m,n,in)\n!KWM#if defined (DEC) || defined (ALPHA)\n!KWM\tlogical*1 m(1),n(1),l,u\n!KWM\tdata l/32/,u/127/\n!KWM\tdo 10 i=1,in\n!KWM\tn(i)=m(i)\n!KWM\tif(n(i).lt.  l) n(i)=l\n!KWM\tif(n(i).gt.  u) n(i)=u\n!KWM   10\tcontinue\n!KWM\treturn\n!KWM#endif\n!KWM\tend\n!KWM Emacs Local Variables: ***\n!KWM Emacs mode: f90        ***\n!KWM Emacs End:             ***\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/lib/trig_degrees.F",
    "content": "!\n! Trigonometric functions which deal with degrees, rather than radians:\n!\n\nreal function sind(theta)\n  implicit none\n  real, intent(in) :: theta\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: degran = pi/180.\n  sind = sin(theta*degran)\nend function sind\n\nreal function cosd(theta)\n  implicit none\n  real, intent(in) :: theta\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: degran = pi/180.\n  cosd = cos(theta*degran)\nend function cosd\n\nreal function tand(theta)\n  implicit none\n  real, intent(in) :: theta\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: degran = pi/180.\n  tand = tan(theta*degran)\nend function tand\n\nreal function atand(x)\n  implicit none\n  real, intent(in) :: x\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: raddeg = 180./pi\n  atand = atan(x)*raddeg\nend function atand\n\nreal function atan2d(x,y)\n  implicit none\n  real, intent(in) :: x,y\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: raddeg = 180./pi\n  atan2d = atan2(x,y)*raddeg\nend function atan2d\n\nreal function asind(x)\n  implicit none\n  real, intent(in) :: x\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: raddeg = pi/180.\n  asind = asin(x)*raddeg\nend function asind\n\nreal function acosd(x)\n  implicit none\n  real, intent(in) :: x\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: raddeg = pi/180.\n  acosd = acos(x)*raddeg\nend function acosd\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/run/Makefile",
    "content": "all:\n\t( cd ..; make )\n\nclean:\n\t( cd ..; make clean )\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/run/README.namelist",
    "content": "Some brief notes on the namelist.input file.  For full details (e.g.,\nfile name template replacement strings, file formats, etc.) see the\nUsers' Guide (HRLDAS_USERS_GUIDE.PDF).\n\nSTARTDATE\n\n    The starting date (GMT) for your HRLDAS integration, expressed as\n    a character string in the form \"YYYY-MM-DD_HH\".  You should probably\n    start on a 00 GMT hour.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  STARTDATE = \"2001-01-01_00\"\n\nENDDATE\n\n    The ending date (GMT) for your HRLDAS integration, expressed as\n    a character string in the form \"YYYY-MM-DD_HH\".\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  ENDDATE = \"2002-07-01_00\"\n\nDATADIR\n\n    A top-level directory under which the original GRIB datasets are\n    organized.  The string defined here may be used in building file\n    names from the templates defined below.  Where the file name\n    templates include the string \"<DataDir>\", that string will be\n    replace by the value set for namelist variable DATADIR.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  DATADIR = \"/data1/user2/datasets\"\n\nRAINFALL_INTERP\n\n    Specifies the option for remapping the precipitation field from\n    the source map to the HRLDAS map.  Options are:\n\n       0: Assign precipitation values on the HRLDAS map from the\n          nearest neighbor on the source map.\n       1: Subdivide the source grid cell into some number of smaller\n          cells, and allocate precipitation from the source grid to\n          the destination grid based on accumulating values from the\n          subcells which fall into the destination grid cell.\n\n    Option 0 may be appropriate, and may save much processing time,\n    for situations in which the HRLDAS grid cells are somewhat smaller\n    than the source grid cells.\n\n    Type:     integer\n    Default:  1 (expensive remapping by subdivision)\n    Example:  RAINFALL_INTERP = 1\n\nFULL_IC_FRQ\n\n    Specifies the interval (in hours) to create full initial\n    conditions for HRLDAS input files.  Special value of -1 means to never\n    create full initial conditions.\n\n    Type:     integer\n    Default:  0 (to create full initial conditions at the starting time only)\n    Example:  FULL_IC_FRQ = 24\n\nRESCALE_SHORTWAVE\n\n    Specifies whether the program will attempt to correct a half-hour time offset\n    that has been noted in the GCIP shortwave radiation analyses.  Set this to \n    .FALSE. if the time offset does not exist, or if you are using a different\n    source of shortwave radiation analyses.\n\n    Type:     logical\n    Default:  .FALSE. (do not apply offset)\n    Example:  RESCALE_SHORTWAVE = .FALSE. \n\nGEO_EM_FLNM\n\n    Specifies the full path name to the file defining the setup of the\n    HRLDAS grid.  This will be a \"geo_em_d##.nc\" file as created by\n    the WPS program geogrid. Enterprising users might create their own \n    substitute files.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  GEO_EM_FLNM = \"/data1/user2/grids/geo_em.d01.nc\"\n\nWRFINPUT_FLNM\n\n    Specifies the full path name to a wrfinput file created as in\n    preparation for running the WRF model.  Enterprising users might\n    create their own substitute files.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  WRFINPUT_FLNM = \"/data1/user2/grids/wrfinput_d01\"\n\nZFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the model elevation field associated with the\n    source temperature data.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  ZFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/SFC_ELEVATION.GRIB\"\n\nTFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the near-surface air temperature field.  Multiple\n    templates may be defined; the file that gets used will be from the\n    first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  TFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/T.<date>\"\n\nUFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the near-surface u-component of the horizontal\n    wind field.  Multiple templates may be defined; the file that gets\n    used will be from the first template which resolves to an existing\n    filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  UFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/U.<date>\",\n\nVFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the near-surface v-component of the horizontal\n    wind field.  Multiple templates may be defined; the file that gets\n    used will be from the first template which resolves to an existing\n    filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  VFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/V.<date>\",\n\nPFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the surface pressure field.  Multiple\n    templates may be defined; the file that gets used will be from the\n    first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  PFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/PSFC.<date>\",\n\nQFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the near-surface specific humidity field.\n    Multiple templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  QFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/Q.<date>\",\n\nLWFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the downwelling long-wave radiation field.\n    Multiple templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  LWFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/LW.<date>\",\n\nSWFILE_PRIMARY\n\n    A file name template for building the full path name of the GRIB\n    file which contains the downwelling short-wave radiation field that\n    the user prefers to use.  Multiple templates may be defined; the\n    file that gets used will be from the first template which resolves\n    to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  SWFILE_PRIMARY = \"<DataDir>/<YYYY>/<MM>/<DD>/SW_analysis.<date>\",\n\nSWFILE_SECONDARY\n\n    A file name template for building the full path name of the GRIB \n    file which contains the downwelling short-wave radiation field\n    that will be used to fill in missing values from the file specified\n    by SWFILE_PRIMARY.  Multiple templates may be defined; the file\n    that gets used will be from the first template which resolves to\n    an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  SWFILE_SECONDARY = \"<DataDir>/<YYYY>/<MM>/<DD>/SW_forecast.<date>\",\n\nPCPFILE_PRIMARY\n\n    A file name template for building the full path name of the GRIB\n    file which contains the precipitation field that the user prefers\n    to use.  Multiple templates may be defined; the file that gets\n    used will be from the first template which resolves to an existing\n    filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  PCPFILE_PRIMARY = \"<DataDir>/<YYYY>/<MM>/<DD>/PCP_analysis.<date>\",\n\nPCPFILE_SECONDARY\n\n    A file name template for building the full path name of the GRIB \n    file which contains the precipitation field that will be used to\n    fill in missing values from the file specified by PCPFILE_PRIMARY.\n    Multiple templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  PCPFILE_SECONDARY = \"<DataDir>/<YYYY>/<MM>/<DD>/PCP_forecast.<date>\",\n\nWEASDFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the water-equivalent accumulated snow depth\n    field.  Multiple templates may be defined; the file that gets used\n    will be from the first template which resolves to an existing\n    filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  WEASDFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/WEASD.<date>\",\n\nCANWATFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the canopy-water field.  Multiple templates\n    may be defined; the file that gets used will be from the first\n    template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  CANWATFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/CANWAT.<date>\",\n\nLANDSFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the land/sea mask of the source data.\n    Multiple templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  LANDSFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/LANDSEA.<date>\",\n\nSKINTFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the skin temperature field.  Multiple\n    templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  SKINTFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/SKINT.<date>\",\n\nSTFILE_TEMPLATES\n\n    File name templates for building the full path names of the GRIB\n    files which contain the soil temperature fields at various levels.\n    Multiple templates must be defined, for specifying fields for\n    the various soil levels.  Multiple groups of levels may be\n    defined, the files that get used will be from the first templates\n    which resolves to existing filenames.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  STFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_T_000-010.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_T_010-040.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_T_040-100.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_T_100-200.<date>\",\n\nSMFILE_TEMPLATES\n\n    File name templates for building the full path names of the GRIB\n    files which contain the soil moisture fields at various levels.\n    Multiple templates must be defined, for specifying fields for\n    the various soil levels.  Multiple groups of levels may be\n    defined, the files that get used will be from the first templates\n    which resolves to existing filenames.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  SMFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_M_000-010.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_M_010-040.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_M_040-100.<date>\",\n\t                        \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_M_100-200.<date>\",\n\n<VTABLE>\n\n    This tag begins Variable table in the style of the WPS program\n    ungrib VTables. This portion of the file is not part of the\n    Fortran namelist (which ends with the \"/\" character).  The VTable\n    is a mapping of GRIB (Edition 1 or Edition 2) code numbers to\n    variable names as recognized in the HRLDAS code.  Users may need\n    to modify the VTable if the GRIB code numbers from their source\n    data sets differ from those defined in this portion of the\n    namelist file.\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/run/namelist.example.complex",
    "content": "&files\n\n STARTDATE        = \"2001-01-01_00\"\n ENDDATE          = \"2002-07-01_00\"\n DataDir          = \"/d2/hrldas/raw\"\n \n RAINFALL_INTERP  = 0\n\n geo_em_flnm      = \"/home/kmanning/grids/geo_em.d01.nc\"\n wrfinput_flnm    = \"/home/kmanning/grids/wrfinput_d01\"\n\n Zfile_template     = \"/d2/kmanning/hrldas_rawdata/ETA_SFC_ELEVATION.GRIB\"\n\n Tfile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.T.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.T.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.T.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.T.<date>.grb\",\n\n Ufile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.U.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.U.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.U.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.U.<date>.grb\",\n\n Vfile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.V.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.V.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.V.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.V.<date>.grb\",\n                      \n Pfile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.P.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.P.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.P.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.P.<date>.grb\",\n\t              \n Qfile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.Q.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.Q.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.Q.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.Q.<date>.grb\",\n\n LWfile_template    = \"<DataDir>/NAM/<init-12>/NAM.LW.<date>.grb\",\n\t              \"<DataDir>/NAM/<init-24>/NAM.LW.<date>.grb\",\n\t              \"<DataDir>/NAM/<init-36>/NAM.LW.<date>.grb\",\n\n WEASDfile_template = \"<DataDir>/NAM/<init-12>/NAM.WEASD.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.WEASD.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.WEASD.<date>.grb\",\n\n CANWTfile_template = \"<DataDir>/NAM/<init-12>/NAM.CANWAT.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.CANWAT.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.CANWAT.<date>.grb\",\n\n LANDSfile_template = \"<DataDir>/NAM/<init-12>/NAM.LANDSEA.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.LANDSEA.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.LANDSEA.<date>.grb\",\n\n SKINTfile_template = \"<DataDir>/NAM/<init-12>/NAM.SKINTEMP.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SKINTEMP.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SKINTEMP.<date>.grb\",\n\n STfile_template    = \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_T_000-010.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_T_010-040.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_T_040-100.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_T_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_T_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_T_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_T_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_T_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_T_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_T_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_T_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_T_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_T_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_T_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_T_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_T_100-200.<date>.grb\",\n\n SMfile_template    = \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_M_000-010.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_M_010-040.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_M_040-100.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_M_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_M_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_M_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_M_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_M_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_M_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_M_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_M_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_M_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_M_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_M_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_M_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_M_100-200.<date>.grb\",\n\n SWfile_primary     = \"<DataDir>/SRB/<YYYY><MM><DD>/SW.<date>.grb\",\n\n SWfile_secondary   = \"<DataDir>/NAM/<init-12>/NAM.SW.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SW.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SW.<date>.grb\",\n\n PCPfile_primary    = \"<DataDir>/ST4/<YYYY><MM><DD>/ST4.<date>.grb\",\n\n PCPfile_secondary  = \"<DataDir>/NAM/<init-12>/NAM.PCP.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.PCP.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.PCP.<date>.grb\",\n\n/\n\n<VTABLE>\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\nGRIB1| Level| From |  To  |          |           |                                         |GRIB2|GRIB2|GRIB2|GRIB2|\nParam| Type |Level1|Level2| Name     | Units     | Description                             |Discp|Catgy|Param|Level|\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n  11 | 105  |   2  |      | T2D      | K         | Temperature       at 2 m                |  0  |  0  |  0  | 103 |\n  51 | 105  |   2  |      | Q2D      | kg kg{-1} | Specific Humidity at 2 m                |  0  |  1  |  0  | 103 |\n  33 | 105  |  10  |      | U2D      | m s-1     | U                 at 10 m               |  0  |  2  |  2  | 103 |\n  34 | 105  |  10  |      | V2D      | m s-1     | V                 at 10 m               |  0  |  2  |  3  | 103 |\n   1 |   1  |   0  |      | PSFC     | Pa        | Surface Pressure                        |  0  |  3  |  0  |   1 |\n 144 | 112  |   0  |  10  | SMOIS_1  | kg m-3    | Soil Moist 0-10 cm below grn layer (Up) |  2  |  0  | 192 | 106 |\n 144 | 112  |  10  |  40  | SMOIS_2  | kg m-3    | Soil Moist 10-40 cm below grn layer     |  2  |  0  | 192 | 106 |\n 144 | 112  |  40  | 100  | SMOIS_3  | kg m-3    | Soil Moist 40-100 cm below grn layer    |  2  |  0  | 192 | 106 |\n 144 | 112  | 100  | 200  | SMOIS_4  | kg m-3    | Soil Moist 100-200 cm below gr layer    |  2  |  0  | 192 | 106 |\n  85 | 112  |   0  |  10  | STEMP_1  | K         | T 0-10 cm below ground layer (Upper)    |  2  |  0  |  2  | 106 |\n  85 | 112  |  10  |  40  | STEMP_2  | K         | T 10-40 cm below ground layer (Upper)   |  2  |  0  |  2  | 106 |\n  85 | 112  |  40  | 100  | STEMP_3  | K         | T 40-100 cm below ground layer (Upper)  |  2  |  0  |  2  | 106 |\n  85 | 112  | 100  | 200  | STEMP_4  | K         | T 100-200 cm below ground layer (Bottom)|  2  |  0  |  2  | 106 |\n  91 |   1  |   0  |      | SEAICE   | proprtn   | Ice flag                                | 10  |  2  |  0  |   1 |\n  81 |   1  |   0  |      | LANDSEA  | proprtn   | Land/Sea flag (1=land,0=sea in NAM)     |  2  |  0  |  0  |   1 |\n  11 |   1  |   0  |      | SKINTEMP | K         | Skin temperature (can use for SST also) |  0  |  0  |  0  |   1 |\n  61 |   1  |   0  |      | RAINFALL | kg m-2    | Accumulated precipitation               |  0  |  1  |  8  |   1 |\n  65 |   1  |   0  |      | WEASD    | kg m-2    | Water equivalent snow depth             |  0  |  1  | 13  |   1 |\n 223 |   1  |   0  |      | CANWAT   | kg m-2    | Plant Canopy Surface Water              |  2  |  0  | 196 |   1 |\n 204 |   1  |   0  |      | SW       | W m-2     | Downward short-wave radiation flux      |  0  |  4  | 192 |   1 |\n 205 |   1  |   0  |      | LW       | W m-2     | Downward long-wave radiation flux       |  0  |  5  | 192 |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Terrain field of source analysis        |  2  |  0  |  7  |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Source model terrain elevation          |  0  |  3  |  5  |   1 |\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n</VTABLE>\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/run/namelist.example.simple",
    "content": "&files\n STARTDATE        = \"2001-01-01_00\"\n ENDDATE          = \"2002-07-01_00\"\n DataDir          = \"/wig/kmanning/HRLDAS_FORCING_RAW\"\n\n RAINFALL_INTERP  = 0\n\n geo_em_flnm      = \"/wig/kmanning/more_hrldas/HRLDAS/for_cb_test/geo_em.d01.nc\"\n wrfinput_flnm    = \"/wig/kmanning/more_hrldas/HRLDAS/for_cb_test/wrfinput_d01\"\n\n Zfile_template     = \"<DataDir>/ETA_SFC_ELEVATION.GRIB\"\n\n Tfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.T.<date>\"\n Ufile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.U.<date>\",\n Vfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.V.<date>\",\n Pfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.P.<date>\",\n Qfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.Q.<date>\",\n LWfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.LW.<date>\",\n WEASDfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.WEASD.<date>\",\n CANWTfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.CANWAT.<date>\",\n LANDSfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.LANDSEA.<date>\",\n SKINTfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SKINTEMP.<date>\",\n\n STfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_000-010.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_010-040.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_040-100.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_100-200.<date>\",\n\n SMfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_000-010.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_010-040.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_040-100.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_100-200.<date>\",\n\n SWfile_primary     = \"<DataDir>/SRB_restamped/SW.<date>30.grb\",\n SWfile_secondary   = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.SW.<date>\",\n\n PCPfile_primary    = \"<DataDir>/<YYYY>/<MM>/<DD>/ST4.<date>.01h\"\n PCPfile_secondary  = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.PCP.<date>\",\n/\n\n<VTABLE>\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\nGRIB1| Level| From |  To  |          |           |                                         |GRIB2|GRIB2|GRIB2|GRIB2|\nParam| Type |Level1|Level2| Name     | Units     | Description                             |Discp|Catgy|Param|Level|\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n  11 | 105  |   2  |      | T2D      | K         | Temperature       at 2 m                |  0  |  0  |  0  | 103 |\n  51 | 105  |   2  |      | Q2D      | kg kg{-1} | Specific Humidity at 2 m                |  0  |  1  |  0  | 103 |\n  33 | 105  |  10  |      | U2D      | m s-1     | U                 at 10 m               |  0  |  2  |  2  | 103 |\n  34 | 105  |  10  |      | V2D      | m s-1     | V                 at 10 m               |  0  |  2  |  3  | 103 |\n   1 |   1  |   0  |      | PSFC     | Pa        | Surface Pressure                        |  0  |  3  |  0  |   1 |\n 144 | 112  |   0  |  10  | SMOIS_1  | kg m-3    | Soil Moist 0-10 cm below grn layer (Up) |  2  |  0  | 192 | 106 |\n 144 | 112  |  10  |  40  | SMOIS_2  | kg m-3    | Soil Moist 10-40 cm below grn layer     |  2  |  0  | 192 | 106 |\n 144 | 112  |  40  | 100  | SMOIS_3  | kg m-3    | Soil Moist 40-100 cm below grn layer    |  2  |  0  | 192 | 106 |\n 144 | 112  | 100  | 200  | SMOIS_4  | kg m-3    | Soil Moist 100-200 cm below gr layer    |  2  |  0  | 192 | 106 |\n  85 | 112  |   0  |  10  | STEMP_1  | K         | T 0-10 cm below ground layer (Upper)    |  2  |  0  |  2  | 106 |\n  85 | 112  |  10  |  40  | STEMP_2  | K         | T 10-40 cm below ground layer (Upper)   |  2  |  0  |  2  | 106 |\n  85 | 112  |  40  | 100  | STEMP_3  | K         | T 40-100 cm below ground layer (Upper)  |  2  |  0  |  2  | 106 |\n  85 | 112  | 100  | 200  | STEMP_4  | K         | T 100-200 cm below ground layer (Bottom)|  2  |  0  |  2  | 106 |\n  91 |   1  |   0  |      | SEAICE   | proprtn   | Ice flag                                | 10  |  2  |  0  |   1 |\n  81 |   1  |   0  |      | LANDSEA  | proprtn   | Land/Sea flag (1=land,0=sea in NAM)     |  2  |  0  |  0  |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Terrain field of source analysis        |  2  |  0  |  7  |   1 |\n  11 |   1  |   0  |      | SKINTEMP | K         | Skin temperature (can use for SST also) |  0  |  0  |  0  |   1 |\n  61 |   1  |   0  |      | RAINRATE | kg m-2    | Accumulated precipitation               |  0  |  1  |  8  |   1 |\n  65 |   1  |   0  |      | WEASD    | kg m-2    | Water equivalent snow depth             |  0  |  1  | 13  |   1 |\n 223 |   1  |   0  |      | CANWAT   | kg m-2    | Plant Canopy Surface Water              |  2  |  0  | 196 |   1 |\n 204 |   1  |   0  |      | SWDOWN   | W m-2     | Downward short-wave radiation flux      |  0  |  4  | 192 |   1 |\n 205 |   1  |   0  |      | LWDOWN   | W m-2     | Downward long-wave radiation flux       |  0  |  5  | 192 |   1 |\n 999 | 999  |   0  |      | TERRAIN  | m         | Source model terrain elevation          |  0  |  3  |  5  |   1 |\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n</VTABLE>\n"
  },
  {
    "path": "src/Land_models/Noah/HRLDAS_COLLECT_DATA/run/namelist.input",
    "content": "&files\n STARTDATE        = \"2001-08-01_00\"\n ENDDATE          = \"2001-09-01_00\"\n DataDir          = \"/scholar/kmanning/more_hrldas/data\"\n FULL_IC_FRQ      = 0\n RAINFALL_INTERP  = 0\n RESCALE_SHORTWAVE = .FALSE.\n\n! geo_em_flnm      = \"/scholar/kmanning/more_hrldas/grib2/redesign/STEP/geo_em.d01.nc\"\n! wrfinput_flnm    = \"/scholar/kmanning/more_hrldas/grib2/redesign/STEP/wrfinput_d01\"\n\n! geo_em_flnm      = \"/scholar/kmanning/more_hrldas/HRLDAS/HRLDAS_COLLECT_DATA/run/combined.minimal\"\n! wrfinput_flnm    = \"/scholar/kmanning/more_hrldas/HRLDAS/HRLDAS_COLLECT_DATA/run/combined.minimal\"\n\n! geo_em_flnm      = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_merc/geo_em.d01.nc\"\n! wrfinput_flnm    = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_merc/wrfinput_d01\"\n\n! geo_em_flnm      = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_ps/geo_em.d01.nc\"\n! wrfinput_flnm    = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_ps/wrfinput_d01\"\n\n! geo_em_flnm      = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_lambert/geo_em.d01.nc\"\n! wrfinput_flnm    = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_lambert/wrfinput_d01\"\n\n geo_em_flnm      = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_latlon/geo_em.d01.nc\"\n wrfinput_flnm    = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_latlon/wrfinput_d01\"\n\n! geo_em_flnm      = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_latlon2/geo_em.d01.nc\"\n! wrfinput_flnm    = \"/scholar/kmanning/more_hrldas/devel-3.2/wps_latlon2/wrfinput_d01\"\n\n Zfile_template     = \"<DataDir>/ETA_SFC_ELEVATION.GRIB\"\n\n Tfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.T.<date>\"\n Ufile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.U.<date>\",\n Vfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.V.<date>\",\n Pfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.P.<date>\",\n Qfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.Q.<date>\",\n LWfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.LW.<date>\",\n WEASDfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.WEASD.<date>\",\n CANWTfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.CANWAT.<date>\",\n LANDSfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.LANDSEA.<date>\",\n SKINTfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SKINTEMP.<date>\",\n\n STfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_000-010.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_010-040.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_040-100.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_100-200.<date>\",\n\n SMfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_000-010.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_010-040.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_040-100.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_100-200.<date>\",\n\n SWfile_primary     = \"<DataDir>/SRB_restamped/SW.<date>30.grb\",\n\n SWfile_secondary   = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.SW.<date>\",\n\n PCPfile_primary    = \"<DataDir>/<YYYY>/<MM>/<DD>/ST4.<date>.01h\"\n ! PCPfile_primary  = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.PCP.<date>\",\n\n PCPfile_secondary  = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.PCP.<date>\",\n/\n\n<VTABLE>\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\nGRIB1| Level| From |  To  |          |           |                                         |GRIB2|GRIB2|GRIB2|GRIB2|\nParam| Type |Level1|Level2| Name     | Units     | Description                             |Discp|Catgy|Param|Level|\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n  11 | 105  |   2  |      | T2D      | K         | Temperature       at 2 m                |  0  |  0  |  0  | 103 |\n  51 | 105  |   2  |      | Q2D      | kg kg{-1} | Specific Humidity at 2 m                |  0  |  1  |  0  | 103 |\n  33 | 105  |  10  |      | U2D      | m s-1     | U                 at 10 m               |  0  |  2  |  2  | 103 |\n  34 | 105  |  10  |      | V2D      | m s-1     | V                 at 10 m               |  0  |  2  |  3  | 103 |\n   1 |   1  |   0  |      | PSFC     | Pa        | Surface Pressure                        |  0  |  3  |  0  |   1 |\n 144 | 112  |   0  |  10  | SMOIS_1  | kg m-3    | Soil Moist 0-10 cm below grn layer (Up) |  2  |  0  | 192 | 106 |\n 144 | 112  |  10  |  40  | SMOIS_2  | kg m-3    | Soil Moist 10-40 cm below grn layer     |  2  |  0  | 192 | 106 |\n 144 | 112  |  40  | 100  | SMOIS_3  | kg m-3    | Soil Moist 40-100 cm below grn layer    |  2  |  0  | 192 | 106 |\n 144 | 112  | 100  | 200  | SMOIS_4  | kg m-3    | Soil Moist 100-200 cm below gr layer    |  2  |  0  | 192 | 106 |\n  85 | 112  |   0  |  10  | STEMP_1  | K         | T 0-10 cm below ground layer (Upper)    |  2  |  0  |  2  | 106 |\n  85 | 112  |  10  |  40  | STEMP_2  | K         | T 10-40 cm below ground layer (Upper)   |  2  |  0  |  2  | 106 |\n  85 | 112  |  40  | 100  | STEMP_3  | K         | T 40-100 cm below ground layer (Upper)  |  2  |  0  |  2  | 106 |\n  85 | 112  | 100  | 200  | STEMP_4  | K         | T 100-200 cm below ground layer (Bottom)|  2  |  0  |  2  | 106 |\n  91 |   1  |   0  |      | SEAICE   | proprtn   | Ice flag                                | 10  |  2  |  0  |   1 |\n  81 |   1  |   0  |      | LANDSEA  | proprtn   | Land/Sea flag (1=land,0=sea in NAM)     |  2  |  0  |  0  |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Terrain field of source analysis        |  2  |  0  |  7  |   1 |\n  11 |   1  |   0  |      | SKINTEMP | K         | Skin temperature (can use for SST also) |  0  |  0  |  0  |   1 |\n  61 |   1  |   0  |      | RAINRATE | kg m-2    | Accumulated precipitation               |  0  |  1  |  8  |   1 |\n  65 |   1  |   0  |      | WEASD    | kg m-2    | Water equivalent snow depth             |  0  |  1  | 13  |   1 |\n 223 |   1  |   0  |      | CANWAT   | kg m-2    | Plant Canopy Surface Water              |  2  |  0  | 196 |   1 |\n 204 |   1  |   0  |      | SWDOWN   | W m-2     | Downward short-wave radiation flux      |  0  |  4  | 192 |   1 |\n 205 |   1  |   0  |      | LWDOWN   | W m-2     | Downward long-wave radiation flux       |  0  |  5  | 192 |   1 |\n 999 | 999  |   0  |      | TERRAIN  | m         | Source model terrain elevation          |  0  |  3  |  5  |   1 |\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n</VTABLE>\n"
  },
  {
    "path": "src/Land_models/Noah/IO_code/Makefile",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\ninclude ../user_build_options\n\nOBJS = \\\n\tNoah_hrldas_driver.o \\\n\tmodule_hrldas_netcdf_io.o\n\nCPPHRLDAS = -D_HRLDAS_OFFLINE_\n\nall:\t$(OBJS)\n\nNoah_hrldas_driver.o: Noah_hrldas_driver.F\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c $(F90FLAGS) $(FREESOURCE) $(MODFLAG). \\\n\t$(MODFLAG)../Noah $(MODFLAG)../Utility_routines -I../../../MPP $(NETCDFMOD) $(*).F\n\t@echo \"\"\n\nmodule_hrldas_netcdf_io.o: module_hrldas_netcdf_io.F\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS)  -o $(@) -c $(F90FLAGS) $(FREESOURCE) $(MODFLAG)../Utility_routines $(NETCDFMOD)  $(*).F\n\t@echo \"\"\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c $(F90FLAGS) $(FREESOURCE) $(*).F\n\t@echo \"\"\n\n\n\n#\n# Dependencies:\n#\n\nNoah_hrldas_driver.o:\tmodule_hrldas_netcdf_io.o\n\n# This command cleans up object files, etc.\nclean:\n\t$(RM) *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Land_models/Noah/IO_code/Noah_hrldas_driver.F",
    "content": "program Noah_hrldas_driver\n\n  USE module_hrldas_netcdf_io\n  USE module_Noahlsm_utility\n  USE module_sf_noahlsm\n  USE module_sf_urban\n  USE module_sfcdif_wrf\n  USE module_date_utilities\n\n#ifdef MPP_LAND\n  use module_mpp_land, only: MPP_LAND_PAR_INI, mpp_land_init, HYDRO_COMM_WORLD\n  use mpi\n#endif\n  IMPLICIT NONE\n\n\n  character(len=9), parameter :: version = \"v20110427\"\n  integer :: LDASIN_VERSION\n\n  ! Dummy parameterized dimension for maximum number of soil levels allowed\n  INTEGER, PARAMETER :: NSOLDX = 100\n  integer :: yw_rst_out\n\n  ! ZSOIL, set through the namelist, is the BOTTOM of each soil layer (m)\n  ! Values are negative, implying depth below the surface.\n  REAL, DIMENSION(NSOLDX) :: ZSOIL\n\n  REAL :: T1V,TH2V\n  LOGICAL :: FNDSNOWH\n\n!-----------------------------------------------------------------\n!  Dimensions from the input file:\n!-----------------------------------------------------------------\n\n!     IX: x-direction points, usually the west-east dimension\n!     JX: y-direction points, usually the south-north dimension\n  INTEGER :: IX\n  INTEGER :: JX\n\n!\n! Attributes from LDASIN input file (or HRLDAS_CONSTANTS_FILE, as the case may be)\n  REAL              :: DX\n  REAL              :: DY\n  REAL              :: TRUELAT1\n  REAL              :: TRUELAT2\n  REAL              :: CEN_LON\n  INTEGER           :: MAPPROJ\n  REAL              :: LAT1\n  REAL              :: LON1\n  INTEGER           :: ISWATER\n\n!-----------------------------------------------------------------\n!  DECLARE VARIABLES FOR GRIDDED SIMULATION\n!-----------------------------------------------------------------\n\n! the following parameters are read from a namelist file\n\n! setup model configuration\n  INTEGER :: KHOUR\n  INTEGER :: KDAY\n\n! Unaccounted-for variables when compiling w/ implicit none F90\n\n  REAL   :: SNOFAC\n  REAL   :: RHO,CHKFF\n\n  INTEGER   :: i,j,k,ns,ierr\n  INTEGER   :: NTIME\n  REAL      :: FRACTION\n\n! Gridded fields\n\n  REAL,    allocatable, DIMENSION(:,:)   :: infxsrt,sfcheadrt, soldrain\n  integer :: forc_typ, snow_assim, HRLDAS_ini_typ\n\n  real, allocatable, dimension(:,:) ::  qsgw\n  integer :: gwsoilcpl\n\n  INTEGER, allocatable, DIMENSION(:,:)   :: VEGTYP,SOLTYP\n  REAL,    allocatable, DIMENSION(:,:)   :: TERRAIN, LATITUDE, LONGITUDE\n  REAL,    allocatable, DIMENSION(:,:)   :: refdk2d, refkdt2d\n  REAL,    allocatable, DIMENSION(:,:)   :: T2,XLONG,U,V,PRES,SHORT,PRCP1, prcp_old\n  REAL,    allocatable, DIMENSION(:,:)   :: FPAR, ZNT, LAI, TBOT_2D, FPAR_SAVE, LAI_SAVE\n  REAL,    allocatable, DIMENSION(:,:)   :: CMC,SNODEP,WEASD,T1\n  REAL,    allocatable, DIMENSION(:,:)   :: ETPX,ETAX,GRDFLX,CHX,RUNOFF1X,RUNOFF2X\n  REAL,    allocatable, DIMENSION(:,:)   :: ETAKIN, QFX\n  REAL,    allocatable, DIMENSION(:,:)   :: RUNOFF3X,EDIRX,ECX,ETTX,SNMAXX,RCX,HX\n  REAL,    allocatable, DIMENSION(:,:)   :: Q2X,SFCSPDX,ALBEDX,SMCMAX1,SMCWLT1\n  REAL,    allocatable, DIMENSION(:,:)   :: SMCREF1,FX,RESX\n  REAL,    allocatable, DIMENSION(:,:)   :: SNOFLXX,SNOEVPX,ACSNOM,ESNOW2D,ACRAIN\n  REAL,    allocatable, DIMENSION(:,:)   :: DRIP2D, DEWFALL, SOILMX, EMISS, XLAI2D\n  REAL,    allocatable, DIMENSION(:,:)   :: SNOTIME\n  REAL,    allocatable, DIMENSION(:,:)   :: EMBRD2D\n  REAL,    allocatable, DIMENSION(:,:)   :: SNOALB2D\n  REAL,    allocatable, DIMENSION(:,:)   :: NOAHRES\n  REAL,    allocatable, DIMENSION(:,:)   :: CMX\n  REAL,    allocatable, DIMENSION(:,:)   :: Q12D\n!KWM  REAL,    allocatable, DIMENSION(:,:)   :: ETPNDX, SFCHEAD, INFXS1, PDDUM2, PCPDRP, SFCWATR2\n\n  REAL,    allocatable, DIMENSION(:,:,:) :: SMC,STC,SH2OX\n  REAL,    allocatable, DIMENSION(:,:,:) :: ZSOILX\n  REAL,    allocatable, DIMENSION(:,:,:) :: SMAV2D\n\n  ! Min/Max values from the 12-monthly Green Vegetation Fraction:\n  REAL,    allocatable, DIMENSION(:,:)   :: GVFMIN, GVFMAX\n\n  REAL,    allocatable, DIMENSION(:,:)   :: etpnd, greenfrac\n  real :: etpnd1\n\n\n\n  real :: albbrd\n!---------------------------------------------------------------------\n! NEW VARIABLES ADDED DURING NOAH F90 UPGRADE CALL to SFLX\n!---------------------------------------------------------------------\n  REAL :: EMISSI\n  REAL :: EMBRD\n\n\n! INTENT(IN) to SFLX:\n  REAL    ::            FFROZP      ! Fraction of precipitation that is frozen\n  REAL    ::            SOLNET      ! Net solar radiaton (W m-2)\n  INTEGER, PARAMETER :: ICE = 0     ! Sea-ice flag  (=1: sea-ice, =0: land)\n  REAL    :: DT       ! Timestep (s) (DT should not exceed 3600 S, recommend 1800 s or less)\n  REAL    :: ZLVL     ! Height (m) above ground of atmospheric forcing variables\n  REAL    :: ZLVL_WIND! Height (m) above ground of atmospheric forcing variables for wind.\n  INTEGER :: NSOIL    ! Number of soil layers\n  REAL, ALLOCATABLE, DIMENSION(:) :: SLDPTH ! The THICKNESS (m) of each soil layer\n  CHARACTER(LEN=256) :: LLANDUSE ! (=USGS, using USGS landuse classification)\n  CHARACTER(LEN=256) :: LSOIL    ! (=STAS, using FAO/STATSGO soil texture classification)\n\n  REAL :: LWDN      ! LW downward radiation (W m-2; positive, not net longwave)\n  REAL :: SOLDN     ! Solar downward radiation (W m-2; positive, not net solar)\n  REAL :: SFCPRS    ! Pressure (Pa) at height ZLVL m above ground\n  REAL :: PRCP      ! Precip rate (kg m-2 s-1) (NOTE: this is a rate)\n  REAL :: SFCTMP    ! Air temperature (K) at height ZLVL m above ground\n  REAL :: Q2        ! Specific Humidity (kg kg-1) at height ZLVL m above ground\n  REAL :: SFCSPD    ! Wind speed (m s-1) at height ZLVL m above ground\n  REAL :: PRCPRAIN  ! Liquid-precipitation rate (KG M-2 S-1) (not used)\n  REAL :: TH2       ! Air potential temperature (K) at height ZLVL m above ground\n  REAL :: Q2SAT     ! Saturation specific humidity (kg kg-1) at height ZLVL m above ground\n  REAL :: DQSDT2    ! Slope of saturation specific humidity curve  (kg kg-1 K-1) at T=SFCTMP\n  INTEGER :: VEGTYPX! Vegetation type (integer index)\n  INTEGER :: SOILTYP! Soil type (integer index)\n  INTEGER ::SLOPETYP! Class of sfc slope (integer index)\n  REAL :: SHDMIN    ! Minimum areal fractional coverage of green vegetation\n  !         (dimensionless fraction 0.0-1.0) <= SHDFAC\n  REAL :: SHDMAX    !UNDOCUMENTED IN SFLX\n  REAL :: TBOT      ! Bottom soil temperature (local yearly-mean of surfacc air temperature)\n  LOGICAL :: RDLAI2D = .FALSE.\n  LOGICAL :: USEMONALB = .FALSE.\n  REAL    :: RIBB = 0.0\n\n\n! INTENT(INOUT) to/from SFLX:\n  REAL :: SNCOVR  ! Fractional snow cover (dimensionless fraction, 0.0-1.0)\n  REAL :: COSZ    ! Solar zenith angle\n  REAL :: DECLIN  ! Solar declension (rad)\n  REAL :: SOLARDIRECT ! Direct component of downward solar radiation (W m-2) (not used)\n  REAL :: Z0      ! Time varying roughness length (m) as function of snow depth\n  REAL :: CMCX    ! Canopy moisture content (m)\n  REAL :: T1X     ! Ground/Canopy/Snowpack effective skin temperature (K)\n  REAL, allocatable, DIMENSION(:)  :: STC1    ! Soil temp (K)\n  REAL, allocatable, DIMENSION(:)  :: SMC1    ! Total soil moisture content (volumetric fraction)\n  REAL, allocatable, DIMENSION(:)  :: SH2O    ! Unfrozen soil moisture content (volumetric fraction)\n  !          NOTE: Frozen soil moisture = SMC - SH2O\n  REAL :: SNOWH   ! Actual snow depth (m)\n  REAL :: SNEQV   ! Liquid water-equivalent snow depth (m)\n  !       NOTE: snow density = SNEQV/SNOWH\n  REAL :: ALBEDO  ! Surface albedo including snow effect (unitless fraction)\n  !      =snow-free albedo (ALB) when SNEQV=0, or\n  !      =FCT(MSNOALB,ALB,VEGTYP,SHDFAC,SHDMIN) when SNEQV>0\n  REAL :: CH      ! Surface exchange coefficient for heat and moisture\n  !   (m s-1); NOTE: CH is technically a conductance since\n  !   it has been multiplied by wind speed.\n  REAL :: CM      ! Surface exchange coefficient for momentum (m s-1); NOTE:\n  !   CM is technically a conductance since it has been\n  !   multiplied by wind speed.\n  REAL :: SNOTIME1\n\n! INTENT(OUT) from SFLX:\n  REAL :: ETT     ! Total plant transpiration (W m-2)\n  REAL :: ETA     ! Actual latent heat flux (W m-2: negative, if up from surface)\n!KWM ???  Is the note about the sign of ETA right ???? !KWM\n  REAL :: SHEAT   ! Sensible heat flux (W m-2: negative, if upward from surface)\n  REAL :: ETA_KINEMATIC ! Actual latent heat flux (kg m/s)\n  REAL :: FDOWN   ! Radiation forcing at the surface (W m-2) = SOLDN*(1-alb)+LWDN\n  REAL :: EC      ! Canopy water evaporation (W m-2)\n  REAL :: EDIR    ! Direct soil evaporation (W m-2)\n  REAL, allocatable, DIMENSION(:) :: ET      ! Plant transpiration from a particular root (soil) layer (W m-2)\n  REAL :: ESNOW   ! Sublimation from (or deposition to if <0) snowpack (W m-2)\n  REAL :: DRIP    ! Through-fall of precip and/or dew in excess of canopy\n  ! water-holding capacity (m)\n  REAL :: DEW     ! Dewfall (or Frostfall for T<273.15) (m)\n\n  REAL :: BETA    ! Ratio of actual to potential evap (dimensionless)\n  REAL :: ETP     ! Potential Evaporation (w m-2)\n  REAL :: SSOIL   ! Soil heat flux (W m-2: negative if downward from surface)\n  REAL :: FLX1    ! Precip-snow sfc (W m-2)\n  REAL :: FLX2    ! Freezing rain latent heat flux (W m-2)\n  REAL :: FLX3    ! Phase-change heat flux from snowmelt (W m-2)\n  REAL :: SNOMLT  ! Snow melt (m) (water equivalent)\n  REAL :: RUNOFF1 ! Surface runoff (m s-1), not infiltrating the surface\n  REAL :: RUNOFF2 ! Subsurface runoff (m s-1), drainage out bottom of last\n  !       soil layer (baseflow).  Note: RUNOFF2 is actually\n  !       the sum of RUNOFF2 and RUNOFF3\n  REAL :: RUNOFF3 ! Numerical trunctation in excess of porosity (SMCMAX)\n  ! for a given soil layer at the end of a time step (m s-1).\n  REAL :: RC      ! Canopy resistance (s m-1)\n  REAL :: PC      ! Plant coefficient (dimensionless fraction, 0.0-1.0)\n  ! where PC*ETP = actual transpiration\n  REAL :: RCS     ! Incoming solar RC factor (dimensionless)\n  REAL :: RCT     ! Air temperature RC factor (dimensionless)\n  REAL :: RCQ     ! Atmos. vapor pressure deficit RC factor (dimensionless)\n  REAL :: RCSOIL  ! Soil moisture RC factor (dimensionless)\n  REAL :: SOILW   ! Available soil moisture in root zone (dimensionless fraction\n  !      between SMCWLT and SMCMAX)\n  REAL :: SOILM   ! Total soil column moisture content (frozen+unfrozen) (m)\n  REAL :: Q1      ! Effective specific humidity at surface (kg kg-1), used for\n  !      diagnosing the specific humidity at 2 meter for\n  !      coupled model\n  REAL, allocatable, dimension(:) :: SMAV    ! Documentation?\n\n  real ::  snoalb, frzx\n  logical :: local = .TRUE.\n\n  character(len=4) :: MMINSL\n\n! Timing:\n  integer :: clock_count_1 = 0\n  integer :: clock_count_2 = 0\n  integer :: clock_rate    = 0\n  real    :: timing_sum    = 0.0\n\n#ifdef _HRLDAS_URBAN_\n! ----------------------------------------------------------------------\n! DECLARATIONS START - urban\n! ----------------------------------------------------------------------\n\n  INTEGER :: KROOF\n  INTEGER :: KWALL\n  INTEGER :: KROAD\n! input variables surface_driver --> lsm\n  INTEGER, parameter  :: num_roof_layers = 4\n  INTEGER, parameter  :: num_wall_layers = 4\n  INTEGER, parameter  :: num_road_layers = 4\n\n  REAL, DIMENSION(1:num_roof_layers)  :: DZR\n  REAL, DIMENSION(1:num_wall_layers)  :: DZB\n  REAL, DIMENSION(1:num_road_layers)  :: DZG\n\n! input variables lsm --> urban\n  INTEGER :: UTYPE_URB ! urban type [urban=1, suburban=2, rural=3]\n  REAL :: TA_URB       ! potential temp at 1st atmospheric level [K]\n  REAL :: QA_URB       ! mixing ratio at 1st atmospheric level  [kg/kg]\n  REAL :: UA_URB       ! wind speed at 1st atmospheric level    [m/s]\n  REAL :: U1_URB       ! u at 1st atmospheric level             [m/s]\n  REAL :: V1_URB       ! v at 1st atmospheric level             [m/s]\n  REAL :: SSG_URB      ! downward total short wave radiation    [W/m/m]\n  REAL :: LLG_URB      ! downward long wave radiation           [W/m/m]\n  REAL :: RAIN_URB     ! precipitation                          [mm/h]\n  REAL :: RHOO_URB     ! air density                            [kg/m^3]\n  REAL :: ZA_URB       ! first atmospheric level                [m]\n  REAL :: DELT_URB     ! time step                              [s]\n  REAL :: SSGD_URB     ! downward direct short wave radiation   [W/m/m]\n  REAL :: SSGQ_URB     ! downward diffuse short wave radiation  [W/m/m]\n  REAL :: XLAT_URB     ! latitude                               [deg]\n  REAL :: OMG_URB      ! hour angle\n  REAL :: ZNT_URB      ! roughness length                       [m]\n  REAL :: TR_URB\n  REAL :: TB_URB\n  REAL :: TG_URB\n  REAL :: TC_URB\n  REAL :: QC_URB\n  REAL :: UC_URB\n  REAL :: XXXR_URB\n  REAL :: XXXB_URB\n  REAL :: XXXG_URB\n  REAL :: XXXC_URB\n  REAL, DIMENSION(1:num_roof_layers) :: TRL_URB  ! roof layer temp [K]\n  REAL, DIMENSION(1:num_wall_layers) :: TBL_URB  ! wall layer temp [K]\n  REAL, DIMENSION(1:num_road_layers) :: TGL_URB  ! road layer temp [K]\n  LOGICAL :: LSOLAR_URB\n! state variable surface_driver <--> lsm <--> urban\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: TR_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: TB_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: TG_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: TC_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: QC_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: UC_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: XXXR_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: XXXB_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: XXXG_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: XXXC_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: SH_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: LH_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: G_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: RN_URB2D\n!\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: TS_URB2D\n\n  REAL, ALLOCATABLE, DIMENSION( :, :, :) :: TRL_URB3D\n  REAL, ALLOCATABLE, DIMENSION( :, :, :) :: TBL_URB3D\n  REAL, ALLOCATABLE, DIMENSION( :, :, :) :: TGL_URB3D\n\n! output variable lsm --> surface_driver\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: PSIM_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: PSIH_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: GZ1OZ0_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: U10_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: V10_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: TH2_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: Q2_URB2D\n!\n!m     REAL, ALLOCATABLE, DIMENSION(:,:) :: AKHS_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: AKMS_URB2D\n!\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: UST_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: FRC_URB2D\n  INTEGER, ALLOCATABLE, DIMENSION(:,:) :: UTYPE_URB2D\n\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: CMR_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: CHR_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: CMC_URB2D\n  REAL, ALLOCATABLE, DIMENSION(:,:) :: CHC_URB2D\n\n! output variables urban --> lsm\n  REAL :: TS_URB     ! surface radiative temperature    [K]\n  REAL :: QS_URB     ! surface humidity                 [-]\n  REAL :: SH_URB     ! sensible heat flux               [W/m/m]\n  REAL :: LH_URB     ! latent heat flux                 [W/m/m]\n  REAL :: LH_KINEMATIC_URB ! latent heat flux, kinetic  [kg/m/m/s]\n  REAL :: SW_URB     ! upward short wave radiation flux [W/m/m]\n  REAL :: ALB_URB    ! time-varying albedo            [fraction]\n  REAL :: LW_URB     ! upward long wave radiation flux  [W/m/m]\n  REAL :: G_URB      ! heat flux into the ground        [W/m/m]\n  REAL :: RN_URB     ! net radiation                    [W/m/m]\n  REAL :: PSIM_URB   ! shear f for momentum             [-]\n  REAL :: PSIH_URB   ! shear f for heat                 [-]\n  REAL :: GZ1OZ0_URB   ! shear f for heat                 [-]\n  REAL :: U10_URB    ! wind u component at 10 m         [m/s]\n  REAL :: V10_URB    ! wind v component at 10 m         [m/s]\n  REAL :: TH2_URB    ! potential temperature at 2 m     [K]\n  REAL :: Q2_URB     ! humidity at 2 m                  [-]\n  REAL :: CHS_URB\n  REAL :: CHS2_URB\n  REAL :: UST_URB\n  REAL :: CMR_URB\n  REAL :: CHR_URB\n  REAL :: CMC_URB\n  REAL :: CHC_URB\n\n  integer :: NUM_URBAN_LAYERS = 10\n\n  REAL, allocatable, dimension(:,:,:) :: TRB_URB4D\n  REAL, allocatable, dimension(:,:,:) :: TW1_URB4D\n  REAL, allocatable, dimension(:,:,:) :: TW2_URB4D\n  REAL, allocatable, dimension(:,:,:) :: TGB_URB4D\n  REAL, allocatable, dimension(:,:,:) :: SFW1_URB3D\n  REAL, allocatable, dimension(:,:,:) :: SFW2_URB3D\n  REAL, allocatable, dimension(:,:,:) :: SFR_URB3D\n  REAL, allocatable, dimension(:,:,:) :: SFG_URB3D\n\n  REAL, allocatable, dimension(:,:,:) :: A_U_BEP\n  REAL, allocatable, dimension(:,:,:) :: A_V_BEP\n  REAL, allocatable, dimension(:,:,:) :: A_T_BEP\n  REAL, allocatable, dimension(:,:,:) :: A_Q_BEP\n  REAL, allocatable, dimension(:,:,:) :: A_E_BEP\n  REAL, allocatable, dimension(:,:,:) :: B_U_BEP\n  REAL, allocatable, dimension(:,:,:) :: B_V_BEP\n  REAL, allocatable, dimension(:,:,:) :: B_T_BEP\n  REAL, allocatable, dimension(:,:,:) :: B_Q_BEP\n  REAL, allocatable, dimension(:,:,:) :: B_E_BEP\n  REAL, allocatable, dimension(:,:,:) :: VL_BEP\n  REAL, allocatable, dimension(:,:,:) :: DLG_BEP\n  REAL, allocatable, dimension(:,:,:) :: SF_BEP\n  REAL, allocatable, dimension(:,:,:) :: DL_U_BEP\n\n  REAL, allocatable, dimension(:,:,:) :: TLEV_URB3D\n  REAL, allocatable, dimension(:,:,:) :: QLEV_URB3D\n  REAL, allocatable, dimension(:,:,:) :: TW1LEV_URB3D\n  REAL, allocatable, dimension(:,:,:) :: TW2LEV_URB3D\n  REAL, allocatable, dimension(:,:,:) :: TGLEV_URB3D\n  REAL, allocatable, dimension(:,:,:) :: TFLEV_URB3D\n  REAL, allocatable, dimension(:,:,:) :: SFWIN1_URB3D\n  REAL, allocatable, dimension(:,:,:) :: SFWIN2_URB3D\n  REAL, allocatable, dimension(:,:  ) :: LF_AC_URB3D\n  REAL, allocatable, dimension(:,:  ) :: SF_AC_URB3D\n  REAL, allocatable, dimension(:,:  ) :: CM_AC_URB3D\n  REAL, allocatable, dimension(:,:  ) :: SFVENT_URB3D\n  REAL, allocatable, dimension(:,:  ) :: LFVENT_URB3D\n\n\n! ----------------------------------------------------------------------\n! DECLARATIONS END - urban\n! ----------------------------------------------------------------------\n\n#endif\n\n  real :: CFACTR, CMCMAX, RSMAX, TOPT, REFKDT, KDT, SBETA, SHDFAC, RSMIN\n  real :: RGL, HS, ZBOT, PSISAT, SLOPE, SNUP, SALP, BEXP, DKSAT, DWSAT\n  real :: SMCMAX, SMCWLT, SMCREF, SMCDRY, F1, QUARTZ, FXEXP, Z0BRD, CZIL\n  real :: XLAI, CSOIL, ALB, PTU, ALBEDOMIN, ALBEDOMAX\n  real :: EMISSMIN, EMISSMAX, LAIMIN, LAIMAX, Z0MIN, Z0MAXnoah\n  real, dimension(NSOLD) :: RTDIS\n  integer :: NROOT\n  real :: LVCOEF\n\n!---------------------------------------------------------------------\n!  DECLARE/Initialize constants\n!---------------------------------------------------------------------\n\n  REAL, PARAMETER :: R=287.04\n  REAL, PARAMETER :: CPHEAT=1004.5\n  INTEGER, PARAMETER :: LAND=1\n\n  character(len=19) :: olddate, newdate, startdate,forcDate\n  CHARACTER(len=256) :: inflnm, outflnm, inflnm_template\n  character :: hgrid\n  integer   :: igrid\n\n  logical            :: restart_flag\n\n! NAMELIST:\n\n  CHARACTER(len=256) :: indir\n  character(len=256) :: outdir = \".\"\n  character(len=256) :: hrldas_constants_file = \" \"\n  character(len=256) :: external_fpar_filename_template = \" \"\n  character(len=256) :: external_lai_filename_template = \" \"\n  character(len=256) :: restart_filename_requested = \" \"\n  integer            :: split_output_count = 1\n  integer            :: restart_frequency_hours\n  integer            :: output_timestep\n  integer            :: subwindow_xstart = 1\n  integer            :: subwindow_ystart = 1\n  integer            :: subwindow_xend = 0\n  integer            :: subwindow_yend = 0\n  integer            :: sfcdif_option = 0\n  integer            :: iz0tlnd = 0\n  logical            :: update_snow_from_forcing = .TRUE.\n\n  integer :: START_YEAR, START_MONTH, START_DAY, START_HOUR, START_MIN\n  integer :: noah_timestep = -999\n  integer :: forcing_timestep = -999\n  character(len = 256):: GEO_STATIC_FLNM\n\n  integer :: gwCycle, GWBASESWCRT\n\n  namelist / NOAHLSM_OFFLINE/ INDIR, NSOIL, ZSOIL, FORCING_TIMESTEP, NOAH_TIMESTEP, &\n       START_YEAR, START_MONTH, START_DAY, START_HOUR, START_MIN, &\n       RESTART_FREQUENCY_HOURS, OUTPUT_TIMESTEP, &\n       SPLIT_OUTPUT_COUNT, SFCDIF_OPTION, IZ0TLND, UPDATE_SNOW_FROM_FORCING, &\n       KHOUR, KDAY, ZLVL, ZLVL_WIND, HRLDAS_CONSTANTS_FILE, OUTDIR, RESTART_FILENAME_REQUESTED, &\n       external_fpar_filename_template, external_lai_filename_template, &\n       subwindow_xstart, subwindow_xend, subwindow_ystart, subwindow_yend, &\n       forc_typ, snow_assim , GEO_STATIC_FLNM, HRLDAS_ini_typ\n  INTEGER  ::  sf_urban_physics = 0                       !urban\n#ifdef _HRLDAS_URBAN_\n  REAL     ::  zlvl_urban\n  namelist / URBAN_OFFLINE / SF_URBAN_PHYSICS, ZLVL_URBAN\n#endif\n!KWM       , VEGMIN, VEGMAX\n\n  integer, parameter :: iunit = 10\n  integer, parameter :: ounit = 11\n\n  integer :: parallel_xstart\n  integer :: parallel_xend\n  integer :: ixfull\n  integer :: jxfull\n  integer :: ixpar\n  integer :: jxpar\n  integer :: xstartpar\n  integer :: ystartpar\n  integer :: nlandpts\n  integer :: rank\n  integer :: imode\n  character(len=256) :: restart_flnm\n\n#ifdef _PARALLEL_\n  integer :: numtasks\n  real, pointer, dimension(:,:) :: vegtyp_ptr\n  integer :: send_tag\n  integer :: recv_tag\n  integer :: istatus\n  integer :: ip\n#endif\n\n#ifdef MPP_LAND\n  call MPP_LAND_INIT()\n  call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n#else\n  rank = 0\n#endif\n  if(rank == 0) then\n\n  LSOIL = 'STAS'\n\n  ! Initialize namelist variables to dummy values, so we can tell\n  ! if they have not been set properly.\n\n  nsoil = 4\n  zsoil = -1.E36\n  zsoil(1:4) = (/ -0.05, -0.25, -0.7, -1.5 /)\n\n  dt = -999.\n\n  start_year = -999\n  start_month = -999\n  start_day = -999\n  start_hour = -999\n  start_min = -999\n  khour = -999\n  kday = -999\n\n  zlvl = 2.0\n  zlvl_wind = 10.0\n!KWM  vegmin = -999.\n!KWM  vegmax = -999.\n\n  output_timestep = 0\n  restart_frequency_hours = 0\n\n  open(30, file=\"namelist.hrldas\", form=\"FORMATTED\")\n  read(30, NOAHLSM_OFFLINE, iostat=ierr)\n  if (ierr /= 0) then\n     write(*,'(/,\" ***** ERROR: Problem reading namelist NOAHLSM_OFFLINE\",/)')\n     rewind(30)\n     read(30, NOAHLSM_OFFLINE)\n     stop \" ***** ERROR: Problem reading namelist NOAHLSM_OFFLINE\"\n  endif\n#ifdef _HRLDAS_URBAN_\n  zlvl_urban = 15.0 ! Default value\n  read(30, URBAN_OFFLINE, iostat=ierr)\n  if (ierr /= 0) then\n     write(*,'(/,\" ***** ERROR: Problem reading namelist URBAN_OFFLINE\",/)')\n     rewind(30)\n     read(30, URBAN_OFFLINE)\n     stop \" ***** ERROR: Problem reading namelist URBAN_OFFLINE\"\n  endif\n#endif\n\n  close(30)\n\n  if ((khour < 0) .and. (kday < 0)) then\n     write(*, '(\" ***** Namelist error: ************************************\")')\n     write(*, '(\" ***** \")')\n     write(*, '(\" *****      Either KHOUR or KDAY must be defined.\")')\n     write(*, '(\" ***** \")')\n     stop\n  else if (( khour < 0 ) .and. (kday > 0)) then\n     khour = kday * 24\n  else if ((khour > 0) .and. (kday > 0)) then\n     write(*, '(\"Namelist warning:  KHOUR and KDAY both defined.\")')\n  else\n     ! all is well.  KHOUR defined\n  endif\n\n  if (forcing_timestep < 0) then\n     write(*, *)\n     write(*, '(\" ***** Namelist error: *****************************************\")')\n     write(*, '(\" ***** \")')\n     write(*, '(\" *****       FORCING_TIMESTEP needs to be set greater than zero.\")')\n     write(*, '(\" ***** \")')\n     write(*, *)\n     stop\n  endif\n\n  if (noah_timestep < 0) then\n     write(*, *)\n     write(*, '(\" ***** Namelist error: *****************************************\")')\n     write(*, '(\" ***** \")')\n     write(*, '(\" *****       NOAH_TIMESTEP needs to be set greater than zero.\")')\n     write(*, '(\" *****                     900 seconds is recommended.       \")')\n     write(*, '(\" ***** \")')\n     write(*, *)\n     stop\n  endif\n\n  !\n  ! Check that OUTPUT_TIMESTEP fits into NOAH_TIMESTEP:\n  !\n  if (output_timestep /= 0) then\n     if (mod(output_timestep, noah_timestep) > 0) then\n        write(*, *)\n        write(*, '(\" ***** Namelist error: *********************************************************\")')\n        write(*, '(\" ***** \")')\n        write(*, '(\" *****       OUTPUT_TIMESTEP should be an integer multiple of NOAH_TIMESTEP.\")')\n        write(*, '(\" *****            OUTPUT_TIMESTEP = \", I12, \" seconds\")') output_timestep\n        write(*, '(\" *****            NOAH_TIMESTEP   = \", I12, \" seconds\")') noah_timestep\n        write(*, '(\" ***** \")')\n        write(*, *)\n        stop\n     endif\n  endif\n\n  !\n  ! Check that RESTART_FREQUENCY_HOURS fits into NOAH_TIMESTEP:\n  !\n  if (restart_frequency_hours /= 0) then\n     if (mod(restart_frequency_hours*3600, noah_timestep) > 0) then\n        write(*, *)\n        write(*, '(\" ***** Namelist error: ******************************************************\")')\n        write(*, '(\" ***** \")')\n        write(*, '(\" *****       RESTART_FREQUENCY_HOURS (converted to seconds) should be an \")')\n        write(*, '(\" *****       integer multiple of NOAH_TIMESTEP.\")')\n        write(*, '(\" *****            RESTART_FREQUENCY_HOURS = \", I12, \" hours:  \", I12, \" seconds\")') &\n             restart_frequency_hours, restart_frequency_hours*3600\n        write(*, '(\" *****            NOAH_TIMESTEP           = \", I12, \" seconds\")') noah_timestep\n        write(*, '(\" ***** \")')\n        write(*, *)\n        stop\n     endif\n  endif\n\n  dt = real(noah_timestep)\n\n#ifdef _PARALLEL_\n\n  call MPI_INIT(ierr)\n  if (ierr /= MPI_SUCCESS) stop \"MPI_INIT\"\n  call MPI_COMM_DUP(MPI_COMM_WORLD, HYDRO_COMM_WORLD, ierr)\n  if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_DUP\"\n\n  call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n  if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n\n  call MPI_COMM_SIZE(HYDRO_COMM_WORLD, numtasks, ierr)\n  if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_SIZE\"\n\n#else\n  rank = 0\n#endif\n\n  call read_hrldas_hdrinfo(hrldas_constants_file, ix, jx, &\n       subwindow_xstart, subwindow_xend, subwindow_ystart, subwindow_yend, &\n       iswater, isurban, llanduse, dx, dy, truelat1, truelat2, cen_lon, lat1, lon1, &\n#ifdef _PARALLEL_\n  igrid, mapproj, vegtyp_ptr)\n\n#else\n  igrid, mapproj)\n#endif\n\n  write(hgrid,'(I1)') igrid\n\n  if (nsoil < 0) then\n     stop \" ***** ERROR: NSOIL must be set in the namelist.\"\n  endif\n\n  write(olddate,'(I4.4,\"-\",I2.2,\"-\",I2.2,\"_\",I2.2,\":\",I2.2,\":\",I2.2)') &\n       start_year, start_month, start_day, start_hour, start_min, 0\n\n  startdate = olddate\n  forcdate = olddate\n\n!......................... end of model configuration (later in a namelist) .....\n\n!KWM#ifdef _PARALLEL_\n!KWM\n!KWM  nlandpts = count(vegtyp_ptr/=iswater)\n!KWM\n!KWM  call MPI_INIT(ierr)\n!KWM  if (ierr /= MPI_SUCCESS) stop \"MPI_INIT\"\n!KWM  call MPI_COMM_DUP(MPI_COMM_WORLD, HYDRO_COMM_WORLD, ierr)\n!KWM  if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_DUP\"\n!KWM\n!KWM  call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n!KWM  if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n!KWM\n!KWM  call MPI_COMM_SIZE(HYDRO_COMM_WORLD, numtasks, ierr)\n!KWM  if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_SIZE\"\n!KWM\n!KWM#else\n!KWM  rank = 0\n!KWM#endif\n\n  call check_outdir(rank, trim(outdir))\n\n  MMINSL='STAS'\n  CALL SOIL_VEG_GEN_PARM( LLANDUSE, MMINSL )\n\n!----------------------------------------------------------------------\n! Allocate arrays for our gridded domain, now that we know the size\n!----------------------------------------------------------------------\n  ixfull = subwindow_xend-subwindow_xstart+1\n  jxfull = subwindow_yend-subwindow_ystart+1\n\n#ifdef _PARALLEL_\n\n  ! Set up our parallal_xstart and parallel_xend values, the x-coordinate points over which\n  ! each particular process will span, such that the land points of the full domain are\n  ! approximately evenly distributed among the processors.  This will make the loop which calls\n  ! SFLX for the I/J points a little more balanced, but could make the\n  ! I/O a little less balanced.\n\n  if (rank == 0) then\n     nlandpts = count(vegtyp_ptr/=iswater)\n     j = 0\n     k= 0\n     do i = subwindow_xstart, subwindow_xend\n        k = k + count( vegtyp_ptr(i,:) /= iswater )\n        if ( ( k >= real(nlandpts*(j+1))/real(numtasks) ) .or. ( i == subwindow_xend ) ) then\n           write(*, '(\"Found range for rank \", I4, \":  points \", I6, I6, I6)') j, ip, i, (i-ip)+1\n\n           if ( j > 0 ) then\n              ! Send the starting and ending points we've computed to the appropriate process (rank).\n              call mpi_send( i, 1, MPI_INTEGER, j, 0, HYDRO_COMM_WORLD, ierr )\n              if (ierr /= MPI_SUCCESS) stop \"Problem with MPI_SEND\"\n              call mpi_send( ip, 1, MPI_INTEGER, j, 1, HYDRO_COMM_WORLD, ierr )\n              if (ierr /= MPI_SUCCESS) stop \"Problem with MPI_SEND\"\n           else\n              parallel_xstart = subwindow_xstart\n              parallel_xend = i\n           endif\n\n           j = j + 1\n           ip = i + 1\n        endif\n     enddo\n  else\n     call mpi_recv( parallel_xend, 1, MPI_INTEGER, 0, 0, HYDRO_COMM_WORLD, istatus, ierr )\n     if (ierr /= MPI_SUCCESS) stop \"Problem with MPI_RECV\"\n     call mpi_recv( parallel_xstart, 1, MPI_INTEGER, 0, 1, HYDRO_COMM_WORLD, istatus, ierr )\n     if (ierr /= MPI_SUCCESS) stop \"Problem with MPI_RECV\"\n     ! print*, 'Rank ', rank, ' received ', parallel_xstart, parallel_xend\n  endif\n\n  ixpar  = parallel_xend-parallel_xstart+1\n  jxpar  = jxfull\n  xstartpar = (parallel_xstart-subwindow_xstart)+1\n  ystartpar = 1\n\n#else\n  ! If we don't run parallel, the single task allocates the full requested subwindow.\n  parallel_xstart = subwindow_xstart\n  parallel_xend   = subwindow_xend\n  ixpar = ixfull\n  jxpar = jxfull\n  xstartpar = 1\n  ystartpar = 1\n#endif\n\n  ! print*, 'parallel_xstart, parallel_xend = ', parallel_xstart, parallel_xend\n\n  allocate( VEGTYP   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SOLTYP   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( TERRAIN  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( LATITUDE (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( LONGITUDE(PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( refdk2d  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( refkdt2d (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( T2       (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( XLONG    (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( U        (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( V        (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( PRES     (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SHORT    (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( PRCP1    (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( PRCP_old    (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( FPAR     (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ZNT      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( LAI      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( CMC      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SNODEP   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( WEASD    (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( T1       (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ETPX     (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ETAX     (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ETAKIN   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( GRDFLX   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( CHX      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( CMX      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( Q12D     (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( RUNOFF1X (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( RUNOFF2X (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( RUNOFF3X (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( EDIRX    (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ECX      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ETTX     (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SNMAXX   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( RCX      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( HX       (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( QFX      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( Q2X      (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SFCSPDX  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ALBEDX   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SMCMAX1  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SMCWLT1  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SMCREF1  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ACSNOM   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ACRAIN   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( ESNOW2D  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n!KWM  allocate( SNOFLXX  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SNOEVPX  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( FX       (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( RESX     (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( DRIP2D   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( DEWFALL  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SOILMX   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( EMISS    (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( XLAI2D   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( GVFMIN   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( GVFMAX   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( TBOT_2D  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SNOTIME  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( EMBRD2D  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( SNOALB2D (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n  allocate( NOAHRES  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n!KWM  allocate( ETPNDX   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n!KWM  allocate( SFCHEAD  (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n!KWM  allocate( INFXS1   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n!KWM  allocate( PDDUM2   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n!KWM  allocate( PCPDRP   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n!KWM  allocate( SFCWATR2 (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n\n  allocate( SMC   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND,NSOIL) )\n  allocate( STC   (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND,NSOIL) )\n  allocate( SH2OX (PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND,NSOIL) )\n  allocate( ZSOILX(PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND,NSOIL) )\n  allocate( SMAV2D(PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND,NSOIL) )\n\n  allocate( SH2O   (NSOIL) )\n  allocate( SLDPTH (NSOIL) )\n  allocate( SMC1   (NSOIL) )\n  allocate( STC1   (NSOIL) )\n  allocate( ET     (NSOIL) )\n  allocate( SMAV   (NSOIL) )\n\n#ifdef _HRLDAS_URBAN_\n  call urban_param_init(DZR,DZB,DZG,num_roof_layers, sf_urban_physics)\n  ALLOCATE(TR_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TB_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TG_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TC_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(QC_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(UC_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(XXXR_URB2D( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(XXXB_URB2D( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(XXXG_URB2D( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(XXXC_URB2D( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SH_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(LH_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(G_URB2D   ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(RN_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TS_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TRL_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND, 1:NUM_ROOF_LAYERS ) )\n  ALLOCATE(TBL_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND, 1:NUM_WALL_LAYERS ) )\n  ALLOCATE(TGL_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND, 1:NUM_ROAD_LAYERS ) )\n  ALLOCATE(PSIM_URB2D   ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(PSIH_URB2D   ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(GZ1OZ0_URB2D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(U10_URB2D    ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(V10_URB2D    ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TH2_URB2D    ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(Q2_URB2D     ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(AKMS_URB2D   ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(UST_URB2D    ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(FRC_URB2D    ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(UTYPE_URB2D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ! BEP:\n  ALLOCATE(TRB_URB4D    ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TW1_URB4D    ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TW2_URB4D    ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TGB_URB4D    ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SFW1_URB3D   ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SFW2_URB3D   ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SFR_URB3D    ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SFG_URB3D    ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n\n  ALLOCATE(A_U_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(A_V_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(A_T_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(A_Q_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(A_E_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(B_U_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(B_V_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(B_T_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(B_Q_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(B_E_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(VL_BEP       ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(DLG_BEP      ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SF_BEP       ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(DL_U_BEP     ( PARALLEL_XSTART:PARALLEL_XEND, 1, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TLEV_URB3D   ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(QLEV_URB3D   ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TW1LEV_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TW2LEV_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TGLEV_URB3D  ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(TFLEV_URB3D  ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SFWIN1_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SFWIN2_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, 1:NUM_URBAN_LAYERS, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(LF_AC_URB3D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SF_AC_URB3D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(CM_AC_URB3D  ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(SFVENT_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(LFVENT_URB3D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(CMR_URB2D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(CHR_URB2D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(CMC_URB2D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  ALLOCATE(CHC_URB2D ( PARALLEL_XSTART:PARALLEL_XEND, SUBWINDOW_YSTART:SUBWINDOW_YEND ) )\n  CMR_URB2D = 0.1\n  CHR_URB2D = 0.1\n  CMC_URB2D = 0.1\n  CHC_URB2D = 0.1\n#endif\n\n!----------------------------------------------------------------------\n! Initialize gridded domain\n!----------------------------------------------------------------------\n\n  ! SLDPTH is the thickness of each layer\n  SLDPTH(1) = -ZSOIL(1)\n  do i = 2, nsoil\n     sldpth(i) = zsoil(i-1)-zsoil(i)\n  enddo\n\n  ETAX=0.0 ! -999.9\n  ETAKIN=0.0 ! -999.9\n  ETPX=-999.9\n  CHX=-999.9\n  CMX = -999.0\n  FX=-999.9\n  HX=-999.9\n  RESX=-999.9\n  GRDFLX=-999.9\n  CMC=0.0\n  T2=-999.9\n  T1=-999.9\n  PRCP1=0\n  PRCP_old=0\n\n  RUNOFF1X=0.0\n  RUNOFF2X=0.0\n  RUNOFF3X=0.0\n  EDIRX=0.0\n  ETTX=0.0\n!FC  ETPNDX=-999.9\n  SNOEVPX=-999.9\n  SNODEP=-999.9\n  SNODEP = 0\n  WEASD = 0\n\n\n  STC=-999.9\n  SH2OX=-999.9\n  SMC=-999.9\n\n  ECX=0.0\n  ACSNOM  = 0.0\n  ACRAIN  = 0.0\n  ESNOW2D = 0.0\n  DRIP2D = 0.0\n  SNOTIME = 0.0\n  DEWFALL = 0.0\n  SOILMX = -999.\n  XLAI2D = 0.\n  GVFMIN = -999.\n  GVFMAX = -999.\n\n  LAI = 0.0\n\n!---------------------------------------------------------------------\n! Initialize static surface data\n!---------------------------------------------------------------------\n\n\n!   OK     VEGTYP     VEGETATION TYPE (INTEGER INDEX)\n!   OK     SOILTYP    SOIL TYPE (INTEGER INDEX)\n!   OK     SLOPETYP   CLASS OF SFC SLOPE (INTEGER INDEX)\n!          SHDMIN     MINIMUM AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!                (FRACTION= 0.0-1.0) <= SHDFAC\n!   N/U    PTU        PHOTO THERMAL UNIT (PLANT PHENOLOGY FOR ANNUALS/CROPS)\n!                (NOT YET USED, BUT PASSED TO REDPRM FOR FUTURE USE IN\n!                VEG PARMS)\n!   OK     ALB        BACKROUND SNOW-FREE SURFACE ALBEDO (FRACTION), FOR JULIAN\n!                DAY OF YEAR (USUALLY FROM TEMPORAL INTERPOLATION OF\n!                MONTHLY MEAN VALUES' CALLING PROG MAY OR MAY NOT\n!                INCLUDE DIURNAL SUN ANGLE EFFECT)\n!   OK     SNOALB     UPPER BOUND ON MAXIMUM ALBEDO OVER DEEP SNOW (E.G. FROM\n!                ROBINSON AND KUKLA, 1985, J. CLIM. & APPL. METEOR.)\n!   OK     TBOT       BOTTOM SOIL TEMPERATURE (LOCAL YEARLY-MEAN SFC AIR\n!                TEMPERATURE)\n!   ??     Z0BRD      Background fixed roughness length (M)\n!   ??     Z0         Time varying roughness length (M) as function of snow depth\n\n\n\n\n!----------------------------------------------------------------------\n! Read Landuse Type and Soil Texture and Other Information\n!----------------------------------------------------------------------\n\n  CALL READLAND_HRLDAS(hrldas_constants_file,                           &\n       parallel_xstart, parallel_xend,                                  &\n       subwindow_ystart, subwindow_yend,                                &\n       ISWATER, VEGTYP, SOLTYP, TERRAIN, TBOT_2D, LATITUDE, LONGITUDE,  &\n\t\t      refdk2d, refkdt2d)\n\n!----------------------------------------------------------------------\n! Initialize Model State\n!----------------------------------------------------------------------\n\n  SLOPETYP = 2\n\n  call myjsfcinit()\n\n  if (restart_filename_requested /= \" \") then\n\n     restart_flag = .TRUE.\n\n     call find_restart_file(rank, trim(restart_filename_requested), startdate, khour, olddate, restart_flnm)\n\n     call read_restart(trim(restart_flnm), sf_urban_physics, iz0tlnd, sfcdif_option,                        &\n          parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, nsoil, olddate)\n\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SOIL_T\"  , stc      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SOIL_M\"  , smc      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SOIL_W\"  , sh2ox    )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"QFX\"     , qfx      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SNODEP\"  , snodep   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"WEASD\"   , weasd    )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"FDOWN\"   , fx       )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ETP\"     , etpx     )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SKINTEMP\", t1       )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ETA\"     , etax     )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ETAKIN\"  , etakin   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"CANWAT\"  , cmc      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"GRDFLX\"  , grdflx   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"CH\"      , chx      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"RUNOFF1\" , runoff1x )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"RUNOFF2\" , runoff2x )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"RUNOFF3\" , runoff3x )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"EDIR\"    , edirx    )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"EC\"      , ecx      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ETT\"     , ettx     )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"RC\"      , rcx      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"HFX\"     , hx       )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SMCMAX\"  , smcmax1  )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SMCREF\"  , smcref1  )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SMCWLT\"  , smcwlt1  )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ALBED\"   , albedx   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ACRAIN\"  , acrain   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ACSNOM\"  , acsnom   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ESNOW\"   , esnow2d  )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"DRIP\"    , drip2d   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"DEWFALL\" , dewfall  )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SOIL_MX\" , soilmx   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"EMISS\"   , emiss    )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"FPAR\"    , fpar     )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"ZNT\"     , znt      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"GVFMIN\"  , gvfmin   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"GVFMAX\"  , gvfmax   )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"SNOTIME\" , snotime  )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"Q12D\"    , q12d     )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"CHX\"     , chx      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"CMX\"     , cmx      )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"LAI\"   , lai   )\n\n     allocate(fpar_save(PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"FPAR_SAVE\", fpar_save, ierr)\n     if (ierr /= 0) deallocate(fpar_save)\n\n     allocate(lai_save(PARALLEL_XSTART:PARALLEL_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n     call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"LAI_SAVE\",  lai_save,  ierr)\n     if (ierr /= 0) deallocate(lai_save)\n\n#ifdef _HRLDAS_URBAN_\n     if (sf_urban_physics == 1) then\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"TS_URB2D\"   , ts_urb2d   )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"TR_URB2D\"   , tr_urb2d   )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"TB_URB2D\"   , tb_urb2d   )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"TG_URB2D\"   , tg_urb2d   )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"TC_URB2D\"   , tc_urb2d   )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"QC_URB2D\"   , qc_urb2d   )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"UC_URB2D\"   , uc_urb2d   )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"TRL_URB3D\"  , trl_urb3d  )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"TBL_URB3D\"  , tbl_urb3d  )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"TGL_URB3D\"  , tgl_urb3d  )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"XXXR_URB2D\" , xxxr_urb2d )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"XXXB_URB2D\" , xxxb_urb2d )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"XXXG_URB2D\" , xxxg_urb2d )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"XXXC_URB2D\" , xxxc_urb2d )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"FRC_URB2D\"  , frc_urb2d  )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"UTYPE_URB2D\", utype_urb2d)\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"CMR_URB2D\"  , cmr_urb2d  )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"CHR_URB2D\"  , chr_urb2d  )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"CMC_URB2D\"  , cmc_urb2d  )\n        call get_from_restart(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, \"CHC_URB2D\"  , chc_urb2d  )\n     endif\n#endif\n\n  else\n\n     restart_flag = .FALSE.\n     inflnm = trim(indir)//\"/\"//&\n          startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n          \".LDASIN_DOMAIN\"//hgrid\n\n! only when forc_typ .eq. 1 or 2, HRLDAS_ini_typ can be set as 1\n  if(forc_typ .gt. 2)  HRLDAS_ini_typ = 0\n\n  if(HRLDAS_ini_typ .eq. 1) then\n     ! read initial parameters and conditions from the HRLDAS forcing data\n     if(forc_typ .eq. 2) then\n          inflnm = trim(indir)//\"/\"//&\n          startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n          startdate(15:16)//\".LDASIN_DOMAIN\"//hgrid\n     else\n          inflnm = trim(indir)//\"/\"//&\n          startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n          \".LDASIN_DOMAIN\"//hgrid\n     endif\n     CALL READINIT_HRLDAS(inflnm, &\n          parallel_xstart, parallel_xend, subwindow_ystart, subwindow_yend,  &\n          NSOIL, SLDPTH, OLDDATE, LDASIN_VERSION, SMC, STC, SH2OX, CMC, T1, &\n          WEASD, SNODEP)\n     ! *** Read lai, fveg etc.\n\n\n     CALL READVEG_HRLDAS(inflnm, &\n          parallel_xstart, parallel_xend, subwindow_ystart, subwindow_yend,  &\n          OLDDATE, VEGTYP, FPAR, LAI, GVFMIN, GVFMAX)\n\n  else\n    call HYDRO_HRLDAS_ini(trim(hrldas_constants_file),&\n       parallel_xend-parallel_xstart+1,subwindow_yend-subwindow_ystart+1, &\n       nsoil,smc,stc,sh2ox, cmc, t1, weasd, snodep,lai, fpar,vegtyp,GVFMIN,GVFMAX,FNDSNOWH)\n  endif\n\n     SOILMX = -1.0 * SMC (:,:,1)* ZSOIL (1)\n     DO K = 2,NSOIL\n        where (SMC(:,:,K) > -1.E25)\n           SOILMX = SOILMX + SMC(:,:,K) * (ZSOIL (K-1) - ZSOIL (K))\n        elsewhere\n           SOILMX = -1.E36\n        endwhere\n\n     ENDDO\n     where (SOILMX > -1.E25) SOILMX = SOILMX * 1.E3 ! Convert from m to mm\n\n     HX = 0.0\n     QFX = 0.0\n     ZNT = -1.0\n\n  endif\n\n!yw added this for restart from different restart date\n  olddate = startdate\n    call getHydroNameList(\"GWSPINCYCLES\", gwCycle)\n    call getHydroNameList(\"GWBASESWCRT\", GWBASESWCRT)\n    call getHydroNameList(\"GWSOILCPL\", gwsoilcpl)\n\n#ifdef _HRLDAS_URBAN_\n  if (sf_urban_physics == 1) then\n     ! Initialize urban stuff.\n     if (.not. restart_flag) then\n        write(*, '(\"Initialize urban var.\")')\n        call urban_var_init(ISURBAN, T1, STC, STC(:,:,4),VEGTYP,                              &\n             PARALLEL_XSTART, PARALLEL_XEND, SUBWINDOW_YSTART, SUBWINDOW_YEND, 1, 1, NSOIL, &\n             restart_flag,sf_urban_physics,                                                   &\n             XXXR_URB2D,XXXB_URB2D,XXXG_URB2D,XXXC_URB2D,                               & ! inout ! OUT ???\n             TR_URB2D,TB_URB2D,TG_URB2D,TC_URB2D,QC_URB2D,                              & ! inout ! OUT ???\n             TRL_URB3D,TBL_URB3D,TGL_URB3D,                                             & ! inout ! OUT ???\n             SH_URB2D,LH_URB2D,G_URB2D,RN_URB2D,                                        & ! inout ! OUT ???\n             TS_URB2D,                                                     &\n             num_urban_layers,                             & ! in\n             TRB_URB4D,TW1_URB4D,TW2_URB4D,TGB_URB4D,      & ! inout\n             TLEV_URB3D,QLEV_URB3D,                        & ! inout\n             TW1LEV_URB3D,TW2LEV_URB3D,                    & ! inout\n             TGLEV_URB3D,TFLEV_URB3D,                      & ! inout\n             SF_AC_URB3D,LF_AC_URB3D,CM_AC_URB3D,          & ! inout\n             SFVENT_URB3D,LFVENT_URB3D,                    & ! inout\n             SFWIN1_URB3D,SFWIN2_URB3D,                    & ! inout\n             SFW1_URB3D,SFW2_URB3D,SFR_URB3D,SFG_URB3D,    & ! inout\n             A_U_BEP,A_V_BEP,A_T_BEP,A_Q_BEP,              & ! inout multi-layer urban\n             A_E_BEP,B_U_BEP,B_V_BEP,                      & ! inout multi-layer urban\n             B_T_BEP,B_Q_BEP,B_E_BEP,DLG_BEP,              & ! inout multi-layer urban\n             DL_U_BEP,SF_BEP,VL_BEP,                       & ! inout multi-layer urban\n             FRC_URB2D, UTYPE_URB2D)                                            ! inout ! OUT ???\n     else\n        write(*, '(\"Restart, so we do not initialize urban var\")')\n     endif\n  endif\n#endif\n\n!------------------------------------------------------------------------\n! Begin Time Loop\n!------------------------------------------------------------------------\n\n  NTIME=(KHOUR+1)*3600./nint(dt)\n  if ( rank == 0 ) then\n     ! Start a timer\n     call system_clock(count=clock_count_1)\n  endif\n\n\n endif  ! end of rank if block\n\n#ifdef MPP_LAND\n   call mpi_bcast(ix,1,MPI_INTEGER,0,HYDRO_COMM_WORLD,ierr)\n   call mpi_bcast(jx,1,MPI_INTEGER,0,HYDRO_COMM_WORLD,ierr)\n   call mpi_bcast(nsoil,1,MPI_INTEGER,0,HYDRO_COMM_WORLD,ierr)\n   call mpi_bcast(ntime,1,MPI_INTEGER,0,HYDRO_COMM_WORLD,ierr)\n#endif\n\n  print*, \"ix =, jx =\", ix,jx\n  allocate( infxsrt   (ix,jx) )\n  allocate( sfcheadrt   (ix,jx) )\n  allocate( soldrain    (ix,jx) )\n  allocate( etpnd   (ix,jx) )\n  allocate( greenfrac   (ix,jx) )\n\n  allocate ( qsgw (ix,jx))\n\n  if(rank .ne. 0) then\n    allocate(smc (ix,jx,nsoil))\n    allocate(stc (ix,jx,nsoil))\n    allocate(sh2ox (ix,jx,nsoil))\n    smc = 0.0\n    stc = 0.0\n    sh2ox = 0.0\n  else\n    greenfrac = 0.0\n!yw    call get_greenfrac(trim(GEO_STATIC_FLNM),greenfrac, ix, jx, olddate)\n  endif\n    sfcheadrt =0.0\n    infxsrt = 0.0\n    etpnd = 0.0\n    soldrain = 0.0\n    qsgw = 0.0\n\n  call hrldas_drv_HYDRO_ini(STC(:,:,1:NSOIL),SMC(:,:,1:NSOIL),SH2OX(:,:,1:NSOIL),infxsrt,sfcheadrt,soldrain,ix,jx,NSOIL, 1, dt, olddate,zsoil(1:NSOIL))\n\n1002   continue\n\n  KLOOP : DO K=1,NTIME\n    if(rank == 0) print*, \"k, NTIME, dt = \",k,NTIME , dt\n\n!--------------------------------------------------------------------------------\n! Output for restart BEFORE the processing for this particular time has begun,\n! so that upon restart, we're ready to go on this time step.\n!--------------------------------------------------------------------------------\n\n  if(forc_typ .eq. 8 ) then\n       if(rank == 0) then\n          call read_forc_ldasout_seq(olddate,hgrid, indir, FORCING_TIMESTEP, ix,jx,infxsrt,soldrain)\n       endif\n\n          call hrldas_drv_HYDRO(STC(:,:,1:NSOIL),SMC(:,:,1:NSOIL),SH2OX(:,:,1:NSOIL), &\n                        infxsrt,sfcheadrt,soldrain,ix,jx,NSOIL,               &\n\t\t\tqsgw)\n          goto 1003\n  endif\n\n  if(rank .eq. 0) then\n\n!---------------------------------------------------------------------------------\n! Read the forcing data.\n!---------------------------------------------------------------------------------\n\n! For HRLDAS, we're assuming (for now) that each time period is in a\n! separate file.  So we can open a new one right now.\n\n     inflnm = trim(indir)//\"/\"//&\n          olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n          \".LDASIN_DOMAIN\"//hgrid\n\n     ! Build a filename template\n     inflnm_template = trim(indir)//\"/<date>.LDASIN_DOMAIN\"//hgrid\n\n!yw     CALL READFORC_HRLDAS(inflnm_template, forcing_timestep, olddate,  &\n!yw          parallel_xstart, parallel_xend, subwindow_ystart, subwindow_yend,    &\n!yw          T2,Q2X,U,V,PRES,XLONG,SHORT,PRCP1,LAI,FPAR)\n\n     if(olddate == forcDate) then\n        CALL HYDRO_forcing_drv(trim(indir), forc_typ,snow_assim,olddate,                      &\n          parallel_xstart, parallel_xend, subwindow_ystart, subwindow_yend,    &\n          T2,Q2X,U,V,PRES,XLONG,SHORT,PRCP1,lai,fpar,snodep,k,FORCING_TIMESTEP,prcp_old)\n\n        call geth_newdate(newdate, forcDate, FORCING_TIMESTEP)\n        forcDate = newdate\n     endif\n\n\n!----------------------------------------------------------------------------------\n! Read possible external maps.  There's got to be some good way to make this\n! more general.\n!----------------------------------------------------------------------------------\n\n     if (external_fpar_filename_template /= \" \") then\n        call read_additional(external_fpar_filename_template, olddate, \"fPAR\", &\n             subwindow_xstart, subwindow_xend, subwindow_ystart, subwindow_yend, FPAR, ierr)\n        if (ierr == 0) then\n           if ( .not. allocated(FPAR_SAVE)) then\n              allocate( FPAR_SAVE (SUBWINDOW_XSTART:SUBWINDOW_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n           endif\n           FPAR_SAVE = FPAR\n        else\n           if (allocated(FPAR_SAVE)) then\n              FPAR = FPAR_SAVE\n           endif\n        endif\n     endif\n\n     if (external_lai_filename_template /= \" \") then\n        RDLAI2D = .TRUE.\n        call read_additional(external_lai_filename_template,  olddate, \"LAI\",  &\n             subwindow_xstart, subwindow_xend, subwindow_ystart, subwindow_yend, LAI, ierr)\n        if (ierr == 0) then\n           if ( .not. allocated(LAI_SAVE)) then\n              allocate( LAI_SAVE (SUBWINDOW_XSTART:SUBWINDOW_XEND,SUBWINDOW_YSTART:SUBWINDOW_YEND) )\n           endif\n           LAI_SAVE = LAI\n        else\n           if (allocated(LAI_SAVE)) then\n              LAI = LAI_SAVE\n           endif\n        endif\n     endif\n\n     if ( ( K == 1 ) .and. ( .not. restart_flag ) ) then\n\n        ! Initial values of Q1, the Z0-level specific humidity, are taken from the ZLVL-level\n        ! values.  Subsequent Q1 values are remembered from the previous time step Q1 values\n        ! as recomputed by SFLX.\n        Q12D = Q2X/(1.0+Q2X) ! Convert mixing ratio to specific humidity\n        if ( SFCDIF_OPTION == 1 ) THEN\n           CHX = 0.0001\n           CMX = 0.0001\n        endif\n     endif\n\n\n!------------------------------------------------------------------------\n! Spatial Loop to Convert Gridded data to single point for 1-D SFLX call\n!------------------------------------------------------------------------\n\n     JLOOP : DO J=subwindow_ystart,subwindow_yend\n        ILOOP : DO I=parallel_xstart, parallel_xend\n!yw           if (gvfmin(i,j) < -1.E25) cycle ILOOP\n           if(abs(u(i,j)) .lt. 200 .and. abs(v(i,j)) .lt. 200) then   !! do not run for missing data\n\n           IF((VEGTYP(I,J).GT.0).AND.(VEGTYP(I,J).NE.ISWATER)) THEN\n              VEGTYPX=VEGTYP(I,J)\n              SOILTYP=SOLTYP(I,J)\n              SFCTMP=T2(I,J)\n              SFCSPD=SQRT(U(I,J)*U(I,J)+V(I,J)*V(I,J))\n              SFCPRS=PRES(I,J)\n              Q2=Q2X(I,J)/(1.0+Q2X(I,J)) ! Convert mixing ratio to specific humidity\n              PRCP=PRCP1(I,J)\n              if (prcp < 0.0) prcp = 0.0 ! Just in case\n              SOLDN=SHORT(I,J)\n              Q1 = Q12D(I,J)\n\n              !\n              ! The following module variables are set in subroutine REDPRM.\n              ! If you want other than the default values based on land/soil\n              ! categories, reset them after the call to REDPRM.\n              !\n              !    -- SOIL PARAMETERS:\n              !\n              !           CSOIL\n              !           BEXP\n              !           DKSAT\n              !           DWSAT\n              !           F1\n              !           PSISAT\n              !           QUARTZ\n              !           SMCDRY\n              !           SMCMAX\n              !           SMCREF\n              !           SMCWLT\n              !\n              !    -- \"UNIVERSAL\" PARAMETERS:\n              !\n              !           ZBOT\n              !           SALP\n              !           SBETA\n              !           REFDK\n              !           FRZK\n              !           FXEXP\n              !           REFKDT\n              !           PTU\n              !           KDT\n              !           CZIL\n              !           SLOPE\n              !           FRZFACT\n              !\n              !    -- VEGETATION PARAMETERS:\n              !\n              !           TOPT\n              !           RGL\n              !           RSMAX\n              !           RSMIN\n              !           HS\n              !           XLAI\n              !           CMCMAX\n              !           CFACTR\n              !           NROOT\n              !           SNUP\n              !           ALB\n              !           Z0BRD\n              !           SHDFAC\n              !           SNOALB_NOAH\n              !           RTDIS\n              !\n\n#ifdef _HRLDAS_URBAN_\n              IF ( SF_URBAN_PHYSICS == 1 ) THEN\n                 IF ( ( VEGTYP(I,J) == ISURBAN  ) .or. ( VEGTYP(I,J) == 31 ) .or. &\n                      ( VEGTYP(I,J) == 32 ) .or. ( VEGTYP(I,J) == 33 ) ) THEN\n                    ! VEGTYPX = 5   ! HARD WIRED CATEGORY IS A PROBLEM.  NEEDS CORRECTION\n                    VEGTYPX = 10   ! HARD WIRED CATEGORY IS A PROBLEM.  NEEDS CORRECTION\n                 ENDIF\n              ELSE\n                 IF ( ( VEGTYP(I,J) == ISURBAN  ) .or. ( VEGTYP(I,J) == 31 ) .or. &\n                      ( VEGTYP(I,J) == 32 ) .or. ( VEGTYP(I,J) == 33 ) ) THEN\n                    VEGTYPX = ISURBAN\n           \t ENDIF\n              ENDIF\n#endif\n\n              CALL REDPRM (VEGTYPX,SOILTYP,SLOPETYP,CFACTR,CMCMAX,RSMAX,TOPT,   &\n                   REFKDT,KDT,SBETA, SHDFAC,RSMIN,RGL,HS,ZBOT,FRZX,            &\n                   PSISAT,SLOPE,SNUP,SALP,BEXP,DKSAT,DWSAT,                    &\n                   SMCMAX,SMCWLT,SMCREF,SMCDRY,F1,QUARTZ,FXEXP,                &\n                   RTDIS,SLDPTH,ZSOIL,NROOT,NSOIL,CZIL,                        &\n                   LAIMIN,LAIMAX,EMISSMIN,EMISSMAX,ALBEDOMIN,ALBEDOMAX,        &\n                   Z0MIN,Z0MAXnoah,CSOIL,PTU,LLANDUSE,LSOIL,.True.,LVCOEF)\n\n              offline_cfactr = cfactr\n              offline_cmcmax = cmcmax\n              offline_rsmax  = rsmax\n              offline_topt   = topt\n              offline_refkdt = refkdt\n              offline_kdt    = kdt\n              offline_sbeta  = sbeta\n              offline_rsmin  = rsmin\n              offline_rgl    = rgl\n              offline_hs     = hs\n              offline_zbot   = zbot\n              offline_frzx   = frzx\n              offline_psisat = psisat\n              offline_slope  = slope\n              offline_snup   = snup\n              offline_salp   = salp\n              offline_bexp   = bexp\n              offline_dksat  = dksat\n              offline_dwsat  = dwsat\n              offline_smcmax = smcmax\n              offline_smcwlt = smcwlt\n              offline_smcref = smcref\n              offline_smcdry = smcdry\n              offline_f1     = f1\n              offline_quartz = quartz\n              offline_fxexp  = fxexp\n              offline_rtdis  = rtdis\n              offline_nroot  = nroot\n              offline_czil   = czil\n              offline_csoil  = csoil\n              offline_ptu    = ptu\n              offline_lvcoef = lvcoef\n\n              SHDFAC = FPAR(I,J)\n              if (VEGTYPX==BARE) SHDFAC=0.0; !KWM Added 20060920 to be consistent with REDPRM\n              IF(VEGTYPX==ISURBAN)THEN\n                 !urban change\n                 SHDFAC=0.05\n                 RSMIN=400.0\n                 SMCMAX = 0.45\n                 SMCREF = 0.42\n                 SMCWLT = 0.40\n              ENDIF\n\n\n              shdmin = gvfmin(i,j)\n              shdmax = gvfmax(i,j)\n\n              if (gvfmax(i,j) == gvfmin(i,j)) then\n                 fraction = 0.0\n              else\n                    fraction = real((dble(SHDFAC)-dble(GVFMIN(I,J)))/(dble(GVFMAX(I,J))-dble(GVFMIN(I,J))))\n!                 fraction = greenfrac(i,j)\n              endif\n\n              fraction = max(fraction,0.)\n              fraction = min(fraction,1.)\n              if ( ( k==1 ) .and. ( .not. restart_flag ) ) then\n                 !\n                 !  First time step, initialize EMISS from reasonable background values.  Subsequent\n                 !  time steps will use the EMISS value calculcated in the previous time step.  This\n                 !  means that EMISS has to go into the RESTART file.\n                 !\n                 emiss(i,j)  = real ( dble(emissmintbl(vegtypx))+dble(fraction)*(dble(emissmaxtbl(vegtypx))-dble(emissmintbl(vegtypx))) )\n              endif\n              z0brd  =  real( dble(z0mintbl    (vegtypx))+dble(fraction)*( dble(z0maxtbl     (vegtypx)) - dble(z0mintbl    (vegtypx))) )\n              albbrd =  real( dble(albedomaxtbl(vegtypx))+dble(fraction)*( dble(albedomintbl (vegtypx)) - dble(albedomaxtbl(vegtypx))) )\n\n              if (allocated(LAI_SAVE)) then\n                 xlai = LAI(I,J) !EXTERNAL\n                 if (xlai==0) xlai=0.05\n              else\n                 xlai   = real(dble(laimintbl(vegtypx))+dble(fraction)*(dble(laimaxtbl(vegtypx))-dble(laimintbl(vegtypx))))\n              endif\n\n              !\n              ! ALBEDX is our 2D albedo map, remembered from the previous timestep through SFLX.\n              ! For the first time step, just use ALBBRD.\n              !\n\n              if ( ( k==1 ) .and. ( .not. restart_flag ) ) then\n                 albedx(i,j) = albbrd\n              endif\n\n              LWDN = XLONG(I,J) * EMISS(I,J)\n\n              !   snow albedo\n              alb = albbrd !?\n              SNOFAC=MIN(SNODEP(I,J)*5.0, 1.0)\n\n              !   Net downward radiation\n              SOLNET=SOLDN*(1.-ALBEDX(I,J))\n\n              IF ( SFCDIF_OPTION == 0 ) THEN\n                 CH = 0.1\n                 CM = 0.1\n              ELSE IF ( SFCDIF_OPTION == 1 ) THEN\n                 CH = CHX(I,J)\n                 CM = CMX(I,J)\n              ENDIF\n\n              if (ZNT(I,J) < 0) then\n                 Z0 = Z0BRD\n              else\n                 Z0 = ZNT(I,J)\n              endif\n\n!     Calculate a saturation specific humidity and slope of saturation specific humidity curve WRT Temperature\n\n              CALL CALTMP(T1(I,J), SFCTMP, SFCPRS, ZLVL, Q2, TH2, T1V, TH2V, RHO)\n              CALL CALHUM(SFCTMP, SFCPRS, Q2SAT, DQSDT2)\n\n!     Calculate the surface exchange coefficients CM, CH\n              IF ( SFCDIF_OPTION == 0 ) then\n                 ! Intent (IN) :: ZLVL, Z0, T1V, TH2V, SFCSPD, CZIL, VEGTYPX, ISURBAN, IZ0TLND\n                 ! Intent (INOUT) :: CM\n                 CALL SFCDIF_OFF (ZLVL, ZLVL_WIND, Z0, T1V, TH2V, SFCSPD, CZIL, CM, CH, &\n                      VEGTYPX, ISURBAN, IZ0TLND )\n              ELSE IF ( SFCDIF_OPTION == 1 ) then\n                 ! Intent (IN) :: ZLVL, Z0, Z0BRD, SFCPRS, T1, SFCTMP, Q1, Q2, SFCSPD, VEGTYP, ISURBAN, IZ0TLND\n                 ! intent (OUT) :: RIBB\n                 ! Intent (INOUT) :: CM, CH\n                 CALL SFCDIF_MYJ ( ZLVL, ZLVL_WIND, Z0, Z0BRD, SFCPRS, T1(I,J), SFCTMP, Q1, Q2, &\n                      SFCSPD, CZIL, RIBB, CM, CH, VEGTYPX, ISURBAN, IZ0TLND )\n              ENDIF\n              IF (Q2 .LT. 0.0) THEN\n                 print*,'Q2<0','I=',I, 'J=',J\n                 Q2=.1E-5\n              ENDIF\n              IF (Q2 .GT. Q2SAT) THEN\n                 ! print*, 'Q2 .GT. Q2SAT', 'I=',I, 'J=',J\n                 ! print*,'Q2=',Q2,'Q2SAT=',Q2SAT\n                 Q2=Q2SAT*0.99\n              ENDIF\n\n              CHKFF = CH * CPHEAT * RHO\n\n              STC1(1:NSOIL)=STC(I,J,1:NSOIL)\n\n              SMC1(1:NSOIL)=SMC(I,J,1:NSOIL)\n              SH2O(1:NSOIL)=SH2OX(I,J,1:NSOIL)\n              ZSOILX(I,J,1:NSOIL)=ZSOIL(1:NSOIL)\n! *** diagnostics\n              SFCSPDX(I,J)=SFCSPD\n\n\n!--- Other conversions 'History (State) Variables\n\n              TBOT=TBOT_2D(I,J)\n              CMCX=CMC(I,J)\n              T1X=T1(I,J)\n              SNOWH=SNODEP(I,J)\n\n              SNEQV = WEASD(I,J)\n\n              esnow = 0.0\n              if (T1X <= 273.15) then\n                 ffrozp = 1.0\n              else\n                 ffrozp = 0.0\n              endif\n\n#ifdef _HRLDAS_URBAN_\n              IF ( SF_URBAN_PHYSICS == 1 ) THEN\n                 IF ( ( VEGTYP(I,J) == ISURBAN  ) .or. ( VEGTYP(I,J) == 31 ) .or. &\n                      ( VEGTYP(I,J) == 32 ) .or. ( VEGTYP(I,J) == 33 ) ) THEN\n                    ! VEGTYPX = 5   ! HARD WIRED CATEGORY IS A PROBLEM.  NEEDS CORRECTION\n                    VEGTYPX = 10   ! HARD WIRED CATEGORY IS A PROBLEM.  NEEDS CORRECTION\n                    SHDFAC = 0.8\n                    ALBBRD  =0.2\n                    T1X= ( T1(I,J) -FRC_URB2D(I,J) * TS_URB2D (I,J) )/ (1-FRC_URB2D(I,J))\n                 ENDIF\n              ELSE\n                 IF ( ( VEGTYP(I,J) == ISURBAN  ) .or. ( VEGTYP(I,J) == 31 ) .or. &\n                      ( VEGTYP(I,J) == 32 ) .or. ( VEGTYP(I,J) == 33 ) ) THEN\n                    VEGTYPX = ISURBAN\n           \t ENDIF\n              ENDIF\n#endif\n\n\n\n              ! The following variables are available here, to subroutine\n              ! SFLX, and to its deeper subroutines via use-association with\n              ! module noahlsm_globals.\n              !\n              !    ALB   : Surface albedo (Fraction 0.0 to 1.0)\n              !    Z0BRD : Roughness Length (m)\n              !    SHDFAC: Green Vegetation Fraction\n              !          : Areal fractional coverage of green vegetation (fraction: 0.0-1.0)\n              !    NROOT : Rooting depth (as the number of layers)\n              !    RSMIN : Minimum Canopy Resistance (s m-1)\n              !    RGL   : Parameter used in radiation stress function\n              !    HS    : Parameter used in vapor pressure deficit function\n              !    SNUP  : Threshold snow depth (in water equivalent m) that\n              !            implies 100 percent snow cover\n              !    XLAI  : Leaf Area Index\n              !    SNOALB_NOAH: Upper bound on maximum albedo over deep snow (e.g., from\n              !            Robinson and Kukla, 1985, J. Clim. & Appl. Meteor.)\n              !    TOPT  : Optimum transpiration air temperature.\n              !    CMCMAX: Maximum canopy water capacity\n              !    CFACTR: Parameter used in the canopy inteception calculation\n              !    RSMAX : Maximum stomatal resistance\n              !    PTU   : Photo thermal unit (plant phenology for annuals/crops)\n              !\n              !    BEXP  : B parameter\n              !    SMCDRY: Dry soil moisture threshold where direct evap from top\n              !            layer ends (volumetric)\n              !    F1    : Soil thermal diffusivity/conductivity coef.\n              !    SMCMAX: Porosity, i.e. saturated value of soil moisture (volumetric)\n              !             -- Max soil moisture content (porosity)\n              !             -- Saturation soil moisture content (from REDPRM)\n              !    SMCREF: Soil moisture threshold where transpiration begins to\n              !            stress (volumetric)\n              !             -- Reference soil moisture  (field capacity)\n              !             -- Reference soil moisture (where soil water\n              !                deficit stress sets in)\n              !    PSISAT: Saturated soil matric potential\n              !    DKSAT : Saturated soil conductivity\n              !    DWSAT :\n              !    SMCWLT: Wilting point soil moisture (volumetric)\n              !    QUARTZ: Soil quartz content\n              !\n              !    SLOPE\n              !    SBETA\n              !    FXEXP\n              !    CSOIL\n              !    SALP  : Tuning parameter\n              !    REFDK : Parameter in the surface runoff parameterization\n              !    REFKDT: Parameter in the surface runoff parameterization\n              !    FRZFACT: Frozen ground parameter\n              !    ZBOT  : Depth (m) of lower boundary soil temperature\n              !    CZIL  : Calculate roughness length of heat\n              !    KDT\n              !\n              ! Arguments to SFLX are:\n              ! ----------------------------------------------------------------------\n              ! 1. CONFIGURATION INFORMATION (C):\n              ! ----------------------------------------------------------------------\n              !    ICE   : Sea-ice flag (1=ice, 0=land)\n              !    DT    : Timestep (sec)\n              !    ZLVL  : Height (m) above ground of atmospheric forcing variables\n              !    NSOIL : Number of soil layers.\n              !    SLDPTH: Thickness of each soil layer (m)\n              ! ----------------------------------------------------------------------\n              ! 3. FORCING DATA (F):\n              ! ----------------------------------------------------------------------\n              !    LWDN  : LW downward radiation, not net (w m-2)\n              !    SOLDN : Solar downward radiation, not net (w m-2)\n              !    SFCPRS: Pressure  (Pa) at height ZLVL above ground\n              !    PRCP  : Precipitation rate (kg m-2 s-1; or mm/s)\n              !    SFCTMP: Air temperature (K) at height ZLVL above ground\n              !    Q2    : Specific humidity (kg kg-1) at height ZLVL above ground\n              !    SFCSPD: Wind speed (m s-1) at height ZLVL above ground\n! UNUSED     !    COSZ  : Solar zenith angle\n! UNUSED     !    PRCPRAIN: Liquid-precipitation rate (kg m-2 s-1) (Not used)\n! UNUSED     !    SOLARDIRECT: Direct component of downward solar radiation (W m-2) (Not used)\n              !    TH2   : Air potential temperature (K) at height ZLVL above ground\n              ! ----------------------------------------------------------------------\n              ! 4. OTHER FORCING (INPUT) DATA (I):\n              ! ----------------------------------------------------------------------\n              !    Q2SAT : Saturation specific humidity (kg kg-1) at height ZLVL above ground\n              !    DQSDT2: Slope (kg kg-1 K-1) of sat specific humidity curve at T=SFCTMP\n              ! ----------------------------------------------------------------------\n              ! 5. CANOPY/SOIL CHARACTERISTICS (S):\n              ! ----------------------------------------------------------------------\n              !   VEGTYPX: Vegetation type (integer index)\n              !   SHDMIN : Minimum areal fractional coverage of green vegetation (Fraction= 0.0-1.0)\n              !   SHDMAX : Maximum areal fractional coverage of annual green vegetation (Not used)\n              !   TBOT   : Bottom soil temperature (K) (local yearly-mean sfc air Temp.\n              !   Z0     : Roughness length (m) modifed by snow depth as appropriate\n              ! ----------------------------------------------------------------------\n              ! 6. HISTORY (STATE) VARIABLES (H):\n              ! ----------------------------------------------------------------------\n              !   CMCX   : Canopy moisture content (m)\n              !   T1X    : Ground/canopy/snowpack effective skin temperature (K)\n              !   STC1   : Soil Temperature (K) :: dimension(NSOIL)\n              !   SMC1   : Total soil moisture content (volumetric fraction) :: dimension(NSOIL)\n              !   SH2O   : Unfrozen soil moisture content (volumetric fraction) :: dimension(NSOIL)\n              !            NOTE: Frozen soil moisture = SMC - SH2O\n              !   SNOWH  : Actual snow depth (m)\n              !   SNEQV  : Liquid water-equivalent snow depth (m).  NOTE: Snow density = SNEQV/SNOWH\n              !   ALBEDO : Surface albedo including snow effect (Fraction)\n              !   CH     : Surface exchange coefficient for heat and moisture (m s-1)\n              !            NOTE: CH is technically a conductance since it has been\n              !            multiplied by wind speed.\n! UNUSED     !   CM     : Surface exchange coefficient for momentum (m s-1)\n              !            NOTE: CM is technically a conductance since it has been\n              !            multiplied by wind speed. (Not used)\n              ! ----------------------------------------------------------------------\n              ! 7. OUTPUT (O):\n              ! ----------------------------------------------------------------------\n              !   ETA    : Actual latent heat flux (W m-2)\n              !   SHEAT  : Sensible heat flux (W m-2)\n              !   ETA_KINEMATIC : Actual latent heat flux (kg m s-1)\n              !   FDOWN  : Radiation forcing at the surface (W m-2)\n              !   EC     : Canopy water evaporation (W m-2)\n              !   EDIR   : Direct soil evaporation (W m-2)\n              !   ET     : Plant transpiration from a particular root/soil layer (W m-2) :: dimension(NSOIL)\n              !   ETT    : Total plant transpiration (W m-2)\n              !   ESNOW  : Sublimation from (or deposition to if ESNOW<0) snowpack (W m-2)\n              !   DRIP   : Through-fall of precip and/or dew in excess of canopy water-holding capacity (m)\n              !   DEW    : Dewfall (or frostfall for T<273.15) (m)\n              !   BETA   : Ratio of actual/potential evaporation (dimensionless)\n              !   ETP    : Potential evaporation (W m-2)\n              !   SSOIL  : Soil heat flux (W m-2)\n              !   FLX1   : Precip-snow sfc (W m-2)\n              !   FLX2   : Freezing rain latent heat flux (W m-2)\n              !   FLX3   : Phase-change heat flux from snowmelt (W m-2)\n              !   SNOMLT : Snow melt (m) (water equivalent)\n              !   SNCOVR : Fractional snow cover (Fraction, 0.0 to 1.0)\n              !   RUNOFF1: Surface runoff (m s-1), not infiltrating the surface\n              !   RUNOFF2: Subsurface runoff (m s-1), drainage out bottom of deepest soil layer (baseflow)\n              !   RUNOFF3: Numerical trunctation in excess of porosity\n              !            for a given soil layer at the end of a time step (m s-1).\n              !            NOTE: the above RUNOFF2 is actually the sum of RUNOFF2 and RUNOFF3\n              !   RC     : Canopy resistance (s m-1)\n              !   PC     : Plant coefficient (Fraction, 0.0 to 1.0) where PC*ETP = Actual transpiration\n              !   RCS    : Incoming solar RC factor (dimensionless)\n              !   RCT    : Air temperature RC factor (dimensionless)\n              !   RCQ    : Atmos vapor pressure deficit RC factor (dimensionless)\n              !   RCSOIL : Soil moisture RC factor (dimensionless)\n              ! ----------------------------------------------------------------------\n              ! 8. DIAGNOSTIC OUTPUT (D):\n              ! ----------------------------------------------------------------------\n              !   SOILW  : Available soil moisture in root zone (Fraction, between SMCWLT and SMCMAX)\n              !   SOILM  : Total soil column moisture content (frozen+unfrozen) (m)\n              !   Q1     : Effective specific humidity at surface (kg kg-1), used for\n              !            diagnosing the specific humidity at 2 meter for coupled model\n\n#ifdef _HRLDAS_URBAN_\n              if ( sf_urban_physics == 1) then\n                 call calc_declin( olddate(1:13), latitude(i,j), longitude(i,j), cosz, omg_urb, declin )\n              endif\n#endif\n\n              snoalb = MAXALB(VEGTYPX) * 0.01 !?????  albed !?????\n\n              EMBRD = -1.E36\n\n              SNOTIME1 = SNOTIME(I,J)\n\n#define _DEBUG_PRINT_ 0\n#if _DEBUG_PRINT_\n              print*, \"Before SFLX.\"\n              print*, 'FFROZP = ', FFROZP\n              print*, 'ICE = ', ICE\n              print*, 'ISURBAN = ', ISURBAN\n              print*, 'DT = ', DT\n              print*, 'ZLVL = ', ZLVL\n              print*, 'NSOIL = ', NSOIL\n              print*, 'SLDPTH = ', SLDPTH\n              print*, 'LLANDUSE = ', trim(LLANDUSE)\n              print*, 'LSOIL = ', trim(LSOIL)\n              print*, 'LWDN = ', LWDN\n              print*, 'SOLDN = ', SOLDN\n              print*, 'SOLNET = ', SOLNET\n              print*, 'SFCPRS = ', SFCPRS\n              print*, 'PRCP = ', PRCP\n              print*, 'SFCTMP = ', SFCTMP\n              print*, 'Q2 = ', Q2\n              print*, 'SFCSPD = ', SFCSPD\n              print*, 'COSZ = ', COSZ\n              print*, 'PRCPRAIN = ', PRCPRAIN\n              print*, 'SOLARDIRECT = ', SOLARDIRECT\n              print*, 'TH2 = ', TH2\n              print*, 'Q2SAT = ', Q2SAT\n              print*, 'DQSDT2 = ', DQSDT2\n              print*, 'VEGTYPX = ', VEGTYPX\n              print*, 'SOILTYP = ', SOILTYP\n              print*, 'SlOPETYP = ', SlOPETYP\n              print*, 'SHDFAC = ', SHDFAC\n!              print*, 'SHDMIN = ', SHDMIN\n!              print*, 'SHDMAX = ', SHDMAX\n              print*, 'ALB = ', ALB\n              print*, 'SNOALB = ', SNOALB\n              print*, 'TBOT = ', TBOT\n              print*, 'Z0BRD = ', Z0BRD\n              print*, 'Z0 = ', Z0\n              print*, 'EMISSI = ', EMISSI\n!              print*, 'EMBRD = ', EMBRD\n              print*, 'CMCX = ', CMCX\n              print*, 'T1X = ', T1X\n              print*, 'STC1 = ', STC1\n              print*, 'SMC1 = ', SMC1\n              print*, 'SH2O = ', SH2O\n              print*, 'SNOWH = ', SNOWH\n              print*, 'SNEQV = ', SNEQV\n              print*, 'ALBEDO = ', ALBEDO\n              print*, 'CH = ', CH\n              print*, 'CM = ', CM\n              print*, 'ETA = ', ETA\n              print*, 'SHEAT = ', SHEAT\n              print*, 'ETA_KINEMATIC = ', ETA_KINEMATIC\n              print*, 'FDOWN = ', FDOWN\n              print*, 'EC = ', EC\n              print*, 'EDIR = ', EDIR\n              print*, 'ET = ', ET\n              print*, 'ETT = ', ETT\n              print*, 'ESNOW = ', ESNOW\n              print*, 'DRIP = ', DRIP\n              print*, 'DEW = ', DEW\n              print*, 'BETA = ', BETA\n              print*, 'ETP = ', ETP\n              print*, 'SSOIL = ', SSOIL\n              print*, 'FLX1 = ', FLX1\n              print*, 'FLX2 = ', FLX2\n              print*, 'FLX3 = ', FLX3\n              print*, 'SNOMLT = ', SNOMLT\n              print*, 'SNCOVR = ', SNCOVR\n              print*, 'RUNOFF1 = ', RUNOFF1\n              print*, 'RUNOFF2 = ', RUNOFF2\n              print*, 'RUNOFF3 = ', RUNOFF3\n              print*, 'RC = ', RC\n              print*, 'PC = ', PC\n              print*, 'RSMIN = ', RSMIN\n              write(*, '(\"XLAI = \", F7.5)') XLAI\n              print*, 'RCS = ', RCS\n              print*, 'RCT = ', RCT\n              print*, 'RCQ = ', RCQ\n              print*, 'RCSOIL = ', RCSOIL\n              print*, 'SOILW = ', SOILW\n              print*, 'SOILM = ', SOILM\n              print*, 'Q1 = ', Q1\n#if 0\n              print*, 'RDLAI2D = ', RDLAI2D\n              print*, 'USEMONALB = ', USEMONALB\n              print*, 'SNOTIME1 = ', SNOTIME1\n              print*, 'RIBB = ', RIBB\n#endif\n              print*, 'SMCWLT = ', SMCWLT\n              print*, 'SMCDRY = ', SMCDRY\n              print*, 'SMCREF = ', SMCREF\n              print*, 'SMCMAX = ', SMCMAX\n              print*, 'NROOT = ', NROOT\n#endif\n\n!              print*, 'SNOWH = ', SNOWH, 'i=',i, 'j=',j\n!              print*, 'SNEQV = ', SNEQV,'i=',i, 'j=',j\n\n              if(GWBASESWCRT .eq. 3) then\n                  REFDK_DATA  = refdk2d(i,j)\n                  REFKDT_DATA = refkdt2d(i,j)\n              endif\n\n              CALL SFLX (FFROZP,ICE,ISURBAN,DT,ZLVL,NSOIL,SLDPTH,   &    !C\n                   .FALSE., LLANDUSE, LSOIL,                        &    !C\n                   LWDN,SOLDN,SOLNET,SFCPRS,PRCP,SFCTMP,Q2,SFCSPD,  &    !F\n                   COSZ,PRCPRAIN, SOLARDIRECT,                      &    !F\n                   TH2,Q2SAT,DQSDT2,                                &    !I\n                   VEGTYPX,SOILTYP,SlOPETYP,SHDFAC,SHDMIN,SHDMAX,   &    !S\n                   ALB,SNOALB,TBOT,Z0BRD,Z0,EMISSI, EMBRD,          &    !S\n                   CMCX,T1X,STC1,SMC1,SH2O,SNOWH,SNEQV,ALBEDO,CH,CM,&    !H\n! ----------------------------------------------------------------------\n! OUTPUTS, DIAGNOSTICS, PARAMETERS BELOW GENERALLY NOT NECESSARY WHEN\n! COUPLED WITH E.G. A NWP MODEL (SUCH AS THE NOAA/NWS/NCEP MESOSCALE ETA\n! MODEL).  OTHER APPLICATIONS MAY REQUIRE DIFFERENT OUTPUT VARIABLES.\n! ----------------------------------------------------------------------\n                   ETA,SHEAT, ETA_KINEMATIC,FDOWN,                  &    !O\n                   EC,EDIR,ET,ETT,ESNOW,DRIP,DEW,                   &    !O\n                   BETA,ETP,SSOIL,                                  &    !O\n                   FLX1,FLX2,FLX3,                                  &    !O\n                   SNOMLT,SNCOVR,                                   &    !O\n                   RUNOFF1,RUNOFF2,RUNOFF3,                         &    !O\n                   RC,PC,RSMIN,XLAI,RCS,RCT,RCQ,RCSOIL,             &    !O\n                   SOILW,SOILM,Q1,SMAV,                             &    !D\n                   RDLAI2D, USEMONALB, SNOTIME1, RIBB,              &\n                   SMCWLT,SMCDRY,SMCREF,SMCMAX,NROOT,               &\n                   sfcheadrt(i,j),INFXSRT(i,j),ETPND1,              &\n\t\t   gwsoilcpl, qsgw(i,j))           !P\n\n\n#if _DEBUG_PRINT_\n              ETPND(i,j) = ETPND(i,j) + etpnd1\n              print*, \"After SFLX.\"\n              print*, 'FFROZP = ', FFROZP\n              print*, 'ICE = ', ICE\n              print*, 'ISURBAN = ', ISURBAN\n              print*, 'DT = ', DT\n              print*, 'ZLVL = ', ZLVL\n              print*, 'NSOIL = ', NSOIL\n              print*, 'SLDPTH = ', SLDPTH\n              print*, 'LLANDUSE = ', trim(LLANDUSE)\n              print*, 'LSOIL = ', trim(LSOIL)\n              print*, 'LWDN = ', LWDN\n              print*, 'SOLDN = ', SOLDN\n              print*, 'SOLNET = ', SOLNET\n              print*, 'SFCPRS = ', SFCPRS\n              print*, 'PRCP = ', PRCP\n              print*, 'SFCTMP = ', SFCTMP\n              print*, 'Q2 = ', Q2\n              print*, 'SFCSPD = ', SFCSPD\n              print*, 'COSZ = ', COSZ\n              print*, 'PRCPRAIN = ', PRCPRAIN\n              print*, 'SOLARDIRECT = ', SOLARDIRECT\n              print*, 'TH2 = ', TH2\n              print*, 'Q2SAT = ', Q2SAT\n              print*, 'DQSDT2 = ', DQSDT2\n              print*, 'VEGTYPX = ', VEGTYPX\n              print*, 'SOILTYP = ', SOILTYP\n              print*, 'SlOPETYP = ', SlOPETYP\n              print*, 'SHDFAC = ', SHDFAC\n!              print*, 'SHDMIN = ', SHDMIN\n!              print*, 'SHDMAX = ', SHDMAX\n              print*, 'ALB = ', ALB\n              print*, 'SNOALB = ', SNOALB\n              print*, 'TBOT = ', TBOT\n              print*, 'Z0BRD = ', Z0BRD\n              print*, 'Z0 = ', Z0\n              print*, 'EMISSI = ', EMISSI\n!              print*, 'EMBRD = ', EMBRD\n              print*, 'CMCX = ', CMCX\n              print*, 'T1X = ', T1X\n              print*, 'STC1 = ', STC1\n              print*, 'SMC1 = ', SMC1\n              print*, 'SH2O = ', SH2O\n              print*, 'SNOWH = ', SNOWH\n              print*, 'SNEQV = ', SNEQV\n              print*, 'ALBEDO = ', ALBEDO\n              print*, 'CH = ', CH\n              print*, 'CM = ', CM\n              print*, 'ETA = ', ETA\n              print*, 'SHEAT = ', SHEAT\n              print*, 'ETA_KINEMATIC = ', ETA_KINEMATIC\n              print*, 'FDOWN = ', FDOWN\n              print*, 'EC = ', EC\n              print*, 'EDIR = ', EDIR\n              print*, 'ET = ', ET\n              print*, 'ETT = ', ETT\n              print*, 'ESNOW = ', ESNOW\n              print*, 'DRIP = ', DRIP\n              print*, 'DEW = ', DEW\n              print*, 'BETA = ', BETA\n              print*, 'ETP = ', ETP\n              print*, 'SSOIL = ', SSOIL\n              print*, 'FLX1 = ', FLX1\n              print*, 'FLX2 = ', FLX2\n              print*, 'FLX3 = ', FLX3\n              print*, 'SNOMLT = ', SNOMLT\n              print*, 'SNCOVR = ', SNCOVR\n              print*, 'RUNOFF1 = ', RUNOFF1\n              print*, 'RUNOFF2 = ', RUNOFF2\n              print*, 'RUNOFF3 = ', RUNOFF3\n              print*, 'RC = ', RC\n              print*, 'PC = ', PC\n              print*, 'RSMIN = ', RSMIN\n              write(*, '(\"XLAI = \", F7.5)') XLAI\n              print*, 'RCS = ', RCS\n              print*, 'RCT = ', RCT\n              print*, 'RCQ = ', RCQ\n              print*, 'RCSOIL = ', RCSOIL\n              print*, 'SOILW = ', SOILW\n              print*, 'SOILM = ', SOILM\n              print*, 'Q1 = ', Q1\n#if 0\n              print*, 'RDLAI2D = ', RDLAI2D\n              print*, 'USEMONALB = ', USEMONALB\n              print*, 'SNOTIME1 = ', SNOTIME1\n              print*, 'RIBB = ', RIBB\n#endif\n              print*, 'SMCWLT = ', SMCWLT\n              print*, 'SMCDRY = ', SMCDRY\n              print*, 'SMCREF = ', SMCREF\n              print*, 'SMCMAX = ', SMCMAX\n              print*, 'NROOT = ', NROOT\n#endif\n!---------------------------------------------------------------------\n! Begin Converting Data back to grid from 1-d and make units conversions\n!---------------------------------------------------------------------\n\n!--------------------------------------------------------------------\n!     Calculate residual of all surface energy balance eqn terms.\n!--------------------------------------------------------------------\n              NOAHRES(I,J) = ( solnet + lwdn ) - sheat + ssoil - eta - ( emissi * STBOLT * (t1x**4) ) - flx1 - flx2 - flx3\n\n!  Convert ETA and ETP from W M-2 to KG M-2 S-1\n!KWM              ETA = ETA/2.501E+6\n              ETP = ETP/2.501E+6\n\n              QFX(I,J) = (EDIR+EC+ETT) + ESNOW ! in W m{-2}\n\n!KWM Overwrite ETA for now\n              ETA = ((EDIR+EC+ETT)/2.501E+6) + (ESNOW/2.83E6)\n\n! Fill output variable arrays and doing output\n\n              STC(I,J,1:NSOIL)=STC1(1:NSOIL)    ! Updated Soil Temperature\n              SMC(I,J,1:NSOIL)=SMC1(1:NSOIL)    ! Updated Soil Moisture\n              SH2OX(I,J,1:NSOIL)=SH2O(1:NSOIL)  ! Updated Soil Liquid Water\n              SMAV2D(I,J,1:NSOIL) = SMAV(1:NSOIL)\n              SNODEP(I,J)=SNOWH                 ! Updated snow depth !KWM\n              WEASD(I,J)=SNEQV      ! ( m of water )\n              FX(I,J)=FDOWN\n              ETPX(I,J)=ETP\n              T1(I,J)=T1X\n              ETAX(I,J)=ETAX(I,J)+ETA*dt ! kg m{-2} s{-1} to mm liquid\n              ETAKIN(I,J)=ETA_KINEMATIC*dt\n              CMC(I,J)=CMCX\n              GRDFLX(I,J)=SSOIL\n              CHX(I,J)=CH\n              CMX(I,J)=CM\n              Q12D(I,J) = Q1\n              ZNT(I,J)=Z0\n              RUNOFF1X(I,J)=RUNOFF1X(I,J)+RUNOFF1*dt*1.E3\n              RUNOFF2X(I,J)=RUNOFF2X(I,J)+RUNOFF2*dt*1.E3\n              SOLDRAIN(i,j) = RUNOFF2*dt*1.E3\n              RUNOFF3X(I,J)=RUNOFF3X(I,J)+RUNOFF3*dt*1.E3\n\n              EDIRX(I,J)=EDIRX(I,J)+(EDIR/2.501E6)*dt ! (W m{-2} to kg m{-2} s{-2} to mm)\n              ECX(I,J)=ECX(I,J)+(EC/2.501E6)*dt       ! (W m{-2} to kg m{-2} s{-2} to mm)\n              ETTX(I,J)=ETTX(I,J)+(ETT/2.501E6)*dt    ! (W m{-2} to kg m{-2} s{-2} to mm)\n!KWM              ETPNDX(I,J)=ETPND\n!KWM              SNMAXX(I,J)=SNMAX\n!KWM              SNOFLXX(I,J)=SNOFLX\n!FC             SNOEVPX(I,J)=SNOEVP\n              RCX(I,J)=RC\n              HX(I,J)=SHEAT\n              SMCMAX1(I,J)=SMCMAX\n              SMCREF1(I,J)=SMCREF\n              SMCWLT1(I,J)=SMCWLT\n              ALBEDX(I,J)=ALBEDO\n              ACRAIN(I,J)=ACRAIN(I,J)+PRCP*dt      ! (mm/s to mm)\n\n              ACSNOM(I,J)=ACSNOM(I,J)+snomlt*1.E3  ! Accumulated snow melt (convert m to mm).\n              ! ESNOW2D:  Accumulated snow sublimation (converted from W m{-2} to kg m{-2} s{-2} to mm)\n              ESNOW2D(I,J)=ESNOW2D(I,J)+(ESNOW/2.83E6)*dt\n              DRIP2D(I,J)=DRIP2D(I,J)+DRIP*1.E3   ! convert m to mm\n              DEWFALL(I,J)=DEWFALL(I,J)+DEW*1.E3  ! convert m to mm\n              SOILMX(I,J)= SOILM*1.E3             ! convert m to mm\n              EMISS(I,J) = EMISSI\n              XLAI2D(I,J) = XLAI\n              ! If there's no snow, set SNOTIME to zero\n              IF (snowh > 1.E-5) THEN\n                 SNOTIME(I,J) = SNOTIME1\n              ELSE\n                 SNOTIME(I,J) = 0.0\n              ENDIF\n              EMBRD2D(I,J) = EMBRD\n              SNOALB2D(I,J) = SNOALB\n\n!DG Convert from point to grid (units of SFHEAD & INFXS (mm)\n!DG Temp assignment for parking lot runoff\n!KWM              SFCHEAD(I,J)=SFHEAD\n!DG       INFXS1(I,J)=PRCP1(I,J)\n!KWM              INFXS1(I,J)=INFXS\n! End temp assignments\n!KWM              PDDUM2(I,J)=PDDUM\n!KWM              PCPDRP(I,J)=DRIP\n!KWM              SFCWATR2(I,J)=SFCWATR\n\n#ifdef _HRLDAS_URBAN_\n              IF (SF_URBAN_PHYSICS == 1 ) THEN                                              ! Beginning of UCM CALL if block\n!--------------------------------------\n! URBAN CANOPY MODEL START - urban\n!--------------------------------------\n! Input variables lsm --> urban\n\n\n                 IF ( ( VEGTYP(I,J) == ISURBAN  ) .or. ( VEGTYP(I,J) == 31 ) .or. &\n                      ( VEGTYP(I,J) == 32 ) .or. ( VEGTYP(I,J) == 33 ) ) THEN\n! Call urban\n\n!\n                    UTYPE_URB = UTYPE_URB2D(I,J) !urban type (low, high or industrial)\n                    TA_URB    = SFCTMP           ! [K]\n                    QA_URB    = Q2X(I,J)         ! [kg/kg]\n                    UA_URB    = SQRT(U(I,J)**2.+V(I,J)**2.)\n                    U1_URB    = U(I,J)\n                    V1_URB    = V(I,J)\n                    IF(UA_URB < 1.) UA_URB=1.    ! [m/s]\n                    SSG_URB   = SOLDN            ! [W/m/m]\n                    SSGD_URB  = 0.8*SOLDN        ! [W/m/m]\n                    SSGQ_URB  = SSG_URB-SSGD_URB ! [W/m/m]\n                    LLG_URB   = LWDN             ! [W/m/m]\n!KWM RAIN_URB  = RAINBL(I,J)      ! [mm]\n                    RAIN_URB  = PRCP*dt          ! [mm]  !KWM\n                    RHOO_URB  = SFCPRS / (287.04 * SFCTMP * (1.0+ 0.61 * Q2X(I,J))) ![kg/m/m/m]\n                    ZA_URB    = ZLVL_URBAN       ! [m]\n                    DELT_URB  = DT               ! [sec]\n                    XLAT_URB  = LATITUDE(I,J)  ! [deg]\n                    ZNT_URB   = ZNT(I,J)\n\n                    LSOLAR_URB = .FALSE.\n\n                    TR_URB = TR_URB2D(I,J)\n                    TB_URB = TB_URB2D(I,J)\n                    TG_URB = TG_URB2D(I,J)\n                    TC_URB = TC_URB2D(I,J)\n                    QC_URB = QC_URB2D(I,J)\n                    UC_URB = UC_URB2D(I,J)\n\n                    DO KROOF = 1,num_roof_layers\n                       TRL_URB(KROOF) = TRL_URB3D(I,J,KROOF)\n                    END DO\n                    DO KWALL = 1,num_wall_layers\n                       TBL_URB(KWALL) = TBL_URB3D(I,J,KWALL)\n                    END DO\n                    DO KROAD = 1,num_road_layers\n                       TGL_URB(KROAD) = TGL_URB3D(I,J,KROAD)\n                    END DO\n\n                    XXXR_URB = XXXR_URB2D(I,J)\n                    XXXB_URB = XXXB_URB2D(I,J)\n                    XXXG_URB = XXXG_URB2D(I,J)\n                    XXXC_URB = XXXC_URB2D(I,J)\n!\n!KWM            CHS_URB  = CHS(I,J)\n!KWM            CHS2_URB = CHS2(I,J)\n                    CHS_URB  = HS !KWM ?????\n                    CHS2_URB = HS !KWM ?????\n\n                    CMR_URB = CMR_URB2D(I,J)\n                    CHR_URB = CHR_URB2D(I,J)\n                    CMC_URB = CMC_URB2D(I,J)\n                    CHC_URB = CHC_URB2D(I,J)\n\n!\n\n                    IF ( .FALSE. ) THEN\n\n                       print*, 'BEFORE CALL URBAN'\n                       print*,'num_roof_layers',num_roof_layers, 'num_wall_layers',  &\n                            num_wall_layers,                                             &\n                            'DZR',DZR,'DZB',DZB,'DZG',DZG,'UTYPE_URB',UTYPE_URB,'TA_URB', &\n                            TA_URB,                                                      &\n                            'QA_URB',QA_URB,'UA_URB',UA_URB,'U1_URB',U1_URB,'V1_URB',    &\n                            V1_URB,                                                     &\n                            'SSG_URB',SSG_URB,'SSGD_URB',SSGD_URB,'SSGQ_URB',SSGQ_URB,  &\n                            'LLG_URB',LLG_URB,'RAIN_URB',RAIN_URB,'RHOO_URB',RHOO_URB,   &\n                            'ZA_URB',ZA_URB, 'DECLIN',DECLIN,'COSZ',COSZ,                &\n                            'OMG_URB',OMG_URB,'XLAT_URB',XLAT_URB,'DELT_URB',DELT_URB,   &\n                            'ZNT_URB',ZNT_URB,'TR_URB',TR_URB, 'TB_URB',TB_URB,'TG_URB',&\n                            TG_URB,'TC_URB',TC_URB,'QC_URB',QC_URB,'TRL_URB',TRL_URB,   &\n                            'TBL_URB',TBL_URB,'TGL_URB',TGL_URB,'XXXR_URB',XXXR_URB,   &\n                            'XXXB_URB',XXXB_URB,'XXXG_URB',XXXG_URB,'XXXC_URB',XXXC_URB,&\n                            'QS_URB',QS_URB,'SH_URB',SH_URB,'LH_URB',   &\n                            LH_URB, 'LH_KINEMATIC_URB',LH_KINEMATIC_URB,'SW_URB',SW_URB,&\n                            'ALB_URB',ALB_URB,'LW_URB',LW_URB,'G_URB',G_URB,'RN_URB',   &\n                            RN_URB, 'PSIM_URB',PSIM_URB,'PSIH_URB',PSIH_URB,          &\n                            'U10_URB',U10_URB,'V10_URB',V10_URB,'TH2_URB',TH2_URB,      &\n                            'Q2_URB',Q2_URB,'CHS_URB',CHS_URB,'CHS2_URB',CHS2_URB\n                    endif\n\n\n\n! Call urban\n\n                    CALL urban(LSOLAR_URB,                                & ! I\n                         num_roof_layers,num_wall_layers,num_road_layers, & ! C\n                         DZR,DZB,DZG,                                     & ! C\n                         UTYPE_URB,TA_URB,QA_URB,UA_URB,U1_URB,V1_URB,SSG_URB, & ! I\n                         SSGD_URB,SSGQ_URB,LLG_URB,RAIN_URB,RHOO_URB,     & ! I\n                         ZA_URB,DECLIN,COSZ,OMG_URB,                      & ! I\n                         XLAT_URB,DELT_URB,ZNT_URB,                       & ! I\n                         CHS_URB, CHS2_URB,                               & ! I\n                         TR_URB, TB_URB, TG_URB, TC_URB, QC_URB,UC_URB,   & ! H\n                         TRL_URB,TBL_URB,TGL_URB,                         & ! H\n                         XXXR_URB, XXXB_URB, XXXG_URB, XXXC_URB,          & ! H\n                         TS_URB,QS_URB,SH_URB,LH_URB,LH_KINEMATIC_URB,    & ! O\n                         SW_URB,ALB_URB,LW_URB,G_URB,RN_URB,PSIM_URB,PSIH_URB, & ! O\n                         GZ1OZ0_URB,                                      & !O\n                         CMR_URB, CHR_URB, CMC_URB, CHC_URB,              & ! INTENT (INOUT)\n                         U10_URB, V10_URB, TH2_URB, Q2_URB,               & ! O\n                         UST_URB)                                           !O\n\n\n                    IF ( .FALSE. ) THEN\n\n                       print*, 'AFTER CALL URBAN'\n                       print*,'num_roof_layers',num_roof_layers, 'num_wall_layers',  &\n                            num_wall_layers,                                             &\n                            'DZR',DZR,'DZB',DZB,'DZG',DZG,'UTYPE_URB',UTYPE_URB,'TA_URB', &\n                            TA_URB,                                                      &\n                            'QA_URB',QA_URB,'UA_URB',UA_URB,'U1_URB',U1_URB,'V1_URB',    &\n                            V1_URB,                                                     &\n                            'SSG_URB',SSG_URB,'SSGD_URB',SSGD_URB,'SSGQ_URB',SSGQ_URB,  &\n                            'LLG_URB',LLG_URB,'RAIN_URB',RAIN_URB,'RHOO_URB',RHOO_URB,   &\n                            'ZA_URB',ZA_URB, 'DECLIN',DECLIN,'COSZ',COSZ,                &\n                            'OMG_URB',OMG_URB,'XLAT_URB',XLAT_URB,'DELT_URB',DELT_URB,   &\n                            'ZNT_URB',ZNT_URB,'TR_URB',TR_URB, 'TB_URB',TB_URB,'TG_URB',&\n                            TG_URB,'TC_URB',TC_URB,'QC_URB',QC_URB,'TRL_URB',TRL_URB,   &\n                            'TBL_URB',TBL_URB,'TGL_URB',TGL_URB,'XXXR_URB',XXXR_URB,   &\n                            'XXXB_URB',XXXB_URB,'XXXG_URB',XXXG_URB,'XXXC_URB',XXXC_URB,&\n                            'TS_URB',TS_URB,'QS_URB',QS_URB,'SH_URB',SH_URB,'LH_URB',   &\n                            LH_URB, 'LH_KINEMATIC_URB',LH_KINEMATIC_URB,'SW_URB',SW_URB,&\n                            'ALB_URB',ALB_URB,'LW_URB',LW_URB,'G_URB',G_URB,'RN_URB',   &\n                            RN_URB, 'PSIM_URB',PSIM_URB,'PSIH_URB',PSIH_URB,          &\n                            'U10_URB',U10_URB,'V10_URB',V10_URB,'TH2_URB',TH2_URB,      &\n                            'Q2_URB',Q2_URB,'CHS_URB',CHS_URB,'CHS2_URB',CHS2_URB\n                    endif\n\n! Overwrite fluxes and surface temperature\n!m\n\n!m            ALBEDO(I,J) = FRC_URB*ALB_URB+FRC_NAT*ALBEDOK   ![-]\n!m            HFX(I,J) = FRC_URB*SH_URB+FRC_NAT*SHEAT         ![W/m/m]\n!m            QFX(I,J) = FRC_URB*LH_KINEMATIC_URB &\n!m                     + FRC_NAT*ETA_KINEMATIC                ![kg/m/m/s]\n!m            LH(I,J) = FRC_URB*LH_URB+FRC_NAT*ETA            ![W/m/m]\n!m            GRDFLX(I,J) = FRC_URB*G_URB+FRC_NAT*SSOIL       ![W/m/m]\n!m            TSK(I,J) = FRC_URB*TS_URB+FRC_NAT*T1            ![K]\n!m            QSFC(I,J)= FRC_URB*QS_URB+FRC_NAT*Q1            ![-]\n\n!\n                    TS_URB2D(I,J) = TS_URB\n!\n\n                    ALBEDX(I,J) = FRC_URB2D(I,J)*ALB_URB+(1-FRC_URB2D(I,J))*ALBEDO    ![-]\n                    HX(I,J) = FRC_URB2D(I,J)*SH_URB+(1-FRC_URB2D(I,J))*SHEAT         ![W/m/m]\n                    ETAKIN(I,J) = FRC_URB2D(I,J)*LH_KINEMATIC_URB &\n                         + (1-FRC_URB2D(I,J))*ETA_KINEMATIC                ![kg/m/m/s]\n                    QFX(I,J) = FRC_URB2D(I,J)*LH_URB+(1-FRC_URB2D(I,J))*ETA            ![W/m/m]\n                    GRDFLX(I,J) = FRC_URB2D(I,J)*G_URB+(1-FRC_URB2D(I,J))*SSOIL       ![W/m/m]\n                    T1(I,J) = FRC_URB2D(I,J)*TS_URB+(1-FRC_URB2D(I,J))*T1X            ![K]\n                    Q2X(I,J)= FRC_URB2D(I,J)*QS_URB+(1-FRC_URB2D(I,J))*Q1            ![-]\n\n                    IF(.FALSE.)THEN\n\n                       print*, ' FRC_URB2D', FRC_URB2D,                        &\n                            'ALB_URB',ALB_URB, 'ALBEDO',ALBEDO, &\n                            'ALBEDX(I,J)',  ALBEDX(I,J),                  &\n                            'SH_URB',SH_URB,'SHEAT',SHEAT, 'HX(I,J)',HX(I,J),  &\n                            'LH_KINEMATIC_URB',LH_KINEMATIC_URB,'ETA_KINEMATIC',  &\n                            ETA_KINEMATIC, 'QFX(I,J)',QFX(I,J),                  &\n                            'LH_URB',LH_URB, 'ETA',ETA, 'ETAKIN(I,J)',ETAKIN(I,J),        &\n                            'G_URB',G_URB,'SSOIL',SSOIL,'GRDFLX(I,J)', GRDFLX(I,J),&\n                            'TS_URB',TS_URB,'T1X',T1X,'T1(I,J)',T1(I,J),          &\n                            'QS_URB',QS_URB,'Q1',Q1,'Q2X(I,J)',Q2X(I,J)\n                    endif\n\n\n\n\n! Renew Urban State Varialbes\n\n                    TR_URB2D(I,J) = TR_URB\n                    TB_URB2D(I,J) = TB_URB\n                    TG_URB2D(I,J) = TG_URB\n                    TC_URB2D(I,J) = TC_URB\n                    QC_URB2D(I,J) = QC_URB\n                    UC_URB2D(I,J) = UC_URB\n\n                    DO KROOF = 1,num_roof_layers\n                       TRL_URB3D(I,J,KROOF) = TRL_URB(KROOF)\n                    END DO\n                    DO KWALL = 1,num_wall_layers\n                       TBL_URB3D(I,J,KWALL) = TBL_URB(KWALL)\n                    END DO\n                    DO KROAD = 1,num_road_layers\n                       TGL_URB3D(I,J,KROAD) = TGL_URB(KROAD)\n                    END DO\n                    XXXR_URB2D(I,J) = XXXR_URB\n                    XXXB_URB2D(I,J) = XXXB_URB\n                    XXXG_URB2D(I,J) = XXXG_URB\n                    XXXC_URB2D(I,J) = XXXC_URB\n\n                    SH_URB2D(I,J)    = SH_URB\n                    LH_URB2D(I,J)    = LH_URB\n                    G_URB2D(I,J)     = G_URB\n                    RN_URB2D(I,J)    = RN_URB\n                    PSIM_URB2D(I,J)  = PSIM_URB\n                    PSIH_URB2D(I,J)  = PSIH_URB\n                    GZ1OZ0_URB2D(I,J)= GZ1OZ0_URB\n                    U10_URB2D(I,J)   = U10_URB\n                    V10_URB2D(I,J)   = V10_URB\n                    TH2_URB2D(I,J)   = TH2_URB\n                    Q2_URB2D(I,J)    = Q2_URB\n                    UST_URB2D(I,J)   = UST_URB\n!\n                    CMR_URB2D(I,J) = CMR_URB\n                    CHR_URB2D(I,J) = CHR_URB\n                    CMC_URB2D(I,J) = CMC_URB\n                    CHC_URB2D(I,J) = CHC_URB\n\n                    AKMS_URB2D(I,J)  = KARMAN * UST_URB2D(I,J)/(GZ1OZ0_URB2D(I,J)-PSIM_URB2D(I,J))\n\n                 else                                          !KWM   ?????\n                    do kroof = 1, num_roof_Layers             !KWM   ?????\n                       TRL_URB3D(i,j,kroof) = STC(i,j,kroof)  !KWM   ?????\n                       TBL_URB3D(i,j,kroof) = STC(i,j,kroof)  !KWM   ?????\n                       TGL_URB3D(i,j,kroof) = STC(i,j,kroof)  !KWM   ?????\n                    enddo                                     !KWM   ?????\n                    TR_URB2D(i,j) = STC(i,j,1)                !KWM   ?????\n                    TB_URB2D(i,j) = STC(i,j,1)                !KWM   ?????\n                    TG_URB2D(i,j) = STC(i,j,1)                !KWM   ?????\n                    TC_URB2D(i,j) = STC(i,j,1)                !KWM   ?????\n\n                 END IF\n\n              ENDIF                                   ! end of UCM CALL if block\n!--------------------------------------\n! Urban Part End - urban\n!--------------------------------------\n#endif\n\n! ***  endif of the land-point\n           ENDIF\n\n       endif  !!!   if(abs(u) .lt. 200) then   !! do not run for missing data\n\n        ENDDO ILOOP\n     ENDDO JLOOP\n!-------------------------------------------------------------------\n! END of 1-D NOAH processing\n!-------------------------------------------------------------------\n\n! Output for history\n     if (output_timestep > 0) then\n        if (mod((k-1)*noah_timestep, output_timestep) == 0) then\n\n           call prepare_output_file(trim(outdir), version, iz0tlnd, sfcdif_option, sf_urban_physics, &\n                igrid, output_timestep, llanduse, split_output_count, hgrid,                &\n                ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar,                         &\n                iswater, mapproj, lat1, lon1, dx, dy, truelat1, truelat2, cen_lon,          &\n                nsoil, sldpth, startdate, olddate, vegtyp, soltyp)\n\n           DEFINE_MODE_LOOP : do imode = 1, 2\n\n              call set_output_define_mode(imode)\n\n              call add_to_output(vegtyp    , \"IVGTYP\"  , \"Dominant vegetation category\"        , \"category\"           )\n              call add_to_output(soltyp    , \"ISLTYP\"  , \"Dominant soil category\"              , \"category\"           )\n              call add_to_output(t1        , \"SKINTEMP\", \"Skin temperature\"                    , \"K\"                  )\n              call add_to_output(cmc*1.E3  , \"CANWAT\"  , \"Canopy water content\"                , \"mm\"                 )\n              call add_to_output(stc       , \"SOIL_T\"  , \"soil temperature\"                    , \"K\"                  )\n              call add_to_output(smc       , \"SOIL_M\"  , \"volumetric soil moisture\"            , \"m{3} m{-3}\"         )\n              call add_to_output(sh2ox     , \"SOIL_W\"  , \"liquid volumetric soil moisture\"     , \"m{3} m{-3}\"         )\n              call add_to_output(soilmx    , \"SOIL_MX\" , \"total column soil moisture\"          , \"mm\"                 )\n              call add_to_output(runoff1x  , \"SFCRNOFF\", \"Accumulatetd surface runoff\"         , \"mm\"                 )\n              call add_to_output(runoff2x  , \"UGDRNOFF\", \"Accumulated underground runoff\"      , \"mm\"                 )\n              call add_to_output(runoff3x  , \"INTRFLOW\", \"Accumulated interflow runoff\"        , \"mm\"                 )\n              call add_to_output(etax      , \"SFCEVP\"  , \"Accumulated evaporation from surface\", \"mm\"                 )\n              call add_to_output(etpnd      , \"ETPND\"  , \"Accumulated evaporation from PONDED Water\", \"mm\"                 )\n              call add_to_output(etakin    , \"ETAKIN\"  , \"Evapotranspiration\"                  , \"mm\"                 )\n              call add_to_output(ecx       , \"CANEVP\"  , \"Accumulated canopy evaporation\"      , \"mm\"                 )\n              call add_to_output(edirx     , \"EDIRX\"   , \"Accumulated direct soil evaporation\" , \"mm\"                 )\n              call add_to_output(ettx      , \"ETTX\"    , \"Accumulated plant transpiration\"     , \"mm\"                 )\n              call add_to_output(albedx    , \"ALBEDX\"  , \"Albedo -- What kind? (I.e., including what effects?)\", \"fraction\")\n              call add_to_output(weasd     , \"WEASD\"   , \"Water equivalent snow depth\"         , \"m\"                  )\n              call add_to_output(acrain    , \"ACRAIN\"  , \"Accumulated precipitation\"           , \"mm\"                 )\n              call add_to_output(acsnom    , \"ACSNOM\"  , \"Accumulated snow melt\"               , \"mm\"                 )\n              call add_to_output(esnow2d   , \"ESNOW\"   , \"Accumulated evaporation of snow\"     , \"mm\"                 )\n              call add_to_output(drip2d    , \"DRIP\"    , \"Accumulated canopy drip\"             , \"mm\"                 )\n              call add_to_output(dewfall   , \"DEWFALL\" , \"Accumulated dewfall\"                 , \"mm\"                 )\n              call add_to_output(snodep    , \"SNODEP\"  , \"Snow depth\"                          , \"m\"                  )\n              call add_to_output(fpar      , \"VEGFRA\"  , \"Green vegetation fraction\"           , \"fraction\"           )\n              call add_to_output(znt       , \"Z0\"      , \"Roughness length\"                    , \"m\"                  )\n              call add_to_output(hx        , \"HFX\"     , \"Upward surface sensible heat flux\"   , \"W m{-2}\"            )\n              call add_to_output(qfx       , \"QFX\"     , \"Upward surface latent heat flux\"     , \"W m{-2}\"            )\n              call add_to_output(grdflx    , \"GRDFLX\"  , \"Ground heat flux at surface\"         , \"W m{-2}\"            )\n              call add_to_output(short     , \"SW\"      , \"Downward shortwave radiation flux\"   , \"W m{-2}\"            )\n              call add_to_output(xlong     , \"LW\"      , \"Downward longwave radiation flux\"    , \"W m{-2}\"            )\n              call add_to_output(fx        , \"FDOWN\"   , \"Radiation forcing at the surface\"    , \"W m{-2}\"            )\n              call add_to_output(xlai2d    , \"XLAI\"    , \"Leaf area index\"                     , \"dimensionless\"      )\n              call add_to_output(snotime   , \"SNOTIME\" , \"Snow age\"                            , \"s\"                  )\n              call add_to_output(embrd2d   , \"EMBRD\"   , \"Background Emissivity\"               , \"dimensionless\"      )\n              call add_to_output(snoalb2d  , \"SNOALB\"  , \"Maximum albedo over deep snow\"       , \"fraction\"           )\n              call add_to_output(noahres   , \"NOAHRES\" , \"Residual of surface energy balance\"  , \"W m{-2}\"            )\n              call add_to_output(chx       , \"CH\"      , \"Heat Exchange Coefficient\"           , \"-\"                  )\n#ifdef _HRLDAS_URBAN_\n              if ( sf_urban_physics == 1 ) then\n                 call add_to_output(trl_urb3d , \"TRL\"  , \"Roof temperature\"                    , \"K\"                  )\n                 call add_to_output(tbl_urb3d , \"TBL\"  , \"Wall temperature\"                    , \"K\"                  )\n                 call add_to_output(tgl_urb3d , \"TGL\"  , \"Road temperature\"                    , \"K\"                  )\n                 call add_to_output(tr_urb2d  , \"TR\"   , \"Roof layer temperature\"              , \"K\"                  )\n                 call add_to_output(tb_urb2d  , \"TB\"   , \"Wall layer temperature\"              , \"K\"                  )\n                 call add_to_output(tg_urb2d  , \"TG\"   , \"Road layer temperature\"              , \"K\"                  )\n                 call add_to_output(tc_urb2d  , \"TC\"   , \"Urban canopy temperature\"            , \"K\"                  )\n              endif\n#endif\n\n           enddo DEFINE_MODE_LOOP\n           call finalize_output_file(split_output_count)\n        endif\n     endif\n\n!yw     if ( rank == 0 ) then\n!yw        if (vegtyp(parallel_xstart,subwindow_ystart)==ISWATER) then\n!yw           write(*,'(\" *** DATE = \", A19)', advance=\"NO\") olddate\n!yw        else\n!yw           write(*,'(\" *** DATE = \", A19, 6F10.5)', advance=\"NO\") olddate, &\n!yw                stc(parallel_xstart,subwindow_ystart,1), xlai2d(parallel_xstart,subwindow_ystart)\n!yw        endif\n!yw     endif\n\n!------------------------------------------------------------------------\n! Update the time\n!------------------------------------------------------------------------\n\n     call geth_newdate(newdate, olddate, nint(dt))\n     olddate = newdate\n\n!------------------------------------------------------------------------\n! End of Time Loop  (do K)\n!------------------------------------------------------------------------\n\n#ifdef _PARALLEL_\n     ! Just for sanity's sake, make sure all processors have caught up\n     ! before continuing to the next time step.\n     call mpi_barrier(HYDRO_COMM_WORLD, ierr)\n     if (ierr /= MPI_SUCCESS) stop \"Problem with MPI_BARRIER\"\n#endif\n\n     if (rank==0) then\n        ! update the timer\n        call system_clock(count=clock_count_2, count_rate=clock_rate)\n        timing_sum = timing_sum + float(clock_count_2-clock_count_1)/float(clock_rate)\n        write(*,'(\"    Timing: \",f6.2,\" Cumulative:  \", f10.2 )') &\n             float(clock_count_2-clock_count_1)/float(clock_rate), &\n             timing_sum\n        clock_count_1 = clock_count_2\n\n     endif\n  endif   ! (rank if block)\n  call hrldas_drv_HYDRO(STC(:,:,1:NSOIL),SMC(:,:,1:NSOIL),SH2OX(:,:,1:NSOIL), &\n                        infxsrt,sfcheadrt,soldrain,ix,jx,NSOIL,               &\n\t\t\tqsgw)\n     if (rank==0) then\n     yw_rst_out = -9999\n\n     print *, \"restart_frequency_hours = \",restart_frequency_hours\n\n!!! restart every month\n     if( (olddate(9:10) == \"01\") .and. (olddate(12:13) == \"00\") .and. &\n                     (olddate(15:16) == \"00\").and. (olddate(18:19) == \"00\")    &\n             .and. (restart_frequency_hours <= 0) )  yw_rst_out = 99\n\n        if ((k >= 0) .and. ((restart_frequency_hours .gt. 0) .and. (mod(k, int(restart_frequency_hours*3600./nint(dt))) == 0) &\n               .or. yw_rst_out .eq. 99) ) then\n           yw_rst_out = -999\n\n           if (rank == 0) print*, 'Write restart at '//olddate(1:13)\n           call prepare_restart_file(trim(outdir), version, iz0tlnd, sfcdif_option,   &\n                sf_urban_physics, igrid, llanduse, olddate, startdate,                         &\n                ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar,                   &\n                nsoil, dx, dy, truelat1, truelat2, mapproj, lat1, lon1, cen_lon,      &\n                iswater, vegtyp)\n\n           ! Since the restart files are not really for user consumption, the units and description are\n           ! a little superfluous.  I've made them optional arguments.  If not present, they both default to \"-\".\n\n           call add_to_restart ( stc,      \"SOIL_T\"   )\n           call add_to_restart ( smc,      \"SOIL_M\"   )\n           call add_to_restart ( sh2ox,    \"SOIL_W\"   )\n           call add_to_restart ( qfx,      \"QFX\"      )\n           call add_to_restart ( snodep,   \"SNODEP\"   )\n           call add_to_restart ( weasd,    \"WEASD\"    )\n           call add_to_restart ( fx,       \"FDOWN\"    )\n           call add_to_restart ( etpx,     \"ETP\"      )\n           call add_to_restart ( t1,       \"SKINTEMP\" )\n           call add_to_restart ( etax,     \"ETA\"      )\n           call add_to_restart ( etakin,   \"ETAKIN\"   )\n           call add_to_restart ( cmc,      \"CANWAT\"   )\n           call add_to_restart ( grdflx,   \"GRDFLX\"   )\n           call add_to_restart ( chx,      \"CH\"       )\n           call add_to_restart ( runoff1x, \"RUNOFF1\"  )\n           call add_to_restart ( runoff2x, \"RUNOFF2\"  )\n           call add_to_restart ( runoff3x, \"RUNOFF3\"  )\n           call add_to_restart ( edirx,    \"EDIR\"     )\n           call add_to_restart ( ettx,     \"ETT\"      )\n           call add_to_restart ( ecx,      \"EC\"       )\n           call add_to_restart ( emiss,    \"EMISS\"    )\n           call add_to_restart ( gvfmin,   \"GVFMIN\"   )\n           call add_to_restart ( gvfmax,   \"GVFMAX\"   )\n           call add_to_restart ( snotime,  \"SNOTIME\"  )\n           call add_to_restart ( q12d,     \"Q12D\"     )\n           call add_to_restart ( chx,      \"CHX\"      )\n           call add_to_restart ( cmx,      \"CMX\"      )\n           call add_to_restart ( fpar,     \"FPAR\"     )\n           call add_to_restart ( znt,      \"ZNT\"      )\n           call add_to_restart ( soilmx,   \"SOIL_MX\"  )\n           call add_to_restart ( dewfall,  \"DEWFALL\"  )\n           call add_to_restart ( drip2d,   \"DRIP\"     )\n           call add_to_restart ( esnow2d,  \"ESNOW\"    )\n           call add_to_restart ( acsnom,   \"ACSNOM\"   )\n           call add_to_restart ( acrain,   \"ACRAIN\"   )\n           call add_to_restart ( albedx,   \"ALBED\"    )\n           call add_to_restart ( smcwlt1,  \"SMCWLT\"   )\n           call add_to_restart ( smcref1,  \"SMCREF\"   )\n           call add_to_restart ( smcmax1,  \"SMCMAX\"   )\n           call add_to_restart ( hx,       \"HFX\"      )\n           call add_to_restart ( rcx,      \"RC\"       )\n           call add_to_restart ( lai,      \"LAI\"       )\n#ifdef _HRLDAS_URBAN_\n           if (sf_urban_physics == 1) then\n              call add_to_restart ( utype_urb2d, \"UTYPE_URB2D\" )\n              call add_to_restart ( trl_urb3d,   \"TRL_URB3D\"   )\n              call add_to_restart ( tbl_urb3d,   \"TBL_URB3D\"   )\n              call add_to_restart ( tgl_urb3d,   \"TGL_URB3D\"   )\n              call add_to_restart ( ts_urb2d,    \"TS_URB2D\"    )\n              call add_to_restart ( tr_urb2d,    \"TR_URB2D\"    )\n              call add_to_restart ( tb_urb2d,    \"TB_URB2D\"    )\n              call add_to_restart ( tg_urb2d,    \"TG_URB2D\"    )\n              call add_to_restart ( tc_urb2d,    \"TC_URB2D\"    )\n              call add_to_restart ( qc_urb2d,    \"QC_URB2D\"    )\n              call add_to_restart ( uc_urb2d,    \"UC_URB2D\"    )\n              call add_to_restart ( xxxr_urb2d,  \"XXXR_URB2D\"  )\n              call add_to_restart ( xxxb_urb2d,  \"XXXB_URB2D\"  )\n              call add_to_restart ( xxxg_urb2d,  \"XXXG_URB2D\"  )\n              call add_to_restart ( xxxc_urb2d,  \"XXXC_URB2D\"  )\n              call add_to_restart ( frc_urb2d,   \"FRC_URB2D\"   )\n              call add_to_restart ( cmr_urb2d,   \"CMR_URB2D\"     )\n              call add_to_restart ( chr_urb2d,   \"CHR_URB2D\"     )\n              call add_to_restart ( cmc_urb2d,   \"CMC_URB2D\"     )\n              call add_to_restart ( chc_urb2d,   \"CHC_URB2D\"     )\n           endif\n#endif\n           if (allocated(FPAR_SAVE)) then\n              call add_to_restart( fpar_save, \"FPAR_SAVE\")\n           endif\n\n           if (allocated(LAI_SAVE)) then\n              call add_to_restart( lai_save, \"LAI_SAVE\")\n           endif\n\n           call finalize_restart_file()\n        endif\n  endif !!! rank if block\n\n1003   continue\n\n  ENDDO KLOOP\n\n   if(GWBASESWCRT .eq. 3) then\n      if(gwCycle > 0) then\n          gwCycle = gwCycle - 1\n          olddate = startdate\n          goto 1002\n      end if\n   endif\n\n#ifdef _PARALLEL_\n  call mpi_finalize(ierr)\n  if (ierr /= MPI_SUCCESS) stop \"Problem with MPI_FINALIZE\"\n#endif\n\n  call hydro_finish()\nEND program Noah_hrldas_driver\n\n!-------------------------------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------------------------------\n\nsubroutine wrf_message(msg)\n  implicit none\n  character(len=*), intent(in) :: msg\n  write(*, '(A)') msg\nend subroutine wrf_message\n\n!-------------------------------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------------------------------\n\nlogical function wrf_dm_on_monitor() result(l)\n  implicit none\n  l = .TRUE.\nend function wrf_dm_on_monitor\n\n!-------------------------------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------------------------------\n\n!---------------------------------------------------------------------\nSUBROUTINE calc_declin ( nowdate, latitude, longitude, cosz, hrang, declin )\n  use module_date_utilities\n!---------------------------------------------------------------------\n   IMPLICIT NONE\n!---------------------------------------------------------------------\n\n   REAL, PARAMETER :: DEGRAD = 3.14159265/180.\n   REAL, PARAMETER :: DPD    = 360./365.\n! !ARGUMENTS:\n   character(len=13), intent(in)  :: nowdate\n   real,              intent(in)  :: latitude\n   real,              intent(in)  :: longitude\n   REAL,              intent(out) :: cosz\n   REAL,              intent(out) :: hrang\n   real,              intent(out) :: DECLIN\n   REAl                           :: JULIAN\n   REAL                           :: OBECL\n   REAL                           :: SINOB\n   REAL                           :: SXLONG\n   REAL                           :: ARG\n   real                           :: tloctim\n   integer                        :: iday\n   integer                        :: ihour\n\n   call geth_idts(nowdate(1:10), nowdate(1:4)//\"-01-01\", iday)\n   read(nowdate(12:13), *) ihour\n   julian = real(iday) + real(ihour)/24.\n!\n! for short wave radiation\n\n   DECLIN=0.\n\n!-----OBECL : OBLIQUITY = 23.5 DEGREE.\n\n   OBECL=23.5*DEGRAD\n   SINOB=SIN(OBECL)\n\n!-----CALCULATE LONGITUDE OF THE SUN FROM VERNAL EQUINOX:\n\n   IF(JULIAN.GE.80.)SXLONG=DPD*(JULIAN-80.)*DEGRAD\n   IF(JULIAN.LT.80.)SXLONG=DPD*(JULIAN+285.)*DEGRAD\n   ARG=SINOB*SIN(SXLONG)\n   DECLIN=ASIN(ARG)\n\n   TLOCTIM = IHOUR + LONGITUDE/15. ! Local time in hours\n   tloctim = AMOD(tloctim+24.0, 24.0)\n   HRANG=15.*(TLOCTIM-12.)*DEGRAD\n   COSZ=SIN(LATITUDE*DEGRAD)*SIN(DECLIN)+COS(LATITUDE*DEGRAD)*COS(DECLIN)*COS(HRANG)\n\n!KWM   write(wrf_err_message,10)DECDEG/DEGRAD\n!KWM10 FORMAT(1X,'*** SOLAR DECLINATION ANGLE = ',F6.2,' DEGREES.',' ***')\n!KWM   CALL wrf_debug (50, wrf_err_message)\n\n END SUBROUTINE calc_declin\n\n!-----------------------------------------------------------------\n SUBROUTINE SOIL_VEG_GEN_PARM( MMINLU, MMINSL)\n!-----------------------------------------------------------------\n\n   USE module_sf_noahlsm\n#ifdef _PARALLEL_\n   use mpi\n#endif\n   IMPLICIT NONE\n\n   CHARACTER(LEN=*), INTENT(IN) :: MMINLU, MMINSL\n   integer :: LUMATCH, IINDEX, LC, NUM_SLOPE\n   integer :: ierr\n   INTEGER , PARAMETER :: OPEN_OK = 0\n\n   character*128 :: mess , message\n   logical, external :: wrf_dm_on_monitor\n\n\n!-----SPECIFY VEGETATION RELATED CHARACTERISTICS :\n!             ALBBCK: SFC albedo (in percentage)\n!                 Z0: Roughness length (m)\n!             SHDFAC: Green vegetation fraction (in percentage)\n!  Note: The ALBEDO, Z0, and SHDFAC values read from the following table\n!          ALBEDO, amd Z0 are specified in LAND-USE TABLE; and SHDFAC is\n!          the monthly green vegetation data\n!             CMXTBL: MAX CNPY Capacity (m)\n!             NROTBL: Rooting depth (layer)\n!              RSMIN: Mimimum stomatal resistance (s m-1)\n!              RSMAX: Max. stomatal resistance (s m-1)\n!                RGL: Parameters used in radiation stress function\n!                 HS: Parameter used in vapor pressure deficit functio\n!               TOPT: Optimum transpiration air temperature. (K)\n!             CMCMAX: Maximum canopy water capacity\n!             CFACTR: Parameter used in the canopy inteception calculati\n!               SNUP: Threshold snow depth (in water equivalent m) that\n!                     implies 100% snow cover\n!                LAI: Leaf area index (dimensionless)\n!             MAXALB: Upper bound on maximum albedo over deep snow\n!\n!-----READ IN VEGETAION PROPERTIES FROM VEGPARM.TBL\n!\n\n   integer :: rank\n\n#ifdef _PARALLEL_\n  call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n  if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n#else\n  rank = 0\n#endif\n\n\n   IF ( wrf_dm_on_monitor() ) THEN\n\n      OPEN(19, FILE='VEGPARM.TBL',FORM='FORMATTED',STATUS='OLD',IOSTAT=ierr)\n      IF(ierr .NE. OPEN_OK ) THEN\n         WRITE(message,FMT='(A)') &\n              'module_sf_noahlsm.F: soil_veg_gen_parm: failure opening VEGPARM.TBL'\n         CALL wrf_error_fatal ( message )\n      END IF\n\n\n      LUMATCH=0\n\n      FIND_LUTYPE : DO WHILE (LUMATCH == 0)\n         READ (19,*,END=2002)\n         READ (19,*,END=2002)LUTYPE\n         READ (19,*)LUCATS,IINDEX\n\n         IF(LUTYPE.EQ.MMINLU)THEN\n            WRITE( mess , * ) 'LANDUSE TYPE = ' // TRIM ( LUTYPE ) // ' FOUND', LUCATS,' CATEGORIES'\n            if (rank == 0) CALL wrf_message( mess )\n            LUMATCH=1\n         ELSE\n            call wrf_message ( \"Skipping over LUTYPE = \" // TRIM ( LUTYPE ) )\n            DO LC = 1, LUCATS+12\n               read(19,*)\n            ENDDO\n         ENDIF\n      ENDDO FIND_LUTYPE\n! prevent possible array overwrite, Bill Bovermann, IBM, May 6, 2008\n      IF ( SIZE(SHDTBL)       < LUCATS .OR. &\n           SIZE(NROTBL)       < LUCATS .OR. &\n           SIZE(RSTBL)        < LUCATS .OR. &\n           SIZE(RGLTBL)       < LUCATS .OR. &\n           SIZE(HSTBL)        < LUCATS .OR. &\n           SIZE(SNUPTBL)      < LUCATS .OR. &\n           SIZE(MAXALB)       < LUCATS .OR. &\n           SIZE(LAIMINTBL)    < LUCATS .OR. &\n           SIZE(LAIMAXTBL)    < LUCATS .OR. &\n           SIZE(Z0MINTBL)     < LUCATS .OR. &\n           SIZE(Z0MAXTBL)     < LUCATS .OR. &\n           SIZE(ALBEDOMINTBL) < LUCATS .OR. &\n           SIZE(ALBEDOMAXTBL) < LUCATS .OR. &\n           SIZE(EMISSMINTBL ) < LUCATS .OR. &\n           SIZE(EMISSMAXTBL ) < LUCATS ) THEN\n         CALL wrf_error_fatal('Table sizes too small for value of LUCATS in module_sf_noahdrv.F')\n      ENDIF\n\n      IF(LUTYPE.EQ.MMINLU)THEN\n         DO LC=1,LUCATS\n            READ (19,*)IINDEX,SHDTBL(LC),                        &\n                 NROTBL(LC),RSTBL(LC),RGLTBL(LC),HSTBL(LC), &\n                 SNUPTBL(LC),MAXALB(LC), LAIMINTBL(LC),     &\n                 LAIMAXTBL(LC),EMISSMINTBL(LC),             &\n                 EMISSMAXTBL(LC), ALBEDOMINTBL(LC),         &\n                 ALBEDOMAXTBL(LC), Z0MINTBL(LC), Z0MAXTBL(LC)\n         ENDDO\n!\n         READ (19,*)\n         READ (19,*)TOPT_DATA\n         READ (19,*)\n         READ (19,*)CMCMAX_DATA\n         READ (19,*)\n         READ (19,*)CFACTR_DATA\n         READ (19,*)\n         READ (19,*)RSMAX_DATA\n         READ (19,*)\n         READ (19,*)BARE\n         READ (19,*)\n         READ (19,*)NATURAL\n      ENDIF\n!\n2002  CONTINUE\n\n      CLOSE (19)\n      IF (LUMATCH == 0) then\n         CALL wrf_error_fatal (\"Land Use Dataset '\"//MMINLU//\"' not found in VEGPARM.TBL.\")\n      ENDIF\n   ENDIF\n\n   CALL wrf_dm_bcast_string  ( LUTYPE  , 4 )\n   CALL wrf_dm_bcast_integer ( LUCATS  , 1 )\n   CALL wrf_dm_bcast_integer ( IINDEX  , 1 )\n   CALL wrf_dm_bcast_integer ( LUMATCH , 1 )\n   CALL wrf_dm_bcast_real    ( SHDTBL  , NLUS )\n   CALL wrf_dm_bcast_real    ( NROTBL  , NLUS )\n   CALL wrf_dm_bcast_real    ( RSTBL   , NLUS )\n   CALL wrf_dm_bcast_real    ( RGLTBL  , NLUS )\n   CALL wrf_dm_bcast_real    ( HSTBL   , NLUS )\n   CALL wrf_dm_bcast_real    ( SNUPTBL , NLUS )\n   CALL wrf_dm_bcast_real    ( LAIMINTBL    , NLUS )\n   CALL wrf_dm_bcast_real    ( LAIMAXTBL    , NLUS )\n   CALL wrf_dm_bcast_real    ( Z0MINTBL     , NLUS )\n   CALL wrf_dm_bcast_real    ( Z0MAXTBL     , NLUS )\n   CALL wrf_dm_bcast_real    ( EMISSMINTBL  , NLUS )\n   CALL wrf_dm_bcast_real    ( EMISSMAXTBL  , NLUS )\n   CALL wrf_dm_bcast_real    ( ALBEDOMINTBL , NLUS )\n   CALL wrf_dm_bcast_real    ( ALBEDOMAXTBL , NLUS )\n   CALL wrf_dm_bcast_real    ( MAXALB  , NLUS )\n   CALL wrf_dm_bcast_real    ( TOPT_DATA    , 1 )\n   CALL wrf_dm_bcast_real    ( CMCMAX_DATA  , 1 )\n   CALL wrf_dm_bcast_real    ( CFACTR_DATA  , 1 )\n   CALL wrf_dm_bcast_real    ( RSMAX_DATA  , 1 )\n   CALL wrf_dm_bcast_integer ( BARE    , 1 )\n   CALL wrf_dm_bcast_integer ( NATURAL , 1 )\n\n!\n!-----READ IN SOIL PROPERTIES FROM SOILPARM.TBL\n!\n   IF ( wrf_dm_on_monitor() ) THEN\n      OPEN(19, FILE='SOILPARM.TBL',FORM='FORMATTED',STATUS='OLD',IOSTAT=ierr)\n      IF(ierr .NE. OPEN_OK ) THEN\n         WRITE(message,FMT='(A)') &\n              'module_sf_noahlsm.F: soil_veg_gen_parm: failure opening SOILPARM.TBL'\n         CALL wrf_error_fatal ( message )\n      END IF\n\n      WRITE(mess,*) 'INPUT SOIL TEXTURE CLASSIFICATION = ', TRIM ( MMINSL )\n      if (rank == 0) CALL wrf_message( mess )\n\n      LUMATCH=0\n\n      READ (19,*)\n      READ (19,2000,END=2003)SLTYPE\n2000  FORMAT (A4)\n      READ (19,*)SLCATS,IINDEX\n      IF(SLTYPE.EQ.MMINSL)THEN\n         WRITE( mess , * ) 'SOIL TEXTURE CLASSIFICATION = ', TRIM ( SLTYPE ) , ' FOUND', &\n              SLCATS,' CATEGORIES'\n         if (rank == 0) CALL wrf_message ( mess )\n         LUMATCH=1\n      ENDIF\n! prevent possible array overwrite, Bill Bovermann, IBM, May 6, 2008\n      IF ( SIZE(BB    ) < SLCATS .OR. &\n           SIZE(DRYSMC) < SLCATS .OR. &\n           SIZE(F11   ) < SLCATS .OR. &\n           SIZE(MAXSMC) < SLCATS .OR. &\n           SIZE(REFSMC) < SLCATS .OR. &\n           SIZE(SATPSI) < SLCATS .OR. &\n           SIZE(SATDK ) < SLCATS .OR. &\n           SIZE(SATDW ) < SLCATS .OR. &\n           SIZE(WLTSMC) < SLCATS .OR. &\n           SIZE(QTZ   ) < SLCATS  ) THEN\n         CALL wrf_error_fatal('Table sizes too small for value of SLCATS in module_sf_noahdrv.F')\n      ENDIF\n      IF(SLTYPE.EQ.MMINSL)THEN\n         DO LC=1,SLCATS\n            READ (19,*) IINDEX,BB(LC),DRYSMC(LC),F11(LC),MAXSMC(LC),&\n                 REFSMC(LC),SATPSI(LC),SATDK(LC), SATDW(LC),   &\n                 WLTSMC(LC), QTZ(LC)\n         ENDDO\n      ENDIF\n\n2003  CONTINUE\n\n      CLOSE (19)\n   ENDIF\n\n   CALL wrf_dm_bcast_integer ( LUMATCH , 1 )\n   CALL wrf_dm_bcast_string  ( SLTYPE  , 4 )\n   CALL wrf_dm_bcast_string  ( MMINSL  , 4 )  ! since this is reset above, see oct2 ^\n   CALL wrf_dm_bcast_integer ( SLCATS  , 1 )\n   CALL wrf_dm_bcast_integer ( IINDEX  , 1 )\n   CALL wrf_dm_bcast_real    ( BB      , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( DRYSMC  , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( F11     , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( MAXSMC  , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( REFSMC  , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( SATPSI  , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( SATDK   , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( SATDW   , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( WLTSMC  , NSLTYPE )\n   CALL wrf_dm_bcast_real    ( QTZ     , NSLTYPE )\n\n   IF(LUMATCH.EQ.0)THEN\n      CALL wrf_message( 'SOIl TEXTURE IN INPUT FILE DOES NOT ' )\n      CALL wrf_message( 'MATCH SOILPARM TABLE'                 )\n      CALL wrf_error_fatal ( 'INCONSISTENT OR MISSING SOILPARM FILE' )\n   ENDIF\n\n!\n!-----READ IN GENERAL PARAMETERS FROM GENPARM.TBL\n!\n   IF ( wrf_dm_on_monitor() ) THEN\n      OPEN(19, FILE='GENPARM.TBL',FORM='FORMATTED',STATUS='OLD',IOSTAT=ierr)\n      IF(ierr .NE. OPEN_OK ) THEN\n         WRITE(message,FMT='(A)') &\n              'module_sf_noahlsm.F: soil_veg_gen_parm: failure opening GENPARM.TBL'\n         CALL wrf_error_fatal ( message )\n      END IF\n\n      READ (19,*)\n      READ (19,*)\n      READ (19,*) NUM_SLOPE\n\n      SLPCATS=NUM_SLOPE\n! prevent possible array overwrite, Bill Bovermann, IBM, May 6, 2008\n      IF ( SIZE(slope_data) < NUM_SLOPE ) THEN\n         CALL wrf_error_fatal('NUM_SLOPE too large for slope_data array in module_sf_noahdrv')\n      ENDIF\n\n      DO LC=1,SLPCATS\n         READ (19,*)SLOPE_DATA(LC)\n      ENDDO\n\n      READ (19,*)\n      READ (19,*)SBETA_DATA\n      READ (19,*)\n      READ (19,*)FXEXP_DATA\n      READ (19,*)\n      READ (19,*)CSOIL_DATA\n      READ (19,*)\n      READ (19,*)SALP_DATA\n      READ (19,*)\n      READ (19,*)REFDK_DATA\n      READ (19,*)\n      READ (19,*)REFKDT_DATA\n      READ (19,*)\n      READ (19,*)FRZK_DATA\n      READ (19,*)\n      READ (19,*)ZBOT_DATA\n      READ (19,*)\n      READ (19,*)CZIL_DATA\n      READ (19,*)\n      READ (19,*)SMLOW_DATA\n      READ (19,*)\n      READ (19,*)SMHIGH_DATA\n      READ (19,*)\n      READ (19,*)LVCOEF_DATA\n      CLOSE (19)\n   ENDIF\n\n   CALL wrf_dm_bcast_integer ( NUM_SLOPE    ,  1 )\n   CALL wrf_dm_bcast_integer ( SLPCATS      ,  1 )\n   CALL wrf_dm_bcast_real    ( SLOPE_DATA   ,  NSLOPE )\n   CALL wrf_dm_bcast_real    ( SBETA_DATA   ,  1 )\n   CALL wrf_dm_bcast_real    ( FXEXP_DATA   ,  1 )\n   CALL wrf_dm_bcast_real    ( CSOIL_DATA   ,  1 )\n   CALL wrf_dm_bcast_real    ( SALP_DATA    ,  1 )\n   CALL wrf_dm_bcast_real    ( REFDK_DATA   ,  1 )\n   CALL wrf_dm_bcast_real    ( REFKDT_DATA  ,  1 )\n   CALL wrf_dm_bcast_real    ( FRZK_DATA    ,  1 )\n   CALL wrf_dm_bcast_real    ( ZBOT_DATA    ,  1 )\n   CALL wrf_dm_bcast_real    ( CZIL_DATA    ,  1 )\n   CALL wrf_dm_bcast_real    ( SMLOW_DATA   ,  1 )\n   CALL wrf_dm_bcast_real    ( SMHIGH_DATA  ,  1 )\n   CALL wrf_dm_bcast_real    ( LVCOEF_DATA  ,  1 )\n\n!-----------------------------------------------------------------\n END SUBROUTINE SOIL_VEG_GEN_PARM\n!-----------------------------------------------------------------\n"
  },
  {
    "path": "src/Land_models/Noah/IO_code/module_hrldas_netcdf_io.F",
    "content": "module module_hrldas_netcdf_io\n  use module_date_utilities\n  use netcdf\n#ifdef _PARALLEL_\n  use mpi\n#endif\n  implicit none\n\n  logical, parameter :: FATAL = .TRUE.\n  logical, parameter :: NOT_FATAL = .FALSE.\n\n  type inputstruct\n     character(len=19)             :: read_date\n     real, pointer, dimension(:,:) :: t\n     real, pointer, dimension(:,:) :: q\n     real, pointer, dimension(:,:) :: u\n     real, pointer, dimension(:,:) :: v\n     real, pointer, dimension(:,:) :: p\n     real, pointer, dimension(:,:) :: lw\n     real, pointer, dimension(:,:) :: sw\n     real, pointer, dimension(:,:) :: pcp\n     real, pointer, dimension(:,:) :: fpar\n     real, pointer, dimension(:,:) :: lai\n  end type inputstruct\n\n  character(len=256), private :: restart_filename_remember\n  integer, private :: iswater_remember\n  integer, private :: xstartpar_remember\n  integer, private, allocatable, dimension(:,:) :: vegtyp_remember\n  integer, private :: ncid_remember\n  integer, private :: output_count_remember = 0\n  logical, private :: define_mode_remember\n  integer, private :: dimid_ix_remember\n  integer, private :: dimid_jx_remember\n  integer, private :: dimid_times_remember\n  integer, private :: dimid_layers_remember\n\n  interface add_to_restart\n     module procedure add_to_restart_2d_float, add_to_restart_2d_integer, add_to_restart_3d\n  end interface\n\n  interface get_from_restart\n     module procedure get_from_restart_2d_float, get_from_restart_2d_integer, get_from_restart_3d\n  end interface\n\n  interface add_to_output\n     module procedure add_to_output_2d_float, add_to_output_2d_integer, add_to_output_3d\n  end interface\n\ncontains\n\n!-------------------------------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------------------------------\n\n  subroutine check_outdir(rank, outdir)\n    implicit none\n\n    ! Check that output directory OUTDIR exists and is writable, by\n    ! trying to open a test file in that directory.  Include a random\n    ! number in the test file name, to greatly reduce the chance of\n    ! collision with existing file names.  This assumes that the\n    ! intrinsic random_seed routine, called without argument, will seed\n    ! the random number generator based on something like system time\n    ! or hardware noise.\n\n    integer,          intent(in) :: rank\n    character(len=*), intent(in) :: outdir\n\n    real                         :: xrand\n    character(len=256)           :: testfile\n    integer                      :: ierr\n\n    if (rank == 0) then\n       call random_seed()\n       call random_number(xrand)\n       write(testfile, '(A,\"/scratch.\",I4.4,\".\",I6.6,\".scratch\")') trim(outdir), rank, int(xrand*1.E6)\n       open(unit=30, file=trim(testfile), status='unknown', iostat=ierr)\n       if (ierr /= 0) then\n          write(*, '(/)')\n          write(*, '(\" ***** Namelist error: ******************************************************\")')\n          write(*, '(\" ***** \")')\n          write(*, '(\" ***** We cannot write a file to the directory specified in namelist option OUTDIR.\")')\n          write(*, '(\" ***** Check namelist option OUTDIR (currently set to ''\", A, \"'')\")') trim(outdir)\n          write(*, '(\" *****       Check that the directory exists, is a directory, and is writable.\")')\n          write(*, '(/)')\n          stop \"OUTDIR Problem\"\n       endif\n       close(unit=30, iostat=ierr, status='delete')\n       if (ierr /= 0) then\n          print*, \"TESTFILE = \" // trim(testfile) // '\"'\n          stop \"Much confusion.  Problem closing test file.\"\n       endif\n    endif\n  end subroutine check_outdir\n\n!-------------------------------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------------------------------\n\n  subroutine find_restart_file(rank, restart_filename_requested, startdate, khour, olddate, restart_flnm)\n    implicit none\n    !\n    ! If the user has requested the latest restart file, find the latest restart file.\n    ! If the user has requested a specific restart file, check that the file exists.\n    !\n    ! Return the restart file name in string RESTART_FLNM.\n    ! Update the OLDDATE string (in case the latest restart file was requested).\n    !\n    integer,            intent(in)    :: rank\n    character(len=*),   intent(in)    :: restart_filename_requested\n    character(len=19),  intent(in)    :: startdate\n    integer,            intent(in)    :: khour\n    character(len=19),  intent(in)    :: olddate\n    character(len=256), intent(out)   :: restart_flnm\n    character(len=19)                 :: locdate\n    integer                           :: ribeg\n    integer                           :: riend\n    logical                           :: lexist\n\n\n    ribeg = index(restart_filename_requested, \"<LATEST>\")-1\n\n    if ( ribeg > 0 ) then\n\n       riend = ribeg + 9\n       ! Find the latest RESTART file\n       call geth_newdate(locdate(1:13), olddate(1:13), khour+24)\n       RLOOP : do\n          restart_flnm = restart_filename_requested(1:ribeg) //                 &\n               locdate(1:4)//locdate(6:7)//locdate(9:10)//locdate(12:13) //     &\n               restart_filename_requested(riend:)\n          inquire (file=trim(restart_flnm), exist=lexist)\n          if ( .not. lexist ) then\n             call geth_newdate(locdate(1:13), locdate(1:13), -1)\n             if (locdate(1:13) < startdate(1:13) ) then\n                write(*, *)\n                write(*, '(\" ***** RESTART error: **************************************************\")')\n                write(*, '(\" ***** \")')\n                write(*, '(\" *****       You have requested to restart from the latest restart file,\")')\n                write(*, '(\" *****       but no restart file was found.\")')\n                write(*, '(\" ***** \")')\n                write(*, *)\n                stop \" ***** ERROR EXIT:  Cannot find a restart file\"\n             endif\n          else\n             exit RLOOP\n          endif\n       enddo RLOOP\n\n    else\n\n       restart_flnm = restart_filename_requested\n       inquire (file=trim(restart_flnm), exist=lexist)\n       if ( .not. lexist ) then\n          write(*, *)\n          write(*, '(\" ***** RESTART error: **************************************************\")')\n          write(*, '(\" ***** \")')\n          write(*, '(\" *****       You have requested to restart from a file that cannot be found.\")')\n          write(*, '(\" *****       Specified restart file = ''\", A, \"''\")') trim(restart_flnm)\n          write(*, '(\" ***** \")')\n          write(*, *)\n          stop \" ***** ERROR EXIT:  Cannot find restart file\"\n       endif\n\n    endif\n\n    if (rank == 0) then\n       write(*, '(\"Found restart file:  ''\", A, \"''\")') trim(restart_flnm)\n    endif\n\n  end subroutine find_restart_file\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine read_hrldas_hdrinfo(wrfinput_flnm, ix, jx, &\n       xstart, xend, ystart, yend,                      &\n       iswater, isurban, llanduse, dx, dy, truelat1, truelat2, cen_lon, lat1, lon1, &\n#ifdef _PARALLEL_\n       igrid, mapproj, dum2d_ptr)\n#else\n       igrid, mapproj)\n#endif\n    ! Return the dimensions of the grid and some map information.\n    implicit none\n    character(len=*),   intent(in)    :: wrfinput_flnm\n    integer,            intent(out)   :: mapproj\n    integer,            intent(out)   :: igrid\n    integer,            intent(out)   :: ix, jx    ! dimensions\n    integer,            intent(in)    :: xstart, ystart ! Subwindow definition\n    integer,            intent(inout) :: xend, yend     ! Subwindow definition\n    integer,            intent(out)   :: iswater   ! vegetation category corresponding to water bodies\n    integer,            intent(out)   :: isurban   ! vegetation category corresponding to urban areas\n    character(len=256), intent(out)   :: llanduse  ! Landuse dataset (USGS or MODI)\n    real,               intent(out)   :: dx\n    real,               intent(out)   :: dy\n    real,               intent(out)   :: truelat1\n    real,               intent(out)   :: truelat2\n    real,               intent(out)   :: cen_lon\n    real,               intent(out)   :: lat1\n    real,               intent(out)   :: lon1\n#ifdef _PARALLEL_\n    real, pointer,   dimension(:,:)   :: dum2d_ptr\n#endif\n    integer :: ncid, dimid, varid, ierr\n    real, allocatable, dimension(:,:) :: dum2d\n    character(len=256) :: units\n    integer :: i\n    integer :: rank\n\n#ifdef _PARALLEL_\n    call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n#else\n    rank = 0\n#endif\n\n\n    ! Open the NetCDF file.\n    if (rank == 0) write(*,'(\"wrfinput_flnm: ''\", A, \"''\")') trim(wrfinput_flnm)\n\n!KWM#ifdef _PARALLEL_\n!KWM    ierr = nf90_open_par(wrfinput_flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n!KWM#else\n    ierr = nf90_open(wrfinput_flnm, NF90_NOWRITE, ncid)\n!KWM#endif\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO: Problem opening wrfinput file: \"//trim(wrfinput_flnm))\n\n    ierr = nf90_inq_dimid(ncid, \"west_east\", dimid)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding dimension 'west_east'\")\n\n    ierr = nf90_inquire_dimension(ncid, dimid, len=ix)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding dimension length for 'west_east'\")\n\n    ierr = nf90_inq_dimid(ncid, \"south_north\", dimid)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding dimension 'south_north'\")\n\n    ierr = nf90_inquire_dimension(ncid, dimid, len=jx)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding dimension length for 'south_north'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"DX\", dx)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'DX'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"DY\", dy)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'DY'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'TRUELAT1'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'TRUELAT2'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", cen_lon)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'STAND_LON'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", mapproj)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'MAP_PROJ'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"GRID_ID\", igrid)\n    if (ierr /= 0) then\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"grid_id\", igrid)\n       call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'GRID_ID' or 'grid_id'\")\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"ISWATER\", iswater)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'ISWATER'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"ISURBAN\", isurban)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'ISURBAN'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MMINLU\", llanduse)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding global attribute 'MMINLU'\")\n\n    ! IBM XLF seems to need something like this:\n    do i = 1, 256\n       if (ichar(llanduse(i:i)) == 0) llanduse(i:i) = \" \"\n    enddo\n\n    if (xend == 0) then\n       xend = ix\n    endif\n    if (yend == 0) then\n       yend = jx\n    endif\n\n!\n! This section is for reading the information from the wrfinput file\n!\n\n    ! We only need to read the one starting point.\n    allocate(dum2d(xstart:xstart,ystart:ystart))\n    call get_2d_netcdf(\"XLAT\", ncid, dum2d,  units, xstart, xstart, ystart, ystart, FATAL, ierr)\n    lat1 = dum2d(xstart,ystart)\n\n    call get_2d_netcdf(\"XLONG\", ncid, dum2d,  units, xstart, xstart, ystart, ystart, FATAL, ierr)\n    lon1 = dum2d(xstart,ystart)\n    deallocate (dum2d)\n\n#ifdef _PARALLEL_\n    allocate(dum2d_ptr(xstart:xend,ystart:yend))\n    call get_2d_netcdf(\"IVGTYP\", ncid, dum2d_ptr,  units, xstart, xend, ystart, yend, FATAL, ierr)\n#endif\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems closing NetCDF file.\")\n\n  end subroutine read_hrldas_hdrinfo\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine readland_hrldas(wrfinput_flnm,                            &\n       xstart, xend,                                                   &\n       ystart, yend,                                                   &\n       iswater, vegtyp, soltyp, terrain, tbot_2d, latitude, longitude, &\n\t\t\t    refdk2d, refkdt2d)\n    implicit none\n    character(len=*),          intent(in)  :: wrfinput_flnm\n    integer,                   intent(in)  :: xstart, xend, ystart, yend\n    integer,                   intent(in)  :: iswater\n    integer, dimension(xstart:xend,ystart:yend), intent(out) :: vegtyp, soltyp\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: terrain\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: tbot_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: latitude\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: longitude\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: refdk2d, refkdt2d\n\n    character(len=256) :: units\n    integer :: ierr, varid\n    integer :: ncid\n    real, dimension(xstart:xend,ystart:yend) :: xdum\n    integer :: rank\n\n#ifdef _PARALLEL_\n    call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n#else\n    rank = 0\n#endif\n\n\n    ! Open the NetCDF file.\n    if (rank == 0) write(*,'(\"wrfinput_flnm: ''\", A, \"''\")') trim(wrfinput_flnm)\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(wrfinput_flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(wrfinput_flnm, NF90_NOWRITE, ncid)\n#endif\n    if (ierr /= 0) then\n       write(*,'(\"READLAND_HRLDAS:  Problem opening wrfinput file: ''\", A, \"''\")') trim(wrfinput_flnm)\n#ifdef _PARALLEL_\n       call mpi_finalize(ierr)\n       if (ierr /= 0) write(*, '(\"Problem with MPI_finalize.\")')\n#endif\n       stop\n    endif\n\n    ! Get Latitude (lat)\n    call get_2d_netcdf(\"XLAT\", ncid, latitude,  units, xstart, xend, ystart, yend, FATAL, ierr)\n    ! print*, 'latitude(xstart,ystart) = ', latitude(xstart,ystart)\n\n    ! Get Longitude (lon)\n    call get_2d_netcdf(\"XLONG\", ncid, longitude, units, xstart, xend, ystart, yend, FATAL, ierr)\n    ! print*, 'longitude(xstart,ystart) = ', longitude(xstart,ystart)\n\n    ! Get Terrain (avg)\n    call get_2d_netcdf(\"HGT\", ncid, terrain,   units, xstart, xend, ystart, yend, FATAL, ierr)\n    ! print*, 'terrain(xstart,ystart) = ', terrain(xstart,ystart)\n\n    ! Get Deep layer temperature (TMN)\n    call get_2d_netcdf(\"TMN\", ncid, tbot_2d,   units, xstart, xend, ystart, yend, FATAL, ierr)\n    ! print*, 'terrain(xstart,ystart) = ', terrain(xstart,ystart)\n\n    ! Get Dominant Land Use categories (use)\n    call get_landuse_netcdf(ncid, xdum ,   units, xstart, xend, ystart, yend)\n    vegtyp = nint(xdum)\n    ! print*, 'vegtyp(xstart,ystart) = ', vegtyp(xstart,ystart)\n\n    ! Get Dominant Soil Type categories in the top layer (stl)\n    call get_soilcat_netcdf(ncid, xdum ,   units, xstart, xend, ystart, yend)\n    soltyp = nint(xdum)\n    ! print*, 'soltyp(xstart,ystart) = ', soltyp(xstart,ystart)\n\n    ! read 2d parameter fields for Noah-LSM\n    ierr = nf90_inq_varid(ncid,\"REFDK\", varid)\n    if(ierr .eq. 0) then\n     call get_2d_netcdf(\"REFDK\", ncid, refdk2d,   units, xstart, xend, ystart, yend, FATAL, ierr)\n    endif\n    ierr = nf90_inq_varid(ncid,\"REFKDT\", varid)\n    if(ierr .eq. 0) then\n     call get_2d_netcdf(\"REFKDT\", ncid, refkdt2d,   units, xstart, xend, ystart, yend, FATAL, ierr)\n   endif\n\n    ! Close the NetCDF file\n    ierr = nf90_close(ncid)\n    if (ierr /= 0) stop \"MODULE_NOAHLSM_HRLDAS_INPUT:  READLAND_HRLDAS:  NF90_CLOSE\"\n\n    ! Make sure vegtyp and soltyp are consistent when it comes to water points,\n    ! by setting soil category to water when vegetation category is water, and\n    ! vice-versa.\n    where (vegtyp == ISWATER) soltyp = 14\n    where (soltyp == 14) vegtyp = ISWATER\n\n  end subroutine readland_hrldas\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine get_landuse_netcdf(ncid, array, units, xstart, xend, ystart, yend)\n    implicit none\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    character(len=256), intent(out) :: units\n    integer :: iret, varid\n    character(len=24), parameter :: name = \"IVGTYP\"\n\n    units = \" \"\n\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       stop \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_landuse_netcdf:  nf90_inq_varid\"\n    endif\n\n    iret = nf90_get_var(ncid, varid, array, (/xstart, ystart/), (/xend-xstart+1, yend-ystart+1/))\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       stop \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_landuse_netcdf:  nf90_get_var\"\n    endif\n\n  end subroutine get_landuse_netcdf\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine get_soilcat_netcdf(ncid, array, units, xstart, xend, ystart, yend)\n    implicit none\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    character(len=256), intent(out) :: units\n    integer :: iret, varid\n    character(len=24), parameter :: name = \"ISLTYP\"\n\n    units = \" \"\n\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    call error_handler(iret, \"Problem finding variable '\"//trim(name)//\"' in the wrfinput file.\")\n\n    iret = nf90_get_var(ncid, varid, array, (/xstart, ystart/), (/xend-xstart+1, yend-ystart+1/))\n    call error_handler(iret, \"Problem retrieving variable \"//trim(name)//\" from the wrfinput file.\")\n\n  end subroutine get_soilcat_netcdf\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine get_2d_netcdf(name, ncid, array, units, xstart, xend, ystart, yend, &\n       fatal_if_error, ierr)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    character(len=256), intent(out) :: units\n    integer :: iret, varid\n    ! FATAL_IF_ERROR:  an input code value:\n    !      .TRUE. if an error in reading the data should stop the program.\n    !      Otherwise the, IERR error flag is set, but the program continues.\n    logical, intent(in) :: fatal_if_error\n    integer, intent(out) :: ierr\n\n    units = \" \"\n\n    iret = nf90_inq_varid(ncid,  name,  varid)\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'ncid = ', ncid\n          call error_handler(iret, \"MODULE_HRLDAS_NETCDF_IO:  Problem finding variable '\"//trim(name)//\"' in NetCDF file.\")\n       else\n          ierr = iret\n          return\n       endif\n    endif\n\n    iret = nf90_get_att(ncid, varid, \"units\", units)\n    if (iret /= 0) units = \"units unknown\"\n!KWM    if (iret /= 0) then\n!KWM       if (FATAL_IF_ERROR) then\n!KWM          print*, 'name = \"', trim(name)//'\"'\n!KWM          stop \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_2d_netcdf:  nf90_get_att:  units.\"\n!KWM       else\n!KWM          ierr = iret\n!KWM          return\n!KWM       endif\n!KWM    endif\n\n    iret = nf90_get_var(ncid, varid, values=array, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'ncid =', ncid\n          call error_handler(iret, \"MODULE_HRLDAS_NETCDF_IO:  Problem retrieving variable '\"//trim(name)//\"' from NetCDF file.\")\n       else\n          ierr = iret\n          return\n       endif\n    endif\n\n    ierr = 0;\n  end subroutine get_2d_netcdf\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine get_2d_netcdf_soillevel(name, ncid, array, units, xstart, xend, ystart, yend, &\n       fatal_if_error, layer_bottom, layer_top, ierr)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    character(len=256), intent(out) :: units\n    ! FATAL_IF_ERROR:  an input code value:\n    !      .TRUE. if an error in reading the data should stop the program.\n    !      Otherwise the, IERR error flag is set, but the program continues.\n    logical, intent(in) :: fatal_if_error\n    integer, intent(out) :: ierr\n    real, intent(out) :: layer_bottom\n    real, intent(out) :: layer_top\n\n    integer :: iret, varid\n\n    units = \" \"\n\n    iret = nf90_inq_varid(ncid,  name,  varid)\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'name = \"', trim(name)//'\"'\n          stop \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_2d_netcdf:  nf90_inq_varid\"\n       else\n          ierr = iret\n          return\n       endif\n    endif\n\n    iret = nf90_get_att(ncid, varid, \"units\", units)\n    if (iret /= 0) units = \"units unknown\"\n\n    iret = nf90_get_var(ncid, varid, values=array, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'name = \"', trim(name)//'\"'\n          print*, 'varid =', varid\n          print*, trim(nf90_strerror(iret))\n          stop \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_2d_netcdf:  nf90_get_var\"\n       else\n          ierr = iret\n          return\n       endif\n    endif\n\n    ! Also get some metadata about the soil layers:\n    iret = nf90_get_att(ncid, varid, \"layer_top\", layer_top)\n    call error_handler(iret, \"Attempted to find 'layer_top' attribute on variable \"//trim(name))\n\n    iret = nf90_get_att(ncid, varid, \"layer_bottom\", layer_bottom)\n    call error_handler(iret, \"Attempted to find 'layer_bottom' attribute on variable \"//trim(name))\n\n    ierr = 0;\n  end subroutine get_2d_netcdf_soillevel\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine readinit_hrldas(netcdf_flnm, xstart, xend, ystart, yend, nsoil, sldpth, target_date, &\n       ldasin_version, smc, stc, sh2o, cmc, t1, weasd, snodep)\n    implicit none\n    character(len=*),                                  intent(in)  :: netcdf_flnm\n    integer,                                           intent(in)  :: xstart, xend\n    integer,                                           intent(in)  :: ystart, yend\n    integer,                                           intent(in)  :: nsoil\n    real,    dimension(nsoil),                         intent(in)  :: sldpth\n    character(len=*),                                  intent(in)  :: target_date\n\n    integer,                                           intent(out) :: ldasin_version\n    real,    dimension(xstart:xend,ystart:yend,nsoil), intent(out) :: smc\n    real,    dimension(xstart:xend,ystart:yend,nsoil), intent(out) :: stc\n    real,    dimension(xstart:xend,ystart:yend,nsoil), intent(out) :: sh2o\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: cmc\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: t1\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: weasd\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: snodep\n\n    character(len=256) :: titlestr\n    character(len=256) :: units\n    character(len=8)   :: name\n    character(len=256) :: ldasin_llanduse\n\n    integer :: ierr, ncid, ierr_snodep\n    integer :: idx\n    real, dimension(100) :: layer_bottom\n    real, dimension(100) :: layer_top\n\n    real, dimension(xstart:xend, ystart:yend, 4) :: soildummy\n    integer :: rank\n\n    !\n    ! Open the NetCDF LDASIN file.\n    !\n\n#ifdef _PARALLEL_\n\n    call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n\n    ierr = nf90_open_par(netcdf_flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    rank = 0\n    ierr = nf90_open(netcdf_flnm, NF90_NOWRITE, ncid)\n#endif\n    if (rank == 0) write(*,'(\"netcdf_flnm: ''\", A, \"''\")') trim(netcdf_flnm)\n    if (ierr /= 0) then\n       if (rank == 0) write(*,'(\"Problem opening netcdf file: ''\", A, \"''\")') trim(netcdf_flnm)\n#ifdef _PARALLEL_\n       call mpi_finalize(ierr)\n#endif\n       stop\n    endif\n\n    !\n    ! Check the NetCDF LDASIN file for a version number.\n    !\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TITLE\", titlestr)\n    if (ierr /= 0) then\n       write(*,'(\"WARNING:  LDASIN file does not have TITLE attribute.\")')\n       write(*,'(\"          This probably means that LDASIN files are from an older release.\")')\n       write(*,'(\"          I assume you know what you are doing.\")')\n       ldasin_version = 0\n    else\n       write(*,'(\"LDASIN TITLE attribute: \", A)') trim(titlestr)\n       ! Pull out the version number, assuming that the version is identified by vYYYYMMDD, and \n       ! based on a search for the string \"v20\".\n       idx = index(trim(titlestr), \"v20\")\n       if (idx <= 0) then\n          write(*,'(\"FATAL:  LDASIN file has a perverse version identifier\")')\n          !  write(*,'(\"          I assume you know what you are doing.\")')\n          stop\n       else\n          read(titlestr(idx+1:), '(I8)', iostat=ierr) ldasin_version\n          if (ierr /= 0) then\n             write(*,'(\"FATAL:  LDASIN file has a perverse version identifier\")')\n             !  write(*,'(\"          I assume you know what you are doing.\")')\n             stop\n          endif\n       endif\n    endif\n    write(*, '(\"ldasin_version = \", I8)') ldasin_version\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MMINLU\", ldasin_llanduse)\n    if (ierr /= 0) then\n       write(*,'(\"WARNING:  LDASIN file does not have MMINLU attribute.\")')\n       write(*,'(\"          This probably means that LDASIN files are from an older release.\")')\n       write(*,'(\"          I assume you know what you are doing.\")')\n    else\n       write(*,'(\"LDASIN MMNINLU attribute: \", A)') ldasin_llanduse\n    endif\n\n    call get_2d_netcdf(\"CANWAT\",     ncid, cmc,     units, xstart, xend, ystart, yend, FATAL, ierr)\n    call get_2d_netcdf(\"SKINTEMP\",   ncid, t1,      units, xstart, xend, ystart, yend, FATAL, ierr)\n    call get_2d_netcdf(\"WEASD\",      ncid, weasd,   units, xstart, xend, ystart, yend, FATAL, ierr)\n    if (trim(units) == \"m\") then\n       ! No conversion necessary\n    else if (trim(units) == \"mm\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else if (trim(units) == \"kg m{-2}\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else if (trim(units) == \"kg/m2\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else\n       print*, 'units = \"'//trim(units)//'\"'\n       stop \"Unrecognized units on WEASD\"\n    endif\n    call get_2d_netcdf(\"SNODEP\",     ncid, weasd,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr_snodep)\n\n    call get_2d_netcdf_soillevel(\"STEMP_1\",    ncid, soildummy(:,:,1), units,  xstart, xend, ystart, yend, FATAL, &\n         layer_bottom(1), layer_top(1), ierr)\n    call get_2d_netcdf_soillevel(\"STEMP_2\",    ncid, soildummy(:,:,2), units,  xstart, xend, ystart, yend, FATAL, &\n         layer_bottom(2), layer_top(2), ierr)\n    call get_2d_netcdf_soillevel(\"STEMP_3\",    ncid, soildummy(:,:,3), units,  xstart, xend, ystart, yend, FATAL, &\n         layer_bottom(3), layer_top(3), ierr)\n    call get_2d_netcdf_soillevel(\"STEMP_4\",    ncid, soildummy(:,:,4), units,  xstart, xend, ystart, yend, FATAL, &\n         layer_bottom(4), layer_top(4), ierr)\n    write(*, '(\"layer_bottom(1:4) = \", 4F9.4)') layer_bottom(1:4)\n    write(*, '(\"layer_top(1:4)    = \", 4F9.4)') layer_top(1:4)\n    write(*, '(\"Soil depth = \", 10F12.6)') sldpth\n\n    call init_interp(xstart, xend, ystart, yend, nsoil, sldpth, stc, 4, soildummy, layer_bottom(1:4), layer_top(1:4))\n\n    call get_2d_netcdf_soillevel(\"SMOIS_1\",    ncid, soildummy(:,:,1), units,  xstart, xend, ystart, yend, FATAL, &\n         layer_bottom(1), layer_top(1), ierr)\n    call get_2d_netcdf_soillevel(\"SMOIS_2\",    ncid, soildummy(:,:,2), units,  xstart, xend, ystart, yend, FATAL, &\n         layer_bottom(2), layer_top(2), ierr)\n    call get_2d_netcdf_soillevel(\"SMOIS_3\",    ncid, soildummy(:,:,3), units,  xstart, xend, ystart, yend, FATAL, &\n         layer_bottom(3), layer_top(3), ierr)\n    call get_2d_netcdf_soillevel(\"SMOIS_4\",    ncid, soildummy(:,:,4), units,  xstart, xend, ystart, yend, FATAL, &\n         layer_bottom(4), layer_top(4), ierr)\n\n    call init_interp(xstart, xend, ystart, yend, nsoil, sldpth, smc, 4, soildummy, layer_bottom(1:4), layer_top(1:4))\n\n\n    if (ierr_snodep /= 0) then\n       ! Quick assumption regarding snow depth.\n       snodep = weasd * 10.\n    endif\n\n    sh2o = smc\n\n    ierr = nf90_close(ncid)\n  end subroutine readinit_hrldas\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine init_interp(xstart, xend, ystart, yend, nsoil, sldpth, var, nvar, src, layer_bottom, layer_top)\n    implicit none\n    integer, intent(in)    :: xstart, xend, ystart, yend, nsoil, nvar\n    real, dimension(nsoil) :: sldpth ! the thickness of each layer\n    real, dimension(xstart:xend, ystart:yend, nsoil), intent(out) :: var\n    real, dimension(xstart:xend, ystart:yend, nvar ), intent(in)  :: src\n    real, dimension(nvar),                            intent(in)  :: layer_bottom ! The depth from the surface of each layer bottom.\n    real, dimension(nvar),                            intent(in)  :: layer_top    ! The depth from the surface of each layer top.\n    integer :: i, j, k, kk, ktop, kbottom\n    real, dimension(nsoil) :: dst_centerpoint\n    real, dimension(nvar)  :: src_centerpoint\n    real :: fraction\n    integer :: ierr\n    integer :: rank\n\n#ifdef _PARALLEL_\n    call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n#else\n    rank = 0\n#endif\n\n    do k = 1, nsoil\n       if (k==1) then\n          dst_centerpoint(k) = sldpth(k)/2.\n       else\n          dst_centerpoint(k) = sldpth(k)/2. + sum(sldpth(1:k-1))\n       endif\n       if (rank == 0) print*, 'k, dst_centerpoint(k) = ', k, dst_centerpoint(k)\n    enddo\n    print*\n\n    do k = 1, nvar\n       src_centerpoint(k) = 0.5*(layer_bottom(k)+layer_top(k))\n       if (rank == 0) print*, 'k, src_centerpoint(k) = ', k, src_centerpoint(k)\n    enddo\n\n    KLOOP : do k = 1, nsoil\n\n       if (dst_centerpoint(k) < src_centerpoint(1)) then\n          ! If the center of the destination layer is closer to the surface than\n          ! the center of the topmost source layer, then simply set the\n          ! value of the destination layer equal to the topmost source layer:\n          if (rank == 0) then\n             print'(\"Shallow destination layer:  Taking destination layer at \",F7.4, \" from source layer at \", F7.4)', &\n                  dst_centerpoint(k), src_centerpoint(1)\n          endif\n          var(:,:,k) = src(:,:,1)\n          cycle KLOOP\n       endif\n\n       if (dst_centerpoint(k) > src_centerpoint(nvar)) then\n          ! If the center of the destination layer is deeper than\n          ! the center of the deepest source layer, then simply set the\n          ! value of the destination layer equal to the deepest source layer:\n          if (rank == 0) then\n             print'(\"Deep destination layer:  Taking destination layer at \",F7.4, \" from source layer at \", F7.4)', &\n                  dst_centerpoint(k), src_centerpoint(nvar)\n          endif\n          var(:,:,k) = src(:,:,nvar)\n          cycle KLOOP\n       endif\n\n       ! Check if the center of the destination layer is \"close\" to the center\n       ! of a source layer.  If so, simply set the value of the destination layer\n       ! equal to the value of that close soil layer:\n       do kk = 1, nvar\n          if (abs(dst_centerpoint(k)-src_centerpoint(kk)) < 0.01) then\n             if (rank == 0) then\n                print'(\"(Near) match for destination layer:  Taking destination layer at \",F7.4, \" from source layer at \", F7.4)', &\n                     dst_centerpoint(k), src_centerpoint(kk)\n             endif\n             var(:,:,k) = src(:,:,kk)\n             cycle KLOOP\n          endif\n       enddo\n\n       ! Otherwise, do a linear interpolation\n\n       ! Get ktop, the index of the top bracketing layer from the source dataset.\n       ! Which from the bottom up, will be the first source level that is closer \n       ! to the surface than the destination level\n       ktop = -99999\n       TOPLOOP : do kk = nvar,1,-1\n          if (src_centerpoint(kk) < dst_centerpoint(k)) then\n             ktop = kk\n             exit TOPLOOP\n          endif\n       enddo TOPLOOP\n       if (ktop < -99998) stop \"ktop problem\"\n\n\n       ! Get kbottom, the index of the bottom bracketing layer from the source dataset.\n       ! Which, from the top down, will be the first source level that is deeper than\n       ! the destination level\n       kbottom = -99999\n       BOTTOMLOOP : do kk = 1, nvar\n          if ( src_centerpoint(kk) > dst_centerpoint(k) ) then\n             kbottom = kk\n             exit BOTTOMLOOP\n          endif\n       enddo BOTTOMLOOP\n       if (kbottom < -99998) stop \"kbottom problem\"\n\n       fraction = (src_centerpoint(kbottom)-dst_centerpoint(k)) / (src_centerpoint(kbottom)-src_centerpoint(ktop))\n\n       ! print '(I2, 1x, 3F7.3, F8.5)', k, src_centerpoint(ktop), dst_centerpoint(k), src_centerpoint(kbottom), fraction\n\n       if (rank == 0) then\n          print '(\"dst(\",I1,\") = src(\",I1,\")*\",F8.5,\" + src(\",I1,\")*\",F8.5)', k, ktop, fraction, kbottom, (1.0-fraction)\n       endif\n\n       var(:,:,k) = (src(:,:,ktop)*fraction) + (src(:,:,kbottom)*(1.0-fraction))\n\n    enddo KLOOP\n\n  end subroutine init_interp\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine READVEG_HRLDAS(flnm, xstart, xend, ystart, yend, target_date, vegtyp, fpar, lai, gvfmin, gvfmax)\n\n    implicit none\n    character(len=*),                                  intent(in)  :: flnm\n    integer,                                           intent(in)  :: xstart, xend\n    integer,                                           intent(in)  :: ystart, yend\n    character(len=*),                                  intent(in)  :: target_date\n    integer, dimension(xstart:xend,ystart:yend),       intent(in)  :: vegtyp\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: fpar\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: lai\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: gvfmin\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: gvfmax\n\n    character(len=8)   :: name\n    character(len=256) :: units\n    integer :: ierr\n\n    integer :: ierr_fpar\n    integer :: ierr_lai\n\n    integer :: i, j\n    integer :: iret, ncid\n\n    ! Open the NetCDF file.\n!KWM    write(*,'(\"flnm: ''\", A, \"''\")') trim(flnm)\n#ifdef _PARALLEL_\n    iret = nf90_open_par(flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    iret = nf90_open(flnm, NF90_NOWRITE, ncid)\n#endif\n    if (iret /= 0) then\n       write(*,'(\"READVEG_HRLDAS:  Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       stop\n    endif\n\n    call get_2d_netcdf(\"VEGFRA\",     ncid, fpar,     units, xstart, xend, ystart, yend, NOT_FATAL, ierr_fpar)\n    call get_2d_netcdf(\"LAI\",        ncid, lai,      units, xstart, xend, ystart, yend, NOT_FATAL, ierr_lai)\n\n    if (ierr_fpar == 0) then\n       ! fpar = fpar * 1.E-2 ! convert from percent to fraction\n    else if (ierr_fpar /= 0) then\n       ! Get it from tables\n       ! print*,' READVEG_HRLDAS:  VEGFRA not found.  Initializing FPAR from table SHDTBL.'\n       do i = xstart, xend\n          do j = ystart, yend\n!KWM             fpar(i,j) = shdtbl(vegtyp(i,j))\n          enddo\n       enddo\n    endif\n    if (ierr_lai /= 0) then\n       ! Get it from tables\n       ! print*,' READVEG_HRLDAS:  LAI not found.  Initializing LAI from table LAITBL.'\n       do i = xstart, xend\n          do j = ystart, yend\n! Fixme for wrfcode input\n!             lai(i,j) = laitbl(vegtyp(i,j))\n          enddo\n       enddo\n    endif\n\n    ! Get Minimum Green Vegetation Fraction GVFMIN\n    call get_2d_netcdf(\"GVFMIN\", ncid, gvfmin,   units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    ! Get Minimum Green Vegetation Fraction GVFMAX\n    call get_2d_netcdf(\"GVFMAX\", ncid, gvfmax,   units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    iret = nf90_close(ncid)\n  end subroutine READVEG_HRLDAS\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine READFORC_HRLDAS(flnm_template, forcing_timestep, target_date, xstart, xend, ystart, yend,  &\n       t,q,u,v,p,lw,sw,pcp,lai,fpar)\n    use kwm_string_utilities\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm_template\n    integer,                            intent(in)  :: forcing_timestep\n    integer,                            intent(in)  :: xstart, xend\n    integer,                            intent(in)  :: ystart, yend\n    character(len=19),                  intent(in)  :: target_date ! (YYYY-MM-DD_hh:mm:ss)\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: t\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: q\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: u\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: v\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: p\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: lw\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: sw\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: pcp\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: lai\n    real,             dimension(xstart:xend,ystart:yend), intent(inout) :: fpar\n\n    character(len=256) :: flnm\n    character(len=256) :: units\n    character(len=256) :: nextflnm\n    integer :: ierr\n    integer :: ncid\n    integer :: rank\n\n    type(inputstruct) :: lastread = inputstruct(\"0000-00-00_00:00:00\", &\n         null(), null(), null(), null(), null(), null(), null(), null(), null(), null() )\n    type(inputstruct) :: nextread= inputstruct(\"0000-00-00_00:00:00\", &\n         null(), null(), null(), null(), null(), null(), null(), null(), null(), null() )\n\n!KWM    print*, 'target_date        = ', target_date\n!KWM    print*, 'lastread%read_date = ', lastread%read_date\n!KWM    print*, 'nextread%read_date = ', nextread%read_date\n\n    if (target_date > nextread%read_date ) then\n       !\n       ! We've advanced beyond the date of the end-bracketing data in memory.\n       ! Read the next (later) forcing data, and put the data into the nextread\n       ! structure.\n       !\n\n       if (nextread%read_date /= \"0000-00-00_00:00:00\") then\n          ! Clear the old lastread data\n          call clear_inputstruct(lastread)\n\n          ! Copy nextread to lastread\n          lastread = nextread\n\n          ! Clear nextread\n          call nullify_inputstruct(nextread)\n       endif\n\n       ! Guess the next read date (from the last read date and the forcing timestep).\n       ! If there is no last date, assume we're at the beginning of our processing\n       ! and take the target_date as the first timestep, for which forcing data\n       ! must be available.\n\n       if (lastread%read_date == \"0000-00-00_00:00:00\") then\n          nextread%read_date = target_date\n       else\n          call geth_newdate(nextread%read_date, lastread%read_date, forcing_timestep)\n       endif\n\n       ! Build a file name\n       flnm = flnm_template\n       call strrep(flnm, \"<date>\", nextread%read_date(1:4)//nextread%read_date(6:7)//nextread%read_date(9:10)//nextread%read_date(12:13))\n\n!KWM       print*, 'new nextread%read_date = ', nextread%read_date\n       !print*, 'read file:  ', trim(flnm)\n\n       ! Open the NetCDF file.\n#ifdef _PARALLEL_\n       ierr = nf90_open_par(flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n       ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n#endif\n       if (ierr /= 0) then\n#ifdef _PARALLEL_\n          call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n          if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n          if (rank == 0) then\n#endif\n             write(*,'(\"A)  Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n#ifdef _PARALLEL_\n          endif\n          call mpi_finalize(ierr)\n#endif\n          stop\n       endif\n\n       ! Allocate space to hold data\n       call allocate_inputstruct(nextread, xstart, xend, ystart, yend)\n\n       ! Read the data\n       call get_2d_netcdf(\"T2D\",     ncid, nextread%t,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(\"Q2D\",     ncid, nextread%q,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(\"U2D\",     ncid, nextread%u,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(\"V2D\",     ncid, nextread%v,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(\"PSFC\",    ncid, nextread%p,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(\"LWDOWN\",  ncid, nextread%lw,    units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(\"SWDOWN\",  ncid, nextread%sw,    units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(\"RAINRATE\",ncid, nextread%pcp,   units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(\"VEGFRA\",  ncid, nextread%fpar,  units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n       if (ierr /= 0) then\n          ! print*, 'VEGFRA not found!'\n          ! If we don't find a new VEGFRA, carry over the old one\n          if (associated(lastread%fpar)) then\n             nextread%fpar = lastread%fpar\n          else\n             nextread%fpar = fpar\n          endif\n       endif\n       call get_2d_netcdf(\"LAI\",     ncid, nextread%lai,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n       if (ierr /= 0) then\n          ! print*, 'LAI not found!'\n          ! If we don't find a new LAI, carry over the old one\n          if (associated(lastread%fpar)) then\n             nextread%lai = lastread%lai\n          endif\n       endif\n\n       ! Close the file\n       ierr = nf90_close(ncid)\n\n    endif\n\n    if (target_date == nextread%read_date) then\n       !\n       ! We have advanced to the later date of our bracketing times for interpolation.\n       ! Take that data as is, no interpolation necessary, move that data into the \n       ! lastread structure, and return that data.\n       !\n\n       ! Fill the t, q, u, v, ... arrays with data from the nextread structure.\n       call copyfrom_inputstruct(nextread, t, q, u, v, p, lw, sw, pcp, fpar, lai, xstart, xend, ystart, yend)\n\n       ! Clear the old lastread data\n       call clear_inputstruct(lastread)\n\n       ! Copy nextread to lastread\n       lastread = nextread\n\n       ! Set the nextread%read_date field to signal that we need to read\n       nextread%read_date = \"0000-00-00_00:00:00\"\n\n       ! Clear nextread\n       call nullify_inputstruct(nextread)\n\n    else if ( ( target_date > lastread%read_date ) .and. ( target_date < nextread%read_date ) ) then\n\n       !\n       ! We are at a Noah time step between the lastread data and the available nextread data.\n       ! Do temporal interpolation and return the interpolated data.  Keep lastread\n       ! and nextread as they were.\n       !\n\n       ! Fill the t, q, u, v, ... arrays with data interpolated between lastread and nextread times.\n       call interpolate_inputstruct(lastread, nextread, target_date, &\n            t, q, u, v, p, lw, sw, pcp, fpar, lai, xstart, xend, ystart, yend)\n\n    else\n\n       print*, 'target_date        = ', target_date\n       print*, 'lastread%read_date = ', lastread%read_date\n       print*, 'nextread%read_date = ', nextread%read_date\n\n       STOP \"We should not be here.  Problem with the logic of READFORC_SHORTER_TIMESTEP\"\n\n    endif\n\n  end subroutine READFORC_HRLDAS\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine allocate_inputstruct(instruct, xstart, xend, ystart, yend)\n    implicit none\n    type(inputstruct)   :: instruct\n    integer, intent(in) :: xstart\n    integer, intent(in) :: xend\n    integer, intent(in) :: ystart\n    integer, intent(in) :: yend\n\n    integer :: allostat\n\n    allocate(instruct%t   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%t\"\n\n    allocate(instruct%q   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%q\"\n\n    allocate(instruct%u   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%u\"\n\n    allocate(instruct%v   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%v\"\n\n    allocate(instruct%p   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%p\"\n\n    allocate(instruct%lw  (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%lw\"\n\n    allocate(instruct%sw  (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%sw\"\n\n    allocate(instruct%pcp (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%pcp\"\n\n    allocate(instruct%fpar(xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%fpar\"\n\n    allocate(instruct%lai (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%lai\"\n  end subroutine allocate_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine copyfrom_inputstruct(instruct, t, q, u, v, p, lw, sw, pcp, fpar, lai, xstart, xend, ystart, yend)\n    implicit none\n    type(inputstruct), intent(in) :: instruct\n    integer,           intent(in) :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: t, q, u, v, p, lw, sw, pcp, fpar, lai\n    t    = instruct%t\n    q    = instruct%q\n    u    = instruct%u\n    v    = instruct%v\n    p    = instruct%p\n    lw   = instruct%lw\n    sw   = instruct%sw\n    pcp  = instruct%pcp\n    fpar = instruct%fpar\n    lai  = instruct%lai\n  end subroutine copyfrom_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine interpolate_inputstruct(instructA, instructB, target_date, &\n       t, q, u, v, p, lw, sw, pcp, fpar, lai, xstart, xend, ystart, yend)\n    implicit none\n    type(inputstruct),                        intent(in)  :: instructA, instructB\n    character(len=19),                        intent(in)  :: target_date\n    integer,                                  intent(in)  :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: t, q, u, v, p, lw, sw, pcp, fpar, lai\n\n    integer :: idts, idts2\n    real    :: fraction\n\n    call geth_idts(target_date, instructA%read_date, idts)\n    call geth_idts(instructB%read_date, instructA%read_date, idts2)\n\n    fraction = real(idts2-idts)/real(idts2)\n    t  = ( instructA%t  * fraction ) + ( instructB%t  * (1.0-fraction) )\n    q  = ( instructA%q  * fraction ) + ( instructB%q  * (1.0-fraction) )\n    u  = ( instructA%u  * fraction ) + ( instructB%u  * (1.0-fraction) )\n    v  = ( instructA%v  * fraction ) + ( instructB%v  * (1.0-fraction) )\n    p  = ( instructA%p  * fraction ) + ( instructB%p  * (1.0-fraction) )\n    lw = ( instructA%lw * fraction ) + ( instructB%lw * (1.0-fraction) )\n    sw = ( instructA%sw * fraction ) + ( instructB%sw * (1.0-fraction) )\n    pcp = instructA%pcp\n    fpar = instructA%fpar\n    lai  = instructA%lai\n  end subroutine interpolate_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine clear_inputstruct(instruct)\n    implicit none\n    type(inputstruct) :: instruct\n\n    if (associated(instruct%t)) then\n       deallocate(instruct%t)\n       nullify(instruct%t)\n    endif\n\n    if (associated(instruct%q)) then\n       deallocate(instruct%q)\n       nullify(instruct%q)\n    endif\n\n    if (associated(instruct%u)) then\n       deallocate(instruct%u)\n       nullify(instruct%u)\n    endif\n\n    if (associated(instruct%v)) then\n       deallocate(instruct%v)\n       nullify(instruct%v)\n    endif\n\n    if (associated(instruct%p)) then\n       deallocate(instruct%p)\n       nullify(instruct%p)\n    endif\n\n    if (associated(instruct%lw)) then\n       deallocate(instruct%lw)\n       nullify(instruct%lw)\n    endif\n\n    if (associated(instruct%sw)) then\n       deallocate(instruct%sw)\n       nullify(instruct%sw)\n    endif\n\n    if (associated(instruct%pcp)) then\n       deallocate(instruct%pcp)\n       nullify(instruct%pcp)\n    endif\n\n    if (associated(instruct%fpar)) then\n       deallocate(instruct%fpar)\n       nullify(instruct%fpar)\n    endif\n\n    if (associated(instruct%lai)) then\n       deallocate(instruct%lai)\n       nullify(instruct%lai)\n    endif\n  end subroutine clear_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine nullify_inputstruct(instruct)\n    implicit none\n    type(inputstruct) :: instruct\n\n    nullify(instruct%t)\n    nullify(instruct%q)\n    nullify(instruct%u)\n    nullify(instruct%v)\n    nullify(instruct%p)\n    nullify(instruct%lw)\n    nullify(instruct%sw)\n    nullify(instruct%pcp)\n    nullify(instruct%fpar)\n    nullify(instruct%lai)\n  end subroutine nullify_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine READSNOW_HRLDAS(flnm,xstart,xend,ystart,yend,target_date,weasd,snodep)\n    implicit none\n\n    character(len=*),                                     intent(in)  :: flnm\n    integer,                                              intent(in)  :: xstart, xend\n    integer,                                              intent(in)  :: ystart, yend\n    character(len=*),                                     intent(in)  :: target_date\n    real,             dimension(xstart:xend,ystart:yend), intent(out) :: weasd\n    real,             dimension(xstart:xend,ystart:yend), intent(out) :: snodep\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n\n    ! Open the NetCDF file.\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n#endif\n    if (ierr /= 0) then\n       write(*,'(\"READSNOW_HRLDAS:  Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       stop\n    endif\n\n    call get_2d_netcdf(\"WEASD\",  ncid, weasd,   units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    if (trim(units) == \"m\") then\n       ! No conversion necessary\n    else if (trim(units) == \"mm\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else if (trim(units) == \"kg m{-2}\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else if (trim(units) == \"kg/m2\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else\n       print*, 'units = \"'//trim(units)//'\"'\n       stop \"Unrecognized units on WEASD\"\n    endif\n\n    call get_2d_netcdf(\"SNODEP\",     ncid, snodep,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n\n    if (ierr /= 0) then\n       ! Quick assumption regarding snow depth.\n       snodep = weasd * 10.\n    endif\n\n    ierr = nf90_close(ncid)\n\n  end subroutine READSNOW_HRLDAS\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine prepare_output_file(outdir, version, iz0tlnd, sfcdif_option, ucmcall, igrid, &\n       output_timestep, llanduse, split_output_count, hgrid, &\n       ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar, iswater,  &\n       mapproj, lat1, lon1, dx, dy, truelat1, truelat2, cen_lon,     &\n       nsoil, sldpth, startdate, date, &\n       vegtyp, soltyp)\n    ! To prepare the output file, we create the file, write dimensions and attributes, write the time variable.\n    ! At the end of this routine, the output file is out of define mode.\n    implicit none\n#include <netcdf.inc>\n\n    character(len=*),                         intent(in) :: outdir\n    character(len=*),                         intent(in) :: version\n    integer,                                  intent(in) :: sfcdif_option\n    integer,                                  intent(in) :: iz0tlnd\n    integer,                                  intent(in) :: ucmcall\n    integer,                                  intent(in) :: igrid\n    integer,                                  intent(in) :: output_timestep\n    character(len=*),                         intent(in) :: llanduse\n    integer,                                  intent(in) :: split_output_count\n    character,                                intent(in) :: hgrid\n    integer,                                  intent(in) :: ixfull\n    integer,                                  intent(in) :: jxfull\n    integer,                                  intent(in) :: ixpar\n    integer,                                  intent(in) :: jxpar\n    integer,                                  intent(in) :: xstartpar\n    integer,                                  intent(in) :: ystartpar\n    integer,                                  intent(in) :: iswater\n    integer,                                  intent(in) :: mapproj\n    real,                                     intent(in) :: lat1\n    real,                                     intent(in) :: lon1\n    real,                                     intent(in) :: dx\n    real,                                     intent(in) :: dy\n    real,                                     intent(in) :: truelat1\n    real,                                     intent(in) :: truelat2\n    real,                                     intent(in) :: cen_lon\n    integer,                                  intent(in) :: nsoil\n    real,             dimension(nsoil),       intent(in) :: sldpth\n    character(len=19),                        intent(in) :: startdate\n    character(len=19),                        intent(in) :: date\n    integer,          dimension(ixpar,jxpar), intent(in) :: vegtyp\n    integer,          dimension(ixpar,jxpar), intent(in) :: soltyp\n\n    integer :: ncid\n\n    integer :: dimid_ix, dimid_jx, dimid_times, dimid_datelen, varid, n\n    integer :: dimid_dum, dimid_layers\n    integer :: iret\n    character(len=256) :: output_flnm\n    character(len=19)  :: date19\n\n    integer :: ierr\n\n    if (output_count_remember == 0) then\n       ! If this is a new output file:\n       !   We have to create a new file, do dimension initializations, and write global attributes to the file.\n       !   Then we get out of define mode.\n       if (mod(output_timestep,3600) == 0) then\n          write(output_flnm, '(A,\"/\",A10,\".LDASOUT_DOMAIN\",I1)') outdir, date(1:4)//date(6:7)//date(9:10)//date(12:13), igrid\n       elseif (mod(output_timestep,60) == 0) then\n          write(output_flnm, '(A,\"/\",A12,\".LDASOUT_DOMAIN\",I1)') outdir, date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n       else\n          write(output_flnm, '(A,\"/\",A14,\".LDASOUT_DOMAIN\",I1)') outdir, date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16)//date(18:19), igrid\n       endif\n#ifdef _PARALLEL_\n       iret = nf90_create(trim(output_flnm), &\n            OR(NF90_CLOBBER, NF90_NETCDF4), ncid, comm=HYDRO_COMM_WORLD, info=MPI_INFO_NULL)\n#else\n       iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n#endif\n       call error_handler(iret, failure=\"Problem nf90_create for \"//trim(output_flnm))\n\n       ncid_remember = ncid\n       define_mode_remember = .TRUE.\n\n       iret = nf90_def_dim(ncid, \"Time\", NF90_UNLIMITED, dimid_times)\n       iret = nf90_def_dim(ncid, \"DateStrLen\", 19, dimid_datelen)\n       ! Dimensions reflect the full size of the subwindow (not the strip known by this particular process).\n       iret = nf90_def_dim(ncid, \"west_east\", ixfull, dimid_ix)\n       iret = nf90_def_dim(ncid, \"south_north\", jxfull, dimid_jx)\n       iret = nf90_def_dim(ncid, \"west_east_stag\", ixfull+1, dimid_dum)\n       iret = nf90_def_dim(ncid, \"south_north_stag\", jxfull+1, dimid_dum)\n       iret = nf90_def_dim(ncid, \"soil_layers_stag\", nsoil, dimid_layers)\n\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"TITLE\", \"OUTPUT FROM HRLDAS \"//version)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -1.E33)\n\n       ! TODO:  Add Grid information   (should look more-or-less like wrfout files)\n       ! TODO:  Add Units information  (should look more-or-less like wrfout files)\n\n       date19(1:19) = \"0000-00-00_00:00:00\"\n       date19(1:len_trim(startdate)) = startdate\n\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"START_DATE\", date19)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", mapproj)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"LAT1\", lat1)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"LON1\", lon1)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"DX\", dx)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"DY\", dy)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"STAND_LON\", cen_lon)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"MMINLU\", llanduse)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"IZ0TLND\", iz0tlnd)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"SFCDIF_OPTION\", sfcdif_option)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"UCMCALL\", ucmcall)\n\n!\n! Done with dimensions and global attributes.\n! Now define and describe our \"Times\" variable.\n!\n\n       iret = nf90_def_var(ncid,  \"Times\",  NF90_CHAR, (/dimid_datelen,dimid_times/), varid)\n       call error_handler(iret, failure=\"Problem nf90_def_var for \"//trim(output_flnm))\n\n       iret = nf90_enddef(ncid)\n       call error_handler(iret, failure=\"Problem nf90_enddef\")\n       define_mode_remember = .FALSE.\n\n    endif\n    xstartpar_remember = xstartpar\n    dimid_ix_remember = dimid_ix\n    dimid_jx_remember = dimid_jx\n    dimid_times_remember = dimid_times\n    dimid_layers_remember = dimid_layers\n    iswater_remember = iswater\n\n    allocate(vegtyp_remember(ixpar,jxpar))\n    vegtyp_remember = vegtyp\n\n!\n! While we're here, put the data for the \"Times\" variable to the NetCDF file.\n!\n\n    date19(1:19) = \"0000-00-00_00:00:00\"\n    date19(1:len_trim(date)) = date\n    iret = nf90_inq_varid(ncid_remember, \"Times\", varid)\n    call error_handler(iret, \"OUTPUT_HRLDAS:  Problem inquiring on 'Times'\")\n\n    iret = nf90_put_var(ncid_remember, varid, date, (/1,output_count_remember+1/), (/19,1/))\n    call error_handler(iret, \"OUTPUT_HRLDAS:  Problem writing variable 'Times'\")\n\n  end subroutine prepare_output_file\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine set_output_define_mode(imode)\n    implicit none\n    integer, intent(in) :: imode\n    integer :: ierr\n\n    if (imode == 1) then\n       ! We need to define things only with a new file, i.e., only when output_count_remember == 0\n       if (output_count_remember > 0) return\n       ierr = nf90_redef(ncid_remember)\n       call error_handler(ierr, failure=\"Problem nf90_redef\")\n       define_mode_remember = .TRUE.\n    else\n       if (define_mode_remember) then\n          ierr = nf90_enddef(ncid_remember)\n          call error_handler(ierr, failure=\"Problem nf90_enddef\")\n          define_mode_remember = .FALSE.\n       endif\n    endif\n\n  end subroutine set_output_define_mode\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine finalize_output_file(split_output_count)\n    implicit none\n    integer, intent(in)  :: split_output_count\n    integer :: ierr\n\n    output_count_remember = output_count_remember + 1\n    if (output_count_remember == split_output_count) then\n       output_count_remember = 0\n       ierr = nf90_close(ncid_remember)\n       call error_handler(ierr, failure=\"Problem nf90_close for output file\")\n    else\n       ierr = nf90_sync(ncid_remember)\n       call error_handler(ierr, failure=\"Problem nf90_sync for output file\")\n    endif\n\n    deallocate(vegtyp_remember)\n\n  end subroutine finalize_output_file\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine add_to_output_2d_float ( array, name, description, units )\n    implicit none\n    real, dimension(:,:), intent(in) :: array\n    character(len=*), intent(in) :: name, description, units\n    integer :: ixpar, jxpar\n\n    if (define_mode_remember) then\n       call make_var_att_2d ( ncid_remember , dimid_ix_remember , dimid_jx_remember , dimid_times_remember , &\n            NF90_FLOAT , trim(name) , trim(description) , trim(units) )\n    else\n       ixpar = size(array,1)\n       jxpar = size(array,2)\n       call put_var_2d (ncid_remember , output_count_remember+1 , vegtyp_remember , iswater_remember , &\n            ixpar , jxpar , xstartpar_remember , trim(name) , array )\n    endif\n  end subroutine add_to_output_2d_float\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine add_to_output_2d_integer ( array, name, description, units )\n    implicit none\n    integer, dimension(:,:), intent(in) :: array\n    character(len=*), intent(in) :: name, description, units\n    integer :: ixpar, jxpar\n\n    if (define_mode_remember) then\n       call make_var_att_2d ( ncid_remember , dimid_ix_remember , dimid_jx_remember , dimid_times_remember , &\n            NF90_INT , trim(name) , trim(description) , trim(units) )\n    else\n       ixpar = size(array,1)\n       jxpar = size(array,2)\n       call put_var_int (ncid_remember , output_count_remember+1 , vegtyp_remember , iswater_remember , &\n            ixpar , jxpar , xstartpar_remember , trim(name) , array )\n    endif\n  end subroutine add_to_output_2d_integer\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine add_to_output_3d ( array, name, description, units )\n    implicit none\n    real, dimension(:,:,:), intent(in) :: array\n    character(len=*), intent(in) :: name, description, units\n    integer :: ixpar, jxpar, kxpar\n\n    if (define_mode_remember) then\n       call make_var_att_3d ( ncid_remember , dimid_ix_remember , dimid_jx_remember , dimid_times_remember , &\n            NF90_FLOAT , dimid_layers_remember, trim(name) , trim(description) , trim(units) )\n    else\n\n       ixpar = size(array,1)\n       jxpar = size(array,2)\n       kxpar = size(array,3)\n\n       call put_var_3d (ncid_remember , output_count_remember+1 , vegtyp_remember , iswater_remember , &\n            ixpar , jxpar , xstartpar_remember , kxpar, trim(name) , array )\n    endif\n  end subroutine add_to_output_3d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine make_var_att_2d(ncid, dimid_ix, dimid_jx, dimid_times, itype, varname, vardesc, varunits)\n    implicit none\n    integer,          intent(in) :: ncid\n    character(len=*), intent(in) :: varname\n    character(len=*), intent(in) :: vardesc\n    character(len=*), intent(in) :: varunits\n    integer,          intent(in) :: dimid_ix\n    integer,          intent(in) :: dimid_jx\n    integer,          intent(in) :: dimid_times\n    integer,          intent(in) :: itype\n    integer :: iret\n    integer :: varid\n\n    iret = nf90_def_var(ncid,  varname,   itype, (/dimid_ix,dimid_jx,dimid_times/), varid)\n    call error_handler(iret, \"MAKE_VAR_ATT_2D: Failure defining variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"MemoryOrder\", \"XY \")\n    call error_handler(iret, \"MAKE_VAR_ATT_2D: Failure adding MemoryOrder attribute to variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"description\", vardesc)\n    call error_handler(iret, \"MAKE_VAR_ATT_2D: Failure adding description attribute to variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"units\", varunits)\n    call error_handler(iret, \"MAKE_VAR_ATT_2D: Failure adding units attribute '\"//trim(varunits)//\"' to variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"stagger\", \"-\")\n    call error_handler(iret, \"MAKE_VAR_ATT_2D: Failure adding stagger attribute to variable \"//trim(varname))\n\n  end subroutine make_var_att_2d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine make_var_att_3d(ncid, dimid_ix, dimid_jx, dimid_times, itype, dimid_layers, varname, vardesc, varunits)\n    implicit none\n    integer,          intent(in) :: ncid\n    character(len=*), intent(in) :: varname\n    character(len=*), intent(in) :: vardesc\n    character(len=*), intent(in) :: varunits\n    integer,          intent(in) :: dimid_ix\n    integer,          intent(in) :: dimid_jx\n    integer,          intent(in) :: dimid_times\n    integer,          intent(in) :: dimid_layers\n    integer,          intent(in) :: itype\n    integer :: iret\n    integer :: varid\n\n    iret = nf90_def_var(ncid,  varname, itype, (/dimid_ix,dimid_jx,dimid_layers,dimid_times/), varid)\n    call error_handler(iret, \"MAKE_VAR_ATT_3D:  Failure defining variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"MemoryOrder\", \"XYZ\")\n    call error_handler(iret, \"MAKE_VAR_ATT_3D: Failure adding MemoryOrder attribute for variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"description\", vardesc)\n    call error_handler(iret, \"MAKE_VAR_ATT_3D: Failure adding description attribute to variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"units\", varunits)\n    call error_handler(iret, \"MAKE_VAR_ATT_3D: Failure adding units attribute '\"//trim(varunits)//\"' to variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"stagger\", \"Z\")\n    call error_handler(iret, \"MAKE_VAR_ATT_3D: Failure adding stagger attribute to variable \"//trim(varname))\n\n  end subroutine make_var_att_3d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine put_var_2d(ncid, output_count, vegtyp, iswater, ix, jx, xstart, varname, vardata)\n    implicit none\n    integer,                   intent(in) :: ncid\n    integer,                   intent(in) :: output_count\n    character(len=*),          intent(in) :: varname\n    integer,                   intent(in) :: ix\n    integer,                   intent(in) :: jx\n    integer,                   intent(in) :: xstart\n    integer, dimension(ix,jx), intent(in) :: vegtyp\n    integer,                   intent(in) :: iswater\n    real,    dimension(ix,jx), intent(in) :: vardata\n\n    real,    dimension(ix,jx)             :: xdum\n    integer                               :: iret\n    integer                               :: varid\n\n    integer, dimension(3) :: nstart\n    integer, dimension(3) :: ncount\n\n    where (vegtyp == ISWATER)\n       xdum = -1.E33\n    elsewhere\n       xdum = vardata\n    endwhere\n\n    iret = nf90_inq_varid(ncid,  varname, varid)\n    call error_handler(iret, \"Subroutine PUT_VAR_2D:  Problem finding variable id for \"//trim(varname)//\".\")\n\n    nstart = (/ xstart ,  1 , output_count /)\n    ncount = (/     ix , jx ,            1 /)\n\n    iret = nf90_put_var(ncid, varid, xdum, start=nstart, count=ncount)\n    call error_handler(iret, \"Subroutine PUT_VAR_2D:  Problem putting variable \"//trim(varname)//\" to NetCDF file.\")\n\n  end subroutine put_var_2d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine put_var_int(ncid, output_count, vegtyp, iswater, ix, jx, xstart, varname, vardata)\n    implicit none\n    integer,                                              intent(in) :: ncid\n    integer,                                              intent(in) :: output_count\n    character(len=*),                                     intent(in) :: varname\n    integer,                                              intent(in) :: ix\n    integer,                                              intent(in) :: jx\n    integer,                                              intent(in) :: xstart\n    integer,                                              intent(in) :: iswater\n    integer, dimension(ix,jx),                            intent(in) :: vegtyp\n    integer, dimension(ix,jx),                            intent(in) :: vardata\n\n    integer                                                          :: iret\n    integer                                                          :: varid\n\n    integer, dimension(3)                                            :: nstart\n    integer, dimension(3)                                            :: ncount\n\n    nstart = (/ xstart ,  1 , output_count /)\n    ncount = (/     ix , jx ,            1 /)\n\n    iret = nf90_inq_varid(ncid,  varname, varid)\n    call error_handler(iret, failure=\"Subroutine PUT_VAR_INT:  Problem finding variable id for variable: \"//varname)\n\n    iret = nf90_put_var(ncid, varid, vardata, nstart, ncount)\n    call error_handler(iret, failure=\"Subroutine PUT_VAR_INT:  Problem putting variable '\"//varname//\"' to NetCDF file.\")\n\n  end subroutine put_var_int\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine put_var_3d(ncid, output_count, vegtyp, iswater, ix, jx, xstart, nsoil, varname, vardata)\n    implicit none\n    integer,                                                    intent(in) :: ncid\n    integer,                                                    intent(in) :: output_count\n    character(len=*),                                           intent(in) :: varname\n    integer,                                                    intent(in) :: ix\n    integer,                                                    intent(in) :: jx\n    integer,                                                    intent(in) :: xstart\n    integer,                                                    intent(in) :: nsoil\n    integer,                                                    intent(in) :: iswater\n    integer, dimension(ix, jx),                                 intent(in) :: vegtyp\n    real,    dimension(ix, jx, nsoil),                          intent(in) :: vardata\n    real,    dimension(ix, jx, nsoil)                                      :: xdum\n    integer                                                                :: iret\n    integer                                                                :: varid\n    integer                                                                :: n\n    integer, dimension(4)                                                  :: nstart\n    integer, dimension(4)                                                  :: ncount\n\n    nstart = (/ xstart ,  1 ,     1 , output_count /)\n    ncount = (/     ix , jx , nsoil ,            1 /)\n\n    xdum = vardata\n    do n = 1, nsoil\n       where (vegtyp(:,:) == ISWATER) xdum(:,:,n) = -1.E33\n    enddo\n\n    iret = nf90_inq_varid(ncid,  varname, varid)\n    call error_handler(iret, \"Subroutine PUT_VAR_3D:  Problem finding variable id for \"//trim(varname)//\".\")\n\n    iret = nf90_put_var(ncid, varid, xdum, start=nstart, count=ncount)\n    call error_handler(iret, \"Subroutine PUT_VAR_3D:  Problem putting variable \"//trim(varname)//\" to NetCDF file.\")\n\n  end subroutine put_var_3d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n  subroutine finalize_restart_file()\n    implicit none\n\n    deallocate(vegtyp_remember)\n    restart_filename_remember = \" \"\n    iswater_remember   = -999999\n    xstartpar_remember = -999999\n\n  end subroutine finalize_restart_file\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine prepare_restart_file(outdir, version, iz0tlnd, sfcdif_option, ucmcall, igrid, llanduse, olddate, startdate,  &\n       ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar,                                    &\n       nsoil, dx, dy, truelat1, truelat2, mapproj, lat1, lon1, cen_lon,                       &\n       iswater, vegtyp)\n\n    implicit none\n#include <netcdf.inc>\n\n    character(len=*),                      intent(in) :: outdir\n    character(len=*),                      intent(in) :: version\n    integer,                               intent(in) :: iz0tlnd\n    integer,                               intent(in) :: sfcdif_option\n    integer,                               intent(in) :: ucmcall\n    integer,                               intent(in) :: igrid\n    character(len=*),                      intent(in) :: llanduse\n    character(len=*),                      intent(in) :: olddate\n    character(len=*),                      intent(in) :: startdate\n    integer,                               intent(in) :: ixfull\n    integer,                               intent(in) :: jxfull\n    integer,                               intent(in) :: ixpar\n    integer,                               intent(in) :: jxpar\n    integer,                               intent(in) :: xstartpar\n    integer,                               intent(in) :: ystartpar\n    integer,                               intent(in) :: nsoil\n    real,                                  intent(in) :: dx, dy\n    real,                                  intent(in) :: truelat1, truelat2\n    integer,                               intent(in) :: mapproj\n    real,                                  intent(in) :: lat1, lon1, cen_lon\n    integer,                               intent(in) :: iswater\n    integer, dimension(ixpar,jxpar),       intent(in) :: vegtyp\n\n    character(len=1) :: hgrid\n    integer :: ncid\n    character(len=256) :: output_flnm\n    integer :: ierr\n    integer :: varid\n    integer :: dimid_times, dimid_datelen, dimid_ix, dimid_jx, dimid_dum, dimid_layers\n    character(len=19) :: date19\n    integer :: rank\n\n#ifdef _PARALLEL_\n\n    call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n\n#else\n\n    rank = 0\n\n#endif\n\n\n    write(output_flnm, '(A,\"/RESTART.\",A10,\"_DOMAIN\",I1)') trim(outdir), olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13), igrid\n    if (rank==0) print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n\n    restart_filename_remember = output_flnm\n    iswater_remember   = iswater\n    xstartpar_remember = xstartpar\n    allocate(vegtyp_remember(ixpar,jxpar))\n    vegtyp_remember = vegtyp\n\n#ifdef _PARALLEL_\n\n    ierr = nf90_create(trim(output_flnm), &\n         OR(NF90_CLOBBER, NF90_NETCDF4), ncid, comm=HYDRO_COMM_WORLD, info=MPI_INFO_NULL)\n#else\n    ierr = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n#endif\n\n    if (ierr /= 0) stop \"Problem nf90_create\"\n\n    ierr = nf90_def_dim(ncid, \"Time\", NF90_UNLIMITED, dimid_times)\n    ierr = nf90_def_dim(ncid, \"DateStrLen\", 19, dimid_datelen)\n    ierr = nf90_def_dim(ncid, \"west_east\", ixfull, dimid_ix)\n    ierr = nf90_def_dim(ncid, \"south_north\", jxfull, dimid_jx)\n    ierr = nf90_def_dim(ncid, \"west_east_stag\", ixfull+1, dimid_dum)\n    ierr = nf90_def_dim(ncid, \"south_north_stag\", jxfull+1, dimid_dum)\n    ierr = nf90_def_dim(ncid, \"soil_layers_stag\", nsoil, dimid_layers)\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TITLE\", \"RESTART FILE FROM HRLDAS \"//version)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -1.E33)\n\n    date19(1:19) = \"0000-00-00_00:00:00\"\n    date19(1:len_trim(startdate)) = startdate\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"START_DATE\", date19)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", mapproj)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LAT1\", lat1)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LON1\", lon1)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"DX\", dx)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"DY\", dy)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"STAND_LON\", cen_lon)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"MMINLU\", llanduse)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"IZ0TLND\", iz0tlnd)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"SFCDIF_OPTION\", sfcdif_option)\n#ifdef _HRLDAS_URBAN_\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"UCMCALL\", ucmcall)\n#endif\n\n!\n! Done with dimensions and global attributes.\n! Now define and describe all our NetCDF restart variables.\n!\n\n    ierr = nf90_def_var(ncid,  \"Times\",  NF90_CHAR, (/dimid_datelen,dimid_times/), varid)\n    ierr = nf90_enddef(ncid)\n\n!\n! Done defining and describing all our NetCDF restart variables.\n! Now actually put the data for each variable into the NetCDF file.\n!\n\n    date19(1:19) = \"0000-00-00_00:00:00\"\n    date19(1:len_trim(olddate)) = olddate\n\n    ierr = nf90_inq_varid(ncid, \"Times\", varid)\n    call error_handler(ierr, \"WRITE_RESTART:  Problem inquiring varid for 'Times'\")\n\n    ierr = nf90_put_var(ncid, varid, olddate, (/1,1/), (/19,1/))\n    call error_handler(ierr, \"WRITE_RESTART:  problem putting 'Times' to restart file\")\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"WRITE_RESTART:  nf90_close\")\n\n  end subroutine prepare_restart_file\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine add_to_restart_2d_float(array, name, units, description)\n    implicit none\n    real,            dimension(:,:),                              intent(in) :: array\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n\n    character(len=256) :: output_flnm\n    integer :: ncid\n    integer :: ierr\n    integer :: dimid_ix\n    integer :: dimid_jx\n    integer :: dimid_times\n    integer :: ixout\n    integer :: xstartout\n    integer :: iswater\n    character(len=256) :: local_units\n    character(len=256) :: local_description\n\n    integer :: ixpar\n    integer :: jxpar\n\n    output_flnm = restart_filename_remember\n    iswater     = iswater_remember\n\n    ixpar = size(array,1)\n    jxpar = size(array,2)\n\n    if (present(units)) then\n       local_units = units\n    else\n       local_units = \"-\"\n    endif\n\n    if (present(description)) then\n       local_description = description\n    else\n       local_description = \"-\"\n    endif\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(output_flnm), NF90_WRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(output_flnm), NF90_WRITE, ncid)\n#endif\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_open\")\n\n    ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'west_east'\")\n\n    ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'south_north'\")\n\n    ierr = nf90_inq_dimid(ncid, \"Time\", dimid_times)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'Time'\")\n\n    ierr = nf90_redef(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_redef\")\n\n    call make_var_att_2d(ncid, dimid_ix, dimid_jx, dimid_times, NF90_FLOAT, name, trim(local_description), trim(local_units))\n\n    ierr = nf90_enddef(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_enddef\")\n\n    call put_var_2d(ncid, 1, vegtyp_remember, iswater, ixpar, jxpar, xstartpar_remember, name, array)\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_close\")\n\n  end subroutine add_to_restart_2d_float\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine add_to_restart_2d_integer(array, name, units, description)\n    implicit none\n    integer,         dimension(:,:),                              intent(in) :: array\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n\n    character(len=256) :: output_flnm\n    integer :: ncid\n    integer :: ierr\n    integer :: dimid_ix\n    integer :: dimid_jx\n    integer :: dimid_times\n    integer :: ixout\n    integer :: xstartout\n    integer :: iswater\n    character(len=256) :: local_units\n    character(len=256) :: local_description\n\n    integer :: ixpar\n    integer :: jxpar\n\n    output_flnm = restart_filename_remember\n    iswater     = iswater_remember\n\n    ixpar = size(array,1)\n    jxpar = size(array,2)\n\n    if (present(units)) then\n       local_units = units\n    else\n       local_units = \"-\"\n    endif\n\n    if (present(description)) then\n       local_description = description\n    else\n       local_description = \"-\"\n    endif\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(output_flnm), NF90_WRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(output_flnm), NF90_WRITE, ncid)\n#endif\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_open\")\n\n    ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'west_east'\")\n\n    ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'south_north'\")\n\n    ierr = nf90_inq_dimid(ncid, \"Time\", dimid_times)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'Time'\")\n\n    ierr = nf90_redef(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_redef\")\n\n    call make_var_att_2d(ncid, dimid_ix, dimid_jx, dimid_times, NF90_INT, name, trim(local_description), trim(local_units))\n\n    ierr = nf90_enddef(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_enddef\")\n\n    call put_var_int(ncid, 1, vegtyp_remember, iswater, ixpar, jxpar, xstartpar_remember, name, array)\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_close\")\n\n  end subroutine add_to_restart_2d_integer\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine add_to_restart_3d(array, name, units, description)\n    implicit none\n    real,            dimension(:,:,:),                            intent(in) :: array\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n\n    character(len=256) :: output_flnm\n    integer :: ncid\n    integer :: ierr\n    integer :: dimid_ix\n    integer :: dimid_jx\n    integer :: dimid_kx\n    integer :: dimid_times\n    integer :: ixout\n    integer :: xstartout\n    integer :: iswater\n    character(len=256) :: local_units\n    character(len=256) :: local_description\n\n    integer :: ixpar\n    integer :: jxpar\n    integer :: kxpar\n\n    output_flnm = restart_filename_remember\n    iswater     = iswater_remember\n\n    ixpar = size(array,1)\n    jxpar = size(array,2)\n    kxpar = size(array,3)\n\n    if (present(units)) then\n       local_units = units\n    else\n       local_units = \"-\"\n    endif\n\n    if (present(description)) then\n       local_description = description\n    else\n       local_description = \"-\"\n    endif\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(output_flnm), NF90_WRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(output_flnm), NF90_WRITE, ncid)\n#endif\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_open\")\n\n    ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'west_east'\")\n\n    ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'south_north'\")\n\n    ierr = nf90_inq_dimid(ncid, \"soil_layers_stag\", dimid_kx)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'soil_layers_stag'\")\n\n    ierr = nf90_inq_dimid(ncid, \"Time\", dimid_times)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_inq_dimid for 'Time'\")\n\n    ierr = nf90_redef(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_redef\")\n\n    call make_var_att_3d(ncid, dimid_ix, dimid_jx, dimid_times, NF90_FLOAT, dimid_kx, name, trim(local_description), trim(local_units))\n\n    ierr = nf90_enddef(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_enddef\")\n\n    call put_var_3d(ncid, 1, vegtyp_remember, iswater, ixpar, jxpar, xstartpar_remember, kxpar, name, array)\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"ADD_TO_RESTART:  nf90_close\")\n\n  end subroutine add_to_restart_3d\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine read_restart(restart_flnm, ucmcall, iz0tlnd, sfcdif_option,   &\n       parallel_xstart, parallel_xend, subwindow_xstart, ix, jx, nsoil,    &\n       olddate)\n\n    ! The restart file is dimensioned by our (possibly subwindowed) grid.  Our indices\n    ! for the parallel I/O reflect the dimensions of the (possibly subwindowed) grid, \n    ! but not the full domain for which LDAS input files may be available.\n\n    implicit none\n\n    character(len=*),             intent(in)  :: restart_flnm\n    integer,                      intent(in)  :: ucmcall\n    integer,                      intent(in)  :: iz0tlnd\n    integer,                      intent(in)  :: sfcdif_option\n    integer,                      intent(in)  :: parallel_xstart\n    integer,                      intent(in)  :: parallel_xend\n    integer,                      intent(in)  :: subwindow_xstart\n    integer,                      intent(in)  :: ix\n    integer,                      intent(in)  :: jx\n    integer,                      intent(in)  :: nsoil\n    character(len=19),            intent(out) :: olddate\n\n    integer :: ierr\n    integer :: ncid\n    integer :: varid\n    character(len=256) :: titlestr\n    integer :: restart_version\n    integer :: idx\n    integer, dimension(4) :: nstart\n    integer, dimension(4) :: ncount\n    integer :: rank\n    integer :: read_iz0tlnd\n    integer :: read_sfcdif\n    integer :: read_ucmcall\n\n    restart_filename_remember = restart_flnm\n\n#ifdef _PARALLEL_\n    call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n\n    ierr = nf90_open_par(trim(restart_flnm), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    rank = 0\n    ierr = nf90_open(trim(restart_flnm), NF90_NOWRITE, ncid)\n#endif\n\n    if (ierr == NF90_ENOTNC) then\n       print*, \"IERR = NF90_ENOTNC\"\n\n    else\n       if (ierr /= NF90_NOERR) then\n          write(*,*)\n          write(*,'(\" ***** Restart problem ***************************************\")')\n          write(*,'(\" ***** \")')\n          write(*,'(\" *****        There was a problem in accessing the file ''\", A, \"''\")') trim(restart_flnm)\n          write(*,'(\" ***** \")')\n       endif\n       call error_handler(ierr, \" trying to open restart file \"//restart_flnm)\n\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TITLE\", titlestr)\n       if (ierr /= 0) then\n          write(*,'(\"WARNING:  RESTART file does not have TITLE attribute.\")')\n          write(*,'(\"          This probably means that LDASIN files are from an older release,\")')\n          write(*,'(\"          And are very likely incompatible with the current code.\")')\n          write(*,'(\"          I assume you know what you are doing.\")')\n          restart_version = 0\n       else\n          if (rank == 0) write(*,'(\"RESTART TITLE attribute: \", A)') trim(titlestr)\n          ! Pull out the version number, assuming that the version is identified by vYYYYMMDD, and \n          ! based on a search for the string \"v20\".\n          idx = index(trim(titlestr), \"v20\")\n          if (idx <= 0) then\n             write(*,'(\"FATAL:  RESTART file has a perverse version identifier\")')\n             !  write(*,'(\"          I assume you know what you are doing.\")')\n             stop\n          else\n             read(titlestr(idx+1:), '(I8)', iostat=ierr) restart_version\n             if (ierr /= 0) then\n                write(*,'(\"FATAL:  RESTART file has a perverse version identifier\")')\n                !  write(*,'(\"          I assume you know what you are doing.\")')\n                stop\n             endif\n          endif\n       endif\n       if (rank == 0) write(*, '(\"ldasin_version = \", I8)') restart_version\n\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"IZ0TLND\", read_iz0tlnd)\n       call error_handler(ierr, \"Problem getting IZ0TLND as attribute of restart file\")\n\n       if (read_iz0tlnd /= iz0tlnd) then\n          if (rank == 0) then\n             write(*,'(/)')\n             write(*,'(\" ***** Restart problem ***************************************\")')\n             write(*,'(\" ***** Do not change namelist option IZ0TLND on restart.\")')\n             write(*,'(\" *****     IZ0TLND in restart  file is \", I1)') read_iz0tlnd\n             write(*,'(\" *****     IZ0TLND in namelist file is \", I1)') iz0tlnd\n             write(*,'(\" ***** Correct the namelist file and resubmit.\")')\n             write(*,'(/)')\n          endif\n#ifdef _PARALLEL_\n          call mpi_finalize(ierr)\n#endif\n          stop\n       endif\n\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"SFCDIF_OPTION\", read_sfcdif)\n       call error_handler(ierr, \"Problem getting SFCDIF_OPTION as attribute of restart file\")\n       if (read_sfcdif /= sfcdif_option) then\n          if (rank == 0) then\n             write(*,'(/)')\n             write(*,'(\" ***** Restart problem ***************************************\")')\n             write(*,'(\" ***** Do not change namelist option SFCDIF_OPTION on restart.\")')\n             write(*,'(\" *****     SFCDIF_OPTION in restart  file is \", I1)') read_sfcdif\n             write(*,'(\" *****     SFCDIF_OPTION in namelist file is \", I1)') sfcdif_option\n             write(*,'(\" ***** Correct the namelist file and resubmit.\")')\n             write(*,'(/)')\n          endif\n#ifdef _PARALLEL_\n          call mpi_finalize(ierr)\n#endif\n          stop\n       endif\n\n#ifdef _HRLDAS_URBAN_\n\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"UCMCALL\", read_ucmcall)\n       call error_handler(ierr, \"Problem getting UCMCALL as attribute of restart file\")\n       if (read_ucmcall /= ucmcall) then\n          if (rank == 0) then\n             write(*,'(/)')\n             write(*,'(\" ***** Restart problem ***************************************\")')\n             write(*,'(\" ***** Do not change namelist option UCMCALL on restart.\")')\n             write(*,'(\" *****     UCMCALL in restart  file is \", I1)') read_ucmcall\n             write(*,'(\" *****     UCMCALL in namelist file is \", I1)') ucmcall\n             write(*,'(\" ***** Correct the namelist file and resubmit.\")')\n             write(*,'(/)')\n          endif\n#ifdef _PARALLEL_\n          call mpi_finalize(ierr)\n#endif\n          stop\n       endif\n\n#endif\n\n! Older RESTART files are incompatible if you use the Urban Canopy Model.\n#if defined _HRLDAS_URBAN_\n       if (ucmcall == 1) then\n          if (restart_version < 20070712) then\n             write(*,'(/,\"  *****************************************************************************  \")')\n             write(*,'(\"  *****  You are using a restart file created prior to version v20070712.\")')\n             write(*,'(\"  *****  That version of restart files has problems with Urban Canopy Model.\")')\n             write(*,'(\"  *****  Update your code and use newer restart files.\")')\n             write(*,'(\"  *****************************************************************************  \",/)')\n             stop\n          endif\n       endif\n#endif\n\n       ! Get the time stamp from the restart file.\n       ierr = nf90_inq_varid(ncid, \"Times\", varid)\n       call error_handler(ierr, \"Problem finding variable in restart file: 'Times'\")\n\n       ierr = nf90_get_var(ncid, varid, olddate)\n       call error_handler(ierr, \"Problem finding variable in restart file: 'Times'\")\n\n       ierr = nf90_close(ncid)\n       call error_handler(ierr, \"Problem closing restart file\")\n    endif\n\n  end subroutine read_restart\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine get_from_restart_2d_float(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                            intent(in) :: parallel_xstart\n    integer,                            intent(in) :: parallel_xend\n    integer,                            intent(in) :: subwindow_xstart\n    integer,                            intent(in) :: ixfull\n    integer,                            intent(in) :: jxfull\n    character(len=*),                   intent(in)  :: name\n    real,             dimension(parallel_xstart:parallel_xend,jxfull), intent(out) :: array\n    integer,          optional,         intent(out) :: return_error\n\n    integer :: ierr\n    integer :: ncid\n    integer :: varid\n    integer, dimension(4) :: nstart\n    integer, dimension(4) :: ncount\n    integer :: rank\n\n#ifdef _PARALLEL_\n\n    call MPI_COMM_RANK(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"MPI_COMM_RANK\"\n\n    ierr = nf90_open_par(trim(restart_filename_remember), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n\n#else\n    rank = 0\n\n    ierr = nf90_open(trim(restart_filename_remember), NF90_NOWRITE, ncid)\n\n#endif\n    call error_handler(ierr, \"GET_FROM_RESTART: Problem opening restart file '\"//trim(restart_filename_remember)//\"'\")\n\n    nstart = (/ parallel_xstart-subwindow_xstart+1, 1,  1, -99999 /)\n    ncount = (/ parallel_xend-parallel_xstart+1,   jxfull,  1, -99999 /)\n\n    if (present(return_error)) then\n       ierr = nf90_inq_varid(ncid, name, varid)\n       if (ierr == NF90_NOERR) then\n          return_error = 0\n          call error_handler(ierr, \"Problem finding variable in restart file '\"//trim(name)//\"'\")\n\n          ierr = nf90_get_var(ncid, varid, array, start=nstart(1:3))\n          call error_handler(ierr, \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n       else\n          return_error = 1\n          if (rank == 0) write(*,'(\"Did not find optional variable ''\",A,\"'' in restart file ''\", A, \"''\")') trim(name), trim(restart_filename_remember)\n       endif\n    else\n       ierr = nf90_inq_varid(ncid, name, varid)\n       call error_handler(ierr, \"Problem finding required variable in restart file: '\"//trim(name)//\"'\")\n\n       ierr = nf90_get_var(ncid, varid, array, start=nstart(1:3))\n       call error_handler(ierr, \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n    endif\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"Problem closing restart file\")\n\n  end subroutine get_from_restart_2d_float\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine get_from_restart_2d_integer(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                                                           intent(in) :: parallel_xstart\n    integer,                                                           intent(in) :: parallel_xend\n    integer,                                                           intent(in) :: subwindow_xstart\n    integer,                                                           intent(in) :: ixfull\n    integer,                                                           intent(in) :: jxfull\n    character(len=*),                                                  intent(in)  :: name\n    integer,          dimension(parallel_xstart:parallel_xend,jxfull), intent(out) :: array\n    integer,          optional,                                        intent(out) :: return_error\n\n    integer :: ierr\n    integer :: ncid\n    integer :: varid\n    integer, dimension(4) :: nstart\n    integer, dimension(4) :: ncount\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(restart_filename_remember), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(restart_filename_remember), NF90_NOWRITE, ncid)\n#endif\n    call error_handler(ierr, \"GET_FROM_RESTART: Problem opening restart file '\"//trim(restart_filename_remember)//\"'\")\n\n    nstart = (/ parallel_xstart-subwindow_xstart+1, 1,  1, -99999 /)\n    ncount = (/ parallel_xend-parallel_xstart+1,   jxfull,  1, -99999 /)\n\n    if (present(return_error)) then\n       ierr = nf90_inq_varid(ncid, name, varid)\n       if (ierr == NF90_NOERR) then\n          return_error = 0\n          call error_handler(ierr, \"Problem finding variable in restart file '\"//trim(name)//\"'\")\n\n          ierr = nf90_get_var(ncid, varid, array, start=nstart(1:3))\n          call error_handler(ierr, \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n       else\n          return_error = 1\n          write(*,'(\"Did not find optional variable ''\",A,\"'' in restart file ''\", A, \"''\")') trim(name), trim(restart_filename_remember)\n       endif\n    else\n       ierr = nf90_inq_varid(ncid, name, varid)\n       call error_handler(ierr, \"Problem finding required variable in restart file: '\"//trim(name)//\"'\")\n\n       ierr = nf90_get_var(ncid, varid, array, start=nstart(1:3))\n       call error_handler(ierr, \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n    endif\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"Problem closing restart file\")\n\n  end subroutine get_from_restart_2d_integer\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine get_from_restart_3d(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                            intent(in) :: parallel_xstart\n    integer,                            intent(in) :: parallel_xend\n    integer,                            intent(in) :: subwindow_xstart\n    integer,                            intent(in) :: ixfull\n    integer,                            intent(in) :: jxfull\n    character(len=*),                   intent(in)  :: name\n    real,             dimension(:,:,:), intent(out) :: array\n    integer,          optional,         intent(out) :: return_error\n\n    integer :: ierr\n    integer :: ncid\n    integer :: varid\n    integer, dimension(4) :: nstart\n    integer, dimension(4) :: ncount\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(restart_filename_remember), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(restart_filename_remember), NF90_NOWRITE, ncid)\n#endif\n    call error_handler(ierr, \"GET_FROM_RESTART: Problem opening restart file '\"//trim(restart_filename_remember)//\"'\")\n\n    nstart = (/parallel_xstart-subwindow_xstart+1,1, 1, 1/)\n    ncount = (/parallel_xend-parallel_xstart+1, size(array,2), size(array,3), 1/)\n\n    if (present(return_error)) then\n       ierr = nf90_inq_varid(ncid, name, varid)\n       if (ierr == NF90_NOERR) then\n          return_error = 0\n          call error_handler(ierr, \"Problem finding variable in restart file '\"//trim(name)//\"'\")\n\n          ierr = nf90_get_var(ncid, varid, array, start=nstart(1:4))\n          call error_handler(ierr, \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n       else\n          return_error = 1\n          write(*,'(\"Did not find optional variable ''\",A,\"'' in restart file ''\", A, \"''\")') trim(name), trim(restart_filename_remember)\n       endif\n    else\n       ierr = nf90_inq_varid(ncid, name, varid)\n       call error_handler(ierr, \"Problem finding required variable in restart file: '\"//trim(name)//\"'\")\n\n       ierr = nf90_get_var(ncid, varid, array, start=nstart(1:4))\n       call error_handler(ierr, \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n    endif\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"Problem closing restart file\")\n\n  end subroutine get_from_restart_3d\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine error_handler(status, failure, success)\n    !\n    ! Check the error flag from a NetCDF function call, and print appropriate\n    ! error message.\n    !\n    implicit none\n    integer,                    intent(in) :: status\n    character(len=*), optional, intent(in) :: failure\n    character(len=*), optional, intent(in) :: success\n\n    if (status .ne. NF90_NOERR) then\n       write(*,'(/,A)') nf90_strerror(status)\n       if (present(failure)) then\n          write(*,'(/,\" ***** \", A,/)') failure\n       endif\n       stop 'Stopped'\n    endif\n\n    if (present(success)) then\n       write(*,'(A)') success\n    endif\n\n  end subroutine error_handler\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine read_additional(flnm_template, hdate, name, xstart, xend, ystart, yend, array, ierr)\n    use kwm_string_utilities\n    implicit none\n    character(len=*),                         intent(in)  :: flnm_template\n    character(len=*),                         intent(in)  :: hdate\n    character(len=*),                         intent(in)  :: name\n    integer,                                  intent(in)  :: xstart\n    integer,                                  intent(in)  :: xend\n    integer,                                  intent(in)  :: ystart\n    integer,                                  intent(in)  :: yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    integer,                                  intent(out) :: ierr\n\n    character(len=256) :: flnm\n    integer :: jday\n    character(len=3) :: hjday\n    integer :: ncid\n    integer :: varid\n    logical :: lexist\n\n    call geth_idts(hdate(1:10), hdate(1:4)//\"-01-01\", jday)\n    jday = jday + 1\n    write(hjday,'(I3.3)') jday\n\n    flnm = flnm_template\n\n    call strrep(flnm, \"<YYYY>\", hdate(1:4))\n    call strrep(flnm, \"<MM>\", hdate(6:7))\n    call strrep(flnm, \"<DD>\", hdate(9:10))\n    call strrep(flnm, \"<HH>\", hdate(12:13))\n    call strrep(flnm, \"<JDAY>\", hjday)\n\n    inquire(file=trim(flnm), exist=lexist)\n    if (.not. lexist) then\n       ierr = 1\n       return\n    endif\n\n    write(*, '(\"Additional flnm = ''\",A,\"''\")') trim(flnm)\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(flnm), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(flnm), NF90_NOWRITE, ncid)\n#endif\n    call error_handler(ierr, failure=\"READ_ADDITIONAL: Problem opening additional file: \"//trim(flnm))\n\n    ierr = nf90_inq_varid(ncid,  name,  varid)\n    call error_handler(ierr, failure=\"READ_ADDITIONAL: Problem finding variable: \"//name)\n\n    ierr = nf90_get_var(ncid, varid, array, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n    call error_handler(ierr, failure=\"READ_ADDITIONAL: Problem getting variable: \"//name)\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, failure=\"READ_ADDITIONAL:  Problem closing file:  \"//trim(flnm))\n\n  end subroutine read_additional\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n end module module_hrldas_netcdf_io\n"
  },
  {
    "path": "src/Land_models/Noah/Makefile",
    "content": "\nall: user_build_options\n\t(cd Utility_routines;\t\tmake)\n\t(cd Noah;\t\t\tmake)\n\t(cd IO_code;\t\t\tmake)\n\t(cd Run;\t\t\tmake -f Makefile)\n#\t(cd HRLDAS_COLLECT_DATA;\tmake)\n\nclean:\n\t(cd Utility_routines;\t\tmake clean)\n\t(cd Noah;\t\t\tmake clean)\n\t(cd IO_code;\t\t\tmake clean)\n\t(cd Run;\t\t\tmake -f Makefile clean)\n\t(cd HRLDAS_COLLECT_DATA;\tmake clean)\n\ntest: all\n\t(cd TEST; ../HRLDAS_COLLECT_DATA/consolidate_grib.exe )\n\t(cd TEST; ../Run/Noah_hrldas_beta )\n\n#all: check user_build_options\n#\t(cd Utility_routines;\tmake)\n#\t(cd Noah;\t\tmake)\n#\t(cd IO_code;\t\tmake)\n#\t(cd Run;\t\tmake)\n#\n#clean:\n#\t(cd Utility_routines;\tmake clean)\n#\t(cd Noah;\t\tmake clean)\n#\t(cd IO_code;\t\tmake clean)\n#\t(cd Run;\t\tmake clean)\n#\n#include user_build_options\n#\n#check:\n#ifeq ($(COMPILERF90),)\n#\t@ echo \"\"\n#\t@ echo \"*************************************************************\"\n#\t@ echo \"*************************************************************\"\n#\t@ echo \"*****                                                   *****\"\n#\t@ echo \"***** Did you set options in file 'user_build_options'? *****\"\n#\t@ echo \"*****                                                   *****\"\n#\t@ echo \"*************************************************************\"\n#\t@ echo \"*************************************************************\"\n#\t@ echo \"\"\n#\t@ exit 1\n#endif\n\n"
  },
  {
    "path": "src/Land_models/Noah/Noah/CMakeLists.txt",
    "content": "add_library(noah STATIC\n        module_sf_urban.F\n        module_sf_noahlsm.F\n)\n"
  },
  {
    "path": "src/Land_models/Noah/Noah/Makefile",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\ninclude ../user_build_options\n\nOBJS = \\\n\tmodule_sf_noahlsm.o \\\n\tmodule_sf_urban.o\n\nCPPHRLDAS = -D_HRLDAS_OFFLINE_\n\nall:\t$(OBJS)\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c $(MODFLAG). $(MODFLAG)../Utility_routines $(F90FLAGS) $(FREESOURCE) $(*).F\n\t@echo \"\"\n\n#\n# Dependencies:\n#\nmodule_sf_noahlsm.o:\tmodule_sf_urban.o\n\n#\n# This command cleans up object (etc) files:\n#\n\nclean:\n\t$(RM) *.o *.mod *.stb *~\n\n"
  },
  {
    "path": "src/Land_models/Noah/Noah/module_sf_noahlsm.F",
    "content": "MODULE module_sf_noahlsm\n  USE module_model_constants\n\n!   REAL, PARAMETER    :: CP = 1004.5\n  REAL, PARAMETER      :: RD = 287.04, SIGMA = 5.67E-8,                 &\n                          CPH2O = 4.218E+3,CPICE = 2.106E+3,            &\n                          LSUBF = 3.335E+5,                             &\n                          EMISSI_S = 0.95\n\n! VEGETATION PARAMETERS\n        INTEGER :: LUCATS , BARE\n        INTEGER :: NATURAL\n        integer, PARAMETER :: NLUS=50\n        CHARACTER(LEN=256) LUTYPE\n        INTEGER, DIMENSION(1:NLUS) :: NROTBL\n        real, dimension(1:NLUS) ::  SNUPTBL, RSTBL, RGLTBL, HSTBL,                &\n                                    SHDTBL, MAXALB,                               &\n                                    EMISSMINTBL, EMISSMAXTBL,                     &\n                                    LAIMINTBL, LAIMAXTBL,                         &\n                                    Z0MINTBL, Z0MAXTBL,                           &\n                                    ALBEDOMINTBL, ALBEDOMAXTBL\n        REAL ::   TOPT_DATA,CMCMAX_DATA,CFACTR_DATA,RSMAX_DATA\n\n! SOIL PARAMETERS\n        INTEGER :: SLCATS\n        INTEGER, PARAMETER :: NSLTYPE=30\n        CHARACTER(LEN=256) SLTYPE\n        REAL, DIMENSION (1:NSLTYPE) :: BB,DRYSMC,F11,                           &\n        MAXSMC, REFSMC,SATPSI,SATDK,SATDW, WLTSMC,QTZ\n\n! LSM GENERAL PARAMETERS\n        INTEGER :: SLPCATS\n        INTEGER, PARAMETER :: NSLOPE=30\n        REAL, DIMENSION (1:NSLOPE) :: SLOPE_DATA\n        REAL ::  SBETA_DATA,FXEXP_DATA,CSOIL_DATA,SALP_DATA,REFDK_DATA,           &\n                 REFKDT_DATA,FRZK_DATA,ZBOT_DATA,  SMLOW_DATA,SMHIGH_DATA,        &\n                        CZIL_DATA\n        REAL ::  LVCOEF_DATA\n\n        CHARACTER*256  :: err_message\n\n#ifdef _HRLDAS_OFFLINE_\n        integer, parameter :: nsold = 100\n        integer :: ISURBAN\n        ! To pass a few arguments to SFLX that used to come from REDPRM:\n        real :: offline_cfactr\n        real :: offline_cmcmax\n        real :: offline_rsmax\n        real :: offline_topt\n        real :: offline_refkdt\n        real :: offline_kdt\n        real :: offline_sbeta\n        real :: offline_rsmin\n        real :: offline_rgl\n        real :: offline_hs\n        real :: offline_zbot\n        real :: offline_frzx\n        real :: offline_psisat\n        real :: offline_slope\n        real :: offline_snup\n        real :: offline_salp\n        real :: offline_bexp\n        real :: offline_dksat\n        real :: offline_dwsat\n        real :: offline_smcmax\n        real :: offline_smcwlt\n        real :: offline_smcref\n        real :: offline_smcdry\n        real :: offline_quartz\n        real :: offline_f1\n        real :: offline_fxexp\n        real, dimension(1:nsold) :: offline_rtdis\n        integer :: offline_nroot\n        real :: offline_czil\n        real :: offline_csoil\n        real :: offline_ptu\n        real :: offline_lvcoef\n#endif\n\n\n\n!\nCONTAINS\n!\n\n      SUBROUTINE SFLX (FFROZP,ICE,ISURBAN,DT,ZLVL,NSOIL,SLDPTH,         &    !C\n                       LOCAL,                                           &    !L\n                       LLANDUSE, LSOIL,                                 &    !CL\n                       LWDN,SOLDN,SOLNET,SFCPRS,PRCP,SFCTMP,Q2,SFCSPD,  &    !F\n                       COSZ,PRCPRAIN, SOLARDIRECT,                      &    !F\n                       TH2,Q2SAT,DQSDT2,                                &    !I\n                       VEGTYP,SOILTYP,SLOPETYP,SHDFAC,SHDMIN,SHDMAX,    &    !I\n                       ALB, SNOALB,TBOT, Z0BRD, Z0, EMISSI, EMBRD,      &    !S\n                       CMC,T1,STC,SMC,SH2O,SNOWH,SNEQV,ALBEDO,CH,CM,    &    !H\n! ----------------------------------------------------------------------\n! OUTPUTS, DIAGNOSTICS, PARAMETERS BELOW GENERALLY NOT NECESSARY WHEN\n! COUPLED WITH E.G. A NWP MODEL (SUCH AS THE NOAA/NWS/NCEP MESOSCALE ETA\n! MODEL).  OTHER APPLICATIONS MAY REQUIRE DIFFERENT OUTPUT VARIABLES.\n! ----------------------------------------------------------------------\n                       ETA,SHEAT, ETA_KINEMATIC,FDOWN,                  &    !O\n                       EC,EDIR,ET,ETT,ESNOW,DRIP,DEW,                   &    !O\n                       BETA,ETP,SSOIL,                                  &    !O\n                       FLX1,FLX2,FLX3,                                  &    !O\n                       SNOMLT,SNCOVR,                                   &    !O\n                       RUNOFF1,RUNOFF2,RUNOFF3,                         &    !O\n                       RC,PC,RSMIN,XLAI,RCS,RCT,RCQ,RCSOIL,             &    !O\n                       SOILW,SOILM,Q1,SMAV,                             &    !D\n                       RDLAI2D,USEMONALB,                               &\n                       SNOTIME1,                                        &\n                       RIBB,                                            &\n                       SMCWLT,SMCDRY,SMCREF,SMCMAX,NROOT,   &\n                       SFHEAD1RT,                                       &    !I\n                       INFXS1RT,ETPND1,                                 &\n\t\t       gwsoilcpl, qlowbdry)                    !P\n! ----------------------------------------------------------------------\n! SUBROUTINE SFLX - UNIFIED NOAHLSM VERSION 1.0 JULY 2007\n! ----------------------------------------------------------------------\n! SUB-DRIVER FOR \"Noah LSM\" FAMILY OF PHYSICS SUBROUTINES FOR A\n! SOIL/VEG/SNOWPACK LAND-SURFACE MODEL TO UPDATE SOIL MOISTURE, SOIL\n! ICE, SOIL TEMPERATURE, SKIN TEMPERATURE, SNOWPACK WATER CONTENT,\n! SNOWDEPTH, AND ALL TERMS OF THE SURFACE ENERGY BALANCE AND SURFACE\n! WATER BALANCE (EXCLUDING INPUT ATMOSPHERIC FORCINGS OF DOWNWARD\n! RADIATION AND PRECIP)\n! ----------------------------------------------------------------------\n! SFLX ARGUMENT LIST KEY:\n! ----------------------------------------------------------------------\n!  C  CONFIGURATION INFORMATION\n!  L  LOGICAL\n! CL  4-string character bearing logical meaning\n!  F  FORCING DATA\n!  I  OTHER (INPUT) FORCING DATA\n!  S  SURFACE CHARACTERISTICS\n!  H  HISTORY (STATE) VARIABLES\n!  O  OUTPUT VARIABLES\n!  D  DIAGNOSTIC OUTPUT\n!  P  Parameters\n!  Msic Miscellaneous terms passed from gridded driver\n! ----------------------------------------------------------------------\n! 1. CONFIGURATION INFORMATION (C):\n! ----------------------------------------------------------------------\n!   ICE        SEA-ICE FLAG  (=1: SEA-ICE, =0: LAND (NO ICE), --1 LAND-ICE).\n!   DT         TIMESTEP (SEC) (DT SHOULD NOT EXCEED 3600 SECS, RECOMMEND\n!                1800 SECS OR LESS)\n!   ZLVL       HEIGHT (M) ABOVE GROUND OF ATMOSPHERIC FORCING VARIABLES\n!   NSOIL      NUMBER OF SOIL LAYERS (AT LEAST 2, AND NOT GREATER THAN\n!                PARAMETER NSOLD SET BELOW)\n!   SLDPTH     THE THICKNESS OF EACH SOIL LAYER (M)\n! ----------------------------------------------------------------------\n! 2. LOGICAL:\n! ----------------------------------------------------------------------\n!   LCH       Exchange coefficient (Ch) calculation flag (false: using\n!                ch-routine SFCDIF; true: Ch is brought in)\n!   LOCAL      Flag for local-site simulation (where there is no\n!              maps for albedo, veg fraction, and roughness\n!             true:  all LSM parameters (inluding albedo, veg fraction and\n!                    roughness length) will be defined by three tables\n!   LLANDUSE  (=USGS, using USGS landuse classification)\n!   LSOIL     (=STAS, using FAO/STATSGO soil texture classification)\n! ----------------------------------------------------------------------\n! 3. FORCING DATA (F):\n! ----------------------------------------------------------------------\n!   LWDN       LW DOWNWARD RADIATION (W M-2; POSITIVE, NOT NET LONGWAVE)\n!   SOLDN      SOLAR DOWNWARD RADIATION (W M-2; POSITIVE, NOT NET SOLAR)\n!   SOLNET     NET DOWNWARD SOLAR RADIATION ((W M-2; POSITIVE)\n!   SFCPRS     PRESSURE AT HEIGHT ZLVL ABOVE GROUND (PASCALS)\n!   PRCP       PRECIP RATE (KG M-2 S-1) (NOTE, THIS IS A RATE)\n!   SFCTMP     AIR TEMPERATURE (K) AT HEIGHT ZLVL ABOVE GROUND\n!   TH2        AIR POTENTIAL TEMPERATURE (K) AT HEIGHT ZLVL ABOVE GROUND\n!   Q2         MIXING RATIO AT HEIGHT ZLVL ABOVE GROUND (KG KG-1)\n!   COSZ       Solar zenith angle (not used for now)\n!   PRCPRAIN   Liquid-precipitation rate (KG M-2 S-1) (not used)\n! SOLARDIRECT  Direct component of downward solar radiation (W M-2) (not used)\n!   FFROZP     FRACTION OF FROZEN PRECIPITATION\n! ----------------------------------------------------------------------\n! 4. OTHER FORCING (INPUT) DATA (I):\n! ----------------------------------------------------------------------\n!   SFCSPD     WIND SPEED (M S-1) AT HEIGHT ZLVL ABOVE GROUND\n!   Q2SAT      SAT SPECIFIC HUMIDITY AT HEIGHT ZLVL ABOVE GROUND (KG KG-1)\n!   DQSDT2     SLOPE OF SAT SPECIFIC HUMIDITY CURVE AT T=SFCTMP\n!                (KG KG-1 K-1)\n! ----------------------------------------------------------------------\n! 5. CANOPY/SOIL CHARACTERISTICS (S):\n! ----------------------------------------------------------------------\n!   VEGTYP     VEGETATION TYPE (INTEGER INDEX)\n!   SOILTYP    SOIL TYPE (INTEGER INDEX)\n!   SLOPETYP   CLASS OF SFC SLOPE (INTEGER INDEX)\n!   SHDFAC     AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!                (FRACTION= 0.0-1.0)\n!   SHDMIN     MINIMUM AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!                (FRACTION= 0.0-1.0) <= SHDFAC\n!   PTU        PHOTO THERMAL UNIT (PLANT PHENOLOGY FOR ANNUALS/CROPS)\n!                (NOT YET USED, BUT PASSED TO REDPRM FOR FUTURE USE IN\n!                VEG PARMS)\n!   ALB        BACKROUND SNOW-FREE SURFACE ALBEDO (FRACTION), FOR JULIAN\n!                DAY OF YEAR (USUALLY FROM TEMPORAL INTERPOLATION OF\n!                MONTHLY MEAN VALUES' CALLING PROG MAY OR MAY NOT\n!                INCLUDE DIURNAL SUN ANGLE EFFECT)\n!   SNOALB     UPPER BOUND ON MAXIMUM ALBEDO OVER DEEP SNOW (E.G. FROM\n!                ROBINSON AND KUKLA, 1985, J. CLIM. & APPL. METEOR.)\n!   TBOT       BOTTOM SOIL TEMPERATURE (LOCAL YEARLY-MEAN SFC AIR\n!                TEMPERATURE)\n!   Z0BRD      Background fixed roughness length (M)\n!   Z0         Time varying roughness length (M) as function of snow depth\n!\n!   EMBRD      Background surface emissivity (between 0 and 1)\n!   EMISSI     Surface emissivity (between 0 and 1)\n! ----------------------------------------------------------------------\n! 6. HISTORY (STATE) VARIABLES (H):\n! ----------------------------------------------------------------------\n!  CMC         CANOPY MOISTURE CONTENT (M)\n!  T1          GROUND/CANOPY/SNOWPACK) EFFECTIVE SKIN TEMPERATURE (K)\n!  STC(NSOIL)  SOIL TEMP (K)\n!  SMC(NSOIL)  TOTAL SOIL MOISTURE CONTENT (VOLUMETRIC FRACTION)\n!  SH2O(NSOIL) UNFROZEN SOIL MOISTURE CONTENT (VOLUMETRIC FRACTION)\n!                NOTE: FROZEN SOIL MOISTURE = SMC - SH2O\n!  SNOWH       ACTUAL SNOW DEPTH (M)\n!  SNEQV       LIQUID WATER-EQUIVALENT SNOW DEPTH (M)\n!                NOTE: SNOW DENSITY = SNEQV/SNOWH\n!  ALBEDO      SURFACE ALBEDO INCLUDING SNOW EFFECT (UNITLESS FRACTION)\n!                =SNOW-FREE ALBEDO (ALB) WHEN SNEQV=0, OR\n!                =FCT(MSNOALB,ALB,VEGTYP,SHDFAC,SHDMIN) WHEN SNEQV>0\n!  CH          SURFACE EXCHANGE COEFFICIENT FOR HEAT AND MOISTURE\n!                (M S-1); NOTE: CH IS TECHNICALLY A CONDUCTANCE SINCE\n!                IT HAS BEEN MULTIPLIED BY WIND SPEED.\n!  CM          SURFACE EXCHANGE COEFFICIENT FOR MOMENTUM (M S-1); NOTE:\n!                CM IS TECHNICALLY A CONDUCTANCE SINCE IT HAS BEEN\n!                MULTIPLIED BY WIND SPEED.\n! ----------------------------------------------------------------------\n! 7. OUTPUT (O):\n! ----------------------------------------------------------------------\n! OUTPUT VARIABLES NECESSARY FOR A COUPLED NUMERICAL WEATHER PREDICTION\n! MODEL, E.G. NOAA/NWS/NCEP MESOSCALE ETA MODEL.  FOR THIS APPLICATION,\n! THE REMAINING OUTPUT/DIAGNOSTIC/PARAMETER BLOCKS BELOW ARE NOT\n! NECESSARY.  OTHER APPLICATIONS MAY REQUIRE DIFFERENT OUTPUT VARIABLES.\n!   ETA        ACTUAL LATENT HEAT FLUX (W m-2: NEGATIVE, IF UP FROM\n!              SURFACE)\n!  ETA_KINEMATIC atctual latent heat flux in Kg m-2 s-1\n!   SHEAT      SENSIBLE HEAT FLUX (W M-2: NEGATIVE, IF UPWARD FROM\n!              SURFACE)\n!   FDOWN      Radiation forcing at the surface (W m-2) = SOLDN*(1-alb)+LWDN\n! ----------------------------------------------------------------------\n!   EC         CANOPY WATER EVAPORATION (W m-2)\n!   EDIR       DIRECT SOIL EVAPORATION (W m-2)\n!   ET(NSOIL)  PLANT TRANSPIRATION FROM A PARTICULAR ROOT (SOIL) LAYER\n!                 (W m-2)\n!   ETT        TOTAL PLANT TRANSPIRATION (W m-2)\n!   ESNOW      SUBLIMATION FROM (OR DEPOSITION TO IF <0) SNOWPACK\n!                (W m-2)\n!   DRIP       THROUGH-FALL OF PRECIP AND/OR DEW IN EXCESS OF CANOPY\n!                WATER-HOLDING CAPACITY (M)\n!   DEW        DEWFALL (OR FROSTFALL FOR T<273.15) (M)\n! ----------------------------------------------------------------------\n!   BETA       RATIO OF ACTUAL/POTENTIAL EVAP (DIMENSIONLESS)\n!   ETP        POTENTIAL EVAPORATION (W m-2)\n!   SSOIL      SOIL HEAT FLUX (W M-2: NEGATIVE IF DOWNWARD FROM SURFACE)\n! ----------------------------------------------------------------------\n!   FLX1       PRECIP-SNOW SFC (W M-2)\n!   FLX2       FREEZING RAIN LATENT HEAT FLUX (W M-2)\n!   FLX3       PHASE-CHANGE HEAT FLUX FROM SNOWMELT (W M-2)\n! ----------------------------------------------------------------------\n!   SNOMLT     SNOW MELT (M) (WATER EQUIVALENT)\n!   SNCOVR     FRACTIONAL SNOW COVER (UNITLESS FRACTION, 0-1)\n! ----------------------------------------------------------------------\n!   RUNOFF1    SURFACE RUNOFF (M S-1), NOT INFILTRATING THE SURFACE\n!   RUNOFF2    SUBSURFACE RUNOFF (M S-1), DRAINAGE OUT BOTTOM OF LAST\n!                SOIL LAYER (BASEFLOW)\n!   RUNOFF3    NUMERICAL TRUNCTATION IN EXCESS OF POROSITY (SMCMAX)\n!                FOR A GIVEN SOIL LAYER AT THE END OF A TIME STEP (M S-1).\n! Note: the above RUNOFF2 is actually the sum of RUNOFF2 and RUNOFF3\n! ----------------------------------------------------------------------\n!   RC         CANOPY RESISTANCE (S M-1)\n!   PC         PLANT COEFFICIENT (UNITLESS FRACTION, 0-1) WHERE PC*ETP\n!                = ACTUAL TRANSP\n!   XLAI       LEAF AREA INDEX (DIMENSIONLESS)\n!   RSMIN      MINIMUM CANOPY RESISTANCE (S M-1)\n!   RCS        INCOMING SOLAR RC FACTOR (DIMENSIONLESS)\n!   RCT        AIR TEMPERATURE RC FACTOR (DIMENSIONLESS)\n!   RCQ        ATMOS VAPOR PRESSURE DEFICIT RC FACTOR (DIMENSIONLESS)\n!   RCSOIL     SOIL MOISTURE RC FACTOR (DIMENSIONLESS)\n! ----------------------------------------------------------------------\n! 8. DIAGNOSTIC OUTPUT (D):\n! ----------------------------------------------------------------------\n!   SOILW      AVAILABLE SOIL MOISTURE IN ROOT ZONE (UNITLESS FRACTION\n!              BETWEEN SMCWLT AND SMCMAX)\n!   SOILM      TOTAL SOIL COLUMN MOISTURE CONTENT (FROZEN+UNFROZEN) (M)\n!   Q1         Effective mixing ratio at surface (kg kg-1), used for\n!              diagnosing the mixing ratio at 2 meter for coupled model\n!   SMAV       Soil Moisture Availability for each layer, as a fraction\n!              between SMCWLT and SMCMAX.\n!  Documentation for SNOTIME1 and SNOABL2 ?????\n!  What categories of arguments do these variables fall into ????\n!  Documentation for RIBB ?????\n!  What category of argument does RIBB fall into ?????\n! ----------------------------------------------------------------------\n! 9. PARAMETERS (P):\n! ----------------------------------------------------------------------\n!   SMCWLT     WILTING POINT (VOLUMETRIC)\n!   SMCDRY     DRY SOIL MOISTURE THRESHOLD WHERE DIRECT EVAP FRM TOP\n!                LAYER ENDS (VOLUMETRIC)\n!   SMCREF     SOIL MOISTURE THRESHOLD WHERE TRANSPIRATION BEGINS TO\n!                STRESS (VOLUMETRIC)\n!   SMCMAX     POROSITY, I.E. SATURATED VALUE OF SOIL MOISTURE\n!                (VOLUMETRIC)\n!   NROOT      NUMBER OF ROOT LAYERS, A FUNCTION OF VEG TYPE, DETERMINED\n!              IN SUBROUTINE REDPRM.\n! ----------------------------------------------------------------------\n\n\n      IMPLICIT NONE\n! ----------------------------------------------------------------------\n\n! DECLARATIONS - LOGICAL AND CHARACTERS\n! ----------------------------------------------------------------------\n      LOGICAL, INTENT(IN)::  LOCAL\n      LOGICAL            ::  FRZGRA, SNOWNG\n      CHARACTER (LEN=256), INTENT(IN)::  LLANDUSE, LSOIL\n\n! ----------------------------------------------------------------------\n! 1. CONFIGURATION INFORMATION (C):\n! ----------------------------------------------------------------------\n      INTEGER,INTENT(IN) ::  ICE,NSOIL,SLOPETYP,SOILTYP,VEGTYP\n      INTEGER, INTENT(IN) :: ISURBAN\n      INTEGER,INTENT(OUT)::  NROOT\n      INTEGER  KZ, K, iout\n\n! ----------------------------------------------------------------------\n! 2. LOGICAL:\n! ----------------------------------------------------------------------\n      LOGICAL, INTENT(IN) :: RDLAI2D\n      LOGICAL, INTENT(IN) :: USEMONALB\n\n      REAL, INTENT(INOUT):: SFHEAD1RT,INFXS1RT, ETPND1\n\n      !BF gw soil coupling\n      real, intent(in)                       :: qlowbdry\n      integer, intent(in)                    :: gwsoilcpl\n      !BF end\n\n      REAL, INTENT(IN)   :: SHDMIN,SHDMAX,DT,DQSDT2,LWDN,PRCP,PRCPRAIN,     &\n                            Q2,Q2SAT,SFCPRS,SFCSPD,SFCTMP, SNOALB,          &\n                            SOLDN,SOLNET,TBOT,TH2,ZLVL,                            &\n                            FFROZP\n      REAL, INTENT(OUT)  :: EMBRD\n      REAL, INTENT(OUT)  :: ALBEDO\n      REAL, INTENT(INOUT):: COSZ, SOLARDIRECT,CH,CM,                        &\n                            CMC,SNEQV,SNCOVR,SNOWH,T1,XLAI,SHDFAC,Z0BRD,    &\n                            EMISSI, ALB\n      REAL, INTENT(INOUT):: SNOTIME1\n      REAL, INTENT(INOUT):: RIBB\n      REAL, DIMENSION(1:NSOIL), INTENT(IN) :: SLDPTH\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: ET\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: SMAV\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) ::  SH2O, SMC, STC\n      REAL,DIMENSION(1:NSOIL)::   RTDIS, ZSOIL\n\n      REAL,INTENT(OUT)   :: ETA_KINEMATIC,BETA,DEW,DRIP,EC,EDIR,ESNOW,ETA,  &\n                            ETP,FLX1,FLX2,FLX3,SHEAT,PC,RUNOFF1,RUNOFF2,    &\n                            RUNOFF3,RC,RSMIN,RCQ,RCS,RCSOIL,RCT,SSOIL,      &\n                            SMCDRY,SMCMAX,SMCREF,SMCWLT,SNOMLT, SOILM,      &\n                            SOILW,FDOWN,Q1\n      REAL :: BEXP,CFACTR,CMCMAX,CSOIL,CZIL,DF1,DF1H,DF1A,DKSAT,DWSAT,      &\n              DSOIL,DTOT,ETT,FRCSNO,FRCSOI,EPSCA,F1,FXEXP,FRZX,HS,          &\n              KDT,LVH2O,PRCP1,PSISAT,QUARTZ,R,RCH,REFKDT,RR,RGL,            &\n              RSMAX,                                                        &\n              RSNOW,SNDENS,SNCOND,SBETA,SN_NEW,SLOPE,SNUP,SALP,SOILWM,      &\n              SOILWW,T1V,T24,T2V,TH2V,TOPT,TFREEZ,TSNOW,ZBOT,Z0,PRCPF,      &\n              ETNS,PTU,LSUBS\n        REAL ::  LVCOEF\n      REAL :: INTERP_FRACTION\n      REAL :: LAIMIN,    LAIMAX\n      REAL :: ALBEDOMIN, ALBEDOMAX\n      REAL :: EMISSMIN,  EMISSMAX\n      REAL :: Z0MIN,     Z0MAX\n\n! ----------------------------------------------------------------------\n! DECLARATIONS - PARAMETERS\n! ----------------------------------------------------------------------\n      PARAMETER (TFREEZ = 273.15)\n      PARAMETER (LVH2O = 2.501E+6)\n      PARAMETER (LSUBS = 2.83E+6)\n      PARAMETER (R = 287.04)\n! ----------------------------------------------------------------------\n!   INITIALIZATION\n! ----------------------------------------------------------------------\n         RUNOFF1 = 0.0\n         RUNOFF2 = 0.0\n         RUNOFF3 = 0.0\n         SNOMLT = 0.0\n\n! ----------------------------------------------------------------------\n!  THE VARIABLE \"ICE\" IS A FLAG DENOTING SEA-ICE / LAND-ICE / ICE-FREE LAND\n!     SEA-ICE CASE,          ICE =  1\n!     NON-GLACIAL LAND,      ICE =  0\n!     GLACIAL-ICE LAND,      ICE = -1\n      IF (ICE /= 0) SHDFAC = 0.0\n! ----------------------------------------------------------------------\n! SEA-ICE LAYERS ARE EQUAL THICKNESS AND SUM TO 3 METERS\n! ----------------------------------------------------------------------\n         IF (ICE == 1) THEN\n            DO KZ = 1,NSOIL\n               ZSOIL (KZ) = -3.* FLOAT (KZ)/ FLOAT (NSOIL)\n            END DO\n\n! ----------------------------------------------------------------------\n! CALCULATE DEPTH (NEGATIVE) BELOW GROUND FROM TOP SKIN SFC TO BOTTOM OF\n!   EACH SOIL LAYER.  NOTE:  SIGN OF ZSOIL IS NEGATIVE (DENOTING BELOW\n!   GROUND)\n! ----------------------------------------------------------------------\n         ELSE\n            ZSOIL (1) = - SLDPTH (1)\n            DO KZ = 2,NSOIL\n               ZSOIL (KZ) = - SLDPTH (KZ) + ZSOIL (KZ -1)\n            END DO\n         END IF\n! ----------------------------------------------------------------------\n! NEXT IS CRUCIAL CALL TO SET THE LAND-SURFACE PARAMETERS, INCLUDING\n! SOIL-TYPE AND VEG-TYPE DEPENDENT PARAMETERS.\n! ----------------------------------------------------------------------\n         CALL REDPRM (VEGTYP,SOILTYP,SLOPETYP,CFACTR,CMCMAX,RSMAX,TOPT,   &\n                       REFKDT,KDT,SBETA, SHDFAC,RSMIN,RGL,HS,ZBOT,FRZX,    &\n                         PSISAT,SLOPE,SNUP,SALP,BEXP,DKSAT,DWSAT,          &\n                         SMCMAX,SMCWLT,SMCREF,SMCDRY,F1,QUARTZ,FXEXP,      &\n                         RTDIS,SLDPTH,ZSOIL,NROOT,NSOIL,CZIL,              &\n                         LAIMIN, LAIMAX, EMISSMIN, EMISSMAX, ALBEDOMIN,    &\n                         ALBEDOMAX, Z0MIN, Z0MAX, CSOIL, PTU, LLANDUSE,    &\n                         LSOIL,LOCAL,LVCOEF)\n\n!urban\n         IF(VEGTYP==ISURBAN)THEN\n              SHDFAC=0.05\n              RSMIN=400.0\n              SMCMAX = 0.45\n              SMCREF = 0.42\n              SMCWLT = 0.40\n              SMCDRY = 0.40\n         ENDIF\n\n         IF ( SHDFAC >= SHDMAX ) THEN\n            EMBRD = EMISSMAX\n            IF (.NOT. RDLAI2D) THEN\n               XLAI  = LAIMAX\n            ENDIF\n            IF (.NOT. USEMONALB) THEN\n               ALB   = ALBEDOMIN\n            ENDIF\n            Z0BRD = Z0MAX\n         ELSE IF ( SHDFAC <= SHDMIN ) THEN\n            EMBRD = EMISSMIN\n            IF(.NOT. RDLAI2D) THEN\n               XLAI  = LAIMIN\n            ENDIF\n            IF(.NOT. USEMONALB) then\n               ALB   = ALBEDOMAX\n            ENDIF\n            Z0BRD = Z0MIN\n         ELSE\n\n            IF ( SHDMAX > SHDMIN ) THEN\n\n               INTERP_FRACTION = ( SHDFAC - SHDMIN ) / ( SHDMAX - SHDMIN )\n               ! Bound INTERP_FRACTION between 0 and 1\n               INTERP_FRACTION = MIN ( INTERP_FRACTION, 1.0 )\n               INTERP_FRACTION = MAX ( INTERP_FRACTION, 0.0 )\n               ! Scale Emissivity and LAI between EMISSMIN and EMISSMAX by INTERP_FRACTION\n               EMBRD = ( ( 1.0 - INTERP_FRACTION ) * EMISSMIN  ) + ( INTERP_FRACTION * EMISSMAX  )\n               IF (.NOT. RDLAI2D) THEN\n                  XLAI  = ( ( 1.0 - INTERP_FRACTION ) * LAIMIN    ) + ( INTERP_FRACTION * LAIMAX    )\n               ENDIF\n               if (.not. USEMONALB) then\n                  ALB   = ( ( 1.0 - INTERP_FRACTION ) * ALBEDOMAX ) + ( INTERP_FRACTION * ALBEDOMIN )\n               endif\n               Z0BRD = ( ( 1.0 - INTERP_FRACTION ) * Z0MIN     ) + ( INTERP_FRACTION * Z0MAX     )\n\n            ELSE\n\n               EMBRD = 0.5 * EMISSMIN  + 0.5 * EMISSMAX\n               IF (.NOT. RDLAI2D) THEN\n                  XLAI  = 0.5 * LAIMIN    + 0.5 * LAIMAX\n               ENDIF\n               if (.not. USEMONALB) then\n                  ALB   = 0.5 * ALBEDOMIN + 0.5 * ALBEDOMAX\n               endif\n               Z0BRD = 0.5 * Z0MIN     + 0.5 * Z0MAX\n\n            ENDIF\n\n         ENDIF\n! ----------------------------------------------------------------------\n!  INITIALIZE PRECIPITATION LOGICALS.\n! ----------------------------------------------------------------------\n         SNOWNG = .FALSE.\n         FRZGRA = .FALSE.\n\n! ----------------------------------------------------------------------\n! OVER SEA-ICE OR GLACIAL-ICE, IF S.W.E. (SNEQV) BELOW THRESHOLD LOWER\n! BOUND (0.01 M FOR SEA-ICE, 0.10 M FOR GLACIAL-ICE), THEN SET AT LOWER\n! BOUND\n! ----------------------------------------------------------------------\n! IF SEA-ICE CASE, ASSIGN DEFAULT WATER-EQUIV SNOW ON TOP\n! ----------------------------------------------------------------------\n         IF (ICE == 1) THEN\n            ! Sea-ice case\n            IF ( SNEQV < 0.01 ) THEN\n               SNEQV = 0.01\n               SNOWH = 0.05\n            ENDIF\n         ELSE IF ( ICE == -1 ) THEN\n            ! Land-ice case\n            IF ( SNEQV < 0.10 ) THEN\n               SNEQV = 0.10\n               SNOWH = 0.50\n            ENDIF\n         END IF\n! ----------------------------------------------------------------------\n! FOR SEA-ICE AND GLACIAL-ICE CASES, SET SMC AND SH20 VALUES = 1.0\n! ----------------------------------------------------------------------\n         IF ( ICE /= 0 ) THEN\n            DO KZ = 1,NSOIL\n               SMC(KZ) = 1.0\n               SH2O(KZ) = 1.0\n            END DO\n         ENDIF\n! ----------------------------------------------------------------------\n! IF INPUT SNOWPACK IS NONZERO, THEN COMPUTE SNOW DENSITY \"SNDENS\" AND\n!   SNOW THERMAL CONDUCTIVITY \"SNCOND\" (NOTE THAT CSNOW IS A FUNCTION\n!   SUBROUTINE)\n! ----------------------------------------------------------------------\n         IF ( SNEQV <= 1.E-7 ) THEN ! safer IF\tkmh (2008/03/25)\n            SNEQV = 0.0\n            SNDENS = 0.0\n            SNOWH = 0.0\n            SNCOND = 1.0\n         ELSE\n            SNDENS = SNEQV / SNOWH\n            IF(SNDENS > 1.0) THEN\n             CALL wrf_error_fatal ( 'Physical snow depth is less than snow water equiv.' )\n            ENDIF\n            CALL CSNOW (SNCOND,SNDENS)\n         END IF\n! ----------------------------------------------------------------------\n! DETERMINE IF IT'S PRECIPITATING AND WHAT KIND OF PRECIP IT IS.\n! IF IT'S PRCPING AND THE AIR TEMP IS COLDER THAN 0 C, IT'S SNOWING!\n! IF IT'S PRCPING AND THE AIR TEMP IS WARMER THAN 0 C, BUT THE GRND\n! TEMP IS COLDER THAN 0 C, FREEZING RAIN IS PRESUMED TO BE FALLING.\n! ----------------------------------------------------------------------\n         IF (PRCP > 0.0) THEN\n! snow defined when fraction of frozen precip (FFROZP) > 0.5,\n! passed in from model microphysics.\n            IF (FFROZP .GT. 0.5) THEN\n               SNOWNG = .TRUE.\n            ELSE\n               IF (T1 <= TFREEZ) FRZGRA = .TRUE.\n            END IF\n         END IF\n! ----------------------------------------------------------------------\n! IF EITHER PRCP FLAG IS SET, DETERMINE NEW SNOWFALL (CONVERTING PRCP\n! RATE FROM KG M-2 S-1 TO A LIQUID EQUIV SNOW DEPTH IN METERS) AND ADD\n! IT TO THE EXISTING SNOWPACK.\n! NOTE THAT SINCE ALL PRECIP IS ADDED TO SNOWPACK, NO PRECIP INFILTRATES\n! INTO THE SOIL SO THAT PRCP1 IS SET TO ZERO.\n! ----------------------------------------------------------------------\n         IF ( (SNOWNG) .OR. (FRZGRA) ) THEN\n            SN_NEW = PRCP * DT * 0.001\n            SNEQV = SNEQV + SN_NEW\n            PRCPF = 0.0\n\n! ----------------------------------------------------------------------\n! UPDATE SNOW DENSITY BASED ON NEW SNOWFALL, USING OLD AND NEW SNOW.\n! UPDATE SNOW THERMAL CONDUCTIVITY\n! ----------------------------------------------------------------------\n            CALL SNOW_NEW (SFCTMP,SN_NEW,SNOWH,SNDENS)\n!\n! kmh 09/04/2006 set Snow Density at 0.2 g/cm**3\n! for \"cold permanent ice\" or new \"dry\" snow\n!\n           IF ( (ICE /= 0) .and. SNCOVR .GT. 0.99 ) THEN\n!  if soil temperature less than 268.15 K, treat as typical Antarctic/Greenland snow firn\n              IF ( STC(1) .LT. (TFREEZ - 5.) ) SNDENS = 0.2\n              IF ( SNOWNG .AND. (T1.LT.273.) .AND. (SFCTMP.LT.273.) ) SNDENS=0.2\n           ENDIF\n!\n            CALL CSNOW (SNCOND,SNDENS)\n\n! ----------------------------------------------------------------------\n! PRECIP IS LIQUID (RAIN), HENCE SAVE IN THE PRECIP VARIABLE THAT\n! LATER CAN WHOLELY OR PARTIALLY INFILTRATE THE SOIL (ALONG WITH\n! ANY CANOPY \"DRIP\" ADDED TO THIS LATER)\n! ----------------------------------------------------------------------\n         ELSE\n            PRCPF = PRCP\n         END IF\n! ----------------------------------------------------------------------\n! DETERMINE SNOWCOVER AND ALBEDO OVER LAND.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! IF SNOW DEPTH=0, SET SNOW FRACTION=0, ALBEDO=SNOW FREE ALBEDO.\n! ----------------------------------------------------------------------\n         IF (ICE == 0 .OR. ICE == -1) THEN\n            IF (SNEQV  == 0.0) THEN\n               SNCOVR = 0.0\n               ALBEDO = ALB\n               EMISSI = EMBRD\n            ELSE\n! ----------------------------------------------------------------------\n! DETERMINE SNOW FRACTIONAL COVERAGE.\n! DETERMINE SURFACE ALBEDO MODIFICATION DUE TO SNOWDEPTH STATE.\n! ----------------------------------------------------------------------\n              CALL SNFRAC (SNEQV,SNUP,SALP,SNOWH,SNCOVR)\n!   Don't limit snow cover fraction over permanent ice kmh 2008/03/25\n            if ( ICE == 0 ) then\n              SNCOVR = MIN(SNCOVR,0.98)\n            endif\n              CALL ALCALC (ALB,SNOALB,EMBRD,SHDFAC,SHDMIN,SNCOVR,T1,ALBEDO,EMISSI,   &\n                         DT,SNOWNG,SNOTIME1,LVCOEF)\n            END IF\n! ----------------------------------------------------------------------\n! SNOW COVER, ALBEDO OVER SEA-ICE, GLACIAL ICE\n! ----------------------------------------------------------------------\n         ELSE\n            SNCOVR = 1.0\n!\n! Albedo of sea ice\n!\n! This value should vary seasonally. 0.65 may be good for Arctic Ocean summer bare ice\n!   value could be as low as 0.4 for Arctic bare ice and melt pond combo (Perovich data)\n!   0.82 may be good for Arctic spring/fall sea ice (Perovich data)\n!   0.81 may be good for Antarctic sea ice (Wendler et al. December cruise data)\n!\n            ALBEDO = 0.80\n!\n            EMISSI = 0.98\n         END IF\n! ----------------------------------------------------------------------\n! THERMAL CONDUCTIVITY FOR SEA-ICE CASE, GLACIAL-ICE CASE\n! ----------------------------------------------------------------------\n         IF ( (ICE == 1) .or. (ICE == -1) ) THEN\n            DF1 = 2.2\n!\n! kmh 09/03/2006\n! kmh 03/25/2008  change SNCOVR threshold to 0.97\n!\n! only apply (small) DF1 conductivity for permanent land ice\n            IF ( (ICE == -1) ) THEN\n               IF (  SNCOVR .GT. 0.97 ) THEN\n                  DF1 = SNCOND\n               ENDIF\n            ENDIF\n!\n         ELSE\n! ----------------------------------------------------------------------\n! NEXT CALCULATE THE SUBSURFACE HEAT FLUX, WHICH FIRST REQUIRES\n! CALCULATION OF THE THERMAL DIFFUSIVITY.  TREATMENT OF THE\n! LATTER FOLLOWS THAT ON PAGES 148-149 FROM \"HEAT TRANSFER IN\n! COLD CLIMATES\", BY V. J. LUNARDINI (PUBLISHED IN 1981\n! BY VAN NOSTRAND REINHOLD CO.) I.E. TREATMENT OF TWO CONTIGUOUS\n! \"PLANE PARALLEL\" MEDIUMS (NAMELY HERE THE FIRST SOIL LAYER\n! AND THE SNOWPACK LAYER, IF ANY). THIS DIFFUSIVITY TREATMENT\n! BEHAVES WELL FOR BOTH ZERO AND NONZERO SNOWPACK, INCLUDING THE\n! LIMIT OF VERY THIN SNOWPACK.  THIS TREATMENT ALSO ELIMINATES\n! THE NEED TO IMPOSE AN ARBITRARY UPPER BOUND ON SUBSURFACE\n! HEAT FLUX WHEN THE SNOWPACK BECOMES EXTREMELY THIN.\n! ----------------------------------------------------------------------\n! FIRST CALCULATE THERMAL DIFFUSIVITY OF TOP SOIL LAYER, USING\n! BOTH THE FROZEN AND LIQUID SOIL MOISTURE, FOLLOWING THE\n! SOIL THERMAL DIFFUSIVITY FUNCTION OF PETERS-LIDARD ET AL.\n! (1998,JAS, VOL 55, 1209-1224), WHICH REQUIRES THE SPECIFYING\n! THE QUARTZ CONTENT OF THE GIVEN SOIL CLASS (SEE ROUTINE REDPRM)\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! NEXT ADD SUBSURFACE HEAT FLUX REDUCTION EFFECT FROM THE\n! OVERLYING GREEN CANOPY, ADAPTED FROM SECTION 2.1.2 OF\n! PETERS-LIDARD ET AL. (1997, JGR, VOL 102(D4))\n! ----------------------------------------------------------------------\n            CALL TDFCND (DF1,SMC (1),QUARTZ,SMCMAX,SH2O (1))\n\n!urban\n            IF ( VEGTYP == ISURBAN ) DF1=3.24\n\n            DF1 = DF1 * EXP (SBETA * SHDFAC)\n!\n! kmh 09/03/2006\n! kmh 03/25/2008  change SNCOVR threshold to 0.97\n!\n            IF (  SNCOVR .GT. 0.97 ) THEN\n               DF1 = SNCOND\n            ENDIF\n!\n! ----------------------------------------------------------------------\n! FINALLY \"PLANE PARALLEL\" SNOWPACK EFFECT FOLLOWING\n! V.J. LINARDINI REFERENCE CITED ABOVE. NOTE THAT DTOT IS\n! COMBINED DEPTH OF SNOWDEPTH AND THICKNESS OF FIRST SOIL LAYER\n! ----------------------------------------------------------------------\n         END IF\n\n         DSOIL = - (0.5 * ZSOIL (1))\n         IF (SNEQV == 0.) THEN\n            SSOIL = DF1 * (T1- STC (1) ) / DSOIL\n         ELSE\n            DTOT = SNOWH + DSOIL\n            FRCSNO = SNOWH / DTOT\n\n! 1. HARMONIC MEAN (SERIES FLOW)\n!        DF1 = (SNCOND*DF1)/(FRCSOI*SNCOND+FRCSNO*DF1)\n            FRCSOI = DSOIL / DTOT\n! 2. ARITHMETIC MEAN (PARALLEL FLOW)\n!        DF1 = FRCSNO*SNCOND + FRCSOI*DF1\n            DF1H = (SNCOND * DF1)/ (FRCSOI * SNCOND+ FRCSNO * DF1)\n\n! 3. GEOMETRIC MEAN (INTERMEDIATE BETWEEN HARMONIC AND ARITHMETIC MEAN)\n!        DF1 = (SNCOND**FRCSNO)*(DF1**FRCSOI)\n! weigh DF by snow fraction\n!        DF1 = DF1H*SNCOVR + DF1A*(1.0-SNCOVR)\n!        DF1 = DF1H*SNCOVR + DF1*(1.0-SNCOVR)\n            DF1A = FRCSNO * SNCOND+ FRCSOI * DF1\n\n! ----------------------------------------------------------------------\n! CALCULATE SUBSURFACE HEAT FLUX, SSOIL, FROM FINAL THERMAL DIFFUSIVITY\n! OF SURFACE MEDIUMS, DF1 ABOVE, AND SKIN TEMPERATURE AND TOP\n! MID-LAYER SOIL TEMPERATURE\n! ----------------------------------------------------------------------\n            DF1 = DF1A * SNCOVR + DF1* (1.0- SNCOVR)\n            IF ( ICE /= 0 ) then\n               !  kmh  12/15/2005  correct for too deep snow layer\n               !  kmh  09/03/2006  adjust DTOT\n               IF ( DTOT .GT. 2.*DSOIL ) then\n                  DTOT = 2.*DSOIL\n               ENDIF\n            ENDIF\n            SSOIL = DF1 * (T1- STC (1) ) / DTOT\n         END IF\n! ----------------------------------------------------------------------\n! DETERMINE SURFACE ROUGHNESS OVER SNOWPACK USING SNOW CONDITION FROM\n! THE PREVIOUS TIMESTEP.\n! ----------------------------------------------------------------------\n         IF (SNCOVR  > 0. ) THEN\n            CALL SNOWZ0 (SNCOVR,Z0,Z0BRD,SNOWH)\n         ELSE\n            Z0=Z0BRD\n         END IF\n! ----------------------------------------------------------------------\n! NEXT CALL ROUTINE SFCDIF TO CALCULATE THE SFC EXCHANGE COEF (CH) FOR\n! HEAT AND MOISTURE.\n\n! NOTE !!!\n! DO NOT CALL SFCDIF UNTIL AFTER ABOVE CALL TO REDPRM, IN CASE\n! ALTERNATIVE VALUES OF ROUGHNESS LENGTH (Z0) AND ZILINTINKEVICH COEF\n! (CZIL) ARE SET THERE VIA NAMELIST I/O.\n\n! NOTE !!!\n! ROUTINE SFCDIF RETURNS A CH THAT REPRESENTS THE WIND SPD TIMES THE\n! \"ORIGINAL\" NONDIMENSIONAL \"Ch\" TYPICAL IN LITERATURE.  HENCE THE CH\n! RETURNED FROM SFCDIF HAS UNITS OF M/S.  THE IMPORTANT COMPANION\n! COEFFICIENT OF CH, CARRIED HERE AS \"RCH\", IS THE CH FROM SFCDIF TIMES\n! AIR DENSITY AND PARAMETER \"CP\".  \"RCH\" IS COMPUTED IN \"CALL PENMAN\".\n! RCH RATHER THAN CH IS THE COEFF USUALLY INVOKED LATER IN EQNS.\n\n! NOTE !!!\n! ----------------------------------------------------------------------\n! SFCDIF ALSO RETURNS THE SURFACE EXCHANGE COEFFICIENT FOR MOMENTUM, CM,\n! ALSO KNOWN AS THE SURFACE DRAGE COEFFICIENT. Needed as a state variable\n! for iterative/implicit solution of CH in SFCDIF\n! ----------------------------------------------------------------------\n!        IF(.NOT.LCH) THEN\n!          T1V = T1 * (1.0+ 0.61 * Q2)\n!          TH2V = TH2 * (1.0+ 0.61 * Q2)\n!          CALL SFCDIF_off (ZLVL,Z0,T1V,TH2V,SFCSPD,CZIL,CM,CH)\n!        ENDIF\n\n! ----------------------------------------------------------------------\n! CALL PENMAN SUBROUTINE TO CALCULATE POTENTIAL EVAPORATION (ETP), AND\n! OTHER PARTIAL PRODUCTS AND SUMS SAVE IN COMMON/RITE FOR LATER\n! CALCULATIONS.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! CALCULATE TOTAL DOWNWARD RADIATION (SOLAR PLUS LONGWAVE) NEEDED IN\n! PENMAN EP SUBROUTINE THAT FOLLOWS\n! ----------------------------------------------------------------------\n!         FDOWN = SOLDN * (1.0- ALBEDO) + LWDN\n         FDOWN =  SOLNET + LWDN\n! ----------------------------------------------------------------------\n! CALC VIRTUAL TEMPS AND VIRTUAL POTENTIAL TEMPS NEEDED BY SUBROUTINES\n! PENMAN.\n         T2V = SFCTMP * (1.0+ 0.61 * Q2 )\n\n         iout=0\n         if(iout.eq.1) then\n         print*,'before penman'\n         print*,' SFCTMP',SFCTMP,'SFCPRS',SFCPRS,'CH',CH,'T2V',T2V,      &\n       'TH2',TH2,'PRCP',PRCP,'FDOWN',FDOWN,'T24',T24,'SSOIL',SSOIL,      &\n        'Q2',Q2,'Q2SAT',Q2SAT,'ETP',ETP,'RCH',RCH,                       &\n        'EPSCA',EPSCA,'RR',RR  ,'SNOWNG',SNOWNG,'FRZGRA',FRZGRA,           &\n        'DQSDT2',DQSDT2,'FLX2',FLX2,'SNOWH',SNOWH,'SNEQV',SNEQV,         &\n        ' DSOIL',DSOIL,' FRCSNO',FRCSNO,' SNCOVR',SNCOVR,' DTOT',DTOT,   &\n       ' ZSOIL (1)',ZSOIL(1),' DF1',DF1,'T1',T1,' STC1',STC(1),          &\n        'ALBEDO',ALBEDO,'SMC',SMC,'STC',STC,'SH2O',SH2O\n         endif\n\n         CALL PENMAN (SFCTMP,SFCPRS,CH,T2V,TH2,PRCP,FDOWN,T24,SSOIL,     &\n                       Q2,Q2SAT,ETP,RCH,EPSCA,RR,SNOWNG,FRZGRA,          &\n!\n! kmh 01/09/2007 add T1,ICE,SNCOVR to call\n!\n                         DQSDT2,FLX2,EMISSI,SNEQV,T1,ICE,SNCOVR)\n!\n! ----------------------------------------------------------------------\n! CALL CANRES TO CALCULATE THE CANOPY RESISTANCE AND CONVERT IT INTO PC\n! IF NONZERO GREENNESS FRACTION\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n!  FROZEN GROUND EXTENSION: TOTAL SOIL WATER \"SMC\" WAS REPLACED\n!  BY UNFROZEN SOIL WATER \"SH2O\" IN CALL TO CANRES BELOW\n! ----------------------------------------------------------------------\n         IF (SHDFAC > 0.) THEN\n            CALL CANRES (SOLDN,CH,SFCTMP,Q2,SFCPRS,SH2O,ZSOIL,NSOIL,     &\n                          SMCWLT,SMCREF,RSMIN,RC,PC,NROOT,Q2SAT,DQSDT2,  &\n                          TOPT,RSMAX,RGL,HS,XLAI,                        &\n                          RCS,RCT,RCQ,RCSOIL,EMISSI)\n         ELSE\n            RC = 0.0\n         END IF\n! ----------------------------------------------------------------------\n! NOW DECIDE MAJOR PATHWAY BRANCH TO TAKE DEPENDING ON WHETHER SNOWPACK\n! EXISTS OR NOT:\n! ----------------------------------------------------------------------\n         ESNOW = 0.0\n         IF (SNEQV  == 0.0) THEN\n            CALL NOPAC (ETP,ETA,PRCP,SMC,SMCMAX,SMCWLT,                  &\n                            SMCREF,SMCDRY,CMC,CMCMAX,NSOIL,DT,           &\n                            SHDFAC,                                      &\n                            SBETA,Q2,T1,SFCTMP,T24,TH2,FDOWN,F1,EMISSI,  &\n                            SSOIL,                                       &\n                            STC,EPSCA,BEXP,PC,RCH,RR,CFACTR,             &\n                            SH2O,SLOPE,KDT,FRZX,PSISAT,ZSOIL,            &\n                            DKSAT,DWSAT,TBOT,ZBOT,RUNOFF1,RUNOFF2,       &\n                            RUNOFF3,EDIR,EC,ET,ETT,NROOT,ICE,RTDIS,      &\n                            QUARTZ,FXEXP,CSOIL,                          &\n                            BETA,DRIP,DEW,FLX1,FLX3,VEGTYP,ISURBAN,      &\n                            SFHEAD1RT,INFXS1RT,ETPND1,                   &\n\t\t            gwsoilcpl, qlowbdry)\n            ETA_KINEMATIC = ETA\n         ELSE\n            CALL SNOPAC (ETP,ETA,PRCP,PRCPF,SNOWNG,SMC,SMCMAX,SMCWLT,    &\n                         SMCREF,SMCDRY,CMC,CMCMAX,NSOIL,DT,              &\n                         SBETA,DF1,                                      &\n                         Q2,T1,SFCTMP,T24,TH2,FDOWN,F1,SSOIL,STC,EPSCA,  &\n                         SFCPRS,BEXP,PC,RCH,RR,CFACTR,SNCOVR,SNEQV,SNDENS,&\n                         SNOWH,SH2O,SLOPE,KDT,FRZX,PSISAT,               &\n                         ZSOIL,DWSAT,DKSAT,TBOT,ZBOT,SHDFAC,RUNOFF1,     &\n                         RUNOFF2,RUNOFF3,EDIR,EC,ET,ETT,NROOT,SNOMLT,    &\n                         ICE,RTDIS,QUARTZ,FXEXP,CSOIL,                   &\n                         BETA,DRIP,DEW,FLX1,FLX2,FLX3,ESNOW,ETNS,EMISSI, &\n                         RIBB,SOLDN,                                     &\n                         ISURBAN,                                        &\n                         VEGTYP, SFHEAD1RT,INFXS1RT,ETPND1,              &\n\t\t\t gwsoilcpl, qlowbdry)\n            ETA_KINEMATIC =  ESNOW + ETNS\n         END IF\n\n!     Calculate effective mixing ratio at grnd level (skin)\n!\n!     Q1=Q2+ETA*CP/RCH\n     Q1=Q2+ETA_KINEMATIC*CP/RCH\n!\n! ----------------------------------------------------------------------\n! DETERMINE SENSIBLE HEAT (H) IN ENERGY UNITS (W M-2)\n! ----------------------------------------------------------------------\n         SHEAT = - (CH * CP * SFCPRS)/ (R * T2V) * ( TH2- T1 )\n\n! ----------------------------------------------------------------------\n! CONVERT EVAP TERMS FROM KINEMATIC (KG M-2 S-1) TO ENERGY UNITS (W M-2)\n! ----------------------------------------------------------------------\n      EDIR = EDIR * LVH2O\n      EC = EC * LVH2O\n      DO K=1,4\n      ET(K) = ET(K) * LVH2O\n      ENDDO\n      ETT = ETT * LVH2O\n\n      ETPND1=ETPND1 * LVH2O\n\n      ESNOW = ESNOW * LSUBS\n      ETP = ETP*((1.-SNCOVR)*LVH2O + SNCOVR*LSUBS)\n      IF (ETP .GT. 0.) THEN\n         ETA = EDIR + EC + ETT + ESNOW\n      ELSE\n        ETA = ETP\n      ENDIF\n! ----------------------------------------------------------------------\n! DETERMINE BETA (RATIO OF ACTUAL TO POTENTIAL EVAP)\n! ----------------------------------------------------------------------\n      IF (ETP == 0.0) THEN\n        BETA = 0.0\n      ELSE\n        BETA = ETA/ETP\n      ENDIF\n\n! ----------------------------------------------------------------------\n! CONVERT THE SIGN OF SOIL HEAT FLUX SO THAT:\n!   SSOIL>0: WARM THE SURFACE  (NIGHT TIME)\n!   SSOIL<0: COOL THE SURFACE  (DAY TIME)\n! ----------------------------------------------------------------------\n         SSOIL = -1.0* SSOIL\n\n! ----------------------------------------------------------------------\n!  FOR THE CASE OF LAND (BUT NOT GLACIAL-ICE):\n!  CONVERT RUNOFF3 (INTERNAL LAYER RUNOFF FROM SUPERSAT) FROM M TO M S-1\n!  AND ADD TO SUBSURFACE RUNOFF/DRAINAGE/BASEFLOW.  RUNOFF2 IS ALREADY\n!  A RATE AT THIS POINT\n! ----------------------------------------------------------------------\n         IF (ICE == 0) THEN\n            RUNOFF3 = RUNOFF3/ DT\n            RUNOFF2 = RUNOFF2+ RUNOFF3\n            SOILM = -1.0* SMC (1)* ZSOIL (1)\n            DO K = 2,NSOIL\n              SOILM = SOILM + SMC (K)* (ZSOIL (K -1) - ZSOIL (K))\n            END DO\n            SOILWM = -1.0* (SMCMAX - SMCWLT)* ZSOIL (1)\n            SOILWW = -1.0* (SMC (1) - SMCWLT)* ZSOIL (1)\n!\n            DO K = 1,NSOIL\n               SMAV(K)=(SMC(K) - SMCWLT)/(SMCMAX - SMCWLT)\n            END DO\n\n            IF (NROOT >= 2) THEN\n              DO K = 2,NROOT\n               SOILWM = SOILWM + (SMCMAX - SMCWLT)* (ZSOIL (K -1) - ZSOIL (K))\n               SOILWW = SOILWW + (SMC(K) - SMCWLT)* (ZSOIL (K -1) - ZSOIL (K))\n              END DO\n            END IF\n            IF (SOILWM .LT. 1.E-6) THEN\n              SOILWM = 0.0\n              SOILW  = 0.0\n              SOILM  = 0.0\n            ELSE\n              SOILW = SOILWW / SOILWM\n            END IF\n         ELSE\n! ----------------------------------------------------------------------\n! FOR THE CASE OF SEA-ICE (ICE=1) OR GLACIAL-ICE (ICE=-1), ADD ANY\n! SNOWMELT DIRECTLY TO SURFACE RUNOFF (RUNOFF1) SINCE THERE IS NO\n! SOIL MEDIUM, AND THUS NO CALL TO SUBROUTINE SMFLX (FOR SOIL MOISTURE\n! TENDENCY).\n! ----------------------------------------------------------------------\n            RUNOFF1 = SNOMLT/DT\n           SOILWM = 0.0\n           SOILW  = 0.0\n           SOILM  = 0.0\n           DO K = 1,NSOIL\n             SMAV(K)= 1.0\n           END DO\n         END IF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SFLX\n! ----------------------------------------------------------------------\n\n      SUBROUTINE ALCALC (ALB,SNOALB,EMBRD,SHDFAC,SHDMIN,SNCOVR,TSNOW,ALBEDO,EMISSI,   &\n                         DT,SNOWNG,SNOTIME1,LVCOEF)\n\n! ----------------------------------------------------------------------\n! CALCULATE ALBEDO INCLUDING SNOW EFFECT (0 -> 1)\n!   ALB     SNOWFREE ALBEDO\n!   SNOALB  MAXIMUM (DEEP) SNOW ALBEDO\n!   SHDFAC    AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!   SHDMIN    MINIMUM AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!   SNCOVR  FRACTIONAL SNOW COVER\n!   ALBEDO  SURFACE ALBEDO INCLUDING SNOW EFFECT\n!   TSNOW   SNOW SURFACE TEMPERATURE (K)\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n! ----------------------------------------------------------------------\n! SNOALB IS ARGUMENT REPRESENTING MAXIMUM ALBEDO OVER DEEP SNOW,\n! AS PASSED INTO SFLX, AND ADAPTED FROM THE SATELLITE-BASED MAXIMUM\n! SNOW ALBEDO FIELDS PROVIDED BY D. ROBINSON AND G. KUKLA\n! (1985, JCAM, VOL 24, 402-411)\n! ----------------------------------------------------------------------\n      REAL, INTENT(IN)  ::  ALB, SNOALB, EMBRD, SHDFAC, SHDMIN, SNCOVR, TSNOW\n      REAL, INTENT(IN)  :: DT\n      LOGICAL, INTENT(IN) :: SNOWNG\n      REAL, INTENT(INOUT):: SNOTIME1\n      REAL, INTENT(OUT) ::  ALBEDO, EMISSI\n      REAL              :: SNOALB2\n      REAL              :: TM,SNOALB1\n      REAL, INTENT(IN)  :: LVCOEF\n      REAL, PARAMETER   :: SNACCA=0.94,SNACCB=0.58,SNTHWA=0.82,SNTHWB=0.46\n! turn of vegetation effect\n!      ALBEDO = ALB + (1.0- (SHDFAC - SHDMIN))* SNCOVR * (SNOALB - ALB)\n!      ALBEDO = (1.0-SNCOVR)*ALB + SNCOVR*SNOALB !this is equivalent to below\n      ALBEDO = ALB + SNCOVR*(SNOALB-ALB)\n      EMISSI = EMBRD + SNCOVR*(EMISSI_S - EMBRD)\n\n!     BASE FORMULATION (DICKINSON ET AL., 1986, COGLEY ET AL., 1990)\n!          IF (TSNOW.LE.263.16) THEN\n!            ALBEDO=SNOALB\n!          ELSE\n!            IF (TSNOW.LT.273.16) THEN\n!              TM=0.1*(TSNOW-263.16)\n!              SNOALB1=0.5*((0.9-0.2*(TM**3))+(0.8-0.16*(TM**3)))\n!            ELSE\n!              SNOALB1=0.67\n!             IF(SNCOVR.GT.0.95) SNOALB1= 0.6\n!             SNOALB1 = ALB + SNCOVR*(SNOALB-ALB)\n!            ENDIF\n!          ENDIF\n!            ALBEDO = ALB + SNCOVR*(SNOALB1-ALB)\n\n!     ISBA FORMULATION (VERSEGHY, 1991; BAKER ET AL., 1990)\n!          SNOALB1 = SNOALB+COEF*(0.85-SNOALB)\n!          SNOALB2=SNOALB1\n!!m          LSTSNW=LSTSNW+1\n!          SNOTIME1 = SNOTIME1 + DT\n!          IF (SNOWNG) THEN\n!             SNOALB2=SNOALB\n!!m             LSTSNW=0\n!             SNOTIME1 = 0.0\n!          ELSE\n!            IF (TSNOW.LT.273.16) THEN\n!!              SNOALB2=SNOALB-0.008*LSTSNW*DT/86400\n!!m              SNOALB2=SNOALB-0.008*SNOTIME1/86400\n!              SNOALB2=(SNOALB2-0.65)*EXP(-0.05*DT/3600)+0.65\n!!              SNOALB2=(ALBEDO-0.65)*EXP(-0.01*DT/3600)+0.65\n!            ELSE\n!              SNOALB2=(SNOALB2-0.5)*EXP(-0.0005*DT/3600)+0.5\n!!              SNOALB2=(SNOALB-0.5)*EXP(-0.24*LSTSNW*DT/86400)+0.5\n!!m              SNOALB2=(SNOALB-0.5)*EXP(-0.24*SNOTIME1/86400)+0.5\n!            ENDIF\n!          ENDIF\n!\n!!               print*,'SNOALB2',SNOALB2,'ALBEDO',ALBEDO,'DT',DT\n!          ALBEDO = ALB + SNCOVR*(SNOALB2-ALB)\n!          IF (ALBEDO .GT. SNOALB2) ALBEDO=SNOALB2\n!!m          LSTSNW1=LSTSNW\n!!          SNOTIME = SNOTIME1\n\n! formulation by Livneh\n! ----------------------------------------------------------------------\n! SNOALB IS CONSIDERED AS THE MAXIMUM SNOW ALBEDO FOR NEW SNOW, AT\n! A VALUE OF 85%. SNOW ALBEDO CURVE DEFAULTS ARE FROM BRAS P.263. SHOULD\n! NOT BE CHANGED EXCEPT FOR SERIOUS PROBLEMS WITH SNOW MELT.\n! TO IMPLEMENT ACCUMULATIN PARAMETERS, SNACCA AND SNACCB, ASSERT THAT IT\n! IS INDEED ACCUMULATION SEASON. I.E. THAT SNOW SURFACE TEMP IS BELOW\n! ZERO AND THE DATE FALLS BETWEEN OCTOBER AND FEBRUARY\n! ----------------------------------------------------------------------\n         SNOALB1 = SNOALB+LVCOEF*(0.85-SNOALB)\n         SNOALB2=SNOALB1\n! ---------------- Initial LSTSNW --------------------------------------\n          IF (SNOWNG) THEN\n             SNOTIME1 = 0.\n          ELSE\n           SNOTIME1=SNOTIME1+DT\n!               IF (TSNOW.LT.273.16) THEN\n                   SNOALB2=SNOALB1*(SNACCA**((SNOTIME1/86400.0)**SNACCB))\n!               ELSE\n!                  SNOALB2 =SNOALB1*(SNTHWA**((SNOTIME1/86400.0)**SNTHWB))\n!               ENDIF\n          ENDIF\n!\n           SNOALB2 = MAX ( SNOALB2, ALB )\n           ALBEDO = ALB + SNCOVR*(SNOALB2-ALB)\n           IF (ALBEDO .GT. SNOALB2) ALBEDO=SNOALB2\n\n!          IF (TSNOW.LT.273.16) THEN\n!            ALBEDO=SNOALB-0.008*DT/86400\n!          ELSE\n!            ALBEDO=(SNOALB-0.5)*EXP(-0.24*DT/86400)+0.5\n!          ENDIF\n\n!      IF (ALBEDO > SNOALB) ALBEDO = SNOALB\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE ALCALC\n! ----------------------------------------------------------------------\n\n      SUBROUTINE CANRES (SOLAR,CH,SFCTMP,Q2,SFCPRS,SMC,ZSOIL,NSOIL,       &\n                         SMCWLT,SMCREF,RSMIN,RC,PC,NROOT,Q2SAT,DQSDT2,    &\n                         TOPT,RSMAX,RGL,HS,XLAI,                          &\n                         RCS,RCT,RCQ,RCSOIL,EMISSI)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE CANRES\n! ----------------------------------------------------------------------\n! CALCULATE CANOPY RESISTANCE WHICH DEPENDS ON INCOMING SOLAR RADIATION,\n! AIR TEMPERATURE, ATMOSPHERIC WATER VAPOR PRESSURE DEFICIT AT THE\n! LOWEST MODEL LEVEL, AND SOIL MOISTURE (PREFERABLY UNFROZEN SOIL\n! MOISTURE RATHER THAN TOTAL)\n! ----------------------------------------------------------------------\n! SOURCE:  JARVIS (1976), NOILHAN AND PLANTON (1989, MWR), JACQUEMIN AND\n! NOILHAN (1990, BLM)\n! SEE ALSO:  CHEN ET AL (1996, JGR, VOL 101(D3), 7251-7268), EQNS 12-14\n! AND TABLE 2 OF SEC. 3.1.2\n! ----------------------------------------------------------------------\n! INPUT:\n!   SOLAR   INCOMING SOLAR RADIATION\n!   CH      SURFACE EXCHANGE COEFFICIENT FOR HEAT AND MOISTURE\n!   SFCTMP  AIR TEMPERATURE AT 1ST LEVEL ABOVE GROUND\n!   Q2      AIR HUMIDITY AT 1ST LEVEL ABOVE GROUND\n!   Q2SAT   SATURATION AIR HUMIDITY AT 1ST LEVEL ABOVE GROUND\n!   DQSDT2  SLOPE OF SATURATION HUMIDITY FUNCTION WRT TEMP\n!   SFCPRS  SURFACE PRESSURE\n!   SMC     VOLUMETRIC SOIL MOISTURE\n!   ZSOIL   SOIL DEPTH (NEGATIVE SIGN, AS IT IS BELOW GROUND)\n!   NSOIL   NO. OF SOIL LAYERS\n!   NROOT   NO. OF SOIL LAYERS IN ROOT ZONE (1.LE.NROOT.LE.NSOIL)\n!   XLAI    LEAF AREA INDEX\n!   SMCWLT  WILTING POINT\n!   SMCREF  REFERENCE SOIL MOISTURE (WHERE SOIL WATER DEFICIT STRESS\n!             SETS IN)\n! RSMIN, RSMAX, TOPT, RGL, HS ARE CANOPY STRESS PARAMETERS SET IN\n!   SURBOUTINE REDPRM\n! OUTPUT:\n!   PC  PLANT COEFFICIENT\n!   RC  CANOPY RESISTANCE\n! ----------------------------------------------------------------------\n\n      IMPLICIT NONE\n      INTEGER, INTENT(IN) :: NROOT,NSOIL\n      INTEGER  K\n      REAL,    INTENT(IN) :: CH,DQSDT2,HS,Q2,Q2SAT,RSMIN,RGL,RSMAX,        &\n                             SFCPRS,SFCTMP,SMCREF,SMCWLT, SOLAR,TOPT,XLAI, &\n                             EMISSI\n      REAL,DIMENSION(1:NSOIL), INTENT(IN) :: SMC,ZSOIL\n      REAL,    INTENT(OUT):: PC,RC,RCQ,RCS,RCSOIL,RCT\n      REAL                :: DELTA,FF,GX,P,RR\n      REAL, DIMENSION(1:NSOIL) ::  PART\n      REAL, PARAMETER     :: SLV = 2.501000E6\n\n\n! ----------------------------------------------------------------------\n! INITIALIZE CANOPY RESISTANCE MULTIPLIER TERMS.\n! ----------------------------------------------------------------------\n      RCS = 0.0\n      RCT = 0.0\n      RCQ = 0.0\n      RCSOIL = 0.0\n\n! ----------------------------------------------------------------------\n! CONTRIBUTION DUE TO INCOMING SOLAR RADIATION\n! ----------------------------------------------------------------------\n      RC = 0.0\n      FF = 0.55*2.0* SOLAR / (RGL * XLAI)\n      RCS = (FF + RSMIN / RSMAX) / (1.0+ FF)\n\n! ----------------------------------------------------------------------\n! CONTRIBUTION DUE TO AIR TEMPERATURE AT FIRST MODEL LEVEL ABOVE GROUND\n! RCT EXPRESSION FROM NOILHAN AND PLANTON (1989, MWR).\n! ----------------------------------------------------------------------\n      RCS = MAX (RCS,0.0001)\n      RCT = 1.0- 0.0016* ( (TOPT - SFCTMP)**2.0)\n\n! ----------------------------------------------------------------------\n! CONTRIBUTION DUE TO VAPOR PRESSURE DEFICIT AT FIRST MODEL LEVEL.\n! RCQ EXPRESSION FROM SSIB\n! ----------------------------------------------------------------------\n      RCT = MAX (RCT,0.0001)\n      RCQ = 1.0/ (1.0+ HS * (Q2SAT - Q2))\n\n! ----------------------------------------------------------------------\n! CONTRIBUTION DUE TO SOIL MOISTURE AVAILABILITY.\n! DETERMINE CONTRIBUTION FROM EACH SOIL LAYER, THEN ADD THEM UP.\n! ----------------------------------------------------------------------\n      RCQ = MAX (RCQ,0.01)\n      GX = (SMC (1) - SMCWLT) / (SMCREF - SMCWLT)\n      IF (GX  >  1.) GX = 1.\n      IF (GX  <  0.) GX = 0.\n\n! ----------------------------------------------------------------------\n! USE SOIL DEPTH AS WEIGHTING FACTOR\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! USE ROOT DISTRIBUTION AS WEIGHTING FACTOR\n!      PART(1) = RTDIS(1) * GX\n! ----------------------------------------------------------------------\n      PART (1) = (ZSOIL (1)/ ZSOIL (NROOT)) * GX\n      DO K = 2,NROOT\n         GX = (SMC (K) - SMCWLT) / (SMCREF - SMCWLT)\n         IF (GX >  1.) GX = 1.\n         IF (GX <  0.) GX = 0.\n! ----------------------------------------------------------------------\n! USE SOIL DEPTH AS WEIGHTING FACTOR\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! USE ROOT DISTRIBUTION AS WEIGHTING FACTOR\n!        PART(K) = RTDIS(K) * GX\n! ----------------------------------------------------------------------\n         PART (K) = ( (ZSOIL (K) - ZSOIL (K -1))/ ZSOIL (NROOT)) * GX\n      END DO\n      DO K = 1,NROOT\n         RCSOIL = RCSOIL + PART (K)\n      END DO\n\n! ----------------------------------------------------------------------\n! DETERMINE CANOPY RESISTANCE DUE TO ALL FACTORS.  CONVERT CANOPY\n! RESISTANCE (RC) TO PLANT COEFFICIENT (PC) TO BE USED WITH POTENTIAL\n! EVAP IN DETERMINING ACTUAL EVAP.  PC IS DETERMINED BY:\n!   PC * LINERIZED PENMAN POTENTIAL EVAP =\n!   PENMAN-MONTEITH ACTUAL EVAPORATION (CONTAINING RC TERM).\n! ----------------------------------------------------------------------\n      RCSOIL = MAX (RCSOIL,0.0001)\n\n      RC = RSMIN / (XLAI * RCS * RCT * RCQ * RCSOIL)\n!      RR = (4.* SIGMA * RD / CP)* (SFCTMP **4.)/ (SFCPRS * CH) + 1.0\n      RR = (4.* EMISSI *SIGMA * RD / CP)* (SFCTMP **4.)/ (SFCPRS * CH) &\n             + 1.0\n\n      DELTA = (SLV / CP)* DQSDT2\n\n      PC = (RR + DELTA)/ (RR * (1. + RC * CH) + DELTA)\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE CANRES\n! ----------------------------------------------------------------------\n\n      SUBROUTINE CSNOW (SNCOND,DSNOW)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE CSNOW\n! FUNCTION CSNOW\n! ----------------------------------------------------------------------\n! CALCULATE SNOW TERMAL CONDUCTIVITY\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN) :: DSNOW\n      REAL, INTENT(OUT):: SNCOND\n      REAL             :: C\n      REAL, PARAMETER  :: UNIT = 0.11631\n\n! ----------------------------------------------------------------------\n! SNCOND IN UNITS OF CAL/(CM*HR*C), RETURNED IN W/(M*C)\n! CSNOW IN UNITS OF CAL/(CM*HR*C), RETURNED IN W/(M*C)\n! BASIC VERSION IS DYACHKOVA EQUATION (1960), FOR RANGE 0.1-0.4\n! ----------------------------------------------------------------------\n      C = 0.328*10** (2.25* DSNOW)\n!      CSNOW=UNIT*C\n\n! ----------------------------------------------------------------------\n! DE VAUX EQUATION (1933), IN RANGE 0.1-0.6\n! ----------------------------------------------------------------------\n!      SNCOND=0.0293*(1.+100.*DSNOW**2)\n!      CSNOW=0.0293*(1.+100.*DSNOW**2)\n\n! ----------------------------------------------------------------------\n! E. ANDERSEN FROM FLERCHINGER\n! ----------------------------------------------------------------------\n!      SNCOND=0.021+2.51*DSNOW**2\n!      CSNOW=0.021+2.51*DSNOW**2\n\n!      SNCOND = UNIT * C\n! double snow thermal conductivity\n      SNCOND = 2.0 * UNIT * C\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE CSNOW\n! ----------------------------------------------------------------------\n\n      SUBROUTINE DEVAP (EDIR,ETP1,SMC,ZSOIL,SHDFAC,SMCMAX,BEXP,         &\n                        DKSAT,DWSAT,SMCDRY,SMCREF,SMCWLT,FXEXP)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE DEVAP\n! FUNCTION DEVAP\n! ----------------------------------------------------------------------\n! CALCULATE DIRECT SOIL EVAPORATION\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN) :: ETP1,SMC,BEXP,DKSAT,DWSAT,FXEXP,              &\n                          SHDFAC,SMCDRY,SMCMAX,ZSOIL,SMCREF,SMCWLT\n      REAL, INTENT(OUT):: EDIR\n      REAL             :: FX, SRATIO\n\n\n! ----------------------------------------------------------------------\n! DIRECT EVAP A FUNCTION OF RELATIVE SOIL MOISTURE AVAILABILITY, LINEAR\n! WHEN FXEXP=1.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! FX > 1 REPRESENTS DEMAND CONTROL\n! FX < 1 REPRESENTS FLUX CONTROL\n! ----------------------------------------------------------------------\n\n      SRATIO = (SMC - SMCDRY) / (SMCMAX - SMCDRY)\n      IF (SRATIO > 0.) THEN\n        FX = SRATIO**FXEXP\n        FX = MAX ( MIN ( FX, 1. ) ,0. )\n      ELSE\n        FX = 0.\n      ENDIF\n\n! ----------------------------------------------------------------------\n! ALLOW FOR THE DIRECT-EVAP-REDUCING EFFECT OF SHADE\n! ----------------------------------------------------------------------\n      EDIR = FX * ( 1.0- SHDFAC ) * ETP1\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE DEVAP\n\n      SUBROUTINE DEVAP_mod (EDIR,ETP1,SMC,ZSOIL,SHDFAC,SMCMAX,BEXP,         &\n                        DKSAT,DWSAT,SMCDRY,SMCREF,SMCWLT,FXEXP,         &\n                        SFHEAD1RT,ETPND1,DT)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE DEVAP\n! FUNCTION DEVAP\n! ----------------------------------------------------------------------\n! CALCULATE DIRECT SOIL EVAPORATION\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN) :: ETP1,SMC,BEXP,DKSAT,DWSAT,FXEXP,              &\n                          SHDFAC,SMCDRY,SMCMAX,ZSOIL,SMCREF,SMCWLT\n      REAL, INTENT(OUT):: EDIR\n      REAL             :: FX, SRATIO\n\n      REAL, INTENT(INOUT) :: SFHEAD1RT,ETPND1\n      REAL, INTENT(IN):: DT\n       REAL             :: EDIRTMP\n\n\n\n! ----------------------------------------------------------------------\n! DIRECT EVAP A FUNCTION OF RELATIVE SOIL MOISTURE AVAILABILITY, LINEAR\n! WHEN FXEXP=1.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! FX > 1 REPRESENTS DEMAND CONTROL\n! FX < 1 REPRESENTS FLUX CONTROL\n! ----------------------------------------------------------------------\n\n      SRATIO = (SMC - SMCDRY) / (SMCMAX - SMCDRY)\n      IF (SRATIO > 0.) THEN\n        FX = SRATIO**FXEXP\n        FX = MAX ( MIN ( FX, 1. ) ,0. )\n      ELSE\n        FX = 0.\n      ENDIF\n\n!DJG NDHMS/WRF-Hydro edits... Adjustment for ponded surface water : Reduce ETP1\n      EDIRTMP = 0.\n      ETPND1 = 0.\n\n!DJG NDHMS/WRF-Hydro edits...  Calc Max Potential Dir Evap. (ETP1 units: }=m/s) EDIRTMP = ( 1.0- SHDFAC ) * ETP1\n! Convert all units to (m)\n! Convert EDIRTMP  from (kg m{-2} s{-1}=m/s) to (m) ...\n      EDIRTMP = EDIRTMP * DT\n\n!DJG NDHMS/WRF-Hydro edits... Convert SFHEAD from (mm) to (m) ...\n      SFHEAD1RT=SFHEAD1RT * 0.001\n\n\n\n!DJG NDHMS/WRF-Hydro edits... Calculate ETPND as reduction in EDIR(TMP)...\n      IF (EDIRTMP > 0.) THEN\n       IF ( EDIRTMP > SFHEAD1RT ) THEN\n         ETPND1 = SFHEAD1RT\n         SFHEAD1RT=0.\n         EDIRTMP = EDIRTMP - ETPND1\n       ELSE\n         ETPND1 = EDIRTMP\n         EDIRTMP = 0.\n         SFHEAD1RT = SFHEAD1RT - ETPND1\n       END IF\n      END IF\n\n!DJG NDHMS/WRF-Hydro edits... Convert SFHEAD units back to (mm)\n      IF ( SFHEAD1RT /= 0.) SFHEAD1RT=SFHEAD1RT * 1000.\n\n!DJG NDHMS/WRF-Hydro edits...Convert ETPND and EDIRTMP back to (mm/s=kg m{-2} s{-1})\n      ETPND1 = ETPND1 / DT\n      EDIRTMP = EDIRTMP / DT\n!DEBUG    print *, \"After DEVAP...SFCHEAD+ETPND1\",SFHEAD1RT+ETPND1*DT\n\n\n! ----------------------------------------------------------------------\n! ALLOW FOR THE DIRECT-EVAP-REDUCING EFFECT OF SHADE\n! ----------------------------------------------------------------------\n!DJG NDHMS/WRF-Hydro edits...\n!       EDIR = FX * ( 1.0- SHDFAC ) * ETP1\n       EDIR = FX * EDIRTMP\n\n\n\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE DEVAP_mod\n! ----------------------------------------------------------------------\n\n      SUBROUTINE EVAPO (ETA1,SMC,NSOIL,CMC,ETP1,DT,ZSOIL,               &\n                         SH2O,                                          &\n                         SMCMAX,BEXP,PC,SMCWLT,DKSAT,DWSAT,             &\n                         SMCREF,SHDFAC,CMCMAX,                          &\n                         SMCDRY,CFACTR,                                 &\n                         EDIR,EC,ET,ETT,SFCTMP,Q2,NROOT,RTDIS,FXEXP,    &\n                         SFHEAD1RT,ETPND1)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE EVAPO\n! ----------------------------------------------------------------------\n! CALCULATE SOIL MOISTURE FLUX.  THE SOIL MOISTURE CONTENT (SMC - A PER\n! UNIT VOLUME MEASUREMENT) IS A DEPENDENT VARIABLE THAT IS UPDATED WITH\n! PROGNOSTIC EQNS. THE CANOPY MOISTURE CONTENT (CMC) IS ALSO UPDATED.\n! FROZEN GROUND VERSION:  NEW STATES ADDED: SH2O, AND FROZEN GROUND\n! CORRECTION FACTOR, FRZFACT AND PARAMETER SLOPE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)   :: NSOIL, NROOT\n      INTEGER               :: I,K\n      REAL,    INTENT(IN)   :: BEXP, CFACTR,CMC,CMCMAX,DKSAT,           &\n                                 DT,DWSAT,FXEXP,PC,Q2,SFCTMP,           &\n                                 SHDFAC,SMCDRY,SMCMAX,SMCREF,SMCWLT\n      REAL,    INTENT(OUT)  :: EC,EDIR,ETA1,ETT\n      REAL                  :: CMC2MS\n      REAL,DIMENSION(1:NSOIL), INTENT(IN) :: RTDIS, SMC, SH2O, ZSOIL\n      REAL,DIMENSION(1:NSOIL), INTENT(OUT) :: ET\n\n      REAL,   INTENT(INOUT) :: SFHEAD1RT,ETPND1,ETP1\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE IF THE POTENTIAL EVAPOTRANSPIRATION IS\n! GREATER THAN ZERO.\n! ----------------------------------------------------------------------\n      EDIR = 0.\n      EC = 0.\n      ETT = 0.\n      DO K = 1,NSOIL\n         ET (K) = 0.\n      END DO\n\n! ----------------------------------------------------------------------\n! RETRIEVE DIRECT EVAPORATION FROM SOIL SURFACE.  CALL THIS FUNCTION\n! ONLY IF VEG COVER NOT COMPLETE.\n! FROZEN GROUND VERSION:  SH2O STATES REPLACE SMC STATES.\n! ----------------------------------------------------------------------\n      IF (ETP1 > 0.0) THEN\n         IF (SHDFAC <  1.) THEN\n             CALL DEVAP (EDIR,ETP1,SMC (1),ZSOIL (1),SHDFAC,SMCMAX,      &\n                         BEXP,DKSAT,DWSAT,SMCDRY,SMCREF,SMCWLT,FXEXP)\n!            CALL DEVAP_mod (EDIR,ETP1,SMC (1),ZSOIL (1),SHDFAC,SMCMAX,      &\n!                        BEXP,DKSAT,DWSAT,SMCDRY,SMCREF,SMCWLT,FXEXP,    &\n!                         SFHEAD1RT,ETPND1,DT)\n!DJG Reduce ETP1 by EDIR & ETPND1...\n!yw                 ETP1=ETP1-EDIR-ETPND1\n         END IF\n! ----------------------------------------------------------------------\n! INITIALIZE PLANT TOTAL TRANSPIRATION, RETRIEVE PLANT TRANSPIRATION,\n! AND ACCUMULATE IT FOR ALL SOIL LAYERS.\n! ----------------------------------------------------------------------\n\n         IF (SHDFAC > 0.0) THEN\n            CALL TRANSP (ET,NSOIL,ETP1,SH2O,CMC,ZSOIL,SHDFAC,SMCWLT,     &\n                          CMCMAX,PC,CFACTR,SMCREF,SFCTMP,Q2,NROOT,RTDIS)\n            DO K = 1,NSOIL\n               ETT = ETT + ET ( K )\n            END DO\n! ----------------------------------------------------------------------\n! CALCULATE CANOPY EVAPORATION.\n! IF STATEMENTS TO AVOID TANGENT LINEAR PROBLEMS NEAR CMC=0.0.\n! ----------------------------------------------------------------------\n            IF (CMC > 0.0) THEN\n               EC = SHDFAC * ( ( CMC / CMCMAX ) ** CFACTR ) * ETP1\n            ELSE\n               EC = 0.0\n            END IF\n! ----------------------------------------------------------------------\n! EC SHOULD BE LIMITED BY THE TOTAL AMOUNT OF AVAILABLE WATER ON THE\n! CANOPY.  -F.CHEN, 18-OCT-1994\n! ----------------------------------------------------------------------\n            CMC2MS = CMC / DT\n            EC = MIN ( CMC2MS, EC )\n         END IF\n      END IF\n! ----------------------------------------------------------------------\n! TOTAL UP EVAP AND TRANSP TYPES TO OBTAIN ACTUAL EVAPOTRANSP\n! ----------------------------------------------------------------------\n      ETA1 = EDIR + ETT + EC\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE EVAPO\n! ----------------------------------------------------------------------\n\n  SUBROUTINE FAC2MIT(SMCMAX,FLIMIT)\n    IMPLICIT NONE\n    REAL, INTENT(IN)  :: SMCMAX\n    REAL, INTENT(OUT) :: FLIMIT\n\n    FLIMIT = 0.90\n\n    IF ( SMCMAX == 0.395 ) THEN\n       FLIMIT = 0.59\n    ELSE IF ( ( SMCMAX == 0.434 ) .OR. ( SMCMAX == 0.404 ) ) THEN\n       FLIMIT = 0.85\n    ELSE IF ( ( SMCMAX == 0.465 ) .OR. ( SMCMAX == 0.406 ) ) THEN\n       FLIMIT = 0.86\n    ELSE IF ( ( SMCMAX == 0.476 ) .OR. ( SMCMAX == 0.439 ) ) THEN\n       FLIMIT = 0.74\n    ELSE IF ( ( SMCMAX == 0.200 ) .OR. ( SMCMAX == 0.464 ) ) THEN\n       FLIMIT = 0.80\n    ENDIF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE FAC2MIT\n! ----------------------------------------------------------------------\n\n      SUBROUTINE FRH2O (FREE,TKELV,SMC,SH2O,SMCMAX,BEXP,PSIS)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE FRH2O\n! ----------------------------------------------------------------------\n! CALCULATE AMOUNT OF SUPERCOOLED LIQUID SOIL WATER CONTENT IF\n! TEMPERATURE IS BELOW 273.15K (T0).  REQUIRES NEWTON-TYPE ITERATION TO\n! SOLVE THE NONLINEAR IMPLICIT EQUATION GIVEN IN EQN 17 OF KOREN ET AL\n! (1999, JGR, VOL 104(D16), 19569-19585).\n! ----------------------------------------------------------------------\n! NEW VERSION (JUNE 2001): MUCH FASTER AND MORE ACCURATE NEWTON\n! ITERATION ACHIEVED BY FIRST TAKING LOG OF EQN CITED ABOVE -- LESS THAN\n! 4 (TYPICALLY 1 OR 2) ITERATIONS ACHIEVES CONVERGENCE.  ALSO, EXPLICIT\n! 1-STEP SOLUTION OPTION FOR SPECIAL CASE OF PARAMETER CK=0, WHICH\n! REDUCES THE ORIGINAL IMPLICIT EQUATION TO A SIMPLER EXPLICIT FORM,\n! KNOWN AS THE \"FLERCHINGER EQN\". IMPROVED HANDLING OF SOLUTION IN THE\n! LIMIT OF FREEZING POINT TEMPERATURE T0.\n! ----------------------------------------------------------------------\n! INPUT:\n\n!   TKELV.........TEMPERATURE (Kelvin)\n!   SMC...........TOTAL SOIL MOISTURE CONTENT (VOLUMETRIC)\n!   SH2O..........LIQUID SOIL MOISTURE CONTENT (VOLUMETRIC)\n!   SMCMAX........SATURATION SOIL MOISTURE CONTENT (FROM REDPRM)\n!   B.............SOIL TYPE \"B\" PARAMETER (FROM REDPRM)\n!   PSIS..........SATURATED SOIL MATRIC POTENTIAL (FROM REDPRM)\n\n! OUTPUT:\n!   FRH2O.........SUPERCOOLED LIQUID WATER CONTENT\n!   FREE..........SUPERCOOLED LIQUID WATER CONTENT\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN)     :: BEXP,PSIS,SH2O,SMC,SMCMAX,TKELV\n      REAL, INTENT(OUT)    :: FREE\n      REAL                 :: BX,DENOM,DF,DSWL,FK,SWL,SWLK\n      INTEGER              :: NLOG,KCOUNT\n!      PARAMETER(CK = 0.0)\n      REAL, PARAMETER      :: CK = 8.0, BLIM = 5.5, ERROR = 0.005,       &\n                              HLICE = 3.335E5, GS = 9.81,DICE = 920.0,   &\n                              DH2O = 1000.0, T0 = 273.15\n\n! ----------------------------------------------------------------------\n! LIMITS ON PARAMETER B: B < 5.5  (use parameter BLIM)\n! SIMULATIONS SHOWED IF B > 5.5 UNFROZEN WATER CONTENT IS\n! NON-REALISTICALLY HIGH AT VERY LOW TEMPERATURES.\n! ----------------------------------------------------------------------\n      BX = BEXP\n\n! ----------------------------------------------------------------------\n! INITIALIZING ITERATIONS COUNTER AND ITERATIVE SOLUTION FLAG.\n! ----------------------------------------------------------------------\n      IF (BEXP >  BLIM) BX = BLIM\n      NLOG = 0\n\n! ----------------------------------------------------------------------\n!  IF TEMPERATURE NOT SIGNIFICANTLY BELOW FREEZING (T0), SH2O = SMC\n! ----------------------------------------------------------------------\n      KCOUNT = 0\n!      FRH2O = SMC\n      IF (TKELV > (T0- 1.E-3)) THEN\n          FREE = SMC\n      ELSE\n\n! ----------------------------------------------------------------------\n! OPTION 1: ITERATED SOLUTION FOR NONZERO CK\n! IN KOREN ET AL, JGR, 1999, EQN 17\n! ----------------------------------------------------------------------\n! INITIAL GUESS FOR SWL (frozen content)\n! ----------------------------------------------------------------------\n         IF (CK /= 0.0) THEN\n            SWL = SMC - SH2O\n! ----------------------------------------------------------------------\n! KEEP WITHIN BOUNDS.\n! ----------------------------------------------------------------------\n            IF (SWL > (SMC -0.02)) SWL = SMC -0.02\n\n! ----------------------------------------------------------------------\n!  START OF ITERATIONS\n! ----------------------------------------------------------------------\n            IF (SWL < 0.) SWL = 0.\n 1001       Continue\n              IF (.NOT.( (NLOG < 10) .AND. (KCOUNT == 0)))   goto 1002\n              NLOG = NLOG +1\n              DF = ALOG ( ( PSIS * GS / HLICE ) * ( ( 1. + CK * SWL )**2.) * &\n                   ( SMCMAX / (SMC - SWL) )** BX) - ALOG ( - (               &\n                   TKELV - T0)/ TKELV)\n              DENOM = 2. * CK / ( 1. + CK * SWL ) + BX / ( SMC - SWL )\n              SWLK = SWL - DF / DENOM\n! ----------------------------------------------------------------------\n! BOUNDS USEFUL FOR MATHEMATICAL SOLUTION.\n! ----------------------------------------------------------------------\n              IF (SWLK > (SMC -0.02)) SWLK = SMC - 0.02\n              IF (SWLK < 0.) SWLK = 0.\n\n! ----------------------------------------------------------------------\n! MATHEMATICAL SOLUTION BOUNDS APPLIED.\n! ----------------------------------------------------------------------\n              DSWL = ABS (SWLK - SWL)\n\n! ----------------------------------------------------------------------\n! IF MORE THAN 10 ITERATIONS, USE EXPLICIT METHOD (CK=0 APPROX.)\n! WHEN DSWL LESS OR EQ. ERROR, NO MORE ITERATIONS REQUIRED.\n! ----------------------------------------------------------------------\n              SWL = SWLK\n              IF ( DSWL <= ERROR ) THEN\n                    KCOUNT = KCOUNT +1\n              END IF\n! ----------------------------------------------------------------------\n!  END OF ITERATIONS\n! ----------------------------------------------------------------------\n! BOUNDS APPLIED WITHIN DO-BLOCK ARE VALID FOR PHYSICAL SOLUTION.\n! ----------------------------------------------------------------------\n!          FRH2O = SMC - SWL\n           goto 1001\n 1002   continue\n           FREE = SMC - SWL\n         END IF\n! ----------------------------------------------------------------------\n! END OPTION 1\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! OPTION 2: EXPLICIT SOLUTION FOR FLERCHINGER EQ. i.e. CK=0\n! IN KOREN ET AL., JGR, 1999, EQN 17\n! APPLY PHYSICAL BOUNDS TO FLERCHINGER SOLUTION\n! ----------------------------------------------------------------------\n         IF (KCOUNT == 0) THEN\n             PRINT *,'Flerchinger USEd in NEW version. Iterations=',NLOG\n                  FK = ( ( (HLICE / (GS * ( - PSIS)))*                    &\n                       ( (TKELV - T0)/ TKELV))** ( -1/ BX))* SMCMAX\n!            FRH2O = MIN (FK, SMC)\n             IF (FK < 0.02) FK = 0.02\n             FREE = MIN (FK, SMC)\n! ----------------------------------------------------------------------\n! END OPTION 2\n! ----------------------------------------------------------------------\n         END IF\n      END IF\n! ----------------------------------------------------------------------\n  END SUBROUTINE FRH2O\n! ----------------------------------------------------------------------\n\n      SUBROUTINE HRT (RHSTS,STC,SMC,SMCMAX,NSOIL,ZSOIL,YY,ZZ1,          &\n                       TBOT,ZBOT,PSISAT,SH2O,DT,BEXP,                   &\n                       F1,DF1,QUARTZ,CSOIL,AI,BI,CI,VEGTYP,ISURBAN)      \n\n! ----------------------------------------------------------------------\n! SUBROUTINE HRT\n! ----------------------------------------------------------------------\n! CALCULATE THE RIGHT HAND SIDE OF THE TIME TENDENCY TERM OF THE SOIL\n! THERMAL DIFFUSION EQUATION.  ALSO TO COMPUTE ( PREPARE ) THE MATRIX\n! COEFFICIENTS FOR THE TRI-DIAGONAL MATRIX OF THE IMPLICIT TIME SCHEME.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      LOGICAL              :: ITAVG\n      INTEGER, INTENT(IN)  :: NSOIL, VEGTYP\n      INTEGER, INTENT(IN)  :: ISURBAN\n      INTEGER              :: I, K\n\n      REAL, INTENT(IN)     :: BEXP, CSOIL, DF1, DT,F1,PSISAT,QUARTZ,     &\n                              SMCMAX ,TBOT,YY,ZZ1, ZBOT\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: SMC,STC,ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT):: SH2O\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)  :: RHSTS\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)  :: AI, BI,CI\n      REAL                 :: DDZ, DDZ2, DENOM, DF1N, DF1K, DTSDZ,       &\n                              DTSDZ2,HCPCT,QTOT,SSOIL,SICE,TAVG,TBK,     &\n                              TBK1,TSNSR,TSURF,CSOIL_LOC\n      REAL, PARAMETER      :: T0 = 273.15, CAIR = 1004.0, CICE = 2.106E6,&\n                              CH2O = 4.2E6\n\n\n!urban\n        IF( VEGTYP == ISURBAN ) then\n            CSOIL_LOC=3.0E6\n        ELSE\n            CSOIL_LOC=CSOIL\n        ENDIF\n\n! ----------------------------------------------------------------------\n! INITIALIZE LOGICAL FOR SOIL LAYER TEMPERATURE AVERAGING.\n! ----------------------------------------------------------------------\n       ITAVG = .TRUE.\n! ----------------------------------------------------------------------\n! BEGIN SECTION FOR TOP SOIL LAYER\n! ----------------------------------------------------------------------\n! CALC THE HEAT CAPACITY OF THE TOP SOIL LAYER\n! ----------------------------------------------------------------------\n      HCPCT = SH2O (1)* CH2O + (1.0- SMCMAX)* CSOIL_LOC + (SMCMAX - SMC (1))&\n       * CAIR                                                           &\n              + ( SMC (1) - SH2O (1) )* CICE\n\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEFFICIENTS AI, BI, AND CI FOR THE TOP LAYER\n! ----------------------------------------------------------------------\n      DDZ = 1.0 / ( -0.5 * ZSOIL (2) )\n      AI (1) = 0.0\n      CI (1) = (DF1 * DDZ) / (ZSOIL (1) * HCPCT)\n\n! ----------------------------------------------------------------------\n! CALCULATE THE VERTICAL SOIL TEMP GRADIENT BTWN THE 1ST AND 2ND SOIL\n! LAYERS.  THEN CALCULATE THE SUBSURFACE HEAT FLUX. USE THE TEMP\n! GRADIENT AND SUBSFC HEAT FLUX TO CALC \"RIGHT-HAND SIDE TENDENCY\n! TERMS\", OR \"RHSTS\", FOR TOP SOIL LAYER.\n! ----------------------------------------------------------------------\n      BI (1) = - CI (1) + DF1 / (0.5 * ZSOIL (1) * ZSOIL (1)* HCPCT *    &\n       ZZ1)\n      DTSDZ = (STC (1) - STC (2)) / ( -0.5 * ZSOIL (2))\n      SSOIL = DF1 * (STC (1) - YY) / (0.5 * ZSOIL (1) * ZZ1)\n!      RHSTS(1) = (DF1 * DTSDZ - SSOIL) / (ZSOIL(1) * HCPCT)\n      DENOM = (ZSOIL (1) * HCPCT)\n\n! ----------------------------------------------------------------------\n! NEXT CAPTURE THE VERTICAL DIFFERENCE OF THE HEAT FLUX AT TOP AND\n! BOTTOM OF FIRST SOIL LAYER FOR USE IN HEAT FLUX CONSTRAINT APPLIED TO\n! POTENTIAL SOIL FREEZING/THAWING IN ROUTINE SNKSRC.\n! ----------------------------------------------------------------------\n!      QTOT = SSOIL - DF1*DTSDZ\n      RHSTS (1) = (DF1 * DTSDZ - SSOIL) / DENOM\n\n! ----------------------------------------------------------------------\n! CALCULATE FROZEN WATER CONTENT IN 1ST SOIL LAYER.\n! ----------------------------------------------------------------------\n      QTOT = -1.0* RHSTS (1)* DENOM\n\n! ----------------------------------------------------------------------\n! IF TEMPERATURE AVERAGING INVOKED (ITAVG=TRUE; ELSE SKIP):\n! SET TEMP \"TSURF\" AT TOP OF SOIL COLUMN (FOR USE IN FREEZING SOIL\n! PHYSICS LATER IN FUNCTION SUBROUTINE SNKSRC).  IF SNOWPACK CONTENT IS\n! ZERO, THEN TSURF EXPRESSION BELOW GIVES TSURF = SKIN TEMP.  IF\n! SNOWPACK IS NONZERO (HENCE ARGUMENT ZZ1=1), THEN TSURF EXPRESSION\n! BELOW YIELDS SOIL COLUMN TOP TEMPERATURE UNDER SNOWPACK.  THEN\n! CALCULATE TEMPERATURE AT BOTTOM INTERFACE OF 1ST SOIL LAYER FOR USE\n! LATER IN FUNCTION SUBROUTINE SNKSRC\n! ----------------------------------------------------------------------\n      SICE = SMC (1) - SH2O (1)\n      IF (ITAVG) THEN\n         TSURF = (YY + (ZZ1-1) * STC (1)) / ZZ1\n! ----------------------------------------------------------------------\n! IF FROZEN WATER PRESENT OR ANY OF LAYER-1 MID-POINT OR BOUNDING\n! INTERFACE TEMPERATURES BELOW FREEZING, THEN CALL SNKSRC TO\n! COMPUTE HEAT SOURCE/SINK (AND CHANGE IN FROZEN WATER CONTENT)\n! DUE TO POSSIBLE SOIL WATER PHASE CHANGE\n! ----------------------------------------------------------------------\n         CALL TBND (STC (1),STC (2),ZSOIL,ZBOT,1,NSOIL,TBK)\n         IF ( (SICE > 0.) .OR. (STC (1) < T0) .OR.                         &\n            (TSURF < T0) .OR. (TBK < T0) ) THEN\n!          TSNSR = SNKSRC (TAVG,SMC(1),SH2O(1),\n            CALL TMPAVG (TAVG,TSURF,STC (1),TBK,ZSOIL,NSOIL,1)\n            CALL SNKSRC (TSNSR,TAVG,SMC (1),SH2O (1),                      &\n                          ZSOIL,NSOIL,SMCMAX,PSISAT,BEXP,DT,1,QTOT)\n!          RHSTS(1) = RHSTS(1) - TSNSR / ( ZSOIL(1) * HCPCT )\n            RHSTS (1) = RHSTS (1) - TSNSR / DENOM\n         END IF\n      ELSE\n!          TSNSR = SNKSRC (STC(1),SMC(1),SH2O(1),\n         IF ( (SICE > 0.) .OR. (STC (1) < T0) ) THEN\n            CALL SNKSRC (TSNSR,STC (1),SMC (1),SH2O (1),                   &\n                          ZSOIL,NSOIL,SMCMAX,PSISAT,BEXP,DT,1,QTOT)\n!          RHSTS(1) = RHSTS(1) - TSNSR / ( ZSOIL(1) * HCPCT )\n            RHSTS (1) = RHSTS (1) - TSNSR / DENOM\n         END IF\n! ----------------------------------------------------------------------\n! THIS ENDS SECTION FOR TOP SOIL LAYER.\n! ----------------------------------------------------------------------\n      END IF\n\n! INITIALIZE DDZ2\n! ----------------------------------------------------------------------\n\n      DDZ2 = 0.0\n      DF1K = DF1\n\n! ----------------------------------------------------------------------\n! LOOP THRU THE REMAINING SOIL LAYERS, REPEATING THE ABOVE PROCESS\n! (EXCEPT SUBSFC OR \"GROUND\" HEAT FLUX NOT REPEATED IN LOWER LAYERS)\n! ----------------------------------------------------------------------\n! CALCULATE HEAT CAPACITY FOR THIS SOIL LAYER.\n! ----------------------------------------------------------------------\n      DO K = 2,NSOIL\n         HCPCT = SH2O (K)* CH2O + (1.0- SMCMAX)* CSOIL_LOC + (SMCMAX - SMC (  &\n                K))* CAIR + ( SMC (K) - SH2O (K) )* CICE\n! ----------------------------------------------------------------------\n! THIS SECTION FOR LAYER 2 OR GREATER, BUT NOT LAST LAYER.\n! ----------------------------------------------------------------------\n! CALCULATE THERMAL DIFFUSIVITY FOR THIS LAYER.\n! ----------------------------------------------------------------------\n         IF (K /= NSOIL) THEN\n\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT THRU THIS LAYER\n! ----------------------------------------------------------------------\n            CALL TDFCND (DF1N,SMC (K),QUARTZ,SMCMAX,SH2O (K))\n\n!urban\n       IF ( VEGTYP == ISURBAN ) DF1N = 3.24\n\n            DENOM = 0.5 * ( ZSOIL (K -1) - ZSOIL (K +1) )\n\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEF, CI, AFTER CALC'NG ITS PARTIAL PRODUCT\n! ----------------------------------------------------------------------\n            DTSDZ2 = ( STC (K) - STC (K +1) ) / DENOM\n            DDZ2 = 2. / (ZSOIL (K -1) - ZSOIL (K +1))\n\n! ----------------------------------------------------------------------\n! IF TEMPERATURE AVERAGING INVOKED (ITAVG=TRUE; ELSE SKIP):  CALCULATE\n! TEMP AT BOTTOM OF LAYER.\n! ----------------------------------------------------------------------\n            CI (K) = - DF1N * DDZ2 / ( (ZSOIL (K -1) - ZSOIL (K)) *      &\n       HCPCT)\n            IF (ITAVG) THEN\n               CALL TBND (STC (K),STC (K +1),ZSOIL,ZBOT,K,NSOIL,TBK1)\n            END IF\n\n         ELSE\n! ----------------------------------------------------------------------\n! SPECIAL CASE OF BOTTOM SOIL LAYER:  CALCULATE THERMAL DIFFUSIVITY FOR\n! BOTTOM LAYER.\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT THRU BOTTOM LAYER.\n! ----------------------------------------------------------------------\n            CALL TDFCND (DF1N,SMC (K),QUARTZ,SMCMAX,SH2O (K))\n\n\n!urban\n       IF ( VEGTYP == ISURBAN ) DF1N = 3.24\n\n            DENOM = .5 * (ZSOIL (K -1) + ZSOIL (K)) - ZBOT\n\n! ----------------------------------------------------------------------\n! SET MATRIX COEF, CI TO ZERO IF BOTTOM LAYER.\n! ----------------------------------------------------------------------\n            DTSDZ2 = (STC (K) - TBOT) / DENOM\n\n! ----------------------------------------------------------------------\n! IF TEMPERATURE AVERAGING INVOKED (ITAVG=TRUE; ELSE SKIP):  CALCULATE\n! TEMP AT BOTTOM OF LAST LAYER.\n! ----------------------------------------------------------------------\n            CI (K) = 0.\n            IF (ITAVG) THEN\n               CALL TBND (STC (K),TBOT,ZSOIL,ZBOT,K,NSOIL,TBK1)\n            END IF\n! ----------------------------------------------------------------------\n! THIS ENDS SPECIAL LOOP FOR BOTTOM LAYER.\n         END IF\n! ----------------------------------------------------------------------\n! CALCULATE RHSTS FOR THIS LAYER AFTER CALC'NG A PARTIAL PRODUCT.\n! ----------------------------------------------------------------------\n         DENOM = ( ZSOIL (K) - ZSOIL (K -1) ) * HCPCT\n         RHSTS (K) = ( DF1N * DTSDZ2- DF1K * DTSDZ ) / DENOM\n         QTOT = -1.0* DENOM * RHSTS (K)\n\n         SICE = SMC (K) - SH2O (K)\n         IF (ITAVG) THEN\n            CALL TMPAVG (TAVG,TBK,STC (K),TBK1,ZSOIL,NSOIL,K)\n!            TSNSR = SNKSRC(TAVG,SMC(K),SH2O(K),ZSOIL,NSOIL,\n            IF ( (SICE > 0.) .OR. (STC (K) < T0) .OR.                   &\n               (TBK .lt. T0) .OR. (TBK1 .lt. T0) ) THEN\n               CALL SNKSRC (TSNSR,TAVG,SMC (K),SH2O (K),ZSOIL,NSOIL,    &\n                             SMCMAX,PSISAT,BEXP,DT,K,QTOT)\n               RHSTS (K) = RHSTS (K) - TSNSR / DENOM\n            END IF\n         ELSE\n!            TSNSR = SNKSRC(STC(K),SMC(K),SH2O(K),ZSOIL,NSOIL,\n            IF ( (SICE > 0.) .OR. (STC (K) < T0) ) THEN\n               CALL SNKSRC (TSNSR,STC (K),SMC (K),SH2O (K),ZSOIL,NSOIL, &\n                             SMCMAX,PSISAT,BEXP,DT,K,QTOT)\n               RHSTS (K) = RHSTS (K) - TSNSR / DENOM\n            END IF\n         END IF\n\n! ----------------------------------------------------------------------\n! CALC MATRIX COEFS, AI, AND BI FOR THIS LAYER.\n! ----------------------------------------------------------------------\n         AI (K) = - DF1K * DDZ / ( (ZSOIL (K -1) - ZSOIL (K)) * HCPCT)\n\n! ----------------------------------------------------------------------\n! RESET VALUES OF DF1, DTSDZ, DDZ, AND TBK FOR LOOP TO NEXT SOIL LAYER.\n! ----------------------------------------------------------------------\n         BI (K) = - (AI (K) + CI (K))\n         TBK = TBK1\n         DF1K = DF1N\n         DTSDZ = DTSDZ2\n         DDZ = DDZ2\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE HRT\n! ----------------------------------------------------------------------\n\n      SUBROUTINE HRTICE (RHSTS,STC,TBOT,ICE,NSOIL,ZSOIL,YY,ZZ1,DF1,AI,BI,CI)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE HRTICE\n! ----------------------------------------------------------------------\n! CALCULATE THE RIGHT HAND SIDE OF THE TIME TENDENCY TERM OF THE SOIL\n! THERMAL DIFFUSION EQUATION IN THE CASE OF SEA-ICE (ICE=1) OR GLACIAL\n! ICE (ICE=-1). COMPUTE (PREPARE) THE MATRIX COEFFICIENTS FOR THE\n! TRI-DIAGONAL MATRIX OF THE IMPLICIT TIME SCHEME.\n!\n! (NOTE:  THIS SUBROUTINE ONLY CALLED FOR SEA-ICE OR GLACIAL ICE, BUT\n! NOT FOR NON-GLACIAL LAND (ICE = 0).\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n\n      INTEGER, INTENT(IN)    :: NSOIL\n      INTEGER                :: K\n\n      REAL,    INTENT(IN)    :: DF1,YY,ZZ1\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: AI, BI,CI\n      REAL, DIMENSION(1:NSOIL), INTENT(IN) :: STC, ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: RHSTS\n      REAL,                     INTENT(IN) :: TBOT\n      INTEGER,                  INTENT(IN) :: ICE\n      REAL                   :: DDZ,DDZ2,DENOM,DTSDZ,DTSDZ2,SSOIL,       &\n                                ZBOT\n      REAL                   :: HCPCT\n      REAL :: DF1K\n      REAL :: DF1N\n      REAL :: ZMD\n\n! ----------------------------------------------------------------------\n! SET A NOMINAL UNIVERSAL VALUE OF THE SEA-ICE SPECIFIC HEAT CAPACITY,\n! HCPCT = 1880.0*917.0.\n! ----------------------------------------------------------------------\n      IF ( ICE == 1 ) THEN\n         ! Sea-ice values\n         HCPCT = 1.72396E+6\n      ELSEIF (ICE == -1) THEN\n! SET A NOMINAL UNIVERSAL VALUE OF GLACIAL-ICE SPECIFIC HEAT CAPACITY,\n!   HCPCT = 2100.0*900.0 = 1.89000E+6 (SOURCE:  BOB GRUMBINE, 2005)\n!   TBOT PASSED IN AS ARGUMENT, VALUE FROM GLOBAL DATA SET\n         !\n         ! A least-squares fit for the four points provided by\n         ! Keith Hines for the Yen (1981) values for Antarctic\n         ! snow firn.\n         !\n         HCPCT = 1.E6 * (0.8194 - 0.1309*0.5*ZSOIL(1))\n         DF1K = DF1\n      ENDIF\n\n! ----------------------------------------------------------------------\n! THE INPUT ARGUMENT DF1 IS A UNIVERSALLY CONSTANT VALUE OF SEA-ICE\n! THERMAL DIFFUSIVITY, SET IN ROUTINE SNOPAC AS DF1 = 2.2.\n! ----------------------------------------------------------------------\n! SET ICE PACK DEPTH.  USE TBOT AS ICE PACK LOWER BOUNDARY TEMPERATURE\n! (THAT OF UNFROZEN SEA WATER AT BOTTOM OF SEA ICE PACK).  ASSUME ICE\n! PACK IS OF N=NSOIL LAYERS SPANNING A UNIFORM CONSTANT ICE PACK\n! THICKNESS AS DEFINED BY ZSOIL(NSOIL) IN ROUTINE SFLX.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEFFICIENTS AI, BI, AND CI FOR THE TOP LAYER\n! ----------------------------------------------------------------------\n      IF (ICE == 1) THEN\n         ZBOT = ZSOIL (NSOIL)\n      ELSE IF (ICE == -1) THEN\n         ZBOT = -25.0\n      ENDIF\n      DDZ = 1.0 / ( -0.5 * ZSOIL (2) )\n      AI (1) = 0.0\n      CI (1) = (DF1 * DDZ) / (ZSOIL (1) * HCPCT)\n\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT BTWN THE TOP AND 2ND SOIL LAYERS.\n! RECALC/ADJUST THE SOIL HEAT FLUX.  USE THE GRADIENT AND FLUX TO CALC\n! RHSTS FOR THE TOP SOIL LAYER.\n! ----------------------------------------------------------------------\n      BI (1) = - CI (1) + DF1/ (0.5 * ZSOIL (1) * ZSOIL (1) * HCPCT *    &\n       ZZ1)\n      DTSDZ = ( STC (1) - STC (2) ) / ( -0.5 * ZSOIL (2) )\n      SSOIL = DF1 * ( STC (1) - YY ) / ( 0.5 * ZSOIL (1) * ZZ1 )\n\n! ----------------------------------------------------------------------\n! INITIALIZE DDZ2\n! ----------------------------------------------------------------------\n      RHSTS (1) = ( DF1 * DTSDZ - SSOIL ) / ( ZSOIL (1) * HCPCT )\n\n! ----------------------------------------------------------------------\n! LOOP THRU THE REMAINING SOIL LAYERS, REPEATING THE ABOVE PROCESS\n! ----------------------------------------------------------------------\n      DDZ2 = 0.0\n      DF1K = DF1\n      DF1N = DF1\n      DO K = 2,NSOIL\n\n       IF ( ICE == -1 ) THEN\n          ZMD = 0.5 * (ZSOIL(K)+ZSOIL(K-1))\n          ! For the land-ice case\n! kmh 09/03/2006 use Yen (1981)'s values for Antarctic snow firn\n!         IF ( K .eq. 2 ) HCPCT = 0.855108E6\n!         IF ( K .eq. 3 ) HCPCT = 0.922906E6\n!         IF ( K .eq. 4 ) HCPCT = 1.009986E6\n\n          ! Least squares fit to the four points supplied by Keith Hines\n          ! from Yen (1981) for Antarctic snow firn.  Not optimal, but\n          ! probably better than just a constant.\n          HCPCT = 1.E6 * ( 0.8194 - 0.1309*ZMD )\n\n!         IF ( K .eq. 2 ) DF1N = 0.345356\n!         IF ( K .eq. 3 ) DF1N = 0.398777\n!         IF ( K .eq. 4 ) DF1N = 0.472653\n\n          ! Least squares fit to the three points supplied by Keith Hines\n          ! from Yen (1981) for Antarctic snow firn.  Not optimal, but\n          ! probably better than just a constant.\n          DF1N = 0.32333 - ( 0.10073 * ZMD )\n       ENDIF\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT THRU THIS LAYER.\n! ----------------------------------------------------------------------\n         IF (K /= NSOIL) THEN\n            DENOM = 0.5 * ( ZSOIL (K -1) - ZSOIL (K +1) )\n\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEF, CI, AFTER CALC'NG ITS PARTIAL PRODUCT.\n! ----------------------------------------------------------------------\n            DTSDZ2 = ( STC (K) - STC (K +1) ) / DENOM\n            DDZ2 = 2. / (ZSOIL (K -1) - ZSOIL (K +1))\n            CI (K) = - DF1N * DDZ2 / ( (ZSOIL (K -1) - ZSOIL (K))*HCPCT)\n\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT THRU THE LOWEST LAYER.\n! ----------------------------------------------------------------------\n         ELSE\n\n! ----------------------------------------------------------------------\n! SET MATRIX COEF, CI TO ZERO.\n! ----------------------------------------------------------------------\n            DTSDZ2 = (STC (K) - TBOT)/ (.5 * (ZSOIL (K -1) + ZSOIL (K)) &\n                     - ZBOT)\n            CI (K) = 0.\n! ----------------------------------------------------------------------\n! CALC RHSTS FOR THIS LAYER AFTER CALC'NG A PARTIAL PRODUCT.\n! ----------------------------------------------------------------------\n         END IF\n         DENOM = ( ZSOIL (K) - ZSOIL (K -1) ) * HCPCT\n\n! ----------------------------------------------------------------------\n! CALC MATRIX COEFS, AI, AND BI FOR THIS LAYER.\n! ----------------------------------------------------------------------\n         RHSTS (K) = ( DF1N * DTSDZ2- DF1K * DTSDZ ) / DENOM\n         AI (K) = - DF1K * DDZ / ( (ZSOIL (K -1) - ZSOIL (K)) * HCPCT)\n\n! ----------------------------------------------------------------------\n! RESET VALUES OF DTSDZ AND DDZ FOR LOOP TO NEXT SOIL LYR.\n! ----------------------------------------------------------------------\n         BI (K) = - (AI (K) + CI (K))\n         DF1K = DF1N\n         DTSDZ = DTSDZ2\n         DDZ = DDZ2\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE HRTICE\n! ----------------------------------------------------------------------\n\n      SUBROUTINE HSTEP (STCOUT,STCIN,RHSTS,DT,NSOIL,AI,BI,CI)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE HSTEP\n! ----------------------------------------------------------------------\n! CALCULATE/UPDATE THE SOIL TEMPERATURE FIELD.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)  :: NSOIL\n      INTEGER              :: K\n\n      REAL, DIMENSION(1:NSOIL), INTENT(IN):: STCIN\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: STCOUT\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT):: RHSTS\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT):: AI,BI,CI\n      REAL, DIMENSION(1:NSOIL) :: RHSTSin\n      REAL, DIMENSION(1:NSOIL) :: CIin\n      REAL                 :: DT\n\n! ----------------------------------------------------------------------\n! CREATE FINITE DIFFERENCE VALUES FOR USE IN ROSR12 ROUTINE\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         RHSTS (K) = RHSTS (K) * DT\n         AI (K) = AI (K) * DT\n         BI (K) = 1. + BI (K) * DT\n         CI (K) = CI (K) * DT\n      END DO\n! ----------------------------------------------------------------------\n! COPY VALUES FOR INPUT VARIABLES BEFORE CALL TO ROSR12\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         RHSTSin (K) = RHSTS (K)\n      END DO\n      DO K = 1,NSOIL\n         CIin (K) = CI (K)\n      END DO\n! ----------------------------------------------------------------------\n! SOLVE THE TRI-DIAGONAL MATRIX EQUATION\n! ----------------------------------------------------------------------\n      CALL ROSR12 (CI,AI,BI,CIin,RHSTSin,RHSTS,NSOIL)\n! ----------------------------------------------------------------------\n! CALC/UPDATE THE SOIL TEMPS USING MATRIX SOLUTION\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         STCOUT (K) = STCIN (K) + CI (K)\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE HSTEP\n! ----------------------------------------------------------------------\n\n      SUBROUTINE NOPAC (ETP,ETA,PRCP,SMC,SMCMAX,SMCWLT,                 &\n                         SMCREF,SMCDRY,CMC,CMCMAX,NSOIL,DT,SHDFAC,      &\n                         SBETA,Q2,T1,SFCTMP,T24,TH2,FDOWN,F1,EMISSI,    &\n                         SSOIL,                                         &\n                         STC,EPSCA,BEXP,PC,RCH,RR,CFACTR,               &\n                         SH2O,SLOPE,KDT,FRZFACT,PSISAT,ZSOIL,           &\n                         DKSAT,DWSAT,TBOT,ZBOT,RUNOFF1,RUNOFF2,         &\n                         RUNOFF3,EDIR,EC,ET,ETT,NROOT,ICE,RTDIS,        &\n                         QUARTZ,FXEXP,CSOIL,                            &\n                         BETA,DRIP,DEW,FLX1,FLX3,VEGTYP,ISURBAN,        &\n!DJG NDHMS/WRF-Hydro edit...\n                         SFHEAD1RT,INFXS1RT,ETPND1,                     &\n\t\t         gwsoilcpl, qlowbdry)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE NOPAC\n! ----------------------------------------------------------------------\n! CALCULATE SOIL MOISTURE AND HEAT FLUX VALUES AND UPDATE SOIL MOISTURE\n! CONTENT AND SOIL HEAT CONTENT VALUES FOR THE CASE WHEN NO SNOW PACK IS\n! PRESENT.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)  :: ICE, NROOT,NSOIL,VEGTYP\n      INTEGER, INTENT(IN)  :: ISURBAN\n      INTEGER              :: K\n\n      REAL, INTENT(IN)     :: BEXP,CFACTR, CMCMAX,CSOIL,DKSAT,DT,DWSAT, &\n                              EPSCA,ETP,FDOWN,F1,FXEXP,FRZFACT,KDT,PC,  &\n                              PRCP,PSISAT,Q2,QUARTZ,RCH,RR,SBETA,SFCTMP,&\n                              SHDFAC,SLOPE,SMCDRY,SMCMAX,SMCREF,SMCWLT, &\n                              T24,TBOT,TH2,ZBOT,EMISSI\n      REAL, INTENT(INOUT)  :: CMC,BETA,T1\n      REAL, INTENT(OUT)    :: DEW,DRIP,EC,EDIR,ETA,ETT,FLX1,FLX3,       &\n                              RUNOFF1,RUNOFF2,RUNOFF3,SSOIL\n!DJG NDHMS/WRF-Hydro edit...\n      REAL, INTENT(INOUT)  :: SFHEAD1RT,INFXS1RT,ETPND1\n      real, intent(in)     :: qlowbdry\n      integer, intent(in) :: gwsoilcpl\n\n      REAL, DIMENSION(1:NSOIL),INTENT(IN)     :: RTDIS,ZSOIL\n      REAL, DIMENSION(1:NSOIL),INTENT(OUT)    :: ET\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SMC,SH2O,STC\n      REAL, DIMENSION(1:NSOIL) :: ET1\n      REAL                 :: EC1,EDIR1,ETT1,DF1,ETA1,ETP1,PRCP1,YY,    &\n                              YYNUM,ZZ1\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE:\n! CONVERT ETP Fnd PRCP FROM KG M-2 S-1 TO M S-1 AND INITIALIZE DEW.\n! ----------------------------------------------------------------------\n      PRCP1 = PRCP * 0.001\n      ETP1 = ETP * 0.001\n      DEW = 0.0\n! ----------------------------------------------------------------------\n! INITIALIZE EVAP TERMS.\n! ----------------------------------------------------------------------\n      EDIR = 0.\n      EDIR1 = 0.\n      EC1 = 0.\n      EC = 0.\n      DO K = 1,NSOIL\n        ET(K) = 0.\n        ET1(K) = 0.\n      END DO\n      ETT = 0.\n      ETT1 = 0.\n\n!DJG NDHMS/WRF-Hydro edit...\n      ETPND1 = 0.\n\n\n      IF (ETP > 0.0) THEN\n         CALL EVAPO (ETA1,SMC,NSOIL,CMC,ETP1,DT,ZSOIL,                  &\n                      SH2O,                                             &\n                      SMCMAX,BEXP,PC,SMCWLT,DKSAT,DWSAT,                &\n                      SMCREF,SHDFAC,CMCMAX,                             &\n                      SMCDRY,CFACTR,                                    &\n                       EDIR1,EC1,ET1,ETT1,SFCTMP,Q2,NROOT,RTDIS,FXEXP,  &\n                      SFHEAD1RT,ETPND1 )\n         CALL SMFLX (SMC,NSOIL,CMC,DT,PRCP1,ZSOIL,                      &\n                      SH2O,SLOPE,KDT,FRZFACT,                           &\n                      SMCMAX,BEXP,SMCWLT,DKSAT,DWSAT,                   &\n                      SHDFAC,CMCMAX,                                    &\n                      RUNOFF1,RUNOFF2,RUNOFF3,                          &\n                      EDIR1,EC1,ET1,                                    &\n                      DRIP, SFHEAD1RT,INFXS1RT,                         &\n\t\t      gwsoilcpl, qlowbdry)\n\n! ----------------------------------------------------------------------\n! CONVERT MODELED EVAPOTRANSPIRATION FROM  M S-1  TO  KG M-2 S-1.\n! ----------------------------------------------------------------------\n\n         ETA = ETA1 * 1000.0\n\n! ----------------------------------------------------------------------\n! IF ETP < 0, ASSUME DEW FORMS (TRANSFORM ETP1 INTO DEW AND REINITIALIZE\n! ETP1 TO ZERO).\n! ----------------------------------------------------------------------\n      ELSE\n         DEW = - ETP1\n\n! ----------------------------------------------------------------------\n! CONVERT PRCP FROM 'KG M-2 S-1' TO 'M S-1' AND ADD DEW AMOUNT.\n! ----------------------------------------------------------------------\n\n         PRCP1 = PRCP1+ DEW\n         CALL SMFLX (SMC,NSOIL,CMC,DT,PRCP1,ZSOIL,                      &\n                      SH2O,SLOPE,KDT,FRZFACT,                           &\n                      SMCMAX,BEXP,SMCWLT,DKSAT,DWSAT,                   &\n                      SHDFAC,CMCMAX,                                    &\n                      RUNOFF1,RUNOFF2,RUNOFF3,                          &\n                      EDIR1,EC1,ET1,                                    &\n                      DRIP, SFHEAD1RT,INFXS1RT,                         &\n\t\t      gwsoilcpl, qlowbdry)\n\n! ----------------------------------------------------------------------\n! CONVERT MODELED EVAPOTRANSPIRATION FROM 'M S-1' TO 'KG M-2 S-1'.\n! ----------------------------------------------------------------------\n!         ETA = ETA1 * 1000.0\n      END IF\n\n! ----------------------------------------------------------------------\n! BASED ON ETP AND E VALUES, DETERMINE BETA\n! ----------------------------------------------------------------------\n\n      IF ( ETP <= 0.0 ) THEN\n         BETA = 0.0\n         ETA = ETP\n         IF ( ETP < 0.0 ) THEN\n            BETA = 1.0\n         END IF\n      ELSE\n         BETA = ETA / ETP\n      END IF\n\n! ----------------------------------------------------------------------\n! CONVERT MODELED EVAPOTRANSPIRATION COMPONENTS 'M S-1' TO 'KG M-2 S-1'.\n! ----------------------------------------------------------------------\n      EDIR = EDIR1*1000.\n      EC = EC1*1000.\n      DO K = 1,NSOIL\n        ET(K) = ET1(K)*1000.\n      END DO\n      ETT = ETT1*1000.\n\n! ----------------------------------------------------------------------\n! GET SOIL THERMAL DIFFUXIVITY/CONDUCTIVITY FOR TOP SOIL LYR,\n! CALC. ADJUSTED TOP LYR SOIL TEMP AND ADJUSTED SOIL FLUX, THEN\n! CALL SHFLX TO COMPUTE/UPDATE SOIL HEAT FLUX AND SOIL TEMPS.\n! ----------------------------------------------------------------------\n\n      CALL TDFCND (DF1,SMC (1),QUARTZ,SMCMAX,SH2O (1))\n\n!urban\n      IF ( VEGTYP == ISURBAN ) DF1=3.24\n!\n\n! ----------------------------------------------------------------------\n! VEGETATION GREENNESS FRACTION REDUCTION IN SUBSURFACE HEAT FLUX\n! VIA REDUCTION FACTOR, WHICH IS CONVENIENT TO APPLY HERE TO THERMAL\n! DIFFUSIVITY THAT IS LATER USED IN HRT TO COMPUTE SUB SFC HEAT FLUX\n! (SEE ADDITIONAL COMMENTS ON VEG EFFECT SUB-SFC HEAT FLX IN\n! ROUTINE SFLX)\n! ----------------------------------------------------------------------\n      DF1 = DF1 * EXP (SBETA * SHDFAC)\n! ----------------------------------------------------------------------\n! COMPUTE INTERMEDIATE TERMS PASSED TO ROUTINE HRT (VIA ROUTINE\n! SHFLX BELOW) FOR USE IN COMPUTING SUBSURFACE HEAT FLUX IN HRT\n! ----------------------------------------------------------------------\n      YYNUM = FDOWN - EMISSI*SIGMA * T24\n      YY = SFCTMP + (YYNUM / RCH + TH2- SFCTMP - BETA * EPSCA) / RR\n\n      ZZ1 = DF1 / ( -0.5 * ZSOIL (1) * RCH * RR ) + 1.0\n\n!urban\n      CALL SHFLX (SSOIL,STC,SMC,SMCMAX,NSOIL,T1,DT,YY,ZZ1,ZSOIL,        &\n                  TBOT,ZBOT,SMCWLT,PSISAT,SH2O,BEXP,F1,DF1,ICE,         &\n                  QUARTZ,CSOIL,VEGTYP,ISURBAN)\n\n! ----------------------------------------------------------------------\n! SET FLX1 AND FLX3 (SNOPACK PHASE CHANGE HEAT FLUXES) TO ZERO SINCE\n! THEY ARE NOT USED HERE IN SNOPAC.  FLX2 (FREEZING RAIN HEAT FLUX) WAS\n! SIMILARLY INITIALIZED IN THE PENMAN ROUTINE.\n! ----------------------------------------------------------------------\n      FLX1 = CPH2O * PRCP * (T1- SFCTMP)\n      FLX3 = 0.0\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE NOPAC\n! ----------------------------------------------------------------------\n\n      SUBROUTINE PENMAN (SFCTMP,SFCPRS,CH,T2V,TH2,PRCP,FDOWN,T24,SSOIL, &\n     &                   Q2,Q2SAT,ETP,RCH,EPSCA,RR,SNOWNG,FRZGRA,       &\n     &              DQSDT2,FLX2,EMISSI_IN,SNEQV,T1,ICE,SNCOVR)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE PENMAN\n! ----------------------------------------------------------------------\n! CALCULATE POTENTIAL EVAPORATION FOR THE CURRENT POINT.  VARIOUS\n! PARTIAL SUMS/PRODUCTS ARE ALSO CALCULATED AND PASSED BACK TO THE\n! CALLING ROUTINE FOR LATER USE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      LOGICAL, INTENT(IN)     :: SNOWNG, FRZGRA\n      REAL, INTENT(IN)        :: CH, DQSDT2,FDOWN,PRCP,                 &\n                                 Q2, Q2SAT,SSOIL, SFCPRS, SFCTMP,       &\n                                 T2V, TH2,EMISSI_IN,SNEQV\n      REAL, INTENT(IN)        :: T1 , SNCOVR\n!\n! kmh 09/13/2006\n      INTEGER, INTENT(IN)     :: ICE\n! kmh 09/03/2006\n!\n      REAL, INTENT(OUT)       :: EPSCA,ETP,FLX2,RCH,RR,T24\n      REAL                    :: A, DELTA, FNET,RAD,RHO,EMISSI,ELCP1,LVS\n\n      REAL, PARAMETER      :: ELCP = 2.4888E+3, LSUBC = 2.501000E+6,CP = 1004.6\n      REAL, PARAMETER      :: LSUBS = 2.83E+6\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE:\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! PREPARE PARTIAL QUANTITIES FOR PENMAN EQUATION.\n! ----------------------------------------------------------------------\n        EMISSI=EMISSI_IN\n        IF (ICE==0) THEN\n           ELCP1  = (1.0-SNCOVR)*ELCP  + SNCOVR*ELCP*LSUBS/LSUBC\n           LVS    = (1.0-SNCOVR)*LSUBC + SNCOVR*LSUBS\n        ELSE\n           IF ( T1 > 273.15 ) THEN\n              ELCP1=ELCP\n              LVS=LSUBC\n           ELSE\n              ELCP1  = ELCP*LSUBS/LSUBC\n              LVS    = LSUBS\n           ENDIF\n        ENDIF\n\n      FLX2 = 0.0\n!      DELTA = ELCP * DQSDT2\n      DELTA = ELCP1 * DQSDT2\n      T24 = SFCTMP * SFCTMP * SFCTMP * SFCTMP\n!      RR = T24 * 6.48E-8 / (SFCPRS * CH) + 1.0\n      RR = EMISSI*T24 * 6.48E-8 / (SFCPRS * CH) + 1.0\n      RHO = SFCPRS / (RD * T2V)\n\n! ----------------------------------------------------------------------\n! ADJUST THE PARTIAL SUMS / PRODUCTS WITH THE LATENT HEAT\n! EFFECTS CAUSED BY FALLING PRECIPITATION.\n! ----------------------------------------------------------------------\n      RCH = RHO * CP * CH\n      IF (.NOT. SNOWNG) THEN\n         IF (PRCP >  0.0) RR = RR + CPH2O * PRCP / RCH\n      ELSE\n         RR = RR + CPICE * PRCP / RCH\n      END IF\n\n! ----------------------------------------------------------------------\n! INCLUDE THE LATENT HEAT EFFECTS OF FRZNG RAIN CONVERTING TO ICE ON\n! IMPACT IN THE CALCULATION OF FLX2 AND FNET.\n! ----------------------------------------------------------------------\n!      FNET = FDOWN - SIGMA * T24- SSOIL\n      FNET = FDOWN -  EMISSI*SIGMA * T24- SSOIL\n      IF (FRZGRA) THEN\n         FLX2 = - LSUBF * PRCP\n         FNET = FNET - FLX2\n! ----------------------------------------------------------------------\n! FINISH PENMAN EQUATION CALCULATIONS.\n! ----------------------------------------------------------------------\n      END IF\n      RAD = FNET / RCH + TH2- SFCTMP\n!      A = ELCP * (Q2SAT - Q2)\n      A = ELCP1 * (Q2SAT - Q2)\n      EPSCA = (A * RR + RAD * DELTA) / (DELTA + RR)\n!      ETP = EPSCA * RCH / LSUBC\n      ETP = EPSCA * RCH / LVS\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE PENMAN\n! ----------------------------------------------------------------------\n\n      SUBROUTINE REDPRM (VEGTYP,SOILTYP,SLOPETYP,CFACTR,CMCMAX,RSMAX,      &\n                         TOPT,                                             &\n                         REFKDT,KDT,SBETA, SHDFAC,RSMIN,RGL,HS,ZBOT,FRZX,  &\n                         PSISAT,SLOPE,SNUP,SALP,BEXP,DKSAT,DWSAT,          &\n                         SMCMAX,SMCWLT,SMCREF,SMCDRY,F1,QUARTZ,FXEXP,      &\n                         RTDIS,SLDPTH,ZSOIL, NROOT,NSOIL,CZIL,             &\n                         LAIMIN, LAIMAX, EMISSMIN, EMISSMAX, ALBEDOMIN,    &\n                         ALBEDOMAX, Z0MIN, Z0MAX, CSOIL, PTU, LLANDUSE,    &\n                         LSOIL, LOCAL,LVCOEF)\n\n      IMPLICIT NONE\n! ----------------------------------------------------------------------\n! Internally set (default valuess)\n! all soil and vegetation parameters required for the execusion oF\n! the Noah lsm are defined in VEGPARM.TBL, SOILPARM.TB, and GENPARM.TBL.\n! ----------------------------------------------------------------------\n!     Vegetation parameters:\n!             ALBBRD: SFC background snow-free albedo\n!             CMXTBL: MAX CNPY Capacity\n!              Z0BRD: Background roughness length\n!             SHDFAC: Green vegetation fraction\n!              NROOT: Rooting depth\n!              RSMIN: Mimimum stomatal resistance\n!              RSMAX: Max. stomatal resistance\n!                RGL: Parameters used in radiation stress function\n!                 HS: Parameter used in vapor pressure deficit functio\n!               TOPT: Optimum transpiration air temperature.\n!             CMCMAX: Maximum canopy water capacity\n!             CFACTR: Parameter used in the canopy inteception calculation\n!               SNUP: Threshold snow depth (in water equivalent m) that\n!                     implies 100 percent snow cover\n!                LAI: Leaf area index\n!\n! ----------------------------------------------------------------------\n!      Soil parameters:\n!        SMCMAX: MAX soil moisture content (porosity)\n!        SMCREF: Reference soil moisture  (field capacity)\n!        SMCWLT: Wilting point soil moisture\n!        SMCWLT: Air dry soil moist content limits\n!       SSATPSI: SAT (saturation) soil potential\n!         DKSAT: SAT soil conductivity\n!          BEXP: B parameter\n!        SSATDW: SAT soil diffusivity\n!           F1: Soil thermal diffusivity/conductivity coef.\n!        QUARTZ: Soil quartz content\n!  Modified by F. Chen (12/22/97)  to use the STATSGO soil map\n!  Modified By F. Chen (01/22/00)  to include PLaya, Lava, and White San\n!  Modified By F. Chen (08/05/02)  to include additional parameters for the Noah\n! NOTE: SATDW = BB*SATDK*(SATPSI/MAXSMC)\n!         F11 = ALOG10(SATPSI) + BB*ALOG10(MAXSMC) + 2.0\n!       REFSMC1=MAXSMC*(5.79E-9/SATDK)**(1/(2*BB+3)) 5.79E-9 m/s= 0.5 mm\n!       REFSMC=REFSMC1+1./3.(MAXSMC-REFSMC1)\n!       WLTSMC1=MAXSMC*(200./SATPSI)**(-1./BB)    (Wetzel and Chang, 198\n!       WLTSMC=WLTSMC1-0.5*WLTSMC1\n! Note: the values for playa is set for it to have a thermal conductivit\n! as sand and to have a hydrulic conductivity as clay\n!\n! ----------------------------------------------------------------------\n! Class parameter 'SLOPETYP' was included to estimate linear reservoir\n! coefficient 'SLOPE' to the baseflow runoff out of the bottom layer.\n! lowest class (slopetyp=0) means highest slope parameter = 1.\n! definition of slopetyp from 'zobler' slope type:\n! slope class  percent slope\n! 1            0-8\n! 2            8-30\n! 3            > 30\n! 4            0-30\n! 5            0-8 & > 30\n! 6            8-30 & > 30\n! 7            0-8, 8-30, > 30\n! 9            GLACIAL ICE\n! BLANK        OCEAN/SEA\n!       SLOPE_DATA: linear reservoir coefficient\n!       SBETA_DATA: parameter used to caluculate vegetation effect on soil heat\n!       FXEXP_DAT:  soil evaporation exponent used in DEVAP\n!       CSOIL_DATA: soil heat capacity [J M-3 K-1]\n!       SALP_DATA: shape parameter of  distribution function of snow cover\n!       REFDK_DATA and REFKDT_DATA: parameters in the surface runoff parameteriz\n!       FRZK_DATA: frozen ground parameter\n!       ZBOT_DATA: depth[M] of lower boundary soil temperature\n!       CZIL_DATA: calculate roughness length of heat\n!       SMLOW_DATA and MHIGH_DATA: two soil moisture wilt, soil moisture referen\n!                 parameters\n! Set maximum number of soil-, veg-, and slopetyp in data statement.\n! ----------------------------------------------------------------------\n      INTEGER, PARAMETER     :: MAX_SLOPETYP=30,MAX_SOILTYP=30,MAX_VEGTYP=30\n      LOGICAL                :: LOCAL\n      CHARACTER (LEN=256), INTENT(IN)::  LLANDUSE, LSOIL\n\n! Veg parameters\n      INTEGER, INTENT(IN)    :: VEGTYP\n      INTEGER, INTENT(OUT)   :: NROOT\n      REAL, INTENT(INOUT)    :: SHDFAC\n      REAL, INTENT(OUT)      :: HS,RSMIN,RGL,SNUP,                          &\n                                CMCMAX,RSMAX,TOPT,                          &\n                                EMISSMIN,  EMISSMAX,                        &\n                                LAIMIN,    LAIMAX,                          &\n                                Z0MIN,     Z0MAX,                           &\n                                ALBEDOMIN, ALBEDOMAX\n! Soil parameters\n      INTEGER, INTENT(IN)    :: SOILTYP\n      REAL, INTENT(OUT)      :: BEXP,DKSAT,DWSAT,F1,QUARTZ,SMCDRY,          &\n                                SMCMAX,SMCREF,SMCWLT,PSISAT\n! General parameters\n      INTEGER, INTENT(IN)    :: SLOPETYP,NSOIL\n      INTEGER                :: I\n\n      REAL,    INTENT(OUT)   :: SLOPE,CZIL,SBETA,FXEXP,                     &\n                                CSOIL,SALP,FRZX,KDT,CFACTR,      &\n                                ZBOT,REFKDT,PTU\n      REAL,    INTENT(OUT)   :: LVCOEF\n      REAL,DIMENSION(1:NSOIL),INTENT(IN) :: SLDPTH,ZSOIL\n      REAL,DIMENSION(1:NSOIL),INTENT(OUT):: RTDIS\n      REAL                   :: FRZFACT,FRZK,REFDK\n\n!      SAVE\n! ----------------------------------------------------------------------\n!\n               IF (SOILTYP .gt. SLCATS) THEN\n                        CALL wrf_error_fatal ( 'Warning: too many input soil types' )\n                   write(6,*) \"SOILTYP, SLCATS \",SOILTYP, SLCATS\n               END IF\n               IF (VEGTYP .gt. LUCATS) THEN\n                     CALL wrf_error_fatal ( 'Warning: too many input landuse types' )\n               END IF\n               IF (SLOPETYP .gt. SLPCATS) THEN\n                     CALL wrf_error_fatal ( 'Warning: too many input slope types' )\n                     write(6,*) \"SLOPETYP , SLPCATS \", SLOPETYP , SLPCATS\n               END IF\n\n! ----------------------------------------------------------------------\n!  SET-UP SOIL PARAMETERS\n! ----------------------------------------------------------------------\n      CSOIL = CSOIL_DATA\n      BEXP = BB (SOILTYP)\n      DKSAT = SATDK (SOILTYP)\n      DWSAT = SATDW (SOILTYP)\n      F1 = F11 (SOILTYP)\n      PSISAT = SATPSI (SOILTYP)\n      QUARTZ = QTZ (SOILTYP)\n      SMCDRY = DRYSMC (SOILTYP)\n      SMCMAX = MAXSMC (SOILTYP)\n      SMCREF = REFSMC (SOILTYP)\n      SMCWLT = WLTSMC (SOILTYP)\n! ----------------------------------------------------------------------\n! Set-up universal parameters (not dependent on SOILTYP, VEGTYP or\n! SLOPETYP)\n! ----------------------------------------------------------------------\n      ZBOT = ZBOT_DATA\n      SALP = SALP_DATA\n      SBETA = SBETA_DATA\n      REFDK = REFDK_DATA\n      FRZK = FRZK_DATA\n      FXEXP = FXEXP_DATA\n      REFKDT = REFKDT_DATA\n      PTU = 0.    ! (not used yet) to satisify intent(out)\n      KDT = REFKDT * DKSAT / REFDK\n      CZIL = CZIL_DATA\n      SLOPE = SLOPE_DATA (SLOPETYP)\n      LVCOEF = LVCOEF_DATA\n\n! ----------------------------------------------------------------------\n! TO ADJUST FRZK PARAMETER TO ACTUAL SOIL TYPE: FRZK * FRZFACT\n! ----------------------------------------------------------------------\n      FRZFACT = (SMCMAX / SMCREF) * (0.412 / 0.468)\n      FRZX = FRZK * FRZFACT\n\n! ----------------------------------------------------------------------\n! SET-UP VEGETATION PARAMETERS\n! ----------------------------------------------------------------------\n      TOPT = TOPT_DATA\n      CMCMAX = CMCMAX_DATA\n      CFACTR = CFACTR_DATA\n      RSMAX = RSMAX_DATA\n      NROOT = NROTBL (VEGTYP)\n      SNUP = SNUPTBL (VEGTYP)\n      RSMIN = RSTBL (VEGTYP)\n      RGL = RGLTBL (VEGTYP)\n      HS = HSTBL (VEGTYP)\n      EMISSMIN  = EMISSMINTBL  (VEGTYP)\n      EMISSMAX  = EMISSMAXTBL  (VEGTYP)\n      LAIMIN    = LAIMINTBL    (VEGTYP)\n      LAIMAX    = LAIMAXTBL    (VEGTYP)\n      Z0MIN     = Z0MINTBL     (VEGTYP)\n      Z0MAX     = Z0MAXTBL     (VEGTYP)\n      ALBEDOMIN = ALBEDOMINTBL (VEGTYP)\n      ALBEDOMAX = ALBEDOMAXTBL (VEGTYP)\n\n               IF (VEGTYP .eq. BARE) SHDFAC = 0.0\n               IF (NROOT .gt. NSOIL) THEN\n                  WRITE (err_message,*) 'Error: too many root layers ',  &\n                                                 NSOIL,NROOT\n                  CALL wrf_error_fatal ( err_message )\n! ----------------------------------------------------------------------\n! CALCULATE ROOT DISTRIBUTION.  PRESENT VERSION ASSUMES UNIFORM\n! DISTRIBUTION BASED ON SOIL LAYER DEPTHS.\n! ----------------------------------------------------------------------\n               END IF\n               DO I = 1,NROOT\n                  RTDIS (I) = - SLDPTH (I)/ ZSOIL (NROOT)\n! ----------------------------------------------------------------------\n!  SET-UP SLOPE PARAMETER\n! ----------------------------------------------------------------------\n               END DO\n\n!        print*,'end of PRMRED'\n!       print*,'VEGTYP',VEGTYP,'SOILTYP',SOILTYP,'SLOPETYP',SLOPETYP,    &\n!    & 'CFACTR',CFACTR,'CMCMAX',CMCMAX,'RSMAX',RSMAX,'TOPT',TOPT,        &\n!    & 'REFKDT',REFKDT,'KDT',KDT,'SBETA',SBETA, 'SHDFAC',SHDFAC,         &\n!    &  'RSMIN',RSMIN,'RGL',RGL,'HS',HS,'ZBOT',ZBOT,'FRZX',FRZX,         &\n!    &  'PSISAT',PSISAT,'SLOPE',SLOPE,'SNUP',SNUP,'SALP',SALP,'BEXP',    &\n!    &   BEXP,                                                           &\n!    &  'DKSAT',DKSAT,'DWSAT',DWSAT,                                     &\n!    &  'SMCMAX',SMCMAX,'SMCWLT',SMCWLT,'SMCREF',SMCREF,'SMCDRY',SMCDRY, &\n!    &  'F1',F1,'QUARTZ',QUARTZ,'FXEXP',FXEXP,                           &\n!    &  'RTDIS',RTDIS,'SLDPTH',SLDPTH,'ZSOIL',ZSOIL, 'NROOT',NROOT,      &\n!    &  'NSOIL',NSOIL,'Z0',Z0,'CZIL',CZIL,'LAI',LAI,                     &\n!    &  'CSOIL',CSOIL,'PTU',PTU,                                         &\n!    &  'LOCAL', LOCAL\n\n      END  SUBROUTINE REDPRM\n\n      SUBROUTINE ROSR12 (P,A,B,C,D,DELTA,NSOIL)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE ROSR12\n! ----------------------------------------------------------------------\n! INVERT (SOLVE) THE TRI-DIAGONAL MATRIX PROBLEM SHOWN BELOW:\n! ###                                            ### ###  ###   ###  ###\n! #B(1), C(1),  0  ,  0  ,  0  ,   . . .  ,    0   # #      #   #      #\n! #A(2), B(2), C(2),  0  ,  0  ,   . . .  ,    0   # #      #   #      #\n! # 0  , A(3), B(3), C(3),  0  ,   . . .  ,    0   # #      #   # D(3) #\n! # 0  ,  0  , A(4), B(4), C(4),   . . .  ,    0   # # P(4) #   # D(4) #\n! # 0  ,  0  ,  0  , A(5), B(5),   . . .  ,    0   # # P(5) #   # D(5) #\n! # .                                          .   # #  .   # = #   .  #\n! # .                                          .   # #  .   #   #   .  #\n! # .                                          .   # #  .   #   #   .  #\n! # 0  , . . . , 0 , A(M-2), B(M-2), C(M-2),   0   # #P(M-2)#   #D(M-2)#\n! # 0  , . . . , 0 ,   0   , A(M-1), B(M-1), C(M-1)# #P(M-1)#   #D(M-1)#\n! # 0  , . . . , 0 ,   0   ,   0   ,  A(M) ,  B(M) # # P(M) #   # D(M) #\n! ###                                            ### ###  ###   ###  ###\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: NSOIL\n      INTEGER               :: K, KK\n\n      REAL, DIMENSION(1:NSOIL), INTENT(IN):: A, B, D\n      REAL, DIMENSION(1:NSOIL),INTENT(INOUT):: C,P,DELTA\n\n! ----------------------------------------------------------------------\n! INITIALIZE EQN COEF C FOR THE LOWEST SOIL LAYER\n! ----------------------------------------------------------------------\n      C (NSOIL) = 0.0\n      P (1) = - C (1) / B (1)\n! ----------------------------------------------------------------------\n! SOLVE THE COEFS FOR THE 1ST SOIL LAYER\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! SOLVE THE COEFS FOR SOIL LAYERS 2 THRU NSOIL\n! ----------------------------------------------------------------------\n      DELTA (1) = D (1) / B (1)\n      DO K = 2,NSOIL\n         P (K) = - C (K) * ( 1.0 / (B (K) + A (K) * P (K -1)) )\n         DELTA (K) = (D (K) - A (K)* DELTA (K -1))* (1.0/ (B (K) + A (K)&\n                    * P (K -1)))\n      END DO\n! ----------------------------------------------------------------------\n! SET P TO DELTA FOR LOWEST SOIL LAYER\n! ----------------------------------------------------------------------\n      P (NSOIL) = DELTA (NSOIL)\n\n! ----------------------------------------------------------------------\n! ADJUST P FOR SOIL LAYERS 2 THRU NSOIL\n! ----------------------------------------------------------------------\n      DO K = 2,NSOIL\n         KK = NSOIL - K + 1\n         P (KK) = P (KK) * P (KK +1) + DELTA (KK)\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE ROSR12\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE SHFLX (SSOIL,STC,SMC,SMCMAX,NSOIL,T1,DT,YY,ZZ1,ZSOIL,  &\n                         TBOT,ZBOT,SMCWLT,PSISAT,SH2O,BEXP,F1,DF1,ICE,  &\n                         QUARTZ,CSOIL,VEGTYP,ISURBAN)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SHFLX\n! ----------------------------------------------------------------------\n! UPDATE THE TEMPERATURE STATE OF THE SOIL COLUMN BASED ON THE THERMAL\n! DIFFUSION EQUATION AND UPDATE THE FROZEN SOIL MOISTURE CONTENT BASED\n! ON THE TEMPERATURE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: ICE, NSOIL, VEGTYP, ISURBAN\n      INTEGER               :: I\n\n      REAL, INTENT(IN)      :: BEXP,CSOIL,DF1,DT,F1,PSISAT,QUARTZ,     &\n                               SMCMAX, SMCWLT, TBOT,YY, ZBOT,ZZ1\n      REAL, INTENT(INOUT)   :: T1\n      REAL, INTENT(OUT)     :: SSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)    :: SMC,ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SH2O\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: STC\n      REAL, DIMENSION(1:NSOIL)             :: AI, BI, CI, STCF,RHSTS\n      REAL, PARAMETER       :: T0 = 273.15\n\n! ----------------------------------------------------------------------\n! HRT ROUTINE CALCS THE RIGHT HAND SIDE OF THE SOIL TEMP DIF EQN\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! SEA-ICE CASE, GLACIAL ICE CASE\n! ----------------------------------------------------------------------\n      IF ( ICE /= 0 ) THEN\n\n         CALL HRTICE (RHSTS,STC,TBOT,ICE,NSOIL,ZSOIL,YY,ZZ1,DF1,AI,BI,CI)\n\n         CALL HSTEP (STCF,STC,RHSTS,DT,NSOIL,AI,BI,CI)\n\n! ----------------------------------------------------------------------\n! LAND-MASS CASE\n! ----------------------------------------------------------------------\n      ELSE\n         CALL HRT (RHSTS,STC,SMC,SMCMAX,NSOIL,ZSOIL,YY,ZZ1,TBOT,        &\n                    ZBOT,PSISAT,SH2O,DT,                                &\n                    BEXP,F1,DF1,QUARTZ,CSOIL,AI,BI,CI,VEGTYP,ISURBAN)\n\n         CALL HSTEP (STCF,STC,RHSTS,DT,NSOIL,AI,BI,CI)\n      END IF\n      DO I = 1,NSOIL\n         STC (I) = STCF (I)\n      END DO\n\n! ----------------------------------------------------------------------\n! IN THE NO SNOWPACK CASE (VIA ROUTINE NOPAC BRANCH,) UPDATE THE GRND\n! (SKIN) TEMPERATURE HERE IN RESPONSE TO THE UPDATED SOIL TEMPERATURE\n! PROFILE ABOVE.  (NOTE: INSPECTION OF ROUTINE SNOPAC SHOWS THAT T1\n! BELOW IS A DUMMY VARIABLE ONLY, AS SKIN TEMPERATURE IS UPDATED\n! DIFFERENTLY IN ROUTINE SNOPAC)\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! CALCULATE SURFACE SOIL HEAT FLUX\n! ----------------------------------------------------------------------\n      T1 = (YY + (ZZ1- 1.0) * STC (1)) / ZZ1\n      SSOIL = DF1 * (STC (1) - T1) / (0.5 * ZSOIL (1))\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SHFLX\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SMFLX (SMC,NSOIL,CMC,DT,PRCP1,ZSOIL,                   &\n     &                   SH2O,SLOPE,KDT,FRZFACT,                        &\n     &                   SMCMAX,BEXP,SMCWLT,DKSAT,DWSAT,                &\n     &                   SHDFAC,CMCMAX,                                 &\n     &                   RUNOFF1,RUNOFF2,RUNOFF3,                       &\n     &                   EDIR,EC,ET,                                    &\n     &                   DRIP, SFHEAD1RT,INFXS1RT,                      &\n\t                 gwsoilcpl, qlowbdry)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SMFLX\n! ----------------------------------------------------------------------\n! CALCULATE SOIL MOISTURE FLUX.  THE SOIL MOISTURE CONTENT (SMC - A PER\n! UNIT VOLUME MEASUREMENT) IS A DEPENDENT VARIABLE THAT IS UPDATED WITH\n! PROGNOSTIC EQNS. THE CANOPY MOISTURE CONTENT (CMC) IS ALSO UPDATED.\n! FROZEN GROUND VERSION:  NEW STATES ADDED: SH2O, AND FROZEN GROUND\n! CORRECTION FACTOR, FRZFACT AND PARAMETER SLOPE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: NSOIL\n      INTEGER               :: I,K\n\n      REAL, INTENT(IN)      :: BEXP, CMCMAX, DKSAT,DWSAT, DT, EC, EDIR,  &\n                               KDT, PRCP1, SHDFAC, SLOPE, SMCMAX, SMCWLT\n      REAL, INTENT(OUT)                      :: DRIP, RUNOFF1, RUNOFF2, RUNOFF3\n      REAL, INTENT(INOUT)   :: CMC\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: ET,ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT):: SMC, SH2O\n      REAL, DIMENSION(1:NSOIL)             :: AI, BI, CI, STCF,RHSTS, RHSTT, &\n                                              SICE, SH2OA, SH2OFG\n      REAL                  :: DUMMY, EXCESS,FRZFACT,PCPDRP,RHSCT,TRHSCT\n      REAL :: FAC2\n      REAL :: FLIMIT\n\n      REAL,    INTENT(INOUT)                 :: SFHEAD1RT,INFXS1RT\n      real, intent(in)                       :: qlowbdry\n      integer, intent(in)                    :: gwsoilcpl\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! COMPUTE THE RIGHT HAND SIDE OF THE CANOPY EQN TERM ( RHSCT )\n! ----------------------------------------------------------------------\n      DUMMY = 0.\n\n! ----------------------------------------------------------------------\n! CONVERT RHSCT (A RATE) TO TRHSCT (AN AMOUNT) AND ADD IT TO EXISTING\n! CMC.  IF RESULTING AMT EXCEEDS MAX CAPACITY, IT BECOMES DRIP AND WILL\n! FALL TO THE GRND.\n! ----------------------------------------------------------------------\n      RHSCT = SHDFAC * PRCP1- EC\n      DRIP = 0.\n      TRHSCT = DT * RHSCT\n      EXCESS = CMC + TRHSCT\n\n! ----------------------------------------------------------------------\n! PCPDRP IS THE COMBINED PRCP1 AND DRIP (FROM CMC) THAT GOES INTO THE\n! SOIL\n! ----------------------------------------------------------------------\n      IF (EXCESS > CMCMAX) DRIP = EXCESS - CMCMAX\n      PCPDRP = (1. - SHDFAC) * PRCP1+ DRIP / DT\n\n! ----------------------------------------------------------------------\n! STORE ICE CONTENT AT EACH SOIL LAYER BEFORE CALLING SRT and SSTEP\n!\n      DO I = 1,NSOIL\n         SICE (I) = SMC (I) - SH2O (I)\n      END DO\n! ----------------------------------------------------------------------\n! CALL SUBROUTINES SRT AND SSTEP TO SOLVE THE SOIL MOISTURE\n! TENDENCY EQUATIONS.\n! IF THE INFILTRATING PRECIP RATE IS NONTRIVIAL,\n!   (WE CONSIDER NONTRIVIAL TO BE A PRECIP TOTAL OVER THE TIME STEP\n!    EXCEEDING ONE ONE-THOUSANDTH OF THE WATER HOLDING CAPACITY OF\n!    THE FIRST SOIL LAYER)\n! THEN CALL THE SRT/SSTEP SUBROUTINE PAIR TWICE IN THE MANNER OF\n!   TIME SCHEME \"F\" (IMPLICIT STATE, AVERAGED COEFFICIENT)\n!   OF SECTION 2 OF KALNAY AND KANAMITSU (1988, MWR, VOL 116,\n!   PAGES 1945-1958)TO MINIMIZE 2-DELTA-T OSCILLATIONS IN THE\n!   SOIL MOISTURE VALUE OF THE TOP SOIL LAYER THAT CAN ARISE BECAUSE\n!   OF THE EXTREME NONLINEAR DEPENDENCE OF THE SOIL HYDRAULIC\n!   DIFFUSIVITY COEFFICIENT AND THE HYDRAULIC CONDUCTIVITY ON THE\n!   SOIL MOISTURE STATE\n! OTHERWISE CALL THE SRT/SSTEP SUBROUTINE PAIR ONCE IN THE MANNER OF\n!   TIME SCHEME \"D\" (IMPLICIT STATE, EXPLICIT COEFFICIENT)\n!   OF SECTION 2 OF KALNAY AND KANAMITSU\n! PCPDRP IS UNITS OF KG/M**2/S OR MM/S, ZSOIL IS NEGATIVE DEPTH IN M\n! ----------------------------------------------------------------------\n!  According to Dr. Ken Mitchell's suggestion, add the second contraint\n!  to remove numerical instability of runoff and soil moisture\n!  FLIMIT is a limit value for FAC2\n      FAC2=0.0\n      DO I=1,NSOIL\n         FAC2=MAX(FAC2,SH2O(I)/SMCMAX)\n      ENDDO\n      CALL FAC2MIT(SMCMAX,FLIMIT)\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! SMC STATES REPLACED BY SH2O STATES IN SRT SUBR.  SH2O & SICE STATES\n! INC&UDED IN SSTEP SUBR.  FROZEN GROUND CORRECTION FACTOR, FRZFACT\n! ADDED.  ALL WATER BALANCE CALCULATIONS USING UNFROZEN WATER\n! ----------------------------------------------------------------------\n\n!DJG NDHMS/WRF-Hydro edit... Add previous ponded water to new precip drip...\n    PCPDRP = PCPDRP + SFHEAD1RT/1000./DT   ! convert SFHEAD1RT to (m/s)\n\n\n      IF ( ( (PCPDRP * DT) > (0.0001*1000.0* (- ZSOIL (1))* SMCMAX) )   &\n           .OR. (FAC2 > FLIMIT) ) THEN\n         CALL SRT (RHSTT,EDIR,ET,SH2O,SH2O,NSOIL,PCPDRP,ZSOIL,          &\n                    DWSAT,DKSAT,SMCMAX,BEXP,RUNOFF1,                    &\n                    RUNOFF2,DT,SMCWLT,SLOPE,KDT,FRZFACT,SICE,AI,BI,CI,  &\n                    SFHEAD1RT,INFXS1RT, &\n\t\t    gwsoilcpl, qlowbdry)\n         CALL SSTEP (SH2OFG,SH2O,DUMMY,RHSTT,RHSCT,DT,NSOIL,SMCMAX,     &\n                        CMCMAX,RUNOFF3,ZSOIL,SMC,SICE,AI,BI,CI,INFXS1RT)\n         DO K = 1,NSOIL\n            SH2OA (K) = (SH2O (K) + SH2OFG (K)) * 0.5\n         END DO\n         CALL SRT (RHSTT,EDIR,ET,SH2O,SH2OA,NSOIL,PCPDRP,ZSOIL,         &\n                    DWSAT,DKSAT,SMCMAX,BEXP,RUNOFF1,                    &\n                    RUNOFF2,DT,SMCWLT,SLOPE,KDT,FRZFACT,SICE,AI,BI,CI,  &\n                    SFHEAD1RT,INFXS1RT, &\n\t\t    gwsoilcpl, qlowbdry)\n         CALL SSTEP (SH2O,SH2O,CMC,RHSTT,RHSCT,DT,NSOIL,SMCMAX,         &\n                        CMCMAX,RUNOFF3,ZSOIL,SMC,SICE,AI,BI,CI,INFXS1RT)\n\n      ELSE\n         CALL SRT (RHSTT,EDIR,ET,SH2O,SH2O,NSOIL,PCPDRP,ZSOIL,          &\n                    DWSAT,DKSAT,SMCMAX,BEXP,RUNOFF1,                    &\n                    RUNOFF2,DT,SMCWLT,SLOPE,KDT,FRZFACT,SICE,AI,BI,CI,  &\n                   SFHEAD1RT,INFXS1RT, &\n\t\t    gwsoilcpl, qlowbdry)\n         CALL SSTEP (SH2O,SH2O,CMC,RHSTT,RHSCT,DT,NSOIL,SMCMAX,         &\n                     CMCMAX,RUNOFF3,ZSOIL,SMC,SICE,AI,BI,CI,INFXS1RT)\n!      RUNOF = RUNOFF\n\n      END IF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SMFLX\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE SNFRAC (SNEQV,SNUP,SALP,SNOWH,SNCOVR)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNFRAC\n! ----------------------------------------------------------------------\n! CALCULATE SNOW FRACTION (0 -> 1)\n! SNEQV   SNOW WATER EQUIVALENT (M)\n! SNUP    THRESHOLD SNEQV DEPTH ABOVE WHICH SNCOVR=1\n! SALP    TUNING PARAMETER\n! SNCOVR  FRACTIONAL SNOW COVER\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      REAL, INTENT(IN)     :: SNEQV,SNUP,SALP,SNOWH\n      REAL, INTENT(OUT)    :: SNCOVR\n      REAL                 :: RSNOW, Z0N\n\n! ----------------------------------------------------------------------\n! SNUP IS VEG-CLASS DEPENDENT SNOWDEPTH THRESHHOLD (SET IN ROUTINE\n! REDPRM) ABOVE WHICH SNOCVR=1.\n! ----------------------------------------------------------------------\n      IF (SNEQV < SNUP) THEN\n         RSNOW = SNEQV / SNUP\n         SNCOVR = 1. - ( EXP ( - SALP * RSNOW) - RSNOW * EXP ( - SALP))\n      ELSE\n         SNCOVR = 1.0\n      END IF\n\n!     FORMULATION OF DICKINSON ET AL. 1986\n!     Z0N = 0.035\n\n!        SNCOVR=SNOWH/(SNOWH + 5*Z0N)\n\n!     FORMULATION OF MARSHALL ET AL. 1994\n!        SNCOVR=SNEQV/(SNEQV + 2*Z0N)\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNFRAC\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SNKSRC (TSNSR,TAVG,SMC,SH2O,ZSOIL,NSOIL,               &\n     &                      SMCMAX,PSISAT,BEXP,DT,K,QTOT)\n! ----------------------------------------------------------------------\n! SUBROUTINE SNKSRC\n! ----------------------------------------------------------------------\n! CALCULATE SINK/SOURCE TERM OF THE TERMAL DIFFUSION EQUATION. (SH2O) IS\n! AVAILABLE LIQUED WATER.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: K,NSOIL\n      REAL, INTENT(IN)      :: BEXP, DT, PSISAT, QTOT, SMC, SMCMAX,    &\n                               TAVG\n      REAL, INTENT(INOUT)   :: SH2O\n\n      REAL, DIMENSION(1:NSOIL), INTENT(IN):: ZSOIL\n\n      REAL                  :: DF, DZ, DZH, FREE, TSNSR,               &\n                               TDN, TM, TUP, TZ, X0, XDN, XH2O, XUP\n\n      REAL, PARAMETER       :: DH2O = 1.0000E3, HLICE = 3.3350E5,      &\n                               T0 = 2.7315E2\n\n      IF (K == 1) THEN\n         DZ = - ZSOIL (1)\n      ELSE\n         DZ = ZSOIL (K -1) - ZSOIL (K)\n      END IF\n! ----------------------------------------------------------------------\n! VIA FUNCTION FRH2O, COMPUTE POTENTIAL OR 'EQUILIBRIUM' UNFROZEN\n! SUPERCOOLED FREE WATER FOR GIVEN SOIL TYPE AND SOIL LAYER TEMPERATURE.\n! FUNCTION FRH20 INVOKES EQN (17) FROM V. KOREN ET AL (1999, JGR, VOL.\n! 104, PG 19573).  (ASIDE:  LATTER EQN IN JOURNAL IN CENTIGRADE UNITS.\n! ROUTINE FRH2O USE FORM OF EQN IN KELVIN UNITS.)\n! ----------------------------------------------------------------------\n!      FREE = FRH2O(TAVG,SMC,SH2O,SMCMAX,BEXP,PSISAT)\n\n! ----------------------------------------------------------------------\n! IN NEXT BLOCK OF CODE, INVOKE EQN 18 OF V. KOREN ET AL (1999, JGR,\n! VOL. 104, PG 19573.)  THAT IS, FIRST ESTIMATE THE NEW AMOUNTOF LIQUID\n! WATER, 'XH2O', IMPLIED BY THE SUM OF (1) THE LIQUID WATER AT THE BEGIN\n! OF CURRENT TIME STEP, AND (2) THE FREEZE OF THAW CHANGE IN LIQUID\n! WATER IMPLIED BY THE HEAT FLUX 'QTOT' PASSED IN FROM ROUTINE HRT.\n! SECOND, DETERMINE IF XH2O NEEDS TO BE BOUNDED BY 'FREE' (EQUIL AMT) OR\n! IF 'FREE' NEEDS TO BE BOUNDED BY XH2O.\n! ----------------------------------------------------------------------\n      CALL FRH2O (FREE,TAVG,SMC,SH2O,SMCMAX,BEXP,PSISAT)\n\n! ----------------------------------------------------------------------\n! FIRST, IF FREEZING AND REMAINING LIQUID LESS THAN LOWER BOUND, THEN\n! REDUCE EXTENT OF FREEZING, THEREBY LETTING SOME OR ALL OF HEAT FLUX\n! QTOT COOL THE SOIL TEMP LATER IN ROUTINE HRT.\n! ----------------------------------------------------------------------\n      XH2O = SH2O + QTOT * DT / (DH2O * HLICE * DZ)\n      IF ( XH2O < SH2O .AND. XH2O < FREE) THEN\n         IF ( FREE > SH2O ) THEN\n            XH2O = SH2O\n         ELSE\n            XH2O = FREE\n         END IF\n      END IF\n! ----------------------------------------------------------------------\n! SECOND, IF THAWING AND THE INCREASE IN LIQUID WATER GREATER THAN UPPER\n! BOUND, THEN REDUCE EXTENT OF THAW, THEREBY LETTING SOME OR ALL OF HEAT\n! FLUX QTOT WARM THE SOIL TEMP LATER IN ROUTINE HRT.\n! ----------------------------------------------------------------------\n      IF ( XH2O > SH2O .AND. XH2O > FREE ) THEN\n         IF ( FREE < SH2O ) THEN\n            XH2O = SH2O\n         ELSE\n            XH2O = FREE\n         END IF\n      END IF\n\n! ----------------------------------------------------------------------\n! CALCULATE PHASE-CHANGE HEAT SOURCE/SINK TERM FOR USE IN ROUTINE HRT\n! AND UPDATE LIQUID WATER TO REFLCET FINAL FREEZE/THAW INCREMENT.\n! ----------------------------------------------------------------------\n!      SNKSRC = -DH2O*HLICE*DZ*(XH2O-SH2O)/DT\n      IF (XH2O < 0.) XH2O = 0.\n      IF (XH2O > SMC) XH2O = SMC\n      TSNSR = - DH2O * HLICE * DZ * (XH2O - SH2O)/ DT\n      SH2O = XH2O\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNKSRC\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SNOPAC (ETP,ETA,PRCP,PRCPF,SNOWNG,SMC,SMCMAX,SMCWLT,   &\n                          SMCREF,SMCDRY,CMC,CMCMAX,NSOIL,DT,            &\n                          SBETA,DF1,                                    &\n                          Q2,T1,SFCTMP,T24,TH2,FDOWN,F1,SSOIL,STC,EPSCA,&\n                         SFCPRS,BEXP,PC,RCH,RR,CFACTR,SNCOVR,ESD,SNDENS,&\n                          SNOWH,SH2O,SLOPE,KDT,FRZFACT,PSISAT,          &\n                          ZSOIL,DWSAT,DKSAT,TBOT,ZBOT,SHDFAC,RUNOFF1,   &\n                          RUNOFF2,RUNOFF3,EDIR,EC,ET,ETT,NROOT,SNOMLT,  &\n                          ICE,RTDIS,QUARTZ,FXEXP,CSOIL,                 &\n                          BETA,DRIP,DEW,FLX1,FLX2,FLX3,ESNOW,ETNS,EMISSI,&\n                          RIBB,SOLDN,                                   &\n                          ISURBAN,                                      &\n\n                          VEGTYP, SFHEAD1RT,INFXS1RT,ETPND1,            &\n\t\t          gwsoilcpl, qlowbdry)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNOPAC\n! ----------------------------------------------------------------------\n! CALCULATE SOIL MOISTURE AND HEAT FLUX VALUES & UPDATE SOIL MOISTURE\n! CONTENT AND SOIL HEAT CONTENT VALUES FOR THE CASE WHEN A SNOW PACK IS\n! PRESENT.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: ICE, NROOT, NSOIL,VEGTYP\n      INTEGER, INTENT(IN)   :: ISURBAN\n      INTEGER               :: K\n!\n! kmh 09/03/2006 add IT16 for surface temperature iteration\n!\n      INTEGER               :: IT16\n      LOGICAL, INTENT(IN)   :: SNOWNG\n\n!DJG NDHMS/WRF-Hydro edit...\n       REAL, INTENT(INOUT)    ::  SFHEAD1RT,INFXS1RT,ETPND1\n\n!BF gw soil coupling\n      real, intent(in)                       :: qlowbdry\n      integer, intent(in)                    :: gwsoilcpl\n\n      REAL, INTENT(IN)      :: BEXP,CFACTR, CMCMAX,CSOIL,DF1,DKSAT,     &\n                               DT,DWSAT, EPSCA,FDOWN,F1,FXEXP,          &\n                               FRZFACT,KDT,PC, PRCP,PSISAT,Q2,QUARTZ,   &\n                               RCH,RR,SBETA,SFCPRS, SFCTMP, SHDFAC,     &\n                               SLOPE,SMCDRY,SMCMAX,SMCREF,SMCWLT, T24,  &\n                               TBOT,TH2,ZBOT,EMISSI,SOLDN\n      REAL, INTENT(INOUT)   :: CMC, BETA, ESD,FLX2,PRCPF,SNOWH,SNCOVR,  &\n                               SNDENS, T1, RIBB, ETP\n      REAL, INTENT(OUT)     :: DEW,DRIP,EC,EDIR, ETNS, ESNOW,ETT,       &\n                               FLX1,FLX3, RUNOFF1,RUNOFF2,RUNOFF3,      &\n                               SSOIL,SNOMLT\n      REAL, DIMENSION(1:NSOIL),INTENT(IN)     :: RTDIS,ZSOIL\n      REAL, DIMENSION(1:NSOIL),INTENT(OUT)    :: ET\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SMC,SH2O,STC\n      REAL, DIMENSION(1:NSOIL) :: ET1\n      REAL                  :: DENOM,DSOIL,DTOT,EC1,EDIR1,ESDFLX,ETA,   &\n                               ETT1, ESNOW1, ESNOW2, ETA1,ETP1,ETP2,    &\n                               ETP3, ETNS1, ETANRG, ETAX, EX, FLX3X,    &\n                               FRCSNO,FRCSOI, PRCP1, QSAT,RSNOW, SEH,   &\n                               SNCOND,SSOIL1, T11,T12, T12A, T12AX,     &\n                               T12B, T14, YY, ZZ1\n!                               T12B, T14, YY, ZZ1,EMISSI_S\n!\n! kmh 01/11/2007 add T15, T16, and DTOT2 for SFC T iteration and snow heat flux\n!\n      REAL                  :: T15, T16, DTOT2\n      REAL, PARAMETER       :: ESDMIN = 1.E-6, LSUBC = 2.501000E+6,     &\n                               LSUBS = 2.83E+6, TFREEZ = 273.15,        &\n                               SNOEXP = 2.0\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE:\n! ----------------------------------------------------------------------\n! IF SEA-ICE (ICE=1) OR GLACIAL-ICE (ICE=-1), SNOWCOVER FRACTION = 1.0,\n! AND SUBLIMATION IS AT THE POTENTIAL RATE.\n! FOR NON-GLACIAL LAND (ICE=0), IF SNOWCOVER FRACTION < 1.0, TOTAL\n! EVAPORATION < POTENTIAL DUE TO NON-POTENTIAL CONTRIBUTION FROM\n! NON-SNOW COVERED FRACTION.\n! ----------------------------------------------------------------------\n! INITIALIZE EVAP TERMS.\n! ----------------------------------------------------------------------\n! conversions:\n! ESNOW [KG M-2 S-1]\n! ESDFLX [KG M-2 S-1] .le. ESNOW\n! ESNOW1 [M S-1]\n! ESNOW2 [M]\n! ETP [KG M-2 S-1]\n! ETP1 [M S-1]\n! ETP2 [M]\n! ----------------------------------------------------------------------\n      DEW = 0.\n      EDIR = 0.\n      EDIR1 = 0.\n      EC1 = 0.\n      EC = 0.\n!      EMISSI_S=0.95    ! For snow\n\n      DO K = 1,NSOIL\n         ET (K) = 0.\n         ET1 (K) = 0.\n      END DO\n      ETT = 0.\n      ETT1 = 0.\n\n!DJG NDHMS/WRF-Hydro edit...\n      ETPND1 = 0.\n\n\n      ETNS = 0.\n      ETNS1 = 0.\n      ESNOW = 0.\n      ESNOW1 = 0.\n      ESNOW2 = 0.\n\n! ----------------------------------------------------------------------\n! CONVERT POTENTIAL EVAP (ETP) FROM KG M-2 S-1 TO ETP1 IN M S-1\n! ----------------------------------------------------------------------\n      PRCP1 = PRCPF *0.001\n! ----------------------------------------------------------------------\n! IF ETP<0 (DOWNWARD) THEN DEWFALL (=FROSTFALL IN THIS CASE).\n! ----------------------------------------------------------------------\n      BETA = 1.0\n      IF (ETP <= 0.0) THEN\n         IF ( ( RIBB >= 0.1 ) .AND. ( FDOWN > 150.0 ) ) THEN\n            ETP=(MIN(ETP*(1.0-RIBB),0.)*SNCOVR/0.980 + ETP*(0.980-SNCOVR))/0.980\n         ENDIF\n        IF(ETP == 0.) BETA = 0.0\n        ETP1 = ETP * 0.001\n         DEW = -ETP1\n         ESNOW2 = ETP1*DT\n         ETANRG = ETP*((1.-SNCOVR)*LSUBC + SNCOVR*LSUBS)\n      ELSE\n         ETP1 = ETP * 0.001\n         IF ( ICE /= 0 ) THEN\n            ! SEA-ICE AND GLACIAL-ICE CASE\n            ESNOW = ETP\n            ESNOW1 = ESNOW*0.001\n            ESNOW2 = ESNOW1*DT\n            ETANRG = ESNOW*LSUBS\n         ELSE IF ( ICE ==  0) THEN\n            ! NON-GLACIAL LAND CASE\n             IF (SNCOVR <  1.) THEN\n               CALL EVAPO (ETNS1,SMC,NSOIL,CMC,ETP1,DT,ZSOIL,           &\n                            SH2O,                                       &\n                            SMCMAX,BEXP,PC,SMCWLT,DKSAT,DWSAT,          &\n                            SMCREF,SHDFAC,CMCMAX,                       &\n                            SMCDRY,CFACTR,                              &\n                            EDIR1,EC1,ET1,ETT1,SFCTMP,Q2,NROOT,RTDIS,   &\n                            FXEXP, SFHEAD1RT,ETPND1)\n! ----------------------------------------------------------------------------\n               EDIR1 = EDIR1* (1. - SNCOVR)\n               EC1 = EC1* (1. - SNCOVR)\n               DO K = 1,NSOIL\n                  ET1 (K) = ET1 (K)* (1. - SNCOVR)\n               END DO\n               ETT1 = ETT1*(1.-SNCOVR)\n!               ETNS1 = EDIR1+ EC1+ ETT1\n               ETNS1 = ETNS1*(1.-SNCOVR)\n! ----------------------------------------------------------------------------\n               EDIR = EDIR1*1000.\n               EC = EC1*1000.\n               DO K = 1,NSOIL\n                  ET (K) = ET1 (K)*1000.\n               END DO\n               ETT = ETT1*1000.\n               ETNS = ETNS1*1000.\n\n\n!DJG NDHMS/WRF-Hydro edit...\n               ETPND1 = ETPND1*1000.\n\n\n! ----------------------------------------------------------------------\n\n!   end IF (SNCOVR .lt. 1.)\n            END IF\n!   end IF (ICE .ne. 1)\n         END IF\n         ESNOW = ETP*SNCOVR\n         ESNOW1 = ESNOW*0.001\n         ESNOW2 = ESNOW1*DT\n         ETANRG = ESNOW*LSUBS + ETNS*LSUBC\n!   end IF (ETP .le. 0.0)\n      END IF\n\n! ----------------------------------------------------------------------\n! IF PRECIP IS FALLING, CALCULATE HEAT FLUX FROM SNOW SFC TO NEWLY\n! ACCUMULATING PRECIP.  NOTE THAT THIS REFLECTS THE FLUX APPROPRIATE FOR\n! THE NOT-YET-UPDATED SKIN TEMPERATURE (T1).  ASSUMES TEMPERATURE OF THE\n! SNOWFALL STRIKING THE GROUND IS =SFCTMP (LOWEST MODEL LEVEL AIR TEMP).\n! ----------------------------------------------------------------------\n      FLX1 = 0.0\n      IF (SNOWNG) THEN\n         FLX1 = CPICE * PRCP * (T1- SFCTMP)\n      ELSE\n         IF (PRCP >  0.0) FLX1 = CPH2O * PRCP * (T1- SFCTMP)\n! ----------------------------------------------------------------------\n! CALCULATE AN 'EFFECTIVE SNOW-GRND SFC TEMP' (T12) BASED ON HEAT FLUXES\n! BETWEEN THE SNOW PACK AND THE SOIL AND ON NET RADIATION.\n! INCLUDE FLX1 (PRECIP-SNOW SFC) AND FLX2 (FREEZING RAIN LATENT HEAT)\n! FLUXES.  FLX1 FROM ABOVE, FLX2 BROUGHT IN VIA COMMOM BLOCK RITE.\n! FLX2 REFLECTS FREEZING RAIN LATENT HEAT FLUX USING T1 CALCULATED IN\n! PENMAN.\n! ----------------------------------------------------------------------\n      END IF\n      DSOIL = - (0.5 * ZSOIL (1))\n      DTOT = SNOWH + DSOIL\n      DENOM = 1.0+ DF1 / (DTOT * RR * RCH)\n! surface emissivity weighted by snow cover fraction\n!      T12A = ( (FDOWN - FLX1 - FLX2 -                                   &\n!     &       ((SNCOVR*EMISSI_S)+EMISSI*(1.0-SNCOVR))*SIGMA *T24)/RCH    &\n!     &       + TH2 - SFCTMP - ETANRG/RCH ) / RR\n      T12A = ( (FDOWN - FLX1- FLX2- EMISSI * SIGMA * T24)/ RCH                    &\n                + TH2- SFCTMP - ETANRG / RCH ) / RR\n\n      T12B = DF1 * STC (1) / (DTOT * RR * RCH)\n\n! ----------------------------------------------------------------------\n! IF THE 'EFFECTIVE SNOW-GRND SFC TEMP' IS AT OR BELOW FREEZING, NO SNOW\n! MELT WILL OCCUR.  SET THE SKIN TEMP TO THIS EFFECTIVE TEMP.  REDUCE\n! (BY SUBLIMINATION ) OR INCREASE (BY FROST) THE DEPTH OF THE SNOWPACK,\n! DEPENDING ON SIGN OF ETP.\n! UPDATE SOIL HEAT FLUX (SSOIL) USING NEW SKIN TEMPERATURE (T1)\n! SINCE NO SNOWMELT, SET ACCUMULATED SNOWMELT TO ZERO, SET 'EFFECTIVE'\n! PRECIP FROM SNOWMELT TO ZERO, SET PHASE-CHANGE HEAT FLUX FROM SNOWMELT\n! TO ZERO.\n! ----------------------------------------------------------------------\n! SUB-FREEZING BLOCK\n! ----------------------------------------------------------------------\n      T12 = (SFCTMP + T12A + T12B) / DENOM\n      IF (T12 <=  TFREEZ) THEN\n         T1 = T12\n         SSOIL = DF1 * (T1- STC (1)) / DTOT\n!        ESD = MAX (0.0, ESD- ETP2)\n         ESD = MAX(0.0, ESD-ESNOW2)\n         FLX3 = 0.0\n         EX = 0.0\n\n         SNOMLT = 0.0\n! ----------------------------------------------------------------------\n! IF THE 'EFFECTIVE SNOW-GRND SFC TEMP' IS ABOVE FREEZING, SNOW MELT\n! WILL OCCUR.  CALL THE SNOW MELT RATE,EX AND AMT, SNOMLT.  REVISE THE\n! EFFECTIVE SNOW DEPTH.  REVISE THE SKIN TEMP BECAUSE IT WOULD HAVE CHGD\n! DUE TO THE LATENT HEAT RELEASED BY THE MELTING. CALC THE LATENT HEAT\n! RELEASED, FLX3. SET THE EFFECTIVE PRECIP, PRCP1 TO THE SNOW MELT RATE,\n! EX FOR USE IN SMFLX.  ADJUSTMENT TO T1 TO ACCOUNT FOR SNOW PATCHES.\n! CALCULATE QSAT VALID AT FREEZING POINT.  NOTE THAT ESAT (SATURATION\n! VAPOR PRESSURE) VALUE OF 6.11E+2 USED HERE IS THAT VALID AT FRZZING\n! POINT.  NOTE THAT ETP FROM CALL PENMAN IN SFLX IS IGNORED HERE IN\n! FAVOR OF BULK ETP OVER 'OPEN WATER' AT FREEZING TEMP.\n! UPDATE SOIL HEAT FLUX (S) USING NEW SKIN TEMPERATURE (T1)\n! ----------------------------------------------------------------------\n! ABOVE FREEZING BLOCK\n! ----------------------------------------------------------------------\n      ELSE\n         T1 = TFREEZ * SNCOVR ** SNOEXP + T12 * (1.0- SNCOVR ** SNOEXP)\n         BETA = 1.0\n\n! ----------------------------------------------------------------------\n! IF POTENTIAL EVAP (SUBLIMATION) GREATER THAN DEPTH OF SNOWPACK.\n! BETA<1\n! SNOWPACK HAS SUBLIMATED AWAY, SET DEPTH TO ZERO.\n! ----------------------------------------------------------------------\n         IF ( ICE /= 0 ) then\n            ! kmh  12/15/2005 modify SSOIL\n            ! kmh  09/03/2006 modify DTOT\n            IF ( DTOT .GT. 2.0*DSOIL ) THEN\n               DTOT = 2.0*DSOIL\n            ENDIF\n         ENDIF\n         SSOIL = DF1 * (T1- STC (1)) / DTOT\n         IF (ESD-ESNOW2 <= ESDMIN) THEN\n            ESD = 0.0\n            EX = 0.0\n            SNOMLT = 0.0\n            FLX3 = 0.0\n! ----------------------------------------------------------------------\n! SUBLIMATION LESS THAN DEPTH OF SNOWPACK\n! SNOWPACK (ESD) REDUCED BY ESNOW2 (DEPTH OF SUBLIMATED SNOW)\n! ----------------------------------------------------------------------\n         ELSE\n            ESD = ESD-ESNOW2\n            ETP3 = ETP * LSUBC\n            SEH = RCH * (T1- TH2)\n            T14 = T1* T1\n            T14 = T14* T14\n!           FLX3 = FDOWN - FLX1 - FLX2 -                                 &\n!                  ((SNCOVR*EMISSI_S)+EMISSI*(1-SNCOVR))*SIGMA*T14 -     &\n!                    SSOIL - SEH - ETANRG\n            FLX3 = FDOWN - FLX1- FLX2- EMISSI*SIGMA * T14- SSOIL - SEH - ETANRG\n            IF (FLX3 <= 0.0) FLX3 = 0.0\n! ----------------------------------------------------------------------\n! SNOWMELT REDUCTION DEPENDING ON SNOW COVER\n! ----------------------------------------------------------------------\n            EX = FLX3*0.001/ LSUBF\n\n! ----------------------------------------------------------------------\n! ESDMIN REPRESENTS A SNOWPACK DEPTH THRESHOLD VALUE BELOW WHICH WE\n! CHOOSE NOT TO RETAIN ANY SNOWPACK, AND INSTEAD INCLUDE IT IN SNOWMELT.\n! ----------------------------------------------------------------------\n            SNOMLT = EX * DT\n            IF (ESD- SNOMLT >=  ESDMIN) THEN\n               ESD = ESD- SNOMLT\n! ----------------------------------------------------------------------\n! SNOWMELT EXCEEDS SNOW DEPTH\n! ----------------------------------------------------------------------\n            ELSE\n               EX = ESD / DT\n               FLX3 = EX *1000.0* LSUBF\n               SNOMLT = ESD\n\n               ESD = 0.0\n! ----------------------------------------------------------------------\n! END OF 'ESD .LE. ETP2' IF-BLOCK\n! ----------------------------------------------------------------------\n            END IF\n         END IF\n\n! ----------------------------------------------------------------------\n! END OF 'T12 .LE. TFREEZ' IF-BLOCK\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! IF NON-GLACIAL LAND, ADD SNOWMELT RATE (EX) TO PRECIP RATE TO BE USED\n! IN SUBROUTINE SMFLX (SOIL MOISTURE EVOLUTION) VIA INFILTRATION.\n!\n! FOR SEA-ICE AND GLACIAL-ICE, THE SNOWMELT WILL BE ADDED TO SUBSURFACE\n! RUNOFF/BASEFLOW LATER NEAR THE END OF SFLX (AFTER RETURN FROM CALL TO\n! SUBROUTINE SNOPAC)\n! ----------------------------------------------------------------------\n         IF (ICE == 0) PRCP1 = PRCP1+ EX\n\n! ----------------------------------------------------------------------\n! SET THE EFFECTIVE POTNL EVAPOTRANSP (ETP1) TO ZERO SINCE THIS IS SNOW\n! CASE, SO SURFACE EVAP NOT CALCULATED FROM EDIR, EC, OR ETT IN SMFLX\n! (BELOW).\n! IF SEAICE (ICE==1) SKIP CALL TO SMFLX.\n! SMFLX RETURNS UPDATED SOIL MOISTURE VALUES FOR NON-GLACIAL LAND.\n! IF SEA-ICE (ICE==1) OR GLACIAL-ICE (ICE==-1), SKIP CALL TO SMFLX,\n! SINCE NO SOIL MEDIUM FOR SEA-ICE OR GLACIAL-ICE.\n! ----------------------------------------------------------------------\n      END IF\n      IF (ICE == 0) THEN\n         CALL SMFLX (SMC,NSOIL,CMC,DT,PRCP1,ZSOIL,                      &\n                      SH2O,SLOPE,KDT,FRZFACT,                           &\n                      SMCMAX,BEXP,SMCWLT,DKSAT,DWSAT,                   &\n                      SHDFAC,CMCMAX,                                    &\n                      RUNOFF1,RUNOFF2,RUNOFF3,                          &\n                      EDIR1,EC1,ET1,                                    &\n                      DRIP, SFHEAD1RT,INFXS1RT,                         &\n\t\t      gwsoilcpl, qlowbdry)\n! ----------------------------------------------------------------------\n! BEFORE CALL SHFLX IN THIS SNOWPACK CASE, SET ZZ1 AND YY ARGUMENTS TO\n! SPECIAL VALUES THAT ENSURE THAT GROUND HEAT FLUX CALCULATED IN SHFLX\n! MATCHES THAT ALREADY COMPUTER FOR BELOW THE SNOWPACK, THUS THE SFC\n! HEAT FLUX TO BE COMPUTED IN SHFLX WILL EFFECTIVELY BE THE FLUX AT THE\n! SNOW TOP SURFACE.  T11 IS A DUMMY ARGUEMENT SO WE WILL NOT USE THE\n! SKIN TEMP VALUE AS REVISED BY SHFLX.\n! ----------------------------------------------------------------------\n      END IF\n      ZZ1 = 1.0\n      YY = STC (1) -0.5* SSOIL * ZSOIL (1)* ZZ1/ DF1\n\n! ----------------------------------------------------------------------\n! SHFLX WILL CALC/UPDATE THE SOIL TEMPS.  NOTE:  THE SUB-SFC HEAT FLUX\n! (SSOIL1) AND THE SKIN TEMP (T11) OUTPUT FROM THIS SHFLX CALL ARE NOT\n! USED  IN ANY SUBSEQUENT CALCULATIONS. RATHER, THEY ARE DUMMY VARIABLES\n! HERE IN THE SNOPAC CASE, SINCE THE SKIN TEMP AND SUB-SFC HEAT FLUX ARE\n! UPDATED INSTEAD NEAR THE BEGINNING OF THE CALL TO SNOPAC.\n! ----------------------------------------------------------------------\n      T11 = T1\n      CALL SHFLX (SSOIL1,STC,SMC,SMCMAX,NSOIL,T11,DT,YY,ZZ1,ZSOIL,      &\n                   TBOT,ZBOT,SMCWLT,PSISAT,SH2O,BEXP,F1,DF1,ICE,        &\n                   QUARTZ,CSOIL,VEGTYP,ISURBAN)\n\n! ----------------------------------------------------------------------\n! SNOW DEPTH AND DENSITY ADJUSTMENT BASED ON SNOW COMPACTION.  YY IS\n! ASSUMED TO BE THE SOIL TEMPERTURE AT THE TOP OF THE SOIL COLUMN.\n! ----------------------------------------------------------------------\n      IF (ICE == 0) THEN\n         ! NON-GLACIAL LAND\n         IF (ESD >  0.) THEN\n            CALL SNOWPACK (ESD,DT,SNOWH,SNDENS,T1,YY)\n         ELSE\n            ESD = 0.\n            SNOWH = 0.\n            SNDENS = 0.\n            SNCOND = 1.\n            SNCOVR = 0.\n         END IF\n      ELSEIF (ICE == 1) THEN\n         ! SEA-ICE\n         IF (ESD .GE. 0.01) THEN\n            CALL SNOWPACK (ESD,DT,SNOWH,SNDENS,T1,YY)\n        ELSE\n           ESD = 0.01\n           SNOWH = 0.05\n           !KWM???? SNDENS =\n           !KWM???? SNCOND =\n           SNCOVR = 1.0\n        ENDIF\n      ELSEIF (ICE == -1) THEN\n         ! GLACIAL-ICE\n         IF (ESD .GE. 0.10) THEN\n            CALL SNOWPACK (ESD,DT,SNOWH,SNDENS,T1,YY)\n         ELSE\n            ESD = 0.10\n            SNOWH = 0.50\n            !KWM???? SNDENS =\n            !KWM???? SNCOND =\n            SNCOVR = 1.0\n        ENDIF\n      ENDIF\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOPAC\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE SNOWPACK (ESD,DTSEC,SNOWH,SNDENS,TSNOW,TSOIL)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNOWPACK\n! ----------------------------------------------------------------------\n! CALCULATE COMPACTION OF SNOWPACK UNDER CONDITIONS OF INCREASING SNOW\n! DENSITY, AS OBTAINED FROM AN APPROXIMATE SOLUTION OF E. ANDERSON'S\n! DIFFERENTIAL EQUATION (3.29), NOAA TECHNICAL REPORT NWS 19, BY VICTOR\n! KOREN, 03/25/95.\n! ----------------------------------------------------------------------\n! ESD     WATER EQUIVALENT OF SNOW (M)\n! DTSEC   TIME STEP (SEC)\n! SNOWH   SNOW DEPTH (M)\n! SNDENS  SNOW DENSITY (G/CM3=DIMENSIONLESS FRACTION OF H2O DENSITY)\n! TSNOW   SNOW SURFACE TEMPERATURE (K)\n! TSOIL   SOIL SURFACE TEMPERATURE (K)\n\n! SUBROUTINE WILL RETURN NEW VALUES OF SNOWH AND SNDENS\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER                :: IPOL, J\n      REAL, INTENT(IN)       :: ESD, DTSEC,TSNOW,TSOIL\n      REAL, INTENT(INOUT)    :: SNOWH, SNDENS\n      REAL                   :: BFAC,DSX,DTHR,DW,SNOWHC,PEXP,           &\n                                TAVGC,TSNOWC,TSOILC,ESDC,ESDCX\n      REAL, PARAMETER        :: C1 = 0.01, C2 = 21.0, G = 9.81,         &\n                                KN = 4000.0\n! ----------------------------------------------------------------------\n! CONVERSION INTO SIMULATION UNITS\n! ----------------------------------------------------------------------\n      SNOWHC = SNOWH *100.\n      ESDC = ESD *100.\n      DTHR = DTSEC /3600.\n      TSNOWC = TSNOW -273.15\n      TSOILC = TSOIL -273.15\n\n! ----------------------------------------------------------------------\n! CALCULATING OF AVERAGE TEMPERATURE OF SNOW PACK\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! CALCULATING OF SNOW DEPTH AND DENSITY AS A RESULT OF COMPACTION\n!  SNDENS=DS0*(EXP(BFAC*ESD)-1.)/(BFAC*ESD)\n!  BFAC=DTHR*C1*EXP(0.08*TAVGC-C2*DS0)\n! NOTE: BFAC*ESD IN SNDENS EQN ABOVE HAS TO BE CAREFULLY TREATED\n! NUMERICALLY BELOW:\n!   C1 IS THE FRACTIONAL INCREASE IN DENSITY (1/(CM*HR))\n!   C2 IS A CONSTANT (CM3/G) KOJIMA ESTIMATED AS 21 CMS/G\n! ----------------------------------------------------------------------\n      TAVGC = 0.5* (TSNOWC + TSOILC)\n      IF (ESDC >  1.E-2) THEN\n         ESDCX = ESDC\n      ELSE\n         ESDCX = 1.E-2\n      END IF\n\n!      DSX = SNDENS*((DEXP(BFAC*ESDC)-1.)/(BFAC*ESDC))\n! ----------------------------------------------------------------------\n! THE FUNCTION OF THE FORM (e**x-1)/x IMBEDDED IN ABOVE EXPRESSION\n! FOR DSX WAS CAUSING NUMERICAL DIFFICULTIES WHEN THE DENOMINATOR \"x\"\n! (I.E. BFAC*ESDC) BECAME ZERO OR APPROACHED ZERO (DESPITE THE FACT THAT\n! THE ANALYTICAL FUNCTION (e**x-1)/x HAS A WELL DEFINED LIMIT AS\n! \"x\" APPROACHES ZERO), HENCE BELOW WE REPLACE THE (e**x-1)/x\n! EXPRESSION WITH AN EQUIVALENT, NUMERICALLY WELL-BEHAVED\n! POLYNOMIAL EXPANSION.\n\n! NUMBER OF TERMS OF POLYNOMIAL EXPANSION, AND HENCE ITS ACCURACY,\n! IS GOVERNED BY ITERATION LIMIT \"IPOL\".\n!      IPOL GREATER THAN 9 ONLY MAKES A DIFFERENCE ON DOUBLE\n!            PRECISION (RELATIVE ERRORS GIVEN IN PERCENT %).\n!       IPOL=9, FOR REL.ERROR <~ 1.6 E-6 % (8 SIGNIFICANT DIGITS)\n!       IPOL=8, FOR REL.ERROR <~ 1.8 E-5 % (7 SIGNIFICANT DIGITS)\n!       IPOL=7, FOR REL.ERROR <~ 1.8 E-4 % ...\n! ----------------------------------------------------------------------\n      BFAC = DTHR * C1* EXP (0.08* TAVGC - C2* SNDENS)\n      IPOL = 4\n      PEXP = 0.\n!        PEXP = (1. + PEXP)*BFAC*ESDC/REAL(J+1)\n      DO J = IPOL,1, -1\n         PEXP = (1. + PEXP)* BFAC * ESDCX / REAL (J +1)\n      END DO\n\n      PEXP = PEXP + 1.\n! ----------------------------------------------------------------------\n! ABOVE LINE ENDS POLYNOMIAL SUBSTITUTION\n! ----------------------------------------------------------------------\n!     END OF KOREAN FORMULATION\n\n!     BASE FORMULATION (COGLEY ET AL., 1990)\n!     CONVERT DENSITY FROM G/CM3 TO KG/M3\n!       DSM=SNDENS*1000.0\n\n!       DSX=DSM+DTSEC*0.5*DSM*G*ESD/\n!    &      (1E7*EXP(-0.02*DSM+KN/(TAVGC+273.16)-14.643))\n\n!  &   CONVERT DENSITY FROM KG/M3 TO G/CM3\n!       DSX=DSX/1000.0\n\n!     END OF COGLEY ET AL. FORMULATION\n\n! ----------------------------------------------------------------------\n! SET UPPER/LOWER LIMIT ON SNOW DENSITY\n! ----------------------------------------------------------------------\n      DSX = SNDENS * (PEXP)\n      IF (DSX > 0.40) DSX = 0.40\n      IF (DSX < 0.05) DSX = 0.05\n! ----------------------------------------------------------------------\n! UPDATE OF SNOW DEPTH AND DENSITY DEPENDING ON LIQUID WATER DURING\n! SNOWMELT.  ASSUMED THAT 13% OF LIQUID WATER CAN BE STORED IN SNOW PER\n! DAY DURING SNOWMELT TILL SNOW DENSITY 0.40.\n! ----------------------------------------------------------------------\n      SNDENS = DSX\n      IF (TSNOWC >=  0.) THEN\n         DW = 0.13* DTHR /24.\n         SNDENS = SNDENS * (1. - DW) + DW\n         IF (SNDENS >=  0.40) SNDENS = 0.40\n! ----------------------------------------------------------------------\n! CALCULATE SNOW DEPTH (CM) FROM SNOW WATER EQUIVALENT AND SNOW DENSITY.\n! CHANGE SNOW DEPTH UNITS TO METERS\n! ----------------------------------------------------------------------\n      END IF\n      SNOWHC = ESDC / SNDENS\n      SNOWH = SNOWHC *0.01\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOWPACK\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SNOWZ0 (SNCOVR,Z0, Z0BRD, SNOWH)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNOWZ0\n! ----------------------------------------------------------------------\n! CALCULATE TOTAL ROUGHNESS LENGTH OVER SNOW\n! SNCOVR  FRACTIONAL SNOW COVER\n! Z0      ROUGHNESS LENGTH (m)\n! Z0S     SNOW ROUGHNESS LENGTH:=0.001 (m)\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN)        :: SNCOVR, Z0BRD\n      REAL, INTENT(OUT)       :: Z0\n      REAL, PARAMETER         :: Z0S=0.001\n      REAL, INTENT(IN)        :: SNOWH\n      REAL                    :: BURIAL\n      REAL                    :: Z0EFF\n\n!m      Z0 = (1.- SNCOVR)* Z0BRD + SNCOVR * Z0S\n      BURIAL = 7.0*Z0BRD - SNOWH\n      IF(BURIAL.LE.0.0007) THEN\n        Z0EFF = Z0S\n      ELSE\n        Z0EFF = BURIAL/7.0\n      ENDIF\n\n      Z0 = (1.- SNCOVR)* Z0BRD + SNCOVR * Z0EFF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOWZ0\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE SNOW_NEW (TEMP,NEWSN,SNOWH,SNDENS)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNOW_NEW\n! ----------------------------------------------------------------------\n! CALCULATE SNOW DEPTH AND DENSITITY TO ACCOUNT FOR THE NEW SNOWFALL.\n! NEW VALUES OF SNOW DEPTH & DENSITY RETURNED.\n\n! TEMP    AIR TEMPERATURE (K)\n! NEWSN   NEW SNOWFALL (M)\n! SNOWH   SNOW DEPTH (M)\n! SNDENS  SNOW DENSITY (G/CM3=DIMENSIONLESS FRACTION OF H2O DENSITY)\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN)        :: NEWSN, TEMP\n      REAL, INTENT(INOUT)     :: SNDENS, SNOWH\n      REAL                    :: DSNEW, HNEWC, SNOWHC,NEWSNC,TEMPC\n\n! ----------------------------------------------------------------------\n! CONVERSION INTO SIMULATION UNITS\n! ----------------------------------------------------------------------\n      SNOWHC = SNOWH *100.\n      NEWSNC = NEWSN *100.\n\n! ----------------------------------------------------------------------\n! CALCULATING NEW SNOWFALL DENSITY DEPENDING ON TEMPERATURE\n! EQUATION FROM GOTTLIB L. 'A GENERAL RUNOFF MODEL FOR SNOWCOVERED\n! AND GLACIERIZED BASIN', 6TH NORDIC HYDROLOGICAL CONFERENCE,\n! VEMADOLEN, SWEDEN, 1980, 172-177PP.\n!-----------------------------------------------------------------------\n      TEMPC = TEMP -273.15\n      IF (TEMPC <=  -15.) THEN\n         DSNEW = 0.05\n      ELSE\n         DSNEW = 0.05+0.0017* (TEMPC +15.)**1.5\n      END IF\n! ----------------------------------------------------------------------\n! ADJUSTMENT OF SNOW DENSITY DEPENDING ON NEW SNOWFALL\n! ----------------------------------------------------------------------\n      HNEWC = NEWSNC / DSNEW\n      IF (SNOWHC + HNEWC .LT. 1.0E-3) THEN\n         SNDENS = MAX(DSNEW,SNDENS)\n      ELSE\n         SNDENS = (SNOWHC * SNDENS + HNEWC * DSNEW)/ (SNOWHC + HNEWC)\n      ENDIF\n      SNOWHC = SNOWHC + HNEWC\n      SNOWH = SNOWHC *0.01\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOW_NEW\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SRT (RHSTT,EDIR,ET,SH2O,SH2OA,NSOIL,PCPDRP,            &\n                       ZSOIL,DWSAT,DKSAT,SMCMAX,BEXP,RUNOFF1,           &\n                     RUNOFF2,DT,SMCWLT,SLOPE,KDT,FRZX,SICE,AI,BI,CI,  &\n                     SFHEAD1RT,INFXS1RT, &\n\t\t     gwsoilcpl, qlowbdry)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SRT\n! ----------------------------------------------------------------------\n! CALCULATE THE RIGHT HAND SIDE OF THE TIME TENDENCY TERM OF THE SOIL\n! WATER DIFFUSION EQUATION.  ALSO TO COMPUTE ( PREPARE ) THE MATRIX\n! COEFFICIENTS FOR THE TRI-DIAGONAL MATRIX OF THE IMPLICIT TIME SCHEME.\n! ----------------------------------------------------------------------\n\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)       :: NSOIL\n      INTEGER                   :: IALP1, IOHINF, J, JJ,  K, KS\n\n!DJG NDHMS/WRF-Hydro edit... Variables used in OV routing infiltration calcs\n       REAL, INTENT(INOUT)     :: SFHEAD1RT, INFXS1RT\n       REAL                    :: SFCWATR,chcksm\n\n      !BF edit: variables for gw soil coupling\n      integer, intent(in)      :: gwsoilcpl\n      real, intent(in)         :: qlowbdry\n\n\n      REAL, INTENT(IN)          :: BEXP, DKSAT, DT, DWSAT, EDIR, FRZX,  &\n                                   KDT, PCPDRP, SLOPE, SMCMAX, SMCWLT\n      REAL, INTENT(OUT)         :: RUNOFF1, RUNOFF2\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: ET, SH2O, SH2OA, SICE,  &\n                                                ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)  :: RHSTT\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)  :: AI, BI, CI\n      REAL, DIMENSION(1:NSOIL)  :: DMAX\n      REAL                      :: ACRT, DD, DDT, DDZ, DDZ2, DENOM,     &\n                                   DENOM2,DICE, DSMDZ, DSMDZ2, DT1,     &\n                                   FCR,INFMAX,MXSMC,MXSMC2,NUMER,PDDUM, &\n                                   PX, SICEMAX,SLOPX, SMCAV, SSTT,      &\n                                   SUM, VAL, WCND, WCND2, WDF, WDF2\n      INTEGER, PARAMETER        :: CVFRZ = 3\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! REFERENCE FROZEN GROUND PARAMETER, CVFRZ, IS A SHAPE PARAMETER OF\n! AREAL DISTRIBUTION FUNCTION OF SOIL ICE CONTENT WHICH EQUALS 1/CV.\n! CV IS A COEFFICIENT OF SPATIAL VARIATION OF SOIL ICE CONTENT.  BASED\n! ON FIELD DATA CV DEPENDS ON AREAL MEAN OF FROZEN DEPTH, AND IT CLOSE\n! TO CONSTANT = 0.6 IF AREAL MEAN FROZEN DEPTH IS ABOVE 20 CM.  THAT IS\n! WHY PARAMETER CVFRZ = 3 (INT{1/0.6*0.6}).\n! CURRENT LOGIC DOESN'T ALLOW CVFRZ BE BIGGER THAN 3\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! DETERMINE RAINFALL INFILTRATION RATE AND RUNOFF.  INCLUDE THE\n! INFILTRATION FORMULE FROM SCHAAKE AND KOREN MODEL.\n! MODIFIED BY Q DUAN\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! LET SICEMAX BE THE GREATEST, IF ANY, FROZEN WATER CONTENT WITHIN SOIL\n! LAYERS.\n! ----------------------------------------------------------------------\n      IOHINF = 1\n      SICEMAX = 0.0\n      DO KS = 1,NSOIL\n         IF (SICE (KS) >  SICEMAX) SICEMAX = SICE (KS)\n! ----------------------------------------------------------------------\n! DETERMINE RAINFALL INFILTRATION RATE AND RUNOFF\n! ----------------------------------------------------------------------\n      END DO\n\n!DJG NDHMS/WRF-Hydro edit...\n!DJG Use previously merged Precip and Sfchead for infil. cap. calc.\n      SFCWATR = PCPDRP\n      PDDUM = SFCWATR\n!DJG original   PDDUM = PCPDRP\n      RUNOFF1 = 0.0\n      INFXS1RT = 0.0\n\n\n\n! ----------------------------------------------------------------------\n! MODIFIED BY Q. DUAN, 5/16/94\n! ----------------------------------------------------------------------\n!        IF (IOHINF == 1) THEN\n\n!DJG NDHMS/WRF-Hydro edit...\n!DJG IF (PCPDRP /=  0.0) THEN\n      IF (SFCWATR /=  0.0) THEN\n         DT1 = DT /86400.\n         SMCAV = SMCMAX - SMCWLT\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! ----------------------------------------------------------------------\n         DMAX (1)= - ZSOIL (1)* SMCAV\n\n         DICE = - ZSOIL (1) * SICE (1)\n         DMAX (1)= DMAX (1)* (1.0- (SH2OA (1) + SICE (1) - SMCWLT)/      &\n                    SMCAV)\n\n         DD = DMAX (1)\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! ----------------------------------------------------------------------\n         DO KS = 2,NSOIL\n\n            DICE = DICE+ ( ZSOIL (KS -1) - ZSOIL (KS) ) * SICE (KS)\n            DMAX (KS) = (ZSOIL (KS -1) - ZSOIL (KS))* SMCAV\n            DMAX (KS) = DMAX (KS)* (1.0- (SH2OA (KS) + SICE (KS)        &\n                        - SMCWLT)/ SMCAV)\n            DD = DD+ DMAX (KS)\n! ----------------------------------------------------------------------\n! VAL = (1.-EXP(-KDT*SQRT(DT1)))\n! IN BELOW, REMOVE THE SQRT IN ABOVE\n! ----------------------------------------------------------------------\n         END DO\n         VAL = (1. - EXP ( - KDT * DT1))\n         DDT = DD * VAL\n!DJG NDHMS/WRF-Hydro edit...\n!DJG        PX = PCPDRP * DT\n         PX = SFCWATR * DT\n         IF (PX <  0.0) PX = 0.0\n\n\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! REDUCTION OF INFILTRATION BASED ON FROZEN GROUND PARAMETERS\n! ----------------------------------------------------------------------\n         INFMAX = (PX * (DDT / (PX + DDT)))/ DT\n         FCR = 1.\n         IF (DICE >  1.E-2) THEN\n            ACRT = CVFRZ * FRZX / DICE\n            SUM = 1.\n            IALP1 = CVFRZ - 1\n            DO J = 1,IALP1\n               K = 1\n               DO JJ = J +1,IALP1\n                  K = K * JJ\n               END DO\n               SUM = SUM + (ACRT ** ( CVFRZ - J)) / FLOAT (K)\n            END DO\n            FCR = 1. - EXP ( - ACRT) * SUM\n         END IF\n\n! ----------------------------------------------------------------------\n! CORRECTION OF INFILTRATION LIMITATION:\n! IF INFMAX .LE. HYDROLIC CONDUCTIVITY ASSIGN INFMAX THE VALUE OF\n! HYDROLIC CONDUCTIVITY\n! ----------------------------------------------------------------------\n!         MXSMC = MAX ( SH2OA(1), SH2OA(2) )\n         INFMAX = INFMAX * FCR\n\n         MXSMC = SH2OA (1)\n         CALL WDFCND (WDF,WCND,MXSMC,SMCMAX,BEXP,DKSAT,DWSAT,           &\n                         SICEMAX)\n         INFMAX = MAX (INFMAX,WCND)\n\n         INFMAX = MIN (INFMAX,PX/DT)\n!DJG NDHMS/WRF-Hydro edit...\n!DJG       IF (PCPDRP >  INFMAX) THEN\n         IF (SFCWATR > INFMAX) THEN\n!DJG          RUNOFF1 = PCPDRP - INFMAX\n          RUNOFF1 = SFCWATR - INFMAX\n          INFXS1RT = RUNOFF1*DT*1000.\n          PDDUM = INFMAX\n         END IF\n\n! ----------------------------------------------------------------------\n! TO AVOID SPURIOUS DRAINAGE BEHAVIOR, 'UPSTREAM DIFFERENCING' IN LINE\n! BELOW REPLACED WITH NEW APPROACH IN 2ND LINE:\n! 'MXSMC = MAX(SH2OA(1), SH2OA(2))'\n! ----------------------------------------------------------------------\n      END IF\n\n      MXSMC = SH2OA (1)\n      CALL WDFCND (WDF,WCND,MXSMC,SMCMAX,BEXP,DKSAT,DWSAT,              &\n                    SICEMAX)\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEFFICIENTS AI, BI, AND CI FOR THE TOP LAYER\n! ----------------------------------------------------------------------\n      DDZ = 1. / ( - .5 * ZSOIL (2) )\n      AI (1) = 0.0\n      BI (1) = WDF * DDZ / ( - ZSOIL (1) )\n\n! ----------------------------------------------------------------------\n! CALC RHSTT FOR THE TOP LAYER AFTER CALC'NG THE VERTICAL SOIL MOISTURE\n! GRADIENT BTWN THE TOP AND NEXT TO TOP LAYERS.\n! ----------------------------------------------------------------------\n      CI (1) = - BI (1)\n      DSMDZ = ( SH2O (1) - SH2O (2) ) / ( - .5 * ZSOIL (2) )\n      RHSTT (1) = (WDF * DSMDZ + WCND- PDDUM + EDIR + ET (1))/ ZSOIL (1)\n\n! ----------------------------------------------------------------------\n! INITIALIZE DDZ2\n! ----------------------------------------------------------------------\n      SSTT = WDF * DSMDZ + WCND+ EDIR + ET (1)\n\n! ----------------------------------------------------------------------\n! LOOP THRU THE REMAINING SOIL LAYERS, REPEATING THE ABV PROCESS\n! ----------------------------------------------------------------------\n      DDZ2 = 0.0\n      DO K = 2,NSOIL\n         DENOM2 = (ZSOIL (K -1) - ZSOIL (K))\n         IF (K /= NSOIL) THEN\n\n! ----------------------------------------------------------------------\n! AGAIN, TO AVOID SPURIOUS DRAINAGE BEHAVIOR, 'UPSTREAM DIFFERENCING' IN\n! LINE BELOW REPLACED WITH NEW APPROACH IN 2ND LINE:\n! 'MXSMC2 = MAX (SH2OA(K), SH2OA(K+1))'\n! ----------------------------------------------------------------------\n            SLOPX = 1.\n\n            MXSMC2 = SH2OA (K)\n            CALL WDFCND (WDF2,WCND2,MXSMC2,SMCMAX,BEXP,DKSAT,DWSAT,     &\n                          SICEMAX)\n! -----------------------------------------------------------------------\n! CALC SOME PARTIAL PRODUCTS FOR LATER USE IN CALC'NG RHSTT\n! ----------------------------------------------------------------------\n            DENOM = (ZSOIL (K -1) - ZSOIL (K +1))\n\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEF, CI, AFTER CALC'NG ITS PARTIAL PRODUCT\n! ----------------------------------------------------------------------\n            DSMDZ2 = (SH2O (K) - SH2O (K +1)) / (DENOM * 0.5)\n            DDZ2 = 2.0 / DENOM\n            CI (K) = - WDF2 * DDZ2 / DENOM2\n\n         ELSE\n! ----------------------------------------------------------------------\n! SLOPE OF BOTTOM LAYER IS INTRODUCED\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! RETRIEVE THE SOIL WATER DIFFUSIVITY AND HYDRAULIC CONDUCTIVITY FOR\n! THIS LAYER\n! ----------------------------------------------------------------------\n            SLOPX = SLOPE\n          CALL WDFCND (WDF2,WCND2,SH2OA (NSOIL),SMCMAX,BEXP,DKSAT,DWSAT,     &\n                            SICEMAX)\n\n! ----------------------------------------------------------------------\n! CALC A PARTIAL PRODUCT FOR LATER USE IN CALC'NG RHSTT\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! SET MATRIX COEF CI TO ZERO\n! ----------------------------------------------------------------------\n            DSMDZ2 = 0.0\n            CI (K) = 0.0\n! ----------------------------------------------------------------------\n! CALC RHSTT FOR THIS LAYER AFTER CALC'NG ITS NUMERATOR\n! ----------------------------------------------------------------------\n         END IF\n\nselect case(gwsoilcpl)\ncase(2)\n        if(K .eq. nsoil) then\n         NUMER = (WDF2 * DSMDZ2) - qLowBdry - (WDF * DSMDZ) - WCND + ET (K)  \n  else\n        ! withdrawal has positive sign (e.g. ET), replenishment has negative sign (e.g. qlowbdry)\n         NUMER = (WDF2 * DSMDZ2) + SLOPX * WCND2- (WDF * DSMDZ)         &\n                 - WCND+ ET (K)\n  end if\n\ncase default\n\n         NUMER = (WDF2 * DSMDZ2) + SLOPX * WCND2- (WDF * DSMDZ)         &\n                 - WCND+ ET (K)\n\n\nend select\n! ----------------------------------------------------------------------\n! CALC MATRIX COEFS, AI, AND BI FOR THIS LAYER\n! ----------------------------------------------------------------------\n         RHSTT (K) = NUMER / ( - DENOM2)\n         AI (K) = - WDF * DDZ / DENOM2\n\n! ----------------------------------------------------------------------\n! RESET VALUES OF WDF, WCND, DSMDZ, AND DDZ FOR LOOP TO NEXT LYR\n! RUNOFF2:  SUB-SURFACE OR BASEFLOW RUNOFF\n! ----------------------------------------------------------------------\n         BI (K) = - ( AI (K) + CI (K) )\n         IF (K .eq. NSOIL) THEN\n\n!BF gwsoil coupling\nselect case (gwsoilcpl)\n case(2)\n            RUNOFF2 = -qLowBdry\n\n case default\n\t    RUNOFF2 = SLOPX * WCND2\n\nend select\n\n         END IF\n         IF (K .ne. NSOIL) THEN\n            WDF = WDF2\n            WCND = WCND2\n            DSMDZ = DSMDZ2\n            DDZ = DDZ2\n         END IF\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE SRT\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SSTEP (SH2OOUT,SH2OIN,CMC,RHSTT,RHSCT,DT,              &\n                        NSOIL,SMCMAX,CMCMAX,RUNOFF3,ZSOIL,SMC,SICE,     &\n                        AI,BI,CI, INFXS1RT)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SSTEP\n! ----------------------------------------------------------------------\n! CALCULATE/UPDATE SOIL MOISTURE CONTENT VALUES AND CANOPY MOISTURE\n! CONTENT VALUES.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)       :: NSOIL\n      INTEGER                   :: I, K, KK11\n\n!!DJG NDHMS/WRF-Hydro edit...\n      REAL, INTENT(INOUT)       :: INFXS1RT\n      REAL                      :: AVAIL\n\n      REAL, INTENT(IN)          :: CMCMAX, DT, SMCMAX\n      REAL, INTENT(OUT)         :: RUNOFF3\n      REAL, INTENT(INOUT)       :: CMC\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)     :: SH2OIN, SICE, ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)    :: SH2OOUT\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT)  :: RHSTT, SMC\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT)  :: AI, BI, CI\n      REAL, DIMENSION(1:NSOIL)  :: RHSTTin\n      REAL, DIMENSION(1:NSOIL)  :: CIin\n      REAL                      :: DDZ, RHSCT, STOT, WPLUS\n\n! ----------------------------------------------------------------------\n! CREATE 'AMOUNT' VALUES OF VARIABLES TO BE INPUT TO THE\n! TRI-DIAGONAL MATRIX ROUTINE.\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         RHSTT (K) = RHSTT (K) * DT\n         AI (K) = AI (K) * DT\n         BI (K) = 1. + BI (K) * DT\n         CI (K) = CI (K) * DT\n      END DO\n! ----------------------------------------------------------------------\n! COPY VALUES FOR INPUT VARIABLES BEFORE CALL TO ROSR12\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         RHSTTin (K) = RHSTT (K)\n      END DO\n      DO K = 1,NSOIL\n         CIin (K) = CI (K)\n      END DO\n! ----------------------------------------------------------------------\n! CALL ROSR12 TO SOLVE THE TRI-DIAGONAL MATRIX\n! ----------------------------------------------------------------------\n      CALL ROSR12 (CI,AI,BI,CIin,RHSTTin,RHSTT,NSOIL)\n! ----------------------------------------------------------------------\n! SUM THE PREVIOUS SMC VALUE AND THE MATRIX SOLUTION TO GET A\n! NEW VALUE.  MIN ALLOWABLE VALUE OF SMC WILL BE 0.02.\n! RUNOFF3: RUNOFF WITHIN SOIL LAYERS\n! ----------------------------------------------------------------------\n      WPLUS = 0.0\n      RUNOFF3 = 0.\n\n      DDZ = - ZSOIL (1)\n      DO K = 1,NSOIL\n         IF (K /= 1) DDZ = ZSOIL (K - 1) - ZSOIL (K)\n         SH2OOUT (K) = SH2OIN (K) + CI (K) + WPLUS / DDZ\n         STOT = SH2OOUT (K) + SICE (K)\n         IF (STOT > SMCMAX) THEN\n            IF (K .eq. 1) THEN\n               DDZ = - ZSOIL (1)\n            ELSE\n               KK11 = K - 1\n               DDZ = - ZSOIL (K) + ZSOIL (KK11)\n            END IF\n            WPLUS = (STOT - SMCMAX) * DDZ\n         ELSE\n            WPLUS = 0.\n         END IF\n         SMC (K) = MAX ( MIN (STOT,SMCMAX),0.02 )\n         SH2OOUT (K) = MAX ( (SMC (K) - SICE (K)),0.0)\n      END DO\n!DJG NDHMS/WRF-Hydro edit...\n!DJG Modifications to redstribute WPLUS/RUNOFF3 (soil moisture closure error) to soil profile\n!DJG beginning at bottom layer (NSOIL)\n         IF (WPLUS > 0.) THEN\n           DO K=NSOIL,2,-1\n\n               IF (K .eq. 2) THEN     !Assign soil depths\n                 DDZ = -ZSOIL(1)\n               ELSE\n                 DDZ = ZSOIL(K-2)-ZSOIL(K-1)\n               END IF\n\n               AVAIL = (SMCMAX - SMC(K-1)) * DDZ    !Det. Avail. Stor.\n\n!               print *, \"ZZZZZ\", K,DDZ,AVAIL,WPLUS,SMC(K),SMC(K-1),SMCMAX\n\n               IF (WPLUS <= AVAIL) THEN\n                 SMC(K-1) = SMC(K-1) + WPLUS/DDZ\n                 WPLUS = 0.\n               ELSE\n                 SMC(K-1) = SMCMAX\n                 WPLUS = WPLUS - AVAIL\n                 IF (K-1 .eq. 1) THEN\n                   INFXS1RT = INFXS1RT + WPLUS*1000\n                   WPLUS = 0.\n                 END IF\n               END IF\n\n!             SMC (K) = MAX ( MIN (STOT,SMCMAX),0.02 )\n             SH2OOUT (K) = MAX ( (SMC (K) - SICE (K)),0.0)\n\n           END DO\n         END IF\n!DJG NDHMS/WRF-Hydro edit...End of modification\n\n\n! ----------------------------------------------------------------------\n! UPDATE CANOPY WATER CONTENT/INTERCEPTION (CMC).  CONVERT RHSCT TO\n! AN 'AMOUNT' VALUE AND ADD TO PREVIOUS CMC VALUE TO GET NEW CMC.\n! ----------------------------------------------------------------------\n      RUNOFF3 = WPLUS\n      CMC = CMC + DT * RHSCT\n      IF (CMC < 1.E-20) CMC = 0.0\n      CMC = MIN (CMC,CMCMAX)\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SSTEP\n! ----------------------------------------------------------------------\n\n      SUBROUTINE TBND (TU,TB,ZSOIL,ZBOT,K,NSOIL,TBND1)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE TBND\n! ----------------------------------------------------------------------\n! CALCULATE TEMPERATURE ON THE BOUNDARY OF THE LAYER BY INTERPOLATION OF\n! THE MIDDLE LAYER TEMPERATURES\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)       :: NSOIL\n      INTEGER                   :: K\n      REAL, INTENT(IN)          :: TB, TU, ZBOT\n      REAL, INTENT(OUT)         :: TBND1\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: ZSOIL\n      REAL                      :: ZB, ZUP\n      REAL, PARAMETER           :: T0 = 273.15\n\n! ----------------------------------------------------------------------\n! USE SURFACE TEMPERATURE ON THE TOP OF THE FIRST LAYER\n! ----------------------------------------------------------------------\n     IF (K == 1) THEN\n         ZUP = 0.\n      ELSE\n         ZUP = ZSOIL (K -1)\n      END IF\n! ----------------------------------------------------------------------\n! USE DEPTH OF THE CONSTANT BOTTOM TEMPERATURE WHEN INTERPOLATE\n! TEMPERATURE INTO THE LAST LAYER BOUNDARY\n! ----------------------------------------------------------------------\n      IF (K ==  NSOIL) THEN\n         ZB = 2.* ZBOT - ZSOIL (K)\n      ELSE\n         ZB = ZSOIL (K +1)\n      END IF\n! ----------------------------------------------------------------------\n! LINEAR INTERPOLATION BETWEEN THE AVERAGE LAYER TEMPERATURES\n! ----------------------------------------------------------------------\n\n      TBND1 = TU + (TB - TU)* (ZUP - ZSOIL (K))/ (ZUP - ZB)\n! ----------------------------------------------------------------------\n  END SUBROUTINE TBND\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE TDFCND ( DF, SMC, QZ, SMCMAX, SH2O)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE TDFCND\n! ----------------------------------------------------------------------\n! CALCULATE THERMAL DIFFUSIVITY AND CONDUCTIVITY OF THE SOIL FOR A GIVEN\n! POINT AND TIME.\n! ----------------------------------------------------------------------\n! PETERS-LIDARD APPROACH (PETERS-LIDARD et al., 1998)\n! June 2001 CHANGES: FROZEN SOIL CONDITION.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN)          :: QZ,  SMC, SMCMAX, SH2O\n      REAL, INTENT(OUT)         :: DF\n      REAL                      :: AKE, GAMMD, THKDRY, THKICE, THKO,    &\n                                   THKQTZ,THKSAT,THKS,THKW,SATRATIO,XU, &\n                                   XUNFROZ\n\n! ----------------------------------------------------------------------\n! WE NOW GET QUARTZ AS AN INPUT ARGUMENT (SET IN ROUTINE REDPRM):\n!      DATA QUARTZ /0.82, 0.10, 0.25, 0.60, 0.52,\n!     &             0.35, 0.60, 0.40, 0.82/\n! ----------------------------------------------------------------------\n! IF THE SOIL HAS ANY MOISTURE CONTENT COMPUTE A PARTIAL SUM/PRODUCT\n! OTHERWISE USE A CONSTANT VALUE WHICH WORKS WELL WITH MOST SOILS\n! ----------------------------------------------------------------------\n!  THKW ......WATER THERMAL CONDUCTIVITY\n!  THKQTZ ....THERMAL CONDUCTIVITY FOR QUARTZ\n!  THKO ......THERMAL CONDUCTIVITY FOR OTHER SOIL COMPONENTS\n!  THKS ......THERMAL CONDUCTIVITY FOR THE SOLIDS COMBINED(QUARTZ+OTHER)\n!  THKICE ....ICE THERMAL CONDUCTIVITY\n!  SMCMAX ....POROSITY (= SMCMAX)\n!  QZ .........QUARTZ CONTENT (SOIL TYPE DEPENDENT)\n! ----------------------------------------------------------------------\n! USE AS IN PETERS-LIDARD, 1998 (MODIF. FROM JOHANSEN, 1975).\n\n!                                  PABLO GRUNMANN, 08/17/98\n! REFS.:\n!      FAROUKI, O.T.,1986: THERMAL PROPERTIES OF SOILS. SERIES ON ROCK\n!              AND SOIL MECHANICS, VOL. 11, TRANS TECH, 136 PP.\n!      JOHANSEN, O., 1975: THERMAL CONDUCTIVITY OF SOILS. PH.D. THESIS,\n!              UNIVERSITY OF TRONDHEIM,\n!      PETERS-LIDARD, C. D., ET AL., 1998: THE EFFECT OF SOIL THERMAL\n!              CONDUCTIVITY PARAMETERIZATION ON SURFACE ENERGY FLUXES\n!              AND TEMPERATURES. JOURNAL OF THE ATMOSPHERIC SCIENCES,\n!              VOL. 55, PP. 1209-1224.\n! ----------------------------------------------------------------------\n! NEEDS PARAMETERS\n! POROSITY(SOIL TYPE):\n!      POROS = SMCMAX\n! SATURATION RATIO:\n! PARAMETERS  W/(M.K)\n      SATRATIO = SMC / SMCMAX\n! ICE CONDUCTIVITY:\n      THKICE = 2.2\n! WATER CONDUCTIVITY:\n      THKW = 0.57\n! THERMAL CONDUCTIVITY OF \"OTHER\" SOIL COMPONENTS\n!      IF (QZ .LE. 0.2) THKO = 3.0\n      THKO = 2.0\n! QUARTZ' CONDUCTIVITY\n      THKQTZ = 7.7\n! SOLIDS' CONDUCTIVITY\n      THKS = (THKQTZ ** QZ)* (THKO ** (1. - QZ))\n\n! UNFROZEN FRACTION (FROM 1., i.e., 100%LIQUID, TO 0. (100% FROZEN))\n      XUNFROZ = SH2O / SMC\n! UNFROZEN VOLUME FOR SATURATION (POROSITY*XUNFROZ)\n      XU = XUNFROZ * SMCMAX\n\n! SATURATED THERMAL CONDUCTIVITY\n      THKSAT = THKS ** (1. - SMCMAX)* THKICE ** (SMCMAX - XU)* THKW **   &\n         (XU)\n\n! DRY DENSITY IN KG/M3\n      GAMMD = (1. - SMCMAX)*2700.\n\n! DRY THERMAL CONDUCTIVITY IN W.M-1.K-1\n      THKDRY = (0.135* GAMMD+ 64.7)/ (2700. - 0.947* GAMMD)\n! FROZEN\n      IF ( (SH2O + 0.0005) <  SMC ) THEN\n         AKE = SATRATIO\n! UNFROZEN\n! RANGE OF VALIDITY FOR THE KERSTEN NUMBER (AKE)\n      ELSE\n\n! KERSTEN NUMBER (USING \"FINE\" FORMULA, VALID FOR SOILS CONTAINING AT\n! LEAST 5% OF PARTICLES WITH DIAMETER LESS THAN 2.E-6 METERS.)\n! (FOR \"COARSE\" FORMULA, SEE PETERS-LIDARD ET AL., 1998).\n\n         IF ( SATRATIO >  0.1 ) THEN\n\n            AKE = LOG10 (SATRATIO) + 1.0\n\n! USE K = KDRY\n         ELSE\n\n            AKE = 0.0\n         END IF\n!  THERMAL CONDUCTIVITY\n\n      END IF\n\n      DF = AKE * (THKSAT - THKDRY) + THKDRY\n! ----------------------------------------------------------------------\n  END SUBROUTINE TDFCND\n! ----------------------------------------------------------------------\n\n      SUBROUTINE TMPAVG (TAVG,TUP,TM,TDN,ZSOIL,NSOIL,K)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE TMPAVG\n! ----------------------------------------------------------------------\n! CALCULATE SOIL LAYER AVERAGE TEMPERATURE (TAVG) IN FREEZING/THAWING\n! LAYER USING UP, DOWN, AND MIDDLE LAYER TEMPERATURES (TUP, TDN, TM),\n! WHERE TUP IS AT TOP BOUNDARY OF LAYER, TDN IS AT BOTTOM BOUNDARY OF\n! LAYER.  TM IS LAYER PROGNOSTIC STATE TEMPERATURE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER  K\n\n      INTEGER  NSOIL\n      REAL     DZ\n      REAL     DZH\n      REAL     T0\n      REAL     TAVG\n      REAL     TDN\n      REAL     TM\n      REAL     TUP\n      REAL     X0\n      REAL     XDN\n      REAL     XUP\n\n      REAL     ZSOIL (NSOIL)\n\n! ----------------------------------------------------------------------\n      PARAMETER (T0 = 2.7315E2)\n      IF (K .eq. 1) THEN\n         DZ = - ZSOIL (1)\n      ELSE\n         DZ = ZSOIL (K -1) - ZSOIL (K)\n      END IF\n\n      DZH = DZ *0.5\n      IF (TUP .lt. T0) THEN\n         IF (TM .lt. T0) THEN\n! ----------------------------------------------------------------------\n! TUP, TM, TDN < T0\n! ----------------------------------------------------------------------\n            IF (TDN .lt. T0) THEN\n               TAVG = (TUP + 2.0* TM + TDN)/ 4.0\n! ----------------------------------------------------------------------\n! TUP & TM < T0,  TDN .ge. T0\n! ----------------------------------------------------------------------\n            ELSE\n               X0 = (T0- TM) * DZH / (TDN - TM)\n               TAVG = 0.5 * (TUP * DZH + TM * (DZH + X0) + T0* (        &\n     &               2.* DZH - X0)) / DZ\n            END IF\n         ELSE\n! ----------------------------------------------------------------------\n! TUP < T0, TM .ge. T0, TDN < T0\n! ----------------------------------------------------------------------\n            IF (TDN .lt. T0) THEN\n               XUP = (T0- TUP) * DZH / (TM - TUP)\n               XDN = DZH - (T0- TM) * DZH / (TDN - TM)\n               TAVG = 0.5 * (TUP * XUP + T0* (2.* DZ - XUP - XDN)       &\n     &                + TDN * XDN) / DZ\n! ----------------------------------------------------------------------\n! TUP < T0, TM .ge. T0, TDN .ge. T0\n! ----------------------------------------------------------------------\n            ELSE\n               XUP = (T0- TUP) * DZH / (TM - TUP)\n               TAVG = 0.5 * (TUP * XUP + T0* (2.* DZ - XUP)) / DZ\n            END IF\n         END IF\n      ELSE\n         IF (TM .lt. T0) THEN\n! ----------------------------------------------------------------------\n! TUP .ge. T0, TM < T0, TDN < T0\n! ----------------------------------------------------------------------\n            IF (TDN .lt. T0) THEN\n               XUP = DZH - (T0- TUP) * DZH / (TM - TUP)\n               TAVG = 0.5 * (T0* (DZ - XUP) + TM * (DZH + XUP)          &\n     &                + TDN * DZH) / DZ\n! ----------------------------------------------------------------------\n! TUP .ge. T0, TM < T0, TDN .ge. T0\n! ----------------------------------------------------------------------\n            ELSE\n               XUP = DZH - (T0- TUP) * DZH / (TM - TUP)\n               XDN = (T0- TM) * DZH / (TDN - TM)\n               TAVG = 0.5 * (T0* (2.* DZ - XUP - XDN) + TM *            &\n     & (XUP + XDN)) / DZ\n            END IF\n         ELSE\n! ----------------------------------------------------------------------\n! TUP .ge. T0, TM .ge. T0, TDN < T0\n! ----------------------------------------------------------------------\n            IF (TDN .lt. T0) THEN\n               XDN = DZH - (T0- TM) * DZH / (TDN - TM)\n               TAVG = (T0* (DZ - XDN) +0.5* (T0+ TDN)* XDN) / DZ\n! ----------------------------------------------------------------------\n! TUP .ge. T0, TM .ge. T0, TDN .ge. T0\n! ----------------------------------------------------------------------\n            ELSE\n               TAVG = (TUP + 2.0* TM + TDN) / 4.0\n            END IF\n         END IF\n      END IF\n! ----------------------------------------------------------------------\n  END SUBROUTINE TMPAVG\n! ----------------------------------------------------------------------\n\n      SUBROUTINE TRANSP (ET,NSOIL,ETP1,SMC,CMC,ZSOIL,SHDFAC,SMCWLT,     &\n     &                      CMCMAX,PC,CFACTR,SMCREF,SFCTMP,Q2,NROOT,    &\n     &                      RTDIS)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE TRANSP\n! ----------------------------------------------------------------------\n! CALCULATE TRANSPIRATION FOR THE VEG CLASS.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER  I\n      INTEGER  K\n      INTEGER  NSOIL\n\n      INTEGER  NROOT\n      REAL     CFACTR\n      REAL     CMC\n      REAL     CMCMAX\n      REAL     DENOM\n      REAL     ET (NSOIL)\n      REAL     ETP1\n      REAL     ETP1A\n!.....REAL PART(NSOIL)\n      REAL     GX (NROOT)\n      REAL     PC\n      REAL     Q2\n      REAL     RTDIS (NSOIL)\n      REAL     RTX\n      REAL     SFCTMP\n      REAL     SGX\n      REAL     SHDFAC\n      REAL     SMC (NSOIL)\n      REAL     SMCREF\n      REAL     SMCWLT\n\n! ----------------------------------------------------------------------\n! INITIALIZE PLANT TRANSP TO ZERO FOR ALL SOIL LAYERS.\n! ----------------------------------------------------------------------\n      REAL     ZSOIL (NSOIL)\n      DO K = 1,NSOIL\n         ET (K) = 0.\n! ----------------------------------------------------------------------\n! CALCULATE AN 'ADJUSTED' POTENTIAL TRANSPIRATION\n! IF STATEMENT BELOW TO AVOID TANGENT LINEAR PROBLEMS NEAR ZERO\n! NOTE: GX AND OTHER TERMS BELOW REDISTRIBUTE TRANSPIRATION BY LAYER,\n! ET(K), AS A FUNCTION OF SOIL MOISTURE AVAILABILITY, WHILE PRESERVING\n! TOTAL ETP1A.\n! ----------------------------------------------------------------------\n      END DO\n      IF (CMC .ne. 0.0) THEN\n         ETP1A = SHDFAC * PC * ETP1 * (1.0- (CMC / CMCMAX) ** CFACTR)\n      ELSE\n         ETP1A = SHDFAC * PC * ETP1\n      END IF\n      SGX = 0.0\n      DO I = 1,NROOT\n         GX (I) = ( SMC (I) - SMCWLT ) / ( SMCREF - SMCWLT )\n         GX (I) = MAX ( MIN ( GX (I), 1. ), 0. )\n         SGX = SGX + GX (I)\n      END DO\n\n      SGX = SGX / NROOT\n      DENOM = 0.\n      DO I = 1,NROOT\n         RTX = RTDIS (I) + GX (I) - SGX\n         GX (I) = GX (I) * MAX ( RTX, 0. )\n         DENOM = DENOM + GX (I)\n      END DO\n\n      IF (DENOM .le. 0.0) DENOM = 1.\n      DO I = 1,NROOT\n         ET (I) = ETP1A * GX (I) / DENOM\n! ----------------------------------------------------------------------\n! ABOVE CODE ASSUMES A VERTICALLY UNIFORM ROOT DISTRIBUTION\n! CODE BELOW TESTS A VARIABLE ROOT DISTRIBUTION\n! ----------------------------------------------------------------------\n!      ET(1) = ( ZSOIL(1) / ZSOIL(NROOT) ) * GX * ETP1A\n!      ET(1) = ( ZSOIL(1) / ZSOIL(NROOT) ) * ETP1A\n! ----------------------------------------------------------------------\n! USING ROOT DISTRIBUTION AS WEIGHTING FACTOR\n! ----------------------------------------------------------------------\n!      ET(1) = RTDIS(1) * ETP1A\n!      ET(1) = ETP1A * PART(1)\n! ----------------------------------------------------------------------\n! LOOP DOWN THRU THE SOIL LAYERS REPEATING THE OPERATION ABOVE,\n! BUT USING THE THICKNESS OF THE SOIL LAYER (RATHER THAN THE\n! ABSOLUTE DEPTH OF EACH LAYER) IN THE FINAL CALCULATION.\n! ----------------------------------------------------------------------\n!      DO K = 2,NROOT\n!        GX = ( SMC(K) - SMCWLT ) / ( SMCREF - SMCWLT )\n!        GX = MAX ( MIN ( GX, 1. ), 0. )\n! TEST CANOPY RESISTANCE\n!        GX = 1.0\n!        ET(K) = ((ZSOIL(K)-ZSOIL(K-1))/ZSOIL(NROOT))*GX*ETP1A\n!        ET(K) = ((ZSOIL(K)-ZSOIL(K-1))/ZSOIL(NROOT))*ETP1A\n! ----------------------------------------------------------------------\n! USING ROOT DISTRIBUTION AS WEIGHTING FACTOR\n! ----------------------------------------------------------------------\n!        ET(K) = RTDIS(K) * ETP1A\n!        ET(K) = ETP1A*PART(K)\n!      END DO\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE TRANSP\n! ----------------------------------------------------------------------\n\n      SUBROUTINE WDFCND (WDF,WCND,SMC,SMCMAX,BEXP,DKSAT,DWSAT,          &\n     &                      SICEMAX)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE WDFCND\n! ----------------------------------------------------------------------\n! CALCULATE SOIL WATER DIFFUSIVITY AND SOIL HYDRAULIC CONDUCTIVITY.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL     BEXP\n      REAL     DKSAT\n      REAL     DWSAT\n      REAL     EXPON\n      REAL     FACTR1\n      REAL     FACTR2\n      REAL     SICEMAX\n      REAL     SMC\n      REAL     SMCMAX\n      REAL     VKwgt\n      REAL     WCND\n\n! ----------------------------------------------------------------------\n!     CALC THE RATIO OF THE ACTUAL TO THE MAX PSBL SOIL H2O CONTENT\n! ----------------------------------------------------------------------\n      REAL     WDF\n      FACTR1 = 0.05 / SMCMAX\n\n! ----------------------------------------------------------------------\n! PREP AN EXPNTL COEF AND CALC THE SOIL WATER DIFFUSIVITY\n! ----------------------------------------------------------------------\n      FACTR2 = SMC / SMCMAX\n      FACTR1 = MIN(FACTR1,FACTR2)\n      EXPON = BEXP + 2.0\n\n! ----------------------------------------------------------------------\n! FROZEN SOIL HYDRAULIC DIFFUSIVITY.  VERY SENSITIVE TO THE VERTICAL\n! GRADIENT OF UNFROZEN WATER. THE LATTER GRADIENT CAN BECOME VERY\n! EXTREME IN FREEZING/THAWING SITUATIONS, AND GIVEN THE RELATIVELY\n! FEW AND THICK SOIL LAYERS, THIS GRADIENT SUFFERES SERIOUS\n! TRUNCTION ERRORS YIELDING ERRONEOUSLY HIGH VERTICAL TRANSPORTS OF\n! UNFROZEN WATER IN BOTH DIRECTIONS FROM HUGE HYDRAULIC DIFFUSIVITY.\n! THEREFORE, WE FOUND WE HAD TO ARBITRARILY CONSTRAIN WDF\n! --\n! VERSION D_10CM: ........  FACTR1 = 0.2/SMCMAX\n! WEIGHTED APPROACH...................... PABLO GRUNMANN, 28_SEP_1999.\n! ----------------------------------------------------------------------\n      WDF = DWSAT * FACTR2 ** EXPON\n      IF (SICEMAX .gt. 0.0) THEN\n         VKWGT = 1./ (1. + (500.* SICEMAX)**3.)\n         WDF = VKWGT * WDF + (1. - VKWGT)* DWSAT * FACTR1** EXPON\n! ----------------------------------------------------------------------\n! RESET THE EXPNTL COEF AND CALC THE HYDRAULIC CONDUCTIVITY\n! ----------------------------------------------------------------------\n      END IF\n      EXPON = (2.0 * BEXP) + 3.0\n      WCND = DKSAT * FACTR2 ** EXPON\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE WDFCND\n! ----------------------------------------------------------------------\n\n\n#ifdef _HRLDAS_OFFLINE_\n      SUBROUTINE SFCDIF_off (ZLM,ZLM_WIND,Z0,THZ0,THLM,SFCSPD,CZIL,AKMS,AKHS, &\n           VEGTYP, ISURBAN, IZ0TLND )\n#else\n      SUBROUTINE SFCDIF_off (ZLM,Z0,THZ0,THLM,SFCSPD,CZIL,AKMS,AKHS)\n#endif\n\n\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SFCDIF (renamed SFCDIF_off to avoid clash with Eta PBL)\n! ----------------------------------------------------------------------\n! CALCULATE SURFACE LAYER EXCHANGE COEFFICIENTS VIA ITERATIVE PROCESS.\n! SEE CHEN ET AL (1997, BLM)\n! ----------------------------------------------------------------------\n\n      IMPLICIT NONE\n#ifdef _HRLDAS_OFFLINE_\n      INTEGER, INTENT(IN) :: VEGTYP\n      INTEGER, INTENT(IN) :: ISURBAN\n      INTEGER, INTENT(IN) :: IZ0TLND\n      REAL,    INTENT(IN) :: ZLM_WIND\n#endif\n\n\n      REAL     WWST, WWST2, G, VKRM, EXCM, BETA, BTG, ELFC, WOLD, WNEW\n      REAL     PIHF, EPSU2, EPSUST, EPSIT, EPSA, ZTMIN, ZTMAX, HPBL,     &\n     & SQVISC\n      REAL     RIC, RRIC, FHNEU, RFC, RFAC, ZZ, PSLMU, PSLMS, PSLHU,     &\n     & PSLHS\n      REAL     XX, PSPMU, YY, PSPMS, PSPHU, PSPHS, ZLM, Z0, THZ0, THLM\n      REAL     SFCSPD, CZIL, AKMS, AKHS, ZILFC, ZU, ZT, RDZ, CXCH\n      REAL     DTHV, DU2, BTGH, WSTAR2, USTAR, ZSLU, ZSLT, RLOGU, RLOGT\n      REAL     RLMO, ZETALT, ZETALU, ZETAU, ZETAT, XLU4, XLT4, XU4, XT4\n!CC   ......REAL ZTFC\n\n      REAL     XLU, XLT, XU, XT, PSMZ, SIMM, PSHZ, SIMH, USTARK, RLMN,  &\n     &         RLMA\n\n      INTEGER  ITRMX, ILECH, ITR\n      PARAMETER                                                         &\n     &        (WWST = 1.2,WWST2 = WWST * WWST,G = 9.8,VKRM = 0.40,      &\n     &         EXCM = 0.001                                             &\n     &        ,BETA = 1./270.,BTG = BETA * G,ELFC = VKRM * BTG          &\n     &                  ,WOLD =.15,WNEW = 1. - WOLD,ITRMX = 05,         &\n     &                   PIHF = 3.14159265/2.)\n      PARAMETER                                                         &\n     &         (EPSU2 = 1.E-4,EPSUST = 0.07,EPSIT = 1.E-4,EPSA = 1.E-8  &\n     &         ,ZTMIN = -5.,ZTMAX = 1.,HPBL = 1000.0                    &\n     &          ,SQVISC = 258.2)\n      PARAMETER                                                         &\n     &       (RIC = 0.183,RRIC = 1.0/ RIC,FHNEU = 0.8,RFC = 0.191       &\n     &        ,RFAC = RIC / (FHNEU * RFC * RFC))\n\n! ----------------------------------------------------------------------\n! NOTE: THE TWO CODE BLOCKS BELOW DEFINE FUNCTIONS\n! ----------------------------------------------------------------------\n! LECH'S SURFACE FUNCTIONS\n! ----------------------------------------------------------------------\n      PSLMU (ZZ)= -0.96* log (1.0-4.5* ZZ)\n      PSLMS (ZZ)= ZZ * RRIC -2.076* (1. -1./ (ZZ +1.))\n      PSLHU (ZZ)= -0.96* log (1.0-4.5* ZZ)\n\n! ----------------------------------------------------------------------\n! PAULSON'S SURFACE FUNCTIONS\n! ----------------------------------------------------------------------\n      PSLHS (ZZ)= ZZ * RFAC -2.076* (1. -1./ (ZZ +1.))\n      PSPMU (XX)= -2.* log ( (XX +1.)*0.5) - log ( (XX * XX +1.)*0.5)   &\n     &        +2.* ATAN (XX)                                            &\n     &- PIHF\n      PSPMS (YY)= 5.* YY\n      PSPHU (XX)= -2.* log ( (XX * XX +1.)*0.5)\n\n! ----------------------------------------------------------------------\n! THIS ROUTINE SFCDIF CAN HANDLE BOTH OVER OPEN WATER (SEA, OCEAN) AND\n! OVER SOLID SURFACE (LAND, SEA-ICE).\n! ----------------------------------------------------------------------\n      PSPHS (YY)= 5.* YY\n\n! ----------------------------------------------------------------------\n!     ZTFC: RATIO OF ZOH/ZOM  LESS OR EQUAL THAN 1\n!     C......ZTFC=0.1\n!     CZIL: CONSTANT C IN Zilitinkevich, S. S.1995,:NOTE ABOUT ZT\n! ----------------------------------------------------------------------\n      ILECH = 0\n\n! ----------------------------------------------------------------------\n#ifdef _HRLDAS_OFFLINE_\n      IF ( (IZ0TLND==0) .or. (VEGTYP == ISURBAN) ) THEN\n         ! Just use the original CZIL value.\n         ZILFC = - CZIL * VKRM * SQVISC\n      ELSE\n         ! Modify CZIL according to Chen & Zhang, 2009\n         ! CZIL = 10 ** -0.40 H, ( where H = 10*Zo )\n         CZIL = 10.0 ** ( -0.40 * ( Z0 / 0.07 ) )\n         ZILFC = - CZIL * VKRM * SQVISC\n      ENDIF\n#else\n      ZILFC = - CZIL * VKRM * SQVISC\n#endif\n\n!     C.......ZT=Z0*ZTFC\n      ZU = Z0\n#ifdef _HRLDAS_OFFLINE_\n      RDZ = 1./ ZLM_WIND\n#else\n      RDZ = 1./ ZLM\n#endif\n      CXCH = EXCM * RDZ\n      DTHV = THLM - THZ0\n\n! ----------------------------------------------------------------------\n! BELJARS CORRECTION OF USTAR\n! ----------------------------------------------------------------------\n      DU2 = MAX (SFCSPD * SFCSPD,EPSU2)\n!cc   If statements to avoid TANGENT LINEAR problems near zero\n      BTGH = BTG * HPBL\n      IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n         WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n      ELSE\n         WSTAR2 = 0.0\n      END IF\n\n! ----------------------------------------------------------------------\n! ZILITINKEVITCH APPROACH FOR ZT\n! ----------------------------------------------------------------------\n      USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n\n! ----------------------------------------------------------------------\n      ZT = EXP (ZILFC * SQRT (USTAR * Z0))* Z0\n#ifdef _HRLDAS_OFFLINE_\n      ZSLU = ZLM_WIND + ZU\n#else\n      ZSLU = ZLM + ZU\n#endif\n!     PRINT*,'ZSLT=',ZSLT\n!     PRINT*,'ZLM=',ZLM\n!     PRINT*,'ZT=',ZT\n\n      ZSLT = ZLM + ZT\n      RLOGU = log (ZSLU / ZU)\n\n      RLOGT = log (ZSLT / ZT)\n!     PRINT*,'RLMO=',RLMO\n!     PRINT*,'ELFC=',ELFC\n!     PRINT*,'AKHS=',AKHS\n!     PRINT*,'DTHV=',DTHV\n!     PRINT*,'USTAR=',USTAR\n\n      RLMO = ELFC * AKHS * DTHV / USTAR **3\n! ----------------------------------------------------------------------\n! 1./MONIN-OBUKKHOV LENGTH-SCALE\n! ----------------------------------------------------------------------\n      DO ITR = 1,ITRMX\n         ZETALT = MAX (ZSLT * RLMO,ZTMIN)\n         RLMO = ZETALT / ZSLT\n         ZETALU = ZSLU * RLMO\n         ZETAU = ZU * RLMO\n\n         ZETAT = ZT * RLMO\n         IF (ILECH .eq. 0) THEN\n            IF (RLMO .lt. 0.)THEN\n               XLU4 = 1. -16.* ZETALU\n               XLT4 = 1. -16.* ZETALT\n               XU4 = 1. -16.* ZETAU\n\n               XT4 = 1. -16.* ZETAT\n               XLU = SQRT (SQRT (XLU4))\n               XLT = SQRT (SQRT (XLT4))\n               XU = SQRT (SQRT (XU4))\n\n               XT = SQRT (SQRT (XT4))\n!     PRINT*,'-----------1------------'\n!     PRINT*,'PSMZ=',PSMZ\n!     PRINT*,'PSPMU(ZETAU)=',PSPMU(ZETAU)\n!     PRINT*,'XU=',XU\n!     PRINT*,'------------------------'\n               PSMZ = PSPMU (XU)\n               SIMM = PSPMU (XLU) - PSMZ + RLOGU\n               PSHZ = PSPHU (XT)\n               SIMH = PSPHU (XLT) - PSHZ + RLOGT\n            ELSE\n               ZETALU = MIN (ZETALU,ZTMAX)\n               ZETALT = MIN (ZETALT,ZTMAX)\n!     PRINT*,'-----------2------------'\n!     PRINT*,'PSMZ=',PSMZ\n!     PRINT*,'PSPMS(ZETAU)=',PSPMS(ZETAU)\n!     PRINT*,'ZETAU=',ZETAU\n!     PRINT*,'------------------------'\n               PSMZ = PSPMS (ZETAU)\n               SIMM = PSPMS (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSPHS (ZETAT)\n               SIMH = PSPHS (ZETALT) - PSHZ + RLOGT\n            END IF\n! ----------------------------------------------------------------------\n! LECH'S FUNCTIONS\n! ----------------------------------------------------------------------\n         ELSE\n            IF (RLMO .lt. 0.)THEN\n!     PRINT*,'-----------3------------'\n!     PRINT*,'PSMZ=',PSMZ\n!     PRINT*,'PSLMU(ZETAU)=',PSLMU(ZETAU)\n!     PRINT*,'ZETAU=',ZETAU\n!     PRINT*,'------------------------'\n               PSMZ = PSLMU (ZETAU)\n               SIMM = PSLMU (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSLHU (ZETAT)\n               SIMH = PSLHU (ZETALT) - PSHZ + RLOGT\n            ELSE\n               ZETALU = MIN (ZETALU,ZTMAX)\n\n               ZETALT = MIN (ZETALT,ZTMAX)\n!     PRINT*,'-----------4------------'\n!     PRINT*,'PSMZ=',PSMZ\n!     PRINT*,'PSLMS(ZETAU)=',PSLMS(ZETAU)\n!     PRINT*,'ZETAU=',ZETAU\n!     PRINT*,'------------------------'\n               PSMZ = PSLMS (ZETAU)\n               SIMM = PSLMS (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSLHS (ZETAT)\n               SIMH = PSLHS (ZETALT) - PSHZ + RLOGT\n            END IF\n! ----------------------------------------------------------------------\n! BELJAARS CORRECTION FOR USTAR\n! ----------------------------------------------------------------------\n         END IF\n\n! ----------------------------------------------------------------------\n! ZILITINKEVITCH FIX FOR ZT\n! ----------------------------------------------------------------------\n         USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n\n         ZT = EXP (ZILFC * SQRT (USTAR * Z0))* Z0\n         ZSLT = ZLM + ZT\n!-----------------------------------------------------------------------\n         RLOGT = log (ZSLT / ZT)\n         USTARK = USTAR * VKRM\n         AKMS = MAX (USTARK / SIMM,CXCH)\n!-----------------------------------------------------------------------\n! IF STATEMENTS TO AVOID TANGENT LINEAR PROBLEMS NEAR ZERO\n!-----------------------------------------------------------------------\n         AKHS = MAX (USTARK / SIMH,CXCH)\n         IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n            WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n         ELSE\n            WSTAR2 = 0.0\n         END IF\n!-----------------------------------------------------------------------\n         RLMN = ELFC * AKHS * DTHV / USTAR **3\n!-----------------------------------------------------------------------\n!     IF(ABS((RLMN-RLMO)/RLMA).LT.EPSIT)    GO TO 110\n!-----------------------------------------------------------------------\n         RLMA = RLMO * WOLD+ RLMN * WNEW\n!-----------------------------------------------------------------------\n         RLMO = RLMA\n!     PRINT*,'----------------------------'\n!     PRINT*,'SFCDIF OUTPUT !  ! ! ! ! ! ! ! !  !   !    !'\n\n!     PRINT*,'ZLM=',ZLM\n!     PRINT*,'Z0=',Z0\n!     PRINT*,'THZ0=',THZ0\n!     PRINT*,'THLM=',THLM\n!     PRINT*,'SFCSPD=',SFCSPD\n!     PRINT*,'CZIL=',CZIL\n!     PRINT*,'AKMS=',AKMS\n!     PRINT*,'AKHS=',AKHS\n!     PRINT*,'----------------------------'\n\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE SFCDIF_off\n! ----------------------------------------------------------------------\n\nEND MODULE module_sf_noahlsm\n"
  },
  {
    "path": "src/Land_models/Noah/Noah/module_sf_noahlsm.F.org",
    "content": "MODULE module_sf_noahlsm\n  USE module_model_constants\n\n!   REAL, PARAMETER    :: CP = 1004.5\n  REAL, PARAMETER      :: RD = 287.04, SIGMA = 5.67E-8,                 &\n                          CPH2O = 4.218E+3,CPICE = 2.106E+3,            &\n                          LSUBF = 3.335E+5,                             &\n                          EMISSI_S = 0.95\n\n! VEGETATION PARAMETERS\n        INTEGER :: LUCATS , BARE\n        INTEGER :: NATURAL\n        integer, PARAMETER :: NLUS=50\n        CHARACTER(LEN=256) LUTYPE\n        INTEGER, DIMENSION(1:NLUS) :: NROTBL\n        real, dimension(1:NLUS) ::  SNUPTBL, RSTBL, RGLTBL, HSTBL,                &\n                                    SHDTBL, MAXALB,                               &\n                                    EMISSMINTBL, EMISSMAXTBL,                     &\n                                    LAIMINTBL, LAIMAXTBL,                         &\n                                    Z0MINTBL, Z0MAXTBL,                           &\n                                    ALBEDOMINTBL, ALBEDOMAXTBL\n        REAL ::   TOPT_DATA,CMCMAX_DATA,CFACTR_DATA,RSMAX_DATA\n\n! SOIL PARAMETERS\n        INTEGER :: SLCATS\n        INTEGER, PARAMETER :: NSLTYPE=30\n        CHARACTER(LEN=256) SLTYPE\n        REAL, DIMENSION (1:NSLTYPE) :: BB,DRYSMC,F11,                           &\n        MAXSMC, REFSMC,SATPSI,SATDK,SATDW, WLTSMC,QTZ\n\n! LSM GENERAL PARAMETERS\n        INTEGER :: SLPCATS\n        INTEGER, PARAMETER :: NSLOPE=30\n        REAL, DIMENSION (1:NSLOPE) :: SLOPE_DATA\n        REAL ::  SBETA_DATA,FXEXP_DATA,CSOIL_DATA,SALP_DATA,REFDK_DATA,           &\n                 REFKDT_DATA,FRZK_DATA,ZBOT_DATA,  SMLOW_DATA,SMHIGH_DATA,        &\n                        CZIL_DATA\n        REAL ::  LVCOEF_DATA\n\n        CHARACTER*256  :: err_message\n\n#ifdef _HRLDAS_OFFLINE_\n        integer, parameter :: nsold = 100\n        integer :: ISURBAN\n        ! To pass a few arguments to SFLX that used to come from REDPRM:\n        real :: offline_cfactr\n        real :: offline_cmcmax\n        real :: offline_rsmax\n        real :: offline_topt\n        real :: offline_refkdt\n        real :: offline_kdt\n        real :: offline_sbeta\n        real :: offline_rsmin\n        real :: offline_rgl\n        real :: offline_hs\n        real :: offline_zbot\n        real :: offline_frzx\n        real :: offline_psisat\n        real :: offline_slope\n        real :: offline_snup\n        real :: offline_salp\n        real :: offline_bexp\n        real :: offline_dksat\n        real :: offline_dwsat\n        real :: offline_smcmax\n        real :: offline_smcwlt\n        real :: offline_smcref\n        real :: offline_smcdry\n        real :: offline_quartz\n        real :: offline_f1\n        real :: offline_fxexp\n        real, dimension(1:nsold) :: offline_rtdis\n        integer :: offline_nroot\n        real :: offline_czil\n        real :: offline_csoil\n        real :: offline_ptu\n        real :: offline_lvcoef\n#endif\n\n!\nCONTAINS\n!\n\n      SUBROUTINE SFLX (FFROZP,ICE,ISURBAN,DT,ZLVL,NSOIL,SLDPTH,         &    !C\n                       LOCAL,                                           &    !L\n                       LLANDUSE, LSOIL,                                 &    !CL\n                       LWDN,SOLDN,SOLNET,SFCPRS,PRCP,SFCTMP,Q2,SFCSPD,  &    !F\n                       COSZ,PRCPRAIN, SOLARDIRECT,                      &    !F\n                       TH2,Q2SAT,DQSDT2,                                &    !I\n                       VEGTYP,SOILTYP,SLOPETYP,SHDFAC,SHDMIN,SHDMAX,    &    !I\n                       ALB, SNOALB,TBOT, Z0BRD, Z0, EMISSI, EMBRD,      &    !S\n                       CMC,T1,STC,SMC,SH2O,SNOWH,SNEQV,ALBEDO,CH,CM,    &    !H\n! ----------------------------------------------------------------------\n! OUTPUTS, DIAGNOSTICS, PARAMETERS BELOW GENERALLY NOT NECESSARY WHEN\n! COUPLED WITH E.G. A NWP MODEL (SUCH AS THE NOAA/NWS/NCEP MESOSCALE ETA\n! MODEL).  OTHER APPLICATIONS MAY REQUIRE DIFFERENT OUTPUT VARIABLES.\n! ----------------------------------------------------------------------\n                       ETA,SHEAT, ETA_KINEMATIC,FDOWN,                  &    !O\n                       EC,EDIR,ET,ETT,ESNOW,DRIP,DEW,                   &    !O\n                       BETA,ETP,SSOIL,                                  &    !O\n                       FLX1,FLX2,FLX3,                                  &    !O\n                       SNOMLT,SNCOVR,                                   &    !O\n                       RUNOFF1,RUNOFF2,RUNOFF3,                         &    !O\n                       RC,PC,RSMIN,XLAI,RCS,RCT,RCQ,RCSOIL,             &    !O\n                       SOILW,SOILM,Q1,SMAV,                             &    !D\n                       RDLAI2D,USEMONALB,                               &\n                       SNOTIME1,                                        &\n                       RIBB,                                            &\n                       SMCWLT,SMCDRY,SMCREF,SMCMAX,NROOT)                    !P\n! ----------------------------------------------------------------------\n! SUBROUTINE SFLX - UNIFIED NOAHLSM VERSION 1.0 JULY 2007\n! ----------------------------------------------------------------------\n! SUB-DRIVER FOR \"Noah LSM\" FAMILY OF PHYSICS SUBROUTINES FOR A\n! SOIL/VEG/SNOWPACK LAND-SURFACE MODEL TO UPDATE SOIL MOISTURE, SOIL\n! ICE, SOIL TEMPERATURE, SKIN TEMPERATURE, SNOWPACK WATER CONTENT,\n! SNOWDEPTH, AND ALL TERMS OF THE SURFACE ENERGY BALANCE AND SURFACE\n! WATER BALANCE (EXCLUDING INPUT ATMOSPHERIC FORCINGS OF DOWNWARD\n! RADIATION AND PRECIP)\n! ----------------------------------------------------------------------\n! SFLX ARGUMENT LIST KEY:\n! ----------------------------------------------------------------------\n!  C  CONFIGURATION INFORMATION\n!  L  LOGICAL\n! CL  4-string character bearing logical meaning\n!  F  FORCING DATA\n!  I  OTHER (INPUT) FORCING DATA\n!  S  SURFACE CHARACTERISTICS\n!  H  HISTORY (STATE) VARIABLES\n!  O  OUTPUT VARIABLES\n!  D  DIAGNOSTIC OUTPUT\n!  P  Parameters\n!  Msic Miscellaneous terms passed from gridded driver\n! ----------------------------------------------------------------------\n! 1. CONFIGURATION INFORMATION (C):\n! ----------------------------------------------------------------------\n!   ICE        SEA-ICE FLAG  (=1: SEA-ICE, =0: LAND (NO ICE), --1 LAND-ICE).\n!   DT         TIMESTEP (SEC) (DT SHOULD NOT EXCEED 3600 SECS, RECOMMEND\n!                1800 SECS OR LESS)\n!   ZLVL       HEIGHT (M) ABOVE GROUND OF ATMOSPHERIC FORCING VARIABLES\n!   NSOIL      NUMBER OF SOIL LAYERS (AT LEAST 2, AND NOT GREATER THAN\n!                PARAMETER NSOLD SET BELOW)\n!   SLDPTH     THE THICKNESS OF EACH SOIL LAYER (M)\n! ----------------------------------------------------------------------\n! 2. LOGICAL:\n! ----------------------------------------------------------------------\n!   LCH       Exchange coefficient (Ch) calculation flag (false: using\n!                ch-routine SFCDIF; true: Ch is brought in)\n!   LOCAL      Flag for local-site simulation (where there is no\n!              maps for albedo, veg fraction, and roughness\n!             true:  all LSM parameters (inluding albedo, veg fraction and\n!                    roughness length) will be defined by three tables\n!   LLANDUSE  (=USGS, using USGS landuse classification)\n!   LSOIL     (=STAS, using FAO/STATSGO soil texture classification)\n! ----------------------------------------------------------------------\n! 3. FORCING DATA (F):\n! ----------------------------------------------------------------------\n!   LWDN       LW DOWNWARD RADIATION (W M-2; POSITIVE, NOT NET LONGWAVE)\n!   SOLDN      SOLAR DOWNWARD RADIATION (W M-2; POSITIVE, NOT NET SOLAR)\n!   SOLNET     NET DOWNWARD SOLAR RADIATION ((W M-2; POSITIVE)\n!   SFCPRS     PRESSURE AT HEIGHT ZLVL ABOVE GROUND (PASCALS)\n!   PRCP       PRECIP RATE (KG M-2 S-1) (NOTE, THIS IS A RATE)\n!   SFCTMP     AIR TEMPERATURE (K) AT HEIGHT ZLVL ABOVE GROUND\n!   TH2        AIR POTENTIAL TEMPERATURE (K) AT HEIGHT ZLVL ABOVE GROUND\n!   Q2         MIXING RATIO AT HEIGHT ZLVL ABOVE GROUND (KG KG-1)\n!   COSZ       Solar zenith angle (not used for now)\n!   PRCPRAIN   Liquid-precipitation rate (KG M-2 S-1) (not used)\n! SOLARDIRECT  Direct component of downward solar radiation (W M-2) (not used)\n!   FFROZP     FRACTION OF FROZEN PRECIPITATION\n! ----------------------------------------------------------------------\n! 4. OTHER FORCING (INPUT) DATA (I):\n! ----------------------------------------------------------------------\n!   SFCSPD     WIND SPEED (M S-1) AT HEIGHT ZLVL ABOVE GROUND\n!   Q2SAT      SAT SPECIFIC HUMIDITY AT HEIGHT ZLVL ABOVE GROUND (KG KG-1)\n!   DQSDT2     SLOPE OF SAT SPECIFIC HUMIDITY CURVE AT T=SFCTMP\n!                (KG KG-1 K-1)\n! ----------------------------------------------------------------------\n! 5. CANOPY/SOIL CHARACTERISTICS (S):\n! ----------------------------------------------------------------------\n!   VEGTYP     VEGETATION TYPE (INTEGER INDEX)\n!   SOILTYP    SOIL TYPE (INTEGER INDEX)\n!   SLOPETYP   CLASS OF SFC SLOPE (INTEGER INDEX)\n!   SHDFAC     AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!                (FRACTION= 0.0-1.0)\n!   SHDMIN     MINIMUM AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!                (FRACTION= 0.0-1.0) <= SHDFAC\n!   PTU        PHOTO THERMAL UNIT (PLANT PHENOLOGY FOR ANNUALS/CROPS)\n!                (NOT YET USED, BUT PASSED TO REDPRM FOR FUTURE USE IN\n!                VEG PARMS)\n!   ALB        BACKROUND SNOW-FREE SURFACE ALBEDO (FRACTION), FOR JULIAN\n!                DAY OF YEAR (USUALLY FROM TEMPORAL INTERPOLATION OF\n!                MONTHLY MEAN VALUES' CALLING PROG MAY OR MAY NOT\n!                INCLUDE DIURNAL SUN ANGLE EFFECT)\n!   SNOALB     UPPER BOUND ON MAXIMUM ALBEDO OVER DEEP SNOW (E.G. FROM\n!                ROBINSON AND KUKLA, 1985, J. CLIM. & APPL. METEOR.)\n!   TBOT       BOTTOM SOIL TEMPERATURE (LOCAL YEARLY-MEAN SFC AIR\n!                TEMPERATURE)\n!   Z0BRD      Background fixed roughness length (M)\n!   Z0         Time varying roughness length (M) as function of snow depth\n!\n!   EMBRD      Background surface emissivity (between 0 and 1)\n!   EMISSI     Surface emissivity (between 0 and 1)\n! ----------------------------------------------------------------------\n! 6. HISTORY (STATE) VARIABLES (H):\n! ----------------------------------------------------------------------\n!  CMC         CANOPY MOISTURE CONTENT (M)\n!  T1          GROUND/CANOPY/SNOWPACK) EFFECTIVE SKIN TEMPERATURE (K)\n!  STC(NSOIL)  SOIL TEMP (K)\n!  SMC(NSOIL)  TOTAL SOIL MOISTURE CONTENT (VOLUMETRIC FRACTION)\n!  SH2O(NSOIL) UNFROZEN SOIL MOISTURE CONTENT (VOLUMETRIC FRACTION)\n!                NOTE: FROZEN SOIL MOISTURE = SMC - SH2O\n!  SNOWH       ACTUAL SNOW DEPTH (M)\n!  SNEQV       LIQUID WATER-EQUIVALENT SNOW DEPTH (M)\n!                NOTE: SNOW DENSITY = SNEQV/SNOWH\n!  ALBEDO      SURFACE ALBEDO INCLUDING SNOW EFFECT (UNITLESS FRACTION)\n!                =SNOW-FREE ALBEDO (ALB) WHEN SNEQV=0, OR\n!                =FCT(MSNOALB,ALB,VEGTYP,SHDFAC,SHDMIN) WHEN SNEQV>0\n!  CH          SURFACE EXCHANGE COEFFICIENT FOR HEAT AND MOISTURE\n!                (M S-1); NOTE: CH IS TECHNICALLY A CONDUCTANCE SINCE\n!                IT HAS BEEN MULTIPLIED BY WIND SPEED.\n!  CM          SURFACE EXCHANGE COEFFICIENT FOR MOMENTUM (M S-1); NOTE:\n!                CM IS TECHNICALLY A CONDUCTANCE SINCE IT HAS BEEN\n!                MULTIPLIED BY WIND SPEED.\n! ----------------------------------------------------------------------\n! 7. OUTPUT (O):\n! ----------------------------------------------------------------------\n! OUTPUT VARIABLES NECESSARY FOR A COUPLED NUMERICAL WEATHER PREDICTION\n! MODEL, E.G. NOAA/NWS/NCEP MESOSCALE ETA MODEL.  FOR THIS APPLICATION,\n! THE REMAINING OUTPUT/DIAGNOSTIC/PARAMETER BLOCKS BELOW ARE NOT\n! NECESSARY.  OTHER APPLICATIONS MAY REQUIRE DIFFERENT OUTPUT VARIABLES.\n!   ETA        ACTUAL LATENT HEAT FLUX (W m-2: NEGATIVE, IF UP FROM\n!              SURFACE)\n!  ETA_KINEMATIC atctual latent heat flux in Kg m-2 s-1\n!   SHEAT      SENSIBLE HEAT FLUX (W M-2: NEGATIVE, IF UPWARD FROM\n!              SURFACE)\n!   FDOWN      Radiation forcing at the surface (W m-2) = SOLDN*(1-alb)+LWDN\n! ----------------------------------------------------------------------\n!   EC         CANOPY WATER EVAPORATION (W m-2)\n!   EDIR       DIRECT SOIL EVAPORATION (W m-2)\n!   ET(NSOIL)  PLANT TRANSPIRATION FROM A PARTICULAR ROOT (SOIL) LAYER\n!                 (W m-2)\n!   ETT        TOTAL PLANT TRANSPIRATION (W m-2)\n!   ESNOW      SUBLIMATION FROM (OR DEPOSITION TO IF <0) SNOWPACK\n!                (W m-2)\n!   DRIP       THROUGH-FALL OF PRECIP AND/OR DEW IN EXCESS OF CANOPY\n!                WATER-HOLDING CAPACITY (M)\n!   DEW        DEWFALL (OR FROSTFALL FOR T<273.15) (M)\n! ----------------------------------------------------------------------\n!   BETA       RATIO OF ACTUAL/POTENTIAL EVAP (DIMENSIONLESS)\n!   ETP        POTENTIAL EVAPORATION (W m-2)\n!   SSOIL      SOIL HEAT FLUX (W M-2: NEGATIVE IF DOWNWARD FROM SURFACE)\n! ----------------------------------------------------------------------\n!   FLX1       PRECIP-SNOW SFC (W M-2)\n!   FLX2       FREEZING RAIN LATENT HEAT FLUX (W M-2)\n!   FLX3       PHASE-CHANGE HEAT FLUX FROM SNOWMELT (W M-2)\n! ----------------------------------------------------------------------\n!   SNOMLT     SNOW MELT (M) (WATER EQUIVALENT)\n!   SNCOVR     FRACTIONAL SNOW COVER (UNITLESS FRACTION, 0-1)\n! ----------------------------------------------------------------------\n!   RUNOFF1    SURFACE RUNOFF (M S-1), NOT INFILTRATING THE SURFACE\n!   RUNOFF2    SUBSURFACE RUNOFF (M S-1), DRAINAGE OUT BOTTOM OF LAST\n!                SOIL LAYER (BASEFLOW)\n!   RUNOFF3    NUMERICAL TRUNCTATION IN EXCESS OF POROSITY (SMCMAX)\n!                FOR A GIVEN SOIL LAYER AT THE END OF A TIME STEP (M S-1).\n! Note: the above RUNOFF2 is actually the sum of RUNOFF2 and RUNOFF3\n! ----------------------------------------------------------------------\n!   RC         CANOPY RESISTANCE (S M-1)\n!   PC         PLANT COEFFICIENT (UNITLESS FRACTION, 0-1) WHERE PC*ETP\n!                = ACTUAL TRANSP\n!   XLAI       LEAF AREA INDEX (DIMENSIONLESS)\n!   RSMIN      MINIMUM CANOPY RESISTANCE (S M-1)\n!   RCS        INCOMING SOLAR RC FACTOR (DIMENSIONLESS)\n!   RCT        AIR TEMPERATURE RC FACTOR (DIMENSIONLESS)\n!   RCQ        ATMOS VAPOR PRESSURE DEFICIT RC FACTOR (DIMENSIONLESS)\n!   RCSOIL     SOIL MOISTURE RC FACTOR (DIMENSIONLESS)\n! ----------------------------------------------------------------------\n! 8. DIAGNOSTIC OUTPUT (D):\n! ----------------------------------------------------------------------\n!   SOILW      AVAILABLE SOIL MOISTURE IN ROOT ZONE (UNITLESS FRACTION\n!              BETWEEN SMCWLT AND SMCMAX)\n!   SOILM      TOTAL SOIL COLUMN MOISTURE CONTENT (FROZEN+UNFROZEN) (M)\n!   Q1         Effective mixing ratio at surface (kg kg-1), used for\n!              diagnosing the mixing ratio at 2 meter for coupled model\n!   SMAV       Soil Moisture Availability for each layer, as a fraction \n!              between SMCWLT and SMCMAX.\n!  Documentation for SNOTIME1 and SNOABL2 ?????\n!  What categories of arguments do these variables fall into ????\n!  Documentation for RIBB ?????\n!  What category of argument does RIBB fall into ?????\n! ----------------------------------------------------------------------\n! 9. PARAMETERS (P):\n! ----------------------------------------------------------------------\n!   SMCWLT     WILTING POINT (VOLUMETRIC)\n!   SMCDRY     DRY SOIL MOISTURE THRESHOLD WHERE DIRECT EVAP FRM TOP\n!                LAYER ENDS (VOLUMETRIC)\n!   SMCREF     SOIL MOISTURE THRESHOLD WHERE TRANSPIRATION BEGINS TO\n!                STRESS (VOLUMETRIC)\n!   SMCMAX     POROSITY, I.E. SATURATED VALUE OF SOIL MOISTURE\n!                (VOLUMETRIC)\n!   NROOT      NUMBER OF ROOT LAYERS, A FUNCTION OF VEG TYPE, DETERMINED\n!              IN SUBROUTINE REDPRM.\n! ----------------------------------------------------------------------\n\n\n      IMPLICIT NONE\n! ----------------------------------------------------------------------\n\n! DECLARATIONS - LOGICAL AND CHARACTERS\n! ----------------------------------------------------------------------\n      LOGICAL, INTENT(IN)::  LOCAL\n      LOGICAL            ::  FRZGRA, SNOWNG\n      CHARACTER (LEN=256), INTENT(IN)::  LLANDUSE, LSOIL\n\n! ----------------------------------------------------------------------\n! 1. CONFIGURATION INFORMATION (C):\n! ----------------------------------------------------------------------\n      INTEGER,INTENT(IN) ::  ICE,NSOIL,SLOPETYP,SOILTYP,VEGTYP\n      INTEGER, INTENT(IN) :: ISURBAN\n      INTEGER,INTENT(OUT)::  NROOT\n      INTEGER  KZ, K, iout\n\n! ----------------------------------------------------------------------\n! 2. LOGICAL:\n! ----------------------------------------------------------------------\n      LOGICAL, INTENT(IN) :: RDLAI2D\n      LOGICAL, INTENT(IN) :: USEMONALB\n\n      REAL, INTENT(IN)   :: SHDMIN,SHDMAX,DT,DQSDT2,LWDN,PRCP,PRCPRAIN,     &\n                            Q2,Q2SAT,SFCPRS,SFCSPD,SFCTMP, SNOALB,          &\n                            SOLDN,SOLNET,TBOT,TH2,ZLVL,                            &\n                            FFROZP\n      REAL, INTENT(OUT)  :: EMBRD\n      REAL, INTENT(OUT)  :: ALBEDO\n      REAL, INTENT(INOUT):: COSZ, SOLARDIRECT,CH,CM,                        &\n                            CMC,SNEQV,SNCOVR,SNOWH,T1,XLAI,SHDFAC,Z0BRD,    &\n                            EMISSI, ALB\n      REAL, INTENT(INOUT):: SNOTIME1\n      REAL, INTENT(INOUT):: RIBB\n      REAL, DIMENSION(1:NSOIL), INTENT(IN) :: SLDPTH\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: ET\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: SMAV\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) ::  SH2O, SMC, STC\n      REAL,DIMENSION(1:NSOIL)::   RTDIS, ZSOIL\n\n      REAL,INTENT(OUT)   :: ETA_KINEMATIC,BETA,DEW,DRIP,EC,EDIR,ESNOW,ETA,  &\n                            ETP,FLX1,FLX2,FLX3,SHEAT,PC,RUNOFF1,RUNOFF2,    &\n                            RUNOFF3,RC,RSMIN,RCQ,RCS,RCSOIL,RCT,SSOIL,      &\n                            SMCDRY,SMCMAX,SMCREF,SMCWLT,SNOMLT, SOILM,      &\n                            SOILW,FDOWN,Q1\n      REAL :: BEXP,CFACTR,CMCMAX,CSOIL,CZIL,DF1,DF1H,DF1A,DKSAT,DWSAT,      &\n              DSOIL,DTOT,ETT,FRCSNO,FRCSOI,EPSCA,F1,FXEXP,FRZX,HS,          &\n              KDT,LVH2O,PRCP1,PSISAT,QUARTZ,R,RCH,REFKDT,RR,RGL,            &\n              RSMAX,                                                        &\n              RSNOW,SNDENS,SNCOND,SBETA,SN_NEW,SLOPE,SNUP,SALP,SOILWM,      &\n              SOILWW,T1V,T24,T2V,TH2V,TOPT,TFREEZ,TSNOW,ZBOT,Z0,PRCPF,      &\n              ETNS,PTU,LSUBS\n        REAL ::  LVCOEF\n      REAL :: INTERP_FRACTION\n      REAL :: LAIMIN,    LAIMAX\n      REAL :: ALBEDOMIN, ALBEDOMAX\n      REAL :: EMISSMIN,  EMISSMAX\n      REAL :: Z0MIN,     Z0MAX\n\n! ----------------------------------------------------------------------\n! DECLARATIONS - PARAMETERS\n! ----------------------------------------------------------------------\n      PARAMETER (TFREEZ = 273.15)\n      PARAMETER (LVH2O = 2.501E+6)\n      PARAMETER (LSUBS = 2.83E+6)\n      PARAMETER (R = 287.04)\n! ----------------------------------------------------------------------\n!   INITIALIZATION\n! ----------------------------------------------------------------------\n         RUNOFF1 = 0.0\n         RUNOFF2 = 0.0\n         RUNOFF3 = 0.0\n         SNOMLT = 0.0\n\n! ----------------------------------------------------------------------\n!  THE VARIABLE \"ICE\" IS A FLAG DENOTING SEA-ICE / LAND-ICE / ICE-FREE LAND\n!     SEA-ICE CASE,          ICE =  1\n!     NON-GLACIAL LAND,      ICE =  0\n!     GLACIAL-ICE LAND,      ICE = -1\n      IF (ICE /= 0) SHDFAC = 0.0\n! ----------------------------------------------------------------------\n! SEA-ICE LAYERS ARE EQUAL THICKNESS AND SUM TO 3 METERS\n! ----------------------------------------------------------------------\n         IF (ICE == 1) THEN\n            DO KZ = 1,NSOIL\n               ZSOIL (KZ) = -3.* FLOAT (KZ)/ FLOAT (NSOIL)\n            END DO\n\n! ----------------------------------------------------------------------\n! CALCULATE DEPTH (NEGATIVE) BELOW GROUND FROM TOP SKIN SFC TO BOTTOM OF\n!   EACH SOIL LAYER.  NOTE:  SIGN OF ZSOIL IS NEGATIVE (DENOTING BELOW\n!   GROUND)\n! ----------------------------------------------------------------------\n         ELSE\n            ZSOIL (1) = - SLDPTH (1)\n            DO KZ = 2,NSOIL\n               ZSOIL (KZ) = - SLDPTH (KZ) + ZSOIL (KZ -1)\n            END DO\n         END IF\n! ----------------------------------------------------------------------\n! NEXT IS CRUCIAL CALL TO SET THE LAND-SURFACE PARAMETERS, INCLUDING\n! SOIL-TYPE AND VEG-TYPE DEPENDENT PARAMETERS.\n! ----------------------------------------------------------------------\n         CALL REDPRM (VEGTYP,SOILTYP,SLOPETYP,CFACTR,CMCMAX,RSMAX,TOPT,   &\n                       REFKDT,KDT,SBETA, SHDFAC,RSMIN,RGL,HS,ZBOT,FRZX,    &\n                         PSISAT,SLOPE,SNUP,SALP,BEXP,DKSAT,DWSAT,          &\n                         SMCMAX,SMCWLT,SMCREF,SMCDRY,F1,QUARTZ,FXEXP,      &\n                         RTDIS,SLDPTH,ZSOIL,NROOT,NSOIL,CZIL,              &\n                         LAIMIN, LAIMAX, EMISSMIN, EMISSMAX, ALBEDOMIN,    &\n                         ALBEDOMAX, Z0MIN, Z0MAX, CSOIL, PTU, LLANDUSE,    &\n                         LSOIL,LOCAL,LVCOEF)\n\n!urban\n         IF(VEGTYP==ISURBAN)THEN\n              SHDFAC=0.05\n              RSMIN=400.0\n              SMCMAX = 0.45\n              SMCREF = 0.42\n              SMCWLT = 0.40\n              SMCDRY = 0.40\n         ENDIF\n\n         IF ( SHDFAC >= SHDMAX ) THEN\n            EMBRD = EMISSMAX\n            IF (.NOT. RDLAI2D) THEN\n               XLAI  = LAIMAX\n            ENDIF\n            IF (.NOT. USEMONALB) THEN\n               ALB   = ALBEDOMIN\n            ENDIF\n            Z0BRD = Z0MAX\n         ELSE IF ( SHDFAC <= SHDMIN ) THEN\n            EMBRD = EMISSMIN\n            IF(.NOT. RDLAI2D) THEN\n               XLAI  = LAIMIN\n            ENDIF\n            IF(.NOT. USEMONALB) then\n               ALB   = ALBEDOMAX\n            ENDIF\n            Z0BRD = Z0MIN\n         ELSE\n\n            IF ( SHDMAX > SHDMIN ) THEN\n\n               INTERP_FRACTION = ( SHDFAC - SHDMIN ) / ( SHDMAX - SHDMIN )\n               ! Bound INTERP_FRACTION between 0 and 1\n               INTERP_FRACTION = MIN ( INTERP_FRACTION, 1.0 )\n               INTERP_FRACTION = MAX ( INTERP_FRACTION, 0.0 )\n               ! Scale Emissivity and LAI between EMISSMIN and EMISSMAX by INTERP_FRACTION\n               EMBRD = ( ( 1.0 - INTERP_FRACTION ) * EMISSMIN  ) + ( INTERP_FRACTION * EMISSMAX  )\n               IF (.NOT. RDLAI2D) THEN\n                  XLAI  = ( ( 1.0 - INTERP_FRACTION ) * LAIMIN    ) + ( INTERP_FRACTION * LAIMAX    )\n               ENDIF\n               if (.not. USEMONALB) then\n                  ALB   = ( ( 1.0 - INTERP_FRACTION ) * ALBEDOMAX ) + ( INTERP_FRACTION * ALBEDOMIN )\n               endif\n               Z0BRD = ( ( 1.0 - INTERP_FRACTION ) * Z0MIN     ) + ( INTERP_FRACTION * Z0MAX     )\n\n            ELSE\n\n               EMBRD = 0.5 * EMISSMIN  + 0.5 * EMISSMAX\n               IF (.NOT. RDLAI2D) THEN\n                  XLAI  = 0.5 * LAIMIN    + 0.5 * LAIMAX\n               ENDIF\n               if (.not. USEMONALB) then\n                  ALB   = 0.5 * ALBEDOMIN + 0.5 * ALBEDOMAX\n               endif\n               Z0BRD = 0.5 * Z0MIN     + 0.5 * Z0MAX\n\n            ENDIF\n\n         ENDIF\n! ----------------------------------------------------------------------\n!  INITIALIZE PRECIPITATION LOGICALS.\n! ----------------------------------------------------------------------\n         SNOWNG = .FALSE.\n         FRZGRA = .FALSE.\n\n! ----------------------------------------------------------------------\n! OVER SEA-ICE OR GLACIAL-ICE, IF S.W.E. (SNEQV) BELOW THRESHOLD LOWER\n! BOUND (0.01 M FOR SEA-ICE, 0.10 M FOR GLACIAL-ICE), THEN SET AT LOWER\n! BOUND\n! ----------------------------------------------------------------------\n! IF SEA-ICE CASE, ASSIGN DEFAULT WATER-EQUIV SNOW ON TOP\n! ----------------------------------------------------------------------\n         IF (ICE == 1) THEN\n            ! Sea-ice case\n            IF ( SNEQV < 0.01 ) THEN\n               SNEQV = 0.01\n               SNOWH = 0.05\n            ENDIF\n         ELSE IF ( ICE == -1 ) THEN\n            ! Land-ice case\n            IF ( SNEQV < 0.10 ) THEN\n               SNEQV = 0.10\n               SNOWH = 0.50\n            ENDIF\n         END IF\n! ----------------------------------------------------------------------\n! FOR SEA-ICE AND GLACIAL-ICE CASES, SET SMC AND SH20 VALUES = 1.0\n! ----------------------------------------------------------------------\n         IF ( ICE /= 0 ) THEN\n            DO KZ = 1,NSOIL\n               SMC(KZ) = 1.0\n               SH2O(KZ) = 1.0\n            END DO\n         ENDIF\n! ----------------------------------------------------------------------\n! IF INPUT SNOWPACK IS NONZERO, THEN COMPUTE SNOW DENSITY \"SNDENS\" AND\n!   SNOW THERMAL CONDUCTIVITY \"SNCOND\" (NOTE THAT CSNOW IS A FUNCTION\n!   SUBROUTINE)\n! ----------------------------------------------------------------------\n         IF ( SNEQV <= 1.E-7 ) THEN ! safer IF\tkmh (2008/03/25)\n            SNEQV = 0.0\n            SNDENS = 0.0\n            SNOWH = 0.0\n            SNCOND = 1.0\n         ELSE\n            SNDENS = SNEQV / SNOWH\n            IF(SNDENS > 1.0) THEN\n             CALL wrf_error_fatal ( 'Physical snow depth is less than snow water equiv.' )\n            ENDIF\n            CALL CSNOW (SNCOND,SNDENS)\n         END IF\n! ----------------------------------------------------------------------\n! DETERMINE IF IT'S PRECIPITATING AND WHAT KIND OF PRECIP IT IS.\n! IF IT'S PRCPING AND THE AIR TEMP IS COLDER THAN 0 C, IT'S SNOWING!\n! IF IT'S PRCPING AND THE AIR TEMP IS WARMER THAN 0 C, BUT THE GRND\n! TEMP IS COLDER THAN 0 C, FREEZING RAIN IS PRESUMED TO BE FALLING.\n! ----------------------------------------------------------------------\n         IF (PRCP > 0.0) THEN\n! snow defined when fraction of frozen precip (FFROZP) > 0.5,\n! passed in from model microphysics.\n            IF (FFROZP .GT. 0.5) THEN\n               SNOWNG = .TRUE.\n            ELSE\n               IF (T1 <= TFREEZ) FRZGRA = .TRUE.\n            END IF\n         END IF\n! ----------------------------------------------------------------------\n! IF EITHER PRCP FLAG IS SET, DETERMINE NEW SNOWFALL (CONVERTING PRCP\n! RATE FROM KG M-2 S-1 TO A LIQUID EQUIV SNOW DEPTH IN METERS) AND ADD\n! IT TO THE EXISTING SNOWPACK.\n! NOTE THAT SINCE ALL PRECIP IS ADDED TO SNOWPACK, NO PRECIP INFILTRATES\n! INTO THE SOIL SO THAT PRCP1 IS SET TO ZERO.\n! ----------------------------------------------------------------------\n         IF ( (SNOWNG) .OR. (FRZGRA) ) THEN\n            SN_NEW = PRCP * DT * 0.001\n            SNEQV = SNEQV + SN_NEW\n            PRCPF = 0.0\n\n! ----------------------------------------------------------------------\n! UPDATE SNOW DENSITY BASED ON NEW SNOWFALL, USING OLD AND NEW SNOW.\n! UPDATE SNOW THERMAL CONDUCTIVITY\n! ----------------------------------------------------------------------\n            CALL SNOW_NEW (SFCTMP,SN_NEW,SNOWH,SNDENS)\n!\n! kmh 09/04/2006 set Snow Density at 0.2 g/cm**3\n! for \"cold permanent ice\" or new \"dry\" snow\n!\n           IF ( (ICE /= 0) .and. SNCOVR .GT. 0.99 ) THEN\n!  if soil temperature less than 268.15 K, treat as typical Antarctic/Greenland snow firn\n              IF ( STC(1) .LT. (TFREEZ - 5.) ) SNDENS = 0.2\n              IF ( SNOWNG .AND. (T1.LT.273.) .AND. (SFCTMP.LT.273.) ) SNDENS=0.2\n           ENDIF\n!\n            CALL CSNOW (SNCOND,SNDENS)\n\n! ----------------------------------------------------------------------\n! PRECIP IS LIQUID (RAIN), HENCE SAVE IN THE PRECIP VARIABLE THAT\n! LATER CAN WHOLELY OR PARTIALLY INFILTRATE THE SOIL (ALONG WITH\n! ANY CANOPY \"DRIP\" ADDED TO THIS LATER)\n! ----------------------------------------------------------------------\n         ELSE\n            PRCPF = PRCP\n         END IF\n! ----------------------------------------------------------------------\n! DETERMINE SNOWCOVER AND ALBEDO OVER LAND.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! IF SNOW DEPTH=0, SET SNOW FRACTION=0, ALBEDO=SNOW FREE ALBEDO.\n! ----------------------------------------------------------------------\n         IF (ICE == 0 .OR. ICE == -1) THEN\n            IF (SNEQV  == 0.0) THEN\n               SNCOVR = 0.0\n               ALBEDO = ALB\n               EMISSI = EMBRD\n            ELSE\n! ----------------------------------------------------------------------\n! DETERMINE SNOW FRACTIONAL COVERAGE.\n! DETERMINE SURFACE ALBEDO MODIFICATION DUE TO SNOWDEPTH STATE.\n! ----------------------------------------------------------------------\n              CALL SNFRAC (SNEQV,SNUP,SALP,SNOWH,SNCOVR)\n!   Don't limit snow cover fraction over permanent ice kmh 2008/03/25\n            if ( ICE == 0 ) then\n              SNCOVR = MIN(SNCOVR,0.98)\n            endif\n              CALL ALCALC (ALB,SNOALB,EMBRD,SHDFAC,SHDMIN,SNCOVR,T1,ALBEDO,EMISSI,   &\n                         DT,SNOWNG,SNOTIME1,LVCOEF)\n            END IF\n! ----------------------------------------------------------------------\n! SNOW COVER, ALBEDO OVER SEA-ICE, GLACIAL ICE\n! ----------------------------------------------------------------------\n         ELSE\n            SNCOVR = 1.0\n!\n! Albedo of sea ice\n!\n! This value should vary seasonally. 0.65 may be good for Arctic Ocean summer bare ice\n!   value could be as low as 0.4 for Arctic bare ice and melt pond combo (Perovich data)\n!   0.82 may be good for Arctic spring/fall sea ice (Perovich data)\n!   0.81 may be good for Antarctic sea ice (Wendler et al. December cruise data)\n!\n            ALBEDO = 0.80\n!\n            EMISSI = 0.98\n         END IF\n! ----------------------------------------------------------------------\n! THERMAL CONDUCTIVITY FOR SEA-ICE CASE, GLACIAL-ICE CASE\n! ----------------------------------------------------------------------\n         IF ( (ICE == 1) .or. (ICE == -1) ) THEN\n            DF1 = 2.2\n!\n! kmh 09/03/2006\n! kmh 03/25/2008  change SNCOVR threshold to 0.97\n!\n! only apply (small) DF1 conductivity for permanent land ice\n            IF ( (ICE == -1) ) THEN\n               IF (  SNCOVR .GT. 0.97 ) THEN\n                  DF1 = SNCOND\n               ENDIF\n            ENDIF\n!\n         ELSE\n! ----------------------------------------------------------------------\n! NEXT CALCULATE THE SUBSURFACE HEAT FLUX, WHICH FIRST REQUIRES\n! CALCULATION OF THE THERMAL DIFFUSIVITY.  TREATMENT OF THE\n! LATTER FOLLOWS THAT ON PAGES 148-149 FROM \"HEAT TRANSFER IN\n! COLD CLIMATES\", BY V. J. LUNARDINI (PUBLISHED IN 1981\n! BY VAN NOSTRAND REINHOLD CO.) I.E. TREATMENT OF TWO CONTIGUOUS\n! \"PLANE PARALLEL\" MEDIUMS (NAMELY HERE THE FIRST SOIL LAYER\n! AND THE SNOWPACK LAYER, IF ANY). THIS DIFFUSIVITY TREATMENT\n! BEHAVES WELL FOR BOTH ZERO AND NONZERO SNOWPACK, INCLUDING THE\n! LIMIT OF VERY THIN SNOWPACK.  THIS TREATMENT ALSO ELIMINATES\n! THE NEED TO IMPOSE AN ARBITRARY UPPER BOUND ON SUBSURFACE\n! HEAT FLUX WHEN THE SNOWPACK BECOMES EXTREMELY THIN.\n! ----------------------------------------------------------------------\n! FIRST CALCULATE THERMAL DIFFUSIVITY OF TOP SOIL LAYER, USING\n! BOTH THE FROZEN AND LIQUID SOIL MOISTURE, FOLLOWING THE\n! SOIL THERMAL DIFFUSIVITY FUNCTION OF PETERS-LIDARD ET AL.\n! (1998,JAS, VOL 55, 1209-1224), WHICH REQUIRES THE SPECIFYING\n! THE QUARTZ CONTENT OF THE GIVEN SOIL CLASS (SEE ROUTINE REDPRM)\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! NEXT ADD SUBSURFACE HEAT FLUX REDUCTION EFFECT FROM THE\n! OVERLYING GREEN CANOPY, ADAPTED FROM SECTION 2.1.2 OF\n! PETERS-LIDARD ET AL. (1997, JGR, VOL 102(D4))\n! ----------------------------------------------------------------------\n            CALL TDFCND (DF1,SMC (1),QUARTZ,SMCMAX,SH2O (1))\n\n!urban\n            IF ( VEGTYP == ISURBAN ) DF1=3.24\n\n            DF1 = DF1 * EXP (SBETA * SHDFAC)\n!\n! kmh 09/03/2006\n! kmh 03/25/2008  change SNCOVR threshold to 0.97\n!\n            IF (  SNCOVR .GT. 0.97 ) THEN\n               DF1 = SNCOND\n            ENDIF\n!\n! ----------------------------------------------------------------------\n! FINALLY \"PLANE PARALLEL\" SNOWPACK EFFECT FOLLOWING\n! V.J. LINARDINI REFERENCE CITED ABOVE. NOTE THAT DTOT IS\n! COMBINED DEPTH OF SNOWDEPTH AND THICKNESS OF FIRST SOIL LAYER\n! ----------------------------------------------------------------------\n         END IF\n\n         DSOIL = - (0.5 * ZSOIL (1))\n         IF (SNEQV == 0.) THEN\n            SSOIL = DF1 * (T1- STC (1) ) / DSOIL\n         ELSE\n            DTOT = SNOWH + DSOIL\n            FRCSNO = SNOWH / DTOT\n\n! 1. HARMONIC MEAN (SERIES FLOW)\n!        DF1 = (SNCOND*DF1)/(FRCSOI*SNCOND+FRCSNO*DF1)\n            FRCSOI = DSOIL / DTOT\n! 2. ARITHMETIC MEAN (PARALLEL FLOW)\n!        DF1 = FRCSNO*SNCOND + FRCSOI*DF1\n            DF1H = (SNCOND * DF1)/ (FRCSOI * SNCOND+ FRCSNO * DF1)\n\n! 3. GEOMETRIC MEAN (INTERMEDIATE BETWEEN HARMONIC AND ARITHMETIC MEAN)\n!        DF1 = (SNCOND**FRCSNO)*(DF1**FRCSOI)\n! weigh DF by snow fraction\n!        DF1 = DF1H*SNCOVR + DF1A*(1.0-SNCOVR)\n!        DF1 = DF1H*SNCOVR + DF1*(1.0-SNCOVR)\n            DF1A = FRCSNO * SNCOND+ FRCSOI * DF1\n\n! ----------------------------------------------------------------------\n! CALCULATE SUBSURFACE HEAT FLUX, SSOIL, FROM FINAL THERMAL DIFFUSIVITY\n! OF SURFACE MEDIUMS, DF1 ABOVE, AND SKIN TEMPERATURE AND TOP\n! MID-LAYER SOIL TEMPERATURE\n! ----------------------------------------------------------------------\n            DF1 = DF1A * SNCOVR + DF1* (1.0- SNCOVR)\n            IF ( ICE /= 0 ) then\n               !  kmh  12/15/2005  correct for too deep snow layer\n               !  kmh  09/03/2006  adjust DTOT\n               IF ( DTOT .GT. 2.*DSOIL ) then\n                  DTOT = 2.*DSOIL\n               ENDIF\n            ENDIF\n            SSOIL = DF1 * (T1- STC (1) ) / DTOT\n         END IF\n! ----------------------------------------------------------------------\n! DETERMINE SURFACE ROUGHNESS OVER SNOWPACK USING SNOW CONDITION FROM\n! THE PREVIOUS TIMESTEP.\n! ----------------------------------------------------------------------\n         IF (SNCOVR  > 0. ) THEN\n            CALL SNOWZ0 (SNCOVR,Z0,Z0BRD,SNOWH)\n         ELSE\n            Z0=Z0BRD\n         END IF\n! ----------------------------------------------------------------------\n! NEXT CALL ROUTINE SFCDIF TO CALCULATE THE SFC EXCHANGE COEF (CH) FOR\n! HEAT AND MOISTURE.\n\n! NOTE !!!\n! DO NOT CALL SFCDIF UNTIL AFTER ABOVE CALL TO REDPRM, IN CASE\n! ALTERNATIVE VALUES OF ROUGHNESS LENGTH (Z0) AND ZILINTINKEVICH COEF\n! (CZIL) ARE SET THERE VIA NAMELIST I/O.\n\n! NOTE !!!\n! ROUTINE SFCDIF RETURNS A CH THAT REPRESENTS THE WIND SPD TIMES THE\n! \"ORIGINAL\" NONDIMENSIONAL \"Ch\" TYPICAL IN LITERATURE.  HENCE THE CH\n! RETURNED FROM SFCDIF HAS UNITS OF M/S.  THE IMPORTANT COMPANION\n! COEFFICIENT OF CH, CARRIED HERE AS \"RCH\", IS THE CH FROM SFCDIF TIMES\n! AIR DENSITY AND PARAMETER \"CP\".  \"RCH\" IS COMPUTED IN \"CALL PENMAN\".\n! RCH RATHER THAN CH IS THE COEFF USUALLY INVOKED LATER IN EQNS.\n\n! NOTE !!!\n! ----------------------------------------------------------------------\n! SFCDIF ALSO RETURNS THE SURFACE EXCHANGE COEFFICIENT FOR MOMENTUM, CM,\n! ALSO KNOWN AS THE SURFACE DRAGE COEFFICIENT. Needed as a state variable\n! for iterative/implicit solution of CH in SFCDIF\n! ----------------------------------------------------------------------\n!        IF(.NOT.LCH) THEN\n!          T1V = T1 * (1.0+ 0.61 * Q2)\n!          TH2V = TH2 * (1.0+ 0.61 * Q2)\n!          CALL SFCDIF_off (ZLVL,Z0,T1V,TH2V,SFCSPD,CZIL,CM,CH)\n!        ENDIF\n\n! ----------------------------------------------------------------------\n! CALL PENMAN SUBROUTINE TO CALCULATE POTENTIAL EVAPORATION (ETP), AND\n! OTHER PARTIAL PRODUCTS AND SUMS SAVE IN COMMON/RITE FOR LATER\n! CALCULATIONS.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! CALCULATE TOTAL DOWNWARD RADIATION (SOLAR PLUS LONGWAVE) NEEDED IN\n! PENMAN EP SUBROUTINE THAT FOLLOWS\n! ----------------------------------------------------------------------\n!         FDOWN = SOLDN * (1.0- ALBEDO) + LWDN\n         FDOWN =  SOLNET + LWDN\n! ----------------------------------------------------------------------\n! CALC VIRTUAL TEMPS AND VIRTUAL POTENTIAL TEMPS NEEDED BY SUBROUTINES\n! PENMAN.\n         T2V = SFCTMP * (1.0+ 0.61 * Q2 )\n\n         iout=0\n         if(iout.eq.1) then\n         print*,'before penman'\n         print*,' SFCTMP',SFCTMP,'SFCPRS',SFCPRS,'CH',CH,'T2V',T2V,      &\n       'TH2',TH2,'PRCP',PRCP,'FDOWN',FDOWN,'T24',T24,'SSOIL',SSOIL,      &\n        'Q2',Q2,'Q2SAT',Q2SAT,'ETP',ETP,'RCH',RCH,                       &\n        'EPSCA',EPSCA,'RR',RR  ,'SNOWNG',SNOWNG,'FRZGRA',FRZGRA,           &\n        'DQSDT2',DQSDT2,'FLX2',FLX2,'SNOWH',SNOWH,'SNEQV',SNEQV,         &\n        ' DSOIL',DSOIL,' FRCSNO',FRCSNO,' SNCOVR',SNCOVR,' DTOT',DTOT,   &\n       ' ZSOIL (1)',ZSOIL(1),' DF1',DF1,'T1',T1,' STC1',STC(1),          &\n        'ALBEDO',ALBEDO,'SMC',SMC,'STC',STC,'SH2O',SH2O\n         endif\n\n         CALL PENMAN (SFCTMP,SFCPRS,CH,T2V,TH2,PRCP,FDOWN,T24,SSOIL,     &\n                       Q2,Q2SAT,ETP,RCH,EPSCA,RR,SNOWNG,FRZGRA,          &\n!\n! kmh 01/09/2007 add T1,ICE,SNCOVR to call\n!\n                         DQSDT2,FLX2,EMISSI,SNEQV,T1,ICE,SNCOVR)\n!\n! ----------------------------------------------------------------------\n! CALL CANRES TO CALCULATE THE CANOPY RESISTANCE AND CONVERT IT INTO PC\n! IF NONZERO GREENNESS FRACTION\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n!  FROZEN GROUND EXTENSION: TOTAL SOIL WATER \"SMC\" WAS REPLACED\n!  BY UNFROZEN SOIL WATER \"SH2O\" IN CALL TO CANRES BELOW\n! ----------------------------------------------------------------------\n         IF (SHDFAC > 0.) THEN\n            CALL CANRES (SOLDN,CH,SFCTMP,Q2,SFCPRS,SH2O,ZSOIL,NSOIL,     &\n                          SMCWLT,SMCREF,RSMIN,RC,PC,NROOT,Q2SAT,DQSDT2,  &\n                          TOPT,RSMAX,RGL,HS,XLAI,                        &\n                          RCS,RCT,RCQ,RCSOIL,EMISSI)\n         ELSE\n            RC = 0.0\n         END IF\n! ----------------------------------------------------------------------\n! NOW DECIDE MAJOR PATHWAY BRANCH TO TAKE DEPENDING ON WHETHER SNOWPACK\n! EXISTS OR NOT:\n! ----------------------------------------------------------------------\n         ESNOW = 0.0\n         IF (SNEQV  == 0.0) THEN\n            CALL NOPAC (ETP,ETA,PRCP,SMC,SMCMAX,SMCWLT,                  &\n                            SMCREF,SMCDRY,CMC,CMCMAX,NSOIL,DT,           &\n                            SHDFAC,                                      &\n                            SBETA,Q2,T1,SFCTMP,T24,TH2,FDOWN,F1,EMISSI,  &\n                            SSOIL,                                       &\n                            STC,EPSCA,BEXP,PC,RCH,RR,CFACTR,             &\n                            SH2O,SLOPE,KDT,FRZX,PSISAT,ZSOIL,            &\n                            DKSAT,DWSAT,TBOT,ZBOT,RUNOFF1,RUNOFF2,       &\n                            RUNOFF3,EDIR,EC,ET,ETT,NROOT,ICE,RTDIS,      &\n                            QUARTZ,FXEXP,CSOIL,                          &\n                            BETA,DRIP,DEW,FLX1,FLX3,VEGTYP,ISURBAN)\n            ETA_KINEMATIC = ETA\n         ELSE\n            CALL SNOPAC (ETP,ETA,PRCP,PRCPF,SNOWNG,SMC,SMCMAX,SMCWLT,    &\n                         SMCREF,SMCDRY,CMC,CMCMAX,NSOIL,DT,              &\n                         SBETA,DF1,                                      &\n                         Q2,T1,SFCTMP,T24,TH2,FDOWN,F1,SSOIL,STC,EPSCA,  &\n                         SFCPRS,BEXP,PC,RCH,RR,CFACTR,SNCOVR,SNEQV,SNDENS,&\n                         SNOWH,SH2O,SLOPE,KDT,FRZX,PSISAT,               &\n                         ZSOIL,DWSAT,DKSAT,TBOT,ZBOT,SHDFAC,RUNOFF1,     &\n                         RUNOFF2,RUNOFF3,EDIR,EC,ET,ETT,NROOT,SNOMLT,    &\n                         ICE,RTDIS,QUARTZ,FXEXP,CSOIL,                   &\n                         BETA,DRIP,DEW,FLX1,FLX2,FLX3,ESNOW,ETNS,EMISSI, &\n                         RIBB,SOLDN,                                     &\n                         ISURBAN,                                        &\n                         VEGTYP)\n            ETA_KINEMATIC =  ESNOW + ETNS\n         END IF\n\n!     Calculate effective mixing ratio at grnd level (skin)\n!\n!     Q1=Q2+ETA*CP/RCH\n     Q1=Q2+ETA_KINEMATIC*CP/RCH\n!\n! ----------------------------------------------------------------------\n! DETERMINE SENSIBLE HEAT (H) IN ENERGY UNITS (W M-2)\n! ----------------------------------------------------------------------\n         SHEAT = - (CH * CP * SFCPRS)/ (R * T2V) * ( TH2- T1 )\n\n! ----------------------------------------------------------------------\n! CONVERT EVAP TERMS FROM KINEMATIC (KG M-2 S-1) TO ENERGY UNITS (W M-2)\n! ----------------------------------------------------------------------\n      EDIR = EDIR * LVH2O\n      EC = EC * LVH2O\n      DO K=1,4\n      ET(K) = ET(K) * LVH2O\n      ENDDO\n      ETT = ETT * LVH2O\n      ESNOW = ESNOW * LSUBS\n      ETP = ETP*((1.-SNCOVR)*LVH2O + SNCOVR*LSUBS)\n      IF (ETP .GT. 0.) THEN\n         ETA = EDIR + EC + ETT + ESNOW\n      ELSE\n        ETA = ETP\n      ENDIF\n! ----------------------------------------------------------------------\n! DETERMINE BETA (RATIO OF ACTUAL TO POTENTIAL EVAP)\n! ----------------------------------------------------------------------\n      IF (ETP == 0.0) THEN\n        BETA = 0.0\n      ELSE\n        BETA = ETA/ETP\n      ENDIF\n\n! ----------------------------------------------------------------------\n! CONVERT THE SIGN OF SOIL HEAT FLUX SO THAT:\n!   SSOIL>0: WARM THE SURFACE  (NIGHT TIME)\n!   SSOIL<0: COOL THE SURFACE  (DAY TIME)\n! ----------------------------------------------------------------------\n         SSOIL = -1.0* SSOIL\n\n! ----------------------------------------------------------------------\n!  FOR THE CASE OF LAND (BUT NOT GLACIAL-ICE):\n!  CONVERT RUNOFF3 (INTERNAL LAYER RUNOFF FROM SUPERSAT) FROM M TO M S-1\n!  AND ADD TO SUBSURFACE RUNOFF/DRAINAGE/BASEFLOW.  RUNOFF2 IS ALREADY\n!  A RATE AT THIS POINT\n! ----------------------------------------------------------------------\n         IF (ICE == 0) THEN\n            RUNOFF3 = RUNOFF3/ DT\n            RUNOFF2 = RUNOFF2+ RUNOFF3\n            SOILM = -1.0* SMC (1)* ZSOIL (1)\n            DO K = 2,NSOIL\n              SOILM = SOILM + SMC (K)* (ZSOIL (K -1) - ZSOIL (K))\n            END DO\n            SOILWM = -1.0* (SMCMAX - SMCWLT)* ZSOIL (1)\n            SOILWW = -1.0* (SMC (1) - SMCWLT)* ZSOIL (1)\n!\n            DO K = 1,NSOIL\n               SMAV(K)=(SMC(K) - SMCWLT)/(SMCMAX - SMCWLT)\n            END DO\n\n            IF (NROOT >= 2) THEN\n              DO K = 2,NROOT\n               SOILWM = SOILWM + (SMCMAX - SMCWLT)* (ZSOIL (K -1) - ZSOIL (K))\n               SOILWW = SOILWW + (SMC(K) - SMCWLT)* (ZSOIL (K -1) - ZSOIL (K))\n              END DO\n            END IF\n            IF (SOILWM .LT. 1.E-6) THEN\n              SOILWM = 0.0\n              SOILW  = 0.0\n              SOILM  = 0.0\n            ELSE\n              SOILW = SOILWW / SOILWM\n            END IF\n         ELSE\n! ----------------------------------------------------------------------\n! FOR THE CASE OF SEA-ICE (ICE=1) OR GLACIAL-ICE (ICE=-1), ADD ANY\n! SNOWMELT DIRECTLY TO SURFACE RUNOFF (RUNOFF1) SINCE THERE IS NO\n! SOIL MEDIUM, AND THUS NO CALL TO SUBROUTINE SMFLX (FOR SOIL MOISTURE\n! TENDENCY).\n! ----------------------------------------------------------------------\n            RUNOFF1 = SNOMLT/DT\n           SOILWM = 0.0\n           SOILW  = 0.0\n           SOILM  = 0.0\n           DO K = 1,NSOIL\n             SMAV(K)= 1.0\n           END DO\n         END IF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SFLX\n! ----------------------------------------------------------------------\n\n      SUBROUTINE ALCALC (ALB,SNOALB,EMBRD,SHDFAC,SHDMIN,SNCOVR,TSNOW,ALBEDO,EMISSI,   &\n                         DT,SNOWNG,SNOTIME1,LVCOEF)\n\n! ----------------------------------------------------------------------\n! CALCULATE ALBEDO INCLUDING SNOW EFFECT (0 -> 1)\n!   ALB     SNOWFREE ALBEDO\n!   SNOALB  MAXIMUM (DEEP) SNOW ALBEDO\n!   SHDFAC    AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!   SHDMIN    MINIMUM AREAL FRACTIONAL COVERAGE OF GREEN VEGETATION\n!   SNCOVR  FRACTIONAL SNOW COVER\n!   ALBEDO  SURFACE ALBEDO INCLUDING SNOW EFFECT\n!   TSNOW   SNOW SURFACE TEMPERATURE (K)\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n! ----------------------------------------------------------------------\n! SNOALB IS ARGUMENT REPRESENTING MAXIMUM ALBEDO OVER DEEP SNOW,\n! AS PASSED INTO SFLX, AND ADAPTED FROM THE SATELLITE-BASED MAXIMUM\n! SNOW ALBEDO FIELDS PROVIDED BY D. ROBINSON AND G. KUKLA\n! (1985, JCAM, VOL 24, 402-411)\n! ----------------------------------------------------------------------\n      REAL, INTENT(IN)  ::  ALB, SNOALB, EMBRD, SHDFAC, SHDMIN, SNCOVR, TSNOW\n      REAL, INTENT(IN)  :: DT\n      LOGICAL, INTENT(IN) :: SNOWNG\n      REAL, INTENT(INOUT):: SNOTIME1\n      REAL, INTENT(OUT) ::  ALBEDO, EMISSI\n      REAL              :: SNOALB2\n      REAL              :: TM,SNOALB1\n      REAL, INTENT(IN)  :: LVCOEF\n      REAL, PARAMETER   :: SNACCA=0.94,SNACCB=0.58,SNTHWA=0.82,SNTHWB=0.46\n! turn of vegetation effect\n!      ALBEDO = ALB + (1.0- (SHDFAC - SHDMIN))* SNCOVR * (SNOALB - ALB)\n!      ALBEDO = (1.0-SNCOVR)*ALB + SNCOVR*SNOALB !this is equivalent to below\n      ALBEDO = ALB + SNCOVR*(SNOALB-ALB)\n      EMISSI = EMBRD + SNCOVR*(EMISSI_S - EMBRD)\n\n!     BASE FORMULATION (DICKINSON ET AL., 1986, COGLEY ET AL., 1990)\n!          IF (TSNOW.LE.263.16) THEN\n!            ALBEDO=SNOALB\n!          ELSE\n!            IF (TSNOW.LT.273.16) THEN\n!              TM=0.1*(TSNOW-263.16)\n!              SNOALB1=0.5*((0.9-0.2*(TM**3))+(0.8-0.16*(TM**3)))\n!            ELSE\n!              SNOALB1=0.67\n!             IF(SNCOVR.GT.0.95) SNOALB1= 0.6\n!             SNOALB1 = ALB + SNCOVR*(SNOALB-ALB)\n!            ENDIF\n!          ENDIF\n!            ALBEDO = ALB + SNCOVR*(SNOALB1-ALB)\n\n!     ISBA FORMULATION (VERSEGHY, 1991; BAKER ET AL., 1990)\n!          SNOALB1 = SNOALB+COEF*(0.85-SNOALB)\n!          SNOALB2=SNOALB1\n!!m          LSTSNW=LSTSNW+1\n!          SNOTIME1 = SNOTIME1 + DT\n!          IF (SNOWNG) THEN\n!             SNOALB2=SNOALB\n!!m             LSTSNW=0\n!             SNOTIME1 = 0.0\n!          ELSE\n!            IF (TSNOW.LT.273.16) THEN\n!!              SNOALB2=SNOALB-0.008*LSTSNW*DT/86400\n!!m              SNOALB2=SNOALB-0.008*SNOTIME1/86400\n!              SNOALB2=(SNOALB2-0.65)*EXP(-0.05*DT/3600)+0.65\n!!              SNOALB2=(ALBEDO-0.65)*EXP(-0.01*DT/3600)+0.65\n!            ELSE\n!              SNOALB2=(SNOALB2-0.5)*EXP(-0.0005*DT/3600)+0.5\n!!              SNOALB2=(SNOALB-0.5)*EXP(-0.24*LSTSNW*DT/86400)+0.5\n!!m              SNOALB2=(SNOALB-0.5)*EXP(-0.24*SNOTIME1/86400)+0.5\n!            ENDIF\n!          ENDIF\n!\n!!               print*,'SNOALB2',SNOALB2,'ALBEDO',ALBEDO,'DT',DT\n!          ALBEDO = ALB + SNCOVR*(SNOALB2-ALB)\n!          IF (ALBEDO .GT. SNOALB2) ALBEDO=SNOALB2\n!!m          LSTSNW1=LSTSNW\n!!          SNOTIME = SNOTIME1\n\n! formulation by Livneh\n! ----------------------------------------------------------------------\n! SNOALB IS CONSIDERED AS THE MAXIMUM SNOW ALBEDO FOR NEW SNOW, AT\n! A VALUE OF 85%. SNOW ALBEDO CURVE DEFAULTS ARE FROM BRAS P.263. SHOULD\n! NOT BE CHANGED EXCEPT FOR SERIOUS PROBLEMS WITH SNOW MELT.\n! TO IMPLEMENT ACCUMULATIN PARAMETERS, SNACCA AND SNACCB, ASSERT THAT IT\n! IS INDEED ACCUMULATION SEASON. I.E. THAT SNOW SURFACE TEMP IS BELOW\n! ZERO AND THE DATE FALLS BETWEEN OCTOBER AND FEBRUARY\n! ----------------------------------------------------------------------\n         SNOALB1 = SNOALB+LVCOEF*(0.85-SNOALB)\n         SNOALB2=SNOALB1\n! ---------------- Initial LSTSNW --------------------------------------\n          IF (SNOWNG) THEN\n             SNOTIME1 = 0.\n          ELSE\n           SNOTIME1=SNOTIME1+DT\n!               IF (TSNOW.LT.273.16) THEN\n                   SNOALB2=SNOALB1*(SNACCA**((SNOTIME1/86400.0)**SNACCB))\n!               ELSE\n!                  SNOALB2 =SNOALB1*(SNTHWA**((SNOTIME1/86400.0)**SNTHWB))\n!               ENDIF\n          ENDIF\n!\n           SNOALB2 = MAX ( SNOALB2, ALB )\n           ALBEDO = ALB + SNCOVR*(SNOALB2-ALB)\n           IF (ALBEDO .GT. SNOALB2) ALBEDO=SNOALB2\n\n!          IF (TSNOW.LT.273.16) THEN\n!            ALBEDO=SNOALB-0.008*DT/86400\n!          ELSE\n!            ALBEDO=(SNOALB-0.5)*EXP(-0.24*DT/86400)+0.5\n!          ENDIF\n\n!      IF (ALBEDO > SNOALB) ALBEDO = SNOALB\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE ALCALC\n! ----------------------------------------------------------------------\n\n      SUBROUTINE CANRES (SOLAR,CH,SFCTMP,Q2,SFCPRS,SMC,ZSOIL,NSOIL,       &\n                         SMCWLT,SMCREF,RSMIN,RC,PC,NROOT,Q2SAT,DQSDT2,    &\n                         TOPT,RSMAX,RGL,HS,XLAI,                          &\n                         RCS,RCT,RCQ,RCSOIL,EMISSI)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE CANRES\n! ----------------------------------------------------------------------\n! CALCULATE CANOPY RESISTANCE WHICH DEPENDS ON INCOMING SOLAR RADIATION,\n! AIR TEMPERATURE, ATMOSPHERIC WATER VAPOR PRESSURE DEFICIT AT THE\n! LOWEST MODEL LEVEL, AND SOIL MOISTURE (PREFERABLY UNFROZEN SOIL\n! MOISTURE RATHER THAN TOTAL)\n! ----------------------------------------------------------------------\n! SOURCE:  JARVIS (1976), NOILHAN AND PLANTON (1989, MWR), JACQUEMIN AND\n! NOILHAN (1990, BLM)\n! SEE ALSO:  CHEN ET AL (1996, JGR, VOL 101(D3), 7251-7268), EQNS 12-14\n! AND TABLE 2 OF SEC. 3.1.2\n! ----------------------------------------------------------------------\n! INPUT:\n!   SOLAR   INCOMING SOLAR RADIATION\n!   CH      SURFACE EXCHANGE COEFFICIENT FOR HEAT AND MOISTURE\n!   SFCTMP  AIR TEMPERATURE AT 1ST LEVEL ABOVE GROUND\n!   Q2      AIR HUMIDITY AT 1ST LEVEL ABOVE GROUND\n!   Q2SAT   SATURATION AIR HUMIDITY AT 1ST LEVEL ABOVE GROUND\n!   DQSDT2  SLOPE OF SATURATION HUMIDITY FUNCTION WRT TEMP\n!   SFCPRS  SURFACE PRESSURE\n!   SMC     VOLUMETRIC SOIL MOISTURE\n!   ZSOIL   SOIL DEPTH (NEGATIVE SIGN, AS IT IS BELOW GROUND)\n!   NSOIL   NO. OF SOIL LAYERS\n!   NROOT   NO. OF SOIL LAYERS IN ROOT ZONE (1.LE.NROOT.LE.NSOIL)\n!   XLAI    LEAF AREA INDEX\n!   SMCWLT  WILTING POINT\n!   SMCREF  REFERENCE SOIL MOISTURE (WHERE SOIL WATER DEFICIT STRESS\n!             SETS IN)\n! RSMIN, RSMAX, TOPT, RGL, HS ARE CANOPY STRESS PARAMETERS SET IN\n!   SURBOUTINE REDPRM\n! OUTPUT:\n!   PC  PLANT COEFFICIENT\n!   RC  CANOPY RESISTANCE\n! ----------------------------------------------------------------------\n\n      IMPLICIT NONE\n      INTEGER, INTENT(IN) :: NROOT,NSOIL\n      INTEGER  K\n      REAL,    INTENT(IN) :: CH,DQSDT2,HS,Q2,Q2SAT,RSMIN,RGL,RSMAX,        &\n                             SFCPRS,SFCTMP,SMCREF,SMCWLT, SOLAR,TOPT,XLAI, &\n                             EMISSI\n      REAL,DIMENSION(1:NSOIL), INTENT(IN) :: SMC,ZSOIL\n      REAL,    INTENT(OUT):: PC,RC,RCQ,RCS,RCSOIL,RCT\n      REAL                :: DELTA,FF,GX,P,RR\n      REAL, DIMENSION(1:NSOIL) ::  PART\n      REAL, PARAMETER     :: SLV = 2.501000E6\n\n\n! ----------------------------------------------------------------------\n! INITIALIZE CANOPY RESISTANCE MULTIPLIER TERMS.\n! ----------------------------------------------------------------------\n      RCS = 0.0\n      RCT = 0.0\n      RCQ = 0.0\n      RCSOIL = 0.0\n\n! ----------------------------------------------------------------------\n! CONTRIBUTION DUE TO INCOMING SOLAR RADIATION\n! ----------------------------------------------------------------------\n      RC = 0.0\n      FF = 0.55*2.0* SOLAR / (RGL * XLAI)\n      RCS = (FF + RSMIN / RSMAX) / (1.0+ FF)\n\n! ----------------------------------------------------------------------\n! CONTRIBUTION DUE TO AIR TEMPERATURE AT FIRST MODEL LEVEL ABOVE GROUND\n! RCT EXPRESSION FROM NOILHAN AND PLANTON (1989, MWR).\n! ----------------------------------------------------------------------\n      RCS = MAX (RCS,0.0001)\n      RCT = 1.0- 0.0016* ( (TOPT - SFCTMP)**2.0)\n\n! ----------------------------------------------------------------------\n! CONTRIBUTION DUE TO VAPOR PRESSURE DEFICIT AT FIRST MODEL LEVEL.\n! RCQ EXPRESSION FROM SSIB\n! ----------------------------------------------------------------------\n      RCT = MAX (RCT,0.0001)\n      RCQ = 1.0/ (1.0+ HS * (Q2SAT - Q2))\n\n! ----------------------------------------------------------------------\n! CONTRIBUTION DUE TO SOIL MOISTURE AVAILABILITY.\n! DETERMINE CONTRIBUTION FROM EACH SOIL LAYER, THEN ADD THEM UP.\n! ----------------------------------------------------------------------\n      RCQ = MAX (RCQ,0.01)\n      GX = (SMC (1) - SMCWLT) / (SMCREF - SMCWLT)\n      IF (GX  >  1.) GX = 1.\n      IF (GX  <  0.) GX = 0.\n\n! ----------------------------------------------------------------------\n! USE SOIL DEPTH AS WEIGHTING FACTOR\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! USE ROOT DISTRIBUTION AS WEIGHTING FACTOR\n!      PART(1) = RTDIS(1) * GX\n! ----------------------------------------------------------------------\n      PART (1) = (ZSOIL (1)/ ZSOIL (NROOT)) * GX\n      DO K = 2,NROOT\n         GX = (SMC (K) - SMCWLT) / (SMCREF - SMCWLT)\n         IF (GX >  1.) GX = 1.\n         IF (GX <  0.) GX = 0.\n! ----------------------------------------------------------------------\n! USE SOIL DEPTH AS WEIGHTING FACTOR\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! USE ROOT DISTRIBUTION AS WEIGHTING FACTOR\n!        PART(K) = RTDIS(K) * GX\n! ----------------------------------------------------------------------\n         PART (K) = ( (ZSOIL (K) - ZSOIL (K -1))/ ZSOIL (NROOT)) * GX\n      END DO\n      DO K = 1,NROOT\n         RCSOIL = RCSOIL + PART (K)\n      END DO\n\n! ----------------------------------------------------------------------\n! DETERMINE CANOPY RESISTANCE DUE TO ALL FACTORS.  CONVERT CANOPY\n! RESISTANCE (RC) TO PLANT COEFFICIENT (PC) TO BE USED WITH POTENTIAL\n! EVAP IN DETERMINING ACTUAL EVAP.  PC IS DETERMINED BY:\n!   PC * LINERIZED PENMAN POTENTIAL EVAP =\n!   PENMAN-MONTEITH ACTUAL EVAPORATION (CONTAINING RC TERM).\n! ----------------------------------------------------------------------\n      RCSOIL = MAX (RCSOIL,0.0001)\n\n      RC = RSMIN / (XLAI * RCS * RCT * RCQ * RCSOIL)\n!      RR = (4.* SIGMA * RD / CP)* (SFCTMP **4.)/ (SFCPRS * CH) + 1.0\n      RR = (4.* EMISSI *SIGMA * RD / CP)* (SFCTMP **4.)/ (SFCPRS * CH) &\n             + 1.0\n\n      DELTA = (SLV / CP)* DQSDT2\n\n      PC = (RR + DELTA)/ (RR * (1. + RC * CH) + DELTA)\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE CANRES\n! ----------------------------------------------------------------------\n\n      SUBROUTINE CSNOW (SNCOND,DSNOW)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE CSNOW\n! FUNCTION CSNOW\n! ----------------------------------------------------------------------\n! CALCULATE SNOW TERMAL CONDUCTIVITY\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN) :: DSNOW\n      REAL, INTENT(OUT):: SNCOND\n      REAL             :: C\n      REAL, PARAMETER  :: UNIT = 0.11631\n\n! ----------------------------------------------------------------------\n! SNCOND IN UNITS OF CAL/(CM*HR*C), RETURNED IN W/(M*C)\n! CSNOW IN UNITS OF CAL/(CM*HR*C), RETURNED IN W/(M*C)\n! BASIC VERSION IS DYACHKOVA EQUATION (1960), FOR RANGE 0.1-0.4\n! ----------------------------------------------------------------------\n      C = 0.328*10** (2.25* DSNOW)\n!      CSNOW=UNIT*C\n\n! ----------------------------------------------------------------------\n! DE VAUX EQUATION (1933), IN RANGE 0.1-0.6\n! ----------------------------------------------------------------------\n!      SNCOND=0.0293*(1.+100.*DSNOW**2)\n!      CSNOW=0.0293*(1.+100.*DSNOW**2)\n\n! ----------------------------------------------------------------------\n! E. ANDERSEN FROM FLERCHINGER\n! ----------------------------------------------------------------------\n!      SNCOND=0.021+2.51*DSNOW**2\n!      CSNOW=0.021+2.51*DSNOW**2\n\n!      SNCOND = UNIT * C\n! double snow thermal conductivity\n      SNCOND = 2.0 * UNIT * C\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE CSNOW\n! ----------------------------------------------------------------------\n\n      SUBROUTINE DEVAP (EDIR,ETP1,SMC,ZSOIL,SHDFAC,SMCMAX,BEXP,         &\n                        DKSAT,DWSAT,SMCDRY,SMCREF,SMCWLT,FXEXP)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE DEVAP\n! FUNCTION DEVAP\n! ----------------------------------------------------------------------\n! CALCULATE DIRECT SOIL EVAPORATION\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN) :: ETP1,SMC,BEXP,DKSAT,DWSAT,FXEXP,              &\n                          SHDFAC,SMCDRY,SMCMAX,ZSOIL,SMCREF,SMCWLT\n      REAL, INTENT(OUT):: EDIR\n      REAL             :: FX, SRATIO\n\n\n! ----------------------------------------------------------------------\n! DIRECT EVAP A FUNCTION OF RELATIVE SOIL MOISTURE AVAILABILITY, LINEAR\n! WHEN FXEXP=1.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! FX > 1 REPRESENTS DEMAND CONTROL\n! FX < 1 REPRESENTS FLUX CONTROL\n! ----------------------------------------------------------------------\n\n      SRATIO = (SMC - SMCDRY) / (SMCMAX - SMCDRY)\n      IF (SRATIO > 0.) THEN\n        FX = SRATIO**FXEXP\n        FX = MAX ( MIN ( FX, 1. ) ,0. )\n      ELSE\n        FX = 0.\n      ENDIF\n\n! ----------------------------------------------------------------------\n! ALLOW FOR THE DIRECT-EVAP-REDUCING EFFECT OF SHADE\n! ----------------------------------------------------------------------\n      EDIR = FX * ( 1.0- SHDFAC ) * ETP1\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE DEVAP\n! ----------------------------------------------------------------------\n\n      SUBROUTINE EVAPO (ETA1,SMC,NSOIL,CMC,ETP1,DT,ZSOIL,               &\n                         SH2O,                                          &\n                         SMCMAX,BEXP,PC,SMCWLT,DKSAT,DWSAT,             &\n                         SMCREF,SHDFAC,CMCMAX,                          &\n                         SMCDRY,CFACTR,                                 &\n                         EDIR,EC,ET,ETT,SFCTMP,Q2,NROOT,RTDIS,FXEXP)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE EVAPO\n! ----------------------------------------------------------------------\n! CALCULATE SOIL MOISTURE FLUX.  THE SOIL MOISTURE CONTENT (SMC - A PER\n! UNIT VOLUME MEASUREMENT) IS A DEPENDENT VARIABLE THAT IS UPDATED WITH\n! PROGNOSTIC EQNS. THE CANOPY MOISTURE CONTENT (CMC) IS ALSO UPDATED.\n! FROZEN GROUND VERSION:  NEW STATES ADDED: SH2O, AND FROZEN GROUND\n! CORRECTION FACTOR, FRZFACT AND PARAMETER SLOPE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)   :: NSOIL, NROOT\n      INTEGER               :: I,K\n      REAL,    INTENT(IN)   :: BEXP, CFACTR,CMC,CMCMAX,DKSAT,           &\n                                 DT,DWSAT,ETP1,FXEXP,PC,Q2,SFCTMP,      &\n                                 SHDFAC,SMCDRY,SMCMAX,SMCREF,SMCWLT\n      REAL,    INTENT(OUT)  :: EC,EDIR,ETA1,ETT\n      REAL                  :: CMC2MS\n      REAL,DIMENSION(1:NSOIL), INTENT(IN) :: RTDIS, SMC, SH2O, ZSOIL\n      REAL,DIMENSION(1:NSOIL), INTENT(OUT) :: ET\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE IF THE POTENTIAL EVAPOTRANSPIRATION IS\n! GREATER THAN ZERO.\n! ----------------------------------------------------------------------\n      EDIR = 0.\n      EC = 0.\n      ETT = 0.\n      DO K = 1,NSOIL\n         ET (K) = 0.\n      END DO\n\n! ----------------------------------------------------------------------\n! RETRIEVE DIRECT EVAPORATION FROM SOIL SURFACE.  CALL THIS FUNCTION\n! ONLY IF VEG COVER NOT COMPLETE.\n! FROZEN GROUND VERSION:  SH2O STATES REPLACE SMC STATES.\n! ----------------------------------------------------------------------\n      IF (ETP1 > 0.0) THEN\n         IF (SHDFAC <  1.) THEN\n             CALL DEVAP (EDIR,ETP1,SMC (1),ZSOIL (1),SHDFAC,SMCMAX,      &\n                         BEXP,DKSAT,DWSAT,SMCDRY,SMCREF,SMCWLT,FXEXP)\n         END IF\n! ----------------------------------------------------------------------\n! INITIALIZE PLANT TOTAL TRANSPIRATION, RETRIEVE PLANT TRANSPIRATION,\n! AND ACCUMULATE IT FOR ALL SOIL LAYERS.\n! ----------------------------------------------------------------------\n\n         IF (SHDFAC > 0.0) THEN\n            CALL TRANSP (ET,NSOIL,ETP1,SH2O,CMC,ZSOIL,SHDFAC,SMCWLT,     &\n                          CMCMAX,PC,CFACTR,SMCREF,SFCTMP,Q2,NROOT,RTDIS)\n            DO K = 1,NSOIL\n               ETT = ETT + ET ( K )\n            END DO\n! ----------------------------------------------------------------------\n! CALCULATE CANOPY EVAPORATION.\n! IF STATEMENTS TO AVOID TANGENT LINEAR PROBLEMS NEAR CMC=0.0.\n! ----------------------------------------------------------------------\n            IF (CMC > 0.0) THEN\n               EC = SHDFAC * ( ( CMC / CMCMAX ) ** CFACTR ) * ETP1\n            ELSE\n               EC = 0.0\n            END IF\n! ----------------------------------------------------------------------\n! EC SHOULD BE LIMITED BY THE TOTAL AMOUNT OF AVAILABLE WATER ON THE\n! CANOPY.  -F.CHEN, 18-OCT-1994\n! ----------------------------------------------------------------------\n            CMC2MS = CMC / DT\n            EC = MIN ( CMC2MS, EC )\n         END IF\n      END IF\n! ----------------------------------------------------------------------\n! TOTAL UP EVAP AND TRANSP TYPES TO OBTAIN ACTUAL EVAPOTRANSP\n! ----------------------------------------------------------------------\n      ETA1 = EDIR + ETT + EC\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE EVAPO\n! ----------------------------------------------------------------------\n\n  SUBROUTINE FAC2MIT(SMCMAX,FLIMIT)\n    IMPLICIT NONE\t\t\n    REAL, INTENT(IN)  :: SMCMAX\n    REAL, INTENT(OUT) :: FLIMIT\n\n    FLIMIT = 0.90\n\n    IF ( SMCMAX == 0.395 ) THEN\n       FLIMIT = 0.59\n    ELSE IF ( ( SMCMAX == 0.434 ) .OR. ( SMCMAX == 0.404 ) ) THEN\n       FLIMIT = 0.85\n    ELSE IF ( ( SMCMAX == 0.465 ) .OR. ( SMCMAX == 0.406 ) ) THEN\n       FLIMIT = 0.86\n    ELSE IF ( ( SMCMAX == 0.476 ) .OR. ( SMCMAX == 0.439 ) ) THEN\n       FLIMIT = 0.74\n    ELSE IF ( ( SMCMAX == 0.200 ) .OR. ( SMCMAX == 0.464 ) ) THEN\n       FLIMIT = 0.80\n    ENDIF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE FAC2MIT\n! ----------------------------------------------------------------------\n\n      SUBROUTINE FRH2O (FREE,TKELV,SMC,SH2O,SMCMAX,BEXP,PSIS)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE FRH2O\n! ----------------------------------------------------------------------\n! CALCULATE AMOUNT OF SUPERCOOLED LIQUID SOIL WATER CONTENT IF\n! TEMPERATURE IS BELOW 273.15K (T0).  REQUIRES NEWTON-TYPE ITERATION TO\n! SOLVE THE NONLINEAR IMPLICIT EQUATION GIVEN IN EQN 17 OF KOREN ET AL\n! (1999, JGR, VOL 104(D16), 19569-19585).\n! ----------------------------------------------------------------------\n! NEW VERSION (JUNE 2001): MUCH FASTER AND MORE ACCURATE NEWTON\n! ITERATION ACHIEVED BY FIRST TAKING LOG OF EQN CITED ABOVE -- LESS THAN\n! 4 (TYPICALLY 1 OR 2) ITERATIONS ACHIEVES CONVERGENCE.  ALSO, EXPLICIT\n! 1-STEP SOLUTION OPTION FOR SPECIAL CASE OF PARAMETER CK=0, WHICH\n! REDUCES THE ORIGINAL IMPLICIT EQUATION TO A SIMPLER EXPLICIT FORM,\n! KNOWN AS THE \"FLERCHINGER EQN\". IMPROVED HANDLING OF SOLUTION IN THE\n! LIMIT OF FREEZING POINT TEMPERATURE T0.\n! ----------------------------------------------------------------------\n! INPUT:\n\n!   TKELV.........TEMPERATURE (Kelvin)\n!   SMC...........TOTAL SOIL MOISTURE CONTENT (VOLUMETRIC)\n!   SH2O..........LIQUID SOIL MOISTURE CONTENT (VOLUMETRIC)\n!   SMCMAX........SATURATION SOIL MOISTURE CONTENT (FROM REDPRM)\n!   B.............SOIL TYPE \"B\" PARAMETER (FROM REDPRM)\n!   PSIS..........SATURATED SOIL MATRIC POTENTIAL (FROM REDPRM)\n\n! OUTPUT:\n!   FRH2O.........SUPERCOOLED LIQUID WATER CONTENT\n!   FREE..........SUPERCOOLED LIQUID WATER CONTENT\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN)     :: BEXP,PSIS,SH2O,SMC,SMCMAX,TKELV\n      REAL, INTENT(OUT)    :: FREE\n      REAL                 :: BX,DENOM,DF,DSWL,FK,SWL,SWLK\n      INTEGER              :: NLOG,KCOUNT\n!      PARAMETER(CK = 0.0)\n      REAL, PARAMETER      :: CK = 8.0, BLIM = 5.5, ERROR = 0.005,       &\n                              HLICE = 3.335E5, GS = 9.81,DICE = 920.0,   &\n                              DH2O = 1000.0, T0 = 273.15\n\n! ----------------------------------------------------------------------\n! LIMITS ON PARAMETER B: B < 5.5  (use parameter BLIM)\n! SIMULATIONS SHOWED IF B > 5.5 UNFROZEN WATER CONTENT IS\n! NON-REALISTICALLY HIGH AT VERY LOW TEMPERATURES.\n! ----------------------------------------------------------------------\n      BX = BEXP\n\n! ----------------------------------------------------------------------\n! INITIALIZING ITERATIONS COUNTER AND ITERATIVE SOLUTION FLAG.\n! ----------------------------------------------------------------------\n      IF (BEXP >  BLIM) BX = BLIM\n      NLOG = 0\n\n! ----------------------------------------------------------------------\n!  IF TEMPERATURE NOT SIGNIFICANTLY BELOW FREEZING (T0), SH2O = SMC\n! ----------------------------------------------------------------------\n      KCOUNT = 0\n!      FRH2O = SMC\n      IF (TKELV > (T0- 1.E-3)) THEN\n          FREE = SMC\n      ELSE\n\n! ----------------------------------------------------------------------\n! OPTION 1: ITERATED SOLUTION FOR NONZERO CK\n! IN KOREN ET AL, JGR, 1999, EQN 17\n! ----------------------------------------------------------------------\n! INITIAL GUESS FOR SWL (frozen content)\n! ----------------------------------------------------------------------\n         IF (CK /= 0.0) THEN\n            SWL = SMC - SH2O\n! ----------------------------------------------------------------------\n! KEEP WITHIN BOUNDS.\n! ----------------------------------------------------------------------\n            IF (SWL > (SMC -0.02)) SWL = SMC -0.02\n\n! ----------------------------------------------------------------------\n!  START OF ITERATIONS\n! ----------------------------------------------------------------------\n            IF (SWL < 0.) SWL = 0.\n 1001       Continue\n              IF (.NOT.( (NLOG < 10) .AND. (KCOUNT == 0)))   goto 1002\n              NLOG = NLOG +1\n              DF = ALOG ( ( PSIS * GS / HLICE ) * ( ( 1. + CK * SWL )**2.) * &\n                   ( SMCMAX / (SMC - SWL) )** BX) - ALOG ( - (               &\n                   TKELV - T0)/ TKELV)\n              DENOM = 2. * CK / ( 1. + CK * SWL ) + BX / ( SMC - SWL )\n              SWLK = SWL - DF / DENOM\n! ----------------------------------------------------------------------\n! BOUNDS USEFUL FOR MATHEMATICAL SOLUTION.\n! ----------------------------------------------------------------------\n              IF (SWLK > (SMC -0.02)) SWLK = SMC - 0.02\n              IF (SWLK < 0.) SWLK = 0.\n\n! ----------------------------------------------------------------------\n! MATHEMATICAL SOLUTION BOUNDS APPLIED.\n! ----------------------------------------------------------------------\n              DSWL = ABS (SWLK - SWL)\n\n! ----------------------------------------------------------------------\n! IF MORE THAN 10 ITERATIONS, USE EXPLICIT METHOD (CK=0 APPROX.)\n! WHEN DSWL LESS OR EQ. ERROR, NO MORE ITERATIONS REQUIRED.\n! ----------------------------------------------------------------------\n              SWL = SWLK\n              IF ( DSWL <= ERROR ) THEN\n                    KCOUNT = KCOUNT +1\n              END IF\n! ----------------------------------------------------------------------\n!  END OF ITERATIONS\n! ----------------------------------------------------------------------\n! BOUNDS APPLIED WITHIN DO-BLOCK ARE VALID FOR PHYSICAL SOLUTION.\n! ----------------------------------------------------------------------\n!          FRH2O = SMC - SWL\n           goto 1001\n 1002   continue\n           FREE = SMC - SWL\n         END IF\n! ----------------------------------------------------------------------\n! END OPTION 1\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! OPTION 2: EXPLICIT SOLUTION FOR FLERCHINGER EQ. i.e. CK=0\n! IN KOREN ET AL., JGR, 1999, EQN 17\n! APPLY PHYSICAL BOUNDS TO FLERCHINGER SOLUTION\n! ----------------------------------------------------------------------\n         IF (KCOUNT == 0) THEN\n             PRINT *,'Flerchinger USEd in NEW version. Iterations=',NLOG\n                  FK = ( ( (HLICE / (GS * ( - PSIS)))*                    &\n                       ( (TKELV - T0)/ TKELV))** ( -1/ BX))* SMCMAX\n!            FRH2O = MIN (FK, SMC)\n             IF (FK < 0.02) FK = 0.02\n             FREE = MIN (FK, SMC)\n! ----------------------------------------------------------------------\n! END OPTION 2\n! ----------------------------------------------------------------------\n         END IF\n      END IF\n! ----------------------------------------------------------------------\n  END SUBROUTINE FRH2O\n! ----------------------------------------------------------------------\n\n      SUBROUTINE HRT (RHSTS,STC,SMC,SMCMAX,NSOIL,ZSOIL,YY,ZZ1,          &\n                       TBOT,ZBOT,PSISAT,SH2O,DT,BEXP,                   &\n                       F1,DF1,QUARTZ,CSOIL,AI,BI,CI,VEGTYP,ISURBAN)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE HRT\n! ----------------------------------------------------------------------\n! CALCULATE THE RIGHT HAND SIDE OF THE TIME TENDENCY TERM OF THE SOIL\n! THERMAL DIFFUSION EQUATION.  ALSO TO COMPUTE ( PREPARE ) THE MATRIX\n! COEFFICIENTS FOR THE TRI-DIAGONAL MATRIX OF THE IMPLICIT TIME SCHEME.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      LOGICAL              :: ITAVG\n      INTEGER, INTENT(IN)  :: NSOIL, VEGTYP\n      INTEGER, INTENT(IN)  :: ISURBAN\n      INTEGER              :: I, K\n\n      REAL, INTENT(IN)     :: BEXP, CSOIL, DF1, DT,F1,PSISAT,QUARTZ,     &\n                              SMCMAX ,TBOT,YY,ZZ1, ZBOT\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: SMC,STC,ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT):: SH2O\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)  :: RHSTS\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)  :: AI, BI,CI\n      REAL                 :: DDZ, DDZ2, DENOM, DF1N, DF1K, DTSDZ,       &\n                              DTSDZ2,HCPCT,QTOT,SSOIL,SICE,TAVG,TBK,     &\n                              TBK1,TSNSR,TSURF,CSOIL_LOC\n      REAL, PARAMETER      :: T0 = 273.15, CAIR = 1004.0, CICE = 2.106E6,&\n                              CH2O = 4.2E6\n\n\n!urban\n        IF( VEGTYP == ISURBAN ) then\n            CSOIL_LOC=3.0E6\n        ELSE\n            CSOIL_LOC=CSOIL\n        ENDIF\n\n! ----------------------------------------------------------------------\n! INITIALIZE LOGICAL FOR SOIL LAYER TEMPERATURE AVERAGING.\n! ----------------------------------------------------------------------\n       ITAVG = .TRUE.\n! ----------------------------------------------------------------------\n! BEGIN SECTION FOR TOP SOIL LAYER\n! ----------------------------------------------------------------------\n! CALC THE HEAT CAPACITY OF THE TOP SOIL LAYER\n! ----------------------------------------------------------------------\n      HCPCT = SH2O (1)* CH2O + (1.0- SMCMAX)* CSOIL_LOC + (SMCMAX - SMC (1))&\n       * CAIR                                                           &\n              + ( SMC (1) - SH2O (1) )* CICE\n\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEFFICIENTS AI, BI, AND CI FOR THE TOP LAYER\n! ----------------------------------------------------------------------\n      DDZ = 1.0 / ( -0.5 * ZSOIL (2) )\n      AI (1) = 0.0\n      CI (1) = (DF1 * DDZ) / (ZSOIL (1) * HCPCT)\n\n! ----------------------------------------------------------------------\n! CALCULATE THE VERTICAL SOIL TEMP GRADIENT BTWN THE 1ST AND 2ND SOIL\n! LAYERS.  THEN CALCULATE THE SUBSURFACE HEAT FLUX. USE THE TEMP\n! GRADIENT AND SUBSFC HEAT FLUX TO CALC \"RIGHT-HAND SIDE TENDENCY\n! TERMS\", OR \"RHSTS\", FOR TOP SOIL LAYER.\n! ----------------------------------------------------------------------\n      BI (1) = - CI (1) + DF1 / (0.5 * ZSOIL (1) * ZSOIL (1)* HCPCT *    &\n       ZZ1)\n      DTSDZ = (STC (1) - STC (2)) / ( -0.5 * ZSOIL (2))\n      SSOIL = DF1 * (STC (1) - YY) / (0.5 * ZSOIL (1) * ZZ1)\n!      RHSTS(1) = (DF1 * DTSDZ - SSOIL) / (ZSOIL(1) * HCPCT)\n      DENOM = (ZSOIL (1) * HCPCT)\n\n! ----------------------------------------------------------------------\n! NEXT CAPTURE THE VERTICAL DIFFERENCE OF THE HEAT FLUX AT TOP AND\n! BOTTOM OF FIRST SOIL LAYER FOR USE IN HEAT FLUX CONSTRAINT APPLIED TO\n! POTENTIAL SOIL FREEZING/THAWING IN ROUTINE SNKSRC.\n! ----------------------------------------------------------------------\n!      QTOT = SSOIL - DF1*DTSDZ\n      RHSTS (1) = (DF1 * DTSDZ - SSOIL) / DENOM\n\n! ----------------------------------------------------------------------\n! CALCULATE FROZEN WATER CONTENT IN 1ST SOIL LAYER.\n! ----------------------------------------------------------------------\n      QTOT = -1.0* RHSTS (1)* DENOM\n\n! ----------------------------------------------------------------------\n! IF TEMPERATURE AVERAGING INVOKED (ITAVG=TRUE; ELSE SKIP):\n! SET TEMP \"TSURF\" AT TOP OF SOIL COLUMN (FOR USE IN FREEZING SOIL\n! PHYSICS LATER IN FUNCTION SUBROUTINE SNKSRC).  IF SNOWPACK CONTENT IS\n! ZERO, THEN TSURF EXPRESSION BELOW GIVES TSURF = SKIN TEMP.  IF\n! SNOWPACK IS NONZERO (HENCE ARGUMENT ZZ1=1), THEN TSURF EXPRESSION\n! BELOW YIELDS SOIL COLUMN TOP TEMPERATURE UNDER SNOWPACK.  THEN\n! CALCULATE TEMPERATURE AT BOTTOM INTERFACE OF 1ST SOIL LAYER FOR USE\n! LATER IN FUNCTION SUBROUTINE SNKSRC\n! ----------------------------------------------------------------------\n      SICE = SMC (1) - SH2O (1)\n      IF (ITAVG) THEN\n         TSURF = (YY + (ZZ1-1) * STC (1)) / ZZ1\n! ----------------------------------------------------------------------\n! IF FROZEN WATER PRESENT OR ANY OF LAYER-1 MID-POINT OR BOUNDING\n! INTERFACE TEMPERATURES BELOW FREEZING, THEN CALL SNKSRC TO\n! COMPUTE HEAT SOURCE/SINK (AND CHANGE IN FROZEN WATER CONTENT)\n! DUE TO POSSIBLE SOIL WATER PHASE CHANGE\n! ----------------------------------------------------------------------\n         CALL TBND (STC (1),STC (2),ZSOIL,ZBOT,1,NSOIL,TBK)\n         IF ( (SICE > 0.) .OR. (STC (1) < T0) .OR.                         &\n            (TSURF < T0) .OR. (TBK < T0) ) THEN\n!          TSNSR = SNKSRC (TAVG,SMC(1),SH2O(1),\n            CALL TMPAVG (TAVG,TSURF,STC (1),TBK,ZSOIL,NSOIL,1)\n            CALL SNKSRC (TSNSR,TAVG,SMC (1),SH2O (1),                      &\n                          ZSOIL,NSOIL,SMCMAX,PSISAT,BEXP,DT,1,QTOT)\n!          RHSTS(1) = RHSTS(1) - TSNSR / ( ZSOIL(1) * HCPCT )\n            RHSTS (1) = RHSTS (1) - TSNSR / DENOM\n         END IF\n      ELSE\n!          TSNSR = SNKSRC (STC(1),SMC(1),SH2O(1),\n         IF ( (SICE > 0.) .OR. (STC (1) < T0) ) THEN\n            CALL SNKSRC (TSNSR,STC (1),SMC (1),SH2O (1),                   &\n                          ZSOIL,NSOIL,SMCMAX,PSISAT,BEXP,DT,1,QTOT)\n!          RHSTS(1) = RHSTS(1) - TSNSR / ( ZSOIL(1) * HCPCT )\n            RHSTS (1) = RHSTS (1) - TSNSR / DENOM\n         END IF\n! ----------------------------------------------------------------------\n! THIS ENDS SECTION FOR TOP SOIL LAYER.\n! ----------------------------------------------------------------------\n      END IF\n\n! INITIALIZE DDZ2\n! ----------------------------------------------------------------------\n\n      DDZ2 = 0.0\n      DF1K = DF1\n\n! ----------------------------------------------------------------------\n! LOOP THRU THE REMAINING SOIL LAYERS, REPEATING THE ABOVE PROCESS\n! (EXCEPT SUBSFC OR \"GROUND\" HEAT FLUX NOT REPEATED IN LOWER LAYERS)\n! ----------------------------------------------------------------------\n! CALCULATE HEAT CAPACITY FOR THIS SOIL LAYER.\n! ----------------------------------------------------------------------\n      DO K = 2,NSOIL\n         HCPCT = SH2O (K)* CH2O + (1.0- SMCMAX)* CSOIL_LOC + (SMCMAX - SMC (  &\n                K))* CAIR + ( SMC (K) - SH2O (K) )* CICE\n! ----------------------------------------------------------------------\n! THIS SECTION FOR LAYER 2 OR GREATER, BUT NOT LAST LAYER.\n! ----------------------------------------------------------------------\n! CALCULATE THERMAL DIFFUSIVITY FOR THIS LAYER.\n! ----------------------------------------------------------------------\n         IF (K /= NSOIL) THEN\n\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT THRU THIS LAYER\n! ----------------------------------------------------------------------\n            CALL TDFCND (DF1N,SMC (K),QUARTZ,SMCMAX,SH2O (K))\n\n!urban\n       IF ( VEGTYP == ISURBAN ) DF1N = 3.24\n\n            DENOM = 0.5 * ( ZSOIL (K -1) - ZSOIL (K +1) )\n\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEF, CI, AFTER CALC'NG ITS PARTIAL PRODUCT\n! ----------------------------------------------------------------------\n            DTSDZ2 = ( STC (K) - STC (K +1) ) / DENOM\n            DDZ2 = 2. / (ZSOIL (K -1) - ZSOIL (K +1))\n\n! ----------------------------------------------------------------------\n! IF TEMPERATURE AVERAGING INVOKED (ITAVG=TRUE; ELSE SKIP):  CALCULATE\n! TEMP AT BOTTOM OF LAYER.\n! ----------------------------------------------------------------------\n            CI (K) = - DF1N * DDZ2 / ( (ZSOIL (K -1) - ZSOIL (K)) *      &\n       HCPCT)\n            IF (ITAVG) THEN\n               CALL TBND (STC (K),STC (K +1),ZSOIL,ZBOT,K,NSOIL,TBK1)\n            END IF\n\n         ELSE\n! ----------------------------------------------------------------------\n! SPECIAL CASE OF BOTTOM SOIL LAYER:  CALCULATE THERMAL DIFFUSIVITY FOR\n! BOTTOM LAYER.\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT THRU BOTTOM LAYER.\n! ----------------------------------------------------------------------\n            CALL TDFCND (DF1N,SMC (K),QUARTZ,SMCMAX,SH2O (K))\n\n\n!urban\n       IF ( VEGTYP == ISURBAN ) DF1N = 3.24\n\n            DENOM = .5 * (ZSOIL (K -1) + ZSOIL (K)) - ZBOT\n\n! ----------------------------------------------------------------------\n! SET MATRIX COEF, CI TO ZERO IF BOTTOM LAYER.\n! ----------------------------------------------------------------------\n            DTSDZ2 = (STC (K) - TBOT) / DENOM\n\n! ----------------------------------------------------------------------\n! IF TEMPERATURE AVERAGING INVOKED (ITAVG=TRUE; ELSE SKIP):  CALCULATE\n! TEMP AT BOTTOM OF LAST LAYER.\n! ----------------------------------------------------------------------\n            CI (K) = 0.\n            IF (ITAVG) THEN\n               CALL TBND (STC (K),TBOT,ZSOIL,ZBOT,K,NSOIL,TBK1)\n            END IF\n! ----------------------------------------------------------------------\n! THIS ENDS SPECIAL LOOP FOR BOTTOM LAYER.\n         END IF\n! ----------------------------------------------------------------------\n! CALCULATE RHSTS FOR THIS LAYER AFTER CALC'NG A PARTIAL PRODUCT.\n! ----------------------------------------------------------------------\n         DENOM = ( ZSOIL (K) - ZSOIL (K -1) ) * HCPCT\n         RHSTS (K) = ( DF1N * DTSDZ2- DF1K * DTSDZ ) / DENOM\n         QTOT = -1.0* DENOM * RHSTS (K)\n\n         SICE = SMC (K) - SH2O (K)\n         IF (ITAVG) THEN\n            CALL TMPAVG (TAVG,TBK,STC (K),TBK1,ZSOIL,NSOIL,K)\n!            TSNSR = SNKSRC(TAVG,SMC(K),SH2O(K),ZSOIL,NSOIL,\n            IF ( (SICE > 0.) .OR. (STC (K) < T0) .OR.                   &\n               (TBK .lt. T0) .OR. (TBK1 .lt. T0) ) THEN\n               CALL SNKSRC (TSNSR,TAVG,SMC (K),SH2O (K),ZSOIL,NSOIL,    &\n                             SMCMAX,PSISAT,BEXP,DT,K,QTOT)\n               RHSTS (K) = RHSTS (K) - TSNSR / DENOM\n            END IF\n         ELSE\n!            TSNSR = SNKSRC(STC(K),SMC(K),SH2O(K),ZSOIL,NSOIL,\n            IF ( (SICE > 0.) .OR. (STC (K) < T0) ) THEN\n               CALL SNKSRC (TSNSR,STC (K),SMC (K),SH2O (K),ZSOIL,NSOIL, &\n                             SMCMAX,PSISAT,BEXP,DT,K,QTOT)\n               RHSTS (K) = RHSTS (K) - TSNSR / DENOM\n            END IF\n         END IF\n\n! ----------------------------------------------------------------------\n! CALC MATRIX COEFS, AI, AND BI FOR THIS LAYER.\n! ----------------------------------------------------------------------\n         AI (K) = - DF1K * DDZ / ( (ZSOIL (K -1) - ZSOIL (K)) * HCPCT)\n\n! ----------------------------------------------------------------------\n! RESET VALUES OF DF1, DTSDZ, DDZ, AND TBK FOR LOOP TO NEXT SOIL LAYER.\n! ----------------------------------------------------------------------\n         BI (K) = - (AI (K) + CI (K))\n         TBK = TBK1\n         DF1K = DF1N\n         DTSDZ = DTSDZ2\n         DDZ = DDZ2\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE HRT\n! ----------------------------------------------------------------------\n\n      SUBROUTINE HRTICE (RHSTS,STC,TBOT,ICE,NSOIL,ZSOIL,YY,ZZ1,DF1,AI,BI,CI)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE HRTICE\n! ----------------------------------------------------------------------\n! CALCULATE THE RIGHT HAND SIDE OF THE TIME TENDENCY TERM OF THE SOIL\n! THERMAL DIFFUSION EQUATION IN THE CASE OF SEA-ICE (ICE=1) OR GLACIAL\n! ICE (ICE=-1). COMPUTE (PREPARE) THE MATRIX COEFFICIENTS FOR THE\n! TRI-DIAGONAL MATRIX OF THE IMPLICIT TIME SCHEME.\n!\n! (NOTE:  THIS SUBROUTINE ONLY CALLED FOR SEA-ICE OR GLACIAL ICE, BUT\n! NOT FOR NON-GLACIAL LAND (ICE = 0).\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n\n      INTEGER, INTENT(IN)    :: NSOIL\n      INTEGER                :: K\n\n      REAL,    INTENT(IN)    :: DF1,YY,ZZ1\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: AI, BI,CI\n      REAL, DIMENSION(1:NSOIL), INTENT(IN) :: STC, ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: RHSTS\n      REAL,                     INTENT(IN) :: TBOT\n      INTEGER,                  INTENT(IN) :: ICE\n      REAL                   :: DDZ,DDZ2,DENOM,DTSDZ,DTSDZ2,SSOIL,       &\n                                ZBOT\n      REAL                   :: HCPCT\n      REAL :: DF1K\n      REAL :: DF1N\n      REAL :: ZMD\n\n! ----------------------------------------------------------------------\n! SET A NOMINAL UNIVERSAL VALUE OF THE SEA-ICE SPECIFIC HEAT CAPACITY,\n! HCPCT = 1880.0*917.0.\n! ----------------------------------------------------------------------\n      IF ( ICE == 1 ) THEN\n         ! Sea-ice values\n         HCPCT = 1.72396E+6\n      ELSEIF (ICE == -1) THEN\n! SET A NOMINAL UNIVERSAL VALUE OF GLACIAL-ICE SPECIFIC HEAT CAPACITY,\n!   HCPCT = 2100.0*900.0 = 1.89000E+6 (SOURCE:  BOB GRUMBINE, 2005)\n!   TBOT PASSED IN AS ARGUMENT, VALUE FROM GLOBAL DATA SET\n         !\n         ! A least-squares fit for the four points provided by\n         ! Keith Hines for the Yen (1981) values for Antarctic\n         ! snow firn.\n         !\n         HCPCT = 1.E6 * (0.8194 - 0.1309*0.5*ZSOIL(1))\n         DF1K = DF1\n      ENDIF\n\n! ----------------------------------------------------------------------\n! THE INPUT ARGUMENT DF1 IS A UNIVERSALLY CONSTANT VALUE OF SEA-ICE\n! THERMAL DIFFUSIVITY, SET IN ROUTINE SNOPAC AS DF1 = 2.2.\n! ----------------------------------------------------------------------\n! SET ICE PACK DEPTH.  USE TBOT AS ICE PACK LOWER BOUNDARY TEMPERATURE\n! (THAT OF UNFROZEN SEA WATER AT BOTTOM OF SEA ICE PACK).  ASSUME ICE\n! PACK IS OF N=NSOIL LAYERS SPANNING A UNIFORM CONSTANT ICE PACK\n! THICKNESS AS DEFINED BY ZSOIL(NSOIL) IN ROUTINE SFLX.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEFFICIENTS AI, BI, AND CI FOR THE TOP LAYER\n! ----------------------------------------------------------------------\n      IF (ICE == 1) THEN\n         ZBOT = ZSOIL (NSOIL)\n      ELSE IF (ICE == -1) THEN\n         ZBOT = -25.0\n      ENDIF\n      DDZ = 1.0 / ( -0.5 * ZSOIL (2) )\n      AI (1) = 0.0\n      CI (1) = (DF1 * DDZ) / (ZSOIL (1) * HCPCT)\n\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT BTWN THE TOP AND 2ND SOIL LAYERS.\n! RECALC/ADJUST THE SOIL HEAT FLUX.  USE THE GRADIENT AND FLUX TO CALC\n! RHSTS FOR THE TOP SOIL LAYER.\n! ----------------------------------------------------------------------\n      BI (1) = - CI (1) + DF1/ (0.5 * ZSOIL (1) * ZSOIL (1) * HCPCT *    &\n       ZZ1)\n      DTSDZ = ( STC (1) - STC (2) ) / ( -0.5 * ZSOIL (2) )\n      SSOIL = DF1 * ( STC (1) - YY ) / ( 0.5 * ZSOIL (1) * ZZ1 )\n\n! ----------------------------------------------------------------------\n! INITIALIZE DDZ2\n! ----------------------------------------------------------------------\n      RHSTS (1) = ( DF1 * DTSDZ - SSOIL ) / ( ZSOIL (1) * HCPCT )\n\n! ----------------------------------------------------------------------\n! LOOP THRU THE REMAINING SOIL LAYERS, REPEATING THE ABOVE PROCESS\n! ----------------------------------------------------------------------\n      DDZ2 = 0.0\n      DF1K = DF1\n      DF1N = DF1\n      DO K = 2,NSOIL\n\n       IF ( ICE == -1 ) THEN\n          ZMD = 0.5 * (ZSOIL(K)+ZSOIL(K-1))\n          ! For the land-ice case\n! kmh 09/03/2006 use Yen (1981)'s values for Antarctic snow firn\n!         IF ( K .eq. 2 ) HCPCT = 0.855108E6\n!         IF ( K .eq. 3 ) HCPCT = 0.922906E6\n!         IF ( K .eq. 4 ) HCPCT = 1.009986E6\n\n          ! Least squares fit to the four points supplied by Keith Hines\n          ! from Yen (1981) for Antarctic snow firn.  Not optimal, but\n          ! probably better than just a constant.\n          HCPCT = 1.E6 * ( 0.8194 - 0.1309*ZMD )\n\n!         IF ( K .eq. 2 ) DF1N = 0.345356\n!         IF ( K .eq. 3 ) DF1N = 0.398777\n!         IF ( K .eq. 4 ) DF1N = 0.472653\n\n          ! Least squares fit to the three points supplied by Keith Hines\n          ! from Yen (1981) for Antarctic snow firn.  Not optimal, but\n          ! probably better than just a constant.\n          DF1N = 0.32333 - ( 0.10073 * ZMD )\n       ENDIF\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT THRU THIS LAYER.\n! ----------------------------------------------------------------------\n         IF (K /= NSOIL) THEN\n            DENOM = 0.5 * ( ZSOIL (K -1) - ZSOIL (K +1) )\n\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEF, CI, AFTER CALC'NG ITS PARTIAL PRODUCT.\n! ----------------------------------------------------------------------\n            DTSDZ2 = ( STC (K) - STC (K +1) ) / DENOM\n            DDZ2 = 2. / (ZSOIL (K -1) - ZSOIL (K +1))\n            CI (K) = - DF1N * DDZ2 / ( (ZSOIL (K -1) - ZSOIL (K))*HCPCT)\n\n! ----------------------------------------------------------------------\n! CALC THE VERTICAL SOIL TEMP GRADIENT THRU THE LOWEST LAYER.\n! ----------------------------------------------------------------------\n         ELSE\n\n! ----------------------------------------------------------------------\n! SET MATRIX COEF, CI TO ZERO.\n! ----------------------------------------------------------------------\n            DTSDZ2 = (STC (K) - TBOT)/ (.5 * (ZSOIL (K -1) + ZSOIL (K)) &\n                     - ZBOT)\n            CI (K) = 0.\n! ----------------------------------------------------------------------\n! CALC RHSTS FOR THIS LAYER AFTER CALC'NG A PARTIAL PRODUCT.\n! ----------------------------------------------------------------------\n         END IF\n         DENOM = ( ZSOIL (K) - ZSOIL (K -1) ) * HCPCT\n\n! ----------------------------------------------------------------------\n! CALC MATRIX COEFS, AI, AND BI FOR THIS LAYER.\n! ----------------------------------------------------------------------\n         RHSTS (K) = ( DF1N * DTSDZ2- DF1K * DTSDZ ) / DENOM\n         AI (K) = - DF1K * DDZ / ( (ZSOIL (K -1) - ZSOIL (K)) * HCPCT)\n\n! ----------------------------------------------------------------------\n! RESET VALUES OF DTSDZ AND DDZ FOR LOOP TO NEXT SOIL LYR.\n! ----------------------------------------------------------------------\n         BI (K) = - (AI (K) + CI (K))\n         DF1K = DF1N\n         DTSDZ = DTSDZ2\n         DDZ = DDZ2\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE HRTICE\n! ----------------------------------------------------------------------\n\n      SUBROUTINE HSTEP (STCOUT,STCIN,RHSTS,DT,NSOIL,AI,BI,CI)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE HSTEP\n! ----------------------------------------------------------------------\n! CALCULATE/UPDATE THE SOIL TEMPERATURE FIELD.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)  :: NSOIL\n      INTEGER              :: K\n\n      REAL, DIMENSION(1:NSOIL), INTENT(IN):: STCIN\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT):: STCOUT\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT):: RHSTS\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT):: AI,BI,CI\n      REAL, DIMENSION(1:NSOIL) :: RHSTSin\n      REAL, DIMENSION(1:NSOIL) :: CIin\n      REAL                 :: DT\n\n! ----------------------------------------------------------------------\n! CREATE FINITE DIFFERENCE VALUES FOR USE IN ROSR12 ROUTINE\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         RHSTS (K) = RHSTS (K) * DT\n         AI (K) = AI (K) * DT\n         BI (K) = 1. + BI (K) * DT\n         CI (K) = CI (K) * DT\n      END DO\n! ----------------------------------------------------------------------\n! COPY VALUES FOR INPUT VARIABLES BEFORE CALL TO ROSR12\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         RHSTSin (K) = RHSTS (K)\n      END DO\n      DO K = 1,NSOIL\n         CIin (K) = CI (K)\n      END DO\n! ----------------------------------------------------------------------\n! SOLVE THE TRI-DIAGONAL MATRIX EQUATION\n! ----------------------------------------------------------------------\n      CALL ROSR12 (CI,AI,BI,CIin,RHSTSin,RHSTS,NSOIL)\n! ----------------------------------------------------------------------\n! CALC/UPDATE THE SOIL TEMPS USING MATRIX SOLUTION\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         STCOUT (K) = STCIN (K) + CI (K)\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE HSTEP\n! ----------------------------------------------------------------------\n\n      SUBROUTINE NOPAC (ETP,ETA,PRCP,SMC,SMCMAX,SMCWLT,                 &\n                         SMCREF,SMCDRY,CMC,CMCMAX,NSOIL,DT,SHDFAC,      &\n                         SBETA,Q2,T1,SFCTMP,T24,TH2,FDOWN,F1,EMISSI,    &\n                         SSOIL,                                         &\n                         STC,EPSCA,BEXP,PC,RCH,RR,CFACTR,               &\n                         SH2O,SLOPE,KDT,FRZFACT,PSISAT,ZSOIL,           &\n                         DKSAT,DWSAT,TBOT,ZBOT,RUNOFF1,RUNOFF2,         &\n                         RUNOFF3,EDIR,EC,ET,ETT,NROOT,ICE,RTDIS,        &\n                         QUARTZ,FXEXP,CSOIL,                            &\n                         BETA,DRIP,DEW,FLX1,FLX3,VEGTYP,ISURBAN)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE NOPAC\n! ----------------------------------------------------------------------\n! CALCULATE SOIL MOISTURE AND HEAT FLUX VALUES AND UPDATE SOIL MOISTURE\n! CONTENT AND SOIL HEAT CONTENT VALUES FOR THE CASE WHEN NO SNOW PACK IS\n! PRESENT.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)  :: ICE, NROOT,NSOIL,VEGTYP\n      INTEGER, INTENT(IN)  :: ISURBAN\n      INTEGER              :: K\n\n      REAL, INTENT(IN)     :: BEXP,CFACTR, CMCMAX,CSOIL,DKSAT,DT,DWSAT, &\n                              EPSCA,ETP,FDOWN,F1,FXEXP,FRZFACT,KDT,PC,  &\n                              PRCP,PSISAT,Q2,QUARTZ,RCH,RR,SBETA,SFCTMP,&\n                              SHDFAC,SLOPE,SMCDRY,SMCMAX,SMCREF,SMCWLT, &\n                              T24,TBOT,TH2,ZBOT,EMISSI\n      REAL, INTENT(INOUT)  :: CMC,BETA,T1\n      REAL, INTENT(OUT)    :: DEW,DRIP,EC,EDIR,ETA,ETT,FLX1,FLX3,       &\n                              RUNOFF1,RUNOFF2,RUNOFF3,SSOIL\n      REAL, DIMENSION(1:NSOIL),INTENT(IN)     :: RTDIS,ZSOIL\n      REAL, DIMENSION(1:NSOIL),INTENT(OUT)    :: ET\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SMC,SH2O,STC\n      REAL, DIMENSION(1:NSOIL) :: ET1\n      REAL                 :: EC1,EDIR1,ETT1,DF1,ETA1,ETP1,PRCP1,YY,    &\n                              YYNUM,ZZ1\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE:\n! CONVERT ETP Fnd PRCP FROM KG M-2 S-1 TO M S-1 AND INITIALIZE DEW.\n! ----------------------------------------------------------------------\n      PRCP1 = PRCP * 0.001\n      ETP1 = ETP * 0.001\n      DEW = 0.0\n! ----------------------------------------------------------------------\n! INITIALIZE EVAP TERMS.\n! ----------------------------------------------------------------------\n      EDIR = 0.\n      EDIR1 = 0.\n      EC1 = 0.\n      EC = 0.\n      DO K = 1,NSOIL\n        ET(K) = 0.\n        ET1(K) = 0.\n      END DO\n      ETT = 0.\n      ETT1 = 0.\n\n      IF (ETP > 0.0) THEN\n         CALL EVAPO (ETA1,SMC,NSOIL,CMC,ETP1,DT,ZSOIL,                  &\n                      SH2O,                                             &\n                      SMCMAX,BEXP,PC,SMCWLT,DKSAT,DWSAT,                &\n                      SMCREF,SHDFAC,CMCMAX,                             &\n                      SMCDRY,CFACTR,                                    &\n                       EDIR1,EC1,ET1,ETT1,SFCTMP,Q2,NROOT,RTDIS,FXEXP)\n         CALL SMFLX (SMC,NSOIL,CMC,DT,PRCP1,ZSOIL,                      &\n                      SH2O,SLOPE,KDT,FRZFACT,                           &\n                      SMCMAX,BEXP,SMCWLT,DKSAT,DWSAT,                   &\n                      SHDFAC,CMCMAX,                                    &\n                      RUNOFF1,RUNOFF2,RUNOFF3,                          &\n                      EDIR1,EC1,ET1,                                    &\n                      DRIP)\n\n! ----------------------------------------------------------------------\n! CONVERT MODELED EVAPOTRANSPIRATION FROM  M S-1  TO  KG M-2 S-1.\n! ----------------------------------------------------------------------\n\n         ETA = ETA1 * 1000.0\n\n! ----------------------------------------------------------------------\n! IF ETP < 0, ASSUME DEW FORMS (TRANSFORM ETP1 INTO DEW AND REINITIALIZE\n! ETP1 TO ZERO).\n! ----------------------------------------------------------------------\n      ELSE\n         DEW = - ETP1\n\n! ----------------------------------------------------------------------\n! CONVERT PRCP FROM 'KG M-2 S-1' TO 'M S-1' AND ADD DEW AMOUNT.\n! ----------------------------------------------------------------------\n\n         PRCP1 = PRCP1+ DEW\n         CALL SMFLX (SMC,NSOIL,CMC,DT,PRCP1,ZSOIL,                      &\n                      SH2O,SLOPE,KDT,FRZFACT,                           &\n                      SMCMAX,BEXP,SMCWLT,DKSAT,DWSAT,                   &\n                      SHDFAC,CMCMAX,                                    &\n                      RUNOFF1,RUNOFF2,RUNOFF3,                          &\n                      EDIR1,EC1,ET1,                                    &\n                      DRIP)\n\n! ----------------------------------------------------------------------\n! CONVERT MODELED EVAPOTRANSPIRATION FROM 'M S-1' TO 'KG M-2 S-1'.\n! ----------------------------------------------------------------------\n!         ETA = ETA1 * 1000.0\n      END IF\n\n! ----------------------------------------------------------------------\n! BASED ON ETP AND E VALUES, DETERMINE BETA\n! ----------------------------------------------------------------------\n\n      IF ( ETP <= 0.0 ) THEN\n         BETA = 0.0\n         ETA = ETP\n         IF ( ETP < 0.0 ) THEN\n            BETA = 1.0\n         END IF\n      ELSE\n         BETA = ETA / ETP\n      END IF\n\n! ----------------------------------------------------------------------\n! CONVERT MODELED EVAPOTRANSPIRATION COMPONENTS 'M S-1' TO 'KG M-2 S-1'.\n! ----------------------------------------------------------------------\n      EDIR = EDIR1*1000.\n      EC = EC1*1000.\n      DO K = 1,NSOIL\n        ET(K) = ET1(K)*1000.\n      END DO\n      ETT = ETT1*1000.\n\n! ----------------------------------------------------------------------\n! GET SOIL THERMAL DIFFUXIVITY/CONDUCTIVITY FOR TOP SOIL LYR,\n! CALC. ADJUSTED TOP LYR SOIL TEMP AND ADJUSTED SOIL FLUX, THEN\n! CALL SHFLX TO COMPUTE/UPDATE SOIL HEAT FLUX AND SOIL TEMPS.\n! ----------------------------------------------------------------------\n\n      CALL TDFCND (DF1,SMC (1),QUARTZ,SMCMAX,SH2O (1))\n\n!urban\n      IF ( VEGTYP == ISURBAN ) DF1=3.24\n!\n\n! ----------------------------------------------------------------------\n! VEGETATION GREENNESS FRACTION REDUCTION IN SUBSURFACE HEAT FLUX\n! VIA REDUCTION FACTOR, WHICH IS CONVENIENT TO APPLY HERE TO THERMAL\n! DIFFUSIVITY THAT IS LATER USED IN HRT TO COMPUTE SUB SFC HEAT FLUX\n! (SEE ADDITIONAL COMMENTS ON VEG EFFECT SUB-SFC HEAT FLX IN\n! ROUTINE SFLX)\n! ----------------------------------------------------------------------\n      DF1 = DF1 * EXP (SBETA * SHDFAC)\n! ----------------------------------------------------------------------\n! COMPUTE INTERMEDIATE TERMS PASSED TO ROUTINE HRT (VIA ROUTINE\n! SHFLX BELOW) FOR USE IN COMPUTING SUBSURFACE HEAT FLUX IN HRT\n! ----------------------------------------------------------------------\n      YYNUM = FDOWN - EMISSI*SIGMA * T24\n      YY = SFCTMP + (YYNUM / RCH + TH2- SFCTMP - BETA * EPSCA) / RR\n\n      ZZ1 = DF1 / ( -0.5 * ZSOIL (1) * RCH * RR ) + 1.0\n\n!urban\n      CALL SHFLX (SSOIL,STC,SMC,SMCMAX,NSOIL,T1,DT,YY,ZZ1,ZSOIL,        &\n                  TBOT,ZBOT,SMCWLT,PSISAT,SH2O,BEXP,F1,DF1,ICE,         &\n                  QUARTZ,CSOIL,VEGTYP,ISURBAN)\n\n! ----------------------------------------------------------------------\n! SET FLX1 AND FLX3 (SNOPACK PHASE CHANGE HEAT FLUXES) TO ZERO SINCE\n! THEY ARE NOT USED HERE IN SNOPAC.  FLX2 (FREEZING RAIN HEAT FLUX) WAS\n! SIMILARLY INITIALIZED IN THE PENMAN ROUTINE.\n! ----------------------------------------------------------------------\n      FLX1 = CPH2O * PRCP * (T1- SFCTMP)\n      FLX3 = 0.0\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE NOPAC\n! ----------------------------------------------------------------------\n\n      SUBROUTINE PENMAN (SFCTMP,SFCPRS,CH,T2V,TH2,PRCP,FDOWN,T24,SSOIL, &\n     &                   Q2,Q2SAT,ETP,RCH,EPSCA,RR,SNOWNG,FRZGRA,       &\n     &              DQSDT2,FLX2,EMISSI_IN,SNEQV,T1,ICE,SNCOVR)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE PENMAN\n! ----------------------------------------------------------------------\n! CALCULATE POTENTIAL EVAPORATION FOR THE CURRENT POINT.  VARIOUS\n! PARTIAL SUMS/PRODUCTS ARE ALSO CALCULATED AND PASSED BACK TO THE\n! CALLING ROUTINE FOR LATER USE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      LOGICAL, INTENT(IN)     :: SNOWNG, FRZGRA\n      REAL, INTENT(IN)        :: CH, DQSDT2,FDOWN,PRCP,                 &\n                                 Q2, Q2SAT,SSOIL, SFCPRS, SFCTMP,       &\n                                 T2V, TH2,EMISSI_IN,SNEQV\n      REAL, INTENT(IN)        :: T1 , SNCOVR\n!\n! kmh 09/13/2006\n      INTEGER, INTENT(IN)     :: ICE\n! kmh 09/03/2006\n!\n      REAL, INTENT(OUT)       :: EPSCA,ETP,FLX2,RCH,RR,T24\n      REAL                    :: A, DELTA, FNET,RAD,RHO,EMISSI,ELCP1,LVS\n\n      REAL, PARAMETER      :: ELCP = 2.4888E+3, LSUBC = 2.501000E+6,CP = 1004.6\n      REAL, PARAMETER      :: LSUBS = 2.83E+6\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE:\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! PREPARE PARTIAL QUANTITIES FOR PENMAN EQUATION.\n! ----------------------------------------------------------------------\n        EMISSI=EMISSI_IN\n        IF (ICE==0) THEN\n           ELCP1  = (1.0-SNCOVR)*ELCP  + SNCOVR*ELCP*LSUBS/LSUBC\n           LVS    = (1.0-SNCOVR)*LSUBC + SNCOVR*LSUBS\n        ELSE\n           IF ( T1 > 273.15 ) THEN\n              ELCP1=ELCP\n              LVS=LSUBC\n           ELSE\n              ELCP1  = ELCP*LSUBS/LSUBC\n              LVS    = LSUBS\n           ENDIF\n        ENDIF\n\n      FLX2 = 0.0\n!      DELTA = ELCP * DQSDT2\n      DELTA = ELCP1 * DQSDT2\n      T24 = SFCTMP * SFCTMP * SFCTMP * SFCTMP\n!      RR = T24 * 6.48E-8 / (SFCPRS * CH) + 1.0\n      RR = EMISSI*T24 * 6.48E-8 / (SFCPRS * CH) + 1.0\n      RHO = SFCPRS / (RD * T2V)\n\n! ----------------------------------------------------------------------\n! ADJUST THE PARTIAL SUMS / PRODUCTS WITH THE LATENT HEAT\n! EFFECTS CAUSED BY FALLING PRECIPITATION.\n! ----------------------------------------------------------------------\n      RCH = RHO * CP * CH\n      IF (.NOT. SNOWNG) THEN\n         IF (PRCP >  0.0) RR = RR + CPH2O * PRCP / RCH\n      ELSE\n         RR = RR + CPICE * PRCP / RCH\n      END IF\n\n! ----------------------------------------------------------------------\n! INCLUDE THE LATENT HEAT EFFECTS OF FRZNG RAIN CONVERTING TO ICE ON\n! IMPACT IN THE CALCULATION OF FLX2 AND FNET.\n! ----------------------------------------------------------------------\n!      FNET = FDOWN - SIGMA * T24- SSOIL\n      FNET = FDOWN -  EMISSI*SIGMA * T24- SSOIL\n      IF (FRZGRA) THEN\n         FLX2 = - LSUBF * PRCP\n         FNET = FNET - FLX2\n! ----------------------------------------------------------------------\n! FINISH PENMAN EQUATION CALCULATIONS.\n! ----------------------------------------------------------------------\n      END IF\n      RAD = FNET / RCH + TH2- SFCTMP\n!      A = ELCP * (Q2SAT - Q2)\n      A = ELCP1 * (Q2SAT - Q2)\n      EPSCA = (A * RR + RAD * DELTA) / (DELTA + RR)\n!      ETP = EPSCA * RCH / LSUBC\n      ETP = EPSCA * RCH / LVS\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE PENMAN\n! ----------------------------------------------------------------------\n\n      SUBROUTINE REDPRM (VEGTYP,SOILTYP,SLOPETYP,CFACTR,CMCMAX,RSMAX,      &\n                         TOPT,                                             &\n                         REFKDT,KDT,SBETA, SHDFAC,RSMIN,RGL,HS,ZBOT,FRZX,  &\n                         PSISAT,SLOPE,SNUP,SALP,BEXP,DKSAT,DWSAT,          &\n                         SMCMAX,SMCWLT,SMCREF,SMCDRY,F1,QUARTZ,FXEXP,      &\n                         RTDIS,SLDPTH,ZSOIL, NROOT,NSOIL,CZIL,             &\n                         LAIMIN, LAIMAX, EMISSMIN, EMISSMAX, ALBEDOMIN,    &\n                         ALBEDOMAX, Z0MIN, Z0MAX, CSOIL, PTU, LLANDUSE,    &\n                         LSOIL, LOCAL,LVCOEF)\n\n      IMPLICIT NONE\n! ----------------------------------------------------------------------\n! Internally set (default valuess)\n! all soil and vegetation parameters required for the execusion oF\n! the Noah lsm are defined in VEGPARM.TBL, SOILPARM.TB, and GENPARM.TBL.\n! ----------------------------------------------------------------------\n!     Vegetation parameters:\n!             ALBBRD: SFC background snow-free albedo\n!             CMXTBL: MAX CNPY Capacity\n!              Z0BRD: Background roughness length\n!             SHDFAC: Green vegetation fraction\n!              NROOT: Rooting depth\n!              RSMIN: Mimimum stomatal resistance\n!              RSMAX: Max. stomatal resistance\n!                RGL: Parameters used in radiation stress function\n!                 HS: Parameter used in vapor pressure deficit functio\n!               TOPT: Optimum transpiration air temperature.\n!             CMCMAX: Maximum canopy water capacity\n!             CFACTR: Parameter used in the canopy inteception calculation\n!               SNUP: Threshold snow depth (in water equivalent m) that\n!                     implies 100 percent snow cover\n!                LAI: Leaf area index\n!\n! ----------------------------------------------------------------------\n!      Soil parameters:\n!        SMCMAX: MAX soil moisture content (porosity)\n!        SMCREF: Reference soil moisture  (field capacity)\n!        SMCWLT: Wilting point soil moisture\n!        SMCWLT: Air dry soil moist content limits\n!       SSATPSI: SAT (saturation) soil potential\n!         DKSAT: SAT soil conductivity\n!          BEXP: B parameter\n!        SSATDW: SAT soil diffusivity\n!           F1: Soil thermal diffusivity/conductivity coef.\n!        QUARTZ: Soil quartz content\n!  Modified by F. Chen (12/22/97)  to use the STATSGO soil map\n!  Modified By F. Chen (01/22/00)  to include PLaya, Lava, and White San\n!  Modified By F. Chen (08/05/02)  to include additional parameters for the Noah\n! NOTE: SATDW = BB*SATDK*(SATPSI/MAXSMC)\n!         F11 = ALOG10(SATPSI) + BB*ALOG10(MAXSMC) + 2.0\n!       REFSMC1=MAXSMC*(5.79E-9/SATDK)**(1/(2*BB+3)) 5.79E-9 m/s= 0.5 mm\n!       REFSMC=REFSMC1+1./3.(MAXSMC-REFSMC1)\n!       WLTSMC1=MAXSMC*(200./SATPSI)**(-1./BB)    (Wetzel and Chang, 198\n!       WLTSMC=WLTSMC1-0.5*WLTSMC1\n! Note: the values for playa is set for it to have a thermal conductivit\n! as sand and to have a hydrulic conductivity as clay\n!\n! ----------------------------------------------------------------------\n! Class parameter 'SLOPETYP' was included to estimate linear reservoir\n! coefficient 'SLOPE' to the baseflow runoff out of the bottom layer.\n! lowest class (slopetyp=0) means highest slope parameter = 1.\n! definition of slopetyp from 'zobler' slope type:\n! slope class  percent slope\n! 1            0-8\n! 2            8-30\n! 3            > 30\n! 4            0-30\n! 5            0-8 & > 30\n! 6            8-30 & > 30\n! 7            0-8, 8-30, > 30\n! 9            GLACIAL ICE\n! BLANK        OCEAN/SEA\n!       SLOPE_DATA: linear reservoir coefficient\n!       SBETA_DATA: parameter used to caluculate vegetation effect on soil heat\n!       FXEXP_DAT:  soil evaporation exponent used in DEVAP\n!       CSOIL_DATA: soil heat capacity [J M-3 K-1]\n!       SALP_DATA: shape parameter of  distribution function of snow cover\n!       REFDK_DATA and REFKDT_DATA: parameters in the surface runoff parameteriz\n!       FRZK_DATA: frozen ground parameter\n!       ZBOT_DATA: depth[M] of lower boundary soil temperature\n!       CZIL_DATA: calculate roughness length of heat\n!       SMLOW_DATA and MHIGH_DATA: two soil moisture wilt, soil moisture referen\n!                 parameters\n! Set maximum number of soil-, veg-, and slopetyp in data statement.\n! ----------------------------------------------------------------------\n      INTEGER, PARAMETER     :: MAX_SLOPETYP=30,MAX_SOILTYP=30,MAX_VEGTYP=30\n      LOGICAL                :: LOCAL\n      CHARACTER (LEN=256), INTENT(IN)::  LLANDUSE, LSOIL\n\n! Veg parameters\n      INTEGER, INTENT(IN)    :: VEGTYP\n      INTEGER, INTENT(OUT)   :: NROOT\n      REAL, INTENT(INOUT)    :: SHDFAC\n      REAL, INTENT(OUT)      :: HS,RSMIN,RGL,SNUP,                          &\n                                CMCMAX,RSMAX,TOPT,                          &\n                                EMISSMIN,  EMISSMAX,                        &\n                                LAIMIN,    LAIMAX,                          &\n                                Z0MIN,     Z0MAX,                           &\n                                ALBEDOMIN, ALBEDOMAX\n! Soil parameters\n      INTEGER, INTENT(IN)    :: SOILTYP\n      REAL, INTENT(OUT)      :: BEXP,DKSAT,DWSAT,F1,QUARTZ,SMCDRY,          &\n                                SMCMAX,SMCREF,SMCWLT,PSISAT\n! General parameters\n      INTEGER, INTENT(IN)    :: SLOPETYP,NSOIL\n      INTEGER                :: I\n\n      REAL,    INTENT(OUT)   :: SLOPE,CZIL,SBETA,FXEXP,                     &\n                                CSOIL,SALP,FRZX,KDT,CFACTR,      &\n                                ZBOT,REFKDT,PTU\n      REAL,    INTENT(OUT)   :: LVCOEF\n      REAL,DIMENSION(1:NSOIL),INTENT(IN) :: SLDPTH,ZSOIL\n      REAL,DIMENSION(1:NSOIL),INTENT(OUT):: RTDIS\n      REAL                   :: FRZFACT,FRZK,REFDK\n\n!      SAVE\n! ----------------------------------------------------------------------\n!\n               IF (SOILTYP .gt. SLCATS) THEN\n                        CALL wrf_error_fatal ( 'Warning: too many input soil types' )\n               END IF\n               IF (VEGTYP .gt. LUCATS) THEN\n                     CALL wrf_error_fatal ( 'Warning: too many input landuse types' )\n               END IF\n               IF (SLOPETYP .gt. SLPCATS) THEN\n                     CALL wrf_error_fatal ( 'Warning: too many input slope types' )\n               END IF\n\n! ----------------------------------------------------------------------\n!  SET-UP SOIL PARAMETERS\n! ----------------------------------------------------------------------\n      CSOIL = CSOIL_DATA\n      BEXP = BB (SOILTYP)\n      DKSAT = SATDK (SOILTYP)\n      DWSAT = SATDW (SOILTYP)\n      F1 = F11 (SOILTYP)\n      PSISAT = SATPSI (SOILTYP)\n      QUARTZ = QTZ (SOILTYP)\n      SMCDRY = DRYSMC (SOILTYP)\n      SMCMAX = MAXSMC (SOILTYP)\n      SMCREF = REFSMC (SOILTYP)\n      SMCWLT = WLTSMC (SOILTYP)\n! ----------------------------------------------------------------------\n! Set-up universal parameters (not dependent on SOILTYP, VEGTYP or\n! SLOPETYP)\n! ----------------------------------------------------------------------\n      ZBOT = ZBOT_DATA\n      SALP = SALP_DATA\n      SBETA = SBETA_DATA\n      REFDK = REFDK_DATA\n      FRZK = FRZK_DATA\n      FXEXP = FXEXP_DATA\n      REFKDT = REFKDT_DATA\n      PTU = 0.    ! (not used yet) to satisify intent(out)\n      KDT = REFKDT * DKSAT / REFDK\n      CZIL = CZIL_DATA\n      SLOPE = SLOPE_DATA (SLOPETYP)\n      LVCOEF = LVCOEF_DATA\n\n! ----------------------------------------------------------------------\n! TO ADJUST FRZK PARAMETER TO ACTUAL SOIL TYPE: FRZK * FRZFACT\n! ----------------------------------------------------------------------\n      FRZFACT = (SMCMAX / SMCREF) * (0.412 / 0.468)\n      FRZX = FRZK * FRZFACT\n\n! ----------------------------------------------------------------------\n! SET-UP VEGETATION PARAMETERS\n! ----------------------------------------------------------------------\n      TOPT = TOPT_DATA\n      CMCMAX = CMCMAX_DATA\n      CFACTR = CFACTR_DATA\n      RSMAX = RSMAX_DATA\n      NROOT = NROTBL (VEGTYP)\n      SNUP = SNUPTBL (VEGTYP)\n      RSMIN = RSTBL (VEGTYP)\n      RGL = RGLTBL (VEGTYP)\n      HS = HSTBL (VEGTYP)\n      EMISSMIN  = EMISSMINTBL  (VEGTYP)\n      EMISSMAX  = EMISSMAXTBL  (VEGTYP)\n      LAIMIN    = LAIMINTBL    (VEGTYP)\n      LAIMAX    = LAIMAXTBL    (VEGTYP)\n      Z0MIN     = Z0MINTBL     (VEGTYP)\n      Z0MAX     = Z0MAXTBL     (VEGTYP)\n      ALBEDOMIN = ALBEDOMINTBL (VEGTYP)\n      ALBEDOMAX = ALBEDOMAXTBL (VEGTYP)\n\n               IF (VEGTYP .eq. BARE) SHDFAC = 0.0\n               IF (NROOT .gt. NSOIL) THEN\n                  WRITE (err_message,*) 'Error: too many root layers ',  &\n                                                 NSOIL,NROOT\n                  CALL wrf_error_fatal ( err_message )\n! ----------------------------------------------------------------------\n! CALCULATE ROOT DISTRIBUTION.  PRESENT VERSION ASSUMES UNIFORM\n! DISTRIBUTION BASED ON SOIL LAYER DEPTHS.\n! ----------------------------------------------------------------------\n               END IF\n               DO I = 1,NROOT\n                  RTDIS (I) = - SLDPTH (I)/ ZSOIL (NROOT)\n! ----------------------------------------------------------------------\n!  SET-UP SLOPE PARAMETER\n! ----------------------------------------------------------------------\n               END DO\n\n!        print*,'end of PRMRED'\n!       print*,'VEGTYP',VEGTYP,'SOILTYP',SOILTYP,'SLOPETYP',SLOPETYP,    &\n!    & 'CFACTR',CFACTR,'CMCMAX',CMCMAX,'RSMAX',RSMAX,'TOPT',TOPT,        &\n!    & 'REFKDT',REFKDT,'KDT',KDT,'SBETA',SBETA, 'SHDFAC',SHDFAC,         &\n!    &  'RSMIN',RSMIN,'RGL',RGL,'HS',HS,'ZBOT',ZBOT,'FRZX',FRZX,         &\n!    &  'PSISAT',PSISAT,'SLOPE',SLOPE,'SNUP',SNUP,'SALP',SALP,'BEXP',    &\n!    &   BEXP,                                                           &\n!    &  'DKSAT',DKSAT,'DWSAT',DWSAT,                                     &\n!    &  'SMCMAX',SMCMAX,'SMCWLT',SMCWLT,'SMCREF',SMCREF,'SMCDRY',SMCDRY, &\n!    &  'F1',F1,'QUARTZ',QUARTZ,'FXEXP',FXEXP,                           &\n!    &  'RTDIS',RTDIS,'SLDPTH',SLDPTH,'ZSOIL',ZSOIL, 'NROOT',NROOT,      &\n!    &  'NSOIL',NSOIL,'Z0',Z0,'CZIL',CZIL,'LAI',LAI,                     &\n!    &  'CSOIL',CSOIL,'PTU',PTU,                                         &\n!    &  'LOCAL', LOCAL\n\n      END  SUBROUTINE REDPRM\n\n      SUBROUTINE ROSR12 (P,A,B,C,D,DELTA,NSOIL)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE ROSR12\n! ----------------------------------------------------------------------\n! INVERT (SOLVE) THE TRI-DIAGONAL MATRIX PROBLEM SHOWN BELOW:\n! ###                                            ### ###  ###   ###  ###\n! #B(1), C(1),  0  ,  0  ,  0  ,   . . .  ,    0   # #      #   #      #\n! #A(2), B(2), C(2),  0  ,  0  ,   . . .  ,    0   # #      #   #      #\n! # 0  , A(3), B(3), C(3),  0  ,   . . .  ,    0   # #      #   # D(3) #\n! # 0  ,  0  , A(4), B(4), C(4),   . . .  ,    0   # # P(4) #   # D(4) #\n! # 0  ,  0  ,  0  , A(5), B(5),   . . .  ,    0   # # P(5) #   # D(5) #\n! # .                                          .   # #  .   # = #   .  #\n! # .                                          .   # #  .   #   #   .  #\n! # .                                          .   # #  .   #   #   .  #\n! # 0  , . . . , 0 , A(M-2), B(M-2), C(M-2),   0   # #P(M-2)#   #D(M-2)#\n! # 0  , . . . , 0 ,   0   , A(M-1), B(M-1), C(M-1)# #P(M-1)#   #D(M-1)#\n! # 0  , . . . , 0 ,   0   ,   0   ,  A(M) ,  B(M) # # P(M) #   # D(M) #\n! ###                                            ### ###  ###   ###  ###\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: NSOIL\n      INTEGER               :: K, KK\n\n      REAL, DIMENSION(1:NSOIL), INTENT(IN):: A, B, D\n      REAL, DIMENSION(1:NSOIL),INTENT(INOUT):: C,P,DELTA\n\n! ----------------------------------------------------------------------\n! INITIALIZE EQN COEF C FOR THE LOWEST SOIL LAYER\n! ----------------------------------------------------------------------\n      C (NSOIL) = 0.0\n      P (1) = - C (1) / B (1)\n! ----------------------------------------------------------------------\n! SOLVE THE COEFS FOR THE 1ST SOIL LAYER\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! SOLVE THE COEFS FOR SOIL LAYERS 2 THRU NSOIL\n! ----------------------------------------------------------------------\n      DELTA (1) = D (1) / B (1)\n      DO K = 2,NSOIL\n         P (K) = - C (K) * ( 1.0 / (B (K) + A (K) * P (K -1)) )\n         DELTA (K) = (D (K) - A (K)* DELTA (K -1))* (1.0/ (B (K) + A (K)&\n                    * P (K -1)))\n      END DO\n! ----------------------------------------------------------------------\n! SET P TO DELTA FOR LOWEST SOIL LAYER\n! ----------------------------------------------------------------------\n      P (NSOIL) = DELTA (NSOIL)\n\n! ----------------------------------------------------------------------\n! ADJUST P FOR SOIL LAYERS 2 THRU NSOIL\n! ----------------------------------------------------------------------\n      DO K = 2,NSOIL\n         KK = NSOIL - K + 1\n         P (KK) = P (KK) * P (KK +1) + DELTA (KK)\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE ROSR12\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE SHFLX (SSOIL,STC,SMC,SMCMAX,NSOIL,T1,DT,YY,ZZ1,ZSOIL,  &\n                         TBOT,ZBOT,SMCWLT,PSISAT,SH2O,BEXP,F1,DF1,ICE,  &\n                         QUARTZ,CSOIL,VEGTYP,ISURBAN)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SHFLX\n! ----------------------------------------------------------------------\n! UPDATE THE TEMPERATURE STATE OF THE SOIL COLUMN BASED ON THE THERMAL\n! DIFFUSION EQUATION AND UPDATE THE FROZEN SOIL MOISTURE CONTENT BASED\n! ON THE TEMPERATURE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: ICE, NSOIL, VEGTYP, ISURBAN\n      INTEGER               :: I\n\n      REAL, INTENT(IN)      :: BEXP,CSOIL,DF1,DT,F1,PSISAT,QUARTZ,     &\n                               SMCMAX, SMCWLT, TBOT,YY, ZBOT,ZZ1\n      REAL, INTENT(INOUT)   :: T1\n      REAL, INTENT(OUT)     :: SSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)    :: SMC,ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SH2O\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: STC\n      REAL, DIMENSION(1:NSOIL)             :: AI, BI, CI, STCF,RHSTS\n      REAL, PARAMETER       :: T0 = 273.15\n\n! ----------------------------------------------------------------------\n! HRT ROUTINE CALCS THE RIGHT HAND SIDE OF THE SOIL TEMP DIF EQN\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! SEA-ICE CASE, GLACIAL ICE CASE\n! ----------------------------------------------------------------------\n      IF ( ICE /= 0 ) THEN\n\n         CALL HRTICE (RHSTS,STC,TBOT,ICE,NSOIL,ZSOIL,YY,ZZ1,DF1,AI,BI,CI)\n\n         CALL HSTEP (STCF,STC,RHSTS,DT,NSOIL,AI,BI,CI)\n\n! ----------------------------------------------------------------------\n! LAND-MASS CASE\n! ----------------------------------------------------------------------\n      ELSE\n         CALL HRT (RHSTS,STC,SMC,SMCMAX,NSOIL,ZSOIL,YY,ZZ1,TBOT,        &\n                    ZBOT,PSISAT,SH2O,DT,                                &\n                    BEXP,F1,DF1,QUARTZ,CSOIL,AI,BI,CI,VEGTYP,ISURBAN)\n\n         CALL HSTEP (STCF,STC,RHSTS,DT,NSOIL,AI,BI,CI)\n      END IF\n      DO I = 1,NSOIL\n         STC (I) = STCF (I)\n      END DO\n\n! ----------------------------------------------------------------------\n! IN THE NO SNOWPACK CASE (VIA ROUTINE NOPAC BRANCH,) UPDATE THE GRND\n! (SKIN) TEMPERATURE HERE IN RESPONSE TO THE UPDATED SOIL TEMPERATURE\n! PROFILE ABOVE.  (NOTE: INSPECTION OF ROUTINE SNOPAC SHOWS THAT T1\n! BELOW IS A DUMMY VARIABLE ONLY, AS SKIN TEMPERATURE IS UPDATED\n! DIFFERENTLY IN ROUTINE SNOPAC)\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! CALCULATE SURFACE SOIL HEAT FLUX\n! ----------------------------------------------------------------------\n      T1 = (YY + (ZZ1- 1.0) * STC (1)) / ZZ1\n      SSOIL = DF1 * (STC (1) - T1) / (0.5 * ZSOIL (1))\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SHFLX\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SMFLX (SMC,NSOIL,CMC,DT,PRCP1,ZSOIL,                   &\n     &                   SH2O,SLOPE,KDT,FRZFACT,                        &\n     &                   SMCMAX,BEXP,SMCWLT,DKSAT,DWSAT,                &\n     &                   SHDFAC,CMCMAX,                                 &\n     &                   RUNOFF1,RUNOFF2,RUNOFF3,                       &\n     &                   EDIR,EC,ET,                                    &\n     &                   DRIP)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SMFLX\n! ----------------------------------------------------------------------\n! CALCULATE SOIL MOISTURE FLUX.  THE SOIL MOISTURE CONTENT (SMC - A PER\n! UNIT VOLUME MEASUREMENT) IS A DEPENDENT VARIABLE THAT IS UPDATED WITH\n! PROGNOSTIC EQNS. THE CANOPY MOISTURE CONTENT (CMC) IS ALSO UPDATED.\n! FROZEN GROUND VERSION:  NEW STATES ADDED: SH2O, AND FROZEN GROUND\n! CORRECTION FACTOR, FRZFACT AND PARAMETER SLOPE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: NSOIL\n      INTEGER               :: I,K\n\n      REAL, INTENT(IN)      :: BEXP, CMCMAX, DKSAT,DWSAT, DT, EC, EDIR,  &\n                               KDT, PRCP1, SHDFAC, SLOPE, SMCMAX, SMCWLT\n      REAL, INTENT(OUT)                      :: DRIP, RUNOFF1, RUNOFF2, RUNOFF3\n      REAL, INTENT(INOUT)   :: CMC\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: ET,ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT):: SMC, SH2O\n      REAL, DIMENSION(1:NSOIL)             :: AI, BI, CI, STCF,RHSTS, RHSTT, &\n                                              SICE, SH2OA, SH2OFG\n      REAL                  :: DUMMY, EXCESS,FRZFACT,PCPDRP,RHSCT,TRHSCT\n      REAL :: FAC2\n      REAL :: FLIMIT\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! COMPUTE THE RIGHT HAND SIDE OF THE CANOPY EQN TERM ( RHSCT )\n! ----------------------------------------------------------------------\n      DUMMY = 0.\n\n! ----------------------------------------------------------------------\n! CONVERT RHSCT (A RATE) TO TRHSCT (AN AMOUNT) AND ADD IT TO EXISTING\n! CMC.  IF RESULTING AMT EXCEEDS MAX CAPACITY, IT BECOMES DRIP AND WILL\n! FALL TO THE GRND.\n! ----------------------------------------------------------------------\n      RHSCT = SHDFAC * PRCP1- EC\n      DRIP = 0.\n      TRHSCT = DT * RHSCT\n      EXCESS = CMC + TRHSCT\n\n! ----------------------------------------------------------------------\n! PCPDRP IS THE COMBINED PRCP1 AND DRIP (FROM CMC) THAT GOES INTO THE\n! SOIL\n! ----------------------------------------------------------------------\n      IF (EXCESS > CMCMAX) DRIP = EXCESS - CMCMAX\n      PCPDRP = (1. - SHDFAC) * PRCP1+ DRIP / DT\n\n! ----------------------------------------------------------------------\n! STORE ICE CONTENT AT EACH SOIL LAYER BEFORE CALLING SRT and SSTEP\n!\n      DO I = 1,NSOIL\n         SICE (I) = SMC (I) - SH2O (I)\n      END DO\n! ----------------------------------------------------------------------\n! CALL SUBROUTINES SRT AND SSTEP TO SOLVE THE SOIL MOISTURE\n! TENDENCY EQUATIONS.\n! IF THE INFILTRATING PRECIP RATE IS NONTRIVIAL,\n!   (WE CONSIDER NONTRIVIAL TO BE A PRECIP TOTAL OVER THE TIME STEP\n!    EXCEEDING ONE ONE-THOUSANDTH OF THE WATER HOLDING CAPACITY OF\n!    THE FIRST SOIL LAYER)\n! THEN CALL THE SRT/SSTEP SUBROUTINE PAIR TWICE IN THE MANNER OF\n!   TIME SCHEME \"F\" (IMPLICIT STATE, AVERAGED COEFFICIENT)\n!   OF SECTION 2 OF KALNAY AND KANAMITSU (1988, MWR, VOL 116,\n!   PAGES 1945-1958)TO MINIMIZE 2-DELTA-T OSCILLATIONS IN THE\n!   SOIL MOISTURE VALUE OF THE TOP SOIL LAYER THAT CAN ARISE BECAUSE\n!   OF THE EXTREME NONLINEAR DEPENDENCE OF THE SOIL HYDRAULIC\n!   DIFFUSIVITY COEFFICIENT AND THE HYDRAULIC CONDUCTIVITY ON THE\n!   SOIL MOISTURE STATE\n! OTHERWISE CALL THE SRT/SSTEP SUBROUTINE PAIR ONCE IN THE MANNER OF\n!   TIME SCHEME \"D\" (IMPLICIT STATE, EXPLICIT COEFFICIENT)\n!   OF SECTION 2 OF KALNAY AND KANAMITSU\n! PCPDRP IS UNITS OF KG/M**2/S OR MM/S, ZSOIL IS NEGATIVE DEPTH IN M\n! ----------------------------------------------------------------------\n!  According to Dr. Ken Mitchell's suggestion, add the second contraint\n!  to remove numerical instability of runoff and soil moisture\n!  FLIMIT is a limit value for FAC2\n      FAC2=0.0\n      DO I=1,NSOIL\n         FAC2=MAX(FAC2,SH2O(I)/SMCMAX)\n      ENDDO\n      CALL FAC2MIT(SMCMAX,FLIMIT)\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! SMC STATES REPLACED BY SH2O STATES IN SRT SUBR.  SH2O & SICE STATES\n! INC&UDED IN SSTEP SUBR.  FROZEN GROUND CORRECTION FACTOR, FRZFACT\n! ADDED.  ALL WATER BALANCE CALCULATIONS USING UNFROZEN WATER\n! ----------------------------------------------------------------------\n      IF ( ( (PCPDRP * DT) > (0.0001*1000.0* (- ZSOIL (1))* SMCMAX) )   &\n           .OR. (FAC2 > FLIMIT) ) THEN\n         CALL SRT (RHSTT,EDIR,ET,SH2O,SH2O,NSOIL,PCPDRP,ZSOIL,          &\n                    DWSAT,DKSAT,SMCMAX,BEXP,RUNOFF1,                    &\n                    RUNOFF2,DT,SMCWLT,SLOPE,KDT,FRZFACT,SICE,AI,BI,CI)\n         CALL SSTEP (SH2OFG,SH2O,DUMMY,RHSTT,RHSCT,DT,NSOIL,SMCMAX,     &\n                        CMCMAX,RUNOFF3,ZSOIL,SMC,SICE,AI,BI,CI)\n         DO K = 1,NSOIL\n            SH2OA (K) = (SH2O (K) + SH2OFG (K)) * 0.5\n         END DO\n         CALL SRT (RHSTT,EDIR,ET,SH2O,SH2OA,NSOIL,PCPDRP,ZSOIL,         &\n                    DWSAT,DKSAT,SMCMAX,BEXP,RUNOFF1,                    &\n                    RUNOFF2,DT,SMCWLT,SLOPE,KDT,FRZFACT,SICE,AI,BI,CI)\n         CALL SSTEP (SH2O,SH2O,CMC,RHSTT,RHSCT,DT,NSOIL,SMCMAX,         &\n                        CMCMAX,RUNOFF3,ZSOIL,SMC,SICE,AI,BI,CI)\n\n      ELSE\n         CALL SRT (RHSTT,EDIR,ET,SH2O,SH2O,NSOIL,PCPDRP,ZSOIL,          &\n                    DWSAT,DKSAT,SMCMAX,BEXP,RUNOFF1,                    &\n                      RUNOFF2,DT,SMCWLT,SLOPE,KDT,FRZFACT,SICE,AI,BI,CI)\n         CALL SSTEP (SH2O,SH2O,CMC,RHSTT,RHSCT,DT,NSOIL,SMCMAX,         &\n                        CMCMAX,RUNOFF3,ZSOIL,SMC,SICE,AI,BI,CI)\n!      RUNOF = RUNOFF\n\n      END IF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SMFLX\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE SNFRAC (SNEQV,SNUP,SALP,SNOWH,SNCOVR)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNFRAC\n! ----------------------------------------------------------------------\n! CALCULATE SNOW FRACTION (0 -> 1)\n! SNEQV   SNOW WATER EQUIVALENT (M)\n! SNUP    THRESHOLD SNEQV DEPTH ABOVE WHICH SNCOVR=1\n! SALP    TUNING PARAMETER\n! SNCOVR  FRACTIONAL SNOW COVER\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      REAL, INTENT(IN)     :: SNEQV,SNUP,SALP,SNOWH\n      REAL, INTENT(OUT)    :: SNCOVR\n      REAL                 :: RSNOW, Z0N\n\n! ----------------------------------------------------------------------\n! SNUP IS VEG-CLASS DEPENDENT SNOWDEPTH THRESHHOLD (SET IN ROUTINE\n! REDPRM) ABOVE WHICH SNOCVR=1.\n! ----------------------------------------------------------------------\n      IF (SNEQV < SNUP) THEN\n         RSNOW = SNEQV / SNUP\n         SNCOVR = 1. - ( EXP ( - SALP * RSNOW) - RSNOW * EXP ( - SALP))\n      ELSE\n         SNCOVR = 1.0\n      END IF\n\n!     FORMULATION OF DICKINSON ET AL. 1986\n!     Z0N = 0.035\n\n!        SNCOVR=SNOWH/(SNOWH + 5*Z0N)\n\n!     FORMULATION OF MARSHALL ET AL. 1994\n!        SNCOVR=SNEQV/(SNEQV + 2*Z0N)\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNFRAC\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SNKSRC (TSNSR,TAVG,SMC,SH2O,ZSOIL,NSOIL,               &\n     &                      SMCMAX,PSISAT,BEXP,DT,K,QTOT)\n! ----------------------------------------------------------------------\n! SUBROUTINE SNKSRC\n! ----------------------------------------------------------------------\n! CALCULATE SINK/SOURCE TERM OF THE TERMAL DIFFUSION EQUATION. (SH2O) IS\n! AVAILABLE LIQUED WATER.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: K,NSOIL\n      REAL, INTENT(IN)      :: BEXP, DT, PSISAT, QTOT, SMC, SMCMAX,    &\n                               TAVG\n      REAL, INTENT(INOUT)   :: SH2O\n\n      REAL, DIMENSION(1:NSOIL), INTENT(IN):: ZSOIL\n\n      REAL                  :: DF, DZ, DZH, FREE, TSNSR,               &\n                               TDN, TM, TUP, TZ, X0, XDN, XH2O, XUP\n\n      REAL, PARAMETER       :: DH2O = 1.0000E3, HLICE = 3.3350E5,      &\n                               T0 = 2.7315E2\n\n      IF (K == 1) THEN\n         DZ = - ZSOIL (1)\n      ELSE\n         DZ = ZSOIL (K -1) - ZSOIL (K)\n      END IF\n! ----------------------------------------------------------------------\n! VIA FUNCTION FRH2O, COMPUTE POTENTIAL OR 'EQUILIBRIUM' UNFROZEN\n! SUPERCOOLED FREE WATER FOR GIVEN SOIL TYPE AND SOIL LAYER TEMPERATURE.\n! FUNCTION FRH20 INVOKES EQN (17) FROM V. KOREN ET AL (1999, JGR, VOL.\n! 104, PG 19573).  (ASIDE:  LATTER EQN IN JOURNAL IN CENTIGRADE UNITS.\n! ROUTINE FRH2O USE FORM OF EQN IN KELVIN UNITS.)\n! ----------------------------------------------------------------------\n!      FREE = FRH2O(TAVG,SMC,SH2O,SMCMAX,BEXP,PSISAT)\n\n! ----------------------------------------------------------------------\n! IN NEXT BLOCK OF CODE, INVOKE EQN 18 OF V. KOREN ET AL (1999, JGR,\n! VOL. 104, PG 19573.)  THAT IS, FIRST ESTIMATE THE NEW AMOUNTOF LIQUID\n! WATER, 'XH2O', IMPLIED BY THE SUM OF (1) THE LIQUID WATER AT THE BEGIN\n! OF CURRENT TIME STEP, AND (2) THE FREEZE OF THAW CHANGE IN LIQUID\n! WATER IMPLIED BY THE HEAT FLUX 'QTOT' PASSED IN FROM ROUTINE HRT.\n! SECOND, DETERMINE IF XH2O NEEDS TO BE BOUNDED BY 'FREE' (EQUIL AMT) OR\n! IF 'FREE' NEEDS TO BE BOUNDED BY XH2O.\n! ----------------------------------------------------------------------\n      CALL FRH2O (FREE,TAVG,SMC,SH2O,SMCMAX,BEXP,PSISAT)\n\n! ----------------------------------------------------------------------\n! FIRST, IF FREEZING AND REMAINING LIQUID LESS THAN LOWER BOUND, THEN\n! REDUCE EXTENT OF FREEZING, THEREBY LETTING SOME OR ALL OF HEAT FLUX\n! QTOT COOL THE SOIL TEMP LATER IN ROUTINE HRT.\n! ----------------------------------------------------------------------\n      XH2O = SH2O + QTOT * DT / (DH2O * HLICE * DZ)\n      IF ( XH2O < SH2O .AND. XH2O < FREE) THEN\n         IF ( FREE > SH2O ) THEN\n            XH2O = SH2O\n         ELSE\n            XH2O = FREE\n         END IF\n      END IF\n! ----------------------------------------------------------------------\n! SECOND, IF THAWING AND THE INCREASE IN LIQUID WATER GREATER THAN UPPER\n! BOUND, THEN REDUCE EXTENT OF THAW, THEREBY LETTING SOME OR ALL OF HEAT\n! FLUX QTOT WARM THE SOIL TEMP LATER IN ROUTINE HRT.\n! ----------------------------------------------------------------------\n      IF ( XH2O > SH2O .AND. XH2O > FREE ) THEN\n         IF ( FREE < SH2O ) THEN\n            XH2O = SH2O\n         ELSE\n            XH2O = FREE\n         END IF\n      END IF\n\n! ----------------------------------------------------------------------\n! CALCULATE PHASE-CHANGE HEAT SOURCE/SINK TERM FOR USE IN ROUTINE HRT\n! AND UPDATE LIQUID WATER TO REFLCET FINAL FREEZE/THAW INCREMENT.\n! ----------------------------------------------------------------------\n!      SNKSRC = -DH2O*HLICE*DZ*(XH2O-SH2O)/DT\n      IF (XH2O < 0.) XH2O = 0.\n      IF (XH2O > SMC) XH2O = SMC\n      TSNSR = - DH2O * HLICE * DZ * (XH2O - SH2O)/ DT\n      SH2O = XH2O\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNKSRC\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SNOPAC (ETP,ETA,PRCP,PRCPF,SNOWNG,SMC,SMCMAX,SMCWLT,   &\n                          SMCREF,SMCDRY,CMC,CMCMAX,NSOIL,DT,            &\n                          SBETA,DF1,                                    &\n                          Q2,T1,SFCTMP,T24,TH2,FDOWN,F1,SSOIL,STC,EPSCA,&\n                         SFCPRS,BEXP,PC,RCH,RR,CFACTR,SNCOVR,ESD,SNDENS,&\n                          SNOWH,SH2O,SLOPE,KDT,FRZFACT,PSISAT,          &\n                          ZSOIL,DWSAT,DKSAT,TBOT,ZBOT,SHDFAC,RUNOFF1,   &\n                          RUNOFF2,RUNOFF3,EDIR,EC,ET,ETT,NROOT,SNOMLT,  &\n                          ICE,RTDIS,QUARTZ,FXEXP,CSOIL,                 &\n                          BETA,DRIP,DEW,FLX1,FLX2,FLX3,ESNOW,ETNS,EMISSI,&\n                          RIBB,SOLDN,                                   &\n                          ISURBAN,                                      &\n\n                          VEGTYP)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNOPAC\n! ----------------------------------------------------------------------\n! CALCULATE SOIL MOISTURE AND HEAT FLUX VALUES & UPDATE SOIL MOISTURE\n! CONTENT AND SOIL HEAT CONTENT VALUES FOR THE CASE WHEN A SNOW PACK IS\n! PRESENT.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER, INTENT(IN)   :: ICE, NROOT, NSOIL,VEGTYP\n      INTEGER, INTENT(IN)   :: ISURBAN\n      INTEGER               :: K\n!\n! kmh 09/03/2006 add IT16 for surface temperature iteration\n!\n      INTEGER               :: IT16\n      LOGICAL, INTENT(IN)   :: SNOWNG\n      REAL, INTENT(IN)      :: BEXP,CFACTR, CMCMAX,CSOIL,DF1,DKSAT,     &\n                               DT,DWSAT, EPSCA,FDOWN,F1,FXEXP,          &\n                               FRZFACT,KDT,PC, PRCP,PSISAT,Q2,QUARTZ,   &\n                               RCH,RR,SBETA,SFCPRS, SFCTMP, SHDFAC,     &\n                               SLOPE,SMCDRY,SMCMAX,SMCREF,SMCWLT, T24,  &\n                               TBOT,TH2,ZBOT,EMISSI,SOLDN\n      REAL, INTENT(INOUT)   :: CMC, BETA, ESD,FLX2,PRCPF,SNOWH,SNCOVR,  &\n                               SNDENS, T1, RIBB, ETP\n      REAL, INTENT(OUT)     :: DEW,DRIP,EC,EDIR, ETNS, ESNOW,ETT,       &\n                               FLX1,FLX3, RUNOFF1,RUNOFF2,RUNOFF3,      &\n                               SSOIL,SNOMLT\n      REAL, DIMENSION(1:NSOIL),INTENT(IN)     :: RTDIS,ZSOIL\n      REAL, DIMENSION(1:NSOIL),INTENT(OUT)    :: ET\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SMC,SH2O,STC\n      REAL, DIMENSION(1:NSOIL) :: ET1\n      REAL                  :: DENOM,DSOIL,DTOT,EC1,EDIR1,ESDFLX,ETA,   &\n                               ETT1, ESNOW1, ESNOW2, ETA1,ETP1,ETP2,    &\n                               ETP3, ETNS1, ETANRG, ETAX, EX, FLX3X,    &\n                               FRCSNO,FRCSOI, PRCP1, QSAT,RSNOW, SEH,   &\n                               SNCOND,SSOIL1, T11,T12, T12A, T12AX,     &\n                               T12B, T14, YY, ZZ1\n!                               T12B, T14, YY, ZZ1,EMISSI_S\n!\n! kmh 01/11/2007 add T15, T16, and DTOT2 for SFC T iteration and snow heat flux\n!\n      REAL                  :: T15, T16, DTOT2\n      REAL, PARAMETER       :: ESDMIN = 1.E-6, LSUBC = 2.501000E+6,     &\n                               LSUBS = 2.83E+6, TFREEZ = 273.15,        &\n                               SNOEXP = 2.0\n\n! ----------------------------------------------------------------------\n! EXECUTABLE CODE BEGINS HERE:\n! ----------------------------------------------------------------------\n! IF SEA-ICE (ICE=1) OR GLACIAL-ICE (ICE=-1), SNOWCOVER FRACTION = 1.0,\n! AND SUBLIMATION IS AT THE POTENTIAL RATE.\n! FOR NON-GLACIAL LAND (ICE=0), IF SNOWCOVER FRACTION < 1.0, TOTAL\n! EVAPORATION < POTENTIAL DUE TO NON-POTENTIAL CONTRIBUTION FROM\n! NON-SNOW COVERED FRACTION.\n! ----------------------------------------------------------------------\n! INITIALIZE EVAP TERMS.\n! ----------------------------------------------------------------------\n! conversions:\n! ESNOW [KG M-2 S-1]\n! ESDFLX [KG M-2 S-1] .le. ESNOW\n! ESNOW1 [M S-1]\n! ESNOW2 [M]\n! ETP [KG M-2 S-1]\n! ETP1 [M S-1]\n! ETP2 [M]\n! ----------------------------------------------------------------------\n      DEW = 0.\n      EDIR = 0.\n      EDIR1 = 0.\n      EC1 = 0.\n      EC = 0.\n!      EMISSI_S=0.95    ! For snow\n\n      DO K = 1,NSOIL\n         ET (K) = 0.\n         ET1 (K) = 0.\n      END DO\n      ETT = 0.\n      ETT1 = 0.\n      ETNS = 0.\n      ETNS1 = 0.\n      ESNOW = 0.\n      ESNOW1 = 0.\n      ESNOW2 = 0.\n\n! ----------------------------------------------------------------------\n! CONVERT POTENTIAL EVAP (ETP) FROM KG M-2 S-1 TO ETP1 IN M S-1\n! ----------------------------------------------------------------------\n      PRCP1 = PRCPF *0.001\n! ----------------------------------------------------------------------\n! IF ETP<0 (DOWNWARD) THEN DEWFALL (=FROSTFALL IN THIS CASE).\n! ----------------------------------------------------------------------\n      BETA = 1.0\n      IF (ETP <= 0.0) THEN\n         IF ( ( RIBB >= 0.1 ) .AND. ( FDOWN > 150.0 ) ) THEN\n            ETP=(MIN(ETP*(1.0-RIBB),0.)*SNCOVR/0.980 + ETP*(0.980-SNCOVR))/0.980\n         ENDIF\n        IF(ETP == 0.) BETA = 0.0\n        ETP1 = ETP * 0.001\n         DEW = -ETP1\n         ESNOW2 = ETP1*DT\n         ETANRG = ETP*((1.-SNCOVR)*LSUBC + SNCOVR*LSUBS)\n      ELSE\n         ETP1 = ETP * 0.001\n         IF ( ICE /= 0 ) THEN\n            ! SEA-ICE AND GLACIAL-ICE CASE\n            ESNOW = ETP\n            ESNOW1 = ESNOW*0.001\n            ESNOW2 = ESNOW1*DT\n            ETANRG = ESNOW*LSUBS\n         ELSE IF ( ICE ==  0) THEN\n            ! NON-GLACIAL LAND CASE\n             IF (SNCOVR <  1.) THEN\n               CALL EVAPO (ETNS1,SMC,NSOIL,CMC,ETP1,DT,ZSOIL,           &\n                            SH2O,                                       &\n                            SMCMAX,BEXP,PC,SMCWLT,DKSAT,DWSAT,          &\n                            SMCREF,SHDFAC,CMCMAX,                       &\n                            SMCDRY,CFACTR,                              &\n                            EDIR1,EC1,ET1,ETT1,SFCTMP,Q2,NROOT,RTDIS,   &\n                            FXEXP)\n! ----------------------------------------------------------------------------\n               EDIR1 = EDIR1* (1. - SNCOVR)\n               EC1 = EC1* (1. - SNCOVR)\n               DO K = 1,NSOIL\n                  ET1 (K) = ET1 (K)* (1. - SNCOVR)\n               END DO\n               ETT1 = ETT1*(1.-SNCOVR)\n!               ETNS1 = EDIR1+ EC1+ ETT1\n               ETNS1 = ETNS1*(1.-SNCOVR)\n! ----------------------------------------------------------------------------\n               EDIR = EDIR1*1000.\n               EC = EC1*1000.\n               DO K = 1,NSOIL\n                  ET (K) = ET1 (K)*1000.\n               END DO\n               ETT = ETT1*1000.\n               ETNS = ETNS1*1000.\n! ----------------------------------------------------------------------\n\n!   end IF (SNCOVR .lt. 1.)\n            END IF\n!   end IF (ICE .ne. 1)\n         END IF\n         ESNOW = ETP*SNCOVR\n         ESNOW1 = ESNOW*0.001\n         ESNOW2 = ESNOW1*DT\n         ETANRG = ESNOW*LSUBS + ETNS*LSUBC\n!   end IF (ETP .le. 0.0)\n      END IF\n\n! ----------------------------------------------------------------------\n! IF PRECIP IS FALLING, CALCULATE HEAT FLUX FROM SNOW SFC TO NEWLY\n! ACCUMULATING PRECIP.  NOTE THAT THIS REFLECTS THE FLUX APPROPRIATE FOR\n! THE NOT-YET-UPDATED SKIN TEMPERATURE (T1).  ASSUMES TEMPERATURE OF THE\n! SNOWFALL STRIKING THE GROUND IS =SFCTMP (LOWEST MODEL LEVEL AIR TEMP).\n! ----------------------------------------------------------------------\n      FLX1 = 0.0\n      IF (SNOWNG) THEN\n         FLX1 = CPICE * PRCP * (T1- SFCTMP)\n      ELSE\n         IF (PRCP >  0.0) FLX1 = CPH2O * PRCP * (T1- SFCTMP)\n! ----------------------------------------------------------------------\n! CALCULATE AN 'EFFECTIVE SNOW-GRND SFC TEMP' (T12) BASED ON HEAT FLUXES\n! BETWEEN THE SNOW PACK AND THE SOIL AND ON NET RADIATION.\n! INCLUDE FLX1 (PRECIP-SNOW SFC) AND FLX2 (FREEZING RAIN LATENT HEAT)\n! FLUXES.  FLX1 FROM ABOVE, FLX2 BROUGHT IN VIA COMMOM BLOCK RITE.\n! FLX2 REFLECTS FREEZING RAIN LATENT HEAT FLUX USING T1 CALCULATED IN\n! PENMAN.\n! ----------------------------------------------------------------------\n      END IF\n      DSOIL = - (0.5 * ZSOIL (1))\n      DTOT = SNOWH + DSOIL\n      DENOM = 1.0+ DF1 / (DTOT * RR * RCH)\n! surface emissivity weighted by snow cover fraction\n!      T12A = ( (FDOWN - FLX1 - FLX2 -                                   &\n!     &       ((SNCOVR*EMISSI_S)+EMISSI*(1.0-SNCOVR))*SIGMA *T24)/RCH    &\n!     &       + TH2 - SFCTMP - ETANRG/RCH ) / RR\n      T12A = ( (FDOWN - FLX1- FLX2- EMISSI * SIGMA * T24)/ RCH                    &\n                + TH2- SFCTMP - ETANRG / RCH ) / RR\n\n      T12B = DF1 * STC (1) / (DTOT * RR * RCH)\n\n! ----------------------------------------------------------------------\n! IF THE 'EFFECTIVE SNOW-GRND SFC TEMP' IS AT OR BELOW FREEZING, NO SNOW\n! MELT WILL OCCUR.  SET THE SKIN TEMP TO THIS EFFECTIVE TEMP.  REDUCE\n! (BY SUBLIMINATION ) OR INCREASE (BY FROST) THE DEPTH OF THE SNOWPACK,\n! DEPENDING ON SIGN OF ETP.\n! UPDATE SOIL HEAT FLUX (SSOIL) USING NEW SKIN TEMPERATURE (T1)\n! SINCE NO SNOWMELT, SET ACCUMULATED SNOWMELT TO ZERO, SET 'EFFECTIVE'\n! PRECIP FROM SNOWMELT TO ZERO, SET PHASE-CHANGE HEAT FLUX FROM SNOWMELT\n! TO ZERO.\n! ----------------------------------------------------------------------\n! SUB-FREEZING BLOCK\n! ----------------------------------------------------------------------\n      T12 = (SFCTMP + T12A + T12B) / DENOM\n      IF (T12 <=  TFREEZ) THEN\n         T1 = T12\n         SSOIL = DF1 * (T1- STC (1)) / DTOT\n!        ESD = MAX (0.0, ESD- ETP2)\n         ESD = MAX(0.0, ESD-ESNOW2)\n         FLX3 = 0.0\n         EX = 0.0\n\n         SNOMLT = 0.0\n! ----------------------------------------------------------------------\n! IF THE 'EFFECTIVE SNOW-GRND SFC TEMP' IS ABOVE FREEZING, SNOW MELT\n! WILL OCCUR.  CALL THE SNOW MELT RATE,EX AND AMT, SNOMLT.  REVISE THE\n! EFFECTIVE SNOW DEPTH.  REVISE THE SKIN TEMP BECAUSE IT WOULD HAVE CHGD\n! DUE TO THE LATENT HEAT RELEASED BY THE MELTING. CALC THE LATENT HEAT\n! RELEASED, FLX3. SET THE EFFECTIVE PRECIP, PRCP1 TO THE SNOW MELT RATE,\n! EX FOR USE IN SMFLX.  ADJUSTMENT TO T1 TO ACCOUNT FOR SNOW PATCHES.\n! CALCULATE QSAT VALID AT FREEZING POINT.  NOTE THAT ESAT (SATURATION\n! VAPOR PRESSURE) VALUE OF 6.11E+2 USED HERE IS THAT VALID AT FRZZING\n! POINT.  NOTE THAT ETP FROM CALL PENMAN IN SFLX IS IGNORED HERE IN\n! FAVOR OF BULK ETP OVER 'OPEN WATER' AT FREEZING TEMP.\n! UPDATE SOIL HEAT FLUX (S) USING NEW SKIN TEMPERATURE (T1)\n! ----------------------------------------------------------------------\n! ABOVE FREEZING BLOCK\n! ----------------------------------------------------------------------\n      ELSE\n         T1 = TFREEZ * SNCOVR ** SNOEXP + T12 * (1.0- SNCOVR ** SNOEXP)\n         BETA = 1.0\n\n! ----------------------------------------------------------------------\n! IF POTENTIAL EVAP (SUBLIMATION) GREATER THAN DEPTH OF SNOWPACK.\n! BETA<1\n! SNOWPACK HAS SUBLIMATED AWAY, SET DEPTH TO ZERO.\n! ----------------------------------------------------------------------\n         IF ( ICE /= 0 ) then\n            ! kmh  12/15/2005 modify SSOIL\n            ! kmh  09/03/2006 modify DTOT\n            IF ( DTOT .GT. 2.0*DSOIL ) THEN\n               DTOT = 2.0*DSOIL\n            ENDIF\n         ENDIF\n         SSOIL = DF1 * (T1- STC (1)) / DTOT\n         IF (ESD-ESNOW2 <= ESDMIN) THEN\n            ESD = 0.0\n            EX = 0.0\n            SNOMLT = 0.0\n            FLX3 = 0.0\n! ----------------------------------------------------------------------\n! SUBLIMATION LESS THAN DEPTH OF SNOWPACK\n! SNOWPACK (ESD) REDUCED BY ESNOW2 (DEPTH OF SUBLIMATED SNOW)\n! ----------------------------------------------------------------------\n         ELSE\n            ESD = ESD-ESNOW2\n            ETP3 = ETP * LSUBC\n            SEH = RCH * (T1- TH2)\n            T14 = T1* T1\n            T14 = T14* T14\n!           FLX3 = FDOWN - FLX1 - FLX2 -                                 &\n!                  ((SNCOVR*EMISSI_S)+EMISSI*(1-SNCOVR))*SIGMA*T14 -     &\n!                    SSOIL - SEH - ETANRG\n            FLX3 = FDOWN - FLX1- FLX2- EMISSI*SIGMA * T14- SSOIL - SEH - ETANRG\n            IF (FLX3 <= 0.0) FLX3 = 0.0\n! ----------------------------------------------------------------------\n! SNOWMELT REDUCTION DEPENDING ON SNOW COVER\n! ----------------------------------------------------------------------\n            EX = FLX3*0.001/ LSUBF\n\n! ----------------------------------------------------------------------\n! ESDMIN REPRESENTS A SNOWPACK DEPTH THRESHOLD VALUE BELOW WHICH WE\n! CHOOSE NOT TO RETAIN ANY SNOWPACK, AND INSTEAD INCLUDE IT IN SNOWMELT.\n! ----------------------------------------------------------------------\n            SNOMLT = EX * DT\n            IF (ESD- SNOMLT >=  ESDMIN) THEN\n               ESD = ESD- SNOMLT\n! ----------------------------------------------------------------------\n! SNOWMELT EXCEEDS SNOW DEPTH\n! ----------------------------------------------------------------------\n            ELSE\n               EX = ESD / DT\n               FLX3 = EX *1000.0* LSUBF\n               SNOMLT = ESD\n\n               ESD = 0.0\n! ----------------------------------------------------------------------\n! END OF 'ESD .LE. ETP2' IF-BLOCK\n! ----------------------------------------------------------------------\n            END IF\n         END IF\n\n! ----------------------------------------------------------------------\n! END OF 'T12 .LE. TFREEZ' IF-BLOCK\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! IF NON-GLACIAL LAND, ADD SNOWMELT RATE (EX) TO PRECIP RATE TO BE USED\n! IN SUBROUTINE SMFLX (SOIL MOISTURE EVOLUTION) VIA INFILTRATION.\n!\n! FOR SEA-ICE AND GLACIAL-ICE, THE SNOWMELT WILL BE ADDED TO SUBSURFACE\n! RUNOFF/BASEFLOW LATER NEAR THE END OF SFLX (AFTER RETURN FROM CALL TO\n! SUBROUTINE SNOPAC)\n! ----------------------------------------------------------------------\n         IF (ICE == 0) PRCP1 = PRCP1+ EX\n\n! ----------------------------------------------------------------------\n! SET THE EFFECTIVE POTNL EVAPOTRANSP (ETP1) TO ZERO SINCE THIS IS SNOW\n! CASE, SO SURFACE EVAP NOT CALCULATED FROM EDIR, EC, OR ETT IN SMFLX\n! (BELOW).\n! IF SEAICE (ICE==1) SKIP CALL TO SMFLX.\n! SMFLX RETURNS UPDATED SOIL MOISTURE VALUES FOR NON-GLACIAL LAND.\n! IF SEA-ICE (ICE==1) OR GLACIAL-ICE (ICE==-1), SKIP CALL TO SMFLX,\n! SINCE NO SOIL MEDIUM FOR SEA-ICE OR GLACIAL-ICE.\n! ----------------------------------------------------------------------\n      END IF\n      IF (ICE == 0) THEN\n         CALL SMFLX (SMC,NSOIL,CMC,DT,PRCP1,ZSOIL,                      &\n                      SH2O,SLOPE,KDT,FRZFACT,                           &\n                      SMCMAX,BEXP,SMCWLT,DKSAT,DWSAT,                   &\n                      SHDFAC,CMCMAX,                                    &\n                      RUNOFF1,RUNOFF2,RUNOFF3,                          &\n                      EDIR1,EC1,ET1,                                    &\n                      DRIP)\n! ----------------------------------------------------------------------\n! BEFORE CALL SHFLX IN THIS SNOWPACK CASE, SET ZZ1 AND YY ARGUMENTS TO\n! SPECIAL VALUES THAT ENSURE THAT GROUND HEAT FLUX CALCULATED IN SHFLX\n! MATCHES THAT ALREADY COMPUTER FOR BELOW THE SNOWPACK, THUS THE SFC\n! HEAT FLUX TO BE COMPUTED IN SHFLX WILL EFFECTIVELY BE THE FLUX AT THE\n! SNOW TOP SURFACE.  T11 IS A DUMMY ARGUEMENT SO WE WILL NOT USE THE\n! SKIN TEMP VALUE AS REVISED BY SHFLX.\n! ----------------------------------------------------------------------\n      END IF\n      ZZ1 = 1.0\n      YY = STC (1) -0.5* SSOIL * ZSOIL (1)* ZZ1/ DF1\n\n! ----------------------------------------------------------------------\n! SHFLX WILL CALC/UPDATE THE SOIL TEMPS.  NOTE:  THE SUB-SFC HEAT FLUX\n! (SSOIL1) AND THE SKIN TEMP (T11) OUTPUT FROM THIS SHFLX CALL ARE NOT\n! USED  IN ANY SUBSEQUENT CALCULATIONS. RATHER, THEY ARE DUMMY VARIABLES\n! HERE IN THE SNOPAC CASE, SINCE THE SKIN TEMP AND SUB-SFC HEAT FLUX ARE\n! UPDATED INSTEAD NEAR THE BEGINNING OF THE CALL TO SNOPAC.\n! ----------------------------------------------------------------------\n      T11 = T1\n      CALL SHFLX (SSOIL1,STC,SMC,SMCMAX,NSOIL,T11,DT,YY,ZZ1,ZSOIL,      &\n                   TBOT,ZBOT,SMCWLT,PSISAT,SH2O,BEXP,F1,DF1,ICE,        &\n                   QUARTZ,CSOIL,VEGTYP,ISURBAN)\n\n! ----------------------------------------------------------------------\n! SNOW DEPTH AND DENSITY ADJUSTMENT BASED ON SNOW COMPACTION.  YY IS\n! ASSUMED TO BE THE SOIL TEMPERTURE AT THE TOP OF THE SOIL COLUMN.\n! ----------------------------------------------------------------------\n      IF (ICE == 0) THEN\n         ! NON-GLACIAL LAND\n         IF (ESD >  0.) THEN\n            CALL SNOWPACK (ESD,DT,SNOWH,SNDENS,T1,YY)\n         ELSE\n            ESD = 0.\n            SNOWH = 0.\n            SNDENS = 0.\n            SNCOND = 1.\n            SNCOVR = 0.\n         END IF\n      ELSEIF (ICE == 1) THEN\n         ! SEA-ICE\n         IF (ESD .GE. 0.01) THEN\n            CALL SNOWPACK (ESD,DT,SNOWH,SNDENS,T1,YY)\n        ELSE\n           ESD = 0.01\n           SNOWH = 0.05\n           !KWM???? SNDENS =\n           !KWM???? SNCOND =\n           SNCOVR = 1.0\n        ENDIF\n      ELSEIF (ICE == -1) THEN\n         ! GLACIAL-ICE\n         IF (ESD .GE. 0.10) THEN\n            CALL SNOWPACK (ESD,DT,SNOWH,SNDENS,T1,YY)\n         ELSE\n            ESD = 0.10\n            SNOWH = 0.50\n            !KWM???? SNDENS =\n            !KWM???? SNCOND =\n            SNCOVR = 1.0\n        ENDIF\n      ENDIF\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOPAC\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE SNOWPACK (ESD,DTSEC,SNOWH,SNDENS,TSNOW,TSOIL)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNOWPACK\n! ----------------------------------------------------------------------\n! CALCULATE COMPACTION OF SNOWPACK UNDER CONDITIONS OF INCREASING SNOW\n! DENSITY, AS OBTAINED FROM AN APPROXIMATE SOLUTION OF E. ANDERSON'S\n! DIFFERENTIAL EQUATION (3.29), NOAA TECHNICAL REPORT NWS 19, BY VICTOR\n! KOREN, 03/25/95.\n! ----------------------------------------------------------------------\n! ESD     WATER EQUIVALENT OF SNOW (M)\n! DTSEC   TIME STEP (SEC)\n! SNOWH   SNOW DEPTH (M)\n! SNDENS  SNOW DENSITY (G/CM3=DIMENSIONLESS FRACTION OF H2O DENSITY)\n! TSNOW   SNOW SURFACE TEMPERATURE (K)\n! TSOIL   SOIL SURFACE TEMPERATURE (K)\n\n! SUBROUTINE WILL RETURN NEW VALUES OF SNOWH AND SNDENS\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n\n      INTEGER                :: IPOL, J\n      REAL, INTENT(IN)       :: ESD, DTSEC,TSNOW,TSOIL\n      REAL, INTENT(INOUT)    :: SNOWH, SNDENS\n      REAL                   :: BFAC,DSX,DTHR,DW,SNOWHC,PEXP,           &\n                                TAVGC,TSNOWC,TSOILC,ESDC,ESDCX\n      REAL, PARAMETER        :: C1 = 0.01, C2 = 21.0, G = 9.81,         &\n                                KN = 4000.0\n! ----------------------------------------------------------------------\n! CONVERSION INTO SIMULATION UNITS\n! ----------------------------------------------------------------------\n      SNOWHC = SNOWH *100.\n      ESDC = ESD *100.\n      DTHR = DTSEC /3600.\n      TSNOWC = TSNOW -273.15\n      TSOILC = TSOIL -273.15\n\n! ----------------------------------------------------------------------\n! CALCULATING OF AVERAGE TEMPERATURE OF SNOW PACK\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! CALCULATING OF SNOW DEPTH AND DENSITY AS A RESULT OF COMPACTION\n!  SNDENS=DS0*(EXP(BFAC*ESD)-1.)/(BFAC*ESD)\n!  BFAC=DTHR*C1*EXP(0.08*TAVGC-C2*DS0)\n! NOTE: BFAC*ESD IN SNDENS EQN ABOVE HAS TO BE CAREFULLY TREATED\n! NUMERICALLY BELOW:\n!   C1 IS THE FRACTIONAL INCREASE IN DENSITY (1/(CM*HR))\n!   C2 IS A CONSTANT (CM3/G) KOJIMA ESTIMATED AS 21 CMS/G\n! ----------------------------------------------------------------------\n      TAVGC = 0.5* (TSNOWC + TSOILC)\n      IF (ESDC >  1.E-2) THEN\n         ESDCX = ESDC\n      ELSE\n         ESDCX = 1.E-2\n      END IF\n\n!      DSX = SNDENS*((DEXP(BFAC*ESDC)-1.)/(BFAC*ESDC))\n! ----------------------------------------------------------------------\n! THE FUNCTION OF THE FORM (e**x-1)/x IMBEDDED IN ABOVE EXPRESSION\n! FOR DSX WAS CAUSING NUMERICAL DIFFICULTIES WHEN THE DENOMINATOR \"x\"\n! (I.E. BFAC*ESDC) BECAME ZERO OR APPROACHED ZERO (DESPITE THE FACT THAT\n! THE ANALYTICAL FUNCTION (e**x-1)/x HAS A WELL DEFINED LIMIT AS\n! \"x\" APPROACHES ZERO), HENCE BELOW WE REPLACE THE (e**x-1)/x\n! EXPRESSION WITH AN EQUIVALENT, NUMERICALLY WELL-BEHAVED\n! POLYNOMIAL EXPANSION.\n\n! NUMBER OF TERMS OF POLYNOMIAL EXPANSION, AND HENCE ITS ACCURACY,\n! IS GOVERNED BY ITERATION LIMIT \"IPOL\".\n!      IPOL GREATER THAN 9 ONLY MAKES A DIFFERENCE ON DOUBLE\n!            PRECISION (RELATIVE ERRORS GIVEN IN PERCENT %).\n!       IPOL=9, FOR REL.ERROR <~ 1.6 E-6 % (8 SIGNIFICANT DIGITS)\n!       IPOL=8, FOR REL.ERROR <~ 1.8 E-5 % (7 SIGNIFICANT DIGITS)\n!       IPOL=7, FOR REL.ERROR <~ 1.8 E-4 % ...\n! ----------------------------------------------------------------------\n      BFAC = DTHR * C1* EXP (0.08* TAVGC - C2* SNDENS)\n      IPOL = 4\n      PEXP = 0.\n!        PEXP = (1. + PEXP)*BFAC*ESDC/REAL(J+1)\n      DO J = IPOL,1, -1\n         PEXP = (1. + PEXP)* BFAC * ESDCX / REAL (J +1)\n      END DO\n\n      PEXP = PEXP + 1.\n! ----------------------------------------------------------------------\n! ABOVE LINE ENDS POLYNOMIAL SUBSTITUTION\n! ----------------------------------------------------------------------\n!     END OF KOREAN FORMULATION\n\n!     BASE FORMULATION (COGLEY ET AL., 1990)\n!     CONVERT DENSITY FROM G/CM3 TO KG/M3\n!       DSM=SNDENS*1000.0\n\n!       DSX=DSM+DTSEC*0.5*DSM*G*ESD/\n!    &      (1E7*EXP(-0.02*DSM+KN/(TAVGC+273.16)-14.643))\n\n!  &   CONVERT DENSITY FROM KG/M3 TO G/CM3\n!       DSX=DSX/1000.0\n\n!     END OF COGLEY ET AL. FORMULATION\n\n! ----------------------------------------------------------------------\n! SET UPPER/LOWER LIMIT ON SNOW DENSITY\n! ----------------------------------------------------------------------\n      DSX = SNDENS * (PEXP)\n      IF (DSX > 0.40) DSX = 0.40\n      IF (DSX < 0.05) DSX = 0.05\n! ----------------------------------------------------------------------\n! UPDATE OF SNOW DEPTH AND DENSITY DEPENDING ON LIQUID WATER DURING\n! SNOWMELT.  ASSUMED THAT 13% OF LIQUID WATER CAN BE STORED IN SNOW PER\n! DAY DURING SNOWMELT TILL SNOW DENSITY 0.40.\n! ----------------------------------------------------------------------\n      SNDENS = DSX\n      IF (TSNOWC >=  0.) THEN\n         DW = 0.13* DTHR /24.\n         SNDENS = SNDENS * (1. - DW) + DW\n         IF (SNDENS >=  0.40) SNDENS = 0.40\n! ----------------------------------------------------------------------\n! CALCULATE SNOW DEPTH (CM) FROM SNOW WATER EQUIVALENT AND SNOW DENSITY.\n! CHANGE SNOW DEPTH UNITS TO METERS\n! ----------------------------------------------------------------------\n      END IF\n      SNOWHC = ESDC / SNDENS\n      SNOWH = SNOWHC *0.01\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOWPACK\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SNOWZ0 (SNCOVR,Z0, Z0BRD, SNOWH)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNOWZ0\n! ----------------------------------------------------------------------\n! CALCULATE TOTAL ROUGHNESS LENGTH OVER SNOW\n! SNCOVR  FRACTIONAL SNOW COVER\n! Z0      ROUGHNESS LENGTH (m)\n! Z0S     SNOW ROUGHNESS LENGTH:=0.001 (m)\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN)        :: SNCOVR, Z0BRD\n      REAL, INTENT(OUT)       :: Z0\n      REAL, PARAMETER         :: Z0S=0.001\n      REAL, INTENT(IN)        :: SNOWH\n      REAL                    :: BURIAL\n      REAL                    :: Z0EFF\n\n!m      Z0 = (1.- SNCOVR)* Z0BRD + SNCOVR * Z0S\n      BURIAL = 7.0*Z0BRD - SNOWH\n      IF(BURIAL.LE.0.0007) THEN\n        Z0EFF = Z0S\n      ELSE      \n        Z0EFF = BURIAL/7.0\n      ENDIF\n      \n      Z0 = (1.- SNCOVR)* Z0BRD + SNCOVR * Z0EFF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOWZ0\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE SNOW_NEW (TEMP,NEWSN,SNOWH,SNDENS)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SNOW_NEW\n! ----------------------------------------------------------------------\n! CALCULATE SNOW DEPTH AND DENSITITY TO ACCOUNT FOR THE NEW SNOWFALL.\n! NEW VALUES OF SNOW DEPTH & DENSITY RETURNED.\n\n! TEMP    AIR TEMPERATURE (K)\n! NEWSN   NEW SNOWFALL (M)\n! SNOWH   SNOW DEPTH (M)\n! SNDENS  SNOW DENSITY (G/CM3=DIMENSIONLESS FRACTION OF H2O DENSITY)\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN)        :: NEWSN, TEMP\n      REAL, INTENT(INOUT)     :: SNDENS, SNOWH\n      REAL                    :: DSNEW, HNEWC, SNOWHC,NEWSNC,TEMPC\n\n! ----------------------------------------------------------------------\n! CONVERSION INTO SIMULATION UNITS\n! ----------------------------------------------------------------------\n      SNOWHC = SNOWH *100.\n      NEWSNC = NEWSN *100.\n\n! ----------------------------------------------------------------------\n! CALCULATING NEW SNOWFALL DENSITY DEPENDING ON TEMPERATURE\n! EQUATION FROM GOTTLIB L. 'A GENERAL RUNOFF MODEL FOR SNOWCOVERED\n! AND GLACIERIZED BASIN', 6TH NORDIC HYDROLOGICAL CONFERENCE,\n! VEMADOLEN, SWEDEN, 1980, 172-177PP.\n!-----------------------------------------------------------------------\n      TEMPC = TEMP -273.15\n      IF (TEMPC <=  -15.) THEN\n         DSNEW = 0.05\n      ELSE\n         DSNEW = 0.05+0.0017* (TEMPC +15.)**1.5\n      END IF\n! ----------------------------------------------------------------------\n! ADJUSTMENT OF SNOW DENSITY DEPENDING ON NEW SNOWFALL\n! ----------------------------------------------------------------------\n      HNEWC = NEWSNC / DSNEW\n      IF (SNOWHC + HNEWC .LT. 1.0E-3) THEN\n         SNDENS = MAX(DSNEW,SNDENS)\n      ELSE\n         SNDENS = (SNOWHC * SNDENS + HNEWC * DSNEW)/ (SNOWHC + HNEWC)\n      ENDIF\n      SNOWHC = SNOWHC + HNEWC\n      SNOWH = SNOWHC *0.01\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOW_NEW\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SRT (RHSTT,EDIR,ET,SH2O,SH2OA,NSOIL,PCPDRP,            &\n                       ZSOIL,DWSAT,DKSAT,SMCMAX,BEXP,RUNOFF1,           &\n                       RUNOFF2,DT,SMCWLT,SLOPE,KDT,FRZX,SICE,AI,BI,CI)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SRT\n! ----------------------------------------------------------------------\n! CALCULATE THE RIGHT HAND SIDE OF THE TIME TENDENCY TERM OF THE SOIL\n! WATER DIFFUSION EQUATION.  ALSO TO COMPUTE ( PREPARE ) THE MATRIX\n! COEFFICIENTS FOR THE TRI-DIAGONAL MATRIX OF THE IMPLICIT TIME SCHEME.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)       :: NSOIL\n      INTEGER                   :: IALP1, IOHINF, J, JJ,  K, KS\n      REAL, INTENT(IN)          :: BEXP, DKSAT, DT, DWSAT, EDIR, FRZX,  &\n                                   KDT, PCPDRP, SLOPE, SMCMAX, SMCWLT\n      REAL, INTENT(OUT)         :: RUNOFF1, RUNOFF2\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: ET, SH2O, SH2OA, SICE,  &\n                                                ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)  :: RHSTT\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)  :: AI, BI, CI\n      REAL, DIMENSION(1:NSOIL)  :: DMAX\n      REAL                      :: ACRT, DD, DDT, DDZ, DDZ2, DENOM,     &\n                                   DENOM2,DICE, DSMDZ, DSMDZ2, DT1,     &\n                                   FCR,INFMAX,MXSMC,MXSMC2,NUMER,PDDUM, &\n                                   PX, SICEMAX,SLOPX, SMCAV, SSTT,      &\n                                   SUM, VAL, WCND, WCND2, WDF, WDF2\n      INTEGER, PARAMETER        :: CVFRZ = 3\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! REFERENCE FROZEN GROUND PARAMETER, CVFRZ, IS A SHAPE PARAMETER OF\n! AREAL DISTRIBUTION FUNCTION OF SOIL ICE CONTENT WHICH EQUALS 1/CV.\n! CV IS A COEFFICIENT OF SPATIAL VARIATION OF SOIL ICE CONTENT.  BASED\n! ON FIELD DATA CV DEPENDS ON AREAL MEAN OF FROZEN DEPTH, AND IT CLOSE\n! TO CONSTANT = 0.6 IF AREAL MEAN FROZEN DEPTH IS ABOVE 20 CM.  THAT IS\n! WHY PARAMETER CVFRZ = 3 (INT{1/0.6*0.6}).\n! CURRENT LOGIC DOESN'T ALLOW CVFRZ BE BIGGER THAN 3\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! DETERMINE RAINFALL INFILTRATION RATE AND RUNOFF.  INCLUDE THE\n! INFILTRATION FORMULE FROM SCHAAKE AND KOREN MODEL.\n! MODIFIED BY Q DUAN\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! LET SICEMAX BE THE GREATEST, IF ANY, FROZEN WATER CONTENT WITHIN SOIL\n! LAYERS.\n! ----------------------------------------------------------------------\n      IOHINF = 1\n      SICEMAX = 0.0\n      DO KS = 1,NSOIL\n         IF (SICE (KS) >  SICEMAX) SICEMAX = SICE (KS)\n! ----------------------------------------------------------------------\n! DETERMINE RAINFALL INFILTRATION RATE AND RUNOFF\n! ----------------------------------------------------------------------\n      END DO\n      PDDUM = PCPDRP\n      RUNOFF1 = 0.0\n\n! ----------------------------------------------------------------------\n! MODIFIED BY Q. DUAN, 5/16/94\n! ----------------------------------------------------------------------\n!        IF (IOHINF == 1) THEN\n\n      IF (PCPDRP /=  0.0) THEN\n         DT1 = DT /86400.\n         SMCAV = SMCMAX - SMCWLT\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! ----------------------------------------------------------------------\n         DMAX (1)= - ZSOIL (1)* SMCAV\n\n         DICE = - ZSOIL (1) * SICE (1)\n         DMAX (1)= DMAX (1)* (1.0- (SH2OA (1) + SICE (1) - SMCWLT)/      &\n                    SMCAV)\n\n         DD = DMAX (1)\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! ----------------------------------------------------------------------\n         DO KS = 2,NSOIL\n\n            DICE = DICE+ ( ZSOIL (KS -1) - ZSOIL (KS) ) * SICE (KS)\n            DMAX (KS) = (ZSOIL (KS -1) - ZSOIL (KS))* SMCAV\n            DMAX (KS) = DMAX (KS)* (1.0- (SH2OA (KS) + SICE (KS)        &\n                        - SMCWLT)/ SMCAV)\n            DD = DD+ DMAX (KS)\n! ----------------------------------------------------------------------\n! VAL = (1.-EXP(-KDT*SQRT(DT1)))\n! IN BELOW, REMOVE THE SQRT IN ABOVE\n! ----------------------------------------------------------------------\n         END DO\n         VAL = (1. - EXP ( - KDT * DT1))\n         DDT = DD * VAL\n         PX = PCPDRP * DT\n         IF (PX <  0.0) PX = 0.0\n\n! ----------------------------------------------------------------------\n! FROZEN GROUND VERSION:\n! REDUCTION OF INFILTRATION BASED ON FROZEN GROUND PARAMETERS\n! ----------------------------------------------------------------------\n         INFMAX = (PX * (DDT / (PX + DDT)))/ DT\n         FCR = 1.\n         IF (DICE >  1.E-2) THEN\n            ACRT = CVFRZ * FRZX / DICE\n            SUM = 1.\n            IALP1 = CVFRZ - 1\n            DO J = 1,IALP1\n               K = 1\n               DO JJ = J +1,IALP1\n                  K = K * JJ\n               END DO\n               SUM = SUM + (ACRT ** ( CVFRZ - J)) / FLOAT (K)\n            END DO\n            FCR = 1. - EXP ( - ACRT) * SUM\n         END IF\n\n! ----------------------------------------------------------------------\n! CORRECTION OF INFILTRATION LIMITATION:\n! IF INFMAX .LE. HYDROLIC CONDUCTIVITY ASSIGN INFMAX THE VALUE OF\n! HYDROLIC CONDUCTIVITY\n! ----------------------------------------------------------------------\n!         MXSMC = MAX ( SH2OA(1), SH2OA(2) )\n         INFMAX = INFMAX * FCR\n\n         MXSMC = SH2OA (1)\n         CALL WDFCND (WDF,WCND,MXSMC,SMCMAX,BEXP,DKSAT,DWSAT,           &\n                         SICEMAX)\n         INFMAX = MAX (INFMAX,WCND)\n\n         INFMAX = MIN (INFMAX,PX/DT)\n         IF (PCPDRP >  INFMAX) THEN\n            RUNOFF1 = PCPDRP - INFMAX\n            PDDUM = INFMAX\n         END IF\n! ----------------------------------------------------------------------\n! TO AVOID SPURIOUS DRAINAGE BEHAVIOR, 'UPSTREAM DIFFERENCING' IN LINE\n! BELOW REPLACED WITH NEW APPROACH IN 2ND LINE:\n! 'MXSMC = MAX(SH2OA(1), SH2OA(2))'\n! ----------------------------------------------------------------------\n      END IF\n\n      MXSMC = SH2OA (1)\n      CALL WDFCND (WDF,WCND,MXSMC,SMCMAX,BEXP,DKSAT,DWSAT,              &\n                    SICEMAX)\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEFFICIENTS AI, BI, AND CI FOR THE TOP LAYER\n! ----------------------------------------------------------------------\n      DDZ = 1. / ( - .5 * ZSOIL (2) )\n      AI (1) = 0.0\n      BI (1) = WDF * DDZ / ( - ZSOIL (1) )\n\n! ----------------------------------------------------------------------\n! CALC RHSTT FOR THE TOP LAYER AFTER CALC'NG THE VERTICAL SOIL MOISTURE\n! GRADIENT BTWN THE TOP AND NEXT TO TOP LAYERS.\n! ----------------------------------------------------------------------\n      CI (1) = - BI (1)\n      DSMDZ = ( SH2O (1) - SH2O (2) ) / ( - .5 * ZSOIL (2) )\n      RHSTT (1) = (WDF * DSMDZ + WCND- PDDUM + EDIR + ET (1))/ ZSOIL (1)\n\n! ----------------------------------------------------------------------\n! INITIALIZE DDZ2\n! ----------------------------------------------------------------------\n      SSTT = WDF * DSMDZ + WCND+ EDIR + ET (1)\n\n! ----------------------------------------------------------------------\n! LOOP THRU THE REMAINING SOIL LAYERS, REPEATING THE ABV PROCESS\n! ----------------------------------------------------------------------\n      DDZ2 = 0.0\n      DO K = 2,NSOIL\n         DENOM2 = (ZSOIL (K -1) - ZSOIL (K))\n         IF (K /= NSOIL) THEN\n\n! ----------------------------------------------------------------------\n! AGAIN, TO AVOID SPURIOUS DRAINAGE BEHAVIOR, 'UPSTREAM DIFFERENCING' IN\n! LINE BELOW REPLACED WITH NEW APPROACH IN 2ND LINE:\n! 'MXSMC2 = MAX (SH2OA(K), SH2OA(K+1))'\n! ----------------------------------------------------------------------\n            SLOPX = 1.\n\n            MXSMC2 = SH2OA (K)\n            CALL WDFCND (WDF2,WCND2,MXSMC2,SMCMAX,BEXP,DKSAT,DWSAT,     &\n                          SICEMAX)\n! -----------------------------------------------------------------------\n! CALC SOME PARTIAL PRODUCTS FOR LATER USE IN CALC'NG RHSTT\n! ----------------------------------------------------------------------\n            DENOM = (ZSOIL (K -1) - ZSOIL (K +1))\n\n! ----------------------------------------------------------------------\n! CALC THE MATRIX COEF, CI, AFTER CALC'NG ITS PARTIAL PRODUCT\n! ----------------------------------------------------------------------\n            DSMDZ2 = (SH2O (K) - SH2O (K +1)) / (DENOM * 0.5)\n            DDZ2 = 2.0 / DENOM\n            CI (K) = - WDF2 * DDZ2 / DENOM2\n\n         ELSE\n! ----------------------------------------------------------------------\n! SLOPE OF BOTTOM LAYER IS INTRODUCED\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! RETRIEVE THE SOIL WATER DIFFUSIVITY AND HYDRAULIC CONDUCTIVITY FOR\n! THIS LAYER\n! ----------------------------------------------------------------------\n            SLOPX = SLOPE\n          CALL WDFCND (WDF2,WCND2,SH2OA (NSOIL),SMCMAX,BEXP,DKSAT,DWSAT,     &\n                            SICEMAX)\n\n! ----------------------------------------------------------------------\n! CALC A PARTIAL PRODUCT FOR LATER USE IN CALC'NG RHSTT\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------\n! SET MATRIX COEF CI TO ZERO\n! ----------------------------------------------------------------------\n            DSMDZ2 = 0.0\n            CI (K) = 0.0\n! ----------------------------------------------------------------------\n! CALC RHSTT FOR THIS LAYER AFTER CALC'NG ITS NUMERATOR\n! ----------------------------------------------------------------------\n         END IF\n         NUMER = (WDF2 * DSMDZ2) + SLOPX * WCND2- (WDF * DSMDZ)         &\n                 - WCND+ ET (K)\n\n! ----------------------------------------------------------------------\n! CALC MATRIX COEFS, AI, AND BI FOR THIS LAYER\n! ----------------------------------------------------------------------\n         RHSTT (K) = NUMER / ( - DENOM2)\n         AI (K) = - WDF * DDZ / DENOM2\n\n! ----------------------------------------------------------------------\n! RESET VALUES OF WDF, WCND, DSMDZ, AND DDZ FOR LOOP TO NEXT LYR\n! RUNOFF2:  SUB-SURFACE OR BASEFLOW RUNOFF\n! ----------------------------------------------------------------------\n         BI (K) = - ( AI (K) + CI (K) )\n         IF (K .eq. NSOIL) THEN\n            RUNOFF2 = SLOPX * WCND2\n         END IF\n         IF (K .ne. NSOIL) THEN\n            WDF = WDF2\n            WCND = WCND2\n            DSMDZ = DSMDZ2\n            DDZ = DDZ2\n         END IF\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE SRT\n! ----------------------------------------------------------------------\n\n      SUBROUTINE SSTEP (SH2OOUT,SH2OIN,CMC,RHSTT,RHSCT,DT,              &\n                        NSOIL,SMCMAX,CMCMAX,RUNOFF3,ZSOIL,SMC,SICE,     &\n                        AI,BI,CI)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SSTEP\n! ----------------------------------------------------------------------\n! CALCULATE/UPDATE SOIL MOISTURE CONTENT VALUES AND CANOPY MOISTURE\n! CONTENT VALUES.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)       :: NSOIL\n      INTEGER                   :: I, K, KK11\n\n      REAL, INTENT(IN)          :: CMCMAX, DT, SMCMAX\n      REAL, INTENT(OUT)         :: RUNOFF3\n      REAL, INTENT(INOUT)       :: CMC\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)     :: SH2OIN, SICE, ZSOIL\n      REAL, DIMENSION(1:NSOIL), INTENT(OUT)    :: SH2OOUT\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT)  :: RHSTT, SMC\n      REAL, DIMENSION(1:NSOIL), INTENT(INOUT)  :: AI, BI, CI\n      REAL, DIMENSION(1:NSOIL)  :: RHSTTin\n      REAL, DIMENSION(1:NSOIL)  :: CIin\n      REAL                      :: DDZ, RHSCT, STOT, WPLUS\n\n! ----------------------------------------------------------------------\n! CREATE 'AMOUNT' VALUES OF VARIABLES TO BE INPUT TO THE\n! TRI-DIAGONAL MATRIX ROUTINE.\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         RHSTT (K) = RHSTT (K) * DT\n         AI (K) = AI (K) * DT\n         BI (K) = 1. + BI (K) * DT\n         CI (K) = CI (K) * DT\n      END DO\n! ----------------------------------------------------------------------\n! COPY VALUES FOR INPUT VARIABLES BEFORE CALL TO ROSR12\n! ----------------------------------------------------------------------\n      DO K = 1,NSOIL\n         RHSTTin (K) = RHSTT (K)\n      END DO\n      DO K = 1,NSOIL\n         CIin (K) = CI (K)\n      END DO\n! ----------------------------------------------------------------------\n! CALL ROSR12 TO SOLVE THE TRI-DIAGONAL MATRIX\n! ----------------------------------------------------------------------\n      CALL ROSR12 (CI,AI,BI,CIin,RHSTTin,RHSTT,NSOIL)\n! ----------------------------------------------------------------------\n! SUM THE PREVIOUS SMC VALUE AND THE MATRIX SOLUTION TO GET A\n! NEW VALUE.  MIN ALLOWABLE VALUE OF SMC WILL BE 0.02.\n! RUNOFF3: RUNOFF WITHIN SOIL LAYERS\n! ----------------------------------------------------------------------\n      WPLUS = 0.0\n      RUNOFF3 = 0.\n\n      DDZ = - ZSOIL (1)\n      DO K = 1,NSOIL\n         IF (K /= 1) DDZ = ZSOIL (K - 1) - ZSOIL (K)\n         SH2OOUT (K) = SH2OIN (K) + CI (K) + WPLUS / DDZ\n         STOT = SH2OOUT (K) + SICE (K)\n         IF (STOT > SMCMAX) THEN\n            IF (K .eq. 1) THEN\n               DDZ = - ZSOIL (1)\n            ELSE\n               KK11 = K - 1\n               DDZ = - ZSOIL (K) + ZSOIL (KK11)\n            END IF\n            WPLUS = (STOT - SMCMAX) * DDZ\n         ELSE\n            WPLUS = 0.\n         END IF\n         SMC (K) = MAX ( MIN (STOT,SMCMAX),0.02 )\n         SH2OOUT (K) = MAX ( (SMC (K) - SICE (K)),0.0)\n      END DO\n\n! ----------------------------------------------------------------------\n! UPDATE CANOPY WATER CONTENT/INTERCEPTION (CMC).  CONVERT RHSCT TO\n! AN 'AMOUNT' VALUE AND ADD TO PREVIOUS CMC VALUE TO GET NEW CMC.\n! ----------------------------------------------------------------------\n      RUNOFF3 = WPLUS\n      CMC = CMC + DT * RHSCT\n      IF (CMC < 1.E-20) CMC = 0.0\n      CMC = MIN (CMC,CMCMAX)\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SSTEP\n! ----------------------------------------------------------------------\n\n      SUBROUTINE TBND (TU,TB,ZSOIL,ZBOT,K,NSOIL,TBND1)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE TBND\n! ----------------------------------------------------------------------\n! CALCULATE TEMPERATURE ON THE BOUNDARY OF THE LAYER BY INTERPOLATION OF\n! THE MIDDLE LAYER TEMPERATURES\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER, INTENT(IN)       :: NSOIL\n      INTEGER                   :: K\n      REAL, INTENT(IN)          :: TB, TU, ZBOT\n      REAL, INTENT(OUT)         :: TBND1\n      REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: ZSOIL\n      REAL                      :: ZB, ZUP\n      REAL, PARAMETER           :: T0 = 273.15\n\n! ----------------------------------------------------------------------\n! USE SURFACE TEMPERATURE ON THE TOP OF THE FIRST LAYER\n! ----------------------------------------------------------------------\n     IF (K == 1) THEN\n         ZUP = 0.\n      ELSE\n         ZUP = ZSOIL (K -1)\n      END IF\n! ----------------------------------------------------------------------\n! USE DEPTH OF THE CONSTANT BOTTOM TEMPERATURE WHEN INTERPOLATE\n! TEMPERATURE INTO THE LAST LAYER BOUNDARY\n! ----------------------------------------------------------------------\n      IF (K ==  NSOIL) THEN\n         ZB = 2.* ZBOT - ZSOIL (K)\n      ELSE\n         ZB = ZSOIL (K +1)\n      END IF\n! ----------------------------------------------------------------------\n! LINEAR INTERPOLATION BETWEEN THE AVERAGE LAYER TEMPERATURES\n! ----------------------------------------------------------------------\n\n      TBND1 = TU + (TB - TU)* (ZUP - ZSOIL (K))/ (ZUP - ZB)\n! ----------------------------------------------------------------------\n  END SUBROUTINE TBND\n! ----------------------------------------------------------------------\n\n\n      SUBROUTINE TDFCND ( DF, SMC, QZ, SMCMAX, SH2O)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE TDFCND\n! ----------------------------------------------------------------------\n! CALCULATE THERMAL DIFFUSIVITY AND CONDUCTIVITY OF THE SOIL FOR A GIVEN\n! POINT AND TIME.\n! ----------------------------------------------------------------------\n! PETERS-LIDARD APPROACH (PETERS-LIDARD et al., 1998)\n! June 2001 CHANGES: FROZEN SOIL CONDITION.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL, INTENT(IN)          :: QZ,  SMC, SMCMAX, SH2O\n      REAL, INTENT(OUT)         :: DF\n      REAL                      :: AKE, GAMMD, THKDRY, THKICE, THKO,    &\n                                   THKQTZ,THKSAT,THKS,THKW,SATRATIO,XU, &\n                                   XUNFROZ\n\n! ----------------------------------------------------------------------\n! WE NOW GET QUARTZ AS AN INPUT ARGUMENT (SET IN ROUTINE REDPRM):\n!      DATA QUARTZ /0.82, 0.10, 0.25, 0.60, 0.52,\n!     &             0.35, 0.60, 0.40, 0.82/\n! ----------------------------------------------------------------------\n! IF THE SOIL HAS ANY MOISTURE CONTENT COMPUTE A PARTIAL SUM/PRODUCT\n! OTHERWISE USE A CONSTANT VALUE WHICH WORKS WELL WITH MOST SOILS\n! ----------------------------------------------------------------------\n!  THKW ......WATER THERMAL CONDUCTIVITY\n!  THKQTZ ....THERMAL CONDUCTIVITY FOR QUARTZ\n!  THKO ......THERMAL CONDUCTIVITY FOR OTHER SOIL COMPONENTS\n!  THKS ......THERMAL CONDUCTIVITY FOR THE SOLIDS COMBINED(QUARTZ+OTHER)\n!  THKICE ....ICE THERMAL CONDUCTIVITY\n!  SMCMAX ....POROSITY (= SMCMAX)\n!  QZ .........QUARTZ CONTENT (SOIL TYPE DEPENDENT)\n! ----------------------------------------------------------------------\n! USE AS IN PETERS-LIDARD, 1998 (MODIF. FROM JOHANSEN, 1975).\n\n!                                  PABLO GRUNMANN, 08/17/98\n! REFS.:\n!      FAROUKI, O.T.,1986: THERMAL PROPERTIES OF SOILS. SERIES ON ROCK\n!              AND SOIL MECHANICS, VOL. 11, TRANS TECH, 136 PP.\n!      JOHANSEN, O., 1975: THERMAL CONDUCTIVITY OF SOILS. PH.D. THESIS,\n!              UNIVERSITY OF TRONDHEIM,\n!      PETERS-LIDARD, C. D., ET AL., 1998: THE EFFECT OF SOIL THERMAL\n!              CONDUCTIVITY PARAMETERIZATION ON SURFACE ENERGY FLUXES\n!              AND TEMPERATURES. JOURNAL OF THE ATMOSPHERIC SCIENCES,\n!              VOL. 55, PP. 1209-1224.\n! ----------------------------------------------------------------------\n! NEEDS PARAMETERS\n! POROSITY(SOIL TYPE):\n!      POROS = SMCMAX\n! SATURATION RATIO:\n! PARAMETERS  W/(M.K)\n      SATRATIO = SMC / SMCMAX\n! ICE CONDUCTIVITY:\n      THKICE = 2.2\n! WATER CONDUCTIVITY:\n      THKW = 0.57\n! THERMAL CONDUCTIVITY OF \"OTHER\" SOIL COMPONENTS\n!      IF (QZ .LE. 0.2) THKO = 3.0\n      THKO = 2.0\n! QUARTZ' CONDUCTIVITY\n      THKQTZ = 7.7\n! SOLIDS' CONDUCTIVITY\n      THKS = (THKQTZ ** QZ)* (THKO ** (1. - QZ))\n\n! UNFROZEN FRACTION (FROM 1., i.e., 100%LIQUID, TO 0. (100% FROZEN))\n      XUNFROZ = SH2O / SMC\n! UNFROZEN VOLUME FOR SATURATION (POROSITY*XUNFROZ)\n      XU = XUNFROZ * SMCMAX\n\n! SATURATED THERMAL CONDUCTIVITY\n      THKSAT = THKS ** (1. - SMCMAX)* THKICE ** (SMCMAX - XU)* THKW **   &\n         (XU)\n\n! DRY DENSITY IN KG/M3\n      GAMMD = (1. - SMCMAX)*2700.\n\n! DRY THERMAL CONDUCTIVITY IN W.M-1.K-1\n      THKDRY = (0.135* GAMMD+ 64.7)/ (2700. - 0.947* GAMMD)\n! FROZEN\n      IF ( (SH2O + 0.0005) <  SMC ) THEN\n         AKE = SATRATIO\n! UNFROZEN\n! RANGE OF VALIDITY FOR THE KERSTEN NUMBER (AKE)\n      ELSE\n\n! KERSTEN NUMBER (USING \"FINE\" FORMULA, VALID FOR SOILS CONTAINING AT\n! LEAST 5% OF PARTICLES WITH DIAMETER LESS THAN 2.E-6 METERS.)\n! (FOR \"COARSE\" FORMULA, SEE PETERS-LIDARD ET AL., 1998).\n\n         IF ( SATRATIO >  0.1 ) THEN\n\n            AKE = LOG10 (SATRATIO) + 1.0\n\n! USE K = KDRY\n         ELSE\n\n            AKE = 0.0\n         END IF\n!  THERMAL CONDUCTIVITY\n\n      END IF\n\n      DF = AKE * (THKSAT - THKDRY) + THKDRY\n! ----------------------------------------------------------------------\n  END SUBROUTINE TDFCND\n! ----------------------------------------------------------------------\n\n      SUBROUTINE TMPAVG (TAVG,TUP,TM,TDN,ZSOIL,NSOIL,K)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE TMPAVG\n! ----------------------------------------------------------------------\n! CALCULATE SOIL LAYER AVERAGE TEMPERATURE (TAVG) IN FREEZING/THAWING\n! LAYER USING UP, DOWN, AND MIDDLE LAYER TEMPERATURES (TUP, TDN, TM),\n! WHERE TUP IS AT TOP BOUNDARY OF LAYER, TDN IS AT BOTTOM BOUNDARY OF\n! LAYER.  TM IS LAYER PROGNOSTIC STATE TEMPERATURE.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER  K\n\n      INTEGER  NSOIL\n      REAL     DZ\n      REAL     DZH\n      REAL     T0\n      REAL     TAVG\n      REAL     TDN\n      REAL     TM\n      REAL     TUP\n      REAL     X0\n      REAL     XDN\n      REAL     XUP\n\n      REAL     ZSOIL (NSOIL)\n\n! ----------------------------------------------------------------------\n      PARAMETER (T0 = 2.7315E2)\n      IF (K .eq. 1) THEN\n         DZ = - ZSOIL (1)\n      ELSE\n         DZ = ZSOIL (K -1) - ZSOIL (K)\n      END IF\n\n      DZH = DZ *0.5\n      IF (TUP .lt. T0) THEN\n         IF (TM .lt. T0) THEN\n! ----------------------------------------------------------------------\n! TUP, TM, TDN < T0\n! ----------------------------------------------------------------------\n            IF (TDN .lt. T0) THEN\n               TAVG = (TUP + 2.0* TM + TDN)/ 4.0\n! ----------------------------------------------------------------------\n! TUP & TM < T0,  TDN .ge. T0\n! ----------------------------------------------------------------------\n            ELSE\n               X0 = (T0- TM) * DZH / (TDN - TM)\n               TAVG = 0.5 * (TUP * DZH + TM * (DZH + X0) + T0* (        &\n     &               2.* DZH - X0)) / DZ\n            END IF\n         ELSE\n! ----------------------------------------------------------------------\n! TUP < T0, TM .ge. T0, TDN < T0\n! ----------------------------------------------------------------------\n            IF (TDN .lt. T0) THEN\n               XUP = (T0- TUP) * DZH / (TM - TUP)\n               XDN = DZH - (T0- TM) * DZH / (TDN - TM)\n               TAVG = 0.5 * (TUP * XUP + T0* (2.* DZ - XUP - XDN)       &\n     &                + TDN * XDN) / DZ\n! ----------------------------------------------------------------------\n! TUP < T0, TM .ge. T0, TDN .ge. T0\n! ----------------------------------------------------------------------\n            ELSE\n               XUP = (T0- TUP) * DZH / (TM - TUP)\n               TAVG = 0.5 * (TUP * XUP + T0* (2.* DZ - XUP)) / DZ\n            END IF\n         END IF\n      ELSE\n         IF (TM .lt. T0) THEN\n! ----------------------------------------------------------------------\n! TUP .ge. T0, TM < T0, TDN < T0\n! ----------------------------------------------------------------------\n            IF (TDN .lt. T0) THEN\n               XUP = DZH - (T0- TUP) * DZH / (TM - TUP)\n               TAVG = 0.5 * (T0* (DZ - XUP) + TM * (DZH + XUP)          &\n     &                + TDN * DZH) / DZ\n! ----------------------------------------------------------------------\n! TUP .ge. T0, TM < T0, TDN .ge. T0\n! ----------------------------------------------------------------------\n            ELSE\n               XUP = DZH - (T0- TUP) * DZH / (TM - TUP)\n               XDN = (T0- TM) * DZH / (TDN - TM)\n               TAVG = 0.5 * (T0* (2.* DZ - XUP - XDN) + TM *            &\n     & (XUP + XDN)) / DZ\n            END IF\n         ELSE\n! ----------------------------------------------------------------------\n! TUP .ge. T0, TM .ge. T0, TDN < T0\n! ----------------------------------------------------------------------\n            IF (TDN .lt. T0) THEN\n               XDN = DZH - (T0- TM) * DZH / (TDN - TM)\n               TAVG = (T0* (DZ - XDN) +0.5* (T0+ TDN)* XDN) / DZ\n! ----------------------------------------------------------------------\n! TUP .ge. T0, TM .ge. T0, TDN .ge. T0\n! ----------------------------------------------------------------------\n            ELSE\n               TAVG = (TUP + 2.0* TM + TDN) / 4.0\n            END IF\n         END IF\n      END IF\n! ----------------------------------------------------------------------\n  END SUBROUTINE TMPAVG\n! ----------------------------------------------------------------------\n\n      SUBROUTINE TRANSP (ET,NSOIL,ETP1,SMC,CMC,ZSOIL,SHDFAC,SMCWLT,     &\n     &                      CMCMAX,PC,CFACTR,SMCREF,SFCTMP,Q2,NROOT,    &\n     &                      RTDIS)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE TRANSP\n! ----------------------------------------------------------------------\n! CALCULATE TRANSPIRATION FOR THE VEG CLASS.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      INTEGER  I\n      INTEGER  K\n      INTEGER  NSOIL\n\n      INTEGER  NROOT\n      REAL     CFACTR\n      REAL     CMC\n      REAL     CMCMAX\n      REAL     DENOM\n      REAL     ET (NSOIL)\n      REAL     ETP1\n      REAL     ETP1A\n!.....REAL PART(NSOIL)\n      REAL     GX (NROOT)\n      REAL     PC\n      REAL     Q2\n      REAL     RTDIS (NSOIL)\n      REAL     RTX\n      REAL     SFCTMP\n      REAL     SGX\n      REAL     SHDFAC\n      REAL     SMC (NSOIL)\n      REAL     SMCREF\n      REAL     SMCWLT\n\n! ----------------------------------------------------------------------\n! INITIALIZE PLANT TRANSP TO ZERO FOR ALL SOIL LAYERS.\n! ----------------------------------------------------------------------\n      REAL     ZSOIL (NSOIL)\n      DO K = 1,NSOIL\n         ET (K) = 0.\n! ----------------------------------------------------------------------\n! CALCULATE AN 'ADJUSTED' POTENTIAL TRANSPIRATION\n! IF STATEMENT BELOW TO AVOID TANGENT LINEAR PROBLEMS NEAR ZERO\n! NOTE: GX AND OTHER TERMS BELOW REDISTRIBUTE TRANSPIRATION BY LAYER,\n! ET(K), AS A FUNCTION OF SOIL MOISTURE AVAILABILITY, WHILE PRESERVING\n! TOTAL ETP1A.\n! ----------------------------------------------------------------------\n      END DO\n      IF (CMC .ne. 0.0) THEN\n         ETP1A = SHDFAC * PC * ETP1 * (1.0- (CMC / CMCMAX) ** CFACTR)\n      ELSE\n         ETP1A = SHDFAC * PC * ETP1\n      END IF\n      SGX = 0.0\n      DO I = 1,NROOT\n         GX (I) = ( SMC (I) - SMCWLT ) / ( SMCREF - SMCWLT )\n         GX (I) = MAX ( MIN ( GX (I), 1. ), 0. )\n         SGX = SGX + GX (I)\n      END DO\n\n      SGX = SGX / NROOT\n      DENOM = 0.\n      DO I = 1,NROOT\n         RTX = RTDIS (I) + GX (I) - SGX\n         GX (I) = GX (I) * MAX ( RTX, 0. )\n         DENOM = DENOM + GX (I)\n      END DO\n\n      IF (DENOM .le. 0.0) DENOM = 1.\n      DO I = 1,NROOT\n         ET (I) = ETP1A * GX (I) / DENOM\n! ----------------------------------------------------------------------\n! ABOVE CODE ASSUMES A VERTICALLY UNIFORM ROOT DISTRIBUTION\n! CODE BELOW TESTS A VARIABLE ROOT DISTRIBUTION\n! ----------------------------------------------------------------------\n!      ET(1) = ( ZSOIL(1) / ZSOIL(NROOT) ) * GX * ETP1A\n!      ET(1) = ( ZSOIL(1) / ZSOIL(NROOT) ) * ETP1A\n! ----------------------------------------------------------------------\n! USING ROOT DISTRIBUTION AS WEIGHTING FACTOR\n! ----------------------------------------------------------------------\n!      ET(1) = RTDIS(1) * ETP1A\n!      ET(1) = ETP1A * PART(1)\n! ----------------------------------------------------------------------\n! LOOP DOWN THRU THE SOIL LAYERS REPEATING THE OPERATION ABOVE,\n! BUT USING THE THICKNESS OF THE SOIL LAYER (RATHER THAN THE\n! ABSOLUTE DEPTH OF EACH LAYER) IN THE FINAL CALCULATION.\n! ----------------------------------------------------------------------\n!      DO K = 2,NROOT\n!        GX = ( SMC(K) - SMCWLT ) / ( SMCREF - SMCWLT )\n!        GX = MAX ( MIN ( GX, 1. ), 0. )\n! TEST CANOPY RESISTANCE\n!        GX = 1.0\n!        ET(K) = ((ZSOIL(K)-ZSOIL(K-1))/ZSOIL(NROOT))*GX*ETP1A\n!        ET(K) = ((ZSOIL(K)-ZSOIL(K-1))/ZSOIL(NROOT))*ETP1A\n! ----------------------------------------------------------------------\n! USING ROOT DISTRIBUTION AS WEIGHTING FACTOR\n! ----------------------------------------------------------------------\n!        ET(K) = RTDIS(K) * ETP1A\n!        ET(K) = ETP1A*PART(K)\n!      END DO\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE TRANSP\n! ----------------------------------------------------------------------\n\n      SUBROUTINE WDFCND (WDF,WCND,SMC,SMCMAX,BEXP,DKSAT,DWSAT,          &\n     &                      SICEMAX)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE WDFCND\n! ----------------------------------------------------------------------\n! CALCULATE SOIL WATER DIFFUSIVITY AND SOIL HYDRAULIC CONDUCTIVITY.\n! ----------------------------------------------------------------------\n      IMPLICIT NONE\n      REAL     BEXP\n      REAL     DKSAT\n      REAL     DWSAT\n      REAL     EXPON\n      REAL     FACTR1\n      REAL     FACTR2\n      REAL     SICEMAX\n      REAL     SMC\n      REAL     SMCMAX\n      REAL     VKwgt\n      REAL     WCND\n\n! ----------------------------------------------------------------------\n!     CALC THE RATIO OF THE ACTUAL TO THE MAX PSBL SOIL H2O CONTENT\n! ----------------------------------------------------------------------\n      REAL     WDF\n      FACTR1 = 0.05 / SMCMAX\n\n! ----------------------------------------------------------------------\n! PREP AN EXPNTL COEF AND CALC THE SOIL WATER DIFFUSIVITY\n! ----------------------------------------------------------------------\n      FACTR2 = SMC / SMCMAX\n      FACTR1 = MIN(FACTR1,FACTR2)\n      EXPON = BEXP + 2.0\n\n! ----------------------------------------------------------------------\n! FROZEN SOIL HYDRAULIC DIFFUSIVITY.  VERY SENSITIVE TO THE VERTICAL\n! GRADIENT OF UNFROZEN WATER. THE LATTER GRADIENT CAN BECOME VERY\n! EXTREME IN FREEZING/THAWING SITUATIONS, AND GIVEN THE RELATIVELY\n! FEW AND THICK SOIL LAYERS, THIS GRADIENT SUFFERES SERIOUS\n! TRUNCTION ERRORS YIELDING ERRONEOUSLY HIGH VERTICAL TRANSPORTS OF\n! UNFROZEN WATER IN BOTH DIRECTIONS FROM HUGE HYDRAULIC DIFFUSIVITY.\n! THEREFORE, WE FOUND WE HAD TO ARBITRARILY CONSTRAIN WDF\n! --\n! VERSION D_10CM: ........  FACTR1 = 0.2/SMCMAX\n! WEIGHTED APPROACH...................... PABLO GRUNMANN, 28_SEP_1999.\n! ----------------------------------------------------------------------\n      WDF = DWSAT * FACTR2 ** EXPON\n      IF (SICEMAX .gt. 0.0) THEN\n         VKWGT = 1./ (1. + (500.* SICEMAX)**3.)\n         WDF = VKWGT * WDF + (1. - VKWGT)* DWSAT * FACTR1** EXPON\n! ----------------------------------------------------------------------\n! RESET THE EXPNTL COEF AND CALC THE HYDRAULIC CONDUCTIVITY\n! ----------------------------------------------------------------------\n      END IF\n      EXPON = (2.0 * BEXP) + 3.0\n      WCND = DKSAT * FACTR2 ** EXPON\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE WDFCND\n! ----------------------------------------------------------------------\n\n#ifdef _HRLDAS_OFFLINE_\n      SUBROUTINE SFCDIF_off (ZLM,ZLM_WIND,Z0,THZ0,THLM,SFCSPD,CZIL,AKMS,AKHS, &\n           VEGTYP, ISURBAN, IZ0TLND )\n#else\n      SUBROUTINE SFCDIF_off (ZLM,Z0,THZ0,THLM,SFCSPD,CZIL,AKMS,AKHS)\n#endif\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SFCDIF (renamed SFCDIF_off to avoid clash with Eta PBL)\n! ----------------------------------------------------------------------\n! CALCULATE SURFACE LAYER EXCHANGE COEFFICIENTS VIA ITERATIVE PROCESS.\n! SEE CHEN ET AL (1997, BLM)\n! ----------------------------------------------------------------------\n\n      IMPLICIT NONE\n#ifdef _HRLDAS_OFFLINE_\n      INTEGER, INTENT(IN) :: VEGTYP\n      INTEGER, INTENT(IN) :: ISURBAN\n      INTEGER, INTENT(IN) :: IZ0TLND\n      REAL,    INTENT(IN) :: ZLM_WIND\n#endif\n      REAL     WWST, WWST2, G, VKRM, EXCM, BETA, BTG, ELFC, WOLD, WNEW\n      REAL     PIHF, EPSU2, EPSUST, EPSIT, EPSA, ZTMIN, ZTMAX, HPBL,     &\n     & SQVISC\n      REAL     RIC, RRIC, FHNEU, RFC, RFAC, ZZ, PSLMU, PSLMS, PSLHU,     &\n     & PSLHS\n      REAL     XX, PSPMU, YY, PSPMS, PSPHU, PSPHS, ZLM, Z0, THZ0, THLM\n      REAL     SFCSPD, CZIL, AKMS, AKHS, ZILFC, ZU, ZT, RDZ, CXCH\n      REAL     DTHV, DU2, BTGH, WSTAR2, USTAR, ZSLU, ZSLT, RLOGU, RLOGT\n      REAL     RLMO, ZETALT, ZETALU, ZETAU, ZETAT, XLU4, XLT4, XU4, XT4\n!CC   ......REAL ZTFC\n\n      REAL     XLU, XLT, XU, XT, PSMZ, SIMM, PSHZ, SIMH, USTARK, RLMN,  &\n     &         RLMA\n\n      INTEGER  ITRMX, ILECH, ITR\n      PARAMETER                                                         &\n     &        (WWST = 1.2,WWST2 = WWST * WWST,G = 9.8,VKRM = 0.40,      &\n     &         EXCM = 0.001                                             &\n     &        ,BETA = 1./270.,BTG = BETA * G,ELFC = VKRM * BTG          &\n     &                  ,WOLD =.15,WNEW = 1. - WOLD,ITRMX = 05,         &\n     &                   PIHF = 3.14159265/2.)\n      PARAMETER                                                         &\n     &         (EPSU2 = 1.E-4,EPSUST = 0.07,EPSIT = 1.E-4,EPSA = 1.E-8  &\n     &         ,ZTMIN = -5.,ZTMAX = 1.,HPBL = 1000.0                    &\n     &          ,SQVISC = 258.2)\n      PARAMETER                                                         &\n     &       (RIC = 0.183,RRIC = 1.0/ RIC,FHNEU = 0.8,RFC = 0.191       &\n     &        ,RFAC = RIC / (FHNEU * RFC * RFC))\n\n! ----------------------------------------------------------------------\n! NOTE: THE TWO CODE BLOCKS BELOW DEFINE FUNCTIONS\n! ----------------------------------------------------------------------\n! LECH'S SURFACE FUNCTIONS\n! ----------------------------------------------------------------------\n      PSLMU (ZZ)= -0.96* log (1.0-4.5* ZZ)\n      PSLMS (ZZ)= ZZ * RRIC -2.076* (1. -1./ (ZZ +1.))\n      PSLHU (ZZ)= -0.96* log (1.0-4.5* ZZ)\n\n! ----------------------------------------------------------------------\n! PAULSON'S SURFACE FUNCTIONS\n! ----------------------------------------------------------------------\n      PSLHS (ZZ)= ZZ * RFAC -2.076* (1. -1./ (ZZ +1.))\n      PSPMU (XX)= -2.* log ( (XX +1.)*0.5) - log ( (XX * XX +1.)*0.5)   &\n     &        +2.* ATAN (XX)                                            &\n     &- PIHF\n      PSPMS (YY)= 5.* YY\n      PSPHU (XX)= -2.* log ( (XX * XX +1.)*0.5)\n\n! ----------------------------------------------------------------------\n! THIS ROUTINE SFCDIF CAN HANDLE BOTH OVER OPEN WATER (SEA, OCEAN) AND\n! OVER SOLID SURFACE (LAND, SEA-ICE).\n! ----------------------------------------------------------------------\n      PSPHS (YY)= 5.* YY\n\n! ----------------------------------------------------------------------\n!     ZTFC: RATIO OF ZOH/ZOM  LESS OR EQUAL THAN 1\n!     C......ZTFC=0.1\n!     CZIL: CONSTANT C IN Zilitinkevich, S. S.1995,:NOTE ABOUT ZT\n! ----------------------------------------------------------------------\n      ILECH = 0\n\n! ----------------------------------------------------------------------\n#ifdef _HRLDAS_OFFLINE_\n      IF ( (IZ0TLND==0) .or. (VEGTYP == ISURBAN) ) THEN\n         ! Just use the original CZIL value.\n         ZILFC = - CZIL * VKRM * SQVISC\n      ELSE\n         ! Modify CZIL according to Chen & Zhang, 2009\n         ! CZIL = 10 ** -0.40 H, ( where H = 10*Zo )\n         CZIL = 10.0 ** ( -0.40 * ( Z0 / 0.07 ) )\n         ZILFC = - CZIL * VKRM * SQVISC\n      ENDIF\n#else\n      ZILFC = - CZIL * VKRM * SQVISC\n#endif\n!     C.......ZT=Z0*ZTFC\n      ZU = Z0\n#ifdef _HRLDAS_OFFLINE_\n      RDZ = 1./ ZLM_WIND\n#else\n      RDZ = 1./ ZLM\n#endif\n      CXCH = EXCM * RDZ\n      DTHV = THLM - THZ0\n\n! ----------------------------------------------------------------------\n! BELJARS CORRECTION OF USTAR\n! ----------------------------------------------------------------------\n      DU2 = MAX (SFCSPD * SFCSPD,EPSU2)\n!cc   If statements to avoid TANGENT LINEAR problems near zero\n      BTGH = BTG * HPBL\n      IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n         WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n      ELSE\n         WSTAR2 = 0.0\n      END IF\n\n! ----------------------------------------------------------------------\n! ZILITINKEVITCH APPROACH FOR ZT\n! ----------------------------------------------------------------------\n      USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n\n! ----------------------------------------------------------------------\n      ZT = EXP (ZILFC * SQRT (USTAR * Z0))* Z0\n#ifdef _HRLDAS_OFFLINE_\n      ZSLU = ZLM_WIND + ZU\n#else\n      ZSLU = ZLM + ZU\n#endif\n!     PRINT*,'ZSLT=',ZSLT\n!     PRINT*,'ZLM=',ZLM\n!     PRINT*,'ZT=',ZT\n\n      ZSLT = ZLM + ZT\n      RLOGU = log (ZSLU / ZU)\n\n      RLOGT = log (ZSLT / ZT)\n!     PRINT*,'RLMO=',RLMO\n!     PRINT*,'ELFC=',ELFC\n!     PRINT*,'AKHS=',AKHS\n!     PRINT*,'DTHV=',DTHV\n!     PRINT*,'USTAR=',USTAR\n\n      RLMO = ELFC * AKHS * DTHV / USTAR **3\n! ----------------------------------------------------------------------\n! 1./MONIN-OBUKKHOV LENGTH-SCALE\n! ----------------------------------------------------------------------\n      DO ITR = 1,ITRMX\n         ZETALT = MAX (ZSLT * RLMO,ZTMIN)\n         RLMO = ZETALT / ZSLT\n         ZETALU = ZSLU * RLMO\n         ZETAU = ZU * RLMO\n\n         ZETAT = ZT * RLMO\n         IF (ILECH .eq. 0) THEN\n            IF (RLMO .lt. 0.)THEN\n               XLU4 = 1. -16.* ZETALU\n               XLT4 = 1. -16.* ZETALT\n               XU4 = 1. -16.* ZETAU\n\n               XT4 = 1. -16.* ZETAT\n               XLU = SQRT (SQRT (XLU4))\n               XLT = SQRT (SQRT (XLT4))\n               XU = SQRT (SQRT (XU4))\n\n               XT = SQRT (SQRT (XT4))\n!     PRINT*,'-----------1------------'\n!     PRINT*,'PSMZ=',PSMZ\n!     PRINT*,'PSPMU(ZETAU)=',PSPMU(ZETAU)\n!     PRINT*,'XU=',XU\n!     PRINT*,'------------------------'\n               PSMZ = PSPMU (XU)\n               SIMM = PSPMU (XLU) - PSMZ + RLOGU\n               PSHZ = PSPHU (XT)\n               SIMH = PSPHU (XLT) - PSHZ + RLOGT\n            ELSE\n               ZETALU = MIN (ZETALU,ZTMAX)\n               ZETALT = MIN (ZETALT,ZTMAX)\n!     PRINT*,'-----------2------------'\n!     PRINT*,'PSMZ=',PSMZ\n!     PRINT*,'PSPMS(ZETAU)=',PSPMS(ZETAU)\n!     PRINT*,'ZETAU=',ZETAU\n!     PRINT*,'------------------------'\n               PSMZ = PSPMS (ZETAU)\n               SIMM = PSPMS (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSPHS (ZETAT)\n               SIMH = PSPHS (ZETALT) - PSHZ + RLOGT\n            END IF\n! ----------------------------------------------------------------------\n! LECH'S FUNCTIONS\n! ----------------------------------------------------------------------\n         ELSE\n            IF (RLMO .lt. 0.)THEN\n!     PRINT*,'-----------3------------'\n!     PRINT*,'PSMZ=',PSMZ\n!     PRINT*,'PSLMU(ZETAU)=',PSLMU(ZETAU)\n!     PRINT*,'ZETAU=',ZETAU\n!     PRINT*,'------------------------'\n               PSMZ = PSLMU (ZETAU)\n               SIMM = PSLMU (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSLHU (ZETAT)\n               SIMH = PSLHU (ZETALT) - PSHZ + RLOGT\n            ELSE\n               ZETALU = MIN (ZETALU,ZTMAX)\n\n               ZETALT = MIN (ZETALT,ZTMAX)\n!     PRINT*,'-----------4------------'\n!     PRINT*,'PSMZ=',PSMZ\n!     PRINT*,'PSLMS(ZETAU)=',PSLMS(ZETAU)\n!     PRINT*,'ZETAU=',ZETAU\n!     PRINT*,'------------------------'\n               PSMZ = PSLMS (ZETAU)\n               SIMM = PSLMS (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSLHS (ZETAT)\n               SIMH = PSLHS (ZETALT) - PSHZ + RLOGT\n            END IF\n! ----------------------------------------------------------------------\n! BELJAARS CORRECTION FOR USTAR\n! ----------------------------------------------------------------------\n         END IF\n\n! ----------------------------------------------------------------------\n! ZILITINKEVITCH FIX FOR ZT\n! ----------------------------------------------------------------------\n         USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n\n         ZT = EXP (ZILFC * SQRT (USTAR * Z0))* Z0\n         ZSLT = ZLM + ZT\n!-----------------------------------------------------------------------\n         RLOGT = log (ZSLT / ZT)\n         USTARK = USTAR * VKRM\n         AKMS = MAX (USTARK / SIMM,CXCH)\n!-----------------------------------------------------------------------\n! IF STATEMENTS TO AVOID TANGENT LINEAR PROBLEMS NEAR ZERO\n!-----------------------------------------------------------------------\n         AKHS = MAX (USTARK / SIMH,CXCH)\n         IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n            WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n         ELSE\n            WSTAR2 = 0.0\n         END IF\n!-----------------------------------------------------------------------\n         RLMN = ELFC * AKHS * DTHV / USTAR **3\n!-----------------------------------------------------------------------\n!     IF(ABS((RLMN-RLMO)/RLMA).LT.EPSIT)    GO TO 110\n!-----------------------------------------------------------------------\n         RLMA = RLMO * WOLD+ RLMN * WNEW\n!-----------------------------------------------------------------------\n         RLMO = RLMA\n!     PRINT*,'----------------------------'\n!     PRINT*,'SFCDIF OUTPUT !  ! ! ! ! ! ! ! !  !   !    !'\n\n!     PRINT*,'ZLM=',ZLM\n!     PRINT*,'Z0=',Z0\n!     PRINT*,'THZ0=',THZ0\n!     PRINT*,'THLM=',THLM\n!     PRINT*,'SFCSPD=',SFCSPD\n!     PRINT*,'CZIL=',CZIL\n!     PRINT*,'AKMS=',AKMS\n!     PRINT*,'AKHS=',AKHS\n!     PRINT*,'----------------------------'\n\n      END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE SFCDIF_off\n! ----------------------------------------------------------------------\n\nEND MODULE module_sf_noahlsm\n"
  },
  {
    "path": "src/Land_models/Noah/Noah/module_sf_urban.F",
    "content": "MODULE module_sf_urban\n\n!===============================================================================\n!     Single-Layer Urban Canopy Model for WRF Noah-LSM\n!     Original Version: 2002/11/06 by Hiroyuki Kusaka\n!     Last Update:      2006/08/24 by Fei Chen and Mukul Tewari (NCAR/RAL)  \n!===============================================================================\n\n   CHARACTER(LEN=4)                :: LU_DATA_TYPE\n\n   INTEGER                         :: ICATE\n\n   REAL, ALLOCATABLE, DIMENSION(:) :: ZR_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: Z0C_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: Z0HC_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: ZDC_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: SVF_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: R_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: RW_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: HGT_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: AH_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: BETR_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: BETB_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: BETG_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: FRC_URB_TBL\n\n   REAL, ALLOCATABLE, DIMENSION(:) :: COP_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: PWIN_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: BETA_TBL\n   INTEGER, ALLOCATABLE, DIMENSION(:) :: SW_COND_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: TIME_ON_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: TIME_OFF_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: TARGTEMP_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: GAPTEMP_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: TARGHUM_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: GAPHUM_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: PERFLO_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: HSESF_TBL\n\n   REAL, ALLOCATABLE, DIMENSION(:) :: CAPR_TBL, CAPB_TBL, CAPG_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: AKSR_TBL, AKSB_TBL, AKSG_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: ALBR_TBL, ALBB_TBL, ALBG_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: EPSR_TBL, EPSB_TBL, EPSG_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: Z0R_TBL,  Z0B_TBL,  Z0G_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: SIGMA_ZED_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: Z0HB_TBL, Z0HG_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: TRLEND_TBL, TBLEND_TBL, TGLEND_TBL\n   REAL, ALLOCATABLE, DIMENSION(:) :: AKANDA_URBAN_TBL\n!for BEP\n\n   ! MAXDIRS :: The maximum number of street directions we're allowed to define\n   INTEGER, PARAMETER :: MAXDIRS = 3\n   ! MAXHGTS :: The maximum number of building height bins we're allowed to define\n   INTEGER, PARAMETER :: MAXHGTS = 50\n\n   INTEGER, ALLOCATABLE, DIMENSION(:)   :: NUMDIR_TBL\n   REAL,    ALLOCATABLE, DIMENSION(:,:) :: STREET_DIRECTION_TBL\n   REAL,    ALLOCATABLE, DIMENSION(:,:) :: STREET_WIDTH_TBL\n   REAL,    ALLOCATABLE, DIMENSION(:,:) :: BUILDING_WIDTH_TBL\n   INTEGER, ALLOCATABLE, DIMENSION(:)   :: NUMHGT_TBL\n   REAL,    ALLOCATABLE, DIMENSION(:,:) :: HEIGHT_BIN_TBL\n   REAL,    ALLOCATABLE, DIMENSION(:,:) :: HPERCENT_BIN_TBL\n!end BEP\n   INTEGER                         :: BOUNDR_DATA,BOUNDB_DATA,BOUNDG_DATA\n   INTEGER                         :: CH_SCHEME_DATA, TS_SCHEME_DATA\n   INTEGER                         :: ahoption        ! Miao, 2007/01/17, cal. ah\n   REAL, DIMENSION(1:24)           :: ahdiuprf        ! ah diurnal profile, tloc: 1-24\n   REAL, DIMENSION(1:24)           :: hsequip_tbl\n\n   INTEGER                         :: allocate_status\n\n!   INTEGER                         :: num_roof_layers\n!   INTEGER                         :: num_wall_layers\n!   INTEGER                         :: num_road_layers\n\n   CONTAINS\n\n!===============================================================================\n!\n! Author:\n!      Hiroyuki KUSAKA, PhD\n!      University of Tsukuba, JAPAN\n!      (CRIEPI, NCAR/MMM visiting scientist, 2002-2004)\n!      kusaka@ccs.tsukuba.ac.jp\n!\n! Co-Researchers:\n!     Fei CHEN, PhD\n!      NCAR/RAP feichen@ucar.edu\n!     Mukul TEWARI, PhD\n!      NCAR/RAP mukul@ucar.edu\n!\n! Purpose:\n!     Calculate surface temeprature, fluxes, canopy air temperature, and canopy wind\n!\n! Subroutines:\n!     module_sf_urban\n!       |- urban\n!            |- read_param\n!            |- mos or jurges\n!            |- multi_layer or force_restore\n!       |- urban_param_init <-- URBPARM.TBL\n!       |- urban_var_init\n!\n! Input Data from WRF [MKS unit]:\n!\n!     UTYPE  [-]     : Urban type. 1=Commercial/Industrial; 2=High-intensity residential; \n!                    : 3=low-intensity residential\n!     TA     [K]     : Potential temperature at 1st wrf level (absolute temp)\n!     QA     [kg/kg] : Mixing ratio at 1st atmospheric level\n!     UA     [m/s]   : Wind speed at 1st atmospheric level\n!     SSG    [W/m/m] : Short wave downward radiation at a flat surface\n!                      Note this is the total of direct and diffusive solar\n!                      downward radiation. If without two components, the\n!                      single solar downward can be used instead.\n!                      SSG = SSGD + SSGQ\n!     LSOLAR [-]     : Indicating the input type of solar downward radiation\n!                      True: both direct and diffusive solar radiation\n!                      are available\n!                      False: only total downward ridiation is available.\n!     SSGD   [W/m/m] : Direct solar radiation at a flat surface\n!                      if SSGD is not available, one can assume a ratio SRATIO\n!                      (e.g., 0.7), so that SSGD = SRATIO*SSG\n!     SSGQ   [W/m/m] : Diffuse solar radiation at a flat surface\n!                      If SSGQ is not available, SSGQ = SSG - SSGD\n!     LLG    [W/m/m] : Long wave downward radiation at a flat surface\n!     RAIN   [mm/h]  : Precipitation\n!     RHOO   [kg/m/m/m] : Air density\n!     ZA     [m]     : First atmospheric level\n!                      as a lowest boundary condition\n!     DECLIN [rad]   : solar declination\n!     COSZ           : = sin(fai)*sin(del)+cos(fai)*cos(del)*cos(omg)\n!     OMG    [rad]   : solar hour angle\n!     XLAT   [deg]   : latitude\n!     DELT   [sec]   : Time step\n!     ZNT    [m]     : Roughnes length\n!\n! Output Data to WRF [MKS unit]:\n!\n!     TS  [K]            : Surface potential temperature (absolute temp)\n!     QS  [-]            : Surface humidity\n!\n!     SH  [W/m/m/]       : Sensible heat flux, = FLXTH*RHOO*CPP\n!     LH  [W/m/m]        : Latent heat flux, = FLXHUM*RHOO*ELL\n!     LH_INEMATIC [kg/m/m/sec]: Moisture Kinematic flux, = FLXHUM*RHOO\n!     SW  [W/m/m]        : Upward shortwave radiation flux,\n!                          = SSG-SNET*697.7*60. (697.7*60.=100.*100.*4.186)\n!     ALB [-]            : Time-varying albedo\n!     LW  [W/m/m]        : Upward longwave radiation flux,\n!                          = LNET*697.7*60.-LLG\n!     G   [W/m/m]        : Heat Flux into the Ground\n!     RN  [W/m/m]        : Net radiation\n!\n!     PSIM  [-]          : Diagnostic similarity stability function for momentum\n!     PSIH  [-]          : Diagnostic similarity stability function for heat\n!\n!     TC  [K]            : Diagnostic canopy air temperature\n!     QC  [-]            : Diagnostic canopy humidity\n!\n!     TH2 [K]            : Diagnostic potential temperature at 2 m\n!     Q2  [-]            : Diagnostic humidity at 2 m\n!     U10 [m/s]          : Diagnostic u wind component at 10 m\n!     V10 [m/s]          : Diagnostic v wind component at 10 m\n!\n!     CHS, CHS2 [m/s]    : CH*U at ZA, CH*U at 2 m (not used)\n!\n! Important parameters:\n!\n! Morphology of the urban canyon:\n! These parameters assigned in the URBPARM.TBL\n!\n!    ZR  [m]             : roof level (building height)\n!    SIGMA_ZED [m]       : Standard Deviation of roof height\n!    ROOF_WIDTH [m]      : roof (i.e., building) width\n!    ROAD_WIDTH [m]      : road width\n!\n! Parameters derived from the morphological terms above.\n! These parameters are computed in the code.\n!\n!    HGT [-]             : normalized building height\n!    SVF [-]             : sky view factor\n!    R   [-]             : Normalized roof width (a.k.a. \"building coverage ratio\")\n!    RW  [-]             : = 1 - R\n!    Z0C [m]             : Roughness length above canyon for momentum (1/10 of ZR)\n!    Z0HC [m]            : Roughness length above canyon for heat (1/10 of Z0C)\n!    ZDC [m]             : Zero plane displacement height (1/5 of ZR)\n!\n! Following parameter are assigned in run/URBPARM.TBL\n!\n!  AH  [ W m{-2} ]        : anthropogenic heat  ( W m{-2} in the table, converted internally to cal cm{-2} )\n!  CAPR[ J m{-3} K{-1} ]  : heat capacity of roof ( units converted in code to [ cal cm{-3} deg{-1} ] )\n!  CAPB[ J m{-3} K{-1} ]  : heat capacity of building wall ( units converted in code to [ cal cm{-3} deg{-1} ] )\n!  CAPG[ J m{-3} K{-1} ]  : heat capacity of road ( units converted in code to [ cal cm{-3} deg{-1} ] )\n!  AKSR [ J m{-1} s{-1} K{-1} ] : thermal conductivity of roof ( units converted in code to [ cal cm{-1} s{-1} deg{-1} ] )\n!  AKSB [ J m{-1} s{-1} K{-1} ] : thermal conductivity of building wall ( units converted in code to [ cal cm{-1} s{-1} deg{-1} ] )\n!  AKSG [ J m{-1} s{-1} K{-1} ] : thermal conductivity of road ( units converted in code to [ cal cm{-1} s{-1} deg{-1} ] )\n!  ALBR [-]               : surface albedo of roof\n!  ALBB [-]               : surface albedo of building wall\n!  ALBG [-]               : surface albedo of road\n!  EPSR [-]               : surface emissivity of roof\n!  EPSB [-]               : surface emissivity of building wall\n!  EPSG [-]               : surface emissivity of road\n!  Z0B [m]                : roughness length for momentum of building wall (only for CH_SCHEME = 1)\n!  Z0G [m]                : roughness length for momentum of road (only for CH_SCHEME = 1)\n!  Z0HB [m]               : roughness length for heat of building wall (only for CH_SCHEME = 1)\n!  Z0HG [m]               : roughness length for heat of road\n!  num_roof_layers        : number of layers within roof\n!  num_wall_layers        : number of layers within building walls\n!  num_road_layers        : number of layers within below road surface\n!   NOTE: for now, these layers are defined as same as the number of soil layers in namelist.input\n!  DZR [cm]               : thickness of each roof layer\n!  DZB [cm]               : thickness of each building wall layer\n!  DZG [cm]               : thickness of each ground layer\n!  BOUNDR [integer 1 or 2] : Boundary Condition for Roof Layer Temp [1: Zero-Flux, 2: T = Constant]\n!  BOUNDB [integer 1 or 2] : Boundary Condition for Building Wall Layer Temp [1: Zero-Flux, 2: T = Constant]\n!  BOUNDG [integer 1 or 2] : Boundary Condition for Road Layer Temp [1: Zero-Flux, 2: T = Constant]\n!  TRLEND [K]             : lower boundary condition of roof temperature\n!  TBLEND [K]             : lower boundary condition of building temperature\n!  TGLEND [K]             : lower boundary condition of ground temperature\n!  CH_SCHEME [integer 1 or 2] : Sfc exchange scheme used for building wall and road\n!                         [1: M-O Similarity Theory,  2: Empirical Form (recommend)]\n!  TS_SCHEME [integer 1 or 2] : Scheme for computing surface temperature (for roof, wall, and road)\n!                         [1: 4-layer model,  2: Force-Restore method]\n!\n!for BEP\n!  numdir [ - ]             : Number of street directions defined for a particular urban category\n!  street_direction [ deg ] : Direction of streets for a particular urban category and a particular street direction\n!  street_width [ m ]       : Width of street for a particular urban category and a particular street direction\n!  building_width [ m ]     : Width of buildings for a particular urban category and a particular street direction\n!  numhgt [ - ]             : Number of building height levels defined for a particular urban category\n!  height_bin [ m ]         : Building height bins defined for a particular urban category.\n!  hpercent_bin [ % ]       : Percentage of a particular urban category populated by buildings of particular height bins\n!end BEP\n! Moved from URBPARM.TBL\n!\n!  BETR [-]            : minimum moisture availability of roof\n!  BETB [-]            : minimum moisture availability of building wall\n!  BETG [-]            : minimum moisture availability of road\n!  Z0R [m]                : roughness length for momentum of roof\n!  Z0HB [m]               : roughness length for heat of building wall (only for CH_SCHEME = 1)\n!  Z0HG [m]               : roughness length for heat of road\n!  num_roof_layers        : number of layers within roof\n!  num_wall_layers        : number of layers within building walls\n!  num_road_layers        : number of layers within below road surface\n!   NOTE: for now, these layers are defined as same as the number of soil layers in namelist.input\n!\n! References:\n!     Kusaka and Kimura (2004) J.Appl.Meteor., vol.43, p1899-1910\n!     Kusaka and Kimura (2004) J.Meteor.Soc.Japan, vol.82, p45-65\n!     Kusaka et al. (2001) Bound.-Layer Meteor., vol.101, p329-358\n!\n! History:\n!     2006/06          modified by H. Kusaka (Univ. Tsukuba), M. Tewari\n!     2005/10/26,      modified by Fei Chen, Mukul Tewari\n!     2003/07/21 WRF , modified  by H. Kusaka of CRIEPI (NCAR/MMM)\n!     2001/08/26 PhD , modified  by H. Kusaka of CRIEPI (Univ.Tsukuba)\n!     1999/08/25 LCM , developed by H. Kusaka of CRIEPI (Univ.Tsukuba)\n!\n!===============================================================================\n!\n!  subroutine urban:\n!\n!===============================================================================\n\n   SUBROUTINE urban(LSOLAR,                                           & ! L\n                    num_roof_layers,num_wall_layers,num_road_layers,  & ! I\n                    DZR,DZB,DZG,                                      & ! I\n                    UTYPE,TA,QA,UA,U1,V1,SSG,SSGD,SSGQ,LLG,RAIN,RHOO, & ! I\n                    ZA,DECLIN,COSZ,OMG,XLAT,DELT,ZNT,                 & ! I\n                    CHS, CHS2,                                        & ! I\n                    TR, TB, TG, TC, QC, UC,                           & ! H\n                    TRL,TBL,TGL,                                      & ! H\n                    XXXR, XXXB, XXXG, XXXC,                           & ! H\n                    TS,QS,SH,LH,LH_KINEMATIC,                         & ! O\n                    SW,ALB,LW,G,RN,PSIM,PSIH,                         & ! O\n                    GZ1OZ0,                                           & ! O\n                    CMR_URB,CHR_URB,CMC_URB,CHC_URB,                  & ! I/O\n                    U10,V10,TH2,Q2,UST                                & ! O\n                    )\n\n   IMPLICIT NONE\n\n   REAL, PARAMETER    :: CP=0.24          ! heat capacity of dry air  [cgs unit]\n   REAL, PARAMETER    :: EL=583.          ! latent heat of vaporation [cgs unit]\n   REAL, PARAMETER    :: SIG=8.17E-11     ! stefun bolzman constant   [cgs unit]\n   REAL, PARAMETER    :: SIG_SI=5.67E-8   !                           [MKS unit]\n   REAL, PARAMETER    :: AK=0.4           ! kalman const.                [-]\n   REAL, PARAMETER    :: PI=3.14159       ! pi                           [-]\n   REAL, PARAMETER    :: TETENA=7.5       ! const. of Tetens Equation    [-]\n   REAL, PARAMETER    :: TETENB=237.3     ! const. of Tetens Equation    [-]\n   REAL, PARAMETER    :: SRATIO=0.75      ! ratio between direct/total solar [-]\n\n   REAL, PARAMETER    :: CPP=1004.5       ! heat capacity of dry air    [J/K/kg]\n   REAL, PARAMETER    :: ELL=2.442E+06    ! latent heat of vaporization [J/kg]\n   REAL, PARAMETER    :: XKA=2.4E-5\n\n!-------------------------------------------------------------------------------\n! C: configuration variables\n!-------------------------------------------------------------------------------\n\n   LOGICAL, INTENT(IN) :: LSOLAR  ! logical    [true=both, false=SSG only]\n\n!  The following variables are also model configuration variables, but are \n!  defined in the URBAN.TBL and in the contains statement in the top of\n!  the module_urban_init, so we should not declare them here.\n\n  INTEGER, INTENT(IN) :: num_roof_layers\n  INTEGER, INTENT(IN) :: num_wall_layers\n  INTEGER, INTENT(IN) :: num_road_layers\n\n\n  REAL, INTENT(IN), DIMENSION(1:num_roof_layers) :: DZR ! grid interval of roof layers [cm]\n  REAL, INTENT(IN), DIMENSION(1:num_wall_layers) :: DZB ! grid interval of wall layers [cm]\n  REAL, INTENT(IN), DIMENSION(1:num_road_layers) :: DZG ! grid interval of road layers [cm]\n\n!-------------------------------------------------------------------------------\n! I: input variables from LSM to Urban\n!-------------------------------------------------------------------------------\n\n   INTEGER, INTENT(IN) :: UTYPE ! urban type [1=Commercial/Industrial, 2=High-intensity residential, \n                                ! 3=low-intensity residential]\n\n   REAL, INTENT(IN)    :: TA   ! potential temp at 1st atmospheric level [K]\n   REAL, INTENT(IN)    :: QA   ! mixing ratio at 1st atmospheric level  [kg/kg]\n   REAL, INTENT(IN)    :: UA   ! wind speed at 1st atmospheric level    [m/s]\n   REAL, INTENT(IN)    :: U1   ! u at 1st atmospheric level             [m/s]\n   REAL, INTENT(IN)    :: V1   ! v at 1st atmospheric level             [m/s]\n   REAL, INTENT(IN)    :: SSG  ! downward total short wave radiation    [W/m/m]\n   REAL, INTENT(IN)    :: LLG  ! downward long wave radiation           [W/m/m]\n   REAL, INTENT(IN)    :: RAIN ! precipitation                          [mm/h]\n   REAL, INTENT(IN)    :: RHOO ! air density                            [kg/m^3]\n   REAL, INTENT(IN)    :: ZA   ! first atmospheric level                [m]\n   REAL, INTENT(IN)    :: DECLIN ! solar declination                    [rad]\n   REAL, INTENT(IN)    :: COSZ ! sin(fai)*sin(del)+cos(fai)*cos(del)*cos(omg)\n   REAL, INTENT(IN)    :: OMG  ! solar hour angle                       [rad]\n\n   REAL, INTENT(IN)    :: XLAT ! latitude                               [deg]\n   REAL, INTENT(IN)    :: DELT ! time step                              [s]\n   REAL, INTENT(IN)    :: ZNT  ! roughness length                       [m]\n   REAL, INTENT(IN)    :: CHS,CHS2 ! CH*U at za and 2 m             [m/s]\n\n   REAL, INTENT(INOUT) :: SSGD ! downward direct short wave radiation   [W/m/m]\n   REAL, INTENT(INOUT) :: SSGQ ! downward diffuse short wave radiation  [W/m/m]\n   REAL, INTENT(INOUT) :: CMR_URB\n   REAL, INTENT(INOUT) :: CHR_URB\n   REAL, INTENT(INOUT) :: CMC_URB\n   REAL, INTENT(INOUT) :: CHC_URB\n\n!-------------------------------------------------------------------------------\n! O: output variables from Urban to LSM\n!-------------------------------------------------------------------------------\n\n   REAL, INTENT(OUT) :: TS     ! surface potential temperature    [K]\n   REAL, INTENT(OUT) :: QS     ! surface humidity                 [K]\n   REAL, INTENT(OUT) :: SH     ! sensible heat flux               [W/m/m]\n   REAL, INTENT(OUT) :: LH     ! latent heat flux                 [W/m/m]\n   REAL, INTENT(OUT) :: LH_KINEMATIC ! latent heat, kinetic     [kg/m/m/s]\n   REAL, INTENT(OUT) :: SW     ! upward short wave radiation flux [W/m/m]\n   REAL, INTENT(OUT) :: ALB    ! time-varying albedo            [fraction]\n   REAL, INTENT(OUT) :: LW     ! upward long wave radiation flux  [W/m/m]\n   REAL, INTENT(OUT) :: G      ! heat flux into the ground        [W/m/m]\n   REAL, INTENT(OUT) :: RN     ! net radition                     [W/m/m]\n   REAL, INTENT(OUT) :: PSIM   ! similality stability shear function for momentum\n   REAL, INTENT(OUT) :: PSIH   ! similality stability shear function for heat\n   REAL, INTENT(OUT) :: GZ1OZ0\n   REAL, INTENT(OUT) :: U10    ! u at 10m                         [m/s]\n   REAL, INTENT(OUT) :: V10    ! u at 10m                         [m/s]\n   REAL, INTENT(OUT) :: TH2    ! potential temperature at 2 m     [K]\n   REAL, INTENT(OUT) :: Q2     ! humidity at 2 m                  [-]\n!m   REAL, INTENT(OUT) :: CHS,CHS2 ! CH*U at za and 2 m             [m/s]\n   REAL, INTENT(OUT) :: UST    ! friction velocity                [m/s]\n\n\n!-------------------------------------------------------------------------------\n! H: Historical (state) variables of Urban : LSM <--> Urban\n!-------------------------------------------------------------------------------\n\n! TR: roof temperature              [K];      TRP: at previous time step [K]\n! TB: building wall temperature     [K];      TBP: at previous time step [K]\n! TG: road temperature              [K];      TGP: at previous time step [K]\n! TC: urban-canopy air temperature  [K];      TCP: at previous time step [K]\n!                                                  (absolute temperature)\n! QC: urban-canopy air mixing ratio [kg/kg];  QCP: at previous time step [kg/kg]\n!\n! XXXR: Monin-Obkhov length for roof          [dimensionless]\n! XXXB: Monin-Obkhov length for building wall [dimensionless]\n! XXXG: Monin-Obkhov length for road          [dimensionless]\n! XXXC: Monin-Obkhov length for urban-canopy  [dimensionless]\n!\n! TRL, TBL, TGL: layer temperature [K] (absolute temperature)\n\n   REAL, INTENT(INOUT):: TR, TB, TG, TC, QC, UC\n   REAL, INTENT(INOUT):: XXXR, XXXB, XXXG, XXXC\n\n   REAL, DIMENSION(1:num_roof_layers), INTENT(INOUT) :: TRL\n   REAL, DIMENSION(1:num_wall_layers), INTENT(INOUT) :: TBL\n   REAL, DIMENSION(1:num_road_layers), INTENT(INOUT) :: TGL\n\n!-------------------------------------------------------------------------------\n! L:  Local variables from read_param\n!-------------------------------------------------------------------------------\n\n   REAL :: ZR, Z0C, Z0HC, ZDC, SVF, R, RW, HGT, AH\n   REAL :: SIGMA_ZED\n   REAL :: CAPR, CAPB, CAPG, AKSR, AKSB, AKSG, ALBR, ALBB, ALBG\n   REAL :: EPSR, EPSB, EPSG, Z0R,  Z0B,  Z0G,  Z0HB, Z0HG\n   REAL :: TRLEND,TBLEND,TGLEND\n   REAL :: T1VR, T1VC,TH2V\n   REAL :: RLMO_URB\n   REAL :: AKANDA_URBAN\n\n   REAL :: TH2X                                                !m\n\n   INTEGER :: BOUNDR, BOUNDB, BOUNDG\n   INTEGER :: CH_SCHEME, TS_SCHEME\n\n   LOGICAL :: SHADOW  ! [true=consider svf and shadow effects, false=consider svf effect only]\n\n!for BEP\n   INTEGER                        :: NUMDIR\n   REAL,    DIMENSION ( MAXDIRS ) :: STREET_DIRECTION\n   REAL,    DIMENSION ( MAXDIRS ) :: STREET_WIDTH\n   REAL,    DIMENSION ( MAXDIRS ) :: BUILDING_WIDTH\n   INTEGER                        :: NUMHGT\n   REAL,    DIMENSION ( MAXHGTS ) :: HEIGHT_BIN\n   REAL,    DIMENSION ( MAXHGTS ) :: HPERCENT_BIN\n!end BEP\n!-------------------------------------------------------------------------------\n! L: Local variables\n!-------------------------------------------------------------------------------\n\n   REAL :: BETR, BETB, BETG\n   REAL :: SX, SD, SQ, RX\n   REAL :: UR, ZC, XLB, BB\n   REAL :: Z, RIBB, RIBG, RIBC, BHR, BHB, BHG, BHC\n   REAL :: TSC, LNET, SNET, FLXUV, THG, FLXTH, FLXHUM, FLXG\n   REAL :: W, VFGS, VFGW, VFWG, VFWS, VFWW\n   REAL :: HOUI1, HOUI2, HOUI3, HOUI4, HOUI5, HOUI6, HOUI7, HOUI8\n   REAL :: SLX, SLX1, SLX2, SLX3, SLX4, SLX5, SLX6, SLX7, SLX8\n   REAL :: FLXTHR, FLXTHB, FLXTHG, FLXHUMR, FLXHUMB, FLXHUMG\n   REAL :: SR, SB, SG, RR, RB, RG\n   REAL :: SR1, SR2, SB1, SB2, SG1, SG2, RR1, RR2, RB1, RB2, RG1, RG2\n   REAL :: HR, HB, HG, ELER, ELEB, ELEG, G0R, G0B, G0G\n   REAL :: ALPHAC, ALPHAR, ALPHAB, ALPHAG\n   REAL :: CHC, CHR, CHB, CHG, CDC, CDR, CDB, CDG\n   REAL :: C1R, C1B, C1G, TE, TC1, TC2, QC1, QC2, QS0R, QS0B, QS0G,RHO,ES\n\n   REAL :: DESDT\n   REAL :: F\n   REAL :: DQS0RDTR\n   REAL :: DRRDTR, DHRDTR, DELERDTR, DG0RDTR\n   REAL :: DTR, DFDT\n   REAL :: FX, FY, GF, GX, GY\n   REAL :: DTCDTB, DTCDTG\n   REAL :: DQCDTB, DQCDTG\n   REAL :: DRBDTB1,  DRBDTG1,  DRBDTB2,  DRBDTG2\n   REAL :: DRGDTB1,  DRGDTG1,  DRGDTB2,  DRGDTG2\n   REAL :: DRBDTB,   DRBDTG,   DRGDTB,   DRGDTG\n   REAL :: DHBDTB,   DHBDTG,   DHGDTB,   DHGDTG\n   REAL :: DELEBDTB, DELEBDTG, DELEGDTG, DELEGDTB\n   REAL :: DG0BDTB,  DG0BDTG,  DG0GDTG,  DG0GDTB\n   REAL :: DQS0BDTB, DQS0GDTG\n   REAL :: DTB, DTG, DTC\n\n   REAL :: THEATAZ    ! Solar Zenith Angle [rad]\n   REAL :: THEATAS    ! = PI/2. - THETAZ\n   REAL :: FAI        ! Latitude [rad]\n   REAL :: CNT,SNT\n   REAL :: PS         ! Surface Pressure [hPa]\n   REAL :: TAV        ! Vertial Temperature [K]\n\n   REAL :: XXX, X, Z0, Z0H, CD, CH\n   REAL :: XXX2, PSIM2, PSIH2, XXX10, PSIM10, PSIH10\n   REAL :: PSIX, PSIT, PSIX2, PSIT2, PSIX10, PSIT10\n\n   REAL :: TRP, TBP, TGP, TCP, QCP, TST, QST\n\n   INTEGER :: iteration, K\n   INTEGER :: tloc\n\n#ifdef _HRLDAS_URBAN_\n   real :: converge_coefficient\n   real :: tbp_hold, qcp_hold\n   real :: tgp_hold, tcp_hold\n   logical :: diverging\n   logical :: converged\n   logical :: converged2\n#endif\n!-------------------------------------------------------------------------------\n! Set parameters\n!-------------------------------------------------------------------------------\n\n! Miao, 2007/01/17, cal. ah\n   if(ahoption==1) then\n     tloc=mod(int(OMG/PI*180./15.+12.+0.5 ),24)\n     if(tloc==0) tloc=24\n   endif\n\n   CALL read_param(UTYPE,ZR,SIGMA_ZED,Z0C,Z0HC,ZDC,SVF,R,RW,HGT,  &\n                   AH,CAPR,CAPB,CAPG,AKSR,AKSB,AKSG,ALBR,ALBB,    &\n                   ALBG,EPSR,EPSB,EPSG,Z0R,Z0B,Z0G,Z0HB,Z0HG,     &\n                   BETR,BETB,BETG,TRLEND,TBLEND,TGLEND,           &\n!for BEP\n                   NUMDIR, STREET_DIRECTION, STREET_WIDTH,        &\n                   BUILDING_WIDTH, NUMHGT, HEIGHT_BIN,            &\n                   HPERCENT_BIN,                                  &\n!end BEP\n                   BOUNDR,BOUNDB,BOUNDG,CH_SCHEME,TS_SCHEME,      &\n                   AKANDA_URBAN)\n\n! Miao, 2007/01/17, cal. ah\n   if(ahoption==1) AH=AH*ahdiuprf(tloc)\n\n   IF( ZDC+Z0C+2. >= ZA) THEN\n    CALL wrf_error_fatal (\"ZDC + Z0C + 2m is larger than the 1st WRF level \"// &\n                           \"Stop in subroutine urban - change ZDC and Z0C\" ) \n   END IF\n\n   IF(.NOT.LSOLAR) THEN\n     SSGD = SRATIO*SSG\n     SSGQ = SSG - SSGD\n   ENDIF\n   SSGD = SRATIO*SSG   ! No radiation scheme has SSGD and SSGQ.\n   SSGQ = SSG - SSGD\n\n   W=2.*1.*HGT\n   VFGS=SVF\n   VFGW=1.-SVF\n   VFWG=(1.-SVF)*(1.-R)/W\n   VFWS=VFWG\n   VFWW=1.-2.*VFWG\n\n!-------------------------------------------------------------------------------\n! Convert unit from MKS to cgs\n! Renew surface and layer temperatures\n!-------------------------------------------------------------------------------\n\n   SX=(SSGD+SSGQ)/697.7/60.  ! downward short wave radition [ly/min]\n   SD=SSGD/697.7/60.         ! downward direct short wave radiation\n   SQ=SSGQ/697.7/60.         ! downward diffuse short wave radiation\n   RX=LLG/697.7/60.          ! downward long wave radiation\n   RHO=RHOO*0.001            ! air density at first atmospheric level\n\n   TRP=TR\n   TBP=TB\n   TGP=TG\n   TCP=TC\n   QCP=QC\n\n   TAV=TA*(1.+0.61*QA)\n   PS=RHOO*287.*TAV/100. ![hPa]\n\n!-------------------------------------------------------------------------------\n! Canopy wind\n!-------------------------------------------------------------------------------\n\n   IF ( ZR + 2. < ZA ) THEN\n     UR=UA*LOG((ZR-ZDC)/Z0C)/LOG((ZA-ZDC)/Z0C)\n     ZC=0.7*ZR\n     XLB=0.4*(ZR-ZDC)\n     ! BB formulation from Inoue (1963)\n     BB = 0.4 * ZR / ( XLB * alog( ( ZR - ZDC ) / Z0C ) )\n     UC=UR*EXP(-BB*(1.-ZC/ZR))\n   ELSE\n     ! PRINT *, 'Warning ZR + 2m  is larger than the 1st WRF level'\n     ZC=ZA/2.\n     UC=UA/2.\n   END IF\n\n!-------------------------------------------------------------------------------\n! Net Short Wave Radiation at roof, wall, and road\n!-------------------------------------------------------------------------------\n\n   SHADOW = .false.\n!   SHADOW = .true.\n\n   IF (SSG > 0.0) THEN\n\n     IF(.NOT.SHADOW) THEN              ! no shadow effects model\n\n       SR1=SX*(1.-ALBR)\n       SG1=SX*VFGS*(1.-ALBG)\n       SB1=SX*VFWS*(1.-ALBB)\n       SG2=SB1*ALBB/(1.-ALBB)*VFGW*(1.-ALBG)\n       SB2=SG1*ALBG/(1.-ALBG)*VFWG*(1.-ALBB)\n\n     ELSE                              ! shadow effects model\n\n       FAI=XLAT*PI/180.\n\n       THEATAS=ABS(ASIN(COSZ))\n       THEATAZ=ABS(ACOS(COSZ))\n\n       SNT=COS(DECLIN)*SIN(OMG)/COS(THEATAS)\n       CNT=(COSZ*SIN(FAI)-SIN(DECLIN))/COS(THEATAS)/COS(FAI)\n\n       HOUI1=(SNT*COS(PI/8.)    -CNT*SIN(PI/8.))\n       HOUI2=(SNT*COS(2.*PI/8.) -CNT*SIN(2.*PI/8.))\n       HOUI3=(SNT*COS(3.*PI/8.) -CNT*SIN(3.*PI/8.))\n       HOUI4=(SNT*COS(4.*PI/8.) -CNT*SIN(4.*PI/8.))\n       HOUI5=(SNT*COS(5.*PI/8.) -CNT*SIN(5.*PI/8.))\n       HOUI6=(SNT*COS(6.*PI/8.) -CNT*SIN(6.*PI/8.))\n       HOUI7=(SNT*COS(7.*PI/8.) -CNT*SIN(7.*PI/8.))\n       HOUI8=(SNT*COS(8.*PI/8.) -CNT*SIN(8.*PI/8.))\n\n       SLX1=HGT*ABS(TAN(THEATAZ))*ABS(HOUI1)\n       SLX2=HGT*ABS(TAN(THEATAZ))*ABS(HOUI2)\n       SLX3=HGT*ABS(TAN(THEATAZ))*ABS(HOUI3)\n       SLX4=HGT*ABS(TAN(THEATAZ))*ABS(HOUI4)\n       SLX5=HGT*ABS(TAN(THEATAZ))*ABS(HOUI5)\n       SLX6=HGT*ABS(TAN(THEATAZ))*ABS(HOUI6)\n       SLX7=HGT*ABS(TAN(THEATAZ))*ABS(HOUI7)\n       SLX8=HGT*ABS(TAN(THEATAZ))*ABS(HOUI8)\n\n       IF(SLX1 > RW) SLX1=RW\n       IF(SLX2 > RW) SLX2=RW\n       IF(SLX3 > RW) SLX3=RW\n       IF(SLX4 > RW) SLX4=RW\n       IF(SLX5 > RW) SLX5=RW\n       IF(SLX6 > RW) SLX6=RW\n       IF(SLX7 > RW) SLX7=RW\n       IF(SLX8 > RW) SLX8=RW\n\n       SLX=(SLX1+SLX2+SLX3+SLX4+SLX5+SLX6+SLX7+SLX8)/8.\n\n       SR1=SD*(1.-ALBR)+SQ*(1.-ALBR)\n       SG1=SD*(RW-SLX)/RW*(1.-ALBG)+SQ*VFGS*(1.-ALBG)\n       SB1=SD*SLX/W*(1.-ALBB)+SQ*VFWS*(1.-ALBB)\n       SG2=SB1*ALBB/(1.-ALBB)*VFGW*(1.-ALBG)\n       SB2=SG1*ALBG/(1.-ALBG)*VFWG*(1.-ALBB)\n\n     END IF\n\n     SR=SR1\n     SG=SG1+SG2\n     SB=SB1+SB2\n\n     SNET=R*SR+W*SB+RW*SG\n\n   ELSE\n\n     SR=0.\n     SG=0.\n     SB=0.\n     SNET=0.\n\n   END IF\n\n!-------------------------------------------------------------------------------\n! Roof\n!-------------------------------------------------------------------------------\n\n!-------------------------------------------------------------------------------\n! CHR, CDR, BETR\n!-------------------------------------------------------------------------------\n\n   ! Z=ZA-ZDC\n   ! BHR=LOG(Z0R/Z0HR)/0.4\n   ! RIBR=(9.8*2./(TA+TRP))*(TA-TRP)*(Z+Z0R)/(UA*UA)\n   ! CALL mos(XXXR,ALPHAR,CDR,BHR,RIBR,Z,Z0R,UA,TA,TRP,RHO)\n\n   ! Alternative option for MOST using SFCDIF routine from Noah\n   ! Virtual temperatures needed by SFCDIF\n   T1VR = TRP* (1.0+ 0.61 * QA)\n   TH2V = (TA + ( 0.0098 * ZA)) * (1.0+ 0.61 * QA)\n\n   ! note that CHR_URB contains UA (=CHR_MOS*UA)\n   RLMO_URB=0.0\n   CALL SFCDIF_URB (ZA,Z0R,T1VR,TH2V,UA,AKANDA_URBAN,CMR_URB,CHR_URB,RLMO_URB,CDR)\n   ALPHAR =  RHO*CP*CHR_URB\n   CHR=ALPHAR/RHO/CP/UA\n\n   IF(RAIN > 1.) BETR=0.7\n\n   IF (TS_SCHEME == 1) THEN\n\n!-------------------------------------------------------------------------------\n! TR  Solving Non-Linear Equation by Newton-Rapson\n! TRL Solving Heat Equation by Tri Diagonal Matrix Algorithm\n!-------------------------------------------------------------------------------\n!      TSC=TRP-273.15\n!      ES=EXP(19.482-4303.4/(TSC+243.5))        ! WMO\n!      ES=6.11*10.**(TETENA*TSC/(TETENB+TSC))   ! Tetens\n!      DESDT=( 6.1078*(2500.-2.4*TSC)/ &        ! Tetens\n!            (0.46151*(TSC+273.15)**2.) )*10.**(7.5*TSC/(237.3+TSC))\n!      ES=6.11*EXP((2.5*10.**6./461.51)*(TRP-273.15)/(273.15*TRP) ) ! Clausius-Clapeyron \n!      DESDT=(2.5*10.**6./461.51)*ES/(TRP**2.)                      ! Clausius-Clapeyron\n!      QS0R=0.622*ES/(PS-0.378*ES)\n!      DQS0RDTR = DESDT*0.622*PS/((PS-0.378*ES)**2.)\n!      DQS0RDTR = 17.269*(273.15-35.86)/((TRP-35.86)**2.)*QS0R\n\n!    TRP=350.\n\n     DO ITERATION=1,20\n\n       ES=6.11*EXP( (2.5*10.**6./461.51)*(TRP-273.15)/(273.15*TRP) )\n       DESDT=(2.5*10.**6./461.51)*ES/(TRP**2.)\n       QS0R=0.622*ES/(PS-0.378*ES)\n       DQS0RDTR = DESDT*0.622*PS/((PS-0.378*ES)**2.)\n\n       RR=EPSR*(RX-SIG*(TRP**4.)/60.)\n       HR=RHO*CP*CHR*UA*(TRP-TA)*100.\n       ELER=RHO*EL*CHR*UA*BETR*(QS0R-QA)*100.\n       G0R=AKSR*(TRP-TRL(1))/(DZR(1)/2.)\n\n       F = SR + RR - HR - ELER - G0R\n\n       DRRDTR = (-4.*EPSR*SIG*TRP**3.)/60.\n       DHRDTR = RHO*CP*CHR*UA*100.\n       DELERDTR = RHO*EL*CHR*UA*BETR*DQS0RDTR*100.\n       DG0RDTR =  2.*AKSR/DZR(1)\n\n       DFDT = DRRDTR - DHRDTR - DELERDTR - DG0RDTR\n       DTR = F/DFDT\n\n       TR = TRP - DTR\n       TRP = TR\n\n       IF( ABS(F) < 0.000001 .AND. ABS(DTR) < 0.000001 ) EXIT\n\n     END DO\n\n! multi-layer heat equation model\n\n     CALL multi_layer(num_roof_layers,BOUNDR,G0R,CAPR,AKSR,TRL,DZR,DELT,TRLEND)\n\n   ELSE\n\n     ES=6.11*EXP( (2.5*10.**6./461.51)*(TRP-273.15)/(273.15*TRP) )\n     QS0R=0.622*ES/(PS-0.378*ES)\n\n     RR=EPSR*(RX-SIG*(TRP**4.)/60.)\n     HR=RHO*CP*CHR*UA*(TRP-TA)*100.\n     ELER=RHO*EL*CHR*UA*BETR*(QS0R-QA)*100.\n     G0R=SR+RR-HR-ELER\n\n     CALL force_restore(CAPR,AKSR,DELT,SR,RR,HR,ELER,TRLEND,TRP,TR)\n\n     TRP=TR\n\n   END IF\n\n   FLXTHR=HR/RHO/CP/100.\n   FLXHUMR=ELER/RHO/EL/100.\n\n!-------------------------------------------------------------------------------\n!  Wall and Road\n!-------------------------------------------------------------------------------\n\n!-------------------------------------------------------------------------------\n!  CHC, CHB, CDB, BETB, CHG, CDG, BETG\n!-------------------------------------------------------------------------------\n\n   ! Z=ZA-ZDC\n   ! BHC=LOG(Z0C/Z0HC)/0.4\n   ! RIBC=(9.8*2./(TA+TCP))*(TA-TCP)*(Z+Z0C)/(UA*UA)\n   !\n   ! CALL mos(XXXC,ALPHAC,CDC,BHC,RIBC,Z,Z0C,UA,TA,TCP,RHO)\n   ! Virtual temperatures needed by SFCDIF routine from Noah\n\n   T1VC = TCP* (1.0+ 0.61 * QA)\n   RLMO_URB=0.0\n   CALL SFCDIF_URB(ZA,Z0C,T1VC,TH2V,UA,AKANDA_URBAN,CMC_URB,CHC_URB,RLMO_URB,CDC)\n   ALPHAC =  RHO*CP*CHC_URB\n\n   IF (CH_SCHEME == 1) THEN\n\n     Z=ZDC\n     BHB=LOG(Z0B/Z0HB)/0.4\n     BHG=LOG(Z0G/Z0HG)/0.4\n     RIBB=(9.8*2./(TCP+TBP))*(TCP-TBP)*(Z+Z0B)/(UC*UC)\n     RIBG=(9.8*2./(TCP+TGP))*(TCP-TGP)*(Z+Z0G)/(UC*UC)\n\n     CALL mos(XXXB,ALPHAB,CDB,BHB,RIBB,Z,Z0B,UC,TCP,TBP,RHO)\n     CALL mos(XXXG,ALPHAG,CDG,BHG,RIBG,Z,Z0G,UC,TCP,TGP,RHO)\n\n   ELSE\n\n     ALPHAB=RHO*CP*(6.15+4.18*UC)/1200.\n     IF(UC > 5.) ALPHAB=RHO*CP*(7.51*UC**0.78)/1200.\n     ALPHAG=RHO*CP*(6.15+4.18*UC)/1200.\n     IF(UC > 5.) ALPHAG=RHO*CP*(7.51*UC**0.78)/1200.\n\n   END IF\n\n   CHC=ALPHAC/RHO/CP/UA\n   CHB=ALPHAB/RHO/CP/UC\n   CHG=ALPHAG/RHO/CP/UC\n\n   BETB=0.0\n   IF(RAIN > 1.) BETG=0.7\n\n   IF (TS_SCHEME == 1) THEN\n\n!-------------------------------------------------------------------------------\n!  TB, TG  Solving Non-Linear Simultaneous Equation by Newton-Rapson\n!  TBL,TGL Solving Heat Equation by Tri Diagonal Matrix Algorithm\n!-------------------------------------------------------------------------------\n\n!    TBP=350.\n!    TGP=350.\n#ifdef _HRLDAS_URBAN_\n     converged = .FALSE.\n     converged2 = .FALSE.\n     diverging = .FALSE.\n     converge_coefficient = 0.8\n     tbp_hold = tbp\n     tgp_hold = tgp\n     tcp_hold = tcp\n     qcp_hold = qcp\n120  continue\n#endif\n\n#ifdef _HRLDAS_URBAN_\n     DO ITERATION=1,100\n#else\n     DO ITERATION=1,20\n#endif\n\n       ES=6.11*EXP( (2.5*10.**6./461.51)*(TBP-273.15)/(273.15*TBP) )\n       DESDT=(2.5*10.**6./461.51)*ES/(TBP**2.)\n       QS0B=0.622*ES/(PS-0.378*ES)\n       DQS0BDTB=DESDT*0.622*PS/((PS-0.378*ES)**2.)\n\n       ES=6.11*EXP( (2.5*10.**6./461.51)*(TGP-273.15)/(273.15*TGP) )\n       DESDT=(2.5*10.**6./461.51)*ES/(TGP**2.)\n       QS0G=0.622*ES/(PS-0.378*ES)\n       DQS0GDTG=DESDT*0.22*PS/((PS-0.378*ES)**2.)\n\n       RG1=EPSG*( RX*VFGS          &\n       +EPSB*VFGW*SIG*TBP**4./60.  &\n       -SIG*TGP**4./60. )\n\n       RB1=EPSB*( RX*VFWS         &\n       +EPSG*VFWG*SIG*TGP**4./60. &\n       +EPSB*VFWW*SIG*TBP**4./60. &\n       -SIG*TBP**4./60. )\n\n       RG2=EPSG*( (1.-EPSB)*(1.-SVF)*VFWS*RX                  &\n       +(1.-EPSB)*(1.-SVF)*VFWG*EPSG*SIG*TGP**4./60.          &\n       +EPSB*(1.-EPSB)*(1.-SVF)*(1.-2.*VFWS)*SIG*TBP**4./60. )\n\n       RB2=EPSB*( (1.-EPSG)*VFWG*VFGS*RX                          &\n       +(1.-EPSG)*EPSB*VFGW*VFWG*SIG*(TBP**4.)/60.                &\n       +(1.-EPSB)*VFWS*(1.-2.*VFWS)*RX                            &\n       +(1.-EPSB)*VFWG*(1.-2.*VFWS)*EPSG*SIG*EPSG*TGP**4./60.     &\n       +EPSB*(1.-EPSB)*(1.-2.*VFWS)*(1.-2.*VFWS)*SIG*TBP**4./60. )\n\n       RG=RG1+RG2\n       RB=RB1+RB2\n\n       DRBDTB1=EPSB*(4.*EPSB*SIG*TB**3.*VFWW-4.*SIG*TB**3.)/60.\n       DRBDTG1=EPSB*(4.*EPSG*SIG*TG**3.*VFWG)/60.\n       DRBDTB2=EPSB*(4.*(1.-EPSG)*EPSB*SIG*TB**3.*VFGW*VFWG &\n               +4.*EPSB*(1.-EPSB)*SIG*TB**3.*VFWW*VFWW)/60.\n       DRBDTG2=EPSB*(4.*(1.-EPSB)*EPSG*SIG*TG**3.*VFWG*VFWW)/60.\n\n       DRGDTB1=EPSG*(4.*EPSB*SIG*TB**3.*VFGW)/60.\n       DRGDTG1=EPSG*(-4.*SIG*TG**3.)/60.\n       DRGDTB2=EPSG*(4.*EPSB*(1.-EPSB)*SIG*TB**3.*VFWW*VFGW)/60.\n       DRGDTG2=EPSG*(4.*(1.-EPSB)*EPSG*SIG*TG**3.*VFWG*VFGW)/60.\n\n       DRBDTB=DRBDTB1+DRBDTB2\n       DRBDTG=DRBDTG1+DRBDTG2\n       DRGDTB=DRGDTB1+DRGDTB2\n       DRGDTG=DRGDTG1+DRGDTG2\n\n       HB=RHO*CP*CHB*UC*(TBP-TCP)*100.\n       HG=RHO*CP*CHG*UC*(TGP-TCP)*100.\n\n       DTCDTB=W*ALPHAB/(RW*ALPHAC+RW*ALPHAG+W*ALPHAB)\n       DTCDTG=RW*ALPHAG/(RW*ALPHAC+RW*ALPHAG+W*ALPHAB)\n\n       DHBDTB=RHO*CP*CHB*UC*(1.-DTCDTB)*100.\n       DHBDTG=RHO*CP*CHB*UC*(0.-DTCDTG)*100.\n       DHGDTG=RHO*CP*CHG*UC*(1.-DTCDTG)*100.\n       DHGDTB=RHO*CP*CHG*UC*(0.-DTCDTB)*100.\n\n       ELEB=RHO*EL*CHB*UC*BETB*(QS0B-QCP)*100.\n       ELEG=RHO*EL*CHG*UC*BETG*(QS0G-QCP)*100.\n\n       DQCDTB=W*ALPHAB*BETB*DQS0BDTB/(RW*ALPHAC+RW*ALPHAG*BETG+W*ALPHAB*BETB)\n       DQCDTG=RW*ALPHAG*BETG*DQS0GDTG/(RW*ALPHAC+RW*ALPHAG*BETG+W*ALPHAB*BETB)\n\n       DELEBDTB=RHO*EL*CHB*UC*BETB*(DQS0BDTB-DQCDTB)*100.\n       DELEBDTG=RHO*EL*CHB*UC*BETB*(0.-DQCDTG)*100.\n       DELEGDTG=RHO*EL*CHG*UC*BETG*(DQS0GDTG-DQCDTG)*100.\n       DELEGDTB=RHO*EL*CHG*UC*BETG*(0.-DQCDTB)*100.\n\n       G0B=AKSB*(TBP-TBL(1))/(DZB(1)/2.)\n       G0G=AKSG*(TGP-TGL(1))/(DZG(1)/2.)\n\n       DG0BDTB=2.*AKSB/DZB(1)\n       DG0BDTG=0.\n       DG0GDTG=2.*AKSG/DZG(1)\n       DG0GDTB=0.\n\n       F = SB + RB - HB - ELEB - G0B\n       FX = DRBDTB - DHBDTB - DELEBDTB - DG0BDTB\n       FY = DRBDTG - DHBDTG - DELEBDTG - DG0BDTG\n\n       GF = SG + RG - HG - ELEG - G0G\n       GX = DRGDTB - DHGDTB - DELEGDTB - DG0GDTB\n       GY = DRGDTG - DHGDTG - DELEGDTG - DG0GDTG\n\n#ifdef _HRLDAS_URBAN_\n       DTB = converge_coefficient * (GF*FY-F*GY)/(FX*GY-GX*FY)\n       DTG = -(GF*converge_coefficient+GX*DTB)/GY\n#else\n       DTB =  (GF*FY-F*GY)/(FX*GY-GX*FY)\n       DTG = -(GF+GX*DTB)/GY\n#endif\n\n       TB = TBP + DTB\n       TG = TGP + DTG\n\n#ifdef _HRLDAS_URBAN_\n       !KWM If things are diverging, get us out of here, and try again\n       if ( (abs(DTB) > 20.0 ) .or. (abs(DTG) > 20.0) ) then\n          diverging = .TRUE.\n          exit\n       endif\n#endif\n\n       TBP = TB\n       TGP = TG\n\n       TC1=RW*ALPHAC+RW*ALPHAG+W*ALPHAB\n       TC2=RW*ALPHAC*TA+RW*ALPHAG*TGP+W*ALPHAB*TBP\n       TC=TC2/TC1\n\n       QC1=RW*ALPHAC+RW*ALPHAG*BETG+W*ALPHAB*BETB\n       QC2=RW*ALPHAC*QA+RW*ALPHAG*BETG*QS0G+W*ALPHAB*BETB*QS0B\n       QC=QC2/QC1\n\n       DTC=TCP - TC\n       TCP=TC\n       QCP=QC\n\n#ifdef _HRLDAS_URBAN_\n       !KWM  Make things depend on the resolution of the machine-representable numbers\n       !KWM  at the size of the temperature values, rather than depending on some \n       !KWM  explicitly-defined epsilon.\n       if ( (abs(DTB) < spacing(TBP)*1.E2)  .and. (abs(DTG) < spacing(TGP)*1.E2) ) THEN   \n          converged = .TRUE.\n          converged2 = .TRUE.\n          EXIT\n       ENDIF\n#else\n       IF( ABS(F) < 0.000001 .AND. ABS(DTB) < 0.000001 &\n        .AND. ABS(GF) < 0.000001 .AND. ABS(DTG) < 0.000001 &\n        .AND. ABS(DTC) < 0.000001) EXIT\n#endif\n\n     END DO\n\n#ifdef _HRLDAS_URBAN_\n     if (.not. converged) then\n        ! Go back and try again with smaller converge_coefficient\n        converge_coefficient = 0.5\n        tbp = tbp_hold\n        tgp = tgp_hold\n        tcp = tcp_hold\n        qcp = qcp_hold\n        converged = .TRUE. ! Set this so the next iteration will exit, no matter.\n        goto 120\n     endif\n\n!KWM     if (.not. converged2) then\n!KWM        print*, 'Not Converged.'\n!KWM     endif\n#endif\n\n     CALL multi_layer(num_wall_layers,BOUNDB,G0B,CAPB,AKSB,TBL,DZB,DELT,TBLEND)\n\n     CALL multi_layer(num_road_layers,BOUNDG,G0G,CAPG,AKSG,TGL,DZG,DELT,TGLEND)\n\n   ELSE\n\n!-------------------------------------------------------------------------------\n!  TB, TG  by Force-Restore Method\n!-------------------------------------------------------------------------------\n\n       ES=6.11*EXP((2.5*10.**6./461.51)*(TBP-273.15)/(273.15*TBP) )\n       QS0B=0.622*ES/(PS-0.378*ES)\n\n       ES=6.11*EXP((2.5*10.**6./461.51)*(TGP-273.15)/(273.15*TGP) )\n       QS0G=0.622*ES/(PS-0.378*ES)\n\n       RG1=EPSG*( RX*VFGS             &\n       +EPSB*VFGW*SIG*TBP**4./60.     &\n       -SIG*TGP**4./60. )\n\n       RB1=EPSB*( RX*VFWS &\n       +EPSG*VFWG*SIG*TGP**4./60. &\n       +EPSB*VFWW*SIG*TBP**4./60. &\n       -SIG*TBP**4./60. )\n\n       RG2=EPSG*( (1.-EPSB)*(1.-SVF)*VFWS*RX                   &\n       +(1.-EPSB)*(1.-SVF)*VFWG*EPSG*SIG*TGP**4./60.           &\n       +EPSB*(1.-EPSB)*(1.-SVF)*(1.-2.*VFWS)*SIG*TBP**4./60. )\n\n       RB2=EPSB*( (1.-EPSG)*VFWG*VFGS*RX                          &\n       +(1.-EPSG)*EPSB*VFGW*VFWG*SIG*(TBP**4.)/60.                &\n       +(1.-EPSB)*VFWS*(1.-2.*VFWS)*RX                            &\n       +(1.-EPSB)*VFWG*(1.-2.*VFWS)*EPSG*SIG*EPSG*TGP**4./60.     &\n       +EPSB*(1.-EPSB)*(1.-2.*VFWS)*(1.-2.*VFWS)*SIG*TBP**4./60. )\n\n       RG=RG1+RG2\n       RB=RB1+RB2\n\n       HB=RHO*CP*CHB*UC*(TBP-TCP)*100.\n       ELEB=RHO*EL*CHB*UC*BETB*(QS0B-QCP)*100.\n       G0B=SB+RB-HB-ELEB\n\n       HG=RHO*CP*CHG*UC*(TGP-TCP)*100.\n       ELEG=RHO*EL*CHG*UC*BETG*(QS0G-QCP)*100.\n       G0G=SG+RG-HG-ELEG\n\n       CALL force_restore(CAPB,AKSB,DELT,SB,RB,HB,ELEB,TBLEND,TBP,TB)\n       CALL force_restore(CAPG,AKSG,DELT,SG,RG,HG,ELEG,TGLEND,TGP,TG)\n\n       TBP=TB\n       TGP=TG\n\n       TC1=RW*ALPHAC+RW*ALPHAG+W*ALPHAB\n       TC2=RW*ALPHAC*TA+RW*ALPHAG*TGP+W*ALPHAB*TBP\n       TC=TC2/TC1\n\n       QC1=RW*ALPHAC+RW*ALPHAG*BETG+W*ALPHAB*BETB\n       QC2=RW*ALPHAC*QA+RW*ALPHAG*BETG*QS0G+W*ALPHAB*BETB*QS0B\n       QC=QC2/QC1\n\n       TCP=TC\n       QCP=QC\n\n   END IF\n\n\n   FLXTHB=HB/RHO/CP/100.\n   FLXHUMB=ELEB/RHO/EL/100.\n   FLXTHG=HG/RHO/CP/100.\n   FLXHUMG=ELEG/RHO/EL/100.\n\n!-------------------------------------------------------------------------------\n! Total Fluxes from Urban Canopy\n!-------------------------------------------------------------------------------\n\n   FLXUV  = ( R*CDR + RW*CDC )*UA*UA\n! Miao, 2007/01/17, cal. ah\n   if(ahoption==1) then\n     FLXTH  = ( R*FLXTHR  + W*FLXTHB  + RW*FLXTHG ) + AH/RHOO/CPP\n   else\n     FLXTH  = ( R*FLXTHR  + W*FLXTHB  + RW*FLXTHG )\n   endif\n   FLXHUM = ( R*FLXHUMR + W*FLXHUMB + RW*FLXHUMG )\n   FLXG =   ( R*G0R + W*G0B + RW*G0G )\n   LNET =     R*RR + W*RB + RW*RG\n\n!----------------------------------------------------------------------------\n! Convert Unit: FLUXES and u* T* q*  --> WRF\n!----------------------------------------------------------------------------\n\n   SH    = FLXTH  * RHOO * CPP    ! Sensible heat flux          [W/m/m]\n   LH    = FLXHUM * RHOO * ELL    ! Latent heat flux            [W/m/m]\n   LH_KINEMATIC = FLXHUM * RHOO   ! Latent heat, Kinematic      [kg/m/m/s]\n   LW    = LLG - (LNET*697.7*60.) ! Upward longwave radiation   [W/m/m]\n   SW    = SSG - (SNET*697.7*60.) ! Upward shortwave radiation  [W/m/m]\n   ALB   = 0.\n   IF( ABS(SSG) > 0.0001) ALB = SW/SSG ! Effective albedo [-]\n   G = -FLXG*697.7*60.            ! [W/m/m]\n   RN = (SNET+LNET)*697.7*60.     ! Net radiation [W/m/m]\n\n   UST = SQRT(FLXUV)              ! u* [m/s]\n   TST = -FLXTH/UST               ! T* [K]\n   QST = -FLXHUM/UST              ! q* [-]\n\n!------------------------------------------------------\n!  diagnostic GRID AVERAGED  PSIM  PSIH  TS QS --> WRF\n!------------------------------------------------------\n\n   Z0 = Z0C\n   Z0H = Z0HC\n   Z = ZA - ZDC\n\n   XXX = 0.4*9.81*Z*TST/TA/UST/UST\n\n   IF ( XXX >= 1. ) XXX = 1.\n   IF ( XXX <= -5. ) XXX = -5.\n\n   IF ( XXX > 0 ) THEN\n     PSIM = -5. * XXX\n     PSIH = -5. * XXX\n   ELSE\n     X = (1.-16.*XXX)**0.25\n     PSIM = 2.*ALOG((1.+X)/2.) + ALOG((1.+X*X)/2.) - 2.*ATAN(X) + PI/2.\n     PSIH = 2.*ALOG((1.+X*X)/2.)\n   END IF\n\n   GZ1OZ0 = ALOG(Z/Z0)\n   CD = 0.4**2./(ALOG(Z/Z0)-PSIM)**2.\n!\n!m   CH = 0.4**2./(ALOG(Z/Z0)-PSIM)/(ALOG(Z/Z0H)-PSIH)\n!m   CHS = 0.4*UST/(ALOG(Z/Z0H)-PSIH)\n!m   TS = TA + FLXTH/CH/UA    ! surface potential temp (flux temp)\n!m   QS = QA + FLXHUM/CH/UA   ! surface humidity\n!\n   TS = TA + FLXTH/CHS    ! surface potential temp (flux temp)\n   QS = QA + FLXHUM/CHS   ! surface humidity\n\n!-------------------------------------------------------\n!  diagnostic  GRID AVERAGED  U10  V10  TH2  Q2 --> WRF\n!-------------------------------------------------------\n\n   XXX2 = (2./Z)*XXX\n   IF ( XXX2 >= 1. ) XXX2 = 1.\n   IF ( XXX2 <= -5. ) XXX2 = -5.\n\n   IF ( XXX2 > 0 ) THEN\n      PSIM2 = -5. * XXX2\n      PSIH2 = -5. * XXX2\n   ELSE\n      X = (1.-16.*XXX2)**0.25\n      PSIM2 = 2.*ALOG((1.+X)/2.) + ALOG((1.+X*X)/2.) - 2.*ATAN(X) + 2.*ATAN(1.)\n      PSIH2 = 2.*ALOG((1.+X*X)/2.)\n   END IF\n!\n!m   CHS2 = 0.4*UST/(ALOG(2./Z0H)-PSIH2)\n!\n\n   XXX10 = (10./Z)*XXX\n   IF ( XXX10 >= 1. ) XXX10 = 1.\n   IF ( XXX10 <= -5. ) XXX10 = -5.\n\n   IF ( XXX10 > 0 ) THEN\n      PSIM10 = -5. * XXX10\n      PSIH10 = -5. * XXX10\n   ELSE\n      X = (1.-16.*XXX10)**0.25\n      PSIM10 = 2.*ALOG((1.+X)/2.) + ALOG((1.+X*X)/2.) - 2.*ATAN(X) + 2.*ATAN(1.)\n      PSIH10 = 2.*ALOG((1.+X*X)/2.)\n   END IF\n\n   PSIX = ALOG(Z/Z0) - PSIM\n   PSIT = ALOG(Z/Z0H) - PSIH\n\n   PSIX2 = ALOG(2./Z0) - PSIM2\n   PSIT2 = ALOG(2./Z0H) - PSIH2\n\n   PSIX10 = ALOG(10./Z0) - PSIM10\n   PSIT10 = ALOG(10./Z0H) - PSIH10\n\n   U10 = U1 * (PSIX10/PSIX)       ! u at 10 m [m/s]\n   V10 = V1 * (PSIX10/PSIX)       ! v at 10 m [m/s]\n\n!   TH2 = TS + (TA-TS)*(PSIT2/PSIT)   ! potential temp at 2 m [K]\n!  TH2 = TS + (TA-TS)*(PSIT2/PSIT)   ! Fei: this seems to be temp (not potential) at 2 m [K]\n!Fei: consistant with M-O theory\n   TH2 = TS + (TA-TS) *(CHS/CHS2)\n\n   Q2 = QS + (QA-QS)*(PSIT2/PSIT)    ! humidity at 2 m       [-]\n\n!   TS = (LW/SIG_SI/0.88)**0.25       ! Radiative temperature [K]\n\n   END SUBROUTINE urban\n!===============================================================================\n!\n!  mos\n!\n!===============================================================================\n   SUBROUTINE mos(XXX,ALPHA,CD,B1,RIB,Z,Z0,UA,TA,TSF,RHO)\n\n!  XXX:   z/L (requires iteration by Newton-Rapson method)\n!  B1:    Stanton number\n!  PSIM:  = PSIX of LSM\n!  PSIH:  = PSIT of LSM\n\n   IMPLICIT NONE\n\n   REAL, PARAMETER     :: CP=0.24\n   REAL, INTENT(IN)    :: B1, Z, Z0, UA, TA, TSF, RHO\n   REAL, INTENT(OUT)   :: ALPHA, CD\n   REAL, INTENT(INOUT) :: XXX, RIB\n   REAL                :: XXX0, X, X0, FAIH, DPSIM, DPSIH\n   REAL                :: F, DF, XXXP, US, TS, AL, XKB, DD, PSIM, PSIH\n   INTEGER             :: NEWT\n   INTEGER, PARAMETER  :: NEWT_END=10\n\n   IF(RIB <= -15.) RIB=-15.\n\n   IF(RIB < 0.) THEN\n\n      DO NEWT=1,NEWT_END\n\n        IF(XXX >= 0.) XXX=-1.E-3\n\n        XXX0=XXX*Z0/(Z+Z0)\n\n        X=(1.-16.*XXX)**0.25\n        X0=(1.-16.*XXX0)**0.25\n\n        PSIM=ALOG((Z+Z0)/Z0) &\n            -ALOG((X+1.)**2.*(X**2.+1.)) &\n            +2.*ATAN(X) &\n            +ALOG((X+1.)**2.*(X0**2.+1.)) &\n            -2.*ATAN(X0)\n        FAIH=1./SQRT(1.-16.*XXX)\n        PSIH=ALOG((Z+Z0)/Z0)+0.4*B1 &\n            -2.*ALOG(SQRT(1.-16.*XXX)+1.) &\n            +2.*ALOG(SQRT(1.-16.*XXX0)+1.)\n\n        DPSIM=(1.-16.*XXX)**(-0.25)/XXX &\n             -(1.-16.*XXX0)**(-0.25)/XXX\n        DPSIH=1./SQRT(1.-16.*XXX)/XXX &\n             -1./SQRT(1.-16.*XXX0)/XXX\n\n        F=RIB*PSIM**2./PSIH-XXX\n\n        DF=RIB*(2.*DPSIM*PSIM*PSIH-DPSIH*PSIM**2.) &\n          /PSIH**2.-1.\n\n        XXXP=XXX\n        XXX=XXXP-F/DF\n        IF(XXX <= -10.) XXX=-10.\n\n      END DO\n\n   ELSE IF(RIB >= 0.142857) THEN\n\n      XXX=0.714\n      PSIM=ALOG((Z+Z0)/Z0)+7.*XXX\n      PSIH=PSIM+0.4*B1\n\n   ELSE\n\n      AL=ALOG((Z+Z0)/Z0)\n      XKB=0.4*B1\n      DD=-4.*RIB*7.*XKB*AL+(AL+XKB)**2.\n      IF(DD <= 0.) DD=0.\n      XXX=(AL+XKB-2.*RIB*7.*AL-SQRT(DD))/(2.*(RIB*7.**2-7.))\n      PSIM=ALOG((Z+Z0)/Z0)+7.*MIN(XXX,0.714)\n      PSIH=PSIM+0.4*B1\n\n   END IF\n\n   US=0.4*UA/PSIM             ! u*\n   IF(US <= 0.01) US=0.01\n   TS=0.4*(TA-TSF)/PSIH       ! T*\n\n   CD=US*US/UA**2.            ! CD\n   ALPHA=RHO*CP*0.4*US/PSIH   ! RHO*CP*CH*U\n\n   RETURN\n   END SUBROUTINE mos\n!===============================================================================\n!\n!  louis79\n!\n!===============================================================================\n   SUBROUTINE louis79(ALPHA,CD,RIB,Z,Z0,UA,RHO)\n\n   IMPLICIT NONE\n\n   REAL, PARAMETER     :: CP=0.24\n   REAL, INTENT(IN)    :: Z, Z0, UA, RHO\n   REAL, INTENT(OUT)   :: ALPHA, CD\n   REAL, INTENT(INOUT) :: RIB\n   REAL                :: A2, XX, CH, CMB, CHB\n\n   A2=(0.4/ALOG(Z/Z0))**2.\n\n   IF(RIB <= -15.) RIB=-15.\n\n   IF(RIB >= 0.0) THEN\n      IF(RIB >= 0.142857) THEN\n         XX=0.714\n      ELSE\n         XX=RIB*LOG(Z/Z0)/(1.-7.*RIB)\n      END IF\n      CH=0.16/0.74/(LOG(Z/Z0)+7.*MIN(XX,0.714))**2.\n      CD=0.16/(LOG(Z/Z0)+7.*MIN(XX,0.714))**2.\n   ELSE\n      CMB=7.4*A2*9.4*SQRT(Z/Z0)\n      CHB=5.3*A2*9.4*SQRT(Z/Z0)\n      CH=A2/0.74*(1.-9.4*RIB/(1.+CHB*SQRT(-RIB)))\n      CD=A2*(1.-9.4*RIB/(1.+CHB*SQRT(-RIB)))\n   END IF\n\n   ALPHA=RHO*CP*CH*UA\n\n   RETURN\n   END SUBROUTINE louis79\n!===============================================================================\n!\n!  louis82\n!\n!===============================================================================\n   SUBROUTINE louis82(ALPHA,CD,RIB,Z,Z0,UA,RHO)\n\n   IMPLICIT NONE\n\n   REAL, PARAMETER     :: CP=0.24\n   REAL, INTENT(IN)    :: Z, Z0, UA, RHO\n   REAL, INTENT(OUT)   :: ALPHA, CD\n   REAL, INTENT(INOUT) :: RIB\n   REAL                :: A2, FM, FH, CH, CHH\n\n   A2=(0.4/ALOG(Z/Z0))**2.\n\n   IF(RIB <= -15.) RIB=-15.\n\n   IF(RIB >= 0.0) THEN\n      FM=1./((1.+(2.*5.*RIB)/SQRT(1.+5.*RIB)))\n      FH=1./(1.+(3.*5.*RIB)*SQRT(1.+5.*RIB))\n      CH=A2*FH\n      CD=A2*FM\n   ELSE\n      CHH=5.*3.*5.*A2*SQRT(Z/Z0)\n      FM=1.-(2.*5.*RIB)/(1.+3.*5.*5.*A2*SQRT(Z/Z0+1.)*(-RIB))\n      FH=1.-(3.*5.*RIB)/(1.+CHH*SQRT(-RIB))\n      CH=A2*FH\n      CD=A2*FM\n   END IF\n\n   ALPHA=RHO*CP*CH*UA\n\n   RETURN\n   END SUBROUTINE louis82\n!===============================================================================\n!\n!  multi_layer\n!\n!===============================================================================\n   SUBROUTINE multi_layer(KM,BOUND,G0,CAP,AKS,TSL,DZ,DELT,TSLEND)\n\n   IMPLICIT NONE\n\n   REAL, INTENT(IN)                   :: G0\n\n   REAL, INTENT(IN)                   :: CAP\n\n   REAL, INTENT(IN)                   :: AKS\n\n   REAL, INTENT(IN)                   :: DELT      ! Time step [ s ]\n\n   REAL, INTENT(IN)                   :: TSLEND\n\n   INTEGER, INTENT(IN)                :: KM\n\n   INTEGER, INTENT(IN)                :: BOUND\n\n   REAL, DIMENSION(KM), INTENT(IN)    :: DZ\n\n   REAL, DIMENSION(KM), INTENT(INOUT) :: TSL\n\n   REAL, DIMENSION(KM)                :: A, B, C, D, X, P, Q\n\n   REAL                               :: DZEND\n\n   INTEGER                            :: K\n\n   DZEND=DZ(KM)\n\n   A(1) = 0.0\n\n   B(1) = CAP*DZ(1)/DELT &\n          +2.*AKS/(DZ(1)+DZ(2))\n   C(1) = -2.*AKS/(DZ(1)+DZ(2))\n   D(1) = CAP*DZ(1)/DELT*TSL(1) + G0\n\n   DO K=2,KM-1\n      A(K) = -2.*AKS/(DZ(K-1)+DZ(K))\n      B(K) = CAP*DZ(K)/DELT + 2.*AKS/(DZ(K-1)+DZ(K)) + 2.*AKS/(DZ(K)+DZ(K+1)) \n      C(K) = -2.*AKS/(DZ(K)+DZ(K+1))\n      D(K) = CAP*DZ(K)/DELT*TSL(K)\n   END DO\n\n   IF(BOUND == 1) THEN                  ! Flux=0\n      A(KM) = -2.*AKS/(DZ(KM-1)+DZ(KM))\n      B(KM) = CAP*DZ(KM)/DELT + 2.*AKS/(DZ(KM-1)+DZ(KM))\n      C(KM) = 0.0\n      D(KM) = CAP*DZ(KM)/DELT*TSL(KM)\n   ELSE                                 ! T=constant\n      A(KM) = -2.*AKS/(DZ(KM-1)+DZ(KM))\n      B(KM) = CAP*DZ(KM)/DELT + 2.*AKS/(DZ(KM-1)+DZ(KM)) + 2.*AKS/(DZ(KM)+DZEND) \n      C(KM) = 0.0\n      D(KM) = CAP*DZ(KM)/DELT*TSL(KM) + 2.*AKS*TSLEND/(DZ(KM)+DZEND)\n   END IF\n\n   P(1) = -C(1)/B(1)\n   Q(1) =  D(1)/B(1)\n\n   DO K=2,KM\n      P(K) = -C(K)/(A(K)*P(K-1)+B(K))\n      Q(K) = (-A(K)*Q(K-1)+D(K))/(A(K)*P(K-1)+B(K))\n   END DO\n\n   X(KM) = Q(KM)\n\n   DO K=KM-1,1,-1\n      X(K) = P(K)*X(K+1)+Q(K)\n   END DO\n\n   DO K=1,KM\n      TSL(K) = X(K)\n   END DO\n\n   RETURN\n   END SUBROUTINE multi_layer\n!===============================================================================\n!\n!  subroutine read_param\n!\n!===============================================================================\n   SUBROUTINE read_param(UTYPE,                                        & ! in\n                         ZR,SIGMA_ZED,Z0C,Z0HC,ZDC,SVF,R,RW,HGT,AH,    & ! out\n                         CAPR,CAPB,CAPG,AKSR,AKSB,AKSG,ALBR,ALBB,ALBG, & ! out\n                         EPSR,EPSB,EPSG,Z0R,Z0B,Z0G,Z0HB,Z0HG,         & ! out\n                         BETR,BETB,BETG,TRLEND,TBLEND,TGLEND,          & ! out\n!for BEP\n                         NUMDIR, STREET_DIRECTION, STREET_WIDTH,       & ! out\n                         BUILDING_WIDTH, NUMHGT, HEIGHT_BIN,           & ! out\n                         HPERCENT_BIN,                                 & ! out\n!end BEP\n                         BOUNDR,BOUNDB,BOUNDG,CH_SCHEME,TS_SCHEME,     & ! out\n                         AKANDA_URBAN)                                   ! out\n\n   INTEGER, INTENT(IN)  :: UTYPE\n\n   REAL, INTENT(OUT)    :: ZR,Z0C,Z0HC,ZDC,SVF,R,RW,HGT,AH,              &\n                           CAPR,CAPB,CAPG,AKSR,AKSB,AKSG,ALBR,ALBB,ALBG, &\n                           SIGMA_ZED,                                    &\n                           EPSR,EPSB,EPSG,Z0R,Z0B,Z0G,Z0HB,Z0HG,         &\n                           BETR,BETB,BETG,TRLEND,TBLEND,TGLEND\n   REAL, INTENT(OUT)    :: AKANDA_URBAN\n!for BEP\n   INTEGER,                     INTENT(OUT) :: NUMDIR\n   REAL,    DIMENSION(MAXDIRS), INTENT(OUT) :: STREET_DIRECTION\n   REAL,    DIMENSION(MAXDIRS), INTENT(OUT) :: STREET_WIDTH\n   REAL,    DIMENSION(MAXDIRS), INTENT(OUT) :: BUILDING_WIDTH\n   INTEGER,                     INTENT(OUT) :: NUMHGT\n   REAL,    DIMENSION(MAXHGTS), INTENT(OUT) :: HEIGHT_BIN\n   REAL,    DIMENSION(MAXHGTS), INTENT(OUT) :: HPERCENT_BIN\n\n!end BEP\n\n   INTEGER, INTENT(OUT) :: BOUNDR,BOUNDB,BOUNDG,CH_SCHEME,TS_SCHEME\n\n   ZR =     ZR_TBL(UTYPE)\n   SIGMA_ZED = SIGMA_ZED_TBL(UTYPE)\n   Z0C=     Z0C_TBL(UTYPE)\n   Z0HC=    Z0HC_TBL(UTYPE)\n   ZDC=     ZDC_TBL(UTYPE)\n   SVF=     SVF_TBL(UTYPE)\n   R=       R_TBL(UTYPE)\n   RW=      RW_TBL(UTYPE)\n   HGT=     HGT_TBL(UTYPE)\n   AH=      AH_TBL(UTYPE)\n   BETR=    BETR_TBL(UTYPE)\n   BETB=    BETB_TBL(UTYPE)\n   BETG=    BETG_TBL(UTYPE)\n\n!m   FRC_URB= FRC_URB_TBL(UTYPE)\n\n   CAPR=    CAPR_TBL(UTYPE)\n   CAPB=    CAPB_TBL(UTYPE)\n   CAPG=    CAPG_TBL(UTYPE)\n   AKSR=    AKSR_TBL(UTYPE)\n   AKSB=    AKSB_TBL(UTYPE)\n   AKSG=    AKSG_TBL(UTYPE)\n   ALBR=    ALBR_TBL(UTYPE)\n   ALBB=    ALBB_TBL(UTYPE)\n   ALBG=    ALBG_TBL(UTYPE)\n   EPSR=    EPSR_TBL(UTYPE)\n   EPSB=    EPSB_TBL(UTYPE)\n   EPSG=    EPSG_TBL(UTYPE)\n   Z0R=     Z0R_TBL(UTYPE)\n   Z0B=     Z0B_TBL(UTYPE)\n   Z0G=     Z0G_TBL(UTYPE)\n   Z0HB=    Z0HB_TBL(UTYPE)\n   Z0HG=    Z0HG_TBL(UTYPE)\n   TRLEND=  TRLEND_TBL(UTYPE)\n   TBLEND=  TBLEND_TBL(UTYPE)\n   TGLEND=  TGLEND_TBL(UTYPE)\n   BOUNDR=  BOUNDR_DATA\n   BOUNDB=  BOUNDB_DATA\n   BOUNDG=  BOUNDG_DATA\n   CH_SCHEME = CH_SCHEME_DATA\n   TS_SCHEME = TS_SCHEME_DATA\n   AKANDA_URBAN = AKANDA_URBAN_TBL(UTYPE)\n\n!for BEP\n\n   STREET_DIRECTION = -1.E36\n   STREET_WIDTH     = -1.E36\n   BUILDING_WIDTH   = -1.E36\n   HEIGHT_BIN       = -1.E36\n   HPERCENT_BIN     = -1.E36\n\n   NUMDIR                     = NUMDIR_TBL ( UTYPE )\n   STREET_DIRECTION(1:NUMDIR) = STREET_DIRECTION_TBL( 1:NUMDIR, UTYPE )\n   STREET_WIDTH    (1:NUMDIR) = STREET_WIDTH_TBL    ( 1:NUMDIR, UTYPE )\n   BUILDING_WIDTH  (1:NUMDIR) = BUILDING_WIDTH_TBL  ( 1:NUMDIR, UTYPE )\n   NUMHGT                     = NUMHGT_TBL ( UTYPE )\n   HEIGHT_BIN      (1:NUMHGT) = HEIGHT_BIN_TBL   ( 1:NUMHGT , UTYPE )\n   HPERCENT_BIN    (1:NUMHGT) = HPERCENT_BIN_TBL ( 1:NUMHGT , UTYPE )\n\n!end BEP\n   END SUBROUTINE read_param\n!===============================================================================\n!\n! subroutine urban_param_init: Read parameters from URBPARM.TBL\n!\n!===============================================================================\n   SUBROUTINE urban_param_init(DZR,DZB,DZG,num_soil_layers, &\n                               sf_urban_physics)\n!                              num_roof_layers,num_wall_layers,num_road_layers)\n\n   IMPLICIT NONE\n\n   INTEGER, INTENT(IN) :: num_soil_layers\n\n!   REAL, DIMENSION(1:num_roof_layers), INTENT(INOUT) :: DZR\n!   REAL, DIMENSION(1:num_wall_layers), INTENT(INOUT) :: DZB\n!   REAL, DIMENSION(1:num_road_layers), INTENT(INOUT) :: DZG\n   REAL, DIMENSION(1:num_soil_layers), INTENT(INOUT) :: DZR\n   REAL, DIMENSION(1:num_soil_layers), INTENT(INOUT) :: DZB\n   REAL, DIMENSION(1:num_soil_layers), INTENT(INOUT) :: DZG\n   INTEGER,                            INTENT(IN)    :: SF_URBAN_PHYSICS\n\n   INTEGER :: LC, K\n   INTEGER :: IOSTATUS, ALLOCATE_STATUS\n   INTEGER :: num_roof_layers\n   INTEGER :: num_wall_layers\n   INTEGER :: num_road_layers\n   INTEGER :: dummy\n   REAL    :: DHGT, HGT, VFWS, VFGS\n\n   REAL, allocatable, dimension(:) :: ROOF_WIDTH\n   REAL, allocatable, dimension(:) :: ROAD_WIDTH\n\n   character(len=512) :: string\n   character(len=128) :: name\n   integer :: indx\n\n   real, parameter :: VonK = 0.4\n   real :: lambda_p\n   real :: lambda_f\n   real :: Cd\n   real :: alpha_macd\n   real :: beta_macd\n   real :: lambda_fr\n\n\n!for BEP\n   real :: dummy_hgt\n   real :: dummy_pct\n   real :: pctsum\n!end BEP\n   num_roof_layers = num_soil_layers\n   num_wall_layers = num_soil_layers\n   num_road_layers = num_soil_layers\n\n\n   ICATE=0\n\n   OPEN (UNIT=11,                &\n         FILE='URBPARM.TBL', &\n         ACCESS='SEQUENTIAL',    &\n         STATUS='OLD',           &\n         ACTION='READ',          &\n         POSITION='REWIND',      &\n         IOSTAT=IOSTATUS)\n\n   IF (IOSTATUS > 0) THEN\n   CALL wrf_error_fatal('ERROR OPEN URBPARM.TBL')\n   ENDIF\n\n   READLOOP : do\n      read(11,'(A512)', iostat=iostatus) string\n      if (iostatus /= 0) exit READLOOP\n      if (string(1:1) == \"#\") cycle READLOOP\n      if (trim(string) == \" \") cycle READLOOP\n      indx = index(string,\":\")\n      if (indx <= 0) cycle READLOOP\n      name = trim(adjustl(string(1:indx-1)))\n\n      ! Here are the variables we expect to be defined in the URBPARM.TBL:\n      if (name == \"Number of urban categories\") then\n         read(string(indx+1:),*) icate\n         IF (.not. ALLOCATED(ZR_TBL)) then\n            ALLOCATE( ZR_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ZR_TBL in urban_param_init')\n            ALLOCATE( SIGMA_ZED_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0)CALL wrf_error_fatal('Error allocating SIGMA_ZED_TBL in urban_param_init')\n            ALLOCATE( Z0C_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating Z0C_TBL in urban_param_init')\n            ALLOCATE( Z0HC_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating Z0HC_TBL in urban_param_init')\n            ALLOCATE( ZDC_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ZDC_TBL in urban_param_init')\n            ALLOCATE( SVF_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating SVF_TBL in urban_param_init')\n            ALLOCATE( R_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating R_TBL in urban_param_init')\n            ALLOCATE( RW_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating RW_TBL in urban_param_init')\n            ALLOCATE( HGT_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating HGT_TBL in urban_param_init')\n            ALLOCATE( AH_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating AH_TBL in urban_param_init')\n            ALLOCATE( BETR_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating BETR_TBL in urban_param_init')\n            ALLOCATE( BETB_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating BETB_TBL in urban_param_init')\n            ALLOCATE( BETG_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating BETG_TBL in urban_param_init')\n            ALLOCATE( CAPR_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating CAPR_TBL in urban_param_init')\n            ALLOCATE( CAPB_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating CAPB_TBL in urban_param_init')\n            ALLOCATE( CAPG_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating CAPG_TBL in urban_param_init')\n            ALLOCATE( AKSR_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating AKSR_TBL in urban_param_init')\n            ALLOCATE( AKSB_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating AKSB_TBL in urban_param_init')\n            ALLOCATE( AKSG_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating AKSG_TBL in urban_param_init')\n            ALLOCATE( ALBR_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ALBR_TBL in urban_param_init')\n            ALLOCATE( ALBB_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ALBB_TBL in urban_param_init')\n            ALLOCATE( ALBG_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ALBG_TBL in urban_param_init')\n            ALLOCATE( EPSR_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating EPSR_TBL in urban_param_init')\n            ALLOCATE( EPSB_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating EPSB_TBL in urban_param_init')\n            ALLOCATE( EPSG_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating EPSG_TBL in urban_param_init')\n            ALLOCATE( Z0R_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating Z0R_TBL in urban_param_init')\n            ALLOCATE( Z0B_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating Z0B_TBL in urban_param_init')\n            ALLOCATE( Z0G_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating Z0G_TBL in urban_param_init')\n            ALLOCATE( AKANDA_URBAN_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating AKANDA_URBAN_TBL in urban_param_init')\n            ALLOCATE( Z0HB_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating Z0HB_TBL in urban_param_init')\n            ALLOCATE( Z0HG_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating Z0HG_TBL in urban_param_init')\n            ALLOCATE( TRLEND_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating TRLEND_TBL in urban_param_init')\n            ALLOCATE( TBLEND_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating TBLEND_TBL in urban_param_init')\n            ALLOCATE( TGLEND_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating TGLEND_TBL in urban_param_init')\n            ALLOCATE( FRC_URB_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating FRC_URB_TBL in urban_param_init')\n            ! ALLOCATE( ROOF_WIDTH(ICATE), stat=allocate_status )\n            ! if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ROOF_WIDTH in urban_param_init')\n            ! ALLOCATE( ROAD_WIDTH(ICATE), stat=allocate_status )\n            ! if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ROAD_WIDTH in urban_param_init')\n            !for BEP\n            ALLOCATE( NUMDIR_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating NUMDIR_TBL in urban_param_init')\n            ALLOCATE( STREET_DIRECTION_TBL(MAXDIRS , ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating STREET_DIRECTION_TBL in urban_param_init')\n            ALLOCATE( STREET_WIDTH_TBL(MAXDIRS , ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating STREET_WIDTH_TBL in urban_param_init')\n            ALLOCATE( BUILDING_WIDTH_TBL(MAXDIRS , ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating BUILDING_WIDTH_TBL in urban_param_init')\n            ALLOCATE( NUMHGT_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating NUMHGT_TBL in urban_param_init')\n            ALLOCATE( HEIGHT_BIN_TBL(MAXHGTS , ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating HEIGHT_BIN_TBL in urban_param_init')\n            ALLOCATE( HPERCENT_BIN_TBL(MAXHGTS , ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating HPERCENT_BIN_TBL in urban_param_init')\n            ALLOCATE( COP_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating COP_TBL in urban_param_init')\n            ALLOCATE( PWIN_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating PWIN_TBL in urban_param_init')\n            ALLOCATE( BETA_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating BETA_TBL in urban_param_init')\n            ALLOCATE( SW_COND_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating SW_COND_TBL in urban_param_init')\n            ALLOCATE( TIME_ON_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating TIME_ON_TBL in urban_param_init')\n            ALLOCATE( TIME_OFF_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating TIME_OFF_TBL in urban_param_init')\n            ALLOCATE( TARGTEMP_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating TARGTEMP_TBL in urban_param_init')\n            ALLOCATE( GAPTEMP_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating GAPTEMP_TBL in urban_param_init')\n            ALLOCATE( TARGHUM_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating TARGHUM_TBL in urban_param_init')\n            ALLOCATE( GAPHUM_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating GAPHUM_TBL in urban_param_init')\n            ALLOCATE( PERFLO_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating PERFLO_TBL in urban_param_init')\n            ALLOCATE( HSESF_TBL(ICATE), stat=allocate_status )\n            if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating HSESF_TBL in urban_param_init')\n         endif\n         numdir_tbl = 0\n         street_direction_tbl = -1.E36\n         street_width_tbl = 0\n         building_width_tbl = 0\n         numhgt_tbl = 0\n         height_bin_tbl = -1.E36\n         hpercent_bin_tbl = -1.E36\n!end BEP\n\n      else if (name == \"ZR\") then\n         read(string(indx+1:),*) zr_tbl(1:icate)\n      else if (name == \"SIGMA_ZED\") then\n         read(string(indx+1:),*) sigma_zed_tbl(1:icate)\n      else if (name == \"ROOF_WIDTH\") then\n         ALLOCATE( ROOF_WIDTH(ICATE), stat=allocate_status )\n         if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ROOF_WIDTH in urban_param_init')\n\n         read(string(indx+1:),*) roof_width(1:icate)\n      else if (name == \"ROAD_WIDTH\") then\n         ALLOCATE( ROAD_WIDTH(ICATE), stat=allocate_status )\n         if(allocate_status /= 0) CALL wrf_error_fatal('Error allocating ROAD_WIDTH in urban_param_init')\n         read(string(indx+1:),*) road_width(1:icate)\n      else if (name == \"AH\") then\n         read(string(indx+1:),*) ah_tbl(1:icate)\n      else if (name == \"FRC_URB\") then\n         read(string(indx+1:),*) frc_urb_tbl(1:icate)\n      else if (name == \"CAPR\") then\n         read(string(indx+1:),*) capr_tbl(1:icate)\n         ! Convert CAPR_TBL from J m{-3} K{-1} to cal cm{-3} deg{-1}\n         capr_tbl = capr_tbl * ( 1.0 / 4.1868 ) * 1.E-6\n      else if (name == \"CAPB\") then\n         read(string(indx+1:),*) capb_tbl(1:icate)\n         ! Convert CABR_TBL from J m{-3} K{-1} to cal cm{-3} deg{-1}\n         capb_tbl = capb_tbl * ( 1.0 / 4.1868 ) * 1.E-6\n      else if (name == \"CAPG\") then\n         read(string(indx+1:),*) capg_tbl(1:icate)\n         ! Convert CABG_TBL from J m{-3} K{-1} to cal cm{-3} deg{-1}\n         capg_tbl = capg_tbl * ( 1.0 / 4.1868 ) * 1.E-6\n      else if (name == \"AKSR\") then\n         read(string(indx+1:),*) aksr_tbl(1:icate)\n         ! Convert AKSR_TBL from J m{-1} s{-1} K{-1} to cal cm{-1} s{-1} deg{-1}\n         AKSR_TBL = AKSR_TBL * ( 1.0 / 4.1868 ) * 1.E-2\n      else if (name == \"AKSB\") then\n         read(string(indx+1:),*) aksb_tbl(1:icate)\n         ! Convert AKSB_TBL from J m{-1} s{-1} K{-1} to cal cm{-1} s{-1} deg{-1}\n         AKSB_TBL = AKSB_TBL * ( 1.0 / 4.1868 ) * 1.E-2\n      else if (name == \"AKSG\") then\n         read(string(indx+1:),*) aksg_tbl(1:icate)\n         ! Convert AKSG_TBL from J m{-1} s{-1} K{-1} to cal cm{-1} s{-1} deg{-1}\n         AKSG_TBL = AKSG_TBL * ( 1.0 / 4.1868 ) * 1.E-2\n      else if (name == \"ALBR\") then\n         read(string(indx+1:),*) albr_tbl(1:icate)\n      else if (name == \"ALBB\") then\n         read(string(indx+1:),*) albb_tbl(1:icate)\n      else if (name == \"ALBG\") then\n         read(string(indx+1:),*) albg_tbl(1:icate)\n      else if (name == \"EPSR\") then\n         read(string(indx+1:),*) epsr_tbl(1:icate)\n      else if (name == \"EPSB\") then\n         read(string(indx+1:),*) epsb_tbl(1:icate)\n      else if (name == \"EPSG\") then\n         read(string(indx+1:),*) epsg_tbl(1:icate)\n      else if (name == \"AKANDA_URBAN\") then\n         read(string(indx+1:),*) akanda_urban_tbl(1:icate)\n      else if (name == \"Z0B\") then\n         read(string(indx+1:),*) z0b_tbl(1:icate)\n      else if (name == \"Z0G\") then\n         read(string(indx+1:),*) z0g_tbl(1:icate)\n      else if (name == \"DDZR\") then\n         read(string(indx+1:),*) dzr(1:num_roof_layers)\n         ! Convert thicknesses from m to cm\n         dzr = dzr * 100.0\n      else if (name == \"DDZB\") then\n         read(string(indx+1:),*) dzb(1:num_wall_layers)\n         ! Convert thicknesses from m to cm\n         dzb = dzb * 100.0\n      else if (name == \"DDZG\") then\n         read(string(indx+1:),*) dzg(1:num_road_layers)\n         ! Convert thicknesses from m to cm\n         dzg = dzg * 100.0\n      else if (name == \"BOUNDR\") then\n         read(string(indx+1:),*) boundr_data\n      else if (name == \"BOUNDB\") then\n         read(string(indx+1:),*) boundb_data\n      else if (name == \"BOUNDG\") then\n         read(string(indx+1:),*) boundg_data\n      else if (name == \"TRLEND\") then\n         read(string(indx+1:),*) trlend_tbl(1:icate)\n      else if (name == \"TBLEND\") then\n         read(string(indx+1:),*) tblend_tbl(1:icate)\n      else if (name == \"TGLEND\") then\n         read(string(indx+1:),*) tglend_tbl(1:icate)\n      else if (name == \"CH_SCHEME\") then\n         read(string(indx+1:),*) ch_scheme_data\n      else if (name == \"TS_SCHEME\") then\n         read(string(indx+1:),*) ts_scheme_data\n      else if (name == \"AHOPTION\") then\n         read(string(indx+1:),*) ahoption\n      else if (name == \"AHDIUPRF\") then\n         read(string(indx+1:),*) ahdiuprf(1:24)\n!for BEP\n      else if (name == \"STREET PARAMETERS\") then\n\n         STREETLOOP : do\n            read(11,'(A512)', iostat=iostatus) string\n            if (string(1:1) == \"#\") cycle STREETLOOP\n            if (trim(string) == \" \") cycle STREETLOOP\n            if (string == \"END STREET PARAMETERS\") exit STREETLOOP\n            read(string, *) k ! , dirst, ws, bs\n            numdir_tbl(k) = numdir_tbl(k) + 1\n            read(string, *) k, street_direction_tbl(numdir_tbl(k),k), &\n                               street_width_tbl(numdir_tbl(k),k), &\n                               building_width_tbl(numdir_tbl(k),k)\n         enddo STREETLOOP\n\n      else if (name == \"BUILDING HEIGHTS\") then\n\n         read(string(indx+1:),*) k\n         HEIGHTLOOP : do\n            read(11,'(A512)', iostat=iostatus) string\n            if (string(1:1) == \"#\") cycle HEIGHTLOOP\n            if (trim(string) == \" \") cycle HEIGHTLOOP\n            if (string == \"END BUILDING HEIGHTS\") exit HEIGHTLOOP\n            read(string,*) dummy_hgt, dummy_pct\n            numhgt_tbl(k) = numhgt_tbl(k) + 1\n            height_bin_tbl(numhgt_tbl(k), k) = dummy_hgt\n            hpercent_bin_tbl(numhgt_tbl(k),k) = dummy_pct\n\n         enddo HEIGHTLOOP\n         pctsum = sum ( hpercent_bin_tbl(:,k) , mask=(hpercent_bin_tbl(:,k)>-1.E25 ) )\n         if ( pctsum /= 100.) then\n            write (*,'(//,\"Building height percentages for category \", I2, \" must sum to 100.0\")') k\n            write (*,'(\"Currently, they sum to \", F6.2,/)') pctsum\n            CALL wrf_error_fatal('pctsum is not equal to 100.')\n         endif\n      else if ( name == \"Z0R\") then\n         read(string(indx+1:),*) Z0R_tbl(1:icate)\n      else if ( name == \"COP\") then\n         read(string(indx+1:),*) cop_tbl(1:icate)\n      else if ( name == \"PWIN\") then\n         read(string(indx+1:),*) pwin_tbl(1:icate)\n      else if ( name == \"BETA\") then\n         read(string(indx+1:),*) beta_tbl(1:icate)\n      else if ( name == \"SW_COND\") then\n         read(string(indx+1:),*) sw_cond_tbl(1:icate)\n      else if ( name == \"TIME_ON\") then\n         read(string(indx+1:),*) time_on_tbl(1:icate)\n      else if ( name == \"TIME_OFF\") then\n         read(string(indx+1:),*) time_off_tbl(1:icate)\n      else if ( name == \"TARGTEMP\") then\n         read(string(indx+1:),*) targtemp_tbl(1:icate)\n      else if ( name == \"GAPTEMP\") then\n         read(string(indx+1:),*) gaptemp_tbl(1:icate)\n      else if ( name == \"TARGHUM\") then\n         read(string(indx+1:),*) targhum_tbl(1:icate)\n      else if ( name == \"GAPHUM\") then\n         read(string(indx+1:),*) gaphum_tbl(1:icate)\n      else if ( name == \"PERFLO\") then\n         read(string(indx+1:),*) perflo_tbl(1:icate)\n      else if (name == \"HSEQUIP\") then\n         read(string(indx+1:),*) hsequip_tbl(1:24)\n      else if (name == \"HSEQUIP_SCALE_FACTOR\") then\n         read(string(indx+1:),*) hsesf_tbl(1:icate)\n!end BEP\n      else\n         CALL wrf_error_fatal('URBPARM.TBL: Unrecognized NAME = \"'//trim(name)//'\" in Subr URBAN_PARAM_INIT')\n      endif\n   enddo READLOOP\n\n   CLOSE(11)\n\n   ! Assign a few table values that do not need to come from URBPARM.TBL\n\n   Z0HB_TBL = 0.1 * Z0B_TBL\n   Z0HG_TBL = 0.1 * Z0G_TBL\n\n   DO LC = 1, ICATE\n\n      ! HGT:  Normalized height\n      HGT_TBL(LC) = ZR_TBL(LC) / ( ROAD_WIDTH(LC) + ROOF_WIDTH(LC) )\n\n      ! R:  Normalized Roof Width (a.k.a. \"building coverage ratio\")\n      R_TBL(LC)  = ROOF_WIDTH(LC) / ( ROAD_WIDTH(LC) + ROOF_WIDTH(LC) )\n\n      RW_TBL(LC) = 1.0 - R_TBL(LC)\n      BETR_TBL(LC) = 0.0\n      BETB_TBL(LC) = 0.0\n      BETG_TBL(LC) = 0.0\n\n      ! The following urban canyon geometry parameters are following Macdonald's (1998) formulations\n\n      ! Lambda_P :: Plan areal fraction, which corresponds to R for a 2-d canyon.\n      ! Lambda_F :: Frontal area index, which corresponds to HGT for a 2-d canyon\n      ! Cd       :: Drag coefficient ( 1.2 from Grimmond and Oke, 1998 )\n      ! Alpha_macd :: Emperical coefficient ( 4.43 from Macdonald et al., 1998 )\n      ! Beta_macd  :: Correction factor for the drag coefficient ( 1.0 from Macdonald et al., 1998 )\n\n      Lambda_P = R_TBL(LC)\n      Lambda_F = HGT_TBL(LC)\n      Cd         = 1.2\n      alpha_macd = 4.43\n      beta_macd  = 1.0\n\n\n      ZDC_TBL(LC) = ZR_TBL(LC) * ( 1.0 + ( alpha_macd ** ( -Lambda_P ) )  * ( Lambda_P - 1.0 ) )\n\n      Z0C_TBL(LC) = ZR_TBL(LC) * ( 1.0 - ZDC_TBL(LC)/ZR_TBL(LC) ) * &\n           exp (-(0.5 * beta_macd * Cd / (VonK**2) * ( 1.0-ZDC_TBL(LC)/ZR_TBL(LC) ) * Lambda_F )**(-0.5))\n\n      IF (SF_URBAN_PHYSICS == 1) THEN\n         ! Include roof height variability in Macdonald\n         ! to parameterize Z0R as a function of ZR_SD (Standard Deviation)\n         Lambda_FR  = SIGMA_ZED_TBL(LC) / ( ROAD_WIDTH(LC) + ROOF_WIDTH(LC) )\n         Z0R_TBL(LC) = ZR_TBL(LC) * ( 1.0 - ZDC_TBL(LC)/ZR_TBL(LC) ) &\n              * exp ( -(0.5 * beta_macd * Cd / (VonK**2) &\n              * ( 1.0-ZDC_TBL(LC)/ZR_TBL(LC) ) * Lambda_FR )**(-0.5))\n      ENDIF\n\n      !\n      ! Z0HC still one-tenth of Z0C, as before ?\n      !\n\n      Z0HC_TBL(LC) = 0.1 * Z0C_TBL(LC)\n\n      !\n      ! Calculate Sky View Factor:\n      !\n      DHGT=HGT_TBL(LC)/100.\n      HGT=0.\n      VFWS=0.\n      HGT=HGT_TBL(LC)-DHGT/2.\n      do k=1,99\n         HGT=HGT-DHGT\n         VFWS=VFWS+0.25*(1.-HGT/SQRT(HGT**2.+RW_TBL(LC)**2.))\n      end do\n\n     VFWS=VFWS/99.\n     VFWS=VFWS*2.\n\n     VFGS=1.-2.*VFWS*HGT_TBL(LC)/RW_TBL(LC)\n     SVF_TBL(LC)=VFGS\n   END DO\n\n   deallocate(roof_width)\n   deallocate(road_width)\n\n   END SUBROUTINE urban_param_init\n!===========================================================================\n!\n! subroutine urban_var_init: initialization of urban state variables\n!\n!===========================================================================\n   SUBROUTINE urban_var_init(ISURBAN, TSURFACE0_URB,TLAYER0_URB,TDEEP0_URB,IVGTYP,  & ! in\n                             ims,ime,jms,jme,kms,kme,num_soil_layers,         & ! in\n!                             num_roof_layers,num_wall_layers,num_road_layers, & ! in\n                             restart,sf_urban_physics,                     & !in\n                             XXXR_URB2D,XXXB_URB2D,XXXG_URB2D,XXXC_URB2D,  & ! inout\n                             TR_URB2D,TB_URB2D,TG_URB2D,TC_URB2D,QC_URB2D, & ! inout\n                             TRL_URB3D,TBL_URB3D,TGL_URB3D,                & ! inout\n                             SH_URB2D,LH_URB2D,G_URB2D,RN_URB2D,           & ! inout\n                             TS_URB2D,                                     & ! inout\n                             num_urban_layers,                             & ! in\n                             TRB_URB4D,TW1_URB4D,TW2_URB4D,TGB_URB4D,      & ! inout\n                             TLEV_URB3D,QLEV_URB3D,                        & ! inout\n                             TW1LEV_URB3D,TW2LEV_URB3D,                    & ! inout\n                             TGLEV_URB3D,TFLEV_URB3D,                      & ! inout\n                             SF_AC_URB3D,LF_AC_URB3D,CM_AC_URB3D,          & ! inout\n                             SFVENT_URB3D,LFVENT_URB3D,                    & ! inout\n                             SFWIN1_URB3D,SFWIN2_URB3D,                    & ! inout\n                             SFW1_URB3D,SFW2_URB3D,SFR_URB3D,SFG_URB3D,    & ! inout\n                             A_U_BEP,A_V_BEP,A_T_BEP,A_Q_BEP,              & ! inout multi-layer urban\n                             A_E_BEP,B_U_BEP,B_V_BEP,                      & ! inout multi-layer urban\n                             B_T_BEP,B_Q_BEP,B_E_BEP,DLG_BEP,              & ! inout multi-layer urban\n                             DL_U_BEP,SF_BEP,VL_BEP,                       & ! inout multi-layer urban\n                             FRC_URB2D, UTYPE_URB2D)                         ! inout\n   IMPLICIT NONE\n\n   INTEGER, INTENT(IN) :: ISURBAN, sf_urban_physics\n   INTEGER, INTENT(IN) :: ims,ime,jms,jme,kms,kme,num_soil_layers\n   INTEGER, INTENT(IN) :: num_urban_layers                            !multi-layer urban\n!   INTEGER, INTENT(IN) :: num_roof_layers, num_wall_layers, num_road_layers\n\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(IN)                    :: TSURFACE0_URB\n#ifdef _HRLDAS_URBAN_\n   REAL, DIMENSION( ims:ime, jms:jme, 1:num_soil_layers ), INTENT(IN) :: TLAYER0_URB\n#else\n   REAL, DIMENSION( ims:ime, 1:num_soil_layers, jms:jme ), INTENT(IN) :: TLAYER0_URB\n#endif\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(IN)                    :: TDEEP0_URB\n   INTEGER, DIMENSION( ims:ime, jms:jme ), INTENT(IN)                 :: IVGTYP\n   LOGICAL , INTENT(IN) :: restart\n\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: TR_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: TB_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: TG_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: TC_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: QC_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: XXXR_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: XXXB_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: XXXG_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: XXXC_URB2D\n\n!   REAL, DIMENSION(ims:ime, 1:num_roof_layers, jms:jme), INTENT(INOUT) :: TRL_URB3D\n!   REAL, DIMENSION(ims:ime, 1:num_wall_layers, jms:jme), INTENT(INOUT) :: TBL_URB3D\n!   REAL, DIMENSION(ims:ime, 1:num_road_layers, jms:jme), INTENT(INOUT) :: TGL_URB3D\n#ifdef _HRLDAS_URBAN_\n   REAL, DIMENSION(ims:ime, jms:jme, 1:num_soil_layers), INTENT(INOUT) :: TRL_URB3D\n   REAL, DIMENSION(ims:ime, jms:jme, 1:num_soil_layers), INTENT(INOUT) :: TBL_URB3D\n   REAL, DIMENSION(ims:ime, jms:jme, 1:num_soil_layers), INTENT(INOUT) :: TGL_URB3D\n#else\n   REAL, DIMENSION(ims:ime, 1:num_soil_layers, jms:jme), INTENT(INOUT) :: TRL_URB3D\n   REAL, DIMENSION(ims:ime, 1:num_soil_layers, jms:jme), INTENT(INOUT) :: TBL_URB3D\n   REAL, DIMENSION(ims:ime, 1:num_soil_layers, jms:jme), INTENT(INOUT) :: TGL_URB3D\n#endif\n\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: SH_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: LH_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: G_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: RN_URB2D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: TS_URB2D\n\n! multi-layer UCM variables\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: TRB_URB4D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: TW1_URB4D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: TW2_URB4D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: TGB_URB4D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: TLEV_URB3D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: QLEV_URB3D\n   REAL, DIMENSION( ims:ime, 1:num_urban_layers, jms:jme ), INTENT(INOUT) :: TW1LEV_URB3D\n   REAL, DIMENSION( ims:ime, 1:num_urban_layers, jms:jme ), INTENT(INOUT) :: TW2LEV_URB3D\n   REAL, DIMENSION( ims:ime, 1:num_urban_layers, jms:jme ), INTENT(INOUT) :: TGLEV_URB3D\n   REAL, DIMENSION( ims:ime, 1:num_urban_layers, jms:jme ), INTENT(INOUT) :: TFLEV_URB3D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: LF_AC_URB3D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: SF_AC_URB3D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: CM_AC_URB3D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: SFVENT_URB3D\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: LFVENT_URB3D\n   REAL, DIMENSION( ims:ime, 1:num_urban_layers, jms:jme ), INTENT(INOUT) :: SFWIN1_URB3D\n   REAL, DIMENSION( ims:ime, 1:num_urban_layers, jms:jme ), INTENT(INOUT) :: SFWIN2_URB3D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: SFW1_URB3D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: SFW2_URB3D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: SFR_URB3D\n   REAL, DIMENSION(ims:ime, 1:num_urban_layers, jms:jme), INTENT(INOUT) :: SFG_URB3D\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: A_U_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: A_V_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: A_T_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: A_Q_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: A_E_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: B_U_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: B_V_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: B_T_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: B_Q_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: B_E_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: VL_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: DLG_BEP\n   REAL, DIMENSION(ims:ime, kms:kme,jms:jme),INTENT(INOUT) :: SF_BEP\n   REAL, DIMENSION(ims:ime, kms:kme, jms:jme), INTENT(INOUT) :: DL_U_BEP\n!\n   REAL, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: FRC_URB2D\n   INTEGER, DIMENSION( ims:ime, jms:jme ), INTENT(INOUT) :: UTYPE_URB2D\n   INTEGER                                            :: UTYPE_URB\n\n   INTEGER :: I,J,K\n\n   DO I=ims,ime\n    DO J=jms,jme\n\n!      XXXR_URB2D(I,J)=0.\n!      XXXB_URB2D(I,J)=0.\n!      XXXG_URB2D(I,J)=0.\n!      XXXC_URB2D(I,J)=0.\n\n      SH_URB2D(I,J)=0.\n      LH_URB2D(I,J)=0.\n      G_URB2D(I,J)=0.\n      RN_URB2D(I,J)=0.\n\n!m\n      FRC_URB2D(I,J)=0.\n      UTYPE_URB2D(I,J)=0\n\n            IF( IVGTYP(I,J) == ISURBAN)  THEN\n               UTYPE_URB2D(I,J) = 2  ! for default. high-intensity\n               UTYPE_URB = UTYPE_URB2D(I,J)  ! for default. high-intensity\n               FRC_URB2D(I,J) = FRC_URB_TBL(UTYPE_URB)\n            ENDIF\n            IF( IVGTYP(I,J) == 31) THEN\n               UTYPE_URB2D(I,J) = 3  ! low-intensity residential\n               UTYPE_URB = UTYPE_URB2D(I,J)  ! low-intensity residential\n               FRC_URB2D(I,J) = FRC_URB_TBL(UTYPE_URB)\n            ENDIF\n            IF( IVGTYP(I,J) == 32) THEN\n               UTYPE_URB2D(I,J) = 2  ! high-intensity\n               UTYPE_URB = UTYPE_URB2D(I,J)  ! high-intensity\n               FRC_URB2D(I,J) = FRC_URB_TBL(UTYPE_URB)\n            ENDIF\n            IF( IVGTYP(I,J) == 33) THEN\n               UTYPE_URB2D(I,J) = 1  !  Commercial/Industrial/Transportation\n               UTYPE_URB = UTYPE_URB2D(I,J)  !  Commercial/Industrial/Transportation\n               FRC_URB2D(I,J) = FRC_URB_TBL(UTYPE_URB)\n            ENDIF\n\n\n      QC_URB2D(I,J)=0.01\n\n       IF (.not.restart) THEN\n\n      XXXR_URB2D(I,J)=0.\n      XXXB_URB2D(I,J)=0.\n      XXXG_URB2D(I,J)=0.\n      XXXC_URB2D(I,J)=0.\n\n\n      TC_URB2D(I,J)=TSURFACE0_URB(I,J)+0.\n      TR_URB2D(I,J)=TSURFACE0_URB(I,J)+0.\n      TB_URB2D(I,J)=TSURFACE0_URB(I,J)+0.\n      TG_URB2D(I,J)=TSURFACE0_URB(I,J)+0.\n!\n      TS_URB2D(I,J)=TSURFACE0_URB(I,J)+0.\n\n!      DO K=1,num_roof_layers\n!     DO K=1,num_soil_layers\n!         TRL_URB3D(I,1,J)=TLAYER0_URB(I,1,J)+0.\n!         TRL_URB3D(I,2,J)=TLAYER0_URB(I,2,J)+0.\n!         TRL_URB3D(I,3,J)=TLAYER0_URB(I,3,J)+0.!\n#ifdef _HRLDAS_URBAN_\n          TRL_URB3D(I,J,4)=TLAYER0_URB(I,J,4)+0.\n\n          TRL_URB3D(I,J,1)=TLAYER0_URB(I,J,1)+0.\n          TRL_URB3D(I,J,2)=0.5*(TLAYER0_URB(I,J,1)+TLAYER0_URB(I,J,2))\n          TRL_URB3D(I,J,3)=TLAYER0_URB(I,J,2)+0.\n          TRL_URB3D(I,J,4)=TLAYER0_URB(I,J,2)+(TLAYER0_URB(I,J,3)-TLAYER0_URB(I,J,2))*0.29\n#else\n          TRL_URB3D(I,4,J)=TLAYER0_URB(I,4,J)+0.\n\n          TRL_URB3D(I,1,J)=TLAYER0_URB(I,1,J)+0.\n          TRL_URB3D(I,2,J)=0.5*(TLAYER0_URB(I,1,J)+TLAYER0_URB(I,2,J))\n          TRL_URB3D(I,3,J)=TLAYER0_URB(I,2,J)+0.\n          TRL_URB3D(I,4,J)=TLAYER0_URB(I,2,J)+(TLAYER0_URB(I,3,J)-TLAYER0_URB(I,2,J))*0.29\n#endif\n!     END DO\n\n!      DO K=1,num_wall_layers\n!      DO K=1,num_soil_layers\n!m        TBL_URB3D(I,1,J)=TLAYER0_URB(I,1,J)+0.\n!m        TBL_URB3D(I,2,J)=TLAYER0_URB(I,2,J)+0.\n!m        TBL_URB3D(I,3,J)=TLAYER0_URB(I,3,J)+0.\n!m        TBL_URB3D(I,4,J)=TLAYER0_URB(I,4,J)+0.\n\n#ifdef _HRLDAS_URBAN_\n        TBL_URB3D(I,J,1)=TLAYER0_URB(I,J,1)+0.\n        TBL_URB3D(I,J,2)=0.5*(TLAYER0_URB(I,J,1)+TLAYER0_URB(I,J,2))\n        TBL_URB3D(I,J,3)=TLAYER0_URB(I,J,2)+0.\n        TBL_URB3D(I,J,4)=TLAYER0_URB(I,J,2)+(TLAYER0_URB(I,J,3)-TLAYER0_URB(I,J,2))*0.29\n#else\n        TBL_URB3D(I,1,J)=TLAYER0_URB(I,1,J)+0.\n        TBL_URB3D(I,2,J)=0.5*(TLAYER0_URB(I,1,J)+TLAYER0_URB(I,2,J))\n        TBL_URB3D(I,3,J)=TLAYER0_URB(I,2,J)+0.\n        TBL_URB3D(I,4,J)=TLAYER0_URB(I,2,J)+(TLAYER0_URB(I,3,J)-TLAYER0_URB(I,2,J))*0.29\n#endif\n!      END DO\n\n!      DO K=1,num_road_layers\n      DO K=1,num_soil_layers\n#ifdef _HRLDAS_URBAN_\n        TGL_URB3D(I,J,K)=TLAYER0_URB(I,J,K)+0.\n#else\n        TGL_URB3D(I,K,J)=TLAYER0_URB(I,K,J)+0.\n#endif\n      END DO\n\n! multi-layer urban\n!      IF( sf_urban_physics .EQ. 2)THEN\n       IF((SF_URBAN_PHYSICS.eq.2).OR.(SF_URBAN_PHYSICS.eq.3)) THEN\n      DO k=1,num_urban_layers\n!        TRB_URB4D(I,k,J)=TSURFACE0_URB(I,J)\n!        TW1_URB4D(I,k,J)=TSURFACE0_URB(I,J)\n!        TW2_URB4D(I,k,J)=TSURFACE0_URB(I,J)\n!        TGB_URB4D(I,k,J)=TSURFACE0_URB(I,J)\n!MT        TRB_URB4D(I,K,J)=tlayer0_urb(I,1,J)\n!MT        TW1_URB4D(I,K,J)=tlayer0_urb(I,1,J)\n!MT        TW2_URB4D(I,K,J)=tlayer0_urb(I,1,J)\n        IF (UTYPE_URB2D(I,J) > 0) THEN\n           TRB_URB4D(I,K,J)=TBLEND_TBL(UTYPE_URB2D(I,J))\n           TW1_URB4D(I,K,J)=TBLEND_TBL(UTYPE_URB2D(I,J))\n           TW2_URB4D(I,K,J)=TBLEND_TBL(UTYPE_URB2D(I,J))\n        ELSE\n#ifdef _HRLDAS_URBAN_\n           TRB_URB4D(I,K,J)=tlayer0_urb(I,J,1)\n           TW1_URB4D(I,K,J)=tlayer0_urb(I,J,1)\n           TW2_URB4D(I,K,J)=tlayer0_urb(I,J,1)\n#else\n           TRB_URB4D(I,K,J)=tlayer0_urb(I,1,J)\n           TW1_URB4D(I,K,J)=tlayer0_urb(I,1,J)\n           TW2_URB4D(I,K,J)=tlayer0_urb(I,1,J)\n#endif\n        ENDIF\n#ifdef _HRLDAS_URBAN_\n        TGB_URB4D(I,K,J)=tlayer0_urb(I,J,1)\n#else\n        TGB_URB4D(I,K,J)=tlayer0_urb(I,1,J)\n#endif\n        SFW1_URB3D(I,K,J)=0.\n        SFW2_URB3D(I,K,J)=0.\n        SFR_URB3D(I,K,J)=0.\n        SFG_URB3D(I,K,J)=0.\n      ENDDO\n\n       ENDIF\n\n      if (SF_URBAN_PHYSICS.EQ.3) then\n         LF_AC_URB3D(I,J)=0.\n         SF_AC_URB3D(I,J)=0.\n         CM_AC_URB3D(I,J)=0.\n         SFVENT_URB3D(I,J)=0.\n         LFVENT_URB3D(I,J)=0.\n\n         DO K=1,num_urban_layers\n            TLEV_URB3D(I,K,J)=tlayer0_urb(I,1,J)\n            TW1LEV_URB3D(I,K,J)=tlayer0_urb(I,1,J)\n            TW2LEV_URB3D(I,K,J)=tlayer0_urb(I,1,J)\n            TGLEV_URB3D(I,K,J)=tlayer0_urb(I,1,J)\n            TFLEV_URB3D(I,K,J)=tlayer0_urb(I,1,J)\n            QLEV_URB3D(I,K,J)=0.01\n            SFWIN1_URB3D(I,K,J)=0.\n            SFWIN2_URB3D(I,K,J)=0.\n!rm         LF_AC_URB3D(I,J)=0.\n!rm         SF_AC_URB3D(I,J)=0.\n!rm         CM_AC_URB3D(I,J)=0.\n!rm         SFVENT_URB3D(I,J)=0.\n!rm         LFVENT_URB3D(I,J)=0.\n         ENDDO\n\n      endif\n\n!      IF( sf_urban_physics .EQ. 2 )THEN\n      IF((SF_URBAN_PHYSICS.eq.2).OR.(SF_URBAN_PHYSICS.eq.3)) THEN\n      DO K= KMS,KME\n          SF_BEP(I,K,J)=1.\n          VL_BEP(I,K,J)=1.\n          A_U_BEP(I,K,J)=0.\n          A_V_BEP(I,K,J)=0.\n          A_T_BEP(I,K,J)=0.\n          A_E_BEP(I,K,J)=0.\n          A_Q_BEP(I,K,J)=0.\n          B_U_BEP(I,K,J)=0.\n          B_V_BEP(I,K,J)=0.\n          B_T_BEP(I,K,J)=0.\n          B_E_BEP(I,K,J)=0.\n          B_Q_BEP(I,K,J)=0.\n          DLG_BEP(I,K,J)=0.\n          DL_U_BEP(I,K,J)=0.\n      END DO\n      ENDIF       !sf_urban_physics=2\n     ENDIF        !restart\n    END DO\n   END DO\n   RETURN\n   END SUBROUTINE urban_var_init\n!===========================================================================\n!\n!  force_restore\n!\n!===========================================================================\n   SUBROUTINE force_restore(CAP,AKS,DELT,S,R,H,LE,TSLEND,TSP,TS)\n\n     REAL, INTENT(IN)  :: CAP,AKS,DELT,S,R,H,LE,TSLEND,TSP\n     REAL, INTENT(OUT) :: TS\n     REAL              :: C1,C2\n\n     C2=24.*3600./2./3.14159\n     C1=SQRT(0.5*C2*CAP*AKS)\n\n     TS = TSP + DELT*( (S+R-H-LE)/C1 -(TSP-TSLEND)/C2 )\n\n   END SUBROUTINE force_restore\n!===========================================================================\n!\n!  bisection (not used)\n!\n!============================================================================== \n   SUBROUTINE bisection(TSP,PS,S,EPS,RX,SIG,RHO,CP,CH,UA,QA,TA,EL,BET,AKS,TSL,DZ,TS) \n\n     REAL, INTENT(IN) :: TSP,PS,S,EPS,RX,SIG,RHO,CP,CH,UA,QA,TA,EL,BET,AKS,TSL,DZ\n     REAL, INTENT(OUT) :: TS\n     REAL :: ES,QS0,R,H,ELE,G0,F1,F\n\n     TS1 = TSP - 5.\n     TS2 = TSP + 5.\n\n     DO ITERATION = 1,22\n\n       ES=6.11*EXP( (2.5*10.**6./461.51)*(TS1-273.15)/(273.15*TS1) )\n       QS0=0.622*ES/(PS-0.378*ES)\n       R=EPS*(RX-SIG*(TS1**4.)/60.)\n       H=RHO*CP*CH*UA*(TS1-TA)*100.\n       ELE=RHO*EL*CH*UA*BET*(QS0-QA)*100.\n       G0=AKS*(TS1-TSL)/(DZ/2.)\n       F1= S + R - H - ELE - G0\n\n       TS=0.5*(TS1+TS2)\n\n       ES=6.11*EXP( (2.5*10.**6./461.51)*(TS-273.15)/(273.15*TS) )\n       QS0=0.622*ES/(PS-0.378*ES)\n       R=EPS*(RX-SIG*(TS**4.)/60.)\n       H=RHO*CP*CH*UA*(TS-TA)*100.\n       ELE=RHO*EL*CH*UA*BET*(QS0-QA)*100.\n       G0=AKS*(TS-TSL)/(DZ/2.)\n       F = S + R - H - ELE - G0\n\n       IF (F1*F > 0.0) THEN\n         TS1=TS\n        ELSE\n         TS2=TS\n       END IF\n\n     END DO\n\n     RETURN\nEND SUBROUTINE bisection\n!===========================================================================\n\nSUBROUTINE SFCDIF_URB (ZLM,Z0,THZ0,THLM,SFCSPD,AKANDA,AKMS,AKHS,RLMO,CD)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE SFCDIF_URB (Urban version of SFCDIF_off)\n! ----------------------------------------------------------------------\n! CALCULATE SURFACE LAYER EXCHANGE COEFFICIENTS VIA ITERATIVE PROCESS.\n! SEE CHEN ET AL (1997, BLM)\n! ----------------------------------------------------------------------\n\n      IMPLICIT NONE\n      REAL     WWST, WWST2, G, VKRM, EXCM, BETA, BTG, ELFC, WOLD, WNEW\n      REAL     PIHF, EPSU2, EPSUST, EPSIT, EPSA, ZTMIN, ZTMAX, HPBL,     &\n     & SQVISC\n      REAL     RIC, RRIC, FHNEU, RFC,RLMO_THR, RFAC, ZZ, PSLMU, PSLMS, PSLHU,     &\n     & PSLHS\n      REAL     XX, PSPMU, YY, PSPMS, PSPHU, PSPHS, ZLM, Z0, THZ0, THLM\n      REAL     SFCSPD, AKANDA, AKMS, AKHS, ZU, ZT, RDZ, CXCH\n      REAL     DTHV, DU2, BTGH, WSTAR2, USTAR, ZSLU, ZSLT, RLOGU, RLOGT\n      REAL     RLMO, ZETALT, ZETALU, ZETAU, ZETAT, XLU4, XLT4, XU4, XT4\n!CC   ......REAL ZTFC\n\n      REAL     XLU, XLT, XU, XT, PSMZ, SIMM, PSHZ, SIMH, USTARK, RLMN,  &\n     &         RLMA\n\n      INTEGER  ITRMX, ILECH, ITR\n      REAL,    INTENT(OUT) :: CD\n      PARAMETER                                                         &\n     &        (WWST = 1.2,WWST2 = WWST * WWST,G = 9.8,VKRM = 0.40,      &\n     &         EXCM = 0.001                                             &\n     &        ,BETA = 1./270.,BTG = BETA * G,ELFC = VKRM * BTG          &\n     &                  ,WOLD =.15,WNEW = 1. - WOLD,ITRMX = 05,         &\n     &                   PIHF = 3.14159265/2.)\n      PARAMETER                                                         &\n     &         (EPSU2 = 1.E-4,EPSUST = 0.07,EPSIT = 1.E-4,EPSA = 1.E-8  &\n     &         ,ZTMIN = -5.,ZTMAX = 1.,HPBL = 1000.0                    &\n     &          ,SQVISC = 258.2)\n      PARAMETER                                                         &\n     &       (RIC = 0.183,RRIC = 1.0/ RIC,FHNEU = 0.8,RFC = 0.191       &\n     &        ,RLMO_THR = 0.001,RFAC = RIC / (FHNEU * RFC * RFC))\n\n! ----------------------------------------------------------------------\n! NOTE: THE TWO CODE BLOCKS BELOW DEFINE FUNCTIONS\n! ----------------------------------------------------------------------\n! LECH'S SURFACE FUNCTIONS\n! ----------------------------------------------------------------------\n      PSLMU (ZZ)= -0.96* log (1.0-4.5* ZZ)\n      PSLMS (ZZ)= ZZ * RRIC -2.076* (1. -1./ (ZZ +1.))\n      PSLHU (ZZ)= -0.96* log (1.0-4.5* ZZ)\n\n! ----------------------------------------------------------------------\n! PAULSON'S SURFACE FUNCTIONS\n! ----------------------------------------------------------------------\n      PSLHS (ZZ)= ZZ * RFAC -2.076* (1. -1./ (ZZ +1.))\n      PSPMU (XX)= -2.* log ( (XX +1.)*0.5) - log ( (XX * XX +1.)*0.5)   &\n     &        +2.* ATAN (XX)                                            &\n     &- PIHF\n      PSPMS (YY)= 5.* YY\n      PSPHU (XX)= -2.* log ( (XX * XX +1.)*0.5)\n\n! ----------------------------------------------------------------------\n! THIS ROUTINE SFCDIF CAN HANDLE BOTH OVER OPEN WATER (SEA, OCEAN) AND\n! OVER SOLID SURFACE (LAND, SEA-ICE).\n! ----------------------------------------------------------------------\n      PSPHS (YY)= 5.* YY\n\n! ----------------------------------------------------------------------\n!     ZTFC: RATIO OF ZOH/ZOM  LESS OR EQUAL THAN 1\n!     C......ZTFC=0.1\n!     CZIL: CONSTANT C IN Zilitinkevich, S. S.1995,:NOTE ABOUT ZT\n! ----------------------------------------------------------------------\n      ILECH = 0\n\n! ----------------------------------------------------------------------\n!      ZILFC = - CZIL * VKRM * SQVISC\n!     C.......ZT=Z0*ZTFC\n      ZU = Z0\n      RDZ = 1./ ZLM\n      CXCH = EXCM * RDZ\n      DTHV = THLM - THZ0\n\n! ----------------------------------------------------------------------\n! BELJARS CORRECTION OF USTAR\n! ----------------------------------------------------------------------\n      DU2 = MAX (SFCSPD * SFCSPD,EPSU2)\n!cc   If statements to avoid TANGENT LINEAR problems near zero\n      BTGH = BTG * HPBL\n      IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n         WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n      ELSE\n         WSTAR2 = 0.0\n      END IF\n\n! ----------------------------------------------------------------------\n! ZILITINKEVITCH APPROACH FOR ZT\n! ----------------------------------------------------------------------\n      USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n\n! ----------------------------------------------------------------------\n! KCL/TL Try Kanda approach instead (Kanda et al. 2007, JAMC)\n!      ZT = EXP (ZILFC * SQRT (USTAR * Z0))* Z0\n      ZT = EXP (2.0-AKANDA*(SQVISC**2 * USTAR * Z0)**0.25)* Z0\n\n      ZSLU = ZLM + ZU\n\n      ZSLT = ZLM + ZT\n      RLOGU = log (ZSLU / ZU)\n\n      RLOGT = log (ZSLT / ZT)\n\n      RLMO = ELFC * AKHS * DTHV / USTAR **3\n! ----------------------------------------------------------------------\n! 1./MONIN-OBUKKHOV LENGTH-SCALE\n! ----------------------------------------------------------------------\n      DO ITR = 1,ITRMX\n         ZETALT = MAX (ZSLT * RLMO,ZTMIN)\n         RLMO = ZETALT / ZSLT\n         ZETALU = ZSLU * RLMO\n         ZETAU = ZU * RLMO\n\n         ZETAT = ZT * RLMO\n         IF (ILECH .eq. 0) THEN\n            IF (RLMO .lt. 0.0)THEN\n               XLU4 = 1. -16.* ZETALU\n               XLT4 = 1. -16.* ZETALT\n               XU4 = 1. -16.* ZETAU\n\n               XT4 = 1. -16.* ZETAT\n               XLU = SQRT (SQRT (XLU4))\n               XLT = SQRT (SQRT (XLT4))\n               XU = SQRT (SQRT (XU4))\n\n               XT = SQRT (SQRT (XT4))\n\n               PSMZ = PSPMU (XU)\n               SIMM = PSPMU (XLU) - PSMZ + RLOGU\n               PSHZ = PSPHU (XT)\n               SIMH = PSPHU (XLT) - PSHZ + RLOGT\n            ELSE\n               ZETALU = MIN (ZETALU,ZTMAX)\n               ZETALT = MIN (ZETALT,ZTMAX)\n               PSMZ = PSPMS (ZETAU)\n               SIMM = PSPMS (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSPHS (ZETAT)\n               SIMH = PSPHS (ZETALT) - PSHZ + RLOGT\n            END IF\n! ----------------------------------------------------------------------\n! LECH'S FUNCTIONS\n! ----------------------------------------------------------------------\n         ELSE\n            IF (RLMO .lt. 0.)THEN\n               PSMZ = PSLMU (ZETAU)\n               SIMM = PSLMU (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSLHU (ZETAT)\n               SIMH = PSLHU (ZETALT) - PSHZ + RLOGT\n            ELSE\n               ZETALU = MIN (ZETALU,ZTMAX)\n               ZETALT = MIN (ZETALT,ZTMAX)\n               PSMZ = PSLMS (ZETAU)\n               SIMM = PSLMS (ZETALU) - PSMZ + RLOGU\n               PSHZ = PSLHS (ZETAT)\n               SIMH = PSLHS (ZETALT) - PSHZ + RLOGT\n            END IF\n! ----------------------------------------------------------------------\n! BELJAARS CORRECTION FOR USTAR\n! ----------------------------------------------------------------------\n         END IF\n            USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n            !KCL/TL\n            !ZT = EXP (ZILFC * SQRT (USTAR * Z0))* Z0\n            ZT = EXP (2.0-AKANDA*(SQVISC**2 * USTAR * Z0)**0.25)* Z0\n            ZSLT = ZLM + ZT\n            RLOGT = log (ZSLT / ZT)\n            USTARK = USTAR * VKRM\n            AKMS = MAX (USTARK / SIMM,CXCH)\n            AKHS = MAX (USTARK / SIMH,CXCH)\n!\n         IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n            WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n         ELSE\n            WSTAR2 = 0.0\n         END IF\n!-----------------------------------------------------------------------\n         RLMN = ELFC * AKHS * DTHV / USTAR **3\n!-----------------------------------------------------------------------\n!     IF(ABS((RLMN-RLMO)/RLMA).LT.EPSIT)    GO TO 110\n!-----------------------------------------------------------------------\n         RLMA = RLMO * WOLD+ RLMN * WNEW\n!-----------------------------------------------------------------------\n         RLMO = RLMA\n\n      END DO\n\n      CD = USTAR*USTAR/SFCSPD**2\n! ----------------------------------------------------------------------\n  END SUBROUTINE SFCDIF_URB\n! ----------------------------------------------------------------------\n!===========================================================================\nEND MODULE module_sf_urban\n"
  },
  {
    "path": "src/Land_models/Noah/Run/GENPARM.TBL",
    "content": "General Parameters\nSLOPE_DATA\n9\n0.1 \n0.6\n1.0\n0.35\n0.55\n0.8\n0.63\n0.0\n0.0\nSBETA_DATA\n-2.0\nFXEXP_DATA\n2.0\nCSOIL_DATA\n2.00E+6\nSALP_DATA\n2.6\nREFDK_DATA\n2.0E-6\nREFKDT_DATA\n1.0\nFRZK_DATA\n0.15\nZBOT_DATA\n-8.0\nCZIL_DATA\n0.1\nSMLOW_DATA\n0.5\nSMHIGH_DATA\n3.0\nLVCOEF_DATA\n0.5\n"
  },
  {
    "path": "src/Land_models/Noah/Run/LANDUSE.TBL",
    "content": "OLD\n13,2, 'ALBD   SLMO   SFEM   SFZ0 THERIN   SCFX   SFHC   '\nSUMMER\n1,      18.,   .05,   .88,   50.,    3.,  1.22, 18.9e5,'Urban land'\n2,      17.,   .30,   .92,   15.,    4.,  2.76, 25.0e5,'Agriculture'\n3,      19.,   .15,   .92,   12.,    3.,  2.37, 20.8e5,'Range-grassland'\n4,      16.,   .30,   .93,   50.,    4.,  2.63, 25.0e5,'Deciduous forest'\n5,      12.,   .30,   .95,   50.,    4.,  3.33, 29.2e5,'Coniferous forest'\n6,      14.,   .35,   .95,   40.,    5.,  2.21, 41.8e5,'Mixed forest and wet land'\n7,       8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25,'Water'\n8,      14.,   .50,   .95,   20.,    6.,  1.36, 29.2e5,'Marsh or wet land'\n9,      25.,   .02,   .85,   10.,    2.,  1.76, 12.0e5,'Desert'\n10,     15.,   .50,   .92,   10.,    5.,  3.67, 9.0e25,'Tundra'\n11,     55.,   .95,   .95,    5.,    5.,    0., 9.0e25,'Permanent ice'\n12,     12.,   .50,   .95,   50.,    5.,  1.66, 29.2e5,'Tropical or subtropical forest'\n13,     20.,   .15,   .92,   15.,    3.,  2.00, 25.0e5,'Savannah'\nWINTER\n1,      18.,   .10,   .88,   50.,    3.,  1.22, 18.9e5,'Urban land'\n2,      23.,   .60,   .92,    5.,    4.,  1.78, 25.0e5,'Agriculture'\n3,      23.,   .30,   .92,   10.,    4.,  1.78, 20.8e5,'Range-grassland'\n4,      17.,   .60,   .93,   50.,    5.,  2.40, 25.0e5,'Deciduous forest'\n5,      12.,   .60,   .95,   50.,    5.,  3.33, 29.2e5,'Coniferous forest'\n6,      14.,   .70,   .95,   40.,    6.,  2.21, 41.8e5,'Mixed forest and wet land'\n7,       8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25,'Water'\n8,      14.,   .75,   .95,   20.,    6.,  1.40, 29.2e5,'Marsh or wet land'\n9,      25.,   .05,   .85,   10.,    2.,  1.76, 12.0e5,'Desert'\n10,     15.,   .90,   .92,   10.,    5.,  3.67, 9.0e25,'Tundra'\n11,     70.,   .95,   .95,    5.,    5.,    0., 9.0e25,'Permanent ice'\n12,     12.,   .50,   .95,   50.,    5.,  1.66, 29.2e5,'Tropical or subtropical forest'\n13,     20.,   .15,   .92,   15.,    3.,  2.00, 25.0e5,'Savannah'\nUSGS\n33,2, 'ALBD   SLMO   SFEM   SFZ0 THERIN   SCFX   SFHC   '\nSUMMER\n1,      15.,   .10,   .88,   80.,    3.,  1.67, 18.9e5,'Urban and Built-Up Land'\n2,      17.,   .30,  .985,   15.,    4.,  2.71, 25.0e5,'Dryland Cropland and Pasture'\n3,      18.,   .50,  .985,   10.,    4.,  2.20, 25.0e5,'Irrigated Cropland and Pasture'\n4,      18.,   .25,  .985,   15.,    4.,  2.56, 25.0e5,'Mixed Dryland/Irrigated Cropland and Pasture'\n5,      18.,   .25,   .98,   14.,    4.,  2.56, 25.0e5,'Cropland/Grassland Mosaic'\n6,      16.,   .35,  .985,   20.,    4.,  3.19, 25.0e5,'Cropland/Woodland Mosaic'\n7,      19.,   .15,   .96,   12.,    3.,  2.37, 20.8e5,'Grassland'\n8,      22.,   .10,   .93,    5.,    3.,  1.56, 20.8e5,'Shrubland'\n9,      20.,   .15,   .95,    6.,    3.,  2.14, 20.8e5,'Mixed Shrubland/Grassland'\n10,     20.,   .15,   .92,   15.,    3.,  2.00, 25.0e5,'Savanna'\n11,     16.,   .30,   .93,   50.,    4.,  2.63, 25.0e5,'Deciduous Broadleaf Forest'\n12,     14.,   .30,   .94,   50.,    4.,  2.86, 25.0e5,'Deciduous Needleleaf Forest'\n13,     12.,   .50,   .95,   50.,    5.,  1.67, 29.2e5,'Evergreen Broadleaf Forest'\n14,     12.,   .30,   .95,   50.,    4.,  3.33, 29.2e5,'Evergreen Needleleaf Forest'\n15,     13.,   .30,   .97,   50.,    4.,  2.11, 41.8e5,'Mixed Forest'\n16,      8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25,'Water Bodies'\n17,     14.,   .60,   .95,   20.,    6.,  1.50, 29.2e5,'Herbaceous Wetland'\n18,     14.,   .35,   .95,   40.,    5.,  1.14, 41.8e5,'Wooded Wetland'\n19,     25.,   .02,   .90,    1.,    2.,  0.81, 12.0e5,'Barren or Sparsely Vegetated'\n20,     15.,   .50,   .92,   10.,    5.,  2.87, 9.0e25,'Herbaceous Tundra'\n21,     15.,   .50,   .93,   30.,    5.,  2.67, 9.0e25,'Wooded Tundra'\n22,     15.,   .50,   .92,   15.,    5.,  2.67, 9.0e25,'Mixed Tundra'\n23,     25.,   .02,   .90,   10.,    2.,  1.60, 12.0e5,'Bare Ground Tundra'\n24,     55.,   .95,   .95,   0.1,    5.,    0., 9.0e25,'Snow or Ice'\n25,     30.,   .40,   .90,    1.,    5.,   .62, 12.0E5,'Playa'\n26,     18.,   .50,   .95,   15.,    6.,   .62, 12.0E5,'Lava'\n27,     70.,   .40,   .90,    1.,    5.,    0., 12.0E5,'White Sand'\n28,     15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5,'Unassigned'\n29,     15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5,'Unassigned'\n30,     15.,   .10,   .88,   80.,    3.,  1.67, 18.9e5,'Unassigned'\n31,     10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5,'Low Intensity Residential '\n32,     10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5,'High Intensity Residential'\n33,     10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5,'Industrial or Commercial'\nWINTER\n1,      15.,   .10,   .88,   80.,    3.,  1.67, 18.9e5,'Urban and Built-Up Land'\n2,      20.,   .60,   .92,    5.,    4.,  2.00, 25.0e5,'Dryland Cropland and Pasture'\n3,      20.,   .50,   .93,    2.,    4.,  1.76, 25.0e5,'Irrigated Cropland and Pasture'\n4,      20.,   .50,   .92,    5.,    4.,  2.00, 25.0e5,'Mixed Dryland/Irrigated Cropland and Pasture'\n5,      20.,   .40,   .92,    5.,    4.,  2.00, 25.0e5,'Cropland/Grassland Mosaic'\n6,      20.,   .60,   .93,   20.,    4.,  2.00, 25.0e5,'Cropland/Woodland Mosaic'\n7,      23.,   .30,   .92,   10.,    4.,  2.00, 20.8e5,'Grassland'\n8,      22.,   .20,   .93,    1.,    4.,  1.30, 20.8e5,'Shrubland'\n9,      22.,   .25,   .93,    1.,    4.,  1.24, 20.8e5,'Mixed Shrubland/Grassland'\n10,     20.,   .15,   .92,   15.,    3.,  2.00, 25.0e5,'Savanna'\n11,     17.,   .60,   .93,   50.,    5.,  2.40, 25.0e5,'Deciduous Broadleaf Forest'\n12,     15.,   .60,   .93,   50.,    5.,  2.60, 25.0e5,'Deciduous Needleleaf Forest'\n13,     12.,   .50,   .95,   50.,    5.,  1.67, 29.2e5,'Evergreen Broadleaf Forest'\n14,     12.,   .60,   .95,   50.,    5.,  3.00, 29.2e5,'Evergreen Needleleaf Forest'\n15,     14.,   .60,   .93,   20.,    6.,  1.12, 41.8e5,'Mixed Forest'\n16,      8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25,'Water Bodies'\n17,     14.,   .75,   .95,   20.,    6.,  1.50, 29.2e5,'Herbaceous Wetland'\n18,     14.,   .70,   .95,   40.,    6.,  1.14, 41.8e5,'Wooded Wetland'\n19,     23.,   .05,   .90,    1.,    2.,  0.81, 12.0e5,'Barren or Sparsely Vegetated'\n20,     15.,   .60,   .92,   10.,    5.,  2.00, 9.0e25,'Herbaceous Tundra'\n21,     15.,   .60,   .93,   30.,    5.,  1.75, 9.0e25,'Wooded Tundra'\n22,     15.,   .60,   .92,   15.,    5.,  1.75, 9.0e25,'Mixed Tundra'\n23,     25.,   .05,   .90,    5.,    5.,  1.80, 12.0e5,'Bare Ground Tundra'\n24,     70.,   .95,   .95,   0.1,    5.,    0., 9.0e25,'Snow or Ice'\n25,     40.,   .40,   .90,    1.,    5.,   .62, 12.0E5,'Playa'\n26,     18.,   .40,   .95,   15.,    5.,   .62, 12.0E5,'Lava'\n27,     70.,   .40,   .90,    1.,    5.,    0., 12.0E5,'White Sand'\n28,     15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5,'Unassigned'\n29,     15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5,'Unassigned'\n30,     15.,   .10,   .88,   80.,    3.,  1.67, 18.9e5,'Unassigned'\n31,     10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5,'Low Intensity Residential '\n32,     10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5,'High Intensity Residential'\n33,     10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5,'Industrial or Commercial'\nMODIFIED_IGBP_MODIS_NOAH\n33,2, 'ALBD   SLMO   SFEM   SFZ0 THERIN   SCFX   SFHC   '\nSUMMER\n1,     12.,   .30,   .95,   50.,    4.,  3.33, 29.2e5, 'Evergreen Needleleaf Forest'\n2,     12.,   .50,   .95,   50.,    5.,  1.67, 29.2e5, 'Evergreen Broadleaf Forest'\n3,     14.,   .30,   .94,   50.,    4.,  2.86, 25.0e5, 'Deciduous Needleleaf Forest'\n4,     16.,   .30,   .93,   50.,    4.,  2.63, 25.0e5, 'Deciduous Broadleaf Forest'\n5,     13.,   .30,   .97,   50.,    4.,  2.11, 41.8e5, 'Mixed Forests'\n6,     22.,   .10,   .93,    5.,    3.,  1.56, 20.8e5, 'Closed Shrublands'\n7,     20.,   .15,   .95,    6.,    3.,  2.14, 20.8e5, 'Open Shrublands'\n8,     22.,   .10,   .93,    5.,    3.,  1.56, 20.8e5, 'Woody Savannas'\n9,     20.,   .15,   .92,   15.,    3.,  2.00, 25.0e5, 'Savannas'\n10,    19.,   .15,   .96,   12.,    3.,  2.37, 20.8e5, 'Grasslands'\n11,    14.,   .42,   .95,   30.,   5.5,  1.32, 35.5e5, 'Permanent wetlands'\n12,    17.,   .30,  .985,   15.,    4.,  2.71, 25.0e5, 'Croplands'\n13,    15.,   .10,   .88,   80.,    3.,  1.67, 18.9e5, 'Urban and Built-Up'\n14,    18.,   .25,   .98,   14.,    4.,  2.56, 25.0e5, 'cropland/natural vegetation mosaic'\n15,    55.,   .95,   .95,   0.1,    5.,    0., 9.0e25, 'Snow and Ice'\n16,    25.,   .02,   .90,    1.,    2.,  0.81, 12.0e5, 'Barren or Sparsely Vegetated'\n17,     8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25, 'Water'\n18,    15.,   .50,   .93,   30.,    5.,  2.67, 9.0e25, 'Wooded Tundra'\n19,    15.,   .50,   .92,   15.,    5.,  2.67, 9.0e25, 'Mixed Tundra'\n20,    25.,   .02,   .90,   10.,    2.,  1.60, 12.0e5, 'Barren Tundra'\n21,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n22,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n23,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n24,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n25,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n26,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n27,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n28,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n29,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n30,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n31,    10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5, 'Low Intensity Residential '\n32,    10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5, 'High Intensity Residential'\n33,    10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5, 'Industrial or Commercial'\nWINTER\n1,     12.,   .60,   .95,   50.,    5.,  3.00, 29.2e5, 'Evergreen Needleleaf Forest'\n2,     12.,   .50,   .95,   50.,    5.,  1.67, 29.2e5, 'Evergreen Broadleaf Forest'\n3,     15.,   .60,   .93,   50.,    5.,  2.60, 25.0e5, 'Deciduous Needleleaf Forest'\n4,     17.,   .60,   .93,   50.,    5.,  2.40, 25.0e5, 'Deciduous Broadleaf Forest'\n5,     14.,   .60,   .93,   20.,    6.,  1.12, 41.8e5, 'Mixed Forests'\n6,     22.,   .20,   .93,    1.,    4.,  1.30, 20.8e5, 'Closed Shrublands'\n7,     22.,   .25,   .93,    1.,    4.,  1.24, 20.8e5, 'Open Shrublands'\n8,     22.,   .20,   .93,    1.,    4.,  1.30, 20.8e5, 'Woody Savannas'\n9,     20.,   .15,   .92,   15.,    3.,  2.00, 25.0e5, 'Savannas'\n10,    23.,   .30,   .92,   10.,    4.,  2.00, 20.8e5, 'Grasslands'\n11,    14.,   .725,  .95,   30.,    6.,  1.32, 35.5e5, 'Permanent wetlands'\n12,    20.,   .60,   .92,    5.,    4.,  2.00, 25.0e5, 'Croplands'\n13,    15.,   .10,   .88,   80.,    3.,  1.67, 18.9e5, 'Urban and Built-Up'\n14     20.,   .40,   .92,    5.,    4.,  2.00, 25.0e5, 'cropland/natural vegetation mosaic'\n15,    70.,   .95,   .95,   0.1,    5.,    0., 9.0e25, 'Snow and Ice'\n16,    23.,   .05,   .90,    1.,    2.,  0.81, 12.0e5, 'Barren or Sparsely Vegetated'\n17,     8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25, 'Water'\n18,    15.,   .60,   .93,   30.,    5.,  1.75, 9.0e25, 'Wooded Tundra'\n19,    15.,   .60,   .92,   15.,    5.,  1.75, 9.0e25, 'Mixed Tundra'\n20,    25.,   .05,   .90,    5.,    5.,  1.80, 12.0e5, 'Barren Tundra'\n21,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n22,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n23,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n24,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n25,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n26,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n27,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n28,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n29,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n30,    15.,   .02,   .88,   80.,    3.,  1.67, 18.9e5, 'Unassigned'\n31,    10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5, 'Low Intensity Residential '\n32,    10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5, 'High Intensity Residential'\n33,    10.,   .10,   .97,   80.,    3.,  1.67, 18.9e5, 'Industrial or Commercial'\nSiB\n16,2, 'ALBD   SLMO   SFEM   SFZ0 THERIN   SCFX   SFHC   '\nSUMMER\n1,      12.,   .50,   .95,   50.,    5.,  1.67, 29.2e5,'Evergreen Broadleaf Trees'\n2,      16.,   .30,   .93,   50.,    4.,  2.63, 25.0e5,'Broadleaf Deciduous Trees'\n3,      14.,   .35,   .95,   40.,    5.,  3.00, 41.8e5,'Deciduous and Evergreen Trees'\n4,      12.,   .30,   .95,   50.,    4.,  3.33, 29.2e5,'Evergreen Needleleaf Trees'\n5,      16.,   .30,   .93,   50.,    4.,  2.38, 25.0e5,'Deciduous Needleleaf Trees'\n6,      20.,   .15,   .92,   15.,    3.,  1.80, 25.0e5,'Ground Cover with Trees and Shrubs'\n7,      19.,   .15,   .92,   12.,    3.,  2.16, 20.8e5,'Groundcover Only'\n8,      19.,   .15,   .92,   12.,    3.,  2.53, 20.8e5,'Broadleaf Shrubs with Perennial Ground Cover'\n9,      19.,   .15,   .92,   12.,    3.,  2.63, 20.8e5,'Broadleaf Shrubs with Bare Soil'\n10,     15.,   .50,   .92,   10.,    5.,  2.73, 9.0e25,'Groundcover with Dwarf Trees and Shrubs'\n11,     25.,   .02,   .85,   10.,    2.,  1.76, 12.0e5,'Bare Soil'\n12,     17.,   .30,   .92,   15.,    4.,  2.76, 25.0e5,'Agriculture or C3 Grassland'\n13,     14.,   .50,   .95,   20.,    6.,  1.36, 29.2e5,'Persistent Wetland'\n14,     19.,   .15,   .92,   12.,    3.,  2.16, 20.8e5,'Dry Coastal Complexes'\n15,      8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25,'Water'\n16,     55.,   .95,   .95,    5.,    5.,    0., 9.0e25,'Ice Cap and Glacier'\nWINTER\n1,      12.,   .50,   .95,   50.,    5.,  1.67, 29.2e5,'Evergreen Broadleaf Trees'\n2,      17.,   .60,   .93,   50.,    5.,  2.41, 25.0e5,'Broadleaf Deciduous Trees'\n3,      14.,   .70,   .95,   40.,    6.,  2.79, 41.8e5,'Deciduous and Evergreen Trees'\n4,      12.,   .60,   .95,   50.,    5.,  3.33, 29.2e5,'Evergreen Needleleaf Trees'\n5,      17.,   .60,   .93,   50.,    5.,  2.16, 25.0e5,'Deciduous Needleleaf Trees'\n6,      20.,   .15,   .92,   15.,    3.,  1.80, 25.0e5,'Ground Cover with Trees and Shrubs'\n7,      23.,   .30,   .92,   10.,    4.,  2.00, 20.8e5,'Groundcover Only'\n8,      23.,   .30,   .92,   10.,    4.,  1.91, 20.8e5,'Broadleaf Shrubs with Perennial Ground Cover'\n9,      23.,   .30,   .92,   10.,    4.,  1.91, 20.8e5,'Broadleaf Shrubs with Bare Soil'\n10,     20.,   .90,   .92,   10.,    5.,  1.80, 9.0e25,'Groundcover with Dwarf Trees and Shrubs'\n11,     25.,   .05,   .85,   10.,    2.,  1.76, 12.0e5,'Bare Soil'\n12,     23.,   .60,   .92,    5.,    4.,  1.78, 25.0e5,'Agriculture or C3 Grassland'\n13,     14.,   .75,   .95,   20.,    6.,  1.50, 29.2e5,'Persistent Wetland'\n14,     23.,   .30,   .92,   10.,    4.,  1.61, 20.8e5,'Dry Coastal Complexes'\n15,      8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25,'Water'\n16,     70.,   .95,   .95,    5.,    5.,    0., 9.0e25,'Ice Cap and Glacier'\nLW12 \n3,1, 'ALBD   SLMO   SFEM   SFZ0 THERIN   SCFX   SFHC   '\nALL-SEASON\n1,      20.,   0.3,   .85,   10.,    4.,  2.00, 20.8e5,'Land'\n2,       8.,   1.0,   .98,  0.01,    6.,    0., 9.0e25,'Water'\n3,      70.,   .95,   .95,    5.,    5.,    0., 9.0e25,'Snow or Ice'\n"
  },
  {
    "path": "src/Land_models/Noah/Run/Makefile",
    "content": ".SUFFIXES:\n.SUFFIXES: .o .f\n\ninclude ../user_build_options\ninclude ../../../macros\n\nOBJS = \\\n\t../IO_code/Noah_hrldas_driver.o \\\n\t../IO_code/module_hrldas_netcdf_io.o \\\n\t../Noah/module_sf_noahlsm.o \\\n\t../Noah/module_sf_urban.o \\\n\t../Utility_routines/module_Noahlsm_utility.o \\\n\t../Utility_routines/module_model_constants.o \\\n\t../Utility_routines/module_sfcdif_wrf.o \\\n\t../Utility_routines/module_date_utilities.o \\\n\t../Utility_routines/kwm_string_utilities.o\n\nCMD = Noah_hrldas_beta\nall:\t$(CMD)\n\nNoah_hrldas_beta: $(OBJS)\n\t@echo \"\"\n# We have to include the modules built in ../IO_code \n\t$(COMPILERF90) -o $(@) $(MODFLAG) -I ../IO_code $(OBJS) $(NETCDFLIB) $(HDF5LIB) -L../../../lib  -lHYDRO $(NETCDFLIB) $(LDFLAGS) $(LIBS)\n\t@echo \"\"\n\n# This command cleans up\nclean:\n\t$(RM) *~ $(CMD)\n\n"
  },
  {
    "path": "src/Land_models/Noah/Run/SOILPARM.TBL",
    "content": "Soil Parameters\nSTAS\n19,1   'BB      DRYSMC      F11     MAXSMC   REFSMC   SATPSI  SATDK      SATDW     WLTSMC  QTZ    '\n1,     2.79,    0.010,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,   0.010,  0.92, 'SAND'\n2,     4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.82, 'LOAMY SAND'\n3,     4.74,    0.047,    -0.569,   0.434,   0.312,   0.141,  5.23E-6,  8.05E-6,   0.047,  0.60, 'SANDY LOAM'\n4,     5.33,    0.084,     0.162,   0.476,   0.360,   0.759,  2.81E-6,  2.39E-5,   0.084,  0.25, 'SILT LOAM'\n5,     3.86,    0.061,     0.162,   0.484,   0.347,   0.955,  2.18E-6,  1.66E-5,   0.061,  0.10, 'SILT'\n6,     5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.40, 'LOAM'\n7,     6.77,    0.069,    -1.491,   0.404,   0.315,   0.135,  4.45E-6,  1.01E-5,   0.069,  0.60, 'SANDY CLAY LOAM'\n8,     8.72,    0.120,    -1.118,   0.464,   0.387,   0.617,  2.03E-6,  2.35E-5,   0.120,  0.10, 'SILTY CLAY LOAM'\n9,     8.17,    0.103,    -1.297,   0.465,   0.382,   0.263,  2.45E-6,  1.13E-5,   0.103,  0.35, 'CLAY LOAM'\n10,   10.73,    0.100,    -3.209,   0.406,   0.338,   0.098,  7.22E-6,  1.87E-5,   0.100,  0.52, 'SANDY CLAY'\n11,   10.39,    0.126,    -1.916,   0.468,   0.404,   0.324,  1.34E-6,  9.64E-6,   0.126,  0.10, 'SILTY CLAY'\n12,   11.55,    0.138,    -2.138,   0.468,   0.412,   0.468,  9.74E-7,  1.12E-5,   0.138,  0.25, 'CLAY'\n13,    5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.05, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,       0.0,     1.0,     0.0,     0.0,      0.0,      0.0,     0.0,  0.60, 'WATER'\n15,    2.79,    0.006,    -1.111,    0.20,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.07, 'BEDROCK'\n16,    4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.25, 'OTHER(land-ice)'\n17,   11.55,    0.030,   -10.472,   0.468,   0.454,   0.468,  9.74E-7,  1.12E-5,   0.030,  0.60, 'PLAYA'\n18,    2.79,    0.006,    -0.472,   0.200,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.52, 'LAVA'\n19,    2.79,     0.01,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,    0.01,  0.92, 'WHITE SAND'\nSoil Parameters\nSTAS-RUC\n19,1   'BB      DRYSMC       HC     MAXSMC   REFSMC   SATPSI  SATDK       SATDW     WLTSMC  QTZ    '\n1,     4.05,    0.002,      1.47,   0.395,   0.174,   0.121,  1.76E-4,  0.608E-6,   0.033,  0.92, 'SAND'\n2,     4.38,    0.035,      1.41,   0.410,   0.179,   0.090,  1.56E-4,  0.514E-5,   0.055,  0.82, 'LOAMY SAND'\n3,     4.90,    0.041,      1.34,   0.435,   0.249,   0.218,  3.47E-5,  0.805E-5,   0.095,  0.60, 'SANDY LOAM'\n4,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.25, 'SILT LOAM'\n5,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.10, 'SILT'\n6,     5.39,    0.050,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.137,  0.40, 'LOAM'\n7,     7.12,    0.068,      1.18,   0.420,   0.299,   0.299,  6.30E-6,  0.990E-5,   0.148,  0.60, 'SANDY CLAY LOAM'\n8,     7.75,    0.060,      1.32,   0.477,   0.357,   0.356,  1.70E-6,  0.237E-4,   0.208,  0.10, 'SILTY CLAY LOAM'\n9,     8.52,    0.085,      1.23,   0.476,   0.391,   0.630,  2.45E-6,  0.113E-4,   0.230,  0.35, 'CLAY LOAM'\n10,   10.40,    0.100,      1.18,   0.426,   0.316,   0.153,  2.17E-6,  0.187E-4,   0.210,  0.52, 'SANDY CLAY'\n11,   10.40,    0.070,      1.15,   0.492,   0.409,   0.490,  1.03E-6,  0.964E-5,   0.250,  0.10, 'SILTY CLAY'\n12,   11.40,    0.068,      1.09,   0.482,   0.400,   0.405,  1.28E-6,  0.112E-4,   0.268,  0.25, 'CLAY'\n13,    5.39,    0.027,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.117,  0.05, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,      4.18,   1.0,     1.0,     0.0,      0.0,       0.0,     0.0,    0.00, 'WATER'\n15,    4.05,    0.004,      2.03,   0.200,   0.10 ,   0.121,  1.41E-4,  0.136E-3,   0.006,  0.60, 'BEDROCK'\n16,    4.90,    0.065,      2.10,   0.435,   0.249,   0.218,  3.47E-5,  0.514E-5,   0.114,  0.05, 'OTHER(land-ice)'\n17,   11.40,    0.030,      1.41,   0.468,   0.454,   0.468,  9.74E-7,  0.112E-4,   0.030,  0.60, 'PLAYA'\n18,    4.05,    0.006,      1.41,   0.200,   0.17,    0.069,  1.41E-4,  0.136E-3,   0.006,  0.52, 'LAVA'\n19,    4.05,     0.01,      1.47,   0.339,   0.236,   0.069,  1.76E-4,  0.608E-6,   0.060,  0.92, 'WHITE SAND'\n\n"
  },
  {
    "path": "src/Land_models/Noah/Run/URBPARM.TBL",
    "content": "# The parameters in this table may vary greatly from city to city.\n# The default values are probably not appropriate for any given city.\n# Users should adapt these values based on the city they are working\n# with.\n\n# Urban Parameters depending on Urban type\n# USGS\n\nNumber of urban categories: 3\n\n#\n#  Where there are multiple columns of values, the values refer, in\n#  order, to: 1) Commercial, 2) High intensity residential, and 3) Low\n#  intensity residential:  I.e.:\n#\n#  Index:     1           2              3\n#  Type:  Commercial, Hi-dens Res, Low-dens Res\n#\n\n#\n# ZR:  Roof level (building height)  [ m ]\n#      (sf_urban_physics=1)\n\nZR: 10.0,  7.5,  5.0\n\n#\n# SIGMA_ZED:  Standard Deviation of roof height  [ m ]\n#      (sf_urban_physics=1)\n\nSIGMA_ZED: 4.0,  3.0,  1.0\n\n#\n# ROOF_WIDTH:  Roof (i.e., building) width  [ m ]\n#      (sf_urban_physics=1)\n\nROOF_WIDTH: 10.0, 9.4, 8.3\n\n#\n# ROAD_WIDTH:  road width  [ m ]\n#      (sf_urban_physics=1)\n#\n\nROAD_WIDTH: 10.0, 9.4, 8.3\n\n#\n# AH:  Anthropogenic heat [ W m{-2} ]\n#      (sf_urban_physics=1)\n#\n\nAH:  90.0, 50.0, 20.0\n\n#\n# FRC_URB:  Fraction of the urban landscape which does not have natural\n#           vegetation. [ Fraction ]\n#      (sf_urban_physics=1,2,3)\n#\n\nFRC_URB: 0.95, 0.9, 0.5\n\n#\n# CAPR:  Heat capacity of roof  [ J m{-3} K{-1} ]\n#      (sf_urban_physics=1,2,3)\n#\n\nCAPR: 1.0E6, 1.0E6, 1.0E6,\n\n#\n# CAPB:  Heat capacity of building wall [ J m{-3} K{-1} ]\n#      (sf_urban_physics=1,2,3)\n#\n\nCAPB: 1.0E6, 1.0E6, 1.0E6,\n\n#\n# CAPG:  Heat capacity of ground (road) [ J m{-3} K{-1} ]\n#      (sf_urban_physics=1,2,3)\n#\n\nCAPG:  1.4E6, 1.4E6, 1.4E6,\n\n#\n# AKSR:  Thermal conductivity of roof [ J m{-1} s{-1} K{-1} ]\n#      (sf_urban_physics=1,2,3)\n#\n\nAKSR:  0.67, 0.67, 0.67,\n\n#\n# AKSB:  Thermal conductivity of building wall [ J m{-1} s{-1} K{-1} ]\n#      (sf_urban_physics=1,2,3)\n#\n\nAKSB:  0.67, 0.67, 0.67,\n\n#\n# AKSG:  Thermal conductivity of ground (road) [ J m{-1} s{-1} K{-1} ]\n#      (sf_urban_physics=1,2,3)\n#\n\nAKSG: 0.4004, 0.4004, 0.4004,\n\n#\n# ALBR:   Surface albedo of roof [ fraction ]\n#      (sf_urban_physics=1,2,3)\n#\n\nALBR: 0.20, 0.20, 0.20\n\n#\n# ALBB:  Surface albedo of building wall [ fraction ]\n#      (sf_urban_physics=1,2,3)\n#\n\nALBB: 0.20, 0.20, 0.20\n\n#\n# ALBG:  Surface albedo of ground (road) [ fraction ]\n#      (sf_urban_physics=1,2,3)\n#\n\nALBG: 0.20, 0.20, 0.20\n\n#\n# EPSR:  Surface emissivity of roof [ - ]\n#      (sf_urban_physics=1,2,3)\n#\n\nEPSR: 0.90, 0.90, 0.90\n\n#\n# EPSB:  Surface emissivity of building wall [-]\n#      (sf_urban_physics=1,2,3)\n#\n\nEPSB: 0.90, 0.90, 0.90\n\n#\n# EPSG:  Surface emissivity of ground (road) [ - ]\n#      (sf_urban_physics=1,2,3)\n#\n\nEPSG: 0.95, 0.95, 0.95\n\n#\n# Z0B:  Roughness length for momentum, over building wall [ m ]\n#       Only active for CH_SCHEME == 1\n#      (sf_urban_physics=1)\n#\n\nZ0B: 0.0001, 0.0001, 0.0001\n\n#\n# Z0G:  Roughness length for momentum, over ground (road) [ m ]\n#       Only active for CH_SCHEME == 1\n#      (sf_urban_physics=1,2,3)\n#\n\nZ0G: 0.01, 0.01, 0.01\n\n#\n# Z0R:  Roughness length for momentum over roof [ m ]\n#      (sf_urban_physics=2,3)\n#\n\nZ0R: 0.01, 0.01, 0.01\n\n#\n#  AKANDA_URBAN:  Coefficient modifying the Kanda approach to computing\n#  surface layer exchange coefficients.\n#      (sf_urban_physics=1)\n\nAKANDA_URBAN:  1.29 1.29 1.29\n\n#\n# COP:  Coefficient of performance of the A/C systems [ - ]\n#      (sf_urban_physics=3)\n#\n\nCOP: 3.5, 3.5, 3.5\n\n#\n# PWIN:  Coverage area fraction of windows in the walls of the building [ - ]\n#      (sf_urban_physics=3)\n#\n\nPWIN: 0.2, 0.2, 0.2\n\n#\n# BETA:  Thermal efficiency of heat exchanger\n#      (sf_urban_physics=3)\n#\n\nBETA: 0.75, 0.75, 0.75\n\n#\n# SW_COND:  Air conditioning switch, 1=ON\n#      (sf_urban_physics=3)\n#\n\nSW_COND: 1, 1, 1\n\n#\n# TIME_ON:  Initial local time of A/C systems, [ h ]\n#      (sf_urban_physics=3)\n#\n\nTIME_ON: 0., 0., 0.\n\n#\n# TIME_OFF:  End local time of A/C systems, [ h ]\n#      (sf_urban_physics=3)\n#\n\nTIME_OFF: 24., 24., 24.\n\n#\n# TARGTEMP:  Target Temperature of the A/C systems, [ K ]\n#      (sf_urban_physics=3)\n#\n\nTARGTEMP: 297., 298., 298.\n\n#\n# GAPTEMP:  Comfort Range of the indoor Temperature, [ K ]\n#      (sf_urban_physics=3)\n#\n\nGAPTEMP: 0.5, 0.5, 0.5\n\n#\n# TARGHUM:  Target humidity of the A/C systems, [ Kg/Kg ]\n#      (sf_urban_physics=3)\n#\n\nTARGHUM: 0.005, 0.005, 0.005\n\n#\n# GAPHUM:  Comfort Range of the specific humidity, [ Kg/Kg ]\n#      (sf_urban_physics=3)\n#\n\nGAPHUM: 0.005, 0.005, 0.005\n\n#\n# PERFLO:  Peak number of occupants per unit floor area, [ person/m^2 ]\n#      (sf_urban_physics=3)\n#\n\nPERFLO: 0.02, 0.01, 0.01\n\n#\n# HSEQUIP:  Diurnal heating profile of heat generated by equipments\n#      (sf_urban_physics=3)\n#\n\nHSEQUIP: 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.5 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.5 0.25 0.25 0.25 0.25 0.25\n\n#\n# HSEQUIP_SCALE_FACTOR:  Peak heat generated by equipments, [ W/m^2 ]\n#      (sf_urban_physics=3)\n#\n\nHSEQUIP_SCALE_FACTOR: 36.00, 20.00, 16.00\n\nSTREET PARAMETERS:\n#      (sf_urban_physics=2,3)\n\n#  urban      street      street     building\n# category  direction     width      width\n# [index]  [deg from N]    [m]        [m]\n\n    1         0.0          20.       20.\n    1        90.0          20.       20.\n    2         0.0          25.       17.\n    2        90.0          25.       17.\n    3         0.0          30.       13.\n    3        90.0          30.       13.\n\nEND STREET PARAMETERS\n\nBUILDING HEIGHTS: 1\n#      (sf_urban_physics=2,3)\n\n#     height   Percentage\n#      [m]       [%]\n       5.0       0.0\n      10.0       0.0\n      15.0      10.0\n      20.0      25.0\n      25.0      40.0\n      30.0      25.0\n      35.0       0.0\nEND BUILDING HEIGHTS\n\nBUILDING HEIGHTS: 2\n#      (sf_urban_physics=2,3)\n\n#     height   Percentage\n#      [m]       [%]\n       5.0        0.0\n      10.0       20.0\n      15.0       60.0\n      20.0       20.0\nEND BUILDING HEIGHTS\n\nBUILDING HEIGHTS: 3\n#      (sf_urban_physics=2,3)\n\n#     height   Percentage\n#      [m]       [%]\n       5.0      15.0\n      10.0      70.0\n      15.0      15.0\nEND BUILDING HEIGHTS\n#\n# DDZR:  Thickness of each roof layer [ m ]\n#        This is currently NOT a function urban type, but a function\n#        of the number of layers.  Number of layers must be 4, for now.\n#      (sf_urban_physics=1)\n\n\nDDZR:  0.05, 0.05, 0.05, 0.05\n\n#\n# DDZB:  Thickness of each building wall layer [ m ]\n#        This is currently NOT a function urban type, but a function\n#        of the number of layers.  Number of layers must be 4, for now.\n#      (sf_urban_physics=1)\n#\n\nDDZB: 0.05, 0.05, 0.05, 0.05\n\n#\n# DDZG:  Thickness of each ground (road) layer [ m ]\n#        This is currently NOT a function urban type, but a function\n#        of the number of layers.  Number of layers must be 4, for now.\n#      (sf_urban_physics=1)\n#\n\nDDZG: 0.05, 0.25, 0.50, 0.75\n\n#\n# BOUNDR:  Lower boundary condition for roof layer temperature [ 1: Zero-Flux,  2: T = Constant ]\n#      (sf_urban_physics=1)\n#\n\nBOUNDR: 1\n\n#\n# BOUNDB:  Lower boundary condition for wall layer temperature [ 1: Zero-Flux,  2: T = Constant ]\n#      (sf_urban_physics=1)\n#\n\nBOUNDB: 1\n\n#\n# BOUNDG:  Lower boundary condition for ground (road) layer temperature [ 1: Zero-Flux,  2: T = Constant ]\n#      (sf_urban_physics=1)\n#\n\nBOUNDG: 1\n\n#\n# TRLEND:  Lower boundary condition for roof temperature [ K ]\n#      (sf_urban_physics=1,2,3)\n#\n\nTRLEND: 293.00, 293.00, 293.00\n\n#\n# TBLEND:  Lower boundary temperature for building wall temperature [ K ]\n#      (sf_urban_physics=1,2,3)\n#\n\nTBLEND: 293.00, 293.00, 293.00\n\n#\n# TGLEND:  Lower boundary temperature for ground (road) temperature [ K ]\n#      (sf_urban_physics=1,2,3)\n#\n\nTGLEND: 293.00, 293.00, 293.00\n\n#\n# Ch of Wall and Road [ 1: M-O Similarity Theory, 2: Empirical Form of Narita et al., 1997 (recommended) ]\n#      (sf_urban_physics=1)\n#\n\nCH_SCHEME: 2\n\n#\n# Surface and Layer Temperatures [ 1: 4-layer model,  2: Force-Restore method ]\n#      (sf_urban_physics=1)\n#\n\nTS_SCHEME: 1\n\n#\n# AHOPTION [ 0: No anthropogenic heating,  1: Anthropogenic heating will be added to sensible heat flux term ]\n#      (sf_urban_physics=1)\n#\n\nAHOPTION: 0\n\n#\n# Anthropogenic Heating diurnal profile.\n#   Multiplication factor applied to AH (as defined in the table above)\n#   Hourly values ( 24 of them ), starting at 01 hours Local Time.\n#   For sub-hourly model time steps, value changes on the hour and is\n#   held constant until the next hour.\n#      (sf_urban_physics=1)\n#\n#\n\nAHDIUPRF: 0.16 0.13 0.08 0.07 0.08 0.26 0.67 0.99 0.89 0.79 0.74 0.73 0.75 0.76 0.82 0.90 1.00 0.95 0.68 0.61 0.53 0.35 0.21 0.18\n"
  },
  {
    "path": "src/Land_models/Noah/Run/VEGPARM.TBL",
    "content": "Vegetation Parameters\nUSGS\n27,1, 'SHDFAC NROOT   RS      RGL      HS      SNUP  MAXALB   LAIMIN  LAIMAX  EMISSMIN EMISSMAX ALBEDOMIN ALBEDOMAX  Z0MIN    Z0MAX  '\n1,      .10,   1,    200.,   999.,   999.0,   0.04,    46.,    1.00,   1.00,   .880,    .880,     .15,      .15,      .50,     .50,     'Urban and Built-Up Land'  \n2,      .80,   3,     40.,   100.,   36.25,   0.04,    66.,    1.56,   5.68,   .920,    .985,     .17,      .23,      .05,     .15,     'Dryland Cropland and Pasture' \n3,      .80,   3,     40.,   100.,   36.25,   0.04,    66.,    1.56,   5.68,   .930,    .985,     .20,      .25,      .02,     .10,     'Irrigated Cropland and Pasture' \n4,      .80,   3,     40.,   100.,   36.25,   0.04,    66.,    1.00,   4.50,   .920,    .985,     .18,      .23,      .05,     .15,     'Mixed Dryland/Irrigated Cropland and Pasture' \n5,      .80,   3,     40.,   100.,   36.25,   0.04,    68.,    2.29,   4.29,   .920,    .980,     .18,      .23,      .05,     .14,     'Cropland/Grassland Mosaic'\n6,      .80,   3,     70.,    65.,   44.14,   0.04,    60.,    2.00,   4.00,   .930,    .985,     .16,      .20,      .20,     .20,     'Cropland/Woodland Mosaic' \n7,      .80,   3,     40.,   100.,   36.35,   0.04,    70.,    0.52,   2.90,   .920,    .960,     .19,      .23,      .10,     .12,     'Grassland' \n8,      .70,   3,    300.,   100.,   42.00,   0.03,    60.,    0.50,   3.66,   .930,    .930,     .25,      .30,      .01,     .05,     'Shrubland' \n9,      .70,   3,    170.,   100.,   39.18,  0.035,    65.,    0.60,   2.60,   .930,    .950,     .22,      .30,      .01,     .06,     'Mixed Shrubland/Grassland' \n10,     .50,   3,     70.,    65.,   54.53,   0.04,    50.,    0.50,   3.66,   .920,    .920,     .20,      .20,      .15,     .15,     'Savanna' \n11,     .80,   4,    100.,    30.,   54.53,   0.08,    58.,    1.85,   3.31,   .930,    .930,     .16,      .17,      .50,     .50,     'Deciduous Broadleaf Forest' \n12,     .70,   4,    150.,    30.,   47.35,   0.08,    54.,    1.00,   5.16,   .930,    .940,     .14,      .15,      .50,     .50,     'Deciduous Needleleaf Forest' \n13,     .95,   4,    150.,    30.,   41.69,   0.08,    35.,    3.08,   6.48,   .950,    .950,     .12,      .12,      .50,     .50,     'Evergreen Broadleaf Forest'\n14,     .70,   4,    125.,    30.,   47.35,   0.08,    52.,    5.00,   6.40,   .950,    .950,     .12,      .12,      .50,     .50,     'Evergreen Needleleaf Forest'  \n15,     .80,   4,    125.,    30.,   51.93,   0.08,    53.,    2.80,   5.50,   .930,    .970,     .17,      .25,      .20,     .50,     'Mixed Forest' \n16,     .00,   0,    100.,    30.,   51.75,   0.01,    70.,    0.01,   0.01,   .980,    .980,     .08,      .08,   0.0001,  0.0001,     'Water Bodies' \n17,     .60,   2,     40.,   100.,   60.00,   0.01,    68.,    1.50,   5.65,   .950,    .950,     .14,      .14,      .20,     .20,     'Herbaceous Wetland' \n18,     .60,   2,    100.,    30.,   51.93,   0.02,    50.,    2.00,   5.80,   .950,    .950,     .14,      .14,      .40,     .40,     'Wooded Wetland' \n19,     .01,   1,    999.,   999.,   999.0,   0.02,    75.,    0.10,   0.75,   .900,    .900,     .38,      .38,      .01,     .01,     'Barren or Sparsely Vegetated' \n20,     .60,   3,    150.,   100.,   42.00,  0.025,    68.,    0.41,   3.35,   .920,    .920,     .15,      .20,      .10,     .10,     'Herbaceous Tundra' \n21,     .60,   3,    150.,   100.,   42.00,  0.025,    55.,    0.41,   3.35,   .930,    .930,     .15,      .20,      .30,     .30,     'Wooded Tundra' \n22,     .60,   3,    150.,   100.,   42.00,  0.025,    60.,    0.41,   3.35,   .920,    .920,     .15,      .20,      .15,     .15,     'Mixed Tundra' \n23,     .30,   2,    200.,   100.,   42.00,   0.02,    75.,    0.41,   3.35,   .900,    .900,     .25,      .25,      .05,     .10,     'Bare Ground Tundra' \n24,     .00,   1,    999.,   999.,   999.0,   0.02,    82.,    0.01,   0.01,   .950,    .950,     .55,      .70,    0.001,   0.001,     'Snow or Ice' \n25,     .50,   1,     40.,   100.,   36.25,   0.02,    75.,    0.01,   0.01,   .890,    .890,     .30,      .30,      .01,     .01,     'Playa' \n26,     .00,   0,    999.,   999.,   999.0,   0.02,    75.,    0.01,   0.01,   .880,    .880,     .16,      .16,      .15,     .15,     'Lava'   \n27,     .00,   0,    999.,   999.,   999.0,   0.02,    75.,    0.01,   0.01,   .830,    .830,     .60,      .60,      .01,     .01,     'White Sand' \nTOPT_DATA\n298.0\nCMCMAX_DATA\n0.5E-3\nCFACTR_DATA\n0.5\nRSMAX_DATA\n5000.0\nBARE\n19\nNATURAL\n5\nVegetation Parameters\nMODIFIED_IGBP_MODIS_NOAH\n20,1, 'SHDFAC NROOT   RS      RGL      HS      SNUP  MAXALB   LAIMIN  LAIMAX   EMISSMIN EMISSMAX ALBEDOMIN ALBEDOMAX   Z0MIN    Z0MAX'\n1       .70,   4,    125.,    30.,   47.35,   0.08,    52.,    5.00,   6.40,   .950,    .950,     .12,      .12,      .50,     .50,         'Evergreen Needleleaf Forest'\n2,      .95,   4,    150.,    30.,   41.69,   0.08,    35.,    3.08,   6.48,   .950,    .950,     .12,      .12,      .50,     .50,         'Evergreen Broadleaf Forest'\n3,      .70,   4,    150.,    30.,   47.35,   0.08,    54.,    1.00,   5.16,   .930,    .940,     .14,      .15,      .50,     .50,         'Deciduous Needleleaf Forest'\n4,      .80,   4,    100.,    30.,   54.53,   0.08,    58.,    1.85,   3.31,   .930,    .930,     .16,      .17,      .50,     .50,         'Deciduous Broadleaf Forest'\n5,      .80,   4,    125.,    30.,   51.93,   0.08,    53.,    2.80,   5.50,   .930,    .970,     .17,      .25,      .20,     .50,         'Mixed Forests'\n6,      .70,   3,    300.,   100.,   42.00,   0.03,    60.,    0.50,   3.66,   .930,    .930,     .25,      .30,      .01,     .05,         'Closed Shrublands'\n7,      .70,   3,    170.,   100.,   39.18,  0.035,    65.,    0.60,   2.60,   .930,    .950,     .22,      .30,      .01,     .06,         'Open Shrublands'\n8,      .70,   3,    300.,   100.,   42.00,   0.03,    60.,    0.50,   3.66,   .930,    .930,     .25,      .30,      .01,     .05,         'Woody Savannas'\n9,      .50,   3,     70.,    65.,   54.53,   0.04,    50.,    0.50,   3.66,   .920,    .920,     .20,      .20,      .15,     .15,         'Savannas'\n10,     .80,   3,     40.,   100.,   36.35,   0.04,    70.,    0.52,   2.90,   .920,    .960,     .19,      .23,      .10,     .12,         'Grasslands'\n11      .60,   2,     70.,    65.,   55.97   0.015     59.,    1.75,   5.72,   .950,    .950,     .14,      .14,      .30,     .30,         'Permanent wetlands'\n12,     .80,   3,     40.,   100.,   36.25,   0.04,    66.,    1.56,   5.68,   .920,    .985,     .17,      .23,      .05,     .15,         'Croplands'\n13,     .10,   1,    200.,   999.,   999.0,   0.04,    46.,    1.00,   1.00,   .880,    .880,     .15,      .15,      .50,     .50,         'Urban and Built-Up'\n14      .80,   3,     40.,   100.,   36.25,   0.04,    68.,    2.29,   4.29,   .920,    .980,     .18,      .23,      .05,     .14,         'cropland/natural vegetation mosaic'\n15,     .00,   1,    999.,   999.,   999.0,   0.02,    82.,    0.01,   0.01,   .950,    .950,     .55,      .70,    0.001,   0.001,         'Snow and Ice'\n16,     .01,   1,    999.,   999.,   999.0,   0.02,    75.,    0.10,   0.75,   .900,    .900,     .38,      .38,      .01,     .01,         'Barren or Sparsely Vegetated'\n17,     .00,   0,    100.,    30.,   51.75,   0.01,    70.,    0.01,   0.01,   .980,    .980,     .08,      .08,   0.0001,  0.0001,         'Water'\n18,     .60,   3,    150.,   100.,   42.00,  0.025,    55.,    0.41,   3.35,   .930,    .930,     .15,      .20,      .30,     .30,         'Wooded Tundra'\n19,     .60,   3,    150.,   100.,   42.00,  0.025,    60.,    0.41,   3.35,   .920,    .920,     .15,      .20,      .15,     .15,         'Mixed Tundra'\n20,     .30,   2,    200.,   100.,   42.00,   0.02,    75.,    0.41,   3.35,   .900,    .900,     .25,      .25,      .05,     .10,         'Barren Tundra'\nTOPT_DATA\n298.0\nCMCMAX_DATA\n0.5E-3\nCFACTR_DATA\n0.5\nRSMAX_DATA\n5000.0\nBARE\n16\nNATURAL\n14\nVegetation Parameters\nUSGS-RUC\n27,1, 'ALBEDO    Z0   LEMI     PC   SHDFAC NROOT   RS      RGL      HS      SNUP    LAI   MAXALB'\n1,     .18,     .50,   .88,   .40,   .10,   1,    200.,   999.,   999.0,   0.04,   4.0,     40.,    'Urban and Built-Up Land'\n2,     .17,     .06,   .92,   .30,   .80,   3,     40.,   100.,   36.25,   0.04,   4.0,     64.,    'Dryland Cropland and Pasture'\n3,     .18,     .075,  .92,   .40,   .80,   3,     40.,   100.,   36.25,   0.04,   4.0,     64.,    'Irrigated Cropland and Pasture'\n4,     .18,     .065,  .92,   .40,   .80,   3,     40.,   100.,   36.25,   0.04,   4.0,     64.,    'Mixed Dryland/Irrigated Cropland and Pasture'\n5,     .18,     .05,   .92,   .40,   .80,   3,     40.,   100.,   36.25,   0.04,   4.0,     64.,    'Cropland/Grassland Mosaic'\n6,     .16,     .20,   .93,   .40,   .80,   3,     70.,    65.,   44.14,   0.04,   4.0,     60.,    'Cropland/Woodland Mosaic'\n7,     .19,     .075   .92,   .40,   .80,   3,     40.,   100.,   36.35,   0.04,   4.0,     64.,    'Grassland'\n8,     .22,     .10,   .88,   .40,   .70,   3,    300.,   100.,   42.00,   0.03,   4.0,     69.,    'Shrubland'\n9,     .20,     .11,   .90,   .40,   .70,   3,    170.,   100.,   39.18,  0.035,   4.0,     67.,    'Mixed Shrubland/Grassland'\n10,    .20,     .15,   .92,   .40,   .50,   3,     70.,    65.,   54.53,   0.04,   4.0,     45.,    'Savanna'\n11,    .16,     .50,   .93,   .55,   .80,   4,    100.,    30.,   54.53,   0.08,   4.0,     58.,    'Deciduous Broadleaf Forest'\n12,    .14,     .50,   .94,   .55,   .70,   4,    150.,    30.,   47.35,   0.08,   4.0,     54.,    'Deciduous Needleleaf Forest'\n13,    .12,     .50,   .95,   .55,   .95,   4,    150.,    30.,   41.69,   0.08,   4.0,     32.,    'Evergreen Broadleaf Forest'\n14,    .12,     .50,   .95,   .55,   .70,   4,    125.,    30.,   47.35,   0.08,   4.0,     52.,    'Evergreen Needleleaf Forest'\n15,    .13,     .50,   .94,   .55,   .80,   4,    125.,    30.,   51.93,   0.08,   4.0,     53.,    'Mixed Forest'\n16,    .08,    .0001,  .98,   .00,   .00,   0,    100.,    30.,   51.75,   0.01,   4.0,     70.,    'Water Bodies'\n17,    .14,     .20,   .95,   .55,   .60,   2,     40.,   100.,   60.00,   0.01,   4.0,     35.,    'Herbaceous Wetland'\n18,    .14,     .40,   .95,   .55,   .60,   2,    100.,    30.,   51.93,   0.02,   4.0,     30.,    'Wooded Wetland'\n19,    .25,     .05,   .85,   .30,   .01,   1,    999.,   999.,   999.0,   0.02,   4.0,     69.,    'Barren or Sparsely Vegetated'\n20,    .15,     .10,   .92,   .30,   .60,   3,    150.,   100.,   42.00,  0.025,   4.0,     58.,    'Herbaceous Tundra'\n21,    .15,     .15,   .93,   .40,   .60,   3,    150.,   100.,   42.00,  0.025,   4.0,     55.,    'Wooded Tundra'\n22,    .15,     .10,   .92,   .40,   .60,   3,    150.,   100.,   42.00,  0.025,   4.0,     55.,    'Mixed Tundra'\n23,    .25,     .065   .85,   .30,   .30,   2,    200.,   100.,   42.00,   0.02,   4.0,     65.,    'Bare Ground Tundra'\n24,    .55,     .05,   .95,   .00,   .00,   1,    999.,   999.,   999.0,   0.02,   4.0,     75.,    'Snow or Ice'\n25,    .30,     .01,   .85,   .30,   .50,   1,     40.,   100.,   36.25,   0.02,   4.0,     69.,    'Playa'\n26,    .16,     .15,   .85,   .00,   .00,   0,    999.,   999.,   999.0,   0.02,   4.0,     69.,    'Lava'\n27,    .60,     .01,   .90,   .00,   .00,   0,    999.,   999.,   999.0,   0.02,   4.0,     69.,    'White Sand'\nTOPT_DATA\n298.0\nCMCMAX_DATA\n0.5E-3\nCFACTR_DATA\n0.5\nRSMAX_DATA\n5000.0\nBARE\n19\nNATURAL\n5\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/Makefile",
    "content": "SHELL=/bin/sh\n.SUFFIXES:\t\n.SUFFIXES:\t.F .c .o .exe\n\ninclude ../user_build_options\n\n# OBJS=\thrldas_extract_point.o \\\n# \tmodule_date_utilities.o \\\n# \targuments_module.o \\\n# \tllxy_generic.o \\\n# \tlccone.o\n\nCMD=\thrldas_extract_point gribextract gribedition gribbyte modify_wrfinput geth_newdate\n\nall: $(CMD)\n\t( cd gcip_sw_to_grib; make )\n\n#\n# Compile the module_date_utilities from the Utility_routines directory\n#\nmodule_date_utilities.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(FREESOURCE) $(F90FLAGS) -c ../Utility_routines/$(*).F\n\n#\n# Compile the arguments_module from the HRLDAS_COLLECT_DATA/lib directory\n#\narguments_module.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(FREESOURCE) $(F90FLAGS) -c ../HRLDAS_COLLECT_DATA/lib/$(*).F\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(FREESOURCE) $(F90FLAGS) -c $(NETCDFMOD) $(MODFLAG). $(*).F\n\n\nhrldas_extract_point: hrldas_extract_point.o\n\t$(COMPILERF90) -o $(@) $(F90FLAGS) $(MODFLAG). \\\n\t\thrldas_extract_point.o arguments_module.o module_date_utilities.o llxy_generic.o lccone.o \\\n\t\t$(NETCDFLIB)\n\ngribextract:\tgribextract.c\n\t$(CC) -o $(@) gribextract.c -lm\n\n\ngribedition:\tgribedition.c\n\t$(CC) -o $(@) gribedition.c -lm\n\ngribbyte:\tgribbyte.c\n\t$(CC) -o $(@) gribbyte.c -lm\n\ngeth_newdate:\n\t$(CC) -o $(@) geth_newdate.c -lm\n\nmodify_wrfinput: modify_wrfinput.o\n\t$(COMPILERF90) -o $(@) $(F90FLAGS) $(MODFLAG). \\\n\t\tmodify_wrfinput.o \\\n\t\t$(NETCDFLIB)\n\n\nhrldas_extract_point.o:\targuments_module.o\nhrldas_extract_point.o:\tmodule_date_utilities.o\nhrldas_extract_point.o:\tllxy_generic.o\nhrldas_extract_point.o:\tlccone.o\n\nclean:\n\t$(RM) *.o *~ $(CMD) *.mod\n\t( cd gcip_sw_to_grib; make clean )\nneat:\n\t$(RM) *.o *~ *.mod\n\t( cd gcip_sw_to_grib; make neat )\n#\n\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/gcip_sw_to_grib/Makefile",
    "content": ".SUFFIXES:\n.SUFFIXES: .F .c .o\n\ninclude ../../user_build_options\n\nOBJS=\tcio.o \\\n\tgbytesys.o \\\n\tmodule_date_utilities.o \\\n\tswap4c.o \\\n\tswap4f.o\n\nCMD=srb_daily_to_grib.exe srb_monthly_to_grib.exe\n\nall: $(CMD)\n\n$(OBJS):$(SRCS)\n\nsrb_daily_to_grib.exe:\t$(OBJS) srb_daily_to_grib.o\n\t$(COMPILERF90) -o srb_daily_to_grib.exe $(F90FLAGS) $(^)\n\nsrb_monthly_to_grib.exe:\t$(OBJS) srb_monthly_to_grib.o\n\t$(COMPILERF90) -o srb_monthly_to_grib.exe $(F90FLAGS) $(^)\n\ncio.o:\t../../HRLDAS_COLLECT_DATA/lib/cio.c\n\t$(CC) -c $(<)\n\nswap4c.o:\t../../HRLDAS_COLLECT_DATA/lib/swap4c.c\n\t$(CC) -c $(<)\n\ngbytesys.o:\t../../HRLDAS_COLLECT_DATA/lib/gbytesys.F\n\t$(COMPILERF90) -c $(F90FLAGS) $(FREESOURCE) $(<)\n\nswap4f.o:\t../../HRLDAS_COLLECT_DATA/lib/swap4f.F\n\t$(COMPILERF90) -c $(F90FLAGS) $(FREESOURCE) -DBIT32 $(<)\n\nmodule_date_utilities.o:\t../../Utility_routines/module_date_utilities.F\n\t$(COMPILERF90) -c $(F90FLAGS) $(FREESOURCE) $(<)\n\n.F.o:\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(FREESOURCE) $(F90FLAGS) -c $(*).F \n\n\nneat:\n\t$(RM) $(OBJS) *~ *.mod srb_daily_to_grib.o srb_monthly_to_grib.o\n\nclean:\n\t$(RM) $(OBJS) $(CMD) *~ *.mod srb_daily_to_grib.o srb_monthly_to_grib.o\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/gcip_sw_to_grib/srb_daily_to_grib.F",
    "content": "!*****************************************************************************!\n!                                                                             !\n! Module to facilitate putting fields into GRIB 1 format.                     !\n!                                                                             !\n! Still needs a lot of work;                                                  !\n! still needs a lot of documentation;                                         !\n! but I'm fairly pleased with the potential.                                  !\n!                                                                             !\n! Author:  Kevin W. Manning                                                   !\n!          NCAR/MMM                                                           !\n!          October 2001 and continuing                                        !\n!          October 2010:  Allow a constant field to be bitmasked.             !\n!          October 2010:  Don't encode the bitmask if the mask includes the   !\n!                         entire grid.  Treat it as a non-bitmasked field.    !\n!                                                                             !\n!*****************************************************************************!\n\nmodule engrib_module_test\n\n  integer, private, parameter :: sec1_size = 28\n  integer, private :: sec1_ptv\n  integer, private :: sec1_cid\n  integer, private :: sec1_pid\n  integer, private :: sec1_gid\n  integer, private :: sec1_gds\n  integer, private :: sec1_bms\n  integer, private :: sec1_prm\n  integer, private :: sec1_lty\n  integer, private :: sec1_lv1\n  integer, private :: sec1_lv2\n  integer, private :: sec1_gyr\n  integer, private :: sec1_gmo\n  integer, private :: sec1_gdy\n  integer, private :: sec1_ghr\n  integer, private :: sec1_gmi\n  integer, private :: sec1_tmu\n  integer, private :: sec1_pr1\n  integer, private :: sec1_pr2\n  integer, private :: sec1_tri\n  integer, private :: sec1_nin\n  integer, private :: sec1_nmi\n  integer, private :: sec1_cen\n  integer, private :: sec1_sub\n  integer, private :: sec1_dsf\n\n  integer, private :: sec2_size\n  integer, private :: sec2_gty\n  integer, private :: sec2_nxp\n  integer, private :: sec2_nyp\n  integer, private :: sec2_la1\n  integer, private :: sec2_lo1\n  integer, private :: sec2_la2\n  integer, private :: sec2_lo2\n  integer, private :: sec2_rac\n  integer, private :: sec2_lov\n  integer, private :: sec2_dxt\n  integer, private :: sec2_dyt\n  integer, private :: sec2_tr1\n  integer, private :: sec2_tr2\n  integer, private :: sec2_pcf  ! Default 0\n\n  integer, private :: sec2_inc  ! Default +1\n  integer, private :: sec2_jnc  ! Default +1\n  integer, private :: sec2_scm  ! Default 0\n  integer, private :: sec2_spl  ! LC:  Latitude of the \"southern pole\"\n\n  integer, private :: sec3_size\n  logical, allocatable, dimension(:,:) :: lbm\n  integer, private :: nummappt\n\n  integer, private :: sec4_size\n  integer, private :: sec4_bsf\n  integer, private :: sec4_rfa\n  integer, private :: sec4_rfb\n  integer, private :: sec4_rfs\n  integer, private :: sec4_nbt\n  integer, allocatable, dimension(:,:) :: gribiarr\n\n  integer, dimension(2) :: newsec0  ! 8 bytes\n  integer, dimension(7) :: newsec1  ! 28 bytes\n  integer, allocatable, dimension(:) :: newsec2\n  integer, allocatable, dimension(:) :: newsec3\n  integer, allocatable, dimension(:) :: newsec4\n  integer, parameter :: newsec5 = Z\"37373737\"  !encodes \"7777\"\n\n#if defined (__sgi) || defined (__sun) || defined (__alpha) || defined (__linux)\n  logical, parameter :: DO_BYTE_SWAP = .TRUE.\n#else\n  logical, parameter :: DO_BYTE_SWAP = .FALSE.\n#endif\n\ncontains\n\n  subroutine open_newgrib(gribunit, flnm)\n!*****************************************************************************!\n!                                                                             !\n! Subroutine OPEN_NEWGRIB:                                                    !\n!    Part of Module ENGRIB_MODULE                                             !\n!                                                                             !\n! Purpose:                                                                    !\n!    Open a c FILE stream for output.                                         !\n!                                                                             !\n! Argument list:                                                              !\n!                                                                             !\n!    Input:                                                                   !\n!       FLNM:     the pathname of the file to create as a GRIB file.          !\n!    Output:                                                                  !\n!       GRIBUNIT: the FILE* stream referring to new file FLNM.                !\n!                                                                             !\n! Side Effects:                                                               !\n!                                                                             !\n!   ** Opens the FILE* stream GRIBUNIT for output as file FLNM.               !\n!                                                                             !\n!   ** If file FLNM does not exist, it is created and ready for new contents. !\n!                                                                             !\n!   ** If file FLNM already exists, it is destroyed, recreated, and ready     !\n!      for new contents.                                                      !\n!                                                                             !\n!   ** If file FLNM for some reason cannot be created (or recreated), an      !\n!      error message is printed and the program is halted.                    !\n!                                                                             !\n! Externals:                                                                  !\n!                                                                             !\n!   ** Subroutine COPEN                                                       !\n!         Where is COPEN? [i.e., what package, module, or source-code file]   !\n!                                                                             !\n!                                                                             !\n!*****************************************************************************!\n    implicit none\n\n! Input:\n    character(len=*), intent(in) :: flnm\n\n! Output:\n    integer, intent(out) :: gribunit\n\n! Local variables:\n    integer :: ierr  ! Error flag returned from call to copen.\n\n    ! Open the file FLNM for output as FILE* stream GRIBUNIT:\n    call copen(gribunit, flnm//char(0), 0, ierr, 0)\n\n    ! Check if the open was successful.  If not, write a message and exit:\n    if (ierr /= 0) then\n       write(*,'(/,\"***** ERROR *****\")')\n       write(*,'(/,\"OPEN_NEWGRIB:  Call to COPEN could not open file \", A,/)') &\n            flnm\n       call abort\n    endif\n\n  end subroutine open_newgrib\n\n  subroutine close_newgrib(gribunit)\n!*****************************************************************************!\n!                                                                             !\n! Subroutine CLOSE_NEWGRIB:                                                   !\n!    Part of Module ENGRIB_MODULE                                             !\n!                                                                             !\n! Purpose:                                                                    !\n!    Close a previously-opened c FILE* stream.                                !\n!                                                                             !\n! Argument list:                                                              !\n!                                                                             !\n!    Input:                                                                   !\n!       GRIBUNIT: the FILE* stream to be closed.                              !\n!    Output:                                                                  !\n!       None                                                                  !\n!                                                                             !\n! Side Effects:                                                               !\n!                                                                             !\n!   ** Closes the FILE* stream GRIBUNIT.                                      !\n!                                                                             !\n!   ** If for some reason the close fails, an error message is printed        !\n!      and the program is halted.                                             !\n!                                                                             !\n! Externals:                                                                  !\n!                                                                             !\n!   ** Subroutine CCLOSE                                                      !\n!         Where is CCLOSE? [i.e., what package, module, or source-code file]  !\n!                                                                             !\n!*****************************************************************************!\n    implicit none\n! Input:\n    integer, intent(in) :: gribunit\n\n! Local variables\n    integer :: ierr ! Error flag returned from call to CCLOSE.\n\n    call cclose(gribunit, 0, ierr)\n    if (ierr /= 0) then\n       write(*,'(/,\"***** ERROR *****\")')\n       write(*,'(/,\"CLOSE_NEWGRIB:  Call to CCLOSE could not close stream \", I12,/)') &\n            gribunit\n       call abort\n    endif\n  end subroutine close_newgrib\n\n\n  subroutine write_grib(gribunit)\n!*****************************************************************************!\n!                                                                             !\n! Subroutine WRITE_GRIB:                                                      !\n!    Part of Module ENGRIB_MODULE                                             !\n!                                                                             !\n! Purpose:                                                                    !\n!    Write                                                                    !\n!                                                                             !\n! Argument list:                                                              !\n!                                                                             !\n!    Input:                                                                   !\n!       GRIBUNIT: the FILE* stream to be written to.                          !\n!                                                                             !\n!    Output:                                                                  !\n!       None                                                                  !\n!                                                                             !\n! Other variables in ENGRIB_MODULE accessed by this subroutine:               !\n!                                                                             !\n!   ** NEWSEC0:  The integer array into which GRIB section 0 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC1:  The integer array into which GRIB section 1 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC2:  The integer array into which GRIB section 2 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC3:  The integer array into which GRIB section 3 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC4:  The integer array into which GRIB section 4 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC5:  The constant character array, with PARAMETER attribute, which!\n!                contains GRIB section 5 information, always \"7777\".          !\n!                                                                             !\n!   ** SEC1_SIZE: The size (bytes) of GRIB section 1, with PARAMETER          !\n!                 attribute; SEC1_SIZE = 28.                                  !\n!                                                                             !\n!   ** SEC2_SIZE: The size (bytes) of GRIB section 2.                         !\n!                                                                             !\n!   ** SEC3_SIZE: The size (bytes) of GRIB section 3.                         !\n!                                                                             !\n!   ** SEC4_SIZE: The size (bytes) of GRIB section 4.                         !\n!                                                                             !\n!   ** DO_BYTE_SWAP:  Logical parameter, machine dependent, TRUE if           !\n!                     byte-swapping is neede upon output.                     !\n!                                                                             !\n! Side Effects:                                                               !\n!                                                                             !\n!   ** Encodes all the GRIB header information into the GRIB header,          !\n!      filling integer arrays NEWSEC0, NEWSEC1, NEWSEC2, NEWSEC3, and         !\n!      NEWSEC4.                                                               !\n!                                                                             !\n!   ** Does byte swapping, if necessary, on integer arrays NEWSEC0, NEWSEC1,  !\n!      NEWSEC2, NEWSEC3, and, NEWSEC4.                                        !\n!                                                                             !\n!   ** Writes a complete GRIB record to FILE* stream GRIBUNIT.                !\n!                                                                             !\n! Other subroutine and functions used from ENGRIB_MODULE:                     !\n!                                                                             !\n!   ** GRIBSEC0_PACK:  Packs GRIB section 0 information into array NEWSEC0    !\n!                                                                             !\n!   ** GRIBSEC1_PACK:  Packs GRIB section 1 information into array NEWSEC1    !\n!                                                                             !\n!   ** GRIBSEC2_PACK:  Packs GRIB section 2 information into array NEWSEC2    !\n!                                                                             !\n!   ** GRIBSEC4_PACK:  Packs GRIB section 4 information into array NEWSEC4    !\n!                                                                             !\n! Externals:                                                                  !\n!                                                                             !\n!   ** SWAP4F                                                                 !\n!                                                                             !\n!   ** BNWRIT                                                                 !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n! Argument list input:\n    integer, intent(in) :: gribunit\n\n! Argument list output: (none)\n\n! Local variables:\n    integer :: ierr, iwrt\n    integer, allocatable, dimension(:) :: output_buffer\n    integer :: output_size\n    integer :: ostart\n    integer :: ioffs\n    integer :: inskip\n    integer :: outskip\n    integer :: i\n    integer :: k\n    integer :: iout\n    integer :: itmp\n\n    ! Final packing of all sections, before the write.\n    ! These should stay in this order:\n    !      gribsec1_pack, gribsec2_pack, gribsec4_pack, gribsec0_pack\n    ! because the other packing needs to be done before we know the final\n    ! size of the grib record to go into GRIB section 0.\n    call gribsec1_pack\n    call gribsec2_pack\n    call gribsec4_pack\n    call gribsec0_pack\n\n! Do the output, byte-swapping, if necessary:\n\n    output_size = 8 + sec1_size + sec2_size + sec3_size + sec4_size + 4\n    allocate(output_buffer(output_size))\n    output_buffer = 0\n\n    ! Copy GRIB Section 0.  Known to be 2 bytes.\n    call sbytes(output_buffer, newsec0, 0, 32, 0, 2)\n    ostart = size(newsec0)\n\n    ! Copy GRIB SEction 1\n    if (mod(sec1_size,4)/=0) stop \"WEIRD SEC1 SIZE FOR SWAPPING\" ! We know sec1_size should be 28\n    do iwrt = 1, size(newsec1)\n       call sbyte(output_buffer(ostart+iwrt), newsec1(iwrt), 0, 32)\n    enddo\n    ostart = ostart + size(newsec1)\n\n    ! Copy GRIB Section 2\n    if (mod(sec2_size,4)/=0) stop \"WEIRD SEC2 SIZE SWAP FOR SWAPPING\" ! We know sec2_size should be 32\n    do iwrt = 1, size(newsec2)\n       call sbyte(output_buffer(ostart+iwrt), newsec2(iwrt), 0, 32)\n    enddo\n    ostart = ostart + size(newsec2)\n    ioffs = 0\n\n       ! Copy GRIB Section 3\n\n    ! Bypass <ostart> words + <outskip> bytes in <output_buffer> before we start packing into the <output_buffer> array.\n    ! Skip <inskip> bytes in <newsec3> before we start reading from <newsec3>\n    inskip = 0\n    outskip = 0\n    i = 1\n    iout = ostart+1\n    do k = 1, sec3_size\n       call gbyte(newsec3(i), itmp, inskip, 8)\n       call sbyte(output_buffer(iout), itmp, outskip, 8)\n       inskip = inskip + 8\n       outskip = outskip + 8\n       if (outskip == 32) then\n          outskip = 0\n          iout = iout + 1\n       endif\n       if (inskip == 32) then\n          inskip = 0\n          i = i + 1\n       endif\n    enddo\n\n    ! Copy GRIB Section 4\n    inskip = 0\n    i = 1\n    do k = 1, sec4_size\n       call gbyte(newsec4(i), itmp, inskip, 8)\n       call sbyte(output_buffer(iout), itmp, outskip, 8)\n       inskip = inskip + 8\n       outskip = outskip + 8\n       if (outskip == 32) then\n          outskip = 0\n          iout = iout + 1\n       endif\n       if (inskip == 32) then\n          inskip = 0\n          i = i + 1\n       endif\n    enddo\n\n    ! Copy GRIB Section 5\n    inskip = 0\n    i = 1\n    do k = 1, 4\n       call gbyte(newsec5, itmp, inskip, 8)\n       call sbyte(output_buffer(iout), itmp, outskip, 8)\n       inskip = inskip + 8\n       outskip = outskip + 8\n       if (outskip == 32) then\n          outskip = 0\n          iout = iout + 1\n       endif\n       if (inskip == 32) then\n          inskip = 0\n          i = i + 1\n       endif\n    enddo\n\n    if (DO_BYTE_SWAP) then\n       if (mod(output_size,4) == 0) then\n          call swap4f(output_buffer, output_size)\n       else\n          call swap4f(output_buffer, output_size+mod(output_size,4))\n       endif\n    endif\n\n    call bnwrit(gribunit, output_buffer, output_size, iwrt, ierr, 0)\n\n  end subroutine write_grib\n\n  subroutine grib_clear\n    call gribsec0_clear\n    call gribsec1_clear\n    call gribsec2_clear\n    call gribsec3_clear\n    call gribsec4_clear\n  end subroutine grib_clear\n\n  subroutine gribsec0_clear\n    implicit none\n    newsec0 = 0\n  end subroutine gribsec0_clear\n\n  subroutine gribsec1_clear\n    implicit none\n    newsec1 = 0\n\n    sec1_ptv = -999999\n    sec1_cid = -999999\n    sec1_pid = -999999\n    sec1_gid = -999999\n    sec1_gds = -999999\n    sec1_bms = -999999\n    sec1_prm = -999999\n    sec1_lty = -999999\n    sec1_lv1 = -999999\n    sec1_lv2 = -999999\n    sec1_gyr = -999999\n    sec1_gmo = -999999\n    sec1_gdy = -999999\n    sec1_ghr = -999999\n    sec1_gmi = -999999\n    sec1_tmu = -999999\n    sec1_pr1 = -999999\n    sec1_pr2 = -999999\n    sec1_tri = -999999\n    sec1_nin = -999999\n    sec1_nmi = -999999\n    sec1_cen = -999999\n    sec1_sub = -999999\n    sec1_dsf = -999999\n\n  end subroutine gribsec1_clear\n\n  subroutine gribsec2_clear\n    implicit none\n    sec2_size = 0\n    sec2_pcf = -999999\n    sec2_inc = -999999\n    sec2_jnc = -999999\n    sec2_rac = -999999\n    sec2_scm = -999999\n    sec2_tr1 = -999999\n    sec2_tr2 = -999999\n    if (allocated(newsec2)) deallocate(newsec2)\n\n  end subroutine gribsec2_clear\n\n  subroutine gribsec3_clear\n    implicit none\n\n    sec3_size = 0\n    nummappt = 0\n    if (allocated(lbm)) deallocate(lbm)\n    if (allocated(newsec3)) deallocate(newsec3)\n\n  end subroutine gribsec3_clear\n\n  subroutine gribsec4_clear\n    implicit none\n    sec4_size = 0\n    sec4_bsf = -999999\n    sec4_rfa = -999999\n    sec4_rfb = -999999\n    sec4_rfs = -999999\n    sec4_nbt = -999999\n    if (allocated(newsec4)) deallocate(newsec4)\n    if (allocated(gribiarr)) deallocate(gribiarr)\n  end subroutine gribsec4_clear\n\n  subroutine gribsec0_pack()\n!*****************************************************************************!\n!                                                                             !\n! Subroutine GRIBSEC0_PACK:                                                   !\n!    Part of Module ENGRIB_MODULE                                             !\n!                                                                             !\n! Purpose:                                                                    !\n!    Pack GRIB section 0 information into array NEWSEC0                       !\n!                                                                             !\n! Argument list:                                                              !\n!                                                                             !\n!    Input:                                                                   !\n!       None                                                                  !\n!    Output:                                                                  !\n!       None                                                                  !\n!                                                                             !\n! Other variables in ENGRIB_MODULE accessed by this subroutine:               !\n!                                                                             !\n!   ** NEWSEC0  :  Integer array to hold GRIB section 0 information.          !\n!                  Modified under GRIBSEC0_PACK.                              !\n!                                                                             !\n!   ** SEC1_SIZE:  Size (bytes) of GRIB section 1.                            !\n!                                                                             !\n!   ** SEC2_SIZE:  Size (bytes) of GRIB section 2.                            !\n!                                                                             !\n!   ** SEC3_SIZE:  Size (bytes) of GRIB section 3.                            !\n!                                                                             !\n!   ** SEC4_SIZE:  Size (bytes) of GRIB section 4.                            !\n!                                                                             !\n! Side Effects:                                                               !\n!                                                                             !\n!   ** Packs GRIB section 0 information into array NEWSEC0                    !\n!                                                                             !\n! Other subroutine and functions used from ENGRIB_MODULE:                     !\n!                                                                             !\n!   ** SBENC:  Packs groups of bits into an integer array.  Basically         !\n!              a wrapper for the SBYTE subroutine.                            !\n!                                                                             !\n! Externals:                                                                  !\n!                                                                             !\n!   None.                                                                     !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n! Local variables:\n    integer :: iskip\n    integer :: totsize\n\n    totsize = 8 + sec1_size + sec2_size + sec3_size + sec4_size + 4\n    iskip = 0\n\n    call sbenc(newsec0, ichar(\"G\"), ichar(\"G\"), iskip, 8)\n    call sbenc(newsec0, ichar(\"R\"), ichar(\"R\"), iskip, 8)\n    call sbenc(newsec0, ichar(\"I\"), ichar(\"I\"), iskip, 8)\n    call sbenc(newsec0, ichar(\"B\"), ichar(\"B\"), iskip, 8)\n\n    call sbenc(newsec0, totsize, -999999, iskip, 24)\n    call sbenc(newsec0, 1, 1, iskip, 8)\n\n  end subroutine gribsec0_pack\n\n  subroutine gribsec1_pack()\n    implicit none\n    integer :: gdsbms, iskip\n\n    gdsbms = 0\n    if (sec1_gds > -999998) then\n       gdsbms = gdsbms + 128*sec1_gds\n    endif\n    if (sec1_bms > -999998) then\n       gdsbms = gdsbms + 64*sec1_bms\n    endif\n\n    iskip = 0\n    call sbenc(newsec1,       28,  28, iskip, 24)\n    call sbenc(newsec1, sec1_ptv, 255, iskip,  8)\n    call sbenc(newsec1, sec1_cid, 255, iskip,  8)\n    call sbenc(newsec1, sec1_pid, 255, iskip,  8)\n    call sbenc(newsec1, sec1_gid, 255, iskip,  8)\n    call sbenc(newsec1,   gdsbms,   0, iskip,  8)\n    call sbenc(newsec1, sec1_prm, 255, iskip,  8)\n    call sbenc(newsec1, sec1_lty, 255, iskip,  8)\n    select case (sec1_lty)\n    case (0:99)\n       call sbenc(newsec1, 0,   0, iskip, 16)\n    case (100,105,107,109,111,113,115,117,119,125,160,200,201)\n       call sbenc(newsec1, sec1_lv1, 0, iskip, 16)\n    case (101,102,104,106,108,110,112,114,116,120,121,128,141)\n       call sbenc(newsec1, sec1_lv1, 0, iskip, 8)\n       call sbenc(newsec1, sec1_lv2, 0, iskip, 8)\n    case default\n       print*, 'SEC1_LTY = ', sec1_lty\n       stop \"Unrecognized SEC1_LTY in GRIBSEC1_PACK\"\n    end select\n    call sbenc(newsec1, sec1_gyr, 255, iskip,  8)\n    call sbenc(newsec1, sec1_gmo, 255, iskip,  8)\n    call sbenc(newsec1, sec1_gdy, 255, iskip,  8)\n    call sbenc(newsec1, sec1_ghr, 255, iskip,  8)\n    call sbenc(newsec1, sec1_gmi, 255, iskip,  8)\n    call sbenc(newsec1, sec1_tmu, 255, iskip,  8)\n    call sbenc(newsec1, sec1_pr1, 255, iskip,  8)\n    call sbenc(newsec1, sec1_pr2, 255, iskip,  8)\n    call sbenc(newsec1, sec1_tri, 255, iskip,  8)\n    call sbenc(newsec1, sec1_nin,   0, iskip, 16)\n    call sbenc(newsec1, sec1_nmi,   0, iskip,  8)\n    call sbenc(newsec1, sec1_cen, 255, iskip,  8)\n    call sbenc(newsec1, sec1_sub, 255, iskip,  8)\n    call sbenc(newsec1, sec1_dsf,   0, iskip,  16)\n\n  end subroutine gribsec1_pack\n\n  subroutine sbenc(buf, in, df, sk, nb)\n    implicit none\n    integer, dimension(*) :: buf ! Buffer to copy bits to.\n    integer, intent(in) :: in             ! word containing bits to copy\n    integer, intent(in) :: df             ! Default bits, in case of no-data value\n    integer, intent(inout) :: sk          ! Number of bits to skip\n    integer, intent(in) :: nb             ! number of bits to encode\n\n    if (in > -999998) then\n!KWM       if ((in == 194) .and. (sk == 48)) then\n!KWM          print*, 'SBENC:  call sbyte:  in,sk,nb = ', in,sk,nb\n!KWM       endif\n       call sbyte(buf, in, sk, nb)\n!KWM       if ((in == 194) .and. (sk == 48)) then\n!KWM          print'(\"SBENC:  BUF(1) = \",Z8.8)', buf(1)\n!KWM          print'(\"SBENC:  BUF(2) = \",Z8.8)', buf(2)\n!KWM       endif\n    else\n       call sbyte(buf, df, sk, nb)\n    endif\n    sk = sk + nb\n  end subroutine sbenc\n\n  subroutine gribsec1_set(parameter_table_version, center_id, process_id, &\n       grid_id, isthere_gds, isthere_bms, parameter_id, level_type, &\n       level_1, level_2, year, month, day, hour, minute, time_unit, &\n       p1, p2, time_range_indicator, number_included, number_missing, &\n       century, subcenter_id, decimal_scale_factor, &\n       hdate)\n    implicit none\n    integer, intent(in), optional :: parameter_table_version, center_id, process_id, &\n         grid_id, isthere_gds, isthere_bms, parameter_id, level_type, &\n         level_1, level_2, year, month, day, hour, minute, time_unit, &\n         p1, p2, time_range_indicator, number_included, number_missing, &\n         century, subcenter_id, decimal_scale_factor\n    character(len=*), intent(in), optional :: hdate\n\n    integer :: cn, yr, mo, dy, hr, mi\n    integer :: ierr\n\n    if (present(parameter_table_version)) sec1_ptv = parameter_table_version\n    if (present(center_id))               sec1_cid = center_id\n    if (present(process_id))              sec1_pid = process_id\n    if (present(grid_id))                 sec1_gid = grid_id\n    if (present(isthere_gds))             sec1_gds = isthere_gds\n    if (present(isthere_bms))             sec1_bms = isthere_bms\n    if (present(parameter_id))            sec1_prm = parameter_id\n    if (present(level_type))              sec1_lty = level_type\n    if (present(level_1))                 sec1_lv1 = level_1\n    if (present(level_2))                 sec1_lv2 = level_2\n    if (present(year))                    sec1_gyr = year\n    if (present(month))                   sec1_gmo = month\n    if (present(day))                     sec1_gdy = day\n    if (present(hour))                    sec1_ghr = hour\n    if (present(minute))                  sec1_gmi = minute\n    if (present(time_unit))               sec1_tmu = time_unit\n    if (present(p1))                      sec1_pr1 = p1\n    if (present(p2))                      sec1_pr2 = p2\n    if (present(time_range_indicator))    sec1_tri = time_range_indicator\n    if (present(number_included))         sec1_nin = number_included\n    if (present(number_missing))          sec1_nmi = number_missing\n    if (present(century))                 sec1_cen = century\n    if (present(subcenter_id))            sec1_sub = subcenter_id\n    if (present(decimal_scale_factor)) then\n       if (decimal_scale_factor < 0) then\n          sec1_dsf = (2**15)-decimal_scale_factor\n       else\n          sec1_dsf = decimal_scale_factor\n       endif\n    endif\n\n    if (present(hdate)) then\n       cn = 0\n       yr = 0\n       mo = 0\n       dy = 0\n       hr = 0\n       mi = 0\n       select case (len(hdate))\n       case (16:)\n          read(hdate,'(I2,I2,1x,I2,1x,I2,1x,I2,1x,I2)', iostat=ierr) cn, yr, mo, dy, hr, mi\n       case (13)\n          read(hdate,'(I2,I2,1x,I2,1x,I2,1x,I2)', iostat=ierr) cn, yr, mo, dy, hr\n       case (10)\n          read(hdate,'(I2,I2,1x,I2,1x,I2)', iostat=ierr) cn, yr, mo, dy\n       case (7)\n          read(hdate,'(I2,I2,1x,I2)', iostat=ierr) cn, yr, mo\n       case (4)\n          read(hdate,'(I2,I2)', iostat=ierr) cn, yr\n       case default\n          print*, \"Bad HDATE = \"//hdate\n          stop \"Bad HDATE in GRIBSEC1_SET\"\n       end select\n       if (ierr /= 0) then\n          print*, 'Problem reading from hdate #'//hdate//\"#\"\n          stop\n       endif\n\n       sec1_gyr = yr\n       sec1_gmo = mo\n       sec1_gdy = dy\n       sec1_ghr = hr\n       sec1_gmi = mi\n       if (yr > 0) then\n          sec1_cen = cn+1\n       else\n          sec1_cen = cn\n       endif\n    endif\n  end subroutine gribsec1_set\n\n  subroutine gribsec3_create()\n\n    sec3_size = (size(lbm,1)*size(lbm,2))/8\n    nover = mod(size(lbm,1)*size(lbm,2), 8)\n    if (nover > 0) then\n       sec3_size = sec3_size + 1\n       numunused = 8-nover\n    endif\n    if (mod(sec3_size,2) == 1) then\n       sec3_size = sec3_size + 1\n       numunused = numunused + 8\n    endif\n\n    sec3_size = sec3_size + 6\n\n    allocate(newsec3((sec3_size+3)/4))\n    newsec3 = 0\n\n    iskip = 0\n    call sbenc(newsec3, sec3_size, sec3_size, iskip, 24)\n    call sbenc(newsec3, numunused, numunused, iskip, 8)\n    call sbenc(newsec3, 0, 0, iskip, 16)\n\n    if ((sec2_inc == 1) .or. (sec2_inc < -999998)) then\n       ist = 1\n       ien = size(lbm,1)\n       inc = 1\n    elseif (sec2_inc == -1) then\n       ist = size(lbm,1)\n       ien = 1\n       inc = -1\n    endif\n\n\n    if ((sec2_jnc == 1) .or. (sec2_jnc < -999998)) then\n       jst = 1\n       jen = size(lbm,2)\n       jnc = 1\n    elseif (sec2_jnc == -1) then\n       jst = size(lbm,2)\n       jen = 1\n       jnc = -1\n    endif\n\n    if ((sec2_scm == 0) .or. (sec2_scm < -999998)) then\n\n       do j = jst, jen, jnc\n          do i = ist, ien, inc\n             if (lbm(i,j)) then\n                lbm(i,j) = .TRUE.\n                call sbenc(newsec3, 1, 1, iskip, 1)\n             else\n                lbm(i,j) = .FALSE.\n                call sbenc(newsec3, 0, 0, iskip, 1)\n             endif\n          enddo\n       enddo\n\n    else if (sec2_scm == 1) then\n\n       do i = ist, ien, inc\n          do j = jst, jen, jnc\n             if (lbm(i,j)) then\n                lbm(i,j) = .TRUE.\n                call sbenc(newsec3, 1, 1, iskip, 1)\n             else\n                lbm(i,j) = .FALSE.\n                call sbenc(newsec3, 0, 0, iskip, 1)\n             endif\n          enddo\n       enddo\n\n    endif\n\n  end subroutine gribsec3_create\n\n  subroutine gribsec2_set(grid_type, nx, ny, la1, lo1, la2, lo2, &\n       resolution_and_component, lov, dx, dy, projection_center_flag, &\n       i_scanning_increment, j_scanning_increment, scanning_mode, truelat1, &\n       truelat2)\n    implicit none\n    integer, intent(in), optional :: grid_type\n    integer, intent(in), optional :: nx\n    integer, intent(in), optional :: ny\n    real,    intent(in), optional :: la1\n    real,    intent(in), optional :: lo1\n    real,    intent(in), optional :: la2\n    real,    intent(in), optional :: lo2\n    integer, intent(in), optional :: resolution_and_component\n    real,    intent(in), optional :: lov\n    real,    intent(in), optional :: dx\n    real,    intent(in), optional :: dy\n    real,    intent(in), optional :: truelat1\n    real,    intent(in), optional :: truelat2\n    integer, intent(in), optional :: projection_center_flag\n    integer, intent(in), optional :: i_scanning_increment\n    integer, intent(in), optional :: j_scanning_increment\n    integer, intent(in), optional :: scanning_mode\n\n    if (present(grid_type))then\n       select case(grid_type)\n       case (0,5)\n          sec2_size = 32\n          allocate(newsec2((sec2_size+3)/4))\n          newsec2 = 0\n       case (1,3)\n          sec2_size = 42\n          allocate(newsec2((sec2_size+3)/4))\n          newsec2 = 0\n       case default\n          print*, 'grid_type = ', grid_type\n          stop \"Unrecognized grid type in GRIBSEC2_SET\"\n       end select\n\n       sec2_gty = grid_type\n       call gribsec1_set(isthere_gds=1)\n    endif\n\n    if (present(nx)) sec2_nxp = nx\n    if (present(ny)) sec2_nyp = ny\n\n    if (present(la1))then\n       if ((la1 > 90.0) .or. (la1 < -90.0)) then\n          write(*,'(\" ***** Latitude problem (la1): \", F20.10)') la1\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (la1 < 0) then\n          sec2_la1 = (2**23) - nint(la1 * 1.E3)\n       else\n          sec2_la1 = nint(la1 * 1.E3)\n       endif\n    endif\n\n    if (present(lo1)) then\n       if ((lo1 > 360.0) .or. (lo1 < -360.0)) then\n          write(*,'(\" ***** Longitude problem (lo1): \", F20.10)') lo1\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (lo1 < 0) then\n          sec2_lo1 = (2**23) - nint(lo1 * 1.E3)\n       else\n          sec2_lo1 = nint(lo1 * 1.E3)\n       endif\n    endif\n    if (present(la2)) then\n       if ((la2 > 90.0) .or. (la2 < -90.0)) then\n          write(*,'(\" ***** Latitude problem (la2): \", F20.10)') la2\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (la2 < 0) then\n          sec2_la2 = (2**23) - nint(la2 * 1.E3)\n       else\n          sec2_la2 = nint(la2*1.E3)\n       endif\n    endif\n    if (present(lo2)) then\n       if ((lo2 > 360.0) .or. (lo2 < -360.0)) then\n          write(*,'(\" ***** Longitude problem (lo2): \", F20.10)') lo2\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (lo2 < 0) then\n          sec2_lo2 = (2**23) - nint(lo2*1.E3)\n       else\n          sec2_lo2 = nint(lo2*1.E3)\n       endif\n    endif\n\n    if (present(resolution_and_component)) sec2_rac = resolution_and_component\n\n    if (present(lov)) then\n       if ((lov > 360.0) .or. (lov < -360.0)) then\n          write(*,'(\" ***** Longitude problem (lov): \", F20.10)') lov\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (lov < 0) then\n          sec2_lov = (2**23) - nint(lov*1.E3)\n       else\n          sec2_lov = nint(lov*1.E3)\n       endif\n    endif\n    if (present(dx)) then\n       sec2_dxt = nint(dx*1.E3)\n!       print*,' sec2_dxt = ', sec2_dxt\n    endif\n    if (present(dy)) then\n       sec2_dyt = nint(dy*1.E3)\n!       print*,' sec2_dyt = ', sec2_dyt\n    endif\n    if (present(truelat1)) then\n       if ((truelat1 > 90.0) .or. (truelat1 < -90.0)) then\n          write(*,'(\" ***** Latitude problem (truelat1): \", F20.10)') truelat1\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (truelat1 < 0) then\n          sec2_tr1 = (2**23) - nint(truelat1*1.E3)\n       else\n          sec2_tr1 = nint(truelat1*1.E3)\n       endif\n    endif\n    if (present(truelat2)) then\n       if ((truelat2 > 90.0) .or. (truelat2 < -90.0)) then\n          write(*,'(\" ***** Latitude problem (truelat2): \", F20.10)') truelat2\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (truelat2 < 0) then\n          sec2_tr2 = (2**23) - nint(truelat2*1.E3)\n       else\n          sec2_tr2 = nint(truelat2*1.E3)\n       endif\n       sec2_spl = (2**23) - (-90000)\n    endif\n\n    if (present(projection_center_flag)) then\n       if ((projection_center_flag < 0) .or. (projection_center_flag > 1)) then\n          write(*, '(/,\"***** FATAL ERROR.  Invalid input to GRIBSEC2_SET\")')\n          write(*, '(\"***** PROJECTION_CENTER_FLAG must be 0 or 1.  Found: \",I12)') &\n               projection_center_flag\n          stop \"***** GRIBSEC2_SET\"\n       endif\n       sec2_pcf = projection_center_flag*128\n    endif\n\n    if (present(i_scanning_increment)) then\n       if(abs(i_scanning_increment) /= 1) then\n          write(*, '(/,\"***** FATAL ERROR.  Invalid input to GRIBSEC2_SET\")')\n          write(*, '(\"***** I_SCANNING_INCREMENT must be +/- 1.  Found: \",I12)') &\n               i_scanning_increment\n          stop \"***** GRIBSEC2_SET\"\n       endif\n       sec2_inc = i_scanning_increment\n    endif\n\n    if (present(j_scanning_increment)) then\n       if(abs(j_scanning_increment) /= 1) then\n          write(*, '(/,\"***** FATAL ERROR.  Invalid input to GRIBSEC2_SET\")')\n          write(*, '(\"***** J_SCANNING_INCREMENT must be +/- 1.  Found: \",I12)') &\n               j_scanning_increment\n          stop \"***** GRIBSEC2_SET\"\n       endif\n       sec2_jnc = j_scanning_increment\n    endif\n\n    if (present(scanning_mode))then\n       if ((scanning_mode < 0) .or. (scanning_mode > 1)) then\n          write(*, '(/,\"***** FATAL ERROR.  Invalid input to GRIBSEC2_SET\")')\n          write(*,'(\"***** SCANNING_MODE must be 0 or 1.  Found: \",I12)') scanning_mode\n          stop \"***** GRIBSEC2_SET\"\n       endif\n       sec2_scm = scanning_mode\n    endif\n\n  end subroutine gribsec2_set\n\n  subroutine gribsec2_pack()\n    implicit none\n    integer :: smf\n    integer :: iskip\n    iskip = 0\n    call sbenc(newsec2, sec2_size,  sec2_size, iskip, 24)\n    call sbenc(newsec2,        0,   0, iskip, 8)\n    call sbenc(newsec2,      255, 255, iskip, 8)\n    call sbenc(newsec2, sec2_gty, 255, iskip, 8)\n\n    smf = 0\n    if (sec2_inc == -1) smf = smf + 128\n    if ((sec2_jnc ==  1) .or. (sec2_jnc < -999998)) smf = smf + 64\n    if (sec2_scm == 1) smf = smf + 32\n\n    select case (sec2_gty)\n    case (0) ! Cylindrical Equidistant\n\n       call sbenc(newsec2, sec2_nxp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_nyp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_la1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_rac, 8, iskip, 8)\n       call sbenc(newsec2, sec2_la2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dxt, 0, iskip, 16)\n       call sbenc(newsec2, sec2_dyt, sec2_dxt, iskip, 16)\n       call sbenc(newsec2, smf,      0, iskip, 8)\n\n    case (1) ! Mercator\n       call sbenc(newsec2, sec2_nxp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_nyp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_la1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_rac, 8, iskip, 8)\n       call sbenc(newsec2, sec2_la2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_tr1, 0, iskip, 24)\n       call sbenc(newsec2, 0,      0, iskip, 8)\n       call sbenc(newsec2, smf,      0, iskip, 8)\n       call sbenc(newsec2, sec2_dxt, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dyt, sec2_dxt, iskip, 24)\n\n    case (3) ! Lambert Conformal\n       call sbenc(newsec2, sec2_nxp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_nyp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_la1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_rac, 8, iskip, 8)\n       call sbenc(newsec2, sec2_lov, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dxt, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dyt, sec2_dxt, iskip, 24)\n       call sbenc(newsec2, sec2_pcf, 0, iskip, 8)\n       call sbenc(newsec2, smf,      0, iskip, 8)\n       call sbenc(newsec2, sec2_tr1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_tr2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_spl, 0, iskip, 24)\n       call sbenc(newsec2, 0, 0, iskip, 24)\n\n\n    case (5) ! Polar Stereographic\n\n       call sbenc(newsec2, sec2_nxp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_nyp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_la1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_rac, 8, iskip, 8)\n       call sbenc(newsec2, sec2_lov, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dxt, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dyt, sec2_dxt, iskip, 24)\n       call sbenc(newsec2, sec2_pcf, 0, iskip, 8)\n       call sbenc(newsec2, smf,      0, iskip, 8)\n    case default\n       write(*, '(\"sec2_gty = \", I12)') sec2_gty\n       stop \"Unrecognized grid type in GRIBSEC2_PACK\"\n    end select\n\n  end subroutine gribsec2_pack\n\n\n\n  subroutine gribsec4_set(binary_scale_factor, reference_value_A, reference_value_B, &\n       reference_value_sign, nbits)\n    implicit none\n    integer, optional, intent(in) :: binary_scale_factor, nbits, reference_value_A, &\n         reference_value_B, reference_value_sign\n\n    if (present(binary_scale_factor)) sec4_bsf = binary_scale_factor\n    if (present(reference_value_A))   sec4_rfa = reference_value_A\n    if (present(reference_value_B))   sec4_rfb = reference_value_B\n    if (present(reference_value_sign))sec4_rfs = reference_value_sign\n    if (present(nbits))               sec4_nbt = nbits\n  end subroutine gribsec4_set\n\n  subroutine gribsec4_pack\n    implicit none\n    integer :: iskip, numunused, bmod, i, j, ist, ien, inc, jst, jen, jnc\n\n    if (sec4_nbt == 0) then\n       ! We have a constant field.  Zero bits needed (sec4_nbt==0)\n       ! to pack each datum.\n       sec4_size = 12\n       allocate(newsec4((sec4_size+3)/4))\n       newsec4 = 0\n       iskip = 0\n       call sbenc(newsec4, sec4_size, -999999, iskip, 24) ! Bytes 1-3\n       call sbenc(newsec4, 0, 0, iskip, 4)                ! Byte 4, bits 1-4\n       call sbenc(newsec4, 8, 0, iskip, 4)                ! Byte 4, bits 5-8\n       call sbenc(newsec4, sec4_bsf, 0, iskip, 16)        ! Bytes 5-6\n\n       if (sec4_rfs == -1) then                          ! Byte 7...\n          call sbenc(newsec4, 1, 0, iskip, 1)\n       elseif (sec4_rfs == 1) then\n          call sbenc(newsec4, 0, 0, iskip, 1)\n       else\n          print*, \"SEC4_RFS (Reference value sign) = \", sec4_rfs\n          stop\n       endif\n       call sbenc(newsec4, sec4_rfa, 0, iskip, 7)\n\n       call sbenc(newsec4, sec4_rfb, 0, iskip, 24)        ! Bytes 8-10\n       call sbenc(newsec4, 0, 0, iskip, 8)                ! Byte 11\n       call sbenc(newsec4, 0, 0, iskip, 8)                ! Byte 12\n\n       if (sec1_bms == 1) then\n\n          ! We have a constant field with a bitmask\n\n          call gribsec3_create()\n\n          bmod = mod(nummappt*sec4_nbt, 8)\n          if (bmod == 0) then\n             numunused = 0\n          else\n             numunused = 8 - bmod\n          endif\n\n          sec4_size = ((nummappt*sec4_nbt)+numunused) / 8 + 11\n          if (mod(sec4_size,2)/=0) then\n             sec4_size = sec4_size + 1\n             numunused = numunused + 8\n          endif\n          if (mod(((nummappt*sec4_nbt)+numunused),16) /= 8) then\n             print*, 'nummappt = ', nummappt\n             print*, 'sec4_nbt = ', sec4_nbt\n             print*, 'sec4_size = ', sec4_size\n             print*, 'numunused = ', numunused\n             stop \"Problem A\"\n          endif\n       endif\n\n       return\n    endif\n\n    ! There must be an even number of bytes.\n\n    if (sec1_bms == 1) then\n\n       call gribsec3_create()\n\n       bmod = mod(nummappt*sec4_nbt, 8)\n       if (bmod == 0) then\n          numunused = 0\n       else\n          numunused = 8 - bmod\n       endif\n\n       sec4_size = ((nummappt*sec4_nbt)+numunused) / 8 + 11\n       if (mod(sec4_size,2)/=0) then\n          sec4_size = sec4_size + 1\n          numunused = numunused + 8\n       endif\n       if (mod(((nummappt*sec4_nbt)+numunused),16) /= 8) then\n          print*, 'sec4_size = ', sec4_size\n          print*, 'numunused = ', numunused\n          stop \"Problem A\"\n       endif\n\n    else\n\n       bmod = mod(size(gribiarr)*sec4_nbt, 8)\n       if (bmod == 0) then\n          numunused = 0\n       else\n          numunused = 8 - bmod\n       endif\n       sec4_size = (size(gribiarr)*sec4_nbt+numunused) / 8 + 11\n\n       if (mod(sec4_size,2) /= 0) then\n          sec4_size = sec4_size + 1\n          numunused = numunused + 8\n       endif\n\n       if (mod(((size(gribiarr)*sec4_nbt)+numunused),16) /= 8) then\n          print*, 'numused = ', size(gribiarr)*sec4_nbt\n          print*, 'sec4_size = ', sec4_size\n          print*, 'numunused = ', numunused\n          stop \"Problem B\"\n       endif\n\n    endif\n\n    allocate(newsec4((sec4_size+3)/4))\n    newsec4 = 0\n    iskip = 0\n    call sbenc(newsec4, sec4_size, -999999, iskip, 24)   ! Bytes 1-3\n    call sbenc(newsec4, 0, 0, iskip, 4)                  ! Byte 4, bits 1-4\n    call sbenc(newsec4, numunused, 0, iskip, 4)          ! Byte 4, bits 5-8\n    call sbenc(newsec4, sec4_bsf, 0, iskip, 16)          ! Bytes 5-6\n\n    if (sec4_rfs == -1) then                          ! Byte 7...\n       call sbenc(newsec4, 1, 0, iskip, 1)\n    elseif (sec4_rfs == 1) then\n       call sbenc(newsec4, 0, 0, iskip, 1)\n    else\n       print*, \"SEC4_RFS (Reference value sign) = \", sec4_rfs\n       stop\n    endif\n\n    call sbenc(newsec4, sec4_rfa, 0, iskip, 7)\n\n    call sbenc(newsec4, sec4_rfb, 0, iskip, 24) ! Bytes 8-10\n    call sbenc(newsec4, sec4_nbt, 0, iskip, 8)\n\n    if ((sec2_inc == 1) .or. (sec2_inc < -999998)) then\n       ist = 1\n       ien = size(gribiarr,1)\n       inc = 1\n    elseif (sec2_inc == -1) then\n       ist = size(gribiarr,1)\n       ien = 1\n       inc = -1\n    endif\n\n    if ((sec2_jnc == 1) .or. (sec2_jnc < -999998)) then\n       jst = 1\n       jen = size(gribiarr,2)\n       jnc = 1\n    elseif (sec2_jnc == -1) then\n       jst = size(gribiarr,2)\n       jen = 1\n       jnc = -1\n    endif\n\n    if (sec1_bms == 1) then\n       call loop_bitmapped(gribiarr,size(gribiarr,1),size(gribiarr,2), &\n            ist,ien,inc,jst,jen,jnc,iskip)\n    else\n       call loop_not_bitmapped(gribiarr,size(gribiarr,1),size(gribiarr,2), &\n            ist,ien,inc,jst,jen,jnc,iskip)\n    endif\n\n\n    do i = 1, numunused\n       call sbenc(newsec4, 0, 0, iskip, 1)\n    enddo\n\n  end subroutine gribsec4_pack\n\n  subroutine loop_bitmapped(iarr,ix,jx,ist,ien,inc,jst,jen,jnc,iskip)\n    implicit none\n    integer, intent(in) :: ist,ien,inc,jst,jen,jnc,ix,jx\n    integer, dimension(ix,jx), intent(in) :: iarr\n    integer, intent(inout) :: iskip\n    integer :: i, j\n\n    if ((sec2_scm == 0) .or. (sec2_scm < -999998)) then\n\n       do j = jst, jen, jnc\n          do i = ist, ien, inc\n             if (lbm(i,j)) then\n                call sbenc(newsec4, iarr(i,j), -999999, iskip, sec4_nbt)\n             endif\n          enddo\n       enddo\n\n    else if (sec2_scm == 1) then\n\n       do i = ist, ien, inc\n          do j = jst, jen, jnc\n             if (lbm(i,j)) then\n                call sbenc(newsec4, iarr(i,j), -999999, iskip, sec4_nbt)\n             endif\n          enddo\n       enddo\n\n    endif\n\n  end subroutine loop_bitmapped\n\n  subroutine loop_not_bitmapped(iarr,ix,jx,ist,ien,inc,jst,jen,jnc,iskip)\n    integer, intent(in) :: ist,ien,inc,jst,jen,jnc,ix,jx\n    integer, dimension(ix,jx), intent(in) :: iarr\n    integer, intent(inout) :: iskip\n    integer :: i, j\n\n    if ((sec2_scm == 0) .or. (sec2_scm < -999998)) then\n\n       do j = jst, jen, jnc\n          do i = ist, ien, inc\n             call sbenc(newsec4, iarr(i,j), -999999, iskip, sec4_nbt)\n          enddo\n       enddo\n\n    else if (sec2_scm == 1) then\n\n       do i = ist, ien, inc\n          do j = jst, jen, jnc\n             call sbenc(newsec4, iarr(i,j), -999999, iskip, sec4_nbt)\n          enddo\n       enddo\n\n    endif\n\n  end subroutine loop_not_bitmapped\n\n  subroutine packarray(input_array, ix, jx, sigdig, eps, &\n       bitmap)\n!\n! Given a floating-point array input_array, returns an integer array gribiarr\n! which represents integer values ready for packing into the GRIB\n! record.\n!\n    implicit none\n    integer,                   intent(in)  :: ix, jx\n    real, dimension(ix,jx),    intent(in)  :: input_array\n    integer, optional,         intent(in)  :: sigdig\n    real,    optional,         intent(in)  :: eps\n    logical, dimension(ix,jx), intent(in), optional :: bitmap\n! Local:\n    integer :: npb\n    integer :: Binary_Scale_Factor\n    integer :: Decimal_Scale_Factor\n    integer :: reference_value_A\n    integer :: reference_value_B\n    integer :: reference_value_sign\n    real :: xmax, xbmax, xrange, xval\n    real :: xmin, dsmin\n    real :: dsmax, bsmax, bsmin, testdiff, tnt\n    integer :: idcflog\n    real :: maxn\n    real :: lval\n    double precision, allocatable, dimension(:) :: arr\n    double precision :: dval\n    integer :: nval, BetterD, BetterE\n    real :: eval, rval\n    logical :: invb\n    integer :: i, j, iia, jja\n\n    real,    allocatable, dimension(:) :: xarr\n    integer, allocatable, dimension(:) :: iarr\n\n    if (present(sigdig) .and. present(eps)) then\n       write(*,'(\"PACKARRAY: Either SIGDIG or EPS must be provided.\")')\n       write(*,'(\"                         You have provided both.\")')\n       stop \"ENGRIB_MODULE : PACKARRAY\"\n    endif\n\n    if (.not.(present(sigdig)) .and. .not.(present(eps))) then\n       write(*,'(\"PACKARRAY: Either SIGDIG or EPS must be provided.\")')\n       write(*,'(\"                         You have provided neither.\")')\n       stop \"ENGRIB_MODULE : PACKARRAY\"\n    endif\n\n    ! Pack into the vector xarr the desired elements of the 2d input_array.\n    if (present(bitmap)) then\n       ! print*, 'count(bitmap) = ', count(bitmap)\n       if (count(bitmap) > 0) then\n          if (count(bitmap) == ix*jx) then\n             ! the provided bitmap includes all points in the field.  Effectively, no bitmap.\n             allocate(xarr(ix*jx))\n             xarr = reshape(input_array, (/ix*jx/))\n          else if (count(bitmap) < ix*jx) then\n             allocate(xarr(count(bitmap)))\n             xarr = pack(input_array, bitmap)\n          else\n             stop \"bitmap confusion\"\n          endif\n       else\n          allocate(xarr(1))\n          xarr = 0.\n       endif\n    else\n       allocate(xarr(ix*jx))\n       xarr = reshape(input_array, (/ix*jx/))\n    endif\n\n    ! Clear out the space for a new grib record.\n    call grib_clear\n\n    call gribsec2_set(nx = ix)\n    call gribsec2_set(ny = jx)\n\n! Copy the bitmask\n    if (present(bitmap)) then\n       if (count(bitmap) < ix*jx) then\n          allocate(lbm(ix,jx))\n          lbm = bitmap\n          nummappt = count(lbm)\n          call gribsec1_set(isthere_bms = 1)\n       endif\n    endif\n\n! Copy the original data into a work array\n\n    allocate(iarr(size(xarr)))\n    allocate(arr(size(xarr)))\n    allocate(gribiarr(ix,jx))\n\n    arr = dble(xarr)\n\n! Get the min and max of the original data\n    xmin = minval(xarr)\n    xmax = maxval(xarr)\n\n    ! print*, 'xmin, xmax = ', xmin, xmax\n\n! Find a decimal scale factor D, such that, when the original data (which is\n! assumed to now be in the proper GRIB-recognized, i.e., mostly SI, units) is\n! multiplied by 10**D, the integer part of the result will have enough\n! precision to contain the appropriate information.\n\n    if (present(sigdig)) then\n       if ((xmin == 0.0) .and. (xmax == 0.0)) then\n          Decimal_Scale_Factor = 0.0\n       else\n          Decimal_Scale_Factor = sigdig-(ceiling(log10(max(abs(xmin),abs(xmax)))))\n       endif\n    endif\n    if (present(eps)) then\n       Decimal_Scale_Factor = -1 + log10(1./eps) ! 1 + log10(1./eps)\n       ! print*, 'eps = ', eps\n       ! print*, 'log10(1./eps) = ', log10(1./eps)\n       ! print*, 'Decimal Scale Factor = ', decimal_scale_factor\n    endif\n\n100 continue\n    if (present(eps)) then\n       testdiff = 1.E33\n       do while ( testdiff > eps )\n          Decimal_Scale_Factor = Decimal_Scale_Factor + 1\n          ! print*, 'Decimal_Scale_Factor = ', Decimal_Scale_Factor\n          arr = dble(xarr) * (10.D0**decimal_scale_factor)\n          ! Try a quick comparison between original array (input_array) and work array\n          testdiff = maxval(abs(((int(arr))*(10.0**(-Decimal_Scale_Factor))) - xarr))\n          ! print*, 'testdiff = ', testdiff\n       enddo\n    endif\n\n    if (present(sigdig)) then\n       arr = dble(xarr) * (10.D0**decimal_scale_factor)\n    endif\n\n! Build the reference value integers:\n! The reference value is simply the minimum of the decimal-scaled values.\n\n    ! Find the decimal-scaled xmin and xmax\n    dsmin = minval(arr)\n    dsmax = maxval(arr)\n\n    if (present(bitmap)) then\n       if (count(bitmap) == 0) then\n          ! Everything is masked out.  Nothing to encode.\n          call gribsec1_set(isthere_bms = 0)\n          Binary_Scale_Factor = 0\n          gribiarr = 0\n          call find_pack_ref_val(dsmin, Reference_Value_A, Reference_Value_B, Reference_Value_Sign, rval)\n\n          call gribsec4_set(binary_scale_factor = 0)\n          call gribsec4_set(reference_value_A = reference_value_A)\n          call gribsec4_set(reference_value_B = reference_value_B)\n          call gribsec4_set(reference_value_Sign = reference_value_Sign)\n          call gribsec4_set(nbits = 0)\n          call gribsec1_set(decimal_scale_factor = Decimal_Scale_Factor)\n          return\n       endif\n    endif\n\n    call find_pack_ref_val(dsmin, Reference_Value_A, Reference_Value_B, Reference_Value_Sign, rval)\n\n! Subtract off the Reference Value:\n    arr = arr - rval\n\n! Find a maximum of the new arr\n    maxn = maxval(arr)\n\n! We'll not use binary scaling for now.\n\n    ! Number of bits needed for packing depends on the maximum value:\n    lval = (log10(maxn+1)/log10(2.0))\n    npb = ceiling(abs(lval))\n    Binary_Scale_Factor = 0\n\n!KWM! Find a better D and E, perhaps, for a given arrmax and a given number\n!KWM! of bits.\n!KWM    call better_D_and_E(npb, real(xmax-xmin), BetterD, BetterE, Decimal_Scale_Factor, Binary_Scale_Factor)\n!KWM\n!KWM    print*, 'Original D, E: ', Decimal_Scale_Factor, Binary_Scale_Factor\n!KWM    print*, 'Better   D, E: ', BetterD, BetterE\n\n    iarr = nint(arr) ! Do we want \"INT\" or \"NINT\" ?\n\n    ! Double check that IARR is all non-negative\n    do i = 1, size(iarr)\n       if (iarr(i) < 0) then\n          print*,' i, ', i, arr(i), int(arr(i))\n          stop \"PACKARRAY problem\"\n       endif\n    enddo\n\n    dval = 1.0D1**(-Decimal_Scale_Factor)\n!  eval = 2.**Binary_Scale_Factor\n    eval = 1.0\n\n! one final test\n    testdiff = maxval(abs(((rval+dble(iarr)*eval)*dval)-xarr))\n    if (present(eps)) then\n       if (testdiff > eps) then\n          print*, '      Trying again:', testdiff, eps\n          Decimal_Scale_Factor = Decimal_Scale_Factor + 1\n          goto 100\n       endif\n    endif\n\n! Find the maximum difference between the original data and the\n! unpacking of the packed data.\n    testdiff = maxval(abs(((rval+dble(iarr)*eval)*dval)-xarr))\n    ! print*, '     Maximum abs(value), difference = ', xmax, testdiff\n\n    call gribsec1_set(decimal_scale_factor = Decimal_Scale_Factor)\n    call gribsec4_set(binary_scale_factor = binary_scale_factor)\n    call gribsec4_set(reference_value_A = reference_value_A)\n    call gribsec4_set(reference_value_B = reference_value_B)\n    call gribsec4_set(reference_value_Sign = reference_value_Sign)\n    call gribsec4_set(nbits = npb)\n!    write(*, '(5x,\"DSF NB MAX = \",2I4,2I12, 1P, 2E14.4, 0P)') &\n!         Decimal_Scale_Factor, npb, eps, testdiff\n\n    ! And finally, unpack IARR into GRIBIARR\n    if (present(bitmap)) then\n       if (count(bitmap) < ix*jx) then\n          gribiarr = unpack(iarr, bitmap, -9999999)\n       else\n          gribiarr = reshape ( iarr, (/ ix , jx /) )\n       endif\n    else\n       gribiarr = reshape ( iarr, (/ ix , jx /) )\n    endif\n\n  end subroutine packarray\n\n  subroutine better_D_and_E(npb, maxn, BetterD, BetterE, OrigD, OrigE)\n    implicit none\n    integer, intent(in)  :: npb\n    real   , intent(in)  :: maxn\n    integer, intent(in)  :: OrigD, OrigE\n    integer, intent(out) :: BetterD, BetterE\n\n    real :: m, tsave, xd, xm\n    integer :: D, E, Dsave, Esave\n    logical :: found\n\n\n    tsave = 1.E35\n    found = .FALSE.\n    m = log10(((2.0**npb)-1)/maxn)\n    ! For a given M and a variety of E values, find D and take an int.\n\n    do E = -10, 10\n       xd = m + float(E)*log10(2.0)\n       D = floor(xd)\n       xm = float(D) - float(E)*log10(2.0)\n\n       ! xm should be <= m\n       if (xm > m) then\n          print*, 'xd, D = ', xd, D\n          stop \"problem:  XM > M\"\n       endif\n\n       ! Save D and E values where m-xm is minimized\n       if ((m-xm)<tsave) then\n          found  = .TRUE.\n          Esave = E\n          Dsave = D\n          tsave = (m-xm)\n       endif\n\n    enddo\n\n    if (found) then\n       BetterD = D\n       BetterE = E\n    else\n       print*, 'Better D and E not found'\n       BetterD = OrigD\n       BetterE = OrigE\n    endif\n\n  end subroutine better_D_and_E\n\n\n  subroutine find_pack_ref_val(x, a, b, isign, rval)\n    ! Find the A and B parameters of the grib reference value xmin.\n    implicit none\n    real,    intent(in)  :: x\n    integer, intent(out) :: a, b, isign\n    real,    intent(out) :: rval\n\n    real :: y, s\n    integer :: e\n\n    if (x==0) then\n       a = 0\n       b = 0\n       isign = 1\n       rval = 0.\n       return\n    endif\n\n    y = abs(x)\n    s = sign(1.0, x)\n    e = exponent(y)\n    isign = int(s)\n\n    b = int(scale(fraction(y), 24+mod(e+128,4)))\n    a = ((e-mod(e+128,4))/4) + 64\n\n    rval = s * ((2.0**(-24)) *b ) * (16.0**(a-64))\n\n! Check for exact floating-point values.  Pretty stringent\n! and probably not terribly portable, but that's life.\n    if (rval /= x) then\n       print*, 'A and B not quite right: a,b=',a,b\n       print*, 'rval = ', rval\n       print*, 'x = ', x\n       stop \"FIND_PACK_REF_VAL\"\n    endif\n\n! B must fit into 24 bits (3 bytes)\n! A must fit into  7 bits\n    do while (b > 16777216)\n       a = a + 1\n\n       if (a > 127) then\n          print*, 'Having trouble packing reference value.'\n          stop \"FIND_PACK_REF_VAL\"\n       endif\n\n       if (isign > 0) then\n          b = b / 16\n       else\n          b = (b+15)/16\n       endif\n       rval = s * ((2.0**(-24)) *b ) * (16.0**(a-64))\n       if (rval > x) then\n          print*, 'rval > x:', rval, x\n          stop \"FIND_PACK_REF_VAL\"\n       endif\n    enddo\n\n  end subroutine find_pack_ref_val\n\nend module engrib_module_test\n\nPROGRAM  sw_to_grib\n  use engrib_module_test\n  use module_date_utilities\n  implicit none\n!\n!       This is an example Fortran program to read the GCIP/SRB archive\n!       of current instantaneous fluxes for a particular day.  It reads\n!       the data for an observation time by looping over the 51 latitude\n!       bands one at a time, and in each pass through the loop, reading\n!       data for the 111 longitude bands, and then proceeding to the\n!       next time.\n!\n!       The program also assigns latitude and longitude coordinates to\n!       the cell-centers, and gives an example of how to obtain the\n!       nominal time of an observation.\n!\n!       NOTE: Northern latitudes are positive, western longitudes are\n!             negative.\n!\n!  VARIABLES:\n!     Fluxi(Lon,Lat,Hour) : Lon=1 to Nlon, Lat=1 to Nlat; Hour=1 to\n!                                  Nhours; instantaneous flux (W/m**2)\n!     Glat(Lat)  : Lat=1 to Nlat; latitude of cell center\n!     Glon(Lon)  : Lon=1 to Nlon; longitude of cell center\n!     Hour       : hour of the day (0-23)\n!     Lat1       : latitude of center of first cell (degrees)\n!     Lon1       : longitude of center of first cell (degrees)\n!     Lrec       : record length\n!     Minute     : minutes; satellite observation is Minute minutes\n!                   after the hour\n!     Nhours     : no. of hours in a day\n!     Nlat       : max no. of latitudes\n!     Nlon       : max no. of longitudes\n!     Reslat     : resolution in latitude (degrees)\n!     Reslon     : resolution in longitude (degrees)\n!     Time       : nominal time (UTC) of satellite observation (hours)\n\n\n  integer :: Nlat\n  integer :: Nlon\n  real    :: Lat1\n  real    :: Lon1\n!     .. Parameters ..\n  integer, parameter :: Nhours = 24\n  real   , parameter :: Reslat = 0.5\n  real   , parameter :: Reslon = 0.5\n  integer, parameter :: Minute = 15\n  integer :: additional_time_offset\n\n  integer, external :: iargc\n\n!     ..\n!     .. Local Scalars ..\n  CHARACTER(len=120) :: Fname\n  INTEGER  :: Hour,  Lat, Lon\n  REAL  :: Time\n  integer :: ierr\n!     ..\n!     .. Local Arrays ..\n  REAL, allocatable, dimension(:, :, :) :: Fluxi\n  real, allocatable, dimension(:)       :: Glat\n  real, allocatable, dimension(:)       :: Glon\n  REAL, allocatable, dimension(:, :)    :: tmp\n\n!     ..\n  character(len=24) :: hdate, newdate\n  integer :: indxs\n  integer :: i\n  integer :: gribunit\n\n! Get name of GCIP/SRB file to be read from command-line.\n!\n\n! This one expect daily files, named according to <yymmdd>sda.i\n\n  if (iargc() < 1) then\n     print*, 'Program expects a command-line argument.'\n     write(*, '(/,\"***** ERROR EXIT *****\",/)')\n     stop\n  endif\n  call getarg(1, Fname)\n\n  hdate = \"2000-00-00_00:00:00.0000\"\n  indxs = index(trim(Fname),\"/\",.TRUE.)\n  hdate(3:4)  = Fname(indxs+1:indxs+2) ! yy\n  hdate(6:7)  = Fname(indxs+3:indxs+4) ! mm\n  hdate(9:10) = Fname(indxs+5:indxs+6) ! dd\n  if ( hdate(1:4) > \"2050\" ) hdate(1:2) = \"19\"\n\n  print*, 'Hdate = ', Hdate\n\n  if (hdate(1:7) < \"2001-07\") then\n     NLat = 51\n     NLon = 111\n     Lat1 = 25.0\n     Lon1 = -125.0\n  else\n     NLat = 61\n     NLon = 121\n     Lat1 = 24.0\n     Lon1 = -126.0\n  endif\n\n  allocate(Fluxi(Nlon, Nlat, Nhours))\n  allocate(Glat(Nlat))\n  allocate(Glon(Nlon))\n  Fluxi = 0.\n\n! Open and read GCIP/SRB file\n! Use c I/O routines to avoid the direct-access Fortran I/O\n\n  call getdata(Fname, Fluxi, Nlon, Nlat, Nhours)\n\n  ! print*, 'Minimum/Maximum Flux = ', minval(Fluxi), maxval(fluxi)\n!KWM     print*, 'Min/Max fractional part = ', minval(abs(Fluxi-int(fluxi))), &\n!KWM          maxval(abs(Fluxi-int(fluxi)))\n\n! Calculate latitude and longitude coordinates of cell centers\n!\n  DO Lat = 1, Nlat\n     Glat( Lat ) = ( Lat-1 ) * Reslat + Lat1\n  ENDDO\n  DO Lon = 1, Nlon\n     Glon( Lon ) = ( Lon-1 ) * Reslon + Lon1\n  ENDDO\n\n  where(fluxi < -998)\n     fluxi = -1.E30\n  end where\n\n  DO Hour = 1, Nhours\n     newdate = hdate\n\n     write(*,'(\"Assuming that the SW Data offset is about 30 minutes, rather than the stated 15 minutes\")')\n     additional_time_offset = 15\n\n     call geth_newdate(newdate(1:16), hdate(1:16), (hour-1)*60+Minute + additional_time_offset)\n     print*, 'newdate = ', newdate(1:16)\n\n     call open_newgrib(gribunit, \"SW.\"//newdate(1:4)//newdate(6:7)//newdate(9:10)//newdate(12:13)//newdate(15:16)//\".grb\")\n     ! Write the data in GRIB format\n!     call packarray(fluxi(:,:,hour), Nlon, Nlat, eps=1.00, bitmap=(fluxi(:,:,hour)>=0.0))\n     call packarray(fluxi(:,:,hour), Nlon, Nlat, eps=1.00, bitmap=(fluxi(:,:,hour)>=-100.0))\n     call gribsec1_set(parameter_id=204)\n     call gribsec1_set(level_type=1)\n     call gribsec1_set(level_1 = 0)\n     call gribsec1_set(hdate=newdate(1:16))\n     call gribsec1_set(P1=00)\n     call gribsec1_set(P2=00)\n     call gribsec1_set(time_unit=1)\n     call gribsec1_set(time_range_indicator=0)\n     call gribsec1_set(center_id=244)\n     call gribsec1_set(process_id=244)\n     call gribsec1_set(subcenter_id=244)\n\n     call gribsec2_set(grid_type=0)\n     call gribsec2_set(la1=Glat(1))\n     call gribsec2_set(lo1=Glon(1))\n     call gribsec2_set(la2=Glat(Nlat))\n     call gribsec2_set(lo2=Glon(Nlon))\n     call gribsec2_set(dx=reslon)\n     call gribsec2_set(dy=reslat)\n     !call gribsec2_set(resolution_and_component=)\n     !call gribsec2_set(scanning_mode=)\n\n     call write_grib(gribunit)\n     call close_newgrib(gribunit)\n\n     if (allocated(lbm)) deallocate(lbm)\n     if (allocated(gribiarr)) deallocate(gribiarr)\n     if (allocated(newsec2)) deallocate(newsec2)\n     if (allocated(newsec3)) deallocate(newsec3)\n     if (allocated(newsec4)) deallocate(newsec4)\n\n  enddo\n\nEND PROGRAM Sw_to_grib\n\nsubroutine getdata(Fname, Fluxi, Nlon, Nlat, Nhours)\n  implicit none\n  integer :: Nlon, Nlat, Nhours, icount\n  real, dimension(Nlon, Nlat, Nhours) :: Fluxi\n  character(len=*) :: Fname\n  integer :: munit\n  integer :: iread\n  integer :: ierr\n  integer :: Lrec\n  Lrec = Nlon * Nlat * Nhours * 4\n\n! Open and read the data.\n  call copen(Munit,trim(Fname)//char(0), 1, ierr, 0)\n  if ((ierr /= 0).or.(Munit == -1)) then\n     print*, 'Error Opening.'\n     write(*, '(/,\"***** ERROR EXIT *****\",/)')\n     stop\n  endif\n\n  call bnread(Munit, Fluxi, Lrec, iread, ierr, 10)\n  if ((ierr /= 0) .or. (iread /= Lrec)) then\n     print*, 'Error Reading.'\n     write(*, '(/,\"***** ERROR EXIT *****\",/)')\n     stop\n  endif\n\n!KWM  call cclose(Munit,0,ierr)\n!KWM  if (ierr /= 0) then\n!KWM     print*, 'Error Closing.'\n!KWM     write(*, '(/,\"***** ERROR EXIT *****\",/)')\n!KWM     stop\n!KWM  endif\n\nend subroutine getdata\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/gcip_sw_to_grib/srb_monthly_to_grib.F",
    "content": "!*****************************************************************************!\n!                                                                             !\n! Module to facilitate putting fields into GRIB 1 format.                     !\n!                                                                             !\n! Still needs a lot of work;                                                  !\n! still needs a lot of documentation;                                         !\n! but I'm fairly pleased with the potential.                                  !\n!                                                                             !\n! Author:  Kevin W. Manning                                                   !\n!          NCAR/MMM                                                           !\n!          October 2001 and continuing                                        !\n!          October 2010:  Allow a constant field to be bitmasked.             !\n!          October 2010:  Don't encode the bitmask if the mask includes the   !\n!                         entire grid.  Treat it as a non-bitmasked field.    !\n!                                                                             !\n!*****************************************************************************!\n\nmodule engrib_module_test\n\n  integer, private, parameter :: sec1_size = 28\n  integer, private :: sec1_ptv\n  integer, private :: sec1_cid\n  integer, private :: sec1_pid\n  integer, private :: sec1_gid\n  integer, private :: sec1_gds\n  integer, private :: sec1_bms\n  integer, private :: sec1_prm\n  integer, private :: sec1_lty\n  integer, private :: sec1_lv1\n  integer, private :: sec1_lv2\n  integer, private :: sec1_gyr\n  integer, private :: sec1_gmo\n  integer, private :: sec1_gdy\n  integer, private :: sec1_ghr\n  integer, private :: sec1_gmi\n  integer, private :: sec1_tmu\n  integer, private :: sec1_pr1\n  integer, private :: sec1_pr2\n  integer, private :: sec1_tri\n  integer, private :: sec1_nin\n  integer, private :: sec1_nmi\n  integer, private :: sec1_cen\n  integer, private :: sec1_sub\n  integer, private :: sec1_dsf\n\n  integer, private :: sec2_size\n  integer, private :: sec2_gty\n  integer, private :: sec2_nxp\n  integer, private :: sec2_nyp\n  integer, private :: sec2_la1\n  integer, private :: sec2_lo1\n  integer, private :: sec2_la2\n  integer, private :: sec2_lo2\n  integer, private :: sec2_rac\n  integer, private :: sec2_lov\n  integer, private :: sec2_dxt\n  integer, private :: sec2_dyt\n  integer, private :: sec2_tr1\n  integer, private :: sec2_tr2\n  integer, private :: sec2_pcf  ! Default 0\n\n  integer, private :: sec2_inc  ! Default +1\n  integer, private :: sec2_jnc  ! Default +1\n  integer, private :: sec2_scm  ! Default 0\n  integer, private :: sec2_spl  ! LC:  Latitude of the \"southern pole\"\n\n  integer, private :: sec3_size\n  logical, allocatable, dimension(:,:) :: lbm\n  integer, private :: nummappt\n\n  integer, private :: sec4_size\n  integer, private :: sec4_bsf\n  integer, private :: sec4_rfa\n  integer, private :: sec4_rfb\n  integer, private :: sec4_rfs\n  integer, private :: sec4_nbt\n  integer, allocatable, dimension(:,:) :: gribiarr\n\n  integer, dimension(2) :: newsec0  ! 8 bytes\n  integer, dimension(7) :: newsec1  ! 28 bytes\n  integer, allocatable, dimension(:) :: newsec2\n  integer, allocatable, dimension(:) :: newsec3\n  integer, allocatable, dimension(:) :: newsec4\n  integer, parameter :: newsec5 = Z\"37373737\"  !encodes \"7777\"\n\n#if defined (__sgi) || defined (__sun) || defined (__alpha) || defined (__linux)\n  logical, parameter :: DO_BYTE_SWAP = .TRUE.\n#else\n  logical, parameter :: DO_BYTE_SWAP = .FALSE.\n#endif\n\ncontains\n\n  subroutine open_newgrib(gribunit, flnm)\n!*****************************************************************************!\n!                                                                             !\n! Subroutine OPEN_NEWGRIB:                                                    !\n!    Part of Module ENGRIB_MODULE                                             !\n!                                                                             !\n! Purpose:                                                                    !\n!    Open a c FILE stream for output.                                         !\n!                                                                             !\n! Argument list:                                                              !\n!                                                                             !\n!    Input:                                                                   !\n!       FLNM:     the pathname of the file to create as a GRIB file.          !\n!    Output:                                                                  !\n!       GRIBUNIT: the FILE* stream referring to new file FLNM.                !\n!                                                                             !\n! Side Effects:                                                               !\n!                                                                             !\n!   ** Opens the FILE* stream GRIBUNIT for output as file FLNM.               !\n!                                                                             !\n!   ** If file FLNM does not exist, it is created and ready for new contents. !\n!                                                                             !\n!   ** If file FLNM already exists, it is destroyed, recreated, and ready     !\n!      for new contents.                                                      !\n!                                                                             !\n!   ** If file FLNM for some reason cannot be created (or recreated), an      !\n!      error message is printed and the program is halted.                    !\n!                                                                             !\n! Externals:                                                                  !\n!                                                                             !\n!   ** Subroutine COPEN                                                       !\n!         Where is COPEN? [i.e., what package, module, or source-code file]   !\n!                                                                             !\n!                                                                             !\n!*****************************************************************************!\n    implicit none\n\n! Input:\n    character(len=*), intent(in) :: flnm\n\n! Output:\n    integer, intent(out) :: gribunit\n\n! Local variables:\n    integer :: ierr  ! Error flag returned from call to copen.\n\n    ! Open the file FLNM for output as FILE* stream GRIBUNIT:\n    call copen(gribunit, flnm//char(0), 0, ierr, 0)\n\n    ! Check if the open was successful.  If not, write a message and exit:\n    if (ierr /= 0) then\n       write(*,'(/,\"***** ERROR *****\")')\n       write(*,'(/,\"OPEN_NEWGRIB:  Call to COPEN could not open file \", A,/)') &\n            flnm\n       call abort\n    endif\n\n  end subroutine open_newgrib\n\n  subroutine close_newgrib(gribunit)\n!*****************************************************************************!\n!                                                                             !\n! Subroutine CLOSE_NEWGRIB:                                                   !\n!    Part of Module ENGRIB_MODULE                                             !\n!                                                                             !\n! Purpose:                                                                    !\n!    Close a previously-opened c FILE* stream.                                !\n!                                                                             !\n! Argument list:                                                              !\n!                                                                             !\n!    Input:                                                                   !\n!       GRIBUNIT: the FILE* stream to be closed.                              !\n!    Output:                                                                  !\n!       None                                                                  !\n!                                                                             !\n! Side Effects:                                                               !\n!                                                                             !\n!   ** Closes the FILE* stream GRIBUNIT.                                      !\n!                                                                             !\n!   ** If for some reason the close fails, an error message is printed        !\n!      and the program is halted.                                             !\n!                                                                             !\n! Externals:                                                                  !\n!                                                                             !\n!   ** Subroutine CCLOSE                                                      !\n!         Where is CCLOSE? [i.e., what package, module, or source-code file]  !\n!                                                                             !\n!*****************************************************************************!\n    implicit none\n! Input:\n    integer, intent(in) :: gribunit\n\n! Local variables\n    integer :: ierr ! Error flag returned from call to CCLOSE.\n\n    call cclose(gribunit, 0, ierr)\n    if (ierr /= 0) then\n       write(*,'(/,\"***** ERROR *****\")')\n       write(*,'(/,\"CLOSE_NEWGRIB:  Call to CCLOSE could not close stream \", I12,/)') &\n            gribunit\n       call abort\n    endif\n  end subroutine close_newgrib\n\n\n  subroutine write_grib(gribunit)\n!*****************************************************************************!\n!                                                                             !\n! Subroutine WRITE_GRIB:                                                      !\n!    Part of Module ENGRIB_MODULE                                             !\n!                                                                             !\n! Purpose:                                                                    !\n!    Write                                                                    !\n!                                                                             !\n! Argument list:                                                              !\n!                                                                             !\n!    Input:                                                                   !\n!       GRIBUNIT: the FILE* stream to be written to.                          !\n!                                                                             !\n!    Output:                                                                  !\n!       None                                                                  !\n!                                                                             !\n! Other variables in ENGRIB_MODULE accessed by this subroutine:               !\n!                                                                             !\n!   ** NEWSEC0:  The integer array into which GRIB section 0 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC1:  The integer array into which GRIB section 1 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC2:  The integer array into which GRIB section 2 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC3:  The integer array into which GRIB section 3 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC4:  The integer array into which GRIB section 4 information is   !\n!                to be packed.  Modified under WRITE_GRIB.                    !\n!                                                                             !\n!   ** NEWSEC5:  The constant character array, with PARAMETER attribute, which!\n!                contains GRIB section 5 information, always \"7777\".          !\n!                                                                             !\n!   ** SEC1_SIZE: The size (bytes) of GRIB section 1, with PARAMETER          !\n!                 attribute; SEC1_SIZE = 28.                                  !\n!                                                                             !\n!   ** SEC2_SIZE: The size (bytes) of GRIB section 2.                         !\n!                                                                             !\n!   ** SEC3_SIZE: The size (bytes) of GRIB section 3.                         !\n!                                                                             !\n!   ** SEC4_SIZE: The size (bytes) of GRIB section 4.                         !\n!                                                                             !\n!   ** DO_BYTE_SWAP:  Logical parameter, machine dependent, TRUE if           !\n!                     byte-swapping is neede upon output.                     !\n!                                                                             !\n! Side Effects:                                                               !\n!                                                                             !\n!   ** Encodes all the GRIB header information into the GRIB header,          !\n!      filling integer arrays NEWSEC0, NEWSEC1, NEWSEC2, NEWSEC3, and         !\n!      NEWSEC4.                                                               !\n!                                                                             !\n!   ** Does byte swapping, if necessary, on integer arrays NEWSEC0, NEWSEC1,  !\n!      NEWSEC2, NEWSEC3, and, NEWSEC4.                                        !\n!                                                                             !\n!   ** Writes a complete GRIB record to FILE* stream GRIBUNIT.                !\n!                                                                             !\n! Other subroutine and functions used from ENGRIB_MODULE:                     !\n!                                                                             !\n!   ** GRIBSEC0_PACK:  Packs GRIB section 0 information into array NEWSEC0    !\n!                                                                             !\n!   ** GRIBSEC1_PACK:  Packs GRIB section 1 information into array NEWSEC1    !\n!                                                                             !\n!   ** GRIBSEC2_PACK:  Packs GRIB section 2 information into array NEWSEC2    !\n!                                                                             !\n!   ** GRIBSEC4_PACK:  Packs GRIB section 4 information into array NEWSEC4    !\n!                                                                             !\n! Externals:                                                                  !\n!                                                                             !\n!   ** SWAP4F                                                                 !\n!                                                                             !\n!   ** BNWRIT                                                                 !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n! Argument list input:\n    integer, intent(in) :: gribunit\n\n! Argument list output: (none)\n\n! Local variables:\n    integer :: ierr, iwrt\n    integer, allocatable, dimension(:) :: output_buffer\n    integer :: output_size\n    integer :: ostart\n    integer :: ioffs\n    integer :: inskip\n    integer :: outskip\n    integer :: i\n    integer :: k\n    integer :: iout\n    integer :: itmp\n\n    ! Final packing of all sections, before the write.\n    ! These should stay in this order:\n    !      gribsec1_pack, gribsec2_pack, gribsec4_pack, gribsec0_pack\n    ! because the other packing needs to be done before we know the final\n    ! size of the grib record to go into GRIB section 0.\n    call gribsec1_pack\n    call gribsec2_pack\n    call gribsec4_pack\n    call gribsec0_pack\n\n! Do the output, byte-swapping, if necessary:\n\n    output_size = 8 + sec1_size + sec2_size + sec3_size + sec4_size + 4\n    allocate(output_buffer(output_size))\n    output_buffer = 0\n\n    ! Copy GRIB Section 0.  Known to be 2 bytes.\n    call sbytes(output_buffer, newsec0, 0, 32, 0, 2)\n    ostart = size(newsec0)\n\n    ! Copy GRIB SEction 1\n    if (mod(sec1_size,4)/=0) stop \"WEIRD SEC1 SIZE FOR SWAPPING\" ! We know sec1_size should be 28\n    do iwrt = 1, size(newsec1)\n       call sbyte(output_buffer(ostart+iwrt), newsec1(iwrt), 0, 32)\n    enddo\n    ostart = ostart + size(newsec1)\n\n    ! Copy GRIB Section 2\n    if (mod(sec2_size,4)/=0) stop \"WEIRD SEC2 SIZE SWAP FOR SWAPPING\" ! We know sec2_size should be 32\n    do iwrt = 1, size(newsec2)\n       call sbyte(output_buffer(ostart+iwrt), newsec2(iwrt), 0, 32)\n    enddo\n    ostart = ostart + size(newsec2)\n    ioffs = 0\n\n       ! Copy GRIB Section 3\n\n    ! Bypass <ostart> words + <outskip> bytes in <output_buffer> before we start packing into the <output_buffer> array.\n    ! Skip <inskip> bytes in <newsec3> before we start reading from <newsec3>\n    inskip = 0\n    outskip = 0\n    i = 1\n    iout = ostart+1\n    do k = 1, sec3_size\n       call gbyte(newsec3(i), itmp, inskip, 8)\n       call sbyte(output_buffer(iout), itmp, outskip, 8)\n       inskip = inskip + 8\n       outskip = outskip + 8\n       if (outskip == 32) then\n          outskip = 0\n          iout = iout + 1\n       endif\n       if (inskip == 32) then\n          inskip = 0\n          i = i + 1\n       endif\n    enddo\n\n    ! Copy GRIB Section 4\n    inskip = 0\n    i = 1\n    do k = 1, sec4_size\n       call gbyte(newsec4(i), itmp, inskip, 8)\n       call sbyte(output_buffer(iout), itmp, outskip, 8)\n       inskip = inskip + 8\n       outskip = outskip + 8\n       if (outskip == 32) then\n          outskip = 0\n          iout = iout + 1\n       endif\n       if (inskip == 32) then\n          inskip = 0\n          i = i + 1\n       endif\n    enddo\n\n    ! Copy GRIB Section 5\n    inskip = 0\n    i = 1\n    do k = 1, 4\n       call gbyte(newsec5, itmp, inskip, 8)\n       call sbyte(output_buffer(iout), itmp, outskip, 8)\n       inskip = inskip + 8\n       outskip = outskip + 8\n       if (outskip == 32) then\n          outskip = 0\n          iout = iout + 1\n       endif\n       if (inskip == 32) then\n          inskip = 0\n          i = i + 1\n       endif\n    enddo\n\n    if (DO_BYTE_SWAP) then\n       if (mod(output_size,4) == 0) then\n          call swap4f(output_buffer, output_size)\n       else\n          call swap4f(output_buffer, output_size+mod(output_size,4))\n       endif\n    endif\n\n    call bnwrit(gribunit, output_buffer, output_size, iwrt, ierr, 0)\n\n  end subroutine write_grib\n\n  subroutine grib_clear\n    call gribsec0_clear\n    call gribsec1_clear\n    call gribsec2_clear\n    call gribsec3_clear\n    call gribsec4_clear\n  end subroutine grib_clear\n\n  subroutine gribsec0_clear\n    implicit none\n    newsec0 = 0\n  end subroutine gribsec0_clear\n\n  subroutine gribsec1_clear\n    implicit none\n    newsec1 = 0\n\n    sec1_ptv = -999999\n    sec1_cid = -999999\n    sec1_pid = -999999\n    sec1_gid = -999999\n    sec1_gds = -999999\n    sec1_bms = -999999\n    sec1_prm = -999999\n    sec1_lty = -999999\n    sec1_lv1 = -999999\n    sec1_lv2 = -999999\n    sec1_gyr = -999999\n    sec1_gmo = -999999\n    sec1_gdy = -999999\n    sec1_ghr = -999999\n    sec1_gmi = -999999\n    sec1_tmu = -999999\n    sec1_pr1 = -999999\n    sec1_pr2 = -999999\n    sec1_tri = -999999\n    sec1_nin = -999999\n    sec1_nmi = -999999\n    sec1_cen = -999999\n    sec1_sub = -999999\n    sec1_dsf = -999999\n\n  end subroutine gribsec1_clear\n\n  subroutine gribsec2_clear\n    implicit none\n    sec2_size = 0\n    sec2_pcf = -999999\n    sec2_inc = -999999\n    sec2_jnc = -999999\n    sec2_rac = -999999\n    sec2_scm = -999999\n    sec2_tr1 = -999999\n    sec2_tr2 = -999999\n    if (allocated(newsec2)) deallocate(newsec2)\n\n  end subroutine gribsec2_clear\n\n  subroutine gribsec3_clear\n    implicit none\n\n    sec3_size = 0\n    nummappt = 0\n    if (allocated(lbm)) deallocate(lbm)\n    if (allocated(newsec3)) deallocate(newsec3)\n\n  end subroutine gribsec3_clear\n\n  subroutine gribsec4_clear\n    implicit none\n    sec4_size = 0\n    sec4_bsf = -999999\n    sec4_rfa = -999999\n    sec4_rfb = -999999\n    sec4_rfs = -999999\n    sec4_nbt = -999999\n    if (allocated(newsec4)) deallocate(newsec4)\n    if (allocated(gribiarr)) deallocate(gribiarr)\n  end subroutine gribsec4_clear\n\n  subroutine gribsec0_pack()\n!*****************************************************************************!\n!                                                                             !\n! Subroutine GRIBSEC0_PACK:                                                   !\n!    Part of Module ENGRIB_MODULE                                             !\n!                                                                             !\n! Purpose:                                                                    !\n!    Pack GRIB section 0 information into array NEWSEC0                       !\n!                                                                             !\n! Argument list:                                                              !\n!                                                                             !\n!    Input:                                                                   !\n!       None                                                                  !\n!    Output:                                                                  !\n!       None                                                                  !\n!                                                                             !\n! Other variables in ENGRIB_MODULE accessed by this subroutine:               !\n!                                                                             !\n!   ** NEWSEC0  :  Integer array to hold GRIB section 0 information.          !\n!                  Modified under GRIBSEC0_PACK.                              !\n!                                                                             !\n!   ** SEC1_SIZE:  Size (bytes) of GRIB section 1.                            !\n!                                                                             !\n!   ** SEC2_SIZE:  Size (bytes) of GRIB section 2.                            !\n!                                                                             !\n!   ** SEC3_SIZE:  Size (bytes) of GRIB section 3.                            !\n!                                                                             !\n!   ** SEC4_SIZE:  Size (bytes) of GRIB section 4.                            !\n!                                                                             !\n! Side Effects:                                                               !\n!                                                                             !\n!   ** Packs GRIB section 0 information into array NEWSEC0                    !\n!                                                                             !\n! Other subroutine and functions used from ENGRIB_MODULE:                     !\n!                                                                             !\n!   ** SBENC:  Packs groups of bits into an integer array.  Basically         !\n!              a wrapper for the SBYTE subroutine.                            !\n!                                                                             !\n! Externals:                                                                  !\n!                                                                             !\n!   None.                                                                     !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n! Local variables:\n    integer :: iskip\n    integer :: totsize\n\n    totsize = 8 + sec1_size + sec2_size + sec3_size + sec4_size + 4\n    iskip = 0\n\n    call sbenc(newsec0, ichar(\"G\"), ichar(\"G\"), iskip, 8)\n    call sbenc(newsec0, ichar(\"R\"), ichar(\"R\"), iskip, 8)\n    call sbenc(newsec0, ichar(\"I\"), ichar(\"I\"), iskip, 8)\n    call sbenc(newsec0, ichar(\"B\"), ichar(\"B\"), iskip, 8)\n\n    call sbenc(newsec0, totsize, -999999, iskip, 24)\n    call sbenc(newsec0, 1, 1, iskip, 8)\n\n  end subroutine gribsec0_pack\n\n  subroutine gribsec1_pack()\n    implicit none\n    integer :: gdsbms, iskip\n\n    gdsbms = 0\n    if (sec1_gds > -999998) then\n       gdsbms = gdsbms + 128*sec1_gds\n    endif\n    if (sec1_bms > -999998) then\n       gdsbms = gdsbms + 64*sec1_bms\n    endif\n\n    iskip = 0\n    call sbenc(newsec1,       28,  28, iskip, 24)\n    call sbenc(newsec1, sec1_ptv, 255, iskip,  8)\n    call sbenc(newsec1, sec1_cid, 255, iskip,  8)\n    call sbenc(newsec1, sec1_pid, 255, iskip,  8)\n    call sbenc(newsec1, sec1_gid, 255, iskip,  8)\n    call sbenc(newsec1,   gdsbms,   0, iskip,  8)\n    call sbenc(newsec1, sec1_prm, 255, iskip,  8)\n    call sbenc(newsec1, sec1_lty, 255, iskip,  8)\n    select case (sec1_lty)\n    case (0:99)\n       call sbenc(newsec1, 0,   0, iskip, 16)\n    case (100,105,107,109,111,113,115,117,119,125,160,200,201)\n       call sbenc(newsec1, sec1_lv1, 0, iskip, 16)\n    case (101,102,104,106,108,110,112,114,116,120,121,128,141)\n       call sbenc(newsec1, sec1_lv1, 0, iskip, 8)\n       call sbenc(newsec1, sec1_lv2, 0, iskip, 8)\n    case default\n       print*, 'SEC1_LTY = ', sec1_lty\n       stop \"Unrecognized SEC1_LTY in GRIBSEC1_PACK\"\n    end select\n    call sbenc(newsec1, sec1_gyr, 255, iskip,  8)\n    call sbenc(newsec1, sec1_gmo, 255, iskip,  8)\n    call sbenc(newsec1, sec1_gdy, 255, iskip,  8)\n    call sbenc(newsec1, sec1_ghr, 255, iskip,  8)\n    call sbenc(newsec1, sec1_gmi, 255, iskip,  8)\n    call sbenc(newsec1, sec1_tmu, 255, iskip,  8)\n    call sbenc(newsec1, sec1_pr1, 255, iskip,  8)\n    call sbenc(newsec1, sec1_pr2, 255, iskip,  8)\n    call sbenc(newsec1, sec1_tri, 255, iskip,  8)\n    call sbenc(newsec1, sec1_nin,   0, iskip, 16)\n    call sbenc(newsec1, sec1_nmi,   0, iskip,  8)\n    call sbenc(newsec1, sec1_cen, 255, iskip,  8)\n    call sbenc(newsec1, sec1_sub, 255, iskip,  8)\n    call sbenc(newsec1, sec1_dsf,   0, iskip,  16)\n\n  end subroutine gribsec1_pack\n\n  subroutine sbenc(buf, in, df, sk, nb)\n    implicit none\n    integer, dimension(*) :: buf ! Buffer to copy bits to.\n    integer, intent(in) :: in             ! word containing bits to copy\n    integer, intent(in) :: df             ! Default bits, in case of no-data value\n    integer, intent(inout) :: sk          ! Number of bits to skip\n    integer, intent(in) :: nb             ! number of bits to encode\n\n    if (in > -999998) then\n!KWM       if ((in == 194) .and. (sk == 48)) then\n!KWM          print*, 'SBENC:  call sbyte:  in,sk,nb = ', in,sk,nb\n!KWM       endif\n       call sbyte(buf, in, sk, nb)\n!KWM       if ((in == 194) .and. (sk == 48)) then\n!KWM          print'(\"SBENC:  BUF(1) = \",Z8.8)', buf(1)\n!KWM          print'(\"SBENC:  BUF(2) = \",Z8.8)', buf(2)\n!KWM       endif\n    else\n       call sbyte(buf, df, sk, nb)\n    endif\n    sk = sk + nb\n  end subroutine sbenc\n\n  subroutine gribsec1_set(parameter_table_version, center_id, process_id, &\n       grid_id, isthere_gds, isthere_bms, parameter_id, level_type, &\n       level_1, level_2, year, month, day, hour, minute, time_unit, &\n       p1, p2, time_range_indicator, number_included, number_missing, &\n       century, subcenter_id, decimal_scale_factor, &\n       hdate)\n    implicit none\n    integer, intent(in), optional :: parameter_table_version, center_id, process_id, &\n         grid_id, isthere_gds, isthere_bms, parameter_id, level_type, &\n         level_1, level_2, year, month, day, hour, minute, time_unit, &\n         p1, p2, time_range_indicator, number_included, number_missing, &\n         century, subcenter_id, decimal_scale_factor\n    character(len=*), intent(in), optional :: hdate\n\n    integer :: cn, yr, mo, dy, hr, mi\n    integer :: ierr\n\n    if (present(parameter_table_version)) sec1_ptv = parameter_table_version\n    if (present(center_id))               sec1_cid = center_id\n    if (present(process_id))              sec1_pid = process_id\n    if (present(grid_id))                 sec1_gid = grid_id\n    if (present(isthere_gds))             sec1_gds = isthere_gds\n    if (present(isthere_bms))             sec1_bms = isthere_bms\n    if (present(parameter_id))            sec1_prm = parameter_id\n    if (present(level_type))              sec1_lty = level_type\n    if (present(level_1))                 sec1_lv1 = level_1\n    if (present(level_2))                 sec1_lv2 = level_2\n    if (present(year))                    sec1_gyr = year\n    if (present(month))                   sec1_gmo = month\n    if (present(day))                     sec1_gdy = day\n    if (present(hour))                    sec1_ghr = hour\n    if (present(minute))                  sec1_gmi = minute\n    if (present(time_unit))               sec1_tmu = time_unit\n    if (present(p1))                      sec1_pr1 = p1\n    if (present(p2))                      sec1_pr2 = p2\n    if (present(time_range_indicator))    sec1_tri = time_range_indicator\n    if (present(number_included))         sec1_nin = number_included\n    if (present(number_missing))          sec1_nmi = number_missing\n    if (present(century))                 sec1_cen = century\n    if (present(subcenter_id))            sec1_sub = subcenter_id\n    if (present(decimal_scale_factor)) then\n       if (decimal_scale_factor < 0) then\n          sec1_dsf = (2**15)-decimal_scale_factor\n       else\n          sec1_dsf = decimal_scale_factor\n       endif\n    endif\n\n    if (present(hdate)) then\n       cn = 0\n       yr = 0\n       mo = 0\n       dy = 0\n       hr = 0\n       mi = 0\n       select case (len(hdate))\n       case (16:)\n          read(hdate,'(I2,I2,1x,I2,1x,I2,1x,I2,1x,I2)', iostat=ierr) cn, yr, mo, dy, hr, mi\n       case (13)\n          read(hdate,'(I2,I2,1x,I2,1x,I2,1x,I2)', iostat=ierr) cn, yr, mo, dy, hr\n       case (10)\n          read(hdate,'(I2,I2,1x,I2,1x,I2)', iostat=ierr) cn, yr, mo, dy\n       case (7)\n          read(hdate,'(I2,I2,1x,I2)', iostat=ierr) cn, yr, mo\n       case (4)\n          read(hdate,'(I2,I2)', iostat=ierr) cn, yr\n       case default\n          print*, \"Bad HDATE = \"//hdate\n          stop \"Bad HDATE in GRIBSEC1_SET\"\n       end select\n       if (ierr /= 0) then\n          print*, 'Problem reading from hdate #'//hdate//\"#\"\n          stop\n       endif\n\n       sec1_gyr = yr\n       sec1_gmo = mo\n       sec1_gdy = dy\n       sec1_ghr = hr\n       sec1_gmi = mi\n       if (yr > 0) then\n          sec1_cen = cn+1\n       else\n          sec1_cen = cn\n       endif\n    endif\n  end subroutine gribsec1_set\n\n  subroutine gribsec3_create()\n\n    sec3_size = (size(lbm,1)*size(lbm,2))/8\n    nover = mod(size(lbm,1)*size(lbm,2), 8)\n    if (nover > 0) then\n       sec3_size = sec3_size + 1\n       numunused = 8-nover\n    endif\n    if (mod(sec3_size,2) == 1) then\n       sec3_size = sec3_size + 1\n       numunused = numunused + 8\n    endif\n\n    sec3_size = sec3_size + 6\n\n    allocate(newsec3((sec3_size+3)/4))\n    newsec3 = 0\n\n    iskip = 0\n    call sbenc(newsec3, sec3_size, sec3_size, iskip, 24)\n    call sbenc(newsec3, numunused, numunused, iskip, 8)\n    call sbenc(newsec3, 0, 0, iskip, 16)\n\n    if ((sec2_inc == 1) .or. (sec2_inc < -999998)) then\n       ist = 1\n       ien = size(lbm,1)\n       inc = 1\n    elseif (sec2_inc == -1) then\n       ist = size(lbm,1)\n       ien = 1\n       inc = -1\n    endif\n\n\n    if ((sec2_jnc == 1) .or. (sec2_jnc < -999998)) then\n       jst = 1\n       jen = size(lbm,2)\n       jnc = 1\n    elseif (sec2_jnc == -1) then\n       jst = size(lbm,2)\n       jen = 1\n       jnc = -1\n    endif\n\n    if ((sec2_scm == 0) .or. (sec2_scm < -999998)) then\n\n       do j = jst, jen, jnc\n          do i = ist, ien, inc\n             if (lbm(i,j)) then\n                lbm(i,j) = .TRUE.\n                call sbenc(newsec3, 1, 1, iskip, 1)\n             else\n                lbm(i,j) = .FALSE.\n                call sbenc(newsec3, 0, 0, iskip, 1)\n             endif\n          enddo\n       enddo\n\n    else if (sec2_scm == 1) then\n\n       do i = ist, ien, inc\n          do j = jst, jen, jnc\n             if (lbm(i,j)) then\n                lbm(i,j) = .TRUE.\n                call sbenc(newsec3, 1, 1, iskip, 1)\n             else\n                lbm(i,j) = .FALSE.\n                call sbenc(newsec3, 0, 0, iskip, 1)\n             endif\n          enddo\n       enddo\n\n    endif\n\n  end subroutine gribsec3_create\n\n  subroutine gribsec2_set(grid_type, nx, ny, la1, lo1, la2, lo2, &\n       resolution_and_component, lov, dx, dy, projection_center_flag, &\n       i_scanning_increment, j_scanning_increment, scanning_mode, truelat1, &\n       truelat2)\n    implicit none\n    integer, intent(in), optional :: grid_type\n    integer, intent(in), optional :: nx\n    integer, intent(in), optional :: ny\n    real,    intent(in), optional :: la1\n    real,    intent(in), optional :: lo1\n    real,    intent(in), optional :: la2\n    real,    intent(in), optional :: lo2\n    integer, intent(in), optional :: resolution_and_component\n    real,    intent(in), optional :: lov\n    real,    intent(in), optional :: dx\n    real,    intent(in), optional :: dy\n    real,    intent(in), optional :: truelat1\n    real,    intent(in), optional :: truelat2\n    integer, intent(in), optional :: projection_center_flag\n    integer, intent(in), optional :: i_scanning_increment\n    integer, intent(in), optional :: j_scanning_increment\n    integer, intent(in), optional :: scanning_mode\n\n    if (present(grid_type))then\n       select case(grid_type)\n       case (0,5)\n          sec2_size = 32\n          allocate(newsec2((sec2_size+3)/4))\n          newsec2 = 0\n       case (1,3)\n          sec2_size = 42\n          allocate(newsec2((sec2_size+3)/4))\n          newsec2 = 0\n       case default\n          print*, 'grid_type = ', grid_type\n          stop \"Unrecognized grid type in GRIBSEC2_SET\"\n       end select\n\n       sec2_gty = grid_type\n       call gribsec1_set(isthere_gds=1)\n    endif\n\n    if (present(nx)) sec2_nxp = nx\n    if (present(ny)) sec2_nyp = ny\n\n    if (present(la1))then\n       if ((la1 > 90.0) .or. (la1 < -90.0)) then\n          write(*,'(\" ***** Latitude problem (la1): \", F20.10)') la1\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (la1 < 0) then\n          sec2_la1 = (2**23) - nint(la1 * 1.E3)\n       else\n          sec2_la1 = nint(la1 * 1.E3)\n       endif\n    endif\n\n    if (present(lo1)) then\n       if ((lo1 > 360.0) .or. (lo1 < -360.0)) then\n          write(*,'(\" ***** Longitude problem (lo1): \", F20.10)') lo1\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (lo1 < 0) then\n          sec2_lo1 = (2**23) - nint(lo1 * 1.E3)\n       else\n          sec2_lo1 = nint(lo1 * 1.E3)\n       endif\n    endif\n    if (present(la2)) then\n       if ((la2 > 90.0) .or. (la2 < -90.0)) then\n          write(*,'(\" ***** Latitude problem (la2): \", F20.10)') la2\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (la2 < 0) then\n          sec2_la2 = (2**23) - nint(la2 * 1.E3)\n       else\n          sec2_la2 = nint(la2*1.E3)\n       endif\n    endif\n    if (present(lo2)) then\n       if ((lo2 > 360.0) .or. (lo2 < -360.0)) then\n          write(*,'(\" ***** Longitude problem (lo2): \", F20.10)') lo2\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (lo2 < 0) then\n          sec2_lo2 = (2**23) - nint(lo2*1.E3)\n       else\n          sec2_lo2 = nint(lo2*1.E3)\n       endif\n    endif\n\n    if (present(resolution_and_component)) sec2_rac = resolution_and_component\n\n    if (present(lov)) then\n       if ((lov > 360.0) .or. (lov < -360.0)) then\n          write(*,'(\" ***** Longitude problem (lov): \", F20.10)') lov\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (lov < 0) then\n          sec2_lov = (2**23) - nint(lov*1.E3)\n       else\n          sec2_lov = nint(lov*1.E3)\n       endif\n    endif\n    if (present(dx)) then\n       sec2_dxt = nint(dx*1.E3)\n!       print*,' sec2_dxt = ', sec2_dxt\n    endif\n    if (present(dy)) then\n       sec2_dyt = nint(dy*1.E3)\n!       print*,' sec2_dyt = ', sec2_dyt\n    endif\n    if (present(truelat1)) then\n       if ((truelat1 > 90.0) .or. (truelat1 < -90.0)) then\n          write(*,'(\" ***** Latitude problem (truelat1): \", F20.10)') truelat1\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (truelat1 < 0) then\n          sec2_tr1 = (2**23) - nint(truelat1*1.E3)\n       else\n          sec2_tr1 = nint(truelat1*1.E3)\n       endif\n    endif\n    if (present(truelat2)) then\n       if ((truelat2 > 90.0) .or. (truelat2 < -90.0)) then\n          write(*,'(\" ***** Latitude problem (truelat2): \", F20.10)') truelat2\n          stop \"GRIBSEC2_SET\"\n       endif\n       if (truelat2 < 0) then\n          sec2_tr2 = (2**23) - nint(truelat2*1.E3)\n       else\n          sec2_tr2 = nint(truelat2*1.E3)\n       endif\n       sec2_spl = (2**23) - (-90000)\n    endif\n\n    if (present(projection_center_flag)) then\n       if ((projection_center_flag < 0) .or. (projection_center_flag > 1)) then\n          write(*, '(/,\"***** FATAL ERROR.  Invalid input to GRIBSEC2_SET\")')\n          write(*, '(\"***** PROJECTION_CENTER_FLAG must be 0 or 1.  Found: \",I12)') &\n               projection_center_flag\n          stop \"***** GRIBSEC2_SET\"\n       endif\n       sec2_pcf = projection_center_flag*128\n    endif\n\n    if (present(i_scanning_increment)) then\n       if(abs(i_scanning_increment) /= 1) then\n          write(*, '(/,\"***** FATAL ERROR.  Invalid input to GRIBSEC2_SET\")')\n          write(*, '(\"***** I_SCANNING_INCREMENT must be +/- 1.  Found: \",I12)') &\n               i_scanning_increment\n          stop \"***** GRIBSEC2_SET\"\n       endif\n       sec2_inc = i_scanning_increment\n    endif\n\n    if (present(j_scanning_increment)) then\n       if(abs(j_scanning_increment) /= 1) then\n          write(*, '(/,\"***** FATAL ERROR.  Invalid input to GRIBSEC2_SET\")')\n          write(*, '(\"***** J_SCANNING_INCREMENT must be +/- 1.  Found: \",I12)') &\n               j_scanning_increment\n          stop \"***** GRIBSEC2_SET\"\n       endif\n       sec2_jnc = j_scanning_increment\n    endif\n\n    if (present(scanning_mode))then\n       if ((scanning_mode < 0) .or. (scanning_mode > 1)) then\n          write(*, '(/,\"***** FATAL ERROR.  Invalid input to GRIBSEC2_SET\")')\n          write(*,'(\"***** SCANNING_MODE must be 0 or 1.  Found: \",I12)') scanning_mode\n          stop \"***** GRIBSEC2_SET\"\n       endif\n       sec2_scm = scanning_mode\n    endif\n\n  end subroutine gribsec2_set\n\n  subroutine gribsec2_pack()\n    implicit none\n    integer :: smf\n    integer :: iskip\n    iskip = 0\n    call sbenc(newsec2, sec2_size,  sec2_size, iskip, 24)\n    call sbenc(newsec2,        0,   0, iskip, 8)\n    call sbenc(newsec2,      255, 255, iskip, 8)\n    call sbenc(newsec2, sec2_gty, 255, iskip, 8)\n\n    smf = 0\n    if (sec2_inc == -1) smf = smf + 128\n    if ((sec2_jnc ==  1) .or. (sec2_jnc < -999998)) smf = smf + 64\n    if (sec2_scm == 1) smf = smf + 32\n\n    select case (sec2_gty)\n    case (0) ! Cylindrical Equidistant\n\n       call sbenc(newsec2, sec2_nxp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_nyp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_la1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_rac, 8, iskip, 8)\n       call sbenc(newsec2, sec2_la2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dxt, 0, iskip, 16)\n       call sbenc(newsec2, sec2_dyt, sec2_dxt, iskip, 16)\n       call sbenc(newsec2, smf,      0, iskip, 8)\n\n    case (1) ! Mercator\n       call sbenc(newsec2, sec2_nxp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_nyp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_la1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_rac, 8, iskip, 8)\n       call sbenc(newsec2, sec2_la2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_tr1, 0, iskip, 24)\n       call sbenc(newsec2, 0,      0, iskip, 8)\n       call sbenc(newsec2, smf,      0, iskip, 8)\n       call sbenc(newsec2, sec2_dxt, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dyt, sec2_dxt, iskip, 24)\n\n    case (3) ! Lambert Conformal\n       call sbenc(newsec2, sec2_nxp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_nyp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_la1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_rac, 8, iskip, 8)\n       call sbenc(newsec2, sec2_lov, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dxt, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dyt, sec2_dxt, iskip, 24)\n       call sbenc(newsec2, sec2_pcf, 0, iskip, 8)\n       call sbenc(newsec2, smf,      0, iskip, 8)\n       call sbenc(newsec2, sec2_tr1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_tr2, 0, iskip, 24)\n       call sbenc(newsec2, sec2_spl, 0, iskip, 24)\n       call sbenc(newsec2, 0, 0, iskip, 24)\n\n\n    case (5) ! Polar Stereographic\n\n       call sbenc(newsec2, sec2_nxp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_nyp, 0, iskip, 16)\n       call sbenc(newsec2, sec2_la1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_lo1, 0, iskip, 24)\n       call sbenc(newsec2, sec2_rac, 8, iskip, 8)\n       call sbenc(newsec2, sec2_lov, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dxt, 0, iskip, 24)\n       call sbenc(newsec2, sec2_dyt, sec2_dxt, iskip, 24)\n       call sbenc(newsec2, sec2_pcf, 0, iskip, 8)\n       call sbenc(newsec2, smf,      0, iskip, 8)\n    case default\n       write(*, '(\"sec2_gty = \", I12)') sec2_gty\n       stop \"Unrecognized grid type in GRIBSEC2_PACK\"\n    end select\n\n  end subroutine gribsec2_pack\n\n\n\n  subroutine gribsec4_set(binary_scale_factor, reference_value_A, reference_value_B, &\n       reference_value_sign, nbits)\n    implicit none\n    integer, optional, intent(in) :: binary_scale_factor, nbits, reference_value_A, &\n         reference_value_B, reference_value_sign\n\n    if (present(binary_scale_factor)) sec4_bsf = binary_scale_factor\n    if (present(reference_value_A))   sec4_rfa = reference_value_A\n    if (present(reference_value_B))   sec4_rfb = reference_value_B\n    if (present(reference_value_sign))sec4_rfs = reference_value_sign\n    if (present(nbits))               sec4_nbt = nbits\n  end subroutine gribsec4_set\n\n  subroutine gribsec4_pack\n    implicit none\n    integer :: iskip, numunused, bmod, i, j, ist, ien, inc, jst, jen, jnc\n\n    if (sec4_nbt == 0) then\n       ! We have a constant field.  Zero bits needed (sec4_nbt==0)\n       ! to pack each datum.\n       sec4_size = 12\n       allocate(newsec4((sec4_size+3)/4))\n       newsec4 = 0\n       iskip = 0\n       call sbenc(newsec4, sec4_size, -999999, iskip, 24) ! Bytes 1-3\n       call sbenc(newsec4, 0, 0, iskip, 4)                ! Byte 4, bits 1-4\n       call sbenc(newsec4, 8, 0, iskip, 4)                ! Byte 4, bits 5-8\n       call sbenc(newsec4, sec4_bsf, 0, iskip, 16)        ! Bytes 5-6\n\n       if (sec4_rfs == -1) then                          ! Byte 7...\n          call sbenc(newsec4, 1, 0, iskip, 1)\n       elseif (sec4_rfs == 1) then\n          call sbenc(newsec4, 0, 0, iskip, 1)\n       else\n          print*, \"SEC4_RFS (Reference value sign) = \", sec4_rfs\n          stop\n       endif\n       call sbenc(newsec4, sec4_rfa, 0, iskip, 7)\n\n       call sbenc(newsec4, sec4_rfb, 0, iskip, 24)        ! Bytes 8-10\n       call sbenc(newsec4, 0, 0, iskip, 8)                ! Byte 11\n       call sbenc(newsec4, 0, 0, iskip, 8)                ! Byte 12\n\n       if (sec1_bms == 1) then\n\n          ! We have a constant field with a bitmask\n\n          call gribsec3_create()\n\n          bmod = mod(nummappt*sec4_nbt, 8)\n          if (bmod == 0) then\n             numunused = 0\n          else\n             numunused = 8 - bmod\n          endif\n\n          sec4_size = ((nummappt*sec4_nbt)+numunused) / 8 + 11\n          if (mod(sec4_size,2)/=0) then\n             sec4_size = sec4_size + 1\n             numunused = numunused + 8\n          endif\n          if (mod(((nummappt*sec4_nbt)+numunused),16) /= 8) then\n             print*, 'nummappt = ', nummappt\n             print*, 'sec4_nbt = ', sec4_nbt\n             print*, 'sec4_size = ', sec4_size\n             print*, 'numunused = ', numunused\n             stop \"Problem A\"\n          endif\n       endif\n\n       return\n    endif\n\n    ! There must be an even number of bytes.\n\n    if (sec1_bms == 1) then\n\n       call gribsec3_create()\n\n       bmod = mod(nummappt*sec4_nbt, 8)\n       if (bmod == 0) then\n          numunused = 0\n       else\n          numunused = 8 - bmod\n       endif\n\n       sec4_size = ((nummappt*sec4_nbt)+numunused) / 8 + 11\n       if (mod(sec4_size,2)/=0) then\n          sec4_size = sec4_size + 1\n          numunused = numunused + 8\n       endif\n       if (mod(((nummappt*sec4_nbt)+numunused),16) /= 8) then\n          print*, 'sec4_size = ', sec4_size\n          print*, 'numunused = ', numunused\n          stop \"Problem A\"\n       endif\n\n    else\n\n       bmod = mod(size(gribiarr)*sec4_nbt, 8)\n       if (bmod == 0) then\n          numunused = 0\n       else\n          numunused = 8 - bmod\n       endif\n       sec4_size = (size(gribiarr)*sec4_nbt+numunused) / 8 + 11\n\n       if (mod(sec4_size,2) /= 0) then\n          sec4_size = sec4_size + 1\n          numunused = numunused + 8\n       endif\n\n       if (mod(((size(gribiarr)*sec4_nbt)+numunused),16) /= 8) then\n          print*, 'numused = ', size(gribiarr)*sec4_nbt\n          print*, 'sec4_size = ', sec4_size\n          print*, 'numunused = ', numunused\n          stop \"Problem B\"\n       endif\n\n    endif\n\n    allocate(newsec4((sec4_size+3)/4))\n    newsec4 = 0\n    iskip = 0\n    call sbenc(newsec4, sec4_size, -999999, iskip, 24)   ! Bytes 1-3\n    call sbenc(newsec4, 0, 0, iskip, 4)                  ! Byte 4, bits 1-4\n    call sbenc(newsec4, numunused, 0, iskip, 4)          ! Byte 4, bits 5-8\n    call sbenc(newsec4, sec4_bsf, 0, iskip, 16)          ! Bytes 5-6\n\n    if (sec4_rfs == -1) then                          ! Byte 7...\n       call sbenc(newsec4, 1, 0, iskip, 1)\n    elseif (sec4_rfs == 1) then\n       call sbenc(newsec4, 0, 0, iskip, 1)\n    else\n       print*, \"SEC4_RFS (Reference value sign) = \", sec4_rfs\n       stop\n    endif\n\n    call sbenc(newsec4, sec4_rfa, 0, iskip, 7)\n\n    call sbenc(newsec4, sec4_rfb, 0, iskip, 24) ! Bytes 8-10\n    call sbenc(newsec4, sec4_nbt, 0, iskip, 8)\n\n    if ((sec2_inc == 1) .or. (sec2_inc < -999998)) then\n       ist = 1\n       ien = size(gribiarr,1)\n       inc = 1\n    elseif (sec2_inc == -1) then\n       ist = size(gribiarr,1)\n       ien = 1\n       inc = -1\n    endif\n\n    if ((sec2_jnc == 1) .or. (sec2_jnc < -999998)) then\n       jst = 1\n       jen = size(gribiarr,2)\n       jnc = 1\n    elseif (sec2_jnc == -1) then\n       jst = size(gribiarr,2)\n       jen = 1\n       jnc = -1\n    endif\n\n    if (sec1_bms == 1) then\n       call loop_bitmapped(gribiarr,size(gribiarr,1),size(gribiarr,2), &\n            ist,ien,inc,jst,jen,jnc,iskip)\n    else\n       call loop_not_bitmapped(gribiarr,size(gribiarr,1),size(gribiarr,2), &\n            ist,ien,inc,jst,jen,jnc,iskip)\n    endif\n\n\n    do i = 1, numunused\n       call sbenc(newsec4, 0, 0, iskip, 1)\n    enddo\n\n  end subroutine gribsec4_pack\n\n  subroutine loop_bitmapped(iarr,ix,jx,ist,ien,inc,jst,jen,jnc,iskip)\n    implicit none\n    integer, intent(in) :: ist,ien,inc,jst,jen,jnc,ix,jx\n    integer, dimension(ix,jx), intent(in) :: iarr\n    integer, intent(inout) :: iskip\n    integer :: i, j\n\n    if ((sec2_scm == 0) .or. (sec2_scm < -999998)) then\n\n       do j = jst, jen, jnc\n          do i = ist, ien, inc\n             if (lbm(i,j)) then\n                call sbenc(newsec4, iarr(i,j), -999999, iskip, sec4_nbt)\n             endif\n          enddo\n       enddo\n\n    else if (sec2_scm == 1) then\n\n       do i = ist, ien, inc\n          do j = jst, jen, jnc\n             if (lbm(i,j)) then\n                call sbenc(newsec4, iarr(i,j), -999999, iskip, sec4_nbt)\n             endif\n          enddo\n       enddo\n\n    endif\n\n  end subroutine loop_bitmapped\n\n  subroutine loop_not_bitmapped(iarr,ix,jx,ist,ien,inc,jst,jen,jnc,iskip)\n    integer, intent(in) :: ist,ien,inc,jst,jen,jnc,ix,jx\n    integer, dimension(ix,jx), intent(in) :: iarr\n    integer, intent(inout) :: iskip\n    integer :: i, j\n\n    if ((sec2_scm == 0) .or. (sec2_scm < -999998)) then\n\n       do j = jst, jen, jnc\n          do i = ist, ien, inc\n             call sbenc(newsec4, iarr(i,j), -999999, iskip, sec4_nbt)\n          enddo\n       enddo\n\n    else if (sec2_scm == 1) then\n\n       do i = ist, ien, inc\n          do j = jst, jen, jnc\n             call sbenc(newsec4, iarr(i,j), -999999, iskip, sec4_nbt)\n          enddo\n       enddo\n\n    endif\n\n  end subroutine loop_not_bitmapped\n\n  subroutine packarray(input_array, ix, jx, sigdig, eps, &\n       bitmap)\n!\n! Given a floating-point array input_array, returns an integer array gribiarr\n! which represents integer values ready for packing into the GRIB\n! record.\n!\n    implicit none\n    integer,                   intent(in)  :: ix, jx\n    real, dimension(ix,jx),    intent(in)  :: input_array\n    integer, optional,         intent(in)  :: sigdig\n    real,    optional,         intent(in)  :: eps\n    logical, dimension(ix,jx), intent(in), optional :: bitmap\n! Local:\n    integer :: npb\n    integer :: Binary_Scale_Factor\n    integer :: Decimal_Scale_Factor\n    integer :: reference_value_A\n    integer :: reference_value_B\n    integer :: reference_value_sign\n    real :: xmax, xbmax, xrange, xval\n    real :: xmin, dsmin\n    real :: dsmax, bsmax, bsmin, testdiff, tnt\n    integer :: idcflog\n    real :: maxn\n    real :: lval\n    double precision, allocatable, dimension(:) :: arr\n    double precision :: dval\n    integer :: nval, BetterD, BetterE\n    real :: eval, rval\n    logical :: invb\n    integer :: i, j, iia, jja\n\n    real,    allocatable, dimension(:) :: xarr\n    integer, allocatable, dimension(:) :: iarr\n\n    if (present(sigdig) .and. present(eps)) then\n       write(*,'(\"PACKARRAY: Either SIGDIG or EPS must be provided.\")')\n       write(*,'(\"                         You have provided both.\")')\n       stop \"ENGRIB_MODULE : PACKARRAY\"\n    endif\n\n    if (.not.(present(sigdig)) .and. .not.(present(eps))) then\n       write(*,'(\"PACKARRAY: Either SIGDIG or EPS must be provided.\")')\n       write(*,'(\"                         You have provided neither.\")')\n       stop \"ENGRIB_MODULE : PACKARRAY\"\n    endif\n\n    ! Pack into the vector xarr the desired elements of the 2d input_array.\n    if (present(bitmap)) then\n       ! print*, 'count(bitmap) = ', count(bitmap)\n       if (count(bitmap) > 0) then\n          if (count(bitmap) == ix*jx) then\n             ! the provided bitmap includes all points in the field.  Effectively, no bitmap.\n             allocate(xarr(ix*jx))\n             xarr = reshape(input_array, (/ix*jx/))\n          else if (count(bitmap) < ix*jx) then\n             allocate(xarr(count(bitmap)))\n             xarr = pack(input_array, bitmap)\n          else\n             stop \"bitmap confusion\"\n          endif\n       else\n          allocate(xarr(1))\n          xarr = 0.\n       endif\n    else\n       allocate(xarr(ix*jx))\n       xarr = reshape(input_array, (/ix*jx/))\n    endif\n\n    ! Clear out the space for a new grib record.\n    call grib_clear\n\n    call gribsec2_set(nx = ix)\n    call gribsec2_set(ny = jx)\n\n! Copy the bitmask\n    if (present(bitmap)) then\n       if (count(bitmap) < ix*jx) then\n          allocate(lbm(ix,jx))\n          lbm = bitmap\n          nummappt = count(lbm)\n          call gribsec1_set(isthere_bms = 1)\n       endif\n    endif\n\n! Copy the original data into a work array\n\n    allocate(iarr(size(xarr)))\n    allocate(arr(size(xarr)))\n    allocate(gribiarr(ix,jx))\n\n    arr = dble(xarr)\n\n! Get the min and max of the original data\n    xmin = minval(xarr)\n    xmax = maxval(xarr)\n\n    ! print*, 'xmin, xmax = ', xmin, xmax\n\n! Find a decimal scale factor D, such that, when the original data (which is\n! assumed to now be in the proper GRIB-recognized, i.e., mostly SI, units) is\n! multiplied by 10**D, the integer part of the result will have enough\n! precision to contain the appropriate information.\n\n    if (present(sigdig)) then\n       if ((xmin == 0.0) .and. (xmax == 0.0)) then\n          Decimal_Scale_Factor = 0.0\n       else\n          Decimal_Scale_Factor = sigdig-(ceiling(log10(max(abs(xmin),abs(xmax)))))\n       endif\n    endif\n    if (present(eps)) then\n       Decimal_Scale_Factor = -1 + log10(1./eps) ! 1 + log10(1./eps)\n       ! print*, 'eps = ', eps\n       ! print*, 'log10(1./eps) = ', log10(1./eps)\n       ! print*, 'Decimal Scale Factor = ', decimal_scale_factor\n    endif\n\n100 continue\n    if (present(eps)) then\n       testdiff = 1.E33\n       do while ( testdiff > eps )\n          Decimal_Scale_Factor = Decimal_Scale_Factor + 1\n          ! print*, 'Decimal_Scale_Factor = ', Decimal_Scale_Factor\n          arr = dble(xarr) * (10.D0**decimal_scale_factor)\n          ! Try a quick comparison between original array (input_array) and work array\n          testdiff = maxval(abs(((int(arr))*(10.0**(-Decimal_Scale_Factor))) - xarr))\n          ! print*, 'testdiff = ', testdiff\n       enddo\n    endif\n\n    if (present(sigdig)) then\n       arr = dble(xarr) * (10.D0**decimal_scale_factor)\n    endif\n\n! Build the reference value integers:\n! The reference value is simply the minimum of the decimal-scaled values.\n\n    ! Find the decimal-scaled xmin and xmax\n    dsmin = minval(arr)\n    dsmax = maxval(arr)\n\n    if (present(bitmap)) then\n       if (count(bitmap) == 0) then\n          ! Everything is masked out.  Nothing to encode.\n          call gribsec1_set(isthere_bms = 0)\n          Binary_Scale_Factor = 0\n          gribiarr = 0\n          call find_pack_ref_val(dsmin, Reference_Value_A, Reference_Value_B, Reference_Value_Sign, rval)\n\n          call gribsec4_set(binary_scale_factor = 0)\n          call gribsec4_set(reference_value_A = reference_value_A)\n          call gribsec4_set(reference_value_B = reference_value_B)\n          call gribsec4_set(reference_value_Sign = reference_value_Sign)\n          call gribsec4_set(nbits = 0)\n          call gribsec1_set(decimal_scale_factor = Decimal_Scale_Factor)\n          return\n       endif\n    endif\n\n    call find_pack_ref_val(dsmin, Reference_Value_A, Reference_Value_B, Reference_Value_Sign, rval)\n\n! Subtract off the Reference Value:\n    arr = arr - rval\n\n! Find a maximum of the new arr\n    maxn = maxval(arr)\n\n! We'll not use binary scaling for now.\n\n    ! Number of bits needed for packing depends on the maximum value:\n    lval = (log10(maxn+1)/log10(2.0))\n    npb = ceiling(abs(lval))\n    Binary_Scale_Factor = 0\n\n!KWM! Find a better D and E, perhaps, for a given arrmax and a given number\n!KWM! of bits.\n!KWM    call better_D_and_E(npb, real(xmax-xmin), BetterD, BetterE, Decimal_Scale_Factor, Binary_Scale_Factor)\n!KWM\n!KWM    print*, 'Original D, E: ', Decimal_Scale_Factor, Binary_Scale_Factor\n!KWM    print*, 'Better   D, E: ', BetterD, BetterE\n\n    iarr = nint(arr) ! Do we want \"INT\" or \"NINT\" ?\n\n    ! Double check that IARR is all non-negative\n    do i = 1, size(iarr)\n       if (iarr(i) < 0) then\n          print*,' i, ', i, arr(i), int(arr(i))\n          stop \"PACKARRAY problem\"\n       endif\n    enddo\n\n    dval = 1.0D1**(-Decimal_Scale_Factor)\n!  eval = 2.**Binary_Scale_Factor\n    eval = 1.0\n\n! one final test\n    testdiff = maxval(abs(((rval+dble(iarr)*eval)*dval)-xarr))\n    if (present(eps)) then\n       if (testdiff > eps) then\n          print*, '      Trying again:', testdiff, eps\n          Decimal_Scale_Factor = Decimal_Scale_Factor + 1\n          goto 100\n       endif\n    endif\n\n! Find the maximum difference between the original data and the\n! unpacking of the packed data.\n    testdiff = maxval(abs(((rval+dble(iarr)*eval)*dval)-xarr))\n    ! print*, '     Maximum abs(value), difference = ', xmax, testdiff\n\n    call gribsec1_set(decimal_scale_factor = Decimal_Scale_Factor)\n    call gribsec4_set(binary_scale_factor = binary_scale_factor)\n    call gribsec4_set(reference_value_A = reference_value_A)\n    call gribsec4_set(reference_value_B = reference_value_B)\n    call gribsec4_set(reference_value_Sign = reference_value_Sign)\n    call gribsec4_set(nbits = npb)\n!    write(*, '(5x,\"DSF NB MAX = \",2I4,2I12, 1P, 2E14.4, 0P)') &\n!         Decimal_Scale_Factor, npb, eps, testdiff\n\n    ! And finally, unpack IARR into GRIBIARR\n    if (present(bitmap)) then\n       if (count(bitmap) < ix*jx) then\n          gribiarr = unpack(iarr, bitmap, -9999999)\n       else\n          gribiarr = reshape ( iarr, (/ ix , jx /) )\n       endif\n    else\n       gribiarr = reshape ( iarr, (/ ix , jx /) )\n    endif\n\n  end subroutine packarray\n\n  subroutine better_D_and_E(npb, maxn, BetterD, BetterE, OrigD, OrigE)\n    implicit none\n    integer, intent(in)  :: npb\n    real   , intent(in)  :: maxn\n    integer, intent(in)  :: OrigD, OrigE\n    integer, intent(out) :: BetterD, BetterE\n\n    real :: m, tsave, xd, xm\n    integer :: D, E, Dsave, Esave\n    logical :: found\n\n\n    tsave = 1.E35\n    found = .FALSE.\n    m = log10(((2.0**npb)-1)/maxn)\n    ! For a given M and a variety of E values, find D and take an int.\n\n    do E = -10, 10\n       xd = m + float(E)*log10(2.0)\n       D = floor(xd)\n       xm = float(D) - float(E)*log10(2.0)\n\n       ! xm should be <= m\n       if (xm > m) then\n          print*, 'xd, D = ', xd, D\n          stop \"problem:  XM > M\"\n       endif\n\n       ! Save D and E values where m-xm is minimized\n       if ((m-xm)<tsave) then\n          found  = .TRUE.\n          Esave = E\n          Dsave = D\n          tsave = (m-xm)\n       endif\n\n    enddo\n\n    if (found) then\n       BetterD = D\n       BetterE = E\n    else\n       print*, 'Better D and E not found'\n       BetterD = OrigD\n       BetterE = OrigE\n    endif\n\n  end subroutine better_D_and_E\n\n\n  subroutine find_pack_ref_val(x, a, b, isign, rval)\n    ! Find the A and B parameters of the grib reference value xmin.\n    implicit none\n    real,    intent(in)  :: x\n    integer, intent(out) :: a, b, isign\n    real,    intent(out) :: rval\n\n    real :: y, s\n    integer :: e\n\n    if (x==0) then\n       a = 0\n       b = 0\n       isign = 1\n       rval = 0.\n       return\n    endif\n\n    y = abs(x)\n    s = sign(1.0, x)\n    e = exponent(y)\n    isign = int(s)\n\n    b = int(scale(fraction(y), 24+mod(e+128,4)))\n    a = ((e-mod(e+128,4))/4) + 64\n\n    rval = s * ((2.0**(-24)) *b ) * (16.0**(a-64))\n\n! Check for exact floating-point values.  Pretty stringent\n! and probably not terribly portable, but that's life.\n    if (rval /= x) then\n       print*, 'A and B not quite right: a,b=',a,b\n       print*, 'rval = ', rval\n       print*, 'x = ', x\n       stop \"FIND_PACK_REF_VAL\"\n    endif\n\n! B must fit into 24 bits (3 bytes)\n! A must fit into  7 bits\n    do while (b > 16777216)\n       a = a + 1\n\n       if (a > 127) then\n          print*, 'Having trouble packing reference value.'\n          stop \"FIND_PACK_REF_VAL\"\n       endif\n\n       if (isign > 0) then\n          b = b / 16\n       else\n          b = (b+15)/16\n       endif\n       rval = s * ((2.0**(-24)) *b ) * (16.0**(a-64))\n       if (rval > x) then\n          print*, 'rval > x:', rval, x\n          stop \"FIND_PACK_REF_VAL\"\n       endif\n    enddo\n\n  end subroutine find_pack_ref_val\n\nend module engrib_module_test\n\nPROGRAM  sw_to_grib\n  use engrib_module_test\n  use module_date_utilities\n  implicit none\n!\n!       This is an example Fortran program to read the GCIP/SRB archive\n!       of current instantaneous fluxes for a particular day.  It reads\n!       the data for an observation time by looping over the 51 latitude\n!       bands one at a time, and in each pass through the loop, reading\n!       data for the 111 longitude bands, and then proceeding to the\n!       next time.\n!\n!       The program also assigns latitude and longitude coordinates to\n!       the cell-centers, and gives an example of how to obtain the\n!       nominal time of an observation.\n!\n!       NOTE: Northern latitudes are positive, western longitudes are\n!             negative.\n!\n!  VARIABLES:\n!     Fluxi(Lon,Lat,Hour) : Lon=1 to Nlon, Lat=1 to Nlat; Hour=1 to\n!                                  Nhours; instantaneous flux (W/m**2)\n!     Glat(Lat)  : Lat=1 to Nlat; latitude of cell center\n!     Glon(Lon)  : Lon=1 to Nlon; longitude of cell center\n!     Hour       : hour of the day (0-23)\n!     Lat1       : latitude of center of first cell (degrees)\n!     Lon1       : longitude of center of first cell (degrees)\n!     Lrec       : record length\n!     Minute     : minutes; satellite observation is Minute minutes\n!                   after the hour\n!     Nhours     : no. of hours in a day\n!     Nlat       : max no. of latitudes\n!     Nlon       : max no. of longitudes\n!     Reslat     : resolution in latitude (degrees)\n!     Reslon     : resolution in longitude (degrees)\n!     Time       : nominal time (UTC) of satellite observation (hours)\n\n\n  integer :: Nlat\n  integer :: Nlon\n  real    :: Lat1\n  real    :: Lon1\n!     .. Parameters ..\n  integer, parameter :: Nhours = 24\n  real   , parameter :: Reslat = 0.5\n  real   , parameter :: Reslon = 0.5\n  integer, parameter :: Minute = 15\n  integer :: additional_time_offset\n\n  integer, external :: iargc\n\n!     ..\n!     .. Local Scalars ..\n  CHARACTER(len=120) :: Fname\n  INTEGER  :: Hour,  Lat, Lon\n  REAL  :: Time\n  integer :: ierr\n!     ..\n!     .. Local Arrays ..\n  REAL, allocatable, dimension(:, :, :) :: Fluxi\n  real, allocatable, dimension(:)       :: Glat\n  real, allocatable, dimension(:)       :: Glon\n  REAL, allocatable, dimension(:, :)    :: tmp\n\n!     ..\n  character(len=24) :: hdate, newdate\n  integer :: indxs\n  integer :: icount\n  integer :: gribunit\n\n! Get name of GCIP/SRB file to be read from command-line.\n!\n  if (iargc() < 1) then\n     print*, 'Program expects a command-line argument.'\n     write(*, '(/,\"***** ERROR EXIT *****\",/)')\n     stop\n  endif\n  call getarg(1, Fname)\n\n  indxs = index(trim(Fname),\"/\",.TRUE.)\n  hdate = \"2000-00-00_00:00:00.0000\"\n  hdate(3:4)  = Fname(indxs+1:indxs+2) ! yy\n  hdate(6:7)  = Fname(indxs+3:indxs+4) ! mm\n\n  print*, 'hdate = ', hdate\n  print*, 'nmdays = ', nmdays(hdate)\n  DAYLOOP : do icount = 1, nmdays(hdate)\n     ! print*, 'DAYLOOP: icount = ', icount\n\n! This one expect 1-month files, named according to <yymm>sda.i\n     hdate = \"2000-00-00_00:00:00.0000\"\n     indxs = index(trim(Fname),\"/\",.TRUE.)\n     hdate(3:4)  = Fname(indxs+1:indxs+2) ! yy\n     hdate(6:7)  = Fname(indxs+3:indxs+4) ! mm\n     write(hdate(9:10), '(I2.2)') icount\n     if ( hdate(1:4) > \"2050\" ) hdate(1:2) = \"19\"\n\n     print*, 'Hdate = ', Hdate\n\n     if (hdate(1:7) < \"2001-07\") then\n        NLat = 51\n        NLon = 111\n        Lat1 = 25.0\n        Lon1 = -125.0\n     else\n        NLat = 61\n        NLon = 121\n        Lat1 = 24.0\n        Lon1 = -126.0\n     endif\n\n     if (icount == 1) then\n        allocate(Fluxi(Nlon, Nlat, Nhours))\n        allocate(Glat(Nlat))\n        allocate(Glon(Nlon))\n     endif\n     Fluxi = 0.\n\n! Open and read GCIP/SRB file\n! Use c I/O routines to avoid the direct-access Fortran I/O\n\n     call getdata(Fname, Fluxi, Nlon, Nlat, Nhours, icount)\n\n!     print*, 'Minimum/Maximum Flux = ', minval(Fluxi), maxval(fluxi)\n!KWM     print*, 'Min/Max fractional part = ', minval(abs(Fluxi-int(fluxi))), &\n!KWM          maxval(abs(Fluxi-int(fluxi)))\n\n! Calculate latitude and longitude coordinates of cell centers\n!\n     if (icount == 1) then\n        DO Lat = 1, Nlat\n           Glat( Lat ) = ( Lat-1 ) * Reslat + Lat1\n        ENDDO\n        DO Lon = 1, Nlon\n           Glon( Lon ) = ( Lon-1 ) * Reslon + Lon1\n        ENDDO\n     endif\n\n!KWM     where(fluxi < -998)\n!KWM        ! fluxi = -1.E30\n!KWM        fluxi = 0\n!KWM     end where\n\n     DO Hour = 1, Nhours\n        newdate = hdate\n\n        write(*,'(\"Assuming that the SW Data offset is about 30 minutes, rather than the stated 15 minutes\")')\n        additional_time_offset = 15\n\n        call geth_newdate(newdate(1:16), hdate(1:16), (hour-1)*60+Minute+additional_time_offset)\n\n        call open_newgrib(gribunit, \"SW.\"// &\n             newdate(1:4)//newdate(6:7)//newdate(9:10)//newdate(12:13)//newdate(15:16)//\".grb\")\n        ! Write the data in GRIB format\n\n        ! Bitmask large negatives.\n        call packarray(fluxi(:,:,hour), Nlon, Nlat, eps=1.00, bitmap=(fluxi(:,:,hour)>=-100.0))\n        ! or don't bitmask:\n!        call packarray(fluxi(:,:,hour), Nlon, Nlat, eps=1.00) ! Don't bitmask\n\n        call gribsec1_set(parameter_id=204)\n        call gribsec1_set(level_type=1)\n        call gribsec1_set(level_1 = 0)\n        call gribsec1_set(hdate=newdate(1:16))\n        call gribsec1_set(P1=00)\n        call gribsec1_set(P2=00)\n        call gribsec1_set(time_unit=1)\n        call gribsec1_set(time_range_indicator=0)\n        ! Set these as particular flags to identify these GCIP SW fields:\n        call gribsec1_set(center_id=244)\n        call gribsec1_set(process_id=244)\n        call gribsec1_set(subcenter_id=244)\n\n        call gribsec2_set(grid_type=0)\n        call gribsec2_set(la1=Glat(1))\n        call gribsec2_set(lo1=Glon(1))\n        call gribsec2_set(la2=Glat(Nlat))\n        call gribsec2_set(lo2=Glon(Nlon))\n        call gribsec2_set(dx=reslon)\n        call gribsec2_set(dy=reslat)\n        !call gribsec2_set(resolution_and_component=)\n        !call gribsec2_set(scanning_mode=)\n\n        call write_grib(gribunit)\n        call close_newgrib(gribunit)\n\n     enddo\n  enddo DAYLOOP\n\nEND PROGRAM Sw_to_grib\n\nsubroutine swap4_rad(in,nn)\n! swaps bytes in groups of 4 to compensate for byte swapping within words\n!    which may occur on some machines.\n  implicit none\n  integer, intent(in) :: nn ! number of bytes to be swapped\n  character, dimension(nn) , intent(inout) :: in  ! Array to be swapped\n\n  integer, parameter :: nbytes=4\n  character, dimension(nbytes) :: ia\n  integer :: i\n  do i=1,nn,nbytes\n     ia = in(i+(nbytes-1):i:-1)\n     in(i:i+(nbytes-1)) = ia\n  enddo\nend subroutine swap4_rad\n\nsubroutine getdata(Fname, Fluxi, Nlon, Nlat, Nhours, icount)\n  implicit none\n  integer :: Nlon, Nlat, Nhours, icount\n  real, dimension(Nlon, Nlat, Nhours) :: Fluxi\n  character(len=*) :: Fname\n  integer, save :: munit\n  integer :: iread\n  integer :: ierr\n  integer :: Lrec\n  logical :: SWAPIT\n  Lrec = Nlon * Nlat * Nhours * 4\n\n! Open and read the data.\n  if (icount == 1) then\n     call copen(Munit,trim(Fname)//char(0), 1, ierr, 0)\n     if ((ierr /= 0).or.(Munit == -1)) then\n        print*, 'Error Opening.'\n        write(*, '(/,\"***** ERROR EXIT *****\",/)')\n        stop\n     else\n        print*, 'File opened: \"'//trim(Fname)//'\"'\n     endif\n  endif\n\n  call bnread(Munit, Fluxi, Lrec, iread, ierr, 10)\n  if ((ierr /= 0) .or. (iread /= Lrec)) then\n     print*, 'Error Reading.'\n     write(*, '(/,\"***** ERROR EXIT *****\",/)')\n     stop\n  endif\n\n!KWM  call cclose(Munit,0,ierr)\n!KWM  if (ierr /= 0) then\n!KWM     print*, 'Error Closing.'\n!KWM     write(*, '(/,\"***** ERROR EXIT *****\",/)')\n!KWM     stop\n!KWM  endif\n\nend subroutine getdata\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/geth_newdate.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <sys/mtio.h>\n#include <sys/ioctl.h>\n#include <sys/uio.h>\n\nint nfeb(int year);\nint geti(char *s, int p, int l);\n\nmain(int *argc, char **argv)\n{\n  char *h, *hh;\n  char *g;\n  char *k;\n  int yrold, moold, dyold, hrold, miold, scold, frold, i, j, ilen;\n  int yrnew, monew, dynew, hrnew, minew, scnew, frnew;\n  int idt;\n  int mday[12];\n\n  int ifrc;\n  int nday, nhour, nmin, nsec, nfrac;\n  char Continuous, SwapFmt;\n\n  mday[0]  = 31;\n  mday[1]  = 28;\n  mday[2]  = 31;\n  mday[3]  = 30;\n  mday[4]  = 31;\n  mday[5]  = 30;\n  mday[6]  = 31;\n  mday[7]  = 31;\n  mday[8]  = 30;\n  mday[9] = 31;\n  mday[10] = 30;\n  mday[11] = 31;\n\n  if (strncmp(\"-swap\", argv[1], 5)) {\n    SwapFmt = 0;\n    idt = atoi(argv[2]);\n    hh = argv[1];\n  }\n  else {\n    SwapFmt = 1;\n    idt = atoi(argv[3]);\n    hh = argv[2];\n  }\n\n  for (i = 0; hh[i] != '\\0'; ++i)\n    ilen = i; \n\n  yrold = 0;\n  moold = 0;\n  dyold = 0;\n  hrold = 0;\n  miold = 0;\n  scold = 0;\n  frold = 0;\n\n  /* Check the date string, to see if it is of the form YYYY-MM-DD_HH  *\n   * or of the form YYYYMMDDHH.                                        */\n  if ( hh[4] == '-' ) {\n    /* We have the form YYYY-MM-DD_HH */\n    Continuous = 0;\n    yrold = geti(hh, 0, 4);\n    moold = geti(hh, 5, 2);\n    dyold = geti(hh, 8, 2);\n    if (ilen>10) {\n      hrold = geti(hh, 11, 2);\n      if (ilen>13) {\n\tmiold = geti(hh, 14, 2);\n\tif (ilen>16) {\n\t  scold = geti(hh, 17, 2);\n\t  if (ilen>19) {\n\t    frold = geti(hh, 20, ilen-19);\n\t  }\n\t}\n      }\n    }\n  }\n  else {\n    int jadd;\n    /* We have the form YYYYMMDDHH */\n    Continuous = 1;\n    jadd = 0;\n    yrold = geti(hh, 0, 4);\n    moold = geti(hh, 4, 2);\n    jadd ++;\n    dyold = geti(hh, 6, 2);\n    jadd ++;\n    if (ilen > 8) {\n      hrold = geti(hh, 8, 2);\n      jadd ++;\n      if (ilen > 10) {\n\tmiold = geti(hh, 10,2);\n\tjadd ++;\n\tif (ilen > 12) {\n\t  scold = geti(hh, 12,2);\n\t  jadd ++;\n\t  if (ilen > 13) {\n\t    frold = geti(hh, 14,ilen-13);\n\t    jadd++;\n\t  }\n\t}\n      }\n    }\n    ilen += jadd;\n  }\n\n  mday[1] = nfeb(yrold); \n\n/*   Compute the number of days, hours, minutes, and seconds in idt */\n\n  if (ilen > 19) /*idt should be in fractions of seconds*/\n    {\n      if (ilen == 20) ifrc = 10;\n      if (ilen == 21) ifrc = 100;\n      if (ilen == 22) ifrc = 1000;\n      if (ilen == 23) ifrc = 10000;\n      nday   = abs(idt)/(86400*ifrc);\n      nhour  = div(abs(idt), 86400*ifrc).rem/(3600*ifrc);\n      nmin = div(abs(idt), 3600*ifrc).rem/(60*ifrc);\n      nsec = div(abs(idt), 60*ifrc).rem/ifrc;\n      nfrac = div(abs(idt), ifrc).rem;\n       }\n  else if (ilen > 17) /* idt should be in seconds */\n    {\n      ifrc = 1;\n      nday   = abs(idt)/86400;  /* Integer number of days in delta-time */\n      nhour = div(abs(idt), 86400).rem/3600;\n      nmin = div(abs(idt), 3600).rem/60;\n      nsec = div(abs(idt), 60).rem;\n      nfrac  = 0;\n    }\n  else if (ilen > 14) /*idt should be in minutes */\n    {\n      ifrc = 1; \n      nday   = abs(idt)/1440; /* Integer number of days in delta-time */\n      nhour = div(abs(idt), 1440).rem/60;\n      nmin = div(abs(idt), 60).rem; \n      nsec   = 0; \n      nfrac  = 0; \n    }\n  else if (ilen > 11)  /* idt should be in hours */\n    {\n      ifrc = 1;\n      nday   = abs(idt)/24; /* Integer number of days in delta-time */\n      nhour = div(abs(idt),24).rem;\n      nmin   = 0; \n      nsec   = 0;\n      nfrac  = 0;\n    }\n  else if (ilen > 8)   /* idt should be in days */\n    {\n      ifrc = 1; \n      nday   = abs(idt);  /* Integer number of days in delta-time */\n      nhour  = 0;\n      nmin   = 0; \n      nsec   = 0; \n      nfrac  = 0; \n    }\n  else\n    {\n      printf(\"Strangeness\\n\");\n      return(-1);\n    }\n\n  if (idt == 0) {\n    yrnew = yrold;\n    monew = moold;\n    dynew = dyold;\n    hrnew = hrold;\n    minew = miold; \n    scnew = scold;\n    frnew = frold;\n  }\n  else if (idt > 0) {\n\n    frnew = frold + nfrac;\n    if (frnew >= ifrc) {\n      frnew = frnew - ifrc;\n      nsec = nsec + 1;}\n\n    scnew = scold + nsec; \n    if (scnew >= 60) {\n      scnew = scnew - 60; \n      nmin  = nmin + 1;}\n\n    minew = miold + nmin; \n    if (minew >= 60) {\n      minew = minew - 60;\n      nhour  = nhour + 1;}\n\n    hrnew = hrold + nhour; \n    if (hrnew >= 24) {\n      hrnew = hrnew - 24; \n      nday  = nday + 1; }\n\n    dynew = dyold;\n    monew = moold;\n    yrnew = yrold;\n    for(i = 1; i <= nday; i++){\n      dynew = dynew + 1;\n      if (dynew > mday[monew-1]) {\n\tdynew = dynew - mday[monew-1]; \n\tmonew = monew + 1; \n\tif (monew > 12) {\n\t  monew = 1; \n\t  yrnew = yrnew + 1; \n\t  /* If the year changes, recompute the number of days in February */\n\t  mday[1] = nfeb(yrnew); }\n      }\n    }\n  }\n\n  else if (idt < 0) {\n\n    frnew = frold - nfrac; \n    if (frnew <  0) {\n      frnew = frnew + ifrc; \n      nsec = nsec - 1; }\n\n    scnew = scold - nsec; \n    if (scnew < 00) {\n      scnew = scnew + 60;\n      nmin  = nmin + 1; }\n\n    minew = miold - nmin;\n    if (minew < 00) {\n      minew = minew + 60;\n      nhour  = nhour + 1;}\n\n    hrnew = hrold - nhour; \n    if (hrnew < 00) {\n      hrnew = hrnew + 24; \n      nday  = nday + 1; }\n\n    dynew = dyold;\n    monew = moold;\n    yrnew = yrold;\n    for(i = 1; i <= nday; i++){\n      dynew = dynew - 1; \n      if (dynew == 0) {\n\tmonew = monew - 1; \n\tif (monew == 0) {\n\t  monew = 12; \n\t  yrnew = yrnew - 1; \n          /* If the year changes, recompute the number of days in February */\n\t  mday[1] = nfeb(yrnew);\n\t}\n\tdynew = mday[monew-1];\n      }\n    }\n  }\n\n  if ( (Continuous) && SwapFmt ) {\n    Continuous = 0;\n  }\n  else if ( ( ! Continuous)  && SwapFmt ) {\n    Continuous = 1;\n  }\n\n  if (ilen > 19) {\n    if (Continuous) {\n      printf(\"%4.4i%2.2i%2.2i%2.2i%2.2i%2.2i%4.4i\\n\",\n\t     yrnew, monew, dynew, hrnew, minew, scnew, frnew); \n    }\n    else {\n      printf(\"%4.4i-%2.2i-%2.2i_%2.2i:%2.2i:%2.2i.%4.4i\\n\",\n\t     yrnew, monew, dynew, hrnew, minew, scnew, frnew); \n    }\n  }\n  else if (ilen > 17) {\n    if (Continuous) {\n      printf(\"%4.4i%2.2i%2.2i%2.2i%2.2i%2.2i\\n\",\n\t     yrnew, monew, dynew, hrnew, minew, scnew); \n    }\n    else {\n      printf(\"%4.4i-%2.2i-%2.2i_%2.2i:%2.2i:%2.2i\\n\",\n\t     yrnew, monew, dynew, hrnew, minew, scnew); \n    }\n  }\n  else if (ilen > 14) {\n    if (Continuous) {\n      printf(\"%4.4i%2.2i%2.2i%2.2i%2.2i\\n\",\n\t     yrnew, monew, dynew, hrnew, minew); \n    }\n    else {\n      printf(\"%4.4i-%2.2i-%2.2i_%2.2i:%2.2i\\n\",\n\t     yrnew, monew, dynew, hrnew, minew); \n    }\n  }\n  else if (ilen > 11) {\n    if (Continuous) {\n      printf(\"%4.4i%2.2i%2.2i%2.2i\\n\",\n\t     yrnew, monew, dynew, hrnew); \n    }\n    else {\n      printf(\"%4.4i-%2.2i-%2.2i_%2.2i\\n\",\n\t     yrnew, monew, dynew, hrnew); \n    }\n  }\n  else if (ilen > 8) {\n    if (Continuous) {\n      printf(\"%4.4i%2.2i%2.2i\\n\",\n\t     yrnew, monew, dynew); \n    }\n    else {\n      printf(\"%4.4i-%2.2i-%2.2i\\n\",\n\t     yrnew, monew, dynew); \n    }\n  }\n  exit(0);\n\n}\n\nint nfeb(int year)\n{\n  int nfeb;\n\n  nfeb = 28; /* By default, February has 28 days ... */\n  if (div(year,4).rem == 0){\n    nfeb = 29;  /* But every four years, it has 29 days ... */\n    if (div(year,100).rem == 0) {\n      nfeb = 28;  /* Except every 100 years, when it has 28 days ... */\n      if (div(year,400).rem == 0){\n\tnfeb = 29;  /* Except every 400 years, when it has 29 days ... */\n\tif (div(year,3600).rem == 0){\n\t  nfeb = 28;  /* Except every 3600 years, when it has 28 days. */\n\t}\n      }\n    }\n  }\n  return(nfeb);\n}\n\nint geti(char *s, int p, int l) {\n  int i, ival;\n  ival = 0;\n  for (i=0; i<l; i++) {\n    ival = (ival*10) + s[p+i]-'0';\n  }\n  return(ival);\n}\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/gribbyte.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n\n*/\n#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <unistd.h>\n#include <string.h>\n#include <math.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n#define MIN(A,B) ((A)<(B) ? A : B)\n\n#define MAXGRIB 2000000\n\nvoid process_grib1_record();\nvoid process_grib2_record(int lengrib);\nvoid check_and_write();\n\nunsigned char ii[MAXGRIB];\nunsigned char *sec0_ptr, *sec1_ptr, *sec2_ptr, *sec3_ptr, *sec4_ptr, *sec5_ptr, *sec6_ptr, *sec7_ptr, *sec8_ptr;\nint fd;  /* Integer referring to input file. */\nunsigned int sec0_len, sec1_len, sec2_len, sec3_len, sec4_len, sec5_len, sec6_len, sec7_len, sec8_len;\n\nint secval, bytnum, bytend;\n\nchar verbose, quiet, decimal;\n\nunsigned char edition;\n  \n\nint main(int argc, char *argv[])\n{ /* main */\n  int c;\n  unsigned char hhh[8];\n  unsigned char hh[4];\n  char optstring[12] = \"vqds:h\";\n  int lengrib;\n\n  char *input_file;  /* Input file name. */\n  char *output_file; /* Output file name. */\n\n  char *usage = \"usage:\\n  %s [-help] [-v] [-q]\\n\"\\\n    \"    [-s secnum,bytnum[:bytend],bytval] <infile>\\n\\n\";\n\n  verbose = 0;\n  quiet = 1;\n  decimal = 0;\n\n  while ( (c=getopt(argc, argv, optstring)) != -1 ) {\n    switch (c){\n    case 'v':\n      verbose = 1;\n      quiet = 0;\n      break;\n    case 'q':\n      quiet = 1;\n      verbose = 0;\n      break;\n    case 'd':\n      decimal = 1;\n      break;\n    case 's':\n      {\n\tint i1, i2, i3;\n\ti1 = -9999;\n\ti2 = -9999;\n\ti3 = -9999; \n\n/* \tprintf(\"optarg = %s\\n\", optarg); */\n\t\n\tif (strchr(optarg,':')) {\n\t  sscanf(optarg, \"%d,%d:%d\", &i1, &i2, &i3);\n \t  // printf(\"i1 i2 i3= %i %i %i\\n\", i1, i2, i3);\n\t  secval = i1;\n\t  bytnum = i2;\n\t  bytend = i3;\n\t  if (bytend < bytnum) {\n\t    fprintf(stderr, \"\\n    In -s option bytend must be greater than bytnum\\n\");\n\t    fprintf(stderr, \"    -s secval,bytnum[:bytend],bytval\\n\");\n\t    fprintf(stderr, \"\\n***** Error exit *****\\n\\n\");\n\t    exit(1);\n\t  }\n\t}\n\telse {\n\t  sscanf(optarg, \"%d,%d,%d\", &i1, &i2);\n\t  secval = i1;\n\t  bytnum = i2;\n\t  bytend = bytnum;\n\t}\n      \n\tif (bytnum < 1) {\n\t  printf(\"Byte number must be greater than zero.\\n\");\n\t  exit (1);\n\t}\n\n\t// printf(\"-s %i,%i,%i\\n\", secval, bytnum, bytend);\n\tbreak;\n      }\n    case 'h':\n      {\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"**************************************************************************\\n\\n\");\n\tfprintf(stderr, \"%s -- extracts specified bytes from a GRIB-formatted file.\\n\", argv[0]);\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, usage,argv[0]); \n\tfprintf(stderr, \"where:\\n      infile  -- the GRIB-formatted file to read.\\n\");\n\tfprintf(stderr, \"      outfile -- the GRIB-formatted file to create.\\n\\n\");\n\tfprintf(stderr, \"options:\\n  -help  : print this help message and exit.\\n\\n\");\n\tfprintf(stderr, \"  -v  : more printout (verbose).\\n\\n\");\n\tfprintf(stderr, \"  -q  : less printout (quiet).\\n\\n\");\n\tfprintf(stderr, \"  -s  : extract byte at section number, byte number.\\n\");\n\tfprintf(stderr, \"        A range of byte numbers may be specified.\\n\");\n\tfprintf(stderr, \"**************************************************************************\\n\");\n\texit (-1); \n      }\n\n    default :\n      fprintf(stderr, usage, argv[0]);\n      exit (-1);\n    }\n  }\n\n  /* Check that the input file is provided as a command-line argument*/\n  input_file = argv[optind];\n  if (input_file == NULL){\n    fprintf(stderr, \"\\nInput file <infile> is a required argument.\\n\");\n    fprintf(stderr, usage, argv[0]);\n    exit (9);\n  }\n\n  /*   Open the input file for reading   */\n  if ( ! ( quiet ) ) {\n    printf(\"\\nInput file = %s\\n\", input_file);\n  }\n  fd = open(argv[optind], O_RDONLY);\n  if (fd == -1) {\n    fprintf(stderr, \"\\n ***** Problem opening input file.  abort *****\\n\");\n    fprintf(stderr, \"       File name: '%s'\\n\\n\", argv[optind]);\n    exit(-4);\n  }\n\n  while (1) {\n    hh[0] = 0;\n    /* Scan forward for a string \"GRIB\" */\n    while ( strncmp(hh, \"GRIB\", 4) != 0 ) {\n      if (read(fd, hh, 4) != 4) goto shutdown; \n      lseek(fd, -3, SEEK_CUR);\n    }\n    lseek(fd, 3, SEEK_CUR);\n\n    /*   We've found the beginning of a GRIB record, now check    */\n    /*   the GRIB edition number.  GRIB Editions 1 and 2 are      */\n    /*   acceptable.                                              */\n    \n    read(fd, hh, 4);\n    edition = hh[3];\n\n    switch (edition) {\n    case 1:\n      sec0_len = 8;\n      break;\n    case 2:\n      sec0_len = 16;\n      break;\n    default:\n      fprintf(stderr,\"Edition number unsupported:  %i\\n\", edition);\n      exit(1);\n    }\n    \n    sec1_len = 0;\n    sec2_len = 0;\n    sec3_len = 0;\n    sec4_len = 0;\n    sec5_len = 0;\n    sec6_len = 0;\n    sec7_len = 0;\n    sec8_len = 0;\n\n    /*   We've found the beginning of a GRIB record, and we know  */\n    /*   The GRIB edition number.  Now find the size of the whole */                     \n    /*   GRIB record.                                             */\n\n    switch (edition) {\n    case 1:\n      lengrib = hh[0]*65536+hh[1]*256+hh[2];\n      break;\n    case 2:\n      read(fd, hhh, 8);\n      lengrib = ((((((hhh[0]*256+hhh[1])*256+hhh[2])*256+hhh[3])*256+hhh[4])*256+hhh[5])*256+hhh[6])*256+hhh[7];\n      break;\n    }\n\n    /* rewind back to the beginning of the GRIB record */\n    lseek(fd, -sec0_len, SEEK_CUR);\n\n    if (lengrib > MAXGRIB) {\n      fprintf(stderr, \"\\n   ***** Increase MAXGRIB > %i\\n\", lengrib);\n      fprintf(stderr, \"   ***** MAXGRIB is currently set to %i\\n\\n\", MAXGRIB);\n      exit (-7);\n    }\n\n    /* Read the whole GRIB record. */\n\n    read(fd, ii, lengrib);\n\n    /* Process */\n\n    switch (edition) {\n\n    case 1:\n      process_grib1_record();\n      break;\n\n    case 2:\n      process_grib2_record(lengrib);\n      break;\n    }\n  }\n\n shutdown:\n\n  return(0);\n  \n}\n\nvoid process_grib1_record() {\n\n  sec0_ptr = ii;\n  sec0_len = 8;\n\n  sec1_ptr = &(ii[sec0_len]);\n  sec1_len = (sec1_ptr[0]*256+sec1_ptr[1])*256+sec1_ptr[2];\n\n  switch(sec1_ptr[7]){\n  default:\n    fprintf(stderr, \"Problem (1) with optional sections\\n\");\n    exit (1);\n  case 0:\n  case 64:\n    sec2_ptr = NULL;\n    sec2_len = 0;\n    break;\n  case 128:\n  case 192:\n    sec2_ptr = &(ii[sec0_len+sec1_len]);\n    sec2_len = (sec2_ptr[0]*256+sec2_ptr[1])*256+sec2_ptr[2];\n    break;\n  }\n  // if (sec2_ptr) printf(\"sec2_start = %i;   sec2_len = %i\\n\", sec2_ptr-ii, sec2_len);\n\n  switch(sec1_ptr[7]){\n  default:\n    fprintf(stderr, \"Problem (2) with optional sections\\n\");\n    exit (1);\n  case 0:\n  case 128:\n    sec3_ptr = NULL;\n    sec3_len = 0;\n    break;\n  case 64:\n  case 192:\n    sec3_ptr = &(ii[sec0_len+sec1_len+sec2_len]);\n    sec3_len = (sec3_ptr[0]*256+sec3_ptr[1])*256+sec3_ptr[2];\n    break;\n  }\n  // if (sec3_ptr) printf(\"sec3_start = %i;   sec3_len = %i\\n\", sec3_ptr-ii, sec3_len);\n\n  sec4_ptr = &(ii[sec0_len+sec1_len+sec2_len+sec3_len]);\n  sec4_len = (sec4_ptr[0]*256+sec4_ptr[1])*256+sec4_ptr[2];\n\n  sec5_ptr = &(ii[sec0_len+sec1_len+sec2_len+sec3_len+sec4_len]);\n  sec5_len = 4;\n\n  // printf(\"sec4_start = %i;   sec4_len = %i\\n\", sec4_ptr-ii, sec4_len);\n\n  check_and_write();\n\n}\n\nvoid process_grib2_record (int lengrib) {\n  unsigned int secsize;\n  unsigned char *ipt;\n\n  /* Scan forward to find the beginning of various GRIB sections */\n  ipt = ii;\n  ipt += sec0_len;\n  sec0_ptr = ii;\n\n  while (ipt - ii < lengrib) {\n    if ((ipt[0] == '7') && (ipt[1] == '7') && (ipt[2] == '7') && (ipt[3] == '7')) {\n      sec8_ptr = ipt;\n      sec8_len = 4;\n      if (secval==8) check_and_write();\n      return;\n    }\n    switch (ipt[4]) { /* ipt[4] encodes the section identifier (1-7) */\n    default:\n      fprintf(stderr,\"This should not happen (3)\");\n      exit(1);\n    case 1:\n      sec1_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec1_len = secsize;\n      if (secval==ipt[4]) check_and_write();\n      break;\n    case 2:\n      sec2_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec2_len = secsize;\n      if (secval==ipt[4]) check_and_write();\n      break;\n    case 3:\n      sec3_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec3_len = secsize;\n      if (secval==ipt[4]) check_and_write();\n      break;\n    case 4:\n      sec4_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec4_len = secsize;\n      if (secval==ipt[4]) check_and_write();\n      break;\n    case 5:\n      sec5_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec5_len = secsize;\n      if (secval==ipt[4]) check_and_write();\n      break;\n    case 6:\n      sec6_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec6_len = secsize;\n      if (secval==ipt[4]) check_and_write();\n      break;\n    case 7:\n      sec7_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec7_len = secsize;\n      if (secval==ipt[4]) check_and_write();\n      break;\n    }\n    ipt += secsize;\n  }\n}\n\nvoid check_and_write() {\n  unsigned char *ipt;\n  int m, foundval;\n\n  /* Extract specified bytes */\n  switch (secval) {\n  case 0:\n    ipt = ii;\n    if (bytend > sec0_len) {\n      fprintf(stderr, \"Byte request beyond section length\\n\");\n      exit (1);\n    }\n    break;\n  case 1:\n    ipt = sec1_ptr;\n    if (bytend > sec1_len) {\n      fprintf(stderr, \"Byte request (%i) beyond section length (%i)\\n\", bytend, sec1_len);\n      exit (1);\n    }\n    break;\n  case 2:\n    ipt = sec2_ptr;\n    if (bytend > sec2_len) {\n      fprintf(stderr, \"Byte request beyond section length\\n\");\n      exit (1);\n    }\n    break;\n  case 3:\n    ipt = sec3_ptr;\n    if (bytend > sec3_len) {\n      fprintf(stderr, \"Byte request beyond section length\\n\");\n      exit (1);\n    }\n    break;\n  case 4:\n    ipt = sec4_ptr;\n    if (bytend > sec4_len) {\n      fprintf(stderr, \"Byte request beyond section length\\n\");\n      exit (1);\n    }\n    break;\n  case 5:\n    ipt = sec5_ptr;\n    if (bytend > sec5_len) {\n      fprintf(stderr, \"Byte request beyond section length\\n\");\n      exit (1);\n    }\n    break;\n  case 6:\n    ipt = sec6_ptr;\n    if (bytend > sec6_len) {\n      fprintf(stderr, \"Byte request beyond section length\\n\");\n      exit (1);\n    }\n    break;\n  case 7:\n    ipt = sec7_ptr;\n    if (bytend > sec7_len) {\n      fprintf(stderr, \"Byte request beyond section length\\n\");\n      exit (1);\n    }\n    break;\n  case 8:\n    ipt = sec8_ptr;\n    if (bytend > sec8_len) {\n      fprintf(stderr, \"Byte request beyond section length\\n\");\n      exit (1);\n    }\n    break;\n  default:\n    fprintf(stderr, \"Problem in specific byte:  Section %i\\n\", secval);\n    exit (1);\n  }\n\n  /* Extract bytes */\n  if ( ! quiet ) {\n    printf(\"Section %i starts at %i\\n\", secval, ipt-ii+1);\n\n    foundval = 0;\n    for (m = bytnum; m<=bytend; m++) {\n      fprintf(stderr, \"Byte number %i:  %i:  \", &(ipt[m]) - ii, ipt[m-1]);\n    }\n  }\n\n\n  if ( !decimal ) {\n    for (m = bytnum; m<=bytend; m++) {\n      printf(\"%i \", ipt[m-1]);\n    }\n    printf(\"\\n\");\n  }\n  else {\n    foundval = 0;\n    for (m = bytnum; m<=bytend; m++) {\n      foundval = (foundval*256) + ipt[m-1];\n    }\n    printf (\"%i\\n\", foundval);\n  }\n\n}\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/gribedition.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n\n*/\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <unistd.h>\n#include <string.h>\n\n  \n\nint main(int argc, char *argv[])\n{ /* main */\n  int fd;            /* Integer referring to input file. */\n  char *input_file;  /* Input file name. */\n  unsigned char edition;\n  unsigned char hh[4];\n\n  /* Check that the input file is provided as a command-line argument*/\n  input_file = argv[1];\n  if (input_file == NULL){\n    fprintf(stderr, \"\\nInput file <infile> is a required argument.\\n\");\n    printf(\"%i\\n\",-1);\n    exit (1);\n  }\n\n  /*   Open the input file for reading   */\n  fd = open(input_file, O_RDONLY);\n  if (fd == -1) {\n    fprintf(stderr, \"\\n ***** Problem opening input file.  Error exit. *****\\n\");\n    fprintf(stderr, \"       File name: '%s'\\n\\n\", input_file);\n    printf(\"-2\\n\");\n    exit (2);\n  }\n\n  /* Scan forward for a string \"GRIB\" */\n  while ( strncmp(hh, \"GRIB\", 4) != 0 ) {\n    if (read(fd, hh, 4) != 4) goto shutdown; \n    lseek(fd, -3, SEEK_CUR);\n  }\n  lseek(fd, 3, SEEK_CUR);\n\n  /*   We've found the beginning of a GRIB record, now read four    */\n  /*   more bytes and check the GRIB edition number.  GRIB Editions */\n  /*   1 and 2 are acceptable.                                      */\n    \n  if (read(fd, hh, 4) != 4) goto shutdown;\n  edition = hh[3];\n\n  switch (edition) {\n  case 1:\n  case 2:\n    printf(\"%i\\n\",edition);\n    close(fd);\n    exit (0);\n  default:\n    fprintf(stderr,\"\\n ***** Edition number unsupported:  %i\\n\", edition);\n    printf(\"%i\\n\",-3);\n    close(fd);\n    exit(1);\n  }\n    \n\n shutdown:\n  fprintf(stderr, \"\\n ***** Problem reading input file.  Error exit. *****\\n\");\n  fprintf(stderr, \"       File name: '%s'\\n\\n\", input_file);\n  close(fd);\n  printf(\"%i\\n\",-4);\n  exit (3);\n  \n}\n\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/gribextract.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n*/\n\n\n/*                                                          */\n/* Extracts specified GRIB records from a GRIB file.        */\n/*                                                          */\n#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <unistd.h>\n#include <string.h>\n#include <math.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n#define MIN(A,B) ((A)<(B) ? A : B)\n\n#define MAXGRIB 2000000\n\nvoid process_grib1_record(int fw, int lengrib);\nvoid process_grib2_record(int fw, int lengrib, unsigned char discipline);\nvoid check_and_write(int fw, int lengrib);\n\nunsigned char ii[MAXGRIB];\nunsigned char *sec1_ptr, *sec2_ptr, *sec3_ptr, *sec4_ptr, *sec5_ptr, *sec6_ptr, *sec7_ptr;\nint fd;  /* Integer referring to input file. */\nunsigned int sec0_len, sec1_len, sec2_len, sec3_len, sec4_len, sec5_len, sec6_len, sec7_len;\nunsigned char itri;\nunsigned int iparm;\ndouble level1_xval, level2_xval;\nint output_count, record_count;\n\nint codeval[100], levtyp[100];\ndouble levval1[100], levval2[100];\nint secval[100], bytnum[100], bytend[100], bytval[100];\n\nint ccount, lcount, scount;\nchar verbose, quiet, force;\n\nunsigned char imonth, iday, ihour, iminute;\nunsigned int iyear;\nunsigned char edition;\nunsigned char level1_type;\nunsigned char level2_type;\n  \n\nint main(int argc, char *argv[])\n{ /* main */\n  int c;\n  unsigned char hhh[8];\n  unsigned char hh[4];\n  char optstring[12] = \"vqfg:c:s:l:h\";\n  int lengrib;\n  int expected_edition;\n  unsigned char discipline;\n\n  char *input_file;  /* Input file name. */\n  char *output_file; /* Output file name. */\n\n  int fw;  /* Integer referring to output file. */\n  off_t offset;\n\n  char *usage = \"usage:\\n  %s [-help | -h] [-v] [-q] [-f]\\n\"\\\n    \"    [-c <codeval> | -c <discipline>,<category>,<parameter>]\\n\"\\\n    \"    [-l <levtyp>,<levval11>,<levval2>]\\n\"\\\n    \"    [-s <secnum>,<bytnum>[:<bytend>],<bytval>] <infile> <outfile>\\n\\n\";\n\n  lcount = 0;\n  ccount = 0;\n  scount = 0;\n\n  output_count = 0;\n  record_count = 0;\n  verbose = 0;\n  quiet = 0;\n  force = 0;\n\n  while ( (c=getopt(argc, argv, optstring)) != -1 ) {\n    switch (c){\n    case 'v':\n      verbose = 1;\n      break;\n    case 'q':\n      quiet = 1;\n      break;\n    case 'f':\n      force = 1;\n      break;\n    case 'c':\n      {\n\tint i1, i2, i3;\n\tint nread;\n\ti1 = -9999;\n\ti2 = -9999;\n\ti3 = -9999; \n\n\tnread = sscanf(optarg, \"%d,%d,%d\", &i1, &i2, &i3);\n\n\tswitch (nread) {\n\tdefault:\n\t  fprintf(stderr, usage,argv[0]); \n\t  exit (1);\n\tcase 1:\n\t  expected_edition = 1;\n\t  codeval[ccount] = i1;\n\t  break;\n\tcase 3:\n\t  expected_edition = 2;\n\t  codeval[ccount] = i1*1000000+i2*1000+i3;\n\t  break;\n\t}\n\t  \n\tccount++;\n\tbreak;\n      }\n    case 'l':\n      {\n\tint i1;\n\tfloat f2, f3;\n\tint nread;\n\n \ti1 = -9999;\n\tf2 = -9999;\n\tf3 = -9999;\n\t// printf(\"optarg = '%s'\\n\", optarg);\n\tnread = sscanf(optarg, \"%d,%f,%f\", &i1, &f2, &f3);\n\t// printf(\"nread = %i\\n\", nread);\n\t// printf(\"i1, f2, f3 = %i %f %f\\n\", i1, f2, f3);\n\tlevtyp[lcount] = i1;\n\tlevval1[lcount] = f2;\n\tlevval2[lcount] = f3;\n      \n\t// printf(\"-l %i,%f,%f\\n\", levtyp[lcount], levval1[lcount], levval2[lcount]);\n\tlcount++;\n\tbreak;\n      }\n\n    case 's':\n      {\n\tint i1, i2, i3, i4;\n\ti1 = -9999;\n\ti2 = -9999;\n\ti3 = -9999; \n\ti4 = -9999; \n\n/* \tprintf(\"optarg = %s\\n\", optarg); */\n\t\n\tif (strchr(optarg,':')) {\n\t  sscanf(optarg, \"%d,%d:%d,%d\", &i1, &i2, &i3, &i4);\n \t  // printf(\"i1 i2 i3 i4 = %i %i %i %i\\n\", i1, i2, i3, i4);\n\t  secval[scount] = i1;\n\t  bytnum[scount] = i2;\n\t  bytend[scount] = i3;\n\t  bytval[scount] = i4;\n\t  if (bytval[scount] < 0) {\n\t    double pfac;\n\t    int imv;\n\t    pfac = ((bytend[scount]-bytnum[scount]+1)*8-1);\n\t    imv = pow(2.,pfac);\n\t    bytval[scount] = imv - bytval[scount];\n\t  }\n\t  if (bytend[scount] < bytnum[scount]) {\n\t    fprintf(stderr, \"\\n    In -s option bytend must be greater than bytnum\\n\");\n\t    fprintf(stderr, \"    -s secval,bytnum[:bytend],bytval\\n\");\n\t    fprintf(stderr, \"\\n***** Error exit *****\\n\\n\");\n\t    exit(1);\n\t  }\n\t}\n\telse {\n\t  sscanf(optarg, \"%d,%d,%d,%d\", &i1, &i2, &i3);\n\t  secval[scount] = i1;\n\t  bytnum[scount] = i2;\n\t  bytval[scount] = i3;\n\t  bytend[scount] = bytnum[scount];\n\t}\n      \n\t// printf(\"-s %i,%i,%i,%i\\n\", secval[scount], bytnum[scount], bytval[scount], bytend[scount]);\n\tscount++;\n\tbreak;\n      }\n    case 'h':\n      {\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"**************************************************************************\\n\\n\");\n\tfprintf(stderr, \"%s\\n           -- extracts specified fields from a GRIB (Edition 1 or Edition 2) file.\\n\", argv[0]);\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, usage,argv[0]); \n\tfprintf(stderr, \"where:\\n      <infile>  -- the GRIB-formatted file to read.\\n\");\n\tfprintf(stderr, \"      <outfile> -- the GRIB-formatted file to create.\\n\\n\");\n\tfprintf(stderr, \"options:\\n  -help  : print this help message and exit.\\n\\n\");\n\tfprintf(stderr, \"  -v  : more printout (verbose).\\n\\n\");\n\tfprintf(stderr, \"  -q  : less printout (quiet).\\n\\n\");\n\tfprintf(stderr, \"  -f  : overwrite an existing output file without asking (force).\\n\\n\");\n\tfprintf(stderr, \"  -c  : extract fields as specified by a comma-separated list of integers,\\n\");\n\tfprintf(stderr, \"        where:\\n\");\n\tfprintf(stderr, \"           <codeval> is the GRIB Editon 1 parameter code.\\n\");\n\tfprintf(stderr, \"        or:\\n\");\n\tfprintf(stderr, \"           <discipline> is the GRIB Edition 2 product discipline.\\n\");\n\tfprintf(stderr, \"           <category> is the GRIB Edition 2 parameter category.\\n\");\n\tfprintf(stderr, \"           <parameter> is the GRIB Edition 2 parameter number.\\n\");\n\tfprintf(stderr, \"  -l  : extract levels as specified by a comma-separated list of integers,\\n\");\n\tfprintf(stderr, \"        where:\\n\");\n\tfprintf(stderr, \"           <levtyp> is the GRIB level-type code.\\n\");\n\tfprintf(stderr, \"           <levval1> is the level value.\\n\");\n\tfprintf(stderr, \"           <levval2> is a second level value (if level is defined by two values).\\n\\n\");\n\tfprintf(stderr, \"                    **** NOTE **** GRIB Edition 1 defines pressure levels in mb.\\n\");\n\tfprintf(stderr, \"                                   GRIB Edition 2 defines pressure levels in Pa.\\n\");\n\tfprintf(stderr, \"  -s  : extract only fields that match section number, byte number, and byte value.\\n\");\n\tfprintf(stderr, \"        Multiple -s flags may be specified.  A range of byte numbers may be specified.\\n\");\n\tfprintf(stderr, \"        where:\\n\");\n\tfprintf(stderr, \"           <secnum> is the GRIB section number to look in.\\n\");\n\tfprintf(stderr, \"           <bytnum> is the byte number in that GRIB section (or the beginning\\n\");\n\tfprintf(stderr, \"                    of a range of bytes) to look at.\\n\");\n\tfprintf(stderr, \"           <bytend> is the end byte number of a range of bytes to look at.\\n\");\n\tfprintf(stderr, \"           <bytval> is the value to match for the specified byte or byte range.\\n\");\n\tfprintf(stderr, \"\\n\\nFor example:  \\n\\n\");\n\tfprintf(stderr, \"      '%s -c 0,2,3'\\n            will extract all V fields from a GRIB Edition2 file.\\n\\n\", argv[0]);\n\tfprintf(stderr, \"      '%s -c 11 -c 33'\\n            will extract all T and U fields from a GRIB Edition 1 file.\\n\\n\",\n\t\targv[0]);\n\tfprintf(stderr, \"      '%s -c 11 -l 100'\\n            will extract all P-level T fields from a GRIB Edition 1 file.\\n\\n\",\n\t\targv[0]);\n\tfprintf(stderr, \"      '%s -l 100,500'\\n            will extract all 500 mb fields from a GRIB Edition 1 file,\\n\",\n\t\targv[0]);\n\tfprintf(stderr, \"                 and all 500 Pa (5 mb) fields from a GRIB Edition 2 file.\\n\\n\");\n\tfprintf(stderr, \"**************************************************************************\\n\");\n\texit (-1); \n      }\n\n    default :\n      fprintf(stderr, usage, argv[0]);\n      exit (-1);\n    }\n  }\n\n  if (ccount == 0) {\n    codeval[ccount] = -9999;\n/*     levtyp[ccount] = -9999; */\n/*     levval1[ccount] = -9999; */\n/*     levval2[ccount] = -9999; */\n  }\n\n  if (scount == 0) {\n    secval[scount] = -9999;\n    bytnum[scount] = -9999;\n    bytend[scount] = -9999;\n    bytval[scount] = -9999;\n  }\n\n  /* Check that the input file is provided as a command-line argument*/\n  input_file = argv[optind];\n  if (input_file == NULL){\n    fprintf(stderr, \"\\nInput file <infile> is a required argument.\\n\");\n    fprintf(stderr, usage, argv[0]);\n    exit (9);\n  }\n\n  /* Check that the output file is provided as a command-line argument*/\n  output_file = argv[optind+1];\n  if (output_file == NULL) {\n    fprintf(stderr, \"\\nOutput file <outfile> is a required argument.\\n\");\n    fprintf(stderr, usage, argv[0]);\n    exit (9);\n  }\n\n  /*   Open the input file for reading   */\n  if ( ! ( quiet ) ) {\n    printf(\"\\nInput file = %s\\n\", input_file);\n  }\n  fd = open(argv[optind], O_RDONLY);\n  if (fd == -1) {\n    fprintf(stderr, \"\\n ***** Problem opening input file.  abort *****\\n\");\n    fprintf(stderr, \"       File name: '%s'\\n\\n\", argv[optind]);\n    exit(-4);\n  }\n\n  if ( ! force ) {\n\n    /*   Check whether the output file already exists.       */\n    /*   If so, query the user before overwriting that file. */\n\n    struct stat fbuf;\n\n    if (stat(output_file, &fbuf) == 0) {\n      char ans;\n      fprintf(stderr, \"\\aOutput file '%s' already exists.  Overwrite? (n) > \", output_file);\n      ans = getchar();\n      fprintf (stderr, \"\\n\");\n      if ((ans != 'y') && (ans != 'Y')) {\n\tfprintf(stderr, \" ***** OK.  Not overwriting file '%s'.  Exit. *****\\n\\n\", output_file);\n\texit (1);\n      }\n    }\n  }\n\n  /* Open the output file for writing.*/\n  if ( ! ( quiet ) ) {\n    printf(\"Output file = %s\\n\", output_file);\n  }\n  fw = creat(output_file, 0644);\n\n  while (1) {\n    hh[0] = 0;\n    /* Scan forward for a string \"GRIB\" */\n    while ( strncmp(hh, \"GRIB\", 4) != 0 ) {\n      if (read(fd, hh, 4) != 4) goto shutdown; \n      offset = -(off_t)3;\n      lseek(fd, offset, SEEK_CUR);\n    }\n    lseek(fd, 3, SEEK_CUR);\n\n    /*   We've found the beginning of a GRIB record, now check    */\n    /*   the GRIB edition number.  GRIB Editions 1 and 2 are      */\n    /*   acceptable.                                              */\n    \n    read(fd, hh, 4);\n    edition = hh[3];\n\n    switch (edition) {\n    case 1:\n      sec0_len = 8;\n      break;\n    case 2:\n      sec0_len = 16;\n      discipline = hh[2];\n      break;\n    default:\n      fprintf(stderr,\"Edition number unsupported:  %i\\n\", edition);\n      exit(1);\n    }\n    \n    sec2_len = 0;\n    sec3_len = 0;\n    sec4_len = 0;\n    sec5_len = 0;\n    sec6_len = 0;\n    sec7_len = 0;\n\n    /*   We've found the beginning of a GRIB record, and we know  */\n    /*   The GRIB edition number.  Now find the size of the whole */                     \n    /*   GRIB record.                                             */\n\n    switch (edition) {\n    case 1:\n      lengrib = hh[0]*65536+hh[1]*256+hh[2];\n      break;\n    case 2:\n      read(fd, hhh, 8);\n      lengrib = ((((((hhh[0]*256+hhh[1])*256+hhh[2])*256+hhh[3])*256+hhh[4])*256+hhh[5])*256+hhh[6])*256+hhh[7];\n      break;\n    default:\n      fprintf(stderr,\"This should not happen (1)\");\n      exit(1);\n    }\n\n    /* rewind back to the beginning of the GRIB record */\n    offset = -(off_t)(sec0_len);\n    lseek(fd, offset, SEEK_CUR);\n\n    if (lengrib > MAXGRIB) {\n      fprintf(stderr, \"\\n   ***** Increase MAXGRIB > %i\\n\", lengrib);\n      fprintf(stderr, \"   ***** MAXGRIB is currently set to %i\\n\\n\", MAXGRIB);\n      exit (-7);\n    }\n\n    record_count++;\n\n    /* Read the whole GRIB record. */\n\n    read(fd, ii, lengrib);\n\n    /* Process */\n\n    switch (edition) {\n\n    default:\n\n      fprintf(stderr,\"This should not happen (2)\");\n      exit(1);\n\n    case 1:\n      /* if (expected_edition==1) { */\n\tprocess_grib1_record(fw, lengrib);\n\t/* } */\n      break;\n\n    case 2:\n      /* if (expected_edition == 2) { */\n\tprocess_grib2_record(fw, lengrib, discipline);\n\t/* } */\n      break;\n    }\n  }\n\n shutdown:\n  close(fw);\n  if ( ! ( quiet ) ) {\n    printf(\"\\noutput_count = %i\\n\", output_count);\n  }\n\n  return(0);\n  \n}\n\nvoid process_grib1_record(int fw, int lengrib) {\n  unsigned char icentury;\n  unsigned char gds_or_bms;\n  sec1_ptr = &(ii[8]);\n  sec1_len = (sec1_ptr[0]*256+sec1_ptr[1])*256+sec1_ptr[2];\n  // printf(\"sec1_start = %i;   sec1_len = %i\\n\", sec1_ptr-ii, sec1_len);\n\n  gds_or_bms = sec1_ptr[7];\n\n  switch(gds_or_bms){\n  default:\n    fprintf(stderr, \"Problem (1) with optional sections\\n\");\n    exit (1);\n  case 0:\n  case 64:\n    sec2_ptr = NULL;\n    sec2_len = 0;\n    break;\n  case 128:\n  case 192:\n    sec2_ptr = &(ii[8+sec1_len]);\n    sec2_len = (sec2_ptr[0]*256+sec2_ptr[1])*256+sec2_ptr[2];\n    break;\n  }\n  // if (sec2_ptr) printf(\"sec2_start = %i;   sec2_len = %i\\n\", sec2_ptr-ii, sec2_len);\n\n  switch(gds_or_bms){\n  default:\n    fprintf(stderr, \"Problem (2) with optional sections\\n\");\n    exit (1);\n  case 0:\n  case 128:\n    sec3_ptr = NULL;\n    sec3_len = 0;\n    break;\n  case 64:\n  case 192:\n    sec3_ptr = &(ii[8+sec1_len+sec2_len]);\n    sec3_len = (sec3_ptr[0]*256+sec3_ptr[1])*256+sec3_ptr[2];\n    break;\n  }\n  // if (sec3_ptr) printf(\"sec3_start = %i;   sec3_len = %i\\n\", sec3_ptr-ii, sec3_len);\n\n  sec4_ptr = &(ii[8+sec1_len+sec2_len+sec3_len]);\n  sec4_len = (sec4_ptr[0]*256+sec4_ptr[1])*256+sec4_ptr[2];\n\n  // printf(\"sec4_start = %i;   sec4_len = %i\\n\", sec4_ptr-ii, sec4_len);\n\n  /* Extract the century, year, month, day, hour, and minute */\n  /* of reference time                                       */\n  icentury = ii[32];\n  iyear = ii[20] + (icentury-MIN(ii[20],1))*100;\n  imonth = ii[21];\n  iday = ii[22];\n  ihour = ii[23];\n  iminute = ii[24];\n\n  /* Extract the parameter number */\n\n  iparm = ii[16]; \n\n  /* Extract the level type */\n\n  level1_type = ii[17];\n\n  /* Time Range Indicator */\n  itri = ii[28];\n\n  /* Extract the level values */\n\n  level1_xval = ii[18];\n  level2_xval = ii[19];\n\n  /* for certain types of levels, the two bytes represent a single value */\n  if ( (level1_type == 100) || (level1_type == 103) || (level1_type == 105) ||\n       (level1_type == 107) || (level1_type == 109) || (level1_type == 111) ||\n       (level1_type == 113) || (level1_type == 115) || (level1_type == 117) || \n       (level1_type == 118) || (level1_type == 119) || (level1_type == 125) ||\n       (level1_type == 160) || (level1_type == 200) || (level1_type == 201)) {\n\n    level1_xval = level1_xval*256+level2_xval;\n    level2_xval = -9999;\n\t\n  }\n\n  check_and_write(fw, lengrib);\n\n}\n\nvoid process_grib2_record (int fw, int lengrib, unsigned char discipline) {\n  unsigned int secsize;\n  unsigned int level1_factor;\n  unsigned int level2_factor;\n  unsigned int scaled_level1_value;\n  unsigned int scaled_level2_value;\n  unsigned char *ipt;\n  unsigned char parameter_category;\n  unsigned char parameter_number;\n\n  /* Scan forward to find the beginning of various GRIB sections */\n  ipt = ii;\n  ipt += sec0_len;\n\n  while (ipt - ii < lengrib) {\n    if ((ipt[0] == '7') && (ipt[1] == '7') && (ipt[2] == '7') && (ipt[3] == '7')) {\n      // printf(\"Hit end of record.\\n\");\n      return;\n    }\n    switch (ipt[4]) { /* ipt[4] encodes the section identifier (1-7) */\n    default:\n      fprintf(stderr,\"This should not happen (3)\");\n      exit(1);\n    case 1:\n      sec1_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec1_len = ((ii[sec0_len+0]*256+ii[sec0_len+1])*256+ii[sec0_len+2])*256+ii[sec0_len+3];\n      /* Extract the century, year, month, day, hour, and minute */\n      /* of reference time                                       */\n      iyear   = ii[sec0_len+12]*256+ii[sec0_len+13];\n      imonth  = ii[sec0_len+14];\n      iday    = ii[sec0_len+15];\n      ihour   = ii[sec0_len+16];\n      iminute = ii[sec0_len+17];\n      break;\n    case 2:\n      sec2_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec2_len = secsize;\n      break;\n    case 3:\n      sec3_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec3_len = secsize;\n      break;\n    case 4:\n      sec4_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec4_len = secsize;\n      parameter_category = ipt[9];\n      parameter_number   = ipt[10];\n      iparm = discipline*1000000 + parameter_category*1000 + parameter_number;\n      // fprintf(stderr, \"parameter_category, parameter_number = %3i %3i %10i\\n\", parameter_category, parameter_number, iparm);\n      level1_type = ipt[22];\n      level1_factor = ipt[23];\n      scaled_level1_value = ((ipt[24]*256+ipt[25])*256+ipt[26])*256+ipt[27];\n      level2_type = ipt[28];\n      level2_factor = ipt[29];\n      scaled_level2_value = ((ipt[30]*256+ipt[31])*256+ipt[32])*256+ipt[33];\n      level1_xval = scaled_level1_value / pow(10., level1_factor);\n      level2_xval = scaled_level2_value / pow(10., level2_factor);\n      break;\n    case 5:\n      sec5_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec5_len = secsize;\n      break;\n    case 6:\n      sec6_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec6_len = secsize;\n      break;\n    case 7:\n      sec7_ptr = &(ii[ipt-ii]);\n      secsize = ((ipt[0]*256+ipt[1])*256+ipt[2])*256+ipt[3];\n      sec7_len = secsize;\n      check_and_write(fw, lengrib);\n      break;\n    }\n    ipt += secsize;\n  }\n}\n\nvoid check_and_write(int fw, int lengrib) {\n  int output_length;\n  int lskip;\n  int k;\n  unsigned char *ipt;\n  int m, foundval;\n\n  /* If the parameter is one we want, write it out. */\n  if (ccount>0) {\n    lskip = 1;\n    for (k=0; k<ccount; k++) {\n      if ((iparm == codeval[k]) || (codeval[k] == -9999)) {\n\tlskip = 0;\n      }\n    }\n    if (lskip) {\n      if ( ! quiet ) printf(\"Skipping (A) %i %7.7i\\n\", record_count, iparm);\n      return;\n    }\n  }\n\n  /* If the level is one we want, write it out. */\n  if (lcount>0) {\n    lskip = 1;\n    for (k=0; k<lcount; k++) {\n\n      if ( ( ( level1_type == levtyp[k]             ) || (levtyp[k]  < -9998)) &&\n\t   ( ( fabsf(level1_xval - levval1[k])<1.E-6) || (levval1[k] < -9998)) &&\n\t   ( ( fabsf(level2_xval - levval2[k])<1.E-6) || (levval2[k] < -9998))) {\n\t// printf(\"Match for %7.7i %i %f %f\\n\", iparm, level1_type, level1_xval, level2_xval);\n\tlskip = 0;\n      }\n    }\n    if (lskip) {\n      if ( ! quiet ) printf(\"Skipping (B) %i %7.7i\\n\", record_count, iparm);\n      return;\n    }\n  }\n  \n\n  /* Check specified bytes */\n  if (scount>0) {/* section specifications */\n    lskip = 1;\n    for (k=0; k<scount; k++) {\n      switch (secval[k]) {\n      case 0:\n\tipt = ii;\n\tbreak;\n      case 1:\n\tipt = sec1_ptr;\n\tbreak;\n      case 2:\n\tipt = sec2_ptr;\n\tbreak;\n      case 3:\n\tipt = sec3_ptr;\n\tbreak;\n      case 4:\n\tipt = sec4_ptr;\n\tbreak;\n      case 5:\n\tipt = sec5_ptr;\n\tbreak;\n      case 6:\n\tipt = sec6_ptr;\n\tbreak;\n      case 7:\n\tipt = sec7_ptr;\n\tbreak;\n      default:\n\tfprintf(stderr, \"Problem in specific byte:  Section %i\\n\", secval[k]);\n\texit (1);\n      }\n\n      /* Handle the range of bytes */\n      foundval = 0;\n      for (m = bytnum[k]; m<=bytend[k]; m++) {\n\t// printf(\"Byte number %i:  %i:  \", &(ipt[m-1]) - ii, ipt[m-1]);\n\tfoundval = (foundval*256) + ipt[m-1];\n\t// printf(\"Foundval = %i\\n\", foundval);\n      }\n      if ( ! quiet ) {\n\t// printf(\"Section %i starts at %i\\n\", secval[k], ipt-ii);\n\tprintf(\"test value: %i   value found: %i\\n\", bytval[k], foundval);\n      }\n      // printf(\"foundval, bytval[k] = %i %i\\n\", foundval, bytval[k]);\n      if (foundval == bytval[k]) {\n\tlskip = 0;\n      }\n    }\n    if (lskip) {\n      if ( ! quiet ) printf(\"Skipping (C) %i %7.7i\\n\", record_count, iparm);\n      return;\n    }\n  }\n\n  if ( ! lskip ) {\n    unsigned char sec0[16];\n    int n;\n\n    output_count++;\n    switch(edition){\n    case 1:\n      write(fw, ii, lengrib);\n      break;\n    case 2:\n\n      output_length = 16 + sec1_len + sec2_len + sec3_len + sec4_len + sec5_len + sec6_len + sec7_len + 4;\n      memcpy(sec0, ii, 16);\n      // Byte-swapped record length.\n      sec0[15] = output_length & 0xFF;\n      sec0[14] = (output_length>>8) & 0xFF;\n      sec0[13] = (output_length>>16) & 0xFF;\n      sec0[12] = (output_length>>24) & 0xFF;\n\n      write(fw, sec0, 16);\n      write(fw, sec1_ptr, sec1_len);\n      if (sec2_len) write(fw, sec2_ptr, sec2_len);\n      write(fw, sec3_ptr, sec3_len);\n      write(fw, sec4_ptr, sec4_len);\n      write(fw, sec5_ptr, sec5_len);\n      write(fw, sec6_ptr, sec6_len);\n      write(fw, sec7_ptr, sec7_len);\n      write(fw, \"7777\", 4);\n      break;\n    }\n    if (verbose) {\n      if (level2_xval != -9999) {\n\tprintf(\"%5i %7.7i %4i %f %f  %4i-%2.2i-%2.2i_%2.2i:%2.2i\\n\", \n\t       record_count, iparm, level1_type, level1_xval, level2_xval,\n\t       iyear, imonth, iday, ihour, iminute);\n      }\n      else {\n\tprintf(\"%4i %3i %4i %f  **   %4i-%2.2i-%2.2i_%2.2i:%2.2i\\n\", \n\t       record_count, iparm, level1_type, level1_xval,\n\t       iyear, imonth, iday, ihour, iminute);\n      }\n    }\n  }\n  else {\n    if ( ! quiet ) printf(\"Skipping (D) %i %7.7i\\n\", record_count, iparm);\n  }\n\n}\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/hrldas_extract_point.F",
    "content": "module module_hrldas_netcdf\n  use netcdf\n  implicit none\n\n  character(len=2), dimension(3), parameter :: projection_list = (/ \"LC\", \"ST\", \"ME\" /)\n  type hrldas_mapinfo_type\n     character(len=2) :: projection\n     integer :: iproj\n     real    :: lat1\n     real    :: lon1\n     real    :: xlonc\n     real    :: dxm\n     real    :: truelat1\n     real    :: truelat2\n  end type hrldas_mapinfo_type\n\ncontains\n\n!------------------------------------------------------------------------------\n! Subroutine get_map_info\n!------------------------------------------------------------------------------\n\n  subroutine get_map_info(flnm, ncid, mapinfo)\n    use netcdf\n    implicit none\n\n    character(len=*),          intent(in)  :: flnm\n    integer,                   intent(out) :: ncid\n    type(hrldas_mapinfo_type), intent(out) :: mapinfo\n\n    integer :: ierr\n\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    call handle_error(ierr, \"file:  \"//trim(flnm))\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", mapinfo%iproj)\n    call handle_error(ierr, \"MAP_PROJ:  \")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LAT1\", mapinfo%lat1)\n    call handle_warning(ierr, \"LAT1:  \")\n\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"Looking instead for LA1\",/)')\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LA1\", mapinfo%lat1)\n       call handle_error(ierr, \"LA1:  \")\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LON1\", mapinfo%lon1)\n    call handle_warning(ierr, \"LON1:  \")\n\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"Looking instead for LO1\",/)')\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"LO1\", mapinfo%lon1)\n       call handle_error(ierr, \"LO1:  \")\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"DX\", mapinfo%dxm)\n    call handle_error(ierr, \"DX:  \")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\", mapinfo%truelat1)\n    call handle_error(ierr, \"TRUELAT1:  \")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\", mapinfo%truelat2)\n    call handle_error(ierr, \"TRUELAT2:  \")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", mapinfo%xlonc)\n    call handle_error(ierr, \"STAND_LON:  \")\n\n    mapinfo%projection = projection_list(mapinfo%iproj)\n\n  end subroutine get_map_info\n\n!------------------------------------------------------------------------------\n! Subroutine close_hrldas_file\n!------------------------------------------------------------------------------\n\n  subroutine close_hrldas_file(ncid)\n    implicit none\n    integer, intent(in) :: ncid\n    integer :: ierr\n    ierr = nf90_close(ncid)\n    call handle_error(ierr, \"Trying to close file.\")\n  end subroutine close_hrldas_file\n\n!------------------------------------------------------------------------------\n! Subroutine lltoxy_hrldas\n!------------------------------------------------------------------------------\n\n  subroutine lltoxy_hrldas(lat, lon, x, y, mapinfo)\n    use module_llxy_generic\n    implicit none\n    real, intent(in) :: lat, lon\n    real, intent(out) :: x, y\n    type(hrldas_mapinfo_type) :: mapinfo\n\n    call lltoxy_generic(lat, lon, x, y, &\n         mapinfo%projection, mapinfo%dxm*1.E-3, mapinfo%lat1, mapinfo%lon1, 1.0, 1.0, &\n         mapinfo%xlonc, mapinfo%truelat1, mapinfo%truelat2)\n\n  end subroutine lltoxy_hrldas\n\n!------------------------------------------------------------------------------\n! Subroutine xytoll_hrldas\n!------------------------------------------------------------------------------\n\n  subroutine xytoll_hrldas(x, y, lat, lon, mapinfo)\n    use module_llxy_generic\n    implicit none\n    real, intent(in) :: lat, lon\n    real, intent(out) :: x, y\n    type(hrldas_mapinfo_type) :: mapinfo\n\n    call xytoll_generic(x, y, lat, lon, &\n         mapinfo%projection, mapinfo%dxm*1.E-3, mapinfo%lat1, mapinfo%lon1, 1.0, 1.0, &\n         mapinfo%xlonc, mapinfo%truelat1, mapinfo%truelat2)\n\n  end subroutine xytoll_hrldas\n\n!------------------------------------------------------------------------------\n! Subroutine handle_error\n!------------------------------------------------------------------------------\n\n  subroutine handle_error(ival, str)\n    implicit none\n    integer, intent(in) :: ival\n    character(len=*), intent(in) :: str\n\n    if (ival == NF90_NOERR) return\n\n    print*, \"----ERROR---------------------------------------------------\"\n    print *, trim(nf90_strerror(ival))\n    if (str /= \"\") print *, str\n    print*, \"------------------------------------------------------------\"\n    stop\n  end subroutine handle_error\n\n!------------------------------------------------------------------------------\n! Subroutine handle_warning\n!------------------------------------------------------------------------------\n\n  subroutine handle_warning(ival, str)\n    implicit none\n    integer, intent(in) :: ival\n    character(len=*), intent(in) :: str\n\n    if (ival == NF90_NOERR) return\n\n    print*, \"----WARNING-------------------------------------------------\"\n    print *, trim(nf90_strerror(ival))\n    if (str /= \"\") print *, str\n    print*, \"------------------------------------------------------------\"\n  end subroutine handle_warning\n\nend module module_hrldas_netcdf\n\n!------------------------------------------------------------------------------\n! ****************************************************************************\n!------------------------------------------------------------------------------\n\nprogram hrldas_extract_point\n!\n! Given a lat/lon pair or an x/y pair, find the nearest grid point\n! and print out all data from that point over a specified period of\n! time.\n!\n  use arguments_module\n  use module_date_utilities\n  use module_hrldas_netcdf\n  implicit none\n\n  real    :: lat\n  real    :: lon\n  real    :: x\n  real    :: y\n  integer :: ival\n  integer :: jval\n  character(len=256) :: flnm\n  character(len=256) :: datadir\n  integer :: outunit = 10\n\n  integer :: ierr\n  integer :: ncid\n  type(hrldas_mapinfo_type) :: mapinfo\n\n  character(len=10) :: nowdate, startdate, enddate\n\n\n  arguments_help = '(\" [-lat <latitude>] [-lon <longitude>] \",/,&\n       &\"              [-x <x-coordinate>] [-y <y-coordinate>]\",/,&\n       & \"             -startdate <yyyymmddhh> -enddate <yyyymmddhh> <LDASOUT directory>\")'\n\n\n!------------------------------------------------------------------------------\n! Handle the command-line arguments.\n!------------------------------------------------------------------------------\n\n  call arg(\"-startdate\",  startdate)\n  call arg(\"-enddate\", enddate)\n  call arg(\"-lat\", -1.E33, lat)\n  call arg(\"-lon\", -1.E33, lon)\n  call arg(\"-x\",   -1.E33, x)\n  call arg(\"-y\",   -1.E33, y)\n  call arg(\"Null\", datadir)\n\n  if ( (lat > -1.E25) .and. (lon > -1.E25)) then\n     if ((x > -1.E25) .or. (y > -1.E25)) then\n        write(*,'(/,\"  ***** Lat/lon specified.  Do not specify x/y *****\")')\n        call print_help\n     endif\n  else if ( (x > -1.E25) .and. (y > -1.E25)) then\n     if ((lat > -1.E25) .or. (lon > -1.E25)) then\n        write(*,'(/,\"  ***** X/y specified.  Do not specify lat/lon *****\")')\n        call print_help\n     endif\n  else\n     write(*,'(/,\"  ***** Point not specified.                         *****\")')\n     write(*,'(  \"  ***** Specify desired point in lat/lon or in x/y.  *****\")')\n     call print_help\n  endif\n\n  if (datadir == \"Null\") then\n     write(*,'(/,\"  ***** Directory name not specified. *****\")')\n     call print_help\n  endif\n\n!------------------------------------------------------------------------------\n! Start us off at the starting time, and loop until our end time\n!------------------------------------------------------------------------------\n\n  nowdate = startdate\n  TIMELOOP : do while ( nowdate <= enddate )\n     print*, nowdate\n\n     !------------------------------------------------------------------------------\n     ! Get map information\n     !------------------------------------------------------------------------------\n\n     flnm = trim(datadir)//\"/\"//nowdate//\".LDASOUT_DOMAIN1\"\n     call get_map_info(trim(flnm), ncid, mapinfo)\n\n     !------------------------------------------------------------------------------\n     ! Get integer Ival/Jval values of the requested point.\n     !------------------------------------------------------------------------------\n\n     if ( (lat > -1.E25) .and. (lon > -1.E25) ) then\n\n        call lltoxy_hrldas(lat, lon, x, y, mapinfo)\n        write(*, '(\"lat, lon = \", F8.4, 1x, F9.4, \",    x, y = \", F9.4, 1x, F9.4)') &\n             lat, lon, x, y\n\n     else\n\n        call xytoll_hrldas(x, y, lat, lon, mapinfo)\n        write(*, '(\"x, y = \", F9.4, 1x, F9.4, \",    lat, lon = \", F8.4, 1x, F9.4)') &\n             x, y, lat, lon\n\n     endif\n\n     ival = int(x)\n     jval = int(y)\n\n     !------------------------------------------------------------------------------\n     ! Make the header for the table.\n     !------------------------------------------------------------------------------\n\n     if (nowdate == startdate) call make_header(ncid, outunit, lat, lon, ival, jval)\n\n     !------------------------------------------------------------------------------\n     ! Loop through the list of variables, pulling out all data at the I/J point.\n     !------------------------------------------------------------------------------\n\n     call loop_through_variable_list(ncid, ival, jval, nowdate, outunit)\n\n     !------------------------------------------------------------------------------\n     ! Shut things down for this time period before proceeding to the next.\n     !------------------------------------------------------------------------------\n\n     call close_hrldas_file(ncid)\n\n     !------------------------------------------------------------------------------\n     ! Update our time and repeat the time loop.\n     !------------------------------------------------------------------------------\n\n     call geth_newdate(nowdate, nowdate, 1)\n\n  enddo TIMELOOP\n\nend program hrldas_extract_point\n\n!------------------------------------------------------------------------------\n! Subroutine make_header\n!------------------------------------------------------------------------------\n\nsubroutine make_header(ncid, outunit, lat, lon, ival, jval)\n  use module_hrldas_netcdf\n  implicit none\n  integer,          intent(in) :: ncid\n  integer,          intent(in) :: outunit\n  real,             intent(in) :: lat\n  real,             intent(in) :: lon\n  integer,          intent(in) :: ival\n  integer,          intent(in) :: jval\n\n  character(len=NF90_MAX_NAME) :: varname\n  integer :: xtype\n  integer :: ndims\n  integer, dimension(NF90_MAX_VAR_DIMS) :: dimids\n  integer :: natts\n  integer :: ierr\n  integer :: varid\n  integer :: nvars\n  integer :: idim\n  character(len=NF90_MAX_NAME), dimension(NF90_MAX_DIMS) :: dimname\n  integer                     , dimension(NF90_MAX_DIMS) :: dimlen\n  character(len=18) :: blank = \"                  \"\n  integer :: zdim\n  integer :: i\n  character(len=18) :: text\n\n  write(outunit,'(\"lat/lon:  \", F12.6, F12.6, \"      Grid I/J: \", I6, I6)') lat, lon, ival, jval\n\n\n  ierr = nf90_inquire(ncid, nVariables=nvars)\n  call handle_error(ierr, \"Trying to find number of variables.\")\n\n!------------------------------------------------------------------------------\n! A preliminary loop through the variables to get the heading for the output files.\n!------------------------------------------------------------------------------\n  do varid = 1, nvars\n\n     ierr = nf90_inquire_variable(ncid, varid, varname, xtype, ndims, dimids, nAtts)\n     call handle_error(ierr, \"Inquiring about a variable.\")\n\n     do idim = 1, ndims\n        ierr = nf90_inquire_dimension(ncid, dimids(idim), dimname(idim), dimlen(idim))\n        call handle_error(ierr, \"Trying to get dimension information for variable \"//trim(varname))\n        if (dimname(idim) == \"soil_layers_stag\") zdim = dimlen(idim)\n     enddo\n\n     if (any(dimname == \"soil_layers_stag\")) then\n        do i = 1, zdim\n           write(text, '(A, \"(\",i1,\")\")') trim(varname), i\n           write(outunit, '(A18)', advance=\"no\") blank(1:(18-len_trim(text))/2)//text\n        enddo\n     else\n        write(outunit, '(A18)', advance=\"no\") blank(1:(18-len_trim(varname))/2)//varname\n     endif\n\n  enddo\n  write(outunit,*)\nend subroutine make_header\n\n!------------------------------------------------------------------------------\n! Subroutine loop_through_variable_list\n!------------------------------------------------------------------------------\n\nsubroutine loop_through_variable_list(ncid, ival, jval, nowdate, outunit)\n  use module_hrldas_netcdf\n  implicit none\n  integer,          intent(in) :: ncid\n  integer,          intent(in) :: ival\n  integer,          intent(in) :: jval\n  character(len=*), intent(in) :: nowdate\n  integer,          intent(in) :: outunit\n\n  integer                      :: nvars\n  integer                      :: varid\n  integer                      :: ierr\n\n  integer :: idim\n  integer :: i\n\n  ! Information returned from nf90_inquire_variable:\n  character(len=NF90_MAX_NAME) :: varname\n  integer :: xtype\n  integer :: ndims\n  integer, dimension(NF90_MAX_VAR_DIMS) :: dimids\n  integer :: natts\n\n  character(len=NF90_MAX_NAME) :: dimname\n  integer                      :: dimlen\n\n  !\n  integer, dimension(NF90_MAX_DIMS) :: start\n  integer, dimension(NF90_MAX_DIMS) :: array_count\n  real                              :: xval\n  real, allocatable, dimension(:)   :: xarr\n  integer                           :: idata\n  logical                           :: multi_layer\n\n  character(len=1), dimension(19)   :: hdata\n  character(len=19)                 :: hdate\n\n!------------------------------------------------------------------------------\n! Find the number of variables in the file.\n!------------------------------------------------------------------------------\n\n  ierr = nf90_inquire(ncid, nVariables=nvars)\n  call handle_error(ierr, \"Trying to find number of variables.\")\n  print*, 'nvars = ', nvars\n\n!------------------------------------------------------------------------------\n! Loop through the variables\n!------------------------------------------------------------------------------\n  do varid = 1, nvars\n\n     ierr = nf90_inquire_variable(ncid, varid, varname, xtype, ndims, dimids, nAtts)\n     call handle_error(ierr, \"Inquiring about a variable.\")\n\n     start = 1\n     array_count = 1\n     if (allocated(xarr)) deallocate(xarr)\n     multi_layer = .FALSE.\n\n!------------------------------------------------------------------------------\n! Loop over the number of dimensions on the variable, making sure we get the\n! right indices in the right order.\n!------------------------------------------------------------------------------\n     do idim = 1, ndims\n        ierr = nf90_inquire_dimension(ncid, dimids(idim), dimname, dimlen)\n        call handle_error(ierr, \"Trying to get dimension information for variable \"//trim(varname))\n\n        if (dimname == \"west_east\") then\n           start(idim) = ival\n        else if (dimname == \"south_north\") then\n           start(idim) = jval\n        else if (dimname == \"soil_layers_stag\") then\n           array_count(idim) = dimlen\n           allocate(xarr(dimlen))\n           multi_layer = .TRUE.\n        else if ( (dimname == \"Times\") .or. (dimname == \"Time\") )then\n           if (dimlen /= 1) then\n              stop \"So far, this program only handles single-time per output file.  Sorry.\"\n           endif\n           start(idim) = 1\n           array_count(idim) = 1\n        else if (dimname == \"DateStrLen\") then\n           start(idim) = 1\n           array_count(idim) = dimlen\n        else\n           print*, 'Unrecognzied dimension:  ', trim(dimname)\n           stop \"Unrecognized dimension.\"\n        endif\n     enddo\n\n     if (xtype == NF90_FLOAT) then\n\n        if (multi_layer) then\n           ierr = nf90_get_var(ncid, varid, xarr, start(1:ndims), array_count(1:ndims))\n           call handle_error(ierr, \"Trying to get variable \"//trim(varname))\n           ! print*, varid, trim(varname), xarr(1:ndims)\n           do i = 1, ndims\n              write(outunit, '(G18.10)', advance=\"no\") xarr(i)\n           enddo\n        else\n           ierr = nf90_get_var(ncid, varid, xval, start(1:ndims))\n           call handle_error(ierr, \"Trying to get variable \"//trim(varname))\n           write(outunit, '(G18.10)', advance=\"no\") xval\n           ! print*, varid, trim(varname), xval\n        endif\n\n     else if (xtype == NF90_INT) then\n        if (multi_layer) stop \"No multi-layer integer variables expected.\"\n\n        ierr = nf90_get_var(ncid, varid, idata, start(1:ndims))\n        call handle_error(ierr, \"Trying to get variable \"//trim(varname))\n        write(outunit, '(I18)', advance=\"no\") idata\n\n     else if (xtype == NF90_CHAR) then\n        ierr = nf90_get_var(ncid, varid, hdata, start, array_count)\n        call handle_error(ierr, \"Trying to get variable \"//trim(varname))\n        hdate = \" \"\n        if (hdata(1) == char(0)) then\n           hdate = nowdate(1:4)//\"-\"//nowdate(5:6)//\"-\"//nowdate(7:8)//\"_\"//nowdate(9:10)\n        else\n           do i = 1, 19\n              hdate(i:i) = hdata(i)\n           enddo\n        endif\n        write(outunit, '(A18)', advance=\"no\") hdate(1:13)\n\n     else\n        print*, varid, trim(varname), \" ??? xtype = \", xtype\n        stop \"Unexpected variable type\"\n     endif\n  enddo\n  write(outunit,*)\n\nend subroutine loop_through_variable_list\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/lccone.F",
    "content": "subroutine lccone (fsplat,ssplat,sign,confac)\n  real, parameter :: conv=0.01745329251994\n  integer :: sign\n  real :: fsplat,ssplat,confac\n  if (abs(fsplat-ssplat).lt.1.E-2) then\n     confac = sin(fsplat*conv)\n  else\n     confac = log10(cos(fsplat*conv))-log10(cos(ssplat*conv))\n     confac = confac/(log10(tan((45.-float(sign)*fsplat/2.)*conv))-&\n          log10(tan((45.-float(sign)*ssplat/2.)*conv)))\n  endif\nend subroutine lccone\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/llxy_generic.F",
    "content": "module module_llxy_generic\n\n  real, parameter, private :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter, private :: piovr2 = pi/2.\n!  real, parameter, private :: re = 6370.949     ! the radius of the earth in km\n  real, parameter, private :: re = 6371.2       ! the radius of the earth in km\n  real, parameter, private :: twopi  = pi*2.\n  real, parameter, private :: degrad = pi/180.\n  real, parameter, private :: ce = 2.*pi*re     ! the circumference of the earth in km\n\n\ncontains\n\n!=======================================================================================\n!=======================================================================================\n\n  subroutine lltoxy_generic (xlat,xlon,x,y, &\n       project,dskm,reflat,reflon,refx,refy,&\n       cenlon,truelat1,truelat2)\n\n!*****************************************************************************!\n!  Notes    - Modeled after XYTOLL in the plots.o library                     !\n!*****************************************************************************!\n\n    implicit none\n\n! Input: ---------------------------------------------------------------------!\n\n    real ::             xlat       ! latitude of the point of interest.\n    real ::             xlon       ! longitude of the point of interest.\n    character(LEN=2) :: project    ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n    real ::             dskm         ! grid distance in km\n    real ::             reflat\n    real ::             reflon\n    real ::             refx\n    real ::             refy\n    real ::             cenlon     ! Grid ratio with respect to MOAD\n    real ::             truelat1   ! True latitude 1, closest to equator\n    real ::             truelat2   ! True latitude 2, closest to pole\n\n! Output: --------------------------------------------------------------------!\n\n    real ::             x          ! x location of the given (lat,lon) point\n    real ::             y          ! y location of the given (lat,lon) point\n\n!  Real variables: -----------------------------------------------------------!\n\n    real          :: flat1\n    real          :: confac            ! cone factor\n    real          :: rcln              ! center longitude in radians  (local)\n    real          :: dj                ! distance from pole to point  (local)\n    real          :: di                ! distance from the central\n    !  meridian to the point        (local)\n    real          :: bm                ! calculation variable         (local)\n\n    real :: rflt, rfln, rlat, rlon, diovrdj, disdjs, ri, rj\n    real :: ct1, st1, tt1, drp\n    real :: isn, pi2\n    real :: londiff\n\n!****************************  subroutine begin  *****************************!\n\n\n    rlat =  xlat * degrad\n    rlon =  xlon * degrad\n    rcln = cenlon * degrad\n    flat1 = truelat1 * degrad\n    rflt = reflat * degrad\n    rfln = reflon * degrad\n\n    if ((xlon - cenlon) < -180) then\n       londiff = ((xlon-cenlon)+360.)*degrad\n    else if ((xlon - cenlon) > 180) then\n       londiff = ((xlon-cenlon)-360.)*degrad\n    else\n       londiff = (xlon-cenlon)*degrad\n    endif\n\n    if (project(1:2) .eq. 'ME') then\n\n       ct1 = re*cos(flat1)\n       dj = ct1 * log(tan (0.5*(rlat + piovr2)))\n       di = ct1 * (rlon - rfln)\n       y = refy +(dj + ct1 * log(cos(rflt)/(1 + sin(rflt))))/dskm\n       x = refx + di/dskm\n\n    else if (project(1:2) .eq. 'CE') then\n\n!KWM     dj = re*(rlat-rflt)\n!KWM     di = re*(rlon-rfln)\n!KWM     y = refy + dj/dskm\n!KWM     x = refx + di/dskm\n\n       ! NOTE:  Cylindrical Equidistant grid increment expressed in terms \n       ! of thousandths of degrees!\n       !  Calculate the distance from the horizontal axis to (J,I)\n       dj = xlat-reflat\n       di = xlon-reflon\n       y = refy + (dj/dskm)\n       x = refx + (di/dskm)\n\n    else if (project(1:2) .eq. 'LC') then\n\n       isn = sign(1.0, truelat2)\n       pi2 = piovr2*isn\n\n       call lccone(truelat1,truelat2,int(sign(1.0, truelat2)),confac)\n       tt1 = tan((pi2 - flat1)*0.5) ! Tangent Term 1.\n       st1 = sin (pi2 - flat1) * re/(confac*dskm)     ! Sine Term 1.\n       bm =  tan((pi2 - rlat)*0.5)\n       if ((rlon-rcln) > pi) then\n          diovrdj = -tan(((rlon-rcln)-2.*pi)*confac)\n       elseif ((rlon-rcln) < -pi) then\n          diovrdj = -tan(((rlon-rcln)+2.*pi)*confac)\n       else\n          diovrdj = -tan((rlon-rcln)*confac)\n       endif\n       disdjs = ( (bm/tt1)**confac * st1)**2\n       ! Dj: y distance (km) from pole to given x/y point.\n       dj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n       ! Di: x distance (km) from central longitude to given x/y point.\n       di = dj * diovrdj\n\n       bm = tan((pi2-rflt)*0.5)\n       if ((rfln-rcln) > pi) then\n          diovrdj = -tan(((rfln-rcln)-2.*pi)*confac)\n       else if ((rfln-rcln) < -pi) then\n          diovrdj = -tan(((rfln-rcln)+2.*pi)*confac)\n       else\n          diovrdj = -tan((rfln - rcln)*confac)\n       endif\n       disdjs = ( (bm/tt1)**confac * st1)**2\n       ! Rj: y distance (km) from pole to reference point.\n       rj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n       ! Ri: x distance (km) from central longitude to reference x/y point.\n       ri = rj * diovrdj\n       y = refy + isn*(dj - rj)\n       x = refx + (di - ri)\n\n    else if (project(1:2) .eq. 'ST') then\n\n       isn = sign(1.0, truelat1)\n       pi2 = piovr2*isn\n\n       diovrdj = -tan(rfln-rcln)\n       bm = (re/dskm)*tan(0.5*(pi2-rflt))\n       disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n       ! RJ:  Distance from pole to reference latitude along the center lon\n       rj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rfln-rcln))\n       ! RI:  Distance from center reference to requested point rlat, rlon.\n       ri = rj * diovrdj\n       diovrdj = -tan(rlon-rcln)\n       bm = (re/dskm)*tan(0.5*(pi2-rlat))\n       disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n       dj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rlon-rcln))\n       di = dj * diovrdj\n       y = refy + isn*(dj-rj)\n       x = refx + (di-ri)\n    endif\n\n!*****************************  Subroutine End  ******************************!\n\n  end subroutine lltoxy_generic\n\n!=======================================================================================\n!=======================================================================================\n\n  subroutine xytoll_generic (x,y,xlat,xlon,&\n       project,dskm,reflat,reflon,refx,refy,&\n       cenlon, truelat1,truelat2)\n\n!*****************************************************************************!\n!  xytoll                                                                     !\n!  Purpose  - To  transform  mesoscale grid point coordinates (x,y) into      !\n!             latitude and longitude coordinates.                             !\n!                                                                             !\n!  On entry - X  and  Y are an ordered pair representing a grid point in  the !\n!             mesoscale grid.                                                 !\n!                                                                             !\n!  On exit  - XLAT, XLON contain  the latitude and longitude respectively     !\n!             that resulted from the transformation.                          !\n!                                                                             !\n!*****************************************************************************!\n    implicit none\n\n! Input\n    real ::             x         ! x (i) coordinate of point of interest\n    real ::             y         ! y (j) coordinate of point of interest\n    character(LEN=2) :: project   ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n    real ::             dskm      ! grid distance in km\n    real ::             reflat    ! latitude of the reference point\n    real ::             reflon    ! longitude of the reference point\n    real ::             refx\n    real ::             refy\n    real ::             cenlon    ! longitude of the center of the projection\n    real ::             truelat1  ! True latitude 1.\n    real ::             truelat2  ! True latitude 2.\n\n! Output\n    real ::             xlat      ! latitude of point (x,y)\n    real ::             xlon      ! longitude of point (x,y)\n\n\n!  Real variables\n\n    real ::            confac           ! cone factor\n    real ::            rfln             ! reference longitude in radians  (local)\n    real ::            rflt             ! reference latitude in radians   (local)\n    real ::            rcln             ! center longitude in radians  (local)\n    real ::            dj, drp, djj     ! distance from the central\n!                                       meridian to the point        (local)\n    real ::            di,dii           ! distance from pole to point  (local)\n    real ::            bm               ! calculation variable         (local)\n    real ::            flat1\n    real ::            ct1, tt1, tt2, pi2\n    integer :: isn\n!****************************  subroutine begin  *****************************!\n\n    rflt = reflat * degrad\n    rfln = reflon * degrad\n    rcln = cenlon * degrad\n    flat1 = truelat1 * degrad\n\n!  If the projection is mercator ('ME') then ...\n\n    if (project(1:2) .eq. 'ME') then\n       di = (x-refx) * dskm\n       !  Calculate the distance the point in question is from the pole\n       dj = -re * cos(flat1)*log(cos(rflt)/(1 + sin(rflt))) + &\n            (y - refy) * dskm\n       !  Calculate the latitude desired in radians\n       xlat = 2.0 * atan(exp(dj/(re*cos(flat1)))) - piovr2\n       !  Calculate the longitude desired in radians\n       xlon = rfln + di/(re*cos(flat1))\n\n       !  Convert the calculated lat,lon pair into degrees\n       xlat = xlat * 180.0/pi\n       xlon = xlon * 180.0/pi\n\n\n! If the projection is cylindrical equidistant ('CE') then ...\n    else if (project(1:2) .eq. 'CE') then\n       ! NOTE:  Cylindrical Equidistant grid increment expressed in terms \n       ! of thousandths of degrees!\n       di = (x-refx) * dskm\n       !  Calculate the distance from the horizontal axis to (J,I)\n       dj = (y-refy) * dskm\n       !  Determine the shift north-south\n       xlat = reflat + dj\n       !  Determine the shift east-west\n       xlon = reflon + di\n\n! If the projection is lambert conic conformal ('LC') then ...\n    else if (project(1:2) .eq. 'LC') then\n\n       isn = sign(1.0, truelat2)\n       pi2 = piovr2*isn\n\n       call lccone(truelat1,truelat2,isn,confac)\n\n       tt1 = tan((pi2 - flat1)*0.5)    ! Tangent Term 1.\n       tt2 = tan((pi2 - rflt  )*0.5)    ! Tangent Term 2.\n       ct1 = -cos(flat1) * re/confac   ! cosine Term 1.\n\n       ! Calculate the (projected) distance from the pole to\n       ! the reference lat/lon.\n       drp = ct1 * (tt2/tt1)**confac\n       ! Now from the pole to the reference y along the center lon.\n       djj = drp * cos((rcln-rfln)*confac)\n\n       ! Now from the pole to the requested y along the center lon.\n       dj = djj + isn * ((y-refy)*dskm)\n       ! Now the (projected) distance from center longitude to reference x\n       dii = drp*sin((rcln-rfln)*confac)\n       ! And now from center longitude to requested X\n       di = dii + ((x-refx)*dskm)\n       !  Calculate the Big Messy equation\n       bm = tt1 * (sqrt(di**2+dj**2) /  abs(ct1))**(1.0/confac)\n       !  Calculate the desired latitude in radians\n       xlat = pi2 - 2.0*atan(bm)\n       !  Calculate the desired longitude in radians\n       xlon = rcln + (1.0/confac) * atan2(di,-dj)\n       !  Convert the calculated lat,lon pair into degrees\n       xlat = xlat * 180.0/pi\n       xlon = xlon * 180.0/pi\n\n\n!  If the projection is polar stereographic ('ST') then ...\n\n    else if (project(1:2) .eq. 'ST') then\n\n       isn = sign(1.0, truelat1)\n       pi2 = piovr2*isn\n\n\n!  Calculate the (projected) y-distance I,J lies from the pole\n\n       drp = -re*cos(rflt) * (1.0 + cos(pi2-flat1)) / (1.0 + cos(pi2-rflt))\n       djj = drp * cos(rcln-rfln)\n       dj = djj + isn*( (y-refy) * dskm )\n       dii = drp * sin(rcln-rfln)\n       di = dii + ((x-refx)*dskm)\n       ! Calculate the Big Messy quantity as would be done for LC\n       ! projections.  This quantity is different in value, same\n       ! in purpose of BM above\n       bm = (1.0/re) * sqrt(di*di + dj*dj) / (1.0 + cos(pi2-flat1))\n       !  Calculate the desired latitude in radians\n       xlat = pi2 - isn*2.0 * atan(bm)\n       !  Calculate the desired longitude in radians\n       xlon = rcln + atan2(di,-dj)\n\n       !  Convert the calculated lat,lon pair into degrees\n       xlat = xlat * 180.0/pi\n       xlon = xlon * 180.0/pi\n\n    else\n       print*, 'Unrecognized project:  ', project\n       stop\n    end if\n\n!  Make sure no values are greater than 180 degrees and none\n!  are less than -180 degrees\n\n    if (xlon .gt. 180.0)  xlon = xlon - 360.0\n    if (xlon .lt. -180.0) xlon = xlon + 360.0\n\n!*****************************  Subroutine End  ******************************!\n\n  end subroutine xytoll_generic\n\n!=======================================================================================\n!=======================================================================================\n\n  subroutine lccone ( fsplat, ssplat, sign, confac )\n    implicit none\n    integer, intent(in)  :: sign\n    real,    intent(in)  :: fsplat\n    real,    intent(in)  :: ssplat\n    real,    intent(out) :: confac\n\n    if (abs(fsplat-ssplat).lt.1.E-2) then\n       confac = sin(fsplat*degrad)\n    else\n       confac = log10(cos(fsplat*degrad))-log10(cos(ssplat*degrad))\n       confac = confac/(log10(tan((45.-float(sign)*fsplat/2.)*degrad))-&\n            log10(tan((45.-float(sign)*ssplat/2.)*degrad)))\n    endif\n  end subroutine lccone\n\nend module module_llxy_generic\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/modify_wrfinput.F",
    "content": "module module_modify_wrfinput\n  use netcdf\n\ncontains\n\n  subroutine find_dimension(ncid, name, idim)\n    !\n    ! Given an NCID and a dimension name, return the dimension value.\n    !\n    implicit none\n    ! Input:\n    integer, intent(in)          :: ncid\n    character(len=*), intent(in) :: name\n    ! Output:\n    integer, intent(out)         :: idim\n\n    ! Local:\n    integer :: iret, dimid\n\n    iret = nf90_inq_dimid(ncid, trim(name), dimid)\n    call error_handler(iret, failure=\"Problem finding dimension id for '\"//trim(name)//\"'\")\n\n    iret = nf90_inquire_dimension(ncid, dimid, len=idim)\n    call error_handler(iret, failure=\"Problem finding '\"//trim(name)//\"' dimension value\")\n  end subroutine find_dimension\n\n  subroutine error_handler(status, failure, success)\n    !\n    ! Check the error flag from a NetCDF function call, and print appropriate\n    ! error message.\n    !\n    implicit none\n    integer,                    intent(in) :: status\n    character(len=*), optional, intent(in) :: failure\n    character(len=*), optional, intent(in) :: success\n    if (status .ne. NF90_NOERR) then\n       write(*,'(/,A)') nf90_strerror(status)\n       if (present(failure)) then\n          write(*,'(/,\" ***** \", A,/)') failure\n       endif\n       stop 'Stopped'\n    endif\n    if (present(success)) then\n       write(*,'(A)') success\n    endif\n  end subroutine error_handler\n\n\nend module module_modify_wrfinput\n\n\nprogram modify_wrfinput\n  use module_modify_wrfinput\n  implicit none\n  character(len=256) :: wrfinput = \" \"\n  character(len=256) :: ldasout = \" \"\n  integer, external :: iargc\n  integer :: numarg\n\n  integer :: i\n  integer :: iret, wrf_ncid, ldas_ncid, copy_ncid\n  integer :: ix, jx,lx\n  logical :: do_urban = .FALSE.\n  character(len=256) :: arg\n\n  numarg = iargc()\n\n  if ((numarg /= 2) .and. (numarg /= 3)) then\n     print*, 'Usage:  modify_wrfinput [-urban] [-help] <wrfinput> <ldasout>'\n     print*, '           Where <wrfinput> is the destination file'\n     print*, '             and <ldasout> is the source file.'\n     stop\n  else\n     ARGLOOP : do i = 1, numarg\n        call getarg (i, arg)\n        if ((arg == \"-urban\") .or. (arg == \"--urban\")) then\n           do_urban = .TRUE.\n           cycle ARGLOOP\n        endif\n        if (( arg == \"-h\") .or. (arg == \"-help\") .or. (arg == \"--help\") ) then\n           print*, 'Usage:  modify_wrfinput [-urban] [-help] <wrfinput> <ldasout>'\n           print*, '           Where <wrfinput> is the destination file'\n           print*, '             and <ldasout> is the source file.'\n           stop\n        endif\n        if ( arg(1:1) == \"-\") then\n           ! All arguments beginning with \"-\" should have been processed by now.\n           print*, 'Unrecognized argument:  ', trim(arg)\n           print*, 'Usage:  modify_wrfinput [-urban] [-help] <wrfinput> <ldasout>'\n           print*, '           Where <wrfinput> is the destination file'\n           print*, '             and <ldasout> is the source file.'\n           stop\n        endif\n        if (wrfinput == \" \") then\n           wrfinput = arg\n           cycle ARGLOOP\n        endif\n        if (ldasout == \" \") then\n           ldasout = arg\n           cycle ARGLOOP\n        endif\n     enddo ARGLOOP\n  endif\n\n  iret = nf90_open(trim(wrfinput), NF90_NOWRITE, wrf_ncid)\n  call error_handler(iret, failure=\"Problem opening file '\"//trim(wrfinput)//\"'\")\n  write(*, '(A, I5)') \"Opening NetCDF wrfinput file '\"//trim(wrfinput)//\"' with wrf_ncid = \", &\n       wrf_ncid\n\n  iret = nf90_open(trim(ldasout), NF90_NOWRITE, ldas_ncid)\n  call error_handler(iret, failure=\"Problem opening file '\"//trim(ldasout)//\"'\")\n  write(*, '(A, I5)') \"Opening NetCDF ldasout file '\"//trim(ldasout)//\"' with ldas_ncid = \", &\n       ldas_ncid\n\n  iret = nf90_create(\"new.nc\", NF90_CLOBBER, copy_ncid)\n  call error_handler(iret, failure=\"Problem creating file 'new.nc'\")\n\n! Copy a dataset   Causes mysterious crashes!\n  call copy_dataset(wrf_ncid, copy_ncid)\n\n  ! Find dimensions\n  call find_dimension(wrf_ncid, \"west_east\", ix)\n  call find_dimension(wrf_ncid, \"south_north\", jx)\n  call find_dimension(wrf_ncid, \"soil_layers_stag\", lx)\n\n  iret = nf90_close(wrf_ncid)\n  call error_handler(iret, failure=\"Problem closing wrf_ncid\")\n\n  iret = nf90_open(\"new.nc\", NF90_WRITE, copy_ncid)\n  call error_handler(iret, failure=\"Problem opening file 'new.nc'\")\n  wrf_ncid = copy_ncid\n\n  !\n  ! Replace existing fields in our copy.\n  !\n  call copy_replace(ldas_ncid, \"CANWAT\", wrf_ncid, \"CANWAT\")\n  call copy_replace(ldas_ncid, \"SOIL_M\", wrf_ncid, \"SMOIS\")\n  call copy_replace(ldas_ncid, \"SOIL_W\", wrf_ncid, \"SH2O\")\n  call copy_replace(ldas_ncid, \"SOIL_T\", wrf_ncid, \"TSLB\")\n  call copy_replace(ldas_ncid, \"VEGFRA\", wrf_ncid, \"VEGFRA\")\n  !\n  ! Add new fields in our copy.\n  !\n  if (do_urban) then\n     call copy_new(ldas_ncid, \"TC\", wrf_ncid, \"TC_URB\")\n     call copy_new(ldas_ncid, \"TR\", wrf_ncid, \"TR_URB\")\n     call copy_new(ldas_ncid, \"TG\", wrf_ncid, \"TG_URB\")\n     call copy_new(ldas_ncid, \"TB\", wrf_ncid, \"TB_URB\")\n     call copy_new(ldas_ncid, \"TRL\", wrf_ncid, \"TRL_URB\")\n     call copy_new(ldas_ncid, \"TGL\", wrf_ncid, \"TGL_URB\")\n     call copy_new(ldas_ncid, \"TBL\", wrf_ncid, \"TBL_URB\")\n  endif\n\n  iret = nf90_close(wrf_ncid)\n  call error_handler(iret, failure=\"Problem closing wrf_ncid\")\n  print*, 'Normal termination of modify_wrfinput'\n\nend program modify_wrfinput\n\nsubroutine copy_replace(source_ncid, source_name, dest_ncid, dest_name)\n  !\n  ! Copy the variable named <source_name> from dataset <source_ncid> to\n  ! variable named <dest_name> in dataset <dest_ncid>.\n  !\n  use module_modify_wrfinput\n  implicit none\n  integer, intent(in) :: source_ncid, dest_ncid\n  character(len=*), intent(in) :: source_name, dest_name\n\n  integer :: source_varid, dest_varid, source_nvdims, dest_nvdims\n\n  real, allocatable, dimension(:,:,:,:) :: xdum\n  real, allocatable, dimension(:,:,:,:) :: dest_gone\n  integer :: iret\n  integer :: xtype, dest_xtype\n\n  integer, dimension(NF90_MAX_VAR_DIMS) :: vstart\n  integer, dimension(NF90_MAX_VAR_DIMS) :: vcount\n  integer, dimension(NF90_MAX_VAR_DIMS) :: source_dimids\n  integer, dimension(NF90_MAX_VAR_DIMS) :: dest_dimids\n\n  integer :: j, destdim\n\n\n  iret = nf90_inq_varid(source_ncid, source_name, source_varid)\n  call error_handler(iret, failure=\"Problem returning varid of field '\" & \n       //trim(source_name)//\"' for source\")\n\n  iret = nf90_inq_varid(dest_ncid, dest_name, dest_varid)\n  call error_handler(iret, failure=\"Problem returning varid of field '\" & \n       //trim(dest_name)//\"' for destination\")\n\n  iret = nf90_inquire_variable(source_ncid, source_varid, &\n       xtype=xtype, ndims=source_nvdims, dimids=source_dimids)\n  call error_handler(iret, failure=\"Problem inquiring variable.\")\n\n  iret = nf90_inquire_variable(dest_ncid, dest_varid, &\n       xtype=dest_xtype, ndims=dest_nvdims, dimids=dest_dimids)\n  call error_handler(iret, failure=\"Problem inquiring variable.\")\n\n  print*, 'name = ', trim(source_name), source_nvdims\n\n  if (xtype /= dest_xtype) then\n     print*, \"Field types do not match.\"\n     stop\n  endif\n\n  if (source_nvdims /= dest_nvdims) then\n     print*, 'source_nvdims = ', source_nvdims\n     print*, 'dest_nvdims = ', dest_nvdims\n     stop \"field dimensions do not match\"\n  endif\n\n  ! The numbers of dimensions match.  Continue.\n\n  if (source_nvdims > 4) stop \"nvdims problem\"\n\n  ! We have an appropriate number of dimensions.  Continue\n\n  vstart = 1\n  vcount = 1\n\n  do j = 1, source_nvdims\n     iret = nf90_inquire_dimension(source_ncid, source_dimids(j), len=vcount(j))\n     call error_handler(iret, failure=\"Problem inquiring dimension\")\n     iret = nf90_inquire_dimension(dest_ncid, dest_dimids(j), len=destdim)\n     call error_handler(iret, failure=\"Problem inquiring dimension\")\n\n     if (vcount(j) /= destdim) then\n        print*, 'source_dims = ', vcount(1:source_nvdims)\n        print*, 'source_dim  = ', vcount(j)\n        print*, 'dest_dims   = ', destdim\n        stop \"field dimensions do not match\"\n     endif\n  enddo\n\n  ! The sizes of dimension match.  Continue\n\n  if (xtype == NF90_FLOAT) then\n\n     allocate(xdum(vcount(1),vcount(2),vcount(3),vcount(4)))\n     allocate(dest_gone(vcount(1),vcount(2),vcount(3),vcount(4)))\n\n     iret = nf90_get_var(source_ncid, source_varid, xdum, start=vstart, count=vcount)\n     call error_handler(iret, failure=\"Problem getting variable\")\n\n     if (source_name == \"VEGFRA\") then\n        ! Vegetation fraction in wrfinput file is in percent, not in fraction.\n        write(*,'(/,\" ***** Scaling VEGFRA by 100.0 for transport to wrfinput file.\",/)')\n        xdum = xdum * 100.0\n     endif\n\n     iret = nf90_get_var(dest_ncid, dest_varid, dest_gone, start=vstart, count=vcount)\n     call error_handler(iret, failure=\"Problem getting variable\")\n\n     where (xdum < -1.E25) xdum = dest_gone\n\n     iret = nf90_put_var(dest_ncid, dest_varid, xdum, start=vstart, count=vcount)\n     call error_handler(iret, failure=\"Problem putting variable\")\n\n     deallocate(xdum)\n     deallocate(dest_gone)\n\n  else\n\n     stop \"xtype\"\n\n  endif\n\nend subroutine copy_replace\n\nsubroutine copy_new(source_ncid, source_name, dest_ncid, dest_name)\n  !\n  ! Copy the variable named <source_name> from dataset <source_ncid> to\n  ! variable named <dest_name> in dataset <dest_ncid>.\n  !\n  use module_modify_wrfinput\n  implicit none\n  integer, intent(in) :: source_ncid, dest_ncid\n  character(len=*), intent(in) :: source_name, dest_name\n\n  integer :: source_varid, dest_varid, source_nvdims\n\n  real, allocatable, dimension(:,:,:,:) :: xdum\n  integer :: iret\n  integer :: xtype\n\n  integer, dimension(NF90_MAX_VAR_DIMS) :: vstart\n  integer, dimension(NF90_MAX_VAR_DIMS) :: vcount\n  integer, dimension(NF90_MAX_VAR_DIMS) :: source_dimids\n  integer, dimension(NF90_MAX_VAR_DIMS) :: dest_dimids\n\n  integer :: j\n  character(len=NF90_MAX_NAME) :: dimname\n\n  iret = nf90_inq_varid(source_ncid, source_name, source_varid)\n  call error_handler(iret, failure=\"Problem returning varid of field '\" & \n       //trim(source_name)//\"' for source\")\n\n  iret = nf90_inquire_variable(source_ncid, source_varid, &\n       xtype=xtype, ndims=source_nvdims, dimids=source_dimids)\n  call error_handler(iret, failure=\"Problem inquiring variable.\")\n\n  print*, 'name = ', trim(source_name), source_nvdims\n\n  if (source_nvdims > 4) stop \"nvdims problem\"\n\n  vstart = 1\n  vcount = 1\n\n  do j = 1, source_nvdims\n\n     iret = nf90_inquire_dimension(source_ncid, source_dimids(j), name=dimname, len=vcount(j))\n     call error_handler(iret, failure=\"Problem inquiring dimension\")\n\n     ! For each of <source_dimids>, find the corresponding <dest_dimids>:\n     iret = nf90_inq_dimid(dest_ncid, trim(dimname), dest_dimids(j))\n     if ((trim(dimname)==\"Times\") .and. (iret /= NF90_NOERR)) then\n        ! Grrrr.  Dimension name might be \"Time\" instead of \"Times\".  Corrected in more recent HRLDAS.\n        iret = nf90_inq_dimid(dest_ncid, \"Time\", dest_dimids(j))\n     endif\n     call error_handler(iret, failure=\"Problem inquiring dimid for dimension '\"//trim(dimname)//\"'\")\n\n  enddo\n\n  if (xtype == NF90_FLOAT) then\n\n     allocate(xdum(vcount(1),vcount(2),vcount(3),vcount(4)))\n\n     iret = nf90_get_var(source_ncid, source_varid, xdum, start=vstart, count=vcount)\n     call error_handler(iret, failure=\"Problem getting variable\")\n\n     ! Put our destination dataset into define mode.\n     iret = nf90_redef(dest_ncid)\n     call error_handler(iret, failure=\"Problem putting dataset in define mode (redef)\")\n\n     ! Define our new variable.\n\n     print*, 'dest_dimids = ', dest_dimids(1:source_nvdims)\n     iret = nf90_def_var(dest_ncid, trim(dest_name), xtype, dest_dimids(1:source_nvdims), dest_varid)\n     call error_handler(iret, failure=\"Problem defining new variable in destination file.\")\n\n     ! Define attributes for our new variable.\n\n     iret = nf90_put_att(dest_ncid, dest_varid, \"FieldType\", 104)\n     call error_handler(iret, failure=\"Problem defining attribute 'FieldType'\")\n\n     iret = nf90_copy_att(source_ncid, source_varid, \"MemoryOrder\", dest_ncid, dest_varid)\n     call error_handler(iret, failure=\"Problem copying attribute 'MemoryOrder'\")\n\n     iret = nf90_copy_att(source_ncid, source_varid, \"description\", dest_ncid, dest_varid)\n     call error_handler(iret, failure=\"Problem copying attribute 'description'\")\n\n     iret = nf90_copy_att(source_ncid, source_varid, \"units\", dest_ncid, dest_varid)\n     call error_handler(iret, failure=\"Problem copying attribute 'units'\")\n\n     iret = nf90_copy_att(source_ncid, source_varid, \"stagger\", dest_ncid, dest_varid)\n     call error_handler(iret, failure=\"Problem copying attribute 'stagger'\")\n\n     iret = nf90_put_att(dest_ncid, dest_varid, \"coordinates\", \"XLONG XLAT\")\n     call error_handler(iret, failure=\"Problem defining attribute 'coordinates'\")\n\n     ! Take us out of define mode.\n\n     iret = nf90_enddef(dest_ncid)\n     call error_handler(iret, failure=\"Problem exiting define mode.\")\n\n     ! Write the new variable.\n\n     iret = nf90_put_var(dest_ncid, dest_varid, xdum, start=vstart, count=vcount)\n     call error_handler(iret, failure=\"Problem putting variable\")\n\n     deallocate(xdum)\n\n  else\n\n     stop \"xtype\"\n\n  endif\n\nend subroutine copy_new\n\nsubroutine copy_dataset(wrf_ncid, copy_ncid)\n  use module_modify_wrfinput\n  implicit none\n  integer, intent(in) :: wrf_ncid, copy_ncid\n  integer :: iret, i, j\n\n  integer :: ndims, nvars, ngatts, unlimdimid, natts\n  character(len=NF90_MAX_NAME) :: name\n  integer :: lendd,  xtype, nvdims\n  integer, dimension(NF90_MAX_VAR_DIMS) :: dimids\n\n  real,             allocatable, dimension(:,:,:,:) :: xdum\n  integer,          allocatable, dimension(:,:,:,:) :: idum\n  character(len=1), allocatable, dimension(:,:,:,:) :: char_array\n  integer, dimension(NF90_MAX_VAR_DIMS) :: vstart\n  integer, dimension(NF90_MAX_VAR_DIMS) :: vcount\n\n  iret = nf90_inquire(wrf_ncid, ndims, nvars, ngatts, unlimdimId)\n  call error_handler(iret, failure=\"Problem inquiring on wrf_ncid\")\n\n  ! Copy the dimensions\n  do i = 1, ndims\n\n     iret = nf90_inquire_dimension(wrf_ncid, i, name, lendd)\n     call error_handler(iret, failure=\"Problem inquiring dimension for wrf_ncid\")\n\n!KWM     if (i /= unlimdimid) then\n     iret = nf90_def_dim (copy_ncid, trim(name), lendd, i)\n     call error_handler(iret, failure=\"Problem defining dimension for copy_ncid\")\n!KWM     else\n!KWM        iret = nf_def_dim (copy_ncid, trim(name), NF_UNLIMITED, i)\n!KWM        call error_handler(iret)\n!KWM     endif\n\n  enddo\n\n  ! Copy the global attributes\n  do i = 1, ngatts\n\n     iret = nf90_inq_attname(wrf_ncid, NF90_GLOBAL, i, name)\n     call error_handler(iret, failure=\"Problem inquiring attname for wrf_ncid\")\n\n     iret = nf90_copy_att(wrf_ncid, NF90_GLOBAL, trim(name), copy_ncid, NF90_GLOBAL)\n     call error_handler(iret, failure=\"Problem copying attribute\")\n\n  enddo\n\n  ! Copy the variable definitions\n\n  do i = 1, nvars\n\n     iret = nf90_inquire_variable(wrf_ncid, i, name, xtype, nvdims, dimids, natts)\n     call error_handler(iret, failure=\"Problem inquiring variable for wrf_ncid\")\n\n     iret = nf90_def_var(copy_ncid, trim(name), xtype, dimids(1:nvdims), i)\n     call error_handler(iret, failure=\"Problem defining variable.\")\n\n     ! Copy the variable's attributes\n     do j = 1, natts\n\n        iret = nf90_inq_attname(wrf_ncid, i, j, name)\n        call error_handler(iret, failure=\"Problem inquiring attribute name\")\n\n        iret = nf90_copy_att(wrf_ncid, i, trim(name), copy_ncid, i)\n        call error_handler(iret, failure=\"Problem copying attribute\")\n\n     enddo\n\n  enddo\n\n  ! Take the new netcdf dataset out of define mode, so it's ready to receive data.\n  iret = nf90_enddef(copy_ncid)\n  call error_handler(iret, failure=\"Problem getting us out of define mode\")\n\n  ! Copy all the data\n\n  do i = 1, nvars\n\n     iret = nf90_inquire_variable(wrf_ncid, i, name, xtype, nvdims, dimids)\n     call error_handler(iret, failure=\"Problem inquiring variable.\")\n     print*, 'name = ', trim(name), nvdims\n     if (nvdims > 4) stop \"nvdims problem\"\n\n     vstart = 1\n     vcount = 1\n\n     do j = 1, nvdims\n        iret = nf90_inquire_dimension(wrf_ncid, dimids(j), name, vcount(j))\n        call error_handler(iret, failure=\"Problem inquiring dimension\")\n     enddo\n\n     if (xtype == NF90_FLOAT) then\n\n        allocate(xdum(vcount(1),vcount(2),vcount(3),vcount(4)))\n        iret = nf90_get_var(wrf_ncid, i, xdum, start=vstart, count=vcount)\n        call error_handler(iret, failure=\"Problem getting float variable\")\n\n        iret = nf90_put_var(copy_ncid, i, xdum, start=vstart, count=vcount)\n        call error_handler(iret, failure=\"Problem putting float variable\")\n        deallocate(xdum)\n\n\n     elseif (xtype == NF90_CHAR) then\n\n        allocate(char_array(vcount(1),vcount(2),vcount(3),vcount(4)))\n        iret = nf90_get_var(wrf_ncid, i, char_array, start=vstart, count=vcount)\n        call error_handler(iret, failure=\"Problem getting char variable\")\n\n        iret = nf90_put_var(copy_ncid, i, char_array, start=vstart, count=vcount)\n        call error_handler(iret, failure=\"Problem putting char variable\")\n        deallocate(char_array)\n\n     elseif (xtype == NF90_INT) then\n\n        allocate(idum(vcount(1),vcount(2),vcount(3),vcount(4)))\n        iret = nf90_get_var(wrf_ncid, i, idum, start=vstart, count=vcount)\n        call error_handler(iret, failure=\"Problem getting int variable\")\n\n        iret = nf90_put_var(copy_ncid, i, idum, start=vstart, count=vcount)\n        call error_handler(iret, failure=\"Problem putting int variable\")\n        deallocate(idum)\n\n     else\n\n        stop \"xtype\"\n\n     endif\n\n  enddo\n\n  iret = nf90_close(copy_ncid)\n  call error_handler(iret, failure=\"Problem closing copy_ncid.\")\n\nend subroutine copy_dataset\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/vectorize/check_test.ncl",
    "content": "load \"$NCARG_ROOT/lib/ncarg/nclex/gsun/gsn_code.ncl\"\n\nbegin\n\nvar2check = \"HFX\"\ntwodlist = systemfunc(\"ls /qnap/yingz/test/20050101*\")\nonedlist = systemfunc(\"ls /d1/output/vector/test/20050101*\")\n\ntwod = new(24,float)\noned = new(24,float)\n\nlat_2d = 2200  ;\nlon_2d = 503  ; 503 - 505 ARE FOREST\n\ndo i=0,23\n outfile = addfile(twodlist(i)+\".nc\",\"r\")\n twod(i) = outfile->$var2check$(0,lat_2d,lon_2d)\nend do\n\nprint(\"2D variables\")\nprint((/twod/))\n\nlat_1d = 983302  ; 503->983302  504->983303  505->983304  \n\ndo i=0,23\n outfile = addfile(onedlist(i)+\".nc\",\"r\")\n oned(i) = outfile->$var2check$(0,0,lat_1d)\nend do\n\nprint(\"\")\nprint(\"vector variables\")\nprint((/oned/))\n\nprint(\"\")\nprint(\"maximum diffrence: \"+max(twod-oned))\n\nend\n\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/vectorize/check_wrfinput.ncl",
    "content": "load \"$NCARG_ROOT/lib/ncarg/nclex/gsun/gsn_code.ncl\"\n\nbegin\n\n;;;;;;;;;;;;\n;  GEO_EM check\n;;;;;;;;;;;;\nprint(\"GEO_EM check\")\nprint(\"\")\n\noutfile = addfile(\"/d1/model/WPS/geo_em.d01.nc\",\"r\")\n\nlat_2d = 2200  ;\nlon_2d = 503  ; 503 - 505 ARE FOREST\n\ntwod_lat = outfile->XLAT_M(0,lat_2d,lon_2d)\ntwod_lon = outfile->XLONG_M(0,lat_2d,lon_2d)\ntwod_land = outfile->LU_INDEX(0,lat_2d,lon_2d)\ntwod_green = outfile->GREENFRAC(0,:,lat_2d,lon_2d)\n\nprint(\"2D variables\")\nprint((/twod_lat/))\nprint((/twod_lon/))\nprint((/twod_land/))\nprint((/twod_green/))\n\n;outfile = addfile(\"/d1/data/vector/WRF/geo_em.FOREST.nc\",\"r\")\noutfile = addfile(\"/d1/data/vector/WRF/geo_em.d01.nc\",\"r\")\n\nlat_1d = 983302  ; 503->983302  504->983303  505->983304  \n\nvector_lat = outfile->XLAT_M(0,0,lat_1d)\nvector_lon = outfile->XLONG_M(0,0,lat_1d)\nvector_green = outfile->GREENFRAC(0,:,0,lat_1d)\n\nprint(\"\")\nprint(\"vector variables\")\nprint((/vector_lat/))\nprint((/vector_lon/))\nprint((/vector_green/))\n\n;;;;;;;;;;;;\n;  WRFINPUT check\n;;;;;;;;;;;;\nprint(\"\")\nprint(\"WRFINPUT check\")\nprint(\"\")\n\noutfile = addfile(\"/d1/model/WRFV3/run/wrfinput_d01.nc\",\"r\")\n\ntwod_veg = outfile->IVGTYP(0,lat_2d,lon_2d)\ntwod_soil = outfile->ISLTYP(0,lat_2d,lon_2d)\ntwod_hgt = outfile->HGT(0,lat_2d,lon_2d)\ntwod_lat = outfile->XLAT(0,lat_2d,lon_2d)\ntwod_lon = outfile->XLONG(0,lat_2d,lon_2d)\ntwod_tmn = outfile->TMN(0,lat_2d,lon_2d)\n\nprint(\"2D variables\")\nprint((/twod_veg/))\nprint((/twod_soil/))\nprint((/twod_hgt/))\nprint((/twod_lat/))\nprint((/twod_lon/))\nprint((/twod_tmn/))\n\n;outfile = addfile(\"/d1/data/vector/WRF/wrfinput.FOREST.nc\",\"r\")\noutfile = addfile(\"/d1/data/vector/WRF/wrfinput_d01.nc\",\"r\")\n\nvector_veg = outfile->IVGTYP(0,0,lat_1d)\nvector_soil = outfile->ISLTYP(0,0,lat_1d)\nvector_hgt = outfile->HGT(0,0,lat_1d)\nvector_lat = outfile->XLAT(0,0,lat_1d)\nvector_lon = outfile->XLONG(0,0,lat_1d)\nvector_tmn = outfile->TMN(0,0,lat_1d)\n\nprint(\"\")\nprint(\"vector variables\")\nprint((/vector_veg/))\nprint((/vector_soil/))\nprint((/vector_hgt/))\nprint((/vector_lat/))\nprint((/vector_lon/))\nprint((/vector_tmn/))\n\nprint(\"Number forest points: \"+num(outfile->IVGTYP.le.5))\n\n;;;;;;;;;;;;\n;  LDASIN init check\n;;;;;;;;;;;;\nprint(\"\")\nprint(\"LDASIN init check\")\nprint(\"\")\n\noutfile = addfile(\"/d1/model/trunk/HRLDAS_COLLECT_DATA/run/2005010100.LDASIN_DOMAIN1.nc\",\"r\")\n\ntwod_CANWAT = outfile->CANWAT(0,lat_2d,lon_2d)\ntwod_SKINTEMP = outfile->SKINTEMP(0,lat_2d,lon_2d)\ntwod_STEMP_1 = outfile->STEMP_1(0,lat_2d,lon_2d)\ntwod_STEMP_2 = outfile->STEMP_2(0,lat_2d,lon_2d)\ntwod_STEMP_3 = outfile->STEMP_3(0,lat_2d,lon_2d)\ntwod_STEMP_4 = outfile->STEMP_4(0,lat_2d,lon_2d)\ntwod_SMOIS_1 = outfile->SMOIS_1(0,lat_2d,lon_2d)\ntwod_SMOIS_2 = outfile->SMOIS_2(0,lat_2d,lon_2d)\ntwod_SMOIS_3 = outfile->SMOIS_3(0,lat_2d,lon_2d)\ntwod_SMOIS_4 = outfile->SMOIS_4(0,lat_2d,lon_2d)\ntwod_VEGFRA = outfile->VEGFRA(0,lat_2d,lon_2d)\ntwod_GVFMIN = outfile->GVFMIN(0,lat_2d,lon_2d)\ntwod_GVFMAX = outfile->GVFMAX(0,lat_2d,lon_2d)\ntwod_Z2D = outfile->Z2D(0,lat_2d,lon_2d)\n\nprint(\"2D variables\")\nprint((/twod_CANWAT/))\nprint((/twod_SKINTEMP/))\nprint((/twod_STEMP_1/))\nprint((/twod_STEMP_2/))\nprint((/twod_STEMP_3/))\nprint((/twod_STEMP_4/))\nprint((/twod_SMOIS_1/))\nprint((/twod_SMOIS_2/))\nprint((/twod_SMOIS_3/))\nprint((/twod_SMOIS_4/))\nprint((/twod_VEGFRA/))\nprint((/twod_GVFMIN/))\nprint((/twod_GVFMAX/))\nprint((/twod_Z2D/))\n\noutfile = addfile(\"/d1/data/vector/ldasin/2005010100.LDASIN_DOMAIN1.nc\",\"r\")\n\nvector_CANWAT = outfile->CANWAT(0,0,lat_1d)\nvector_SKINTEMP = outfile->SKINTEMP(0,0,lat_1d)\nvector_STEMP_1 = outfile->STEMP_1(0,0,lat_1d)\nvector_STEMP_2 = outfile->STEMP_2(0,0,lat_1d)\nvector_STEMP_3 = outfile->STEMP_3(0,0,lat_1d)\nvector_STEMP_4 = outfile->STEMP_4(0,0,lat_1d)\nvector_SMOIS_1 = outfile->SMOIS_1(0,0,lat_1d)\nvector_SMOIS_2 = outfile->SMOIS_2(0,0,lat_1d)\nvector_SMOIS_3 = outfile->SMOIS_3(0,0,lat_1d)\nvector_SMOIS_4 = outfile->SMOIS_4(0,0,lat_1d)\nvector_VEGFRA = outfile->VEGFRA(0,0,lat_1d)\nvector_GVFMIN = outfile->GVFMIN(0,0,lat_1d)\nvector_GVFMAX = outfile->GVFMAX(0,0,lat_1d)\nvector_Z2D = outfile->Z2D(0,0,lat_1d)\n\nprint(\"\")\nprint(\"vector variables\")\nprint((/vector_CANWAT/))\nprint((/vector_SKINTEMP/))\nprint((/vector_STEMP_1/))\nprint((/vector_STEMP_2/))\nprint((/vector_STEMP_3/))\nprint((/vector_STEMP_4/))\nprint((/vector_SMOIS_1/))\nprint((/vector_SMOIS_2/))\nprint((/vector_SMOIS_3/))\nprint((/vector_SMOIS_4/))\nprint((/vector_VEGFRA/))\nprint((/vector_GVFMIN/))\nprint((/vector_GVFMAX/))\nprint((/vector_Z2D/))\n\n;;;;;;;;;;;;\n;  LDASIN check\n;;;;;;;;;;;;\nprint(\"\")\nprint(\"LDASIN check\")\nprint(\"\")\n\noutfile = addfile(\"/d1/model/trunk/HRLDAS_COLLECT_DATA/run/2005010100.LDASIN_DOMAIN1.nc\",\"r\")\n\ntwod_T2D = outfile->T2D(0,lat_2d,lon_2d)\ntwod_Q2D = outfile->Q2D(0,lat_2d,lon_2d)\ntwod_U2D = outfile->U2D(0,lat_2d,lon_2d)\ntwod_V2D = outfile->V2D(0,lat_2d,lon_2d)\ntwod_PSFC = outfile->PSFC(0,lat_2d,lon_2d)\ntwod_RAINRATE = outfile->RAINRATE(0,lat_2d,lon_2d)\ntwod_SWDOWN = outfile->SWDOWN(0,lat_2d,lon_2d)\ntwod_LWDOWN = outfile->LWDOWN(0,lat_2d,lon_2d)\ntwod_WEASD = outfile->WEASD(0,lat_2d,lon_2d)\n\nprint(\"2D variables\")\nprint((/twod_T2D/))\nprint((/twod_Q2D/))\nprint((/twod_U2D/))\nprint((/twod_V2D/))\nprint((/twod_PSFC/))\nprint((/twod_RAINRATE/))\nprint((/twod_SWDOWN/))\nprint((/twod_LWDOWN/))\nprint((/twod_WEASD/))\n\noutfile = addfile(\"/d1/data/vector/ldasin/2005010100.LDASIN_DOMAIN1.nc\",\"r\")\n\nvector_T2D = outfile->T2D(0,0,lat_1d)\nvector_Q2D = outfile->Q2D(0,0,lat_1d)\nvector_U2D = outfile->U2D(0,0,lat_1d)\nvector_V2D = outfile->V2D(0,0,lat_1d)\nvector_PSFC = outfile->PSFC(0,0,lat_1d)\nvector_RAINRATE = outfile->RAINRATE(0,0,lat_1d)\nvector_SWDOWN = outfile->SWDOWN(0,0,lat_1d)\nvector_LWDOWN = outfile->LWDOWN(0,0,lat_1d)\nvector_WEASD = outfile->WEASD(0,0,lat_1d)\n\nprint(\"\")\nprint(\"vector variables\")\nprint((/vector_T2D/))\nprint((/vector_Q2D/))\nprint((/vector_U2D/))\nprint((/vector_V2D/))\nprint((/vector_PSFC/))\nprint((/vector_RAINRATE/))\nprint((/vector_SWDOWN/))\nprint((/vector_LWDOWN/))\nprint((/vector_WEASD/))\n\nend\n\n\n;vector_lat = outfile->XLAT_M\n;vector_lon = outfile->XLONG_M\n\n;do i = 0,1563015\n;  if(vector_lat(0,0,i).gt.twod_lat(0,0)-0.01 .and. vector_lat(0,0,i).lt.twod_lat(0,0)+0.01 .and. \\\n;     vector_lon(0,0,i).gt.twod_lon(0,0)-0.01 .and. vector_lon(0,0,i).lt.twod_lon(0,0)+0.01) then\n;    print(vector_lat(0,0,i)+\" \"+twod_lat(0,0))\n;    print(vector_lon(0,0,i)+\" \"+twod_lon(0,0))\n;    print(\"i: \"+i)\n;  end if\n;end do\n\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/vectorize/namelist.vectorize",
    "content": "&vectorize_namelist\n full_geo_em = \"../../wps_lambert/geo_em.d01.nc\"\n vector_directory = \"./vector/\"\n keep_lu_list = 1,2,3,4,8,12,\n/\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/vectorize/procedure.txt",
    "content": "Procedure is basically:\n\n1. vectorize_geo_em.f90 (not really necessary if you already have the\nLDASIN files, but I did it anyway)\n2. vectorize_wrfinput.f90\n3. compile the ldasin*.f90 files; the expectation is they will be named\nvectorize_ldasin_init, vectorize_ldasin_00Z, vectorize_ldasin_non00Z\n4. change year and Julian day range you want to do in the perl script\n5. run perl script\n6. run vectorize_ldasin_init (creates the initialization file)\n7. check_wrfinput.ncl : will compare vector version of the geo_em,\nwrfinput, and ldasin files to the 2D files\n8. check_test.ncl : will compare a 24hr simulation between vector and 2D\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/vectorize/vectorize.perl",
    "content": "#!/usr/bin/perl\n\n# Set the number of days you want to run the system\n$day_start = 32;  # 305=Nov 1\n$day_end = 273;    # 181=Jun 30; 212=Jul 31; 243=Aug 31\n                   \n$year = 2005;\n\n# Utilities\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\n         \"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\",\n         \"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\",\"30\",\n\t \"31\",\"32\",\"33\",\"34\",\"35\",\"36\",\"37\",\"38\",\"39\",\"40\",\n\t \"41\",\"42\",\"43\",\"44\",\"45\",\"46\",\"47\",\"48\",\"49\",\"50\",\n\t \"51\",\"52\",\"53\",\"54\",\"55\",\"56\",\"57\",\"58\",\"59\",\"60\",\n\t \"61\",\"62\",\"63\",\"64\",\"65\",\"66\",\"67\",\"68\",\"69\",\"70\",\n\t \"71\",\"72\",\"73\",\"74\",\"75\",\"76\",\"77\",\"78\",\"79\",\"80\",\n\t \"81\",\"82\",\"83\",\"84\",\"85\",\"86\",\"87\",\"88\",\"89\",\"90\",\n\t \"91\",\"92\",\"93\",\"94\",\"95\",\"96\",\"97\",\"98\",\"99\");\n@days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n# This will be the outer time loop\n\nfor($julday=$day_start;$julday<=$day_end;$julday=$julday+1)\n\n { \n \n # This little section finds the text month and day in format of date and netcdf file title\n \n for($mo=1;$mo<=12;$mo++)\n  {\n  if($year == 2004 || $year == 2008) \n   {\n    if($julday>$leap_days[$mo-1] && $julday<=$leap_days[$mo]) \n     {\n       $mon = $mo;\n       $day = $julday - $leap_days[$mo-1];\n     }\n   }else{\n    if($julday>$days[$mo-1] && $julday<=$days[$mo]) \n     {\n       $mon = $mo;\n       $day = $julday - $days[$mo-1];\n     }\n    }\n  }\n\n###########################################\n# Vectorize LDASIN files\n########################################### \n\n  print(\"Starting vectorize for $year$nums[$mon]$nums[$day]$nums[$hr]\\n\");\n\n  for($hr=0;$hr<=23;$hr++)\n   {\n    if($hr == 0) \n     {\n      system(\"vectorize_ldasin_00Z $year$nums[$mon]$nums[$day]$nums[$hr].LDASIN_DOMAIN1\");\n     }else{\n      system(\"vectorize_ldasin_non00Z $year$nums[$mon]$nums[$day]$nums[$hr].LDASIN_DOMAIN1\");\n     }\n   }\n\n } # End of outer time loop\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/vectorize/vectorize_geo_em.F",
    "content": "program vectorize_geo_em\n  use netcdf\n  implicit none\n\n  integer :: ncid_in, ncid_out\n  integer :: iret,iloc,ilat,ilon\n  integer :: dim_date, dim_we, dim_sn, dim_time, dim_mo, ndims, nvars, natts\n  integer :: varid_in(4), varid_out(4)\n  character (len = 80) :: attname\n  character(len=256) :: input_file\n  character(len=256) :: output_file\n\n  real,    allocatable, dimension(:,:,:)   :: lu_index\n  real,    allocatable, dimension(:,:,:)   :: xlat_in\n  real,    allocatable, dimension(:,:,:)   :: xlon_in\n  real,    allocatable, dimension(:,:,:,:) :: green_in\n  real,    allocatable, dimension(:,:,:)   :: xlat_out\n  real,    allocatable, dimension(:,:,:)   :: xlon_out\n  real,    allocatable, dimension(:,:,:,:) :: green_out\n  logical, allocatable, dimension(:,:)     :: lumask\n\n  integer :: dimid\n  integer :: west_east_old\n  integer :: south_north_old\n  integer :: west_east_new\n  integer :: south_north_new = 1\n\n  integer, dimension(100) :: keep_lu_list\n  character(len=256) :: lustring\n  integer :: landuse_count\n  integer :: k\n\n  character(len=256) :: full_geo_em\n  character(len=256) :: vector_directory\n  character(len=256) :: dumstr\n\n  namelist/vectorize_namelist/ keep_lu_list, full_geo_em, vector_directory\n\n  ! Default values\n  keep_lu_list = -99999\n  landuse_count = 0\n  full_geo_em = \" \"\n  vector_directory = \" \"\n  open(12, file=\"namelist.vectorize\", status='old', form='formatted', action='read')\n  read(12, vectorize_namelist)\n  close(12)\n  do while (keep_lu_list(landuse_count+1) > 0)\n     landuse_count = landuse_count + 1\n  enddo\n  write(*,'(\"Keep the following \", I4, \" land-use categories:\")') landuse_count\n  write(*,'(\"         \", I4)') keep_lu_list(1:landuse_count)\n\n!!!!!\n! OPEN OLD GEO_EM FILE AND CREATE NEW VECTOR FILE\n!!!!!\n\n  iret = nf90_open(trim(full_geo_em), NF90_NOWRITE, ncid_in)\n  call error_handler(iret, \"Problem opening file '\"//trim(input_file)//\"'\")\n\n  iret = nf90_create(trim(vector_directory)//trim(full_geo_em(index(full_geo_em,\"/\",.TRUE.):)), NF90_CLOBBER, ncid_out)\n  call error_handler(iret, \"Problem creating file '\"//trim(output_file)//\"'\")\n\n!!!!!\n! DIMENSIONS FROM OLD FILE\n!!!!!\n\n  call get_dimlen ( ncid_in, \"west_east\", west_east_old )\n  call get_dimlen ( ncid_in, \"south_north\", south_north_old )\n\n  allocate ( lu_index ( west_east_old , south_north_old , 1 ) )\n  allocate ( xlat_in  ( west_east_old , south_north_old , 1 ) )\n  allocate ( xlon_in  ( west_east_old , south_north_old , 1 ) )\n  allocate ( green_in ( west_east_old , south_north_old , 12, 1 ) )\n\n!!!!!\n! READ IN VARIABLES ONE AT A TIME, EXTRACT AND WRITE TO NEW FILE\n!!!!!\n\n!!!!!\n! LU_INDEX - only used to extract desired points\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"LU_INDEX\",varid_in(1))\n  call error_handler(iret, \"Problem getting varid for 'LU_INDEX'\")\n\n  iret = nf90_get_var(ncid_in, varid_in(1), lu_index)\n  call error_handler(iret, \"Problem getting variable 'LU_INDEX'\")\n\n!!!!!\n! XLAT\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"XLAT_M\",varid_in(2))\n  call error_handler(iret, \"Problem getting varid for 'XLAT_M'\")\n\n  iret = nf90_get_var(ncid_in, varid_in(2), xlat_in)\n  call error_handler(iret, \"Problem getting variable 'XLAT_M'\")\n\n!!!!!\n! XLONG\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"XLONG_M\",varid_in(3))\n  call error_handler(iret, \"Problem getting varid for 'XLONG_M'\")\n\n  iret = nf90_get_var(ncid_in, varid_in(3), xlon_in)\n  call error_handler(iret, \"Problem getting variable 'XLONG_M'\")\n\n!!!!!\n! GREENFRAC\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"GREENFRAC\",varid_in(4))\n  call error_handler(iret, \"Problem getting varid for 'GREENFRAC'\")\n\n  iret = nf90_get_var(ncid_in, varid_in(4), green_in)\n  call error_handler(iret, \"Problem getting variable 'GREENFRAC'\")\n\n  allocate(lumask(west_east_old, south_north_old))\n  lumask = .FALSE.\n  do k = 1, landuse_count\n     where (nint(lu_index(:,:,1)) == keep_lu_list(k)) lumask = .TRUE.\n  enddo\n  west_east_new = count(lumask)\n  write(*, '(\"Count of points to keep = \", I20)') west_east_new\n\n  allocate ( xlat_out  ( west_east_new , south_north_new , 1 ) )\n  allocate ( xlon_out  ( west_east_new , south_north_new , 1 ) )\n  allocate ( green_out ( west_east_new , south_north_new , 12, 1 ) )\n\n  iloc = 0\n  do ilat = 1,south_north_old\n     do ilon = 1,west_east_old\n        if(lumask(ilon,ilat)) then\n           iloc = iloc + 1\n           if (iloc > west_east_new) then\n              print*, 'up to ', iloc\n              stop \"Too many!\"\n           endif\n           ! print*, 'iloc, ilon, ilat = ', iloc, ilon, ilat\n           xlat_out(iloc,1,1) = xlat_in(ilon,ilat,1)\n           xlon_out(iloc,1,1) = xlon_in(ilon,ilat,1)\n           green_out(iloc,1,:,1) = green_in(ilon,ilat,:,1)\n        endif\n     enddo\n  enddo\n  if (iloc /= west_east_new) stop \"Problem\"\n\n!!!!!\n! DIMENSIONS IN NEW FILE\n!!!!!\n\n  iret = nf90_def_dim(ncid_out,\"Time\",NF90_UNLIMITED,dim_time)\n  call error_handler(iret, \"Problem defining dimension 'Time'\")\n\n  iret = nf90_def_dim(ncid_out,\"DateStrLen\",19,dim_date)\n  call error_handler(iret, \"Problem defining dimension 'DateStrLen'\")\n\n  iret = nf90_def_dim(ncid_out,\"west_east\",west_east_new,dim_we)\n  call error_handler(iret, \"Problem defining dimension 'west_east'\")\n\n  iret = nf90_def_dim(ncid_out,\"south_north\",south_north_new,dim_sn)\n  call error_handler(iret, \"Problem defining dimension 'south_north'\")\n\n  iret = nf90_def_dim(ncid_out,\"month\",12,dim_MO)\n  call error_handler(iret, \"Problem defining dimension 'month'\")\n\n!!!!!\n! TAKE CARE OF THE PESKY GLOBAL ATTRIBUTES\n!!!!!\n\n  iret = nf90_inquire(ncid_in,ndims, nvars, natts)\n  call error_handler(iret, \"Problem getting number attributes\")\n\n  do iloc = 1, natts\n\n    iret = nf90_inq_attname(ncid_in,NF90_GLOBAL, iloc, attname)\n    call error_handler(iret,\"Problem getting attribute name\")\n\n    iret = nf90_copy_att(ncid_in, NF90_GLOBAL, trim(attname), ncid_out, NF90_GLOBAL)\n    call error_handler(iret,\"Problem copying attribute\")\n\n  end do\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"WEST-EAST_GRID_DIMENSION\", west_east_new+1)\n  call error_handler(iret,\"Problem putting attribute 'WEST-EAST_GRID_DIMENSION'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"SOUTH-NORTH_GRID_DIMENSION\", south_north_new+1)\n  call error_handler(iret,\"Problem putting attribute 'SOUTH-NORTH_GRID_DIMENSION'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"WEST-EAST_PATCH_END_UNSTAG\", west_east_new)\n  call error_handler(iret,\"Problem putting attribute 'WEST-EAST_PATCH_END_UNSTAG'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"WEST-EAST_PATCH_END_STAG\", west_east_new+1)\n  call error_handler(iret,\"Problem putting attribute 'WEST-EAST_PATCH_END_STAG'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"SOUTH-NORTH_PATCH_END_UNSTAG\", south_north_new)\n  call error_handler(iret,\"Problem putting attribute 'SOUTH-NORTH_PATCH_END_STAG'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"SOUTH-NORTH_PATCH_END_STAG\", south_north_new+1)\n  call error_handler(iret,\"Problem putting attribute 'SOUTH-NORTH-PATCH_END_STAG'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"i_parent_end\", west_east_new+1)\n  call error_handler(iret,\"Problem putting attribute 'i_parent_end'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"j_parent_end\", south_north_new+1)\n  call error_handler(iret,\"Problem putting attribute 'j_parent_end'\")\n\n  lustring = \" \"\n  do k = 1, landuse_count\n     write(dumstr, *) keep_lu_list(k)\n     if (k>1) lustring = trim(lustring)//\",\"\n     lustring = trim(lustring) // trim(adjustl(dumstr))\n  enddo\n  iret = nf90_put_att(ncid_out, NF90_GLOBAL, \"vector_landuse_indices\", trim(adjustl(lustring)))\n  call error_handler(iret,\"Problem putting attribute 'vector_landuse_indices'\")\n\n!!!!!\n! XLAT\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"XLAT_M\",NF90_FLOAT,(/dim_we,dim_sn,dim_time/),varid_out(1))\n  call error_handler(iret, \"Problem defining variable 'XLAT_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"FieldType\",104)\n    call error_handler(iret, \"Problem making attribute 'FieldType' for variable 'XLAT_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"MemoryOrder\",\"XY \")\n    call error_handler(iret, \"Problem making attribute 'MemoryOrder' for variable 'XLAT_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"units\",\"degrees latitude\")\n    call error_handler(iret, \"Problem making attribute 'units' for variable 'XLAT_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"description\",\"Latitude on mass grid\")\n    call error_handler(iret, \"Problem making attribute 'description' for variable 'XLAT_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"stagger\",\"M\")\n    call error_handler(iret, \"Problem making attribute 'stagger' for variable 'XLAT_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"sr_x\",1)\n    call error_handler(iret, \"Problem making attribute 'sr_x' for variable 'XLAT_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"sr_y\",1)\n    call error_handler(iret, \"Problem making attribute 'sr_y' for variable 'XLAT_M'\")\n\n!!!!!\n! XLONG\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"XLONG_M\",NF90_FLOAT,(/dim_we,dim_sn,dim_time/),varid_out(2))\n  call error_handler(iret, \"Problem defining variable 'XLONG_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"FieldType\",104)\n    call error_handler(iret, \"Problem defining attribute 'FieldType' for variable 'XLONG_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"MemoryOrder\",\"XY \")\n    call error_handler(iret, \"Problem defining attribute 'MemoryOrder' for variable 'XLONG_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"units\",\"degrees longitude\")\n    call error_handler(iret, \"Problem defining attribute 'units' for variable 'XLONG_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"description\",\"Longitude on mass grid\")\n    call error_handler(iret, \"Problem defining attribute 'description' for variable 'XLONG_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"stagger\",\"M\")\n    call error_handler(iret, \"Problem defining attribute 'stagger' for variable 'XLONG_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"sr_x\",1)\n    call error_handler(iret, \"Problem defining attribute 'sr_x' for variable 'XLONG_M'\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"sr_y\",1)\n    call error_handler(iret, \"Problem defining attribute 'sr_y' for variable 'XLONG_M'\")\n\n!!!!!\n! GREENFRAC\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"GREENFRAC\",NF90_FLOAT,(/dim_we,dim_sn,dim_mo,dim_time/),varid_out(3))\n  call error_handler(iret, \"Problem defining variable 'GREENFRAC'\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"FieldType\",104)\n    call error_handler(iret, \"Problem defining attribute 'FieldType' for variable 'GREENFRAC'\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"MemoryOrder\",\"XYZ\")\n    call error_handler(iret, \"Problem defining attribute 'MemoryOrder' for variable 'GREENFRAC'\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"units\",\"fraction\")\n    call error_handler(iret, \"Problem defining attribute 'units' for variable 'GREENFRAC'\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"description\",\"Monthly green fraction\")\n    call error_handler(iret, \"Problem defining attribute 'description' for variable 'GREENFRAC'\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"stagger\",\"M\")\n    call error_handler(iret, \"Problem defining attribute 'stagger' for variable 'GREENFRAC'\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"sr_x\",1)\n    call error_handler(iret, \"Problem defining attribute 'sr_x' for variable 'GREENFRAC'\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"sr_y\",1)\n    call error_handler(iret, \"Problem defining attribute 'sr_y' for variable 'GREENFRAC'\")\n\n  iret = nf90_enddef(ncid_out)\n  call error_handler(iret, \"Problem exiting the define mode\")\n\n\n!!!!!\n! WRITE VARIABLES\n!!!!!\n\n  iret = nf90_put_var(ncid_out,varid_out(1),xlat_out)\n  call error_handler(iret, \"Problem writing variable 'XLAT_M'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(2),xlon_out)\n  call error_handler(iret, \"Problem writing variable 'XLONG_M'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(3),green_out)\n  call error_handler(iret, \"Problem writing variable 'GREENFRAC'\")\n\n  iret = nf90_close(ncid_out)\n  call error_handler(iret, \"Problem closing output file\")\n\n  iret = nf90_close(ncid_in)\n  call error_handler(iret, \"Problem closing input file\")\n\nend program\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n\nsubroutine error_handler(ierr, failure)\n  use netcdf\n  implicit none\n  integer, intent(in) :: ierr\n  character(len=*), intent(in) :: failure\n\n  if (ierr == NF90_NOERR) return\n\n  write(*, '(\"----ERROR---------------------------------------------------\")')\n  write(*, '(5X,A)') trim(nf90_strerror(ierr))\n  if (failure /= \"\") write(*, '(5X,A)') trim(failure)\n  write(*, '(\"------------------------------------------------------------\")')\n  stop\n\nend subroutine error_handler\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n\nsubroutine get_dimlen(ncid, name, dimlen)\n  use netcdf\n  implicit none\n  integer, intent(in) :: ncid\n  character(len=*), intent(in) :: name\n  integer, intent(out) :: dimlen\n\n  integer :: dimid\n  integer :: ierr\n\n  ierr = nf90_inq_dimid(ncid, name, dimid)\n  call error_handler(ierr, \"GET_DIMLEN : Problem getting dimension id for '\"//name//\"'\")\n\n  ierr = nf90_inquire_dimension(ncid, dimid, len=dimlen)\n  call error_handler(ierr, \"GET_DIMLEN : Problem getting dimension length for '\"//name//\"'\")\n\nend subroutine get_dimlen\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/vectorize/vectorize_ldasin.F",
    "content": "program vectorize_ldasin\n  use netcdf\n  implicit none\n\n  integer :: ncid_in, ncid_out\n  integer :: iret,iloc,ilat,ilon\n  integer :: dim_date, dim_we, dim_sn, dim_time\n  integer, dimension(23) :: varid_in,  &\n       &                    varid_out\n\n  character(len=256) :: attstring\n  real               :: attfloat\n  integer            :: attint\n\n  integer :: south_north_old\n  integer :: west_east_old\n  integer :: south_north_new\n  integer :: west_east_new\n  integer :: k\n  integer, dimension(100) :: keep_lu_list\n  integer :: landuse_count\n  logical :: FOUND_WEASD\n  logical :: FOUND_VEGFRA\n  logical :: FOUND_CANWAT\n  logical :: FOUND_SKINTEMP\n  logical :: FOUND_STEMP1\n  logical :: FOUND_STEMP2\n  logical :: FOUND_STEMP3\n  logical :: FOUND_STEMP4\n  logical :: FOUND_SMOIS1\n  logical :: FOUND_SMOIS2\n  logical :: FOUND_SMOIS3\n  logical :: FOUND_SMOIS4\n  logical :: FOUND_GVFMIN\n  logical :: FOUND_GVFMAX\n  logical :: FOUND_Z2D\n  logical, allocatable, dimension(:,:) :: lumask\n  real, allocatable, dimension(:,:,:) :: lu_index\n  real, allocatable, dimension(:,:,:) :: t2d_in,       &\n       &                                 q2d_in,       &\n       &                                 u2d_in,       &\n       &                                 v2d_in,       &\n       &                                 psfc_in,      &\n       &                                 rainrate_in,  &\n       &                                 swdown_in,    &\n       &                                 lwdown_in,    &\n       &                                 weasd_in,     &\n       &                                 vegfra_in,    &\n       &                                 canwat_in,    &\n       &                                 skintemp_in,  &\n       &                                 stemp1_in,    &\n       &                                 stemp2_in,    &\n       &                                 stemp3_in,    &\n       &                                 stemp4_in,    &\n       &                                 smois1_in,    &\n       &                                 smois2_in,    &\n       &                                 smois3_in,    &\n       &                                 smois4_in,    &\n       &                                 gvfmin_in,    &\n       &                                 gvfmax_in,    &\n       &                                 z2d_in\n  real, allocatable, dimension(:,:,:) :: t2d_out,      &\n       &                                 q2d_out,      &\n       &                                 u2d_out,      &\n       &                                 v2d_out,      &\n       &                                 psfc_out,     &\n       &                                 rainrate_out, &\n       &                                 swdown_out,   &\n       &                                 lwdown_out,   &\n       &                                 weasd_out,    &\n       &                                 vegfra_out,   &\n       &                                 canwat_out,   &\n       &                                 skintemp_out, &\n       &                                 stemp1_out,   &\n       &                                 stemp2_out,   &\n       &                                 stemp3_out,   &\n       &                                 stemp4_out,   &\n       &                                 smois1_out,   &\n       &                                 smois2_out,   &\n       &                                 smois3_out,   &\n       &                                 smois4_out,   &\n       &                                 gvfmin_out,   &\n       &                                 gvfmax_out,   &\n       &                                 z2d_out\n\n  character(len=256) :: infile\n  character(len=256) :: full_geo_em\n  character(len=256) :: vector_directory\n  character(len=256) :: lustring\n  character(len=256) :: dumstr\n\n  namelist/vectorize_namelist/ keep_lu_list, full_geo_em, vector_directory\n\n  ! Default values\n  keep_lu_list = -99999\n  landuse_count = 0\n  full_geo_em = \" \"\n  vector_directory = \" \"\n  open(12, file=\"namelist.vectorize\", status='old', form='formatted', action='read')\n  read(12, vectorize_namelist)\n  close(12)\n  do while (keep_lu_list(landuse_count+1) > 0)\n     landuse_count = landuse_count + 1\n  enddo\n  write(*,'(\"Keep the following \", I4, \" land-use categories:\")') landuse_count\n  write(*,'(\"         \", I4)') keep_lu_list(1:landuse_count)\n\n  call getarg(1,infile)\n  print *, 'Processing file: ',trim(infile)\n\n!!!!!\n! READ GEO_EM FILE TO GET THE VEGTYPE\n!!!!!\n\n  iret = nf90_open(trim(full_geo_em), NF90_NOWRITE, ncid_in)\n  call error_handler(iret, \"Problem opening geo_em file ''\"//trim(full_geo_em)//\"''\")\n\n  call get_dimlen(ncid_in, \"west_east\", west_east_old)\n  call get_dimlen(ncid_in, \"south_north\", south_north_old)\n\n  allocate(lu_index(west_east_old, south_north_old, 1))\n\n  iret = nf90_inq_varid(ncid_in,\"LU_INDEX\",varid_in(1))\n  call error_handler(iret, \"Problem getting varid for LU_INDEX from geo_em file\")\n\n  iret = nf90_get_var(ncid_in, varid_in(1), lu_index)\n  call error_handler(iret, \"Problem getting variable LU_INDEX from geo_em file\")\n\n  iret = nf90_close(ncid_in)\n  call error_handler(iret, \"Problem closing geo_em file\")\n\n  allocate(t2d_in     (west_east_old, south_north_old, 1))\n  allocate(q2d_in     (west_east_old, south_north_old, 1))\n  allocate(u2d_in     (west_east_old, south_north_old, 1))\n  allocate(v2d_in     (west_east_old, south_north_old, 1))\n  allocate(psfc_in    (west_east_old, south_north_old, 1))\n  allocate(rainrate_in(west_east_old, south_north_old, 1))\n  allocate(swdown_in  (west_east_old, south_north_old, 1))\n  allocate(lwdown_in  (west_east_old, south_north_old, 1))\n  allocate(weasd_in   (west_east_old, south_north_old, 1))\n  allocate(vegfra_in  (west_east_old, south_north_old, 1))\n  allocate(canwat_in  (west_east_old, south_north_old, 1))\n  allocate(skintemp_in(west_east_old, south_north_old, 1))\n  allocate(stemp1_in  (west_east_old, south_north_old, 1))\n  allocate(stemp2_in  (west_east_old, south_north_old, 1))\n  allocate(stemp3_in  (west_east_old, south_north_old, 1))\n  allocate(stemp4_in  (west_east_old, south_north_old, 1))\n  allocate(smois1_in  (west_east_old, south_north_old, 1))\n  allocate(smois2_in  (west_east_old, south_north_old, 1))\n  allocate(smois3_in  (west_east_old, south_north_old, 1))\n  allocate(smois4_in  (west_east_old, south_north_old, 1))\n  allocate(gvfmin_in  (west_east_old, south_north_old, 1))\n  allocate(gvfmax_in  (west_east_old, south_north_old, 1))\n  allocate(z2d_in     (west_east_old, south_north_old, 1))\n\n  allocate(lumask(west_east_old, south_north_old))\n  lumask = .FALSE.\n  do k = 1, landuse_count\n     where (nint(lu_index(:,:,1)) == keep_lu_list(k)) lumask = .TRUE.\n  enddo\n  west_east_new = count(lumask)\n  south_north_new = 1\n  write(*, '(\"Count of points to keep = \", I20)') west_east_new\n\n  allocate(t2d_out     (west_east_new, south_north_new, 1))\n  allocate(q2d_out     (west_east_new, south_north_new, 1))\n  allocate(u2d_out     (west_east_new, south_north_new, 1))\n  allocate(v2d_out     (west_east_new, south_north_new, 1))\n  allocate(psfc_out    (west_east_new, south_north_new, 1))\n  allocate(rainrate_out(west_east_new, south_north_new, 1))\n  allocate(swdown_out  (west_east_new, south_north_new, 1))\n  allocate(lwdown_out  (west_east_new, south_north_new, 1))\n  allocate(weasd_out   (west_east_new, south_north_new, 1))\n  allocate(vegfra_out  (west_east_new, south_north_new, 1))\n  allocate(canwat_out  (west_east_new, south_north_new, 1))\n  allocate(skintemp_out(west_east_new, south_north_new, 1))\n  allocate(stemp1_out  (west_east_new, south_north_new, 1))\n  allocate(stemp2_out  (west_east_new, south_north_new, 1))\n  allocate(stemp3_out  (west_east_new, south_north_new, 1))\n  allocate(stemp4_out  (west_east_new, south_north_new, 1))\n  allocate(smois1_out  (west_east_new, south_north_new, 1))\n  allocate(smois2_out  (west_east_new, south_north_new, 1))\n  allocate(smois3_out  (west_east_new, south_north_new, 1))\n  allocate(smois4_out  (west_east_new, south_north_new, 1))\n  allocate(gvfmin_out  (west_east_new, south_north_new, 1))\n  allocate(gvfmax_out  (west_east_new, south_north_new, 1))\n  allocate(z2d_out     (west_east_new, south_north_new, 1))\n\n!!!!!\n! READ IN VARIABLES\n!!!!!\n\n  iret = nf90_open(trim(infile), NF90_NOWRITE, ncid_in)\n  call error_handler(iret, \"Problem opening input file\")\n\n  call read_var_2d(ncid_in, \"T2D\",      varid_in(1), t2d_in(:,:,1),      west_east_old, south_north_old)\n  call read_var_2d(ncid_in, \"Q2D\",      varid_in(2), q2d_in(:,:,1),      west_east_old, south_north_old)\n  call read_var_2d(ncid_in, \"U2D\",      varid_in(3), u2d_in(:,:,1),      west_east_old, south_north_old)\n  call read_var_2d(ncid_in, \"V2D\",      varid_in(4), v2d_in(:,:,1),      west_east_old, south_north_old)\n  call read_var_2d(ncid_in, \"PSFC\",     varid_in(5), psfc_in(:,:,1),     west_east_old, south_north_old)\n  call read_var_2d(ncid_in, \"RAINRATE\", varid_in(6), rainrate_in(:,:,1), west_east_old, south_north_old)\n  call read_var_2d(ncid_in, \"SWDOWN\",   varid_in(7), swdown_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d(ncid_in, \"LWDOWN\",   varid_in(8), lwdown_in(:,:,1),   west_east_old, south_north_old)\n\n  ! Optional variables:\n\n  call read_var_2d_optional(ncid_in, \"WEASD\",    FOUND_WEASD,    varid_in(9),  weasd_in(:,:,1),    west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"VEGFRA\",   FOUND_VEGFRA,   varid_in(10), vegfra_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"CANWAT\",   FOUND_CANWAT,   varid_in(11), canwat_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"SKINTEMP\", FOUND_SKINTEMP, varid_in(12), skintemp_in(:,:,1), west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"STEMP_1\",  FOUND_STEMP1,   varid_in(13), stemp1_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"STEMP_2\",  FOUND_STEMP2,   varid_in(14), stemp2_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"STEMP_3\",  FOUND_STEMP3,   varid_in(15), stemp3_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"STEMP_4\",  FOUND_STEMP4,   varid_in(16), stemp4_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"SMOIS_1\",  FOUND_SMOIS1,   varid_in(17), smois1_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"SMOIS_2\",  FOUND_SMOIS2,   varid_in(18), smois2_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"SMOIS_3\",  FOUND_SMOIS3,   varid_in(19), smois3_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"SMOIS_4\",  FOUND_SMOIS4,   varid_in(20), smois4_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"GVFMIN\",   FOUND_GVFMIN,   varid_in(21), gvfmin_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"GVFMAX\",   FOUND_GVFMAX,   varid_in(22), gvfmax_in(:,:,1),   west_east_old, south_north_old)\n  call read_var_2d_optional(ncid_in, \"Z2D\",      FOUND_Z2D,      varid_in(23), z2d_in(:,:,1),      west_east_old, south_north_old)\n\n!!!!!\n! CREATE A NEW FILE IN VECTOR FORMAT\n!!!!!\n\n  iret = nf90_create(trim(vector_directory)//trim(infile(index(infile,\"/\",.TRUE.):)), NF90_CLOBBER, ncid_out)\n  call error_handler(iret, \"Problem creating file '\"//trim(vector_directory)//trim(infile(index(infile,\"/\",.TRUE.):))//\"'\")\n\n  iret = nf90_def_dim(ncid_out,\"Time\",NF90_UNLIMITED,dim_time)\n  call error_handler(iret, \"Problem defining dimension 'Time'\")\n\n  iret = nf90_def_dim(ncid_out,\"DateStrLen\",19,dim_date)\n  call error_handler(iret, \"Problem defining dimension 'DateStrLen'\")\n\n  iret = nf90_def_dim(ncid_out,\"west_east\",west_east_new,dim_we)\n  call error_handler(iret, \"Problem defining dimension 'west_east'\")\n\n  iret = nf90_def_dim(ncid_out,\"south_north\",south_north_new,dim_sn)\n  call error_handler(iret, \"Problem defining dimension 'south_north'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"TITLE\", attstring)\n  call error_handler(iret, \"Problem getting attribute 'TITLE'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"TITLE\",trim(attstring))\n  call error_handler(iret, \"Problem putting attribute 'TITLE'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"missing_value\", attfloat)\n  call error_handler(iret, \"Problem getting attribute 'missing_value'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"missing_value\", attfloat)\n  call error_handler(iret, \"Problem putting attribute 'missing_value'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"_FillValue\", attfloat)\n  call error_handler(iret, \"Problem getting attribute '_FillValue'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"_FillValue\", attfloat)\n  call error_handler(iret, \"Problem putting attribute '_FillValue'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"WEST-EAST_GRID_DIMENSION\", west_east_new+1)\n  call error_handler(iret, \"Problem putting attribute 'WEST-EAST_GRID_DIMENSION'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"SOUTH-NORTH_GRID_DIMENSION\", south_north_new+1)\n  call error_handler(iret, \"Problem putting attribute 'SOUTH-NORTH_GRID_DIMENSION'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"DX\", attfloat)\n  call error_handler(iret, \"Problem getting attribute 'DX'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"DX\", attfloat)\n  call error_handler(iret, \"Problem putting attribute 'DX'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"DY\", attfloat)\n  call error_handler(iret, \"Problem getting attribute 'DY'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"DY\", attfloat)\n  call error_handler(iret, \"Problem putting attribute 'DY'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"TRUELAT1\", attfloat)\n  call error_handler(iret, \"Problem getting attribute 'TRUELAT1'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"TRUELAT1\", attfloat)\n  call error_handler(iret, \"Problem putting attribute 'TRUELAT1'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"TRUELAT2\", attfloat)\n  call error_handler(iret, \"Problem getting attribute 'TRUELAT2'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"TRUELAT2\", attfloat)\n  call error_handler(iret, \"Problem putting attribute 'TRUELAT2'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"LA1\", attfloat)\n  call error_handler(iret, \"Problem getting attribute 'LA1'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"LA1\", attfloat)\n  call error_handler(iret, \"Problem putting attribute 'LA1'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"LO1\", attfloat)\n  call error_handler(iret, \"Problem getting attribute 'LO1'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"LO1\", attfloat)\n  call error_handler(iret, \"Problem putting attribute 'LO1'\")\n\n!KWM  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"LA2\", attfloat)\n!KWM  call error_handler(iret, \"Problem putting attribute 'LA2'\")\n!KWM\n!KWM  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"LA2\", attfloat)\n!KWM  call error_handler(iret, \"Problem putting attribute 'LA2'\")\n!KWM\n!KWM  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"LO2\", attfloat)\n!KWM  call error_handler(iret, \"Problem getting attribute 'LO2'\")\n!KWM\n!KWM  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"LO2\", attfloat)\n!KWM  call error_handler(iret, \"Problem putting attribute 'LO2'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"STAND_LON\", attfloat)\n  call error_handler(iret, \"Problem getting attribute 'STAND_LON'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"STAND_LON\", attfloat)\n  call error_handler(iret, \"Problem putting attribute 'STAND_LON'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"MAP_PROJ\", attint)\n  call error_handler(iret, \"Problem getting attribute 'MAP_PROJ'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"MAP_PROJ\", attint)\n  call error_handler(iret, \"Problem putting attribute 'MAP_PROJ'\")\n\n  iret = nf90_get_att(ncid_in, NF90_GLOBAL, \"MMINLU\", attstring)\n  call error_handler(iret, \"Problem getting attribute 'MMINLU'\")\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"MMINLU\", attstring)\n  call error_handler(iret, \"Problem putting attribute 'MMINLU'\")\n\n  lustring = \" \"\n  do k = 1, landuse_count\n     write(dumstr, *) keep_lu_list(k)\n     if (k>1) lustring = trim(lustring)//\",\"\n     lustring = trim(lustring) // trim(adjustl(dumstr))\n  enddo\n  iret = nf90_put_att(ncid_out, NF90_GLOBAL, \"vector_landuse_indices\", trim(lustring))\n  call error_handler(iret,\"Problem putting attribute 'vector_landuse_indices'\")\n\n!!!!!\n! Fill our vectors\n!!!!!\n\n  iloc = 0\n  do ilat = 1,south_north_old\n     do ilon = 1,west_east_old\n        if (lumask(ilon,ilat)) then\n           iloc = iloc + 1\n           if (iloc > west_east_new) then\n              print*, 'up to ', iloc\n              stop \"Too many!\"\n           endif\n           t2d_out(iloc,1,1) = t2d_in(ilon,ilat,1)\n           q2d_out(iloc,1,1) = q2d_in(ilon,ilat,1)\n           u2d_out(iloc,1,1) = u2d_in(ilon,ilat,1)\n           v2d_out(iloc,1,1) = v2d_in(ilon,ilat,1)\n           psfc_out(iloc,1,1) = psfc_in(ilon,ilat,1)\n           rainrate_out(iloc,1,1) = rainrate_in(ilon,ilat,1)\n           swdown_out(iloc,1,1) = swdown_in(ilon,ilat,1)\n           lwdown_out(iloc,1,1) = lwdown_in(ilon,ilat,1)\n           if (FOUND_WEASD)    weasd_out   (iloc,1,1) = weasd_in   (ilon,ilat,1)\n           if (FOUND_VEGFRA)   vegfra_out  (iloc,1,1) = vegfra_in  (ilon,ilat,1) \n           if (FOUND_CANWAT)   canwat_out  (iloc,1,1) = canwat_in  (ilon,ilat,1)\n           if (FOUND_SKINTEMP) skintemp_out(iloc,1,1) = skintemp_in(ilon,ilat,1) \n           if (FOUND_STEMP1)   stemp1_out  (iloc,1,1) = stemp1_in  (ilon,ilat,1) \n           if (FOUND_STEMP1)   stemp2_out  (iloc,1,1) = stemp2_in  (ilon,ilat,1) \n           if (FOUND_STEMP1)   stemp3_out  (iloc,1,1) = stemp3_in  (ilon,ilat,1) \n           if (FOUND_STEMP1)   stemp4_out  (iloc,1,1) = stemp4_in  (ilon,ilat,1) \n           if (FOUND_SMOIS1)   smois1_out  (iloc,1,1) = smois1_in  (ilon,ilat,1) \n           if (FOUND_SMOIS1)   smois2_out  (iloc,1,1) = smois2_in  (ilon,ilat,1) \n           if (FOUND_SMOIS1)   smois3_out  (iloc,1,1) = smois3_in  (ilon,ilat,1) \n           if (FOUND_SMOIS1)   smois4_out  (iloc,1,1) = smois4_in  (ilon,ilat,1) \n           if (FOUND_GVFMIN)   gvfmin_out  (iloc,1,1) = gvfmin_in  (ilon,ilat,1) \n           if (FOUND_GVFMAX)   gvfmax_out  (iloc,1,1) = gvfmax_in  (ilon,ilat,1) \n           if (FOUND_Z2D)      z2d_out     (iloc,1,1) = z2d_in     (ilon,ilat,1) \n        endif\n     enddo\n  enddo\n\n!!!!!\n! Define the new variables in our output file\n!!!!!\n\n  call define_var(ncid_out, \"T2D\",      dim_we, dim_sn, dim_time, varid_out(1), \"K\")\n  call define_var(ncid_out, \"Q2D\",      dim_we, dim_sn, dim_time, varid_out(2), \"kg kg{-1}\")\n  call define_var(ncid_out, \"U2D\",      dim_we, dim_sn, dim_time, varid_out(3), \"m s{-1}\")\n  call define_var(ncid_out, \"V2D\",      dim_we, dim_sn, dim_time, varid_out(4), \"m s{-1}\")\n  call define_var(ncid_out, \"PSFC\",     dim_we, dim_sn, dim_time, varid_out(5), \"Pa\")\n  call define_var(ncid_out, \"RAINRATE\", dim_we, dim_sn, dim_time, varid_out(6), \"mm s{-1}\")\n  call define_var(ncid_out, \"SWDOWN\",   dim_we, dim_sn, dim_time, varid_out(7), \"W m{-2}\")\n  call define_var(ncid_out, \"LWDOWN\",   dim_we, dim_sn, dim_time, varid_out(8), \"W m{-2}\")\n\n  if ( FOUND_WEASD ) then\n     call define_var(ncid_out, \"WEASD\", dim_we, dim_sn, dim_time, varid_out(9), \"kg m{-2}\")\n  endif\n\n  if ( FOUND_VEGFRA ) then\n     call define_var(ncid_out, \"VEGFRA\", dim_we, dim_sn, dim_time, varid_out(10), \"%\")\n  endif\n\n  if ( FOUND_CANWAT ) then\n     call define_var(ncid_out, \"CANWAT\", dim_we, dim_sn, dim_time, varid_out(11), \"kg m{-2}\")\n  endif\n\n  if ( FOUND_SKINTEMP ) then\n     call define_var(ncid_out, \"SKINTEMP\", dim_we, dim_sn, dim_time, varid_out(12), \"K\")\n  endif\n\n  if ( FOUND_STEMP1 ) then\n     call define_var(ncid_out, \"STEMP_1\", dim_we, dim_sn, dim_time, varid_out(13), \"K\")\n  endif\n\n  if ( FOUND_STEMP2 ) then\n     call define_var(ncid_out, \"STEMP_2\", dim_we, dim_sn, dim_time, varid_out(14), \"K\")\n  endif\n\n  if ( FOUND_STEMP3 ) then\n     call define_var(ncid_out, \"STEMP_3\", dim_we, dim_sn, dim_time, varid_out(15), \"K\")\n  endif\n\n  if ( FOUND_STEMP4 ) then\n     call define_var(ncid_out, \"STEMP_4\", dim_we, dim_sn, dim_time, varid_out(16), \"K\")\n  endif\n\n  if ( FOUND_SMOIS1 ) then\n     call define_var(ncid_out, \"SMOIS_1\", dim_we, dim_sn, dim_time, varid_out(17), \"fraction\")\n  endif\n\n  if ( FOUND_SMOIS2 ) then\n     call define_var(ncid_out, \"SMOIS_2\", dim_we, dim_sn, dim_time, varid_out(18), \"fraction\")\n  endif\n\n  if ( FOUND_SMOIS3 ) then\n     call define_var(ncid_out, \"SMOIS_3\", dim_we, dim_sn, dim_time, varid_out(19), \"fraction\")\n  endif\n\n  if ( FOUND_SMOIS4 ) then\n     call define_var(ncid_out, \"SMOIS_4\", dim_we, dim_sn, dim_time, varid_out(20), \"fraction\")\n  endif\n\n  if ( FOUND_GVFMIN ) then\n     call define_var(ncid_out, \"GVFMIN\", dim_we, dim_sn, dim_time, varid_out(21), \"%\")\n  endif\n\n  if ( FOUND_GVFMAX ) then\n     call define_var(ncid_out, \"GVFMAX\", dim_we, dim_sn, dim_time, varid_out(22), \"%\")\n  endif\n\n  if ( FOUND_Z2D ) then\n     call define_var(ncid_out, \"Z2D\",    dim_we, dim_sn, dim_time, varid_out(23), \"m\")\n  endif\n\n!!!!!\n! Get out of define mode\n!!!!!\n\n  iret = nf90_enddef(ncid_out)\n  call error_handler(iret, \"Problem exiting define mode\")\n\n!!!!!\n! WRITE VARIABLES\n!!!!!\n\n  iret = nf90_put_var(ncid_out,varid_out(1),t2d_out)\n  call error_handler(iret, \"Problem writing variable 'T2D'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(2),q2d_out)\n  call error_handler(iret, \"Problem writing variable 'Q2D'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(3),u2d_out)\n  call error_handler(iret, \"Problem writing variable 'U2D'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(4),v2d_out)\n  call error_handler(iret, \"Problem writing variable 'V2D'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(5),psfc_out)\n  call error_handler(iret, \"Problem writing variable 'PSFC'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(6),rainrate_out)\n  call error_handler(iret, \"Problem writing variable 'RAINRATE'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(7),swdown_out)\n  call error_handler(iret, \"Problem writing variable 'SWDOWN'\")\n\n  iret = nf90_put_var(ncid_out,varid_out(8),lwdown_out)\n  call error_handler(iret, \"Problem writing variable 'LWDOWN'\")\n\n  if ( FOUND_WEASD ) then\n     iret = nf90_put_var(ncid_out,varid_out(9),weasd_out)\n     call error_handler(iret, \"Problem writing variable 'WEASD'\")\n  endif\n\n  if ( FOUND_VEGFRA ) then\n     iret = nf90_put_var(ncid_out,varid_out(10),vegfra_out)\n     call error_handler(iret, \"Problem writing variable 'VEGFRA'\")\n  endif\n\n  if ( FOUND_CANWAT ) then\n     iret = nf90_put_var(ncid_out,varid_out(11),canwat_out)\n     call error_handler(iret, \"Problem writing variable 'CANWAT'\")\n  endif\n\n  if ( FOUND_SKINTEMP ) then\n     iret = nf90_put_var(ncid_out,varid_out(12),skintemp_out)\n     call error_handler(iret, \"Problem writing variable 'SKINTEMP'\")\n  endif\n\n  if ( FOUND_STEMP1 ) then\n     iret = nf90_put_var(ncid_out,varid_out(13),stemp1_out)\n     call error_handler(iret, \"Problem writing variable 'STEMP_1'\")\n  endif\n\n  if ( FOUND_STEMP2 ) then\n     iret = nf90_put_var(ncid_out,varid_out(14),stemp2_out)\n     call error_handler(iret, \"Problem writing variable 'STEMP_2'\")\n  endif\n\n  if ( FOUND_STEMP3 ) then\n     iret = nf90_put_var(ncid_out,varid_out(15),stemp3_out)\n     call error_handler(iret, \"Problem writing variable 'STEMP_3'\")\n  endif\n\n  if ( FOUND_STEMP4 ) then\n     iret = nf90_put_var(ncid_out,varid_out(16),stemp4_out)\n     call error_handler(iret, \"Problem writing variable 'STEMP_4'\")\n  endif\n\n  if ( FOUND_SMOIS1 ) then\n     iret = nf90_put_var(ncid_out,varid_out(17),smois1_out)\n     call error_handler(iret, \"Problem writing variable 'SMOIS_1'\")\n  endif\n\n  if ( FOUND_SMOIS2 ) then\n     iret = nf90_put_var(ncid_out,varid_out(18),smois2_out)\n     call error_handler(iret, \"Problem writing variable 'SMOIS_2'\")\n  endif\n\n  if ( FOUND_SMOIS3 ) then\n     iret = nf90_put_var(ncid_out,varid_out(19),smois3_out)\n     call error_handler(iret, \"Problem writing variable 'SMOIS_3'\")\n  endif\n\n  if ( FOUND_SMOIS4 ) then\n     iret = nf90_put_var(ncid_out,varid_out(20),smois4_out)\n     call error_handler(iret, \"Problem writing variable 'SMOIS_4'\")\n  endif\n\n  if ( FOUND_GVFMIN ) then\n     iret = nf90_put_var(ncid_out,varid_out(21),gvfmin_out)\n     call error_handler(iret, \"Problem writing variable 'GVFMIN'\")\n  endif\n\n  if ( FOUND_GVFMAX ) then\n     iret = nf90_put_var(ncid_out,varid_out(22),gvfmax_out)\n     call error_handler(iret, \"Problem writing variable 'GVFMAX'\")\n  endif\n\n  if ( FOUND_Z2D ) then\n     iret = nf90_put_var(ncid_out,varid_out(23),z2d_out)\n     call error_handler(iret, \"Problem writing variable 'Z2D'\")\n  endif\n\n  iret = nf90_close(ncid_out)\n  call error_handler(iret, \"Problem closing output file\")\n\n  iret = nf90_close(ncid_in)\n  call error_handler(iret, \"Problem closing input file\")\n\nend program vectorize_ldasin\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n\nsubroutine error_handler(ierr, failure)\n  use netcdf\n  implicit none\n  integer, intent(in) :: ierr\n  character(len=*), intent(in) :: failure\n\n  if (ierr == NF90_NOERR) return\n\n  write(*, '(\"----ERROR---------------------------------------------------\")')\n  write(*, '(5X,A)') trim(nf90_strerror(ierr))\n  if (failure /= \"\") write(*, '(5X,A)') trim(failure)\n  write(*, '(\"------------------------------------------------------------\")')\n  stop\n\nend subroutine error_handler\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n\nsubroutine get_dimlen(ncid, name, dimlen)\n  use netcdf\n  implicit none\n  integer, intent(in) :: ncid\n  character(len=*), intent(in) :: name\n  integer, intent(out) :: dimlen\n\n  integer :: dimid\n  integer :: ierr\n\n  ierr = nf90_inq_dimid(ncid, name, dimid)\n  call error_handler(ierr, \"GET_DIMLEN : Problem getting dimension id for '\"//name//\"'\")\n\n  ierr = nf90_inquire_dimension(ncid, dimid, len=dimlen)\n  call error_handler(ierr, \"GET_DIMLEN : Problem getting dimension length for '\"//name//\"'\")\n\nend subroutine get_dimlen\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n\nsubroutine read_var_2d(ncid, name, varid, array, idim, jdim)\n  use netcdf\n  implicit none\n  integer,                    intent(in)  :: ncid\n  character(len=*),           intent(in)  :: name\n  integer,                    intent(in)  :: idim\n  integer,                    intent(in)  :: jdim\n  integer,                    intent(out) :: varid\n  real, dimension(idim,jdim), intent(out) :: array   ! Assumed-shape array\n\n  integer :: iret\n\n  iret = nf90_inq_varid ( ncid, name, varid )\n  call error_handler(iret, \"Problem getting varid for '\"//name//\"'\")\n\n  iret = nf90_get_var ( ncid, varid, array)\n  call error_handler(iret, \"Problem getting variable '\"//name//\"'\")\n\nend subroutine read_var_2d\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n\nsubroutine read_var_2d_optional(ncid, name, found, varid, array, idim, jdim)\n  use netcdf\n  implicit none\n  integer,                    intent(in)  :: ncid\n  character(len=*),           intent(in)  :: name\n  integer,                    intent(in)  :: idim\n  integer,                    intent(in)  :: jdim\n  logical,                    intent(out) :: found\n  integer,                    intent(out) :: varid\n  real, dimension(idim,jdim), intent(out) :: array   ! Assumed-shape array\n\n  integer :: iret\n\n  iret = nf90_inq_varid ( ncid, name, varid )\n  if ( iret /= NF90_NOERR ) then\n     found = .FALSE.\n     write(*,'(\"Problem getting varid for variable ''\",A,\"''\")') name\n     write(*,'(\"Continuing to process this time without ''\",A,\"''\")') name\n  else\n     found = .TRUE.\n     iret = nf90_get_var(ncid, varid, array)\n     call error_handler(iret, \"Problem getting variable '\"//name//\"'\")\n  endif\n\nend subroutine read_var_2d_optional\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n\nsubroutine define_var(ncid, name, dim_we, dim_sn, dim_time, varid, units)\n  use netcdf\n  implicit none\n  integer,          intent(in)  :: ncid\n  character(len=*), intent(in)  :: name\n  integer,          intent(in)  :: dim_we\n  integer,          intent(in)  :: dim_sn\n  integer,          intent(in)  :: dim_time\n  integer,          intent(out) :: varid\n  character(len=*), intent(in)  :: units\n  integer :: iret\n\n  iret = nf90_def_var(ncid, name, NF90_FLOAT, (/dim_we,dim_sn,dim_time/), varid)\n  call error_handler(iret, \"Problem defining variable '\"//name//\"'\")\n  iret = nf90_put_att(ncid,varid,\"units\",units)\n  call error_handler(iret, \"Problem putting attribute 'units' for variable '\"//name//\"'\")\n  iret = nf90_put_att(ncid,varid,\"_FillValue\",-1.E36)\n  call error_handler(iret, \"Problem putting attribute '_FillValue' for variable '\"//name//\"'\")\nend subroutine define_var\n\n!-----------------------------------------------------------------------------\n!-----------------------------------------------------------------------------\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_programs/vectorize/vectorize_wrfinput.f90",
    "content": "program vectorize_wrfinput\n  use netcdf\n  implicit none\n\n  integer :: ncid_in, ncid_out\n  integer :: iret,iloc,ilat,ilon\n  integer :: dim_date, dim_we, dim_sn, dim_time, ndims, nvars, natts\n  integer :: varid_in(6), varid_out(6)\n  character (len = 80) :: attname\n\n  integer, parameter :: west_east = 1563016\n  integer, parameter :: south_north = 1\n  real :: lu_index(1795,2632,1)\n  integer, dimension(1795,2632,1) :: ivgtyp_in,   &\n                                     isltyp_in\n     real, dimension(1795,2632,1) :: hgt_in,      &\n\t\t\t\t     xlat_in,     &\n\t\t\t\t     xlong_in,    &\n                                     tmn_in\n  integer, dimension(west_east,south_north,1) :: ivgtyp_out,   &\n                                                 isltyp_out\n     real, dimension(west_east,south_north,1) :: hgt_out,      &\n\t\t\t\t\t         xlat_out,     &\n\t\t\t\t\t         xlong_out,    &\n                                                 tmn_out\n\n!!!!!\n! READ GEO_EM FILE TO GET THE VEGTYPE\n!!!!!\n\n  iret = nf90_open(\"/d1/model/WPS/geo_em.d01.nc\", NF90_NOWRITE, ncid_in)\n   if(iret/=0) print*, \"Problem opening file\"\n\n  iret = nf90_inq_varid(ncid_in,\"LU_INDEX\",varid_in(1))\n   if(iret/=0) print*, \"Problem getting varid\"\n\n  iret = nf90_get_var(ncid_in, varid_in(1), lu_index)\n   if(iret/=0) print*, \"Problem getting variable\"\n\n  iret = nf90_close(ncid_in)\n   if(iret/=0) print*, \"Problem closing file\"\n\n!!!!!\n! CREATE A NEW FILE IN VECTOR FORMAT\n!!!!!\n\n  iret = nf90_create(\"/d1/data/vector/WRF/wrfinput_d01\", NF90_CLOBBER, ncid_out)\n   if(iret/=0) print*, \"Problem creating file\"\n\n  iret = nf90_def_dim(ncid_out,\"Time\",NF90_UNLIMITED,dim_time)\n  iret = nf90_def_dim(ncid_out,\"DateStrLen\",19,dim_date)\n  iret = nf90_def_dim(ncid_out,\"west_east\",west_east,dim_we)\n  iret = nf90_def_dim(ncid_out,\"south_north\",south_north,dim_sn)\n\n  iret = nf90_open(\"/d1/model/WRFV3/run/wrfinput_d01\", NF90_NOWRITE, ncid_in)\n   if(iret/=0) print*, \"Problem opening file\"\n\n  iret = nf90_inquire(ncid_in,ndims, nvars, natts)\n   if(iret/=0) print*, \"Problem getting number attributes\"\n\n  do iloc = 1, natts\n    iret = nf90_inq_attname(ncid_in,NF90_GLOBAL, iloc, attname)\n     if(iret/=0) print*, \"Problem getting attribute name\"\n    iret = nf90_copy_att(ncid_in, NF90_GLOBAL, trim(attname), ncid_out, NF90_GLOBAL)\n  end do\n\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"WEST-EAST_GRID_DIMENSION\", west_east+1)\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"SOUTH-NORTH_GRID_DIMENSION\", south_north+1)\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"WEST-EAST_PATCH_END_UNSTAG\", west_east)\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"WEST-EAST_PATCH_END_STAG\", west_east+1)\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"SOUTH-NORTH_PATCH_END_UNSTAG\", south_north)\n  iret = nf90_put_att(ncid_out,NF90_GLOBAL,\"SOUTH-NORTH_PATCH_END_STAG\", south_north+1)\n\n!!!!!\n! READ IN VARIABLES ONE AT A TIME, EXTRACT AND WRITE TO NEW FILE\n!!!!!\n\n!!!!!\n! IVGTYP\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"IVGTYP\",varid_in(1))\n   if(iret/=0) print*, \"Problem getting varid\"\n\n  iret = nf90_get_var(ncid_in, varid_in(1), ivgtyp_in)\n   if(iret/=0) print*, \"Problem getting variable\"\n\n!!!!!\n! ISLTYP\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"ISLTYP\",varid_in(2))\n   if(iret/=0) print*, \"Problem getting varid\"\n\n  iret = nf90_get_var(ncid_in, varid_in(2), isltyp_in)\n   if(iret/=0) print*, \"Problem getting variable\"\n\n!!!!!\n! HGT\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"HGT\",varid_in(3))\n   if(iret/=0) print*, \"Problem getting varid\"\n\n  iret = nf90_get_var(ncid_in, varid_in(3), hgt_in)\n   if(iret/=0) print*, \"Problem getting variable\"\n\n!!!!!\n! XLAT\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"XLAT\",varid_in(4))\n   if(iret/=0) print*, \"Problem getting varid\"\n\n  iret = nf90_get_var(ncid_in, varid_in(4), xlat_in)\n   if(iret/=0) print*, \"Problem getting variable\"\n\n!!!!!\n! XLONG\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"XLONG\",varid_in(5))\n   if(iret/=0) print*, \"Problem getting varid\"\n\n  iret = nf90_get_var(ncid_in, varid_in(5), xlong_in)\n   if(iret/=0) print*, \"Problem getting variable\"\n\n!!!!!\n! TMN\n!!!!!\n\n  iret = nf90_inq_varid(ncid_in,\"TMN\",varid_in(6))\n   if(iret/=0) print*, \"Problem getting varid\"\n\n  iret = nf90_get_var(ncid_in, varid_in(6), tmn_in)\n   if(iret/=0) print*, \"Problem getting variable\"\n\n  iloc = 0\n  do ilat = 1,2632\n  do ilon = 1,1795\n   if(lu_index(ilon,ilat,1)>=1 .and. lu_index(ilon,ilat,1)<=5) then\n     iloc = iloc + 1\n     ivgtyp_out(iloc,1,1) = ivgtyp_in(ilon,ilat,1)\n     isltyp_out(iloc,1,1) = isltyp_in(ilon,ilat,1)\n        hgt_out(iloc,1,1) = hgt_in(ilon,ilat,1)\n       xlat_out(iloc,1,1) = xlat_in(ilon,ilat,1)\n      xlong_out(iloc,1,1) = xlong_in(ilon,ilat,1)\n        tmn_out(iloc,1,1) = tmn_in(ilon,ilat,1)\n   end if\n  end do\n  end do\n\n!!!!!\n! IVGTYP\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"IVGTYP\",NF90_INT,(/dim_we,dim_sn,dim_time/),varid_out(1))\n   if(iret/=0) print*, \"Problem defining variable\"\n    iret = nf90_put_att(ncid_out,varid_out(1),\"FieldType\",106)\n    iret = nf90_put_att(ncid_out,varid_out(1),\"MemoryOrder\",\"XY \")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"description\",\"DOMINANT VEGETATION CATEGORY\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"units\",\"\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"stagger\",\"\")\n    iret = nf90_put_att(ncid_out,varid_out(1),\"coordinates\",\"XLONG XLAT\")\n\n!!!!!\n! ISLTYP\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"ISLTYP\",NF90_INT,(/dim_we,dim_sn,dim_time/),varid_out(2))\n   if(iret/=0) print*, \"Problem defining variable\"\n    iret = nf90_put_att(ncid_out,varid_out(2),\"FieldType\",106)\n    iret = nf90_put_att(ncid_out,varid_out(2),\"MemoryOrder\",\"XY \")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"description\",\"DOMINANT SOIL CATEGORY\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"units\",\"\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"stagger\",\"\")\n    iret = nf90_put_att(ncid_out,varid_out(2),\"coordinates\",\"XLONG XLAT\")\n\n!!!!!\n! HGT\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"HGT\",NF90_FLOAT,(/dim_we,dim_sn,dim_time/),varid_out(3))\n   if(iret/=0) print*, \"Problem defining variable\"\n    iret = nf90_put_att(ncid_out,varid_out(3),\"FieldType\",104)\n    iret = nf90_put_att(ncid_out,varid_out(3),\"MemoryOrder\",\"XY \")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"description\",\"Terrain Height\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"units\",\"m\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"stagger\",\"\")\n    iret = nf90_put_att(ncid_out,varid_out(3),\"coordinates\",\"XLONG XLAT\")\n\n!!!!!\n! XLAT\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"XLAT\",NF90_FLOAT,(/dim_we,dim_sn,dim_time/),varid_out(4))\n   if(iret/=0) print*, \"Problem defining variable\"\n    iret = nf90_put_att(ncid_out,varid_out(4),\"FieldType\",104)\n    iret = nf90_put_att(ncid_out,varid_out(4),\"MemoryOrder\",\"XY \")\n    iret = nf90_put_att(ncid_out,varid_out(4),\"description\",\"LATITUDE, SOUTH IS NEGATIVE\")\n    iret = nf90_put_att(ncid_out,varid_out(4),\"units\",\"degree_north\")\n    iret = nf90_put_att(ncid_out,varid_out(4),\"stagger\",\"\")\n\n!!!!!\n! XLONG\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"XLONG\",NF90_FLOAT,(/dim_we,dim_sn,dim_time/),varid_out(5))\n   if(iret/=0) print*, \"Problem defining variable\"\n    iret = nf90_put_att(ncid_out,varid_out(5),\"FieldType\",104)\n    iret = nf90_put_att(ncid_out,varid_out(5),\"MemoryOrder\",\"XY \")\n    iret = nf90_put_att(ncid_out,varid_out(5),\"description\",\"LONGITUDE, WEST IS NEGATIVE\")\n    iret = nf90_put_att(ncid_out,varid_out(5),\"units\",\"degree_east\")\n    iret = nf90_put_att(ncid_out,varid_out(5),\"stagger\",\"\")\n\n!!!!!\n! TMN\n!!!!!\n\n  iret = nf90_def_var(ncid_out,\"TMN\",NF90_FLOAT,(/dim_we,dim_sn,dim_time/),varid_out(6))\n   if(iret/=0) print*, \"Problem defining variable\"\n    iret = nf90_put_att(ncid_out,varid_out(6),\"FieldType\",104)\n    iret = nf90_put_att(ncid_out,varid_out(6),\"MemoryOrder\",\"XY \")\n    iret = nf90_put_att(ncid_out,varid_out(6),\"description\",\"SOIL TEMPERATURE AT LOWER BOUNDARY\")\n    iret = nf90_put_att(ncid_out,varid_out(6),\"units\",\"K\")\n    iret = nf90_put_att(ncid_out,varid_out(6),\"stagger\",\"\")\n    iret = nf90_put_att(ncid_out,varid_out(6),\"coordinates\",\"XLONG XLAT\")\n\n  iret = nf90_enddef(ncid_out)\n\n\n!!!!!\n! WRITE VARIABLES\n!!!!!\n\n  iret = nf90_put_var(ncid_out,varid_out(1),ivgtyp_out)\n   if(iret/=0) print*, \"Problem writing variable\", iret\n\n  iret = nf90_put_var(ncid_out,varid_out(2),isltyp_out)\n   if(iret/=0) print*, \"Problem writing variable\", iret\n\n  iret = nf90_put_var(ncid_out,varid_out(3),hgt_out)\n   if(iret/=0) print*, \"Problem writing variable\", iret\n\n  iret = nf90_put_var(ncid_out,varid_out(4),xlat_out)\n   if(iret/=0) print*, \"Problem writing variable\", iret\n\n  iret = nf90_put_var(ncid_out,varid_out(5),xlong_out)\n   if(iret/=0) print*, \"Problem writing variable\", iret\n\n  iret = nf90_put_var(ncid_out,varid_out(6),tmn_out)\n   if(iret/=0) print*, \"Problem writing variable\", iret\n\n\n  iret = nf90_close(ncid_out)\n   if(iret/=0) print*, \"Problem closing output file\"\n\n  iret = nf90_close(ncid_in)\n   if(iret/=0) print*, \"Problem closing input file\"\n\n\nend program\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_routines/CMakeLists.txt",
    "content": "add_library(noah_util STATIC\n        kwm_string_utilities.F\n        module_date_utilities.F\n        module_model_constants.F\n        module_Noahlsm_utility.F\n        module_sfcdif_wrf.F\n)\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_routines/Makefile",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\ninclude ../user_build_options\n\nOBJS = \\\n\tmodule_date_utilities.o \\\n\tmodule_model_constants.o \\\n\tmodule_Noahlsm_utility.o \\\n\tmodule_sfcdif_wrf.o \\\n\tkwm_string_utilities.o\n\nCPPHRLDAS = -D_HRLDAS_OFFLINE_\n\n\nall:\t$(OBJS)\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS)  -o $(@) -c $(F90FLAGS) $(FREESOURCE) $(*).F\n\t@echo \"\"\n\n#\n# Dependencies:\n#\n\nmodule_Noahlsm.o:\tmodule_Noahlsm_param_init.o\n\n#\n# This command cleans up object (etc.) files:\n#\n\nclean:\n\t$(RM) *.o *.mod *.stb *~\n\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_routines/kwm_string_utilities.F",
    "content": "module kwm_string_utilities\n\ncontains\n\n  subroutine strrep(string, rep1, rep2)\n    ! In string 1, replace expression rep1 with expression rep2.\n    ! if rep2 is shorter than rep1, fill the end of the string\n    ! with blanks\n\n    implicit none\n    character(len=*) :: string, rep1, rep2\n    integer :: idx, inlen, len1, len2\n\n    do\n       inlen = len(string)\n       len1 = len(rep1)\n       len2 = len(rep2)\n       idx = index(string, rep1)-1\n\n       if (idx == -1) then\n          return\n       else\n          string = string(1:idx)// rep2 // &\n               string((idx+len1+1):inlen) // &\n               \"                                                    \"\n       endif\n    enddo\n\n  end subroutine strrep\n\n\n  character(len=1024) function unblank(string) result(return_string)\n    ! Remove blanks (and tabs [char(9)] from string\n    implicit none\n    character(len=*), intent(in) :: string\n    integer :: i, j,  lenstr\n\n    return_string = \" \"\n\n    if ( verify(string,\" \"//char(9)) == 0 ) then\n       stop 'String is all blanks.'\n    endif\n\n    j = 0\n    do i = 1, len(string)\n       if ((string(i:i).ne.' ').and.(string(i:i).ne.char(9))) then\n          j = j + 1\n          return_string(j:j) = string(i:i)\n       endif\n    enddo\n\n  end function unblank\n\n!KWM  character function upcase(h)\n!KWM    implicit none\n!KWM    character :: h\n!KWM\n!KWM    if ((ichar(h).ge.96) .and. (ichar(h).le.123)) then\n!KWM       upcase = char(ichar(h)-32)\n!KWM    else\n!KWM       upcase = h\n!KWM    endif\n!KWM\n!KWM  end function upcase\n\n  character(len=256) function upcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \" \"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.96) .and. (ichar(h(i:i)).le.123)) then\n          return_string(i:i) = char(ichar(h(i:i))-32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function upcase\n\n!KWM  character function downcase(h)\n!KWM    implicit none\n!KWM    character h\n!KWM\n!KWM    if ((ichar(h).ge.65) .and. (ichar(h).le.90)) then\n!KWM       downcase = char(ichar(h)+32)\n!KWM    else\n!KWM       downcase = h\n!KWM    endif\n!KWM  end function downcase\n\n  character(len=256) function downcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \" \"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.65) .and. (ichar(h(i:i)).le.90)) then\n          return_string(i:i) = char(ichar(h(i:i))+32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function downcase\n\n\nend module kwm_string_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_routines/module_Noahlsm_utility.F",
    "content": "MODULE module_Noahlsm_utility\n\n  REAL, PARAMETER      :: CP = 1004.5, RD = 287.04, SIGMA = 5.67E-8,    &\n                          CPH2O = 4.218E+3,CPICE = 2.106E+3,            &\n                          LSUBF = 3.335E+5\n\nCONTAINS\n\n  SUBROUTINE CALTMP(T1, SFCTMP, SFCPRS, ZLVL, Q2, TH2, T1V, TH2V, RHO )\n\n    IMPLICIT NONE\n\n    ! Input:\n    REAL, INTENT(IN)       :: T1     ! Skin temperature (K)\n    REAL, INTENT(IN)       :: SFCTMP ! Air temperature (K) at level ZLVL\n    REAL, INTENT(IN)       :: Q2     ! Specific Humidity (kg/kg) at level ZLVL\n    REAL, INTENT(IN)       :: SFCPRS ! Atmospheric pressure (Pa) at level ZLVL\n    REAL, INTENT(IN)       :: ZLVL   ! Height (m AGL) where atmospheric fields are valid\n\n    ! Output:\n    REAL, INTENT(OUT)      :: TH2    ! Potential temperature (considering the reference pressure to be at the surface)\n    REAL, INTENT(OUT)      :: T1V    ! Virtual skin temperature (K)\n    REAL, INTENT(OUT)      :: TH2V   ! Virtual potential temperature at ZLVL\n    REAL, INTENT(OUT)      :: RHO    ! Density\n\n    ! Local:\n    REAL                   :: T2V\n\n    TH2 = SFCTMP + ( 0.0098 * ZLVL)\n    T1V= T1 * (1.0+ 0.61 * Q2)\n    TH2V = TH2 * (1.0+ 0.61 * Q2)\n    T2V = SFCTMP * ( 1.0 + 0.61 * Q2 )\n    RHO = SFCPRS/(RD * T2V)\n\n  END SUBROUTINE CALTMP\n\n  SUBROUTINE CALHUM(SFCTMP, SFCPRS, Q2SAT, DQSDT2)\n\n    IMPLICIT NONE\n\n    ! Input:\n    REAL, INTENT(IN)       :: SFCTMP\n    REAL, INTENT(IN)       :: SFCPRS\n\n    ! Output:\n    REAL, INTENT(OUT)      :: Q2SAT   ! Saturated specific humidity\n    REAL, INTENT(OUT)      :: DQSDT2\n\n    ! Local\n    REAL, PARAMETER        :: A2=17.67,A3=273.15,A4=29.65, ELWV=2.501E6,        &\n                              A23M4=A2*(A3-A4), E0=611.0, RV=461.0,             &\n                              EPSILON=0.622\n    REAL                   :: ES\n\n    ! ES:  e.g. Dutton chapter 8, eq 11\n        ES = E0 * EXP ( ELWV/RV*(1./A3 - 1./SFCTMP) )\n\n    ! Q2SAT:\n        Q2SAT = EPSILON * ES / (SFCPRS-(1-EPSILON)*ES)\n\n! DQSDT2 is calculated assuming Q2SAT is a specific humidity\n        !KWM DQSDT2=(Q2SAT/(1+Q2SAT))*A23M4/(SFCTMP-A4)**2\n        DQSDT2=Q2SAT*A23M4/(SFCTMP-A4)**2\n\n        END SUBROUTINE CALHUM\n\n\nEND MODULE module_Noahlsm_utility\n\nsubroutine wrf_error_fatal(string)\n  implicit none\n  character(len=*), intent(in) :: string\n  print*, string\n  stop\nend subroutine wrf_error_fatal\n\nsubroutine wrf_dm_bcast_real(rval, ival)\n  implicit none\n  real,    intent(in) :: rval\n  integer, intent(in) :: ival\nend subroutine wrf_dm_bcast_real\n\nsubroutine wrf_dm_bcast_integer(rval, ival)\n  implicit none\n  integer, intent(in) :: rval\n  integer, intent(in) :: ival\nend subroutine wrf_dm_bcast_integer\n\nsubroutine wrf_dm_bcast_string(rval, ival)\n  implicit none\n  character(len=*), intent(in) :: rval\n  integer,          intent(in) :: ival\nend subroutine wrf_dm_bcast_string\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_routines/module_date_utilities.F",
    "content": "module Module_Date_utilities\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n    !  From old date (\"YYYY-MM-DD HH:MM:SS.ffff\" or \"YYYYMMDDHHMMSSffff\") and \n    !  delta-time, compute the new date.\n\n    !  on entry     -  odate  -  the old hdate.\n    !                  idt    -  the change in time\n\n    !  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n    !  Local Variables\n\n    !  yrold    -  indicates the year associated with \"odate\"\n    !  moold    -  indicates the month associated with \"odate\"\n    !  dyold    -  indicates the day associated with \"odate\"\n    !  hrold    -  indicates the hour associated with \"odate\"\n    !  miold    -  indicates the minute associated with \"odate\"\n    !  scold    -  indicates the second associated with \"odate\"\n\n    !  yrnew    -  indicates the year associated with \"ndate\"\n    !  monew    -  indicates the month associated with \"ndate\"\n    !  dynew    -  indicates the day associated with \"ndate\"\n    !  hrnew    -  indicates the hour associated with \"ndate\"\n    !  minew    -  indicates the minute associated with \"ndate\"\n    !  scnew    -  indicates the second associated with \"ndate\"\n\n    !  mday     -  a list assigning the number of days in each month\n\n    !  i        -  loop counter\n    !  nday     -  the integer number of days represented by \"idt\"\n    !  nhour    -  the integer number of hours in \"idt\" after taking out\n    !              all the whole days\n    !  nmin     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days and whole hours.\n    !  nsec     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days, whole hours, and whole minutes.\n\n    integer :: newlen, oldlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n    logical :: punct\n    integer :: yrstart, yrend, mostart, moend, dystart, dyend\n    integer :: hrstart, hrend, mistart, miend, scstart, scend, frstart\n    integer :: units\n    integer, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n\n    ! Determine if odate is \"YYYY-MM-DD_HH ... \" or \"YYYYMMDDHH....\"\n    if (odate(5:5) == \"-\") then\n       punct = .TRUE.\n    else\n       punct = .FALSE.\n    endif\n\n    !  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    oldlen = LEN(odate)\n    if (punct) then\n       yrstart = 1\n       yrend = 4\n       mostart = 6\n       moend = 7\n       dystart = 9\n       dyend = 10\n       hrstart = 12\n       hrend = 13\n       mistart = 15\n       miend = 16\n       scstart = 18\n       scend = 19\n       frstart = 21\n       select case (oldlen)\n       case (10)\n          ! Days\n          units = 1\n       case (13)\n          ! Hours\n          units = 2\n       case (16)\n          ! Minutes\n          units = 3\n       case (19)\n          ! Seconds\n          units = 4\n       case (21)\n          ! Tenths\n          units = 5\n       case (22)\n          ! Hundredths\n          units = 6\n       case (23)\n          ! Thousandths\n          units = 7\n       case (24)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n          stop\n       end select\n\n       if (oldlen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n\n    else\n\n       yrstart = 1\n       yrend = 4\n       mostart = 5\n       moend = 6\n       dystart = 7\n       dyend = 8\n       hrstart = 9\n       hrend = 10\n       mistart = 11\n       miend = 12\n       scstart = 13\n       scend = 14\n       frstart = 15\n\n       select case (oldlen)\n       case (8)\n          ! Days\n          units = 1\n       case (10)\n          ! Hours\n          units = 2\n       case (12)\n          ! Minutes\n          units = 3\n       case (14)\n          ! Seconds\n          units = 4\n       case (15)\n          ! Tenths\n          units = 5\n       case (16)\n          ! Hundredths\n          units = 6\n       case (17)\n          ! Thousandths\n          units = 7\n       case (18)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n          stop\n       end select\n    endif\n\n    !  Use internal READ statements to convert the CHARACTER string\n    !  date into INTEGER components.\n\n    read(odate(yrstart:yrend),  '(i4)') yrold\n    read(odate(mostart:moend),  '(i2)') moold\n    read(odate(dystart:dyend), '(i2)') dyold\n    if (units.ge.2) then\n       read(odate(hrstart:hrend),'(i2)') hrold\n       if (units.ge.3) then\n          read(odate(mistart:miend),'(i2)') miold\n          if (units.ge.4) then\n             read(odate(scstart:scend),'(i2)') scold\n             if (units.ge.5) then\n                read(odate(frstart:oldlen),*) frold\n             end if\n          end if\n       end if\n    end if\n\n    !  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n    !  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n    !  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n    !  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n    !  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n    !  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n    !  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n    !  Check that the fractional part  of ODATE makes sense.\n\n!KWM      IF ((scold.GT.59).or.(scold.LT.0)) THEN\n!KWM         WRITE(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n!KWM         opass = .FALSE.\n!KWM      END IF\n\n    if (.not.opass) then\n       write(*,*) 'Crazy ODATE: ', odate(1:oldlen), oldlen\n       stop\n    end if\n\n    !  Date Checks are completed.  Continue.\n\n\n    !  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (units.ge.5) then !idt should be in fractions of seconds\n       ifrc = oldlen-(frstart)+1\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (units.eq.4) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (units.eq.3) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.2) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.1) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            oldlen\n       write(*,*) '#'//odate(1:oldlen)//'#'\n       stop\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n    !  Now construct the new mdate\n\n    newlen = LEN(ndate)\n\n    if (punct) then\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n    else\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n119       format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,116) yrnew, monew, dynew, hrnew, minew\n116       format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,113) yrnew, monew, dynew, hrnew\n113       format(i4,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,110) yrnew, monew, dynew\n110       format(i4,i2.2,i2.2)\n\n       end if\n\n    endif\n\n    if (punct .and. (oldlen.ge.11) .and. (newlen.ge.11)) ndate(11:11) = sp\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n\n    implicit none\n\n    !  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n    !  compute the time difference.\n\n    !  on entry     -  newdate  -  the new hdate.\n    !                  olddate  -  the old hdate.\n\n    !  on exit      -  idt    -  the change in time.\n    !                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n\n    !  Local Variables\n\n    !  yrnew    -  indicates the year associated with \"ndate\"\n    !  yrold    -  indicates the year associated with \"odate\"\n    !  monew    -  indicates the month associated with \"ndate\"\n    !  moold    -  indicates the month associated with \"odate\"\n    !  dynew    -  indicates the day associated with \"ndate\"\n    !  dyold    -  indicates the day associated with \"odate\"\n    !  hrnew    -  indicates the hour associated with \"ndate\"\n    !  hrold    -  indicates the hour associated with \"odate\"\n    !  minew    -  indicates the minute associated with \"ndate\"\n    !  miold    -  indicates the minute associated with \"odate\"\n    !  scnew    -  indicates the second associated with \"ndate\"\n    !  scold    -  indicates the second associated with \"odate\"\n    !  i        -  loop counter\n    !  mday     -  a list assigning the number of days in each month\n\n    ! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    integer :: oldlen, newlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: i, newdys, olddys\n    logical :: npass, opass\n    integer :: timesign\n    integer :: ifrc\n    integer, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n    logical :: punct\n    integer :: yrstart, yrend, mostart, moend, dystart, dyend\n    integer :: hrstart, hrend, mistart, miend, scstart, scend, frstart\n    integer :: units\n\n    oldlen = len(olddate)\n    newlen = len(newdate)\n    if (newlen.ne.oldlen) then\n       write(*,'(\"GETH_IDTS: NEWLEN /= OLDLEN: \", A, 3x, A)') newdate(1:newlen), olddate(1:oldlen)\n       stop\n    endif\n\n    if (olddate.gt.newdate) then\n       timesign = -1\n\n       ifrc = oldlen\n       oldlen = newlen\n       newlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       timesign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n    ! Break down old hdate into parts\n\n    ! Determine if olddate is punctuated or not\n    if (odate(5:5) == \"-\") then\n       punct = .TRUE.\n       if (ndate(5:5) /= \"-\") then\n          write(*,'(\"GETH_IDTS: Dates appear to be different formats: \", A, 3x, A)') &\n               ndate(1:newlen), odate(1:oldlen)\n          stop\n       endif\n    else\n       punct = .FALSE.\n       if (ndate(5:5) == \"-\") then\n          write(*,'(\"GETH_IDTS: Dates appear to be different formats: \", A, 3x, A)') &\n               ndate(1:newlen), odate(1:oldlen)\n          stop\n       endif\n    endif\n\n    if (punct) then\n       yrstart = 1\n       yrend = 4\n       mostart = 6\n       moend = 7\n       dystart = 9\n       dyend = 10\n       hrstart = 12\n       hrend = 13\n       mistart = 15\n       miend = 16\n       scstart = 18\n       scend = 19\n       frstart = 21\n       select case (oldlen)\n       case (10)\n          ! Days\n          units = 1\n       case (13)\n          ! Hours\n          units = 2\n       case (16)\n          ! Minutes\n          units = 3\n       case (19)\n          ! Seconds\n          units = 4\n       case (21)\n          ! Tenths\n          units = 5\n       case (22)\n          ! Hundredths\n          units = 6\n       case (23)\n          ! Thousandths\n          units = 7\n       case (24)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_idts:  odd length: #'//trim(odate)//'#'\n          stop\n       end select\n    else\n\n       yrstart = 1\n       yrend = 4\n       mostart = 5\n       moend = 6\n       dystart = 7\n       dyend = 8\n       hrstart = 9\n       hrend = 10\n       mistart = 11\n       miend = 12\n       scstart = 13\n       scend = 14\n       frstart = 15\n\n       select case (oldlen)\n       case (8)\n          ! Days\n          units = 1\n       case (10)\n          ! Hours\n          units = 2\n       case (12)\n          ! Minutes\n          units = 3\n       case (14)\n          ! Seconds\n          units = 4\n       case (15)\n          ! Tenths\n          units = 5\n       case (16)\n          ! Hundredths\n          units = 6\n       case (17)\n          ! Thousandths\n          units = 7\n       case (18)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_idts:  odd length: #'//trim(odate)//'#'\n          stop\n       end select\n    endif\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    read(odate(yrstart:yrend), '(i4)') yrold\n    read(odate(mostart:moend), '(i2)') moold\n    read(odate(dystart:dyend), '(i2)') dyold\n    if (units.ge.2) then\n       read(odate(hrstart:hrend),'(i2)') hrold\n       if (units.ge.3) then\n          read(odate(mistart:miend),'(i2)') miold\n          if (units.ge.4) then\n             read(odate(scstart:scend),'(i2)') scold\n             if (units.ge.5) then\n                read(odate(frstart:oldlen),*) frold\n             end if\n          end if\n       end if\n    end if\n\n    !  Break down new hdate into parts\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(ndate(yrstart:yrend), '(i4)') yrnew\n    read(ndate(mostart:moend), '(i2)') monew\n    read(ndate(dystart:dyend), '(i2)') dynew\n    if (units.ge.2) then\n       read(ndate(hrstart:hrend),'(i2)') hrnew\n       if (units.ge.3) then\n          read(ndate(mistart:miend),'(i2)') minew\n          if (units.ge.4) then\n             read(ndate(scstart:scend),'(i2)') scnew\n             if (units.ge.5) then\n                read(ndate(frstart:newlen),*) frnew\n             end if\n          end if\n       end if\n    end if\n\n    !  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n    !  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n       write(*,*) 'GETH_IDTS:  Month of NDATE = ', monew\n       npass = .false.\n    end if\n\n    !  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n       opass = .false.\n    end if\n\n    !  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    endif\n\n    !  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    end if\n\n    !  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n       npass = .false.\n    end if\n\n    !  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n       opass = .false.\n    end if\n\n    !  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n       npass = .false.\n    end if\n\n    !  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n       opass = .false.\n    end if\n\n    !  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n       npass = .false.\n    end if\n\n    !  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'Screwy NDATE: ', ndate(1:newlen)\n       stop\n    end if\n\n    if (.not. opass) then\n       print*, 'Screwy ODATE: ', odate(1:oldlen)\n       stop\n    end if\n\n    !  Date Checks are completed.  Continue.\n\n    !  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n    !  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n    !  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n    !  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n    !  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n    !  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (units.ge.2) then\n       idt = idt*24 + (hrnew - hrold)\n       if (units.ge.3) then\n          idt = idt*60 + (minew - miold)\n          if (units.ge.4) then\n             idt = idt*60 + (scnew - scold)\n             if (units.ge.5) then\n                ifrc = oldlen-(frstart-1)\n                ifrc = 10**ifrc\n                idt = idt * ifrc + (frnew-frold)\n             endif\n          endif\n       endif\n    endif\n\n    if (timesign .eq. -1) then\n       idt = idt * timesign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n    !\n    ! Compute the number of days in February for the given year.\n    !\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n    !\n    ! Compute the number of days in the month of given date hdate.\n    !\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    read(hdate(1:7), '(I4,1x,I2)') year, month\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\n\n  function monthabbr_to_mm(mon) result(mm)\n    implicit none\n\n    character(len=3), intent(in) :: mon\n\n    integer :: mm\n\n    if (mon == \"Jan\") then\n       mm = 1\n    elseif (mon == \"Feb\") then\n       mm = 2\n    elseif (mon == \"Mar\") then\n       mm = 3\n    elseif (mon == \"Apr\") then\n       mm = 4\n    elseif (mon == \"May\") then\n       mm = 5\n    elseif (mon == \"Jun\") then\n       mm = 6\n    elseif (mon == \"Jul\") then\n       mm = 7\n    elseif (mon == \"Aug\") then\n       mm = 8\n    elseif (mon == \"Sep\") then\n       mm = 9\n    elseif (mon == \"Oct\") then\n       mm = 10\n    elseif (mon == \"Nov\") then\n       mm = 11\n    elseif (mon == \"Dec\") then\n       mm = 12\n    else\n       write(*, '(\"Function monthabbr_to_mm:  mon = <\",A,\">\")') mon\n       stop  \"Function monthabbr_to_mm:  Unrecognized mon\"\n    endif\n  end function monthabbr_to_mm\n\n  subroutine swap_date_format(indate, outdate)\n    implicit none\n    character(len=*), intent(in)  :: indate\n    character(len=*), intent(out) :: outdate\n    integer :: inlen\n\n    inlen = len(indate)\n    if (indate(5:5) == \"-\") then\n       select case (inlen)\n       case (10)\n          ! YYYY-MM-DD\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)\n       case (13)\n          ! YYYY-MM-DD_HH\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)\n       case (16)\n          ! YYYY-MM-DD_HH:mm\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)\n       case (19)\n          ! YYYY-MM-DD_HH:mm:ss\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)//&\n               indate(18:19)\n       case (21,22,23,24)\n          ! YYYY-MM-DD_HH:mm:ss.f[f[f[f]]]\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)//&\n               indate(18:19)//indate(21:inlen)\n       case default\n          write(*,'(\"Unrecognized length: <\", A,\">\")') indate\n          stop\n       end select\n    else\n       select case (inlen)\n       case (8)\n          ! YYYYMMDD\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)\n       case (10)\n          ! YYYYMMDDHH\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)\n       case (12)\n          ! YYYYMMDDHHmm\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)\n       case (14)\n          ! YYYYMMDDHHmmss\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)//\":\"//indate(13:14)\n       case (15,16,17,18)\n          ! YYYYMMDDHHmmssf[f[f[f]]]\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)//\":\"//indate(13:14)//\".\"//indate(15:inlen)\n       case default\n          write(*,'(\"Unrecognized length: <\", A,\">\")') indate\n          stop\n       end select\n    endif\n\n  end subroutine swap_date_format\n\n  character(len=3) function mm_to_monthabbr(ii) result(mon)\n    implicit none\n    integer, intent(in) :: ii\n    character(len=3), parameter, dimension(12) :: month = (/ &\n         \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", &\n         \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" /)\n    if (ii > 0 .and. ii < 13 ) then\n       mon = month(ii)\n    else\n       stop \"mm_to_monthabbr\"\n    endif\n  end function mm_to_monthabbr\n\nend module Module_Date_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_routines/module_model_constants.F",
    "content": "!WRF:MODEL_LAYER:CONSTANTS\n!\n\n MODULE module_model_constants\n\n   !  2. Following are constants for use in defining real number bounds.\n\n   !  A really small number.\n\n   REAL    , PARAMETER :: epsilon         = 1.E-15\n\n   !  4. Following is information related to the physical constants.\n\n   !  These are the physical constants used within the model.\n\n! JM NOTE -- can we name this grav instead?\n   REAL    , PARAMETER :: g = 9.81  ! acceleration due to gravity (m {s}^-2)\n\n#if ( NMM_CORE == 1 )\n   REAL    , PARAMETER :: r_d          = 287.04\n   REAL    , PARAMETER :: cp           = 1004.6\n#else\n   REAL    , PARAMETER :: r_d          = 287.\n   REAL    , PARAMETER :: cp           = 7.*r_d/2.\n#endif\n\n   REAL    , PARAMETER :: r_v          = 461.6\n   REAL    , PARAMETER :: cv           = cp-r_d\n   REAL    , PARAMETER :: cpv          = 4.*r_v\n   REAL    , PARAMETER :: cvv          = cpv-r_v\n   REAL    , PARAMETER :: cvpm         = -cv/cp\n   REAL    , PARAMETER :: cliq         = 4190.\n   REAL    , PARAMETER :: cice         = 2106.\n   REAL    , PARAMETER :: psat         = 610.78\n   REAL    , PARAMETER :: rcv          = r_d/cv\n   REAL    , PARAMETER :: rcp          = r_d/cp\n   REAL    , PARAMETER :: rovg         = r_d/g\n   REAL    , PARAMETER :: c2           = cp * rcv\n   real    , parameter :: mwdry        = 28.966 ! molecular weight of dry air (g/mole)\n\n   REAL    , PARAMETER :: p1000mb      = 100000.\n   REAL    , PARAMETER :: t0           = 300.\n   REAL    , PARAMETER :: p0           = p1000mb\n   REAL    , PARAMETER :: cpovcv       = cp/(cp-r_d)\n   REAL    , PARAMETER :: cvovcp       = 1./cpovcv\n   REAL    , PARAMETER :: rvovrd       = r_v/r_d\n\n   REAL    , PARAMETER :: reradius     = 1./6370.0e03\n\n   REAL    , PARAMETER :: asselin      = .025\n!   REAL    , PARAMETER :: asselin      = .0\n   REAL    , PARAMETER :: cb           = 25.\n\n   REAL    , PARAMETER :: XLV0         = 3.15E6\n   REAL    , PARAMETER :: XLV1         = 2370.\n   REAL    , PARAMETER :: XLS0         = 2.905E6\n   REAL    , PARAMETER :: XLS1         = 259.532\n\n   REAL    , PARAMETER :: XLS          = 2.85E6\n   REAL    , PARAMETER :: XLV          = 2.5E6\n   REAL    , PARAMETER :: XLF          = 3.50E5\n\n   REAL    , PARAMETER :: rhowater     = 1000.\n   REAL    , PARAMETER :: rhosnow      = 100.\n   REAL    , PARAMETER :: rhoair0      = 1.28\n!\n   REAL    , PARAMETER :: n_ccn0       = 1.0E8\n!\n   REAL    , PARAMETER :: DEGRAD       = 3.1415926/180.\n   REAL    , PARAMETER :: DPD          = 360./365.\n\n   REAL    , PARAMETER ::  SVP1=0.6112\n   REAL    , PARAMETER ::  SVP2=17.67\n   REAL    , PARAMETER ::  SVP3=29.65\n   REAL    , PARAMETER ::  SVPT0=273.15\n   REAL    , PARAMETER ::  EP_1=R_v/R_d-1.\n   REAL    , PARAMETER ::  EP_2=R_d/R_v\n   REAL    , PARAMETER ::  KARMAN=0.4\n   REAL    , PARAMETER ::  EOMEG=7.2921E-5\n   REAL    , PARAMETER ::  STBOLT=5.67051E-8\n\n   REAL    , PARAMETER ::  prandtl = 1./3.0\n                                         ! constants for w-damping option\n   REAL    , PARAMETER ::  w_alpha = 0.3 ! strength m/s/s\n   REAL    , PARAMETER ::  w_beta  = 1.0 ! activation cfl number\n\n       REAL , PARAMETER ::  pq0=379.90516\n       REAL , PARAMETER ::  epsq2=0.2\n       REAL , PARAMETER ::  a2=17.2693882\n       REAL , PARAMETER ::  a3=273.16\n       REAL , PARAMETER ::  a4=35.86\n       REAL , PARAMETER ::  epsq=1.e-12\n       REAL , PARAMETER ::  p608=rvovrd-1.\n!#if ( NMM_CORE == 1 )\n       REAL , PARAMETER ::  climit=1.e-20\n       REAL , PARAMETER ::  cm1=2937.4\n       REAL , PARAMETER ::  cm2=4.9283\n       REAL , PARAMETER ::  cm3=23.5518\n!       REAL , PARAMETER ::  defc=8.0\n!       REAL , PARAMETER ::  defm=32.0\n       REAL , PARAMETER ::  defc=0.0\n       REAL , PARAMETER ::  defm=99999.0\n       REAL , PARAMETER ::  epsfc=1./1.05\n       REAL , PARAMETER ::  epswet=0.0\n       REAL , PARAMETER ::  fcdif=1./3.\n#ifdef HWRF\n       REAL , PARAMETER ::  fcm=0.0\n#else\n       REAL , PARAMETER ::  fcm=0.00003\n#endif\n       REAL , PARAMETER ::  gma=-r_d*(1.-rcp)*0.5\n       REAL , PARAMETER ::  p400=40000.0\n       REAL , PARAMETER ::  phitp=15000.0\n       REAL , PARAMETER ::  pi2=2.*3.1415926\n       REAL , PARAMETER ::  plbtm=105000.0\n       REAL , PARAMETER ::  plomd=64200.0\n       REAL , PARAMETER ::  pmdhi=35000.0\n       REAL , PARAMETER ::  q2ini=0.50\n       REAL , PARAMETER ::  rfcp=0.25/cp\n       REAL , PARAMETER ::  rhcrit_land=0.75\n       REAL , PARAMETER ::  rhcrit_sea=0.80\n       REAL , PARAMETER ::  rlag=14.8125\n       REAL , PARAMETER ::  rlx=0.90\n       REAL , PARAMETER ::  scq2=50.0\n       REAL , PARAMETER ::  slopht=0.001\n       REAL , PARAMETER ::  tlc=2.*0.703972477\n       REAL , PARAMETER ::  wa=0.15\n       REAL , PARAMETER ::  wght=0.35\n       REAL , PARAMETER ::  wpc=0.075\n       REAL , PARAMETER ::  z0land=0.10\n#ifdef HWRF\n       REAL , PARAMETER ::  z0max=0.01\n#else\n       REAL , PARAMETER ::  z0max=0.008\n#endif\n       REAL , PARAMETER ::  z0sea=0.001\n!#endif\n\n\n   !  Earth\n\n   !  The value for P2SI *must* be set to 1.0 for Earth\n   !  Although, now we may not need this declaration here (see above)\n   !REAL    , PARAMETER :: P2SI         = 1.0\n\n   !  Orbital constants:\n\n   INTEGER , PARAMETER :: PLANET_YEAR = 365\n   REAL , PARAMETER :: OBLIQUITY = 23.5\n   REAL , PARAMETER :: ECCENTRICITY = 0.014\n   REAL , PARAMETER :: SEMIMAJORAXIS = 1.0 ! In AU\n   ! Don't know the following values, so we'll fake them for now\n   REAL , PARAMETER :: zero_date = 0.0   ! Time of perihelion passage\n   !  Fraction into the year (from perhelion) of the\n   !  occurrence of the Northern Spring Equinox\n   REAL , PARAMETER :: EQUINOX_FRACTION= 0.0\n\n CONTAINS\n   SUBROUTINE init_module_model_constants\n   END SUBROUTINE init_module_model_constants\n END MODULE module_model_constants\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_routines/module_sfcdif_wrf.F",
    "content": "! Note:  Initialize USTAR to 0.1 at start of HRLDAS driver.\n!        USTAR subsequently gets updated.\n\nmodule module_sfcdif_wrf\n  use module_model_constants\n\n  integer, parameter, private :: ITRMX = 5\n\n  real,    parameter, private :: EXCML   = 0.0001\n  real,    parameter, private :: EXCMS   = 0.0001\n  real,    parameter, private :: VKARMAN = 0.4\n  real,    parameter, private :: ZTFC    = 1.0\n  real,    parameter, private :: ELOCP   = 2.72E6 / CP\n  real,    parameter, private :: EPSU2   = 1.E-6\n  real,    parameter, private :: EPSUST  = 1.e-9\n  real,    parameter, private :: SQVISC  = 258.2\n  real,    parameter, private :: RIC     = 0.505\n  real,    parameter, private :: EPSZT   = 1.E-28\n\n  integer, parameter, private :: KZTM  = 10001\n  integer, parameter, private :: KZTM2 = KZTM-2\n\n  real,    parameter, private :: WWST  = 1.2\n  real,    parameter, private :: WWST2 = WWST*WWST\n  real,    parameter, private :: ztmin2 = -5.0\n\n  ! These need to be initialized somewhere.\n  real, private :: dzeta2\n  real, private :: ztmax2\n  real, dimension(KZTM), private :: PSIH2\n  real, dimension(KZTM), private :: PSIM2\n\ncontains\n\n  SUBROUTINE SFCDIF_MYJ ( ZSL, ZSL_WIND, Z0, Z0BASE, SFCPRS, TZ0,    &\n       TLOW, QZ0,  QLOW, SFCSPD, CZIL, RIB, AKMS, AKHS, VEGTYP,      &\n       ISURBAN, IZ0TLND )\n!     ****************************************************************\n!     *                                                              *\n!     *                       SURFACE LAYER                          *\n!     *                                                              *\n!     ****************************************************************\n!----------------------------------------------------------------------\n!\n    IMPLICIT NONE\n!\n!----------------------------------------------------------------------\n!\n    REAL, INTENT(IN) :: ZSL       ! Height above ground (m) of atmospheric T,Q fields\n    REAL, INTENT(IN) :: ZSL_WIND  ! Height above ground (m) of atmospheric wind fields\n    REAL, INTENT(IN) :: Z0   ! Roughness length (m); may be adjusted for snow\n    REAL, INTENT(IN) :: Z0BASE ! Background roughness length (m)\n    REAL, INTENT(IN) :: SFCPRS\n    REAL, INTENT(IN) :: TZ0  ! Temperature (K) at level Z0 above ground -- assumed to be the Skin Temperature.\n    REAL, INTENT(IN) :: TLOW ! Temperature (K) at level <Za> above ground.\n    REAL, INTENT(IN) :: QZ0  ! Specific humidity (kg/kg) at level Z0 above ground\n    REAL, INTENT(IN) :: QLOW ! Specific humidity (kg/kg) at level ZSL above ground\n    REAL, INTENT(IN) :: SFCSPD\n    REAL, INTENT(IN) :: CZIL\n    INTEGER, INTENT(IN) :: VEGTYP\n    INTEGER, INTENT(IN) :: ISURBAN\n    INTEGER, INTENT(IN) :: IZ0TLND\n!\n    REAL,INTENT(INOUT) :: AKHS\n    REAL,INTENT(INOUT) :: AKMS\n    REAL,INTENT(OUT)   :: RIB\n!----------------------------------------------------------------------\n!***\n!***  LOCAL VARIABLES\n!***\n    REAL :: THLOW ! Potential Temperature (K) at level ZSL above ground.\n    REAL :: THZ0  ! Potential Temperature (K) at level Z0 above ground.\n    REAL :: THELOW !\n    REAL :: CWMLOW ! Cloud water (assumed to be zero for HRLDAS)\n    REAL :: USTAR\n    REAL :: RLMO\n    INTEGER :: ITR,K\n    REAL :: CZIL_LOCAL\n    REAL :: ZILFC\n!\n    REAL :: A,B,BTGH,BTGX,CXCHL,CXCHS,CZETMAX,DTHV,DU2,ELFC      &\n         & ,PSHZ,PSHZL,PSMZ,PSMZL   &\n         & ,RDZT                                  &\n         & ,RLOGT,RLOGU,RZ,RZST,RZSU,SIMH,SIMM,TEM,THM          &\n         & ,USTARK,WSTAR2               &\n         & ,ZETALT,ZETALU          &\n         & ,ZETAT,ZETAU,ZQ,ZSLT,ZSLU,ZT,ZU,ZZIL\n\n!----------------------------------------------------------------------\n!**********************************************************************\n!----------------------------------------------------------------------\n\n!----------------------------------------------------------------------\n! Compute potential temperatures from input <Za>-level temperature TLOW\n! and input Skin-level (or Z0-level) temperature.\n\n    THLOW = TLOW * (P0/SFCPRS) ** RCP\n    THZ0  = TZ0  * (P0/SFCPRS) ** RCP  ! Should actually use a pressure at Z0?\n\n    ! For THELOW, WRF uses (1-QC*ELOCP/T)*TH.  If QC is assumed to be zero,\n    ! Then THELOW is just TH ?\n    THELOW = THLOW\n!----------------------------------------------------------------------\n\n    CXCHL=EXCML/ZSL\n !\n    BTGX=G/THLOW\n    ELFC=VKARMAN*BTGX\n\n!MBKWM    IF(PBLH>1000.)THEN\n!MBKWM       BTGH=BTGX*PBLH\n!MBKWM    ELSE\n    BTGH=BTGX*1000.\n!MBKWM    ENDIF\n\n!----------------------------------------------------------------------\n\n    THM=(THELOW+THZ0)*0.5\n    TEM=(TLOW+TZ0)*0.5\n!\n    A=THM*P608\n    B=(ELOCP/TEM-1.-P608)*THM\n    CWMLOW = 0.0 ! MB/KWM Assume no cloud water\n!\n    DTHV=((THELOW-THZ0)*((QLOW+QZ0+CWMLOW)*(0.5*P608)+1.)          &\n         &        +(QLOW-QZ0+CWMLOW)*A+CWMLOW*B)\n!\n!    DU2=MAX((ULOW-UZ0)**2+(VLOW-VZ0)**2,EPSU2)\n    DU2 = MAX(SFCSPD*SFCSPD,EPSU2)\n    RIB=BTGX*DTHV*ZSL_WIND*ZSL_WIND/DU2/ZSL\n!----------------------------------------------------------------------\n!----------------------------------------------------------------------\n    ZU=Z0\n    ZT=ZU*ZTFC\n    ZSLU=ZSL_WIND+ZU\n    RZSU=ZSLU/ZU\n    RLOGU=LOG(RZSU)\n    ZSLT=ZSL+ZU ! u,v and t are at the same level\n\n    IF ( (IZ0TLND==0) .or. (VEGTYP == ISURBAN) ) THEN\n       ! Just use the incoming CZIL value.\n       ZILFC=-CZIL*VKARMAN*SQVISC\n    ELSE\n       ! Modify CZIL according to Chen & Zhang, 2009\n       ! CZIL = 10 ** -0.40 H, ( where H = 10*Zo )\n       CZIL_LOCAL = 10.0 ** ( -0.40 * ( Z0 / 0.07 ) )\n       ZILFC=-CZIL_LOCAL*VKARMAN*SQVISC\n    ENDIF\n\n!----------------------------------------------------------------------\n!\n!  RIB modification to ZILFC term\n!\n!      CZETMAX = 20.\n    CZETMAX = 10.\n! stable\n    IF(DTHV>0.)THEN\n       IF (RIB<RIC) THEN\n          ZZIL=ZILFC*(1.0+(RIB/RIC)*(RIB/RIC)*CZETMAX)\n       ELSE\n          ZZIL=ZILFC*(1.0+CZETMAX)\n       ENDIF\n! unstable\n    ELSE\n       ZZIL=ZILFC\n    ENDIF\n\n!----------------------------------------------------------------------\n    ! First guess of USTAR based on input (previous timestep) AKHS and AKMS?\n    IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n       WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n    ELSE\n       WSTAR2 = 0.0\n    END IF\n    USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n!----------------------------------------------------------------------\n\n!\n!----------------------------------------------------------------------\n!\n    land_point_iteration: DO ITR=1,ITRMX\n!\n!----------------------------------------------------------------------\n!***  ZILITINKEVITCH FIX FOR ZT\n!----------------------------------------------------------------------\n!\n       ZT=MAX(EXP(ZZIL*SQRT(USTAR*Z0BASE))*Z0BASE,EPSZT)\n!\n       RZST=ZSLT/ZT\n       RLOGT=LOG(RZST)\n!\n!----------------------------------------------------------------------\n!***  1./MONIN-OBUKHOV LENGTH-SCALE\n!----------------------------------------------------------------------\n!\n       RLMO=ELFC*AKHS*DTHV/USTAR**3\n       ZETALU=ZSLU*RLMO\n       ZETALT=ZSLT*RLMO\n       ZETAU=ZU*RLMO\n       ZETAT=ZT*RLMO\n!\n       ZETALU=MIN(MAX(ZETALU,ZTMIN2),ZTMAX2)\n       ZETALT=MIN(MAX(ZETALT,ZTMIN2),ZTMAX2)\n       ZETAU=MIN(MAX(ZETAU,ZTMIN2/RZSU),ZTMAX2/RZSU)\n       ZETAT=MIN(MAX(ZETAT,ZTMIN2/RZST),ZTMAX2/RZST)\n!\n!----------------------------------------------------------------------\n!***  LAND FUNCTIONS\n!----------------------------------------------------------------------\n!\n       RZ=(ZETAU-ZTMIN2)/DZETA2\n       K=INT(RZ)\n       RDZT=RZ-REAL(K)\n       K=MIN(K,KZTM2)\n       K=MAX(K,0)\n       PSMZ=(PSIM2(K+2)-PSIM2(K+1))*RDZT+PSIM2(K+1)\n!\n       RZ=(ZETALU-ZTMIN2)/DZETA2\n       K=INT(RZ)\n       RDZT=RZ-REAL(K)\n       K=MIN(K,KZTM2)\n       K=MAX(K,0)\n       PSMZL=(PSIM2(K+2)-PSIM2(K+1))*RDZT+PSIM2(K+1)\n!\n       SIMM=PSMZL-PSMZ+RLOGU\n!\n       RZ=(ZETAT-ZTMIN2)/DZETA2\n       K=INT(RZ)\n       RDZT=RZ-REAL(K)\n       K=MIN(K,KZTM2)\n       K=MAX(K,0)\n       PSHZ=(PSIH2(K+2)-PSIH2(K+1))*RDZT+PSIH2(K+1)\n!\n       RZ=(ZETALT-ZTMIN2)/DZETA2\n       K=INT(RZ)\n       RDZT=RZ-REAL(K)\n       K=MIN(K,KZTM2)\n       K=MAX(K,0)\n       PSHZL=(PSIH2(K+2)-PSIH2(K+1))*RDZT+PSIH2(K+1)\n!\n       SIMH=(PSHZL-PSHZ+RLOGT)\n!----------------------------------------------------------------------\n       USTARK=USTAR*VKARMAN\n       AKMS=MAX(USTARK/SIMM,CXCHL)\n       AKHS=MAX(USTARK/SIMH,CXCHL)\n!\n!----------------------------------------------------------------------\n!***  BELJAARS CORRECTION FOR USTAR\n!----------------------------------------------------------------------\n!\n       IF(DTHV<=0.)THEN                                           !zj\n          WSTAR2=WWST2*ABS(BTGH*AKHS*DTHV)**(2./3.)               !zj\n       ELSE                                                       !zj\n          WSTAR2=0.                                               !zj\n       ENDIF                                                      !zj\n!\n       USTAR=MAX(SQRT(AKMS*SQRT(DU2+WSTAR2)),EPSUST)\n\n!----------------------------------------------------------------------\n    ENDDO land_point_iteration\n!----------------------------------------------------------------------\n\n  END SUBROUTINE SFCDIF_MYJ\n\n  SUBROUTINE MYJSFCINIT()\n!----------------------------------------------------------------------\n    IMPLICIT NONE\n!----------------------------------------------------------------------\n    INTEGER :: K\n!\n    REAL :: X,ZETA1,ZETA2,ZRNG1,ZRNG2,ZTMAX1,DZETA1\n!\n    REAL, parameter :: PIHF=3.1415926/2.\n    real, parameter :: EPS=1.E-6\n    real, parameter :: ztmin1 = -5.0\n!----------------------------------------------------------------------\n\n!----------------------------------------------------------------------\n!----------------------------------------------------------------------\n!\n!***  COMPUTE SURFACE LAYER INTEGRAL FUNCTIONS\n!\n!----------------------------------------------------------------------\n\n      ZTMAX1=1.0\n      ZTMAX2=1.0\n\n      ZRNG1=ZTMAX1-ZTMIN1\n      ZRNG2=ZTMAX2-ZTMIN2\n\n      DZETA1=ZRNG1/(KZTM-1)\n      DZETA2=ZRNG2/(KZTM-1)\n!\n!----------------------------------------------------------------------\n!***  FUNCTION DEFINITION LOOP\n!----------------------------------------------------------------------\n!\n      ZETA1=ZTMIN1\n      ZETA2=ZTMIN2\n!\n      DO K=1,KZTM\n!\n!----------------------------------------------------------------------\n!***  UNSTABLE RANGE\n!----------------------------------------------------------------------\n!\n         IF(ZETA2<0.)THEN\n!\n!----------------------------------------------------------------------\n!***  PAULSON 1970 FUNCTIONS\n!----------------------------------------------------------------------\n!\n            X=SQRT(SQRT(1.-16.*ZETA2))\n!\n            PSIM2(K)=-2.*LOG((X+1.)/2.)-LOG((X*X+1.)/2.)+2.*ATAN(X)-PIHF\n            PSIH2(K)=-2.*LOG((X*X+1.)/2.)\n!----------------------------------------------------------------------\n!***  STABLE RANGE\n!----------------------------------------------------------------------\n!\n         ELSE\n!\n!----------------------------------------------------------------------\n!***  HOLTSLAG AND DE BRUIN 1988\n!----------------------------------------------------------------------\n!\n            PSIM2(K)=0.7*ZETA2+0.75*ZETA2*(6.-0.35*ZETA2)*EXP(-0.35*ZETA2)\n            PSIH2(K)=0.7*ZETA2+0.75*ZETA2*(6.-0.35*ZETA2)*EXP(-0.35*ZETA2)\n!----------------------------------------------------------------------\n!\n         ENDIF\n!\n!----------------------------------------------------------------------\n         IF(K==KZTM)THEN\n            ZTMAX1=ZETA1\n            ZTMAX2=ZETA2\n         ENDIF\n!\n         ZETA1=ZETA1+DZETA1\n         ZETA2=ZETA2+DZETA2\n!----------------------------------------------------------------------\n      ENDDO\n!----------------------------------------------------------------------\n      ZTMAX1=ZTMAX1-EPS\n      ZTMAX2=ZTMAX2-EPS\n!----------------------------------------------------------------------\n!\n    END SUBROUTINE MYJSFCINIT\n\nEND MODULE MODULE_SFCDIF_WRF\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_scripts/modify_wrfinput.ncl",
    "content": "\n\n; Run with, for example:\n;    ncl ldasout=\\\"2003070412.LDASOUT_DOMAIN1\\\" wrfinput=\\\"wrfinput_d01\\\" modify_wrfinput.ncl\n\n\n\nf = addfile(wrfinput+\".nc\", \"w\")\ng = addfile(ldasout+\".nc\", \"r\")\n\n\nf->CANWAT = where(f->LANDMASK.eq.1, g->CANWAT,   f->CANWAT)\n; f->TSK    = where(f->LANDMASK.eq.1, g->SKINTEMP, f->TSK)\n\nprintVarSummary(f->LANDMASK)\nprintVarSummary(f->TSLB)\nprintVarSummary(g->SOIL_T)\n\ndims = dimsizes(f->TSLB)\nkdim = dims(1)\n\ndo k=0,kdim-1\n   f->TSLB (:,k,:,:) = where(f->LANDMASK.eq.1, g->SOIL_T(:,k,:,:), f->TSLB (:,k,:,:))\n   f->SMOIS(:,k,:,:) = where(f->LANDMASK.eq.1, g->SOIL_M(:,k,:,:), f->SMOIS(:,k,:,:))\n   f->SH2O (:,k,:,:) = where(f->LANDMASK.eq.1, g->SOIL_W(:,k,:,:), f->SH2O (:,k,:,:))\nend do\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_scripts/nam_3d_gribextract.csh",
    "content": "#!/bin/tcsh -ef\n\n#\n#  This script is intended primarily as an example of how to use the gribextract\n#  program to extract individual records from a GRIB Edition 1 dataset\n#\n\nset initial = 0\n\nwhile ( ${#argv} > 0 )\n\n   if ( ( \"${argv[1]}\" == \"-help\" ) || ( \"${argv[1]}\" == \"--help\" ) || ( \"${argv[1]}\" == \"-h\" ) ) then\n      printf \"Usage:  $0 [--initial] <nam_file>\\n\"\n      exit (1)\n   else if ( ( \"${argv[1]}\" == \"-initial\" ) || ( \"${argv[1]}\" == \"--initial\" ) ) then\n      set initial = 1\n   else\n      set nam_file = ${1}\n   endif\n   shift\n\nend\n\n#\n# Attempt to find the Utility_programs directory, assuming it is one up from where the Utility_scripts are found.\n#\n\nset scriptexe = $0\nset firstchar = `echo ${scriptexe} | cut -b 0-1`\nif ( \"${firstchar}\" == \".\" || \"${firstchar}\" == \"/\") then\n   # We have a path explicitly in the command as issued.\n   set scriptdir = ${scriptexe:h}\n   set progdir = ${scriptdir:h}/Utility_programs\nelse\n   # No path explicitly issued.  Assume Utility_programs is one up from here.\n   set progdir = ../Utility_programs\nendif\n\nif ( ! -e ${progdir} ) then\n   printf \"Cannot find directory %s\\n\" ${progdir}\n   exit (1)\nendif\n\n\n#\n# From the ${nam_file}, extract downwelling longwave radiation.  Only take the\n# instantaneous field, skipping the average fields.\n#\n\n${progdir}/gribextract -q -c 205 -l 1,0,0 -s 1,21,0 ${nam_file} LW.grb\n\nif ( -z LW.grb ) rm LW.grb\n\n#\n# From the ${nam_file}, extract downwelling shortwave radiation.  Only take the\n# instantaneous field, skipping the average fields.\n#\n\n${progdir}/gribextract -q -c 204 -l 1,0,0 -s 1,21,0 ${nam_file} SW.grb\n\nif ( -z SW.grb ) rm SW.grb\n\n\n\nRenameFiles:\n\n\n\n\nforeach file ( *.grb )\n\n    #\n    # This is perhaps getting too fancy here, but use the od (octal dump) command to \n    # pull specific bytes out of the grib record, specifically, the bytes identifying\n    # the time of the field:\n    #\n    set cc = `od -j 32 -N 1 -t u1 ${file}`\n    set yy = `od -j 20 -N 1 -t u1 ${file}`\n    set mm = `od -j 21 -N 1 -t u1 ${file}`\n    set dd = `od -j 22 -N 1 -t u1 ${file}`\n    set hh = `od -j 23 -N 1 -t u1 ${file}`\n\n    set p1 = `od -j 26 -N 1 -t u1 ${file}`\n    set p2 = `od -j 27 -N 1 -t u1 ${file}`\n    set ti = `od -j 28 -N 1 -t u1 ${file}`\n\n    set cc = `printf \"%2.2d\" ${cc[2]}`\n    set yy = `printf \"%2.2d\" ${yy[2]}`\n    set mm = `printf \"%2.2d\" ${mm[2]}`\n    set dd = `printf \"%2.2d\" ${dd[2]}`\n    set hh = `printf \"%2.2d\" ${hh[2]}`\n\n    set yytest = `dc -e \"${yy} p\"`  # use dc to pop the value, which returns a value without any leading zeroes.\n    if ( ${yytest} > 0 ) @ cc --\n\n    echo \"p1 = $p1[2];  p2 = $p2[2];  ti = $ti[2]\"\n    # echo $cc $yy $mm $dd $hh\n\n    if ( ${p1[2]} == 0 ) then\n       set validdate = ${cc}${yy}${mm}${dd}${hh}\n    else\n       set validdate = `${progdir}/geth_newdate ${cc}${yy}${mm}${dd}${hh} ${p1[2]}`\n    endif\n\n    #\n    # Move the data into directories identified by time:\n    #\n\n    mkdir -p ${validdate}\n    mv ${file} ${validdate}/NAM.${file:r}.${validdate}.grb\nend\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_scripts/ncep_rad_gribextract.csh",
    "content": "#!/bin/tcsh -ef\n\n#\n#  This script is intended primarily as an example of how to use the gribextract\n#  program to extract individual records from a GRIB Edition 1 dataset\n#\n\nset initial = 0\n\nwhile ( ${#argv} > 0 )\n\n   if ( ( \"${argv[1]}\" == \"-help\" ) || ( \"${argv[1]}\" == \"--help\" ) || ( \"${argv[1]}\" == \"-h\" ) ) then\n      printf \"Usage:  $0 [--initial] <RAD_file>\\n\"\n      exit (1)\n   else if ( ( \"${argv[1]}\" == \"-initial\" ) || ( \"${argv[1]}\" == \"--initial\" ) ) then\n      set initial = 1\n   else\n      set RAD_file = ${1}\n   endif\n   shift\n\nend\n\n#\n# From the ${nam_file}, extract downwelling longwave radiation.  Only take the\n# instantaneous field, skipping the fields.\n#\n\n#../Utility_programs/gribextract -q -c 205,1,0 -s 1,21,0 ${nam_file} LW.grb\n#../Utility_programs/gribextract -q -c 205,1,0 ${nam_file} LW.grb\n\n#if ( -z LW.grb ) rm LW.grb\n\nset edition = `../Utility_programs/gribedition ${RAD_file}`\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 205\n   set level_code     = 1,0\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,5,192\n   set level_code     = 1,0\nendif\nset LWDOWN_file = LWDOWN.grb\n../Utility_programs/gribextract -q -c ${parameter_code} -l ${level_code} ${RAD_file} ${LWDOWN_file}\n\n#\n# From the ${nam_file}, extract downwelling shortwave radiation.  Only take the\n# instantaneous field, skipping the fields.\n#\n\n#../Utility_programs/gribextract -q -c 204,1,0 -s 1,21,0 ${nam_file} SW.grb\n#../Utility_programs/gribextract -q -c 204,1,0 ${nam_file} SW.grb\n#if ( -z SW.grb ) rm SW.grb\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 204\n   set level_code     = 1,0\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,4,192\n   set level_code     = 1,0\nendif\nset SWDOWN_file = SWDOWN.grb\n../Utility_programs/gribextract -q -c ${parameter_code} -l ${level_code} ${RAD_file} ${SWDOWN_file}\n\n\nRenameFiles:\n\n\n\n\nforeach file ( *.grb )\n\n    #\n    # This is perhaps getting too fancy here, but use the od (octal dump) command to \n    # pull specific bytes out of the grib record, specifically, the bytes identifying\n    # the time of the field:\n    #\n    set cc = `od -j 32 -N 1 -t u1 ${file}`\n    set yy = `od -j 20 -N 1 -t u1 ${file}`\n    set mm = `od -j 21 -N 1 -t u1 ${file}`\n    set dd = `od -j 22 -N 1 -t u1 ${file}`\n    set hh = `od -j 23 -N 1 -t u1 ${file}`\n\n    set p1 = `od -j 26 -N 1 -t u1 ${file}`\n    set p2 = `od -j 27 -N 1 -t u1 ${file}`\n    set ti = `od -j 28 -N 1 -t u1 ${file}`\n\n    set cc = `printf \"%2.2d\" ${cc[2]}`\n    set yy = `printf \"%2.2d\" ${yy[2]}`\n    set mm = `printf \"%2.2d\" ${mm[2]}`\n    set dd = `printf \"%2.2d\" ${dd[2]}`\n    set hh = `printf \"%2.2d\" ${hh[2]}`\n\n    if ( ${yy} > 00 ) @ cc --\n\n    echo \"p1 = $p1[2];  p2 = $p2[2];  ti = $ti[2]\"\n    # echo $cc $yy $mm $dd $hh\n\n    if ( ${p1[2]} == 0 ) then\n       set validdate = ${cc}${yy}${mm}${dd}${hh}\n    else\n       set validdate = `../Utility_programs/geth_newdate ${cc}${yy}${mm}${dd}${hh} ${p1[2]}`\n    endif\n\n    #\n    # Move the data into directories identified by time:\n    #\n\n    mkdir -p ${validdate}\n    mv ${file} ${validdate}/NCEP.${file:r}.${validdate}.grb\nend\n"
  },
  {
    "path": "src/Land_models/Noah/Utility_scripts/ndas_surface_gribextract.csh",
    "content": "#!/bin/tcsh  -f\n\n#\n#  This script is intended primarily as an example of how to use the gribextract\n#  program to extract individual records from a GRIB dataset.  Users will likely\n#  have to adapt this script to their particular needs.\n#\n\n#\n# Process command-line arguments:\n#\n\nset initial = 0  # Default value\n\nwhile ( ${#argv} > 0 )\n\n   if ( ( \"${argv[1]}\" == \"-help\" ) || ( \"${argv[1]}\" == \"--help\" ) || ( \"${argv[1]}\" == \"-h\" ) ) then\n      printf \"Usage:  $0 [--initial] <ndas_sf_file>\\n\"\n      exit (1)\n   else if ( ( \"${argv[1]}\" == \"-initial\" ) || ( \"${argv[1]}\" == \"--initial\" ) ) then\n      set initial = 1\n   else\n      set ndas_sf_file = ${1}\n   endif\n   shift\n\nend\n\n#\n# Attempt to find the Utility_programs directory, assuming it is one up from where the Utility_scripts are found.\n#\nset scriptexe = $0\nset firstchar = `echo ${scriptexe} | cut -b 0-1`\nif ( \"${firstchar}\" == \".\" || \"${firstchar}\" == \"/\") then\n   # We have a path explicitly in the command as issued.\n   set scriptdir = ${scriptexe:h}\n   set progdir = ${scriptdir:h}/Utility_programs\nelse\n   # No path explicitly issued.  Assume Utility_programs is one up from here.\n   set progdir = ../Utility_programs\nendif\n\nif ( ! -e ${progdir} ) then\n   printf \"Cannot find directory %s\\n\" ${progdir}\n   exit (1)\nendif\n\n\n#\n# Determine if the file ${ndas_sf_file} is GRIB edition 1 or GRIB edition 2.\n#\n\nset edition = `${progdir}/gribedition ${ndas_sf_file}`\nif ( ( ${edition} != 1) && ( ${edition} != 2 ) ) then\n   printf  \"\\n ***** File not recognized as GRIB Edition 1 or GRIB Edition 2.\\n\"\n   printf  \" ***** File:  '%s'\\n\" ${ndas_sf_file}\n   exit (1)\nendif\n\n#\n# From the file ${ndas_sf_file}, extract the 2-m temperature field \n# and put it in the file ${T2_file}.  The string \"-c 11,105,2\" means:\n#     field code  11 = temperature\n#     level code 105 = meters above ground level\n#     level value  2 = 2 m AGL\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 11\n   set level_code     = 105,2\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,0,0\n   set level_code     = 103,2\nendif\nset T2_file = T2.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${T2_file}\n\n#\n# From the file ${ndas_sf_file}, extract the 2-m specific humidity field \n# and put it in the file ${Q2_file}.  The string \"-c 51,105,2\" means:\n#     field code  51 = specific humidity\n#     level code 105 = meters above ground level\n#     level value  2 = 2 m AGL\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 51\n   set level_code     = 105,2\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,1,0\n   set level_code     = 103,2\nendif\nset Q2_file = Q2.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${Q2_file}\n\n#\n# From the file ${ndas_sf_file}, extract the 10-m wind field (U component)\n# and put it in the files ${U10_file}.  The strings \"-c 33,105,10\" \n#     field code  33 = U component of horizontal wind\n#     level code 105 = meters above ground level\n#     level value 10 = 10 m AGL\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 33\n   set level_code     = 105,10\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,2,2\n   set level_code     = 103,10\nendif\nset U10_file = U10.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${U10_file}\n\n#\n# From the file ${ndas_sf_file}, extract the 10-m wind field (V component)\n# and put it in the files ${V10_file}.  The strings \"-c 34,105,10\" \n#     field code  34 = V component of horizontal wind\n#     level code 105 = meters above ground level\n#     level value 10 = 10 m AGL\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 34\n   set level_code     = 105,10\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,2,3\n   set level_code     = 103,10\nendif\nset V10_file = V10.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${V10_file}\n\n#\n# From the file ${ndas_sf_file}, extract the surface pressure field \n# and put it in the file ${PSFC_file}.  The string \"-c 1,1,0\" means:\n#     field code  1 = pressure\n#     level code  1 = surface\n#     level value 0 = surface\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 1\n   set level_code     = 1,0\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,3,0\n   set level_code     = 1,0\nendif\nset PSFC_file = PSFC.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${PSFC_file}\n\n#\n# From the file ${ndas_sf_file}, extract the water equivalent snow depth field,\n# and put it in the file ${WEASD_file}.  Here's an example where additional data\n# from the GRIB record are needed to uniquely identify a single field to extract\n# The string \"-c 65,1,0\" means:\n#     field code  65 = Water equivalent snow depth\n#     level code  1 = surface\n#     level value 0 = surface\n# The string \"-s 1,21,0\" means \"extract only fields for which section 1, byte 21 is \n# equal to zero.\"  Byte 21 of section 1 indicates whether the field is an analysis \n# field, or an accumulation over a time window.  We want only the analysis field.\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 65\n   set level_code     = 1,0\n   set section_code   = 1,21,0\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,1,13\n   set level_code     = 1,0\n   set section_code   = 4,8:9,0\nendif\nset WEASD_file = WEASD.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} -s ${section_code} ${ndas_sf_file} ${WEASD_file}\n\nif ( ! ${initial} ) goto RenameFiles\n\n#\n# From the file ${ndas_sf_file}, extract the source model terrain elevation field\n# and put it in the file ${ELEVATION_file}.  The string \"-c 7,1,0\" means:\n#     field code  7 = Geopotential height\n#     level code  1 = surface\n#     level value 0 = surface\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 7\n   set level_code     = 1,0\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,3,5\n   set level_code     = 1,0\nendif\nset ELEVATION_file = SURFACE_ELEVATION.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${ELEVATION_file}\n\n#\n# From the file ${ndas_sf_file}, extract the LAND/SEA flag \n# and put it in the file ${LANDSEA_file}.  The string \"-c 81,1,0\" means:\n#     field code  81 = land/sea flag\n#     level code  1 = surface\n#     level value 0 = surface\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 81\n   set level_code     = 1,0\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 2,0,0\n   set level_code     = 1,0\nendif\nset LANDSEA_file = LANDSEA.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${LANDSEA_file}\n\n#\n# From the file ${ndas_sf_file}, extract the canopy water flag\n# and put it in the file ${CANWAT_file}.  The string \"-c 223,1,0\" means:\n#     field code  223 = land/sea flag\n#     level code  1 = surface\n#     level value 0 = surface\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 223\n   set level_code     = 1,0\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 2,0,196\n   set level_code     = 1,0\nendif\nset CANWAT_file = CANWAT.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${CANWAT_file}\n\n#\n# From the file ${ndas_sf_file}, extract the skin temperature field\n# and put it in the file ${SKINTEMP_file}.  The string \"-c 11,1,0\" means:\n#     field code  11 = temperature\n#     level code  1 = surface (i.e., skin)\n#     level value 0 = surface\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 11\n   set level_code     = 1,0\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 0,0,0\n   set level_code     = 1,0\nendif\nset SKINTEMP_file = SKINTEMP.grb\n${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${SKINTEMP_file}\n\n#\n# From the file ${ndas_sf_file}, extract the soil temperature fields, for which\n# we have a priori knowledge about the soil levels.\n#  Field code 85 = soil temperature\n#  Level code 112 = depth below the surface in cm.\n#  Level values 0,10; 10,40; 40,100; and 100,200 indicate 0 to 10 cm, 10 to 40 cm, etc.\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 85\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 2,0,2\nendif\nforeach level ( 1 2 3 4 )\n   if ( ${level} == 1 ) then\n      set SOILT_file = SOIL_T_000-010.grb\n      if ( ${edition} == 1 ) then\n         set level_code = 112,0,10\n      else if ( ${edition} == 2 ) then\n         set level_code = 106,0,0.10\n      endif\n   else if ( ${level} == 2 ) then\n      set SOILT_file = SOIL_T_010-040.grb\n      if ( ${edition} == 1 ) then\n         set level_code = 112,10,40\n      else if ( ${edition} == 2 ) then\n         set level_code = 106,0.10,0.40\n      endif\n   else if ( ${level} == 3 ) then\n      set SOILT_file = SOIL_T_040-100.grb\n      if ( ${edition} == 1 ) then\n         set level_code = 112,40,100\n      else if ( ${edition} == 2 ) then\n         set level_code = 106,0.40,1.00\n      endif\n   else if ( ${level} == 4 ) then\n      set SOILT_file = SOIL_T_100-200.grb\n      if ( ${edition} == 1 ) then\n         set level_code = 112,100,200\n      else if ( ${edition} == 2 ) then\n         set level_code = 106,1.0,2.0\n      endif\n   endif\n   ${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${SOILT_file}\nend\n\n#\n# From the file ${ndas_sf_file}, extract the soil moisture fields, for which\n# we have a priori knowledge about the soil levels.\n#  Field code 144 = volumetric soil temperature\n#  Level code 112 = depth below the surface in cm.\n#  Level values 0,10; 10,40; 40,100; and 100,200 indicate 0 to 10 cm, 10 to 40 cm, etc.\n#\n\nif ( ${edition} == 1 ) then\n   set parameter_code = 144\nelse if ( ${edition} == 2 ) then\n   set parameter_code = 2,0,192\nendif\nforeach level ( 1 2 3 4 )\n   if ( ${level} == 1 ) then\n      set SOILM_file = SOIL_M_000-010.grb\n      if ( ${edition} == 1 ) then\n         set level_code = 112,0,10\n      else if ( ${edition} == 2 ) then\n         set level_code = 106,0,0.10\n      endif\n   else if ( ${level} == 2 ) then\n      set SOILM_file = SOIL_M_010-040.grb\n      if ( ${edition} == 1 ) then\n         set level_code = 112,10,40\n      else if ( ${edition} == 2 ) then\n         set level_code = 106,0.10,0.40\n      endif\n   else if ( ${level} == 3 ) then\n      set SOILM_file = SOIL_M_040-100.grb\n      if ( ${edition} == 1 ) then\n         set level_code = 112,40,100\n      else if ( ${edition} == 2 ) then\n         set level_code = 106,0.40,1.00\n      endif\n   else if ( ${level} == 4 ) then\n      set SOILM_file = SOIL_M_100-200.grb\n      if ( ${edition} == 1 ) then\n         set level_code = 112,100,200\n      else if ( ${edition} == 2 ) then\n         set level_code = 106,1.0,2.0\n      endif\n   endif\n   ${progdir}/gribextract -q -c ${parameter_code} -l ${level_code} ${ndas_sf_file} ${SOILM_file}\nend\n\nRenameFiles:\n\n\nforeach file ( *.grb )\n\n    #\n    # This is perhaps getting too fancy here, but use the od (octal dump) command to \n    # pull specific bytes out of the grib record, specifically, the bytes identifying\n    # the time of the field:\n    #\n\n    if ( ${edition} == 1 ) then\n       set cc = `${progdir}/gribbyte -s 1,25 ${file}`\n       set yy = `${progdir}/gribbyte -s 1,13 ${file}`\n       set mm = `${progdir}/gribbyte -s 1,14 ${file}`\n       set dd = `${progdir}/gribbyte -s 1,15 ${file}`\n       set hh = `${progdir}/gribbyte -s 1,16 ${file}`\n\n       set tu = `${progdir}/gribbyte -s 1,18 ${file}`\n       set p1 = `${progdir}/gribbyte -s 1,19 ${file}`\n       set p2 = `${progdir}/gribbyte -s 1,20 ${file}`\n       set ti = `${progdir}/gribbyte -s 1,21 ${file}`\n\n       set cc = `printf \"%2.2d\" ${cc}`\n       set yy = `printf \"%2.2d\" ${yy}`\n       set mm = `printf \"%2.2d\" ${mm}`\n       set dd = `printf \"%2.2d\" ${dd}`\n       set hh = `printf \"%2.2d\" ${hh}`\n\n       set yytest = `dc -e \"${yy} p\"`  # use dc to pop the value, which returns a value without any leading zeroes.\n       if ( ${yytest} > 0 ) @ cc --\n\n       # echo \"tu = ${tu};   p1 = $p1;  p2 = $p2;  ti = $ti\"\n\n       #\n       # Compute a valid date, based on reference time and time offset.\n       # Ultimately, this should take into account time units and time\n       # range indicator.\n       #\n\n       if ( ( ${tu} == 1 ) && ( ${ti} == 0 ) )  then\n\t  set validdate = `${progdir}/geth_newdate ${cc}${yy}${mm}${dd}${hh} ${p1}`\n       else\n\t  set validdate = 0000000000\n       endif\n\t\n       #\n       # Move the data into directories identified by time:\n       #\n\n       mkdir -p ${cc}${yy}${mm}${dd}${hh}\n       mv ${file} ${cc}${yy}${mm}${dd}${hh}/NDAS.${file:r}.${validdate}.grb\n\n   else if ( ${edition} == 2 ) then\n       set yyyy = `${progdir}/gribbyte -s 1,13:14 -d ${file}`\n       set mm   = `${progdir}/gribbyte -s 1,15 ${file}`\n       set dd   = `${progdir}/gribbyte -s 1,16 ${file}`\n       set hh   = `${progdir}/gribbyte -s 1,17 ${file}`\n       set yyyy = `printf \"%4.4d\" ${yyyy}`\n       set mm = `printf \"%2.2d\" ${mm}`\n       set dd = `printf \"%2.2d\" ${dd}`\n       set hh = `printf \"%2.2d\" ${hh}`\n\n       # Compute a valid date, based on reference time and time offset.\n       set tu = `${progdir}/gribbyte -s 4,18 ${file}`\n       set p1 = `${progdir}/gribbyte -s 4,19:22 -d ${file}`\n       \n       echo \"tu = ${tu};  p1 = ${p1}\"\n\n       if ( ${tu} == 1 )  then\n          set validdate = `${progdir}/geth_newdate ${yyyy}${mm}${dd}${hh} ${p1}`\n       else\n          set validdate = 0000000000\n       endif\n\n       #\n       # Move the data into directories identified by time:\n       #\n       mkdir -p ${yyyy}${mm}${dd}${hh}\n       mv ${file} ${yyyy}${mm}${dd}${hh}/NDAS.${file:r}.${validdate}.grb\n   endif\nend\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/Makefile",
    "content": ".SUFFIXES:\t.F .o\n#\nOBJS=\tmodule_hd.o \\\n\tfluxes_statistics.o \\\n\tkwm_date_utilities.o \\\n\tkwm_plot_utilities.o \\\n\tkwm_grid_utilities.o \\\n\tkwm_string_utilities.o \\\n\tllxy_generic.o lccone.o get_unused_unit.o\n\nCMD=\tfluxes_statistics.exe\n\n\nF90=\tpgf90\nFFLAGS=\t-Mfree -byteswapio -C -g\nNETCDF=/scholar/kmanning/netcdf-3.6.3-pgf90\n\n# F90=\tifort\n# FFLAGS=\t-free -convert big_endian -check bounds -g\n# NETCDF=/home/kmanning/netcdf-3.6.0-p1-ifort\n\nINCLUDES= -I. -I$(NETCDF)/include\nLIBS=\t-L$(NETCDF)/lib -lnetcdf \\\n\t-L$(NCARG_ROOT)/lib -lncarg -lncarg_gks -lncarg_c \\\n\t-L/usr/X11R6/lib -lX11 \\\n\t-L/usr/lib/gcc/i386-redhat-linux/3.4.6 -lg2c \n\nall: $(CMD)\n\n$(CMD): $(OBJS)\n\t$(F90) $(FFLAGS) -o $(CMD) $(INCLUDES) $(OBJS) $(LIBS)\n\n.F.o:\n\t$(F90) $(FFLAGS) $(INCLUDES) -c $(<)\n\nclean:\n\trm -f $(OBJS) $(CMD) *~ *.mod\n\nfluxes_statistics.o:\tkwm_plot_utilities.o\nfluxes_statistics.o:\tkwm_date_utilities.o\nfluxes_statistics.o:\tkwm_grid_utilities.o\nkwm_plot_utilities.o:\tkwm_string_utilities.o\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/fluxes_statistics.F",
    "content": "program fluxes_statistics\n  use kwm_date_utilities\n  use kwm_grid_utilities\n  use kwm_plot_utilities, only : kwm_init_ncargks, color_index, connect_the_dots, line_in_color, kwm_close_ncargks\n  use module_hd\n!  use v3_module\n  implicit none\n\n  character(len=256) :: flnm\n  character(len=16) :: startdate = \"2002-06-01_00:00\"\n  character(len=16) :: enddate =   \"2002-06-24_00:00\"\n\n  integer :: ntim\n  integer :: ista\n\n  integer, parameter :: MAXSTA = 9\n  ! integer, parameter :: MAXTIM = 9500\n  integer, parameter :: MAXTIM = 4500\n  real, dimension(MAXSTA) :: lat, lon, x, y\n  real, dimension(MAXSTA, MAXTIM) :: hfx = -1.E33\n  real, dimension(MAXSTA, MAXTIM) :: qfx_old = -1.E33\n  real, dimension(MAXSTA, MAXTIM) :: qfx_corrected = -1.E33\n  real, dimension(MAXSTA, MAXTIM) :: hrldas_hfx = -1.E33\n  real, dimension(MAXSTA, MAXTIM) :: hrldas_qfx = -1.E33\n  real, pointer, dimension(:,:) :: hfxptr, qfxptr, vegtyp, soltyp\n\n  integer :: ierr, ibf, iaf, ihr\n  character(len=16) :: nowdate\n  integer, parameter :: icode = 10, iunit = 10\n\n  character(len=16), dimension(MAXSTA,MAXTIM) :: hdate, hrldas_hdate\n  integer :: itime\n  logical :: lexist\n  integer, dimension(0:23) :: qfxcount = 0, station_qfxcount, qfxcount_old = 0, station_qfxcount_old\n  integer, dimension(0:23) :: hfxcount = 0, station_hfxcount\n\n  real, dimension(0:23) :: qfxrmse = 0, qfxbias = 0, qfxoavg = 0, qfxmavg = 0 \n  real, dimension(0:23) :: qfxrmse_old = 0, qfxbias_old = 0, qfxoavg_old = 0, qfxmavg_old = 0 \n  real, dimension(0:23) :: hfxrmse = 0, hfxbias = 0, hfxoavg = 0, hfxmavg = 0\n\n  real, dimension(0:23) :: station_qfxrmse, station_qfxbias, station_qfxoavg, station_qfxmavg\n  real, dimension(0:23) :: station_qfxrmse_old, station_qfxbias_old, station_qfxoavg_old, station_qfxmavg_old\n\n  real, dimension(0:23) :: station_hfxrmse, station_hfxbias, station_hfxoavg, station_hfxmavg\n\n  real :: station_qfx_bias, station_qfxcorr_bias, station_hfx_bias\n  real :: station_qfx_rmse, station_qfxcorr_rmse, station_hfx_rmse\n  integer :: station_hfx_count, station_qfx_count, station_qfxcorr_count\n\n  type(nf_structure) :: nfstruct\n  real :: xl, xr, xb, xt, wl, wr, wb, wt\n  integer :: ml\n  real, dimension(0:24) :: xarray_diurnal = (/ ( itime, itime=0,24 ) /)\n  integer :: narray\n  real, dimension(10000) :: xarray\n  real, dimension(10000) :: yarray\n  real, dimension(10000) :: zarray\n  real, dimension(10000) :: xxarray\n  real, dimension(10000) :: yyarray\n  real, dimension(10000) :: zzarray\n  real, dimension(10000) :: xxxarray\n  real, dimension(10000) :: yyyarray\n\n  real, dimension(10000) :: qfxcorrobs_allsta, qfxcorrmdl_allsta\n  integer                :: qfxcorr_ndim_allsta\n  real                   :: qfxcorr_bias_allsta, qfxcorr_rmse_allsta, qfxcorr_correlation_allsta, qfxcorr_lsra_allsta, qfxcorr_lsrb_allsta\n\n  real, dimension(10000) :: hfxobs_allsta, hfxmdl_allsta\n  integer                :: hfx_ndim_allsta\n  real                   :: hfx_bias_allsta, hfx_rmse_allsta, hfx_correlation_allsta, hfx_lsra_allsta, hfx_lsrb_allsta\n\n  real, dimension(10000) :: qfxobs_allsta, qfxmdl_allsta\n  integer                :: qfx_ndim_allsta\n  real                   :: qfx_bias_allsta, qfx_rmse_allsta, qfx_correlation_allsta, qfx_lsra_allsta, qfx_lsrb_allsta\n\n  character(len=256) :: fluxobs_directory = \"\"\n  character(len=256) :: ldasout_directory = \"\"\n\n  real :: bias\n  real :: rmse\n  real :: correlation\n  real :: lsra\n  real :: lsrb\n  character(len=1) :: textsta\n\n  real :: frame_left\n  real :: frame_right\n  real :: frame_bottom\n  real :: frame_top\n  real :: textsize\n\n  call read_namelist(fluxobs_directory, ldasout_directory)\n\n!KWM  open(iunit, file=\"mem.dump\", form='unformatted')\n!KWM  close(iunit, status=\"delete\")\n!KWM  inquire (file=\"mem.dump\", exist=lexist)\n!KWM\n!KWM  if (.not. lexist) then\n\n     call geth_idts(enddate, startdate, ntim)\n     ntim = (ntim / 15) + 1\n     print*, 'ntim = ', ntim\n\n     ! Read the IHOP site data into arrays\n\n     do ista = 1, maxsta\n        call read_ihop(fluxobs_directory, startdate, ista, lat(ista), lon(ista),  &\n             hdate(ista,:), hfx(ista,:), qfx_old(ista,:), qfx_corrected(ista,:), maxtim)\n     enddo\n\n     ! Read the HRLDAS (NetCDF-format) data into arrays\n     call geth_newdate(nowdate(1:16), startdate(1:16), -60)\n\n     do while ( nowdate <= enddate )\n        call geth_newdate(nowdate, nowdate, 60)\n        print*, 'nowdate = ', nowdate\n!        flnm = \"/avn2/kmanning/T1_TEST/Run/\"&\n!        flnm = \"/avn2/kmanning/STATS/LDASOUT/\"&\n        flnm = trim(ldasout_directory)//\"/\" &\n             //nowdate(1:4)//nowdate(6:7)// &\n             nowdate(9:10)//nowdate(12:13)//\".LDASOUT_DOMAIN1\"\n        call netcdf_open(trim(flnm), nfstruct)\n\n\n!KWM  call kwm_init_ncargks(\"locations.cgm\")\n!KWM        call wrfmap(nfstruct)\n!KWM        call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n!KWM        call set(xl, xr, xb, xt, 1., float(nfstruct%idim), 1., float(nfstruct%jdim), 1)\n\n        if (nowdate == startdate) then\n           do ista = 1, maxsta\n              call lltoxy_hd(lat(ista), lon(ista), x(ista), y(ista), nfstruct)\n!KWM CORRECT OFFSET              ! x and y are in dot-point coordinates.  \n!KWM CORRECT OFFSET              ! Convert to cross-point coordinates\n!KWM CORRECT OFFSET              x(ista) = x(ista) - 0.5\n!KWM CORRECT OFFSET              y(ista) = y(ista) - 0.5\n              print*, 'nfstruct%dskm = ', nfstruct%dskm\n              print*, 'reflat, reflon = ', nfstruct%reflat, nfstruct%reflon\n              print*, 'lat, lon, x, y = ', lat(ista), lon(ista), x(ista), y(ista)\n!KWM              call ngdots(x(ista), y(ista), 1, 1.0, color_index(\"red\"))\n           enddo\n        endif\n\n!KWM  call kwm_close_ncargks\n\n        call netcdf_get_field(nfstruct, \"HFX\", 1, hfxptr)\n        call netcdf_get_field(nfstruct, \"QFX\", 1, qfxptr)\n        ! call netcdf_get_field(nfstruct, \"IVGTYP\", 1, vegtyp)\n        ! call netcdf_get_field(nfstruct, \"ISLTYP\", 1, soltyp)\n\n        ! qfxptr = qfxptr * 2.5E6 ! For some of the older data I have that is in different units\n\n        call geth_idts(nowdate, startdate, itime)\n        itime = (itime / 15) + 1\n        if (itime > maxtim) stop \"Increase maxtim\"\n        ! print*, 'itime = ', itime, nowdate\n\n        do ista = 1, maxsta\n           ! print*, 'x y = ', x(ista), y(ista)\n           hrldas_hdate(ista, itime) = nowdate\n!KWM           hrldas_hfx(ista, itime) = hfxptr(nint(x(ista)),nint(y(ista)))\n!KWM           hrldas_qfx(ista, itime) = qfxptr(nint(x(ista)),nint(y(ista)))\n           hrldas_hfx(ista,itime) = &\n                four_point(hfxptr, nfstruct%idim, nfstruct%jdim, x(ista), y(ista))\n           hrldas_qfx(ista,itime) = &\n                four_point(qfxptr, nfstruct%idim, nfstruct%jdim, x(ista), y(ista))\n           ! print*, 'Station, vegetype, soiltype = ', ista,  &\n           ! vegtyp(nint(x(ista)), nint(y(ista))), soltyp(nint(x(ista)), nint(y(ista)))\n        enddo\n        ! print*, hrldas_hfx(:,itime)\n\n        ierr = nf90_close(nfstruct%ncid)\n\n        deallocate(hfxptr, qfxptr)\n        nullify(hfxptr, qfxptr)\n!KWM        deallocate(vegtyp)\n!KWM        nullify(vegtyp)\n!KWM        deallocate(soltyp)\n!KWM        nullify(soltyp)\n\n     enddo\n\n\n\n     ! Fill in observed flux data on the hour\n     do itime = 2, maxtim-1\n        do ista = 1, maxsta\n           if (qfx_corrected(ista,itime) < -1.E25) then\n              if ((qfx_corrected(ista,itime-1) > -1.E25) .and. &\n                   (qfx_corrected(ista,itime+1) > -1.E25)) then\n                 qfx_corrected(ista,itime) = &\n                      0.5*(qfx_corrected(ista,itime-1)+qfx_corrected(ista,itime+1))\n              endif\n           endif\n           if (qfx_old(ista,itime) < -1.E25) then\n              if ((qfx_old(ista,itime-1) > -1.E25) .and. &\n                   (qfx_old(ista,itime+1) > -1.E25)) then\n                 qfx_old(ista,itime) = &\n                      0.5*(qfx_old(ista,itime-1)+qfx_old(ista,itime+1))\n              endif\n           endif\n           if (hfx(ista,itime) < -1.E25) then\n              if ((hfx(ista,itime-1) > -1.E25) .and. (hfx(ista,itime+1) > -1.E25)) then\n                 hfx(ista,itime) = 0.5*(hfx(ista,itime-1)+hfx(ista,itime+1))\n              endif\n           endif\n        enddo\n     enddo\n\n     ! Fill in hrldas flux data on the off times\n     TIMELOOP : do itime = 2, maxtim-1\n        do ista = 1, maxsta\n           if (hrldas_hdate(ista,itime) > enddate) exit TIMELOOP\n           if (hdate(ista,itime) > enddate) exit TIMELOOP\n!KWM           print '(A, i6, i6, f12.8, \"(\",A16,\")\" 1x, \"(\",A16, \")\")', 'itime, ista = ', &\n!KWM                itime, ista, hrldas_qfx(ista, itime), hdate(ista, itime), hrldas_hdate(ista, itime)\n           if ( hrldas_qfx(ista, itime) < -1.E25 ) then\n              ibf = itime\n              do while ( hrldas_qfx(ista, ibf) < -1.E25)\n                 ibf = ibf - 1\n              enddo\n              iaf = itime\n              do while ( hrldas_qfx(ista, iaf) < -1.E25)\n                 iaf = iaf + 1\n              enddo\n              hrldas_qfx(ista,itime) = (hrldas_qfx(ista,ibf)*(iaf-itime) + &\n                   hrldas_qfx(ista,iaf)*(itime-ibf))/float(iaf-ibf)\n           endif\n\n           if ( hrldas_hfx(ista, itime) < -1.E25 ) then\n              ibf = itime\n              do while ( hrldas_hfx(ista, ibf) < -1.E25)\n                 ibf = ibf - 1\n              enddo\n              iaf = itime\n              do while ( hrldas_hfx(ista, iaf) < -1.E25)\n                 iaf = iaf + 1\n              enddo\n              hrldas_hfx(ista,itime) = (hrldas_hfx(ista,ibf)*(iaf-itime) + &\n                   hrldas_hfx(ista,iaf)*(itime-ibf))/float(iaf-ibf)\n           endif\n\n        enddo\n     enddo TIMELOOP\n\n!KWM     ! Mem Dump\n!KWM     open(114, file='mem.dump', form='unformatted', action='write')\n!KWM     write(114) lat, lon, x, y, hrldas_hdate, hrldas_hfx, hrldas_qfx, &\n!KWM          hdate, hfx, qfx_old, qfx_corrected, ntim\n!KWM     close(114)\n!KWM  else\n!KWM     open(114, file='mem.dump', form='unformatted', action='read')\n!KWM     read(114) lat, lon, x, y, hrldas_hdate, hrldas_hfx, hrldas_qfx, &\n!KWM          hdate, hfx, qfx_old, qfx_corrected, ntim\n!KWM     close(114)\n!KWM  endif\n\n  ! Now that I've got everything, do some plotting:\n\n  call kwm_init_ncargks(\"fluxes.cgm\")\n  call gaseti(\"LTY\", 2)\n\n  qfxcorr_ndim_allsta = 0\n  hfx_ndim_allsta = 0\n  qfx_ndim_allsta = 0\n\n  STATIONLOOP : do ista = 1, maxsta\n\n     write(textsta, '(I1)') ista\n     station_qfxoavg = 0.\n     station_qfxmavg = 0.\n     station_qfxbias = 0.\n     station_qfxrmse = 0.\n     station_qfxcount = 0\n\n     station_hfxoavg = 0.\n     station_hfxmavg = 0.\n     station_hfxbias = 0.\n     station_hfxrmse = 0.\n     station_hfxcount = 0\n\n     station_qfxoavg_old = 0.\n     station_qfxmavg_old = 0.\n     station_qfxbias_old = 0.\n     station_qfxrmse_old = 0.\n     station_qfxcount_old = 0\n\n     station_hfx_bias = 0.\n     station_qfx_bias = 0.\n     station_qfxcorr_bias = 0.\n\n     station_hfx_count = 0.\n     station_qfx_count = 0.\n     station_qfxcorr_count = 0.\n\n     station_hfx_rmse = 0.\n     station_qfx_rmse = 0.\n     station_qfxcorr_rmse = 0.\n\n     call gsln(1)\n     nowdate = startdate\n\n     ! QFX_Corrected\n     do while ( nowdate(1:13) < enddate(1:13) )\n        call geth_newdate(nowdate(1:13), nowdate(1:13), 1)\n        call geth_idts(nowdate(1:13), startdate(1:13), itime)\n        itime = (itime * 4) + 1\n        ! if (qfx_corrected(ista,itime) > -1.E25) then\n        if (qfx_corrected(ista,itime) > -2000) then\n           read(nowdate(12:13),*) ihr\n           qfxoavg(ihr) = qfxoavg(ihr) + qfx_corrected(ista,itime+1)\n           qfxmavg(ihr) = qfxmavg(ihr) + hrldas_qfx(ista,itime)\n           qfxbias(ihr) = qfxbias(ihr) + (hrldas_qfx(ista,itime)-qfx_corrected(ista,itime+1))\n           qfxrmse(ihr) = qfxrmse(ihr) + &\n                ((hrldas_qfx(ista,itime) - qfx_corrected(ista,itime+1))**2)\n           qfxcount(ihr) = qfxcount(ihr) + 1\n\n           station_qfxoavg(ihr) = station_qfxoavg(ihr) + qfx_corrected(ista,itime+1)\n           station_qfxmavg(ihr) = station_qfxmavg(ihr) + hrldas_qfx(ista,itime)\n           station_qfxbias(ihr) = station_qfxbias(ihr) + (hrldas_qfx(ista,itime)-qfx_corrected(ista,itime+1))\n           station_qfxrmse(ihr) = station_qfxrmse(ihr) + ((hrldas_qfx(ista,itime) - qfx_corrected(ista,itime+1))**2)\n           station_qfxcount(ihr) = station_qfxcount(ihr) + 1\n\n           station_qfxcorr_bias = station_qfxcorr_bias + (hrldas_qfx(ista,itime)-qfx_corrected(ista, itime+1))\n           station_qfxcorr_rmse = station_qfxcorr_rmse + (hrldas_qfx(ista,itime)-qfx_corrected(ista, itime+1))**2\n\n           station_qfxcorr_count = station_qfxcorr_count + 1\n\n           xarray(station_qfxcorr_count) = float(itime)\n           yarray(station_qfxcorr_count) = qfx_corrected(ista,itime+1)\n           zarray(station_qfxcorr_count) = hrldas_qfx(ista,itime)\n\n           qfxcorr_ndim_allsta = qfxcorr_ndim_allsta + 1\n           qfxcorrobs_allsta(qfxcorr_ndim_allsta) = qfx_corrected(ista,itime+1)\n           qfxcorrmdl_allsta(qfxcorr_ndim_allsta) = hrldas_qfx(ista,itime)\n\n        endif\n     enddo\n\n     frame_left   = 0.0\n     frame_right  = 0.5\n     frame_bottom = 0.5\n     frame_top    = 1.0\n     xl = frame_left\n     xr = frame_right\n     xb = frame_bottom\n     xt = frame_top\n     call set ( xl , xr , xb , xt , 0.0 , 1.0 , 0.0 , 1.0 , 1 )\n     call perim(0,0,0,0)\n     call pchiqu(0.525, 0.95, \"QFX:  Station \"//textsta, 0.0075, 0.0, 0.0)\n\n     xl = frame_left   + (frame_right-frame_left  )*0.15\n     xr = frame_left   + (frame_right-frame_left  )*0.95\n     xb = frame_bottom + (frame_top  -frame_bottom)*0.10\n     xt = frame_bottom + (frame_top  -frame_bottom)*0.90\n     call set ( xl , xr , xb , xt , xarray(1) , xarray(station_qfxcorr_count) , -100.0 , 500.0 , 1 )\n     call gasetc(\"XLF\", '(F5.0)')\n     call gasetc(\"YLF\", '(F5.0)')\n     call gasetr(\"XLS\", 0.015  * min(xr-xl,xt-xb))\n     call gasetr(\"YLS\", 0.015  * min(xr-xl,xt-xb))\n     call gasetr(\"XLO\", 0.008 * min(xr-xl,xt-xb))\n     call gasetr(\"YLO\", 0.008 * min(xr-xl,xt-xb))\n     call gasetr(\"XMJ\", 0.014 * min(xr-xl,xt-xb))\n     call gasetr(\"YMJ\", 0.014 * min(xr-xl,xt-xb))\n     call gasetr(\"XMN\", 0.007 * min(xr-xl,xt-xb))\n     call gasetr(\"YMN\", 0.007 * min(xr-xl,xt-xb))\n     call periml(0, 0, 6, 0)\n     call connect_the_dots(xarray, yarray, station_qfxcorr_count, color=\"blue\")\n\n     nowdate = startdate\n     ! QFX_old\n     do while ( nowdate(1:13) < enddate(1:13) )\n        call geth_newdate(nowdate(1:13), nowdate(1:13), 1)\n        call geth_idts(nowdate(1:13), startdate(1:13), itime)\n        itime = (itime * 4) + 1\n        if (qfx_old(ista,itime) > -2000) then\n           read(nowdate(12:13),*) ihr\n           qfxoavg_old(ihr) = qfxoavg_old(ihr) + qfx_old(ista,itime+1)\n           qfxmavg_old(ihr) = qfxmavg_old(ihr) + hrldas_qfx(ista,itime)\n           qfxbias_old(ihr) = qfxbias_old(ihr) + (hrldas_qfx(ista,itime)-qfx_old(ista,itime+1))\n           qfxrmse_old(ihr) = qfxrmse_old(ihr) + &\n                ((hrldas_qfx(ista,itime) - qfx_old(ista,itime+1))**2)\n           qfxcount_old(ihr) = qfxcount_old(ihr) + 1\n\n           station_qfxoavg_old(ihr) = station_qfxoavg_old(ihr) + qfx_old(ista,itime+1)\n           station_qfxmavg_old(ihr) = station_qfxmavg_old(ihr) + hrldas_qfx(ista,itime)\n           station_qfxbias_old(ihr) = station_qfxbias_old(ihr) + (hrldas_qfx(ista,itime)-qfx_old(ista,itime+1))\n           station_qfxrmse_old(ihr) = station_qfxrmse_old(ihr) + ((hrldas_qfx(ista,itime) - qfx_old(ista,itime+1))**2)\n           station_qfxcount_old(ihr) = station_qfxcount_old(ihr) + 1\n\n           station_qfx_bias = station_qfx_bias + (hrldas_qfx(ista,itime) - qfx_old(ista, itime+1))\n           station_qfx_rmse = station_qfx_rmse + (hrldas_qfx(ista,itime) - qfx_old(ista, itime+1))**2\n           station_qfx_count = station_qfx_count + 1\n\n           xxarray(station_qfx_count) = float(itime)\n           yyarray(station_qfx_count) = qfx_old(ista,itime+1)\n           zzarray(station_qfx_count) = hrldas_qfx(ista,itime)\n\n           qfx_ndim_allsta = qfx_ndim_allsta + 1\n           qfxobs_allsta(qfx_ndim_allsta) = qfx_old(ista,itime+1)\n           qfxmdl_allsta(qfx_ndim_allsta) = hrldas_qfx(ista,itime)\n\n        endif\n     enddo\n\n     ! HRLDAS qfx\n     narray = 0\n     nowdate = startdate\n     do while ( nowdate(1:13) < enddate(1:13) )\n        call geth_newdate(nowdate(1:13), nowdate(1:13), 1)\n        call geth_idts(nowdate(1:13), startdate(1:13), itime)\n        itime = (itime * 4) + 1\n        if (hrldas_qfx(ista,itime) > -2000) then\n           narray = narray + 1\n           xxxarray(narray) = float(itime)\n           yyyarray(narray) = hrldas_qfx(ista,itime)\n        endif\n     enddo\n\n     call connect_the_dots(xxarray, yyarray, station_qfx_count, color=\"green\")\n     call connect_the_dots(xxxarray, yyyarray, narray, color=\"red\")\n\n     call gasetc(\"YLF\", '(F5.0)')\n     call gasetc(\"XLF\", '(F5.0)')\n\n     call flux_stats(yarray,  zarray,  station_qfxcorr_count, bias, rmse, correlation, lsra, lsrb)\n     call draw_scatter(\"Obs QFX Corrected\", \"HRLDAS QFX\", yarray, zarray, station_qfxcorr_count, &\n          &            bias, rmse, correlation, lsra, lsrb, 0.5, 1.0, 0.5, 1.0)\n\n     call flux_stats(yyarray, zzarray, station_qfx_count,     bias, rmse, correlation, lsra, lsrb)\n     call draw_scatter(\"Obs QFX\", \"HRLDAS QFX\", yyarray, zzarray, station_qfx_count, &\n          &            bias, rmse, correlation, lsra, lsrb, 0.5, 1.0, 0., 0.5)\n\n     station_qfxoavg = station_qfxoavg / float(station_qfxcount)\n     station_qfxmavg = station_qfxmavg / float(station_qfxcount)\n     station_qfxbias = station_qfxbias / float(station_qfxcount)\n     station_qfxrmse = sqrt(station_qfxrmse/float(station_qfxcount))\n\n     station_qfxoavg_old = station_qfxoavg_old / float(station_qfxcount_old)\n     station_qfxmavg_old = station_qfxmavg_old / float(station_qfxcount_old)\n     station_qfxbias_old = station_qfxbias_old / float(station_qfxcount_old)\n     station_qfxrmse_old = sqrt(station_qfxrmse_old/float(station_qfxcount_old))\n\n     frame_left   = 0.0\n     frame_right  = 0.5\n     frame_bottom = 0.0\n     frame_top    = 0.5\n     xl = frame_left\n     xr = frame_right\n     xb = frame_bottom\n     xt = frame_top\n     call set ( xl , xr , xb , xt , 0.0 , 1.0 , 0.0 , 1.0 , 1 )\n     call perim(0,0,0,0)\n     textsize = min((xr-xl),(xt-xb))*0.015\n     call pchiqu(0.5, 0.95, \"QFX -- Average diurnal cycle:  Station \"//textsta, textsize, 0.0, 0.0)\n     xl = frame_left   + (frame_right-frame_left  )*0.15\n     xr = frame_left   + (frame_right-frame_left  )*0.95\n     xb = frame_bottom + (frame_top  -frame_bottom)*0.10\n     xt = frame_bottom + (frame_top  -frame_bottom)*0.90\n\n     call pchiqu(0.18, 0.87, \"Obs:\", textsize, 0., -1.)\n     call pchiqu(0.18, 0.84, \"Obs Corr\", textsize, 0., -1.)\n     call pchiqu(0.18, 0.81, \"HRLDAS:\", textsize, 0., -1.)\n     call line_in_color(.3, .87, .40, .87, color_index(\"green\"))\n     call line_in_color(.3, .84, .40, .84, color_index(\"blue\"))\n     call line_in_color(.3, .81, .40, .81, color_index(\"red\"))\n\n     call set ( xl , xr , xb , xt , xarray_diurnal(0) , xarray_diurnal(24) , -100.0 , 500.0 , 1 )\n     call line_in_color(xarray_diurnal(0), 0.0, xarray_diurnal(24), 0.0, color_index(\"gray90\"))\n     call line_in_color(xarray_diurnal(0), 100.0, xarray_diurnal(24), 100.0, color_index(\"gray90\"))\n     call line_in_color(xarray_diurnal(0), 200.0, xarray_diurnal(24), 200.0, color_index(\"gray90\"))\n     call line_in_color(xarray_diurnal(0), 300.0, xarray_diurnal(24), 300.0, color_index(\"gray90\"))\n     call line_in_color(xarray_diurnal(0), 400.0, xarray_diurnal(24), 400.0, color_index(\"gray90\"))\n     call gasetc(\"XLF\", \"(I2.2)\")\n     call periml(24, 0, 6, 0)\n\n     call connect_the_dots(xarray_diurnal, (/station_qfxoavg,station_qfxoavg(0)/), 25, color=\"blue\")\n     call connect_the_dots(xarray_diurnal, (/station_qfxoavg_old,station_qfxoavg_old(0)/), 25, color=\"green\")\n     call connect_the_dots(xarray_diurnal, (/station_qfxmavg,station_qfxmavg(0)/), 25, color=\"red\")\n\n     call frame()\n\n     ! HFX\n\n     nowdate = startdate\n     do while ( nowdate(1:13) < enddate(1:13) )\n        call geth_newdate(nowdate(1:13), nowdate(1:13), 1)\n        call geth_idts(nowdate(1:13), startdate(1:13), itime)\n        itime = (itime * 4) + 1\n        if (hfx(ista,itime) > -2000) then\n           read(nowdate(12:13),*) ihr\n           hfxoavg(ihr) = hfxoavg(ihr) + hfx(ista,itime+1)\n           hfxmavg(ihr) = hfxmavg(ihr) + hrldas_hfx(ista,itime)\n           hfxbias(ihr) = hfxbias(ihr) + (hrldas_hfx(ista,itime)-hfx(ista,itime+1))\n           hfxrmse(ihr) = hfxrmse(ihr) + &\n                ((hrldas_hfx(ista,itime) - hfx(ista,itime+1))**2)\n           hfxcount(ihr) = hfxcount(ihr) + 1\n\n           station_hfxoavg(ihr) = station_hfxoavg(ihr) + hfx(ista,itime+1)\n           station_hfxmavg(ihr) = station_hfxmavg(ihr) + hrldas_hfx(ista,itime)\n           station_hfxbias(ihr) = station_hfxbias(ihr) + (hrldas_hfx(ista,itime)-hfx(ista,itime+1))\n           station_hfxrmse(ihr) = station_hfxrmse(ihr) + ((hrldas_hfx(ista,itime) - hfx(ista,itime+1))**2)\n           station_hfxcount(ihr) = station_hfxcount(ihr) + 1\n\n           station_hfx_bias = station_hfx_bias + (hrldas_hfx(ista,itime) - hfx(ista, itime+1))\n           station_hfx_rmse = station_hfx_rmse + (hrldas_hfx(ista,itime) - hfx(ista, itime+1))**2\n           station_hfx_count = station_hfx_count + 1\n\n           xarray(station_hfx_count) = float(itime)\n           yarray(station_hfx_count) = hfx(ista,itime+1)\n           zarray(station_hfx_count) = hrldas_hfx(ista,itime)\n\n           hfx_ndim_allsta = hfx_ndim_allsta + 1\n           hfxobs_allsta(hfx_ndim_allsta) = hfx(ista, itime+1)\n           hfxmdl_allsta(hfx_ndim_allsta) = hrldas_hfx(ista,itime)\n\n        endif\n     enddo\n\n     frame_left   = 0.0\n     frame_right  = 0.5\n     frame_bottom = 0.5\n     frame_top    = 1.0\n     xl = frame_left\n     xr = frame_right\n     xb = frame_bottom\n     xt = frame_top\n     call set ( xl , xr , xb , xt , 0.0 , 1.0 , 0.0 , 1.0 , 1 )\n     call perim(0,0,0,0)\n     textsize = min(xr-xl,xt-xb)*0.015\n     call pchiqu(0.5, 0.95, \"HFX:  Station \"//textsta, textsize, 0.0, 0.0)\n     xl = frame_left   + (frame_right-frame_left  )*0.15\n     xr = frame_left   + (frame_right-frame_left  )*0.95\n     xb = frame_bottom + (frame_top  -frame_bottom)*0.10\n     xt = frame_bottom + (frame_top  -frame_bottom)*0.90\n     wl = xarray(1)\n     wr = xarray(station_hfx_count)\n     wb = -100.0\n     wt = 500.0\n     call set (xl, xr, xb, xt, wl, wr, wb, wt, 1)\n     call gasetc(\"XLF\", '(F5.0)')\n     call periml(0, 0, 0, 0)\n     call connect_the_dots(xarray,yarray,station_hfx_count,color=\"blue\")\n\n     narray = 0\n     ! HRLDAS hfx\n     nowdate = startdate\n     do while ( nowdate(1:13) < enddate(1:13) )\n        call geth_newdate(nowdate(1:13), nowdate(1:13), 1)\n        call geth_idts(nowdate(1:13), startdate(1:13), itime)\n        itime = (itime * 4) + 1\n        if (hrldas_hfx(ista,itime) > -1.E25) then\n           narray = narray + 1\n           xxxarray(narray) = float(itime)\n           yyyarray(narray) = hrldas_hfx(ista,itime)\n        endif\n     enddo\n\n     call connect_the_dots(xxxarray,yyyarray,narray,color=\"red\")\n\n     call flux_stats(yarray, zarray, station_hfx_count,     bias, rmse, correlation, lsra, lsrb)\n     call draw_scatter(\"Obs HFX\", \"HRLDAS HFX\", yarray, zarray, station_qfx_count, &\n          &            bias, rmse, correlation, lsra, lsrb, 0.5, 1.0, 0.5, 1.0)\n\n     station_hfxoavg = station_hfxoavg / float(station_hfxcount)\n     station_hfxmavg = station_hfxmavg / float(station_hfxcount)\n     station_hfxbias = station_hfxbias / float(station_hfxcount)\n     station_hfxrmse = sqrt(station_hfxrmse/float(station_hfxcount))\n\n     call gsplci(color_index(\"black\"))\n     frame_left   = 0.0\n     frame_right  = 0.5\n     frame_bottom = 0.0\n     frame_top    = 0.5\n     xl = frame_left\n     xr = frame_right\n     xb = frame_bottom\n     xt = frame_top\n     call set ( xl , xr , xb , xt , 0.0 , 1.0 , 0.0 , 1.0 , 1 )\n     call perim(0,0,0,0)\n\n     textsize = min(xr-xl,xt-xb)*0.015\n     call pchiqu(0.5, 0.95, \"HFX -- Average diurnal cycle: Station \"//textsta, textsize, 0.0, 0.0)\n\n     call pchiqu(0.18, 0.87, \"Obs:\", textsize, 0., -1.)\n     call pchiqu(0.18, 0.84, \"HRLDAS:\", textsize, 0., -1.)\n     call line_in_color(.3, .87, .40, .87, color_index(\"blue\"))\n     call line_in_color(.3, .84, .40, .84, color_index(\"red\"))\n\n     xl = frame_left   + (frame_right-frame_left  )*0.15\n     xr = frame_left   + (frame_right-frame_left  )*0.95\n     xb = frame_bottom + (frame_top  -frame_bottom)*0.10\n     xt = frame_bottom + (frame_top  -frame_bottom)*0.90\n     call set ( xl , xr , xb , xt , xarray_diurnal(0) , xarray_diurnal(24) , -100.0 , 500.0 , 1 )\n     call line_in_color(xarray_diurnal(0), 0.0, xarray_diurnal(24), 0.0, color_index(\"gray90\"))\n     call line_in_color(xarray_diurnal(0), 100.0, xarray_diurnal(24), 100.0, color_index(\"gray90\"))\n     call line_in_color(xarray_diurnal(0), 200.0, xarray_diurnal(24), 200.0, color_index(\"gray90\"))\n     call line_in_color(xarray_diurnal(0), 300.0, xarray_diurnal(24), 300.0, color_index(\"gray90\"))\n     call line_in_color(xarray_diurnal(0), 400.0, xarray_diurnal(24), 400.0, color_index(\"gray90\"))\n     call periml(24,0,6,0)\n\n     call connect_the_dots(xarray_diurnal, (/station_hfxoavg,station_hfxoavg(0)/), 25, color=\"blue\")\n     call connect_the_dots(xarray_diurnal, (/station_hfxmavg,station_hfxmavg(0)/), 25, color=\"red\")\n\n     call frame()\n\n     write(*,'(I2,2x,8F10.4)') ista, sqrt(station_hfx_rmse/float(station_hfx_count)), &\n          sqrt(station_qfx_rmse/float(station_qfx_count)), &\n          sqrt(station_qfxcorr_rmse/float(station_qfxcorr_count)), &\n          station_hfx_bias/float(station_hfx_count), &\n          station_qfx_bias/float(station_qfx_count), &\n          station_qfxcorr_bias/float(station_qfxcorr_count)\n\n  enddo STATIONLOOP\n\n  qfxoavg = qfxoavg / float(qfxcount)\n  qfxmavg = qfxmavg / float(qfxcount)\n  qfxbias = qfxbias / float(qfxcount)\n  qfxrmse = sqrt(qfxrmse/float(qfxcount))\n\n  qfxoavg_old = qfxoavg_old / float(qfxcount_old)\n  qfxmavg_old = qfxmavg_old / float(qfxcount_old)\n  qfxbias_old = qfxbias_old / float(qfxcount_old)\n  qfxrmse_old = sqrt(qfxrmse_old/float(qfxcount_old))\n\n  hfxoavg = hfxoavg / float(hfxcount)\n  hfxmavg = hfxmavg / float(hfxcount)\n  hfxbias = hfxbias / float(hfxcount)\n  hfxrmse = sqrt(hfxrmse/float(hfxcount))\n\n  ! Plot our average diurnal cycle.\n\n  call gsplci(color_index(\"black\"))\n  call set (0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.5*(.15+.9), 0.93, \"Observed QFX (solid), Corrected Observed QFX (dot), HRLDAS QFX (dash)\", 0.013, 0., 0.)\n  call set (.15, .9, .55, .9, 0., 24., -100., 500., 1)\n  call gasetc(\"XLF\", '(I2.2)')\n  call gasetc(\"YLF\", '(F5.0)')\n  call periml(8, 3, 6, 0)\n  call line_in_color(0., 0., 24., 0., color_index(\"gray90\"))\n\n  call gsln(1)\n  call connect_the_dots(xarray_diurnal, (/qfxoavg_old,qfxoavg_old(0)/), 25)\n\n  call gsln(3)\n  call connect_the_dots(xarray_diurnal, (/qfxoavg,qfxoavg(0)/), 25)\n\n  call gsln(2)\n  call connect_the_dots(xarray_diurnal, (/qfxmavg,qfxmavg(0)/), 25)\n  call gsln(1)\n\n  call set (0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.5*(.15+.9), 0.46, \"QFX bias w.r.t original obs (solid) and corrected obs (dot)\", 0.013, 0., 0.)\n  call pchiqu(0.5*(.15+.9), 0.42, \"QFX rmse w.r.t original obs (dash) and corrected obs (dot-dash)\", 0.013, 0., 0.)\n  call set (.15, .9, .05, .40, 0., 24., -100., 200., 1)\n  call gasetc(\"XLF\", '(I2.2)')\n  call gasetc(\"YLF\", '(F5.0)')\n\n  call line_in_color(0., -50., 24., -50., color_index(\"gray90\"))\n  call line_in_color(0., 0., 24., 0., color_index(\"blue2\"))\n  call line_in_color(0., 50., 24., 50., color_index(\"gray90\"))\n  call line_in_color(0., 100., 24., 100., color_index(\"gray90\"))\n  call line_in_color(0., 150., 24., 150., color_index(\"gray90\"))\n  call periml(8, 3, 6, 0)\n\n  call gsln(1)\n  call connect_the_dots(xarray_diurnal, (/qfxbias_old,qfxbias_old(0)/), 25)\n\n  call gsln(3)\n  call connect_the_dots(xarray_diurnal, (/qfxbias,qfxbias(0)/), 25)\n\n  call gsln(2)\n  call connect_the_dots(xarray_diurnal, (/qfxrmse_old,qfxrmse_old(0)/), 25)\n\n  call gsln(4)\n  call connect_the_dots(xarray_diurnal, (/qfxrmse,qfxrmse(0)/), 25)\n  call gsln(1)\n\n  call frame()\n\n  call set (0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.5*(.15+.9), 0.93, \"Observed HFX (solid) and HRLDAS HFX (dash)\", 0.013, 0., 0.)\n  call gasetc(\"XLF\", '(I2.2)')\n  call gasetc(\"YLF\", '(F5.0)')\n  call set (.15, .9, .55, .9, 0., 24., -100., 500., 1)\n  call periml(8, 3, 6, 0)\n\n  call line_in_color(0., 0., 24., 0., color_index(\"gray90\"))\n\n  call gsln(1)\n  call connect_the_dots(xarray_diurnal, (/hfxoavg,hfxoavg(0)/), 25)\n\n  call gsln(2)\n  call connect_the_dots(xarray_diurnal, (/hfxmavg,hfxmavg(0)/), 25)\n  call gsln(1)\n\n  call set (0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.5*(.15+.9), 0.43, \"HFX bias (solid) and RMSE (dash)\", 0.013, 0., 0.)\n  call gasetc(\"XLF\", '(I2.2)')\n  call gasetc(\"YLF\", '(F5.0)')\n  call set (.15, .9, .05, .4, 0., 24., -100., 200., 1)\n\n  call line_in_color(0., -50., 24., -50., color_index(\"gray90\"))\n  call line_in_color(0., 0., 24., 0., color_index(\"blue2\"))\n  call line_in_color(0.,  50., 24.,  50., color_index(\"gray90\"))\n  call line_in_color(0., 100., 24., 100., color_index(\"gray90\"))\n  call line_in_color(0., 150., 24., 150., color_index(\"gray90\"))\n\n  call periml(8, 3, 6, 0)\n\n\n  call gsln(1)\n  call connect_the_dots(xarray_diurnal, (/hfxbias, hfxbias(0)/), 25)\n\n  call gsln(2)\n  call connect_the_dots(xarray_diurnal, (/hfxrmse, hfxrmse(0)/), 25)\n  call gsln(1)\n  call frame()\n\n  ! Compute our statistics over all stations\n  call flux_stats(qfxcorrobs_allsta, qfxcorrmdl_allsta, qfxcorr_ndim_allsta, &\n       &          qfxcorr_bias_allsta, qfxcorr_rmse_allsta, qfxcorr_correlation_allsta, &\n       &          qfxcorr_lsra_allsta, qfxcorr_lsrb_allsta)\n\n  call draw_scatter(\"Obs QFX Corrected\", \"HRLDAS QFX\", qfxcorrobs_allsta, qfxcorrmdl_allsta, qfxcorr_ndim_allsta, &\n       &            qfxcorr_bias_allsta, qfxcorr_rmse_allsta, qfxcorr_correlation_allsta, qfxcorr_lsra_allsta, qfxcorr_lsrb_allsta,&\n       &            0.0, 1.0, 0.0, 1.0)\n\n  call frame()\n\n  call flux_stats(qfxobs_allsta, qfxmdl_allsta, qfx_ndim_allsta, qfx_bias_allsta, qfx_rmse_allsta, qfx_correlation_allsta, qfx_lsra_allsta, qfx_lsrb_allsta)\n  call draw_scatter(\"Obs QFX\", \"HRLDAS QFX\", qfxobs_allsta, qfxmdl_allsta, qfx_ndim_allsta, &\n       &            qfx_bias_allsta, qfx_rmse_allsta, qfx_correlation_allsta, qfx_lsra_allsta, qfx_lsrb_allsta, &\n       &            0.0, 1.0, 0.0, 1.0)\n  call frame()\n\n  call flux_stats(hfxobs_allsta, hfxmdl_allsta, hfx_ndim_allsta, hfx_bias_allsta, hfx_rmse_allsta, hfx_correlation_allsta, hfx_lsra_allsta, hfx_lsrb_allsta)\n  call draw_scatter(\"Obs HFX\", \"HRLDAS HFX\", hfxobs_allsta, hfxmdl_allsta, hfx_ndim_allsta, &\n       &            hfx_bias_allsta, hfx_rmse_allsta, hfx_correlation_allsta, hfx_lsra_allsta, hfx_lsrb_allsta, &\n       &            0.0, 1.0, 0.0, 1.0)\n  call frame()\n\n  call kwm_close_ncargks()\nend program fluxes_statistics\n\n!--------------------------------------------------------------------------------\n!--------------------------------------------------------------------------------\n\nsubroutine read_ihop(fluxobs_directory, &\n     startdate, ista, lat, lon, hdate, hfx, qfx_old, qfx_corrected, maxtim)\n  use kwm_date_utilities\n  use kwm_string_utilities\n  implicit none\n  character(len=*),                     intent(in)  :: fluxobs_directory\n  character(len=16),                    intent(in)  :: startdate\n  integer,                              intent(in)  :: ista\n  integer,                              intent(in)  :: maxtim\n  real,                                 intent(out) :: lat\n  real,                                 intent(out) :: lon\n  character(len=16), dimension(maxtim), intent(out) :: hdate\n  real,              dimension(maxtim), intent(out) :: hfx\n  real,              dimension(maxtim), intent(out) :: qfx_old\n  real,              dimension(maxtim), intent(out) :: qfx_corrected\n\n  character(len=256) :: flnm\n  integer, parameter :: iunit = 26\n  character(len=16) :: rddate\n\n  integer :: rdyyyy, rdmm, rddd, rdhhmmss\n  integer :: ierr, idum, itime\n  real :: rd_rlw, rd_rsw\n\n  real :: rt_T, rd_P, rd_MR, rd_SPD, rd_U, rd_V, rd_rainacc, rd_rainr\n  real :: rd_Rnet, rd_Rpar, rd_Tsfc, rd_LE, rd_H, rd_Gsfc, rd_LEc\n  integer :: indx\n  character(len=8) :: Hrd_LEc\n\n  character(len=256) :: string\n\n  if (ista < 10) then\n     write(flnm, fmt='(A,\"/IHOPUDS\",I1,\"r.txt\")') trim(fluxobs_directory), ista\n     ! write(flnm,'(\"/avn2/kmanning/STATS/IHOP_DATA/Sites/LE_corrected-fromSEB/&\n     ! &IHOPUDS\",I1,\"r.txt\")') ista\n  else if (ista == 10) then\n     write(flnm, fmt='(A,\"/IHOPUDCUS\",I2,\"r.txt\")') trim(fluxobs_directory), ista\n     ! write(flnm,'(\"/avn2/kmanning/STATS/IHOP_DATA/Sites/LE_corrected-fromSEB/&\n     ! &IHOPUDCUS10r.txt\")')\n  endif\n\n  open(iunit, file=trim(flnm), status='old', form='formatted', action='read', iostat=ierr)\n  if (ierr /= 0) then\n     write(*,'(\"***** ERROR EXIT *****\",/)')\n     write(*,'(3x, \"Problem opening flux observations file:\", /, 6x, A,/)') \"'\"//trim(flnm)//\"'\"\n     write(*,'(\"***** ERROR EXIT *****\")')\n     stop\n  endif\n\n  select case (ista)\n  case (1)\n     lat = 36.0 + 28.370/60.\n     lon = -(100.0 + 37.075/60.)\n  case (2)\n     lat = 36.0 + 37.327/60.\n     lon = -(100.0 + 37.619/60.)\n  case (3)\n     lat = 36.0 + 51.662/60.\n     lon = -(100.0 + 35.670/60.)\n  case (4)\n     lat = 37.0 + 21.474/60.\n     lon = -(98.0 + 14.679/60.)\n  case (5)\n     lat = 37.0 + 22.684/60.\n     lon = -(98.0 + 9.816/60.)\n  case (6)\n     lat = 37.0 + 21.269/60.\n     lon = -(97.0 + 39.200/60.)\n  case (7)\n     lat = 37.0 + 18.792/60.\n     lon = -(96.0 + 56.323/60.)\n  case (8)\n     lat = 37.0 + 24.418/60.\n     lon = -(96.0 + 45.937/60.)\n  case(9)\n     lat = 37.0 + 24.618/60.\n     lon = -(96.0 + 34.028/60.)\n  case (10)\n     ! From Joe Alfieri\n     lat =  36.8764333333\n     lon = -100.60890111\n  end select\n\n\n  ! Skip 4 header lines\n  read(iunit,'(///)')\n  READLOOP : do\n\n!\n! Fore some reason, I'm having a hard time reading this file with\n! the Intel compiler.  Mabye it's fixed in a later version.  For now,\n! stick with pgi.\n!\n! Anyway, the read into character string Hrd_LEc is done because some bad data\n! values in the file are encoded as the string \"NaN\".  Arrgh!\n!\n\n\n     if (ista == 10) then\n        read(iunit,*, iostat=ierr) idum, idum, idum, idum, idum, rdyyyy, &\n             rdmm, rddd, rdhhmmss, idum, idum, rd_rsw, rd_rlw, rt_T, rd_P, rd_MR, &\n             rd_SPD, rd_U, rd_V, rd_rainacc, rd_rainr, rd_Rnet, rd_Rpar, &\n             rd_Tsfc, rd_LE, Hrd_LEc, rd_H, rd_Gsfc\n     else\n        read(iunit,*, iostat=ierr) idum, idum, idum, idum, idum, rdyyyy, &\n              rdmm, rddd, rdhhmmss, idum, rd_rsw, rd_rlw, rt_T, rd_P, rd_MR, &\n              rd_SPD, rd_U, rd_V, rd_rainacc, rd_rainr, rd_Rnet, rd_Rpar, &\n              rd_Tsfc, rd_LE, Hrd_LEc, rd_H, rd_Gsfc\n     endif\n     if (ierr == -1) then\n        print*, 'Hit end of file.'\n        exit\n     endif\n     if (ierr /= 0) then\n        print*, 'Hit read error.', ierr\n        stop\n     endif\n     write(rddate, '(I4.4,2(\"-\",I2.2),\"_\",I2.2,\":\",I2.2)') rdyyyy, rdmm, rddd, &\n          rdhhmmss/10000, mod(rdhhmmss/100, 100)\n     print '(I2, 2x, A, 3F20.10)', ista, rddate, rd_H, rd_le, rd_lec\n     if (rddate(1:16) >= startdate(1:16)) then\n        call geth_idts(rddate(1:16), startdate(1:16), itime)\n        print*, 'rddate, startdate = ', rddate, '  ', startdate\n        itime = (itime / 15) + 1\n        if (itime > maxtim) stop \"Increase maxtim.\"\n!     if (rd_rlw < 9998) lw(itime) = rd_rlw\n!     if (rd_rsw < 9998) sw(itime) = rd_rsw\n\n        if (rd_H < 9998) HFX(itime) = rd_H\n        if (rd_LE < 9998) QFX_OLD(itime) = rd_LE\n        if (Hrd_LEc(1:3) /= \"NaN\") then\n           read(Hrd_LEc, '(F7.0)', iostat=ierr) rd_lec\n           if (ierr == 0) then\n              if (rd_LEc < 9998) QFX_CORRECTED(itime) = rd_LEc\n           else\n              stop \"Problem converting rd_LEc\"\n           endif\n        endif\n\n        hdate(itime) = rddate\n!KWM     print*, rdyyyy, rdmm, rddd, rdhhmmss, hdate(icount)\n     endif\n  enddo READLOOP\n  close(iunit)\n  print*, 'finish routine read_ihop.'\n\nend subroutine read_ihop\n\n!--------------------------------------------------------------------------------\n!--------------------------------------------------------------------------------\n\nsubroutine read_namelist(fluxobs_directory, ldasout_directory)\n  implicit none\n  character(len=256), intent(out) :: fluxobs_directory\n  character(len=256), intent(out) :: ldasout_directory\n  namelist/fluxstats/ fluxobs_directory, ldasout_directory\n\n  integer :: ierr\n\n  open(11, file=\"namelist.fluxstats\", status='old', form='formatted', action='read', iostat=ierr)\n  if (ierr /= 0) then\n     write(*,'(\"***** ERROR EXIT *****\",/)')\n     write(*,'(3x, \"Problem opening namelist file:\", /, 6x, A,/)') \"'\"//\"namelist.fluxstats\"//\"'\"\n     write(*,'(\"***** ERROR EXIT *****\")')\n     stop\n  endif\n\n  read(11, nml=fluxstats, iostat=ierr)\n  if (ierr /= 0) then\n     write(*,'(\"***** ERROR EXIT *****\",/)')\n     write(*,'(3x, \"Problem reading namelist file:\", /, 6x, A,/)') \"'\"//\"namelist.fluxstats\"//\"'\"\n     write(*,'(\"***** ERROR EXIT *****\")')\n     stop\n  endif\n\n  close(11)\n\n  print*, 'fluxobs_directory = \"'//trim(fluxobs_directory)//'\"'\n\nend subroutine read_namelist\n\n!--------------------------------------------------------------------------------\n!--------------------------------------------------------------------------------\n\nsubroutine draw_scatter(abbr1, abbr2, obs, mdl, ndim, bias, rmse, correlation, lsra, lsrb, &\n     & frame_left, frame_right, frame_bottom, frame_top)\n  use kwm_plot_utilities, only: line_in_color, find_good_range, color_index\n  implicit none\n  character(len=*),      intent(in)  :: abbr1\n  character(len=*),      intent(in)  :: abbr2\n  integer,               intent(in)  :: ndim\n  real, dimension(ndim), intent(in)  :: obs\n  real, dimension(ndim), intent(in)  :: mdl\n  real,                  intent(in)  :: bias\n  real,                  intent(in)  :: rmse\n  real,                  intent(in)  :: correlation\n  real,                  intent(in)  :: lsra\n  real,                  intent(in)  :: lsrb\n  real,                  intent(in)  :: frame_left\n  real,                  intent(in)  :: frame_right\n  real,                  intent(in)  :: frame_bottom\n  real,                  intent(in)  :: frame_top\n\n  real    :: hold_xl\n  real    :: hold_xr\n  real    :: hold_xb\n  real    :: hold_xt\n  real    :: hold_wl\n  real    :: hold_wr\n  real    :: hold_wb\n  real    :: hold_wt\n  integer :: hold_ml\n  real    :: hold_xls\n  real    :: hold_yls\n  real    :: hold_xlo\n  real    :: hold_ylo\n  real    :: hold_xmj\n  real    :: hold_ymj\n  real    :: hold_xmn\n  real    :: hold_ymn\n  character(len=80) :: hold_xlf\n  character(len=80) :: hold_ylf\n\n  real :: xl\n  real :: xr\n  real :: xb\n  real :: xt\n\n  character(len=256) :: text\n  real    :: minrange, maxrange\n  integer :: expn, irange\n  integer :: n\n  integer :: iblue\n  integer :: ired\n  integer :: iblack\n\n  real    :: text_scale1\n  real    :: text_scale2\n\n  call getset(hold_xl, hold_xr, hold_xb, hold_xt, hold_wl, hold_wr, hold_wb, hold_wt, hold_ml)\n  call gagetc(\"XLF\", hold_xlf)\n  call gagetc(\"YLF\", hold_ylf)\n  call gagetr(\"XLS\", hold_xls)\n  call gagetr(\"YLS\", hold_yls)\n  call gagetr(\"XLO\", hold_xlo)\n  call gagetr(\"YLO\", hold_ylo)\n  call gagetr(\"XMJ\", hold_xmj)\n  call gagetr(\"YMJ\", hold_ymj)\n  call gagetr(\"XMN\", hold_xmn)\n  call gagetr(\"YMN\", hold_ymn)\n\n\n  iblue  = color_index(\"blue\")\n  ired   = color_index(\"red\")\n  iblack = color_index(\"black\")\n\n  xl = frame_left\n  xr = frame_right\n  xb = frame_bottom\n  xt = frame_top\n\n  text_scale1 = 0.014 * min((xr-xl),(xt-xb))\n  text_scale2 = 0.012 * min((xr-xl),(xt-xb))\n\n  call set(xl, xr, xb, xt, 0., 1., 0., 1., 1)\n  call perim(0,0,0,0)\n\n  write(text, '(A,\" / \",A, \":  Scatter Plot\")') abbr1, abbr2\n  call pchiqu(.55, .95, trim(text), text_scale1, 0.0, 0.0)\n\n  write(text, '(A, \" ( W m~S2~-2   )\")') abbr1\n  call pchiqu(.55, .05, trim(text), text_scale1, 0.0, 0.0)\n\n  write(text, '(A, \" ( W m~S2~-2   )\")') abbr2\n  call pchiqu(.06, .5, trim(text), text_scale1, 90.0, 0.0)\n\n  write(text,'(\"Bias:  \", F10.4)') bias\n  call pchiqu(0.17, 0.876, trim(text), text_scale2, 0.0, -1.0)\n\n  write(text,'(\"RMSE:  \", F10.4)') rmse\n  call pchiqu(0.17, 0.846, trim(text), text_scale2, 0.0, -1.0)\n\n  write(text,'(\"Corr:  \", F10.4)') correlation\n  call pchiqu(0.17, 0.816, trim(text), text_scale2, 0.0, -1.0)\n\n  minrange = min(minval(mdl,mask=(mdl>-1.E25)), minval(obs,mask=(obs>-1.E25)))\n  maxrange = max(maxval(mdl,mask=(mdl>-1.E25)), maxval(obs,mask=(obs>-1.E25)))\n  call find_good_range(minrange, maxrange, expn, irange)\n\n  xl = frame_left   + (frame_right-frame_left  )*0.15\n  xr = frame_left   + (frame_right-frame_left  )*0.95\n  xb = frame_bottom + (frame_top  -frame_bottom)*0.10\n  xt = frame_bottom + (frame_top  -frame_bottom)*0.90\n\n  call set(xl, xr, xb, xt, minrange, maxrange, minrange, maxrange, 1)\n  call line_in_color(minrange, minrange, maxrange, maxrange, iblack)\n\n  call line_in_color(minrange, lsra+lsrb*minrange, maxrange, lsra+lsrb*maxrange, ired)\n\n  do n = 1, ndim\n     if ( (obs(n) > -1.E25) .and. (mdl(n) > -1.E25) ) then\n        call ngdots(obs(n), mdl(n), 1, (maxrange-minrange)*0.005, iblue)\n     endif\n  enddo\n  call gasetc(\"XLF\", \"(F5.0)\")\n  call gasetc(\"YLF\", \"(F5.0)\")\n  call gasetr(\"XLS\", 0.015  * min(xr-xl,xt-xb))\n  call gasetr(\"YLS\", 0.015  * min(xr-xl,xt-xb))\n  call gasetr(\"XLO\", 0.008 * min(xr-xl,xt-xb))\n  call gasetr(\"YLO\", 0.008 * min(xr-xl,xt-xb))\n  call gasetr(\"XMJ\", 0.014 * min(xr-xl,xt-xb))\n  call gasetr(\"YMJ\", 0.014 * min(xr-xl,xt-xb))\n  call gasetr(\"XMN\", 0.007 * min(xr-xl,xt-xb))\n  call gasetr(\"YMN\", 0.007 * min(xr-xl,xt-xb))\n  call periml(irange,2,irange,2)\n\n  ! Restore original condition\n  call gasetc(\"XLF\", trim(hold_xlf))\n  call gasetc(\"YLF\", trim(hold_ylf))\n  call gasetr(\"XLS\", hold_xls)\n  call gasetr(\"YLS\", hold_yls)\n  call gasetr(\"XLO\", hold_xlo)\n  call gasetr(\"YLO\", hold_ylo)\n  call gasetr(\"XMJ\", hold_xmj)\n  call gasetr(\"YMJ\", hold_ymj)\n  call gasetr(\"XMN\", hold_xmn)\n  call gasetr(\"YMN\", hold_ymn)\n  call set(hold_xl, hold_xr, hold_xb, hold_xt, hold_wl, hold_wr, hold_wb, hold_wt, hold_ml)\nend subroutine draw_scatter\n\n!--------------------------------------------------------------------------------\n!--------------------------------------------------------------------------------\n\nsubroutine flux_stats(obs, mdl, ndim, bias, rmse, correlation, lsra, lsrb)\n  implicit none\n  integer, intent(in) :: ndim\n  real, dimension(ndim), intent(in)  :: obs\n  real, dimension(ndim), intent(in)  :: mdl\n  real,                  intent(out) :: bias\n  real,                  intent(out) :: rmse\n  real,                  intent(out) :: correlation\n  real,                  intent(out) :: lsra\n  real,                  intent(out) :: lsrb\n\n  integer :: n\n  integer :: ndat\n\n  real (kind=8) :: sumx, sumy, sumxx, sumxy, sumyy, sxx, sxy, syy\n\n  bias = 0.0\n  rmse = 0.0\n  ndat = 0.0\n  sumx   = 0.0\n  sumy   = 0.0\n  sumxx  = 0.0\n  sumxy  = 0.0\n  sumyy  = 0.0\n\n  do n = 1, ndim\n     if (( obs(n) > -1.E25 ) .and. ( mdl(n) > -1.E25 )) then\n        bias  = bias + (mdl(n)-obs(n))\n        rmse  = rmse + (mdl(n)-obs(n))*(mdl(n)-obs(n))\n        sumx  = sumx + obs(n)\n        sumy  = sumy + mdl(n)\n        sumxx = sumxx  + ( obs(n)*obs(n) )\n        sumyy = sumyy  + ( mdl(n)*mdl(n) )\n        sumxy = sumxy  + ( obs(n)*mdl(n) )\n        ndat = ndat + 1\n     endif\n  enddo\n\n  bias = bias / real(ndat)\n  rmse = sqrt ( rmse / real(ndat) )\n\n  sxx = sumxx - sumx*sumx/real(ndat)\n  syy = sumyy - sumy*sumy/real(ndat)\n  sxy = sumxy - sumx*sumy/real(ndat)\n\n  correlation = sxy/sqrt(sxx*syy)\n\n  lsrb = ( (ndat*sumxy) - (sumx*sumy) ) / ( (ndat*sumxx) - (sumx*sumx) )\n  lsra = ( sumy - (lsrb*sumx) ) / real(ndat)\n\nend subroutine flux_stats\n\n!--------------------------------------------------------------------------------\n!--------------------------------------------------------------------------------\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/get_unused_unit.F",
    "content": "integer function get_unused_unit() result(iunit)\n  implicit none\n  integer :: i\n  logical :: used\n\n  do i = 11, 255\n     inquire(unit=i, opened=used)\n     if (.not. used) then\n        iunit = i\n        return\n     endif\n  enddo\n\n  print*, \"GET_UNUSED_UNIT:  \"\n  print*, \"      Problem getting unused unit number.\"\n  call abort()\n\nend function get_unused_unit\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/kwm_date_utilities.F",
    "content": "module kwm_date_utilities\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n!  From old date ('YYYY-MM-DD HH:MM:SS.ffff') and\n!  delta-time, compute the new date.\n\n!  on entry     -  odate  -  the old hdate.\n!                  idt    -  the change in time\n\n!  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n\n!  Local Variables\n\n!  yrold    -  indicates the year associated with \"odate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scold    -  indicates the second associated with \"odate\"\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n\n!  mday     -  a list assigning the number of days in each month\n\n!  i        -  loop counter\n!  nday     -  the integer number of days represented by \"idt\"\n!  nhour    -  the integer number of hours in \"idt\" after taking out\n!              all the whole days\n!  nmin     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days and whole hours.\n!  nsec     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days, whole hours, and whole minutes.\n\n    integer :: nlen, olen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n\n    logical :: punctuated\n    logical :: idtdy, idthr, idtmin, idtsec, idtfrac\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n!  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    olen = len(odate)\n    if (punctuated) then\n       if (olen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n    endif\n\n!  Use internal READ statements to convert the CHARACTER string\n!  date into INTEGER components.\n\n    idtdy   = .FALSE.\n    idthr   = .FALSE.\n    idtmin  = .FALSE.\n    idtsec  = .FALSE.\n    idtfrac = .FALSE.\n    read(odate(1:4),  '(i4)') yrold\n    if (punctuated) then\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.13) then\n          idthr = .TRUE.\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             idtmin = .TRUE.\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                idtsec = .TRUE.\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   idtfrac = .TRUE.\n                   read(odate(21:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    else ! Not punctuated\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.10) then\n          idthr = .TRUE.\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             idtmin = .TRUE.\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                idtsec = .TRUE.\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   idtfrac = .TRUE.\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n!  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n!  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n!  Check that the fractional part  of ODATE makes sense.\n\n!KWM      IF ((scold.GT.59).or.(scold.LT.0)) THEN\n!KWM         WRITE(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n!KWM         opass = .FALSE.\n!KWM      END IF\n\n    if (.not.opass) then\n       write(*,*) 'Crazy ODATE: ', odate(1:olen), olen\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n\n!  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (idtfrac) then !idt should be in fractions of seconds\n       if (punctuated) then\n          ifrc = olen-14\n       else\n          ifrc = olen-20\n       endif\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (idtsec) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (idtmin) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (idthr) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (idtdy) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            olen\n       write(*,*) odate(1:olen)\n       call abort()\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n!  Now construct the new mdate\n\n    nlen = LEN(ndate)\n\n    if (punctuated) then\n\n       if (nlen.gt.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:19)//'.'//hfrc(31-nlen:10)\n\n       else if (nlen.eq.19.or.nlen.eq.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n          if (nlen.eq.20) ndate = ndate(1:19)//'.'\n\n       else if (nlen.eq.16) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (nlen.eq.13) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n       if (olen.ge.11) ndate(11:11) = sp\n\n    else\n\n       if (nlen.gt.20) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:18)//hfrc(31-nlen:10)\n\n       else if (nlen.eq.14) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n14        format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.12) then\n          write(ndate,12) yrnew, monew, dynew, hrnew, minew\n12        format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,210) yrnew, monew, dynew, hrnew\n210       format(i4,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.8) then\n          write(ndate,8) yrnew, monew, dynew\n8         format(i4,i2.2,i2.2)\n\n       else\n          stop \"DATELEN PROBLEM\"\n       end if\n    endif\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n    implicit none\n\n!  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n!  compute the time difference.\n\n!  on entry     -  newdate  -  the new hdate.\n!                  olddate  -  the old hdate.\n\n!  on exit      -  idt    -  the change in time.\n!                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n!  Local Variables\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  yrold    -  indicates the year associated with \"odate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n!  scold    -  indicates the second associated with \"odate\"\n!  i        -  loop counter\n!  mday     -  a list assigning the number of days in each month\n\n! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    character (len=24) :: tdate\n    integer :: olen, nlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), i, newdys, olddys\n    logical :: npass, opass\n    integer :: isign\n    integer :: ifrc\n\n    logical :: punctuated\n\n    olen = len(olddate)\n    nlen = len(newdate)\n    if (nlen.ne.olen) then\n       write(*,'(\"GETH_IDTS: NLEN /= OLEN: \", A, 3x, A)') newdate(1:nlen), olddate(1:olen)\n       call abort\n    endif\n\n    if (olddate.gt.newdate) then\n       isign = -1\n\n       ifrc = olen\n       olen = nlen\n       nlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       isign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n\n!  Break down old and new hdates into parts\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(odate(1:4),  '(i4)') yrold\n    read(ndate(1:4),  '(i4)') yrnew\n\n    if (punctuated) then\n\n!  Break down old hdate into parts\n\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       if (olen.ge.13) then\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   if (olen.eq.21) then\n                      read(odate(21:21),'(i1)') frold\n                   else if (olen.eq.22) then\n                      read(odate(21:22),'(i2)') frold\n                   else if (olen.eq.23) then\n                      read(odate(21:23),'(i3)') frold\n                   else if (olen.eq.24) then\n                      read(odate(21:24),'(i4)') frold\n                   endif\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(6:7),  '(i2)') monew\n       read(ndate(9:10), '(i2)') dynew\n       if (nlen.ge.13) then\n          read(ndate(12:13),'(i2)') hrnew\n          if (nlen.ge.16) then\n             read(ndate(15:16),'(i2)') minew\n             if (nlen.ge.19) then\n                read(ndate(18:19),'(i2)') scnew\n                if (nlen.gt.20) then\n                   read(ndate(21:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    else\n\n!  Break down old hdate into parts\n\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       if (olen.ge.10) then\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(5:6),  '(i2)') monew\n       read(ndate(7:8), '(i2)') dynew\n       if (nlen.ge.10) then\n          read(ndate(9:10),'(i2)') hrnew\n          if (nlen.ge.12) then\n             read(ndate(11:12),'(i2)') minew\n             if (nlen.ge.14) then\n                read(ndate(13:14),'(i2)') scnew\n                if (nlen.ge.15) then\n                   read(ndate(15:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n!  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n       print*, 'GETH_IDTS:  Month of NDATE = ', monew\n       npass = .false.\n    end if\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n       opass = .false.\n    end if\n\n!  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    endif\n\n!  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    end if\n\n!  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n       npass = .false.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n       opass = .false.\n    end if\n\n!  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n       npass = .false.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n       opass = .false.\n    end if\n\n!  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n       npass = .false.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'Screwy NDATE: ', ndate(1:nlen)\n       call abort()\n    end if\n\n    if (.not. opass) then\n       print*, 'Screwy ODATE: ', odate(1:olen)\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n!  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n!  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n!  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (punctuated) then\n       if (olen.gt.10) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.13) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.16) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.20) then\n                   ifrc = olen-20\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    else\n       if (olen.gt.8) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.10) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.12) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.14) then\n                   ifrc = olen-14\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    endif\n\n    if (isign .eq. -1) then\n       idt = idt * isign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n!\n! Compute the number of days in February for the given year.\n!\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n!\n! Compute the number of days in the month of given date hdate.\n!\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    if (hdate(5:5) == \"-\") then\n       read(hdate(1:7), '(I4,1x,I2)') year, month\n    else\n       read(hdate(1:6), '(I4,I2)') year, month\n    endif\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\nend module kwm_date_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/kwm_grid_utilities.F",
    "content": "module kwm_grid_utilities\n  private :: oned\ncontains\n\n  real function bint(array, ix, jx, x, y) result(val)\n    implicit none\n!\n!  Overlapping parabolic interpolation of array to point x, y.\n!\n    integer, intent(in)                   :: ix, jx\n    real   , intent(in), dimension(ix,jx) :: array\n    real   , intent(in)                   :: x, y\n\n    real, dimension(4,4) :: STL\n    integer :: I, J, K, KK, L, LL\n    real    :: XX, YY, A, B, C, D, E, F, G, H\n\n    if ((X < 2) .or. (Y < 2) .or. (X > IX-1) .or. (Y > JX-1)) then\n       val = -1.E33\n       return\n    endif\n\n    I = int(X)\n    J = int(Y)\n    XX = X-I\n    YY = Y-J\n!    IF(ABS(XX) <= 0.0001 .and. ABS(YY) <= 0.0001) THEN\n!       val = array(i,j)\n!       RETURN\n!    ENDIF\n\n    STL = ARRAY( I-1:I+2 , J-1:J+2 )\n\n    A = ONED(XX,STL(1,1),STL(2,1),STL(3,1),STL(4,1))\n    B = ONED(XX,STL(1,2),STL(2,2),STL(3,2),STL(4,2))\n    C = ONED(XX,STL(1,3),STL(2,3),STL(3,3),STL(4,3))\n    D = ONED(XX,STL(1,4),STL(2,4),STL(3,4),STL(4,4))\n    val = ONED(YY,A,B,C,D)\n\n  end function bint\n\n  real function bint_p(array, ix, jx, x, y) result(val)\n    implicit none\n!\n!  Overlapping parabolic interpolation of array to point x, y.\n!\n    integer, intent(in)                            :: ix, jx\n    real   , pointer, dimension(:,:)               :: array\n    real   , intent(in)                            :: x, y\n\n    real, dimension(4,4) :: STL\n    integer :: I, J, K, KK, L, LL\n    real    :: XX, YY, A, B, C, D, E, F, G, H\n\n    if ((X < 2) .or. (Y < 2) .or. (X > IX-1) .or. (Y > JX-1)) then\n       val = -1.E33\n       return\n    endif\n\n    I = int(X)\n    J = int(Y)\n    XX = X-I\n    YY = Y-J\n!    IF(ABS(XX) <= 0.0001 .and. ABS(YY) <= 0.0001) THEN\n!       val = array(i,j)\n!       RETURN\n!    ENDIF\n\n    STL = ARRAY( I-1:I+2 , J-1:J+2 )\n\n    A = ONED(XX,STL(1,1),STL(2,1),STL(3,1),STL(4,1))\n    B = ONED(XX,STL(1,2),STL(2,2),STL(3,2),STL(4,2))\n    C = ONED(XX,STL(1,3),STL(2,3),STL(3,3),STL(4,3))\n    D = ONED(XX,STL(1,4),STL(2,4),STL(3,4),STL(4,4))\n    val = ONED(YY,A,B,C,D)\n\n  end function bint_p\n\n  REAL FUNCTION ONED(X,A,B,C,D) result(val)\n    implicit none\n    real, intent(in) :: X, A, B, C, D\n    IF (abs(X) < 1.E-5) then\n       val = B\n    else if (abs(X-1.) < 1.E-5) then\n       val = C\n    else\n       val = (1.0-X)*(B+X*(0.5*(C-A)+X*(0.5*(C+A)-B)))+X*(C+(1.0-X)*(0.5 &\n            *(B-D)+(1.0-X)*(0.5*(B+D)-C)))\n    endif\n  END FUNCTION ONED\n\n  real function four_point(array, ix, jx, x, y) result(val)\n\n!*****************************************************************************!\n! Performs a 4-point interpolation to a given (x,y) coordinate in an array.   !\n! The X coordinate corresponds to the first dimension of array ARRAY.         !\n! The Y coordinate corresponds to the second dimension of array ARRAY.        !\n! For points outside the domain, the return value is -1.E33.                  !\n!*****************************************************************************!\n\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, intent(in), dimension(ix,jx) :: array\n    real, intent(in) :: x, y\n\n    integer :: i, j, ip, jp\n    real :: dx, dy, rx, ry\n\n    if (((x-ix)>1.E-4) .or. ((y-jx)>1.E-4) .or. (x < 0.99999) .or. (y < 0.99999)) then\n       if((x-ix)>1.E-5)  print*, 'x, ix = ', x, ix, ((x-ix)>1.E-5), (x-ix)\n       if ( y < 0.99999) print*, 'y = ', y\n       val = -1.E33\n    else\n       i = int(x+1.E-5)\n       j = int(y+1.E-5)\n\n       ! The following MAX test should be safe, since we've already checked\n       ! that we're not too much less than 1.0\n       i = max(i, 1)\n       j = max(j, 1)\n\n       dx = x-i\n       dy = y-j\n       if (dx < 1.E-4) dx = 0.0\n       if (dx > 0.9999) dx = 1.0\n       if (dy < 1.E-4) dy = 0.0\n       if (dy > 0.9999) dy = 1.0\n       rx = 1.0 - dx\n       ry = 1.0 - dy\n\n       ! The following MIN test should be safe, since we've already\n       ip = min(i+1, ix)\n       jp = min(j+1, jx)\n\n!KWM       print*, 'ip, jp = ', ip, jp\n!KWM       print*, 'i, j = ', i, j\n!KWM       print*, 'rx, ry, dx, dy = ', rx, ry, dx, dy\n\n       val= array(i ,j )*RY*RX + &\n            array(ip,j )*RY*DX + &\n            array(i ,jp)*DY*RX + &\n            array(ip,jp)*DY*DX\n    endif\n\n  end function four_point\n\n\n\n  real function four_point_p(array, ix, jx, x, y) result(val)\n\n!*****************************************************************************!\n! Performs a 4-point interpolation to a given (x,y) coordinate in an array.   !\n! The X coordinate corresponds to the first dimension of array ARRAY.         !\n! The Y coordinate corresponds to the second dimension of array ARRAY.        !\n! For points outside the domain, the return value is -1.E33.                  !\n!*****************************************************************************!\n\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, pointer, dimension(:,:) :: array\n    real, intent(in) :: x, y\n\n    integer :: i, j\n    real :: dx, dy, rx, ry\n\n    if ((x > ix) .or. (y > jx) .or. (x < 1) .or. (y < 1)) then\n       val = -1.E33\n    else\n       i = int(x)\n       j = int(y)\n       dx = x-i\n       dy = y-j\n       rx = 1.0 - dx\n       ry = 1.0 - dy\n\n       val= array(i  ,j  )*RY*RX + &\n            array(i+1,j  )*RY*DX + &\n            array(i  ,j+1)*DY*RX + &\n            array(i+1,j+1)*DY*DX\n    endif\n\n  end function four_point_p\n\n\n  subroutine smdsm(FLD, ix, jx, npass)\n\n!*****************************************************************************!\n!                                                                             !\n!  Purpose: Smooth the 2-d field FLD with the 2-pass smoother/desmoother      !\n!           Watch it.  All values of FLD are assumed to be valid, that is,    !\n!           no stagger is assumed.                                            !\n!                                                                             !\n!   On Entry:  FLD(IX,JX):  2-d field to be smoothed.                         !\n!              IX, JX    :  Dimensions of 2-d field FLD.                      !\n!              NPASS     :  Optional number of passes of the two-pass smoother!\n!                           (default 1 pass of the two-pass smoother)         !\n!                                                                             !\n!   On Exit:   FLD(IX,JX):  The smoothed 2-d field.                           !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n    INTEGER, intent(in) :: IX, JX\n    REAL, intent(inout), dimension(ix,jx) :: FLD\n    integer, intent(in), optional :: npass\n\n!  XNU(N) : Smoothing coefficient for pass N\n    REAL, parameter, dimension(2) :: XNU = (/ 0.50, -0.52 /)\n    INTEGER :: I, J, N, NP, IND\n    REAL :: ASV, APLUS, CELL\n\n    if (present(npass)) then\n       np = npass\n    else\n       np = 1\n    endif\n\n    NUMPASS : do n = 1, np\n\n       DO IND = 1, 2\n\n!...  FIRST, SMOOTH IN THE IX DIRECTION\n          DO I = 2,IX-1\n             ASV = FLD(I,1)\n             DO J = 2,JX-1\n                APLUS = FLD(I,J+1)\n                CELL = FLD(I,J)\n                FLD(I,J) = FLD(I,J) + XNU(IND)*((ASV + APLUS)/2.0 - FLD(I,J))\n                ASV = CELL\n             ENDDO\n          ENDDO\n\n!...  NOW, SMOOTH IN THE JX DIRECTION\n          DO J = 2,JX-1\n             ASV = FLD(1,J)\n             DO I = 2,IX-1\n                APLUS = FLD(I+1,J)\n                CELL = FLD(I,J)\n                FLD(I,J) = FLD(I,J) + XNU(IND)*((ASV + APLUS)/2.0 - FLD(I,J))\n                ASV = CELL\n             ENDDO\n          ENDDO\n\n       ENDDO\n\n    enddo NUMPASS\n\n  END subroutine smdsm\n\n\n  subroutine smt121(FLD, ix, jx, npass)\n\n!*****************************************************************************!\n!                                                                             !\n!   Purpose :  Performs 1-2-1 smoothing on a 2-d field FLD.                   !\n!              Watch it.  All values of FLD are assumed to be valid, that is, !\n!              no stagger is assumed.                                         !\n!                                                                             !\n!   On entry : FLD(IX,JX): 2-D field to be smoothed.                          !\n!                   IX,JX: The dimensions of the field FLD.                   !\n!                   NPASS: Optional number of passes (default 1).             !\n!                                                                             !\n!   On exit :  FLD(IX,JX): The smoothed field.                                !\n!                                                                             !\n!   The final value at any particular grid point is a weighted sum            !\n!   of that grid point and the eight immediately surrounding points           !\n!   thus:                                                                     !\n!                        1 2 1                                                !\n!                        2 4 2                                                !\n!                        1 2 1                                                !\n!                                                                             !\n!   At edges, we weight thus:                                                 !\n!                        -----                                                !\n!                        2 4 2                                                !\n!                        1 2 1                                                !\n!                                                                             !\n!   At corners, we weight thus:                                               !\n!                        +---                                                 !\n!                        |4 2                                                 !\n!                        |2 1                                                 !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n    integer, intent(in) :: ix, jx\n    REAL, intent(inout), dimension(ix,jx) :: FLD\n    integer, intent(in), optional :: npass\n\n    integer :: i, j, n, np\n    real :: cell, aplus, asv\n\n    if (present(npass)) then\n       np = npass\n    else\n       np = 1\n    endif\n\n\n    NUMPASS : do n = 1, np\n\n       DO I = 1, IX\n          ASV = FLD(I,1)\n          FLD(I,1) = (2.*FLD(I,1) + FLD(I,2))/3.\n          DO J = 2, JX-1\n             APLUS = FLD(I,J+1)\n             CELL = FLD(I,J)\n             FLD(I,J) = 0.5*FLD(I,J) + 0.25*(ASV+APLUS)\n             ASV = CELL\n          ENDDO\n          FLD(I,JX) = (2.*FLD(I,JX) + ASV)/3.\n       ENDDO\n\n       DO J=1,JX\n          ASV = FLD(1,J)\n          FLD(1,J) = (2.*FLD(1,J) + FLD(2,J))/3.\n          DO I=2,IX-1\n             APLUS = FLD(I+1,J)\n             CELL = FLD(I,J)\n             FLD(I,J) = 0.5*FLD(I,J) + 0.25*(ASV+APLUS)\n             ASV = CELL\n          ENDDO\n          FLD(IX,J) = (2.*FLD(IX,J) + ASV)/3.\n       ENDDO\n\n    enddo NUMPASS\n\n  END subroutine smt121\n\n  subroutine gaussian_filter(fld, filt, ix, jx, dxkm, half_width)\n!\n! Implementation of a gaussian filter.\n!\n! Purpose:  Return a smoothed version of array FLD in array FILT.\n!\n    implicit none\n    integer, intent(in) :: ix, jx ! Dimensions of input/output arrays\n    real, intent(in), dimension(ix,jx) :: fld  ! Input array to be filtered.\n    real, intent(out),dimension(ix,jx) :: filt ! Output filtered array.\n    real, intent(in) :: dxkm       ! Grid spacing in km\n    real, intent(in) :: half_width ! Half_Width in km\n\n    real,    parameter :: pi = 3.14159265358979\n    real,    parameter :: twopi = 2.*pi\n\n    integer :: i, j, ii, jj, iii, jjj\n    real :: x, y\n    real :: sigma, sigsq\n    integer :: fsz, hsz\n    real :: cval, eval\n    real, dimension(ix,jx) :: tmp\n    real, allocatable, dimension(:) :: v\n    real, allocatable, dimension(:,:) :: k\n\n    sigma =  (half_width/dxkm)\n    sigsq = sigma*sigma\n    fsz = (nint(8*sigma)*2)-1\n    hsz = (fsz+1)/2\n    allocate(k(fsz,fsz))\n    allocate(v(fsz))\n\n    filt = 0.\n    tmp = 0.\n\n! Compute the kernel\n\n! I'd rather do it in one step, going directly to my vector v,\n! but I don't see how to be able to do that cleanly and still\n! correct for the error (how much the sum differs from 1.0).\n\n! First I compute the two-dimensional kernel array.\n    cval = 1./(twopi*sigsq)\n    do i = 1, fsz\n       x = float(hsz-i)\n       do j = 1, fsz\n          y = float(hsz-j)\n          eval = -((x*x)+(y*y))/(2.*sigsq)\n          k(i,j) = exp(eval)\n       enddo\n    enddo\n    k = k*cval\n! Sum to see how far off of one we are, and divide k/sum\n! to correct for that error (i.e., we want to sum to 1.0)\n    k = k/sum(k)\n\n! Now figure my vector from the corrected kernel array.\n    v = k(1,:) / sqrt(k(1,1))\n\n! Apply the kernel\n\n    do j = 1, jx\n       do i = 1, ix\n          do ii = 1, fsz\n             iii = (i-hsz)+ii\n             if (iii < 1) iii = 1\n             if (iii > ix) iii = ix\n             tmp(i,j) = tmp(i,j) + v(ii)*fld(iii,j)\n          enddo\n       enddo\n    enddo\n\n    do i = 1, ix\n       do j = 1, jx\n          do jj = 1, fsz\n             jjj = (j-hsz)+jj\n             if (jjj < 1) jjj = 1\n             if (jjj > jx) jjj = jx\n             filt(i,j) = filt(i,j) + v(jj)*tmp(i,jjj)\n          enddo\n       enddo\n    enddo\n\n  end subroutine gaussian_filter\n\n  subroutine crs2dot(slab1,slab2,ix,jx)\n\n    ! PURPOSE: Interpolate in horizontal from cross to dot points\n\n    implicit none\n    integer, intent(in) :: ix,jx\n    real, dimension(ix,jx), intent(in)  :: slab1\n    real, dimension(ix,jx), intent(out) :: slab2\n    integer :: ie,je,i,j\n\n    IE=IX-1\n    JE=JX-1\n    DO I=2,IE\n       DO J=2,JE\n          SLAB2(I,J)=0.25*(SLAB1(I,J)+SLAB1(I-1,J)+SLAB1(I,J-1)+SLAB1(I-1,J-1))\n       enddo\n    enddo\n    DO I=2,IE\n       SLAB2(I,1)=0.5*(SLAB1(I,1)+SLAB1(I-1,1))\n       SLAB2(I,JX)=0.5*(SLAB1(I,JE)+SLAB1(I-1,JE))\n    enddo\n    DO J=2,JE\n       SLAB2(1,J)=0.5*(SLAB1(1,J)+SLAB1(1,J-1))\n       SLAB2(IX,J)=0.5*(SLAB1(IE,J)+SLAB1(IE,J-1))\n    enddo\n    SLAB2(1,1)=SLAB1(1,1)\n    SLAB2(1,JX)=SLAB1(1,JE)\n    SLAB2(IX,JX)=SLAB1(IE,JE)\n    SLAB2(IX,1)=SLAB1(IE,1)\n\n  end subroutine crs2dot\n\n!KWM  SUBROUTINE MQD (NOBS, XC, YC, DAT, IX, JX, A1)\n!KWM    use kwm_matrix_utilities\n!KWM!\n!KWM! This routine does your basic, no-frills MQD analysis.  Adapted from\n!KWM! the routines in RAWINS and LITTLE_R.\n!KWM!\n!KWM!\n!KWM! MULTIQUADRIC INTERPOLATION BASED ON NUSS AND TITLEY (1994 MWR).\n!KWM! THE FREE PARAMETERS ARE LAMBDA, THE SMOOTHING FACTOR AND C, THE\n!KWM! MULTIQUADRIC PARAMETER. IF THE PROCEDURE BOMBS, THE MOST LIKELY\n!KWM! PROBLEM IS THAT THE VALUE FOR C IS INCORRECT. FOR LONG, NARROW\n!KWM! DOMAINS, IT MIGHT BE A PROBLEM.\n!KWM!  ON ENTRY:\n!KWM!         NOBS      :: Number of observations\n!KWM!         DAT(nobs) :: Difference of first guess from obs. ( obs-FG)\n!KWM!         XC (nobs) :: 1st coordinate of the observations\n!KWM!         YC (nobs) :: 2nd coordinate of the observations\n!KWM!         IX        :: 1st dimension of first-guess and analysis arrays\n!KWM!         JX        :: 2nd dimension of first-guess and analysis arrays\n!KWM!         A1(ix,jx) :: dimension(ix,jx):: first guess;\n!KWM!\n!KWM! ON EXIT:\n!KWM!         A1(ix,jx) :: Objective analysis\n!KWM!\n!KWM!  PROGRAMMED BY JIM BRESCH NCAR/UW    12/14/94\n!KWM!  Adapted to use blas routines by Kevin W. Manning.\n!KWM!  Further adapted, improved efficiency.\n!KWM!  Dropped into kwm modules package, October 2001.\n!KWM\n!KWM! As far as coordinate values:\n!KWM!     XC is the coordinate in the IX dimension,\n!KWM!     YC is the coordinate in the JX dimension.\n!KWM! regardless of whether I is Y and J is X or I is X and J is Y.\n!KWM!\n!KWM    implicit none\n!KWM\n!KWM! First, the subroutine arguments:\n!KWM    integer, intent(in)                      :: NOBS\n!KWM    integer, intent(in)                      :: IX\n!KWM    integer, intent(in)                      :: JX\n!KWM    real   , intent(in)   , dimension(nobs)  :: XC\n!KWM    real   , intent(in)   , dimension(nobs)  :: YC\n!KWM    real   , intent(in)   , dimension(nobs)  :: DAT\n!KWM    real   , intent(inout), dimension(ix,jx) :: A1\n!KWM\n!KWM! Now all the local names:\n!KWM    real   , parameter            :: lambda = 0.0025 ! Smoothing Factor\n!KWM\n!KWM    real   , dimension(ix,nobs)   :: QGI             ! Work space\n!KWM    real   , dimension(nobs,nobs) :: QI              ! Work space\n!KWM    real   , dimension(ix,jx)     :: A2              ! Work space\n!KWM    real,    dimension(ix*nobs)   :: XDUM            ! Work space\n!KWM\n!KWM    real                          :: C               ! MultiQuadric Parameter\n!KWM    real                          :: ERRM\n!KWM    integer                       :: I\n!KWM    integer                       :: J\n!KWM    integer                       :: IG\n!KWM    integer                       :: JG\n!KWM    IF (NOBS .LT. 3) THEN\n!KWM       WRITE(6,*) 'WARNING: NOBS < 3. NO MODIFICATION TO THE FIRST '//&\n!KWM            'GUESS FIELD OCCURRED.'\n!KWM       RETURN\n!KWM    ENDIF\n!KWM    C = 0.0008 * (MAX0(IX,JX)) ! MultiQuadric Parameter\n!KWM!\n!KWM! SET ERRM, THE MEAN ERROR VALUE FOR THE VARIABLE BEING ANALYZED. THE\n!KWM! RESULTS ARE NOT TOO SENSITIVE TO THIS PARAMETER, BUT THE VALUES MUST\n!KWM! BE SANE.\n!KWM    ERRM = 1.0\n!KWM\n!KWM    A2 = A1\n!KWM\n!KWM! FILL THE QI MATRIX\n!KWM    DO J = 1, NOBS\n!KWM       DO I = 1, NOBS\n!KWM          QI(I,J) = -1.* SQRT(((XC(J)-XC(I))**2 +&\n!KWM               (YC(J)-YC(I))**2)/(C*C)+1.)\n!KWM       ENDDO\n!KWM    ENDDO\n!KWM\n!KWM! ACCOUNT FOR OBSERVATIONAL UNCERTAINTY (NUSS AND TITLEY 1994)\n!KWM    DO J = 1, NOBS\n!KWM       I = J\n!KWM       QI(I,J) = QI(I,J) + NOBS*LAMBDA*ERRM\n!KWM    ENDDO\n!KWM\n!KWM! FIND THE INVERSE OF QI\n!KWM    call invert(qi, nobs, nobs)\n!KWM! QI NOW CONTAINS THE INVERSE OF ITSELF...\n!KWM\n!KWM    xdum = matmul(Qi, dat)\n!KWM\n!KWM! FILL THE QGI MATRIX\n!KWM    DO JG = 1, JX\n!KWM       DO IG = 1, IX\n!KWM          DO I = 1, NOBS\n!KWM             QGI(IG,I) = -1.* SQRT(((FLOAT(IG)-XC(I))**2 +&\n!KWM                  (FLOAT(JG)-YC(I))**2)/(C*C)+1.)\n!KWM          ENDDO\n!KWM       ENDDO\n!KWM! MULTIPLY QI INVERSE AND QGI\n!KWM! MULTIPLY THE PRODUCT WITH THE DATA VECTOR\n!KWM       A1(1:,JG) = matmul(Qgi, xdum)\n!KWM    ENDDO\n!KWM! ADD THE FIRST GUESS TO THE ARRAY\n!KWM    A1 = A1 + A2\n!KWM\n!KWM  END SUBROUTINE MQD\n\nend module kwm_grid_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/kwm_plot_utilities.F",
    "content": "!\n! Module with some handy graphics routines.\n!\n! This is very much a work in progress.\n!\n! A lot of this has been adapted from Mark Stoelinga's RIP program,\n! which is highly recommended.\n!\nmodule kwm_plot_utilities\n  integer                          , private :: nsq\n  real,              dimension(256), private :: rsq, usq\n  character(len=20), dimension(256), private :: cosq\n\n\n  ! NCO:  number of already-defined and named colors\n  integer, private :: nco\n\n  type named_color\n     character(len=20) :: name\n     real :: r\n     real :: g\n     real :: b\n  end type named_color\n\n  type(named_color), private, dimension(0:255) :: co\n\n  type plotconfig_type\n     integer :: nicecon\n     logical :: nolb\n     logical :: cbar\n     logical :: nohl\n  end type plotconfig_type\n  type(plotconfig_type), private :: plotconfig = plotconfig_type(30, .FALSE., .TRUE., .FALSE.)\n\n  integer,                    private :: nconarea\n  integer, parameter,         private :: maxcon = 80\n  real,    dimension(maxcon), private :: valcon\n  integer, dimension(maxcon), private :: majcon\n  integer, dimension(maxcon), private :: icoindcp\n  real ,                      private :: valmin\n  real ,                      private :: valmax\n  real ,                      private :: nsqmax, nsqmin\n  character(len=4) ,          private :: method = \"cont\"\n  real ,                      private :: frame_left = 0.0\n  real ,                      private :: frame_right = 1.0\n  real ,                      private :: frame_bottom = 0.0\n  real ,                      private :: frame_top = 1.0\n  logical,                    private :: larng\n\n  interface line_in_color\n     module procedure line_in_color_integer, line_in_color_string\n  end interface\n\ncontains\n\n!****************************************************************************************\n\n  subroutine kwm_start_ncargks(new_cgm_name)\n    implicit none\n    ! I can never remember what I called the subroutine.\n    character(len=*), optional, intent(in) :: new_cgm_name\n    if ( present (new_cgm_name) ) then\n       call kwm_init_ncargks(new_cgm_name)\n    else\n       call kwm_init_ncargks()\n    endif\n  end subroutine kwm_start_ncargks\n\n  subroutine kwm_open_ncargks(new_cgm_name)\n    implicit none\n    ! I can never remember what I called the subroutine.\n    character(len=*), optional, intent(in) :: new_cgm_name\n    if ( present (new_cgm_name) ) then\n       call kwm_init_ncargks(new_cgm_name)\n    else\n       call kwm_init_ncargks()\n    endif\n  end subroutine kwm_open_ncargks\n\n!****************************************************************************************\n\n  subroutine kwm_init_ncargks(new_cgm_name)\n! Starts off the NCAR Graphics package.\n! Opens workstation 1 as a CGM workstation.\n! Opens workstation 2 as a WISS.\n! Defines a couple of colors, and sets a couple of NCAR Graphics parameters\n!\n! If you want the gmeta file to be called something other than \"gmeta\",\n! give this subroutine the optional argument.\n    implicit none\n    character(len=*), optional, intent(in) :: new_cgm_name\n    character(len=80) :: newname\n    character(len=1) :: hdum\n\n    call gopks(6,0)\n\n    if (present(new_cgm_name)) then\n       newname = trim(new_cgm_name)\n       call gesc(-1391, 1, newname, 1, 1, hdum)\n    endif\n\n    call gopwk(1,119,1)\n    call gopwk(2,120,3)\n    call gacwk(1)\n    call gacwk(2)\n\n    call define_color(\"white\")\n    call define_color(\"black\")\n    call pcseti(\"FN\", 21)\n    call pcsetc(\"FC\", \"~\")\n  end subroutine kwm_init_ncargks\n\n!****************************************************************************************\n\n  subroutine kwm_close_ncargks\n    implicit none\n    call gdawk(1)\n    call gdawk(2)\n    call gclwk(1)\n    call gclwk(2)\n    call gclks\n\n    ! reset some accounting arrays\n    nsq = 0\n    rsq = 0.\n    cosq = \"\"\n    nco = 0\n    co = named_color(\"\",0.,0.,0.)\n\n  end subroutine kwm_close_ncargks\n\n!****************************************************************************************\n\n  subroutine gset_named_color(NAME)\n    ! Calls NCAR-Graphics subroutine GSCR to set the next color index\n    ! to the rgb values indicated by the color named NAME.\n\n    ! Side effects:  Associate RGB values with a color index NCO.\n    !                Increment module variable NCO.\n    implicit none\n    character(len=*), intent(in) :: NAME\n    type(named_color) :: color\n\n    print*\n    print*, ' ***** '\n    print*, ' ***** You probably want \"define_color(NAME)\" instead.'\n    print*, ' ***** '\n    print*\n\n    color = get_x11_color(name)\n    call gscr(1, nco, color%r, color%g, color%b)\n    nco = nco+1\n\n  end subroutine gset_named_color\n\n!****************************************************************************************\n\n  subroutine set_pval(arng, nicecon, cmth, frml, frmr, frmb, frmt, cbar, nolb, nohl)\n    implicit none\n    logical, optional, intent(in) :: arng\n    integer, optional, intent(in) :: nicecon   ! Approximate number of contours\n    character(len=4), optional, intent(in) :: cmth ! \"fill\", \"cont\", or \"both\"\n    real, optional, intent(in) :: frml, frmr, frmb, frmt\n    logical, optional, intent(in) :: cbar, nolb, nohl\n    if (present(arng))    larng = arng\n    if (present(nicecon)) plotconfig%nicecon = nicecon\n    if (present(cmth)   ) method = cmth\n    if (present(frml)   ) frame_left  = frml\n    if (present(frmr)   ) frame_right = frmr\n    if (present(frmb)   ) frame_bottom = frmb\n    if (present(frmt)   ) frame_top = frmt\n    if (present(cbar)   ) plotconfig%cbar = cbar\n    if (present(nolb)   ) plotconfig%nolb = nolb\n    if (present(nohl)   ) plotconfig%nohl = nohl\n\n  end subroutine set_pval\n\n!****************************************************************************************\n\n  subroutine fillcell(array, ix, jx, mask)\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, intent(in), dimension(ix,jx) :: array\n    logical, dimension(ix,jx), optional, intent(in) :: mask\n\n    logical, dimension(ix,jx) :: bmask\n    integer :: i, j, n, mjsk, numcon\n    real :: xmn, xmx, cintuse\n    type(named_color) :: cotmp\n    integer :: ico, icomax\n\n    type(named_color), dimension(maxcon) :: usit\n\n    mjsk = 0\n\n    if (present(mask)) then\n       bmask = mask\n    else\n       bmask = .TRUE.\n    endif\n\n!   Get the contour values\n    if (larng) then\n\n       numcon = plotconfig%nicecon\n       xmn = minval(array, mask=bmask)\n       xmx = maxval(array, mask=bmask)\n       do i = 1, numcon\n          valcon(i) = xmn + (xmx-xmn)*float(i-1)/float(numcon-1)\n       enddo\n       usq = xmn + (xmx-xmn)*rsq*0.01 ! *float(nsq-1)/float(nsq)\n\n    else\n\n       call getconvals(plotconfig%nicecon, mjsk, &\n            array, ix, jx, maxcon, valcon, majcon, &\n            cintuse, numcon, &\n            rbeg = rsq(1), rend=rsq(nsq))\n       usq = rsq\n       xmn = usq(1)\n       xmx = usq(nsq)\n    endif\n\n    if (numcon == 0) then\n       ! No coloring levels, so just return.\n       return\n    endif\n\n    nconarea = numcon+1\n! Set up colors.\n!   Assign the red, green, and blue fractions to the color sequence\n!\n    ILOOP : do i=1,nsq\n       ! nco is the number of colors already assigned by name\n       do j=0,nco-1\n          if (cosq(i) == co(j)%name) then\n             usit(i) = co(j)\n             cycle ILOOP\n          endif\n       enddo\n       ! If the color name is not found, look for it, add it to the list\n       ! of named colors, and increment NCO, the number of named colors.\n       usit(i) = get_x11_color(cosq(i))\n       co(nco) = usit(i)\n       nco = nco + 1\n    enddo ILOOP\n\n    nco = nco - 1\n    icomax = nco\n\n! Now see if new colors need to be defined.\n    COLORLOOP : do i=1,nconarea\n       icoindcp(i) = -1\n       cotmp = color_fraction( i, usit, usq, nsq, numcon, valcon )\n!\n!   Assign color index to icoindcp\n!      First check if color already exists\n!\n       do ico=0,icomax\n          if ( (abs(cotmp%r - co(ico)%r)<=0.001) .and. &\n               (abs(cotmp%g - co(ico)%g)<=0.001) .and. &\n               (abs(cotmp%b - co(ico)%b)<=0.001) ) then\n             icoindcp(i)=ico\n             call gscr(1,ico,co(ico)%r,co(ico)%g,co(ico)%b)\n             cycle COLORLOOP\n          endif\n       enddo\n!\n!      If not, set the new color and assign its index to icoincdcp\n!\n       icomax=icomax+1\n       if (icomax == 256) then\n          write(*,'(\"pltcon is trying to define color number 256, but 255\",/,&\n               &\"is the limit.  Try increasing the contour interval, or\",/,&\n               &\"reduce the number of colors defined in the color table.\")')\n          stop\n       endif\n       call gscr(1,icomax,cotmp%r,cotmp%g,cotmp%b)\n       co(icomax) = cotmp\n       icoindcp(i)=icomax\n    enddo COLORLOOP\n\n    do i = 1, ix\n       JLOOP : do j = 1, jx\n          if (.not. bmask(i,j)) cycle JLOOP\n          if (array(i,j) <= xmn) cycle JLOOP\n          do n = numcon, 1, -1\n             if ( array(i,j) >= valcon(n)) then\n                call ngsquares((/float(i)/), (/float(j)/), 1, 1., icoindcp(n+1))\n                exit\n             endif\n          enddo\n       enddo JLOOP\n    enddo\n\n    if (plotconfig%cbar) then\n       call labelbar(array, ix, jx, numcon)\n    endif\n\n  end subroutine fillcell\n\n!****************************************************************************************\n\n  subroutine labelbar(array, ix, jx, numcon, iskip)\n! Put on a color-scale and label the box\n    implicit none\n    integer, intent(in) :: ix, jx, numcon\n    integer, optional, intent(in) :: iskip\n    real, dimension(ix,jx) , intent(in) :: array\n    real :: xmx, xmn\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n\n    real :: xlmn, xlmx, ylmn, ylmx\n\n    integer :: n, ierr\n\n    integer :: ipx, ipn, ip\n    character(len=40) :: fmt, hh\n    integer, dimension(2) :: mxlc, mnlc\n\n    real :: txtsz\n    real :: mmsz\n\n    txtsz = 0.009 * min((frame_right-frame_left),(frame_top-frame_bottom))\n    mmsz = 0.015 * min((frame_right-frame_left),(frame_top-frame_bottom))\n\n    call gsplci(1)\n    call pcseti(\"CC\", 1)\n\n    call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n\n    call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n!KWM    call line(frame_left, frame_bottom, frame_right, frame_bottom)\n!KWM    call line(frame_left, frame_bottom, frame_left, frame_top)\n!KWM    call line(frame_left, frame_top, frame_right, frame_top)\n!KWM    call line(frame_right, frame_bottom, frame_right, frame_top)\n!    call set(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n\n!    call set(frame_left, frame_right, frame_bottom, frame_top, &\n!         0., 1., 0., 1., ml)\n\n    mxlc = maxloc(array)\n    mnlc = minloc(array)\n    xmx = array(mxlc(1), mxlc(2))\n    xmn = array(mnlc(1), mnlc(2))\n\n    xlmn = xr + 0.005\n    ! xlmx = xlmn + (frame_right-xr)*0.25\n    xlmx = xlmn + 0.050\n\n    do n = 1, numcon\n       ylmn = xb + float(n-1)/float(numcon) * (xt-xb)\n       ylmx = xb + float(n  )/float(numcon) * (xt-xb)\n!       call fillbox(xlmn, xlmx, ylmn, ylmx, icoindcp(n+1))\n       call fillbox(xlmn, xlmx, ylmn, ylmx, icoindcp(n))\n    enddo\n    call gslwsc(1.)\n    call line(xlmn,xb,xlmn,xt)\n    call line(xlmx,xb,xlmx,xt)\n    do n = 1, numcon!nsq\n       ylmn = xb + float(n-1)/float(numcon) * (xt-xb)\n       ylmx = xb + float(n  )/float(numcon) * (xt-xb)\n       call line(xlmn, ylmn, xlmx, ylmn)\n       call line(xlmn, ylmx, xlmx, ylmx)\n    enddo\n    call gslwsc(1.)\n\n    ! Determine the scaling for the numbers to be printed:\n\n    if (abs(xmx) > 1.E-12) then\n       ipx = alog10(abs(xmx))\n    else\n       ipx = 0\n    endif\n    if (abs(xmn) > 1.E-12) then\n       ipn = alog10(abs(xmn))\n    else\n       ipn = 0\n    endif\n    if (ipx - ipn > 6) then\n       ip = -(3*ipx+ipn)/4\n    else\n       ip = -min(ipx, ipn)\n    endif\n    if (ip > 0) then\n       write(fmt,'(\"(G14.5E2)\")')\n    else\n       write(fmt,'(\"(\",I3,\"PF12.4)\")') ip\n    endif\n\n!    do n = numcon+1, 1, -1\n    do n = numcon, 2, -1\n       ylmn = xb + float(n-1)/float(numcon) * (xt-xb)\n       if (n == numcon+1) then\n          write(hh, fmt=fmt) xmx\n!          print*, 'xmx, valcon(n) = ', xmx, valcon(n)\n          if (xmx == valcon(n-1)) then\n             ! Don't repeat the max value\n             hh = \"\"\n          endif\n       else\n          write(hh, fmt=fmt) valcon(n-1)\n       endif\n       if (present(iskip)) then\n          if (mod(n-2,iskip) == 0) then\n             call pchiqu(xlmx-0.030, ylmn, hh, txtsz * iskip * 0.66, 0., -1.)\n          endif\n       else\n          call pchiqu(xlmx+0.005, ylmn, hh, txtsz, 0., -1.)\n       endif\n    enddo\n\n    if (ip < 0) then\n       !call pchiqu(xlmn, xb-0.03, \"scaled by 1.E\"//fmt(2:4), txtsz, 0., -1.)\n       call pchiqu(xlmn, xb, \"~V-1Q~scaled by 1.E\"//fmt(2:4), txtsz, 0., -1.)\n    endif\n\n    write(fmt, '(\" at \",I4, 1x, I4)') mxlc(1), mxlc(2)\n\n    write(hh, '(F14.5)') xmx\n!    call pchiqu(xr, (xb-0.06), \"(x) Max value = \"//hh//trim(fmt),&\n!         mmsz, 0., 1.)\n\n!    call pchiqu(xr, xb-2*mmsz, \"(x) Max value = \"//hh//trim(fmt),&\n!         mmsz, 0., 1.)\n\n    write(fmt, '(\" at \",I4, 1x, I4)') mnlc(1), mnlc(2)\n    write(hh, '(F14.6)') xmn\n\n!    call pchiqu(xr, (xb-0.08), \"(+) Min value = \"//hh//trim(fmt), &\n!         mmsz, 0., 1.)\n\n!    call pchiqu(xr, xb-4*mmsz, \"(+) Min value = \"//hh//trim(fmt), &\n!         mmsz, 0., 1.)\n\n    call set(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n\n  end subroutine labelbar\n\n!****************************************************************************************\n\n  subroutine pltcon(array, ix, jx)\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, dimension(ix,jx), intent(in) :: array\n\n    integer, parameter :: lwrk = 800000, liwk = 2000000\n    real, dimension(lwrk) :: rwrk\n    integer, dimension(liwk) :: iwrk\n\n    integer, parameter :: niam = 1000000\n    integer, parameter :: ncs = 1000000\n    integer, dimension(niam) :: iam\n    real,    dimension(niam) :: xcs, ycs\n    integer, dimension(50000)  :: iaia, igia\n\n    real :: cintuse, cr, cg, cb\n    integer :: numcon\n    integer :: mjsk\n    integer :: ico, i, j, icomax, ierr\n    type(named_color) cotmp\n    type(named_color), dimension(maxcon) :: usit\n    real :: xmn, xmx\n\n    mjsk = 0\n\n!   Get the contour values\n    if (larng) then\n\n       numcon = plotconfig%nicecon\n       xmn = minval(array)\n       xmx = maxval(array)\n       do i = 1, numcon\n          valcon(i) = xmn + (xmx-xmn)*float(i-1)/float(numcon-1)\n       enddo\n       usq = xmn + (xmx-xmn)*rsq*0.01 ! *float(nsq-1)/float(nsq)\n\n    else\n\n       call getconvals(plotconfig%nicecon, mjsk, &\n            array, ix, jx, maxcon, valcon, majcon, &\n            cintuse, numcon, &\n            rbeg = rsq(1), rend=rsq(nsq))\n       usq = rsq\n\n    endif\n\n!KWM    print*, 'usq = ', usq(1:numcon)\n\n! Number of areas for filling is one plus the number of contours,\n! i.e., the contours define the boundaries between areas.\n    nconarea = numcon+1\n\n    call cpseti('SET',0)   ! we'll use our own set call\n    call cpseti('CLS',0)   ! we'll use our own cont. values\n!\n!   Some settings for hi/lo and contour labels\n!\n    call cpseti('NSD',-4)\n    call cpseti('NOF',7)\n    call cpsetr('PC6',.6)\n\n! Set up colors.\n!   Assign the red, green, and blue fractions to the color sequence\n!\n    ILOOP : do i=1,nsq\n       ! nco is the number of colors already assigned by name\n       do j=0,nco-1\n          if (cosq(i) == co(j)%name) then\n             usit(i) = co(j)\n             cycle ILOOP\n          endif\n       enddo\n       ! If the color name is not found, look for it, add it to the list\n       ! of named colors, and increment NCO, the number of named colors.\n       usit(i) = get_x11_color(cosq(i))\n       co(nco) = usit(i)\n       nco = nco + 1\n    enddo ILOOP\n\n    nco = nco - 1\n    icomax = nco\n!\n! USIT is now our list of color names and associated rgb values in\n! our color sequence.  Color values in USIT correspond to USQ\n\n! Note that we haven't actually called GSCR to assign RGB values to\n! color indices yet.  This will come later\n\n    COLORLOOP : do i=1,nconarea\n       icoindcp(i) = -1\n       cotmp = color_fraction( i, usit, usq, nsq, numcon, valcon )\n!\n!   Assign color index to icoindcp\n!      First check if color already exists\n!\n       do ico=0,icomax\n          if ( (abs(cotmp%r - co(ico)%r)<=0.001) .and. &\n               (abs(cotmp%g - co(ico)%g)<=0.001) .and. &\n               (abs(cotmp%b - co(ico)%b)<=0.001) ) then\n             icoindcp(i)=ico\n             call gscr(1,ico,co(ico)%r,co(ico)%g,co(ico)%b)\n             cycle COLORLOOP\n          endif\n       enddo\n!\n!      If not, set the new color and assign its index to icoincdcp\n!\n       icomax=icomax+1\n       if (icomax == 256) then\n          write(*,'(\"pltcon is trying to define color number 256, but 255\",/,&\n               &\"is the limit.  Try increasing the contour interval, or\",/,&\n               &\"reduce the number of colors defined in the color table.\")')\n          stop\n       endif\n       call gscr(1,icomax,cotmp%r,cotmp%g,cotmp%b)\n       co(icomax) = cotmp\n       icoindcp(i)=icomax\n    enddo COLORLOOP\n\n    call cpseti('NVS', 4)\n    call cpseti('NCL',numcon)\n    if (plotconfig%nohl) then\n       call cpsetc(\"HIT\", ' ')\n       call cpsetc(\"LOT\", ' ')\n    endif\n    do i=1,numcon\n       call cpseti('PAI',i)\n       call cpsetr('CLV',valcon(i))\n       if (plotconfig%nolb) then\n          call cpseti('CLU',1)\n       else\n          call cpseti('CLU',3)\n       endif\n       call cpseti('AIB',i)\n       call cpseti('AIA',i+1)\n    enddo\n\n    call cprect(array,ix,ix,jx,rwrk,lwrk,iwrk,liwk)\n    call arinam(iam,niam) ! Initialize the area map\n\n    call cpclam(array,rwrk,iwrk,iam)  ! put cont. lines in area map\n    if ((method == \"both\") .or. (method == \"fill\")) then\n       call arscam(iam,xcs,ycs,ncs,iaia,igia,5000,cpcolr)\n       if (plotconfig%cbar) then\n          call labelbar(array, ix, jx, numcon)\n       endif\n    endif\n\n!KWM! Add a color bar.\n!KWM!    call color_bar(nsq, 0., rsq(nsq))\n!KWM    if (larng) then\n!KWM       call color_bar(numcon-1, valmin, valmax)\n!KWM    else\n!KWM       call color_bar(numcon, valmin, valmax)\n!KWM    endif\n\n    if ((method == \"cont\") .or. (method == \"both\")) then\n       ! Contour lines:\n       call cplbdr(array, rwrk, iwrk)\n       call cpcldr(array, rwrk, iwrk)\n    endif\n\n    call gsplci(1)\n    call pcseti(\"CC\", 1)\n  end subroutine pltcon\n\n!****************************************************************************************\n\n  subroutine color_bar(nthresh, cmin, cmax)\n    implicit none\n    integer, intent(in) :: nthresh\n    real, intent(in) :: cmin, cmax\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n\n    real :: xlmn, xlmx, ylmn, ylmx\n    integer :: n, ipx, ipn, ip\n\n    character(len=14) :: hh, fmt\n    integer :: i, j, jj\n    integer :: ierr\n\n    call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n    call set(frame_left,frame_right,frame_bottom,frame_top,0.,1.,0.,1.,ml)\n\n    xlmn = xr + 0.005\n    ! xlmx = xlmn + (1.-xr)*0.25\n    xlmn = xlmn + .050\n\n    do n = 1, nthresh+1\n       ylmn = xb + float(n-1)/float(nthresh+1) * (xt-xb)\n       ylmx = xb + float(n  )/float(nthresh+1) * (xt-xb)\n       if (n <= nthresh) then\n          call cpseti('PAI',n)\n          call cpgeti('AIB',j)\n          call fillbox(xlmn, xlmx, ylmn, ylmx, icoindcp(j))\n!          call fillbox(xlmn, xlmx, ylmn, ylmx, color_index(cosq(n)))\n       else\n          call cpseti('PAI',n-1)\n          call cpgeti('AIA',jj)\n          call cpgeti('AIB',j)\n          call fillbox(xlmn, xlmx, ylmn, ylmx, icoindcp(jj))\n!          call fillbox(xlmn, xlmx, ylmn, ylmx, color_index(cosq(n)))\n       endif\n    enddo\n\n    call gslwsc(1.)\n    call line(xlmn,xb,xlmn,xt)\n    call line(xlmx,xb,xlmx,xt)\n    do n = 1, nthresh+1\n       ylmn = xb + float(n-1)/float(nthresh+1) * (xt-xb)\n       ylmx = xb + float(n  )/float(nthresh+1) * (xt-xb)\n       call line(xlmn, ylmn, xlmx, ylmn)\n       call line(xlmn, ylmx, xlmx, ylmx)\n    enddo\n    call gslwsc(1.)\n\n! Determine the scaling for the numbers to be printed:\n\n    if (abs(cmax) > 1.E-12) then\n       ipx = alog10(abs(cmax))\n    else\n       ipx = 0\n    endif\n    if (abs(cmin) > 1.E-12) then\n       ipn = alog10(abs(cmin))\n    else\n       ipn = 0\n    endif\n    if (ipx - ipn > 6) then\n       ip = -(3*ipx+ipn)/4\n    else\n       ip = -min(ipx, ipn)\n    endif\n    if (ip > 0) then\n       write(fmt,'(\"(G14.5E2)\")')\n    else\n       write(fmt,'(\"(\",I3,\"PF12.4)\")') ip\n       if (ierr /= 0) fmt=\"(G20.5E2)\"\n    endif\n\n    do n = nthresh, 1, -1\n       ylmn = xb + float(n)/float(nthresh+1) * (xt-xb)\n       if (n == nthresh+1) then\n!        write(hh, '(G14.5E2)') xmx\n          write(hh, fmt=fmt) cmax\n       else\n!        write(hh, '(G14.5E2)') thresh(n)\n          write(hh, fmt=fmt) valcon(n) !thresh(n)\n       endif\n       call pchiqu(xlmx+0.005, ylmn, hh, 0.009, 0., -1.)\n    enddo\n\n    if (ip < 0) then\n       !call pchiqu(xlmn, xb-0.03, \"scaled by 1.E\"//fmt(2:4), 0.009, 0., -1.)\n       call pchiqu(xlmn, xb, \"~V-1Q~scaled by 1.E\"//fmt(2:4), 0.009, 0., -1.)\n    endif\n\n!    write(fmt, '(\" at \",I4, 1x, I4)') mxlcx, mxlcy\n\n!    write(hh, '(F14.5)') xmx\n!    call pchiqu(xlmn-0.17, (xb-0.06), \"(x) Max value = \"//hh//fmt,&\n!         0.011, 0., 1.)\n\n!    write(fmt, '(\" at \",I4, 1x, I4)') mnlcx, mnlcy\n!    write(hh, '(F14.6)') xmn\n!    call pchiqu(xlmn-0.17, (xb-0.10), \"(+) Min value = \"//hh//fmt, &\n!         0.011, 0., 1.)\n\n    call set(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n  end subroutine color_bar\n\n!==============================================================================\n\n  type(named_color) function get_x11_color(name) result (c)\n    use kwm_string_utilities\n    implicit none\n    character(len=*) :: name\n    integer :: r, g, b, i\n    character(len=20) :: cname\n\n    logical, save :: already_read = .FALSE.\n    integer :: ierr, idx\n    character(len=80) :: string, stringname\n    integer, external :: get_unused_unit\n    integer :: iunit\n\n    real, dimension(2500), save :: readlist_r, readlist_g, readlist_b\n    character(len=64), dimension(2500), save :: readlist_name\n    integer, save :: readlist_count = 0\n    logical :: lthere\n\n    if (.not. already_read) then\n       already_read = .TRUE.\n       iunit = get_unused_unit()\n\n       inquire(file=\"/usr/lib/X11/rgb.txt\", exist=lthere)\n       if (lthere) then\n          open(iunit, file=\"/usr/lib/X11/rgb.txt\", form='formatted', &\n               status='old', action='read', iostat=ierr)\n       else\n          inquire(file=\"/usr/share/X11/rgb.txt\", exist=lthere)\n          if (lthere) then\n             open(iunit, file=\"/usr/share/X11/rgb.txt\", form='formatted', &\n                  status='old', action='read', iostat=ierr)\n          else\n             stop 'KWM_PLOT_UTILITIES:  Cannot find X11 \"rgb.txt\" file'\n          endif\n       endif\n       if (ierr /= 0) stop \"color table\"\n       do\n\n          read(iunit, '(A)', iostat=ierr) string\n          if (ierr /= 0) exit\n          if (string(1:1) == \"!\") cycle\n\n          stringname = \" \"\n          read(string, *) r, g, b\n          ! Find the index of the first alphabetical character\n          idx = verify(string, \" 0123456789\"//char(9)) ! char(9) is tab\n          stringname = trim(string(idx:))\n          stringname = downcase(trim(stringname))\n          stringname = unblank(trim(stringname))\n\n          readlist_count = readlist_count + 1\n          readlist_r(readlist_count) = float(r)/255.\n          readlist_g(readlist_count) = float(g)/255.\n          readlist_b(readlist_count) = float(b)/255.\n          readlist_name(readlist_count) = stringname\n\n       enddo\n\n       close(iunit)\n    endif\n\n    ! Search through readlist for name\n\n    if (name(1:1) == \"#\") then\n       read(name(2:7), '(Z2,Z2,Z2)') r, g, b\n       cname = name\n       c = named_color(cname, float(r)/255., float(g)/255., float(b)/255.)\n       return\n    else if ((name(1:2) == \"0x\") .or. (name(1:2) == \"0X\")) then\n       read(name(3:8), '(Z2,Z2,Z2)') r, g, b\n       cname = name\n       c = named_color(cname, float(r)/255., float(g)/255., float(b)/255.)\n       return\n    else\n\n       do i = 1, readlist_count\n          if (name == readlist_name(i)) then\n             cname = name\n             c = named_color(cname, readlist_r(i), readlist_g(i), readlist_b(i))\n             return\n          endif\n       enddo\n\n       write(*, '(\"color not found: \", A)') trim(name)\n    endif\n\n  end function get_x11_color\n\n  type(named_color) function color_fraction(i, usit, rsq, count, numcon, valcon) &\n       result (c)\n! Returns c(name,r,g,b) that is to be used for index i\n\n    implicit none\n    integer, intent(in)                             :: i\n    integer, intent(in)                             :: count\n    type(named_color), intent(in), dimension(count) :: usit\n    real,              intent(in), dimension(count) :: rsq\n    integer, intent(in)                             :: numcon\n    real,    intent(in),          dimension(numcon) :: valcon\n\n    real :: val\n    real :: red, green, blue, fac\n    integer :: isq\n\n    if (numcon == 0) then\n       print*, 'numcon = ', numcon\n       c = named_color(\"white\", 1., 1., 1.)\n       return\n    endif\n    if (numcon == 1) then\n       print*, 'numcon = ', numcon\n       c = named_color(\"white\", 1., 1., 1.)\n       return\n    endif\n\n    valmin=valcon(1)-.5*(valcon(2)-valcon(1))\n    valmax=valcon(numcon)+.5*(valcon(numcon)-valcon(numcon-1))\n\n    if (i == 1) then\n       val=valmin\n    elseif (i == numcon+1) then\n       val=valmax\n    else\n       val=.5*(valcon(i-1)+valcon(i))\n    endif\n\n    c = named_color(\"transparent\", -1., -1., -1.)\n\n    if (val.le.valcon(1)) then\n       if (usit(1)%name /= \"transparent\" ) c = usit(1)\n    elseif (val.ge.valcon(numcon)) then\n       if (usit(nsq)%name /= \"transparent\" ) c = usit(nsq)\n    else\n       ! Interpolate from USIT rgb values (associated with RSQ\n       ! floating-point values) to a new color c.\n\n       do isq=1,nsq-1\n          if (val.ge.rsq(isq).and.val.le.rsq(isq+1)) then\n             if ( usit(isq  )%name /= \"transparent\" .and. &\n                  usit(isq+1)%name /= \"transparent\" ) then\n                fac=(val-rsq(isq))/(rsq(isq+1)-rsq(isq))\n                red  =fac*usit(isq+1)%r+(1.-fac)*usit(isq)%r\n                green=fac*usit(isq+1)%g+(1.-fac)*usit(isq)%g\n                blue =fac*usit(isq+1)%b+(1.-fac)*usit(isq)%b\n                c = named_color(\"\", red, green, blue)\n             endif\n             return\n          endif\n       enddo\n!KWM       print*, 'usit%name = ', usit%name\n!KWM       print*, 'rsq = ', rsq\n!KWM       print*, 'valcon = ', valcon\n!KWM       print*, 'valmin, valmax = ', valmin, valmax\n!KWM       print*, 'val = ', val\n!KWM       stop \"Not Found.\"\n    endif\n  end function color_fraction\n\n!==============================================================================\n\n  subroutine getconvals(ncon,mjsk, &\n       array,ix,jx,maxcon,valcon,majcon, &\n       cintuse, numcon, rbeg, rend, rint, fmsg)\n! Swiped from Mark Stoelinga's RIP program and adapted.\n    implicit none\n    real,            optional, intent(in) :: rbeg ! cbeg\n    real,            optional, intent(in) :: rend ! cend\n    real,            optional, intent(in) :: rint ! cint\n    real,            optional, intent(in) :: fmsg ! rmsg\n    integer,                   intent(in) :: ncon\n    integer,                   intent(in) :: mjsk\n    integer,                   intent(in) :: ix, jx\n    integer,                   intent(in) :: maxcon\n    real,    dimension(ix,jx), intent(in) :: array\n\n    real,    dimension(maxcon), intent(out) :: valcon\n    integer, dimension(maxcon), intent(out) :: majcon\n    real,                       intent(out) :: cintuse\n    integer,                    intent(out) :: numcon\n\n    integer :: ii, i, j, itmp, imaj, imajrel\n!\n!\n    real :: cbeg, cend, cint, rmsg\n    real :: cb, ce, ci, tmp, fac, diff, fv, rmax, rmin, crange\n    real :: p\n    logical :: mult\n!\n!   mjsk is the number of minor (unlabeled) contours desired\n!   between major (labeled) contours.\n!\n    logical :: choosecb, chooseci\n\n    if (present(fmsg)) then\n       rmsg = fmsg\n    else\n       rmsg = -1.E30\n    endif\n\n!\n!   cbeg is the beginning contour value.  rmsg means pick a\n!   nice value close to the max value in the field. -rmsg means\n!   pick a nice value close to the min value in the field.\n!\n    if (present(rbeg)) then\n       cbeg = rbeg\n    else\n       cbeg = rmsg\n    endif\n!\n!   cend is the ending contour value.  rmsg means pick a nice\n!   value close to the max value in the field. -rmsg means pick\n!   a nice value close to the min value in the field.\n!\n    if (present(rend)) then\n       cend = rend\n    else\n       cend = -rmsg\n    endif\n!\n!   cint is the contour interval. rmsg means pick a nice value\n!   that generates close to ncon contours.\n!\n    if (present(rint)) then\n       cint = rint\n    else\n       cint = rmsg\n    endif\n!\n!   mult means use a multiplicative contour interval instead of\n!   an additive one.  If mult is true, cbeg and cend must be of\n!   the same sign (otherwise cend will be changed to a value\n!   that is of the same sign as cbeg), and all contour values\n!   will also be the same sign.\n!\n!KWM  mult = lmult(ipl)\n    mult = .FALSE.\n!\n!   First get max and min in field.\n!\n    if (all(array==rmsg)) then\n       write(*,*)'   In getconvals: not generating any contours'\n       write(*,*)'    because all values are special value.'\n       numcon=0\n       return\n    endif\n!\n    rmax = maxval(array, mask=(array/=rmsg))\n    rmin = minval(array, mask=(array/=rmsg))\n\n    if (rmax == rmin) then\n       write(*,*)'   In getconvals: not generating any contours'\n       write(*,*)'    because field is constant.  Value = ',rmax\n       numcon=0\n       return\n    endif\n!\n    choosecb=.false.\n    if (cbeg == rmsg) then\n       cb=rmax\n       choosecb=.true.\n    elseif (cbeg == -rmsg) then\n       cb=rmin\n       choosecb=.true.\n    else\n       cb=cbeg\n    endif\n!\n    if (cend == rmsg) then\n       ce=rmax\n    elseif (cend == -rmsg) then\n       ce=rmin\n    else\n       ce=cend\n    endif\n!\n    chooseci=.false.\n    if (cint == rmsg .or. cint == 0.0) then\n       chooseci=.true.\n    elseif (cint < 0.0) then\n       ci=-cint\n    else\n       ci=cint\n    endif\n!\n!KWM  if (mult) then\n!KWM     if (cb == 0.0.or.ce == 0.0) then\n!KWM        write(iup,*)'In getconvals: not generating any contours'\n!KWM        write(iup,*)'   because mult is true and cbeg or cend'\n!KWM        write(iup,*)'   are zero. cbeg,cend=',cbeg,cend\n!KWM        numcon=0\n!KWM        return\n!KWM     endif\n!KWM     if (cb*ce.lt.0.0) then\n!KWM        write(iup,*)'In getconvals: not generating any contours'\n!KWM        write(iup,*)'   because mult is true and cbeg and cend are'\n!KWM        write(iup,*)'   of opposite sign.  cbeg,cend=',cbeg,cend\n!KWM        numcon=0\n!KWM        return\n!KWM     endif\n!KWM     if (ci == 1.0) chooseci=.true.\n!KWM     if (cb.lt.0.0) then\n!KWM        iswitch=1\n!KWM        cb=-cb\n!KWM        ce=-ce\n!KWM        temp=rmax\n!KWM        rmax=-rmin\n!KWM        rmin=-temp\n!KWM     else\n!KWM        iswitch=0\n!KWM     endif\n!KWM     valm=1e-8*cb\n!KWM     rmax=max(rmax,valm)\n!KWM     rmin=max(rmin,valm)\n!KWM     ce=max(ce,valm)\n!KWM  endif\n!\n!   Set up start, end, and interval.\n!\n!KWM  if (.not.mult) then\n    if (chooseci) then\n       crange=max(abs(ce-cb),1.e-10)\n       ci = crange/ncon\n       p = 10.**(int(alog10(ci)+50000.)-50000)\n       ci=max(ci,p)\n       ii=int(ci/p)\n       if (ii.ge.7) then\n          ci = 10.*p\n       else\n          ci = ii*p\n       endif\n    endif\n    if (choosecb) then\n       cb=nint(cb/ci)*ci\n       if (cb.ge.rmax) cb=cb-ci\n       if (cb.le.rmin) cb=cb+ci\n    endif\n!KWM  else\n!KWM     if (choosecb) then\n!KWM        cmax=10.**(int(alog10(rmax)+50000.)-50000)\n!KWM        cmin=10.**(int(alog10(rmin)+50000.)-50000+1)\n!KWM        cb=10.**(nint(alog10(cb)+50000.)-50000)\n!KWM        cb=min(max(cb,cmin),cmax)\n!KWM     endif\n!KWM     if (chooseci) then\n!KWM        ci=(max(ce,cb)/min(ce,cb))**(1./(max(ncon,2)-1))\n!KWM        if (ci.le.1.6) then\n!KWM           ci=sqrt(2.)\n!KWM        elseif (ci.le.3.5) then\n!KWM           ci=2.\n!KWM        elseif (ci.le.7.5) then\n!KWM           ci=5.\n!KWM        else\n!KWM           ci=10.**nint(alog10(ci))\n!KWM        endif\n!KWM     endif\n!KWM  endif\n    cintuse=ci\n!\n!   Generate contour levels.\n!\n!KWM  if (.not.mult) then\n    if (ce.lt.cb) then\n       ci=-abs(ci)\n    else\n       ci=abs(ci)\n    endif\n!KWM  else\n!KWM     alci=alog(ci)\n!KWM     if (abs(ce).lt.abs(cb)) then\n!KWM        alci=-abs(alci)\n!KWM     else\n!KWM        alci=abs(alci)\n!KWM     endif\n!KWM     ci=exp(alci)\n!KWM  endif\n    numcon=1\n    valcon(numcon)=cb\n50  numcon=numcon+1\n    if (numcon.gt.maxcon) goto 100\n!KWM  if (.not.mult) then\n    valcon(numcon)=valcon(numcon-1)+ci\n!KWM  else\n!KWM     valcon(numcon)=valcon(numcon-1)*ci\n!KWM  endif\n    if ((ce.ge.cb.and.valcon(numcon).gt.ce).or.&\n         (ce.lt.cb.and.valcon(numcon).lt.ce)) goto 100\n    goto 50\n100 numcon=numcon-1\n!\n!   Return mult contours to opposite sign, if iswitch=1\n!\n!KWM  if (mult) then\n!KWM     if (iswitch == 1) then\n!KWM        do i=1,numcon\n!KWM           valcon(i)=-valcon(i)\n!KWM        enddo\n!KWM     endif\n!KWM  endif\n!\n!   Determine major contours\n!\n    do i=1,numcon\n       if (.not.mult) then\n          fac=valcon(i)/((mjsk+1)*abs(ci))\n       else\n          fac=alog10(abs(valcon(i)))\n       endif\n       diff=abs(fac-float(nint(fac)))\n       if (diff.lt..001) then\n          imaj=i\n          goto 200\n       endif\n    enddo\n    imaj=1\n200 continue\n    imajrel=mod(imaj,mjsk+1)-(mjsk+1)\n    do i=1,numcon\n       if (.not.mult) then\n          fac=valcon(i)/((mjsk+1)*abs(ci))\n       else\n          fac=1.\n       endif\n       if (abs(fac).lt.1e-4) then    ! zero contour\n          valcon(i)=0.0\n          majcon(i)=0\n       elseif (mod(i-imajrel,mjsk+1) == 0) then\n          if (valcon(i).gt.0) then ! positive major (labeled) contour\n             majcon(i)=2\n          else                     ! negative major (labeled) contour\n             majcon(i)=-2\n          endif\n       else\n          if (valcon(i).gt.0) then   ! positive unlabeled contour\n             majcon(i)=1\n          else                       ! negative unlabeled contour\n             majcon(i)=-1\n          endif\n       endif\n    enddo\n!\n!   Reorder if valcon(1) > valcon(numcon)\n!\n    if (valcon(1).gt.valcon(numcon)) then\n       do i=1,numcon/2\n          ii=numcon+1-i\n          tmp=valcon(i)\n          valcon(i)=valcon(ii)\n          valcon(ii)=tmp\n          itmp=majcon(i)\n          majcon(i)=majcon(ii)\n          majcon(ii)=itmp\n       enddo\n    endif\n!\n  end subroutine getconvals\n\n!****************************************************************************************\n\n  subroutine cpcolr (xcra,ycra,ncra,iaia,igia,naia)\n!\n!   This is a user-supplied areas subroutine which allows the user\n!   to color areas in a particular way.\n!\n    implicit none\n    integer, intent(in) :: naia, ncra\n    real   , intent(in), dimension(ncra) :: xcra, ycra\n    integer, intent(in), dimension(naia) :: iaia, igia\n\n    integer :: ifll, i\n!\n!   Assume polygon will be filled until we find otherwise.\n!\n    ifll=1\n!\n!   If any area identifier is negative, don't fill the polygon\n!\n    do i=1,naia\n       if (iaia(i).lt.0.) then\n          ifll=0\n       endif\n    enddo\n!\n!   Otherwise, fill the polygon in the color implied by its area\n!   identifier relative to edge group 3 (the contour-line group).\n!\n    if (ifll.ne.0) then\n       ifll=0\n       do i=1,naia\n          if (igia(i) == 3) then\n             ifll=iaia(i)\n          endif\n       enddo\n!\n!      Note that if icoindcp(ifll) is negative, that means this\n!      polygon should remain transparent (i.e. not filled).\n!\n       if (ifll.ge.1) then\n          if (ifll.le.nconarea.and.icoindcp(ifll).ge.0) then\n             call gsfaci(icoindcp(ifll))\n             call gfa (ncra-1,xcra,ycra)\n          else\n             write(*, '(\"ifll = \",I12)') ifll\n             write(*, '(\"icoindcp(ifll) = \",I2)') icoindcp(ifll)\n             stop \"Transparent problem.  Fix it?\"\n          endif\n       endif\n    endif\n\n  end subroutine cpcolr\n\n!****************************************************************************************\n\n  subroutine dfclrs\n    ! A couple of predefined colors, namely, white and black.\n    implicit none\n    integer :: i\n\n    print*\n    print*, ' ***** '\n    print*, ' ***** Do not use DFCLRS.'\n    print*, ' ***** '\n    print*\n\n    nco = 0\n    co%name = \" \"\n\n    co(nco)= named_color(\"white\", 1., 1., 1.)\n    nco = nco + 1\n\n    co(nco) = named_color(\"black\", 0., 0., 0.)\n    nco = nco + 1\n\n    do i = 0, nco-1\n       call gscr(1, i, co(i)%r, co(i)%g, co(i)%b)\n    enddo\n\n  end subroutine dfclrs\n\n!****************************************************************************************\n\n  subroutine define_color(name)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer :: i\n\n    ! print*, 'Function DEFINE_COLOR:  name = ', trim(name)\n\n    do i = 0, nco-1\n       if (co(i)%name == name) return\n    enddo\n\n    co(nco) = get_x11_color(name)\n    call gscr(1, nco, co(nco)%r, co(nco)%g, co(nco)%b)\n    ! print*,' nco, r,g,b = ', nco, co(nco)%r, co(nco)%g, co(nco)%b\n    nco = nco + 1\n\n  end subroutine define_color\n\n!****************************************************************************************\n\n  subroutine new_color(name, r, g, b)\n    implicit none\n    character(len=*), intent(in) :: name\n    real, intent(in) :: r, g, b\n    integer :: i\n\n    do i = 0, nco-1\n       if (co(i)%name == name) then\n          write(*,'(\"Subroutine NEW_COLOR:  color \",A,\" already defined.\")') name\n          return\n       endif\n    enddo\n\n    co(nco)= named_color(name, r, g, b)\n    call gscr(1, nco, co(nco)%r, co(nco)%g, co(nco)%b)\n    nco = nco + 1\n\n  end subroutine new_color\n\n!****************************************************************************************\n\n  integer function color_index(name) result(ci)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer :: i\n\n    do i = 0, nco-1\n       ! print*, 'i, co(i)%name, name = ', i, trim(co(i)%name), trim(name)\n       if (co(i)%name == name) then\n          ci = i\n          return\n       endif\n    enddo\n\n    ! If the color has not already been defined, define it.\n    call define_color(name)\n    do i = 0, nco-1\n       if (co(i)%name == name) then\n          ci = i\n          return\n       endif\n    enddo\n\n    ! If the color is STILL not defined, we've got more problems than that.\n    print*, 'function COLOR_INDEX:  Color not defined: ', trim(name)\n    stop\n\n  end function color_index\n\n!****************************************************************************************\n\n  subroutine named_color_sequence(seqname, cbeg, cend)\n    implicit none\n    character(len=*) :: seqname\n    real :: cbeg, cend\n    integer :: i, nnco\n    real :: r\n\n    nsqmin = cbeg\n    nsqmax = cend\n\n    select case (seqname)\n    case (\"precip\")\n       call initcosq\n       nnco = 16\n       do i = 1, nnco\n          r = (cend-cbeg)*float(i-1)/float(nnco-1) + cbeg\n          select case (i)\n          case (1)\n             call addcosq(r, \"white\")\n          case (2)\n             call addcosq(r, \"gray70\")\n          case (3)\n             call addcosq(r, \"darkgreen\")\n          case (4)\n             call addcosq(r, \"green3\")\n          case (5)\n             call addcosq(r, \"green\")\n          case (6)\n             call addcosq(r, \"gold\")\n          case (7)\n             call addcosq(r, \"goldenrod\")\n          case (8)\n             call addcosq(r, \"darkgoldenrod\")\n          case (9)\n             call addcosq(r, \"orange3\")\n          case (10)\n             call addcosq(r, \"tomato3\")\n          case (11)\n             call addcosq(r, \"red4\")\n          case (12)\n             call addcosq(r, \"darkorchid4\")\n          case (13)\n             call addcosq(r, \"darkorchid3\")\n          case (14)\n             call addcosq(r, \"slateblue2\")\n          case (15)\n             call addcosq(r, \"dodgerblue3\")\n          case (16)\n             call addcosq(r, \"cyan\")\n          end select\n\n       enddo\n    case (\"temperature\")\n\n       call initcosq\n       nnco = 6\n       do i = 1, nnco\n          r = (cend-cbeg)*float(i-1)/float(nnco-1) + cbeg\n          select case (i)\n          case (1)\n             call addcosq(r, \"cyan\")\n          case (2)\n             call addcosq(r, \"blue\")\n          case (3)\n             call addcosq(r, \"white\")\n          case (4)\n             call addcosq(r, \"red\")\n          case (5)\n             call addcosq(r, \"magenta\")\n          case (6)\n             call addcosq(r, \"green\")\n          end select\n       enddo\n    case default\n       print*, 'NAMED_COLOR_SEQUENCE: unknown sequence name: ', trim(seqname)\n    end select\n\n  end subroutine named_color_sequence\n\n!****************************************************************************************\n\n  subroutine set_color_sequence(cosqstr)\n    implicit none\n    character(len=*), intent(in) :: cosqstr\n    integer :: i, j, ierr\n\n    call initcosq\n\n    i = 1\n    j = index(cosqstr(i:),',')\n    parse : do\n\n       nsq = nsq + 1\n       read(cosqstr(i:j-1),*, iostat=ierr) rsq(nsq)\n       if (ierr /= 0) then\n          write(*,'(\"Problem reading float from:  #\", A,\"#\" )') cosqstr(i:j)\n          stop\n       endif\n       i = j+1\n       j = index(cosqstr(i:),',')-1+i\n\n       if (j > i) then\n          cosq(nsq) = cosqstr(i:j-1)\n          i = j+1\n          j = index(cosqstr(i:),',')-1+i\n       else\n          cosq(nsq) = cosqstr(i:)\n          exit\n       endif\n    enddo parse\n\n    ! Make sure that the color sequence values are ascending:\n    do i = 1, nsq-1\n       if (rsq(i+1) < rsq(i)) then\n          write(*,'(\"Color sequence out of order:\")')\n          do j = 1, nsq\n             if (j == i) then\n                write(*,*) \"------>\", rsq(j), cosq(j) , \"<-------\"\n             else\n                write(*,*) \"       \", rsq(j), cosq(j)\n             endif\n          enddo\n          stop\n       endif\n    enddo\n\n  end subroutine set_color_sequence\n\n!****************************************************************************************\n\n  subroutine initcosq()\n    implicit none\n    nsq = 0\n    rsq = 0\n    cosq = \"\"\n  end subroutine initcosq\n\n!****************************************************************************************\n\n  subroutine addcosq(rval, coname)\n    implicit none\n    real :: rval\n    character(len=*) :: coname\n\n    nsq = nsq + 1\n    rsq(nsq)  = rval\n    cosq(nsq) = coname\n  end subroutine addcosq\n\n!****************************************************************************************\n\n  subroutine set_gscr_color_indices(is,ie,seqstr)\n    ! Set all the ncargks color indices between IS and IE to the\n    ! colors listed in the SEQSTR\n\n    implicit none\n\n    integer, intent(in) :: is ! Index Start\n    integer, intent(in) :: ie ! Index End\n\n    character(len=*), intent(in) :: seqstr ! Color Sequence String,\n    ! of the form \"cval,color,cval,color,cval,color...\"\n\n\n    type copair_type\n       real :: xseq\n       character(len=64) :: hseq\n       real :: r, g, b\n    end type copair_type\n\n    type(copair_type), dimension(256) :: copair\n\n    type(named_color) :: c\n\n\n    integer :: cocount\n\n    integer :: ii, jj, ir, ig, ib\n    character(len=4096) :: current\n    real :: xseq\n    character(len=64) :: hseq\n\n    real :: x, minseq, maxseq, f, r, g, b, h\n\n    ! Parse the seqstr\n    current = trim(seqstr)//\",\"\n\n    ii = index(current,\",\");\n    cocount = 0\n    do while (ii > 0)\n       read(current(1:ii-1),*) xseq\n       current = current(ii+1:)\n       ii = index(current,\",\");\n       hseq = current(1:ii-1)\n       current = current(ii+1:)\n       ii = index(current,\",\")\n       cocount = cocount + 1\n\n       copair(cocount)%xseq = xseq\n       copair(cocount)%hseq = hseq\n\n       c = get_x11_color(trim(hseq))\n       copair(cocount)%r = c%r\n       copair(cocount)%g = c%g\n       copair(cocount)%b = c%b\n    enddo\n\n    minseq = copair(1)%xseq\n    maxseq = copair(cocount)%xseq\n\n    do ii = is, ie\n       ! Where are we between min and max.\n       x = minseq + float(ii-is)/float(ie-is)*(maxseq-minseq)\n\n       do jj = 1, cocount-1\n          ! Where is X bounded in our color sequence list.\n          if (x == copair(jj)%xseq) then\n             r = copair(jj)%r\n             g = copair(jj)%g\n             b = copair(jj)%b\n          else\n             if ((x >= copair(jj)%xseq) .and. (x <= copair(jj+1)%xseq)) then\n                f = (x - copair(jj)%xseq)/(copair(jj+1)%xseq-copair(jj)%xseq)\n                h = 1.0-f\n                r = (copair(jj)%r*h + copair(jj+1)%r*f)\n                g = (copair(jj)%g*h + copair(jj+1)%g*f)\n                b = (copair(jj)%b*h + copair(jj+1)%b*f)\n                exit\n             endif\n          endif\n       enddo\n       call gscr(1, ii, r, g, b)\n    enddo\n\n  end subroutine set_gscr_color_indices\n\n!****************************************************************************************\n\n  subroutine fillbox(xmin,xmax,ymin,ymax,icol)\n!\n! Draw filled box\n!\n    implicit none\n\n! Input:\n\n    real, intent(in) :: xmin, xmax, ymin, ymax\n    integer, intent(in) :: icol   ! Color index of the color to use.\n\n! Local:\n    integer, parameter :: nra = 4\n    integer, parameter :: nim = 2\n    integer, parameter :: nnd = nra+2*nim\n    integer, parameter :: nst = nra+nim\n\n    real, dimension(nst) :: dst\n    real, dimension(nnd) :: ind\n    real, dimension(nra) :: x4, y4\n    real :: sz\n    integer :: i\n\n    x4(1:2) = xmin\n    x4(3:4) = xmax\n    y4(1) = ymin\n    y4(2:3) = ymax\n    y4(4) = ymin\n\n    call sfsgfa(x4, y4, nra, dst, nst, ind, nnd, icol)\n  end subroutine fillbox\n\n!****************************************************************************************\n\n  subroutine ngsquares(x,y,ndim,xs,icol)\n!\n! Draw filled squares at specified x-y coordinates\n!\n    implicit none\n\n! Input:\n    integer, intent(in) :: ndim   ! Number of filled squares to draw.\n\n    real, intent(in), dimension(ndim) :: x, y ! x-y coordinates of the centers\n    !  of the squares\n\n    integer, intent(in) :: icol   ! Color index of the color to use.\n    real, intent(in) :: xs        ! Size to draw the squares.\n\n! Local:\n    integer, parameter :: nra = 4\n    integer, parameter :: nim = 2\n    integer, parameter :: nnd = nra+2*nim\n    integer, parameter :: nst = nra+nim\n\n    real, dimension(nst) :: dst\n    real, dimension(nnd) :: ind\n    real, dimension(nra) :: x4, y4\n    real :: sz\n    integer :: i\n\n    sz = xs * 0.5 ! Each side is (1/2)* xs away from the center.\n\n    do i = 1, ndim\n       x4(1) = x(i) - sz\n       x4(2) = x4(1)\n       x4(3) = x(i) + sz\n       x4(4) = x4(3)\n\n       y4(1) = y(i) - sz\n       y4(2) = y(i) + sz\n       y4(3) = y4(2)\n       y4(4) = y4(1)\n\n       call sfsgfa(x4, y4, nra, dst, nst, ind, nnd, icol)\n    enddo\n  end subroutine ngsquares\n\n!****************************************************************************************\n\n  subroutine kwm_color_table(input_string)\n    use kwm_string_utilities\n    implicit none\n    character(len=*), intent(in) :: input_string\n    integer :: istart, iend, iidx\n    integer :: icount, ierr\n    real :: xval\n    character(len=64) :: hcol\n    character(len=1024) :: string\n\n    call initcosq\n\n\n    string = unblank(trim(input_string))\n\n    istart = 1\n    icount = 0\n    iidx = 1\n    do while ( iidx > 0 )\n       iidx = index(string(istart:),',')\n       if (iidx == 0) then\n          iend = len(string) + 1\n       else\n          iend = iidx + istart - 1\n       endif\n\n       if (mod(icount,2) == 0) then\n          read(string(istart:iend-1),*, iostat=ierr) xval\n          if (ierr /= 0) then\n             write(*,'(\"Cannot read float from string: #\",A,\"#\")') string(istart:iend-1)\n             stop\n          endif\n       else\n          hcol = string(istart:iend-1)\n          call addcosq(xval, trim(hcol))\n       endif\n\n       istart = iend+1\n       icount = icount + 1\n\n    enddo\n  end subroutine kwm_color_table\n\n!****************************************************************************************\n\n  subroutine find_good_range(ymin, ymax, expn, irange)\n    !\n    ! Given an initial <ymin> and <ymax> (minimum and maximum of some field), \n    ! return \"good round numbers\" for <ymin> and <ymax>.\n    ! <irange> is the number of steps between our good round <ymin> and good round <ymax>\n    ! <expn> is the power-of-ten scaling applied to get our round numbers.\n    !\n    ! There are <irange> steps of size 10.0**<expn> between output values of <ymin> and <ymax>\n    !\n    implicit none\n    real, intent(inout)  :: ymin\n    real, intent(inout)  :: ymax\n    integer, intent(out) :: expn\n    integer, intent(out) :: irange\n\n    integer :: iymin\n    integer :: iymax\n\n    expn = floor(log10(ymax-ymin)) - 1\n\n    iymin = floor   ( (10.0**(real(-expn))) * ymin )\n    iymax = ceiling ( (10.0**(real(-expn))) * ymax )\n    irange = (iymax-iymin)\n\n    ! If we've got too many steps between iymin and iymax,\n    ! then shift to the next power-of-ten for our scaling.\n    if (irange > 20) then\n       iymin = floor  (real(iymin)*0.1)\n       iymax = ceiling(real(iymax)*0.1)\n       expn = expn + 1\n       irange = (iymax-iymin)\n    endif\n\n    ymin = real(iymin) * 10.0**(real(expn))\n    ymax = real(iymax) * 10.0**(real(expn))\n\n  end subroutine find_good_range\n\n!****************************************************************************************\n\n  subroutine line_in_color_integer(x1, y1, x2, y2, color, line_width)\n    !\n    ! Draw a straight line from point (x1,y1) to point (x2,y2).\n    ! The optional <color> can adjust the line color.\n    ! The optional <line_width> can adjust the line width.\n    !\n    ! At the end of the routine, the preset color and line width\n    ! revert back to the values in place before the subroutine was called.\n    implicit none\n    real,              intent(in) :: x1, y1, x2, y2\n    integer,           intent(in) :: color\n    real,    optional, intent(in) :: line_width\n\n    integer :: ierr, color_save\n    real    :: line_width_save\n\n    if (present(line_width)) then\n       call gqlwsc(ierr, line_width_save)\n       call gslwsc(line_width)\n    endif\n\n    call gqplci(ierr, color_save)\n    call gsplci(color)\n\n    call frstpt(x1,y1)\n    call vector(x2,y2)\n    call plotif(0., 0., 2)\n\n    call gsplci(color_save)\n\n    if (present(line_width)) then\n       call gslwsc(line_width_save)\n    endif\n\n  end subroutine line_in_color_integer\n\n  subroutine line_in_color_string(x1, y1, x2, y2, color, line_width)\n    !\n    ! Draw a straight line from point (x1,y1) to point (x2,y2).\n    ! The optional <color> can adjust the line color.\n    ! The optional <line_width> can adjust the line width.\n    !\n    ! At the end of the routine, the preset color and line width\n    ! revert back to the values in place before the subroutine was called.\n    implicit none\n    real,                       intent(in) :: x1, y1, x2, y2\n    character(len=*),           intent(in) :: color\n    real,             optional, intent(in) :: line_width\n\n    integer :: ierr, color_save\n    real    :: line_width_save\n\n    if (present(line_width)) then\n       call gqlwsc(ierr, line_width_save)\n       call gslwsc(line_width)\n    endif\n\n    call gqplci(ierr, color_save)\n    call gsplci(color_index(color))\n\n    call frstpt(x1,y1)\n    call vector(x2,y2)\n    call plotif(0., 0., 2)\n\n    call gsplci(color_save)\n\n    if (present(line_width)) then\n       call gslwsc(line_width_save)\n    endif\n\n  end subroutine line_in_color_string\n\n!****************************************************************************************\n\n  subroutine fillpolygon(x,y,n,icol)\n    !\n    ! Draw filled polygon\n    !\n    implicit none\n\n    ! Input:\n\n    integer,            intent(in) :: n      ! Number of points defining the polygon\n    real, dimension(n), intent(in) :: x      ! X-coordinates of the points\n    real, dimension(n), intent(in) :: y      ! Y-coordinates of the points\n    integer,            intent(in) :: icol   ! Color index of the color to use.\n\n    ! Local:\n    integer, parameter :: nra = 400\n    integer, parameter :: nim = nra\n    integer, parameter :: nnd = nra+2*nim\n    integer, parameter :: nst = nra+nim\n\n    real, dimension(nst) :: dst\n    real, dimension(nnd) :: ind\n    real :: sz\n    integer :: i\n\n    if (n > nra) then\n       write(*,'(\"N   = \", I10)') n\n       write(*,'(\"NRA = \", I10)') nra\n       stop \"Boost parameter NRA in subroutine FILLPOLYGON\"\n    endif\n\n    call sfsgfa(x, y, n, dst, nst, ind, nnd, icol)\n\n  end subroutine fillpolygon\n\n!****************************************************************************************\n\n  subroutine connect_the_dots(x, y, n, color, line_width, on_missing)\n    !\n    ! Given paired arrays X and Y, each of size N, connect the dots in order.\n    ! Optional color and line_width settings will override the original settings.\n    ! At the end of the routine, the original color and line_width settings are\n    ! restored.\n    !\n    ! Values more negative than -1.E25 are considered bad data.\n    !    if (on_missing == \"SKIP\") then\n    !        Skip over bad data, connecting all good data points in order.\n    !    else if (on_missing == \"BREAK\") then\n    !        Break the line at a bad data point, restarting at the next good point.\n    !    endif\n    !\n    implicit none\n    integer,                    intent(in) :: n\n    real,         dimension(n), intent(in) :: x\n    real,         dimension(n), intent(in) :: y\n    character(len=*), optional, intent(in) :: color\n    real,             optional, intent(in) :: line_width\n    character(len=*), optional, intent(in) :: on_missing\n\n    integer :: i, ierr, color_save\n    real    :: line_width_save\n    logical :: pd\n    logical :: skip\n\n    if (present(color)) then\n       call gqplci(ierr, color_save)\n       call gsplci(color_index(color))\n    endif\n\n    if (present(line_width)) then\n       call gqlwsc(ierr, line_width_save)\n       call gslwsc(line_width)\n    endif\n\n    if (present(on_missing)) then\n       if (on_missing == \"SKIP\") then\n          skip = .TRUE.\n       else if (on_missing == \"BREAK\") then\n          skip = .FALSE.\n       else\n          write(*,'(\"CONNECT_THE_DOTS:\")')\n          write(*,'(\"   Optional ON_MISSING should be ''SKIP'' or ''BREAK'', not ''\",A,\"''\")') on_missing\n          stop\n       endif\n    else\n       skip = .TRUE.\n    endif\n\n    pd = .FALSE.\n\n    if (skip) then\n       do i = 1, n\n          if (y(i) > -1.E25) then\n             if (pd) then\n                call vector(x(i), y(i))\n             else\n                call frstpt(x(i), y(i))\n                pd = .TRUE.\n             endif\n          endif\n       enddo\n    else\n       do i = 1, n\n          if (y(i) > -1.E25) then\n             if (pd) then\n                call vector(x(i), y(i))\n             else\n                call frstpt(x(i), y(i))\n                pd = .TRUE.\n             endif\n          else\n             if (pd) then\n                call plotif(0., 0., 2)\n                pd = .FALSE.\n             endif\n          endif\n       enddo\n    endif\n    call plotif(0., 0., 2)\n\n    if (present(color)) then\n       call gsplci(color_save)\n    endif\n\n    if (present(line_width)) then\n       call gslwsc(line_width_save)\n    endif\n\n  end subroutine connect_the_dots\n!****************************************************************************************\n\nend module kwm_plot_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/kwm_string_utilities.F",
    "content": "module kwm_string_utilities\n\ncontains\n\n  subroutine strrep(string, rep1, rep2)\n    ! In string 1, replace expression rep1 with expression rep2.\n    ! if rep2 is shorter than rep1, fill the end of the string\n    ! with blanks\n\n    implicit none\n    character(len=*) :: string, rep1, rep2\n    integer :: idx, inlen, len1, len2\n\n    do\n       inlen = len(string)\n       len1 = len(rep1)\n       len2 = len(rep2)\n       idx = index(string, rep1)-1\n\n       if (idx == -1) then\n          return\n       else\n          string = string(1:idx)// rep2 // &\n               string((idx+len1+1):inlen) // &\n               \"                                                    \"\n       endif\n    enddo\n\n  end subroutine strrep\n\n\n  character(len=1024) function unblank(string) result(return_string)\n    ! Remove blanks (and tabs [char(9)] from string\n    implicit none\n    character(len=*), intent(in) :: string\n    integer :: i, j,  lenstr\n\n    return_string = \"\"\n\n    if ( verify(string,\" \"//char(9)) == 0 ) then\n       stop 'String is all blanks.'\n    endif\n\n    j = 0\n    do i = 1, len(string)\n       if ((string(i:i).ne.' ').and.(string(i:i).ne.char(9))) then\n          j = j + 1\n          return_string(j:j) = string(i:i)\n       endif\n    enddo\n\n  end function unblank\n\n!KWM  character function upcase(h)\n!KWM    implicit none\n!KWM    character :: h\n!KWM\n!KWM    if ((ichar(h).ge.96) .and. (ichar(h).le.123)) then\n!KWM       upcase = char(ichar(h)-32)\n!KWM    else\n!KWM       upcase = h\n!KWM    endif\n!KWM\n!KWM  end function upcase\n\n  character(len=256) function upcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \"\"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.96) .and. (ichar(h(i:i)).le.123)) then\n          return_string(i:i) = char(ichar(h(i:i))-32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function upcase\n\n!KWM  character function downcase(h)\n!KWM    implicit none\n!KWM    character h\n!KWM\n!KWM    if ((ichar(h).ge.65) .and. (ichar(h).le.90)) then\n!KWM       downcase = char(ichar(h)+32)\n!KWM    else\n!KWM       downcase = h\n!KWM    endif\n!KWM  end function downcase\n\n  character(len=256) function downcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \"\"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.65) .and. (ichar(h(i:i)).le.90)) then\n          return_string(i:i) = char(ichar(h(i:i))+32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function downcase\n\n\nend module kwm_string_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/lccone.F",
    "content": "subroutine lccone (fsplat,ssplat,sign,confac)\n  real, parameter :: conv=0.01745329251994\n  integer :: sign\n  real :: fsplat,ssplat,confac\n  if (abs(fsplat-ssplat).lt.1.E-2) then\n     confac = sin(fsplat*conv)\n  else\n     confac = log10(cos(fsplat*conv))-log10(cos(ssplat*conv))\n     confac = confac/(log10(tan((45.-float(sign)*fsplat/2.)*conv))-&\n          log10(tan((45.-float(sign)*ssplat/2.)*conv)))\n  endif\nend subroutine lccone\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/llxy_generic.F",
    "content": "subroutine lltoxy_generic (xlat,xlon,x,y,&\n     project,dskm,reflat,reflon,refx,refy,&\n     cenlon,truelat1,truelat2)\n\n!*****************************************************************************!\n!  Notes    - Modeled after XYTOLL in the plots.o library                     !\n!*****************************************************************************!\n\n  implicit none\n\n! Input: ---------------------------------------------------------------------!\n\n  real ::             xlat       ! latitude of the point of interest.\n  real ::             xlon       ! longitude of the point of interest.\n  character(LEN=2) :: project    ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n  real ::             dskm         ! grid distance in km\n  real ::             reflat\n  real ::             reflon\n  real ::             refx\n  real ::             refy\n  real ::             cenlon     ! Grid ratio with respect to MOAD\n  real ::             truelat1   ! True latitude 1, closest to equator\n  real ::             truelat2   ! True latitude 2, closest to pole\n\n! Output: --------------------------------------------------------------------!\n\n  real ::             x          ! x location of the given (lat,lon) point\n  real ::             y          ! y location of the given (lat,lon) point\n\n!  Parameters: ---------------------------------------------------------------!\n\n  real, parameter :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter :: piovr2 = pi/2.\n!  real, parameter :: re = 6370.949     ! the radius of the earth in km\n  real, parameter :: re = 6371.2       ! the radius of the earth in km\n  real, parameter :: ce = 2.*pi*re     ! the circumference of the earth in km\n  real, parameter :: degrad = pi/180.\n\n!  Real variables: -----------------------------------------------------------!\n\n  real          :: flat1\n  real          :: confac            ! cone factor\n  real          :: rcln              ! center longitude in radians  (local)\n  real          :: dj                ! distance from pole to point  (local)\n  real          :: di                ! distance from the central\n                                     !  meridian to the point        (local)\n  real          :: bm                ! calculation variable         (local)\n\n  real :: rflt, rfln, rlat, rlon, diovrdj, disdjs, ri, rj\n  real :: ct1, st1, tt1, drp\n  real :: isn, pi2\n  real :: londiff\n\n!****************************  subroutine begin  *****************************!\n\n\n  rlat =  xlat * degrad\n  rlon =  xlon * degrad\n  rcln = cenlon * degrad\n  flat1 = truelat1 * degrad\n  rflt = reflat * degrad\n  rfln = reflon * degrad\n\n  if ((xlon - cenlon) < -180) then\n     londiff = ((xlon-cenlon)+360.)*degrad\n  else if ((xlon - cenlon) > 180) then\n     londiff = ((xlon-cenlon)-360.)*degrad\n  else\n     londiff = (xlon-cenlon)*degrad\n  endif\n\n\n  if (project(1:2) .eq. 'ME') then\n\n     ct1 = re*cos(flat1)\n     dj = ct1 * log(tan (0.5*(rlat + piovr2)))\n     di = ct1 * (rlon - rfln)\n     y = refy +(dj + ct1 * log(cos(rflt)/(1 + sin(rflt))))/dskm\n     x = refx + di/dskm\n\n  else if (project(1:2) .eq. 'CE') then\n\n!KWM     dj = re*(rlat-rflt)\n!KWM     di = re*(rlon-rfln)\n!KWM     y = refy + dj/dskm\n!KWM     x = refx + di/dskm\n\n     ! NOTE:  Cylindrical Equidistant grid increment expressed in terms\n     ! of thousandths of degrees!\n     !  Calculate the distance from the horizontal axis to (J,I)\n     dj = xlat-reflat\n     di = xlon-reflon\n     y = refy + (dj/dskm)\n     x = refx + (di/dskm)\n\n  else if (project(1:2) .eq. 'LC') then\n\n     isn = sign(1.0, truelat2)\n     pi2 = piovr2*isn\n\n     call lccone(truelat1,truelat2,int(sign(1.0, truelat2)),confac)\n     tt1 = tan((pi2 - flat1)*0.5) ! Tangent Term 1.\n     st1 = sin (pi2 - flat1) * re/(confac*dskm)     ! Sine Term 1.\n     bm =  tan((pi2 - rlat)*0.5)\n     if ((rlon-rcln) > pi) then\n        diovrdj = -tan(((rlon-rcln)-2.*pi)*confac)\n     elseif ((rlon-rcln) < -pi) then\n        diovrdj = -tan(((rlon-rcln)+2.*pi)*confac)\n     else\n        diovrdj = -tan((rlon-rcln)*confac)\n     endif\n     disdjs = ( (bm/tt1)**confac * st1)**2\n     ! Dj: y distance (km) from pole to given x/y point.\n     dj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n     ! Di: x distance (km) from central longitude to given x/y point.\n     di = dj * diovrdj\n\n     bm = tan((pi2-rflt)*0.5)\n     if ((rfln-rcln) > pi) then\n        diovrdj = -tan(((rfln-rcln)-2.*pi)*confac)\n     else if ((rfln-rcln) < -pi) then\n        diovrdj = -tan(((rfln-rcln)+2.*pi)*confac)\n     else\n        diovrdj = -tan((rfln - rcln)*confac)\n     endif\n     disdjs = ( (bm/tt1)**confac * st1)**2\n     ! Rj: y distance (km) from pole to reference point.\n     rj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n     ! Ri: x distance (km) from central longitude to reference x/y point.\n     ri = rj * diovrdj\n     y = refy + isn*(dj - rj)\n     x = refx + (di - ri)\n\n  else if (project(1:2) .eq. 'ST') then\n\n     isn = sign(1.0, truelat1)\n     pi2 = piovr2*isn\n\n     diovrdj = -tan(rfln-rcln)\n     bm = (re/dskm)*tan(0.5*(pi2-rflt))\n     disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n     ! RJ:  Distance from pole to reference latitude along the center lon\n     rj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rfln-rcln))\n     ! RI:  Distance from center reference to requested point rlat, rlon.\n     ri = rj * diovrdj\n     diovrdj = -tan(rlon-rcln)\n     bm = (re/dskm)*tan(0.5*(pi2-rlat))\n     disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n     dj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rlon-rcln))\n     di = dj * diovrdj\n     y = refy + isn*(dj-rj)\n     x = refx + (di-ri)\n  endif\n\n!*****************************  Subroutine End  ******************************!\n\nend subroutine lltoxy_generic\n\nsubroutine xytoll_generic (x,y,xlat,xlon,&\n     project,dskm,reflat,reflon,refx,refy,&\n     cenlon, truelat1,truelat2)\n\n!*****************************************************************************!\n!  xytoll                                                                     !\n!  Purpose  - To  transform  mesoscale grid point coordinates (x,y) into      !\n!             latitude and longitude coordinates.                             !\n!                                                                             !\n!  On entry - X  and  Y are an ordered pair representing a grid point in  the !\n!             mesoscale grid.                                                 !\n!                                                                             !\n!  On exit  - XLAT, XLON contain  the latitude and longitude respectively     !\n!             that resulted from the transformation.                          !\n!                                                                             !\n!*****************************************************************************!\n  implicit none\n\n! Input\n  real ::             x         ! x (i) coordinate of point of interest\n  real ::             y         ! y (j) coordinate of point of interest\n  character(LEN=2) :: project   ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n  real ::             dskm      ! grid distance in km\n  real ::             reflat    ! latitude of the reference point\n  real ::             reflon    ! longitude of the reference point\n  real ::             refx\n  real ::             refy\n  real ::             cenlon    ! longitude of the center of the projection\n  real ::             truelat1  ! True latitude 1.\n  real ::             truelat2  ! True latitude 2.\n\n! Output\n  real ::             xlat      ! latitude of point (x,y)\n  real ::             xlon      ! longitude of point (x,y)\n\n! Parameters\n\n  real, parameter :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter :: piovr2 = pi/2.\n  real, parameter :: twopi  = pi*2.\n!  real, parameter :: re = 6370.949     ! the radius of the earth in km\n  real, parameter :: re = 6371.2\n  real, parameter :: degrad = pi/180.\n\n!  Real variables\n\n  real ::            confac           ! cone factor\n  real ::            rfln             ! reference longitude in radians  (local)\n  real ::            rflt             ! reference latitude in radians   (local)\n  real ::            rcln             ! center longitude in radians  (local)\n  real ::            dj, drp, djj     ! distance from the central\n!                                       meridian to the point        (local)\n  real ::            di,dii           ! distance from pole to point  (local)\n  real ::            bm               ! calculation variable         (local)\n  real ::            flat1\n  real ::            ct1, tt1, tt2, pi2\n  integer :: isn\n!****************************  subroutine begin  *****************************!\n\n  rflt = reflat * degrad\n  rfln = reflon * degrad\n  rcln = cenlon * degrad\n  flat1 = truelat1 * degrad\n\n!  If the projection is mercator ('ME') then ...\n\n  if (project(1:2) .eq. 'ME') then\n     di = (x-refx) * dskm\n     !  Calculate the distance the point in question is from the pole\n     dj = -re * cos(flat1)*log(cos(rflt)/(1 + sin(rflt))) + &\n          (y - refy) * dskm\n     !  Calculate the latitude desired in radians\n     xlat = 2.0 * atan(exp(dj/(re*cos(flat1)))) - piovr2\n     !  Calculate the longitude desired in radians\n     xlon = rfln + di/(re*cos(flat1))\n\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n\n! If the projection is cylindrical equidistant ('CE') then ...\n  else if (project(1:2) .eq. 'CE') then\n     ! NOTE:  Cylindrical Equidistant grid increment expressed in terms\n     ! of thousandths of degrees!\n     di = (x-refx) * dskm\n     !  Calculate the distance from the horizontal axis to (J,I)\n     dj = (y-refy) * dskm\n     !  Determine the shift north-south\n     xlat = reflat + dj\n     !  Determine the shift east-west\n     xlon = reflon + di\n\n! If the projection is lambert conic conformal ('LC') then ...\n  else if (project(1:2) .eq. 'LC') then\n\n     isn = sign(1.0, truelat2)\n     pi2 = piovr2*isn\n\n     call lccone(truelat1,truelat2,isn,confac)\n\n     tt1 = tan((pi2 - flat1)*0.5)    ! Tangent Term 1.\n     tt2 = tan((pi2 - rflt  )*0.5)    ! Tangent Term 2.\n     ct1 = -cos(flat1) * re/confac   ! cosine Term 1.\n\n     ! Calculate the (projected) distance from the pole to\n     ! the reference lat/lon.\n     drp = ct1 * (tt2/tt1)**confac\n     ! Now from the pole to the reference y along the center lon.\n     djj = drp * cos((rcln-rfln)*confac)\n\n     ! Now from the pole to the requested y along the center lon.\n     dj = djj + isn * ((y-refy)*dskm)\n     ! Now the (projected) distance from center longitude to reference x\n     dii = drp*sin((rcln-rfln)*confac)\n     ! And now from center longitude to requested X\n     di = dii + ((x-refx)*dskm)\n     !  Calculate the Big Messy equation\n     bm = tt1 * (sqrt(di**2+dj**2) /  abs(ct1))**(1.0/confac)\n     !  Calculate the desired latitude in radians\n     xlat = pi2 - 2.0*atan(bm)\n     !  Calculate the desired longitude in radians\n     xlon = rcln + (1.0/confac) * atan2(di,-dj)\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n\n!  If the projection is polar stereographic ('ST') then ...\n\n  else if (project(1:2) .eq. 'ST') then\n\n     isn = sign(1.0, truelat1)\n     pi2 = piovr2*isn\n\n\n!  Calculate the (projected) y-distance I,J lies from the pole\n\n     drp = -re*cos(rflt) * (1.0 + cos(pi2-flat1)) / (1.0 + cos(pi2-rflt))\n     djj = drp * cos(rcln-rfln)\n     dj = djj + isn*( (y-refy) * dskm )\n     dii = drp * sin(rcln-rfln)\n     di = dii + ((x-refx)*dskm)\n     ! Calculate the Big Messy quantity as would be done for LC\n     ! projections.  This quantity is different in value, same\n     ! in purpose of BM above\n     bm = (1.0/re) * sqrt(di*di + dj*dj) / (1.0 + cos(pi2-flat1))\n     !  Calculate the desired latitude in radians\n     xlat = pi2 - isn*2.0 * atan(bm)\n     !  Calculate the desired longitude in radians\n     xlon = rcln + atan2(di,-dj)\n\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n  else\n     print*, 'Unrecognized project:  ', project\n     stop\n  end if\n\n!  Make sure no values are greater than 180 degrees and none\n!  are less than -180 degrees\n\n  if (xlon .gt. 180.0)  xlon = xlon - 360.0\n  if (xlon .lt. -180.0) xlon = xlon + 360.0\n\n!*****************************  Subroutine End  ******************************!\n\nend subroutine xytoll_generic\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/module_hd.F",
    "content": "module module_hd\n  use netcdf\n  type nf_structure\n     integer :: ncid\n     integer :: nvar\n     integer :: ndim\n     character(len=NF90_MAX_NAME), dimension(NF90_MAX_DIMS) :: dimname\n     integer, dimension(NF90_MAX_DIMS) :: dimlen\n     integer :: tdim\n     integer :: idim\n     integer :: jdim\n     integer :: kdim\n     integer :: map_proj\n     real    :: dskm\n     real    :: xlonc\n     real    :: truelat1\n     real    :: truelat2\n     real    :: reflat\n     real    :: reflon\n     real    :: refx\n     real    :: refy\n  end type nf_structure\n\n  interface netcdf_get_field\n     module procedure netcdf_get_field_2d, netcdf_get_field_3d\n  end interface\n\ncontains\n\n  subroutine netcdf_get_time(nfstruct, name, time_index, time_return)\n    implicit none\n    type(nf_structure), intent(in) :: nfstruct\n    character(len=*),   intent(in) :: name\n    integer,            intent(in) :: time_index\n    integer :: ncid, varid, dimid\n    integer :: iret, DateStrLen\n    integer, dimension(2) :: start, nfcount\n    character(len=24) :: time_return\n\n    ncid = nfstruct%ncid\n\n    ! We need the varid of this field\n    iret = nf90_inq_varid(ncid, name, varid)\n    if (iret /= 0) then\n       write(*,'(\"Variable = ''\",A,\"''\")') name\n       write(*,'(\"NF90_INQ_VARID:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_inq_dimid(ncid, \"DateStrLen\", dimid)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQ_DIMID (for DateStrLen):  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_inquire_dimension(ncid, dimid, len=DateStrLen)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQUIRE_DIMENSION:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    start(1) = 1\n    start(2) = time_index\n    nfcount(1) = DateStrLen\n    nfcount(2) = 1\n\n    iret = nf90_get_var(ncid, varid, time_return, start, nfcount)\n    if (iret /= 0) then\n       write(*,'(\"netcdf_get_time:  NF90_GET_VAR:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n\n  end subroutine netcdf_get_time\n\n  subroutine netcdf_get_field_2d(nfstruct, name, time_index, ptr2d)\n    implicit none\n    type(nf_structure), intent(in) :: nfstruct\n    integer, intent(in) :: time_index\n    real, pointer, dimension(:,:) :: ptr2d\n    character(len=*), intent(in) :: name\n    integer :: iret\n    integer, dimension(20) :: start, nfcount\n    integer :: varid\n    integer, dimension(20) :: dimids\n    integer :: ndims\n    integer :: ncid\n\n    ncid = nfstruct%ncid\n\n    ! We need the varid of this field\n    iret = nf90_inq_varid(ncid, name, varid)\n    if (iret /= 0) then\n       write(*,'(\"Variable = ''\",A,\"''\")') name\n       write(*,'(\"NF90_INQ_VARID:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    ! We need the dimensions of this variable\n    iret = nf90_inquire_variable(ncid, varid, ndims=ndims, dimids=dimids)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQUIRE_VARIABLE:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n\n    if (ndims == 3) then\n       allocate(ptr2d(nfstruct%idim,nfstruct%jdim))\n       start(1) = 1\n       start(2) = 1\n       start(3) = time_index\n       nfcount(1) = nfstruct%idim\n       nfcount(2) = nfstruct%jdim\n       nfcount(3) = 1\n    else\n       print*, 'ndim = ', nfstruct%ndim\n       print*, 'name = ', name\n       stop \"NETCDF_GET_FIELD: No can do with these dimensions.\"\n    endif\n\n    iret = nf90_get_var(ncid, varid, ptr2d, start, nfcount)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_VAR:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n  end subroutine netcdf_get_field_2d\n\n  subroutine netcdf_get_field_3d(nfstruct, name, time_index, ptr3d)\n    implicit none\n    type(nf_structure), intent(in) :: nfstruct\n    integer, intent(in) :: time_index\n    real, pointer, dimension(:,:,:) :: ptr3d\n    character(len=*), intent(in) :: name\n    integer :: iret\n    integer, dimension(20) :: start, nfcount\n    integer :: varid\n    integer, dimension(20) :: dimids\n    integer :: ndims\n    integer :: ncid\n\n    ncid = nfstruct%ncid\n\n    ! We need the varid of this field\n    iret = nf90_inq_varid(ncid, name, varid)\n    if (iret /= 0) then\n       write(*,'(\"Variable = ''\",A,\"''\")') name\n       write(*,'(\"NF90_INQ_VARID:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    ! We need the dimensions of this variable\n    iret = nf90_inquire_variable(ncid, varid, ndims=ndims, dimids=dimids)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQUIRE_VARIABLE:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n\n    if (ndims == 4) then\n       allocate(ptr3d(nfstruct%idim,nfstruct%jdim,nfstruct%kdim))\n       start(1) = 1\n       start(2) = 1\n       start(3) = 1\n       start(4) = time_index\n       nfcount(1) = nfstruct%idim\n       nfcount(2) = nfstruct%jdim\n       nfcount(3) = nfstruct%kdim\n       nfcount(4) = 1\n    else\n       print*, 'ndim = ', nfstruct%ndim\n       print*, 'name = ', name\n       stop \"NETCDF_GET_FIELD: No can do with these dimensions.\"\n    endif\n\n    iret = nf90_get_var(ncid, varid, ptr3d, start, nfcount)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_VAR:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n  end subroutine netcdf_get_field_3d\n\n  subroutine netcdf_open(flnm, nfstruct)\n    ! Opens a netcdf file and fills the fields in nfstruct for:\n    !      ncid\n    !      nvar\n    !      ndim\n    !      dimname\n    !      dimlen\n    !      tdim\n    !      idim\n    !      jdim\n    !      kdim\n    !   etc.\n    ! use netcdf\n    ! use module_hd\n    implicit none\n\n    character(len=*), intent(in)    :: flnm\n    type(nf_structure), intent(out) :: nfstruct\n\n    integer :: iret\n    integer :: ncid\n    integer :: nvar\n    integer :: ndim\n    integer :: dimid\n    character(len=NF90_MAX_NAME), dimension(NF90_MAX_DIMS) :: dimname\n    integer, dimension(NF90_MAX_DIMS) :: dimlen\n    integer :: tdim, idim, jdim, kdim, map_proj\n    real    :: dskm, truelat1, truelat2, xlonc\n    real    :: reflat, reflon\n    real    :: dxm\n\n    tdim = 0\n    idim = 0\n    jdim = 0\n    kdim = 1\n\n    iret = nf90_open(trim(flnm), NF90_NOWRITE, ncid)\n    if (iret /= 0) then\n       write(*,'(\"***** ERROR EXIT *****\")')\n       write(*,'(/,5x,\"NF90_OPEN:  \",A)') nf90_strerror(iret)\n       write(*,'(8x,A,/)') \"FILE = '\"//trim(flnm)//\"'\"\n       write(*,'(\"***** ERROR EXIT *****\")')\n       stop\n    endif\n\n    iret = nf90_inquire(ncid, nVariables=nvar,  nDimensions=ndim)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQUIRE nVariables:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n!KWM    print*, 'nvar = ', nvar, '  ndim = ', ndim\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", map_proj)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for MAP_PROJ:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\", dxm)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for DX:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n    dskm = dxm * 1.E-3\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for TRUELAT1:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for TRUELAT2:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", xlonc)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for STAND_LON:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"LAT1\", reflat)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for LAT1:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"LON1\", reflon)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for LON1:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    do dimid = 1, ndim\n       iret = nf90_inquire_dimension(ncid, dimid, dimname(dimid), dimlen(dimid))\n       if (iret /= 0) then\n          write(*,'(\"NF90_INQUIRE_DIMENSION:  \",A)') nf90_strerror(iret)\n          stop\n       endif\n!KWM       write(*,'(\"Dimension = \", A20, 2x, i5)') dimname(dimid), dimlen(dimid)\n       if (dimname(dimid) == \"Times\") tdim = dimlen(dimid)\n       if (dimname(dimid) == \"west_east\") idim = dimlen(dimid)\n       if (dimname(dimid) == \"south_north\") jdim = dimlen(dimid)\n       if (dimname(dimid) == \"soil_layers_stag\") kdim = dimlen(dimid)\n    enddo\n\n    nfstruct%ncid = ncid\n    nfstruct%nvar = nvar\n    nfstruct%ndim = ndim\n    nfstruct%dimname = dimname\n    nfstruct%dimlen = dimlen\n    nfstruct%tdim = tdim\n    nfstruct%idim = idim\n    nfstruct%jdim = jdim\n    nfstruct%kdim = kdim\n    nfstruct%map_proj = map_proj\n    nfstruct%truelat1 = truelat1\n    nfstruct%truelat2 = truelat2\n    nfstruct%dskm    = dskm\n    nfstruct%xlonc    = xlonc\n    nfstruct%reflat   = reflat\n    nfstruct%reflon   = reflon\n    nfstruct%refx     = 1.0\n    nfstruct%refy     = 1.0\n  end subroutine netcdf_open\n\n  subroutine lltoxy_hd(lat, lon, x, y, nfstruct)\n    real, intent(in) :: lat, lon\n    real, intent(out) :: x, y\n    type (nf_structure), intent(in) :: nfstruct\n\n    select case (nfstruct%map_proj)\n    case (1)\n       project = \"LC\"\n    case (2)\n       project = \"ST\"\n    case (3)\n       project = \"ME\"\n    case default\n       print*, 'MODULE_HD:  LLTOXY_HD:  Put the map projection in:  proj = ', nfstruct%map_proj\n       stop\n    end select\n\n    call lltoxy_generic(lat, lon, x, y, &\n         project,nfstruct%dskm,nfstruct%reflat,nfstruct%reflon,nfstruct%refx,nfstruct%refy, &\n         nfstruct%xlonc,nfstruct%truelat1,nfstruct%truelat2)\n\n  end subroutine lltoxy_hd\n\n#if defined( _NCARGKS_ )\n\n  subroutine wrfmap(nfstruct)\n    ! use kwm_plot_utilities\n    implicit none\n    type(nf_structure), intent(in) :: nfstruct\n\n    integer :: jprj\n    real :: plat, plon, rota\n    real :: plm1, plm2, plm3, plm4\n    integer :: jlts = 2;\n    integer :: jgrd = 0;\n    integer :: iout = 4;\n    integer :: idot = 0;\n    integer :: ierr\n    character(len=2) :: project\n\n    if (nfstruct%map_proj == 1) then\n       jprj = 3\n       plat = nfstruct%truelat1\n       plon = nfstruct%xlonc\n       rota = nfstruct%truelat2\n       project = \"LC\"\n       call xytoll_generic(1.0, 1.0, plm1, plm2, &\n            project,nfstruct%dskm,nfstruct%reflat,nfstruct%reflon,nfstruct%refx,nfstruct%refy,&\n            nfstruct%xlonc,nfstruct%truelat1,nfstruct%truelat2)\n\n       call xytoll_generic(float(nfstruct%idim), float(nfstruct%jdim), plm3, plm4, &\n            project,nfstruct%dskm,nfstruct%reflat,nfstruct%reflon,nfstruct%refx,nfstruct%refy,&\n            nfstruct%xlonc,nfstruct%truelat1,nfstruct%truelat2)\n    else\n       print*, 'Put the map projection in:  proj = ', nfstruct%map_proj\n       stop\n    endif\n\n    print*, 'call supmap:  ', jprj, plat, plon, rota, plm1, plm2, plm3, plm4, jlts, jgrd, iout, idot, ierr\n    call supmap(jprj, plat, plon, rota, plm1, plm2, plm3, plm4, jlts, jgrd, iout, idot, ierr)\n\n  end subroutine wrfmap\n\n#endif\n\nend module module_hd\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/Fluxes_statistics/namelist.fluxstats",
    "content": "&fluxstats\n\nfluxobs_directory = \"/scholar/kmanning/LSM_STEP/IHOP_obs/LE_corrected_from_SEB\"\n\nldasout_directory = \"/scholar2/kmanning/VERY_TEMPORARY_HRLDAS/Run_3.2\"\nldasout_directory = \"/scholar/kmanning/more_hrldas/hrldas-v3.1/Run\"\n\n\n/\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/Makefile",
    "content": "SHELL=/bin/sh\n.SUFFIXES:\t\n.SUFFIXES:\t.c .o .F\nOBJS=\trdmet.o \\\n\trdsom_mem.o \\\n\trdbz.o \\\n\tkwm_date_utilities.o \\\n\tkwm_plot_utilities.o \\\n\tkwm_string_utilities.o \\\n\tmodule_hd.o \\\n\tlccone.o llxy_generic.o get_unused_unit.o\n#\n#\nBZDIR=\t/home/kmanning/bzip2-1.0.2\nCC=cc\n\n# FC=ifort\n# FFLAGS  = -free -convert big_endian -g -check bounds\n\nFC=pgf90\nFFLAGS  = -Mfree -byteswapio\n\nCCFLAGS = -I. -I$(BZDIR)\nLDFLAGS=\nFINCLUDES=\t-I. -I$(NETCDF)/include\nLIBS=\t-L$(NETCDF)/lib -lnetcdf -L$(BZDIR) -lbz2 \\\n\t-L$(NCARG_ROOT)/lib -lncarg -lncarg_gks -lncarg_c \\\n\t-L/usr/X11R6/lib -lX11 \\\n\t-L/usr/lib/gcc/i386-redhat-linux/3.4.6 -lg2c \n\nRM = \trm -f\nCMD=\tokmeso_statistics.exe\n\n# Lines from here on down should not need to be changed.  They are the\n# actual rules which make uses to build $(CMD).\n#\nall:\t$(CMD)\n\n$(CMD):\t$(OBJS)\n\t$(FC) -o $(CMD) $(OBJS) $(LIBS)\n\n.F.o:\n\t$(FC) -c $(FINCLUDES) $(FFLAGS) $(<)\n\n.c.o:\n\t$(CC) -c $(CCFLAGS) $(<)\n\nclean:\n\t$(RM) $(CMD) *.o *~ *.mod\n#\nkwm_plot_utilities.o:\tkwm_string_utilities.o\nrdsom_mem.o:\t\tkwm_date_utilities.o\nrdsom_mem.o:\t\tkwm_plot_utilities.o\nrdsom_mem.o:\t\tmodule_hd.o\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/get_unused_unit.F",
    "content": "integer function get_unused_unit() result(iunit)\n  implicit none\n  integer :: i\n  logical :: used\n\n  do i = 11, 255\n     inquire(unit=i, opened=used)\n     if (.not. used) then\n        iunit = i\n        return\n     endif\n  enddo\n\n  print*, \"GET_UNUSED_UNIT:  \"\n  print*, \"      Problem getting unused unit number.\"\n  call abort()\n\nend function get_unused_unit\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/kwm_date_utilities.F",
    "content": "module kwm_date_utilities\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n!  From old date ('YYYY-MM-DD HH:MM:SS.ffff') and\n!  delta-time, compute the new date.\n\n!  on entry     -  odate  -  the old hdate.\n!                  idt    -  the change in time\n\n!  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n\n!  Local Variables\n\n!  yrold    -  indicates the year associated with \"odate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scold    -  indicates the second associated with \"odate\"\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n\n!  mday     -  a list assigning the number of days in each month\n\n!  i        -  loop counter\n!  nday     -  the integer number of days represented by \"idt\"\n!  nhour    -  the integer number of hours in \"idt\" after taking out\n!              all the whole days\n!  nmin     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days and whole hours.\n!  nsec     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days, whole hours, and whole minutes.\n\n    integer :: nlen, olen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n\n    logical :: punctuated\n    logical :: idtdy, idthr, idtmin, idtsec, idtfrac\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n!  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    olen = len(odate)\n    if (punctuated) then\n       if (olen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n    endif\n\n!  Use internal READ statements to convert the CHARACTER string\n!  date into INTEGER components.\n\n    idtdy   = .FALSE.\n    idthr   = .FALSE.\n    idtmin  = .FALSE.\n    idtsec  = .FALSE.\n    idtfrac = .FALSE.\n    read(odate(1:4),  '(i4)') yrold\n    if (punctuated) then\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.13) then\n          idthr = .TRUE.\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             idtmin = .TRUE.\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                idtsec = .TRUE.\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   idtfrac = .TRUE.\n                   read(odate(21:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    else ! Not punctuated\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.10) then\n          idthr = .TRUE.\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             idtmin = .TRUE.\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                idtsec = .TRUE.\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   idtfrac = .TRUE.\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n!  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n!  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n!  Check that the fractional part  of ODATE makes sense.\n\n!KWM      IF ((scold.GT.59).or.(scold.LT.0)) THEN\n!KWM         WRITE(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n!KWM         opass = .FALSE.\n!KWM      END IF\n\n    if (.not.opass) then\n       write(*,*) 'Crazy ODATE: ', odate(1:olen), olen\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n\n!  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (idtfrac) then !idt should be in fractions of seconds\n       if (punctuated) then\n          ifrc = olen-14\n       else\n          ifrc = olen-20\n       endif\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (idtsec) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (idtmin) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (idthr) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (idtdy) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            olen\n       write(*,*) odate(1:olen)\n       call abort()\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n!  Now construct the new mdate\n\n    nlen = LEN(ndate)\n\n    if (punctuated) then\n\n       if (nlen.gt.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:19)//'.'//hfrc(31-nlen:10)\n\n       else if (nlen.eq.19.or.nlen.eq.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n          if (nlen.eq.20) ndate = ndate(1:19)//'.'\n\n       else if (nlen.eq.16) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (nlen.eq.13) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n       if (olen.ge.11) ndate(11:11) = sp\n\n    else\n\n       if (nlen.gt.20) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:18)//hfrc(31-nlen:10)\n\n       else if (nlen.eq.14) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n14        format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.12) then\n          write(ndate,12) yrnew, monew, dynew, hrnew, minew\n12        format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,210) yrnew, monew, dynew, hrnew\n210       format(i4,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.8) then\n          write(ndate,8) yrnew, monew, dynew\n8         format(i4,i2.2,i2.2)\n\n       else\n          stop \"DATELEN PROBLEM\"\n       end if\n    endif\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n    implicit none\n\n!  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n!  compute the time difference.\n\n!  on entry     -  newdate  -  the new hdate.\n!                  olddate  -  the old hdate.\n\n!  on exit      -  idt    -  the change in time.\n!                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n!  Local Variables\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  yrold    -  indicates the year associated with \"odate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n!  scold    -  indicates the second associated with \"odate\"\n!  i        -  loop counter\n!  mday     -  a list assigning the number of days in each month\n\n! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    character (len=24) :: tdate\n    integer :: olen, nlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), i, newdys, olddys\n    logical :: npass, opass\n    integer :: isign\n    integer :: ifrc\n\n    logical :: punctuated\n\n    olen = len(olddate)\n    nlen = len(newdate)\n    if (nlen.ne.olen) then\n       write(*,'(\"GETH_IDTS: NLEN /= OLEN: \", A, 3x, A)') newdate(1:nlen), olddate(1:olen)\n       call abort\n    endif\n\n    if (olddate.gt.newdate) then\n       isign = -1\n\n       ifrc = olen\n       olen = nlen\n       nlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       isign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n\n!  Break down old and new hdates into parts\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(odate(1:4),  '(i4)') yrold\n    read(ndate(1:4),  '(i4)') yrnew\n\n    if (punctuated) then\n\n!  Break down old hdate into parts\n\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       if (olen.ge.13) then\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   if (olen.eq.21) then\n                      read(odate(21:21),'(i1)') frold\n                   else if (olen.eq.22) then\n                      read(odate(21:22),'(i2)') frold\n                   else if (olen.eq.23) then\n                      read(odate(21:23),'(i3)') frold\n                   else if (olen.eq.24) then\n                      read(odate(21:24),'(i4)') frold\n                   endif\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(6:7),  '(i2)') monew\n       read(ndate(9:10), '(i2)') dynew\n       if (nlen.ge.13) then\n          read(ndate(12:13),'(i2)') hrnew\n          if (nlen.ge.16) then\n             read(ndate(15:16),'(i2)') minew\n             if (nlen.ge.19) then\n                read(ndate(18:19),'(i2)') scnew\n                if (nlen.gt.20) then\n                   read(ndate(21:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    else\n\n!  Break down old hdate into parts\n\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       if (olen.ge.10) then\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(5:6),  '(i2)') monew\n       read(ndate(7:8), '(i2)') dynew\n       if (nlen.ge.10) then\n          read(ndate(9:10),'(i2)') hrnew\n          if (nlen.ge.12) then\n             read(ndate(11:12),'(i2)') minew\n             if (nlen.ge.14) then\n                read(ndate(13:14),'(i2)') scnew\n                if (nlen.ge.15) then\n                   read(ndate(15:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n!  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n       print*, 'GETH_IDTS:  Month of NDATE = ', monew\n       npass = .false.\n    end if\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n       opass = .false.\n    end if\n\n!  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    endif\n\n!  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    end if\n\n!  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n       npass = .false.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n       opass = .false.\n    end if\n\n!  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n       npass = .false.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n       opass = .false.\n    end if\n\n!  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n       npass = .false.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'Screwy NDATE: ', ndate(1:nlen)\n       call abort()\n    end if\n\n    if (.not. opass) then\n       print*, 'Screwy ODATE: ', odate(1:olen)\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n!  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n!  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n!  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (punctuated) then\n       if (olen.gt.10) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.13) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.16) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.20) then\n                   ifrc = olen-20\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    else\n       if (olen.gt.8) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.10) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.12) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.14) then\n                   ifrc = olen-14\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    endif\n\n    if (isign .eq. -1) then\n       idt = idt * isign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n!\n! Compute the number of days in February for the given year.\n!\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n!\n! Compute the number of days in the month of given date hdate.\n!\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    if (hdate(5:5) == \"-\") then\n       read(hdate(1:7), '(I4,1x,I2)') year, month\n    else\n       read(hdate(1:6), '(I4,I2)') year, month\n    endif\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\nend module kwm_date_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/kwm_plot_utilities.F",
    "content": "!\n! Module with some handy graphics routines.\n!\n! This is very much a work in progress.\n!\n! A lot of this has been adapted from Mark Stoelinga's RIP program,\n! which is highly recommended.\n!\nmodule kwm_plot_utilities\n  integer                           :: nsq\n  real,              dimension(256) :: rsq, usq\n  character(len=20), dimension(256) :: cosq\n\n\n  ! NCO:  number of already-defined and named colors\n  integer :: nco\n\n  type named_color\n     character(len=20) :: name\n     real :: r\n     real :: g\n     real :: b\n  end type named_color\n\n  type(named_color), dimension(0:255) :: co\n\n  type plotconfig_type\n     integer :: nicecon\n     logical :: nolb\n     logical :: cbar\n     logical :: nohl\n  end type plotconfig_type\n  type(plotconfig_type) :: plotconfig = plotconfig_type(30, .FALSE., .TRUE., .FALSE.)\n\n  integer :: nconarea\n\n  integer, parameter :: maxcon = 80\n  real, dimension(maxcon) :: valcon\n  integer, dimension(maxcon) :: majcon\n  integer, dimension(maxcon) :: icoindcp\n  real :: valmin, valmax\n  logical :: larng\n\n  real :: nsqmax, nsqmin\n  character(len=4) :: method = \"cont\"\n  real :: frame_left = 0.0\n  real :: frame_right = 1.0\n  real :: frame_bottom = 0.0\n  real :: frame_top = 1.0\n\n  interface line_in_color\n     module procedure line_in_color_integer, line_in_color_string\n  end interface\n\ncontains\n\n!****************************************************************************************\n\n  subroutine kwm_start_ncargks(new_cgm_name)\n    implicit none\n    ! I can never remember what I called the subroutine.\n    character(len=*), optional, intent(in) :: new_cgm_name\n    if ( present (new_cgm_name) ) then\n       call kwm_init_ncargks(new_cgm_name)\n    else\n       call kwm_init_ncargks()\n    endif\n  end subroutine kwm_start_ncargks\n\n  subroutine kwm_open_ncargks(new_cgm_name)\n    implicit none\n    ! I can never remember what I called the subroutine.\n    character(len=*), optional, intent(in) :: new_cgm_name\n    if ( present (new_cgm_name) ) then\n       call kwm_init_ncargks(new_cgm_name)\n    else\n       call kwm_init_ncargks()\n    endif\n  end subroutine kwm_open_ncargks\n\n!****************************************************************************************\n\n  subroutine kwm_init_ncargks(new_cgm_name)\n! Starts off the NCAR Graphics package.\n! Opens workstation 1 as a CGM workstation.\n! Opens workstation 2 as a WISS.\n! Defines a couple of colors, and sets a couple of NCAR Graphics parameters\n!\n! If you want the gmeta file to be called something other than \"gmeta\",\n! give this subroutine the optional argument.\n    implicit none\n    character(len=*), optional, intent(in) :: new_cgm_name\n    character(len=80) :: newname\n    character(len=1) :: hdum\n\n    call gopks(6,0)\n\n    if (present(new_cgm_name)) then\n       newname = trim(new_cgm_name)\n       call gesc(-1391, 1, newname, 1, 1, hdum)\n    endif\n\n    call gopwk(1,119,1)\n    call gopwk(2,120,3)\n    call gacwk(1)\n    call gacwk(2)\n\n    call define_color(\"white\")\n    call define_color(\"black\")\n    call pcseti(\"FN\", 21)\n    call pcsetc(\"FC\", \"~\")\n  end subroutine kwm_init_ncargks\n\n!****************************************************************************************\n\n  subroutine kwm_close_ncargks\n    implicit none\n    call gdawk(1)\n    call gdawk(2)\n    call gclwk(1)\n    call gclwk(2)\n    call gclks\n\n    ! reset some accounting arrays\n    nsq = 0\n    rsq = 0.\n    cosq = \"\"\n    nco = 0\n    co = named_color(\"\",0.,0.,0.)\n\n  end subroutine kwm_close_ncargks\n\n!****************************************************************************************\n\n  subroutine gset_named_color(NAME)\n    ! Calls NCAR-Graphics subroutine GSCR to set the next color index\n    ! to the rgb values indicated by the color named NAME.\n\n    ! Side effects:  Associate RGB values with a color index NCO.\n    !                Increment module variable NCO.\n    implicit none\n    character(len=*), intent(in) :: NAME\n    type(named_color) :: color\n\n    print*\n    print*, ' ***** '\n    print*, ' ***** You probably want \"define_color(NAME)\" instead.'\n    print*, ' ***** '\n    print*\n\n    color = get_x11_color(name)\n    call gscr(1, nco, color%r, color%g, color%b)\n    nco = nco+1\n\n  end subroutine gset_named_color\n\n!****************************************************************************************\n\n  subroutine set_pval(nicecon, cmth, frml, frmr, frmb, frmt, cbar, nolb, nohl)\n    implicit none\n    integer, optional, intent(in) :: nicecon   ! Approximate number of contours\n    character(len=4), optional, intent(in) :: cmth ! \"fill\", \"cont\", or \"both\"\n    real, optional, intent(in) :: frml, frmr, frmb, frmt\n    logical, optional, intent(in) :: cbar, nolb, nohl\n    if (present(nicecon)) plotconfig%nicecon = nicecon\n    if (present(cmth)   ) method = cmth\n    if (present(frml)   ) frame_left  = frml\n    if (present(frmr)   ) frame_right = frmr\n    if (present(frmb)   ) frame_bottom = frmb\n    if (present(frmt)   ) frame_top = frmt\n    if (present(cbar)   ) plotconfig%cbar = cbar\n    if (present(nolb)   ) plotconfig%nolb = nolb\n    if (present(nohl)   ) plotconfig%nohl = nohl\n\n  end subroutine set_pval\n\n!****************************************************************************************\n\n  subroutine fillcell(array, ix, jx, mask)\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, intent(in), dimension(ix,jx) :: array\n    logical, dimension(ix,jx), optional, intent(in) :: mask\n\n    logical, dimension(ix,jx) :: bmask\n    integer :: i, j, n, mjsk, numcon\n    real :: xmn, xmx, cintuse\n    type(named_color) :: cotmp\n    integer :: ico, icomax\n\n    type(named_color), dimension(maxcon) :: usit\n\n    mjsk = 0\n\n    if (present(mask)) then\n       bmask = mask\n    else\n       bmask = .TRUE.\n    endif\n\n!   Get the contour values\n    if (larng) then\n\n       numcon = plotconfig%nicecon\n       xmn = minval(array, mask=bmask)\n       xmx = maxval(array, mask=bmask)\n       do i = 1, numcon\n          valcon(i) = xmn + (xmx-xmn)*float(i-1)/float(numcon-1)\n       enddo\n       usq = xmn + (xmx-xmn)*rsq*0.01 ! *float(nsq-1)/float(nsq)\n\n    else\n\n       call getconvals(plotconfig%nicecon, mjsk, &\n            array, ix, jx, maxcon, valcon, majcon, &\n            cintuse, numcon, &\n            rbeg = rsq(1), rend=rsq(nsq))\n       usq = rsq\n       xmn = usq(1)\n       xmx = usq(nsq)\n    endif\n\n    if (numcon == 0) then\n       ! No coloring levels, so just return.\n       return\n    endif\n\n    nconarea = numcon+1\n! Set up colors.\n!   Assign the red, green, and blue fractions to the color sequence\n!\n    ILOOP : do i=1,nsq\n       ! nco is the number of colors already assigned by name\n       do j=0,nco-1\n          if (cosq(i) == co(j)%name) then\n             usit(i) = co(j)\n             cycle ILOOP\n          endif\n       enddo\n       ! If the color name is not found, look for it, add it to the list\n       ! of named colors, and increment NCO, the number of named colors.\n       usit(i) = get_x11_color(cosq(i))\n       co(nco) = usit(i)\n       nco = nco + 1\n    enddo ILOOP\n\n    nco = nco - 1\n    icomax = nco\n\n! Now see if new colors need to be defined.\n    COLORLOOP : do i=1,nconarea\n       icoindcp(i) = -1\n       cotmp = color_fraction( i, usit, usq, nsq, numcon, valcon )\n!\n!   Assign color index to icoindcp\n!      First check if color already exists\n!\n       do ico=0,icomax\n          if ( (abs(cotmp%r - co(ico)%r)<=0.001) .and. &\n               (abs(cotmp%g - co(ico)%g)<=0.001) .and. &\n               (abs(cotmp%b - co(ico)%b)<=0.001) ) then\n             icoindcp(i)=ico\n             call gscr(1,ico,co(ico)%r,co(ico)%g,co(ico)%b)\n             cycle COLORLOOP\n          endif\n       enddo\n!\n!      If not, set the new color and assign its index to icoincdcp\n!\n       icomax=icomax+1\n       if (icomax == 256) then\n          write(*,'(\"pltcon is trying to define color number 256, but 255\",/,&\n               &\"is the limit.  Try increasing the contour interval, or\",/,&\n               &\"reduce the number of colors defined in the color table.\")')\n          stop\n       endif\n       call gscr(1,icomax,cotmp%r,cotmp%g,cotmp%b)\n       co(icomax) = cotmp\n       icoindcp(i)=icomax\n    enddo COLORLOOP\n\n    do i = 1, ix\n       JLOOP : do j = 1, jx\n          if (.not. bmask(i,j)) cycle JLOOP\n          if (array(i,j) <= xmn) cycle JLOOP\n          do n = numcon, 1, -1\n             if ( array(i,j) >= valcon(n)) then\n                call ngsquares((/float(i)/), (/float(j)/), 1, 1., icoindcp(n+1))\n                exit\n             endif\n          enddo\n       enddo JLOOP\n    enddo\n\n    if (plotconfig%cbar) then\n       call labelbar(array, ix, jx, numcon)\n    endif\n\n  end subroutine fillcell\n\n!****************************************************************************************\n\n  subroutine labelbar(array, ix, jx, numcon, iskip)\n! Put on a color-scale and label the box\n    implicit none\n    integer, intent(in) :: ix, jx, numcon\n    integer, optional, intent(in) :: iskip\n    real, dimension(ix,jx) , intent(in) :: array\n    real :: xmx, xmn\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n\n    real :: xlmn, xlmx, ylmn, ylmx\n\n    integer :: n, ierr\n\n    integer :: ipx, ipn, ip\n    character(len=40) :: fmt, hh\n    integer, dimension(2) :: mxlc, mnlc\n\n    real :: txtsz\n    real :: mmsz\n\n    txtsz = 0.009 * min((frame_right-frame_left),(frame_top-frame_bottom))\n    mmsz = 0.015 * min((frame_right-frame_left),(frame_top-frame_bottom))\n\n    call gsplci(1)\n    call pcseti(\"CC\", 1)\n\n    call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n\n    call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n!KWM    call line(frame_left, frame_bottom, frame_right, frame_bottom)\n!KWM    call line(frame_left, frame_bottom, frame_left, frame_top)\n!KWM    call line(frame_left, frame_top, frame_right, frame_top)\n!KWM    call line(frame_right, frame_bottom, frame_right, frame_top)\n!    call set(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n\n!    call set(frame_left, frame_right, frame_bottom, frame_top, &\n!         0., 1., 0., 1., ml)\n\n    mxlc = maxloc(array)\n    mnlc = minloc(array)\n    xmx = array(mxlc(1), mxlc(2))\n    xmn = array(mnlc(1), mnlc(2))\n\n    xlmn = xr + 0.005\n    ! xlmx = xlmn + (frame_right-xr)*0.25\n    xlmx = xlmn + 0.050\n\n    do n = 1, numcon\n       ylmn = xb + float(n-1)/float(numcon) * (xt-xb)\n       ylmx = xb + float(n  )/float(numcon) * (xt-xb)\n!       call fillbox(xlmn, xlmx, ylmn, ylmx, icoindcp(n+1))\n       call fillbox(xlmn, xlmx, ylmn, ylmx, icoindcp(n))\n    enddo\n    call gslwsc(1.)\n    call line(xlmn,xb,xlmn,xt)\n    call line(xlmx,xb,xlmx,xt)\n    do n = 1, numcon!nsq\n       ylmn = xb + float(n-1)/float(numcon) * (xt-xb)\n       ylmx = xb + float(n  )/float(numcon) * (xt-xb)\n       call line(xlmn, ylmn, xlmx, ylmn)\n       call line(xlmn, ylmx, xlmx, ylmx)\n    enddo\n    call gslwsc(1.)\n\n    ! Determine the scaling for the numbers to be printed:\n\n    if (abs(xmx) > 1.E-12) then\n       ipx = alog10(abs(xmx))\n    else\n       ipx = 0\n    endif\n    if (abs(xmn) > 1.E-12) then\n       ipn = alog10(abs(xmn))\n    else\n       ipn = 0\n    endif\n    if (ipx - ipn > 6) then\n       ip = -(3*ipx+ipn)/4\n    else\n       ip = -min(ipx, ipn)\n    endif\n    if (ip > 0) then\n       write(fmt,'(\"(G14.5E2)\")')\n    else\n       write(fmt,'(\"(\",I3,\"PF12.4)\")') ip\n    endif\n\n!    do n = numcon+1, 1, -1\n    do n = numcon, 2, -1\n       ylmn = xb + float(n-1)/float(numcon) * (xt-xb)\n       if (n == numcon+1) then\n          write(hh, fmt=fmt) xmx\n!          print*, 'xmx, valcon(n) = ', xmx, valcon(n)\n          if (xmx == valcon(n-1)) then\n             ! Don't repeat the max value\n             hh = \"\"\n          endif\n       else\n          write(hh, fmt=fmt) valcon(n-1)\n       endif\n       if (present(iskip)) then\n          if (mod(n-2,iskip) == 0) then\n             call pchiqu(xlmx-0.030, ylmn, hh, txtsz * iskip * 0.66, 0., -1.)\n          endif\n       else\n          call pchiqu(xlmx+0.005, ylmn, hh, txtsz, 0., -1.)\n       endif\n    enddo\n\n    if (ip < 0) then\n       !call pchiqu(xlmn, xb-0.03, \"scaled by 1.E\"//fmt(2:4), txtsz, 0., -1.)\n       call pchiqu(xlmn, xb, \"~V-1Q~scaled by 1.E\"//fmt(2:4), txtsz, 0., -1.)\n    endif\n\n    write(fmt, '(\" at \",I4, 1x, I4)') mxlc(1), mxlc(2)\n\n    write(hh, '(F14.5)') xmx\n!    call pchiqu(xr, (xb-0.06), \"(x) Max value = \"//hh//trim(fmt),&\n!         mmsz, 0., 1.)\n\n!    call pchiqu(xr, xb-2*mmsz, \"(x) Max value = \"//hh//trim(fmt),&\n!         mmsz, 0., 1.)\n\n    write(fmt, '(\" at \",I4, 1x, I4)') mnlc(1), mnlc(2)\n    write(hh, '(F14.6)') xmn\n\n!    call pchiqu(xr, (xb-0.08), \"(+) Min value = \"//hh//trim(fmt), &\n!         mmsz, 0., 1.)\n\n!    call pchiqu(xr, xb-4*mmsz, \"(+) Min value = \"//hh//trim(fmt), &\n!         mmsz, 0., 1.)\n\n    call set(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n\n  end subroutine labelbar\n\n!****************************************************************************************\n\n  subroutine pltcon(array, ix, jx)\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, dimension(ix,jx), intent(in) :: array\n\n    integer, parameter :: lwrk = 800000, liwk = 2000000\n    real, dimension(lwrk) :: rwrk\n    integer, dimension(liwk) :: iwrk\n\n    integer, parameter :: niam = 1000000\n    integer, parameter :: ncs = 1000000\n    integer, dimension(niam) :: iam\n    real,    dimension(niam) :: xcs, ycs\n    integer, dimension(50000)  :: iaia, igia\n\n    real :: cintuse, cr, cg, cb\n    integer :: numcon\n    integer :: mjsk\n    integer :: ico, i, j, icomax, ierr\n    type(named_color) cotmp\n    type(named_color), dimension(maxcon) :: usit\n    real :: xmn, xmx\n\n    mjsk = 0\n\n!   Get the contour values\n    if (larng) then\n\n       numcon = plotconfig%nicecon\n       xmn = minval(array)\n       xmx = maxval(array)\n       do i = 1, numcon\n          valcon(i) = xmn + (xmx-xmn)*float(i-1)/float(numcon-1)\n       enddo\n       usq = xmn + (xmx-xmn)*rsq*0.01 ! *float(nsq-1)/float(nsq)\n\n    else\n\n       call getconvals(plotconfig%nicecon, mjsk, &\n            array, ix, jx, maxcon, valcon, majcon, &\n            cintuse, numcon, &\n            rbeg = rsq(1), rend=rsq(nsq))\n       usq = rsq\n\n    endif\n\n!KWM    print*, 'usq = ', usq(1:numcon)\n\n! Number of areas for filling is one plus the number of contours,\n! i.e., the contours define the boundaries between areas.\n    nconarea = numcon+1\n\n    call cpseti('SET',0)   ! we'll use our own set call\n    call cpseti('CLS',0)   ! we'll use our own cont. values\n!\n!   Some settings for hi/lo and contour labels\n!\n    call cpseti('NSD',-4)\n    call cpseti('NOF',7)\n    call cpsetr('PC6',.6)\n\n! Set up colors.\n!   Assign the red, green, and blue fractions to the color sequence\n!\n    ILOOP : do i=1,nsq\n       ! nco is the number of colors already assigned by name\n       do j=0,nco-1\n          if (cosq(i) == co(j)%name) then\n             usit(i) = co(j)\n             cycle ILOOP\n          endif\n       enddo\n       ! If the color name is not found, look for it, add it to the list\n       ! of named colors, and increment NCO, the number of named colors.\n       usit(i) = get_x11_color(cosq(i))\n       co(nco) = usit(i)\n       nco = nco + 1\n    enddo ILOOP\n\n    nco = nco - 1\n    icomax = nco\n!\n! USIT is now our list of color names and associated rgb values in\n! our color sequence.  Color values in USIT correspond to USQ\n\n! Note that we haven't actually called GSCR to assign RGB values to\n! color indices yet.  This will come later\n\n    COLORLOOP : do i=1,nconarea\n       icoindcp(i) = -1\n       cotmp = color_fraction( i, usit, usq, nsq, numcon, valcon )\n!\n!   Assign color index to icoindcp\n!      First check if color already exists\n!\n       do ico=0,icomax\n          if ( (abs(cotmp%r - co(ico)%r)<=0.001) .and. &\n               (abs(cotmp%g - co(ico)%g)<=0.001) .and. &\n               (abs(cotmp%b - co(ico)%b)<=0.001) ) then\n             icoindcp(i)=ico\n             call gscr(1,ico,co(ico)%r,co(ico)%g,co(ico)%b)\n             cycle COLORLOOP\n          endif\n       enddo\n!\n!      If not, set the new color and assign its index to icoincdcp\n!\n       icomax=icomax+1\n       if (icomax == 256) then\n          write(*,'(\"pltcon is trying to define color number 256, but 255\",/,&\n               &\"is the limit.  Try increasing the contour interval, or\",/,&\n               &\"reduce the number of colors defined in the color table.\")')\n          stop\n       endif\n       call gscr(1,icomax,cotmp%r,cotmp%g,cotmp%b)\n       co(icomax) = cotmp\n       icoindcp(i)=icomax\n    enddo COLORLOOP\n\n    call cpseti('NVS', 4)\n    call cpseti('NCL',numcon)\n    if (plotconfig%nohl) then\n       call cpsetc(\"HIT\", ' ')\n       call cpsetc(\"LOT\", ' ')\n    endif\n    do i=1,numcon\n       call cpseti('PAI',i)\n       call cpsetr('CLV',valcon(i))\n       if (plotconfig%nolb) then\n          call cpseti('CLU',1)\n       else\n          call cpseti('CLU',3)\n       endif\n       call cpseti('AIB',i)\n       call cpseti('AIA',i+1)\n    enddo\n\n    call cprect(array,ix,ix,jx,rwrk,lwrk,iwrk,liwk)\n    call arinam(iam,niam) ! Initialize the area map\n\n    call cpclam(array,rwrk,iwrk,iam)  ! put cont. lines in area map\n    if ((method == \"both\") .or. (method == \"fill\")) then\n       call arscam(iam,xcs,ycs,ncs,iaia,igia,5000,cpcolr)\n       if (plotconfig%cbar) then\n          call labelbar(array, ix, jx, numcon)\n       endif\n    endif\n\n!KWM! Add a color bar.\n!KWM!    call color_bar(nsq, 0., rsq(nsq))\n!KWM    if (larng) then\n!KWM       call color_bar(numcon-1, valmin, valmax)\n!KWM    else\n!KWM       call color_bar(numcon, valmin, valmax)\n!KWM    endif\n\n    if ((method == \"cont\") .or. (method == \"both\")) then\n       ! Contour lines:\n       call cplbdr(array, rwrk, iwrk)\n       call cpcldr(array, rwrk, iwrk)\n    endif\n\n    call gsplci(1)\n    call pcseti(\"CC\", 1)\n  end subroutine pltcon\n\n!****************************************************************************************\n\n  subroutine color_bar(nthresh, cmin, cmax)\n    implicit none\n    integer, intent(in) :: nthresh\n    real, intent(in) :: cmin, cmax\n    real :: xl, xr, xb, xt, wl, wr, wb, wt\n    integer :: ml\n\n    real :: xlmn, xlmx, ylmn, ylmx\n    integer :: n, ipx, ipn, ip\n\n    character(len=14) :: hh, fmt\n    integer :: i, j, jj\n    integer :: ierr\n\n    call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n    call set(frame_left,frame_right,frame_bottom,frame_top,0.,1.,0.,1.,ml)\n\n    xlmn = xr + 0.005\n    ! xlmx = xlmn + (1.-xr)*0.25\n    xlmn = xlmn + .050\n\n    do n = 1, nthresh+1\n       ylmn = xb + float(n-1)/float(nthresh+1) * (xt-xb)\n       ylmx = xb + float(n  )/float(nthresh+1) * (xt-xb)\n       if (n <= nthresh) then\n          call cpseti('PAI',n)\n          call cpgeti('AIB',j)\n          call fillbox(xlmn, xlmx, ylmn, ylmx, icoindcp(j))\n!          call fillbox(xlmn, xlmx, ylmn, ylmx, color_index(cosq(n)))\n       else\n          call cpseti('PAI',n-1)\n          call cpgeti('AIA',jj)\n          call cpgeti('AIB',j)\n          call fillbox(xlmn, xlmx, ylmn, ylmx, icoindcp(jj))\n!          call fillbox(xlmn, xlmx, ylmn, ylmx, color_index(cosq(n)))\n       endif\n    enddo\n\n    call gslwsc(1.)\n    call line(xlmn,xb,xlmn,xt)\n    call line(xlmx,xb,xlmx,xt)\n    do n = 1, nthresh+1\n       ylmn = xb + float(n-1)/float(nthresh+1) * (xt-xb)\n       ylmx = xb + float(n  )/float(nthresh+1) * (xt-xb)\n       call line(xlmn, ylmn, xlmx, ylmn)\n       call line(xlmn, ylmx, xlmx, ylmx)\n    enddo\n    call gslwsc(1.)\n\n! Determine the scaling for the numbers to be printed:\n\n    if (abs(cmax) > 1.E-12) then\n       ipx = alog10(abs(cmax))\n    else\n       ipx = 0\n    endif\n    if (abs(cmin) > 1.E-12) then\n       ipn = alog10(abs(cmin))\n    else\n       ipn = 0\n    endif\n    if (ipx - ipn > 6) then\n       ip = -(3*ipx+ipn)/4\n    else\n       ip = -min(ipx, ipn)\n    endif\n    if (ip > 0) then\n       write(fmt,'(\"(G14.5E2)\")')\n    else\n       write(fmt,'(\"(\",I3,\"PF12.4)\")') ip\n       if (ierr /= 0) fmt=\"(G20.5E2)\"\n    endif\n\n    do n = nthresh, 1, -1\n       ylmn = xb + float(n)/float(nthresh+1) * (xt-xb)\n       if (n == nthresh+1) then\n!        write(hh, '(G14.5E2)') xmx\n          write(hh, fmt=fmt) cmax\n       else\n!        write(hh, '(G14.5E2)') thresh(n)\n          write(hh, fmt=fmt) valcon(n) !thresh(n)\n       endif\n       call pchiqu(xlmx+0.005, ylmn, hh, 0.009, 0., -1.)\n    enddo\n\n    if (ip < 0) then\n       !call pchiqu(xlmn, xb-0.03, \"scaled by 1.E\"//fmt(2:4), 0.009, 0., -1.)\n       call pchiqu(xlmn, xb, \"~V-1Q~scaled by 1.E\"//fmt(2:4), 0.009, 0., -1.)\n    endif\n\n!    write(fmt, '(\" at \",I4, 1x, I4)') mxlcx, mxlcy\n\n!    write(hh, '(F14.5)') xmx\n!    call pchiqu(xlmn-0.17, (xb-0.06), \"(x) Max value = \"//hh//fmt,&\n!         0.011, 0., 1.)\n\n!    write(fmt, '(\" at \",I4, 1x, I4)') mnlcx, mnlcy\n!    write(hh, '(F14.6)') xmn\n!    call pchiqu(xlmn-0.17, (xb-0.10), \"(+) Min value = \"//hh//fmt, &\n!         0.011, 0., 1.)\n\n    call set(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n  end subroutine color_bar\n\n!==============================================================================\n\n  type(named_color) function get_x11_color(name) result (c)\n    use kwm_string_utilities\n    implicit none\n    character(len=*) :: name\n    integer :: r, g, b, i\n    character(len=20) :: cname\n\n    logical, save :: already_read = .FALSE.\n    integer :: ierr, idx\n    character(len=80) :: string, stringname\n    integer, external :: get_unused_unit\n    integer :: iunit\n\n    real, dimension(2500), save :: readlist_r, readlist_g, readlist_b\n    character(len=64), dimension(2500), save :: readlist_name\n    integer, save :: readlist_count = 0\n    logical :: lthere\n\n    if (.not. already_read) then\n       already_read = .TRUE.\n       iunit = get_unused_unit()\n\n       inquire(file=\"/usr/lib/X11/rgb.txt\", exist=lthere)\n       if (lthere) then\n          open(iunit, file=\"/usr/lib/X11/rgb.txt\", form='formatted', &\n               status='old', action='read', iostat=ierr)\n       else\n          inquire(file=\"/usr/share/X11/rgb.txt\", exist=lthere)\n          if (lthere) then\n             open(iunit, file=\"/usr/share/X11/rgb.txt\", form='formatted', &\n                  status='old', action='read', iostat=ierr)\n          else\n             stop 'KWM_PLOT_UTILITIES:  Cannot find X11 \"rgb.txt\" file'\n          endif\n       endif\n       if (ierr /= 0) stop \"color table\"\n       do\n\n          read(iunit, '(A)', iostat=ierr) string\n          if (ierr /= 0) exit\n          if (string(1:1) == \"!\") cycle\n\n          stringname = \" \"\n          read(string, *) r, g, b\n          ! Find the index of the first alphabetical character\n          idx = verify(string, \" 0123456789\"//char(9)) ! char(9) is tab\n          stringname = trim(string(idx:))\n          stringname = downcase(trim(stringname))\n          stringname = unblank(trim(stringname))\n\n          readlist_count = readlist_count + 1\n          readlist_r(readlist_count) = float(r)/255.\n          readlist_g(readlist_count) = float(g)/255.\n          readlist_b(readlist_count) = float(b)/255.\n          readlist_name(readlist_count) = stringname\n\n       enddo\n\n       close(iunit)\n    endif\n\n    ! Search through readlist for name\n\n    if (name(1:1) == \"#\") then\n       read(name(2:7), '(Z2,Z2,Z2)') r, g, b\n       cname = name\n       c = named_color(cname, float(r)/255., float(g)/255., float(b)/255.)\n       return\n    else if ((name(1:2) == \"0x\") .or. (name(1:2) == \"0X\")) then\n       read(name(3:8), '(Z2,Z2,Z2)') r, g, b\n       cname = name\n       c = named_color(cname, float(r)/255., float(g)/255., float(b)/255.)\n       return\n    else\n\n       do i = 1, readlist_count\n          if (name == readlist_name(i)) then\n             cname = name\n             c = named_color(cname, readlist_r(i), readlist_g(i), readlist_b(i))\n             return\n          endif\n       enddo\n\n       write(*, '(\"color not found: \", A)') trim(name)\n    endif\n\n  end function get_x11_color\n\n  type(named_color) function color_fraction(i, usit, rsq, count, numcon, valcon) &\n       result (c)\n! Returns c(name,r,g,b) that is to be used for index i\n\n    implicit none\n    integer, intent(in)                             :: i\n    integer, intent(in)                             :: count\n    type(named_color), intent(in), dimension(count) :: usit\n    real,              intent(in), dimension(count) :: rsq\n    integer, intent(in)                             :: numcon\n    real,    intent(in),          dimension(numcon) :: valcon\n\n    real :: val\n    real :: red, green, blue, fac\n    integer :: isq\n\n    if (numcon == 0) then\n       print*, 'numcon = ', numcon\n       c = named_color(\"white\", 1., 1., 1.)\n       return\n    endif\n    if (numcon == 1) then\n       print*, 'numcon = ', numcon\n       c = named_color(\"white\", 1., 1., 1.)\n       return\n    endif\n\n    valmin=valcon(1)-.5*(valcon(2)-valcon(1))\n    valmax=valcon(numcon)+.5*(valcon(numcon)-valcon(numcon-1))\n\n    if (i == 1) then\n       val=valmin\n    elseif (i == numcon+1) then\n       val=valmax\n    else\n       val=.5*(valcon(i-1)+valcon(i))\n    endif\n\n    c = named_color(\"transparent\", -1., -1., -1.)\n\n    if (val.le.valcon(1)) then\n       if (usit(1)%name /= \"transparent\" ) c = usit(1)\n    elseif (val.ge.valcon(numcon)) then\n       if (usit(nsq)%name /= \"transparent\" ) c = usit(nsq)\n    else\n       ! Interpolate from USIT rgb values (associated with RSQ\n       ! floating-point values) to a new color c.\n\n       do isq=1,nsq-1\n          if (val.ge.rsq(isq).and.val.le.rsq(isq+1)) then\n             if ( usit(isq  )%name /= \"transparent\" .and. &\n                  usit(isq+1)%name /= \"transparent\" ) then\n                fac=(val-rsq(isq))/(rsq(isq+1)-rsq(isq))\n                red  =fac*usit(isq+1)%r+(1.-fac)*usit(isq)%r\n                green=fac*usit(isq+1)%g+(1.-fac)*usit(isq)%g\n                blue =fac*usit(isq+1)%b+(1.-fac)*usit(isq)%b\n                c = named_color(\"\", red, green, blue)\n             endif\n             return\n          endif\n       enddo\n!KWM       print*, 'usit%name = ', usit%name\n!KWM       print*, 'rsq = ', rsq\n!KWM       print*, 'valcon = ', valcon\n!KWM       print*, 'valmin, valmax = ', valmin, valmax\n!KWM       print*, 'val = ', val\n!KWM       stop \"Not Found.\"\n    endif\n  end function color_fraction\n\n!==============================================================================\n\n  subroutine getconvals(ncon,mjsk, &\n       array,ix,jx,maxcon,valcon,majcon, &\n       cintuse, numcon, rbeg, rend, rint, fmsg)\n! Swiped from Mark Stoelinga's RIP program and adapted.\n    implicit none\n    real,            optional, intent(in) :: rbeg ! cbeg\n    real,            optional, intent(in) :: rend ! cend\n    real,            optional, intent(in) :: rint ! cint\n    real,            optional, intent(in) :: fmsg ! rmsg\n    integer,                   intent(in) :: ncon\n    integer,                   intent(in) :: mjsk\n    integer,                   intent(in) :: ix, jx\n    integer,                   intent(in) :: maxcon\n    real,    dimension(ix,jx), intent(in) :: array\n\n    real,    dimension(maxcon), intent(out) :: valcon\n    integer, dimension(maxcon), intent(out) :: majcon\n    real,                       intent(out) :: cintuse\n    integer,                    intent(out) :: numcon\n\n    integer :: ii, i, j, itmp, imaj, imajrel\n!\n!\n    real :: cbeg, cend, cint, rmsg\n    real :: cb, ce, ci, tmp, fac, diff, fv, rmax, rmin, crange\n    real :: p\n    logical :: mult\n!\n!   mjsk is the number of minor (unlabeled) contours desired\n!   between major (labeled) contours.\n!\n    logical :: choosecb, chooseci\n\n    if (present(fmsg)) then\n       rmsg = fmsg\n    else\n       rmsg = -1.E30\n    endif\n\n!\n!   cbeg is the beginning contour value.  rmsg means pick a\n!   nice value close to the max value in the field. -rmsg means\n!   pick a nice value close to the min value in the field.\n!\n    if (present(rbeg)) then\n       cbeg = rbeg\n    else\n       cbeg = rmsg\n    endif\n!\n!   cend is the ending contour value.  rmsg means pick a nice\n!   value close to the max value in the field. -rmsg means pick\n!   a nice value close to the min value in the field.\n!\n    if (present(rend)) then\n       cend = rend\n    else\n       cend = -rmsg\n    endif\n!\n!   cint is the contour interval. rmsg means pick a nice value\n!   that generates close to ncon contours.\n!\n    if (present(rint)) then\n       cint = rint\n    else\n       cint = rmsg\n    endif\n!\n!   mult means use a multiplicative contour interval instead of\n!   an additive one.  If mult is true, cbeg and cend must be of\n!   the same sign (otherwise cend will be changed to a value\n!   that is of the same sign as cbeg), and all contour values\n!   will also be the same sign.\n!\n!KWM  mult = lmult(ipl)\n    mult = .FALSE.\n!\n!   First get max and min in field.\n!\n    if (all(array==rmsg)) then\n       write(*,*)'   In getconvals: not generating any contours'\n       write(*,*)'    because all values are special value.'\n       numcon=0\n       return\n    endif\n!\n    rmax = maxval(array, mask=(array/=rmsg))\n    rmin = minval(array, mask=(array/=rmsg))\n\n    if (rmax == rmin) then\n       write(*,*)'   In getconvals: not generating any contours'\n       write(*,*)'    because field is constant.  Value = ',rmax\n       numcon=0\n       return\n    endif\n!\n    choosecb=.false.\n    if (cbeg == rmsg) then\n       cb=rmax\n       choosecb=.true.\n    elseif (cbeg == -rmsg) then\n       cb=rmin\n       choosecb=.true.\n    else\n       cb=cbeg\n    endif\n!\n    if (cend == rmsg) then\n       ce=rmax\n    elseif (cend == -rmsg) then\n       ce=rmin\n    else\n       ce=cend\n    endif\n!\n    chooseci=.false.\n    if (cint == rmsg .or. cint == 0.0) then\n       chooseci=.true.\n    elseif (cint < 0.0) then\n       ci=-cint\n    else\n       ci=cint\n    endif\n!\n!KWM  if (mult) then\n!KWM     if (cb == 0.0.or.ce == 0.0) then\n!KWM        write(iup,*)'In getconvals: not generating any contours'\n!KWM        write(iup,*)'   because mult is true and cbeg or cend'\n!KWM        write(iup,*)'   are zero. cbeg,cend=',cbeg,cend\n!KWM        numcon=0\n!KWM        return\n!KWM     endif\n!KWM     if (cb*ce.lt.0.0) then\n!KWM        write(iup,*)'In getconvals: not generating any contours'\n!KWM        write(iup,*)'   because mult is true and cbeg and cend are'\n!KWM        write(iup,*)'   of opposite sign.  cbeg,cend=',cbeg,cend\n!KWM        numcon=0\n!KWM        return\n!KWM     endif\n!KWM     if (ci == 1.0) chooseci=.true.\n!KWM     if (cb.lt.0.0) then\n!KWM        iswitch=1\n!KWM        cb=-cb\n!KWM        ce=-ce\n!KWM        temp=rmax\n!KWM        rmax=-rmin\n!KWM        rmin=-temp\n!KWM     else\n!KWM        iswitch=0\n!KWM     endif\n!KWM     valm=1e-8*cb\n!KWM     rmax=max(rmax,valm)\n!KWM     rmin=max(rmin,valm)\n!KWM     ce=max(ce,valm)\n!KWM  endif\n!\n!   Set up start, end, and interval.\n!\n!KWM  if (.not.mult) then\n    if (chooseci) then\n       crange=max(abs(ce-cb),1.e-10)\n       ci = crange/ncon\n       p = 10.**(int(alog10(ci)+50000.)-50000)\n       ci=max(ci,p)\n       ii=int(ci/p)\n       if (ii.ge.7) then\n          ci = 10.*p\n       else\n          ci = ii*p\n       endif\n    endif\n    if (choosecb) then\n       cb=nint(cb/ci)*ci\n       if (cb.ge.rmax) cb=cb-ci\n       if (cb.le.rmin) cb=cb+ci\n    endif\n!KWM  else\n!KWM     if (choosecb) then\n!KWM        cmax=10.**(int(alog10(rmax)+50000.)-50000)\n!KWM        cmin=10.**(int(alog10(rmin)+50000.)-50000+1)\n!KWM        cb=10.**(nint(alog10(cb)+50000.)-50000)\n!KWM        cb=min(max(cb,cmin),cmax)\n!KWM     endif\n!KWM     if (chooseci) then\n!KWM        ci=(max(ce,cb)/min(ce,cb))**(1./(max(ncon,2)-1))\n!KWM        if (ci.le.1.6) then\n!KWM           ci=sqrt(2.)\n!KWM        elseif (ci.le.3.5) then\n!KWM           ci=2.\n!KWM        elseif (ci.le.7.5) then\n!KWM           ci=5.\n!KWM        else\n!KWM           ci=10.**nint(alog10(ci))\n!KWM        endif\n!KWM     endif\n!KWM  endif\n    cintuse=ci\n!\n!   Generate contour levels.\n!\n!KWM  if (.not.mult) then\n    if (ce.lt.cb) then\n       ci=-abs(ci)\n    else\n       ci=abs(ci)\n    endif\n!KWM  else\n!KWM     alci=alog(ci)\n!KWM     if (abs(ce).lt.abs(cb)) then\n!KWM        alci=-abs(alci)\n!KWM     else\n!KWM        alci=abs(alci)\n!KWM     endif\n!KWM     ci=exp(alci)\n!KWM  endif\n    numcon=1\n    valcon(numcon)=cb\n50  numcon=numcon+1\n    if (numcon.gt.maxcon) goto 100\n!KWM  if (.not.mult) then\n    valcon(numcon)=valcon(numcon-1)+ci\n!KWM  else\n!KWM     valcon(numcon)=valcon(numcon-1)*ci\n!KWM  endif\n    if ((ce.ge.cb.and.valcon(numcon).gt.ce).or.&\n         (ce.lt.cb.and.valcon(numcon).lt.ce)) goto 100\n    goto 50\n100 numcon=numcon-1\n!\n!   Return mult contours to opposite sign, if iswitch=1\n!\n!KWM  if (mult) then\n!KWM     if (iswitch == 1) then\n!KWM        do i=1,numcon\n!KWM           valcon(i)=-valcon(i)\n!KWM        enddo\n!KWM     endif\n!KWM  endif\n!\n!   Determine major contours\n!\n    do i=1,numcon\n       if (.not.mult) then\n          fac=valcon(i)/((mjsk+1)*abs(ci))\n       else\n          fac=alog10(abs(valcon(i)))\n       endif\n       diff=abs(fac-float(nint(fac)))\n       if (diff.lt..001) then\n          imaj=i\n          goto 200\n       endif\n    enddo\n    imaj=1\n200 continue\n    imajrel=mod(imaj,mjsk+1)-(mjsk+1)\n    do i=1,numcon\n       if (.not.mult) then\n          fac=valcon(i)/((mjsk+1)*abs(ci))\n       else\n          fac=1.\n       endif\n       if (abs(fac).lt.1e-4) then    ! zero contour\n          valcon(i)=0.0\n          majcon(i)=0\n       elseif (mod(i-imajrel,mjsk+1) == 0) then\n          if (valcon(i).gt.0) then ! positive major (labeled) contour\n             majcon(i)=2\n          else                     ! negative major (labeled) contour\n             majcon(i)=-2\n          endif\n       else\n          if (valcon(i).gt.0) then   ! positive unlabeled contour\n             majcon(i)=1\n          else                       ! negative unlabeled contour\n             majcon(i)=-1\n          endif\n       endif\n    enddo\n!\n!   Reorder if valcon(1) > valcon(numcon)\n!\n    if (valcon(1).gt.valcon(numcon)) then\n       do i=1,numcon/2\n          ii=numcon+1-i\n          tmp=valcon(i)\n          valcon(i)=valcon(ii)\n          valcon(ii)=tmp\n          itmp=majcon(i)\n          majcon(i)=majcon(ii)\n          majcon(ii)=itmp\n       enddo\n    endif\n!\n  end subroutine getconvals\n\n!****************************************************************************************\n\n  subroutine cpcolr (xcra,ycra,ncra,iaia,igia,naia)\n!\n!   This is a user-supplied areas subroutine which allows the user\n!   to color areas in a particular way.\n!\n    implicit none\n    integer, intent(in) :: naia, ncra\n    real   , intent(in), dimension(ncra) :: xcra, ycra\n    integer, intent(in), dimension(naia) :: iaia, igia\n\n    integer :: ifll, i\n!\n!   Assume polygon will be filled until we find otherwise.\n!\n    ifll=1\n!\n!   If any area identifier is negative, don't fill the polygon\n!\n    do i=1,naia\n       if (iaia(i).lt.0.) then\n          ifll=0\n       endif\n    enddo\n!\n!   Otherwise, fill the polygon in the color implied by its area\n!   identifier relative to edge group 3 (the contour-line group).\n!\n    if (ifll.ne.0) then\n       ifll=0\n       do i=1,naia\n          if (igia(i) == 3) then\n             ifll=iaia(i)\n          endif\n       enddo\n!\n!      Note that if icoindcp(ifll) is negative, that means this\n!      polygon should remain transparent (i.e. not filled).\n!\n       if (ifll.ge.1) then\n          if (ifll.le.nconarea.and.icoindcp(ifll).ge.0) then\n             call gsfaci(icoindcp(ifll))\n             call gfa (ncra-1,xcra,ycra)\n          else\n             write(*, '(\"ifll = \",I12)') ifll\n             write(*, '(\"icoindcp(ifll) = \",I2)') icoindcp(ifll)\n             stop \"Transparent problem.  Fix it?\"\n          endif\n       endif\n    endif\n\n  end subroutine cpcolr\n\n!****************************************************************************************\n\n  subroutine dfclrs\n    ! A couple of predefined colors, namely, white and black.\n    implicit none\n    integer :: i\n\n    print*\n    print*, ' ***** '\n    print*, ' ***** Do not use DFCLRS.'\n    print*, ' ***** '\n    print*\n\n    nco = 0\n    co%name = \" \"\n\n    co(nco)= named_color(\"white\", 1., 1., 1.)\n    nco = nco + 1\n\n    co(nco) = named_color(\"black\", 0., 0., 0.)\n    nco = nco + 1\n\n    do i = 0, nco-1\n       call gscr(1, i, co(i)%r, co(i)%g, co(i)%b)\n    enddo\n\n  end subroutine dfclrs\n\n!****************************************************************************************\n\n  subroutine define_color(name)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer :: i\n\n    ! print*, 'Function DEFINE_COLOR:  name = ', trim(name)\n\n    do i = 0, nco-1\n       if (co(i)%name == name) return\n    enddo\n\n    co(nco) = get_x11_color(name)\n    call gscr(1, nco, co(nco)%r, co(nco)%g, co(nco)%b)\n    ! print*,' nco, r,g,b = ', nco, co(nco)%r, co(nco)%g, co(nco)%b\n    nco = nco + 1\n\n  end subroutine define_color\n\n!****************************************************************************************\n\n  subroutine new_color(name, r, g, b)\n    implicit none\n    character(len=*), intent(in) :: name\n    real, intent(in) :: r, g, b\n    integer :: i\n\n    do i = 0, nco-1\n       if (co(i)%name == name) then\n          write(*,'(\"Subroutine NEW_COLOR:  color \",A,\" already defined.\")') name\n          return\n       endif\n    enddo\n\n    co(nco)= named_color(name, r, g, b)\n    call gscr(1, nco, co(nco)%r, co(nco)%g, co(nco)%b)\n    nco = nco + 1\n\n  end subroutine new_color\n\n!****************************************************************************************\n\n  integer function color_index(name) result(ci)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer :: i\n\n    do i = 0, nco-1\n       ! print*, 'i, co(i)%name, name = ', i, trim(co(i)%name), trim(name)\n       if (co(i)%name == name) then\n          ci = i\n          return\n       endif\n    enddo\n\n    ! If the color has not already been defined, define it.\n    call define_color(name)\n    do i = 0, nco-1\n       if (co(i)%name == name) then\n          ci = i\n          return\n       endif\n    enddo\n\n    ! If the color is STILL not defined, we've got more problems than that.\n    print*, 'function COLOR_INDEX:  Color not defined: ', trim(name)\n    stop\n\n  end function color_index\n\n!****************************************************************************************\n\n  subroutine named_color_sequence(seqname, cbeg, cend)\n    implicit none\n    character(len=*) :: seqname\n    real :: cbeg, cend\n    integer :: i, nnco\n    real :: r\n\n    nsqmin = cbeg\n    nsqmax = cend\n\n    select case (seqname)\n    case (\"precip\")\n       call initcosq\n       nnco = 16\n       do i = 1, nnco\n          r = (cend-cbeg)*float(i-1)/float(nnco-1) + cbeg\n          select case (i)\n          case (1)\n             call addcosq(r, \"white\")\n          case (2)\n             call addcosq(r, \"gray70\")\n          case (3)\n             call addcosq(r, \"darkgreen\")\n          case (4)\n             call addcosq(r, \"green3\")\n          case (5)\n             call addcosq(r, \"green\")\n          case (6)\n             call addcosq(r, \"gold\")\n          case (7)\n             call addcosq(r, \"goldenrod\")\n          case (8)\n             call addcosq(r, \"darkgoldenrod\")\n          case (9)\n             call addcosq(r, \"orange3\")\n          case (10)\n             call addcosq(r, \"tomato3\")\n          case (11)\n             call addcosq(r, \"red4\")\n          case (12)\n             call addcosq(r, \"darkorchid4\")\n          case (13)\n             call addcosq(r, \"darkorchid3\")\n          case (14)\n             call addcosq(r, \"slateblue2\")\n          case (15)\n             call addcosq(r, \"dodgerblue3\")\n          case (16)\n             call addcosq(r, \"cyan\")\n          end select\n\n       enddo\n    case (\"temperature\")\n\n       call initcosq\n       nnco = 6\n       do i = 1, nnco\n          r = (cend-cbeg)*float(i-1)/float(nnco-1) + cbeg\n          select case (i)\n          case (1)\n             call addcosq(r, \"cyan\")\n          case (2)\n             call addcosq(r, \"blue\")\n          case (3)\n             call addcosq(r, \"white\")\n          case (4)\n             call addcosq(r, \"red\")\n          case (5)\n             call addcosq(r, \"magenta\")\n          case (6)\n             call addcosq(r, \"green\")\n          end select\n       enddo\n    case default\n       print*, 'NAMED_COLOR_SEQUENCE: unknown sequence name: ', trim(seqname)\n    end select\n\n  end subroutine named_color_sequence\n\n!****************************************************************************************\n\n  subroutine set_color_sequence(cosqstr)\n    implicit none\n    character(len=*), intent(in) :: cosqstr\n    integer :: i, j, ierr\n\n    call initcosq\n\n    i = 1\n    j = index(cosqstr(i:),',')\n    parse : do\n\n       nsq = nsq + 1\n       read(cosqstr(i:j-1),*, iostat=ierr) rsq(nsq)\n       if (ierr /= 0) then\n          write(*,'(\"Problem reading float from:  #\", A,\"#\" )') cosqstr(i:j)\n          stop\n       endif\n       i = j+1\n       j = index(cosqstr(i:),',')-1+i\n\n       if (j > i) then\n          cosq(nsq) = cosqstr(i:j-1)\n          i = j+1\n          j = index(cosqstr(i:),',')-1+i\n       else\n          cosq(nsq) = cosqstr(i:)\n          exit\n       endif\n    enddo parse\n\n    ! Make sure that the color sequence values are ascending:\n    do i = 1, nsq-1\n       if (rsq(i+1) < rsq(i)) then\n          write(*,'(\"Color sequence out of order:\")')\n          do j = 1, nsq\n             if (j == i) then\n                write(*,*) \"------>\", rsq(j), cosq(j) , \"<-------\"\n             else\n                write(*,*) \"       \", rsq(j), cosq(j)\n             endif\n          enddo\n          stop\n       endif\n    enddo\n\n  end subroutine set_color_sequence\n\n!****************************************************************************************\n\n  subroutine initcosq()\n    implicit none\n    nsq = 0\n    rsq = 0\n    cosq = \"\"\n  end subroutine initcosq\n\n!****************************************************************************************\n\n  subroutine addcosq(rval, coname)\n    implicit none\n    real :: rval\n    character(len=*) :: coname\n\n    nsq = nsq + 1\n    rsq(nsq)  = rval\n    cosq(nsq) = coname\n  end subroutine addcosq\n\n!****************************************************************************************\n\n  subroutine set_gscr_color_indices(is,ie,seqstr)\n    ! Set all the ncargks color indices between IS and IE to the\n    ! colors listed in the SEQSTR\n\n    implicit none\n\n    integer, intent(in) :: is ! Index Start\n    integer, intent(in) :: ie ! Index End\n\n    character(len=*), intent(in) :: seqstr ! Color Sequence String,\n    ! of the form \"cval,color,cval,color,cval,color...\"\n\n\n    type copair_type\n       real :: xseq\n       character(len=64) :: hseq\n       real :: r, g, b\n    end type copair_type\n\n    type(copair_type), dimension(256) :: copair\n\n    type(named_color) :: c\n\n\n    integer :: cocount\n\n    integer :: ii, jj, ir, ig, ib\n    character(len=4096) :: current\n    real :: xseq\n    character(len=64) :: hseq\n\n    real :: x, minseq, maxseq, f, r, g, b, h\n\n    ! Parse the seqstr\n    current = trim(seqstr)//\",\"\n\n    ii = index(current,\",\");\n    cocount = 0\n    do while (ii > 0)\n       read(current(1:ii-1),*) xseq\n       current = current(ii+1:)\n       ii = index(current,\",\");\n       hseq = current(1:ii-1)\n       current = current(ii+1:)\n       ii = index(current,\",\")\n       cocount = cocount + 1\n\n       copair(cocount)%xseq = xseq\n       copair(cocount)%hseq = hseq\n\n       c = get_x11_color(trim(hseq))\n       copair(cocount)%r = c%r\n       copair(cocount)%g = c%g\n       copair(cocount)%b = c%b\n    enddo\n\n    minseq = copair(1)%xseq\n    maxseq = copair(cocount)%xseq\n\n    do ii = is, ie\n       ! Where are we between min and max.\n       x = minseq + float(ii-is)/float(ie-is)*(maxseq-minseq)\n\n       do jj = 1, cocount-1\n          ! Where is X bounded in our color sequence list.\n          if (x == copair(jj)%xseq) then\n             r = copair(jj)%r\n             g = copair(jj)%g\n             b = copair(jj)%b\n          else\n             if ((x >= copair(jj)%xseq) .and. (x <= copair(jj+1)%xseq)) then\n                f = (x - copair(jj)%xseq)/(copair(jj+1)%xseq-copair(jj)%xseq)\n                h = 1.0-f\n                r = (copair(jj)%r*h + copair(jj+1)%r*f)\n                g = (copair(jj)%g*h + copair(jj+1)%g*f)\n                b = (copair(jj)%b*h + copair(jj+1)%b*f)\n                exit\n             endif\n          endif\n       enddo\n       call gscr(1, ii, r, g, b)\n    enddo\n\n  end subroutine set_gscr_color_indices\n\n!****************************************************************************************\n\n  subroutine fillbox(xmin,xmax,ymin,ymax,icol)\n!\n! Draw filled box\n!\n    implicit none\n\n! Input:\n\n    real, intent(in) :: xmin, xmax, ymin, ymax\n    integer, intent(in) :: icol   ! Color index of the color to use.\n\n! Local:\n    integer, parameter :: nra = 4\n    integer, parameter :: nim = 2\n    integer, parameter :: nnd = nra+2*nim\n    integer, parameter :: nst = nra+nim\n\n    real, dimension(nst) :: dst\n    real, dimension(nnd) :: ind\n    real, dimension(nra) :: x4, y4\n    real :: sz\n    integer :: i\n\n    x4(1:2) = xmin\n    x4(3:4) = xmax\n    y4(1) = ymin\n    y4(2:3) = ymax\n    y4(4) = ymin\n\n    call sfsgfa(x4, y4, nra, dst, nst, ind, nnd, icol)\n  end subroutine fillbox\n\n!****************************************************************************************\n\n  subroutine ngsquares(x,y,ndim,xs,icol)\n!\n! Draw filled squares at specified x-y coordinates\n!\n    implicit none\n\n! Input:\n    integer, intent(in) :: ndim   ! Number of filled squares to draw.\n\n    real, intent(in), dimension(ndim) :: x, y ! x-y coordinates of the centers\n    !  of the squares\n\n    integer, intent(in) :: icol   ! Color index of the color to use.\n    real, intent(in) :: xs        ! Size to draw the squares.\n\n! Local:\n    integer, parameter :: nra = 4\n    integer, parameter :: nim = 2\n    integer, parameter :: nnd = nra+2*nim\n    integer, parameter :: nst = nra+nim\n\n    real, dimension(nst) :: dst\n    real, dimension(nnd) :: ind\n    real, dimension(nra) :: x4, y4\n    real :: sz\n    integer :: i\n\n    sz = xs * 0.5 ! Each side is (1/2)* xs away from the center.\n\n    do i = 1, ndim\n       x4(1) = x(i) - sz\n       x4(2) = x4(1)\n       x4(3) = x(i) + sz\n       x4(4) = x4(3)\n\n       y4(1) = y(i) - sz\n       y4(2) = y(i) + sz\n       y4(3) = y4(2)\n       y4(4) = y4(1)\n\n       call sfsgfa(x4, y4, nra, dst, nst, ind, nnd, icol)\n    enddo\n  end subroutine ngsquares\n\n!****************************************************************************************\n\n  subroutine kwm_color_table(input_string)\n    use kwm_string_utilities\n    implicit none\n    character(len=*), intent(in) :: input_string\n    integer :: istart, iend, iidx\n    integer :: icount, ierr\n    real :: xval\n    character(len=64) :: hcol\n    character(len=1024) :: string\n\n    call initcosq\n\n\n    string = unblank(trim(input_string))\n\n    istart = 1\n    icount = 0\n    iidx = 1\n    do while ( iidx > 0 )\n       iidx = index(string(istart:),',')\n       if (iidx == 0) then\n          iend = len(string) + 1\n       else\n          iend = iidx + istart - 1\n       endif\n\n       if (mod(icount,2) == 0) then\n          read(string(istart:iend-1),*, iostat=ierr) xval\n          if (ierr /= 0) then\n             write(*,'(\"Cannot read float from string: #\",A,\"#\")') string(istart:iend-1)\n             stop\n          endif\n       else\n          hcol = string(istart:iend-1)\n          call addcosq(xval, trim(hcol))\n       endif\n\n       istart = iend+1\n       icount = icount + 1\n\n    enddo\n  end subroutine kwm_color_table\n\n!****************************************************************************************\n\n  subroutine find_good_range(ymin, ymax, expn, irange)\n    !\n    ! Given an initial <ymin> and <ymax> (minimum and maximum of some field), \n    ! return \"good round numbers\" for <ymin> and <ymax>.\n    ! <irange> is the number of steps between our good round <ymin> and good round <ymax>\n    ! <expn> is the power-of-ten scaling applied to get our round numbers.\n    !\n    ! There are <irange> steps of size 10.0**<expn> between output values of <ymin> and <ymax>\n    !\n    implicit none\n    real, intent(inout)  :: ymin\n    real, intent(inout)  :: ymax\n    integer, intent(out) :: expn\n    integer, intent(out) :: irange\n\n    integer :: iymin\n    integer :: iymax\n\n    expn = floor(log10(ymax-ymin)) - 1\n\n    iymin = floor   ( (10.0**(real(-expn))) * ymin )\n    iymax = ceiling ( (10.0**(real(-expn))) * ymax )\n    irange = (iymax-iymin)\n\n    ! If we've got too many steps between iymin and iymax,\n    ! then shift to the next power-of-ten for our scaling.\n    if (irange > 20) then\n       iymin = floor  (real(iymin)*0.1)\n       iymax = ceiling(real(iymax)*0.1)\n       expn = expn + 1\n       irange = (iymax-iymin)\n    endif\n\n    ymin = real(iymin) * 10.0**(real(expn))\n    ymax = real(iymax) * 10.0**(real(expn))\n\n  end subroutine find_good_range\n\n!****************************************************************************************\n\n  subroutine line_in_color_integer(x1, y1, x2, y2, color, line_width)\n    !\n    ! Draw a straight line from point (x1,y1) to point (x2,y2).\n    ! The optional <color> can adjust the line color.\n    ! The optional <line_width> can adjust the line width.\n    !\n    ! At the end of the routine, the preset color and line width\n    ! revert back to the values in place before the subroutine was called.\n    implicit none\n    real,              intent(in) :: x1, y1, x2, y2\n    integer,           intent(in) :: color\n    real,    optional, intent(in) :: line_width\n\n    integer :: ierr, color_save\n    real    :: line_width_save\n\n    if (present(line_width)) then\n       call gqlwsc(ierr, line_width_save)\n       call gslwsc(line_width)\n    endif\n\n    call gqplci(ierr, color_save)\n    call gsplci(color)\n\n    call frstpt(x1,y1)\n    call vector(x2,y2)\n    call plotif(0., 0., 2)\n\n    call gsplci(color_save)\n\n    if (present(line_width)) then\n       call gslwsc(line_width_save)\n    endif\n\n  end subroutine line_in_color_integer\n\n  subroutine line_in_color_string(x1, y1, x2, y2, color, line_width)\n    !\n    ! Draw a straight line from point (x1,y1) to point (x2,y2).\n    ! The optional <color> can adjust the line color.\n    ! The optional <line_width> can adjust the line width.\n    !\n    ! At the end of the routine, the preset color and line width\n    ! revert back to the values in place before the subroutine was called.\n    implicit none\n    real,                       intent(in) :: x1, y1, x2, y2\n    character(len=*),           intent(in) :: color\n    real,             optional, intent(in) :: line_width\n\n    integer :: ierr, color_save\n    real    :: line_width_save\n\n    if (present(line_width)) then\n       call gqlwsc(ierr, line_width_save)\n       call gslwsc(line_width)\n    endif\n\n    call gqplci(ierr, color_save)\n    call gsplci(color_index(color))\n\n    call frstpt(x1,y1)\n    call vector(x2,y2)\n    call plotif(0., 0., 2)\n\n    call gsplci(color_save)\n\n    if (present(line_width)) then\n       call gslwsc(line_width_save)\n    endif\n\n  end subroutine line_in_color_string\n\n!****************************************************************************************\n\n  subroutine connect_the_dots(x, y, n, color, line_width, on_missing)\n    !\n    ! Given paired arrays X and Y, each of size N, connect the dots in order.\n    ! Optional color and line_width settings will override the original settings.\n    ! At the end of the routine, the original color and line_width settings are\n    ! restored.\n    !\n    ! Values more negative than -1.E25 are considered bad data.\n    !    if (on_missing == \"SKIP\") then\n    !        Skip over bad data, connecting all good data points in order.\n    !    else if (on_missing == \"BREAK\") then\n    !        Break the line at a bad data point, restarting at the next good point.\n    !    endif\n    !\n    implicit none\n    integer,                    intent(in) :: n\n    real,         dimension(n), intent(in) :: x\n    real,         dimension(n), intent(in) :: y\n    character(len=*), optional, intent(in) :: color\n    real,             optional, intent(in) :: line_width\n    character(len=*), optional, intent(in) :: on_missing\n\n    integer :: i, ierr, color_save\n    real    :: line_width_save\n    logical :: pd\n    logical :: skip\n\n    if (present(color)) then\n       call gqplci(ierr, color_save)\n       call gsplci(color_index(color))\n    endif\n\n    if (present(line_width)) then\n       call gqlwsc(ierr, line_width_save)\n       call gslwsc(line_width)\n    endif\n\n    if (present(on_missing)) then\n       if (on_missing == \"SKIP\") then\n          skip = .TRUE.\n       else if (on_missing == \"BREAK\") then\n          skip = .FALSE.\n       else\n          write(*,'(\"CONNECT_THE_DOTS:\")')\n          write(*,'(\"   Optional ON_MISSING should be ''SKIP'' or ''BREAK'', not ''\",A,\"''\")') on_missing\n          stop\n       endif\n    else\n       skip = .TRUE.\n    endif\n\n    pd = .FALSE.\n\n    if (skip) then\n       do i = 1, n\n          if (y(i) > -1.E25) then\n             if (pd) then\n                call vector(x(i), y(i))\n             else\n                call frstpt(x(i), y(i))\n                pd = .TRUE.\n             endif\n          endif\n       enddo\n    else\n       do i = 1, n\n          if (y(i) > -1.E25) then\n             if (pd) then\n                call vector(x(i), y(i))\n             else\n                call frstpt(x(i), y(i))\n                pd = .TRUE.\n             endif\n          else\n             if (pd) then\n                call plotif(0., 0., 2)\n                pd = .FALSE.\n             endif\n          endif\n       enddo\n    endif\n    call plotif(0., 0., 2)\n\n    if (present(color)) then\n       call gsplci(color_save)\n    endif\n\n    if (present(line_width)) then\n       call gslwsc(line_width_save)\n    endif\n\n  end subroutine connect_the_dots\n!****************************************************************************************\n\nend module kwm_plot_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/kwm_string_utilities.F",
    "content": "module kwm_string_utilities\n\ncontains\n\n  subroutine strrep(string, rep1, rep2)\n    ! In string 1, replace expression rep1 with expression rep2.\n    ! if rep2 is shorter than rep1, fill the end of the string\n    ! with blanks\n\n    implicit none\n    character(len=*) :: string, rep1, rep2\n    integer :: idx, inlen, len1, len2\n\n    do\n       inlen = len(string)\n       len1 = len(rep1)\n       len2 = len(rep2)\n       idx = index(string, rep1)-1\n\n       if (idx == -1) then\n          return\n       else\n          string = string(1:idx)// rep2 // &\n               string((idx+len1+1):inlen) // &\n               \"                                                    \"\n       endif\n    enddo\n\n  end subroutine strrep\n\n\n  character(len=1024) function unblank(string) result(return_string)\n    ! Remove blanks (and tabs [char(9)] from string\n    implicit none\n    character(len=*), intent(in) :: string\n    integer :: i, j,  lenstr\n\n    return_string = \"\"\n\n    if ( verify(string,\" \"//char(9)) == 0 ) then\n       stop 'String is all blanks.'\n    endif\n\n    j = 0\n    do i = 1, len(string)\n       if ((string(i:i).ne.' ').and.(string(i:i).ne.char(9))) then\n          j = j + 1\n          return_string(j:j) = string(i:i)\n       endif\n    enddo\n\n  end function unblank\n\n!KWM  character function upcase(h)\n!KWM    implicit none\n!KWM    character :: h\n!KWM\n!KWM    if ((ichar(h).ge.96) .and. (ichar(h).le.123)) then\n!KWM       upcase = char(ichar(h)-32)\n!KWM    else\n!KWM       upcase = h\n!KWM    endif\n!KWM\n!KWM  end function upcase\n\n  character(len=256) function upcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \"\"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.96) .and. (ichar(h(i:i)).le.123)) then\n          return_string(i:i) = char(ichar(h(i:i))-32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function upcase\n\n!KWM  character function downcase(h)\n!KWM    implicit none\n!KWM    character h\n!KWM\n!KWM    if ((ichar(h).ge.65) .and. (ichar(h).le.90)) then\n!KWM       downcase = char(ichar(h)+32)\n!KWM    else\n!KWM       downcase = h\n!KWM    endif\n!KWM  end function downcase\n\n  character(len=256) function downcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \"\"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.65) .and. (ichar(h(i:i)).le.90)) then\n          return_string(i:i) = char(ichar(h(i:i))+32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function downcase\n\n\nend module kwm_string_utilities\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/lccone.F",
    "content": "subroutine lccone (fsplat,ssplat,sign,confac)\n  real, parameter :: conv=0.01745329251994\n  integer :: sign\n  real :: fsplat,ssplat,confac\n  if (abs(fsplat-ssplat).lt.1.E-2) then\n     confac = sin(fsplat*conv)\n  else\n     confac = log10(cos(fsplat*conv))-log10(cos(ssplat*conv))\n     confac = confac/(log10(tan((45.-float(sign)*fsplat/2.)*conv))-&\n          log10(tan((45.-float(sign)*ssplat/2.)*conv)))\n  endif\nend subroutine lccone\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/llxy_generic.F",
    "content": "subroutine lltoxy_generic (xlat,xlon,x,y,&\n     project,dskm,reflat,reflon,refx,refy,&\n     cenlon,truelat1,truelat2)\n\n!*****************************************************************************!\n!  Notes    - Modeled after XYTOLL in the plots.o library                     !\n!*****************************************************************************!\n\n  implicit none\n\n! Input: ---------------------------------------------------------------------!\n\n  real ::             xlat       ! latitude of the point of interest.\n  real ::             xlon       ! longitude of the point of interest.\n  character(LEN=2) :: project    ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n  real ::             dskm         ! grid distance in km\n  real ::             reflat\n  real ::             reflon\n  real ::             refx\n  real ::             refy\n  real ::             cenlon     ! Grid ratio with respect to MOAD\n  real ::             truelat1   ! True latitude 1, closest to equator\n  real ::             truelat2   ! True latitude 2, closest to pole\n\n! Output: --------------------------------------------------------------------!\n\n  real ::             x          ! x location of the given (lat,lon) point\n  real ::             y          ! y location of the given (lat,lon) point\n\n!  Parameters: ---------------------------------------------------------------!\n\n  real, parameter :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter :: piovr2 = pi/2.\n!  real, parameter :: re = 6370.949     ! the radius of the earth in km\n  real, parameter :: re = 6371.2       ! the radius of the earth in km\n  real, parameter :: ce = 2.*pi*re     ! the circumference of the earth in km\n  real, parameter :: degrad = pi/180.\n\n!  Real variables: -----------------------------------------------------------!\n\n  real          :: flat1\n  real          :: confac            ! cone factor\n  real          :: rcln              ! center longitude in radians  (local)\n  real          :: dj                ! distance from pole to point  (local)\n  real          :: di                ! distance from the central\n                                     !  meridian to the point        (local)\n  real          :: bm                ! calculation variable         (local)\n\n  real :: rflt, rfln, rlat, rlon, diovrdj, disdjs, ri, rj\n  real :: ct1, st1, tt1, drp\n  real :: isn, pi2\n  real :: londiff\n\n!****************************  subroutine begin  *****************************!\n\n\n  rlat =  xlat * degrad\n  rlon =  xlon * degrad\n  rcln = cenlon * degrad\n  flat1 = truelat1 * degrad\n  rflt = reflat * degrad\n  rfln = reflon * degrad\n\n  if ((xlon - cenlon) < -180) then\n     londiff = ((xlon-cenlon)+360.)*degrad\n  else if ((xlon - cenlon) > 180) then\n     londiff = ((xlon-cenlon)-360.)*degrad\n  else\n     londiff = (xlon-cenlon)*degrad\n  endif\n\n\n  if (project(1:2) .eq. 'ME') then\n\n     ct1 = re*cos(flat1)\n     dj = ct1 * log(tan (0.5*(rlat + piovr2)))\n     di = ct1 * (rlon - rfln)\n     y = refy +(dj + ct1 * log(cos(rflt)/(1 + sin(rflt))))/dskm\n     x = refx + di/dskm\n\n  else if (project(1:2) .eq. 'CE') then\n\n!KWM     dj = re*(rlat-rflt)\n!KWM     di = re*(rlon-rfln)\n!KWM     y = refy + dj/dskm\n!KWM     x = refx + di/dskm\n\n     ! NOTE:  Cylindrical Equidistant grid increment expressed in terms\n     ! of thousandths of degrees!\n     !  Calculate the distance from the horizontal axis to (J,I)\n     dj = xlat-reflat\n     di = xlon-reflon\n     y = refy + (dj/dskm)\n     x = refx + (di/dskm)\n\n  else if (project(1:2) .eq. 'LC') then\n\n     isn = sign(1.0, truelat2)\n     pi2 = piovr2*isn\n\n     call lccone(truelat1,truelat2,int(sign(1.0, truelat2)),confac)\n     tt1 = tan((pi2 - flat1)*0.5) ! Tangent Term 1.\n     st1 = sin (pi2 - flat1) * re/(confac*dskm)     ! Sine Term 1.\n     bm =  tan((pi2 - rlat)*0.5)\n     if ((rlon-rcln) > pi) then\n        diovrdj = -tan(((rlon-rcln)-2.*pi)*confac)\n     elseif ((rlon-rcln) < -pi) then\n        diovrdj = -tan(((rlon-rcln)+2.*pi)*confac)\n     else\n        diovrdj = -tan((rlon-rcln)*confac)\n     endif\n     disdjs = ( (bm/tt1)**confac * st1)**2\n     ! Dj: y distance (km) from pole to given x/y point.\n     dj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n     ! Di: x distance (km) from central longitude to given x/y point.\n     di = dj * diovrdj\n\n     bm = tan((pi2-rflt)*0.5)\n     if ((rfln-rcln) > pi) then\n        diovrdj = -tan(((rfln-rcln)-2.*pi)*confac)\n     else if ((rfln-rcln) < -pi) then\n        diovrdj = -tan(((rfln-rcln)+2.*pi)*confac)\n     else\n        diovrdj = -tan((rfln - rcln)*confac)\n     endif\n     disdjs = ( (bm/tt1)**confac * st1)**2\n     ! Rj: y distance (km) from pole to reference point.\n     rj = -sqrt(disdjs/(1+diovrdj*diovrdj))\n     ! Ri: x distance (km) from central longitude to reference x/y point.\n     ri = rj * diovrdj\n     y = refy + isn*(dj - rj)\n     x = refx + (di - ri)\n\n  else if (project(1:2) .eq. 'ST') then\n\n     isn = sign(1.0, truelat1)\n     pi2 = piovr2*isn\n\n     diovrdj = -tan(rfln-rcln)\n     bm = (re/dskm)*tan(0.5*(pi2-rflt))\n     disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n     ! RJ:  Distance from pole to reference latitude along the center lon\n     rj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rfln-rcln))\n     ! RI:  Distance from center reference to requested point rlat, rlon.\n     ri = rj * diovrdj\n     diovrdj = -tan(rlon-rcln)\n     bm = (re/dskm)*tan(0.5*(pi2-rlat))\n     disdjs = (bm*(1.0 + cos(pi2-flat1)))**2\n     dj = -sign(sqrt(disdjs/(1+diovrdj**2)),cos(rlon-rcln))\n     di = dj * diovrdj\n     y = refy + isn*(dj-rj)\n     x = refx + (di-ri)\n  endif\n\n!*****************************  Subroutine End  ******************************!\n\nend subroutine lltoxy_generic\n\nsubroutine xytoll_generic (x,y,xlat,xlon,&\n     project,dskm,reflat,reflon,refx,refy,&\n     cenlon, truelat1,truelat2)\n\n!*****************************************************************************!\n!  xytoll                                                                     !\n!  Purpose  - To  transform  mesoscale grid point coordinates (x,y) into      !\n!             latitude and longitude coordinates.                             !\n!                                                                             !\n!  On entry - X  and  Y are an ordered pair representing a grid point in  the !\n!             mesoscale grid.                                                 !\n!                                                                             !\n!  On exit  - XLAT, XLON contain  the latitude and longitude respectively     !\n!             that resulted from the transformation.                          !\n!                                                                             !\n!*****************************************************************************!\n  implicit none\n\n! Input\n  real ::             x         ! x (i) coordinate of point of interest\n  real ::             y         ! y (j) coordinate of point of interest\n  character(LEN=2) :: project   ! projection indicator (\"ME\", \"CE\", \"LC\", \"ST\")\n  real ::             dskm      ! grid distance in km\n  real ::             reflat    ! latitude of the reference point\n  real ::             reflon    ! longitude of the reference point\n  real ::             refx\n  real ::             refy\n  real ::             cenlon    ! longitude of the center of the projection\n  real ::             truelat1  ! True latitude 1.\n  real ::             truelat2  ! True latitude 2.\n\n! Output\n  real ::             xlat      ! latitude of point (x,y)\n  real ::             xlon      ! longitude of point (x,y)\n\n! Parameters\n\n  real, parameter :: pi = 3.141592653589793   ! you know!  pi = 180 degrees\n  real, parameter :: piovr2 = pi/2.\n  real, parameter :: twopi  = pi*2.\n!  real, parameter :: re = 6370.949     ! the radius of the earth in km\n  real, parameter :: re = 6371.2\n  real, parameter :: degrad = pi/180.\n\n!  Real variables\n\n  real ::            confac           ! cone factor\n  real ::            rfln             ! reference longitude in radians  (local)\n  real ::            rflt             ! reference latitude in radians   (local)\n  real ::            rcln             ! center longitude in radians  (local)\n  real ::            dj, drp, djj     ! distance from the central\n!                                       meridian to the point        (local)\n  real ::            di,dii           ! distance from pole to point  (local)\n  real ::            bm               ! calculation variable         (local)\n  real ::            flat1\n  real ::            ct1, tt1, tt2, pi2\n  integer :: isn\n!****************************  subroutine begin  *****************************!\n\n  rflt = reflat * degrad\n  rfln = reflon * degrad\n  rcln = cenlon * degrad\n  flat1 = truelat1 * degrad\n\n!  If the projection is mercator ('ME') then ...\n\n  if (project(1:2) .eq. 'ME') then\n     di = (x-refx) * dskm\n     !  Calculate the distance the point in question is from the pole\n     dj = -re * cos(flat1)*log(cos(rflt)/(1 + sin(rflt))) + &\n          (y - refy) * dskm\n     !  Calculate the latitude desired in radians\n     xlat = 2.0 * atan(exp(dj/(re*cos(flat1)))) - piovr2\n     !  Calculate the longitude desired in radians\n     xlon = rfln + di/(re*cos(flat1))\n\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n\n! If the projection is cylindrical equidistant ('CE') then ...\n  else if (project(1:2) .eq. 'CE') then\n     ! NOTE:  Cylindrical Equidistant grid increment expressed in terms\n     ! of thousandths of degrees!\n     di = (x-refx) * dskm\n     !  Calculate the distance from the horizontal axis to (J,I)\n     dj = (y-refy) * dskm\n     !  Determine the shift north-south\n     xlat = reflat + dj\n     !  Determine the shift east-west\n     xlon = reflon + di\n\n! If the projection is lambert conic conformal ('LC') then ...\n  else if (project(1:2) .eq. 'LC') then\n\n     isn = sign(1.0, truelat2)\n     pi2 = piovr2*isn\n\n     call lccone(truelat1,truelat2,isn,confac)\n\n     tt1 = tan((pi2 - flat1)*0.5)    ! Tangent Term 1.\n     tt2 = tan((pi2 - rflt  )*0.5)    ! Tangent Term 2.\n     ct1 = -cos(flat1) * re/confac   ! cosine Term 1.\n\n     ! Calculate the (projected) distance from the pole to\n     ! the reference lat/lon.\n     drp = ct1 * (tt2/tt1)**confac\n     ! Now from the pole to the reference y along the center lon.\n     djj = drp * cos((rcln-rfln)*confac)\n\n     ! Now from the pole to the requested y along the center lon.\n     dj = djj + isn * ((y-refy)*dskm)\n     ! Now the (projected) distance from center longitude to reference x\n     dii = drp*sin((rcln-rfln)*confac)\n     ! And now from center longitude to requested X\n     di = dii + ((x-refx)*dskm)\n     !  Calculate the Big Messy equation\n     bm = tt1 * (sqrt(di**2+dj**2) /  abs(ct1))**(1.0/confac)\n     !  Calculate the desired latitude in radians\n     xlat = pi2 - 2.0*atan(bm)\n     !  Calculate the desired longitude in radians\n     xlon = rcln + (1.0/confac) * atan2(di,-dj)\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n\n!  If the projection is polar stereographic ('ST') then ...\n\n  else if (project(1:2) .eq. 'ST') then\n\n     isn = sign(1.0, truelat1)\n     pi2 = piovr2*isn\n\n\n!  Calculate the (projected) y-distance I,J lies from the pole\n\n     drp = -re*cos(rflt) * (1.0 + cos(pi2-flat1)) / (1.0 + cos(pi2-rflt))\n     djj = drp * cos(rcln-rfln)\n     dj = djj + isn*( (y-refy) * dskm )\n     dii = drp * sin(rcln-rfln)\n     di = dii + ((x-refx)*dskm)\n     ! Calculate the Big Messy quantity as would be done for LC\n     ! projections.  This quantity is different in value, same\n     ! in purpose of BM above\n     bm = (1.0/re) * sqrt(di*di + dj*dj) / (1.0 + cos(pi2-flat1))\n     !  Calculate the desired latitude in radians\n     xlat = pi2 - isn*2.0 * atan(bm)\n     !  Calculate the desired longitude in radians\n     xlon = rcln + atan2(di,-dj)\n\n     !  Convert the calculated lat,lon pair into degrees\n     xlat = xlat * 180.0/pi\n     xlon = xlon * 180.0/pi\n\n  else\n     print*, 'Unrecognized project:  ', project\n     stop\n  end if\n\n!  Make sure no values are greater than 180 degrees and none\n!  are less than -180 degrees\n\n  if (xlon .gt. 180.0)  xlon = xlon - 360.0\n  if (xlon .lt. -180.0) xlon = xlon + 360.0\n\n!*****************************  Subroutine End  ******************************!\n\nend subroutine xytoll_generic\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/module_hd.F",
    "content": "module module_hd\n  use netcdf\n  type nf_structure\n     sequence\n     integer :: ncid\n     integer :: nvar\n     integer :: ndim\n     character(len=NF90_MAX_NAME), dimension(NF90_MAX_DIMS) :: dimname\n     integer, dimension(NF90_MAX_DIMS) :: dimlen\n     integer :: tdim\n     integer :: idim\n     integer :: jdim\n     integer :: kdim\n     integer :: map_proj\n     real    :: dskm\n     real    :: xlonc\n     real    :: truelat1\n     real    :: truelat2\n     real    :: reflat\n     real    :: reflon\n     real    :: refx\n     real    :: refy\n  end type nf_structure\n\n  interface netcdf_get_field\n     module procedure netcdf_get_field_2d, netcdf_get_field_3d\n  end interface\n\ncontains\n\n  subroutine netcdf_get_time(nfstruct, name, time_index, time_return)\n    implicit none\n    type(nf_structure), intent(in) :: nfstruct\n    character(len=*),   intent(in) :: name\n    integer,            intent(in) :: time_index\n    integer :: ncid, varid, dimid\n    integer :: iret, DateStrLen\n    integer, dimension(2) :: start, nfcount\n    character(len=24) :: time_return\n\n    ncid = nfstruct%ncid\n\n    ! We need the varid of this field\n    iret = nf90_inq_varid(ncid, name, varid)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQ_VARID:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_inq_dimid(ncid, \"DateStrLen\", dimid)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQ_DIMID (for DateStrLen):  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_inquire_dimension(ncid, dimid, len=DateStrLen)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQUIRE_DIMENSION:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    start(1) = 1\n    start(2) = time_index\n    nfcount(1) = DateStrLen\n    nfcount(2) = 1\n\n    iret = nf90_get_var(ncid, varid, time_return, start, nfcount)\n    if (iret /= 0) then\n       write(*,'(\"netcdf_get_time:  NF90_GET_VAR:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n\n  end subroutine netcdf_get_time\n\n  subroutine netcdf_get_field_2d(nfstruct, name, time_index, ptr2d)\n    implicit none\n    type(nf_structure), intent(in) :: nfstruct\n    integer, intent(in) :: time_index\n    real, pointer, dimension(:,:) :: ptr2d\n    character(len=*), intent(in) :: name\n    integer :: iret\n    integer, dimension(20) :: start, nfcount\n    integer :: varid\n    integer, dimension(20) :: dimids\n    integer :: ndims\n    integer :: ncid\n\n    ncid = nfstruct%ncid\n\n    ! We need the varid of this field\n    iret = nf90_inq_varid(ncid, name, varid)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQ_VARID:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    ! We need the dimensions of this variable\n    iret = nf90_inquire_variable(ncid, varid, ndims=ndims, dimids=dimids)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQUIRE_VARIABLE:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n\n    if (ndims == 3) then\n       allocate(ptr2d(nfstruct%idim,nfstruct%jdim))\n       start(1) = 1\n       start(2) = 1\n       start(3) = time_index\n       nfcount(1) = nfstruct%idim\n       nfcount(2) = nfstruct%jdim\n       nfcount(3) = 1\n    else\n       print*, 'ndim = ', nfstruct%ndim\n       print*, 'name = ', name\n       stop \"NETCDF_GET_FIELD: No can do with these dimensions.\"\n    endif\n\n    iret = nf90_get_var(ncid, varid, ptr2d, start, nfcount)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_VAR:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n  end subroutine netcdf_get_field_2d\n\n  subroutine netcdf_get_field_3d(nfstruct, name, time_index, ptr3d)\n    implicit none\n    type(nf_structure), intent(in) :: nfstruct\n    integer, intent(in) :: time_index\n    real, pointer, dimension(:,:,:) :: ptr3d\n    character(len=*), intent(in) :: name\n    integer :: iret\n    integer, dimension(20) :: start, nfcount\n    integer :: varid\n    integer, dimension(20) :: dimids\n    integer :: ndims\n    integer :: ncid\n\n    ncid = nfstruct%ncid\n\n    ! We need the varid of this field\n    iret = nf90_inq_varid(ncid, name, varid)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQ_VARID:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    ! We need the dimensions of this variable\n    iret = nf90_inquire_variable(ncid, varid, ndims=ndims, dimids=dimids)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQUIRE_VARIABLE:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n\n    if (ndims == 4) then\n       allocate(ptr3d(nfstruct%idim,nfstruct%jdim,nfstruct%kdim))\n       start(1) = 1\n       start(2) = 1\n       start(3) = 1\n       start(4) = time_index\n       nfcount(1) = nfstruct%idim\n       nfcount(2) = nfstruct%jdim\n       nfcount(3) = nfstruct%kdim\n       nfcount(4) = 1\n    else\n       print*, 'ndim = ', nfstruct%ndim\n       print*, 'name = ', name\n       stop \"NETCDF_GET_FIELD: No can do with these dimensions.\"\n    endif\n\n    iret = nf90_get_var(ncid, varid, ptr3d, start, nfcount)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_VAR:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n  end subroutine netcdf_get_field_3d\n\n  subroutine netcdf_open(flnm, nfstruct)\n    ! Opens a netcdf file and fills the fields in nfstruct for:\n    !      ncid\n    !      nvar\n    !      ndim\n    !      dimname\n    !      dimlen\n    !      tdim\n    !      idim\n    !      jdim\n    !      kdim\n    !   etc.\n    ! use netcdf\n    ! use module_hd\n    implicit none\n\n    character(len=*), intent(in)    :: flnm\n    type(nf_structure), intent(out) :: nfstruct\n\n    integer :: iret\n    integer :: ncid\n    integer :: nvar\n    integer :: ndim\n    integer :: dimid\n    character(len=NF90_MAX_NAME), dimension(NF90_MAX_DIMS) :: dimname\n    integer, dimension(NF90_MAX_DIMS) :: dimlen\n    integer :: tdim, idim, jdim, kdim, map_proj\n    real    :: dskm, truelat1, truelat2, xlonc\n    real    :: reflat, reflon\n    real    :: dxm\n\n    tdim = 0\n    idim = 0\n    jdim = 0\n    kdim = 1\n\n    iret = nf90_open(trim(flnm), NF90_NOWRITE, ncid)\n    if (iret /= 0) then\n       write(*,'(\"NF90_OPEN:  \",A)') nf90_strerror(iret)\n       write(*,'(A)') \"FILE = '\"//trim(flnm)//\"'\"\n       stop\n    endif\n\n    iret = nf90_inquire(ncid, nVariables=nvar,  nDimensions=ndim)\n    if (iret /= 0) then\n       write(*,'(\"NF90_INQUIRE nVariables:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n!KWM    print*, 'nvar = ', nvar, '  ndim = ', ndim\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", map_proj)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for MAP_PROJ:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\", dxm)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for DX:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n    dskm = dxm * 1.E-3\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for TRUELAT1:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for TRUELAT2:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", xlonc)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for STAND_LON:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"LAT1\", reflat)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for LAT1:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"LON1\", reflon)\n    if (iret /= 0) then\n       write(*,'(\"NF90_GET_ATT problem for LON1:  \",A)') nf90_strerror(iret)\n       stop\n    endif\n\n    do dimid = 1, ndim\n       iret = nf90_inquire_dimension(ncid, dimid, dimname(dimid), dimlen(dimid))\n       if (iret /= 0) then\n          write(*,'(\"NF90_INQUIRE_DIMENSION:  \",A)') nf90_strerror(iret)\n          stop\n       endif\n!KWM       write(*,'(\"Dimension = \", A20, 2x, i5)') dimname(dimid), dimlen(dimid)\n       if (dimname(dimid) == \"Times\") tdim = dimlen(dimid)\n       if (dimname(dimid) == \"west_east\") idim = dimlen(dimid)\n       if (dimname(dimid) == \"south_north\") jdim = dimlen(dimid)\n       if (dimname(dimid) == \"soil_layers_stag\") kdim = dimlen(dimid)\n    enddo\n\n    nfstruct%ncid = ncid\n    nfstruct%nvar = nvar\n    nfstruct%ndim = ndim\n    nfstruct%dimname = dimname\n    nfstruct%dimlen = dimlen\n    nfstruct%tdim = tdim\n    nfstruct%idim = idim\n    nfstruct%jdim = jdim\n    nfstruct%kdim = kdim\n    nfstruct%map_proj = map_proj\n    nfstruct%truelat1 = truelat1\n    nfstruct%truelat2 = truelat2\n    nfstruct%dskm    = dskm\n    nfstruct%xlonc    = xlonc\n    nfstruct%reflat   = reflat\n    nfstruct%reflon   = reflon\n    nfstruct%refx     = 1.0\n    nfstruct%refy     = 1.0\n  end subroutine netcdf_open\n\n  subroutine lltoxy_hd(lat, lon, x, y, nfstruct)\n    real, intent(in) :: lat, lon\n    real, intent(out) :: x, y\n    type (nf_structure), intent(in) :: nfstruct\n\n    select case (nfstruct%map_proj)\n    case (1)\n       project = \"LC\"\n    case (2)\n       project = \"ST\"\n    case (3)\n       project = \"ME\"\n    case default\n       print*, 'MODULE_HD:  LLTOXY_HD:  Put the map projection in:  proj = ', nfstruct%map_proj\n       stop\n    end select\n\n    call lltoxy_generic(lat, lon, x, y, &\n         project,nfstruct%dskm,nfstruct%reflat,nfstruct%reflon,nfstruct%refx,nfstruct%refy, &\n         nfstruct%xlonc,nfstruct%truelat1,nfstruct%truelat2)\n\n  end subroutine lltoxy_hd\n\n#if defined( _NCARGKS_ )\n\n  subroutine wrfmap(nfstruct)\n    ! use kwm_plot_utilities\n    implicit none\n    type(nf_structure), intent(in) :: nfstruct\n\n    integer :: jprj\n    real :: plat, plon, rota\n    real :: plm1, plm2, plm3, plm4\n    integer :: jlts = 2;\n    integer :: jgrd = 0;\n    integer :: iout = 4;\n    integer :: idot = 0;\n    integer :: ierr\n    character(len=2) :: project\n\n    if (nfstruct%map_proj == 1) then\n       jprj = 3\n       plat = nfstruct%truelat1\n       plon = nfstruct%xlonc\n       rota = nfstruct%truelat2\n       project = \"LC\"\n       call xytoll_generic(1.0, 1.0, plm1, plm2, &\n            project,nfstruct%dskm,nfstruct%reflat,nfstruct%reflon,nfstruct%refx,nfstruct%refy,&\n            nfstruct%xlonc,nfstruct%truelat1,nfstruct%truelat2)\n\n       call xytoll_generic(float(nfstruct%idim), float(nfstruct%jdim), plm3, plm4, &\n            project,nfstruct%dskm,nfstruct%reflat,nfstruct%reflon,nfstruct%refx,nfstruct%refy,&\n            nfstruct%xlonc,nfstruct%truelat1,nfstruct%truelat2)\n    else\n       print*, 'Put the map projection in:  proj = ', nfstruct%map_proj\n       stop\n    endif\n\n    print*, 'call supmap:  ', jprj, plat, plon, rota, plm1, plm2, plm3, plm4, jlts, jgrd, iout, idot, ierr\n    call supmap(jprj, plat, plon, rota, plm1, plm2, plm3, plm4, jlts, jgrd, iout, idot, ierr)\n\n  end subroutine wrfmap\n\n#endif\n\nend module module_hd\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/okmeso.namelist",
    "content": "&okmeso\n  ldasout_dir     = \"/scholar2/kmanning/VERY_TEMPORARY_HRLDAS/Run_3.2\"\n  okmeso_soil_dir = \"/scholar/kmanning/more_hrldas/OKMESO/SoilMoisture\"\n  okmeso_met_dir  = \"/scholar/kmanning/more_hrldas/OKMESO/MetVariables\"\n\n  statistics_startdate = \"2002060100\"\n  statistics_enddate   = \"2002063000\"\n/\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/rdbz.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n\n*/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <bzlib.h>\n\nFILE *f[255];\nBZFILE *b[255];\n\n#define BUFFLEN 10485760\n\nint  ibuf = 0;\nint  nbuf;\nint rdit;\nchar buffer[BUFFLEN];\n\nint bz_open_(char *flnm, int *iunit, int *ierr, int *ivrb) {\n\n  /*      Input:  *flnm,  *ivrb   */\n  /*      Output: *iunit, *ierr   */\n  /* ivrb is a verbose flag */\n\n  int bzerror;\n  int i;\n\n  *ierr = 0;\n/*   printf(\"flnm = '%s'\\n\", flnm); */\n\n  /* Find an iunit number, the first unused *f and *b index */\n  /* Use only numbers greater than 99 */\n  for (i = 100; i<256; i++) {\n    if ( ! f[i] ) break;\n  }\n  if (i > 255) {\n    printf(\"too many in bz_open_\\n\");\n    exit ( 1 ) ;\n  }\n  *iunit = i;\n  \n\n  f[*iunit] = fopen(flnm, \"r\");\n  if ( !f ) {\n    printf(\"open error: '%s'\\n\", flnm);\n    *ierr = 1;\n    return (0);\n    exit ( 1 ) ;\n  }\n\n  b[*iunit] = BZ2_bzReadOpen (&bzerror, f[*iunit], 0, 1, NULL, 0);\n  if (bzerror != BZ_OK) {\n    printf(\"bzopen error: '%s'\\n\", flnm);\n    BZ2_bzReadClose (&bzerror, b[*iunit]);\n    *ierr = 2;\n    return(0);\n    exit ( 1 ) ;\n  }\n\n  rdit = 1;\n  if (*ivrb > 0) printf(\"BZOPEN file '%s' as bzunit %i\\n\", flnm, *iunit);\n  return (0);\n}\n\nint bz_read_string_(int *iunit, unsigned char *string, int *length, int *ierr){\n\n  int nbuf;\n  int bzerror;\n\n  nbuf = BZ2_bzRead(&bzerror, b[*iunit], string, *length);\n\n  *ierr = bzerror;\n  return(0);\n\n}\n\nint bz_restart_(int *offset) {\n  rdit = 0;\n  ibuf += *offset;\n  if (ibuf < 0) ibuf = 0;\n}\n\nint bz_advance_line_() {\n  while ( buffer[ibuf] != '\\n') ibuf++;\n  ibuf++;\n}\n\nint bz_getline_(int *iunit, char *string, int *length, int *ierr) {\n  /* \n     Error flags returned:  \n            -1:  ?\n  */\n\n  int bzerror;\n  int istring;\n\n  /* Initialize our string to all blanks. */\n  for (istring=0; istring<*length; istring++) {\n    string[istring] = ' ';\n  }\n\n  /* For  efficiency considerations, read a chunk into a buffer, and \n     take bytes from the buffer as needed.  When the buffer is exhausted,\n     read more into the buffer */\n\n  istring = 0;\n  bzerror = BZ_OK;\n\n READMORE:\n\n  if ((ibuf == 0) && ( rdit )) {\n    printf(\"reading to buffer ... \");\n    nbuf = BZ2_bzRead(&bzerror, b[*iunit], buffer, BUFFLEN);\n    printf(\"nbuf = %i\\n\", nbuf);\n    switch (bzerror) {\n    case BZ_OK:\n      /* ok */\n      *ierr = 0;\n      break;\n    case BZ_STREAM_END:\n      /* ok */\n      *ierr = 0;\n      break;\n    case BZ_PARAM_ERROR:\n      printf(\"bzerror == BZ_PARAM_ERROR\\n\");\n      *ierr = -1;\n      return(0);\n      break;\n    case BZ_SEQUENCE_ERROR:\n      printf(\"bzerror == BZ_SEQUENCE_ERROR\\n\");\n      *ierr = -1;\n      return(0);\n      break;\n    case BZ_IO_ERROR:\n      printf(\"bzerror == BZ_SEQUENCE_ERROR\\n\");\n      *ierr = -1;\n      return(0);\n      break;\n    case BZ_UNEXPECTED_EOF:\n      printf(\"bzerror == BZ_UNEXPECTED_EOF\\n\");\n      *ierr = -1;\n      return(0);\n      break;\n    case BZ_DATA_ERROR:\n      printf(\"bzerror == BZ_DATA_ERROR\\n\");\n      *ierr = -1;\n      return(0);\n      break;\n    case BZ_DATA_ERROR_MAGIC:\n      printf(\"bzerror == BZ_DATA_ERROR_MAGIC\\n\");\n      *ierr = -1;\n      return(0);\n      break;\n    case BZ_MEM_ERROR:\n      printf(\"bzerror == BZ_MEM_ERROR\\n\");\n      *ierr = -1;\n      return(0);\n      break;\n    default:\n      printf(\"other\\n\");\n      *ierr = -1;\n      return(0);\n      exit ( -1 );\n    }\n  }\n\n  /* Copy bytes from the buffer to the string, until we hit a newline\n     or we've exhausted the buffer */\n/*   printf(\"ibuf, nbuf = %i %i\\n\", ibuf, nbuf); */\n  while ((ibuf < nbuf) && ( buffer[ibuf] != '\\n')) {\n    string[istring] = buffer[ibuf];\n    istring++;\n    ibuf++;\n    if (ibuf == nbuf) {\n      ibuf = 0;\n      goto READMORE;\n    }\n  }\n  if (buffer[ibuf] == '\\n') ibuf++;\n  if (ibuf == nbuf) ibuf = 0;\n\n  istring--;\n\n  if (istring < 0) {\n    printf(\"Problem!\\n\");\n    exit (1);\n  }\n  string[istring] = ' ';\n\n/*   printf(\"string = '%s'\\n\", string); */\n  *ierr = 0;\n  return(0);\n\n}\n\n#if defined (__SLOW__)\n\nint bz_getline_(int *iunit, char *string, int *length, int *ierr){\n  /* \n     Error flags returned:  \n            -1:  ?\n  */\n\n  int nbuf;\n  int bzerror;\n  int istring;\n\n  char h;\n\n  for (istring=0; istring<*length; istring++) {\n    string[istring] = ' ';\n  }\n\n  /* Read one character at a time */\n  /* Probably very inefficient, but what the heck.  It works. */\n  istring = 0;\n  h = NULL;\n  while ( h != '\\n') {\n    nbuf = BZ2_bzRead(&bzerror, b[*iunit], &h, 1);\n    if (bzerror == BZ_OK) {\n      string[istring] = h;\n      istring++;\n    }\n    else {\n/*       printf(\"bzerror = %i\\n\", bzerror); */\n/*       printf(\"h = %i : '%c' \\n\", h, h); */\n      if (bzerror == -1) {\n\t*ierr = -1;\n\treturn(0);\n      }\n    }\n  }\n  istring--;\n  if (istring < 0) {\n    printf(\"Problem!\\n\");\n    exit (1);\n  }\n  string[istring] = ' ';\n\n  *ierr = bzerror;\n  return(0);\n\n}\n#endif\n\nint bz_close_(int *iunit, int *ierr, int *ivrb) {\n  int bzerror;\n\n  if (*ivrb > 0) printf(\"Attempting to BZCLOSE bzunit %i\\n\", *iunit);\n\n  if (b[*iunit]) {\n    BZ2_bzReadClose (ierr, b[*iunit]);\n  }\n  if (f[*iunit]) {\n    fclose(f[*iunit]);\n  }\n  b[*iunit] = NULL;\n  f[*iunit] = NULL;\n  ibuf = 0;\n  if (*ivrb > 0) printf(\"BZCLOSE bzunit %i\\n\", *iunit);\n  return(0);\n}\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/rdmet.F",
    "content": "subroutine rdmet(okmeso_met, nstation, station, idate, pcp, Tair_out, TS05_out, TS10_out, TS30_out)\n  implicit none\n  character(len=*),                      intent(in)  :: okmeso_met\n  integer,                               intent(in)  :: nstation\n  character(len=4), dimension(nstation), intent(in)  :: station\n  character(len=*),                      intent(in)  :: idate\n  real,             dimension(nstation), intent(out) :: pcp\n  real,             dimension(nstation), intent(out) :: Tair_out\n  real,             dimension(nstation), intent(out) :: TS05_out\n  real,             dimension(nstation), intent(out) :: TS10_out\n  real,             dimension(nstation), intent(out) :: TS30_out\n\n  integer, save :: iunit\n  integer :: ierr, i\n  character(len=256) :: flnm\n  character(len=256) :: string\n\n  character(len=4) :: stid\n  character(len=16) :: hdate\n\n  real :: relh, Tair, wspd, wvec, wdir, wdsd, wssd, wmax, rain, pres, &\n       srad, ta9m, ws2m, ts10, tb10, ts05, tb05, ts30, batv\n\n  integer :: qrelh, qtair, qwspd, qwvec, qwdir, qwdsd, qwssd, qwmax, qrain, &\n       qpres, qsrad, qta9m, qws2m, qts10, qtb10, qts05, qtb05, qts30\n  integer :: iwdir\n\n  real :: U,V,Qv\n\n  character(len=256) :: fileopen = \"NULL\"\n\n  ! Default values to return\n  pcp = -99999.\n  Tair_out = -99999.\n  TS05_out = -99999.\n  TS10_out = -99999.\n  TS30_out = -99999.\n\n  write(flnm, '(A, \"/\", A8, \".mwq.bz2\")') okmeso_met, idate(1:8)\n\n  if (trim(fileopen) /= trim(flnm)) then\n     ! When we first open a file, we read past four header lines:\n\n     if (trim(fileopen) /= \"NULL\") call bz_close(iunit, ierr, 1)\n\n     call bz_open(trim(flnm)//char(0), iunit, ierr, 0)\n     if (ierr /= 0) stop \"bz_open returns non-zero\"\n     fileopen = trim(flnm)\n\n     call bz_getline(iunit, string, len(string), ierr)\n     if (ierr /= 0) stop \"bz_getline returns non-zero\"\n     print*, trim(string)\n\n     call bz_getline(iunit, string, len(string), ierr)\n     if (ierr /= 0) stop \"bz_getline returns non-zero\"\n     print*, trim(string)\n\n     call bz_getline(iunit, string, len(string), ierr)\n     if (ierr /= 0) stop \"bz_getline returns non-zero\"\n     print*, trim(string)\n\n     call bz_getline(iunit, string, len(string), ierr)\n     if (ierr /= 0) stop \"bz_getline returns non-zero\"\n     print*, trim(string)\n\n\n  else\n       call bz_restart(-1000)\n       call bz_advance_line()\n       call bz_advance_line()\n       call bz_advance_line()\n       call bz_advance_line()\n  endif\n\n  ! Scan forward through the file until we hit the time/date\n  ! in which we are interested.\n  FindDateLoop : do\n\n     call bz_getline(iunit, string, len(string), ierr)\n     if (ierr /= 0) then\n        stop \"bz_getline returns non-zero\"\n     endif\n\n     if ( string(8:19) == idate(1:10)//\"00\") then\n        exit FindDateLoop\n     endif\n     if (string(8:19) > idate) then\n        return\n     endif\n  enddo FindDateLoop\n\n  ! Now scan through the records, pulling out station data, until we hit the\n  ! end of file or end of this date/time.\n\n  ! The things we want to do stuff with are:\n  !    RELH:  Relative Humidity at 1.5 m      (%)\n  !    Tair:  Air Temperature at 2 m          (C)\n  !    WSPD:  Wind speed at 10 m              (m/s)\n  !    WDIR:  Wind direction at 10 m          (degrees)\n  !    PRES:  Pressure at 10 m                (hPa)\n  !    RAIN:  Rainfall at 10 m,               (mm)\n  !           accumulation since 00Z\n  !    SRAD:  Solar Radiation at 10 m         (W/m2)\n  !    WS2M:  Wind speed at 2 m               (m/s)\n  !    TS05:  Soil Temperature at 5 cm        (C)\n  !    TS10:  Soil Temperature at 10 cm       (C)\n  !    TS30:  Soil Temperature at 30 cm       (C)\n  !    TB05:  Bare Soil Temperature at 5 cm   (C)\n  !    TB10:  Bare Soil Temperature at 10 cm  (C)\n\n\n  RDLOOP : do\n\n     if ( string(8:19) /= idate(1:10)//\"00\") exit RDLOOP\n\n     read(string(1:208), 101, iostat=ierr) stid, &\n          hdate(1:4), hdate(6:7), hdate(9:10), hdate(12:13), hdate(15:16), &\n          relh, qrelh, Tair, qtair, wspd, qwspd, wvec, qwvec, iwdir, qwdir, &\n          wdsd, qwdsd, wssd, qwssd, wmax, qwmax, rain, qrain, pres, qpres, &\n          srad, qsrad, ta9m, qta9m, ws2m, qws2m, ts10, qts10, tb10, qtb10, &\n          ts05, qts05, tb05, qtb05, ts30, qts30, batv\n\n     if (ierr /= 0) then\n        print*, 'string = \"'//string//'\"'\n        stop\n     endif\n\n     ! Match up the station name we just read with our station table.\n\n     StnLoop : do i = 1, nstation\n        if (stid == station(i)) then\n\n           ! Floating point wind direction\n           wdir = float(iwdir)\n\n           ! Convert temperatures to K\n           if (Tair > -100) Tair = Tair + 273.15\n           if (TS05 > -100) TS05 = TS05 + 273.15\n           if (TS10 > -100) TS10 = TS10 + 273.15\n           if (TS30 > -100) TS30 = TS30 + 273.15\n           if (TB05 > -100) TB05 = TB05 + 273.15\n           if (TB10 > -100) TB10 = TB10 + 273.15\n\n           ! Convert pressure to Pa\n\n           if (PRES > 0) PRES = PRES * 1.E2\n\n           ! Convert RELH to Qv:\n\n           call RHtoQV( RELH, Tair, PRES, Qv )\n\n           ! Convert WSPD and WDIR to U and V\n\n           call SDtoUV(WSPD, WDIR, U, V)\n\n           ! Don't allow negative Short-Wave radiation.\n\n           SRAD = max(SRAD,0.0)\n\n           pcp(i) = rain\n\n           Tair_out(i) = Tair\n           TS05_out(i) = TS05\n           TS10_out(i) = TS10\n           TS30_out(i) = TS30\n\n           exit StnLoop\n        endif\n\n        if (i == nstation) print*, \"station not matched:  \", stid\n     enddo StnLoop\n\n     ! Get another string for the next pass through the loop:\n     call bz_getline(iunit, string, len(string), ierr)\n     if (ierr /= 0) then\n        stop \"bz_getline returns non-zero\"\n     endif\n\n  enddo RDLOOP\n\n101 format(1x,A4,2x,A4,4A2,4(F7.1,I3),1(I6,I3),3(F7.1,I3),1(F8.2,I3),1(F9.2,I3),&\n       9(F7.1,I3),F7.1)\n\nend subroutine rdmet\n\nsubroutine RHtoQV( RH, T, P, Q )\n  implicit none\n  real, intent(in)  :: RH ! %\n  real, intent(in)  :: T  ! K\n  real, intent(in)  :: P  ! Pa\n  real, intent(out) :: Q  ! kg/kg\n\n  real, parameter :: E0    = 611.2    ! Pa\n  real, parameter :: SVP2  = 17.67\n  real, parameter :: SVP3  = 29.65\n  real, parameter :: T00   = 273.15\n  real, parameter :: EPS   = 0.622\n\n  real :: ES, QS\n\n  if ((T > 0) .and. ( P > 0) .and. ( RH > 0 )) then\n\n     ES=E0*EXP(SVP2*(T-T00)/(T-SVP3))\n     QS=EPS*ES/(P-ES)\n     Q = RH*1.E-2*QS\n  else\n     Q = -999.\n  endif\n\nend subroutine RHtoQV\n\nsubroutine SDtoUV(WSPD, WDIR, U, V)\n  implicit none\n  real, intent(inout)  :: WSPD, WDIR\n  real, intent(out) :: U, V\n\n  real, parameter :: pi = 3.14159265\n  real, parameter :: degrad = pi/180.\n\n  if ((wspd > -400) .and. (wdir > -400)) then\n     u = - wspd * sin(wdir*degrad)\n     v = - wspd * cos(wdir*degrad)\n  else\n     u = -999\n     v = -999\n  endif\n\nend subroutine SDtoUV\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/rdsom.F",
    "content": "module module_ver\n  implicit none\n  type mapinfo_type\n     integer :: ix\n     integer :: jx\n\n     character(len=40) :: projection\n     real    :: dx\n     real    :: dy\n     real    :: xlonc\n     real    :: reflat\n     real    :: reflon\n     real    :: refx\n     real    :: refy\n     real    :: truelat1\n     real    :: truelat2\n  end type mapinfo_type\n\n  type(mapinfo_type) :: map\n\nend module module_ver\n\nprogram ver\n  use kwm_date_utilities\n  use kwm_plot_utilities\n  use module_ver\n  implicit none\n\n  integer, parameter :: maxstn = 200\n  integer, parameter :: maxtime = 2500\n  integer :: nstation\n  character(len=4), dimension(maxstn) :: station\n  real, dimension(maxstn) :: stnlat, stnlon, stnx, stny\n  integer :: i, idt, indx\n\n!  character(len=10), parameter :: startdate = \"2002051300\"\n  character(len=10), parameter :: startdate = \"2002030100\"\n  character(len=10), parameter :: enddate   = \"2002063000\"\n  character(len=10) :: nowdate\n\n  real, dimension(4, maxstn, maxtime) :: wc, sm\n\n  character(len=256) :: wrfstatic ! wrfstatic filename\n\n  call getarg(1, wrfstatic)\n\n  print*, 'loc(station) = ', loc(station)\n\n\n  ! Read the wrfstatic file to get map information\n  call rdwrfstatic(wrfstatic)\n\n  ! Find the OK Mesonet stations.\n  call rdgeomeso(station, nstation, stnlat, stnlon, maxstn, 0)\n\n  ! Find x/y\n  do i = 1, nstation\n     call lltoxy_generic(stnlat(i), stnlon(i), stnx(i), stny(i), &\n          map%projection, 1.E-3*map%dx, map%reflat, map%reflon, map%refx, map%refy,&\n          map%xlonc, map%truelat1, map%truelat2)\n  enddo\n\n  ! Loop over time\n  call geth_newdate(nowdate, startdate, -1)\n  DATELOOP: do while ( nowdate < enddate)\n     call geth_newdate(nowdate, nowdate, 1)\n     call geth_idts(nowdate, startdate, idt)\n     indx = idt + 1\n     print*, 'nowdate = ', nowdate, indx\n\n     ! Get station data from the OK Mesonet files\n     do i = 1, nstation\n        call rdsom(station(i), nowdate//\"00\", wc(1:4,i,indx))\n     enddo\n\n     ! Get corresponding HRLDAS results from HRLDAS files\n     call rdhrldas(station, stnlat, stnlon, nstation, nowdate, sm(1:4,1:nstation,indx))\n\n  enddo DATELOOP\n\n  ! Make some plots\n  call kwm_init_ncargks(\"sm.cgm\")\n  do i = 1, nstation\n     call pltsm(station(i), wc(1:2,i,1:indx), sm(1:2,i,1:indx), 2, indx, startdate, &\n          stnlat(i), stnlon(i), stnx(i), stny(i))\n  enddo\n  call kwm_close_ncargks\n\nend program ver\n\nsubroutine pltsm(stn, wc, sm, nlev, ndim, startdate, stnlat, stnlon, stnx, stny)\n  use kwm_plot_utilities\n  use kwm_date_utilities\n  implicit none\n  character(len=*),           intent(in) :: stn\n  integer,                    intent(in) :: nlev\n  integer,                    intent(in) :: ndim\n  real, dimension(nlev,ndim), intent(in) :: wc\n  real, dimension(nlev,ndim), intent(in) :: sm\n  character(len=*),           intent(in) :: startdate\n  real,                       intent(in) :: stnlat\n  real,                       intent(in) :: stnlon\n  real,                       intent(in) :: stnx\n  real,                       intent(in) :: stny\n\n  integer :: i,n\n  character(len=256) :: text\n  character(len=10)  :: enddate\n\n  call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.14, 0.85, stn, 0.020, 0., -1.)\n  write(text,'(\"Lat/Lon = \", F6.2, 1x, F7.2)') stnlat, stnlon\n  call pchiqu(0.10, 0.81, trim(text), 0.012, 0., -1.)\n  write(text,'(\"X/Y = \", F6.2, 1x, F7.2)') stnx, stny\n  call pchiqu(0.10, 0.78, trim(text), 0.012, 0., -1.)\n  text = \"from \"//startdate(1:4)//\"-\"//startdate(5:6)//\"-\"//startdate(7:8)//\" \"//startdate(9:10)//\" Z\"\n  call pchiqu(0.44, 0.85, trim(text), 0.012, 0., -1.)\n\n  call geth_newdate(enddate(1:10), startdate(1:10), ndim-1)\n  text = \"to   \"//enddate(1:4)//\"-\"//enddate(5:6)//\"-\"//enddate(7:8)//\" \"//enddate(9:10)//\" Z\"\n  call pchiqu(0.44, 0.82, trim(text), 0.012, 0., -1.)\n\n  call gasetc(\"YLF\", '(F5.2)')\n  call gasetc(\"XLF\", '(I4)')\n\n  do n = 1, nlev\n\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 1., float(ndim), 0., 0.5, 1)\n     else if (n == 2) then\n        call set(.1, .9, .15, .4, 1., float(ndim), 0., 0.5, 1)\n     endif\n\n     call periml(0,0,5,1)\n\n     call gsplci(color_index(\"blue\"))\n     do i = 1, ndim\n        if (i == 1) then\n           call frstpt(float(i), wc(n,i))\n        else\n           call vector(float(i), wc(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n     call gsplci(color_index(\"red\"))\n     do i = 1, ndim\n        if (i == 1) then\n           call frstpt(float(i), sm(n,i))\n        else\n           call vector(float(i), sm(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n     call gsplci(color_index(\"black\"))\n  enddo\n  call frame()\nend subroutine pltsm\n\n\nsubroutine rdgeomeso(station, nstation, stnlat, stnlon, maxstn, iverbose)\n  implicit none\n  integer,                             intent(in)  :: maxstn\n  character(len=4), dimension(maxstn), intent(out) :: station\n  real, dimension(maxstn),             intent(out) :: stnlat, stnlon\n  integer,                             intent(out) :: nstation\n  integer,                             intent(in) :: iverbose\n\n  character(len=256) :: string\n  integer :: ierr\n\n  integer, parameter :: iunit = 10\n\n  station = \"    \"\n  stnlat = -999.0\n  stnlon = -999.0\n  nstation = 0\n\n  open(iunit, file=\"/scholar/kmanning/more_hrldas/OKMESO/geomeso.tbl\", &\n       status='old', form='formatted', action='read')\n\n  PRELOOP : do\n     read(iunit, '(A256)', iostat=ierr) string\n     if (ierr /= 0) stop \"PRELOOP\"\n     if (string(1:6) == \"[STOP]\") exit PRELOOP\n  enddo PRELOOP\n\n  RDLOOP : do\n     read(iunit, '(A256)', iostat=ierr) string\n     if (ierr /= 0) exit RDLOOP\n\n     nstation = nstation + 1\n     read(string(6:9), '(A4)', iostat=ierr) station(nstation)\n     if (ierr /= 0) stop \"RDGEOMESO:  problem extracting station name\"\n     read(string(64:81), '(F8.4,1x,F9.4)', iostat=ierr) stnlat(nstation), stnlon(nstation)\n     if (ierr /= 0) stop \"RDGEOMESO:  problem extracting lat/lon\"\n     if (iverbose > 0) print*, station(nstation), stnlat(nstation), stnlon(nstation)\n\n  enddo RDLOOP\n  close(iunit)\nend subroutine rdgeomeso\n\n\nsubroutine rdsom(stn, idate, wc)\n  implicit none\n  character(len=*), intent(in) :: stn, idate\n  real, dimension(4), intent(out) :: wc\n  integer :: ierr\n  character(len=256) :: string, flnm\n  character(len=12) :: rddate ! yyyymmddhhmm\n  character(len=4)  :: rdstn\n\n  integer :: i\n\n  real, dimension(4) :: st, tr, mp\n  integer, dimension(4) :: stq, trq, mpq, wcq\n  real :: tref\n  integer, parameter :: iunit = 10\n  wc = -99999.\n\n\n!  write(flnm, &\n!   '(\"/wig/kmanning/HRLDAS_WRFDRIVER/VERIFICATION/OKMeso_Soil/\",A8,\".som\")') &\n!   idate(1:8)\n\n  write(flnm, &\n       '(\"/wig/kmanning/HRLDAS_WRFDRIVER/VERIFICATION/OKMeso_SoilMoisture_SOM/\",A8,\".som\")') &\n   idate(1:8)\n\n  open(iunit, file=trim(flnm), status='old', form='formatted', action='read')\n\n  RDLOOP : do\n     read(iunit, '(A256)', iostat=ierr) string\n     if (ierr /= 0) exit RDLOOP\n     read(string(6:17), '(A12)', iostat=ierr) rddate\n     if (ierr /= 0) stop \"Problem extracting date\"\n     if (rddate == idate) then\n        read(string(1:4), '(A4)', iostat=ierr) rdstn\n        if (ierr /= 0) stop \"Problem extracting station name\"\n        if (rdstn == stn) then\n!KWM           print*, trim(string)\n           read(string(19:),*, iostat=ierr) ((st(i), stq(i), tr(i), trq(i), mp(i), mpq(i), wc(i), wcq(i)), i=1,4), &\n                tref\n           if (ierr /= 0) stop \"Problem extracting data\"\n!KWM           print*, 'st = ', st\n!KWM           print*, 'tr = ', tr\n!KWM           print*, 'mp = ', mp\n!KWM           print*, 'wc = ', wc\n!KWM           print*, 'tref = ', tref\n           exit RDLOOP\n        endif\n     endif\n  enddo RDLOOP\n\n  close(iunit)\n\nend subroutine rdsom\n\nsubroutine rdwrfstatic(wrfstatic)\n  use module_ver\n  implicit none\n  character(len=*), intent(in) :: wrfstatic\n\n#include <netcdf.inc>\n  integer :: ncid, iret, dimid\n  real, dimension(16) :: corner_lat, corner_lon\n\n  ! Open the NetCDF file, and get mapping information.\n  write(*,'(\"wrfsi_static_flnm: ''\", A, \"''\")') trim(wrfstatic)\n    iret = nf_open(wrfstatic, NF_WRITE, ncid)\n    if (iret /= 0) then\n       write(*,'(\"Problem opening wrfsi_static file: ''\", A, \"''\")') &\n            trim(wrfstatic)\n       stop\n    endif\n\n    iret = nf_inq_dimid(ncid, \"west_east\", dimid)\n    if (iret /= 0) then\n       stop \"nf_inq_dimid:  west_east\"\n    endif\n\n    iret = nf_inq_dimlen(ncid, dimid, map%ix)\n    if (iret /= 0) then\n       stop \"nf_inq_dimlen:  west_east\"\n    endif\n\n    iret = nf_inq_dimid(ncid, \"south_north\", dimid)\n    if (iret /= 0) then\n       stop \"nf_inq_dimid:  south_north\"\n    endif\n\n    iret = nf_inq_dimlen(ncid, dimid, map%jx)\n    if (iret /= 0) then\n       stop \"nf_inq_dimlen:  south_north\"\n    endif\n\n    iret = nf_inq_dimid(ncid, \"land_cat\", dimid)\n    if (iret /= 0) then\n       stop \"nf_inq_dimid:  land_cat\"\n    endif\n\n!KWM    iret = nf_inq_dimlen(ncid, dimid, land_cat)\n!KWM    if (iret /= 0) then\n!KWM       stop \"nf_inq_dimlen:  land_cat\"\n!KWM    endif\n!KWM\n!KWM    iret = nf_inq_dimid(ncid, \"soil_cat\", dimid)\n!KWM    if (iret /= 0) then\n!KWM       stop \"nf_inq_dimid:  soil_cat\"\n!KWM    endif\n!KWM\n!KWM    iret = nf_inq_dimlen(ncid, dimid, soil_cat)\n!KWM    if (iret /= 0) then\n!KWM       stop \"nf_inq_dimlen:  soil_cat\"\n!KWM    endif\n!KWM\n\n! Various map attributes\n\n    iret = nf_get_att_text(ncid, NF_GLOBAL, \"map_projection\", map%projection)\n    if (iret /= 0) then\n       stop \"nf_get_att_float:  projection\"\n    endif\n\n    if (map%projection(1:17) == \"LAMBERT CONFORMAL\") map%projection = \"LC\"\n\n    iret = nf_get_att_real(ncid, NF_GLOBAL, \"TRUELAT1\", map%truelat1)\n    if (iret /= 0) then\n       stop \"nf_get_att_float:  truelat1\"\n    endif\n\n    iret = nf_get_att_real(ncid, NF_GLOBAL, \"TRUELAT2\", map%truelat2)\n    if (iret /= 0) then\n       stop \"nf_get_att_float:  truelat2\"\n    endif\n\n    iret = nf_get_att_real(ncid, NF_GLOBAL, \"DX\", map%dx)\n    if (iret /= 0) then\n       stop \"nf_get_att_float:  dx\"\n    endif\n\n    iret = nf_get_att_real(ncid, NF_GLOBAL, \"DY\", map%dy)\n    if (iret /= 0) then\n       stop \"nf_get_att_float:  dy\"\n    endif\n\n    iret = nf_get_att_real(ncid, NF_GLOBAL, \"STAND_LON\", map%xlonc)\n    if (iret /= 0) then\n       stop \"nf_get_att_float:  xlonc\"\n    endif\n\n    iret = nf_get_att_real(ncid, NF_GLOBAL, \"corner_lats\", corner_lat)\n    if (iret /= 0) then\n       stop \"nf_get_att_float:  corner_lat\"\n    endif\n\n    iret = nf_get_att_real(ncid, NF_GLOBAL, \"corner_lons\", corner_lon)\n    if (iret /= 0) then\n       stop \"nf_get_att_float:  corner_lon\"\n    endif\n\n    map%reflat = corner_lat(1)\n    map%reflon = corner_lon(1)\n    map%refx = 1.0\n    map%refy = 1.0\n\n    iret = nf_close(ncid)\n\nend subroutine rdwrfstatic\n\nsubroutine rdhrldas(stn, stnlat, stnlon, nstation, idate, sm)\n  use module_ver\n  implicit none\n  integer,                               intent(in)  :: nstation\n  character(len=*), dimension(nstation), intent(in)  :: stn\n  real, dimension(nstation),             intent(in)  :: stnlat\n  real, dimension(nstation),             intent(in)  :: stnlon\n  character(len=*),                      intent(in)  :: idate\n  real, dimension(4,nstation),           intent(out) :: sm\n\n  character(len=256) :: flnm\n#include <netcdf.inc>\n  integer :: iret, ncid\n  integer :: dimid, varid, idim, jdim\n  real, allocatable, dimension(:,:) :: var\n  real :: x, y, i, j\n  integer :: ista, ilvl\n\n  sm = -99999.\n\n  write(flnm, &\n   '(\"/scholar2/kmanning/VERY_TEMPORARY_HRLDAS/Run_3.2/\",A10,\".LDASOUT_DOMAIN1\")') idate(1:10)\n\n\n  iret = nf_open(flnm, NF_WRITE, ncid)\n  if (iret /= 0) then\n     write(*,'(\"Problem opening flnm: ''\", A, \"''\")') &\n          trim(flnm)\n     stop\n  endif\n\n!KWM  iret = nf_inq_dimid(ncid, \"idim\", dimid)\n!KWM  if (iret /= 0) then\n!KWM     stop \"nf_inq_dimid:  idim\"\n!KWM  endif\n!KWM\n!KWM  iret = nf_inq_dimlen(ncid, dimid, idim)\n!KWM  if (iret /= 0) then\n!KWM     stop \"nf_inq_dimlen:  idim\"\n!KWM  endif\n!KWM\n!KWM  iret = nf_inq_dimid(ncid, \"jdim\", dimid)\n!KWM  if (iret /= 0) then\n!KWM     stop \"nf_inq_dimid:  jdim\"\n!KWM  endif\n!KWM\n!KWM  iret = nf_inq_dimlen(ncid, dimid, jdim)\n!KWM  if (iret /= 0) then\n!KWM     stop \"nf_inq_dimlen:  jdim\"\n!KWM  endif\n\n!KWM  print*, 'ix, jx = ', map%ix, map%jx\n!KWM  print*, 'map = ', map\n\n  ! Read a soil-moisture field\n\n  do ilvl = 1, 4\n\n     iret = nf_inq_varid(ncid, \"SOIL_M_\"//char(ilvl+ichar(\"0\")), varid)\n     if (iret /= 0) then\n        stop \"nf_inq_varid:  SOIL_M_\"\n     endif\n!KWM     print*, \"SOIL_M_\"//char(ilvl+ichar(\"0\")), ' varid = ', varid\n\n     allocate(var(map%ix, map%jx))\n\n     iret = nf_get_var_real(ncid, varid, var)\n     if (iret /= 0) then\n        stop \"nf_get_var_real: SOIL_M_1\"\n     endif\n\n     do ista = 1, nstation\n        call lltoxy_generic(stnlat(ista), stnlon(ista), x, y, &\n             map%projection, 1.E-3*map%dx, map%reflat, map%reflon, map%refx, map%refy,&\n             map%xlonc, map%truelat1, map%truelat2)\n\n!        print*, 'lat, lon, x, y = ', stnlat(ista), stnlon(ista), x, y\n        sm(ilvl, ista) = var(nint(x), nint(y))\n\n     enddo\n\n     deallocate(var)\n  enddo\n\nend subroutine rdhrldas\n"
  },
  {
    "path": "src/Land_models/Noah/VERIFICATION/OKMeso_statistics/rdsom_mem.F",
    "content": "module module_ver\n  implicit none\n\n  integer, parameter :: maxstn = 200\n  integer, parameter :: maxtime = 5000\n\n  type mapinfo_type\n     sequence\n     integer :: ix\n     integer :: jx\n\n     character(len=40) :: projection\n     real    :: dx\n     real    :: dy\n     real    :: xlonc\n     real    :: reflat\n     real    :: reflon\n     real    :: refx\n     real    :: refy\n     real    :: truelat1\n     real    :: truelat2\n  end type mapinfo_type\n\n  type(mapinfo_type) :: map\n\n  type memory_type\n     sequence\n     integer :: indx\n     integer :: nstation\n     character(len=4), dimension(maxstn) :: station\n     real, dimension(maxstn) :: stnlat\n     real, dimension(maxstn) :: stnlon\n     real, dimension(maxstn) :: stnx\n     real, dimension(maxstn) :: stny\n     real, dimension(4, maxstn, maxtime) :: wc\n     real, dimension(4, maxstn, maxtime) :: sm\n     real, dimension(4, maxstn, maxtime) :: st\n\n     real, dimension(maxstn, maxtime) :: okpcp\n     real, dimension(maxstn, maxtime) :: okTair\n     real, dimension(maxstn, maxtime) :: okTs05\n     real, dimension(maxstn, maxtime) :: okTs10\n     real, dimension(maxstn, maxtime) :: okTs30\n\n  end type memory_type\n\n  type(memory_type), target :: mem\n\nend module module_ver\n\nprogram ver\n  use kwm_date_utilities\n  use kwm_plot_utilities\n  use module_ver\n  use module_hd\n  implicit none\n\n  integer :: i, n, idt\n\n  character(len=10) :: startdate\n  character(len=10) :: enddate\n  character(len=10) :: nowdate\n\n  character(len=256) :: okmeso_soil_dir  ! Directory where OKMeso soil data reside\n  character(len=256) :: okmeso_met_dir   ! Directory where OKMeso meteorological data reside\n  character(len=256) :: ldasout_dir      ! Directory where the LDASOUT files reside\n\n  logical :: lexist\n\n  real :: hold, tmp\n  integer, pointer :: nstation, indx\n  real, pointer, dimension(:) :: stnlat, stnlon, stnx, stny\n  real, pointer, dimension(:,:) :: okpcp, okTair, okTs05, okTs10, okTs30, okts\n  real, pointer, dimension(:, :, :) :: wc, sm, st\n\n  integer, dimension(2,maxstn,maxtime) :: tflag, mflag\n  real, dimension(2, maxtime) :: wa, sa, smcount, stcount, sta, okta\n  real, dimension(2) :: avsmbias, avsmrmse, avwcmean, avsmmean\n  real, dimension(2) :: avstbias, avstrmse, avstamean, avoktmean\n\n  real, allocatable, dimension(:,:) :: diurnal_obs, diurnal_mdl\n\n  type(nf_structure) :: nfstruct_for_map\n  integer :: iret\n\n\n  nstation => mem%nstation\n  indx     => mem%indx\n  stnlat   => mem%stnlat\n  stnlon   => mem%stnlon\n  stnx     => mem%stnx\n  stny     => mem%stny\n  okpcp    => mem%okpcp\n  okTair   => mem%okTair\n  okTs05   => mem%okTs05\n  okTs10   => mem%okTs10\n  okTs30   => mem%okTs30\n  sm       => mem%sm\n  wc       => mem%wc\n  st       => mem%st\n\n  call read_namelist(okmeso_soil_dir, okmeso_met_dir, ldasout_dir, startdate, enddate)\n\n!KWM  inquire(file=\"rdsom.mem\", exist=lexist)\n!KWM\n!KWM  if (.not. lexist) then\n\n     call netcdf_open(trim(ldasout_dir)//\"/\"//startdate//\".LDASOUT_DOMAIN1\", nfstruct_for_map)\n     iret = nf90_close(nfstruct_for_map%ncid)\n\n     ! Find the OK Mesonet stations.\n     call rdgeomeso(trim(okmeso_soil_dir), mem%station, nstation, stnlat, stnlon, maxstn, 0)\n\n     ! Find x/y\n     do i = 1, nstation\n        call lltoxy_hd(stnlat(i), stnlon(i), stnx(i), stny(i), nfstruct_for_map)\n     enddo\n\n     ! Loop over time\n     call geth_newdate(nowdate, startdate, -1)\n     DATELOOP: do while ( nowdate < enddate)\n        call geth_newdate(nowdate, nowdate, 1)\n        call geth_idts(nowdate, startdate, idt)\n        indx = idt + 1\n        print*, 'nowdate = ', nowdate, indx\n\n        ! Get station data from the OK Mesonet files\n        do i = 1, nstation\n           call rdsom(trim(okmeso_soil_dir), mem%station(i), nowdate//\"00\", wc(1:4,i,indx))\n        enddo\n\n        call rdmet(trim(okmeso_met_dir), nstation, mem%station(1:nstation), nowdate//\"00\", &\n             okpcp(1:nstation,indx), okTair(1:nstation,indx), &\n             okTs05(1:nstation,indx), okTs10(1:nstation, indx), okTs30(1:nstation,indx))\n\n        ! Get corresponding HRLDAS results from HRLDAS files\n        call rdhrldas(trim(ldasout_dir), mem%station, stnlat, stnlon, nstation, nowdate, &\n             sm(1:4,1:nstation,indx), st(1:4, 1:nstation, indx))\n\n     enddo DATELOOP\n\n!KWM     open(12, file=\"rdsom.mem\", form='unformatted', action='write')\n!KWM     write(12) map\n!KWM     write(12) mem\n!KWM     close(12)\n!KWM\n!KWM  else\n!KWM\n!KWM     print*, 'indx = ', indx\n!KWM\n!KWM     open(12, file=\"rdsom.mem\", form='unformatted', action='read')\n!KWM     read(12) map\n!KWM     read(12) mem\n!KWM     close(12)\n!KWM\n!KWM     print*, 'indx = ', indx\n!KWM\n!KWM  endif\n\n  ! Convert accumulated rain from 00Z to hourly rain.\n  do i = 1, nstation\n     do n = 1, indx\n        if (n == 1) then\n           hold = 0.\n        endif\n        if (mod(n-1,24) == 1) then\n           hold = 0\n        endif\n        tmp = okpcp(i,n) - hold\n        hold = okpcp(i,n)\n        okpcp(i,n) = tmp\n     enddo\n  enddo\n\n\n  ! Make some plots\n  call kwm_init_ncargks(\"sm.cgm\")\n  do i = 1, nstation\n\n     do n = 1, 2\n        call qc_sm(wc(n,i,1:indx), mflag(n,i,1:indx), indx)\n        if (mem%station(i) == \"HASK\") mflag(n,i,1:indx) = 1\n        if (mem%station(i) == \"KING\") mflag(n,i,1:indx) = 1\n        if (mem%station(i) == \"SKIA\") mflag(n,i,1:indx) = 1\n\n        ! If 65% of the station is suspect, throw out everything\n        if (count(mflag(n,i,1:indx)==1) > 0.65*indx) then\n           mflag(n,i,1:indx) = 1\n        endif\n\n     enddo\n\n     call pltsm(mem%station(i), wc(1:2,i,1:indx), sm(1:2,i,1:indx), &\n          st(1:2,i,1:indx), 2, indx, startdate, &\n          stnlat(i), stnlon(i), stnx(i), stny(i), okpcp(i,1:indx), &\n          okTair(i,1:indx), okTs05(i,1:indx), okTs30(i,1:indx), &\n          mflag(:,i,1:indx))\n\n  enddo\n\n\n  ! Now construct some averages of all the stations\n\n  allocate(diurnal_obs(2,0:23))\n  allocate(diurnal_mdl(2,0:23))\n  diurnal_obs = 0.\n  diurnal_mdl = 0.\n\n  do n = 1, 2\n     allocate(okts(nstation,indx))\n     okts = -1.E32\n     select case (n)\n     case (1)\n        okts(1:nstation,1:indx) = okts05(1:nstation,1:indx) ! okts10?\n     case (2)\n        okts(1:nstation,1:indx) = okts30(1:nstation,1:indx)\n     end select\n\n     call construct_averages_temperature(startdate, enddate, nstation, indx, &\n          st(n,1:nstation,1:indx), &\n          okts(1:nstation,1:indx), &\n          tflag(n,1:nstation,1:indx), &\n          sta(n,1:indx), okta(n,1:indx), &\n          avstamean(n), avoktmean(n), avstbias(n), avstrmse(n), stcount(n,1:indx),&\n          diurnal_obs(n,0:23), diurnal_mdl(n,0:23))\n\n     deallocate(okts)\n\n     call construct_averages_moisture(nstation, indx, &\n          wc(n,1:nstation,1:indx), &\n          sm(n,1:nstation,1:indx), &\n          mflag(n,1:nstation,1:indx), &\n          wa(n,1:indx), sa(n,1:indx), &\n          avwcmean(n), avsmmean(n), avsmbias(n), avsmrmse(n), smcount(n,1:indx))\n  enddo\n\n  ! And plot the averages\n\n  call pltav_sm(2, indx, wa(1:2, 1:indx), sa(1:2, 1:indx), smcount(1:2,1:indx), &\n       startdate, &\n       avwcmean, avsmmean, avsmbias, avsmrmse)\n\n  call pltav_st(2, indx, sta(1:2, 1:indx), okta(1:2, 1:indx), stcount(1:2,1:indx), &\n       startdate, &\n       avstamean, avoktmean, avstbias, avstrmse)\n\n  call pltav_diurnal(diurnal_obs, diurnal_mdl)\n\n\n  call kwm_close_ncargks\n\nend program ver\n\nsubroutine pltav_diurnal(obs, mdl)\n  use kwm_plot_utilities\n  implicit none\n  real, dimension(2,0:23), intent(in) :: obs, mdl\n  integer :: n, i\n\n  call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.16, 0.85, \"Soil T Average Diurnal Cycle: \", 0.012, 0., -1.)\n  call pchiqu(0.16, 0.82, \"Soil T Average Diurnal Cycle: \", 0.012, 0., -1.)\n\n  call pchiqu(0.44, 0.85, \"OK Mesonet: \", 0.012, 0., -1.)\n  call pchiqu(0.44, 0.82, \"HRLDAS: \",     0.012, 0., -1.)\n  call gsplci(color_index(\"blue\"))\n  call line(.69, 0.85, .80, 0.85)\n  call gsplci(color_index(\"red\"))\n  call line(.69, 0.82, .80, 0.82)\n  call gsplci(color_index(\"black\"))\n\n  call gasetc(\"YLF\", '(F5.1)')\n  call gasetc(\"XLF\", '(I4)')\n\n\n  do n = 1, 2\n     call gsplci(color_index(\"black\"))\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 0., 24., 287., 294., 1)\n     else if (n == 2) then\n        call set(.1, .9, .15, .4, 0., 24., 288., 290., 1)\n     endif\n     call periml(24,0,5,1)\n\n     call gsplci(color_index(\"blue\"))\n     call frstpt(0., obs(n,0))\n     do i = 1, 24\n        call vector(float(i), obs(n,mod(i,24)))\n     enddo\n     call plotif(0., 0., 2)\n\n\n     call gsplci(color_index(\"red\"))\n     call frstpt(0., mdl(n,0))\n     do i = 1, 24\n        call vector(float(i), mdl(n,mod(i,24)))\n     enddo\n     call plotif(0., 0., 2)\n  enddo\n\nend subroutine pltav_diurnal\n\nsubroutine pltav_st(nlev, ndim, wa, sa, scount, startdate, wcmean, smmean, bias, rmse)\n  use kwm_plot_utilities\n  use kwm_date_utilities\n  implicit none\n  integer, intent(in) :: nlev, ndim\n  real, dimension(nlev,ndim), intent(in) :: wa, sa, scount\n  character(len=*), intent(in) :: startdate\n  real, dimension(2), intent(in) :: wcmean, smmean, bias, rmse\n\n  character(len=19) :: enddate\n  integer :: n, i\n  character(len=256) :: text\n  logical :: pd\n\n  real :: xl, xr, xb, xt, wl, wr, wb, wt\n  integer :: ml\n\n  call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.56, 0.85, \"Soil T: \", 0.012, 0., -1.)\n  call pchiqu(0.56, 0.82, \"Soil T: \", 0.012, 0., -1.)\n\n  call gflas1(4)\n  call pchiqu(0.14, 0.95, \"Averages\", 0.020, 0., -1.)\n  text = \"from \"//startdate(1:4)//\"-\"//startdate(5:6)//\"-\"//startdate(7:8)//\" \"//startdate(9:10)//\" Z\"\n  call pchiqu(0.44, 0.95, trim(text), 0.012, 0., -1.)\n\n  call geth_newdate(enddate(1:10), startdate(1:10), ndim-1)\n  text = \"to   \"//enddate(1:4)//\"-\"//enddate(5:6)//\"-\"//enddate(7:8)//\" \"//enddate(9:10)//\" Z\"\n  call pchiqu(0.44, 0.92, trim(text), 0.012, 0., -1.)\n\n  call pchiqu(0.44, 0.85, \"OK Mesonet: \", 0.012, 0., -1.)\n  call pchiqu(0.44, 0.82, \"HRLDAS: \",     0.012, 0., -1.)\n  call gsplci(color_index(\"blue\"))\n  call line(.69, 0.85, .80, 0.85)\n  call gsplci(color_index(\"red\"))\n  call line(.69, 0.82, .80, 0.82)\n  call gsplci(color_index(\"black\"))\n\n  call pchiqu(0.10, 0.77, \"Level 1\", 0.012, 0., -1.)\n  call pchiqu(0.10, 0.42, \"Level 2\", 0.012, 0., -1.)\n  call gflas2\n\n\n  call gasetc(\"YLF\", '(F5.2)')\n  call gasetc(\"XLF\", '(I4)')\n\n  do n = 1, nlev\n     call gsplci(color_index(\"black\"))\n\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 0., float(ndim-1)/24., 0., 125., 1)\n        call plotif(0., 0., 2)\n\n        call gasetc(\"YLF\", '(F4.1)')\n        call gaseti(\"YLO\", -835)\n        call periml((ndim-1)/24,0,5,1)\n        call gaseti(\"YLO\", 20)\n        call gasetc(\"YLF\", '(F5.2)')\n\n\n     endif\n\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 0., float(ndim-1)/24., 270., 310., 1)\n     else if (n == 2) then\n        call set(.1, .9, .15, .4, 0., float(ndim-1)/24., 270., 310., 1)\n     endif\n\n     call periml((ndim-1)/24,0,5,1)\n\n     call gsplci(color_index(\"blue\"))\n     pd = .FALSE.\n     do i = 1, ndim\n        if (.not. pd) then\n           call frstpt(float(i-1)/24., wa(n,i))\n           pd = .TRUE.\n        else\n           call vector(float(i-1)/24., wa(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n\n     call gsplci(color_index(\"red\"))\n     do i = 1, ndim\n        if (i == 1) then\n           call frstpt(float(i-1)/24., sa(n,i))\n        else\n           call vector(float(i-1)/24., sa(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n     call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n     call set   (xl, xr, xb, xt, wl, wr, 0., 125., ml)\n\n     call gsplci(color_index(\"grey75\"))\n     do i = 1, ndim\n        if (i == 1) then\n           call frstpt(float(i-1)/24., scount(n,i))\n        else\n           call vector(float(i-1)/24., scount(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n\n     call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n     if (n == 1) then\n        write(text, '(\"OKMESO mean Soil T:  \", F6.2)') wcmean(n)\n        call pchiqu(0.12, .725, trim(text), 0.013, 0., -1.)\n        write(text, '(\"HRLDAS mean Soil T:  \", F6.2)') smmean(n)\n        call pchiqu(0.55, .725, trim(text), 0.013, 0., -1.)\n        write(text, '(\"bias: \", F6.3, \"    RMSE: \", F5.3)') bias(n), rmse(n)\n        call pchiqu(0.55, .695, trim(text), 0.013, 0., -1.)\n     else if (n == 2) then\n        write(text, '(\"OKMESO mean Soil T:  \", F6.2)') wcmean(n)\n        call pchiqu(0.12, .375, trim(text), 0.013, 0., -1.)\n        write(text, '(\"HRLDAS mean Soil T:  \", F6.2)') smmean(n)\n        call pchiqu(0.55, .375, trim(text), 0.013, 0., -1.)\n        write(text, '(\"bias: \", F6.3, \"    RMSE: \", F5.3)') bias(n), rmse(n)\n        call pchiqu(0.55, .345, trim(text), 0.013, 0., -1.)\n     endif\n\n\n  enddo\n\n  call gflas3(4)\n\n  call frame()\n\nend subroutine pltav_st\n\nsubroutine pltav_sm(nlev, ndim, wa, sa, scount, startdate, wcmean, smmean, bias, rmse)\n  use kwm_plot_utilities\n  use kwm_date_utilities\n  implicit none\n  integer, intent(in) :: nlev, ndim\n  real, dimension(nlev,ndim), intent(in) :: wa, sa, scount\n  character(len=*), intent(in) :: startdate\n  real, dimension(2), intent(in) :: wcmean, smmean, bias, rmse\n\n  character(len=19) :: enddate\n  integer :: n, i\n  character(len=256) :: text\n  logical :: pd\n\n  real :: xl, xr, xb, xt, wl, wr, wb, wt\n  integer :: ml\n\n  call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.56, 0.85, \"Soil Moisture: \", 0.012, 0., -1.)\n  call pchiqu(0.56, 0.82, \"Soil Moisture: \", 0.012, 0., -1.)\n\n  call gflas1(4)\n  call pchiqu(0.14, 0.95, \"Averages\", 0.020, 0., -1.)\n  text = \"from \"//startdate(1:4)//\"-\"//startdate(5:6)//\"-\"//startdate(7:8)//\" \"//startdate(9:10)//\" Z\"\n  call pchiqu(0.44, 0.95, trim(text), 0.012, 0., -1.)\n\n  call geth_newdate(enddate(1:10), startdate(1:10), ndim-1)\n  text = \"to   \"//enddate(1:4)//\"-\"//enddate(5:6)//\"-\"//enddate(7:8)//\" \"//enddate(9:10)//\" Z\"\n  call pchiqu(0.44, 0.92, trim(text), 0.012, 0., -1.)\n\n  call pchiqu(0.44, 0.85, \"OK Mesonet: \", 0.012, 0., -1.)\n  call pchiqu(0.44, 0.82, \"HRLDAS: \",     0.012, 0., -1.)\n  call gsplci(color_index(\"blue\"))\n  call line(.69, 0.85, .80, 0.85)\n  call gsplci(color_index(\"red\"))\n  call line(.69, 0.82, .80, 0.82)\n  call gsplci(color_index(\"black\"))\n\n  call pchiqu(0.10, 0.77, \"Level 1\", 0.012, 0., -1.)\n  call pchiqu(0.10, 0.42, \"Level 2\", 0.012, 0., -1.)\n  call gflas2\n\n\n  call gasetc(\"YLF\", '(F5.2)')\n  call gasetc(\"XLF\", '(I4)')\n\n  do n = 1, nlev\n     call gsplci(color_index(\"black\"))\n\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 0., float(ndim-1)/24., 0., 125., 1)\n        call plotif(0., 0., 2)\n\n        call gasetc(\"YLF\", '(F4.1)')\n        call gaseti(\"YLO\", -835)\n        call periml((ndim-1)/24,0,5,1)\n        call gaseti(\"YLO\", 20)\n        call gasetc(\"YLF\", '(F5.2)')\n\n\n     endif\n\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 0., float(ndim-1)/24., 0., 0.5, 1)\n     else if (n == 2) then\n        call set(.1, .9, .15, .4, 0., float(ndim-1)/24., 0., 0.5, 1)\n     endif\n\n     call periml((ndim-1)/24,0,5,1)\n\n     call gsplci(color_index(\"blue\"))\n     pd = .FALSE.\n     do i = 1, ndim\n        if (.not. pd) then\n           call frstpt(float(i-1)/24., wa(n,i))\n           pd = .TRUE.\n        else\n           call vector(float(i-1)/24., wa(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n\n     call gsplci(color_index(\"red\"))\n     do i = 1, ndim\n        if (i == 1) then\n           call frstpt(float(i-1)/24., sa(n,i))\n        else\n           call vector(float(i-1)/24., sa(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n     call getset(xl, xr, xb, xt, wl, wr, wb, wt, ml)\n     call set   (xl, xr, xb, xt, wl, wr, 0., 125., ml)\n\n     call gsplci(color_index(\"grey75\"))\n     do i = 1, ndim\n        if (i == 1) then\n           call frstpt(float(i-1)/24., scount(n,i))\n        else\n           call vector(float(i-1)/24., scount(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n\n     call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n     if (n == 1) then\n        write(text, '(\"OKMESO mean Soil Moisture:  \", F5.3)') wcmean(n)\n        call pchiqu(0.12, .725, trim(text), 0.013, 0., -1.)\n        write(text, '(\"HRLDAS mean Soil Moisture:  \", F5.3)') smmean(n)\n        call pchiqu(0.55, .725, trim(text), 0.013, 0., -1.)\n        write(text, '(\"bias: \", F6.3, \"    RMSE: \", F5.3)') bias(n), rmse(n)\n        call pchiqu(0.55, .695, trim(text), 0.013, 0., -1.)\n     else if (n == 2) then\n        write(text, '(\"OKMESO mean Soil Moisture:  \", F5.3)') wcmean(n)\n        call pchiqu(0.12, .375, trim(text), 0.013, 0., -1.)\n        write(text, '(\"HRLDAS mean Soil Moisture:  \", F5.3)') smmean(n)\n        call pchiqu(0.55, .375, trim(text), 0.013, 0., -1.)\n        write(text, '(\"bias: \", F6.3, \"    RMSE: \", F5.3)') bias(n), rmse(n)\n        call pchiqu(0.55, .345, trim(text), 0.013, 0., -1.)\n     endif\n\n\n  enddo\n\n  call gflas3(4)\n\n  call frame()\n\nend subroutine pltav_sm\n\nsubroutine construct_averages_moisture(nstation, indx, obs, mdl, flag, wa, sa, &\n     obsmean, mdlmean, bias, rmse, scount)\n  implicit none\n  integer, intent(in) :: nstation, indx\n  real,    dimension(nstation,indx), intent(in)  :: obs, mdl\n  integer, dimension(nstation,indx), intent(in)  :: flag\n  real,    dimension(indx),          intent(out) :: wa, sa\n  real,                              intent(out) :: bias, rmse, obsmean, mdlmean\n  real,    dimension(indx),          intent(out) :: scount\n\n  integer :: n, i, count, bcount\n\n  bcount = 0\n  rmse = 0.0\n  bias = 0.0\n  obsmean = 0.0\n  mdlmean = 0.0\n\n  do i = 1, indx\n     wa(i) = 0\n     sa(i) = 0\n     count = 0\n     do n = 1, nstation\n        if ( (flag(n,i)==0) .and. (mdl(n,i)>0) ) then\n           wa(i) = wa(i) + obs(n,i)\n           sa(i) = sa(i) + mdl(n,i)\n           count = count + 1\n           bias = bias + (mdl(n,i)-obs(n,i))\n           rmse = rmse + (mdl(n,i)-obs(n,i))**2\n           obsmean = obsmean + obs(n,i)\n           mdlmean = mdlmean + mdl(n,i)\n           bcount = bcount + 1\n        endif\n     enddo\n\n     if (count > 0) then\n        wa(i) = wa(i) / real(count)\n        sa(i) = sa(i) / real(count)\n     else\n        wa(i) = 0.\n        sa(i) = 0.\n     endif\n     scount(i) = count\n\n  enddo\n\n  bias = bias / real(bcount)\n  rmse = sqrt(rmse/real(bcount))\n  obsmean = obsmean / real(bcount)\n  mdlmean = mdlmean / real(bcount)\n\n\nend subroutine construct_averages_moisture\n\nsubroutine construct_averages_temperature(startdate, enddate, nstation, indx, obs, mdl, flag, wa, sa, &\n     obsmean, mdlmean, bias, rmse, scount, diurnal_obs, diurnal_mdl)\n  use kwm_date_utilities\n  implicit none\n  character(len=*), intent(in) :: startdate, enddate\n  integer, intent(in) :: nstation, indx\n  real,    dimension(nstation,indx), intent(in)  :: obs, mdl\n  integer, dimension(nstation,indx), intent(in)  :: flag\n  real,    dimension(indx),          intent(out) :: wa, sa\n  real,                              intent(out) :: bias, rmse, obsmean, mdlmean\n  real,    dimension(indx),          intent(out) :: scount\n  real,    dimension(0:23),          intent(out) :: diurnal_obs, diurnal_mdl\n\n  integer, dimension(0:23) :: ocount, mcount\n  integer :: n, i, count, bcount, ihr\n  character(len=10) :: nowdate\n\n  bcount = 0\n  rmse = 0.0\n  bias = 0.0\n  obsmean = 0.0\n  mdlmean = 0.0\n\n  do i = 1, indx\n     wa(i) = 0\n     sa(i) = 0\n     count = 0\n     do n = 1, nstation\n!        if ( (flag(n,i)==0) .and. (mdl(n,i)>0) ) then\n        if ( (obs(n,i)>0) .and. (mdl(n,i)>0) ) then\n           wa(i) = wa(i) + obs(n,i)\n           sa(i) = sa(i) + mdl(n,i)\n           count = count + 1\n           bias = bias + (mdl(n,i)-obs(n,i))\n           rmse = rmse + (mdl(n,i)-obs(n,i))**2\n           obsmean = obsmean + obs(n,i)\n           mdlmean = mdlmean + mdl(n,i)\n           bcount = bcount + 1\n        endif\n     enddo\n\n     if (count > 0) then\n        wa(i) = wa(i) / real(count)\n        sa(i) = sa(i) / real(count)\n     else\n        wa(i) = 0.\n        sa(i) = 0.\n     endif\n     scount(i) = count\n\n  enddo\n\n  bias = bias / real(bcount)\n  rmse = sqrt(rmse/real(bcount))\n  obsmean = obsmean / real(bcount)\n  mdlmean = mdlmean / real(bcount)\n\n  ! And construct an average diurnal cycle\n  diurnal_obs(0:23) = 0.0\n  diurnal_mdl(0:23) = 0.0\n  ocount(0:23) = 0\n  mcount(0:23) = 0\n  print*, 'startdate = \"', startdate, '\"'\n  do i = 1, indx\n     call geth_newdate(nowdate, startdate(1:10), (i-1))\n     read(nowdate(9:10), *) ihr\n     do n = 1, nstation\n        if (obs(n,i) > 0) then\n           diurnal_obs(ihr) = diurnal_obs(ihr) + obs(n,i)\n           ocount(ihr) = ocount(ihr) + 1\n        endif\n        if (mdl(n,i) > 0) then\n           diurnal_mdl(ihr) = diurnal_mdl(ihr) + mdl(n,i)\n           mcount(ihr) = mcount(ihr) + 1\n        endif\n     enddo\n  enddo\n  diurnal_obs(0:23) = diurnal_obs(0:23) / float(ocount(0:23))\n  diurnal_mdl(0:23) = diurnal_mdl(0:23) / float(mcount(0:23))\n\n  print*, 'diurnal_obs = ', diurnal_obs\n  print*, 'diurnal_mdl = ', diurnal_mdl\n\n\nend subroutine construct_averages_temperature\n\nsubroutine pltsm(stn, wc, sm, st, nlev, ndim, startdate, stnlat, stnlon, stnx, stny, &\n     okpcp, okTair, okTs05, okTs30, flag)\n  use kwm_plot_utilities\n  use kwm_date_utilities\n  implicit none\n  character(len=*),           intent(in) :: stn\n  integer,                    intent(in) :: nlev\n  integer,                    intent(in) :: ndim\n  real, dimension(nlev,ndim), intent(in) :: wc           ! Observations\n  real, dimension(nlev,ndim), intent(in) :: sm           ! HRLDAS\n  real, dimension(nlev,ndim), intent(in) :: st\n  character(len=*),           intent(in) :: startdate\n  real,                       intent(in) :: stnlat\n  real,                       intent(in) :: stnlon\n  real,                       intent(in) :: stnx\n  real,                       intent(in) :: stny\n  real, dimension(ndim),      intent(in) :: okpcp\n  real, dimension(ndim),      intent(in) :: okTair\n  real, dimension(ndim),      intent(in) :: okTs05\n  real, dimension(ndim),      intent(in) :: okTs30\n  integer, dimension(2,ndim),   intent(in) :: flag\n\n  integer :: i,n\n  character(len=256) :: text\n  character(len=10)  :: enddate\n  logical :: pd\n\n  real :: wcmean, smmean\n  integer :: wccount, smcount\n\n  integer :: smbcount\n  real    :: smbias\n  real    :: smrmse\n\n\n  call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.56, 0.85, \"Soil Moisture: \", 0.012, 0., -1.)\n  call pchiqu(0.56, 0.82, \"Soil Moisture: \", 0.012, 0., -1.)\n  call pchiqu(0.44, 0.79, \"OK Mesonet hourly precip: \", 0.012, 0., -1.)\n  call gsplci(color_index(\"green3\"))\n  call line(.69, 0.79, .80, 0.79)\n  call gsplci(color_index(\"black\"))\n\n  call gflas1(2)\n  call pchiqu(0.14, 0.95, stn, 0.020, 0., -1.)\n  write(text,'(\"Lat/Lon = \", F6.2, 1x, F7.2)') stnlat, stnlon\n  call pchiqu(0.10, 0.91, trim(text), 0.012, 0., -1.)\n  write(text,'(\"X/Y = \", F6.2, 1x, F7.2)') stnx, stny\n  call pchiqu(0.10, 0.88, trim(text), 0.012, 0., -1.)\n  text = \"from \"//startdate(1:4)//\"-\"//startdate(5:6)//\"-\"//startdate(7:8)//\" \"//startdate(9:10)//\" Z\"\n  call pchiqu(0.44, 0.95, trim(text), 0.012, 0., -1.)\n\n  call geth_newdate(enddate(1:10), startdate(1:10), ndim-1)\n  text = \"to   \"//enddate(1:4)//\"-\"//enddate(5:6)//\"-\"//enddate(7:8)//\" \"//enddate(9:10)//\" Z\"\n  call pchiqu(0.44, 0.92, trim(text), 0.012, 0., -1.)\n\n  call pchiqu(0.44, 0.85, \"OK Mesonet: \", 0.012, 0., -1.)\n  call pchiqu(0.44, 0.82, \"HRLDAS: \",     0.012, 0., -1.)\n  call gsplci(color_index(\"blue\"))\n  call line(.69, 0.85, .80, 0.85)\n  call gsplci(color_index(\"red\"))\n  call line(.69, 0.82, .80, 0.82)\n  call gsplci(color_index(\"black\"))\n\n  call pchiqu(0.10, 0.77, \"Level 1\", 0.012, 0., -1.)\n  call pchiqu(0.10, 0.42, \"Level 2\", 0.012, 0., -1.)\n  call gflas2\n\n\n  call gasetc(\"YLF\", '(F5.2)')\n  call gasetc(\"XLF\", '(I4)')\n\n  do n = 1, nlev\n\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 0., float(ndim-1)/24., 0., 25., 1)\n        do i = 1, ndim\n           call fillbox((float(i)-1.0)/24., (float(i)+1.0)/24., 0., okpcp(i), color_index(\"green3\"))\n        enddo\n        call plotif(0., 0., 2)\n\n        call gasetc(\"YLF\", '(F4.1)')\n        call gaseti(\"YLO\", -835)\n        call periml((ndim-1)/24,0,5,1)\n        call gaseti(\"YLO\", 20)\n        call gasetc(\"YLF\", '(F5.2)')\n\n\n     endif\n\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 0., float(ndim-1)/24., 0., 0.5, 1)\n     else if (n == 2) then\n        call set(.1, .9, .15, .4, 0., float(ndim-1)/24., 0., 0.5, 1)\n     endif\n\n     call periml((ndim-1)/24,0,5,1)\n\n     if (flag(n,1) == 1) then\n        call gsplci(color_index(\"gray90\"))\n     else\n        call gsplci(color_index(\"blue\"))\n     endif\n\n     pd = .FALSE.\n     wcmean = 0.\n     wccount = 0\n     do i = 1, ndim\n        if (.not. pd) then\n           call frstpt(float(i-1)/24., wc(n,i))\n           if (flag(n,i) == 0) then\n              wcmean = wcmean + wc(n,i)\n              wccount = wccount + 1\n              if (stn == \"ANTL\") print*, 'wcmean, wc = ', wcmean, wc(n,i)\n           endif\n           pd = .TRUE.\n        else\n           call vector(float(i-1)/24., wc(n,i))\n           if (flag(n,i) == 0) then\n              wcmean = wcmean + wc(n,i)\n              wccount = wccount + 1\n              if (stn == \"ANTL\") print*, 'wcmean, wc = ', wcmean, wc(n,i)\n           endif\n        endif\n\n        if (i==ndim)then\n           call plotif(0., 0., 2)\n           pd = .FALSE.\n        else if (flag(n,i) /= flag(n,i+1)) then\n           call plotif(0., 0., 2)\n           pd = .FALSE.\n           if (flag(n,i+1) == 0) then\n              call gsplci(color_index(\"blue\"))\n           else\n              call gsplci(color_index(\"gray90\"))\n           endif\n\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n     call gsplci(color_index(\"red\"))\n     smmean = 0.\n     smcount = 0\n     do i = 1, ndim\n        if (i == 1) then\n           call frstpt(float(i-1)/24., sm(n,i))\n           smmean = smmean + sm(n,i)\n           smcount = smcount + 1\n        else\n           call vector(float(i-1)/24., sm(n,i))\n           smmean = smmean + sm(n,i)\n           smcount = smcount + 1\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n     smbcount = 0\n     smbias = 0.0\n     smrmse = 0.0\n     do i = 1, ndim\n        if (flag(n,i) == 0) then ! ((sm(n,i)>0).and.(wc(n,i)>0)) then\n           smbias = smbias + (sm(n,i)-wc(n,i))\n           smrmse = smrmse + ((sm(n,i)-wc(n,i))**2)\n           smbcount = smbcount + 1\n        endif\n     enddo\n     if (smbcount > 0) then\n        smbias = smbias / float(smbcount)\n        smrmse = sqrt(smrmse / float(smbcount))\n     endif\n\n     call gsplci(color_index(\"black\"))\n\n     if (smcount > 0) then\n        smmean = smmean / float(smcount)\n     endif\n     wcmean = wcmean / float(wccount)\n\n     if (smbcount > 0) then\n        if (n == 1) then\n           write(*,'(A4, 3(3x,F6.3))', advance=\"no\") stn, smmean, smbias, smrmse\n        else\n           write(*,'(\"   \", 3(3x,F6.3))', advance=\"no\") smmean, smbias, smrmse\n        endif\n     endif\n     if (n==2)  write(*,*)\n\n     call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n     if (n == 1) then\n        write(text, '(\"HRLDAS mean Soil Moisture:  \", F5.3)') smmean\n        call pchiqu(0.55, .725, trim(text), 0.013, 0., -1.)\n        write(text, '(\"bias: \", F6.3, \"    RMSE: \", F5.3)') smbias, smrmse\n        call pchiqu(0.55, .695, trim(text), 0.013, 0., -1.)\n     else if (n == 2) then\n        write(text, '(\"HRLDAS mean Soil Moisture:  \", F5.3)') smmean\n        call pchiqu(0.55, .375, trim(text), 0.013, 0., -1.)\n        write(text, '(\"bias: \", F6.3, \"    RMSE: \", F5.3)') smbias, smrmse\n        call pchiqu(0.55, .345, trim(text), 0.013, 0., -1.)\n     endif\n\n  enddo\n\n\n  call gflas3(2)\n\n  call frame()\n\n  ! Now plot up temperature information\n  call gasetc(\"YLF\", '(F5.1)')\n\n  call set(0., 1., 0., 1., 0., 1., 0., 1., 1)\n  call pchiqu(0.56, 0.85, \"Soil T: \", 0.012, 0., -1.)\n  call pchiqu(0.56, 0.82, \"Soil T: \", 0.012, 0., -1.)\n\n\n\n\n  do n = 1, nlev\n\n     if (n == 1) then\n        call set(.1, .9, .5, .75, 0., float(ndim-1)/24., 275., 305., 1)\n     else if (n == 2) then\n        call set(.1, .9, .15, .4, 0., float(ndim-1)/24., 275., 305., 1)\n     endif\n\n     call periml((ndim-1)/24,0,5,1)\n\n  call gflas3(2)\n\n\n     call gsplci(color_index(\"blue\"))\n     pd = .FALSE.\n     if (n == 1) then\n        do i = 1, ndim\n           if (.not. pd) then\n              if (okTs05(i) >= 0) then\n                 call frstpt(float(i-1)/24., okTs05(i))\n                 pd = .TRUE.\n              endif\n           else\n              if (okTs05(i) < 10) then\n                 call plotif(0., 0., 2)\n                 pd = .FALSE.\n              else\n                 call vector(float(i-1)/24., okTs05(i))\n              endif\n           endif\n        enddo\n     else if (n == 2) then\n        do i = 1, ndim\n           if (.not. pd) then\n              if (okTs30(i) >= 0) then\n                 call frstpt(float(i-1)/24., okTs30(i))\n                 pd = .TRUE.\n              endif\n           else\n              if (okTs30(i) < 10) then\n                 call plotif(0., 0., 2)\n                 pd = .FALSE.\n              else\n                 call vector(float(i-1)/24., okTs30(i))\n              endif\n           endif\n        enddo\n     endif\n!KWM        if (i == 1) then\n!KWM           if (n == 1) then\n!KWM              call frstpt(float(i-1)/24., okTs05(i))\n!KWM           else\n!KWM              call frstpt(float(i-1)/24., okTs30(i))\n!KWM           endif\n!KWM        else\n!KWM           if (n == 1) then\n!KWM              call vector(float(i-1)/24., okTs05(i))\n!KWM           else\n!KWM              call vector(float(i-1)/24., okTs30(i))\n!KWM           endif\n!KWM        endif\n!KWM     enddo\n     call plotif(0., 0., 2)\n\n     call gsplci(color_index(\"red\"))\n     do i = 1, ndim\n        if (i == 1) then\n           call frstpt(float(i-1)/24., st(n,i))\n        else\n          call vector(float(i-1)/24., st(n,i))\n        endif\n     enddo\n     call plotif(0., 0., 2)\n\n     if (n == 1) then\n\n!KWM        call gsplci(color_index(\"magenta\"))\n!KWM        call set(.1, .9, .5, .75, 0., float(ndim-1)/24., 270., 310., 1)\n!KWM        do i = 1, ndim\n!KWM           if (i == 1) then\n!KWM              call frstpt(float(i-1)/24., okTair(i))\n!KWM           else\n!KWM              call vector(float(i-1)/24., okTair(i))\n!KWM           endif\n!KWM        enddo\n!KWM        call plotif(0., 0., 2)\n\n     endif\n\n     call gsplci(color_index(\"black\"))\n  enddo\n\n\n\n  call frame()\nend subroutine pltsm\n\n\nsubroutine rdgeomeso(okmeso_soil_dir, station, nstation, stnlat, stnlon, maxstn, iverbose)\n  implicit none\n  character(len=*),                    intent(in)  :: okmeso_soil_dir\n  integer,                             intent(in)  :: maxstn\n  character(len=4), dimension(maxstn), intent(out) :: station\n  real, dimension(maxstn),             intent(out) :: stnlat, stnlon\n  integer,                             intent(out) :: nstation\n  integer,                             intent(in) :: iverbose\n\n  character(len=256) :: string\n  integer :: ierr\n\n  integer, parameter :: iunit = 10\n\n  station = \"    \"\n  stnlat = -999.0\n  stnlon = -999.0\n  nstation = 0\n\n  open(iunit, file=trim(okmeso_soil_dir)//\"/geomeso.tbl\", status='old', form='formatted', action='read')\n\n  PRELOOP : do\n     read(iunit, '(A256)', iostat=ierr) string\n     if (ierr /= 0) stop \"PRELOOP\"\n     if (string(1:6) == \"[STOP]\") exit PRELOOP\n  enddo PRELOOP\n\n  RDLOOP : do\n     read(iunit, '(A256)', iostat=ierr) string\n     if (ierr /= 0) exit RDLOOP\n\n     nstation = nstation + 1\n     read(string(6:9), '(A4)', iostat=ierr) station(nstation)\n     if (ierr /= 0) stop \"RDGEOMESO:  problem extracting station name\"\n     read(string(64:81), '(F8.4,1x,F9.4)', iostat=ierr) stnlat(nstation), stnlon(nstation)\n     if (ierr /= 0) stop \"RDGEOMESO:  problem extracting lat/lon\"\n     if (iverbose > 0) print*, station(nstation), stnlat(nstation), stnlon(nstation)\n\n  enddo RDLOOP\n  close(iunit)\nend subroutine rdgeomeso\n\n\nsubroutine rdsom(okmeso_soil_dir, stn, idate, wc)\n  implicit none\n  character(len=*),   intent(in)  :: okmeso_soil_dir\n  character(len=*),   intent(in)  :: stn, idate\n  real, dimension(4), intent(out) :: wc\n  integer :: ierr\n  character(len=256) :: string, flnm\n  character(len=12) :: rddate ! yyyymmddhhmm\n  character(len=4)  :: rdstn\n\n  integer :: i\n\n  real, dimension(4) :: st, tr, mp\n  integer, dimension(4) :: stq, trq, mpq, wcq\n  real :: tref\n  integer, parameter :: iunit = 10\n  wc = -99999.\n\n\n  write(flnm, '(A,\"/\",A8,\".som\")') okmeso_soil_dir, idate(1:8)\n\n  open(iunit, file=trim(flnm), status='old', form='formatted', action='read')\n\n  RDLOOP : do\n     read(iunit, '(A256)', iostat=ierr) string\n     if (ierr /= 0) exit RDLOOP\n     read(string(6:17), '(A12)', iostat=ierr) rddate\n     if (ierr /= 0) stop \"Problem extracting date\"\n     if (rddate == idate) then\n        read(string(1:4), '(A4)', iostat=ierr) rdstn\n        if (ierr /= 0) stop \"Problem extracting station name\"\n        if (rdstn == stn) then\n!KWM           print*, trim(string)\n           read(string(19:),*, iostat=ierr) ((st(i), stq(i), tr(i), trq(i), mp(i), mpq(i), wc(i), wcq(i)), i=1,4), &\n                tref\n           if (ierr /= 0) stop \"Problem extracting data\"\n!KWM           print*, 'st = ', st\n!KWM           print*, 'tr = ', tr\n!KWM           print*, 'mp = ', mp\n!KWM           print*, 'wc = ', wc\n!KWM           print*, 'tref = ', tref\n           exit RDLOOP\n        endif\n     endif\n  enddo RDLOOP\n\n  close(iunit)\n\nend subroutine rdsom\n\nsubroutine rdhrldas(ldasout_dir, stn, stnlat, stnlon, nstation, idate, sm, st)\n  use module_ver\n  use module_hd\n  implicit none\n  character(len=*),                      intent(in)  :: ldasout_dir\n  integer,                               intent(in)  :: nstation\n  character(len=*), dimension(nstation), intent(in)  :: stn\n  real, dimension(nstation),             intent(in)  :: stnlat\n  real, dimension(nstation),             intent(in)  :: stnlon\n  character(len=*),                      intent(in)  :: idate\n  real, dimension(4,nstation),           intent(out) :: sm\n  real, dimension(4,nstation),           intent(out) :: st\n\n  character(len=256) :: flnm, tmpflnm\n  real, pointer, dimension(:,:,:) :: smptr, stptr\n  real :: x, y, i, j\n  integer :: ista, ilvl\n  integer :: iret\n  type(nf_structure) :: nfstruct\n  logical :: bzipped, lexist\n\n  sm = -99999.\n  st = -99999.\n\n  bzipped = .FALSE.\n  write(flnm, '(A,\"/\",A10,\".LDASOUT_DOMAIN1\")') ldasout_dir, idate(1:10)\n\n  inquire(file=trim(flnm), exist=lexist)\n  if (lexist) then\n     tmpflnm = flnm\n  else\n     flnm = trim(flnm)//\".bz2\"\n     inquire(file=trim(flnm), exist=lexist)\n     if (lexist) then\n        print*, 'bunzipping.'\n        bzipped = .TRUE.\n        tmpflnm = \"/tmp/bbn3.bz2\"\n        call system(\"rm -f \"//trim(tmpflnm))\n        call system(\"bzip2 -cd \"//trim(flnm)//\" > \"//trim(tmpflnm))\n     endif\n  endif\n\n  call netcdf_open(trim(tmpflnm), nfstruct)\n\n  ! Read a soil-moisture field\n\n  call netcdf_get_field_3d(nfstruct, \"SOIL_M\", 1, smptr)\n  call netcdf_get_field_3d(nfstruct, \"SOIL_T\", 1, stptr)\n\n  do ilvl = 1, 4\n\n     do ista = 1, nstation\n        call lltoxy_hd(stnlat(ista), stnlon(ista), x, y, nfstruct)\n\n!KWM        print*, 'lat, lon, x, y = ', stnlat(ista), stnlon(ista), x, y\n!KWM        print*, 'shape(smptr) = ', shape(smptr)\n!KWM        print*, 'shape(sm) = ', shape(sm)\n        sm(ilvl, ista) = smptr(nint(x), nint(y), ilvl)\n        st(ilvl, ista) = stptr(nint(x), nint(y), ilvl)\n\n     enddo\n\n  enddo\n\n  iret = nf90_close(nfstruct%ncid)\n  deallocate(stptr, smptr)\n  nullify(stptr, smptr)\n  if (bzipped) then\n     call system(\"rm \"//trim(tmpflnm))\n  endif\n\nend subroutine rdhrldas\n\nsubroutine qc_sm(wc, flag, indx)\n  implicit none\n  integer,                  intent(in)  :: indx\n  real,    dimension(indx), intent(in)  :: wc\n  integer, dimension(indx), intent(out) :: flag\n\n  integer :: i, n, istart, ihold1, ihold2, npass\n  real :: val1, val2\n  integer :: samestart, samecount, samecount_maximum, sameend, jm, jp\n  real :: ymax, ymin\n  real, dimension(indx) :: tmp, tmp2\n\n  ! Flag 0 == OK\n  ! Flag 1 == Suspect\n  flag = 0\n\n!  samecount_maximum = 1440\n  samecount_maximum = 288\n\n  where (wc <= 0) flag = 1\n\n  ymax = maxval(wc, mask=(flag==0))\n  ymin = minval(wc, mask=(flag==0))\n!KWM  print*, stid//' ymin, ymax = ', ymin, ymax\n\n  samestart = 0\n  samecount = 0\n  sameend = 0\n  val1 = -999.\n  val2 = -999.\n\n  ! Find the first unflagged value.\n  jm = 1\n  do while (flag(jm) == 1)\n     jm = jm + 1\n     if (jm > indx) exit\n  enddo\n  if (jm <= indx) then\n     val2 = wc(jm)\n  endif\n\n  TIMELOOP : do\n\n     ! Find the next unflagged value.\n     jp = jm + 1\n     if (jp > indx) exit TIMELOOP\n     do while (flag(jp) == 1)\n        jp = jp + 1\n        if (jp > indx) exit TIMELOOP\n     enddo\n\n     if ((wc(jp) == val1) .or. (wc(jp) == val2)) then\n        samecount = samecount + 1\n        sameend = jp\n        if (samestart == 0) samestart = jm\n     else\n\n        if (samecount > samecount_maximum) then\n           flag(samestart:sameend) = 1\n        else if ( (max(val1,val2) > ymin + (ymax-ymin)*0.80) .and. &\n             ( samecount > samecount_maximum*0.15)) then\n           flag(samestart:sameend) = 1\n        else if ( (min(val1,val2) < ymin + (ymax-ymin)*0.20) .and. &\n             ( samecount > samecount_maximum*0.15)) then\n           flag(samestart:sameend) = 1\n        endif\n\n        val1 = val2\n        val2 = wc(jp)\n\n        samecount = 0\n        samestart = 0\n        sameend = 0\n     endif\n\n     ! Call what used to be the \"next\" unflagged value, the latest unflagged value:\n     jm = jp\n  enddo TIMELOOP\n\n  if (samecount > samecount_maximum) then\n     flag(samestart:sameend) = 1\n  endif\n\n\n#ifdef _BLAHH_\n     ! Flag regions with near-constant wc for a long time\n\n     istart = -1\n     do i = 2, indx\n\n        if ((wc(n,i) >= 0).and.(wc(n,i-1)>=0) ) then\n\n           if (abs(wc(n,i)-wc(n,i-1)) < 5.E-3) then\n           ! if there's no (little) change:\n\n              if (istart == -1) istart = i\n\n              if (i == indx) then\n\n                 if (istart > 0) then\n                    if ((i-istart) > 50) then\n                       flag(n,istart:i-1) = 1\n                    endif\n                    istart = -1\n                 endif\n\n              endif\n\n           else\n           ! if there has been some change:\n\n               if (istart > 0) then\n                 if ((i-istart) > 50) then\n                    flag(n,istart:i-1) = 1\n                 endif\n                 istart = -1\n              endif\n\n           endif\n        endif\n     enddo\n\n#endif\n\nend subroutine qc_sm\n\nsubroutine read_namelist(okmeso_soil_dir, okmeso_met_dir, ldasout_dir, startdate, enddate)\n  implicit none\n  character(len=256) :: okmeso_soil_dir\n  character(len=256) :: okmeso_met_dir\n  character(len=256), intent(out) :: ldasout_dir\n  character(len=10),  intent(out) :: startdate\n  character(len=10),  intent(out) :: enddate\n  integer ::  ierr\n  character(len=10)  :: statistics_startdate\n  character(len=10)  :: statistics_enddate\n\n  okmeso_soil_dir = \"UNSPECIFIED\"\n  okmeso_met_dir  = \"UNSPECIFIED\"\n  ldasout_dir     = \"UNSPECIFIED\"\n\n\n  namelist /okmeso/ okmeso_soil_dir, okmeso_met_dir, ldasout_dir, &\n       statistics_startdate, statistics_enddate\n\n  open(10, file=\"okmeso.namelist\", status='old', form='formatted', action='read', iostat=ierr)\n  if (ierr /= 0) then\n     write(*,'(\"Namelist file not found:  okmeso.namelist\")')\n     stop\n  endif\n  read(10, okmeso, iostat=ierr)\n  if (ierr /= 0) then\n     write(*,'(\"Problem reading namelist file:  okmeso.namelist\")')\n     stop\n  endif\n  close(10)\n\n  startdate = statistics_startdate\n  enddate   = statistics_enddate\n\nend subroutine read_namelist\n"
  },
  {
    "path": "src/Land_models/Noah/user_build_options.bak",
    "content": "\n# flag from HRLDAS\nCOMPILERF90 = $(COMPILER90)\nFREESOURCE      =\nMODFLAG               =       -I\nLIBJASPER       =       -ljpeg -L/scholar/kmanning/jasper/lib -ljasper\nINCJASPER       =       -I/scholar/kmanning/jasper/include\nNETCDFMOD       =       -I $(NETCDFINC)\nBZIP2           =       YES\nBZIP2_LIB       =       -lbz2\nBZIP2_INCLUDE   =       -I/usr/include\nCC              =       cc\n"
  },
  {
    "path": "src/Land_models/Noah/user_build_options.gfort",
    "content": "#=============================================================================================\n#  Options for Linux with Intel Fortran -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tifort\n# FREESOURCE\t=\t-free\n# F90FLAGS\t=\t-convert big_endian # -g -O0 -check all,noshape,nopointer,noarg_temp_created -mp -fpe0\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-ifort/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-ifort/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# BZIP2_LIB\t=\t-L/usr/lib -lbz2\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with g95 -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tg95\n# FREESOURCE\t=\t-ffree-form  -ffree-line-length-huge\n# F90FLAGS\t=\t-fendian=big -fno-second-underscore # -g -fbounds-check -O0\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-g95/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-g95/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with gfortran -- Serial\n#=============================================================================================\n\n  COMPILERF90\t=\tgfortran\n  FREESOURCE\t=\t-ffree-form  -ffree-line-length-none\n  F90FLAGS\t=\t-fconvert=big-endian # -g\n  MODFLAG\t\t=\t-I\n  LDFLAGS\t\t=\n  CPP\t\t=\tcpp\n  CPPFLAGS\t=\t-C -P -traditional -D_GFORTRAN_ # -D_HRLDAS_URBAN_\n  LIBS\t\t=\n  LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n  INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n  NETCDFMOD\t=\t-I /d1/weiyu/gfortran/netcdf-3.6.3/include\n  NETCDFLIB\t=\t-L /d1/weiyu/gfortran/netcdf-3.6.3/lib -lnetcdf\n  BZIP2\t\t=\tYES\n  BZIP2_LIB\t=\t-lbz2\n  BZIP2_INCLUDE\t=\t-I/usr/include\n  RM\t\t=\trm -f\n  CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with pgf90 -- Serial\n#=============================================================================================\n\n#COMPILERF90\t=\tmpif90\n#CPPFLAGS\t=\t-C -P -traditional -DMPP_LAND # -D_HRLDAS_URBAN_ \n#COMPILERF90\t=\tpgf90 \n#CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_ \n#FREESOURCE\t=\t-Mfree\n#F90FLAGS\t=\t-byteswapio # -g -C\n#MODFLAG\t\t=\t-I\n#LDFLAGS\t\t=\n#CPP\t\t=\tcpp\n#LIBS\t\t=\n#LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n#INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n#NETCDFMOD\t=\t-I$(HOME)/netcdf/include\n#NETCDFLIB\t=\t-L$(HOME)/netcdf/lib -lnetcdf\n#BZIP2\t\t=\tYES\n#BZIP2_LIB\t=\t-lbz2\n#BZIP2_INCLUDE\t=\t-I/usr/include\n#RM\t\t=\trm -f\n#CC\t\t=\tcc\n#\n##=============================================================================================\n#  Options for Linux with pgf90 -- Parallel\n#=============================================================================================\n\n# COMPILERF90\t=\tmpif90 -f90=pgf90\n# FREESOURCE\t=\t-Mfree\n# F90FLAGS\t=\t-byteswapio # -g -C\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_PARALLEL_ # -D_HRLDAS_URBAN_ \n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-4.1.1-parallel-pgf90/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-4.1.1-parallel-pgf90/lib -lnetcdf -lcurl\n# HDF5LIB\t\t=       -L/scholar/kmanning/HDF5/lib -lhdf5_hl -lhdf5 -lz\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for IBM -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\txlf\n# FREESOURCE\t=\t-qfree=f90\n# F90FLAGS\t=\t-g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# INCJASPER\t=\t-I/contrib/jasper/include\n# LIBJASPER\t=\t-ljpeg -L/contrib/jasper/lib -ljasper\n# NETCDFMOD\t=\t-I/usr/local/include\n# NETCDFLIB\t=\t-L/usr/local/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-L/contrib/bzip2/lib -lbz2\n# BZIP2_INCLUDE\t=\t-I/contrib/bzip2/include\n# RM\t\t=\trm -f\n# CC\t\t=\txlC\n\n#=============================================================================================\n#  Options for IBM -- Parallel\n#=============================================================================================\n\n# COMPILERF90\t=\tmpxlf90_r\n# FREESOURCE\t=\t-qfree=f90\n# F90FLAGS\t=\t-g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_PARALLEL_ # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# INCJASPER\t=\t-I/contrib/jasper/include\n# LIBJASPER\t=\t-ljpeg -L/contrib/jasper/lib -ljasper\n# NETCDFMOD\t=\t-I/contrib/netcdf-4.1.1-mpi/include\n# NETCDFLIB\t=\t-L/contrib/netcdf-4.1.1-mpi/lib -lnetcdf\n# HDF5LIB\t\t=\t-L/contrib/hdf5-1.8.4-patch1-mpi/lib -lhdf5_hl -lhdf5 -lz -lgpfs\n# BZIP2\t\t=\tNO\n# BZIP2_LIB\t=\n# BZIP2_INCLUDE\t=\n# RM\t\t=\trm -f\n# CC\t\t=\tcc_r\n"
  },
  {
    "path": "src/Land_models/Noah/user_build_options.gfortran",
    "content": "#=============================================================================================\n#  Options for Linux with Intel Fortran -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tifort\n# FREESOURCE\t=\t-free\n# F90FLAGS\t=\t-convert big_endian # -g -O0 -check all,noshape,nopointer,noarg_temp_created -mp -fpe0\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-ifort/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-ifort/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# BZIP2_LIB\t=\t-L/usr/lib -lbz2\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with g95 -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tg95\n# FREESOURCE\t=\t-ffree-form  -ffree-line-length-huge\n# F90FLAGS\t=\t-fendian=big -fno-second-underscore # -g -fbounds-check -O0\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-g95/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-g95/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with gfortran -- Serial\n#=============================================================================================\n\n COMPILERF90\t=\tgfortran\n FREESOURCE\t=\t-ffree-form  -ffree-line-length-none\n F90FLAGS\t=\t-fconvert=big-endian # -g\n MODFLAG\t\t=\t-I\n LDFLAGS\t\t=\n CPP\t\t=\tcpp\n CPPFLAGS\t=\t-C -P -traditional -D_GFORTRAN_ # -D_HRLDAS_URBAN_\n LIBS\t\t=\n LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-gfortran/include\n NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-gfortran/lib -lnetcdf\n BZIP2\t\t=\tYES\n BZIP2_LIB\t=\t-lbz2\n BZIP2_INCLUDE\t=\t-I/usr/include\n RM\t\t=\trm -f\n CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with pgf90 -- Serial\n#=============================================================================================\n\n#COMPILERF90\t=\tmpif90\n#FREESOURCE\t=\t-Mfree\n#F90FLAGS\t=\t-byteswapio # -g -C\n#MODFLAG\t\t=\t-I\n#LDFLAGS\t\t=\n#CPP\t\t=\tcpp\n#CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_ \n#LIBS\t\t=\n#LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n#INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n#NETCDFMOD\t=\t-I$(HOME)/netcdf/include\n#NETCDFLIB\t=\t-L$(HOME)/netcdf/lib -lnetcdf\n#BZIP2\t\t=\tYES\n#BZIP2_LIB\t=\t-lbz2\n#BZIP2_INCLUDE\t=\t-I/usr/include\n#RM\t\t=\trm -f\n#CC\t\t=\tcc\n#\n#=============================================================================================\n#  Options for Linux with pgf90 -- Parallel\n#=============================================================================================\n\n# COMPILERF90\t=\tmpif90 -f90=pgf90\n# FREESOURCE\t=\t-Mfree\n# F90FLAGS\t=\t-byteswapio # -g -C\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_PARALLEL_ # -D_HRLDAS_URBAN_ \n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-4.1.1-parallel-pgf90/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-4.1.1-parallel-pgf90/lib -lnetcdf -lcurl\n# HDF5LIB\t\t=       -L/scholar/kmanning/HDF5/lib -lhdf5_hl -lhdf5 -lz\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for IBM -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\txlf\n# FREESOURCE\t=\t-qfree=f90\n# F90FLAGS\t=\t-g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# INCJASPER\t=\t-I/contrib/jasper/include\n# LIBJASPER\t=\t-ljpeg -L/contrib/jasper/lib -ljasper\n# NETCDFMOD\t=\t-I/usr/local/include\n# NETCDFLIB\t=\t-L/usr/local/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-L/contrib/bzip2/lib -lbz2\n# BZIP2_INCLUDE\t=\t-I/contrib/bzip2/include\n# RM\t\t=\trm -f\n# CC\t\t=\txlC\n\n#=============================================================================================\n#  Options for IBM -- Parallel\n#=============================================================================================\n\n# COMPILERF90\t=\tmpxlf90_r\n# FREESOURCE\t=\t-qfree=f90\n# F90FLAGS\t=\t-g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_PARALLEL_ # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# INCJASPER\t=\t-I/contrib/jasper/include\n# LIBJASPER\t=\t-ljpeg -L/contrib/jasper/lib -ljasper\n# NETCDFMOD\t=\t-I/contrib/netcdf-4.1.1-mpi/include\n# NETCDFLIB\t=\t-L/contrib/netcdf-4.1.1-mpi/lib -lnetcdf\n# HDF5LIB\t\t=\t-L/contrib/hdf5-1.8.4-patch1-mpi/lib -lhdf5_hl -lhdf5 -lz -lgpfs\n# BZIP2\t\t=\tNO\n# BZIP2_LIB\t=\n# BZIP2_INCLUDE\t=\n# RM\t\t=\trm -f\n# CC\t\t=\tcc_r\n"
  },
  {
    "path": "src/Land_models/Noah/user_build_options.linux",
    "content": "#=============================================================================================\n#  Options for Linux with Intel Fortran -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tifort\n# FREESOURCE\t=\t-free\n# F90FLAGS\t=\t-convert big_endian # -g -O0 -check all,noshape,nopointer,noarg_temp_created -mp -fpe0\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-ifort/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-ifort/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# BZIP2_LIB\t=\t-L/usr/lib -lbz2\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with g95 -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tg95\n# FREESOURCE\t=\t-ffree-form  -ffree-line-length-huge\n# F90FLAGS\t=\t-fendian=big -fno-second-underscore # -g -fbounds-check -O0\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-g95/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-g95/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with gfortran -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tgfortran\n# FREESOURCE\t=\t-ffree-form  -ffree-line-length-none\n# F90FLAGS\t=\t-fconvert=big-endian # -g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_GFORTRAN_ # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-gfortran/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-gfortran/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with pgf90 -- Serial\n#=============================================================================================\n\nCOMPILERF90\t=\tmpif90\nCPPFLAGS\t=\t-C -P -traditional -DMPP_LAND # -D_HRLDAS_URBAN_ \n#COMPILERF90\t=\tpgf90 \n#CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_ \nFREESOURCE\t=\t-Mfree\nF90FLAGS\t=\t-byteswapio # -g -C\nMODFLAG\t\t=\t-I\nLDFLAGS\t\t=\nCPP\t\t=\tcpp\nLIBS\t\t=\nLIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\nINCJASPER\t=\t-I/scholar/kmanning/jasper/include\nNETCDFMOD\t=\t-I$(HOME)/netcdf/include\nNETCDFLIB\t=\t-L$(HOME)/netcdf/lib -lnetcdf\nBZIP2\t\t=\tYES\nBZIP2_LIB\t=\t-lbz2\nBZIP2_INCLUDE\t=\t-I/usr/include\nRM\t\t=\trm -f\nCC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with pgf90 -- Parallel\n#=============================================================================================\n\n# COMPILERF90\t=\tmpif90 -f90=pgf90\n# FREESOURCE\t=\t-Mfree\n# F90FLAGS\t=\t-byteswapio # -g -C\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_PARALLEL_ # -D_HRLDAS_URBAN_ \n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-4.1.1-parallel-pgf90/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-4.1.1-parallel-pgf90/lib -lnetcdf -lcurl\n# HDF5LIB\t\t=       -L/scholar/kmanning/HDF5/lib -lhdf5_hl -lhdf5 -lz\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for IBM -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\txlf\n# FREESOURCE\t=\t-qfree=f90\n# F90FLAGS\t=\t-g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# INCJASPER\t=\t-I/contrib/jasper/include\n# LIBJASPER\t=\t-ljpeg -L/contrib/jasper/lib -ljasper\n# NETCDFMOD\t=\t-I/usr/local/include\n# NETCDFLIB\t=\t-L/usr/local/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-L/contrib/bzip2/lib -lbz2\n# BZIP2_INCLUDE\t=\t-I/contrib/bzip2/include\n# RM\t\t=\trm -f\n# CC\t\t=\txlC\n\n#=============================================================================================\n#  Options for IBM -- Parallel\n#=============================================================================================\n\n# COMPILERF90\t=\tmpxlf90_r\n# FREESOURCE\t=\t-qfree=f90\n# F90FLAGS\t=\t-g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_PARALLEL_ # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# INCJASPER\t=\t-I/contrib/jasper/include\n# LIBJASPER\t=\t-ljpeg -L/contrib/jasper/lib -ljasper\n# NETCDFMOD\t=\t-I/contrib/netcdf-4.1.1-mpi/include\n# NETCDFLIB\t=\t-L/contrib/netcdf-4.1.1-mpi/lib -lnetcdf\n# HDF5LIB\t\t=\t-L/contrib/hdf5-1.8.4-patch1-mpi/lib -lhdf5_hl -lhdf5 -lz -lgpfs\n# BZIP2\t\t=\tNO\n# BZIP2_LIB\t=\n# BZIP2_INCLUDE\t=\n# RM\t\t=\trm -f\n# CC\t\t=\tcc_r\n"
  },
  {
    "path": "src/Land_models/Noah/user_build_options.linux.sequential",
    "content": "#=============================================================================================\n#  Options for Linux with Intel Fortran -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tifort\n# FREESOURCE\t=\t-free\n# F90FLAGS\t=\t-convert big_endian # -g -O0 -check all,noshape,nopointer,noarg_temp_created -mp -fpe0\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-ifort/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-ifort/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# BZIP2_LIB\t=\t-L/usr/lib -lbz2\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with g95 -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tg95\n# FREESOURCE\t=\t-ffree-form  -ffree-line-length-huge\n# F90FLAGS\t=\t-fendian=big -fno-second-underscore # -g -fbounds-check -O0\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-g95/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-g95/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with gfortran -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\tgfortran\n# FREESOURCE\t=\t-ffree-form  -ffree-line-length-none\n# F90FLAGS\t=\t-fconvert=big-endian # -g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_GFORTRAN_ # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-3.6.3-gfortran/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-3.6.3-gfortran/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with pgf90 -- Serial\n#=============================================================================================\n\n#COMPILERF90\t=\tmpif90\n#CPPFLAGS\t=\t-C -P -traditional -DMPP_LAND # -D_HRLDAS_URBAN_ \nCOMPILERF90\t=\tpgf90 \nCPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_ \nFREESOURCE\t=\t-Mfree\nF90FLAGS\t=\t-byteswapio # -g -C\nMODFLAG\t\t=\t-I\nLDFLAGS\t\t=\nCPP\t\t=\tcpp\nLIBS\t\t=\nLIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\nINCJASPER\t=\t-I/scholar/kmanning/jasper/include\nNETCDFMOD\t=\t-I$(HOME)/netcdf/include\nNETCDFLIB\t=\t-L$(HOME)/netcdf/lib -lnetcdf\nBZIP2\t\t=\tYES\nBZIP2_LIB\t=\t-lbz2\nBZIP2_INCLUDE\t=\t-I/usr/include\nRM\t\t=\trm -f\nCC\t\t=\tcc\n\n#=============================================================================================\n#  Options for Linux with pgf90 -- Parallel\n#=============================================================================================\n\n# COMPILERF90\t=\tmpif90 -f90=pgf90\n# FREESOURCE\t=\t-Mfree\n# F90FLAGS\t=\t-byteswapio # -g -C\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_PARALLEL_ # -D_HRLDAS_URBAN_ \n# LIBS\t\t=\n# LIBJASPER\t=\t-ljpeg -L/scholar/kmanning/jasper/lib -ljasper\n# INCJASPER\t=\t-I/scholar/kmanning/jasper/include\n# NETCDFMOD\t=\t-I/scholar/kmanning/netcdf-4.1.1-parallel-pgf90/include\n# NETCDFLIB\t=\t-L/scholar/kmanning/netcdf-4.1.1-parallel-pgf90/lib -lnetcdf -lcurl\n# HDF5LIB\t\t=       -L/scholar/kmanning/HDF5/lib -lhdf5_hl -lhdf5 -lz\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-lbz2\n# BZIP2_INCLUDE\t=\t-I/usr/include\n# RM\t\t=\trm -f\n# CC\t\t=\tcc\n\n#=============================================================================================\n#  Options for IBM -- Serial\n#=============================================================================================\n\n# COMPILERF90\t=\txlf\n# FREESOURCE\t=\t-qfree=f90\n# F90FLAGS\t=\t-g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# INCJASPER\t=\t-I/contrib/jasper/include\n# LIBJASPER\t=\t-ljpeg -L/contrib/jasper/lib -ljasper\n# NETCDFMOD\t=\t-I/usr/local/include\n# NETCDFLIB\t=\t-L/usr/local/lib -lnetcdf\n# BZIP2\t\t=\tYES\n# BZIP2_LIB\t=\t-L/contrib/bzip2/lib -lbz2\n# BZIP2_INCLUDE\t=\t-I/contrib/bzip2/include\n# RM\t\t=\trm -f\n# CC\t\t=\txlC\n\n#=============================================================================================\n#  Options for IBM -- Parallel\n#=============================================================================================\n\n# COMPILERF90\t=\tmpxlf90_r\n# FREESOURCE\t=\t-qfree=f90\n# F90FLAGS\t=\t-g\n# MODFLAG\t\t=\t-I\n# LDFLAGS\t\t=\n# CPP\t\t=\tcpp\n# CPPFLAGS\t=\t-C -P -traditional -D_PARALLEL_ # -D_HRLDAS_URBAN_\n# LIBS\t\t=\n# INCJASPER\t=\t-I/contrib/jasper/include\n# LIBJASPER\t=\t-ljpeg -L/contrib/jasper/lib -ljasper\n# NETCDFMOD\t=\t-I/contrib/netcdf-4.1.1-mpi/include\n# NETCDFLIB\t=\t-L/contrib/netcdf-4.1.1-mpi/lib -lnetcdf\n# HDF5LIB\t\t=\t-L/contrib/hdf5-1.8.4-patch1-mpi/lib -lhdf5_hl -lhdf5 -lz -lgpfs\n# BZIP2\t\t=\tNO\n# BZIP2_LIB\t=\n# BZIP2_INCLUDE\t=\n# RM\t\t=\trm -f\n# CC\t\t=\tcc_r\n"
  },
  {
    "path": "src/Land_models/NoahMP/CMakeLists.txt",
    "content": "add_subdirectory(\"phys\")\nadd_subdirectory(\"Utility_routines\")\nadd_subdirectory(\"data_structures\")\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/Makefile",
    "content": " SHELL=/bin/sh\n.SUFFIXES:\t\n.SUFFIXES:\t.F .c .o .exe\n\ninclude ../user_build_options\n\nOBJS=\tcreate_forcing.o\n\nCMD=\tcreate_forcing.exe\n\ndefault:\n\t(cd lib; make)\n\t(make -f Makefile all)\n\nall:\tlib/libsmda.a $(CMD)\n\t(cd lib; make)\n\nlib/libsmda.a:\n\t(cd lib; make)\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPP_NETCDF4_COMPRESS) $(FREESOURCE) $(F90FLAGS) $(LDFLAGS) -c $(NETCDFMOD) -I./lib -I./lib $(*).F\n\n$(CMD):\tlib/libsmda.a $(OBJS)\n\t(cd lib; make)\n\t$(COMPILERF90) -o $(@) -I./lib $(F90FLAGS) $(LDFLAGS) -I./lib $(OBJS) \\\n\t\t-L./lib -lsmda $(NETCDFLIB) $(BZIP2_LIB) $(LIBJASPER)\n\nclean:\n\t$(RM) *.o *~ *.exe *.mod\n\t(cd lib; make clean)\n#\n\n\n\n\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/create_forcing.F",
    "content": "program create_forcing\n  use module_grib\n  use module_geo_em\n  use kwm_grid_utilities\n  use kwm_date_utilities\n  use kwm_string_utilities\n  implicit none\n\n  character(len=9), parameter :: version = \"v20150518\"\n\n  character(len=256) :: namelist_file\n  character(len=13) :: date\n\n  type (geo_em_type) :: geo_em\n\n\n  integer, parameter :: MAXTEMPLATE = 10\n\n  type DataBuffer\n     character(len=256)                         :: label\n     character(len=256)                         :: units\n     real, pointer,      dimension(:,:)         :: field\n     character(len=19)                          :: hdate ! A punctuated date, out to seconds.\n     character(len=256), dimension(MAXTEMPLATE) :: flnm_template\n     real                                       :: layer1\n     real                                       :: layer2\n     character(len=4)                           :: remap_type\n     integer                                    :: fatality ! How we may or may not handle missing data.\n  end type DataBuffer\n\n  type VtableEntry\n     integer :: g1_parm\n     integer :: g1_levtyp\n     integer :: level1\n     integer :: level2\n     character(len=32) :: name\n     character(len=32) :: units\n     character(len=32) :: desc\n     integer :: g2_discp\n     integer :: g2_cat\n     integer :: g2_parm\n     integer :: g2_levtyp\n  end type VtableEntry\n\n  type(VtableEntry), dimension(64) :: vtable\n  integer :: vtable_count\n\n  type (DataBuffer) ::    Tprev,    Tcurrent,    Tpost\n  type (DataBuffer) ::    Qprev,    Qcurrent,    Qpost\n  type (DataBuffer) ::    Pprev,    Pcurrent,    Ppost\n  type (DataBuffer) ::    Uprev,    Ucurrent,    Upost\n  type (DataBuffer) ::    Vprev,    Vcurrent,    Vpost\n  type (DataBuffer) ::   LWprev,   LWcurrent,   LWpost\n  type (DataBuffer) ::  SW1prev,  SW1current,  SW1post\n  type (DataBuffer) ::  SW2prev,  SW2current,  SW2post\n  type (DataBuffer) :: PCP1prev, PCP1current, PCP1post\n  type (DataBuffer) :: PCP2prev, PCP2current, PCP2post\n  type (DataBuffer) ::    Hprev,    Hcurrent,    Hpost\n\n  type (DataBuffer) :: WEASDprev, WEASDcurrent, WEASDpost\n  type (DataBuffer) :: CANWTprev, CANWTcurrent, CANWTpost\n  type (DataBuffer) ::   SKTprev,   SKTcurrent,   SKTpost\n  type (DataBuffer), dimension(4) :: STprev, STcurrent, STpost\n  type (DataBuffer), dimension(4) :: SMprev, SMcurrent, SMpost\n\n  type (DataBuffer) :: Zcurrent\n  type (DataBuffer) :: LANDSEA\n  type (DataBuffer) :: gvfmin\n  type (DataBuffer) :: gvfmax\n  type (DataBuffer) :: vegfra\n  type (DataBuffer) :: lai\n\n  integer, pointer, dimension(:,:)   :: tempint    ! temporary array\n\n  real , dimension(4) :: dzs, zs\n\n  integer :: i, j\n  integer :: ierr\n  character(len=1) :: hgrid\n  character(len=8) :: name\n\n  integer :: ncid\n  integer :: ihour\n  integer :: numarg\n  integer :: unmatched\n#ifndef _GFORTRAN_\n  ! For some reason, gfortran does not like this declared external,\n  ! but everyone else wants it declared external.  So we use #ifndef\n  integer, external :: iargc\n#endif\n\n\n  ! Namelist variables\n  character(len=13)  :: startdate ! A punctuated date out to hours\n  character(len=13)  :: enddate   ! A punctuated date out to hours\n  character(len=256) :: DataDir\n  character(len=256) :: OutputDir\n  character(len=256) :: geo_em_flnm\n  character(len=256) :: initial_flnm\n  integer            :: rainfall_interp ! 0=Nearest Neighbor; 1=more expensive, grid fill method\n  integer            :: full_ic_frq     ! How frequently (hours) to make full surface initial conditions.\n                                        ! FULL_IC_FRC==0 means do this only at the startdate.\n                                        ! FULL_IC_FRC==-1 means never make full surface initial conditions.\n  logical            :: rescale_shortwave\n  logical            :: update_snow\n  logical            :: forcing_height_2d\n  logical            :: truncate_sw\n  integer            :: expand_loop\n  logical            :: init_lai\n  logical            :: vary_lai\n  logical            :: mask_water\n  character(len=256), dimension(MAXTEMPLATE) :: Tfile_template         ! T forcing\n  character(len=256), dimension(MAXTEMPLATE) :: Qfile_template         ! Q forcing\n  character(len=256), dimension(MAXTEMPLATE) :: Pfile_template         ! P forcing\n  character(len=256), dimension(MAXTEMPLATE) :: Ufile_template         ! U forcing\n  character(len=256), dimension(MAXTEMPLATE) :: Vfile_template         ! V forcing\n  character(len=256), dimension(MAXTEMPLATE) :: LWfile_template        ! LW forcing\n  character(len=256), dimension(MAXTEMPLATE) :: SWfile_primary         ! SW forcing\n  character(len=256), dimension(MAXTEMPLATE) :: SWfile_secondary       ! Optional SW forcing\n  character(len=256), dimension(MAXTEMPLATE) :: PCPfile_primary        ! Precipitation forcing\n  character(len=256), dimension(MAXTEMPLATE) :: PCPfile_secondary      ! Optional precipitation forcing\n  character(len=256), dimension(MAXTEMPLATE) :: Hfile_template         ! Optional 2D forcing height\n\n  character(len=256), dimension(MAXTEMPLATE) :: WEASDfile_template     ! SWE initial field\n  character(len=256), dimension(MAXTEMPLATE) :: CANWTfile_template     ! Canopy water initial field\n  character(len=256), dimension(MAXTEMPLATE) :: SKINTfile_template     ! Skin temperature initial\n  character(len=256), dimension(4,MAXTEMPLATE) :: STfile_template      ! Soil temperature initial\n  character(len=256), dimension(4,MAXTEMPLATE) :: SMfile_template      ! Soil moisture initial\n\n  character(len=256), dimension(MAXTEMPLATE) :: Zfile_template         ! source model surface elevation\n  character(len=256), dimension(MAXTEMPLATE) :: LANDSfile_template     ! Land-sea mask from forcing\n\n\n\n  namelist /files/ startdate, enddate, DataDir, OutputDir, &\n       geo_em_flnm,                                        &\n       rainfall_interp, full_ic_frq, rescale_shortwave,    &\n       update_snow, forcing_height_2d,                     &\n       truncate_sw, expand_loop,                           &\n       init_lai, vary_lai,mask_water,                      &\n       Tfile_template, Qfile_template, Pfile_template,     &\n       Ufile_template, Vfile_template, LWfile_template,    &\n       SWfile_primary, SWfile_secondary, PCPfile_primary,  &\n       PCPfile_secondary, Hfile_template, WEASDfile_template,&\n       CANWTfile_template, SKINTfile_template, STfile_template, &\n       SMfile_template, Zfile_template, LANDSfile_template\n\n\n  full_ic_frq        = 0\n  rainfall_interp    = 1\n  rescale_shortwave  = .FALSE.\n  update_snow        = .FALSE.\n  forcing_height_2d  = .FALSE.\n  truncate_sw        = .FALSE.\n  init_lai           = .FALSE.\n  vary_lai           = .FALSE.\n  mask_water         = .FALSE.\n  expand_loop        = 0\n  Tfile_template     = \" \"\n  Qfile_template     = \" \"\n  Pfile_template     = \" \"\n  Ufile_template     = \" \"\n  Vfile_template     = \" \"\n  LWfile_template    = \" \"\n  SWfile_primary     = \" \"\n  SWfile_secondary   = \" \"\n  PCPfile_primary    = \" \"\n  PCPfile_secondary  = \" \"\n  Hfile_template     = \" \"\n  WEASDfile_template = \" \"\n  CANWTfile_template = \" \"\n  SKINTfile_template = \" \"\n  STfile_template    = \" \"\n  SMfile_template    = \" \"\n  Zfile_template     = \" \"\n  LANDSfile_template = \" \"\n\n\n!--------------------------------------------------------------------------\n! Read namelist\n!--------------------------------------------------------------------------\n\n  numarg = iargc()\n  if (numarg > 0) then\n     call getarg(1, namelist_file)\n  else\n     namelist_file = \"namelist.input\"\n  endif\n\n  open(12,file=trim(namelist_file), form='formatted', action='read', status='old', iostat=ierr)\n  if (ierr /= 0) then\n     write(*,*)\n     write(*,'(\"  *****  Failure trying to open file ''\", A, \"''\")') trim(namelist_file)\n     write(*,*)\n     write(*,'(\"Program takes an optional command-line argument, the name of the namelist file.\")')\n     if ( numarg > 0 ) then\n        write(*,'(\"In this case, you provided the name ''\", A, \"''\")') trim(namelist_file)\n     endif\n     write(*,*)\n     write(*,'(\"With no command-line argument, program expects the namelist file to be\")')\n     write(*,'(\"called ''namelist.input'', which must be present in the working directory. \")')\n     write(*,*)\n     stop\n  endif\n  read(12,files)\n  close(12)\n\n!--------------------------------------------------------------------------\n! Read Vtable\n!--------------------------------------------------------------------------\n\n  call read_vtable(trim(namelist_file))   ! subroutine below\n\n!--------------------------------------------------------------------------\n! Begin to fill in our file name template strings\n!--------------------------------------------------------------------------\n\n  do j = 1, maxtemplate\n     call strrep(    Tfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(    Qfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(    Pfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(    Ufile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(    Vfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(   LWfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(    SWfile_primary(j), \"<DataDir>\", trim(DataDir))\n     call strrep(  SWfile_secondary(j), \"<DataDir>\", trim(DataDir))\n     call strrep(   PCPfile_primary(j), \"<DataDir>\", trim(DataDir))\n     call strrep( PCPfile_secondary(j), \"<DataDir>\", trim(DataDir))\n     call strrep(    Hfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(WEASDfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(CANWTfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(SKINTfile_template(j), \"<DataDir>\", trim(DataDir))\n     do i = 1, 4\n        call strrep(STfile_template(i,j), \"<DataDir>\", trim(DataDir))\n        call strrep(SMfile_template(i,j), \"<DataDir>\", trim(DataDir))\n     enddo\n     call strrep(    Zfile_template(j), \"<DataDir>\", trim(DataDir))\n     call strrep(LANDSfile_template(j), \"<DataDir>\", trim(DataDir))\n  enddo\n\n!------------------------------------------------------------------------\n! Read the geo_em file\n!------------------------------------------------------------------------\n\n  call strrep(geo_em_flnm, \"<DataDir>\", trim(DataDir))\n  write(*,'(A)') 'geo_em_flnm    = \"'//trim(geo_em_flnm)//'\"'\n\n  call read_geo_em_file(trim(geo_em_flnm), geo_em, ierr)\n  if (ierr /= 0) stop \"FATAL ERROR: Problem reading geo_em file\"\n  write(hgrid,'(I1)') geo_em%grid_id\n\n  nullify(gvfmin%field)\n  nullify(gvfmax%field)\n  nullify(vegfra%field)\n  allocate(gvfmin%field(geo_em%idim, geo_em%jdim))\n  allocate(gvfmax%field(geo_em%idim, geo_em%jdim))\n  allocate(vegfra%field(geo_em%idim, geo_em%jdim))\n  if(vary_lai .or. init_lai) allocate(lai%field(geo_em%idim, geo_em%jdim))\n\n  gvfmin%field(:,:) = minval(geo_em%veg,3)\n  gvfmax%field(:,:) = maxval(geo_em%veg,3)\n\n! Not certain why the following is necessary since we are simulating over the WRF points\n!    so they should have been filled properly already, commenting (Barlage 20140529)\n\n!  call fillsm(gvfmin%field, (geo_em%use /= geo_em%iswater), geo_em%idim, geo_em%jdim)\n!  call fillsm(gvfmax%field, (geo_em%use /= geo_em%iswater), geo_em%idim, geo_em%jdim)\n\n  where (gvfmin%field < 0.0) gvfmin%field = 0.0\n  where (gvfmax%field < 0.0) gvfmax%field = 0.0\n\n!--------------------------------------------------------------------------\n! Data buffer structure initializations\n!--------------------------------------------------------------------------\n\n  call data_buffer_init(    Tprev,    Tcurrent,    Tpost,     Tfile_template,\"bint\", \"T2D\"                )\n  call data_buffer_init(    Qprev,    Qcurrent,    Qpost,     Qfile_template,\"bint\", \"Q2D\"                )\n  call data_buffer_init(    Pprev,    Pcurrent,    Ppost,     Pfile_template,\"bint\", \"PSFC\"               )\n  call data_buffer_init(    Uprev,    Ucurrent,    Upost,     Ufile_template,\"bint\", \"U2D\"                )\n  call data_buffer_init(    Vprev,    Vcurrent,    Vpost,     Vfile_template,\"bint\", \"V2D\"                )\n  call data_buffer_init(   LWprev,   LWcurrent,   LWpost,    LWfile_template,\"bint\", \"LWDOWN\"             )\n  call data_buffer_init(  SW1prev,  SW1current,  SW1post,     SWfile_primary,\"bint\", \"SWDOWN\"  ,fatality=2)\n  call data_buffer_init(  SW2prev,  SW2current,  SW2post,   SWfile_secondary,\"bint\", \"SWDOWN\"             )\n  call data_buffer_init( PCP1prev, PCP1current, PCP1post,    PCPfile_primary, \"4pt\", \"RAINRATE\",fatality=2)\n  call data_buffer_init( PCP2prev, PCP2current, PCP2post,  PCPfile_secondary, \"4pt\", \"RAINRATE\"           )\n  call data_buffer_init(    Hprev,    Hcurrent,    Hpost,     Hfile_template,\"bint\", \"ZLVL2D\"             )\n  call data_buffer_init(WEASDprev,WEASDcurrent,WEASDpost, WEASDfile_template,\"16pt\", \"SNOW\"               )\n  call data_buffer_init(CANWTprev,CANWTcurrent,CANWTpost, CANWTfile_template,\"16pt\", \"CANWAT\"             )\n  call data_buffer_init(  SKTprev,  SKTcurrent,  SKTpost, SKINTfile_template,\"bint\", \"TSK\"                )\n  do i = 1, 4\n     write(name, '(\"STEMP_\",i1)') i\n     call data_buffer_init(  STprev(i),   STcurrent(i),   STpost(i), STfile_template(i,:),  \"16pt\", name )\n     write(name, '(\"SMOIS_\",i1)') i\n     call data_buffer_init(  SMprev(i),   SMcurrent(i),   SMpost(i), SMfile_template(i,:),  \"16pt\", name )\n  enddo\n\n  Zcurrent%label    = \"TERRAIN\"\n  Zcurrent%hdate    = \"0000-00-00_00:00:00\"\n  Zcurrent%flnm_template = Zfile_template\n\n  LANDSEA%label         = \"LANDSEA\"\n  LANDSEA%hdate         = \"0000-00-00_00:00:00\"\n  LANDSEA%flnm_template = LANDSfile_template\n\n  gvfmin%label = \"SHDMIN\"\n  gvfmin%units = \"%\"\n  gvfmin%layer1 = -1.E36\n  gvfmin%layer2 = -1.E36\n\n  gvfmax%label = \"SHDMAX\"\n  gvfmax%units = \"%\"\n  gvfmax%layer1 = -1.E36\n  gvfmax%layer2 = -1.E36\n\n  vegfra%label = \"VEGFRA\"\n  vegfra%units = \"%\"\n  vegfra%layer1 = -1.E36\n  vegfra%layer2 = -1.E36\n\n  if(vary_lai .or. init_lai) then\n    lai%label = \"LAI\"\n    lai%units = \"m^2/m^2\"\n    lai%layer1 = -1.E36\n    lai%layer2 = -1.E36\n  end if\n\n!--------------------------------------------------------------------------\n! Loop DATELOOP is the main loop over time.\n!--------------------------------------------------------------------------\n\n  date = startdate\n\n  DATELOOP : do while ( date <= enddate )\n\n     call geth_idts(date(1:13), startdate(1:13), ihour)\n\n     print*, 'Date = ', Date, \"  ihour = \", ihour\n\n     call interpolate_vegetation(\"VEGFRA\", date, geo_em%idim, geo_em%jdim, geo_em%veg, vegfra%field)\n\n     if(vary_lai) call interpolate_vegetation(\"LAI\", date, geo_em%idim, geo_em%jdim, geo_em%lai, lai%field)\n\n! Not certain why the following is necessary since we are simulating over the WRF points\n!    so they should have been filled properly already, commenting (Barlage 20140529)\n!     call fillsm(vegfra%field, (geo_em%use /= geo_em%iswater), geo_em%idim, geo_em%jdim)\n\n     call process(date, Tcurrent, Tprev, Tpost, geo_em, expand_loop)\n     call process(date, Qcurrent, Qprev, Qpost, geo_em, expand_loop)\n     call process(date, Pcurrent, Pprev, Ppost, geo_em, expand_loop)\n     call process(date, Ucurrent, Uprev, Upost, geo_em, expand_loop)\n     call process(date, Vcurrent, Vprev, Vpost, geo_em, expand_loop)\n     call process(date, LWcurrent,   LWprev,   LWpost, geo_em, expand_loop)\n     call process(date, SW1current,  SW1prev,  SW1post, geo_em, expand_loop)\n     call process(date, SW2current,  SW2prev,  SW2post, geo_em, expand_loop)\n     call process(date, PCP1current, PCP1prev, PCP1post, geo_em, expand_loop)\n     call process(date, PCP2current, PCP2prev, PCP2post, geo_em, expand_loop)\n     if(forcing_height_2d) call process(date, Hcurrent, Hprev, Hpost, geo_em, expand_loop)\n\n     call open_netcdf_for_output( &\n          trim(OutputDir)//date(1:4)//date(6:7)//date(9:10)//date(12:13)//\".LDASIN_DOMAIN\"//hgrid, &\n          ncid, version, geo_em%idim, geo_em%jdim, geo_em, .false.)\n\n     ! For output, the Tcurrent%field needs to be readjusted to model elevation\n     Tcurrent%field = Tcurrent%field + ( -0.0065 * geo_em%ter )\n\n     ! Fill in missing areas in PCP1 with data from PCP2\n     where (PCP2current%field <=0) PCP2current%field=0\n     where (PCP1current%field <-1.E25) PCP1current%field=PCP2current%field\n     where (PCP1current%field <=0) PCP1current%field=0\n\n     ! Fill in missing areas in SW1 with data from SW2\n     where (SW2current%field <= 0) SW2current%field = 0\n     where (SW1current%field <= 0) SW1current%field = SW2current%field\n     where (SW1current%field <= 0) SW1current%field = 0\n\n     ! If the sun isn't up, there shouldn't be any SW.\n     ! This may be a little extreme (ignores atmospheric refraction effects, e.g.); it \n     ! causes an awfully abrupt terminator.  Will have to consider.\n\n     if (truncate_sw) &\n       call nighttime_SW(SW1current%hdate, SW1current%field, geo_em%idim, geo_em%jdim, geo_em)\n\n     if (mask_water) then\n       where(geo_em%use == geo_em%iswater)    Tcurrent%field = -1.e36\n       where(geo_em%use == geo_em%iswater)    Qcurrent%field = -1.e36\n       where(geo_em%use == geo_em%iswater)    Pcurrent%field = -1.e36\n       where(geo_em%use == geo_em%iswater)    Ucurrent%field = -1.e36\n       where(geo_em%use == geo_em%iswater)    Vcurrent%field = -1.e36\n       where(geo_em%use == geo_em%iswater)   LWcurrent%field = -1.e36\n       where(geo_em%use == geo_em%iswater)  SW1current%field = -1.e36\n       where(geo_em%use == geo_em%iswater) PCP1current%field = -1.e36\n       if(forcing_height_2d) where(geo_em%use == geo_em%iswater) Hcurrent%field = -1.e36\n     end if\n\n     if(date == startdate) then  ! Do a quick test to see if any valid land points have problems\n       unmatched = count(Tcurrent%field < -1.e30 .and. geo_em%use /= geo_em%iswater)\n       if(unmatched > 0) then\n         print *, \"You have this many undefined T points over valid land points: \", unmatched\n         print *, \"This tends to happen around coastlines or for unresolved islands in your forcing data\"\n      \t print *, \"===== Consider increasing expand_loop in namelist =====\"\n      \t print *, \"However, this may also occur if your forcing source does not cover your domain.\"\n      \t stop\n       end if\n     end if\n\n     call output_databuffer(ncid,    Tcurrent)\n     call output_databuffer(ncid,    Qcurrent)\n     call output_databuffer(ncid,    Pcurrent)\n     call output_databuffer(ncid,    Ucurrent)\n     call output_databuffer(ncid,    Vcurrent)\n     call output_databuffer(ncid,   LWcurrent)\n     call output_databuffer(ncid,  SW1current)\n     call output_databuffer(ncid, PCP1current)\n     if(forcing_height_2d) call output_databuffer(ncid,    Hcurrent)\n\n     if (date(12:13) == \"00\" .and. update_snow) then\n        where (WEASDcurrent%field < 0)       WEASDcurrent%field = 0.0\n        where (geo_em%use == geo_em%iswater) WEASDcurrent%field = 0.0\n        call output_databuffer(ncid, WEASDcurrent)\n     endif\n\n     if (date(12:13) == \"00\") then\n        where (geo_em%use == geo_em%iswater .or. geo_em%use == geo_em%islake) vegfra%field = 0.0\n        call output_databuffer(ncid, vegfra)\n     endif\n\n     if (date(12:13) == \"00\" .and. vary_lai) then\n        where (geo_em%use == geo_em%iswater .or. geo_em%use == geo_em%islake) lai%field = 0.0\n        call output_databuffer(ncid, lai)\n     endif\n\n     ierr = nf90_close(ncid)\n     call error_handler(ierr, \"Problem closing Netcdf file\")\n\n     if ( full_ic_frq > -1 ) then  ! full_ic_frq == -1 turns off extra processing for initial conditions.\n        if ( ( (full_ic_frq>0) .and. (mod(ihour, full_ic_frq)==0) ) .or. ( ihour==0 ) ) then\n\n           call open_netcdf_for_output( trim(OutputDir)//\"HRLDAS_setup_\"//date(1:4)//date(6:7)//date(9:10)//date(12:13)//\"_d\"//hgrid, &\n             ncid, version, geo_em%idim, geo_em%jdim, geo_em, .true.)\n\n           call output_timestring_to_netcdf(ncid, date)\n\n           where(geo_em%use == geo_em%iswater .or. geo_em%use == geo_em%islake) geo_em%tmn = -1.e36\n\n           call output_to_netcdf(ncid,     \"XLAT\", \"degree_north\", geo_em%lat, geo_em%idim, geo_em%jdim)\n           call output_to_netcdf(ncid,    \"XLONG\", \"degree_east\" , geo_em%lon, geo_em%idim, geo_em%jdim)\n           call output_to_netcdf(ncid,      \"TMN\",           \"K\" , geo_em%tmn, geo_em%idim, geo_em%jdim)\n           call output_to_netcdf(ncid,      \"HGT\",           \"m\" , geo_em%ter, geo_em%idim, geo_em%jdim)\n           call output_to_netcdf(ncid,   \"SEAICE\",            \"\" , geo_em%ice, geo_em%idim, geo_em%jdim)\n           call output_to_netcdf(ncid,\"MAPFAC_MX\",            \"\" , geo_em%mmx, geo_em%idim, geo_em%jdim)\n           call output_to_netcdf(ncid,\"MAPFAC_MY\",            \"\" , geo_em%mmy, geo_em%idim, geo_em%jdim)\n           call output_to_netcdf(ncid,   \"SHDMAX\",           \"%\" , gvfmax%field, geo_em%idim, geo_em%jdim)\n           call output_to_netcdf(ncid,   \"SHDMIN\",           \"%\" , gvfmin%field, geo_em%idim, geo_em%jdim)\n\n           if(init_lai) then\n\t     call interpolate_vegetation(\"LAI\", date, geo_em%idim, geo_em%jdim, geo_em%lai, lai%field)\n             call output_to_netcdf(ncid,   \"LAI\",      \"m^2/m^2\" , lai%field, geo_em%idim, geo_em%jdim)\n\t   end if\n\n           allocate(tempint(geo_em%idim, geo_em%jdim))\n\t   tempint = int(geo_em%msk)\n           call output_to_netcdf_int(ncid, \"XLAND\",           \"\" , tempint, geo_em%idim, geo_em%jdim)\n\t   tempint = int(geo_em%use)\n           call output_to_netcdf_int(ncid,\"IVGTYP\",           \"\" , tempint, geo_em%idim, geo_em%jdim)\n\t   tempint = int(geo_em%soi)\n           call output_to_netcdf_int(ncid,\"ISLTYP\",           \"\" , tempint, geo_em%idim, geo_em%jdim)\n\n\n           call process(date, WEASDcurrent, WEASDprev, WEASDpost, geo_em, expand_loop);\n           where (WEASDcurrent%field < 0) WEASDcurrent%field = 0\n           call output_databuffer(ncid, WEASDcurrent)\n\n           call process(date, CANWTcurrent, CANWTprev, CANWTpost, geo_em, expand_loop);\n           where (CANWTcurrent%field < 0) CANWTcurrent%field = 0\n           call output_databuffer(ncid, CANWTcurrent)\n           deallocate(CANWTprev%field, stat=ierr)\n           deallocate(CANWTcurrent%field, stat=ierr)\n           deallocate(CANWTpost%field, stat=ierr)\n\n           call process(date, SKTcurrent, SKTprev, SKTpost, geo_em, expand_loop);\n           call output_databuffer(ncid,   SKTcurrent)\n           deallocate(SKTprev%field, stat=ierr)\n           deallocate(SKTcurrent%field, stat=ierr)\n           deallocate(SKTpost%field, stat=ierr)\n\n           do i = 1, 4\n              call process(date, STcurrent(i), STprev(i), STpost(i), geo_em, expand_loop);\n              call process(date, SMcurrent(i), SMprev(i), SMpost(i), geo_em, expand_loop);\n\t      dzs(i) = STcurrent(i)%layer2 - STcurrent(i)%layer1\n\t      if (i == 1) then\n\t        zs(i) = 0.5 * STcurrent(i)%layer2\n\t      else\n\t        zs(i) = 0.5*dzs(i) + sum(dzs(1:i-1))\n\t      end if\n           enddo\n\n           call output_to_netcdf_vector(ncid, \"DZS\", \"m\", 4, dzs)\n           call output_to_netcdf_vector(ncid, \"ZS\", \"m\", 4, zs)\n\n           unmatched = count(STcurrent(1)%field < -1.e30 .and. geo_em%use /= geo_em%iswater)\n           if(unmatched > 0) then\n             print *, \"You have this many undefined soil points over valid land points: \", unmatched\n             print *, \"This tends to happen around coastlines or for unresolved islands in your forcing data\"\n      \t     print *, \"===== Consider increasing expand_loop in namelist =====\"\n      \t     print *, \"However, this may also occur if your forcing source does not cover your domain.\"\n      \t     stop\n           end if\n\n           call output_to_netcdf_soil(ncid, \"TSLB\", \"K\", STcurrent(1)%field, STcurrent(2)%field, STcurrent(3)%field,  &\n\t                                STcurrent(4)%field, geo_em%idim, geo_em%jdim, 4)\n           do i = 1, 4\n              deallocate(STprev(i)%field, stat=ierr)\n              deallocate(STcurrent(i)%field, stat=ierr)\n              deallocate(STpost(i)%field, stat=ierr)\n           enddo\n\n           do i = 1, 4\n              ! Put a rough maximum on soil moisture, before we write it out.\n              where (SMcurrent(i)%field > 0.5) SMcurrent(i)%field = 0.5  ! Change to 0.5 (Barlage 20140529)\n           enddo\n\n           call output_to_netcdf_soil(ncid, \"SMOIS\", \"m^3/m^3\", SMcurrent(1)%field, SMcurrent(2)%field, SMcurrent(3)%field,  &\n\t                                SMcurrent(4)%field, geo_em%idim, geo_em%jdim, 4)\n           do i = 1, 4\n              deallocate(SMprev(i)%field, stat=ierr)\n              deallocate(SMcurrent(i)%field, stat=ierr)\n              deallocate(SMpost(i)%field, stat=ierr)\n           enddo\n\n           ierr = nf90_close(ncid)\n           call error_handler(ierr, \"Problem closing initial file\")\n\n        endif\n     endif\n\n     call geth_newdate(date, date, 1)\n  enddo DATELOOP\n\n\n  deallocate(Tprev%field, stat=ierr)\n  deallocate(Tcurrent%field, stat=ierr)\n  deallocate(Tpost%field, stat=ierr)\n\n  deallocate(Qprev%field, stat=ierr)\n  deallocate(Qcurrent%field, stat=ierr)\n  deallocate(Qpost%field, stat=ierr)\n\n  deallocate(Pprev%field, stat=ierr)\n  deallocate(Pcurrent%field, stat=ierr)\n  deallocate(Ppost%field, stat=ierr)\n\n  deallocate(Uprev%field, stat=ierr)\n  deallocate(Ucurrent%field, stat=ierr)\n  deallocate(Upost%field, stat=ierr)\n\n  deallocate(Vprev%field, stat=ierr)\n  deallocate(Vcurrent%field, stat=ierr)\n  deallocate(Vpost%field, stat=ierr)\n\n  deallocate(LWprev%field, stat=ierr)\n  deallocate(LWcurrent%field, stat=ierr)\n  deallocate(LWpost%field, stat=ierr)\n\n  deallocate(SW1prev%field, stat=ierr)\n  deallocate(SW1current%field, stat=ierr)\n  deallocate(SW1post%field, stat=ierr)\n\n  deallocate(SW2prev%field, stat=ierr)\n  deallocate(SW2current%field, stat=ierr)\n  deallocate(SW2post%field, stat=ierr)\n\n  deallocate(PCP1prev%field, stat=ierr)\n  deallocate(PCP1current%field, stat=ierr)\n  deallocate(PCP1post%field, stat=ierr)\n\n  deallocate(PCP2prev%field, stat=ierr)\n  deallocate(PCP2current%field, stat=ierr)\n  deallocate(PCP2post%field, stat=ierr)\n\n  deallocate(Hprev%field, stat=ierr)\n  deallocate(Hcurrent%field, stat=ierr)\n  deallocate(Hpost%field, stat=ierr)\n\n  deallocate(WEASDprev%field, stat=ierr)\n  deallocate(WEASDcurrent%field, stat=ierr)\n  deallocate(WEASDpost%field, stat=ierr)\n\n  deallocate(LANDSEA%field, stat=ierr)\n  deallocate(zcurrent%field, stat=ierr)\n  deallocate(gvfmin%field, stat=ierr)\n  deallocate(gvfmax%field, stat=ierr)\n  deallocate(vegfra%field, stat=ierr)\n  deallocate(geo_em%lat, stat=ierr)\n  deallocate(geo_em%lon, stat=ierr)\n  deallocate(geo_em%ter, stat=ierr)\n  deallocate(geo_em%use, stat=ierr)\n  deallocate(geo_em%veg, stat=ierr)\n\n  call grib2_clear_parameter_table\n\n\ncontains\n\n!==============================================================================\n!==============================================================================\n  subroutine read_vtable(filename)\n    implicit none\n    character(len=*), intent(in) :: filename\n\n    character(len=256) :: string\n    integer :: ierr\n    integer :: jstart, jbar\n    character(len=64) :: val\n    integer :: vcount\n\n    !\n    ! Open the file\n    !\n    open(12, file=filename, status='old', form='formatted', iostat=ierr)\n\n    !\n    ! Scan forward until we find the string <VTABLE>\n    !\n    do\n       read(12, '(A255)', iostat=ierr) string\n       if (ierr /= 0) stop \"FATAL ERROR: Problem searching for <VTABLE>\"\n       if (string == \"<VTABLE>\") exit\n    enddo\n\n    !\n    ! We've found the <VTABLE> marker.  Now read the table information\n    !\n\n    vcount = 0\n    VLOOP : do\n       read(12, '(A255)', iostat=ierr) string\n       if (ierr /= 0) stop \"FATAL ERROR: Problem reading Variable Table\"\n       if (string == \"</VTABLE>\") exit\n       if (string(1:1) == \"-\") cycle\n       if (string(1:1) == \"#\") cycle\n       if (string(1:5) == \"GRIB1\") cycle\n       if (string(1:5) == \"Param\") cycle\n       write(*, '(A)') trim(string)\n\n       jstart = 1\n       vcount = vcount + 1\n       if (vcount > size(vtable)) then\n          write(*,'(\"FATAL ERROR:      Parameterized size of vtable (\",I4,\") is too small.\")') size(vtable)\n          write(*,'(\"FATAL ERROR:      Change the dimensions of vtable and recompile.\",/)')\n          stop\n       endif\n\n       BLOOP : do j = 1, 11\n          ! The fields are delimited by '|'\n          jbar = index(string(jstart:255),'|') + jstart - 2\n          val = trim(adjustl(string(jstart:jbar)))\n          jstart = jbar + 2\n          select case (j)\n          case (1)\n             read(val,*,iostat=ierr) vtable(vcount)%g1_parm\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop \"FATAL ERROR: Vtable read problem entry\"\n             endif\n          case (2)\n             read(val,*,iostat=ierr) vtable(vcount)%g1_levtyp\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop \"FATAL ERROR: Vtable read problem entry\"\n             endif\n          case (3)\n             read(val,*,iostat=ierr) vtable(vcount)%level1\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop \"FATAL ERROR: Vtable read problem entry\"\n             endif\n          case (4)\n             if (val == \" \") then\n                vtable(vcount)%level2 = 999\n             else\n                read(val,*,iostat=ierr) vtable(vcount)%level2\n                if (ierr /= 0) then\n                   write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                   stop \"FATAL ERROR: Vtable read problem entry\"\n                endif\n             endif\n          case (5)\n             vtable(vcount)%name = val\n          case (6)\n             vtable(vcount)%units = val\n          case (7)\n             vtable(vcount)%desc = val\n          case (8)\n             read(val,*,iostat=ierr) vtable(vcount)%g2_discp\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop \"FATAL ERROR: Vtable read problem entry\"\n             endif\n          case (9)\n             read(val,*,iostat=ierr) vtable(vcount)%g2_cat\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop \"FATAL ERROR: Vtable read problem entry\"\n             endif\n          case (10)\n             read(val,*,iostat=ierr) vtable(vcount)%g2_parm\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop \"FATAL ERROR: Vtable read problem entry\"\n             endif\n          case (11)\n             read(val,*,iostat=ierr) vtable(vcount)%g2_levtyp\n             if (ierr /= 0) then\n                write(*,'(\"Vtable read problem, entry \", I4, \" column \", I4)') vcount, j\n                stop \"FATAL ERROR: Vtable read problem entry\"\n             endif\n          end select\n\n       enddo BLOOP\n\n       ! write(*,'(I4,I4,I4,I4,1x,A,1x,A,1x,A,I4,I4,I4,I4)') vtable(vcount)%g1_parm, vtable(vcount)%g1_levtyp, &\n       !      vtable(vcount)%level1, vtable(vcount)%level2, trim(vtable(vcount)%name), &\n       !      trim(vtable(vcount)%units), trim(vtable(vcount)%desc), vtable(vcount)%g2_discp, &\n       !      vtable(vcount)%g2_cat, vtable(vcount)%g2_parm, vtable(vcount)%g2_levtyp\n\n    enddo VLOOP\n\n    vtable_count = vcount\n\n  end subroutine read_vtable\n\n!==============================================================================\n!==============================================================================\n\n  subroutine data_buffer_init(prev, current, post, file_template, remap_type, label, fatality)\n    implicit none\n    type (DataBuffer) :: prev, current, post\n    character(len=256), dimension(MAXTEMPLATE), intent(in)  :: file_template\n    character(len=*),  intent(in)  :: label\n    character(len=*),  intent(in) :: remap_type\n    integer, optional, intent(in) :: fatality\n    prev%label    = label\n    prev%hdate    = \"0000-00-00_00:00:00\"\n    prev%flnm_template = file_template\n    prev%remap_type = remap_type\n    if (present(fatality)) then\n       prev%fatality=fatality\n    else\n       prev%fatality=0\n    endif\n    current = prev\n    post    = prev\n  end subroutine data_buffer_init\n\n!==============================================================================\n!==============================================================================\n\n  subroutine copy_data_buffer(out, in)\n    !\n    ! Copy the databuffer type from <in> to <out>\n    !\n    ! We do this to be explicit in allocating new memory for\n    ! pointer array <out%field>, and copying the data from\n    ! <in%field> to <out%field> (instead of merely pointing\n    ! <out%field> => <in%field>\n    implicit none\n    type(DataBuffer), intent(out) :: out\n    type(DataBuffer), intent(in)  :: in\n\n\n    out%label = in%label\n    out%units = in%units\n    out%hdate = in%hdate\n    out%flnm_template = in%flnm_template\n    out%layer1 = in%layer1\n    out%layer2 = in%layer2\n    out%remap_type = in%remap_type\n    out%fatality = in%fatality\n\n    if (associated(in%field)) then\n       allocate(out%field(size(in%field,1), size(in%field,2)))\n       out%field = in%field\n    else\n       nullify(out%field)\n    endif\n\n\n  end subroutine copy_data_buffer\n\n!==============================================================================\n!==============================================================================\n\n  subroutine process(input_date, current, prev, post, geo_em, expand_loop)\n    use module_input_data_structure\n    implicit none\n    character(len=*), intent(in)    :: input_date\n    type(DataBuffer), intent(inout) :: current\n    type(DataBuffer), intent(inout) :: prev\n    type(DataBuffer), intent(inout) :: post\n    type (geo_em_type), intent(in)  :: geo_em\n    integer, intent(in)             :: expand_loop\n\n    type(input_data_type) :: datastruct\n    type(input_data_type) :: Zdatastruct\n    type(input_data_type) :: LANDSEAdatastruct\n\n    real    :: xval\n\n    integer :: ierr\n    integer :: idts\n\n    integer :: idim\n    integer :: jdim\n\n    character(len=256) :: teststring\n\n\n    ! The fatality level in the DataBuffer structure indicates what sort\n    ! of errors are fatal and what sort of errors we want to try to\n    ! recover from.\n    !\n    ! fatality==0 means that any problem is a fatal error, and we stop.\n    !\n    ! fatality==2 means that if we cannot find a matching file, and we\n    ! cannot find files from which we may do temporal interpolation, we\n    ! do not stop, but return a missing-data field.  The calling routine\n    ! is responsible for filling in missing data.\n    nullify(datastruct%data)\n    nullify(zdatastruct%data)\n    nullify(LANDSEAdatastruct%data)\n\n    idim = geo_em%idim\n    jdim = geo_em%jdim\n\n    current%hdate = input_date(1:13)//\":00:00\"\n\n    if (associated(current%field)) then\n       deallocate(current%field)\n       nullify(current%field)\n    endif\n\n    ! First, check if a post buffer matches the current date.\n    if (post%hdate == current%hdate) then\n       ! The post buffer matches the current date.  This is the data we want.\n\n       call copy_data_buffer(current, post)\n       if (associated(prev%field)) deallocate(prev%field)\n       call copy_data_buffer(prev, post)\n\n       deallocate(post%field)\n       nullify(post%field)\n       post%hdate = \"0000-00-00_00:00:00\"\n       return\n    endif\n\n    ! Next, search for a GRIB file matching the current date.\n\n    teststring = upcase(current%flnm_template(1))\n    teststring = unblank(teststring)\n\n    if ( teststring(1:9) == \"CONSTANT:\") then\n       read(teststring(10:),*) xval\n       allocate(current%field(idim,jdim))\n       current%field = xval\n       select case ( current%label )\n       case (\"WEASD\")\n          current%units = \"kg/m^2\"\n          current%layer1 = -1.E36\n          current%layer2 = -1.E36\n       case (\"CANWAT\")\n          current%units = \"kg/m^2\"\n          current%layer1 = -1.E36\n          current%layer2 = -1.E36\n       case (\"SKINTEMP\")\n          current%units = \"K\"\n          current%layer1 = -1.E36\n          current%layer2 = -1.E36\n       case (\"STEMP_1\")\n          current%units = \"K\"\n          current%layer1 = 0.0\n          current%layer2 = 0.1\n       case (\"STEMP_2\")\n          current%units = \"K\"\n          current%layer1 = 0.1\n          current%layer2 = 0.4\n       case (\"STEMP_3\")\n          current%units = \"K\"\n          current%layer1 = 0.4\n          current%layer2 = 1.0\n       case (\"STEMP_4\")\n          current%units = \"K\"\n          current%layer1 = 1.0\n          current%layer2 = 2.0\n       case (\"SMOIS_1\")\n          current%units = \"m^3/m^3\"\n          current%layer1 = 0.0\n          current%layer2 = 0.1\n       case (\"SMOIS_2\")\n          current%units = \"m^3/m^3\"\n          current%layer1 = 0.1\n          current%layer2 = 0.4\n       case (\"SMOIS_3\")\n          current%units = \"m^3/m^3\"\n          current%layer1 = 0.4\n          current%layer2 = 1.0\n       case (\"SMOIS_4\")\n          current%units = \"m^3/m^3\"\n          current%layer1 = 1.0\n          current%layer2 = 2.0\n       case default\n          write(*,'(\"Constant field not allowed for field \",A)') trim(current%label)\n          stop \"FATAL ERROR: Constant field not allowed for field\"\n       end select\n\n       return\n    endif\n\n    call grib_file_search_now(current, datastruct, ierr)\n\n    if (ierr == 0) then\n\n       !\n       ! Attempt to fill in masked-out data in the original data array.\n       !\n\n       if(expand_loop > 0) call expand_9pt_input(datastruct%data,datastruct%nx, datastruct%ny, expand_loop)\n\n       ! If this is air temperature data, we need to adjust to sea-level:\n       ! This will later be adjusted back to the destination surface elevation.\n       if (current%label == \"T2D\") then\n          ! Get the source model terrain data file.\n          Zcurrent%hdate = current%hdate\n          call grib_file_search_now(Zcurrent, Zdatastruct, ierr)\n          if (ierr /= 0) then\n             stop \"FATAL ERROR: Source model terrain data not found\"\n          endif\n\n          if ( .not. check_if_same_map(datastruct, Zdatastruct) ) then\n             stop \"FATAL ERROR: 1) Source model terrain dimensions do not match source model temperature dimensions\"\n          endif\n\t  where(Zdatastruct%data < 0.0) Zdatastruct%data = 0.0   ! Barlage 20140529\n          datastruct%data = datastruct%data - ( -0.0065 * Zdatastruct%data )\n          deallocate(Zdatastruct%data)\n          nullify(Zdatastruct%data)\n       endif\n\n       ! If this field is soil temperature or moisture, fill in some water points\n       ! with a smooth expansion of the land-point data.  We do this\n       ! so that interpolation can be a little more sane.\n       if ( (current%label(1:6) == \"STEMP_\") .or. (current%label(1:6) == \"SMOIS_\") ) then\n          ! Get the source model Land/Sea mask data.\n          LANDSEA%hdate = current%hdate\n          call grib_file_search_now(LANDSEA, LANDSEAdatastruct, ierr)\n          if (ierr /= 0) then\n             print*, \"Source model land/sea data not found; assuming a bitmap exists\"\n\t     LANDSEAdatastruct%data = -1   ! Initialize LS mask to -1, if not available we assume bitmap Barlage\n\t  else\n             where(LANDSEAdatastruct%data == 0) datastruct%data = -1e36\n             deallocate(LANDSEAdatastruct%data)\n          endif\n! Barlage 20140529: comment the following and use expand_9pt to deal with missing values\n!          call fillsm(datastruct%data, (LANDSEAdatastruct%data /= 0), datastruct%nx, datastruct%ny)\n\n          where(datastruct%data < 0) datastruct%data = -1e36   ! This used for bitmap data Barlage 20150520\n\n! Barlage 20140529: the following will probably do an additional expansion, but it won't hurt\n          call expand_9pt_input(datastruct%data,datastruct%nx, datastruct%ny, expand_loop)\n          nullify(LANDSEAdatastruct%data)\n       endif\n\n       ! remap the datastruct data to the model grid\n       if (current%label == \"RAINRATE\") then\n          allocate(current%field(idim, jdim))\n          if (rainfall_interp == 0) then\n             call interp_rainfall_nearest_neighbor(datastruct, current%field, geo_em%idim, geo_em%jdim, geo_em)\n          else if (rainfall_interp == 1) then\n             call interp_rainfall(datastruct, current%field, geo_em%idim, geo_em%jdim, geo_em)\n             ! call another_interp_rainfall(datastruct, current%field, geo_em%idim, geo_em%jdim, geo_em)\n          endif\n       else\n          ! This remap function allocates current%field and fills it.\n          call remap(datastruct, geo_em, current)\n       endif\n       deallocate(datastruct%data)\n       nullify(datastruct%data)\n\n! Barlage 20140529: comment the following\n!       if ( (current%label(1:6) == \"STEMP_\") .or. (current%label(1:6) == \"SMOIS_\") ) then\n!          where (geo_em%use == geo_em%iswater) current%field=-1.E36\n!       endif\n\n       ! Make the current data available as previous data, in preparation for the next time step.\n       if (associated(prev%field)) deallocate(prev%field)\n       call copy_data_buffer(prev, current)\n\n       ! Clear post\n       if (associated(post%field)) then\n          deallocate(post%field)\n          nullify(post%field)\n       endif\n       post%hdate = \"0000-00-00_00:00:00\"\n\n       ! We've got the data we wanted, so get out of here.\n       return\n\n    endif\n\n    ! We did not find data.  Let's try to temporally interpolate.\n\n    ! A \"prev\" buffer must exist for us.  Check that.\n\n    if (prev%hdate ==  \"0000-00-00_00:00:00\") then\n\n       if (current%fatality == 2) then\n          allocate(current%field(idim, jdim))\n          current%field = -1.E36\n          write(*,'(13x, \":  Prior data missing for \", A, \".  Returning missing-data field.\")') &\n               trim(current%label)\n          return\n       endif\n\n       write(*,'(\"Field label= \",A)') trim(current%label)\n       write(*,'(\"No previous data.\")')\n       stop \"FATAL ERROR: No previous data\"\n    endif\n\n    ! The \"prev\" buffer must be recent.  Check that\n    call geth_idts (current%hdate, prev%hdate, idts)\n    if (idts > 43200) then\n\n       if (current%fatality == 2) then\n          allocate(current%field(idim, jdim))\n          current%field = -1.E36\n          if (associated(prev%field)) then\n             deallocate(prev%field)\n             nullify(prev%field)\n          endif\n          prev%hdate = \"0000-00-00_00:00:00\"\n          write(*,'(13x, \":  Prior data is out-of-date for \", A, \".  Returning missing-data field.\")') &\n               trim(current%label)\n          return\n       endif\n\n       write(*,'(\"Previous data is out of date.\")')\n       stop \"FATAL ERROR: Previous data is out of date\"\n    endif\n\n    ! Check for a \"post\" buffer.\n\n    if (post%hdate > current%hdate) then\n       call geth_idts(post%hdate, prev%hdate, idts)\n       if (idts > 43200) then\n\n          if (current%fatality == 2) then\n             allocate(current%field(idim, jdim))\n             current%field = -1.E36\n             if (associated(prev%field)) then\n                deallocate(prev%field)\n                nullify(prev%field)\n             endif\n             prev%hdate = \"0000-00-00_00:00:00\"\n             write(*,'(13x, \":  Time range for interpolation of \", A, \" is too large.  \",&\n                  &\"Returning missing-data field.\")') &\n                  trim(current%label)\n             return\n          endif\n          stop\n       endif\n\n       if (current%label == \"RAINRATE\") then\n          ! Don't temporally interpolate the rain rate.\n          allocate(current%field(size(prev%field,1), size(prev%field,2)))\n          ! Take the \"post\" field, because that field should be the accumulation\n          ! between \"prev\" and \"post\"\n          current%field = post%field\n       else\n          call temporal_interpolation(prev, post, current)\n       endif\n       ! We have the data we want, so we can exit.\n       return\n    endif\n\n    ! No post buffer, so we must read some new data into a post buffer\n\n    call grib_file_search_future(current, post, datastruct, ierr)\n\n    if (ierr /= 0) then\n\n       if (current%fatality == 2) then\n          allocate(current%field(idim, jdim))\n          current%field = -1.E36\n          if (associated(prev%field)) then\n             deallocate(prev%field)\n             nullify(prev%field)\n          endif\n          prev%hdate = \"0000-00-00_00:00:00\"\n          write(*,'(13x, \":  No later data for interpolation of \", A, \".  Returning missing-data field.\")') &\n               trim(current%label)\n          return\n       endif\n\n       write(*,'(\"We could not find later data to interpolate\")')\n       stop \"FATAL ERROR: Could not find later data to interpolate\"\n    endif\n\n    ! If this is air temperature data, we need to adjust to sea-level:\n    ! This will later be adjusted back to the destination surface elevation.\n    if (current%label == \"T2D\") then\n       ! Get the source model terrain data file.\n       Zcurrent%hdate = post%hdate\n       call grib_file_search_now(Zcurrent, Zdatastruct, ierr)\n       if (ierr /= 0) then\n          stop \"FATAL ERROR: Source model terrain data not found\"\n       endif\n       if ( .not. check_if_same_map(datastruct, Zdatastruct) ) then\n          stop \"FATAL ERROR: 2) Source model terrain dimensions do not match source model temperature dimensions\"\n       endif\n       where(Zdatastruct%data < 0.0) Zdatastruct%data = 0.0   ! Barlage 20140529\n       datastruct%data = datastruct%data - ( -0.0065 * Zdatastruct%data )\n       deallocate(Zdatastruct%data)\n       nullify(Zdatastruct%data)\n    endif\n\n    ! remap the datastruct data to the model grid\n\n    ! This remap function allocates post%field and fills it.\n    call remap(datastruct, geo_em, post)\n    deallocate(datastruct%data)\n    nullify(datastruct%data)\n\n    if (current%label == \"RAINRATE\") then\n       ! Don't temporally interpolate the rain rate.\n       ! Simply carry the previous value forward.\n       allocate(current%field(size(prev%field,1), size(prev%field,2)))\n       current%field = post%field\n    else\n       call temporal_interpolation(prev, post, current)\n    endif\n\n    ! We have the data we want, and prev and post are both up-to-date,\n    ! so we can exit.\n\n  end subroutine process\n\n!==============================================================================\n!==============================================================================\n\n  subroutine expand_9pt_input(data, nx, ny, maxloop)\n\n  ! This routine checks for missing data in the input forcing and\n  !  expands using a 9pt average; Added to deal with input data such\n  !  as NLDAS which doesn't have any values over water\n\n    implicit none\n    integer,                    intent(in)      :: nx\n    integer,                    intent(in)      :: ny\n    real,    dimension(nx, ny), intent(inout)   :: data\n    integer,                    intent(in)      :: maxloop\n\n    integer :: i, k, ilo, ihi, klo, khi, loop, testnum\n    real, dimension(nx,ny) :: hold\n\n    do loop = 1, maxloop\n       hold = data\n       do i = 1, nx\n          do k = 1, ny\n             if (hold(i,k) < -1e10 ) then\n                ilo = max( 1,i-1)\n                ihi = min(nx,i+1)\n                klo = max( 1,k-1)\n                khi = min(ny,k+1)\n                testnum = count(hold(ilo:ihi,klo:khi) > -1e10)\n                if(testnum > 0) then\n                   data(i,k) = sum(hold(ilo:ihi,klo:khi), hold(ilo:ihi,klo:khi) > -1e10)/testnum\n                endif\n             endif\n          enddo\n       enddo\n    enddo\n\n  end subroutine expand_9pt_input\n\n!==============================================================================\n!==============================================================================\n\n  subroutine remap(datastruct, geo_em, buff)\n    use module_input_data_structure\n    implicit none\n    type(input_data_type), intent(in)  :: datastruct\n    type (geo_em_type), intent(in) :: geo_em\n    type(DataBuffer), intent(inout)  :: buff\n\n    integer :: i, j\n    integer :: idim, jdim\n    real, allocatable, dimension(:,:) :: etax, etay\n    real :: east_longitude\n\n    buff%layer1 = datastruct%layer1\n    buff%layer2 = datastruct%layer2\n\n    idim = geo_em%idim\n    jdim = geo_em%jdim\n    allocate(buff%field(idim,jdim))\n    allocate(etax(idim,jdim))\n    allocate(etay(idim,jdim))\n\n    do i = 1, idim\n       do j = 1, jdim\n#if 0\n!Removed, because this seemed to break some grids.\n          ! Lon must be between 0 and 360 E\n          if (geo_em%lon(i,j) < 0) then\n             east_longitude = geo_em%lon(i,j) + 360.\n          else\n             east_longitude = geo_em%lon(i,j)\n          endif\n          call latlon_to_ij(datastruct%proj, geo_em%lat(i,j), east_longitude, etax(i,j), etay(i,j))\n#else\n          call latlon_to_ij(datastruct%proj, geo_em%lat(i,j), geo_em%lon(i,j), etax(i,j), etay(i,j))\n#endif\n\n          if (buff%remap_type==\"bint\") then\n             buff%field(i,j) = bint_p(datastruct%data, datastruct%nx, datastruct%ny, etax(i,j), etay(i,j))\n          else if (buff%remap_type == \"4pt\") then\n             buff%field(i,j) = four_point_p(datastruct%data, datastruct%nx, datastruct%ny, etax(i,j), etay(i,j))\n          else if (buff%remap_type == \"16pt\") then\n             buff%field(i,j) = wt_sixteen_pt_average(datastruct%data, datastruct%nx, datastruct%ny, &\n\t                                 etax(i,j), etay(i,j),-1E+36,-1E+36)\n          else\n             print*, \"'\"//trim(buff%remap_type)//\"'\"\n             stop \"FATAL ERROR: remap type\"\n          endif\n\n       enddo\n    enddo\n    deallocate(etax)\n    deallocate(etay)\n\n\n  end subroutine remap\n\n!==============================================================================\n!==============================================================================\n\n  subroutine grib_file_search_future(current, post, datastruct, ierr)\n    use module_input_data_structure\n    implicit none\n    type(DataBuffer), intent(inout) :: current\n    type(DataBuffer), intent(inout) :: post\n    type(input_data_type), intent(out) :: datastruct\n    integer, intent(out) :: ierr\n\n    character(len=13) :: kdate\n    integer :: i, j\n    character(len=256) :: flnm\n\n    logical :: lexist\n\n    nullify(datastruct%data)\n\n    ierr = 1\n    kdate = current%hdate(1:13)\n\n    DATE_SEEK_LOOP : do i = 1, 12\n\n       TEMPLATE_LOOP : do j = 1, MAXTEMPLATE\n          if (current%flnm_template(j) /= \" \") then\n             flnm = current%flnm_template(j)\n\n             call fill_template(flnm, kdate)\n\n             write(*,'(A)') \"             \"//\":  Checking for file '\"//trim(flnm)//\"'\"\n\n             inquire(file=trim(flnm), exist=lexist)\n             if ( .not. lexist ) then\n                inquire(file=trim(flnm)//\".bz2\", exist=lexist)\n                if (lexist) then\n                   flnm = trim(flnm)//\".bz2\"\n                endif\n             endif\n\n             if (lexist) then\n                write(*,'(A)') \"             \"//\":  Found file \"//trim(flnm)\n                ierr = 0\n                exit DATE_SEEK_LOOP\n             endif\n          endif\n       enddo TEMPLATE_LOOP\n\n       call geth_newdate(kdate, kdate, 1)\n\n    enddo DATE_SEEK_LOOP\n\n    ! If we haven't found any matching data yet, then get out of here.\n    if (ierr == 1) return\n\n    call get_single_datastruct_from_grib(trim(flnm), kdate, datastruct, ierr)\n    post%hdate = kdate//\":00:00\"\n    post%units = datastruct%units\n\n  end subroutine grib_file_search_future\n\n!==============================================================================\n!==============================================================================\n\n  subroutine grib_file_search_now(current, datastruct, ierr)\n    use module_input_data_structure\n    implicit none\n    type(DataBuffer), intent(inout)  :: current\n    type(input_data_type), intent(out) :: datastruct\n    integer, intent(out) :: ierr\n    character(len=256) :: flnm\n    logical :: lexist\n    integer :: j\n    character(len=13) :: kdate\n\n    kdate = current%hdate(1:13)\n\n    ierr = 1\n\n    TEMPLATE_LOOP : do j = 1, MAXTEMPLATE\n       if (current%flnm_template(j) /= \" \") then\n          flnm = current%flnm_template(j)\n\n          call fill_template(flnm, kdate)\n\n          write(*,'(A)') \"             \"//\":  Checking for file '\"//trim(flnm)//\"'\"\n\n          inquire(file=trim(flnm), exist=lexist)\n          if ( .not. lexist ) then\n             inquire(file=trim(flnm)//\".bz2\", exist=lexist)\n             if (lexist) then\n                flnm = trim(flnm)//\".bz2\"\n             endif\n          endif\n\n          if (lexist) then\n             write(*,'(A)') \"             \"//\":  Found file \"//trim(flnm)\n             ierr = 0\n             exit TEMPLATE_LOOP\n          endif\n       endif\n    enddo TEMPLATE_LOOP\n    if (ierr == 1) return\n\n    nullify(datastruct%data)  ! Barlage: move from above\n\n    call get_single_datastruct_from_grib(trim(flnm), kdate, datastruct, ierr)\n    current%units = datastruct%units\n\n    if ( current%label /= datastruct%field ) then\n       write(*,'(/,1x,80(\"*\"))')\n       write(*,'(\" *****  PROBLEM:  Requested field name does not match the name in the Vtable entry.\")')\n       write(*,'(\" ***** \")')\n       write(*,'(\" *****      Requested field name: ''\",A,\"''\")') trim(current%label)\n       write(*,'(\" *****      Field name in the Vtable entry:  ''\",A,\"''\")') trim(datastruct%field)\n       write(*,'(\" ***** \")')\n       write(*,'(\" *****  Please check your VTable entries and filename templates in your namelist\")')\n       write(*,'(\" *****  to be sure you are getting the fields you think you are getting.\")')\n       write(*,'(1x,80(\"*\"),/)')\n       stop\n    endif\n\n  end subroutine grib_file_search_now\n\n!==============================================================================\n!==============================================================================\n\n  subroutine temporal_interpolation(prev, post, current)\n    implicit none\n    type(DataBuffer), intent(in) :: prev\n    type(DataBuffer), intent(in) :: post\n    type(DataBuffer), intent(inout) :: current\n\n    integer :: xdiff\n    integer :: tdiff\n    real    :: fraction\n\n    call geth_idts(current%hdate, prev%hdate, xdiff)\n    call geth_idts(post%hdate, prev%hdate, tdiff)\n\n    fraction = real(xdiff)/real(tdiff)\n\n    allocate(current%field(size(prev%field,1), size(prev%field,2)))\n    current%field = (prev%field)*(1.0-fraction) + (post%field)*(fraction)\n\n!KWM    if (prev%layer1 /= post%layer1) then\n!KWM       print*, 'prev%layer1  = ', prev%layer1\n!KWM       print*, 'post%layer1  = ', post%layer1\n!KWM       stop \"layer1 mismatch\"\n!KWM    endif\n!KWM    if (prev%layer2 /= post%layer2) then\n!KWM       print*, 'prev%layer2  = ', prev%layer2\n!KWM       print*, 'post%layer2  = ', post%layer2\n!KWM       stop \"layer2 mismatch\"\n!KWM    endif\n!KWM    current%layer1 = prev%layer1\n!KWM    current%layer2 = prev%layer2\n\n  end subroutine temporal_interpolation\n\n!==============================================================================\n!==============================================================================\n\n  subroutine output_databuffer(ncid, buff)\n    implicit none\n    integer,              intent(in) :: ncid\n    type (DataBuffer),    intent(in) :: buff\n    ! Wrapper around call to output_to_netcdf\n    call output_to_netcdf(ncid, buff%label, buff%units, buff%field, &\n         size(buff%field,1), size(buff%field,2))\n  end subroutine output_databuffer\n\n!==============================================================================\n!==============================================================================\n\n  subroutine get_single_datastruct_from_grib(gribflnm, kdate, datastruct, ierr)\n    use module_grib\n    use kwm_string_utilities\n    use module_input_data_structure\n    implicit none\n    character(len=*), intent(in) :: gribflnm, kdate\n    type(input_data_type), intent(out) :: datastruct\n    integer, intent(out) :: ierr\n\n    character(len=256) :: flnm\n    integer(kind=8) :: gribunit\n    integer :: istat\n\n    !-------------------------------------------------------------------------\n    nullify(datastruct%data)\n\n    flnm = gribflnm\n\n    call fill_template(flnm, kdate)\n\n    ! Open the unit and read the first GRIB record\n    call gribopen(flnm, gribunit, ierr);\n    if (ierr /= 0) then\n       if (ierr == 2) then\n          write(*, '(\"File does not exist: \",A)') trim(flnm)\n       else\n          write(*, '(\"Undetermined problem opening file: \", A)') trim(flnm)\n       endif\n       return\n       stop \"FATAL ERROR: get_single_datastruct_from_grib\"\n    endif\n    if (associated(datastruct%data)) then\n       deallocate(datastruct%data)\n       nullify(datastruct%data)\n    endif\n    call read_grib_unit(gribunit, datastruct, ierr, trim(flnm))\n    if (ierr /= 0) then\n       print*, 'Returning error flag from get_single_datastruct_from_grib (1)'\n       print*, 'gribunit = ', gribunit\n       print*, 'flnm = ', trim(flnm)\n       print*, 'ierr = ', ierr\n       if (associated(datastruct%data)) then\n          deallocate(datastruct%data)\n          nullify(datastruct%data)\n       endif\n       return\n    endif\n    call gribclose(gribunit)\n\n  end subroutine get_single_datastruct_from_grib\n\n!==============================================================================\n!==============================================================================\n\n  subroutine read_grib_unit(nunit, datastruct, ierr, info)\n    use module_grib\n    use module_input_data_structure\n    implicit none\n    integer(kind=8), intent(in) :: nunit\n    type(input_data_type), intent(out) :: datastruct\n    integer :: ierr, i, j\n    real :: rb, xdum\n    real :: oldmax\n    real :: newmax\n    integer :: astat\n    character(len=*), intent(in), optional :: info\n\n    type(GribStruct)  :: grib\n    character(len=64)  :: name\n    character(len=256) :: units\n    character(len=256) :: description\n\n    ! Returned from grib_level_information\n    character(len=256) :: level_type\n    character(len=256) :: level_units\n    real               :: level_value\n    real               :: level2_value\n\n    ! Returned from grib_time_information\n    character(len=19)  :: reference_date\n    character(len=19)  :: valid_date\n    character(len=256) :: process\n    character(len=256) :: processing\n    integer            :: p1_seconds\n    integer            :: p2_seconds\n\n    real, parameter :: grrth = 6370.949\n    real, external  :: tand\n    real, external  :: sind\n    real, external  :: cosd\n\n    !\n    ! Get a grib field, unpacking all header information.\n    !\n    nullify(grib%buffer)\n    nullify(grib%bitmap)\n    nullify(grib%array)\n    nullify(grib%sec7%floated)\n    nullify(datastruct%data)\n\n    call grib_next_field(nunit, grib, ierr)\n    if (ierr /= 0) then\n       write(*, '(\"Returning error from read_grib_unit:  nunit = \", I3, \"  ierr = \", I3)') nunit, ierr\n       if (present(info)) print*, info\n       return\n    endif\n\n    !\n    ! Match the grib record we've just read with one of our grib table entries.\n    !\n    if (grib%edition == 1) then\n       G1SEARCH : do j = 1, vtable_count\n          if ( (grib%g1sec1%parameter == vtable(j)%g1_parm) .and. &\n               (grib%g1sec1%leveltyp  == vtable(j)%g1_levtyp) .and. &\n               (grib%g1sec1%levelval  == vtable(j)%level1) ) then\n             if ( (grib%g1sec1%level2val  == vtable(j)%level2) .or. &\n                  (grib%g1sec1%level2val < -1.E25) .or. &\n                  (vtable(j)%level2 == 999) ) then\n                ! print*, 'Parameter match:  ', &\n                !      grib%g1sec1%parameter, grib%g1sec1%leveltyp, grib%g1sec1%levelval, grib%g1sec1%level2val\n                datastruct%field  = vtable(j)%name\n                datastruct%desc   = vtable(j)%desc\n                datastruct%units  = vtable(j)%units\n                write(*, '(A, \"  GRIB Editon 1\")') datastruct%field\n                exit G1SEARCH\n             endif\n          endif\n          if (j == vtable_count) then\n             write(*,'(/,\" ***** ERROR *****\")')\n             write(*,'(\" *****       GRIB Edition 1 data does not match a Vtable entry\")')\n             print*, grib%g1sec1%parameter, grib%g1sec1%leveltyp, grib%g1sec1%levelval, grib%g1sec1%level2val\n             stop \"FATAL ERROR: GRIB Edition 1 data does not match a Vtable entry\"\n          endif\n       enddo G1SEARCH\n    else if (grib%edition == 2) then\n       G2SEARCH : do j = 1, vtable_count\n          if ( (grib%discipline == vtable(j)%g2_discp) .and. &\n               (grib%sec4%parameter_category == vtable(j)%g2_cat) .and. &\n               (grib%sec4%parameter_number == vtable(j)%g2_parm) .and. &\n               (grib%sec4%ltype1  == vtable(j)%g2_levtyp) .and. &\n               (grib%sec4%lvalue1  == vtable(j)%level1) ) then\n             if ( (grib%sec4%lvalue2  == vtable(j)%level2) .or. &\n                  (grib%sec4%lvalue2 < -1.E25) .or. &\n                  (vtable(j)%level2 == 999) ) then\n                ! print*, 'Parameter match:  ', &\n                !      grib%discipline, grib%sec4%parameter_category, grib%sec4%ltype1, grib%sec4%lvalue1, grib%sec4%lvalue2\n                datastruct%field  = vtable(j)%name\n                datastruct%desc   = vtable(j)%desc\n                datastruct%units  = vtable(j)%units\n                write(*, '(A, \"  GRIB Editon 2\")') datastruct%field\n                exit G2SEARCH\n             endif\n          endif\n          if (j == vtable_count) then\n             write(*,'(/,\" ***** ERROR *****\")')\n             write(*,'(\" *****       GRIB Edition 2 data does not match a Vtable entry\")')\n             print*, grib%discipline, grib%sec4%parameter_category, grib%sec4%parameter_number, &\n                  grib%sec4%ltype1, grib%sec4%lvalue1, grib%sec4%lvalue2\n             stop \"FATAL ERROR: GRIB Edition 2 data does not match a Vtable entry\"\n          endif\n       enddo G2SEARCH\n    endif\n\n    call grib_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    datastruct%hdate = valid_date\n\n    datastruct%layer1 = -1.E36\n    datastruct%layer2 = -1.E36\n\n    description = \" \"\n\n! Barlage: is it necessary to read external grib tables? why not just read namelist table for this info 20150518\n!\n!    call grib_parameter_text_information(grib, name, units, description)\n! Barlage: move assignment up 20150518\n!    datastruct%desc   = description\n!    datastruct%units  = units\n\n    ! print*, 'description = \"' // trim(description) // '\"'\n\n    call grib_level_information(grib, level_type, level_units, level_value, level2_value)\n\n    datastruct%layer1 = level_value\n    datastruct%layer2 = level2_value\n\n    call grib_map_information(grib)\n\n    datastruct%nx = grib%mapinfo%nx\n    datastruct%ny = grib%mapinfo%ny\n\n    call map_init(datastruct%proj)\n!KWM    datastruct%proj%lat1 = grib%mapinfo%lat1\n!KWM    if (grib%mapinfo%lon1 > 180) then\n!KWM       datastruct%proj%lon1 = grib%mapinfo%lon1-360\n!KWM    else\n!KWM       datastruct%startlon = grib%mapinfo%lon1\n!KWM    endif\n\n    if (grib%mapinfo%hproj == \"CE\") then\n\n       call map_set(PROJ_LATLON, datastruct%proj, lat1=grib%mapinfo%lat1, lon1=grib%mapinfo%lon1, &\n            latinc=grib%mapinfo%dy, loninc=grib%mapinfo%dx, knowni=1.0, knownj=1.0)\n\n    else if (grib%mapinfo%hproj == \"LC\") then\n\n       call map_set(PROJ_LC, datastruct%proj, lat1=grib%mapinfo%lat1, lon1=grib%mapinfo%lon1, &\n            knowni=1.0, knownj=1.0, truelat1=grib%mapinfo%truelat1, truelat2=grib%mapinfo%truelat2, &\n            stdlon=grib%mapinfo%xlonc, dx=grib%mapinfo%dx*1.E3)\n\n    else if (grib%mapinfo%hproj == \"ST\") then\n\n       call map_set(PROJ_PS, datastruct%proj, lat1=grib%mapinfo%lat1, lon1=grib%mapinfo%lon1, truelat1=grib%mapinfo%truelat1, &\n            knowni=1.0, knownj=1.0, stdlon=grib%mapinfo%xlonc, dx=grib%mapinfo%dx*1.E3)\n\n    else\n\n       write(*,'(\"Unrecognized grib%mapinfo%hproj:  \", A2)') grib%mapinfo%hproj\n       stop \"FATAL ERROR: Unrecognized grib mapinfo hproj\"\n\n    endif\n\n    if (associated(datastruct%data)) then\n       deallocate(datastruct%data)\n       nullify(datastruct%data)\n    endif\n    allocate(datastruct%data(datastruct%nx,datastruct%ny), stat=astat)\n    if (astat /= 0) stop \"FATAL ERROR: Problem (A) allocating datastruct%data\"\n\n    call gribdata(grib)\n    datastruct%data = grib%array\n    call deallogrib(grib)\n\n    ! If the data are from GCIP SRB archives, they're at 15 minutes off the hour.\n    ! Ignore that 15-minute offset in that case, and put the date right on the hour.\n\n    if (datastruct%field == \"SWDOWN\") then\n       if (rescale_shortwave) then\n          call rescale_sw_time_offset(datastruct)\n       endif\n       datastruct%hdate(15:16) = \"00\"\n       ! TEST:  Set zero data values to missing data for GCIP SW fields\n       ! where (datastruct%data <= 0) datastruct%data = -1.E36\n    endif\n\n!MB: want mm units in v3.7\n!KWM    if (description == \"Plant Canopy Surface Water\") then\n!    if (datastruct%field == \"CANWAT\") then\n!       ! Convert canwat from kg m{-2} (that is, mm) to m\n!       datastruct%data = datastruct%data * 1.E-3\n!       datastruct%units = \"m\"\n!    endif\n\n    if (datastruct%field(1:6) == \"SMOIS_\") then\n       ! If units are kg m{-2} (that is, mm), convert to volumetric\n     if ( (datastruct%units == \"kg/m^2\") .or. (datastruct%units == \"mm\") ) then\n       write(*,*) \"Converting soil water content to volumetric using thickness[m]: \", &\n           (datastruct%layer2 - datastruct%layer1)\n       datastruct%data = datastruct%data * 1.E-3 / (datastruct%layer2 - datastruct%layer1)\n       datastruct%units = \"m^3/m^3\"\n     elseif (datastruct%units == \"gldas\") then  ! hack to take care of bad units in GLDAS MBv3.7\n       if(datastruct%field(1:7) == \"SMOIS_1\") datastruct%layer1 = 0\n       if(datastruct%field(1:7) == \"SMOIS_1\") datastruct%layer2 = 0.1\n       if(datastruct%field(1:7) == \"SMOIS_2\") datastruct%layer1 = 0.1\n       if(datastruct%field(1:7) == \"SMOIS_2\") datastruct%layer2 = 0.4\n       if(datastruct%field(1:7) == \"SMOIS_3\") datastruct%layer1 = 0.4\n       if(datastruct%field(1:7) == \"SMOIS_3\") datastruct%layer2 = 1.0\n       if(datastruct%field(1:7) == \"SMOIS_4\") datastruct%layer1 = 1.0\n       if(datastruct%field(1:7) == \"SMOIS_4\") datastruct%layer2 = 2.0\n       write(*,*) \"Converting soil water content to volumetric using thickness[m]: \", &\n           (datastruct%layer2 - datastruct%layer1)\n       datastruct%data = datastruct%data * 1.E-3 / (datastruct%layer2 - datastruct%layer1)\n       datastruct%units = \"m^3/m^3\"\n     endif\n    endif\n\n    ! print*, 'Description = \"'//trim(description)//'\"'\n    ! if (description == \"Total precipitation\") then\n    if (datastruct%field == \"RAINRATE\") then\n       ! print*, 'datastruct%units = ', datastruct%units\n       ! Convert from kg/m^2 (that is, mm) in <nn> hours to mm/s\n       if ( (datastruct%units == \"kg/m^2\") .or. (datastruct%units == \"mm\") ) then\n!KWM          print*, 'Time information:  '\n!KWM          print*, '                   Reference Date ' // reference_date\n!KWM          print*, '                   Reference Date ' // valid_date\n!KWM          print*, '                                  ' // trim(process)\n!KWM          print*, '                                  ' // trim(processing)\n!KWM          print*, '                               P1 ', p1_seconds\n!KWM          print*, '                               P2 ', p2_seconds\n          if (processing(1:12) == \"Accumulation\") then\n             oldmax = maxval(datastruct%data, mask=(datastruct%data > -1.E25))\n             write(*,'(13x, \"Maxval adjusted from \", F12.6)', advance=\"no\") oldmax\n             where (datastruct%data > -1.E25)\n                datastruct%data = datastruct%data * (1.0 / float(p2_seconds - p1_seconds))\n             endwhere\n             newmax = maxval(datastruct%data, mask=(datastruct%data > -1.E25))\n             write(*,'(\" to \", F12.6, \":    factor of \", I8)') newmax, NINT(oldmax/newmax)\n             ! Change the units to mm/s, reflecting the rescaling we just did.\n             datastruct%units = \"mm/s\"\n          else\n             stop \"FATAL ERROR: Precip Problem A?\"\n          endif\n       elseif ( (datastruct%units == \"kg/m^2/s\") ) then ! For example, GLDAS; MB v3.7\n          datastruct%units = \"mm/s\"\n       else\n          stop \"FATAL ERROR: Precip Problem B?\"\n       endif\n    endif\n\n  end subroutine read_grib_unit\n\n!==============================================================================\n!==============================================================================\n\n  logical function check_if_same_map(A, B) result (lval)\n    ! Check two DATASTRUCT structures to see if they have the same grid/map.\n    use module_input_data_structure\n    implicit none\n    type(input_data_type), intent(in) :: A\n    type(input_data_type), intent(in) :: B\n\n    lval = .TRUE.\n\n    if (A%proj%code /= B%proj%code)    lval = .FALSE.\n    if (A%nx       /= B%nx)       lval = .FALSE.\n    if (A%ny       /= B%ny)       lval = .FALSE.\n    if (abs(A%proj%lat1 - B%proj%lat1) > 1.E-4) lval = .FALSE.\n    if (abs(A%proj%lon1 - B%proj%lon1) > 1.E-4) lval = .FALSE.\n    if ((A%proj%latinc > -1.E25) .and. (B%proj%latinc > -1.E25)) then\n       if (abs(A%proj%latinc - B%proj%latinc) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%loninc > -1.E25) .and. (B%proj%loninc > -1.E25)) then\n       if (abs(A%proj%loninc - B%proj%loninc) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%dx > -1.E25) .and. (B%proj%dx > -1.E25)) then\n       if (abs(A%proj%dx - B%proj%dx) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%dy > -1.E25) .and. (B%proj%dy > -1.E25)) then\n       if (abs(A%proj%dy - B%proj%dy) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%stdlon > -1.E25) .and. (B%proj%stdlon > -1.E25)) then\n       if (abs(A%proj%stdlon  - B%proj%stdlon) > 1.E-4)   lval = .FALSE.\n    endif\n    if ((A%proj%truelat1 > -1.E25) .and. (B%proj%truelat1 > -1.E25)) then\n       if (abs(A%proj%truelat1 - B%proj%truelat1) > 1.E-4) lval = .FALSE.\n    endif\n    if ((A%proj%truelat2 > -1.E25) .and. (B%proj%truelat2 > -1.E25)) then\n       if (abs(A%proj%truelat2 - B%proj%truelat2) > 1.E-4) lval = .FALSE.\n    endif\n\n    if (.not. lval) then\n       write(*, '(\"CHECK_IF_SAME_MAP:\")')\n       write(*, '(\"     proj_code= \", I12, I12)') A%proj%code, B%proj%code\n       write(*, '(\"     nx       = \", I12, I12)') A%nx, B%nx\n       write(*, '(\"     ny       = \", I12, I12)') A%ny, B%ny\n       write(*, '(\"     startlat = \", F20.12, F20.12)') A%proj%lat1, B%proj%lat1\n       write(*, '(\"     startlon = \", F20.12, F20.12)') A%proj%lon1, B%proj%lon1\n       write(*, '(\"     deltalat = \", F20.12, F20.12)') A%proj%latinc, B%proj%latinc\n       write(*, '(\"     deltalon = \", F20.12, F20.12)') A%proj%loninc, B%proj%loninc\n       write(*, '(\"     dx       = \", F20.12, F20.12)') A%proj%dx, B%proj%dx\n       write(*, '(\"     dy       = \", F20.12, F20.12)') A%proj%dy, B%proj%dy\n       write(*, '(\"     xlonc    = \", F20.12, F20.12)') A%proj%stdlon, B%proj%stdlon\n       write(*, '(\"     truelat1 = \", F20.12, F20.12)') A%proj%truelat1, B%proj%truelat1\n       write(*, '(\"     truelat2 = \", F20.12, F20.12)') A%proj%truelat2, B%proj%truelat2\n    endif\n\n  end function check_if_same_map\n\n!==============================================================================\n!==============================================================================\n\nend program create_forcing\n\n!==============================================================================\n!==============================================================================\n\nsubroutine interpolate_vegetation(name, date, idim, jdim, vegin, vegout)\n  implicit none\n  character(len=*),              intent(in)  :: name\n  character(len=*),              intent(in)  :: date\n  integer,                       intent(in)  :: idim, jdim\n  real, dimension(idim,jdim,12), intent(in)  :: vegin\n  real, dimension(idim,jdim)   , intent(out) :: vegout\n\n  integer :: imo\n  integer :: imo2\n  integer :: imody\n  real, allocatable, dimension(:,:) :: xdum, xdum2\n\n  integer, parameter, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n\n  ! Vegetation Fraction field\n\n  read(date(6:10), '(I2,1x,I2)') imo, imody\n\n  if (imody == 15) then\n     vegout = vegin(:,:,imo)\n  else if (imody > 15) then\n     allocate(xdum(idim,jdim), xdum2(idim,jdim))\n     xdum  = vegin(:,:,imo)\n     xdum2 = vegin(:,:,mod(imo,12)+1)\n     vegout = xdum + float(imody-15)/float(mday(imo))*(xdum2-xdum)\n     deallocate(xdum, xdum2)\n  else if (imody < 15) then\n     allocate(xdum(idim,jdim), xdum2(idim,jdim))\n     xdum2  = vegin(:,:,imo)\n     if (imo == 1) then\n        imo2 = 12\n     else\n        imo2 = imo - 1\n     endif\n     xdum   = vegin(:,:,imo2)\n\n     vegout = xdum + float(mday(imo2)-(15-imody)) / float(mday(imo2)) &\n          *(xdum2-xdum)\n     deallocate(xdum, xdum2)\n     if(trim(name) == \"VEGFRA\") then\n       where (vegout <= 0) vegout = 1.E-2 !???\n     end if\n  endif\nend subroutine interpolate_vegetation\n\n!==============================================================================\n!==============================================================================\n\nsubroutine fill_template(string, date)\n  use kwm_string_utilities\n  use kwm_date_utilities\n  implicit none\n  character(len=*), intent(inout) :: string\n  character(len=*), intent(in)    :: date\n\n  character(len=2)  :: hh\n  character(len=13) :: dd\n  character(len=3)  :: hnn\n  integer           :: nn\n  integer           :: idx\n\n  call strrep(string, \"<YYYY>\", date(1:4))\n  call strrep(string, \"<MM>\",   date(6:7))\n  call strrep(string, \"<DD>\",   date(9:10))\n  call strrep(string, \"<HH>\",   date(12:13))\n  call strrep(string, \"<date>\", date(1:4)//date(6:7)//date(9:10)//date(12:13))\n\n  !\n  ! Build the filenames for analyses in range 0-(minus)12h\n  !\n  if ( index(string, \"<init+12>\") > 0) then\n     hh = date(12:13)\n     if (hh == \"00\") then\n        dd = date\n     elseif (hh <= \"12\") then\n        dd=date(1:11)//\"12\"\n     else\n        dd=date(1:11)//\"00\"\n        call geth_newdate(dd, dd, 24)\n     endif\n     call strrep(string, \"<init+12>\", dd(1:4)//dd(6:7)//dd(9:10)//dd(12:13))\n  endif\n\n!\n!  Build the filenames for forecasts in ranges 0-12h, 12-24h, 24-36h, etc.\n!\n\n  idx = index(string, \"<init-\")\n  if (idx > 0) then\n     hnn = string(idx+5:idx+7)\n     read(hnn,*) nn\n     call geth_newdate(dd, date, (nn+12))\n     hh = dd(12:13)\n     if (hh == \"00\") then\n        call geth_newdate(dd, dd, -12)\n     elseif (hh <= \"12\") then\n        dd=dd(1:11)//\"00\"\n     else\n        dd=dd(1:11)//\"12\"\n     endif\n     call strrep(string, \"<init\"//hnn//\">\", dd(1:4)//dd(6:7)//dd(9:10)//dd(12:13))\n  endif\n\nend subroutine fill_template\n\n!==============================================================================\n!==============================================================================\n\nsubroutine open_netcdf_for_output(output_flnm, ncid, version, ix, jx, geo_em, init)\n  use module_geo_em\n  implicit none\n  character(len=*), intent(in) :: output_flnm\n  character(len=*), intent(in) :: version\n  integer, intent(in) :: ix, jx\n  integer, intent(out) :: ncid\n  type (geo_em_type), intent(in) :: geo_em\n  logical, intent(in) :: init\n\n  integer :: ierr, dimid\n  integer, parameter :: datestrlen = 19\n\n#ifdef _NETCDF4_COMPRESS_YES_\n      ierr = nf90_create(trim(output_flnm), NF90_HDF5, ncid)\n#else\n      ierr = nf90_create(trim(output_flnm), NF90_WRITE, ncid)\n#endif\n  call error_handler(ierr, \"Problem nf90_create: \"//trim(output_flnm))\n\n  ierr = nf90_def_dim(ncid, \"Time\", NF90_UNLIMITED, dimid)\n  call error_handler(ierr, \"Problem nf90_def_dim Time\")\n\n  ierr = nf90_def_dim(ncid, \"DateStrLen\", datestrlen, dimid)\n  call error_handler(ierr, \"Problem nf90_def_dim DateStrLen\")\n\n  ierr = nf90_def_dim(ncid, \"west_east\", ix, dimid)\n  call error_handler(ierr, \"Problem nf90_def_dim west_east\")\n\n  ierr = nf90_def_dim(ncid, \"south_north\", jx, dimid)\n  call error_handler(ierr, \"Problem nf90_def_dim south_north\")\n\n  if (init) then\n\n    ierr = nf90_def_dim(ncid, \"soil_layers_stag\", 4, dimid)\n    call error_handler(ierr, \"Problem nf90_def_dim soil_layers_stag\")\n\n  end if\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TITLE\", \"OUTPUT FROM CONSOLIDATE_GRIB \"//version)\n  call error_handler(ierr, \"Problem nf90_put_att TITLE\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -1.E36)\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"_FillValue\", -1.E36)\n  call error_handler(ierr, \"Problem nf90_put_att missing_value\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"WEST-EAST_GRID_DIMENSION\", ix+1)\n  call error_handler(ierr, \"Problem nf90_put_att WEST-EAST_GRID_DIMENSION\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"SOUTH-NORTH_GRID_DIMENSION\", jx+1)\n  call error_handler(ierr, \"Problem nf90_put_att SOUTH-NORTH_GRID_DIMENSION\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"DX\", geo_em%proj%dx)\n  call error_handler(ierr, \"Problem nf90_put_att DX\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"DY\", geo_em%proj%dx)\n  call error_handler(ierr, \"Problem nf90_put_att DY\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT1\", geo_em%proj%truelat1)\n  call error_handler(ierr, \"Problem nf90_put_att TRUELAT1\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT2\", geo_em%proj%truelat2)\n  call error_handler(ierr, \"Problem nf90_put_att TRUELAT2\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LA1\", geo_em%proj%lat1)\n  call error_handler(ierr, \"Problem nf90_put_att LA1\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LO1\", geo_em%proj%lon1)\n  call error_handler(ierr, \"Problem nf90_put_att LO1\")\n\n!KWM  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LA2\", geo_em%la2)\n!KWM  call error_handler(ierr, \"Problem nf90_put_att LA2\")\n\n!KWM  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LO2\", geo_em%lo2)\n!KWM  call error_handler(ierr, \"Problem nf90_put_att LO2\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"STAND_LON\", geo_em%proj%stdlon)\n  call error_handler(ierr, \"Problem nf90_put_att STAND_LON\")\n\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", geo_em%proj%code)\n  call error_handler(ierr, \"Problem nf90_put_att MAP_PROJ\")\n\n  if (init) then\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"GRID_ID\", geo_em%grid_id)\n    call error_handler(ierr, \"Problem nf90_put_att GRID_ID\")\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"ISWATER\", geo_em%iswater)\n    call error_handler(ierr, \"Problem nf90_put_att ISWATER\")\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"ISLAKE\", geo_em%islake)\n    call error_handler(ierr, \"Problem nf90_put_att ISLAKE\")\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"ISURBAN\", geo_em%isurban)\n    call error_handler(ierr, \"Problem nf90_put_att ISURBAN\")\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"ISICE\", geo_em%isice)\n    call error_handler(ierr, \"Problem nf90_put_att ISICE\")\n\n  end if\n\n!\n! Even though the LDASIN files should work whichever landuse_datset\n! is used at the HRLDAS step, it might be good to know which was\n! used for making this dataset:\n!\n  ierr = nf90_put_att(ncid, NF90_GLOBAL, \"MMINLU\", geo_em%landuse_dataset)\n  call error_handler(ierr, \"Problem nf90_put_att MMINLU\")\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"Problem exiting define mode\")\nend subroutine open_netcdf_for_output\n\n!==============================================================================\n!==============================================================================\n\nsubroutine output_timestring_to_netcdf(ncid, hdate)\n  ! Write the date/time stamp as a variable to the NetCDF file.\n  use netcdf\n  use module_geo_em\n  implicit none\n  integer,                     intent(in) :: ncid\n  character(len=*),            intent(in) :: hdate\n\n  integer,          parameter                :: DateStrLen = 19\n  character(len=1), dimension(DateStrLen, 1) :: output_hdate\n  integer                                    :: dimid_datestrlen\n  integer                                    :: dimid_time\n  integer                                    :: varid\n  integer                                    :: i\n  integer                                    :: ierr\n\n  output_hdate(:,1) = (/ \"0\",\"0\",\"0\",\"0\",\"-\",\"0\",\"0\",\"-\",\"0\",\"0\",\"_\",\"0\",\"0\",\":\",\"0\",\"0\",\":\",\"0\",\"0\" /)\n  do i = 1, len(hdate)\n     output_hdate(i,1) = hdate(i:i)\n  enddo\n\n  ierr = nf90_inq_dimid(ncid, \"Time\", dimid_time)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem finding dimension 'Time'\")\n\n  ierr = nf90_inq_dimid(ncid, \"DateStrLen\", dimid_datestrlen)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem finding dimension 'DateStrLen'\")\n\n  ierr = nf90_redef(ncid)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem NF90_REDEF\")\n\n#ifdef _NETCDF4_COMPRESS_YES_\n  ierr = nf90_def_var(ncid,  \"Times\",  NF90_CHAR, (/dimid_datestrlen,dimid_Time/), varid, deflate_level=2)\n#else\n  ierr = nf90_def_var(ncid,  \"Times\",  NF90_CHAR, (/dimid_datestrlen,dimid_Time/), varid)\n#endif\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem defining variable 'Times'\")\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem with enddef\")\n\n  ierr = nf90_put_var(ncid, varid, output_hdate, (/1,1/), (/datestrlen,1/))\n  call error_handler(ierr, \"OUTPUT_TIMESTRING_TO_NETCDF: Problem putting variable 'Time'\")\n\nend subroutine output_timestring_to_netcdf\n\n!==============================================================================\n!==============================================================================\n\nsubroutine output_to_netcdf(ncid, name, units, array, idim, jdim)\n  use module_geo_em\n  implicit none\n  integer, intent(in) :: ncid\n  character(len=*), intent(in) :: name\n  character(len=*), intent(in) :: units\n  integer, intent(in) :: idim, jdim\n  real, dimension(idim,jdim), intent(in) :: array\n\n  integer :: varid, ierr\n  integer :: dimid_time, dimid_ix, dimid_jx\n\n  ierr = nf90_inq_dimid(ncid, \"Time\", dimid_time)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'Time'\")\n\n  ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'west_east'\")\n\n  ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'south_north'\")\n\n  ierr = nf90_redef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem NF90_REDEF\")\n\n#ifdef _NETCDF4_COMPRESS_YES_\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_Time/), varid, deflate_level=2)\n#else\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_Time/), varid)\n#endif\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem defining variable \"//trim(name))\n\n  ierr = nf90_put_att(ncid, varid, \"units\", trim(units))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting attribute units: \"//trim(units))\n\n  ! ierr = nf90_put_att(ncid, varid, \"missing_value\", -1.E36)\n  ierr = nf90_put_att(ncid, varid, \"_FillValue\", -1.E36)\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem with enddef\")\n\n  ierr = nf90_put_var(ncid, varid, array, (/1,1,1/), (/idim,jdim,1/))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting variable \"//trim(name))\n\nend subroutine output_to_netcdf\n\nsubroutine output_to_netcdf_soil(ncid, name, units, array1, array2, array3, array4, idim, jdim, nsoil)\n  use module_geo_em\n  implicit none\n  integer, intent(in) :: ncid\n  character(len=*), intent(in) :: name\n  character(len=*), intent(in) :: units\n  integer, intent(in) :: idim, jdim, nsoil\n  real, dimension(idim,jdim), intent(in) :: array1, array2, array3, array4\n\n  real, dimension(idim,jdim,nsoil) :: array3d\n\n  integer :: varid, ierr\n  integer :: dimid_time, dimid_ix, dimid_jx, dimid_kx\n\n  array3d(:,:,1) = array1\n  array3d(:,:,2) = array2\n  array3d(:,:,3) = array3\n  array3d(:,:,4) = array4\n\n  ierr = nf90_inq_dimid(ncid, \"Time\", dimid_time)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'Time'\")\n\n  ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'west_east'\")\n\n  ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'south_north'\")\n\n  ierr = nf90_inq_dimid(ncid, \"soil_layers_stag\", dimid_kx)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'soil_layers_stag'\")\n\n  ierr = nf90_redef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem NF90_REDEF\")\n\n#ifdef _NETCDF4_COMPRESS_YES_\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_kx,dimid_Time/), varid, deflate_level=2)\n#else\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_kx,dimid_Time/), varid)\n#endif\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem defining variable \"//trim(name))\n\n  ierr = nf90_put_att(ncid, varid, \"units\", trim(units))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting attribute units: \"//trim(units))\n\n  ! ierr = nf90_put_att(ncid, varid, \"missing_value\", -1.E36)\n  ierr = nf90_put_att(ncid, varid, \"_FillValue\", -1.E36)\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem with enddef\")\n\n  ierr = nf90_put_var(ncid, varid, array3d, (/1,1,1,1/), (/idim,jdim,nsoil,1/))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting variable \"//trim(name))\n\nend subroutine output_to_netcdf_soil\n\nsubroutine output_to_netcdf_int(ncid, name, units, array, idim, jdim)\n  use module_geo_em\n  implicit none\n  integer, intent(in) :: ncid\n  character(len=*), intent(in) :: name\n  character(len=*), intent(in) :: units\n  integer, intent(in) :: idim, jdim\n  integer, dimension(idim,jdim), intent(in) :: array\n\n  integer :: varid, ierr\n  integer :: dimid_time, dimid_ix, dimid_jx\n\n  ierr = nf90_inq_dimid(ncid, \"Time\", dimid_time)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'Time'\")\n\n  ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'west_east'\")\n\n  ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'south_north'\")\n\n  ierr = nf90_redef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem NF90_REDEF\")\n\n#ifdef _NETCDF4_COMPRESS_YES_\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_INT, (/dimid_ix,dimid_jx,dimid_Time/), varid, deflate_level=2)\n#else\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_INT, (/dimid_ix,dimid_jx,dimid_Time/), varid)\n#endif\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem defining variable \"//trim(name))\n\n  ierr = nf90_put_att(ncid, varid, \"units\", trim(units))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting attribute units: \"//trim(units))\n\n  ! ierr = nf90_put_att(ncid, varid, \"missing_value\", -1.E36)\n  ierr = nf90_put_att(ncid, varid, \"_FillValue\", -999999)\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem with enddef\")\n\n  ierr = nf90_put_var(ncid, varid, array, (/1,1,1/), (/idim,jdim,1/))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting variable \"//trim(name))\n\nend subroutine output_to_netcdf_int\n\nsubroutine output_to_netcdf_vector(ncid, name, units, nsoil, array)\n  use module_geo_em\n  implicit none\n  integer, intent(in) :: ncid\n  character(len=*), intent(in) :: name\n  character(len=*), intent(in) :: units\n  integer, intent(in) :: nsoil\n  real, dimension(nsoil), intent(in) :: array\n\n  integer :: varid, ierr\n  integer :: dimid_time, dimid_kx\n\n  ierr = nf90_inq_dimid(ncid, \"Time\", dimid_time)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'Time'\")\n\n  ierr = nf90_inq_dimid(ncid, \"soil_layers_stag\", dimid_kx)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem finding dimension 'soil_layers_stag'\")\n\n  ierr = nf90_redef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem NF90_REDEF\")\n\n#ifdef _NETCDF4_COMPRESS_YES_\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_FLOAT, (/dimid_kx,dimid_Time/), varid, deflate_level=2)\n#else\n  ierr = nf90_def_var(ncid,  trim(name),  NF90_FLOAT, (/dimid_kx,dimid_Time/), varid)\n#endif\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem defining variable \"//trim(name))\n\n  ierr = nf90_put_att(ncid, varid, \"units\", trim(units))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting attribute units: \"//trim(units))\n\n  ierr = nf90_put_att(ncid, varid, \"_FillValue\", -1.e36)\n\n  ierr = nf90_enddef(ncid)\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem with enddef\")\n\n  ierr = nf90_put_var(ncid, varid, array, (/1,1/), (/nsoil,1/))\n  call error_handler(ierr, \"OUTPUT_TO_NETCDF: Problem putting variable \"//trim(name))\n\nend subroutine output_to_netcdf_vector\n\n!==============================================================================\n!==============================================================================\n\nsubroutine fillsm(data, mask, nx, ny)\n  use kwm_grid_utilities\n  implicit none\n  integer,                    intent(in)      :: nx\n  integer,                    intent(in)      :: ny\n  real,    dimension(nx, ny), intent(inout)   :: data\n  logical, dimension(nx, ny), intent(in)      :: mask\n\n  integer :: i, k\n  real, dimension(nx,ny) :: hold\n\n  hold = data\n\n  do i = 1, 100\n     call smt121(data, nx, ny, 5)\n     where(mask)\n        data = hold\n     end where\n  enddo\n\nend subroutine fillsm\n\n!==============================================================================\n!==============================================================================\n\nsubroutine interp_rainfall_nearest_neighbor(datastruct, newarr, mix, mjx, geo_em)\n  !\n  ! Fill array <newarr> with rainfall data from <datastruct>\n  !\n  use module_input_data_structure\n  use kwm_grid_utilities\n  use module_geo_em\n  implicit none\n  type(input_data_type) :: datastruct\n  type(geo_em_type), intent(in) :: geo_em\n  integer, intent(in) :: mix, mjx\n  real, dimension(mix,mjx) :: newarr\n\n  integer :: ii, jj\n  real    :: x, y\n  integer :: xn, yn\n  real    :: east_longitude\n\n  newarr = 0.0\n\n  !KWM where (datastruct%data < 0) datastruct%data = 0\n  do ii = 1, mix\n     do jj = 1, mjx\n        ! Compute the x/y location in the <datastruct> dataset of the HRLDAS point (ii,jj).\n\n        ! call datastruct_lltoxy(geo_em%lat(ii,jj), geo_em%lon(ii,jj), x, y, datastruct)\n\n#if 0\n        ! Lon must be between 0 and 360 E\n        if (geo_em%lon(ii,jj) < 0) then\n           east_longitude = geo_em%lon(ii,jj) + 360.\n        else\n           east_longitude = geo_em%lon(ii,jj)\n        endif\n\n        call latlon_to_ij(datastruct%proj, geo_em%lat(ii,jj), east_longitude, x, y)\n#else\n        call latlon_to_ij(datastruct%proj, geo_em%lat(ii,jj), geo_em%lon(ii,jj), x, y)\n#endif\n\n        xn = nint(x)\n        yn = nint(y)\n        if ((xn>0).and.(yn>0).and.(xn<=size(datastruct%data,1)).and.(yn<=size(datastruct%data,2))) then\n           newarr(ii,jj) = datastruct%data(xn,yn)\n           !KWM if (newarr(ii,jj) < 0) newarr(ii,jj) = 0\n           if (newarr(ii,jj) < 0) newarr(ii,jj) = -1.E36\n        else\n           newarr(ii,jj) = -1.E36\n        endif\n     enddo\n  enddo\n\nend subroutine interp_rainfall_nearest_neighbor\n\n!==============================================================================\n!==============================================================================\n\nsubroutine interp_rainfall(datastruct, newarr, mix, mjx, geo_em)\n  ! fill array newarr with rainfall data from datastruct\n  use module_input_data_structure\n!  use v3_module\n  use kwm_grid_utilities\n  use module_geo_em\n  implicit none\n  type(input_data_type) :: datastruct\n  type(geo_em_type), intent(in) :: geo_em\n  integer, intent(in) :: mix, mjx\n  real, dimension(mix,mjx) :: newarr, fcount\n  integer :: i, j\n  real :: xlat, xlon, xx, yy\n  real, parameter :: badval = -1.E30\n  real :: factor\n  integer :: ii, jj, iii, jjj\n  real :: x, y, mx, my, x2, y2\n  ! real, save, allocatable, dimension(:,:) :: mxa, mya\n  real, allocatable, dimension(:,:) :: mxa, mya\n  integer :: astat\n\n!  integer, parameter :: nsub = 50\n!  integer, parameter :: nsub = 15\n!  integer, parameter :: nsub = 8\n!  integer, parameter :: nsub = 4\n\n  integer :: nsub\n\n  ! Select nsub to have at least 10x10 source grid cells\n  ! per destination grid cell.\n  if(datastruct%proj%code == 0) then  ! Make a special exception for lat-lon: Barlage 20150311\n    nsub = 10\n  else\n    nsub = ceiling(datastruct%proj%dx*1.E-3 * 10.0 / (geo_em%proj%dx*1.E-3))\n  end if\n  print*, 'nsub = ', nsub\n\n  newarr = 0.0\n  fcount = 0.0\n\n  ! Take a more expensive approach, assigning portions of rainfall\n  ! field's grid cells to various WRF grid cells as necessary.\n\n  ! We recompute the mapping information every time, in case our source grid has changed.\n\n  ILOOP : do i = 1, datastruct%nx\n     JLOOP : do j = 1, datastruct%ny\n        ! Compute (x,y) in WRF grid of point (gx,gy) in precip grid.\n!KWM        call datastruct_xytoll(float(i), float(j), xlat, xlon, datastruct)\n        call ij_to_latlon(datastruct%proj, float(i), float(j), xlat, xlon)\n        call latlon_to_ij(geo_em%proj, xlat, xlon, x, y)\n        ! Now X and Y are the x and y coordinates in the WRF\n        ! grid of the RAINFALL point i, j.\n\n        if ((x > -2) .and. (y > -2) .and. (x < mix+2) .and. (y < mjx+2)) then\n\n           do ii = 1, nsub\n              x = float(i) + 0.5 * (1./float(nsub)-1) + float(ii-1)/float(nsub)\n              do jj = 1, nsub\n                 y = float(j) + 0.5 *(1./float(nsub)-1) + float(jj-1)/float(nsub)\n!KWM                 call datastruct_xytoll(x, y, xlat, xlon, datastruct)\n                 call ij_to_latlon(datastruct%proj,x, y, xlat, xlon)\n                 call latlon_to_ij(geo_em%proj, xlat, xlon, x2, y2)\n\n                 iii = nint(x2)\n                 jjj = nint(y2)\n                 if ((jjj > 0) .and. (iii > 0) .and. (jjj <= mjx) .and. (iii <= mix)) then\n                    if (datastruct%data(i,j) > 0) then\n                       newarr(iii,jjj) = newarr(iii,jjj) + datastruct%data(i,j)\n                    endif\n                    fcount(iii,jjj) = fcount(iii,jjj) + 1.0\n                 endif\n              enddo\n           enddo\n\n        endif\n     enddo JLOOP\n  enddo ILOOP\n\n  where (fcount > 0.0)\n     newarr = newarr / fcount\n  elsewhere\n     newarr = -1.E36\n  end where\n\n  where (newarr < 0)\n!     newarr = 0.0 ! -1.E36\n     newarr = -1.E36\n  end where\n\nend subroutine interp_rainfall\n\n!==============================================================================\n!==============================================================================\n\nsubroutine another_interp_rainfall(datastruct, newarr, mix, mjx, geo_em)\n  !\n  ! Fill array newarr with rainfall data from datastruct\n  !\n  ! Take an expensive approach, assigning portions of rainfall\n  ! field's grid cells to various WRF grid cells as necessary.\n  !\n  use module_input_data_structure\n  use kwm_grid_utilities\n  use module_geo_em\n  implicit none\n  type(input_data_type) :: datastruct\n  type(geo_em_type), intent(in) :: geo_em\n  integer, intent(in) :: mix, mjx\n  real, dimension(mix,mjx) :: newarr, fcount\n  integer :: i, j\n  real :: xlat, xlon, xx, yy\n  real, parameter :: badval = -1.E30\n  real :: factor\n  integer :: ii, jj, iii, jjj\n  real :: x, y, mx, my\n  real, save, allocatable, dimension(:,:) :: mxa, mya\n  integer :: astat\n\n  ! For high-resolution cases, is this just going to exhaust our memory?\n  real, save, allocatable, dimension(:,:,:,:) :: x2, y2\n\n  integer :: nsub\n\n  ! We need to check datastruct%iproj, datastruct%nx, datastruct%ny, datastruct%proj%lat1, datastruct%startlon\n  ! datastruct%proj%latinc, datastruct%proj%loninc, datastruct%dx, datastruct%dy, datastruct%xlonc, datastruct%truelat1,\n  ! and datastruct%truelat1 to be sure that our datastruct data is not from some different\n  ! grid.\n\n  logical :: samegrid\n  integer, save :: iproj = -9999\n  integer, save :: nx\n  integer, save :: ny\n  real,    save :: startlat\n  real,    save :: startlon\n  real,    save :: deltalat\n  real,    save :: deltalon\n  real,    save :: dx\n  real,    save :: dy\n  real,    save :: xlonc\n  real,    save :: truelat1\n  real,    save :: truelat2\n\n  ! Check the grid info:\n  samegrid = .TRUE.\n  if (iproj    /= datastruct%proj%code)      samegrid=.FALSE.\n  if (nx       /= datastruct%nx)             samegrid=.FALSE.\n  if (ny       /= datastruct%ny)             samegrid=.FALSE.\n  if (startlat /= datastruct%proj%lat1)      samegrid=.FALSE.\n  if (startlon /= datastruct%proj%lon1)      samegrid=.FALSE.\n  if (      dx /= datastruct%proj%dx)        samegrid=.FALSE.\n  if (      dy /= datastruct%proj%dy)        samegrid=.FALSE.\n  if (   xlonc /= datastruct%proj%stdlon)    samegrid=.FALSE.\n  if (truelat1 /= datastruct%proj%truelat1)  samegrid=.FALSE.\n  if (truelat2 /= datastruct%proj%truelat2)  samegrid=.FALSE.\n\n  ! Select nsub to have at least 10x10 source grid cells\n  ! per destination grid cell.\n  ! nsub = ceiling(datastruct%proj%dx * 10.0 / (geo_em%proj%dx))\n  nsub = ceiling(datastruct%proj%dx * 11.0 / geo_em%proj%dx)\n\n  newarr = 0.0\n  fcount = 0.0\n\n  if (.not. samegrid) then\n     write(*,'(\"Computing new grid information for rainfall remapping.\")')\n     print*, 'nsub = ', nsub\n     if (allocated(mxa)) deallocate(mxa)\n     if (allocated(mya)) deallocate(mya)\n     if (allocated(x2))  deallocate(x2)\n     if (allocated(y2))  deallocate(y2)\n     ! Save this information:\n     iproj    = datastruct%proj%code\n     nx       = datastruct%nx\n     ny       = datastruct%ny\n     startlat = datastruct%proj%lat1\n     startlon = datastruct%proj%lon1\n     dx       = datastruct%proj%dx\n     dy       = datastruct%proj%dy\n     xlonc    = datastruct%proj%stdlon\n     truelat1 = datastruct%proj%truelat1\n     truelat2 = datastruct%proj%truelat2\n  endif\n\n  if (.not. allocated(mxa)) then\n     allocate(mxa(datastruct%nx,datastruct%ny), stat=astat)\n     if (astat /= 0) stop \"FATAL ERROR: Problem allocating MXA\"\n     allocate(mya(datastruct%nx,datastruct%ny), stat=astat)\n     if (astat /= 0) stop \"FATAL ERROR: Problem allocating MYA\"\n     allocate(x2(datastruct%nx,datastruct%ny,nsub,nsub), stat=astat)\n     if (astat /= 0) stop \"FATAL ERROR: Problem allocating X2\"\n     allocate(y2(datastruct%nx,datastruct%ny,nsub,nsub), stat=astat)\n     if (astat /= 0) stop \"FATAL ERROR: Problem allocating Y2\"\n     ILOOP1 : do i = 1, datastruct%nx\n        JLOOP1 : do j = 1, datastruct%ny\n           ! Compute (x,y) in WRF grid of point (gx,gy) in precip grid.\n           call ij_to_latlon(datastruct%proj, float(i), float(j), xlat, xlon)\n           call latlon_to_ij(geo_em%proj, xlat, xlon, mxa(i,j), mya(i,j))\n\n           ! Now MX and MY are the x and y coordinates in the WRF\n           ! grid of the RAINFALL point i, j.\n\n        if ((mxa(i,j) > -2) .and. (mya(i,j) > -2) .and. (mxa(i,j) < mix+2) .and. (mya(i,j) < mjx+2)) then\n           do ii = 1, nsub\n              x = float(i) + 0.5 * (1./float(nsub)-1) + float(ii-1)/float(nsub)\n              do jj = 1, nsub\n                 y = float(j) + 0.5 *(1./float(nsub)-1) + float(jj-1)/float(nsub)\n                 call ij_to_latlon(datastruct%proj, x, y, xlat, xlon)\n                 call latlon_to_ij(geo_em%proj, xlat, xlon, x2(i,j,ii,jj), y2(i,j,ii,jj))\n              enddo\n           enddo\n\n        endif\n\n        enddo JLOOP1\n     enddo ILOOP1\n  endif\n\n  ILOOP : do i = 1, datastruct%nx\n     JLOOP : do j = 1, datastruct%ny\n        ! Find the WRF coordinates of the DATASTRUCT point in question\n        if ((mxa(i,j) > -2) .and. (mya(i,j) > -2) .and. (mxa(i,j) < mix+2) .and. (mya(i,j) < mjx+2)) then\n\n           do ii = 1, nsub\n              do jj = 1, nsub\n                 iii = nint(x2(i,j,ii,jj))\n                 jjj = nint(y2(i,j,ii,jj))\n                 if ((jjj > 0) .and. (iii > 0) .and. (jjj <= mjx) .and. (iii <= mix)) then\n                    ! if (datastruct%data(i,j) >0) then\n                    if (datastruct%data(i,j) >=0) then\n                       newarr(iii,jjj) = newarr(iii,jjj) + datastruct%data(i,j)\n                    endif\n                    fcount(iii,jjj) = fcount(iii,jjj) + 1.0\n                 endif\n              enddo\n           enddo\n        endif\n     enddo JLOOP\n  enddo ILOOP\n\n  where (fcount > 0.0)\n     newarr = newarr / fcount\n  elsewhere\n     newarr = -1.E36\n  end where\n\n  where (newarr < 0)\n!     newarr = 0.0 ! -1.E36\n     newarr = -1.E36\n  end where\n\nend subroutine another_interp_rainfall\n\n!==============================================================================\n!==============================================================================\n\nsubroutine rescale_sw_time_offset(datastruct)\n  use module_input_data_structure\n  use kwm_date_utilities\n  implicit none\n  type(input_data_type), intent(inout) :: datastruct\n\n  integer :: idim\n  integer :: jdim\n\n!KWM  real, parameter :: pi = 3.14159265\n\n  character(len=16) :: nowdate\n  integer :: jday\n  integer :: ihour\n  integer :: iminute\n\n  integer :: i, j\n  real    :: lat, lon\n  real    :: latrad, lonrad\n\n  real :: gg\n  real :: declin\n  real :: tc\n  real :: SHA\n  real :: hour\n  real :: time_of_day\n  real :: time_of_day00\n  real :: cza\n  real :: cza00\n\n  idim = datastruct%nx\n  jdim = datastruct%ny\n\n  ! Get the hour and minute from the date string.\n  read(datastruct%hdate(12:16), '(I2,1x,I2)') ihour, iminute\n  if (iminute == 0) return ! No adjusting of SW data necessary\n\n  ! Find the julian day from the date string.\n  call geth_idts(datastruct%hdate(1:10), datastruct%hdate(1:4)//\"-01-01\", jday)\n  jday = jday + 1\n\n  ! The (GMT) time of day as encoded in the data, hours and fractional minutes.\n  time_of_day = float(ihour) + float(iminute)/60.\n\n  ! The (GMT) time of day, truncated to the hour.\n  time_of_day00 = float(ihour)\n\n  write(*, '(12x,\"SW offset:  Record time:\", F6.3, \";  HRLDAS analysis time:\", F6.3, \";   Time offset (hours):\",  F6.4)') &\n       time_of_day, time_of_day00, time_of_day - time_of_day00\n\n  do i = 1, idim\n     do j = 1, jdim\n\n        ! First, compute the lat/lon at the DATASTRUCT points.\n!KWM        call datastruct_xytoll(float(i), float(j), lat, lon, datastruct)\n        call ij_to_latlon(datastruct%proj, float(i), float(j), lat, lon)\n        latrad = lat*pi/180.\n        lonrad = lon*pi/180.\n\n        call get_declin(jday, time_of_day, latrad, lonrad, declin, sha)\n\n        ! CZA -- Cosine of the solar zenith angle\n        cza = sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA)\n        if (cza < 0.1) cza = 0;\n\n        call get_declin(jday, time_of_day00, latrad, lonrad, declin, sha)\n        cza00 = sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA)\n        if (cza00 < 0) cza00 = 0;\n\n        if (datastruct%data(i,j) > 0) then\n           if (cza < 0.05) then\n              datastruct%data(i,j) = 0.\n           else\n              datastruct%data(i,j) = cza00/cza * datastruct%data(i,j)\n           endif\n        endif\n     enddo\n  enddo\n\nend subroutine rescale_sw_time_offset\n\n!==============================================================================\n!==============================================================================\n\nsubroutine get_declin(jday, gmthour, latrad, lonrad, declin, sha)\n  implicit none\n  integer, intent(in) :: jday\n  real, intent(in) :: gmthour\n  real, intent(in) :: latrad\n  real, intent(in) :: lonrad\n  real, intent(out) :: declin\n  real, intent(out) :: sha\n  ! real, intent(out) :: sza\n\n  real :: gg, tc\n  real, parameter :: pi = 3.14159265\n\n  ! Fractional day of the year, in radians\n  gg = (360./365.25) * (JDAY+gmthour/24.) * pi/180.\n\n  ! Solar declination angle, in radians.\n  DECLIN = 0.006918 - 0.399912*cos(gg) + 0.070257*sin(gg) - 0.006758*cos(2.0*gg) + &\n       0.000907*sin(2.0*gg) - 0.002697*cos(3.0*gg) + 0.00148*sin(3.0*gg)\n\n  ! Time Correction for solar angle, in radians.  Whatever.\n  TC = 0.000075 + 0.001868*cos(gg) - 0.032077*sin(gg) - 0.014615*cos(2.0*gg) - &\n       0.040849*sin(2.0*gg)\n\n  ! Solar Hour Angle, in radians\n  SHA = ((gmthour-12.0)*15.0)*(pi/180.) + lonrad + TC\n  ! SHA = (gmthour*15.0)*(pi/180.) + lonrad + TC\n\n  ! ! Solar Zenith Angle, in radians\n  ! SZA = acos(sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA))\n\n  !  ! Solar Elevation Angle, in radians.\n  !  SEA = (pi/2.)-SZA\n\n  !  ! Azimuth Angle\n  !  AZ = acos((sin(DECLIN)-sin(latrad)*cos(SZA))/(cos(Latrad)*sin(SZA)))\n\nend subroutine get_declin\n\n!==============================================================================\n!==============================================================================\n\nsubroutine nighttime_SW(hdate, field, idim, jdim, geo_em)\n  ! IDIM and JDIM are the dimensions of FIELD, which should also be the same \n  ! as the geo_em%IDIM and geo_em%JDIM dimensions.\n  use module_geo_em\n  use kwm_date_utilities\n  use kwm_grid_utilities\n  implicit none\n  character(len=*), intent(in) :: hdate\n  integer, intent(in) :: idim, jdim\n  type (geo_em_type), intent(in) :: geo_em\n  real, dimension(idim,jdim), intent(inout) :: field\n\n  integer :: i, j, jday, ihour, iminute\n  real :: lat, lon, latrad, lonrad, gmthour\n  real :: declin, sha, cosza\n  real, dimension(idim, jdim) :: maskarray\n  real, dimension(idim, jdim) :: mask2\n\n  integer :: ii, jj, mcount, iiterm\n  integer :: cdist\n  integer :: iimin, iimax, jjmin, jjmax\n  integer, allocatable, dimension(:,:) :: mtx\n\n  call geth_idts(hdate(1:10), hdate(1:4)//\"-01-01\", jday)\n  jday = jday + 1\n  read(hdate(12:16), '(I2,1x,I2)') ihour, iminute\n  gmthour = float(ihour) + float(iminute)/60.\n\n  ! Make a mask array\n  do i = 1, idim\n     do j = 1, jdim\n        latrad = geo_em%lat(i,j) * rad_per_deg\n        lonrad = geo_em%lon(i,j) * rad_per_deg\n        call get_declin(jday, gmthour, latrad, lonrad, declin, sha)\n\n        cosza = sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA)\n\n        if (cosza > 0.0) then\n           maskarray(i,j) = 1.0\n        else\n           maskarray(i,j) = 0.0\n        endif\n     enddo\n  enddo\n\n  ! Smooth the mask array a bit, to get us a less abrupt change\n  !        Took this out on 14 Feb 2008.  Kind of a hack.\n  ! call smt121(maskarray, idim, jdim, 10)\n\n  field = field * maskarray\n\nend subroutine nighttime_SW\n\n!==============================================================================\n!==============================================================================\n\nsubroutine close_flnm(flnm)\n  implicit none\n  character(len=*), intent(in) :: flnm\n  integer :: n\n  inquire(file=trim(flnm), number=n)\n  if (n > -1) close(n)\nend subroutine close_flnm\n\n!==============================================================================\n!==============================================================================\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/Makefile",
    "content": "SHELL=/bin/sh\n.SUFFIXES:\t\n.SUFFIXES:\t.F .c .o\n\ninclude ../../user_build_options\n\nOBJS=\tmodule_grib2.o \\\n\tmodule_grib2_tables.o \\\n\ttrig_degrees.o \\\n\tmodule_input_data_structure.o \\\n\targuments_module.o \\\n\tgbytesys.o \\\n\tswap4f.o \\\n\tmodule_llxy.o \\\n\tcio.o \\\n\tkwm_date_utilities.o \\\n\tkwm_grid_utilities.o \\\n\tkwm_timing_utilities.o \\\n\tkwm_string_utilities.o \\\n\tswap4c.o \\\n\tget_unused_unit.o \\\n\tdecode_jpeg2000.o  \\\n\tio_f.o \\\n\tmodule_mapinfo.o \\\n\tmodule_grib1.o \\\n\tmodule_grib.o \\\n\tmodule_grib_common.o \\\n\tmodule_geo_em.o \n\nCMD=\tlibsmda.a\n\nGRIBCODE_OPT = -DBIT32\nBZIP_CPP = -D_BZIP_$(BZIP2)\n\nall:\t$(CMD)\n\nlibsmda.a:\t$(OBJS)\n\t$(RM) libsmda.a\n\tar q libsmda.a $(OBJS)\n\nswap4c.o:\tswap4c.c\n\t$(CC) -c swap4c.c\n\nio_f.o:\tio_f.c\n\t$(CC) -c $(CCFLAGS) $(BZIP_CPP) $(BZIP2_INCLUDE) io_f.c\n\ndecode_jpeg2000.o:\tdecode_jpeg2000.c\n\t$(CC) -c $(INCJASPER) $(<)\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(GRIBCODE_OPT) $(BZIP_CPP) -c $(FREESOURCE) $(F90FLAGS) $(LDFLAGS) $(NETCDFMOD) $(*).F\n\n.c.o:\n\t$(CC) -c $(BZIP_CPP) $(<)\n\nclean:\n\t$(RM) $(OBJS) $(CMD) *.mod *~\n#\nmodule_grib2.o:\tmodule_grib2.F module_grib2_tables.o module_grib1.o module_mapinfo.o kwm_date_utilities.o module_grib_common.o\nmodule_grib1.o: module_grib1.F module_mapinfo.o kwm_date_utilities.o module_grib_common.o\nmodule_grib.o:\tmodule_grib.F module_grib1.o module_grib2.o\nmodule_input_data_structure.o:\tmodule_llxy.o\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/arguments_module.F",
    "content": "module arguments_module\n  implicit none\n  private\n  public :: arg\n  public :: print_help\n  character(len=2400), public :: arguments_help\n\n  logical :: adone = .FALSE.\n  character(len=120), dimension(0:2000) :: harg\n  integer :: numarg\n\n  interface arg\n     module procedure &\n          argi, argndi,&\n          argf,&\n          argl,&\n          argh, argndh, argnd1h,&\n          argsub\n  end interface\n\ncontains\n\n!==============================================================================\n\n  subroutine argi(string, default, ival)\n! Handle the case for optional integer flags,\n! i.e., (FLAG, DEFAULT, VALUE) for integers.\n    implicit none\n    character(len=*) :: string\n    integer :: default\n    integer :: ival\n    integer :: ierr, i, nval\n\n    call initialize\n\n    ival = default\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          read(harg(i+1),*, iostat=ierr) ival\n          if (ierr /= 0) then\n             call print_help\n          endif\n          harg(i:numarg-2) = harg(i+2:numarg)\n          numarg = numarg - 2\n          return\n       endif\n    enddo\n\n    do i = 1, nval\n       if ( (harg(i)(1:len(string)) == string).and.&\n            (scan(harg(i)(len(string)+1:),\"0123456789\") .ne. 0) )then\n          read(harg(i)(len(string)+1:),*, iostat=ierr) ival\n          if (ierr == 0) then\n             harg(i:numarg-1) = harg(i+1:numarg)\n             numarg = numarg - 1\n             return\n          endif\n       endif\n    enddo\n\n  end subroutine argi\n\n!==============================================================================\n\n  subroutine argndi(string, ival)\n! Handle the case of required integer flags,\n! i.e., (FLAG, VALUE) for integers.\n    implicit none\n    character(len=*) :: string\n    integer :: ival\n\n    integer :: ierr, i, nval\n\n    call initialize\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          read(harg(i+1),*) ival\n          harg(i:numarg-2) = harg(i+2:numarg)\n          numarg = numarg - 2\n          return\n       endif\n    enddo\n\n    nval = numarg\n    do i = 1, nval\n\n       if ( (harg(i)(1:len(string)) == string).and.&\n            (scan(harg(i)(len(string)+1:),\"0123456789\") .ne. 0) )then\n          read(harg(i)(len(string)+1:),*, iostat=ierr) ival\n          if (ierr == 0) then\n             harg(i:numarg-1) = harg(i+1:numarg)\n             numarg = numarg - 1\n             return\n          endif\n       endif\n    enddo\n\n    write(*,'(/,\"WARNING: Argument \", A, \" MUST be present.\",/)') trim(string)\n    call print_help\n  end subroutine argndi\n\n!==============================================================================\n\n  subroutine argf(string, default, xval)\n! Handle the case for optional real flags,\n! i.e., (FLAG, DEFAULT, VALUE) for reals.\n    implicit none\n    character(len=*) :: string\n    real :: default\n    real :: xval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    xval = default\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          read(harg(i+1),*) xval\n          harg(i:numarg-2) = harg(i+2:numarg)\n          numarg = numarg - 2\n          return\n       endif\n    enddo\n\n    nval = numarg\n    do i = 1, nval\n\n       if ( (harg(i)(1:len(string)) == string).and.&\n            (scan(harg(i)(len(string)+1:),\"0123456789\") .ne. 0) )then\n          read(harg(i)(len(string)+1:),*, iostat=ierr) xval\n          if (ierr == 0) then\n             harg(i:numarg-1) = harg(i+1:numarg)\n             numarg = numarg - 1\n             return\n          endif\n       endif\n    enddo\n  end subroutine argf\n\n!==============================================================================\n\n  subroutine argl(string, default, lval)\n! Handle the case of optional logical flags,\n! i.e., (FLAG, DEFAULT, VALUE) for logicals.\n    implicit none\n    character(len=*) :: string\n    logical :: default\n    logical :: lval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    lval = default\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          lval = .not.(default)\n          harg(i:numarg-1) = harg(i+1:numarg)\n          numarg = numarg - 1\n          return\n       endif\n    enddo\n\n  end subroutine argl\n\n!==============================================================================\n\n  subroutine argh(string, default, hval)\n! Handle the case of optional flagged string arguments,\n! i.e., (FLAG, DEFAULT, VALUE) for strings.\n    implicit none\n    character(len=*) :: string\n    character(len=*) :: default\n    character(len=*) :: hval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    hval = default\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          hval = harg(i+1)\n          harg(i:numarg-2) = harg(i+2:numarg)\n          numarg = numarg - 2\n          return\n       endif\n    enddo\n\n    nval = numarg\n    do i = 1, nval\n\n       if (harg(i)(1:len(string)) == string) then\n          hval = harg(i)(len(string)+1:)\n          harg(i:numarg-1) = harg(i+1:numarg)\n          numarg = numarg - 1\n          return\n       endif\n    enddo\n  end subroutine argh\n\n!==============================================================================\n\n  subroutine argndh(string, hval)\n! Handle the case of required flagged string arguments,\n! i.e., (FLAG, VALUE) for strings.\n!    or\n! Handle the case of optional unflagged string arguments.\n! i.e., (DEFAULT, VALUE) for strings.\n\n    implicit none\n    character(len=*) :: string\n    character(len=*) :: hval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    if (string(1:1) .eq. \"-\") then\n! STRING is a flag.\n! Handle the case of required flagged string arguments\n\n       nval = numarg\n       do i = 1, nval\n          if (harg(i) == string) then\n             if (i == numarg) call print_help\n             hval = harg(i+1)\n             if (hval(1:1) == '-') call print_help\n             harg(i:numarg-2) = harg(i+2:numarg)\n             numarg = numarg - 2\n             return\n          endif\n       enddo\n\n       do i = 1, nval\n\n          if (harg(i)(1:len(string)) == string) then\n             hval = harg(i)(len(string)+1:)\n             harg(i:numarg-1) = harg(i+1:numarg)\n             numarg = numarg - 1\n             return\n          endif\n       enddo\n\n       write(*,'(/,\"WARNING: Argument \", A, \" MUST be present.\",/)') trim(string)\n       call print_help\n    else\n! STRING is a default string value.\n! Handle the case of optional unflagged string arguments.\n\n       if (numarg > 0) then\n          if (harg(1)(1:1) == \"-\") then\n             call print_help\n          else\n             hval = harg(1)\n             harg(1:numarg-1) = harg(2:numarg)\n             numarg = numarg - 1\n          endif\n       else\n          hval = string\n       endif\n    endif\n\n  end subroutine argndh\n\n!==============================================================================\n!KWM\n!KWM  subroutine arg1h(default, hval)\n!KWM! Handle the case of optional unflagged string arguments.\n!KWM    implicit none\n!KWM    character(len=*) :: default\n!KWM    character(len=*) :: hval\n!KWM\n!KWM    integer :: nval, i, ierr\n!KWM\n!KWM    call initialize\n!KWM\n!KWM    if (numarg > 0) then\n!KWM       hval = harg(1)\n!KWM       harg(1:numarg-1) = harg(2:numarg)\n!KWM       numarg = numarg - 1\n!KWM    else\n!KWM       hval = default\n!KWM    endif\n!KWM\n!KWM  end subroutine arg1h\n!KWM\n!==============================================================================\n\n  subroutine argnd1h(hval)\n! Handle the case of required unflagged string arguments.\n    implicit none\n    character(len=*) :: hval\n\n    integer :: nval, i, ierr\n\n    call initialize\n\n    if (numarg /= 1) then\n       write(*,'(/,\"WARNING: A final command-line argument MUST be present.\")')\n       call print_help\n    else\n       if (harg(numarg)(1:1) == \"-\") then\n          call print_help\n       else\n          hval = harg(numarg)\n       endif\n    endif\n\n  end subroutine argnd1h\n\n!==============================================================================\n\n  subroutine argsub(string, subr)\n! Handle the case of a subprogram.\n    implicit none\n    character(len=*) :: string\n    integer :: nval, i\n    external subr\n\n    call initialize\n\n    nval = numarg\n    do i = 1, nval\n       if (harg(i) == string) then\n          call subr\n       endif\n    enddo\n\n  end subroutine argsub\n\n!==============================================================================\n\n  subroutine print_help\n    write(*,'(/,\"Usage: \", A, 1x)', advance=\"no\") trim(harg(0))\n    write(*,arguments_help)\n    write(*,'(/)')\n    stop\n  end subroutine print_help\n\n!==============================================================================\n\n  subroutine initialize\n    implicit none\n    integer :: i\n    integer, external :: iargc\n\n    if (.not. adone) then\n       numarg = iargc()\n       do i = 0, numarg\n          call getarg(i, harg(i))\n       enddo\n       adone = .TRUE.\n    endif\n\n  end subroutine initialize\n\n!==============================================================================\n\nend module arguments_module\n\n!KWMprogram test1\n!KWM  use arguments_module\n!KWM  implicit none\n!KWM  integer :: i, j, k\n!KWM  real :: x, y, z\n!KWM  logical :: g, gg\n!KWM  character(len=120) :: h, flnm\n!KWM  arguments_help = '(\"-a i -b b -c c -aa aa -bb bb -cc cc -g -gg -h h flnm\")'\n!KWM  call arg(\"-a\", i)\n!KWM  call arg(\"-b\", 12, k)\n!KWM  call arg(\"-c\", 11, j)\n!KWM  call arg(\"-aa\", 1.10, x)\n!KWM  call arg(\"-bb\", 1.12, y)\n!KWM  call arg(\"-cc\", 1.11, z)\n!KWM  call arg(\"-g\", .TRUE., g)\n!KWM  call arg(\"-gg\", .FALSE., gg)\n!KWM  call arg(\"-h\", \"Whatever\", h)\n!KWM  call arg(flnm)\n!KWM\n!KWM  print*, 'i, j, k = ', i, j, k\n!KWM  print*, 'x, y, z = ', x, y, z\n!KWM  print*, 'g, gg = ', g, gg\n!KWM\n!KWM  print*,' h = ', trim(h)\n!KWM  print*, 'flnm = ', trim(flnm)\n!KWM\n!KWMend program test1\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/cio.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n\n*/\n\n/*  FILE: cio.c  */\n/*  C functions to write bytes to UNIX files - called from FORTRAN */\n/*  copen\n    bnread\n    bnwrit\n    cclose\n    rewtap\n    eoftap\n    fsftap\n    bsrtap\n    bsrfil */\n/*  870417  */\n\n#if defined(CRAY)\n\n#define copen  COPEN\n#define bnread BNREAD\n#define bnwrit BNWRIT\n#define cclose CCLOSE\n#define rewtap REWTAP\n#define eoftap EOFTAP\n#define bsrtap BSRTAP\n#define bnseek BNSEEK\n#define bsrfil BSRFIL\n#define bsftap BSFTAP\n#define fsftap FSFTAP\n#define catoi  CATOI\n\n#elif defined (__sgi) || defined (__sun) || defined (__alpha) || defined (__linux)\n\n#define copen copen_\n#define cclose cclose_\n#define bnread bnread_\n#define bnwrit bnwrit_\n#define bsrtap bsrtap_\n#define bnseek bnseek_\n#define rewtap rewtap_\n#define eoftap eoftap_\n#define bsrfil bsrfil_\n#define bsftap bsftap_\n#define fsftap fsftap_\n#define catoi  catoi_\n\n#elif defined (IBM) || defined (HP)\n\n#define copen copen\n#define cclose cclose\n#define bnread bnread\n#define bnwrit bnwrit\n#define bsrtap bsrtap\n#define bnseek bnseek\n#define rewtap rewtap\n#define eoftap eoftap\n#define bsrfil bsrfil\n#define bsftap bsftap\n#define fsftap fsftap\n#define catoi  catoi\n\n#endif\n\n#include <stdio.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <unistd.h>\n/* #include <sys/mtio.h> */\n#include <sys/ioctl.h>\n#include <sys/uio.h>\n\n/* ****************************************************************** */\n\ncopen(nunit, name, mode, err, oflag)\n /*\n  * nunit = UNIX file descriptor associated with file named *name*\n  * name  = UNIX file name \n  * mode  = 0 : write only - file will be created if it doesn't exist, \n                           - otherwise will be rewritten\n          = 1 : read only\n          = 2 : read/write\n  * err   = 0 : no error opening file.\n         != 0 : Error opening file\n  * oflag = 0 : no notification if file opened OK \n          = 1 : file name and unit number printed\n  */\n\n#if defined (__sgi) && defined (BIT64)\n    int64_t          *nunit;\n    int64_t          *mode;\n    int64_t          *err;\n    int64_t          *oflag;\n#else\n    int          *nunit;\n    int          *mode;\n    int          *err;\n    int          *oflag;\n#endif\n    char         name[120];\n\n{\n    int             fd, i;\n    char            fname[120];\n    extern int      errno;\t/* I/O error return */\n\n    /* strip trailing blanks and add null character to name */\n    for (i = 0; name[i] != ' ' && name[i] != '\\0' && i < 120; ++i)\n\tfname[i] = name[i];\n    fname[i] = '\\0';\n\n    if (*oflag != 0) {\n\tprintf(\"Copen: File = %s\\n\", fname);\n    }\n\n/* if (*mode == 0)    WRITE ONLY\n   printf (\"UNIX File descriptor: %d\\n\", fd = open (fname, O_WRONLY));\n     printf (\"UNIX File descriptor: %d\\n\", fd = creat (fname, 0777));\n   else if (*mode == 1)   READ ONLY\n     printf (\"UNIX File descriptor: %d\\n\", fd = open (fname, O_RDONLY));\n   else   READ/WRITE\n     printf (\"UNIX File descriptor: %d\\n\", fd = open (fname, O_RDWR));*/\n\n    if (*mode == 0) {\t\t/* WRITE ONLY */\n\tfd = creat(fname, 0777);\n    }\n    else if (*mode == 1) {\t/* READ ONLY */\n\tfd = open(fname, O_RDONLY);\n    }\n    else {\t\t\t/* READ/WRITE */\n\tfd = open(fname, O_RDWR);\n    }\n\n    if (*oflag != 0)\n\tprintf(\"UNIX File descriptor: %d\\n\\n\", fd);\n\n    if (fd == -1) {\t\t/* error opening file */\n\tprintf(\"Error opening '%s'  Error status: %d\\n\", fname, errno);\n\tperror(\"copen.c\");\n\t*err = errno;\n    }\n    else {\n      *err = 0;\n      *nunit = fd;\n    }\n\n    return(0);\n}\n\n/* ****************************************************************** */\nbnseek(fd, bread, mode, iprint)\n\n/*  Move the read/write file pointer\n       fd     : Unix file descriptor.\n       bread  : Number of bytes to move the pointer.\n       mode   : How to move the pointer:\n               = 0 : move the pointer ahead BREAD bytes.\n               < 0 : move the pointer to location BREAD.\n               > 0 : move the pointer to the end + BREAD bytes. (?)\n       iprint : Flag to turn on (iprint = 1)  or off (iprint = 0) print.\n\n   Location 0 [bnseek(fd,0,-1,0)] puts us just before the first byte, \n   so the next bnread will get byte 1.\n*/\n\n    int            *fd, *bread, *mode, *iprint;\n\n{\n    off_t           i, offset;\n    int             how_to_space;\n\n    if (*mode == 0)\n\thow_to_space = SEEK_CUR;\n    else if (*mode < 0)\n\thow_to_space = SEEK_SET;\n    else\n\thow_to_space = SEEK_END;\n\n    offset = *bread;\n    i = lseek(*fd, offset, how_to_space);\n    if (*iprint != 0) \n       printf(\" lseek return=%d, *mode=%d\\n\", i, *mode);\n\n    return(0);\n}\n\n/* ****************************************************************** */\n\nbnread(fd, buf, nbuf, bread, ios, idiag)\n /*\n  * fd = UNIX file descriptor number (NOT a Fortran unit) \n  * buf = area into which to read \n  * nbuf = number of bytes to read from fd \n  * bread = number actually read \n  * ios = error number returned to Fortran: \n          1 = End of File\n          2 = Error in reading\n  * idiag : if non-zero, error and EOF messages will be printed\n  */\n\n#if defined (__sgi) && defined (BIT64)\n    int64_t        *fd, *nbuf, buf[], *bread, *ios, *idiag;\n#else\n    int            *fd, *nbuf, buf[], *bread, *ios, *idiag;\n#endif\n\n{\n    int             bytesread;\n\n    /* printf (\"BNREAD Fd = %d Nbuf = %d\\n\", *fd, *nbuf); */\n    bytesread = read(*fd, buf, *nbuf);\n    /* printf (\"Bytes %d   stat %d\\n\", bytesread, errno);  */\n\n    if (bytesread == -1) {\t/* error reading file */\n\tif (*idiag != 0)\n\t    printf(\"Error reading C unit %d\\n\", *fd);\n\tperror(\"bnread.c\");\n\t*ios = 2;\n\t/*  *ios = errno; */\n    } else if (bytesread == 0) {/* end-of-file on input */\n\tif (*idiag != 0)\n\t    printf(\"End of file on C unit %d\\n\", *fd);\n            *ios = 1; \n\t/*  *ios = errno; */\n    } else {\t\t\t/* read OK */\n\n\t/*\n\t * printf (\"BNREAD - bytes read = %d   Buf = %d %d %d\\n\", bytesread,\n\t * buf[0], buf[1], buf[2]);\n\t */\n\t*ios = 0;\n    };\n\n    *bread = bytesread;\n    return(0);\n}\n\n/* ****************************************************************** */\n\nbnwrit(fd, buf, nbuf, bwritten, err, idiag)\n    int            *fd, *nbuf, buf[], *bwritten, *err, *idiag;\n\n /*\n  * fd = UNIX file descriptor number (NOT a Fortran unit) buf = area from\n  * which to write nbuf = number of bytes to write to fd bwritten = number\n  * actually written err = UNIX error number returned to FORTRAN idiag : if\n  * non-zero, error and EOF messages will be printed\n  */\n\n{\n    int             byteswritten;\n\n    /*\n     * printf (\"BNWRIT Fd = %d Nbuf = %d   Buf = %d %d %d\\n\", fd, *nbuf,\n     * buf[0], buf[1], buf[2]);\n     */\n    byteswritten = write(*fd, buf, *nbuf);\n    /* printf (\"Bytes %d   stat %d\\n\", byteswritten, errno);  */\n\n    *err = 0;\n    if (byteswritten == -1) {\t/* error writing file */\n\tif (*idiag != 0)\n\t    printf(\"Error writing C unit %d\\n\", *fd);\n\tperror(\"bnwrit.c\");\n\t*err = errno;\n    };\n\n    *bwritten = byteswritten;\n    return(0);\n}\n\n/* ****************************************************************** */\n\ncclose(nunit, iprint, err)\n/*\nClose a C (UNIX?) file descriptor:\n  nunit  : (INPUT)  : The C (UNIX?) file descriptor to close.\n  iprint : (INPUT)  : Print flag ( iprint == 0 : no print on successful close)\n                                 ( iprint != 0 : Some printout)\n  err    : (OUTPUT) : Error flag ( err = 0 : Successful close)\n                                 ( err = 1 : Error on close)\n     */\n    int            *nunit, *iprint, *err;\n{\n    extern int      errno;\t/* I/O error return */\n    int             istat;\n\n    if ( *iprint != 0 )\n      printf(\"\\n *** CCLOSE : Closing file descriptor: NUNIT = %d \\n\", *nunit);\n\n    istat = close(*nunit);\n    if (istat == 0) {\n      if ( *iprint != 0 )\n\tprintf(\" *** CCLOSE successful: File descriptor: NUNIT = %d \\n\", *nunit);\n    }\n    else\n      printf(\"CCLOSE error: %d : File descriptor NUNIT = %d \\n\", istat, *nunit);\n\n    *err = istat;\n    return(0);\n}\n\n/* ****************************************************************** */\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/decode_jpeg2000.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n\n*/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <jasper/jasper.h>\n\n#if defined (CRAY)\n\n#define info_jpeg2000 INFO_JPEG2000\n#define decode_jpeg2000 DECODE_JPEG2000\n\n#elif defined (__sgi) || defined (__sun) || defined (__alpha) || defined (__linux)\n\n#define info_jpeg2000 info_jpeg2000_\n#define decode_jpeg2000 decode_jpeg2000_\n\n#elif defined (IBM) || defined (HP)\n\n#define info_jpeg2000 info_jpeg2000\n#define decode_jpeg2000 decode_jpeg2000\n\n#endif\n\n\nvoid info_jpeg2000(char *buffer, int *length, int *width, int *height, jas_image_t **image, jas_stream_t **instream) {\n  int fmtid;\n  char *opts=0;\n  jas_image_cmpt_t *pcmpt;\n\n  /* Initialize jasper stuff */\n  jas_init();\n\n  /* open the buffer */\n  if ( ! (*instream = jas_stream_memopen(buffer, *length))) {\n    fprintf(stderr, \"cannot open input buffer\\n\");\n    exit(1);\n  }\n\n  /* Get image format */\n  if ((fmtid = jas_image_getfmt(*instream)) < 0) {\n    fprintf(stderr, \"decode_jpeg2000:  unknown image format:  fmtid = %i\\n\", fmtid);\n    return;\n    exit (1);\n  }\n\n  /* Decode the image. */\n\n  if (!(*image = jpc_decode(*instream, opts))) {\n    fprintf(stderr, \"cannot load image\\n\");\n    exit (1);\n  }\n  pcmpt=(*image)->cmpts_[0];\n  *width = pcmpt->width_;\n  *height = pcmpt->height_;\n}\n\n\nvoid decode_jpeg2000(jas_image_t **image, jas_stream_t **instream, int *width, int *height, int *buf) {\n  /* Call info_jpeg2000_ before calling decode_jpeg2000_ */\n  jas_matrix_t *data;\n  jas_image_cmpt_t *pcmpt;\n  int i, j, k, ierr;\n\n  pcmpt=(*image)->cmpts_[0];\n  data=jas_matrix_create(jas_image_height(*image), jas_image_width(*image));\n  jas_image_readcmpt(*image,0,0,0,jas_image_width(*image), jas_image_height(*image), data);\n  k=0;\n  for (i=0;i<pcmpt->height_;i++) {\n    for (j=0;j<pcmpt->width_;j++) {\n      buf[k++]=data->rows_[i][j];\n    }\n  }\n  jas_matrix_destroy(data);\n  ierr=jas_stream_close(*instream);\n  jas_image_destroy(*image);\n\n}\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/gbytesys.F",
    "content": "!-----------------------------------------------------------------------\n!       Choice of computers\n!-----------------------------------------------------------------------\n!\n!                 CRAY XMP,YMP/UNICOS       (#define CRAY)\n!                 VAX/VMS                   (#define VAX)\n!                 Stardent 1500/3000/UNIX   (#define STARDENT)\n!                 IBM RS/6000-AIX           (#define IBM)\n!                 SUN Sparcstation          (#define SUN)\n!                 SGI Silicon Graphics      (#define SGI)\n!                 HP 7xx                    (#define HP)\n!                 DEC ALPHA                 (#define ALPHA)\n! +------------------------------------------------------------------+\n! _                     SYSTEM DEPENDENT ROUTINES                    _\n! _                                                                  _\n! _    This module contains short utility routines that are not      _\n! _ of the FORTRAN 77 standard and may differ from system to system. _\n! _ These include bit manipulation, I/O, JCL calls, and vector       _\n! _ functions.                                                       _\n! +------------------------------------------------------------------+\n! +------------------------------------------------------------------+\n!\n!          DATA SET UTILITY    AT LEVEL 003 AS OF 02/25/92\nSUBROUTINE GBYTE(IN,IOUT,ISKIP,NBYTE)\n!\n! THIS PROGRAM WRITTEN BY.....\n!             DR. ROBERT C. GAMMILL, CONSULTANT\n!             NATIONAL CENTER FOR ATMOSPHERIC RESEARCH\n!             MAY 1972\n!\n!             CHANGES FOR CRAY Y-MP8/832\n!             CRAY CFT77 FORTRAN\n!             JULY 1992, RUSSELL E. JONES\n!             NATIONAL WEATHER SERVICE\n!\n! THIS IS THE FORTRAN VERSION OF GBYTE\n!\n  INTEGER    IN(*)\n  INTEGER    IOUT\n#if defined (CRAY) || defined (BIT64)\n\n  INTEGER    MASKS(64)\n!\n  DATA  NBITSW/64/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 64 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,  &\n       4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,      &\n       1048575, 2097151, 4194303, 8388607, 16777215, 33554431,       &\n       67108863, 134217727, 268435455, 536870911, 1073741823,        &\n       2147483647, 4294967295, 8589934591, 17179869183,              &\n       34359738367, 68719476735, 137438953471, 274877906943,         &\n       549755813887, 1099511627775, 2199023255551, 4398046511103,    &\n       8796093022207, 17592186044415, 35184372088831,                &\n       70368744177663, 140737488355327, 281474976710655,             &\n       562949953421311, 1125899906842623, 2251799813685247,          &\n       4503599627370495, 9007199254740991, 18014398509481983,        &\n       36028797018963967, 72057594037927935, 144115188075855871,     &\n       288230376151711743, 576460752303423487, 1152921504606846975,  &\n       2305843009213693951, 4611686018427387903, 9223372036854775807, &\n       -1/\n#else\n  INTEGER    MASKS(32)\n!\n  DATA  NBITSW/32/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 32 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, &\n       4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,     &\n       1048575, 2097151, 4194303, 8388607, 16777215, 33554431,      &\n       67108863, 134217727, 268435455, 536870911, 1073741823,       &\n       2147483647, -1/\n#endif\n!\n! NBYTE MUST BE LESS THAN OR EQUAL TO NBITSW\n!\n  ICON   = NBITSW - NBYTE\n  IF (ICON.LT.0) RETURN\n  MASK   = MASKS(NBYTE)\n!\n! INDEX TELLS HOW MANY WORDS INTO THE ARRAY 'IN' THE NEXT BYTE APPEARS.\n!\n  INDEX  = ISKIP / NBITSW\n!\n! II TELLS HOW MANY BITS THE BYTE IS FROM THE LEFT SIDE OF THE WORD.\n!\n  II     = MOD(ISKIP,NBITSW)\n!\n! MOVER SPECIFIES HOW FAR TO THE RIGHT NBYTE MUST BE MOVED IN ORDER\n!    TO BE RIGHT ADJUSTED.\n!\n  MOVER = ICON - II\n!\n  IF (MOVER.GT.0) THEN\n     IOUT  = IAND(ISHFT(IN(INDEX+1),-MOVER),MASK)\n!\n! THE BYTE IS SPLIT ACROSS A WORD BREAK.\n!\n  ELSE IF (MOVER.LT.0) THEN\n     MOVEL = - MOVER\n     MOVER = NBITSW - MOVEL\n     IOUT  = IAND(IOR(ISHFT(IN(INDEX+1),MOVEL),    &\n          &          ISHFT(IN(INDEX+2),-MOVER)),MASK)\n!\n! THE BYTE IS ALREADY RIGHT ADJUSTED.\n!\n  ELSE\n     IOUT  = IAND(IN(INDEX+1),MASK)\n  ENDIF\n!\nEND SUBROUTINE GBYTE\n!\n! +------------------------------------------------------------------+\nSUBROUTINE GBYTES(IN,IOUT,ISKIP,NBYTE,NSKIP,N)\n!\n! THIS PROGRAM WRITTEN BY.....\n!             DR. ROBERT C. GAMMILL, CONSULTANT\n!             NATIONAL CENTER FOR ATMOSPHERIC RESEARCH\n!             MAY 1972\n!\n!             CHANGES FOR CRAY Y-MP8/832\n!             CRAY CFT77 FORTRAN\n!             JULY 1992, RUSSELL E. JONES\n!             NATIONAL WEATHER SERVICE\n!\n! THIS IS THE FORTRAN VERSION OF GBYTES.\n!\n  INTEGER    IN(*)\n  INTEGER    IOUT(*)\n#if defined (CRAY) || defined (BIT64)\n!CDIR$ INTEGER=64\n  INTEGER    MASKS(64)\n!\n  DATA  NBITSW/64/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 64 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,     &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,      &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,       &\n       & 2147483647, 4294967295, 8589934591, 17179869183,             &\n       & 34359738367, 68719476735, 137438953471, 274877906943,        &\n       & 549755813887, 1099511627775, 2199023255551, 4398046511103,   &\n       & 8796093022207, 17592186044415, 35184372088831,               &\n       & 70368744177663, 140737488355327, 281474976710655,            &\n       & 562949953421311, 1125899906842623, 2251799813685247,         &\n       & 4503599627370495, 9007199254740991, 18014398509481983,       &\n       & 36028797018963967, 72057594037927935, 144115188075855871,    &\n       & 288230376151711743, 576460752303423487, 1152921504606846975, &\n       & 2305843009213693951, 4611686018427387903, 9223372036854775807, &\n       & -1/\n#else\n  INTEGER    MASKS(32)\n!\n  DATA  NBITSW/32/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 32 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,   &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,       &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,        &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,         &\n       & 2147483647, -1/\n#endif\n!\n! NBYTE MUST BE LESS THAN OR EQUAL TO NBITSW\n!\n  ICON   = NBITSW - NBYTE\n  IF (ICON.LT.0) RETURN\n  MASK   = MASKS(NBYTE)\n!\n! INDEX TELLS HOW MANY WORDS INTO THE ARRAY 'IN' THE NEXT BYTE APPEARS.\n!\n  INDEX  = ISKIP / NBITSW\n!\n! II TELLS HOW MANY BITS THE BYTE IS FROM THE LEFT SIDE OF THE WORD.\n!\n  II     = MOD(ISKIP,NBITSW)\n!\n! ISTEP IS THE DISTANCE IN BITS FROM THE START OF ONE BYTE TO THE NEXT.\n!\n  ISTEP  = NBYTE + NSKIP\n!\n! IWORDS TELLS HOW MANY WORDS TO SKIP FROM ONE BYTE TO THE NEXT.\n!\n  IWORDS = ISTEP / NBITSW\n!\n! IBITS TELLS HOW MANY BITS TO SKIP AFTER SKIPPING IWORDS.\n!\n  IBITS  = MOD(ISTEP,NBITSW)\n!\n  DO I = 1,N\n!\n! MOVER SPECIFIES HOW FAR TO THE RIGHT A BYTE MUST BE MOVED IN ORDER\n!\n!    TO BE RIGHT ADJUSTED.\n!    TO BE RIGHT ADJUSTED.\n!\n     MOVER = ICON - II\n!\n! THE BYTE IS SPLIT ACROSS A WORD BREAK.\n!\n     IF (MOVER.LT.0) THEN\n        MOVEL   = - MOVER\n        MOVER   = NBITSW - MOVEL\n        IOUT(I) = IAND(IOR(ISHFT(IN(INDEX+1),MOVEL),   &\n             &            ISHFT(IN(INDEX+2),-MOVER)),MASK)\n!\n! RIGHT ADJUST THE BYTE.\n!\n     ELSE IF (MOVER.GT.0) THEN\n        IOUT(I) = IAND(ISHFT(IN(INDEX+1),-MOVER),MASK)\n!\n! THE BYTE IS ALREADY RIGHT ADJUSTED.\n!\n     ELSE\n        IOUT(I) = IAND(IN(INDEX+1),MASK)\n     ENDIF\n!\n! INCREMENT II AND INDEX.\n!\n     II    = II + IBITS\n     INDEX = INDEX + IWORDS\n     IF (II.GE.NBITSW) THEN\n        II    = II - NBITSW\n        INDEX = INDEX + 1\n     ENDIF\n!\n  END DO\nEND SUBROUTINE GBYTES\n!\n! +------------------------------------------------------------------+\nSUBROUTINE SBYTE(IOUT,IN,ISKIP,NBYTE)\n! THIS PROGRAM WRITTEN BY.....\n!             DR. ROBERT C. GAMMILL, CONSULTANT\n!             NATIONAL CENTER FOR ATMOSPHERIC RESEARCH\n!             JULY 1972\n! THIS IS THE FORTRAN VERSIONS OF SBYTE.\n!             FORTRAN 90\n!             AUGUST 1990  RUSSELL E. JONES\n!             NATIONAL WEATHER SERVICE\n!\n! USAGE:    CALL SBYTE (PCKD,UNPK,INOFST,NBIT)\n!\n!   INPUT ARGUMENT LIST:\n!     UNPK     -  NBITS OF THE RIGHT SIDE OF UNPK IS MOVED TO\n!                 ARRAY PCKD. INOFST BITS ARE SKIPPED OVER BEFORE\n!                 THE DATA IS MOVED, NBITS ARE STORED.\n!    INOFST    -  A FULLWORD INTEGER SPECIFYING THE INITAL OFFSET\n!                 IN BITS OF THE FIRST BYTE, COUNTED FROM THE\n!                 LEFTMOST BIT IN PCKD.\n!    NBITS     -  A FULLWORD INTEGER SPECIFYING THE NUMBER OF BITS\n!                 IN EACH BYTE TO BE PACKED.  LEGAL BYTE WIDTHS\n!                 ARE IN THE RANGE 1 - 32.\n!   OUTPUT ARGUMENT LIST:\n!    PCKD      -  THE FULLWORD IN MEMORY TO WHICH PACKING IS TO\n!                 BEGIN STARTING AT BIT INOFST. THE INOSTAT BITS\n!                 ARE NOT ALTERED.\n!\n  INTEGER    IN\n  INTEGER    IOUT(*)\n#if defined (CRAY) || defined (BIT64)\n  INTEGER    MASKS(64)\n!\n  DATA  NBITSW/64/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 64 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,   &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,\t      &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,\t      &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,\t      &\n       & 2147483647, 4294967295, 8589934591, 17179869183,\t\t      &\n       & 34359738367, 68719476735, 137438953471, 274877906943,\t      &\n       & 549755813887, 1099511627775, 2199023255551, 4398046511103,     &\n       & 8796093022207, 17592186044415, 35184372088831,\t\t      &\n       & 70368744177663, 140737488355327, 281474976710655,\t      &\n       & 562949953421311, 1125899906842623, 2251799813685247,\t      &\n       & 4503599627370495, 9007199254740991, 18014398509481983,\t      &\n       & 36028797018963967, 72057594037927935, 144115188075855871,      &\n       & 288230376151711743, 576460752303423487, 1152921504606846975,   &\n       & 2305843009213693951, 4611686018427387903, 9223372036854775807, &\n       & -1/\n#else\n  INTEGER    MASKS(32)\n!\n  DATA  NBITSW/32/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 32 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,   &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,       &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,        &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,         &\n       & 2147483647, -1/\n#endif\n!\n! NBYTE MUST BE LESS THAN OR EQUAL TO NBITSW\n!\n  ICON  = NBITSW - NBYTE\n  IF (ICON.LT.0) RETURN\n  MASK  = MASKS(NBYTE)\n!\n! INDEX TELLS HOW MANY WORDS INTO IOUT THE NEXT BYTE IS TO BE STORED.\n!\n  INDEX = ISKIP / NBITSW\n!\n! II TELLS HOW MANY BITS IN FROM THE LEFT SIDE OF THE WORD TO STORE IT.\n!\n  II    = MOD(ISKIP,NBITSW)\n!\n  J     = IAND(MASK,IN)\n  MOVEL = ICON - II\n!\n! BYTE IS TO BE STORED IN MIDDLE OF WORD.  SHIFT LEFT.\n!\n  IF (MOVEL.GT.0) THEN\n     MSK           = ISHFT(MASK,MOVEL)\n     IOUT(INDEX+1) = IOR(IAND(NOT(MSK),IOUT(INDEX+1)),   &\n          &    ISHFT(J,MOVEL))\n!\n! THE BYTE IS TO BE SPLIT ACROSS A WORD BREAK.\n!\n  ELSE IF (MOVEL.LT.0) THEN\n     MSK           = MASKS(NBYTE+MOVEL)\n     IOUT(INDEX+1) = IOR(IAND(NOT(MSK),IOUT(INDEX+1)),    &\n          &    ISHFT(J,MOVEL))\n     ITEMP         = IAND(MASKS(NBITSW+MOVEL),IOUT(INDEX+2))\n     IOUT(INDEX+2) = IOR(ITEMP,ISHFT(J,NBITSW+MOVEL))\n!\n! BYTE IS TO BE STORED RIGHT-ADJUSTED.\n!\n  ELSE\n     IOUT(INDEX+1) = IOR(IAND(NOT(MASK),IOUT(INDEX+1)),J)\n  ENDIF\n!\nEND SUBROUTINE SBYTE\n!\n! +------------------------------------------------------------------+\nSUBROUTINE SBYTES(IOUT,IN,ISKIP,NBYTE,NSKIP,N)\n! THIS PROGRAM WRITTEN BY.....\n!             DR. ROBERT C. GAMMILL, CONSULTANT\n!             NATIONAL CENTER FOR ATMOSPHERIC RESEARCH\n!             JULY 1972\n! THIS IS THE FORTRAN VERSIONS OF SBYTES.\n!\n!             FORTRAN 90\n!             AUGUST 1990  RUSSELL E. JONES\n!             NATIONAL WEATHER SERVICE\n!\n! USAGE:    CALL SBYTES (PCKD,UNPK,INOFST,NBIT, NSKIP,ITER)\n!\n!   INPUT ARGUMENT LIST:\n!     UNPK     -  NBITS OF THE RIGHT SIDE OF EACH WORD OF ARRAY\n!                 UNPK IS MOVED TO ARRAY PCKD. INOFST BITS ARE\n!                 SKIPPED OVER BEFORE THE 1ST DATA IS MOVED, NBITS\n!                 ARE STORED, NSKIP BITS ARE SKIPPED OVER, THE NEXT\n!                 NBITS ARE MOVED,  BIT ARE SKIPPED OVER, ETC. UNTIL\n!                 ITER GROUPS OF BITS ARE PACKED.\n!    INOFST    -  A FULLWORD INTEGER SPECIFYING THE INITAL OFFSET\n!                 IN BITS OF THE FIRST BYTE, COUNTED FROM THE\n!                 LEFTMOST BIT IN PCKD.\n!    NBITS     -  A FULLWORD INTEGER SPECIFYING THE NUMBER OF BITS\n!                 IN EACH BYTE TO BE PACKED.  LEGAL BYTE WIDTHS\n!                 ARE IN THE RANGE 1 - 32.\n!    NSKIP     -  A FULLWORD INTEGER SPECIFYING THE NUMBER OF BITS\n!                 TO SKIP BETWEEN SUCCESSIVE BYTES.  ALL NON-NEGATIVE\n!                 SKIP COUNTS ARE LEGAL.\n!    ITER      -  A FULLWORD INTEGER SPECIFYING THE TOTAL NUMBER OF\n!                 BYTES TO BE PACKED, AS CONTROLLED BY INOFST,\n!                 NBIT AND NSKIP ABOVE.   ALL NON-NEGATIVE ITERATION\n!                 COUNTS ARE LEGAL.\n!\n!   OUTPUT ARGUMENT LIST:\n!    PCKD      -  THE FULLWORD IN MEMORY TO WHICH PACKING IS TO\n!                 BEGIN STARTING AT BIT INOFST. THE INOSTAT BITS\n!                 ARE NOT ALTERED. NSKIP BITS ARE NOT ALTERED.\n!\n  INTEGER    IN(*)\n  INTEGER    IOUT(*)\n#if defined (CRAY) || defined (BIT64)\n  INTEGER    MASKS(64)\n!\n  DATA  NBITSW/64/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 64 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,     &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,\t\t&\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,\t\t&\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,\t\t&\n       & 2147483647, 4294967295, 8589934591, 17179869183,\t\t\t&\n       & 34359738367, 68719476735, 137438953471, 274877906943,\t\t&\n       & 549755813887, 1099511627775, 2199023255551, 4398046511103,\t&\n       & 8796093022207, 17592186044415, 35184372088831,\t\t\t&\n       & 70368744177663, 140737488355327, 281474976710655,\t\t&\n       & 562949953421311, 1125899906842623, 2251799813685247,\t\t&\n       & 4503599627370495, 9007199254740991, 18014398509481983,\t\t&\n       & 36028797018963967, 72057594037927935, 144115188075855871,\t&\n       & 288230376151711743, 576460752303423487, 1152921504606846975,\t&\n       & 2305843009213693951, 4611686018427387903, 9223372036854775807,   &\n       & -1/\n#else\n  INTEGER    MASKS(32)\n!\n  DATA  NBITSW/32/\n!\n!     MASKS TABLE PUT IN DECIMAL SO IT WILL COMPILE ON ANY 32 BIT\n!     COMPUTER\n!\n  DATA  MASKS / 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047,   &\n       & 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287,       &\n       & 1048575, 2097151, 4194303, 8388607, 16777215, 33554431,        &\n       & 67108863, 134217727, 268435455, 536870911, 1073741823,         &\n       & 2147483647, -1/\n#endif\n!\n! NBYTE MUST BE LESS THAN OR EQUAL TO NBITSW\n!\n  ICON = NBITSW - NBYTE\n  IF (ICON.LT.0) RETURN\n  MASK   = MASKS(NBYTE)\n!\n! INDEX TELLS HOW MANY WORDS INTO IOUT THE NEXT BYTE IS TO BE STORED.\n!\n  INDEX  = ISKIP / NBITSW\n!\n! II TELLS HOW MANY BITS IN FROM THE LEFT SIDE OF THE WORD TO STORE IT.\n!\n  II     = MOD(ISKIP,NBITSW)\n!\n! ISTEP IS THE DISTANCE IN BITS FROM ONE BYTE POSITION TO THE NEXT.\n!\n  ISTEP  = NBYTE + NSKIP\n!\n! IWORDS TELLS HOW MANY WORDS TO SKIP FROM ONE BYTE TO THE NEXT.\n!\n  IWORDS = ISTEP / NBITSW\n!\n! IBITS TELLS HOW MANY BITS TO SKIP AFTER SKIPPING IWORDS.\n!\n  IBITS  = MOD(ISTEP,NBITSW)\n!\n  DO I = 1,N\n     J     = IAND(MASK,IN(I))\n     MOVEL = ICON - II\n!\n! BYTE IS TO BE STORED IN MIDDLE OF WORD.  SHIFT LEFT.\n!\n     IF (MOVEL.GT.0) THEN\n        MSK           = ISHFT(MASK,MOVEL)\n        IOUT(INDEX+1) = IOR(IAND(NOT(MSK),IOUT(INDEX+1)),   &\n             &    ISHFT(J,MOVEL))\n!\n! THE BYTE IS TO BE SPLIT ACROSS A WORD BREAK.\n!\n     ELSE IF (MOVEL.LT.0) THEN\n        MSK           = MASKS(NBYTE+MOVEL)\n        IOUT(INDEX+1) = IOR(IAND(NOT(MSK),IOUT(INDEX+1)),    &\n             &    ISHFT(J,MOVEL))\n        ITEMP         = IAND(MASKS(NBITSW+MOVEL),IOUT(INDEX+2))\n        IOUT(INDEX+2) = IOR(ITEMP,ISHFT(J,NBITSW+MOVEL))\n!\n! BYTE IS TO BE STORED RIGHT-ADJUSTED.\n!\n     ELSE\n        IOUT(INDEX+1) = IOR(IAND(NOT(MASK),IOUT(INDEX+1)),J)\n     ENDIF\n!\n     II    = II + IBITS\n     INDEX = INDEX + IWORDS\n     IF (II.GE.NBITSW) THEN\n        II    = II - NBITSW\n        INDEX = INDEX + 1\n     ENDIF\n!\n  END DO\nEND SUBROUTINE SBYTES\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/get_unused_unit.F",
    "content": "integer function get_unused_unit() result(iunit)\n  implicit none\n  integer :: i\n  logical :: used\n\n  do i = 11, 255\n     inquire(unit=i, opened=used)\n     if (.not. used) then\n        iunit = i\n        return\n     endif\n  enddo\n\n  print*, \"GET_UNUSED_UNIT:  \"\n  print*, \"      Problem getting unused unit number.\"\n  call abort()\n\nend function get_unused_unit\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/io_f.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#ifdef _BZIP_YES\n#include <bzlib.h> \n#endif\n\n#if defined (CRAY)\n\n#define c_gribopen C_GRIBOPEN\n#define c_close C_CLOSE\n#define c_writeopen C_WRITEOPEN\n#define io_fread IO_FREAD\n#define io_fwrite IO_FWRITE\n#define io_fseek IO_FSEEK\n#define io_ftell IO_FTELL\n\n#elif defined (__sgi) || defined (__sun) || defined (__alpha) || defined (__linux)\n\n#define c_gribopen c_gribopen_\n#define c_close c_close_\n#define c_writeopen c_writeopen_\n#define io_fread io_fread_\n#define io_fwrite io_fwrite_\n#define io_fseek io_fseek_\n#define io_ftell io_ftell_\n\n#elif defined (IBM) || defined (HP)\n\n#define c_gribopen c_gribopen\n#define c_close c_close\n#define c_writeopen c_writeopen\n#define io_fread io_fread\n#define io_fwrite io_fwrite\n#define io_fseek io_fseek\n#define io_ftell io_ftell\n\n#endif\n\n\nstruct GribFileInfo {\n  FILE *fd;\n  int compression;\n#ifdef _BZIP_YES\n  BZFILE* b;\n#endif\n\n};\n\nvoid c_gribopen(char *filename, struct GribFileInfo **GFPTR, int *ierr) {\n/* \n   Purpose:\n   \n      Open a file for reading.\n\n   Input:\n\n      filename:  The (null-terminated) name of the file to open.\n\n   Output:\n \n      GFPTR:  A pointer to a structure containing various file metadata,\n              including the all important FILE pointer.\n\n      ierr:   An error status flag.  ierr == 0 -- File opened successfully.\n                                     ierr == 1 -- Unsuccessful attempt to open the file\n                                                  (reason for failure undetermined).\n\n   Side effects:\n\n      The file is opened, and the file stream pointer is positioned at\n      the beginning of the file.  A determination is made (based on\n      file suffix) on whether the file is bzip2-compressed or not.  If\n      the file is bzip2-compressed, the file is opened for BZIP2\n      sequential reading.\n\n*/\n\n\n  struct GribFileInfo *lg;\n  \n  /* Allocate space for my new GribFileInfo structure */\n  lg = (struct GribFileInfo*) calloc(1,sizeof(struct GribFileInfo));\n\n  /* Open the file, setting the FILE pointer in my new GribFileInfo structure */\n  lg->fd = fopen(filename, \"r\");\n  if (! lg->fd) {\n    *ierr = 1;\n  }\n  else {\n    *ierr = 0;\n  }\n\n#ifdef _BZIP_YES\n  /* If the file ends in \".bz2\", assume it is a bzip2-compressed file, and */\n  /* initialize things for reading a bzip2-compressed file.                */\n  \n  if (strstr(filename,\".bz2\\0\")) {\n    int bzerror;\n    int verbosity = 1;\n    int small = 0;\n    /*  printf(\"BZIP2 compressed file.\\n\"); */\n    lg->b = BZ2_bzReadOpen( &bzerror, lg->fd, verbosity, small, NULL, 0 );\n    if ( bzerror != BZ_OK ) {\n      BZ2_bzReadClose ( &bzerror, lg->b );\n      printf (\"Problem BZopen.\\n\");\n      exit (1);\n    }\n    lg->compression = 2;\n  }\n  else {\n    lg->compression = 0;\n  }\n#else\n  lg->compression = 0;\n#endif\n\n  /*  printf(\"c_gribopen:  lg->fd = %lu\\n\", lg->fd); */\n  *GFPTR = lg;\n}\n\nvoid c_writeopen(char *filename, struct GribFileInfo **GFPTR) {\n  struct GribFileInfo *lg;\n  lg = (struct GribFileInfo*) calloc(1,sizeof(struct GribFileInfo));\n  lg->fd = fopen(filename, \"w\");\n}\n\nvoid c_close(struct GribFileInfo **GFPTR) {\n  int bzerror;\n  int ierr;\n  switch ((*GFPTR)->compression) {\n  default:\n    printf(\"Unrecognized compression:  %i\\n\",(*GFPTR)->compression);\n    exit (1);\n#ifdef _BZIP_YES\n  case 2:\n    BZ2_bzReadClose ( &bzerror, (*GFPTR)->b );\n    if ( bzerror != BZ_OK ) {\n      printf (\"Problem with call to BZ2_bz_ReadClose.\\n\");\n      exit (1);\n    }\n    fclose((*GFPTR)->fd);\n    free((*GFPTR));\n    break;\n#endif\n  case 0:\n    ierr = fclose((*GFPTR)->fd);\n    if (ierr) {\n      printf(\"close error:  %i\\n\", ierr);\n      exit (1);\n    }\n    free((*GFPTR));\n    break;\n  }\n}\n\nvoid io_fread(struct GribFileInfo **GFPTR, char *buf, int *nread, int *iread, int *ierr) {\n  int read_return;\n  int bzerror;\n  /*  printf(\"io_fread:  GFPTR->fd = %lu\\n\", (*GFPTR)->fd); */\n  \n  switch ((*GFPTR)->compression) {\n  default:\n    printf(\"Unrecognized compression:  %i\\n\",(*GFPTR)->compression);\n    exit (1);\n#ifdef _BZIP_YES\n  case 2:\n    read_return = BZ2_bzRead ( &bzerror, (*GFPTR)->b, buf, *nread );\n    break;\n#endif\n  case 0:\n    read_return = fread(buf, 1, *nread, (*GFPTR)->fd);\n    break;\n  }\n  if (read_return != *nread) {\n    *iread = read_return;\n    *ierr = 1;\n  }\n  else {\n    *ierr = 0;\n    *iread = read_return;\n  }\n  return;\n}\n\nvoid io_fwrite(struct GribFileInfo **GFPTR, char *buf, int *nwrite, int *ierr) {\n\n  int write_return;\n  write_return = fwrite(buf, 1, *nwrite, (*GFPTR)->fd);\n  if (write_return != *nwrite) {\n    *ierr = 1;\n  }\n  else {\n    *ierr = 0;\n  }\n}\n\nvoid io_fseek(struct GribFileInfo **GFPTR, int *nbytes, int *mode) {\n  int iseek;\n  printf(\"No fseek!\\n\");\n  exit (1);\n  switch (*mode) {\n  case 0:\n    iseek = fseek((*GFPTR)->fd, *nbytes, SEEK_CUR);\n    break;\n  case 1:\n    iseek = fseek((*GFPTR)->fd, *nbytes, SEEK_SET);\n    break;\n  case 2:\n    iseek = fseek((*GFPTR)->fd, *nbytes, SEEK_END);\n    break;\n  default:\n    printf(\"io_fseek_:  Unrecognized mode:  %i\\n\", *mode);\n    exit (1);\n  }\n\n  if (iseek != 0) {\n    printf(\"io_fseek_:  Seek problem.\\n\");\n    exit (1);\n  }\n\n}\n\nvoid io_ftell(struct GribFileInfo **GFPTR, long *itell) {\n  *itell = ftell((*GFPTR)->fd);\n  if (itell < 0) {\n    printf(\"io_ftell_:  Problem from ftell.\\n\");\n    exit (1);\n  }\n}\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/kwm_date_utilities.F",
    "content": "module kwm_date_utilities\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n!  From old date ('YYYY-MM-DD HH:MM:SS.ffff') and\n!  delta-time, compute the new date.\n\n!  on entry     -  odate  -  the old hdate.\n!                  idt    -  the change in time\n\n!  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n\n!  Local Variables\n\n!  yrold    -  indicates the year associated with \"odate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scold    -  indicates the second associated with \"odate\"\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n\n!  mday     -  a list assigning the number of days in each month\n\n!  i        -  loop counter\n!  nday     -  the integer number of days represented by \"idt\"\n!  nhour    -  the integer number of hours in \"idt\" after taking out\n!              all the whole days\n!  nmin     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days and whole hours.\n!  nsec     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days, whole hours, and whole minutes.\n\n    integer :: nlen, olen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n\n    logical :: punctuated\n    logical :: idtdy, idthr, idtmin, idtsec, idtfrac\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n!  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    olen = len(odate)\n    if (punctuated) then\n       if (olen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n    endif\n\n!  Use internal READ statements to convert the CHARACTER string\n!  date into INTEGER components.\n\n    idtdy   = .FALSE.\n    idthr   = .FALSE.\n    idtmin  = .FALSE.\n    idtsec  = .FALSE.\n    idtfrac = .FALSE.\n    read(odate(1:4),  '(i4)') yrold\n    if (punctuated) then\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.13) then\n          idthr = .TRUE.\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             idtmin = .TRUE.\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                idtsec = .TRUE.\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   idtfrac = .TRUE.\n                   read(odate(21:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    else ! Not punctuated\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       idtdy = .TRUE.\n       if (olen.ge.10) then\n          idthr = .TRUE.\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             idtmin = .TRUE.\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                idtsec = .TRUE.\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   idtfrac = .TRUE.\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n!  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'WARNING: GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n!  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'WARNING: GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'WARNING: GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'WARNING: GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'WARNING: GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n!  Check that the fractional part  of ODATE makes sense.\n\n!KWM      IF ((scold.GT.59).or.(scold.LT.0)) THEN\n!KWM         WRITE(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n!KWM         opass = .FALSE.\n!KWM      END IF\n\n    if (.not.opass) then\n       write(*,*) 'WARNING: Crazy ODATE: ', odate(1:olen), olen\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n\n!  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (idtfrac) then !idt should be in fractions of seconds\n       if (punctuated) then\n          ifrc = olen-14\n       else\n          ifrc = olen-20\n       endif\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (idtsec) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (idtmin) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (idthr) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (idtdy) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''WARNING: GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            olen\n       write(*,*) odate(1:olen)\n       call abort()\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n!  Now construct the new mdate\n\n    nlen = LEN(ndate)\n\n    if (punctuated) then\n\n       if (nlen.gt.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:19)//'.'//hfrc(31-nlen:10)\n\n       else if (nlen.eq.19.or.nlen.eq.20) then\n          write(ndate(1:19),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n          if (nlen.eq.20) ndate = ndate(1:19)//'.'\n\n       else if (nlen.eq.16) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (nlen.eq.13) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n       if (olen.ge.11) ndate(11:11) = sp\n\n    else\n\n       if (nlen.gt.20) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:18)//hfrc(31-nlen:10)\n\n       else if (nlen.eq.14) then\n          write(ndate(1:14),14) yrnew, monew, dynew, hrnew, minew, scnew\n14        format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.12) then\n          write(ndate,12) yrnew, monew, dynew, hrnew, minew\n12        format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.10) then\n          write(ndate,210) yrnew, monew, dynew, hrnew\n210       format(i4,i2.2,i2.2,i2.2)\n\n       else if (nlen.eq.8) then\n          write(ndate,8) yrnew, monew, dynew\n8         format(i4,i2.2,i2.2)\n\n       else\n          stop \"FATAL ERROR: In module kwm_date_utilities.F -- DATELEN PROBLEM\"\n       end if\n    endif\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n    implicit none\n\n!  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n!  compute the time difference.\n\n!  on entry     -  newdate  -  the new hdate.\n!                  olddate  -  the old hdate.\n\n!  on exit      -  idt    -  the change in time.\n!                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n!  Local Variables\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  yrold    -  indicates the year associated with \"odate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n!  scold    -  indicates the second associated with \"odate\"\n!  i        -  loop counter\n!  mday     -  a list assigning the number of days in each month\n\n! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    character (len=24) :: tdate\n    integer :: olen, nlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: mday(12), i, newdys, olddys\n    logical :: npass, opass\n    integer :: isign\n    integer :: ifrc\n\n    logical :: punctuated\n\n    olen = len(olddate)\n    nlen = len(newdate)\n    if (nlen.ne.olen) then\n       write(*,'(\"WARNING: GETH_IDTS: NLEN /= OLEN: \", A, 3x, A)') newdate(1:nlen), olddate(1:olen)\n       call abort\n    endif\n\n    if (olddate.gt.newdate) then\n       isign = -1\n\n       ifrc = olen\n       olen = nlen\n       nlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       isign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n!  Assign the number of days in a months\n\n    mday( 1) = 31\n    mday( 2) = 28\n    mday( 3) = 31\n    mday( 4) = 30\n    mday( 5) = 31\n    mday( 6) = 30\n    mday( 7) = 31\n    mday( 8) = 31\n    mday( 9) = 30\n    mday(10) = 31\n    mday(11) = 30\n    mday(12) = 31\n\n!  Determine if the date is \"punctuated\" or just a string of numbers.\n    if ( odate(5:5) == \"-\") then\n       punctuated = .TRUE.\n    else\n       punctuated = .FALSE.\n    endif\n\n\n!  Break down old and new hdates into parts\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(odate(1:4),  '(i4)') yrold\n    read(ndate(1:4),  '(i4)') yrnew\n\n    if (punctuated) then\n\n!  Break down old hdate into parts\n\n       read(odate(6:7),  '(i2)') moold\n       read(odate(9:10), '(i2)') dyold\n       if (olen.ge.13) then\n          read(odate(12:13),'(i2)') hrold\n          if (olen.ge.16) then\n             read(odate(15:16),'(i2)') miold\n             if (olen.ge.19) then\n                read(odate(18:19),'(i2)') scold\n                if (olen.gt.20) then\n                   if (olen.eq.21) then\n                      read(odate(21:21),'(i1)') frold\n                   else if (olen.eq.22) then\n                      read(odate(21:22),'(i2)') frold\n                   else if (olen.eq.23) then\n                      read(odate(21:23),'(i3)') frold\n                   else if (olen.eq.24) then\n                      read(odate(21:24),'(i4)') frold\n                   endif\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(6:7),  '(i2)') monew\n       read(ndate(9:10), '(i2)') dynew\n       if (nlen.ge.13) then\n          read(ndate(12:13),'(i2)') hrnew\n          if (nlen.ge.16) then\n             read(ndate(15:16),'(i2)') minew\n             if (nlen.ge.19) then\n                read(ndate(18:19),'(i2)') scnew\n                if (nlen.gt.20) then\n                   read(ndate(21:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    else\n\n!  Break down old hdate into parts\n\n       read(odate(5:6),  '(i2)') moold\n       read(odate(7:8), '(i2)') dyold\n       if (olen.ge.10) then\n          read(odate(9:10),'(i2)') hrold\n          if (olen.ge.12) then\n             read(odate(11:12),'(i2)') miold\n             if (olen.ge.14) then\n                read(odate(13:14),'(i2)') scold\n                if (olen.ge.15) then\n                   read(odate(15:olen),*) frold\n                end if\n             end if\n          end if\n       end if\n\n!  Break down new hdate into parts\n\n       read(ndate(5:6),  '(i2)') monew\n       read(ndate(7:8), '(i2)') dynew\n       if (nlen.ge.10) then\n          read(ndate(9:10),'(i2)') hrnew\n          if (nlen.ge.12) then\n             read(ndate(11:12),'(i2)') minew\n             if (nlen.ge.14) then\n                read(ndate(13:14),'(i2)') scnew\n                if (nlen.ge.15) then\n                   read(ndate(15:nlen),*) frnew\n                end if\n             end if\n          end if\n       end if\n    endif\n\n!  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n!  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n       print*, 'GETH_IDTS:  Month of NDATE = ', monew\n       npass = .false.\n    end if\n\n!  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n       opass = .false.\n    end if\n\n!  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    endif\n\n!  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    end if\n\n!  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n       npass = .false.\n    end if\n\n!  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n       opass = .false.\n    end if\n\n!  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n       npass = .false.\n    end if\n\n!  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n       opass = .false.\n    end if\n\n!  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n       npass = .false.\n    end if\n\n!  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'Screwy NDATE: ', ndate(1:nlen)\n       call abort()\n    end if\n\n    if (.not. opass) then\n       print*, 'Screwy ODATE: ', odate(1:olen)\n       call abort()\n    end if\n\n!  Date Checks are completed.  Continue.\n\n!  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n!  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n!  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (punctuated) then\n       if (olen.gt.10) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.13) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.16) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.20) then\n                   ifrc = olen-20\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    else\n       if (olen.gt.8) then\n          idt = idt*24 + (hrnew - hrold)\n          if (olen.gt.10) then\n             idt = idt*60 + (minew - miold)\n             if (olen.gt.12) then\n                idt = idt*60 + (scnew - scold)\n                if (olen.gt.14) then\n                   ifrc = olen-14\n                   ifrc = 10**ifrc\n                   idt = idt * ifrc + (frnew-frold)\n                endif\n             endif\n          endif\n       endif\n    endif\n\n    if (isign .eq. -1) then\n       idt = idt * isign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n!\n! Compute the number of days in February for the given year.\n!\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n!\n! Compute the number of days in the month of given date hdate.\n!\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    if (hdate(5:5) == \"-\") then\n       read(hdate(1:7), '(I4,1x,I2)') year, month\n    else\n       read(hdate(1:6), '(I4,I2)') year, month\n    endif\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\nend module kwm_date_utilities\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/kwm_grid_utilities.F",
    "content": "module kwm_grid_utilities\n  private :: oned\ncontains\n\n  real function bint(array, ix, jx, x, y) result(val)\n    implicit none\n!\n!  Overlapping parabolic interpolation of array to point x, y.\n!\n    integer, intent(in)                   :: ix, jx\n    real   , intent(in), dimension(ix,jx) :: array\n    real   , intent(in)                   :: x, y\n\n    real, dimension(4,4) :: STL\n    integer :: I, J, K, KK, L, LL\n    real    :: XX, YY, A, B, C, D, E, F, G, H\n\n    if ((X < 2) .or. (Y < 2) .or. (X > IX-1) .or. (Y > JX-1)) then\n       val = -1.E36\n       return\n    endif\n\n    I = int(X)\n    J = int(Y)\n    XX = X-I\n    YY = Y-J\n!    IF(ABS(XX) <= 0.0001 .and. ABS(YY) <= 0.0001) THEN\n!       val = array(i,j)\n!       RETURN\n!    ENDIF\n\n    STL = ARRAY( I-1:I+2 , J-1:J+2 )\n\n    A = ONED(XX,STL(1,1),STL(2,1),STL(3,1),STL(4,1))\n    B = ONED(XX,STL(1,2),STL(2,2),STL(3,2),STL(4,2))\n    C = ONED(XX,STL(1,3),STL(2,3),STL(3,3),STL(4,3))\n    D = ONED(XX,STL(1,4),STL(2,4),STL(3,4),STL(4,4))\n    val = ONED(YY,A,B,C,D)\n\n  end function bint\n\n  real function bint_p(array, ix, jx, x, y) result(val)\n    implicit none\n!\n!  Overlapping parabolic interpolation of array to point x, y.\n!\n    integer, intent(in)                            :: ix, jx\n    real   , pointer, dimension(:,:)               :: array\n    real   , intent(in)                            :: x, y\n\n    real, dimension(4,4) :: STL\n    integer :: I, J, II, JJ, L, LL\n    real    :: XX, YY, A, B, C, D, E, F, G, H\n    integer :: number_good  ! Barlage\n\n!KWM    if ((X < 1) .or. (Y < 1) .or. (X > IX) .or. (Y > JX)) then\n!KWM       val = -1.E36\n!KWM       return\n!KWM    endif\n\n    I = int(X)\n    J = int(Y)\n    XX = X-I\n    YY = Y-J\n\n!    IF(ABS(XX) <= 0.0001 .and. ABS(YY) <= 0.0001) THEN\n!       val = array(i,j)\n!       RETURN\n!    ENDIF\n\n    do II = -1, 2\n       do JJ = -1, 2\n          if ((I+II<1) .or. (I+II>IX).or. (J+JJ<1) .or. (J+JJ>JX)) then\n             STL(II+2,JJ+2) = -1.E36\n          else\n             STL(II+2,JJ+2) = ARRAY(I+II,J+JJ)\n          endif\n       enddo\n    enddo\n\n    ! STL = ARRAY( I-1:I+2 , J-1:J+2 )\n\n    ! if (ANY(STL<-1.E25)) then\n    !    val = -1.E36\n    !    return\n    ! endif\n\n    ! Corner points missing are OK.  Any other points missing and we have a problem.\n    if ((ANY(STL(:,2:3)<-1.E25)) .or. (ANY(STL(2:3,:)<-1.E25))) then\n\n    ! Barlage 20150522: if this is violated, send back the average if any points are\n    !                   valid, this could prevent problems if close to source boundary\n\n      if (ANY(STL > -1.E25)) then\n        val = sum(STL, MASK = STL > -1.E25)\n        number_good = count(STL > -1.E25)\n\tval = val / number_good\n      else\n       val = -1.E36\n      end if\n\n      return\n    endif\n\n!KWM    do JJ = 4, 1, -1\n!KWM       print*, (STL(II,JJ),II=1,4)\n!KWM    enddo\n!KWM    print*, '-----------------------------------'\n\n    A = ONED(XX,STL(1,1),STL(2,1),STL(3,1),STL(4,1))\n    B = ONED(XX,STL(1,2),STL(2,2),STL(3,2),STL(4,2))\n    C = ONED(XX,STL(1,3),STL(2,3),STL(3,3),STL(4,3))\n    D = ONED(XX,STL(1,4),STL(2,4),STL(3,4),STL(4,4))\n    val = ONED(YY,A,B,C,D)\n\n    if (ANY(STL<-1.E25)) then\n\n       E = ONED(YY,STL(1,1),STL(1,2),STL(1,3),STL(1,4))\n       F = ONED(YY,STL(2,1),STL(2,2),STL(2,3),STL(2,4))\n       G = ONED(YY,STL(3,1),STL(3,2),STL(3,3),STL(3,4))\n       H = ONED(YY,STL(4,1),STL(4,2),STL(4,3),STL(4,4))\n       val = 0.5 * (val + ONED(XX,E,F,G,H))\n    endif\n\n    ! Constrain the results to fall between the original min and maximum of the 16 points\n    val = min(val, maxval(STL))\n    val = max(val, minval(STL))\n\n  end function bint_p\n\n  REAL FUNCTION ONED(X,A,B,C,D) result(val)\n    ! Points B and C must have good data.\n    ! Points A and D may have the no-data indication (value less than -1.E25)\n    implicit none\n    real, intent(in) :: X, A, B, C, D\n\n    if (B < -1.E25) stop \"FATAL ERROR: In kwm_grid_utilities.F -- Point B in ONED\"\n    if (C < -1.E25) stop \"FATAL ERROR: In kwm_grid_utilities.F -- Point C in ONED\"\n\n    IF (abs(X) < 1.E-5) then\n       val = B\n    else if (abs(X-1.) < 1.E-5) then\n       val = C\n    else\n\n       if ((A<-1.E25).and.(D<-1.E25)) then\n          ! Points A and D have the no-data flag.\n          val = (B*(1.0-X)) + (C*X)\n       else if (D<-1.E25) then\n          ! No-data flag at point D.  Point A is good (or the previous If-test would have caught it).\n          val = B+X*(0.5*(C-A)+X*(0.5*(C+A)-B))\n       else if (A<-1.E25) then\n          ! No-data flag at point A.  Point D is good (or the earlier If-test would have caught it).\n          val = C+(1.0-X)*(0.5*(B-D)+(1.0-X)*(0.5*(B+D)-C))\n       else\n          ! All four points have good data\n          val = (1.0-X)*(B+X*(0.5*(C-A)+X*(0.5*(C+A)-B)))+X*(C+(1.0-X)*(0.5 &\n               *(B-D)+(1.0-X)*(0.5*(B+D)-C)))\n       endif\n\n    endif\n  END FUNCTION ONED\n\n  real function four_point(array, ix, jx, x, y) result(val)\n\n!*****************************************************************************!\n! Performs a 4-point interpolation to a given (x,y) coordinate in an array.   !\n! The X coordinate corresponds to the first dimension of array ARRAY.         !\n! The Y coordinate corresponds to the second dimension of array ARRAY.        !\n! For points outside the domain, the return value is -1.E36.                  !\n!*****************************************************************************!\n\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, intent(in), dimension(ix,jx) :: array\n    real, intent(in) :: x, y\n\n    integer :: i, j, ip, jp\n    real :: dx, dy, rx, ry\n\n    if (((x-ix)>1.E-4) .or. ((y-jx)>1.E-4) .or. (x < 0.99999) .or. (y < 0.99999)) then\n       if((x-ix)>1.E-5)  print*, 'x, ix = ', x, ix, ((x-ix)>1.E-5), (x-ix)\n       if ( y < 0.99999) print*, 'y = ', y\n       val = -1.E36\n    else\n       i = int(x+1.E-5)\n       j = int(y+1.E-5)\n\n       ! The following MAX test should be safe, since we've already checked\n       ! that we're not too much less than 1.0\n       i = max(i, 1)\n       j = max(j, 1)\n\n       dx = x-i\n       dy = y-j\n       if (dx < 1.E-4) dx = 0.0\n       if (dx > 0.9999) dx = 1.0\n       if (dy < 1.E-4) dy = 0.0\n       if (dy > 0.9999) dy = 1.0\n       rx = 1.0 - dx\n       ry = 1.0 - dy\n\n       ! The following MIN test should be safe, since we've already\n       ip = min(i+1, ix)\n       jp = min(j+1, jx)\n\n       if (ANY(array(i:ip,j:jp)<-1.E25)) then\n          val = -1.E36\n          return\n       endif\n\n\n!KWM       print*, 'ip, jp = ', ip, jp\n!KWM       print*, 'i, j = ', i, j\n!KWM       print*, 'rx, ry, dx, dy = ', rx, ry, dx, dy\n\n       val= array(i ,j )*RY*RX + &\n            array(ip,j )*RY*DX + &\n            array(i ,jp)*DY*RX + &\n            array(ip,jp)*DY*DX\n    endif\n\n  end function four_point\n\n\n\n  real function four_point_p(array, ix, jx, x, y) result(val)\n\n!*****************************************************************************!\n! Performs a 4-point interpolation to a given (x,y) coordinate in an array.   !\n! The X coordinate corresponds to the first dimension of array ARRAY.         !\n! The Y coordinate corresponds to the second dimension of array ARRAY.        !\n! For points outside the domain, the return value is -1.E36.                  !\n!*****************************************************************************!\n\n    implicit none\n    integer, intent(in) :: ix, jx\n    real, pointer, dimension(:,:) :: array\n    real, intent(in) :: x, y\n\n    integer :: i, j\n    real :: dx, dy, rx, ry\n\n    if ((x > ix) .or. (y > jx) .or. (x < 1) .or. (y < 1)) then\n       val = -1.E36\n    else\n       i = int(x)\n       j = int(y)\n       dx = x-i\n       dy = y-j\n       rx = 1.0 - dx\n       ry = 1.0 - dy\n\n       val= array(i  ,j  )*RY*RX + &\n            array(i+1,j  )*RY*DX + &\n            array(i  ,j+1)*DY*RX + &\n            array(i+1,j+1)*DY*DX\n    endif\n\n  end function four_point_p\n\n   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n   ! Name: wt_sixteen_pt_average\n   !\n   ! Purpose: Weighted average of sixteen surrounding grid point values\n   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n   real function wt_sixteen_pt_average(array, nx, ny, x, y, msgvalin, msgvalout) result(val)\n\n      implicit none\n\n      ! Arguments\n      integer, intent(in) :: nx, ny\n      real, pointer, dimension(:,:) :: array\n      real, intent(in) :: x, y               ! The location to interpolate to\n      real, intent(in) :: msgvalin,msgvalout\n\n      ! Local variables\n      integer :: i, j, ifx, ify\n      integer :: arrayistart,arrayiend,arrayjstart,arrayjend\n      integer :: subistart,subiend,subjstart,subjend\n      real :: sum, sum_weight, pcoef\n      real, dimension(4,4) :: distance\n      real, dimension(4,4) :: weights\n      real, dimension(4,4) :: subset\n\n      ifx = floor(x)\n      ify = floor(y)\n\n      ! First see whether the point is far enough within the array to\n      !   allow for a sixteen point average. If not, fill with missing values.\n      if (ifx < 2 .or. ifx > nx-2 .or. ify < 2 .or. ify > ny-2) then\n         subset = msgvalin\n\t arrayistart = max(ifx-1,1)\n\t arrayiend = min(ifx+2,nx)\n\t arrayjstart = max(ify-1,1)\n\t arrayjend = min(ify+2,ny)\n\t subistart = 1\n\t subiend = 4\n\t subjstart = 1\n\t subjend = 4\n         if (ifx < 2)    subistart = 4 - (arrayiend - arrayistart)\n         if (ifx > nx-2) subiend   = arrayiend - arrayistart + 1\n         if (ify < 2)    subjstart = 4 - (arrayjend - arrayjstart)\n         if (ify > ny-2) subjend   = arrayjend - arrayjstart + 1\n\t subset(subistart:subiend,subjstart:subjend) = array(arrayistart:arrayiend,arrayjstart:arrayjend)\n!         print *, arrayistart,arrayiend,arrayjstart,arrayjend\n!\t print *, subistart,subiend,subjstart,subjend\n!\t print *, ifx,ify,nx,ny,x,y\n!\t stop\n      else\n         subset(:,:) = array(ifx-1:ifx+2,ify-1:ify+2)\n      end if\n!\t print *, ifx,ify,nx,ny,x,y\n!\t print *, array(ifx-1:ifx+2,ify-1:ify+2)\n!\t print *, subset\n!\t stop\n\n      sum_weight = 0.0\n      pcoef = 2.0\n      do i=1,4\n         do j=1,4\n\n            if (subset(i,j) == msgvalin) then\n               weights(i,j) = 0.0\n            else\n               distance(i,j) = sqrt((x-real(ifx-2+i))**2+(y-real(ify-2+j))**2)\n               weights(i,j) = max(0., 2.0 - distance(i,j))  ! from WPS\n!               weights(i,j) = min(2.0,1.0/(max(0.1,distance(i,j)))**pcoef)  ! IDW looks strange\n            end if\n\n            sum_weight = sum_weight + weights(i,j)\n\n         end do\n      end do\n      goto 1000\n\t print *, ifx,ify,nx,ny,x,y\n\t print *, distance(:,4)\n\t print *, distance(:,3)\n\t print *, distance(:,2)\n\t print *, distance(:,1)\n\t print *, weights(:,4)\n\t print *, weights(:,3)\n\t print *, weights(:,2)\n\t print *, weights(:,1)\n\t print *, subset(:,4)\n\t print *, subset(:,3)\n\t print *, subset(:,2)\n\t print *, subset(:,1)\n\t print *, sum_weight\n!\t stop\n1000 continue\n      if (sum_weight == 0.0) then\n         val = msgvalout\n      else\n         sum = 0.0\n         do i=1,4\n            do j=1,4\n               sum = sum + weights(i,j) * subset(i,j)\n            end do\n         end do\n         val = sum / sum_weight\n!\t print *, val, sum_weight\n      end if\n\n   end function wt_sixteen_pt_average\n\n\n  subroutine smdsm(FLD, ix, jx, npass)\n\n!*****************************************************************************!\n!                                                                             !\n!  Purpose: Smooth the 2-d field FLD with the 2-pass smoother/desmoother      !\n!           Watch it.  All values of FLD are assumed to be valid, that is,    !\n!           no stagger is assumed.                                            !\n!                                                                             !\n!   On Entry:  FLD(IX,JX):  2-d field to be smoothed.                         !\n!              IX, JX    :  Dimensions of 2-d field FLD.                      !\n!              NPASS     :  Optional number of passes of the two-pass smoother!\n!                           (default 1 pass of the two-pass smoother)         !\n!                                                                             !\n!   On Exit:   FLD(IX,JX):  The smoothed 2-d field.                           !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n    INTEGER, intent(in) :: IX, JX\n    REAL, intent(inout), dimension(ix,jx) :: FLD\n    integer, intent(in), optional :: npass\n\n!  XNU(N) : Smoothing coefficient for pass N\n    REAL, parameter, dimension(2) :: XNU = (/ 0.50, -0.52 /)\n    INTEGER :: I, J, N, NP, IND\n    REAL :: ASV, APLUS, CELL\n\n    if (present(npass)) then\n       np = npass\n    else\n       np = 1\n    endif\n\n    NUMPASS : do n = 1, np\n\n       DO IND = 1, 2\n\n!...  FIRST, SMOOTH IN THE IX DIRECTION\n          DO I = 2,IX-1\n             ASV = FLD(I,1)\n             DO J = 2,JX-1\n                APLUS = FLD(I,J+1)\n                CELL = FLD(I,J)\n                FLD(I,J) = FLD(I,J) + XNU(IND)*((ASV + APLUS)/2.0 - FLD(I,J))\n                ASV = CELL\n             ENDDO\n          ENDDO\n\n!...  NOW, SMOOTH IN THE JX DIRECTION\n          DO J = 2,JX-1\n             ASV = FLD(1,J)\n             DO I = 2,IX-1\n                APLUS = FLD(I+1,J)\n                CELL = FLD(I,J)\n                FLD(I,J) = FLD(I,J) + XNU(IND)*((ASV + APLUS)/2.0 - FLD(I,J))\n                ASV = CELL\n             ENDDO\n          ENDDO\n\n       ENDDO\n\n    enddo NUMPASS\n\n  END subroutine smdsm\n\n\n  subroutine smt121(FLD, ix, jx, npass)\n\n!*****************************************************************************!\n!                                                                             !\n!   Purpose :  Performs 1-2-1 smoothing on a 2-d field FLD.                   !\n!              Watch it.  All values of FLD are assumed to be valid, that is, !\n!              no stagger is assumed.                                         !\n!                                                                             !\n!   On entry : FLD(IX,JX): 2-D field to be smoothed.                          !\n!                   IX,JX: The dimensions of the field FLD.                   !\n!                   NPASS: Optional number of passes (default 1).             !\n!                                                                             !\n!   On exit :  FLD(IX,JX): The smoothed field.                                !\n!                                                                             !\n!   The final value at any particular grid point is a weighted sum            !\n!   of that grid point and the eight immediately surrounding points           !\n!   thus:                                                                     !\n!                        1 2 1                                                !\n!                        2 4 2                                                !\n!                        1 2 1                                                !\n!                                                                             !\n!   At edges, we weight thus:                                                 !\n!                        -----                                                !\n!                        2 4 2                                                !\n!                        1 2 1                                                !\n!                                                                             !\n!   At corners, we weight thus:                                               !\n!                        +---                                                 !\n!                        |4 2                                                 !\n!                        |2 1                                                 !\n!                                                                             !\n!*****************************************************************************!\n\n    implicit none\n\n    integer, intent(in) :: ix, jx\n    REAL, intent(inout), dimension(ix,jx) :: FLD\n    integer, intent(in), optional :: npass\n\n    integer :: i, j, n, np\n    real :: cell, aplus, asv\n\n    if (present(npass)) then\n       np = npass\n    else\n       np = 1\n    endif\n\n\n    NUMPASS : do n = 1, np\n\n       DO I = 1, IX\n          ASV = FLD(I,1)\n          FLD(I,1) = (2.*FLD(I,1) + FLD(I,2))/3.\n          DO J = 2, JX-1\n             APLUS = FLD(I,J+1)\n             CELL = FLD(I,J)\n             FLD(I,J) = 0.5*FLD(I,J) + 0.25*(ASV+APLUS)\n             ASV = CELL\n          ENDDO\n          FLD(I,JX) = (2.*FLD(I,JX) + ASV)/3.\n       ENDDO\n\n       DO J=1,JX\n          ASV = FLD(1,J)\n          FLD(1,J) = (2.*FLD(1,J) + FLD(2,J))/3.\n          DO I=2,IX-1\n             APLUS = FLD(I+1,J)\n             CELL = FLD(I,J)\n             FLD(I,J) = 0.5*FLD(I,J) + 0.25*(ASV+APLUS)\n             ASV = CELL\n          ENDDO\n          FLD(IX,J) = (2.*FLD(IX,J) + ASV)/3.\n       ENDDO\n\n    enddo NUMPASS\n\n  END subroutine smt121\n\n  subroutine gaussian_filter(fld, filt, ix, jx, dxkm, half_width)\n!\n! Implementation of a gaussian filter.\n!\n! Purpose:  Return a smoothed version of array FLD in array FILT.\n!\n    implicit none\n    integer, intent(in) :: ix, jx ! Dimensions of input/output arrays\n    real, intent(in), dimension(ix,jx) :: fld  ! Input array to be filtered.\n    real, intent(out),dimension(ix,jx) :: filt ! Output filtered array.\n    real, intent(in) :: dxkm       ! Grid spacing in km\n    real, intent(in) :: half_width ! Half_Width in km\n\n    real,    parameter :: pi = 3.14159265358979\n    real,    parameter :: twopi = 2.*pi\n\n    integer :: i, j, ii, jj, iii, jjj\n    real :: x, y\n    real :: sigma, sigsq\n    integer :: fsz, hsz\n    real :: cval, eval\n    real, dimension(ix,jx) :: tmp\n    real, allocatable, dimension(:) :: v\n    real, allocatable, dimension(:,:) :: k\n\n    sigma =  (half_width/dxkm)\n    sigsq = sigma*sigma\n    fsz = (nint(8*sigma)*2)-1\n    hsz = (fsz+1)/2\n    allocate(k(fsz,fsz))\n    allocate(v(fsz))\n\n    filt = 0.\n    tmp = 0.\n\n! Compute the kernel\n\n! I'd rather do it in one step, going directly to my vector v,\n! but I don't see how to be able to do that cleanly and still\n! correct for the error (how much the sum differs from 1.0).\n\n! First I compute the two-dimensional kernel array.\n    cval = 1./(twopi*sigsq)\n    do i = 1, fsz\n       x = float(hsz-i)\n       do j = 1, fsz\n          y = float(hsz-j)\n          eval = -((x*x)+(y*y))/(2.*sigsq)\n          k(i,j) = exp(eval)\n       enddo\n    enddo\n    k = k*cval\n! Sum to see how far off of one we are, and divide k/sum\n! to correct for that error (i.e., we want to sum to 1.0)\n    k = k/sum(k)\n\n! Now figure my vector from the corrected kernel array.\n    v = k(1,:) / sqrt(k(1,1))\n\n! Apply the kernel\n\n    do j = 1, jx\n       do i = 1, ix\n          do ii = 1, fsz\n             iii = (i-hsz)+ii\n             if (iii < 1) iii = 1\n             if (iii > ix) iii = ix\n             tmp(i,j) = tmp(i,j) + v(ii)*fld(iii,j)\n          enddo\n       enddo\n    enddo\n\n    do i = 1, ix\n       do j = 1, jx\n          do jj = 1, fsz\n             jjj = (j-hsz)+jj\n             if (jjj < 1) jjj = 1\n             if (jjj > jx) jjj = jx\n             filt(i,j) = filt(i,j) + v(jj)*tmp(i,jjj)\n          enddo\n       enddo\n    enddo\n\n  end subroutine gaussian_filter\n\n  subroutine crs2dot(slab1,slab2,ix,jx)\n\n    ! PURPOSE: Interpolate in horizontal from cross to dot points\n\n    implicit none\n    integer, intent(in) :: ix,jx\n    real, dimension(ix,jx), intent(in)  :: slab1\n    real, dimension(ix,jx), intent(out) :: slab2\n    integer :: ie,je,i,j\n\n    IE=IX-1\n    JE=JX-1\n    DO I=2,IE\n       DO J=2,JE\n          SLAB2(I,J)=0.25*(SLAB1(I,J)+SLAB1(I-1,J)+SLAB1(I,J-1)+SLAB1(I-1,J-1))\n       enddo\n    enddo\n    DO I=2,IE\n       SLAB2(I,1)=0.5*(SLAB1(I,1)+SLAB1(I-1,1))\n       SLAB2(I,JX)=0.5*(SLAB1(I,JE)+SLAB1(I-1,JE))\n    enddo\n    DO J=2,JE\n       SLAB2(1,J)=0.5*(SLAB1(1,J)+SLAB1(1,J-1))\n       SLAB2(IX,J)=0.5*(SLAB1(IE,J)+SLAB1(IE,J-1))\n    enddo\n    SLAB2(1,1)=SLAB1(1,1)\n    SLAB2(1,JX)=SLAB1(1,JE)\n    SLAB2(IX,JX)=SLAB1(IE,JE)\n    SLAB2(IX,1)=SLAB1(IE,1)\n\n  end subroutine crs2dot\n\nend module kwm_grid_utilities\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/kwm_string_utilities.F",
    "content": "module kwm_string_utilities\n\ncontains\n\n  subroutine strrep(string, rep1, rep2)\n    ! In string 1, replace expression rep1 with expression rep2.\n    ! if rep2 is shorter than rep1, fill the end of the string\n    ! with blanks\n\n    implicit none\n    character(len=*) :: string, rep1, rep2\n    integer :: idx, inlen, len1, len2\n\n    do\n       inlen = len(string)\n       len1 = len(rep1)\n       len2 = len(rep2)\n       idx = index(string, rep1)-1\n\n       if (idx == -1) then\n          return\n       else\n          string = string(1:idx)// rep2 // &\n               string((idx+len1+1):inlen) // &\n               \"                                                    \"\n       endif\n    enddo\n\n  end subroutine strrep\n\n\n  character(len=1024) function unblank(string) result(return_string)\n    ! Remove blanks (and tabs [char(9)] from string\n    implicit none\n    character(len=*), intent(in) :: string\n    integer :: i, j,  lenstr\n\n    return_string = \" \"\n\n    if ( verify(string,\" \"//char(9)) == 0 ) then\n       stop 'FATAL ERROR: In module kwm_string_utilities.F -- String is all blanks.'\n    endif\n\n    j = 0\n    do i = 1, len(string)\n       if ((string(i:i).ne.' ').and.(string(i:i).ne.char(9))) then\n          j = j + 1\n          return_string(j:j) = string(i:i)\n       endif\n    enddo\n\n  end function unblank\n\n!KWM  character function upcase(h)\n!KWM    implicit none\n!KWM    character :: h\n!KWM\n!KWM    if ((ichar(h).ge.96) .and. (ichar(h).le.123)) then\n!KWM       upcase = char(ichar(h)-32)\n!KWM    else\n!KWM       upcase = h\n!KWM    endif\n!KWM\n!KWM  end function upcase\n\n  character(len=256) function upcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \" \"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.96) .and. (ichar(h(i:i)).le.123)) then\n          return_string(i:i) = char(ichar(h(i:i))-32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function upcase\n\n!KWM  character function downcase(h)\n!KWM    implicit none\n!KWM    character h\n!KWM\n!KWM    if ((ichar(h).ge.65) .and. (ichar(h).le.90)) then\n!KWM       downcase = char(ichar(h)+32)\n!KWM    else\n!KWM       downcase = h\n!KWM    endif\n!KWM  end function downcase\n\n  character(len=256) function downcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \" \"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.65) .and. (ichar(h(i:i)).le.90)) then\n          return_string(i:i) = char(ichar(h(i:i))+32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function downcase\n\n\nend module kwm_string_utilities\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/kwm_timing_utilities.F",
    "content": "module kwm_timing_utilities\n  implicit none\n  integer, parameter :: kwm_timing_dimension = 100\n  integer, dimension(kwm_timing_dimension) :: Acount, Asum\n\ncontains\n\n  subroutine timing_start(num)\n    implicit none\n    integer, intent(in) :: num\n    if (num > kwm_timing_dimension) then\n       stop \"FATAL ERROR: In module kwm_timing_utilities.F -- TIMING_START PROBLEM.  USE A SMALLER NUM.\"\n    endif\n    call system_clock(Acount(num))\n  end subroutine timing_start\n\n  subroutine timing_end(num, string, ivrb)\n    implicit none\n    integer, intent(in) :: num, ivrb\n    integer :: count_rate, count_max\n    character(len=*), intent(in) :: string\n    integer :: Bcount\n    call system_clock(count=Bcount, count_rate=count_rate, count_max=count_max)\n\n    Asum(num) = Asum(num)+(Bcount-Acount(num))\n    if (ivrb /= 0) then\n       print*,' Timing for '//string//': ', float(Bcount-Acount(num))/float(count_rate), &\n            float(Asum(num))/float(count_rate)\n    endif\n  end subroutine timing_end\n\nend module kwm_timing_utilities\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_geo_em.F",
    "content": "module module_geo_em\n!-------------------------------------------------------------\n! At the moment, all that is used from the geo_em file\n! is the array of monthly green vegetation fractions.\n!\n! We also grab projection/grid information, to ensure that\n! the geo_em and wrfinput files are consistent.\n!\n! Modified by Barlage (v3.7) to remove dependence on wrfinput file\n!  Therefore, all grid information is read in this module now.\n!\n!-------------------------------------------------------------\n  use netcdf\n  use module_llxy\n  implicit none\n  ! Define a data structure for WRF geo_em file\n\n  type geo_em_type\n     type(proj_info) :: proj\n     integer :: grid_id\n     integer :: idim\n     integer :: jdim\n     character(len=256) :: landuse_dataset ! \"MODIFIED_IGBP_MODIS_NOAH\" or \"USGS\"\n     integer :: iswater\n     integer :: islake\n     integer :: isurban\n     integer :: isice\n     real, pointer, dimension(:,:)   :: lat    ! Grid point latitudes\n     real, pointer, dimension(:,:)   :: lon    ! Grid point longitudes\n     real, pointer, dimension(:,:)   :: ter    ! Terrain field\n     real, pointer, dimension(:,:)   :: use    ! Land-use (vegetation) field\n     real, pointer, dimension(:,:)   :: tmn    ! Deep soil temperature\n     real, pointer, dimension(:,:)   :: soi    ! Soil type\n     real, pointer, dimension(:,:)   :: msk    ! Land mask\n     real, pointer, dimension(:,:)   :: mmx    ! mapfac_mx\n     real, pointer, dimension(:,:)   :: mmy    ! mapfac_my\n     real, pointer, dimension(:,:)   :: ice    ! Seaice placeholder\n     real, pointer, dimension(:,:,:) :: veg\n     real, pointer, dimension(:,:,:) :: lai\n  end type geo_em_type\n\ncontains\n\n  subroutine read_geo_em_file(flnm, geo_em, ierr)\n\n!---------------------------------------------------------------\n!  At the moment, all we need from the geo_em file is the\n!  array of monthly green vegetation fractions.\n!\n!  We also read projection/grid information, to ensure that\n!  the geo_em and wrfinput files are consistent.\n!\n!  As of v3.7, geo_em is the only WPS/WRF file we read, so it grabs everything\n!---------------------------------------------------------------\n\n    implicit none\n\n    character(len=*),   intent(in)  :: flnm\n    type (geo_em_type), intent(out) :: geo_em\n    integer,            intent(out) :: ierr\n    ! Local:\n    integer :: ncid\n    integer :: iret\n    integer :: dimid\n    integer :: i,j,l\n    integer                           :: map_proj\n    real                              :: truelat1\n    real                              :: truelat2\n    real                              :: stdlon\n    real                              :: dx\n    real                              :: latinc\n    real                              :: loninc\n    real                              :: la1\n    real                              :: lo1\n    real                              :: pole_lat\n    real                              :: pole_lon\n    real, pointer, dimension(:,:,:)   :: soil_top_cat\n    integer                           :: dominant_index\n    real                              :: dominant_value\n    integer                           :: iswater_soil\n\n\n! Open the NetCDF file.\n    print*, 'flnm = ', flnm\n    iret = nf90_open(flnm, NF90_NOWRITE, ncid)\n    call error_handler(iret, \"Problem reading geo_em file: \"//flnm)\n\n! Find out about dimensions in the file.\n\n    iret = nf90_inq_dimid(ncid, \"west_east\", dimid)\n    call error_handler(iret, \"STOP:  Problem finding NetCDF dimension 'west_east'\")\n    iret = nf90_inquire_dimension(ncid, dimid, len=geo_em%idim)\n    call error_handler(iret, \"STOP:  Problem finding NetCDF dimension 'west_east'\")\n\n    iret = nf90_inq_dimid(ncid, \"south_north\", dimid)\n    call error_handler(iret, \"STOP:  Problem finding NetCDF dimension 'south_north'\")\n    iret = nf90_inquire_dimension(ncid, dimid, len=geo_em%jdim)\n    call error_handler(iret, \"STOP:  Problem finding NetCDF dimension 'south_north'\")\n\n! Grid id.  Check for the string \"GRID_ID\" or the string \"grid_id\"\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL,\"grid_id\", geo_em%grid_id)\n    if (iret /= 0) then\n       iret = nf90_get_att(ncid, NF90_GLOBAL,\"GRID_ID\", geo_em%grid_id)\n       call error_handler(iret, \"STOP:  nf90_get_att:  'grid_id' or 'GRID_ID' not found.\")\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"ISWATER\" , geo_em%iswater)\n    call error_handler(iret, \"STOP:  nf90_get_att:  ISWATER\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"ISLAKE\" , geo_em%islake)\n    call error_handler(iret, \"STOP:  nf90_get_att:  ISLAKE\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"ISURBAN\" , geo_em%isurban)\n    call error_handler(iret, \"STOP:  nf90_get_att:  ISURBAN\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"ISICE\" , geo_em%isice)\n    call error_handler(iret, \"STOP:  nf90_get_att:  ISICE\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"MMINLU\" , geo_em%landuse_dataset)\n    call error_handler(iret, \"STOP:  nf90_get_att:  MMINLU\")\n\n! Get Latitude\n    allocate(geo_em%lat(geo_em%idim, geo_em%jdim))\n    call get_2d(\"XLAT_M\", ncid, geo_em%lat, geo_em%idim, geo_em%jdim)\n    la1 = geo_em%lat(1,1)\n\n! Get Longitude\n    allocate(geo_em%lon(geo_em%idim, geo_em%jdim))\n    call get_2d(\"XLONG_M\", ncid, geo_em%lon, geo_em%idim, geo_em%jdim)\n    lo1 = geo_em%lon(1,1)\n\n! Get Terrain\n    allocate(geo_em%ter(geo_em%idim, geo_em%jdim))\n    call get_2d(\"HGT_M\", ncid, geo_em%ter, geo_em%idim, geo_em%jdim)\n\n! Get Deep Soil Temperature (adjust to elevation)\n    allocate(geo_em%tmn(geo_em%idim, geo_em%jdim))\n    call get_2d(\"SOILTEMP\", ncid, geo_em%tmn, geo_em%idim, geo_em%jdim)\n    geo_em%tmn = geo_em%tmn - 0.0065 * geo_em%ter\n\n! Get Land Use categories\n    allocate(geo_em%use(geo_em%idim, geo_em%jdim))\n    call get_2d(\"LU_INDEX\", ncid, geo_em%use, geo_em%idim, geo_em%jdim)\n\n! Create XLAND\n    allocate(geo_em%msk(geo_em%idim, geo_em%jdim))\n    where(geo_em%use .eq. geo_em%iswater .or.  geo_em%use .eq. geo_em%islake) geo_em%msk = 2\n    where(geo_em%use .ne. geo_em%iswater .and. geo_em%use .ne. geo_em%islake) geo_em%msk = 1\n\n! Create SEAICE\n    allocate(geo_em%ice(geo_em%idim, geo_em%jdim))\n    geo_em%ice = 0.0\n\n! Get Soil categories\n!   soil is a problem since real does some manipulation, so we need to read the % data\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"ISOILWATER\" , iswater_soil)\n    call error_handler(iret, \"STOP:  nf90_get_att:  ISOILWATER\")\n\n    allocate(soil_top_cat(geo_em%idim, geo_em%jdim, 16))  ! potential problem with hardcoding 16?\n    call get_soil_cat(ncid, soil_top_cat, geo_em%idim, geo_em%jdim, 16)\n    allocate(geo_em%soi(geo_em%idim, geo_em%jdim))\n\n      DO i = 1 , geo_em%idim\n         DO j = 1 , geo_em%jdim\n            dominant_value = soil_top_cat(i,j,1)\n            dominant_index = 1\n            IF ( geo_em%msk(i,j) .LT. 1.5 ) THEN\n               DO l = 2 , 16\n                  IF ( ( l .NE. iswater_soil ) .AND. ( soil_top_cat(i,j,l) .GT. dominant_value ) ) THEN\n                     dominant_value = soil_top_cat(i,j,l)\n                     dominant_index = l\n                  END IF\n               END DO\n               IF ( dominant_value .LT. 0.01 ) dominant_index = 8\n            ELSE\n               dominant_index = iswater_soil\n            END IF\n            geo_em%soi(i,j) = dominant_index\n         END DO\n      END DO\n\n    where(geo_em%use .eq. geo_em%iswater .or.  geo_em%use .eq. geo_em%islake) geo_em%soi = 14\n    where(geo_em%use .ne. geo_em%iswater .and. geo_em%use .ne. geo_em%islake .and. geo_em%soi .eq. 14) geo_em%soi = 8\n\n! Get MAPFAC_MX (for MMF groundwater)\n    allocate(geo_em%mmx(geo_em%idim, geo_em%jdim))\n    call get_2d(\"MAPFAC_MX\", ncid, geo_em%mmx, geo_em%idim, geo_em%jdim)\n\n! Get MAPFAC_MY (for MMF groundwater)\n    allocate(geo_em%mmy(geo_em%idim, geo_em%jdim))\n    call get_2d(\"MAPFAC_MY\", ncid, geo_em%mmy, geo_em%idim, geo_em%jdim)\n\n! Get monthly Greenness Fractions\n    allocate(geo_em%veg(geo_em%idim, geo_em%jdim, 12))\n    call get_monthly(ncid, \"GREENFRAC\", geo_em%veg, geo_em%idim, geo_em%jdim, 12)\n    geo_em%veg = 100.0 * geo_em%veg  ! change to range consistent with wrfinput\n\n! Get monthly leaf area index\n    allocate(geo_em%lai(geo_em%idim, geo_em%jdim, 12))\n    call get_monthly(ncid, \"LAI12M\", geo_em%lai, geo_em%idim, geo_em%jdim, 12)\n\n! Projection information:\n\n    call map_init(geo_em%proj)\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL,\"MAP_PROJ\", map_proj)\n    call error_handler(iret, \"STOP:  nf90_get_att:  map projection problem\")\n\n    if (map_proj == PROJ_LC) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\" , truelat2)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT2\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_LC, geo_em%proj, lat1=la1, lon1=lo1, knowni=1.0, knownj=1.0, &\n            truelat1=truelat1, truelat2=truelat2, stdlon=stdlon, dx=dx)\n\n    else if (map_proj == PROJ_PS) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_PS, geo_em%proj, lat1=la1, lon1=lo1, truelat1=truelat1, &\n            knowni=1.0, knownj=1.0, stdlon=stdlon, dx=dx)\n\n    else if (map_proj == PROJ_MERC) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_MERC, geo_em%proj, lat1=la1, lon1=lo1, knowni=1.0, knownj=1.0, &\n            truelat1=truelat1, dx=dx)\n\n    else if (map_proj == PROJ_CASSINI) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"POLE_LAT\" , pole_lat)\n       call error_handler(iret, \"STOP:  nf90_get_att:  POLE_LAT\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"POLE_LON\" , pole_lon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  POLE_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       ! For Cassini projection, module_llxy assumes a spherical earth\n       ! with circumference EARTH_CIRC_M\n       latinc = 360.0*dx/EARTH_CIRC_M\n       loninc = 360.0*dx/EARTH_CIRC_M\n\n       call map_set(PROJ_CASSINI, geo_em%proj, lat1=la1, lon1=lo1, latinc=latinc, loninc=loninc, &\n            knowni=1.0, knownj=1.0, lat0=pole_lat, lon0=pole_lon, stdlon=stdlon)\n\n    else if (map_proj == PROJ_LATLON) then\n       stop \"FATAL ERROR: In module_geo_em.F -- PROJ_LATLON is not a valid map projection for WRF.\"\n\n       ! iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       ! call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       ! For lat/lon projection, module_llxy assumes a spherical earth\n       ! with circumference EARTH_CIRC_M\n       ! latinc = 360.0*dx/EARTH_CIRC_M\n       ! loninc = 360.0*dx/EARTH_CIRC_M\n\n       ! call map_set(PROJ_LATLON, geo_em%proj, lat1=la1, lon1=lo1, &\n       !      latinc=latinc, loninc=loninc, knowni=1.0, knownj=1.0)\n\n    else if (map_proj == PROJ_PS_WGS84) then\n       stop \"FATAL ERROR: In module_geo_em.F -- PROJ_PS_WGS84 is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_PS_WGS84, geo_em%proj, lat1=geo_em%la1, lon1=geo_em%lo1, knowni=1.0, knownj=1.0, &\n       !     stdlon=geo_em%lov, dx=geo_em%dx)\n    else if (map_proj == PROJ_GAUSS) then\n       stop \"FATAL ERROR: In module_geo_em.F -- PROJ_GAUSS is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_GAUSS, geo_em%proj, lat1=, lon1=, nlat=, loninc=)\n    else if (map_proj == PROJ_CYL) then\n       stop \"FATAL ERROR: In module_geo_em.F -- PROJ_CYL is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_CYL, geo_em%proj, latinc=, loninc=, stdlon=)\n    else if (map_proj == PROJ_ALBERS_NAD83) then\n       stop \"FATAL ERROR: In module_geo_em.F -- PROJ_ALBERS_NAD83 is not a valid map projection for WRF.\"\n       !call map_set(PROJ_ALBERS_NAD83, geo_em%proj, lat1=, lon1=, knowni=, knownj=, truelat1=, truelat2=, stdlon=, dx=)\n    else if (map_proj == PROJ_ROTLL) then\n       stop \"FATAL ERROR: In module_geo_em.F -- PROJ_ROTLL is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_ROTLL, geo_em%proj, lat1=geo_em%lat1, lon1=geo_em%lon1, ixdim=, jydim=, phi=, lambda=)\n    else\n       write(*,'(\"WARNING: Unknown geo_em map projection:  map_proj = \", I10)') map_proj\n       stop \"FATAL ERROR: In module_geo_em.F -- Unknown geo_em map projection\"\n    endif\n\n! Close the file and get out of here\n\n    iret = nf90_close(ncid)\n    call error_handler(iret, \"STOP:  Problem closing file??\")\n\n    ierr = 0\n    print*, \"Done with subroutine read_geo_em_file\"\n\n  end subroutine read_geo_em_file\n\n  subroutine get_monthly(ncid, name, array, idim, jdim, kdim)\n    implicit none\n    integer, intent(in)                          :: ncid\n    character(len=*), intent(in)                 :: name\n    integer, intent(in)                          :: idim\n    integer, intent(in)                          :: jdim\n    integer, intent(in)                          :: kdim\n    real, dimension(idim,jdim,kdim), intent(out) :: array\n    ! Local:\n    integer :: ierr\n    integer :: varid\n\n    ierr = nf90_inq_varid(ncid,  trim(name),  varid)\n    if(ierr /= 0 .and. trim(name) == \"GREENFRAC\") call error_handler(ierr, \"STOP:  Problem finding GREENFRAC in geo_em file\")\n\n    if(ierr /= 0 .and. trim(name) == \"LAI12M\") then    ! LAI not available in this version\n      array = -1.e36\n      return\n    end if\n\n    ierr = nf90_get_var(ncid, varid, array)\n    call error_handler(ierr, \"STOP:  Problem getting \"//trim(name)//\" from geo_em file\")\n\n  end subroutine get_monthly\n\n  subroutine get_soil_cat(ncid, array, idim, jdim, kdim)\n    implicit none\n    integer, intent(in)                          :: ncid\n    integer, intent(in)                          :: idim\n    integer, intent(in)                          :: jdim\n    integer, intent(in)                          :: kdim\n    real, dimension(idim,jdim,kdim), intent(out) :: array\n    ! Local:\n    integer :: ierr\n    integer :: varid\n\n    ierr = nf90_inq_varid(ncid,  \"SOILCTOP\",  varid)\n    call error_handler(ierr, \"STOP:  Problem finding SOILCTOP in geo_em file\")\n\n    ierr = nf90_get_var(ncid, varid, array)\n    call error_handler(ierr, \"STOP:  Problem getting SOILCTOP from geo_em file\")\n\n  end subroutine get_soil_cat\n\n  subroutine get_2d(name, ncid, array, idim, jdim)\n    !\n    ! From the NetCDF unit <ncid>, read the variable named <name> with\n    ! dimensions <idim> and <jdim>, filling the pre-dimensioned array <array>\n    !\n    implicit none\n    character(len=*),           intent(in)  :: name\n    integer,                    intent(in)  :: ncid\n    integer,                    intent(in)  :: idim\n    integer,                    intent(in)  :: jdim\n    real, dimension(idim,jdim), intent(out) :: array\n    ! Local:\n    integer                                 :: ierr\n    integer                                 :: varid\n\n    ierr = nf90_inq_varid(ncid,  name,  varid)\n    ! If the variable is \"XLAT\", and \"XLAT\" is not found, look for \"XLAT_M\"\n    ! If the variable is \"XLAT_M\", and \"XLAT_M\" is not found, look for \"XLAT\"\n    ! If the variable is \"XLONG\", and \"XLONG\" is not found, look for \"XLONG_M\"\n    ! If the variable is \"XLONG_M\", and \"XLONG_M\" is not found, look for \"XLONG\"\n    if (name == \"XLAT\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLAT_M\",  varid)\n       endif\n    else if (name == \"XLAT_M\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLAT\",  varid)\n       endif\n    else  if (name == \"XLONG\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLONG_M\",  varid)\n       endif\n    else if (name == \"XLONG_M\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLONG\",  varid)\n       endif\n    endif\n    call error_handler(ierr, \"STOP:  READ_GEO_EM: Problem finding variable '\"//trim(name)//\"' in geo_em file.\")\n\n\n    ierr = nf90_get_var(ncid, varid, array)\n    call error_handler(ierr, \"STOP:  READ_GEO_EM:  Problem retrieving variable '\"//trim(name)//\"' from geo_em file.\")\n\n  end subroutine get_2d\n\n\n  subroutine error_handler(status, failure, success)\n    !\n    ! Check the error flag from a NetCDF function call, and print appropriate\n    ! error message.\n    !\n    implicit none\n    integer,                    intent(in) :: status\n    character(len=*), optional, intent(in) :: failure\n    character(len=*), optional, intent(in) :: success\n\n    if (status .ne. NF90_NOERR) then\n       if (present(failure)) then\n          write(*,'(/,\"WARNING:  ***** \", A)') failure\n       endif\n       write(*,'(\"WARNING:  ***** \",A,/)') nf90_strerror(status)\n       stop 'FATAL ERROR: In module_geo_em.F -- Stopped'\n    endif\n\n    if (present(success)) then\n       write(*,'(A)') success\n    endif\n\n  end subroutine error_handler\n\nend module module_geo_em\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_grib.F",
    "content": "module module_grib\n  use module_grib1\n  use module_grib2\n  use module_grib_common\n  implicit none\n\n! Many of these are wrapper functions which call the appropriate GRIB1\n! or GRIB2 routines as necessary.\n\ncontains\n\n\n!=================================================================================\n!=================================================================================\n\n  subroutine gribopen(filename, fd, ierr)\n    implicit none\n    !\n    ! Purpose:\n    !      Open the GRIB2 file for reading, and do a few set-up tasks.\n    !\n    ! Input:\n    !      filename:  Name of the GRIB2 file to open.\n    !\n    ! Output:\n    !      fd:        Integer value for the c pointer to a memory location for \n    !                 a structure containing file information, among which is \n    !                 the FILE pointer.\n    !\n    !      ierr:      An error flag.  ierr == 0 -- File opened successfully.\n    !                                 ierr == 1 -- There was some problem opening the file.\n    !                                 ierr == 2 -- The specified file does not exist.\n    !\n    ! Side effects:\n    !      - File <filename> is opened for reading\n    !      - The file stream pointer for <filename>, contained within structure <fd>,\n    !        is positioned at the beginning of the file.\n    !\n    character(len=*), intent(in)  :: filename\n    integer(kind=8),  intent(out) :: fd\n    integer,          intent(out) :: ierr\n\n    logical :: lexist\n\n    ierr = 0\n\n    ! First check the existence of the file.\n    inquire(file=trim(filename), exist=lexist)\n    if (.not. lexist) then\n       ierr = 2\n       return\n    endif\n\n    call c_gribopen(trim(filename)//char(0), fd, ierr)\n\n  end subroutine gribopen\n\n!=================================================================================\n!=================================================================================\n\n  subroutine gribclose(fd)\n    implicit none\n    integer(kind=8), intent(in) :: fd\n    call c_close(fd)\n  end subroutine gribclose\n\n!=================================================================================\n!=================================================================================\n\n  subroutine getgrib(fd, grib, ierr)\n    implicit none\n    !\n    ! Purpose:\n    !      Read a single grib record, but do no unpacking and no interpretation\n    !      of header information beyond the size and edition nuber from GRIB \n    !      section zero.\n    !\n    integer(kind=8), intent(in)      :: fd\n    type (GribStruct), intent(inout) :: grib\n    integer, intent(out)             :: ierr\n\n    integer :: extra\n    integer :: iloc\n    integer :: iread\n    integer :: seventest\n\n    logical, save                 :: grib1_tables_read = .FALSE.\n    logical, save                 :: grib2_tables_read = .FALSE.\n\n    !\n    ! Position our file pointer at the beginning of the next GRIB record.\n    !\n\n    call findgrib(fd, grib, iloc)\n    if (iloc < 0) then\n       ierr = 1\n       return\n    endif\n\n    ! Read the full grib record.\n    call io_fread(fd, grib%buffer(17:), grib%size-16, iread, ierr)\n    if (iread /= grib%size-16) then\n       iloc = -7\n       return\n    endif\n    if (ierr /= 0) then\n       iloc = -8\n       return\n    endif\n\n    grib%iskip = 0\n\n    extra = 4 - mod(grib%size,4)\n    call swap4f(grib%buffer, grib%size+extra)\n\n    !\n    !  Check the last four bytes\n    !\n    call gbyte(grib%buffer, seventest, (grib%size-4)*8, 32)\n    if (seventest /= string_sevens) then\n       write(*,'(\"WARNING: Cannot find marker (7777) for end of GRIB record\")')\n       stop \"FATAL ERROR: In module_grib.F -- Problem finding end of GRIB record\"\n    endif\n\n    ! Read grib tables.\n! Barlage: is it necessary to read external grib tables? why not just read namelist table for this info 20150518\n!    if (grib%edition == 1) then\n!       if (.not. grib1_tables_read) then\n!          call grib1_read_parameter_tables()\n!          grib1_tables_read = .TRUE.\n!       endif\n!    else\n!       if (.not. grib2_tables_read) then\n!          call grib2_read_parameter_tables()\n!          grib2_tables_read = .TRUE.\n!       endif\n!    endif\n\n  end subroutine getgrib\n\n!=================================================================================\n!=================================================================================\n\n  subroutine findgrib(fd, grib, iloc)\n    implicit none\n    ! Purpose:\n    !      Seek in an open GRIB file for the string \"GRIB\", which\n    !      indicates the beginning of a GRIB record.\n    ! Input:\n    !      fd: A file stream pointer to a file opened by subroutine GRIBOPEN\n    !\n    ! Output:\n    !      iloc:  The location (by byte count) in the file stream <fd>\n    !             at the beginning of this particular GRIB record.  Or,\n    !             a negative number indicating a read problem (probably we \n    !             hit the end of the file.\n    !\n    ! Side Effects:\n    !      Position the c file pointer at the beginning of the grib record.\n\n    integer(kind=8), intent(in) :: fd\n    type (GribStruct) :: grib\n    integer, intent(out) :: iloc\n\n    integer :: ierr\n    integer :: iread\n    integer :: itell\n    character(len=4) :: h4\n    character(len=1), dimension(12) :: buf12\n    integer :: extra\n    integer :: i\n\n    call io_fread(fd, h4, 4, iread, ierr)\n\n    if (iread /= 4) then\n       ! Probably, we've hit the end of file without finding a GRIB record\n       iloc = -1\n       return\n    endif\n\n    if (ierr /= 0) then\n       ! Probably, we've hit the end of file without finding a GRIB record\n       iloc = -2\n       return\n    endif\n\n    do while ( h4 /= \"GRIB\")\n       ! Adjust our buffer and read one more byte\n       h4(1:3) = h4(2:4)\n       call io_fread(fd, h4(4:4), 1, iread, ierr)\n       if (iread /= 1) then\n          iloc = -3;\n          return\n       endif\n       if (ierr /= 0) then\n          iloc = -4;\n          return\n       endif\n    enddo\n\n    !\n    !   To have got this far, we must have found the beginning of a GRIB\n    !   record.\n    !\n\n    !\n    ! Read the next 12 bytes to determine GRIB record size\n    !\n\n    call io_fread(fd, buf12, 12, iread, ierr)\n    if (iread /= 12) then\n       iloc = -5\n       return\n    endif\n    if (ierr /= 0) then\n       iloc = -6\n       return\n    endif\n\n    call swap4f(buf12, 12)\n\n    ! Get the grib edition number.\n    call gbyte(buf12, grib%edition, 24, 8)\n    if (grib%edition == 2) then\n       call gbyte(buf12, grib%size, 64, 32)\n    else if (grib%edition == 1) then\n       call gbyte(buf12, grib%size, 0, 24)\n    else\n       write(*, '(\"WARNING: Grib Edition:  \", I10)') grib%edition\n       stop \"FATAL ERROR: In module_grib.F -- Grib Edition.\"\n    endif\n    ! write(*, '(\"Grib Edition:  \", I10, \"  Record size:  \", I10)') grib%edition, grib%size\n\n    !\n    ! Allocate space for the full grib record.  The \"extra\" space allocated\n    ! insures that we have a multiple of four bytes in our buffer, so the \n    ! byte-swapping will work correctly without out-of-bounds array references.\n    !\n\n    extra = 4 - mod(grib%size,4)\n    allocate(grib%buffer(grib%size + extra), stat=ierr)\n    if (ierr /= 0) then\n       write(*,'(\"WARNING: Problem allocating buffer for GRIB data in subroutine GETGRIB\")')\n       stop \"FATAL ERROR: In module_grib.F -- Problem allocating buffer for GRIB data in subroutine GETGRIB\"\n    endif\n    do i = 1, 4\n       grib%buffer(i) = h4(i:i)\n    enddo\n    call swap4f(grib%buffer, 4)\n\n    do i = 1, 12\n       grib%buffer(i+4) = buf12(i)\n    enddo\n\n    ! Swap the bytes here, to make things consistent when we read the rest of the buffer.\n    call swap4f(grib%buffer, 16)\n\n    !\n    !  Position the file stream pointer to the beginning of the GRIB record.\n    !\n    ! call io_fseek(fd, -16, 0);\n\n    !\n    ! Find the stream pointer position\n    !\n\n    call io_ftell(fd, itell)\n\n    !\n    !  Return the byte position of the beginning of this GRIB record\n    !\n    iloc = itell\n\n\n  end subroutine findgrib\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_next_field(fd, grib, ierr)\n    implicit none\n    !\n    ! Purpose:\n    !      Unpack the next field in a GRIB file.  The field may already be\n    !      available in <grib%buffer>; if not, we read from the file into \n    !      <grib%buffer>.\n    !\n\n    integer(kind=8), intent(in) :: fd\n    type (GribStruct), intent(inout) :: grib\n    integer, intent(out) :: ierr\n    integer :: iloc\n    integer :: isection\n    integer :: test_sevens\n\n    ierr = 0\n\n    FIELD_LOOP : do\n\n       if ( .not. associated (grib%buffer) ) then\n          ! print*, 'Try to read a new record'\n          ! Get the next complete GRIB record (which may contain more than one field,\n          ! which is why we have the complication of the outer do loop here).\n          call getgrib(fd, grib, ierr)\n          if (ierr /= 0) return\n       else\n          ! See if we're at \"7777\"  If so, deallocate things and read a new record.\n          call gbyte(grib%buffer, test_sevens, grib%iskip, 32)\n          if (test_sevens == string_sevens) then\n             call deallogrib(grib)\n             cycle FIELD_LOOP\n          endif\n       endif\n\n       select case (grib%edition)\n       case default\n\n          write(*, '(\"WARNING: MODULE_GRIB:  GRIB_NEXT_FIELD:  Unrecognized edition = \", I10)') grib%edition\n          stop \"FATAL ERROR: In module_grib.F -- GRIB_NEXT_FIELD: Unrecognized edition\"\n\n       case (1)\n          ! print*, 'Unpacking section 0'\n\n          ! GRIB Edition 1 is a lot simpler, because we do not pack more than one field\n          ! into a GRIB record.  Just process the whole record and be done with it.\n          call grib1_unpack_sec0(grib%buffer, size(grib%buffer), grib%iskip)\n          call grib1_unpack_sec1(grib%buffer, size(grib%buffer), grib%iskip, grib%g1sec1)\n          if (grib%g1sec1%ifgds) call grib1_unpack_sec2(grib%buffer, size(grib%buffer), grib%iskip, grib%g1sec2)\n          if (grib%g1sec1%ifbms) call grib1_unpack_sec3(grib)\n          call grib1_unpack_sec4(grib%buffer, size(grib%buffer), grib%iskip, grib%g1sec4)\n          ! call grib1_unpack_sec5(grib%buffer, size(grib%buffer), grib%iskip)\n          ! We have unpacked a GRIB record's data field.  Time to return.\n          return\n\n       case (2)\n\n          call unpack_next_grib2_section(isection, grib)\n\n          do while ( isection < 7 )\n             call unpack_next_grib2_section(isection, grib)\n          enddo\n\n          if (isection == 7) then\n             ! We have unpacked a GRIB record's data field.  Time to return.\n             return\n          else if (isection == 8) then\n             call deallogrib(grib)\n          endif\n       end select\n\n    enddo FIELD_LOOP\n\n  end subroutine grib_next_field\n\n!=================================================================================\n!=================================================================================\n\n  subroutine gribdata(grib)\n    ! Unpack the field and put in into the <grib->array> memory.\n    implicit none\n    type (GribStruct), intent(inout) :: grib\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"WARNING: MODULE_GRIB:  GRIBDATA:  Unrecognized grib%edition\", I10)') grib%edition\n       stop \"FATAL ERROR: In module_grib.F -- GRIBDATA : Unrecognized grib%edition\"\n    case (1)\n       call grib1_gribdata(grib)\n    case (2)\n       call grib2_gribdata(grib)\n    end select\n\n  end subroutine gribdata\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_parameter_text_information(grib, name, units, description)\n    implicit none\n    type (GribStruct) :: grib\n    character(len=64) :: name\n    character(len=256) :: units\n    character(len=256) :: description\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"WARNING: MODULE_GRIB:  GRIB_PARAMETER_TEXT_INFORMATION:  Unrecognized grib%edition\", I10)') grib%edition\n       stop \"FATAL ERROR: In module_grib.F -- GRIB_PARAMETER_TEXT_INFORMATION: Unrecognized grib%edition\"\n    case (1)\n       call grib1_parameter_text_information(grib%g1sec1, name, units, description)\n    case (2)\n       call grib2_parameter_text_information(grib, name, units, description)\n    end select\n  end subroutine grib_parameter_text_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_level_information(grib, level_type, level_units, level_value, level2_value)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=256), intent(out) :: level_type\n    character(len=256), intent(out) :: level_units\n    real,               intent(out) :: level_value\n    real,               intent(out) :: level2_value\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"WARNING: MODULE_GRIB:  GRIB_LEVEL_INFORMATION:  Unrecognized grib%edition\", I10)') grib%edition\n       stop \"FATAL ERROR: In module_grib.F -- GRIB_LEVE_INFORMATION: Unrecognized grib%edition\"\n    case (1)\n       call grib1_level_information(grib, level_type, level_units, level_value, level2_value)\n    case (2)\n       call grib2_level_information(grib, level_type, level_units, level_value, level2_value)\n    end select\n\n  end subroutine grib_level_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=19), intent(out)  :: reference_date\n    character(len=19), intent(out)  :: valid_date\n    character(len=256), intent(out) :: process\n    character(len=256), intent(out) :: processing\n    integer,            intent(out) :: p1_seconds\n    integer,            intent(out) :: p2_seconds\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"WARNING: MODULE_GRIB:  GRIB_TIME_INFORMATION:  Unrecognized grib%edition\", I10)') grib%edition\n       stop \"FATAL ERROR: In module_grib.F -- GRIB_TIME_INFORMATION: Unrecognized grib%edition\"\n    case (1)\n       call grib1_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    case (2)\n       call grib2_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    end select\n\n  end subroutine grib_time_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_valid_date(grib, validdate)\n    ! Hmmmm.  This could also be a subfunction of unpacking\n    ! GRIB2 section 4 (GRIB1 Section 1), and making <validdate>\n    ! an element of <grib> at the top level\n    implicit none\n    type (GribStruct), intent(in)  :: grib\n    character(len=19), intent(out) :: validdate\n    !\n\n    select case (grib%edition)\n    case default\n       write(*,'(\"WARNING: MODULE_GRIB:  GRIB_VALID_DATE:  Unrecognized grib%edition\", I10)') grib%edition\n       stop \"FATAL ERROR: In module_grib.F -- GRIB_VALID_DATE: Unrecognized grib%edition\"\n    case (1)\n       call grib1_valid_date(grib%g1sec1, validdate)\n    case (2)\n       call grib2_valid_date(grib, validdate)\n    end select\n  end subroutine grib_valid_date\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib_map_information(grib)\n    implicit none\n    type(GribStruct), intent(inout) :: grib\n    select case (grib%edition)\n    case default\n       write(*,'(\"WARNING: MODULE_GRIB:  GRIB_MAP_INFORMATION:  Unrecognized grib%edition\", I10)') grib%edition\n       stop \"FATAL ERROR: In module_grib.F -- GRIB_MAP_INFORMATION: Unrecognized grib%edition\"\n    case (1)\n       call grib1_map_information(grib%g1sec2, grib%mapinfo)\n    case (2)\n       call grib2_map_information(grib)\n    end select\n\n  end subroutine grib_map_information\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_grib1.F",
    "content": "module module_grib1\n  use module_mapinfo\n  use kwm_date_utilities\n  use module_grib_common\n  implicit none\n\n  type grib1_parameter_table_entry\n     character(len=256) :: name\n     character(len=64)  :: units\n     character(len=16)  :: abbr\n  end type grib1_parameter_table_entry\n  type(grib1_parameter_table_entry), dimension(1:255) :: grib1_parameter_table\n\ncontains\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_parameter_text_information(sec1, name, units, description)\n    implicit none\n    ! Need to read tables and get information from stored table data\n    type (G1Section1Struct), intent(in)  :: sec1\n    character(len=64),       intent(out) :: name\n    character(len=64),       intent(out) :: units\n    character(len=64),       intent(out) :: description\n\n    name = trim(grib1_parameter_table(sec1%parameter)%abbr)\n    units = trim(grib1_parameter_table(sec1%parameter)%units)\n    description = trim(grib1_parameter_table(sec1%parameter)%name)\n\n  end subroutine grib1_parameter_text_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=19), intent(out)  :: reference_date\n    character(len=19), intent(out)  :: valid_date\n    character(len=256), intent(out) :: process\n    character(len=256), intent(out) :: processing\n    integer,            intent(out) :: p1_seconds\n    integer,            intent(out) :: p2_seconds\n\n    reference_date = grib%g1sec1%hdate\n\n    call grib1_valid_date(grib%g1sec1, valid_date)\n\n    select case (grib%g1sec1%tri) ! Time Range Indicator\n    case default\n       write(process,'(\"WARNING: MODULE_GRIB1:  GRIB1_TIME_INFORMATION:  Unrecognized GRIB1 Time Range Indicator \", I10)') grib%g1sec1%tri\n       write(processing,'(\"WARNING: MODULE_GRIB1:  GRIB1_TIME_INFORMATION:  Unrecognized GRIB1 Time Range Indicator \", I10)') grib%g1sec1%tri\n       print*, trim(process)\n       stop \"FATAL ERROR: In module module_grib1.F -- GRIB1_TIME_INFORMATION: Unrecognized GRIB1 Time Range Indicator\"\n    case (0)\n       process = \"Forecast product\"\n       processing = \"Forecast product\"\n    case (1,10)\n       process = \"Analysis product\"\n       processing = \"Analysis product\"\n    case (3)\n       process = \"Average product\"\n       processing = \"Average product\"\n    case (4)\n       process = \"Accumulation\"\n       processing = \"Accumulation\"\n    end select\n\n    select case (grib%g1sec1%ftu) ! Forecast Time Units\n    case default\n       write(*,'(\"WARNING: Unrecognized GRIB1 forecast time units:  \",I10)') grib%g1sec1%ftu\n       stop \"FATAL ERROR: In module module_grib1.F -- Unrecognized GRIB1 forecast time units\"\n    case (0) ! Minute\n       p1_seconds = grib%g1sec1%p1 * 60\n       p2_seconds = grib%g1sec1%p2 * 60\n    case (1) ! Hour\n       p1_seconds = grib%g1sec1%p1 * 3600\n       p2_seconds = grib%g1sec1%p2 * 3600\n    end select\n\n  end subroutine grib1_time_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_level_information(grib, level_type, level_units, level_value, level2_value)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=256), intent(out) :: level_type\n    character(len=256), intent(out) :: level_units\n    real,               intent(out) :: level_value\n    real,               intent(out) :: level2_value\n\n    level_value = -1.E36\n    level2_value = -1.E36\n    level_units = \" \"\n    select case (grib%g1sec1%leveltyp)\n    case default\n       write(level_type, '(\"Unrecognized level type:  \", I10)') grib%g1sec1%leveltyp\n    case (1)\n       level_type = \"Ground or water surface\"\n    case (2)\n       level_type = \"Cloud base level\"\n    case (3)\n       level_type = \"Cloud top level\"\n    case (4)\n       level_type = \"Level of 0{o} C isotherm\"\n    case (5)\n       level_type = \"Level of adiabatic condensation lifted from surface\"\n    case (6)\n       level_type = \"Maximum wind level\"\n    case (7)\n       level_type = \"Tropopause\"\n    case (8)\n       level_type = \"Nominal top of atmosphere\"\n    case (9)\n       level_type = \"Sea Bottom\"\n    case (20)\n       level_type = \"Isothermal level\"\n       level_units = \"K\"\n       level_value = grib%g1sec1%levelval\n    case (100)\n       level_type = \"Isobaric level\"\n       level_units = \"Pa\"\n       level_value = grib%g1sec1%levelval\n    case (101)\n       level_type = \"Layer between two isobaric levels\"\n       level_units = \"kPa\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (102)\n       level_type = \"Mean Sea Level\"\n       level_units = \"MSL\"\n    case (103)\n       level_type = \"Specified altitude above MSL\"\n       level_units = \"m\"\n       level_value = grib%g1sec1%levelval\n    case (104)\n       level_type = \"Layer between two specified altitudes above MSL\"\n       level_units = \"hm\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (105)\n       level_type = \"Specified height level above ground\"\n       level_units = \"m\"\n       level_value = grib%g1sec1%levelval\n    case (106)\n       level_type = \"Layer between two specified height levels above ground\"\n       level_units = \"hm\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (107)\n       level_type = \"Sigma level\"\n       level_units = \"Sigma value\"\n       level_value = grib%g1sec1%levelval\n    case (108)\n       level_type = \"Layer between two sigma levels\"\n       level_units = \"Sigma value\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (109)\n       level_type = \"Hybrid level\"\n       level_units = \"Level number\"\n       level_value = grib%g1sec1%levelval\n    case (110)\n       level_type = \"Layer between two hybrid levels\"\n       level_units = \"Level number\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (111)\n       level_type = \"Depth below land surface\"\n       level_units = \"m\" ! Original data has cm, we convert to m\n       level_value = grib%g1sec1%levelval * 1.E-2 ! Converted to m\n    case (112)\n       level_type = \"Layer between two depths below land surface\"\n       level_units = \"m\"! Original data has cm, we convert to m\n       level_value = grib%g1sec1%levelval * 1.E-2   ! Converted to m\n       level2_value = grib%g1sec1%level2val * 1.E-2 ! Converted to m\n    case (113)\n       level_type = \"Isentropic level\"\n       level_units = \"K\"\n       level_value = grib%g1sec1%levelval\n    case (114)\n       level_type = \"Layer between two isentropic levels\"\n       level_units = \"K\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (115)\n       level_type = \"Level at specified pressure difference from ground\"\n       level_units = \"hPa\"\n       level_value = grib%g1sec1%levelval\n    case (116)\n       level_type = \"Layer between two levels at specified pressure differences from ground\"\n       level_units = \"hPa\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (117)\n       level_type = \"PV Surface\"\n       level_units = \"10{-6} K m{2} kg{-1} s{-1}\"\n       level_value = grib%g1sec1%levelval\n    case (119)\n       level_type = \"Eta level\"\n       level_units = \"Eta Value\"\n       level_value = grib%g1sec1%levelval\n    case (120)\n       level_type = \"Layer between two Eta levels\"\n       level_units = \"Eta Value\"\n       level_value = grib%g1sec1%levelval\n       level2_value = grib%g1sec1%level2val\n    case (200)\n       level_type = \"Entire atmosphere as a single column\"\n    case (204)\n       level_type = \"Highest tropospheric freezing level\"\n    case (209)\n       level_type = \"Boundary-layer cloud bottom level\"\n    case (210)\n       level_type = \"Boundary-layer cloud top level\"\n    case (211)\n       level_type = \"Boundary-layer cloud layer\"\n    case (212)\n       level_type = \"Low cloud bottom level\"\n    case (213)\n       level_type = \"Low cloud top level\"\n    case (214)\n       level_type = \"Low cloud layer\"\n    case (222)\n       level_type = \"Middle cloud bottom level\"\n    case (223)\n       level_type = \"Middle cloud top level\"\n    case (224)\n       level_type = \"Middle cloud layer\"\n    case (232)\n       level_type = \"High cloud bottom level\"\n    case (233)\n       level_type = \"High cloud top level\"\n    case (234)\n       level_type = \"High cloud layer\"\n    case (242)\n       level_type = \"Convective cloud bottom level\"\n    case (243)\n       level_type = \"Convective cloud top level\"\n    case (244)\n       level_type = \"Convective cloud layer\"\n    end select\n\n  end subroutine grib1_level_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec0(buffer, buffsize, iskip)\n    implicit none\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n    iskip = iskip + 8*8\n  end subroutine grib1_unpack_sec0\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec1(buffer, buffsize, iskip, sec1)\n    implicit none\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n    type (G1Section1Struct),               intent(out)   :: sec1\n\n    integer :: yy\n    integer :: century\n    integer :: gdsbms\n\n    sec1%isize      = unpack_unsigned_integer(buffer, 3, iskip)\n    sec1%ptvn       = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%center     = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%process    = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%grid       = unpack_unsigned_integer(buffer, 1, iskip)\n    gdsbms          = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%parameter  = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%leveltyp   = unpack_unsigned_integer(buffer, 1, iskip)\n    select case (sec1%leveltyp)\n    case default\n       sec1%levelval   = unpack_unsigned_integer(buffer, 2, iskip)\n       sec1%level2val  = -1.E36\n    case (107)\n       sec1%levelval   = 1.E-5 * unpack_unsigned_integer(buffer, 2, iskip) ! Sigma value conversion\n       sec1%level2val  = -1.E36\n    case (20)\n       sec1%levelval   = 1.E-2 * unpack_unsigned_integer(buffer, 2, iskip)\n       sec1%level2val  = -1.E36\n    case (108)\n       sec1%levelval   = 1.E-2 * unpack_unsigned_integer(buffer, 1, iskip)\n       sec1%level2val  = 1.E-2 * unpack_unsigned_integer(buffer, 1, iskip)\n    case (119)\n       sec1%levelval   = 1.E-5 * unpack_unsigned_integer(buffer, 2, iskip) ! Eta value conversion\n       sec1%level2val  = -1.E36\n    case (120)\n       sec1%levelval   = 1.E-2 * unpack_unsigned_integer(buffer, 1, iskip) ! Eta value conversion\n       sec1%level2val  = 1.E-2 * unpack_unsigned_integer(buffer, 1, iskip) ! Eta value conversion\n    case (101,102:104,106,110,112,114,116,121,128,141)\n       sec1%levelval   = unpack_unsigned_integer(buffer, 1, iskip)\n       sec1%level2val  = unpack_unsigned_integer(buffer, 1, iskip)\n    end select\n    yy              = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%month      = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%day        = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%hour       = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%minute     = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%ftu        = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%p1         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%p2         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%tri        = unpack_unsigned_integer(buffer, 1, iskip)\n    if ( sec1%tri == 10 ) then\n       ! The P1 value extends over two bytes.  P2 is not in the header.\n       sec1%p1 = ( sec1%p1 * 256 ) + sec1%p2\n       sec1%p2 = 0\n    endif\n    sec1%navg       = unpack_unsigned_integer(buffer, 2, iskip)\n    sec1%nmissavg   = unpack_unsigned_integer(buffer, 1, iskip)\n    century         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%subcenter  = unpack_unsigned_integer(buffer, 1, iskip)\n    sec1%decimal_scale_factor  = unpack_signed_integer(buffer, 2, iskip)\n\n    select case (gdsbms)\n    case default\n       write(*,'(\"WARNING: GRIB1_UNPACK_SEC1:  GRIB1 Section 1:  Unrecognized GDS/BMS flag: \", I10)') gdsbms\n       stop \"FATAL ERROR: In module module_grib1.F -- GRIB1 Section 1: Unrecognized GDS/BMS flag\"\n    case (0)\n       sec1%ifgds = .FALSE.\n       sec1%ifbms = .FALSE.\n    case (64)\n       sec1%ifgds = .FALSE.\n       sec1%ifbms = .TRUE.\n    case (128)\n       sec1%ifgds = .TRUE.\n       sec1%ifbms = .FALSE.\n    case (192)\n       sec1%ifgds = .TRUE.\n       sec1%ifbms = .TRUE.\n    end select\n\n    if ( yy > 0 ) then\n       sec1%year       = (century-1) * 100 + yy\n    else\n       sec1%year       = century * 100\n    endif\n\n    write(sec1%hdate, '(I4.4,\"-\",I2.2,\"-\",I2.2,\"_\",I2.2,\":\",I2.2,\":\",I2.2)') &\n         sec1%year, sec1%month, sec1%day, sec1%hour, sec1%minute, 00\n\n  end subroutine grib1_unpack_sec1\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec2(buffer, buffsize, iskip, sec2)\n    implicit none\n\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n    type (G1Section2Struct),               intent(inout) :: sec2\n    integer :: idum\n\n    sec2%isize      = unpack_unsigned_integer(buffer, 3, iskip)\n    sec2%nv         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec2%pv         = unpack_unsigned_integer(buffer, 1, iskip)\n    sec2%drt        = unpack_unsigned_integer(buffer, 1, iskip)\n\n    select case (sec2%drt)\n    case (0) ! Lat/Lon grid\n\n       sec2%nx = unpack_unsigned_integer(buffer, 2, iskip)\n       sec2%ny = unpack_unsigned_integer(buffer, 2, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       if (idum == 90000) then\n          sec2%lat1 = 90.0\n       elseif (idum == -90000) then\n          sec2%lat1 = -90.0\n       else\n          sec2%lat1 = ((real(idum)*1.E-1)*1.E-1)*1.E-1\n       endif\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lon1 = real(idum)*1.E-3\n       sec2%rac = unpack_unsigned_integer(buffer, 1, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lat2 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lon2 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 2, iskip)\n       sec2%dx = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 2, iskip)\n       sec2%dy = real(idum)*1.E-3\n       sec2%scanning_mode = unpack_unsigned_integer(buffer, 1, iskip)\n\n       if ( btest(sec2%scanning_mode, 7) ) then\n          sec2%i_scan_direction = -1\n       else\n          sec2%i_scan_direction = 1\n       endif\n\n       if ( btest(sec2%scanning_mode, 6) ) then\n          sec2%j_scan_direction = 1\n       else\n          sec2%j_scan_direction = -1\n       endif\n\n       if ( btest(sec2%scanning_mode, 5) ) then\n          sec2%orientation = -1\n       else\n          sec2%orientation = 1\n       endif\n\n       ! Skip those last four bytes:\n       iskip = iskip + (4*8)\n\n       sec2%latin1 = -1.E36\n       sec2%latin2 = -1.E36\n\n    case (3) ! Lambert Conformal grid\n\n       sec2%nx = unpack_unsigned_integer(buffer, 2, iskip)\n       sec2%ny = unpack_unsigned_integer(buffer, 2, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lat1 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lon1 = real(idum)*1.E-3\n       sec2%rac = unpack_unsigned_integer(buffer, 1, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lov = real(idum)*1.E-3\n       idum = unpack_unsigned_integer(buffer, 3, iskip)\n       sec2%dx = real(idum)*1.E-3\n       idum = unpack_unsigned_integer(buffer, 3, iskip)\n       sec2%dy = real(idum)*1.E-3\n       sec2%center = unpack_unsigned_integer(buffer, 1, iskip)\n       sec2%scanning_mode = unpack_unsigned_integer(buffer, 1, iskip)\n\n       if ( btest(sec2%scanning_mode, 7) ) then\n          sec2%i_scan_direction = -1\n       else\n          sec2%i_scan_direction = 1\n       endif\n\n       if ( btest(sec2%scanning_mode, 6) ) then\n          sec2%j_scan_direction = 1\n       else\n          sec2%j_scan_direction = -1\n       endif\n\n       if ( btest(sec2%scanning_mode, 5) ) then\n          sec2%orientation = -1\n       else\n          sec2%orientation = 1\n       endif\n\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%latin1 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%latin2 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%polelat = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%polelon = real(idum)*1.E-3\n       ! Skip those last two bytes:\n       iskip = iskip + 16\n       ! print*, 'nx, ny = ', sec2%nx, sec2%ny\n       ! print*, 'lat1, lon1 = ', sec2%lat1, sec2%lon1\n       ! print*, 'lov, truelat1, truelat2 = ', sec2%lov, sec2%latin1, sec2%latin2\n       ! print*, 'dx, dy = ', sec2%dx, sec2%dy\n\n    case (5) ! Polar Stereographic grid\n\n       sec2%nx = unpack_unsigned_integer(buffer, 2, iskip)\n       sec2%ny = unpack_unsigned_integer(buffer, 2, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lat1 = real(idum)*1.E-3\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lon1 = real(idum)*1.E-3\n       sec2%rac = unpack_unsigned_integer(buffer, 1, iskip)\n       idum          = unpack_signed_integer(buffer, 3, iskip)\n       sec2%lov = real(idum)*1.E-3\n       idum = unpack_unsigned_integer(buffer, 3, iskip)\n       sec2%dx = real(idum) * 1.E-3\n       idum = unpack_unsigned_integer(buffer, 3, iskip)\n       sec2%dy = real(idum) * 1.E-3\n       sec2%center = unpack_unsigned_integer(buffer, 1, iskip)\n       sec2%scanning_mode = unpack_unsigned_integer(buffer, 1, iskip)\n\n       if ( btest(sec2%scanning_mode, 7) ) then\n          sec2%i_scan_direction = -1\n       else\n          sec2%i_scan_direction = 1\n       endif\n\n       if ( btest(sec2%scanning_mode, 6) ) then\n          sec2%j_scan_direction = 1\n       else\n          sec2%j_scan_direction = -1\n       endif\n\n       if ( btest(sec2%scanning_mode, 5) ) then\n          sec2%orientation = -1\n       else\n          sec2%orientation = 1\n       endif\n\n       if (sec2%center==0) then\n          sec2%latin1 = 60.0\n       else\n          sec2%latin1 = -60.0\n       endif\n       sec2%latin2 = -1.E36\n       ! Skip those last four bytes:\n       iskip = iskip + (4*8)\n       ! print*, 'nx, ny = ', sec2%nx, sec2%ny\n       ! print*, 'lat1, lon1 = ', sec2%lat1, sec2%lon1\n       ! print*, 'lov, truelat1, truelat2 = ', sec2%lov, sec2%latin1, sec2%latin2\n       ! print*, 'dx, dy = ', sec2%dx, sec2%dy\n\n    case default\n\n       write(*,'(\"WARNING: GRIB1_UNPACK_SEC2:  Unrecognized GRIB1 grid type (drt):  \", I10)') sec2%drt\n       stop \"FATAL ERROR: In module module_grib1.F -- Unrecognized GRIB1 grid type (drt)\"\n\n    end select\n\n  end subroutine grib1_unpack_sec2\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec3(grib)\n    ! Bit Map Section (bitmap section)\n    implicit none\n    type (GribStruct),                     intent(inout) :: grib\n\n    integer :: bitmap_beginning\n    integer :: bitmap_length\n    integer :: idim, jdim\n\n    grib%g1sec3%isize      = unpack_unsigned_integer(grib%buffer, 3, grib%iskip)\n    grib%g1sec3%nunused    = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%g1sec3%numeric    = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n\n    grib%g1sec3%bitmap_beginning = grib%iskip/8\n    bitmap_length    = grib%g1sec3%isize-6\n\n    ! I may need to reorient the bitmap, too, depending on data ordering....\n    idim = grib%g1sec2%nx\n    jdim = grib%g1sec2%ny\n    allocate(grib%bitmap(idim,jdim))\n    call gbytes(grib%buffer, grib%bitmap, grib%g1sec3%bitmap_beginning*8, 1, 0, idim*jdim)\n\n    ! And skip to the end of the section\n    grib%iskip = grib%iskip + (bitmap_length*8)\n\n  end subroutine grib1_unpack_sec3\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec4(buffer, buffsize, iskip, sec4)\n    implicit none\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n    type (G1Section4Struct),               intent(out)   :: sec4\n\n    integer :: n\n    real    :: xref2\n    integer :: isign, characteristic, mantissa\n\n    sec4%isize      = unpack_unsigned_integer(buffer, 3, iskip)\n\n    do n = 1, 4\n       call gbyte(buffer, sec4%flag(n), iskip, 1)\n       iskip = iskip + 1\n    enddo\n    call gbyte(buffer, sec4%nunused, iskip, 4)\n    iskip = iskip + 4\n\n    sec4%binary_scale_factor  = unpack_signed_integer(buffer, 2, iskip)\n\n    ! Unpack the floating-point number\n    call gbyte(buffer, isign, iskip, 1)\n    iskip = iskip + 1\n    call gbyte(buffer, characteristic, iskip, 7)\n    iskip = iskip + 7\n    call gbyte(buffer, mantissa, iskip, 24)\n    iskip = iskip + 24\n    ! print*, 'isign = ', isign\n    ! print*, 'characteristic = ', characteristic\n    ! print*, 'mantissa = ', mantissa\n    xref2 = real(dble(mantissa) / dble(2**24) * dble(16 ** (characteristic-64)))\n    if (isign==1) xref2 = -xref2\n    ! print*, 'Reference value = ', xref2\n    sec4%reference_value = xref2\n    sec4%nbits = unpack_unsigned_integer(buffer, 1, iskip)\n\n    sec4%start_of_packed_data = iskip/8\n\n    ! Skip to the end of this section\n    iskip = iskip + (sec4%isize-11)*8\n\n  end subroutine grib1_unpack_sec4\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_unpack_sec5(buffer, buffsize, iskip)\n    implicit none\n    ! Real simple.  Just check for the \"7777\" flag which marks the end of the\n    ! GRIB1 record.\n    integer,                               intent(in)    :: buffsize\n    character(len=1), dimension(buffsize), intent(in)    :: buffer\n    integer,                               intent(inout) :: iskip\n\n    integer :: test_sevens\n\n    test_sevens = unpack_unsigned_integer(buffer, 4, iskip)\n    if (test_sevens /= string_sevens) then\n       write(*, '(\"WARNING:  MODULE_GRIB1:  GRIB1_UNPACK_SEC5:  Problem:  Lost the way in GRIB1 record.\")')\n       stop \"FATAL ERROR: In module module_grib1.F -- Problem: Lost the way in GRIB1 record.\"\n    endif\n\n  end subroutine grib1_unpack_sec5\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_gribdata(grib)\n    implicit none\n    type (GribStruct)                     :: grib\n    ! real, pointer, dimension(:,:) :: array\n\n    if (grib%g1sec4%flag(1)==0) then\n       ! Grid-point data\n       if (grib%g1sec4%flag(2) == 0) then\n          ! Simple packing\n          if (grib%g1sec4%flag(3)==0) then\n             ! Original field held floating-point values\n             if (grib%g1sec4%flag(4)==0) then\n                ! No additional flags in octet 14\n                allocate(grib%array(grib%mapinfo%nx,grib%mapinfo%ny))\n                if (grib%g1sec1%ifbms) then\n                   call grib1_sgup_bitmap(grib, grib%array, grib%bitmap, grib%mapinfo%nx, grib%mapinfo%ny)\n                else\n                   call grib1_sgup_nobitmap(grib, grib%array, grib%mapinfo%nx, grib%mapinfo%ny)\n                endif\n             else\n                stop \"FATAL ERROR: In module module_grib1.F -- GRIB1:  Section 4:  Additional flags in octed 14\"\n             endif\n          else\n             stop \"FATAL ERROR: In module module_grib1.F -- GRIB1:  Section 4:  Original field held integer values.\"\n          endif\n       else\n          stop \"FATAL ERROR: In module module_grib1.F -- GRIB1:  Section 4:  Complex packing\"\n       endif\n    else\n       stop \"FATAL ERROR: In module module_grib1.F -- GRIB1:  Section 4:  Spherical Harmonic coefficients\"\n    endif\n\n  end subroutine grib1_gribdata\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_map_information(sec2, mapinfo)\n    implicit none\n    type(G1Section2Struct), intent(in) :: sec2\n    type(MapInfoStruct), intent(out)   :: mapinfo\n    select case (sec2%drt)\n    case default\n       write(*, '(\"WARNING: Unrecognized GRIB1 grid data representation type:  \", I12)') sec2%drt\n       stop \"FATAL ERROR: In module module_grib1.F -- GRIB1_MAP_INFORMATION:  Unrecognized grid data representation type.\"\n    case (0) ! Cylindrical Equidistant\n       mapinfo%hproj = \"CE\"\n       mapinfo%supmap_jproj = 8\n       mapinfo%nx   = sec2%nx\n       mapinfo%ny   = sec2%ny\n       mapinfo%dx   = sec2%dx\n       mapinfo%dy   = sec2%dy * sec2%j_scan_direction\n       mapinfo%lat1 = sec2%lat1\n       mapinfo%lon1 = sec2%lon1\n       mapinfo%lat2 = sec2%lat2\n       mapinfo%lon2 = sec2%lon2\n       mapinfo%xlonc    = -1.E33\n       mapinfo%truelat1 = -1.E33\n       mapinfo%truelat2 = -1.E33\n    case (3) ! Lambert Conformal\n       mapinfo%hproj = \"LC\"\n       mapinfo%supmap_jproj = 3\n       mapinfo%nx   = sec2%nx\n       mapinfo%ny   = sec2%ny\n       mapinfo%dx   = sec2%dx\n       mapinfo%dy   = sec2%dy\n       mapinfo%lat1 = sec2%lat1\n       mapinfo%lon1 = sec2%lon1\n       mapinfo%lat2 = -1.E36\n       mapinfo%lon2 = -1.E36\n       mapinfo%xlonc = sec2%lov\n       mapinfo%truelat1 = sec2%latin1\n       mapinfo%truelat2 = sec2%latin2\n    case (5) ! Polar Stereographic\n       mapinfo%hproj = \"ST\"\n       mapinfo%supmap_jproj = 1\n       mapinfo%nx   = sec2%nx\n       mapinfo%ny   = sec2%ny\n       mapinfo%dx   = sec2%dx\n       mapinfo%dy   = sec2%dy\n       mapinfo%lat1 = sec2%lat1\n       mapinfo%lon1 = sec2%lon1\n       mapinfo%lat2 = -1.E36\n       mapinfo%lon2 = -1.E36\n       mapinfo%xlonc = sec2%lov\n       mapinfo%truelat1 = sec2%latin1\n       mapinfo%truelat2 = sec2%latin2\n    end select\n  end subroutine grib1_map_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine GRIB1_SGUP_NOBITMAP(grib, array, idim, jdim)\n    ! GRIB 1 Data unpacking:  Simple grid-point unpacking without a bitmap\n    implicit none\n    type (GribStruct) :: grib\n    integer, intent(in) :: idim, jdim\n    real, dimension(idim*jdim), intent(out) :: array\n\n    integer, dimension(idim*jdim) :: IX\n    double precision :: dfac, bfac\n    integer :: iskip\n\n    integer :: i, j, m, n\n\n    DFAC = 1.0 / (10.D0**(grib%g1sec1%decimal_scale_factor))\n    BFAC = 2.D0**(grib%g1sec4%binary_scale_factor)\n\n! sec4%nbits is the number of bits used per datum.\n! If sec4%nbits = 255, assume they mean sec4%nbits = 0\n\n    if (grib%g1sec4%nbits == 255) grib%g1sec4%nbits = 0\n\n    if (grib%g1sec4%nbits > 0) then\n       call gbytes(grib%buffer, IX, grib%g1sec4%start_of_packed_data*8, grib%g1sec4%nbits, 0, idim*jdim)\n    endif\n\n! If sec4(8) is 0, assume datarray is constant, scaled from the value of sec4%reference_value\n\n    if (grib%g1sec4%nbits == 0) then\n       array = DFAC * grib%g1sec4%reference_value\n    else\n       ! Check point order!!!\n\n       if (grib%g1sec2%orientation == 1) then\n          ! We're good.  Fortran(i,j)\n       elseif (grib%g1sec2%orientation == -1) then\n          write(*,'(\"grib%g1sec2%orientation = \", I12)') grib%g1sec2%orientation\n          stop \"FATAL ERROR: In module module_grib1.F -- TODO:  GRIB1_SGUP_NOBITMAP:  grib%g1sec2%orientation = -1\"\n       else\n          write(*,'(\"grib%g1sec2%orientation = \", I12)') grib%g1sec2%orientation\n          stop \"FATAL ERROR: In module module_grib1.F -- TODO:  GRIB1_SGUP_NOBITMAP:  Problem recognizing grib%g1sec2%orientation\"\n       endif\n\n       if (grib%g1sec2%i_scan_direction == 1) then\n          ! We're good.\n       elseif (grib%g1sec2%i_scan_direction == -1) then\n          write(*,'(\"grib%g1sec2%i_scan_direction = \", I12)') grib%g1sec2%i_scan_direction\n          stop \"FATAL ERROR: In module module_grib1.F -- TODO:  GRIB1_SGUP_NOBITMAP:  grib%g1sec2%i_scan_direction = -1\"\n       else\n          write(*,'(\"grib%g1sec2%i_scan_direction = \", I12)') grib%g1sec2%i_scan_direction\n          stop \"FATAL ERROR: In module module_grib1.F -- GRIB1_SGUP_NOBITMAP:   Problem recognizing grib%g1sec2%i_scan_direction\"\n       endif\n\n       if (grib%g1sec2%j_scan_direction == 1) then\n          array = DFAC * (dble(grib%g1sec4%reference_value) + (dble(IX)*BFAC))\n       elseif (grib%g1sec2%j_scan_direction == -1) then\n          do j = 1, jdim\n             do i = 1, idim\n                n = (j-1)*idim + i\n                m = (jdim-j)*idim + i\n                array(n) = DFAC * (dble(grib%g1sec4%reference_value) + (dble(IX(m))*BFAC))\n             enddo\n          enddo\n       else\n          write(*,'(\"grib%g1sec2%j_scan_direction = \", I12)') grib%g1sec2%j_scan_direction\n          stop \"FATAL ERROR: In module module_grib1.F -- GRIB1_SGUP_NOBITMAP:  Problem recognizing grib%g1sec2%j_scan_direction\"\n       endif\n    endif\n\n  end subroutine GRIB1_SGUP_NOBITMAP\n\n!=================================================================================\n!=================================================================================\n\n  subroutine GRIB1_SGUP_BITMAP(grib, array, bitmap, nx, ny)\n    ! Simple grid-point unpacking, with a bitmap.\n    implicit none\n    type (GribStruct)      :: grib\n    integer, intent(in) :: nx, ny\n    real, dimension(nx*ny), intent(out) :: array\n    integer, dimension(nx*ny), intent(in) :: bitmap\n\n    type(G1Section1Struct), pointer :: sec1\n    type(G1Section3Struct), pointer :: sec3\n    type(G1Section4Struct), pointer :: sec4\n\n    integer :: ndat ! Number of data points in the final grid.\n    double precision :: dfac, bfac\n    integer :: iskip, nbm, i, nn\n\n    integer, allocatable, dimension(:) :: bmdat\n\n    array = -1.E30\n\n    ndat = nx * ny\n\n!\n! Compute the parameters involved with packing\n!\n    DFAC = 1.0 / 10.**(grib%g1sec1%decimal_scale_factor)\n    BFAC = 2.**grib%g1sec4%binary_scale_factor\n\n! grib%g1sec4%isize   : The number of bytes in the whole of GRIB Grib%g1section 4.\n! grib%g1sec4%nunused : The number of unused bits at the end of GRIB Section 4.\n! GRIB%G1SEC4%nbits : The number of bits per data value.\n\n\n! 1) There are fewer than NDAT data values, because a bitmap was used.\n!    Compute the number of data values (NBM).  There are 11 extra bytes\n!    in the header section 4.  NBM equals the total number of data bits (not\n!    counting the header bits), minus the number of unused buts, and then\n!    divided by the number of bits per data value.\n\n! If grib%g1sec4%nbits is 0, assume <array> is constant value of DFAC * grib%g1sec4%reference_value\n\n    if (grib%g1sec4%nbits.eq.0) then\n       where(bitmap(1:ndat)==1) array = DFAC * grib%g1sec4%reference_value\n       return\n    endif\n    nbm = ((grib%g1sec4%isize-11)*8-grib%g1sec4%nunused)/grib%g1sec4%nbits\n    allocate(bmdat(nbm))\n    if (nbm /= count(bitmap==1)) then\n       print*, \"NBM, count(bitmap==1):  \", nbm, count(bitmap==1)\n       write(*,'(\"WARNING: GRIB1_SGUP_BITMAP:  Problem with the number of data values in the bitmap.\")')\n       stop \"FATAL ERROR: In module module_grib1.F -- Problem with the number of data values in the bitmap\"\n    endif\n\n! grib%g1sec4%nbits is the number of bits used per datum value.\n! If grib%g1sec4%nbits = 255, assume they mean grib%g1sec4%nbits = 0\n    if (grib%g1sec4%nbits == 255) grib%g1sec4%nbits = 0\n\n! Read the data from the <buffer> array\n    call gbytes(grib%buffer, bmdat, grib%g1sec4%start_of_packed_data*8, grib%g1sec4%nbits, 0, nbm)\n\n    if (grib%g1sec2%orientation == 1) then\n       ! We're good.  Fortran(i,j)\n    elseif (grib%g1sec2%orientation == -1) then\n       write(*,'(\"grib%g1sec2%orientation = \", I12)') grib%g1sec2%orientation\n       stop \"FATAL ERROR: In module module_grib1.F -- TODO:  GRIB1_SGUP_BITMAP:  grib%g1sec2%orientation = -1\"\n    else\n       write(*,'(\"grib%g1sec2%orientation = \", I12)') grib%g1sec2%orientation\n       stop \"FATAL ERROR: In module module_grib1.F -- TODO:  GRIB1_SGUP_BITMAP:  Problem recognizing grib%g1sec2%orientation\"\n    endif\n\n! Check the i scan direction:\n    if (grib%g1sec2%i_scan_direction == 1) then\n       ! We're good.\n    elseif (grib%g1sec2%i_scan_direction == -1) then\n       write(*,'(\"grib%g1sec2%i_scan_direction = \", I12)') grib%g1sec2%i_scan_direction\n       stop \"FATAL ERROR: In module module_grib1.F -- TODO:  GRIB1_SGUP_BITMAP:  grib%g1sec2%i_scan_direction = -1\"\n    else\n       write(*,'(\"grib%g1sec2%i_scan_direction = \", I12)') grib%g1sec2%i_scan_direction\n       stop \"FATAL ERROR: In module module_grib1.F -- GRIB1_SGUP_BITMAP:  Problem recognizing grib%g1sec2%i_scan_direction\"\n    endif\n\n! Check the j scan direction:\n    if (grib%g1sec2%j_scan_direction == 1) then\n       ! We're good.\n    elseif (grib%g1sec2%j_scan_direction == -1) then\n       write(*,'(\"grib%g1sec2%j_scan_direction = \", I12)') grib%g1sec2%j_scan_direction\n       ! stop \"TODO:  GRIB1_SGUP_BITMAP:  grib%g1sec2%j_scan_direction = -1\"\n    else\n       write(*,'(\"grib%g1sec2%j_scan_direction = \", I12)') grib%g1sec2%j_scan_direction\n       stop \"FATAL ERROR: In module module_grib1.F -- GRIB1_SGUP_BITMAP:  Problem recognizing grib%g1sec2%j_scan_direction\"\n    endif\n\n\n\n! Unpack the data according to packing parameters DFAC, BFAC, and XEC4(1),\n! and masked by the bitmap BITMAP.\n    nn = 0\n    do i = 1, ndat\n       if (bitmap(i)==1) then\n          nn = nn + 1\n          array(i) = DFAC * (dble(grib%g1sec4%reference_value) + (dble(bmdat(nn))*BFAC))\n       endif\n    enddo\n\n! Deallocate the scratch BMDAT array\n    deallocate(bmdat)\n  end subroutine GRIB1_SGUP_BITMAP\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_valid_date(sec1, validdate)\n    implicit none\n    type(G1Section1Struct), intent(in) :: sec1\n    character(len=19), intent(out) :: validdate\n\n    character(len=19) :: refdate\n    integer :: tfac\n\n    refdate = sec1%hdate\n\n    ! Find TFAC, which is a factor to convert the given time offset\n    ! to seconds.\n    select case (sec1%ftu)\n    case (0)\n       tfac = 60\n    case (1)\n       tfac = 3600\n    case (2)\n       tfac = 86400\n    case (10)\n       tfac = 10800\n    case (11)\n       tfac = 21600\n    case (12)\n       tfac = 43200\n    case (254)\n       tfac = 1\n    case default\n       write(*, '(\"WARNING: Unrecognized GRIB1 Forecast Time Unit: \", I6)') sec1%ftu\n       stop \"FATAL ERROR: In module module_grib1.F -- Unrecognized GRIB1 Forecast Time Unit\"\n    end select\n\n    select case (sec1%tri) ! \"Time Range Indicator\"\n    case default\n       write(*, '(\"WARNING: Unrecognized GRIB1 Time Range Indicator: \", I6)') sec1%tri\n       stop \"FATAL ERROR: In module module_grib1.F -- Unrecognized GRIB1 Time Range Indicator\"\n    case (3) ! Average\n       ! Average from (reference_time + p1) to (reference time + p2)\n       call geth_newdate(validdate, refdate, tfac*(sec1%p1+sec1%p2)/2)\n    case(4) ! Accumulation from refdate + P1 to refdate + P2,\n       ! valid at refdate + P2\n       ! call geth_newdate(fdate,     refdate, tfac*sec1(17))\n       call geth_newdate(validdate, refdate, tfac*sec1%p2)\n!       if (present(offset)) then\n!          offset = tfac*(sec1%p2-sec1%p1)\n!       endif\n    case(5) ! Difference, valid at refdate + P2\n       call geth_newdate(validdate, refdate, tfac*sec1%p2)\n    case (0:1,10) ! Product valid at refdate + P1\n       call geth_newdate(validdate, refdate, tfac*sec1%p1)\n    end select\n\n  end subroutine grib1_valid_date\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib1_read_parameter_tables\n    implicit none\n    character(len=256) :: grib_root\n    character(len=256) :: table_filename\n    integer :: iunit\n    integer :: ierr\n    integer :: p1\n    integer :: p2\n    integer :: p3\n    integer, external :: get_unused_unit\n\n    character(len=200) :: string\n    character(len=256) :: parameter_name\n    character(len=64)  :: parameter_units\n    character(len=8)   :: parameter_abbr\n    integer            :: parameter_index\n\n    call getenv(\"GRIB_ROOT\", grib_root)\n    if (trim(grib_root)==\" \") then\n       write(*,'(\"WARNING: Not finding environment variable GRIB_ROOT.\")')\n       write(*,'(\"WARNING: Program does not know where to find GRIB parameter tables\")')\n       stop \"FATAL ERROR: In module module_grib1.F -- Not finding environment variable GRIB_ROOT\"\n    endif\n    table_filename = trim(grib_root)//\"/GRIB1_PARAMETER_TABLE\"\n\n    iunit = get_unused_unit()\n\n#ifndef NCEP_WCOSS\n\n#else\n    open(iunit, file=trim(table_filename), status='old', form='formatted', action='read', iostat=ierr)\n#endif\n    if (ierr /= 0) then\n       write(*,'(/,\"WARNING:  ***** ERROR *****\",/)')\n       write(*,'(\"WARNING:  ***** Problem opening file ''\", A, \"''\")') trim(table_filename)\n       write(*,'(\"WARNING:  ***** Does file exist?  Is file readable?\",/)')\n       stop \"FATAL ERROR: In module module_grib1.F -- Unable to open file\"\n    endif\n\n    READ_TABLE : do\n#ifndef NCEP_WCOSS\n\n#else\n       read(iunit, '(A200)', iostat=ierr) string\n#endif\n       if (ierr /= 0) exit READ_TABLE\n       if (string(1:1) == \"#\") cycle READ_TABLE\n\n       p1 = index(string, \"|\") - 1\n       p2 = p1 + index(string(p1+2:), \"|\")\n       p3 = p2 + index(string(p2+2:), \"|\")\n       read(string(1:p1),*) parameter_index\n       parameter_name = trim(adjustl(string(p1+2:p2)))\n       parameter_units = trim(adjustl(string(p2+2:p3)))\n       parameter_abbr = trim(adjustl(string(p3+2:)))\n       ! write(*, '(I3,1x,\"#\",A,\"#\",1x,\"#\",A,\"#\",1x,\"#\",A,\"#\")') parameter_index, trim(parameter_name), trim(parameter_units), trim(parameter_abbr)\n       grib1_parameter_table(parameter_index)%name  = trim(parameter_name)\n       grib1_parameter_table(parameter_index)%units = trim(parameter_units)\n       grib1_parameter_table(parameter_index)%abbr  = trim(parameter_abbr)\n\n    enddo READ_TABLE\n#ifndef NCEP_WCOSS\n\n#else\n    close(iunit)\n#endif\n  end subroutine grib1_read_parameter_tables\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib1\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_grib2.F",
    "content": "module module_grib2\n  use module_mapinfo\n  use module_grib2_tables\n  use kwm_date_utilities\n  use module_grib_common\n  implicit none\n\ncontains\n\n!==============================================================================\n!==============================================================================\n  subroutine grib2_gribdata(grib)\n    implicit none\n    type (GribStruct), intent(inout) :: grib\n    ! Reorient data as necessary to put grib%array(1,1) at the lower left corner\n  end subroutine grib2_gribdata\n\n!==============================================================================\n!==============================================================================\n\n  subroutine grib2_valid_date(grib, validdate)\n    ! Hmmmm.  This could also be a subfunction of unpacking\n    ! GRIB2 section 4, and making <validdate> an element of <grib>\n    implicit none\n    type (GribStruct), intent(in)  :: grib\n    character(len=19), intent(out) :: validdate\n    !\n    !Local:\n    character(len=19) :: refdate\n    integer :: fcst_time\n    integer :: time_factor\n\n    refdate = grib%sec1%hdate\n\n    select case (grib%sec1%srt) ! Check the \"significance of reference time\"\n    case default\n       write(*,'(\"WARNING: Unrecognized ''Significance of Reference Time'' (GRIB2, section 1, octet 12):  \", I10)') grib%sec1%srt\n       stop \"FATAL ERROR: In module module_grib2.F -- Unrecognized Significance of Reference Time\"\n\n    case (0:1)  ! <grib%sec1%hdate> refers to the analysis time(0) or forecast start time (1)\n\n       select case (grib%sec4%product_template_number) ! Check the product template number\n       case default\n          write(*,'(\"WARNING: Unrecognized Product Definition Template: \", I8)') grib%sec4%product_template_number\n       case (0) ! Analysis or forecast at a point in time\n          fcst_time = grib%sec4%time\n          select case (grib%sec4%time_range_indicator) ! Check the units on the time\n          case default\n             write(*,'(\"WARNING: Unrecognized time range indicator: \", I8)') grib%sec4%time_range_indicator\n             stop \"FATAL ERROR: In module module_grib2.F -- Unrecognized time range indicator\"\n          case (0) ! Time in minutes\n             time_factor = 60\n             call geth_newdate(validdate(1:19), refdate(1:19), fcst_time*time_factor)\n          case (1) ! Time in hours\n             time_factor = 3600\n             call geth_newdate(validdate(1:19), refdate(1:19), fcst_time*time_factor)\n          end select\n       end select\n!       case (2)  ! <grib%sec1%hdate> refers to the forecast valid time\n    end select\n  end subroutine grib2_valid_date\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_map_information(grib)\n    implicit none\n    type(GribStruct), intent(inout) :: grib\n\n    select case (grib%sec3%grid_template_number)\n    case default\n       write(*, '(\"WARNING: Unrecognized GRIB 2 grid template number:  \", I12)') grib%sec3%grid_template_number\n       stop \"FATAL ERROR: In module module_grib2.F -- GRIB2_MAP_INFORMATION:  Unrecognized grid template number.\"\n    case (0)\n       ! call print_sec3(grib, 10000)\n       grib%mapinfo%hproj = \"CE\"\n       grib%mapinfo%supmap_jproj = 8\n       grib%mapinfo%nx = grib%sec3%nx\n       grib%mapinfo%ny = grib%sec3%ny\n       grib%mapinfo%dx = grib%sec3%gt_3_0%dx\n       grib%mapinfo%dy = grib%sec3%gt_3_0%dy * grib%sec3%gt_3_0%j_scan_direction\n       grib%mapinfo%lat1 = grib%sec3%GT_3_0%la1\n       grib%mapinfo%lon1 = grib%sec3%GT_3_0%lo1\n       grib%mapinfo%xlonc = -1.E33\n       grib%mapinfo%truelat1 = -1.E33\n       grib%mapinfo%truelat1 = -1.E33\n    case (30)\n       grib%mapinfo%hproj = \"LC\"\n       grib%mapinfo%supmap_jproj = 3\n       grib%mapinfo%nx = grib%sec3%nx\n       grib%mapinfo%ny = grib%sec3%ny\n       grib%mapinfo%dx = grib%sec3%GT_3_30%dx\n       grib%mapinfo%dy = grib%sec3%GT_3_30%dy\n       grib%mapinfo%lat1 = grib%sec3%GT_3_30%la1\n       grib%mapinfo%lon1 = grib%sec3%GT_3_30%lo1\n       grib%mapinfo%xlonc = grib%sec3%GT_3_30%lov\n       grib%mapinfo%truelat1 = grib%sec3%GT_3_30%latin1\n       grib%mapinfo%truelat2 = grib%sec3%GT_3_30%latin2\n    end select\n  end subroutine grib2_map_information\n\n\n!=================================================================================\n!=================================================================================\n\n  subroutine fortran_decode_jpeg2000(buffer, buffer_length, decoded)\n    implicit none\n    !\n    ! Purpose:\n    !      Take a character array <buffer> which contains a JPEG2000-encoded field,\n    !      and return the decoded field as an integer array.  This subroutine is \n    !      simply a wrapper for the c code that decodes jpeg2000 streams.\n    !\n    ! Input:\n    !      buffer:        Character buffer which holds the JPEG2000-encoded field.\n    !      buffer_length: Size of character array <buffer>.\n    !\n    ! Output\n    !      decoded:       Pointer to an integer array representing the decoded field.\n    !\n    ! Side Effects:\n    !      Any?  Probably some in the subroutines called from this routine.\n    !\n    integer,                                    intent(in) :: buffer_length\n    character(len=1), dimension(buffer_length), intent(in) :: buffer\n    integer, pointer, dimension(:)                         :: decoded\n\n    ! Local:\n    integer         :: width\n    integer         :: height\n    integer(kind=8) :: image_pointer\n    integer(kind=8) :: stream_pointer\n    integer         :: allocation_status\n\n    call info_jpeg2000(buffer, buffer_length, width, height, image_pointer, stream_pointer)\n\n    allocate(decoded(width*height), stat=allocation_status)\n    if (allocation_status /= 0) then\n       write(*,'(\"WARNING: Problem allocating space in FORTRAN_DECODE_JPEG2000.\")')\n       stop \"FATAL ERROR: In module module_grib2.F -- Problem allocating space in FORTRAN_DECODE_JPEG2000\"\n    endif\n\n    call decode_jpeg2000(image_pointer, stream_pointer, width, height, decoded)\n\n  end subroutine fortran_decode_jpeg2000\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_parameter_text_information(grib, abbr, units, description)\n    implicit none\n    ! This could really be considered a substep of unpacking section 4.  Let's \n    ! move it there sometime, and create grib%abbr, grib%units, grib%description!\n    type (GribStruct), intent(in)  :: grib\n    character(len=16), intent(out) :: abbr\n    character(len=256), intent(out) :: units\n    character(len=256), intent(out) :: description\n    character(len=256) :: category_name\n\n    call get_parameter_table_information(grib%discipline, &\n         grib%sec4%parameter_category, grib%sec4%parameter_number, &\n         category_name, description, units)\n    abbr = \"ABBR\"\n\n  end subroutine grib2_parameter_text_information\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_time_information(grib, reference_date, valid_date, process, processing, p1_seconds, p2_seconds)\n    implicit none\n    type (GribStruct), intent(in)   :: grib\n    character(len=19), intent(out)  :: reference_date\n    character(len=19)  :: valid_date\n    character(len=256) :: process\n    character(len=256) :: processing\n    integer, intent(out)            :: p1_seconds\n    integer, intent(out)            :: p2_seconds\n\n    character(len=256) :: text3\n\n    reference_date = grib%sec1%hdate\n\n    select case (grib%sec1%srt)\n    case default\n       write(process,'(\"Unrecognized significance of reference time\")')\n       write(*,'(A)') trim(process)\n    case (0)\n       write(process,'(\"Analysis time:   \", A, 1x, A)') grib%sec1%hdate(1:10), grib%sec1%hdate(12:19)\n    case (1)\n       write(process,'(\"Start of forecast:   \", A, 1x, A)') grib%sec1%hdate(1:10), grib%sec1%hdate(12:19)\n    case (2)\n       write(process,'(\"Verifying time of forecast:   \", A, 1x, A)') grib%sec1%hdate(1:10), grib%sec1%hdate(12:19)\n    case (3)\n       write(process,'(\"Observation time:  \", A, 1x, A)') grib%sec1%hdate(1:10), grib%sec1%hdate(12:19)\n    end select\n\n    processing = \" \"\n    text3 = \" \"\n    select case (grib%sec4%product_template_number)\n    case default\n       write(processing,'(\"Unrecognized Product Definition Template: \", I8)') grib%sec4%product_template_number\n    case (0)\n       select case (grib%sec4%time_range_indicator)\n       case default\n          write(processing,'(\"Unrecognized time range indicator:\", I8)') grib%sec4%time_range_indicator\n          valid_date = \"0000-00-00_00:00:00\"\n          p1_seconds = 0\n          p2_seconds = 0\n       case (0)\n          write(processing,'(\"Forecast time:  \",I8,\" minutes\")') grib%sec4%time\n          p1_seconds = grib%sec4%time*60\n          p2_seconds = 0\n          call geth_newdate(valid_date, grib%sec1%hdate, p1_seconds)\n          write(text3, '(\"Forecast valid time:  \", A, 1x, A)') valid_date(1:10), valid_date(12:19)\n       case (1)\n          write(processing,'(\"Forecast time:  \",I8,\" hours\")') grib%sec4%time\n          p1_seconds = grib%sec4%time*3600\n          p2_seconds = 0\n          call geth_newdate(valid_date, grib%sec1%hdate, p1_seconds)\n          write(text3, '(\"Forecast valid time:  \", A, 1x, A)') valid_date(1:10), valid_date(12:19)\n       case (2)\n          write(processing,'(\"Forecast time:  \",I8,\" days\")') grib%sec4%time\n          p1_seconds = grib%sec4%time*86400\n          p2_seconds = 0\n          call geth_newdate(valid_date, grib%sec1%hdate, p1_seconds)\n          write(text3, '(\"Forecast valid time:  \", A, 1x, A)') valid_date(1:10), valid_date(12:19)\n       case (13)\n          write(processing,'(\"Forecast time:  \",I8,\" seconds\")') grib%sec4%time\n          p1_seconds = grib%sec4%time\n          p2_seconds = 0\n          call geth_newdate(valid_date, grib%sec1%hdate, grib%sec4%time)\n          write(text3, '(\"Forecast valid time:  \", A, 1x, A)') valid_date(1:10), valid_date(12:19)\n\n       end select\n    case (8)\n       select case (grib%sec4%PDT_4_8%statistical_process)\n       case default\n          write(processing, '(\"Unrecognized statistical process: \",I4)') grib%sec4%PDT_4_8%statistical_process\n       case (0)\n          write(processing, '(\"Average over \", I6, 1x, A)') &\n               grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n          write(text3, '(\"from \", A, \" to \", A)') &\n               grib%sec4%PDT_4_8%begin_hdate, grib%sec4%PDT_4_8%end_hdate\n          processing = trim(processing)//\" \"//trim(text3)\n       case (1)\n          write(processing, '(\"Accumulation over \", I6, 1x, A)') &\n               grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n          write(text3, '(\"from \", A, \" to \", A)') &\n               grib%sec4%PDT_4_8%begin_hdate, grib%sec4%PDT_4_8%end_hdate\n          processing = trim(processing)//\" \"//trim(text3)\n          valid_date = grib%sec4%PDT_4_8%end_hdate\n\n          select case (grib%sec4%time_range_indicator)\n          case default\n             write(processing,'(\"Unrecognized time range indicator for accumulation:\", I8)') grib%sec4%time_range_indicator\n             stop \"FATAL ERROR: In module module_grib2.F -- Unrecognized time range indicator for accumulation\"\n          case (0)\n             p1_seconds = grib%sec4%time*60\n          case (1)\n             p1_seconds = grib%sec4%time*3600\n          case (2)\n             p1_seconds = grib%sec4%time*86400\n          case (13)\n             p1_seconds = grib%sec4%time\n          end select\n\n          select case (grib%sec4%PDT_4_8%time_range_unit)\n          case default\n             write(processing,'(\"Unrecognized time range unit for accumulation:\", I8)') grib%sec4%PDT_4_8%time_range_unit\n             stop \"FATAL ERROR: In module module_grib2.F -- Unrecognized time range unit for accumulation\"\n          case (0)\n             p2_seconds = p1_seconds + (grib%sec4%PDT_4_8%length_of_time_range) * 60\n          case (1)\n             p2_seconds = p1_seconds + (grib%sec4%PDT_4_8%length_of_time_range) * 3600\n          case (2)\n             p2_seconds = p1_seconds + (grib%sec4%PDT_4_8%length_of_time_range) * 86400\n          case (13)\n             p1_seconds = p1_seconds + (grib%sec4%PDT_4_8%length_of_time_range)\n          end select\n\n       case (2)\n          write(processing, '(\"Maximum in \", I6, 1x, A)') &\n               grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n       case (3)\n          write(processing, '(\"Minimum in \", I6, 1x, A)') &\n               grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n       case (4)\n          write(processing, '(\"Difference over \", I6, 1x, A)') &\n              grib%sec4%PDT_4_8%length_of_time_range, interpret_time_unit(grib%sec4%PDT_4_8%time_range_unit)\n       end select\n    end select\n  end subroutine grib2_time_information\n\n!=================================================================================\n!=================================================================================\n\n#ifdef _DEAD_\n  subroutine get_grib_bitmap(grib, bitmap)\n    implicit none\n    type (GribStruct), intent(in) :: grib\n    integer, pointer, dimension(:,:) :: bitmap\n\n    if (grib%sec6%bit_map_indicator /= 255) then\n       bitmap => grib%sec6%bitmap\n    else\n       nullify(bitmap)\n    endif\n\n  end subroutine get_grib_bitmap\n#endif\n!=================================================================================\n!=================================================================================\n\n  subroutine get_grib_dimensions(grib, idim, jdim)\n    ! Probably not needed, since we define a mapinfo structure.\n    implicit none\n    type (GribStruct), intent(in)  :: grib\n    integer,           intent(out) :: idim\n    integer,           intent(out) :: jdim\n    idim = grib%sec3%nx\n    jdim = grib%sec3%ny\n  end subroutine get_grib_dimensions\n\n!=================================================================================\n!=================================================================================\n\n  subroutine get_grib_data_array(grib, array)\n    implicit none\n    type (GribStruct), intent(in) :: grib\n    real, pointer, dimension(:,:) :: array\n    array => grib%array\n  end subroutine get_grib_data_array\n\n\n!=================================================================================\n!=================================================================================\n\n  subroutine deallogrib(grib)\n    type (GribStruct) :: grib\n    if (associated(grib%buffer)) then\n       deallocate(grib%buffer)\n       nullify(grib%buffer)\n    endif\n    if (associated(grib%bitmap)) then\n       deallocate(grib%bitmap)\n       nullify(grib%bitmap)\n    endif\n    if (associated(grib%array)) then\n       deallocate(grib%array)\n       nullify(grib%array)\n    endif\n    if (associated(grib%sec7%floated)) then\n       deallocate(grib%sec7%floated)\n       nullify(grib%sec7%floated)\n    endif\n    grib%size = 0\n  end subroutine deallogrib\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_level_information(grib, level_type, level_units, level_value, level2_value)\n    implicit none\n    type (GribStruct),  intent(in)  :: grib\n    character(len=256), intent(out) :: level_type\n    character(len=256), intent(out) :: level_units\n    real,               intent(out) :: level_value\n    real,               intent(out) :: level2_value\n\n    level2_value = -1.E36\n    select case (grib%sec4%product_template_number)\n    case default\n       write(*,'(\"WARNING: MODULE_GRIB2:  GRIB2_LEVEL_INFORMATION:  Unrecognized product_template_number: \", I4)') &\n            grib%sec4%product_template_number\n       stop \"FATAL ERROR: In module module_grib2.F -- GRIB2_LEVEL_INFORMATION: Unrecognized product_template_number\"\n    case (0)\n       call get_level_string(grib%sec4%ltype1, level_type, level_units)\n       level_value  = grib%sec4%level1\n       if (grib%sec4%ltype2 /= 255) then\n          level2_value = grib%sec4%level2\n       endif\n    case (8)\n       call get_level_string(grib%sec4%ltype1, level_type, level_units)\n       level_value  = grib%sec4%level1\n       if (grib%sec4%ltype2 /= 255) then\n          level2_value = grib%sec4%level2\n       endif\n    end select\n\n    ! write(*,'(\"MODULE_GRIB2:  GRIB2_LEVEL_INFORMATION:  To do.\")')\n    ! stop\n  end subroutine grib2_level_information\n\n!=================================================================================\n!=================================================================================\n\n\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_next_grib2_section(isection, grib)\n\n    !  Returns the section number of the section just unpacked\n    implicit none\n    integer, intent(out) :: isection\n    type(GribStruct), intent(inout) :: grib\n    integer :: iread\n    character(len=4) :: hh\n    integer :: isize\n    integer :: ierr\n    integer :: n\n    integer :: edition\n    integer :: gribsizeA, gribsizeB\n    integer(kind=8) :: gribsize\n    character(len=1), dimension(12) :: buf\n\n    ! Take four bytes:\n\n    isize = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n\n    if (isize == string_grib) then\n       grib%iskip = grib%iskip + 16\n       isection = 0\n       grib%discipline = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       edition    = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       gribsizeA  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       gribsizeB  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       if (gribsizeA /= 0) then\n          stop \"FATAL ERROR: In module module_grib2.F -- UNPACK_NEXT_GRIB2_SECTION:  Large size.  Despair!\"\n       endif\n       gribsize = gribsizeB\n       return\n    else if (isize == string_sevens) then\n       isection = 8\n       return\n    else\n       isection = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       select case (isection)\n       case (1)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec1(grib);\n          ! call print_sec1(grib, 10000);\n       case (3)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec3(grib);\n          ! call print_sec3(grib, 10000);\n       case (4)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec4(grib);\n          ! call print_sec4(grib);\n       case (5)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec5(grib);\n          ! call print_sec5(grib);\n       case (6)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec6(grib);\n          ! call print_sec6(grib,10000);\n       case (7)\n          grib%iskip = grib%iskip - 5*8\n          call unpack_sec7(grib);\n          ! call print_sec7(grib);\n       case default\n          write(*,'(\"WARNING: Section?  \", I10)') isection\n          stop \"FATAL ERROR: In module module_grib2.F -- Section?\"\n       end select\n    endif\n\n  end subroutine unpack_next_grib2_section\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec1(grib)\n    implicit none\n    type (GribStruct), intent(inout) :: grib\n\n    character(len=8) :: hdate\n    integer :: section\n\n    grib%sec1%size              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section                     = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%center            = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    grib%sec1%subcenter         = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    grib%sec1%mtvn              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%ltvn              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)  \n    grib%sec1%srt               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%year              = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    grib%sec1%month             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%day               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%hour              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%minute            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%second            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%production_status = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    grib%sec1%data_type         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)  \n\n    write(grib%sec1%hdate, '(I4.4,\"-\",I2.2,\"-\",I2.2,\"_\",I2.2,\":\",I2.2,\":\",I2.2)') &\n         grib%sec1%year, grib%sec1%month, grib%sec1%day, grib%sec1%hour, grib%sec1%minute, grib%sec1%second\n\n  end subroutine unpack_sec1\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec1(grib, verbosity)\n    implicit none\n    type(GribStruct), intent(in)  :: grib\n    integer,          intent(in)  :: verbosity\n\n    if (verbosity >= 10) then\n       write(*,'(\"Section 1:\")')\n       if (verbosity >= 100) then\n          write(*,'(\"   Length of section:               \",I4)') grib%sec1%size\n          write(*,'(\"   Originating Center:              \",I4)') grib%sec1%center\n          write(*,'(\"   Originating Subcenter:           \",I4)') grib%sec1%subcenter\n          write(*,'(\"   Master Tables Version Number:    \",I4)') grib%sec1%mtvn\n          write(*,'(\"   Local Tables Version Number:     \",I4)') grib%sec1%ltvn\n          write(*,'(\"   Significance of Reference Time:  \",I4,\":  \")', advance=\"no\") grib%sec1%srt\n\n          select case (grib%sec1%srt)\n          case default\n             write( *, '(\"Unrecognized significance of reference time\")' )\n          case (0)\n             write(*,'(\"analysis time.  \", A, 1x, A)')\n          case (1)\n             write(*,'(\"forecast start time.  \", A, 1x, A)')\n          case (2)\n             write(*,'(\"verifying time of forecast.  \", A, 1x, A)')\n          case (3)\n             write(*,'(\"observation time.  \", A, 1x, A)')\n          end select\n\n          if (verbosity >= 500) then\n             write(*,'(\"   Year (Reference Time):           \",I4)') grib%sec1%year\n             write(*,'(\"   Month (Reference Time):          \",I4)') grib%sec1%month\n             write(*,'(\"   Day (Reference Time):            \",I4)') grib%sec1%day\n             write(*,'(\"   Hour (Reference Time):           \",I4)') grib%sec1%hour\n             write(*,'(\"   Minute (Reference Time):         \",I4)') grib%sec1%minute\n             write(*,'(\"   Second (Reference Time):         \",I4)') grib%sec1%second\n          endif\n          write(*,'(\"   Reference Time:                  \",A)') grib%sec1%hdate\n          write(*,'(\"   Production Status:               \",I4)') grib%sec1%production_status\n          write(*,'(\"   Data Type:                       \",I4)') grib%sec1%data_type\n       endif\n\n       !\n       ! Data Type\n       !\n\n       select case (grib%sec1%data_type)\n       case (0)\n          write(*,'(\"  Analysis products\")')\n       case (1)\n          write(*,'(\"  Forecast products\")')\n       case (2)\n          write(*,'(\"  Analysis and Forecast products\")')\n       case (3)\n          write(*,'(\"  Control Forecast products\")')\n       case (4)\n          write(*,'(\"  Perturbed Forecast products\")')\n       case (5)\n          write(*,'(\"  Control and Perturbed Forecast products\")')\n       case (6)\n          write(*,'(\"  Processed satellite observations\")')\n       case (7)\n          write(*,'(\"  Processed radar observations\")')\n       case (8:191)\n          write(*,'(\"   Data Type:                       \",I4)') grib%sec1%data_type\n       case (192:254)\n          write(*,'(\"   Data Type:                       \",I4)') grib%sec1%data_type\n       case (255)\n          write(*,'(\"   Data Type:                       \",I4)') grib%sec1%data_type\n       end select\n\n       !\n       ! Significance of Reference Time\n       !\n       select case (grib%sec1%srt)\n       case (0)\n          write(*,'(\"  Analysis at time \",A)') grib%sec1%hdate\n       case (1)\n          write(*,'(\"  Forecast initialized at time \",A)') grib%sec1%hdate\n       case (2)\n          write(*,'(\"  Forecast verifying at time \",A)') grib%sec1%hdate\n       case (3)\n          write(*,'(\"  Observation time \",A)') grib%sec1%hdate\n       case (4:191)\n          write(*,'(\"  Reference time \",A)') grib%sec1%hdate\n       case (192:254)\n          write(*,'(\"  Reference time \",A)') grib%sec1%hdate\n       case (255)\n          write(*,'(\"  Reference time \",A)') grib%sec1%hdate\n       end select\n\n    endif\n\n  end subroutine print_sec1\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec3(grib)\n    implicit none\n    type(GribStruct), intent(inout), target :: grib\n\n    integer :: section\n    type (Section3Struct), pointer :: sec3\n    type (GT_3_0_Struct),  pointer :: GT_3_0\n    type (GT_3_30_Struct), pointer :: GT_3_30\n\n    integer :: i\n\n    ! Temporary integers to hold\n    integer :: ila1\n    integer :: ilo1\n    integer :: ila2\n    integer :: ilo2\n    integer :: ilad\n    integer :: ilov\n    integer :: iplat\n    integer :: iplon\n    integer :: ilatin1\n    integer :: ilatin2\n    integer :: idi\n    integer :: idj\n\n    sec3 => grib%sec3\n\n    sec3%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n\n    if (section /= 3) then\n       write(*,'(\"WARNING: Section 3:  We are lost!  \",I4)') section\n       stop \"FATAL ERROR: In module module_grib2.F -- Section 3: We are lost\"\n    endif\n\n    sec3%grid_definition_source   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    sec3%number_of_data_points    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    sec3%octets_for_optional_list = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    sec3%list_interpretation      = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    sec3%grid_template_number     = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n\n    select case (sec3%grid_template_number)\n    case (0)\n\n       ! Cylindrical Equidistant Grid\n\n       GT_3_0 => sec3%GT_3_0\n\n       Sec3%shape_of_earth                   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_0%scale_factor_of_radius         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_0%scaled_value_of_radius         = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%scale_factor_major_axis        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_0%scaled_value_major_axis        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%scale_factor_minor_axis        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_0%scaled_value_minor_axis        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec3%nx                               = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec3%ny                               = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%basic_angle                    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%subdivisions_of_basic_angle    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       ila1                                  = unpack_signed_integer  (grib%buffer, 4, grib%iskip)\n       ilo1                                  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_0%resolution_and_component_flags = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       ila2                                  = unpack_signed_integer  (grib%buffer, 4, grib%iskip)\n       ilo2                                  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       idi                                   = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       idj                                   = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       GT_3_0%scanning_mode                  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n\n       GT_3_0%la1 = ila1 * 1.E-6\n       GT_3_0%lo1 = ilo1 * 1.E-6\n       GT_3_0%la2 = ila2 * 1.E-6\n       GT_3_0%lo2 = ilo2 * 1.E-6\n       GT_3_0%dx  = idi  * 1.E-6\n       GT_3_0%dy  = idj  * 1.E-6\n\n       ! 0/1:  I direction increments given?\n       if (btest(GT_3_0%resolution_and_component_flags,5)) then\n          GT_3_0%i_direction_increments_given = 1\n       else\n          GT_3_0%i_direction_increments_given = 0\n       endif\n\n       ! 0/1:  J direction increments given?\n       if (btest(GT_3_0%resolution_and_component_flags,4)) then\n          GT_3_0%j_direction_increments_given = 1\n       else\n          GT_3_0%j_direction_increments_given = 0\n       endif\n\n       ! 0/1:  Earth-relative/Grid-relative winds\n       if (btest(GT_3_0%resolution_and_component_flags,3)) then\n          GT_3_0%winds_grid_relative = 1\n       else\n          GT_3_0%winds_grid_relative = 0\n       endif\n\n       if (btest(GT_3_0%scanning_mode,7)) then\n          GT_3_0%i_scan_direction = -1\n       else\n          GT_3_0%i_scan_direction = 1\n       endif\n\n       if (btest(GT_3_0%scanning_mode,6)) then\n          GT_3_0%j_scan_direction = 1\n       else\n          GT_3_0%j_scan_direction = -1\n       endif\n\n       if (btest(GT_3_0%scanning_mode,5)) then\n          GT_3_0%i_scan_consecutive=0\n       else\n          GT_3_0%i_scan_consecutive=1\n       endif\n\n       if (btest(GT_3_0%scanning_mode,4)) then\n          GT_3_0%boustrophedon=1\n       else\n          GT_3_0%boustrophedon=0\n       endif\n\n       nullify(GT_3_0)\n\n    case (30)\n\n       ! Lambert Conformal Grid\n\n       GT_3_30 => sec3%GT_3_30\n\n       sec3%shape_of_earth                    = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scale_factor_of_radius         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scaled_value_of_radius         = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_30%scale_factor_major_axis        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scaled_value_major_axis        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       GT_3_30%scale_factor_minor_axis        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scaled_value_minor_axis        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec3%nx                                = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec3%ny                                = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       ila1                                   = unpack_signed_integer  (grib%buffer, 4, grib%iskip)\n       ilo1                                   = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       GT_3_30%resolution_and_component_flags = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       ilad                                   = unpack_signed_integer  (grib%buffer, 4, grib%iskip)     \n       ilov                                   = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       idi                                    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       idj                                    = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       GT_3_30%projection_center_flag         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       GT_3_30%scanning_mode                  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       ilatin1                                = unpack_signed_integer  (grib%buffer, 4, grib%iskip)     \n       ilatin2                                = unpack_signed_integer  (grib%buffer, 4, grib%iskip)     \n       iplat                                  = unpack_signed_integer  (grib%buffer, 4, grib%iskip)     \n       iplon                                  = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n\n       GT_3_30%la1            = ila1    * 1.E-6\n       GT_3_30%lo1            = ilo1    * 1.E-6\n       GT_3_30%lad            = ilad    * 1.E-6\n       GT_3_30%lov            = ilov    * 1.E-6\n       GT_3_30%dx             = idi     * 1.E-6\n       GT_3_30%dy             = idj     * 1.E-6\n       GT_3_30%latin1         = ilatin1 * 1.E-6\n       GT_3_30%latin2         = ilatin2 * 1.E-6\n       GT_3_30%pole_latitude  = iplat   * 1.E-6\n       GT_3_30%pole_longitude = iplon   * 1.E-6\n\n       ! 0/1:  I direction increments given?\n       if (btest(GT_3_30%resolution_and_component_flags,5)) then\n          GT_3_30%i_direction_increments_given = 1\n       else\n          GT_3_30%i_direction_increments_given = 0\n       endif\n\n       ! 0/1:  J direction increments given?\n       if (btest(GT_3_30%resolution_and_component_flags,4)) then\n          GT_3_30%j_direction_increments_given = 1\n       else\n          GT_3_30%j_direction_increments_given = 0\n       endif\n\n       ! 0/1:  Earth-relative/Grid-relative winds\n       if (btest(GT_3_30%resolution_and_component_flags,3)) then\n          GT_3_30%winds_grid_relative = 1\n       else\n          GT_3_30%winds_grid_relative = 0\n       endif\n\n       if (btest(GT_3_30%scanning_mode,7)) then\n          GT_3_30%i_scan_direction = -1\n       else\n          GT_3_30%i_scan_direction = 1\n       endif\n\n       if (btest(GT_3_30%scanning_mode,6)) then\n          GT_3_30%j_scan_direction = 1\n       else\n          GT_3_30%j_scan_direction = -1\n       endif\n\n       if (btest(GT_3_30%scanning_mode,5)) then\n          GT_3_30%i_scan_consecutive=0\n       else\n          GT_3_30%i_scan_consecutive=1\n       endif\n\n       if (btest(GT_3_30%scanning_mode,4)) then\n          GT_3_30%boustrophedon=1\n       else\n          GT_3_30%boustrophedon=0\n       endif\n\n\n\n       nullify(GT_3_30)\n\n    case default\n       write(*,'(\"WARNING: Unknown grid_template_number: \",I4)') sec3%grid_template_number\n       stop \"FATAL ERROR: In module module_grib2.F -- Unknown grid_template_number.\"\n    end select\n\n    nullify(sec3)\n\n  end subroutine unpack_sec3\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec3(grib, verbosity)\n    implicit none\n    type(GribStruct), target, intent(in) ::  grib\n    integer,          intent(in) :: verbosity\n\n    type(Section3Struct), pointer :: sec3\n    sec3 => grib%sec3\n    if (verbosity >= 10) then\n       write(*,'(\"Section 3\")')\n       if (verbosity >= 100) then\n          write(*,'(\"   Length of section:               \",I4)') sec3%size\n          write(*,'(\"   Source of Grid Definition:       \",I4)') sec3%grid_definition_source\n          write(*,'(\"   Number of data points:           \",I8)') sec3%number_of_data_points\n          write(*,'(\"   Octets for optional list:        \",I4)') sec3%octets_for_optional_list\n          write(*,'(\"   Interpretation of optional list: \",I4)') sec3%list_interpretation\n          write(*,'(\"   Grid Definition Template Number: \",I4)') sec3%grid_template_number\n          write(*,'(\"        Shape of earth           : \",I4)') sec3%shape_of_earth\n          select case (sec3%shape_of_earth)\n          case (6)\n             write(*,'(\"         Earth assumed spherical with radius of 6371229.0 m\")')\n          case default\n             write(*,'(\"         Unrecognized shape_of_earth:  \", I4)') sec3%shape_of_earth\n          end select\n          select case (sec3%grid_template_number)\n          case (0)\n             write(*,'(\"  Cylindrical Equidistant Grid:\")')\n             write(*,'(\"     Scale factor of radius:    \",I8)') sec3%GT_3_0%scale_factor_of_radius\n             write(*,'(\"     Scaled value of radius:    \",I8)') sec3%GT_3_0%scaled_value_of_radius\n             write(*,'(\"     Scale factor major axis:   \",I8)') sec3%GT_3_0%scale_factor_major_axis\n             write(*,'(\"     Scaled value major axis:   \",I8)') sec3%GT_3_0%scaled_value_major_axis\n             write(*,'(\"     Scale factor minor axis:   \",I8)') sec3%GT_3_0%scale_factor_minor_axis\n             write(*,'(\"     Scaled value minor axis:   \",I8)') sec3%GT_3_0%scaled_value_minor_axis\n             write(*,'(\"     Ni                         \",I8)') sec3%nx\n             write(*,'(\"     Nj                         \",I8)') sec3%ny\n             write(*,'(\"     basic angle:               \",I8)') sec3%GT_3_0%basic_angle\n             write(*,'(\"     subdivisions of angle:     \",I8)') sec3%GT_3_0%subdivisions_of_basic_angle\n             write(*,'(\"     La1:                       \",F10.6)') sec3%GT_3_0%la1\n             write(*,'(\"     Lo1:                       \",F10.6)') sec3%GT_3_0%lo1\n             write(*,'(\"     Resolution/Component flags \",I4, 1x, B8.8)') sec3%GT_3_0%resolution_and_component_flags, &\n                  sec3%GT_3_0%resolution_and_component_flags\n             if (sec3%GT_3_0%i_direction_increments_given == 1) then\n                write(*,'(\"                 I direction increments given\")')\n             else\n                write(*,'(\"                 I direction increments not given\")')\n             endif\n             if (sec3%GT_3_0%j_direction_increments_given == 1) then\n                write(*,'(\"                 J direction increments given\")')\n             else\n                write(*,'(\"                 J direction increments not given\")')\n             endif\n             if (sec3%GT_3_0%winds_grid_relative == 1) then\n                write(*,'(\"                 Horizontal wind components are grid-relative\")')\n             else\n                write(*,'(\"                 Horizontal wind components are earth-relative\")')\n             endif\n             write(*,'(\"     La2:                       \",F10.6)') sec3%GT_3_0%la2\n             write(*,'(\"     Lo2:                       \",F10.6)') sec3%GT_3_0%lo2\n             write(*,'(\"     Dx :                       \",F10.6)') sec3%GT_3_0%dx\n             write(*,'(\"     Dy:                        \",F10.6)') sec3%GT_3_0%dy\n             write(*,'(\"     Scanning Mode:             \",I4, 1x, B8.8)') sec3%GT_3_0%scanning_mode, sec3%GT_3_0%scanning_mode\n             write(*,'(\"             I scan direction   = \", I4)') sec3%GT_3_0%i_scan_direction\n             write(*,'(\"             J scan direction   = \", I4)') sec3%GT_3_0%j_scan_direction\n             write(*,'(\"             I scan consecutive = \", I4)') sec3%GT_3_0%i_scan_consecutive\n             write(*,'(\"             Boustrophedon      = \", I4)') sec3%GT_3_0%boustrophedon\n          case (30)\n             write(*,'(\"  Lambert Conformal Grid: \")')\n             write(*,'(\"     Scale factor of radius:    \",I8)') sec3%GT_3_30%scale_factor_of_radius\n             write(*,'(\"     Scaled value of radius:    \",I8)') sec3%GT_3_30%scaled_value_of_radius\n             write(*,'(\"     Scale factor major axis:   \",I8)') sec3%GT_3_30%scale_factor_major_axis\n             write(*,'(\"     Scaled value major axis:   \",I8)') sec3%GT_3_30%scaled_value_major_axis\n             write(*,'(\"     Scale factor minor axis:   \",I8)') sec3%GT_3_30%scale_factor_minor_axis\n             write(*,'(\"     Scaled value minor axis:   \",I8)') sec3%GT_3_30%scaled_value_minor_axis\n             write(*,'(\"     Ni                         \",I8)') sec3%nx\n             write(*,'(\"     Nj                         \",I8)') sec3%ny\n             write(*,'(\"     La1:                       \",F10.6)') sec3%GT_3_30%la1\n             write(*,'(\"     Lo1:                       \",F10.6)') sec3%GT_3_30%lo1\n             write(*,'(\"     Resolution/Component flags \",I4,\": \", B8.8)') sec3%GT_3_30%resolution_and_component_flags, &\n                  sec3%GT_3_30%resolution_and_component_flags\n             if (sec3%GT_3_30%i_direction_increments_given == 1) then\n                write(*,'(\"                 I direction increments given\")')\n             else\n                write(*,'(\"                 I direction increments not given\")')\n             endif\n             if (sec3%GT_3_30%j_direction_increments_given == 1) then\n                write(*,'(\"                 J direction increments given\")')\n             else\n                write(*,'(\"                 J direction increments not given\")')\n             endif\n             if (sec3%GT_3_30%winds_grid_relative == 1) then\n                write(*,'(\"                 Horizontal wind components are grid-relative\")')\n             else\n                write(*,'(\"                 Horizontal wind components are earth-relative\")')\n             endif\n             write(*,'(\"     Lad:                       \",F10.6)') sec3%GT_3_30%lad\n             write(*,'(\"     Lov:                       \",F10.6)') sec3%GT_3_30%lov\n             write(*,'(\"     Dx :                       \",F10.6)') sec3%GT_3_30%dx\n             write(*,'(\"     Dy:                        \",F10.6)') sec3%GT_3_30%dy\n             write(*,'(\"     Projection Center Flag     \",I8)') sec3%GT_3_30%projection_center_flag\n             write(*,'(\"     Scanning Mode:             \",I8, \": \", B8.8)') sec3%GT_3_30%scanning_mode, sec3%GT_3_30%scanning_mode\n             write(*,'(\"             I scan direction   = \", I8)') sec3%GT_3_30%i_scan_direction\n             write(*,'(\"             J scan direction   = \", I8)') sec3%GT_3_30%j_scan_direction\n             write(*,'(\"             I scan consecutive = \", I8)') sec3%GT_3_30%i_scan_consecutive\n             write(*,'(\"             Boustrophedon      = \", I8)') sec3%GT_3_30%boustrophedon\n             write(*,'(\"     Latin1:                    \",F10.6)') sec3%GT_3_30%latin1\n             write(*,'(\"     Latin2:                    \",F10.6)') sec3%GT_3_30%latin2\n             write(*,'(\"     Southern Pole Latitude:    \",F10.6)') sec3%GT_3_30%pole_latitude\n             write(*,'(\"     Southern Pole Longitude:   \",F10.6)') sec3%GT_3_30%pole_longitude\n          case default\n             write(*,'(\"Unknown grid_template_number: \",I8)') sec3%grid_template_number\n             stop\n          end select\n       endif\n    endif\n\n  end subroutine print_sec3\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec4(grib)\n    implicit none\n    type (GribStruct), target, intent(inout) :: grib\n    integer :: section\n    type (Section4Struct), pointer :: sec4\n!    type (PDT_4_0_Struct), pointer :: PDT_4_0\n    type (PDT_4_8_Struct), pointer :: PDT_4_8\n\n    integer :: time_conversion_to_seconds\n\n    sec4 => grib%sec4\n\n    sec4%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    if (section /= 4) then\n       write(*,'(\"WARNING: Section 4:  We are lost!  \", I4)') section\n       stop \"FATAL ERROR: In module module_grib2.F -- Section 4: Problem\"\n    endif\n\n    sec4%number_of_coord_values  = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    sec4%product_template_number = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n\n    select case (sec4%product_template_number)\n    case (0)\n\n       ! PDT_4_0 => sec4%PDT_4_0\n\n       sec4%parameter_category                   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%parameter_number                     = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%type_of_generating_process        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%background_process_id             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%generating_process_id             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%data_cutoff_hours                 = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n       sec4%data_cutoff_minutes               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%time_range_indicator              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%time                              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec4%ltype1                            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%lscale1                           = unpack_signed_integer(grib%buffer, 1, grib%iskip)\n       sec4%lvalue1                           = unpack_signed_integer(grib%buffer, 4, grib%iskip)\n       sec4%level1                            = real(sec4%lvalue1) / (10.**real(sec4%lscale1))\n       sec4%ltype2                            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%lscale2                           = unpack_signed_integer(grib%buffer, 1, grib%iskip)\n       sec4%lvalue2                           = unpack_signed_integer(grib%buffer, 4, grib%iskip)\n       sec4%level2                            = real(sec4%lvalue2) / (10.**real(sec4%lscale2))\n\n    case (8)\n\n       PDT_4_8 => sec4%PDT_4_8\n\n       sec4%parameter_category                   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%parameter_number                     = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%type_of_generating_process        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%background_process_id             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%generating_process_id             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%data_cutoff_hours                 = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n       sec4%data_cutoff_minutes               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%time_range_indicator              = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%time                              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec4%ltype1                            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%lscale1                           = unpack_signed_integer(grib%buffer, 1, grib%iskip)\n       sec4%lvalue1                           = unpack_signed_integer(grib%buffer, 4, grib%iskip)\n       sec4%level1                            = real(sec4%lvalue1) / (10.**real(sec4%lscale1))\n       sec4%ltype2                            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec4%lscale2                           = unpack_signed_integer(grib%buffer, 1, grib%iskip)\n       sec4%lvalue2                           = unpack_signed_integer(grib%buffer, 4, grib%iskip)\n       sec4%level2                            = real(sec4%lvalue2) / (10.**real(sec4%lscale2))\n       PDT_4_8%end_year                          = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n       PDT_4_8%end_month                         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%end_day                           = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%end_hour                          = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%end_minute                        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%end_second                        = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       select case (sec4%time_range_indicator)\n       case default\n          write(*,'(\"WARNING: sec4%time_range_indicator = \", I4)') sec4%time_range_indicator\n          stop \"FATAL ERROR: In module module_grib2.F -- time conversion error\"\n       case (0)\n          time_conversion_to_seconds = 60\n       case (1)\n          time_conversion_to_seconds = 3600\n       case (2)\n          time_conversion_to_seconds = 86400\n       case (13)\n          time_conversion_to_seconds = 1\n       end select\n       call geth_newdate(PDT_4_8%begin_hdate, grib%sec1%hdate, sec4%time*time_conversion_to_seconds)\n       write(PDT_4_8%end_hdate, '(I4.4,2(\"-\",I2.2),\"_\",2(I2.2,\":\"),I2.2)') &\n            PDT_4_8%end_year, PDT_4_8%end_month, PDT_4_8%end_day, PDT_4_8%end_hour, PDT_4_8%end_minute, PDT_4_8%end_second\n       PDT_4_8%number_of_time_range_specifications  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%number_missing                       = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       PDT_4_8%statistical_process                  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%type_of_time_increment               = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%time_range_unit                      = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%length_of_time_range                 = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       PDT_4_8%time_increment_unit                  = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       PDT_4_8%time_increment                       = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n\n       if (PDT_4_8%number_of_time_range_specifications > 1) then\n          write(*,'(\"WARNING: Hmmmm.  number of time range specifications = \", I8)') PDT_4_8%number_of_time_range_specifications\n          stop \"FATAL ERROR: In module module_grib2.F -- number of time range specifications\"\n       endif\n\n    case default\n       write(*,'(\"WARNING: Unrecognized product_template_number: \", I4)') sec4%product_template_number\n       stop \"FATAL ERROR: In module module_grib2.F -- Unrecognized product_template_number\"\n    end select\n\n  end subroutine unpack_sec4\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec4(grib)\n    implicit none\n    type (GribStruct), target, intent(in) :: grib\n    type (Section4Struct), pointer :: sec4\n\n    sec4 => grib%sec4\n\n    write(*,'(\"Section 4\")')\n    write(*,'(\"   Length of section:                   \",I8)') sec4%size\n    write(*,'(\"   Number of Coordinate Values:         \",I8)') sec4%number_of_coord_values\n    write(*,'(\"   Product Definition Template Number:  \",I8)') sec4%product_template_number\n    select case (sec4%product_template_number)\n    case (0)\n       write(*,'(\"  PDT 4.0:  Analysis or fcst at a horiz lvl or lyr at a point in time\")')\n       write(*,'(\"      parameter category:           \",I8)') sec4%parameter_category\n       write(*,'(\"      parameter number:             \",I8)') sec4%parameter_number\n       write(*,'(\"      type of generatiing process:  \",I8)') sec4%type_of_generating_process\n       write(*,'(\"      background process id:        \",I8)') sec4%background_process_id\n       write(*,'(\"      generating process id:        \",I8)') sec4%generating_process_id\n       write(*,'(\"      data cutoff hours:            \",I8)') sec4%data_cutoff_hours\n       write(*,'(\"      data cutoff minutes:          \",I8)') sec4%data_cutoff_minutes\n       write(*,'(\"      Time Range Indicator:         \",I8)') sec4%time_range_indicator\n       write(*,'(\"      time:                         \",I8)') sec4%time\n       write(*,'(\"      type of first fixed surface:  \",I8)') sec4%ltype1\n       write(*,'(\"      scale factor of first surface:  \",I8)') sec4%lscale1\n       write(*,'(\"      scaled value of first surface:  \",I8)') sec4%lvalue1\n       write(*,'(\"      First level                    \",F20.4)') sec4%level1\n       if (sec4%ltype2 /= 255) then\n          write(*,'(\"      type of second fixed surface:  \",I8)') sec4%ltype2\n          write(*,'(\"      scale factor of second surface:  \",I8)') sec4%lscale2\n          write(*,'(\"      scaled value of second surface:  \",I8)') sec4%lvalue2\n          write(*,'(\"      Second level                   \",F8.2)') sec4%level2\n       endif\n    case (8)\n       write(*,'(\"  PDT 4.8:  Average, accumulation ....\")')\n       write(*,'(\"      parameter category:           \",I8)') sec4%parameter_category\n       write(*,'(\"      parameter number:             \",I8)') sec4%parameter_number\n       write(*,'(\"      type of generatiing process:  \",I8)') sec4%type_of_generating_process\n       write(*,'(\"      background process id:        \",I8)') sec4%background_process_id\n       write(*,'(\"      generating process id:        \",I8)') sec4%generating_process_id\n       write(*,'(\"      data cutoff hours:            \",I8)') sec4%data_cutoff_hours\n       write(*,'(\"      data cutoff minutes:          \",I8)') sec4%data_cutoff_minutes\n       write(*,'(\"      Time Range Indicator:         \",I8)') sec4%time_range_indicator\n       write(*,'(\"      time:                         \",I8)') sec4%time\n       write(*,'(\"      type of first fixed surface:  \",I8)') sec4%ltype1\n       write(*,'(\"      scale factor of first surface:  \",I8)') sec4%lscale1\n       write(*,'(\"      scaled value of first surface:  \",I8)') sec4%lvalue1\n       write(*,'(\"      First level                    \",F10.2)') sec4%level1\n       if (sec4%ltype2 /= 255) then\n          write(*,'(\"      type of second fixed surface:  \",I8)') sec4%ltype2\n          write(*,'(\"      scale factor of second surface:  \",I8)') sec4%lscale2\n          write(*,'(\"      scaled value of second surface:  \",I8)') sec4%lvalue2\n          write(*,'(\"      Second level                  \",F10.2)') sec4%level2\n       endif\n       write(*,'(\"      End Year:                        \",I8)') sec4%PDT_4_8%end_year\n       write(*,'(\"      End Month:                       \",I8)') sec4%PDT_4_8%end_month\n       write(*,'(\"      End Day:                         \",I8)') sec4%PDT_4_8%end_day\n       write(*,'(\"      End Hour:                        \",I8)') sec4%PDT_4_8%end_hour\n       write(*,'(\"      End Minute:                      \",I8)') sec4%PDT_4_8%end_minute\n       write(*,'(\"      End Second:                      \",I8)') sec4%PDT_4_8%end_second\n       write(*,'(\"      Ene Hdate:                       \", A)') sec4%PDT_4_8%end_hdate\n       write(*,'(\"      Number of time range specifications: \",I8)') sec4%PDT_4_8%number_of_time_range_specifications\n       write(*,'(\"      Number missing:                  \",I8)') sec4%PDT_4_8%number_missing\n       write(*,'(\"      Statistical Process:              \",I8)') sec4%PDT_4_8%statistical_process\n       write(*,'(\"      Type of time increment:           \",I8)') sec4%PDT_4_8%type_of_time_increment\n       write(*,'(\"      time range unit:                  \",I8)') sec4%PDT_4_8%time_range_unit\n       write(*,'(\"      length of time range:             \",I8)') sec4%PDT_4_8%length_of_time_range\n       write(*,'(\"      time increment unit:              \",I8)') sec4%PDT_4_8%time_increment_unit\n       write(*,'(\"      time increment:                   \",I8)') sec4%PDT_4_8%time_increment\n    case default\n       write(*,'(\"WARNING: Unrecognized product_template_number: \",I8)') sec4%product_template_number\n       stop \"FATAL ERROR: Unrecognized product_template_number.\"\n    end select\n  end subroutine print_sec4\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec5(grib)\n    implicit none\n    type (GribStruct), target, intent(inout) :: grib\n    type (Section5Struct), pointer :: sec5\n    integer :: section\n    integer :: isign\n    integer :: iref\n    integer :: iref40\n    real    :: xref40\n    integer :: iref2\n    real    :: xref2\n    equivalence (iref40, xref40)\n    equivalence (iref2, xref2)\n\n    sec5 => grib%sec5\n\n    sec5%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    if (section /= 5) then\n       write(*,'(\"WARNING: Section 5:  We are lost!  \", I8)') section\n       stop \"FATAL ERROR: In module module_grib2.F -- Section 5 Problem\"\n    endif\n\n    sec5%nval                 = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    sec5%data_template_number = unpack_unsigned_integer(grib%buffer, 2, grib%iskip)\n    select case (sec5%data_template_number)\n    case (0)\n       iref = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       write(*, '(\"iref = \", I16)') iref\n\n       sec5%DRT_5_0%binary_scale_factor  = unpack_signed_integer(grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_0%decimal_scale_factor = unpack_signed_integer(grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_0%nbits                = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_0%data_type            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       stop \"Problem\"\n\n    case (2)\n       iref2                             = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%reference_value      = xref2\n       sec5%DRT_5_2%binary_scale_factor  = unpack_signed_integer  (grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_2%decimal_scale_factor = unpack_signed_integer  (grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_2%nbits                = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_2%data_type            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%group_splitting_method = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%missing_value_management = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%substitute1              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%substitute2              = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%ng                       = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%widths_reference         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%widths_nbits             = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%lengths_reference        = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%length_increment         = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n       sec5%DRT_5_2%length_of_last_group     = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)     \n       sec5%DRT_5_2%lengths_nbits            = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)     \n\n    case (40)\n\n       iref40 = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n       sec5%DRT_5_40%reference_value = xref40\n\n       sec5%DRT_5_40%binary_scale_factor = unpack_signed_integer(grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_40%decimal_scale_factor = unpack_signed_integer(grib%buffer, 2, grib%iskip)\n       sec5%DRT_5_40%nbits = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_40%data_type = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_40%compression_type = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n       sec5%DRT_5_40%target_compression_ratio = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    case default\n       write(*,'(\"WARNING: Unrecognized Data Representation Template Number: \", I8)') sec5%data_template_number\n       stop \"FATAL ERROR: In module module_grib2.F -- Unrecognized Data Representation Template Number\"\n    end select\n\n  end subroutine unpack_sec5\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec5(grib)\n    implicit none\n    type (GribStruct), target, intent(in) :: grib\n    type (Section5Struct), pointer :: sec5\n    sec5 => grib%sec5\n    write(*,'(\"Section 5\")')\n    write(*,'(\"   Length of section:                   \",I8)') sec5%size\n    write(*,'(\"   Number of data points:               \",I8)') sec5%nval\n    write(*,'(\"   Data Representation Template Number: \",I8)') sec5%data_template_number\n    select case (sec5%data_template_number)\n    case (2)\n\n\n       write(*,'(\"     reference value:               \", G20.8)') sec5%DRT_5_2%reference_value\n       write(*,'(\"     binary scale factor:           \", I8)') sec5%DRT_5_2%binary_scale_factor\n       write(*,'(\"     decimal scale factor           \", I8)') sec5%DRT_5_2%decimal_scale_factor\n       write(*,'(\"     nbits:                         \", I8)') sec5%DRT_5_2%nbits\n       write(*,'(\"     data type:                     \", I8)') sec5%DRT_5_2%data_type\n       write(*,'(\"     group splitting method         \", I8)') sec5%DRT_5_2%group_splitting_method\n       write(*,'(\"     missing value management       \", I8)') sec5%DRT_5_2%missing_value_management\n       write(*,'(\"     primary substitute:            \", I8)') sec5%DRT_5_2%substitute1\n       write(*,'(\"     secondary substitute:          \", I8)') sec5%DRT_5_2%substitute2\n       write(*,'(\"     NG                             \", I8)') sec5%DRT_5_2%ng\n       write(*,'(\"     widths_reference               \", I8)') sec5%DRT_5_2%widths_reference\n       write(*,'(\"     widths_nbits                   \", I8)') sec5%DRT_5_2%widths_nbits\n       write(*,'(\"     lengths_reference              \", I8)') sec5%DRT_5_2%lengths_reference\n       write(*,'(\"     length increment               \", I8)') sec5%DRT_5_2%length_increment\n       write(*,'(\"     last length                    \", I8)') sec5%DRT_5_2%length_of_last_group\n       write(*,'(\"     lengths_nbits                  \", I8)') sec5%DRT_5_2%lengths_nbits\n\n\n    case (40)\n       write(*,'(\"     reference value:               \", G20.8)') sec5%DRT_5_40%reference_value\n       write(*,'(\"     binary scale factor:           \", I8)') sec5%DRT_5_40%binary_scale_factor\n       write(*,'(\"     decimal scale factor:          \", I8)') sec5%DRT_5_40%decimal_scale_factor\n       write(*,'(\"     nbits:                         \", I8)') sec5%DRT_5_40%nbits\n       write(*,'(\"     data type:                     \", I8)') sec5%DRT_5_40%data_type\n       write(*,'(\"     compression type:              \", I8)') sec5%DRT_5_40%compression_type\n       write(*,'(\"     target compression ratio:      \", I8)') sec5%DRT_5_40%target_compression_ratio\n    case default\n       write(*,'(\"WARNING: Unrecognized Data Representation Template Number: \",I8)') sec5%data_template_number\n       stop \"FATAL ERROR: In module in module_grib2.F -- Problem\"\n    end select\n  end subroutine print_sec5\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec6(grib)\n    implicit none\n    type (GribStruct), target, intent(inout) :: grib\n\n    integer :: section\n    integer :: section_start\n\n    type (Section6Struct), pointer :: sec6\n\n\n    section_start = grib%iskip\n\n    sec6 => grib%sec6\n\n    sec6%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    if (section /= 6) then\n       write(*,'(\"WARNING: Section 6:  We are lost!  \", I8)') section\n       stop \"FATAL ERROR: In module module_grib2.F -- Section 6\"\n    endif\n\n    sec6%bit_map_indicator = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)  \n    select case (sec6%bit_map_indicator)\n    case default\n       write(*,'(\"WARNING: Oooooh, bit mapped field:  \",I8)')  sec6%bit_map_indicator\n       stop \"FATAL ERROR: In module module_grib2.F -- Unrecognized bit_map_indicator\"\n    case (255)\n       ! No bitmap.\n       ! No action needed here.\n    case (254)\n       ! Bitmap previously defined in this GRIB record.\n       ! No action needed here.  The previously-defined bitmap\n       ! should still be stored and used as necessary.\n    case (0)\n       ! write(*,'(\"Read a new bitmap:  \", I8, I8)') sec6%bit_map_indicator, sec6%size-6\n       if (associated(grib%bitmap)) then\n          deallocate(grib%bitmap)\n          nullify(grib%bitmap)\n       endif\n       allocate(grib%bitmap(grib%sec3%nx, grib%sec3%ny))\n       call gbytes(grib%buffer, grib%bitmap, grib%iskip, 1, 0, grib%sec3%number_of_data_points)\n       ! grib%iskip = grib%iskip + grib%sec3%number_of_data_points\n    end select\n\n    ! Position ourselves at the end of the section.\n    grib%iskip = section_start + (sec6%size*8)\n\n  end subroutine unpack_sec6\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec6(grib, verbosity)\n    implicit none\n    type (GribStruct), intent(in), target :: grib\n    integer,           intent(in)         :: verbosity\n\n    type (Section6Struct), pointer :: sec6\n    sec6 => grib%sec6\n    if (verbosity >= 10) then\n       write(*,'(\"Section 6\")')\n       if (verbosity >= 100) then\n          write(*,'(\"   Length of section:                   \",I8)') sec6%size\n          write(*,'(\"   Bit Map Indicator:                   \",I8)') sec6%bit_map_indicator\n          select case (sec6%bit_map_indicator)\n          case default\n             write(*,'(\"Oooooh, bit mapped field:  \",I8)') sec6%bit_map_indicator\n          case (0)\n             write(*,'(\"      A bit map applies and is defined here.\")')\n             ! write(*,'(\"      Bitmap of length: \",I8)') size(sec6%packed_bitmap)\n          case (254)\n             write(*,'(\"      A previously-defined bit map applies.\")')\n          case (255)\n             write(*,'(\"      A bit map does not apply\")')\n          end select\n       endif\n    endif\n  end subroutine print_sec6\n\n!=================================================================================\n!=================================================================================\n\n  subroutine unpack_sec7(grib)\n    implicit none\n    integer ::  section\n    type (GribStruct), target, intent(inout) :: grib\n    type (Section5Struct), pointer :: sec5\n    type (Section7Struct), pointer :: sec7\n\n    integer, pointer, dimension(:)  :: decoded\n    integer, allocatable, dimension(:) :: group\n    integer :: decoded_length\n    integer :: i\n    integer :: j\n    integer :: k\n    integer :: n\n    integer :: allostat\n    integer ::  ng\n    integer :: nbits\n    integer :: tot\n    integer, allocatable, dimension(:) :: x1\n    integer, allocatable, dimension(:) :: widths\n    integer, allocatable, dimension(:) :: lengths\n    integer, allocatable, dimension(:) :: L\n\n    integer :: sec7_beginning\n\n    sec7_beginning = grib%iskip/8\n\n    sec7 => grib%sec7\n    sec5 => grib%sec5\n\n    sec7%size = unpack_unsigned_integer(grib%buffer, 4, grib%iskip)\n    section   = unpack_unsigned_integer(grib%buffer, 1, grib%iskip)\n    if (section /= 7) then\n       write(*,'(\"WARNING: Section 7:  We are lost!  \", I8)') section\n       stop \"FATAL ERROR: In module module_grib2.F -- Section 7\"\n    endif\n\n    select case (sec5%data_template_number)\n    case default\n       write(*, '(\"WARNING: Unrecognized Data Representation Template Number: \", I8)') sec5%data_template_number\n       stop \"FATAL ERROR: In module module_grib2.F -- Unrecognized Data Representation Template Number\"\n    case (2)\n       ! Grid-point data -- complex packing\n       ng = sec5%DRT_5_2%ng\n       nbits = sec5%DRT_5_2%nbits\n\n       allocate(x1(ng))\n       call gbytes(grib%buffer, x1, grib%iskip, nbits, 0, ng)\n       grib%iskip = grib%iskip + (nbits*ng)\n\n       ! Make sure we align at a byte boundary\n       if (mod(grib%iskip,8)>0) then\n          grib%iskip = grib%iskip + 8-mod(grib%iskip,8)\n       endif\n\n       allocate(widths(ng))\n       call gbytes(grib%buffer, widths, grib%iskip, sec5%DRT_5_2%widths_nbits, 0, ng)\n       grib%iskip = grib%iskip + (sec5%DRT_5_2%widths_nbits*ng)\n\n       ! Make sure we align at a byte boundary\n       if (mod(grib%iskip,8)>0) then\n          grib%iskip = grib%iskip + 8-mod(grib%iskip,8)\n       endif\n\n       allocate(lengths(ng))\n       call gbytes(grib%buffer, lengths, grib%iskip, sec5%DRT_5_2%lengths_nbits, 0, ng)\n       grib%iskip = grib%iskip + (sec5%DRT_5_2%lengths_nbits *  ng)\n\n       ! Make sure we align at a byte boundary\n       if (mod(grib%iskip,8)>0) then\n          grib%iskip = grib%iskip + 8-mod(grib%iskip,8)\n       endif\n\n       allocate(decoded(sec5%nval))\n       if (associated(sec7%floated)) then\n          deallocate(sec7%floated)\n          nullify(sec7%floated)\n       endif\n       allocate(sec7%floated(sec5%nval))\n       allocate(L(ng))\n       tot = 0\n       j = 1\n       do i = 1, ng\n          L(i) = sec5%DRT_5_2%lengths_reference + lengths(i) * sec5%DRT_5_2%length_increment\n          if (i==ng) L(i) = sec5%DRT_5_2%length_of_last_group\n          tot = tot + (widths(i)*L(i))\n          ! write(*, '(\"i, x1, widths, lengths, L = \", 10I)') i, x1(i), widths(i), lengths(i), L(i), tot, tot/8\n\n          ! For each group <i>, read <L> values of size <widths> bits.\n          if (widths(i) > 0) then\n             call gbytes(grib%buffer, decoded(j), grib%iskip, widths(i), 0, L(i))\n             grib%iskip = grib%iskip + widths(i)*L(i)\n             do k = 0, L(i)-1\n                sec7%floated(j+k) = sec5%DRT_5_2%reference_value + (real(x1(i) + decoded(j+k)) * real(2**sec5%DRT_5_2%binary_scale_factor))\n                sec7%floated(j+k) = sec7%floated(j+k) / real(10**(sec5%DRT_5_2%decimal_scale_factor))\n             enddo\n          endif\n          j = j + L(i)\n       enddo\n       deallocate(x1)\n       deallocate(lengths)\n       deallocate(widths)\n       deallocate(decoded)\n       nullify(decoded)\n       deallocate(L)\n\n    case (40)\n\n       ! Grid-point data -- JPEG 2000\n\n       if (sec5%DRT_5_40%nbits == 0) then\n          if (associated(sec7%floated)) then\n             deallocate(sec7%floated)\n             nullify(sec7%floated)\n          endif\n          allocate(sec7%floated(grib%sec3%nx * grib%sec3%ny), stat=allostat)\n          if (allostat /= 0) stop \"FATAL ERROR: In module module_grib2.F -- Allocation problem 1\"\n          do i = 1, ( grib%sec3%nx * grib%sec3%ny )\n             sec7%floated(i) = sec5%DRT_5_40%reference_value * (10.0 ** (-sec5%DRT_5_40%decimal_scale_factor))\n          enddo\n\n       else\n\n          ! Hack:  Unswap our previously swapped bytes.\n          ! Need to find a better way of handling swapping\n          call swap4f(grib%buffer, size(grib%buffer))\n\n          grib%iskip = grib%iskip + (sec7%size-5)*8\n\n          ! call fortran_decode_jpeg2000(grib%buffer(6:), sec7%size-5, decoded)\n          call fortran_decode_jpeg2000(grib%buffer(sec7_beginning+6:), sec7%size-5, decoded)\n\n          if (.not. associated(decoded)) then\n             write(*,'(\"Problem decoding jpeg2000.\")')\n             ! stop \"Problem\"\n          else\n             if (associated(sec7%floated)) then\n                deallocate(sec7%floated)\n                nullify(sec7%floated)\n             endif\n             allocate(sec7%floated(size(decoded)))\n             do i=1,  size(decoded)\n                sec7%floated(i) = sec5%DRT_5_40%reference_value + decoded(i) * 2.0 ** real(sec5%DRT_5_40%binary_scale_factor)\n                sec7%floated(i) = sec7%floated(i) * 10.0 ** real(-sec5%DRT_5_40%decimal_scale_factor)\n             enddo\n             deallocate(decoded)\n             nullify(decoded)\n          endif\n          ! Reswap\n          call swap4f(grib%buffer, size(grib%buffer))\n       endif\n\n    end select\n\n    ! Build the full 2-d array, unpacking from the bitmap if necessary\n\n    if (associated(grib%array)) then\n       deallocate(grib%array)\n       nullify(grib%array)\n    endif\n    allocate(grib%array(grib%sec3%nx, grib%sec3%ny))\n    grib%array = 0.0\n\n    if (grib%sec6%bit_map_indicator == 255) then\n       do i = 1, grib%sec3%nx\n          do j = 1, grib%sec3%ny\n             n = (j-1)*grib%sec3%nx + i\n             grib%array(i,j) = sec7%floated(n)\n          enddo\n       enddo\n    else\n       n = 0\n       do j = 1, grib%sec3%ny\n          do i = 1, grib%sec3%nx\n             if (grib%bitmap(i,j)==1) then\n                n = n + 1\n                grib%array(i,j) = sec7%floated(n)\n             endif\n          enddo\n       enddo\n    endif\n\n    ! Position ourselves at the end of the section.\n    grib%iskip = (sec7_beginning + sec7%size) * 8\n  end subroutine unpack_sec7\n\n!=================================================================================\n!=================================================================================\n\n  subroutine print_sec7(grib)\n    implicit none\n    type (GribStruct), target, intent(in) :: grib\n    type (Section7Struct), pointer :: sec7\n    sec7 => grib%sec7\n    write(*,'(\"Section 7\")')\n    write(*,'(\"   Length of section:                   \",I8)') sec7%size\n    if (associated(sec7%floated)) then\n       write(*,'(\"   First value =                        \", F15.8)') sec7%floated(1)\n    endif\n  end subroutine print_sec7\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib2\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_grib2_tables.F",
    "content": "module module_grib2_tables\n\n  type table_entry_struct\n     integer                   :: product_discipline\n     integer                   :: parameter_category\n     integer                   :: parameter_index\n     character(len=256)        :: category_name\n     character(len=256)        :: parameter_name\n     character(len=256)        :: parameter_units\n     type(table_entry_struct), pointer  :: next\n  end type table_entry_struct\n  type(table_entry_struct), target :: table\n\ncontains\n\n!=================================================================================\n!=================================================================================\n\n  subroutine grib2_read_parameter_tables\n    implicit none\n    integer :: iunit\n    character(len=200) :: string\n    integer :: ierr\n    integer, external :: get_unused_unit\n    integer :: p1, p2, p3\n\n    integer            :: product_discipline_index\n    integer            :: parameter_category_index\n    character(len=128) :: parameter_category_name\n\n\n    integer           :: parameter_index\n    character(len=64) :: parameter_name\n    character(len=32) :: parameter_units\n    character(len=256) :: grib_root\n    character(len=256) :: table_filename\n\n    call getenv(\"GRIB_ROOT\", grib_root)\n    if (trim(grib_root)==\" \") then\n       write(*,'(\"WARNING: Not finding environment variable GRIB_ROOT.\")')\n       write(*,'(\"WARNING: Program does not know where to find GRIB parameter tables\")')\n       stop \"FATAL ERROR: In module module_grib2_tables.F -- Unable to find the environment varaible GRIB_ROOT\"\n    endif\n    table_filename = trim(grib_root)//\"/GRIB2_PARAMETER_TABLE\"\n\n    iunit = get_unused_unit()\n    nullify(table%next)\n\n#ifndef NCEP_WCOSS\n\n#else\n    open(iunit, file=trim(table_filename), status='old', form='formatted', action='read', iostat=ierr)\n#endif\n\n    if (ierr /= 0) then\n       write(*,'(/,\" ***** ERROR *****\",/)')\n       write(*,'(\" ***** Problem opening file ''\", A, \"''\")') trim(table_filename)\n       write(*,'(\" ***** Does file exist?  Is file readable?\",/)')\n       stop \"FATAL ERROR: In module module_grib2_tables.F -- Problem opening file\"\n    endif\n\n    READ_TABLE : do\n#ifndef NCEP_WCOSS\n\n#else\n       read(iunit, '(A200)', iostat=ierr) string\n#endif\n       if (ierr /= 0) exit READ_TABLE\n       if (string(1:1) == \"#\") cycle READ_TABLE\n       if (string(1:1) == \"+\") then\n          !\n          ! read table header info, separated by '+' signs\n          !\n          p1 = index(string, \"+\")\n          p1 = p1 + 1\n          p2 = p1 + index(string(p1:), \"+\")\n          p3 = p2 + index(string(p2:), \"+\")\n          read(string(p1:p2-2), *) product_discipline_index\n          read(string(p2:p3-2), *) parameter_category_index\n          parameter_category_name = trim(adjustl(string(p3:)))\n       else\n          p1 = index(string, \"|\") - 1\n          p2 = p1 + index(string(p1+2:), \"|\")\n          read(string(1:p1),*) parameter_index\n          parameter_name = trim(adjustl(string(p1+2:p2)))\n          parameter_units = trim(adjustl(string(p2+2:)))\n          ! print*, parameter_index, trim(parameter_name),\" \", trim(parameter_units)\n\n          call add_to_growing_table(product_discipline_index, parameter_category_index, parameter_category_name, &\n               parameter_index, parameter_name, parameter_units)\n\n       endif\n    enddo READ_TABLE\n#ifndef NCEP_WCOSS\n#else\n    close(iunit)\n#endif\n\n  end subroutine grib2_read_parameter_tables\n\n!=================================================================================\n!=================================================================================\n\n  subroutine add_to_growing_table(pdi, pci, pcn, pi, pn, pu)\n    implicit none\n! Input:\n!       pdi:  Parameter Discipline index number\n!       pci:  Parameter Category index number in discipline <pdi>\n!       pi:   Parameter index number in category <pci> and discipline <pdi>\n!       pcn:  Parameter category name\n!       pn:   Parameter name\n!       pu:   Parameter units\n\n! Input\n    integer, intent(in) :: pdi\n    integer, intent(in) :: pci\n    integer, intent(in) :: pi\n    character(len=*), intent(in) :: pcn\n    character(len=*), intent(in) :: pn\n    character(len=*), intent(in) :: pu\n\n! Local\n    type(table_entry_struct), pointer:: table_pointer\n\n    ! Start us off by pointing to the top of the table.\n    table_pointer => table\n\n    ! Seek for the end of the table.\n    do while (associated(table_pointer%next))\n       table_pointer => table_pointer%next\n    enddo\n\n    ! Now that we're at the end of the table, create a new entry\n    allocate(table_pointer%next)\n    table_pointer => table_pointer%next\n    nullify(table_pointer%next)\n\n    ! Fill our new entry with the information passed into this subroutine\n    table_pointer%product_discipline = pdi\n    table_pointer%parameter_category =   pci\n    table_pointer%parameter_index    =   pi\n    table_pointer%category_name    =   pcn\n    table_pointer%parameter_name     =   pn\n    table_pointer%parameter_units    =   pu\n\n  end subroutine add_to_growing_table\n\n!=================================================================================\n!=================================================================================\n  subroutine grib2_clear_parameter_table\n    implicit none\n\n! Local\n    type(table_entry_struct), pointer:: table_pointer\n    type(table_entry_struct), pointer:: next_pointer\n\n    ! Start us off by pointing to the top of the table.\n    table_pointer => table\n\n    do while ( associated(table_pointer%next) )\n       next_pointer => table_pointer%next\n       if (associated(table_pointer, table)) then\n          table_pointer => next_pointer\n          nullify(next_pointer)\n       else\n          nullify(table_pointer%next)\n          deallocate(table_pointer)\n          table_pointer => next_pointer\n          nullify(next_pointer)\n       endif\n    enddo\n\n    if (associated(table_pointer)) then\n       ! deallocate(table_pointer)\n       nullify(table_pointer)\n    endif\n    if (associated(next_pointer)) then\n       nullify(next_pointer)\n    endif\n\n  end subroutine grib2_clear_parameter_table\n\n!=================================================================================\n!=================================================================================\n\n  subroutine get_parameter_table_information(discipline, category, parameter_index, &\n       category_name, parameter_name, parameter_units)\n    implicit none\n    integer, intent(in) :: discipline, category, parameter_index\n    character(len=256), intent(out) :: category_name, parameter_name, parameter_units\n\n    type(table_entry_struct), pointer:: table_pointer\n    write(category_name, '(\"Discipline: \", I3, \"   Unknown category: \", I3)') discipline, category\n    write(parameter_name, '(\"Unknown parameter: \", I3)') parameter_index\n    parameter_units = \" \"\n\n    table_pointer => table\n    do while (associated(table_pointer%next))\n       table_pointer => table_pointer%next\n       if ( ( table_pointer%product_discipline == discipline ) .and. &\n            ( table_pointer%parameter_category == category ) .and. &\n            ( table_pointer%parameter_index    == parameter_index) ) then\n          ! We found a match\n          category_name = table_pointer%category_name\n          parameter_name = table_pointer%parameter_name\n          parameter_units = table_pointer%parameter_units\n          exit\n       endif\n    enddo\n\n  end subroutine get_parameter_table_information\n\n!=================================================================================\n!=================================================================================\n\n  character(len=32) function interpret_time_unit(i) result(string)\n    implicit none\n    integer, intent(in) :: i\n\n    select case (i)\n    case default\n       write(string, '(\"unrecognized time units: \", I4)') i\n    case (0)\n       string = \"minutes\"\n    case (1)\n       string = \"hours\"\n    case (2)\n       string = \"days\"\n    case (3)\n       string = \"months\"\n    case (4)\n       string = \"years\"\n    case (13)\n       string = \"seconds\"\n    end select\n  end function interpret_time_unit\n\n!=================================================================================\n!=================================================================================\n\n  subroutine get_level_string(surface_type_code, text, units)\n    implicit none\n    integer, intent(in) :: surface_type_code\n    character(len=256), intent(out) :: text\n    character(len=256), intent(out) :: units\n\n    units = \" \"\n    select case (surface_type_code)\n    case default\n       write(text,'(\"Unrecognized type of surface\", I4)') surface_type_code\n    case (1)\n       write(text,'(\"Level:  Ground or water surface\")')\n    case (2)\n       write(text,'(\"Level:  Cloud base level\")')\n    case (3)\n       write(text,'(\"Level:  Cloud top level\")')\n    case (4)\n       write(text,'(\"Level:  0~S~o~N~C isotherm level\")')\n    case (5)\n       write(text,'(\"Level:  Adiabatic lifting condensation level\")')\n    case (6)\n       write(text,'(\"Level:  Maximum wind level\")')\n    case (7)\n       write(text,'(\"Level:  Tropopause\")')\n    case (8)\n       write(text,'(\"Level:  Nominal top of atmosphere\")')\n    case (9)\n       write(text,'(\"Level:  Sea bottom\")')\n    case (20)\n       write(text,'(\"Level:  Isothermal level \")')\n       units = \"K\"\n    case (100)\n       write(text,'(\"Level:  Isobaric surface \")')\n       units = \"Pa\"\n    case (101)\n       write(text,'(\"Level:  Mean sea level\")')\n    case (102)\n       write(text,'(\"Level:  Height MSL \")')\n       units = \"m\"\n    case (103)\n       write(text,'(\"Level:  Height AGL \")')\n       units = \"m\"\n    case (104)\n       write(text,'(\"Level:  Sigma level \")')\n       units = \"sigma value\"\n    case (105)\n       write(text,'(\"Level:  Hybrid level \")')\n    case (106)\n       write(text,'(\"Level:  Depth below land surface \")')\n       units = \"m\"\n    case (107)\n       write(text,'(\"Level:  Isentropic level \")')\n       units = \"K\"\n    case (108)\n       write(text,'(\"Level:  Specified pressure difference from ground \")')\n       units = \"Pa\"\n    case (109)\n       write(text,'(\"Level:  Potential vorticity surface \")')\n       units = \"Kg m{2} kg{-1} s{-1}\"\n    case (111)\n       write(text,'(\"Level:  Eta level \")')\n    case (117)\n       write(text,'(\"Level:  Mixed-layer depth \")')\n       units = \"m\"\n    case (160)\n       write(text,'(\"Level:  Depth below sea-level \")')\n       units = \"m\"\n    end select\n\n  end subroutine get_level_string\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib2_tables\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_grib_common.F",
    "content": "module module_grib_common\n  use module_mapinfo\n  ! Low-level stuff used by both module_grib1 and module_grib2\n  implicit none\n  integer, parameter :: string_sevens = Z\"37373737\" ! Encodes \"7777\", which marks the end of a GRIB record.\n  integer, parameter :: string_grib   = Z\"47524942\" ! Encodes \"GRIB\", which marks the beginning of a GRIB record\n\n  type G1Section1Struct\n     integer :: isize\n     integer :: ptvn\n     integer :: center\n     integer :: process\n     integer :: grid\n     logical :: ifgds\n     logical :: ifbms\n     integer :: parameter\n     integer :: leveltyp\n     real    :: levelval\n     real    :: level2val\n     integer :: year\n     integer :: month\n     integer :: day\n     integer :: hour\n     integer :: minute\n     integer :: ftu\n     integer :: p1\n     integer :: p2\n     integer :: tri\n     integer :: navg\n     integer :: nmissavg\n     integer :: subcenter\n     integer :: decimal_scale_factor\n     character(len=19) :: hdate\n  end type G1Section1Struct\n\n  type G1Section2Struct\n     integer :: isize\n     integer :: nv\n     integer :: pv\n     integer :: drt\n     integer :: nx\n     integer :: ny\n     real    :: lat1\n     real    :: lon1\n     integer :: rac\n     real    :: lat2\n     real    :: lon2\n     real    :: lov\n     real    :: dx\n     real    :: dy\n     integer :: center\n     integer :: scanning_mode\n     integer :: i_scan_direction\n     integer :: j_scan_direction\n     integer :: orientation\n     real    :: latin1\n     real    :: latin2\n     real    :: polelat\n     real    :: polelon\n  end type G1Section2Struct\n\n  type G1Section3Struct\n     integer :: isize\n     integer :: nunused\n     integer :: numeric\n     integer :: bitmap_beginning\n  end type G1Section3Struct\n\n  type G1Section4Struct\n     integer :: isize\n     integer, dimension(4) :: flag\n     integer :: nunused\n     integer :: binary_scale_factor\n     real    :: reference_value\n     integer :: nbits\n     integer :: start_of_packed_data\n  end type G1Section4Struct\n\n  type Section1Struct\n     integer :: size\n     integer :: center\n     integer :: subcenter\n     integer :: mtvn\n     integer :: ltvn\n     integer :: srt\n     integer :: year\n     integer :: month\n     integer :: day\n     integer :: hour\n     integer :: minute\n     integer :: second\n     integer :: production_status\n     integer :: data_type\n     character(len=19) :: hdate\n  end type Section1Struct\n\n  type GT_3_0_Struct\n     integer :: scale_factor_of_radius\n     integer :: scaled_value_of_radius\n     integer :: scale_factor_major_axis\n     integer :: scaled_value_major_axis\n     integer :: scale_factor_minor_axis\n     integer :: scaled_value_minor_axis\n     integer :: basic_angle\n     integer :: subdivisions_of_basic_angle\n     real    :: la1\n     real    :: lo1\n     integer :: resolution_and_component_flags\n     real    :: la2\n     real    :: lo2\n     real    :: dx\n     real    :: dy\n     integer :: scanning_mode\n     integer :: i_direction_increments_given\n     integer :: j_direction_increments_given\n     integer :: winds_grid_relative\n     integer :: i_scan_direction\n     integer :: j_scan_direction\n     integer :: i_scan_consecutive\n     integer :: boustrophedon\n  end type GT_3_0_Struct\n\n  type GT_3_30_Struct\n     integer :: shape_of_earth\n     integer :: scale_factor_of_radius\n     integer :: scaled_value_of_radius\n     integer :: scale_factor_major_axis\n     integer :: scaled_value_major_axis\n     integer :: scale_factor_minor_axis\n     integer :: scaled_value_minor_axis\n     real    :: la1\n     real    :: lo1\n     integer :: resolution_and_component_flags\n     real    :: lad\n     real    :: lov\n     real    :: dx\n     real    :: dy\n     integer :: projection_center_flag\n     integer :: scanning_mode\n     real    :: latin1\n     real    :: latin2\n     real    :: pole_latitude\n     real    :: pole_longitude\n     integer :: i_direction_increments_given\n     integer :: j_direction_increments_given\n     integer :: winds_grid_relative\n     integer :: i_scan_direction\n     integer :: j_scan_direction\n     integer :: i_scan_consecutive\n     integer :: boustrophedon\n  end type GT_3_30_Struct\n\n  type Section3Struct\n     integer :: size\n     integer :: grid_definition_source\n     integer :: number_of_data_points\n     integer :: octets_for_optional_list\n     integer :: list_interpretation\n     integer :: grid_template_number\n     integer :: nx\n     integer :: ny\n     integer :: shape_of_earth\n     type (GT_3_0_Struct) :: GT_3_0\n     type (GT_3_30_Struct) :: GT_3_30\n  end type Section3Struct\n\n!  type PDT_4_0_Struct\n!  end type PDT_4_0_Struct\n\n  type PDT_4_8_Struct\n     integer :: end_year\n     integer :: end_month\n     integer :: end_day\n     integer :: end_hour\n     integer :: end_minute\n     integer :: end_second\n     character(len=19) :: begin_hdate\n     character(len=19) :: end_hdate\n     integer :: number_of_time_range_specifications\n     integer :: number_missing\n     integer :: statistical_process\n     integer :: type_of_time_increment\n     integer :: time_range_unit\n     integer :: length_of_time_range\n     integer :: time_increment_unit\n     integer :: time_increment\n  end type PDT_4_8_Struct\n\n  type Section4Struct\n     integer :: size\n     integer :: number_of_coord_values\n     integer :: product_template_number\n     integer :: parameter_category\n     integer :: parameter_number\n     integer :: type_of_generating_process\n     integer :: background_process_id\n     integer :: generating_process_id\n     integer :: data_cutoff_hours\n     integer :: data_cutoff_minutes\n     integer :: time_range_indicator\n     integer :: time\n     integer :: ltype1\n     integer :: lscale1\n     integer :: lvalue1\n     real    :: level1\n     integer :: ltype2\n     integer :: lscale2\n     integer :: lvalue2\n     real    :: level2\n     ! type (PDT_4_0_Struct) :: PDT_4_0\n     type (PDT_4_8_Struct) :: PDT_4_8\n\n  end type Section4Struct\n\n  type DRT_5_0_Struct\n     integer :: binary_scale_factor\n     integer :: decimal_scale_factor\n     integer :: nbits\n     integer :: data_type\n  end type DRT_5_0_Struct\n\n  type DRT_5_2_Struct\n     real    :: reference_value\n     integer :: binary_scale_factor\n     integer :: decimal_scale_factor\n     integer :: nbits\n     integer :: data_type\n     integer :: group_splitting_method\n     integer :: missing_value_management\n     integer :: substitute1\n     integer :: substitute2\n     integer :: ng\n     integer :: widths_reference\n     integer :: widths_nbits\n     integer :: lengths_reference\n     integer :: length_increment\n     integer :: length_of_last_group\n     integer :: lengths_nbits\n  end type DRT_5_2_Struct\n\n  type DRT_5_40_Struct\n     real :: reference_value\n     integer :: binary_scale_factor\n     integer :: decimal_scale_factor\n     integer :: nbits\n     integer :: data_type\n     integer :: compression_type\n     integer :: target_compression_ratio\n  end type DRT_5_40_Struct\n\n  type Section5Struct\n     integer :: size\n     integer :: nval\n     integer :: data_template_number\n     type (DRT_5_0_Struct) :: DRT_5_0\n     type (DRT_5_2_Struct) :: DRT_5_2\n     type (DRT_5_40_Struct) :: DRT_5_40\n  end type Section5Struct\n\n  type Section6Struct\n     integer :: size\n     integer :: bit_map_indicator\n  end type Section6Struct\n\n  type Section7Struct\n     integer :: size\n     real, pointer, dimension(:)   :: floated\n  end type Section7Struct\n\n  type GribStruct\n     integer :: edition\n     integer :: size\n     character(len=1), pointer, dimension(:)   :: buffer\n     real,             pointer, dimension(:,:) :: array\n     integer,          pointer, dimension(:,:) :: bitmap\n     integer :: iskip\n     integer :: discipline\n\n     type(G1Section1Struct) :: g1sec1\n     type(G1Section2Struct) :: g1sec2\n     type(G1Section3Struct) :: g1sec3\n     type(G1Section4Struct) :: g1sec4\n\n     type(Section1Struct) :: sec1\n     type(Section3Struct) :: sec3\n     type(Section4Struct) :: sec4\n     type(Section5Struct) :: sec5\n     type(Section6Struct) :: sec6\n     type(Section7Struct) :: sec7\n     type(MapInfoStruct)  :: mapinfo\n  end type GribStruct\n\ncontains\n\n!=================================================================================\n!=================================================================================\n\n  integer function unpack_signed_integer(buffer, nbytes, iskip) RESULT (signed_integer)\n    implicit none\n    !\n    ! Purpose:\n    !      From a string of bytes in a buffer array, unpack a stream of bytes into an \n    !      integer variable, with the a priori knowledge that this stream of bytes\n    !      represents a signed integer, the sign indicated by the first bit in the stream. \n    !      The <iskip> indicator is then incremented to refer to the position in the \n    !      <buffer> array at the end of the integer just read.\n    !\n    ! Input:\n    !      buffer:  A buffer array from which we unpack data.\n    !      nbytes:  The number of bytes to read from <buffer> as representing a signed integer\n    !      iskip:   The number of bytes to skip in <buffer> before unpacking <nbytes> of data.\n    !\n    ! Output:\n    !      iskip:   The number of bits in <buffer> up to and including the signed integer \n    !               just read.\n    !\n    ! Return Value:\n    !      The integer unpacked from <buffer>\n    !\n    ! Side effects:\n    !      None\n    !\n    character(len=1), dimension(*), intent(in)    :: buffer\n    integer,                        intent(in)    :: nbytes\n    integer,                        intent(inout) :: iskip\n\n    integer :: isign\n\n    ! Read the first bit, to determine whether this integer is negative (<isign>==1)\n    ! or non-negative (<isign>==0)\n    call gbyte(buffer, isign, iskip, 1)\n\n    ! Read the remaining bits of the integer\n    call gbyte(buffer, signed_integer, iskip+1, (nbytes*8)-1)\n\n    ! Apply the sign we read before to the integer value.\n    if (isign == 1) then\n       signed_integer = -signed_integer\n    endif\n\n    ! Update the <iskip> indicator.\n    iskip = iskip + (nbytes*8)\n\n  end function unpack_signed_integer\n\n!=================================================================================\n!=================================================================================\n\n  integer function unpack_unsigned_integer(buffer, nbytes, iskip) RESULT (unsigned_integer)\n    implicit none\n    !\n    ! Purpose:\n    !      From a string of bytes in a buffer array, unpack a stream of bytes into an \n    !      integer variable, with the a priori knowledge that this stream of bytes\n    !      represents an _unsigned_ integer.  The <iskip> indicator is then incremented \n    !      to refer to the position in the <buffer> array at the end of the integer just read.\n    !\n    ! Input:\n    !      buffer:  A buffer array from which we unpack data.\n    !      nbytes:  The number of bytes to read from <buffer> as representing an unsigned integer\n    !      iskip:   The number of bytes to skip in <buffer> before unpacking <nbytes> of data.\n    !\n    ! Output:\n    !      iskip:   The number of bits in <buffer> up to and including the unsigned integer \n    !               just read.\n    !\n    ! Return Value:\n    !      The integer unpacked from <buffer>\n    !\n    ! Side effects:\n    !      None\n    !\n    character(len=1), dimension(*), intent(in)    :: buffer\n    integer,                        intent(in)    :: nbytes\n    integer,                        intent(inout) :: iskip\n\n    call gbyte(buffer, unsigned_integer, iskip, nbytes*8)\n\n    ! Update the <iskip> indicator.\n    iskip = iskip + (nbytes*8)\n\n  end function unpack_unsigned_integer\n\n!=================================================================================\n!=================================================================================\n\nend module module_grib_common\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_input_data_structure.F",
    "content": "module module_input_data_structure\n  use module_llxy\n  type input_data_type\n     integer                       :: nx     ! Grid Dimension -- X direction\n     integer                       :: ny     ! Grid Dimension -- Y direction\n     type(proj_info)               :: proj   ! Map Projection information\n     character(len=24)             :: hdate  ! Date (YYYY-MM-DD_hh:mm:ss.ffff)\n     character(len=9)              :: field  ! Field name\n     character(len=25)             :: units  ! Field units\n     character(len=46)             :: desc   ! Field description\n     real                          :: layer1 ! Top of a layer definition\n     real                          :: layer2 ! Bottom of a layer definition\n     real, pointer, dimension(:,:) :: data   ! The data array\n  end type input_data_type\n\nend module module_input_data_structure\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_llxy.F",
    "content": "MODULE module_llxy\n\n! Module that defines constants, data structures, and\n! subroutines used to convert grid indices to lat/lon\n! and vice versa.\n!\n! SUPPORTED PROJECTIONS\n! ---------------------\n! Cylindrical Lat/Lon (code = PROJ_LATLON)\n! Mercator (code = PROJ_MERC)\n! Lambert Conformal (code = PROJ_LC)\n! Gaussian (code = PROJ_GAUSS)\n! Polar Stereographic (code = PROJ_PS)\n! Rotated Lat/Lon (code = PROJ_ROTLL)\n!\n! REMARKS\n! -------\n! The routines contained within were adapted from routines\n! obtained from NCEP's w3 library.  The original NCEP routines were less\n! flexible (e.g., polar-stereo routines only supported truelat of 60N/60S)\n! than what we needed, so modifications based on equations in Hoke, Hayes, and\n! Renninger (AFGWC/TN/79-003) were added to improve the flexibility.\n! Additionally, coding was improved to F90 standards and the routines were\n! combined into this module.\n!\n! ASSUMPTIONS\n! -----------\n!  Grid Definition:\n!    For mercator, lambert conformal, and polar-stereographic projections,\n!    the routines within assume the following:\n!\n!       1.  Grid is dimensioned (i,j) where i is the East-West direction,\n!           positive toward the east, and j is the north-south direction,\n!           positive toward the north.\n!       2.  Origin is at (1,1) and is located at the southwest corner,\n!           regardless of hemispere.\n!       3.  Grid spacing (dx) is always positive.\n!       4.  Values of true latitudes must be positive for NH domains\n!           and negative for SH domains.\n!\n!     For the latlon and Gaussian projection, the grid origin may be at any\n!     of the corners, and the deltalat and deltalon values can be signed to\n!     account for this using the following convention:\n!       Origin Location        Deltalat Sign      Deltalon Sign\n!       ---------------        -------------      -------------\n!        SW Corner                  +                   +\n!        NE Corner                  -                   -\n!        NW Corner                  -                   +\n!        SE Corner                  +                   -\n!\n!  Data Definitions:\n!       1. Any arguments that are a latitude value are expressed in\n!          degrees north with a valid range of -90 -> 90\n!       2. Any arguments that are a longitude value are expressed in\n!          degrees east with a valid range of -180 -> 180.\n!       3. Distances are in meters and are always positive.\n!       4. The standard longitude (stdlon) is defined as the longitude\n!          line which is parallel to the grid's y-axis (j-direction), along\n!          which latitude increases (NOT the absolute value of latitude, but\n!          the actual latitude, such that latitude increases continuously\n!          from the south pole to the north pole) as j increases.\n!       5. One true latitude value is required for polar-stereographic and\n!          mercator projections, and defines at which latitude the\n!          grid spacing is true.  For lambert conformal, two true latitude\n!          values must be specified, but may be set equal to each other to\n!          specify a tangent projection instead of a secant projection.\n!\n! USAGE\n! -----\n! To use the routines in this module, the calling routines must have the\n! following statement at the beginning of its declaration block:\n!   USE map_utils\n!\n! The use of the module not only provides access to the necessary routines,\n! but also defines a structure of TYPE (proj_info) that can be used\n! to declare a variable of the same type to hold your map projection\n! information.  It also defines some integer parameters that contain\n! the projection codes so one only has to use those variable names rather\n! than remembering the acutal code when using them.  The basic steps are\n! as follows:\n!\n!   1.  Ensure the \"USE map_utils\" is in your declarations.\n!   2.  Declare the projection information structure as type(proj_info):\n!         TYPE(proj_info) :: proj\n!   3.  Populate your structure by calling the map_set routine:\n!         CALL map_set(code,lat1,lon1,knowni,knownj,dx,stdlon,truelat1,truelat2,proj)\n!       where:\n!         code (input) = one of PROJ_LATLON, PROJ_MERC, PROJ_LC, PROJ_PS,\n!                        PROJ_GAUSS, or PROJ_ROTLL\n!         lat1 (input) = Latitude of grid origin point (i,j)=(1,1)\n!                         (see assumptions!)\n!         lon1 (input) = Longitude of grid origin\n!         knowni (input) = origin point, x-location\n!         knownj (input) = origin point, y-location\n!         dx (input) = grid spacing in meters (ignored for LATLON projections)\n!         stdlon (input) = Standard longitude for PROJ_PS and PROJ_LC,\n!               deltalon (see assumptions) for PROJ_LATLON,\n!               ignored for PROJ_MERC\n!         truelat1 (input) = 1st true latitude for PROJ_PS, PROJ_LC, and\n!                PROJ_MERC, deltalat (see assumptions) for PROJ_LATLON\n!         truelat2 (input) = 2nd true latitude for PROJ_LC,\n!                ignored for all others.\n!         proj (output) = The structure of type (proj_info) that will be fully\n!                populated after this call\n!\n!   4.  Now that the proj structure is populated, you may call either\n!       of the following routines:\n!\n!       latlon_to_ij(proj, lat, lon, i, j)\n!       ij_to_latlon(proj, i, j, lat, lon)\n!\n!       It is incumbent upon the calling routine to determine whether or\n!       not the values returned are within your domain's bounds.  All values\n!       of i, j, lat, and lon are REAL values.\n!\n!\n! REFERENCES\n! ----------\n!  Hoke, Hayes, and Renninger, \"Map Preojections and Grid Systems for\n!       Meteorological Applications.\" AFGWC/TN-79/003(Rev), Air Weather\n!       Service, 1985.\n!\n!  NCAR MM5v3 Modeling System, REGRIDDER program, module_first_guess_map.F\n!  NCEP routines w3fb06, w3fb07, w3fb08, w3fb09, w3fb11, w3fb12\n!\n! HISTORY\n! -------\n! 27 Mar 2001 - Original Version\n!               Brent L. Shaw, NOAA/FSL (CSU/CIRA)\n!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n   INTEGER, PARAMETER :: HH=4, VV=5\n\n   REAL, PARAMETER :: PI = 3.141592653589793\n   REAL, PARAMETER :: OMEGA_E = 7.292e-5\n\n   REAL, PARAMETER :: DEG_PER_RAD = 180./PI\n   REAL, PARAMETER :: RAD_PER_DEG = PI/180.\n\n   REAL, PARAMETER :: A_WGS84  = 6378137.\n   REAL, PARAMETER :: B_WGS84  = 6356752.314\n   REAL, PARAMETER :: RE_WGS84 = A_WGS84\n   REAL, PARAMETER :: E_WGS84  = 0.081819192\n\n   REAL, PARAMETER :: A_NAD83  = 6378137.\n   REAL, PARAMETER :: RE_NAD83 = A_NAD83\n   REAL, PARAMETER :: E_NAD83  = 0.0818187034\n\n   REAL, PARAMETER :: EARTH_RADIUS_M = 6370000.\n   REAL, PARAMETER :: EARTH_CIRC_M = 2.*PI*EARTH_RADIUS_M\n\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_LATLON = 0\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_LC = 1\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_PS = 2\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_PS_WGS84 = 102\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_MERC = 3\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_GAUSS = 4\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_CYL = 5\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_CASSINI = 6\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_ALBERS_NAD83 = 105\n   INTEGER, PUBLIC, PARAMETER  :: PROJ_ROTLL = 203\n\n   ! Define some private constants\n   INTEGER, PRIVATE, PARAMETER :: HIGH = 8\n\n   TYPE proj_info\n\n      INTEGER          :: code     ! Integer code for projection TYPE\n      INTEGER          :: nlat     ! For Gaussian -- number of latitude points \n                                   !  north of the equator\n      INTEGER          :: nlon     !\n                                   !\n      INTEGER          :: ixdim    ! For Rotated Lat/Lon -- number of mass points\n                                   !  in an odd row\n      INTEGER          :: jydim    ! For Rotated Lat/Lon -- number of rows\n      INTEGER          :: stagger  ! For Rotated Lat/Lon -- mass or velocity grid \n      REAL             :: phi      ! For Rotated Lat/Lon -- domain half-extent in \n                                   !  degrees latitude\n      REAL             :: lambda   ! For Rotated Lat/Lon -- domain half-extend in\n                                   !  degrees longitude\n      REAL             :: lat1     ! SW latitude (1,1) in degrees (-90->90N)\n      REAL             :: lon1     ! SW longitude (1,1) in degrees (-180->180E)\n      REAL             :: lat0     ! For Cassini, latitude of projection pole\n      REAL             :: lon0     ! For Cassini, longitude of projection pole\n      REAL             :: dx       ! Grid spacing in meters at truelats, used\n                                   !  only for ps, lc, and merc projections\n      REAL             :: dy       ! Grid spacing in meters at truelats, used\n                                   !  only for ps, lc, and merc projections\n      REAL             :: latinc   ! Latitude increment for cylindrical lat/lon\n      REAL             :: loninc   ! Longitude increment for cylindrical lat/lon\n                                   !  also the lon increment for Gaussian grid\n      REAL             :: dlat     ! Lat increment for lat/lon grids\n      REAL             :: dlon     ! Lon increment for lat/lon grids\n      REAL             :: stdlon   ! Longitude parallel to y-axis (-180->180E)\n      REAL             :: truelat1 ! First true latitude (all projections)\n      REAL             :: truelat2 ! Second true lat (LC only)\n      REAL             :: hemi     ! 1 for NH, -1 for SH\n      REAL             :: cone     ! Cone factor for LC projections\n      REAL             :: polei    ! Computed i-location of pole point\n      REAL             :: polej    ! Computed j-location of pole point\n      REAL             :: rsw      ! Computed radius to SW corner\n      REAL             :: rebydx   ! Earth radius divided by dx\n      REAL             :: knowni   ! X-location of known lat/lon\n      REAL             :: knownj   ! Y-location of known lat/lon\n      REAL             :: re_m     ! Radius of spherical earth, meters\n      REAL             :: rho0     ! For Albers equal area\n      REAL             :: nc       ! For Albers equal area\n      REAL             :: bigc     ! For Albers equal area\n      LOGICAL          :: init     ! Flag to indicate if this struct is\n                                   !  ready for use\n      LOGICAL          :: wrap     ! For Gaussian -- flag to indicate wrapping \n                                   !  around globe?\n      REAL, POINTER, DIMENSION(:) :: gauss_lat  ! Latitude array for Gaussian grid\n\n   END TYPE proj_info\n\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n CONTAINS\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n   SUBROUTINE map_init(proj)\n      ! Initializes the map projection structure to missing values\n\n      IMPLICIT NONE\n      TYPE(proj_info), INTENT(INOUT)  :: proj\n\n      proj%lat1     = -999.9\n      proj%lon1     = -999.9\n      proj%lat0     = -999.9\n      proj%lon0     = -999.9\n      proj%dx       = -999.9\n      proj%dy       = -999.9\n      proj%latinc   = -999.9\n      proj%loninc   = -999.9\n      proj%stdlon   = -999.9\n      proj%truelat1 = -999.9\n      proj%truelat2 = -999.9\n      proj%phi      = -999.9\n      proj%lambda   = -999.9\n      proj%ixdim    = -999\n      proj%jydim    = -999\n      proj%stagger  = HH\n      proj%nlat     = 0\n      proj%nlon     = 0\n      proj%hemi     = 0.0\n      proj%cone     = -999.9\n      proj%polei    = -999.9\n      proj%polej    = -999.9\n      proj%rsw      = -999.9\n      proj%knowni   = -999.9\n      proj%knownj   = -999.9\n      proj%re_m     = EARTH_RADIUS_M\n      proj%init     = .FALSE.\n      proj%wrap     = .FALSE.\n      proj%rho0     = 0.\n      proj%nc       = 0.\n      proj%bigc     = 0.\n      nullify(proj%gauss_lat)\n\n   END SUBROUTINE map_init\n\n\n   SUBROUTINE map_set(proj_code, proj, lat1, lon1, lat0, lon0, knowni, knownj, dx, latinc, &\n                      loninc, stdlon, truelat1, truelat2, nlat, nlon, ixdim, jydim, &\n                      stagger, phi, lambda, r_earth)\n      ! Given a partially filled proj_info structure, this routine computes\n      ! polei, polej, rsw, and cone (if LC projection) to complete the\n      ! structure.  This allows us to eliminate redundant calculations when\n      ! calling the coordinate conversion routines multiple times for the\n      ! same map.\n      ! This will generally be the first routine called when a user wants\n      ! to be able to use the coordinate conversion routines, and it\n      ! will call the appropriate subroutines based on the\n      ! proj%code which indicates which projection type this is.\n\n      IMPLICIT NONE\n\n      ! Declare arguments\n      INTEGER, INTENT(IN)               :: proj_code\n      INTEGER, INTENT(IN), OPTIONAL     :: nlat\n      INTEGER, INTENT(IN), OPTIONAL     :: nlon\n      INTEGER, INTENT(IN), OPTIONAL     :: ixdim\n      INTEGER, INTENT(IN), OPTIONAL     :: jydim\n      INTEGER, INTENT(IN), OPTIONAL     :: stagger\n      REAL, INTENT(IN), OPTIONAL        :: latinc\n      REAL, INTENT(IN), OPTIONAL        :: loninc\n      REAL, INTENT(IN), OPTIONAL        :: lat1\n      REAL, INTENT(IN), OPTIONAL        :: lon1\n      REAL, INTENT(IN), OPTIONAL        :: lat0\n      REAL, INTENT(IN), OPTIONAL        :: lon0\n      REAL, INTENT(IN), OPTIONAL        :: dx\n      REAL, INTENT(IN), OPTIONAL        :: stdlon\n      REAL, INTENT(IN), OPTIONAL        :: truelat1\n      REAL, INTENT(IN), OPTIONAL        :: truelat2\n      REAL, INTENT(IN), OPTIONAL        :: knowni\n      REAL, INTENT(IN), OPTIONAL        :: knownj\n      REAL, INTENT(IN), OPTIONAL        :: phi\n      REAL, INTENT(IN), OPTIONAL        :: lambda\n      REAL, INTENT(IN), OPTIONAL        :: r_earth\n      TYPE(proj_info), INTENT(OUT)      :: proj\n\n      INTEGER :: iter\n      REAL :: dummy_lon1\n      REAL :: dummy_lon0\n      REAL :: dummy_stdlon\n\n      ! First, verify that mandatory parameters are present for the specified proj_code\n      IF ( proj_code == PROJ_LC ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(truelat2) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, truelat2, lat1, lon1, knowni, knownj, stdlon, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_PS ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, lat1, lon1, knonwi, knownj, stdlon, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_PS_WGS84 ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, lat1, lon1, knonwi, knownj, stdlon, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_ALBERS_NAD83 ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(truelat2) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, truelat2, lat1, lon1, knonwi, knownj, stdlon, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_MERC ) THEN\n         IF ( .NOT.PRESENT(truelat1) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(dx) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' truelat1, lat1, lon1, knowni, knownj, dx'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_LATLON ) THEN\n         IF ( .NOT.PRESENT(latinc) .OR. &\n              .NOT.PRESENT(loninc) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' latinc, loninc, knowni, knownj, lat1, lon1'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_CYL ) THEN\n         IF ( .NOT.PRESENT(latinc) .OR. &\n              .NOT.PRESENT(loninc) .OR. &\n              .NOT.PRESENT(stdlon) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' latinc, loninc, stdlon'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_CASSINI ) THEN\n         IF ( .NOT.PRESENT(latinc) .OR. &\n              .NOT.PRESENT(loninc) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(lat0) .OR. &\n              .NOT.PRESENT(lon0) .OR. &\n              .NOT.PRESENT(knowni) .OR. &\n              .NOT.PRESENT(knownj) .OR. &\n              .NOT.PRESENT(stdlon) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' latinc, loninc, lat1, lon1, knowni, knownj, lat0, lon0, stdlon'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_GAUSS ) THEN\n         IF ( .NOT.PRESENT(nlat) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(loninc) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' nlat, lat1, lon1, loninc'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE IF ( proj_code == PROJ_ROTLL ) THEN\n         IF ( .NOT.PRESENT(ixdim) .OR. &\n              .NOT.PRESENT(jydim) .OR. &\n              .NOT.PRESENT(phi) .OR. &\n              .NOT.PRESENT(lambda) .OR. &\n              .NOT.PRESENT(lat1) .OR. &\n              .NOT.PRESENT(lon1) .OR. &\n              .NOT.PRESENT(stagger) ) THEN\n            PRINT '(A,I2)', 'The following are mandatory parameters for projection code : ', proj_code\n            PRINT '(A)', ' ixdim, jydim, phi, lambda, lat1, lon1, stagger'\n            STOP 'MAP_INIT'\n         END IF\n      ELSE\n         PRINT '(A,I2)', 'Unknown projection code: ', proj_code\n         STOP 'MAP_INIT'\n      END IF\n\n      ! Check for validity of mandatory variables in proj\n      IF ( PRESENT(lat1) ) THEN\n         IF ( ABS(lat1) .GT. 90. ) THEN\n            PRINT '(A)', 'Latitude of origin corner required as follows:'\n            PRINT '(A)', '    -90N <= lat1 < = 90.N'\n            PRINT '(\"Latitude found:\", F20.8)', lat1\n            STOP 'MAP_INIT'\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(lon1) ) THEN\n         dummy_lon1 = lon1\n         IF ( ABS(dummy_lon1) .GT. 180.) THEN\n            iter = 0\n            DO WHILE (ABS(dummy_lon1) > 180. .AND. iter < 10)\n               IF (dummy_lon1 < -180.) dummy_lon1 = dummy_lon1 + 360.\n               IF (dummy_lon1 > 180.) dummy_lon1 = dummy_lon1 - 360.\n               iter = iter + 1\n            END DO\n            IF (abs(dummy_lon1) > 180.) THEN\n               PRINT '(A)', 'Longitude of origin required as follows:'\n               PRINT '(A)', '   -180E <= lon1 <= 180W'\n               STOP 'MAP_INIT'\n            ENDIF\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(lon0) ) THEN\n         dummy_lon0 = lon0\n         IF ( ABS(dummy_lon0) .GT. 180.) THEN\n            iter = 0\n            DO WHILE (ABS(dummy_lon0) > 180. .AND. iter < 10)\n               IF (dummy_lon0 < -180.) dummy_lon0 = dummy_lon0 + 360.\n               IF (dummy_lon0 > 180.) dummy_lon0 = dummy_lon0 - 360.\n               iter = iter + 1\n            END DO\n            IF (abs(dummy_lon0) > 180.) THEN\n               PRINT '(A)', 'Longitude of pole required as follows:'\n               PRINT '(A)', '   -180E <= lon0 <= 180W'\n               STOP 'MAP_INIT'\n            ENDIF\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(dx) ) THEN\n         IF ((dx .LE. 0.).AND.(proj_code .NE. PROJ_LATLON)) THEN\n            PRINT '(A)', 'Require grid spacing (dx) in meters be positive'\n            STOP 'MAP_INIT'\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(stdlon) ) THEN\n         dummy_stdlon = stdlon\n         IF ((ABS(dummy_stdlon) > 180.).AND.(proj_code /= PROJ_MERC)) THEN\n            iter = 0\n            DO WHILE (ABS(dummy_stdlon) > 180. .AND. iter < 10)\n               IF (dummy_stdlon < -180.) dummy_stdlon = dummy_stdlon + 360.\n               IF (dummy_stdlon > 180.) dummy_stdlon = dummy_stdlon - 360.\n               iter = iter + 1\n            END DO\n            IF (abs(dummy_stdlon) > 180.) THEN\n               PRINT '(A)', 'Need orientation longitude (stdlon) as: '\n               PRINT '(A)', '   -180E <= stdlon <= 180W'\n               STOP 'MAP_INIT'\n            ENDIF\n         ENDIF\n      ENDIF\n\n      IF ( PRESENT(truelat1) ) THEN\n         IF (ABS(truelat1).GT.90.) THEN\n            PRINT '(A)', 'Set true latitude 1 for all projections'\n            STOP 'MAP_INIT'\n         ENDIF\n      ENDIF\n\n      CALL map_init(proj)\n      proj%code  = proj_code\n      IF ( PRESENT(lat1) )     proj%lat1     = lat1\n      IF ( PRESENT(lon1) )     proj%lon1     = dummy_lon1\n      IF ( PRESENT(lat0) )     proj%lat0     = lat0\n      IF ( PRESENT(lon0) )     proj%lon0     = dummy_lon0\n      IF ( PRESENT(latinc) )   proj%latinc   = latinc\n      IF ( PRESENT(loninc) )   proj%loninc   = loninc\n      IF ( PRESENT(knowni) )   proj%knowni   = knowni\n      IF ( PRESENT(knownj) )   proj%knownj   = knownj\n      IF ( PRESENT(dx) )       proj%dx       = dx\n      IF ( PRESENT(stdlon) )   proj%stdlon   = dummy_stdlon\n      IF ( PRESENT(truelat1) ) proj%truelat1 = truelat1\n      IF ( PRESENT(truelat2) ) proj%truelat2 = truelat2\n      IF ( PRESENT(nlat) )     proj%nlat     = nlat\n      IF ( PRESENT(nlon) )     proj%nlon     = nlon\n      IF ( PRESENT(ixdim) )    proj%ixdim    = ixdim\n      IF ( PRESENT(jydim) )    proj%jydim    = jydim\n      IF ( PRESENT(stagger) )  proj%stagger  = stagger\n      IF ( PRESENT(phi) )      proj%phi      = phi\n      IF ( PRESENT(lambda) )   proj%lambda   = lambda\n      IF ( PRESENT(r_earth) )  proj%re_m     = r_earth\n\n      IF ( PRESENT(dx) ) THEN\n         IF ( (proj_code == PROJ_LC) .OR. (proj_code == PROJ_PS) .OR. &\n              (proj_code == PROJ_PS_WGS84) .OR. (proj_code == PROJ_ALBERS_NAD83) .OR. &\n              (proj_code == PROJ_MERC) ) THEN\n            proj%dx = dx\n            IF (truelat1 .LT. 0.) THEN\n               proj%hemi = -1.0\n            ELSE\n               proj%hemi = 1.0\n            ENDIF\n            proj%rebydx = proj%re_m / dx\n         ENDIF\n      ENDIF\n\n      pick_proj: SELECT CASE(proj%code)\n\n         CASE(PROJ_PS)\n            CALL set_ps(proj)\n\n         CASE(PROJ_PS_WGS84)\n            CALL set_ps_wgs84(proj)\n\n         CASE(PROJ_ALBERS_NAD83)\n            CALL set_albers_nad83(proj)\n\n         CASE(PROJ_LC)\n            IF (ABS(proj%truelat2) .GT. 90.) THEN\n               proj%truelat2=proj%truelat1\n            ENDIF\n            CALL set_lc(proj)\n\n         CASE (PROJ_MERC)\n            CALL set_merc(proj)\n\n         CASE (PROJ_LATLON)\n\n         CASE (PROJ_GAUSS)\n            CALL set_gauss(proj)\n\n         CASE (PROJ_CYL)\n            CALL set_cyl(proj)\n\n         CASE (PROJ_CASSINI)\n            CALL set_cassini(proj)\n\n         CASE (PROJ_ROTLL)\n\n      END SELECT pick_proj\n      proj%init = .TRUE.\n\n      RETURN\n\n   END SUBROUTINE map_set\n\n\n   SUBROUTINE latlon_to_ij(proj, lat, lon, i, j)\n      ! Converts input lat/lon values to the cartesian (i,j) value\n      ! for the given projection.\n\n      IMPLICIT NONE\n      TYPE(proj_info), INTENT(IN)          :: proj\n      REAL, INTENT(IN)                     :: lat\n      REAL, INTENT(IN)                     :: lon\n      REAL, INTENT(OUT)                    :: i\n      REAL, INTENT(OUT)                    :: j\n\n      IF (.NOT.proj%init) THEN\n         PRINT '(A)', 'You have not called map_set for this projection'\n         STOP 'LATLON_TO_IJ'\n      ENDIF\n\n      SELECT CASE(proj%code)\n\n         CASE(PROJ_LATLON)\n            CALL llij_latlon(lat,lon,proj,i,j)\n\n         CASE(PROJ_MERC)\n            CALL llij_merc(lat,lon,proj,i,j)\n\n         CASE(PROJ_PS)\n            CALL llij_ps(lat,lon,proj,i,j)\n\n         CASE(PROJ_PS_WGS84)\n            CALL llij_ps_wgs84(lat,lon,proj,i,j)\n\n         CASE(PROJ_ALBERS_NAD83)\n            CALL llij_albers_nad83(lat,lon,proj,i,j)\n\n         CASE(PROJ_LC)\n            CALL llij_lc(lat,lon,proj,i,j)\n\n         CASE(PROJ_GAUSS)\n            CALL llij_gauss(lat,lon,proj,i,j)\n\n         CASE(PROJ_CYL)\n            CALL llij_cyl(lat,lon,proj,i,j)\n\n         CASE(PROJ_CASSINI)\n            CALL llij_cassini(lat,lon,proj,i,j)\n\n         CASE(PROJ_ROTLL)\n            CALL llij_rotlatlon(lat,lon,proj,i,j)\n\n         CASE DEFAULT\n            PRINT '(A,I2)', 'Unrecognized map projection code: ', proj%code\n            STOP 'LATLON_TO_IJ'\n\n      END SELECT\n\n      RETURN\n\n   END SUBROUTINE latlon_to_ij\n\n\n   SUBROUTINE ij_to_latlon(proj, i, j, lat, lon)\n      ! Computes geographical latitude and longitude for a given (i,j) point\n      ! in a grid with a projection of proj\n\n      IMPLICIT NONE\n      TYPE(proj_info),INTENT(IN)          :: proj\n      REAL, INTENT(IN)                    :: i\n      REAL, INTENT(IN)                    :: j\n      REAL, INTENT(OUT)                   :: lat\n      REAL, INTENT(OUT)                   :: lon\n\n      IF (.NOT.proj%init) THEN\n         PRINT '(A)', 'You have not called map_set for this projection'\n         STOP 'IJ_TO_LATLON'\n      ENDIF\n      SELECT CASE (proj%code)\n\n         CASE (PROJ_LATLON)\n            CALL ijll_latlon(i, j, proj, lat, lon)\n\n         CASE (PROJ_MERC)\n            CALL ijll_merc(i, j, proj, lat, lon)\n\n         CASE (PROJ_PS)\n            CALL ijll_ps(i, j, proj, lat, lon)\n\n         CASE (PROJ_PS_WGS84)\n            CALL ijll_ps_wgs84(i, j, proj, lat, lon)\n\n         CASE (PROJ_ALBERS_NAD83)\n            CALL ijll_albers_nad83(i, j, proj, lat, lon)\n\n         CASE (PROJ_LC)\n            CALL ijll_lc(i, j, proj, lat, lon)\n\n         CASE (PROJ_CYL)\n            CALL ijll_cyl(i, j, proj, lat, lon)\n\n         CASE (PROJ_CASSINI)\n            CALL ijll_cassini(i, j, proj, lat, lon)\n\n         CASE (PROJ_ROTLL)\n            CALL ijll_rotlatlon(i, j, proj, lat, lon)\n\n         CASE DEFAULT\n            PRINT '(A,I2)', 'Unrecognized map projection code: ', proj%code\n            STOP 'IJ_TO_LATLON'\n\n      END SELECT\n      RETURN\n   END SUBROUTINE ij_to_latlon\n\n\n   SUBROUTINE set_ps(proj)\n      ! Initializes a polar-stereographic map projection from the partially\n      ! filled proj structure. This routine computes the radius to the\n      ! southwest corner and computes the i/j location of the pole for use\n      ! in llij_ps and ijll_ps.\n      IMPLICIT NONE\n\n      ! Declare args\n      TYPE(proj_info), INTENT(INOUT)    :: proj\n\n      ! Local vars\n      REAL                              :: ala1\n      REAL                              :: alo1\n      REAL                              :: reflon\n      REAL                              :: scale_top\n\n      ! Executable code\n      reflon = proj%stdlon + 90.\n\n      ! Compute numerator term of map scale factor\n      scale_top = 1. + proj%hemi * SIN(proj%truelat1 * rad_per_deg)\n\n      ! Compute radius to lower-left (SW) corner\n      ala1 = proj%lat1 * rad_per_deg\n      proj%rsw = proj%rebydx*COS(ala1)*scale_top/(1.+proj%hemi*SIN(ala1))\n\n      ! Find the pole point\n      alo1 = (proj%lon1 - reflon) * rad_per_deg\n      proj%polei = proj%knowni - proj%rsw * COS(alo1)\n      proj%polej = proj%knownj - proj%hemi * proj%rsw * SIN(alo1)\n\n      RETURN\n\n   END SUBROUTINE set_ps\n\n\n   SUBROUTINE llij_ps(lat,lon,proj,i,j)\n      ! Given latitude (-90 to 90), longitude (-180 to 180), and the\n      ! standard polar-stereographic projection information via the\n      ! public proj structure, this routine returns the i/j indices which\n      ! if within the domain range from 1->nx and 1->ny, respectively.\n\n      IMPLICIT NONE\n\n      ! Delcare input arguments\n      REAL, INTENT(IN)               :: lat\n      REAL, INTENT(IN)               :: lon\n      TYPE(proj_info),INTENT(IN)     :: proj\n\n      ! Declare output arguments\n      REAL, INTENT(OUT)              :: i !(x-index)\n      REAL, INTENT(OUT)              :: j !(y-index)\n\n      ! Declare local variables\n\n      REAL                           :: reflon\n      REAL                           :: scale_top\n      REAL                           :: ala\n      REAL                           :: alo\n      REAL                           :: rm\n\n      ! BEGIN CODE\n\n      reflon = proj%stdlon + 90.\n\n      ! Compute numerator term of map scale factor\n\n      scale_top = 1. + proj%hemi * SIN(proj%truelat1 * rad_per_deg)\n\n      ! Find radius to desired point\n      ala = lat * rad_per_deg\n      rm = proj%rebydx * COS(ala) * scale_top/(1. + proj%hemi *SIN(ala))\n      alo = (lon - reflon) * rad_per_deg\n      i = proj%polei + rm * COS(alo)\n      j = proj%polej + proj%hemi * rm * SIN(alo)\n\n      RETURN\n\n   END SUBROUTINE llij_ps\n\n\n   SUBROUTINE ijll_ps(i, j, proj, lat, lon)\n\n      ! This is the inverse subroutine of llij_ps.  It returns the\n      ! latitude and longitude of an i/j point given the projection info \n      ! structure.\n\n      IMPLICIT NONE\n\n      ! Declare input arguments\n      REAL, INTENT(IN)                    :: i    ! Column\n      REAL, INTENT(IN)                    :: j    ! Row\n      TYPE (proj_info), INTENT(IN)        :: proj\n\n      ! Declare output arguments\n      REAL, INTENT(OUT)                   :: lat     ! -90 -> 90 north\n      REAL, INTENT(OUT)                   :: lon     ! -180 -> 180 East\n\n      ! Local variables\n      REAL                                :: reflon\n      REAL                                :: scale_top\n      REAL                                :: xx,yy\n      REAL                                :: gi2, r2\n      REAL                                :: arccos\n\n      ! Begin Code\n\n      ! Compute the reference longitude by rotating 90 degrees to the east\n      ! to find the longitude line parallel to the positive x-axis.\n      reflon = proj%stdlon + 90.\n\n      ! Compute numerator term of map scale factor\n      scale_top = 1. + proj%hemi * SIN(proj%truelat1 * rad_per_deg)\n\n      ! Compute radius to point of interest\n      xx = i - proj%polei\n      yy = (j - proj%polej) * proj%hemi\n      r2 = xx**2 + yy**2\n\n      ! Now the magic code\n      IF (r2 .EQ. 0.) THEN\n         lat = proj%hemi * 90.\n         lon = reflon\n      ELSE\n         gi2 = (proj%rebydx * scale_top)**2.\n         lat = deg_per_rad * proj%hemi * ASIN((gi2-r2)/(gi2+r2))\n         arccos = ACOS(xx/SQRT(r2))\n         IF (yy .GT. 0) THEN\n            lon = reflon + deg_per_rad * arccos\n         ELSE\n            lon = reflon - deg_per_rad * arccos\n         ENDIF\n      ENDIF\n\n      ! Convert to a -180 -> 180 East convention\n      IF (lon .GT. 180.) lon = lon - 360.\n      IF (lon .LT. -180.) lon = lon + 360.\n\n      RETURN\n\n   END SUBROUTINE ijll_ps\n\n\n   SUBROUTINE set_ps_wgs84(proj)\n      ! Initializes a polar-stereographic map projection (WGS84 ellipsoid) \n      ! from the partially filled proj structure. This routine computes the \n      ! radius to the southwest corner and computes the i/j location of the \n      ! pole for use in llij_ps and ijll_ps.\n\n      IMPLICIT NONE\n\n      ! Arguments\n      TYPE(proj_info), INTENT(INOUT)    :: proj\n\n      ! Local variables\n      real :: h, mc, tc, t, rho\n\n      h = proj%hemi\n\n      mc = cos(h*proj%truelat1*rad_per_deg)/sqrt(1.0-(E_WGS84*sin(h*proj%truelat1*rad_per_deg))**2.0)\n      tc = sqrt(((1.0-sin(h*proj%truelat1*rad_per_deg))/(1.0+sin(h*proj%truelat1*rad_per_deg)))* &\n                (((1.0+E_WGS84*sin(h*proj%truelat1*rad_per_deg))/(1.0-E_WGS84*sin(h*proj%truelat1*rad_per_deg)))**E_WGS84 ))\n\n      ! Find the i/j location of reference lat/lon with respect to the pole of the projection\n      t = sqrt(((1.0-sin(h*proj%lat1*rad_per_deg))/(1.0+sin(h*proj%lat1*rad_per_deg)))* &\n               (((1.0+E_WGS84*sin(h*proj%lat1*rad_per_deg))/(1.0-E_WGS84*sin(h*proj%lat1*rad_per_deg)) )**E_WGS84 ) )\n      rho = h * (A_WGS84 / proj%dx) * mc * t / tc\n      proj%polei = rho * sin((h*proj%lon1 - h*proj%stdlon)*rad_per_deg)\n      proj%polej = -rho * cos((h*proj%lon1 - h*proj%stdlon)*rad_per_deg)\n\n      RETURN\n\n   END SUBROUTINE set_ps_wgs84\n\n\n   SUBROUTINE llij_ps_wgs84(lat,lon,proj,i,j)\n      ! Given latitude (-90 to 90), longitude (-180 to 180), and the\n      ! standard polar-stereographic projection information via the\n      ! public proj structure, this routine returns the i/j indices which\n      ! if within the domain range from 1->nx and 1->ny, respectively.\n\n      IMPLICIT NONE\n\n      ! Arguments\n      REAL, INTENT(IN)               :: lat\n      REAL, INTENT(IN)               :: lon\n      REAL, INTENT(OUT)              :: i !(x-index)\n      REAL, INTENT(OUT)              :: j !(y-index)\n      TYPE(proj_info),INTENT(IN)     :: proj\n\n      ! Local variables\n      real :: h, mc, tc, t, rho\n\n      h = proj%hemi\n\n      mc = cos(h*proj%truelat1*rad_per_deg)/sqrt(1.0-(E_WGS84*sin(h*proj%truelat1*rad_per_deg))**2.0)\n      tc = sqrt(((1.0-sin(h*proj%truelat1*rad_per_deg))/(1.0+sin(h*proj%truelat1*rad_per_deg)))* &\n                (((1.0+E_WGS84*sin(h*proj%truelat1*rad_per_deg))/(1.0-E_WGS84*sin(h*proj%truelat1*rad_per_deg)))**E_WGS84 ))\n\n      t = sqrt(((1.0-sin(h*lat*rad_per_deg))/(1.0+sin(h*lat*rad_per_deg))) * &\n               (((1.0+E_WGS84*sin(h*lat*rad_per_deg))/(1.0-E_WGS84*sin(h*lat*rad_per_deg)))**E_WGS84))\n\n      ! Find the x/y location of the requested lat/lon with respect to the pole of the projection\n      rho = (A_WGS84 / proj%dx) * mc * t / tc\n      i = h *  rho * sin((h*lon - h*proj%stdlon)*rad_per_deg)\n      j = h *(-rho)* cos((h*lon - h*proj%stdlon)*rad_per_deg)\n\n      ! Get i/j relative to reference i/j\n      i = proj%knowni + (i - proj%polei)\n      j = proj%knownj + (j - proj%polej)\n\n      RETURN\n\n   END SUBROUTINE llij_ps_wgs84\n\n\n   SUBROUTINE ijll_ps_wgs84(i, j, proj, lat, lon)\n\n      ! This is the inverse subroutine of llij_ps.  It returns the\n      ! latitude and longitude of an i/j point given the projection info \n      ! structure.\n\n      implicit none\n\n      ! Arguments\n      REAL, INTENT(IN)                    :: i    ! Column\n      REAL, INTENT(IN)                    :: j    ! Row\n      REAL, INTENT(OUT)                   :: lat     ! -90 -> 90 north\n      REAL, INTENT(OUT)                   :: lon     ! -180 -> 180 East\n      TYPE (proj_info), INTENT(IN)        :: proj\n\n      ! Local variables\n      real :: h, mc, tc, t, rho, x, y\n      real :: chi, a, b, c, d\n\n      h = proj%hemi\n      x = (i - proj%knowni + proj%polei)\n      y = (j - proj%knownj + proj%polej)\n\n      mc = cos(h*proj%truelat1*rad_per_deg)/sqrt(1.0-(E_WGS84*sin(h*proj%truelat1*rad_per_deg))**2.0)\n      tc = sqrt(((1.0-sin(h*proj%truelat1*rad_per_deg))/(1.0+sin(h*proj%truelat1*rad_per_deg))) * &\n                (((1.0+E_WGS84*sin(h*proj%truelat1*rad_per_deg))/(1.0-E_WGS84*sin(h*proj%truelat1*rad_per_deg)))**E_WGS84 ))\n\n      rho = sqrt((x*proj%dx)**2.0 + (y*proj%dx)**2.0)\n      t = rho * tc / (A_WGS84 * mc)\n\n      lon = h*proj%stdlon*rad_per_deg + h*atan2(h*x,h*(-y))\n\n      chi = PI/2.0-2.0*atan(t)\n      a = 1./2.*E_WGS84**2. + 5./24.*E_WGS84**4. +  1./40.*E_WGS84**6.  +    73./2016.*E_WGS84**8.\n      b =                     7./24.*E_WGS84**4. + 29./120.*E_WGS84**6. + 54113./40320.*E_WGS84**8.\n      c =                                           7./30.*E_WGS84**6.  +    81./280.*E_WGS84**8.\n      d =                                                                  4279./20160.*E_WGS84**8.\n\n      lat = chi + sin(2.*chi)*(a + cos(2.*chi)*(b + cos(2.*chi)*(c + d*cos(2.*chi))))\n      lat = h * lat\n\n      lat = lat*deg_per_rad\n      lon = lon*deg_per_rad\n\n      RETURN\n\n   END SUBROUTINE ijll_ps_wgs84\n\n\n   SUBROUTINE set_albers_nad83(proj)\n      ! Initializes an Albers equal area map projection (NAD83 ellipsoid) \n      ! from the partially filled proj structure. This routine computes the \n      ! radius to the southwest corner and computes the i/j location of the \n      ! pole for use in llij_albers_nad83 and ijll_albers_nad83.\n\n      IMPLICIT NONE\n\n      ! Arguments\n      TYPE(proj_info), INTENT(INOUT)    :: proj\n\n      ! Local variables\n      real :: h, m1, m2, q1, q2, theta, q, sinphi\n\n      h = proj%hemi\n\n      m1 = cos(h*proj%truelat1*rad_per_deg)/sqrt(1.0-(E_NAD83*sin(h*proj%truelat1*rad_per_deg))**2.0)\n      m2 = cos(h*proj%truelat2*rad_per_deg)/sqrt(1.0-(E_NAD83*sin(h*proj%truelat2*rad_per_deg))**2.0)\n\n      sinphi = sin(proj%truelat1*rad_per_deg)\n      q1 = (1.0-E_NAD83**2.0) * &\n           ((sinphi/(1.0-(E_NAD83*sinphi)**2.0)) - 1.0/(2.0*E_NAD83) * log((1.0-E_NAD83*sinphi)/(1.0+E_NAD83*sinphi)))\n\n      sinphi = sin(proj%truelat2*rad_per_deg)\n      q2 = (1.0-E_NAD83**2.0) * &\n           ((sinphi/(1.0-(E_NAD83*sinphi)**2.0)) - 1.0/(2.0*E_NAD83) * log((1.0-E_NAD83*sinphi)/(1.0+E_NAD83*sinphi)))\n\n      if (proj%truelat1 == proj%truelat2) then\n         proj%nc = sin(proj%truelat1*rad_per_deg)\n      else\n         proj%nc = (m1**2.0 - m2**2.0) / (q2 - q1)\n      end if\n\n      proj%bigc = m1**2.0 + proj%nc*q1\n\n      ! Find the i/j location of reference lat/lon with respect to the pole of the projection\n      sinphi = sin(proj%lat1*rad_per_deg)\n      q = (1.0-E_NAD83**2.0) * &\n           ((sinphi/(1.0-(E_NAD83*sinphi)**2.0)) - 1.0/(2.0*E_NAD83) * log((1.0-E_NAD83*sinphi)/(1.0+E_NAD83*sinphi)))\n\n      proj%rho0 = h * (A_NAD83 / proj%dx) * sqrt(proj%bigc - proj%nc * q) / proj%nc \n      theta = proj%nc*(proj%lon1 - proj%stdlon)*rad_per_deg\n\n      proj%polei = proj%rho0 * sin(h*theta)\n      proj%polej = proj%rho0 - proj%rho0 * cos(h*theta)\n\n      RETURN\n\n   END SUBROUTINE set_albers_nad83\n\n\n   SUBROUTINE llij_albers_nad83(lat,lon,proj,i,j)\n      ! Given latitude (-90 to 90), longitude (-180 to 180), and the\n      ! standard projection information via the\n      ! public proj structure, this routine returns the i/j indices which\n      ! if within the domain range from 1->nx and 1->ny, respectively.\n\n      IMPLICIT NONE\n\n      ! Arguments\n      REAL, INTENT(IN)               :: lat\n      REAL, INTENT(IN)               :: lon\n      REAL, INTENT(OUT)              :: i !(x-index)\n      REAL, INTENT(OUT)              :: j !(y-index)\n      TYPE(proj_info),INTENT(IN)     :: proj\n\n      ! Local variables\n      real :: h, q, rho, theta, sinphi\n\n      h = proj%hemi\n\n      sinphi = sin(h*lat*rad_per_deg)\n\n      ! Find the x/y location of the requested lat/lon with respect to the pole of the projection\n      q = (1.0-E_NAD83**2.0) * &\n           ((sinphi/(1.0-(E_NAD83*sinphi)**2.0)) - 1.0/(2.0*E_NAD83) * log((1.0-E_NAD83*sinphi)/(1.0+E_NAD83*sinphi)))\n\n      rho = h * (A_NAD83 / proj%dx) * sqrt(proj%bigc - proj%nc * q) / proj%nc\n      theta = proj%nc * (h*lon - h*proj%stdlon)*rad_per_deg\n\n      i = h*rho*sin(theta)\n      j = h*proj%rho0 - h*rho*cos(theta)\n\n      ! Get i/j relative to reference i/j\n      i = proj%knowni + (i - proj%polei)\n      j = proj%knownj + (j - proj%polej)\n\n      RETURN\n\n   END SUBROUTINE llij_albers_nad83\n\n\n   SUBROUTINE ijll_albers_nad83(i, j, proj, lat, lon)\n\n      ! This is the inverse subroutine of llij_albers_nad83.  It returns the \n      ! latitude and longitude of an i/j point given the projection info \n      ! structure.\n\n      implicit none\n\n      ! Arguments\n      REAL, INTENT(IN)                    :: i    ! Column\n      REAL, INTENT(IN)                    :: j    ! Row\n      REAL, INTENT(OUT)                   :: lat     ! -90 -> 90 north\n      REAL, INTENT(OUT)                   :: lon     ! -180 -> 180 East\n      TYPE (proj_info), INTENT(IN)        :: proj\n\n      ! Local variables\n      real :: h, q, rho, theta, beta, x, y\n      real :: a, b, c\n\n      h = proj%hemi\n\n      x = (i - proj%knowni + proj%polei)\n      y = (j - proj%knownj + proj%polej)\n\n      rho = sqrt(x**2.0 + (proj%rho0 - y)**2.0)\n      theta = atan2(x, proj%rho0-y)\n\n      q = (proj%bigc - (rho*proj%nc*proj%dx/A_NAD83)**2.0) / proj%nc\n\n      beta = asin(q/(1.0 - log((1.0-E_NAD83)/(1.0+E_NAD83))*(1.0-E_NAD83**2.0)/(2.0*E_NAD83)))\n      a = 1./3.*E_NAD83**2. + 31./180.*E_NAD83**4. + 517./5040.*E_NAD83**6.\n      b =                     23./360.*E_NAD83**4. + 251./3780.*E_NAD83**6.\n      c =                                            761./45360.*E_NAD83**6.\n\n      lat = beta + a*sin(2.*beta) + b*sin(4.*beta) + c*sin(6.*beta)\n\n      lat = h*lat*deg_per_rad\n      lon = proj%stdlon + theta*deg_per_rad/proj%nc\n\n      RETURN\n\n   END SUBROUTINE ijll_albers_nad83\n\n\n   SUBROUTINE set_lc(proj)\n      ! Initialize the remaining items in the proj structure for a\n      ! lambert conformal grid.\n\n      IMPLICIT NONE\n\n      TYPE(proj_info), INTENT(INOUT)     :: proj\n\n      REAL                               :: arg\n      REAL                               :: deltalon1\n      REAL                               :: tl1r\n      REAL                               :: ctl1r\n\n      ! Compute cone factor\n      CALL lc_cone(proj%truelat1, proj%truelat2, proj%cone)\n\n      ! Compute longitude differences and ensure we stay out of the\n      ! forbidden \"cut zone\"\n      deltalon1 = proj%lon1 - proj%stdlon\n      IF (deltalon1 .GT. +180.) deltalon1 = deltalon1 - 360.\n      IF (deltalon1 .LT. -180.) deltalon1 = deltalon1 + 360.\n\n      ! Convert truelat1 to radian and compute COS for later use\n      tl1r = proj%truelat1 * rad_per_deg\n      ctl1r = COS(tl1r)\n\n      ! Compute the radius to our known lower-left (SW) corner\n      proj%rsw = proj%rebydx * ctl1r/proj%cone * &\n             (TAN((90.*proj%hemi-proj%lat1)*rad_per_deg/2.) / &\n              TAN((90.*proj%hemi-proj%truelat1)*rad_per_deg/2.))**proj%cone\n\n      ! Find pole point\n      arg = proj%cone*(deltalon1*rad_per_deg)\n      proj%polei = proj%hemi*proj%knowni - proj%hemi * proj%rsw * SIN(arg)\n      proj%polej = proj%hemi*proj%knownj + proj%rsw * COS(arg)\n\n      RETURN\n\n   END SUBROUTINE set_lc\n\n\n   SUBROUTINE lc_cone(truelat1, truelat2, cone)\n\n   ! Subroutine to compute the cone factor of a Lambert Conformal projection\n\n      IMPLICIT NONE\n\n      ! Input Args\n      REAL, INTENT(IN)             :: truelat1  ! (-90 -> 90 degrees N)\n      REAL, INTENT(IN)             :: truelat2  !   \"   \"  \"   \"     \"\n\n      ! Output Args\n      REAL, INTENT(OUT)            :: cone\n\n      ! Locals\n\n      ! BEGIN CODE\n\n      ! First, see if this is a secant or tangent projection.  For tangent\n      ! projections, truelat1 = truelat2 and the cone is tangent to the\n      ! Earth's surface at this latitude.  For secant projections, the cone\n      ! intersects the Earth's surface at each of the distinctly different\n      ! latitudes\n      IF (ABS(truelat1-truelat2) .GT. 0.1) THEN\n         cone = ALOG10(COS(truelat1*rad_per_deg)) - &\n                ALOG10(COS(truelat2*rad_per_deg))\n         cone = cone /(ALOG10(TAN((45.0 - ABS(truelat1)/2.0) * rad_per_deg)) - &\n                ALOG10(TAN((45.0 - ABS(truelat2)/2.0) * rad_per_deg)))        \n      ELSE\n         cone = SIN(ABS(truelat1)*rad_per_deg )\n      ENDIF\n\n      RETURN\n\n   END SUBROUTINE lc_cone\n\n\n   SUBROUTINE ijll_lc( i, j, proj, lat, lon)\n\n   ! Subroutine to convert from the (i,j) cartesian coordinate to the\n   ! geographical latitude and longitude for a Lambert Conformal projection.\n\n   ! History:\n   ! 25 Jul 01: Corrected by B. Shaw, NOAA/FSL\n   !\n      IMPLICIT NONE\n\n      ! Input Args\n      REAL, INTENT(IN)              :: i        ! Cartesian X coordinate\n      REAL, INTENT(IN)              :: j        ! Cartesian Y coordinate\n      TYPE(proj_info),INTENT(IN)    :: proj     ! Projection info structure\n\n      ! Output Args\n      REAL, INTENT(OUT)             :: lat      ! Latitude (-90->90 deg N)\n      REAL, INTENT(OUT)             :: lon      ! Longitude (-180->180 E)\n\n      ! Locals\n      REAL                          :: inew\n      REAL                          :: jnew\n      REAL                          :: r\n      REAL                          :: chi,chi1,chi2\n      REAL                          :: r2\n      REAL                          :: xx\n      REAL                          :: yy\n\n      ! BEGIN CODE\n\n      chi1 = (90. - proj%hemi*proj%truelat1)*rad_per_deg\n      chi2 = (90. - proj%hemi*proj%truelat2)*rad_per_deg\n\n      ! See if we are in the southern hemispere and flip the indices\n      ! if we are.\n      inew = proj%hemi * i\n      jnew = proj%hemi * j\n\n      ! Compute radius**2 to i/j location\n      xx = inew - proj%polei\n      yy = proj%polej - jnew\n      r2 = (xx*xx + yy*yy)\n      r = SQRT(r2)/proj%rebydx\n\n      ! Convert to lat/lon\n      IF (r2 .EQ. 0.) THEN\n         lat = proj%hemi * 90.\n         lon = proj%stdlon\n      ELSE\n\n         ! Longitude\n         lon = proj%stdlon + deg_per_rad * ATAN2(proj%hemi*xx,yy)/proj%cone\n         lon = MOD(lon+360., 360.)\n\n         ! Latitude.  Latitude determined by solving an equation adapted \n         ! from:\n         !  Maling, D.H., 1973: Coordinate Systems and Map Projections\n         ! Equations #20 in Appendix I.\n\n         IF (chi1 .EQ. chi2) THEN\n            chi = 2.0*ATAN( ( r/TAN(chi1) )**(1./proj%cone) * TAN(chi1*0.5) )\n         ELSE\n            chi = 2.0*ATAN( (r*proj%cone/SIN(chi1))**(1./proj%cone) * TAN(chi1*0.5)) \n         ENDIF\n         lat = (90.0-chi*deg_per_rad)*proj%hemi\n\n      ENDIF\n\n      IF (lon .GT. +180.) lon = lon - 360.\n      IF (lon .LT. -180.) lon = lon + 360.\n\n      RETURN\n\n   END SUBROUTINE ijll_lc\n\n\n   SUBROUTINE llij_lc( lat, lon, proj, i, j)\n\n   ! Subroutine to compute the geographical latitude and longitude values\n   ! to the cartesian x/y on a Lambert Conformal projection.\n\n      IMPLICIT NONE\n\n      ! Input Args\n      REAL, INTENT(IN)              :: lat      ! Latitude (-90->90 deg N)\n      REAL, INTENT(IN)              :: lon      ! Longitude (-180->180 E)\n      TYPE(proj_info),INTENT(IN)      :: proj     ! Projection info structure\n\n      ! Output Args\n      REAL, INTENT(OUT)             :: i        ! Cartesian X coordinate\n      REAL, INTENT(OUT)             :: j        ! Cartesian Y coordinate\n\n      ! Locals\n      REAL                          :: arg\n      REAL                          :: deltalon\n      REAL                          :: tl1r\n      REAL                          :: rm\n      REAL                          :: ctl1r\n\n\n      ! BEGIN CODE\n\n      ! Compute deltalon between known longitude and standard lon and ensure\n      ! it is not in the cut zone\n      deltalon = lon - proj%stdlon\n      IF (deltalon .GT. +180.) deltalon = deltalon - 360.\n      IF (deltalon .LT. -180.) deltalon = deltalon + 360.\n\n      ! Convert truelat1 to radian and compute COS for later use\n      tl1r = proj%truelat1 * rad_per_deg\n      ctl1r = COS(tl1r)\n\n      ! Radius to desired point\n      rm = proj%rebydx * ctl1r/proj%cone * &\n           (TAN((90.*proj%hemi-lat)*rad_per_deg/2.) / &\n            TAN((90.*proj%hemi-proj%truelat1)*rad_per_deg/2.))**proj%cone\n\n      arg = proj%cone*(deltalon*rad_per_deg)\n      i = proj%polei + proj%hemi * rm * SIN(arg)\n      j = proj%polej - rm * COS(arg)\n\n      ! Finally, if we are in the southern hemisphere, flip the i/j\n      ! values to a coordinate system where (1,1) is the SW corner\n      ! (what we assume) which is different than the original NCEP\n      ! algorithms which used the NE corner as the origin in the\n      ! southern hemisphere (left-hand vs. right-hand coordinate?)\n      i = proj%hemi * i\n      j = proj%hemi * j\n\n      RETURN\n   END SUBROUTINE llij_lc\n\n\n   SUBROUTINE set_merc(proj)\n\n      ! Sets up the remaining basic elements for the mercator projection\n\n      IMPLICIT NONE\n      TYPE(proj_info), INTENT(INOUT)       :: proj\n      REAL                                 :: clain\n\n\n      !  Preliminary variables\n\n      clain = COS(rad_per_deg*proj%truelat1)\n      proj%dlon = proj%dx / (proj%re_m * clain)\n\n      ! Compute distance from equator to origin, and store in the\n      ! proj%rsw tag.\n\n      proj%rsw = 0.\n      IF (proj%lat1 .NE. 0.) THEN\n         proj%rsw = (ALOG(TAN(0.5*((proj%lat1+90.)*rad_per_deg))))/proj%dlon\n      ENDIF\n\n      RETURN\n\n   END SUBROUTINE set_merc\n\n\n   SUBROUTINE llij_merc(lat, lon, proj, i, j)\n\n      ! Compute i/j coordinate from lat lon for mercator projection\n\n      IMPLICIT NONE\n      REAL, INTENT(IN)              :: lat\n      REAL, INTENT(IN)              :: lon\n      TYPE(proj_info),INTENT(IN)    :: proj\n      REAL,INTENT(OUT)              :: i\n      REAL,INTENT(OUT)              :: j\n      REAL                          :: deltalon\n\n      deltalon = lon - proj%lon1\n      IF (deltalon .LT. -180.) deltalon = deltalon + 360.\n      IF (deltalon .GT. 180.) deltalon = deltalon - 360.\n      i = proj%knowni + (deltalon/(proj%dlon*deg_per_rad))\n      j = proj%knownj + (ALOG(TAN(0.5*((lat + 90.) * rad_per_deg)))) / &\n             proj%dlon - proj%rsw\n\n      RETURN\n\n   END SUBROUTINE llij_merc\n\n\n   SUBROUTINE ijll_merc(i, j, proj, lat, lon)\n\n      ! Compute the lat/lon from i/j for mercator projection\n\n      IMPLICIT NONE\n      REAL,INTENT(IN)               :: i\n      REAL,INTENT(IN)               :: j\n      TYPE(proj_info),INTENT(IN)    :: proj\n      REAL, INTENT(OUT)             :: lat\n      REAL, INTENT(OUT)             :: lon\n\n\n      lat = 2.0*ATAN(EXP(proj%dlon*(proj%rsw + j-proj%knownj)))*deg_per_rad - 90.\n      lon = (i-proj%knowni)*proj%dlon*deg_per_rad + proj%lon1\n      IF (lon.GT.180.) lon = lon - 360.\n      IF (lon.LT.-180.) lon = lon + 360.\n      RETURN\n\n   END SUBROUTINE ijll_merc\n\n\n   SUBROUTINE llij_latlon(lat, lon, proj, i, j)\n\n      ! Compute the i/j location of a lat/lon on a LATLON grid.\n      IMPLICIT NONE\n      REAL, INTENT(IN)             :: lat\n      REAL, INTENT(IN)             :: lon\n      TYPE(proj_info), INTENT(IN)  :: proj\n      REAL, INTENT(OUT)            :: i\n      REAL, INTENT(OUT)            :: j\n\n      REAL                         :: deltalat\n      REAL                         :: deltalon\n\n      ! Compute deltalat and deltalon as the difference between the input \n      ! lat/lon and the origin lat/lon\n      deltalat = lat - proj%lat1\n      deltalon = lon - proj%lon1\n\n      ! Compute i/j\n      i = deltalon/proj%loninc\n      j = deltalat/proj%latinc\n\n      i = i + proj%knowni\n      j = j + proj%knownj\n\n      RETURN\n\n   END SUBROUTINE llij_latlon\n\n\n   SUBROUTINE ijll_latlon(i, j, proj, lat, lon)\n\n      ! Compute the lat/lon location of an i/j on a LATLON grid.\n      IMPLICIT NONE\n      REAL, INTENT(IN)             :: i\n      REAL, INTENT(IN)             :: j\n      TYPE(proj_info), INTENT(IN)  :: proj\n      REAL, INTENT(OUT)            :: lat\n      REAL, INTENT(OUT)            :: lon\n\n      REAL                         :: i_work, j_work\n      REAL                         :: deltalat\n      REAL                         :: deltalon\n\n      i_work = i - proj%knowni\n      j_work = j - proj%knownj\n\n      ! Compute deltalat and deltalon\n      deltalat = j_work*proj%latinc\n      deltalon = i_work*proj%loninc\n\n      lat = proj%lat1 + deltalat\n      lon = proj%lon1 + deltalon\n\n      RETURN\n\n   END SUBROUTINE ijll_latlon\n\n\n   SUBROUTINE set_cyl(proj)\n\n      implicit none\n\n      ! Arguments\n      type(proj_info), intent(inout) :: proj\n\n      proj%hemi = 1.0\n\n   END SUBROUTINE set_cyl\n\n\n   SUBROUTINE llij_cyl(lat, lon, proj, i, j)\n\n      implicit none\n\n      ! Arguments\n      real, intent(in) :: lat, lon\n      real, intent(out) :: i, j\n      type(proj_info), intent(in) :: proj\n\n      ! Local variables\n      real :: deltalat\n      real :: deltalon\n\n      ! Compute deltalat and deltalon as the difference between the input\n      ! lat/lon and the origin lat/lon\n      deltalat = lat - proj%lat1\n!      deltalon = lon - proj%stdlon\n      deltalon = lon - proj%lon1\n\n      if (deltalon <   0.) deltalon = deltalon + 360.\n      if (deltalon > 360.) deltalon = deltalon - 360.\n\n      ! Compute i/j\n      i = deltalon/proj%loninc\n      j = deltalat/proj%latinc\n\n      if (i <= 0.)              i = i + 360./proj%loninc\n      if (i > 360./proj%loninc) i = i - 360./proj%loninc\n\n      i = i + proj%knowni\n      j = j + proj%knownj\n\n   END SUBROUTINE llij_cyl\n\n\n   SUBROUTINE ijll_cyl(i, j, proj, lat, lon)\n\n      implicit none\n\n      ! Arguments\n      real, intent(in) :: i, j\n      real, intent(out) :: lat, lon\n      type(proj_info), intent(in) :: proj\n\n      ! Local variables\n      real :: deltalat\n      real :: deltalon\n      real :: i_work, j_work\n\n      i_work = i - proj%knowni\n      j_work = j - proj%knownj\n\n      if (i_work < 0.)              i_work = i_work + 360./proj%loninc\n      if (i_work >= 360./proj%loninc) i_work = i_work - 360./proj%loninc\n\n      ! Compute deltalat and deltalon\n      deltalat = j_work*proj%latinc\n      deltalon = i_work*proj%loninc\n\n      lat = deltalat + proj%lat1\n!      lon = deltalon + proj%stdlon\n      lon = deltalon + proj%lon1\n\n      if (lon < -180.) lon = lon + 360.\n      if (lon >  180.) lon = lon - 360.\n\n   END SUBROUTINE ijll_cyl\n\n\n   SUBROUTINE set_cassini(proj)\n\n      implicit none\n\n      ! Arguments\n      type(proj_info), intent(inout) :: proj\n\n      ! Local variables\n      real :: comp_lat, comp_lon\n      logical :: global_domain\n\n      proj%hemi = 1.0\n\n      ! Try to determine whether this domain has global coverage\n      if (abs(proj%lat1 - proj%latinc/2. + 90.) < 0.001 .and. &\n          abs(mod(proj%lon1 - proj%loninc/2. - proj%stdlon,360.)) < 0.001) then\n         global_domain = .true.\n      else\n         global_domain = .false.\n      end if\n\n      if (abs(proj%lat0) /= 90. .and. .not.global_domain) then\n         call rotate_coords(proj%lat1,proj%lon1,comp_lat,comp_lon,proj%lat0,proj%lon0,proj%stdlon,-1)\n         proj%lat1 = comp_lat\n         proj%lon1 = comp_lon\n      end if\n\n   END SUBROUTINE set_cassini\n\n\n   SUBROUTINE llij_cassini(lat, lon, proj, i, j)\n\n      implicit none\n\n      ! Arguments\n      real, intent(in) :: lat, lon\n      real, intent(out) :: i, j\n      type(proj_info), intent(in) :: proj\n\n      ! Local variables\n      real :: comp_lat, comp_lon\n\n      ! Convert geographic to computational lat/lon\n      if (abs(proj%lat0) /= 90.) then\n         call rotate_coords(lat,lon,comp_lat,comp_lon,proj%lat0,proj%lon0,proj%stdlon,-1)\n      else\n         comp_lat = lat\n         comp_lon = lon\n      end if\n\n      ! Convert computational lat/lon to i/j\n      call llij_cyl(comp_lat, comp_lon, proj, i, j)\n\n   END SUBROUTINE llij_cassini\n\n\n   SUBROUTINE ijll_cassini(i, j, proj, lat, lon)\n\n      implicit none\n\n      ! Arguments\n      real, intent(in) :: i, j\n      real, intent(out) :: lat, lon\n      type(proj_info), intent(in) :: proj\n\n      ! Local variables\n      real :: comp_lat, comp_lon\n\n      ! Convert i/j to computational lat/lon\n      call ijll_cyl(i, j, proj, comp_lat, comp_lon)\n\n      ! Convert computational to geographic lat/lon\n      if (abs(proj%lat0) /= 90.) then\n         call rotate_coords(comp_lat,comp_lon,lat,lon,proj%lat0,proj%lon0,proj%stdlon,1)\n      else\n         lat = comp_lat\n         lon = comp_lon\n      end if\n\n   END SUBROUTINE ijll_cassini\n\n\n   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \n   ! Purpose: Converts between computational and geographic lat/lon for Cassini\n   !\n   ! Notes: This routine was provided by Bill Skamarock, 2007-03-27\n   !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \n   SUBROUTINE rotate_coords(ilat,ilon,olat,olon,lat_np,lon_np,lon_0,direction)\n\n      IMPLICIT NONE\n\n      REAL, INTENT(IN   ) :: ilat, ilon\n      REAL, INTENT(  OUT) :: olat, olon\n      REAL, INTENT(IN   ) :: lat_np, lon_np, lon_0\n      INTEGER, INTENT(IN  ), OPTIONAL :: direction\n      ! >=0, default : computational -> geographical\n      ! < 0          : geographical  -> computational\n\n      REAL :: rlat, rlon\n      REAL :: phi_np, lam_np, lam_0, dlam\n      REAL :: sinphi, cosphi, coslam, sinlam\n\n      ! Convert all angles to radians\n      phi_np = lat_np * rad_per_deg\n      lam_np = lon_np * rad_per_deg\n      lam_0  = lon_0  * rad_per_deg\n      rlat = ilat * rad_per_deg\n      rlon = ilon * rad_per_deg\n\n      IF (PRESENT(direction) .AND. (direction < 0)) THEN\n         ! The equations are exactly the same except for one small difference\n         ! with respect to longitude ...\n         dlam = PI - lam_0\n      ELSE\n         dlam = lam_np\n      END IF\n      sinphi = COS(phi_np)*COS(rlat)*COS(rlon-dlam) + SIN(phi_np)*SIN(rlat)\n      cosphi = SQRT(1.-sinphi*sinphi)\n      coslam = SIN(phi_np)*COS(rlat)*COS(rlon-dlam) - COS(phi_np)*SIN(rlat)\n      sinlam = COS(rlat)*SIN(rlon-dlam)\n      IF ( cosphi /= 0. ) THEN\n         coslam = coslam/cosphi\n         sinlam = sinlam/cosphi\n      END IF\n      olat = deg_per_rad*ASIN(sinphi)\n      olon = deg_per_rad*(ATAN2(sinlam,coslam)-dlam-lam_0+lam_np)\n      ! Both of my F90 text books prefer the DO-EXIT form, and claim it is faster\n      ! when optimization is turned on (as we will always do...)\n      DO\n         IF (olon >= -180.) EXIT\n         olon = olon + 360.\n      END DO\n      DO\n         IF (olon <=  180.) EXIT\n         olon = olon - 360.\n      END DO\n\n   END SUBROUTINE rotate_coords\n\n\n   SUBROUTINE llij_rotlatlon(lat, lon, proj, i_real, j_real)\n\n      IMPLICIT NONE\n\n      ! Arguments\n      REAL, INTENT(IN) :: lat, lon\n      REAL             :: i, j\n      REAL, INTENT(OUT) :: i_real, j_real\n      TYPE (proj_info), INTENT(IN) :: proj\n\n      ! Local variables\n      INTEGER :: ii,imt,jj,jmt,k,krows,ncol,nrow,iri\n      REAL(KIND=HIGH) :: dphd,dlmd !Grid increments, degrees\n      REAL(KIND=HIGH) :: glatd  !Geographic latitude, positive north\n      REAL(KIND=HIGH) :: glond  !Geographic longitude, positive west\n      REAL(KIND=HIGH) :: col,d1,d2,d2r,dlm,dlm1,dlm2,dph,glat,glon,    &\n                         pi,r2d,row,tlat,tlat1,tlat2,              &\n                         tlon,tlon1,tlon2,tph0,tlm0,x,y,z\n\n      glatd = lat\n      glond = -lon\n\n      dphd = proj%phi/REAL((proj%jydim-1)/2)\n      dlmd = proj%lambda/REAL(proj%ixdim-1)\n\n      pi = ACOS(-1.0)\n      d2r = pi/180.\n      r2d = 1./d2r\n\n      imt = 2*proj%ixdim-1\n      jmt = proj%jydim/2+1\n\n      glat = glatd*d2r\n      glon = glond*d2r\n      dph = dphd*d2r\n      dlm = dlmd*d2r\n      tph0 = proj%lat1*d2r\n      tlm0 = -proj%lon1*d2r\n\n      x = COS(tph0)*COS(glat)*COS(glon-tlm0)+SIN(tph0)*SIN(glat)\n      y = -COS(glat)*SIN(glon-tlm0)\n      z = COS(tph0)*SIN(glat)-SIN(tph0)*COS(glat)*COS(glon-tlm0)\n      tlat = r2d*ATAN(z/SQRT(x*x+y*y))\n      tlon = r2d*ATAN(y/x)\n\n      row = tlat/dphd+jmt\n      col = tlon/dlmd+proj%ixdim\n\n      if ( (row - INT(row)) .gt. 0.999) then\n         row = row + 0.0002\n      else if ( (col - INT(col)) .gt. 0.999) then\n         col = col + 0.0002\n      end if\n\n      nrow = INT(row)\n      ncol = INT(col)\n\n!      nrow = NINT(row)\n!      ncol = NINT(col)\n\n      tlat = tlat*d2r\n      tlon = tlon*d2r\n\n\n      IF (proj%stagger == HH) THEN\n\n         IF (mod(nrow,2) .eq. 0) then\n            i_real = col / 2.0\n         ELSE\n            i_real = col / 2.0 + 0.5\n         ENDIF\n         j_real=row\n\n\n         IF ((abs(MOD(nrow,2)) == 1 .AND. abs(MOD(ncol,2)) == 1) .OR. &\n             (MOD(nrow,2) == 0 .AND. MOD(ncol,2) == 0)) THEN\n\n            tlat1 = (nrow-jmt)*dph\n            tlat2 = tlat1+dph\n            tlon1 = (ncol-proj%ixdim)*dlm\n            tlon2 = tlon1+dlm\n\n            dlm1 = tlon-tlon1\n            dlm2 = tlon-tlon2\n            d1 = ACOS(COS(tlat)*COS(tlat1)*COS(dlm1)+SIN(tlat)*SIN(tlat1))\n            d2 = ACOS(COS(tlat)*COS(tlat2)*COS(dlm2)+SIN(tlat)*SIN(tlat2))\n\n            IF (d1 > d2) THEN\n               nrow = nrow+1\n               ncol = ncol+1\n            END IF\n\n         ELSE\n            tlat1 = (nrow+1-jmt)*dph\n            tlat2 = tlat1-dph\n            tlon1 = (ncol-proj%ixdim)*dlm\n            tlon2 = tlon1+dlm\n            dlm1 = tlon-tlon1\n            dlm2 = tlon-tlon2\n            d1 = ACOS(COS(tlat)*COS(tlat1)*COS(dlm1)+SIN(tlat)*SIN(tlat1))\n            d2 = ACOS(COS(tlat)*COS(tlat2)*COS(dlm2)+SIN(tlat)*SIN(tlat2))\n\n            IF (d1 < d2) THEN\n               nrow = nrow+1\n            ELSE\n               ncol = ncol+1\n            END IF\n         END IF\n\n      ELSE IF (proj%stagger == VV) THEN\n\n         IF (mod(nrow,2) .eq. 0) then\n            i_real = col / 2.0 + 0.5\n         ELSE\n            i_real = col / 2.0\n         ENDIF\n         j_real=row\n\n         IF ((MOD(nrow,2) == 0 .AND. abs(MOD(ncol,2)) == 1) .OR. &\n             (abs(MOD(nrow,2)) == 1 .AND. MOD(ncol,2) == 0)) THEN\n            tlat1 = (nrow-jmt)*dph\n            tlat2 = tlat1+dph\n            tlon1 = (ncol-proj%ixdim)*dlm\n            tlon2 = tlon1+dlm\n            dlm1 = tlon-tlon1\n            dlm2 = tlon-tlon2\n            d1 = ACOS(COS(tlat)*COS(tlat1)*COS(dlm1)+SIN(tlat)*SIN(tlat1))\n            d2 = ACOS(COS(tlat)*COS(tlat2)*COS(dlm2)+SIN(tlat)*SIN(tlat2))\n\n            IF (d1 > d2) THEN\n               nrow = nrow+1\n               ncol = ncol+1\n            END IF\n\n         ELSE\n            tlat1 = (nrow+1-jmt)*dph\n            tlat2 = tlat1-dph\n            tlon1 = (ncol-proj%ixdim)*dlm\n            tlon2 = tlon1+dlm\n            dlm1 = tlon-tlon1\n            dlm2 = tlon-tlon2\n            d1 = ACOS(COS(tlat)*COS(tlat1)*COS(dlm1)+SIN(tlat)*SIN(tlat1))\n            d2 = ACOS(COS(tlat)*COS(tlat2)*COS(dlm2)+SIN(tlat)*SIN(tlat2))\n\n            IF (d1 < d2) THEN\n               nrow = nrow+1\n            ELSE\n               ncol = ncol+1\n            END IF\n         END IF\n      END IF\n\n\n!!! Added next line as a Kludge - not yet understood why needed\n      if (ncol .le. 0) ncol=ncol-1\n\n      jj = nrow\n      ii = ncol/2\n\n      IF (proj%stagger == HH) THEN\n         IF (abs(MOD(jj,2)) == 1) ii = ii+1\n      ELSE IF (proj%stagger == VV) THEN\n         IF (MOD(jj,2) == 0) ii=ii+1\n      END IF\n\n      i = REAL(ii)\n      j = REAL(jj)\n\n   END SUBROUTINE llij_rotlatlon\n\n\n   SUBROUTINE ijll_rotlatlon(i, j, proj, lat,lon)\n\n      IMPLICIT NONE\n\n      ! Arguments\n      REAL, INTENT(IN) :: i, j\n      REAL, INTENT(OUT) :: lat, lon\n      TYPE (proj_info), INTENT(IN) :: proj\n\n      ! Local variables\n      INTEGER :: ih,jh\n      INTEGER :: midcol,midrow,ncol,iadd1,iadd2,imt,jh2,knrow,krem,kv,nrow\n      REAL :: i_work, j_work\n      REAL :: dphd,dlmd !Grid increments, degrees\n      REAL(KIND=HIGH) :: arg1,arg2,d2r,fctr,glatr,glatd,glond,pi, &\n              r2d,tlatd,tlond,tlatr,tlonr,tlm0,tph0\n      REAL :: col\n\n      i_work = i\n      j_work = j\n\n      if ( (j - INT(j)) .gt. 0.999) then\n         j_work = j + 0.0002\n      endif\n\n      jh = INT(j_work)\n\n      dphd = proj%phi/REAL((proj%jydim-1)/2)\n      dlmd = proj%lambda/REAL(proj%ixdim-1)\n\n      pi = ACOS(-1.0)\n      d2r = pi/180.\n      r2d = 1./d2r\n      tph0 = proj%lat1*d2r\n      tlm0 = -proj%lon1*d2r\n\n      midrow = (proj%jydim+1)/2\n      midcol = proj%ixdim\n\n      col = 2*i_work-1+abs(MOD(jh+1,2))\n      tlatd = (j_work-midrow)*dphd\n      tlond = (col-midcol)*dlmd\n\n       IF (proj%stagger == VV) THEN\n          if (mod(jh,2) .eq. 0) then\n             tlond = tlond - DLMD\n          else\n             tlond = tlond + DLMD\n          end if\n       END IF\n\n      tlatr = tlatd*d2r\n      tlonr = tlond*d2r\n      arg1 = SIN(tlatr)*COS(tph0)+COS(tlatr)*SIN(tph0)*COS(tlonr)\n      glatr = ASIN(arg1)\n\n      glatd = glatr*r2d\n\n      arg2 = COS(tlatr)*COS(tlonr)/(COS(glatr)*COS(tph0))-TAN(glatr)*TAN(tph0)\n      IF (ABS(arg2) > 1.) arg2 = ABS(arg2)/arg2\n      fctr = 1.\n      IF (tlond > 0.) fctr = -1.\n\n      glond = tlm0*r2d+fctr*ACOS(arg2)*r2d\n\n      lat = glatd\n      lon = -glond\n\n      IF (lon .GT. +180.) lon = lon - 360.\n      IF (lon .LT. -180.) lon = lon + 360.\n\n   END SUBROUTINE ijll_rotlatlon\n\n\n   SUBROUTINE set_gauss(proj)\n\n      IMPLICIT NONE\n\n      ! Argument\n      type (proj_info), intent(inout) :: proj\n\n      !  Initialize the array that will hold the Gaussian latitudes.\n\n      IF ( ASSOCIATED( proj%gauss_lat ) ) THEN\n         DEALLOCATE ( proj%gauss_lat )\n      END IF\n\n      !  Get the needed space for our array.\n\n      ALLOCATE ( proj%gauss_lat(proj%nlat*2) )\n\n      !  Compute the Gaussian latitudes.\n\n      CALL gausll( proj%nlat*2 , proj%gauss_lat )\n\n      !  Now, these could be upside down from what we want, so let's check.\n      !  We take advantage of the equatorial symmetry to remove any sort of\n      !  array re-ordering.\n\n      IF ( ABS(proj%gauss_lat(1) - proj%lat1) .GT. 0.01 ) THEN\n         proj%gauss_lat = -1. * proj%gauss_lat\n      END IF\n\n      !  Just a sanity check.\n\n      IF ( ABS(proj%gauss_lat(1) - proj%lat1) .GT. 0.01 ) THEN\n         PRINT '(A)','Oops, something is not right with the Gaussian latitude computation.'\n         PRINT '(A,F8.3,A)','The input data gave the starting latitude as ',proj%lat1,'.'\n         PRINT '(A,F8.3,A)','This routine computed the starting latitude as +-',ABS(proj%gauss_lat(1)),'.'\n         PRINT '(A,F8.3,A)','The difference is larger than 0.01 degrees, which is not expected.'\n         STOP 'Gaussian_latitude_computation'\n      END IF\n\n   END SUBROUTINE set_gauss\n\n\n   SUBROUTINE gausll ( nlat , lat_sp )\n\n      IMPLICIT NONE\n\n      INTEGER                            :: nlat , i\n      REAL (KIND=HIGH) , PARAMETER       :: pi = 3.141592653589793\n      REAL (KIND=HIGH) , DIMENSION(nlat) :: cosc , gwt , sinc , colat , wos2 , lat\n      REAL             , DIMENSION(nlat) :: lat_sp\n\n      CALL lggaus(nlat, cosc, gwt, sinc, colat, wos2)\n\n      DO i = 1, nlat\n         lat(i) = ACOS(sinc(i)) * 180._HIGH / pi\n         IF (i.gt.nlat/2) lat(i) = -lat(i)\n      END DO\n\n      lat_sp = REAL(lat)\n\n   END SUBROUTINE gausll\n\n\n   SUBROUTINE lggaus( nlat, cosc, gwt, sinc, colat, wos2 )\n\n      IMPLICIT NONE\n\n      !  LGGAUS finds the Gaussian latitudes by finding the roots of the\n      !  ordinary Legendre polynomial of degree NLAT using Newton's\n      !  iteration method.\n\n      !  On entry:\n            integer NLAT ! the number of latitudes (degree of the polynomial)\n\n      !  On exit: for each Gaussian latitude\n      !     COSC   - cos(colatitude) or sin(latitude)\n      !     GWT    - the Gaussian weights\n      !     SINC   - sin(colatitude) or cos(latitude)\n      !     COLAT  - the colatitudes in radians\n      !     WOS2   - Gaussian weight over sin**2(colatitude)\n\n      REAL (KIND=HIGH) , DIMENSION(nlat) :: cosc , gwt , sinc , colat  , wos2 \n      REAL (KIND=HIGH) , PARAMETER       :: pi = 3.141592653589793\n\n      !  Convergence criterion for iteration of cos latitude\n\n      REAL , PARAMETER :: xlim  = 1.0E-14\n\n      INTEGER :: nzero, i, j\n      REAL (KIND=HIGH) :: fi, fi1, a, b, g, gm, gp, gt, delta, c, d\n\n      !  The number of zeros between pole and equator\n\n      nzero = nlat/2\n\n      !  Set first guess for cos(colat)\n\n      DO i=1,nzero\n         cosc(i) = SIN( (i-0.5)*pi/nlat + pi*0.5 )\n      END DO\n\n      !  Constants for determining the derivative of the polynomial\n      fi  = nlat\n      fi1 = fi+1.0\n      a   = fi*fi1 / SQRT(4.0*fi1*fi1-1.0)\n      b   = fi1*fi / SQRT(4.0*fi*fi-1.0)\n\n      !  Loop over latitudes, iterating the search for each root\n\n      DO i=1,nzero\n         j=0\n\n         !  Determine the value of the ordinary Legendre polynomial for\n         !  the current guess root\n\n         DO\n            CALL lgord( g, cosc(i), nlat )\n\n            !  Determine the derivative of the polynomial at this point\n\n            CALL lgord( gm, cosc(i), nlat-1 )\n            CALL lgord( gp, cosc(i), nlat+1 )\n            gt = (cosc(i)*cosc(i)-1.0) / (a*gp-b*gm)\n\n            !  Update the estimate of the root\n\n            delta   = g*gt\n            cosc(i) = cosc(i) - delta\n\n            !  If convergence criterion has not been met, keep trying\n\n            j = j+1\n            IF( ABS(delta).GT.xlim ) CYCLE\n\n            !  Determine the Gaussian weights\n\n            c      = 2.0 *( 1.0-cosc(i)*cosc(i) )\n            CALL lgord( d, cosc(i), nlat-1 )\n            d      = d*d*fi*fi\n            gwt(i) = c *( fi-0.5 ) / d\n            EXIT\n\n         END DO\n\n      END DO\n\n      !  Determine the colatitudes and sin(colat) and weights over sin**2\n\n      DO i=1,nzero\n         colat(i)= ACOS(cosc(i))\n         sinc(i) = SIN(colat(i))\n         wos2(i) = gwt(i) /( sinc(i)*sinc(i) )\n      END DO\n\n      !  If NLAT is odd, set values at the equator\n\n      IF( MOD(nlat,2) .NE. 0 ) THEN\n         i       = nzero+1\n         cosc(i) = 0.0\n         c       = 2.0\n         CALL lgord( d, cosc(i), nlat-1 )\n         d       = d*d*fi*fi\n         gwt(i)  = c *( fi-0.5 ) / d\n         colat(i)= pi*0.5\n         sinc(i) = 1.0\n         wos2(i) = gwt(i)\n      END IF\n\n      !  Determine the southern hemisphere values by symmetry\n\n      DO i=nlat-nzero+1,nlat\n         cosc(i) =-cosc(nlat+1-i)\n         gwt(i)  = gwt(nlat+1-i)\n         colat(i)= pi-colat(nlat+1-i)\n         sinc(i) = sinc(nlat+1-i)\n         wos2(i) = wos2(nlat+1-i)\n      END DO\n\n   END SUBROUTINE lggaus\n\n\n   SUBROUTINE lgord( f, cosc, n )\n\n      IMPLICIT NONE\n\n      !  LGORD calculates the value of an ordinary Legendre polynomial at a\n      !  specific latitude.\n\n      !  On entry:\n      !     cosc - COS(colatitude)\n      !     n      - the degree of the polynomial\n\n      !  On exit:\n      !     f      - the value of the Legendre polynomial of degree N at\n      !              latitude ASIN(cosc)\n\n      REAL (KIND=HIGH) :: s1, c4, a, b, fk, f, cosc, colat, c1, fn, ang\n      INTEGER :: n, k\n\n      !  Determine the colatitude\n\n      colat = ACOS(cosc)\n\n      c1 = SQRT(2.0_HIGH)\n      DO k=1,n\n         c1 = c1 * SQRT( 1.0 - 1.0/(4*k*k) )\n      END DO\n\n      fn = n\n      ang= fn * colat\n      s1 = 0.0\n      c4 = 1.0\n      a  =-1.0\n      b  = 0.0\n      DO k=0,n,2\n         IF (k.eq.n) c4 = 0.5 * c4\n         s1 = s1 + c4 * COS(ang)\n         a  = a + 2.0\n         b  = b + 1.0\n         fk = k\n         ang= colat * (fn-fk-2.0)\n         c4 = ( a * (fn-b+1.0) / ( b * (fn+fn-a) ) ) * c4\n      END DO\n\n      f = s1 * c1\n\n   END SUBROUTINE lgord\n\n\n   SUBROUTINE llij_gauss (lat, lon, proj, i, j)\n\n      IMPLICIT NONE\n\n      REAL    , INTENT(IN)  :: lat, lon\n      REAL    , INTENT(OUT) :: i, j\n      TYPE (proj_info), INTENT(IN) :: proj\n\n      INTEGER :: n , n_low\n      LOGICAL :: found = .FALSE.\n      REAL    :: diff_1 , diff_nlat\n\n      !  The easy one first, get the x location.  The calling routine has already made\n      !  sure that the necessary assumptions concerning the sign of the deltalon and the\n      !  relative east/west'ness of the longitude and the starting longitude are consistent\n      !  to allow this easy computation.\n\n      i = ( lon - proj%lon1 ) / proj%loninc + 1.\n\n      !  Since this is a global data set, we need to be concerned about wrapping the\n      !  fields around the globe.\n\n!      IF      ( ( proj%loninc .GT. 0 ) .AND. &\n!                ( FLOOR((lon-proj%lon1)/proj%loninc) + 1 .GE. proj%ixdim ) .AND. &\n!                ( lon + proj%loninc .GE. proj%lon1 + 360 ) ) THEN\n!! BUG: We may need to set proj%wrap, but proj is intent(in)\n!! WHAT IS THIS USED FOR?\n!!        proj%wrap = .TRUE.\n!         i = proj%ixdim\n!      ELSE IF ( ( proj%loninc .LT. 0 ) .AND. &\n!                ( FLOOR((lon-proj%lon1)/proj%loninc) + 1 .GE. proj%ixdim ) .AND. &\n!                ( lon + proj%loninc .LE. proj%lon1 - 360 ) ) THEN\n! ! BUG: We may need to set proj%wrap, but proj is intent(in)\n! ! WHAT IS THIS USED FOR?\n! !        proj%wrap = .TRUE.\n!         i = proj%ixdim\n!      END IF\n\n      !  Yet another quicky test, can we find bounding values?  If not, then we may be\n      !  dealing with putting data to a polar projection, so just give them them maximal\n      !  value for the location.  This is an OK assumption for the interpolation across the\n      !  top of the pole, given how close the longitude lines are.\n\n      IF ( ABS(lat) .GT. ABS(proj%gauss_lat(1)) ) THEN\n\n         diff_1    = lat - proj%gauss_lat(1)\n         diff_nlat = lat - proj%gauss_lat(proj%nlat*2)\n\n         IF ( ABS(diff_1) .LT. ABS(diff_nlat) ) THEN\n            j = 1\n         ELSE\n            j = proj%nlat*2\n         END IF\n\n      !  If the latitude is between the two bounding values, we have to search and interpolate.\n\n      ELSE\n\n         DO n = 1 , proj%nlat*2 -1\n            IF ( ( proj%gauss_lat(n) - lat ) * ( proj%gauss_lat(n+1) - lat ) .LE. 0 ) THEN\n               found = .TRUE.\n               n_low = n\n               EXIT\n            END IF\n         END DO\n\n         !  Everything still OK?\n\n         IF ( .NOT. found ) THEN\n            PRINT '(A)','Troubles in river city.  No bounding values of latitude found in the Gaussian routines.'\n            STOP 'Gee_no_bounding_lats_Gaussian'\n         END IF\n\n         j = ( ( proj%gauss_lat(n_low) - lat                     ) * ( n_low + 1 ) + &\n               ( lat                   - proj%gauss_lat(n_low+1) ) * ( n_low     ) ) / &\n               ( proj%gauss_lat(n_low) - proj%gauss_lat(n_low+1) )\n\n      END IF\n\n   END SUBROUTINE llij_gauss\n\nEND MODULE module_llxy\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_mapinfo.F",
    "content": "module module_mapinfo\n\n  implicit none\n\n  type MapInfoStruct\n     character(len=2) :: hproj         ! Two-character abbreviation identifying map projection\n     integer          :: supmap_jproj  ! Integer as used in NCAR-Graphics subroutine SUPMAP to identify map projection\n     integer          :: nx\n     integer          :: ny\n     real             :: dx            ! Grid spacing in km or degrees as appropriate\n     real             :: dy            ! Grid spacing in km or degrees as appropriate\n     real             :: lat1          ! We need to make this a reference latitude?\n     real             :: lon1          ! We need to make this a reference longitude?\n     real             :: lat2          ! For Cylindrical Equidistant grids\n     real             :: lon2          ! For Cylindrical Equidistant grids\n     real             :: xlonc\n     real             :: truelat1\n     real             :: truelat2\n  end type MapInfoStruct\n\ncontains\n  subroutine print_mapinfo(mapinfo)\n    implicit none\n    type (MapInfoStruct), intent(in) ::  mapinfo\n    write(*,'(\"MAPINFO:  \")')\n    write(*,'(4x, \"       HPROJ = \", A2)') mapinfo%hproj\n    write(*,'(4x, \"SUPMAP_JPROJ = \", I2)') mapinfo%supmap_jproj\n    write(*,'(4x, \"          NX = \", I6)') mapinfo%nx\n    write(*,'(4x, \"          NY = \", I6)') mapinfo%ny\n    write(*,'(4x, \"          DX = \", F12.4)') mapinfo%dx\n    write(*,'(4x, \"          DY = \", F12.4)') mapinfo%dy\n    write(*,'(4x, \"        LAT1 = \", F12.4)') mapinfo%lat1\n    write(*,'(4x, \"        LON1 = \", F12.4)') mapinfo%lon1\n    if ( mapinfo%lat2 > -1.E25)     write(*,'(4x, \"        LAT2 = \", F12.4)') mapinfo%lat2\n    if ( mapinfo%lon2 > -1.E25)     write(*,'(4x, \"        LON2 = \", F12.4)') mapinfo%lon2\n    if ( mapinfo%xlonc > -1.E25)    write(*,'(4x, \"       XLONC = \", F12.4)') mapinfo%xlonc\n    if ( mapinfo%truelat1 > -1.E25) write(*,'(4x, \"    TRUELAT1 = \", F12.4)') mapinfo%truelat1\n    if ( mapinfo%truelat2 > -1.E25) write(*,'(4x, \"    TRUELAT2 = \", F12.4)') mapinfo%truelat2\n  end subroutine print_mapinfo\n\nend module module_mapinfo\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/module_wrfinputfile.F",
    "content": "module module_wrfinputfile\n  use netcdf\n  use module_llxy\n  implicit none\n  ! Define a data structure for wrfinput file\n\n  type wrfinput_type\n     type(proj_info) :: proj\n     integer :: grid_id\n     integer :: idim\n     integer :: jdim\n\n     character(len=256) :: landuse_dataset  ! \"MODIFIED_IGBP_MODIS_NOAH\" or \"USGS\"\n     integer :: iswater\n     !\n     ! Some 2d arrays of grid/geographical information:\n     !\n     real, pointer, dimension(:,:)   :: lat    ! Grid point latitudes\n     real, pointer, dimension(:,:)   :: lon    ! Grid point longitudes\n     real, pointer, dimension(:,:)   :: ter    ! Terrain field\n     real, pointer, dimension(:,:)   :: use    ! Land-use (vegetation) field\n!KWM     real, pointer, dimension(:,:)   :: tmn    ! Deep-soil temperature field\n     real, pointer, dimension(:,:,:) :: veg    ! 12-month Green Vegetation Fraction climatology\n  end type wrfinput_type\n\ncontains\n\n  subroutine read_wrfinput_file(flnm, wrfinput, ierr)\n    !\n    ! Reads the wrfinput file identified by <flnm>, and fills out\n    ! the <wrfinput> structure with the appropriate values.\n    !\n    implicit none\n\n    character(len=*),     intent(in)  :: flnm\n    type (wrfinput_type), intent(out) :: wrfinput\n    integer, intent(out)              :: ierr\n    ! Local:\n    integer                           :: ncid\n    integer                           :: iret\n    integer                           :: dimid\n    integer                           :: map_proj\n    real                              :: truelat1\n    real                              :: truelat2\n    real                              :: stdlon\n    real                              :: dx\n    real                              :: latinc\n    real                              :: loninc\n    real                              :: la1\n    real                              :: lo1\n    real                              :: pole_lat\n    real                              :: pole_lon\n\n! Open the NetCDF file.\n    iret = nf90_open(flnm, NF90_NOWRITE, ncid)\n    call error_handler(iret, \"Problem with wrfinput file: \"//flnm)\n\n! Find out about dimensions in the file.\n\n    iret = nf90_inq_dimid(ncid, \"west_east\", dimid)\n    call error_handler(iret, \"STOP:  Problem finding west_east dimension\")\n    iret = nf90_inquire_dimension(ncid, dimid, len=wrfinput%idim)\n    call error_handler(iret, \"STOP:  Problem finding west_east dimension\")\n\n    iret = nf90_inq_dimid(ncid, \"south_north\", dimid)\n    call error_handler(iret, \"STOP:  Problem finding south_north dimension\")\n    iret = nf90_inquire_dimension(ncid, dimid, len=wrfinput%jdim)\n    call error_handler(iret, \"STOP:  Problem finding south_north dimension\")\n\n    ! Grid id.  Check for the string \"GRID_ID\" or the string \"grid_id\"\n    iret = nf90_get_att(ncid, NF90_GLOBAL,\"GRID_ID\", wrfinput%grid_id)\n    if (iret /= 0) then\n       iret = nf90_get_att(ncid, NF90_GLOBAL,\"grid_id\", wrfinput%grid_id)\n       call error_handler(iret, \"STOP:  nf90_get_att:  'grid_id' or 'GRID_ID' not found.\")\n    endif\n\n    ! Get Latitude\n    allocate(wrfinput%lat(wrfinput%idim, wrfinput%jdim))\n    call get_2d(\"XLAT\", ncid, wrfinput%lat, wrfinput%idim, wrfinput%jdim)\n    la1 = wrfinput%lat(1,1)\n\n    ! Get Longitude\n    allocate(wrfinput%lon(wrfinput%idim, wrfinput%jdim))\n    call get_2d(\"XLONG\", ncid, wrfinput%lon, wrfinput%idim, wrfinput%jdim)\n    lo1 = wrfinput%lon(1,1)\n\n    ! Get Terrain\n    allocate(wrfinput%ter(wrfinput%idim, wrfinput%jdim))\n    call get_2d(\"HGT\", ncid, wrfinput%ter, wrfinput%idim, wrfinput%jdim)\n\n    ! Get Land Use categories\n    allocate(wrfinput%use(wrfinput%idim, wrfinput%jdim))\n    call get_2d(\"IVGTYP\", ncid, wrfinput%use, wrfinput%idim, wrfinput%jdim)\n\n!KWM  ! Get deep soil Temperature field\n!KWM  allocate(wrfinput%tmn(wrfinput%idim, wrfinput%jdim))\n!KWM  call get_2d(\"TMN\", ncid, wrfinput%tmn, wrfinput%idim, wrfinput%jdim)\n\n    ! Projection information:\n\n    call map_init(wrfinput%proj)\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL,\"MAP_PROJ\", map_proj)\n    call error_handler(iret, \"STOP:  nf90_get_att:  map projection problem\")\n\n    if (map_proj == PROJ_LC) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\" , truelat2)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT2\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_LC, wrfinput%proj, lat1=la1, lon1=lo1, knowni=1.0, knownj=1.0, &\n            truelat1=truelat1, truelat2=truelat2, stdlon=stdlon, dx=dx)\n\n    else if (map_proj == PROJ_PS) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_PS, wrfinput%proj, lat1=la1, lon1=lo1, truelat1=truelat1, &\n            knowni=1.0, knownj=1.0, stdlon=stdlon, dx=dx)\n\n    else if (map_proj == PROJ_MERC) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\" , truelat1)\n       call error_handler(iret, \"STOP:  nf90_get_att:  TRUELAT1\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       call map_set(PROJ_MERC, wrfinput%proj, lat1=la1, lon1=lo1, knowni=1.0, knownj=1.0, &\n            truelat1=truelat1, dx=dx)\n\n    else if (map_proj == PROJ_CASSINI) then\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"POLE_LAT\" , pole_lat)\n       call error_handler(iret, \"STOP:  nf90_get_att:  POLE_LAT\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"POLE_LON\" , pole_lon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  POLE_LON\")\n\n       iret = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", stdlon)\n       call error_handler(iret, \"STOP:  nf90_get_att:  STAND_LON\")\n\n       ! For Cassini projection, module_llxy assumes a spherical earth\n       ! with circumference EARTH_CIRC_M\n       latinc = 360.0*dx/EARTH_CIRC_M\n       loninc = 360.0*dx/EARTH_CIRC_M\n\n       call map_set(PROJ_CASSINI, wrfinput%proj, lat1=la1, lon1=lo1, latinc=latinc, loninc=loninc, &\n            knowni=1.0, knownj=1.0, lat0=pole_lat, lon0=pole_lon, stdlon=stdlon)\n\n    else if (map_proj == PROJ_LATLON) then\n       stop \"FATAL ERROR: In module_wrfinputfile.F -- PROJ_LATLON is not a valid map projection for WRF.\"\n\n       ! iret = nf90_get_att(ncid, NF90_GLOBAL, \"DX\" , dx)\n       ! call error_handler(iret, \"STOP:  nf90_get_att:  DX\")\n\n       ! For lat/lon projection, module_llxy assumes a spherical earth\n       ! with circumference EARTH_CIRC_M\n       ! latinc = 360.0*dx/EARTH_CIRC_M\n       ! loninc = 360.0*dx/EARTH_CIRC_M\n\n       ! call map_set(PROJ_LATLON, wrfinput%proj, lat1=la1, lon1=lo1, &\n       !      latinc=latinc, loninc=loninc, knowni=1.0, knownj=1.0)\n\n    else if (map_proj == PROJ_PS_WGS84) then\n       stop \"FATAL ERROR: In module_wrfinputfile.F -- PROJ_PS_WGS84 is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_PS_WGS84, wrfinput%proj, lat1=wrfinput%la1, lon1=wrfinput%lo1, knowni=1.0, knownj=1.0, &\n       !     stdlon=wrfinput%lov, dx=wrfinput%dx)\n    else if (map_proj == PROJ_GAUSS) then\n       stop \"FATAL ERROR: In module_wrfinputfile.F -- PROJ_GAUSS is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_GAUSS, wrfinput%proj, lat1=, lon1=, nlat=, loninc=)\n    else if (map_proj == PROJ_CYL) then\n       stop \"FATAL ERROR: In module_wrfinputfile.F -- PROJ_CYL is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_CYL, wrfinput%proj, latinc=, loninc=, stdlon=)\n    else if (map_proj == PROJ_ALBERS_NAD83) then\n       stop \"FATAL ERROR: In module_wrfinputfile.F -- PROJ_ALBERS_NAD83 is not a valid map projection for WRF.\"\n       !call map_set(PROJ_ALBERS_NAD83, wrfinput%proj, lat1=, lon1=, knowni=, knownj=, truelat1=, truelat2=, stdlon=, dx=)\n    else if (map_proj == PROJ_ROTLL) then\n       stop \"FATAL ERROR: In module_wrfinputfile.F -- PROJ_ROTLL is not a valid map projection for WRF.\"\n       ! call map_set(PROJ_ROTLL, wrfinput%proj, lat1=wrfinput%lat1, lon1=wrfinput%lon1, ixdim=, jydim=, phi=, lambda=)\n    else\n       write(*,'(\"WARNING: In module_wrfinputfile.F -- Unknown wrfinput map projection:  map_proj = \", I10)') map_proj\n       stop \"FATAL ERROR: In module_wrfinputfile.F -- Unknown wrfinput map projection\"\n    endif\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"ISWATER\" , wrfinput%iswater)\n    call error_handler(iret, \"STOP:  nf90_get_att:  ISWATER\")\n\n    iret = nf90_get_att(ncid, NF90_GLOBAL, \"MMINLU\" , wrfinput%landuse_dataset)\n    call error_handler(iret, \"STOP:  nf90_get_att:  MMINLU\")\n\n    ! Close the file and get out of here\n\n    iret = nf90_close(ncid)\n    call error_handler(iret, \"STOP:  Problem closing file??\")\n\n    ierr = 0\n    print*, \"Done with subroutine read_wrfinput_file\"\n\n  end subroutine read_wrfinput_file\n\n  subroutine get_2d(name, ncid, array, idim, jdim)\n    !\n    ! From the NetCDF unit <ncid>, read the variable named <name> with\n    ! dimensions <idim> and <jdim>, filling the pre-dimensioned array <array>\n    !\n    implicit none\n    character(len=*),           intent(in)  :: name\n    integer,                    intent(in)  :: ncid\n    integer,                    intent(in)  :: idim\n    integer,                    intent(in)  :: jdim\n    real, dimension(idim,jdim), intent(out) :: array\n    ! Local:\n    integer                                 :: ierr\n    integer                                 :: varid\n\n    ierr = nf90_inq_varid(ncid,  name,  varid)\n    ! If the variable is \"XLAT\", and \"XLAT\" is not found, look for \"XLAT_M\"\n    ! If the variable is \"XLAT_M\", and \"XLAT_M\" is not found, look for \"XLAT\"\n    ! If the variable is \"XLONG\", and \"XLONG\" is not found, look for \"XLONG_M\"\n    ! If the variable is \"XLONG_M\", and \"XLONG_M\" is not found, look for \"XLONG\"\n    if (name == \"XLAT\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLAT_M\",  varid)\n       endif\n    else if (name == \"XLAT_M\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLAT\",  varid)\n       endif\n    else  if (name == \"XLONG\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLONG_M\",  varid)\n       endif\n    else if (name == \"XLONG_M\") then\n       if (ierr /= 0) then\n          ierr = nf90_inq_varid(ncid,  \"XLONG\",  varid)\n       endif\n    endif\n    call error_handler(ierr, \"STOP:  READ_WRFINPUT: Problem finding variable '\"//trim(name)//\"' in wrfinput file.\")\n\n\n    ierr = nf90_get_var(ncid, varid, array)\n    call error_handler(ierr, \"STOP:  READ_WRFINPUT:  Problem retrieving variable '\"//trim(name)//\"' from wrfinput file.\")\n\n  end subroutine get_2d\n\n\n  subroutine error_handler(status, failure, success)\n    !\n    ! Check the error flag from a NetCDF function call, and print appropriate\n    ! error message.\n    !\n    implicit none\n    integer,                    intent(in) :: status\n    character(len=*), optional, intent(in) :: failure\n    character(len=*), optional, intent(in) :: success\n\n    if (status .ne. NF90_NOERR) then\n       if (present(failure)) then\n          write(*,'(/,\" ***** \", A)') failure\n       endif\n       write(*,'(\" ***** \",A,/)') nf90_strerror(status)\n       stop 'FATAL ERROR: In module_wrfinputfile.F -- Stopped'\n    endif\n\n    if (present(success)) then\n       write(*,'(A)') success\n    endif\n\n  end subroutine error_handler\n\n\nend module module_wrfinputfile\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/swap4c.c",
    "content": "/*\n  Program Name:\n  Author(s)/Contact(s):\n  Abstract:\n  History Log:\n \n  Usage:\n  Parameters: <Specify typical arguments passed>\n  Input Files:\n        <list file names and briefly describe the data they include>\n  Output Files:\n        <list file names and briefly describe the information they include>\n \n  Condition codes:\n        <list exit condition or error codes returned >\n        If appropriate, descriptive troubleshooting instructions or\n        likely causes for failures could be mentioned here with the\n        appropriate error code\n \n  User controllable options: <if applicable>\n*/\n\nvoid swap4c(char i[], int n) {\n  int j;\n  int m;\n  char hold;\n\n  for (m=0; m<n; m+=4){\n    hold =i[m+0];\n    i[m+0]=i[m+3];\n    i[m+3]=hold;\n\n    hold =i[m+1];\n    i[m+1]=i[m+2];\n    i[m+2]=hold;\n    \n  }\n}\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/swap4f.F",
    "content": "subroutine swap4f(in,nn)\n#if defined (__alpha) || defined (__linux) || defined (__G95__)\n! swaps bytes in groups of 4 to compensate for byte swapping within\n!    words which occurs on DEC machines.\n  implicit none\n  integer, intent(in) :: nn ! number of bytes to be swapped\n  logical*1 , dimension(nn) , intent(inout) :: in  ! Array to be swapped\n#if defined (BIT32)\n  integer, parameter :: nbytes=4\n#elif defined (BIT64)\n  integer, parameter :: nbytes=8\n#else\n  \"Please use the CPP option -BIT32 or -BIT64\"\n#endif\n\n  logical*1, dimension(nbytes) :: ia\n  integer :: i\n  do i=1,nn,nbytes\n     ia = in(i+(nbytes-1):i:-1)\n     in(i:i+(nbytes-1)) = ia\n  enddo\n\n#endif\nend\n!KWM -------------------------------------------------------------------------\n!KWM -------------------------------------------------------------------------\n!KWM -------------------------------------------------------------------------\n!KWM\n!KWM    Here are the original swap routines.  I use only SWAP4.  I modified\n!KWM    SWAP4 to use the same array on input and output, rather than make a\n!KWM    new output array IO.  I keep these around just for reference.\n!KWM\n!KWM -------------------------------------------------------------------------\n!KWM -------------------------------------------------------------------------\n!KWM -------------------------------------------------------------------------\n!KWM\n!KWM\tsubroutine swap4(in,io,nn)\n!KWM#if defined (DEC) || defined (ALPHA)\n!KWM! swaps bytes in groups of 4 to compensate for byte swapping within\n!KWM!    words which occurs on DEC (VAX) and PC machines.\n!KWM!\n!KWM! in - input array to be swapped\n!KWM! io - ouput array with bytes swapped\n!KWM! nn - number of bytes to be swapped\n!KWM\tlogical*1   in(1),io(1),ih\n!KWM!       character*1 in(1),io(1),ih             ! Cray CF90 (Version 3.0.1.3)\n!KWM!          Use character*1 instead of logical*1 when compling on a Cray\n!KWM\tdo 10 i=1,nn,4\n!KWM\tih=in(i)\n!KWM\tio(i)=in(i+3)\n!KWM\tio(i+3)=ih\n!KWM\tih=in(i+1)\n!KWM\tio(i+1)=in(i+2)\n!KWM\tio(i+2)=ih\n!KWM   10\tcontinue\n!KWM\treturn\n!KWM#endif\n!KWM\tend\n!KWM\tsubroutine swap2(in,io,nn)\n!KWM#if defined (DEC) || defined (ALPHA)\n!KWM! swaps bytes in groups of 2 to compensate for byte swapping within\n!KWM!    words which occurs on DEC (VAX) and PC machines.\n!KWM!\n!KWM! in - input array to be swapped\n!KWM! io - ouput array with bytes swapped\n!KWM! nn - number of bytes to be swapped\n!KWM\tlogical*1   in(1),io(1),ih\n!KWM!       character*1 in(1),io(1),ih             ! Cray CF90 (Version 3.0.1.3)\n!KWM!          Use character*1 instead of logical*1 when compling on a Cray\n!KWM\tdo 10 i=1,nn,2\n!KWM\tih=in(i)\n!KWM\tio(i)=in(i+1)\n!KWM\tio(i+1)=ih\n!KWM   10\tcontinue\n!KWM\treturn\n!KWM#endif\n!KWM\tend\n!KWM\n!KWM\tsubroutine filt(m,n,in)\n!KWM#if defined (DEC) || defined (ALPHA)\n!KWM\tlogical*1 m(1),n(1),l,u\n!KWM\tdata l/32/,u/127/\n!KWM\tdo 10 i=1,in\n!KWM\tn(i)=m(i)\n!KWM\tif(n(i).lt.  l) n(i)=l\n!KWM\tif(n(i).gt.  u) n(i)=u\n!KWM   10\tcontinue\n!KWM\treturn\n!KWM#endif\n!KWM\tend\n!KWM Emacs Local Variables: ***\n!KWM Emacs mode: f90        ***\n!KWM Emacs End:             ***\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/lib/trig_degrees.F",
    "content": "!\n! Trigonometric functions which deal with degrees, rather than radians:\n!\n\nreal function sind(theta)\n  implicit none\n  real, intent(in) :: theta\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: degran = pi/180.\n  sind = sin(theta*degran)\nend function sind\n\nreal function cosd(theta)\n  implicit none\n  real, intent(in) :: theta\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: degran = pi/180.\n  cosd = cos(theta*degran)\nend function cosd\n\nreal function tand(theta)\n  implicit none\n  real, intent(in) :: theta\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: degran = pi/180.\n  tand = tan(theta*degran)\nend function tand\n\nreal function atand(x)\n  implicit none\n  real, intent(in) :: x\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: raddeg = 180./pi\n  atand = atan(x)*raddeg\nend function atand\n\nreal function atan2d(x,y)\n  implicit none\n  real, intent(in) :: x,y\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: raddeg = 180./pi\n  atan2d = atan2(x,y)*raddeg\nend function atan2d\n\nreal function asind(x)\n  implicit none\n  real, intent(in) :: x\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: raddeg = pi/180.\n  asind = asin(x)*raddeg\nend function asind\n\nreal function acosd(x)\n  implicit none\n  real, intent(in) :: x\n  real, parameter :: pi = 3.141592653589\n  real, parameter :: raddeg = pi/180.\n  acosd = acos(x)*raddeg\nend function acosd\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/Makefile",
    "content": "all:\n\t( cd ..; make )\n\nclean:\n\t( cd ..; make clean )\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/README.namelist",
    "content": "Some brief notes on the namelist.input file.  For full details (e.g.,\nfile name template replacement strings, file formats, etc.) see the\nUsers' Guide (HRLDAS_USERS_GUIDE.PDF).\n\nSTARTDATE\n\n    The starting date (GMT) for your HRLDAS integration, expressed as\n    a character string in the form \"YYYY-MM-DD_HH\".  You should probably\n    start on a 00 GMT hour.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  STARTDATE = \"2001-01-01_00\"\n\nENDDATE\n\n    The ending date (GMT) for your HRLDAS integration, expressed as\n    a character string in the form \"YYYY-MM-DD_HH\".\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  ENDDATE = \"2002-07-01_00\"\n\nDATADIR\n\n    A top-level directory under which the original GRIB datasets are\n    organized.  The string defined here may be used in building file\n    names from the templates defined below.  Where the file name\n    templates include the string \"<DataDir>\", that string will be\n    replace by the value set for namelist variable DATADIR.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  DATADIR = \"/data1/user2/datasets\"\n\nOUTPUTDIR\n\n    A top-level directory under which the forcing files will be stored.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  DATADIR = \"/data1/user2/ldasin\"\n\nRAINFALL_INTERP\n\n    Specifies the option for remapping the precipitation field from\n    the source map to the HRLDAS map.  Options are:\n\n       0: Assign precipitation values on the HRLDAS map from the\n          nearest neighbor on the source map.\n       1: Subdivide the source grid cell into some number of smaller\n          cells, and allocate precipitation from the source grid to\n          the destination grid based on accumulating values from the\n          subcells which fall into the destination grid cell.\n\n    Option 0 may be appropriate, and may save much processing time,\n    for situations in which the HRLDAS grid cells are somewhat smaller\n    than the source grid cells.\n\n    Type:     integer\n    Default:  1 (expensive remapping by subdivision)\n    Example:  RAINFALL_INTERP = 1\n\nFULL_IC_FRQ\n\n    Specifies the interval (in hours) to create full initial\n    conditions for HRLDAS input files.  Special value of -1 means to never\n    create full initial conditions. Option -1 is useful for extending existing\n    forcing datasets that don't need initialization.\n\n    Type:     integer\n    Default:  0 (to create full initial conditions at the starting time only)\n    Example:  FULL_IC_FRQ = 24\n\nRESCALE_SHORTWAVE\n\n    Specifies whether the program will attempt to correct a half-hour time offset\n    that has been noted in the GCIP shortwave radiation analyses.  Set this to \n    .FALSE. if the time offset does not exist, or if you are using a different\n    source of shortwave radiation analyses.\n\n    Type:     logical\n    Default:  .FALSE. (do not apply offset)\n    Example:  RESCALE_SHORTWAVE = .FALSE. \n\nUPDATE_SNOW\n\n    Specifies whether the program will replace snow at 00Z of every day. If set to\n    .TRUE. an input dataset must be provided at 00Z of each day. If set to .FALSE. \n    snow in only an initialized field. \n    \n    Type:     logical\n    Default:  .FALSE. \n    Example:  UPDATE_SNOW = .FALSE. \n\nFORCING_HEIGHT_2D\n\n    Used when one has time-varying 2D fields of forcing height, e.g., dynamic model-level forcing.\n\n    Type:     logical\n    Default:  .FALSE. \n    Example:  FORCING_HEIGHT_2D = .FALSE. \n\nTRUNCATE_SW \n\n    Used when one is concerned about the temporal consistency of shortwave forcing, \n    e.g., potentially with GOES solar forcing. Calculates the cosine of zenith angle\n    and sets shortwave forcing to zero if cos(Z) < 0.\n\n    Type:     logical\n    Default:  .FALSE. \n    Example:  TRUNCATE_SW = .FALSE. \n\nEXPAND_LOOP\n \n    Used to expand the input data to fill in missing values. This is useful primarily near coastlines.\n    Set EXPAND_LOOP to determine the number of 9pt expansions are done. Only missing data are filled.\n    For example, some input data sets soil temperature or moisture to missing over ocean. Expanding\n    will use the coastline values to extrapolate. Additionally, if your domain has islands that are \n    unresolved by the input data, you may need to expand many loops to fill all land. The number of \n    loops needed generally depends on the spatial resolution of both the input data and WRF grid.\n\n    Type:     integer\n    Default:  1 \n    Example:  EXPAND_LOOP = 1 (For input data like NARR, this is usually sufficient unless there\n                               are isolated islands)\n\nGEO_EM_FLNM\n\n    Specifies the full path name to the file defining the setup of the\n    HRLDAS grid.  This will be a \"geo_em_d##.nc\" file as created by\n    the WPS program geogrid. Enterprising users might create their own \n    substitute files.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  GEO_EM_FLNM = \"/data1/user2/grids/geo_em.d01.nc\"\n\nWRFINPUT_FLNM\n\n    Specifies the full path name to a wrfinput file created as in\n    preparation for running the WRF model.  Enterprising users might\n    create their own substitute files.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  WRFINPUT_FLNM = \"/data1/user2/grids/wrfinput_d01\"\n\nZFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the model elevation field associated with the\n    source temperature data.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  ZFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/SFC_ELEVATION.GRIB\"\n\nTFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the near-surface air temperature field.  Multiple\n    templates may be defined; the file that gets used will be from the\n    first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  TFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/T.<date>\"\n\nUFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the near-surface u-component of the horizontal\n    wind field.  Multiple templates may be defined; the file that gets\n    used will be from the first template which resolves to an existing\n    filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  UFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/U.<date>\",\n\nVFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the near-surface v-component of the horizontal\n    wind field.  Multiple templates may be defined; the file that gets\n    used will be from the first template which resolves to an existing\n    filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  VFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/V.<date>\",\n\nPFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the surface pressure field.  Multiple\n    templates may be defined; the file that gets used will be from the\n    first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  PFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/PSFC.<date>\",\n\nQFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the near-surface specific humidity field.\n    Multiple templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  QFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/Q.<date>\",\n\nLWFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the downwelling long-wave radiation field.\n    Multiple templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  LWFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/LW.<date>\",\n\nSWFILE_PRIMARY\n\n    A file name template for building the full path name of the GRIB\n    file which contains the downwelling short-wave radiation field that\n    the user prefers to use.  Multiple templates may be defined; the\n    file that gets used will be from the first template which resolves\n    to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  SWFILE_PRIMARY = \"<DataDir>/<YYYY>/<MM>/<DD>/SW_analysis.<date>\",\n\nSWFILE_SECONDARY\n\n    A file name template for building the full path name of the GRIB \n    file which contains the downwelling short-wave radiation field\n    that will be used to fill in missing values from the file specified\n    by SWFILE_PRIMARY.  Multiple templates may be defined; the file\n    that gets used will be from the first template which resolves to\n    an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  SWFILE_SECONDARY = \"<DataDir>/<YYYY>/<MM>/<DD>/SW_forecast.<date>\",\n\nPCPFILE_PRIMARY\n\n    A file name template for building the full path name of the GRIB\n    file which contains the precipitation field that the user prefers\n    to use.  Multiple templates may be defined; the file that gets\n    used will be from the first template which resolves to an existing\n    filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  PCPFILE_PRIMARY = \"<DataDir>/<YYYY>/<MM>/<DD>/PCP_analysis.<date>\",\n\nPCPFILE_SECONDARY\n\n    A file name template for building the full path name of the GRIB \n    file which contains the precipitation field that will be used to\n    fill in missing values from the file specified by PCPFILE_PRIMARY.\n    Multiple templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  PCPFILE_SECONDARY = \"<DataDir>/<YYYY>/<MM>/<DD>/PCP_forecast.<date>\",\n\nHFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the time-varying 2D forcing height field associated \n    with the source data.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  HFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/H_FORCING.<date>.grb\"\n\nWEASDFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the water-equivalent accumulated snow depth\n    field.  Multiple templates may be defined; the file that gets used\n    will be from the first template which resolves to an existing\n    filename.\n\n    A constant value may be specified for the snow water equivalent\n    field.  To specify a constant value, use the string\n    \"CONSTANT:<value>\", replacing \"<value>\" with the desired value\n    of the snow water equivalent field, in units of kg m{-2}.\n\n    Type:     character string\n    Default:  No valid default value\n    Examples: WEASDFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/WEASD.<date>\",\n              WEASDFILE_TEMPLATE = \"CONSTANT:0.0\"\n\nCANWATFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the canopy-water field.  Multiple templates\n    may be defined; the file that gets used will be from the first\n    template which resolves to an existing filename.\n\n    A constant value may be specified for the canopy water field.\n    To specify a constant value, use the string \"CONSTANT:<value>\",\n    replacing \"<value>\" with the desired value of the canopy water\n    field, in units of kg m{-2}.\n\n    Type:     character string\n    Default:  No valid default value\n    Examples: CANWATFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/CANWAT.<date>\",\n              CANWATFILE_TEMPLATE = \"CONSTANT:0.05\",\n\nLANDSFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the land/sea mask of the source data.\n    Multiple templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  LANDSFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/LANDSEA.<date>\",\n\nSKINTFILE_TEMPLATE\n\n    A file name template for building the full path name of the GRIB\n    file which contains the skin temperature field.  Multiple\n    templates may be defined; the file that gets used will be\n    from the first template which resolves to an existing filename.\n\n    A constant value may be specified for the skin temperature field.\n    To specify a constant value, use the string \"CONSTANT:<value>\",\n    replacing \"<value>\" with the desired value of the skin temperature\n    field, in units of K.\n\n    Type:     character string\n    Default:  No valid default value\n    Examples: SKINTFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/SKINT.<date>\",\n              SKINTFILE_TEMPLATE = \"CONSTANT:285.0\",\n\nSTFILE_TEMPLATES\n\n    File name templates for building the full path names of the GRIB\n    files which contain the soil temperature fields at various levels.\n    Multiple templates must be defined, for specifying fields for\n    the various soil levels.  Multiple groups of levels may be\n    defined, the files that get used will be from the first templates\n    which resolves to existing filenames.\n\n    A constant value may be specified for the soil temperature field.\n    To specify a constant value, use the string \"CONSTANT:<value>\",\n    replacing \"<value>\" with the desired value of the soil temperature\n    field, in units of K.\n\n    Type:     character string\n    Default:  No valid default value\n    Examples: STFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_T_000-010.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_T_010-040.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_T_040-100.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_T_100-200.<date>\",\n              STFILE_TEMPLATE = \"CONSTANT:285.0\",\n                                \"CONSTANT:282.0\",\n                                \"CONSTANT:278.0\",\n                                \"CONSTANT:275.0\",\n\nSMFILE_TEMPLATES\n\n    File name templates for building the full path names of the GRIB\n    files which contain the soil moisture fields at various levels.\n    Multiple templates must be defined, for specifying fields for\n    the various soil levels.  Multiple groups of levels may be\n    defined, the files that get used will be from the first templates\n    which resolves to existing filenames.\n\n    A constant value may be specified for the soil moisture field.\n    To specify a constant value, use the string \"CONSTANT:<value>\",\n    replacing \"<value>\" with the desired value of the soil moisture\n    field, in units of volumetric proportion.\n\n    Type:     character string\n    Default:  No valid default value\n    Example:  SMFILE_TEMPLATE = \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_M_000-010.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_M_010-040.<date>\",\n                                \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_M_040-100.<date>\",\n\t                        \"<DataDir>/<YYYY>/<MM>/<DD>/SOIL_M_100-200.<date>\",\n              SMFILE_TEMPLATE = \"CONSTANT:0.25\",\n                                \"CONSTANT:0.30\",\n                                \"CONSTANT:0.32\",\n                                \"CONSTANT:0.35\",\n\n<VTABLE>\n\n    This tag begins Variable table in the style of the WPS program\n    ungrib VTables. This portion of the file is not part of the\n    Fortran namelist (which ends with the \"/\" character).  The VTable\n    is a mapping of GRIB (Edition 1 or Edition 2) code numbers to\n    variable names as recognized in the HRLDAS code.  Users may need\n    to modify the VTable if the GRIB code numbers from their source\n    data sets differ from those defined in this portion of the\n    namelist file.\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/check_SW.ncl",
    "content": "load \"$NCARG_ROOT/lib/ncarg/nclex/gsun/gsn_code.ncl\"\nload \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl\"\nload \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl\"  \n\nbegin\n\n; need to 'setenv NCL_GRIB_PTABLE_PATH ../gribtab.noah.gtb'\n\nlat2print = 400\nlon2print = 1200 ;230 ;400;  (400,100) strange (320,720) 0E,20N\nyyyy = \"2010\"\nmm = \"01\"\ndd = \"02\"\n\ninfiles = systemfunc(\"ls /d1/barlage/data/GLDAS/extracted/SWdown24/GLDAS_SWdown.\"+yyyy+mm+dd+\"*.grb\")\nhr_files = addfiles(infiles,\"r\")\nprint(getfilevarnames(hr_files[1]))\n\nhr_rad = new(24,float)\ndo i = 0,23\n hr_rad(i) = hr_files[i]->SWdown_GDS0_SFC_ave(lat2print,lon2print)\nend do\nprint(hr_rad)\n\norigpath = \"/d1/barlage/data/GLDAS/extracted/SWdown/\"\nsixhr_rad = new(24,float)\ninfile = addfile(origpath+\"GLDAS_SWdown.\"+yyyy+mm+dd+\"00.grb\",\"r\")\nprint(getfilevarnames(infile))\nsixhr_rad(0) = infile->SWdown_GDS0_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(origpath+\"GLDAS_SWdown.\"+yyyy+mm+dd+\"03.grb\",\"r\")\nsixhr_rad(3) = infile->SWdown_GDS0_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(origpath+\"GLDAS_SWdown.\"+yyyy+mm+dd+\"06.grb\",\"r\")\nsixhr_rad(6) = infile->SWdown_GDS0_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(origpath+\"GLDAS_SWdown.\"+yyyy+mm+dd+\"09.grb\",\"r\")\nsixhr_rad(9) = infile->SWdown_GDS0_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(origpath+\"GLDAS_SWdown.\"+yyyy+mm+dd+\"12.grb\",\"r\")\nsixhr_rad(12) = infile->SWdown_GDS0_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(origpath+\"GLDAS_SWdown.\"+yyyy+mm+dd+\"15.grb\",\"r\")\nsixhr_rad(15) = infile->SWdown_GDS0_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(origpath+\"GLDAS_SWdown.\"+yyyy+mm+dd+\"18.grb\",\"r\")\nsixhr_rad(18) = infile->SWdown_GDS0_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(origpath+\"GLDAS_SWdown.\"+yyyy+mm+dd+\"21.grb\",\"r\")\nsixhr_rad(21) = infile->SWdown_GDS0_SFC_ave3h(lat2print,lon2print)\nprint(sixhr_rad)\n\nprint(sum(hr_rad))\nprint(sum(sixhr_rad))\n\nname = \"check_SW\"\nscreen = 1\nif(screen.eq.1) then\n  wks = gsn_open_wks(\"x11\",name) \nelse\n  wks = gsn_open_wks(\"pdf\",name) \nend if\n\ntime = ispan(0,23,1)\n res2                   = True                     ; plot mods desired\n res2@xyMarkLineModes   = (/\"Markers\",\"MarkLines\"/)                ; choose which have markers\n res2@xyMonoMarkLineMode= False\n res2@xyMarkers         =  (/16,16/)                      ; choose type of marker  \n res2@xyMarkerColors    = (/\"black\",\"red\"/)                    ; Marker color\n res2@xyLineColors       = (/\"black\",\"red\"/)                    ; Marker color\n res2@xyMarkerSizeF     = 0.004                     ; Marker size (default 0.01)\n\n plot  = gsn_csm_xy (wks,(/time,time/),(/hr_rad,sixhr_rad/),res2) ; create plot\n\nend\n\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/combine_precips.f90",
    "content": "implicit none\ninteger,parameter           :: maxpts = 864000, lugbin1 = 11, lugbin2 = 12, lugbout = 10, lugi = 0\ninteger,dimension(200)      :: jpds,jgds,kpds,kgds\nlogical*1,dimension(maxpts) :: lb\nreal,dimension(maxpts)      :: data_in1, data_in2, data_out\ninteger                     :: iret, j, kf, k\ncharacter*100               :: infile1,infile2,outfile\n\ncall getarg(1,infile1)\ncall getarg(2,infile2)\ncall getarg(3,outfile)\n\n! READ IN SNOW\n\ncall baopenr(lugbin2,infile2,iret)\nif(iret/=0) stop 4\n\n! Set GRIB1 field identification values to search for\n\nj=0      ! search from beginning\njgds    =  -1\njpds    =  -1\njpds(5) = 131\n\ncall getgb(lugbin2,lugi,maxpts,j,jpds,jgds,kf,k,kpds,kgds,lb,data_in2,iret)\nif(iret/=0) stop 5\n\ncall baclose(lugbin2,iret)\nif(iret/=0) stop 6\n\n! READ IN RAIN\n\ncall baopenr(lugbin1,infile1,iret)\nif(iret/=0) stop 1\n\n! Set GRIB1 field identification values to search for\n\nj=0      ! search from beginning\njgds    =  -1\njpds    =  -1\njpds(5) = 132\n\ncall getgb(lugbin1,lugi,maxpts,j,jpds,jgds,kf,k,kpds,kgds,lb,data_in1,iret)\nif(iret/=0) stop 2\n\ncall baclose(lugbin1,iret)\nif(iret/=0) stop 3\n\n! COMBINE AND PUT INTO TOTAL PRECIP\n\nkpds(5)  = 59\nkpds(22)  = 8\n\ndata_out = data_in1 + data_in2\nwhere (data_out<0) data_out = 0\n\ncall baopenw(lugbout,outfile,iret)\nif(iret/=0) stop 10\n\ncall putgb(lugbout,maxpts,kpds,kgds,lb,data_out,iret)\nif(iret/=0) stop 11\n\ncall baclose(lugbout,iret)\nif(iret/=0) stop 12\n\n\nend\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/combine_precips.perl",
    "content": "#!/usr/bin/perl\n\n\n$filename = \"combine_precips\";\nsystem (\"pgf90 -o $filename $filename.f90 -L/home/barlage/programs/w3lib-1.6 -lw3\");\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n\t \"30\",\"31\");\n\t \n@yrs = (\"10\");\n\n$day_start = 1;\n$day_end = 3;\n\n@hrs = (\"00\",\"03\",\"06\",\"09\",\"12\",\"15\",\"18\",\"21\");\n\n@noleap_days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days   = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n$data_dir = \"/d1/barlage/data/GLDAS/extracted\";\n$results_dir = \"/d1/barlage/data/GLDAS/extracted\";\n\nfor $yy (@yrs)\n {\n# This will be the jday time loop\n\nfor($julday=$day_start;$julday<=$day_end;$julday++)\n\n { \n \n # This little section finds the text month and day\n \n @modays = @noleap_days;\n if($yy == \"00\" || $yy == \"04\" || $yy == \"08\" || $yy == \"12\") {@modays = @leap_days}\n\n for($mo=1;$mo<=12;$mo++)\n  {\n    if($julday>$modays[$mo-1] && $julday<=$modays[$mo]) \n     {\n       $mon = $mo;\n       $day = $julday - $modays[$mo-1];\n     }\n  }\n\nfor $hr (@hrs)\n {\n  $file1_in  =    \"$data_dir/Rainf/GLDAS_Rainf.20$yy$nums[$mon]$nums[$day]$hr.grb\";\n  $file2_in  =    \"$data_dir/Snowf/GLDAS_Snowf.20$yy$nums[$mon]$nums[$day]$hr.grb\";\n  $file_out =  \"$results_dir/Precip/GLDAS_Precip.20$yy$nums[$mon]$nums[$day]$hr.grb\";\n  print (\"$file_out \\n\");\n  system (\"$filename $file1_in $file2_in $file_out\");\n }\n }\n }\n\nsystem(\"rm $filename\");\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/create_UV.f90",
    "content": "implicit none\ninteger,parameter           :: maxpts = 864000, lugbin = 10, lugbout1 = 11, lugbout2 = 12, lugi = 0\ninteger,dimension(200)      :: jpds,jgds,kpds,kgds\nlogical*1,dimension(maxpts) :: lb\nreal,dimension(maxpts)      :: data_in, data_out\ninteger                     :: iret, j, kf, k\ncharacter*100               :: infile,outfile1,outfile2\n\ncall getarg(1,infile)\ncall getarg(2,outfile1)\ncall getarg(3,outfile2)\n\n! READ IN DUMMY VARIABLE\n\ncall baopenr(lugbin,infile,iret)\nif(iret/=0) stop 1\n\n! Set GRIB1 field identification values to search for\n\nj=0      ! search from beginning\njgds    =  -1\njpds    =  -1\njpds(5) = 32\n\ncall getgb(lugbin,lugi,maxpts,j,jpds,jgds,kf,k,kpds,kgds,lb,data_in,iret)\nif(iret/=0) stop 2\n\ncall baclose(lugbin,iret)\nif(iret/=0) stop 3\n\n! Set all wind to U\n\nkpds(5)  = 33\n\ndata_out = data_in\n\ncall baopenw(lugbout1,outfile1,iret)\nif(iret/=0) stop 4\n\ncall putgb(lugbout1,maxpts,kpds,kgds,lb,data_out,iret)\nif(iret/=0) stop 5\n\ncall baclose(lugbout1,iret)\nif(iret/=0) stop 6\n\n\n! CREATE FAKE V AND SET TO ZERO\n\nkpds(5)  = 34\n\ndata_out = 0\n\ncall baopenw(lugbout2,outfile2,iret)\nif(iret/=0) stop 7\n\ncall putgb(lugbout2,maxpts,kpds,kgds,lb,data_out,iret)\nif(iret/=0) stop 8\n\ncall baclose(lugbout2,iret)\nif(iret/=0) stop 9\n\n\nend\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/create_UV.perl",
    "content": "#!/usr/bin/perl\n\n\n$filename = \"create_UV\";\nsystem (\"pgf90 -o $filename $filename.f90 -L/home/barlage/programs/w3lib-1.6 -lw3\");\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n\t \"30\",\"31\");\n\t \n@yrs = (\"10\");\n\n$day_start = 1;\n$day_end = 3;\n\n@hrs = (\"00\",\"03\",\"06\",\"09\",\"12\",\"15\",\"18\",\"21\");\n\n@noleap_days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days   = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n$data_dir = \"/d1/barlage/data/GLDAS/extracted\";\n$results_dir = \"/d1/barlage/data/GLDAS/extracted\";\n\nfor $yy (@yrs)\n {\n\n# This will be the jday time loop\n\nfor($julday=$day_start;$julday<=$day_end;$julday++)\n\n { \n \n # This little section finds the text month and day\n \n @modays = @noleap_days;\n if($yy == \"00\" || $yy == \"04\" || $yy == \"08\" || $yy == \"12\") {@modays = @leap_days}\n\n for($mo=1;$mo<=12;$mo++)\n  {\n    if($julday>$modays[$mo-1] && $julday<=$modays[$mo]) \n     {\n       $mon = $mo;\n       $day = $julday - $modays[$mo-1];\n     }\n  }\n\nfor $hr (@hrs)\n {\n\n  $file_in  =    \"$data_dir/Wind/GLDAS_Wind.20$yy$nums[$mon]$nums[$day]$hr.grb\";\n  $file1_out =  \" $results_dir/U/GLDAS_U.20$yy$nums[$mon]$nums[$day]$hr.grb\";\n  $file2_out =  \" $results_dir/V/GLDAS_V.20$yy$nums[$mon]$nums[$day]$hr.grb\";\n\n  print (\"$file_in \\n\");\n  system (\"$filename $file_in $file1_out $file2_out\");\n }\n }\n } # End of outer time loop\n\nsystem(\"rm $filename\");\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/extract_gldas.perl",
    "content": "#!/usr/bin/perl\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n\t \"30\",\"31\");\n\t \n@yrs = (\"10\");\n\n$day_start = 1;\n$day_end   = 3;\n\n@hrs = (\"00\",\"03\",\"06\",\"09\",\"12\",\"15\",\"18\",\"21\");\n\n$cc = \"20\";   # Manually set the century\n\n@noleap_days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days   = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n@vars = (\"Rainf\",\"Snowf\",\"Wind\",\"Tair\",\"Qair\",\"Psurf\",\"SWdown\",\"LWdown\"); \n\n$data_dir = \"/d1/barlage/data/GLDAS/raw\";\n$results_dir = \"/d1/barlage/data/GLDAS/extracted\";\n\nfor $var (@vars)\n {\nfor $yy (@yrs)\n {\n\n# This will be the jday time loop\n\nfor($julday=$day_start;$julday<=$day_end;$julday++)\n\n { \n \n # This little section finds the text month and day\n \n @modays = @noleap_days;\n if($yy == \"92\" || $yy == \"96\") {@modays = @leap_days}\n if($yy == \"00\" || $yy == \"04\" || $yy == \"08\" || $yy == \"12\") {@modays = @leap_days}\n\n for($mo=1;$mo<=12;$mo++)\n  {\n    if($julday>$modays[$mo-1] && $julday<=$modays[$mo]) \n     {\n       $mon = $mo;\n       $day = $julday - $modays[$mo-1];\n     }\n  }\n\n  $jday3 = \"$julday\";\n  if($julday<100) {$jday3 = \"0$julday\"};\n  if($julday<10) {$jday3 = \"00$julday\"};\n  \n  @infiles = ( `ls $data_dir/GLDAS_NOAH025SUBP_3H.A$cc$yy$jday3*` );\n  chop(@infiles);\n\nfor($hr=1;$hr<=8;$hr++)\n {\n\n  $file = $infiles[$hr-1];\n\n  system (\"wgrib -s $file | grep ':$var:' | wgrib -i -grib $file -o $results_dir/$var/GLDAS_$var.20$yy$nums[$mon]$nums[$day]$hrs[$hr-1].grb \");\n }\n }\n } # End of outer time loop\n }\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/extract_gldas_init.perl",
    "content": "#!/usr/bin/perl\n\n\t \n$date = \"2010010100\";   # Manually set the date\n\n$data_dir = \"/d1/barlage/data/GLDAS/raw\";\n$results_dir = \"/d1/barlage/data/GLDAS/extracted/INIT\";\n\n$file = \"$data_dir/GLDAS_NOAH025SUBP_3H.A2010001.0000.001.2010048211443.grb\";\n\n@vars = (\"SWE\",\"Canopint\",\"AvgSurfT\",\"SoilM\",\"TSoil\"); \n\nfor $var (@vars)\n {\n\n  if($var eq \"SoilM\" || $var eq \"TSoil\") \n   {\n     system (\"wgrib -s $file | grep ':${var}:0-1' | wgrib -i -grib $file -o $results_dir/GLDAS_${var}_100-200.$date.grb \");\n     system (\"wgrib -s $file | grep ':${var}:0-2' | wgrib -i -grib $file -o $results_dir/GLDAS_${var}_040-100.$date.grb \");\n     system (\"wgrib -s $file | grep ':${var}:0-3' | wgrib -i -grib $file -o $results_dir/GLDAS_${var}_010-040.$date.grb \");\n     system (\"wgrib -s $file | grep ':${var}:0-4' | wgrib -i -grib $file -o $results_dir/GLDAS_${var}_000-010.$date.grb \");\n   } else\n   {\n     system (\"wgrib -s $file | grep ':$var:' | wgrib -i -grib $file -o $results_dir/GLDAS_$var.$date.grb \");\n   }\n\n }\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/fill_SSRD.f90",
    "content": "program fill_SSRD\nimplicit none\ninteger,parameter :: maxpts = 864000, lugbin1 = 10, lugbin2 = 11, lugi = 0\ninteger,parameter :: lugbout = 20\ninteger,dimension(200)      :: jpds,jgds,kpds,kgds\nlogical*1,dimension(maxpts) :: lb\nreal,dimension(maxpts)      :: data_in1, data_in2, lat, lon, cosdiff,datadiff\nreal,dimension(maxpts,4)    :: data_out, cza\ninteger                     :: i, iret, j, kf, k, yr(4), mo(4), dy(4), hr(4)\nreal                        :: jday(4), hr_mid(4),critnrg,critcos\ncharacter*100               :: infile1,infile2,outfile(4)\nlogical                     :: check1,check2\nreal, parameter   :: pi = 3.14159265\ninteger,parameter :: testpt = 518136\nlogical,parameter :: debug = .true.\n\nopen(20, file='fill_SSRD.input', form ='formatted')\n  read(20,'(a100)') infile1\n  read(20,'(a100)') infile2\n do i=1,4\n  read(20,'(a100)') outfile(i)\n  read(20,*) yr(i), mo(i), dy(i), hr(i), jday(i), hr_mid(i)\n end do\nclose(20)\n\ndo i = 0,599\n  lat( i*1440+1 : i*1440+1440 ) = -59.875 + i*0.25\nend do\ndo i = 0,1439\n  lon( i+1 : : 1440 ) = -179.875 + i*0.25\nend do\n\nif(debug) print *, lat(testpt),lon(testpt)\n\nlat = lat * pi / 180.0\nlon = lon * pi / 180.0\n\n! GET COSINE ZENITH ANGLE ARRAY FOR EACH HOUR\n\ndo i = 1,4\n  call get_cza(jday(i),hr_mid(i),lat,lon,cza(:,i))\nend do\n\n! READ IN VARIABLE\n\ndata_in1 = 0.0\ndata_in2 = 0.0\n\ninquire(file=infile1,exist=check1)\ninquire(file=infile2,exist=check2)\n\nif(check1) then\n\n  call baopenr(lugbin1,infile1,iret)\n  if(iret/=0) stop 11\n\n! Set GRIB1 field identification values to search for\n\n  j=0      ! search from beginning\n  jgds    =  -1\n  jpds    =  -1\n\n  call getgb(lugbin1,lugi,maxpts,j,jpds,jgds,kf,k,kpds,kgds,lb,data_in1,iret)\n  if(iret/=0) stop 21\n\n  call baclose(lugbin1,iret)\n  if(iret/=0) stop 31\n\nend if\n\nif(check2) then\n\n  call baopenr(lugbin2,infile2,iret)\n  if(iret/=0) stop 12\n\n! Set GRIB1 field identification values to search for\n\n  j=0      ! search from beginning\n  jgds    =  -1\n  jpds    =  -1\n\n  call getgb(lugbin2,lugi,maxpts,j,jpds,jgds,kf,k,kpds,kgds,lb,data_in2,iret)\n  if(iret/=0) stop 22\n\n  call baclose(lugbin2,iret)\n  if(iret/=0) stop 32\n\nend if\nif(debug) print *, cza(testpt,1), data_in1(testpt)\nif(debug) print *, cza(testpt,4), data_in2(testpt)\nif(debug) print *, count(cza(:,1)<0.and.data_in1>0)\nif(debug) print *, count(cza(:,4)<0.and.data_in2>0)\n\n! START MESSING WITH THE INPUT DATA\n\nwhere(data_in1 <= 0 .or. cza(:,1) <= 0.0)\n  data_in1 = 0.0\n  cza(:,1) = 0.0\nend where\nwhere(data_in2 <= 0 .or. cza(:,4) <= 0.0)\n  data_in2 = 0.0\n  cza(:,4) = 0.0\nend where\n\ncritnrg = 50.0\ncritcos = 0.05\ndata_out(:,1) = data_in1\ndata_out(:,4) = data_in2\ndata_out(:,2) = (2.0*data_in1 + data_in2)/3.0  ! default to linear interp\ndata_out(:,3) = (data_in1 + 2.0*data_in2)/3.0\n\nwhere(data_in1 > critnrg .and. data_in2 <= critnrg .and. cza(:,1) > critcos)\n  data_out(:,2) = cza(:,2)/cza(:,1) * data_in1   ! if sun sufficently high\n  data_out(:,3) = cza(:,3)/cza(:,1) * data_in1   ! around sunset, use left value\nend where\n\nwhere(data_in1 <= critnrg .and. data_in2 > critnrg .and. cza(:,4) > critcos)\n  data_out(:,2) = cza(:,2)/cza(:,4) * data_in2   ! if sun sufficently high\n  data_out(:,3) = cza(:,3)/cza(:,4) * data_in2   ! around sunrise, use right value\nend where\n\nwhere(data_in1 > critnrg .and. data_in2 > critnrg .and. cza(:,1) > critcos .and. cza(:,4) > critcos)\n  data_out(:,3) = cza(:,3)/cza(:,4) * data_in2  ! mid-day with sufficient sun\n  data_out(:,2) = cza(:,2)/cza(:,1) * data_in1  !   so use zenith angle\nend where\n\n! WRITE OUT NEW FILES\n\ndo i = 1,4\n\n  where(data_out(:,i) <= 0 .or. cza(:,i) <= 0.0) data_out(:,i) = 0.0\n\n  if(debug) print *, cza(testpt,i), data_out(testpt,i), data_in1(testpt), data_in2(testpt)\n\n  kpds(8)  = yr(i)\n  kpds(9)  = mo(i)\n  kpds(10) = dy(i)\n  kpds(11) = hr(i)\n  kpds(15) = 0            ! change number of hours in average to 1\n  kpds(22) = 2            ! preserve 2 decimal points\n\n  call baopenw(lugbout+i,outfile(i),iret)\n  if(iret/=0) stop 4\n\n  call putgb(lugbout+i,maxpts,kpds,kgds,lb,data_out(:,i),iret)\n  if(iret/=0) stop 5\n\n  call baclose(lugbout+i,iret)\n  if(iret/=0) stop 6\n\nend do\n\nif(debug) print *\n\ncontains\n\nsubroutine get_cza(jday, gmthour, latrad, lonrad, cza)\n  implicit none\n  integer,parameter :: maxpts = 864000\n  real, intent(in) :: jday,gmthour\n  real, intent(in) :: latrad(maxpts)\n  real, intent(in) :: lonrad(maxpts)\n  real, intent(out) :: cza(maxpts)\n\n  real :: gg, tc, declin, sha(maxpts)\n  real, parameter :: pi = 3.14159265\n\n  ! Fractional day of the year, in radians\n  gg = (360./365.25) * (JDAY+gmthour/24.) * pi/180.\n\n  ! Solar declination angle, in radians.\n  DECLIN = 0.006918 - 0.399912*cos(gg) + 0.070257*sin(gg) - 0.006758*cos(2.0*gg) + &\n       0.000907*sin(2.0*gg) - 0.002697*cos(3.0*gg) + 0.00148*sin(3.0*gg)\n\n  ! Time Correction for solar angle, in radians.  Whatever.\n  TC = 0.000075 + 0.001868*cos(gg) - 0.032077*sin(gg) - 0.014615*cos(2.0*gg) - &\n       0.040849*sin(2.0*gg)\n!  TC = 0.0000\n\n  ! Solar Hour Angle, in radians\n  SHA = ((gmthour-12.0)*15.0)*(pi/180.) + lonrad + TC\n  ! SHA = (gmthour*15.0)*(pi/180.) + lonrad + TC\n\n  ! ! Solar Zenith Angle, in radians\n  CZA = sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA)\n  where(cza.lt.0) cza = 0.0\n\nend subroutine get_cza\n\n\nend program fill_SSRD\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/fill_SSRD.perl",
    "content": "#!/usr/bin/perl\n\n\n$filename = \"fill_SSRD\";\n\n$w3lib = '/home/barlage/programs/w3lib-1.6 -lw3';\n\nsystem (\"pgf90 -o $filename $filename.f90 -L$w3lib\");\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n         \"30\",\"31\",\"32\",\"33\",\"34\",\"35\",\"36\",\"37\",\"38\",\"39\",\n\t \"40\",\"41\",\"42\",\"43\",\"44\",\"45\",\"46\",\"47\",\"48\",\"49\",\n\t \"50\",\"51\",\"52\",\"53\",\"54\",\"55\",\"56\",\"57\",\"58\",\"59\",\n\t \"60\",\"61\",\"62\",\"63\",\"64\",\"65\",\"66\",\"67\",\"68\",\"69\",\n\t \"70\",\"71\",\"72\",\"73\",\"74\",\"75\",\"76\",\"77\",\"78\",\"79\",\n\t \"80\",\"81\",\"82\",\"83\",\"84\",\"85\",\"86\",\"87\",\"88\",\"89\",\n\t \"90\",\"91\",\"92\",\"93\",\"94\",\"95\",\"96\",\"97\",\"98\",\"99\");\n\t \n@noleap_days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days   = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n$cc = \"20\";  # Manually set century\n\n@yys = (\"10\");\n\n$day_start = 1;\n$day_end = 3;\n\n$data_dir = \"/d1/barlage/data/GLDAS/extracted\";\n\nfor $yy (@yys)\n {\n\n# This will be the jday time loop\n\nfor($jday=$day_start;$jday<=$day_end;$jday++)\n\n { \n \n # This little section finds the text month and day\n \n @modays = @noleap_days;\n if($yy == \"00\" || $yy == \"04\" || $yy == \"08\" || $yy == \"12\") {@modays = @leap_days}\n\n for($mo=1;$mo<=12;$mo++)\n  {\n    if($jday>$modays[$mo-1] && $jday<=$modays[$mo]) \n     {\n       $mm = $mo;\n       $dd = $jday - $modays[$mo-1];\n     }\n  } \n\n  print (\"$yy $mm $dd $jday\\n\");\n \n  $dd_now = $nums[$dd];\n  $mm_now = $nums[$mm];\n  $yy_now = $nums[$yy];\n\nfor($hh=0; $hh<=21; $hh=$hh+3)\n {\n\n # GLDAS1 data are 3hr instant NOT averages for the previous three hours\n\n  open(FILE, \"> fill_SSRD.input\") || die print \"Can't open: \\n\";\n\n # find the bracket days for interpolation\n #   - will need editing if crossing century\n\n $file_in = \"$data_dir/SWdown/GLDAS_SWdown.$cc$yy_now$mm_now$dd_now$nums[$hh].grb\";\n   print FILE \"$file_in \\n\";\n\n if($hh != 21) {\n   $file_in = \"$data_dir/SWdown/GLDAS_SWdown.$cc$yy_now$mm_now$dd_now$nums[$hh+3].grb\";\n     print FILE \"$file_in \\n\";\n  }else{\n   # find the next day since averages are ending at filename time\n   #   - will need editing if crossing century\n \n   $jdayp1 = $jday + 1;\n   if($dd != $days[$mm]) {\n     $ddp1 = $dd + 1;\n     $mmp1 = $mm;\n     $yyp1 = $yy;\n    }else{\n     $ddp1 = 1;\n     $mmp1 = $mm + 1;\n     $yyp1 = $yy;\n     if($mmp1 > 12) {\n       $mmp1 = 1;\n       $yyp1 = $yy + 1;\n       $jdayp1 = 1;\n     }\n    }\n\n   $file_in = \"$data_dir/SWdown/GLDAS_SWdown.$cc$nums[$yyp1]$nums[$mmp1]$nums[$ddp1]00.grb\";\n     print FILE \"$file_in \\n\";\n\n  }\n \n  $hh_out = $hh;\n  $file_out = \"$data_dir/SWdown24/GLDAS_SWdown.$cc$yy_now$mm_now$dd_now$nums[$hh_out].grb\";\n    print FILE \"$file_out \\n\";\n    print FILE \"$yy $mm $dd $hh_out $jday $hh_out\\n\";\n  $hh_out = $hh + 1;\n  $file_out = \"$data_dir/SWdown24/GLDAS_SWdown.$cc$yy_now$mm_now$dd_now$nums[$hh_out].grb\";\n    print FILE \"$file_out \\n\";\n    print FILE \"$yy $mm $dd $hh_out $jday $hh_out\\n\";\n  $hh_out = $hh + 2;\n  $file_out = \"$data_dir/SWdown24/GLDAS_SWdown.$cc$yy_now$mm_now$dd_now$nums[$hh_out].grb\";\n    print FILE \"$file_out \\n\";\n    print FILE \"$yy $mm $dd $hh_out $jday $hh_out\\n\";\n\n  if($hh != 21) {\n    $hh_out = $hh + 3;\n    $file_out = \"$data_dir/SWdown24/GLDAS_SWdown.$cc$yy_now$mm_now$dd_now$nums[$hh_out].grb\";\n      print FILE \"$file_out \\n\";\n      print FILE \"$yy $mm $dd $hh_out $jday $hh_out\\n\";\n   }else{\n \n    $file_out = \"$data_dir/SWdown24/GLDAS_SWdown.$cc$nums[$yyp1]$nums[$mmp1]$nums[$ddp1]00.grb\";\n      print FILE \"$file_out \\n\";\n      print FILE \"$yyp1 $mmp1 $ddp1 0 $jdayp1 0\\n\";\n  }\n\n # end of file naming mess\n\n  close(FILE);\n\n  system (\"$filename\");\n\n }\n }\n }\nsystem(\"rm $filename\");\nsystem(\"rm $filename.input\");\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/gribtab_GLDAS_NOAH.gtb",
    "content": "-1:-1:-1:-1\n001:Psurf:Surface pressure [Pa]\n007:Hgt:Terrain height [m]\n011:Tair:Near surface air temperature [K]\n032:Wind:Near surface wind speed [m/s]\n033:Uwind:Near surface wind u-component [m/s]\n034:Vwind:Near surface wind v-component [m/s]\n051:Qair:Near surface specific humidity [kg/kg]\n057:Evap:Total Evapotranspiration [kg/m^2/s]\n059:Precip:Total Precipitation rate [kg/m^2/s]\n065:SWE:Snow Water Equivalent [kg/m^2]\n071:Canopint:Total canopy water storage [kg/m^2]\n085:TSoil:Soil temperature [K]\n086:SoilM:Soil moisture content [kg/m^2]\n099:Qsm:Snowmelt [kg/m^2/s]\n111:SWnet:Net Shortwave Radiation [W/m^2]\n112:LWnet:Net Longwave Radiation [W/m^2]\n121:Qle:Latent Heat Flux [W/m^2]\n122:Qh:Sensible Heat Flux [W/m^2]\n131:Snowf:Snowfall rate [kg/m^2/s]\n132:Rainf:Rainfall rate [kg/m^2/s]\n138:AvgSurfT:Average Surface Temperature [K]\n155:Qg:Ground Heat Flux [W/m^2]\n204:SWdown:Surface incident shortwave radiation [W/m^2]\n205:LWdown:Surface incident longwave radiation [W/m^2]\n234:Qsb:Subsurface Runoff [kg/m^2/s]\n235:Qs:Surface Runoff [kg/m^2/s]\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/GLDAS/namelist.input.GLDAS",
    "content": "&files\n STARTDATE          = \"2010-01-01_00\"\n ENDDATE            = \"2010-01-03_00\"\n DataDir            = \"/d1/barlage/data/GLDAS/extracted\"\n OutputDir          = \"/d1/barlage/data/GLDAS/LDASIN/\"\n FULL_IC_FRQ        = 0\n RAINFALL_INTERP    = 0\n RESCALE_SHORTWAVE  = .FALSE.\n UPDATE_SNOW        = .FALSE.\n FORCING_HEIGHT_2D  = .FALSE.\n TRUNCATE_SW        = .FALSE.\n EXPAND_LOOP        = 1\n INIT_LAI           = .TRUE.\n VARY_LAI           = .TRUE.\n MASK_WATER         = .TRUE.\n\n geo_em_flnm        = \"/d1/barlage/data/mptest/geo_em.d01.nc\"\n\n Zfile_template     = \"examples/GLDAS/GLDAS_ELEVATION.grb\"\n\n Tfile_template     = \"<DataDir>/Tair/GLDAS_Tair.<date>.grb\"\n Ufile_template     = \"<DataDir>/U/GLDAS_U.<date>.grb\",\n Vfile_template     = \"<DataDir>/V/GLDAS_V.<date>.grb\",\n Pfile_template     = \"<DataDir>/Psurf/GLDAS_Psurf.<date>.grb\",\n Qfile_template     = \"<DataDir>/Qair/GLDAS_Qair.<date>.grb\",\n LWfile_template    = \"<DataDir>/LWdown/GLDAS_LWdown.<date>.grb\",\n SWfile_primary     = \"<DataDir>/SWdown24/GLDAS_SWdown.<date>.grb\",\n SWfile_secondary   = \"<DataDir>/SWdown24/GLDAS_SWdown.<date>.grb\",\n PCPfile_primary    = \"<DataDir>/Precip/GLDAS_Precip.<date>.grb\"\n PCPfile_secondary  = \"<DataDir>/Precip/GLDAS_Precip.<date>.grb\",\n\n WEASDfile_template = \"<DataDir>/INIT/GLDAS_SWE.<date>.grb\",\n CANWTfile_template = \"<DataDir>/INIT/GLDAS_Canopint.<date>.grb\",\n SKINTfile_template = \"<DataDir>/INIT/GLDAS_AvgSurfT.<date>.grb\",\n\n STfile_template    = \"<DataDir>/INIT/GLDAS_TSoil_000-010.<date>.grb\",\n                      \"<DataDir>/INIT/GLDAS_TSoil_010-040.<date>.grb\",\n                      \"<DataDir>/INIT/GLDAS_TSoil_040-100.<date>.grb\",\n                      \"<DataDir>/INIT/GLDAS_TSoil_100-200.<date>.grb\",\n\n SMfile_template    = \"<DataDir>/INIT/GLDAS_SoilM_000-010.<date>.grb\",\n                      \"<DataDir>/INIT/GLDAS_SoilM_010-040.<date>.grb\",\n                      \"<DataDir>/INIT/GLDAS_SoilM_040-100.<date>.grb\",\n                      \"<DataDir>/INIT/GLDAS_SoilM_100-200.<date>.grb\",\n\n/\n\n<VTABLE>\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\nGRIB1| Level| From |  To  |          |           |                                         |GRIB2|GRIB2|GRIB2|GRIB2|\nParam| Type |Level1|Level2| Name     | Units     | Description                             |Discp|Catgy|Param|Level|\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n  11 |   1  |   0  |      | T2D      | K         | Temperature       at 2 m                |  0  |  0  |  0  | 103 |\n  51 |   1  |   0  |      | Q2D      | kg/kg     | Specific Humidity at 2 m                |  0  |  1  |  0  | 103 |\n  33 |   1  |   0  |      | U2D      | m/s       | U                 at 10 m               |  0  |  2  |  2  | 103 |\n  34 |   1  |   0  |      | V2D      | m/s       | V                 at 10 m               |  0  |  2  |  3  | 103 |\n   1 |   1  |   0  |      | PSFC     | Pa        | Surface Pressure                        |  0  |  3  |  0  |   1 |\n  59 |   1  |   0  |      | RAINRATE | kg/m^2/s  | Precipitation Rate                      |  0  |  1  |  8  |   1 |\n 204 |   1  |   0  |      | SWDOWN   | W/m^2     | Downward short-wave radiation flux      |  0  |  4  | 192 |   1 |\n 205 |   1  |   0  |      | LWDOWN   | W/m^2     | Downward long-wave radiation flux       |  0  |  5  | 192 |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Terrain field of source analysis        |  2  |  0  |  7  |   1 |\n 138 |   1  |   0  |      | TSK      | K         | Skin temperature                        |  0  |  0  |  0  |   1 |\n  65 |   1  |   0  |      | SNOW     | kg/m^2    | Water equivalent snow depth             |  0  |  1  | 13  |   1 |\n  71 |   1  |   0  |      | CANWAT   | kg/m^2    | Plant Canopy Surface Water              |  2  |  0  | 196 |   1 |\n  86 | 112  |   0  |   4  | SMOIS_1  | gldas     | Soil Moist 0-10 cm below grn layer (Up) |  2  |  0  | 192 | 106 |\n  86 | 112  |   0  |   3  | SMOIS_2  | gldas     | Soil Moist 10-40 cm below grn layer     |  2  |  0  | 192 | 106 |\n  86 | 112  |   0  |   2  | SMOIS_3  | gldas     | Soil Moist 40-100 cm below grn layer    |  2  |  0  | 192 | 106 |\n  86 | 112  |   0  |   1  | SMOIS_4  | gldas     | Soil Moist 100-200 cm below gr layer    |  2  |  0  | 192 | 106 |\n  85 | 112  |   0  |   4  | STEMP_1  | K         | T 0-10 cm below ground layer (Upper)    |  2  |  0  |  2  | 106 |\n  85 | 112  |   0  |   3  | STEMP_2  | K         | T 10-40 cm below ground layer (Upper)   |  2  |  0  |  2  | 106 |\n  85 | 112  |   0  |   2  | STEMP_3  | K         | T 40-100 cm below ground layer (Upper)  |  2  |  0  |  2  | 106 |\n  85 | 112  |   0  |   1  | STEMP_4  | K         | T 100-200 cm below ground layer (Bottom)|  2  |  0  |  2  | 106 |\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n</VTABLE>\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NARR/check_SW.ncl",
    "content": "load \"$NCARG_ROOT/lib/ncarg/nclex/gsun/gsn_code.ncl\"\nload \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl\"\nload \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl\"  \n\nbegin\n\nlat2print = 150;100\nlon2print = 180;300;\nyyyy = \"2010\" \nmm = \"01\"  \ndd = \"01\"\n\nfine_path = \"/d1/barlage/data/NARR/extracted/DSWRF24/\"\ncoarse_path = \"/d1/barlage/data/NARR/extracted/DSWRF/\"\n\ninfiles = systemfunc(\"ls \"+fine_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"*.grb\")\nhr_files = addfiles(infiles,\"r\")\nprint(getfilevarnames(hr_files[1]))\n\nhr_rad = new(24,float)\ndo i = 0,23\n hr_rad(i) = hr_files[i]->DSWRF_221_SFC_ave1h(lat2print,lon2print)\nend do\nprint(hr_rad)\n\nsixhr_rad = new(24,float)\ninfile = addfile(coarse_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"00.grb\",\"r\")\nsixhr_rad(0) = infile->DSWRF_221_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(coarse_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"03.grb\",\"r\")\nsixhr_rad(3) = infile->DSWRF_221_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(coarse_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"06.grb\",\"r\")\nsixhr_rad(6) = infile->DSWRF_221_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(coarse_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"09.grb\",\"r\")\nsixhr_rad(9) = infile->DSWRF_221_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(coarse_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"12.grb\",\"r\")\nsixhr_rad(12) = infile->DSWRF_221_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(coarse_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"15.grb\",\"r\")\nsixhr_rad(15) = infile->DSWRF_221_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(coarse_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"18.grb\",\"r\")\nsixhr_rad(18) = infile->DSWRF_221_SFC_ave3h(lat2print,lon2print)\ninfile = addfile(coarse_path+\"NARR_DSWRF.\"+yyyy+mm+dd+\"21.grb\",\"r\")\nsixhr_rad(21) = infile->DSWRF_221_SFC_ave3h(lat2print,lon2print)\nprint(sixhr_rad)\n\nprint(sum(hr_rad))\nprint(sum(sixhr_rad)*3.0)\n\nname = \"check_SW\"\nscreen = 0\nif(screen.eq.1) then\n  wks = gsn_open_wks(\"x11\",name) \nelse\n  wks = gsn_open_wks(\"png\",name) \nend if\n\ntime = ispan(0,23,1)\n res2                   = True                     ; plot mods desired\n res2@xyMarkLineModes   = (/\"Markers\",\"MarkLines\"/)                ; choose which have markers\n res2@xyMonoMarkLineMode= False\n res2@xyMarkers         =  (/16,16/)                      ; choose type of marker  \n res2@xyMarkerColors    = (/\"black\",\"red\"/)                    ; Marker color\n res2@xyLineColors       = (/\"black\",\"red\"/)                    ; Marker color\n res2@xyMarkerSizeF     = 0.004                     ; Marker size (default 0.01)\n\n plot  = gsn_csm_xy (wks,(/time,time/),(/hr_rad,sixhr_rad/),res2) ; create plot\n\nend\n\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NARR/extract_narr_30m.perl",
    "content": "#!/usr/bin/perl\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n\t \"30\",\"31\");\n\t \n@yrs = (\"10\");\n\n$day_start = 1;\n$day_end = 3;\n\n@hrs = (\"00\",\"03\",\"06\",\"09\",\"12\",\"15\",\"18\",\"21\");\n\n@noleap_days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days   = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n@vars = (\"PRES\",\"TMP\",\"SPFH\",\"UGRD\",\"VGRD\"); \n\n$data_dir = \"/d1/barlage/data/NARR/raw\";\n$results_dir = \"/d1/barlage/data/NARR/extracted\";\n\nfor $var (@vars)\n {\nfor $yy (@yrs)\n {\n\n# This will be the jday time loop\n\nfor($julday=$day_start;$julday<=$day_end;$julday++)\n\n { \n \n # This little section finds the text month and day\n \n @modays = @noleap_days;\n if($yy == \"00\" || $yy == \"04\" || $yy == \"08\" || $yy == \"12\") {@modays = @leap_days}\n\n for($mo=1;$mo<=12;$mo++)\n  {\n    if($julday>$modays[$mo-1] && $julday<=$modays[$mo]) \n     {\n       $mon = $mo;\n       $day = $julday - $modays[$mo-1];\n     }\n  }\n\n  $jday3 = \"$julday\";\n  if($julday<100) {$jday3 = \"0$julday\"};\n  if($julday<10) {$jday3 = \"00$julday\"};\n\nfor $hr (@hrs)\n {\n\n  $file = `ls ${data_dir}/merged_AWIP32.20$yy$nums[$mon]$nums[$day]$hr.RS.flx`;\n  chop($file);\n\n  system (\"wgrib -s $file | grep ':$var:30' | wgrib -i -grib $file -o $results_dir/$var/NARR_$var.20$yy$nums[$mon]$nums[$day]$hr.grb \");\n\n }\n }\n } # End of outer time loop\n }\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NARR/extract_narr_init.perl",
    "content": "#!/usr/bin/perl\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n\t \"30\",\"31\");\n\t \n@hrs = (\"00\",\"03\",\"06\",\"09\",\"12\",\"15\",\"18\",\"21\");\n\n@noleap_days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days   = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n$yyyy = \"2010\";\n$mm = \"01\";\n$dd = \"01\";\n$hh = \"00\";\n\n$data_dir = \"/d1/barlage/data/NARR/raw\";\n$results_dir = \"/d1/barlage/data/NARR/extracted\";\n\n$filesfc = \"${data_dir}/merged_AWIP32.$yyyy$mm$dd$hh.RS.sfc\";\n$fileflx = \"${data_dir}/merged_AWIP32.$yyyy$mm$dd$hh.RS.flx\";\n\nprint(\"$filesfc\\n\");\nprint(\"$fileflx\\n\");\n\nsystem (\"wgrib -s $fileflx | grep ':TSOIL:0-10'    | wgrib -i -grib $fileflx -o ${results_dir}/INIT/NARR_TSOIL:0-10.$yyyy$mm$dd$hh.grb\");\nsystem (\"wgrib -s $fileflx | grep ':TSOIL:10-40'   | wgrib -i -grib $fileflx -o ${results_dir}/INIT/NARR_TSOIL:10-40.$yyyy$mm$dd$hh.grb\");\nsystem (\"wgrib -s $fileflx | grep ':TSOIL:40-100'  | wgrib -i -grib $fileflx -o ${results_dir}/INIT/NARR_TSOIL:40-100.$yyyy$mm$dd$hh.grb\");\nsystem (\"wgrib -s $fileflx | grep ':TSOIL:100-200' | wgrib -i -grib $fileflx -o ${results_dir}/INIT/NARR_TSOIL:100-200.$yyyy$mm$dd$hh.grb\");\n\nsystem (\"wgrib -s $fileflx | grep ':SOILW:0-10'    | wgrib -i -grib $fileflx -o ${results_dir}/INIT/NARR_SOILW:0-10.$yyyy$mm$dd$hh.grb\");\nsystem (\"wgrib -s $fileflx | grep ':SOILW:10-40'   | wgrib -i -grib $fileflx -o ${results_dir}/INIT/NARR_SOILW:10-40.$yyyy$mm$dd$hh.grb\");\nsystem (\"wgrib -s $fileflx | grep ':SOILW:40-100'  | wgrib -i -grib $fileflx -o ${results_dir}/INIT/NARR_SOILW:40-100.$yyyy$mm$dd$hh.grb\");\nsystem (\"wgrib -s $fileflx | grep ':SOILW:100-200' | wgrib -i -grib $fileflx -o ${results_dir}/INIT/NARR_SOILW:100-200.$yyyy$mm$dd$hh.grb\");\n\nsystem (\"wgrib -s $filesfc | grep ':TMP:sfc'       | wgrib -i -grib $filesfc -o ${results_dir}/INIT/NARR_TMP:sfc.$yyyy$mm$dd$hh.grb\");\nsystem (\"wgrib -s $filesfc | grep ':CNWAT:sfc'     | wgrib -i -grib $filesfc -o ${results_dir}/INIT/NARR_CNWAT.$yyyy$mm$dd$hh.grb\");\nsystem (\"wgrib -s $filesfc | grep ':WEASD:sfc'     | wgrib -i -grib $filesfc -o ${results_dir}/INIT/NARR_WEASD.$yyyy$mm$dd$hh.grb\");\n\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NARR/extract_narr_sfc.perl",
    "content": "#!/usr/bin/perl\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n\t \"30\",\"31\");\n\t \n@yrs = (\"10\");\n\n$day_start = 1;\n$day_end = 3;\n\n@hrs = (\"00\",\"03\",\"06\",\"09\",\"12\",\"15\",\"18\",\"21\");\n\n@noleap_days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days   = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n@vars = (\"APCP\",\"DLWRF\",\"DSWRF\"); \n\n$data_dir = \"/d1/barlage/data/NARR/raw\";\n$results_dir = \"/d1/barlage/data/NARR/extracted\";\n\nfor $var (@vars)\n {\nfor $yy (@yrs)\n {\n\n# This will be the jday time loop\n\nfor($julday=$day_start;$julday<=$day_end;$julday++)\n\n { \n \n # This little section finds the text month and day\n \n @modays = @noleap_days;\n if($yy == \"00\" || $yy == \"04\" || $yy == \"08\" || $yy == \"12\") {@modays = @leap_days}\n\n for($mo=1;$mo<=12;$mo++)\n  {\n    if($julday>$modays[$mo-1] && $julday<=$modays[$mo]) \n     {\n       $mon = $mo;\n       $day = $julday - $modays[$mo-1];\n     }\n  }\n\n  $jday3 = \"$julday\";\n  if($julday<100) {$jday3 = \"0$julday\"};\n  if($julday<10) {$jday3 = \"00$julday\"};\n\nfor $hr (@hrs)\n {\n\n  $file = `ls ${data_dir}/merged_AWIP32.20$yy$nums[$mon]$nums[$day]$hr.RS.sfc`;\n  chop($file);\n\n  system (\"wgrib -s $file | grep ':$var:sfc:0' | wgrib -i -grib $file -o $results_dir/$var/NARR_$var.20$yy$nums[$mon]$nums[$day]$hr.grb \");\n\n }\n }\n } # End of outer time loop\n }\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NARR/fill_DSWRF.f90",
    "content": "program fill_DSWRF\nimplicit none\ninteger,parameter :: maxpts = 96673, lugbin = 10, lugi = 0\ninteger,parameter :: lugbout = 20\ninteger,dimension(200)      :: jpds,jgds,kpds,kgds\nlogical*1,dimension(maxpts) :: lb\nreal,dimension(maxpts)      :: data_in, lat, lon, sum_cza, czaxta\nreal,dimension(maxpts,3)    :: data_out, cza\ninteger                     :: i, iret, j, kf, k, yr(3), mo(3), dy(3), hr(3)\nreal                        :: jday(3), hr_mid(3)\ncharacter*100               :: infile,outfile(3)\nreal, parameter    :: pi = 3.14159265\ninteger, parameter :: testpt = 76401\nlogical, parameter :: debug = .false.\n\nopen(20, file='fill_DSWRF.input', form ='formatted')\n  read(20,'(a100)') infile\n do i=1,3\n  read(20,'(a100)') outfile(i)\n  read(20,*) yr(i), mo(i), dy(i), hr(i), jday(i), hr_mid(i)\n end do\nclose(20)\n\nopen(30, file='NARR_lat', form ='formatted')\ndo i = 0,276\n  read(30,'(349f7.2)') lat( i*349+1 : i*349+349 )\nend do\nclose(30)\nopen(30, file='NARR_lon', form ='formatted')\ndo i = 0,276\n  read(30,'(349f8.2)') lon( i*349+1 : i*349+349 )\nend do\nclose(30)\n\nif (debug) print *, lat(testpt),lon(testpt)\nlat = lat * pi / 180.0\nlon = lon * pi / 180.0\n\n! GET COSINE ZENITH ANGLE ARRAY FOR EACH HOUR\n\ndo i = 1,3\n  call get_cza(jday(i),hr_mid(i),lat,lon,cza(:,i))\nend do\n  call get_cza(jday(3),hr_mid(3)+1,lat,lon,czaxta)\n\nsum_cza = cza(:,1) + 2.0*cza(:,2) + 2.0*cza(:,3) + czaxta  ! the sum of all zenith angles\n\nif (debug) print *, lat(testpt),lon(testpt),cza(testpt,:),sum_cza(testpt)\n\n! READ IN VARIABLE\n\n  call baopenr(lugbin,infile,iret)\n  if(iret/=0) stop 1\n\n! Set GRIB1 field identification values to search for\n\n  j=0      ! search from beginning\n  jgds    =  -1\n  jpds    =  -1\n\n  call getgb(lugbin,lugi,maxpts,j,jpds,jgds,kf,k,kpds,kgds,lb,data_in,iret)\n  if(iret/=0) stop 2\n\n  call baclose(lugbin,iret)\n  if(iret/=0) stop 3\n\n! START MESSING WITH THE INPUT DATA\n\nwhere(data_in < 0) data_in = 0.0\n\ndata_out = 0.0\ndo j = 1, maxpts\n if(sum_cza(j) > 0.0) then\n   do i = 1,3\n     data_out(j,i) = cza(j,i)/sum_cza(j) * data_in(j) * 6.0\n   end do\n end if\nend do\n\n! If there is input solar, but sun is not up at three mid-hours, check if up at hour 4 and put in 3rd hour\n\n!where(sum_cza == 0.0 .and. czaxta > 0.0 .and. data_in > 5.0) data_out(:,3) = data_in * 3.0\n\n! If there is input solar > 5 W/m2, and all 4 hours sun is not up, let me know\n\ndo i = 1, maxpts\n  if(sum_cza(i) == 0.0 .and. data_in(i) > 5.0) &\n    print *, \"Seems to be sun with no sun up\", sum_cza(i),czaxta(i),data_in(i)\nend do\n\n! WRITE OUT TO THE 3 NEW FILES\n\ndo i = 1,3\n\nif (debug) print *, cza(testpt,i), data_out(testpt,i), data_in(testpt)     ! 17820 = lat(50),lon(180)\n\n  kpds(8)  = yr(i)\n  if(yr(i) == 00) then\n    kpds(8)  = 100\n    kpds(21) = 20\n  end if\n  kpds(9)  = mo(i)\n  kpds(10) = dy(i)\n  kpds(11) = hr(i)\n  kpds(15) = 1            ! change number of hours in average to 1\n  kpds(22) = 2            ! preserve 2 decimal points\n\n  call baopenw(lugbout+i,outfile(i),iret)\n  if(iret/=0) stop 4\n\n  call putgb(lugbout+i,maxpts,kpds,kgds,lb,data_out(:,i),iret)\n  if(iret/=0) stop 5\n\n  call baclose(lugbout+i,iret)\n  if(iret/=0) stop 6\n\nend do\n\ncontains\n\nsubroutine get_cza(jday, gmthour, latrad, lonrad, cza)\n  implicit none\n  integer,parameter :: maxpts = 96673\n  real, intent(in) :: jday,gmthour\n  real, intent(in) :: latrad(maxpts)\n  real, intent(in) :: lonrad(maxpts)\n  real, intent(out) :: cza(maxpts)\n\n  real :: gg, tc, declin, sha(maxpts)\n  real, parameter :: pi = 3.14159265\n\n  ! Fractional day of the year, in radians\n  gg = (360./365.25) * (JDAY+gmthour/24.) * pi/180.\n\n  ! Solar declination angle, in radians.\n  DECLIN = 0.006918 - 0.399912*cos(gg) + 0.070257*sin(gg) - 0.006758*cos(2.0*gg) + &\n       0.000907*sin(2.0*gg) - 0.002697*cos(3.0*gg) + 0.00148*sin(3.0*gg)\n\n  ! Time Correction for solar angle, in radians.  Whatever.\n  TC = 0.000075 + 0.001868*cos(gg) - 0.032077*sin(gg) - 0.014615*cos(2.0*gg) - &\n       0.040849*sin(2.0*gg)\n!  TC = 0.0000\n\n  ! Solar Hour Angle, in radians\n  SHA = ((gmthour-12.0)*15.0)*(pi/180.) + lonrad + TC\n  ! SHA = (gmthour*15.0)*(pi/180.) + lonrad + TC\n\n  ! ! Solar Zenith Angle, in radians\n  CZA = sin(latrad)*sin(DECLIN)+cos(latrad)*cos(DECLIN)*cos(SHA)\n  where(cza.lt.0) cza = 0.0\n\nend subroutine get_cza\n\n\nend program fill_DSWRF\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NARR/fill_DSWRF.perl",
    "content": "#!/usr/bin/perl\n\n\n$filename = \"fill_DSWRF\";\n\n$w3lib = '/home/barlage/programs/w3lib-1.6 -lw3';\n\nsystem (\"pgf90 -o $filename $filename.f90 -L$w3lib\");\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n         \"30\",\"31\",\"32\",\"33\",\"34\",\"35\",\"36\",\"37\",\"38\",\"39\",\n\t \"40\",\"41\",\"42\",\"43\",\"44\",\"45\",\"46\",\"47\",\"48\",\"49\",\n\t \"50\",\"51\",\"52\",\"53\",\"54\",\"55\",\"56\",\"57\",\"58\",\"59\",\n\t \"60\",\"61\",\"62\",\"63\",\"64\",\"65\",\"66\",\"67\",\"68\",\"69\",\n\t \"70\",\"71\",\"72\",\"73\",\"74\",\"75\",\"76\",\"77\",\"78\",\"79\",\n\t \"80\",\"81\",\"82\",\"83\",\"84\",\"85\",\"86\",\"87\",\"88\",\"89\",\n\t \"90\",\"91\",\"92\",\"93\",\"94\",\"95\",\"96\",\"97\",\"98\",\"99\");\n\t \n@leap_days    = (0,31,29,31,30,31,30,31,31,30,31,30,31);\n@nonleap_days = (0,31,28,31,30,31,30,31,31,30,31,30,31);\n\n$cc = \"20\";  # Manually set century\n@yrs = (\"10\");\n$start_month = 1;\n$end_month = 1;\n\n$data_dir = \"/d1/barlage/data/NARR/extracted\";\n\nfor $yr (@yrs)\n {\nfor($mo=$start_month; $mo<=$end_month; $mo++)\n {\n  @days = @nonleap_days;\n  if($yr == \"80\" || $yr == \"84\" || $yr == \"88\" || $yr == \"92\" || $yr == \"96\") {@days = @leap_days}\n  if($yr == \"00\" || $yr == \"04\" || $yr == \"08\" || $yr == \"12\") {@days = @leap_days}\n  $jdaymo = 0;\n  for($jmo=0; $jmo<=$mo-1; $jmo++) {$jdaymo = $jdaymo + $days[$jmo]}\n\n#for($dy=1; $dy<=$days[$mo]; $dy++)\nfor($dy=1; $dy<=3; $dy++)\n {\n \n  $jday = $jdaymo + $dy;\n\n  print (\"$yr $mo $dy $jday\\n\");\n \n  $dy_now = $nums[$dy];\n  $mo_now = $nums[$mo];\n  $yr_now = $nums[$yr];\n\nfor($hr=0; $hr<=21; $hr=$hr+3)\n {\n\n # NARR data are 3hr averages valid from file time to file time + 3hrs\n\n  open(FILE, \"> fill_DSWRF.input\") || die print \"Can't open: \\n\";\n\n  $file_in = \"$data_dir/DSWRF/NARR_DSWRF.$cc$yr_now$mo_now$dy_now$nums[$hr].grb\";\n  print FILE \"$file_in \\n\";\n\n   $hr_out = $hr;\n   $file_out = \"$data_dir/DSWRF24/NARR_DSWRF.$cc$yr_now$mo_now$dy_now$nums[$hr_out].grb\";\n   print FILE \"$file_out \\n\";\n   print FILE \"$yr $mo $dy $hr_out $jday $hr_out\\n\";\n\n   $hr_out = $hr + 1;\n   $file_out = \"$data_dir/DSWRF24/NARR_DSWRF.$cc$yr_now$mo_now$dy_now$nums[$hr_out].grb\";\n   print FILE \"$file_out \\n\";\n   print FILE \"$yr $mo $dy $hr_out $jday $hr_out\\n\";\n\n   $hr_out = $hr + 2;\n   $file_out = \"$data_dir/DSWRF24/NARR_DSWRF.$cc$yr_now$mo_now$dy_now$nums[$hr_out].grb\";\n   print FILE \"$file_out \\n\";\n   print FILE \"$yr $mo $dy $hr_out $jday $hr_out\\n\";\n\n # end of file naming mess\n\n  close(FILE);\n\n  system (\"./$filename\");\n\n }\n }\n\n }\n }\nsystem(\"rm $filename\");\nsystem(\"rm $filename.input\");\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NARR/namelist.input.NARR",
    "content": "&files\n STARTDATE          = \"2010-01-01_00\"\n ENDDATE            = \"2010-01-03_00\"\n DATADIR            = \"/d1/barlage/data/NARR/extracted\"\n OUTPUTDIR          = \"/d1/barlage/data/NARR/LDASIN/\"\n FULL_IC_FRQ        = 0\n RAINFALL_INTERP    = 0\n RESCALE_SHORTWAVE  = .FALSE.\n UPDATE_SNOW        = .FALSE.\n FORCING_HEIGHT_2D  = .FALSE.\n TRUNCATE_SW        = .FALSE.\n EXPAND_LOOP        = 1\n INIT_LAI           = .TRUE.\n VARY_LAI           = .TRUE.\n MASK_WATER         = .TRUE.\n\n geo_em_flnm        = \"/d1/barlage/data/mptest/geo_em.d01.nc\"\n\n Zfile_template     = \"examples/NARR/NARR_ELEVATION.grb\"\n LANDSfile_template = \"examples/NARR/NARR.LANDSEA_MASK.grb\",\n\n Tfile_template     = \"<DataDir>/TMP/NARR_TMP.<date>.grb\"\n Ufile_template     = \"<DataDir>/UGRD/NARR_UGRD.<date>.grb\",\n Vfile_template     = \"<DataDir>/VGRD/NARR_VGRD.<date>.grb\",\n Pfile_template     = \"<DataDir>/PRES/NARR_PRES.<date>.grb\",\n Qfile_template     = \"<DataDir>/SPFH/NARR_SPFH.<date>.grb\",\n LWfile_template    = \"<DataDir>/DLWRF/NARR_DLWRF.<date>.grb\",\n SWfile_primary     = \"<DataDir>/DSWRF24/NARR_DSWRF.<date>.grb\",\n SWfile_secondary   = \"<DataDir>/DSWRF24/NARR_DSWRF.<date>.grb\",\n PCPfile_primary    = \"<DataDir>/APCP/NARR_APCP.<date>.grb\",\n PCPfile_secondary  = \"<DataDir>/APCP/NARR_APCP.<date>.grb\",\n\n WEASDfile_template = \"<DataDir>/INIT/NARR_WEASD.<date>.grb\",\n CANWTfile_template = \"<DataDir>/INIT/NARR_CNWAT.<date>.grb\",\n SKINTfile_template = \"<DataDir>/INIT/NARR_TMP:sfc.<date>.grb\",\n STfile_template    = \"<DataDir>/INIT/NARR_TSOIL:0-10.<date>.grb\",\n                      \"<DataDir>/INIT/NARR_TSOIL:10-40.<date>.grb\",\n                      \"<DataDir>/INIT/NARR_TSOIL:40-100.<date>.grb\",\n                      \"<DataDir>/INIT/NARR_TSOIL:100-200.<date>.grb\",\n\n SMfile_template    = \"<DataDir>/INIT/NARR_SOILW:0-10.<date>.grb\",\n                      \"<DataDir>/INIT/NARR_SOILW:10-40.<date>.grb\",\n                      \"<DataDir>/INIT/NARR_SOILW:40-100.<date>.grb\",\n                      \"<DataDir>/INIT/NARR_SOILW:100-200.<date>.grb\",\n\n/\n\n<VTABLE>\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\nGRIB1| Level| From |  To  |          |           |                                         |GRIB2|GRIB2|GRIB2|GRIB2|\nParam| Type |Level1|Level2| Name     | Units     | Description                             |Discp|Catgy|Param|Level|\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n  11 | 105  |  30  |      | T2D      | K         | Temperature       at 30 m               |  0  |  0  |  0  | 103 |\n  51 | 105  |  30  |      | Q2D      | kg/kg     | Specific Humidity at 30 m               |  0  |  1  |  0  | 103 |\n  33 | 105  |  30  |      | U2D      | m/s       | U                 at 30 m               |  0  |  2  |  2  | 103 |\n  34 | 105  |  30  |      | V2D      | m/s       | V                 at 30 m               |  0  |  2  |  3  | 103 |\n   1 | 105  |  30  |      | PSFC     | Pa        | Surface Pressure                        |  0  |  3  |  0  |   1 |\n  61 |   1  |   0  |      | RAINRATE | kg/m^2    | Accumulated precipitation               |  0  |  1  |  8  |   1 |\n 204 |   1  |   0  |      | SWDOWN   | W/m^2     | Downward short-wave radiation flux      |  0  |  4  | 192 |   1 |\n 205 |   1  |   0  |      | LWDOWN   | W/m^2     | Downward long-wave radiation flux       |  0  |  5  | 192 |   1 |\n  81 |   1  |   0  |      | LANDSEA  | proprtn   | Land/Sea flag (1=land,0=sea in NAM)     |  2  |  0  |  0  |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Terrain field of source analysis        |  2  |  0  |  7  |   1 |\n  11 |   1  |   0  |      | TSK      | K         | Skin temperature                        |  0  |  0  |  0  |   1 |\n  65 |   1  |   0  |      | SNOW     | kg/m^2    | Water equivalent snow depth             |  0  |  1  | 13  |   1 |\n 223 |   1  |   0  |      | CANWAT   | kg/m^2    | Plant Canopy Surface Water              |  2  |  0  | 196 |   1 |\n 144 | 112  |   0  |  10  | SMOIS_1  | m^3/m^3   | Soil Moist 0-10 cm below grn layer (Up) |  2  |  0  | 192 | 106 |\n 144 | 112  |  10  |  40  | SMOIS_2  | m^3/m^3   | Soil Moist 10-40 cm below grn layer     |  2  |  0  | 192 | 106 |\n 144 | 112  |  40  | 100  | SMOIS_3  | m^3/m^3   | Soil Moist 40-100 cm below grn layer    |  2  |  0  | 192 | 106 |\n 144 | 112  | 100  | 200  | SMOIS_4  | m^3/m^3   | Soil Moist 100-200 cm below gr layer    |  2  |  0  | 192 | 106 |\n  85 | 112  |   0  |  10  | STEMP_1  | K         | T 0-10 cm below ground layer (Upper)    |  2  |  0  |  2  | 106 |\n  85 | 112  |  10  |  40  | STEMP_2  | K         | T 10-40 cm below ground layer (Upper)   |  2  |  0  |  2  | 106 |\n  85 | 112  |  40  | 100  | STEMP_3  | K         | T 40-100 cm below ground layer (Upper)  |  2  |  0  |  2  | 106 |\n  85 | 112  | 100  | 200  | STEMP_4  | K         | T 100-200 cm below ground layer (Bottom)|  2  |  0  |  2  | 106 |\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n</VTABLE>\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NLDAS/extract_nldas.perl",
    "content": "#!/usr/bin/perl\n\n@nums = (\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \n\t \"30\",\"31\");\n\n@yrs = (\"10\");\n\n$day_start = 1;\n$day_end   = 3;\n\n$cc = \"20\";   # Manually set the century\n\n@noleap_days = (0,31,59,90,120,151,181,212,243,273,304,334,365);\n@leap_days   = (0,31,60,91,121,152,182,213,244,274,305,335,366);\n\n@vars = (\"DLWRF\",\"DSWRF\",\"APCP\",\"PRES\",\"TMP\",\"SPFH\",\"UGRD\",\"VGRD\"); \n\n$data_dir = \"/d1/barlage/data/NLDAS/raw\";\n$results_dir = \"/d1/barlage/data/NLDAS/extracted\";\n\nfor $var (@vars)\n {\nfor $yy (@yrs)\n {\n\n# This is clumsy, but take care of leap years\nif($yy == \"92\" || $yy == \"96\") {$day_end = 366}\nif($yy == \"00\" || $yy == \"04\" || $yy == \"08\" || $yy == \"12\") {$day_end = 366}\n\n@modays = @noleap_days;\nif($yy == \"92\" || $yy == \"96\") {@modays = @leap_days}\nif($yy == \"00\" || $yy == \"04\" || $yy == \"08\" || $yy == \"12\") {@modays = @leap_days}\n\n# This will be the jday time loop\n\nfor($julday=$day_start;$julday<=$day_end;$julday++)\n\n { \n \n # This little section finds the text month and day\n \n for($mo=1;$mo<=12;$mo++)\n  {\n    if($julday>$modays[$mo-1] && $julday<=$modays[$mo]) \n     {\n       $mon = $mo;\n       $day = $julday - $modays[$mo-1];\n     }\n  }\n\n for($hr=0;$hr<=23;$hr++)\n {\n\n   $file = \"$data_dir/NLDAS_FORA0125_H.A$cc$yy$nums[$mon]$nums[$day].$nums[$hr]00.002.grb\";\n\n   system (\"wgrib -s $file | grep ':$var:' | wgrib -i -grib $file -o $results_dir/$var/NLDAS_$var.$cc$yy$nums[$mon]$nums[$day]$nums[$hr].grb \");\n\n }\n }\n } # End of outer time loop\n }\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NLDAS/extract_nldas_init.perl",
    "content": "#!/usr/bin/perl\n\n\t \n$date = \"20100101\";   # Manually set the date\n$hh = \"00\";           # Manually set the hour\n\n@vars = (\"WEASD\",\"CNWAT\",\"AVSFT\",\"SOILM\",\"TSOIL\"); \n\n$data_dir = \"/d1/barlage/data/NLDAS/raw\";\n$results_dir = \"/d1/barlage/data/NLDAS/extracted/INIT\";\n\nfor $var (@vars)\n {\n\n  $file = \"$data_dir/NLDAS_NOAH0125_H.A$date.${hh}00.002.grb\";\n\n  if($var eq \"SOILM\" || $var eq \"TSOIL\") \n   {\n     system (\"wgrib -s $file | grep ':$var:0-10 ' | wgrib -i -grib $file -o $results_dir/NLDAS_${var}_000-010.$date$hh.grb \");\n     system (\"wgrib -s $file | grep ':$var:10-40' | wgrib -i -grib $file -o $results_dir/NLDAS_${var}_010-040.$date$hh.grb \");\n     system (\"wgrib -s $file | grep ':$var:40-100' | wgrib -i -grib $file -o $results_dir/NLDAS_${var}_040-100.$date$hh.grb \");\n     system (\"wgrib -s $file | grep ':$var:100-200' | wgrib -i -grib $file -o $results_dir/NLDAS_${var}_100-200.$date$hh.grb \");\n   } else\n   {\n     system (\"wgrib -s $file | grep ':$var:' | wgrib -i -grib $file -o $results_dir/NLDAS_$var.$date$hh.grb \");\n   }\n\n }\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/NLDAS/namelist.input.NLDAS",
    "content": "&files\n STARTDATE          = \"2010-01-01_00\"\n ENDDATE            = \"2010-01-03_00\"\n DataDir            = \"/d1/barlage/data/NLDAS/extracted\"\n OutputDir          = \"/d1/barlage/data/NLDAS/LDASIN/\"\n FULL_IC_FRQ        = 0\n RAINFALL_INTERP    = 0\n RESCALE_SHORTWAVE  = .FALSE.\n UPDATE_SNOW        = .FALSE.\n FORCING_HEIGHT_2D  = .FALSE.\n TRUNCATE_SW        = .FALSE.\n EXPAND_LOOP        = 1\n INIT_LAI           = .TRUE.\n VARY_LAI           = .TRUE.\n MASK_WATER         = .TRUE.\n\n geo_em_flnm        = \"/d1/barlage/data/mptest/geo_em.d01.nc\"\n\n Zfile_template     = \"examples/NLDAS/NLDAS_ELEVATION.grb\"\n\n Tfile_template     = \"<DataDir>/TMP/NLDAS_TMP.<date>.grb\"\n Ufile_template     = \"<DataDir>/UGRD/NLDAS_UGRD.<date>.grb\",\n Vfile_template     = \"<DataDir>/VGRD/NLDAS_VGRD.<date>.grb\",\n Pfile_template     = \"<DataDir>/PRES/NLDAS_PRES.<date>.grb\",\n Qfile_template     = \"<DataDir>/SPFH/NLDAS_SPFH.<date>.grb\",\n LWfile_template    = \"<DataDir>/DLWRF/NLDAS_DLWRF.<date>.grb\",\n SWfile_primary     = \"<DataDir>/DSWRF/NLDAS_DSWRF.<date>.grb\",\n SWfile_secondary   = \"<DataDir>/DSWRF/NLDAS_DSWRF.<date>.grb\",\n PCPfile_primary    = \"<DataDir>/APCP/NLDAS_APCP.<date>.grb\"\n PCPfile_secondary  = \"<DataDir>/APCP/NLDAS_APCP.<date>.grb\",\n\n WEASDfile_template = \"<DataDir>/INIT/NLDAS_WEASD.<date>.grb\",\n CANWTfile_template = \"<DataDir>/INIT/NLDAS_CNWAT.<date>.grb\",\n SKINTfile_template = \"<DataDir>/INIT/NLDAS_AVSFT.<date>.grb\",\n\n STfile_template    = \"<DataDir>/INIT/NLDAS_TSOIL_000-010.<date>.grb\",\n                      \"<DataDir>/INIT/NLDAS_TSOIL_010-040.<date>.grb\",\n                      \"<DataDir>/INIT/NLDAS_TSOIL_040-100.<date>.grb\",\n                      \"<DataDir>/INIT/NLDAS_TSOIL_100-200.<date>.grb\",\n\n SMfile_template    = \"<DataDir>/INIT/NLDAS_SOILM_000-010.<date>.grb\",\n                      \"<DataDir>/INIT/NLDAS_SOILM_010-040.<date>.grb\",\n                      \"<DataDir>/INIT/NLDAS_SOILM_040-100.<date>.grb\",\n                      \"<DataDir>/INIT/NLDAS_SOILM_100-200.<date>.grb\",\n\n/\n\n<VTABLE>\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\nGRIB1| Level| From |  To  |          |           |                                         |GRIB2|GRIB2|GRIB2|GRIB2|\nParam| Type |Level1|Level2| Name     | Units     | Description                             |Discp|Catgy|Param|Level|\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n  11 | 105  |   2  |      | T2D      | K         | Temperature       at 2 m                |  0  |  0  |  0  | 103 |\n  51 | 105  |   2  |      | Q2D      | kg/kg     | Specific Humidity at 2 m                |  0  |  1  |  0  | 103 |\n  33 | 105  |  10  |      | U2D      | m/s       | U                 at 10 m               |  0  |  2  |  2  | 103 |\n  34 | 105  |  10  |      | V2D      | m/s       | V                 at 10 m               |  0  |  2  |  3  | 103 |\n   1 |   1  |   0  |      | PSFC     | Pa        | Surface Pressure                        |  0  |  3  |  0  |   1 |\n  61 |   1  |   0  |      | RAINRATE | kg/m^2    | Accumulated precipitation               |  0  |  1  |  8  |   1 |\n 204 |   1  |   0  |      | SWDOWN   | W/m^2     | Downward short-wave radiation flux      |  0  |  4  | 192 |   1 |\n 205 |   1  |   0  |      | LWDOWN   | W/m^2     | Downward long-wave radiation flux       |  0  |  5  | 192 |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Terrain field of source analysis        |  2  |  0  |  7  |   1 |\n 148 |   1  |   0  |      | TSK      | K         | Skin temperature                        |  0  |  0  |  0  |   1 |\n  65 |   1  |   0  |      | SNOW     | kg/m^2    | Water equivalent snow depth             |  0  |  1  | 13  |   1 |\n 223 |   1  |   0  |      | CANWAT   | kg/m^2    | Plant Canopy Surface Water              |  2  |  0  | 196 |   1 |\n  86 | 112  |   0  |  10  | SMOIS_1  | kg/m^2    | Soil Moist 0-10 cm below grn layer (Up) |  2  |  0  | 192 | 106 |\n  86 | 112  |  10  |  40  | SMOIS_2  | kg/m^2    | Soil Moist 10-40 cm below grn layer     |  2  |  0  | 192 | 106 |\n  86 | 112  |  40  | 100  | SMOIS_3  | kg/m^2    | Soil Moist 40-100 cm below grn layer    |  2  |  0  | 192 | 106 |\n  86 | 112  | 100  | 200  | SMOIS_4  | kg/m^2    | Soil Moist 100-200 cm below gr layer    |  2  |  0  | 192 | 106 |\n  85 | 112  |   0  |  10  | STEMP_1  | K         | T 0-10 cm below ground layer (Upper)    |  2  |  0  |  2  | 106 |\n  85 | 112  |  10  |  40  | STEMP_2  | K         | T 10-40 cm below ground layer (Upper)   |  2  |  0  |  2  | 106 |\n  85 | 112  |  40  | 100  | STEMP_3  | K         | T 40-100 cm below ground layer (Upper)  |  2  |  0  |  2  | 106 |\n  85 | 112  | 100  | 200  | STEMP_4  | K         | T 100-200 cm below ground layer (Bottom)|  2  |  0  |  2  | 106 |\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n</VTABLE>\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/namelist.example.complex",
    "content": "&files\n\n STARTDATE        = \"2001-01-01_00\"\n ENDDATE          = \"2002-07-01_00\"\n DataDir          = \"/d2/hrldas/raw\"\n \n RAINFALL_INTERP  = 0\n\n geo_em_flnm      = \"/home/kmanning/grids/geo_em.d01.nc\"\n wrfinput_flnm    = \"/home/kmanning/grids/wrfinput_d01\"\n\n Zfile_template     = \"/d2/kmanning/hrldas_rawdata/ETA_SFC_ELEVATION.GRIB\"\n\n Tfile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.T.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.T.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.T.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.T.<date>.grb\",\n\n Ufile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.U.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.U.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.U.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.U.<date>.grb\",\n\n Vfile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.V.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.V.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.V.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.V.<date>.grb\",\n                      \n Pfile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.P.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.P.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.P.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.P.<date>.grb\",\n\t              \n Qfile_template     = \"<DataDir>/NDAS/<init+12>/NDAS.Q.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.Q.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.Q.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.Q.<date>.grb\",\n\n LWfile_template    = \"<DataDir>/NAM/<init-12>/NAM.LW.<date>.grb\",\n\t              \"<DataDir>/NAM/<init-24>/NAM.LW.<date>.grb\",\n\t              \"<DataDir>/NAM/<init-36>/NAM.LW.<date>.grb\",\n\n WEASDfile_template = \"<DataDir>/NAM/<init-12>/NAM.WEASD.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.WEASD.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.WEASD.<date>.grb\",\n\n CANWTfile_template = \"<DataDir>/NAM/<init-12>/NAM.CANWAT.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.CANWAT.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.CANWAT.<date>.grb\",\n\n LANDSfile_template = \"<DataDir>/NAM/<init-12>/NAM.LANDSEA.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.LANDSEA.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.LANDSEA.<date>.grb\",\n\n SKINTfile_template = \"<DataDir>/NAM/<init-12>/NAM.SKINTEMP.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SKINTEMP.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SKINTEMP.<date>.grb\",\n\n STfile_template    = \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_T_000-010.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_T_010-040.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_T_040-100.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_T_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_T_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_T_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_T_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_T_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_T_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_T_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_T_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_T_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_T_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_T_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_T_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_T_100-200.<date>.grb\",\n\n SMfile_template    = \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_M_000-010.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_M_010-040.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_M_040-100.<date>.grb\",\n                      \"<DataDir>/NDAS/<init+12>/NDAS.SOIL_M_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_M_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_M_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_M_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-12>/NAM.SOIL_M_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_M_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_M_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_M_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SOIL_M_100-200.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_M_000-010.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_M_010-040.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_M_040-100.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SOIL_M_100-200.<date>.grb\",\n\n SWfile_primary     = \"<DataDir>/SRB/<YYYY><MM><DD>/SW.<date>.grb\",\n\n SWfile_secondary   = \"<DataDir>/NAM/<init-12>/NAM.SW.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.SW.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.SW.<date>.grb\",\n\n PCPfile_primary    = \"<DataDir>/ST4/<YYYY><MM><DD>/ST4.<date>.grb\",\n\n PCPfile_secondary  = \"<DataDir>/NAM/<init-12>/NAM.PCP.<date>.grb\",\n                      \"<DataDir>/NAM/<init-24>/NAM.PCP.<date>.grb\",\n                      \"<DataDir>/NAM/<init-36>/NAM.PCP.<date>.grb\",\n\n/\n\n<VTABLE>\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\nGRIB1| Level| From |  To  |          |           |                                         |GRIB2|GRIB2|GRIB2|GRIB2|\nParam| Type |Level1|Level2| Name     | Units     | Description                             |Discp|Catgy|Param|Level|\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n  11 | 105  |   2  |      | T2D      | K         | Temperature       at 2 m                |  0  |  0  |  0  | 103 |\n  51 | 105  |   2  |      | Q2D      | kg kg{-1} | Specific Humidity at 2 m                |  0  |  1  |  0  | 103 |\n  33 | 105  |  10  |      | U2D      | m s-1     | U                 at 10 m               |  0  |  2  |  2  | 103 |\n  34 | 105  |  10  |      | V2D      | m s-1     | V                 at 10 m               |  0  |  2  |  3  | 103 |\n   1 |   1  |   0  |      | PSFC     | Pa        | Surface Pressure                        |  0  |  3  |  0  |   1 |\n 144 | 112  |   0  |  10  | SMOIS_1  | kg m-3    | Soil Moist 0-10 cm below grn layer (Up) |  2  |  0  | 192 | 106 |\n 144 | 112  |  10  |  40  | SMOIS_2  | kg m-3    | Soil Moist 10-40 cm below grn layer     |  2  |  0  | 192 | 106 |\n 144 | 112  |  40  | 100  | SMOIS_3  | kg m-3    | Soil Moist 40-100 cm below grn layer    |  2  |  0  | 192 | 106 |\n 144 | 112  | 100  | 200  | SMOIS_4  | kg m-3    | Soil Moist 100-200 cm below gr layer    |  2  |  0  | 192 | 106 |\n  85 | 112  |   0  |  10  | STEMP_1  | K         | T 0-10 cm below ground layer (Upper)    |  2  |  0  |  2  | 106 |\n  85 | 112  |  10  |  40  | STEMP_2  | K         | T 10-40 cm below ground layer (Upper)   |  2  |  0  |  2  | 106 |\n  85 | 112  |  40  | 100  | STEMP_3  | K         | T 40-100 cm below ground layer (Upper)  |  2  |  0  |  2  | 106 |\n  85 | 112  | 100  | 200  | STEMP_4  | K         | T 100-200 cm below ground layer (Bottom)|  2  |  0  |  2  | 106 |\n  91 |   1  |   0  |      | SEAICE   | proprtn   | Ice flag                                | 10  |  2  |  0  |   1 |\n  81 |   1  |   0  |      | LANDSEA  | proprtn   | Land/Sea flag (1=land,0=sea in NAM)     |  2  |  0  |  0  |   1 |\n  11 |   1  |   0  |      | SKINTEMP | K         | Skin temperature (can use for SST also) |  0  |  0  |  0  |   1 |\n  61 |   1  |   0  |      | RAINFALL | kg m-2    | Accumulated precipitation               |  0  |  1  |  8  |   1 |\n  65 |   1  |   0  |      | WEASD    | kg m-2    | Water equivalent snow depth             |  0  |  1  | 13  |   1 |\n 223 |   1  |   0  |      | CANWAT   | kg m-2    | Plant Canopy Surface Water              |  2  |  0  | 196 |   1 |\n 204 |   1  |   0  |      | SW       | W m-2     | Downward short-wave radiation flux      |  0  |  4  | 192 |   1 |\n 205 |   1  |   0  |      | LW       | W m-2     | Downward long-wave radiation flux       |  0  |  5  | 192 |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Terrain field of source analysis        |  2  |  0  |  7  |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Source model terrain elevation          |  0  |  3  |  5  |   1 |\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n</VTABLE>\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/namelist.example.simple",
    "content": "&files\n STARTDATE        = \"2001-01-01_00\"\n ENDDATE          = \"2002-07-01_00\"\n DataDir          = \"/wig/kmanning/HRLDAS_FORCING_RAW\"\n\n RAINFALL_INTERP  = 0\n\n geo_em_flnm      = \"/wig/kmanning/more_hrldas/HRLDAS/for_cb_test/geo_em.d01.nc\"\n wrfinput_flnm    = \"/wig/kmanning/more_hrldas/HRLDAS/for_cb_test/wrfinput_d01\"\n\n Zfile_template     = \"<DataDir>/ETA_SFC_ELEVATION.GRIB\"\n\n Tfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.T.<date>\"\n Ufile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.U.<date>\",\n Vfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.V.<date>\",\n Pfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.P.<date>\",\n Qfile_template     = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.Q.<date>\",\n LWfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.LW.<date>\",\n WEASDfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.WEASD.<date>\",\n CANWTfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.CANWAT.<date>\",\n LANDSfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.LANDSEA.<date>\",\n SKINTfile_template = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SKINTEMP.<date>\",\n\n STfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_000-010.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_010-040.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_040-100.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_T_100-200.<date>\",\n\n SMfile_template    = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_000-010.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_010-040.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_040-100.<date>\",\n                      \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFanal.SOIL_M_100-200.<date>\",\n\n SWfile_primary     = \"<DataDir>/SRB_restamped/SW.<date>30.grb\",\n SWfile_secondary   = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.SW.<date>\",\n\n PCPfile_primary    = \"<DataDir>/<YYYY>/<MM>/<DD>/ST4.<date>.01h\"\n PCPfile_secondary  = \"<DataDir>/<YYYY>/<MM>/<DD>/EDAS.SFfcst.PCP.<date>\",\n/\n\n<VTABLE>\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\nGRIB1| Level| From |  To  |          |           |                                         |GRIB2|GRIB2|GRIB2|GRIB2|\nParam| Type |Level1|Level2| Name     | Units     | Description                             |Discp|Catgy|Param|Level|\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n  11 | 105  |   2  |      | T2D      | K         | Temperature       at 2 m                |  0  |  0  |  0  | 103 |\n  51 | 105  |   2  |      | Q2D      | kg kg{-1} | Specific Humidity at 2 m                |  0  |  1  |  0  | 103 |\n  33 | 105  |  10  |      | U2D      | m s-1     | U                 at 10 m               |  0  |  2  |  2  | 103 |\n  34 | 105  |  10  |      | V2D      | m s-1     | V                 at 10 m               |  0  |  2  |  3  | 103 |\n   1 |   1  |   0  |      | PSFC     | Pa        | Surface Pressure                        |  0  |  3  |  0  |   1 |\n 144 | 112  |   0  |  10  | SMOIS_1  | kg m-3    | Soil Moist 0-10 cm below grn layer (Up) |  2  |  0  | 192 | 106 |\n 144 | 112  |  10  |  40  | SMOIS_2  | kg m-3    | Soil Moist 10-40 cm below grn layer     |  2  |  0  | 192 | 106 |\n 144 | 112  |  40  | 100  | SMOIS_3  | kg m-3    | Soil Moist 40-100 cm below grn layer    |  2  |  0  | 192 | 106 |\n 144 | 112  | 100  | 200  | SMOIS_4  | kg m-3    | Soil Moist 100-200 cm below gr layer    |  2  |  0  | 192 | 106 |\n  85 | 112  |   0  |  10  | STEMP_1  | K         | T 0-10 cm below ground layer (Upper)    |  2  |  0  |  2  | 106 |\n  85 | 112  |  10  |  40  | STEMP_2  | K         | T 10-40 cm below ground layer (Upper)   |  2  |  0  |  2  | 106 |\n  85 | 112  |  40  | 100  | STEMP_3  | K         | T 40-100 cm below ground layer (Upper)  |  2  |  0  |  2  | 106 |\n  85 | 112  | 100  | 200  | STEMP_4  | K         | T 100-200 cm below ground layer (Bottom)|  2  |  0  |  2  | 106 |\n  91 |   1  |   0  |      | SEAICE   | proprtn   | Ice flag                                | 10  |  2  |  0  |   1 |\n  81 |   1  |   0  |      | LANDSEA  | proprtn   | Land/Sea flag (1=land,0=sea in NAM)     |  2  |  0  |  0  |   1 |\n   7 |   1  |   0  |      | TERRAIN  | m         | Terrain field of source analysis        |  2  |  0  |  7  |   1 |\n  11 |   1  |   0  |      | SKINTEMP | K         | Skin temperature (can use for SST also) |  0  |  0  |  0  |   1 |\n  61 |   1  |   0  |      | RAINRATE | kg m-2    | Accumulated precipitation               |  0  |  1  |  8  |   1 |\n  65 |   1  |   0  |      | WEASD    | kg m-2    | Water equivalent snow depth             |  0  |  1  | 13  |   1 |\n 223 |   1  |   0  |      | CANWAT   | kg m-2    | Plant Canopy Surface Water              |  2  |  0  | 196 |   1 |\n 204 |   1  |   0  |      | SWDOWN   | W m-2     | Downward short-wave radiation flux      |  0  |  4  | 192 |   1 |\n 205 |   1  |   0  |      | LWDOWN   | W m-2     | Downward long-wave radiation flux       |  0  |  5  | 192 |   1 |\n 999 | 999  |   0  |      | TERRAIN  | m         | Source model terrain elevation          |  0  |  3  |  5  |   1 |\n-----+------+------+------+----------+-----------+-----------------------------------------+-----------------------+\n</VTABLE>\n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/vector/create_ldasin_files.ncl",
    "content": ";;;\n;;;  This script created by Barlage to provide some guidance on how to create\n;;;   HRLDAS forcing files for point-based simulations\n;;;\n\n\nload \"$NCARG_ROOT/lib/ncarg/nclex/gsun/gsn_code.ncl\"\nload \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl\"\nload \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl\"  \n\nbegin\n\nyyyy_start = 2012     ; time you want to start creating forcing\n  mm_start = 2\n  dd_start = 1\n  hh_start = 0\n\nhh_spacing = 1        ; number of hours between forcing files\n\ntotal_timesteps = 49  ; set manually\nnumber_stations = 3\n\nnums = (/\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\", \\\n         \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\", \\\n\t \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\", \\\n\t \"30\",\"31\" /)\nddinmm = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n\nprecip_input = new((/total_timesteps,number_stations/),float)\nswdown_input = new((/total_timesteps,number_stations/),float)\nlwdown_input = new((/total_timesteps,number_stations/),float)\nsfctmp_input = new((/total_timesteps,number_stations/),float)\nspechu_input = new((/total_timesteps,number_stations/),float)\nu_wind_input = new((/total_timesteps,number_stations/),float)\nv_wind_input = new((/total_timesteps,number_stations/),float)\nsfcprs_input = new((/total_timesteps,number_stations/),float)\n\n;;;;;;;;;;;;\n; READ YOUR FORCING DATA INTO DATA STRUCTURES\n;\n; YOU WILL NEED THE FOLLOWING:\n;    PRECIPITATION RATE [mm/s]\n;    DOWNWARD SOLAR [W/m^2]\n;    DOWNWARD LONGWAVE [W/m^2]\n;    TEMPERATURE [K]\n;    SPECIFIC HUMIDITY [kg/kg]\n;    U/V WIND COMPONENTS [m/s] (the model doesn't care about direction)\n;    PRESSURE [Pa]\n;    \n;    ***********Note: you may need to adjust units*************\n;;;;;;;;;;;;\n\nstation1 = readAsciiTable(\"location1.dat\" , 13, \"float\", 0)\nstation2 = readAsciiTable(\"location2.dat\" , 13, \"float\", 0)\nstation3 = readAsciiTable(\"location3.dat\" , 13, \"float\", 0)\n\nprecip_input(:,0) = station1(:,12)  ; precip in column 13 in example\nprecip_input(:,1) = station2(:,12)\nprecip_input(:,2) = station3(:,12)\n\nswdown_input(:,0) = station1(:,10)  ; shortwave down in column 11 in example\nswdown_input(:,1) = station2(:,10)\nswdown_input(:,2) = station3(:,10)\n\nlwdown_input(:,0) = station1(:,11)  ; longwave down in column 12 in example\nlwdown_input(:,1) = station2(:,11)\nlwdown_input(:,2) = station3(:,11)\n\nsfctmp_input(:,0) = station1(:,7)   ; temperature in column 8 in example\nsfctmp_input(:,1) = station2(:,7)\nsfctmp_input(:,2) = station3(:,7)\n\nu_wind_input(:,0) = station1(:,5)   ; wind speed in column 6 in example\nu_wind_input(:,1) = station2(:,5)\nu_wind_input(:,2) = station3(:,5)\n\nv_wind_input(:,0) = 0.0             ; direction doesn't matter so set v=0\nv_wind_input(:,1) = 0.0\nv_wind_input(:,2) = 0.0\n\nsfcprs_input(:,0) = station1(:,9) * 100.0   ; pressure in column 10 in example\nsfcprs_input(:,1) = station2(:,9) * 100.0   ; convert from hPa to Pa\nsfcprs_input(:,2) = station3(:,9) * 100.0\n\n; RELATIVE humidity in column 9; convert to SPECIFIC humidity\n;   1. calculate saturation vapor pressure from temperature\n;   2. calculate vapor pressure from RH and 1.\n;   3. calcuate spec hum using pressure and 2.\n\nspechu_input(:,0) = station1(:,8)   ; this is actually RH in example\nspechu_input(:,1) = station2(:,8)\nspechu_input(:,2) = station3(:,8)\n\nsvp = 611.2*exp(17.67*(sfctmp_input-273.15)/(sfctmp_input-29.65)) ; [Pa]\ne   = spechu_input/100.0 * svp                                    ; [Pa]\nspechu_input = (0.622*e)/(sfcprs_input-(1.0-0.622)*e) ; now it is specific humidity\n\n; DONE FILLING INPUT DATA STRUCTURE, NOW MOVE TO FORCING FILES\n;\n; Shouldn't need to modify anything below\n\ndo istep = 0, total_timesteps - 1\n\n filename = yyyy_start+nums(mm_start)+nums(dd_start)+nums(hh_start)+\".LDASIN_DOMAIN1\"\n print( \"Starting creation of: \"+ filename )\n \n outfile = addfile(filename+\".nc\",\"c\")\n filedimdef(outfile,(/\"Time\",\"south_north\",\"west_east\"/),(/1,1,number_stations/),(/True,False,False/))\n \n vartmp = new((/1,1,number_stations/),\"float\")\n vartmp!0 = \"Time\"\n vartmp!1 = \"south_north\"\n vartmp!2 = \"west_east\"\n \n vartmp(0,0,:) = (/ sfctmp_input(istep,:) /)  ; fill temporary structure with forcing\n vartmp@units = \"K\"\n outfile->T2D = vartmp\n \n vartmp(0,0,:) = (/ spechu_input(istep,:) /)  ; fill temporary structure with forcing\n vartmp@units = \"kg/kg\"\n outfile->Q2D = vartmp\n \n vartmp(0,0,:) = (/ u_wind_input(istep,:) /)  ; fill temporary structure with forcing\n vartmp@units = \"m/s\"\n outfile->U2D = vartmp\n\n vartmp(0,0,:) = (/ v_wind_input(istep,:) /)  ; fill temporary structure with forcing\n vartmp@units = \"m/s\"\n outfile->V2D = vartmp\n\n vartmp(0,0,:) = (/ sfcprs_input(istep,:) /)  ; fill temporary structure with forcing\n vartmp@units = \"Pa\"\n outfile->PSFC = vartmp\n\n vartmp(0,0,:) = (/ precip_input(istep,:) /)  ; fill temporary structure with forcing\n vartmp@units = \"mm/s\"\n outfile->RAINRATE = vartmp\n \n vartmp(0,0,:) = (/ swdown_input(istep,:) /)  ; fill temporary structure with forcing\n vartmp@units = \"W/m^2\"\n outfile->SWDOWN = vartmp\n \n vartmp(0,0,:) = (/ lwdown_input(istep,:) /)  ; fill temporary structure with forcing\n vartmp@units = \"W/m^2\"\n outfile->LWDOWN = vartmp\n \n delete(vartmp)\n \n system(\"mv \"+filename+\".nc \"+filename)  ; get rid of the .nc\n \n ; now increment the time\n \n if(mod(yyyy_start,4).eq.0) then  ; take care of leap years, add more if necessary\n   ddinmm(1) = 29\n end if\n\n hh_start = hh_start + hh_spacing\n if(hh_start .gt. 23) then\n   dd_start = dd_start + 1\n   hh_start = hh_start - 24\n end if\n \n if(dd_start .gt. ddinmm(mm_start-1)) then\n   mm_start = mm_start + 1\n   dd_start = 1\n end if\n \n if(mm_start .gt. 12) then\n   yyyy_start = yyyy_start + 1\n   mm_start = 1\n end if\n \nend do\n\nend\n\n \n"
  },
  {
    "path": "src/Land_models/NoahMP/HRLDAS_forcing/run/examples/vector/create_setup.ncl",
    "content": "load \"$NCARG_ROOT/lib/ncarg/nclex/gsun/gsn_code.ncl\"\nload \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl\"\nload \"$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl\"  \n\nbegin\n\n; manually create a SETUP file from observations\n;    file will contain both initial conditions and location information\n\ninitial_date = \"2012020100\"        ; time you want to start simulation\nnumber_stations = 3\n\nsetup_filename = \"HRLDAS_setup_\"+initial_date+\"_d1\"\n\nsystem(\"if [ -e \"+setup_filename+\".nc ]; then rm -f \"+setup_filename+ \".nc;fi\")\n\noutfile = addfile(setup_filename+\".nc\",\"c\")\n filedimdef(outfile,(/\"Time\",\"south_north\",    \"west_east\",\"soil_layers_stag\"/), \\\n                    (/     1,            1,number_stations,                 4/), \\\n\t\t    (/  True,        False,          False,             False/))\n\n; Define some temporary variables\n\n vartmp = new((/1,1,number_stations/),\"float\")\n vartmp!0 = \"Time\"\n vartmp!1 = \"south_north\"\n vartmp!2 = \"west_east\"\n \n var3tmp = new((/1,4,1,number_stations/),\"float\")\n var3tmp!0 = \"Time\"\n var3tmp!1 = \"soil_layers_stag\"\n var3tmp!2 = \"south_north\"\n var3tmp!3 = \"west_east\"\n \n ivartmp = new((/1,1,number_stations/),\"integer\")\n ivartmp!0 = \"Time\"\n ivartmp!1 = \"south_north\"\n ivartmp!2 = \"west_east\"\n\n varztmp = new((/1,4/),\"float\")\n varztmp!0 = \"Time\"\n varztmp!1 = \"soil_layers_stag\"\n \n; Set up the time\n\n timestring = \"2012-02-01_00:00:00\"\n timetemp = stringtochar(timestring)\n timechar = new((/1,19/),\"character\")\n timechar(0,:) = timetemp(0:18)\n timechar!0 = \"Time\"\n timechar!1 = \"DateStrLen\"\n \n   outfile->Times = timechar\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;; Set up the location-specific information\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n\n vartmp(0,0,:) = (/31.62,31.04,30.78/)     ;  set the latitude\n   vartmp@units = \"degrees_north\"\n \n   outfile->XLAT = vartmp\n\n vartmp(0,0,:) = (/-95.08,-97.25,-96.72/)  ;  set the longitude\n   vartmp@units = \"degrees_east\"\n  \n   outfile->XLONG = vartmp\n\n vartmp(0,0,:) = (/290.0,290.0,290.0/)     ;  set the deep soil temperature\n   vartmp@units = \"K\"\n \n   outfile->TMN = vartmp\n\n vartmp(0,0,:) = (/100.0,100.0,100.0/)     ;  set the elevation\n   vartmp@units = \"m\"\n \n   outfile->HGT = vartmp\n\n vartmp(0,0,:) = (/0.0,0.0,0.0/)           ;  set the seaice (shouldn't be used since the points\n   vartmp@units = \"\"                       ;   should be land\n                                           \n   outfile->SEAICE = vartmp\n\n vartmp(0,0,:) = (/0.0,0.0,0.0/)           ;  for future use\n   vartmp@units = \"\"\n \n   outfile->MAPFAC_MX = vartmp\n\n vartmp(0,0,:) = (/0.0,0.0,0.0/)           ;  for future use\n   vartmp@units = \"\"\n \n   outfile->MAPFAC_MY = vartmp\n\n vartmp(0,0,:) = (/95.0,95.0,95.0/)        ;  set the maximum annual vegetation fraction\n   vartmp@units = \"%\"\n \n   outfile->SHDMAX = vartmp\n\n vartmp(0,0,:) = (/95.0,95.0,95.0/)        ;  set the minimum annual vegetation fraction\n   vartmp@units = \"%\"\n \n   outfile->SHDMIN = vartmp\n\n vartmp(0,0,:) = (/2.0,2.0,2.0/)           ;  set the LAI (will initialized dynamic vegetation)\n   vartmp@units = \"m^2/m^2\"\n \n   outfile->LAI = vartmp\n\n ivartmp(0,0,:) = (/1,1,1/)                ;  set the landmask (1 = land)\n   ivartmp@units = \"\"\n \n outfile->XLAND = ivartmp\n\n ivartmp(0,0,:) = (/10,10,10/)             ;  set the land class types of each point\n   ivartmp@units = \"\"                      ;  needs to be based on either MODIS or USGS class scheme\n\t\t\t\t\t   ;  make sure you set these below for consistency:\n\t\t\t\t\t   ;      outfile@MMINLU\n\t\t\t\t\t   ;      outfile@ISWATER\n\t\t\t\t\t   ;      outfile@ISURBAN\n\t\t\t\t\t   ;      outfile@ISICE\n  \n   outfile->IVGTYP = ivartmp\n\n ivartmp(0,0,:) = (/12,9,3/)               ;  set the soil texture class types of each point\n   ivartmp@units = \"\"\n \n outfile->ISLTYP = ivartmp\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;  State initialization here\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n vartmp(0,0,:) = (/0.0,0.0,0.0/)           ;  set the initial SWE\n   vartmp@units = \"kg/m^2\"\n \n outfile->SNOW = vartmp\n\n vartmp(0,0,:) = (/0.0,0.0,0.0/)           ;  set the initial canopy water content\n   vartmp@units = \"kg/m^2\"\n \n outfile->CANWAT = vartmp\n\n vartmp(0,0,:) = (/300.0,300.0,300.0/)     ;  set the initial surface temperature\n   vartmp@units = \"K\"\n \n outfile->TSK = vartmp\n \n varztmp(0,:) = (/0.1,0.3,0.6,1.0/)        ;  set the soil layer thicknesses\n   varztmp@units = \"m\"\n \n outfile->DZS = varztmp\n \n varztmp(0,:) = (/0.05,0.25,0.7,1.5/)      ;  set the soil layer nodes\n   varztmp@units = \"m\"\n \n outfile->ZS = varztmp\n \n var3tmp(0,0,0,:) = (/300.0,300.0,300.0/)  ;  set the initial soil temperature: layer 1\n var3tmp(0,1,0,:) = (/300.0,300.0,300.0/)  ;  set the initial soil temperature: layer 2\n var3tmp(0,2,0,:) = (/300.0,300.0,300.0/)  ;  set the initial soil temperature: layer 3\n var3tmp(0,3,0,:) = (/300.0,300.0,300.0/)  ;  set the initial soil temperature: layer 4\n   var3tmp@units = \"K\"\n \n outfile->TSLB = var3tmp\n\n var3tmp(0,0,0,:) = (/0.2,0.2,0.2/)        ;  set the initial soil moisture: layer 1\n var3tmp(0,1,0,:) = (/0.2,0.2,0.2/)        ;  set the initial soil moisture: layer 2\n var3tmp(0,2,0,:) = (/0.2,0.2,0.2/)        ;  set the initial soil moisture: layer 3\n var3tmp(0,3,0,:) = (/0.2,0.2,0.2/)        ;  set the initial soil moisture: layer 4\n   var3tmp@units = \"m^3/m^3\"\n \n outfile->SMOIS = var3tmp\n\n;;;;;;;;;;;;;;;;;;;;\n; Global attributes, many are not used and should be removed\n;;;;;;;;;;;;;;;;;;;;\n\n\noutfile@TITLE = \"OUTPUT FROM VECTOR CREATION SCRIPTS: m.barlage v20150608\" ;\noutfile@DX        = 1000.0  ; not used\noutfile@DY        = 1000.0  ; not used\noutfile@TRUELAT1  = 45.0    ; not used\noutfile@TRUELAT2  = 45.0    ; not used\noutfile@STAND_LON = 45.0    ; not used\noutfile@MAP_PROJ  = 1       ; not used\noutfile@GRID_ID   = 1       ; used for grid labeling\noutfile@ISWATER   = 17      ; water type in land classification       (17 for MODIS; 16 for USGS)\noutfile@ISURBAN   = 13      ; urban type in land classification       (13 for MODIS;  1 for USGS)\noutfile@ISICE     = 15      ; snow/ice type in land classification    (15 for MODIS; 24 for USGS)\noutfile@MMINLU    = \"MODIFIED_IGBP_MODIS_NOAH\"  ; land classification (USGS or MODIFIED_IGBP_MODIS_NOAH)\n\n\n system(\"mv \"+setup_filename+\".nc \"+setup_filename)  ; get rid of the .nc\n\nend\n"
  },
  {
    "path": "src/Land_models/NoahMP/IO_code/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\ninclude ../user_build_options\n\nOBJS_NoahMP = module_NoahMP_hrldas_driver.o\n\nOBJS = \\\n\tmain_hrldas_driver.o \\\n\tmodule_hrldas_netcdf_io.o\n\nCPPHRLDAS = -D_HRLDAS_OFFLINE_ $(MOD_OPT)\n\nall:\t$(OBJS_NoahMP) $(OBJS)\n\nNoahMP : $(OBJS_NoahMP) $(OBJS)\n\nmodule_NoahMP_hrldas_driver.o: module_NoahMP_hrldas_driver.F ../../../HYDRO_drv/module_HYDRO_drv.o ../../../Data_Rec/module_namelist.o ../../../Data_Rec/module_RT_data.o\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c $(F90FLAGS) $(FREESOURCE) $(MODFLAG) -I. \\\n\t-I../phys -I../phys/surfex -I../Utility_routines -I../../../mod $(NETCDFMOD) $(*).F\n\t@echo \"\"\n\nmain_hrldas_driver.o: ../../../OrchestratorLayer/orchestrator.o main_hrldas_driver.F\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c $(F90FLAGS) $(LDFLAGS) $(FREESOURCE) -I ../MPP -I. \\\n\t-I../phys -I../phys/surfex -I../Utility_routines -I../../../mod -I../../../MPP -I../data_structures $(NETCDFMOD) $(*).F\n#\t$(COMPILERF90) -o $(@) -c $(F90FLAGS) $(FREESOURCE) -I ../MPP -I. \\\n#\t-I../phys -I../Utility_routines $(NETCDFMOD) $(*).f90\n\t@echo \"\"\n\nmodule_hrldas_netcdf_io.o: module_hrldas_netcdf_io.F\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c $(F90FLAGS) $(FREESOURCE) -I ../MPP -I ../../../mod -I../Utility_routines $(MODFLAG) $(NETCDFMOD) $(*).F\n\t@echo \"\"\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c $(F90FLAGS) $(FREESOURCE) $(*).F\n\t@echo \"\"\n\n#\n# Dependencies:\n#\n\nmain_hrldas_driver.o:\t$(OBJS_NoahMP) \\\n\t\t\t../../../MPP/mpp_land.o \\\n                        ../../../Routing/module_NWM_io.o\n$(OBJS_NoahMP):\tmodule_hrldas_netcdf_io.o\n\n# This command cleans up object files, etc.\nclean:\n\t$(RM) *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Land_models/NoahMP/IO_code/main_hrldas_driver.F",
    "content": "program noah_hrldas_driver\n! this is the main program to drive HRLDAS-Noah, HRLDAS-NoahMP, and other Land models.\n\n#ifdef Noah1d\n! this is used to drive Noah1d\n  use module_noah1d_hrldas_driver, only: land_driver_ini, land_driver_exe\n#else\n  ! this is used to drive NoahMP\n  use module_noahmp_hrldas_driver, only: land_driver_ini, land_driver_exe\n#endif\n\n  use module_HYDRO_drv, only: HYDRO_finish\n\n  ! NEW MODULE WITH DT INCLUDING STATE, PARAMETER,FORCING AND GEOMETRY. Different modules\n  use state_module, only: state_type\n  use parameters\n  use forcing\n  use geometry\n  use orchestrator_base\n\n  implicit none\n  integer :: ITIME, NTIME\n  type(state_type) :: state\n\n  call orchestrator%init()\n\n  call land_driver_ini(NTIME, state)\n\n#ifdef WRF_HYDRO\n  do ITIME = 1, NTIME\n#else\n  do ITIME = 0, NTIME\n#endif\n     ! DTs must be passed to the exe.\n     call land_driver_exe(ITIME, state)\n  end do\n#ifdef WRF_HYDRO\n  !Pass state for destruction\n  call hydro_finish()\n#endif\n\nend program noah_hrldas_driver\n"
  },
  {
    "path": "src/Land_models/NoahMP/IO_code/module_NoahMP_hrldas_driver.F",
    "content": "module module_NoahMP_hrldas_driver\n\n  USE module_hrldas_netcdf_io\n  USE module_sf_noahmp_groundwater\n  USE module_sf_noahmpdrv, only: noahmp_init, noahmplsm\n  USE module_date_utilities\n  USE orchestrator_base\n  USE config_base, only: wrf_hydro, noah_lsm\n  USE modi_ini_csts\n#ifdef MPP_LAND\n  use module_mpp_land, only: MPP_LAND_PAR_INI, mpp_land_init, getLocalXY, mpp_land_bcast_char, mpp_land_sync\n  use module_mpp_land, only: check_land, node_info, numprocs\n  use module_cpl_land, only: cpl_land_init, fatal_error_stop\n  !use mpi\n#endif\n#ifdef WRF_HYDRO\n  use module_NWM_io, only: output_NoahMP_NWM\n#endif\n\n  IMPLICIT NONE\n\n!#ifdef MPP_LAND\n!  use mpi\n!#endif\n\n#ifdef WRF_HYDRO\n   REAL,    allocatable, DIMENSION(:,:)   :: infxsrt,sfcheadrt, soldrain\n   !LRK - Remove HRLDAS_ini_typ for WRF-Hydro\n   integer :: forc_typ, snow_assim, HRLDAS_ini_typ\n   !integer :: forc_typ, snow_assim\n   REAL,    allocatable, DIMENSION(:,:)   :: etpnd, greenfrac, prcp0\n   real :: etpnd1\n   character(len=19) :: forcDate\n   ! LRK - Remove GEO_STATIC_FLNM\n   !character(len = 256):: GEO_STATIC_FLNM\n   real, allocatable, dimension(:) :: zsoil\n   integer :: kk\n   !integer  :: finemesh, finemesh_factor\n ! INOUT (new accumulator variables for output water balance)\n   REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ACCPRCP ! accumulated precip [mm]\n   REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ACCECAN  ! accumulated canopy evap [mm]\n   REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ACCETRAN ! accumulated transpiration [mm]\n   REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ACCEDIR ! accumulated direct soil evap [mm]\n   integer :: io_config_outputs = 0\n   integer :: reset_flag = 0\n   integer :: t0OutputFlag = 0\n   REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SOILSAT_TOP ! top 2 layer soil saturation [fraction]\n   REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SOILSAT ! column integrated soil saturation [fraction]\n   REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SOILICE ! fraction of soil moisture that is ice [fraction]\n   REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNOWT_AVG ! snowpack average temperature (by layer mass) [K] ** DIAGNOSTIC VARIABLE\n   integer, parameter                                      ::  max_ioc_num_vars = 200\n   integer, parameter                                      ::  ioc_var_len = 20\n   character(len=ioc_var_len), DIMENSION(max_ioc_num_vars) ::  IOCVARS\n#endif\n\n  character(len=9), parameter :: version = \"v20150506\"\n  integer :: LDASIN_VERSION\n\n!------------------------------------------------------------------------\n! Begin exact copy of declaration section from driver (substitute allocatable, remove intent)\n!------------------------------------------------------------------------\n\n! IN only (as defined in WRF)\n\n  INTEGER                                 ::  ITIMESTEP ! timestep number\n  INTEGER                                 ::  YR        ! 4-digit year\n  REAL                                    ::  JULIAN_IN ! Julian day\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  COSZEN    ! cosine zenith angle\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  XLAT_URB2D! latitude [rad]\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  DZ8W      ! thickness of atmo layers [m]\n  REAL                                    ::  DTBL      ! timestep [s]\n  REAL,    ALLOCATABLE, DIMENSION(:)      ::  DZS       ! thickness of soil layers [m]\n  INTEGER                                 ::  NSOIL     ! number of soil layers\n  INTEGER                                 ::  NUM_SOIL_LAYERS     ! number of soil layers\n  INTEGER                                 :: crocus_opt\n  INTEGER                                 :: act_lev\n  REAL                                    ::  DX        ! horizontal grid spacing [m]\n  INTEGER, ALLOCATABLE, DIMENSION(:,:)    ::  IVGTYP    ! vegetation type\n  INTEGER, ALLOCATABLE, DIMENSION(:,:)    ::  ISLTYP    ! soil type\n  INTEGER, ALLOCATABLE, DIMENSION(:,:)    ::  GLACINFO  ! location of  glacier\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GLACT     ! glacier thickness\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  VIS_ICEALB! map of visible ice albedo\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  VEGFRA    ! vegetation fraction []\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TMN       ! deep soil temperature [K]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  XLAND     ! =2 ocean; =1 land/seaice\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  XICE      ! fraction of grid that is seaice\n  REAL                                    ::  XICE_THRESHOLD! fraction of grid determining seaice\n  INTEGER                                 ::  ISICE     ! land cover category for ice\n  INTEGER                                 ::  ISURBAN   ! land cover category for urban\n  INTEGER                                 ::  ISLAKE    ! land cover category for lake\n  INTEGER                                 ::  ISWATER   ! land cover category for water\n  INTEGER                                 ::  IDVEG     ! dynamic vegetation (1 -> off ; 2 -> on) with opt_crs = 1\n  INTEGER                                 ::  IOPT_CRS  ! canopy stomatal resistance (1-> Ball-Berry; 2->Jarvis)\n  INTEGER                                 ::  IOPT_BTR  ! soil moisture factor for stomatal resistance (1-> Noah; 2-> CLM; 3-> SSiB)\n  INTEGER                                 ::  IOPT_RUN  ! runoff and groundwater (1->SIMGM; 2->SIMTOP; 3->Schaake96; 4->BATS)\n  INTEGER                                 ::  IOPT_SFC  ! surface layer drag coeff (CH & CM) (1->M-O; 2->Chen97)\n  INTEGER                                 ::  IOPT_FRZ  ! supercooled liquid water (1-> NY06; 2->Koren99)\n  INTEGER                                 ::  IOPT_INF  ! frozen soil permeability (1-> NY06; 2->Koren99)\n  INTEGER                                 ::  IOPT_RAD  ! radiation transfer (1->gap=F(3D,cosz); 2->gap=0; 3->gap=1-Fveg)\n  INTEGER                                 ::  IOPT_ALB  ! snow surface albedo (1->BATS; 2->CLASS)\n  INTEGER                                 ::  IOPT_SNF  ! rainfall & snowfall (1-Jordan91; 2->BATS; 3->Noah)\n  INTEGER                                 ::  IOPT_TBOT ! lower boundary of soil temperature (1->zero-flux; 2->Noah)\n  INTEGER                                 ::  IOPT_STC  ! snow/soil temperature time scheme\n  INTEGER                                 ::  IOPT_GLA  ! glacier option (1->phase change; 2->simple)\n  INTEGER                                 ::  IOPT_RSF  ! surface resistance option (1->Zeng; 2->simple)\n  INTEGER                                 ::  IZ0TLND   ! option of Chen adjustment of Czil (not used)\n  INTEGER                                 ::  IOPT_SOIL ! soil configuration option\n  INTEGER                                 ::  IOPT_PEDO ! soil pedotransfer function option\n  INTEGER                                 ::  IOPT_CROP ! crop model option (0->none; 1->Liu et al.)\n  INTEGER                                 ::  IOPT_IMPERV !imperviousness infiltration adjustment (0->none; 1->total;\n                                                                                        !2->Alley&Veenhuis; 9->old)\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  T_PHY     ! 3D atmospheric temperature valid at mid-levels [K]\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  QV_CURR   ! 3D water vapor mixing ratio [kg/kg_dry]\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  U_PHY     ! 3D U wind component [m/s]\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  V_PHY     ! 3D V wind component [m/s]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SWDOWN    ! solar down at surface [W m-2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GLW       ! longwave down at surface [W m-2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  P8W       ! 3D pressure, valid at interface [Pa]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RAINBL, RAINBL_tmp    ! precipitation entering land model [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNOWBL    ! snow entering land model [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SR        ! frozen precip ratio entering land model [-]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RAINCV    ! convective precip forcing [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RAINNCV   ! non-convective precip forcing [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RAINSHV   ! shallow conv. precip forcing [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNOWNCV   ! non-covective snow forcing (subset of rainncv) [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GRAUPELNCV! non-convective graupel forcing (subset of rainncv) [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  HAILNCV   ! non-convective hail forcing (subset of rainncv) [mm]\n\n! New spatially varying fields\n\n  CHARACTER(LEN = 256)                    ::  spatial_filename\n#ifdef SPATIAL_SOIL\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  bexp_3D    ! C-H B exponent\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  smcdry_3D  ! Soil Moisture Limit: Dry\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  smcwlt_3D  ! Soil Moisture Limit: Wilt\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  smcref_3D  ! Soil Moisture Limit: Reference\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  smcmax_3D  ! Soil Moisture Limit: Max\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  dksat_3D   ! Saturated Soil Conductivity\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  dwsat_3D   ! Saturated Soil Diffusivity\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  psisat_3D  ! Saturated Matric Potential\n  REAL, ALLOCATABLE, DIMENSION(:,:,:)     ::  quartz_3D  ! Soil quartz content\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  refdk_2D   ! Reference Soil Conductivity\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  refkdt_2D  ! Soil Infiltration Parameter\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  slope_2D   ! Soil Drainage Parameter\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  cwpvt_2D   ! Canopy wind parameter\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  vcmx25_2D  ! VCmax at 25C\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  mp_2D      ! Slope of Ball-Berry rs-P relationship\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  hvt_2D     ! Canopy Height\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  mfsno_2D   ! Snow cover m parameter\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  rsurfexp_2D! exponent in the shape parameter for soil resistance option 1\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  axaj_2D    ! Tension water distribution inflection parameter [-]\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  bxaj_2D    ! Tension water distribution shape parameter [-]\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  xxaj_2D    ! Free water distribution shape parameter [-]\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  imperv_2D  ! impervious fraction\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  ssi_2D     ! liquid water holding capacity for snowpack (m3/m3)\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  snowretfac_2D   ! snowpack water release timescale factor (1/s)\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  tau0_2D         ! tau0 from Yang97 eqn. 10a\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  rsurfsnow_2D    ! surface resistence for snow [s/m]\n  REAL, ALLOCATABLE, DIMENSION(:,:)       ::  scamax_2D       ! maximum fractional snow covered area (0.0-1.0)\n#endif\n\n! INOUT (with generic LSM equivalent) (as defined in WRF)\n\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TSK       ! surface radiative temperature [K]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  HFX       ! sensible heat flux [W m-2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QFX       ! latent heat flux [kg s-1 m-2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  LH        ! latent heat flux [W m-2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GRDFLX    ! ground/snow heat flux [W m-2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SMSTAV    ! soil moisture avail. [not used]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SMSTOT    ! total soil water [mm][not used]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SFCRUNOFF ! accumulated surface runoff [m]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  UDRUNOFF  ! accumulated sub-surface runoff [m]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ALBEDO    ! total grid albedo []\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNOWC     ! snow cover fraction []\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  SMOISEQ   ! volumetric soil moisture [m3/m3]\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  SMOIS     ! volumetric soil moisture [m3/m3]\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  SH2O      ! volumetric liquid soil moisture [m3/m3]\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  TSLB      ! soil temperature [K]\n!  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNOW      ! snow water equivalent [mm] ** (sometime) PROGNOSTIC VARIABLE\n!  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNOWH     ! physical snow depth [m] ** (sometime) PROGNOSTIC VARIABLE\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CANWAT    ! total canopy water + ice [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ACSNOM    ! accumulated snow melt leaving pack\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ACSNOW    ! accumulated snow on grid\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  EMISS     ! surface bulk emissivity\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QSFC      ! bulk surface specific humidity\n\n! INOUT (with no Noah LSM equivalent) (as defined in WRF)\n\n  INTEGER, ALLOCATABLE, DIMENSION(:,:)    ::  ISNOWXY   ! actual no. of snow layers\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TVXY      ! vegetation leaf temperature\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TGXY      ! bulk ground surface temperature\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CANICEXY  ! canopy-intercepted ice (mm)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CANLIQXY  ! canopy-intercepted liquid water (mm)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  EAHXY     ! canopy air vapor pressure (pa)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TAHXY     ! canopy air temperature (k)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CMXY      ! bulk momentum drag coefficient\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CHXY      ! bulk sensible heat exchange coefficient\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  FWETXY    ! wetted or snowed fraction of the canopy (-)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNEQVOXY  ! snow mass at last time step(mm h2o)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ALBOLDXY  ! snow albedo at last time step (-)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QSNOWXY   ! snowfall on the ground [mm/s]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QRAINXY   ! rainfall on the ground [mm/s]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  WSLAKEXY  ! lake water storage [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ZWTXY     ! water table depth [m]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  WAXY      ! water in the \"aquifer\" [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  WTXY      ! groundwater storage [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SMCWTDXY  ! groundwater storage [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  DEEPRECHXY! groundwater storage [mm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RECHXY    ! groundwater storage [mm]\n!  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  TSNOXY    ! snow temperature [K] ** REFACTOR THIS!\n!  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  ZSNSOXY   ! snow layer depth [m] ** REFACTOR THIS!\n!  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  SNICEXY   ! snow layer ice [mm] ** REFACTOR THIS!\n!  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  SNLIQXY   ! snow layer liquid water [mm] ** REFACTOR THIS!\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  LFMASSXY  ! leaf mass [g/m2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RTMASSXY  ! mass of fine roots [g/m2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  STMASSXY  ! stem mass [g/m2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  WOODXY    ! mass of wood (incl. woody roots) [g/m2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  STBLCPXY  ! stable carbon in deep soil [g/m2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  FASTCPXY  ! short-lived carbon, shallow soil [g/m2]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  LAI       ! leaf area index\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  XSAIXY    ! stem area index\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TAUSSXY   ! snow age factor\n\n! OUT (with no Noah LSM equivalent) (as defined in WRF)\n\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  T2MVXY    ! 2m temperature of vegetation part\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  T2MBXY    ! 2m temperature of bare ground part\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  Q2MVXY    ! 2m mixing ratio of vegetation part\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  Q2MBXY    ! 2m mixing ratio of bare ground part\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TRADXY    ! surface radiative temperature (k)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  NEEXY     ! net ecosys exchange (g/m2/s CO2)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GPPXY     ! gross primary assimilation [g/m2/s C]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  NPPXY     ! net primary productivity [g/m2/s C]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  FVEGXY    ! Noah-MP vegetation fraction [-]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RUNSFXY   ! surface runoff [mm/s]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RUNSBXY   ! subsurface runoff [mm/s]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ECANXY    ! evaporation of intercepted water (mm/s)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  EDIRXY    ! soil surface evaporation rate (mm/s]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ETRANXY   ! transpiration rate (mm/s)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  FSAXY     ! total absorbed solar radiation (w/m2)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  FIRAXY    ! total net longwave rad (w/m2) [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  APARXY    ! photosyn active energy by canopy (w/m2)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  PSNXY     ! total photosynthesis (umol co2/m2/s) [+]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SAVXY     ! solar rad absorbed by veg. (w/m2)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SAGXY     ! solar rad absorbed by ground (w/m2)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RSSUNXY   ! sunlit leaf stomatal resistance (s/m)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RSSHAXY   ! shaded leaf stomatal resistance (s/m)\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  ALBSNDXY  ! snow albedo (direct)\n  REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  ALBSNIXY  ! snow albedo (diffuse)\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  BGAPXY    ! between gap fraction\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  WGAPXY    ! within gap fraction\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TGVXY     ! under canopy ground temperature[K]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TGBXY     ! bare ground temperature [K]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CHVXY     ! sensible heat exchange coefficient vegetated\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CHBXY     ! sensible heat exchange coefficient bare-ground\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SHGXY     ! veg ground sen. heat [w/m2]   [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SHCXY     ! canopy sen. heat [w/m2]   [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SHBXY     ! bare sensible heat [w/m2]  [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  EVGXY     ! veg ground evap. heat [w/m2]  [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  EVBXY     ! bare soil evaporation [w/m2]  [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GHVXY     ! veg ground heat flux [w/m2]  [+ to soil]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GHBXY     ! bare ground heat flux [w/m2] [+ to soil]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  IRGXY     ! veg ground net LW rad. [w/m2] [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  IRCXY     ! canopy net LW rad. [w/m2] [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  IRBXY     ! bare net longwave rad. [w/m2] [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TRXY      ! transpiration [w/m2]  [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  EVCXY     ! canopy evaporation heat [w/m2]  [+ to atm]\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CHLEAFXY  ! leaf exchange coefficient\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CHUCXY    ! under canopy exchange coefficient\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CHV2XY    ! veg 2m exchange coefficient\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CHB2XY    ! bare 2m exchange coefficient\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  Z0        ! roughness length output to WRF\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  ZNT       ! roughness length output to WRF\n  INTEGER   ::  ids,ide, jds,jde, kds,kde,  &  ! d -> domain\n   &            ims,ime, jms,jme, kms,kme,  &  ! m -> memory\n   &            its,ite, jts,jte, kts,kte      ! t -> tile\n\n!------------------------------------------------------------------------\n! Needed for NoahMP init\n!------------------------------------------------------------------------\n\n  LOGICAL                                 ::  FNDSOILW    ! soil water present in input\n  LOGICAL                                 ::  FNDSNOWH    ! snow depth present in input\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  CHSTARXY    ! for consistency with MP_init; delete later\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SEAICE      ! seaice fraction\n\n!------------------------------------------------------------------------\n! Needed for MMF_RUNOFF (IOPT_RUN = 5); not part of MP driver in WRF\n!------------------------------------------------------------------------\n\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  MSFTX\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  MSFTY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  EQZWT\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RIVERBEDXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  RIVERCONDXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  PEXPXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  FDEPTHXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  AREAXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QRFSXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QSPRINGSXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QRFXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QSPRINGXY\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  QSLATXY\n  REAL                                    ::  WTDDT  = 30.0    ! frequency of groundwater call [minutes]\n  INTEGER                                 ::  STEPWTD = 1      ! step of groundwater call\n\n!------------------------------------------------------------------------\n! Crocus\n!------------------------------------------------------------------------\n\n  REAL,       ALLOCATABLE, DIMENSION(:,:)     ::  PSNOWTHRUFALXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:)     ::  PSNOWALBXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:)     ::  PSNOWHEIGHTXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:)     ::  PSNOWTOTSWEXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:)     ::  FLOW_SNOW\n  REAL,       ALLOCATABLE, DIMENSION(:,:)     ::  FLOW_ICE\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWHEATXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWRHOXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWSWEXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWGRAN1XY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWGRAN2XY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWAGEXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWLIQXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWTEMPXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWDZXY\n  REAL,       ALLOCATABLE, DIMENSION(:,:,:)   ::  PSNOWHISTXY\n\n!------------------------------------------------------------------------\n! 2D variables not used in WRF - should be removed?\n!------------------------------------------------------------------------\n\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  XLONIN      ! longitude\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  TERRAIN     ! terrain height\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GVFMIN      ! annual minimum in vegetation fraction\n  REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  GVFMAX      ! annual maximum in vegetation fraction\n\n!------------------------------------------------------------------------\n! End 2D variables not used in WRF\n!------------------------------------------------------------------------\n\n  CHARACTER(LEN=256) :: MMINSL  = 'STAS'  ! soil classification\n  CHARACTER(LEN=256) :: LLANDUSE          ! (=USGS, using USGS landuse classification)\n\n!------------------------------------------------------------------------\n! Timing:\n!------------------------------------------------------------------------\n\n  INTEGER :: NTIME          ! total timesteps\n  INTEGER :: ITIME          ! LSM time step\n  integer :: clock_count_1 = 0\n  integer :: clock_count_2 = 0\n  integer :: clock_rate    = 0\n  real    :: timing_sum    = 0.0\n\n  integer :: sflx_count_sum\n  integer :: count_before_sflx\n  integer :: count_after_sflx\n\n!---------------------------------------------------------------------\n!  DECLARE/Initialize constants\n!---------------------------------------------------------------------\n\n    INTEGER                             :: I\n    INTEGER                             :: J\n    INTEGER                             :: SLOPETYP\n    INTEGER                             :: YEARLEN\n    INTEGER, PARAMETER                  :: NSNOW = 3    ! number of snow layers fixed to 3\n    REAL, PARAMETER                     :: undefined_real = 9.9692099683868690E36 ! NetCDF float   FillValue\n    INTEGER, PARAMETER                  :: undefined_int = -2147483647            ! NetCDF integer FillValue\n    LOGICAL                             :: update_lai, update_veg\n\n!---------------------------------------------------------------------\n!  File naming, parallel\n!---------------------------------------------------------------------\n\n  character(len=19)  :: olddate, newdate, startdate\n  character          :: hgrid, hgrid_hydro\n  integer            :: igrid, igrid_hydro\n  logical            :: lexist\n  integer            :: imode, iimode\n  integer            :: ixfull\n  integer            :: jxfull\n  integer            :: ixpar\n  integer            :: jxpar\n  integer            :: xstartpar\n  integer            :: ystartpar\n  integer            :: rank = 0\n  CHARACTER(len=256) :: inflnm, outflnm, inflnm_template\n  logical            :: restart_flag\n  character(len=256) :: restart_flnm\n  integer            :: ierr\n\n!---------------------------------------------------------------------\n! Attributes from LDASIN input file (or HRLDAS_SETUP_FILE, as the case may be)\n!---------------------------------------------------------------------\n\n  INTEGER           :: IX\n  INTEGER           :: JX\n  REAL              :: DY\n  REAL              :: TRUELAT1\n  REAL              :: TRUELAT2\n  REAL              :: CEN_LON\n  INTEGER           :: MAPPROJ\n  REAL              :: LAT1\n  REAL              :: LON1\n\n#ifdef MPP_LAND\n  integer ix_tmp, jx_tmp\n#endif\n\n#ifdef WRF_HYDRO\n  character(len=19)  :: tmpdate\n  character(len=1000) :: VARLIST\n  integer :: brkflag = 0\n  integer :: varind = 1\n#endif\n\n  integer :: xstart, xend, ystart, yend !convenience variables\n\n  contains\n\n  subroutine land_driver_ini(NTIME_out, state, wrfits,wrfite,wrfjts,wrfjte)\n     use module_HYDRO_drv, only: HYDRO_ini\n     use config_base, only: nlst\n     use module_rt_data, only: rt_domain\n     use module_hrldas_HYDRO, only: open_print_mpp\n     use state_module, only: state_type\n     implicit  none\n     integer, intent(out) :: NTIME_out\n     integer, parameter :: did=1\n     integer :: khour\n     type(state_type), intent(out) :: state\n\n    ! initilization for stand alone parallel code.\n    integer, optional, intent(in) :: wrfits,wrfite,wrfjts,wrfjte\n\n#ifdef MPP_LAND\n    call read_dim(noah_lsm%hrldas_setup_file,ix_tmp,jx_tmp)\n    call MPP_LAND_INIT(ix_tmp,jx_tmp)\n#endif\n\n#ifdef WRF_HYDRO\n    forc_typ = wrf_hydro%forc_typ\n#endif\n\n  dtbl = real(noah_lsm%noah_timestep)\n  num_soil_layers = noah_lsm%nsoil      ! because surface driver uses the long form\n  act_lev    = noah_lsm%act_lev\n  crocus_opt = noah_lsm%crocus_opt\n  IDVEG      = noah_lsm%dynamic_veg_option ! transfer from namelist to driver format\n  IOPT_CRS   = noah_lsm%canopy_stomatal_resistance_option\n  IOPT_BTR   = noah_lsm%btr_option\n  IOPT_RUN   = noah_lsm%runoff_option\n  IOPT_SFC   = noah_lsm%surface_drag_option\n  IOPT_FRZ   = noah_lsm%supercooled_water_option\n  IOPT_INF   = noah_lsm%frozen_soil_option\n  IOPT_RAD   = noah_lsm%radiative_transfer_option\n  IOPT_ALB   = noah_lsm%snow_albedo_option\n  IOPT_SNF   = noah_lsm%pcp_partition_option\n  IOPT_TBOT  = noah_lsm%tbot_option\n  IOPT_STC   = noah_lsm%temp_time_scheme_option\n  IOPT_GLA   = noah_lsm%glacier_option\n  IOPT_RSF   = noah_lsm%surface_resistance_option\n  IOPT_SOIL  = noah_lsm%soil_data_option\n  IOPT_PEDO  = noah_lsm%pedotransfer_option\n  IOPT_CROP  = noah_lsm%crop_option\n  IOPT_IMPERV = noah_lsm%imperv_option\n\n  khour = noah_lsm%khour\n\n  !!----------------------------------------------------------------------------\n  !! channel_only\n  call updateNameList(\"channel_only\",0)\n  if(forc_typ .eq. 9)  call updateNameList(\"channel_only\",1)\n  call updateNameList(\"channelBucket_only\",0)\n  if(forc_typ .eq. 10) call updateNameList(\"channelBucket_only\",1)\n\n  if(forc_typ .eq. 9 .or. forc_typ .eq. 10) then\n     write(olddate,'(I4.4,\"-\",I2.2,\"-\",I2.2,\"_\",I2.2,\":\",I2.2,\":\",I2.2)') &\n          noah_lsm%start_year, noah_lsm%start_month, noah_lsm%start_day, noah_lsm%start_hour, noah_lsm%start_min, 0\n     forcdate = olddate\n     if ((khour < 0) .and. (noah_lsm%kday < 0)) then\n        write(*, '(\"FATAL ERROR: In module_NoahMP_hrldas_driver.F land_driver_ini() - \"// &\n             \"Namelist error: Either KHOUR or KDAY must be defined.\")')\n        stop\n     else if (( khour < 0 ) .and. (noah_lsm%kday > 0)) then\n        khour = noah_lsm%kday * 24\n     else if ((khour > 0) .and. (noah_lsm%kday > 0)) then\n        write(*, '(\"WARNING: In land_driver_ini() - Check Namelist: KHOUR and KDAY both defined.\")')\n        stop\n     endif\n     NTIME = khour*3600./nint(dtbl)\n     NTIME_out = NTIME\n\n     if(.not. RT_DOMAIN(did)%initialized) then\n        nlst(did)%dt = real(noah_lsm%noah_timestep)\n        nlst(did)%khour = khour ! Adding kHOUR to be used in the NWM output routines.\n        nlst(did)%olddate(1:19) = olddate(1:19)\n        nlst(did)%startdate(1:19) = olddate(1:19)\n        nlst(did)%nsoil = -999999\n#ifdef MPP_LAND\n        call mpp_land_bcast_int1(nlst(did)%nsoil)\n#endif\n        allocate(nlst(did)%zsoil8(nlst(did)%nsoil))\n        nlst(did)%zsoil8(1:nlst(did)%nsoil) = zsoil(1:nlst(did)%nsoil)\n        call HYDRO_ini(ntime,did,ix0=1,jx0=1)\n        RT_DOMAIN(did)%initialized = .true.\n     endif ! if .not. RT_DOMAIN(did)%initialized\n\n     call open_print_mpp(6)\n\n     return  !! no more init necessary if channel_only or channelBucket_only\n\n  endif\n  !!----------------------------------------------------------------------------\n  !! channel_only\n\n\n!---------------------------------------------------------------------\n!  NAMELIST end\n!---------------------------------------------------------------------\n\n!---------------------------------------------------------------------\n!  NAMELIST check begin\n!---------------------------------------------------------------------\n\n  update_lai = .true.   ! default: use LAI if present in forcing file\n  if (noah_lsm%dynamic_veg_option == 2 .or. noah_lsm%dynamic_veg_option == 5 .or. noah_lsm%dynamic_veg_option == 6) &\n    update_lai = .false.\n\n  update_veg = .false.  ! default: don't use VEGFRA if present in forcing file\n  if (noah_lsm%dynamic_veg_option == 1 .or. noah_lsm%dynamic_veg_option == 6 .or. noah_lsm%dynamic_veg_option == 7) &\n    update_veg = .true.\n\n  if (noah_lsm%nsoil < 0) then\n     stop \"FATAL ERROR: In module_NoahMP_hrldas_driver.F land_driver_ini()\"// &\n          \" - NSOIL must be set in the namelist.\"\n  endif\n\n  if ((khour < 0) .and. (noah_lsm%kday < 0)) then\n#ifdef HYDRO_D\n     write(*, '(\"FATAL ERROR: In module_NoahMP_hrldas_driver.F land_driver_ini() - \"// &\n                \"Namelist error.\")')\n     write(*, '(\" ***** \")')\n     write(*, '(\" *****      Either KHOUR or KDAY must be defined.\")')\n     write(*, '(\" ***** \")')\n#endif\n     stop\n  else if (( khour < 0 ) .and. (noah_lsm%kday > 0)) then\n     khour = noah_lsm%kday * 24\n     write(*, '(\"WARNING: In land_driver_ini() - KHOUR < 0. DEFINED USING KDAY.\")')\n  else if ((khour > 0) .and. (noah_lsm%kday > 0)) then\n     write(*, '(\"WARNING: In land_driver_ini() - Check Namelist: KHOUR and KDAY both defined.\")')\n  else\n     ! all is well.  KHOUR defined\n  endif\n\n  if (noah_lsm%forcing_timestep < 0) then\n        write(*, *)\n        write(*, '(\"FATAL ERROR: In module_NoahMP_hrldas_driver.F land_driver_ini()- \"// &\n                   \"Namelist error.\")')\n        write(*, '(\" ***** \")')\n        write(*, '(\" *****       FORCING_TIMESTEP needs to be set greater than zero.\")')\n        write(*, '(\" ***** \")')\n        write(*, *)\n        stop\n  endif\n\n  if (noah_lsm%noah_timestep < 0) then\n        write(*, *)\n        write(*, '(\"FATAL ERROR: In module_NoahMP_hrldas_driver.F land_driver_ini()\"// &\n                   \" - Namelist error.\")')\n        write(*, '(\" ***** \")')\n        write(*, '(\" *****       NOAH_TIMESTEP needs to be set greater than zero.\")')\n        write(*, '(\" *****                     900 seconds is recommended.       \")')\n        write(*, '(\" ***** \")')\n        write(*, *)\n        stop\n  endif\n\n  !\n  ! Check that OUTPUT_TIMESTEP fits into NOAH_TIMESTEP:\n  !\n  if (noah_lsm%output_timestep /= 0) then\n     if (mod(noah_lsm%output_timestep, noah_lsm%noah_timestep) > 0) then\n        write(*, *)\n        write(*, '(\"FATAL ERROR: In module_NoahMP_hrldas_driver.F land_driver_ini() - \"// &\n                   \"Namelist error.\")')\n        write(*, '(\" ***** \")')\n        write(*, '(\" *****       OUTPUT_TIMESTEP should set to an integer multiple of NOAH_TIMESTEP.\")')\n        write(*, '(\" *****            OUTPUT_TIMESTEP = \", I12, \" seconds\")') noah_lsm%output_timestep\n        write(*, '(\" *****            NOAH_TIMESTEP   = \", I12, \" seconds\")') noah_lsm%noah_timestep\n        write(*, '(\" ***** \")')\n        write(*, *)\n        stop\n     endif\n  endif\n\n  !\n  ! Check that RESTART_FREQUENCY_HOURS fits into NOAH_TIMESTEP:\n  !\n  if (noah_lsm%restart_frequency_hours /= 0) then\n     if (mod(noah_lsm%restart_frequency_hours*3600, noah_lsm%noah_timestep) > 0) then\n        write(*, *)\n        write(*, '(\"FATAL ERROR: In module_NoahMP_hrldas_driver.F land_driver_ini() - \"// &\n                   \"Namelist error.\")')\n        write(*, '(\" *****       RESTART_FREQUENCY_HOURS (converted to seconds) should set to an \")')\n        write(*, '(\" *****       integer multiple of NOAH_TIMESTEP.\")')\n        write(*, '(\" *****            RESTART_FREQUENCY_HOURS = \", I12, \" hours:  \", I12, \" seconds\")') &\n             noah_lsm%restart_frequency_hours, noah_lsm%restart_frequency_hours*3600\n        write(*, '(\" *****            NOAH_TIMESTEP           = \", I12, \" seconds\")') noah_lsm%noah_timestep\n        write(*, '(\" ***** \")')\n        write(*, *)\n        stop\n     endif\n  endif\n\n  if (noah_lsm%dynamic_veg_option == 2 .or. noah_lsm%dynamic_veg_option == 5 .or. noah_lsm%dynamic_veg_option == 6) then\n     if ( noah_lsm%canopy_stomatal_resistance_option /= 1) then\n        write(*, *)\n        write(*, '(\"FATAL ERROR: In module_NoahMP_hrldas_driver.F land_driver_ini() - \"// &\n                   \"Namelist error.\")')\n        write(*, '(\" ***** \")')\n        write(*, '(\" *****       CANOPY_STOMATAL_RESISTANCE_OPTION must be 1 when DYNAMIC_VEG_OPTION == 2/5/6\")')\n        write(*, *)\n        stop\n     endif\n  endif\n\n!---------------------------------------------------------------------\n!  NAMELIST check end\n!---------------------------------------------------------------------\n\n!----------------------------------------------------------------------\n! Initialize gridded domain\n!----------------------------------------------------------------------\n\n#ifdef MPP_LAND\n#ifdef WRF_HYDRO\n  if(wrf_hydro%finemesh .ne. 0) then\n     write(*, '(\"WARNING: In module_NoahMP_hrldas_driver.F land_driver_ini() - \"// &\n          \"noah_lsm%x and y start and noah_lsm%x and yend calculated using wrf_hydro%finemesh_factor\")')\n\n     xstart = (wrfits-1) * wrf_hydro%finemesh_factor + 1\n     xend = (wrfite-1) * wrf_hydro%finemesh_factor\n     ystart = (wrfjts-1) * wrf_hydro%finemesh_factor + 1\n     yend = (wrfjte-1) * wrf_hydro%finemesh_factor\n     call CPL_LAND_INIT(xstart,xend, ystart,yend)\n     ix_tmp = xend - xstart + 1\n     jx_tmp = yend - ystart + 1\n\n    else\n#endif\n       call read_dim(noah_lsm%hrldas_setup_file,ix_tmp,jx_tmp)\n       call MPP_LAND_PAR_INI(1,ix_tmp,jx_tmp,1)\n       call getLocalXY(ix_tmp,jx_tmp,noah_lsm%xstart,noah_lsm%ystart,noah_lsm%xend,noah_lsm%yend)\n#ifdef WRF_HYDRO\n    endif\n#endif\n#endif\n\n    call read_hrldas_hdrinfo(noah_lsm%hrldas_setup_file, ix, jx, &\n         noah_lsm%xstart, noah_lsm%xend, noah_lsm%ystart, noah_lsm%yend, &\n         iswater, islake, isurban, isice, llanduse, dx, dy, truelat1, truelat2, cen_lon, lat1, lon1, &\n         igrid, mapproj)\n  write(hgrid,'(I1)') igrid\n\n  write(olddate,'(I4.4,\"-\",I2.2,\"-\",I2.2,\"_\",I2.2,\":\",I2.2,\":\",I2.2)') &\n       noah_lsm%start_year, noah_lsm%start_month, noah_lsm%start_day, noah_lsm%start_hour, noah_lsm%start_min, 0\n\n  startdate = olddate\n\n#ifdef MPP_LAND\n  ix = ix_tmp\n  jx = jx_tmp\n#endif\n\n#ifdef WRF_HYDRO\n  forcdate = olddate\n#endif\n\n  ! Convenience variables\n  xstart = noah_lsm%xstart\n  ystart = noah_lsm%ystart\n  xend = noah_lsm%xend\n  yend = noah_lsm%yend\n  nsoil = noah_lsm%nsoil\n  act_lev = noah_lsm%act_lev\n  crocus_opt = noah_lsm%crocus_opt\n  ids = xstart\n  ide = xend\n  jds = ystart\n  jde = yend\n  kds = 1\n  kde = 2\n  its = xstart\n  ite = xend\n  jts = ystart\n  jte = yend\n  kts = 1\n  kte = 2\n  ims = xstart\n  ime = xend\n  jms = ystart\n  jme = yend\n  kms = 1\n  kme = 2\n\n!---------------------------------------------------------------------\n!  Allocate multi-dimension fields for subwindow calculation\n!---------------------------------------------------------------------\n\n  ixfull = xend-xstart+1\n  jxfull = yend-ystart+1\n\n  ixpar = ixfull\n  jxpar = jxfull\n  xstartpar = 1\n  ystartpar = 1\n\n  !Initialize state variables\n  call state%init()\n\n  ALLOCATE ( COSZEN    (XSTART:XEND,YSTART:YEND) )    ! cosine zenith angle\n  ALLOCATE ( XLAT_URB2D(XSTART:XEND,YSTART:YEND) )    ! latitude [rad]\n  ALLOCATE ( DZ8W      (XSTART:XEND,KDS:KDE,YSTART:YEND) )  ! thickness of atmo layers [m]\n  ALLOCATE ( DZS       (1:NSOIL)                   )  ! thickness of soil layers [m]\n  ALLOCATE ( IVGTYP    (XSTART:XEND,YSTART:YEND) )    ! vegetation type\n  ALLOCATE ( ISLTYP    (XSTART:XEND,YSTART:YEND) )    ! soil type\n  ALLOCATE ( VEGFRA    (XSTART:XEND,YSTART:YEND) )    ! vegetation fraction []\n  if (crocus_opt /= 0) then\n     ALLOCATE (GLACINFO(XSTART:XEND,YSTART:YEND) )    ! loacation of glacier\n     ALLOCATE (GLACT   (XSTART:XEND,YSTART:YEND) )    ! glacier thickness [m]\n     ALLOCATE (VIS_ICEALB(XSTART:XEND,YSTART:YEND))\n  end if\n  ALLOCATE ( TMN       (XSTART:XEND,YSTART:YEND) )    ! deep soil temperature [K]\n  ALLOCATE ( XLAND     (XSTART:XEND,YSTART:YEND) )    ! =2 ocean; =1 land/seaice\n  ALLOCATE ( XICE      (XSTART:XEND,YSTART:YEND) )    ! fraction of grid that is seaice\n  ALLOCATE ( T_PHY     (XSTART:XEND,KDS:KDE,YSTART:YEND) )  ! 3D atmospheric temperature valid at mid-levels [K]\n  ALLOCATE ( QV_CURR   (XSTART:XEND,KDS:KDE,YSTART:YEND) )  ! 3D water vapor mixing ratio [kg/kg_dry]\n  ALLOCATE ( U_PHY     (XSTART:XEND,KDS:KDE,YSTART:YEND) )  ! 3D U wind component [m/s]\n  ALLOCATE ( V_PHY     (XSTART:XEND,KDS:KDE,YSTART:YEND) )  ! 3D V wind component [m/s]\n  ALLOCATE ( SWDOWN    (XSTART:XEND,YSTART:YEND) )    ! solar down at surface [W m-2]\n  ALLOCATE ( GLW       (XSTART:XEND,YSTART:YEND) )    ! longwave down at surface [W m-2]\n  ALLOCATE ( P8W       (XSTART:XEND,KDS:KDE,YSTART:YEND) )  ! 3D pressure, valid at interface [Pa]\n  ALLOCATE ( RAINBL    (XSTART:XEND,YSTART:YEND) )    ! total precipitation entering land model [mm]\n  ALLOCATE ( SNOWBL    (XSTART:XEND,YSTART:YEND) )    ! snow entering land model [mm]\n  ALLOCATE ( RAINBL_tmp    (XSTART:XEND,YSTART:YEND) )    ! precipitation entering land model [mm]\n  ALLOCATE ( SR        (XSTART:XEND,YSTART:YEND) )    ! frozen precip ratio entering land model [-]\n  ALLOCATE ( RAINCV    (XSTART:XEND,YSTART:YEND) )    ! convective precip forcing [mm]\n  ALLOCATE ( RAINNCV   (XSTART:XEND,YSTART:YEND) )    ! non-convective precip forcing [mm]\n  ALLOCATE ( RAINSHV   (XSTART:XEND,YSTART:YEND) )    ! shallow conv. precip forcing [mm]\n  ALLOCATE ( SNOWNCV   (XSTART:XEND,YSTART:YEND) )    ! non-covective snow forcing (subset of rainncv) [mm]\n  ALLOCATE ( GRAUPELNCV(XSTART:XEND,YSTART:YEND) )    ! non-convective graupel forcing (subset of rainncv) [mm]\n  ALLOCATE ( HAILNCV   (XSTART:XEND,YSTART:YEND) )    ! non-convective hail forcing (subset of rainncv) [mm]\n\n#ifdef SPATIAL_SOIL\n  ALLOCATE ( bexp_3d    (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! C-H B exponent\n  ALLOCATE ( smcdry_3D  (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! Soil Moisture Limit: Dry\n  ALLOCATE ( smcwlt_3D  (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! Soil Moisture Limit: Wilt\n  ALLOCATE ( smcref_3D  (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! Soil Moisture Limit: Reference\n  ALLOCATE ( smcmax_3D  (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! Soil Moisture Limit: Max\n  ALLOCATE ( dksat_3D   (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! Saturated Soil Conductivity\n  ALLOCATE ( dwsat_3D   (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! Saturated Soil Diffusivity\n  ALLOCATE ( psisat_3D  (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! Saturated Matric Potential\n  ALLOCATE ( quartz_3D  (XSTART:XEND,1:NSOIL,YSTART:YEND) )    ! Soil quartz content\n  ALLOCATE ( refdk_2D   (XSTART:XEND,YSTART:YEND) )            ! Reference Soil Conductivity\n  ALLOCATE ( refkdt_2D  (XSTART:XEND,YSTART:YEND) )            ! Soil Infiltration Parameter\n  ALLOCATE ( slope_2D   (XSTART:XEND,YSTART:YEND) )            ! Soil Drainage Parameter\n  ALLOCATE ( cwpvt_2D   (XSTART:XEND,YSTART:YEND) )            ! Canopy wind parameter\n  ALLOCATE ( vcmx25_2D  (XSTART:XEND,YSTART:YEND) )            ! VCmax at 25C\n  ALLOCATE ( mp_2D      (XSTART:XEND,YSTART:YEND) )            ! Slope of Ball-Berry rs-P relationship\n  ALLOCATE ( hvt_2D     (XSTART:XEND,YSTART:YEND) )            ! Canopy Height\n  ALLOCATE ( mfsno_2D   (XSTART:XEND,YSTART:YEND) )            ! Snow cover m parameter\n  ALLOCATE ( rsurfexp_2D(XSTART:XEND,YSTART:YEND) )            ! exponent in the shape parameter for soil resistance option 1\n  ALLOCATE ( axaj_2D    (XSTART:XEND,YSTART:YEND) )            ! Tension water distribution inflection parameter [-]\n  ALLOCATE ( bxaj_2D    (XSTART:XEND,YSTART:YEND) )            ! Tension water distribution shape parameter [-]\n  ALLOCATE ( xxaj_2D    (XSTART:XEND,YSTART:YEND) )            ! Free water distribution shape parameter [-]\n  ALLOCATE ( imperv_2D  (XSTART:XEND,YSTART:YEND) )            ! impervious fraction\n  ALLOCATE ( ssi_2D     (XSTART:XEND,YSTART:YEND) )            ! liquid water holding capacity for snowpack (m3/m3)\n  ALLOCATE ( snowretfac_2D (XSTART:XEND,YSTART:YEND) )         ! snowpack water release timescale factor (1/s)\n  ALLOCATE ( tau0_2D    (XSTART:XEND,YSTART:YEND) )            ! tau0 from Yang97 eqn. 10a\n  ALLOCATE ( rsurfsnow_2D (XSTART:XEND,YSTART:YEND) )          ! surface resistence for snow [s/m]\n  ALLOCATE ( scamax_2D  (XSTART:XEND,YSTART:YEND) )            ! maximum fractional snow covered area (0.0-1.0)\n#endif\n\n! INOUT (with generic LSM equivalent) (as defined in WRF)\n\n  ALLOCATE ( TSK       (XSTART:XEND,YSTART:YEND) )  ! surface radiative temperature [K]\n  ALLOCATE ( HFX       (XSTART:XEND,YSTART:YEND) )  ! sensible heat flux [W m-2]\n  ALLOCATE ( QFX       (XSTART:XEND,YSTART:YEND) )  ! latent heat flux [kg s-1 m-2]\n  ALLOCATE ( LH        (XSTART:XEND,YSTART:YEND) )  ! latent heat flux [W m-2]\n  ALLOCATE ( GRDFLX    (XSTART:XEND,YSTART:YEND) )  ! ground/snow heat flux [W m-2]\n  ALLOCATE ( SMSTAV    (XSTART:XEND,YSTART:YEND) )  ! soil moisture avail. [not used]\n  ALLOCATE ( SMSTOT    (XSTART:XEND,YSTART:YEND) )  ! total soil water [mm][not used]\n  ALLOCATE ( SFCRUNOFF (XSTART:XEND,YSTART:YEND) )  ! accumulated surface runoff [m]\n  ALLOCATE ( UDRUNOFF  (XSTART:XEND,YSTART:YEND) )  ! accumulated sub-surface runoff [m]\n  ALLOCATE ( ALBEDO    (XSTART:XEND,YSTART:YEND) )  ! total grid albedo []\n  ALLOCATE ( SNOWC     (XSTART:XEND,YSTART:YEND) )  ! snow cover fraction []\n  ALLOCATE ( SMOISEQ   (XSTART:XEND,1:NSOIL,YSTART:YEND) )     ! eq volumetric soil moisture [m3/m3]\n  ALLOCATE ( SMOIS     (XSTART:XEND,1:NSOIL,YSTART:YEND) )     ! volumetric soil moisture [m3/m3]\n  ALLOCATE ( SH2O      (XSTART:XEND,1:NSOIL,YSTART:YEND) )     ! volumetric liquid soil moisture [m3/m3]\n  ALLOCATE ( TSLB      (XSTART:XEND,1:NSOIL,YSTART:YEND) )     ! soil temperature [K]\n  !ALLOCATE ( SNOW      (XSTART:XEND,YSTART:YEND) )  ! snow water equivalent [mm]\n  !ALLOCATE ( SNOWH     (XSTART:XEND,YSTART:YEND) )  ! physical snow depth [m]\n  ALLOCATE ( CANWAT    (XSTART:XEND,YSTART:YEND) )  ! total canopy water + ice [mm]\n  ALLOCATE ( ACSNOM    (XSTART:XEND,YSTART:YEND) )  ! accumulated snow melt leaving pack\n  ALLOCATE ( ACSNOW    (XSTART:XEND,YSTART:YEND) )  ! accumulated snow on grid\n  ALLOCATE ( EMISS     (XSTART:XEND,YSTART:YEND) )  ! surface bulk emissivity\n  ALLOCATE ( QSFC      (XSTART:XEND,YSTART:YEND) )  ! bulk surface specific humidity\n\n! INOUT (with no Noah LSM equivalent) (as defined in WRF)\n\n  ALLOCATE ( ISNOWXY   (XSTART:XEND,YSTART:YEND) )  ! actual no. of snow layers\n  ALLOCATE ( TVXY      (XSTART:XEND,YSTART:YEND) )  ! vegetation leaf temperature\n  ALLOCATE ( TGXY      (XSTART:XEND,YSTART:YEND) )  ! bulk ground surface temperature\n  ALLOCATE ( CANICEXY  (XSTART:XEND,YSTART:YEND) )  ! canopy-intercepted ice (mm)\n  ALLOCATE ( CANLIQXY  (XSTART:XEND,YSTART:YEND) )  ! canopy-intercepted liquid water (mm)\n  ALLOCATE ( EAHXY     (XSTART:XEND,YSTART:YEND) )  ! canopy air vapor pressure (pa)\n  ALLOCATE ( TAHXY     (XSTART:XEND,YSTART:YEND) )  ! canopy air temperature (k)\n  ALLOCATE ( CMXY      (XSTART:XEND,YSTART:YEND) )  ! bulk momentum drag coefficient\n  ALLOCATE ( CHXY      (XSTART:XEND,YSTART:YEND) )  ! bulk sensible heat exchange coefficient\n  ALLOCATE ( FWETXY    (XSTART:XEND,YSTART:YEND) )  ! wetted or snowed fraction of the canopy (-)\n  ALLOCATE ( SNEQVOXY  (XSTART:XEND,YSTART:YEND) )  ! snow mass at last time step(mm h2o)\n  ALLOCATE ( ALBOLDXY  (XSTART:XEND,YSTART:YEND) )  ! snow albedo at last time step (-)\n  ALLOCATE ( QSNOWXY   (XSTART:XEND,YSTART:YEND) )  ! snowfall on the ground [mm/s]\n  ALLOCATE ( QRAINXY   (XSTART:XEND,YSTART:YEND) )  ! rainfall on the ground [mm/s]\n  ALLOCATE ( WSLAKEXY  (XSTART:XEND,YSTART:YEND) )  ! lake water storage [mm]\n  ALLOCATE ( ZWTXY     (XSTART:XEND,YSTART:YEND) )  ! water table depth [m]\n  ALLOCATE ( WAXY      (XSTART:XEND,YSTART:YEND) )  ! water in the \"aquifer\" [mm]\n  ALLOCATE ( WTXY      (XSTART:XEND,YSTART:YEND) )  ! groundwater storage [mm]\n  ALLOCATE ( SMCWTDXY  (XSTART:XEND,YSTART:YEND) )  ! soil moisture below the bottom of the column (m3m-3)\n  ALLOCATE ( DEEPRECHXY(XSTART:XEND,YSTART:YEND) )  ! recharge to the water table when deep (m)\n  ALLOCATE ( RECHXY    (XSTART:XEND,YSTART:YEND) )  ! recharge to the water table (diagnostic) (m)\n  !ALLOCATE ( TSNOXY    (XSTART:XEND,-NSNOW+1:0,    YSTART:YEND) )  ! snow temperature [K]\n  !ALLOCATE ( ZSNSOXY   (XSTART:XEND,-NSNOW+1:NSOIL,YSTART:YEND) )  ! snow layer depth [m]\n  !ALLOCATE ( SNICEXY   (XSTART:XEND,-NSNOW+1:0,    YSTART:YEND) )  ! snow layer ice [mm]\n  !ALLOCATE ( SNLIQXY   (XSTART:XEND,-NSNOW+1:0,    YSTART:YEND) )  ! snow layer liquid water [mm]\n  ALLOCATE ( LFMASSXY  (XSTART:XEND,YSTART:YEND) )  ! leaf mass [g/m2]\n  ALLOCATE ( RTMASSXY  (XSTART:XEND,YSTART:YEND) )  ! mass of fine roots [g/m2]\n  ALLOCATE ( STMASSXY  (XSTART:XEND,YSTART:YEND) )  ! stem mass [g/m2]\n  ALLOCATE ( WOODXY    (XSTART:XEND,YSTART:YEND) )  ! mass of wood (incl. woody roots) [g/m2]\n  ALLOCATE ( STBLCPXY  (XSTART:XEND,YSTART:YEND) )  ! stable carbon in deep soil [g/m2]\n  ALLOCATE ( FASTCPXY  (XSTART:XEND,YSTART:YEND) )  ! short-lived carbon, shallow soil [g/m2]\n  ALLOCATE ( LAI       (XSTART:XEND,YSTART:YEND) )  ! leaf area index\n  ALLOCATE ( XSAIXY    (XSTART:XEND,YSTART:YEND) )  ! stem area index\n  ALLOCATE ( TAUSSXY   (XSTART:XEND,YSTART:YEND) )  ! snow age factor\n\n! OUT (with no Noah LSM equivalent) (as defined in WRF)\n\n  ALLOCATE ( T2MVXY    (XSTART:XEND,YSTART:YEND) )  ! 2m temperature of vegetation part\n  ALLOCATE ( T2MBXY    (XSTART:XEND,YSTART:YEND) )  ! 2m temperature of bare ground part\n  ALLOCATE ( Q2MVXY    (XSTART:XEND,YSTART:YEND) )  ! 2m mixing ratio of vegetation part\n  ALLOCATE ( Q2MBXY    (XSTART:XEND,YSTART:YEND) )  ! 2m mixing ratio of bare ground part\n  ALLOCATE ( TRADXY    (XSTART:XEND,YSTART:YEND) )  ! surface radiative temperature (k)\n  ALLOCATE ( NEEXY     (XSTART:XEND,YSTART:YEND) )  ! net ecosys exchange (g/m2/s CO2)\n  ALLOCATE ( GPPXY     (XSTART:XEND,YSTART:YEND) )  ! gross primary assimilation [g/m2/s C]\n  ALLOCATE ( NPPXY     (XSTART:XEND,YSTART:YEND) )  ! net primary productivity [g/m2/s C]\n  ALLOCATE ( FVEGXY    (XSTART:XEND,YSTART:YEND) )  ! Noah-MP vegetation fraction [-]\n  ALLOCATE ( RUNSFXY   (XSTART:XEND,YSTART:YEND) )  ! surface runoff [mm/s]\n  ALLOCATE ( RUNSBXY   (XSTART:XEND,YSTART:YEND) )  ! subsurface runoff [mm/s]\n  ALLOCATE ( ECANXY    (XSTART:XEND,YSTART:YEND) )  ! evaporation of intercepted water (mm/s)\n  ALLOCATE ( EDIRXY    (XSTART:XEND,YSTART:YEND) )  ! soil surface evaporation rate (mm/s]\n  ALLOCATE ( ETRANXY   (XSTART:XEND,YSTART:YEND) )  ! transpiration rate (mm/s)\n  ALLOCATE ( FSAXY     (XSTART:XEND,YSTART:YEND) )  ! total absorbed solar radiation (w/m2)\n  ALLOCATE ( FIRAXY    (XSTART:XEND,YSTART:YEND) )  ! total net longwave rad (w/m2) [+ to atm]\n  ALLOCATE ( APARXY    (XSTART:XEND,YSTART:YEND) )  ! photosyn active energy by canopy (w/m2)\n  ALLOCATE ( PSNXY     (XSTART:XEND,YSTART:YEND) )  ! total photosynthesis (umol co2/m2/s) [+]\n  ALLOCATE ( SAVXY     (XSTART:XEND,YSTART:YEND) )  ! solar rad absorbed by veg. (w/m2)\n  ALLOCATE ( SAGXY     (XSTART:XEND,YSTART:YEND) )  ! solar rad absorbed by ground (w/m2)\n  ALLOCATE ( RSSUNXY   (XSTART:XEND,YSTART:YEND) )  ! sunlit leaf stomatal resistance (s/m)\n  ALLOCATE ( RSSHAXY   (XSTART:XEND,YSTART:YEND) )  ! shaded leaf stomatal resistance (s/m)\n  ALLOCATE ( ALBSNDXY  (XSTART:XEND,1:2,YSTART:YEND) )  ! snow albedo (direct)\n  ALLOCATE ( ALBSNIXY  (XSTART:XEND,1:2,YSTART:YEND) )  ! snow albedo (diffuse)\n  ALLOCATE ( BGAPXY    (XSTART:XEND,YSTART:YEND) )  ! between gap fraction\n  ALLOCATE ( WGAPXY    (XSTART:XEND,YSTART:YEND) )  ! within gap fraction\n  ALLOCATE ( TGVXY     (XSTART:XEND,YSTART:YEND) )  ! under canopy ground temperature[K]\n  ALLOCATE ( TGBXY     (XSTART:XEND,YSTART:YEND) )  ! bare ground temperature [K]\n  ALLOCATE ( CHVXY     (XSTART:XEND,YSTART:YEND) )  ! sensible heat exchange coefficient vegetated\n  ALLOCATE ( CHBXY     (XSTART:XEND,YSTART:YEND) )  ! sensible heat exchange coefficient bare-ground\n  ALLOCATE ( SHGXY     (XSTART:XEND,YSTART:YEND) )  ! veg ground sen. heat [w/m2]   [+ to atm]\n  ALLOCATE ( SHCXY     (XSTART:XEND,YSTART:YEND) )  ! canopy sen. heat [w/m2]   [+ to atm]\n  ALLOCATE ( SHBXY     (XSTART:XEND,YSTART:YEND) )  ! bare sensible heat [w/m2]  [+ to atm]\n  ALLOCATE ( EVGXY     (XSTART:XEND,YSTART:YEND) )  ! veg ground evap. heat [w/m2]  [+ to atm]\n  ALLOCATE ( EVBXY     (XSTART:XEND,YSTART:YEND) )  ! bare soil evaporation [w/m2]  [+ to atm]\n  ALLOCATE ( GHVXY     (XSTART:XEND,YSTART:YEND) )  ! veg ground heat flux [w/m2]  [+ to soil]\n  ALLOCATE ( GHBXY     (XSTART:XEND,YSTART:YEND) )  ! bare ground heat flux [w/m2] [+ to soil]\n  ALLOCATE ( IRGXY     (XSTART:XEND,YSTART:YEND) )  ! veg ground net LW rad. [w/m2] [+ to atm]\n  ALLOCATE ( IRCXY     (XSTART:XEND,YSTART:YEND) )  ! canopy net LW rad. [w/m2] [+ to atm]\n  ALLOCATE ( IRBXY     (XSTART:XEND,YSTART:YEND) )  ! bare net longwave rad. [w/m2] [+ to atm]\n  ALLOCATE ( TRXY      (XSTART:XEND,YSTART:YEND) )  ! transpiration [w/m2]  [+ to atm]\n  ALLOCATE ( EVCXY     (XSTART:XEND,YSTART:YEND) )  ! canopy evaporation heat [w/m2]  [+ to atm]\n  ALLOCATE ( CHLEAFXY  (XSTART:XEND,YSTART:YEND) )  ! leaf exchange coefficient\n  ALLOCATE ( CHUCXY    (XSTART:XEND,YSTART:YEND) )  ! under canopy exchange coefficient\n  ALLOCATE ( CHV2XY    (XSTART:XEND,YSTART:YEND) )  ! veg 2m exchange coefficient\n  ALLOCATE ( CHB2XY    (XSTART:XEND,YSTART:YEND) )  ! bare 2m exchange coefficient\n  ALLOCATE ( Z0        (XSTART:XEND,YSTART:YEND) )  ! roughness length output to WRF\n  ALLOCATE ( ZNT       (XSTART:XEND,YSTART:YEND) )  ! roughness length output to WRF\n\n  ALLOCATE ( XLONIN    (XSTART:XEND,YSTART:YEND) )  ! longitude\n  ALLOCATE ( TERRAIN   (XSTART:XEND,YSTART:YEND) )  ! terrain height\n  ALLOCATE ( GVFMIN    (XSTART:XEND,YSTART:YEND) )  ! annual minimum in vegetation fraction\n  ALLOCATE ( GVFMAX    (XSTART:XEND,YSTART:YEND) )  ! annual maximum in vegetation fraction\n\n!------------------------------------------------------------------------\n! Needed for MMF_RUNOFF (IOPT_RUN = 5); not part of MP driver in WRF\n!------------------------------------------------------------------------\n\n  ALLOCATE ( MSFTX       (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( MSFTY       (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( EQZWT       (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( RIVERBEDXY  (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( RIVERCONDXY (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( PEXPXY      (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( FDEPTHXY    (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( AREAXY      (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( QRFSXY      (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( QSPRINGSXY  (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( QRFXY       (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( QSPRINGXY   (XSTART:XEND,YSTART:YEND) )  !\n  ALLOCATE ( QSLATXY     (XSTART:XEND,YSTART:YEND) )  !\n\n!------------------------------------------------------------------------\n\n  ALLOCATE ( CHSTARXY  (XSTART:XEND,YSTART:YEND) )  ! for consistency with MP_init; delete later\n  ALLOCATE ( SEAICE    (XSTART:XEND,YSTART:YEND) )  ! seaice fraction\n  if (crocus_opt /= 0) then\n     ALLOCATE ( PSNOWTHRUFALXY (XSTART:XEND,YSTART:YEND) )\n     ALLOCATE ( PSNOWALBXY     (XSTART:XEND,YSTART:YEND) )\n     ALLOCATE ( PSNOWHEIGHTXY  (XSTART:XEND,YSTART:YEND) )\n     ALLOCATE ( PSNOWTOTSWEXY  (XSTART:XEND,YSTART:YEND) )\n     ALLOCATE ( FLOW_SNOW      (XSTART:XEND,YSTART:YEND) )\n     ALLOCATE ( FLOW_ICE       (XSTART:XEND,YSTART:YEND) )\n     ALLOCATE ( PSNOWHEATXY    (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWRHOXY     (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWSWEXY     (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWGRAN1XY   (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWGRAN2XY   (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWAGEXY     (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWLIQXY     (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWTEMPXY    (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWDZXY      (XSTART:XEND,1:act_lev,YSTART:YEND) )\n     ALLOCATE ( PSNOWHISTXY    (XSTART:XEND,1:act_lev,YSTART:YEND) )\n   end if ! crocus_opt /= 0\n\n#ifdef WRF_HYDRO\n   allocate( greenfrac   (XSTART:XEND,YSTART:YEND))\n   greenfrac = 0\n\n   ALLOCATE ( ACCPRCP  (XSTART:XEND,YSTART:YEND) )  ! accumulated precip [mm]\n   ALLOCATE ( ACCECAN  (XSTART:XEND,YSTART:YEND) )  ! accumulated canopy evap [mm]\n   ALLOCATE ( ACCETRAN  (XSTART:XEND,YSTART:YEND) )  ! accumulated transpiration [mm]\n   ALLOCATE ( ACCEDIR  (XSTART:XEND,YSTART:YEND) )  ! accumulated direct soil evap [mm]\n\n   ALLOCATE ( SOILSAT_TOP  (XSTART:XEND,YSTART:YEND) )  ! top 2 layer soil saturation [fraction]\n   ALLOCATE ( SOILSAT  (XSTART:XEND,YSTART:YEND) )  ! column integrated soil saturation [fraction]\n   ALLOCATE ( SOILICE  (XSTART:XEND,YSTART:YEND) )  ! fraction of soil moisture that is ice [fraction]\n   ALLOCATE ( SNOWT_AVG  (XSTART:XEND,YSTART:YEND) )  ! snowpack average temperature (by layer mass) [K]\n\n ! Initialize accumulator variables to 0\n   ACCPRCP = 0.0\n   ACCECAN = 0.0\n   ACCETRAN = 0.0\n   ACCEDIR = 0.0\n#endif\n\n  COSZEN     = undefined_real\n  XLAT_URB2D = undefined_real\n  DZ8W       = undefined_real\n  DZS        = undefined_real\n  IVGTYP     = undefined_int\n  if (crocus_opt /= 0) then\n     GLACINFO   = undefined_int\n     GLACT      = undefined_real\n     VIS_ICEALB = undefined_real\n  end if\n  ISLTYP     = undefined_int\n  VEGFRA     = undefined_real\n  GVFMAX     = undefined_real\n  TMN        = undefined_real\n  XLAND      = undefined_real\n  XICE       = undefined_real\n  T_PHY      = undefined_real\n  QV_CURR    = undefined_real\n  U_PHY      = undefined_real\n  V_PHY      = undefined_real\n  SWDOWN     = undefined_real\n  GLW        = undefined_real\n  P8W        = undefined_real\n  RAINBL     = undefined_real\n  SNOWBL     = undefined_real\n  RAINBL_tmp = undefined_real\n  SR         = undefined_real\n  RAINCV     = undefined_real\n  RAINNCV    = undefined_real\n  RAINSHV    = undefined_real\n  SNOWNCV    = undefined_real\n  GRAUPELNCV = undefined_real\n  HAILNCV    = undefined_real\n  TSK        = undefined_real\n  QFX        = undefined_real\n  SMSTAV     = undefined_real\n  SMSTOT     = undefined_real\n  SMOIS      = undefined_real\n  SH2O       = undefined_real\n  TSLB       = undefined_real\n  !SNOW       = undefined_real\n  !SNOWH      = undefined_real\n  CANWAT     = undefined_real\n  ACSNOM     = 0.0\n  ACSNOW     = 0.0\n  QSFC       = undefined_real\n  SFCRUNOFF  = 0.0\n  UDRUNOFF   = 0.0\n  SMOISEQ    = undefined_real\n  ALBEDO     = undefined_real\n  ISNOWXY    = undefined_int\n  TVXY       = undefined_real\n  TGXY       = undefined_real\n  CANICEXY   = undefined_real\n  CANLIQXY   = undefined_real\n  EAHXY      = undefined_real\n  TAHXY      = undefined_real\n  CMXY       = undefined_real\n  CHXY       = undefined_real\n  FWETXY     = undefined_real\n  SNEQVOXY   = undefined_real\n  ALBOLDXY   = undefined_real\n  QSNOWXY    = undefined_real\n  QRAINXY    = undefined_real\n  WSLAKEXY   = undefined_real\n  ZWTXY      = undefined_real\n  WAXY       = undefined_real\n  WTXY       = undefined_real\n  !TSNOXY     = undefined_real\n  !SNICEXY    = undefined_real\n  !SNLIQXY    = undefined_real\n  LFMASSXY   = undefined_real\n  RTMASSXY   = undefined_real\n  STMASSXY   = undefined_real\n  WOODXY     = undefined_real\n  STBLCPXY   = undefined_real\n  FASTCPXY   = undefined_real\n  LAI        = undefined_real\n  XSAIXY     = undefined_real\n  TAUSSXY    = undefined_real\n  XLONIN     = undefined_real\n  SEAICE     = undefined_real\n  SMCWTDXY   = undefined_real\n  DEEPRECHXY = 0.0\n  RECHXY     = 0.0\n  !ZSNSOXY    = undefined_real\n  GRDFLX     = undefined_real\n  HFX        = undefined_real\n  LH         = undefined_real\n  EMISS      = undefined_real\n  SNOWC      = undefined_real\n  T2MVXY     = undefined_real\n  T2MBXY     = undefined_real\n  Q2MVXY     = undefined_real\n  Q2MBXY     = undefined_real\n  TRADXY     = undefined_real\n  NEEXY      = undefined_real\n  GPPXY      = undefined_real\n  NPPXY      = undefined_real\n  FVEGXY     = undefined_real\n  RUNSFXY    = undefined_real\n  RUNSBXY    = undefined_real\n  ECANXY     = undefined_real\n  EDIRXY     = undefined_real\n  ETRANXY    = undefined_real\n  FSAXY      = undefined_real\n  FIRAXY     = undefined_real\n  APARXY     = undefined_real\n  PSNXY      = undefined_real\n  SAVXY      = undefined_real\n  FIRAXY     = undefined_real\n  SAGXY      = undefined_real\n  RSSUNXY    = undefined_real\n  RSSHAXY    = undefined_real\n  ALBSNDXY   = undefined_real\n  ALBSNIXY   = undefined_real\n  BGAPXY     = undefined_real\n  WGAPXY     = undefined_real\n  TGVXY      = undefined_real\n  TGBXY      = undefined_real\n  CHVXY      = undefined_real\n  CHBXY      = undefined_real\n  SHGXY      = undefined_real\n  SHCXY      = undefined_real\n  SHBXY      = undefined_real\n  EVGXY      = undefined_real\n  EVBXY      = undefined_real\n  GHVXY      = undefined_real\n  GHBXY      = undefined_real\n  IRGXY      = undefined_real\n  IRCXY      = undefined_real\n  IRBXY      = undefined_real\n  TRXY       = undefined_real\n  EVCXY      = undefined_real\n  CHLEAFXY   = undefined_real\n  CHUCXY     = undefined_real\n  CHV2XY     = undefined_real\n  CHB2XY     = undefined_real\n  TERRAIN    = undefined_real\n  GVFMIN     = undefined_real\n  GVFMAX     = undefined_real\n  MSFTX      = undefined_real\n  MSFTY      = undefined_real\n  EQZWT      = undefined_real\n  RIVERBEDXY = undefined_real\n  RIVERCONDXY= undefined_real\n  PEXPXY     = undefined_real\n  FDEPTHXY   = undefined_real\n  AREAXY     = undefined_real\n  QRFSXY     = undefined_real\n  QSPRINGSXY = undefined_real\n  QRFXY      = undefined_real\n  QSPRINGXY  = undefined_real\n  QSLATXY    = undefined_real\n  CHSTARXY   = undefined_real\n  Z0         = undefined_real\n  ZNT        = undefined_real\n\n#ifdef WRF_HYDRO\n  SOILSAT_TOP = undefined_real\n  SOILSAT     = undefined_real\n  SOILICE     = undefined_real\n  SNOWT_AVG   = undefined_real\n#endif\n\n  XLAND          = 1.0   ! water = 2.0, land = 1.0\n  XICE           = 0.0   ! fraction of grid that is seaice\n  XICE_THRESHOLD = 0.5   ! fraction of grid determining seaice (from WRF)\n\n!----------------------------------------------------------------------\n! Read Landuse Type and Soil Texture and Other Information\n!----------------------------------------------------------------------\n\n  CALL READLAND_HRLDAS(noah_lsm%HRLDAS_SETUP_FILE, XSTART, XEND, YSTART, &\n                       YEND,   ISWATER,    ISLAKE,   IVGTYP, &\n                       ISLTYP, TERRAIN,    TMN,      XLAT_URB2D, &\n                       XLONIN, XLAND,      SEAICE,   MSFTX, &\n                       MSFTY,  crocus_opt, GLACINFO, GLACT, &\n                       VIS_ICEALB)\n\n  WHERE(SEAICE > 0.0) XICE = 1.0\n\n!----------------------------------------------------------------------\n! Crocus: Initialize glacier\n!----------------------------------------------------------------------\n  if (crocus_opt /= 0) then\n     !PSNOWLIQXY     = undefined_real\n     !PSNOWTEMPXY    = undefined_real\n     !PSNOWDZXY      = undefined_real\n     !PSNOWHEATXY    = undefined_real\n     !PSNOWRHOXY     = undefined_real\n     !PSNOWSWEXY     = undefined_real\n     !PSNOWGRAN1XY   = undefined_real\n     !PSNOWGRAN2XY   = undefined_real\n     !PSNOWHISTXY    = undefined_real\n     !PSNOWALBXY     = undefined_real\n     !PSNOWTHRUFALXY = undefined_real\n     !PSNOWHEIGHTXY  = undefined_real\n     !PSNOWTOTSWEXY  = undefined_real\n     !FLOW_SNOW      = undefined_real\n     !FLOW_ICE       = undefined_real\n     !PSNOWAGEXY     = undefined_real\n\n! These should probably be kept initialized with an undefined value (above)\n! to allow tracking of cells that fall through the cracks in value updates\n! (also worth noting that 0 is not a valid value for all of these variables).\n! However, since restarts are not currently water-masking 2d reals, this makes\n! for odd value ranges in the LSM restarts so leaving as 0s for now.\n! On quick tests, the only one of these that changes answers if NOT initialized\n! at 0 is PSNOWHISTXY so making sure that one is covered in value initialization\n! loop below in case we go back to undefined_real for these.\n     PSNOWLIQXY     = 0.\n     PSNOWTEMPXY    = 0.\n     PSNOWDZXY      = 0.\n     PSNOWHEATXY    = 0.\n     PSNOWRHOXY     = 0.\n     PSNOWSWEXY     = 0.\n     PSNOWGRAN1XY   = 0.\n     PSNOWGRAN2XY   = 0.\n     PSNOWHISTXY    = 0.\n     PSNOWALBXY     = 0.\n     PSNOWTHRUFALXY = 0.\n     PSNOWHEIGHTXY  = 0.\n     PSNOWTOTSWEXY  = 0.\n     FLOW_ICE       = 0.\n     FLOW_SNOW      = 0.\n     PSNOWAGEXY     = 0.\n\n     WHERE(GLACINFO > 0.0) PSNOWALBXY=0.35\n\n     do kk = 1, act_lev\n        WHERE(GLACINFO > 0.0) PSNOWRHOXY  (:,kk,:) = 900.\n        WHERE(GLACINFO > 0.0) PSNOWDZXY   (:,kk,:) = GLACT/act_lev\n        WHERE(GLACINFO > 0.0) PSNOWSWEXY  (:,kk,:) = PSNOWDZXY(:,kk,:)*PSNOWRHOXY(:,KK,:)\n        WHERE(GLACINFO > 0.0) PSNOWHEATXY (:,kk,:) = -PSNOWSWEXY(:,kk,:)*333231.05\n        WHERE(GLACINFO > 0.0) PSNOWGRAN1XY(:,kk,:) = 0.0009\n        WHERE(GLACINFO > 0.0) PSNOWGRAN2XY(:,kk,:) = 99    ! 1\n        WHERE(GLACINFO > 0.0) PSNOWAGEXY  (:,kk,:) = 20000\n        WHERE(GLACINFO > 0.0) PSNOWHISTXY  (:,kk,:) = 0.\n     enddo\n\n     CALL INI_CSTS\n  end if ! crocus_opt /= 0\n\n\n!------------------------------------------------------------------------\n! For spatially-varying soil parameters, read in necessary extra fields\n!------------------------------------------------------------------------\n\n#ifdef SPATIAL_SOIL\n    CALL READ_3D_SOIL(noah_lsm%SPATIAL_FILENAME, XSTART, XEND, YSTART, YEND, &\n                      NSOIL,BEXP_3D,SMCDRY_3D,SMCWLT_3D,SMCREF_3D,SMCMAX_3D,  &\n\t\t      DKSAT_3D,DWSAT_3D,PSISAT_3D,QUARTZ_3D,REFDK_2D,REFKDT_2D,&\n\t\t      SLOPE_2D,CWPVT_2D,VCMX25_2D,MP_2D,HVT_2D,MFSNO_2D,RSURFEXP_2D, &\n                      SSI_2D,SNOWRETFAC_2D,TAU0_2D,RSURFSNOW_2D,SCAMAX_2D)\n\n    if (noah_lsm%runoff_option == 7) then\n        CALL READ_XAJ_RUNOFF(noah_lsm%SPATIAL_FILENAME,XSTART, XEND, YSTART, YEND, &\n                             AXAJ_2D,BXAJ_2D,XXAJ_2D)\n    end if\n\n    if (noah_lsm%imperv_option > 0 .and. noah_lsm%imperv_option < 9) then\n        CALL READ_IMPERV(noah_lsm%SPATIAL_FILENAME,XSTART, XEND, YSTART, YEND, &\n                             IMPERV_2D)\n    end if\n\n#endif\n\n!------------------------------------------------------------------------\n! For IOPT_RUN = 5 (MMF groundwater), read in necessary extra fields\n! This option is not tested for parallel use in the offline driver\n!------------------------------------------------------------------------\n\n  if (noah_lsm%runoff_option == 5) then\n    CALL READ_MMF_RUNOFF(noah_lsm%MMF_RUNOFF_FILE, XSTART, XEND, YSTART, YEND,&\n                         ZWTXY,EQZWT,RIVERBEDXY,RIVERCONDXY,PEXPXY,FDEPTHXY)\n  end if\n\n!----------------------------------------------------------------------\n! Initialize Model State\n!----------------------------------------------------------------------\n\n  SLOPETYP = 2\n  DZS       =  noah_lsm%SOIL_THICK_INPUT(1:NSOIL)\n\n  ITIMESTEP = 1\n\n  if (noah_lsm%restart_filename_requested /= \" \") then\n     restart_flag = .TRUE.\n\n  if(noah_lsm%rst_bi_in .eq. 0) then\n\n#ifdef WRF_HYDRO\n      tmpdate = olddate\n#endif\n\n     call find_restart_file(rank, trim(noah_lsm%restart_filename_requested), startdate, khour, olddate, restart_flnm)\n\n     call read_restart(trim(restart_flnm), xstart, xend, xstart, ixfull, jxfull, noah_lsm%nsoil, olddate)\n\n#ifdef WRF_HYDRO\n      olddate = tmpdate\n#endif\n\n       ITIMESTEP = 2\n\n#ifdef MPP_LAND\n     call mpp_land_bcast_char(19,OLDDATE(1:19))\n#endif\n\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SOIL_T\"  , TSLB     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SNOW_T\"  , state%TSNOXY   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SMC\"     , SMOIS    )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SH2O\"    , SH2O     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ZSNSO\"   , state%ZSNSOXY  )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SNICE\"   , state%SNICEXY  )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SNLIQ\"   , state%SNLIQXY  )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"QSNOW\"   , QSNOWXY  )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"FWET\"    , FWETXY   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SNEQVO\"  , SNEQVOXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"EAH\"     , EAHXY    )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"TAH\"     , TAHXY    )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ALBOLD\"  , ALBOLDXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"CM\"      , CMXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"CH\"      , CHXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ISNOW\"   , ISNOWXY  )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"CANLIQ\"  , CANLIQXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"CANICE\"  , CANICEXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SNEQV\"   , state%SNOW     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SNOWH\"   , state%SNOWH    )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"TV\"      , TVXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"TG\"      , TGXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ZWT\"     , ZWTXY    )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"WA\"      , WAXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"WT\"      , WTXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"WSLAKE\"  , WSLAKEXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"LFMASS\"  , LFMASSXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"RTMASS\"  , RTMASSXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"STMASS\"  , STMASSXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"WOOD\"    , WOODXY   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"STBLCP\"  , STBLCPXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"FASTCP\"  , FASTCPXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"LAI\"     , LAI      )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SAI\"     , XSAIXY   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"VEGFRA\"  , VEGFRA   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"GVFMIN\"  , GVFMIN   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"GVFMAX\"  , GVFMAX   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ACMELT\"  , ACSNOM   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ACSNOW\"  , ACSNOW   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"TAUSS\"   , TAUSSXY  )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"QSFC\"    , QSFC     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SFCRUNOFF\",SFCRUNOFF   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"UDRUNOFF\" ,UDRUNOFF    )\n     if (crocus_opt /= 0) then\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWAGE\",     PSNOWAGEXY    )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWDZ\",      PSNOWDZXY     )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWGRAN1\",   PSNOWGRAN1XY  )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWGRAN2\",   PSNOWGRAN2XY  )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWHEAT\",    PSNOWHEATXY   )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWHIST\",    PSNOWHISTXY   )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWLIQ\",     PSNOWLIQXY    )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWRHO\",     PSNOWRHOXY    )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWSWE\",     PSNOWSWEXY    )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWTEMP\",    PSNOWTEMPXY   )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWALB\",     PSNOWALBXY    )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWHEIGHT\",  PSNOWHEIGHTXY )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWTHRUFAL\", PSNOWTHRUFALXY)\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PSNOWTOTSWE\",  PSNOWTOTSWEXY )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"FLOW_SNOW\",    FLOW_SNOW     )\n        call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"FLOW_ICE\",     FLOW_ICE      )\n     end if ! crocus_opt /= 0\n#ifdef WRF_HYDRO\n     if(checkRstV(\"ACCPRCP\") .eq. 0) call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ACCPRCP\"  ,ACCPRCP    )\n     if(checkRstV(\"ACCECAN\") .eq. 0) call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ACCECAN\"  ,ACCECAN    )\n     if(checkRstV(\"ACCEDIR\") .eq. 0) call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ACCEDIR\"  ,ACCEDIR    )\n     if(checkRstV(\"ACCETRAN\") .eq. 0) call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"ACCETRAN\" ,ACCETRAN    )\n#endif\n! below for opt_run = 5\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SMOISEQ\"   , SMOISEQ    )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"AREAXY\"    , AREAXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"SMCWTDXY\"  , SMCWTDXY   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"QRFXY\"     , QRFXY      )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"DEEPRECHXY\", DEEPRECHXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"QSPRINGXY\" , QSPRINGXY  )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"QSLATXY\"   , QSLATXY    )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"QRFSXY\"    , QRFSXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"QSPRINGSXY\", QSPRINGSXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"RECHXY\"    , RECHXY     )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"FDEPTHXY\"   ,FDEPTHXY   )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"RIVERCONDXY\",RIVERCONDXY)\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"RIVERBEDXY\" ,RIVERBEDXY )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"EQZWT\"      ,EQZWT      )\n     call get_from_restart(xstart, xend, xstart, ixfull, jxfull, \"PEXPXY\"     ,PEXPXY     )\n  else  !  rst_bi_in\n#ifdef MPP_LAND\n     call mpp_land_bcast_char(19,OLDDATE(1:19))\n#endif\n     ITIMESTEP = 2\n     call lsm_rst_bi_in(state)\n  endif\n\n     STEPWTD = nint(WTDDT*60./DTBL)\n     STEPWTD = max(STEPWTD,1)\n\n! Must still call NOAHMP_INIT even in restart to set up parameter arrays (also done in WRF)\n\n     CALL NOAHMP_INIT(    LLANDUSE,     state%SNOW,    state%SNOWH,   CANWAT,   ISLTYP,   IVGTYP, &   ! call from WRF phys_init\n                    TSLB,    SMOIS,     SH2O,      DZS, FNDSOILW, FNDSNOWH, &\n                     TSK,  ISNOWXY,     TVXY,     TGXY, CANICEXY,      TMN,     XICE, &\n                CANLIQXY,    EAHXY,    TAHXY,     CMXY,     CHXY,                     &\n                  FWETXY, SNEQVOXY, ALBOLDXY,  QSNOWXY, WSLAKEXY,    ZWTXY,     WAXY, &\n                    WTXY,   state%TSNOXY,  state%ZSNSOXY,  state%SNICEXY,  state%SNLIQXY, LFMASSXY, RTMASSXY, &\n                STMASSXY,   WOODXY, STBLCPXY, FASTCPXY,   XSAIXY, LAI,                    &\n                  T2MVXY,   T2MBXY, CHSTARXY,                                         &\n                   NSOIL,  .true.,                                                   &\n                  .true.,noah_lsm%runoff_option,noah_lsm%crop_option,noah_lsm%pedotransfer_option, &\n                  ids,ide+1, jds,jde+1, kds,kde,                &  ! domain\n                  ims,ime, jms,jme, kms,kme,                &  ! memory\n                  its,ite, jts,jte, kts,kte                 &  ! tile\n                     ,smoiseq  ,smcwtdxy ,rechxy   ,deeprechxy, areaxy ,dx, dy, msftx, msfty,&\n                     wtddt    ,stepwtd  ,dtbl  ,qrfsxy ,qspringsxy  ,qslatxy,                  &\n                     fdepthxy ,terrain ,riverbedxy ,eqzwt ,rivercondxy ,pexpxy              &\n                     )\n  else  ! for none restart\n\n     restart_flag = .FALSE.\n\n     SMOIS     =  undefined_real\n     TSLB      =  undefined_real\n     SH2O      =  undefined_real\n     CANLIQXY  =  undefined_real\n     TSK       =  undefined_real\n     RAINBL_tmp    =  undefined_real\n     !SNOW      =  undefined_real\n     !SNOWH     =  undefined_real\n\n! LRK - Remove HRLDAS_ini_typ for WRF-Hydro. Originally, there was a fork\n!       for difference forcing types, or if the user desired a different\n!       reading from wrfinput. However, for WRF-Hydro uses, we only use\n!       option 1 at this point, so removing all other potential options,\n!       which was 0 before. This will force the user to place SHDMIN/SHDMAX\n!       into the wrfinput file now as opposed to allowing it to be read\n!       in from the geogrid file.\n!#ifdef WRF_HYDRO\n!  if((forc_typ .gt. 2) .and. (forc_typ .ne. 6) ) HRLDAS_ini_typ = 0\n\n!  if(HRLDAS_ini_typ .eq. 1) then\n!     ! read initial parameters and conditions from the HRLDAS forcing data\n!     if(forc_typ .eq. 2) then\n!          inflnm = trim(indir)//\"/\"//&\n!          startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n!          startdate(15:16)//\".LDASIN_DOMAIN\"//hgrid\n!     else\n!          inflnm = trim(indir)//\"/\"//&\n!          startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n!          \".LDASIN_DOMAIN\"//hgrid\n!     endif\n\n!#else\n\n!     inflnm = trim(indir)//\"/\"//&\n!          startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n!          \".LDASIN_DOMAIN\"//hgrid\n!#endif\n\n     CALL READINIT_HRLDAS(noah_lsm%HRLDAS_SETUP_FILE, xstart, xend, ystart, yend,  &\n          NSOIL, DZS, OLDDATE, LDASIN_VERSION, SMOIS,       &\n          TSLB, CANWAT, TSK, state%SNOW, state%SNOWH, FNDSNOWH)\n\n!yw     VEGFRA    =  undefined_real\n!yw     LAI       =  undefined_real\n!yw     GVFMIN    =  undefined_real\n!yw     GVFMAX    =  undefined_real\n\n     CALL READVEG_HRLDAS(noah_lsm%HRLDAS_SETUP_FILE, xstart, xend, ystart, yend,  &\n          OLDDATE, IVGTYP, VEGFRA, LAI, GVFMIN, GVFMAX)\n\n!#ifdef WRF_HYDRO\n!  else   !  HRLDAS_ini_typ\n\n!#ifdef MPP_LAND\n!    call HYDRO_HRLDAS_ini_mpp   &\n!#else\n!    call HYDRO_HRLDAS_ini   &\n!#endif\n!       (trim(hrldas_setup_file), xend-xstart+1,yend-ystart+1, &\n!       nsoil,SMOIS(:,1:NSOIL,:),TSLB(:,1:NSOIL,:),SH2O(:,1:NSOIL,:), CANWAT, TSK,SNOW,SNOWH,lai,VEGFRA,IVGTYP,FNDSNOWH)\n!       if(maxval(VEGFRA) .le. 1)  VEGFRA = VEGFRA * 100\n\n!       greenfrac = 0.0\n!#ifdef MPP_LAND\n!        call get_greenfrac_mpp &\n!#else\n!      call get_greenfrac &\n!#endif\n!         (trim(GEO_STATIC_FLNM),greenfrac, ix, jx, olddate, GVFMAX)\n!        !yw GVFMAX = maxval(greenfrac)\n!\tif(maxval(GVFMAX) .le. 1)  GVFMAX = GVFMAX * 100\n!  endif   ! initialization type\n!#endif\n\n!     SNOW = SNOW * 1000.    ! Convert snow water equivalent to mm. MB: remove v3.7\n\n     FNDSOILW = .FALSE.\n     CALL NOAHMP_INIT(    LLANDUSE,     state%SNOW,    state%SNOWH,   CANWAT,   ISLTYP,   IVGTYP, &   ! call from WRF phys_init\n                    TSLB,    SMOIS,     SH2O,      DZS, FNDSOILW, FNDSNOWH, &\n                     TSK,  ISNOWXY,     TVXY,     TGXY, CANICEXY,      TMN,     XICE, &\n                CANLIQXY,    EAHXY,    TAHXY,     CMXY,     CHXY,                     &\n                  FWETXY, SNEQVOXY, ALBOLDXY,  QSNOWXY, WSLAKEXY,    ZWTXY,     WAXY, &\n                    WTXY,   state%TSNOXY,  state%ZSNSOXY,  state%SNICEXY,  state%SNLIQXY, LFMASSXY, RTMASSXY, &\n                STMASSXY,   WOODXY, STBLCPXY, FASTCPXY,   XSAIXY, LAI,                    &\n                  T2MVXY,   T2MBXY, CHSTARXY,                                         &\n                   NSOIL,  .false.,                                                   &\n                  .true.,noah_lsm%runoff_option,noah_lsm%crop_option,noah_lsm%pedotransfer_option,  &\n                  ids,ide+1, jds,jde+1, kds,kde,                &  ! domain\n                  ims,ime, jms,jme, kms,kme,                &  ! memory\n                  its,ite, jts,jte, kts,kte                 &  ! tile\n                     ,smoiseq  ,smcwtdxy ,rechxy   ,deeprechxy, areaxy ,dx, dy, msftx, msfty,&\n                     wtddt    ,stepwtd  ,dtbl  ,qrfsxy ,qspringsxy  ,qslatxy,                  &\n                     fdepthxy ,terrain ,riverbedxy ,eqzwt ,rivercondxy ,pexpxy              &\n                     )\n\n      TAUSSXY = 0.0   ! Need to be added to _INIT later\n\n\n  endif  ! end of restart if block\n\n  NTIME=(KHOUR)*3600./nint(dtbl)\n\n#ifdef HYDRO_D\n  print*, \"NTIME = \", NTIME , \"KHOUR=\",KHOUR,\"dtbl = \", dtbl\n#endif\n\n  ! assinging the KHOUR to be used in the NWM output routing for global metadata\n  nlst(did)%khour = khour\n\n  call system_clock(count=clock_count_1)   ! Start a timer\n\n  if (crocus_opt /= 0) &\n     PSNOWTHRUFALXY(:,:) = 0.\n\n#ifdef WRF_HYDRO\n   allocate( infxsrt   (ix,jx) )\n   allocate( sfcheadrt (ix,jx) )\n   allocate( soldrain  (ix,jx) )\n   allocate( etpnd     (ix,jx) )\n   allocate( prcp0     (ix,jx) )\n\n   prcp0     = 0\n   sfcheadrt = 0.0\n   infxsrt   = 0.0\n   etpnd     = 0.0\n   soldrain  = 0.0\n\n   allocate(zsoil (NSOIL))\n   zsoil = 0\n\n   zsoil(1) = -1 * noah_lsm%soil_thick_input(1)\n   do kk = 2, NSOIL\n      zsoil(kk) = zsoil(kk-1)-noah_lsm%soil_thick_input(kk)\n   end do\n#ifdef HYDRO_D\n   print*, \"zsoil/soil_thick_input = \", noah_lsm%soil_thick_input(1:NSOIL)\n#endif\n\n   call hrldas_drv_HYDRO_ini(TSLB(:,1:NSOIL,:),SMOIS(:,1:NSOIL,:),SH2O(:,1:NSOIL,:), &\n         infxsrt,sfcheadrt,soldrain,ix,jx,NSOIL, SMOIS,real(noah_lsm%noah_timestep), &\n         olddate,zsoil(1:NSOIL))\n\ncall get_iocflag(1, io_config_outputs)\ncall get_rstrt_swc(1, reset_flag)\n\n#ifdef WRF_HYDRO\nif (reset_flag == 1) then\n     ACCPRCP = 0.0\n     ACCECAN = 0.0\n     ACCEDIR = 0.0\n     ACCETRAN = 0.0\n     SFCRUNOFF = 0.0\n     UDRUNOFF = 0.0\n     ACSNOM = 0.0\n     ACSNOW = 0.0\nendif\n#endif\n\n   !!--- Setup variable list. Change as needed; rest of parsing should adapt automatically.\n   if (io_config_outputs .eq. 0) then\n        VARLIST = 'IVGTYP,ISLTYP,FVEG,LAI,SAI,SWFORC,COSZ,LWFORC,RAINRATE,EMISS,FSA,FIRA,GRDFLX,HFX,LH,ECAN,EDIR,ALBEDO,' // &\n                  'ETRAN,UGDRNOFF,SFCRNOFF,CANLIQ,CANICE,ZWT,WA,WT,ACCPRCP,ACCECAN,ACCEDIR,ACCETRAN,SAV,TR,EVC,IRC,SHC,' // &\n                  'IRG,SHG,EVG,GHV,SAG,IRB,SHB,EVB,GHB,TRAD,TG,TV,TAH,TGV,TGB,T2MV,T2MB,Q2MV,Q2MB,EAH,FWET,ZSNSO_SN,SNICE,' // &\n                  'SNLIQ,SOIL_T,SOIL_W,SNOW_T,SOIL_M,SNOWH,SNEQV,QSNOW,ISNOW,FSNO,ACSNOW,ACSNOM,CM,CH,CHV,CHB,CHLEAF,CHUC,' // &\n                  'CHV2,CHB2,LFMASS,RTMASS,STMASS,WOOD,STBLCP,FASTCP,NEE,GPP,NPP,PSN,APAR,ACCET,CANWAT,SOILICE,SOILSAT_TOP,'// &\n                  'SOILSAT,SNOWT_AVG,QRAIN,glacier,glacier_thickness,PSNOWALB,PSNOWTHRUFAL,PSNOWHEIGHT,PSNOWTOTSWE,'// &\n                  'PSNOWGRAN1,PSNOWGRAN2,PSNOWAGE,PSNOWTEMP,PSNOWDZ,PSNOWHIST,PSNOWLIQ,PSNOWHEAT,PSNOWRHO,PSNOWSWE,'// &\n                  'FLOW_ICE,FLOW_SNOW'\n\n   endif\n   if (io_config_outputs .eq. 1) then\n        VARLIST = 'SNOWH,SNEQV,FSNO,SOILSAT_TOP,SNOWT_AVG,ACCET'\n   endif\n   if (io_config_outputs .eq. 2) then\n        VARLIST = 'SNOWH,SNEQV,FSNO,SOILSAT_TOP,SNOWT_AVG,ACCET'\n   endif\n   if (io_config_outputs .eq. 3) then\n        VARLIST = 'UGDRNOFF,ACSNOM,SNOWH,SNEQV,ACCECAN,ACCETRAN,ACCEDIR,SNLIQ,ISNOW,SOIL_T,FSNO,SOIL_M,GRDFLX,HFX,LH,FIRA,FSA,TRAD,SOILSAT_TOP,SNOWT_AVG,SOILICE,ACCET,CANWAT'\n   endif\n   if (io_config_outputs .eq. 4) then\n        VARLIST = 'UGDRNOFF,SFCRNOFF,ACSNOM,SNEQV,SOILSAT_TOP,SOILSAT,ACCET,CANWAT,PET'\n   endif\n   if (io_config_outputs .eq. 5) then\n        VARLIST = 'UGDRNOFF,SFCRNOFF,ACCET,SNEQV,SNOWH,FSNO,SOIL_M,SOIL_W,TRAD,FIRA,FSA,LH,HFX'\n   endif\n   if (io_config_outputs .eq. 6) then\n        VARLIST = 'UGDRNOFF,SFCRNOFF,ACSNOM,SNOWH,SNEQV,ACCECAN,ACCETRAN,ACCEDIR,SNLIQ,ISNOW,SOIL_T,FSNO,SOIL_M,GRDFLX,HFX,LH,FIRA,FSA,TRAD,SOILSAT_TOP,SOILSAT,SNOWT_AVG,SOILICE,ACCET,CANWAT'\n   endif\n\n   !!--- Parse into character array. Constructor not valid with uneven\n   !!--- strings in f90 so using brute force.\n\n   do while (brkflag .eq. 0)\n      if (index(VARLIST, ',') .eq. 0) then\n          IOCVARS(varind) = adjustl(VARLIST)\n          brkflag = 1\n          if (varind > max_ioc_num_vars) then\n#ifdef MPP_LAND\n             call fatal_error_stop(\"ERROR: number of vars is greater than current max_num_vars\")\n#else\n             stop \"Error: number of vars is greater than current max_num_vars\"\n#endif\n          endif\n       else\n#ifdef HYDRO_D\n          if (len(adjustl(VARLIST(1:(index(VARLIST, ',')-1)))) > ioc_var_len) then\n             print *,\"WARNING: length of \", adjustl(VARLIST(1:(index(VARLIST, ',')-1))), &\n                  \" is longer than ioc_var_len\"\n          end if\n#endif\n          IOCVARS(varind) = adjustl(VARLIST(1:(index(VARLIST, ',')-1)))\n          VARLIST = VARLIST((index(VARLIST, ',')+1):)\n          varind = varind + 1\n       endif\n   end do\n\n   if(wrf_hydro%finemesh .ne. 0 ) then\n       if(restart_flag) then\n          NTIME_out =  10\n       else\n          NTIME_out =  1\n       endif\n       return\n   endif\n#endif\n\n   NTIME_out = NTIME\n\n#ifdef WRF_HYDRO\n   call get_t0OutputFlag(1, t0OutputFlag)\n#ifdef MPP_LAND\n   if(my_id .eq. io_id) &\n       print*, \"t0OutputFlag: \", t0OutputFlag\n#endif\n\n! ldas_output subroutine will be called when\n! the t0OutputFlag is 1 in the hydro.namelist\n! the ldas_output requires one variables ITIME\n! which is the LSM timestep, we declare it here\n! since it does not exist at this point\n  ITIME = 0\n  if(t0OutputFlag .eq. 1) call ldas_output(ITIME,state)\n!#else\n!  if (restart_filename_requested == \" \") then\n!     if(t0OutputFlag .eq. 1) call ldas_output()\n!  endif\n!#endif\n#endif\n\nend subroutine land_driver_ini\n\n!===============================================================================\n  subroutine land_driver_exe(itime, state)\n    use module_hydro_io, only: read_channel_only\n    use state_module, only: state_type\n    use module_date_utilities ! Calculating iday outside of loop now\n    implicit  none\n    type(state_type) :: state\n    integer :: itime          ! timestep loop\n    integer :: iday           ! Moved these outside calc_declin loop for speedup\n    integer :: ihr\n    integer :: imin\n    integer :: isec\n\n!---------------------------------------------------------------------------------\n! Read the forcing data.\n!---------------------------------------------------------------------------------\n\n#ifdef MPP_LAND\n     call mpp_land_bcast_char(19,OLDDATE(1:19))\n#endif\n\n#ifdef WRF_HYDRO\n!      if(forc_typ .eq. 8) then\n!          call read_forc_ldasout(olddate,hgrid, indir, dtbl,ix,jx,infxsrt,soldrain)\n!          call hrldas_drv_HYDRO(TSLB(:,1:NSOIL,:),SMOIS(:,1:NSOIL,:),SH2O(:,1:NSOIL,:),infxsrt,sfcheadrt,soldrain,ix,jx,NSOIL)\n!          return\n!      endif\n#endif\n\n#ifdef WRF_HYDRO\n      if(forc_typ .eq. 8) then\n          call read_forc_ldasout(olddate,hgrid, noah_lsm%indir, dtbl,ix,jx,infxsrt,soldrain)\n          call hrldas_drv_HYDRO(TSLB(:,1:NSOIL,:),SMOIS(:,1:NSOIL,:),SH2O(:,1:NSOIL,:),infxsrt,sfcheadrt,soldrain,ix,jx,NSOIL)\n          call geth_newdate(newdate, olddate, nint(dtbl))\n          olddate = newdate\n          return\n      endif\n      if(forc_typ .eq. 9 .or. forc_typ .eq. 10) then\n         !! JLM:: fix hgrid: This becomes 1 eventhough 3 is specified in hydro.namelist\n         !! JLM: This is initalized by read_hrldas_hdrinfo\n         !! JLM: Appears that we should differentiate the LSM and HYDRO igrids, define a local\n         !! JLM: igrid for this purpose.\n         !! JLM: ?*?* hrldas_drv_HYDRO.F should be made a module *?*?\n         !! JLM:  Simple modification which forces type, rank and kind checking...\n          call getNameList('igrid', igrid_hydro)  !! get hydro namelist info :: case sensitive\n          write(hgrid_hydro,'(I1)') igrid_hydro\n          call read_channel_only(olddate, hgrid_hydro, noah_lsm%indir, noah_lsm%forcing_timestep)\n          call hrldas_drv_HYDRO(TSLB(:,1:NSOIL,:),SMOIS(:,1:NSOIL,:),SH2O(:,1:NSOIL,:),infxsrt,sfcheadrt,soldrain,ix,jx,NSOIL)\n          call geth_newdate(newdate, olddate, nint(dtbl))\n          olddate = newdate\n          return\n      endif\n#endif\n\n! For HRLDAS, we're assuming (for now) that each time period is in a\n! separate file.  So we can open a new one right now.\n\n     inflnm = trim(noah_lsm%indir)//\"/\"//&\n          olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n          \".LDASIN_DOMAIN\"//hgrid\n\n     ! Build a filename template\n     inflnm_template = trim(noah_lsm%indir)//\"/<date>.LDASIN_DOMAIN\"//hgrid\n\n\n#ifdef WRF_HYDRO\n\n     if(wrf_hydro%finemesh .ne. 0) goto 991\n\n     if(forc_typ .eq. 0) then\n        CALL READFORC_HRLDAS(INFLNM_TEMPLATE, noah_lsm%FORCING_TIMESTEP, OLDDATE,  &\n             XSTART, XEND, YSTART, YEND,                                  &\n             noah_lsm%forcing_name_T ,noah_lsm%forcing_name_Q ,noah_lsm%forcing_name_U , &\n\t     noah_lsm%forcing_name_V ,noah_lsm%forcing_name_P ,noah_lsm%forcing_name_LW, &\n\t     noah_lsm%forcing_name_SW,noah_lsm%forcing_name_PR,noah_lsm%forcing_name_SN, &\n\t     noah_lsm%forcing_name_LF, &\n             T_PHY(:,1,:),QV_CURR(:,1,:),U_PHY(:,1,:),V_PHY(:,1,:),          &\n             P8W(:,1,:), GLW       ,SWDOWN      ,RAINBL_tmp, &\n             SNOWBL, VEGFRA, update_veg, LAI, &\n             update_lai)\n     else\n        if(olddate == forcDate) then\n           CALL HYDRO_frocing_drv(trim(noah_lsm%indir), forc_typ, wrf_hydro%snow_assim, olddate,                     &\n               xstart, xend, ystart, yend,    &\n               noah_lsm%forcing_name_T ,noah_lsm%forcing_name_Q ,noah_lsm%forcing_name_U , &\n               noah_lsm%forcing_name_V ,noah_lsm%forcing_name_P ,noah_lsm%forcing_name_LW, &\n               noah_lsm%forcing_name_SW,noah_lsm%forcing_name_PR,noah_lsm%forcing_name_SN, &\n               noah_lsm%forcing_name_LF, &\n               T_PHY(:,1,:), QV_CURR(:,1,:), U_PHY(:,1,:), V_PHY(:,1,:), &\n               P8W(:,1,:), GLW, SWDOWN, RAINBL_tmp, &\n               LAI, SNOWBL, VEGFRA, state%SNOWH, &\n               ITIME, noah_lsm%FORCING_TIMESTEP, prcp0)\n               if(maxval(VEGFRA) .le. 1)  VEGFRA = VEGFRA * 100\n\n           call geth_newdate(newdate, forcDate, noah_lsm%FORCING_TIMESTEP)\n           forcDate = newdate\n        endif\n     endif\n\n#else\n     CALL READFORC_HRLDAS(INFLNM_TEMPLATE, noah_lsm%FORCING_TIMESTEP, OLDDATE,  &\n          XSTART, XEND, YSTART, YEND,                                  &\n          noah_lsm%forcing_name_T ,noah_lsm%forcing_name_Q ,noah_lsm%forcing_name_U , &\n\t  noah_lsm%forcing_name_V ,noah_lsm%forcing_name_P ,noah_lsm%forcing_name_LW, &\n\t  noah_lsm%forcing_name_SW,noah_lsm%forcing_name_PR,noah_lsm%forcing_name_SN, &\n\t  noah_lsm%forcing_name_LF, &\n          T_PHY(:,1,:),QV_CURR(:,1,:),U_PHY(:,1,:),V_PHY(:,1,:),          &\n\t    P8W(:,1,:), GLW       ,SWDOWN      ,RAINBL_tmp, SNOWBL, VEGFRA, update_veg, LAI, update_lai)\n#endif\n\n991  continue\n\n     where(XLAND > 1.5)   T_PHY(:,1,:) = 0.0  ! Prevent some overflow problems with ifort compiler [MB:20150812]\n     where(XLAND > 1.5)   U_PHY(:,1,:) = 0.0\n     where(XLAND > 1.5)   V_PHY(:,1,:) = 0.0\n     where(XLAND > 1.5) QV_CURR(:,1,:) = 0.0\n     where(XLAND > 1.5)     P8W(:,1,:) = 0.0\n     where(XLAND > 1.5)     GLW        = 0.0\n     where(XLAND > 1.5)  SWDOWN        = 0.0\n     where(XLAND > 1.5) RAINBL_tmp     = 0.0\n     where(XLAND > 1.5) SNOWBL         = 0.0\n\n     QV_CURR(:,1,:) = QV_CURR(:,1,:)/(1.0 - QV_CURR(:,1,:))  ! Assuming input forcing are specific hum.;\n                                                             ! WRF wants mixing ratio at driver level\n     P8W(:,2,:)     = P8W(:,1,:)      ! WRF uses lowest two layers\n     T_PHY(:,2,:)   = T_PHY(:,1,:)    ! Only pressure is needed in two layer but fill the rest\n     U_PHY(:,2,:)   = U_PHY(:,1,:)    !\n     V_PHY(:,2,:)   = V_PHY(:,1,:)    !\n     QV_CURR(:,2,:) = QV_CURR(:,1,:)  !\n     RAINBL = RAINBL_tmp * DTBL       ! RAINBL in WRF is [mm]\n     SNOWBL = SNOWBL * DTBL           !\n     SR         = 0.0                 ! Will only use component if opt_snf=4\n     RAINCV     = 0.0\n     RAINNCV    = RAINBL\n     RAINSHV    = 0.0\n     SNOWNCV    = SNOWBL\n     GRAUPELNCV = 0.0\n     HAILNCV    = 0.0\n     DZ8W = 2 * noah_lsm%ZLVL                    ! 2* to be consistent with WRF model level\n!------------------------------------------------------------------------\n! Noah-MP updates we can do before spatial loop.\n!------------------------------------------------------------------------\n\n   ! create a few fields that are IN in WRF - coszen, julian_in,yr\n   ! Previously calculating julian_in occured within calc_declin, which is called for all grid cells\n   ! but is only dependant on the current date which does not change over cells\n\n   CALL GETH_IDTS(OLDDATE(1:10), OLDDATE(1:4)//\"-01-01\", iday)\n   READ(OLDDATE(12:13), *) ihr\n   READ(OLDDATE(15:16), *) imin\n   READ(OLDDATE(18:19), *) isec\n   JULIAN_IN = real(iday) + real(ihr)/24.\n\n    DO J = YSTART,YEND\n    DO I = XSTART,XEND\n      CALL CALC_DECLIN(XLAT_URB2D(I,J), XLONIN(I,J), JULIAN_IN, ihr, imin, isec, COSZEN(I,J))\n    END DO\n    END DO\n\n    READ(OLDDATE(1:4),*)  YR\n    YEARLEN = 365                      ! find length of year for phenology (also S Hemisphere)\n    if (mod(YR,4) == 0) then\n       YEARLEN = 366\n       if (mod(YR,100) == 0) then\n          YEARLEN = 365\n          if (mod(YR,400) == 0) then\n             YEARLEN = 366\n          endif\n       endif\n    endif\n\n    IF (ITIME == 1 .AND. .NOT. RESTART_FLAG ) THEN\n      EAHXY = (P8W(:,1,:)*QV_CURR(:,1,:))/(0.622+QV_CURR(:,1,:)) ! Initial guess only.\n      TAHXY = T_PHY(:,1,:)                                       ! Initial guess only.\n      CHXY = 0.1\n      CMXY = 0.1\n    ENDIF\n\n!------------------------------------------------------------------------\n! Skip model call at t=1 since initial conditions are at start time; First model time is +1\n!------------------------------------------------------------------------\n\n   IF (ITIME > 0) THEN\n\n!------------------------------------------------------------------------\n! Call to Noah-MP driver same as surface_driver\n!------------------------------------------------------------------------\n     sflx_count_sum = 0 ! Timing\n\n   ! Timing information for SFLX:\n\n    call system_clock(count=count_before_sflx, count_rate=clock_rate)\n\n         CALL noahmplsm(ITIMESTEP,       YR, JULIAN_IN,   COSZEN, XLAT_URB2D, &\n\t           DZ8W,     DTBL,      DZS,     NUM_SOIL_LAYERS,         DX, &\n\t\t IVGTYP,   ISLTYP,   VEGFRA,   GVFMAX,       TMN,             &\n\t\t  XLAND,     XICE,     XICE_THRESHOLD,                        &\n                  IDVEG, IOPT_CRS, IOPT_BTR, IOPT_RUN,  IOPT_SFC,   IOPT_FRZ, &\n\t       IOPT_INF, IOPT_RAD, IOPT_ALB, IOPT_SNF, IOPT_TBOT,   IOPT_STC, &\n\t       IOPT_GLA, IOPT_RSF,IOPT_SOIL,IOPT_PEDO, IOPT_CROP,             &\n               IOPT_IMPERV, IZ0TLND,                                          &\n\t\t  T_PHY,  QV_CURR,    U_PHY,    V_PHY,    SWDOWN,        GLW, &\n\t\t    P8W,   RAINBL,       SR,                                  &\n\t\t    TSK,      HFX,      QFX,       LH,    GRDFLX,     SMSTAV, &\n\t\t SMSTOT,SFCRUNOFF, UDRUNOFF,   ALBEDO,     SNOWC,      SMOIS, &\n\t\t   SH2O,     TSLB,     state%SNOW,    state%SNOWH,    CANWAT,     ACSNOM, &\n\t\t ACSNOW,    EMISS,     QSFC,                                  &\n \t\t     Z0,      ZNT,                                            & ! IN/OUT LSM eqv\n\t\tISNOWXY,     TVXY,     TGXY, CANICEXY,  CANLIQXY,      EAHXY, &\n\t\t  TAHXY,     CMXY,     CHXY,   FWETXY,  SNEQVOXY,   ALBOLDXY, &\n\t\tQSNOWXY, QRAINXY, WSLAKEXY,  ZWTXY,  WAXY,   WTXY,    state%TSNOXY, &\n\t\tstate%ZSNSOXY,  state%SNICEXY,  state%SNLIQXY, LFMASSXY,  RTMASSXY,   STMASSXY, &\n\t\t WOODXY, STBLCPXY, FASTCPXY,      LAI,    XSAIXY,    TAUSSXY, &\n\t        SMOISEQ, SMCWTDXY,DEEPRECHXY,  RECHXY,                        & ! IN/OUT Noah MP only\n\t         T2MVXY,   T2MBXY,   Q2MVXY,   Q2MBXY,                        &\n                 TRADXY,    NEEXY,    GPPXY,    NPPXY,    FVEGXY,    RUNSFXY, &\n\t        RUNSBXY,   ECANXY,   EDIRXY,  ETRANXY,     FSAXY,     FIRAXY, &\n                 APARXY,    PSNXY,    SAVXY,    SAGXY,   RSSUNXY,    RSSHAXY, &\n               ALBSNDXY, ALBSNIXY,                                            & ! OUT Noah MP only\n                 BGAPXY,   WGAPXY,    TGVXY,    TGBXY,     CHVXY,      CHBXY, &\n\t\t  SHGXY,    SHCXY,    SHBXY,    EVGXY,     EVBXY,      GHVXY, &\n\t\t  GHBXY,    IRGXY,    IRCXY,    IRBXY,      TRXY,      EVCXY, &\n\t       CHLEAFXY,   CHUCXY,   CHV2XY,   CHB2XY,                        &\n             PSNOWLIQXY,   PSNOWTEMPXY,      PSNOWDZXY,  PSNOWHEATXY,         &\n             PSNOWRHOXY,    PSNOWSWEXY,   PSNOWGRAN1XY, PSNOWGRAN2XY,         &\n            PSNOWHISTXY,    PSNOWALBXY,     PSNOWAGEXY,      act_lev,         &\n          PSNOWHEIGHTXY, PSNOWTOTSWEXY, PSNOWTHRUFALXY,     GLACINFO,         &\n                  GLACT,      FLOW_ICE,      FLOW_SNOW,   crocus_opt,         &\n#ifdef SPATIAL_SOIL\n                 BEXP_3D,SMCDRY_3D,SMCWLT_3D,SMCREF_3D,SMCMAX_3D,             &\n\t\t DKSAT_3D,DWSAT_3D,PSISAT_3D,QUARTZ_3D,                       &\n\t\t REFDK_2D,REFKDT_2D,SLOPE_2D,                                 &\n\t\t CWPVT_2D,VCMX25_2D,MP_2D,HVT_2D,MFSNO_2D,RSURFEXP_2D,        &\n                 AXAJ_2D,BXAJ_2D,XXAJ_2D,                                     &\n                 IMPERV_2D,                                                   &\n                 SSI_2D,SNOWRETFAC_2D,TAU0_2D,RSURFSNOW_2D,SCAMAX_2D,         &\n#endif\n#ifdef WRF_HYDRO\n                 sfcheadrt,INFXSRT,soldrain,                          &    !O\n#endif\n                ids,ide, jds,jde, kds,kde,                      &\n                ims,ime, jms,jme, kms,kme,                      &\n                its,ite, jts,jte, kts,kte,        &\n! variables below are optional\n                MP_RAINC =  RAINCV, MP_RAINNC =    RAINNCV, MP_SHCV = RAINSHV,&\n    MP_SNOW  = SNOWNCV, MP_GRAUP  = GRAUPELNCV, MP_HAIL = HAILNCV, &\n    VIS_ICEALB=VIS_ICEALB &\n#ifdef WRF_HYDRO\n                , ACCPRCP=ACCPRCP,  ACCECAN=ACCECAN, ACCETRAN=ACCETRAN,  ACCEDIR=ACCEDIR  &\n                , SOILSAT_TOP=SOILSAT_TOP, SOILSAT=SOILSAT, SOILICE=SOILICE, SNOWT_AVG=SNOWT_AVG      &\n#endif\n                )\n\n\n          call system_clock(count=count_after_sflx, count_rate=clock_rate)\n          sflx_count_sum = sflx_count_sum + ( count_after_sflx - count_before_sflx )\n\n  IF(noah_lsm%RUNOFF_OPTION.EQ.5.AND.MOD(ITIME,STEPWTD).EQ.0)THEN\n           CALL wrf_message('calling WTABLE' )\n\n!gmm update wtable from lateral flow and shed water to rivers\n           CALL WTABLE_MMF_NOAHMP(                                        &\n\t       NUM_SOIL_LAYERS,  XLAND, XICE,       XICE_THRESHOLD, ISICE,    &\n               ISLTYP,      SMOISEQ,    DZS,        WTDDT,                &\n               FDEPTHXY,    AREAXY,     TERRAIN,    ISURBAN,    IVGTYP,   &\n               RIVERCONDXY, RIVERBEDXY, EQZWT,      PEXPXY,               &\n               SMOIS,       SH2O,       SMCWTDXY,   ZWTXY,                &\n\t       QRFXY,       DEEPRECHXY, QSPRINGXY,                        &\n               QSLATXY,     QRFSXY,     QSPRINGSXY, RECHXY,               &\n               IDS,IDE, JDS,JDE, KDS,KDE,                                 &\n               IMS,IME, JMS,JME, KMS,KME,                                 &\n               ITS,ITE, JTS,JTE, KTS,KTE )\n\n ENDIF\n\n!------------------------------------------------------------------------\n! END of surface_driver consistent code\n!------------------------------------------------------------------------\n\n ENDIF   ! SKIP FIRST TIMESTEP\n\n#ifdef WRF_HYDRO\n     call geth_newdate(newdate, olddate, nint(dtbl))\n     olddate = newdate\n     call hrldas_drv_HYDRO(TSLB(:,1:NSOIL,:),SMOIS(:,1:NSOIL,:),SH2O(:,1:NSOIL,:),infxsrt,sfcheadrt,soldrain,ix,jx,NSOIL)\n#endif\n\n! Output for history\n     OUTPUT_FOR_HISTORY: if (noah_lsm%output_timestep > 0) then\n        if (mod(ITIME * noah_lsm%noah_timestep, noah_lsm%output_timestep) == 0) then\n\n           ! convert RAINRATE back to mm/s for output\n           RAINBL = RAINBL_tmp\n           call ldas_output(ITIME,state)\n\n\n        endif\n     endif OUTPUT_FOR_HISTORY\n\n     if (IVGTYP(xstart,ystart)==ISWATER) then\n       write(*,'(\" ***DATE=\", A19)', advance=\"NO\") olddate\n     else\n       write(*,'(\" ***DATE=\", A19, 6F10.5)', advance=\"NO\") olddate, TSLB(xstart,1,ystart), LAI(xstart,ystart)\n     endif\n\n!------------------------------------------------------------------------\n! Write Restart - timestamp equal to output will have same states\n!------------------------------------------------------------------------\n\n      if ( (noah_lsm%restart_frequency_hours .gt. 0) .and. &\n           (mod(ITIME, int(noah_lsm%restart_frequency_hours*3600./nint(dtbl))) == 0)) then\n       if(noah_lsm%rst_bi_out .eq. 0) then\n           call lsm_restart(state)\n       else\n           call lsm_rst_bi_out(state)\n       endif\n#ifdef WRF_HYDRO\n      else\n       if (noah_lsm%restart_frequency_hours <= 0) then\n          if ( (olddate( 9:10) == \"01\") .and. (olddate(12:13) == \"00\") .and. &\n               (olddate(15:16) == \"00\") .and. (olddate(18:19) == \"00\") ) then\n               if(noah_lsm%rst_bi_out .eq. 0) then\n                   call lsm_restart(state)  ! jlm - i moved all the restart code to a subroutine.\n               else\n                   call lsm_rst_bi_out(state)\n               endif\n          endif\n       endif\n#endif\n      endif\n\n!------------------------------------------------------------------------\n! Advance the time\n!------------------------------------------------------------------------\n#ifndef WRF_HYDRO\n     call geth_newdate(newdate, olddate, nint(dtbl))\n     olddate = newdate\n#endif\n\n! update the timer\n     call system_clock(count=clock_count_2, count_rate=clock_rate)\n     timing_sum = timing_sum + float(clock_count_2-clock_count_1)/float(clock_rate)\n     write(*,'(\"    Timing: \",f6.2,\" Cumulative:  \", f10.2, \"  SFLX: \", f6.2 )') &\n          float(clock_count_2-clock_count_1)/float(clock_rate), &\n          timing_sum, real(sflx_count_sum) / real(clock_rate)\n     clock_count_1 = clock_count_2\n\n\n      ITIMESTEP = ITIMESTEP + 1\n\nend subroutine land_driver_exe\n\n!!===============================================================================\nsubroutine  ldas_output(itime, state)\n  use state_module, only: state_type\n\n  type(state_type) :: state\n  integer, intent(in)  :: itime ! time step of the LSM\n\n!#ifdef WRF_HYDRO\n!if ( (io_config_outputs .eq. 0) ) then\n!#endif\n!#ifndef WRF_HYDRO\n!           call prepare_output_file (trim(outdir), version, &\n!                igrid, output_timestep, llanduse, split_output_count, hgrid,                &\n!                ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar,                         &\n!                iswater, mapproj, lat1, lon1, dx, dy, truelat1, truelat2, cen_lon,          &\n!                nsoil, nsnow, dzs, startdate, olddate, IVGTYP, ISLTYP)\n!\n!           DEFINE_MODE_LOOP : do imode = 1, 2\n!\n!              call set_output_define_mode(imode)\n!\n!              ! For 3D arrays, we need to know whether the Z dimension is snow layers, or soil layers.\n!\n!        ! Properties - Assigned or predicted\n!              call add_to_output(IVGTYP     , \"IVGTYP\"  , \"Dominant vegetation category\"         , \"category\"              )\n!              call add_to_output(ISLTYP     , \"ISLTYP\"  , \"Dominant soil category\"               , \"category\"              )\n!              call add_to_output(FVEGXY     , \"FVEG\"    , \"Green Vegetation Fraction\"              , \"-\"                   )\n!              call add_to_output(LAI        , \"LAI\"     , \"Leaf area index\"                      , \"-\"                     )\n!              call add_to_output(XSAIXY     , \"SAI\"     , \"Stem area index\"                      , \"-\"                     )\n!        ! Forcing\n!              call add_to_output(SWDOWN     , \"SWFORC\"  , \"Shortwave forcing\"                    , \"W m{-2}\"               )\n!              call add_to_output(COSZEN     , \"COSZ\"    , \"Cosine of zenith angle\"                    , \"W m{-2}\"               )\n!              call add_to_output(GLW        , \"LWFORC\"  , \"Longwave forcing\"                    , \"W m{-2}\"               )\n!              call add_to_output(RAINBL     , \"RAINRATE\", \"Precipitation rate\"                   , \"kg m{-2} s{-1}\"        )\n!        ! Grid energy budget terms\n!              call add_to_output(EMISS      , \"EMISS\"   , \"Grid emissivity\"                    , \"\"               )\n!              call add_to_output(FSAXY      , \"FSA\"     , \"Total absorbed SW radiation\"          , \"W m{-2}\"               )\n!              call add_to_output(FIRAXY     , \"FIRA\"    , \"Total net LW radiation to atmosphere\" , \"W m{-2}\"               )\n!              call add_to_output(GRDFLX     , \"GRDFLX\"  , \"Heat flux into the soil\"              , \"W m{-2}\"               )\n!              call add_to_output(HFX        , \"HFX\"     , \"Total sensible heat to atmosphere\"    , \"W m{-2}\"               )\n!              call add_to_output(LH         , \"LH\"      , \"Total latent heat to atmosphere\"    , \"W m{-2}\"               )\n!              call add_to_output(ECANXY     , \"ECAN\"    , \"Canopy water evaporation rate\"        , \"kg m{-2} s{-1}\"        )\n!              call add_to_output(EDIRXY     , \"EDIR\"    , \"Direct from soil evaporation rate\"    , \"kg m{-2} s{-1}\"        )\n!              call add_to_output(ALBEDO     , \"ALBEDO\"  , \"Surface albedo\"                         , \"-\"                   )\n!              call add_to_output(ETRANXY    , \"ETRAN\"   , \"Transpiration rate\"                   , \"kg m{-2} s{-1}\"        )\n!        ! Grid water budget terms - in addition to above\n!              call add_to_output(UDRUNOFF   , \"UGDRNOFF\", \"Accumulated underground runoff\"       , \"mm\"                    )\n!              call add_to_output(SFCRUNOFF  , \"SFCRNOFF\", \"Accumulatetd surface runoff\"          , \"mm\"                    )\n!              call add_to_output(CANLIQXY   , \"CANLIQ\"  , \"Canopy liquid water content\"          , \"mm\"                    )\n!              call add_to_output(CANICEXY   , \"CANICE\"  , \"Canopy ice water content\"             , \"mm\"                    )\n!              call add_to_output(ZWTXY      , \"ZWT\"     , \"Depth to water table\"                 , \"m\"                     )\n!              call add_to_output(WAXY       , \"WA\"      , \"Water in aquifer\"                     , \"kg m{-2}\"              )\n!              call add_to_output(WTXY       , \"WT\"      , \"Water in aquifer and saturated soil\"  , \"kg m{-2}\"              )\n!        ! Additional needed to close the canopy energy budget\n!              call add_to_output(SAVXY      , \"SAV\"     , \"Solar radiative heat flux absorbed by vegetation\", \"W m{-2}\"    )\n!              call add_to_output(TRXY       , \"TR\"      , \"Transpiration heat\"                     , \"W m{-2}\"             )\n!              call add_to_output(EVCXY      , \"EVC\"     , \"Canopy evap heat\"                       , \"W m{-2}\"             )\n!              call add_to_output(IRCXY      , \"IRC\"     , \"Canopy net LW rad\"                      , \"W m{-2}\"             )\n!              call add_to_output(SHCXY      , \"SHC\"     , \"Canopy sensible heat\"                   , \"W m{-2}\"             )\n!        ! Additional needed to close the under canopy ground energy budget\n!              call add_to_output(IRGXY      , \"IRG\"     , \"Ground net LW rad\"                      , \"W m{-2}\"             )\n!              call add_to_output(SHGXY      , \"SHG\"     , \"Ground sensible heat\"                   , \"W m{-2}\"             )\n!              call add_to_output(EVGXY      , \"EVG\"     , \"Ground evap heat\"                       , \"W m{-2}\"             )\n!              call add_to_output(GHVXY      , \"GHV\"     , \"Ground heat flux + to soil vegetated\"   , \"W m{-2}\"             )\n!        ! Needed to close the bare ground energy budget\n!              call add_to_output(SAGXY      , \"SAG\"     , \"Solar radiative heat flux absorbed by ground\", \"W m{-2}\"        )\n!              call add_to_output(IRBXY      , \"IRB\"     , \"Net LW rad to atm bare\"                 , \"W m{-2}\"             )\n!              call add_to_output(SHBXY      , \"SHB\"     , \"Sensible heat to atm bare\"              , \"W m{-2}\"             )\n!              call add_to_output(EVBXY      , \"EVB\"     , \"Evaporation heat to atm bare\"           , \"W m{-2}\"             )\n!              call add_to_output(GHBXY      , \"GHB\"     , \"Ground heat flux + to soil bare\"        , \"W m{-2}\"             )\n!        ! Above-soil temperatures\n!              call add_to_output(TRADXY     , \"TRAD\"    , \"Surface radiative temperature\"        , \"K\"                     )\n!              call add_to_output(TGXY       , \"TG\"      , \"Ground temperature\"                   , \"K\"                     )\n!              call add_to_output(TVXY       , \"TV\"      , \"Vegetation temperature\"               , \"K\"                     )\n!              call add_to_output(TAHXY      , \"TAH\"     , \"Canopy air temperature\"               , \"K\"                     )\n!              call add_to_output(TGVXY      , \"TGV\"     , \"Ground surface Temp vegetated\"          , \"K\"                   )\n!              call add_to_output(TGBXY      , \"TGB\"     , \"Ground surface Temp bare\"               , \"K\"                   )\n!              call add_to_output(T2MVXY     , \"T2MV\"    , \"2m Air Temp vegetated\"                  , \"K\"                   )\n!              call add_to_output(T2MBXY     , \"T2MB\"    , \"2m Air Temp bare\"                       , \"K\"                   )\n!        ! Above-soil moisture\n!              call add_to_output(Q2MVXY     , \"Q2MV\"    , \"2m mixing ratio vegetated\"              , \"kg/kg\"               )\n!              call add_to_output(Q2MBXY     , \"Q2MB\"    , \"2m mixing ratio bare\"                   , \"kg/kg\"               )\n!              call add_to_output(EAHXY      , \"EAH\"     , \"Canopy air vapor pressure\"            , \"Pa\"                    )\n!              call add_to_output(FWETXY     , \"FWET\"    , \"Wetted or snowed fraction of canopy\"  , \"fraction\"              )\n!        ! Snow and soil - 3D terms\n!              call add_to_output(ZSNSOXY(:,-nsnow+1:0,:),  \"ZSNSO_SN\" , \"Snow layer depths from snow surface\", \"m\", \"SNOW\")\n!              call add_to_output(SNICEXY    , \"SNICE\"   , \"Snow layer ice\"                       , \"mm\"             , \"SNOW\")\n!              call add_to_output(SNLIQXY    , \"SNLIQ\"   , \"Snow layer liquid water\"              , \"mm\"             , \"SNOW\")\n!              call add_to_output(TSLB       , \"SOIL_T\"  , \"soil temperature\"                     , \"K\"              , \"SOIL\")\n!              call add_to_output(SH2O       , \"SOIL_W\"  , \"liquid volumetric soil moisture\"      , \"m3 m-3\"         , \"SOIL\")\n!              call add_to_output(TSNOXY     , \"SNOW_T\"  , \"snow temperature\"                     , \"K\"              , \"SNOW\")\n!              call add_to_output(SMOIS      , \"SOIL_M\"  , \"volumetric soil moisture\"             , \"m{3} m{-3}\"     , \"SOIL\")\n!        ! Snow - 2D terms\n!              call add_to_output(SNOWH      , \"SNOWH\"   , \"Snow depth\"                           , \"m\"                     )\n!              call add_to_output(SNOW       , \"SNEQV\"   , \"Snow water equivalent\"                , \"kg m{-2}\"              )\n!              call add_to_output(QSNOWXY    , \"QSNOW\"   , \"Snowfall rate\"                        , \"mm s{-1}\"              )\n!              call add_to_output(ISNOWXY    , \"ISNOW\"   , \"Number of snow layers\"                , \"count\"                 )\n!              call add_to_output(SNOWC      , \"FSNO\"    , \"Snow-cover fraction on the ground\"      , \"\"                    )\n!              call add_to_output(ACSNOW     , \"ACSNOW\"  , \"accumulated snow fall\"                  , \"mm\"                  )\n!              call add_to_output(ACSNOM     , \"ACSNOM\"  , \"accumulated melting water out of snow bottom\" , \"mm\"            )\n!        ! Exchange coefficients\n!              call add_to_output(CMXY       , \"CM\"      , \"Momentum drag coefficient\"            , \"\"                      )\n!              call add_to_output(CHXY       , \"CH\"      , \"Sensible heat exchange coefficient\"   , \"\"                      )\n!              call add_to_output(CHVXY      , \"CHV\"     , \"Exchange coefficient vegetated\"         , \"m s{-1}\"             )\n!              call add_to_output(CHBXY      , \"CHB\"     , \"Exchange coefficient bare\"              , \"m s{-1}\"             )\n!              call add_to_output(CHLEAFXY   , \"CHLEAF\"  , \"Exchange coefficient leaf\"              , \"m s{-1}\"             )\n!              call add_to_output(CHUCXY     , \"CHUC\"    , \"Exchange coefficient bare\"              , \"m s{-1}\"             )\n!              call add_to_output(CHV2XY     , \"CHV2\"    , \"Exchange coefficient 2-meter vegetated\" , \"m s{-1}\"             )\n!              call add_to_output(CHB2XY     , \"CHB2\"    , \"Exchange coefficient 2-meter bare\"      , \"m s{-1}\"             )\n!        ! Carbon allocation model\n!              call add_to_output(LFMASSXY   , \"LFMASS\"  , \"Leaf mass\"                            , \"g m{-2}\"               )\n!              call add_to_output(RTMASSXY   , \"RTMASS\"  , \"Mass of fine roots\"                   , \"g m{-2}\"               )\n!              call add_to_output(STMASSXY   , \"STMASS\"  , \"Stem mass\"                            , \"g m{-2}\"               )\n!              call add_to_output(WOODXY     , \"WOOD\"    , \"Mass of wood and woody roots\"         , \"g m{-2}\"               )\n!              call add_to_output(STBLCPXY   , \"STBLCP\"  , \"Stable carbon in deep soil\"           , \"g m{-2}\"               )\n!              call add_to_output(FASTCPXY   , \"FASTCP\"  , \"Short-lived carbon in shallow soil\"   , \"g m{-2}\"               )\n!              call add_to_output(NEEXY      , \"NEE\"     , \"Net ecosystem exchange\"                 , \"g m{-2} s{-1} CO2\"   )\n!              call add_to_output(GPPXY      , \"GPP\"     , \"Net instantaneous assimilation\"         , \"g m{-2} s{-1} C\"     )\n!              call add_to_output(NPPXY      , \"NPP\"     , \"Net primary productivity\"               , \"g m{-2} s{-1} C\"     )\n!              call add_to_output(PSNXY      , \"PSN\"     , \"Total photosynthesis\"                   , \"umol CO@ m{-2} s{-1}\")\n!              call add_to_output(APARXY     , \"APAR\"    , \"Photosynthesis active energy by canopy\" , \"W m{-2}\"             )\n!\n!        ! Carbon allocation model\n!\t    IF(RUNOFF_OPTION == 5) THEN\n!              call add_to_output(SMCWTDXY   , \"SMCWTD\"   , \"Leaf mass\"                            , \"g m{-2}\"               )\n!              call add_to_output(RECHXY     , \"RECH\"     , \"Mass of fine roots\"                   , \"g m{-2}\"               )\n!              call add_to_output(QRFSXY     , \"QRFS\"     , \"Stem mass\"                            , \"g m{-2}\"               )\n!              call add_to_output(QSPRINGSXY , \"QSPRINGS\" , \"Mass of wood and woody roots\"         , \"g m{-2}\"               )\n!              call add_to_output(QSLATXY    , \"QSLAT\"    , \"Stable carbon in deep soil\"           , \"g m{-2}\"               )\n!\t    ENDIF\n!\n!           enddo DEFINE_MODE_LOOP\n!\n!           call finalize_output_file(split_output_count)\n!#ifdef WRF_HYDRO\n!else\n!#endif\n!#endif /* WRF_HYDRO */\n\n#ifdef WRF_HYDRO\n   ! Logan add begin\n   ! Go through each variable. For the first time the NWM output routine is\n   ! called, the file is created and all output variables (desired per flags),\n   ! are created in define mode.\n\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,ITIME,startdate,olddate,ixpar,jxpar,1,float(IVGTYP),IVGTYP,1)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,float(ISLTYP),IVGTYP,2)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,FVEGXY,IVGTYP,3)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,LAI,IVGTYP,4)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,XSAIXY,IVGTYP,5)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,SWDOWN,IVGTYP,6)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,COSZEN,IVGTYP,7)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,GLW,IVGTYP,8)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,RAINBL,IVGTYP,9)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,EMISS,IVGTYP,10)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,FSAXY,IVGTYP,11)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,FIRAXY,IVGTYP,12)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,GRDFLX,IVGTYP,13)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,HFX,IVGTYP,14)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,LH,IVGTYP,15)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ECANXY,IVGTYP,16)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,EDIRXY,IVGTYP,17)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ALBEDO,IVGTYP,18)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ETRANXY,IVGTYP,19)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,UDRUNOFF,IVGTYP,20)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,SFCRUNOFF,IVGTYP,21)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CANLIQXY,IVGTYP,22)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CANICEXY,IVGTYP,23)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ZWTXY,IVGTYP,24)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,WAXY,IVGTYP,25)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,WTXY,IVGTYP,26)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ACCPRCP,IVGTYP,27)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ACCECAN,IVGTYP,28)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ACCEDIR,IVGTYP,29)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ACCETRAN,IVGTYP,30)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,SAVXY,IVGTYP,31)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,TRXY,IVGTYP,32)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,EVCXY,IVGTYP,33)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,IRCXY,IVGTYP,34)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,SHCXY,IVGTYP,35)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,IRGXY,IVGTYP,36)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,SHGXY,IVGTYP,37)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,EVGXY,IVGTYP,38)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,GHVXY,IVGTYP,39)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,SAGXY,IVGTYP,40)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,IRBXY,IVGTYP,41)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,SHBXY,IVGTYP,42)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,EVBXY,IVGTYP,43)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,GHBXY,IVGTYP,44)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,TRADXY,IVGTYP,45)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,TGXY,IVGTYP,46)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,TVXY,IVGTYP,47)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,TAHXY,IVGTYP,48)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,TGVXY,IVGTYP,49)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,TGBXY,IVGTYP,50)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,T2MVXY,IVGTYP,51)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,T2MBXY,IVGTYP,52)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,Q2MVXY,IVGTYP,53)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,Q2MBXY,IVGTYP,54)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,EAHXY,IVGTYP,55)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,FWETXY,IVGTYP,56)\n   !call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,float(ZSNOXY(:,-nsnow+1:0,:)),IVGTYP,57)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,3,state%SNICEXY,IVGTYP,58)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,3,state%SNLIQXY,IVGTYP,59)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,4,TSLB,IVGTYP,60)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,4,SH2O,IVGTYP,61)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,3,state%TSNOXY,IVGTYP,62)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,4,SMOIS,IVGTYP,63)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,state%SNOWH,IVGTYP,64)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,state%SNOW,IVGTYP,65)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,QSNOWXY,IVGTYP,66)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,float(ISNOWXY),IVGTYP,67)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,SNOWC,IVGTYP,68)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ACSNOW,IVGTYP,69)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,ACSNOM,IVGTYP,70)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CMXY,IVGTYP,71)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CHXY,IVGTYP,72)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CHVXY,IVGTYP,73)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CHBXY,IVGTYP,74)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CHLEAFXY,IVGTYP,75)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CHUCXY,IVGTYP,76)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CHV2XY,IVGTYP,77)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CHB2XY,IVGTYP,78)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,LFMASSXY,IVGTYP,79)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,RTMASSXY,IVGTYP,80)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,STMASSXY,IVGTYP,81)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,WOODXY,IVGTYP,82)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,STBLCPXY,IVGTYP,83)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,FASTCPXY,IVGTYP,84)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,NEEXY,IVGTYP,85)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,GPPXY,IVGTYP,86)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,NPPXY,IVGTYP,87)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,PSNXY,IVGTYP,88)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,APARXY,IVGTYP,89)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,(ACCECAN+ACCEDIR+ACCETRAN),IVGTYP,90)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,CANWAT,IVGTYP,91)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,(SOILICE),IVGTYP,92)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,(SOILSAT_TOP),IVGTYP,93)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,(SOILSAT),IVGTYP,94)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,(SNOWT_AVG),IVGTYP,95)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,2,ALBSNDXY,IVGTYP,96)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,2,ALBSNIXY,IVGTYP,97)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,QRAINXY,IVGTYP,98)\n   if (crocus_opt /= 0) then\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,float(GLACINFO),IVGTYP,99)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,(GLACT),IVGTYP,100)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,PSNOWALBXY,IVGTYP,101)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,PSNOWTHRUFALXY,IVGTYP,102)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,PSNOWHEIGHTXY,IVGTYP,103)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,PSNOWTOTSWEXY,IVGTYP,104)\n\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWGRAN1XY,IVGTYP,105)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWGRAN2XY,IVGTYP,106)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWAGEXY,IVGTYP,107)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWTEMPXY,IVGTYP,108)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWDZXY,IVGTYP,109)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWHISTXY,IVGTYP,110)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,(PSNOWLIQXY),IVGTYP,111)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWHEATXY,IVGTYP,112)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWRHOXY ,IVGTYP,113)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,noah_lsm%act_lev,PSNOWSWEXY,IVGTYP,114)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,FLOW_ICE,IVGTYP,115)\n   call output_NoahMP_NWM(trim(noah_lsm%outdir),igrid,noah_lsm%output_timestep,itime,startdate,olddate,ixpar,jxpar,1,FLOW_SNOW,IVGTYP,116)\n   end if ! crocus_opt /= 0\n#endif /* WRF_HYDRO */\n\n!#ifdef WRF_HYDRO\n!endif\n!#endif\n\nend subroutine  ldas_output\n\n!!===============================================================================\nsubroutine lsm_restart(state)\n  use state_module, only: state_type\n  implicit none\n  type(state_type) :: state\n  character(len=256):: tmpStr\n  integer :: ncid\n\n#ifdef HYDRO_D\n  print*, 'Write restart at '//olddate(1:13)\n#endif\n\n  call prepare_restart_file (trim(noah_lsm%outdir), version,   igrid,     llanduse,  &\n                             olddate,               startdate, ixfull,    jxfull,    &\n                             ixpar,                 jxpar,     xstartpar, ystartpar, &\n                             nsoil,                 nsnow,     dx,        dy,        &\n                             truelat1,              truelat2,  mapproj,   lat1,      &\n                             lon1,                  cen_lon,   iswater,   ivgtyp,    &\n                             glacinfo,              glact,     act_lev,   VIS_ICEALB)\n\n\n   write(tmpStr, '(A,\"/RESTART.\",A10,\"_DOMAIN\",I1)') trim(noah_lsm%outdir), olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13), igrid\n\n\n#ifdef MPP_LAND\n  if(my_id .eq. io_id) then\n#endif\n     ierr = nf90_open(trim(tmpStr),  NF90_WRITE, ncid)\n     call define_rst_variables(ncid,state)\n#ifdef MPP_LAND\n  endif\n#endif\n\n  call add_to_restart(ncid,TSLB      , \"SOIL_T\", layers=\"SOIL\")\n  call add_to_restart(ncid,state%TSNOXY    , \"SNOW_T\", layers=\"SNOW\")\n  call add_to_restart(ncid,SMOIS     , \"SMC\"   , layers=\"SOIL\")\n  call add_to_restart(ncid,SH2O      , \"SH2O\"  , layers=\"SOIL\")\n  call add_to_restart(ncid,state%ZSNSOXY   , \"ZSNSO\" , layers=\"SOSN\")\n  call add_to_restart(ncid,state%SNICEXY   , \"SNICE\" , layers=\"SNOW\")\n  call add_to_restart(ncid,state%SNLIQXY   , \"SNLIQ\" , layers=\"SNOW\")\n  call add_to_restart(ncid,QSNOWXY   , \"QSNOW\" )\n  call add_to_restart(ncid,FWETXY    , \"FWET\"  )\n  call add_to_restart(ncid,SNEQVOXY  , \"SNEQVO\")\n  call add_to_restart(ncid,EAHXY     , \"EAH\"   )\n  call add_to_restart(ncid,TAHXY     , \"TAH\"   )\n  call add_to_restart(ncid,ALBOLDXY  , \"ALBOLD\")\n  call add_to_restart(ncid,CMXY      , \"CM\"    )\n  call add_to_restart(ncid,CHXY      , \"CH\"    )\n  call add_to_restart(ncid,ISNOWXY   , \"ISNOW\" )\n  call add_to_restart(ncid,CANLIQXY  , \"CANLIQ\")\n  call add_to_restart(ncid,CANICEXY  , \"CANICE\")\n  call add_to_restart(ncid,state%SNOW      , \"SNEQV\" )\n  call add_to_restart(ncid,state%SNOWH     , \"SNOWH\" )\n  call add_to_restart(ncid,TVXY      , \"TV\"    )\n  call add_to_restart(ncid,TGXY      , \"TG\"    )\n  call add_to_restart(ncid,ZWTXY     , \"ZWT\"   )\n  call add_to_restart(ncid,WAXY      , \"WA\"    )\n  call add_to_restart(ncid,WTXY      , \"WT\"    )\n  call add_to_restart(ncid,WSLAKEXY  , \"WSLAKE\")\n  call add_to_restart(ncid,LFMASSXY  , \"LFMASS\")\n  call add_to_restart(ncid,RTMASSXY  , \"RTMASS\")\n  call add_to_restart(ncid,STMASSXY  , \"STMASS\")\n  call add_to_restart(ncid,WOODXY    , \"WOOD\"  )\n  call add_to_restart(ncid,STBLCPXY  , \"STBLCP\")\n  call add_to_restart(ncid,FASTCPXY  , \"FASTCP\")\n  call add_to_restart(ncid,LAI       , \"LAI\"   )\n  call add_to_restart(ncid,XSAIXY    , \"SAI\"   )\n  call add_to_restart(ncid,VEGFRA    , \"VEGFRA\")\n  call add_to_restart(ncid,GVFMIN    , \"GVFMIN\")\n  call add_to_restart(ncid,GVFMAX    , \"GVFMAX\")\n  call add_to_restart(ncid,ACSNOM    , \"ACMELT\")\n  call add_to_restart(ncid,ACSNOW    , \"ACSNOW\")\n  call add_to_restart(ncid,TAUSSXY   , \"TAUSS\" )\n  call add_to_restart(ncid,QSFC      , \"QSFC\"  )\n  call add_to_restart(ncid,SFCRUNOFF , \"SFCRUNOFF\")\n  call add_to_restart(ncid,UDRUNOFF  , \"UDRUNOFF\" )\n  if (crocus_opt /= 0) then\n     call add_to_restart(ncid, PSNOWAGEXY    , \"PSNOWAGE\"  , LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWDZXY     , \"PSNOWDZ\"   , LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWGRAN1XY  , \"PSNOWGRAN1\", LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWGRAN2XY  , \"PSNOWGRAN2\", LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWHEATXY   , \"PSNOWHEAT\" , LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWHISTXY   , \"PSNOWHIST\" , LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWLIQXY    , \"PSNOWLIQ\"  , LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWRHOXY    , \"PSNOWRHO\"  , LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWSWEXY    , \"PSNOWSWE\"  , LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWTEMPXY   , \"PSNOWTEMP\" , LAYERS=\"MAXS\")\n     call add_to_restart(ncid, PSNOWALBXY    , \"PSNOWALB\"    )\n     call add_to_restart(ncid, PSNOWHEIGHTXY , \"PSNOWHEIGHT\" )\n     call add_to_restart(ncid, PSNOWTHRUFALXY, \"PSNOWTHRUFAL\")\n     call add_to_restart(ncid, PSNOWTOTSWEXY , \"PSNOWTOTSWE\" )\n     call add_to_restart(ncid, FLOW_ICE      , \"FLOW_ICE\"    )\n     call add_to_restart(ncid, FLOW_SNOW     , \"FLOW_SNOW\"   )\n  end if ! crocus_opt /= 0\n#ifdef WRF_HYDRO\n  call add_to_restart(ncid,ACCPRCP   , \"ACCPRCP\" )\n  call add_to_restart(ncid,ACCECAN   , \"ACCECAN\" )\n  call add_to_restart(ncid,ACCEDIR   , \"ACCEDIR\" )\n  call add_to_restart(ncid,ACCETRAN  , \"ACCETRAN\" )\n#endif\n! below for opt_run = 5\n  call add_to_restart(ncid,SMOISEQ   , \"SMOISEQ\"  , layers=\"SOIL\"  )\n  call add_to_restart(ncid,AREAXY    , \"AREAXY\"     )\n  call add_to_restart(ncid,SMCWTDXY  , \"SMCWTDXY\"   )\n  call add_to_restart(ncid,DEEPRECHXY, \"DEEPRECHXY\" )\n  call add_to_restart(ncid,QSLATXY   , \"QSLATXY\"    )\n  call add_to_restart(ncid,QRFSXY    , \"QRFSXY\"     )\n  call add_to_restart(ncid,QSPRINGSXY, \"QSPRINGSXY\" )\n  call add_to_restart(ncid,RECHXY    , \"RECHXY\"     )\n  call add_to_restart(ncid,QRFXY     , \"QRFXY\"      )\n  call add_to_restart(ncid,QSPRINGXY , \"QSPRINGXY\"  )\n  call add_to_restart(ncid,FDEPTHXY , \"FDEPTHXY\"  )\n  call add_to_restart(ncid,RIVERCONDXY , \"RIVERCONDXY\"  )\n  call add_to_restart(ncid,RIVERBEDXY , \"RIVERBEDXY\"  )\n  call add_to_restart(ncid,EQZWT , \"EQZWT\"  )\n  call add_to_restart(ncid,PEXPXY , \"PEXPXY\"  )\n\n#ifdef MPP_LAND\n  if(my_id .eq. io_id) then\n     ierr = nf90_close(ncid)\n  endif\n#endif\n\n  call finalize_restart_file()\n\nend subroutine lsm_restart\n\nsubroutine lsm_rst_bi_out(state)\n  use state_module, only: state_type\n  implicit none\n  type(state_type) :: state\n  integer :: iunit, ierr\n  character(len=256) :: output_flnm, str_tmp\n  integer  :: i0,ie, i, istep, mkdirStatus\n\n\n#ifdef MPP_LAND\n  call mpp_land_sync()\n\n\n i0 = 0\n istep = 64\n ie = istep\n do i = 0, numprocs,istep\n   if(my_id .ge. i0 .and. my_id .lt. ie) then\n#endif\n\n  write(output_flnm, '(A,\"/RESTART.\",A10,\"_DOMAIN\",I1)') trim(noah_lsm%outdir), olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13),igrid\n  iunit =56\n\n#ifdef MPP_LAND\n             if(my_id .lt. 10) then\n                  write(str_tmp,'(I1)') my_id\n             else if(my_id .lt. 100) then\n                  write(str_tmp,'(I2)') my_id\n             else if(my_id .lt. 1000) then\n                  write(str_tmp,'(I3)') my_id\n             else if(my_id .lt. 10000) then\n                  write(str_tmp,'(I4)') my_id\n             else if(my_id .lt. 100000) then\n                  write(str_tmp,'(I5)') my_id\n             else\n                continue\n             endif\n  open(iunit,file=\"restart/\"//trim(output_flnm)//\".\"//trim(str_tmp),form=\"unformatted\",ERR=102, access=\"sequential\")\n#else\n  open(iunit,file=\"restart/\"//trim(output_flnm),form=\"unformatted\",ERR=102, access=\"sequential\")\n#endif\n\n  write(iunit,ERR=101) TSLB\n  write(iunit,ERR=101) state%TSNOXY\n  write(iunit,ERR=101) SMOIS\n  write(iunit,ERR=101) SH2O\n  write(iunit,ERR=101) state%ZSNSOXY\n  write(iunit,ERR=101) state%SNICEXY\n  write(iunit,ERR=101) state%SNLIQXY\n  write(iunit,ERR=101) QSNOWXY\n  write(iunit,ERR=101) FWETXY\n  write(iunit,ERR=101) SNEQVOXY\n  write(iunit,ERR=101) EAHXY\n  write(iunit,ERR=101) TAHXY\n  write(iunit,ERR=101) ALBOLDXY\n  write(iunit,ERR=101) CMXY\n  write(iunit,ERR=101) CHXY\n  write(iunit,ERR=101) ISNOWXY\n  write(iunit,ERR=101) CANLIQXY\n  write(iunit,ERR=101) CANICEXY\n  write(iunit,ERR=101) state%SNOW\n  write(iunit,ERR=101) state%SNOWH\n  write(iunit,ERR=101) TVXY\n  write(iunit,ERR=101) TGXY\n  write(iunit,ERR=101) ZWTXY\n  write(iunit,ERR=101) WAXY\n  write(iunit,ERR=101) WTXY\n  write(iunit,ERR=101) WSLAKEXY\n  write(iunit,ERR=101) LFMASSXY\n  write(iunit,ERR=101) RTMASSXY\n  write(iunit,ERR=101) STMASSXY\n  write(iunit,ERR=101) WOODXY\n  write(iunit,ERR=101) STBLCPXY\n  write(iunit,ERR=101) FASTCPXY\n  write(iunit,ERR=101) LAI\n  write(iunit,ERR=101) XSAIXY\n  write(iunit,ERR=101) VEGFRA\n  write(iunit,ERR=101) GVFMIN\n  write(iunit,ERR=101) GVFMAX\n  write(iunit,ERR=101) ACSNOM\n  write(iunit,ERR=101) ACSNOW\n  write(iunit,ERR=101) TAUSSXY\n  write(iunit,ERR=101) QSFC\n  write(iunit,ERR=101) SFCRUNOFF\n  write(iunit,ERR=101) UDRUNOFF\n  if (crocus_opt /= 0) then\n     write(iunit,ERR=101) PSNOWAGEXY\n     write(iunit,ERR=101) PSNOWDZXY\n     write(iunit,ERR=101) PSNOWGRAN1XY\n     write(iunit,ERR=101) PSNOWGRAN2XY\n     write(iunit,ERR=101) PSNOWHEATXY\n     write(iunit,ERR=101) PSNOWHISTXY\n     write(iunit,ERR=101) PSNOWLIQXY\n     write(iunit,ERR=101) PSNOWRHOXY\n     write(iunit,ERR=101) PSNOWSWEXY\n     write(iunit,ERR=101) PSNOWTEMPXY\n     write(iunit,ERR=101) PSNOWALBXY\n     write(iunit,ERR=101) PSNOWHEIGHTXY\n     write(iunit,ERR=101) PSNOWTHRUFALXY\n     write(iunit,ERR=101) PSNOWTOTSWEXY\n     write(iunit,ERR=101) FLOW_SNOW\n     write(iunit,ERR=101) FLOW_ICE\n  end if ! crocus_opt /= 0\n! #ifndef REALTIME\n! #ifdef WRF_HYDRO\n!   write(iunit,ERR=101) ACCPRCP\n!   write(iunit,ERR=101) ACCECAN\n!   write(iunit,ERR=101) ACCEDIR\n!   write(iunit,ERR=101) ACCETRAN\n! #endif\n! #endif\n! ! below for opt_run = 5\n!   if(IOPT_RUN .eq. 5) then\n!      write(iunit,ERR=101) SMOISEQ\n!      write(iunit,ERR=101) AREAXY\n!      write(iunit,ERR=101) SMCWTDXY\n!      write(iunit,ERR=101) DEEPRECHXY\n!      write(iunit,ERR=101) QSLATXY\n!      write(iunit,ERR=101) QRFSXY\n!      write(iunit,ERR=101) QSPRINGSXY\n!      write(iunit,ERR=101) RECHXY\n!      write(iunit,ERR=101) QRFXY\n!      write(iunit,ERR=101) QSPRINGXY\n!      write(iunit,ERR=101) FDEPTHXY\n!      write(iunit,ERR=101) RIVERCONDXY\n!      write(iunit,ERR=101) RIVERBEDXY\n!      write(iunit,ERR=101) EQZWT\n!      write(iunit,ERR=101) PEXPXY\n!   endif\n\n  close(iunit)\n\n#ifdef MPP_LAND\n    endif\n    call mpp_land_sync()\n    i0 = i0 + istep\n    ie = ie + istep\n  end do ! end do of i loop\n#endif\n\n  return\n101  continue\n#ifdef MPP_LAND\n  call fatal_error_stop(\"FATAL ERROR: failed to write lsm restartfile\")\n#else\n  stop \"failed to write lsm restart file\"\n#endif\n102  continue\n#ifdef MPP_LAND\n  call fatal_error_stop(\"FATAL ERROR: failed to open lsm restartfile\")\n#else\n  stop \"FATAL ERROR: failed to open restart file\"\n#endif\nend subroutine lsm_rst_bi_out\n\nsubroutine lsm_rst_bi_in(state)\n  use state_module, only: state_type\n  implicit none\n  type(state_type) :: state\n  integer :: iunit, ierr\n  character(len=256):: str_tmp\n  integer  :: i0,ie, i, istep\n\n  iunit = 56\n#ifdef MPP_LAND\n i0 = 0\n istep = 64\n ie = istep\n do i = 0, numprocs,istep\n   if(my_id .ge. i0 .and. my_id .lt. ie) then\n\n             if(my_id .lt. 10) then\n                  write(str_tmp,'(I1)') my_id\n             else if(my_id .lt. 100) then\n                  write(str_tmp,'(I2)') my_id\n             else if(my_id .lt. 1000) then\n                  write(str_tmp,'(I3)') my_id\n             else if(my_id .lt. 10000) then\n                  write(str_tmp,'(I4)') my_id\n             else if(my_id .lt. 100000) then\n                  write(str_tmp,'(I5)') my_id\n             else\n                continue\n             endif\n  open(iunit,file=trim(noah_lsm%restart_filename_requested)//\".\"//trim(str_tmp),form=\"unformatted\",ERR=101, access=\"sequential\")\n#else\n  open(iunit,file=trim(noah_lsm%restart_filename_requested),form=\"unformatted\",ERR=101, access=\"sequential\")\n#endif\n\n\n  read(iunit,ERR=101) TSLB\n  read(iunit,ERR=101) state%TSNOXY\n  read(iunit,ERR=101) SMOIS\n  read(iunit,ERR=101) SH2O\n  read(iunit,ERR=101) state%ZSNSOXY\n  read(iunit,ERR=101) state%SNICEXY\n  read(iunit,ERR=101) state%SNLIQXY\n  read(iunit,ERR=101) QSNOWXY\n  read(iunit,ERR=101) FWETXY\n  read(iunit,ERR=101) SNEQVOXY\n  read(iunit,ERR=101) EAHXY\n  read(iunit,ERR=101) TAHXY\n  read(iunit,ERR=101) ALBOLDXY\n  read(iunit,ERR=101) CMXY\n  read(iunit,ERR=101) CHXY\n  read(iunit,ERR=101) ISNOWXY\n  read(iunit,ERR=101) CANLIQXY\n  read(iunit,ERR=101) CANICEXY\n  read(iunit,ERR=101) state%SNOW\n  read(iunit,ERR=101) state%SNOWH\n  read(iunit,ERR=101) TVXY\n  read(iunit,ERR=101) TGXY\n  read(iunit,ERR=101) ZWTXY\n  read(iunit,ERR=101) WAXY\n  read(iunit,ERR=101) WTXY\n  read(iunit,ERR=101) WSLAKEXY\n  read(iunit,ERR=101) LFMASSXY\n  read(iunit,ERR=101) RTMASSXY\n  read(iunit,ERR=101) STMASSXY\n  read(iunit,ERR=101) WOODXY\n  read(iunit,ERR=101) STBLCPXY\n  read(iunit,ERR=101) FASTCPXY\n  read(iunit,ERR=101) LAI\n  read(iunit,ERR=101) XSAIXY\n  read(iunit,ERR=101) VEGFRA\n  read(iunit,ERR=101) GVFMIN\n  read(iunit,ERR=101) GVFMAX\n  read(iunit,ERR=101) ACSNOM\n  read(iunit,ERR=101) ACSNOW\n  read(iunit,ERR=101) TAUSSXY\n  read(iunit,ERR=101) QSFC\n  read(iunit,ERR=101) SFCRUNOFF\n  read(iunit,ERR=101) UDRUNOFF\n  if (crocus_opt /= 0) then\n     read(iunit,ERR=101) PSNOWAGEXY\n     read(iunit,ERR=101) PSNOWDZXY\n     read(iunit,ERR=101) PSNOWGRAN1XY\n     read(iunit,ERR=101) PSNOWGRAN2XY\n     read(iunit,ERR=101) PSNOWHEATXY\n     read(iunit,ERR=101) PSNOWHISTXY\n     read(iunit,ERR=101) PSNOWLIQXY\n     read(iunit,ERR=101) PSNOWRHOXY\n     read(iunit,ERR=101) PSNOWSWEXY\n     read(iunit,ERR=101) PSNOWTEMPXY\n     read(iunit,ERR=101) PSNOWALBXY\n     read(iunit,ERR=101) PSNOWHEIGHTXY\n     read(iunit,ERR=101) PSNOWTHRUFALXY\n     read(iunit,ERR=101) PSNOWTOTSWEXY\n     read(iunit,ERR=101) FLOW_SNOW\n     read(iunit,ERR=101) FLOW_ICE\n  end if ! crocus_opt /= 0\n\n  ! read(iunit,ERR=101) PSNOWLIQXY\n! #ifndef REALTIME\n! #ifdef WRF_HYDRO\n!   read(iunit,ERR=101) ACCPRCP\n!   read(iunit,ERR=101) ACCECAN\n!   read(iunit,ERR=101) ACCEDIR\n!   read(iunit,ERR=101) ACCETRAN\n! #endif\n! #endif\n! ! below for opt_run = 5\n!   if(IOPT_RUN .eq. 5) then\n!       read(iunit,ERR=101) SMOISEQ\n!       read(iunit,ERR=101) AREAXY\n!       read(iunit,ERR=101) SMCWTDXY\n!       read(iunit,ERR=101) DEEPRECHXY\n!       read(iunit,ERR=101) QSLATXY\n!       read(iunit,ERR=101) QRFSXY\n!       read(iunit,ERR=101) QSPRINGSXY\n!       read(iunit,ERR=101) RECHXY\n!       read(iunit,ERR=101) QRFXY\n!       read(iunit,ERR=101) QSPRINGXY\n!       read(iunit,ERR=101) FDEPTHXY\n!       read(iunit,ERR=101) RIVERCONDXY\n!       read(iunit,ERR=101) RIVERBEDXY\n!       read(iunit,ERR=101) EQZWT\n!       read(iunit,ERR=101) PEXPXY\n!   endif\n  close(iunit)\n\n#ifdef MPP_LAND\n    endif\n    call mpp_land_sync()\n    i0 = i0 + istep\n    ie = ie + istep\n  end do ! end do of i loop\n#endif\n\n  return\n\n101  continue\n#ifdef MPP_LAND\n  call fatal_error_stop(\"FATAL ERROR: failed to read in lsm restartfile \"   &\n          //trim(noah_lsm%restart_filename_requested)//\".\"//trim(str_tmp))\n#else\n  stop \"FATAL ERROR: failed to read lsm restart file\"\n#endif\nend subroutine lsm_rst_bi_in\n\n\nsubroutine define_rst_variables(ncid, state)\n  use state_module, only: state_type\n  implicit none\n  type(state_type) :: state\n  integer ncid\n  !      character(len=*) :: tmpStr\n\n  call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_float() - \"// &\n       \"Problem nf90_open\")\n  ierr = nf90_redef(ncid)\n  call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_float() - \"// &\n       \"Problem nf90_redef\")\n! add the variables\n\n  call define_rst_var(ncid,TSLB      , \"SOIL_T\", layers=\"SOIL\")\n  call define_rst_var(ncid,state%TSNOXY    , \"SNOW_T\", layers=\"SNOW\")\n  call define_rst_var(ncid,SMOIS     , \"SMC\"   , layers=\"SOIL\")\n  call define_rst_var(ncid,SH2O      , \"SH2O\"  , layers=\"SOIL\")\n  call define_rst_var(ncid,state%ZSNSOXY   , \"ZSNSO\" , layers=\"SOSN\")\n  call define_rst_var(ncid,state%SNICEXY   , \"SNICE\" , layers=\"SNOW\")\n  call define_rst_var(ncid,state%SNLIQXY   , \"SNLIQ\" , layers=\"SNOW\")\n  call define_rst_var(ncid,QSNOWXY   , \"QSNOW\" )\n  call define_rst_var(ncid,FWETXY    , \"FWET\"  )\n  call define_rst_var(ncid,SNEQVOXY  , \"SNEQVO\")\n  call define_rst_var(ncid,EAHXY     , \"EAH\"   )\n  call define_rst_var(ncid,TAHXY     , \"TAH\"   )\n  call define_rst_var(ncid,ALBOLDXY  , \"ALBOLD\")\n  call define_rst_var(ncid,CMXY      , \"CM\"    )\n  call define_rst_var(ncid,CHXY      , \"CH\"    )\n  call define_rst_var(ncid,ISNOWXY   , \"ISNOW\" )\n  call define_rst_var(ncid,CANLIQXY  , \"CANLIQ\")\n  call define_rst_var(ncid,CANICEXY  , \"CANICE\")\n  call define_rst_var(ncid,state%SNOW      , \"SNEQV\" )\n  call define_rst_var(ncid,state%SNOWH     , \"SNOWH\" )\n  call define_rst_var(ncid,TVXY      , \"TV\"    )\n  call define_rst_var(ncid,TGXY      , \"TG\"    )\n  call define_rst_var(ncid,ZWTXY     , \"ZWT\"   )\n  call define_rst_var(ncid,WAXY      , \"WA\"    )\n  call define_rst_var(ncid,WTXY      , \"WT\"    )\n  call define_rst_var(ncid,WSLAKEXY  , \"WSLAKE\")\n  call define_rst_var(ncid,LFMASSXY  , \"LFMASS\")\n  call define_rst_var(ncid,RTMASSXY  , \"RTMASS\")\n  call define_rst_var(ncid,STMASSXY  , \"STMASS\")\n  call define_rst_var(ncid,WOODXY    , \"WOOD\"  )\n  call define_rst_var(ncid,STBLCPXY  , \"STBLCP\")\n  call define_rst_var(ncid,FASTCPXY  , \"FASTCP\")\n  call define_rst_var(ncid,LAI       , \"LAI\"   )\n  call define_rst_var(ncid,XSAIXY    , \"SAI\"   )\n  call define_rst_var(ncid,VEGFRA    , \"VEGFRA\")\n  call define_rst_var(ncid,GVFMIN    , \"GVFMIN\")\n  call define_rst_var(ncid,GVFMAX    , \"GVFMAX\")\n  call define_rst_var(ncid,ACSNOM    , \"ACMELT\")\n  call define_rst_var(ncid,ACSNOW    , \"ACSNOW\")\n  call define_rst_var(ncid,TAUSSXY   , \"TAUSS\" )\n  call define_rst_var(ncid,QSFC      , \"QSFC\"  )\n  call define_rst_var(ncid,SFCRUNOFF , \"SFCRUNOFF\")\n  call define_rst_var(ncid,UDRUNOFF  , \"UDRUNOFF\" )\n  if (crocus_opt /= 0) then\n     call define_rst_var(ncid,PSNOWAGEXY    , \"PSNOWAGE\"  , layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWDZXY     , \"PSNOWDZ\"   , layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWGRAN1XY  , \"PSNOWGRAN1\", layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWGRAN2XY  , \"PSNOWGRAN2\", layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWHEATXY   , \"PSNOWHEAT\" , layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWHISTXY   , \"PSNOWHIST\" , layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWLIQXY    , \"PSNOWLIQ\"  , layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWRHOXY    , \"PSNOWRHO\"  , layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWSWEXY    , \"PSNOWSWE\"  , layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWTEMPXY   , \"PSNOWTEMP\" , layers=\"MAXS\")\n     call define_rst_var(ncid,PSNOWALBXY    , \"PSNOWALB\"    )\n     call define_rst_var(ncid,PSNOWHEIGHTXY , \"PSNOWHEIGHT\" )\n     call define_rst_var(ncid,PSNOWTHRUFALXY, \"PSNOWTHRUFAL\")\n     call define_rst_var(ncid,PSNOWTOTSWEXY , \"PSNOWTOTSWE\" )\n     call define_rst_var(ncid,FLOW_SNOW     , \"FLOW_SNOW\"   )\n     call define_rst_var(ncid,FLOW_ICE      , \"FLOW_ICE\"    )\n  end if ! crocus_opt /= 0\n#ifdef WRF_HYDRO\n  call define_rst_var(ncid,ACCPRCP   , \"ACCPRCP\" )\n  call define_rst_var(ncid,ACCECAN   , \"ACCECAN\" )\n  call define_rst_var(ncid,ACCEDIR   , \"ACCEDIR\" )\n  call define_rst_var(ncid,ACCETRAN  , \"ACCETRAN\" )\n#endif\n! below for opt_run = 5\n  call define_rst_var(ncid,SMOISEQ   , \"SMOISEQ\"  , layers=\"SOIL\"  )\n  call define_rst_var(ncid,AREAXY    , \"AREAXY\"     )\n  call define_rst_var(ncid,SMCWTDXY  , \"SMCWTDXY\"   )\n  call define_rst_var(ncid,DEEPRECHXY, \"DEEPRECHXY\" )\n  call define_rst_var(ncid,QSLATXY   , \"QSLATXY\"    )\n  call define_rst_var(ncid,QRFSXY    , \"QRFSXY\"     )\n  call define_rst_var(ncid,QSPRINGSXY, \"QSPRINGSXY\" )\n  call define_rst_var(ncid,RECHXY    , \"RECHXY\"     )\n  call define_rst_var(ncid,QRFXY     , \"QRFXY\"      )\n  call define_rst_var(ncid,QSPRINGXY , \"QSPRINGXY\"  )\n  call define_rst_var(ncid,FDEPTHXY , \"FDEPTHXY\"  )\n  call define_rst_var(ncid,RIVERCONDXY , \"RIVERCONDXY\"  )\n  call define_rst_var(ncid,RIVERBEDXY , \"RIVERBEDXY\"  )\n  call define_rst_var(ncid,EQZWT , \"EQZWT\"  )\n  call define_rst_var(ncid,PEXPXY , \"PEXPXY\"  )\n      ierr = nf90_enddef(ncid)\n      call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_float() - \"// &\n                             \"Problem nf90_enddef\")\n      call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_3d() - \"// &\n                             \"Problem nf90_close\")\n\n   end subroutine define_rst_variables\n\nend module module_NoahMP_hrldas_driver\n\n!subroutine wrf_message(msg)\n!  implicit none\n!  character(len=*), intent(in) :: msg\n!  print*, msg\n!end subroutine wrf_message\n\nlogical function wrf_dm_on_monitor() result(l)\n  l = .TRUE.\n  return\nend function wrf_dm_on_monitor\n\n\n!------------------------------------------------------------------------------------\n!------------------------------------------------------------------------------------\n\nSUBROUTINE CALC_DECLIN (LATITUDE, LONGITUDE, JULIAN, IHOUR, IMINUTE, ISECOND, COSZ)\n\n!---------------------------------------------------------------------\n   IMPLICIT NONE\n!---------------------------------------------------------------------\n\n   REAL, PARAMETER :: DEGRAD = 3.14159265/180.\n   REAL, PARAMETER :: DPD    = 360./365.\n! !ARGUMENTS:\n   REAL,              INTENT(IN)  :: LATITUDE\n   REAL,              INTENT(IN)  :: LONGITUDE\n   REAL,              INTENT(IN)  :: JULIAN      ! Calculated outside of the loop\n   INTEGER,           INTENT(IN)  :: IHOUR       ! used in local time calc\n   INTEGER,           INTENT(IN)  :: IMINUTE     ! used in local time calc\n   INTEGER,           INTENT(IN)  :: ISECOND     ! used in local time calc\n   REAL,              INTENT(OUT) :: COSZ        ! unchanged, but moved to end of subroutine call\n\n   REAL                           :: HRANG\n   REAL                           :: DECLIN\n   REAL                           :: OBECL\n   REAL                           :: SINOB\n   REAL                           :: SXLONG\n   REAL                           :: ARG\n   REAL                           :: TLOCTIM\n\n!\n! FOR SHORT WAVE RADIATION\n\n   DECLIN=0.\n\n!-----OBECL : OBLIQUITY = 23.5 DEGREE.\n\n   OBECL=23.5*DEGRAD\n   SINOB=SIN(OBECL)\n\n!-----CALCULATE LONGITUDE OF THE SUN FROM VERNAL EQUINOX:\n\n   IF(JULIAN.GE.80.)SXLONG=DPD*(JULIAN-80.)*DEGRAD\n   IF(JULIAN.LT.80.)SXLONG=DPD*(JULIAN+285.)*DEGRAD\n   ARG=SINOB*SIN(SXLONG)\n   DECLIN=ASIN(ARG)\n\n   TLOCTIM = REAL(IHOUR) + REAL(IMINUTE)/60.0 + REAL(ISECOND)/3600.0 + LONGITUDE/15.0 ! LOCAL TIME IN HOURS\n   TLOCTIM = AMOD(TLOCTIM+24.0, 24.0)\n   HRANG=15.*(TLOCTIM-12.)*DEGRAD\n   COSZ=SIN(LATITUDE*DEGRAD)*SIN(DECLIN)+COS(LATITUDE*DEGRAD)*COS(DECLIN)*COS(HRANG)\n\n END SUBROUTINE CALC_DECLIN\n\n!\n!------------------------------------------------------------------------------------------\n"
  },
  {
    "path": "src/Land_models/NoahMP/IO_code/module_hrldas_netcdf_io.F",
    "content": "module module_hrldas_netcdf_io\n  use module_date_utilities\n  use netcdf\n  use module_hydro_stop, only:HYDRO_stop\n  use, intrinsic :: ieee_arithmetic, only: IEEE_Value, IEEE_QUIET_NAN\n\n#ifdef MPP_LAND\n  use module_mpp_land, only:mpp_land_bcast_int1, decompose_data_real, mpp_land_bcast_real1, decompose_data_int, &\n                  io_id, global_nx, global_ny, my_id, write_io_real, write_io_int, write_io_real3d,decompose_data_real3d, &\n                   mpp_land_sync,mpp_land_bcast_char,mpp_land_bcast\n#endif\n\n#ifdef _PARALLEL_\n  use mpi\n#endif\n  implicit none\n\n  logical, parameter :: FATAL = .TRUE.\n  logical, parameter :: NOT_FATAL = .FALSE.\n\n  type inputstruct\n     character(len=19)             :: read_date\n     real, pointer, dimension(:,:) :: t\n     real, pointer, dimension(:,:) :: q\n     real, pointer, dimension(:,:) :: u\n     real, pointer, dimension(:,:) :: v\n     real, pointer, dimension(:,:) :: p\n     real, pointer, dimension(:,:) :: lw\n     real, pointer, dimension(:,:) :: sw\n     real, pointer, dimension(:,:) :: pcp\n     real, pointer, dimension(:,:) :: snow\n     real, pointer, dimension(:,:) :: vegfra\n     real, pointer, dimension(:,:) :: lai\n  end type inputstruct\n\n  character(len=256), private :: restart_filename_remember\n  integer, private :: iswater_remember\n  integer, private :: xstartpar_remember\n  integer, private, allocatable, dimension(:,:) :: vegtyp_remember\n  integer, private :: ncid_remember\n  integer, private :: output_count_remember = 0\n  logical, private :: define_mode_remember\n  integer, private :: dimid_ix_remember\n  integer, private :: dimid_jx_remember\n  integer, private :: dimid_times_remember\n  integer, private :: dimid_layers_remember\n  integer, private :: dimid_snow_layers_remember\n  integer, private :: dimid_glacier_layers_remember\n  integer, private :: crocus_opt = 0\n\n  interface define_rst_var\n     module procedure define_3d_real,define_2d_real,define_2d_int\n  end interface\n\n  interface prepare_output_file\n#ifdef MPP_LAND\n     module procedure prepare_output_file_mpp\n#else\n     module procedure prepare_output_file_seq\n#endif\n  end interface\n\n  interface prepare_restart_file\n#ifdef MPP_LAND\n     module procedure prepare_restart_file_mpp\n#else\n     module procedure prepare_restart_file_seq\n#endif\n  end interface\n\n\n  interface add_to_restart\n#ifdef MPP_LAND\n     module procedure add_to_restart_2d_float_mpp, add_to_restart_2d_integer_mpp, add_to_restart_3d_mpp\n#else\n     module procedure add_to_restart_2d_float, add_to_restart_2d_integer, add_to_restart_3d\n#endif\n  end interface\n\n  interface get_from_restart\n#ifdef MPP_LAND\n     module procedure get_from_restart_2d_float_mpp, get_from_restart_2d_integer_mpp, get_from_restart_3d_mpp, &\n              get_from_restart_att\n#else\n     module procedure get_from_restart_2d_float, get_from_restart_2d_integer, get_from_restart_3d, get_from_restart_att\n#endif\n  end interface\n\n  interface add_to_output\n#ifdef MPP_LAND\n     module procedure add_to_output_2d_float_mpp, add_to_output_2d_integer_mpp, add_to_output_3d_mpp\n#else\n     module procedure add_to_output_2d_float, add_to_output_2d_integer, add_to_output_3d\n#endif\n  end interface\n\ncontains\n\n!-------------------------------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------------------------------\n\n!!! check the existing of the variable from restart file\n  integer function checkRstV(name)\n       implicit none\n       character(len=*) name\n       integer :: ncid, ierr, varid\n#ifdef MPP_LAND\n     if(my_id .eq. io_id) then\n#endif\n       checkRstV = nf90_open(trim(restart_filename_remember), NF90_NOWRITE, ncid)\n       if(checkRstV .eq. 0) then\n           checkRstV = nf90_inq_varid(ncid, name, varid)\n       endif\n#ifdef MPP_LAND\n     endif\n       call mpp_land_bcast_int1(checkRstV)\n#endif\n  end function checkRstV\n\n\n!-------------------------------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------------------------------\n\n  subroutine get_2d_netcdf_soillevel(name, ncid, array, units, xstart, xend, ystart, yend, &\n       fatal_if_error, layer_bottom, layer_top, ierr)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    character(len=256), intent(out) :: units\n    ! FATAL_IF_ERROR:  an input code value:\n    !      .TRUE. if an error in reading the data should stop the program.\n    !      Otherwise the, IERR error flag is set, but the program continues.\n    logical, intent(in) :: fatal_if_error\n    integer, intent(out) :: ierr\n    real, intent(out) :: layer_bottom\n    real, intent(out) :: layer_top\n\n    integer :: iret, varid\n#ifdef MPP_LAND\n    real:: g_array(global_nx,global_ny)\n#endif\n\n    units = \" \"\n\n#ifdef MPP_LAND\n    if(my_id .eq. 0) then\n#endif\n\n    iret = nf90_inq_varid(ncid,  name,  varid)\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'name = \"', trim(name)//'\"'\n          stop \"FATAL ERROR: In get_2d_netcdf_soillevel() - error nf90_inq_varid\"\n       else\n          ierr = iret\n#ifdef MPP_LAND\n          goto 9992\n#endif\n          return\n       endif\n    endif\n\n    iret = nf90_get_att(ncid, varid, \"units\", units)\n    if (iret /= 0) units = \"units unknown\"\n\n#ifdef MPP_LAND\n    iret = nf90_get_var(ncid, varid, values=g_array, start=(/1,1/), count=(/global_nx,global_ny/))\n#else\n    iret = nf90_get_var(ncid, varid, values=array, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n#endif\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'name = \"', trim(name)//'\"'\n          print*, 'varid =', varid\n          print*, trim(nf90_strerror(iret))\n          stop \"FATAL ERROR: In get_2d_netcdf_soillevel() - error nf90_get_var\"\n       else\n          ierr = iret\n#ifdef MPP_LAND\n          goto 9992\n#endif\n          return\n       endif\n    endif\n\n    ! Also get some metadata about the soil layers:\n    iret = nf90_get_att(ncid, varid, \"layer_top\", layer_top)\n    call error_handler(iret, \"Attempted to find 'layer_top' attribute on variable \"//trim(name))\n\n    iret = nf90_get_att(ncid, varid, \"layer_bottom\", layer_bottom)\n    call error_handler(iret, \"Attempted to find 'layer_bottom' attribute on variable \"//trim(name))\n\n    ierr = 0;\n#ifdef MPP_LAND\n9992    continue\n    endif\n    call mpp_land_bcast_int1(ierr)\n    call mpp_land_bcast_char(256,units)\n    call mpp_land_bcast(layer_bottom)\n    call mpp_land_bcast(layer_top)\n    if(ierr /= 0) return\n    call decompose_data_real(g_array,array)\n#endif\n  end subroutine get_2d_netcdf_soillevel\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine check_outdir(rank, outdir)\n    implicit none\n\n    ! Check that output directory OUTDIR exists and is writable, by\n    ! trying to open a test file in that directory.  Include a random\n    ! number in the test file name, to greatly reduce the chance of\n    ! collision with existing file names.  This assumes that the\n    ! intrinsic random_seed routine, called without argument, will seed\n    ! the random number generator based on something like system time\n    ! or hardware noise.\n\n    integer,          intent(in) :: rank\n    character(len=*), intent(in) :: outdir\n\n    real                         :: xrand\n    character(len=256)           :: testfile\n    integer                      :: ierr\n\n    if (rank == 0) then\n       call random_seed()\n       call random_number(xrand)\n       write(testfile, '(A,\"/scratch.\",I4.4,\".\",I6.6,\".scratch\")') trim(outdir), rank, int(xrand*1.E6)\n       open(unit=30, file=trim(testfile), status='unknown', iostat=ierr)\n       if (ierr /= 0) then\n          write(*, '(/)')\n          write(*, '(\" ***** Namelist error: ******************************************************\")')\n          write(*, '(\" ***** \")')\n          write(*, '(\" ***** We cannot write a file to the directory specified in namelist option OUTDIR.\")')\n          write(*, '(\" ***** Check namelist option OUTDIR (currently set to ''\", A, \"'')\")') trim(outdir)\n          write(*, '(\" *****       Check that the directory exists, is a directory, and is writable.\")')\n          write(*, '(/)')\n          stop \"FATAL ERROR: In module_hrldas_netcdf_io.F check_outdir()\"// &\n               \" - Check namelist.hrldas option OUTDIR.\"\n       endif\n       close(unit=30, iostat=ierr, status='delete')\n       if (ierr /= 0) then\n          print*, \"TESTFILE = \" // trim(testfile) // '\"'\n          stop \"FATAL ERROR: In module_hrldas_netcdf_io.F check_outdir()\"// &\n               \" - Much confusion.  Problem closing test file.\"\n       endif\n    endif\n  end subroutine check_outdir\n\n!-------------------------------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------------------------------\n\n  subroutine find_restart_file(rank, restart_filename_requested, startdate, khour, olddate, restart_flnm)\n    implicit none\n    !\n    ! If the user has requested the latest restart file, find the latest restart file.\n    ! If the user has requested a specific restart file, check that the file exists.\n    !\n    ! Return the restart file name in string RESTART_FLNM.\n    ! Update the OLDDATE string (in case the latest restart file was requested).\n    !\n    integer,            intent(in)    :: rank\n    character(len=*),   intent(in)    :: restart_filename_requested\n    character(len=19),  intent(in)    :: startdate\n    integer,            intent(in)    :: khour\n    character(len=19),  intent(in)    :: olddate\n    character(len=256), intent(out)   :: restart_flnm\n    character(len=19)                 :: locdate\n    integer                           :: ribeg\n    integer                           :: riend\n    logical                           :: lexist\n\n#ifdef MPP_LAND\n     if(my_id .ne. IO_id) return\n#endif\n\n    ribeg = index(restart_filename_requested, \"<LATEST>\")-1\n\n    if ( ribeg > 0 ) then\n\n       riend = ribeg + 9\n       ! Find the latest RESTART file\n       call geth_newdate(locdate(1:13), olddate(1:13), khour+24)\n       RLOOP : do\n          restart_flnm = restart_filename_requested(1:ribeg) //                 &\n               locdate(1:4)//locdate(6:7)//locdate(9:10)//locdate(12:13) //     &\n               restart_filename_requested(riend:)\n          inquire (file=trim(restart_flnm), exist=lexist)\n          if ( .not. lexist ) then\n             call geth_newdate(locdate(1:13), locdate(1:13), -1)\n             if (locdate(1:13) < startdate(1:13) ) then\n                write(*, *)\n                write(*, '(\" ***** RESTART error: **************************************************\")')\n                write(*, '(\" ***** \")')\n                write(*, '(\" *****       You have requested to restart from the latest restart file,\")')\n                write(*, '(\" *****       but no restart file was found.\")')\n                write(*, '(\" ***** \")')\n                write(*, *)\n#ifdef MPP_LAND\n#ifdef WRF_HYDRO\n                call hydro_stop( \"FATAL ERROR: In module_hrldas_netcdf_io.F find_restart_file()\"// &\n                     \" - Cannot find a restart file.\")\n#endif\n#else\n                stop \"FATAL ERROR: In module_hrldas_netcdf_io.F find_restart_file()\"// &\n                     \" - Cannot find a restart file.\"\n#endif\n             endif\n          else\n             exit RLOOP\n          endif\n       enddo RLOOP\n\n    else\n\n      restart_flnm = restart_filename_requested\n      inquire (file=trim(restart_flnm), exist=lexist)\n      if ( .not. lexist ) then\n         inquire (file=trim(restart_flnm)//\".0\", exist=lexist)\n         if ( .not. lexist ) then\n           write(*, *)\n           write(*, '(\" ***** RESTART error: **************************************************\")')\n           write(*, '(\" ***** \")')\n           write(*, '(\" *****       You have requested to restart from a file that cannot be found.\")')\n           write(*, '(\" *****       Specified restart file = ''\", A, \"''\")') trim(restart_flnm)\n           write(*, '(\" ***** \")')\n           write(*, *)\n#ifdef MPP_LAND\n#ifdef WRF_HYDRO\n           call hydro_stop( \"FATAL ERROR: In module_hrldas_netcdf_io.F find_restart_file()\"// &\n               \" - Cannot find restart file.\")\n#endif\n#else\n           stop \"FATAL ERROR: In module_hrldas_netcdf_io.F find_restart_file()\"// &\n               \" - Cannot find restart file.\"\n#endif\n         endif\n      endif\n\n    endif\n\n    if (rank == 0) then\n#ifdef HYDRO_D\n       write(*, '(\"Found restart file:  ''\", A, \"''\")') trim(restart_flnm)\n#endif\n    endif\n\n  end subroutine find_restart_file\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine read_dim(wrfinput_flnm, ix, jx)\n       implicit none\n       character(len=*),   intent(in)    :: wrfinput_flnm\n       integer,            intent(out)   :: ix, jx    ! dimensions\n       integer  :: ncid, dimid, ierr\n       ierr = nf90_open(wrfinput_flnm, NF90_NOWRITE, ncid)\n\n       ierr = nf90_inq_dimid(ncid, \"west_east\", dimid)\n       call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding dimension 'west_east'\")\n\n       ierr = nf90_inquire_dimension(ncid, dimid, len=ix)\n       call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding dimension length for 'west_east'\")\n\n       ierr = nf90_inq_dimid(ncid, \"south_north\", dimid)\n       call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding dimension 'south_north'\")\n\n       ierr = nf90_inquire_dimension(ncid, dimid, len=jx)\n       call error_handler(ierr, failure=\"READ_HRLDAS_HDRINFO:  Problems finding dimension length for 'south_north'\")\n\n  end subroutine read_dim\n\n  subroutine read_hrldas_hdrinfo(wrfinput_flnm, ix, jx, &\n       xstart, xend, ystart, yend,                      &\n       iswater, islake, isurban, isice, llanduse, dx, dy, truelat1, truelat2, cen_lon, lat1, lon1, &\n#ifdef _PARALLEL_\n       igrid, mapproj, dum2d_ptr)\n#else\n       igrid, mapproj)\n#endif\n    ! Return the dimensions of the grid and some map information.\n    implicit none\n    character(len=*),   intent(in)    :: wrfinput_flnm\n    integer,            intent(out)   :: mapproj\n    integer,            intent(out)   :: igrid\n    integer,            intent(out)   :: ix, jx    ! dimensions\n    integer,            intent(in)    :: xstart, ystart ! Subwindow definition\n#ifdef MPP_LAND\n    integer,            intent(in) :: xend, yend     ! Subwindow definition\n#else\n    integer,            intent(inout) :: xend, yend     ! Subwindow definition\n#endif\n    integer,            intent(out)   :: iswater   ! vegetation category corresponding to water bodies\n    integer,            intent(out)   :: islake    ! vegetation category corresponding to lakes\n    integer,            intent(out)   :: isurban   ! vegetation category corresponding to urban areas\n    integer,            intent(out)   :: isice     ! vegetation category corresponding to ice areas\n    character(len=256), intent(out)   :: llanduse  ! Landuse dataset (USGS or MODI)\n    real,               intent(out)   :: dx\n    real,               intent(out)   :: dy\n    real,               intent(out)   :: truelat1\n    real,               intent(out)   :: truelat2\n    real,               intent(out)   :: cen_lon\n    real,               intent(out)   :: lat1\n    real,               intent(out)   :: lon1\n#ifdef _PARALLEL_\n    real, pointer,   dimension(:,:)   :: dum2d_ptr\n#endif\n    integer, volatile :: ncid, dimid, varid, ierr\n    real, allocatable, dimension(:,:), volatile :: dum2d\n    character(len=256) :: units\n    integer :: i\n    integer :: rank\n\n#ifdef _PARALLEL_\n    call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F \"// &\n                                  \"read_hrldas_hdrinfo() - MPI_Comm_rank\"\n#else\n    rank = 0\n#endif\n\n\n    ! Open the NetCDF file.\n    if (rank == 0) then\n#ifdef HYDRO_D\n        write(*,'(\"wrfinput_flnm: ''\", A, \"''\")') trim(wrfinput_flnm)\n#endif\n    endif\n\n!KWM#ifdef _PARALLEL_\n!KWM    ierr = nf90_open_par(wrfinput_flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n!KWM#else\n    ierr = nf90_open(wrfinput_flnm, NF90_NOWRITE, ncid)\n!KWM#endif\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo() - \"// &\n                       \"Problem opening wrfinput file: \"//trim(wrfinput_flnm))\n\n    ierr = nf90_inq_dimid(ncid, \"west_east\", dimid)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo() - \"// &\n                       \"Problems finding dimension 'west_east'\")\n\n    ierr = nf90_inquire_dimension(ncid, dimid, len=ix)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo() - \"// &\n                       \"Problems finding dimension length for 'west_east'\")\n\n    ierr = nf90_inq_dimid(ncid, \"south_north\", dimid)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo() - \"// &\n                       \"Problems finding dimension 'south_north'\")\n\n    ierr = nf90_inquire_dimension(ncid, dimid, len=jx)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding dimension length for 'south_north'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"DX\", dx)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'DX'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"DY\", dy)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'DY'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'TRUELAT1'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'TRUELAT2'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"STAND_LON\", cen_lon)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'STAND_LON'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", mapproj)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'MAP_PROJ'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"GRID_ID\", igrid)\n    if (ierr /= 0) then\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"grid_id\", igrid)\n       call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                          \"Problems finding global attribute 'GRID_ID' or 'grid_id'\")\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"ISWATER\", iswater)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'ISWATER'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"ISLAKE\", islake)\n    if(ierr /= 0) then\n      write(*,*) \"Problems finding global attribute: ISLAKE; setting to -1\"\n      islake = -1\n    end if\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"ISURBAN\", isurban)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'ISURBAN'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"ISICE\", isice)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'ISICE'\")\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MMINLU\", llanduse)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \"Problems finding global attribute 'MMINLU'\")\n\n    ! IBM XLF seems to need something like this:\n    do i = 1, 256\n       if (ichar(llanduse(i:i)) == 0) llanduse(i:i) = \" \"\n    enddo\n\n#ifndef MPP_LAND\n    if (xend == 0) then\n       xend = ix\n    endif\n    if (yend == 0) then\n       yend = jx\n    endif\n#endif\n\n!\n! This section is for reading the information from the wrfinput file\n!\n\n    ! We only need to read the one starting point.\n#ifdef MPP_LAND\n    allocate(dum2d(xstart:xend,ystart:yend))\n    call get_2d_netcdf(\"XLAT\", ncid, dum2d,  units, xstart, xend  , ystart, yend , FATAL, ierr)\n#else\n    allocate(dum2d(xstart:xstart,ystart:ystart))\n    call get_2d_netcdf(\"XLAT\", ncid, dum2d,  units, xstart, xstart, ystart, ystart, FATAL, ierr)\n#endif\n    lat1 = dum2d(xstart,ystart)\n\n#ifdef MPP_LAND\n    call get_2d_netcdf(\"XLONG\", ncid, dum2d,  units, xstart, xend  , ystart, yend  , FATAL, ierr)\n#else\n    call get_2d_netcdf(\"XLONG\", ncid, dum2d,  units, xstart, xstart, ystart, ystart, FATAL, ierr)\n#endif\n    lon1 = dum2d(xstart,ystart)\n    deallocate (dum2d)\n\n#ifdef MPP_LAND\n    call mpp_land_bcast_real1(lon1)\n    call mpp_land_bcast_real1(lat1)\n#endif\n\n#ifdef _PARALLEL_\n    allocate(dum2d_ptr(xstart:xend,ystart:yend))\n    call get_2d_netcdf(\"IVGTYP\", ncid, dum2d_ptr,  units, xstart, xend, ystart, yend, FATAL, ierr)\n#endif\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, failure=\"In read_hrldas_hdrinfo()- \"// &\n                       \" Problems closing NetCDF file.\")\n\n  end subroutine read_hrldas_hdrinfo\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine readland_hrldas(wrfinput_flnm,                            &\n       xstart, xend,                                                   &\n       ystart, yend,                                                   &\n       iswater, islake, vegtyp, soltyp, terrain, tbot_2d, latitude,    &\n       longitude, xland, seaice, msftx, msfty, &\n       local_crocus_opt, glacinfo, glact, vis_icealb)\n    implicit none\n    character(len=*),          intent(in)  :: wrfinput_flnm\n    integer,                   intent(in)  :: xstart, xend, ystart, yend\n    integer,                   intent(in)  :: iswater\n    integer,                   intent(in)  :: islake\n    integer, dimension(xstart:xend,ystart:yend), intent(out) :: vegtyp, soltyp\n    integer,                                     intent(in)  :: local_crocus_opt\n    integer, dimension(xstart:xend,ystart:yend), intent(out), optional :: glacinfo\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: terrain\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: tbot_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: latitude\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: longitude\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: xland\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: seaice\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: msftx\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: msfty\n    real,    dimension(:,:), intent(inout), allocatable :: glact\n    real,    dimension(:,:), intent(inout), allocatable :: vis_icealb\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n    real, dimension(xstart:xend,ystart:yend) :: xdum\n    integer :: rank\n\n    crocus_opt = local_crocus_opt ! setting module scope variable\n\n#ifdef _PARALLEL_\n    call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F readland_hrldas()\"// &\n                                  \" - MPI_Comm_rank\"\n#else\n    rank = 0\n#endif\n\n\n    ! Open the NetCDF file.\n    if (rank == 0) then\n#ifdef HYDRO_D\n       write(*,'(\"wrfinput_flnm: ''\", A, \"''\")') trim(wrfinput_flnm)\n#endif\n    endif\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(wrfinput_flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(wrfinput_flnm, NF90_NOWRITE, ncid)\n#endif\n    if (ierr /= 0) then\n       write(*,'(\"READLAND_HRLDAS:  Problem opening wrfinput file: ''\", A, \"''\")') trim(wrfinput_flnm)\n#ifdef _PARALLEL_\n       call MPI_Finalize(ierr)\n       if (ierr /= 0) write(*, '(\"Problem with MPI_Finalize.\")')\n#endif\n       stop \"FATAL ERROR: In module_hrldas_netcdf_io.F readland_hrldas()\"// &\n            \" - Problem opening wrfinput file.\"\n    endif\n\n    ! Get Latitude (lat)\n    call get_2d_netcdf(\"XLAT\", ncid, latitude,  units, xstart, xend, ystart, yend, FATAL, ierr)\n    ! print*, 'latitude(xstart,ystart) = ', latitude(xstart,ystart)\n\n    ! Get Longitude (lon)\n    call get_2d_netcdf(\"XLONG\", ncid, longitude, units, xstart, xend, ystart, yend, FATAL, ierr)\n    ! print*, 'longitude(xstart,ystart) = ', longitude(xstart,ystart)\n\n    ! Get land mask (xland)\n    call get_2d_netcdf(\"XLAND\", ncid, xland, units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n    ! print*, 'xland(xstart,ystart) = ', xland(xstart,ystart)\n\n    ! Get seaice (seaice)\n    call get_2d_netcdf(\"SEAICE\", ncid, seaice, units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n    ! print*, 'seaice(xstart,ystart) = ', seaice(xstart,ystart)\n\n    ! Get Terrain (avg)\n    call get_2d_netcdf(\"HGT\", ncid, terrain,   units, xstart, xend, ystart, yend, FATAL, ierr)\n    ! print*, 'terrain(xstart,ystart) = ', terrain(xstart,ystart)\n\n    ! Get Deep layer temperature (TMN)\n    call get_2d_netcdf(\"TMN\", ncid, tbot_2d,   units, xstart, xend, ystart, yend, FATAL, ierr)\n    ! print*, 'terrain(xstart,ystart) = ', terrain(xstart,ystart)\n\n    ! Get Map Factors (MAPFAC_MX)\n    call get_2d_netcdf(\"MAPFAC_MX\", ncid, msftx,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n    ! print*, 'msftx(xstart,ystart) = ', msftx(xstart,ystart)\n    if (ierr /= 0) print*, 'Did not find MAPFAC_MX, only needed for iopt_run=5'\n\n    ! Get Map Factors (MAPFAC_MY)\n    call get_2d_netcdf(\"MAPFAC_MY\", ncid, msfty,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n    ! print*, 'msfty(xstart,ystart) = ', msfty(xstart,ystart)\n    if (ierr /= 0) print*, 'Did not find MAPFAC_MY, only needed for iopt_run=5'\n\n    ! Get Dominant Land Use categories (use)\n    call get_landuse_or_glacinfo_netcdf(\"landuse\",ncid, xdum , units, xstart, xend, ystart, yend, FATAL, ierr)\n    vegtyp = nint(xdum)\n    ! print*, 'vegtyp(xstart,ystart) = ', vegtyp(xstart,ystart)\n\n    ! Get Glacier info (glacinfo)\n    ! - crocus_opt = 0 : don't read in\n    ! - crocus_opt = 1\n    !   - no glacier or glacier_thickness: ERROR\n    !   - glacier = 0: WARNING\n    if (crocus_opt /= 0) then\n       call get_landuse_or_glacinfo_netcdf(\"glacinfo\", ncid, xdum , units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n       if (ierr == 0) then\n          glacinfo = nint(xdum)\n       else\n          stop \"FATAL ERROR: In module_hrldas_netcdf_io.F readland_hrldas()\"// &\n               \" - crocus_opt on but netcdf read of glacinfo returned non-zero\"\n       end if\n\n       if (allocated(glact) .eqv. .false.) error stop \"FATAL ERROR: glact not initialized but crocus is on\"\n       ! Get Glacier thickness (glact)\n       call get_2d_netcdf(\"glacier_thickness\", ncid, glact,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n       if (ierr /= 0) then\n          glact = 0.0\n          print *, \"WARNING: crocus_opt on but get_2d_netcdf of glacier_thickness returned\", ierr, &\n               \". Setting glacier thickness to 0.0\"\n       end if\n\n       if (allocated(vis_icealb) .eqv. .false.) error stop \"FATAL ERROR: vis_icealb not initialized but crocus is on\"\n       ! Get visible ice albedo map (vis_icealb)\n       call get_2d_netcdf(\"min_vis\", ncid, vis_icealb,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n       if (ierr /= 0) then\n          vis_icealb = IEEE_VALUE(vis_icealb, IEEE_QUIET_NAN)\n          print*, 'WARNING: crocus_opt on but did not find min_vis, setting to NaN'\n       end if\n    end if ! crocus_opt /= 0\n\n\n    ! Get Dominant Soil Type categories in the top layer (stl)\n    call get_soilcat_netcdf(ncid, xdum ,   units, xstart, xend, ystart, yend)\n    soltyp = nint(xdum)\n    ! print*, 'soltyp(xstart,ystart) = ', soltyp(xstart,ystart)\n\n    ! Close the NetCDF file\n    ierr = nf90_close(ncid)\n    if (ierr /= 0) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F readland_hrldas()\"// &\n                        \" - MODULE_NOAHLSM_HRLDAS_INPUT: NF90_CLOSE\"\n\n    ! Make sure vegtyp and soltyp are consistent when it comes to water points,\n    ! by setting soil category to water when vegetation category is water, and\n    ! vice-versa.\n    where (vegtyp == ISWATER .or. vegtyp == ISLAKE) soltyp = 14\n    where (soltyp == 14) vegtyp = ISWATER\n\n  end subroutine readland_hrldas\n\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine read_mmf_runoff(wrfinput_flnm,                            &\n       xstart, xend,                                                   &\n       ystart, yend,                                                   &\n       zwt,eqzwt,riverbed,rivercond,pexp,fdepth)\n    implicit none\n    character(len=*),          intent(in)  :: wrfinput_flnm\n    integer,                   intent(in)  :: xstart, xend, ystart, yend\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: zwt\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: eqzwt\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: riverbed\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: rivercond\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: pexp\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: fdepth\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n    real, dimension(xstart:xend,ystart:yend) :: xdum\n    integer :: rank\n\n#ifdef _PARALLEL_\n    call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F read_mmf_runoff()\"// &\n                                  \" - MPI_Comm_rank\"\n#else\n    rank = 0\n#endif\n\n\n    ! Open the NetCDF file.\n    if (rank == 0) then\n#ifdef HYDRO_D\n        write(*,'(\"wrfinput_flnm: ''\", A, \"''\")') trim(wrfinput_flnm)\n#endif\n    endif\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(wrfinput_flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(wrfinput_flnm, NF90_NOWRITE, ncid)\n#endif\n    if (ierr /= 0) then\n       write(*,'(\"read_mmf_runoff:  Problem opening wrfinput file: ''\", A, \"''\")') trim(wrfinput_flnm)\n#ifdef _PARALLEL_\n       call MPI_Finalize(ierr)\n       if (ierr /= 0) write(*, '(\"Problem with MPI_Finalize.\")')\n#endif\n       stop \"FATAL ERROR: In module_hrldas_netcdf_io.F read_mmf_runoff()\"// &\n            \" - Problem opening wrfinput file.\"\n    endif\n\n    ! Get water table depth (ZWT)\n    call get_2d_netcdf(\"ZWT\", ncid, zwt,  units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    ! Get equilibrium water table depth (EQZWT)\n    call get_2d_netcdf(\"EQZWT\", ncid, eqzwt,  units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    ! Get equilibrium water table depth (RIVERBED)\n    call get_2d_netcdf(\"RIVERBED\", ncid, riverbed,  units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    ! Get equilibrium water table depth (RIVERCOND)\n    call get_2d_netcdf(\"RIVERCOND\", ncid, rivercond,  units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    ! Get equilibrium water table depth (PEXP)\n    call get_2d_netcdf(\"PEXP\", ncid, pexp,  units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    ! Get equilibrium water table depth (FDEPTH)\n    call get_2d_netcdf(\"FDEPTH\", ncid, fdepth,  units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    ! Close the NetCDF file\n    ierr = nf90_close(ncid)\n    if (ierr /= 0) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F read_mmf_runoff()\"// &\n                        \" - NF90_CLOSE problem.\"\n\n\n  end subroutine read_mmf_runoff\n\n!-------------------------------------------------------------------------------------------\n\n  subroutine read_xaj_runoff(spatial_filename,xstart, xend,ystart, yend,           &\n                             axaj_2d,bxaj_2d,xxaj_2d)\n\n    implicit none\n    character(len=*),          intent(in)  :: spatial_filename\n    integer,                   intent(in)  :: xstart, xend, ystart, yend\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: axaj_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: bxaj_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: xxaj_2d\n\n    character(len=24)  :: name\n    character(len=256) :: units\n    integer :: ierr,iret, varid\n    integer :: ncid\n    real, dimension(xstart:xend,ystart:yend) :: xdum\n!------------------------------------------------------------------------------------------------------\n\n    ierr = nf90_open(spatial_filename, NF90_NOWRITE, ncid)\n    if (ierr /= 0) then\n       write(*,'(\"FATAL ERROR: In read_xaj_runoff():  Problem opening soil file: ''\", A, \"''\")') trim(spatial_filename)\n       stop\n    endif\n\n    name = \"AXAJ\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_xaj_runoff():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, axaj_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"BXAJ\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_xaj_runoff():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, bxaj_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"XXAJ\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_xaj_runoff():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xxaj_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    ! Close the NetCDF file\n    ierr = nf90_close(ncid)\n    if (ierr /= 0) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F read_xaj_runoff() -  NF90_CLOSE\"\n\n  end subroutine read_xaj_runoff\n\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine read_imperv(spatial_filename, xstart, xend, ystart, yend, imperv_2d)\n\n    implicit none\n    character(len=*),          intent(in)  :: spatial_filename\n    integer,                   intent(in)  :: xstart, xend, ystart, yend\n    real,    dimension(xstart:xend,ystart:yend), intent(out) :: imperv_2d\n\n    character(len=24)  :: name\n    character(len=256) :: units\n    integer :: ierr,iret, varid\n    integer :: ncid\n    real, dimension(xstart:xend,ystart:yend) :: xdum\n!------------------------------------------------------------------------------------------------------\n\n    ierr = nf90_open(spatial_filename, NF90_NOWRITE, ncid)\n    if (ierr /= 0) then\n       write(*,'(\"FATAL ERROR: In read_imperv():  Problem opening soil file: ''\", A, \"''\")') trim(spatial_filename)\n       stop\n    endif\n\n    name = \"imperv\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_imperv():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, imperv_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    ! Close the NetCDF file\n    ierr = nf90_close(ncid)\n    if (ierr /= 0) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F read_imperv() -  NF90_CLOSE\"\n\n  end subroutine read_imperv\n\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine read_3d_soil(spatial_filename,xstart, xend,ystart, yend,           &\n                          nsoil,bexp_3d,smcdry_3d,smcwlt_3d,smcref_3d,smcmax_3d,  &\n\t\t          dksat_3d,dwsat_3d,psisat_3d,quartz_3d,refdk_2d,refkdt_2d,slope_2d,&\n\t\t\t  cwpvt_2d,vcmx25_2d,mp_2d,hvt_2d,mfsno_2d,rsurfexp_2d, &\n                          ssi_2d,snowretfac_2d,tau0_2d,rsurfsnow_2d,scamax_2d)\n    implicit none\n    character(len=*),          intent(in)  :: spatial_filename\n    integer,                   intent(in)  :: xstart, xend, ystart, yend\n    integer,                   intent(in)  :: nsoil\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: bexp_3d\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: smcdry_3d\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: smcwlt_3d\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: smcref_3d\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: smcmax_3d\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: dksat_3d\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: dwsat_3d\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: psisat_3d\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: quartz_3d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: refdk_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: refkdt_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: slope_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: cwpvt_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: vcmx25_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: mp_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: hvt_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: mfsno_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: rsurfexp_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: ssi_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: snowretfac_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: tau0_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: rsurfsnow_2d\n    real,    dimension(xstart:xend,ystart:yend), intent(out)       :: scamax_2d\n\n    character(len=24)  :: name\n    character(len=256) :: units\n    integer :: ierr,iret, varid,isoil\n    integer :: ncid\n    real, dimension(xstart:xend,ystart:yend,nsoil) :: xdum\n\n    ierr = nf90_open(spatial_filename, NF90_NOWRITE, ncid)\n    if (ierr /= 0) then\n       write(*,'(\"FATAL ERROR: In read_3d_soil():  Problem opening 3d soil file: ''\", A, \"''\")') trim(spatial_filename)\n       stop\n    endif\n\n    name = \"bexp\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      bexp_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"smcdry\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      smcdry_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"smcwlt\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      smcwlt_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"smcref\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil(): Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      smcref_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"smcmax\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      smcmax_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"dksat\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      dksat_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"dwsat\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      dwsat_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"psisat\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      psisat_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"quartz\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, xdum, start=(/xstart,ystart,1/), count=(/xend-xstart+1,yend-ystart+1,nsoil/))\n\n    do isoil = 1,4\n      quartz_3d(:,isoil,:) = xdum(:,:,isoil)\n    end do\n\n    name = \"refdk\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, refdk_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n\n    name = \"refkdt\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, refkdt_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n\n    name = \"slope\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, slope_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"cwpvt\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, cwpvt_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"vcmx25\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, vcmx25_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"mp\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, mp_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"hvt\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, hvt_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"mfsno\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, mfsno_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"rsurfexp\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, rsurfexp_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"ssi\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, ssi_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"snowretfac\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, snowretfac_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"tau0\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, tau0_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"rsurfsnow\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, rsurfsnow_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n!\n    name = \"scamax\"\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n      print*, 'ncid = ', ncid\n      write(*,*) \"FATAL ERROR: In read_3d_soil():  Problem finding variable '\"//trim(name)//\"' in NetCDF file: \" // trim(spatial_filename)\n      stop\n    endif\n\n    iret = nf90_get_var(ncid, varid, scamax_2d, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n\n    ! Close the NetCDF file\n    ierr = nf90_close(ncid)\n    if (ierr /= 0) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F read_3d_soil() -  NF90_CLOSE\"\n\n  end subroutine read_3d_soil\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine get_landuse_or_glacinfo_netcdf(in_name, ncid, array, units, &\n                                            xstart, xend, ystart, yend, &\n                                            fatal, ierr)\n    implicit none\n    character(len=*), intent(in) :: in_name\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n    logical, intent(in) :: fatal\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    character(len=256), intent(out) :: units\n    integer, intent(out)            :: ierr\n    integer :: iret, varid\n    character(len=24) :: name\n    ierr = 0\n    units = \" \"\n\n    if (trim(in_name) == \"landuse\") then\n       name = \"IVGTYP\"\n    else if (trim(in_name) == \"glacinfo\") then\n       name = \"glacier\"\n    end if\n\n\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n       ierr = iret\n       call report_landuse_or_glacinfo_error(name, fatal)\n    end if\n\n    iret = nf90_get_var(ncid, varid, array, (/xstart, ystart/), (/xend-xstart+1, yend-ystart+1/))\n    if (iret /= 0) then\n       ierr = iret\n       call report_landuse_or_glacinfo_error(name, fatal)\n    end if\n  end subroutine get_landuse_or_glacinfo_netcdf\n\n  subroutine report_landuse_or_glacinfo_error(name, fatal)\n    implicit none\n    character(len=24), intent(in) :: name\n    logical, intent(in)           :: fatal\n    character(len=142), parameter :: land_error = &\n         \"FATAL ERROR: In module_hrldas_netcdf_io.F get_landuse_or_glacinfo_netcdf() &\n         &- MODULE_NOAHLSM_HRLDAS_INPUT: nf90_inq_varid for variable landuse\"\n    character(len=142), parameter :: glacier_error = &\n         \"FATAL ERROR: In module_hrldas_netcdf_io.F get_landuse_or_glacinfo_netcdf() &\n         &- MODULE_NOAHLSM_HRLDAS_INPUT: nf90_inq_varid for variable glacier\"\n    if (fatal .eqv. .true.) return\n    print*, 'name = \"', trim(name)//'\"'\n    if (trim(name) == \"landuse\") then\n       stop land_error\n    else\n       stop glacier_error\n    end if\n  end subroutine report_landuse_or_glacinfo_error\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine get_soilcat_netcdf(ncid, array, units, xstart, xend, ystart, yend)\n    implicit none\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    character(len=256), intent(out) :: units\n    integer :: iret, varid\n    character(len=24), parameter :: name = \"ISLTYP\"\n\n    units = \" \"\n\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    call error_handler(iret, \"Problem finding variable '\"//trim(name)//\"' in the wrfinput file.\")\n\n    iret = nf90_get_var(ncid, varid, array, (/xstart, ystart/), (/xend-xstart+1, yend-ystart+1/))\n    call error_handler(iret, \"Problem retrieving variable \"//trim(name)//\" from the wrfinput file.\")\n\n  end subroutine get_soilcat_netcdf\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine get_2d_netcdf(name, ncid, array, units, xstart, xend, ystart, yend, &\n       fatal_if_error, ierr)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n#ifdef MPP_LAND\n    real, dimension(:,:), intent(inout) :: array\n#else\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n#endif\n    character(len=*), intent(out) :: units\n    integer :: iret, varid\n    ! FATAL_IF_ERROR:  an input code value:\n    !      .TRUE. if an error in reading the data should stop the program.\n    !      Otherwise the, IERR error flag is set, but the program continues.\n    logical, intent(in) :: fatal_if_error\n    integer, intent(out), volatile :: ierr\n#ifdef MPP_LAND\n    real, volatile :: g_array(global_nx,global_ny)\n#endif\n\n    ierr = 0\n\n#ifdef MPP_LAND\n    if(my_id .eq. 0) then\n#endif\n    iret = nf90_inq_varid(ncid,  name,  varid)\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'ncid = ', ncid\n          call error_handler(iret, \"FATAL ERROR: In get_2d_netcdf() -  Problem finding variable '\"//trim(name)//\"' in NetCDF file.\")\n       else\n          ierr = iret\n#ifdef MPP_LAND\n          goto 9991\n#endif\n          return\n       endif\n    endif\n\n    iret = nf90_get_att(ncid, varid, \"units\", units)\n    if (iret /= 0) units = \"units unknown\"\n!KWM    if (iret /= 0) then\n!KWM       if (FATAL_IF_ERROR) then\n!KWM          print*, 'name = \"', trim(name)//'\"'\n!KWM          stop \"MODULE_NOAHLSM_HRLDAS_INPUT:  get_2d_netcdf:  nf90_get_att:  units.\"\n!KWM       else\n!KWM          ierr = iret\n!KWM          return\n!KWM       endif\n!KWM    endif\n\n#ifdef MPP_LAND\n    iret = nf90_get_var(ncid, varid, values=g_array, start=(/1,1/), count=(/global_nx,global_ny/))\n#else\n    iret = nf90_get_var(ncid, varid, values=array, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n#endif\n    if (iret /= 0) then\n#ifdef MPP_LAND\n          goto 9991\n#endif\n       if (FATAL_IF_ERROR) then\n          print*, 'ncid =', ncid\n          call error_handler(iret, \"In module_hrldas_netcdf_io.F - \"// &\n               \"  Problem retrieving variable '\"//trim(name)//\"' from NetCDF file.\")\n       else\n          ierr = iret\n          return\n       endif\n    endif\n\n    ierr = 0;\n#ifdef MPP_LAND\n9991    continue\n    endif\n    call mpp_land_bcast_int1(ierr)\n    !yyww call mpp_land_bcast(units)\n    call mpp_land_bcast_char(256,units)\n    if(ierr /= 0) return\n#ifdef HYDRO_D\n    write(6,*) \"my_id, xstart,xend, ystart, yend\",my_id, xstart,xend, ystart, yend\n#endif\n    call decompose_data_real(g_array,array)\n\n#endif\n  end subroutine get_2d_netcdf\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine get_netcdf_soillevel(name, ncid, array, units, xstart, xend, ystart, yend, fatal_if_error, ierr)\n    implicit none\n    character(len=*), intent(in) :: name\n    integer, intent(in) :: ncid\n    integer, intent(in) :: xstart, xend, ystart, yend\n    real, dimension(xstart:xend,4,ystart:yend), intent(out) :: array\n    character(len=256), intent(out) :: units\n    ! FATAL_IF_ERROR:  an input code value:\n    !      .TRUE. if an error in reading the data should stop the program.\n    !      Otherwise the, IERR error flag is set, but the program continues.\n    logical, intent(in) :: fatal_if_error\n    integer, intent(out) :: ierr\n\n    integer :: iret, varid, isoil\n#ifdef MPP_LAND\n    real:: g_array(global_nx,4,global_ny)\n    real:: insoil(global_nx,global_ny,4)\n#else\n    real:: insoil(xstart:xend,ystart:yend,4)\n#endif\n\n    units = \" \"\n\n#ifdef MPP_LAND\n    if(my_id .eq. 0) then\n#endif\n\n    iret = nf90_inq_varid(ncid,  name,  varid)\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'name = \"', trim(name)//'\"'\n          stop \"FATAL ERROR: In module_hrldas_netcdf_io.F get_2d_netcdf_soillevel()\"// &\n               \" - nf90_inq_varid problem.\"\n       else\n          ierr = iret\n#ifdef MPP_LAND\n          goto 9992\n#endif\n          return\n       endif\n    endif\n\n    iret = nf90_get_att(ncid, varid, \"units\", units)\n    if (iret /= 0) units = \"units unknown\"\n\n#ifdef MPP_LAND\n    iret = nf90_get_var(ncid, varid, values=insoil, start=(/1,1,1,1/), count=(/global_nx,global_ny,4,1/))\n    do isoil = 1,4\n      g_array(:,isoil,:) = insoil(:,:,isoil)\n    end do\n#else\n    iret = nf90_get_var(ncid, varid, values=insoil, start=(/xstart,ystart,1,1/), count=(/xend-xstart+1,yend-ystart+1,4,1/))\n    do isoil = 1,4\n      array(:,isoil,:) = insoil(:,:,isoil)\n    end do\n#endif\n    if (iret /= 0) then\n       if (FATAL_IF_ERROR) then\n          print*, 'name = \"', trim(name)//'\"'\n          print*, 'varid =', varid\n          print*, trim(nf90_strerror(iret))\n          stop \"FATAL ERROR: In module_hrldas_netcdf_io.F get_2d_netcdf_soillevel()\"// &\n               \" - nf90_get_var problem\"\n       else\n          ierr = iret\n#ifdef MPP_LAND\n          goto 9992\n#endif\n          return\n       endif\n    endif\n\n    ierr = 0;\n#ifdef MPP_LAND\n9992    continue\n    endif\n    call mpp_land_bcast_int1(ierr)\n    call mpp_land_bcast_char(256,units)\n    if(ierr /= 0) return\n    call decompose_data_real3d(g_array,array,4)\n#endif\n  end subroutine get_netcdf_soillevel\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine readinit_hrldas(netcdf_flnm, xstart, xend, ystart, yend, nsoil, sldpth, target_date, &\n       ldasin_version, smc, stc, cmc, t1, weasd, snodep, fndsnowh)\n    implicit none\n    character(len=*),                                  intent(in)  :: netcdf_flnm\n    integer,                                           intent(in)  :: xstart, xend\n    integer,                                           intent(in)  :: ystart, yend\n    integer,                                           intent(in)  :: nsoil\n    real,    dimension(nsoil),                         intent(in)  :: sldpth\n    character(len=*),                                  intent(in)  :: target_date\n\n    integer,                                           intent(out) :: ldasin_version\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: smc\n    real,    dimension(xstart:xend,nsoil,ystart:yend), intent(out) :: stc\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: cmc\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: t1\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: weasd\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: snodep\n    logical,                                           intent(out) :: fndsnowh\n\n    character(len=256) :: titlestr\n    character(len=256) :: units\n    character(len=8)   :: name\n    character(len=256) :: ldasin_llanduse\n\n    integer :: ierr, ncid, ierr_snodep, varid\n    integer :: idx, isoil\n    real, dimension(100) :: layer_bottom\n    real, dimension(100) :: layer_top\n    real, dimension(4)   :: dzs\n\n    real, dimension(xstart:xend, ystart:yend, 4) :: insoil\n    real, dimension(xstart:xend, 4, ystart:yend) :: soildummy\n    integer :: rank\n\n    !\n    ! Open the NetCDF LDASIN file.\n    !\n\n#ifdef _PARALLEL_\n\n    call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In  module_hrldas_netcdf_io.F\"// &\n                                  \" readinit_hrldas() - MPI_Comm_rank\"\n\n    ierr = nf90_open_par(netcdf_flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    rank = 0\n    ierr = nf90_open(netcdf_flnm, NF90_NOWRITE, ncid)\n#endif\n    if (rank == 0) then\n#ifdef HYDRO_D\n        write(*,'(\"netcdf_flnm: ''\", A, \"''\")') trim(netcdf_flnm)\n#endif\n    endif\n    if (ierr /= 0) then\n       if (rank == 0) then\n#ifdef HYDRO_D\n           write(*,'(\"Problem opening netcdf file: ''\", A, \"''\")') trim(netcdf_flnm)\n#endif\n       endif\n#ifdef _PARALLEL_\n       call MPI_Finalize(ierr)\n#endif\n       stop \"FATAL ERROR: In  module_hrldas_netcdf_io.F readinit_hrldas()\"// &\n            \" - Problem opening netcdf file.\"\n    endif\n\n    !\n    ! Check the NetCDF LDASIN file for a version number.\n    !\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TITLE\", titlestr)\n    if (ierr /= 0) then\n       write(*,'(\"WARNING:  LDASIN file does not have TITLE attribute.\")')\n       write(*,'(\"          This probably means that LDASIN files are from an older release.\")')\n       write(*,'(\"          I assume you know what you are doing.\")')\n       ldasin_version = 0\n    else\n#ifdef HYDRO_D\n       write(*,'(\"LDASIN TITLE attribute: \", A)') trim(titlestr)\n#endif\n       ! Pull out the version number, assuming that the version is identified by vYYYYMMDD, and\n       ! based on a search for the string \"v20\".\n       idx = index(trim(titlestr), \"v20\")\n       if (idx <= 0) then\n          write(*,'(\"WARNING:  LDASIN file has a perverse version identifier\")')\n          !  write(*,'(\"          I assume you know what you are doing.\")')\n          ! stop\n       else\n          read(titlestr(idx+1:), '(I8)', iostat=ierr) ldasin_version\n          if (ierr /= 0) then\n             write(*,'(\"WARNING:  LDASIN file has a perverse version identifier\")')\n             !  write(*,'(\"          I assume you know what you are doing.\")')\n             ! stop\n          endif\n       endif\n    endif\n    write(*, '(\"ldasin_version = \", I8)') ldasin_version\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, \"MMINLU\", ldasin_llanduse)\n    if (ierr /= 0) then\n       write(*,'(\"WARNING:  LDASIN file does not have MMINLU attribute.\")')\n       write(*,'(\"          This probably means that LDASIN files are from an older release.\")')\n       write(*,'(\"          I assume you know what you are doing.\")')\n    else\n#ifdef HYDRO_D\n       write(*,'(\"LDASIN MMNINLU attribute: \", A)') ldasin_llanduse\n#endif\n    endif\n\n    call get_2d_netcdf(\"CANWAT\", ncid, cmc,     units, xstart, xend, ystart, yend, FATAL, ierr)\n    call get_2d_netcdf(\"TSK\",    ncid, t1,      units, xstart, xend, ystart, yend, FATAL, ierr)\n    call get_2d_netcdf(\"SNOW\",   ncid, weasd,   units, xstart, xend, ystart, yend, FATAL, ierr)\n! MB: assume in mm in v3.7\n!    if (trim(units) == \"m\") then\n!       ! No conversion necessary\n!    else if (trim(units) == \"mm\") then\n!       ! convert WEASD from mm to m\n!       weasd = weasd * 1.E-3\n!    else if (trim(units) == \"kg m{-2}\") then\n!       ! convert WEASD from mm to m\n!       weasd = weasd * 1.E-3\n!    else if (trim(units) == \"kg m-2\") then\n!       ! convert WEASD from mm to m\n!       weasd = weasd * 1.E-3\n!    else if (trim(units) == \"kg/m2\") then\n!       ! convert WEASD from mm to m\n!       weasd = weasd * 1.E-3\n!    else\n!       print*, 'units = \"'//trim(units)//'\"'\n!       stop \"Unrecognized units on WEASD\"\n!    endif\n\n    snodep = 0.0\n    call get_2d_netcdf(\"SNODEP\",     ncid, snodep,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr_snodep)\n    fndsnowh = .true.\n    if (ierr_snodep /= 0) fndsnowh = .false.\n\n    ! Get the interfaces from the input file (not the variable as of v3.7)\n\n    ierr = nf90_inq_varid(ncid,  \"DZS\",  varid)\n    ierr = nf90_get_var(ncid, varid, values=dzs, start=(/1/), count=(/4/))\n\n    layer_top(1) = 0.0\n    layer_bottom(1) = dzs(1)\n    do isoil = 2, 4\n      layer_top(isoil) = layer_bottom(isoil-1)\n      layer_bottom(isoil) = layer_top(isoil) + dzs(isoil)\n    end do\n\n    call get_netcdf_soillevel(\"TSLB\", ncid, soildummy, units,  xstart, xend, ystart, yend, FATAL, ierr)\n\n#ifdef HYDRO_D\n    write(*, '(\"layer_bottom(1:4) = \", 4F9.4)') layer_bottom(1:4)\n    write(*, '(\"layer_top(1:4)    = \", 4F9.4)') layer_top(1:4)\n    write(*, '(\"Soil depth = \", 10F12.6)') sldpth\n#endif\n    call init_interp(xstart, xend, ystart, yend, nsoil, sldpth, stc, 4, soildummy, layer_bottom(1:4), layer_top(1:4))\n\n    call get_netcdf_soillevel(\"SMOIS\", ncid, soildummy, units,  xstart, xend, ystart, yend, FATAL, ierr)\n\n    call init_interp(xstart, xend, ystart, yend, nsoil, sldpth, smc, 4, soildummy, layer_bottom(1:4), layer_top(1:4))\n\n    ierr = nf90_close(ncid)\n  end subroutine readinit_hrldas\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine init_interp(xstart, xend, ystart, yend, nsoil, sldpth, var, nvar, src, layer_bottom, layer_top)\n    implicit none\n    integer, intent(in)    :: xstart, xend, ystart, yend, nsoil, nvar\n    real, dimension(nsoil) :: sldpth ! the thickness of each layer\n    real, dimension(xstart:xend, nsoil, ystart:yend), intent(out) :: var\n    real, dimension(xstart:xend, nvar, ystart:yend ), intent(in)  :: src\n    real, dimension(nvar),                            intent(in)  :: layer_bottom ! The depth from the surface of each layer bottom.\n    real, dimension(nvar),                            intent(in)  :: layer_top    ! The depth from the surface of each layer top.\n    integer :: i, j, k, kk, ktop, kbottom\n    real, dimension(nsoil) :: dst_centerpoint\n    real, dimension(nvar)  :: src_centerpoint\n    real :: fraction\n    integer :: ierr\n    integer :: rank\n\n#ifdef _PARALLEL_\n    call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In  module_hrldas_netcdf_io.F init_interp()\"// &\n                                  \" - MPI_Comm_rank.\"\n#else\n    rank = 0\n#endif\n\n    do k = 1, nsoil\n       if (k==1) then\n          dst_centerpoint(k) = sldpth(k)/2.\n       else\n          dst_centerpoint(k) = sldpth(k)/2. + sum(sldpth(1:k-1))\n       endif\n       if (rank == 0) then\n#ifdef HYDRO_D\n          print*, 'k, dst_centerpoint(k) = ', k, dst_centerpoint(k)\n#endif\n       endif\n    enddo\n    print*\n\n    do k = 1, nvar\n       src_centerpoint(k) = 0.5*(layer_bottom(k)+layer_top(k))\n       if (rank == 0) then\n#ifdef HYDRO_D\n              print*, 'k, src_centerpoint(k) = ', k, src_centerpoint(k)\n#endif\n      endif\n    enddo\n\n    KLOOP : do k = 1, nsoil\n\n       if (dst_centerpoint(k) < src_centerpoint(1)) then\n          ! If the center of the destination layer is closer to the surface than\n          ! the center of the topmost source layer, then simply set the\n          ! value of the destination layer equal to the topmost source layer:\n          if (rank == 0) then\n#ifdef HYDRO_D\n             print'(\"Shallow destination layer:  Taking destination layer at \",F7.4, \" from source layer at \", F7.4)', &\n                  dst_centerpoint(k), src_centerpoint(1)\n#endif\n          endif\n          var(:,k,:) = src(:,1,:)\n          cycle KLOOP\n       endif\n\n       if (dst_centerpoint(k) > src_centerpoint(nvar)) then\n          ! If the center of the destination layer is deeper than\n          ! the center of the deepest source layer, then simply set the\n          ! value of the destination layer equal to the deepest source layer:\n          if (rank == 0) then\n#ifdef HYDRO_D\n             print'(\"Deep destination layer:  Taking destination layer at \",F7.4, \" from source layer at \", F7.4)', &\n                  dst_centerpoint(k), src_centerpoint(nvar)\n#endif\n          endif\n          var(:,k,:) = src(:,nvar,:)\n          cycle KLOOP\n       endif\n\n       ! Check if the center of the destination layer is \"close\" to the center\n       ! of a source layer.  If so, simply set the value of the destination layer\n       ! equal to the value of that close soil layer:\n       do kk = 1, nvar\n          if (abs(dst_centerpoint(k)-src_centerpoint(kk)) < 0.01) then\n             if (rank == 0) then\n#ifdef HYDRO_D\n                print'(\"(Near) match for destination layer:  Taking destination layer at \",F7.4, \" from source layer at \", F7.4)', &\n                     dst_centerpoint(k), src_centerpoint(kk)\n#endif\n             endif\n             var(:,k,:) = src(:,kk,:)\n             cycle KLOOP\n          endif\n       enddo\n\n       ! Otherwise, do a linear interpolation\n\n       ! Get ktop, the index of the top bracketing layer from the source dataset.\n       ! Which from the bottom up, will be the first source level that is closer\n       ! to the surface than the destination level\n       ktop = -99999\n       TOPLOOP : do kk = nvar,1,-1\n          if (src_centerpoint(kk) < dst_centerpoint(k)) then\n             ktop = kk\n             exit TOPLOOP\n          endif\n       enddo TOPLOOP\n       if (ktop < -99998) stop \"FATAL ERROR: In  module_hrldas_netcdf_io.F init_interp()\"// &\n                               \" - ktop problem\"\n\n\n       ! Get kbottom, the index of the bottom bracketing layer from the source dataset.\n       ! Which, from the top down, will be the first source level that is deeper than\n       ! the destination level\n       kbottom = -99999\n       BOTTOMLOOP : do kk = 1, nvar\n          if ( src_centerpoint(kk) > dst_centerpoint(k) ) then\n             kbottom = kk\n             exit BOTTOMLOOP\n          endif\n       enddo BOTTOMLOOP\n       if (kbottom < -99998) stop \"FATAL ERROR: In  module_hrldas_netcdf_io.F init_interp()\"// &\n                                  \" - kbottom problem\"\n\n       fraction = (src_centerpoint(kbottom)-dst_centerpoint(k)) / (src_centerpoint(kbottom)-src_centerpoint(ktop))\n\n       ! print '(I2, 1x, 3F7.3, F8.5)', k, src_centerpoint(ktop), dst_centerpoint(k), src_centerpoint(kbottom), fraction\n\n       if (rank == 0) then\n#ifdef HYDRO_D\n          print '(\"dst(\",I1,\") = src(\",I1,\")*\",F8.5,\" + src(\",I1,\")*\",F8.5)', k, ktop, fraction, kbottom, (1.0-fraction)\n#endif\n       endif\n\n       var(:,:,k) = (src(:,ktop,:)*fraction) + (src(:,kbottom,:)*(1.0-fraction))\n\n    enddo KLOOP\n\n  end subroutine init_interp\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine READVEG_HRLDAS(flnm, xstart, xend, ystart, yend, target_date, vegtyp, vegfra, lai, gvfmin, gvfmax)\n\n    implicit none\n    character(len=*),                                  intent(in)  :: flnm\n    integer,                                           intent(in)  :: xstart, xend\n    integer,                                           intent(in)  :: ystart, yend\n    character(len=*),                                  intent(in)  :: target_date\n    integer, dimension(xstart:xend,ystart:yend),       intent(in)  :: vegtyp\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: vegfra\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: lai\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: gvfmin\n    real,    dimension(xstart:xend,ystart:yend),       intent(out) :: gvfmax\n\n    character(len=8)   :: name\n    character(len=256) :: units\n    integer :: ierr\n\n    integer :: ierr_vegfra\n    integer :: ierr_lai\n\n    integer :: i, j\n    integer :: iret, ncid\n\n    ! Open the NetCDF file.\n!KWM    write(*,'(\"flnm: ''\", A, \"''\")') trim(flnm)\n#ifdef _PARALLEL_\n    iret = nf90_open_par(flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    iret = nf90_open(flnm, NF90_NOWRITE, ncid)\n#endif\n    if (iret /= 0) then\n       write(*,'(\"FATAL ERROR: In  module_hrldas_netcdf_io.F READVEG_HRLDAS()\"// &\n                 \" - Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       stop\n    endif\n\n    call get_2d_netcdf(\"VEGFRA\",     ncid, vegfra,     units, xstart, xend, ystart, yend, NOT_FATAL, ierr_vegfra)\n    call get_2d_netcdf(\"LAI\",        ncid, lai,      units, xstart, xend, ystart, yend, NOT_FATAL, ierr_lai)\n\n    if (ierr_vegfra == 0) then\n       ! vegfra = vegfra * 1.E-2 ! convert from percent to fraction\n    else if (ierr_vegfra /= 0) then\n       ! Get it from tables\n       ! print*,' READVEG_HRLDAS:  VEGFRA not found.  Initializing VEGFRA from table SHDTBL.'\n       do i = xstart, xend\n          do j = ystart, yend\n!KWM             vegfra(i,j) = shdtbl(vegtyp(i,j))\n          enddo\n       enddo\n    endif\n    if (ierr_lai /= 0) then\n       ! Get it from tables\n       ! print*,' READVEG_HRLDAS:  LAI not found.  Initializing LAI from table LAITBL.'\n       do i = xstart, xend\n          do j = ystart, yend\n! Fixme for wrfcode input\n!             lai(i,j) = laitbl(vegtyp(i,j))\n          enddo\n       enddo\n    endif\n\n    ! Get Minimum Green Vegetation Fraction SHDMIN\n    call get_2d_netcdf(\"SHDMIN\", ncid, gvfmin,   units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    ! Get Minimum Green Vegetation Fraction SHDMAX\n    call get_2d_netcdf(\"SHDMAX\", ncid, gvfmax,   units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    iret = nf90_close(ncid)\n  end subroutine READVEG_HRLDAS\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine READFORC_HRLDAS(flnm_template, forcing_timestep, target_date, xstart, xend, ystart, yend,  &\n       forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n       forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n       t,q,u,v,p,lw,sw,pcp,snow,vegfra,update_veg,lai,update_lai)\n    use kwm_string_utilities\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm_template\n    integer,                            intent(in)  :: forcing_timestep\n    integer,                            intent(in)  :: xstart, xend\n    integer,                            intent(in)  :: ystart, yend\n    character(len=19),                  intent(in)  :: target_date ! (YYYY-MM-DD_hh:mm:ss)\n    character(len=256),                 intent(in)  :: forcing_name_T\n    character(len=256),                 intent(in)  :: forcing_name_Q\n    character(len=256),                 intent(in)  :: forcing_name_U\n    character(len=256),                 intent(in)  :: forcing_name_V\n    character(len=256),                 intent(in)  :: forcing_name_P\n    character(len=256),                 intent(in)  :: forcing_name_LW\n    character(len=256),                 intent(in)  :: forcing_name_SW\n    character(len=256),                 intent(in)  :: forcing_name_PR\n    character(len=256),                 intent(in)  :: forcing_name_SN\n    character(len=256),                 intent(in)  :: forcing_name_LF\n\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: t\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: q\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: u\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: v\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: p\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: lw\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: sw\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: pcp\n    real,             dimension(xstart:xend,ystart:yend), intent(out)   :: snow\n    real,             dimension(xstart:xend,ystart:yend), intent(inout) :: lai    !Barlage v3.7: change to inout\n    real,             dimension(xstart:xend,ystart:yend), intent(inout) :: vegfra\n    logical,                            intent(in)  :: update_veg, update_lai  ! Barlage v3.7: for veg read control\n\n    real,             dimension(xstart:xend,ystart:yend)                :: liqfrac\n    logical :: snow_read = .false.\n\n    character(len=256) :: flnm\n    character(len=256) :: units\n    character(len=256) :: nextflnm\n    integer :: ierr\n    integer :: ncid\n    integer :: rank\n\n    type(inputstruct) :: lastread = inputstruct(\"0000-00-00_00:00:00\", &\n         null(), null(), null(), null(), null(), null(), null(), null(), null(), null(), null())\n    type(inputstruct) :: nextread= inputstruct(\"0000-00-00_00:00:00\", &\n         null(), null(), null(), null(), null(), null(), null(), null(), null(), null(), null())\n\n!KWM    print*, 'target_date        = ', target_date\n!KWM    print*, 'lastread%read_date = ', lastread%read_date\n!KWM    print*, 'nextread%read_date = ', nextread%read_date\n\n\n#ifdef MPP_LAND\n     call mpp_land_bcast_char(19,target_date(1:19))\n     call mpp_land_bcast_char(19,nextread%read_date(1:19))\n#endif\n\n    if (target_date > nextread%read_date ) then\n       !\n       ! We've advanced beyond the date of the end-bracketing data in memory.\n       ! Read the next (later) forcing data, and put the data into the nextread\n       ! structure.\n       !\n       if (nextread%read_date /= \"0000-00-00_00:00:00\") then\n          ! Clear the old lastread data\n          call clear_inputstruct(lastread)\n\n          ! Copy nextread to lastread\n          lastread = nextread\n\n          ! Clear nextread\n          call nullify_inputstruct(nextread)\n       endif\n\n       ! Guess the next read date (from the last read date and the forcing timestep).\n       ! If there is no last date, assume we're at the beginning of our processing\n       ! and take the target_date as the first timestep, for which forcing data\n       ! must be available.\n\n#ifdef MPP_LAND\n     call mpp_land_bcast_char(19,lastread%read_date(1:19))\n#endif\n       if (lastread%read_date == \"0000-00-00_00:00:00\") then\n          nextread%read_date = target_date\n       else\n          call geth_newdate(nextread%read_date, lastread%read_date, forcing_timestep)\n       endif\n\n       ! Build a file name\n       flnm = flnm_template\n\n#ifdef MPP_LAND\n       if(my_id .eq. IO_id) then\n#endif\n       call strrep(flnm, \"<date>\", nextread%read_date(1:4)//nextread%read_date(6:7)//nextread%read_date(9:10)//nextread%read_date(12:13))\n\n       !print*, 'read file:  ', trim(flnm)\n       ! Open the NetCDF file.\n#ifdef _PARALLEL_\n       ierr = nf90_open_par(flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n       ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n#endif\n       if (ierr /= 0) then\n#ifdef _PARALLEL_\n          call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n          if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In  module_hrldas_netcdf_io.F\"// &\n                                        \" READFORC_HRLDAS() - MPI_Comm_rank\"\n          if (rank == 0) then\n#endif\n             write(*,'(\"A)  Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n#ifdef _PARALLEL_\n          endif\n          call MPI_Finalize(ierr)\n#endif\n          stop  \"FATAL ERROR: In  module_hrldas_netcdf_io.F READFORC_HRLDAS()\"// &\n                \" - Problem opening netcdf file\"\n       endif\n\n#ifdef MPP_LAND\n      endif\n#endif\n       ! Allocate space to hold data\n       call allocate_inputstruct(nextread, xstart, xend, ystart, yend)\n\n       ! Read the data\n       call get_2d_netcdf(trim(forcing_name_T) , ncid, nextread%t,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(trim(forcing_name_Q) , ncid, nextread%q,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(trim(forcing_name_U) , ncid, nextread%u,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(trim(forcing_name_V) , ncid, nextread%v,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(trim(forcing_name_P) , ncid, nextread%p,     units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(trim(forcing_name_LW), ncid, nextread%lw,    units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(trim(forcing_name_SW), ncid, nextread%sw,    units, xstart, xend, ystart, yend, FATAL, ierr)\n       call get_2d_netcdf(trim(forcing_name_PR), ncid, nextread%pcp,   units, xstart, xend, ystart, yend, FATAL, ierr)\n\n       nextread%snow = 0.0  ! Assume zero in case not present\n       if(trim(forcing_name_SN) /= \"\") then\n         call get_2d_netcdf(trim(forcing_name_SN), ncid, nextread%snow,  units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n         if(ierr == 0) snow_read = .true.\n       end if\n\n       if(trim(forcing_name_LF) /= \"\" .and. .not. snow_read) then   ! snow was not read in\n         liqfrac = 1.0            ! Assume all liquid in case not present\n         call get_2d_netcdf(trim(forcing_name_LF), ncid, liqfrac,  units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n         if (ierr == 0) nextread%snow = (1.0 - liqfrac ) * nextread%pcp\n       end if\n\n       if(update_veg) then    ! Barlage v3.7: update only if dveg option is appropriate\n\n         call get_2d_netcdf(\"VEGFRA\",  ncid, nextread%vegfra,units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n         if (ierr /= 0) then\n          ! print*, 'VEGFRA not found!'\n          ! If we don't find a new VEGFRA, carry over the old one\n          if (associated(lastread%vegfra)) then\n             nextread%vegfra = lastread%vegfra\n          else\n             nextread%vegfra = vegfra\n          endif\n         endif\n\n       endif\n\n       if(update_lai) then    ! Barlage v3.7: update only if dveg option is appropriate\n\n         call get_2d_netcdf(\"LAI\",     ncid, nextread%lai,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n         if (ierr /= 0) then\n          ! print*, 'LAI not found!'\n          ! If we don't find a new LAI, carry over the old one\n          if (associated(lastread%lai)) then\n            nextread%lai = lastread%lai\n          else\n            nextread%lai = lai\n          endif\n         endif\n\n       endif\n\n#ifdef MPP_LAND\n       if(my_id .eq. IO_id) &\n#endif\n       ! Close the file\n       ierr = nf90_close(ncid)\n\n    endif\n\n\n#ifdef MPP_LAND\n     call mpp_land_bcast_char(19,target_date(1:19))\n#endif\n\n\n    if (target_date == nextread%read_date) then\n       !\n       ! We have advanced to the later date of our bracketing times for interpolation.\n       ! Take that data as is, no interpolation necessary, move that data into the\n       ! lastread structure, and return that data.\n       !\n\n       ! Fill the t, q, u, v, ... arrays with data from the nextread structure.\n       call copyfrom_inputstruct(nextread, t, q, u, v, p, lw, sw, pcp, snow, vegfra, lai, &\n                                 update_veg, update_lai, xstart, xend, ystart, yend)\n\n       ! Clear the old lastread data\n       call clear_inputstruct(lastread)\n\n       ! Copy nextread to lastread\n       lastread = nextread\n\n       ! Set the nextread%read_date field to signal that we need to read\n       nextread%read_date = \"0000-00-00_00:00:00\"\n\n       ! Clear nextread\n       call nullify_inputstruct(nextread)\n\n    else if ( ( target_date > lastread%read_date ) .and. ( target_date < nextread%read_date ) ) then\n\n       !\n       ! We are at a Noah time step between the lastread data and the available nextread data.\n       ! Do temporal interpolation and return the interpolated data.  Keep lastread\n       ! and nextread as they were.\n       !\n\n       ! Fill the t, q, u, v, ... arrays with data interpolated between lastread and nextread times.\n       call interpolate_inputstruct(lastread, nextread, target_date, &\n            t, q, u, v, p, lw, sw, pcp, snow, vegfra, lai, update_veg, update_lai, xstart, xend, ystart, yend)\n\n    else\n\n       print*, 'target_date        = ', target_date\n       print*, 'lastread%read_date = ', lastread%read_date\n       print*, 'nextread%read_date = ', nextread%read_date\n\n       STOP \"FATAL ERROR: We should not be here.  Problem with the logic of READFORC_SHORTER_TIMESTEP\"\n\n    endif\n\n  end subroutine READFORC_HRLDAS\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine allocate_inputstruct(instruct, xstart, xend, ystart, yend)\n    implicit none\n    type(inputstruct)   :: instruct\n    integer, intent(in) :: xstart\n    integer, intent(in) :: xend\n    integer, intent(in) :: ystart\n    integer, intent(in) :: yend\n\n    integer :: allostat\n\n    allocate(instruct%t   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%t\"\n\n    allocate(instruct%q   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%q\"\n\n    allocate(instruct%u   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%u\"\n\n    allocate(instruct%v   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%v\"\n\n    allocate(instruct%p   (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%p\"\n\n    allocate(instruct%lw  (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%lw\"\n\n    allocate(instruct%sw  (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%sw\"\n\n    allocate(instruct%pcp (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%pcp\"\n\n    allocate(instruct%snow (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"Problem allocating instruct%snow\"\n\n    allocate(instruct%vegfra(xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct()- Problem allocating instruct%vegfra\"\n\n    allocate(instruct%lai (xstart:xend,ystart:yend), stat=allostat )\n    if (allostat/=0) stop \"FATAL ERROR: In allocate_inputstruct() - Problem allocating instruct%lai\"\n#ifdef MPP_LAND\n    instruct%lai = 0.0\n#endif\n  end subroutine allocate_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine copyfrom_inputstruct(instruct, t, q, u, v, p, lw, sw, pcp, snow, vegfra, lai, &\n                                  update_veg, update_lai, xstart, xend, ystart, yend)\n    implicit none\n    type(inputstruct), intent(in) :: instruct\n    integer,           intent(in) :: xstart, xend, ystart, yend\n    logical,           intent(in)  :: update_veg, update_lai  ! Barlage v3.7: for veg read control\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: t, q, u, v, p, lw, sw, pcp, snow, vegfra, lai\n    t    = instruct%t\n    q    = instruct%q\n    u    = instruct%u\n    v    = instruct%v\n    p    = instruct%p\n    lw   = instruct%lw\n    sw   = instruct%sw\n    snow = instruct%snow\n    pcp  = instruct%pcp\n    if(update_veg) vegfra = instruct%vegfra\n    if(update_lai)   lai  = instruct%lai\n  end subroutine copyfrom_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine interpolate_inputstruct(instructA, instructB, target_date, &\n       t, q, u, v, p, lw, sw, pcp, snow, vegfra, lai, update_veg, update_lai, xstart, xend, ystart, yend)\n    implicit none\n    type(inputstruct),                        intent(in)  :: instructA, instructB\n    character(len=19),                        intent(in)  :: target_date\n    integer,                                  intent(in)  :: xstart, xend, ystart, yend\n    logical,                                  intent(in)  :: update_veg, update_lai  ! Barlage v3.7: for veg read control\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: t, q, u, v, p, lw, sw, pcp, snow, vegfra, lai\n\n    integer :: idts, idts2\n    real    :: fraction\n\n    call geth_idts(target_date, instructA%read_date, idts)\n    call geth_idts(instructB%read_date, instructA%read_date, idts2)\n\n    fraction = real(idts2-idts)/real(idts2)\n    t  = ( instructA%t  * fraction ) + ( instructB%t  * (1.0-fraction) )\n    q  = ( instructA%q  * fraction ) + ( instructB%q  * (1.0-fraction) )\n    u  = ( instructA%u  * fraction ) + ( instructB%u  * (1.0-fraction) )\n    v  = ( instructA%v  * fraction ) + ( instructB%v  * (1.0-fraction) )\n    p  = ( instructA%p  * fraction ) + ( instructB%p  * (1.0-fraction) )\n    lw = ( instructA%lw * fraction ) + ( instructB%lw * (1.0-fraction) )\n    sw = ( instructA%sw * fraction ) + ( instructB%sw * (1.0-fraction) )\n    snow = instructA%snow\n    pcp = instructA%pcp\n    if(update_veg) vegfra = instructA%vegfra\n    if(update_lai)   lai  = instructA%lai\n  end subroutine interpolate_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine clear_inputstruct(instruct)\n    implicit none\n    type(inputstruct) :: instruct\n\n    if (associated(instruct%t)) then\n       deallocate(instruct%t)\n       nullify(instruct%t)\n    endif\n\n    if (associated(instruct%q)) then\n       deallocate(instruct%q)\n       nullify(instruct%q)\n    endif\n\n    if (associated(instruct%u)) then\n       deallocate(instruct%u)\n       nullify(instruct%u)\n    endif\n\n    if (associated(instruct%v)) then\n       deallocate(instruct%v)\n       nullify(instruct%v)\n    endif\n\n    if (associated(instruct%p)) then\n       deallocate(instruct%p)\n       nullify(instruct%p)\n    endif\n\n    if (associated(instruct%lw)) then\n       deallocate(instruct%lw)\n       nullify(instruct%lw)\n    endif\n\n    if (associated(instruct%sw)) then\n       deallocate(instruct%sw)\n       nullify(instruct%sw)\n    endif\n\n    if (associated(instruct%pcp)) then\n       deallocate(instruct%pcp)\n       nullify(instruct%pcp)\n    endif\n\n    if (associated(instruct%snow)) then\n       deallocate(instruct%snow)\n       nullify(instruct%snow)\n    endif\n\n    if (associated(instruct%vegfra)) then\n       deallocate(instruct%vegfra)\n       nullify(instruct%vegfra)\n    endif\n\n    if (associated(instruct%lai)) then\n       deallocate(instruct%lai)\n       nullify(instruct%lai)\n    endif\n  end subroutine clear_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine nullify_inputstruct(instruct)\n    implicit none\n    type(inputstruct) :: instruct\n\n    nullify(instruct%t)\n    nullify(instruct%q)\n    nullify(instruct%u)\n    nullify(instruct%v)\n    nullify(instruct%p)\n    nullify(instruct%lw)\n    nullify(instruct%sw)\n    nullify(instruct%pcp)\n    nullify(instruct%vegfra)\n    nullify(instruct%lai)\n  end subroutine nullify_inputstruct\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine READSNOW_HRLDAS(flnm,xstart,xend,ystart,yend,target_date,weasd,snodep)\n    implicit none\n\n    character(len=*),                                     intent(in)  :: flnm\n    integer,                                              intent(in)  :: xstart, xend\n    integer,                                              intent(in)  :: ystart, yend\n    character(len=*),                                     intent(in)  :: target_date\n    real,             dimension(xstart:xend,ystart:yend), intent(out) :: weasd\n    real,             dimension(xstart:xend,ystart:yend), intent(out) :: snodep\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n\n    ! Open the NetCDF file.\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(flnm, NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n#endif\n    if (ierr /= 0) then\n       write(*,'(\"FATAL ERROR: In  module_hrldas_netcdf_io.F READSNOW_HRLDAS()\"// &\n                 \" - Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       stop\n    endif\n\n    call get_2d_netcdf(\"WEASD\",  ncid, weasd,   units, xstart, xend, ystart, yend, FATAL, ierr)\n\n    if (trim(units) == \"m\") then\n       ! No conversion necessary\n    else if (trim(units) == \"mm\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else if (trim(units) == \"kg m{-2}\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else if (trim(units) == \"kg/m2\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else\n       print*, 'units = \"'//trim(units)//'\"'\n       stop \"FATAL ERROR: In  module_hrldas_netcdf_io.F READSNOW_HRLDAS()\"// &\n            \" - Unrecognized units on WEASD\"\n    endif\n\n    call get_2d_netcdf(\"SNODEP\",     ncid, snodep,   units, xstart, xend, ystart, yend, NOT_FATAL, ierr)\n\n    if (ierr /= 0) then\n       ! Quick assumption regarding snow depth.\n       snodep = weasd * 10.\n    endif\n\n    ierr = nf90_close(ncid)\n\n  end subroutine READSNOW_HRLDAS\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n#ifdef MPP_LAND\n  subroutine prepare_output_file_mpp(outdir, version, igrid, &\n       output_timestep, llanduse, split_output_count, hgrid, &\n       ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar, iswater,  &\n       mapproj, lat1, lon1, dx, dy, truelat1, truelat2, cen_lon,     &\n       nsoil, nsnow, sldpth, startdate, date, &\n       vegtyp, soltyp, act_level)\n\n    implicit none\n\n    character(len=*),                         intent(in) :: outdir\n    character(len=*),                         intent(in) :: version\n    integer,                                  intent(in) :: igrid\n    integer,                                  intent(in) :: output_timestep\n    character(len=*),                         intent(in) :: llanduse\n    integer,                                  intent(in) :: split_output_count\n    character,                                intent(in) :: hgrid\n    integer,                                  intent(in) :: ixfull\n    integer,                                  intent(in) :: jxfull\n    integer,                                  intent(in) :: ixpar\n    integer,                                  intent(in) :: jxpar\n    integer,                                  intent(in) :: xstartpar\n    integer,                                  intent(in) :: ystartpar\n    integer,                                  intent(in) :: iswater\n    integer,                                  intent(in) :: mapproj\n    real,                                     intent(in) :: lat1\n    real,                                     intent(in) :: lon1\n    real,                                     intent(in) :: dx\n    real,                                     intent(in) :: dy\n    real,                                     intent(in) :: truelat1\n    real,                                     intent(in) :: truelat2\n    real,                                     intent(in) :: cen_lon\n    integer,                                  intent(in) :: nsoil\n    integer,                                  intent(in) :: nsnow\n    integer, optional,                        intent(in) :: act_level\n    real,             dimension(nsoil),       intent(in) :: sldpth\n    character(len=19),                        intent(in) :: startdate\n    character(len=19),                        intent(in) :: date\n    integer,          dimension(ixpar,jxpar), intent(in) :: vegtyp\n    integer,          dimension(ixpar,jxpar), intent(in) :: soltyp\n    integer,          dimension(global_nx,global_ny) :: g_vegtyp\n    integer,          dimension(global_nx,global_ny) :: g_soltyp\n\n    call write_io_int(vegtyp, g_vegtyp)\n    call write_io_int(soltyp, g_soltyp)\n\n    if(my_id .eq. IO_id) then\n       call prepare_output_file_seq(outdir, version, igrid, &\n       output_timestep, llanduse, split_output_count, hgrid, &\n       global_nx, global_ny, global_nx, global_ny, xstartpar, ystartpar, iswater,  &\n       mapproj, lat1, lon1, dx, dy, truelat1, truelat2, cen_lon,     &\n       nsoil, nsnow, sldpth, startdate, date, &\n       g_vegtyp, g_soltyp, act_level)\n    end if\n\n    end subroutine prepare_output_file_mpp\n#endif\n\n  subroutine prepare_output_file_seq(outdir, version, igrid, &\n       output_timestep, llanduse, split_output_count, hgrid, &\n       ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar, iswater,  &\n       mapproj, lat1, lon1, dx, dy, truelat1, truelat2, cen_lon,     &\n       nsoil, nsnow, sldpth, startdate, date, &\n       vegtyp, soltyp, act_level)\n    ! To prepare the output file, we create the file, write dimensions and attributes, write the time variable.\n    ! At the end of this routine, the output file is out of define mode.\n    implicit none\n#include <netcdf.inc>\n\n    character(len=*),                         intent(in) :: outdir\n    character(len=*),                         intent(in) :: version\n    integer,                                  intent(in) :: igrid\n    integer,                                  intent(in) :: output_timestep\n    character(len=*),                         intent(in) :: llanduse\n    integer,                                  intent(in) :: split_output_count\n    character,                                intent(in) :: hgrid\n    integer,                                  intent(in) :: ixfull\n    integer,                                  intent(in) :: jxfull\n    integer,                                  intent(in) :: ixpar\n    integer,                                  intent(in) :: jxpar\n    integer,                                  intent(in) :: xstartpar\n    integer,                                  intent(in) :: ystartpar\n    integer,                                  intent(in) :: iswater\n    integer,                                  intent(in) :: mapproj\n    real,                                     intent(in) :: lat1\n    real,                                     intent(in) :: lon1\n    real,                                     intent(in) :: dx\n    real,                                     intent(in) :: dy\n    real,                                     intent(in) :: truelat1\n    real,                                     intent(in) :: truelat2\n    real,                                     intent(in) :: cen_lon\n    integer,                                  intent(in) :: nsoil\n    integer,                                  intent(in) :: nsnow\n    integer,          optional,               intent(in) :: act_level\n    real,             dimension(nsoil),       intent(in) :: sldpth\n    character(len=19),                        intent(in) :: startdate\n    character(len=19),                        intent(in) :: date\n    integer,          dimension(ixpar,jxpar), intent(in) :: vegtyp\n    integer,          dimension(ixpar,jxpar), intent(in) :: soltyp\n\n    integer :: ncid\n\n    integer :: dimid_ix, dimid_jx, dimid_times, dimid_datelen, varid, n\n    integer :: dimid_dum, dimid_layers, dimid_snow_layers\n    integer :: dimid_glacier_layers\n    integer :: iret\n    character(len=256) :: output_flnm\n    character(len=19)  :: date19\n    integer :: sec_valid_date ! Seconds since the beginning of the model run\n    character(len=34)  :: date340\n\n    integer :: ierr\n\n    if (output_count_remember == 0) then\n       ! If this is a new output file:\n       !   We have to create a new file, do dimension initializations, and write global attributes to the file.\n       !   Then we get out of define mode.\n       if (mod(output_timestep,3600) == 0) then\n\t  ! LK - Temp for NWC IOC\n          write(output_flnm, '(A,\"/\",A12,\".LDASOUT_DOMAIN\",I1)') outdir, date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n       elseif (mod(output_timestep,60) == 0) then\n          write(output_flnm, '(A,\"/\",A12,\".LDASOUT_DOMAIN\",I1)') outdir, date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n       else\n          write(output_flnm, '(A,\"/\",A14,\".LDASOUT_DOMAIN\",I1)') outdir, date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16)//date(18:19), igrid\n       endif\n#ifdef _PARALLEL_\n       iret = nf90_create(trim(output_flnm), &\n            OR(NF90_CLOBBER, NF90_NETCDF4), ncid, comm=HYDRO_COMM_WORLD, info=MPI_INFO_NULL)\n#else\n       iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n#endif\n       call error_handler(iret, failure=\"Problem nf90_create for \"//trim(output_flnm))\n\n       ncid_remember = ncid\n       define_mode_remember = .TRUE.\n\n       iret = nf90_def_dim(ncid, \"time\", NF90_UNLIMITED, dimid_times)\n       !iret = nf90_def_dim(ncid, \"DateStrLen\", 19, dimid_datelen)\n       ! Dimensions reflect the full size of the subwindow (not the strip known by this particular process).\n       iret = nf90_def_dim(ncid, \"west_east\", ixfull, dimid_ix)\n       iret = nf90_def_dim(ncid, \"south_north\", jxfull, dimid_jx)\n       !iret = nf90_def_dim(ncid, \"west_east_stag\", ixfull+1, dimid_dum)\n       !iret = nf90_def_dim(ncid, \"south_north_stag\", jxfull+1, dimid_dum)\n       iret = nf90_def_dim(ncid, \"soil_layers_stag\", nsoil, dimid_layers)\n       iret = nf90_def_dim(ncid, \"snow_layers\", nsnow, dimid_snow_layers)\n       if (crocus_opt /= 0) &\n            iret = nf90_def_dim(ncid, \"glacier_levels\", act_level, dimid_glacier_layers)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"TITLE\", \"OUTPUT FROM HRLDAS \"//version)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -1.E33)\n\n       ! TODO:  Add Grid information   (should look more-or-less like wrfout files)\n       ! TODO:  Add Units information  (should look more-or-less like wrfout files)\n\n       date19(1:19) = \"0000-00-00_00:00:00\"\n       date19(1:len_trim(startdate)) = startdate\n\n       date340(1:34) = \"seconds since \" // trim(startdate(1:10)) // \" \" // trim(startdate(12:16)) // \" UTC\"\n       call geth_idts(trim(date),trim(startdate),sec_valid_date)\n\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", mapproj)\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"LAT1\", lat1)\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"LON1\", lon1)\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"DX\", dx)\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"DY\", dy)\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"STAND_LON\", cen_lon)\n       !iret = nf90_put_att(ncid, NF90_GLOBAL, \"MMINLU\", llanduse)\n\n!\n! Done with dimensions and global attributes.\n! Now define and describe our \"Times\" variable.\n!\n\n       iret = nf90_def_var(ncid, \"time\", NF90_INT, (/dimid_times/), varid)\n       call error_handler(iret, failure=\"In module_hrldas_netcdf_io.F prepare_output_file_seq()\"// &\n                                        \" - Problem nf90_def_var for \"//trim(output_flnm))\n       iret = nf90_put_att(ncid, varid, \"long_name\", \"valid output time\")\n       call error_handler(iret, failure=\"In module_hrldas_netcdf_io.F prepare_output_file_seq()\"// &\n                                        \" - Problem nf90_put_var for \"//trim(output_flnm))\n       iret = nf90_put_att(ncid, varid, \"units\", trim(date340))\n       call error_handler(iret, failure=\"In module_hrldas_netcdf_io.F prepare_output_file_seq()\"// &\n                                        \" - Problem nf90_put_var for \"//trim(output_flnm))\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(startdate))\n       call error_handler(iret, failure=\"In module_hrldas_netcdf_io.F prepare_output_file_seq()\"// &\n                                        \" - Problem nf90_put_var for \"//trim(output_flnm))\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(date))\n       call error_handler(iret, failure=\"In module_hrldas_netcdf_io.F prepare_output_file_seq()\"// &\n                                        \" - Problem nf90_put_var for \"//trim(output_flnm))\n\n       iret = nf90_enddef(ncid)\n       call error_handler(iret, failure=\"In module_hrldas_netcdf_io.F prepare_output_file_seq()\"// &\n                                        \" - Problem nf90_enddef\")\n       define_mode_remember = .FALSE.\n\n    endif\n    xstartpar_remember = xstartpar\n    dimid_ix_remember = dimid_ix\n    dimid_jx_remember = dimid_jx\n    dimid_times_remember = dimid_times\n    dimid_layers_remember = dimid_layers\n    dimid_snow_layers_remember = dimid_snow_layers\n    if (crocus_opt /= 0) &\n         dimid_glacier_layers_remember = dimid_glacier_layers\n    iswater_remember = iswater\n\n    allocate(vegtyp_remember(ixpar,jxpar))\n    vegtyp_remember = vegtyp\n\n!\n! While we're here, put the data for the \"Times\" variable to the NetCDF file.\n!\n\n    date19(1:19) = \"0000-00-00_00:00:00\"\n    date19(1:len_trim(date)) = date\n    iret = nf90_inq_varid(ncid_remember, \"time\", varid)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F prepare_output_file_seq()\"// &\n                             \" - Problem inquiring on 'Times'\")\n\n    iret = nf90_put_var(ncid_remember, varid, sec_valid_date)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F prepare_output_file_seq()\"// &\n                             \" - Problem writing variable 'Times'\")\n\n  end subroutine prepare_output_file_seq\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine set_output_define_mode(imode)\n    implicit none\n    integer, intent(in) :: imode\n    integer :: ierr\n\n#ifdef MPP_LAND\n    if(my_id .ne. IO_id) return\n#endif\n\n    if (imode == 1) then\n       ! We need to define things only with a new file, i.e., only when output_count_remember == 0\n       if (output_count_remember > 0) return\n       ierr = nf90_redef(ncid_remember)\n       call error_handler(ierr, failure=\"In module_hrldas_netcdf_io.F \"// &\n            \"prepare_output_file_seq() - Problem nf90_redef\")\n       define_mode_remember = .TRUE.\n    else\n       if (define_mode_remember) then\n          ierr = nf90_enddef(ncid_remember)\n          call error_handler(ierr, failure=\"In module_hrldas_netcdf_io.F \"// &\n               \"prepare_output_file_seq() - Problem nf90_enddef\")\n          define_mode_remember = .FALSE.\n       endif\n    endif\n\n  end subroutine set_output_define_mode\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine finalize_output_file(split_output_count)\n    implicit none\n    integer, intent(in)  :: split_output_count\n    integer :: ierr\n\n#ifdef MPP_LAND\n    if(my_id .ne. IO_id) return\n#endif\n\n    output_count_remember = output_count_remember + 1\n    if (output_count_remember == split_output_count) then\n       output_count_remember = 0\n       ierr = nf90_close(ncid_remember)\n       call error_handler(ierr, failure=\"In module_hrldas_netcdf_io.F \"// &\n            \"prepare_output_file_seq() - Problem nf90_close for output file\")\n    else\n       ierr = nf90_sync(ncid_remember)\n       call error_handler(ierr, failure=\"In module_hrldas_netcdf_io.F \"// &\n            \"prepare_output_file_seq() - Problem nf90_sync for output file\")\n    endif\n\n!yw    deallocate(vegtyp_remember)\n    if(allocated(vegtyp_remember)) deallocate(vegtyp_remember)\n  end subroutine finalize_output_file\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n#ifdef MPP_LAND\n  subroutine add_to_output_2d_float_mpp ( array, name, description, units, varlist )\n    implicit none\n    real, dimension(:,:), intent(in) :: array\n    real, dimension(global_nx,global_ny) :: garray\n    character(len=*), intent(in) :: name, description, units\n    character(len=15), dimension(30), optional :: varlist\n    character(len=15) :: namestretch\n    logical :: vartest\n    if (present(varlist)) then\n\tnamestretch = name\n\tvartest = ANY(varlist .eq. namestretch)\n    else\n\tvartest = .TRUE.\n    endif\n    if ( vartest ) then\n    \tcall write_io_real(array,garray)\n    \tif(my_id .eq. io_id) then\n        \t call add_to_output_2d_float( garray, name, description, units, varlist )\n    \tendif\n    endif\n  end subroutine add_to_output_2d_float_mpp\n\n  subroutine add_to_output_2d_integer_mpp ( array, name, description, units, varlist )\n    implicit none\n    integer, dimension(:,:), intent(in) :: array\n    character(len=*), intent(in) :: name, description, units\n    integer, dimension(global_nx,global_ny) :: garray\n    character(len=15), dimension(30), optional :: varlist\n    character(len=15) :: namestretch\n    logical :: vartest\n    if (present(varlist)) then\n        namestretch = name\n        vartest = ANY(varlist .eq. namestretch)\n    else\n        vartest = .TRUE.\n    endif\n    if ( vartest ) then\n    \tcall write_io_int(array,garray)\n    \tif(my_id .eq. io_id) then\n        \t call add_to_output_2d_integer( garray, name, description, units, varlist )\n\tendif\n    endif\n  end subroutine add_to_output_2d_integer_mpp\n\n  subroutine add_to_output_3d_mpp ( array, name, description, units, snow_or_soil, varlist )\n    implicit none\n    real, dimension(:,:,:), intent(in) :: array\n    character(len=*), intent(in) :: name, description, units\n    character(len=4), intent(in) :: snow_or_soil\n    integer :: k, klevel\n    real, allocatable, dimension(:,:,:) :: garray\n    character(len=15), dimension(30), optional :: varlist\n    character(len=15) :: namestretch\n    logical :: vartest\n    if (present(varlist)) then\n        namestretch = name\n        vartest = ANY(varlist .eq. namestretch)\n    else\n        vartest = .TRUE.\n    endif\n    if ( vartest ) then\n\tklevel = size(array,2)\n    \tallocate(garray(global_nx,klevel,global_ny))\n    \tcall write_io_real3d(array,garray,klevel)\n    \tif(my_id .eq. io_id) then\n       \t\tcall add_to_output_3d( garray, name, description, units, snow_or_soil )\n    \tendif\n    \tdeallocate(garray)\n    endif\n  end subroutine add_to_output_3d_mpp\n#endif\n\n  subroutine add_to_output_2d_float ( array, name, description, units, varlist )\n    implicit none\n    real, dimension(:,:), intent(in) :: array\n    character(len=*), intent(in) :: name, description, units\n    integer :: ixpar, jxpar\n    character(len=15), dimension(30), optional :: varlist\n    character(len=15) :: namestretch\n    logical :: vartest\n    if (present(varlist)) then\n        namestretch = name\n        vartest = ANY(varlist .eq. namestretch)\n    else\n        vartest = .TRUE.\n    endif\n    if ( vartest ) then\n    \tif (define_mode_remember) then\n       \t\tcall make_var_att_2d ( ncid_remember , dimid_ix_remember , dimid_jx_remember , dimid_times_remember , &\n            \t\tNF90_FLOAT , trim(name) , trim(description) , trim(units) )\n    \telse\n       \t\tixpar = size(array,1)\n       \t\tjxpar = size(array,2)\n       \t\tcall put_var_2d (ncid_remember , output_count_remember+1 , vegtyp_remember , iswater_remember , &\n            \t\tixpar , jxpar , xstartpar_remember , trim(name) , array, .false. )\n    \tendif\n    endif\n  end subroutine add_to_output_2d_float\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine add_to_output_2d_integer ( array, name, description, units, varlist )\n    implicit none\n    integer, dimension(:,:), intent(in) :: array\n    character(len=*), intent(in) :: name, description, units\n    integer :: ixpar, jxpar\n    character(len=15), dimension(30), optional :: varlist\n    character(len=15) :: namestretch\n    logical :: vartest\n    if (present(varlist)) then\n        namestretch = name\n        vartest = ANY(varlist .eq. namestretch)\n    else\n        vartest = .TRUE.\n    endif\n    if ( vartest ) then\n    \tif (define_mode_remember) then\n       \t\tcall make_var_att_2d ( ncid_remember , dimid_ix_remember , dimid_jx_remember , dimid_times_remember , &\n            \t\tNF90_INT , trim(name) , trim(description) , trim(units) )\n    \telse\n       \t\tixpar = size(array,1)\n       \t\tjxpar = size(array,2)\n       \t\tcall put_var_int (ncid_remember , output_count_remember+1 , vegtyp_remember , iswater_remember , &\n            \t\tixpar , jxpar , xstartpar_remember , trim(name) , array )\n    \tendif\n    endif\n  end subroutine add_to_output_2d_integer\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine add_to_output_3d ( array, name, description, units, snow_or_soil, varlist )\n    implicit none\n    real, dimension(:,:,:), intent(in) :: array\n    character(len=*), intent(in) :: name, description, units\n    character(len=4), intent(in) :: snow_or_soil\n    integer :: ixpar, jxpar, kxpar\n    integer :: zdimid\n    character(len=15), dimension(30), optional :: varlist\n    character(len=15) :: namestretch\n    logical :: vartest\n    if (present(varlist)) then\n        namestretch = name\n        vartest = ANY(varlist .eq. namestretch)\n    else\n        vartest = .TRUE.\n    endif\n    if ( vartest ) then\n    \tif (define_mode_remember) then\n       \t\tif (snow_or_soil == \"SOIL\") then\n          \t\tzdimid = dimid_layers_remember\n       \t\telseif (snow_or_soil == \"SNOW\") then\n          \t\tzdimid = dimid_snow_layers_remember\n                elseif (snow_or_soil == \"MAXS\") then\n                        zdimid = dimid_glacier_layers_remember\n       \t\telse\n          \t\twrite(*,'(\"SNOW_OR_SOIL unrecognized: \", A)') adjustl(trim(snow_or_soil))\n          stop \"FATAL ERROR: In module_hrldas_netcdf_io.F add_to_output_3d() - SNOW_OR_SOIL\"\n       \t\tendif\n       \t\tcall make_var_att_3d ( ncid_remember , dimid_ix_remember , dimid_jx_remember , dimid_times_remember , &\n            \t\tNF90_FLOAT , zdimid, trim(name) , trim(description) , trim(units) )\n    \telse\n       \t\tixpar = size(array,1)\n       \t\tkxpar = size(array,2)\n       \t\tjxpar = size(array,3)\n       \t\tcall put_var_3d (ncid_remember , output_count_remember+1 , vegtyp_remember , iswater_remember , &\n            \t\tixpar , jxpar , xstartpar_remember , kxpar, trim(name) , array )\n    \tendif\n    endif\n  end subroutine add_to_output_3d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine make_var_att_2d(ncid, dimid_ix, dimid_jx, dimid_times, itype, varname, vardesc, varunits)\n    implicit none\n    integer,          intent(in) :: ncid\n    character(len=*), intent(in) :: varname\n    character(len=*), intent(in) :: vardesc\n    character(len=*), intent(in) :: varunits\n    integer,          intent(in) :: dimid_ix\n    integer,          intent(in) :: dimid_jx\n    integer,          intent(in) :: dimid_times\n    integer,          intent(in) :: itype\n    integer :: iret\n    integer :: varid\n\n    iret = nf90_def_var(ncid,  varname,   itype, (/dimid_ix,dimid_jx,dimid_times/), varid)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F make_var_att_2d() - \"// &\n         \"Failure defining variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"MemoryOrder\", \"XY \")\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F make_var_att_2d() - \"// &\n         \"Failure adding MemoryOrder attribute to variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"description\", vardesc)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F make_var_att_2d() - \"// &\n         \"Failure adding description attribute to variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"units\", varunits)\n    call error_handler(iret, \"MAKE_VAR_ATT_2D: Failure adding units attribute '\"//trim(varunits)//\"' to variable \"//trim(varname))\n\n    !iret = nf90_put_att(ncid, varid, \"stagger\", \"-\")\n    !call error_handler(iret, \"MAKE_VAR_ATT_2D: Failure adding stagger attribute to variable \"//trim(varname))\n\n  end subroutine make_var_att_2d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine make_var_att_3d(ncid, dimid_ix, dimid_jx, dimid_times, itype, dimid_layers, varname, vardesc, varunits)\n    implicit none\n    integer,          intent(in) :: ncid\n    character(len=*), intent(in) :: varname\n    character(len=*), intent(in) :: vardesc\n    character(len=*), intent(in) :: varunits\n    integer,          intent(in) :: dimid_ix\n    integer,          intent(in) :: dimid_jx\n    integer,          intent(in) :: dimid_times\n    integer,          intent(in) :: dimid_layers\n    integer,          intent(in) :: itype\n    integer :: iret\n    integer :: varid\n\n    iret = nf90_def_var(ncid,  varname, itype, (/dimid_ix,dimid_layers,dimid_jx,dimid_times/), varid)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F make_var_att_3d() - \"// &\n         \"Failure defining variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"MemoryOrder\", \"XZY\")\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F make_var_att_3d() - \"// &\n         \"Failure adding MemoryOrder attribute for variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"description\", vardesc)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F make_var_att_3d() - \"// &\n         \"Failure adding description attribute to variable \"//trim(varname))\n\n    iret = nf90_put_att(ncid, varid, \"units\", varunits)\n    call error_handler(iret, \"MAKE_VAR_ATT_3D: Failure adding units attribute '\"//trim(varunits)//\"' to variable \"//trim(varname))\n\n    !iret = nf90_put_att(ncid, varid, \"stagger\", \"Z\")\n    !call error_handler(iret, \"MAKE_VAR_ATT_3D: Failure adding stagger attribute to variable \"//trim(varname))\n\n  end subroutine make_var_att_3d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine put_var_2d(ncid, output_count, vegtyp, iswater, ix, jx, xstart, varname, vardata, restart_flag)\n    implicit none\n    integer,                   intent(in) :: ncid\n    integer,                   intent(in) :: output_count\n    character(len=*),          intent(in) :: varname\n    integer,                   intent(in) :: ix\n    integer,                   intent(in) :: jx\n    integer,                   intent(in) :: xstart\n    integer, dimension(ix,jx), intent(in) :: vegtyp\n    integer,                   intent(in) :: iswater\n    real,    dimension(ix,jx), intent(in) :: vardata\n    logical,                   intent(in) :: restart_flag\n\n    real,    dimension(ix,jx)             :: xdum\n    integer                               :: iret\n    integer                               :: varid\n\n    integer, dimension(3) :: nstart\n    integer, dimension(3) :: ncount\n\n    where (vegtyp == ISWATER .and. .not. restart_flag)\n       xdum = -1.E33\n    elsewhere\n       xdum = vardata\n    endwhere\n\n    iret = nf90_inq_varid(ncid,  varname, varid)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F put_var_2d() - \"// &\n         \"Problem finding variable id for \"//trim(varname)//\".\")\n\n    nstart = (/ xstart ,  1 , output_count /)\n    ncount = (/     ix , jx ,            1 /)\n\n    iret = nf90_put_var(ncid, varid, xdum, start=nstart, count=ncount)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F put_var_2d() - \"// &\n         \"Problem putting variable \"//trim(varname)//\" to NetCDF file.\")\n\n  end subroutine put_var_2d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine put_var_int(ncid, output_count, vegtyp, iswater, ix, jx, xstart, varname, vardata)\n    implicit none\n    integer,                                              intent(in) :: ncid\n    integer,                                              intent(in) :: output_count\n    character(len=*),                                     intent(in) :: varname\n    integer,                                              intent(in) :: ix\n    integer,                                              intent(in) :: jx\n    integer,                                              intent(in) :: xstart\n    integer,                                              intent(in) :: iswater\n    integer, dimension(ix,jx),                            intent(in) :: vegtyp\n    integer, dimension(ix,jx),                            intent(in) :: vardata\n\n    integer                                                          :: iret\n    integer                                                          :: varid\n\n    integer, dimension(3)                                            :: nstart\n    integer, dimension(3)                                            :: ncount\n\n    nstart = (/ xstart ,  1 , output_count /)\n    ncount = (/     ix , jx ,            1 /)\n\n    iret = nf90_inq_varid(ncid,  varname, varid)\n    call error_handler(iret, failure=\"Subroutine PUT_VAR_INT:  Problem finding variable id for variable: \"//varname)\n\n    iret = nf90_put_var(ncid, varid, vardata, nstart, ncount)\n    call error_handler(iret, failure=\"Subroutine PUT_VAR_INT:  Problem putting variable '\"//varname//\"' to NetCDF file.\")\n\n  end subroutine put_var_int\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine put_var_3d(ncid, output_count, vegtyp, iswater, ix, jx, xstart, nsoil, varname, vardata)\n    implicit none\n    integer,                                                    intent(in) :: ncid\n    integer,                                                    intent(in) :: output_count\n    character(len=*),                                           intent(in) :: varname\n    integer,                                                    intent(in) :: ix\n    integer,                                                    intent(in) :: jx\n    integer,                                                    intent(in) :: xstart\n    integer,                                                    intent(in) :: nsoil\n    integer,                                                    intent(in) :: iswater\n    integer, dimension(ix, jx),                                 intent(in) :: vegtyp\n    real,    dimension(ix, nsoil, jx),                          intent(in) :: vardata\n    real,    dimension(ix, nsoil, jx)                                      :: xdum\n    integer                                                                :: iret\n    integer                                                                :: varid\n    integer                                                                :: n\n    integer, dimension(4)                                                  :: nstart\n    integer, dimension(4)                                                  :: ncount\n\n    nstart = (/ xstart ,  1 ,     1 , output_count /)\n    ncount = (/     ix , nsoil , jx ,            1 /)\n\n    xdum = vardata\n    do n = 1, nsoil\n       where (vegtyp(:,:) == ISWATER) xdum(:,n,:) = -1.E33\n    enddo\n\n    iret = nf90_inq_varid(ncid,  varname, varid)\n    call error_handler(iret, \"In module_hrldas_netcdf_io.F put_var_3d() - \"// &\n         \"Problem finding variable id for \"//trim(varname)//\".\")\n\n    iret = nf90_put_var(ncid, varid, xdum, start=nstart, count=ncount)\n    call error_handler(iret,  \"In module_hrldas_netcdf_io.F put_var_3d() - \"// &\n         \"Problem putting variable \"//trim(varname)//\" to NetCDF file.\")\n\n  end subroutine put_var_3d\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n  subroutine finalize_restart_file()\n    implicit none\n\n    !yw  deallocate(vegtyp_remember)\n    if(allocated(vegtyp_remember)) deallocate(vegtyp_remember)\n    restart_filename_remember = \" \"\n    iswater_remember   = -999999\n    xstartpar_remember = -999999\n\n  end subroutine finalize_restart_file\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n#ifdef MPP_LAND\n      subroutine prepare_restart_file_mpp(outdir, version, igrid, llanduse, olddate, startdate,  &\n           ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar,                                   &\n           nsoil, nsnow, dx, dy, truelat1, truelat2, mapproj,                                    &\n           lat1, lon1, cen_lon, iswater, vegtyp, glacinfo,                                       &\n           glact, act_level, vis_icealb)\n\n\n    implicit none\n\n    character(len=*),                      intent(in) :: outdir\n    character(len=*),                      intent(in) :: version\n    integer,                               intent(in) :: igrid\n    character(len=*),                      intent(in) :: llanduse\n    character(len=*),                      intent(in) :: olddate\n    character(len=*),                      intent(in) :: startdate\n    integer,                               intent(in) :: ixfull\n    integer,                               intent(in) :: jxfull\n    integer,                               intent(in) :: ixpar\n    integer,                               intent(in) :: jxpar\n    integer,                               intent(in) :: xstartpar\n    integer,                               intent(in) :: ystartpar\n    integer,                               intent(in) :: nsoil\n    integer,                               intent(in) :: nsnow\n    integer, optional,                     intent(in) :: act_level\n    real,                                  intent(in) :: dx, dy\n    real,                                  intent(in) :: truelat1, truelat2\n    integer,                               intent(in) :: mapproj\n    real,                                  intent(in) :: lat1, lon1, cen_lon\n    integer,                               intent(in) :: iswater\n    integer, dimension(ixpar,jxpar),       intent(in) :: vegtyp\n    integer, dimension(global_nx,global_ny) :: gvegtyp\n    ! the following three vars have ixpar, jxpar bounds\n    integer, dimension(:,:), allocatable, intent(in) :: glacinfo\n    real,    dimension(:,:), allocatable, intent(in) :: glact\n    real,    dimension(:,:), allocatable, intent(in) :: vis_icealb\n\n    call write_io_int(vegtyp, gvegtyp)\n    if(my_id .eq. io_id) then\n      call prepare_restart_file_seq(outdir, version, igrid, llanduse, olddate, startdate,  &\n       global_nx, global_ny, global_nx, global_ny, xstartpar, ystartpar,               &\n       nsoil, nsnow, dx, dy, truelat1, truelat2, mapproj, lat1, lon1, cen_lon,         &\n       iswater, gvegtyp, act_level)\n    endif\n\n    call mpp_land_sync()\n\n    end subroutine prepare_restart_file_mpp\n#endif\n\n  subroutine prepare_restart_file_seq(outdir, version, igrid, llanduse, olddate, startdate,  &\n       ixfull, jxfull, ixpar, jxpar, xstartpar, ystartpar,                                    &\n       nsoil, nsnow, dx, dy, truelat1, truelat2, mapproj, lat1, lon1, cen_lon,                       &\n       iswater, vegtyp, act_level)\n    use iso_fortran_env, only : compiler_version\n    implicit none\n#include <netcdf.inc>\n\n    character(len=*),                      intent(in) :: outdir\n    character(len=*),                      intent(in) :: version\n    integer,                               intent(in) :: igrid\n    character(len=*),                      intent(in) :: llanduse\n    character(len=*),                      intent(in) :: olddate\n    character(len=*),                      intent(in) :: startdate\n    integer,                               intent(in) :: ixfull\n    integer,                               intent(in) :: jxfull\n    integer,                               intent(in) :: ixpar\n    integer,                               intent(in) :: jxpar\n    integer,                               intent(in) :: xstartpar\n    integer,                               intent(in) :: ystartpar\n    integer,                               intent(in) :: nsoil\n    integer,                               intent(in) :: nsnow\n    integer, optional,                     intent(in) :: act_level\n    real,                                  intent(in) :: dx, dy\n    real,                                  intent(in) :: truelat1, truelat2\n    integer,                               intent(in) :: mapproj\n    real,                                  intent(in) :: lat1, lon1, cen_lon\n    integer,                               intent(in) :: iswater\n    integer, dimension(ixpar,jxpar),       intent(in) :: vegtyp\n\n    character(len=1) :: hgrid\n    integer :: ncid\n    character(len=256) :: output_flnm\n    integer :: ierr\n    integer :: varid\n    integer :: dimid_times, dimid_datelen, dimid_ix, dimid_jx, dimid_dum, dimid_layers, dimid_snow_layers, dimid_sosn_layers\n    integer :: dimid_glacier_layers\n    character(len=19) :: date19\n    integer :: rank\n\n#ifdef _PARALLEL_\n\n    call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F\"// &\n                                  \" prepare_restart_file_seq() - MPI_Comm_rank problem\"\n\n#else\n\n    rank = 0\n\n#endif\n\n    write(output_flnm, '(A,\"/RESTART.\",A10,\"_DOMAIN\",I1)') trim(outdir), olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13), igrid\n    if (rank==0) then\n#ifdef HYDRO_D\n      print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n    endif\n\n    restart_filename_remember = output_flnm\n    iswater_remember   = iswater\n    xstartpar_remember = xstartpar\n    allocate(vegtyp_remember(ixpar,jxpar))\n    vegtyp_remember = vegtyp\n\n#ifdef _PARALLEL_\n\n    ierr = nf90_create(trim(output_flnm), &\n         OR(NF90_CLOBBER, NF90_NETCDF4), ncid, comm=HYDRO_COMM_WORLD, info=MPI_INFO_NULL)\n#else\n    ierr = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n#endif\n\n    if (ierr /= 0) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F\"// &\n                       \" prepare_restart_file_seq() - Problem nf90_create\"\n\n    ierr = nf90_def_dim(ncid, \"Time\", NF90_UNLIMITED, dimid_times)\n    ierr = nf90_def_dim(ncid, \"DateStrLen\", 19, dimid_datelen)\n    ierr = nf90_def_dim(ncid, \"west_east\", ixfull, dimid_ix)\n    ierr = nf90_def_dim(ncid, \"south_north\", jxfull, dimid_jx)\n    ierr = nf90_def_dim(ncid, \"west_east_stag\", ixfull+1, dimid_dum)\n    ierr = nf90_def_dim(ncid, \"south_north_stag\", jxfull+1, dimid_dum)\n    ierr = nf90_def_dim(ncid, \"soil_layers_stag\", nsoil, dimid_layers)\n    ierr = nf90_def_dim(ncid, \"snow_layers\", nsnow, dimid_snow_layers)\n    ierr = nf90_def_dim(ncid, \"sosn_layers\", nsnow+nsoil, dimid_sosn_layers)\n    if (crocus_opt /= 0) &\n         ierr = nf90_def_dim(ncid, \"glacier_levels\", act_level, dimid_glacier_layers)\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TITLE\", \"RESTART FILE FROM HRLDAS \"//version)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"compiler_version\", compiler_version())\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -1.E33)\n\n    date19(1:19) = \"0000-00-00_00:00:00\"\n    date19(1:len_trim(startdate)) = startdate\n\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"START_DATE\", date19)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"MAP_PROJ\", mapproj)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LAT1\", lat1)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"LON1\", lon1)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"DX\", dx)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"DY\", dy)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT1\", truelat1)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"TRUELAT2\", truelat2)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"STAND_LON\", cen_lon)\n    ierr = nf90_put_att(ncid, NF90_GLOBAL, \"MMINLU\", llanduse)\n\n!\n! Done with dimensions and global attributes.\n! Now define and describe all our NetCDF restart variables.\n!\n\n    ierr = nf90_def_var(ncid,  \"Times\",  NF90_CHAR, (/dimid_datelen,dimid_times/), varid)\n    ierr = nf90_enddef(ncid)\n\n!\n! Done defining and describing all our NetCDF restart variables.\n! Now actually put the data for each variable into the NetCDF file.\n!\n\n    date19(1:19) = \"0000-00-00_00:00:00\"\n    date19(1:len_trim(olddate)) = olddate\n\n    ierr = nf90_inq_varid(ncid, \"Times\", varid)\n    call error_handler(ierr, \"In module_hrldas_netcdf_io.F prepare_restart_file_seq\"// &\n                             \" - Problem inquiring varid for 'Times'\")\n\n!    write(6,*) \"yywww olddate  = \", olddate\n!    write(6,*) \"yywww output_count_remember  = \", output_count_remember\n\n    ierr = nf90_put_var(ncid, varid, olddate, (/1,1/), (/19,1/))\n    call error_handler(ierr, \"WRITE_RESTART:  problem putting 'Times' to restart file\")\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"WRITE_RESTART:  nf90_close\")\n\n  end subroutine prepare_restart_file_seq\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n#ifdef MPP_LAND\n  subroutine add_to_restart_2d_float_mpp(ncid,array, name, units, description)\n    implicit none\n    real,            dimension(:,:),                              intent(in) :: array\n    real,            dimension(global_nx,global_ny) :: garray\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n    integer :: ncid\n    call write_io_real(array,garray)\n    if(my_id .eq. IO_id) then\n         call add_to_restart_2d_float(ncid,garray, name, units, description)\n    endif\n    call mpp_land_sync()\n  end subroutine add_to_restart_2d_float_mpp\n\n  subroutine add_to_restart_2d_integer_mpp(ncid,array, name, units, description)\n    implicit none\n    integer,            dimension(:,:),                              intent(in) :: array\n    integer,            dimension(global_nx,global_ny) :: garray\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n    integer :: ncid\n    call write_io_int(array,garray)\n    if(my_id .eq. IO_id) then\n         call add_to_restart_2d_integer(ncid,garray, name, units, description)\n    endif\n    call mpp_land_sync()\n  end subroutine add_to_restart_2d_integer_mpp\n\n  subroutine add_to_restart_3d_mpp(ncid,array, name, units, description, layers)\n    implicit none\n    real,            dimension(:,:,:),                            intent(in) :: array\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n    character(len=4), optional,                                   intent(in) :: layers\n    integer  :: k, klevel\n    integer :: ncid\n\n    real, allocatable, dimension(:,:,:) :: garray\n    klevel = size(array,2)\n    allocate(garray(global_nx,klevel,global_ny))\n\n       call write_io_real3d(array,garray,klevel)\n\n    if(my_id .eq. IO_id) then\n         call add_to_restart_3d(ncid,garray, name, units, description, layers)\n    endif\n    deallocate(garray)\n\n    call mpp_land_sync()\n  end subroutine add_to_restart_3d_mpp\n\n\n#endif\n\n  subroutine add_to_restart_2d_float(ncid,array, name, units, description)\n    implicit none\n    real,            dimension(:,:),                              intent(in) :: array\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n\n    character(len=256) :: output_flnm\n    integer :: ncid\n    integer :: ierr\n    integer :: dimid_ix\n    integer :: dimid_jx\n    integer :: dimid_times\n    integer :: ixout\n    integer :: xstartout\n    integer :: iswater\n    character(len=256) :: local_units\n    character(len=256) :: local_description\n\n    integer :: ixpar\n    integer :: jxpar\n\n    output_flnm = restart_filename_remember\n    iswater     = iswater_remember\n\n    ixpar = size(array,1)\n    jxpar = size(array,2)\n\n    if (present(units)) then\n       local_units = units\n    else\n       local_units = \"-\"\n    endif\n\n    if (present(description)) then\n       local_description = description\n    else\n       local_description = \"-\"\n    endif\n\n    call put_var_2d(ncid, 1, vegtyp_remember, iswater, ixpar, jxpar, xstartpar_remember, name, array, .true.)\n\n  end subroutine add_to_restart_2d_float\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine add_to_restart_2d_integer(ncid,array, name, units, description)\n    implicit none\n    integer,         dimension(:,:),                              intent(in) :: array\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n\n    character(len=256) :: output_flnm\n    integer :: ncid\n    integer :: ierr\n    integer :: dimid_ix\n    integer :: dimid_jx\n    integer :: dimid_times\n    integer :: ixout\n    integer :: xstartout\n    integer :: iswater\n    character(len=256) :: local_units\n    character(len=256) :: local_description\n\n    integer :: ixpar\n    integer :: jxpar\n\n    output_flnm = restart_filename_remember\n    iswater     = iswater_remember\n\n    ixpar = size(array,1)\n    jxpar = size(array,2)\n\n    if (present(units)) then\n       local_units = units\n    else\n       local_units = \"-\"\n    endif\n\n    if (present(description)) then\n       local_description = description\n    else\n       local_description = \"-\"\n    endif\n\n     call put_var_int(ncid, 1, vegtyp_remember, iswater, ixpar, jxpar, xstartpar_remember, name, array)\n\n\n  end subroutine add_to_restart_2d_integer\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine add_to_restart_3d(ncid,array, name, units, description, layers)\n    implicit none\n    real,            dimension(:,:,:),                            intent(in) :: array\n    character(len=*),                                             intent(in) :: name\n    character(len=*), optional,                                   intent(in) :: units\n    character(len=*), optional,                                   intent(in) :: description\n    character(len=4), optional,                                   intent(in) :: layers\n\n    character(len=256) :: output_flnm\n    integer :: ncid\n    integer :: ierr\n    integer :: dimid_ix\n    integer :: dimid_jx\n    integer :: dimid_kx\n    integer :: dimid_times\n    integer :: ixout\n    integer :: xstartout\n    integer :: iswater\n    character(len=256) :: local_units\n    character(len=256) :: local_description\n\n    integer :: ixpar\n    integer :: jxpar\n    integer :: kxpar\n    character(len=4) :: output_layers\n\n    output_flnm = restart_filename_remember\n    iswater     = iswater_remember\n\n    if (present(layers)) then\n       output_layers = layers\n    else\n       output_layers = \"SOIL\"\n    endif\n\n    ixpar = size(array,1)\n    kxpar = size(array,2)\n    jxpar = size(array,3)\n\n    call put_var_3d(ncid, 1, vegtyp_remember, iswater, ixpar, jxpar, xstartpar_remember, kxpar, name, array)\n\n\n  end subroutine add_to_restart_3d\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine read_restart(restart_flnm,  &\n       parallel_xstart, parallel_xend, subwindow_xstart, ix, jx, nsoil,    &\n       olddate)\n\n    ! The restart file is dimensioned by our (possibly subwindowed) grid.  Our indices\n    ! for the parallel I/O reflect the dimensions of the (possibly subwindowed) grid,\n    ! but not the full domain for which LDAS input files may be available.\n\n    implicit none\n\n    character(len=*),             intent(in)  :: restart_flnm\n    integer,                      intent(in)  :: parallel_xstart\n    integer,                      intent(in)  :: parallel_xend\n    integer,                      intent(in)  :: subwindow_xstart\n    integer,                      intent(in)  :: ix\n    integer,                      intent(in)  :: jx\n    integer,                      intent(in)  :: nsoil\n    character(len=19),            intent(out) :: olddate\n\n    integer :: ierr\n    integer :: ncid\n    integer :: varid\n    character(len=256) :: titlestr\n    integer :: restart_version\n    integer :: idx\n    integer, dimension(4) :: nstart\n    integer, dimension(4) :: ncount\n    integer :: rank\n    integer :: read_sfcdif\n\n#ifdef MPP_LAND\n     if(my_id .ne. IO_id) return\n#endif\n\n    restart_filename_remember = restart_flnm\n\n#ifdef _PARALLEL_\n    call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F \"// &\n                                  \"read_restart() - MPI_Comm_rank\"\n\n    ierr = nf90_open_par(trim(restart_flnm), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    rank = 0\n    ierr = nf90_open(trim(restart_flnm), NF90_NOWRITE, ncid)\n#endif\n\n    if (ierr == NF90_ENOTNC) then\n#ifdef HYDRO_D\n       print*, \"IERR = NF90_ENOTNC\"\n#endif\n\n    else\n       if (ierr /= NF90_NOERR) then\n          write(*,*)\n          write(*,'(\" ***** Restart problem ***************************************\")')\n          write(*,'(\" ***** \")')\n          write(*,'(\" *****        There was a problem in accessing the file ''\", A, \"''\")') trim(restart_flnm)\n          write(*,'(\" ***** \")')\n       endif\n       call error_handler(ierr, \"FALTAL ERROR: In module_hrldas_netcdf_io.F read_restart() - \"// &\n            \"trying to open restart file \"//restart_flnm)\n\n       ierr = nf90_get_att(ncid, NF90_GLOBAL, \"TITLE\", titlestr)\n       if (ierr /= 0) then\n          write(*,'(\"WARNING:  RESTART file does not have TITLE attribute.\")')\n          write(*,'(\"          This probably means that LDASIN files are from an older release,\")')\n          write(*,'(\"          And are very likely incompatible with the current code.\")')\n          write(*,'(\"          I assume you know what you are doing.\")')\n          restart_version = 0\n       else\n          if (rank == 0) then\n#ifdef HYDRO_D\n                write(*,'(\"RESTART TITLE attribute: \", A)') trim(titlestr)\n#endif\n          endif\n          ! Pull out the version number, assuming that the version is identified by vYYYYMMDD, and\n          ! based on a search for the string \"v20\".\n          idx = index(trim(titlestr), \"v20\")\n          if (idx <= 0) then\n             write(*,'(\"FATAL ERROR:  RESTART file has a perverse version identifier\")')\n             !  write(*,'(\"          I assume you know what you are doing.\")')\n             stop\n          else\n             read(titlestr(idx+1:), '(I8)', iostat=ierr) restart_version\n             if (ierr /= 0) then\n                write(*,'(\"FATAL ERROR:  RESTART file has a perverse version identifier\")')\n                !  write(*,'(\"          I assume you know what you are doing.\")')\n                stop\n             endif\n          endif\n       endif\n\n       ! Get the time stamp from the restart file.\n       ierr = nf90_inq_varid(ncid, \"Times\", varid)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F read_restart() - \"// &\n                                \"Problem finding variable in restart file: 'Times'\")\n\n       ierr = nf90_get_var(ncid, varid, olddate)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F read_restart() - \"// &\n                                \"Problem finding variable in restart file: 'Times'\")\n\n       ierr = nf90_close(ncid)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F read_restart() - \"// &\n                                \"Problem closing restart file\")\n    endif\n\n  end subroutine read_restart\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n#ifdef MPP_LAND\n  subroutine get_from_restart_2d_float_mpp(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                            intent(in) :: parallel_xstart\n    integer,                            intent(in) :: parallel_xend\n    integer,                            intent(in) :: subwindow_xstart\n    integer,                            intent(in) :: ixfull\n    integer,                            intent(in) :: jxfull\n    character(len=*),                   intent(in)  :: name\n    real,             dimension(parallel_xstart:parallel_xend,jxfull), intent(out) :: array\n    real,             dimension(global_nx,global_ny):: garray\n    integer,          optional,         intent(out) :: return_error\n\n    if(checkRstV(name) .ne. 0) return\n\n      if(my_id .eq. IO_id) then\n          call get_from_restart_2d_float(1, global_nx, 1, global_nx, global_ny, name, garray, return_error)\n      endif\n      call decompose_data_real(garray,array)\n  end subroutine get_from_restart_2d_float_mpp\n\n  subroutine get_from_restart_2d_integer_mpp(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                            intent(in) :: parallel_xstart\n    integer,                            intent(in) :: parallel_xend\n    integer,                            intent(in) :: subwindow_xstart\n    integer,                            intent(in) :: ixfull\n    integer,                            intent(in) :: jxfull\n    character(len=*),                   intent(in)  :: name\n    integer,             dimension(parallel_xstart:parallel_xend,jxfull), intent(out) :: array\n    integer,             dimension(global_nx,global_ny):: garray\n    integer,          optional,         intent(out) :: return_error\n\n    if(checkRstV(name) .ne. 0) return\n\n      if(my_id .eq. IO_id) then\n          call get_from_restart_2d_integer(1, global_nx, 1, global_nx, global_ny, name, garray, return_error)\n      endif\n      call decompose_data_int(garray,array)\n  end subroutine get_from_restart_2d_integer_mpp\n\n  subroutine get_from_restart_3d_mpp(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                            intent(in) :: parallel_xstart\n    integer,                            intent(in) :: parallel_xend\n    integer,                            intent(in) :: subwindow_xstart\n    integer,                            intent(in) :: ixfull\n    integer,                            intent(in) :: jxfull\n    character(len=*),                   intent(in)  :: name\n    real,             dimension(:,:,:), intent(out) :: array\n    integer,          optional,         intent(out) :: return_error\n    integer :: klevel,k\n    real, allocatable, dimension(:,:,:) :: garray\n\n    if(checkRstV(name) .ne. 0) return\n\n    klevel = size(array,2)\n    allocate(garray(global_nx,klevel,global_ny))\n\n\n      if(my_id .eq. IO_id) then\n          call get_from_restart_3d(1, global_nx, 1, global_nx, global_ny, name, garray, return_error)\n      endif\n      do k = 1, klevel\n         call decompose_data_real(garray(:,k,:),array(:,k,:))\n      end do\n      deallocate(garray)\n\n  end subroutine get_from_restart_3d_mpp\n#endif\n\n  subroutine get_from_restart_att(itime)\n    implicit none\n    integer,intent(out) :: itime\n    integer  :: ncid, ierr\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n        ierr = nf90_open(trim(restart_filename_remember), NF90_NOWRITE, ncid)\n        ierr = nf90_get_att(ncid, NF90_GLOBAL, \"ITIMESTEP\", itime)\n        call error_handler(ierr, failure=\"In module_hrldas_netcdf_io.F get_from_restart_att - \"// &\n                                         \"Problems finding global attribute 'ITIMESTEP'\")\n         ierr = nf90_close(ncid)\n#ifdef MPP_LAND\n    endif\n#endif\n  end subroutine get_from_restart_att\n\n  subroutine get_from_restart_2d_float(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                            intent(in) :: parallel_xstart\n    integer,                            intent(in) :: parallel_xend\n    integer,                            intent(in) :: subwindow_xstart\n    integer,                            intent(in) :: ixfull\n    integer,                            intent(in) :: jxfull\n    character(len=*),                   intent(in)  :: name\n    real,             dimension(parallel_xstart:parallel_xend,jxfull), intent(out) :: array\n    integer,          optional,         intent(out) :: return_error\n\n    integer :: ierr\n    integer :: ncid\n    integer :: varid\n    integer, dimension(4) :: nstart\n    integer, dimension(4) :: ncount\n    integer :: rank\n\n#ifdef _PARALLEL_\n\n    call MPI_Comm_rank(HYDRO_COMM_WORLD, rank, ierr)\n    if (ierr /= MPI_SUCCESS) stop \"FATAL ERROR: In module_hrldas_netcdf_io.F \"// &\n                                  \"get_from_restart_2d_float() - MPI_Comm_rank\"\n\n    ierr = nf90_open_par(trim(restart_filename_remember), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n\n#else\n    rank = 0\n\n    ierr = nf90_open(trim(restart_filename_remember), NF90_NOWRITE, ncid)\n\n#endif\n    call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_float() - \"// &\n                       \"Problem opening restart file '\"//trim(restart_filename_remember)//\"'\")\n\n    nstart = (/ parallel_xstart-subwindow_xstart+1, 1,  1, -99999 /)\n    ncount = (/ parallel_xend-parallel_xstart+1,   jxfull,  1, -99999 /)\n\n    if (present(return_error)) then\n       ierr = nf90_inq_varid(ncid, name, varid)\n       if (ierr == NF90_NOERR) then\n          return_error = 0\n          call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_float(): Problem finding variable in restart file '\"//trim(name)//\"'\")\n\n          ierr = nf90_get_var(ncid, varid, array, start=nstart(1:3))\n          call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_float(): Problem finding variable in restart file: '\"//trim(name)//\"'\")\n       else\n          return_error = 1\n          if (rank == 0) write(*,'(\"Did not find optional variable ''\",A,\"'' in restart file ''\", A, \"''\")') trim(name), trim(restart_filename_remember)\n       endif\n    else\n       ierr = nf90_inq_varid(ncid, name, varid)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_float(): Problem finding required variable in restart file: '\"//trim(name)//\"'\")\n\n       ierr = nf90_get_var(ncid, varid, array, start=nstart(1:3))\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_float(): Problem finding variable in restart file: '\"//trim(name)//\"'\")\n    endif\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_float(): Problem closing restart file\")\n\n  end subroutine get_from_restart_2d_float\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine get_from_restart_2d_integer(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                                                           intent(in) :: parallel_xstart\n    integer,                                                           intent(in) :: parallel_xend\n    integer,                                                           intent(in) :: subwindow_xstart\n    integer,                                                           intent(in) :: ixfull\n    integer,                                                           intent(in) :: jxfull\n    character(len=*),                                                  intent(in)  :: name\n    integer,          dimension(parallel_xstart:parallel_xend,jxfull), intent(out) :: array\n    integer,          optional,                                        intent(out) :: return_error\n\n    integer :: ierr\n    integer :: ncid\n    integer :: varid\n    integer, dimension(4) :: nstart\n    integer, dimension(4) :: ncount\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(restart_filename_remember), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(restart_filename_remember), NF90_NOWRITE, ncid)\n#endif\n    call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_integer() - \"// &\n                       \"Problem opening restart file '\"//trim(restart_filename_remember)//\"'\")\n\n    nstart = (/ parallel_xstart-subwindow_xstart+1, 1,  1, -99999 /)\n    ncount = (/ parallel_xend-parallel_xstart+1,   jxfull,  1, -99999 /)\n\n    if (present(return_error)) then\n       ierr = nf90_inq_varid(ncid, name, varid)\n       if (ierr == NF90_NOERR) then\n          return_error = 0\n          call error_handler(ierr, \"Problem finding variable in restart file '\"//trim(name)//\"'\")\n\n          ierr = nf90_get_var(ncid, varid, array, start=nstart(1:3))\n          call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_integer()-Problem finding variable in restart file: '\"//trim(name)//\"'\")\n       else\n          return_error = 1\n          write(*,'(\"Did not find optional variable ''\",A,\"'' in restart file ''\", A, \"''\")') trim(name), trim(restart_filename_remember)\n       endif\n    else\n       ierr = nf90_inq_varid(ncid, name, varid)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_integer() - \"// &\n                          \"Problem finding required variable in restart file: '\"//trim(name)//\"'\")\n\n       ierr = nf90_get_var(ncid, varid, array, start=nstart(1:3))\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_integer() - \"// &\n                          \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n    endif\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_2d_integer() - \"// &\n                             \"Problem closing restart file\")\n\n  end subroutine get_from_restart_2d_integer\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine get_from_restart_3d(parallel_xstart, parallel_xend, subwindow_xstart, ixfull, jxfull, name, array, return_error)\n    implicit none\n    integer,                            intent(in) :: parallel_xstart\n    integer,                            intent(in) :: parallel_xend\n    integer,                            intent(in) :: subwindow_xstart\n    integer,                            intent(in) :: ixfull\n    integer,                            intent(in) :: jxfull\n    character(len=*),                   intent(in)  :: name\n    real,             dimension(:,:,:), intent(out) :: array\n    integer,          optional,         intent(out) :: return_error\n\n    integer :: ierr\n    integer :: ncid\n    integer :: varid\n    integer, dimension(4) :: nstart\n    integer, dimension(4) :: ncount\n\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(restart_filename_remember), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(restart_filename_remember), NF90_NOWRITE, ncid)\n#endif\n    call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_3d() - \"// &\n                       \"Problem opening restart file '\"//trim(restart_filename_remember)//\"'\")\n\n    nstart = (/parallel_xstart-subwindow_xstart+1,1, 1, 1/)\n    ncount = (/parallel_xend-parallel_xstart+1, size(array,2), size(array,3), 1/)\n\n    if (present(return_error)) then\n       ierr = nf90_inq_varid(ncid, name, varid)\n       if (ierr == NF90_NOERR) then\n          return_error = 0\n          call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_3d() - \"// &\n                             \"Problem finding variable in restart file '\"//trim(name)//\"'\")\n\n          ierr = nf90_get_var(ncid, varid, array, start=nstart(1:4))\n          call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_3d() - \"// &\n                             \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n       else\n          return_error = 1\n          write(*,'(\"Did not find optional variable ''\",A,\"'' in restart file ''\", A, \"''\")') trim(name), trim(restart_filename_remember)\n       endif\n    else\n       ierr = nf90_inq_varid(ncid, name, varid)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_3d() - \"// &\n                          \"Problem finding required variable in restart file: '\"//trim(name)//\"'\")\n\n       ierr = nf90_get_var(ncid, varid, array, start=nstart(1:4))\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_3d() - \"// &\n                          \"Problem finding variable in restart file: '\"//trim(name)//\"'\")\n    endif\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, \"In module_hrldas_netcdf_io.F get_from_restart_3d() - \"// &\n                       \"Problem closing restart file\")\n\n  end subroutine get_from_restart_3d\n\n!-----------------------------------------------------------------------------------------\n!-----------------------------------------------------------------------------------------\n\n  subroutine error_handler(status, failure, success)\n    !\n    ! Check the error flag from a NetCDF function call, and print appropriate\n    ! error message.\n    !\n    implicit none\n    integer,                    intent(in) :: status\n    character(len=*), optional, intent(in) :: failure\n    character(len=*), optional, intent(in) :: success\n\n    if (status .ne. NF90_NOERR) then\n       write(*,'(/,A)') nf90_strerror(status)\n       if (present(failure)) then\n          write(*,'(/,\" ***** \", A,/)') failure\n       endif\n       stop 'FATAL ERROR: Model stopped'\n    endif\n\n    if (present(success)) then\n#ifdef HYDRO_D\n       write(*,'(A)') success\n#endif\n    endif\n\n  end subroutine error_handler\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n  subroutine read_additional(flnm_template, hdate, name, xstart, xend, ystart, yend, array, ierr)\n    use kwm_string_utilities\n    implicit none\n    character(len=*),                         intent(in)  :: flnm_template\n    character(len=*),                         intent(in)  :: hdate\n    character(len=*),                         intent(in)  :: name\n    integer,                                  intent(in)  :: xstart\n    integer,                                  intent(in)  :: xend\n    integer,                                  intent(in)  :: ystart\n    integer,                                  intent(in)  :: yend\n    real, dimension(xstart:xend,ystart:yend), intent(out) :: array\n    integer,                                  intent(out) :: ierr\n\n    character(len=256) :: flnm\n    integer :: jday\n    character(len=3) :: hjday\n    integer :: ncid\n    integer :: varid\n    logical :: lexist\n\n    call geth_idts(hdate(1:10), hdate(1:4)//\"-01-01\", jday)\n    jday = jday + 1\n    write(hjday,'(I3.3)') jday\n\n    flnm = flnm_template\n\n    call strrep(flnm, \"<YYYY>\", hdate(1:4))\n    call strrep(flnm, \"<MM>\", hdate(6:7))\n    call strrep(flnm, \"<DD>\", hdate(9:10))\n    call strrep(flnm, \"<HH>\", hdate(12:13))\n    call strrep(flnm, \"<JDAY>\", hjday)\n\n    inquire(file=trim(flnm), exist=lexist)\n    if (.not. lexist) then\n       ierr = 1\n       return\n    endif\n\n#ifdef HYDRO_D\n    write(*, '(\"Additional flnm = ''\",A,\"''\")') trim(flnm)\n\n#endif\n#ifdef _PARALLEL_\n    ierr = nf90_open_par(trim(flnm), NF90_NOWRITE, HYDRO_COMM_WORLD, MPI_INFO_NULL, ncid)\n#else\n    ierr = nf90_open(trim(flnm), NF90_NOWRITE, ncid)\n#endif\n    call error_handler(ierr, failure=\"In read_additional() - Problem opening additional file: \"//trim(flnm))\n\n    ierr = nf90_inq_varid(ncid,  name,  varid)\n    call error_handler(ierr, failure=\"In read_additional() - Problem finding variable: \"//name)\n\n    ierr = nf90_get_var(ncid, varid, array, start=(/xstart,ystart/), count=(/xend-xstart+1,yend-ystart+1/))\n    call error_handler(ierr, failure=\"In read_additional() - Problem getting variable: \"//name)\n\n    ierr = nf90_close(ncid)\n    call error_handler(ierr, failure=\"In read_additional() - Problem closing file:  \"//trim(flnm))\n\n  end subroutine read_additional\n\n!---------------------------------------------------------------------------------------------------------\n!---------------------------------------------------------------------------------------------------------\n\n\n   subroutine define_2d_real(ncid, array,name,description, units)\n       implicit none\n       real,         dimension(:,:),                              intent(in) :: array\n       character(len=*),                                             intent(in) :: name\n       character(len=*), optional,                                   intent(in) :: units\n       character(len=*), optional,                                   intent(in) :: description\n       integer :: ierr, ncid, dimid_ix, dimid_jx, dimid_times\n       ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_integer() - \"// &\n                             \"Problem nf90_inq_dimid for 'west_east'\")\n\n       ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_integer() - \"// &\n                             \"Problem nf90_inq_dimid for 'south_north'\")\n\n       ierr = nf90_inq_dimid(ncid, \"Time\", dimid_times)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_3d() - \"// &\n                             \"Problem nf90_inq_dimid for 'Time'\")\n\n       call make_var_att_2d(ncid, dimid_ix, dimid_jx, dimid_times, NF90_FLOAT, name, \"\", \"\")\n   end subroutine define_2d_real\n\n   subroutine define_2d_int(ncid, array,name,description, units)\n       implicit none\n       integer,         dimension(:,:),                              intent(in) :: array\n       character(len=*),                                             intent(in) :: name\n       character(len=*), optional,                                   intent(in) :: units\n       character(len=*), optional,                                   intent(in) :: description\n       integer :: ierr, ncid, dimid_ix, dimid_jx, dimid_times\n\n       ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_integer() - \"// &\n                             \"Problem nf90_inq_dimid for 'west_east'\")\n\n       ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_integer() - \"// &\n                             \"Problem nf90_inq_dimid for 'south_north'\")\n\n       ierr = nf90_inq_dimid(ncid, \"Time\", dimid_times)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_3d() - \"// &\n                             \"Problem nf90_inq_dimid for 'Time'\")\n\n       call make_var_att_2d(ncid, dimid_ix, dimid_jx, dimid_times, NF90_INT, name, \"\", \"\")\n   end subroutine define_2d_int\n\n   subroutine define_3d_real(ncid, array,name,units,description, layers)\n       implicit none\n       real,         dimension(:,:,:),                              intent(in) :: array\n       character(len=*),                                             intent(in) :: name\n       character(len=*), optional,                                   intent(in) :: units\n       character(len=*), optional,                                   intent(in) :: description\n       character(len=4), optional,                                   intent(in) :: layers\n\n       integer :: ierr, ncid, dimid_ix, dimid_jx, dimid_times, dimid_kx\n       character(len=4) :: output_layers\n\n       if (present(layers)) then\n          output_layers = layers\n       else\n          output_layers = \"SOIL\"\n       endif\n\n       ierr = nf90_inq_dimid(ncid, \"west_east\", dimid_ix)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_integer() - \"// &\n                             \"Problem nf90_inq_dimid for 'west_east'\")\n\n       ierr = nf90_inq_dimid(ncid, \"south_north\", dimid_jx)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_2d_integer() - \"// &\n                             \"Problem nf90_inq_dimid for 'south_north'\")\n\n       ierr = nf90_inq_dimid(ncid, \"Time\", dimid_times)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_3d() - \"// &\n                             \"Problem nf90_inq_dimid for 'Time'\")\n\n       if (output_layers == \"SOIL\") then\n       ierr = nf90_inq_dimid(ncid, \"soil_layers_stag\", dimid_kx)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_3d() - \"// &\n                                \"Problem nf90_inq_dimid for 'soil_layers_stag'\")\n    else if (output_layers == \"SNOW\") then\n       ierr = nf90_inq_dimid(ncid, \"snow_layers\", dimid_kx)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_3d() - \"// &\n                                \"Problem nf90_inq_dimid for 'snow_layers'\")\n    else if (output_layers == \"SOSN\") then\n       ierr = nf90_inq_dimid(ncid, \"sosn_layers\", dimid_kx)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_3d() - \"// &\n                                \"Problem nf90_inq_dimid for 'sosn_layers'\")\n    else if (output_layers == \"MAXS\" .and. crocus_opt /= 0) then\n       ierr = nf90_inq_dimid(ncid, \"glacier_levels\", dimid_kx)\n       call error_handler(ierr, \"In module_hrldas_netcdf_io.F add_to_restart_3d() - \"// &\n                                \"Problem nf90_inq_dimid for 'glacier_levels'\")\n    else\n       stop \"FATAL ERROR: In module_hrldas_netcdf_io.F add_to_restart_3d() - PANIC!\"\n    endif\n    call make_var_att_3d(ncid, dimid_ix, dimid_jx, dimid_times, NF90_FLOAT, dimid_kx, name, \"\", \"\")\n   end subroutine define_3d_real\n\n\n end module module_hrldas_netcdf_io\n"
  },
  {
    "path": "src/Land_models/NoahMP/Makefile",
    "content": "\nall: user_build_options\n\t(cd Utility_routines;\t\tmake)\n\t(cd phys;\t\t\tmake)\n\t(cd data_structures;\t\tmake)\n\t(cd IO_code;\t\t\tmake)\n\t(cd run;\t\t\tmake)\n\nclean:\n\t(cd Utility_routines;\t\tmake clean)\n\t(cd phys;\t\t\tmake clean)\n\t(cd data_structures;\t\tmake clean)\n\t(cd IO_code;\t\t\tmake clean)\n\t(cd run;\t\t\tmake clean)\n\n### explicitly point to other land model options\nNoahMP: user_build_options\n\t(cd Utility_routines;\t\tmake)\n\t(cd phys;\t\t\tmake)\n\t(cd data_structures;\t\tmake)\n\t(cd IO_code;\t\t\tmake NoahMP MOD_OPT=\"-DNoahMP\")\n\t(cd run;\t\t\tmake -f Makefile NoahMP)\n"
  },
  {
    "path": "src/Land_models/NoahMP/README",
    "content": "\nHRLDAS v3.7 Release Notes\n============================\n\nNew capabilities:\n\n1. A parallel capability has been added by Wei Yu (weiyu@ncar.edu) to support mpi only.\n\n To compile with parallel version\n  edit the file 'user_build_options'\n  uncommment the compiler section with MPI (available for pgf90 and ifort compilers)\n\n To compile with sequential version\n  edit the file 'user_build_options'\n  uncommment the compiler section without MPI\n\n\n2. System setup and execution now requires only a WRF/WPS geo_em file. Dependence on the wrfinput file has been removed.\n\n\n3. As part of #2, initialization no longer occurs in the first forcing file, but in the file listed in the namelist as:\n    HRLDAS_SETUP_FILE = \"\"\n\n   The initialization fields are:\n     SNOW,CANWAT,TSK,TSLB,SMOIS\n   \n   This file also contains the static grid/domain information:\n     XLAT,XLONG,TMN,HGT,SEAICE,MAPFAC_MX,MAPFAC_MY,SHDMAX,SHDMIN,XLAND,IVGTYP,ISLTYP,DZS,ZS\n\n   This file can also contains some optional fields:\n     LAI\n     \n   NOTE: a WRF input file can be used as a HRLDAS_SETUP_FILE\n\n4. The timing structure has changed:\n\n   - The initial conditions are the states at START time. \n   - First forcing file used is START time + FORCING_TIMESTEP \n   - First integration is START time + NOAH_TIMESTEP \n   - First output file is now START time + OUTPUT_TIMESTEP     \n   - RESTART file states are consistent with OUTPUT file states with the same time stamp\n\n\n5. Instructions for using GLDAS and NLDAS as forcing has been provided in addition to the NARR instructions (see /docs)\n     Also, a NCL script has been included for preparing single- or multi-point forcing\n     \n\n6. Initial LAI (if present in the HRLDAS_SETUP_FILE) will be used to initialize the leaf and stem carbon pools\n\n\n7. Removed dependence on external GRIB tables for forcing creation; now in namelist only\n"
  },
  {
    "path": "src/Land_models/NoahMP/Utility_routines/CMakeLists.txt",
    "content": "add_library(noahmp_util STATIC\n        kwm_string_utilities.F\n        module_date_utilities.F\n        module_model_constants.F\n        module_wrf_utilities.F\n)\n\ntarget_link_libraries(noahmp_util PUBLIC hydro_mpp)\n"
  },
  {
    "path": "src/Land_models/NoahMP/Utility_routines/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\ninclude ../user_build_options\n\nOBJS = \\\n\tmodule_date_utilities.o \\\n\tmodule_model_constants.o \\\n\tmodule_wrf_utilities.o \\\n\tkwm_string_utilities.o\n\nCPPHRLDAS = -D_HRLDAS_OFFLINE_\n\n\nall:\t$(OBJS)\n\n.F.o:\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c $(F90FLAGS) $(LDFLAGS) $(MODFLAG) $(FREESOURCE) $(*).F\n\t@echo \"\"\n\n#\n# Dependencies:\n#\n\n#\n# This command cleans up object (etc.) files:\n#\n\nclean:\n\t$(RM) *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Land_models/NoahMP/Utility_routines/kwm_string_utilities.F",
    "content": "module kwm_string_utilities\n\ncontains\n\n  subroutine strrep(string, rep1, rep2)\n    ! In string 1, replace expression rep1 with expression rep2.\n    ! if rep2 is shorter than rep1, fill the end of the string\n    ! with blanks\n\n    implicit none\n    character(len=*) :: string, rep1, rep2\n    integer :: idx, inlen, len1, len2\n\n    do\n       inlen = len(string)\n       len1 = len(rep1)\n       len2 = len(rep2)\n       idx = index(string, rep1)-1\n\n       if (idx == -1) then\n          return\n       else\n          string = string(1:idx)// rep2 // &\n               string((idx+len1+1):inlen) // &\n               \"                                                    \"\n       endif\n    enddo\n\n  end subroutine strrep\n\n\n  character(len=1024) function unblank(string) result(return_string)\n    ! Remove blanks (and tabs [char(9)] from string\n    implicit none\n    character(len=*), intent(in) :: string\n    integer :: i, j,  lenstr\n\n    return_string = \" \"\n\n    if ( verify(string,\" \"//char(9)) == 0 ) then\n       stop 'FATAL ERROR: In unblank() - String is all blanks.'\n    endif\n\n    j = 0\n    do i = 1, len(string)\n       if ((string(i:i).ne.' ').and.(string(i:i).ne.char(9))) then\n          j = j + 1\n          return_string(j:j) = string(i:i)\n       endif\n    enddo\n\n  end function unblank\n\n!KWM  character function upcase(h)\n!KWM    implicit none\n!KWM    character :: h\n!KWM\n!KWM    if ((ichar(h).ge.96) .and. (ichar(h).le.123)) then\n!KWM       upcase = char(ichar(h)-32)\n!KWM    else\n!KWM       upcase = h\n!KWM    endif\n!KWM\n!KWM  end function upcase\n\n  character(len=256) function upcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \" \"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.96) .and. (ichar(h(i:i)).le.123)) then\n          return_string(i:i) = char(ichar(h(i:i))-32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function upcase\n\n!KWM  character function downcase(h)\n!KWM    implicit none\n!KWM    character h\n!KWM\n!KWM    if ((ichar(h).ge.65) .and. (ichar(h).le.90)) then\n!KWM       downcase = char(ichar(h)+32)\n!KWM    else\n!KWM       downcase = h\n!KWM    endif\n!KWM  end function downcase\n\n  character(len=256) function downcase(h) result(return_string)\n    implicit none\n    character(len=*), intent(in) :: h\n    integer :: i\n\n    return_string = \" \"\n\n    do i = 1, len_trim(h)\n\n       if ((ichar(h(i:i)).ge.65) .and. (ichar(h(i:i)).le.90)) then\n          return_string(i:i) = char(ichar(h(i:i))+32)\n       else\n          return_string(i:i) = h(i:i)\n       endif\n    enddo\n\n  end function downcase\n\n\nend module kwm_string_utilities\n"
  },
  {
    "path": "src/Land_models/NoahMP/Utility_routines/module_date_utilities.F",
    "content": "module Module_Date_utilities\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n    !  From old date (\"YYYY-MM-DD HH:MM:SS.ffff\" or \"YYYYMMDDHHMMSSffff\") and \n    !  delta-time, compute the new date.\n\n    !  on entry     -  odate  -  the old hdate.\n    !                  idt    -  the change in time\n\n    !  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n    !  Local Variables\n\n    !  yrold    -  indicates the year associated with \"odate\"\n    !  moold    -  indicates the month associated with \"odate\"\n    !  dyold    -  indicates the day associated with \"odate\"\n    !  hrold    -  indicates the hour associated with \"odate\"\n    !  miold    -  indicates the minute associated with \"odate\"\n    !  scold    -  indicates the second associated with \"odate\"\n\n    !  yrnew    -  indicates the year associated with \"ndate\"\n    !  monew    -  indicates the month associated with \"ndate\"\n    !  dynew    -  indicates the day associated with \"ndate\"\n    !  hrnew    -  indicates the hour associated with \"ndate\"\n    !  minew    -  indicates the minute associated with \"ndate\"\n    !  scnew    -  indicates the second associated with \"ndate\"\n\n    !  mday     -  a list assigning the number of days in each month\n\n    !  i        -  loop counter\n    !  nday     -  the integer number of days represented by \"idt\"\n    !  nhour    -  the integer number of hours in \"idt\" after taking out\n    !              all the whole days\n    !  nmin     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days and whole hours.\n    !  nsec     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days, whole hours, and whole minutes.\n\n    integer :: newlen, oldlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n    logical :: punct\n    integer :: yrstart, yrend, mostart, moend, dystart, dyend\n    integer :: hrstart, hrend, mistart, miend, scstart, scend, frstart\n    integer :: units\n    integer, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n\n    ! Determine if odate is \"YYYY-MM-DD_HH ... \" or \"YYYYMMDDHH....\"\n    if (odate(5:5) == \"-\") then\n       punct = .TRUE.\n    else\n       punct = .FALSE.\n    endif\n\n    !  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    oldlen = LEN(odate)\n    if (punct) then\n       yrstart = 1\n       yrend = 4\n       mostart = 6\n       moend = 7\n       dystart = 9\n       dyend = 10\n       hrstart = 12\n       hrend = 13\n       mistart = 15\n       miend = 16\n       scstart = 18\n       scend = 19\n       frstart = 21\n       select case (oldlen)\n       case (10)\n          ! Days\n          units = 1\n       case (13)\n          ! Hours\n          units = 2\n       case (16)\n          ! Minutes\n          units = 3\n       case (19)\n          ! Seconds\n          units = 4\n       case (21)\n          ! Tenths\n          units = 5\n       case (22)\n          ! Hundredths\n          units = 6\n       case (23)\n          ! Thousandths\n          units = 7\n       case (24)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'FATAL ERROR: In geth_newdate() - odd length: #'//trim(odate)//'#'\n          stop\n       end select\n\n       if (oldlen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n\n    else\n\n       yrstart = 1\n       yrend = 4\n       mostart = 5\n       moend = 6\n       dystart = 7\n       dyend = 8\n       hrstart = 9\n       hrend = 10\n       mistart = 11\n       miend = 12\n       scstart = 13\n       scend = 14\n       frstart = 15\n\n       select case (oldlen)\n       case (8)\n          ! Days\n          units = 1\n       case (10)\n          ! Hours\n          units = 2\n       case (12)\n          ! Minutes\n          units = 3\n       case (14)\n          ! Seconds\n          units = 4\n       case (15)\n          ! Tenths\n          units = 5\n       case (16)\n          ! Hundredths\n          units = 6\n       case (17)\n          ! Thousandths\n          units = 7\n       case (18)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'FATAL ERROR: In geth_newdate() - odd length: #'//trim(odate)//'#'\n          stop\n       end select\n    endif\n\n    !  Use internal READ statements to convert the CHARACTER string\n    !  date into INTEGER components.\n\n    read(odate(yrstart:yrend),  '(i4)') yrold\n    read(odate(mostart:moend),  '(i2)') moold\n    read(odate(dystart:dyend), '(i2)') dyold\n    if (units.ge.2) then\n       read(odate(hrstart:hrend),'(i2)') hrold\n       if (units.ge.3) then\n          read(odate(mistart:miend),'(i2)') miold\n          if (units.ge.4) then\n             read(odate(scstart:scend),'(i2)') scold\n             if (units.ge.5) then\n                read(odate(frstart:oldlen),*) frold\n             end if\n          end if\n       end if\n    end if\n\n    !  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n    !  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n    !  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n    !  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n    !  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n    !  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n    !  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n    !  Check that the fractional part  of ODATE makes sense.\n\n!KWM      IF ((scold.GT.59).or.(scold.LT.0)) THEN\n!KWM         WRITE(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n!KWM         opass = .FALSE.\n!KWM      END IF\n\n    if (.not.opass) then\n       write(*,*) 'FATAL ERROR: In geth_newdate() - Crazy ODATE: ', odate(1:oldlen), oldlen\n       stop\n    end if\n\n    !  Date Checks are completed.  Continue.\n\n\n    !  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (units.ge.5) then !idt should be in fractions of seconds\n       ifrc = oldlen-(frstart)+1\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (units.eq.4) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (units.eq.3) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.2) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.1) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''FATAL ERROR: geth_newdate() - Strange length for ODATE: '', i3)') &\n            oldlen\n       write(*,*) '#'//odate(1:oldlen)//'#'\n       stop\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n    !  Now construct the new mdate\n\n    newlen = LEN(ndate)\n\n    if (punct) then\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n    else\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n119       format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,116) yrnew, monew, dynew, hrnew, minew\n116       format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,113) yrnew, monew, dynew, hrnew\n113       format(i4,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,110) yrnew, monew, dynew\n110       format(i4,i2.2,i2.2)\n\n       end if\n\n    endif\n\n    if (punct .and. (oldlen.ge.11) .and. (newlen.ge.11)) ndate(11:11) = sp\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n\n    implicit none\n\n    !  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n    !  compute the time difference.\n\n    !  on entry     -  newdate  -  the new hdate.\n    !                  olddate  -  the old hdate.\n\n    !  on exit      -  idt    -  the change in time.\n    !                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n\n    !  Local Variables\n\n    !  yrnew    -  indicates the year associated with \"ndate\"\n    !  yrold    -  indicates the year associated with \"odate\"\n    !  monew    -  indicates the month associated with \"ndate\"\n    !  moold    -  indicates the month associated with \"odate\"\n    !  dynew    -  indicates the day associated with \"ndate\"\n    !  dyold    -  indicates the day associated with \"odate\"\n    !  hrnew    -  indicates the hour associated with \"ndate\"\n    !  hrold    -  indicates the hour associated with \"odate\"\n    !  minew    -  indicates the minute associated with \"ndate\"\n    !  miold    -  indicates the minute associated with \"odate\"\n    !  scnew    -  indicates the second associated with \"ndate\"\n    !  scold    -  indicates the second associated with \"odate\"\n    !  i        -  loop counter\n    !  mday     -  a list assigning the number of days in each month\n\n    ! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    integer :: oldlen, newlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: i, newdys, olddys\n    logical :: npass, opass\n    integer :: timesign\n    integer :: ifrc\n    integer, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n    logical :: punct\n    integer :: yrstart, yrend, mostart, moend, dystart, dyend\n    integer :: hrstart, hrend, mistart, miend, scstart, scend, frstart\n    integer :: units\n\n    oldlen = len(olddate)\n    newlen = len(newdate)\n    if (newlen.ne.oldlen) then\n       write(*,'(\"FATAL ERROR: In geth_idts() - NEWLEN /= OLDLEN: \", A, 3x, A)') newdate(1:newlen), olddate(1:oldlen)\n       stop\n    endif\n\n    if (olddate.gt.newdate) then\n       timesign = -1\n\n       ifrc = oldlen\n       oldlen = newlen\n       newlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       timesign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n    ! Break down old hdate into parts\n\n    ! Determine if olddate is punctuated or not\n    if (odate(5:5) == \"-\") then\n       punct = .TRUE.\n       if (ndate(5:5) /= \"-\") then\n          write(*,'(\"FATAL ERROR: In geth_idts() - Dates appear to be different formats: \", A, 3x, A)') &\n               ndate(1:newlen), odate(1:oldlen)\n          stop\n       endif\n    else\n       punct = .FALSE.\n       if (ndate(5:5) == \"-\") then\n          write(*,'(\"FATAL ERROR: In geth_idts() - Dates appear to be different formats: \", A, 3x, A)') &\n               ndate(1:newlen), odate(1:oldlen)\n          stop\n       endif\n    endif\n\n    if (punct) then\n       yrstart = 1\n       yrend = 4\n       mostart = 6\n       moend = 7\n       dystart = 9\n       dyend = 10\n       hrstart = 12\n       hrend = 13\n       mistart = 15\n       miend = 16\n       scstart = 18\n       scend = 19\n       frstart = 21\n       select case (oldlen)\n       case (10)\n          ! Days\n          units = 1\n       case (13)\n          ! Hours\n          units = 2\n       case (16)\n          ! Minutes\n          units = 3\n       case (19)\n          ! Seconds\n          units = 4\n       case (21)\n          ! Tenths\n          units = 5\n       case (22)\n          ! Hundredths\n          units = 6\n       case (23)\n          ! Thousandths\n          units = 7\n       case (24)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'FATAL ERROR: In geth_idts() - odd length: #'//trim(odate)//'#'\n          stop\n       end select\n    else\n\n       yrstart = 1\n       yrend = 4\n       mostart = 5\n       moend = 6\n       dystart = 7\n       dyend = 8\n       hrstart = 9\n       hrend = 10\n       mistart = 11\n       miend = 12\n       scstart = 13\n       scend = 14\n       frstart = 15\n\n       select case (oldlen)\n       case (8)\n          ! Days\n          units = 1\n       case (10)\n          ! Hours\n          units = 2\n       case (12)\n          ! Minutes\n          units = 3\n       case (14)\n          ! Seconds\n          units = 4\n       case (15)\n          ! Tenths\n          units = 5\n       case (16)\n          ! Hundredths\n          units = 6\n       case (17)\n          ! Thousandths\n          units = 7\n       case (18)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'FATAL ERROR: In geth_idts() - odd length: #'//trim(odate)//'#'\n          stop\n       end select\n    endif\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    read(odate(yrstart:yrend), '(i4)') yrold\n    read(odate(mostart:moend), '(i2)') moold\n    read(odate(dystart:dyend), '(i2)') dyold\n    if (units.ge.2) then\n       read(odate(hrstart:hrend),'(i2)') hrold\n       if (units.ge.3) then\n          read(odate(mistart:miend),'(i2)') miold\n          if (units.ge.4) then\n             read(odate(scstart:scend),'(i2)') scold\n             if (units.ge.5) then\n                read(odate(frstart:oldlen),*) frold\n             end if\n          end if\n       end if\n    end if\n\n    !  Break down new hdate into parts\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(ndate(yrstart:yrend), '(i4)') yrnew\n    read(ndate(mostart:moend), '(i2)') monew\n    read(ndate(dystart:dyend), '(i2)') dynew\n    if (units.ge.2) then\n       read(ndate(hrstart:hrend),'(i2)') hrnew\n       if (units.ge.3) then\n          read(ndate(mistart:miend),'(i2)') minew\n          if (units.ge.4) then\n             read(ndate(scstart:scend),'(i2)') scnew\n             if (units.ge.5) then\n                read(ndate(frstart:newlen),*) frnew\n             end if\n          end if\n       end if\n    end if\n\n    !  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n    !  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n       write(*,*) 'GETH_IDTS:  Month of NDATE = ', monew\n       npass = .false.\n    end if\n\n    !  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n       opass = .false.\n    end if\n\n    !  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n          npass = .false.\n       end if\n    endif\n\n    !  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n          opass = .false.\n       end if\n    end if\n\n    !  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n       npass = .false.\n    end if\n\n    !  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n       opass = .false.\n    end if\n\n    !  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n       npass = .false.\n    end if\n\n    !  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n       opass = .false.\n    end if\n\n    !  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n       npass = .false.\n    end if\n\n    !  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'FATAL ERROR: In geth_idts() - Screwy NDATE: ', ndate(1:newlen)\n       stop\n    end if\n\n    if (.not. opass) then\n       print*, 'FATAL ERROR: In geth_idts() - Screwy ODATE: ', odate(1:oldlen)\n       stop\n    end if\n\n    !  Date Checks are completed.  Continue.\n\n    !  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n    !  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n    !  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n    !  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n    !  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n    !  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (units.ge.2) then\n       idt = idt*24 + (hrnew - hrold)\n       if (units.ge.3) then\n          idt = idt*60 + (minew - miold)\n          if (units.ge.4) then\n             idt = idt*60 + (scnew - scold)\n             if (units.ge.5) then\n                ifrc = oldlen-(frstart-1)\n                ifrc = 10**ifrc\n                idt = idt * ifrc + (frnew-frold)\n             endif\n          endif\n       endif\n    endif\n\n    if (timesign .eq. -1) then\n       idt = idt * timesign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n    !\n    ! Compute the number of days in February for the given year.\n    !\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n    !\n    ! Compute the number of days in the month of given date hdate.\n    !\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    read(hdate(1:7), '(I4,1x,I2)') year, month\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\n\n  function monthabbr_to_mm(mon) result(mm)\n    implicit none\n\n    character(len=3), intent(in) :: mon\n\n    integer :: mm\n\n    if (mon == \"Jan\") then\n       mm = 1\n    elseif (mon == \"Feb\") then\n       mm = 2\n    elseif (mon == \"Mar\") then\n       mm = 3\n    elseif (mon == \"Apr\") then\n       mm = 4\n    elseif (mon == \"May\") then\n       mm = 5\n    elseif (mon == \"Jun\") then\n       mm = 6\n    elseif (mon == \"Jul\") then\n       mm = 7\n    elseif (mon == \"Aug\") then\n       mm = 8\n    elseif (mon == \"Sep\") then\n       mm = 9\n    elseif (mon == \"Oct\") then\n       mm = 10\n    elseif (mon == \"Nov\") then\n       mm = 11\n    elseif (mon == \"Dec\") then\n       mm = 12\n    else\n       write(*, '(\"Function monthabbr_to_mm:  mon = <\",A,\">\")') mon\n       stop  \"FATAL ERROR: In monthabbr_to_mm() - Unrecognized mon\"\n    endif\n  end function monthabbr_to_mm\n\n  subroutine swap_date_format(indate, outdate)\n    implicit none\n    character(len=*), intent(in)  :: indate\n    character(len=*), intent(out) :: outdate\n    integer :: inlen\n\n    inlen = len(indate)\n    if (indate(5:5) == \"-\") then\n       select case (inlen)\n       case (10)\n          ! YYYY-MM-DD\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)\n       case (13)\n          ! YYYY-MM-DD_HH\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)\n       case (16)\n          ! YYYY-MM-DD_HH:mm\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)\n       case (19)\n          ! YYYY-MM-DD_HH:mm:ss\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)//&\n               indate(18:19)\n       case (21,22,23,24)\n          ! YYYY-MM-DD_HH:mm:ss.f[f[f[f]]]\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)//&\n               indate(18:19)//indate(21:inlen)\n       case default\n          write(*,'(\"FATAL ERROR: In swap_date_format() - Unrecognized length: <\", A,\">\")') indate\n          stop\n       end select\n    else\n       select case (inlen)\n       case (8)\n          ! YYYYMMDD\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)\n       case (10)\n          ! YYYYMMDDHH\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)\n       case (12)\n          ! YYYYMMDDHHmm\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)\n       case (14)\n          ! YYYYMMDDHHmmss\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)//\":\"//indate(13:14)\n       case (15,16,17,18)\n          ! YYYYMMDDHHmmssf[f[f[f]]]\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)//\":\"//indate(13:14)//\".\"//indate(15:inlen)\n       case default\n          write(*,'(\"FATAL ERROR: In swap_date_format() - Unrecognized length: <\", A,\">\")') indate\n          stop\n       end select\n    endif\n\n  end subroutine swap_date_format\n\n  character(len=3) function mm_to_monthabbr(ii) result(mon)\n    implicit none\n    integer, intent(in) :: ii\n    character(len=3), parameter, dimension(12) :: month = (/ &\n         \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", &\n         \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" /)\n    if (ii > 0 .and. ii < 13 ) then\n       mon = month(ii)\n    else\n       stop \"FATAL ERROR: In mm_to_monthabbr()- Unrecognized the index of months\"\n    endif\n  end function mm_to_monthabbr\n\nend module Module_Date_utilities\n"
  },
  {
    "path": "src/Land_models/NoahMP/Utility_routines/module_model_constants.F",
    "content": "!WRF:MODEL_LAYER:CONSTANTS\n!\n\n MODULE module_model_constants\n\n   !  2. Following are constants for use in defining real number bounds.\n\n   !  A really small number.\n\n   REAL    , PARAMETER :: epsilon         = 1.E-15\n\n   !  4. Following is information related to the physical constants.\n\n   !  These are the physical constants used within the model.\n\n! JM NOTE -- can we name this grav instead?\n   REAL    , PARAMETER :: g = 9.81  ! acceleration due to gravity (m {s}^-2)\n\n#if ( NMM_CORE == 1 )\n   REAL    , PARAMETER :: r_d          = 287.04\n   REAL    , PARAMETER :: cp           = 1004.6\n#else\n   REAL    , PARAMETER :: r_d          = 287.\n   REAL    , PARAMETER :: cp           = 7.*r_d/2.\n#endif\n\n   REAL    , PARAMETER :: r_v          = 461.6\n   REAL    , PARAMETER :: cv           = cp-r_d\n   REAL    , PARAMETER :: cpv          = 4.*r_v\n   REAL    , PARAMETER :: cvv          = cpv-r_v\n   REAL    , PARAMETER :: cvpm         = -cv/cp\n   REAL    , PARAMETER :: cliq         = 4190.\n   REAL    , PARAMETER :: cice         = 2106.\n   REAL    , PARAMETER :: psat         = 610.78\n   REAL    , PARAMETER :: rcv          = r_d/cv\n   REAL    , PARAMETER :: rcp          = r_d/cp\n   REAL    , PARAMETER :: rovg         = r_d/g\n   REAL    , PARAMETER :: c2           = cp * rcv\n   real    , parameter :: mwdry        = 28.966 ! molecular weight of dry air (g/mole)\n\n   REAL    , PARAMETER :: p1000mb      = 100000.\n   REAL    , PARAMETER :: t0           = 300.\n   REAL    , PARAMETER :: p0           = p1000mb\n   REAL    , PARAMETER :: cpovcv       = cp/(cp-r_d)\n   REAL    , PARAMETER :: cvovcp       = 1./cpovcv\n   REAL    , PARAMETER :: rvovrd       = r_v/r_d\n\n   REAL    , PARAMETER :: reradius     = 1./6370.0e03\n\n   REAL    , PARAMETER :: asselin      = .025\n!   REAL    , PARAMETER :: asselin      = .0\n   REAL    , PARAMETER :: cb           = 25.\n\n   REAL    , PARAMETER :: XLV0         = 3.15E6\n   REAL    , PARAMETER :: XLV1         = 2370.\n   REAL    , PARAMETER :: XLS0         = 2.905E6\n   REAL    , PARAMETER :: XLS1         = 259.532\n\n   REAL    , PARAMETER :: XLS          = 2.85E6\n   REAL    , PARAMETER :: XLV          = 2.5E6\n   REAL    , PARAMETER :: XLF          = 3.50E5\n\n   REAL    , PARAMETER :: rhowater     = 1000.\n   REAL    , PARAMETER :: rhosnow      = 100.\n   REAL    , PARAMETER :: rhoair0      = 1.28\n!\n   REAL    , PARAMETER :: n_ccn0       = 1.0E8\n!\n   REAL    , PARAMETER :: piconst      = 3.1415926535897932384626433\n   REAL    , PARAMETER :: DEGRAD       = piconst/180.\n   REAL    , PARAMETER :: DPD          = 360./365.\n\n   REAL    , PARAMETER ::  SVP1=0.6112\n   REAL    , PARAMETER ::  SVP2=17.67\n   REAL    , PARAMETER ::  SVP3=29.65\n   REAL    , PARAMETER ::  SVPT0=273.15\n   REAL    , PARAMETER ::  EP_1=R_v/R_d-1.\n   REAL    , PARAMETER ::  EP_2=R_d/R_v\n   REAL    , PARAMETER ::  KARMAN=0.4\n   REAL    , PARAMETER ::  EOMEG=7.2921E-5\n   REAL    , PARAMETER ::  STBOLT=5.67051E-8\n\n   REAL    , PARAMETER ::  prandtl = 1./3.0\n                                         ! constants for w-damping option\n   REAL    , PARAMETER ::  w_alpha = 0.3 ! strength m/s/s\n   REAL    , PARAMETER ::  w_beta  = 1.0 ! activation cfl number\n\n       REAL , PARAMETER ::  pq0=379.90516\n       REAL , PARAMETER ::  epsq2=0.2\n       REAL , PARAMETER ::  a2=17.2693882\n       REAL , PARAMETER ::  a3=273.16\n       REAL , PARAMETER ::  a4=35.86\n       REAL , PARAMETER ::  epsq=1.e-12\n       REAL , PARAMETER ::  p608=rvovrd-1.\n!#if ( NMM_CORE == 1 )\n       REAL , PARAMETER ::  climit=1.e-20\n       REAL , PARAMETER ::  cm1=2937.4\n       REAL , PARAMETER ::  cm2=4.9283\n       REAL , PARAMETER ::  cm3=23.5518\n!       REAL , PARAMETER ::  defc=8.0\n!       REAL , PARAMETER ::  defm=32.0\n       REAL , PARAMETER ::  defc=0.0\n       REAL , PARAMETER ::  defm=99999.0\n       REAL , PARAMETER ::  epsfc=1./1.05\n       REAL , PARAMETER ::  epswet=0.0\n       REAL , PARAMETER ::  fcdif=1./3.\n#ifdef HWRF\n       REAL , PARAMETER ::  fcm=0.0\n#else\n       REAL , PARAMETER ::  fcm=0.00003\n#endif\n       REAL , PARAMETER ::  gma=-r_d*(1.-rcp)*0.5\n       REAL , PARAMETER ::  p400=40000.0\n       REAL , PARAMETER ::  phitp=15000.0\n       REAL , PARAMETER ::  pi2=2.*3.1415926, pi1=3.1415926\n       REAL , PARAMETER ::  plbtm=105000.0\n       REAL , PARAMETER ::  plomd=64200.0\n       REAL , PARAMETER ::  pmdhi=35000.0\n       REAL , PARAMETER ::  q2ini=0.50\n       REAL , PARAMETER ::  rfcp=0.25/cp\n       REAL , PARAMETER ::  rhcrit_land=0.75\n       REAL , PARAMETER ::  rhcrit_sea=0.80\n       REAL , PARAMETER ::  rlag=14.8125\n       REAL , PARAMETER ::  rlx=0.90\n       REAL , PARAMETER ::  scq2=50.0\n       REAL , PARAMETER ::  slopht=0.001\n       REAL , PARAMETER ::  tlc=2.*0.703972477\n       REAL , PARAMETER ::  wa=0.15\n       REAL , PARAMETER ::  wght=0.35\n       REAL , PARAMETER ::  wpc=0.075\n       REAL , PARAMETER ::  z0land=0.10\n#ifdef HWRF\n       REAL , PARAMETER ::  z0max=0.01\n#else\n       REAL , PARAMETER ::  z0max=0.008\n#endif\n       REAL , PARAMETER ::  z0sea=0.001\n!#endif\n\n\n   !  Earth\n\n   !  The value for P2SI *must* be set to 1.0 for Earth\n   !  Although, now we may not need this declaration here (see above)\n   !REAL    , PARAMETER :: P2SI         = 1.0\n\n   !  Orbital constants:\n\n   INTEGER , PARAMETER :: PLANET_YEAR = 365\n   REAL , PARAMETER :: OBLIQUITY = 23.5\n   REAL , PARAMETER :: ECCENTRICITY = 0.014\n   REAL , PARAMETER :: SEMIMAJORAXIS = 1.0 ! In AU\n   ! Don't know the following values, so we'll fake them for now\n   REAL , PARAMETER :: zero_date = 0.0   ! Time of perihelion passage\n   !  Fraction into the year (from perhelion) of the\n   !  occurrence of the Northern Spring Equinox\n   REAL , PARAMETER :: EQUINOX_FRACTION= 0.0\n\n! 2012103\n#if (EM_CORE == 1)\n! for calls to set_tiles\n   INTEGER, PARAMETER :: ZONE_SOLVE_EM = 1\n   INTEGER, PARAMETER :: ZONE_SFS = 2\n#endif\n\n CONTAINS\n   SUBROUTINE init_module_model_constants\n   END SUBROUTINE init_module_model_constants\n END MODULE module_model_constants\n"
  },
  {
    "path": "src/Land_models/NoahMP/Utility_routines/module_wrf_utilities.F",
    "content": "!WRF:DRIVER_LAYER:UTIL\n!\n\nSUBROUTINE wrf_message( str )\n  IMPLICIT NONE\n\n  CHARACTER*(*) str\n  print *,trim(str)\n\nEND SUBROUTINE wrf_message\n\nSUBROUTINE wrf_error_fatal( str )\n  IMPLICIT NONE\n  CHARACTER*(*) str\n#ifdef NCEP_WCOSS\n  write(78,*) 'FATAL ERROR: ',trim(str)\n  call flush(78)\n  close(78)\n#else\n  write(6,*) 'FATAL ERROR: ',trim(str)\n  call flush(6)\n#endif\n\n  CALL wrf_abort\nEND SUBROUTINE wrf_error_fatal\n\nSUBROUTINE wrf_abort\n  use module_cpl_land\n  integer ierr\n  call MPI_Abort(HYDRO_COMM_WORLD,1,ierr)\n  call MPI_Finalize(ierr)\n  STOP 'wrf_abort'\nEND SUBROUTINE wrf_abort\n\nSUBROUTINE wrf_debug( level , str )\n  IMPLICIT NONE\n  CHARACTER*(*) str\n  INTEGER , INTENT (IN) :: level\n  CALL wrf_message( str )\n  RETURN\nEND SUBROUTINE wrf_debug\n\nsubroutine wrf_dm_bcast_real(rval, ival)\n  implicit none\n  real,    intent(in) :: rval\n  integer, intent(in) :: ival\nend subroutine wrf_dm_bcast_real\n\nsubroutine wrf_dm_bcast_integer(rval, ival)\n  implicit none\n  integer, intent(in) :: rval\n  integer, intent(in) :: ival\nend subroutine wrf_dm_bcast_integer\n\nsubroutine wrf_dm_bcast_string(rval, ival)\n  implicit none\n  character(len=*), intent(in) :: rval\n  integer,          intent(in) :: ival\nend subroutine wrf_dm_bcast_string\n"
  },
  {
    "path": "src/Land_models/NoahMP/data_structures/CMakeLists.txt",
    "content": "add_library(noahmp_data STATIC\n        forcing.f90\n        geometry.f90\n        parameters.f90\n        state.f90\n        )\n\ntarget_link_libraries(noahmp_data PUBLIC hydro_orchestrator)"
  },
  {
    "path": "src/Land_models/NoahMP/data_structures/Makefile",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .f90\n\ninclude ../../../macros\n\nOBJS = \\\n\tstate.o \\\n\tforcing.o \\\n\tparameters.o \\\n\tgeometry.o\n\nall:\t$(OBJS)\n\n#module_RT.o: module_RT.F\n#\t@echo \"\"\n#\t$(CPP) $(CPPFLAGS) $(*).F > $(*).f\n#\t$(COMPILER90) -o $(@) $(F90FLAGS) $(MODFLAG)  $(*).f\n#\t$(RMD) $(*).f\n#\t@echo \"\"\n#\tcp *.mod ../mod\n\n.f90.o:\n\t@echo \"Data structures Makefile:\"\n#\t$(COMPILER90) -o $(@) $(F90FLAGS) $(MODFLAG) $(*).f\n\t$(COMPILER90) $(CPPINVOKE) -o $(@) $(FPPFLAGS) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) -I../../../OrchestratorLayer $(*).f90\n#\t$(RMD) $(*).f\n\t@echo \"\"\n\tar -r ../../../lib/libHYDRO.a $(@)\n\tcp *.mod ../../../mod\n\n#\n# Dependencies:\n#\n# io_manager.o: ../IO/netcdf_layer.o\n\n# orchestrator.o: ig.o\n\nclean:\t\n\trm -f *.o *.mod *.stb *~ *.f\n"
  },
  {
    "path": "src/Land_models/NoahMP/data_structures/forcing.f90",
    "content": "module forcing\n\nend module forcing\n"
  },
  {
    "path": "src/Land_models/NoahMP/data_structures/geometry.f90",
    "content": "module geometry\n\nend module geometry\n"
  },
  {
    "path": "src/Land_models/NoahMP/data_structures/parameters.f90",
    "content": "module parameters\n\nend module parameters\n"
  },
  {
    "path": "src/Land_models/NoahMP/data_structures/state.f90",
    "content": "module state_module\n  implicit none\n\n  type state_type\n     !SNOW VARIABLES\n     REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  TSNOXY    ! snow temperature [K] ** REFACTOR THIS!\n     REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  ZSNSOXY   ! snow layer depth [m] ** REFACTOR THIS!\n     REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  SNICEXY   ! snow layer ice [mm] ** REFACTOR THIS!\n     REAL,    ALLOCATABLE, DIMENSION(:,:,:)  ::  SNLIQXY   ! snow layer liquid water [mm] ** REFACTOR THIS!\n     REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNOW      ! snow water equivalent [mm] ** (sometime) PROGNOSTIC VARIABLE\n     REAL,    ALLOCATABLE, DIMENSION(:,:)    ::  SNOWH     ! physical snow depth [m] ** (sometime) PROGNOSTIC VARIABLE\n   contains\n     procedure :: init => init_undefined\n  end type state_type\n\ncontains\n  !Are we actually initializing?\n  subroutine init_undefined(this)\n    use config_base, only: noah_lsm\n    implicit none\n\n    class(state_type) :: this\n    integer, parameter :: NSNOW = 3 !As definined in module_NoahMP,hrldas_driver.F. TODO Getting from a config later\n    REAL, PARAMETER :: undefined_real = 9.9692099683868690E36 ! TODO Getting from a config later\n    integer :: xstart, xend, ystart, yend, nsoil\n\n    xstart = noah_lsm%xstart\n    xend = noah_lsm%xend\n    ystart = noah_lsm%ystart\n    yend = noah_lsm%yend\n    nsoil = noah_lsm%nsoil\n\n    ALLOCATE ( this%TSNOXY    (XSTART:XEND,-NSNOW+1:0,    YSTART:YEND), source = undefined_real )  ! snow temperature [K]\n    ALLOCATE ( this%ZSNSOXY   (XSTART:XEND,-NSNOW+1:NSOIL,YSTART:YEND), source = undefined_real )  ! snow layer depth [m]\n    ALLOCATE ( this%SNICEXY   (XSTART:XEND,-NSNOW+1:0,    YSTART:YEND), source = undefined_real )  ! snow layer ice [mm]\n    ALLOCATE ( this%SNLIQXY   (XSTART:XEND,-NSNOW+1:0,    YSTART:YEND), source = undefined_real )  ! snow layer liquid water [mm]\n    ALLOCATE ( this%SNOW      (XSTART:XEND,YSTART:YEND), source = undefined_real )  ! snow water equivalent [mm]\n    ALLOCATE ( this%SNOWH     (XSTART:XEND,YSTART:YEND), source = undefined_real )  ! physical snow depth [m]\n\n  end subroutine init_undefined\n\nend module state_module\n"
  },
  {
    "path": "src/Land_models/NoahMP/hydro/Makefile.hydro",
    "content": "\nall: user_build_options\n\t(cd Utility_routines;\t\tmake)\n\t(cd phys;\t\t\tmake)\n\t(cd data_structures;\t\tmake)\n\t(cd IO_code;\t\t\tmake)\n\t(cd run;\t\t\tmake)\n\nclean:\n\t(cd Utility_routines;\t\tmake clean)\n\t(cd phys;\t\t\tmake clean)\n\t(cd data_structures;\t\tmake clean)\n\t(cd IO_code;\t\t\tmake clean)\n\t(cd run;\t\t\tmake clean)\n\n### explicitly point to other land model options\nNoahMP: user_build_options\n\t(cd Utility_routines;\t\tmake)\n\t(cd phys;\t\t\tmake)\n\t(cd data_structures;\t\tmake)\n\t(cd IO_code;\t\t\tmake NoahMP MOD_OPT=\"-DNoahMP\")\n\t(cd run;\t\t\tmake -f Makefile NoahMP)\n"
  },
  {
    "path": "src/Land_models/NoahMP/hydro/Makefile_run",
    "content": ".SUFFIXES:\n.SUFFIXES: .o .f\n\nifeq ($(WRF_HYDRO_RAPID),1)\ninclude ${PETSC_DIR}/conf/variables\ninclude ${PETSC_DIR}/conf/rules\nTAO_FORTRAN_LIB=-L/opt/apps/intel11_1/mvapich2_1_6/tao/1.10.1/lib/westmere-cxx\nendif\n\ninclude ../user_build_options\n\nifeq ($(WRF_HYDRO_RAPID),1)\nPHDF5_INC=-I ${TACC_HDF5_INC}\nRAPID_MACRO = ${TAO_FORTRAN_LIB} ${TAO_LIB} ${PETSC_LIB}\nRAPID_LIB =  -lrapid\nelse\nRAPID_MACRO = \nRAPID_LIB =  \nendif\n\nOBJS_NoahMP = ../IO_code/module_NoahMP_hrldas_driver.o \n\nOBJS = \\\n\t../IO_code/main_hrldas_driver.o \\\n\t../IO_code/module_hrldas_netcdf_io.o \\\n\t../phys/module_sf_noahmpdrv.o \\\n\t../phys/module_sf_noahmplsm.o \\\n\t../phys/module_sf_noahmp_glacier.o \\\n\t../phys/module_sf_noahmp_groundwater.o \\\n\t../Utility_routines/module_wrf_utilities.o \\\n\t../Utility_routines/module_model_constants.o \\\n\t../Utility_routines/module_date_utilities.o \\\n\t../Utility_routines/kwm_string_utilities.o\n\nCMD = hrldas.exe\nall:\t$(CMD)\n\n### default we create the exe based on NoahMP\nhrldas.exe: $(OBJS)\n\t@echo \"\"\n\techo \"${TAO_FORTRAN_LIB} ${TAO_LIB} ${PETSC_LIB} ${PHDF5_INC} -Wl,-rpath,${TACC_HDF5_LIB} -L${TACC_HDF5_LIB} -lhdf5 -lz\"\n# We have to include the modules built in ../IO_code \n\t$(COMPILERF90) -o $(@) -I../IO_code -I../phys $(OBJS) $(OBJS_NoahMP) $(HYDRO_LIB) $(RAPID_LIB) $(NETCDFLIB) $(RAPID_MACRO) $(LDFLAGS) $(LIBS)\n\n\t@echo \"\"\n\n# Template to create the exe file based on different land model. Such as NoahMP\nNoahMP: $(OBJS)\n\t@echo \"\"\n\t$(COMPILERF90) -o hrldas.exe -I../IO_code -I../phys $(OBJS) $(OBJS_NoahMP)  $(HYDRO_LIB) $(NETCDFLIB) $(LDFLAGS) $(LIBS)\n\t@echo \"\"\n\n# This command cleans up\nclean:\n\t$(RM) *~ $(CMD)\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/hydro/user_build_options.bak",
    "content": "\n# flag from HRLDAS\nCOMPILERF90 = $(COMPILER90)\nFREESOURCE      =\nLIBJASPER       =       -ljpeg -L/scholar/kmanning/jasper/lib -ljasper\nINCJASPER       =       -I/scholar/kmanning/jasper/include\nNETCDFMOD       =       -I $(NETCDFINC)\nBZIP2           =       YES\nBZIP2_LIB       =       -lbz2\nBZIP2_INCLUDE   =       -I/usr/include\nCC              =       cc\nHYDRO_LIB = -L../../../lib  -lHYDRO\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/CMakeLists.txt",
    "content": "add_subdirectory(\"surfex\")\n\nadd_library(noahmp_phys STATIC\n        module_sf_noahmpdrv.F\n        module_sf_noahmp_glacier.F\n        module_sf_noahmp_groundwater.F\n        module_sf_noahmplsm.F\n)\n\ntarget_link_libraries(noahmp_phys snowcro crocus_surfex)\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/Makefile",
    "content": "# Makefile\n#\ninclude ../user_build_options\n\nSRCS := $(wildcard *.F)\nOBJS := $(SRCS:%.F=%.o)\nSUR_SRCS := $(wildcard surfex/*.F)\nSUR_OBJS := $(SUR_SRCS:%.F=%.o)\nCPPHRLDAS = -D_HRLDAS_OFFLINE_\n\n# Check whether or not to build Crocus\nifndef BUILD_CROCUS\nBUILD_CROCUS:=1\nendif\nifeq ($(BUILD_CROCUS), 1)\n        SUR_OBJS := $(filter-out ../surfex/module_snowcro_intercept.o, $(SUR_OBJS))\nelse\n        SUR_OBJS := $(filter-out ../surfex/module_snowcro.o, $(SUR_OBJS))\nendif\n\nall: $(OBJS)\n\n%.o:%.F\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $(@) -c -I../Utility_routines -Isurfex $(F90FLAGS) $(LDFLAGS) $(FREESOURCE) $(*).F\n\t@echo \"\"\n\nsurfex/%.o:\n\t$(MAKE) --directory=surfex/\n\n#\n# Dependencies:\n#\nmodule_sf_noahmpdrv.o:\tmodule_sf_noahmplsm.o module_sf_noahmp_glacier.o module_sf_noahmp_groundwater.o $(SUR_OBJS)\nmodule_sf_noahmp_groundwater.o: module_sf_noahmplsm.o\n\n#\n# This command cleans up object (etc) files:\n#\nclean:\n\t$(MAKE) clean --directory=surfex\n\t$(RM) *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/module_sf_noahmp_glacier.F",
    "content": "MODULE NOAHMP_GLACIER_GLOBALS\n\n  implicit none\n\n! ==================================================================================================\n!------------------------------------------------------------------------------------------!\n! Physical Constants:                                                                      !\n!------------------------------------------------------------------------------------------!\n\n  REAL, PARAMETER :: GRAV   = 9.80616   !acceleration due to gravity (m/s2)\n  REAL, PARAMETER :: SB     = 5.67E-08  !Stefan-Boltzmann constant (w/m2/k4)\n  REAL, PARAMETER :: VKC    = 0.40      !von Karman constant\n  REAL, PARAMETER :: TFRZ   = 273.16    !freezing/melting point (k)\n  REAL, PARAMETER :: HSUB   = 2.8440E06 !latent heat of sublimation (j/kg)\n  REAL, PARAMETER :: HVAP   = 2.5104E06 !latent heat of vaporization (j/kg)\n  REAL, PARAMETER :: HFUS   = 0.3336E06 !latent heat of fusion (j/kg)\n  REAL, PARAMETER :: CWAT   = 4.188E06  !specific heat capacity of water (j/m3/k)\n  REAL, PARAMETER :: CICE   = 2.094E06  !specific heat capacity of ice (j/m3/k)\n  REAL, PARAMETER :: CPAIR  = 1004.64   !heat capacity dry air at const pres (j/kg/k)\n  REAL, PARAMETER :: TKWAT  = 0.6       !thermal conductivity of water (w/m/k)\n  REAL, PARAMETER :: TKICE  = 2.2       !thermal conductivity of ice (w/m/k)\n  REAL, PARAMETER :: TKAIR  = 0.023     !thermal conductivity of air (w/m/k)\n  REAL, PARAMETER :: RAIR   = 287.04    !gas constant for dry air (j/kg/k)\n  REAL, PARAMETER :: RW     = 461.269   !gas constant for  water vapor (j/kg/k)\n  REAL, PARAMETER :: DENH2O = 1000.     !density of water (kg/m3)\n  REAL, PARAMETER :: DENICE = 917.      !density of ice (kg/m3)\n\n! =====================================options for different schemes================================\n\n! options for ground snow surface albedo\n! 1-> BATS; 2 -> CLASS\n\n  INTEGER :: OPT_ALB != 2    !(suggested 2)\n\n! options for partitioning  precipitation into rainfall & snowfall\n! 1 -> Jordan (1991); 2 -> BATS: when SFCTMP<TFRZ+2.2 ; 3-> SFCTMP<TFRZ\n\n  INTEGER :: OPT_SNF != 1    !(suggested 1)\n\n! options for lower boundary condition of soil temperature\n! 1 -> zero heat flux from bottom (ZBOT and TBOT not used)\n! 2 -> TBOT at ZBOT (8m) read from a file (original Noah)\n\n  INTEGER :: OPT_TBOT != 2   !(suggested 2)\n\n! options for snow/soil teperature time scheme (only layer 1)\n! 1 -> semi-implicit; 2 -> full implicit (original Noah)\n\n  INTEGER :: OPT_STC != 1    !(suggested 1)\n\n! options for glacier treatment\n! 1 -> include phase change of ice; 2 -> ice treatment more like original Noah\n\n  INTEGER :: OPT_GLA != 1    !(suggested 1)\n\n! adjustable parameters for snow processes\n\n  REAL, PARAMETER :: Z0SNO  = 0.002  !snow surface roughness length (m) (0.002)\n  REAL, PARAMETER :: SSI    = 0.03   !liquid water holding capacity for snowpack (m3/m3) (0.03)\n  REAL, PARAMETER :: SWEMX  = 1.00   !new snow mass to fully cover old snow (mm)\n                                     !equivalent to 10mm depth (density = 100 kg/m3)\n\n!------------------------------------------------------------------------------------------!\nEND MODULE NOAHMP_GLACIER_GLOBALS\n!------------------------------------------------------------------------------------------!\n\nMODULE NOAHMP_GLACIER_ROUTINES\n  USE NOAHMP_GLACIER_GLOBALS\n  IMPLICIT NONE\n\n  public  :: NOAHMP_OPTIONS_GLACIER\n  public  :: NOAHMP_GLACIER\n\n  private :: ATM_GLACIER\n  private :: ENERGY_GLACIER\n  private ::       THERMOPROP_GLACIER\n  private ::               CSNOW_GLACIER\n  private ::       RADIATION_GLACIER\n  private ::               SNOW_AGE_GLACIER\n  private ::               SNOWALB_BATS_GLACIER\n  private ::               SNOWALB_CLASS_GLACIER\n  private ::       GLACIER_FLUX\n  private ::               SFCDIF1_GLACIER\n  private ::       TSNOSOI_GLACIER\n  private ::               HRT_GLACIER\n  private ::               HSTEP_GLACIER\n  private ::                         ROSR12_GLACIER\n  private ::       PHASECHANGE_GLACIER\n\n  private :: WATER_GLACIER\n  private ::       SNOWWATER_GLACIER\n  private ::               SNOWFALL_GLACIER\n  private ::               COMBINE_GLACIER\n  private ::               DIVIDE_GLACIER\n  private ::                         COMBO_GLACIER\n  private ::               COMPACT_GLACIER\n  private ::               SNOWH2O_GLACIER\n\n  private :: ERROR_GLACIER\n\ncontains\n!\n! ==================================================================================================\n\n  SUBROUTINE NOAHMP_GLACIER (&\n                   ILOC    ,JLOC    ,COSZ    ,NSNOW   ,NSOIL   ,DT      , & ! IN : Time/Space/Model-related\n                   SFCTMP  ,SFCPRS  ,UU      ,VV      ,Q2      ,SOLDN   , & ! IN : Forcing\n                   PRCP    ,LWDN    ,TBOT    ,ZLVL    ,FICEOLD ,ZSOIL   , & ! IN : Forcing\n                   SWE_LIMIT                                            , & ! IN : Forcing\n                   QSNOW, QRAIN,  SNEQVO,  ALBOLD,  CM,   CH   ,ISNOW   , & ! IN/OUT :\n                   SNEQV   ,SMC     ,ZSNSO   ,SNOWH   ,SNICE   ,SNLIQ   , & ! IN/OUT :\n                   TG      ,STC     ,SH2O    ,TAUSS   ,QSFC    ,          & ! IN/OUT :\n                   FSA     ,FSR     ,FIRA    ,FSH     ,FGEV    ,SSOIL   , & ! OUT :\n                   TRAD    ,EDIR    ,RUNSRF  ,RUNSUB  ,SAG     ,ALBEDO  , & ! OUT :\n                   QSNBOT  ,PONDING ,PONDING1,PONDING2,T2M     ,Q2E     , & ! OUT :\n                   EMISSI,  FPICE,    CH2B                                & ! OUT :\n#ifdef WRF_HYDRO\n                   , sfcheadrt                                            &\n#endif\n                   )\n\n! --------------------------------------------------------------------------------------------------\n! Initial code: Guo-Yue Niu, Oct. 2007\n! Modified to glacier: Michael Barlage, June 2012\n! --------------------------------------------------------------------------------------------------\n  implicit none\n! --------------------------------------------------------------------------------------------------\n! input\n  INTEGER                        , INTENT(IN)    :: ILOC   !grid index\n  INTEGER                        , INTENT(IN)    :: JLOC   !grid index\n  REAL                           , INTENT(IN)    :: COSZ   !cosine solar zenith angle [0-1]\n  INTEGER                        , INTENT(IN)    :: NSNOW  !maximum no. of snow layers\n  INTEGER                        , INTENT(IN)    :: NSOIL  !no. of soil layers\n  REAL                           , INTENT(IN)    :: DT     !time step [sec]\n  REAL                           , INTENT(IN)    :: SFCTMP !surface air temperature [K]\n  REAL                           , INTENT(IN)    :: SFCPRS !pressure (pa)\n  REAL                           , INTENT(IN)    :: UU     !wind speed in eastward dir (m/s)\n  REAL                           , INTENT(IN)    :: VV     !wind speed in northward dir (m/s)\n  REAL                           , INTENT(IN)    :: Q2     !mixing ratio (kg/kg) lowest model layer\n  REAL                           , INTENT(IN)    :: SOLDN  !downward shortwave radiation (w/m2)\n  REAL                           , INTENT(IN)    :: PRCP   !precipitation rate (kg m-2 s-1)\n  REAL                           , INTENT(IN)    :: LWDN   !downward longwave radiation (w/m2)\n  REAL                           , INTENT(IN)    :: TBOT   !bottom condition for soil temp. [K]\n  REAL                           , INTENT(IN)    :: ZLVL   !reference height (m)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: FICEOLD!ice fraction at last timestep\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: ZSOIL  !layer-bottom depth from soil surf (m)\n  REAL                           , INTENT(IN)    :: SWE_LIMIT   !maximum SWE limit (mm)\n\n#ifdef WRF_HYDRO\n  REAL                           , INTENT(INOUT)    :: sfcheadrt\n#endif\n\n! input/output : need arbitary intial values\n  REAL                           , INTENT(INOUT) :: QSNOW  !snowfall [mm/s]\n  REAL                           , INTENT(INOUT) :: QRAIN  !rainfall [mm/s]\n  REAL                           , INTENT(INOUT) :: SNEQVO !snow mass at last time step (mm)\n  REAL                           , INTENT(INOUT) :: ALBOLD !snow albedo at last time step (CLASS type)\n  REAL                           , INTENT(INOUT) :: CM     !momentum drag coefficient\n  REAL                           , INTENT(INOUT) :: CH     !sensible heat exchange coefficient\n\n! prognostic variables\n  INTEGER                        , INTENT(INOUT) :: ISNOW  !actual no. of snow layers [-]\n  REAL                           , INTENT(INOUT) :: SNEQV  !snow water eqv. [mm]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SMC    !soil moisture (ice + liq.) [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: ZSNSO  !layer-bottom depth from snow surf [m]\n  REAL                           , INTENT(INOUT) :: SNOWH  !snow height [m]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE  !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ  !snow layer liquid water [mm]\n  REAL                           , INTENT(INOUT) :: TG     !ground temperature (k)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow/soil temperature [k]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O   !liquid soil moisture [m3/m3]\n  REAL                           , INTENT(INOUT) :: TAUSS  !non-dimensional snow age\n  REAL                           , INTENT(INOUT) :: QSFC   !mixing ratio at lowest model layer\n\n! output\n  REAL                           , INTENT(OUT)   :: FSA    !total absorbed solar radiation (w/m2)\n  REAL                           , INTENT(OUT)   :: FSR    !total reflected solar radiation (w/m2)\n  REAL                           , INTENT(OUT)   :: FIRA   !total net LW rad (w/m2)  [+ to atm]\n  REAL                           , INTENT(OUT)   :: FSH    !total sensible heat (w/m2) [+ to atm]\n  REAL                           , INTENT(OUT)   :: FGEV   !ground evap heat (w/m2) [+ to atm]\n  REAL                           , INTENT(OUT)   :: SSOIL  !ground heat flux (w/m2)   [+ to soil]\n  REAL                           , INTENT(OUT)   :: TRAD   !surface radiative temperature (k)\n  REAL                           , INTENT(OUT)   :: EDIR   !soil surface evaporation rate (mm/s]\n  REAL                           , INTENT(OUT)   :: RUNSRF !surface runoff [mm/s]\n  REAL                           , INTENT(OUT)   :: RUNSUB !baseflow (saturation excess) [mm/s]\n  REAL                           , INTENT(OUT)   :: SAG    !solar rad absorbed by ground (w/m2)\n  REAL                           , INTENT(OUT)   :: ALBEDO !surface albedo [-]\n  REAL                           , INTENT(OUT)   :: QSNBOT !snowmelt [mm/s]\n  REAL                           , INTENT(OUT)   :: PONDING!surface ponding [mm]\n  REAL                           , INTENT(OUT)   :: PONDING1!surface ponding [mm]\n  REAL                           , INTENT(OUT)   :: PONDING2!surface ponding [mm]\n  REAL                           , INTENT(OUT)   :: T2M     !2-m air temperature over bare ground part [k]\n  REAL                           , INTENT(OUT)   :: Q2E\n  REAL                           , INTENT(OUT)   :: EMISSI\n  REAL                           , INTENT(OUT)   :: FPICE\n  REAL                           , INTENT(OUT)   :: CH2B\n\n! local\n  INTEGER                                        :: IZ     !do-loop index\n  INTEGER, DIMENSION(-NSNOW+1:NSOIL)             :: IMELT  !phase change index [1-melt; 2-freeze]\n  REAL                                           :: RHOAIR !density air (kg/m3)\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                :: DZSNSO !snow/soil layer thickness [m]\n  REAL                                           :: THAIR  !potential temperature (k)\n  REAL                                           :: QAIR   !specific humidity (kg/kg) (q2/(1+q2))\n  REAL                                           :: EAIR   !vapor pressure air (pa)\n  REAL, DIMENSION(       1:    2)                :: SOLAD  !incoming direct solar rad (w/m2)\n  REAL, DIMENSION(       1:    2)                :: SOLAI  !incoming diffuse solar rad (w/m2)\n  REAL, DIMENSION(       1:NSOIL)                :: SICE   !soil ice content (m3/m3)\n  REAL, DIMENSION(-NSNOW+1:    0)                :: SNICEV !partial volume ice of snow [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0)                :: SNLIQV !partial volume liq of snow [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0)                :: EPORE  !effective porosity [m3/m3]\n  REAL                                           :: QDEW   !ground surface dew rate [mm/s]\n  REAL                                           :: QVAP   !ground surface evap. rate [mm/s]\n  REAL                                           :: LATHEA !latent heat [j/kg]\n  REAL                                           :: QMELT  !internal pack melt\n  REAL                                           :: SWDOWN !downward solar [w/m2]\n  REAL                                           :: BEG_WB !beginning water for error check\n  REAL                                           :: ZBOT = -8.0\n\n  CHARACTER*256 message\n\n! --------------------------------------------------------------------------------------------------\n! re-process atmospheric forcing\n\n   CALL ATM_GLACIER (SFCPRS ,SFCTMP ,Q2     ,SOLDN  ,COSZ   ,THAIR  , &\n                     QAIR   ,EAIR   ,RHOAIR ,SOLAD  ,SOLAI  ,SWDOWN )\n\n   BEG_WB = SNEQV\n\n! snow/soil layer thickness (m); interface depth: ZSNSO < 0; layer thickness DZSNSO > 0\n\n     DO IZ = ISNOW+1, NSOIL\n         IF(IZ == ISNOW+1) THEN\n           DZSNSO(IZ) = - ZSNSO(IZ)\n         ELSE\n           DZSNSO(IZ) = ZSNSO(IZ-1) - ZSNSO(IZ)\n         END IF\n     END DO\n\n! compute energy budget (momentum & energy fluxes and phase changes)\n\n    CALL ENERGY_GLACIER (NSNOW  ,NSOIL  ,ISNOW  ,DT     ,QSNOW  ,RHOAIR , & !in\n                         EAIR   ,SFCPRS ,QAIR   ,SFCTMP ,LWDN   ,UU     , & !in\n                         VV     ,SOLAD  ,SOLAI  ,COSZ   ,ZLVL   ,         & !in\n                         TBOT   ,ZBOT   ,ZSNSO  ,DZSNSO ,                 & !in\n                         TG     ,STC    ,SNOWH  ,SNEQV  ,SNEQVO ,SH2O   , & !inout\n                         SMC    ,SNICE  ,SNLIQ  ,ALBOLD ,CM     ,CH     , & !inout\n                         TAUSS  ,QSFC   ,                                 & !inout\n                         IMELT  ,SNICEV ,SNLIQV ,EPORE  ,QMELT  ,PONDING, & !out\n\t\t         SAG    ,FSA    ,FSR    ,FIRA   ,FSH    ,FGEV   , & !out\n\t\t         TRAD   ,T2M    ,SSOIL  ,LATHEA ,Q2E    ,EMISSI, CH2B )   !out\n\n    SICE = MAX(0.0, SMC - SH2O)\n    SNEQVO  = SNEQV\n\n    QVAP = MAX( FGEV/LATHEA, 0.)       ! positive part of fgev [mm/s] > 0\n    QDEW = ABS( MIN(FGEV/LATHEA, 0.))  ! negative part of fgev [mm/s] > 0\n    EDIR = QVAP - QDEW\n\n! compute water budgets (water storages, ET components, and runoff)\n\n     CALL WATER_GLACIER (NSNOW  ,NSOIL  ,IMELT  ,DT     ,PRCP   ,SFCTMP , & !in\n                         QVAP   ,QDEW   ,FICEOLD,ZSOIL  , SWE_LIMIT     , & !in\n                         ISNOW  ,SNOWH  ,SNEQV  ,SNICE  ,SNLIQ  ,STC    , & !inout\n                         DZSNSO ,SH2O   ,SICE   ,PONDING,ZSNSO  ,FSH    , & !inout\n                         RUNSRF ,RUNSUB ,QSNOW, QRAIN, PONDING1, PONDING2,QSNBOT,FPICE &  !out\n#ifdef WRF_HYDRO\n                        , sfcheadrt                     &\n#endif\n                        )\n\n     IF(OPT_GLA == 2) THEN\n       EDIR = QVAP - QDEW\n       FGEV = EDIR * LATHEA\n     END IF\n\n     IF(MAXVAL(SICE) < 0.0001) THEN\n       WRITE(message,*) \"GLACIER HAS MELTED AT:\",ILOC,JLOC,\" ARE YOU SURE THIS SHOULD BE A GLACIER POINT?\"\n       CALL wrf_debug(10,TRIM(message))\n     END IF\n\n! water and energy balance check\n\n     CALL ERROR_GLACIER (ILOC   ,JLOC   ,SWDOWN ,FSA    ,FSR    ,FIRA   , &\n                         FSH    ,FGEV   ,SSOIL  ,SAG    ,PRCP   ,EDIR   , &\n\t\t         RUNSRF ,RUNSUB ,SNEQV  ,DT     ,BEG_WB )\n\n    IF(SNOWH <= 1.E-6 .OR. SNEQV <= 1.E-3) THEN\n     SNOWH = 0.0\n     SNEQV = 0.0\n    END IF\n\n    IF(SWDOWN.NE.0.) THEN\n      ALBEDO = FSR / SWDOWN\n    ELSE\n      ALBEDO = -999.9\n    END IF\n\n\n  END SUBROUTINE NOAHMP_GLACIER\n! ==================================================================================================\n  SUBROUTINE ATM_GLACIER (SFCPRS ,SFCTMP ,Q2     ,SOLDN  ,COSZ   ,THAIR  , &\n                          QAIR   ,EAIR   ,RHOAIR ,SOLAD  ,SOLAI  , &\n                          SWDOWN )\n! --------------------------------------------------------------------------------------------------\n! re-process atmospheric forcing\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n\n  REAL                          , INTENT(IN)  :: SFCPRS !pressure (pa)\n  REAL                          , INTENT(IN)  :: SFCTMP !surface air temperature [k]\n  REAL                          , INTENT(IN)  :: Q2     !mixing ratio (kg/kg)\n  REAL                          , INTENT(IN)  :: SOLDN  !downward shortwave radiation (w/m2)\n  REAL                          , INTENT(IN)  :: COSZ   !cosine solar zenith angle [0-1]\n\n! outputs\n\n  REAL                          , INTENT(OUT) :: THAIR  !potential temperature (k)\n  REAL                          , INTENT(OUT) :: QAIR   !specific humidity (kg/kg) (q2/(1+q2))\n  REAL                          , INTENT(OUT) :: EAIR   !vapor pressure air (pa)\n  REAL, DIMENSION(       1:   2), INTENT(OUT) :: SOLAD  !incoming direct solar radiation (w/m2)\n  REAL, DIMENSION(       1:   2), INTENT(OUT) :: SOLAI  !incoming diffuse solar radiation (w/m2)\n  REAL                          , INTENT(OUT) :: RHOAIR !density air (kg/m3)\n  REAL                          , INTENT(OUT) :: SWDOWN !downward solar filtered by sun angle [w/m2]\n\n!locals\n\n  REAL                                        :: PAIR   !atm bottom level pressure (pa)\n! --------------------------------------------------------------------------------------------------\n\n       PAIR   = SFCPRS                   ! atm bottom level pressure (pa)\n       THAIR  = SFCTMP * (SFCPRS/PAIR)**(RAIR/CPAIR)\n!       QAIR   = Q2 / (1.0+Q2)           ! mixing ratio to specific humidity [kg/kg]\n       QAIR   = Q2                       ! In WRF, driver converts to specific humidity\n\n       EAIR   = QAIR*SFCPRS / (0.622+0.378*QAIR)\n       RHOAIR = (SFCPRS-0.378*EAIR) / (RAIR*SFCTMP)\n\n       IF(COSZ <= 0.) THEN\n          SWDOWN = 0.\n       ELSE\n          SWDOWN = SOLDN\n       END IF\n\n       SOLAD(1) = SWDOWN*0.7*0.5     ! direct  vis\n       SOLAD(2) = SWDOWN*0.7*0.5     ! direct  nir\n       SOLAI(1) = SWDOWN*0.3*0.5     ! diffuse vis\n       SOLAI(2) = SWDOWN*0.3*0.5     ! diffuse nir\n\n  END SUBROUTINE ATM_GLACIER\n! ==================================================================================================\n! --------------------------------------------------------------------------------------------------\n  SUBROUTINE ENERGY_GLACIER (NSNOW  ,NSOIL  ,ISNOW  ,DT     ,QSNOW  ,RHOAIR , & !in\n                             EAIR   ,SFCPRS ,QAIR   ,SFCTMP ,LWDN   ,UU     , & !in\n                             VV     ,SOLAD  ,SOLAI  ,COSZ   ,ZREF   ,         & !in\n                             TBOT   ,ZBOT   ,ZSNSO  ,DZSNSO ,                 & !in\n                             TG     ,STC    ,SNOWH  ,SNEQV  ,SNEQVO ,SH2O   , & !inout\n                             SMC    ,SNICE  ,SNLIQ  ,ALBOLD ,CM     ,CH     , & !inout\n                             TAUSS  ,QSFC   ,                                 & !inout\n                             IMELT  ,SNICEV ,SNLIQV ,EPORE  ,QMELT  ,PONDING, & !out\n                             SAG    ,FSA    ,FSR    ,FIRA   ,FSH    ,FGEV   , & !out\n                             TRAD   ,T2M    ,SSOIL  ,LATHEA ,Q2E    ,EMISSI, CH2B )   !out\n\n! --------------------------------------------------------------------------------------------------\n! --------------------------------------------------------------------------------------------------\n!  USE NOAHMP_VEG_PARAMETERS\n!  USE NOAHMP_RAD_PARAMETERS\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n  INTEGER                           , INTENT(IN)    :: NSNOW  !maximum no. of snow layers\n  INTEGER                           , INTENT(IN)    :: NSOIL  !number of soil layers\n  INTEGER                           , INTENT(IN)    :: ISNOW  !actual no. of snow layers\n  REAL                              , INTENT(IN)    :: DT     !time step [sec]\n  REAL                              , INTENT(IN)    :: QSNOW  !snowfall on the ground (mm/s)\n  REAL                              , INTENT(IN)    :: RHOAIR !density air (kg/m3)\n  REAL                              , INTENT(IN)    :: EAIR   !vapor pressure air (pa)\n  REAL                              , INTENT(IN)    :: SFCPRS !pressure (pa)\n  REAL                              , INTENT(IN)    :: QAIR   !specific humidity (kg/kg)\n  REAL                              , INTENT(IN)    :: SFCTMP !air temperature (k)\n  REAL                              , INTENT(IN)    :: LWDN   !downward longwave radiation (w/m2)\n  REAL                              , INTENT(IN)    :: UU     !wind speed in e-w dir (m/s)\n  REAL                              , INTENT(IN)    :: VV     !wind speed in n-s dir (m/s)\n  REAL   , DIMENSION(       1:    2), INTENT(IN)    :: SOLAD  !incoming direct solar rad. (w/m2)\n  REAL   , DIMENSION(       1:    2), INTENT(IN)    :: SOLAI  !incoming diffuse solar rad. (w/m2)\n  REAL                              , INTENT(IN)    :: COSZ   !cosine solar zenith angle (0-1)\n  REAL                              , INTENT(IN)    :: ZREF   !reference height (m)\n  REAL                              , INTENT(IN)    :: TBOT   !bottom condition for soil temp. (k)\n  REAL                              , INTENT(IN)    :: ZBOT   !depth for TBOT [m]\n  REAL   , DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)    :: ZSNSO  !layer-bottom depth from snow surf [m]\n  REAL   , DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)    :: DZSNSO !depth of snow & soil layer-bottom [m]\n\n! input & output\n  REAL                              , INTENT(INOUT) :: TG     !ground temperature (k)\n  REAL   , DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow/soil temperature [k]\n  REAL                              , INTENT(INOUT) :: SNOWH  !snow height [m]\n  REAL                              , INTENT(INOUT) :: SNEQV  !snow mass (mm)\n  REAL                              , INTENT(INOUT) :: SNEQVO !snow mass at last time step (mm)\n  REAL   , DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O   !liquid soil moisture [m3/m3]\n  REAL   , DIMENSION(       1:NSOIL), INTENT(INOUT) :: SMC    !soil moisture (ice + liq.) [m3/m3]\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE  !snow ice mass (kg/m2)\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ  !snow liq mass (kg/m2)\n  REAL                              , INTENT(INOUT) :: ALBOLD !snow albedo at last time step(CLASS type)\n  REAL                              , INTENT(INOUT) :: CM     !momentum drag coefficient\n  REAL                              , INTENT(INOUT) :: CH     !sensible heat exchange coefficient\n  REAL                              , INTENT(INOUT) :: TAUSS  !snow aging factor\n  REAL                              , INTENT(INOUT) :: QSFC   !mixing ratio at lowest model layer\n\n! outputs\n  INTEGER, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT)   :: IMELT  !phase change index [1-melt; 2-freeze]\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(OUT)   :: SNICEV !partial volume ice [m3/m3]\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(OUT)   :: SNLIQV !partial volume liq. water [m3/m3]\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(OUT)   :: EPORE  !effective porosity [m3/m3]\n  REAL                              , INTENT(OUT)   :: QMELT  !snowmelt [mm/s]\n  REAL                              , INTENT(OUT)   :: PONDING!pounding at ground [mm]\n  REAL                              , INTENT(OUT)   :: SAG    !solar rad. absorbed by ground (w/m2)\n  REAL                              , INTENT(OUT)   :: FSA    !tot. absorbed solar radiation (w/m2)\n  REAL                              , INTENT(OUT)   :: FSR    !tot. reflected solar radiation (w/m2)\n  REAL                              , INTENT(OUT)   :: FIRA   !total net LW. rad (w/m2)   [+ to atm]\n  REAL                              , INTENT(OUT)   :: FSH    !total sensible heat (w/m2) [+ to atm]\n  REAL                              , INTENT(OUT)   :: FGEV   !ground evaporation (w/m2)  [+ to atm]\n  REAL                              , INTENT(OUT)   :: TRAD   !radiative temperature (k)\n  REAL                              , INTENT(OUT)   :: T2M    !2 m height air temperature (k)\n  REAL                              , INTENT(OUT)   :: SSOIL  !ground heat flux (w/m2)   [+ to soil]\n  REAL                              , INTENT(OUT)   :: LATHEA !latent heat vap./sublimation (j/kg)\n  REAL                              , INTENT(OUT)   :: Q2E\n  REAL                              , INTENT(OUT)   :: EMISSI\n  REAL                              , INTENT(OUT)   :: CH2B   !sensible heat conductance, canopy air to ZLVL air (m/s)\n\n\n! local\n  REAL                                              :: UR     !wind speed at height ZLVL (m/s)\n  REAL                                              :: ZLVL   !reference height (m)\n  REAL                                              :: RSURF  !ground surface resistance (s/m)\n  REAL                                              :: ZPD    !zero plane displacement (m)\n  REAL                                              :: Z0MG   !z0 momentum, ground (m)\n  REAL                                              :: EMG    !ground emissivity\n  REAL                                              :: FIRE   !emitted IR (w/m2)\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                   :: FACT   !temporary used in phase change\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                   :: DF     !thermal conductivity [w/m/k]\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                   :: HCPCT  !heat capacity [j/m3/k]\n  REAL                                              :: GAMMA  !psychrometric constant (pa/k)\n  REAL                                              :: RHSUR  !raltive humidity in surface soil/snow air space (-)\n\n! ---------------------------------------------------------------------------------------------------\n\n! wind speed at reference height: ur >= 1\n\n    UR = MAX( SQRT(UU**2.+VV**2.), 1. )\n\n! roughness length and displacement height\n\n     Z0MG = Z0SNO\n     ZPD  = SNOWH\n\n     ZLVL = ZPD + ZREF\n\n! Thermal properties of soil, snow, lake, and frozen soil\n\n  CALL THERMOPROP_GLACIER (NSOIL   ,NSNOW   ,ISNOW   ,DZSNSO  ,          & !in\n                           DT      ,SNOWH   ,SNICE   ,SNLIQ   ,          & !in\n                           DF      ,HCPCT   ,SNICEV  ,SNLIQV  ,EPORE   , & !out\n                           FACT    )                                       !out\n\n! Solar radiation: absorbed & reflected by the ground\n\n  CALL  RADIATION_GLACIER (DT      ,TG      ,SNEQVO  ,SNEQV   ,COSZ    , & !in\n                           QSNOW   ,SOLAD   ,SOLAI   ,                   & !in\n                           ALBOLD  ,TAUSS   ,                            & !inout\n                           SAG     ,FSR     ,FSA)                          !out\n\n! vegetation and ground emissivity\n\n     EMG = 0.98\n\n! soil surface resistance for ground evap.\n\n     RHSUR = 1.0\n     RSURF = 1.0\n\n! set psychrometric constant\n\n     LATHEA = HSUB\n     GAMMA = CPAIR*SFCPRS/(0.622*LATHEA)\n\n! Surface temperatures of the ground and energy fluxes\n\n    CALL GLACIER_FLUX (NSOIL   ,NSNOW   ,EMG     ,ISNOW   ,DF      ,DZSNSO  ,Z0MG    , & !in\n                       ZLVL    ,ZPD     ,QAIR    ,SFCTMP  ,RHOAIR  ,SFCPRS  , & !in\n\t\t       UR      ,GAMMA   ,RSURF   ,LWDN    ,RHSUR   ,SMC     , & !in\n\t\t       EAIR    ,STC     ,SAG     ,SNOWH   ,LATHEA  ,SH2O    , & !in\n\t\t       CM      ,CH      ,TG      ,QSFC    ,          & !inout\n\t\t       FIRA    ,FSH     ,FGEV    ,SSOIL   ,          & !out\n\t\t       T2M     ,Q2E     ,CH2B)                         !out\n\n!energy balance at surface: SAG=(IRB+SHB+EVB+GHB)\n\n    FIRE = LWDN + FIRA\n\n    IF(FIRE <=0.) call wrf_error_fatal(\"STOP in Noah-MP: emitted longwave <0\")\n\n    ! Compute a net emissivity\n    EMISSI = EMG\n\n    ! When we're computing a TRAD, subtract from the emitted IR the\n    ! reflected portion of the incoming LWDN, so we're just\n    ! considering the IR originating in the canopy/ground system.\n\n    TRAD = ( ( FIRE - (1-EMISSI)*LWDN ) / (EMISSI*SB) ) ** 0.25\n\n! 3L snow & 4L soil temperatures\n\n    CALL TSNOSOI_GLACIER (NSOIL   ,NSNOW   ,ISNOW   ,DT      ,TBOT    , & !in\n                          SSOIL   ,SNOWH   ,ZBOT    ,ZSNSO   ,DF      , & !in\n\t\t          HCPCT   ,                                     & !in\n                          STC     )                                       !inout\n\n! adjusting snow surface temperature\n     IF(OPT_STC == 2) THEN\n      IF (SNOWH > 0.05 .AND. TG > TFRZ) TG = TFRZ\n     END IF\n\n! Energy released or consumed by snow & ice\n\n CALL PHASECHANGE_GLACIER (NSNOW   ,NSOIL   ,ISNOW   ,DT      ,FACT    , & !in\n                           DZSNSO  ,                                     & !in\n                           STC     ,SNICE   ,SNLIQ   ,SNEQV   ,SNOWH   , & !inout\n                           SMC     ,SH2O    ,                            & !inout\n                           QMELT   ,IMELT   ,PONDING )                     !out\n\n\n  END SUBROUTINE ENERGY_GLACIER\n! ==================================================================================================\n  SUBROUTINE THERMOPROP_GLACIER (NSOIL   ,NSNOW   ,ISNOW   ,DZSNSO  , & !in\n                                 DT      ,SNOWH   ,SNICE   ,SNLIQ   , & !in\n                                 DF      ,HCPCT   ,SNICEV  ,SNLIQV  ,EPORE   , & !out\n                                 FACT    )                                       !out\n! -------------------------------------------------------------------------------------------------\n! -------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n  INTEGER                        , INTENT(IN)  :: NSOIL   !number of soil layers\n  INTEGER                        , INTENT(IN)  :: NSNOW   !maximum no. of snow layers\n  INTEGER                        , INTENT(IN)  :: ISNOW   !actual no. of snow layers\n  REAL                           , INTENT(IN)  :: DT      !time step [s]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)  :: SNICE   !snow ice mass (kg/m2)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)  :: SNLIQ   !snow liq mass (kg/m2)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: DZSNSO  !thickness of snow/soil layers [m]\n  REAL                           , INTENT(IN)  :: SNOWH   !snow height [m]\n\n! outputs\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: DF      !thermal conductivity [w/m/k]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: HCPCT   !heat capacity [j/m3/k]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: SNICEV  !partial volume of ice [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: SNLIQV  !partial volume of liquid water [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: EPORE   !effective porosity [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: FACT    !computing energy for phase change\n! --------------------------------------------------------------------------------------------------\n! locals\n\n  INTEGER :: IZ, IZ2\n  REAL, DIMENSION(-NSNOW+1:    0)              :: CVSNO   !volumetric specific heat (j/m3/k)\n  REAL, DIMENSION(-NSNOW+1:    0)              :: TKSNO   !snow thermal conductivity (j/m3/k)\n\n!++ Model crashed (divided by zero) with REAL instead of REAL*8\n  REAL*8                                         :: ZMID    !mid-point soil depth\n\n! --------------------------------------------------------------------------------------------------\n\n! compute snow thermal conductivity and heat capacity\n\n    CALL CSNOW_GLACIER (ISNOW   ,NSNOW   ,NSOIL   ,SNICE   ,SNLIQ   ,DZSNSO  , & !in\n                        TKSNO   ,CVSNO   ,SNICEV  ,SNLIQV  ,EPORE   )   !out\n\n    DO IZ = ISNOW+1, 0\n      DF   (IZ) = TKSNO(IZ)\n      HCPCT(IZ) = CVSNO(IZ)\n    END DO\n\n! compute soil thermal properties (using Noah glacial ice approximations)\n\n    DO  IZ = 1, NSOIL\n       ZMID      = 0.5 * (DZSNSO(IZ))\n       DO IZ2 = 1, IZ-1\n         ZMID = ZMID + DZSNSO(IZ2)\n       END DO\n       HCPCT(IZ) = 1.E6 * ( 0.8194 + 0.1309*ZMID )\n       DF(IZ)    = 0.32333 + ( 0.10073 * ZMID )\n    END DO\n\n! combine a temporary variable used for melting/freezing of snow and frozen soil\n\n    DO IZ = ISNOW+1,NSOIL\n     FACT(IZ) = DT/(HCPCT(IZ)*DZSNSO(IZ))\n    END DO\n\n! snow/soil interface\n\n    IF(ISNOW == 0) THEN\n       DF(1) = (DF(1)*DZSNSO(1)+0.35*SNOWH)      / (SNOWH    +DZSNSO(1))\n    ELSE\n       DF(1) = (DF(1)*DZSNSO(1)+DF(0)*DZSNSO(0)) / (DZSNSO(0)+DZSNSO(1))\n    END IF\n\n\n  END SUBROUTINE THERMOPROP_GLACIER\n! ==================================================================================================\n! --------------------------------------------------------------------------------------------------\n  SUBROUTINE CSNOW_GLACIER (ISNOW   ,NSNOW   ,NSOIL   ,SNICE   ,SNLIQ   ,DZSNSO  , & !in\n                            TKSNO   ,CVSNO   ,SNICEV  ,SNLIQV  ,EPORE   )   !out\n! --------------------------------------------------------------------------------------------------\n! Snow bulk density,volumetric capacity, and thermal conductivity\n!---------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n!---------------------------------------------------------------------------------------------------\n! inputs\n\n  INTEGER,                          INTENT(IN) :: ISNOW  !number of snow layers (-)\n  INTEGER                        ,  INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  INTEGER                        ,  INTENT(IN) :: NSOIL  !number of soil layers\n  REAL, DIMENSION(-NSNOW+1:    0),  INTENT(IN) :: SNICE  !snow ice mass (kg/m2)\n  REAL, DIMENSION(-NSNOW+1:    0),  INTENT(IN) :: SNLIQ  !snow liq mass (kg/m2)\n  REAL, DIMENSION(-NSNOW+1:NSOIL),  INTENT(IN) :: DZSNSO !snow/soil layer thickness [m]\n\n! outputs\n\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: CVSNO  !volumetric specific heat (j/m3/k)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: TKSNO  !thermal conductivity (w/m/k)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: SNICEV !partial volume of ice [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: SNLIQV !partial volume of liquid water [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: EPORE  !effective porosity [m3/m3]\n\n! locals\n\n  INTEGER :: IZ\n  REAL, DIMENSION(-NSNOW+1:    0) :: BDSNOI  !bulk density of snow(kg/m3)\n\n!---------------------------------------------------------------------------------------------------\n! thermal capacity of snow\n\n  DO IZ = ISNOW+1, 0\n      SNICEV(IZ)   = MIN(1., SNICE(IZ)/(DZSNSO(IZ)*DENICE) )\n      EPORE(IZ)    = 1. - SNICEV(IZ)\n      SNLIQV(IZ)   = MIN(EPORE(IZ),SNLIQ(IZ)/(DZSNSO(IZ)*DENH2O))\n  ENDDO\n\n  DO IZ = ISNOW+1, 0\n      BDSNOI(IZ) = (SNICE(IZ)+SNLIQ(IZ))/DZSNSO(IZ)\n      CVSNO(IZ) = CICE*SNICEV(IZ)+CWAT*SNLIQV(IZ)\n!      CVSNO(IZ) = 0.525E06                          ! constant\n  enddo\n\n! thermal conductivity of snow\n\n  DO IZ = ISNOW+1, 0\n     TKSNO(IZ) = 3.2217E-6*BDSNOI(IZ)**2.           ! Stieglitz(yen,1965)\n!    TKSNO(IZ) = 2E-2+2.5E-6*BDSNOI(IZ)*BDSNOI(IZ)   ! Anderson, 1976\n!    TKSNO(IZ) = 0.35                                ! constant\n!    TKSNO(IZ) = 2.576E-6*BDSNOI(IZ)**2. + 0.074    ! Verseghy (1991)\n!    TKSNO(IZ) = 2.22*(BDSNOI(IZ)/1000.)**1.88      ! Douvill(Yen, 1981)\n  ENDDO\n\n  END SUBROUTINE CSNOW_GLACIER\n!===================================================================================================\n  SUBROUTINE RADIATION_GLACIER (DT      ,TG      ,SNEQVO  ,SNEQV   ,COSZ    , & !in\n                                QSNOW   ,SOLAD   ,SOLAI   ,                   & !in\n                                ALBOLD  ,TAUSS   ,                            & !inout\n                                SAG     ,FSR     ,FSA)                          !out\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n  REAL, INTENT(IN)                     :: DT     !time step [s]\n  REAL, INTENT(IN)                     :: TG     !ground temperature (k)\n  REAL, INTENT(IN)                     :: SNEQVO !snow mass at last time step(mm)\n  REAL, INTENT(IN)                     :: SNEQV  !snow mass (mm)\n  REAL, INTENT(IN)                     :: COSZ   !cosine solar zenith angle (0-1)\n  REAL, INTENT(IN)                     :: QSNOW  !snowfall (mm/s)\n  REAL, DIMENSION(1:2)    , INTENT(IN) :: SOLAD  !incoming direct solar radiation (w/m2)\n  REAL, DIMENSION(1:2)    , INTENT(IN) :: SOLAI  !incoming diffuse solar radiation (w/m2)\n\n! inout\n  REAL,                  INTENT(INOUT) :: ALBOLD !snow albedo at last time step (CLASS type)\n  REAL,                  INTENT(INOUT) :: TAUSS  !non-dimensional snow age\n\n! output\n  REAL, INTENT(OUT)                    :: SAG    !solar radiation absorbed by ground (w/m2)\n  REAL, INTENT(OUT)                    :: FSR    !total reflected solar radiation (w/m2)\n  REAL, INTENT(OUT)                    :: FSA    !total absorbed solar radiation (w/m2)\n\n! local\n  INTEGER                              :: IB     !number of radiation bands\n  INTEGER                              :: NBAND  !number of radiation bands\n  REAL                                 :: FAGE   !snow age function (0 - new snow)\n  REAL, DIMENSION(1:2)                 :: ALBSND !snow albedo (direct)\n  REAL, DIMENSION(1:2)                 :: ALBSNI !snow albedo (diffuse)\n  REAL                                 :: ALB    !current CLASS albedo\n  REAL                                 :: ABS    !temporary absorbed rad\n  REAL                                 :: REF    !temporary reflected rad\n  REAL                                 :: FSNO   !snow-cover fraction, = 1 if any snow\n  REAL, DIMENSION(1:2)                 :: ALBICE !albedo land ice: 1=vis, 2=nir\n\n  REAL,PARAMETER :: MPE = 1.E-6\n\n! --------------------------------------------------------------------------------------------------\n\n  NBAND = 2\n  ALBSND = 0.0\n  ALBSNI = 0.0\n  ALBICE(1) = 0.80    !albedo land ice: 1=vis, 2=nir\n  ALBICE(2) = 0.55\n\n! snow age\n\n  CALL SNOW_AGE_GLACIER (DT,TG,SNEQVO,SNEQV,TAUSS,FAGE)\n\n! snow albedos: age even when sun is not present\n\n  IF(OPT_ALB == 1) &\n     CALL SNOWALB_BATS_GLACIER (NBAND,COSZ,FAGE,ALBSND,ALBSNI)\n  IF(OPT_ALB == 2) THEN\n     CALL SNOWALB_CLASS_GLACIER(NBAND,QSNOW,DT,ALB,ALBOLD,ALBSND,ALBSNI)\n     ALBOLD = ALB\n  END IF\n\n! zero summed solar fluxes\n\n   SAG = 0.\n   FSA = 0.\n   FSR = 0.\n\n   FSNO = 0.0\n   IF(SNEQV > 0.0) FSNO = 1.0\n\n! loop over nband wavebands\n\n  DO IB = 1, NBAND\n\n    ALBSND(IB) = ALBICE(IB)*(1.-FSNO) + ALBSND(IB)*FSNO\n    ALBSNI(IB) = ALBICE(IB)*(1.-FSNO) + ALBSNI(IB)*FSNO\n\n! solar radiation absorbed by ground surface\n\n    ABS = SOLAD(IB)*(1.-ALBSND(IB)) + SOLAI(IB)*(1.-ALBSNI(IB))\n    SAG = SAG + ABS\n    FSA = FSA + ABS\n\n    REF = SOLAD(IB)*ALBSND(IB) + SOLAI(IB)*ALBSNI(IB)\n    FSR = FSR + REF\n\n  END DO\n\n  END SUBROUTINE RADIATION_GLACIER\n! ==================================================================================================\n  SUBROUTINE SNOW_AGE_GLACIER (DT,TG,SNEQVO,SNEQV,TAUSS,FAGE)\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! ------------------------ code history ------------------------------------------------------------\n! from BATS\n! ------------------------ input/output variables --------------------------------------------------\n!input\n   REAL, INTENT(IN) :: DT        !main time step (s)\n   REAL, INTENT(IN) :: TG        !ground temperature (k)\n   REAL, INTENT(IN) :: SNEQVO    !snow mass at last time step(mm)\n   REAL, INTENT(IN) :: SNEQV     !snow water per unit ground area (mm)\n\n! inout\n  REAL,  INTENT(INOUT) :: TAUSS  !non-dimensional snow age\n\n!output\n   REAL, INTENT(OUT) :: FAGE     !snow age\n\n!local\n   REAL            :: TAGE       !total aging effects\n   REAL            :: AGE1       !effects of grain growth due to vapor diffusion\n   REAL            :: AGE2       !effects of grain growth at freezing of melt water\n   REAL            :: AGE3       !effects of soot\n   REAL            :: DELA       !temporary variable\n   REAL            :: SGE        !temporary variable\n   REAL            :: DELS       !temporary variable\n   REAL            :: DELA0      !temporary variable\n   REAL            :: ARG        !temporary variable\n! See Yang et al. (1997) J.of Climate for detail.\n!---------------------------------------------------------------------------------------------------\n\n   IF(SNEQV.LE.0.0) THEN\n          TAUSS = 0.\n   ELSE IF (SNEQV.GT.800.) THEN\n          TAUSS = 0.\n   ELSE\n!          TAUSS = 0.\n          DELA0 = 1.E-6*DT\n          ARG   = 5.E3*(1./TFRZ-1./TG)\n          AGE1  = EXP(ARG)\n          AGE2  = EXP(AMIN1(0.,10.*ARG))\n          AGE3  = 0.3\n          TAGE  = AGE1+AGE2+AGE3\n          DELA  = DELA0*TAGE\n          DELS  = AMAX1(0.0,SNEQV-SNEQVO) / SWEMX\n          SGE   = (TAUSS+DELA)*(1.0-DELS)\n          TAUSS = AMAX1(0.,SGE)\n   ENDIF\n\n   FAGE= TAUSS/(TAUSS+1.)\n\n  END SUBROUTINE SNOW_AGE_GLACIER\n! ==================================================================================================\n! --------------------------------------------------------------------------------------------------\n  SUBROUTINE SNOWALB_BATS_GLACIER (NBAND,COSZ,FAGE,ALBSND,ALBSNI)\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n\n  INTEGER,INTENT(IN) :: NBAND  !number of waveband classes\n\n  REAL,INTENT(IN) :: COSZ    !cosine solar zenith angle\n  REAL,INTENT(IN) :: FAGE    !snow age correction\n\n! output\n\n  REAL, DIMENSION(1:2),INTENT(OUT) :: ALBSND !snow albedo for direct(1=vis, 2=nir)\n  REAL, DIMENSION(1:2),INTENT(OUT) :: ALBSNI !snow albedo for diffuse\n! ---------------------------------------------------------------------------------------------\n\n  REAL :: FZEN                 !zenith angle correction\n  REAL :: CF1                  !temperary variable\n  REAL :: SL2                  !2.*SL\n  REAL :: SL1                  !1/SL\n  REAL :: SL                   !adjustable parameter\n  REAL, PARAMETER :: C1 = 0.2  !default in BATS\n  REAL, PARAMETER :: C2 = 0.5  !default in BATS\n!  REAL, PARAMETER :: C1 = 0.2 * 2. ! double the default to match Sleepers River's\n!  REAL, PARAMETER :: C2 = 0.5 * 2. ! snow surface albedo (double aging effects)\n! ---------------------------------------------------------------------------------------------\n! zero albedos for all points\n\n        ALBSND(1: NBAND) = 0.\n        ALBSNI(1: NBAND) = 0.\n\n! when cosz > 0\n\n        SL=2.0\n        SL1=1./SL\n        SL2=2.*SL\n        CF1=((1.+SL1)/(1.+SL2*COSZ)-SL1)\n        FZEN=AMAX1(CF1,0.)\n\n        ALBSNI(1)=0.95*(1.-C1*FAGE)\n        ALBSNI(2)=0.65*(1.-C2*FAGE)\n\n        ALBSND(1)=ALBSNI(1)+0.4*FZEN*(1.-ALBSNI(1))    !  vis direct\n        ALBSND(2)=ALBSNI(2)+0.4*FZEN*(1.-ALBSNI(2))    !  nir direct\n\n  END SUBROUTINE SNOWALB_BATS_GLACIER\n! ==================================================================================================\n! --------------------------------------------------------------------------------------------------\n  SUBROUTINE SNOWALB_CLASS_GLACIER (NBAND,QSNOW,DT,ALB,ALBOLD,ALBSND,ALBSNI)\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n\n  INTEGER,INTENT(IN) :: NBAND  !number of waveband classes\n\n  REAL,INTENT(IN) :: QSNOW     !snowfall (mm/s)\n  REAL,INTENT(IN) :: DT        !time step (sec)\n  REAL,INTENT(IN) :: ALBOLD    !snow albedo at last time step\n\n! in & out\n\n  REAL,                INTENT(INOUT) :: ALB        !\n! output\n\n  REAL, DIMENSION(1:2),INTENT(OUT) :: ALBSND !snow albedo for direct(1=vis, 2=nir)\n  REAL, DIMENSION(1:2),INTENT(OUT) :: ALBSNI !snow albedo for diffuse\n! ---------------------------------------------------------------------------------------------\n\n! ---------------------------------------------------------------------------------------------\n! zero albedos for all points\n\n        ALBSND(1: NBAND) = 0.\n        ALBSNI(1: NBAND) = 0.\n\n! when cosz > 0\n\n         ALB = 0.55 + (ALBOLD-0.55) * EXP(-0.01*DT/3600.)\n\n! 1 mm fresh snow(SWE) -- 10mm snow depth, assumed the fresh snow density 100kg/m3\n! here assume 1cm snow depth will fully cover the old snow\n\n         IF (QSNOW > 0.) then\n           ALB = ALB + MIN(QSNOW*DT,SWEMX) * (0.84-ALB)/(SWEMX)\n         ENDIF\n\n         ALBSNI(1)= ALB         ! vis diffuse\n         ALBSNI(2)= ALB         ! nir diffuse\n         ALBSND(1)= ALB         ! vis direct\n         ALBSND(2)= ALB         ! nir direct\n\n  END SUBROUTINE SNOWALB_CLASS_GLACIER\n! ==================================================================================================\n  SUBROUTINE GLACIER_FLUX (NSOIL   ,NSNOW   ,EMG     ,ISNOW   ,DF      ,DZSNSO  ,Z0M     , & !in\n                           ZLVL    ,ZPD     ,QAIR    ,SFCTMP  ,RHOAIR  ,SFCPRS  , & !in\n\t\t\t   UR      ,GAMMA   ,RSURF   ,LWDN    ,RHSUR   ,SMC     , & !in\n\t\t\t   EAIR    ,STC     ,SAG     ,SNOWH   ,LATHEA  ,SH2O    , & !in\n                           CM      ,CH      ,TGB     ,QSFC    ,          & !inout\n                           IRB     ,SHB     ,EVB     ,GHB     ,          & !out\n                           T2MB    ,Q2B     ,EHB2)                         !out\n\n! --------------------------------------------------------------------------------------------------\n! use newton-raphson iteration to solve ground (tg) temperature\n! that balances the surface energy budgets for glacier.\n\n! bare soil:\n! -SAB + IRB[TG] + SHB[TG] + EVB[TG] + GHB[TG] = 0\n! ----------------------------------------------------------------------\n!  USE MODULE_MODEL_CONSTANTS\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  INTEGER, INTENT(IN)                         :: NSNOW  !maximum no. of snow layers\n  INTEGER, INTENT(IN)                         :: NSOIL  !number of soil layers\n  REAL,                            INTENT(IN) :: EMG    !ground emissivity\n  INTEGER,                         INTENT(IN) :: ISNOW  !actual no. of snow layers\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DF     !thermal conductivity of snow/soil (w/m/k)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !thickness of snow/soil layers (m)\n  REAL,                            INTENT(IN) :: Z0M    !roughness length, momentum, ground (m)\n  REAL,                            INTENT(IN) :: ZLVL   !reference height (m)\n  REAL,                            INTENT(IN) :: ZPD    !zero plane displacement (m)\n  REAL,                            INTENT(IN) :: QAIR   !specific humidity at height zlvl (kg/kg)\n  REAL,                            INTENT(IN) :: SFCTMP !air temperature at reference height (k)\n  REAL,                            INTENT(IN) :: RHOAIR !density air (kg/m3)\n  REAL,                            INTENT(IN) :: SFCPRS !density air (kg/m3)\n  REAL,                            INTENT(IN) :: UR     !wind speed at height zlvl (m/s)\n  REAL,                            INTENT(IN) :: GAMMA  !psychrometric constant (pa/k)\n  REAL,                            INTENT(IN) :: RSURF  !ground surface resistance (s/m)\n  REAL,                            INTENT(IN) :: LWDN   !atmospheric longwave radiation (w/m2)\n  REAL,                            INTENT(IN) :: RHSUR  !raltive humidity in surface soil/snow air space (-)\n  REAL,                            INTENT(IN) :: EAIR   !vapor pressure air at height (pa)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: STC    !soil/snow temperature (k)\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: SMC    !soil moisture\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: SH2O   !soil liquid water\n  REAL,                            INTENT(IN) :: SAG    !solar radiation absorbed by ground (w/m2)\n  REAL,                            INTENT(IN) :: SNOWH  !actual snow depth [m]\n  REAL,                            INTENT(IN) :: LATHEA !latent heat of vaporization/subli (j/kg)\n\n! input/output\n  REAL,                         INTENT(INOUT) :: CM     !momentum drag coefficient\n  REAL,                         INTENT(INOUT) :: CH     !sensible heat exchange coefficient\n  REAL,                         INTENT(INOUT) :: TGB    !ground temperature (k)\n  REAL,                         INTENT(INOUT) :: QSFC   !mixing ratio at lowest model layer\n\n! output\n! -SAB + IRB[TG] + SHB[TG] + EVB[TG] + GHB[TG] = 0\n  REAL,                           INTENT(OUT) :: IRB    !net longwave rad (w/m2)   [+ to atm]\n  REAL,                           INTENT(OUT) :: SHB    !sensible heat flux (w/m2) [+ to atm]\n  REAL,                           INTENT(OUT) :: EVB    !latent heat flux (w/m2)   [+ to atm]\n  REAL,                           INTENT(OUT) :: GHB    !ground heat flux (w/m2)  [+ to soil]\n  REAL,                           INTENT(OUT) :: T2MB   !2 m height air temperature (k)\n  REAL,                           INTENT(OUT) :: Q2B    !bare ground heat conductance\n  REAL,                           INTENT(OUT) :: EHB2   !sensible heat conductance for diagnostics\n\n\n! local variables\n  INTEGER :: NITERB  !number of iterations for surface temperature\n  REAL    :: MPE     !prevents overflow error if division by zero\n  REAL    :: DTG        !change in tg, last iteration (k)\n  INTEGER :: MOZSGN  !number of times MOZ changes sign\n  REAL    :: MOZOLD     !Monin-Obukhov stability parameter from prior iteration\n  REAL    :: FM2          !Monin-Obukhov momentum adjustment at 2m\n  REAL    :: FH2          !Monin-Obukhov heat adjustment at 2m\n  REAL    :: CH2          !Surface exchange at 2m\n  REAL    :: H          !temporary sensible heat flux (w/m2)\n  REAL    :: FV         !friction velocity (m/s)\n  REAL    :: CIR        !coefficients for ir as function of ts**4\n  REAL    :: CGH        !coefficients for st as function of ts\n  REAL    :: CSH        !coefficients for sh as function of ts\n  REAL    :: CEV        !coefficients for ev as function of esat[ts]\n  REAL    :: CQ2B       !\n  INTEGER :: ITER    !iteration index\n  REAL    :: Z0H        !roughness length, sensible heat, ground (m)\n  REAL    :: MOZ        !Monin-Obukhov stability parameter\n  REAL    :: FM         !momentum stability correction, weighted by prior iters\n  REAL    :: FH         !sen heat stability correction, weighted by prior iters\n  REAL    :: RAMB       !aerodynamic resistance for momentum (s/m)\n  REAL    :: RAHB       !aerodynamic resistance for sensible heat (s/m)\n  REAL    :: RAWB       !aerodynamic resistance for water vapor (s/m)\n  REAL    :: ESTG       !saturation vapor pressure at tg (pa)\n  REAL    :: DESTG      !d(es)/dt at tg (pa/K)\n  REAL    :: ESATW      !es for water\n  REAL    :: ESATI      !es for ice\n  REAL    :: DSATW      !d(es)/dt at tg (pa/K) for water\n  REAL    :: DSATI      !d(es)/dt at tg (pa/K) for ice\n  REAL    :: A          !temporary calculation\n  REAL    :: B          !temporary calculation\n  REAL    :: T, TDC     !Kelvin to degree Celsius with limit -50 to +50\n  REAL, DIMENSION(       1:NSOIL) :: SICE   !soil ice\n\n  TDC(T)   = MIN( 50., MAX(-50.,(T-TFRZ)) )\n\n! -----------------------------------------------------------------\n! initialization variables that do not depend on stability iteration\n! -----------------------------------------------------------------\n        NITERB = 5\n        MPE    = 1E-6\n        DTG    = 0.\n        MOZ    = 0.\n        MOZSGN = 0\n        MOZOLD = 0.\n        H      = 0.\n        FV     = 0.1\n\n        CIR = EMG*SB\n        CGH = 2.*DF(ISNOW+1)/DZSNSO(ISNOW+1)\n\n! -----------------------------------------------------------------\n      loop3: DO ITER = 1, NITERB  ! begin stability iteration\n\n        Z0H = Z0M\n\n!       For now, only allow SFCDIF1 until others can be fixed\n\n        CALL SFCDIF1_GLACIER(ITER   ,ZLVL   ,ZPD    ,Z0H    ,Z0M    , & !in\n                     QAIR   ,SFCTMP ,H      ,RHOAIR ,MPE    ,UR     , & !in\n       &             MOZ    ,MOZSGN ,FM     ,FH     ,FM2    ,FH2    , & !inout\n       &             FV     ,CM     ,CH     ,CH2)                       !out\n\n        RAMB = MAX(1.,1./(CM*UR))\n        RAHB = MAX(1.,1./(CH*UR))\n        RAWB = RAHB\n\n! es and d(es)/dt evaluated at tg\n\n        T = TDC(TGB)\n        CALL ESAT(T, ESATW, ESATI, DSATW, DSATI)\n        IF (T .GT. 0.) THEN\n            ESTG  = ESATW\n            DESTG = DSATW\n        ELSE\n            ESTG  = ESATI\n            DESTG = DSATI\n        END IF\n\n        CSH = RHOAIR*CPAIR/RAHB\n\tIF(SNOWH > 0.0 .OR. OPT_GLA == 1) THEN\n          CEV = RHOAIR*CPAIR/GAMMA/(RSURF+RAWB)\n\tELSE\n\t  CEV = 0.0   ! don't allow any sublimation of glacier in opt_gla=2\n\tEND IF\n\n! surface fluxes and dtg\n\n        IRB   = CIR * TGB**4 - EMG*LWDN\n        SHB   = CSH * (TGB        - SFCTMP      )\n        EVB   = CEV * (ESTG*RHSUR - EAIR        )\n        GHB   = CGH * (TGB        - STC(ISNOW+1))\n\n        B     = SAG-IRB-SHB-EVB-GHB\n        A     = 4.*CIR*TGB**3 + CSH + CEV*DESTG + CGH\n        DTG   = B/A\n\n        IRB = IRB + 4.*CIR*TGB**3*DTG\n        SHB = SHB + CSH*DTG\n        EVB = EVB + CEV*DESTG*DTG\n        GHB = GHB + CGH*DTG\n\n! update ground surface temperature\n        TGB = TGB + DTG\n\n! for M-O length\n        H = CSH * (TGB - SFCTMP)\n\n        T = TDC(TGB)\n        CALL ESAT(T, ESATW, ESATI, DSATW, DSATI)\n        IF (T .GT. 0.) THEN\n            ESTG  = ESATW\n        ELSE\n            ESTG  = ESATI\n        END IF\n        QSFC = 0.622*(ESTG*RHSUR)/(SFCPRS-0.378*(ESTG*RHSUR))\n\n     END DO loop3 ! end stability iteration\n! -----------------------------------------------------------------\n\n! if snow on ground and TG > TFRZ: reset TG = TFRZ. reevaluate ground fluxes.\n\n     SICE = SMC - SH2O\n     IF(OPT_STC == 1 .OR. OPT_STC ==3) THEN\n     IF ((MAXVAL(SICE) > 0.0 .OR. SNOWH > 0.0) .AND. TGB > TFRZ .AND. OPT_GLA == 1) THEN\n          TGB = TFRZ\n          T = TDC(TGB)                              ! MB: recalculate ESTG\n          CALL ESAT(T, ESATW, ESATI, DSATW, DSATI)\n          ESTG  = ESATI\n          QSFC = 0.622*(ESTG*RHSUR)/(SFCPRS-0.378*(ESTG*RHSUR))\n          IRB = CIR * TGB**4 - EMG*LWDN\n          SHB = CSH * (TGB        - SFCTMP)\n          EVB = CEV * (ESTG*RHSUR - EAIR )          !ESTG reevaluate ?\n          GHB = SAG - (IRB+SHB+EVB)\n     END IF\n     END IF\n\n! 2m air temperature\n     EHB2  = FV*VKC/(LOG((2.+Z0H)/Z0H)-FH2)\n     CQ2B  = EHB2\n     IF (EHB2.lt.1.E-5 ) THEN\n       T2MB  = TGB\n       Q2B   = QSFC\n     ELSE\n       T2MB  = TGB - SHB/(RHOAIR*CPAIR) * 1./EHB2\n       Q2B   = QSFC - EVB/(LATHEA*RHOAIR)*(1./CQ2B + RSURF)\n     ENDIF\n\n! update CH\n     CH = 1./RAHB\n\n  END SUBROUTINE GLACIER_FLUX\n!  ==================================================================================================\n  SUBROUTINE ESAT(T, ESW, ESI, DESW, DESI)\n!---------------------------------------------------------------------------------------------------\n! use polynomials to calculate saturation vapor pressure and derivative with\n! respect to temperature: over water when t > 0 c and over ice when t <= 0 c\n  IMPLICIT NONE\n!---------------------------------------------------------------------------------------------------\n! in\n\n  REAL, intent(in)  :: T              !temperature\n\n!out\n\n  REAL, intent(out) :: ESW            !saturation vapor pressure over water (pa)\n  REAL, intent(out) :: ESI            !saturation vapor pressure over ice (pa)\n  REAL, intent(out) :: DESW           !d(esat)/dt over water (pa/K)\n  REAL, intent(out) :: DESI           !d(esat)/dt over ice (pa/K)\n\n! local\n\n  REAL :: A0,A1,A2,A3,A4,A5,A6  !coefficients for esat over water\n  REAL :: B0,B1,B2,B3,B4,B5,B6  !coefficients for esat over ice\n  REAL :: C0,C1,C2,C3,C4,C5,C6  !coefficients for dsat over water\n  REAL :: D0,D1,D2,D3,D4,D5,D6  !coefficients for dsat over ice\n\n  PARAMETER (A0=6.107799961    , A1=4.436518521E-01,  &\n             A2=1.428945805E-02, A3=2.650648471E-04,  &\n             A4=3.031240396E-06, A5=2.034080948E-08,  &\n             A6=6.136820929E-11)\n\n  PARAMETER (B0=6.109177956    , B1=5.034698970E-01,  &\n             B2=1.886013408E-02, B3=4.176223716E-04,  &\n             B4=5.824720280E-06, B5=4.838803174E-08,  &\n             B6=1.838826904E-10)\n\n  PARAMETER (C0= 4.438099984E-01, C1=2.857002636E-02,  &\n             C2= 7.938054040E-04, C3=1.215215065E-05,  &\n             C4= 1.036561403E-07, C5=3.532421810e-10,  &\n             C6=-7.090244804E-13)\n\n  PARAMETER (D0=5.030305237E-01, D1=3.773255020E-02,  &\n             D2=1.267995369E-03, D3=2.477563108E-05,  &\n             D4=3.005693132E-07, D5=2.158542548E-09,  &\n             D6=7.131097725E-12)\n\n  ESW  = 100.*(A0+T*(A1+T*(A2+T*(A3+T*(A4+T*(A5+T*A6))))))\n  ESI  = 100.*(B0+T*(B1+T*(B2+T*(B3+T*(B4+T*(B5+T*B6))))))\n  DESW = 100.*(C0+T*(C1+T*(C2+T*(C3+T*(C4+T*(C5+T*C6))))))\n  DESI = 100.*(D0+T*(D1+T*(D2+T*(D3+T*(D4+T*(D5+T*D6))))))\n\n  END SUBROUTINE ESAT\n! ==================================================================================================\n\n  SUBROUTINE SFCDIF1_GLACIER(ITER   ,ZLVL   ,ZPD    ,Z0H    ,Z0M    , & !in\n                     QAIR   ,SFCTMP ,H      ,RHOAIR ,MPE    ,UR     , & !in\n       &             MOZ    ,MOZSGN ,FM     ,FH     ,FM2    ,FH2    , & !inout\n       &             FV     ,CM     ,CH     ,CH2     )                  !out\n! -------------------------------------------------------------------------------------------------\n! computing surface drag coefficient CM for momentum and CH for heat\n! -------------------------------------------------------------------------------------------------\n    IMPLICIT NONE\n! -------------------------------------------------------------------------------------------------\n! inputs\n    INTEGER,              INTENT(IN) :: ITER   !iteration index\n    REAL,                 INTENT(IN) :: ZLVL   !reference height  (m)\n    REAL,                 INTENT(IN) :: ZPD    !zero plane displacement (m)\n    REAL,                 INTENT(IN) :: Z0H    !roughness length, sensible heat, ground (m)\n    REAL,                 INTENT(IN) :: Z0M    !roughness length, momentum, ground (m)\n    REAL,                 INTENT(IN) :: QAIR   !specific humidity at reference height (kg/kg)\n    REAL,                 INTENT(IN) :: SFCTMP !temperature at reference height (k)\n    REAL,                 INTENT(IN) :: H      !sensible heat flux (w/m2) [+ to atm]\n    REAL,                 INTENT(IN) :: RHOAIR !density air (kg/m**3)\n    REAL,                 INTENT(IN) :: MPE    !prevents overflow error if division by zero\n    REAL,                 INTENT(IN) :: UR     !wind speed (m/s)\n\n! in & out\n    REAL,              INTENT(INOUT) :: MOZ    !Monin-Obukhov stability (z/L)\n    INTEGER,           INTENT(INOUT) :: MOZSGN !number of times moz changes sign\n    REAL,              INTENT(INOUT) :: FM     !momentum stability correction, weighted by prior iters\n    REAL,              INTENT(INOUT) :: FH     !sen heat stability correction, weighted by prior iters\n    REAL,              INTENT(INOUT) :: FM2    !sen heat stability correction, weighted by prior iters\n    REAL,              INTENT(INOUT) :: FH2    !sen heat stability correction, weighted by prior iters\n\n! outputs\n    REAL,                INTENT(OUT) :: FV     !friction velocity (m/s)\n    REAL,                INTENT(OUT) :: CM     !drag coefficient for momentum\n    REAL,                INTENT(OUT) :: CH     !drag coefficient for heat\n    REAL,                INTENT(OUT) :: CH2    !drag coefficient for heat\n\n! locals\n    REAL    :: MOZOLD                   !Monin-Obukhov stability parameter from prior iteration\n    REAL    :: TMPCM                    !temporary calculation for CM\n    REAL    :: TMPCH                    !temporary calculation for CH\n    REAL    :: MOL                      !Monin-Obukhov length (m)\n    REAL    :: TVIR                     !temporary virtual temperature (k)\n    REAL    :: TMP1,TMP2,TMP3           !temporary calculation\n    REAL    :: FMNEW                    !stability correction factor, momentum, for current moz\n    REAL    :: FHNEW                    !stability correction factor, sen heat, for current moz\n    REAL    :: MOZ2                     !2/L\n    REAL    :: TMPCM2                   !temporary calculation for CM2\n    REAL    :: TMPCH2                   !temporary calculation for CH2\n    REAL    :: FM2NEW                   !stability correction factor, momentum, for current moz\n    REAL    :: FH2NEW                   !stability correction factor, sen heat, for current moz\n    REAL    :: TMP12,TMP22,TMP32        !temporary calculation\n\n    REAL    :: CMFM, CHFH, CM2FM2, CH2FH2\n\n\n! -------------------------------------------------------------------------------------------------\n! Monin-Obukhov stability parameter moz for next iteration\n\n    MOZOLD = MOZ\n\n    IF(ZLVL <= ZPD) THEN\n       write(*,*) 'WARNING: critical glacier problem: ZLVL <= ZPD; model stops', zlvl, zpd\n       call wrf_error_fatal(\"STOP in Noah-MP glacier\")\n    ENDIF\n\n    TMPCM = LOG((ZLVL-ZPD) / Z0M)\n    TMPCH = LOG((ZLVL-ZPD) / Z0H)\n    TMPCM2 = LOG((2.0 + Z0M) / Z0M)\n    TMPCH2 = LOG((2.0 + Z0H) / Z0H)\n\n    IF(ITER == 1) THEN\n       FV   = 0.0\n       MOZ  = 0.0\n       MOL  = 0.0\n       MOZ2 = 0.0\n    ELSE\n       TVIR = (1. + 0.61*QAIR) * SFCTMP\n       TMP1 = VKC * (GRAV/TVIR) * H/(RHOAIR*CPAIR)\n       IF (ABS(TMP1) .LE. MPE) TMP1 = MPE\n       MOL  = -1. * FV**3 / TMP1\n       MOZ  = MIN( (ZLVL-ZPD)/MOL, 1.)\n       MOZ2  = MIN( (2.0 + Z0H)/MOL, 1.)\n    ENDIF\n\n! accumulate number of times moz changes sign.\n\n    IF (MOZOLD*MOZ .LT. 0.) MOZSGN = MOZSGN+1\n    IF (MOZSGN .GE. 2) THEN\n       MOZ = 0.\n       FM = 0.\n       FH = 0.\n       MOZ2 = 0.\n       FM2 = 0.\n       FH2 = 0.\n    ENDIF\n\n! evaluate stability-dependent variables using moz from prior iteration\n    IF (MOZ .LT. 0.) THEN\n       TMP1 = (1. - 16.*MOZ)**0.25\n       TMP2 = LOG((1.+TMP1*TMP1)/2.)\n       TMP3 = LOG((1.+TMP1)/2.)\n       FMNEW = 2.*TMP3 + TMP2 - 2.*ATAN(TMP1) + 1.5707963\n       FHNEW = 2*TMP2\n\n! 2-meter\n       TMP12 = (1. - 16.*MOZ2)**0.25\n       TMP22 = LOG((1.+TMP12*TMP12)/2.)\n       TMP32 = LOG((1.+TMP12)/2.)\n       FM2NEW = 2.*TMP32 + TMP22 - 2.*ATAN(TMP12) + 1.5707963\n       FH2NEW = 2*TMP22\n    ELSE\n       FMNEW = -5.*MOZ\n       FHNEW = FMNEW\n       FM2NEW = -5.*MOZ2\n       FH2NEW = FM2NEW\n    ENDIF\n\n! except for first iteration, weight stability factors for previous\n! iteration to help avoid flip-flops from one iteration to the next\n\n    IF (ITER == 1) THEN\n       FM = FMNEW\n       FH = FHNEW\n       FM2 = FM2NEW\n       FH2 = FH2NEW\n    ELSE\n       FM = 0.5 * (FM+FMNEW)\n       FH = 0.5 * (FH+FHNEW)\n       FM2 = 0.5 * (FM2+FM2NEW)\n       FH2 = 0.5 * (FH2+FH2NEW)\n    ENDIF\n\n! exchange coefficients\n\n    FH = MIN(FH,0.9*TMPCH)\n    FM = MIN(FM,0.9*TMPCM)\n    FH2 = MIN(FH2,0.9*TMPCH2)\n    FM2 = MIN(FM2,0.9*TMPCM2)\n\n    CMFM = TMPCM-FM\n    CHFH = TMPCH-FH\n    CM2FM2 = TMPCM2-FM2\n    CH2FH2 = TMPCH2-FH2\n    IF(ABS(CMFM) <= MPE) CMFM = MPE\n    IF(ABS(CHFH) <= MPE) CHFH = MPE\n    IF(ABS(CM2FM2) <= MPE) CM2FM2 = MPE\n    IF(ABS(CH2FH2) <= MPE) CH2FH2 = MPE\n    CM  = VKC*VKC/(CMFM*CMFM)\n    CH  = VKC*VKC/(CMFM*CHFH)\n    CH2  = VKC*VKC/(CM2FM2*CH2FH2)\n\n! friction velocity\n\n    FV = UR * SQRT(CM)\n    CH2  = VKC*FV/CH2FH2\n\n  END SUBROUTINE SFCDIF1_GLACIER\n! ==================================================================================================\n  SUBROUTINE TSNOSOI_GLACIER (NSOIL   ,NSNOW   ,ISNOW   ,DT      ,TBOT    , & !in\n                              SSOIL   ,SNOWH   ,ZBOT    ,ZSNSO   ,DF      , & !in\n\t\t\t      HCPCT   ,                                     & !in\n                              STC     )                                       !inout\n! --------------------------------------------------------------------------------------------------\n! Compute snow (up to 3L) and soil (4L) temperature. Note that snow temperatures\n! during melting season may exceed melting point (TFRZ) but later in PHASECHANGE\n! subroutine the snow temperatures are reset to TFRZ for melting snow.\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n!input\n\n    INTEGER,                         INTENT(IN)  :: NSOIL  !no of soil layers (4)\n    INTEGER,                         INTENT(IN)  :: NSNOW  !maximum no of snow layers (3)\n    INTEGER,                         INTENT(IN)  :: ISNOW  !actual no of snow layers\n\n    REAL,                            INTENT(IN)  :: DT     !time step (s)\n    REAL,                            INTENT(IN)  :: TBOT   !\n    REAL,                            INTENT(IN)  :: SSOIL  !ground heat flux (w/m2)\n    REAL,                            INTENT(IN)  :: SNOWH  !snow depth (m)\n    REAL,                            INTENT(IN)  :: ZBOT   !from soil surface (m)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: ZSNSO  !layer-bot. depth from snow surf.(m)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: DF     !thermal conductivity\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: HCPCT  !heat capacity (J/m3/k)\n\n!input and output\n\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC\n\n!local\n\n    INTEGER                                      :: IZ\n    REAL                                         :: ZBOTSNO   !ZBOT from snow surface\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: AI, BI, CI, RHSTS\n    REAL                                         :: EFLXB !energy influx from soil bottom (w/m2)\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: PHI   !light through water (w/m2)\n\n! ----------------------------------------------------------------------\n\n! prescribe solar penetration into ice/snow\n\n    PHI(ISNOW+1:NSOIL) = 0.\n\n! adjust ZBOT from soil surface to ZBOTSNO from snow surface\n\n    ZBOTSNO = ZBOT - SNOWH    !from snow surface\n\n! compute ice temperatures\n\n      CALL HRT_GLACIER   (NSNOW     ,NSOIL     ,ISNOW     ,ZSNSO     , &\n                          STC       ,TBOT      ,ZBOTSNO   ,DF        , &\n                          HCPCT     ,SSOIL     ,PHI       ,            &\n                          AI        ,BI        ,CI        ,RHSTS     , &\n                          EFLXB     )\n\n      CALL HSTEP_GLACIER (NSNOW     ,NSOIL     ,ISNOW     ,DT        , &\n                          AI        ,BI        ,CI        ,RHSTS     , &\n                          STC       )\n\n  END SUBROUTINE TSNOSOI_GLACIER\n! ==================================================================================================\n! ----------------------------------------------------------------------\n  SUBROUTINE HRT_GLACIER (NSNOW     ,NSOIL     ,ISNOW     ,ZSNSO     , & !in\n                          STC       ,TBOT      ,ZBOT      ,DF        , & !in\n                          HCPCT     ,SSOIL     ,PHI       ,            & !in\n                          AI        ,BI        ,CI        ,RHSTS     , & !out\n                          BOTFLX    )                                    !out\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! calculate the right hand side of the time tendency term of the soil\n! thermal diffusion equation.  also to compute ( prepare ) the matrix\n! coefficients for the tri-diagonal matrix of the implicit time scheme.\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n    INTEGER,                         INTENT(IN)  :: NSOIL  !no of soil layers (4)\n    INTEGER,                         INTENT(IN)  :: NSNOW  !maximum no of snow layers (3)\n    INTEGER,                         INTENT(IN)  :: ISNOW  !actual no of snow layers\n    REAL,                            INTENT(IN)  :: TBOT   !bottom soil temp. at ZBOT (k)\n    REAL,                            INTENT(IN)  :: ZBOT   !depth of lower boundary condition (m)\n                                                           !from soil surface not snow surface\n    REAL,                            INTENT(IN)  :: SSOIL  !ground heat flux (w/m2)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: ZSNSO  !depth of layer-bottom of snow/soil (m)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: STC    !snow/soil temperature (k)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: DF     !thermal conductivity [w/m/k]\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: HCPCT  !heat capacity [j/m3/k]\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: PHI    !light through water (w/m2)\n\n! output\n\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: RHSTS  !right-hand side of the matrix\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: AI     !left-hand side coefficient\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: BI     !left-hand side coefficient\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: CI     !left-hand side coefficient\n    REAL,                            INTENT(OUT) :: BOTFLX !energy influx from soil bottom (w/m2)\n\n! local\n\n    INTEGER                                      :: K\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: DDZ\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: DENOM\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: DTSDZ\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: EFLUX\n    REAL                                         :: TEMP1\n! ----------------------------------------------------------------------\n\n    DO K = ISNOW+1, NSOIL\n        IF (K == ISNOW+1) THEN\n           DENOM(K)  = - ZSNSO(K) * HCPCT(K)\n           TEMP1     = - ZSNSO(K+1)\n           DDZ(K)    = 2.0 / TEMP1\n           DTSDZ(K)  = 2.0 * (STC(K) - STC(K+1)) / TEMP1\n           EFLUX(K)  = DF(K) * DTSDZ(K) - SSOIL - PHI(K)\n        ELSE IF (K < NSOIL) THEN\n           DENOM(K)  = (ZSNSO(K-1) - ZSNSO(K)) * HCPCT(K)\n           TEMP1     = ZSNSO(K-1) - ZSNSO(K+1)\n           DDZ(K)    = 2.0 / TEMP1\n           DTSDZ(K)  = 2.0 * (STC(K) - STC(K+1)) / TEMP1\n           EFLUX(K)  = (DF(K)*DTSDZ(K) - DF(K-1)*DTSDZ(K-1)) - PHI(K)\n        ELSE IF (K == NSOIL) THEN\n           DENOM(K)  = (ZSNSO(K-1) - ZSNSO(K)) * HCPCT(K)\n           TEMP1     =  ZSNSO(K-1) - ZSNSO(K)\n           IF(OPT_TBOT == 1) THEN\n               BOTFLX     = 0.\n           END IF\n           IF(OPT_TBOT == 2) THEN\n               DTSDZ(K)  = (STC(K) - TBOT) / ( 0.5*(ZSNSO(K-1)+ZSNSO(K)) - ZBOT)\n               BOTFLX    = -DF(K) * DTSDZ(K)\n           END IF\n           EFLUX(K)  = (-BOTFLX - DF(K-1)*DTSDZ(K-1) ) - PHI(K)\n        END IF\n    END DO\n\n    DO K = ISNOW+1, NSOIL\n        IF (K == ISNOW+1) THEN\n           AI(K)    =   0.0\n           CI(K)    = - DF(K)   * DDZ(K) / DENOM(K)\n           IF (OPT_STC == 1 .OR. OPT_STC == 3) THEN\n              BI(K) = - CI(K)\n           END IF\n           IF (OPT_STC == 2) THEN\n              BI(K) = - CI(K) + DF(K)/(0.5*ZSNSO(K)*ZSNSO(K)*HCPCT(K))\n           END IF\n        ELSE IF (K < NSOIL) THEN\n           AI(K)    = - DF(K-1) * DDZ(K-1) / DENOM(K)\n           CI(K)    = - DF(K  ) * DDZ(K  ) / DENOM(K)\n           BI(K)    = - (AI(K) + CI (K))\n        ELSE IF (K == NSOIL) THEN\n           AI(K)    = - DF(K-1) * DDZ(K-1) / DENOM(K)\n           CI(K)    = 0.0\n           BI(K)    = - (AI(K) + CI(K))\n        END IF\n           RHSTS(K)  = EFLUX(K)/ (-DENOM(K))\n    END DO\n\n  END SUBROUTINE HRT_GLACIER\n! ==================================================================================================\n! ----------------------------------------------------------------------\n  SUBROUTINE HSTEP_GLACIER (NSNOW     ,NSOIL     ,ISNOW     ,DT        ,  & !in\n                            AI        ,BI        ,CI        ,RHSTS     ,  & !inout\n                            STC       )                                     !inout\n! ----------------------------------------------------------------------\n! CALCULATE/UPDATE THE SOIL TEMPERATURE FIELD.\n! ----------------------------------------------------------------------\n    implicit none\n! ----------------------------------------------------------------------\n! input\n\n    INTEGER,                         INTENT(IN)    :: NSOIL\n    INTEGER,                         INTENT(IN)    :: NSNOW\n    INTEGER,                         INTENT(IN)    :: ISNOW\n    REAL,                            INTENT(IN)    :: DT\n\n! output & input\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: AI\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: BI\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: CI\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: RHSTS\n\n! local\n    INTEGER                                        :: K\n    REAL, DIMENSION(-NSNOW+1:NSOIL)                :: RHSTSIN\n    REAL, DIMENSION(-NSNOW+1:NSOIL)                :: CIIN\n! ----------------------------------------------------------------------\n\n    DO K = ISNOW+1,NSOIL\n       RHSTS(K) =   RHSTS(K) * DT\n       AI(K)    =      AI(K) * DT\n       BI(K)    = 1. + BI(K) * DT\n       CI(K)    =      CI(K) * DT\n    END DO\n\n! copy values for input variables before call to rosr12\n\n    DO K = ISNOW+1,NSOIL\n       RHSTSIN(K) = RHSTS(K)\n       CIIN(K)    = CI(K)\n    END DO\n\n! solve the tri-diagonal matrix equation\n\n    CALL ROSR12_GLACIER (CI,AI,BI,CIIN,RHSTSIN,RHSTS,ISNOW+1,NSOIL,NSNOW)\n\n! update snow & soil temperature\n\n    DO K = ISNOW+1,NSOIL\n       STC (K) = STC (K) + CI (K)\n    END DO\n\n  END SUBROUTINE HSTEP_GLACIER\n! ==================================================================================================\n  SUBROUTINE ROSR12_GLACIER (P,A,B,C,D,DELTA,NTOP,NSOIL,NSNOW)\n! ----------------------------------------------------------------------\n! SUBROUTINE ROSR12\n! ----------------------------------------------------------------------\n! INVERT (SOLVE) THE TRI-DIAGONAL MATRIX PROBLEM SHOWN BELOW:\n! ###                                            ### ###  ###   ###  ###\n! #B(1), C(1),  0  ,  0  ,  0  ,   . . .  ,    0   # #      #   #      #\n! #A(2), B(2), C(2),  0  ,  0  ,   . . .  ,    0   # #      #   #      #\n! # 0  , A(3), B(3), C(3),  0  ,   . . .  ,    0   # #      #   # D(3) #\n! # 0  ,  0  , A(4), B(4), C(4),   . . .  ,    0   # # P(4) #   # D(4) #\n! # 0  ,  0  ,  0  , A(5), B(5),   . . .  ,    0   # # P(5) #   # D(5) #\n! # .                                          .   # #  .   # = #   .  #\n! # .                                          .   # #  .   #   #   .  #\n! # .                                          .   # #  .   #   #   .  #\n! # 0  , . . . , 0 , A(M-2), B(M-2), C(M-2),   0   # #P(M-2)#   #D(M-2)#\n! # 0  , . . . , 0 ,   0   , A(M-1), B(M-1), C(M-1)# #P(M-1)#   #D(M-1)#\n! # 0  , . . . , 0 ,   0   ,   0   ,  A(M) ,  B(M) # # P(M) #   # D(M) #\n! ###                                            ### ###  ###   ###  ###\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n\n    INTEGER, INTENT(IN)   :: NTOP\n    INTEGER, INTENT(IN)   :: NSOIL,NSNOW\n    INTEGER               :: K, KK\n\n    REAL, DIMENSION(-NSNOW+1:NSOIL),INTENT(IN):: A, B, D\n    REAL, DIMENSION(-NSNOW+1:NSOIL),INTENT(INOUT):: C,P,DELTA\n\n! ----------------------------------------------------------------------\n! INITIALIZE EQN COEF C FOR THE LOWEST SOIL LAYER\n! ----------------------------------------------------------------------\n    C (NSOIL) = 0.0\n    P (NTOP) = - C (NTOP) / B (NTOP)\n! ----------------------------------------------------------------------\n! SOLVE THE COEFS FOR THE 1ST SOIL LAYER\n! ----------------------------------------------------------------------\n    DELTA (NTOP) = D (NTOP) / B (NTOP)\n! ----------------------------------------------------------------------\n! SOLVE THE COEFS FOR SOIL LAYERS 2 THRU NSOIL\n! ----------------------------------------------------------------------\n    DO K = NTOP+1,NSOIL\n       P (K) = - C (K) * ( 1.0 / (B (K) + A (K) * P (K -1)) )\n       DELTA (K) = (D (K) - A (K)* DELTA (K -1))* (1.0/ (B (K) + A (K)&\n            * P (K -1)))\n    END DO\n! ----------------------------------------------------------------------\n! SET P TO DELTA FOR LOWEST SOIL LAYER\n! ----------------------------------------------------------------------\n    P (NSOIL) = DELTA (NSOIL)\n! ----------------------------------------------------------------------\n! ADJUST P FOR SOIL LAYERS 2 THRU NSOIL\n! ----------------------------------------------------------------------\n    DO K = NTOP+1,NSOIL\n       KK = NSOIL - K + (NTOP-1) + 1\n       P (KK) = P (KK) * P (KK +1) + DELTA (KK)\n    END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE ROSR12_GLACIER\n! ----------------------------------------------------------------------\n! ==================================================================================================\n  SUBROUTINE PHASECHANGE_GLACIER (NSNOW   ,NSOIL   ,ISNOW   ,DT      ,FACT    , & !in\n                                  DZSNSO  ,                                     & !in\n                                  STC     ,SNICE   ,SNLIQ   ,SNEQV   ,SNOWH   , & !inout\n                                  SMC     ,SH2O    ,                            & !inout\n                                  QMELT   ,IMELT   ,PONDING )                     !out\n! ----------------------------------------------------------------------\n! melting/freezing of snow water and soil water\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! inputs\n\n  INTEGER, INTENT(IN)                             :: NSNOW  !maximum no. of snow layers [=3]\n  INTEGER, INTENT(IN)                             :: NSOIL  !No. of soil layers [=4]\n  INTEGER, INTENT(IN)                             :: ISNOW  !actual no. of snow layers [<=3]\n  REAL, INTENT(IN)                                :: DT     !land model time step (sec)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)     :: FACT   !temporary\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)     :: DZSNSO !snow/soil layer thickness [m]\n\n! inputs/outputs\n\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT)  :: STC    !snow/soil layer temperature [k]\n  REAL, DIMENSION(-NSNOW+1:0)    , INTENT(INOUT)  :: SNICE  !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:0)    , INTENT(INOUT)  :: SNLIQ  !snow layer liquid water [mm]\n  REAL, INTENT(INOUT)                             :: SNEQV\n  REAL, INTENT(INOUT)                             :: SNOWH\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT)  :: SH2O   !soil liquid water [m3/m3]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT)  :: SMC    !total soil water [m3/m3]\n\n! outputs\n  REAL,                               INTENT(OUT) :: QMELT  !snowmelt rate [mm/s]\n  INTEGER, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: IMELT  !phase change index\n  REAL,                               INTENT(OUT) :: PONDING!snowmelt when snow has no layer [mm]\n\n! local\n\n  INTEGER                         :: J,K         !do loop index\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: HM        !energy residual [w/m2]\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: XM        !melting or freezing water [kg/m2]\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: WMASS0\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: WICE0\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: WLIQ0\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: MICE      !soil/snow ice mass [mm]\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: MLIQ      !soil/snow liquid water mass [mm]\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: HEATR     !energy residual or loss after melting/freezing\n  REAL                            :: TEMP1     !temporary variables [kg/m2]\n  REAL                            :: PROPOR\n  REAL                            :: XMF       !total latent heat of phase change\n\n! ----------------------------------------------------------------------\n! Initialization\n\n    QMELT   = 0.\n    PONDING = 0.\n    XMF     = 0.\n\n    DO J = ISNOW+1,0           ! all snow layers\n         MICE(J) = SNICE(J)\n         MLIQ(J) = SNLIQ(J)\n    END DO\n\n    DO J = ISNOW+1,0           ! all snow layers; do ice later\n         IMELT(J)    = 0\n         HM(J)       = 0.\n         XM(J)       = 0.\n         WICE0(J)    = MICE(J)\n         WLIQ0(J)    = MLIQ(J)\n         WMASS0(J)   = MICE(J) + MLIQ(J)\n    ENDDO\n\n    DO J = ISNOW+1,0\n         IF (MICE(J) > 0. .AND. STC(J) >= TFRZ) THEN  ! melting\n             IMELT(J) = 1\n         ENDIF\n         IF (MLIQ(J) > 0. .AND. STC(J)  < TFRZ) THEN  ! freezing\n             IMELT(J) = 2\n         ENDIF\n\n    ENDDO\n\n! Calculate the energy surplus and loss for melting and freezing\n\n    DO J = ISNOW+1,0\n         IF (IMELT(J) > 0) THEN\n             HM(J) = (STC(J)-TFRZ)/FACT(J)\n             STC(J) = TFRZ\n         ENDIF\n\n         IF (IMELT(J) == 1 .AND. HM(J) < 0.) THEN\n            HM(J) = 0.\n            IMELT(J) = 0\n         ENDIF\n         IF (IMELT(J) == 2 .AND. HM(J) > 0.) THEN\n            HM(J) = 0.\n            IMELT(J) = 0\n         ENDIF\n         XM(J) = HM(J)*DT/HFUS\n    ENDDO\n\n! The rate of melting and freezing for snow without a layer, opt_gla==1 treated below\n\nIF (OPT_GLA == 2) THEN\n\n    IF (ISNOW == 0 .AND. SNEQV > 0. .AND. STC(1) >= TFRZ) THEN\n        HM(1)    = (STC(1)-TFRZ)/FACT(1)             ! available heat\n        STC(1)   = TFRZ                              ! set T to freezing\n        XM(1)    = HM(1)*DT/HFUS                     ! total snow melt possible\n\n        TEMP1  = SNEQV\n        SNEQV  = MAX(0.,TEMP1-XM(1))                 ! snow remaining\n        PROPOR = SNEQV/TEMP1                         ! fraction melted\n        SNOWH  = MAX(0.,PROPOR * SNOWH)              ! new snow height\n        HEATR(1)  = HM(1) - HFUS*(TEMP1-SNEQV)/DT    ! excess heat\n        IF (HEATR(1) > 0.) THEN\n              XM(1)  = HEATR(1)*DT/HFUS\n              STC(1) = STC(1) + FACT(1)*HEATR(1)     ! re-heat ice\n        ELSE\n              XM(1) = 0.                             ! heat used up\n              HM(1) = 0.\n        ENDIF\n        QMELT   = MAX(0.,(TEMP1-SNEQV))/DT           ! melted snow rate\n        XMF     = HFUS*QMELT                         ! melted snow energy\n        PONDING = TEMP1-SNEQV                        ! melt water\n    ENDIF\n\nEND IF  ! OPT_GLA == 2\n\n! The rate of melting and freezing for snow\n\n    DO J = ISNOW+1,0\n      IF (IMELT(J) > 0 .AND. ABS(HM(J)) > 0.) THEN\n\n         HEATR(J) = 0.\n         IF (XM(J) > 0.) THEN\n            MICE(J) = MAX(0., WICE0(J)-XM(J))\n            HEATR(J) = HM(J) - HFUS*(WICE0(J)-MICE(J))/DT\n         ELSE IF (XM(J) < 0.) THEN\n            MICE(J) = MIN(WMASS0(J), WICE0(J)-XM(J))\n            HEATR(J) = HM(J) - HFUS*(WICE0(J)-MICE(J))/DT\n         ENDIF\n\n         MLIQ(J) = MAX(0.,WMASS0(J)-MICE(J))\n\n         IF (ABS(HEATR(J)) > 0.) THEN\n            STC(J) = STC(J) + FACT(J)*HEATR(J)\n            IF (MLIQ(J)*MICE(J)>0.) STC(J) = TFRZ\n         ENDIF\n\n         QMELT = QMELT + MAX(0.,(WICE0(J)-MICE(J)))/DT\n\n      ENDIF\n    ENDDO\n\nIF (OPT_GLA == 1) THEN     ! operate on the ice layers\n\n    DO J = 1, NSOIL            ! all soil layers\n         MLIQ(J) =  SH2O(J)            * DZSNSO(J) * 1000.\n         MICE(J) = (SMC(J) - SH2O(J))  * DZSNSO(J) * 1000.\n    END DO\n\n    DO J = 1,NSOIL       ! all layers\n         IMELT(J)    = 0\n         HM(J)       = 0.\n         XM(J)       = 0.\n         WICE0(J)    = MICE(J)\n         WLIQ0(J)    = MLIQ(J)\n         WMASS0(J)   = MICE(J) + MLIQ(J)\n    ENDDO\n\n    DO J = 1,NSOIL\n         IF (MICE(J) > 0. .AND. STC(J) >= TFRZ) THEN  ! melting\n             IMELT(J) = 1\n         ENDIF\n         IF (MLIQ(J) > 0. .AND. STC(J)  < TFRZ) THEN  ! freezing\n             IMELT(J) = 2\n         ENDIF\n\n         ! If snow exists, but its thickness is not enough to create a layer\n         IF (ISNOW == 0 .AND. SNEQV > 0. .AND. J == 1) THEN\n             IF (STC(J) >= TFRZ) THEN\n                IMELT(J) = 1\n             ENDIF\n         ENDIF\n    ENDDO\n\n! Calculate the energy surplus and loss for melting and freezing\n\n    DO J = 1,NSOIL\n         IF (IMELT(J) > 0) THEN\n             HM(J) = (STC(J)-TFRZ)/FACT(J)\n             STC(J) = TFRZ\n         ENDIF\n\n         IF (IMELT(J) == 1 .AND. HM(J) < 0.) THEN\n            HM(J) = 0.\n            IMELT(J) = 0\n         ENDIF\n         IF (IMELT(J) == 2 .AND. HM(J) > 0.) THEN\n            HM(J) = 0.\n            IMELT(J) = 0\n         ENDIF\n         XM(J) = HM(J)*DT/HFUS\n    ENDDO\n\n! The rate of melting and freezing for snow without a layer, needs more work.\n\n    IF (ISNOW == 0 .AND. SNEQV > 0. .AND. XM(1) > 0.) THEN\n        TEMP1  = SNEQV\n        SNEQV  = MAX(0.,TEMP1-XM(1))\n        PROPOR = SNEQV/TEMP1\n        SNOWH  = MAX(0.,PROPOR * SNOWH)\n        HEATR(1)  = HM(1) - HFUS*(TEMP1-SNEQV)/DT\n        IF (HEATR(1) > 0.) THEN\n              XM(1) = HEATR(1)*DT/HFUS\n              HM(1) = HEATR(1)\n\t      IMELT(1) = 1\n        ELSE\n              XM(1) = 0.\n              HM(1) = 0.\n\t      IMELT(1) = 0\n        ENDIF\n        QMELT   = MAX(0.,(TEMP1-SNEQV))/DT\n        XMF     = HFUS*QMELT\n        PONDING = TEMP1-SNEQV\n    ENDIF\n\n! The rate of melting and freezing for soil\n\n    DO J = 1,NSOIL\n      IF (IMELT(J) > 0 .AND. ABS(HM(J)) > 0.) THEN\n\n         HEATR(J) = 0.\n         IF (XM(J) > 0.) THEN\n            MICE(J) = MAX(0., WICE0(J)-XM(J))\n            HEATR(J) = HM(J) - HFUS*(WICE0(J)-MICE(J))/DT\n         ELSE IF (XM(J) < 0.) THEN\n            MICE(J) = MIN(WMASS0(J), WICE0(J)-XM(J))\n            HEATR(J) = HM(J) - HFUS*(WICE0(J)-MICE(J))/DT\n         ENDIF\n\n         MLIQ(J) = MAX(0.,WMASS0(J)-MICE(J))\n\n         IF (ABS(HEATR(J)) > 0.) THEN\n            STC(J) = STC(J) + FACT(J)*HEATR(J)\n            IF (J <= 0) THEN                             ! snow\n               IF (MLIQ(J)*MICE(J)>0.) STC(J) = TFRZ\n            END IF\n         ENDIF\n\n         IF (J > 0) XMF = XMF + HFUS * (WICE0(J)-MICE(J))/DT\n\n         IF (J < 1) THEN\n            QMELT = QMELT + MAX(0.,(WICE0(J)-MICE(J)))/DT\n         ENDIF\n      ENDIF\n    ENDDO\n    HEATR = 0.0\n    XM = 0.0\n\n! Deal with residuals in ice/soil\n\n! FIRST REMOVE EXCESS HEAT BY REDUCING TEMPERATURE OF LAYERS\n\n    IF (ANY(STC(1:4) > TFRZ) .AND. ANY(STC(1:4) < TFRZ)) THEN\n      DO J = 1,NSOIL\n        IF ( STC(J) > TFRZ ) THEN\n\t  HEATR(J) = (STC(J)-TFRZ)/FACT(J)\n          DO K = 1,NSOIL\n\t    IF (J .NE. K .AND. STC(K) < TFRZ .AND. HEATR(J) > 0.1) THEN\n\t      HEATR(K) = (STC(K)-TFRZ)/FACT(K)\n\t      IF (ABS(HEATR(K)) > HEATR(J)) THEN  ! LAYER ABSORBS ALL\n\t        HEATR(K) = HEATR(K) + HEATR(J)\n\t\tSTC(K) = TFRZ + HEATR(K)*FACT(K)\n\t\tHEATR(J) = 0.0\n              ELSE\n\t        HEATR(J) = HEATR(J) + HEATR(K)\n\t\tHEATR(K) = 0.0\n\t\tSTC(K) = TFRZ\n              END IF\n\t    END IF\n\t  END DO\n          STC(J) = TFRZ + HEATR(J)*FACT(J)\n        END IF\n      END DO\n    END IF\n\n! NOW REMOVE EXCESS COLD BY INCREASING TEMPERATURE OF LAYERS (MAY NOT BE NECESSARY WITH ABOVE LOOP)\n\n    IF (ANY(STC(1:4) > TFRZ) .AND. ANY(STC(1:4) < TFRZ)) THEN\n      DO J = 1,NSOIL\n        IF ( STC(J) < TFRZ ) THEN\n\t  HEATR(J) = (STC(J)-TFRZ)/FACT(J)\n          DO K = 1,NSOIL\n\t    IF (J .NE. K .AND. STC(K) > TFRZ .AND. HEATR(J) < -0.1) THEN\n\t      HEATR(K) = (STC(K)-TFRZ)/FACT(K)\n\t      IF (HEATR(K) > ABS(HEATR(J))) THEN  ! LAYER ABSORBS ALL\n\t        HEATR(K) = HEATR(K) + HEATR(J)\n\t\tSTC(K) = TFRZ + HEATR(K)*FACT(K)\n\t\tHEATR(J) = 0.0\n              ELSE\n\t        HEATR(J) = HEATR(J) + HEATR(K)\n\t\tHEATR(K) = 0.0\n\t\tSTC(K) = TFRZ\n              END IF\n\t    END IF\n\t  END DO\n          STC(J) = TFRZ + HEATR(J)*FACT(J)\n        END IF\n      END DO\n    END IF\n\n! NOW REMOVE EXCESS HEAT BY MELTING ICE\n\n    IF (ANY(STC(1:4) > TFRZ) .AND. ANY(MICE(1:4) > 0.)) THEN\n      DO J = 1,NSOIL\n        IF ( STC(J) > TFRZ ) THEN\n\t  HEATR(J) = (STC(J)-TFRZ)/FACT(J)\n          XM(J) = HEATR(J)*DT/HFUS\n          DO K = 1,NSOIL\n\t    IF (J .NE. K .AND. MICE(K) > 0. .AND. XM(J) > 0.1) THEN\n\t      IF (MICE(K) > XM(J)) THEN  ! LAYER ABSORBS ALL\n\t        MICE(K) = MICE(K) - XM(J)\n\t\tXMF = XMF + HFUS * XM(J)/DT\n\t\tSTC(K) = TFRZ\n\t\tXM(J) = 0.0\n              ELSE\n\t        XM(J) = XM(J) - MICE(K)\n\t\tXMF = XMF + HFUS * MICE(K)/DT\n\t\tMICE(K) = 0.0\n\t\tSTC(K) = TFRZ\n              END IF\n              MLIQ(K) = MAX(0.,WMASS0(K)-MICE(K))\n\t    END IF\n\t  END DO\n\t  HEATR(J) = XM(J)*HFUS/DT\n          STC(J) = TFRZ + HEATR(J)*FACT(J)\n        END IF\n      END DO\n    END IF\n\n! NOW REMOVE EXCESS COLD BY FREEZING LIQUID OF LAYERS (MAY NOT BE NECESSARY WITH ABOVE LOOP)\n\n    IF (ANY(STC(1:4) < TFRZ) .AND. ANY(MLIQ(1:4) > 0.)) THEN\n      DO J = 1,NSOIL\n        IF ( STC(J) < TFRZ ) THEN\n\t  HEATR(J) = (STC(J)-TFRZ)/FACT(J)\n          XM(J) = HEATR(J)*DT/HFUS\n          DO K = 1,NSOIL\n\t    IF (J .NE. K .AND. MLIQ(K) > 0. .AND. XM(J) < -0.1) THEN\n\t      IF (MLIQ(K) > ABS(XM(J))) THEN  ! LAYER ABSORBS ALL\n\t        MICE(K) = MICE(K) - XM(J)\n\t\tXMF = XMF + HFUS * XM(J)/DT\n\t\tSTC(K) = TFRZ\n\t\tXM(J) = 0.0\n              ELSE\n\t        XM(J) = XM(J) + MLIQ(K)\n\t\tXMF = XMF - HFUS * MLIQ(K)/DT\n\t\tMICE(K) = WMASS0(K)\n\t\tSTC(K) = TFRZ\n              END IF\n              MLIQ(K) = MAX(0.,WMASS0(K)-MICE(K))\n\t    END IF\n\t  END DO\n\t  HEATR(J) = XM(J)*HFUS/DT\n          STC(J) = TFRZ + HEATR(J)*FACT(J)\n        END IF\n      END DO\n    END IF\n\nEND IF   ! OPT_GLA == 1\n\n    DO J = ISNOW+1,0             ! snow\n       SNLIQ(J) = MLIQ(J)\n       SNICE(J) = MICE(J)\n    END DO\n\n    DO J = 1, NSOIL              ! soil\n      IF(OPT_GLA == 1) THEN\n       SH2O(J) =  MLIQ(J)            / (1000. * DZSNSO(J))\n       SH2O(J) =  MAX(0.0,MIN(1.0,SH2O(J)))\n!       SMC(J)  = (MLIQ(J) + MICE(J)) / (1000. * DZSNSO(J))\n      ELSEIF(OPT_GLA == 2) THEN\n       SH2O(J) = 0.0             ! ice, assume all frozen...forever\n      END IF\n      SMC(J)  = 1.0\n    END DO\n\n  END SUBROUTINE PHASECHANGE_GLACIER\n! ==================================================================================================\n  SUBROUTINE WATER_GLACIER (NSNOW  ,NSOIL  ,IMELT  ,DT     ,PRCP   ,SFCTMP , & !in\n                            QVAP   ,QDEW   ,FICEOLD,ZSOIL  , SWE_LIMIT     , & !in\n                            ISNOW  ,SNOWH  ,SNEQV  ,SNICE  ,SNLIQ  ,STC    , & !inout\n                            DZSNSO ,SH2O   ,SICE   ,PONDING,ZSNSO  ,FSH    , & !inout\n                            RUNSRF ,RUNSUB ,QSNOW, QRAIN, PONDING1 ,PONDING2,QSNBOT,FPICE     &   !out\n#ifdef WRF_HYDRO\n                            , sfcheadrt                                      &\n#endif\n                            )  !out\n! ----------------------------------------------------------------------\n! Code history:\n! Initial code: Guo-Yue Niu, Oct. 2007\n! ----------------------------------------------------------------------\n  implicit none\n! ----------------------------------------------------------------------\n! input\n  INTEGER,                         INTENT(IN)    :: NSNOW   !maximum no. of snow layers\n  INTEGER,                         INTENT(IN)    :: NSOIL   !no. of soil layers\n  INTEGER, DIMENSION(-NSNOW+1:0) , INTENT(IN)    :: IMELT   !melting state index [1-melt; 2-freeze]\n  REAL,                            INTENT(IN)    :: DT      !main time step (s)\n  REAL,                            INTENT(IN)    :: PRCP    !precipitation (mm/s)\n  REAL,                            INTENT(IN)    :: SFCTMP  !surface air temperature [k]\n  REAL,                            INTENT(INOUT)    :: QVAP    !soil surface evaporation rate[mm/s]\n  REAL,                            INTENT(INOUT)    :: QDEW    !soil surface dew rate[mm/s]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: FICEOLD !ice fraction at last timestep\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: ZSOIL  !layer-bottom depth from soil surf (m)\n  REAL,                            INTENT(IN)    :: SWE_LIMIT  !maximum SWE limit (mm)\n\n! input/output\n  INTEGER,                         INTENT(INOUT) :: ISNOW   !actual no. of snow layers\n  REAL,                            INTENT(INOUT) :: SNOWH   !snow height [m]\n  REAL,                            INTENT(INOUT) :: SNEQV   !snow water eqv. [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE   !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ   !snow layer liquid water [mm]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC     !snow/soil layer temperature [k]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO  !snow/soil layer thickness [m]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O    !soil liquid water content [m3/m3]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SICE    !soil ice content [m3/m3]\n  REAL                           , INTENT(INOUT) :: PONDING ![mm]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: ZSNSO   !layer-bottom depth from snow surf [m]\n  REAL                           , INTENT(INOUT) :: FSH     !total sensible heat (w/m2) [+ to atm]\n\n! output\n  REAL,                            INTENT(OUT)   :: RUNSRF  !surface runoff [mm/s]\n  REAL,                            INTENT(OUT)   :: RUNSUB  !baseflow (sturation excess) [mm/s]\n  REAL,                            INTENT(OUT)   :: QSNOW   !snow at ground srf (mm/s) [+]\n  REAL,                            INTENT(OUT)   :: QRAIN   !rain at ground srf (mm/s) [+]\n  REAL,                            INTENT(OUT)   :: PONDING1\n  REAL,                            INTENT(OUT)   :: PONDING2\n  REAL,                            INTENT(OUT)   :: QSNBOT  !melting water out of snow bottom [mm/s]\n  REAL,                            INTENT(OUT)   :: FPICE   !precipitation frozen fraction\n\n! local\n  REAL                                           :: QSEVA   !soil surface evap rate [mm/s]\n  REAL                                           :: QSDEW   !soil surface dew rate [mm/s]\n  REAL                                           :: QSNFRO  !snow surface frost rate[mm/s]\n  REAL                                           :: QSNSUB  !snow surface sublimation rate [mm/s]\n  REAL                                           :: SNOWHIN !snow depth increasing rate (m/s)\n  REAL                                           :: SNOFLOW !glacier flow [mm/s]\n  REAL                                           :: BDFALL  !density of new snow (mm water/m snow)\n  REAL                                           :: REPLACE !replacement water due to sublimation of glacier\n  REAL, DIMENSION(       1:NSOIL)                :: SICE_SAVE  !soil ice content [m3/m3]\n  REAL, DIMENSION(       1:NSOIL)                :: SH2O_SAVE  !soil liquid water content [m3/m3]\n  INTEGER :: ILEV\n\n#ifdef WRF_HYDRO\n  REAL                           , INTENT(INOUT)    :: sfcheadrt\n#endif\n\n! ----------------------------------------------------------------------\n! initialize\n\n   SNOFLOW         = 0.\n   RUNSUB          = 0.\n   RUNSRF          = 0.\n   SICE_SAVE       = SICE\n   SH2O_SAVE       = SH2O\n\n! --------------------------------------------------------------------\n! partition precipitation into rain and snow (from CANWATER)\n\n! Jordan (1991)\n\n     IF(OPT_SNF == 1 .OR. OPT_SNF == 4) THEN\n       IF(SFCTMP > TFRZ+2.5)THEN\n           FPICE = 0.\n       ELSE\n         IF(SFCTMP <= TFRZ+0.5)THEN\n           FPICE = 1.0\n         ELSE IF(SFCTMP <= TFRZ+2.)THEN\n           FPICE = 1.-(-54.632 + 0.2*SFCTMP)\n         ELSE\n           FPICE = 0.6\n         ENDIF\n       ENDIF\n     ENDIF\n\n     IF(OPT_SNF == 2) THEN\n       IF(SFCTMP >= TFRZ+2.2) THEN\n           FPICE = 0.\n       ELSE\n           FPICE = 1.0\n       ENDIF\n     ENDIF\n\n     IF(OPT_SNF == 3) THEN\n       IF(SFCTMP >= TFRZ) THEN\n           FPICE = 0.\n       ELSE\n           FPICE = 1.0\n       ENDIF\n     ENDIF\n!     print*, 'fpice: ',fpice\n\n! Hedstrom NR and JW Pomeroy (1998), Hydrol. Processes, 12, 1611-1625\n! fresh snow density\n\n     BDFALL = MIN(120.,67.92+51.25*EXP((SFCTMP-TFRZ)/2.59)) !MB: change to MIN v3.7\n\n     QRAIN   = PRCP * (1.-FPICE)\n     QSNOW   = PRCP * FPICE\n     SNOWHIN = QSNOW/BDFALL\n!     print *, 'qrain, qsnow',qrain,qsnow,qrain*dt,qsnow*dt\n\n! sublimation, frost, evaporation, and dew\n\n     QSNSUB = QVAP  ! send total sublimation/frost to SNOWWATER and deal with it there\n     QSNFRO = QDEW\n\n     CALL SNOWWATER_GLACIER (NSNOW  ,NSOIL  ,IMELT  ,DT     ,SFCTMP , & !in\n                             SNOWHIN,QSNOW  ,QSNFRO ,QSNSUB ,QRAIN  , & !in\n                             FICEOLD,ZSOIL  ,SWE_LIMIT              , & !in\n                             ISNOW  ,SNOWH  ,SNEQV  ,SNICE  ,SNLIQ  , & !inout\n                             SH2O   ,SICE   ,STC    ,DZSNSO ,ZSNSO  , & !inout\n                             FSH    ,                                 & !inout\n                             QSNBOT ,SNOFLOW,PONDING1       ,PONDING2)  !out\n\n    !PONDING: melting water from snow when there is no layer\n\n    RUNSRF = (PONDING+PONDING1+PONDING2)/DT\n\n    IF(ISNOW == 0) THEN\n      RUNSRF = RUNSRF + QSNBOT + QRAIN\n    ELSE\n      RUNSRF = RUNSRF + QSNBOT\n    ENDIF\n\n#ifdef WRF_HYDRO\n      RUNSRF = RUNSRF + sfcheadrt/DT  !sfcheadrt units (mm)\n#endif\n\n    IF(OPT_GLA == 1) THEN\n      REPLACE = 0.0\n      DO ILEV = 1,NSOIL\n       REPLACE = REPLACE + DZSNSO(ILEV)*(SICE(ILEV) - SICE_SAVE(ILEV) + SH2O(ILEV) - SH2O_SAVE(ILEV))\n      END DO\n      REPLACE = REPLACE * 1000.0 / DT     ! convert to [mm/s]\n\n      SICE = MIN(1.0,SICE_SAVE)\n    ELSEIF(OPT_GLA == 2) THEN\n      SICE = 1.0\n    END IF\n    SH2O = 1.0 - SICE\n\n    ! use RUNSUB as a water balancer, SNOFLOW is snow that disappears, REPLACE is\n    !   water from below that replaces glacier loss\n\n    IF(OPT_GLA == 1) THEN\n      RUNSUB       = SNOFLOW + REPLACE\n    ELSEIF(OPT_GLA == 2) THEN\n      RUNSUB       = SNOFLOW\n      QVAP = QSNSUB\n      QDEW = QSNFRO\n    END IF\n\n  END SUBROUTINE WATER_GLACIER\n! ==================================================================================================\n! ----------------------------------------------------------------------\n  SUBROUTINE SNOWWATER_GLACIER (NSNOW  ,NSOIL  ,IMELT  ,DT     ,SFCTMP , & !in\n                                SNOWHIN,QSNOW  ,QSNFRO ,QSNSUB ,QRAIN  , & !in\n                                FICEOLD,ZSOIL  ,SWE_LIMIT              , & !in\n                                ISNOW  ,SNOWH  ,SNEQV  ,SNICE  ,SNLIQ  , & !inout\n                                SH2O   ,SICE   ,STC    ,DZSNSO ,ZSNSO  , & !inout\n\t\t\t\tFSH    ,                                 & !inout\n                                QSNBOT ,SNOFLOW,PONDING1       ,PONDING2)  !out\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  INTEGER,                         INTENT(IN)    :: NSNOW  !maximum no. of snow layers\n  INTEGER,                         INTENT(IN)    :: NSOIL  !no. of soil layers\n  INTEGER, DIMENSION(-NSNOW+1:0) , INTENT(IN)    :: IMELT  !melting state index [0-no melt;1-melt]\n  REAL,                            INTENT(IN)    :: DT     !time step (s)\n  REAL,                            INTENT(IN)    :: SFCTMP !surface air temperature [k]\n  REAL,                            INTENT(IN)    :: SNOWHIN!snow depth increasing rate (m/s)\n  REAL,                            INTENT(IN)    :: QSNOW  !snow at ground srf (mm/s) [+]\n  REAL,                            INTENT(INOUT)    :: QSNFRO !snow surface frost rate[mm/s]\n  REAL,                            INTENT(INOUT)    :: QSNSUB !snow surface sublimation rate[mm/s]\n  REAL,                            INTENT(IN)    :: QRAIN  !snow surface rain rate[mm/s]\n  REAL, DIMENSION(-NSNOW+1:0)    , INTENT(IN)    :: FICEOLD!ice fraction at last timestep\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: ZSOIL  !layer-bottom depth from soil surf (m)\n  REAL,                            INTENT(IN)    :: SWE_LIMIT  !maximum SWE limit (mm)\n\n! input & output\n  INTEGER,                         INTENT(INOUT) :: ISNOW  !actual no. of snow layers\n  REAL,                            INTENT(INOUT) :: SNOWH  !snow height [m]\n  REAL,                            INTENT(INOUT) :: SNEQV  !snow water eqv. [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE  !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ  !snow layer liquid water [mm]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O   !soil liquid moisture (m3/m3)\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SICE   !soil ice moisture (m3/m3)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow layer temperature [k]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO !snow/soil layer thickness [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: ZSNSO  !layer-bottom depth from snow surf [m]\n  REAL                           , INTENT(INOUT) :: FSH     !total sensible heat (w/m2) [+ to atm]\n\n! output\n  REAL,                              INTENT(OUT) :: QSNBOT !melting water out of snow bottom [mm/s]\n  REAL,                              INTENT(OUT) :: SNOFLOW!glacier flow [mm]\n  REAL,                              INTENT(OUT) :: PONDING1\n  REAL,                              INTENT(OUT) :: PONDING2\n\n! local\n  INTEGER :: IZ\n  REAL    :: BDSNOW  !bulk density of snow (kg/m3)\n! ----------------------------------------------------------------------\n   SNOFLOW = 0.0\n   PONDING1 = 0.0\n   PONDING2 = 0.0\n\n   CALL SNOWFALL_GLACIER (NSOIL  ,NSNOW  ,DT     ,QSNOW  ,SNOWHIN, & !in\n                          SFCTMP ,                                 & !in\n                          ISNOW  ,SNOWH  ,DZSNSO ,STC    ,SNICE  , & !inout\n                          SNLIQ  ,SNEQV  )                           !inout\n\n   IF(ISNOW < 0) THEN        !WHEN MORE THAN ONE LAYER\n     CALL  COMPACT_GLACIER (NSNOW  ,NSOIL  ,DT     ,STC    ,SNICE  , & !in\n                            SNLIQ  ,IMELT  ,FICEOLD,                 & !in\n                            ISNOW  ,DZSNSO )                           !inout\n\n     CALL  COMBINE_GLACIER (NSNOW  ,NSOIL  ,                         & !in\n                            ISNOW  ,SH2O   ,STC    ,SNICE  ,SNLIQ  , & !inout\n                            DZSNSO ,SICE   ,SNOWH  ,SNEQV  ,         & !inout\n                            PONDING1       ,PONDING2)                  !out\n\n     CALL   DIVIDE_GLACIER (NSNOW  ,NSOIL  ,                         & !in\n                            ISNOW  ,STC    ,SNICE  ,SNLIQ  ,DZSNSO )   !inout\n   END IF\n\n!SET EMPTY SNOW LAYERS TO ZERO\n\n   DO IZ = -NSNOW+1, ISNOW\n        SNICE(IZ) = 0.\n        SNLIQ(IZ) = 0.\n        STC(IZ)   = 0.\n        DZSNSO(IZ)= 0.\n        ZSNSO(IZ) = 0.\n   ENDDO\n\n   CALL  SNOWH2O_GLACIER (NSNOW  ,NSOIL  ,DT     ,QSNFRO ,QSNSUB , & !in\n                          QRAIN  ,                                 & !in\n                          ISNOW  ,DZSNSO ,SNOWH  ,SNEQV  ,SNICE  , & !inout\n                          SNLIQ  ,SH2O   ,SICE   ,STC    ,         & !inout\n\t\t\t  PONDING1       ,PONDING2       ,FSH    , & !inout\n                          QSNBOT )                                   !out\n\n!to obtain equilibrium state of snow in glacier region\n\n   IF(SNEQV > SWE_LIMIT) THEN   ! 2000 mm -> maximum water depth\n      BDSNOW      = SNICE(0) / DZSNSO(0)\n      SNOFLOW     = (SNEQV - SWE_LIMIT)\n      SNICE(0)    = SNICE(0)  - SNOFLOW\n      DZSNSO(0)   = DZSNSO(0) - SNOFLOW/BDSNOW\n      SNOFLOW     = SNOFLOW / DT\n   END IF\n\n\n! sum up snow mass for layered snow\n\n   IF(ISNOW /= 0) THEN\n       SNEQV = 0.\n       DO IZ = ISNOW+1,0\n             SNEQV = SNEQV + SNICE(IZ) + SNLIQ(IZ)\n       ENDDO\n   END IF\n\n! Reset ZSNSO and layer thinkness DZSNSO\n\n   DO IZ = ISNOW+1, 0\n        DZSNSO(IZ) = -DZSNSO(IZ)\n   END DO\n\n   DZSNSO(1) = ZSOIL(1)\n   DO IZ = 2,NSOIL\n        DZSNSO(IZ) = (ZSOIL(IZ) - ZSOIL(IZ-1))\n   END DO\n\n   ZSNSO(ISNOW+1) = DZSNSO(ISNOW+1)\n   DO IZ = ISNOW+2 ,NSOIL\n       ZSNSO(IZ) = ZSNSO(IZ-1) + DZSNSO(IZ)\n   ENDDO\n\n   DO IZ = ISNOW+1 ,NSOIL\n       DZSNSO(IZ) = -DZSNSO(IZ)\n   END DO\n\n  END SUBROUTINE SNOWWATER_GLACIER\n! ==================================================================================================\n  SUBROUTINE SNOWFALL_GLACIER (NSOIL  ,NSNOW  ,DT     ,QSNOW  ,SNOWHIN , & !in\n                               SFCTMP ,                                  & !in\n                               ISNOW  ,SNOWH  ,DZSNSO ,STC    ,SNICE   , & !inout\n                               SNLIQ  ,SNEQV  )                            !inout\n! ----------------------------------------------------------------------\n! snow depth and density to account for the new snowfall.\n! new values of snow depth & density returned.\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n  INTEGER,                            INTENT(IN) :: NSOIL  !no. of soil layers\n  INTEGER,                            INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  REAL,                               INTENT(IN) :: DT     !main time step (s)\n  REAL,                               INTENT(IN) :: QSNOW  !snow at ground srf (mm/s) [+]\n  REAL,                               INTENT(IN) :: SNOWHIN!snow depth increasing rate (m/s)\n  REAL,                               INTENT(IN) :: SFCTMP !surface air temperature [k]\n\n! input and output\n\n  INTEGER,                         INTENT(INOUT) :: ISNOW  !actual no. of snow layers\n  REAL,                            INTENT(INOUT) :: SNOWH  !snow depth [m]\n  REAL,                            INTENT(INOUT) :: SNEQV  !swow water equivalent [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO !thickness of snow/soil layers (m)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow layer temperature [k]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE  !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ  !snow layer liquid water [mm]\n\n! local\n\n  INTEGER :: NEWNODE            ! 0-no new layers, 1-creating new layers\n! ----------------------------------------------------------------------\n    NEWNODE  = 0\n\n! shallow snow / no layer\n\n    IF(ISNOW == 0 .and. QSNOW > 0.)  THEN\n      SNOWH = SNOWH + SNOWHIN * DT\n      SNEQV = SNEQV + QSNOW * DT\n    END IF\n\n! creating a new layer\n\n    IF(ISNOW == 0  .AND. QSNOW>0. .AND. SNOWH >= 0.05) THEN\n      ISNOW    = -1\n      NEWNODE  =  1\n      DZSNSO(0)= SNOWH\n      SNOWH    = 0.\n      STC(0)   = MIN(273.16, SFCTMP)   ! temporary setup\n      SNICE(0) = SNEQV\n      SNLIQ(0) = 0.\n    END IF\n\n! snow with layers\n\n    IF(ISNOW <  0 .AND. NEWNODE == 0 .AND. QSNOW > 0.) then\n         SNICE(ISNOW+1)  = SNICE(ISNOW+1)   + QSNOW   * DT\n         DZSNSO(ISNOW+1) = DZSNSO(ISNOW+1)  + SNOWHIN * DT\n    ENDIF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOWFALL_GLACIER\n! ==================================================================================================\n! ----------------------------------------------------------------------\n  SUBROUTINE COMPACT_GLACIER (NSNOW  ,NSOIL  ,DT     ,STC    ,SNICE , & !in\n                              SNLIQ  ,IMELT  ,FICEOLD,                & !in\n                              ISNOW  ,DZSNSO )                          !inout\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n   INTEGER,                         INTENT(IN)    :: NSOIL  !no. of soil layers [ =4]\n   INTEGER,                         INTENT(IN)    :: NSNOW  !maximum no. of snow layers [ =3]\n   INTEGER, DIMENSION(-NSNOW+1:0) , INTENT(IN)    :: IMELT  !melting state index [0-no melt;1-melt]\n   REAL,                            INTENT(IN)    :: DT     !time step (sec)\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)    :: STC    !snow layer temperature [k]\n   REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: SNICE  !snow layer ice [mm]\n   REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: SNLIQ  !snow layer liquid water [mm]\n   REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: FICEOLD!ice fraction at last timestep\n\n! input and output\n   INTEGER,                         INTENT(INOUT) :: ISNOW  ! actual no. of snow layers\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO ! snow layer thickness [m]\n\n! local\n   REAL, PARAMETER     :: C2 = 21.e-3   ![m3/kg] ! default 21.e-3\n   REAL, PARAMETER     :: C3 = 2.5e-6   ![1/s]\n   REAL, PARAMETER     :: C4 = 0.04     ![1/k]\n   REAL, PARAMETER     :: C5 = 2.0      !\n   REAL, PARAMETER     :: DM = 100.0    !upper Limit on destructive metamorphism compaction [kg/m3]\n   REAL, PARAMETER     :: ETA0 = 0.8e+6 !viscosity coefficient [kg-s/m2]\n                                        !according to Anderson, it is between 0.52e6~1.38e6\n   REAL :: BURDEN !pressure of overlying snow [kg/m2]\n   REAL :: DDZ1   !rate of settling of snow pack due to destructive metamorphism.\n   REAL :: DDZ2   !rate of compaction of snow pack due to overburden.\n   REAL :: DDZ3   !rate of compaction of snow pack due to melt [1/s]\n   REAL :: DEXPF  !EXPF=exp(-c4*(273.15-STC)).\n   REAL :: TD     !STC - TFRZ [K]\n   REAL :: PDZDTC !nodal rate of change in fractional-thickness due to compaction [fraction/s]\n   REAL :: VOID   !void (1 - SNICE - SNLIQ)\n   REAL :: WX     !water mass (ice + liquid) [kg/m2]\n   REAL :: BI     !partial density of ice [kg/m3]\n   REAL, DIMENSION(-NSNOW+1:0) :: FICE   !fraction of ice at current time step\n\n   INTEGER  :: J\n\n! ----------------------------------------------------------------------\n    BURDEN = 0.0\n\n    DO J = ISNOW+1, 0\n\n        WX      = SNICE(J) + SNLIQ(J)\n        FICE(J) = SNICE(J) / WX\n        VOID    = 1. - (SNICE(J)/DENICE + SNLIQ(J)/DENH2O) / DZSNSO(J)\n\n        ! Allow compaction only for non-saturated node and higher ice lens node.\n        IF (VOID > 0.001 .AND. SNICE(J) > 0.1) THEN\n           BI = SNICE(J) / DZSNSO(J)\n           TD = MAX(0.,TFRZ-STC(J))\n           DEXPF = EXP(-C4*TD)\n\n           ! Settling as a result of destructive metamorphism\n\n           DDZ1 = -C3*DEXPF\n\n           IF (BI > DM) DDZ1 = DDZ1*EXP(-46.0E-3*(BI-DM))\n\n           ! Liquid water term\n\n           IF (SNLIQ(J) > 0.01*DZSNSO(J)) DDZ1=DDZ1*C5\n\n           ! Compaction due to overburden\n\n           DDZ2 = -(BURDEN+0.5*WX)*EXP(-0.08*TD-C2*BI)/ETA0 ! 0.5*WX -> self-burden\n\n           ! Compaction occurring during melt\n\n           IF (IMELT(J) == 1) THEN\n              DDZ3 = MAX(0.,(FICEOLD(J) - FICE(J))/MAX(1.E-6,FICEOLD(J)))\n              DDZ3 = - DDZ3/DT           ! sometimes too large\n           ELSE\n              DDZ3 = 0.\n           END IF\n\n           ! Time rate of fractional change in DZ (units of s-1)\n\n           PDZDTC = (DDZ1 + DDZ2 + DDZ3)*DT\n           PDZDTC = MAX(-0.5,PDZDTC)\n\n           ! The change in DZ due to compaction\n\n           DZSNSO(J) = DZSNSO(J)*(1.+PDZDTC)\n        END IF\n\n        ! Pressure of overlying snow\n\n        BURDEN = BURDEN + WX\n\n    END DO\n\n  END SUBROUTINE COMPACT_GLACIER\n! ==================================================================================================\n  SUBROUTINE COMBINE_GLACIER (NSNOW  ,NSOIL  ,                         & !in\n                              ISNOW  ,SH2O   ,STC    ,SNICE  ,SNLIQ  , & !inout\n                              DZSNSO ,SICE   ,SNOWH  ,SNEQV  ,         & !inout\n                              PONDING1       ,PONDING2)                  !inout\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n    INTEGER, INTENT(IN)     :: NSNOW                        !maximum no. of snow layers\n    INTEGER, INTENT(IN)     :: NSOIL                        !no. of soil layers\n\n! input and output\n\n    INTEGER,                         INTENT(INOUT) :: ISNOW !actual no. of snow layers\n    REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O  !soil liquid moisture (m3/m3)\n    REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SICE  !soil ice moisture (m3/m3)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC   !snow layer temperature [k]\n    REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE !snow layer ice [mm]\n    REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ !snow layer liquid water [mm]\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO!snow layer depth [m]\n    REAL,                            INTENT(INOUT) :: SNEQV !snow water equivalent [m]\n    REAL,                            INTENT(INOUT) :: SNOWH !snow depth [m]\n    REAL,                            INTENT(INOUT) :: PONDING1\n    REAL,                            INTENT(INOUT) :: PONDING2\n\n! local variables:\n\n    INTEGER :: I,J,K,L               ! node indices\n    INTEGER :: ISNOW_OLD             ! number of top snow layer\n    INTEGER :: MSSI                  ! node index\n    INTEGER :: NEIBOR                ! adjacent node selected for combination\n    REAL    :: ZWICE                 ! total ice mass in snow\n    REAL    :: ZWLIQ                 ! total liquid water in snow\n    REAL    :: DZMIN(3)              ! minimum of top snow layer\n    DATA DZMIN /0.045, 0.05, 0.2/\n!    DATA DZMIN /0.025, 0.025, 0.1/  ! MB: change limit\n!-----------------------------------------------------------------------\n\n       ISNOW_OLD = ISNOW\n\n       DO J = ISNOW_OLD+1,0\n          IF (SNICE(J) <= .1) THEN\n             IF(J /= 0) THEN\n                SNLIQ(J+1) = SNLIQ(J+1) + SNLIQ(J)\n                SNICE(J+1) = SNICE(J+1) + SNICE(J)\n             ELSE\n               IF (ISNOW_OLD < -1) THEN\n                SNLIQ(J-1) = SNLIQ(J-1) + SNLIQ(J)\n                SNICE(J-1) = SNICE(J-1) + SNICE(J)\n               ELSE\n                PONDING1 = PONDING1 + SNLIQ(J)       ! ISNOW WILL GET SET TO ZERO BELOW\n                SNEQV = SNICE(J)                     ! PONDING WILL GET ADDED TO PONDING FROM\n                SNOWH = DZSNSO(J)                    ! PHASECHANGE WHICH SHOULD BE ZERO HERE\n                SNLIQ(J) = 0.0                       ! BECAUSE THERE IT WAS ONLY CALCULATED\n                SNICE(J) = 0.0                       ! FOR THIN SNOW\n                DZSNSO(J) = 0.0\n               ENDIF\n!                SH2O(1) = SH2O(1)+SNLIQ(J)/(DZSNSO(1)*1000.)\n!                SICE(1) = SICE(1)+SNICE(J)/(DZSNSO(1)*1000.)\n             ENDIF\n\n             ! shift all elements above this down by one.\n             IF (J > ISNOW+1 .AND. ISNOW < -1) THEN\n                DO I = J, ISNOW+2, -1\n                   STC(I)   = STC(I-1)\n                   SNLIQ(I) = SNLIQ(I-1)\n                   SNICE(I) = SNICE(I-1)\n                   DZSNSO(I)= DZSNSO(I-1)\n                END DO\n             END IF\n             ISNOW = ISNOW + 1\n          END IF\n       END DO\n\n! to conserve water in case of too large surface sublimation\n\n       IF(SICE(1) < 0.) THEN\n          SH2O(1) = SH2O(1) + SICE(1)\n          SICE(1) = 0.\n       END IF\n\n       IF(ISNOW ==0) RETURN   ! MB: get out if no longer multi-layer\n\n       SNEQV  = 0.\n       SNOWH  = 0.\n       ZWICE  = 0.\n       ZWLIQ  = 0.\n\n       DO J = ISNOW+1,0\n             SNEQV = SNEQV + SNICE(J) + SNLIQ(J)\n             SNOWH = SNOWH + DZSNSO(J)\n             ZWICE = ZWICE + SNICE(J)\n             ZWLIQ = ZWLIQ + SNLIQ(J)\n       END DO\n\n! check the snow depth - all snow gone\n! the liquid water assumes ponding on soil surface.\n\n!       IF (SNOWH < 0.025 .AND. ISNOW < 0 ) THEN ! MB: change limit\n       IF (SNOWH < 0.05 .AND. ISNOW < 0 ) THEN\n          ISNOW  = 0\n          SNEQV = ZWICE\n          PONDING2 = PONDING2 + ZWLIQ           ! LIMIT OF ISNOW < 0 MEANS INPUT PONDING\n          IF(SNEQV <= 0.) SNOWH = 0.            ! SHOULD BE ZERO; SEE ABOVE\n       END IF\n\n!       IF (SNOWH < 0.05 ) THEN\n!          ISNOW  = 0\n!          SNEQV = ZWICE\n!          SH2O(1) = SH2O(1) + ZWLIQ / (DZSNSO(1) * 1000.)\n!          IF(SNEQV <= 0.) SNOWH = 0.\n!       END IF\n\n! check the snow depth - snow layers combined\n\n       IF (ISNOW < -1) THEN\n\n          ISNOW_OLD = ISNOW\n          MSSI     = 1\n\n          DO I = ISNOW_OLD+1,0\n             IF (DZSNSO(I) < DZMIN(MSSI)) THEN\n\n                IF (I == ISNOW+1) THEN\n                   NEIBOR = I + 1\n                ELSE IF (I == 0) THEN\n                   NEIBOR = I - 1\n                ELSE\n                   NEIBOR = I + 1\n                   IF ((DZSNSO(I-1)+DZSNSO(I)) < (DZSNSO(I+1)+DZSNSO(I))) NEIBOR = I-1\n                END IF\n\n                ! Node l and j are combined and stored as node j.\n                IF (NEIBOR > I) THEN\n                   J = NEIBOR\n                   L = I\n                ELSE\n                   J = I\n                   L = NEIBOR\n                END IF\n\n                CALL COMBO_GLACIER (DZSNSO(J), SNLIQ(J), SNICE(J), &\n                   STC(J), DZSNSO(L), SNLIQ(L), SNICE(L), STC(L) )\n\n                ! Now shift all elements above this down one.\n                IF (J-1 > ISNOW+1) THEN\n                   DO K = J-1, ISNOW+2, -1\n                      STC(K)   = STC(K-1)\n                      SNICE(K) = SNICE(K-1)\n                      SNLIQ(K) = SNLIQ(K-1)\n                      DZSNSO(K) = DZSNSO(K-1)\n                   END DO\n                END IF\n\n                ! Decrease the number of snow layers\n                ISNOW = ISNOW + 1\n                IF (ISNOW >= -1) EXIT\n             ELSE\n\n                ! The layer thickness is greater than the prescribed minimum value\n                MSSI = MSSI + 1\n\n             END IF\n          END DO\n\n       END IF\n\n  END SUBROUTINE COMBINE_GLACIER\n! ==================================================================================================\n\n! ----------------------------------------------------------------------\n  SUBROUTINE COMBO_GLACIER(DZ,  WLIQ,  WICE, T, DZ2, WLIQ2, WICE2, T2)\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------s\n! input\n\n    REAL, INTENT(IN)    :: DZ2   !nodal thickness of 2 elements being combined [m]\n    REAL, INTENT(IN)    :: WLIQ2 !liquid water of element 2 [kg/m2]\n    REAL, INTENT(IN)    :: WICE2 !ice of element 2 [kg/m2]\n    REAL, INTENT(IN)    :: T2    !nodal temperature of element 2 [k]\n    REAL, INTENT(INOUT) :: DZ    !nodal thickness of 1 elements being combined [m]\n    REAL, INTENT(INOUT) :: WLIQ  !liquid water of element 1\n    REAL, INTENT(INOUT) :: WICE  !ice of element 1 [kg/m2]\n    REAL, INTENT(INOUT) :: T     !node temperature of element 1 [k]\n\n! local\n\n    REAL                :: DZC   !total thickness of nodes 1 and 2 (DZC=DZ+DZ2).\n    REAL                :: WLIQC !combined liquid water [kg/m2]\n    REAL                :: WICEC !combined ice [kg/m2]\n    REAL                :: TC    !combined node temperature [k]\n    REAL                :: H     !enthalpy of element 1 [J/m2]\n    REAL                :: H2    !enthalpy of element 2 [J/m2]\n    REAL                :: HC    !temporary\n\n!-----------------------------------------------------------------------\n\n    DZC = DZ+DZ2\n    WICEC = (WICE+WICE2)\n    WLIQC = (WLIQ+WLIQ2)\n    H = (CICE*WICE+CWAT*WLIQ) * (T-TFRZ)+HFUS*WLIQ\n    H2= (CICE*WICE2+CWAT*WLIQ2) * (T2-TFRZ)+HFUS*WLIQ2\n\n    HC = H + H2\n    IF(HC < 0.)THEN\n       TC = TFRZ + HC/(CICE*WICEC + CWAT*WLIQC)\n    ELSE IF (HC.LE.HFUS*WLIQC) THEN\n       TC = TFRZ\n    ELSE\n       TC = TFRZ + (HC - HFUS*WLIQC) / (CICE*WICEC + CWAT*WLIQC)\n    END IF\n\n    DZ = DZC\n    WICE = WICEC\n    WLIQ = WLIQC\n    T = TC\n\n  END SUBROUTINE COMBO_GLACIER\n! ==================================================================================================\n  SUBROUTINE DIVIDE_GLACIER (NSNOW  ,NSOIL  ,                         & !in\n                             ISNOW  ,STC    ,SNICE  ,SNLIQ  ,DZSNSO  )  !inout\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n    INTEGER, INTENT(IN)                            :: NSNOW !maximum no. of snow layers [ =3]\n    INTEGER, INTENT(IN)                            :: NSOIL !no. of soil layers [ =4]\n\n! input and output\n\n    INTEGER                        , INTENT(INOUT) :: ISNOW !actual no. of snow layers\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC   !snow layer temperature [k]\n    REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE !snow layer ice [mm]\n    REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ !snow layer liquid water [mm]\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO!snow layer depth [m]\n\n! local variables:\n\n    INTEGER                                        :: J     !indices\n    INTEGER                                        :: MSNO  !number of layer (top) to MSNO (bot)\n    REAL                                           :: DRR   !thickness of the combined [m]\n    REAL, DIMENSION(       1:NSNOW)                :: DZ    !snow layer thickness [m]\n    REAL, DIMENSION(       1:NSNOW)                :: SWICE !partial volume of ice [m3/m3]\n    REAL, DIMENSION(       1:NSNOW)                :: SWLIQ !partial volume of liquid water [m3/m3]\n    REAL, DIMENSION(       1:NSNOW)                :: TSNO  !node temperature [k]\n    REAL                                           :: ZWICE !temporary\n    REAL                                           :: ZWLIQ !temporary\n    REAL                                           :: PROPOR!temporary\n    REAL                                           :: DTDZ  !temporary\n! ----------------------------------------------------------------------\n\n    DO J = 1,NSNOW\n          IF (J <= ABS(ISNOW)) THEN\n             DZ(J)    = DZSNSO(J+ISNOW)\n             SWICE(J) = SNICE(J+ISNOW)\n             SWLIQ(J) = SNLIQ(J+ISNOW)\n             TSNO(J)  = STC(J+ISNOW)\n          END IF\n    END DO\n\n       MSNO = ABS(ISNOW)\n\n       IF (MSNO == 1) THEN\n          ! Specify a new snow layer\n          IF (DZ(1) > 0.05) THEN\n             MSNO = 2\n             DZ(1)    = DZ(1)/2.\n             SWICE(1) = SWICE(1)/2.\n             SWLIQ(1) = SWLIQ(1)/2.\n             DZ(2)    = DZ(1)\n             SWICE(2) = SWICE(1)\n             SWLIQ(2) = SWLIQ(1)\n             TSNO(2)  = TSNO(1)\n          END IF\n       END IF\n\n       IF (MSNO > 1) THEN\n          IF (DZ(1) > 0.05) THEN\n             DRR      = DZ(1) - 0.05\n             PROPOR   = DRR/DZ(1)\n             ZWICE    = PROPOR*SWICE(1)\n             ZWLIQ    = PROPOR*SWLIQ(1)\n             PROPOR   = 0.05/DZ(1)\n             SWICE(1) = PROPOR*SWICE(1)\n             SWLIQ(1) = PROPOR*SWLIQ(1)\n             DZ(1)    = 0.05\n\n             CALL COMBO_GLACIER (DZ(2), SWLIQ(2), SWICE(2), TSNO(2), DRR, &\n                  ZWLIQ, ZWICE, TSNO(1))\n\n             ! subdivide a new layer\n!             IF (MSNO <= 2 .AND. DZ(2) > 0.20) THEN  ! MB: change limit\n             IF (MSNO <= 2 .AND. DZ(2) > 0.10) THEN\n                MSNO = 3\n                DTDZ = (TSNO(1) - TSNO(2))/((DZ(1)+DZ(2))/2.)\n                DZ(2)    = DZ(2)/2.\n                SWICE(2) = SWICE(2)/2.\n                SWLIQ(2) = SWLIQ(2)/2.\n                DZ(3)    = DZ(2)\n                SWICE(3) = SWICE(2)\n                SWLIQ(3) = SWLIQ(2)\n                TSNO(3) = TSNO(2) - DTDZ*DZ(2)/2.\n                IF (TSNO(3) >= TFRZ) THEN\n                   TSNO(3)  = TSNO(2)\n                ELSE\n                   TSNO(2) = TSNO(2) + DTDZ*DZ(2)/2.\n                ENDIF\n\n             END IF\n          END IF\n       END IF\n\n       IF (MSNO > 2) THEN\n          IF (DZ(2) > 0.2) THEN\n             DRR = DZ(2) - 0.2\n             PROPOR   = DRR/DZ(2)\n             ZWICE    = PROPOR*SWICE(2)\n             ZWLIQ    = PROPOR*SWLIQ(2)\n             PROPOR   = 0.2/DZ(2)\n             SWICE(2) = PROPOR*SWICE(2)\n             SWLIQ(2) = PROPOR*SWLIQ(2)\n             DZ(2)    = 0.2\n             CALL COMBO_GLACIER (DZ(3), SWLIQ(3), SWICE(3), TSNO(3), DRR, &\n                  ZWLIQ, ZWICE, TSNO(2))\n          END IF\n       END IF\n\n       ISNOW = -MSNO\n\n    DO J = ISNOW+1,0\n             DZSNSO(J) = DZ(J-ISNOW)\n             SNICE(J) = SWICE(J-ISNOW)\n             SNLIQ(J) = SWLIQ(J-ISNOW)\n             STC(J)   = TSNO(J-ISNOW)\n    END DO\n\n\n!    DO J = ISNOW+1,NSOIL\n!    WRITE(*,'(I5,7F10.3)') J, DZSNSO(J), SNICE(J), SNLIQ(J),STC(J)\n!    END DO\n\n  END SUBROUTINE DIVIDE_GLACIER\n! ==================================================================================================\n  SUBROUTINE SNOWH2O_GLACIER (NSNOW  ,NSOIL  ,DT     ,QSNFRO ,QSNSUB , & !in\n                              QRAIN  ,                                 & !in\n                              ISNOW  ,DZSNSO ,SNOWH  ,SNEQV  ,SNICE  , & !inout\n                              SNLIQ  ,SH2O   ,SICE   ,STC    ,         & !inout\n                              PONDING1       ,PONDING2       ,FSH    , & !inout\n                              QSNBOT )                                   !out\n! ----------------------------------------------------------------------\n! Renew the mass of ice lens (SNICE) and liquid (SNLIQ) of the\n! surface snow layer resulting from sublimation (frost) / evaporation (dew)\n! ----------------------------------------------------------------------\n   IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n   INTEGER,                         INTENT(IN)    :: NSNOW  !maximum no. of snow layers[=3]\n   INTEGER,                         INTENT(IN)    :: NSOIL  !No. of soil layers[=4]\n   REAL,                            INTENT(IN)    :: DT     !time step\n   REAL,                            INTENT(INOUT)    :: QSNFRO !snow surface frost rate[mm/s]\n   REAL,                            INTENT(INOUT)    :: QSNSUB !snow surface sublimation rate[mm/s]\n   REAL,                            INTENT(IN)    :: QRAIN  !snow surface rain rate[mm/s]\n\n! output\n\n   REAL,                            INTENT(OUT)   :: QSNBOT !melting water out of snow bottom [mm/s]\n\n! input and output\n\n   INTEGER,                         INTENT(INOUT) :: ISNOW  !actual no. of snow layers\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO ! snow layer depth [m]\n   REAL,                            INTENT(INOUT) :: SNOWH  !snow height [m]\n   REAL,                            INTENT(INOUT) :: SNEQV  !snow water eqv. [mm]\n   REAL, DIMENSION(-NSNOW+1:0),     INTENT(INOUT) :: SNICE  !snow layer ice [mm]\n   REAL, DIMENSION(-NSNOW+1:0),     INTENT(INOUT) :: SNLIQ  !snow layer liquid water [mm]\n   REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O   !soil liquid moisture (m3/m3)\n   REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SICE   !soil ice moisture (m3/m3)\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow layer temperature [k]\n   REAL,                            INTENT(INOUT) :: PONDING1\n   REAL,                            INTENT(INOUT) :: PONDING2\n   REAL,                            INTENT(INOUT) :: FSH     !total sensible heat (w/m2) [+ to atm]\n\n! local variables:\n\n   INTEGER                     :: J         !do loop/array indices\n   REAL                        :: QIN       !water flow into the element (mm/s)\n   REAL                        :: QOUT      !water flow out of the element (mm/s)\n   REAL                        :: WGDIF     !ice mass after minus sublimation\n   REAL, DIMENSION(-NSNOW+1:0) :: VOL_LIQ   !partial volume of liquid water in layer\n   REAL, DIMENSION(-NSNOW+1:0) :: VOL_ICE   !partial volume of ice lens in layer\n   REAL, DIMENSION(-NSNOW+1:0) :: EPORE     !effective porosity = porosity - VOL_ICE\n   REAL :: PROPOR, TEMP\n! ----------------------------------------------------------------------\n\n!for the case when SNEQV becomes '0' after 'COMBINE'\n\n   IF(SNEQV == 0.) THEN\n     IF(OPT_GLA == 1) THEN\n       SICE(1) =  SICE(1) + (QSNFRO-QSNSUB)*DT/(DZSNSO(1)*1000.)\n     ELSEIF(OPT_GLA == 2) THEN\n       FSH = FSH - (QSNFRO-QSNSUB)*HSUB\n       QSNFRO = 0.0\n       QSNSUB = 0.0\n     END IF\n   END IF\n\n! for shallow snow without a layer\n! snow surface sublimation may be larger than existing snow mass. To conserve water,\n! excessive sublimation is used to reduce soil water. Smaller time steps would tend\n! to aviod this problem.\n\n   IF(ISNOW == 0 .and. SNEQV > 0.) THEN\n      IF(OPT_GLA == 1) THEN\n        TEMP   = SNEQV\n        SNEQV  = SNEQV - QSNSUB*DT + QSNFRO*DT\n        PROPOR = SNEQV/TEMP\n        SNOWH  = MAX(0.,PROPOR * SNOWH)\n      ELSEIF(OPT_GLA == 2) THEN\n        FSH = FSH - (QSNFRO-QSNSUB)*HSUB\n        QSNFRO = 0.0\n        QSNSUB = 0.0\n      END IF\n\n      IF(SNEQV < 0.) THEN\n         SICE(1) = SICE(1) + SNEQV/(DZSNSO(1)*1000.)\n         SNEQV   = 0.\n         SNOWH   = 0.\n      END IF\n      IF(SICE(1) < 0.) THEN\n         SH2O(1) = SH2O(1) + SICE(1)\n         SICE(1) = 0.\n      END IF\n   END IF\n\n   IF(SNOWH <= 1.E-8 .OR. SNEQV <= 1.E-6) THEN\n     SNOWH = 0.0\n     SNEQV = 0.0\n   END IF\n\n! for deep snow\n\n   IF ( ISNOW < 0 ) THEN !KWM added this IF statement to prevent out-of-bounds array references\n\n      WGDIF = SNICE(ISNOW+1) - QSNSUB*DT + QSNFRO*DT\n      SNICE(ISNOW+1) = WGDIF\n      IF (WGDIF < 1.e-6 .and. ISNOW <0) THEN\n         CALL  COMBINE_GLACIER (NSNOW  ,NSOIL  ,                         & !in\n                                ISNOW  ,SH2O   ,STC    ,SNICE  ,SNLIQ  , & !inout\n                                DZSNSO ,SICE   ,SNOWH  ,SNEQV  ,         & !inout\n                               PONDING1, PONDING2 )                        !inout\n      ENDIF\n      !KWM:  Subroutine COMBINE can change ISNOW to make it 0 again?\n      IF ( ISNOW < 0 ) THEN !KWM added this IF statement to prevent out-of-bounds array references\n         SNLIQ(ISNOW+1) = SNLIQ(ISNOW+1) + QRAIN * DT\n         SNLIQ(ISNOW+1) = MAX(0., SNLIQ(ISNOW+1))\n      ENDIF\n\n   ENDIF !KWM  -- Can the ENDIF be moved toward the end of the subroutine (Just set QSNBOT=0)?\n\n! Porosity and partial volume\n\n   !KWM Looks to me like loop index / IF test can be simplified.\n\n   DO J = -NSNOW+1, 0\n      IF (J >= ISNOW+1) THEN\n         VOL_ICE(J)      = MIN(1., SNICE(J)/(DZSNSO(J)*DENICE))\n         EPORE(J)        = 1. - VOL_ICE(J)\n         VOL_LIQ(J)      = MIN(EPORE(J),SNLIQ(J)/(DZSNSO(J)*DENH2O))\n      END IF\n   END DO\n\n   QIN = 0.\n   QOUT = 0.\n\n   !KWM Looks to me like loop index / IF test can be simplified.\n\n   DO J = -NSNOW+1, 0\n      IF (J >= ISNOW+1) THEN\n         SNLIQ(J) = SNLIQ(J) + QIN\n         IF (J <= -1) THEN\n            IF (EPORE(J) < 0.05 .OR. EPORE(J+1) < 0.05) THEN\n               QOUT = 0.\n            ELSE\n               QOUT = MAX(0.,(VOL_LIQ(J)-SSI*EPORE(J))*DZSNSO(J))\n               QOUT = MIN(QOUT,(1.-VOL_ICE(J+1)-VOL_LIQ(J+1))*DZSNSO(J+1))\n            END IF\n         ELSE\n            QOUT = MAX(0.,(VOL_LIQ(J) - SSI*EPORE(J))*DZSNSO(J))\n         END IF\n         QOUT = QOUT*1000.\n         SNLIQ(J) = SNLIQ(J) - QOUT\n         QIN = QOUT\n      END IF\n   END DO\n\n! Liquid water from snow bottom to soil\n\n   QSNBOT = QOUT / DT           ! mm/s\n\n  END SUBROUTINE SNOWH2O_GLACIER\n! ********************* end of water subroutines ******************************************\n! ==================================================================================================\n  SUBROUTINE ERROR_GLACIER (ILOC   ,JLOC   ,SWDOWN ,FSA    ,FSR    ,FIRA   , &\n                            FSH    ,FGEV   ,SSOIL  ,SAG    ,PRCP   ,EDIR   , &\n\t\t            RUNSRF ,RUNSUB ,SNEQV  ,DT     ,BEG_WB )\n! --------------------------------------------------------------------------------------------------\n! check surface energy balance and water balance\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n  INTEGER                        , INTENT(IN) :: ILOC   !grid index\n  INTEGER                        , INTENT(IN) :: JLOC   !grid index\n  REAL                           , INTENT(IN) :: SWDOWN !downward solar filtered by sun angle [w/m2]\n  REAL                           , INTENT(IN) :: FSA    !total absorbed solar radiation (w/m2)\n  REAL                           , INTENT(IN) :: FSR    !total reflected solar radiation (w/m2)\n  REAL                           , INTENT(IN) :: FIRA   !total net longwave rad (w/m2)  [+ to atm]\n  REAL                           , INTENT(IN) :: FSH    !total sensible heat (w/m2)     [+ to atm]\n  REAL                           , INTENT(IN) :: FGEV   !ground evaporation heat (w/m2) [+ to atm]\n  REAL                           , INTENT(IN) :: SSOIL  !ground heat flux (w/m2)        [+ to soil]\n  REAL                           , INTENT(IN) :: SAG\n\n  REAL                           , INTENT(IN) :: PRCP   !precipitation rate (kg m-2 s-1)\n  REAL                           , INTENT(IN) :: EDIR   !soil surface evaporation rate[mm/s]\n  REAL                           , INTENT(IN) :: RUNSRF !surface runoff [mm/s]\n  REAL                           , INTENT(IN) :: RUNSUB !baseflow (saturation excess) [mm/s]\n  REAL                           , INTENT(IN) :: SNEQV  !snow water eqv. [mm]\n  REAL                           , INTENT(IN) :: DT     !time step [sec]\n  REAL                           , INTENT(IN) :: BEG_WB !water storage at begin of a timesetp [mm]\n\n  REAL                                        :: END_WB !water storage at end of a timestep [mm]\n  REAL                                        :: ERRWAT !error in water balance [mm/timestep]\n  REAL                                        :: ERRENG !error in surface energy balance [w/m2]\n  REAL                                        :: ERRSW  !error in shortwave radiation balance [w/m2]\n  CHARACTER(len=256)                          :: message\n! --------------------------------------------------------------------------------------------------\n   ERRSW   = SWDOWN - (FSA + FSR)\n   IF (ERRSW > 0.01) THEN            ! w/m2\n     WRITE(*,*) \"SAG    =\",SAG\n     WRITE(*,*) \"FSA    =\",FSA\n     WRITE(*,*) \"FSR    =\",FSR\n     WRITE(message,*) 'ERRSW =',ERRSW\n     call wrf_message(trim(message))\n     call wrf_error_fatal(\"Radiation budget problem in NOAHMP GLACIER\")\n   END IF\n\n   ERRENG = SAG-(FIRA+FSH+FGEV+SSOIL)\n   IF(ERRENG > 0.01) THEN\n      write(message,*) 'ERRENG =',ERRENG\n      call wrf_message(trim(message))\n      WRITE(message,'(i6,1x,i6,1x,5F10.4)')ILOC,JLOC,SAG,FIRA,FSH,FGEV,SSOIL\n      call wrf_message(trim(message))\n      call wrf_error_fatal(\"Energy budget problem in NOAHMP GLACIER\")\n   END IF\n\n   END_WB = SNEQV\n   ERRWAT = END_WB-BEG_WB-(PRCP-EDIR-RUNSRF-RUNSUB)*DT\n\n#ifndef WRF_HYDRO\n   IF(ABS(ERRWAT) > 0.1) THEN\n      if (ERRWAT > 0) then\n         call wrf_message ('The model is gaining water (ERRWAT is positive)')\n      else\n         call wrf_message('The model is losing water (ERRWAT is negative)')\n      endif\n      write(message, *) 'ERRWAT =',ERRWAT, \"kg m{-2} timestep{-1}\"\n      call wrf_message(trim(message))\n      WRITE(message,'(\"    I      J     END_WB     BEG_WB       PRCP       EDIR      RUNSRF     RUNSUB\")')\n           call wrf_message(trim(message))\n           WRITE(message,'(i6,1x,i6,1x,2f15.3,4f11.5)')ILOC,JLOC,END_WB,BEG_WB,PRCP*DT,&\n                EDIR*DT,RUNSRF*DT,RUNSUB*DT\n           call wrf_message(trim(message))\n           call wrf_error_fatal(\"Water budget problem in NOAHMP GLACIER\")\n        END IF\n#endif\n\n END SUBROUTINE ERROR_GLACIER\n! ==================================================================================================\n\n  SUBROUTINE NOAHMP_OPTIONS_GLACIER(iopt_alb  ,iopt_snf  ,iopt_tbot, iopt_stc, iopt_gla )\n\n  IMPLICIT NONE\n\n  INTEGER,  INTENT(IN) :: iopt_alb  !snow surface albedo (1->BATS; 2->CLASS)\n  INTEGER,  INTENT(IN) :: iopt_snf  !rainfall & snowfall (1-Jordan91; 2->BATS; 3->Noah)\n  INTEGER,  INTENT(IN) :: iopt_tbot !lower boundary of soil temperature (1->zero-flux; 2->Noah)\n  INTEGER,  INTENT(IN) :: iopt_stc  !snow/soil temperature time scheme (only layer 1)\n                                    ! 1 -> semi-implicit; 2 -> full implicit (original Noah)\n  INTEGER,  INTENT(IN) :: IOPT_GLA  ! glacier option (1->phase change; 2->simple)\n\n! -------------------------------------------------------------------------------------------------\n\n  opt_alb  = iopt_alb\n  opt_snf  = iopt_snf\n  opt_tbot = iopt_tbot\n  opt_stc  = iopt_stc\n  opt_gla  = iopt_gla\n\n  end subroutine noahmp_options_glacier\n\nEND MODULE NOAHMP_GLACIER_ROUTINES\n! ==================================================================================================\n\nMODULE MODULE_SF_NOAHMP_GLACIER\n\n  USE NOAHMP_GLACIER_ROUTINES\n  USE NOAHMP_GLACIER_GLOBALS\n\nEND MODULE MODULE_SF_NOAHMP_GLACIER\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/module_sf_noahmp_groundwater.F",
    "content": "MODULE module_sf_noahmp_groundwater\n!===============================================================================\n! Module to calculate lateral groundwater flow and the flux between groundwater and rivers\n! plus the routine to update soil moisture and water table due to those two fluxes\n! according to the Miguez-Macho & Fan groundwater scheme (Miguez-Macho et al., JGR 2007).\n! Module written by Gonzalo Miguez-Macho , U. de Santiago de Compostela, Galicia, Spain\n! November 2012\n!===============================================================================\n\nCONTAINS\n\n  SUBROUTINE WTABLE_mmf_noahmp (NSOIL     ,XLAND    ,XICE    ,XICE_THRESHOLD  ,ISICE ,& !in\n                                ISLTYP    ,SMOISEQ  ,DZS     ,WTDDT                  ,& !in\n                                FDEPTH    ,AREA     ,TOPO    ,ISURBAN ,IVGTYP        ,& !in\n                                RIVERCOND ,RIVERBED ,EQWTD   ,PEXP                   ,& !in\n                                SMOIS     ,SH2OXY   ,SMCWTD  ,WTD  ,QRF              ,& !inout\n                                DEEPRECH  ,QSPRING  ,QSLAT   ,QRFS ,QSPRINGS  ,RECH  ,& !inout\n                                ids,ide, jds,jde, kds,kde,                    &\n                                ims,ime, jms,jme, kms,kme,                    &\n                                its,ite, jts,jte, kts,kte                     )\n\n! ----------------------------------------------------------------------\n  USE NOAHMP_TABLES, ONLY: BEXP_TABLE, DKSAT_TABLE, SMCMAX_TABLE,PSISAT_TABLE, SMCWLT_TABLE\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! IN only\n\n  INTEGER,  INTENT(IN   )   ::     ids,ide, jds,jde, kds,kde,  &\n       &                           ims,ime, jms,jme, kms,kme,  &\n       &                           its,ite, jts,jte, kts,kte\n    REAL,   INTENT(IN)        ::     WTDDT\n    REAL,   INTENT(IN)        ::     XICE_THRESHOLD\n    INTEGER,  INTENT(IN   )   ::     ISICE\n    REAL,    DIMENSION( ims:ime, jms:jme )                     , &\n         &   INTENT(IN   )    ::                          XLAND, &\n                                                           XICE\n    INTEGER, DIMENSION( ims:ime, jms:jme )                     , &\n             INTENT(IN   )    ::                         ISLTYP, &\n                                                         IVGTYP\n    INTEGER, INTENT(IN)       ::     nsoil\n    INTEGER, INTENT(IN)       ::     ISURBAN\n    REAL,     DIMENSION( ims:ime , 1:nsoil, jms:jme ), &\n         &    INTENT(IN)      ::                        SMOISEQ\n    REAL,     DIMENSION(1:nsoil), INTENT(IN)     ::         DZS\n    REAL,    DIMENSION( ims:ime, jms:jme )                     , &\n         &   INTENT(IN)       ::                         FDEPTH, &\n                                                           AREA, &\n                                                           TOPO, &\n                                                          EQWTD, &\n                                                           PEXP, &\n                                                       RIVERBED, &\n                                                      RIVERCOND\n\n! IN and OUT\n\n    REAL,     DIMENSION( ims:ime , 1:nsoil, jms:jme ), &\n         &    INTENT(INOUT)   ::                          SMOIS, &\n         &                                                SH2OXY\n\n\n    REAL,    DIMENSION( ims:ime, jms:jme )                     , &\n         &   INTENT(INOUT)    ::                            WTD, &\n                                                         SMCWTD, &\n                                                       DEEPRECH, &\n                                                          QSLAT, &\n                                                           QRFS, &\n                                                       QSPRINGS, &\n                                                           RECH\n\n!OUT\n\n    REAL,    DIMENSION( ims:ime, jms:jme )                     , &\n         &   INTENT(OUT)      ::                            QRF, &  !groundwater - river water flux\n                                                        QSPRING     !water springing at the surface from groundwater convergence in the column\n\n!LOCAL\n\n  INTEGER                          :: I,J,K\n  REAL, DIMENSION(       0:NSOIL)  :: ZSOIL !depth of soil layer-bottom [m]\n  REAL,  DIMENSION(      1:NSOIL)  :: SMCEQ  !equilibrium soil water  content [m3/m3]\n  REAL,  DIMENSION(      1:NSOIL)  :: SMC,SH2O\n  REAL                                        :: DELTAT,RCOND,TOTWATER,PSI &\n                                                ,WFLUXDEEP,WCNDDEEP,DDZ,SMCWTDMID &\n                                                ,WPLUS,WMINUS\n  REAL,      DIMENSION( ims:ime, jms:jme )    :: QLAT\n  INTEGER,   DIMENSION( ims:ime, jms:jme )    :: LANDMASK !-1 for water (ice or no ice) and glacial areas, 1 for land where the LSM does its soil moisture calculations.\n\n  REAL :: BEXP,DKSAT,PSISAT,SMCMAX,SMCWLT\n\n    DELTAT = WTDDT * 60. !timestep in seconds for this calculation\n\n    ZSOIL(0) = 0.\n    ZSOIL(1) = -DZS(1)\n    DO K = 2, NSOIL\n       ZSOIL(K)         = -DZS(K) + ZSOIL(K-1)\n    END DO\n\n    WHERE(XLAND-1.5.LT.0..AND.XICE.LT. XICE_THRESHOLD.AND.IVGTYP.NE.ISICE)\n         LANDMASK=1\n    ELSEWHERE\n         LANDMASK=-1\n    ENDWHERE\n\n!Calculate lateral flow\n\n    QLAT = 0.\nCALL LATERALFLOW(ISLTYP,WTD,QLAT,FDEPTH,TOPO,LANDMASK,DELTAT,AREA       &\n                        ,ids,ide,jds,jde,kds,kde                      &\n                        ,ims,ime,jms,jme,kms,kme                      &\n                        ,its,ite,jts,jte,kts,kte                      )\n\n\n!compute flux from grounwater to rivers in the cell\n\n    DO J=jts,jte\n       DO I=its,ite\n          IF(LANDMASK(I,J).GT.0)THEN\n             IF(WTD(I,J) .GT. RIVERBED(I,J) .AND.  EQWTD(I,J) .GT. RIVERBED(I,J)) THEN\n               RCOND = RIVERCOND(I,J) * EXP(PEXP(I,J)*(WTD(I,J)-EQWTD(I,J)))\n             ELSE\n               RCOND = RIVERCOND(I,J)\n             ENDIF\n             QRF(I,J) = RCOND * (WTD(I,J)-RIVERBED(I,J)) * DELTAT/AREA(I,J)\n!for now, dont allow it to go from river to groundwater\n             QRF(I,J) = MAX(QRF(I,J),0.)\n          ELSE\n             QRF(I,J) = 0.\n          ENDIF\n       ENDDO\n    ENDDO\n\n\n    DO J=jts,jte\n       DO I=its,ite\n          IF(LANDMASK(I,J).GT.0)THEN\n\n            BEXP   = BEXP_TABLE   (ISLTYP(I,J))\n            DKSAT  = DKSAT_TABLE  (ISLTYP(I,J))\n            PSISAT = -1.0*PSISAT_TABLE (ISLTYP(I,J))\n            SMCMAX = SMCMAX_TABLE (ISLTYP(I,J))\n            SMCWLT = SMCWLT_TABLE (ISLTYP(I,J))\n\n             IF(IVGTYP(I,J)==ISURBAN)THEN\n                 SMCMAX = 0.45\n                 SMCWLT = 0.40\n             ENDIF\n\n!for deep water table calculate recharge\n             IF(WTD(I,J) < ZSOIL(NSOIL)-DZS(NSOIL))THEN\n!assume all liquid if the wtd is deep\n                DDZ = ZSOIL(NSOIL)-WTD(I,J)\n                SMCWTDMID = 0.5 * (SMCWTD(I,J) + SMCMAX )\n                PSI = PSISAT * ( SMCMAX / SMCWTD(I,J) ) ** BEXP\n                WCNDDEEP = DKSAT * ( SMCWTDMID / SMCMAX ) ** (2.0*BEXP + 3.0)\n                WFLUXDEEP =  - DELTAT * WCNDDEEP * ( (PSISAT-PSI) / DDZ - 1.)\n!update deep soil moisture\n                SMCWTD(I,J) = SMCWTD(I,J)  + (DEEPRECH(I,J) -  WFLUXDEEP)  / DDZ\n                WPLUS       = MAX((SMCWTD(I,J)-SMCMAX), 0.0) * DDZ\n                WMINUS       = MAX((1.E-4-SMCWTD(I,J)), 0.0) * DDZ\n                SMCWTD(I,J) = MAX( MIN(SMCWTD(I,J),SMCMAX) , 1.E-4)\n                WFLUXDEEP = WFLUXDEEP + WPLUS - WMINUS\n                DEEPRECH(I,J) = WFLUXDEEP\n              ENDIF\n\n\n!Total water flux to or from groundwater in the cell\n             TOTWATER = QLAT(I,J) - QRF(I,J) + DEEPRECH(I,J)\n\n             SMC(1:NSOIL) = SMOIS(I,1:NSOIL,J)\n             SH2O(1:NSOIL) = SH2OXY(I,1:NSOIL,J)\n             SMCEQ(1:NSOIL) = SMOISEQ(I,1:NSOIL,J)\n\n!Update the water table depth and soil moisture\n             CALL UPDATEWTD ( NSOIL, DZS , ZSOIL, SMCEQ, SMCMAX, SMCWLT, PSISAT, BEXP ,I , J , &!in\n                              TOTWATER, WTD(I,J), SMC, SH2O, SMCWTD(I,J)      , &!inout\n                              QSPRING(I,J) ) !out\n\n!now update soil moisture\n             SMOIS(I,1:NSOIL,J) = SMC(1:NSOIL)\n             SH2OXY(I,1:NSOIL,J) = SH2O(1:NSOIL)\n\n           ENDIF\n       ENDDO\n    ENDDO\n\n!accumulate fluxes for output\n\n    DO J=jts,jte\n       DO I=its,ite\n           QSLAT(I,J) = QSLAT(I,J) + QLAT(I,J)*1.E3\n           QRFS(I,J) = QRFS(I,J) + QRF(I,J)*1.E3\n           QSPRINGS(I,J) = QSPRINGS(I,J) + QSPRING(I,J)*1.E3\n           RECH(I,J) = RECH(I,J) + DEEPRECH(I,J)*1.E3\n!zero out DEEPRECH\n           DEEPRECH(I,J) =0.\n       ENDDO\n    ENDDO\n\n\nEND  SUBROUTINE WTABLE_mmf_noahmp\n! ==================================================================================================\n! ----------------------------------------------------------------------\n  SUBROUTINE LATERALFLOW  (ISLTYP,WTD,QLAT,FDEPTH,TOPO,LANDMASK,DELTAT,AREA &\n                           ,ids,ide,jds,jde,kds,kde                      &\n                           ,ims,ime,jms,jme,kms,kme                      &\n                           ,its,ite,jts,jte,kts,kte                      )\n! ----------------------------------------------------------------------\n  USE NOAHMP_TABLES, ONLY : DKSAT_TABLE\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  INTEGER,  INTENT(IN   )   ::     ids,ide, jds,jde, kds,kde,  &\n       &                           ims,ime, jms,jme, kms,kme,  &\n       &                           its,ite, jts,jte, kts,kte\n  REAL                                  , INTENT(IN) :: DELTAT                                 \n  INTEGER, DIMENSION( ims:ime, jms:jme ), INTENT(IN) :: ISLTYP, LANDMASK\n  REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN) :: FDEPTH,WTD,TOPO,AREA\n\n!output\n  REAL, DIMENSION( ims:ime , jms:jme ), INTENT(OUT) :: QLAT\n\n!local\n  INTEGER                              :: I, J, itsh,iteh,jtsh,jteh\n  REAL                                 :: Q,KLAT\n  REAL, DIMENSION( ims:ime , jms:jme ) :: KCELL, HEAD\n\n  REAL, DIMENSION(19)      :: KLATFACTOR\n  DATA KLATFACTOR /2.,3.,4.,10.,10.,12.,14.,20.,24.,28.,40.,48.,2.,0.,10.,0.,20.,2.,2./\n\n  REAL,    PARAMETER :: PI = 3.14159265\n  REAL,    PARAMETER :: FANGLE = 0.22754493   ! = 0.5*sqrt(0.5*tan(pi/8))\n\nitsh=max(its-1,ids)\niteh=min(ite+1,ide-1)\njtsh=max(jts-1,jds)\njteh=min(jte+1,jde-1)\n\n\n    DO J=jtsh,jteh\n       DO I=itsh,iteh\n           IF(FDEPTH(I,J).GT.0.)THEN\n                 KLAT = DKSAT_TABLE(ISLTYP(I,J)) * KLATFACTOR(ISLTYP(I,J))\n                 IF(WTD(I,J) < -1.5)THEN\n                     KCELL(I,J) = FDEPTH(I,J) * KLAT * EXP( (WTD(I,J) + 1.5) / FDEPTH(I,J) )\n                 ELSE\n                     KCELL(I,J) = KLAT * ( WTD(I,J) + 1.5 + FDEPTH(I,J) )  \n                 ENDIF\n           ELSE\n                 KCELL(i,J) = 0.\n           ENDIF\n\n           HEAD(I,J) = TOPO(I,J) + WTD(I,J)\n       ENDDO\n    ENDDO\n\nitsh=max(its,ids+1)\niteh=min(ite,ide-2)\njtsh=max(jts,jds+1)\njteh=min(jte,jde-2)\n\n    DO J=jtsh,jteh\n       DO I=itsh,iteh\n          IF(LANDMASK(I,J).GT.0)THEN\n                 Q=0.\n\n                 Q  = Q + (KCELL(I-1,J+1)+KCELL(I,J)) &\n                        * (HEAD(I-1,J+1)-HEAD(I,J))/SQRT(2.)\n\n                 Q  = Q +  (KCELL(I-1,J)+KCELL(I,J)) &\n                        *  (HEAD(I-1,J)-HEAD(I,J))\n\n                 Q  = Q +  (KCELL(I-1,J-1)+KCELL(I,J)) &\n                        * (HEAD(I-1,J-1)-HEAD(I,J))/SQRT(2.)\n\n                 Q  = Q +  (KCELL(I,J+1)+KCELL(I,J)) &\n                        * (HEAD(I,J+1)-HEAD(I,J))\n\n                 Q  = Q +  (KCELL(I,J-1)+KCELL(I,J)) &\n                        * (HEAD(I,J-1)-HEAD(I,J))\n\n                 Q  = Q +  (KCELL(I+1,J+1)+KCELL(I,J)) &\n                        * (HEAD(I+1,J+1)-HEAD(I,J))/SQRT(2.)\n\n                 Q  = Q +  (KCELL(I+1,J)+KCELL(I,J)) &\n                        * (HEAD(I+1,J)-HEAD(I,J))\n\n                 Q  = Q +  (KCELL(I+1,J-1)+KCELL(I,J)) &\n                        * (HEAD(I+1,J-1)-HEAD(I,J))/SQRT(2.)\n\n\n                 QLAT(I,J) = FANGLE* Q * DELTAT / AREA(I,J)\n          ENDIF\n       ENDDO\n    ENDDO\n\n\nEND  SUBROUTINE LATERALFLOW\n! ==================================================================================================\n! ----------------------------------------------------------------------\n  SUBROUTINE UPDATEWTD  (NSOIL,  DZS,  ZSOIL ,SMCEQ                ,& !in\n                         SMCMAX, SMCWLT, PSISAT, BEXP ,ILOC ,JLOC  ,& !in\n                         TOTWATER, WTD ,SMC, SH2O ,SMCWTD          ,& !inout\n                         QSPRING                                 )  !out\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  INTEGER,                         INTENT(IN) :: NSOIL !no. of soil layers\n  INTEGER,                         INTENT(IN) :: ILOC, JLOC\n  REAL,                         INTENT(IN)    :: SMCMAX\n  REAL,                         INTENT(IN)    :: SMCWLT\n  REAL,                         INTENT(IN)    :: PSISAT\n  REAL,                         INTENT(IN)    :: BEXP\n  REAL,  DIMENSION(       0:NSOIL), INTENT(IN) :: ZSOIL !depth of soil layer-bottom [m]\n  REAL,  DIMENSION(       1:NSOIL), INTENT(IN) :: SMCEQ  !equilibrium soil water  content [m3/m3]\n  REAL,  DIMENSION(       1:NSOIL), INTENT(IN) :: DZS ! soil layer thickness [m]\n! input-output\n  REAL                           , INTENT(INOUT) :: TOTWATER\n  REAL                           , INTENT(INOUT) :: WTD\n  REAL                           , INTENT(INOUT) :: SMCWTD\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SMC\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O\n! output\n  REAL                           , INTENT(OUT) :: QSPRING\n!local\n  INTEGER                                     :: K\n  INTEGER                                     :: K1\n  INTEGER                                     :: IWTD\n  INTEGER                                     :: KWTD\n  REAL                                        :: MAXWATUP, MAXWATDW ,WTDOLD\n  REAL                                        :: WGPMID\n  REAL                                        :: SYIELDDW\n  REAL                                        :: DZUP\n  REAL                                        :: SMCEQDEEP\n  REAL, DIMENSION(       1:NSOIL)             :: SICE\n! -------------------------------------------------------------\n\n\n\n  QSPRING=0.\n\n  SICE = SMC - SH2O\n\niwtd=1\n\n!case 1: totwater > 0 (water table going up):\nIF(totwater.gt.0.)then\n\n\n         if(wtd.ge.zsoil(nsoil))then\n\n            do k=nsoil-1,1,-1\n              if(wtd.lt.zsoil(k))exit\n            enddo\n            iwtd=k\n            kwtd=iwtd+1\n\n!max water that fits in the layer\n            maxwatup=dzs(kwtd)*(smcmax-smc(kwtd))\n\n            if(totwater.le.maxwatup)then\n               smc(kwtd) = smc(kwtd) + totwater / dzs(kwtd)\n               smc(kwtd) = min(smc(kwtd),smcmax)\n               if(smc(kwtd).gt.smceq(kwtd))wtd = min ( ( smc(kwtd)*dzs(kwtd) &\n                 - smceq(kwtd)*zsoil(iwtd) + smcmax*zsoil(kwtd) ) / &\n                     ( smcmax-smceq(kwtd) ) , zsoil(iwtd) )\n               totwater=0.\n            else   !water enough to saturate the layer\n              smc(kwtd) = smcmax\n              totwater=totwater-maxwatup\n              k1=iwtd\n              do k=k1,0,-1\n                 wtd = zsoil(k)\n                 iwtd=k-1\n                 if(k.eq.0)exit\n                 maxwatup=dzs(k)*(smcmax-smc(k))\n                 if(totwater.le.maxwatup)then\n                   smc(k) = smc(k) + totwater / dzs(k)\n                   smc(k) = min(smc(k),smcmax)\n                   if(smc(k).gt.smceq(k))wtd = min ( ( smc(k)*dzs(k) &\n                     - smceq(k)*zsoil(iwtd) + smcmax*zsoil(k) ) / &\n                     ( smcmax-smceq(k) ) , zsoil(iwtd) )\n                   totwater=0.\n                   exit\n                 else\n                    smc(k) = smcmax\n                    totwater=totwater-maxwatup\n                 endif\n\n              enddo\n\n            endif\n\n         elseif(wtd.ge.zsoil(nsoil)-dzs(nsoil))then ! wtd below bottom of soil model\n\n            !gmmequilibrium soil moisture content\n               smceqdeep = smcmax * ( psisat / &\n                           (psisat - dzs(nsoil)) ) ** (1./bexp)\n!               smceqdeep = max(smceqdeep,smcwlt)\n               smceqdeep = max(smceqdeep,1.E-4)\n\n            maxwatup=(smcmax-smcwtd)*dzs(nsoil)\n\n            if(totwater.le.maxwatup)then\n                smcwtd = smcwtd + totwater / dzs(nsoil)\n                smcwtd = min(smcwtd,smcmax)\n                if(smcwtd.gt.smceqdeep)wtd = min( ( smcwtd*dzs(nsoil) &\n                 - smceqdeep*zsoil(nsoil) + smcmax*(zsoil(nsoil)-dzs(nsoil)) ) / &\n                     ( smcmax-smceqdeep ) , zsoil(nsoil) )\n                totwater=0.\n            else\n                smcwtd=smcmax\n                totwater=totwater-maxwatup\n                do k=nsoil,0,-1\n                    wtd=zsoil(k)\n                    iwtd=k-1\n                    if(k.eq.0)exit\n                    maxwatup=dzs(k)*(smcmax-smc(k))\n                    if(totwater.le.maxwatup)then\n                     smc(k) = min(smc(k) + totwater / dzs(k),smcmax)\n                     if(smc(k).gt.smceq(k))wtd = min ( ( smc(k)*dzs(k) &\n                        - smceq(k)*zsoil(iwtd) + smcmax*zsoil(k) ) / &\n                           ( smcmax-smceq(k) ) , zsoil(iwtd) )\n                     totwater=0.\n                     exit\n                    else\n                     smc(k) = smcmax\n                     totwater=totwater-maxwatup\n                    endif\n                enddo\n             endif\n\n!deep water table\n       else\n\n            maxwatup=(smcmax-smcwtd)*(zsoil(nsoil)-dzs(nsoil)-wtd)\n            if(totwater.le.maxwatup)then\n               wtd = wtd + totwater/(smcmax-smcwtd)\n               totwater=0.\n            else\n               totwater=totwater-maxwatup\n               wtd=zsoil(nsoil)-dzs(nsoil)\n               maxwatup=(smcmax-smcwtd)*dzs(nsoil)\n              if(totwater.le.maxwatup)then\n\n            !gmmequilibrium soil moisture content\n               smceqdeep = smcmax * ( psisat / &\n                           (psisat - dzs(nsoil)) ) ** (1./bexp)\n!               smceqdeep = max(smceqdeep,smcwlt)\n               smceqdeep = max(smceqdeep,1.E-4)\n\n                smcwtd = smcwtd + totwater / dzs(nsoil)\n                smcwtd = min(smcwtd,smcmax)\n                wtd = ( smcwtd*dzs(nsoil) &\n                 - smceqdeep*zsoil(nsoil) + smcmax*(zsoil(nsoil)-dzs(nsoil)) ) / &\n                     ( smcmax-smceqdeep )\n                totwater=0.\n              else\n                smcwtd=smcmax\n                totwater=totwater-maxwatup\n                do k=nsoil,0,-1\n                    wtd=zsoil(k)\n                    iwtd=k-1\n                    if(k.eq.0)exit\n                    maxwatup=dzs(k)*(smcmax-smc(k))\n\n                    if(totwater.le.maxwatup)then\n                     smc(k) = smc(k) + totwater / dzs(k)\n                     smc(k) = min(smc(k),smcmax)\n                     if(smc(k).gt.smceq(k))wtd = ( smc(k)*dzs(k) &\n                        - smceq(k)*zsoil(iwtd) + smcmax*zsoil(k) ) / &\n                           ( smcmax-smceq(k) )\n                     totwater=0.\n                     exit\n                    else\n                     smc(k) = smcmax\n                     totwater=totwater-maxwatup\n                    endif\n                   enddo\n               endif\n             endif\n         endif\n\n!water springing at the surface\n        qspring=totwater\n\n!case 2: totwater < 0 (water table going down):\nELSEIF(totwater.lt.0.)then\n\n\n         if(wtd.ge.zsoil(nsoil))then !wtd in the resolved layers\n\n            do k=nsoil-1,1,-1\n               if(wtd.lt.zsoil(k))exit\n            enddo\n            iwtd=k\n\n               k1=iwtd+1\n               do kwtd=k1,nsoil\n\n!max water that the layer can yield\n                  maxwatdw=dzs(kwtd)*(smc(kwtd)-max(smceq(kwtd),sice(kwtd)))\n\n                  if(-totwater.le.maxwatdw)then\n                        smc(kwtd) = smc(kwtd) + totwater / dzs(kwtd)\n                        if(smc(kwtd).gt.smceq(kwtd))then\n                              wtd = ( smc(kwtd)*dzs(kwtd) &\n                                 - smceq(kwtd)*zsoil(iwtd) + smcmax*zsoil(kwtd) ) / &\n                                 ( smcmax-smceq(kwtd) )\n                         else\n                              wtd=zsoil(kwtd)\n                              iwtd=iwtd+1\n                         endif\n                         totwater=0.\n                         exit\n                   else\n                         wtd = zsoil(kwtd)\n                         iwtd=iwtd+1\n                         if(maxwatdw.ge.0.)then\n                            smc(kwtd) = smc(kwtd) + maxwatdw / dzs(kwtd)\n                            totwater = totwater + maxwatdw\n                         endif\n                   endif\n\n                enddo\n\n               if(iwtd.eq.nsoil.and.totwater.lt.0.)then\n            !gmmequilibrium soil moisture content\n               smceqdeep = smcmax * ( psisat / &\n                           (psisat - dzs(nsoil)) ) ** (1./bexp)\n!               smceqdeep = max(smceqdeep,smcwlt)\n               smceqdeep = max(smceqdeep,1.E-4)\n\n                  maxwatdw=dzs(nsoil)*(smcwtd-smceqdeep)\n\n                  if(-totwater.le.maxwatdw)then\n\n                       smcwtd = smcwtd + totwater / dzs(nsoil)\n                       wtd = max( ( smcwtd*dzs(nsoil) &\n                           - smceqdeep*zsoil(nsoil) + smcmax*(zsoil(nsoil)-dzs(nsoil)) ) / &\n                            ( smcmax-smceqdeep ) , zsoil(nsoil)-dzs(nsoil) )\n\n                  else\n\n                       wtd=zsoil(nsoil)-dzs(nsoil)\n                       smcwtd = smcwtd + totwater / dzs(nsoil)\n!and now even further down\n                       dzup=(smceqdeep-smcwtd)*dzs(nsoil)/(smcmax-smceqdeep)\n                       wtd=wtd-dzup\n                       smcwtd=smceqdeep\n\n                  endif\n\n                endif\n\n\n\n        elseif(wtd.ge.zsoil(nsoil)-dzs(nsoil))then\n\n!if wtd was already below the bottom of the resolved soil crust\n            !gmmequilibrium soil moisture content\n               smceqdeep = smcmax * ( psisat / &\n                           (psisat - dzs(nsoil)) ) ** (1./bexp)\n!               smceqdeep = max(smceqdeep,smcwlt)\n               smceqdeep = max(smceqdeep,1.E-4)\n\n            maxwatdw=dzs(nsoil)*(smcwtd-smceqdeep)\n\n            if(-totwater.le.maxwatdw)then\n\n               smcwtd = smcwtd + totwater / dzs(nsoil)\n               wtd = max( ( smcwtd*dzs(nsoil) &\n                    - smceqdeep*zsoil(nsoil) + smcmax*(zsoil(nsoil)-dzs(nsoil)) ) / &\n                    ( smcmax-smceqdeep ) , zsoil(nsoil)-dzs(nsoil) )\n\n            else\n\n               wtd=zsoil(nsoil)-dzs(nsoil)\n               smcwtd = smcwtd + totwater / dzs(nsoil)\n!and now even further down\n               dzup=(smceqdeep-smcwtd)*dzs(nsoil)/(smcmax-smceqdeep)\n               wtd=wtd-dzup\n               smcwtd=smceqdeep\n\n             endif\n\n         else\n!gmmequilibrium soil moisture content\n               wgpmid = smcmax * ( psisat / &\n                    (psisat - (zsoil(nsoil)-wtd)) ) ** (1./bexp)\n!               wgpmid=max(wgpmid,smcwlt)\n               wgpmid=max(wgpmid,1.E-4)\n               syielddw=smcmax-wgpmid\n               wtdold=wtd\n               wtd = wtdold + totwater/syielddw\n!update wtdwgp\n               smcwtd = (smcwtd*(zsoil(nsoil)-wtdold)+wgpmid*(wtdold-wtd) ) / (zsoil(nsoil)-wtd)\n\n          endif\n\n          qspring=0.\n\nENDIF\n\n         SH2O = SMC - SICE\n\n\nEND  SUBROUTINE UPDATEWTD\n\n! ----------------------------------------------------------------------\n\nEND MODULE module_sf_noahmp_groundwater\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/module_sf_noahmpdrv.F",
    "content": "MODULE module_sf_noahmpdrv\n\n!-------------------------------\n#if ( WRF_CHEM == 1 )\n  USE module_data_gocart_dust\n#endif\n!-------------------------------\n\n!\nCONTAINS\n!\n  SUBROUTINE noahmplsm(ITIMESTEP,        YR,   JULIAN,   COSZIN,   XLATIN,  & ! IN : Time/Space-related\n                  DZ8W,       DT,       DZS,    NSOIL,       DX,            & ! IN : Model configuration\n\t        IVGTYP,   ISLTYP,    VEGFRA,   VEGMAX,      TMN,            & ! IN : Vegetation/Soil characteristics\n\t\t XLAND,     XICE,XICE_THRES,                                & ! IN : Vegetation/Soil characteristics\n                 IDVEG, IOPT_CRS,  IOPT_BTR, IOPT_RUN, IOPT_SFC, IOPT_FRZ,  & ! IN : User options\n              IOPT_INF, IOPT_RAD,  IOPT_ALB, IOPT_SNF,IOPT_TBOT, IOPT_STC,  & ! IN : User options\n              IOPT_GLA, IOPT_RSF, IOPT_SOIL,IOPT_PEDO,IOPT_CROP,            & ! IN : User options\n              IOPT_IMPERV, IZ0TLND,                                         & ! IN : User options\n                   T3D,     QV3D,     U_PHY,    V_PHY,   SWDOWN,      GLW,  & ! IN : Forcing\n\t\t P8W3D,PRECIP_IN,        SR,                                & ! IN : Forcing\n                   TSK,      HFX,      QFX,        LH,   GRDFLX,    SMSTAV, & ! IN/OUT LSM eqv\n                SMSTOT,SFCRUNOFF, UDRUNOFF,    ALBEDO,    SNOWC,     SMOIS, & ! IN/OUT LSM eqv\n\t\t  SH2O,     TSLB,     SNOW,     SNOWH,   CANWAT,    ACSNOM, & ! IN/OUT LSM eqv\n\t\tACSNOW,    EMISS,     QSFC,                                 & ! IN/OUT LSM eqv\n \t\t    Z0,      ZNT,                                           & ! IN/OUT LSM eqv\n               ISNOWXY,     TVXY,     TGXY,  CANICEXY, CANLIQXY,     EAHXY, & ! IN/OUT Noah MP only\n\t         TAHXY,     CMXY,     CHXY,    FWETXY, SNEQVOXY,  ALBOLDXY, & ! IN/OUT Noah MP only\n               QSNOWXY, QRAINXY, WSLAKEXY, ZWTXY,  WAXY,   WTXY,    TSNOXY, & ! IN/OUT Noah MP only\n\t       ZSNSOXY,  SNICEXY,  SNLIQXY,  LFMASSXY, RTMASSXY,  STMASSXY, & ! IN/OUT Noah MP only\n\t        WOODXY, STBLCPXY, FASTCPXY,    XLAIXY,   XSAIXY,   TAUSSXY, & ! IN/OUT Noah MP only\n\t       SMOISEQ, SMCWTDXY,DEEPRECHXY,   RECHXY,                      & ! IN/OUT Noah MP only\n\t        T2MVXY,   T2MBXY,    Q2MVXY,   Q2MBXY,                      & ! OUT Noah MP only\n\t        TRADXY,    NEEXY,    GPPXY,     NPPXY,   FVEGXY,   RUNSFXY, & ! OUT Noah MP only\n\t       RUNSBXY,   ECANXY,   EDIRXY,   ETRANXY,    FSAXY,    FIRAXY, & ! OUT Noah MP only\n\t        APARXY,    PSNXY,    SAVXY,     SAGXY,  RSSUNXY,   RSSHAXY, & ! OUT Noah MP only\n              ALBSNDXY, ALBSNIXY,                                           & ! OUT Noah MP only\n\t\tBGAPXY,   WGAPXY,    TGVXY,     TGBXY,    CHVXY,     CHBXY, & ! OUT Noah MP only\n\t\t SHGXY,    SHCXY,    SHBXY,     EVGXY,    EVBXY,     GHVXY, & ! OUT Noah MP only\n\t\t GHBXY,    IRGXY,    IRCXY,     IRBXY,     TRXY,     EVCXY, & ! OUT Noah MP only\n              CHLEAFXY,   CHUCXY,   CHV2XY,    CHB2XY,                      & ! OUT Noah MP only\n              PSNOWLIQXY, PSNOWTEMPXY, PSNOWDZXY,                           & ! OUT    for crocus\n              PSNOWHEATXY, PSNOWRHOXY, PSNOWSWEXY,                          & ! IN/OUT for crocus\n              PSNOWGRAN1XY, PSNOWGRAN2XY, PSNOWHISTXY,                      & ! IN/OUT for crocus\n              PSNOWALBXY, PSNOWAGEXY, act_level,                            & ! IN/OUT for crocus\n              PSNOWHEIGHTXY, PSNOWTOTSWEXY,  PSNOWTHRUFALXY,                & ! OUT    for crocus\n              GLACINFO ,GLACT,                                              & ! IN/OUT for crocus\n              FLOW_ICE, FLOW_SNOW,                                          & ! OUT    for crocus\n              crocus_opt,                                                   & ! IN     for crocus\n#ifdef SPATIAL_SOIL\n                 BEXP_3D,SMCDRY_3D,SMCWLT_3D,SMCREF_3D,SMCMAX_3D,             &\n\t\t DKSAT_3D,DWSAT_3D,PSISAT_3D,QUARTZ_3D,                       &\n\t\t REFDK_2D,REFKDT_2D,SLOPE_2D,                                 &\n\t\t CWPVT_2D,VCMX25_2D,MP_2D,HVT_2D,MFSNO_2D,RSURFEXP_2D,        &\n                 AXAJ_2D,BXAJ_2D,XXAJ_2D,                                     &\n                 IMPERV_2D,                                                   &\n                 SSI_2D,SNOWRETFAC_2D,TAU0_2D,RSURFSNOW_2D,SCAMAX_2D,         &\n#endif\n#ifdef WRF_HYDRO\n               sfcheadrt,INFXSRT,soldrain,                                  &\n#endif\n               ids,ide,  jds,jde,  kds,kde,                    &\n               ims,ime,  jms,jme,  kms,kme,                    &\n               its,ite,  jts,jte,  kts,kte,                    &\n               MP_RAINC, MP_RAINNC, MP_SHCV, MP_SNOW, MP_GRAUP, MP_HAIL, &\n               VIS_ICEALB  &\n#ifdef WRF_HYDRO\n               , ACCPRCP,  ACCECAN, ACCETRAN,   ACCEDIR        &         ! NEW output accumulator variables\n               , SOILSAT_TOP, SOILSAT, SOILICE, SNOWT_AVG      &         ! NEW soil saturation and snow temp\n#endif\n               )\n!----------------------------------------------------------------\n    USE MODULE_SF_NOAHMPLSM\n    USE module_sf_noahmp_glacier\n    USE NOAHMP_TABLES, ONLY: ISICE_TABLE, CO2_TABLE, O2_TABLE, HVB_TABLE, HVT_TABLE\n    USE module_snowcro\n    USE MODD_SNOW_PAR, ONLY: XZ0SN, XZ0HSN\n\n!----------------------------------------------------------------\n    IMPLICIT NONE\n!----------------------------------------------------------------\n\n! IN only\n\n    INTEGER,                                         INTENT(IN   ) ::  ITIMESTEP ! timestep number\n    INTEGER,                                         INTENT(IN   ) ::  YR        ! 4-digit year\n    REAL,                                            INTENT(IN   ) ::  JULIAN    ! Julian day\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  COSZIN    ! cosine zenith angle\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  XLATIN    ! latitude [rad]\n    REAL,    DIMENSION( ims:ime, kms:kme, jms:jme ), INTENT(IN   ) ::  DZ8W      ! thickness of atmo layers [m]\n    REAL,                                            INTENT(IN   ) ::  DT        ! timestep [s]\n    REAL,    DIMENSION(1:nsoil),                     INTENT(IN   ) ::  DZS       ! thickness of soil layers [m]\n    INTEGER,                                         INTENT(IN   ) ::  NSOIL     ! number of soil layers\n    REAL,                                            INTENT(IN   ) ::  DX        ! horizontal grid spacing [m]\n    INTEGER, DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  IVGTYP    ! vegetation type\n    INTEGER, DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  ISLTYP    ! soil type\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  VEGFRA    ! vegetation fraction []\n    REAL,    DIMENSION( ims:ime ,         jms:jme ), INTENT(IN   ) ::  VEGMAX    ! annual max vegetation fraction []\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  TMN       ! deep soil temperature [K]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  XLAND     ! =2 ocean; =1 land/seaice\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  XICE      ! fraction of grid that is seaice\n    REAL,                                            INTENT(IN   ) ::  XICE_THRES! fraction of grid determining seaice\n    INTEGER,                                         INTENT(IN   ) ::  IDVEG     ! dynamic vegetation (1 -> off ; 2 -> on) with opt_crs = 1\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_CRS  ! canopy stomatal resistance (1-> Ball-Berry; 2->Jarvis)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_BTR  ! soil moisture factor for stomatal resistance (1-> Noah; 2-> CLM; 3-> SSiB)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_RUN  ! runoff and groundwater (1->SIMGM; 2->SIMTOP; 3->Schaake96; 4->BATS)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_SFC  ! surface layer drag coeff (CH & CM) (1->M-O; 2->Chen97)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_FRZ  ! supercooled liquid water (1-> NY06; 2->Koren99)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_INF  ! frozen soil permeability (1-> NY06; 2->Koren99)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_RAD  ! radiation transfer (1->gap=F(3D,cosz); 2->gap=0; 3->gap=1-Fveg)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_ALB  ! snow surface albedo (1->BATS; 2->CLASS)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_SNF  ! rainfall & snowfall (1-Jordan91; 2->BATS; 3->Noah)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_TBOT ! lower boundary of soil temperature (1->zero-flux; 2->Noah)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_STC  ! snow/soil temperature time scheme\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_GLA  ! glacier option (1->phase change; 2->simple)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_RSF  ! surface resistance (1->Sakaguchi/Zeng; 2->Seller; 3->mod Sellers; 4->1+snow)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_SOIL ! soil configuration option\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_PEDO ! soil pedotransfer function option\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_CROP ! crop model option (0->none; 1->Liu et al.)\n    INTEGER,                                         INTENT(IN   ) ::  IOPT_IMPERV !imperviousness infiltration adjustment (0->none; 1->total;\n                                                                                        !9->old)\n    INTEGER,                                         INTENT(IN   ) ::  IZ0TLND   ! option of Chen adjustment of Czil (not used)\n    REAL,    DIMENSION( ims:ime, kms:kme, jms:jme ), INTENT(IN   ) ::  T3D       ! 3D atmospheric temperature valid at mid-levels [K]\n    REAL,    DIMENSION( ims:ime, kms:kme, jms:jme ), INTENT(IN   ) ::  QV3D      ! 3D water vapor mixing ratio [kg/kg_dry]\n    REAL,    DIMENSION( ims:ime, kms:kme, jms:jme ), INTENT(IN   ) ::  U_PHY     ! 3D U wind component [m/s]\n    REAL,    DIMENSION( ims:ime, kms:kme, jms:jme ), INTENT(IN   ) ::  V_PHY     ! 3D V wind component [m/s]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  SWDOWN    ! solar down at surface [W m-2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  GLW       ! longwave down at surface [W m-2]\n    REAL,    DIMENSION( ims:ime, kms:kme, jms:jme ), INTENT(IN   ) ::  P8W3D     ! 3D pressure, valid at interface [Pa]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  PRECIP_IN ! total input precipitation [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ) ::  SR        ! frozen precipitation ratio [-]\n\n!Optional Detailed Precipitation Partitioning Inputs\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ), OPTIONAL ::  MP_RAINC  ! convective precipitation entering land model [mm] ! MB/AN : v3.7\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ), OPTIONAL ::  MP_RAINNC ! large-scale precipitation entering land model [mm]! MB/AN : v3.7\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ), OPTIONAL ::  MP_SHCV   ! shallow conv precip entering land model [mm]      ! MB/AN : v3.7\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ), OPTIONAL ::  MP_SNOW   ! snow precipitation entering land model [mm]       ! MB/AN : v3.7\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ), OPTIONAL ::  MP_GRAUP  ! graupel precipitation entering land model [mm]    ! MB/AN : v3.7\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(IN   ), OPTIONAL ::  MP_HAIL   ! hail precipitation entering land model [mm]       ! MB/AN : v3.7\n#ifdef WRF_HYDRO\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  sfcheadrt,INFXSRT,soldrain   ! for WRF-Hydro\n#endif\n#ifdef SPATIAL_SOIL\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  BEXP_3D   ! C-H B exponent\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  SMCDRY_3D ! Soil Moisture Limit: Dry\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  SMCWLT_3D ! Soil Moisture Limit: Wilt\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  SMCREF_3D ! Soil Moisture Limit: Reference\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  SMCMAX_3D ! Soil Moisture Limit: Max\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  DKSAT_3D  ! Saturated Soil Conductivity\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  DWSAT_3D  ! Saturated Soil Diffusivity\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  PSISAT_3D ! Saturated Matric Potential\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(IN) ::  QUARTZ_3D ! Soil quartz content\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  REFDK_2D  ! Reference Soil Conductivity\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  REFKDT_2D ! Soil Infiltration Parameter\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  SLOPE_2D  ! Soil Drainage Parameter\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  CWPVT_2D  ! Canopy wind parameter\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  VCMX25_2D ! VCmax at 25C\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  MP_2D     ! Slope of Ball-Berry rs-P relationship\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  HVT_2D    ! Canopy Height\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  MFSNO_2D  ! Snow cover m parameter\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  RSURFEXP_2D ! exponent in the shape parameter for soil resistance option 1\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  AXAJ_2D   ! Xinanjiang: Tension water distribution inflection parameter [-]\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  BXAJ_2D   ! Xinanjiang: Tension water distribution shape parameter [-]\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  XXAJ_2D   ! Xinanjiang: Free water distribution shape parameter [-]\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  IMPERV_2D ! impervious fraction\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  SSI_2D         ! liquid water holding capacity for snowpack (m3/m3)\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  SNOWRETFAC_2D  ! snowpack water release timescale factor (1/s)\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  TAU0_2D        ! tau0 from Yang97 eqn. 10a\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  RSURFSNOW_2D   ! surface resistence for snow [s/m]\n    REAL,    DIMENSION( ims:ime, jms:jme ), INTENT(IN)          ::  SCAMAX_2D      ! max fractional snow covered area (0.0-1.0)\n#endif\n\n! INOUT (with generic LSM equivalent)\n\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  TSK       ! surface radiative temperature [K]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  HFX       ! sensible heat flux [W m-2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  QFX       ! latent heat flux [kg s-1 m-2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  LH        ! latent heat flux [W m-2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  GRDFLX    ! ground/snow heat flux [W m-2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  SMSTAV    ! soil moisture avail. [not used]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  SMSTOT    ! total soil water [mm][not used]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  SFCRUNOFF ! accumulated surface runoff [m]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  UDRUNOFF  ! accumulated sub-surface runoff [m]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  ALBEDO    ! total grid albedo []\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  SNOWC     ! snow cover fraction []\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(INOUT) ::  SMOIS     ! volumetric soil moisture [m3/m3]\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(INOUT) ::  SH2O      ! volumetric liquid soil moisture [m3/m3]\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(INOUT) ::  TSLB      ! soil temperature [K]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  SNOW      ! snow water equivalent [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  SNOWH     ! physical snow depth [m]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  CANWAT    ! total canopy water + ice [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  ACSNOM    ! accumulated snow melt leaving pack\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  ACSNOW    ! accumulated snow on grid\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  EMISS     ! surface bulk emissivity\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  QSFC      ! bulk surface specific humidity\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  Z0        ! combined z0 sent to coupled model\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  ZNT       ! combined z0 sent to coupled model\n\n! INOUT (with no Noah LSM equivalent)\n\n    INTEGER, DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  ISNOWXY   ! actual no. of snow layers\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  TVXY      ! vegetation leaf temperature\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  TGXY      ! bulk ground surface temperature\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  CANICEXY  ! canopy-intercepted ice (mm)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  CANLIQXY  ! canopy-intercepted liquid water (mm)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  EAHXY     ! canopy air vapor pressure (pa)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  TAHXY     ! canopy air temperature (k)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  CMXY      ! bulk momentum drag coefficient\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  CHXY      ! bulk sensible heat exchange coefficient\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  FWETXY    ! wetted or snowed fraction of the canopy (-)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  SNEQVOXY  ! snow mass at last time step(mm h2o)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  ALBOLDXY  ! snow albedo at last time step (-)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  QSNOWXY   ! snowfall on the ground [mm/s]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  QRAINXY   ! rainfall on the ground [mm/s]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  WSLAKEXY  ! lake water storage [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  ZWTXY     ! water table depth [m]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  WAXY      ! water in the \"aquifer\" [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  WTXY      ! groundwater storage [mm]\n    REAL,    DIMENSION( ims:ime,-2:0,     jms:jme ), INTENT(INOUT) ::  TSNOXY    ! snow temperature [K]\n    REAL,    DIMENSION( ims:ime,-2:NSOIL, jms:jme ), INTENT(INOUT) ::  ZSNSOXY   ! snow layer depth [m]\n    REAL,    DIMENSION( ims:ime,-2:0,     jms:jme ), INTENT(INOUT) ::  SNICEXY   ! snow layer ice [mm]\n    REAL,    DIMENSION( ims:ime,-2:0,     jms:jme ), INTENT(INOUT) ::  SNLIQXY   ! snow layer liquid water [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  LFMASSXY  ! leaf mass [g/m2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  RTMASSXY  ! mass of fine roots [g/m2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  STMASSXY  ! stem mass [g/m2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  WOODXY    ! mass of wood (incl. woody roots) [g/m2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  STBLCPXY  ! stable carbon in deep soil [g/m2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  FASTCPXY  ! short-lived carbon, shallow soil [g/m2]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  XLAIXY    ! leaf area index\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  XSAIXY    ! stem area index\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  TAUSSXY   ! snow age factor\n    REAL,    DIMENSION( ims:ime, 1:nsoil, jms:jme ), INTENT(INOUT) ::  SMOISEQ   ! eq volumetric soil moisture [m3/m3]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  SMCWTDXY  ! soil moisture content in the layer to the water table when deep\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  DEEPRECHXY ! recharge to the water table when deep\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(INOUT) ::  RECHXY    ! recharge to the water table (diagnostic)\n\n! OUT (with no Noah LSM equivalent)\n\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  T2MVXY    ! 2m temperature of vegetation part\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  T2MBXY    ! 2m temperature of bare ground part\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  Q2MVXY    ! 2m mixing ratio of vegetation part\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  Q2MBXY    ! 2m mixing ratio of bare ground part\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  TRADXY    ! surface radiative temperature (k)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  NEEXY     ! net ecosys exchange (g/m2/s CO2)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  GPPXY     ! gross primary assimilation [g/m2/s C]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  NPPXY     ! net primary productivity [g/m2/s C]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  FVEGXY    ! Noah-MP vegetation fraction [-]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  RUNSFXY   ! surface runoff [mm/s]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  RUNSBXY   ! subsurface runoff [mm/s]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  ECANXY    ! evaporation of intercepted water (mm/s)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  EDIRXY    ! soil surface evaporation rate (mm/s]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  ETRANXY   ! transpiration rate (mm/s)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  FSAXY     ! total absorbed solar radiation (w/m2)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  FIRAXY    ! total net longwave rad (w/m2) [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  APARXY    ! photosyn active energy by canopy (w/m2)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  PSNXY     ! total photosynthesis (umol co2/m2/s) [+]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  SAVXY     ! solar rad absorbed by veg. (w/m2)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  SAGXY     ! solar rad absorbed by ground (w/m2)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  RSSUNXY   ! sunlit leaf stomatal resistance (s/m)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  RSSHAXY   ! shaded leaf stomatal resistance (s/m)\n    REAL,    DIMENSION( ims:ime,1:2,      jms:jme ), INTENT(OUT  ) ::  ALBSNDXY  ! snow albedo (direct)\n    REAL,    DIMENSION( ims:ime,1:2,      jms:jme ), INTENT(OUT  ) ::  ALBSNIXY  ! snow albedo (diffuse)\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  BGAPXY    ! between gap fraction\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  WGAPXY    ! within gap fraction\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  TGVXY     ! under canopy ground temperature[K]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  TGBXY     ! bare ground temperature [K]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  CHVXY     ! sensible heat exchange coefficient vegetated\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  CHBXY     ! sensible heat exchange coefficient bare-ground\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  SHGXY     ! veg ground sen. heat [w/m2]   [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  SHCXY     ! canopy sen. heat [w/m2]   [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  SHBXY     ! bare sensible heat [w/m2]     [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  EVGXY     ! veg ground evap. heat [w/m2]  [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  EVBXY     ! bare soil evaporation [w/m2]  [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  GHVXY     ! veg ground heat flux [w/m2]  [+ to soil]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  GHBXY     ! bare ground heat flux [w/m2] [+ to soil]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  IRGXY     ! veg ground net LW rad. [w/m2] [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  IRCXY     ! canopy net LW rad. [w/m2] [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  IRBXY     ! bare net longwave rad. [w/m2] [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  TRXY      ! transpiration [w/m2]  [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  EVCXY     ! canopy evaporation heat [w/m2]  [+ to atm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  CHLEAFXY  ! leaf exchange coefficient\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  CHUCXY    ! under canopy exchange coefficient\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  CHV2XY    ! veg 2m exchange coefficient\n    REAL,    DIMENSION( ims:ime,          jms:jme ), INTENT(OUT  ) ::  CHB2XY    ! bare 2m exchange coefficient\n    INTEGER,  INTENT(IN   )   ::     ids,ide, jds,jde, kds,kde,  &  ! d -> domain\n         &                           ims,ime, jms,jme, kms,kme,  &  ! m -> memory\n         &                           its,ite, jts,jte, kts,kte      ! t -> tile\n\n#ifdef WRF_HYDRO\n    REAL,    DIMENSION( ims:ime,          jms:jme ), OPTIONAL, INTENT(INOUT) ::  ACCPRCP     ! accumulated precip [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), OPTIONAL, INTENT(INOUT) ::  ACCECAN     ! accumulated canopy evap [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), OPTIONAL, INTENT(INOUT) ::  ACCETRAN    ! accumulated transpiration [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), OPTIONAL, INTENT(INOUT) ::  ACCEDIR     ! accumulated direct soil evap [mm]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), OPTIONAL, INTENT(INOUT) ::  SOILSAT_TOP ! soil saturation in the top layer [fraction]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), OPTIONAL, INTENT(INOUT) ::  SOILSAT     ! soil saturation column integrated [fraction]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), OPTIONAL, INTENT(INOUT) ::  SOILICE     ! fraction of soil moisture that is ice [fraction]\n    REAL,    DIMENSION( ims:ime,          jms:jme ), OPTIONAL, INTENT(INOUT) ::  SNOWT_AVG   ! average snowpack temperature (by layer mass) [K]\n#endif\n\n! 1D equivalent of 2D/3D fields\n\n! IN only\n\n    REAL                                :: COSZ         ! cosine zenith angle\n    REAL                                :: LAT          ! latitude [rad]\n    REAL                                :: Z_ML         ! model height [m]\n    INTEGER                             :: VEGTYP       ! vegetation type\n    INTEGER                             :: SOILTYP      ! soil type\n    INTEGER                             :: CROPTYPE     ! crop type\n    REAL                                :: FVEG         ! vegetation fraction [-]\n    REAL                                :: FVGMAX       ! annual max vegetation fraction []\n    REAL                                :: TBOT         ! deep soil temperature [K]\n    REAL                                :: T_ML         ! temperature valid at mid-levels [K]\n    REAL                                :: Q_ML         ! water vapor mixing ratio [kg/kg_dry]\n    REAL                                :: U_ML         ! U wind component [m/s]\n    REAL                                :: V_ML         ! V wind component [m/s]\n    REAL                                :: SWDN         ! solar down at surface [W m-2]\n    REAL                                :: LWDN         ! longwave down at surface [W m-2]\n    REAL                                :: P_ML         ! pressure, valid at interface [Pa]\n    REAL                                :: PSFC         ! surface pressure [Pa]\n    REAL                                :: PRCP         ! total precipitation entering  [mm]         ! MB/AN : v3.7\n    REAL                                :: PRCPCONV     ! convective precipitation entering  [mm]    ! MB/AN : v3.7\n    REAL                                :: PRCPNONC     ! non-convective precipitation entering [mm] ! MB/AN : v3.7\n    REAL                                :: PRCPSHCV     ! shallow convective precip entering  [mm]   ! MB/AN : v3.7\n    REAL                                :: PRCPSNOW     ! snow entering land model [mm]              ! MB/AN : v3.7\n    REAL                                :: PRCPGRPL     ! graupel entering land model [mm]           ! MB/AN : v3.7\n    REAL                                :: PRCPHAIL     ! hail entering land model [mm]              ! MB/AN : v3.7\n    REAL                                :: PRCPOTHR     ! other precip, e.g. fog [mm]                ! MB/AN : v3.7\n\n! INOUT (with generic LSM equivalent)\n\n    REAL                                :: FSH          ! total sensible heat (w/m2) [+ to atm]\n    REAL                                :: SSOIL        ! soil heat heat (w/m2)\n    REAL                                :: SALB         ! surface albedo (-)\n    REAL                                :: FSNO         ! snow cover fraction (-)\n    REAL,   DIMENSION( 1:NSOIL)         :: SMCEQ        ! eq vol. soil moisture (m3/m3)\n    REAL,   DIMENSION( 1:NSOIL)         :: SMC          ! vol. soil moisture (m3/m3)\n    REAL,   DIMENSION( 1:NSOIL)         :: SMH2O        ! vol. soil liquid water (m3/m3)\n    REAL,   DIMENSION(-2:NSOIL)         :: STC          ! snow/soil tmperatures\n    REAL                                :: SWE          ! snow water equivalent (mm)\n    REAL                                :: SNDPTH       ! snow depth (m)\n    REAL                                :: EMISSI       ! net surface emissivity\n    REAL                                :: QSFC1D       ! bulk surface specific humidity\n\n! INOUT (with no Noah LSM equivalent)\n\n    INTEGER                             :: ISNOW        ! actual no. of snow layers\n    REAL                                :: TV           ! vegetation canopy temperature\n    REAL                                :: TG           ! ground surface temperature\n    REAL                                :: CANICE       ! canopy-intercepted ice (mm)\n    REAL                                :: CANLIQ       ! canopy-intercepted liquid water (mm)\n    REAL                                :: EAH          ! canopy air vapor pressure (pa)\n    REAL                                :: TAH          ! canopy air temperature (k)\n    REAL                                :: CM           ! momentum drag coefficient\n    REAL                                :: CH           ! sensible heat exchange coefficient\n    REAL                                :: FWET         ! wetted or snowed fraction of the canopy (-)\n    REAL                                :: SNEQVO       ! snow mass at last time step(mm h2o)\n    REAL                                :: ALBOLD       ! snow albedo at last time step (-)\n    REAL                                :: QSNOW        ! snowfall on the ground [mm/s]\n    REAL                                :: QRAIN        ! rainfall on the ground [mm/s]\n    REAL                                :: WSLAKE       ! lake water storage [mm]\n    REAL                                :: ZWT          ! water table depth [m]\n    REAL                                :: WA           ! water in the \"aquifer\" [mm]\n    REAL                                :: WT           ! groundwater storage [mm]\n    REAL                                :: SMCWTD       ! soil moisture content in the layer to the water table when deep\n    REAL                                :: DEEPRECH     ! recharge to the water table when deep\n    REAL                                :: RECH         ! recharge to the water table (diagnostic)\n    REAL, DIMENSION(-2:NSOIL)           :: ZSNSO        ! snow layer depth [m]\n    REAL, DIMENSION(-2:              0) :: SNICE        ! snow layer ice [mm]\n    REAL, DIMENSION(-2:              0) :: SNLIQ        ! snow layer liquid water [mm]\n    REAL                                :: LFMASS       ! leaf mass [g/m2]\n    REAL                                :: RTMASS       ! mass of fine roots [g/m2]\n    REAL                                :: STMASS       ! stem mass [g/m2]\n    REAL                                :: WOOD         ! mass of wood (incl. woody roots) [g/m2]\n    REAL                                :: GRAIN        ! mass of grain XING [g/m2]\n    REAL                                :: GDD          ! mass of grain XING[g/m2]\n    INTEGER                             :: PGS          !stem respiration [g/m2/s]\n    REAL                                :: STBLCP       ! stable carbon in deep soil [g/m2]\n    REAL                                :: FASTCP       ! short-lived carbon, shallow soil [g/m2]\n    REAL                                :: PLAI         ! leaf area index\n    REAL                                :: PSAI         ! stem area index\n    REAL                                :: TAUSS        ! non-dimensional snow age\n\n! OUT (with no Noah LSM equivalent)\n\n    REAL                                :: Z0WRF        ! combined z0 sent to coupled model\n    REAL                                :: T2MV         ! 2m temperature of vegetation part\n    REAL                                :: T2MB         ! 2m temperature of bare ground part\n    REAL                                :: Q2MV         ! 2m mixing ratio of vegetation part\n    REAL                                :: Q2MB         ! 2m mixing ratio of bare ground part\n    REAL                                :: TRAD         ! surface radiative temperature (k)\n    REAL                                :: NEE          ! net ecosys exchange (g/m2/s CO2)\n    REAL                                :: GPP          ! gross primary assimilation [g/m2/s C]\n    REAL                                :: NPP          ! net primary productivity [g/m2/s C]\n    REAL                                :: FVEGMP       ! greenness vegetation fraction [-]\n    REAL                                :: RUNSF        ! surface runoff [mm/s]\n    REAL                                :: RUNSB        ! subsurface runoff [mm/s]\n    REAL                                :: ECAN         ! evaporation of intercepted water (mm/s)\n    REAL                                :: ETRAN        ! transpiration rate (mm/s)\n    REAL                                :: ESOIL        ! soil surface evaporation rate (mm/s]\n    REAL                                :: FSA          ! total absorbed solar radiation (w/m2)\n    REAL                                :: FIRA         ! total net longwave rad (w/m2) [+ to atm]\n    REAL                                :: APAR         ! photosyn active energy by canopy (w/m2)\n    REAL                                :: PSN          ! total photosynthesis (umol co2/m2/s) [+]\n    REAL                                :: SAV          ! solar rad absorbed by veg. (w/m2)\n    REAL                                :: SAG          ! solar rad absorbed by ground (w/m2)\n    REAL                                :: RSSUN        ! sunlit leaf stomatal resistance (s/m)\n    REAL                                :: RSSHA        ! shaded leaf stomatal resistance (s/m)\n    REAL, DIMENSION(1:2)                :: ALBSND       ! snow albedo (direct)\n    REAL, DIMENSION(1:2)                :: ALBSNI       ! snow albedo (diffuse)\n    REAL                                :: RB           ! leaf boundary layer resistance (s/m)\n    REAL                                :: LAISUN       ! sunlit leaf area index (m2/m2)\n    REAL                                :: LAISHA       ! shaded leaf area index (m2/m2)\n    REAL                                :: BGAP         ! between gap fraction\n    REAL                                :: WGAP         ! within gap fraction\n    REAL                                :: TGV          ! under canopy ground temperature[K]\n    REAL                                :: TGB          ! bare ground temperature [K]\n    REAL                                :: CHV          ! sensible heat exchange coefficient vegetated\n    REAL                                :: CHB          ! sensible heat exchange coefficient bare-ground\n    REAL                                :: IRC          ! canopy net LW rad. [w/m2] [+ to atm]\n    REAL                                :: IRG          ! veg ground net LW rad. [w/m2] [+ to atm]\n    REAL                                :: SHC          ! canopy sen. heat [w/m2]   [+ to atm]\n    REAL                                :: SHG          ! veg ground sen. heat [w/m2]   [+ to atm]\n    REAL                                :: EVG          ! veg ground evap. heat [w/m2]  [+ to atm]\n    REAL                                :: GHV          ! veg ground heat flux [w/m2]  [+ to soil]\n    REAL                                :: IRB          ! bare net longwave rad. [w/m2] [+ to atm]\n    REAL                                :: SHB          ! bare sensible heat [w/m2]     [+ to atm]\n    REAL                                :: EVB          ! bare evaporation heat [w/m2]  [+ to atm]\n    REAL                                :: GHB          ! bare ground heat flux [w/m2] [+ to soil]\n    REAL                                :: TR           ! transpiration [w/m2]  [+ to atm]\n    REAL                                :: EVC          ! canopy evaporation heat [w/m2]  [+ to atm]\n    REAL                                :: CHLEAF       ! leaf exchange coefficient\n    REAL                                :: CHUC         ! under canopy exchange coefficient\n    REAL                                :: CHV2         ! veg 2m exchange coefficient\n    REAL                                :: CHB2         ! bare 2m exchange coefficient\n    REAL                                :: PAHV         ! precipitation advected heat - vegetation net (W/m2)\n    REAL                                :: PAHG         ! precipitation advected heat - under canopy net (W/m2)\n    REAL                                :: PAHB         ! precipitation advected heat - bare ground net (W/m2)\n    REAL                                :: PAH          ! precipitation advected heat - total (W/m2)\n\n! Intermediate terms\n\n    REAL                                :: FPICE        ! snow fraction of precip\n    REAL                                :: FCEV         ! canopy evaporation heat (w/m2) [+ to atm]\n    REAL                                :: FGEV         ! ground evaporation heat (w/m2) [+ to atm]\n    REAL                                :: FCTR         ! transpiration heat flux (w/m2) [+ to atm]\n    REAL                                :: QSNBOT       ! snowmelt out bottom of pack [mm/s]\n    REAL                                :: PONDING      ! snowmelt with no pack [mm]\n    REAL                                :: PONDING1     ! snowmelt with no pack [mm]\n    REAL                                :: PONDING2     ! snowmelt with no pack [mm]\n\n! Local terms\n\n    REAL                                :: FSR          ! total reflected solar radiation (w/m2)\n    REAL, DIMENSION(-2:0)               :: FICEOLD      ! snow layer ice fraction []\n    REAL                                :: CO2PP        ! CO2 partial pressure [Pa]\n    REAL                                :: O2PP         ! O2 partial pressure [Pa]\n    REAL, DIMENSION(1:NSOIL)            :: ZSOIL        ! depth to soil interfaces [m]\n    REAL                                :: FOLN         ! nitrogen saturation [%]\n\n    REAL                                :: QC           ! cloud specific humidity for MYJ [not used]\n    REAL                                :: PBLH         ! PBL height for MYJ [not used]\n    REAL                                :: DZ8W1D       ! model level heights for MYJ [not used]\n\n    INTEGER                             :: I\n    INTEGER                             :: J\n    INTEGER                             :: K\n    INTEGER                             :: ICE\n    INTEGER                             :: SLOPETYP\n    LOGICAL                             :: IPRINT\n\n    INTEGER                             :: SOILCOLOR    ! soil color index\n    INTEGER                             :: IST          ! surface type 1-soil; 2-lake\n    INTEGER                             :: YEARLEN\n\n    INTEGER, PARAMETER                  :: NSNOW = 3    ! number of snow layers fixed to 3\n    REAL, PARAMETER                     :: undefined_value = -1.E36\n\n    type(noahmp_parameters) :: parameters\n\n\n    INTEGER,                INTENT(IN)                 :: act_level\n    REAL, DIMENSION(:,:),   INTENT(INOUT), allocatable :: PSNOWALBXY    ! Prognostic surface snow albedo\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable :: PSNOWHEATXY\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable :: PSNOWRHOXY\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable :: PSNOWSWEXY\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable :: PSNOWGRAN1XY   ! Snow layer(s) grain parameter 1\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable :: PSNOWGRAN2XY   ! Snow layer(s) grain parameter 2\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable :: PSNOWHISTXY       ! Snow layer(s) grain historical parameter\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable :: PSNOWAGEXY ! Snow grain age\n\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable   :: PSNOWLIQXY\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable   :: PSNOWTEMPXY\n    REAL, DIMENSION(:,:,:), INTENT(INOUT), allocatable   :: PSNOWDZXY\n\n    REAL, DIMENSION(:,:),   INTENT(INOUT), allocatable  :: PSNOWTHRUFALXY ! rate that liquid water leaves snow pack [kg/(m2 s)]   (should only be out)\n    REAL, DIMENSION(:,:),   INTENT(INOUT), allocatable  :: PSNOWHEIGHTXY   ! integrated crocus snowheight PSNOWDZXY\n    REAL, DIMENSION(:,:),   INTENT(INOUT), allocatable  :: PSNOWTOTSWEXY   ! crocus snowheight PSNOWSWE\n    REAL, DIMENSION(:,:),   INTENT(INOUT), allocatable  ::   FLOW_ICE\n    REAL, DIMENSION(:,:),   INTENT(INOUT), allocatable  ::   FLOW_SNOW\n    INTEGER,DIMENSION(:,:), INTENT(INOUT), allocatable  :: GLACINFO\n    REAL, DIMENSION(:,:),   INTENT(INOUT), allocatable  :: GLACT\n    INTEGER,                INTENT(IN)                  :: crocus_opt\n    REAL, DIMENSION(:,:),   INTENT(INOUT), allocatable  :: VIS_ICEALB\n\n    INTEGER                                             :: GLACINFOH,GLACR ! glacier info\n    CHARACTER(LEN=11)                                   :: HSNOWRES\n    CHARACTER(LEN=3)                                    :: HIMPLICIT_WIND\n    LOGICAL                                             :: OGLACIER\n\n    REAL, DIMENSION(1)                :: ZP_RRSNOW ,ZP_PSN3L, ZP_QA\n    REAL, DIMENSION(1)                :: ZP_PEW_A_COEF, ZP_PEW_B_COEF\n    REAL, DIMENSION(1)                :: ZP_PET_A_COEF, ZP_PEQ_A_COEF\n    REAL, DIMENSION(1)                :: ZP_PET_B_COEF, ZP_PEQ_B_COEF\n    REAL, PARAMETER                   :: ZTFRZ = 273.16 !freezing/melting point (k)\n    REAL                              :: ZFPICE ! snow fraction of precip\n    REAL, DIMENSION(1)                :: FOO1, FOO2\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWSWE\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWDZ\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWRHO\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWHEAT\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWTEMP\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWLIQ\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWGRAN1\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWGRAN2\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWHIST\n    REAL, DIMENSION(:,:), allocatable :: ZP_SNOWAGE\n\n    REAL, DIMENSION(1) :: ZP_VMOD,ZP_RHOA, ZP_UREF\n    REAL, DIMENSION(1) :: ZP_EXNS, ZP_EXNA, ZP_DIRCOSZW\n    REAL, DIMENSION(1) :: ZP_Z0NAT\n    REAL, DIMENSION(1) :: ZP_Z0HNAT, ZP_ALB, ZP_SOILCOND\n    REAL, DIMENSION(1) :: ZP_D_G,ZP_SNOWALB, ZP_VIS_ICEALB\n    REAL, DIMENSION(1) :: ZFLOW_ICE, ZFLOW_SNOW\n    REAL, DIMENSION(1) :: ZP_THRUFAL, ZP_GRNDFLUX, ZP_EVAPCOR\n    REAL, DIMENSION(1) :: ZP_RNSNOW, ZP_GFLUXSNOW, ZP_HPSNOW\n    REAL, DIMENSION(1) :: ZP_LEL3L, ZP_SNDRIFT, ZP_RI\n    REAL, DIMENSION(1) :: ZP_SNOWHMASS\n    REAL, DIMENSION(1) :: ZP_USTARSNOW\n    REAL, DIMENSION(1) :: ZP_VEGTYPE, ZP_ZENITH\n    REAL, DIMENSION(1) :: ZP_PS        ! PSFC\n    REAL, DIMENSION(1) :: ZP_SRSNOW    ! QSNOW\n    REAL, DIMENSION(1) :: ZP_TA        ! T_ML\n    REAL, DIMENSION(1) :: ZP_TG        ! TG?\n    REAL, DIMENSION(1) :: ZP_SW_RAD    ! SWDN\n    REAL, DIMENSION(1) :: ZP_LW_RAD    ! LWDN\n    REAL, DIMENSION(1) :: ZP_ZREF      ! Z_ML\n    REAL, DIMENSION(1) :: ZP_HSNOW     ! FSH\n    REAL, DIMENSION(1) :: ZP_LES3L     ! FGEV\n    REAL, DIMENSION(1) :: ZP_EVAP      ! ESOIL\n    REAL, DIMENSION(1) :: ZP_EMISNOW   ! EMISSI\n    REAL, DIMENSION(1) :: ZP_CDSNOW    ! CM\n    REAL, DIMENSION(1) :: ZP_CHSNOW    ! CH\n    REAL, DIMENSION(1) :: ZP_QS        ! QSFC1D\n    REAL, DIMENSION(1) :: ZP_Z0EFF     ! effective roughness\n\n    !     Added some temporary fields for using noahmp-glacier to calculate 2m variables\n    REAL, DIMENSION(-2:NSOIL) :: ZSNSOT ! snow layer depth [m]\n    REAL, DIMENSION(-2:0)     :: SNICET ! snow layer ice [mm]\n    REAL, DIMENSION(-2:0)     :: SNLIQT ! snow layer liquid water [mm]\n\n    REAL, DIMENSION(-2:NSOIL) :: ZSNSOTH ! snow layer depth [m]\n    REAL, DIMENSION(-2:0)     :: SNICEH  ! snow layer ice [mm]\n    REAL, DIMENSION(-2:NSOIL) :: ZSNSOH  ! snow layer depth [m]\n\n    !     Added  fluxes:\n    REAL,DIMENSION(1) :: ZP_FSA_CROCUS\n    REAL,DIMENSION(1) :: ZP_FSR_CROCUS\n    REAL,DIMENSION(1) :: ZP_FIRA_CROCUS\n\n    LOGICAL      :: OSNOWDRIFT, OSNOWDRIFT_SUBLIM ! activate snowdrift, sublimation during drift\n    LOGICAL      :: OSNOW_ABS_ZENITH ! activate parametrization of solar absorption for polar regions\n    REAL         :: SWEH\n    REAL         :: SNDPTHH\n    REAL         :: SNEQVOH\n    CHARACTER(3) :: HSNOWMETAMO, HSNOWRAD\n\n    REAL,   DIMENSION( 1:NSOIL)    :: liq_frac\n\n    ! crocus, assign mock local values, and initialize. These values should be in namelist.\n    if (crocus_opt /= 0) then\n       allocate(ZP_SNOWSWE  (1,1:act_level))\n       allocate(ZP_SNOWDZ   (1,1:act_level))\n       allocate(ZP_SNOWRHO  (1,1:act_level))\n       allocate(ZP_SNOWHEAT (1,1:act_level))\n       allocate(ZP_SNOWTEMP (1,1:act_level))\n       allocate(ZP_SNOWLIQ  (1,1:act_level))\n       allocate(ZP_SNOWGRAN1(1,1:act_level))\n       allocate(ZP_SNOWGRAN2(1,1:act_level))\n       allocate(ZP_SNOWHIST (1,1:act_level))\n       allocate(ZP_SNOWAGE  (1,1:act_level))\n\n       HSNOWRES = 'ISBA-SNOW3L'  !   'DEF'\n       OGLACIER = .false.\n       !      OGLACIER = .true.\n       HIMPLICIT_WIND = 'NEW'\n       !      HIMPLICIT_WIND = 'OLD'\n\n       ZP_VEGTYPE = 1.0\n       OSNOWDRIFT = .true.\n       OSNOWDRIFT_SUBLIM = .true.\n       OSNOW_ABS_ZENITH = .false.\n       HSNOWMETAMO = 'B92'\n       !      HSNOWMETAMO = 'C13'\n       HSNOWRAD         = 'B92'\n       !     HSNOWRAD         = 'TAR2'\n    else\n       allocate(ZP_SNOWDZ   (1,1)) ! This is allocated to avoid SEGFAULT when crocus_opt=0 and\n       ZP_SNOWDZ = 0.0             ! optimization is off\n    end if ! crocus_opt /= 0\n\n! ----------------------------------------------------------------------\n\n    CALL NOAHMP_OPTIONS(IDVEG  ,IOPT_CRS  ,IOPT_BTR  ,IOPT_RUN  ,IOPT_SFC  ,IOPT_FRZ , &\n                     IOPT_INF  ,IOPT_RAD  ,IOPT_ALB  ,IOPT_SNF  ,IOPT_TBOT, IOPT_STC , &\n\t\t     IOPT_RSF  ,IOPT_SOIL ,IOPT_PEDO ,IOPT_CROP, IOPT_IMPERV )\n\n    IPRINT    =  .false.                     ! debug printout\n\n    YEARLEN = 365                            ! find length of year for phenology (also S Hemisphere)\n    if (mod(YR,4) == 0) then\n       YEARLEN = 366\n       if (mod(YR,100) == 0) then\n          YEARLEN = 365\n          if (mod(YR,400) == 0) then\n             YEARLEN = 366\n          endif\n       endif\n    endif\n\n    ZSOIL(1) = -DZS(1)                    ! depth to soil interfaces (<0) [m]\n    DO K = 2, NSOIL\n       ZSOIL(K) = -DZS(K) + ZSOIL(K-1)\n    END DO\n\n    JLOOP : DO J=jts,jte\n       IF(ITIMESTEP == 1)THEN\n          DO I=its,ite\n             IF((XLAND(I,J)-1.5) >= 0.) THEN    ! Open water case\n                IF(XICE(I,J) == 1. .AND. IPRINT) PRINT *,' sea-ice at water point, I=',I,'J=',J\n                SMSTAV(I,J) = 1.0\n                SMSTOT(I,J) = 1.0\n                DO K = 1, NSOIL\n                   SMOIS(I,K,J) = 1.0\n                    TSLB(I,K,J) = 273.16\n                ENDDO\n             ELSE\n                IF(XICE(I,J) == 1.) THEN        ! Sea-ice case\n                   SMSTAV(I,J) = 1.0\n                   SMSTOT(I,J) = 1.0\n                   DO K = 1, NSOIL\n                      SMOIS(I,K,J) = 1.0\n                   ENDDO\n                ENDIF\n             ENDIF\n          ENDDO\n       ENDIF                                                               ! end of initialization over ocean\n\n\n!-----------------------------------------------------------------------\n   ILOOP : DO I = its, ite\n      ! Reset GLACR and ICE at the start of every iteration\n      GLACR = 0\n      ICE   = 0\n\n    IF (XICE(I,J) >= XICE_THRES) THEN\n       ICE = 1                            ! Sea-ice point\n\n       SH2O  (i,1:NSOIL,j) = 1.0\n       XLAIXY(i,j)         = 0.01\n\n       CYCLE ILOOP ! Skip any processing at sea-ice points\n\n    ELSE\n\n       IF((XLAND(I,J)-1.5) >= 0.) CYCLE ILOOP   ! Open water case\n\n!     2D to 1D\n\n! IN only\n\n       COSZ   = COSZIN  (I,J)                         ! cos zenith angle []\n       LAT    = XLATIN  (I,J)                         ! latitude [rad]\n       Z_ML   = 0.5*DZ8W(I,1,J)                       ! DZ8W: thickness of full levels; ZLVL forcing height [m]\n       VEGTYP = IVGTYP(I,J)                           ! vegetation type\n       SOILTYP= ISLTYP(I,J)                           ! soil type\n       FVEG   = VEGFRA(I,J)/100.                      ! vegetation fraction [0-1]\n       FVGMAX = VEGMAX (I,J)/100.                     ! Vegetation fraction annual max [0-1]\n       TBOT = TMN(I,J)                                ! Fixed deep soil temperature for land\n       T_ML   = T3D(I,1,J)                            ! temperature defined at intermediate level [K]\n       Q_ML   = QV3D(I,1,J)/(1.0+QV3D(I,1,J))         ! convert from mixing ratio to specific humidity [kg/kg]\n       U_ML   = U_PHY(I,1,J)                          ! u-wind at interface [m/s]\n       V_ML   = V_PHY(I,1,J)                          ! v-wind at interface [m/s]\n       SWDN   = SWDOWN(I,J)                           ! shortwave down from SW scheme [W/m2]\n       LWDN   = GLW(I,J)                              ! total longwave down from LW scheme [W/m2]\n       P_ML   =(P8W3D(I,KTS+1,J)+P8W3D(I,KTS,J))*0.5  ! surface pressure defined at intermediate level [Pa]\n\t                                              !    consistent with temperature, mixing ratio\n       PSFC   = P8W3D(I,1,J)                          ! surface pressure defined a full levels [Pa]\n       PRCP   = PRECIP_IN (I,J) / DT                  ! timestep total precip rate (glacier) [mm/s]! MB: v3.7\n\n       CROPTYPE = 0\n       if (crocus_opt /= 0) then\n          ZFLOW_ICE = 0\n          ZFLOW_SNOW = 0\n       end if\n\n       IF (PRESENT(MP_RAINC) .AND. PRESENT(MP_RAINNC) .AND. PRESENT(MP_SHCV) .AND. &\n           PRESENT(MP_SNOW)  .AND. PRESENT(MP_GRAUP)  .AND. PRESENT(MP_HAIL)   ) THEN\n\n         PRCPCONV  = MP_RAINC (I,J)/DT                ! timestep convective precip rate [mm/s]     ! MB: v3.7\n         PRCPNONC  = MP_RAINNC(I,J)/DT                ! timestep non-convective precip rate [mm/s] ! MB: v3.7\n         PRCPSHCV  = MP_SHCV(I,J)  /DT                ! timestep shallow conv precip rate [mm/s]   ! MB: v3.7\n         PRCPSNOW  = MP_SNOW(I,J)  /DT                ! timestep snow precip rate [mm/s]           ! MB: v3.7\n         PRCPGRPL  = MP_GRAUP(I,J) /DT                ! timestep graupel precip rate [mm/s]        ! MB: v3.7\n         PRCPHAIL  = MP_HAIL(I,J)  /DT                ! timestep hail precip rate [mm/s]           ! MB: v3.7\n\n         PRCPOTHR  = PRCP - PRCPCONV - PRCPNONC - PRCPSHCV ! take care of other (fog) contained in rainbl\n\t PRCPOTHR  = MAX(0.0,PRCPOTHR)\n\t PRCPNONC  = PRCPNONC + PRCPOTHR\n         PRCPSNOW  = PRCPSNOW + SR(I,J)  * PRCPOTHR\n       ELSE\n         PRCPCONV  = 0.\n         PRCPNONC  = PRCP\n         PRCPSHCV  = 0.\n         PRCPSNOW  = SR(I,J) * PRCP\n         PRCPGRPL  = 0.\n         PRCPHAIL  = 0.\n       ENDIF\n\n! IN/OUT fields\n\n       ISNOW                 = ISNOWXY (I,J)                ! snow layers []\n       SMC  (      1:NSOIL)  = SMOIS   (I,      1:NSOIL,J)  ! soil total moisture [m3/m3]\n       SMH2O(      1:NSOIL)  = SH2O    (I,      1:NSOIL,J)  ! soil liquid moisture [m3/m3]\n       STC  (-NSNOW+1:    0) = TSNOXY  (I,-NSNOW+1:    0,J) ! snow temperatures [K]\n       STC  (      1:NSOIL)  = TSLB    (I,      1:NSOIL,J)  ! soil temperatures [K]\n       SWE                   = SNOW    (I,J)                ! snow water equivalent [mm]\n       SNDPTH                = SNOWH   (I,J)                ! snow depth [m]\n       QSFC1D                = QSFC    (I,J)\n\n! INOUT (with no Noah LSM equivalent)\n\n       TV                    = TVXY    (I,J)                ! leaf temperature [K]\n       TG                    = TGXY    (I,J)                ! ground temperature [K]\n       CANLIQ                = CANLIQXY(I,J)                ! canopy liquid water [mm]\n       CANICE                = CANICEXY(I,J)                ! canopy frozen water [mm]\n       EAH                   = EAHXY   (I,J)                ! canopy vapor pressure [Pa]\n       TAH                   = TAHXY   (I,J)                ! canopy temperature [K]\n       CM                    = CMXY    (I,J)                ! avg. momentum exchange (MP only) [m/s]\n       CH                    = CHXY    (I,J)                ! avg. heat exchange (MP only) [m/s]\n       FWET                  = FWETXY  (I,J)                ! canopy fraction wet or snow\n       SNEQVO                = SNEQVOXY(I,J)                ! SWE previous timestep\n       ALBOLD                = ALBOLDXY(I,J)                ! albedo previous timestep, for snow aging\n       QSNOW                 = QSNOWXY (I,J)                ! snow falling on ground\n       QRAIN                 = QRAINXY (I,J)                ! rain falling on ground\n       WSLAKE                = WSLAKEXY(I,J)                ! lake water storage (can be neg.) (mm)\n       ZWT                   = ZWTXY   (I,J)                ! depth to water table [m]\n       WA                    = WAXY    (I,J)                ! water storage in aquifer [mm]\n       WT                    = WTXY    (I,J)                ! water in aquifer&saturated soil [mm]\n       ZSNSO(-NSNOW+1:NSOIL) = ZSNSOXY (I,-NSNOW+1:NSOIL,J) ! depth to layer interface\n       SNICE(-NSNOW+1:    0) = SNICEXY (I,-NSNOW+1:    0,J) ! snow layer ice content\n       SNLIQ(-NSNOW+1:    0) = SNLIQXY (I,-NSNOW+1:    0,J) ! snow layer water content\n       LFMASS                = LFMASSXY(I,J)                ! leaf mass\n       RTMASS                = RTMASSXY(I,J)                ! root mass\n       STMASS                = STMASSXY(I,J)                ! stem mass\n       WOOD                  = WOODXY  (I,J)                ! mass of wood (incl. woody roots) [g/m2]\n       STBLCP                = STBLCPXY(I,J)                ! stable carbon pool\n       FASTCP                = FASTCPXY(I,J)                ! fast carbon pool\n       PLAI                  = XLAIXY  (I,J)                ! leaf area index [-] (no snow effects)\n       PSAI                  = XSAIXY  (I,J)                ! stem area index [-] (no snow effects)\n       TAUSS                 = TAUSSXY (I,J)                ! non-dimensional snow age\n       SMCEQ(       1:NSOIL) = SMOISEQ (I,       1:NSOIL,J)\n       SMCWTD                = SMCWTDXY(I,J)\n       RECH                  = 0.\n       DEEPRECH              = 0.\n\n       SLOPETYP     = 1                               ! set underground runoff slope term\n       IST          = 1                               ! MP surface type: 1 = land; 2 = lake\n       SOILCOLOR    = 4                               ! soil color: assuming a middle color category ?????????\n\n       IF(SOILTYP == 14 .AND. XICE(I,J) == 0.) THEN\n          IF(IPRINT) PRINT *, ' SOIL TYPE FOUND TO BE WATER AT A LAND-POINT'\n          IF(IPRINT) PRINT *, i,j,'RESET SOIL in surfce.F'\n          SOILTYP = 7\n       ENDIF\n\n#ifdef SPATIAL_SOIL\n       parameters%bexp   = BEXP_3D  (I,1:NSOIL,J) ! C-H B exponent\n       parameters%smcdry = SMCDRY_3D(I,1:NSOIL,J) ! Soil Moisture Limit: Dry\n       parameters%smcwlt = SMCWLT_3D(I,1:NSOIL,J) ! Soil Moisture Limit: Wilt\n       parameters%smcref = SMCREF_3D(I,1:NSOIL,J) ! Soil Moisture Limit: Reference\n       parameters%smcmax = SMCMAX_3D(I,1:NSOIL,J) ! Soil Moisture Limit: Max\n       parameters%dksat  = DKSAT_3D (I,1:NSOIL,J) ! Saturated Soil Conductivity\n       parameters%dwsat  = DWSAT_3D (I,1:NSOIL,J) ! Saturated Soil Diffusivity\n       parameters%psisat = PSISAT_3D(I,1:NSOIL,J) ! Saturated Matric Potential\n       parameters%quartz = QUARTZ_3D(I,1:NSOIL,J) ! Soil quartz content\n       parameters%refdk  = REFDK_2D (I,J)         ! Reference Soil Conductivity\n       parameters%refkdt = REFKDT_2D(I,J)         ! Soil Infiltration Parameter\n       parameters%slope  = SLOPE_2D (I,J)         ! Soil Drainage Parameter\n       parameters%cwpvt  = CWPVT_2D(I,J)          ! Canopy wind parameter\n       parameters%vcmx25 = VCMX25_2D(I,J)         ! VCmax at 25C\n       parameters%mp     = MP_2D(I,J)             ! Slope of Ball-Berry rs-P relationship\n       parameters%hvt    = HVT_2D(I,J)            ! Canopy Height\n       parameters%mfsno  = MFSNO_2D(I,J)          ! Snow cover m parameter\n       parameters%rsurf_exp = RSURFEXP_2D(I,J)    ! exponent in the shape parameter for soil resistance option 1\n       parameters%axaj   = AXAJ_2D(I,J)           ! Xinanjiang: Tension water distribution inflection parameter [-]\n       parameters%bxaj   = BXAJ_2D(I,J)           ! Xinanjiang: Tension water distribution shape parameter [-]\n       parameters%xxaj   = XXAJ_2D(I,J)           ! Xinanjiang: Free water distribution shape parameter [-]\n       parameters%imperv = IMPERV_2D(I,J)         ! impervious fraction\n       parameters%ssi    = SSI_2D(I,J)            ! liquid water holding capacity for snowpack (m3/m3)\n       parameters%snow_ret_fac = SNOWRETFAC_2D(I,J)   ! snowpack water release timescale factor (1/s)\n       parameters%tau0   = TAU0_2D(I,J)           ! tau0 from Yang97 eqn. 10a\n       parameters%rsurf_snow = RSURFSNOW_2D(I,J)  ! surface resistence for snow [s/m]\n       parameters%scamax = SCAMAX_2D(I,J)         ! maximum fractional snow covered area (0.0-1.0)\n#endif\n       CALL TRANSFER_MP_PARAMETERS(VEGTYP,SOILTYP,SLOPETYP,SOILCOLOR,CROPTYPE,parameters,iopt_imperv)\n\n       GRAIN = 0.0                ! mass of grain [g/m2]\n       GDD   = 0.0                ! growing degree days\n       PGS   = 0                  ! crop growth stage\n\n       if (HVT_TABLE(VEGTYP) > 0.0) then\n         parameters%hvb = parameters%hvt * HVB_TABLE(VEGTYP) / HVT_TABLE(VEGTYP)\n       else\n         parameters%hvb = 0.0\n       endif\n\n       !ADCHANGE: Add some sanity checks in case calibration knocks the order of these out of sequence.\n       !The min diffs were pulled from the existing SOILPARM.TBL defaults.\n       !Currently water is 0, so enforcing 0 as the absolute min.\n       parameters%smcmax = min(parameters%smcmax, 1.0)\n       parameters%smcref = max(min(parameters%smcref, parameters%smcmax - 0.01), 0.0)\n       parameters%smcwlt = max(min(parameters%smcwlt, parameters%smcref - 0.01), 0.0)\n       parameters%smcdry = max(min(parameters%smcdry, parameters%smcref - 0.01), 0.0)\n\n! Initialized local\n\n       FICEOLD = 0.0\n       FICEOLD(ISNOW+1:0) = SNICEXY(I,ISNOW+1:0,J) &  ! snow ice fraction\n           /(SNICEXY(I,ISNOW+1:0,J)+SNLIQXY(I,ISNOW+1:0,J))\n       CO2PP  = CO2_TABLE * P_ML                      ! partial pressure co2 [Pa]\n       O2PP   = O2_TABLE  * P_ML                      ! partial pressure  o2 [Pa]\n       FOLN   = 1.0                                   ! for now, set to nitrogen saturation\n       QC     = undefined_value                       ! test dummy value\n       PBLH   = undefined_value                       ! test dummy value ! PBL height\n       DZ8W1D = DZ8W (I,1,J)                          ! thickness of atmospheric layers\n\n! Initialize crocus, !  Do this before NOAHMP, so that outputs (such as TG) from Noah-mp glacier affect Crocus this step\n       if (crocus_opt /= 0) then\n          GLACINFOH = GLACINFO(I,J)   ! vegetation type\n\n          ZP_SNOWSWE(1,1:act_level) = PSNOWSWEXY(I,1:act_level,J)\n          ZP_SNOWRHO(1,1:act_level) = PSNOWRHOXY(I,1:act_level,J)\n          ZP_SNOWHEAT(1,1:act_level) = PSNOWHEATXY(I,1:act_level,J)\n          ZP_SNOWGRAN1(1,1:act_level) = PSNOWGRAN1XY(I,1:act_level,J)\n          ZP_SNOWGRAN2(1,1:act_level) = PSNOWGRAN2XY(I,1:act_level,J)\n          ZP_SNOWHIST(1,1:act_level) = PSNOWHISTXY(I,1:act_level,J)\n          ZP_SNOWAGE(1,1:act_level)= PSNOWAGEXY(I,1:act_level,J)\n          ZP_SNOWLIQ(1,1:act_level) = PSNOWLIQXY(I,1:act_level,J)\n          ZP_SNOWTEMP(1,1:act_level) = PSNOWTEMPXY(I,1:act_level,J)\n          ZP_SNOWDZ(1,1:act_level) = PSNOWDZXY(I,1:act_level,J)\n          ZP_SNOWALB(1) =  PSNOWALBXY(I,J)\n          ZP_EVAP(1)    =  0 !PSNOWEVAPXY(I,J)\n          ZP_vis_icealb(1) = VIS_ICEALB(I,J)\n\n          ZP_ZENITH    = ACOS(COSZIN(I,J))\n\n          ! Currently the surfex naming convention is being used\n          ZP_PS(1)  =   PSFC\n          ZP_SRSNOW(1) = QSNOW\n          ZP_TA(1) = T_ML\n          ZP_TG(1)  =  TSLB(i,1,j)\n          IF (ZP_SNOWTEMP(1,3) .ne. 0 ) then\n             ZP_TG(1)  =  (TSLB(i,1,j)+ZP_SNOWTEMP(1,3))/2.\n          end if\n          ZP_RHOA(1) = P_ML/(T_ML*287.058)\n          ZP_SW_RAD(1)  = SWDN\n          ZP_LW_RAD(1)  = LWDN\n          ZP_ZREF(1)       = Z_ML\n          ZP_HSNOW(1)   = FSH\n          ZP_LES3L(1)      = FGEV\n          ZP_EVAP(1)       = ESOIL\n          ZP_EMISNOW(1) = EMISSI\n          ZP_CDSNOW(1)  = CM\n          ZP_CHSNOW(1)  = CH\n          ZP_QS(1)             = QSFC1D\n          ZP_QA(1)             =Q_ML\n          ZP_ALB(1)            = ALBEDO(I,J) !soil/vegetation albedo. Is SALB combined snow/soil albedo?\n          ZP_EXNA(1)             = (P_ML/1.e5)** (287.04/1004.6) !(P/XP00)**(XRD/XCPD)\n          ZP_EXNS(1)             = (PSFC/1.e5)** (287.04/1004.6) !(P/XP00)**(XRD/XCPD)\n          ZP_DIRCOSZW(1)   = 1.0    !(for now we use a flat surface)\n          ZP_UREF(1)            = Z_ML\n\n          ZP_Z0EFF(1)          =  XZ0SN\n          ZP_Z0NAT(1)         =  XZ0SN\n          ZP_Z0HNAT(1)      = XZ0HSN\n\n          !     in offline mode, A_COEF = 0, and B_COEF = variable of interest at atmospheric level  (Boone et al, 2017; The interaction between soil-biasphere-------)\n          ZP_PSN3L(1)    = 1.0\n          ZP_VMOD(1)     = 1.0      !(assume terrain is flat)\n          ZP_D_G(1)         = 0.1   ! should read from namelits (soil_thick_input)\n\n          !     Fluxes\n          ZP_FSA_CROCUS(1)  = 0\n          ZP_FSR_CROCUS(1) = 0\n          ZP_FIRA_CROCUS(1) = 0\n\n          ZP_SOILCOND(1) = 0.32333+(0.10073*(-ZSNSO(1)))\n\n          ZP_PEW_A_COEF(1)  = 0.0\n          ZP_PEW_B_COEF(1)  = sqrt(U_ML**2+V_ML**2)\n          ZP_PET_A_COEF(1)    =0.0\n          ZP_PEQ_A_COEF(1)   = 0.0\n          ZP_PET_B_COEF(1)   = T_ML*(1.e5/P_ML)** (287.04/1004.6)\n          ZP_PEQ_B_COEF(1)   = Q_ML\n\n          ZP_VMOD(1)  =      ZP_PEW_B_COEF(1)\n\n\n          ! Added from module_sf_noahmp_glacier:\n          ! partition precipitation into rain and snow (from CANWATER)\n          ! Jordan (1991)\n          IF(IOPT_SNF == 1 .OR. IOPT_SNF == 4) THEN\n             IF(T_ML > ZTFRZ+2.5)THEN\n                ZFPICE = 0.\n             ELSE\n                IF(T_ML <= ZTFRZ+0.5)THEN\n                   ZFPICE = 1.0\n                ELSE IF(T_ML <= ZTFRZ+2.)THEN\n                   ZFPICE = 1.-(-54.632 + 0.2*T_ML)\n                ELSE\n                   ZFPICE = 0.6\n                ENDIF\n             ENDIF\n          ENDIF\n\n          IF(IOPT_SNF == 2) THEN\n             IF(T_ML >= ZTFRZ+2.2) THEN\n                ZFPICE = 0.\n             ELSE\n                ZFPICE = 1.0\n             ENDIF\n          ENDIF\n\n          IF(IOPT_SNF == 3) THEN\n             IF(T_ML >= ZTFRZ) THEN\n                ZFPICE = 0.\n             ELSE\n                ZFPICE = 1.0\n             ENDIF\n          ENDIF\n\n          !     Hedstrom NR and JW Pomeroy (1998), Hydrol. Processes, 12, 1611-1625\n          !     fresh snow density\n\n          ZP_RRSNOW(1)   = PRCP* (1.-ZFPICE)\n          ZP_SRSNOW(1)   = PRCP*ZFPICE\n\n          ZP_THRUFAL(:) = 0.0\n      end if ! crocus_opt /= 0\n\n       IF(VEGTYP == 25) FVEG = 0.0                  ! Set playa, lava, sand to bare\n       IF(VEGTYP == 25) PLAI = 0.0\n       IF(VEGTYP == 26) FVEG = 0.0                  ! hard coded for USGS\n       IF(VEGTYP == 26) PLAI = 0.0\n       IF(VEGTYP == 27) FVEG = 0.0\n       IF(VEGTYP == 27) PLAI = 0.0\n\n       ! If running crocus, test if glaicer has has comletely melted, then RUN NoahMP\n       IF ( (crocus_opt == 0) .or. (GLACINFOH == 1 .and. ZP_SNOWDZ(1,1) .eq. 0.0)) THEN\n          IF ( VEGTYP == ISICE_TABLE ) THEN\n             ICE = -1                           ! Land-ice point\n             if (crocus_opt /= 0) &\n                  GLACR = 1\n             CALL NOAHMP_OPTIONS_GLACIER(IOPT_ALB  ,IOPT_SNF  ,IOPT_TBOT, IOPT_STC, IOPT_GLA )\n\n             TBOT = MIN(TBOT,263.15)                      ! set deep temp to at most -10C\n             CALL NOAHMP_GLACIER(I,       J,    COSZ,   NSNOW,   NSOIL,      DT, & ! IN : Time/Space/Model-related\n                              T_ML,    P_ML,    U_ML,    V_ML,    Q_ML,    SWDN, & ! IN : Forcing\n                              PRCP,    LWDN,    TBOT,    Z_ML, FICEOLD,   ZSOIL, & ! IN : Forcing\n                              parameters%swe_limit,                              & ! IN : Forcing\n                             QSNOW, QRAIN, SNEQVO,  ALBOLD,   CM,   CH,   ISNOW, & ! IN/OUT :\n                               SWE,     SMC,   ZSNSO,  SNDPTH,   SNICE,   SNLIQ, & ! IN/OUT :\n                                TG,     STC,   SMH2O,   TAUSS,  QSFC1D,          & ! IN/OUT :\n                               FSA,     FSR,    FIRA,     FSH,    FGEV,   SSOIL, & ! OUT :\n                              TRAD,   ESOIL,   RUNSF,   RUNSB,     SAG,    SALB, & ! OUT :\n                             QSNBOT,PONDING,PONDING1,PONDING2,    T2MB,    Q2MB, & ! OUT :\n                             EMISSI,  FPICE,    CHB2 &                             ! OUT :\n#ifdef WRF_HYDRO\n                             , sfcheadrt(i,j)                                      &\n#endif\n                             )\n          ENDIF ! VEGTYP == ISICE_TABLE\n       ELSE IF (crocus_opt /= 0 .and. GLACINFOH == 1 .and. ZP_SNOWDZ(1,1) .gt. 0.0) THEN\n          ICE = -1               ! Land-ice point\n          GLACR= 1\n          CALL NOAHMP_OPTIONS_GLACIER(IOPT_ALB  ,IOPT_SNF  ,IOPT_TBOT, IOPT_STC, IOPT_GLA )\n          TBOT = MIN(TBOT,263.15) ! set deep temp to at most -10C\n                                  ! send snow info from crocus to Noahmp_glacier to calc 2m temps etc\n                                  ! move NOAHMP_GLACIER to after CROCUS\n                                  ! for temperatre glacier, set top soil temp to 272\n          ZP_TG(1) = 272.0\n          ! Why is this if block here? Not sure top condition would ever trigger  \n          ! given we are already in an if block requiring ZP_SNOWDZ(1,1) .gt. 0.0. (AD)\n          IF (ZP_SNOWDZ(1,1) .eq. 0.0 .and. ZP_SRSNOW(1) .eq. 0.0) THEN\n          ELSE\n            CALL SNOWCRO(HSNOWRES, OGLACIER, HIMPLICIT_WIND,                   & !(IN)\n                  ZP_PEW_A_COEF, ZP_PEW_B_COEF,                                & !(IN)\n                  ZP_PET_A_COEF, ZP_PEQ_A_COEF, ZP_PET_B_COEF, ZP_PEQ_B_COEF,  & !(IN)\n                  ZP_SNOWSWE,ZP_SNOWRHO, ZP_SNOWHEAT, ZP_SNOWALB,              & ! (INOUT) !several layers\n                  ZP_SNOWGRAN1, ZP_SNOWGRAN2, ZP_SNOWHIST, ZP_SNOWAGE, DT,     & !(INOUT) PTSTEP: (IN)\n                  ZP_PS, ZP_SRSNOW, ZP_RRSNOW ,ZP_PSN3L, ZP_TA, ZP_TG,         & !(IN)\n                  ZP_SW_RAD, ZP_QA, ZP_VMOD, ZP_LW_RAD, ZP_RHOA, ZP_UREF,      & !(IN)\n                  ZP_EXNS, ZP_EXNA, ZP_DIRCOSZW, ZP_ZREF, ZP_Z0NAT, ZP_Z0EFF,  & !(IN)\n                  ZP_Z0HNAT, ZP_ALB, ZP_SOILCOND, ZP_D_G,                      & !(IN)\n                  ZP_SNOWLIQ,                                                  & !(OUT)\n                  ZP_SNOWTEMP, ZP_SNOWDZ, ZP_THRUFAL, ZP_GRNDFLUX, ZP_EVAPCOR, & !(OUT)\n                  ZP_RNSNOW, ZP_HSNOW, ZP_GFLUXSNOW, ZP_HPSNOW, ZP_LES3L,      & !(OUT)\n                  ZP_LEL3L, ZP_EVAP, ZP_SNDRIFT, ZP_RI,                        & !(OUT)\n                  ZP_EMISNOW, ZP_CDSNOW, ZP_USTARSNOW,                         & !(OUT)\n                  ZP_CHSNOW, ZP_SNOWHMASS, ZP_QS,                              & !(OUT)\n                  ZP_VEGTYPE, ZP_ZENITH,                                       & !(IN)\n                  OSNOWDRIFT,OSNOWDRIFT_SUBLIM,                                & !(IN)\n                  OSNOW_ABS_ZENITH, HSNOWMETAMO,HSNOWRAD,                      &\n                  act_level, ZP_VIS_ICEALB,                                    &\n                  ZP_FSA_CROCUS, ZP_FSR_CROCUS, ZP_FIRA_CROCUS,                &\n                  ZFLOW_ICE, ZFLOW_SNOW,                                       &\n                  I,J) !(OUT)\n\n             !  Call to NOAHM_GLACIER to after CROCUS to calculte 2m temp and other 2m variables.\n             !  But use snow info from CROCUS.\n\n             ZSNSO(-NSNOW:0) = 0.0\n             ALBOLD= ZP_SNOWALB(1)\n             SNDPTHH = sum(ZP_SNOWDZ)\n             SNEQVOH= sum(PSNOWSWEXY(I,:,J))\n             SWEH = sum(ZP_SNOWDZ) ! duplicate of SNDPTHH?\n             ZSNSOTH(-1)=-SNDPTHH/2\n             zsnsoTH(0)=-SNDPTHH\n             ZSNSOTH(1)=-SNDPTHH-0.1\n             zSNSOTH(2)=ZSNSO(1)-0.3\n             zSNSOTH(3)=ZSNSO(2)-0.6\n             zSNSOTH(4)=ZSNSO(3)-1.0\n             STC(-NSNOW+3)=273.15\n             STC(-NSNOW+2)=(ZP_SNOWTEMP(1,1))\n             ISNOW=-NSNOW+1 ! (for glacier, always assume a snow layer)\n             SNICEH=sum(PSNOWDZXY(I,:,J))*1000./(NSNOW)\n             if (SNDPTHH .eq. 0) then\n                if(VEGTYP .eq. 24) then\n                   ISNOW=1\n                else\n                   ISNOW=0\n                endif\n             endif\n\n             CALL NOAHMP_GLACIER(     I,       J,    COSZ,   NSNOW,   NSOIL,      DT, & ! IN : Time/Space/Model-related\n                  T_ML,    P_ML,    U_ML,    V_ML,    Q_ML,    SWDN,   & ! IN : Forcing\n                  PRCP,    LWDN,    TBOT,    Z_ML, FICEOLD,   ZSOIL,   & ! IN : Forcing\n                  parameters%swe_limit                               , & ! IN : Forcing\n                  QSNOW, QRAIN, SNEQVOH,  ALBOLD,   CM,   CH,   ISNOW, & ! IN/OUT :\n!                 SWE,     SMC,   ZSNSO,  SNDPTH,   SNICE,   SNLIQ,    & ! IN/OUT :\n                  SWEH,     SMC,   ZSNSOTH,  SNDPTHH,   SNICEH,   SNLIQ, & ! IN/OUT :\n                  TG,     STC,   SMH2O,   TAUSS,  QSFC1D,              & ! IN/OUT :\n                  FSA,     FSR,    FIRA,     FSH,    FGEV,   SSOIL,    & ! OUT :\n                  TRAD,   ESOIL,   RUNSF,   RUNSB,     SAG,    SALB,   & ! OUT :\n                  QSNBOT,PONDING,PONDING1,PONDING2,    T2MB,    Q2MB,  & ! OUT :\n                  EMISSI,  FPICE,    CHB2                              & ! OUT :\n#ifdef WRF_HYDRO\n                  , sfcheadrt(i,j)                                     &\n#endif\n             )\n\n\n             RUNSF=ZP_THRUFAL(1)\n             RUNSB=0.            ! assume that there are no subsurface runoff under the glacier.\n#ifdef WRF_HYDRO\n             RUNSF=ZP_THRUFAL(1)+sfcheadrt(i,j)/DT\n#endif\n\n             SNLIQ = 0\n             FOO1 = MAX((ZP_LEL3L+ZP_LES3L)/2.8440E06,0.)\n             FOO2 = ABS(MIN((ZP_LEL3L+ZP_LES3L)/2.8440E06,0.))\n\n             FSA = ZP_FSA_CROCUS(1)\n             FSR = ZP_FSR_CROCUS(1)\n             FIRA = ZP_FIRA_CROCUS(1)\n             FSH = ZP_HSNOW(1)\n             FGEV = ZP_LEL3L(1)+ZP_LES3L(1)\n             SSOIL=ZP_GRNDFLUX(1)\n             ESOIL = FOO1(1)-FOO2(1)\n\n             TG=ZP_SNOWTEMP(1,1)\n             STC   (      1:NSOIL)=273.16\n\n             ! If a crocus glacier cell has melted out, need to reset so NoahMP can take over.\n             ! Note that NOAHMP_GLACIER call above updates SNDPTHH, so we are checking ZP_SNOWDZ instead.\n             ! Also note that Crocus can generate VERY small negative ZP_SNOWDZ, so we use a <= test.\n             ! The negative outputs should probably be caught and fixed in Crocus.\n             if (ZP_SNOWDZ(1,1) .le. 0.0) then\n               print *, \"Crocus glacier cell has melted out. Switching to NoahMP.\", i, j\n               GLACR = 0\n               ! Resetting soil moisture to max possible for a soil (smc=1 while glacier).\n               ! This will not conserve mass, but avoids unphysical condition when we transition to NoahMP.\n               ! Scaling liquid content based on original ratio (likely small since frozen).\n               if (all(smc .gt. 0.)) then\n                 liq_frac = smh2o/smc\n                 smc = min(smc, parameters%smcmax)\n                 smh2o = smc*liq_frac\n               endif\n             end if\n\n             !----------------\n          ENDIF ! If not (ZP_SNOWDZ(1,1) .eq. 0.0 .and. ZP_SRSNOW(1) .eq. 0.0)\n                ! If crocus is not running, use the original NOAH-MP glacier\n       ELSE IF (crocus_opt /= 0 .and. &\n            GLACINFOH .ne. 1 .and. &\n            VEGTYP == ISICE_TABLE) THEN ! all other glacier grid points\n          ICE = -1\n          GLACR= 1\n          CALL NOAHMP_OPTIONS_GLACIER(IOPT_ALB  ,IOPT_SNF  ,IOPT_TBOT, IOPT_STC, IOPT_GLA )\n          TBOT = MIN(TBOT,263.15) ! set deep temp to at most -10C\n\n          CALL NOAHMP_GLACIER(     I,       J,    COSZ,   NSNOW,   NSOIL,      DT, & ! IN : Time/Space/Model-related\n               T_ML,    P_ML,    U_ML,    V_ML,    Q_ML,    SWDN,  & ! IN : Forcing\n               PRCP,    LWDN,    TBOT,    Z_ML, FICEOLD,   ZSOIL,  & ! IN : Forcing\n               parameters%swe_limit,                               &\n               QSNOW, QRAIN, SNEQVO,  ALBOLD,   CM,   CH,   ISNOW, & ! IN/OUT :\n               SWE,     SMC,   ZSNSO,  SNDPTH,   SNICE,   SNLIQ,   & ! IN/OUT :\n               TG,     STC,   SMH2O,   TAUSS,  QSFC1D,             & ! IN/OUT :\n               FSA,     FSR,    FIRA,     FSH,    FGEV,   SSOIL,   & ! OUT :\n               TRAD,   ESOIL,   RUNSF,   RUNSB,     SAG,    SALB,  & ! OUT :\n               QSNBOT,PONDING,PONDING1,PONDING2,    T2MB,    Q2MB, & ! OUT :\n               EMISSI,  FPICE,    CHB2                             & ! OUT :\n#ifdef WRF_HYDRO\n               , sfcheadrt(i,j)                                    &\n#endif\n               )\n       ENDIF\n\n       IF ((crocus_opt == 0 .and. VEGTYP == ISICE_TABLE) .or. GLACR == 1) THEN\n         FSNO   = 1.0\n         TV     = undefined_value     ! Output from standard Noah-MP undefined for glacier points\n         TGB    = TG\n         CANICE = undefined_value\n         CANLIQ = undefined_value\n         EAH    = undefined_value\n         TAH    = undefined_value\n         FWET   = undefined_value\n         WSLAKE = undefined_value\n         ZWT    = undefined_value\n         WA     = undefined_value\n         WT     = undefined_value\n         LFMASS = undefined_value\n         RTMASS = undefined_value\n         STMASS = undefined_value\n         WOOD   = undefined_value\n         STBLCP = undefined_value\n         FASTCP = undefined_value\n         PLAI   = undefined_value\n         PSAI   = undefined_value\n         T2MV   = undefined_value\n         Q2MV   = undefined_value\n         NEE    = undefined_value\n         GPP    = undefined_value\n         NPP    = undefined_value\n         FVEGMP = 0.0\n         ECAN   = undefined_value\n         ETRAN  = undefined_value\n         APAR   = undefined_value\n         PSN    = undefined_value\n         SAV    = undefined_value\n         RSSUN  = undefined_value\n         RSSHA  = undefined_value\n         BGAP   = undefined_value\n         WGAP   = undefined_value\n         TGV    = undefined_value\n         CHV    = undefined_value\n         CHB    = CH\n         IRC    = undefined_value\n         IRG    = undefined_value\n         SHC    = undefined_value\n         SHG    = undefined_value\n         EVG    = undefined_value\n         GHV    = undefined_value\n         IRB    = FIRA\n         SHB    = FSH\n         EVB    = FGEV\n         GHB    = SSOIL\n         TR     = undefined_value\n         EVC    = undefined_value\n         CHLEAF = undefined_value\n         CHUC   = undefined_value\n         CHV2   = undefined_value\n         FCEV   = undefined_value\n         FCTR   = undefined_value\n         Z0WRF  = 0.002\n         QFX(I,J) = ESOIL\n         LH (I,J) = FGEV\n         ALBSND = undefined_value\n         ALBSNI = undefined_value\n\n      ELSE\n         ICE=0 ! Neither sea ice or land ice.\n\n         if (crocus_opt /= 0 .and. GLACINFOH == 1) then\n            IF (PLAI .lt. -1000) THEN\n               PLAI = 0.5            ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (TAH .lt. -1000) THEN\n               TAH = 273.2           ! trude test. Glacier points does not have a TAH value (-1e+36). Give TAH a value after glaicer has melted.\n            endif\n            IF (EAH .lt. -1000) THEN\n               EAH = 750             ! trude test. Glacier points does not have a EAH value (-1e+36). Give EAH a value  after glaicer has melted.\n            endif\n            IF (FWET .lt. -1000) THEN\n               FWET = 0.05           ! trude test. Glacier points does not have a FWET value (-1e+36). Give FWET a value  after glaicer has melted.\n            endif\n            IF (CANLIQ .lt. -1000) THEN\n               CANLIQ = 0.05         ! trude test. Glacier points does not have a CANLIQ value (-1e+36). Give CANLIQ a value  after glaicer has melted.\n            endif\n            IF (CANICE .lt. -1000) THEN\n               CANICE = 0.00         ! trude test. Glacier points does not have a CANICE value (-1e+36). Give CANICE a value  after glaicer has melted.\n            endif\n            IF (TV .lt. -1000) THEN\n               TV = T_ML +0.5        ! trude test. Glacier points does not have a TV value (-1e+36). Give TV a value  after glaicer has melted.\n            endif\n            IF (TG .le. -1000) THEN\n               TG = T_ML +1.         ! trude test. Glacier points does not have a TG value (-1e+36). Give TG a value  after glaicer has melted.\n            endif\n            ! IF (ZSNSO(1) .le. -1000) THEN\n            !    ZSNSO(:) = 0.       ! trude test. Glacier points does not have a ZSNSO(1) value (-1e+36). Give ZSNSO(1) a value  after glaicer has melted.\n            ! endif\n            ! next varables could probably be defined from input somewhere\n            IF (ZWT .lt. -1000) THEN\n               ZWT = 2.5             ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (WA .lt. -1000) THEN\n               WA = 4900.            ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (WT .lt. -1000) THEN\n               WT = 4900.            ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (WSLAKE .lt. -1000) THEN\n               WSLAKE = 0.           ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (LFMASS .lt. -1000) THEN\n               LFMASS = 6.68219      ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (RTMASS .lt. -1000) THEN\n               RTMASS = 500.         ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (STMASS .lt. -1000) THEN\n               STMASS = 17.82        ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (WOOD .lt. -1000) THEN\n               WOOD = 500.           ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (STBLCP .lt. -1000) THEN\n               STBLCP = 1000.        ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (FASTCP .lt. -1000) THEN\n               FASTCP = 1000.        ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n            IF (PSAI .lt. -1000) THEN\n               PSAI = 0.49           ! trude test. Glacier points does not have a LAI value (-1e+36). Give LAI a value.\n            endif\n         end if ! crocus_opt /= 0\n\n\n         CALL NOAHMP_SFLX (parameters, &\n            I       , J       , LAT     , YEARLEN , JULIAN  , COSZ    , & ! IN : Time/Space-related\n            DT      , DX      , DZ8W1D  , NSOIL   , ZSOIL   , NSNOW   , & ! IN : Model configuration\n            FVEG    , FVGMAX  , VEGTYP  , ICE     , IST     , CROPTYPE, & ! IN : Vegetation/Soil characteristics\n            SMCEQ   ,                                                   & ! IN : Vegetation/Soil characteristics\n            T_ML    , P_ML    , PSFC    , U_ML    , V_ML    , Q_ML    , & ! IN : Forcing\n            QC      , SWDN    , LWDN    ,                               & ! IN : Forcing\n\t    PRCPCONV, PRCPNONC, PRCPSHCV, PRCPSNOW, PRCPGRPL, PRCPHAIL, & ! IN : Forcing\n            TBOT    , CO2PP   , O2PP    , FOLN    , FICEOLD , Z_ML    , & ! IN : Forcing\n            ALBOLD  , SNEQVO  ,                                         & ! IN/OUT :\n            STC     , SMH2O   , SMC     , TAH     , EAH     , FWET    , & ! IN/OUT :\n            CANLIQ  , CANICE  , TV      , TG    , QSFC1D, QSNOW, QRAIN, & ! IN/OUT :\n            ISNOW   , ZSNSO   , SNDPTH  , SWE     , SNICE   , SNLIQ   , & ! IN/OUT :\n            ZWT     , WA      , WT      , WSLAKE  , LFMASS  , RTMASS  , & ! IN/OUT :\n            STMASS  , WOOD    , STBLCP  , FASTCP  , PLAI    , PSAI    , & ! IN/OUT :\n            CM      , CH      , TAUSS   ,                               & ! IN/OUT :\n            GRAIN   , GDD     , PGS     ,                               & ! IN/OUT\n            SMCWTD  ,DEEPRECH , RECH    ,                               & ! IN/OUT :\n            Z0WRF   ,                                                   &\n            FSA     , FSR     , FIRA    , FSH     , SSOIL   , FCEV    , & ! OUT :\n            FGEV    , FCTR    , ECAN    , ETRAN   , ESOIL   , TRAD    , & ! OUT :\n            TGB     , TGV     , T2MV    , T2MB    , Q2MV    , Q2MB    , & ! OUT :\n            RUNSF   , RUNSB   , APAR    , PSN     , SAV     , SAG     , & ! OUT :\n            FSNO    , NEE     , GPP     , NPP     , FVEGMP  , SALB    , & ! OUT :\n            QSNBOT  , PONDING , PONDING1, PONDING2, RSSUN   , RSSHA   , & ! OUT :\n            ALBSND  , ALBSNI  ,                                         & ! OUT :\n            BGAP    , WGAP    , CHV     , CHB     , EMISSI  ,           & ! OUT :\n            SHG     , SHC     , SHB     , EVG     , EVB     , GHV     , & ! OUT :\n\t    GHB     , IRG     , IRC     , IRB     , TR      , EVC     , & ! OUT :\n\t    CHLEAF  , CHUC    , CHV2    , CHB2    , FPICE   , PAHV    , &\n            PAHG    , PAHB    , PAH     , LAISUN  , LAISHA  , RB        &\n#ifdef WRF_HYDRO\n            , sfcheadrt(i,j)                               &\n#endif\n            )            ! OUT :\n\n            QFX(I,J) = ECAN + ESOIL + ETRAN\n            LH       (I,J)                = FCEV + FGEV + FCTR\n\n   ENDIF ! glacial split ends\n\n#ifdef WRF_HYDRO\n\n!---LPR Attention: lpr added this part 2013-09-04 below to avoid restart NaN values----\n!----------------- which may cause the RAPID crash--------------------------\n!yw    if(isnan(RUNSF)) then\n     if((RUNSF+1.0) .eq. RUNSF) then\n         RUNSF   = 0\n         RUNSB   = 0\n     endif\n\n!----lpr add end------------------------------------------------------------------------\n\n!AD_CHANGE: Glacier cells can produce small negative subsurface runoff for mass balance.\n!           This will crash channel routing, so only pass along positive runoff.\n\n     if((RUNSF+1.0) .eq. RUNSF) then\n         RUNSF   = 0\n         RUNSB   = 0\n#ifdef HYDRO_D\n        print*, \"Warning: NAN found from RUNSF and set to 0.\"\n#endif\n     endif\n\n            soldrain(i,j) = max(RUNSB*dt, 0.)        !mm , underground runoff\n            INFXSRT(i,j) = RUNSF*dt        !mm , surface runoff\n\n#endif\n\n\n! INPUT/OUTPUT\n\n             TSK      (I,J)                = TRAD\n             HFX      (I,J)                = FSH\n             GRDFLX   (I,J)                = SSOIL\n\t     SMSTAV   (I,J)                = 0.0  ! [maintained as Noah consistency]\n             SMSTOT   (I,J)                = 0.0  ! [maintained as Noah consistency]\n             SFCRUNOFF(I,J)                = SFCRUNOFF(I,J) + RUNSF * DT\n             UDRUNOFF (I,J)                = UDRUNOFF(I,J)  + RUNSB * DT\n#ifdef WRF_HYDRO\n             if(present(ACCPRCP)) ACCPRCP  (I,J)                = ACCPRCP(I,J) + PRCP * DT\n             if(present(ACCECAN)) ACCECAN  (I,J)                = ACCECAN(I,J) + ECAN * DT\n             if(present(ACCETRAN)) ACCETRAN (I,J)                = ACCETRAN(I,J) + ETRAN * DT\n             if(present(ACCEDIR)) ACCEDIR  (I,J)                = ACCEDIR(I,J) + ESOIL * DT\n\n\t     ! Top 2 layer soil saturation\n             if(present(SOILSAT_TOP)) SOILSAT_TOP (I,J)           = SUM(SMC(1:2) * DZS(1:2)) / SUM(parameters%smcmax(1:2) * DZS(1:2))\n\t     ! Soil column integrated soil saturation\n             if(present(SOILSAT)) SOILSAT (I,J)  = SUM(SMC(1:NSOIL) * DZS(1:NSOIL)) / SUM(parameters%smcmax(1:NSOIL) * DZS(1:NSOIL))\n\t     ! Soil column integrated soil ice fraction\n\t     if(present(SOILICE)) SOILICE (I,J)  = 1. - ( SUM(SMH2O(1:NSOIL) * DZS(1:NSOIL)) / SUM(SMC(1:NSOIL) * DZS(1:NSOIL)) )\n             ! Snowpack average temperature (weighted by layer mass)\n             if (present(SNOWT_AVG)) then\n\t\tif ( SUM(SNICE(-NSNOW+1:0) + SNLIQ(-NSNOW+1:0)) .gt. 0 ) then\n\t\t  SNOWT_AVG (I,J)  = SUM(STC(-NSNOW+1:0) * (SNICE(-NSNOW+1:0) + SNLIQ(-NSNOW+1:0))) / SUM(SNICE(-NSNOW+1:0) + SNLIQ(-NSNOW+1:0))\n\t\telse\n\t\t  SNOWT_AVG (I,J) = undefined_value\n\t\tendif\n\t     endif\n#endif\n             IF ( SALB > -999 ) THEN\n                ALBEDO(I,J)                = SALB\n             ENDIF\n             SNOWC    (I,J)                = FSNO\n             SMOIS    (I,      1:NSOIL,J)  = SMC   (      1:NSOIL)\n             SH2O     (I,      1:NSOIL,J)  = SMH2O (      1:NSOIL)\n             TSLB     (I,      1:NSOIL,J)  = STC   (      1:NSOIL)\n             SNOW     (I,J)                = SWE\n             SNOWH    (I,J)                = SNDPTH\n             CANWAT   (I,J)                = CANLIQ + CANICE\n             ACSNOW   (I,J)                = ACSNOW(I,J) + PRCP*DT * FPICE ! mm\n             ACSNOM   (I,J)                = ACSNOM(I,J) + QSNBOT*DT + PONDING + PONDING1 + PONDING2\n             EMISS    (I,J)                = EMISSI\n             QSFC     (I,J)                = QSFC1D\n\n             ISNOWXY  (I,J)                = ISNOW\n             TVXY     (I,J)                = TV\n             TGXY     (I,J)                = TG\n             CANLIQXY (I,J)                = CANLIQ\n             CANICEXY (I,J)                = CANICE\n             EAHXY    (I,J)                = EAH\n             TAHXY    (I,J)                = TAH\n             CMXY     (I,J)                = CM\n             CHXY     (I,J)                = CH\n             FWETXY   (I,J)                = FWET\n             SNEQVOXY (I,J)                = SNEQVO\n             ALBOLDXY (I,J)                = ALBOLD\n             QSNOWXY  (I,J)                = QSNOW\n             QRAINXY  (I,J)                = QRAIN\n             WSLAKEXY (I,J)                = WSLAKE\n             ZWTXY    (I,J)                = ZWT\n             WAXY     (I,J)                = WA\n             WTXY     (I,J)                = WT\n             TSNOXY   (I,-NSNOW+1:    0,J) = STC   (-NSNOW+1:    0)\n             ZSNSOXY  (I,-NSNOW+1:NSOIL,J) = ZSNSO (-NSNOW+1:NSOIL)\n             SNICEXY  (I,-NSNOW+1:    0,J) = SNICE (-NSNOW+1:    0)\n             SNLIQXY  (I,-NSNOW+1:    0,J) = SNLIQ (-NSNOW+1:    0)\n             LFMASSXY (I,J)                = LFMASS\n             RTMASSXY (I,J)                = RTMASS\n             STMASSXY (I,J)                = STMASS\n             WOODXY   (I,J)                = WOOD\n             STBLCPXY (I,J)                = STBLCP\n             FASTCPXY (I,J)                = FASTCP\n             XLAIXY   (I,J)                = PLAI\n             XSAIXY   (I,J)                = PSAI\n             TAUSSXY  (I,J)                = TAUSS\n\n! OUTPUT\n\n             Z0       (I,J)                = Z0WRF\n             ZNT      (I,J)                = Z0WRF\n             T2MVXY   (I,J)                = T2MV\n             T2MBXY   (I,J)                = T2MB\n             Q2MVXY   (I,J)                = Q2MV/(1.0 - Q2MV)  ! specific humidity to mixing ratio\n             Q2MBXY   (I,J)                = Q2MB/(1.0 - Q2MB)  ! consistent with registry def of Q2\n             TRADXY   (I,J)                = TRAD\n             NEEXY    (I,J)                = NEE\n             GPPXY    (I,J)                = GPP\n             NPPXY    (I,J)                = NPP\n             FVEGXY   (I,J)                = FVEGMP\n             RUNSFXY  (I,J)                = RUNSF\n             RUNSBXY  (I,J)                = RUNSB\n             ECANXY   (I,J)                = ECAN\n             EDIRXY   (I,J)                = ESOIL\n             ETRANXY  (I,J)                = ETRAN\n             FSAXY    (I,J)                = FSA\n             FIRAXY   (I,J)                = FIRA\n             APARXY   (I,J)                = APAR\n             PSNXY    (I,J)                = PSN\n             SAVXY    (I,J)                = SAV\n             SAGXY    (I,J)                = SAG\n             RSSUNXY  (I,J)                = RSSUN\n             RSSHAXY  (I,J)                = RSSHA\n             IF(SWE > 0.0) THEN\n               ALBSNDXY (I,:,J)            = ALBSND   !snow albedo (direct)\n               ALBSNIXY (I,:,J)            = ALBSNI   !snow albedo (diffuse)\n             ELSE\n               ALBSNDXY (I,:,J)            = 0.0   !snow albedo (direct)\n               ALBSNIXY (I,:,J)            = 0.0   !snow albedo (diffuse)\n             ENDIF\n             BGAPXY   (I,J)                = BGAP\n             WGAPXY   (I,J)                = WGAP\n             TGVXY    (I,J)                = TGV\n             TGBXY    (I,J)                = TGB\n             CHVXY    (I,J)                = CHV\n             CHBXY    (I,J)                = CHB\n             IRCXY    (I,J)                = IRC\n             IRGXY    (I,J)                = IRG\n             SHCXY    (I,J)                = SHC\n             SHGXY    (I,J)                = SHG\n             EVGXY    (I,J)                = EVG\n             GHVXY    (I,J)                = GHV\n             IRBXY    (I,J)                = IRB\n             SHBXY    (I,J)                = SHB\n             EVBXY    (I,J)                = EVB\n             GHBXY    (I,J)                = GHB\n             TRXY     (I,J)                = TR\n             EVCXY    (I,J)                = EVC\n             CHLEAFXY (I,J)                = CHLEAF\n             CHUCXY   (I,J)                = CHUC\n             CHV2XY   (I,J)                = CHV2\n             CHB2XY   (I,J)                = CHB2\n             RECHXY   (I,J)                = RECHXY(I,J) + RECH*1.E3 !RECHARGE TO THE WATER TABLE\n             DEEPRECHXY(I,J)               = DEEPRECHXY(I,J) + DEEPRECH\n             SMCWTDXY(I,J)                 = SMCWTD\n\n             if (crocus_opt /= 0) then\n                PSNOWSWEXY(I,1:act_level,J)   = ZP_SNOWSWE(1,1:act_level)\n                PSNOWRHOXY(I,1:act_level,J)   = ZP_SNOWRHO(1,1:act_level)\n                PSNOWHEATXY(I,1:act_level,J)  = ZP_SNOWHEAT(1,1:act_level)\n                PSNOWGRAN1XY(I,1:act_level,J) = ZP_SNOWGRAN1(1,1:act_level)\n                PSNOWGRAN2XY(I,1:act_level,J) = ZP_SNOWGRAN2(1,1:act_level)\n                PSNOWHISTXY(I,1:act_level,J)  = ZP_SNOWHIST(1,1:act_level)\n                PSNOWAGEXY(I,1:act_level,J)   = ZP_SNOWAGE(1,1:act_level)\n                PSNOWLIQXY(I,1:act_level,J)   = ZP_SNOWLIQ(1,1:act_level)\n                PSNOWTEMPXY(I,1:act_level,J)  = ZP_SNOWTEMP(1,1:act_level)\n                PSNOWDZXY(I,1:act_level,J)    = ZP_SNOWDZ(1,1:act_level)\n\n                PSNOWALBXY(I,J)     = ZP_SNOWALB(1)\n                PSNOWTHRUFALXY(I,J) = ZP_THRUFAL(1)*DT\n                FLOW_ICE(I,J)       = FLOW_ICE(I,J)+ZFLOW_ICE(1)*DT\n                FLOW_SNOW(I,J)      = FLOW_SNOW(I,J)+ZFLOW_SNOW(1)*DT\n                PSNOWHEIGHTXY(I,J)  = sum(PSNOWDZXY(I,:,J))\n                PSNOWTOTSWEXY(I,J)  = sum(PSNOWSWEXY(I,:,J))\n\n                if (GLACINFO(I,J).eq.1 .and. PSNOWHEIGHTXY(I,J).gt.0) then\n                   ALBEDO   (I,J) = ZP_SNOWALB(1)\n                   SNOW     (I,J) = PSNOWTOTSWEXY(I,J)\n                   SNOWH    (I,J) = PSNOWHEIGHTXY(I,J)\n                   ACSNOM   (I,J) = FLOW_ICE(I,J)+FLOW_SNOW(I,J)\n                   CANWAT   (I,J) = 0.\n#ifdef WRF_HYDRO\n                   if(present(ACCETRAN)) ACCETRAN(I,J) = 0.\n                   if(present(ACCECAN))  ACCECAN(I,J)  = 0.\n                   if(present(ACCEDIR))  ACCEDIR(I,J)  = ACCEDIR(I,J) + (zp_evap(1)*DT) - (ESOIL*DT)\n                   if(present(SOILSAT_TOP)) SOILSAT_TOP (I,J) = undefined_value\n                   if(present(SOILSAT))   SOILSAT(I,J) = undefined_value\n#endif\n                endif\n             end if ! crocus_opt /= 0\n          ENDIF                                                         ! endif of land-sea test\n      ENDDO ILOOP                                                       ! of I loop\n   ENDDO JLOOP                                                          ! of J loop\n\n!------------------------------------------------------\n  END SUBROUTINE noahmplsm\n!------------------------------------------------------\n\nSUBROUTINE TRANSFER_MP_PARAMETERS(VEGTYPE,SOILTYPE,SLOPETYPE,SOILCOLOR,CROPTYPE,parameters,iopt_imperv)\n\n  USE NOAHMP_TABLES\n  USE MODULE_SF_NOAHMPLSM\n\n  implicit none\n\n  INTEGER, INTENT(IN)    :: VEGTYPE\n  INTEGER, INTENT(IN)    :: SOILTYPE\n  INTEGER, INTENT(IN)    :: SLOPETYPE\n  INTEGER, INTENT(IN)    :: SOILCOLOR\n  INTEGER, INTENT(IN)    :: CROPTYPE\n  INTEGER, INTENT(IN)    :: iopt_imperv\n\n  type (noahmp_parameters), intent(inout) :: parameters\n\n  REAL    :: REFDK\n  REAL    :: REFKDT\n  REAL    :: FRZK\n  REAL    :: FRZFACT\n\n  parameters%ISWATER   =   ISWATER_TABLE\n  parameters%ISBARREN  =  ISBARREN_TABLE\n  parameters%ISICE     =     ISICE_TABLE\n  parameters%ISCROP    =    ISCROP_TABLE\n  parameters%EBLFOREST = EBLFOREST_TABLE\n\n  parameters%URBAN_FLAG = .FALSE.\n  IF( VEGTYPE == ISURBAN_TABLE                  .or. VEGTYPE == LOW_DENSITY_RESIDENTIAL_TABLE  .or. &\n      VEGTYPE == HIGH_DENSITY_RESIDENTIAL_TABLE .or. VEGTYPE == HIGH_INTENSITY_INDUSTRIAL_TABLE ) THEN\n     parameters%URBAN_FLAG = .TRUE.\n  ENDIF\n\n!------------------------------------------------------------------------------------------!\n! Transfer veg parameters\n!------------------------------------------------------------------------------------------!\n\n  parameters%CH2OP  =  CH2OP_TABLE(VEGTYPE)       !maximum intercepted h2o per unit lai+sai (mm)\n  parameters%DLEAF  =  DLEAF_TABLE(VEGTYPE)       !characteristic leaf dimension (m)\n  parameters%Z0MVT  =  Z0MVT_TABLE(VEGTYPE)       !momentum roughness length (m)\n!  parameters%HVT    =    HVT_TABLE(VEGTYPE)       !top of canopy (m)\n  parameters%HVB    =    HVB_TABLE(VEGTYPE)       !bottom of canopy (m)\n  parameters%DEN    =    DEN_TABLE(VEGTYPE)       !tree density (no. of trunks per m2)\n  parameters%RC     =     RC_TABLE(VEGTYPE)       !tree crown radius (m)\n!  parameters%MFSNO  =  MFSNO_TABLE(VEGTYPE)       !snowmelt m parameter ()\n  parameters%SAIM   =   SAIM_TABLE(VEGTYPE,:)     !monthly stem area index, one-sided\n  parameters%LAIM   =   LAIM_TABLE(VEGTYPE,:)     !monthly leaf area index, one-sided\n  parameters%SLA    =    SLA_TABLE(VEGTYPE)       !single-side leaf area per Kg [m2/kg]\n  parameters%DILEFC = DILEFC_TABLE(VEGTYPE)       !coeficient for leaf stress death [1/s]\n  parameters%DILEFW = DILEFW_TABLE(VEGTYPE)       !coeficient for leaf stress death [1/s]\n  parameters%FRAGR  =  FRAGR_TABLE(VEGTYPE)       !fraction of growth respiration  !original was 0.3\n  parameters%LTOVRC = LTOVRC_TABLE(VEGTYPE)       !leaf turnover [1/s]\n\n  parameters%C3PSN  =  C3PSN_TABLE(VEGTYPE)       !photosynthetic pathway: 0. = c4, 1. = c3\n  parameters%KC25   =   KC25_TABLE(VEGTYPE)       !co2 michaelis-menten constant at 25c (pa)\n  parameters%AKC    =    AKC_TABLE(VEGTYPE)       !q10 for kc25\n  parameters%KO25   =   KO25_TABLE(VEGTYPE)       !o2 michaelis-menten constant at 25c (pa)\n  parameters%AKO    =    AKO_TABLE(VEGTYPE)       !q10 for ko25\n!  parameters%VCMX25 = VCMX25_TABLE(VEGTYPE)       !maximum rate of carboxylation at 25c (umol co2/m**2/s)\n  parameters%AVCMX  =  AVCMX_TABLE(VEGTYPE)       !q10 for vcmx25\n  parameters%BP     =     BP_TABLE(VEGTYPE)       !minimum leaf conductance (umol/m**2/s)\n!  parameters%MP     =     MP_TABLE(VEGTYPE)       !slope of conductance-to-photosynthesis relationship\n  parameters%QE25   =   QE25_TABLE(VEGTYPE)       !quantum efficiency at 25c (umol co2 / umol photon)\n  parameters%AQE    =    AQE_TABLE(VEGTYPE)       !q10 for qe25\n  parameters%RMF25  =  RMF25_TABLE(VEGTYPE)       !leaf maintenance respiration at 25c (umol co2/m**2/s)\n  parameters%RMS25  =  RMS25_TABLE(VEGTYPE)       !stem maintenance respiration at 25c (umol co2/kg bio/s)\n  parameters%RMR25  =  RMR25_TABLE(VEGTYPE)       !root maintenance respiration at 25c (umol co2/kg bio/s)\n  parameters%ARM    =    ARM_TABLE(VEGTYPE)       !q10 for maintenance respiration\n  parameters%FOLNMX = FOLNMX_TABLE(VEGTYPE)       !foliage nitrogen concentration when f(n)=1 (%)\n  parameters%TMIN   =   TMIN_TABLE(VEGTYPE)       !minimum temperature for photosynthesis (k)\n\n  parameters%XL     =     XL_TABLE(VEGTYPE)       !leaf/stem orientation index\n  parameters%RHOL   =   RHOL_TABLE(VEGTYPE,:)     !leaf reflectance: 1=vis, 2=nir\n  parameters%RHOS   =   RHOS_TABLE(VEGTYPE,:)     !stem reflectance: 1=vis, 2=nir\n  parameters%TAUL   =   TAUL_TABLE(VEGTYPE,:)     !leaf transmittance: 1=vis, 2=nir\n  parameters%TAUS   =   TAUS_TABLE(VEGTYPE,:)     !stem transmittance: 1=vis, 2=nir\n\n  parameters%MRP    =    MRP_TABLE(VEGTYPE)       !microbial respiration parameter (umol co2 /kg c/ s)\n!  parameters%CWPVT  =  CWPVT_TABLE(VEGTYPE)       !empirical canopy wind parameter\n\n  parameters%WRRAT  =  WRRAT_TABLE(VEGTYPE)       !wood to non-wood ratio\n  parameters%WDPOOL = WDPOOL_TABLE(VEGTYPE)       !wood pool (switch 1 or 0) depending on woody or not [-]\n  parameters%TDLEF  =  TDLEF_TABLE(VEGTYPE)       !characteristic T for leaf freezing [K]\n\n  parameters%NROOT  =  NROOT_TABLE(VEGTYPE)       !number of soil layers with root present\n  parameters%RGL    =    RGL_TABLE(VEGTYPE)       !Parameter used in radiation stress function\n  parameters%RSMIN  =     RS_TABLE(VEGTYPE)       !Minimum stomatal resistance [s m-1]\n  parameters%HS     =     HS_TABLE(VEGTYPE)       !Parameter used in vapor pressure deficit function\n  parameters%TOPT   =   TOPT_TABLE(VEGTYPE)       !Optimum transpiration air temperature [K]\n  parameters%RSMAX  =  RSMAX_TABLE(VEGTYPE)       !Maximal stomatal resistance [s m-1]\n\n!------------------------------------------------------------------------------------------!\n! Transfer rad parameters\n!------------------------------------------------------------------------------------------!\n\n   parameters%ALBSAT    = ALBSAT_TABLE(SOILCOLOR,:)\n   parameters%ALBDRY    = ALBDRY_TABLE(SOILCOLOR,:)\n   parameters%ALBICE    = ALBICE_TABLE\n   parameters%ALBLAK    = ALBLAK_TABLE\n   parameters%OMEGAS    = OMEGAS_TABLE\n   parameters%BETADS    = BETADS_TABLE\n   parameters%BETAIS    = BETAIS_TABLE\n   parameters%EG        = EG_TABLE\n\n!------------------------------------------------------------------------------------------!\n! Transfer crop parameters\n!------------------------------------------------------------------------------------------!\n\n  IF(CROPTYPE > 0) THEN\n   parameters%PLTDAY    =    PLTDAY_TABLE(CROPTYPE)    ! Planting date\n   parameters%HSDAY     =     HSDAY_TABLE(CROPTYPE)    ! Harvest date\n   parameters%PLANTPOP  =  PLANTPOP_TABLE(CROPTYPE)    ! Plant density [per ha] - used?\n   parameters%IRRI      =      IRRI_TABLE(CROPTYPE)    ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n   parameters%GDDTBASE  =  GDDTBASE_TABLE(CROPTYPE)    ! Base temperature for GDD accumulation [C]\n   parameters%GDDTCUT   =   GDDTCUT_TABLE(CROPTYPE)    ! Upper temperature for GDD accumulation [C]\n   parameters%GDDS1     =     GDDS1_TABLE(CROPTYPE)    ! GDD from seeding to emergence\n   parameters%GDDS2     =     GDDS2_TABLE(CROPTYPE)    ! GDD from seeding to initial vegetative\n   parameters%GDDS3     =     GDDS3_TABLE(CROPTYPE)    ! GDD from seeding to post vegetative\n   parameters%GDDS4     =     GDDS4_TABLE(CROPTYPE)    ! GDD from seeding to intial reproductive\n   parameters%GDDS5     =     GDDS5_TABLE(CROPTYPE)    ! GDD from seeding to pysical maturity\n   parameters%C3C4      =      C3C4_TABLE(CROPTYPE)    ! photosynthetic pathway:  1. = c3 2. = c4\n   parameters%AREF      =      AREF_TABLE(CROPTYPE)    ! reference maximum CO2 assimulation rate\n   parameters%PSNRF     =     PSNRF_TABLE(CROPTYPE)    ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\n   parameters%I2PAR     =     I2PAR_TABLE(CROPTYPE)    ! Fraction of incoming solar radiation to photosynthetically active radiation\n   parameters%TASSIM0   =   TASSIM0_TABLE(CROPTYPE)    ! Minimum temperature for CO2 assimulation [C]\n   parameters%TASSIM1   =   TASSIM1_TABLE(CROPTYPE)    ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\n   parameters%TASSIM2   =   TASSIM2_TABLE(CROPTYPE)    ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\n   parameters%K         =         K_TABLE(CROPTYPE)    ! light extinction coefficient\n   parameters%EPSI      =      EPSI_TABLE(CROPTYPE)    ! initial light use efficiency\n   parameters%Q10MR     =     Q10MR_TABLE(CROPTYPE)    ! q10 for maintainance respiration\n   parameters%FOLN_MX   =   FOLN_MX_TABLE(CROPTYPE)    ! foliage nitrogen concentration when f(n)=1 (%)\n   parameters%LEFREEZ   =   LEFREEZ_TABLE(CROPTYPE)    ! characteristic T for leaf freezing [K]\n   parameters%DILE_FC   =   DILE_FC_TABLE(CROPTYPE,:)  ! coeficient for temperature leaf stress death [1/s]\n   parameters%DILE_FW   =   DILE_FW_TABLE(CROPTYPE,:)  ! coeficient for water leaf stress death [1/s]\n   parameters%FRA_GR    =    FRA_GR_TABLE(CROPTYPE)    ! fraction of growth respiration\n   parameters%LF_OVRC   =   LF_OVRC_TABLE(CROPTYPE,:)  ! fraction of leaf turnover  [1/s]\n   parameters%ST_OVRC   =   ST_OVRC_TABLE(CROPTYPE,:)  ! fraction of stem turnover  [1/s]\n   parameters%RT_OVRC   =   RT_OVRC_TABLE(CROPTYPE,:)  ! fraction of root tunrover  [1/s]\n   parameters%LFMR25    =    LFMR25_TABLE(CROPTYPE)    ! leaf maintenance respiration at 25C [umol CO2/m**2  /s]\n   parameters%STMR25    =    STMR25_TABLE(CROPTYPE)    ! stem maintenance respiration at 25C [umol CO2/kg bio/s]\n   parameters%RTMR25    =    RTMR25_TABLE(CROPTYPE)    ! root maintenance respiration at 25C [umol CO2/kg bio/s]\n   parameters%GRAINMR25 = GRAINMR25_TABLE(CROPTYPE)    ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n   parameters%LFPT      =      LFPT_TABLE(CROPTYPE,:)  ! fraction of carbohydrate flux to leaf\n   parameters%STPT      =      STPT_TABLE(CROPTYPE,:)  ! fraction of carbohydrate flux to stem\n   parameters%RTPT      =      RTPT_TABLE(CROPTYPE,:)  ! fraction of carbohydrate flux to root\n   parameters%GRAINPT   =   GRAINPT_TABLE(CROPTYPE,:)  ! fraction of carbohydrate flux to grain\n   parameters%BIO2LAI   =   BIO2LAI_TABLE(CROPTYPE)    ! leaf are per living leaf biomass [m^2/kg]\n  END IF\n\n!------------------------------------------------------------------------------------------!\n! Transfer global parameters\n!------------------------------------------------------------------------------------------!\n\n   parameters%CO2        =         CO2_TABLE\n   parameters%O2         =          O2_TABLE\n   parameters%TIMEAN     =      TIMEAN_TABLE\n   parameters%FSATMX     =      FSATMX_TABLE\n   parameters%Z0SNO      =       Z0SNO_TABLE\n   parameters%SWEMX      =       SWEMX_TABLE\n   parameters%GRAIN_GROWTH = GRAIN_GROWTH_TABLE\n   parameters%EXTRA_GROWTH = EXTRA_GROWTH_TABLE\n   parameters%DIRT_SOOT    =    DIRT_SOOT_TABLE\n   parameters%BATS_COSZ    =    BATS_COSZ_TABLE\n   parameters%BATS_VIS_NEW = BATS_VIS_NEW_TABLE\n   parameters%BATS_NIR_NEW = BATS_NIR_NEW_TABLE\n   parameters%BATS_VIS_AGE = BATS_VIS_AGE_TABLE\n   parameters%BATS_NIR_AGE = BATS_NIR_AGE_TABLE\n   parameters%BATS_VIS_DIR = BATS_VIS_DIR_TABLE\n   parameters%BATS_NIR_DIR = BATS_NIR_DIR_TABLE\n   parameters%SWE_LIMIT  =  SWE_LIMIT_TABLE\n\n! ----------------------------------------------------------------------\n!  Transfer soil parameters\n! ----------------------------------------------------------------------\n\n#ifndef SPATIAL_SOIL\n    parameters%BEXP   = BEXP_TABLE   (SOILTYPE)\n    parameters%DKSAT  = DKSAT_TABLE  (SOILTYPE)\n    parameters%DWSAT  = DWSAT_TABLE  (SOILTYPE)\n    parameters%F1     = F1_TABLE     (SOILTYPE)\n    parameters%PSISAT = PSISAT_TABLE (SOILTYPE)\n    parameters%QUARTZ = QUARTZ_TABLE (SOILTYPE)\n    parameters%SMCDRY = SMCDRY_TABLE (SOILTYPE)\n    parameters%SMCMAX = SMCMAX_TABLE (SOILTYPE)\n    parameters%SMCREF = SMCREF_TABLE (SOILTYPE)\n    parameters%SMCWLT = SMCWLT_TABLE (SOILTYPE)\n    parameters%REFDK  = REFDK_TABLE\n    parameters%REFKDT = REFKDT_TABLE\n    parameters%SLOPE  = SLOPE_TABLE(SLOPETYPE)\n    parameters%CWPVT  =  CWPVT_TABLE(VEGTYPE)       !empirical canopy wind parameter\n    parameters%VCMX25 = VCMX25_TABLE(VEGTYPE)       !maximum rate of carboxylation at 25c (umol co2/m**2/s)\n    parameters%MFSNO  =  MFSNO_TABLE(VEGTYPE)       !snowmelt m parameter ()\n    parameters%HVT    =    HVT_TABLE(VEGTYPE)       !top of canopy (m)\n    parameters%MP     =     MP_TABLE(VEGTYPE)       !slope of conductance-to-photosynthesis relationship\n    parameters%RSURF_EXP  =   RSURF_EXP_TABLE\n    parameters%AXAJ = AXAJ_TABLE(SOILTYPE)\n    parameters%BXAJ = BXAJ_TABLE(SOILTYPE)\n    parameters%XXAJ = XXAJ_TABLE(SOILTYPE)\n    IF (parameters%URBAN_FLAG) THEN\n      parameters%IMPERV = IMPERV_URBAN_TABLE\n    ELSE\n      parameters%IMPERV = 0.0\n    ENDIF\n    parameters%SSI    = SSI_TABLE\n    parameters%SNOW_RET_FAC = SNOW_RET_FAC_TABLE\n    parameters%TAU0   = TAU0_TABLE\n    parameters%RSURF_SNOW = RSURF_SNOW_TABLE\n    parameters%SCAMAX = SCAMAX_TABLE\n#endif\n! ----------------------------------------------------------------------\n! Transfer GENPARM parameters\n! ----------------------------------------------------------------------\n    parameters%CSOIL  = CSOIL_TABLE\n    parameters%ZBOT   = ZBOT_TABLE\n    parameters%CZIL   = CZIL_TABLE\n\n    FRZK   = FRZK_TABLE\n    parameters%KDT    = parameters%REFKDT * parameters%DKSAT(1) / parameters%REFDK\n\n    IF(parameters%URBAN_FLAG)THEN  ! Hardcoding some urban parameters for soil\n       if (iopt_imperv .eq. 9) then\n         parameters%SMCMAX = 0.45\n         parameters%SMCREF = 0.42\n         parameters%SMCWLT = 0.40\n         parameters%SMCDRY = 0.40\n       endif\n       parameters%CSOIL  = 3.E6\n    ENDIF\n\n! adjust FRZK parameter to actual soil type: FRZK * FRZFACT\n\n    IF(SOILTYPE /= 14) then\n      FRZFACT = (parameters%SMCMAX(1) / parameters%SMCREF(1)) * (0.412 / 0.468)\n      parameters%FRZX = FRZK * FRZFACT\n    END IF\n\n END SUBROUTINE TRANSFER_MP_PARAMETERS\n\nSUBROUTINE PEDOTRANSFER_SR2006(nsoil,sand,clay,orgm,parameters)\n\n  use module_sf_noahmplsm\n  use noahmp_tables\n\n  implicit none\n\n  integer,                    intent(in   ) :: nsoil     ! number of soil layers\n  real, dimension( 1:nsoil ), intent(inout) :: sand\n  real, dimension( 1:nsoil ), intent(inout) :: clay\n  real, dimension( 1:nsoil ), intent(inout) :: orgm\n\n  real, dimension( 1:nsoil ) :: theta_1500t\n  real, dimension( 1:nsoil ) :: theta_1500\n  real, dimension( 1:nsoil ) :: theta_33t\n  real, dimension( 1:nsoil ) :: theta_33\n  real, dimension( 1:nsoil ) :: theta_s33t\n  real, dimension( 1:nsoil ) :: theta_s33\n  real, dimension( 1:nsoil ) :: psi_et\n  real, dimension( 1:nsoil ) :: psi_e\n\n  type(noahmp_parameters), intent(inout) :: parameters\n  integer :: k\n\n  do k = 1,4\n    if(sand(k) <= 0 .or. clay(k) <= 0) then\n      sand(k) = 0.41\n      clay(k) = 0.18\n    end if\n    if(orgm(k) <= 0 ) orgm(k) = 0.0\n  end do\n\n  theta_1500t =   sr2006_theta_1500t_a*sand       &\n                + sr2006_theta_1500t_b*clay       &\n                + sr2006_theta_1500t_c*orgm       &\n                + sr2006_theta_1500t_d*sand*orgm  &\n                + sr2006_theta_1500t_e*clay*orgm  &\n                + sr2006_theta_1500t_f*sand*clay  &\n                + sr2006_theta_1500t_g\n\n  theta_1500  =   theta_1500t                      &\n                + sr2006_theta_1500_a*theta_1500t  &\n                + sr2006_theta_1500_b\n\n  theta_33t   =   sr2006_theta_33t_a*sand       &\n                + sr2006_theta_33t_b*clay       &\n                + sr2006_theta_33t_c*orgm       &\n                + sr2006_theta_33t_d*sand*orgm  &\n                + sr2006_theta_33t_e*clay*orgm  &\n                + sr2006_theta_33t_f*sand*clay  &\n                + sr2006_theta_33t_g\n\n  theta_33    =   theta_33t                              &\n                + sr2006_theta_33_a*theta_33t*theta_33t  &\n                + sr2006_theta_33_b*theta_33t            &\n                + sr2006_theta_33_c\n\n  theta_s33t  =   sr2006_theta_s33t_a*sand      &\n                + sr2006_theta_s33t_b*clay      &\n                + sr2006_theta_s33t_c*orgm      &\n                + sr2006_theta_s33t_d*sand*orgm &\n                + sr2006_theta_s33t_e*clay*orgm &\n                + sr2006_theta_s33t_f*sand*clay &\n                + sr2006_theta_s33t_g\n\n  theta_s33   = theta_s33t                       &\n                + sr2006_theta_s33_a*theta_s33t  &\n                + sr2006_theta_s33_b\n\n  psi_et      =   sr2006_psi_et_a*sand           &\n                + sr2006_psi_et_b*clay           &\n                + sr2006_psi_et_c*theta_s33      &\n                + sr2006_psi_et_d*sand*theta_s33 &\n                + sr2006_psi_et_e*clay*theta_s33 &\n                + sr2006_psi_et_f*sand*clay      &\n                + sr2006_psi_et_g\n\n  psi_e       =   psi_et                        &\n                + sr2006_psi_e_a*psi_et*psi_et  &\n                + sr2006_psi_e_b*psi_et         &\n                + sr2006_psi_e_c\n\n  parameters%smcwlt = theta_1500\n  parameters%smcref = theta_33\n  parameters%smcmax =   theta_33    &\n                      + theta_s33            &\n                      + sr2006_smcmax_a*sand &\n                      + sr2006_smcmax_b\n\n  parameters%bexp   = 3.816712826 / (log(theta_33) - log(theta_1500) )\n  parameters%psisat = psi_e\n  parameters%dksat  = 1930.0 * (parameters%smcmax - theta_33) ** (3.0 - 1.0/parameters%bexp)\n  parameters%quartz = sand\n\n! Units conversion\n\n  parameters%psisat = max(0.1,parameters%psisat)     ! arbitrarily impose a limit of 0.1kpa\n  parameters%psisat = 0.101997 * parameters%psisat   ! convert kpa to m\n  parameters%dksat  = parameters%dksat / 3600000.0   ! convert mm/h to m/s\n  parameters%dwsat  = parameters%dksat * parameters%psisat *parameters%bexp / parameters%smcmax  ! units should be m*m/s\n  parameters%smcdry = parameters%smcwlt\n\n! Introducing somewhat arbitrary limits (based on SOILPARM) to prevent bad things\n\n  parameters%smcmax = max(0.32 ,min(parameters%smcmax,             0.50 ))\n  parameters%smcref = max(0.17 ,min(parameters%smcref,parameters%smcmax ))\n  parameters%smcwlt = max(0.01 ,min(parameters%smcwlt,parameters%smcref ))\n  parameters%smcdry = max(0.01 ,min(parameters%smcdry,parameters%smcref ))\n  parameters%bexp   = max(2.50 ,min(parameters%bexp,               12.0 ))\n  parameters%psisat = max(0.03 ,min(parameters%psisat,             1.00 ))\n  parameters%dksat  = max(5.e-7,min(parameters%dksat,              1.e-5))\n  parameters%dwsat  = max(1.e-6,min(parameters%dwsat,              3.e-5))\n  parameters%quartz = max(0.05 ,min(parameters%quartz,             0.95 ))\n\n END SUBROUTINE PEDOTRANSFER_SR2006\n\n  SUBROUTINE NOAHMP_INIT ( MMINLU, SNOW , SNOWH , CANWAT , ISLTYP ,   IVGTYP, &\n       TSLB , SMOIS , SH2O , DZS , FNDSOILW , FNDSNOWH ,             &\n       TSK, isnowxy , tvxy     ,tgxy     ,canicexy ,         TMN,     XICE,   &\n       canliqxy ,eahxy    ,tahxy    ,cmxy     ,chxy     ,                     &\n       fwetxy   ,sneqvoxy ,alboldxy ,qsnowxy  ,wslakexy ,zwtxy    ,waxy     , &\n       wtxy     ,tsnoxy   ,zsnsoxy  ,snicexy  ,snliqxy  ,lfmassxy ,rtmassxy , &\n       stmassxy ,woodxy   ,stblcpxy ,fastcpxy ,xsaixy   ,lai      ,           &\n!jref:start\n       t2mvxy   ,t2mbxy   ,chstarxy,            &\n!jref:end\n       NSOIL, restart,                 &\n       allowed_to_read , iopt_run, iopt_crop, iopt_pedo,   &\n       ids,ide, jds,jde, kds,kde,                &\n       ims,ime, jms,jme, kms,kme,                &\n       its,ite, jts,jte, kts,kte,                &\n       smoiseq  ,smcwtdxy ,rechxy   ,deeprechxy, areaxy, dx, dy, msftx, msfty,&     ! Optional groundwater\n       wtddt    ,stepwtd  ,dt       ,qrfsxy     ,qspringsxy  , qslatxy    ,  &      ! Optional groundwater\n       fdepthxy ,ht     ,riverbedxy ,eqzwt     ,rivercondxy ,pexpxy            )    ! Optional groundwater\n\n  USE NOAHMP_TABLES\n\n  IMPLICIT NONE\n\n! Initializing Canopy air temperature to 287 K seems dangerous to me [KWM].\n\n    INTEGER, INTENT(IN   )    ::     ids,ide, jds,jde, kds,kde,  &\n         &                           ims,ime, jms,jme, kms,kme,  &\n         &                           its,ite, jts,jte, kts,kte\n\n    INTEGER, INTENT(IN)       ::     NSOIL, iopt_run, iopt_crop, iopt_pedo\n\n    LOGICAL, INTENT(IN)       ::     restart,                    &\n         &                           allowed_to_read\n\n    REAL,    DIMENSION( NSOIL), INTENT(IN)    ::     DZS  ! Thickness of the soil layers [m]\n    REAL,    INTENT(IN) , OPTIONAL ::     DX, DY\n    REAL,    DIMENSION( ims:ime, jms:jme ) ,  INTENT(IN) , OPTIONAL :: MSFTX,MSFTY\n\n    REAL,    DIMENSION( ims:ime, NSOIL, jms:jme ) ,    &\n         &   INTENT(INOUT)    ::     SMOIS,                      &\n         &                           SH2O,                       &\n         &                           TSLB\n\n    REAL,    DIMENSION( ims:ime, jms:jme ) ,                     &\n         &   INTENT(INOUT)    ::     SNOW,                       &\n         &                           SNOWH,                      &\n         &                           CANWAT\n\n    INTEGER, DIMENSION( ims:ime, jms:jme ),                      &\n         &   INTENT(IN)       ::     ISLTYP,  &\n                                     IVGTYP\n\n    LOGICAL, INTENT(IN)       ::     FNDSOILW,                   &\n         &                           FNDSNOWH\n\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(IN) :: TSK         !skin temperature (k)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: TMN         !deep soil temperature (k)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(IN) :: XICE         !sea ice fraction\n    INTEGER, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: isnowxy     !actual no. of snow layers\n    REAL, DIMENSION(ims:ime,-2:NSOIL,jms:jme), INTENT(INOUT) :: zsnsoxy  !snow layer depth [m]\n    REAL, DIMENSION(ims:ime,-2:              0,jms:jme), INTENT(INOUT) :: tsnoxy   !snow temperature [K]\n    REAL, DIMENSION(ims:ime,-2:              0,jms:jme), INTENT(INOUT) :: snicexy  !snow layer ice [mm]\n    REAL, DIMENSION(ims:ime,-2:              0,jms:jme), INTENT(INOUT) :: snliqxy  !snow layer liquid water [mm]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: tvxy        !vegetation canopy temperature\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: tgxy        !ground surface temperature\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: canicexy    !canopy-intercepted ice (mm)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: canliqxy    !canopy-intercepted liquid water (mm)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: eahxy       !canopy air vapor pressure (pa)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: tahxy       !canopy air temperature (k)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: cmxy        !momentum drag coefficient\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: chxy        !sensible heat exchange coefficient\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: fwetxy      !wetted or snowed fraction of the canopy (-)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: sneqvoxy    !snow mass at last time step(mm h2o)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: alboldxy    !snow albedo at last time step (-)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: qsnowxy     !snowfall on the ground [mm/s]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: wslakexy    !lake water storage [mm]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: zwtxy       !water table depth [m]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: waxy        !water in the \"aquifer\" [mm]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: wtxy        !groundwater storage [mm]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: lfmassxy    !leaf mass [g/m2]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: rtmassxy    !mass of fine roots [g/m2]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: stmassxy    !stem mass [g/m2]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: woodxy      !mass of wood (incl. woody roots) [g/m2]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: stblcpxy    !stable carbon in deep soil [g/m2]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: fastcpxy    !short-lived carbon, shallow soil [g/m2]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: xsaixy      !stem area index\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: lai         !leaf area index\n\n! IOPT_RUN = 5 option\n\n    REAL, DIMENSION(ims:ime,1:nsoil,jms:jme), INTENT(INOUT) , OPTIONAL :: smoiseq !equilibrium soil moisture content [m3m-3]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) , OPTIONAL :: smcwtdxy    !deep soil moisture content [m3m-3]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) , OPTIONAL :: deeprechxy  !deep recharge [m]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) , OPTIONAL :: rechxy      !accumulated recharge [mm]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) , OPTIONAL :: qrfsxy      !accumulated flux from groundwater to rivers [mm]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) , OPTIONAL :: qspringsxy  !accumulated seeping water [mm]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) , OPTIONAL :: qslatxy     !accumulated lateral flow [mm]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) , OPTIONAL :: areaxy      !grid cell area [m2]\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(IN) , OPTIONAL :: FDEPTHXY    !efolding depth for transmissivity (m)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(IN) , OPTIONAL :: HT          !terrain height (m)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(IN) , OPTIONAL :: RIVERBEDXY  !riverbed depth (m)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(IN) , OPTIONAL :: EQZWT       !equilibrium water table depth (m)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(IN) , OPTIONAL :: RIVERCONDXY !river conductance\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(IN) , OPTIONAL :: PEXPXY      !factor for river conductance\n\n    INTEGER,  INTENT(INOUT) , OPTIONAL :: STEPWTD\n    REAL, INTENT(IN) , OPTIONAL :: DT, WTDDT\n\n!jref:start\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: t2mvxy        !2m temperature vegetation part (k)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: t2mbxy        !2m temperature bare ground part (k)\n    REAL, DIMENSION(ims:ime,jms:jme), INTENT(INOUT) :: chstarxy        !dummy\n!jref:end\n\n\n    REAL, DIMENSION(1:NSOIL)  :: ZSOIL      ! Depth of the soil layer bottom (m) from\n    !                                                   the surface (negative)\n\n    REAL                      :: BEXP, SMCMAX, PSISAT\n    REAL                      :: FK, masslai,masssai\n\n    REAL, PARAMETER           :: BLIM  = 5.5\n    REAL, PARAMETER           :: HLICE = 3.335E5\n    REAL, PARAMETER           :: GRAV = 9.81\n    REAL, PARAMETER           :: T0 = 273.15\n\n    INTEGER                   :: errflag, i,j,itf,jtf,ns\n\n    character(len=80) :: err_message\n    character(len=4)  :: MMINSL\n    character(len=*), intent(in) :: MMINLU\n    MMINSL='STAS'\n\n    call read_mp_veg_parameters(trim(MMINLU))\n    call read_mp_soil_parameters()\n    call read_mp_rad_parameters()\n    call read_mp_global_parameters()\n    if(iopt_crop == 1) call read_mp_crop_parameters()\n    if(iopt_pedo == 1) call read_mp_optional_parameters()\n\n    IF( .NOT. restart ) THEN\n\n       itf=min0(ite,ide-1)\n       jtf=min0(jte,jde-1)\n\n       !\n       ! initialize physical snow height SNOWH\n       !\n       IF(.NOT.FNDSNOWH)THEN\n          ! If no SNOWH do the following\n          CALL wrf_message( 'SNOW HEIGHT NOT FOUND - VALUE DEFINED IN LSMINIT' )\n          DO J = jts,jtf\n             DO I = its,itf\n                SNOWH(I,J)=SNOW(I,J)*0.005               ! SNOW in mm and SNOWH in m\n             ENDDO\n          ENDDO\n       ENDIF\n\n       errflag = 0\n       DO j = jts,jtf\n          DO i = its,itf\n             IF ( ISLTYP( i,j ) .LT. 1 ) THEN\n                errflag = 1\n                WRITE(err_message,*)\"module_sf_noahlsm.F: lsminit: out of range ISLTYP \",i,j,ISLTYP( i,j )\n                CALL wrf_message(err_message)\n             ENDIF\n          ENDDO\n       ENDDO\n       IF ( errflag .EQ. 1 ) THEN\n          CALL wrf_error_fatal( \"module_sf_noahlsm.F: lsminit: out of range value \"// &\n               \"of ISLTYP. Is this field in the input?\" )\n       ENDIF\n! GAC-->LATERALFLOW\n! 20130219 - No longer need this - see module_data_gocart_dust\n!#if ( WRF_CHEM == 1 )\n!       !\n!       ! need this parameter for dust parameterization in wrf/chem\n!       !\n!       do I=1,NSLTYPE\n!          porosity(i)=maxsmc(i)\n!       enddo\n!#endif\n! <--GAC\n\n! initialize soil liquid water content SH2O\n\n       DO J = jts , jtf\n          DO I = its , itf\n\t    IF(IVGTYP(I,J)==ISICE_TABLE .AND. XICE(I,J) <= 0.0) THEN\n              DO NS=1, NSOIL\n\t        SMOIS(I,NS,J) = 1.0                     ! glacier starts all frozen\n\t        SH2O(I,NS,J) = 0.0\n\t        TSLB(I,NS,J) = MIN(TSLB(I,NS,J),263.15) ! set glacier temp to at most -10C\n              END DO\n\t        !TMN(I,J) = MIN(TMN(I,J),263.15)         ! set deep temp to at most -10C\n\t\tSNOW(I,J) = MAX(SNOW(I,J), 10.0)        ! set SWE to at least 10mm\n                SNOWH(I,J)=SNOW(I,J)*0.01               ! SNOW in mm and SNOWH in m\n\t    ELSE\n\n              BEXP   =   BEXP_TABLE(ISLTYP(I,J))\n              SMCMAX = SMCMAX_TABLE(ISLTYP(I,J))\n              PSISAT = PSISAT_TABLE(ISLTYP(I,J))\n\n              DO NS=1, NSOIL\n\t        IF ( SMOIS(I,NS,J) > SMCMAX )  SMOIS(I,NS,J) = SMCMAX\n              END DO\n              IF ( ( BEXP > 0.0 ) .AND. ( SMCMAX > 0.0 ) .AND. ( PSISAT > 0.0 ) ) THEN\n                DO NS=1, NSOIL\n                   IF ( TSLB(I,NS,J) < 273.149 ) THEN    ! Use explicit as initial soil ice\n                      FK=(( (HLICE/(GRAV*(-PSISAT))) *                              &\n                           ((TSLB(I,NS,J)-T0)/TSLB(I,NS,J)) )**(-1/BEXP) )*SMCMAX\n                      FK = MAX(FK, 0.02)\n                      SH2O(I,NS,J) = MIN( FK, SMOIS(I,NS,J) )\n                   ELSE\n                      SH2O(I,NS,J)=SMOIS(I,NS,J)\n                   ENDIF\n                END DO\n              ELSE\n                DO NS=1, NSOIL\n                   SH2O(I,NS,J)=SMOIS(I,NS,J)\n                END DO\n              ENDIF\n            ENDIF\n          ENDDO\n       ENDDO\n!  ENDIF\n\n\n       DO J = jts,jtf\n          DO I = its,itf\n             tvxy       (I,J) = TSK(I,J)\n\t       if(snow(i,j) > 0.0 .and. tsk(i,j) > 273.15) tvxy(I,J) = 273.15\n             tgxy       (I,J) = TSK(I,J)\n\t       if(snow(i,j) > 0.0 .and. tsk(i,j) > 273.15) tgxy(I,J) = 273.15\n             CANWAT     (I,J) = 0.0\n             canliqxy   (I,J) = CANWAT(I,J)\n             canicexy   (I,J) = 0.\n             eahxy      (I,J) = 2000.\n             tahxy      (I,J) = TSK(I,J)\n\t       if(snow(i,j) > 0.0 .and. tsk(i,j) > 273.15) tahxy(I,J) = 273.15\n!             tahxy      (I,J) = 287.\n!jref:start\n             t2mvxy     (I,J) = TSK(I,J)\n\t       if(snow(i,j) > 0.0 .and. tsk(i,j) > 273.15) t2mvxy(I,J) = 273.15\n             t2mbxy     (I,J) = TSK(I,J)\n\t       if(snow(i,j) > 0.0 .and. tsk(i,j) > 273.15) t2mbxy(I,J) = 273.15\n             chstarxy     (I,J) = 0.1\n!jref:end\n\n             cmxy       (I,J) = 0.0\n             chxy       (I,J) = 0.0\n             fwetxy     (I,J) = 0.0\n             sneqvoxy   (I,J) = 0.0\n             alboldxy   (I,J) = 0.65\n             qsnowxy    (I,J) = 0.0\n             wslakexy   (I,J) = 0.0\n\n             if(iopt_run.ne.5) then\n                   waxy       (I,J) = 4900.                                       !???\n                   wtxy       (I,J) = waxy(i,j)                                   !???\n                   zwtxy      (I,J) = (25. + 2.0) - waxy(i,j)/1000/0.2            !???\n             else\n                   waxy       (I,J) = 0.\n                   wtxy       (I,J) = 0.\n                   areaxy     (I,J) = (DX * DY) / ( MSFTX(I,J) * MSFTY(I,J) )\n             endif\n\n           IF(IVGTYP(I,J) == ISBARREN_TABLE .OR. IVGTYP(I,J) == ISICE_TABLE .OR. &\n\t      IVGTYP(I,J) == ISURBAN_TABLE  .OR. IVGTYP(I,J) == ISWATER_TABLE ) THEN\n\n\t     lai        (I,J) = 0.0\n             xsaixy     (I,J) = 0.0\n             lfmassxy   (I,J) = 0.0\n             stmassxy   (I,J) = 0.0\n             rtmassxy   (I,J) = 0.0\n             woodxy     (I,J) = 0.0\n             stblcpxy   (I,J) = 0.0\n             fastcpxy   (I,J) = 0.0\n\n\t   ELSE\n\n\t     lai        (I,J) = max(lai(i,j),0.05)             ! at least start with 0.05 for arbitrary initialization (v3.7)\n             xsaixy     (I,J) = max(0.1*lai(I,J),0.05)         ! MB: arbitrarily initialize SAI using input LAI (v3.7)\n             masslai = 1000. / max(SLA_TABLE(IVGTYP(I,J)),1.0) ! conversion from lai to mass  (v3.7)\n             lfmassxy   (I,J) = lai(i,j)*masslai               ! use LAI to initialize (v3.7)\n             masssai = 1000. / 3.0                             ! conversion from lai to mass (v3.7)\n             stmassxy   (I,J) = xsaixy(i,j)*masssai            ! use SAI to initialize (v3.7)\n             rtmassxy   (I,J) = 500.0                          ! these are all arbitrary and probably should be\n             woodxy     (I,J) = 500.0                          ! in the table or read from initialization\n             stblcpxy   (I,J) = 1000.0                         !\n             fastcpxy   (I,J) = 1000.0                         !\n\n\t   END IF\n\n          enddo\n       enddo\n\n       ! Given the soil layer thicknesses (in DZS), initialize the soil layer\n       ! depths from the surface.\n       ZSOIL(1)         = -DZS(1)          ! negative\n       DO NS=2, NSOIL\n          ZSOIL(NS)       = ZSOIL(NS-1) - DZS(NS)\n       END DO\n\n       ! Initialize snow/soil layer arrays ZSNSOXY, TSNOXY, SNICEXY, SNLIQXY,\n       ! and ISNOWXY\n       CALL snow_init ( ims , ime , jms , jme , its , itf , jts , jtf , 3 , &\n            &           NSOIL , zsoil , snow , tgxy , snowh ,     &\n            &           zsnsoxy , tsnoxy , snicexy , snliqxy , isnowxy )\n\n       !initialize arrays for groundwater dynamics iopt_run=5\n\n       if(iopt_run.eq.5) then\n          IF ( PRESENT(smoiseq)     .AND. &\n            PRESENT(smcwtdxy)    .AND. &\n            PRESENT(rechxy)      .AND. &\n            PRESENT(deeprechxy)  .AND. &\n            PRESENT(areaxy)      .AND. &\n            PRESENT(dx)          .AND. &\n            PRESENT(dy)          .AND. &\n            PRESENT(msftx)       .AND. &\n            PRESENT(msfty)       .AND. &\n            PRESENT(wtddt)       .AND. &\n            PRESENT(stepwtd)     .AND. &\n            PRESENT(dt)          .AND. &\n            PRESENT(qrfsxy)      .AND. &\n            PRESENT(qspringsxy)  .AND. &\n            PRESENT(qslatxy)     .AND. &\n            PRESENT(fdepthxy)    .AND. &\n            PRESENT(ht)          .AND. &\n            PRESENT(riverbedxy)  .AND. &\n            PRESENT(eqzwt)       .AND. &\n            PRESENT(rivercondxy) .AND. &\n            PRESENT(pexpxy)            ) THEN\n\n             STEPWTD = nint(WTDDT*60./DT)\n             STEPWTD = max(STEPWTD,1)\n\n              CALL groundwater_init ( &\n      &       nsoil, zsoil , dzs  ,isltyp, ivgtyp,wtddt , &\n      &       fdepthxy, ht, riverbedxy, eqzwt, rivercondxy, pexpxy , areaxy, zwtxy,   &\n      &       smois,sh2o, smoiseq, smcwtdxy, deeprechxy, rechxy, qslatxy, qrfsxy, qspringsxy, &\n      &       ids,ide, jds,jde, kds,kde,                    &\n      &       ims,ime, jms,jme, kms,kme,                    &\n      &       its,ite, jts,jte, kts,kte                     )\n\n          ELSE\n             CALL wrf_error_fatal ('Not enough fields to use groundwater option in Noah-MP')\n          END IF\n       endif\n\n    ENDIF\n  END SUBROUTINE NOAHMP_INIT\n\n!------------------------------------------------------------------------------------------\n!------------------------------------------------------------------------------------------\n\n  SUBROUTINE SNOW_INIT ( ims , ime , jms , jme , its , itf , jts , jtf ,                  &\n       &                 NSNOW , NSOIL , ZSOIL , SWE , TGXY , SNODEP ,                    &\n       &                 ZSNSOXY , TSNOXY , SNICEXY ,SNLIQXY , ISNOWXY )\n!------------------------------------------------------------------------------------------\n!   Initialize snow arrays for Noah-MP LSM, based in input SNOWDEP, NSNOW\n!   ISNOWXY is an index array, indicating the index of the top snow layer.  Valid indices\n!           for snow layers range from 0 (no snow) and -1 (shallow snow) to (-NSNOW)+1 (deep snow).\n!   TSNOXY holds the temperature of the snow layer.  Snow layers are initialized with\n!          temperature = ground temperature [?].  Snow-free levels in the array have value 0.0\n!   SNICEXY is the frozen content of a snow layer.  Initial estimate based on SNODEP and SWE\n!   SNLIQXY is the liquid content of a snow layer.  Initialized to 0.0\n!   ZNSNOXY is the layer depth from the surface.\n!------------------------------------------------------------------------------------------\n    IMPLICIT NONE\n!------------------------------------------------------------------------------------------\n    INTEGER, INTENT(IN)                              :: ims, ime, jms, jme\n    INTEGER, INTENT(IN)                              :: its, itf, jts, jtf\n    INTEGER, INTENT(IN)                              :: NSNOW\n    INTEGER, INTENT(IN)                              :: NSOIL\n    REAL,    INTENT(IN), DIMENSION(ims:ime, jms:jme) :: SWE\n    REAL,    INTENT(IN), DIMENSION(ims:ime, jms:jme) :: SNODEP\n    REAL,    INTENT(IN), DIMENSION(ims:ime, jms:jme) :: TGXY\n    REAL,    INTENT(IN), DIMENSION(1:NSOIL)          :: ZSOIL\n\n    INTEGER, INTENT(OUT), DIMENSION(ims:ime, jms:jme)                :: ISNOWXY ! Top snow layer index\n    REAL,    INTENT(OUT), DIMENSION(ims:ime, -NSNOW+1:NSOIL,jms:jme) :: ZSNSOXY ! Snow/soil layer depth from surface [m]\n    REAL,    INTENT(OUT), DIMENSION(ims:ime, -NSNOW+1:    0,jms:jme) :: TSNOXY  ! Snow layer temperature [K]\n    REAL,    INTENT(OUT), DIMENSION(ims:ime, -NSNOW+1:    0,jms:jme) :: SNICEXY ! Snow layer ice content [mm]\n    REAL,    INTENT(OUT), DIMENSION(ims:ime, -NSNOW+1:    0,jms:jme) :: SNLIQXY ! snow layer liquid content [mm]\n\n! Local variables:\n!   DZSNO   holds the thicknesses of the various snow layers.\n!   DZSNOSO holds the thicknesses of the various soil/snow layers.\n    INTEGER                           :: I,J,IZ\n    REAL,   DIMENSION(-NSNOW+1:    0) :: DZSNO\n    REAL,   DIMENSION(-NSNOW+1:NSOIL) :: DZSNSO\n\n!------------------------------------------------------------------------------------------\n\n    DO J = jts , jtf\n       DO I = its , itf\n          IF ( SNODEP(I,J) < 0.025 ) THEN\n             ISNOWXY(I,J) = 0\n             DZSNO(-NSNOW+1:0) = 0.\n          ELSE\n             IF ( ( SNODEP(I,J) >= 0.025 ) .AND. ( SNODEP(I,J) <= 0.05 ) ) THEN\n                ISNOWXY(I,J)    = -1\n                DZSNO(0)  = SNODEP(I,J)\n             ELSE IF ( ( SNODEP(I,J) > 0.05 ) .AND. ( SNODEP(I,J) <= 0.10 ) ) THEN\n                ISNOWXY(I,J)    = -2\n                DZSNO(-1) = SNODEP(I,J)/2.\n                DZSNO( 0) = SNODEP(I,J)/2.\n             ELSE IF ( (SNODEP(I,J) > 0.10 ) .AND. ( SNODEP(I,J) <= 0.25 ) ) THEN\n                ISNOWXY(I,J)    = -2\n                DZSNO(-1) = 0.05\n                DZSNO( 0) = SNODEP(I,J) - DZSNO(-1)\n             ELSE IF ( ( SNODEP(I,J) > 0.25 ) .AND. ( SNODEP(I,J) <= 0.45 ) ) THEN\n                ISNOWXY(I,J)    = -3\n                DZSNO(-2) = 0.05\n                DZSNO(-1) = 0.5*(SNODEP(I,J)-DZSNO(-2))\n                DZSNO( 0) = 0.5*(SNODEP(I,J)-DZSNO(-2))\n             ELSE IF ( SNODEP(I,J) > 0.45 ) THEN\n                ISNOWXY(I,J)     = -3\n                DZSNO(-2) = 0.05\n                DZSNO(-1) = 0.20\n                DZSNO( 0) = SNODEP(I,J) - DZSNO(-1) - DZSNO(-2)\n             ELSE\n                CALL wrf_error_fatal(\"Problem with the logic assigning snow layers.\")\n             END IF\n          END IF\n\n          TSNOXY (I,-NSNOW+1:0,J) = 0.\n          SNICEXY(I,-NSNOW+1:0,J) = 0.\n          SNLIQXY(I,-NSNOW+1:0,J) = 0.\n          DO IZ = ISNOWXY(I,J)+1 , 0\n             TSNOXY(I,IZ,J)  = TGXY(I,J)  ! [k]\n             SNLIQXY(I,IZ,J) = 0.00\n             SNICEXY(I,IZ,J) = 1.00 * DZSNO(IZ) * (SWE(I,J)/SNODEP(I,J))  ! [kg/m3]\n          END DO\n\n          ! Assign local variable DZSNSO, the soil/snow layer thicknesses, for snow layers\n          DO IZ = ISNOWXY(I,J)+1 , 0\n             DZSNSO(IZ) = -DZSNO(IZ)\n          END DO\n\n          ! Assign local variable DZSNSO, the soil/snow layer thicknesses, for soil layers\n          DZSNSO(1) = ZSOIL(1)\n          DO IZ = 2 , NSOIL\n             DZSNSO(IZ) = (ZSOIL(IZ) - ZSOIL(IZ-1))\n          END DO\n\n          ! Assign ZSNSOXY, the layer depths, for soil and snow layers\n          ZSNSOXY(I,ISNOWXY(I,J)+1,J) = DZSNSO(ISNOWXY(I,J)+1)\n          DO IZ = ISNOWXY(I,J)+2 , NSOIL\n             ZSNSOXY(I,IZ,J) = ZSNSOXY(I,IZ-1,J) + DZSNSO(IZ)\n          ENDDO\n\n       END DO\n    END DO\n\n  END SUBROUTINE SNOW_INIT\n! ==================================================================================================\n! ----------------------------------------------------------------------\n    SUBROUTINE GROUNDWATER_INIT (   &\n            &            NSOIL , ZSOIL , DZS, ISLTYP, IVGTYP, WTDDT , &\n            &            FDEPTH, TOPO, RIVERBED, EQWTD, RIVERCOND, PEXP , AREA ,WTD ,  &\n            &            SMOIS,SH2O, SMOISEQ, SMCWTDXY, DEEPRECHXY, RECHXY ,  &\n            &            QSLATXY, QRFSXY, QSPRINGSXY,                  &\n            &            ids,ide, jds,jde, kds,kde,                    &\n            &            ims,ime, jms,jme, kms,kme,                    &\n            &            its,ite, jts,jte, kts,kte                     )\n\n\n  USE NOAHMP_TABLES, ONLY : BEXP_TABLE,SMCMAX_TABLE,PSISAT_TABLE,SMCWLT_TABLE,DWSAT_TABLE,DKSAT_TABLE, &\n                                ISURBAN_TABLE, ISICE_TABLE ,ISWATER_TABLE\n  USE module_sf_noahmp_groundwater, ONLY : LATERALFLOW\n\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n\n    INTEGER,  INTENT(IN   )   ::     ids,ide, jds,jde, kds,kde,  &\n         &                           ims,ime, jms,jme, kms,kme,  &\n         &                           its,ite, jts,jte, kts,kte\n    INTEGER, INTENT(IN)                              :: NSOIL\n    REAL,   INTENT(IN)                               ::     WTDDT\n    REAL,    INTENT(IN), DIMENSION(1:NSOIL)          :: ZSOIL,DZS\n    INTEGER, INTENT(IN), DIMENSION(ims:ime, jms:jme) :: ISLTYP, IVGTYP\n    REAL,    INTENT(IN), DIMENSION(ims:ime, jms:jme) :: FDEPTH, TOPO, RIVERBED, EQWTD, RIVERCOND, PEXP , AREA\n    REAL,    INTENT(INOUT), DIMENSION(ims:ime, jms:jme) :: WTD\n    REAL,     DIMENSION( ims:ime , 1:nsoil, jms:jme ), &\n         &    INTENT(INOUT)   ::                          SMOIS, &\n         &                                                 SH2O, &\n         &                                                 SMOISEQ\n    REAL,    INTENT(INOUT), DIMENSION(ims:ime, jms:jme) ::  &\n                                                           SMCWTDXY, &\n                                                           DEEPRECHXY, &\n                                                           RECHXY, &\n                                                           QSLATXY, &\n                                                           QRFSXY, &\n                                                           QSPRINGSXY\n! local\n    INTEGER  :: I,J,K,ITER,itf,jtf\n    REAL :: BEXP,SMCMAX,PSISAT,SMCWLT,DWSAT,DKSAT\n    REAL :: FRLIQ,SMCEQDEEP\n    REAL :: DELTAT,RCOND\n    REAL :: AA,BBB,CC,DD,DX,FUNC,DFUNC,DDZ,EXPON,SMC,FLUX\n    REAL, DIMENSION(1:NSOIL) :: SMCEQ\n    REAL,      DIMENSION( ims:ime, jms:jme )    :: QLAT, QRF\n    INTEGER,   DIMENSION( ims:ime, jms:jme )    :: LANDMASK !-1 for water (ice or no ice) and glacial areas, 1 for land where the LSM does its soil moisture calculations\n\n\n       itf=min0(ite,ide-1)\n       jtf=min0(jte,jde-1)\n\n!first compute lateral flow and flow to rivers to initialize deep soil moisture\n\n    DELTAT = WTDDT * 60. !timestep in seconds for this calculation\n\n    WHERE(IVGTYP.NE.ISWATER_TABLE.AND.IVGTYP.NE.ISICE_TABLE)\n         LANDMASK=1\n    ELSEWHERE\n         LANDMASK=-1\n    ENDWHERE\n\n!Calculate lateral flow\n\n    QLAT = 0.\nCALL LATERALFLOW(ISLTYP,WTD,QLAT,FDEPTH,TOPO,LANDMASK,DELTAT,AREA       &\n                        ,ids,ide,jds,jde,kds,kde                      &\n                        ,ims,ime,jms,jme,kms,kme                      &\n                        ,its,ite,jts,jte,kts,kte                      )\n\n\n!compute flux from grounwater to rivers in the cell\n\n    DO J=jts,jtf\n       DO I=its,itf\n          IF(LANDMASK(I,J).GT.0)THEN\n             IF(WTD(I,J) .GT. RIVERBED(I,J) .AND.  EQWTD(I,J) .GT. RIVERBED(I,J)) THEN\n               RCOND = RIVERCOND(I,J) * EXP(PEXP(I,J)*(WTD(I,J)-EQWTD(I,J)))\n             ELSE\n               RCOND = RIVERCOND(I,J)\n             ENDIF\n             QRF(I,J) = RCOND * (WTD(I,J)-RIVERBED(I,J)) * DELTAT/AREA(I,J)\n!for now, dont allow it to go from river to groundwater\n             QRF(I,J) = MAX(QRF(I,J),0.)\n          ELSE\n             QRF(I,J) = 0.\n          ENDIF\n       ENDDO\n    ENDDO\n\n!now compute eq. soil moisture, change soil moisture to be compatible with the water table and compute deep soil moisture\n\n       DO J = jts,jtf\n          DO I = its,itf\n             BEXP   =   BEXP_TABLE(ISLTYP(I,J))\n             SMCMAX = SMCMAX_TABLE(ISLTYP(I,J))\n             SMCWLT = SMCWLT_TABLE(ISLTYP(I,J))\n             IF(IVGTYP(I,J)==ISURBAN_TABLE)THEN\n                 SMCMAX = 0.45\n                 SMCWLT = 0.40\n             ENDIF\n             DWSAT  =   DWSAT_TABLE(ISLTYP(I,J))\n             DKSAT  =   DKSAT_TABLE(ISLTYP(I,J))\n             PSISAT = -PSISAT_TABLE(ISLTYP(I,J))\n           IF ( ( BEXP > 0.0 ) .AND. ( smcmax > 0.0 ) .AND. ( -psisat > 0.0 ) ) THEN\n             !initialize equilibrium soil moisture for water table diagnostic\n                    CALL EQSMOISTURE(NSOIL ,  ZSOIL , SMCMAX , SMCWLT ,DWSAT, DKSAT  ,BEXP  , & !in\n                                     SMCEQ                          )  !out\n\n             SMOISEQ (I,1:NSOIL,J) = SMCEQ (1:NSOIL)\n\n\n              !make sure that below the water table the layers are saturated and initialize the deep soil moisture\n             IF(WTD(I,J) < ZSOIL(NSOIL)-DZS(NSOIL)) THEN\n\n!initialize deep soil moisture so that the flux compensates qlat+qrf\n!use Newton-Raphson method to find soil moisture\n\n                         EXPON = 2. * BEXP + 3.\n                         DDZ = ZSOIL(NSOIL) - WTD(I,J)\n                         CC = PSISAT/DDZ\n                         FLUX = (QLAT(I,J)-QRF(I,J))/DELTAT\n\n                         SMC = 0.5 * SMCMAX\n\n                         DO ITER = 1, 100\n                           DD = (SMC+SMCMAX)/(2.*SMCMAX)\n                           AA = -DKSAT * DD  ** EXPON\n                           BBB = CC * ( (SMCMAX/SMC)**BEXP - 1. ) + 1.\n                           FUNC =  AA * BBB - FLUX\n                           DFUNC = -DKSAT * (EXPON/(2.*SMCMAX)) * DD ** (EXPON - 1.) * BBB &\n                                   + AA * CC * (-BEXP) * SMCMAX ** BEXP * SMC ** (-BEXP-1.)\n\n                           DX = FUNC/DFUNC\n                           SMC = SMC - DX\n                           IF ( ABS (DX) < 1.E-6)EXIT\n                         ENDDO\n\n                  SMCWTDXY(I,J) = MAX(SMC,1.E-4)\n\n             ELSEIF(WTD(I,J) < ZSOIL(NSOIL))THEN\n                  SMCEQDEEP = SMCMAX * ( PSISAT / ( PSISAT - DZS(NSOIL) ) ) ** (1./BEXP)\n!                  SMCEQDEEP = MAX(SMCEQDEEP,SMCWLT)\n                  SMCEQDEEP = MAX(SMCEQDEEP,1.E-4)\n                  SMCWTDXY(I,J) = SMCMAX * ( WTD(I,J) -  (ZSOIL(NSOIL)-DZS(NSOIL))) + &\n                                  SMCEQDEEP * (ZSOIL(NSOIL) - WTD(I,J))\n\n             ELSE !water table within the resolved layers\n                  SMCWTDXY(I,J) = SMCMAX\n                  DO K=NSOIL,2,-1\n                     IF(WTD(I,J) .GE. ZSOIL(K-1))THEN\n                          FRLIQ = SH2O(I,K,J) / SMOIS(I,K,J)\n                          SMOIS(I,K,J) = SMCMAX\n                          SH2O(I,K,J) = SMCMAX * FRLIQ\n                     ELSE\n                          IF(SMOIS(I,K,J).LT.SMCEQ(K))THEN\n                              WTD(I,J) = ZSOIL(K)\n                          ELSE\n                              WTD(I,J) = ( SMOIS(I,K,J)*DZS(K) - SMCEQ(K)*ZSOIL(K-1) + SMCMAX*ZSOIL(K) ) / &\n                                         (SMCMAX - SMCEQ(K))\n                          ENDIF\n                          EXIT\n                     ENDIF\n                  ENDDO\n             ENDIF\n            ELSE\n              SMOISEQ (I,1:NSOIL,J) = SMCMAX\n              SMCWTDXY(I,J) = SMCMAX\n              WTD(I,J) = 0.\n            ENDIF\n\n!zero out some arrays\n\n             DEEPRECHXY(I,J) = 0.\n             RECHXY(I,J) = 0.\n             QSLATXY(I,J) = 0.\n             QRFSXY(I,J) = 0.\n             QSPRINGSXY(I,J) = 0.\n\n          ENDDO\n       ENDDO\n\n\n\n\n    END  SUBROUTINE GROUNDWATER_INIT\n! ==================================================================================================\n! ----------------------------------------------------------------------\n  SUBROUTINE EQSMOISTURE(NSOIL  ,  ZSOIL , SMCMAX , SMCWLT, DWSAT , DKSAT ,BEXP , & !in\n                         SMCEQ                          )  !out\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  INTEGER,                         INTENT(IN) :: NSOIL !no. of soil layers\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: ZSOIL !depth of soil layer-bottom [m]\n  REAL,                            INTENT(IN) :: SMCMAX , SMCWLT, BEXP , DWSAT, DKSAT\n!output\n  REAL,  DIMENSION(      1:NSOIL), INTENT(OUT) :: SMCEQ  !equilibrium soil water  content [m3/m3]\n!local\n  INTEGER                                     :: K , ITER\n  REAL                                        :: DDZ , SMC, FUNC, DFUNC , AA, BB , EXPON, DX\n\n!gmmcompute equilibrium soil moisture content for the layer when wtd=zsoil(k)\n\n\n   DO K=1,NSOIL\n\n            IF ( K == 1 )THEN\n                DDZ = -ZSOIL(K+1) * 0.5\n            ELSEIF ( K < NSOIL ) THEN\n                DDZ = ( ZSOIL(K-1) - ZSOIL(K+1) ) * 0.5\n            ELSE\n                DDZ = ZSOIL(K-1) - ZSOIL(K)\n            ENDIF\n\n!use Newton-Raphson method to find eq soil moisture\n\n            EXPON = BEXP +1.\n            AA = DWSAT/DDZ\n            BB = DKSAT / SMCMAX ** EXPON\n\n            SMC = 0.5 * SMCMAX\n\n         DO ITER = 1, 100\n            FUNC = (SMC - SMCMAX) * AA +  BB * SMC ** EXPON\n            DFUNC = AA + BB * EXPON * SMC ** BEXP\n\n            DX = FUNC/DFUNC\n            SMC = SMC - DX\n            IF ( ABS (DX) < 1.E-6)EXIT\n         ENDDO\n\n!             SMCEQ(K) = MIN(MAX(SMC,SMCWLT),SMCMAX*0.99)\n             SMCEQ(K) = MIN(MAX(SMC,1.E-4),SMCMAX*0.99)\n   ENDDO\n\nEND  SUBROUTINE EQSMOISTURE\n!\n!------------------------------------------------------------------------------------------\n!------------------------------------------------------------------------------------------\n!\nEND MODULE module_sf_noahmpdrv\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/module_sf_noahmplsm.F",
    "content": "MODULE MODULE_SF_NOAHMPLSM\n\n  IMPLICIT NONE\n\n  public  :: noahmp_options\n  public  :: NOAHMP_SFLX\n\n  private :: ATM\n  private :: PHENOLOGY\n  private :: PRECIP_HEAT\n  private :: ENERGY\n  private ::       THERMOPROP\n  private ::               CSNOW\n  private ::               TDFCND\n  private ::       RADIATION\n  private ::               ALBEDO\n  private ::                         SNOW_AGE\n  private ::                         SNOWALB_BATS\n  private ::                         SNOWALB_CLASS\n  private ::                         GROUNDALB\n  private ::                         TWOSTREAM\n  private ::               SURRAD\n  private ::       VEGE_FLUX\n  private ::               SFCDIF1\n  private ::               SFCDIF2\n  private ::               STOMATA\n  private ::               CANRES\n  private ::               ESAT\n  private ::               RAGRB\n  private ::       BARE_FLUX\n  private ::       TSNOSOI\n  private ::               HRT\n  private ::               HSTEP\n  private ::                         ROSR12\n  private ::       PHASECHANGE\n  private ::               FRH2O\n\n  private :: WATER\n  private ::       CANWATER\n  private ::       SNOWWATER\n  private ::               SNOWFALL\n  private ::               COMBINE\n  private ::               DIVIDE\n  private ::                         COMBO\n  private ::               COMPACT\n  private ::               SNOWH2O\n  private ::       SOILWATER\n  private ::               ZWTEQ\n  private ::               INFIL\n  private ::               SRT\n  private ::                         WDFCND1\n  private ::                         WDFCND2\n  private ::               SSTEP\n  private ::       GROUNDWATER\n  private ::       SHALLOWWATERTABLE\n\n  private :: CARBON\n  private ::       CO2FLUX\n!  private ::       BVOCFLUX\n!  private ::       CH4FLUX\n\n  private :: ERROR\n\n! =====================================options for different schemes================================\n! **recommended\n\n  INTEGER :: DVEG     ! options for dynamic vegetation:\n                      !   1 -> off (use table LAI; use FVEG = SHDFAC from input)\n                      !   2 -> on  (together with OPT_CRS = 1)\n                      !   3 -> off (use table LAI; calculate FVEG)\n                      ! **4 -> off (use table LAI; use maximum vegetation fraction)\n                      ! **5 -> on  (use maximum vegetation fraction)\n                      !   6 -> on  (use FVEG = SHDFAC from input)\n                      !   7 -> off (use input LAI; use FVEG = SHDFAC from input)\n                      !   8 -> off (use input LAI; calculate FVEG)\n                      !   9 -> off (use input LAI; use maximum vegetation fraction)\n                      !  10 -> crop model on (use maximum vegetation fraction)\n\n  INTEGER :: OPT_CRS  ! options for canopy stomatal resistance\n                      ! **1 -> Ball-Berry\n\t\t      !   2 -> Jarvis\n\n  INTEGER :: OPT_BTR  ! options for soil moisture factor for stomatal resistance\n                      ! **1 -> Noah (soil moisture)\n                      !   2 -> CLM  (matric potential)\n                      !   3 -> SSiB (matric potential)\n\n  INTEGER :: OPT_RUN  ! options for runoff and groundwater\n                      ! **1 -> TOPMODEL with groundwater (Niu et al. 2007 JGR) ;\n                      !   2 -> TOPMODEL with an equilibrium water table (Niu et al. 2005 JGR) ;\n                      !   3 -> original surface and subsurface runoff (free drainage)\n                      !   4 -> BATS surface and subsurface runoff (free drainage)\n                      !   5 -> Miguez-Macho&Fan groundwater scheme (Miguez-Macho et al. 2007 JGR; Fan et al. 2007 JGR)\n\t\t      !          (needs further testing for public use)\n\n  INTEGER :: OPT_SFC  ! options for surface layer drag coeff (CH & CM)\n                      ! **1 -> M-O\n\t\t      ! **2 -> original Noah (Chen97)\n\t\t      ! **3 -> MYJ consistent; 4->YSU consistent. MB: removed in v3.7 for further testing\n\n  INTEGER :: OPT_FRZ  ! options for supercooled liquid water (or ice fraction)\n                      ! **1 -> no iteration (Niu and Yang, 2006 JHM)\n\t\t      !   2 -> Koren's iteration\n\n  INTEGER :: OPT_INF  ! options for frozen soil permeability\n                      ! **1 -> linear effects, more permeable (Niu and Yang, 2006, JHM)\n                      !   2 -> nonlinear effects, less permeable (old)\n\n  INTEGER :: OPT_RAD  ! options for radiation transfer\n                      !   1 -> modified two-stream (gap = F(solar angle, 3D structure ...)<1-FVEG)\n                      !   2 -> two-stream applied to grid-cell (gap = 0)\n                      ! **3 -> two-stream applied to vegetated fraction (gap=1-FVEG)\n\n  INTEGER :: OPT_ALB  ! options for ground snow surface albedo\n                      !   1 -> BATS\n\t\t      ! **2 -> CLASS\n\n  INTEGER :: OPT_SNF  ! options for partitioning  precipitation into rainfall & snowfall\n                      ! **1 -> Jordan (1991)\n\t\t      !   2 -> BATS: when SFCTMP<TFRZ+2.2\n\t\t      !   3 -> SFCTMP < TFRZ\n\t\t      !   4 -> Use WRF microphysics output\n\n  INTEGER :: OPT_TBOT ! options for lower boundary condition of soil temperature\n                      !   1 -> zero heat flux from bottom (ZBOT and TBOT not used)\n                      ! **2 -> TBOT at ZBOT (8m) read from a file (original Noah)\n\n  INTEGER :: OPT_STC  ! options for snow/soil temperature time scheme (only layer 1)\n                      ! **1 -> semi-implicit; flux top boundary condition\n\t\t      !   2 -> full implicit (original Noah); temperature top boundary condition\n                      !   3 -> same as 1, but FSNO for TS calculation (generally improves snow; v3.7)\n\n  INTEGER :: OPT_RSF  ! options for surface resistent to evaporation/sublimation\n                      ! **1 -> Sakaguchi and Zeng, 2009\n\t\t      !   2 -> Sellers (1992)\n                      !   3 -> adjusted Sellers to decrease RSURF for wet soil\n\t\t      !   4 -> option 1 for non-snow; rsurf = rsurf_snow for snow (set in MPTABLE); AD v3.8\n\n  INTEGER :: OPT_SOIL ! options for defining soil properties\n                      ! **1 -> use input dominant soil texture\n\t\t      !   2 -> use input soil texture that varies with depth\n                      !   3 -> use soil composition (sand, clay, orgm) and pedotransfer functions (OPT_PEDO)\n\t\t      !   4 -> use input soil properties (BEXP_3D, SMCMAX_3D, etc.)\n\n  INTEGER :: OPT_PEDO ! options for pedotransfer functions (used when OPT_SOIL = 3)\n                      ! **1 -> Saxton and Rawls (2006)\n\n  INTEGER :: OPT_CROP ! options for crop model\n                      ! **0 -> No crop model, will run default dynamic vegetation\n                      !   1 -> Liu, et al. 2016\n\n  INTEGER :: OPT_IMPERV  ! options for imperviousness infiltration adjustment\n                      !   0 -> no imperviousness adjustment\n                      !   1 -> use total imperviousness\n                      !   2 -> use effective imperviousness from Alley & Veenhuis\n                      ! **9 -> older model behavior (urban soil parameter adjustment\n                      !        and mixed runoff adjustment depending on runoff scheme)\n\n!------------------------------------------------------------------------------------------!\n! Physical Constants:                                                                      !\n!------------------------------------------------------------------------------------------!\n\n  REAL, PARAMETER :: GRAV   = 9.80616   !acceleration due to gravity (m/s2)\n  REAL, PARAMETER :: SB     = 5.67E-08  !Stefan-Boltzmann constant (w/m2/k4)\n  REAL, PARAMETER :: VKC    = 0.40      !von Karman constant\n  REAL, PARAMETER :: TFRZ   = 273.16    !freezing/melting point (k)\n  REAL, PARAMETER :: HSUB   = 2.8440E06 !latent heat of sublimation (j/kg)\n  REAL, PARAMETER :: HVAP   = 2.5104E06 !latent heat of vaporization (j/kg)\n  REAL, PARAMETER :: HFUS   = 0.3336E06 !latent heat of fusion (j/kg)\n  REAL, PARAMETER :: CWAT   = 4.188E06  !specific heat capacity of water (j/m3/k)\n  REAL, PARAMETER :: CICE   = 2.094E06  !specific heat capacity of ice (j/m3/k)\n  REAL, PARAMETER :: CPAIR  = 1004.64   !heat capacity dry air at const pres (j/kg/k)\n  REAL, PARAMETER :: TKWAT  = 0.6       !thermal conductivity of water (w/m/k)\n  REAL, PARAMETER :: TKICE  = 2.2       !thermal conductivity of ice (w/m/k)\n  REAL, PARAMETER :: TKAIR  = 0.023     !thermal conductivity of air (w/m/k) (not used MB: 20140718)\n  REAL, PARAMETER :: RAIR   = 287.04    !gas constant for dry air (j/kg/k)\n  REAL, PARAMETER :: RW     = 461.269   !gas constant for  water vapor (j/kg/k)\n  REAL, PARAMETER :: DENH2O = 1000.     !density of water (kg/m3)\n  REAL, PARAMETER :: DENICE = 917.      !density of ice (kg/m3)\n\n  INTEGER, PRIVATE, PARAMETER :: MBAND = 2\n  INTEGER, PRIVATE, PARAMETER :: NSOIL = 4\n  INTEGER, PRIVATE, PARAMETER :: NSTAGE = 8\n\n  TYPE noahmp_parameters ! define a NoahMP parameters type\n\n!------------------------------------------------------------------------------------------!\n! From the veg section of MPTABLE.TBL\n!------------------------------------------------------------------------------------------!\n\n    LOGICAL :: URBAN_FLAG\n    INTEGER :: ISWATER\n    INTEGER :: ISBARREN\n    INTEGER :: ISICE\n    INTEGER :: ISCROP\n    INTEGER :: EBLFOREST\n\n    REAL :: CH2OP              !maximum intercepted h2o per unit lai+sai (mm)\n    REAL :: DLEAF              !characteristic leaf dimension (m)\n    REAL :: Z0MVT              !momentum roughness length (m)\n    REAL :: HVT                !top of canopy (m)\n    REAL :: HVB                !bottom of canopy (m)\n    REAL :: DEN                !tree density (no. of trunks per m2)\n    REAL :: RC                 !tree crown radius (m)\n    REAL :: MFSNO              !snowmelt m parameter ()\n    REAL :: SAIM(12)           !monthly stem area index, one-sided\n    REAL :: LAIM(12)           !monthly leaf area index, one-sided\n    REAL :: SLA                !single-side leaf area per Kg [m2/kg]\n    REAL :: DILEFC             !coeficient for leaf stress death [1/s]\n    REAL :: DILEFW             !coeficient for leaf stress death [1/s]\n    REAL :: FRAGR              !fraction of growth respiration  !original was 0.3\n    REAL :: LTOVRC             !leaf turnover [1/s]\n\n    REAL :: C3PSN              !photosynthetic pathway: 0. = c4, 1. = c3\n    REAL :: KC25               !co2 michaelis-menten constant at 25c (pa)\n    REAL :: AKC                !q10 for kc25\n    REAL :: KO25               !o2 michaelis-menten constant at 25c (pa)\n    REAL :: AKO                !q10 for ko25\n    REAL :: VCMX25             !maximum rate of carboxylation at 25c (umol co2/m**2/s)\n    REAL :: AVCMX              !q10 for vcmx25\n    REAL :: BP                 !minimum leaf conductance (umol/m**2/s)\n    REAL :: MP                 !slope of conductance-to-photosynthesis relationship\n    REAL :: QE25               !quantum efficiency at 25c (umol co2 / umol photon)\n    REAL :: AQE                !q10 for qe25\n    REAL :: RMF25              !leaf maintenance respiration at 25c (umol co2/m**2/s)\n    REAL :: RMS25              !stem maintenance respiration at 25c (umol co2/kg bio/s)\n    REAL :: RMR25              !root maintenance respiration at 25c (umol co2/kg bio/s)\n    REAL :: ARM                !q10 for maintenance respiration\n    REAL :: FOLNMX             !foliage nitrogen concentration when f(n)=1 (%)\n    REAL :: TMIN               !minimum temperature for photosynthesis (k)\n\n    REAL :: XL                 !leaf/stem orientation index\n    REAL :: RHOL(MBAND)        !leaf reflectance: 1=vis, 2=nir\n    REAL :: RHOS(MBAND)        !stem reflectance: 1=vis, 2=nir\n    REAL :: TAUL(MBAND)        !leaf transmittance: 1=vis, 2=nir\n    REAL :: TAUS(MBAND)        !stem transmittance: 1=vis, 2=nir\n\n    REAL :: MRP                !microbial respiration parameter (umol co2 /kg c/ s)\n    REAL :: CWPVT              !empirical canopy wind parameter\n\n    REAL :: WRRAT              !wood to non-wood ratio\n    REAL :: WDPOOL             !wood pool (switch 1 or 0) depending on woody or not [-]\n    REAL :: TDLEF              !characteristic T for leaf freezing [K]\n\n  INTEGER :: NROOT              !number of soil layers with root present\n     REAL :: RGL                !Parameter used in radiation stress function\n     REAL :: RSMIN              !Minimum stomatal resistance [s m-1]\n     REAL :: HS                 !Parameter used in vapor pressure deficit function\n     REAL :: TOPT               !Optimum transpiration air temperature [K]\n     REAL :: RSMAX              !Maximal stomatal resistance [s m-1]\n\n     REAL :: SLAREA\n     REAL :: EPS(5)\n\n!------------------------------------------------------------------------------------------!\n! From the rad section of MPTABLE.TBL\n!------------------------------------------------------------------------------------------!\n\n     REAL :: ALBSAT(MBAND)       !saturated soil albedos: 1=vis, 2=nir\n     REAL :: ALBDRY(MBAND)       !dry soil albedos: 1=vis, 2=nir\n     REAL :: ALBICE(MBAND)       !albedo land ice: 1=vis, 2=nir\n     REAL :: ALBLAK(MBAND)       !albedo frozen lakes: 1=vis, 2=nir\n     REAL :: OMEGAS(MBAND)       !two-stream parameter omega for snow\n     REAL :: BETADS              !two-stream parameter betad for snow\n     REAL :: BETAIS              !two-stream parameter betad for snow\n     REAL :: EG(2)               !emissivity\n\n!------------------------------------------------------------------------------------------!\n! From the globals section of MPTABLE.TBL\n!------------------------------------------------------------------------------------------!\n\n     REAL :: CO2          !co2 partial pressure\n     REAL :: O2           !o2 partial pressure\n     REAL :: TIMEAN       !gridcell mean topgraphic index (global mean)\n     REAL :: FSATMX       !maximum surface saturated fraction (global mean)\n     REAL :: Z0SNO        !snow surface roughness length (m) (0.002)\n     REAL :: SSI          !liquid water holding capacity for snowpack (m3/m3)\n     REAL :: SNOW_RET_FAC !snowpack water release timescale factor (1/s)\n     REAL :: SWEMX        !new snow mass to fully cover old snow (mm)\n     REAL :: TAU0         !tau0 from Yang97 eqn. 10a\n     REAL :: GRAIN_GROWTH !growth from vapor diffusion Yang97 eqn. 10b\n     REAL :: EXTRA_GROWTH !extra growth near freezing Yang97 eqn. 10c\n     REAL :: DIRT_SOOT    !dirt and soot term Yang97 eqn. 10d\n     REAL :: BATS_COSZ    !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n     REAL :: BATS_VIS_NEW !new snow visible albedo\n     REAL :: BATS_NIR_NEW !new snow NIR albedo\n     REAL :: BATS_VIS_AGE !age factor for diffuse visible snow albedo Yang97 eqn. 17\n     REAL :: BATS_NIR_AGE !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n     REAL :: BATS_VIS_DIR !cosz factor for direct visible snow albedo Yang97 eqn. 15\n     REAL :: BATS_NIR_DIR !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n     REAL :: RSURF_SNOW   !surface resistance for snow(s/m)\n     REAL :: RSURF_EXP    !exponent in the shape parameter for soil resistance option 1\n     REAL :: IMPERV       !impervious fraction\n     REAL :: SCAMAX       !maximum fractional snow covered area (0.0-1.0)\n     REAL :: SWE_LIMIT    !maximum SWE limit (mm)\n\n!------------------------------------------------------------------------------------------!\n! From the crop section of MPTABLE.TBL\n!------------------------------------------------------------------------------------------!\n\n  INTEGER :: PLTDAY           ! Planting date\n  INTEGER :: HSDAY            ! Harvest date\n     REAL :: PLANTPOP         ! Plant density [per ha] - used?\n     REAL :: IRRI             ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n     REAL :: GDDTBASE         ! Base temperature for GDD accumulation [C]\n     REAL :: GDDTCUT          ! Upper temperature for GDD accumulation [C]\n     REAL :: GDDS1            ! GDD from seeding to emergence\n     REAL :: GDDS2            ! GDD from seeding to initial vegetative\n     REAL :: GDDS3            ! GDD from seeding to post vegetative\n     REAL :: GDDS4            ! GDD from seeding to intial reproductive\n     REAL :: GDDS5            ! GDD from seeding to pysical maturity\n  INTEGER :: C3C4             ! photosynthetic pathway:  1 = c3 2 = c4\n     REAL :: AREF             ! reference maximum CO2 assimulation rate\n     REAL :: PSNRF            ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\n     REAL :: I2PAR            ! Fraction of incoming solar radiation to photosynthetically active radiation\n     REAL :: TASSIM0          ! Minimum temperature for CO2 assimulation [C]\n     REAL :: TASSIM1          ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\n     REAL :: TASSIM2          ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\n     REAL :: K                ! light extinction coefficient\n     REAL :: EPSI             ! initial light use efficiency\n     REAL :: Q10MR            ! q10 for maintainance respiration\n     REAL :: FOLN_MX          ! foliage nitrogen concentration when f(n)=1 (%)\n     REAL :: LEFREEZ          ! characteristic T for leaf freezing [K]\n     REAL :: DILE_FC(NSTAGE)  ! coeficient for temperature leaf stress death [1/s]\n     REAL :: DILE_FW(NSTAGE)  ! coeficient for water leaf stress death [1/s]\n     REAL :: FRA_GR           ! fraction of growth respiration\n     REAL :: LF_OVRC(NSTAGE)  ! fraction of leaf turnover  [1/s]\n     REAL :: ST_OVRC(NSTAGE)  ! fraction of stem turnover  [1/s]\n     REAL :: RT_OVRC(NSTAGE)  ! fraction of root tunrover  [1/s]\n     REAL :: LFMR25           ! leaf maintenance respiration at 25C [umol CO2/m**2  /s]\n     REAL :: STMR25           ! stem maintenance respiration at 25C [umol CO2/kg bio/s]\n     REAL :: RTMR25           ! root maintenance respiration at 25C [umol CO2/kg bio/s]\n     REAL :: GRAINMR25        ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n     REAL :: LFPT(NSTAGE)     ! fraction of carbohydrate flux to leaf\n     REAL :: STPT(NSTAGE)     ! fraction of carbohydrate flux to stem\n     REAL :: RTPT(NSTAGE)     ! fraction of carbohydrate flux to root\n     REAL :: GRAINPT(NSTAGE)  ! fraction of carbohydrate flux to grain\n     REAL :: BIO2LAI          ! leaf are per living leaf biomass [m^2/kg]\n\n!------------------------------------------------------------------------------------------!\n! From the SOILPARM.TBL tables, as functions of soil category.\n!------------------------------------------------------------------------------------------!\n     REAL :: BEXP(NSOIL)   !B parameter\n     REAL :: SMCDRY(NSOIL) !dry soil moisture threshold where direct evap from top\n                           !layer ends (volumetric) (not used MB: 20140718)\n     REAL :: SMCWLT(NSOIL) !wilting point soil moisture (volumetric)\n     REAL :: SMCREF(NSOIL) !reference soil moisture (field capacity) (volumetric)\n     REAL :: SMCMAX(NSOIL) !porosity, saturated value of soil moisture (volumetric)\n     REAL :: PSISAT(NSOIL) !saturated soil matric potential\n     REAL :: DKSAT(NSOIL)  !saturated soil hydraulic conductivity\n     REAL :: DWSAT(NSOIL)  !saturated soil hydraulic diffusivity\n     REAL :: QUARTZ(NSOIL) !soil quartz content\n     REAL :: F1            !soil thermal diffusivity/conductivity coef (not used MB: 20140718)\n     REAL :: AXAJ          !Xinanjiang: Tension water distribution inflection parameter [-]\n     REAL :: BXAJ          !Xinanjiang: Tension water distribution shape parameter [-]\n     REAL :: XXAJ          !Xinanjiang: Free water distribution shape parameter [-]\n!------------------------------------------------------------------------------------------!\n! From the GENPARM.TBL file\n!------------------------------------------------------------------------------------------!\n     REAL :: SLOPE       !slope index (0 - 1)\n     REAL :: CSOIL       !vol. soil heat capacity [j/m3/K]\n     REAL :: ZBOT        !Depth (m) of lower boundary soil temperature\n     REAL :: CZIL        !Calculate roughness length of heat\n     REAL :: REFDK\n     REAL :: REFKDT\n\n     REAL :: KDT         !used in compute maximum infiltration rate (in INFIL)\n     REAL :: FRZX        !used in compute maximum infiltration rate (in INFIL)\n\n  END TYPE noahmp_parameters\n\ncontains\n!\n!== begin noahmp_sflx ==============================================================================\n\n  SUBROUTINE NOAHMP_SFLX (parameters, &\n                   ILOC    , JLOC    , LAT     , YEARLEN , JULIAN  , COSZ    , & ! IN : Time/Space-related\n                   DT      , DX      , DZ8W    , NSOIL   , ZSOIL   , NSNOW   , & ! IN : Model configuration\n                   SHDFAC  , SHDMAX  , VEGTYP  , ICE     , IST     , CROPTYPE, & ! IN : Vegetation/Soil characteristics\n                   SMCEQ   ,                                                   & ! IN : Vegetation/Soil characteristics\n                   SFCTMP  , SFCPRS  , PSFC    , UU      , VV      , Q2      , & ! IN : Forcing\n                   QC      , SOLDN   , LWDN    ,                               & ! IN : Forcing\n\t           PRCPCONV, PRCPNONC, PRCPSHCV, PRCPSNOW, PRCPGRPL, PRCPHAIL, & ! IN : Forcing\n                   TBOT    , CO2AIR  , O2AIR   , FOLN    , FICEOLD , ZLVL    , & ! IN : Forcing\n                   ALBOLD  , SNEQVO  ,                                         & ! IN/OUT :\n                   STC     , SH2O    , SMC     , TAH     , EAH     , FWET    , & ! IN/OUT :\n                   CANLIQ  , CANICE  , TV      , TG      , QSFC, QSNOW, QRAIN, & ! IN/OUT :\n                   ISNOW   , ZSNSO   , SNOWH   , SNEQV   , SNICE   , SNLIQ   , & ! IN/OUT :\n                   ZWT     , WA      , WT      , WSLAKE  , LFMASS  , RTMASS  , & ! IN/OUT :\n                   STMASS  , WOOD    , STBLCP  , FASTCP  , LAI     , SAI     , & ! IN/OUT :\n                   CM      , CH      , TAUSS   ,                               & ! IN/OUT :\n                   GRAIN   , GDD     , PGS     ,                               & ! IN/OUT\n                   SMCWTD  ,DEEPRECH , RECH    ,                               & ! IN/OUT :\n\t\t   Z0WRF   , &\n                   FSA     , FSR     , FIRA    , FSH     , SSOIL   , FCEV    , & ! OUT :\n                   FGEV    , FCTR    , ECAN    , ETRAN   , EDIR    , TRAD    , & ! OUT :\n                   TGB     , TGV     , T2MV    , T2MB    , Q2V     , Q2B     , & ! OUT :\n                   RUNSRF  , RUNSUB  , APAR    , PSN     , SAV     , SAG     , & ! OUT :\n                   FSNO    , NEE     , GPP     , NPP     , FVEG    , ALBEDO  , & ! OUT :\n                   QSNBOT  , PONDING , PONDING1, PONDING2, RSSUN   , RSSHA   , & ! OUT :\n\t\t   ALBSND  , ALBSNI  ,                                         & ! OUT :\n                   BGAP    , WGAP    , CHV     , CHB     , EMISSI  ,           & ! OUT :\n\t\t   SHG     , SHC     , SHB     , EVG     , EVB     , GHV     , & ! OUT :\n\t\t   GHB     , IRG     , IRC     , IRB     , TR      , EVC     , & ! OUT :\n\t\t   CHLEAF  , CHUC    , CHV2    , CHB2    , FPICE   , PAHV    , &\n                   PAHG    , PAHB    , PAH     , LAISUN  , LAISHA  , RB        & ! OUT\n#ifdef WRF_HYDRO\n                   ,SFCHEADRT                                                  & ! IN/OUT :\n#endif\n                   )\n\n! --------------------------------------------------------------------------------------------------\n! Initial code: Guo-Yue Niu, Oct. 2007\n! --------------------------------------------------------------------------------------------------\n\n  implicit none\n! --------------------------------------------------------------------------------------------------\n! input\n  type (noahmp_parameters), INTENT(IN) :: parameters\n\n  INTEGER                        , INTENT(IN)    :: ICE    !ice (ice = 1)\n  INTEGER                        , INTENT(IN)    :: IST    !surface type 1->soil; 2->lake\n  INTEGER                        , INTENT(IN)    :: VEGTYP !vegetation type\n  INTEGER                        , INTENT(IN)    :: CROPTYPE !crop type\n  INTEGER                        , INTENT(IN)    :: NSNOW  !maximum no. of snow layers\n  INTEGER                        , INTENT(IN)    :: NSOIL  !no. of soil layers\n  INTEGER                        , INTENT(IN)    :: ILOC   !grid index\n  INTEGER                        , INTENT(IN)    :: JLOC   !grid index\n  REAL                           , INTENT(IN)    :: DT     !time step [sec]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: ZSOIL  !layer-bottom depth from soil surf (m)\n  REAL                           , INTENT(IN)    :: Q2     !mixing ratio (kg/kg) lowest model layer\n  REAL                           , INTENT(IN)    :: SFCTMP !surface air temperature [K]\n  REAL                           , INTENT(IN)    :: UU     !wind speed in eastward dir (m/s)\n  REAL                           , INTENT(IN)    :: VV     !wind speed in northward dir (m/s)\n  REAL                           , INTENT(IN)    :: SOLDN  !downward shortwave radiation (w/m2)\n  REAL                           , INTENT(IN)    :: LWDN   !downward longwave radiation (w/m2)\n  REAL                           , INTENT(IN)    :: SFCPRS !pressure (pa)\n  REAL                           , INTENT(INOUT) :: ZLVL   !reference height (m)\n  REAL                           , INTENT(IN)    :: COSZ   !cosine solar zenith angle [0-1]\n  REAL                           , INTENT(IN)    :: TBOT   !bottom condition for soil temp. [K]\n  REAL                           , INTENT(IN)    :: FOLN   !foliage nitrogen (%) [1-saturated]\n  REAL                           , INTENT(IN)    :: SHDFAC !green vegetation fraction [0.0-1.0]\n  INTEGER                        , INTENT(IN)    :: YEARLEN!Number of days in the particular year.\n  REAL                           , INTENT(IN)    :: JULIAN !Julian day of year (floating point)\n  REAL                           , INTENT(IN)    :: LAT    !latitude (radians)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: FICEOLD!ice fraction at last timestep\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: SMCEQ  !equilibrium soil water  content [m3/m3]\n  REAL                           , INTENT(IN)    :: PRCPCONV ! convective precipitation entering  [mm/s]    ! MB/AN : v3.7\n  REAL                           , INTENT(IN)    :: PRCPNONC ! non-convective precipitation entering [mm/s] ! MB/AN : v3.7\n  REAL                           , INTENT(IN)    :: PRCPSHCV ! shallow convective precip entering  [mm/s]   ! MB/AN : v3.7\n  REAL                           , INTENT(IN)    :: PRCPSNOW ! snow entering land model [mm/s]              ! MB/AN : v3.7\n  REAL                           , INTENT(IN)    :: PRCPGRPL ! graupel entering land model [mm/s]           ! MB/AN : v3.7\n  REAL                           , INTENT(IN)    :: PRCPHAIL ! hail entering land model [mm/s]              ! MB/AN : v3.7\n\n!jref:start; in\n  REAL                           , INTENT(IN)    :: QC     !cloud water mixing ratio\n  REAL                           , INTENT(INOUT)    :: QSFC   !mixing ratio at lowest model layer\n  REAL                           , INTENT(IN)    :: PSFC   !pressure at lowest model layer\n  REAL                           , INTENT(IN)    :: DZ8W   !thickness of lowest layer\n  REAL                           , INTENT(IN)    :: DX\n  REAL                           , INTENT(IN)    :: SHDMAX  !yearly max vegetation fraction\n!jref:end\n\n#ifdef WRF_HYDRO\n  REAL                           , INTENT(INOUT)    :: sfcheadrt\n#endif\n\n! input/output : need arbitary intial values\n  REAL                           , INTENT(INOUT) :: QSNOW  !snowfall [mm/s]\n  REAL                           , INTENT(INOUT) :: QRAIN  !rainfall [mm/s]\n  REAL                           , INTENT(INOUT) :: FWET   !wetted or snowed fraction of canopy (-)\n  REAL                           , INTENT(INOUT) :: SNEQVO !snow mass at last time step (mm)\n  REAL                           , INTENT(INOUT) :: EAH    !canopy air vapor pressure (pa)\n  REAL                           , INTENT(INOUT) :: TAH    !canopy air tmeperature (k)\n  REAL                           , INTENT(INOUT) :: ALBOLD !snow albedo at last time step (CLASS type)\n  REAL                           , INTENT(INOUT) :: CM     !momentum drag coefficient\n  REAL                           , INTENT(INOUT) :: CH     !sensible heat exchange coefficient\n  REAL                           , INTENT(INOUT) :: TAUSS  !non-dimensional snow age\n\n! prognostic variables\n  INTEGER                        , INTENT(INOUT) :: ISNOW  !actual no. of snow layers [-]\n  REAL                           , INTENT(INOUT) :: CANLIQ !intercepted liquid water (mm)\n  REAL                           , INTENT(INOUT) :: CANICE !intercepted ice mass (mm)\n  REAL                           , INTENT(INOUT) :: SNEQV  !snow water eqv. [mm]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SMC    !soil moisture (ice + liq.) [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: ZSNSO  !layer-bottom depth from snow surf [m]\n  REAL                           , INTENT(INOUT) :: SNOWH  !snow height [m]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE  !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ  !snow layer liquid water [mm]\n  REAL                           , INTENT(INOUT) :: TV     !vegetation temperature (k)\n  REAL                           , INTENT(INOUT) :: TG     !ground temperature (k)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow/soil temperature [k]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O   !liquid soil moisture [m3/m3]\n  REAL                           , INTENT(INOUT) :: ZWT    !depth to water table [m]\n  REAL                           , INTENT(INOUT) :: WA     !water storage in aquifer [mm]\n  REAL                           , INTENT(INOUT) :: WT     !water in aquifer&saturated soil [mm]\n  REAL                           , INTENT(INOUT) :: WSLAKE !lake water storage (can be neg.) (mm)\n  REAL,                            INTENT(INOUT) :: SMCWTD !soil water content between bottom of the soil and water table [m3/m3]\n  REAL,                            INTENT(INOUT) :: DEEPRECH !recharge to or from the water table when deep [m]\n  REAL,                            INTENT(INOUT) :: RECH !recharge to or from the water table when shallow [m] (diagnostic)\n\n! output\n  REAL                           , INTENT(OUT)   :: Z0WRF  !combined z0 sent to coupled model\n  REAL                           , INTENT(OUT)   :: FSA    !total absorbed solar radiation (w/m2)\n  REAL                           , INTENT(OUT)   :: FSR    !total reflected solar radiation (w/m2)\n  REAL                           , INTENT(OUT)   :: FIRA   !total net LW rad (w/m2)  [+ to atm]\n  REAL                           , INTENT(OUT)   :: FSH    !total sensible heat (w/m2) [+ to atm]\n  REAL                           , INTENT(OUT)   :: FCEV   !canopy evap heat (w/m2) [+ to atm]\n  REAL                           , INTENT(OUT)   :: FGEV   !ground evap heat (w/m2) [+ to atm]\n  REAL                           , INTENT(OUT)   :: FCTR   !transpiration heat (w/m2) [+ to atm]\n  REAL                           , INTENT(OUT)   :: SSOIL  !ground heat flux (w/m2)   [+ to soil]\n  REAL                           , INTENT(OUT)   :: TRAD   !surface radiative temperature (k)\n  REAL                                           :: TS     !surface temperature (k)\n  REAL                           , INTENT(OUT)   :: ECAN   !evaporation of intercepted water (mm/s)\n  REAL                           , INTENT(OUT)   :: ETRAN  !transpiration rate (mm/s)\n  REAL                           , INTENT(OUT)   :: EDIR   !soil surface evaporation rate (mm/s]\n  REAL                           , INTENT(OUT)   :: RUNSRF !surface runoff [mm/s]\n  REAL                           , INTENT(OUT)   :: RUNSUB !baseflow (saturation excess) [mm/s]\n  REAL                           , INTENT(OUT)   :: PSN    !total photosynthesis (umol co2/m2/s) [+]\n  REAL                           , INTENT(OUT)   :: APAR   !photosyn active energy by canopy (w/m2)\n  REAL                           , INTENT(OUT)   :: SAV    !solar rad absorbed by veg. (w/m2)\n  REAL                           , INTENT(OUT)   :: SAG    !solar rad absorbed by ground (w/m2)\n  REAL                           , INTENT(OUT)   :: FSNO   !snow cover fraction on the ground (-)\n  REAL                           , INTENT(OUT)   :: FVEG   !green vegetation fraction [0.0-1.0]\n  REAL                           , INTENT(OUT)   :: ALBEDO !surface albedo [-]\n  REAL                                           :: ERRWAT !water error [kg m{-2}]\n  REAL                           , INTENT(OUT)   :: QSNBOT !snowmelt out bottom of pack [mm/s]\n  REAL                           , INTENT(OUT)   :: PONDING!surface ponding [mm]\n  REAL                           , INTENT(OUT)   :: PONDING1!surface ponding [mm]\n  REAL                           , INTENT(OUT)   :: PONDING2!surface ponding [mm]\n  REAL                           , INTENT(OUT)   :: RB        ! leaf boundary layer resistance (s/m)\n  REAL                           , INTENT(OUT)   :: LAISUN    ! sunlit leaf area index (m2/m2)\n  REAL                           , INTENT(OUT)   :: LAISHA    ! shaded leaf area index (m2/m2)\n\n!jref:start; output\n  REAL                           , INTENT(OUT)     :: T2MV   !2-m air temperature over vegetated part [k]\n  REAL                           , INTENT(OUT)     :: T2MB   !2-m air temperature over bare ground part [k]\n  REAL, INTENT(OUT) :: RSSUN        !sunlit leaf stomatal resistance (s/m)\n  REAL, INTENT(OUT) :: RSSHA        !shaded leaf stomatal resistance (s/m)\n  REAL, INTENT(OUT) :: BGAP\n  REAL, INTENT(OUT) :: WGAP\n  REAL, DIMENSION(1:2)              , INTENT(OUT)   :: ALBSND   !snow albedo (direct)\n  REAL, DIMENSION(1:2)              , INTENT(OUT)   :: ALBSNI   !snow albedo (diffuse)\n  REAL, INTENT(OUT) :: TGV\n  REAL, INTENT(OUT) :: TGB\n  REAL              :: Q1\n  REAL, INTENT(OUT) :: EMISSI\n!jref:end\n\n! local\n  INTEGER                                        :: IZ     !do-loop index\n  INTEGER, DIMENSION(-NSNOW+1:NSOIL)             :: IMELT  !phase change index [1-melt; 2-freeze]\n  REAL                                           :: CMC    !intercepted water (CANICE+CANLIQ) (mm)\n  REAL                                           :: TAUX   !wind stress: e-w (n/m2)\n  REAL                                           :: TAUY   !wind stress: n-s (n/m2)\n  REAL                                           :: RHOAIR !density air (kg/m3)\n!  REAL, DIMENSION(       1:    5)                :: VOCFLX !voc fluxes [ug C m-2 h-1]\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                :: DZSNSO !snow/soil layer thickness [m]\n  REAL                                           :: THAIR  !potential temperature (k)\n  REAL                                           :: QAIR   !specific humidity (kg/kg) (q2/(1+q2))\n  REAL                                           :: EAIR   !vapor pressure air (pa)\n  REAL, DIMENSION(       1:    2)                :: SOLAD  !incoming direct solar rad (w/m2)\n  REAL, DIMENSION(       1:    2)                :: SOLAI  !incoming diffuse solar rad (w/m2)\n  REAL                                           :: QPRECC !convective precipitation (mm/s)\n  REAL                                           :: QPRECL !large-scale precipitation (mm/s)\n  REAL                                           :: IGS    !growing season index (0=off, 1=on)\n  REAL                                           :: ELAI   !leaf area index, after burying by snow\n  REAL                                           :: ESAI   !stem area index, after burying by snow\n  REAL                                           :: BEVAP  !soil water evaporation factor (0 - 1)\n  REAL, DIMENSION(       1:NSOIL)                :: BTRANI !Soil water transpiration factor (0 - 1)\n  REAL                                           :: BTRAN  !soil water transpiration factor (0 - 1)\n  REAL                                           :: QIN    !groundwater recharge [mm/s]\n  REAL                                           :: QDIS   !groundwater discharge [mm/s]\n  REAL, DIMENSION(       1:NSOIL)                :: SICE   !soil ice content (m3/m3)\n  REAL, DIMENSION(-NSNOW+1:    0)                :: SNICEV !partial volume ice of snow [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0)                :: SNLIQV !partial volume liq of snow [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0)                :: EPORE  !effective porosity [m3/m3]\n  REAL                                           :: TOTSC  !total soil carbon (g/m2)\n  REAL                                           :: TOTLB  !total living carbon (g/m2)\n  REAL                                           :: T2M    !2-meter air temperature (k)\n  REAL                                           :: QDEW   !ground surface dew rate [mm/s]\n  REAL                                           :: QVAP   !ground surface evap. rate [mm/s]\n  REAL                                           :: LATHEA !latent heat [j/kg]\n  REAL                                           :: SWDOWN !downward solar [w/m2]\n  REAL                                           :: QMELT  !snowmelt [mm/s]\n  REAL                                           :: BEG_WB !water storage at begin of a step [mm]\n  REAL,INTENT(OUT)                                              :: IRC    !canopy net LW rad. [w/m2] [+ to atm]\n  REAL,INTENT(OUT)                                              :: IRG    !ground net LW rad. [w/m2] [+ to atm]\n  REAL,INTENT(OUT)                                              :: SHC    !canopy sen. heat [w/m2]   [+ to atm]\n  REAL,INTENT(OUT)                                              :: SHG    !ground sen. heat [w/m2]   [+ to atm]\n  REAL,INTENT(OUT)                                              :: EVG    !ground evap. heat [w/m2]  [+ to atm]\n  REAL,INTENT(OUT)                                              :: GHV    !ground heat flux [w/m2]  [+ to soil]\n  REAL,INTENT(OUT)                                              :: IRB    !net longwave rad. [w/m2] [+ to atm]\n  REAL,INTENT(OUT)                                              :: SHB    !sensible heat [w/m2]     [+ to atm]\n  REAL,INTENT(OUT)                                              :: EVB    !evaporation heat [w/m2]  [+ to atm]\n  REAL,INTENT(OUT)                                              :: GHB    !ground heat flux [w/m2] [+ to soil]\n  REAL,INTENT(OUT)                                              :: EVC    !canopy evap. heat [w/m2]  [+ to atm]\n  REAL,INTENT(OUT)                                              :: TR     !transpiration heat [w/m2] [+ to atm]\n  REAL, INTENT(OUT)   :: FPICE   !snow fraction in precipitation\n  REAL, INTENT(OUT)   :: PAHV    !precipitation advected heat - vegetation net (W/m2)\n  REAL, INTENT(OUT)   :: PAHG    !precipitation advected heat - under canopy net (W/m2)\n  REAL, INTENT(OUT)   :: PAHB    !precipitation advected heat - bare ground net (W/m2)\n  REAL, INTENT(OUT)                                           :: PAH     !precipitation advected heat - total (W/m2)\n\n!jref:start\n  REAL                                           :: FSRV\n  REAL                                           :: FSRG\n  REAL,INTENT(OUT)                               :: Q2V\n  REAL,INTENT(OUT)                               :: Q2B\n  REAL :: Q2E\n  REAL :: QFX\n  REAL,INTENT(OUT)                               :: CHV    !sensible heat exchange coefficient over vegetated fraction\n  REAL,INTENT(OUT)                               :: CHB    !sensible heat exchange coefficient over bare-ground\n  REAL,INTENT(OUT)                               :: CHLEAF !leaf exchange coefficient\n  REAL,INTENT(OUT)                               :: CHUC   !under canopy exchange coefficient\n  REAL,INTENT(OUT)                               :: CHV2    !sensible heat exchange coefficient over vegetated fraction\n  REAL,INTENT(OUT)                               :: CHB2    !sensible heat exchange coefficient over bare-ground\n!jref:end\n\n! carbon\n! inputs\n  REAL                           , INTENT(IN)    :: CO2AIR !atmospheric co2 concentration (pa)\n  REAL                           , INTENT(IN)    :: O2AIR  !atmospheric o2 concentration (pa)\n\n! inputs and outputs : prognostic variables\n  REAL                        , INTENT(INOUT)    :: LFMASS !leaf mass [g/m2]\n  REAL                        , INTENT(INOUT)    :: RTMASS !mass of fine roots [g/m2]\n  REAL                        , INTENT(INOUT)    :: STMASS !stem mass [g/m2]\n  REAL                        , INTENT(INOUT)    :: WOOD   !mass of wood (incl. woody roots) [g/m2]\n  REAL                        , INTENT(INOUT)    :: STBLCP !stable carbon in deep soil [g/m2]\n  REAL                        , INTENT(INOUT)    :: FASTCP !short-lived carbon, shallow soil [g/m2]\n  REAL                        , INTENT(INOUT)    :: LAI    !leaf area index [-]\n  REAL                        , INTENT(INOUT)    :: SAI    !stem area index [-]\n  REAL                        , INTENT(INOUT)    :: GRAIN  !grain mass [g/m2]\n  REAL                        , INTENT(INOUT)    :: GDD    !growing degree days\n  INTEGER                     , INTENT(INOUT)    :: PGS    !plant growing stage [-]\n\n! outputs\n  REAL                          , INTENT(OUT)    :: NEE    !net ecosys exchange (g/m2/s CO2)\n  REAL                          , INTENT(OUT)    :: GPP    !net instantaneous assimilation [g/m2/s C]\n  REAL                          , INTENT(OUT)    :: NPP    !net primary productivity [g/m2/s C]\n  REAL                                           :: AUTORS !net ecosystem respiration (g/m2/s C)\n  REAL                                           :: HETERS !organic respiration (g/m2/s C)\n  REAL                                           :: TROOT  !root-zone averaged temperature (k)\n  REAL                                           :: BDFALL   !bulk density of new snow (kg/m3)    ! MB/AN: v3.7\n  REAL                                           :: RAIN     !rain rate                   (mm/s)  ! MB/AN: v3.7\n  REAL                                           :: SNOW     !liquid equivalent snow rate (mm/s)  ! MB/AN: v3.7\n  REAL                                           :: FP                                            ! MB/AN: v3.7\n  REAL                                           :: PRCP                                          ! MB/AN: v3.7\n!more local variables for precip heat MB\n  REAL                                           :: QINTR   !interception rate for rain (mm/s)\n  REAL                                           :: QDRIPR  !drip rate for rain (mm/s)\n  REAL                                           :: QTHROR  !throughfall for rain (mm/s)\n  REAL                                           :: QINTS   !interception (loading) rate for snowfall (mm/s)\n  REAL                                           :: QDRIPS  !drip (unloading) rate for intercepted snow (mm/s)\n  REAL                                           :: QTHROS  !throughfall of snowfall (mm/s)\n  REAL                                           :: SNOWHIN !snow depth increasing rate (m/s)\n  REAL                                 :: LATHEAV !latent heat vap./sublimation (j/kg)\n  REAL                                 :: LATHEAG !latent heat vap./sublimation (j/kg)\n  LOGICAL                             :: FROZEN_GROUND ! used to define latent heat pathway\n  LOGICAL                             :: FROZEN_CANOPY ! used to define latent heat pathway\n  LOGICAL                             :: dveg_active ! flag to run dynamic vegetation\n  LOGICAL                             :: crop_active ! flag to run crop model\n\n  ! INTENT (OUT) variables need to be assigned a value.  These normally get assigned values\n  ! only if DVEG == 2.\n  nee = 0.0\n  npp = 0.0\n  gpp = 0.0\n      PAHV  = 0.\n      PAHG  = 0.\n      PAHB  = 0.\n      PAH  = 0.\n\n! --------------------------------------------------------------------------------------------------\n! re-process atmospheric forcing\n\n   CALL ATM (parameters,SFCPRS  ,SFCTMP   ,Q2      ,                            &\n             PRCPCONV, PRCPNONC,PRCPSHCV,PRCPSNOW,PRCPGRPL,PRCPHAIL, &\n             SOLDN   ,COSZ     ,THAIR   ,QAIR    ,                   &\n             EAIR    ,RHOAIR   ,QPRECC  ,QPRECL  ,SOLAD   ,SOLAI   , &\n             SWDOWN  ,BDFALL   ,RAIN    ,SNOW    ,FP      ,FPICE   , PRCP )\n\n! snow/soil layer thickness (m)\n\n     DO IZ = ISNOW+1, NSOIL\n         IF(IZ == ISNOW+1) THEN\n           DZSNSO(IZ) = - ZSNSO(IZ)\n         ELSE\n           DZSNSO(IZ) = ZSNSO(IZ-1) - ZSNSO(IZ)\n         END IF\n     END DO\n\n! root-zone temperature\n\n     TROOT  = 0.\n     DO IZ=1,parameters%NROOT\n        TROOT = TROOT + STC(IZ)*DZSNSO(IZ)/(-ZSOIL(parameters%NROOT))\n     ENDDO\n\n! total water storage for water balance check\n\n     IF(IST == 1) THEN\n     BEG_WB = CANLIQ + CANICE + SNEQV + WA\n     DO IZ = 1,NSOIL\n        BEG_WB = BEG_WB + SMC(IZ) * DZSNSO(IZ) * 1000.\n     END DO\n     END IF\n\n! vegetation phenology\n\n     CALL PHENOLOGY (parameters,VEGTYP ,croptype, SNOWH  , TV     , LAT   , YEARLEN , JULIAN , & !in\n                     LAI    , SAI    , TROOT  , ELAI    , ESAI   ,IGS, PGS)\n\n!input GVF should be consistent with LAI\n     IF(DVEG == 1 .or. DVEG == 6 .or. DVEG == 7) THEN\n        FVEG = SHDFAC\n        IF(FVEG <= 0.05) FVEG = 0.05\n     ELSE IF (DVEG == 2 .or. DVEG == 3 .or. DVEG == 8) THEN\n        FVEG = 1.-EXP(-0.52*(LAI+SAI))\n        IF(FVEG <= 0.05) FVEG = 0.05\n     ELSE IF (DVEG == 4 .or. DVEG == 5 .or. DVEG == 9) THEN\n        FVEG = SHDMAX\n        IF(FVEG <= 0.05) FVEG = 0.05\n     ELSE\n        WRITE(*,*) \"-------- FATAL CALLED IN SFLX -----------\"\n        CALL wrf_error_fatal(\"Namelist parameter DVEG unknown\")\n     ENDIF\n     IF(OPT_CROP > 0 .and. CROPTYPE > 0) THEN\n        FVEG = SHDMAX\n        IF(FVEG <= 0.05) FVEG = 0.05\n     ENDIF\n     IF(parameters%urban_flag .OR. VEGTYP == parameters%ISBARREN) FVEG = 0.0\n     IF(ELAI+ESAI == 0.0) FVEG = 0.0\n\n    CALL PRECIP_HEAT(parameters,ILOC   ,JLOC   ,VEGTYP ,DT     ,UU     ,VV     , & !in\n                     ELAI   ,ESAI   ,FVEG   ,IST    ,                 & !in\n                     BDFALL ,RAIN   ,SNOW   ,FP     ,                 & !in\n                     CANLIQ ,CANICE ,TV     ,SFCTMP ,TG     ,         & !in\n                     QINTR  ,QDRIPR ,QTHROR ,QINTS  ,QDRIPS ,QTHROS , & !out\n                     PAHV   ,PAHG   ,PAHB   ,QRAIN  ,QSNOW  ,SNOWHIN, & !out\n\t             FWET   ,CMC                                    )   !out\n\n! compute energy budget (momentum & energy fluxes and phase changes)\n\n    CALL ENERGY (parameters,ICE    ,VEGTYP ,IST    ,NSNOW  ,NSOIL  , & !in\n                 ISNOW  ,DT     ,RHOAIR ,SFCPRS ,QAIR   , & !in\n                 SFCTMP ,THAIR  ,LWDN   ,UU     ,VV     ,ZLVL   , & !in\n                 CO2AIR ,O2AIR  ,SOLAD  ,SOLAI  ,COSZ   ,IGS    , & !in\n                 EAIR   ,TBOT   ,ZSNSO  ,ZSOIL  , & !in\n                 ELAI   ,ESAI   ,FWET   ,FOLN   ,         & !in\n                 FVEG   ,PAHV   ,PAHG   ,PAHB   ,                 & !in\n                 QSNOW  ,DZSNSO ,LAT    ,CANLIQ ,CANICE ,iloc, jloc , & !in\n\t\t Z0WRF  ,                                         &\n                 IMELT  ,SNICEV ,SNLIQV ,EPORE  ,T2M    ,FSNO   , & !out\n                 SAV    ,SAG    ,QMELT  ,FSA    ,FSR    ,TAUX   , & !out\n                 TAUY   ,FIRA   ,FSH    ,FCEV   ,FGEV   ,FCTR   , & !out\n                 TRAD   ,PSN    ,APAR   ,SSOIL  ,BTRANI ,BTRAN  , & !out\n                 PONDING,TS     ,LATHEAV , LATHEAG , frozen_canopy,frozen_ground,                         & !out\n                 TV     ,TG     ,STC    ,SNOWH  ,EAH    ,TAH    , & !inout\n                 SNEQVO ,SNEQV  ,SH2O   ,SMC    ,SNICE  ,SNLIQ  , & !inout\n                 ALBOLD ,CM     ,CH     ,DX     ,DZ8W   ,Q2     , & !inout\n                 TAUSS  ,LAISUN ,LAISHA ,RB ,                     & !inout\n!jref:start\n                 QC     ,QSFC   ,PSFC   , & !in\n                 T2MV   ,T2MB  ,FSRV   , &\n                 FSRG   ,RSSUN   ,RSSHA ,ALBSND  ,ALBSNI, BGAP   ,WGAP,TGV,TGB,&\n                 Q1     ,Q2V    ,Q2B    ,Q2E    ,CHV   ,CHB     , & !out\n                 EMISSI ,PAH    ,                                 &\n\t\t     SHG,SHC,SHB,EVG,EVB,GHV,GHB,IRG,IRC,IRB,TR,EVC,CHLEAF,CHUC,CHV2,CHB2 )                                            !out\n!jref:end\n\n    SICE(:) = MAX(0.0, SMC(:) - SH2O(:))\n    SNEQVO  = SNEQV\n\n    QVAP = MAX( FGEV/LATHEAG, 0.)       ! positive part of fgev; Barlage change to ground v3.6\n    QDEW = ABS( MIN(FGEV/LATHEAG, 0.))  ! negative part of fgev\n    EDIR = QVAP - QDEW\n\n! compute water budgets (water storages, ET components, and runoff)\n\n     CALL WATER (parameters,VEGTYP ,NSNOW  ,NSOIL  ,IMELT  ,DT     ,UU     , & !in\n                 VV     ,FCEV   ,FCTR   ,QPRECC ,QPRECL ,ELAI   , & !in\n                 ESAI   ,SFCTMP ,QVAP   ,QDEW   ,ZSOIL  ,BTRANI , & !in\n                 FICEOLD,PONDING,TG     ,IST    ,FVEG   ,iloc,jloc , SMCEQ , & !in\n                 BDFALL ,FP     ,RAIN   ,SNOW   ,                 & !in  MB/AN: v3.7\n\t\t QSNOW  ,QRAIN  ,SNOWHIN,LATHEAV,LATHEAG,frozen_canopy,frozen_ground,  & !in  MB\n                 ISNOW  ,CANLIQ ,CANICE ,TV     ,SNOWH  ,SNEQV  , & !inout\n                 SNICE  ,SNLIQ  ,STC    ,ZSNSO  ,SH2O   ,SMC    , & !inout\n                 SICE   ,ZWT    ,WA     ,WT     ,DZSNSO ,WSLAKE , & !inout\n                 SMCWTD ,DEEPRECH,RECH                          , & !inout\n                 CMC    ,ECAN   ,ETRAN  ,FWET   ,RUNSRF ,RUNSUB , & !out\n                 QIN    ,QDIS   ,PONDING1       ,PONDING2,&\n                 QSNBOT                             &\n#ifdef WRF_HYDRO\n                        ,sfcheadrt                     &\n#endif\n                 )  !out\n\n!     write(*,'(a20,10F15.5)') 'SFLX:RUNOFF=',RUNSRF*DT,RUNSUB*DT,EDIR*DT\n\n! compute carbon budgets (carbon storages and co2 & bvoc fluxes)\n\n   crop_active = .false.\n   dveg_active = .false.\n   IF (DVEG == 2 .OR. DVEG == 5 .OR. DVEG == 6) dveg_active = .true.\n   IF (OPT_CROP > 0 .and. CROPTYPE > 0) THEN\n     crop_active = .true.\n     dveg_active = .false.\n   ENDIF\n\n   IF (dveg_active) THEN\n     CALL CARBON (parameters,NSNOW  ,NSOIL  ,VEGTYP ,DT     ,ZSOIL  , & !in\n                 DZSNSO ,STC    ,SMC    ,TV     ,TG     ,PSN    , & !in\n                 FOLN   ,BTRAN  ,APAR   ,FVEG   ,IGS    , & !in\n                 TROOT  ,IST    ,LAT    ,iloc   ,jloc   , & !in\n                 LFMASS ,RTMASS ,STMASS ,WOOD   ,STBLCP ,FASTCP , & !inout\n                 GPP    ,NPP    ,NEE    ,AUTORS ,HETERS ,TOTSC  , & !out\n                 TOTLB  ,LAI    ,SAI    )                   !out\n   END IF\n\n   IF (OPT_CROP == 1 .and. crop_active) THEN\n    CALL CARBON_CROP (parameters,NSNOW  ,NSOIL  ,VEGTYP ,DT     ,ZSOIL  ,JULIAN , & !in\n                         DZSNSO ,STC    ,SMC    ,TV     ,PSN    ,FOLN   ,BTRAN  , & !in\n\t\t\t SOLDN  ,T2M    ,                                         & !in\n                         LFMASS ,RTMASS ,STMASS ,WOOD   ,STBLCP ,FASTCP ,GRAIN  , & !inout\n\t\t\t LAI    ,SAI    ,GDD    ,                                 & !inout\n                         GPP    ,NPP    ,NEE    ,AUTORS ,HETERS ,TOTSC  ,TOTLB, PGS    ) !out\n   END IF\n\n! water and energy balance check\n\n     CALL ERROR (parameters,SWDOWN ,FSA    ,FSR    ,FIRA   ,FSH    ,FCEV   , & !in\n                 FGEV   ,FCTR   ,SSOIL  ,BEG_WB ,CANLIQ ,CANICE , & !in\n                 SNEQV  ,WA     ,SMC    ,DZSNSO ,PRCP   ,ECAN   , & !in\n                 ETRAN  ,EDIR   ,RUNSRF ,RUNSUB ,DT     ,NSOIL  , & !in\n                 NSNOW  ,IST    ,ERRWAT ,ILOC   , JLOC  ,FVEG   , &\n                 SAV    ,SAG    ,FSRV   ,FSRG   ,ZWT    ,PAH    , &\n                 PAHV   ,PAHG   ,PAHB   )   !in ( Except ERRWAT, which is out )\n\n! urban - jref\n    QFX = ETRAN + ECAN + EDIR\n    IF ( parameters%urban_flag ) THEN\n       QSFC = QFX/(RHOAIR*CH) + QAIR\n       Q2B = QSFC\n    END IF\n\n    IF(SNOWH <= 1.E-6 .OR. SNEQV <= 1.E-3) THEN\n     SNOWH = 0.0\n     SNEQV = 0.0\n    END IF\n\n    IF(SWDOWN.NE.0.) THEN\n      ALBEDO = FSR / SWDOWN\n    ELSE\n      ALBEDO = -999.9\n    END IF\n\n\n  END SUBROUTINE NOAHMP_SFLX\n\n!== begin atm ======================================================================================\n\n  SUBROUTINE ATM (parameters,SFCPRS  ,SFCTMP   ,Q2      ,                             &\n                  PRCPCONV,PRCPNONC ,PRCPSHCV,PRCPSNOW,PRCPGRPL,PRCPHAIL , &\n                  SOLDN   ,COSZ     ,THAIR   ,QAIR    ,                    &\n                  EAIR    ,RHOAIR   ,QPRECC  ,QPRECL  ,SOLAD   , SOLAI   , &\n\t\t  SWDOWN  ,BDFALL   ,RAIN    ,SNOW    ,FP      , FPICE   ,PRCP )\n! --------------------------------------------------------------------------------------------------\n! re-process atmospheric forcing\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n\n  type (noahmp_parameters), intent(in) :: parameters\n  REAL                          , INTENT(IN)  :: SFCPRS !pressure (pa)\n  REAL                          , INTENT(IN)  :: SFCTMP !surface air temperature [k]\n  REAL                          , INTENT(IN)  :: Q2     !mixing ratio (kg/kg)\n  REAL                          , INTENT(IN)  :: PRCPCONV ! convective precipitation entering  [mm/s]    ! MB/AN : v3.7\n  REAL                          , INTENT(IN)  :: PRCPNONC ! non-convective precipitation entering [mm/s] ! MB/AN : v3.7\n  REAL                          , INTENT(IN)  :: PRCPSHCV ! shallow convective precip entering  [mm/s]   ! MB/AN : v3.7\n  REAL                          , INTENT(IN)  :: PRCPSNOW ! snow entering land model [mm/s]              ! MB/AN : v3.7\n  REAL                          , INTENT(IN)  :: PRCPGRPL ! graupel entering land model [mm/s]           ! MB/AN : v3.7\n  REAL                          , INTENT(IN)  :: PRCPHAIL ! hail entering land model [mm/s]              ! MB/AN : v3.7\n  REAL                          , INTENT(IN)  :: SOLDN  !downward shortwave radiation (w/m2)\n  REAL                          , INTENT(IN)  :: COSZ   !cosine solar zenith angle [0-1]\n\n! outputs\n\n  REAL                          , INTENT(OUT) :: THAIR  !potential temperature (k)\n  REAL                          , INTENT(OUT) :: QAIR   !specific humidity (kg/kg) (q2/(1+q2))\n  REAL                          , INTENT(OUT) :: EAIR   !vapor pressure air (pa)\n  REAL                          , INTENT(OUT) :: RHOAIR !density air (kg/m3)\n  REAL                          , INTENT(OUT) :: QPRECC !convective precipitation (mm/s)\n  REAL                          , INTENT(OUT) :: QPRECL !large-scale precipitation (mm/s)\n  REAL, DIMENSION(       1:   2), INTENT(OUT) :: SOLAD  !incoming direct solar radiation (w/m2)\n  REAL, DIMENSION(       1:   2), INTENT(OUT) :: SOLAI  !incoming diffuse solar radiation (w/m2)\n  REAL                          , INTENT(OUT) :: SWDOWN !downward solar filtered by sun angle [w/m2]\n  REAL                          , INTENT(OUT) :: BDFALL  !!bulk density of snowfall (kg/m3) AJN\n  REAL                          , INTENT(OUT) :: RAIN    !rainfall (mm/s) AJN\n  REAL                          , INTENT(OUT) :: SNOW    !liquid equivalent snowfall (mm/s) AJN\n  REAL                          , INTENT(OUT) :: FP      !fraction of area receiving precipitation  AJN\n  REAL                          , INTENT(OUT) :: FPICE   !fraction of ice                AJN\n  REAL                          , INTENT(OUT) :: PRCP    !total precipitation [mm/s]     ! MB/AN : v3.7\n\n!locals\n\n  REAL                                        :: PAIR   !atm bottom level pressure (pa)\n  REAL                                        :: PRCP_FROZEN   !total frozen precipitation [mm/s] ! MB/AN : v3.7\n  REAL, PARAMETER                             :: RHO_GRPL = 500.0  ! graupel bulk density [kg/m3] ! MB/AN : v3.7\n  REAL, PARAMETER                             :: RHO_HAIL = 917.0  ! hail bulk density [kg/m3]    ! MB/AN : v3.7\n! --------------------------------------------------------------------------------------------------\n\n!jref: seems like PAIR should be P1000mb??\n       PAIR   = SFCPRS                   ! atm bottom level pressure (pa)\n       THAIR  = SFCTMP * (SFCPRS/PAIR)**(RAIR/CPAIR)\n\n       QAIR   = Q2                       ! In WRF, driver converts to specific humidity\n\n       EAIR   = QAIR*SFCPRS / (0.622+0.378*QAIR)\n       RHOAIR = (SFCPRS-0.378*EAIR) / (RAIR*SFCTMP)\n\n       IF(COSZ <= 0.) THEN\n          SWDOWN = 0.\n       ELSE\n          SWDOWN = SOLDN\n       END IF\n\n       SOLAD(1) = SWDOWN*0.7*0.5     ! direct  vis\n       SOLAD(2) = SWDOWN*0.7*0.5     ! direct  nir\n       SOLAI(1) = SWDOWN*0.3*0.5     ! diffuse vis\n       SOLAI(2) = SWDOWN*0.3*0.5     ! diffuse nir\n\n       PRCP = PRCPCONV + PRCPNONC + PRCPSHCV\n\n       IF(OPT_SNF == 4) THEN\n         QPRECC = PRCPCONV + PRCPSHCV\n\t QPRECL = PRCPNONC\n       ELSE\n         QPRECC = 0.10 * PRCP          ! should be from the atmospheric model\n         QPRECL = 0.90 * PRCP          ! should be from the atmospheric model\n       END IF\n\n! fractional area that receives precipitation (see, Niu et al. 2005)\n\n    FP = 0.0\n    IF(QPRECC + QPRECL > 0.) &\n       FP = (QPRECC + QPRECL) / (10.*QPRECC + QPRECL)\n\n! partition precipitation into rain and snow. Moved from CANWAT MB/AN: v3.7\n\n! Jordan (1991)\n\n     IF(OPT_SNF == 1) THEN\n       IF(SFCTMP > TFRZ+2.5)THEN\n           FPICE = 0.\n       ELSE\n         IF(SFCTMP <= TFRZ+0.5)THEN\n           FPICE = 1.0\n         ELSE IF(SFCTMP <= TFRZ+2.)THEN\n           FPICE = 1.-(-54.632 + 0.2*SFCTMP)\n         ELSE\n           FPICE = 0.6\n         ENDIF\n       ENDIF\n     ENDIF\n\n     IF(OPT_SNF == 2) THEN\n       IF(SFCTMP >= TFRZ+2.2) THEN\n           FPICE = 0.\n       ELSE\n           FPICE = 1.0\n       ENDIF\n     ENDIF\n\n     IF(OPT_SNF == 3) THEN\n       IF(SFCTMP >= TFRZ) THEN\n           FPICE = 0.\n       ELSE\n           FPICE = 1.0\n       ENDIF\n     ENDIF\n\n! Hedstrom NR and JW Pomeroy (1998), Hydrol. Processes, 12, 1611-1625\n! fresh snow density\n\n     BDFALL = MIN(120.,67.92+51.25*EXP((SFCTMP-TFRZ)/2.59))       !MB/AN: change to MIN\n     IF(OPT_SNF == 4) THEN\n        PRCP_FROZEN = PRCPSNOW + PRCPGRPL + PRCPHAIL\n        IF(PRCPNONC > 0. .and. PRCP_FROZEN > 0.) THEN\n\t  FPICE = MIN(1.0,PRCP_FROZEN/PRCPNONC)\n\t  FPICE = MAX(0.0,FPICE)\n\t  BDFALL = BDFALL*(PRCPSNOW/PRCP_FROZEN) + RHO_GRPL*(PRCPGRPL/PRCP_FROZEN) + &\n\t             RHO_HAIL*(PRCPHAIL/PRCP_FROZEN)\n\tELSE\n\t  FPICE = 0.0\n        ENDIF\n\n     ENDIF\n\n     RAIN   = PRCP * (1.-FPICE)\n     SNOW   = PRCP * FPICE\n\n\n  END SUBROUTINE ATM\n\n!== begin phenology ================================================================================\n\n  SUBROUTINE PHENOLOGY (parameters,VEGTYP ,croptype, SNOWH  , TV     , LAT   , YEARLEN , JULIAN , & !in\n                        LAI    , SAI    , TROOT  , ELAI    , ESAI   , IGS, PGS)\n\n! --------------------------------------------------------------------------------------------------\n! vegetation phenology considering vegeation canopy being buries by snow and evolution in time\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER                , INTENT(IN   ) :: VEGTYP !vegetation type\n  INTEGER                , INTENT(IN   ) :: CROPTYPE !vegetation type\n  REAL                   , INTENT(IN   ) :: SNOWH  !snow height [m]\n  REAL                   , INTENT(IN   ) :: TV     !vegetation temperature (k)\n  REAL                   , INTENT(IN   ) :: LAT    !latitude (radians)\n  INTEGER                , INTENT(IN   ) :: YEARLEN!Number of days in the particular year\n  REAL                   , INTENT(IN   ) :: JULIAN !Julian day of year (fractional) ( 0 <= JULIAN < YEARLEN )\n  real                   , INTENT(IN   ) :: TROOT  !root-zone averaged temperature (k)\n  REAL                   , INTENT(INOUT) :: LAI    !LAI, unadjusted for burying by snow\n  REAL                   , INTENT(INOUT) :: SAI    !SAI, unadjusted for burying by snow\n\n! outputs\n  REAL                   , INTENT(OUT  ) :: ELAI   !leaf area index, after burying by snow\n  REAL                   , INTENT(OUT  ) :: ESAI   !stem area index, after burying by snow\n  REAL                   , INTENT(OUT  ) :: IGS    !growing season index (0=off, 1=on)\n  INTEGER                , INTENT(IN   ) :: PGS    !plant growing stage\n\n! locals\n\n  REAL                                   :: DB     !thickness of canopy buried by snow (m)\n  REAL                                   :: FB     !fraction of canopy buried by snow\n  REAL                                   :: SNOWHC !critical snow depth at which short vege\n                                                   !is fully covered by snow\n\n  INTEGER                                :: K       !index\n  INTEGER                                :: IT1,IT2 !interpolation months\n  REAL                                   :: DAY     !current day of year ( 0 <= DAY < YEARLEN )\n  REAL                                   :: WT1,WT2 !interpolation weights\n  REAL                                   :: T       !current month (1.00, ..., 12.00)\n! --------------------------------------------------------------------------------------------------\n\nIF (CROPTYPE == 0) THEN\n\n  IF ( DVEG == 1 .or. DVEG == 3 .or. DVEG == 4 ) THEN\n\n     IF (LAT >= 0.) THEN\n        ! Northern Hemisphere\n        DAY = JULIAN\n     ELSE\n        ! Southern Hemisphere.  DAY is shifted by 1/2 year.\n        DAY = MOD ( JULIAN + ( 0.5 * YEARLEN ) , REAL(YEARLEN) )\n     ENDIF\n\n     T = 12. * DAY / REAL(YEARLEN)\n     IT1 = T + 0.5\n     IT2 = IT1 + 1\n     WT1 = (IT1+0.5) - T\n     WT2 = 1.-WT1\n     IF (IT1 .LT.  1) IT1 = 12\n     IF (IT2 .GT. 12) IT2 = 1\n\n     LAI = WT1*parameters%LAIM(IT1) + WT2*parameters%LAIM(IT2)\n     SAI = WT1*parameters%SAIM(IT1) + WT2*parameters%SAIM(IT2)\n  ENDIF\n\n  IF(DVEG == 7 .or. DVEG == 8 .or. DVEG == 9) THEN\n    SAI = MAX(0.05,0.1 * LAI)  ! when reading LAI, set SAI to 10% LAI, but not below 0.05 MB: v3.8\n    IF (LAI < 0.05) SAI = 0.0  ! if LAI below minimum, make sure SAI = 0\n  ENDIF\n\n  IF (SAI < 0.05) SAI = 0.0                    ! MB: SAI CHECK, change to 0.05 v3.6\n  IF (LAI < 0.05 .OR. SAI == 0.0) LAI = 0.0  ! MB: LAI CHECK\n\n  IF ( ( VEGTYP == parameters%iswater ) .OR. ( VEGTYP == parameters%ISBARREN ) .OR. &\n       ( VEGTYP == parameters%ISICE   ) .or. ( parameters%urban_flag ) ) THEN\n     LAI  = 0.\n     SAI  = 0.\n  ENDIF\n\nENDIF   ! CROPTYPE == 0\n\n!buried by snow\n\n     DB = MIN( MAX(SNOWH - parameters%HVB,0.), parameters%HVT-parameters%HVB )\n     FB = DB / MAX(1.E-06,parameters%HVT-parameters%HVB)\n\n     IF(parameters%HVT> 0. .AND. parameters%HVT <= 1.0) THEN          !MB: change to 1.0 and 0.2 to reflect\n       SNOWHC = parameters%HVT*EXP(-SNOWH/0.2)             !      changes to HVT in MPTABLE\n       if (SNOWHC .le. SNOWH) then  ! AD: change this min to an if then since precision was leading to divide by 0s\n          FB = 1.\n       else\n          FB = SNOWH/SNOWHC\n       endif\n     ENDIF\n\n     ELAI =  LAI*(1.-FB)\n     ESAI =  SAI*(1.-FB)\n     IF (ESAI < 0.05 .and. CROPTYPE == 0) ESAI = 0.0                   ! MB: ESAI CHECK, change to 0.05 v3.6\n     IF ((ELAI < 0.05 .OR. ESAI == 0.0) .and. CROPTYPE == 0) ELAI = 0.0  ! MB: LAI CHECK\n\n! set growing season flag\n\n     IF ((TV .GT. parameters%TMIN .and. CROPTYPE == 0).or.(PGS > 2 .and. PGS < 7 .and. CROPTYPE > 0)) THEN\n         IGS = 1.\n     ELSE\n         IGS = 0.\n     ENDIF\n\n  END SUBROUTINE PHENOLOGY\n\n!== begin precip_heat ==============================================================================\n\n  SUBROUTINE PRECIP_HEAT (parameters,ILOC   ,JLOC   ,VEGTYP ,DT     ,UU     ,VV     , & !in\n                          ELAI   ,ESAI   ,FVEG   ,IST    ,                 & !in\n                          BDFALL ,RAIN   ,SNOW   ,FP     ,                 & !in\n                          CANLIQ ,CANICE ,TV     ,SFCTMP ,TG     ,         & !in\n                          QINTR  ,QDRIPR ,QTHROR ,QINTS  ,QDRIPS ,QTHROS , & !out\n\t\t\t  PAHV   ,PAHG   ,PAHB   ,QRAIN  ,QSNOW  ,SNOWHIN, & !out\n\t\t\t  FWET   ,CMC                                    )   !out\n\n! ------------------------ code history ------------------------------\n! Michael Barlage: Oct 2013 - split CANWATER to calculate precip movement for\n!                             tracking of advected heat\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! ------------------------ input/output variables --------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,INTENT(IN)  :: ILOC    !grid index\n  INTEGER,INTENT(IN)  :: JLOC    !grid index\n  INTEGER,INTENT(IN)  :: VEGTYP  !vegetation type\n  INTEGER,INTENT(IN)  :: IST     !surface type 1-soil; 2-lake\n  REAL,   INTENT(IN)  :: DT      !main time step (s)\n  REAL,   INTENT(IN)  :: UU      !u-direction wind speed [m/s]\n  REAL,   INTENT(IN)  :: VV      !v-direction wind speed [m/s]\n  REAL,   INTENT(IN)  :: ELAI    !leaf area index, after burying by snow\n  REAL,   INTENT(IN)  :: ESAI    !stem area index, after burying by snow\n  REAL,   INTENT(IN)  :: FVEG    !greeness vegetation fraction (-)\n  REAL,   INTENT(IN)  :: BDFALL  !bulk density of snowfall (kg/m3)\n  REAL,   INTENT(IN)  :: RAIN    !rainfall (mm/s)\n  REAL,   INTENT(IN)  :: SNOW    !snowfall (mm/s)\n  REAL,   INTENT(IN)  :: FP      !fraction of the gridcell that receives precipitation\n  REAL,   INTENT(IN)  :: TV      !vegetation temperature (k)\n  REAL,   INTENT(IN)  :: SFCTMP  !model-level temperature (k)\n  REAL,   INTENT(IN)  :: TG      !ground temperature (k)\n\n! input & output\n  REAL, INTENT(INOUT) :: CANLIQ  !intercepted liquid water (mm)\n  REAL, INTENT(INOUT) :: CANICE  !intercepted ice mass (mm)\n\n! output\n  REAL, INTENT(OUT)   :: QINTR   !interception rate for rain (mm/s)\n  REAL, INTENT(OUT)   :: QDRIPR  !drip rate for rain (mm/s)\n  REAL, INTENT(OUT)   :: QTHROR  !throughfall for rain (mm/s)\n  REAL, INTENT(OUT)   :: QINTS   !interception (loading) rate for snowfall (mm/s)\n  REAL, INTENT(OUT)   :: QDRIPS  !drip (unloading) rate for intercepted snow (mm/s)\n  REAL, INTENT(OUT)   :: QTHROS  !throughfall of snowfall (mm/s)\n  REAL, INTENT(OUT)   :: PAHV    !precipitation advected heat - vegetation net (W/m2)\n  REAL, INTENT(OUT)   :: PAHG    !precipitation advected heat - under canopy net (W/m2)\n  REAL, INTENT(OUT)   :: PAHB    !precipitation advected heat - bare ground net (W/m2)\n  REAL, INTENT(OUT)   :: QRAIN   !rain at ground srf (mm/s) [+]\n  REAL, INTENT(OUT)   :: QSNOW   !snow at ground srf (mm/s) [+]\n  REAL, INTENT(OUT)   :: SNOWHIN !snow depth increasing rate (m/s)\n  REAL, INTENT(OUT)   :: FWET    !wetted or snowed fraction of the canopy (-)\n  REAL, INTENT(OUT)   :: CMC     !intercepted water (mm)\n! --------------------------------------------------------------------\n\n! ------------------------ local variables ---------------------------\n  REAL                :: MAXSNO  !canopy capacity for snow interception (mm)\n  REAL                :: MAXLIQ  !canopy capacity for rain interception (mm)\n  REAL                :: FT      !temperature factor for unloading rate\n  REAL                :: FV      !wind factor for unloading rate\n  REAL                :: PAH_AC  !precipitation advected heat - air to canopy (W/m2)\n  REAL                :: PAH_CG  !precipitation advected heat - canopy to ground (W/m2)\n  REAL                :: PAH_AG  !precipitation advected heat - air to ground (W/m2)\n  REAL                :: ICEDRIP !canice unloading\n! --------------------------------------------------------------------\n! initialization\n\n      QINTR   = 0.\n      QDRIPR  = 0.\n      QTHROR  = 0.\n      QINTR   = 0.\n      QINTS   = 0.\n      QDRIPS  = 0.\n      QTHROS  = 0.\n      PAH_AC  = 0.\n      PAH_CG  = 0.\n      PAH_AG  = 0.\n      PAHV    = 0.\n      PAHG    = 0.\n      PAHB    = 0.\n      QRAIN   = 0.0\n      QSNOW   = 0.0\n      SNOWHIN = 0.0\n      ICEDRIP = 0.0\n!      print*, \"precip_heat begin canopy balance:\",canliq+canice+(rain+snow)*dt\n!      print*,  \"precip_heat snow*3600.0:\",snow*3600.0\n!      print*,  \"precip_heat rain*3600.0:\",rain*3600.0\n!      print*,  \"precip_heat canice:\",canice\n!      print*,  \"precip_heat canliq:\",canliq\n\n! --------------------------- liquid water ------------------------------\n! maximum canopy water\n\n      MAXLIQ =  parameters%CH2OP * (ELAI+ ESAI)\n\n! average interception and throughfall\n\n      IF((ELAI+ ESAI).GT.0.) THEN\n         QINTR  = FVEG * RAIN * FP  ! interception capability\n         QINTR  = MIN(QINTR, (MAXLIQ - CANLIQ)/DT * (1.-EXP(-RAIN*DT/MAXLIQ)) )\n         QINTR  = MAX(QINTR, 0.)\n         QDRIPR = FVEG * RAIN - QINTR\n         QTHROR = (1.-FVEG) * RAIN\n         CANLIQ=MAX(0.,CANLIQ+QINTR*DT)\n      ELSE\n         QINTR  = 0.\n         QDRIPR = 0.\n         QTHROR = RAIN\n\t IF(CANLIQ > 0.) THEN             ! FOR CASE OF CANOPY GETTING BURIED\n\t   QDRIPR = QDRIPR + CANLIQ/DT\n\t   CANLIQ = 0.0\n\t END IF\n      END IF\n\n! heat transported by liquid water\n\n      PAH_AC = FVEG * RAIN * (CWAT/1000.0) * (SFCTMP - TV)\n      PAH_CG = QDRIPR * (CWAT/1000.0) * (TV - TG)\n      PAH_AG = QTHROR * (CWAT/1000.0) * (SFCTMP - TG)\n!      print*, \"precip_heat PAH_AC:\",PAH_AC\n!      print*, \"precip_heat PAH_CG:\",PAH_CG\n!      print*, \"precip_heat PAH_AG:\",PAH_AG\n\n! --------------------------- canopy ice ------------------------------\n! for canopy ice\n\n      MAXSNO = 6.6*(0.27+46./BDFALL) * (ELAI+ ESAI)\n\n      IF((ELAI+ ESAI).GT.0.) THEN\n         QINTS = FVEG * SNOW * FP\n         QINTS = MIN(QINTS, (MAXSNO - CANICE)/DT * (1.-EXP(-SNOW*DT/MAXSNO)) )\n         QINTS = MAX(QINTS, 0.)\n         FT = MAX(0.0,(TV - 270.15) / 1.87E5)\n         FV = SQRT(UU*UU + VV*VV) / 1.56E5\n\t ! MB: changed below to reflect the rain assumption that all precip gets intercepted\n\t ICEDRIP = MAX(0.,CANICE) * (FV+FT)    !MB: removed /DT\n         QDRIPS = (FVEG * SNOW - QINTS) + ICEDRIP\n         QTHROS = (1.0-FVEG) * SNOW\n         CANICE= MAX(0.,CANICE + (QINTS - ICEDRIP)*DT)\n      ELSE\n         QINTS  = 0.\n         QDRIPS = 0.\n         QTHROS = SNOW\n\t IF(CANICE > 0.) THEN             ! FOR CASE OF CANOPY GETTING BURIED\n\t   QDRIPS = QDRIPS + CANICE/DT\n\t   CANICE = 0.0\n\t END IF\n      ENDIF\n!      print*, \"precip_heat canopy through:\",3600.0*(FVEG * SNOW - QINTS)\n!      print*, \"precip_heat canopy drip:\",3600.0*MAX(0.,CANICE) * (FV+FT)\n\n! wetted fraction of canopy\n\n      IF(CANICE.GT.0.) THEN\n           FWET = MAX(0.,CANICE) / MAX(MAXSNO,1.E-06)\n      ELSE\n           FWET = MAX(0.,CANLIQ) / MAX(MAXLIQ,1.E-06)\n      ENDIF\n      FWET = MIN(FWET, 1.) ** 0.667\n\n! total canopy water\n\n      CMC = CANLIQ + CANICE\n\n! heat transported by snow/ice\n\n      PAH_AC = PAH_AC +  FVEG * SNOW * (CICE/1000.0) * (SFCTMP - TV)\n      PAH_CG = PAH_CG + QDRIPS * (CICE/1000.0) * (TV - TG)\n      PAH_AG = PAH_AG + QTHROS * (CICE/1000.0) * (SFCTMP - TG)\n\n      PAHV = PAH_AC - PAH_CG\n      PAHG = PAH_CG\n      PAHB = PAH_AG\n\n      IF (FVEG > 0.0 .AND. FVEG < 1.0) THEN\n        PAHG = PAHG / FVEG         ! these will be multiplied by fraction later\n\tPAHB = PAHB / (1.0-FVEG)\n      ELSEIF (FVEG <= 0.0) THEN\n        PAHB = PAHG + PAHB         ! for case of canopy getting buried\n        PAHG = 0.0\n\tPAHV = 0.0\n      ELSEIF (FVEG >= 1.0) THEN\n\tPAHB = 0.0\n      END IF\n\n      PAHV = MAX(PAHV,-20.0)       ! Put some artificial limits here for stability\n      PAHV = MIN(PAHV,20.0)\n      PAHG = MAX(PAHG,-20.0)\n      PAHG = MIN(PAHG,20.0)\n      PAHB = MAX(PAHB,-20.0)\n      PAHB = MIN(PAHB,20.0)\n\n!      print*, 'precip_heat sfctmp,tv,tg:',sfctmp,tv,tg\n!      print*, 'precip_heat 3600.0*qints+qdrips+qthros:',3600.0*(qints+qdrips+qthros)\n!      print*, \"precip_heat maxsno:\",maxsno\n!      print*, \"precip_heat PAH_AC:\",PAH_AC\n!      print*, \"precip_heat PAH_CG:\",PAH_CG\n!      print*, \"precip_heat PAH_AG:\",PAH_AG\n\n!      print*, \"precip_heat PAHV:\",PAHV\n!      print*, \"precip_heat PAHG:\",PAHG\n!      print*, \"precip_heat PAHB:\",PAHB\n!      print*, \"precip_heat fveg:\",fveg\n!      print*,  \"precip_heat qints*3600.0:\",qints*3600.0\n!      print*,  \"precip_heat qdrips*3600.0:\",qdrips*3600.0\n!      print*,  \"precip_heat qthros*3600.0:\",qthros*3600.0\n\n! rain or snow on the ground\n\n      QRAIN   = QDRIPR + QTHROR\n      QSNOW   = QDRIPS + QTHROS\n      SNOWHIN = QSNOW/BDFALL\n\n      IF (IST == 2 .AND. TG > TFRZ) THEN\n         QSNOW   = 0.\n         SNOWHIN = 0.\n      END IF\n!      print*,  \"precip_heat qsnow*3600.0:\",qsnow*3600.0\n!      print*,  \"precip_heat qrain*3600.0:\",qrain*3600.0\n!      print*,  \"precip_heat SNOWHIN:\",SNOWHIN\n!      print*,  \"precip_heat canice:\",canice\n!      print*,  \"precip_heat canliq:\",canliq\n!      print*, \"precip_heat end canopy balance:\",canliq+canice+(qrain+qsnow)*dt\n\n\n  END SUBROUTINE PRECIP_HEAT\n\n!== begin error ====================================================================================\n\n  SUBROUTINE ERROR (parameters,SWDOWN ,FSA    ,FSR    ,FIRA   ,FSH    ,FCEV   , &\n                    FGEV   ,FCTR   ,SSOIL  ,BEG_WB ,CANLIQ ,CANICE , &\n                    SNEQV  ,WA     ,SMC    ,DZSNSO ,PRCP   ,ECAN   , &\n                    ETRAN  ,EDIR   ,RUNSRF ,RUNSUB ,DT     ,NSOIL  , &\n                    NSNOW  ,IST    ,ERRWAT, ILOC   ,JLOC   ,FVEG   , &\n                    SAV    ,SAG    ,FSRV   ,FSRG   ,ZWT    ,PAH    , &\n                    PAHV   ,PAHG   ,PAHB   )\n! --------------------------------------------------------------------------------------------------\n! check surface energy balance and water balance\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER                        , INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  INTEGER                        , INTENT(IN) :: NSOIL  !number of soil layers\n  INTEGER                        , INTENT(IN) :: IST    !surface type 1->soil; 2->lake\n  INTEGER                        , INTENT(IN) :: ILOC   !grid index\n  INTEGER                        , INTENT(IN) :: JLOC   !grid index\n  REAL                           , INTENT(IN) :: SWDOWN !downward solar filtered by sun angle [w/m2]\n  REAL                           , INTENT(IN) :: FSA    !total absorbed solar radiation (w/m2)\n  REAL                           , INTENT(IN) :: FSR    !total reflected solar radiation (w/m2)\n  REAL                           , INTENT(IN) :: FIRA   !total net longwave rad (w/m2)  [+ to atm]\n  REAL                           , INTENT(IN) :: FSH    !total sensible heat (w/m2)     [+ to atm]\n  REAL                           , INTENT(IN) :: FCEV   !canopy evaporation heat (w/m2) [+ to atm]\n  REAL                           , INTENT(IN) :: FGEV   !ground evaporation heat (w/m2) [+ to atm]\n  REAL                           , INTENT(IN) :: FCTR   !transpiration heat flux (w/m2) [+ to atm]\n  REAL                           , INTENT(IN) :: SSOIL  !ground heat flux (w/m2)        [+ to soil]\n  REAL                           , INTENT(IN) :: FVEG\n  REAL                           , INTENT(IN) :: SAV\n  REAL                           , INTENT(IN) :: SAG\n  REAL                           , INTENT(IN) :: FSRV\n  REAL                           , INTENT(IN) :: FSRG\n  REAL                           , INTENT(IN) :: ZWT\n\n  REAL                           , INTENT(IN) :: PRCP   !precipitation rate (kg m-2 s-1)\n  REAL                           , INTENT(IN) :: ECAN   !evaporation of intercepted water (mm/s)\n  REAL                           , INTENT(IN) :: ETRAN  !transpiration rate (mm/s)\n  REAL                           , INTENT(IN) :: EDIR   !soil surface evaporation rate[mm/s]\n  REAL                           , INTENT(IN) :: RUNSRF !surface runoff [mm/s]\n  REAL                           , INTENT(IN) :: RUNSUB !baseflow (saturation excess) [mm/s]\n  REAL                           , INTENT(IN) :: CANLIQ !intercepted liquid water (mm)\n  REAL                           , INTENT(IN) :: CANICE !intercepted ice mass (mm)\n  REAL                           , INTENT(IN) :: SNEQV  !snow water eqv. [mm]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: SMC    !soil moisture (ice + liq.) [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !snow/soil layer thickness [m]\n  REAL                           , INTENT(IN) :: WA     !water storage in aquifer [mm]\n  REAL                           , INTENT(IN) :: DT     !time step [sec]\n  REAL                           , INTENT(IN) :: BEG_WB !water storage at begin of a timesetp [mm]\n  REAL                           , INTENT(OUT) :: ERRWAT !error in water balance [mm/timestep]\n  REAL, INTENT(IN)   :: PAH     !precipitation advected heat - total (W/m2)\n  REAL, INTENT(IN)   :: PAHV    !precipitation advected heat - total (W/m2)\n  REAL, INTENT(IN)   :: PAHG    !precipitation advected heat - total (W/m2)\n  REAL, INTENT(IN)   :: PAHB    !precipitation advected heat - total (W/m2)\n\n  INTEGER                                     :: IZ     !do-loop index\n  REAL                                        :: END_WB !water storage at end of a timestep [mm]\n  !KWM REAL                                        :: ERRWAT !error in water balance [mm/timestep]\n  REAL                                        :: ERRENG !error in surface energy balance [w/m2]\n  REAL                                        :: ERRSW  !error in shortwave radiation balance [w/m2]\n  REAL                                        :: FSRVG\n  CHARACTER(len=256)                          :: message\n! --------------------------------------------------------------------------------------------------\n!jref:start\n   ERRSW   = SWDOWN - (FSA + FSR)\n!   ERRSW   = SWDOWN - (SAV+SAG + FSRV+FSRG)\n!   WRITE(*,*) \"ERRSW =\",ERRSW\n   IF (ABS(ERRSW) > 0.01) THEN            ! w/m2\n   WRITE(*,*) \"VEGETATION!\"\n   WRITE(*,*) \"SWDOWN*FVEG =\",SWDOWN*FVEG\n   WRITE(*,*) \"FVEG*(SAV+SAG) =\",FVEG*SAV + SAG\n   WRITE(*,*) \"FVEG*(FSRV +FSRG)=\",FVEG*FSRV + FSRG\n   WRITE(*,*) \"GROUND!\"\n   WRITE(*,*) \"(1-.FVEG)*SWDOWN =\",(1.-FVEG)*SWDOWN\n   WRITE(*,*) \"(1.-FVEG)*SAG =\",(1.-FVEG)*SAG\n   WRITE(*,*) \"(1.-FVEG)*FSRG=\",(1.-FVEG)*FSRG\n   WRITE(*,*) \"FSRV   =\",FSRV\n   WRITE(*,*) \"FSRG   =\",FSRG\n   WRITE(*,*) \"FSR    =\",FSR\n   WRITE(*,*) \"SAV    =\",SAV\n   WRITE(*,*) \"SAG    =\",SAG\n   WRITE(*,*) \"FSA    =\",FSA\n!jref:end\n      WRITE(message,*) 'ERRSW =',ERRSW\n      call wrf_message(trim(message))\n      call wrf_error_fatal(\"Stop in Noah-MP\")\n   END IF\n\n   ERRENG = SAV+SAG-(FIRA+FSH+FCEV+FGEV+FCTR+SSOIL) +PAH\n!   ERRENG = FVEG*SAV+SAG-(FIRA+FSH+FCEV+FGEV+FCTR+SSOIL)\n!   WRITE(*,*) \"ERRENG =\",ERRENG\n   IF(ABS(ERRENG) > 0.01) THEN\n      write(message,*) 'ERRENG =',ERRENG,' at i,j: ',ILOC,JLOC\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Net solar:       \",FSA\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Net longwave:    \",FIRA\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Total sensible:  \",FSH\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Canopy evap:     \",FCEV\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Ground evap:     \",FGEV\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Transpiration:   \",FCTR\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Total ground:    \",SSOIL\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,4F10.4)') \"Precip advected: \",PAH,PAHV,PAHG,PAHB\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Precip: \",PRCP\n      call wrf_message(trim(message))\n      WRITE(message,'(a17,F10.4)') \"Veg fraction: \",FVEG\n      call wrf_message(trim(message))\n      call wrf_error_fatal(\"Energy budget problem in NOAHMP LSM\")\n   END IF\n\n   IF (IST == 1) THEN                                       !soil\n        END_WB = CANLIQ + CANICE + SNEQV + WA\n        DO IZ = 1,NSOIL\n          END_WB = END_WB + SMC(IZ) * DZSNSO(IZ) * 1000.\n        END DO\n        ERRWAT = END_WB-BEG_WB-(PRCP-ECAN-ETRAN-EDIR-RUNSRF-RUNSUB)*DT\n\n#ifndef WRF_HYDRO\n        IF(ABS(ERRWAT) > 0.1) THEN\n           if (ERRWAT > 0) then\n              call wrf_message ('The model is gaining water (ERRWAT is positive)')\n           else\n              call wrf_message('The model is losing water (ERRWAT is negative)')\n           endif\n           write(message, *) 'ERRWAT =',ERRWAT, \"kg m{-2} timestep{-1}\"\n           call wrf_message(trim(message))\n           WRITE(message, &\n           '(\"    I      J     END_WB     BEG_WB       PRCP       ECAN       EDIR      ETRAN      RUNSRF     RUNSUB\")')\n           call wrf_message(trim(message))\n           WRITE(message,'(i6,1x,i6,1x,2f15.3,9f11.5)')ILOC,JLOC,END_WB,BEG_WB,PRCP*DT,ECAN*DT,&\n                EDIR*DT,ETRAN*DT,RUNSRF*DT,RUNSUB*DT,ZWT\n           call wrf_message(trim(message))\n           call wrf_error_fatal(\"Water budget problem in NOAHMP LSM\")\n        END IF\n#endif\n   ELSE                 !KWM\n      ERRWAT = 0.0      !KWM\n   ENDIF\n\n END SUBROUTINE ERROR\n\n!== begin energy ===================================================================================\n\n  SUBROUTINE ENERGY (parameters,ICE    ,VEGTYP ,IST    ,NSNOW  ,NSOIL  , & !in\n                     ISNOW  ,DT     ,RHOAIR ,SFCPRS ,QAIR   , & !in\n                     SFCTMP ,THAIR  ,LWDN   ,UU     ,VV     ,ZREF   , & !in\n                     CO2AIR ,O2AIR  ,SOLAD  ,SOLAI  ,COSZ   ,IGS    , & !in\n                     EAIR   ,TBOT   ,ZSNSO  ,ZSOIL  , & !in\n                     ELAI   ,ESAI   ,FWET   ,FOLN   ,         & !in\n                     FVEG   ,PAHV   ,PAHG   ,PAHB   ,                 & !in\n                     QSNOW  ,DZSNSO ,LAT    ,CANLIQ ,CANICE ,ILOC   , JLOC, & !in\n\t\t     Z0WRF  ,                                         &\n                     IMELT  ,SNICEV ,SNLIQV ,EPORE  ,T2M    ,FSNO   , & !out\n                     SAV    ,SAG    ,QMELT  ,FSA    ,FSR    ,TAUX   , & !out\n                     TAUY   ,FIRA   ,FSH    ,FCEV   ,FGEV   ,FCTR   , & !out\n                     TRAD   ,PSN    ,APAR   ,SSOIL  ,BTRANI ,BTRAN  , & !out\n                     PONDING,TS     ,LATHEAV , LATHEAG , frozen_canopy,frozen_ground,                       & !out\n                     TV     ,TG     ,STC    ,SNOWH  ,EAH    ,TAH    , & !inout\n                     SNEQVO ,SNEQV  ,SH2O   ,SMC    ,SNICE  ,SNLIQ  , & !inout\n                     ALBOLD ,CM     ,CH     ,DX     ,DZ8W   ,Q2     , &   !inout\n                     TAUSS  ,LAISUN ,LAISHA ,RB ,                     & !inout\n!jref:start\n                     QC     ,QSFC   ,PSFC   , & !in\n                     T2MV   ,T2MB   ,FSRV   , &\n                     FSRG   ,RSSUN  ,RSSHA  ,ALBSND  ,ALBSNI,BGAP   ,WGAP,TGV,TGB,&\n                     Q1     ,Q2V    ,Q2B    ,Q2E    ,CHV  ,CHB, EMISSI,PAH  ,&\n\t\t     SHG,SHC,SHB,EVG,EVB,GHV,GHB,IRG,IRC,IRB,TR,EVC,CHLEAF,CHUC,CHV2,CHB2 )   !out\n!jref:end\n\n! --------------------------------------------------------------------------------------------------\n! we use different approaches to deal with subgrid features of radiation transfer and turbulent\n! transfer. We use 'tile' approach to compute turbulent fluxes, while we use modified two-\n! stream to compute radiation transfer. Tile approach, assemblying vegetation canopies together,\n! may expose too much ground surfaces (either covered by snow or grass) to solar radiation. The\n! modified two-stream assumes vegetation covers fully the gridcell but with gaps between tree\n! crowns.\n! --------------------------------------------------------------------------------------------------\n! turbulence transfer : 'tile' approach to compute energy fluxes in vegetated fraction and\n!                         bare fraction separately and then sum them up weighted by fraction\n!                     --------------------------------------\n!                    / O  O  O  O  O  O  O  O  /          /\n!                   /  |  |  |  |  |  |  |  | /          /\n!                  / O  O  O  O  O  O  O  O  /          /\n!                 /  |  |  |tile1|  |  |  | /  tile2   /\n!                / O  O  O  O  O  O  O  O  /  bare    /\n!               /  |  |  | vegetated |  | /          /\n!              / O  O  O  O  O  O  O  O  /          /\n!             /  |  |  |  |  |  |  |  | /          /\n!            --------------------------------------\n! --------------------------------------------------------------------------------------------------\n! radiation transfer : modified two-stream (Yang and Friedl, 2003, JGR; Niu ang Yang, 2004, JGR)\n!                     --------------------------------------  two-stream treats leaves as\n!                    /   O   O   O   O   O   O   O   O    /  cloud over the entire grid-cell,\n!                   /    |   |   |   |   |   |   |   |   / while the modified two-stream\n!                  /   O   O   O   O   O   O   O   O    / aggregates cloudy leaves into\n!                 /    |   |   |   |   |   |   |   |   / tree crowns with gaps (as shown in\n!                /   O   O   O   O   O   O   O   O    / the left figure). We assume these\n!               /    |   |   |   |   |   |   |   |   / tree crowns are evenly distributed\n!              /   O   O   O   O   O   O   O   O    / within the gridcell with 100% veg\n!             /    |   |   |   |   |   |   |   |   / fraction, but with gaps. The 'tile'\n!            -------------------------------------- approach overlaps too much shadows.\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n  type (noahmp_parameters), intent(in) :: parameters\n  integer                           , INTENT(IN)    :: ILOC\n  integer                           , INTENT(IN)    :: JLOC\n  INTEGER                           , INTENT(IN)    :: ICE    !ice (ice = 1)\n  INTEGER                           , INTENT(IN)    :: VEGTYP !vegetation physiology type\n  INTEGER                           , INTENT(IN)    :: IST    !surface type: 1->soil; 2->lake\n  INTEGER                           , INTENT(IN)    :: NSNOW  !maximum no. of snow layers\n  INTEGER                           , INTENT(IN)    :: NSOIL  !number of soil layers\n  INTEGER                           , INTENT(IN)    :: ISNOW  !actual no. of snow layers\n  REAL                              , INTENT(IN)    :: DT     !time step [sec]\n  REAL                              , INTENT(IN)    :: QSNOW  !snowfall on the ground (mm/s)\n  REAL                              , INTENT(IN)    :: RHOAIR !density air (kg/m3)\n  REAL                              , INTENT(IN)    :: EAIR   !vapor pressure air (pa)\n  REAL                              , INTENT(IN)    :: SFCPRS !pressure (pa)\n  REAL                              , INTENT(IN)    :: QAIR   !specific humidity (kg/kg)\n  REAL                              , INTENT(IN)    :: SFCTMP !air temperature (k)\n  REAL                              , INTENT(IN)    :: THAIR  !potential temperature (k)\n  REAL                              , INTENT(IN)    :: LWDN   !downward longwave radiation (w/m2)\n  REAL                              , INTENT(IN)    :: UU     !wind speed in e-w dir (m/s)\n  REAL                              , INTENT(IN)    :: VV     !wind speed in n-s dir (m/s)\n  REAL   , DIMENSION(       1:    2), INTENT(IN)    :: SOLAD  !incoming direct solar rad. (w/m2)\n  REAL   , DIMENSION(       1:    2), INTENT(IN)    :: SOLAI  !incoming diffuse solar rad. (w/m2)\n  REAL                              , INTENT(IN)    :: COSZ   !cosine solar zenith angle (0-1)\n  REAL                              , INTENT(IN)    :: ELAI   !LAI adjusted for burying by snow\n  REAL                              , INTENT(IN)    :: ESAI   !LAI adjusted for burying by snow\n  REAL                              , INTENT(IN)    :: FWET   !fraction of canopy that is wet [-]\n  REAL                              , INTENT(IN)    :: FVEG   !greeness vegetation fraction (-)\n  REAL                              , INTENT(IN)    :: LAT    !latitude (radians)\n  REAL                              , INTENT(IN)    :: CANLIQ !canopy-intercepted liquid water (mm)\n  REAL                              , INTENT(IN)    :: CANICE !canopy-intercepted ice mass (mm)\n  REAL                              , INTENT(IN)    :: FOLN   !foliage nitrogen (%)\n  REAL                              , INTENT(IN)    :: CO2AIR !atmospheric co2 concentration (pa)\n  REAL                              , INTENT(IN)    :: O2AIR  !atmospheric o2 concentration (pa)\n  REAL                              , INTENT(IN)    :: IGS    !growing season index (0=off, 1=on)\n\n  REAL                              , INTENT(IN)    :: ZREF   !reference height (m)\n  REAL                              , INTENT(IN)    :: TBOT   !bottom condition for soil temp. (k)\n  REAL   , DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)    :: ZSNSO  !layer-bottom depth from snow surf [m]\n  REAL   , DIMENSION(       1:NSOIL), INTENT(IN)    :: ZSOIL  !layer-bottom depth from soil surf [m]\n  REAL   , DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)    :: DZSNSO !depth of snow & soil layer-bottom [m]\n  REAL, INTENT(IN)   :: PAHV    !precipitation advected heat - vegetation net (W/m2)\n  REAL, INTENT(IN)   :: PAHG    !precipitation advected heat - under canopy net (W/m2)\n  REAL, INTENT(IN)   :: PAHB    !precipitation advected heat - bare ground net (W/m2)\n\n!jref:start; in\n  REAL                              , INTENT(IN)    :: QC     !cloud water mixing ratio\n  REAL                              , INTENT(INOUT) :: QSFC   !mixing ratio at lowest model layer\n  REAL                              , INTENT(IN)    :: PSFC   !pressure at lowest model layer\n  REAL                              , INTENT(IN)    :: DX     !horisontal resolution\n  REAL                              , INTENT(IN)    :: DZ8W   !thickness of lowest layer\n  REAL                              , INTENT(IN)    :: Q2     !mixing ratio (kg/kg)\n!jref:end\n\n! outputs\n  REAL                              , INTENT(OUT)   :: Z0WRF  !combined z0 sent to coupled model\n  INTEGER, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT)   :: IMELT  !phase change index [1-melt; 2-freeze]\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(OUT)   :: SNICEV !partial volume ice [m3/m3]\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(OUT)   :: SNLIQV !partial volume liq. water [m3/m3]\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(OUT)   :: EPORE  !effective porosity [m3/m3]\n  REAL                              , INTENT(OUT)   :: FSNO   !snow cover fraction (-)\n  REAL                              , INTENT(OUT)   :: QMELT  !snowmelt [mm/s]\n  REAL                              , INTENT(OUT)   :: PONDING!pounding at ground [mm]\n  REAL                              , INTENT(OUT)   :: SAV    !solar rad. absorbed by veg. (w/m2)\n  REAL                              , INTENT(OUT)   :: SAG    !solar rad. absorbed by ground (w/m2)\n  REAL                              , INTENT(OUT)   :: FSA    !tot. absorbed solar radiation (w/m2)\n  REAL                              , INTENT(OUT)   :: FSR    !tot. reflected solar radiation (w/m2)\n  REAL                              , INTENT(OUT)   :: TAUX   !wind stress: e-w (n/m2)\n  REAL                              , INTENT(OUT)   :: TAUY   !wind stress: n-s (n/m2)\n  REAL                              , INTENT(OUT)   :: FIRA   !total net LW. rad (w/m2)   [+ to atm]\n  REAL                              , INTENT(OUT)   :: FSH    !total sensible heat (w/m2) [+ to atm]\n  REAL                              , INTENT(OUT)   :: FCEV   !canopy evaporation (w/m2)  [+ to atm]\n  REAL                              , INTENT(OUT)   :: FGEV   !ground evaporation (w/m2)  [+ to atm]\n  REAL                              , INTENT(OUT)   :: FCTR   !transpiration (w/m2)       [+ to atm]\n  REAL                              , INTENT(OUT)   :: TRAD   !radiative temperature (k)\n  REAL                              , INTENT(OUT)   :: T2M    !2 m height air temperature (k)\n  REAL                              , INTENT(OUT)   :: PSN    !total photosyn. (umolco2/m2/s) [+]\n  REAL                              , INTENT(OUT)   :: APAR   !total photosyn. active energy (w/m2)\n  REAL                              , INTENT(OUT)   :: SSOIL  !ground heat flux (w/m2)   [+ to soil]\n  REAL   , DIMENSION(       1:NSOIL), INTENT(OUT)   :: BTRANI !soil water transpiration factor (0-1)\n  REAL                              , INTENT(OUT)   :: BTRAN  !soil water transpiration factor (0-1)\n!  REAL                              , INTENT(OUT)   :: LATHEA !latent heat vap./sublimation (j/kg)\n  REAL                              , INTENT(OUT)   :: LATHEAV !latent heat vap./sublimation (j/kg)\n  REAL                              , INTENT(OUT)   :: LATHEAG !latent heat vap./sublimation (j/kg)\n  LOGICAL                           , INTENT(OUT)   :: FROZEN_GROUND ! used to define latent heat pathway\n  LOGICAL                           , INTENT(OUT)   :: FROZEN_CANOPY ! used to define latent heat pathway\n\n!jref:start\n  REAL                              , INTENT(OUT)   :: FSRV    !veg. reflected solar radiation (w/m2)\n  REAL                              , INTENT(OUT)   :: FSRG    !ground reflected solar radiation (w/m2)\n  REAL, INTENT(OUT) :: RSSUN        !sunlit leaf stomatal resistance (s/m)\n  REAL, INTENT(OUT) :: RSSHA        !shaded leaf stomatal resistance (s/m)\n!jref:end - out for debug\n\n!jref:start; output\n  REAL                              , INTENT(OUT)   :: T2MV   !2-m air temperature over vegetated part [k]\n  REAL                              , INTENT(OUT)   :: T2MB   !2-m air temperature over bare ground part [k]\n  REAL                              , INTENT(OUT)   :: BGAP\n  REAL                              , INTENT(OUT)   :: WGAP\n  REAL, DIMENSION(1:2)              , INTENT(OUT)   :: ALBSND   !snow albedo (direct)\n  REAL, DIMENSION(1:2)              , INTENT(OUT)   :: ALBSNI   !snow albedo (diffuse)\n!jref:end\n\n! input & output\n  REAL                              , INTENT(INOUT) :: TS     !surface temperature (k)\n  REAL                              , INTENT(INOUT) :: TV     !vegetation temperature (k)\n  REAL                              , INTENT(INOUT) :: TG     !ground temperature (k)\n  REAL   , DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow/soil temperature [k]\n  REAL                              , INTENT(INOUT) :: SNOWH  !snow height [m]\n  REAL                              , INTENT(INOUT) :: SNEQV  !snow mass (mm)\n  REAL                              , INTENT(INOUT) :: SNEQVO !snow mass at last time step (mm)\n  REAL   , DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O   !liquid soil moisture [m3/m3]\n  REAL   , DIMENSION(       1:NSOIL), INTENT(INOUT) :: SMC    !soil moisture (ice + liq.) [m3/m3]\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE  !snow ice mass (kg/m2)\n  REAL   , DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ  !snow liq mass (kg/m2)\n  REAL                              , INTENT(INOUT) :: EAH    !canopy air vapor pressure (pa)\n  REAL                              , INTENT(INOUT) :: TAH    !canopy air temperature (k)\n  REAL                              , INTENT(INOUT) :: ALBOLD !snow albedo at last time step(CLASS type)\n  REAL                              , INTENT(INOUT) :: TAUSS  !non-dimensional snow age\n  REAL                              , INTENT(INOUT) :: CM     !momentum drag coefficient\n  REAL                              , INTENT(INOUT) :: CH     !sensible heat exchange coefficient\n  REAL                              , INTENT(INOUT) :: Q1\n  REAL                              , INTENT(INOUT) :: RB     !leaf boundary layer resistance (s/m)\n  REAL                              , INTENT(INOUT) :: LAISUN !sunlit leaf area index (m2/m2)\n  REAL                              , INTENT(INOUT) :: LAISHA !shaded leaf area index (m2/m2)\n!  REAL                                              :: Q2E\n  REAL,                               INTENT(OUT)   :: EMISSI\n  REAL,                               INTENT(OUT)   :: PAH    !precipitation advected heat - total (W/m2)\n\n! local\n  INTEGER                                           :: IZ     !do-loop index\n  LOGICAL                                           :: VEG    !true if vegetated surface\n  REAL                                              :: UR     !wind speed at height ZLVL (m/s)\n  REAL                                              :: ZLVL   !reference height (m)\n  REAL                                              :: FSUN   !sunlit fraction of canopy [-]\n ! REAL                                              :: RB     !leaf boundary layer resistance (s/m)\n  REAL                                              :: RSURF  !ground surface resistance (s/m)\n  REAL                                              :: L_RSURF!Dry-layer thickness for computing RSURF (Sakaguchi and Zeng, 2009)\n  REAL                                              :: D_RSURF!Reduced vapor diffusivity in soil for computing RSURF (SZ09)\n  REAL                                              :: BEVAP  !soil water evaporation factor (0- 1)\n  REAL                                              :: MOL    !Monin-Obukhov length (m)\n  REAL                                              :: VAI    !sum of LAI  + stem area index [m2/m2]\n  REAL                                              :: CWP    !canopy wind extinction parameter\n  REAL                                              :: ZPD    !zero plane displacement (m)\n  REAL                                              :: Z0M    !z0 momentum (m)\n  REAL                                              :: ZPDG   !zero plane displacement (m)\n  REAL                                              :: Z0MG   !z0 momentum, ground (m)\n  REAL                                              :: EMV    !vegetation emissivity\n  REAL                                              :: EMG    !ground emissivity\n  REAL                                              :: FIRE   !emitted IR (w/m2)\n\n  REAL                                              :: PSNSUN !sunlit photosynthesis (umolco2/m2/s)\n  REAL                                              :: PSNSHA !shaded photosynthesis (umolco2/m2/s)\n!jref:start - for debug\n!  REAL                                              :: RSSUN  !sunlit stomatal resistance (s/m)\n!  REAL                                              :: RSSHA  !shaded stomatal resistance (s/m)\n!jref:end - for debug\n  REAL                                              :: PARSUN !par absorbed per sunlit LAI (w/m2)\n  REAL                                              :: PARSHA !par absorbed per shaded LAI (w/m2)\n\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                   :: FACT   !temporary used in phase change\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                   :: DF     !thermal conductivity [w/m/k]\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                   :: HCPCT  !heat capacity [j/m3/k]\n  REAL                                              :: BDSNO  !bulk density of snow (kg/m3)\n  REAL                                              :: FMELT  !melting factor for snow cover frac\n  REAL                                              :: GX     !temporary variable\n  REAL, DIMENSION(-NSNOW+1:NSOIL)                   :: PHI    !light through water (w/m2)\n!  REAL                                              :: GAMMA  !psychrometric constant (pa/k)\n  REAL                                              :: GAMMAV  !psychrometric constant (pa/k)\n  REAL                                              :: GAMMAG  !psychrometric constant (pa/k)\n  REAL                                              :: PSI    !surface layer soil matrix potential (m)\n  REAL                                              :: RHSUR  !raltive humidity in surface soil/snow air space (-)\n\n! temperature and fluxes over vegetated fraction\n\n  REAL                                              :: TAUXV  !wind stress: e-w dir [n/m2]\n  REAL                                              :: TAUYV  !wind stress: n-s dir [n/m2]\n  REAL,INTENT(OUT)                                              :: IRC    !canopy net LW rad. [w/m2] [+ to atm]\n  REAL,INTENT(OUT)                                              :: IRG    !ground net LW rad. [w/m2] [+ to atm]\n  REAL,INTENT(OUT)                                              :: SHC    !canopy sen. heat [w/m2]   [+ to atm]\n  REAL,INTENT(OUT)                                              :: SHG    !ground sen. heat [w/m2]   [+ to atm]\n!jref:start\n  REAL,INTENT(OUT)                                  :: Q2V\n  REAL,INTENT(OUT)                                  :: Q2B\n  REAL,INTENT(OUT)                                  :: Q2E\n!jref:end\n  REAL,INTENT(OUT)                                              :: EVC    !canopy evap. heat [w/m2]  [+ to atm]\n  REAL,INTENT(OUT)                                              :: EVG    !ground evap. heat [w/m2]  [+ to atm]\n  REAL,INTENT(OUT)                                              :: TR     !transpiration heat [w/m2] [+ to atm]\n  REAL,INTENT(OUT)                                              :: GHV    !ground heat flux [w/m2]  [+ to soil]\n  REAL,INTENT(OUT)                                  :: TGV    !ground surface temp. [k]\n  REAL                                              :: CMV    !momentum drag coefficient\n  REAL,INTENT(OUT)                                  :: CHV    !sensible heat exchange coefficient\n\n! temperature and fluxes over bare soil fraction\n\n  REAL                                              :: TAUXB  !wind stress: e-w dir [n/m2]\n  REAL                                              :: TAUYB  !wind stress: n-s dir [n/m2]\n  REAL,INTENT(OUT)                                              :: IRB    !net longwave rad. [w/m2] [+ to atm]\n  REAL,INTENT(OUT)                                              :: SHB    !sensible heat [w/m2]     [+ to atm]\n  REAL,INTENT(OUT)                                              :: EVB    !evaporation heat [w/m2]  [+ to atm]\n  REAL,INTENT(OUT)                                              :: GHB    !ground heat flux [w/m2] [+ to soil]\n  REAL,INTENT(OUT)                                  :: TGB    !ground surface temp. [k]\n  REAL                                              :: CMB    !momentum drag coefficient\n  REAL,INTENT(OUT)                                  :: CHB    !sensible heat exchange coefficient\n  REAL,INTENT(OUT)                                  :: CHLEAF !leaf exchange coefficient\n  REAL,INTENT(OUT)                                  :: CHUC   !under canopy exchange coefficient\n!jref:start\n  REAL,INTENT(OUT)                                  :: CHV2    !sensible heat conductance, canopy air to ZLVL air (m/s)\n  REAL,INTENT(OUT)                                  :: CHB2    !sensible heat conductance, canopy air to ZLVL air (m/s)\n  REAL                                  :: noahmpres\n\n!jref:end\n\n  REAL, PARAMETER                   :: MPE    = 1.E-6\n  REAL, PARAMETER                   :: PSIWLT = -150.  !metric potential for wilting point (m)\n  REAL, PARAMETER                   :: Z0     = 0.002  ! Bare-soil roughness length (m) (i.e., under the canopy)\n\n! ---------------------------------------------------------------------------------------------------\n! initialize fluxes from veg. fraction\n\n    TAUXV     = 0.\n    TAUYV     = 0.\n    IRC       = 0.\n    SHC       = 0.\n    IRG       = 0.\n    SHG       = 0.\n    EVG       = 0.\n    EVC       = 0.\n    TR        = 0.\n    GHV       = 0.\n    PSNSUN    = 0.\n    PSNSHA    = 0.\n    T2MV      = 0.\n    Q2V       = 0.\n    CHV       = 0.\n    CHLEAF    = 0.\n    CHUC      = 0.\n    CHV2      = 0.\n    RB        = 0.\n\n! wind speed at reference height: ur >= 1\n\n    UR = MAX( SQRT(UU**2.+VV**2.), 1. )\n\n! vegetated or non-vegetated\n\n    VAI = ELAI + ESAI\n    VEG = .FALSE.\n    IF(VAI > 0.) VEG = .TRUE.\n\n! ground snow cover fraction [Niu and Yang, 2007, JGR]\n\n     FSNO = 0.\n     IF(SNOWH.GT.0.)  THEN\n         BDSNO    = SNEQV / SNOWH\n         FMELT    = (BDSNO/100.)**parameters%MFSNO\n         FSNO     = parameters%SCAMAX * TANH( SNOWH /(2.5* Z0 * FMELT))\n     ENDIF\n\n! ground roughness length\n\n     IF(IST == 2) THEN\n       IF(TG .LE. TFRZ) THEN\n         Z0MG = 0.01 * (1.0-FSNO) + FSNO * parameters%Z0SNO\n       ELSE\n         Z0MG = 0.01\n       END IF\n     ELSE\n       Z0MG = Z0 * (1.0-FSNO) + FSNO * parameters%Z0SNO\n     END IF\n\n! roughness length and displacement height\n\n     ZPDG  = SNOWH\n     IF(VEG) THEN\n        Z0M  = parameters%Z0MVT\n        ZPD  = 0.65 * parameters%HVT\n        IF(SNOWH.GT.ZPD) ZPD  = SNOWH\n     ELSE\n        Z0M  = Z0MG\n        ZPD  = ZPDG\n     END IF\n\n! special case for urban\n\n     IF (parameters%urban_flag) THEN\n       Z0MG = parameters%Z0MVT\n       ZPDG  = 0.65 * parameters%HVT\n       Z0M  = Z0MG\n       ZPD  = ZPDG\n     END IF\n\n     ZLVL = MAX(ZPD,parameters%HVT) + ZREF\n     IF(ZPDG >= ZLVL) ZLVL = ZPDG + ZREF\n!     UR   = UR*LOG(ZLVL/Z0M)/LOG(10./Z0M)       !input UR is at 10m\n\n! canopy wind absorption coeffcient\n\n     CWP = parameters%CWPVT\n\n! Thermal properties of soil, snow, lake, and frozen soil\n\n  CALL THERMOPROP (parameters,NSOIL   ,NSNOW   ,ISNOW   ,IST     ,DZSNSO  , & !in\n                   DT      ,SNOWH   ,SNICE   ,SNLIQ   , & !in\n                   SMC     ,SH2O    ,TG      ,STC     ,UR      , & !in\n                   LAT     ,Z0M     ,ZLVL    ,VEGTYP  , & !in\n                   DF      ,HCPCT   ,SNICEV  ,SNLIQV  ,EPORE   , & !out\n                   FACT    )                              !out\n\n! Solar radiation: absorbed & reflected by the ground and canopy\n\n  CALL  RADIATION (parameters,VEGTYP  ,IST     ,ICE     ,NSOIL   , & !in\n                   SNEQVO  ,SNEQV   ,DT      ,COSZ    ,SNOWH   , & !in\n                   TG      ,TV      ,FSNO    ,QSNOW   ,FWET    , & !in\n                   ELAI    ,ESAI    ,SMC     ,SOLAD   ,SOLAI   , & !in\n                   FVEG    ,ILOC    ,JLOC    ,                   & !in\n                   ALBOLD  ,TAUSS   ,                            & !inout\n                   FSUN    ,LAISUN  ,LAISHA  ,PARSUN  ,PARSHA  , & !out\n                   SAV     ,SAG     ,FSR     ,FSA     ,FSRV    , &\n                   FSRG    ,ALBSND  ,ALBSNI  ,BGAP    ,WGAP     )  !out\n\n! vegetation and ground emissivity\n\n     EMV = 1. - EXP(-(ELAI+ESAI)/1.0)\n     IF (ICE == 1) THEN\n       EMG = 0.98*(1.-FSNO) + 1.0*FSNO\n     ELSE\n       EMG = parameters%EG(IST)*(1.-FSNO) + 1.0*FSNO\n     END IF\n\n! soil moisture factor controlling stomatal resistance\n\n     BTRAN = 0.\n\n     IF(IST ==1 ) THEN\n       DO IZ = 1, parameters%NROOT\n          IF(OPT_BTR == 1) then                  ! Noah\n            GX    = (SH2O(IZ)-parameters%SMCWLT(IZ)) / (parameters%SMCREF(IZ)-parameters%SMCWLT(IZ))\n          END IF\n          IF(OPT_BTR == 2) then                  ! CLM\n            PSI   = MAX(PSIWLT,-parameters%PSISAT(IZ)*(MAX(0.01,SH2O(IZ))/parameters%SMCMAX(IZ))**(-parameters%BEXP(IZ)) )\n            GX    = (1.-PSI/PSIWLT)/(1.+parameters%PSISAT(IZ)/PSIWLT)\n          END IF\n          IF(OPT_BTR == 3) then                  ! SSiB\n            PSI   = MAX(PSIWLT,-parameters%PSISAT(IZ)*(MAX(0.01,SH2O(IZ))/parameters%SMCMAX(IZ))**(-parameters%BEXP(IZ)) )\n            GX    = 1.-EXP(-5.8*(LOG(PSIWLT/PSI)))\n          END IF\n\n          GX = MIN(1.,MAX(0.,GX))\n          BTRANI(IZ) = MAX(MPE,DZSNSO(IZ) / (-ZSOIL(parameters%NROOT)) * GX)\n          BTRAN      = BTRAN + BTRANI(IZ)\n       END DO\n       BTRAN = MAX(MPE,BTRAN)\n\n       BTRANI(1:parameters%NROOT) = BTRANI(1:parameters%NROOT)/BTRAN\n     END IF\n\n! soil surface resistance for ground evap.\n\n     BEVAP = MAX(0.0,SH2O(1)/parameters%SMCMAX(1))\n     IF(IST == 2) THEN\n       RSURF = 1.          ! avoid being divided by 0\n       RHSUR = 1.0\n     ELSE\n\n       IF(OPT_RSF == 1 .OR. OPT_RSF == 4) THEN\n         ! RSURF based on Sakaguchi and Zeng, 2009\n         ! taking the \"residual water content\" to be the wilting point,\n         ! and correcting the exponent on the D term (typo in SZ09 ?)\n         L_RSURF = (-ZSOIL(1)) * ( exp ( (1.0 - MIN(1.0,SH2O(1)/parameters%SMCMAX(1))) ** parameters%RSURF_EXP ) - 1.0 ) / ( 2.71828 - 1.0 )\n         D_RSURF = 2.2E-5 * parameters%SMCMAX(1) * parameters%SMCMAX(1) * ( 1.0 - parameters%SMCWLT(1) / parameters%SMCMAX(1) ) ** (2.0+3.0/parameters%BEXP(1))\n         RSURF = L_RSURF / D_RSURF\n       ELSEIF(OPT_RSF == 2) THEN\n         RSURF = FSNO * 1. + (1.-FSNO)* EXP(8.25-4.225*BEVAP) !Sellers (1992) ! Older RSURF computations\n       ELSEIF(OPT_RSF == 3) THEN\n         RSURF = FSNO * 1. + (1.-FSNO)* EXP(8.25-6.0  *BEVAP) !adjusted to decrease RSURF for wet soil\n       ENDIF\n\n       IF(OPT_RSF == 4) THEN  ! AD: FSNO weighted; snow RSURF set in MPTABLE v3.8\n         RSURF = 1. / (FSNO * (1./parameters%RSURF_SNOW) + (1.-FSNO) * (1./max(RSURF, 0.001)))\n       ENDIF\n\n       IF(SH2O(1) < 0.01 .and. SNOWH == 0.) RSURF = 1.E6\n       PSI   = -parameters%PSISAT(1)*(MAX(0.01,SH2O(1))/parameters%SMCMAX(1))**(-parameters%BEXP(1))\n       RHSUR = FSNO + (1.-FSNO) * EXP(PSI*GRAV/(RW*TG))\n     END IF\n\n! urban - jref\n     IF (parameters%urban_flag .and. SNOWH == 0. ) THEN\n        RSURF = 1.E6\n     ENDIF\n\n! set psychrometric constant\n\n     IF (TV .GT. TFRZ) THEN           ! Barlage: add distinction between ground and\n        LATHEAV = HVAP                ! vegetation in v3.6\n\tfrozen_canopy = .false.\n     ELSE\n        LATHEAV = HSUB\n\tfrozen_canopy = .true.\n     END IF\n     GAMMAV = CPAIR*SFCPRS/(0.622*LATHEAV)\n\n     IF (TG .GT. TFRZ) THEN\n        LATHEAG = HVAP\n\tfrozen_ground = .false.\n     ELSE\n        LATHEAG = HSUB\n\tfrozen_ground = .true.\n     END IF\n     GAMMAG = CPAIR*SFCPRS/(0.622*LATHEAG)\n\n!     IF (SFCTMP .GT. TFRZ) THEN\n!        LATHEA = HVAP\n!     ELSE\n!        LATHEA = HSUB\n!     END IF\n!     GAMMA = CPAIR*SFCPRS/(0.622*LATHEA)\n\n! Surface temperatures of the ground and canopy and energy fluxes\n\n    IF (VEG .AND. FVEG > 0) THEN\n    TGV = TG\n    CMV = CM\n    CHV = CH\n    CALL VEGE_FLUX (parameters,NSNOW   ,NSOIL   ,ISNOW   ,VEGTYP  ,VEG     , & !in\n                    DT      ,SAV     ,SAG     ,LWDN    ,UR      , & !in\n                    UU      ,VV      ,SFCTMP  ,THAIR   ,QAIR    , & !in\n                    EAIR    ,RHOAIR  ,SNOWH   ,VAI     ,GAMMAV   ,GAMMAG   , & !in\n                    FWET    ,LAISUN  ,LAISHA  ,CWP     ,DZSNSO  , & !in\n                    ZLVL    ,ZPD     ,Z0M     ,FVEG    , & !in\n                    Z0MG    ,EMV     ,EMG     ,CANLIQ  ,FSNO, & !in\n                    CANICE  ,STC     ,DF      ,RSSUN   ,RSSHA   , & !in\n                    RSURF   ,LATHEAV ,LATHEAG ,PARSUN  ,PARSHA  ,IGS     , & !in\n                    FOLN    ,CO2AIR  ,O2AIR   ,BTRAN   ,SFCPRS  , & !in\n                    RHSUR   ,ILOC    ,JLOC    ,Q2      ,PAHV  ,PAHG  , & !in\n                    EAH     ,TAH     ,TV      ,TGV     ,CMV     , & !inout\n                    CHV     ,DX      ,DZ8W    ,                   & !inout\n                    TAUXV   ,TAUYV   ,IRG     ,IRC     ,SHG     , & !out\n                    SHC     ,EVG     ,EVC     ,TR      ,GHV     , & !out\n                    T2MV    ,PSNSUN  ,PSNSHA  ,                   & !out\n!jref:start\n                    QC      ,QSFC    ,PSFC    , & !in\n                    Q2V     ,CHV2, CHLEAF, CHUC)               !inout\n!jref:end\n    END IF\n\n    TGB = TG\n    CMB = CM\n    CHB = CH\n    CALL BARE_FLUX (parameters,NSNOW   ,NSOIL   ,ISNOW   ,DT      ,SAG     , & !in\n                    LWDN    ,UR      ,UU      ,VV      ,SFCTMP  , & !in\n                    THAIR   ,QAIR    ,EAIR    ,RHOAIR  ,SNOWH   , & !in\n                    DZSNSO  ,ZLVL    ,ZPDG    ,Z0MG    ,FSNO,          & !in\n                    EMG     ,STC     ,DF      ,RSURF   ,LATHEAG  , & !in\n                    GAMMAG   ,RHSUR   ,ILOC    ,JLOC    ,Q2      ,PAHB  , & !in\n                    TGB     ,CMB     ,CHB     ,                   & !inout\n                    TAUXB   ,TAUYB   ,IRB     ,SHB     ,EVB     , & !out\n                    GHB     ,T2MB    ,DX      ,DZ8W    ,VEGTYP  , & !out\n!jref:start\n                    QC      ,QSFC    ,PSFC    , & !in\n                    SFCPRS  ,Q2B,   CHB2)                          !in\n!jref:end\n\n!energy balance at vege canopy: SAV          =(IRC+SHC+EVC+TR)     *FVEG  at   FVEG\n!energy balance at vege ground: SAG*    FVEG =(IRG+SHG+EVG+GHV)    *FVEG  at   FVEG\n!energy balance at bare ground: SAG*(1.-FVEG)=(IRB+SHB+EVB+GHB)*(1.-FVEG) at 1-FVEG\n\n    IF (VEG .AND. FVEG > 0) THEN\n        TAUX  = FVEG * TAUXV     + (1.0 - FVEG) * TAUXB\n        TAUY  = FVEG * TAUYV     + (1.0 - FVEG) * TAUYB\n        FIRA  = FVEG * IRG       + (1.0 - FVEG) * IRB       + IRC\n        FSH   = FVEG * SHG       + (1.0 - FVEG) * SHB       + SHC\n        FGEV  = FVEG * EVG       + (1.0 - FVEG) * EVB\n        SSOIL = FVEG * GHV       + (1.0 - FVEG) * GHB\n        FCEV  = EVC\n        FCTR  = TR\n\tPAH   = FVEG * PAHG      + (1.0 - FVEG) * PAHB   + PAHV\n        TG    = FVEG * TGV       + (1.0 - FVEG) * TGB\n        T2M   = FVEG * T2MV      + (1.0 - FVEG) * T2MB\n        TS    = FVEG * TV        + (1.0 - FVEG) * TGB\n        CM    = FVEG * CMV       + (1.0 - FVEG) * CMB      ! better way to average?\n        CH    = FVEG * CHV       + (1.0 - FVEG) * CHB\n        Q1    = FVEG * (EAH*0.622/(SFCPRS - 0.378*EAH)) + (1.0 - FVEG)*QSFC\n        Q2E   = FVEG * Q2V       + (1.0 - FVEG) * Q2B\n\tZ0WRF = Z0M\n    ELSE\n        TAUX  = TAUXB\n        TAUY  = TAUYB\n        FIRA  = IRB\n        FSH   = SHB\n        FGEV  = EVB\n        SSOIL = GHB\n        TG    = TGB\n        T2M   = T2MB\n        FCEV  = 0.\n        FCTR  = 0.\n\tPAH   = PAHB\n        TS    = TG\n        CM    = CMB\n        CH    = CHB\n        Q1    = QSFC\n        Q2E   = Q2B\n        RSSUN = 0.0\n        RSSHA = 0.0\n        TGV   = TGB\n        CHV   = CHB\n\tZ0WRF = Z0MG\n    END IF\n\n    FIRE = LWDN + FIRA\n\n    IF(FIRE <=0.) THEN\n       WRITE(6,*) 'emitted longwave <0; skin T may be wrong due to inconsistent'\n       WRITE(6,*) 'input of SHDFAC with LAI'\n       WRITE(6,*) ILOC, JLOC, 'SHDFAC=',FVEG,'VAI=',VAI,'TV=',TV,'TG=',TG\n       WRITE(6,*) 'LWDN=',LWDN,'FIRA=',FIRA,'SNOWH=',SNOWH\n       call wrf_error_fatal(\"STOP in Noah-MP\")\n    END IF\n\n    ! Compute a net emissivity\n    EMISSI = FVEG * ( EMG*(1-EMV) + EMV + EMV*(1-EMV)*(1-EMG) ) + &\n         (1-FVEG) * EMG\n\n    ! When we're computing a TRAD, subtract from the emitted IR the\n    ! reflected portion of the incoming LWDN, so we're just\n    ! considering the IR originating in the canopy/ground system.\n\n    TRAD = ( ( FIRE - (1-EMISSI)*LWDN ) / (EMISSI*SB) ) ** 0.25\n\n    ! Old TRAD calculation not taking into account Emissivity:\n    ! TRAD = (FIRE/SB)**0.25\n\n    APAR = PARSUN*LAISUN + PARSHA*LAISHA\n    PSN  = PSNSUN*LAISUN + PSNSHA*LAISHA\n\n! 3L snow & 4L soil temperatures\n\n    CALL TSNOSOI (parameters,ICE     ,NSOIL   ,NSNOW   ,ISNOW   ,IST     , & !in\n                  TBOT    ,ZSNSO   ,SSOIL   ,DF      ,HCPCT   , & !in\n                  SAG     ,DT      ,SNOWH   ,DZSNSO  , & !in\n                  TG      ,ILOC    ,JLOC    ,                   & !in\n                  STC     )                                       !inout\n\n! adjusting snow surface temperature\n     IF(OPT_STC == 2) THEN\n      IF (SNOWH > 0.05 .AND. TG > TFRZ) THEN\n        TGV = TFRZ\n        TGB = TFRZ\n          IF (VEG .AND. FVEG > 0) THEN\n             TG    = FVEG * TGV       + (1.0 - FVEG) * TGB\n             TS    = FVEG * TV        + (1.0 - FVEG) * TGB\n          ELSE\n             TG    = TGB\n             TS    = TGB\n          END IF\n      END IF\n     END IF\n\n! Energy released or consumed by snow & frozen soil\n\n CALL PHASECHANGE (parameters,NSNOW   ,NSOIL   ,ISNOW   ,DT      ,FACT    , & !in\n                   DZSNSO  ,HCPCT   ,IST     ,ILOC    ,JLOC    , & !in\n                   STC     ,SNICE   ,SNLIQ   ,SNEQV   ,SNOWH   , & !inout\n                   SMC     ,SH2O    ,                            & !inout\n                   QMELT   ,IMELT   ,PONDING )                     !out\n\n\n  END SUBROUTINE ENERGY\n\n!== begin thermoprop ===============================================================================\n\n  SUBROUTINE THERMOPROP (parameters,NSOIL   ,NSNOW   ,ISNOW   ,IST     ,DZSNSO  , & !in\n                         DT      ,SNOWH   ,SNICE   ,SNLIQ   , & !in\n                         SMC     ,SH2O    ,TG      ,STC     ,UR      , & !in\n                         LAT     ,Z0M     ,ZLVL    ,VEGTYP  , & !in\n                         DF      ,HCPCT   ,SNICEV  ,SNLIQV  ,EPORE   , & !out\n                         FACT    )                                       !out\n! -------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER                        , INTENT(IN)  :: NSOIL   !number of soil layers\n  INTEGER                        , INTENT(IN)  :: NSNOW   !maximum no. of snow layers\n  INTEGER                        , INTENT(IN)  :: ISNOW   !actual no. of snow layers\n  INTEGER                        , INTENT(IN)  :: IST     !surface type\n  REAL                           , INTENT(IN)  :: DT      !time step [s]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)  :: SNICE   !snow ice mass (kg/m2)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)  :: SNLIQ   !snow liq mass (kg/m2)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: DZSNSO  !thickness of snow/soil layers [m]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)  :: SMC     !soil moisture (ice + liq.) [m3/m3]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)  :: SH2O    !liquid soil moisture [m3/m3]\n  REAL                           , INTENT(IN)  :: SNOWH   !snow height [m]\n  REAL,                            INTENT(IN)  :: TG      !surface temperature (k)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: STC     !snow/soil/lake temp. (k)\n  REAL,                            INTENT(IN)  :: UR      !wind speed at ZLVL (m/s)\n  REAL,                            INTENT(IN)  :: LAT     !latitude (radians)\n  REAL,                            INTENT(IN)  :: Z0M     !roughness length (m)\n  REAL,                            INTENT(IN)  :: ZLVL    !reference height (m)\n  INTEGER                        , INTENT(IN)  :: VEGTYP  !vegtyp type\n\n! outputs\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: DF      !thermal conductivity [w/m/k]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: HCPCT   !heat capacity [j/m3/k]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: SNICEV  !partial volume of ice [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: SNLIQV  !partial volume of liquid water [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: EPORE   !effective porosity [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: FACT    !computing energy for phase change\n! --------------------------------------------------------------------------------------------------\n! locals\n\n  INTEGER :: IZ\n  REAL, DIMENSION(-NSNOW+1:    0)              :: CVSNO   !volumetric specific heat (j/m3/k)\n  REAL, DIMENSION(-NSNOW+1:    0)              :: TKSNO   !snow thermal conductivity (j/m3/k)\n  REAL, DIMENSION(       1:NSOIL)              :: SICE    !soil ice content\n! --------------------------------------------------------------------------------------------------\n\n! compute snow thermal conductivity and heat capacity\n\n    CALL CSNOW (parameters,ISNOW   ,NSNOW   ,NSOIL   ,SNICE   ,SNLIQ   ,DZSNSO  , & !in\n                TKSNO   ,CVSNO   ,SNICEV  ,SNLIQV  ,EPORE   )   !out\n\n    DO IZ = ISNOW+1, 0\n      DF   (IZ) = TKSNO(IZ)\n      HCPCT(IZ) = CVSNO(IZ)\n    END DO\n\n! compute soil thermal properties\n\n    DO  IZ = 1, NSOIL\n       SICE(IZ)  = SMC(IZ) - SH2O(IZ)\n       HCPCT(IZ) = SH2O(IZ)*CWAT + (1.0-parameters%SMCMAX(IZ))*parameters%CSOIL &\n                + (parameters%SMCMAX(IZ)-SMC(IZ))*CPAIR + SICE(IZ)*CICE\n       CALL TDFCND (parameters,IZ,DF(IZ), SMC(IZ), SH2O(IZ))\n    END DO\n\n    IF ( parameters%urban_flag ) THEN\n       DO IZ = 1,NSOIL\n         DF(IZ) = 3.24\n       END DO\n    ENDIF\n\n! heat flux reduction effect from the overlying green canopy, adapted from\n! section 2.1.2 of Peters-Lidard et al. (1997, JGR, VOL 102(D4)).\n! not in use because of the separation of the canopy layer from the ground.\n! but this may represent the effects of leaf litter (Niu comments)\n!       DF1 = DF1 * EXP (SBETA * SHDFAC)\n\n! compute lake thermal properties\n! (no consideration of turbulent mixing for this version)\n\n    IF(IST == 2) THEN\n       DO IZ = 1, NSOIL\n         IF(STC(IZ) > TFRZ) THEN\n            HCPCT(IZ) = CWAT\n            DF(IZ)    = TKWAT  !+ KEDDY * CWAT\n         ELSE\n            HCPCT(IZ) = CICE\n            DF(IZ)    = TKICE\n         END IF\n       END DO\n    END IF\n\n! combine a temporary variable used for melting/freezing of snow and frozen soil\n\n    DO IZ = ISNOW+1,NSOIL\n     FACT(IZ) = DT/(HCPCT(IZ)*DZSNSO(IZ))\n    END DO\n\n! snow/soil interface\n\n    IF(ISNOW == 0) THEN\n       DF(1) = (DF(1)*DZSNSO(1)+0.35*SNOWH)      / (SNOWH    +DZSNSO(1))\n    ELSE\n       DF(1) = (DF(1)*DZSNSO(1)+DF(0)*DZSNSO(0)) / (DZSNSO(0)+DZSNSO(1))\n    END IF\n\n\n  END SUBROUTINE THERMOPROP\n\n!== begin csnow ====================================================================================\n\n  SUBROUTINE CSNOW (parameters,ISNOW   ,NSNOW   ,NSOIL   ,SNICE   ,SNLIQ   ,DZSNSO  , & !in\n                    TKSNO   ,CVSNO   ,SNICEV  ,SNLIQV  ,EPORE   )   !out\n! --------------------------------------------------------------------------------------------------\n! Snow bulk density,volumetric capacity, and thermal conductivity\n!---------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n!---------------------------------------------------------------------------------------------------\n! inputs\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                          INTENT(IN) :: ISNOW  !number of snow layers (-)\n  INTEGER                        ,  INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  INTEGER                        ,  INTENT(IN) :: NSOIL  !number of soil layers\n  REAL, DIMENSION(-NSNOW+1:    0),  INTENT(IN) :: SNICE  !snow ice mass (kg/m2)\n  REAL, DIMENSION(-NSNOW+1:    0),  INTENT(IN) :: SNLIQ  !snow liq mass (kg/m2)\n  REAL, DIMENSION(-NSNOW+1:NSOIL),  INTENT(IN) :: DZSNSO !snow/soil layer thickness [m]\n\n! outputs\n\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: CVSNO  !volumetric specific heat (j/m3/k)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: TKSNO  !thermal conductivity (w/m/k)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: SNICEV !partial volume of ice [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: SNLIQV !partial volume of liquid water [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(OUT) :: EPORE  !effective porosity [m3/m3]\n\n! locals\n\n  INTEGER :: IZ\n  REAL, DIMENSION(-NSNOW+1:    0) :: BDSNOI  !bulk density of snow(kg/m3)\n\n!---------------------------------------------------------------------------------------------------\n! thermal capacity of snow\n\n  DO IZ = ISNOW+1, 0\n      SNICEV(IZ)   = MIN(1., SNICE(IZ)/(DZSNSO(IZ)*DENICE) )\n      EPORE(IZ)    = 1. - SNICEV(IZ)\n      SNLIQV(IZ)   = MIN(EPORE(IZ),SNLIQ(IZ)/(DZSNSO(IZ)*DENH2O))\n  ENDDO\n\n  DO IZ = ISNOW+1, 0\n      BDSNOI(IZ) = (SNICE(IZ)+SNLIQ(IZ))/DZSNSO(IZ)\n      CVSNO(IZ) = CICE*SNICEV(IZ)+CWAT*SNLIQV(IZ)\n!      CVSNO(IZ) = 0.525E06                          ! constant\n  enddo\n\n! thermal conductivity of snow\n\n  DO IZ = ISNOW+1, 0\n     TKSNO(IZ) = 3.2217E-6*BDSNOI(IZ)**2.           ! Stieglitz(yen,1965)\n!    TKSNO(IZ) = 2E-2+2.5E-6*BDSNOI(IZ)*BDSNOI(IZ)   ! Anderson, 1976\n!    TKSNO(IZ) = 0.35                                ! constant\n!    TKSNO(IZ) = 2.576E-6*BDSNOI(IZ)**2. + 0.074    ! Verseghy (1991)\n!    TKSNO(IZ) = 2.22*(BDSNOI(IZ)/1000.)**1.88      ! Douvill(Yen, 1981)\n  ENDDO\n\n  END SUBROUTINE CSNOW\n\n!== begin tdfcnd ===================================================================================\n\n  SUBROUTINE TDFCND (parameters, ISOIL, DF, SMC, SH2O)\n! --------------------------------------------------------------------------------------------------\n! Calculate thermal diffusivity and conductivity of the soil.\n! Peters-Lidard approach (Peters-Lidard et al., 1998)\n! --------------------------------------------------------------------------------------------------\n! Code history:\n! June 2001 changes: frozen soil condition.\n! --------------------------------------------------------------------------------------------------\n    IMPLICIT NONE\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER, INTENT(IN)    :: ISOIL  ! soil layer\n    REAL, INTENT(IN)       :: SMC    ! total soil water\n    REAL, INTENT(IN)       :: SH2O   ! liq. soil water\n    REAL, INTENT(OUT)      :: DF     ! thermal diffusivity\n\n! local variables\n    REAL  :: AKE\n    REAL  :: GAMMD\n    REAL  :: THKDRY\n    REAL  :: THKO     ! thermal conductivity for other soil components\n    REAL  :: THKQTZ   ! thermal conductivity for quartz\n    REAL  :: THKSAT   !\n    REAL  :: THKS     ! thermal conductivity for the solids\n    REAL  :: THKW     ! water thermal conductivity\n    REAL  :: SATRATIO\n    REAL  :: XU\n    REAL  :: XUNFROZ\n! --------------------------------------------------------------------------------------------------\n! We now get quartz as an input argument (set in routine redprm):\n!      DATA QUARTZ /0.82, 0.10, 0.25, 0.60, 0.52,\n!     &             0.35, 0.60, 0.40, 0.82/\n! --------------------------------------------------------------------------------------------------\n! If the soil has any moisture content compute a partial sum/product\n! otherwise use a constant value which works well with most soils\n! --------------------------------------------------------------------------------------------------\n!  QUARTZ ....QUARTZ CONTENT (SOIL TYPE DEPENDENT)\n! --------------------------------------------------------------------------------------------------\n! USE AS IN PETERS-LIDARD, 1998 (MODIF. FROM JOHANSEN, 1975).\n\n!                                  PABLO GRUNMANN, 08/17/98\n! Refs.:\n!      Farouki, O.T.,1986: Thermal properties of soils. Series on Rock\n!              and Soil Mechanics, Vol. 11, Trans Tech, 136 pp.\n!      Johansen, O., 1975: Thermal conductivity of soils. PH.D. Thesis,\n!              University of Trondheim,\n!      Peters-Lidard, C. D., et al., 1998: The effect of soil thermal\n!              conductivity parameterization on surface energy fluxes\n!              and temperatures. Journal of The Atmospheric Sciences,\n!              Vol. 55, pp. 1209-1224.\n! --------------------------------------------------------------------------------------------------\n! NEEDS PARAMETERS\n! POROSITY(SOIL TYPE):\n!      POROS = SMCMAX\n! SATURATION RATIO:\n! PARAMETERS  W/(M.K)\n    SATRATIO = SMC / parameters%SMCMAX(ISOIL)\n    THKW = 0.57\n!      IF (QUARTZ .LE. 0.2) THKO = 3.0\n    THKO = 2.0\n! SOLIDS' CONDUCTIVITY\n! QUARTZ' CONDUCTIVITY\n    THKQTZ = 7.7\n\n! UNFROZEN FRACTION (FROM 1., i.e., 100%LIQUID, TO 0. (100% FROZEN))\n    THKS = (THKQTZ ** parameters%QUARTZ(ISOIL))* (THKO ** (1. - parameters%QUARTZ(ISOIL)))\n\n! UNFROZEN VOLUME FOR SATURATION (POROSITY*XUNFROZ)\n    XUNFROZ = 1.0                       ! Prevent divide by zero (suggested by D. Mocko)\n    IF(SMC > 0.) XUNFROZ = SH2O / SMC\n! SATURATED THERMAL CONDUCTIVITY\n    XU = XUNFROZ * parameters%SMCMAX(ISOIL)\n\n! DRY DENSITY IN KG/M3\n    THKSAT = THKS ** (1. - parameters%SMCMAX(ISOIL))* TKICE ** (parameters%SMCMAX(ISOIL) - XU)* THKW **   &\n         (XU)\n\n! DRY THERMAL CONDUCTIVITY IN W.M-1.K-1\n    GAMMD = (1. - parameters%SMCMAX(ISOIL))*2700.\n\n    THKDRY = (0.135* GAMMD+ 64.7)/ (2700. - 0.947* GAMMD)\n! FROZEN\n    IF ( (SH2O + 0.0005) <  SMC ) THEN\n       AKE = SATRATIO\n! UNFROZEN\n! RANGE OF VALIDITY FOR THE KERSTEN NUMBER (AKE)\n    ELSE\n\n! KERSTEN NUMBER (USING \"FINE\" FORMULA, VALID FOR SOILS CONTAINING AT\n! LEAST 5% OF PARTICLES WITH DIAMETER LESS THAN 2.E-6 METERS.)\n! (FOR \"COARSE\" FORMULA, SEE PETERS-LIDARD ET AL., 1998).\n\n       IF ( SATRATIO >  0.1 ) THEN\n\n          AKE = LOG10 (SATRATIO) + 1.0\n\n! USE K = KDRY\n       ELSE\n\n          AKE = 0.0\n       END IF\n!  THERMAL CONDUCTIVITY\n\n    END IF\n\n    DF = AKE * (THKSAT - THKDRY) + THKDRY\n\n\n  end subroutine TDFCND\n\n!== begin radiation ================================================================================\n\n  SUBROUTINE RADIATION (parameters,VEGTYP  ,IST     ,ICE     ,NSOIL   , & !in\n                        SNEQVO  ,SNEQV   ,DT      ,COSZ    ,SNOWH   , & !in\n                        TG      ,TV      ,FSNO    ,QSNOW   ,FWET    , & !in\n                        ELAI    ,ESAI    ,SMC     ,SOLAD   ,SOLAI   , & !in\n                        FVEG    ,ILOC    ,JLOC    ,                   & !in\n                        ALBOLD  ,TAUSS   ,                            & !inout\n                        FSUN    ,LAISUN  ,LAISHA  ,PARSUN  ,PARSHA  , & !out\n                        SAV     ,SAG     ,FSR     ,FSA     ,FSRV    , &\n                        FSRG    ,ALBSND  ,ALBSNI  ,BGAP    ,WGAP    )   !out\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER, INTENT(IN)                  :: ILOC\n  INTEGER, INTENT(IN)                  :: JLOC\n  INTEGER, INTENT(IN)                  :: VEGTYP !vegetation type\n  INTEGER, INTENT(IN)                  :: IST    !surface type\n  INTEGER, INTENT(IN)                  :: ICE    !ice (ice = 1)\n  INTEGER, INTENT(IN)                  :: NSOIL  !number of soil layers\n\n  REAL, INTENT(IN)                     :: DT     !time step [s]\n  REAL, INTENT(IN)                     :: QSNOW  !snowfall (mm/s)\n  REAL, INTENT(IN)                     :: SNEQVO !snow mass at last time step(mm)\n  REAL, INTENT(IN)                     :: SNEQV  !snow mass (mm)\n  REAL, INTENT(IN)                     :: SNOWH  !snow height (mm)\n  REAL, INTENT(IN)                     :: COSZ   !cosine solar zenith angle (0-1)\n  REAL, INTENT(IN)                     :: TG     !ground temperature (k)\n  REAL, INTENT(IN)                     :: TV     !vegetation temperature (k)\n  REAL, INTENT(IN)                     :: ELAI   !LAI, one-sided, adjusted for burying by snow\n  REAL, INTENT(IN)                     :: ESAI   !SAI, one-sided, adjusted for burying by snow\n  REAL, INTENT(IN)                     :: FWET   !fraction of canopy that is wet\n  REAL, DIMENSION(1:NSOIL), INTENT(IN) :: SMC    !volumetric soil water [m3/m3]\n  REAL, DIMENSION(1:2)    , INTENT(IN) :: SOLAD  !incoming direct solar radiation (w/m2)\n  REAL, DIMENSION(1:2)    , INTENT(IN) :: SOLAI  !incoming diffuse solar radiation (w/m2)\n  REAL, INTENT(IN)                     :: FSNO   !snow cover fraction (-)\n  REAL, INTENT(IN)                     :: FVEG   !green vegetation fraction [0.0-1.0]\n\n! inout\n  REAL,                  INTENT(INOUT) :: ALBOLD !snow albedo at last time step (CLASS type)\n  REAL,                  INTENT(INOUT) :: TAUSS  !non-dimensional snow age.\n\n! output\n  REAL, INTENT(OUT)                    :: FSUN   !sunlit fraction of canopy (-)\n  REAL, INTENT(OUT)                    :: LAISUN !sunlit leaf area (-)\n  REAL, INTENT(OUT)                    :: LAISHA !shaded leaf area (-)\n  REAL, INTENT(OUT)                    :: PARSUN !average absorbed par for sunlit leaves (w/m2)\n  REAL, INTENT(OUT)                    :: PARSHA !average absorbed par for shaded leaves (w/m2)\n  REAL, INTENT(OUT)                    :: SAV    !solar radiation absorbed by vegetation (w/m2)\n  REAL, INTENT(OUT)                    :: SAG    !solar radiation absorbed by ground (w/m2)\n  REAL, INTENT(OUT)                    :: FSA    !total absorbed solar radiation (w/m2)\n  REAL, INTENT(OUT)                    :: FSR    !total reflected solar radiation (w/m2)\n\n!jref:start\n  REAL, INTENT(OUT)                    :: FSRV    !veg. reflected solar radiation (w/m2)\n  REAL, INTENT(OUT)                    :: FSRG    !ground reflected solar radiation (w/m2)\n  REAL, INTENT(OUT)                    :: BGAP\n  REAL, INTENT(OUT)                    :: WGAP\n  REAL, DIMENSION(1:2), INTENT(OUT)    :: ALBSND   !snow albedo (direct)\n  REAL, DIMENSION(1:2), INTENT(OUT)    :: ALBSNI   !snow albedo (diffuse)\n!jref:end\n\n! local\n  REAL                                 :: FAGE   !snow age function (0 - new snow)\n  REAL, DIMENSION(1:2)                 :: ALBGRD !ground albedo (direct)\n  REAL, DIMENSION(1:2)                 :: ALBGRI !ground albedo (diffuse)\n  REAL, DIMENSION(1:2)                 :: ALBD   !surface albedo (direct)\n  REAL, DIMENSION(1:2)                 :: ALBI   !surface albedo (diffuse)\n  REAL, DIMENSION(1:2)                 :: FABD   !flux abs by veg (per unit direct flux)\n  REAL, DIMENSION(1:2)                 :: FABI   !flux abs by veg (per unit diffuse flux)\n  REAL, DIMENSION(1:2)                 :: FTDD   !down direct flux below veg (per unit dir flux)\n  REAL, DIMENSION(1:2)                 :: FTID   !down diffuse flux below veg (per unit dir flux)\n  REAL, DIMENSION(1:2)                 :: FTII   !down diffuse flux below veg (per unit dif flux)\n!jref:start\n  REAL, DIMENSION(1:2)                 :: FREVI\n  REAL, DIMENSION(1:2)                 :: FREVD\n  REAL, DIMENSION(1:2)                 :: FREGI\n  REAL, DIMENSION(1:2)                 :: FREGD\n!jref:end\n\n  REAL                                 :: FSHA   !shaded fraction of canopy\n  REAL                                 :: VAI    !total LAI + stem area index, one sided\n\n  REAL,PARAMETER :: MPE = 1.E-6\n  LOGICAL VEG  !true: vegetated for surface temperature calculation\n\n! --------------------------------------------------------------------------------------------------\n\n! surface abeldo\n\n   CALL ALBEDO (parameters,VEGTYP ,IST    ,ICE    ,NSOIL  , & !in\n                DT     ,COSZ   ,FAGE   ,ELAI   ,ESAI   , & !in\n                TG     ,TV     ,SNOWH  ,FSNO   ,FWET   , & !in\n                SMC    ,SNEQVO ,SNEQV  ,QSNOW  ,FVEG   , & !in\n                ILOC   ,JLOC   ,                         & !in\n                ALBOLD ,TAUSS                          , & !inout\n                ALBGRD ,ALBGRI ,ALBD   ,ALBI   ,FABD   , & !out\n                FABI   ,FTDD   ,FTID   ,FTII   ,FSUN   , & !)   !out\n                FREVI  ,FREVD   ,FREGD ,FREGI  ,BGAP   , & !inout\n                WGAP   ,ALBSND ,ALBSNI )\n\n! surface radiation\n\n     FSHA = 1.-FSUN\n     LAISUN = ELAI*FSUN\n     LAISHA = ELAI*FSHA\n     VAI = ELAI+ ESAI\n     IF (VAI .GT. 0.) THEN\n        VEG = .TRUE.\n     ELSE\n        VEG = .FALSE.\n     END IF\n\n   CALL SURRAD (parameters,MPE    ,FSUN   ,FSHA   ,ELAI   ,VAI    , & !in\n                LAISUN ,LAISHA ,SOLAD  ,SOLAI  ,FABD   , & !in\n                FABI   ,FTDD   ,FTID   ,FTII   ,ALBGRD , & !in\n                ALBGRI ,ALBD   ,ALBI   ,ILOC   ,JLOC   , & !in\n                PARSUN ,PARSHA ,SAV    ,SAG    ,FSA    , & !out\n                FSR    ,                                 & !out\n                FREVI  ,FREVD  ,FREGD  ,FREGI  ,FSRV   , & !inout\n                FSRG)\n\n  END SUBROUTINE RADIATION\n\n!== begin albedo ===================================================================================\n\n  SUBROUTINE ALBEDO (parameters,VEGTYP ,IST    ,ICE    ,NSOIL  , & !in\n                     DT     ,COSZ   ,FAGE   ,ELAI   ,ESAI   , & !in\n                     TG     ,TV     ,SNOWH  ,FSNO   ,FWET   , & !in\n                     SMC    ,SNEQVO ,SNEQV  ,QSNOW  ,FVEG   , & !in\n                     ILOC   ,JLOC   ,                         & !in\n                     ALBOLD ,TAUSS                          , & !inout\n                     ALBGRD ,ALBGRI ,ALBD   ,ALBI   ,FABD   , & !out\n                     FABI   ,FTDD   ,FTID   ,FTII   ,FSUN   , & !out\n                     FREVI  ,FREVD  ,FREGD  ,FREGI  ,BGAP   , & !out\n                     WGAP   ,ALBSND ,ALBSNI )\n\n! --------------------------------------------------------------------------------------------------\n! surface albedos. also fluxes (per unit incoming direct and diffuse\n! radiation) reflected, transmitted, and absorbed by vegetation.\n! also sunlit fraction of the canopy.\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                  INTENT(IN)  :: ILOC\n  INTEGER,                  INTENT(IN)  :: JLOC\n  INTEGER,                  INTENT(IN)  :: NSOIL  !number of soil layers\n  INTEGER,                  INTENT(IN)  :: VEGTYP !vegetation type\n  INTEGER,                  INTENT(IN)  :: IST    !surface type\n  INTEGER,                  INTENT(IN)  :: ICE    !ice (ice = 1)\n\n  REAL,                     INTENT(IN)  :: DT     !time step [sec]\n  REAL,                     INTENT(IN)  :: QSNOW  !snowfall\n  REAL,                     INTENT(IN)  :: COSZ   !cosine solar zenith angle for next time step\n  REAL,                     INTENT(IN)  :: SNOWH  !snow height (mm)\n  REAL,                     INTENT(IN)  :: TG     !ground temperature (k)\n  REAL,                     INTENT(IN)  :: TV     !vegetation temperature (k)\n  REAL,                     INTENT(IN)  :: ELAI   !LAI, one-sided, adjusted for burying by snow\n  REAL,                     INTENT(IN)  :: ESAI   !SAI, one-sided, adjusted for burying by snow\n  REAL,                     INTENT(IN)  :: FSNO   !fraction of grid covered by snow\n  REAL,                     INTENT(IN)  :: FWET   !fraction of canopy that is wet\n  REAL,                     INTENT(IN)  :: SNEQVO !snow mass at last time step(mm)\n  REAL,                     INTENT(IN)  :: SNEQV  !snow mass (mm)\n  REAL,                     INTENT(IN)  :: FVEG   !green vegetation fraction [0.0-1.0]\n  REAL, DIMENSION(1:NSOIL), INTENT(IN)  :: SMC    !volumetric soil water (m3/m3)\n\n! inout\n  REAL,                  INTENT(INOUT)  :: ALBOLD !snow albedo at last time step (CLASS type)\n  REAL,                  INTENT(INOUT)  :: TAUSS  !non-dimensional snow age\n\n! output\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: ALBGRD !ground albedo (direct)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: ALBGRI !ground albedo (diffuse)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: ALBD   !surface albedo (direct)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: ALBI   !surface albedo (diffuse)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FABD   !flux abs by veg (per unit direct flux)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FABI   !flux abs by veg (per unit diffuse flux)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FTDD   !down direct flux below veg (per unit dir flux)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FTID   !down diffuse flux below veg (per unit dir flux)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FTII   !down diffuse flux below veg (per unit dif flux)\n  REAL,                     INTENT(OUT) :: FSUN   !sunlit fraction of canopy (-)\n!jref:start\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FREVD\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FREVI\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FREGD\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: FREGI\n  REAL, INTENT(OUT) :: BGAP\n  REAL, INTENT(OUT) :: WGAP\n!jref:end\n\n! ------------------------------------------------------------------------\n! ------------------------ local variables -------------------------------\n! local\n  REAL                 :: FAGE     !snow age function\n  REAL                 :: ALB\n  INTEGER              :: IB       !indices\n  INTEGER              :: NBAND    !number of solar radiation wave bands\n  INTEGER              :: IC       !direct beam: ic=0; diffuse: ic=1\n\n  REAL                 :: WL       !fraction of LAI+SAI that is LAI\n  REAL                 :: WS       !fraction of LAI+SAI that is SAI\n  REAL                 :: MPE      !prevents overflow for division by zero\n\n  REAL, DIMENSION(1:2) :: RHO      !leaf/stem reflectance weighted by fraction LAI and SAI\n  REAL, DIMENSION(1:2) :: TAU      !leaf/stem transmittance weighted by fraction LAI and SAI\n  REAL, DIMENSION(1:2) :: FTDI     !down direct flux below veg per unit dif flux = 0\n  REAL, DIMENSION(1:2), INTENT(OUT) :: ALBSND   !snow albedo (direct)\n  REAL, DIMENSION(1:2), INTENT(OUT) :: ALBSNI   !snow albedo (diffuse)\n\n  REAL                 :: VAI      !ELAI+ESAI\n  REAL                 :: GDIR     !average projected leaf/stem area in solar direction\n  REAL                 :: EXT      !optical depth direct beam per unit leaf + stem area\n\n! --------------------------------------------------------------------------------------------------\n\n  NBAND = 2\n  MPE = 1.E-06\n  BGAP = 0.\n  WGAP = 0.\n\n! initialize output because solar radiation only done if COSZ > 0\n\n  DO IB = 1, NBAND\n    ALBD(IB) = 0.\n    ALBI(IB) = 0.\n    ALBGRD(IB) = 0.\n    ALBGRI(IB) = 0.\n    ALBSND(IB) = 0.\n    ALBSNI(IB) = 0.\n    FABD(IB) = 0.\n    FABI(IB) = 0.\n    FTDD(IB) = 0.\n    FTID(IB) = 0.\n    FTII(IB) = 0.\n    IF (IB.EQ.1) FSUN = 0.\n  END DO\n\n  IF(COSZ <= 0) GOTO 100\n\n! weight reflectance/transmittance by LAI and SAI\n\n  DO IB = 1, NBAND\n    VAI = ELAI + ESAI\n    WL  = ELAI / MAX(VAI,MPE)\n    WS  = ESAI / MAX(VAI,MPE)\n    RHO(IB) = MAX(parameters%RHOL(IB)*WL+parameters%RHOS(IB)*WS, MPE)\n    TAU(IB) = MAX(parameters%TAUL(IB)*WL+parameters%TAUS(IB)*WS, MPE)\n  END DO\n\n! snow age\n\n   CALL SNOW_AGE (parameters,DT,TG,SNEQVO,SNEQV,TAUSS,FAGE)\n\n! snow albedos: only if COSZ > 0 and FSNO > 0\n\n  IF(OPT_ALB == 1) &\n     CALL SNOWALB_BATS (parameters,NBAND, FSNO,COSZ,FAGE,ALBSND,ALBSNI)\n  IF(OPT_ALB == 2) THEN\n     CALL SNOWALB_CLASS (parameters,NBAND,QSNOW,DT,ALB,ALBOLD,ALBSND,ALBSNI,ILOC,JLOC)\n     ALBOLD = ALB\n  END IF\n\n! ground surface albedo\n\n  CALL GROUNDALB (parameters,NSOIL   ,NBAND   ,ICE     ,IST     , & !in\n                  FSNO    ,SMC     ,ALBSND  ,ALBSNI  ,COSZ    , & !in\n                  TG      ,ILOC    ,JLOC    ,                   & !in\n                  ALBGRD  ,ALBGRI  )                              !out\n\n! loop over NBAND wavebands to calculate surface albedos and solar\n! fluxes for unit incoming direct (IC=0) and diffuse flux (IC=1)\n\n  DO IB = 1, NBAND\n      IC = 0      ! direct\n      CALL TWOSTREAM (parameters,IB     ,IC      ,VEGTYP  ,COSZ    ,VAI    , & !in\n                      FWET   ,TV      ,ALBGRD  ,ALBGRI  ,RHO    , & !in\n                      TAU    ,FVEG    ,IST     ,ILOC    ,JLOC   , & !in\n                      FABD   ,ALBD    ,FTDD    ,FTID    ,GDIR   , &!)   !out\n                      FREVD  ,FREGD   ,BGAP    ,WGAP)\n\n      IC = 1      ! diffuse\n      CALL TWOSTREAM (parameters,IB     ,IC      ,VEGTYP  ,COSZ    ,VAI    , & !in\n                      FWET   ,TV      ,ALBGRD  ,ALBGRI  ,RHO    , & !in\n                      TAU    ,FVEG    ,IST     ,ILOC    ,JLOC   , & !in\n                      FABI   ,ALBI    ,FTDI    ,FTII    ,GDIR   , & !)   !out\n                      FREVI  ,FREGI   ,BGAP    ,WGAP)\n\n  END DO\n\n! sunlit fraction of canopy. set FSUN = 0 if FSUN < 0.01.\n\n  EXT = GDIR/COSZ * SQRT(1.-RHO(1)-TAU(1))\n  FSUN = (1.-EXP(-EXT*VAI)) / MAX(EXT*VAI,MPE)\n  EXT = FSUN\n\n  IF (EXT .LT. 0.01) THEN\n     WL = 0.\n  ELSE\n     WL = EXT\n  END IF\n  FSUN = WL\n\n100 CONTINUE\n\n  END SUBROUTINE ALBEDO\n\n!== begin surrad ===================================================================================\n\n  SUBROUTINE SURRAD (parameters,MPE     ,FSUN    ,FSHA    ,ELAI    ,VAI     , & !in\n                     LAISUN  ,LAISHA  ,SOLAD   ,SOLAI   ,FABD    , & !in\n                     FABI    ,FTDD    ,FTID    ,FTII    ,ALBGRD  , & !in\n                     ALBGRI  ,ALBD    ,ALBI    ,ILOC    ,JLOC    , & !in\n                     PARSUN  ,PARSHA  ,SAV     ,SAG     ,FSA     , & !out\n                     FSR     , & !)                                       !out\n                     FREVI   ,FREVD   ,FREGD   ,FREGI   ,FSRV    , &\n                     FSRG) !inout\n\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER, INTENT(IN)              :: ILOC\n  INTEGER, INTENT(IN)              :: JLOC\n  REAL, INTENT(IN)                 :: MPE     !prevents underflow errors if division by zero\n\n  REAL, INTENT(IN)                 :: FSUN    !sunlit fraction of canopy\n  REAL, INTENT(IN)                 :: FSHA    !shaded fraction of canopy\n  REAL, INTENT(IN)                 :: ELAI    !leaf area, one-sided\n  REAL, INTENT(IN)                 :: VAI     !leaf + stem area, one-sided\n  REAL, INTENT(IN)                 :: LAISUN  !sunlit leaf area index, one-sided\n  REAL, INTENT(IN)                 :: LAISHA  !shaded leaf area index, one-sided\n\n  REAL, DIMENSION(1:2), INTENT(IN) :: SOLAD   !incoming direct solar radiation (w/m2)\n  REAL, DIMENSION(1:2), INTENT(IN) :: SOLAI   !incoming diffuse solar radiation (w/m2)\n  REAL, DIMENSION(1:2), INTENT(IN) :: FABD    !flux abs by veg (per unit incoming direct flux)\n  REAL, DIMENSION(1:2), INTENT(IN) :: FABI    !flux abs by veg (per unit incoming diffuse flux)\n  REAL, DIMENSION(1:2), INTENT(IN) :: FTDD    !down dir flux below veg (per incoming dir flux)\n  REAL, DIMENSION(1:2), INTENT(IN) :: FTID    !down dif flux below veg (per incoming dir flux)\n  REAL, DIMENSION(1:2), INTENT(IN) :: FTII    !down dif flux below veg (per incoming dif flux)\n  REAL, DIMENSION(1:2), INTENT(IN) :: ALBGRD  !ground albedo (direct)\n  REAL, DIMENSION(1:2), INTENT(IN) :: ALBGRI  !ground albedo (diffuse)\n  REAL, DIMENSION(1:2), INTENT(IN) :: ALBD    !overall surface albedo (direct)\n  REAL, DIMENSION(1:2), INTENT(IN) :: ALBI    !overall surface albedo (diffuse)\n\n  REAL, DIMENSION(1:2), INTENT(IN) :: FREVD    !overall surface albedo veg (direct)\n  REAL, DIMENSION(1:2), INTENT(IN) :: FREVI    !overall surface albedo veg (diffuse)\n  REAL, DIMENSION(1:2), INTENT(IN) :: FREGD    !overall surface albedo grd (direct)\n  REAL, DIMENSION(1:2), INTENT(IN) :: FREGI    !overall surface albedo grd (diffuse)\n\n! output\n\n  REAL, INTENT(OUT)                :: PARSUN  !average absorbed par for sunlit leaves (w/m2)\n  REAL, INTENT(OUT)                :: PARSHA  !average absorbed par for shaded leaves (w/m2)\n  REAL, INTENT(OUT)                :: SAV     !solar radiation absorbed by vegetation (w/m2)\n  REAL, INTENT(OUT)                :: SAG     !solar radiation absorbed by ground (w/m2)\n  REAL, INTENT(OUT)                :: FSA     !total absorbed solar radiation (w/m2)\n  REAL, INTENT(OUT)                :: FSR     !total reflected solar radiation (w/m2)\n  REAL, INTENT(OUT)                :: FSRV    !reflected solar radiation by vegetation\n  REAL, INTENT(OUT)                :: FSRG    !reflected solar radiation by ground\n\n! ------------------------ local variables ----------------------------------------------------\n  INTEGER                          :: IB      !waveband number (1=vis, 2=nir)\n  INTEGER                          :: NBAND   !number of solar radiation waveband classes\n\n  REAL                             :: ABS     !absorbed solar radiation (w/m2)\n  REAL                             :: RNIR    !reflected solar radiation [nir] (w/m2)\n  REAL                             :: RVIS    !reflected solar radiation [vis] (w/m2)\n  REAL                             :: LAIFRA  !leaf area fraction of canopy\n  REAL                             :: TRD     !transmitted solar radiation: direct (w/m2)\n  REAL                             :: TRI     !transmitted solar radiation: diffuse (w/m2)\n  REAL, DIMENSION(1:2)             :: CAD     !direct beam absorbed by canopy (w/m2)\n  REAL, DIMENSION(1:2)             :: CAI     !diffuse radiation absorbed by canopy (w/m2)\n! ---------------------------------------------------------------------------------------------\n   NBAND = 2\n\n! zero summed solar fluxes\n\n    SAG = 0.\n    SAV = 0.\n    FSA = 0.\n\n! loop over nband wavebands\n\n  DO IB = 1, NBAND\n\n! absorbed by canopy\n\n    CAD(IB) = SOLAD(IB)*FABD(IB)\n    CAI(IB) = SOLAI(IB)*FABI(IB)\n    SAV     = SAV + CAD(IB) + CAI(IB)\n    FSA     = FSA + CAD(IB) + CAI(IB)\n\n! transmitted solar fluxes incident on ground\n\n    TRD = SOLAD(IB)*FTDD(IB)\n    TRI = SOLAD(IB)*FTID(IB) + SOLAI(IB)*FTII(IB)\n\n! solar radiation absorbed by ground surface\n\n    ABS = TRD*(1.-ALBGRD(IB)) + TRI*(1.-ALBGRI(IB))\n    SAG = SAG + ABS\n    FSA = FSA + ABS\n  END DO\n\n! partition visible canopy absorption to sunlit and shaded fractions\n! to get average absorbed par for sunlit and shaded leaves\n\n     LAIFRA = ELAI / MAX(VAI,MPE)\n     IF (FSUN .GT. 0.) THEN\n        PARSUN = (CAD(1)+FSUN*CAI(1)) * LAIFRA / MAX(LAISUN,MPE)\n        PARSHA = (FSHA*CAI(1))*LAIFRA / MAX(LAISHA,MPE)\n     ELSE\n        PARSUN = 0.\n        PARSHA = (CAD(1)+CAI(1))*LAIFRA /MAX(LAISHA,MPE)\n     ENDIF\n\n! reflected solar radiation\n\n     RVIS = ALBD(1)*SOLAD(1) + ALBI(1)*SOLAI(1)\n     RNIR = ALBD(2)*SOLAD(2) + ALBI(2)*SOLAI(2)\n     FSR  = RVIS + RNIR\n\n! reflected solar radiation of veg. and ground (combined ground)\n     FSRV = FREVD(1)*SOLAD(1)+FREVI(1)*SOLAI(1)+FREVD(2)*SOLAD(2)+FREVI(2)*SOLAI(2)\n     FSRG = FREGD(1)*SOLAD(1)+FREGI(1)*SOLAI(1)+FREGD(2)*SOLAD(2)+FREGI(2)*SOLAI(2)\n\n\n  END SUBROUTINE SURRAD\n\n!== begin snow_age =================================================================================\n\n  SUBROUTINE SNOW_AGE (parameters,DT,TG,SNEQVO,SNEQV,TAUSS,FAGE)\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ------------------------ code history ------------------------------------------------------------\n! from BATS\n! ------------------------ input/output variables --------------------------------------------------\n!input\n  type (noahmp_parameters), intent(in) :: parameters\n   REAL, INTENT(IN) :: DT        !main time step (s)\n   REAL, INTENT(IN) :: TG        !ground temperature (k)\n   REAL, INTENT(IN) :: SNEQVO    !snow mass at last time step(mm)\n   REAL, INTENT(IN) :: SNEQV     !snow water per unit ground area (mm)\n\n!output\n   REAL, INTENT(OUT) :: FAGE     !snow age\n\n!input/output\n   REAL, INTENT(INOUT) :: TAUSS      !non-dimensional snow age\n!local\n   REAL            :: TAGE       !total aging effects\n   REAL            :: AGE1       !effects of grain growth due to vapor diffusion\n   REAL            :: AGE2       !effects of grain growth at freezing of melt water\n   REAL            :: AGE3       !effects of soot\n   REAL            :: DELA       !temporary variable\n   REAL            :: SGE        !temporary variable\n   REAL            :: DELS       !temporary variable\n   REAL            :: DELA0      !temporary variable\n   REAL            :: ARG        !temporary variable\n! See Yang et al. (1997) J.of Climate for detail.\n!---------------------------------------------------------------------------------------------------\n\n   IF(SNEQV.LE.0.0) THEN\n          TAUSS = 0.\n   ELSE\n          DELA0 = DT/parameters%TAU0\n          ARG   = parameters%GRAIN_GROWTH*(1./TFRZ-1./TG)\n          AGE1  = EXP(ARG)\n          AGE2  = EXP(AMIN1(0.,parameters%EXTRA_GROWTH*ARG))\n          AGE3  = parameters%DIRT_SOOT\n          TAGE  = AGE1+AGE2+AGE3\n          DELA  = DELA0*TAGE\n          DELS  = AMAX1(0.0,SNEQV-SNEQVO) / parameters%SWEMX\n          SGE   = (TAUSS+DELA)*(1.0-DELS)\n          TAUSS = AMAX1(0.,SGE)\n   ENDIF\n\n   FAGE= TAUSS/(TAUSS+1.)\n\n  END SUBROUTINE SNOW_AGE\n\n!== begin snowalb_bats =============================================================================\n\n  SUBROUTINE SNOWALB_BATS (parameters,NBAND,FSNO,COSZ,FAGE,ALBSND,ALBSNI)\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,INTENT(IN) :: NBAND  !number of waveband classes\n\n  REAL,INTENT(IN) :: COSZ    !cosine solar zenith angle\n  REAL,INTENT(IN) :: FSNO    !snow cover fraction (-)\n  REAL,INTENT(IN) :: FAGE    !snow age correction\n\n! output\n\n  REAL, DIMENSION(1:2),INTENT(OUT) :: ALBSND !snow albedo for direct(1=vis, 2=nir)\n  REAL, DIMENSION(1:2),INTENT(OUT) :: ALBSNI !snow albedo for diffuse\n! ---------------------------------------------------------------------------------------------\n\n! ------------------------ local variables ----------------------------------------------------\n  INTEGER :: IB          !waveband class\n\n  REAL :: FZEN                 !zenith angle correction\n  REAL :: CF1                  !temperary variable\n  REAL :: SL2                  !2.*SL\n  REAL :: SL1                  !1/SL\n  REAL :: SL                   !adjustable parameter\n!  REAL, PARAMETER :: C1 = 0.2  !default in BATS\n!  REAL, PARAMETER :: C2 = 0.5  !default in BATS\n!  REAL, PARAMETER :: C1 = 0.2 * 2. ! double the default to match Sleepers River's\n!  REAL, PARAMETER :: C2 = 0.5 * 2. ! snow surface albedo (double aging effects)\n! ---------------------------------------------------------------------------------------------\n! zero albedos for all points\n\n        ALBSND(1: NBAND) = 0.\n        ALBSNI(1: NBAND) = 0.\n\n! when cosz > 0\n\n        SL=parameters%BATS_COSZ\n        SL1=1./SL\n        SL2=2.*SL\n        CF1=((1.+SL1)/(1.+SL2*COSZ)-SL1)\n        FZEN=AMAX1(CF1,0.)\n\n        ALBSNI(1)=parameters%BATS_VIS_NEW*(1.-parameters%BATS_VIS_AGE*FAGE)\n        ALBSNI(2)=parameters%BATS_NIR_NEW*(1.-parameters%BATS_NIR_AGE*FAGE)\n\n        ALBSND(1)=ALBSNI(1)+parameters%BATS_VIS_DIR*FZEN*(1.-ALBSNI(1))    !  vis direct\n        ALBSND(2)=ALBSNI(2)+parameters%BATS_NIR_DIR*FZEN*(1.-ALBSNI(2))    !  nir direct\n\n  END SUBROUTINE SNOWALB_BATS\n\n!== begin snowalb_class ============================================================================\n\n  SUBROUTINE SNOWALB_CLASS (parameters,NBAND,QSNOW,DT,ALB,ALBOLD,ALBSND,ALBSNI,ILOC,JLOC)\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,INTENT(IN) :: ILOC !grid index\n  INTEGER,INTENT(IN) :: JLOC !grid index\n  INTEGER,INTENT(IN) :: NBAND  !number of waveband classes\n\n  REAL,INTENT(IN) :: QSNOW     !snowfall (mm/s)\n  REAL,INTENT(IN) :: DT        !time step (sec)\n  REAL,INTENT(IN) :: ALBOLD    !snow albedo at last time step\n\n! in & out\n\n  REAL,                INTENT(INOUT) :: ALB        !\n! output\n\n  REAL, DIMENSION(1:2),INTENT(OUT) :: ALBSND !snow albedo for direct(1=vis, 2=nir)\n  REAL, DIMENSION(1:2),INTENT(OUT) :: ALBSNI !snow albedo for diffuse\n! ---------------------------------------------------------------------------------------------\n\n! ------------------------ local variables ----------------------------------------------------\n  INTEGER :: IB          !waveband class\n\n! ---------------------------------------------------------------------------------------------\n! zero albedos for all points\n\n        ALBSND(1: NBAND) = 0.\n        ALBSNI(1: NBAND) = 0.\n\n! when cosz > 0\n\n         ALB = 0.55 + (ALBOLD-0.55) * EXP(-0.01*DT/3600.)\n\n! 1 mm fresh snow(SWE) -- 10mm snow depth, assumed the fresh snow density 100kg/m3\n! here assume 1cm snow depth will fully cover the old snow\n\n         IF (QSNOW > 0.) then\n           ALB = ALB + MIN(QSNOW,parameters%SWEMX/DT) * (0.84-ALB)/(parameters%SWEMX/DT)\n         ENDIF\n\n         ALBSNI(1)= ALB         ! vis diffuse\n         ALBSNI(2)= ALB         ! nir diffuse\n         ALBSND(1)= ALB         ! vis direct\n         ALBSND(2)= ALB         ! nir direct\n\n  END SUBROUTINE SNOWALB_CLASS\n\n!== begin groundalb ================================================================================\n\n  SUBROUTINE GROUNDALB (parameters,NSOIL   ,NBAND   ,ICE     ,IST     , & !in\n                        FSNO    ,SMC     ,ALBSND  ,ALBSNI  ,COSZ    , & !in\n                        TG      ,ILOC    ,JLOC    ,                   & !in\n                        ALBGRD  ,ALBGRI  )                              !out\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n!input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                  INTENT(IN)  :: ILOC   !grid index\n  INTEGER,                  INTENT(IN)  :: JLOC   !grid index\n  INTEGER,                  INTENT(IN)  :: NSOIL  !number of soil layers\n  INTEGER,                  INTENT(IN)  :: NBAND  !number of solar radiation waveband classes\n  INTEGER,                  INTENT(IN)  :: ICE    !value of ist for land ice\n  INTEGER,                  INTENT(IN)  :: IST    !surface type\n  REAL,                     INTENT(IN)  :: FSNO   !fraction of surface covered with snow (-)\n  REAL,                     INTENT(IN)  :: TG     !ground temperature (k)\n  REAL,                     INTENT(IN)  :: COSZ   !cosine solar zenith angle (0-1)\n  REAL, DIMENSION(1:NSOIL), INTENT(IN)  :: SMC    !volumetric soil water content (m3/m3)\n  REAL, DIMENSION(1:    2), INTENT(IN)  :: ALBSND !direct beam snow albedo (vis, nir)\n  REAL, DIMENSION(1:    2), INTENT(IN)  :: ALBSNI !diffuse snow albedo (vis, nir)\n\n!output\n\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: ALBGRD !ground albedo (direct beam: vis, nir)\n  REAL, DIMENSION(1:    2), INTENT(OUT) :: ALBGRI !ground albedo (diffuse: vis, nir)\n\n!local\n\n  INTEGER                               :: IB     !waveband number (1=vis, 2=nir)\n  REAL                                  :: INC    !soil water correction factor for soil albedo\n  REAL                                  :: ALBSOD !soil albedo (direct)\n  REAL                                  :: ALBSOI !soil albedo (diffuse)\n! --------------------------------------------------------------------------------------------------\n\n  DO IB = 1, NBAND\n        INC = MAX(0.11-0.40*SMC(1), 0.)\n        IF (IST .EQ. 1)  THEN                     !soil\n           ALBSOD = MIN(parameters%ALBSAT(IB)+INC,parameters%ALBDRY(IB))\n           ALBSOI = ALBSOD\n        ELSE IF (TG .GT. TFRZ) THEN               !unfrozen lake, wetland\n           ALBSOD = 0.06/(MAX(0.01,COSZ)**1.7 + 0.15)\n           ALBSOI = 0.06\n        ELSE                                      !frozen lake, wetland\n           ALBSOD = parameters%ALBLAK(IB)\n           ALBSOI = ALBSOD\n        END IF\n\n! increase desert and semi-desert albedos\n\n!        IF (IST .EQ. 1 .AND. ISC .EQ. 9) THEN\n!           ALBSOD = ALBSOD + 0.10\n!           ALBSOI = ALBSOI + 0.10\n!        end if\n\n        ALBGRD(IB) = ALBSOD*(1.-FSNO) + ALBSND(IB)*FSNO\n        ALBGRI(IB) = ALBSOI*(1.-FSNO) + ALBSNI(IB)*FSNO\n  END DO\n\n  END SUBROUTINE GROUNDALB\n\n!== begin twostream ================================================================================\n\n  SUBROUTINE TWOSTREAM (parameters,IB     ,IC      ,VEGTYP  ,COSZ    ,VAI    , & !in\n                        FWET   ,T       ,ALBGRD  ,ALBGRI  ,RHO    , & !in\n                        TAU    ,FVEG    ,IST     ,ILOC    ,JLOC   , & !in\n                        FAB    ,FRE     ,FTD     ,FTI     ,GDIR   , & !)   !out\n                        FREV   ,FREG    ,BGAP    ,WGAP)\n\n! --------------------------------------------------------------------------------------------------\n! use two-stream approximation of Dickinson (1983) Adv Geophysics\n! 25:305-353 and Sellers (1985) Int J Remote Sensing 6:1335-1372\n! to calculate fluxes absorbed by vegetation, reflected by vegetation,\n! and transmitted through vegetation for unit incoming direct or diffuse\n! flux given an underlying surface with known albedo.\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n   INTEGER,              INTENT(IN)  :: ILOC    !grid index\n   INTEGER,              INTENT(IN)  :: JLOC    !grid index\n   INTEGER,              INTENT(IN)  :: IST     !surface type\n   INTEGER,              INTENT(IN)  :: IB      !waveband number\n   INTEGER,              INTENT(IN)  :: IC      !0=unit incoming direct; 1=unit incoming diffuse\n   INTEGER,              INTENT(IN)  :: VEGTYP  !vegetation type\n\n   REAL,                 INTENT(IN)  :: COSZ    !cosine of direct zenith angle (0-1)\n   REAL,                 INTENT(IN)  :: VAI     !one-sided leaf+stem area index (m2/m2)\n   REAL,                 INTENT(IN)  :: FWET    !fraction of lai, sai that is wetted (-)\n   REAL,                 INTENT(IN)  :: T       !surface temperature (k)\n\n   REAL, DIMENSION(1:2), INTENT(IN)  :: ALBGRD  !direct  albedo of underlying surface (-)\n   REAL, DIMENSION(1:2), INTENT(IN)  :: ALBGRI  !diffuse albedo of underlying surface (-)\n   REAL, DIMENSION(1:2), INTENT(IN)  :: RHO     !leaf+stem reflectance\n   REAL, DIMENSION(1:2), INTENT(IN)  :: TAU     !leaf+stem transmittance\n   REAL,                 INTENT(IN)  :: FVEG    !green vegetation fraction [0.0-1.0]\n\n! output\n\n   REAL, DIMENSION(1:2), INTENT(OUT) :: FAB     !flux abs by veg layer (per unit incoming flux)\n   REAL, DIMENSION(1:2), INTENT(OUT) :: FRE     !flux refl above veg layer (per unit incoming flux)\n   REAL, DIMENSION(1:2), INTENT(OUT) :: FTD     !down dir flux below veg layer (per unit in flux)\n   REAL, DIMENSION(1:2), INTENT(OUT) :: FTI     !down dif flux below veg layer (per unit in flux)\n   REAL,                 INTENT(OUT) :: GDIR    !projected leaf+stem area in solar direction\n   REAL, DIMENSION(1:2), INTENT(OUT) :: FREV    !flux reflected by veg layer   (per unit incoming flux)\n   REAL, DIMENSION(1:2), INTENT(OUT) :: FREG    !flux reflected by ground (per unit incoming flux)\n\n! local\n   REAL                              :: OMEGA   !fraction of intercepted radiation that is scattered\n   REAL                              :: OMEGAL  !omega for leaves\n   REAL                              :: BETAI   !upscatter parameter for diffuse radiation\n   REAL                              :: BETAIL  !betai for leaves\n   REAL                              :: BETAD   !upscatter parameter for direct beam radiation\n   REAL                              :: BETADL  !betad for leaves\n   REAL                              :: EXT     !optical depth of direct beam per unit leaf area\n   REAL                              :: AVMU    !average diffuse optical depth\n\n   REAL                              :: COSZI   !0.001 <= cosz <= 1.000\n   REAL                              :: ASU     !single scattering albedo\n   REAL                              :: CHIL    ! -0.4 <= xl <= 0.6\n\n   REAL                              :: TMP0,TMP1,TMP2,TMP3,TMP4,TMP5,TMP6,TMP7,TMP8,TMP9\n   REAL                              :: P1,P2,P3,P4,S1,S2,U1,U2,U3\n   REAL                              :: B,C,D,D1,D2,F,H,H1,H2,H3,H4,H5,H6,H7,H8,H9,H10\n   REAL                              :: PHI1,PHI2,SIGMA\n   REAL                              :: FTDS,FTIS,FRES\n   REAL                              :: DENFVEG\n   REAL                              :: VAI_SPREAD\n!jref:start\n   REAL                              :: FREVEG,FREBAR,FTDVEG,FTIVEG,FTDBAR,FTIBAR\n   REAL                              :: THETAZ\n!jref:end\n\n!  variables for the modified two-stream scheme\n!  Niu and Yang (2004), JGR\n\n   REAL, PARAMETER :: PAI = 3.14159265\n   REAL :: HD       !crown depth (m)\n   REAL :: BB       !vertical crown radius (m)\n   REAL :: THETAP   !angle conversion from SZA\n   REAL :: FA       !foliage volume density (m-1)\n   REAL :: NEWVAI   !effective LSAI (-)\n\n   REAL,INTENT(INOUT) :: BGAP     !between canopy gap fraction for beam (-)\n   REAL,INTENT(INOUT) :: WGAP     !within canopy gap fraction for beam (-)\n\n   REAL :: KOPEN    !gap fraction for diffue light (-)\n   REAL :: GAP      !total gap fraction for beam ( <=1-shafac )\n\n! -----------------------------------------------------------------\n! compute within and between gaps\n     VAI_SPREAD = VAI\n     if(VAI == 0.0) THEN\n         GAP     = 1.0\n         KOPEN   = 1.0\n     ELSE\n         IF(OPT_RAD == 1) THEN\n\t   DENFVEG = -LOG(MAX(1.0-FVEG,0.01))/(PAI*parameters%RC**2)\n           HD      = parameters%HVT - parameters%HVB\n           BB      = 0.5 * HD\n           THETAP  = ATAN(BB/parameters%RC * TAN(ACOS(MAX(0.01,COSZ))) )\n           ! BGAP    = EXP(-parameters%DEN * PAI * parameters%RC**2/COS(THETAP) )\n           BGAP    = EXP(-DENFVEG * PAI * parameters%RC**2/COS(THETAP) )\n           FA      = VAI/(1.33 * PAI * parameters%RC**3.0 *(BB/parameters%RC)*DENFVEG)\n           NEWVAI  = HD*FA\n           WGAP    = (1.0-BGAP) * EXP(-0.5*NEWVAI/COSZ)\n           GAP     = MIN(1.0-FVEG, BGAP+WGAP)\n\n           KOPEN   = 0.05\n         END IF\n\n         IF(OPT_RAD == 2) THEN\n           GAP     = 0.0\n           KOPEN   = 0.0\n         END IF\n\n         IF(OPT_RAD == 3) THEN\n           GAP     = 1.0-FVEG\n           KOPEN   = 1.0-FVEG\n         END IF\n     end if\n\n! calculate two-stream parameters OMEGA, BETAD, BETAI, AVMU, GDIR, EXT.\n! OMEGA, BETAD, BETAI are adjusted for snow. values for OMEGA*BETAD\n! and OMEGA*BETAI are calculated and then divided by the new OMEGA\n! because the product OMEGA*BETAI, OMEGA*BETAD is used in solution.\n! also, the transmittances and reflectances (TAU, RHO) are linear\n! weights of leaf and stem values.\n\n     COSZI  = MAX(0.001, COSZ)\n     CHIL   = MIN( MAX(parameters%XL, -0.4), 0.6)\n     IF (ABS(CHIL) .LE. 0.01) CHIL = 0.01\n     PHI1   = 0.5 - 0.633*CHIL - 0.330*CHIL*CHIL\n     PHI2   = 0.877 * (1.-2.*PHI1)\n     GDIR   = PHI1 + PHI2*COSZI\n     EXT    = GDIR/COSZI\n     AVMU   = ( 1. - PHI1/PHI2 * LOG((PHI1+PHI2)/PHI1) ) / PHI2\n     OMEGAL = RHO(IB) + TAU(IB)\n     TMP0   = GDIR + PHI2*COSZI\n     TMP1   = PHI1*COSZI\n     ASU    = 0.5*OMEGAL*GDIR/TMP0 * ( 1.-TMP1/TMP0*LOG((TMP1+TMP0)/TMP1) )\n     BETADL = (1.+AVMU*EXT)/(OMEGAL*AVMU*EXT)*ASU\n     BETAIL = 0.5 * ( RHO(IB)+TAU(IB) + (RHO(IB)-TAU(IB))   &\n            * ((1.+CHIL)/2.)**2 ) / OMEGAL\n\n! adjust omega, betad, and betai for intercepted snow\n\n     IF (T .GT. TFRZ) THEN                                !no snow\n        TMP0 = OMEGAL\n        TMP1 = BETADL\n        TMP2 = BETAIL\n     ELSE\n        TMP0 =   (1.-FWET)*OMEGAL        + FWET*parameters%OMEGAS(IB)\n        TMP1 = ( (1.-FWET)*OMEGAL*BETADL + FWET*parameters%OMEGAS(IB)*parameters%BETADS ) / TMP0\n        TMP2 = ( (1.-FWET)*OMEGAL*BETAIL + FWET*parameters%OMEGAS(IB)*parameters%BETAIS ) / TMP0\n     END IF\n\n     OMEGA = TMP0\n     BETAD = TMP1\n     BETAI = TMP2\n\n! absorbed, reflected, transmitted fluxes per unit incoming radiation\n\n     B = 1. - OMEGA + OMEGA*BETAI\n     C = OMEGA*BETAI\n     TMP0 = AVMU*EXT\n     D = TMP0 * OMEGA*BETAD\n     F = TMP0 * OMEGA*(1.-BETAD)\n     TMP1 = B*B - C*C\n     H = SQRT(TMP1) / AVMU\n     SIGMA = TMP0*TMP0 - TMP1\n     if ( ABS (SIGMA) < 1.e-6 ) SIGMA = SIGN(1.e-6,SIGMA)\n     P1 = B + AVMU*H\n     P2 = B - AVMU*H\n     P3 = B + TMP0\n     P4 = B - TMP0\n     S1 = EXP(-H*VAI)\n     S2 = EXP(-EXT*VAI)\n     IF (IC .EQ. 0) THEN\n        U1 = B - C/ALBGRD(IB)\n        U2 = B - C*ALBGRD(IB)\n        U3 = F + C*ALBGRD(IB)\n     ELSE\n        U1 = B - C/ALBGRI(IB)\n        U2 = B - C*ALBGRI(IB)\n        U3 = F + C*ALBGRI(IB)\n     END IF\n     TMP2 = U1 - AVMU*H\n     TMP3 = U1 + AVMU*H\n     D1 = P1*TMP2/S1 - P2*TMP3*S1\n     TMP4 = U2 + AVMU*H\n     TMP5 = U2 - AVMU*H\n     D2 = TMP4/S1 - TMP5*S1\n     H1 = -D*P4 - C*F\n     TMP6 = D - H1*P3/SIGMA\n     TMP7 = ( D - C - H1/SIGMA*(U1+TMP0) ) * S2\n     H2 = ( TMP6*TMP2/S1 - P2*TMP7 ) / D1\n     H3 = - ( TMP6*TMP3*S1 - P1*TMP7 ) / D1\n     H4 = -F*P3 - C*D\n     TMP8 = H4/SIGMA\n     TMP9 = ( U3 - TMP8*(U2-TMP0) ) * S2\n     H5 = - ( TMP8*TMP4/S1 + TMP9 ) / D2\n     H6 = ( TMP8*TMP5*S1 + TMP9 ) / D2\n     H7 = (C*TMP2) / (D1*S1)\n     H8 = (-C*TMP3*S1) / D1\n     H9 = TMP4 / (D2*S1)\n     H10 = (-TMP5*S1) / D2\n\n! downward direct and diffuse fluxes below vegetation\n! Niu and Yang (2004), JGR.\n\n     IF (IC .EQ. 0) THEN\n        FTDS = S2                           *(1.0-GAP) + GAP\n        FTIS = (H4*S2/SIGMA + H5*S1 + H6/S1)*(1.0-GAP)\n     ELSE\n        FTDS = 0.\n        FTIS = (H9*S1 + H10/S1)*(1.0-KOPEN) + KOPEN\n     END IF\n     FTD(IB) = FTDS\n     FTI(IB) = FTIS\n\n! flux reflected by the surface (veg. and ground)\n\n     IF (IC .EQ. 0) THEN\n        FRES   = (H1/SIGMA + H2 + H3)*(1.0-GAP  ) + ALBGRD(IB)*GAP\n        FREVEG = (H1/SIGMA + H2 + H3)*(1.0-GAP  )\n        FREBAR = ALBGRD(IB)*GAP                   !jref - separate veg. and ground reflection\n     ELSE\n        FRES   = (H7 + H8) *(1.0-KOPEN) + ALBGRI(IB)*KOPEN\n        FREVEG = (H7 + H8) *(1.0-KOPEN) + ALBGRI(IB)*KOPEN\n        FREBAR = 0                                !jref - separate veg. and ground reflection\n     END IF\n     FRE(IB) = FRES\n\n     FREV(IB) = FREVEG\n     FREG(IB) = FREBAR\n\n! flux absorbed by vegetation\n\n     FAB(IB) = 1. - FRE(IB) - (1.-ALBGRD(IB))*FTD(IB) &\n                            - (1.-ALBGRI(IB))*FTI(IB)\n\n!if(iloc == 1.and.jloc ==  2) then\n!  write(*,'(a7,2i2,5(a6,f8.4),2(a9,f8.4))') \"ib,ic: \",ib,ic,\" GAP: \",GAP,\" FTD: \",FTD(IB),\" FTI: \",FTI(IB),\" FRE: \", &\n!         FRE(IB),\" FAB: \",FAB(IB),\" ALBGRD: \",ALBGRD(IB),\" ALBGRI: \",ALBGRI(IB)\n!end if\n\n  END SUBROUTINE TWOSTREAM\n\n!== begin vege_flux ================================================================================\n\n  SUBROUTINE VEGE_FLUX(parameters,NSNOW   ,NSOIL   ,ISNOW   ,VEGTYP  ,VEG     , & !in\n                       DT      ,SAV     ,SAG     ,LWDN    ,UR      , & !in\n                       UU      ,VV      ,SFCTMP  ,THAIR   ,QAIR    , & !in\n                       EAIR    ,RHOAIR  ,SNOWH   ,VAI     ,GAMMAV   ,GAMMAG,  & !in\n                       FWET    ,LAISUN  ,LAISHA  ,CWP     ,DZSNSO  , & !in\n                       ZLVL    ,ZPD     ,Z0M     ,FVEG    , & !in\n                       Z0MG    ,EMV     ,EMG     ,CANLIQ  ,FSNO,          & !in\n                       CANICE  ,STC     ,DF      ,RSSUN   ,RSSHA   , & !in\n                       RSURF   ,LATHEAV ,LATHEAG  ,PARSUN  ,PARSHA  ,IGS     , & !in\n                       FOLN    ,CO2AIR  ,O2AIR   ,BTRAN   ,SFCPRS  , & !in\n                       RHSUR   ,ILOC    ,JLOC    ,Q2      ,PAHV    ,PAHG     , & !in\n                       EAH     ,TAH     ,TV      ,TG      ,CM      , & !inout\n                       CH      ,DX      ,DZ8W    ,                   & !\n                       TAUXV   ,TAUYV   ,IRG     ,IRC     ,SHG     , & !out\n                       SHC     ,EVG     ,EVC     ,TR      ,GH      , & !out\n                       T2MV    ,PSNSUN  ,PSNSHA  ,                   & !out\n                       QC      ,QSFC    ,PSFC    ,                   & !in\n                       Q2V     ,CAH2    ,CHLEAF  ,CHUC    )            !inout\n\n! --------------------------------------------------------------------------------------------------\n! use newton-raphson iteration to solve for vegetation (tv) and\n! ground (tg) temperatures that balance the surface energy budgets\n\n! vegetated:\n! -SAV + IRC[TV] + SHC[TV] + EVC[TV] + TR[TV] = 0\n! -SAG + IRG[TG] + SHG[TG] + EVG[TG] + GH[TG] = 0\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                         INTENT(IN) :: ILOC   !grid index\n  INTEGER,                         INTENT(IN) :: JLOC   !grid index\n  LOGICAL,                         INTENT(IN) :: VEG    !true if vegetated surface\n  INTEGER,                         INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  INTEGER,                         INTENT(IN) :: NSOIL  !number of soil layers\n  INTEGER,                         INTENT(IN) :: ISNOW  !actual no. of snow layers\n  INTEGER,                         INTENT(IN) :: VEGTYP !vegetation physiology type\n  REAL,                            INTENT(IN) :: FVEG   !greeness vegetation fraction (-)\n  REAL,                            INTENT(IN) :: SAV    !solar rad absorbed by veg (w/m2)\n  REAL,                            INTENT(IN) :: SAG    !solar rad absorbed by ground (w/m2)\n  REAL,                            INTENT(IN) :: LWDN   !atmospheric longwave radiation (w/m2)\n  REAL,                            INTENT(IN) :: UR     !wind speed at height zlvl (m/s)\n  REAL,                            INTENT(IN) :: UU     !wind speed in eastward dir (m/s)\n  REAL,                            INTENT(IN) :: VV     !wind speed in northward dir (m/s)\n  REAL,                            INTENT(IN) :: SFCTMP !air temperature at reference height (k)\n  REAL,                            INTENT(IN) :: THAIR  !potential temp at reference height (k)\n  REAL,                            INTENT(IN) :: EAIR   !vapor pressure air at zlvl (pa)\n  REAL,                            INTENT(IN) :: QAIR   !specific humidity at zlvl (kg/kg)\n  REAL,                            INTENT(IN) :: RHOAIR !density air (kg/m**3)\n  REAL,                            INTENT(IN) :: DT     !time step (s)\n  REAL,                            INTENT(IN) :: FSNO     !snow fraction\n\n  REAL,                            INTENT(IN) :: SNOWH  !actual snow depth [m]\n  REAL,                            INTENT(IN) :: FWET   !wetted fraction of canopy\n  REAL,                            INTENT(IN) :: CWP    !canopy wind parameter\n\n  REAL,                            INTENT(IN) :: VAI    !total leaf area index + stem area index\n  REAL,                            INTENT(IN) :: LAISUN !sunlit leaf area index, one-sided (m2/m2)\n  REAL,                            INTENT(IN) :: LAISHA !shaded leaf area index, one-sided (m2/m2)\n  REAL,                            INTENT(IN) :: ZLVL   !reference height (m)\n  REAL,                            INTENT(IN) :: ZPD    !zero plane displacement (m)\n  REAL,                            INTENT(IN) :: Z0M    !roughness length, momentum (m)\n  REAL,                            INTENT(IN) :: Z0MG   !roughness length, momentum, ground (m)\n  REAL,                            INTENT(IN) :: EMV    !vegetation emissivity\n  REAL,                            INTENT(IN) :: EMG    !ground emissivity\n\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: STC    !soil/snow temperature (k)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DF     !thermal conductivity of snow/soil (w/m/k)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !thinkness of snow/soil layers (m)\n  REAL,                            INTENT(IN) :: CANLIQ !intercepted liquid water (mm)\n  REAL,                            INTENT(IN) :: CANICE !intercepted ice mass (mm)\n  REAL,                            INTENT(IN) :: RSURF  !ground surface resistance (s/m)\n!  REAL,                            INTENT(IN) :: GAMMA  !psychrometric constant (pa/K)\n!  REAL,                            INTENT(IN) :: LATHEA !latent heat of vaporization/subli (j/kg)\n  REAL,                            INTENT(IN) :: GAMMAV  !psychrometric constant (pa/K)\n  REAL,                            INTENT(IN) :: LATHEAV !latent heat of vaporization/subli (j/kg)\n  REAL,                            INTENT(IN) :: GAMMAG  !psychrometric constant (pa/K)\n  REAL,                            INTENT(IN) :: LATHEAG !latent heat of vaporization/subli (j/kg)\n  REAL,                            INTENT(IN) :: PARSUN !par absorbed per unit sunlit lai (w/m2)\n  REAL,                            INTENT(IN) :: PARSHA !par absorbed per unit shaded lai (w/m2)\n  REAL,                            INTENT(IN) :: FOLN   !foliage nitrogen (%)\n  REAL,                            INTENT(IN) :: CO2AIR !atmospheric co2 concentration (pa)\n  REAL,                            INTENT(IN) :: O2AIR  !atmospheric o2 concentration (pa)\n  REAL,                            INTENT(IN) :: IGS    !growing season index (0=off, 1=on)\n  REAL,                            INTENT(IN) :: SFCPRS !pressure (pa)\n  REAL,                            INTENT(IN) :: BTRAN  !soil water transpiration factor (0 to 1)\n  REAL,                            INTENT(IN) :: RHSUR  !raltive humidity in surface soil/snow air space (-)\n\n  REAL                           , INTENT(IN) :: QC     !cloud water mixing ratio\n  REAL                           , INTENT(IN) :: PSFC   !pressure at lowest model layer\n  REAL                           , INTENT(IN) :: DX     !grid spacing\n  REAL                           , INTENT(IN) :: Q2     !mixing ratio (kg/kg)\n  REAL                           , INTENT(IN) :: DZ8W   !thickness of lowest layer\n  REAL                           , INTENT(INOUT) :: QSFC   !mixing ratio at lowest model layer\n  REAL, INTENT(IN)   :: PAHV  !precipitation advected heat - canopy net IN (W/m2)\n  REAL, INTENT(IN)   :: PAHG  !precipitation advected heat - ground net IN (W/m2)\n\n! input/output\n  REAL,                         INTENT(INOUT) :: EAH    !canopy air vapor pressure (pa)\n  REAL,                         INTENT(INOUT) :: TAH    !canopy air temperature (k)\n  REAL,                         INTENT(INOUT) :: TV     !vegetation temperature (k)\n  REAL,                         INTENT(INOUT) :: TG     !ground temperature (k)\n  REAL,                         INTENT(INOUT) :: CM     !momentum drag coefficient\n  REAL,                         INTENT(INOUT) :: CH     !sensible heat exchange coefficient\n\n! output\n! -FSA + FIRA + FSH + (FCEV + FCTR + FGEV) + FCST + SSOIL = 0\n  REAL,                           INTENT(OUT) :: TAUXV  !wind stress: e-w (n/m2)\n  REAL,                           INTENT(OUT) :: TAUYV  !wind stress: n-s (n/m2)\n  REAL,                           INTENT(OUT) :: IRC    !net longwave radiation (w/m2) [+= to atm]\n  REAL,                           INTENT(OUT) :: SHC    !sensible heat flux (w/m2)     [+= to atm]\n  REAL,                           INTENT(OUT) :: EVC    !evaporation heat flux (w/m2)  [+= to atm]\n  REAL,                           INTENT(OUT) :: IRG    !net longwave radiation (w/m2) [+= to atm]\n  REAL,                           INTENT(OUT) :: SHG    !sensible heat flux (w/m2)     [+= to atm]\n  REAL,                           INTENT(OUT) :: EVG    !evaporation heat flux (w/m2)  [+= to atm]\n  REAL,                           INTENT(OUT) :: TR     !transpiration heat flux (w/m2)[+= to atm]\n  REAL,                           INTENT(OUT) :: GH     !ground heat (w/m2) [+ = to soil]\n  REAL,                           INTENT(OUT) :: T2MV   !2 m height air temperature (k)\n  REAL,                           INTENT(OUT) :: PSNSUN !sunlit leaf photosynthesis (umolco2/m2/s)\n  REAL,                           INTENT(OUT) :: PSNSHA !shaded leaf photosynthesis (umolco2/m2/s)\n  REAL,                           INTENT(OUT) :: CHLEAF !leaf exchange coefficient\n  REAL,                           INTENT(OUT) :: CHUC   !under canopy exchange coefficient\n\n  REAL,                           INTENT(OUT) :: Q2V\n  REAL :: CAH    !sensible heat conductance, canopy air to ZLVL air (m/s)\n  REAL :: U10V    !10 m wind speed in eastward dir (m/s)\n  REAL :: V10V    !10 m wind speed in eastward dir (m/s)\n  REAL :: WSPD\n\n! ------------------------ local variables ----------------------------------------------------\n  REAL :: CW           !water vapor exchange coefficient\n  REAL :: FV           !friction velocity (m/s)\n  REAL :: WSTAR        !friction velocity n vertical direction (m/s) (only for SFCDIF2)\n  REAL :: Z0H          !roughness length, sensible heat (m)\n  REAL :: Z0HG         !roughness length, sensible heat (m)\n  REAL :: RB           !bulk leaf boundary layer resistance (s/m)\n  REAL :: RAMC         !aerodynamic resistance for momentum (s/m)\n  REAL :: RAHC         !aerodynamic resistance for sensible heat (s/m)\n  REAL :: RAWC         !aerodynamic resistance for water vapor (s/m)\n  REAL :: RAMG         !aerodynamic resistance for momentum (s/m)\n  REAL :: RAHG         !aerodynamic resistance for sensible heat (s/m)\n  REAL :: RAWG         !aerodynamic resistance for water vapor (s/m)\n\n  REAL, INTENT(OUT) :: RSSUN        !sunlit leaf stomatal resistance (s/m)\n  REAL, INTENT(OUT) :: RSSHA        !shaded leaf stomatal resistance (s/m)\n\n  REAL :: MOL          !Monin-Obukhov length (m)\n  REAL :: DTV          !change in tv, last iteration (k)\n  REAL :: DTG          !change in tg, last iteration (k)\n\n  REAL :: AIR,CIR      !coefficients for ir as function of ts**4\n  REAL :: CSH          !coefficients for sh as function of ts\n  REAL :: CEV          !coefficients for ev as function of esat[ts]\n  REAL :: CGH          !coefficients for st as function of ts\n  REAL :: ATR,CTR      !coefficients for tr as function of esat[ts]\n  REAL :: ATA,BTA      !coefficients for tah as function of ts\n  REAL :: AEA,BEA      !coefficients for eah as function of esat[ts]\n\n  REAL :: ESTV         !saturation vapor pressure at tv (pa)\n  REAL :: ESTG         !saturation vapor pressure at tg (pa)\n  REAL :: DESTV        !d(es)/dt at ts (pa/k)\n  REAL :: DESTG        !d(es)/dt at tg (pa/k)\n  REAL :: ESATW        !es for water\n  REAL :: ESATI        !es for ice\n  REAL :: DSATW        !d(es)/dt at tg (pa/k) for water\n  REAL :: DSATI        !d(es)/dt at tg (pa/k) for ice\n\n  REAL :: FM           !momentum stability correction, weighted by prior iters\n  REAL :: FH           !sen heat stability correction, weighted by prior iters\n  REAL :: FHG          !sen heat stability correction, ground\n  REAL :: HCAN         !canopy height (m) [note: hcan >= z0mg]\n\n  REAL :: A            !temporary calculation\n  REAL :: B            !temporary calculation\n  REAL :: CVH          !sensible heat conductance, leaf surface to canopy air (m/s)\n  REAL :: CAW          !latent heat conductance, canopy air ZLVL air (m/s)\n  REAL :: CTW          !transpiration conductance, leaf to canopy air (m/s)\n  REAL :: CEW          !evaporation conductance, leaf to canopy air (m/s)\n  REAL :: CGW          !latent heat conductance, ground to canopy air (m/s)\n  REAL :: COND         !sum of conductances (s/m)\n  REAL :: UC           !wind speed at top of canopy (m/s)\n  REAL :: KH           !turbulent transfer coefficient, sensible heat, (m2/s)\n  REAL :: H            !temporary sensible heat flux (w/m2)\n  REAL :: HG           !temporary sensible heat flux (w/m2)\n  REAL :: MOZ          !Monin-Obukhov stability parameter\n  REAL :: MOZG         !Monin-Obukhov stability parameter\n  REAL :: MOZOLD       !Monin-Obukhov stability parameter from prior iteration\n  REAL :: FM2          !Monin-Obukhov momentum adjustment at 2m\n  REAL :: FH2          !Monin-Obukhov heat adjustment at 2m\n  REAL :: CH2          !Surface exchange at 2m\n  REAL :: THSTAR          !Surface exchange at 2m\n\n  REAL :: THVAIR\n  REAL :: THAH\n  REAL :: RAHC2        !aerodynamic resistance for sensible heat (s/m)\n  REAL :: RAWC2        !aerodynamic resistance for water vapor (s/m)\n  REAL, INTENT(OUT):: CAH2         !sensible heat conductance for diagnostics\n  REAL :: CH2V         !exchange coefficient for 2m over vegetation.\n  REAL :: CQ2V         !exchange coefficient for 2m over vegetation.\n  REAL :: EAH2         !2m vapor pressure over canopy\n  REAL :: QFX        !moisture flux\n  REAL :: E1\n\n\n  REAL :: VAIE         !total leaf area index + stem area index,effective\n  REAL :: LAISUNE      !sunlit leaf area index, one-sided (m2/m2),effective\n  REAL :: LAISHAE      !shaded leaf area index, one-sided (m2/m2),effective\n\n  INTEGER :: K         !index\n  INTEGER :: ITER      !iteration index\n\n!jref - NITERC test from 5 to 20\n  INTEGER, PARAMETER :: NITERC = 20   !number of iterations for surface temperature\n!jref - NITERG test from 3-5\n  INTEGER, PARAMETER :: NITERG = 5   !number of iterations for ground temperature\n  INTEGER :: MOZSGN    !number of times MOZ changes sign\n  REAL    :: MPE       !prevents overflow error if division by zero\n\n  INTEGER :: LITER     !Last iteration\n\n\n  REAL :: T, TDC       !Kelvin to degree Celsius with limit -50 to +50\n\n  character(len=80) ::  message\n\n  TDC(T)   = MIN( 50., MAX(-50.,(T-TFRZ)) )\n! ---------------------------------------------------------------------------------------------\n\n        MPE = 1E-6\n        LITER = 0\n        FV = 0.1\n\n! ---------------------------------------------------------------------------------------------\n! initialization variables that do not depend on stability iteration\n! ---------------------------------------------------------------------------------------------\n        DTV = 0.\n        DTG = 0.\n        MOZ    = 0.\n        MOZSGN = 0\n        MOZOLD = 0.\n        FH2    = 0.\n        HG     = 0.\n        H      = 0.\n        QFX    = 0.\n\n! limit LAI\n\n        VAIE    = MIN(6.,VAI   )\n        LAISUNE = MIN(6.,LAISUN)\n        LAISHAE = MIN(6.,LAISHA)\n\n! saturation vapor pressure at ground temperature\n\n        T = TDC(TG)\n        CALL ESAT(T, ESATW, ESATI, DSATW, DSATI)\n        IF (T .GT. 0.) THEN\n           ESTG = ESATW\n        ELSE\n           ESTG = ESATI\n        END IF\n\n!jref - consistent surface specific humidity for sfcdif3 and sfcdif4\n\n        QSFC = 0.622*EAIR/(PSFC-0.378*EAIR)\n\n! canopy height\n\n        HCAN = parameters%HVT\n        UC = UR*LOG(HCAN/Z0M)/LOG(ZLVL/Z0M)\n        UC = UR*LOG((HCAN-ZPD+Z0M)/Z0M)/LOG(ZLVL/Z0M)   ! MB: add ZPD v3.7\n        IF((HCAN-ZPD) <= 0.) THEN\n          WRITE(message,*) \"CRITICAL PROBLEM: HCAN <= ZPD\"\n          call wrf_message ( message )\n          WRITE(message,*) 'i,j point=',ILOC, JLOC\n          call wrf_message ( message )\n          WRITE(message,*) 'HCAN  =',HCAN\n          call wrf_message ( message )\n          WRITE(message,*) 'ZPD   =',ZPD\n          call wrf_message ( message )\n          write (message, *) 'SNOWH =',SNOWH\n          call wrf_message ( message )\n          call wrf_error_fatal ( \"CRITICAL PROBLEM IN MODULE_SF_NOAHMPLSM:VEGEFLUX\" )\n        END IF\n\n! prepare for longwave rad.\n\n        AIR = -EMV*(1.+(1.-EMV)*(1.-EMG))*LWDN - EMV*EMG*SB*TG**4\n        CIR = (2.-EMV*(1.-EMG))*EMV*SB\n! ---------------------------------------------------------------------------------------------\n      loop1: DO ITER = 1, NITERC    !  begin stability iteration\n\n       IF(ITER == 1) THEN\n            Z0H  = Z0M\n            Z0HG = Z0MG\n       ELSE\n            Z0H  = Z0M    !* EXP(-CZIL*0.4*258.2*SQRT(FV*Z0M))\n            Z0HG = Z0MG   !* EXP(-CZIL*0.4*258.2*SQRT(FV*Z0MG))\n       END IF\n\n! aerodyn resistances between heights zlvl and d+z0v\n\n       IF(OPT_SFC == 1) THEN\n          CALL SFCDIF1(parameters,ITER   ,SFCTMP ,RHOAIR ,H      ,QAIR   , & !in\n                       ZLVL   ,ZPD    ,Z0M    ,Z0H    ,UR     , & !in\n                       MPE    ,ILOC   ,JLOC   ,                 & !in\n                       MOZ    ,MOZSGN ,FM     ,FH     ,FM2,FH2, & !inout\n                       CM     ,CH     ,FV     ,CH2     )          !out\n       ENDIF\n\n       IF(OPT_SFC == 2) THEN\n          CALL SFCDIF2(parameters,ITER   ,Z0M    ,TAH    ,THAIR  ,UR     , & !in\n                       ZLVL   ,ILOC   ,JLOC   ,         & !in\n                       CM     ,CH     ,MOZ    ,WSTAR  ,         & !in\n                       FV     )                                   !out\n          ! Undo the multiplication by windspeed that SFCDIF2\n          ! applies to exchange coefficients CH and CM:\n          CH = CH / UR\n          CM = CM / UR\n       ENDIF\n\n       RAMC = MAX(1.,1./(CM*UR))\n       RAHC = MAX(1.,1./(CH*UR))\n       RAWC = RAHC\n\n! aerodyn resistance between heights z0g and d+z0v, RAG, and leaf\n! boundary layer resistance, RB\n\n       CALL RAGRB(parameters,ITER   ,VAIE   ,RHOAIR ,HG     ,TAH    , & !in\n                  ZPD    ,Z0MG   ,Z0HG   ,HCAN   ,UC     , & !in\n                  Z0H    ,FV     ,CWP    ,VEGTYP ,MPE    , & !in\n                  TV     ,MOZG   ,FHG    ,ILOC   ,JLOC   , & !inout\n                  RAMG   ,RAHG   ,RAWG   ,RB     )           !out\n\n! es and d(es)/dt evaluated at tv\n\n       T = TDC(TV)\n       CALL ESAT(T, ESATW, ESATI, DSATW, DSATI)\n       IF (T .GT. 0.) THEN\n          ESTV  = ESATW\n          DESTV = DSATW\n       ELSE\n          ESTV  = ESATI\n          DESTV = DSATI\n       END IF\n\n! stomatal resistance\n\n     IF(ITER == 1) THEN\n        IF (OPT_CRS == 1) then  ! Ball-Berry\n         CALL STOMATA (parameters,VEGTYP,MPE   ,PARSUN ,FOLN  ,ILOC  , JLOC , & !in\n                       TV    ,ESTV  ,EAH    ,SFCTMP,SFCPRS, & !in\n                       O2AIR ,CO2AIR,IGS    ,BTRAN ,RB    , & !in\n                       RSSUN ,PSNSUN)                         !out\n\n         CALL STOMATA (parameters,VEGTYP,MPE   ,PARSHA ,FOLN  ,ILOC  , JLOC , & !in\n                       TV    ,ESTV  ,EAH    ,SFCTMP,SFCPRS, & !in\n                       O2AIR ,CO2AIR,IGS    ,BTRAN ,RB    , & !in\n                       RSSHA ,PSNSHA)                         !out\n        END IF\n\n        IF (OPT_CRS == 2) then  ! Jarvis\n         CALL  CANRES (parameters,PARSUN,TV    ,BTRAN ,EAH    ,SFCPRS, & !in\n                       RSSUN ,PSNSUN,ILOC  ,JLOC   )          !out\n\n         CALL  CANRES (parameters,PARSHA,TV    ,BTRAN ,EAH    ,SFCPRS, & !in\n                       RSSHA ,PSNSHA,ILOC  ,JLOC   )          !out\n        END IF\n     END IF\n\n! prepare for sensible heat flux above veg.\n\n        CAH  = 1./RAHC\n        CVH  = 2.*VAIE/RB\n        CGH  = 1./RAHG\n        COND = CAH + CVH + CGH\n        ATA  = (SFCTMP*CAH + TG*CGH) / COND\n        BTA  = CVH/COND\n        CSH  = (1.-BTA)*RHOAIR*CPAIR*CVH\n\n! prepare for latent heat flux above veg.\n\n        CAW  = 1./RAWC\n        CEW  = FWET*VAIE/RB\n        CTW  = (1.-FWET)*(LAISUNE/(RB+RSSUN) + LAISHAE/(RB+RSSHA))\n        CGW  = 1./(RAWG+RSURF)\n        COND = CAW + CEW + CTW + CGW\n        AEA  = (EAIR*CAW + ESTG*CGW) / COND\n        BEA  = (CEW+CTW)/COND\n        CEV  = (1.-BEA)*CEW*RHOAIR*CPAIR/GAMMAV   ! Barlage: change to vegetation v3.6\n        CTR  = (1.-BEA)*CTW*RHOAIR*CPAIR/GAMMAV\n\n! evaluate surface fluxes with current temperature and solve for dts\n\n        TAH = ATA + BTA*TV               ! canopy air T.\n        EAH = AEA + BEA*ESTV             ! canopy air e\n\n        IRC = FVEG*(AIR + CIR*TV**4)\n        SHC = FVEG*RHOAIR*CPAIR*CVH * (  TV-TAH)\n        EVC = FVEG*RHOAIR*CPAIR*CEW * (ESTV-EAH) / GAMMAV ! Barlage: change to v in v3.6\n        TR  = FVEG*RHOAIR*CPAIR*CTW * (ESTV-EAH) / GAMMAV\n\tIF (TV > TFRZ) THEN\n          EVC = MIN(CANLIQ*LATHEAV/DT,EVC)    ! Barlage: add if block for canice in v3.6\n\tELSE\n          EVC = MIN(CANICE*LATHEAV/DT,EVC)\n\tEND IF\n\n        B   = SAV-IRC-SHC-EVC-TR+PAHV                          !additional w/m2\n        A   = FVEG*(4.*CIR*TV**3 + CSH + (CEV+CTR)*DESTV) !volumetric heat capacity\n        DTV = B/A\n\n        IRC = IRC + FVEG*4.*CIR*TV**3*DTV\n        SHC = SHC + FVEG*CSH*DTV\n        EVC = EVC + FVEG*CEV*DESTV*DTV\n        TR  = TR  + FVEG*CTR*DESTV*DTV\n\n! update vegetation surface temperature\n        TV  = TV + DTV\n!        TAH = ATA + BTA*TV               ! canopy air T; update here for consistency\n\n! for computing M-O length in the next iteration\n        H  = RHOAIR*CPAIR*(TAH - SFCTMP) /RAHC\n        HG = RHOAIR*CPAIR*(TG  - TAH)   /RAHG\n\n! consistent specific humidity from canopy air vapor pressure\n        QSFC = (0.622*EAH)/(SFCPRS-0.378*EAH)\n\n        IF (LITER == 1) THEN\n           exit loop1\n        ENDIF\n        IF (ITER >= 5 .AND. ABS(DTV) <= 0.01 .AND. LITER == 0) THEN\n           LITER = 1\n        ENDIF\n\n     END DO loop1 ! end stability iteration\n\n! under-canopy fluxes and tg\n\n        AIR = - EMG*(1.-EMV)*LWDN - EMG*EMV*SB*TV**4\n        CIR = EMG*SB\n        CSH = RHOAIR*CPAIR/RAHG\n        CEV = RHOAIR*CPAIR / (GAMMAG*(RAWG+RSURF))  ! Barlage: change to ground v3.6\n        CGH = 2.*DF(ISNOW+1)/DZSNSO(ISNOW+1)\n\n     loop2: DO ITER = 1, NITERG\n\n        T = TDC(TG)\n        CALL ESAT(T, ESATW, ESATI, DSATW, DSATI)\n        IF (T .GT. 0.) THEN\n            ESTG  = ESATW\n            DESTG = DSATW\n        ELSE\n            ESTG  = ESATI\n            DESTG = DSATI\n        END IF\n\n        IRG = CIR*TG**4 + AIR\n        SHG = CSH * (TG         - TAH         )\n        EVG = CEV * (ESTG*RHSUR - EAH         )\n        GH  = CGH * (TG         - STC(ISNOW+1))\n\n        B = SAG-IRG-SHG-EVG-GH+PAHG\n        A = 4.*CIR*TG**3+CSH+CEV*DESTG+CGH\n        DTG = B/A\n\n        IRG = IRG + 4.*CIR*TG**3*DTG\n        SHG = SHG + CSH*DTG\n        EVG = EVG + CEV*DESTG*DTG\n        GH  = GH  + CGH*DTG\n        TG  = TG  + DTG\n\n     END DO loop2\n\n!     TAH = (CAH*SFCTMP + CVH*TV + CGH*TG)/(CAH + CVH + CGH)\n\n! if snow on ground and TG > TFRZ: reset TG = TFRZ. reevaluate ground fluxes.\n\n     IF(OPT_STC == 1 .OR. OPT_STC == 3) THEN\n     IF (SNOWH > 0.05 .AND. TG > TFRZ) THEN\n        IF(OPT_STC == 1) TG  = TFRZ\n        IF(OPT_STC == 3) TG  = (1.-FSNO)*TG + FSNO*TFRZ   ! MB: allow TG>0C during melt v3.7\n        IRG = CIR*TG**4 - EMG*(1.-EMV)*LWDN - EMG*EMV*SB*TV**4\n        SHG = CSH * (TG         - TAH)\n        EVG = CEV * (ESTG*RHSUR - EAH)\n        GH  = SAG+PAHG - (IRG+SHG+EVG)\n     END IF\n     END IF\n\n! wind stresses\n\n     TAUXV = -RHOAIR*CM*UR*UU\n     TAUYV = -RHOAIR*CM*UR*VV\n\n! consistent vegetation air temperature and vapor pressure since TG is not consistent with the TAH/EAH\n! calculation.\n!     TAH = SFCTMP + (SHG+SHC)/(RHOAIR*CPAIR*CAH)\n!     TAH = SFCTMP + (SHG*FVEG+SHC)/(RHOAIR*CPAIR*CAH) ! ground flux need fveg\n!     EAH = EAIR + (EVC+FVEG*(TR+EVG))/(RHOAIR*CAW*CPAIR/GAMMAG )\n!     QFX = (QSFC-QAIR)*RHOAIR*CAW !*CPAIR/GAMMAG\n\n! 2m temperature over vegetation ( corrected for low CQ2V values )\n   IF (OPT_SFC == 1 .OR. OPT_SFC == 2) THEN\n!      CAH2 = FV*1./VKC*LOG((2.+Z0H)/Z0H)\n      CAH2 = FV*VKC/LOG((2.+Z0H)/Z0H)\n      CAH2 = FV*VKC/(LOG((2.+Z0H)/Z0H)-FH2)\n      CQ2V = CAH2\n      IF (CAH2 .LT. 1.E-5 ) THEN\n         T2MV = TAH\n!         Q2V  = (EAH*0.622/(SFCPRS - 0.378*EAH))\n         Q2V  = QSFC\n      ELSE\n         T2MV = TAH - (SHG+SHC/FVEG)/(RHOAIR*CPAIR) * 1./CAH2\n!         Q2V = (EAH*0.622/(SFCPRS - 0.378*EAH))- QFX/(RHOAIR*FV)* 1./VKC * LOG((2.+Z0H)/Z0H)\n         Q2V = QSFC - ((EVC+TR)/FVEG+EVG)/(LATHEAV*RHOAIR) * 1./CQ2V\n      ENDIF\n   ENDIF\n\n! update CH for output\n     CH = CAH\n     CHLEAF = CVH\n     CHUC = 1./RAHG\n\n  END SUBROUTINE VEGE_FLUX\n\n!== begin bare_flux ================================================================================\n\n  SUBROUTINE BARE_FLUX (parameters,NSNOW   ,NSOIL   ,ISNOW   ,DT      ,SAG     , & !in\n                        LWDN    ,UR      ,UU      ,VV      ,SFCTMP  , & !in\n                        THAIR   ,QAIR    ,EAIR    ,RHOAIR  ,SNOWH   , & !in\n                        DZSNSO  ,ZLVL    ,ZPD     ,Z0M     ,FSNO    , & !in\n                        EMG     ,STC     ,DF      ,RSURF   ,LATHEA  , & !in\n                        GAMMA   ,RHSUR   ,ILOC    ,JLOC    ,Q2      ,PAHB  , & !in\n                        TGB     ,CM      ,CH      ,          & !inout\n                        TAUXB   ,TAUYB   ,IRB     ,SHB     ,EVB     , & !out\n                        GHB     ,T2MB    ,DX      ,DZ8W    ,IVGTYP  , & !out\n                        QC      ,QSFC    ,PSFC    ,                   & !in\n                        SFCPRS  ,Q2B     ,EHB2    )                     !in\n\n! --------------------------------------------------------------------------------------------------\n! use newton-raphson iteration to solve ground (tg) temperature\n! that balances the surface energy budgets for bare soil fraction.\n\n! bare soil:\n! -SAB + IRB[TG] + SHB[TG] + EVB[TG] + GHB[TG] = 0\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  integer                        , INTENT(IN) :: ILOC   !grid index\n  integer                        , INTENT(IN) :: JLOC   !grid index\n  INTEGER,                         INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  INTEGER,                         INTENT(IN) :: NSOIL  !number of soil layers\n  INTEGER,                         INTENT(IN) :: ISNOW  !actual no. of snow layers\n  REAL,                            INTENT(IN) :: DT     !time step (s)\n  REAL,                            INTENT(IN) :: SAG    !solar radiation absorbed by ground (w/m2)\n  REAL,                            INTENT(IN) :: LWDN   !atmospheric longwave radiation (w/m2)\n  REAL,                            INTENT(IN) :: UR     !wind speed at height zlvl (m/s)\n  REAL,                            INTENT(IN) :: UU     !wind speed in eastward dir (m/s)\n  REAL,                            INTENT(IN) :: VV     !wind speed in northward dir (m/s)\n  REAL,                            INTENT(IN) :: SFCTMP !air temperature at reference height (k)\n  REAL,                            INTENT(IN) :: THAIR  !potential temperature at height zlvl (k)\n  REAL,                            INTENT(IN) :: QAIR   !specific humidity at height zlvl (kg/kg)\n  REAL,                            INTENT(IN) :: EAIR   !vapor pressure air at height (pa)\n  REAL,                            INTENT(IN) :: RHOAIR !density air (kg/m3)\n  REAL,                            INTENT(IN) :: SNOWH  !actual snow depth [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !thickness of snow/soil layers (m)\n  REAL,                            INTENT(IN) :: ZLVL   !reference height (m)\n  REAL,                            INTENT(IN) :: ZPD    !zero plane displacement (m)\n  REAL,                            INTENT(IN) :: Z0M    !roughness length, momentum, ground (m)\n  REAL,                            INTENT(IN) :: EMG    !ground emissivity\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: STC    !soil/snow temperature (k)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DF     !thermal conductivity of snow/soil (w/m/k)\n  REAL,                            INTENT(IN) :: RSURF  !ground surface resistance (s/m)\n  REAL,                            INTENT(IN) :: LATHEA !latent heat of vaporization/subli (j/kg)\n  REAL,                            INTENT(IN) :: GAMMA  !psychrometric constant (pa/k)\n  REAL,                            INTENT(IN) :: RHSUR  !raltive humidity in surface soil/snow air space (-)\n  REAL,                            INTENT(IN) :: FSNO     !snow fraction\n\n!jref:start; in\n  INTEGER                        , INTENT(IN) :: IVGTYP\n  REAL                           , INTENT(IN) :: QC     !cloud water mixing ratio\n  REAL                           , INTENT(INOUT) :: QSFC   !mixing ratio at lowest model layer\n  REAL                           , INTENT(IN) :: PSFC   !pressure at lowest model layer\n  REAL                           , INTENT(IN) :: SFCPRS !pressure at lowest model layer\n  REAL                           , INTENT(IN) :: DX     !horisontal grid spacing\n  REAL                           , INTENT(IN) :: Q2     !mixing ratio (kg/kg)\n  REAL                           , INTENT(IN) :: DZ8W   !thickness of lowest layer\n!jref:end\n  REAL, INTENT(IN)   :: PAHB  !precipitation advected heat - ground net IN (W/m2)\n\n! input/output\n  REAL,                         INTENT(INOUT) :: TGB    !ground temperature (k)\n  REAL,                         INTENT(INOUT) :: CM     !momentum drag coefficient\n  REAL,                         INTENT(INOUT) :: CH     !sensible heat exchange coefficient\n\n! output\n! -SAB + IRB[TG] + SHB[TG] + EVB[TG] + GHB[TG] = 0\n\n  REAL,                           INTENT(OUT) :: TAUXB  !wind stress: e-w (n/m2)\n  REAL,                           INTENT(OUT) :: TAUYB  !wind stress: n-s (n/m2)\n  REAL,                           INTENT(OUT) :: IRB    !net longwave rad (w/m2)   [+ to atm]\n  REAL,                           INTENT(OUT) :: SHB    !sensible heat flux (w/m2) [+ to atm]\n  REAL,                           INTENT(OUT) :: EVB    !latent heat flux (w/m2)   [+ to atm]\n  REAL,                           INTENT(OUT) :: GHB    !ground heat flux (w/m2)  [+ to soil]\n  REAL,                           INTENT(OUT) :: T2MB   !2 m height air temperature (k)\n!jref:start\n  REAL,                           INTENT(OUT) :: Q2B    !bare ground heat conductance\n  REAL :: EHB    !bare ground heat conductance\n  REAL :: U10B    !10 m wind speed in eastward dir (m/s)\n  REAL :: V10B    !10 m wind speed in eastward dir (m/s)\n  REAL :: WSPD\n!jref:end\n\n! local variables\n\n  REAL :: TAUX       !wind stress: e-w (n/m2)\n  REAL :: TAUY       !wind stress: n-s (n/m2)\n  REAL :: FIRA       !total net longwave rad (w/m2)      [+ to atm]\n  REAL :: FSH        !total sensible heat flux (w/m2)    [+ to atm]\n  REAL :: FGEV       !ground evaporation heat flux (w/m2)[+ to atm]\n  REAL :: SSOIL      !soil heat flux (w/m2)             [+ to soil]\n  REAL :: FIRE       !emitted ir (w/m2)\n  REAL :: TRAD       !radiative temperature (k)\n  REAL :: TAH        !\"surface\" temperature at height z0h+zpd (k)\n\n  REAL :: CW         !water vapor exchange coefficient\n  REAL :: FV         !friction velocity (m/s)\n  REAL :: WSTAR      !friction velocity n vertical direction (m/s) (only for SFCDIF2)\n  REAL :: Z0H        !roughness length, sensible heat, ground (m)\n  REAL :: RB         !bulk leaf boundary layer resistance (s/m)\n  REAL :: RAMB       !aerodynamic resistance for momentum (s/m)\n  REAL :: RAHB       !aerodynamic resistance for sensible heat (s/m)\n  REAL :: RAWB       !aerodynamic resistance for water vapor (s/m)\n  REAL :: MOL        !Monin-Obukhov length (m)\n  REAL :: DTG        !change in tg, last iteration (k)\n\n  REAL :: CIR        !coefficients for ir as function of ts**4\n  REAL :: CSH        !coefficients for sh as function of ts\n  REAL :: CEV        !coefficients for ev as function of esat[ts]\n  REAL :: CGH        !coefficients for st as function of ts\n\n!jref:start\n  REAL :: RAHB2      !aerodynamic resistance for sensible heat 2m (s/m)\n  REAL :: RAWB2      !aerodynamic resistance for water vapor 2m (s/m)\n  REAL,INTENT(OUT) :: EHB2       !sensible heat conductance for diagnostics\n  REAL :: CH2B       !exchange coefficient for 2m temp.\n  REAL :: CQ2B       !exchange coefficient for 2m temp.\n  REAL :: THVAIR     !virtual potential air temp\n  REAL :: THGH       !potential ground temp\n  REAL :: EMB        !momentum conductance\n  REAL :: QFX        !moisture flux\n  REAL :: ESTG2      !saturation vapor pressure at 2m (pa)\n  INTEGER :: VEGTYP     !vegetation type set to isbarren\n  REAL :: E1\n!jref:end\n\n  REAL :: ESTG       !saturation vapor pressure at tg (pa)\n  REAL :: DESTG      !d(es)/dt at tg (pa/K)\n  REAL :: ESATW      !es for water\n  REAL :: ESATI      !es for ice\n  REAL :: DSATW      !d(es)/dt at tg (pa/K) for water\n  REAL :: DSATI      !d(es)/dt at tg (pa/K) for ice\n\n  REAL :: A          !temporary calculation\n  REAL :: B          !temporary calculation\n  REAL :: H          !temporary sensible heat flux (w/m2)\n  REAL :: MOZ        !Monin-Obukhov stability parameter\n  REAL :: MOZOLD     !Monin-Obukhov stability parameter from prior iteration\n  REAL :: FM         !momentum stability correction, weighted by prior iters\n  REAL :: FH         !sen heat stability correction, weighted by prior iters\n  INTEGER :: MOZSGN  !number of times MOZ changes sign\n  REAL :: FM2          !Monin-Obukhov momentum adjustment at 2m\n  REAL :: FH2          !Monin-Obukhov heat adjustment at 2m\n  REAL :: CH2          !Surface exchange at 2m\n\n  INTEGER :: ITER    !iteration index\n  INTEGER :: NITERB  !number of iterations for surface temperature\n  REAL    :: MPE     !prevents overflow error if division by zero\n!jref:start\n!  DATA NITERB /3/\n  DATA NITERB /5/\n  SAVE NITERB\n  REAL :: T, TDC     !Kelvin to degree Celsius with limit -50 to +50\n  TDC(T)   = MIN( 50., MAX(-50.,(T-TFRZ)) )\n\n! -----------------------------------------------------------------\n! initialization variables that do not depend on stability iteration\n! -----------------------------------------------------------------\n        MPE = 1E-6\n        DTG = 0.\n        MOZ    = 0.\n        MOZSGN = 0\n        MOZOLD = 0.\n        FH2    = 0.\n        H      = 0.\n        QFX    = 0.\n        FV     = 0.1\n\n        CIR = EMG*SB\n        CGH = 2.*DF(ISNOW+1)/DZSNSO(ISNOW+1)\n\n! -----------------------------------------------------------------\n      loop3: DO ITER = 1, NITERB  ! begin stability iteration\n\n        IF(ITER == 1) THEN\n            Z0H = Z0M\n        ELSE\n            Z0H = Z0M !* EXP(-CZIL*0.4*258.2*SQRT(FV*Z0M))\n        END IF\n\n        IF(OPT_SFC == 1) THEN\n          CALL SFCDIF1(parameters,ITER   ,SFCTMP ,RHOAIR ,H      ,QAIR   , & !in\n                       ZLVL   ,ZPD    ,Z0M    ,Z0H    ,UR     , & !in\n                       MPE    ,ILOC   ,JLOC   ,                 & !in\n                       MOZ    ,MOZSGN ,FM     ,FH     ,FM2,FH2, & !inout\n                       CM     ,CH     ,FV     ,CH2     )          !out\n        ENDIF\n\n        IF(OPT_SFC == 2) THEN\n          CALL SFCDIF2(parameters,ITER   ,Z0M    ,TGB    ,THAIR  ,UR     , & !in\n                       ZLVL   ,ILOC   ,JLOC   ,         & !in\n                       CM     ,CH     ,MOZ    ,WSTAR  ,         & !in\n                       FV     )                                   !out\n          ! Undo the multiplication by windspeed that SFCDIF2\n          ! applies to exchange coefficients CH and CM:\n          CH = CH / UR\n          CM = CM / UR\n          IF(SNOWH > 0.) THEN\n             CM = MIN(0.01,CM)   ! CM & CH are too large, causing\n             CH = MIN(0.01,CH)   ! computational instability\n          END IF\n\n        ENDIF\n\n        RAMB = MAX(1.,1./(CM*UR))\n        RAHB = MAX(1.,1./(CH*UR))\n        RAWB = RAHB\n\n!jref - variables for diagnostics\n        EMB = 1./RAMB\n        EHB = 1./RAHB\n\n! es and d(es)/dt evaluated at tg\n\n        T = TDC(TGB)\n        CALL ESAT(T, ESATW, ESATI, DSATW, DSATI)\n        IF (T .GT. 0.) THEN\n            ESTG  = ESATW\n            DESTG = DSATW\n        ELSE\n            ESTG  = ESATI\n            DESTG = DSATI\n        END IF\n\n        CSH = RHOAIR*CPAIR/RAHB\n        CEV = RHOAIR*CPAIR/GAMMA/(RSURF+RAWB)\n\n! surface fluxes and dtg\n\n        IRB   = CIR * TGB**4 - EMG*LWDN\n        SHB   = CSH * (TGB        - SFCTMP      )\n        EVB   = CEV * (ESTG*RHSUR - EAIR        )\n        GHB   = CGH * (TGB        - STC(ISNOW+1))\n\n        B     = SAG-IRB-SHB-EVB-GHB+PAHB\n        A     = 4.*CIR*TGB**3 + CSH + CEV*DESTG + CGH\n        DTG   = B/A\n\n        IRB = IRB + 4.*CIR*TGB**3*DTG\n        SHB = SHB + CSH*DTG\n        EVB = EVB + CEV*DESTG*DTG\n        GHB = GHB + CGH*DTG\n\n! update ground surface temperature\n        TGB = TGB + DTG\n\n! for M-O length\n        H = CSH * (TGB - SFCTMP)\n\n        T = TDC(TGB)\n        CALL ESAT(T, ESATW, ESATI, DSATW, DSATI)\n        IF (T .GT. 0.) THEN\n            ESTG  = ESATW\n        ELSE\n            ESTG  = ESATI\n        END IF\n        QSFC = 0.622*(ESTG*RHSUR)/(PSFC-0.378*(ESTG*RHSUR))\n\n        QFX = (QSFC-QAIR)*CEV*GAMMA/CPAIR\n\n     END DO loop3 ! end stability iteration\n! -----------------------------------------------------------------\n\n! if snow on ground and TG > TFRZ: reset TG = TFRZ. reevaluate ground fluxes.\n\n     IF(OPT_STC == 1 .OR. OPT_STC == 3) THEN\n     IF (SNOWH > 0.05 .AND. TGB > TFRZ) THEN\n          IF(OPT_STC == 1) TGB = TFRZ\n          IF(OPT_STC == 3) TGB  = (1.-FSNO)*TGB + FSNO*TFRZ  ! MB: allow TG>0C during melt v3.7\n          IRB = CIR * TGB**4 - EMG*LWDN\n          SHB = CSH * (TGB        - SFCTMP)\n          EVB = CEV * (ESTG*RHSUR - EAIR )          !ESTG reevaluate ?\n          GHB = SAG+PAHB - (IRB+SHB+EVB)\n     END IF\n     END IF\n\n! wind stresses\n\n     TAUXB = -RHOAIR*CM*UR*UU\n     TAUYB = -RHOAIR*CM*UR*VV\n\n!jref:start; errors in original equation corrected.\n! 2m air temperature\n     IF(OPT_SFC == 1 .OR. OPT_SFC ==2) THEN\n       EHB2  = FV*VKC/LOG((2.+Z0H)/Z0H)\n       EHB2  = FV*VKC/(LOG((2.+Z0H)/Z0H)-FH2)\n       CQ2B  = EHB2\n       IF (EHB2.lt.1.E-5 ) THEN\n         T2MB  = TGB\n         Q2B   = QSFC\n       ELSE\n         T2MB  = TGB - SHB/(RHOAIR*CPAIR) * 1./EHB2\n         Q2B   = QSFC - EVB/(LATHEA*RHOAIR)*(1./CQ2B + RSURF)\n       ENDIF\n       IF (parameters%urban_flag) Q2B = QSFC\n     END IF\n\n! update CH\n     CH = EHB\n\n  END SUBROUTINE BARE_FLUX\n\n!== begin ragrb ====================================================================================\n\n  SUBROUTINE RAGRB(parameters,ITER   ,VAI    ,RHOAIR ,HG     ,TAH    , & !in\n                   ZPD    ,Z0MG   ,Z0HG   ,HCAN   ,UC     , & !in\n                   Z0H    ,FV     ,CWP    ,VEGTYP ,MPE    , & !in\n                   TV     ,MOZG   ,FHG    ,ILOC   ,JLOC   , & !inout\n                   RAMG   ,RAHG   ,RAWG   ,RB     )           !out\n! --------------------------------------------------------------------------------------------------\n! compute under-canopy aerodynamic resistance RAG and leaf boundary layer\n! resistance RB\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,              INTENT(IN) :: ILOC   !grid index\n  INTEGER,              INTENT(IN) :: JLOC   !grid index\n  INTEGER,              INTENT(IN) :: ITER   !iteration index\n  INTEGER,              INTENT(IN) :: VEGTYP !vegetation physiology type\n  REAL,                 INTENT(IN) :: VAI    !total LAI + stem area index, one sided\n  REAL,                 INTENT(IN) :: RHOAIR !density air (kg/m3)\n  REAL,                 INTENT(IN) :: HG     !ground sensible heat flux (w/m2)\n  REAL,                 INTENT(IN) :: TV     !vegetation temperature (k)\n  REAL,                 INTENT(IN) :: TAH    !air temperature at height z0h+zpd (k)\n  REAL,                 INTENT(IN) :: ZPD    !zero plane displacement (m)\n  REAL,                 INTENT(IN) :: Z0MG   !roughness length, momentum, ground (m)\n  REAL,                 INTENT(IN) :: HCAN   !canopy height (m) [note: hcan >= z0mg]\n  REAL,                 INTENT(IN) :: UC     !wind speed at top of canopy (m/s)\n  REAL,                 INTENT(IN) :: Z0H    !roughness length, sensible heat (m)\n  REAL,                 INTENT(IN) :: Z0HG   !roughness length, sensible heat, ground (m)\n  REAL,                 INTENT(IN) :: FV     !friction velocity (m/s)\n  REAL,                 INTENT(IN) :: CWP    !canopy wind parameter\n  REAL,                 INTENT(IN) :: MPE    !prevents overflow error if division by zero\n\n! in & out\n\n  REAL,              INTENT(INOUT) :: MOZG   !Monin-Obukhov stability parameter\n  REAL,              INTENT(INOUT) :: FHG    !stability correction\n\n! outputs\n  REAL                             :: RAMG   !aerodynamic resistance for momentum (s/m)\n  REAL                             :: RAHG   !aerodynamic resistance for sensible heat (s/m)\n  REAL                             :: RAWG   !aerodynamic resistance for water vapor (s/m)\n  REAL                             :: RB     !bulk leaf boundary layer resistance (s/m)\n\n\n  REAL :: KH           !turbulent transfer coefficient, sensible heat, (m2/s)\n  REAL :: TMP1         !temporary calculation\n  REAL :: TMP2         !temporary calculation\n  REAL :: TMPRAH2      !temporary calculation for aerodynamic resistances\n  REAL :: TMPRB        !temporary calculation for rb\n  real :: MOLG,FHGNEW,CWPC\n! --------------------------------------------------------------------------------------------------\n! stability correction to below canopy resistance\n\n       MOZG = 0.\n       MOLG = 0.\n\n       IF(ITER > 1) THEN\n        TMP1 = VKC * (GRAV/TAH) * HG/(RHOAIR*CPAIR)\n        IF (ABS(TMP1) .LE. MPE) TMP1 = MPE\n        MOLG = -1. * FV**3 / TMP1\n        MOZG = MIN( (ZPD-Z0MG)/MOLG, 1.)\n       END IF\n\n       IF (MOZG < 0.) THEN\n          FHGNEW  = (1. - 15.*MOZG)**(-0.25)\n       ELSE\n          FHGNEW  = 1.+ 4.7*MOZG\n       ENDIF\n\n       IF (ITER == 1) THEN\n          FHG = FHGNEW\n       ELSE\n          FHG = 0.5 * (FHG+FHGNEW)\n       ENDIF\n\n       CWPC = (CWP * VAI * HCAN * FHG)**0.5\n!       CWPC = (CWP*FHG)**0.5\n\n       TMP1 = EXP( -CWPC*Z0HG/HCAN )\n       TMP2 = EXP( -CWPC*(Z0H+ZPD)/HCAN )\n       TMPRAH2 = HCAN*EXP(CWPC) / CWPC * (TMP1-TMP2)\n\n! aerodynamic resistances raw and rah between heights zpd+z0h and z0hg.\n\n       KH  = MAX ( VKC*FV*(HCAN-ZPD), MPE )\n       RAMG = 0.\n       RAHG = TMPRAH2 / KH\n       RAWG = RAHG\n\n! leaf boundary layer resistance\n\n       TMPRB  = CWPC*50. / (1. - EXP(-CWPC/2.))\n       RB     = TMPRB * SQRT(parameters%DLEAF/UC)\n       RB     = MAX(RB,20.0)\n!       RB = 200\n\n  END SUBROUTINE RAGRB\n\n!== begin sfcdif1 ==================================================================================\n\n  SUBROUTINE SFCDIF1(parameters,ITER   ,SFCTMP ,RHOAIR ,H      ,QAIR   , & !in\n       &             ZLVL   ,ZPD    ,Z0M    ,Z0H    ,UR     , & !in\n       &             MPE    ,ILOC   ,JLOC   ,                 & !in\n       &             MOZ    ,MOZSGN ,FM     ,FH     ,FM2,FH2, & !inout\n       &             CM     ,CH     ,FV     ,CH2     )          !out\n! -------------------------------------------------------------------------------------------------\n! computing surface drag coefficient CM for momentum and CH for heat\n! -------------------------------------------------------------------------------------------------\n    IMPLICIT NONE\n! -------------------------------------------------------------------------------------------------\n! inputs\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER,              INTENT(IN) :: ILOC   !grid index\n    INTEGER,              INTENT(IN) :: JLOC   !grid index\n    INTEGER,              INTENT(IN) :: ITER   !iteration index\n    REAL,                 INTENT(IN) :: SFCTMP !temperature at reference height (k)\n    REAL,                 INTENT(IN) :: RHOAIR !density air (kg/m**3)\n    REAL,                 INTENT(IN) :: H      !sensible heat flux (w/m2) [+ to atm]\n    REAL,                 INTENT(IN) :: QAIR   !specific humidity at reference height (kg/kg)\n    REAL,                 INTENT(IN) :: ZLVL   !reference height  (m)\n    REAL,                 INTENT(IN) :: ZPD    !zero plane displacement (m)\n    REAL,                 INTENT(IN) :: Z0H    !roughness length, sensible heat, ground (m)\n    REAL,                 INTENT(IN) :: Z0M    !roughness length, momentum, ground (m)\n    REAL,                 INTENT(IN) :: UR     !wind speed (m/s)\n    REAL,                 INTENT(IN) :: MPE    !prevents overflow error if division by zero\n! in & out\n\n    INTEGER,           INTENT(INOUT) :: MOZSGN !number of times moz changes sign\n    REAL,              INTENT(INOUT) :: MOZ    !Monin-Obukhov stability (z/L)\n    REAL,              INTENT(INOUT) :: FM     !momentum stability correction, weighted by prior iters\n    REAL,              INTENT(INOUT) :: FH     !sen heat stability correction, weighted by prior iters\n    REAL,              INTENT(INOUT) :: FM2    !sen heat stability correction, weighted by prior iters\n    REAL,              INTENT(INOUT) :: FH2    !sen heat stability correction, weighted by prior iters\n\n! outputs\n\n    REAL,                INTENT(OUT) :: CM     !drag coefficient for momentum\n    REAL,                INTENT(OUT) :: CH     !drag coefficient for heat\n    REAL,                INTENT(OUT) :: FV     !friction velocity (m/s)\n    REAL,                INTENT(OUT) :: CH2    !drag coefficient for heat\n\n! locals\n    REAL    :: MOL                      !Monin-Obukhov length (m)\n    REAL    :: TMPCM                    !temporary calculation for CM\n    REAL    :: TMPCH                    !temporary calculation for CH\n    REAL    :: FMNEW                    !stability correction factor, momentum, for current moz\n    REAL    :: FHNEW                    !stability correction factor, sen heat, for current moz\n    REAL    :: MOZOLD                   !Monin-Obukhov stability parameter from prior iteration\n    REAL    :: TMP1,TMP2,TMP3,TMP4,TMP5 !temporary calculation\n    REAL    :: TVIR                     !temporary virtual temperature (k)\n    REAL    :: MOZ2                     !2/L\n    REAL    :: TMPCM2                   !temporary calculation for CM2\n    REAL    :: TMPCH2                   !temporary calculation for CH2\n    REAL    :: FM2NEW                   !stability correction factor, momentum, for current moz\n    REAL    :: FH2NEW                   !stability correction factor, sen heat, for current moz\n    REAL    :: TMP12,TMP22,TMP32        !temporary calculation\n\n    REAL    :: CMFM, CHFH, CM2FM2, CH2FH2\n! -------------------------------------------------------------------------------------------------\n! Monin-Obukhov stability parameter moz for next iteration\n\n    MOZOLD = MOZ\n\n    IF(ZLVL <= ZPD) THEN\n       write(*,*) 'WARNING: critical problem: ZLVL <= ZPD; model stops'\n       call wrf_error_fatal(\"STOP in Noah-MP\")\n    ENDIF\n\n    TMPCM = LOG((ZLVL-ZPD) / Z0M)\n    TMPCH = LOG((ZLVL-ZPD) / Z0H)\n    TMPCM2 = LOG((2.0 + Z0M) / Z0M)\n    TMPCH2 = LOG((2.0 + Z0H) / Z0H)\n\n    IF(ITER == 1) THEN\n       FV   = 0.0\n       MOZ  = 0.0\n       MOL  = 0.0\n       MOZ2 = 0.0\n    ELSE\n       TVIR = (1. + 0.61*QAIR) * SFCTMP\n       TMP1 = VKC * (GRAV/TVIR) * H/(RHOAIR*CPAIR)\n       IF (ABS(TMP1) .LE. MPE) TMP1 = MPE\n       MOL  = -1. * FV**3 / TMP1\n       MOZ  = MIN( (ZLVL-ZPD)/MOL, 1.)\n       MOZ2  = MIN( (2.0 + Z0H)/MOL, 1.)\n    ENDIF\n\n! accumulate number of times moz changes sign.\n\n    IF (MOZOLD*MOZ .LT. 0.) MOZSGN = MOZSGN+1\n    IF (MOZSGN .GE. 2) THEN\n       MOZ = 0.\n       FM = 0.\n       FH = 0.\n       MOZ2 = 0.\n       FM2 = 0.\n       FH2 = 0.\n    ENDIF\n\n! evaluate stability-dependent variables using moz from prior iteration\n    IF (MOZ .LT. 0.) THEN\n       TMP1 = (1. - 16.*MOZ)**0.25\n       TMP2 = LOG((1.+TMP1*TMP1)/2.)\n       TMP3 = LOG((1.+TMP1)/2.)\n       FMNEW = 2.*TMP3 + TMP2 - 2.*ATAN(TMP1) + 1.5707963\n       FHNEW = 2*TMP2\n\n! 2-meter\n       TMP12 = (1. - 16.*MOZ2)**0.25\n       TMP22 = LOG((1.+TMP12*TMP12)/2.)\n       TMP32 = LOG((1.+TMP12)/2.)\n       FM2NEW = 2.*TMP32 + TMP22 - 2.*ATAN(TMP12) + 1.5707963\n       FH2NEW = 2*TMP22\n    ELSE\n       FMNEW = -5.*MOZ\n       FHNEW = FMNEW\n       FM2NEW = -5.*MOZ2\n       FH2NEW = FM2NEW\n    ENDIF\n\n! except for first iteration, weight stability factors for previous\n! iteration to help avoid flip-flops from one iteration to the next\n\n    IF (ITER == 1) THEN\n       FM = FMNEW\n       FH = FHNEW\n       FM2 = FM2NEW\n       FH2 = FH2NEW\n    ELSE\n       FM = 0.5 * (FM+FMNEW)\n       FH = 0.5 * (FH+FHNEW)\n       FM2 = 0.5 * (FM2+FM2NEW)\n       FH2 = 0.5 * (FH2+FH2NEW)\n    ENDIF\n\n! exchange coefficients\n\n    FH = MIN(FH,0.9*TMPCH)\n    FM = MIN(FM,0.9*TMPCM)\n    FH2 = MIN(FH2,0.9*TMPCH2)\n    FM2 = MIN(FM2,0.9*TMPCM2)\n\n    CMFM = TMPCM-FM\n    CHFH = TMPCH-FH\n    CM2FM2 = TMPCM2-FM2\n    CH2FH2 = TMPCH2-FH2\n    IF(ABS(CMFM) <= MPE) CMFM = MPE\n    IF(ABS(CHFH) <= MPE) CHFH = MPE\n    IF(ABS(CM2FM2) <= MPE) CM2FM2 = MPE\n    IF(ABS(CH2FH2) <= MPE) CH2FH2 = MPE\n    CM  = VKC*VKC/(CMFM*CMFM)\n    CH  = VKC*VKC/(CMFM*CHFH)\n    CH2  = VKC*VKC/(CM2FM2*CH2FH2)\n\n! friction velocity\n\n    FV = UR * SQRT(CM)\n    CH2  = VKC*FV/CH2FH2\n\n  END SUBROUTINE SFCDIF1\n\n!== begin sfcdif2 ==================================================================================\n\n  SUBROUTINE SFCDIF2(parameters,ITER   ,Z0     ,THZ0   ,THLM   ,SFCSPD , & !in\n                     ZLM    ,ILOC   ,JLOC   ,         & !in\n                     AKMS   ,AKHS   ,RLMO   ,WSTAR2 ,         & !in\n                     USTAR  )                                   !out\n\n! -------------------------------------------------------------------------------------------------\n! SUBROUTINE SFCDIF (renamed SFCDIF_off to avoid clash with Eta PBL)\n! -------------------------------------------------------------------------------------------------\n! CALCULATE SURFACE LAYER EXCHANGE COEFFICIENTS VIA ITERATIVE PROCESS.\n! SEE CHEN ET AL (1997, BLM)\n! -------------------------------------------------------------------------------------------------\n    IMPLICIT NONE\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER, INTENT(IN) :: ILOC\n    INTEGER, INTENT(IN) :: JLOC\n    INTEGER, INTENT(IN) :: ITER\n    REAL,    INTENT(IN) :: ZLM, Z0, THZ0, THLM, SFCSPD\n    REAL, intent(INOUT) :: AKMS\n    REAL, intent(INOUT) :: AKHS\n    REAL, intent(INOUT) :: RLMO\n    REAL, intent(INOUT) :: WSTAR2\n    REAL,   intent(OUT) :: USTAR\n\n    REAL     ZZ, PSLMU, PSLMS, PSLHU, PSLHS\n    REAL     XX, PSPMU, YY, PSPMS, PSPHU, PSPHS\n    REAL     ZILFC, ZU, ZT, RDZ, CXCH\n    REAL     DTHV, DU2, BTGH, ZSLU, ZSLT, RLOGU, RLOGT\n    REAL     ZETALT, ZETALU, ZETAU, ZETAT, XLU4, XLT4, XU4, XT4\n\n    REAL     XLU, XLT, XU, XT, PSMZ, SIMM, PSHZ, SIMH, USTARK, RLMN,  &\n         &         RLMA\n\n    INTEGER  ILECH, ITR\n\n    INTEGER, PARAMETER :: ITRMX  = 5\n    REAL,    PARAMETER :: WWST   = 1.2\n    REAL,    PARAMETER :: WWST2  = WWST * WWST\n    REAL,    PARAMETER :: VKRM   = 0.40\n    REAL,    PARAMETER :: EXCM   = 0.001\n    REAL,    PARAMETER :: BETA   = 1.0 / 270.0\n    REAL,    PARAMETER :: BTG    = BETA * GRAV\n    REAL,    PARAMETER :: ELFC   = VKRM * BTG\n    REAL,    PARAMETER :: WOLD   = 0.15\n    REAL,    PARAMETER :: WNEW   = 1.0 - WOLD\n    REAL,    PARAMETER :: PIHF   = 3.14159265 / 2.\n    REAL,    PARAMETER :: EPSU2  = 1.E-4\n    REAL,    PARAMETER :: EPSUST = 0.07\n    REAL,    PARAMETER :: EPSIT  = 1.E-4\n    REAL,    PARAMETER :: EPSA   = 1.E-8\n    REAL,    PARAMETER :: ZTMIN  = -5.0\n    REAL,    PARAMETER :: ZTMAX  = 1.0\n    REAL,    PARAMETER :: HPBL   = 1000.0\n    REAL,    PARAMETER :: SQVISC = 258.2\n    REAL,    PARAMETER :: RIC    = 0.183\n    REAL,    PARAMETER :: RRIC   = 1.0 / RIC\n    REAL,    PARAMETER :: FHNEU  = 0.8\n    REAL,    PARAMETER :: RFC    = 0.191\n    REAL,    PARAMETER :: RFAC   = RIC / ( FHNEU * RFC * RFC )\n\n! ----------------------------------------------------------------------\n! NOTE: THE TWO CODE BLOCKS BELOW DEFINE FUNCTIONS\n! ----------------------------------------------------------------------\n! LECH'S SURFACE FUNCTIONS\n    PSLMU (ZZ)= -0.96* log (1.0-4.5* ZZ)\n    PSLMS (ZZ)= ZZ * RRIC -2.076* (1. -1./ (ZZ +1.))\n    PSLHU (ZZ)= -0.96* log (1.0-4.5* ZZ)\n    PSLHS (ZZ)= ZZ * RFAC -2.076* (1. -1./ (ZZ +1.))\n! PAULSON'S SURFACE FUNCTIONS\n    PSPMU (XX)= -2.* log ( (XX +1.)*0.5) - log ( (XX * XX +1.)*0.5)   &\n         &        +2.* ATAN (XX)                                            &\n         &- PIHF\n    PSPMS (YY)= 5.* YY\n    PSPHU (XX)= -2.* log ( (XX * XX +1.)*0.5)\n    PSPHS (YY)= 5.* YY\n\n! THIS ROUTINE SFCDIF CAN HANDLE BOTH OVER OPEN WATER (SEA, OCEAN) AND\n! OVER SOLID SURFACE (LAND, SEA-ICE).\n! ----------------------------------------------------------------------\n!     ZTFC: RATIO OF ZOH/ZOM  LESS OR EQUAL THAN 1\n!     C......ZTFC=0.1\n!     CZIL: CONSTANT C IN Zilitinkevich, S. S.1995,:NOTE ABOUT ZT\n! ----------------------------------------------------------------------\n    ILECH = 0\n\n! ----------------------------------------------------------------------\n    ZILFC = - parameters%CZIL * VKRM * SQVISC\n    ZU = Z0\n    RDZ = 1./ ZLM\n    CXCH = EXCM * RDZ\n    DTHV = THLM - THZ0\n\n! BELJARS CORRECTION OF USTAR\n    DU2 = MAX (SFCSPD * SFCSPD,EPSU2)\n    BTGH = BTG * HPBL\n\n    IF(ITER == 1) THEN\n        IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n           WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n        ELSE\n           WSTAR2 = 0.0\n        END IF\n        USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n        RLMO = ELFC * AKHS * DTHV / USTAR **3\n    END IF\n\n! ZILITINKEVITCH APPROACH FOR ZT\n    ZT = MAX(1.E-6,EXP (ZILFC * SQRT (USTAR * Z0))* Z0)\n    ZSLU = ZLM + ZU\n    ZSLT = ZLM + ZT\n    RLOGU = log (ZSLU / ZU)\n    RLOGT = log (ZSLT / ZT)\n\n! ----------------------------------------------------------------------\n! 1./MONIN-OBUKKHOV LENGTH-SCALE\n! ----------------------------------------------------------------------\n    ZETALT = MAX (ZSLT * RLMO,ZTMIN)\n    RLMO = ZETALT / ZSLT\n    ZETALU = ZSLU * RLMO\n    ZETAU = ZU * RLMO\n    ZETAT = ZT * RLMO\n\n    IF (ILECH .eq. 0) THEN\n       IF (RLMO .lt. 0.)THEN\n          XLU4 = 1. -16.* ZETALU\n          XLT4 = 1. -16.* ZETALT\n          XU4  = 1. -16.* ZETAU\n          XT4  = 1. -16.* ZETAT\n          XLU  = SQRT (SQRT (XLU4))\n          XLT  = SQRT (SQRT (XLT4))\n          XU   = SQRT (SQRT (XU4))\n\n          XT = SQRT (SQRT (XT4))\n          PSMZ = PSPMU (XU)\n          SIMM = PSPMU (XLU) - PSMZ + RLOGU\n          PSHZ = PSPHU (XT)\n          SIMH = PSPHU (XLT) - PSHZ + RLOGT\n       ELSE\n          ZETALU = MIN (ZETALU,ZTMAX)\n          ZETALT = MIN (ZETALT,ZTMAX)\n          ZETAU  = MIN (ZETAU,ZTMAX/(ZSLU/ZU))   ! Barlage: add limit on ZETAU/ZETAT\n          ZETAT  = MIN (ZETAT,ZTMAX/(ZSLT/ZT))   ! Barlage: prevent SIMM/SIMH < 0\n          PSMZ = PSPMS (ZETAU)\n          SIMM = PSPMS (ZETALU) - PSMZ + RLOGU\n          PSHZ = PSPHS (ZETAT)\n          SIMH = PSPHS (ZETALT) - PSHZ + RLOGT\n       END IF\n! ----------------------------------------------------------------------\n! LECH'S FUNCTIONS\n! ----------------------------------------------------------------------\n    ELSE\n       IF (RLMO .lt. 0.)THEN\n          PSMZ = PSLMU (ZETAU)\n          SIMM = PSLMU (ZETALU) - PSMZ + RLOGU\n          PSHZ = PSLHU (ZETAT)\n          SIMH = PSLHU (ZETALT) - PSHZ + RLOGT\n       ELSE\n          ZETALU = MIN (ZETALU,ZTMAX)\n          ZETALT = MIN (ZETALT,ZTMAX)\n          PSMZ = PSLMS (ZETAU)\n          SIMM = PSLMS (ZETALU) - PSMZ + RLOGU\n          PSHZ = PSLHS (ZETAT)\n          SIMH = PSLHS (ZETALT) - PSHZ + RLOGT\n       END IF\n! ----------------------------------------------------------------------\n       END IF\n\n! ----------------------------------------------------------------------\n! BELJAARS CORRECTION FOR USTAR\n! ----------------------------------------------------------------------\n       USTAR = MAX (SQRT (AKMS * SQRT (DU2+ WSTAR2)),EPSUST)\n\n! ZILITINKEVITCH FIX FOR ZT\n       ZT = MAX(1.E-6,EXP (ZILFC * SQRT (USTAR * Z0))* Z0)\n       ZSLT = ZLM + ZT\n!-----------------------------------------------------------------------\n       RLOGT = log (ZSLT / ZT)\n       USTARK = USTAR * VKRM\n       IF(SIMM < 1.e-6) SIMM = 1.e-6        ! Limit stability function\n       AKMS = MAX (USTARK / SIMM,CXCH)\n!-----------------------------------------------------------------------\n! IF STATEMENTS TO AVOID TANGENT LINEAR PROBLEMS NEAR ZERO\n!-----------------------------------------------------------------------\n       IF(SIMH < 1.e-6) SIMH = 1.e-6        ! Limit stability function\n       AKHS = MAX (USTARK / SIMH,CXCH)\n\n       IF (BTGH * AKHS * DTHV .ne. 0.0) THEN\n          WSTAR2 = WWST2* ABS (BTGH * AKHS * DTHV)** (2./3.)\n       ELSE\n          WSTAR2 = 0.0\n       END IF\n!-----------------------------------------------------------------------\n       RLMN = ELFC * AKHS * DTHV / USTAR **3\n!-----------------------------------------------------------------------\n!     IF(ABS((RLMN-RLMO)/RLMA).LT.EPSIT)    GO TO 110\n!-----------------------------------------------------------------------\n       RLMA = RLMO * WOLD+ RLMN * WNEW\n!-----------------------------------------------------------------------\n       RLMO = RLMA\n\n!       write(*,'(a20,10f15.6)')'SFCDIF: RLMO=',RLMO,RLMN,ELFC , AKHS , DTHV , USTAR\n!    END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE SFCDIF2\n\n!== begin esat =====================================================================================\n\n  SUBROUTINE ESAT(T, ESW, ESI, DESW, DESI)\n!---------------------------------------------------------------------------------------------------\n! use polynomials to calculate saturation vapor pressure and derivative with\n! respect to temperature: over water when t > 0 c and over ice when t <= 0 c\n  IMPLICIT NONE\n!---------------------------------------------------------------------------------------------------\n! in\n\n  REAL, intent(in)  :: T              !temperature\n\n!out\n\n  REAL, intent(out) :: ESW            !saturation vapor pressure over water (pa)\n  REAL, intent(out) :: ESI            !saturation vapor pressure over ice (pa)\n  REAL, intent(out) :: DESW           !d(esat)/dt over water (pa/K)\n  REAL, intent(out) :: DESI           !d(esat)/dt over ice (pa/K)\n\n! local\n\n  REAL :: A0,A1,A2,A3,A4,A5,A6  !coefficients for esat over water\n  REAL :: B0,B1,B2,B3,B4,B5,B6  !coefficients for esat over ice\n  REAL :: C0,C1,C2,C3,C4,C5,C6  !coefficients for dsat over water\n  REAL :: D0,D1,D2,D3,D4,D5,D6  !coefficients for dsat over ice\n\n  PARAMETER (A0=6.107799961    , A1=4.436518521E-01,  &\n             A2=1.428945805E-02, A3=2.650648471E-04,  &\n             A4=3.031240396E-06, A5=2.034080948E-08,  &\n             A6=6.136820929E-11)\n\n  PARAMETER (B0=6.109177956    , B1=5.034698970E-01,  &\n             B2=1.886013408E-02, B3=4.176223716E-04,  &\n             B4=5.824720280E-06, B5=4.838803174E-08,  &\n             B6=1.838826904E-10)\n\n  PARAMETER (C0= 4.438099984E-01, C1=2.857002636E-02,  &\n             C2= 7.938054040E-04, C3=1.215215065E-05,  &\n             C4= 1.036561403E-07, C5=3.532421810e-10,  &\n             C6=-7.090244804E-13)\n\n  PARAMETER (D0=5.030305237E-01, D1=3.773255020E-02,  &\n             D2=1.267995369E-03, D3=2.477563108E-05,  &\n             D4=3.005693132E-07, D5=2.158542548E-09,  &\n             D6=7.131097725E-12)\n\n  ESW  = 100.*(A0+T*(A1+T*(A2+T*(A3+T*(A4+T*(A5+T*A6))))))\n  ESI  = 100.*(B0+T*(B1+T*(B2+T*(B3+T*(B4+T*(B5+T*B6))))))\n  DESW = 100.*(C0+T*(C1+T*(C2+T*(C3+T*(C4+T*(C5+T*C6))))))\n  DESI = 100.*(D0+T*(D1+T*(D2+T*(D3+T*(D4+T*(D5+T*D6))))))\n\n  END SUBROUTINE ESAT\n\n!== begin stomata ==================================================================================\n\n  SUBROUTINE STOMATA (parameters,VEGTYP  ,MPE     ,APAR    ,FOLN    ,ILOC    , JLOC, & !in\n                      TV      ,EI      ,EA      ,SFCTMP  ,SFCPRS  , & !in\n                      O2      ,CO2     ,IGS     ,BTRAN   ,RB      , & !in\n                      RS      ,PSN     )                              !out\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n      INTEGER,INTENT(IN)  :: ILOC   !grid index\n      INTEGER,INTENT(IN)  :: JLOC   !grid index\n      INTEGER,INTENT(IN)  :: VEGTYP !vegetation physiology type\n\n      REAL, INTENT(IN)    :: IGS    !growing season index (0=off, 1=on)\n      REAL, INTENT(IN)    :: MPE    !prevents division by zero errors\n\n      REAL, INTENT(IN)    :: TV     !foliage temperature (k)\n      REAL, INTENT(IN)    :: EI     !vapor pressure inside leaf (sat vapor press at tv) (pa)\n      REAL, INTENT(IN)    :: EA     !vapor pressure of canopy air (pa)\n      REAL, INTENT(IN)    :: APAR   !par absorbed per unit lai (w/m2)\n      REAL, INTENT(IN)    :: O2     !atmospheric o2 concentration (pa)\n      REAL, INTENT(IN)    :: CO2    !atmospheric co2 concentration (pa)\n      REAL, INTENT(IN)    :: SFCPRS !air pressure at reference height (pa)\n      REAL, INTENT(IN)    :: SFCTMP !air temperature at reference height (k)\n      REAL, INTENT(IN)    :: BTRAN  !soil water transpiration factor (0 to 1)\n      REAL, INTENT(IN)    :: FOLN   !foliage nitrogen concentration (%)\n      REAL, INTENT(IN)    :: RB     !boundary layer resistance (s/m)\n\n! output\n      REAL, INTENT(OUT)   :: RS     !leaf stomatal resistance (s/m)\n      REAL, INTENT(OUT)   :: PSN    !foliage photosynthesis (umol co2 /m2/ s) [always +]\n\n! in&out\n      REAL                :: RLB    !boundary layer resistance (s m2 / umol)\n! ---------------------------------------------------------------------------------------------\n\n! ------------------------ local variables ----------------------------------------------------\n      INTEGER :: ITER     !iteration index\n      INTEGER :: NITER    !number of iterations\n\n      DATA NITER /3/\n      SAVE NITER\n\n      REAL :: AB          !used in statement functions\n      REAL :: BC          !used in statement functions\n      REAL :: F1          !generic temperature response (statement function)\n      REAL :: F2          !generic temperature inhibition (statement function)\n      REAL :: TC          !foliage temperature (degree Celsius)\n      REAL :: CS          !co2 concentration at leaf surface (pa)\n      REAL :: KC          !co2 Michaelis-Menten constant (pa)\n      REAL :: KO          !o2 Michaelis-Menten constant (pa)\n      REAL :: A,B,C,Q     !intermediate calculations for RS\n      REAL :: R1,R2       !roots for RS\n      REAL :: FNF         !foliage nitrogen adjustment factor (0 to 1)\n      REAL :: PPF         !absorb photosynthetic photon flux (umol photons/m2/s)\n      REAL :: WC          !Rubisco limited photosynthesis (umol co2/m2/s)\n      REAL :: WJ          !light limited photosynthesis (umol co2/m2/s)\n      REAL :: WE          !export limited photosynthesis (umol co2/m2/s)\n      REAL :: CP          !co2 compensation point (pa)\n      REAL :: CI          !internal co2 (pa)\n      REAL :: AWC         !intermediate calculation for wc\n      REAL :: VCMX        !maximum rate of carbonylation (umol co2/m2/s)\n      REAL :: J           !electron transport (umol co2/m2/s)\n      REAL :: CEA         !constrain ea or else model blows up\n      REAL :: CF          !s m2/umol -> s/m\n\n      F1(AB,BC) = AB**((BC-25.)/10.)\n      F2(AB) = 1. + EXP((-2.2E05+710.*(AB+273.16))/(8.314*(AB+273.16)))\n      REAL :: T\n! ---------------------------------------------------------------------------------------------\n\n! initialize RS=RSMAX and PSN=0 because will only do calculations\n! for APAR > 0, in which case RS <= RSMAX and PSN >= 0\n\n         CF = SFCPRS/(8.314*SFCTMP)*1.e06\n         RS = 1./parameters%BP * CF\n         PSN = 0.\n\n         IF (APAR .LE. 0.) RETURN\n\n         FNF = MIN( FOLN/MAX(MPE,parameters%FOLNMX), 1.0 )\n         TC  = TV-TFRZ\n         PPF = 4.6*APAR\n         J   = PPF*parameters%QE25\n         KC  = parameters%KC25 * F1(parameters%AKC,TC)\n         KO  = parameters%KO25 * F1(parameters%AKO,TC)\n         AWC = KC * (1.+O2/KO)\n         CP  = 0.5*KC/KO*O2*0.21\n         VCMX = parameters%VCMX25 / F2(TC) * FNF * BTRAN * F1(parameters%AVCMX,TC)\n\n! first guess ci\n\n         CI = 0.7*CO2*parameters%C3PSN + 0.4*CO2*(1.-parameters%C3PSN)\n\n! rb: s/m -> s m**2 / umol\n\n         RLB = RB/CF\n\n! constrain ea\n\n         CEA = MAX(0.25*EI*parameters%C3PSN+0.40*EI*(1.-parameters%C3PSN), MIN(EA,EI) )\n\n! ci iteration\n!jref: C3PSN is equal to 1 for all veg types.\n       DO ITER = 1, NITER\n            WJ = MAX(CI-CP,0.)*J/(CI+2.*CP)*parameters%C3PSN  + J*(1.-parameters%C3PSN)\n            WC = MAX(CI-CP,0.)*VCMX/(CI+AWC)*parameters%C3PSN + VCMX*(1.-parameters%C3PSN)\n            WE = 0.5*VCMX*parameters%C3PSN + 4000.*VCMX*CI/SFCPRS*(1.-parameters%C3PSN)\n            PSN = MIN(WJ,WC,WE) * IGS\n\n            CS = MAX( CO2-1.37*RLB*SFCPRS*PSN, MPE )\n            A = parameters%MP*PSN*SFCPRS*CEA / (CS*EI) + parameters%BP\n            B = ( parameters%MP*PSN*SFCPRS/CS + parameters%BP ) * RLB - 1.\n            C = -RLB\n            IF (B .GE. 0.) THEN\n               Q = -0.5*( B + SQRT(B*B-4.*A*C) )\n            ELSE\n               Q = -0.5*( B - SQRT(B*B-4.*A*C) )\n            END IF\n            R1 = Q/A\n            R2 = C/Q\n            RS = MAX(R1,R2)\n            CI = MAX( CS-PSN*SFCPRS*1.65*RS, 0. )\n       END DO\n\n! rs, rb:  s m**2 / umol -> s/m\n\n         RS = RS*CF\n\n  END SUBROUTINE STOMATA\n\n!== begin canres ===================================================================================\n\n  SUBROUTINE CANRES (parameters,PAR   ,SFCTMP,RCSOIL ,EAH   ,SFCPRS , & !in\n                     RC    ,PSN   ,ILOC   ,JLOC  )           !out\n\n! --------------------------------------------------------------------------------------------------\n! calculate canopy resistance which depends on incoming solar radiation,\n! air temperature, atmospheric water vapor pressure deficit at the\n! lowest model level, and soil moisture (preferably unfrozen soil\n! moisture rather than total)\n! --------------------------------------------------------------------------------------------------\n! source:  Jarvis (1976), Noilhan and Planton (1989, MWR), Jacquemin and\n! Noilhan (1990, BLM). Chen et al (1996, JGR, Vol 101(D3), 7251-7268),\n! eqns 12-14 and table 2 of sec. 3.1.2\n! --------------------------------------------------------------------------------------------------\n!niu    USE module_Noahlsm_utility\n! --------------------------------------------------------------------------------------------------\n    IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n! inputs\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER,                  INTENT(IN)  :: ILOC   !grid index\n    INTEGER,                  INTENT(IN)  :: JLOC   !grid index\n    REAL,                     INTENT(IN)  :: PAR    !par absorbed per unit sunlit lai (w/m2)\n    REAL,                     INTENT(IN)  :: SFCTMP !canopy air temperature\n    REAL,                     INTENT(IN)  :: SFCPRS !surface pressure (pa)\n    REAL,                     INTENT(IN)  :: EAH    !water vapor pressure (pa)\n    REAL,                     INTENT(IN)  :: RCSOIL !soil moisture stress factor\n\n!outputs\n\n    REAL,                     INTENT(OUT) :: RC     !canopy resistance per unit LAI\n    REAL,                     INTENT(OUT) :: PSN    !foliage photosynthesis (umolco2/m2/s)\n\n!local\n\n    REAL                                  :: RCQ\n    REAL                                  :: RCS\n    REAL                                  :: RCT\n    REAL                                  :: FF\n    REAL                                  :: Q2     !water vapor mixing ratio (kg/kg)\n    REAL                                  :: Q2SAT  !saturation Q2\n    REAL                                  :: DQSDT2 !d(Q2SAT)/d(T)\n\n! RSMIN, RSMAX, TOPT, RGL, HS are canopy stress parameters set in REDPRM\n! ----------------------------------------------------------------------\n! initialize canopy resistance multiplier terms.\n! ----------------------------------------------------------------------\n    RC     = 0.0\n    RCS    = 0.0\n    RCT    = 0.0\n    RCQ    = 0.0\n\n!  compute Q2 and Q2SAT\n\n    Q2 = 0.622 *  EAH  / (SFCPRS - 0.378 * EAH) !specific humidity [kg/kg]\n    Q2 = Q2 / (1.0 + Q2)                        !mixing ratio [kg/kg]\n\n    CALL CALHUM(parameters,SFCTMP, SFCPRS, Q2SAT, DQSDT2)\n\n! contribution due to incoming solar radiation\n\n    FF  = 2.0 * PAR / parameters%RGL\n    RCS = (FF + parameters%RSMIN / parameters%RSMAX) / (1.0+ FF)\n    RCS = MAX (RCS,0.0001)\n\n! contribution due to air temperature\n\n    RCT = 1.0- 0.0016* ( (parameters%TOPT - SFCTMP)**2.0)\n    RCT = MAX (RCT,0.0001)\n\n! contribution due to vapor pressure deficit\n\n    RCQ = 1.0/ (1.0+ parameters%HS * MAX(0.,Q2SAT-Q2))\n    RCQ = MAX (RCQ,0.01)\n\n! determine canopy resistance due to all factors\n\n    RC  = parameters%RSMIN / (RCS * RCT * RCQ * RCSOIL)\n    PSN = -999.99       ! PSN not applied for dynamic carbon\n\n  END SUBROUTINE CANRES\n\n!== begin calhum ===================================================================================\n\n        SUBROUTINE CALHUM(parameters,SFCTMP, SFCPRS, Q2SAT, DQSDT2)\n\n        IMPLICIT NONE\n\n  type (noahmp_parameters), intent(in) :: parameters\n        REAL, INTENT(IN)       :: SFCTMP, SFCPRS\n        REAL, INTENT(OUT)      :: Q2SAT, DQSDT2\n        REAL, PARAMETER        :: A2=17.67,A3=273.15,A4=29.65, ELWV=2.501E6,         &\n                                  A23M4=A2*(A3-A4), E0=0.611, RV=461.0,             &\n                                  EPSILON=0.622\n        REAL                   :: ES, SFCPRSX\n\n! Q2SAT: saturated mixing ratio\n        ES = E0 * EXP ( ELWV/RV*(1./A3 - 1./SFCTMP) )\n! convert SFCPRS from Pa to KPa\n        SFCPRSX = SFCPRS*1.E-3\n        Q2SAT = EPSILON * ES / (SFCPRSX-ES)\n! convert from  g/g to g/kg\n        Q2SAT = Q2SAT * 1.E3\n! Q2SAT is currently a 'mixing ratio'\n\n! DQSDT2 is calculated assuming Q2SAT is a specific humidity\n        DQSDT2=(Q2SAT/(1+Q2SAT))*A23M4/(SFCTMP-A4)**2\n\n! DG Q2SAT needs to be in g/g when returned for SFLX\n        Q2SAT = Q2SAT / 1.E3\n\n        END SUBROUTINE CALHUM\n\n!== begin tsnosoi ==================================================================================\n\n  SUBROUTINE TSNOSOI (parameters,ICE     ,NSOIL   ,NSNOW   ,ISNOW   ,IST     , & !in\n                      TBOT    ,ZSNSO   ,SSOIL   ,DF      ,HCPCT   , & !in\n                      SAG     ,DT      ,SNOWH   ,DZSNSO  , & !in\n                      TG      ,ILOC    ,JLOC    ,                   & !in\n                      STC     )                                       !inout\n! --------------------------------------------------------------------------------------------------\n! Compute snow (up to 3L) and soil (4L) temperature. Note that snow temperatures\n! during melting season may exceed melting point (TFRZ) but later in PHASECHANGE\n! subroutine the snow temperatures are reset to TFRZ for melting snow.\n! --------------------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! --------------------------------------------------------------------------------------------------\n!input\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER,                         INTENT(IN)  :: ILOC\n    INTEGER,                         INTENT(IN)  :: JLOC\n    INTEGER,                         INTENT(IN)  :: ICE    !\n    INTEGER,                         INTENT(IN)  :: NSOIL  !no of soil layers (4)\n    INTEGER,                         INTENT(IN)  :: NSNOW  !maximum no of snow layers (3)\n    INTEGER,                         INTENT(IN)  :: ISNOW  !actual no of snow layers\n    INTEGER,                         INTENT(IN)  :: IST    !surface type\n\n    REAL,                            INTENT(IN)  :: DT     !time step (s)\n    REAL,                            INTENT(IN)  :: TBOT   !\n    REAL,                            INTENT(IN)  :: SSOIL  !ground heat flux (w/m2)\n    REAL,                            INTENT(IN)  :: SAG    !solar rad. absorbed by ground (w/m2)\n    REAL,                            INTENT(IN)  :: SNOWH  !snow depth (m)\n    REAL,                            INTENT(IN)  :: TG     !ground temperature (k)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: ZSNSO  !layer-bot. depth from snow surf.(m)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: DZSNSO !snow/soil layer thickness (m)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: DF     !thermal conductivity\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: HCPCT  !heat capacity (J/m3/k)\n\n!input and output\n\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC\n\n!local\n\n    INTEGER                                      :: IZ\n    REAL                                         :: ZBOTSNO   !ZBOT from snow surface\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: AI, BI, CI, RHSTS\n    REAL                                         :: EFLXB !energy influx from soil bottom (w/m2)\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: PHI   !light through water (w/m2)\n\n    REAL, DIMENSION(-NSNOW+1:NSOIL) :: TBEG\n    REAL                            :: ERR_EST !heat storage error  (w/m2)\n    REAL                            :: SSOIL2  !ground heat flux (w/m2) (for energy check)\n    REAL                            :: EFLXB2  !heat flux from the bottom (w/m2) (for energy check)\n    character(len=256)              :: message\n! ----------------------------------------------------------------------\n! compute solar penetration through water, needs more work\n\n    PHI(ISNOW+1:NSOIL) = 0.\n\n! adjust ZBOT from soil surface to ZBOTSNO from snow surface\n\n    ZBOTSNO = parameters%ZBOT - SNOWH    !from snow surface\n\n! snow/soil heat storage for energy balance check\n\n    DO IZ = ISNOW+1, NSOIL\n       TBEG(IZ) = STC(IZ)\n    ENDDO\n\n! compute soil temperatures\n\n      CALL HRT   (parameters,NSNOW     ,NSOIL     ,ISNOW     ,ZSNSO     , &\n                  STC       ,TBOT      ,ZBOTSNO   ,DT        , &\n                  DF        ,HCPCT     ,SSOIL     ,PHI       , &\n                  AI        ,BI        ,CI        ,RHSTS     , &\n                  EFLXB     )\n\n      CALL HSTEP (parameters,NSNOW     ,NSOIL     ,ISNOW     ,DT        , &\n                  AI        ,BI        ,CI        ,RHSTS     , &\n                  STC       )\n\n! update ground heat flux just for energy check, but not for final output\n! otherwise, it would break the surface energy balance\n\n    IF(OPT_TBOT == 1) THEN\n       EFLXB2  = 0.\n    ELSE IF(OPT_TBOT == 2) THEN\n       EFLXB2  = DF(NSOIL)*(TBOT-STC(NSOIL)) / &\n            (0.5*(ZSNSO(NSOIL-1)+ZSNSO(NSOIL)) - ZBOTSNO)\n    END IF\n\n    ! Skip the energy balance check for now, until we can make it work\n    ! right for small time steps.\n    return\n\n! energy balance check\n\n    ERR_EST = 0.0\n    DO IZ = ISNOW+1, NSOIL\n       ERR_EST = ERR_EST + (STC(IZ)-TBEG(IZ)) * DZSNSO(IZ) * HCPCT(IZ) / DT\n    ENDDO\n\n    if (OPT_STC == 1 .OR. OPT_STC == 3) THEN   ! semi-implicit\n       ERR_EST = ERR_EST - (SSOIL +EFLXB)\n    ELSE                     ! full-implicit\n       SSOIL2 = DF(ISNOW+1)*(TG-STC(ISNOW+1))/(0.5*DZSNSO(ISNOW+1))   !M. Barlage\n       ERR_EST = ERR_EST - (SSOIL2+EFLXB2)\n    ENDIF\n\n    IF (ABS(ERR_EST) > 1.) THEN    ! W/m2\n       WRITE(message,*) 'TSNOSOI is losing(-)/gaining(+) false energy',ERR_EST,' W/m2'\n       call wrf_message(trim(message))\n       WRITE(message,'(i6,1x,i6,1x,i3,F18.13,5F20.12)') &\n            ILOC, JLOC, IST,ERR_EST,SSOIL,SNOWH,TG,STC(ISNOW+1),EFLXB\n       call wrf_message(trim(message))\n       !niu      STOP\n    END IF\n\n  END SUBROUTINE TSNOSOI\n\n!== begin hrt ======================================================================================\n\n  SUBROUTINE HRT (parameters,NSNOW     ,NSOIL     ,ISNOW     ,ZSNSO     , &\n                  STC       ,TBOT      ,ZBOT      ,DT        , &\n                  DF        ,HCPCT     ,SSOIL     ,PHI       , &\n                  AI        ,BI        ,CI        ,RHSTS     , &\n                  BOTFLX    )\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! calculate the right hand side of the time tendency term of the soil\n! thermal diffusion equation.  also to compute ( prepare ) the matrix\n! coefficients for the tri-diagonal matrix of the implicit time scheme.\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER,                         INTENT(IN)  :: NSOIL  !no of soil layers (4)\n    INTEGER,                         INTENT(IN)  :: NSNOW  !maximum no of snow layers (3)\n    INTEGER,                         INTENT(IN)  :: ISNOW  !actual no of snow layers\n    REAL,                            INTENT(IN)  :: TBOT   !bottom soil temp. at ZBOT (k)\n    REAL,                            INTENT(IN)  :: ZBOT   !depth of lower boundary condition (m)\n                                                           !from soil surface not snow surface\n    REAL,                            INTENT(IN)  :: DT     !time step (s)\n    REAL,                            INTENT(IN)  :: SSOIL  !ground heat flux (w/m2)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: ZSNSO  !depth of layer-bottom of snow/soil (m)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: STC    !snow/soil temperature (k)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: DF     !thermal conductivity [w/m/k]\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: HCPCT  !heat capacity [j/m3/k]\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)  :: PHI    !light through water (w/m2)\n\n! output\n\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: RHSTS  !right-hand side of the matrix\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: AI     !left-hand side coefficient\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: BI     !left-hand side coefficient\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: CI     !left-hand side coefficient\n    REAL,                            INTENT(OUT) :: BOTFLX !energy influx from soil bottom (w/m2)\n\n! local\n\n    INTEGER                                      :: K\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: DDZ\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: DZ\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: DENOM\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: DTSDZ\n    REAL, DIMENSION(-NSNOW+1:NSOIL)              :: EFLUX\n    REAL                                         :: TEMP1\n! ----------------------------------------------------------------------\n\n    DO K = ISNOW+1, NSOIL\n        IF (K == ISNOW+1) THEN\n           DENOM(K)  = - ZSNSO(K) * HCPCT(K)\n           TEMP1     = - ZSNSO(K+1)\n           DDZ(K)    = 2.0 / TEMP1\n           DTSDZ(K)  = 2.0 * (STC(K) - STC(K+1)) / TEMP1\n           EFLUX(K)  = DF(K) * DTSDZ(K) - SSOIL - PHI(K)\n        ELSE IF (K < NSOIL) THEN\n           DENOM(K)  = (ZSNSO(K-1) - ZSNSO(K)) * HCPCT(K)\n           TEMP1     = ZSNSO(K-1) - ZSNSO(K+1)\n           DDZ(K)    = 2.0 / TEMP1\n           DTSDZ(K)  = 2.0 * (STC(K) - STC(K+1)) / TEMP1\n           EFLUX(K)  = (DF(K)*DTSDZ(K) - DF(K-1)*DTSDZ(K-1)) - PHI(K)\n        ELSE IF (K == NSOIL) THEN\n           DENOM(K)  = (ZSNSO(K-1) - ZSNSO(K)) * HCPCT(K)\n           TEMP1     =  ZSNSO(K-1) - ZSNSO(K)\n           IF(OPT_TBOT == 1) THEN\n               BOTFLX     = 0.\n           END IF\n           IF(OPT_TBOT == 2) THEN\n               DTSDZ(K)  = (STC(K) - TBOT) / ( 0.5*(ZSNSO(K-1)+ZSNSO(K)) - ZBOT)\n               BOTFLX    = -DF(K) * DTSDZ(K)\n           END IF\n           EFLUX(K)  = (-BOTFLX - DF(K-1)*DTSDZ(K-1) ) - PHI(K)\n        END IF\n    END DO\n\n    DO K = ISNOW+1, NSOIL\n        IF (K == ISNOW+1) THEN\n           AI(K)    =   0.0\n           CI(K)    = - DF(K)   * DDZ(K) / DENOM(K)\n           IF (OPT_STC == 1 .OR. OPT_STC == 3 ) THEN\n              BI(K) = - CI(K)\n           END IF\n           IF (OPT_STC == 2) THEN\n              BI(K) = - CI(K) + DF(K)/(0.5*ZSNSO(K)*ZSNSO(K)*HCPCT(K))\n           END IF\n        ELSE IF (K < NSOIL) THEN\n           AI(K)    = - DF(K-1) * DDZ(K-1) / DENOM(K)\n           CI(K)    = - DF(K  ) * DDZ(K  ) / DENOM(K)\n           BI(K)    = - (AI(K) + CI (K))\n        ELSE IF (K == NSOIL) THEN\n           AI(K)    = - DF(K-1) * DDZ(K-1) / DENOM(K)\n           CI(K)    = 0.0\n           BI(K)    = - (AI(K) + CI(K))\n        END IF\n           RHSTS(K)  = EFLUX(K)/ (-DENOM(K))\n    END DO\n\n  END SUBROUTINE HRT\n\n!== begin hstep ====================================================================================\n\n  SUBROUTINE HSTEP (parameters,NSNOW     ,NSOIL     ,ISNOW     ,DT        ,  &\n                    AI        ,BI        ,CI        ,RHSTS     ,  &\n                    STC       )\n! ----------------------------------------------------------------------\n! CALCULATE/UPDATE THE SOIL TEMPERATURE FIELD.\n! ----------------------------------------------------------------------\n    implicit none\n! ----------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER,                         INTENT(IN)    :: NSOIL\n    INTEGER,                         INTENT(IN)    :: NSNOW\n    INTEGER,                         INTENT(IN)    :: ISNOW\n    REAL,                            INTENT(IN)    :: DT\n\n! output & input\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: RHSTS\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: AI\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: BI\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: CI\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC\n\n! local\n    INTEGER                                        :: K\n    REAL, DIMENSION(-NSNOW+1:NSOIL)                :: RHSTSIN\n    REAL, DIMENSION(-NSNOW+1:NSOIL)                :: CIIN\n! ----------------------------------------------------------------------\n\n    DO K = ISNOW+1,NSOIL\n       RHSTS(K) =   RHSTS(K) * DT\n       AI(K)    =      AI(K) * DT\n       BI(K)    = 1. + BI(K) * DT\n       CI(K)    =      CI(K) * DT\n    END DO\n\n! copy values for input variables before call to rosr12\n\n    DO K = ISNOW+1,NSOIL\n       RHSTSIN(K) = RHSTS(K)\n       CIIN(K)    = CI(K)\n    END DO\n\n! solve the tri-diagonal matrix equation\n\n    CALL ROSR12 (CI,AI,BI,CIIN,RHSTSIN,RHSTS,ISNOW+1,NSOIL,NSNOW)\n\n! update snow & soil temperature\n\n    DO K = ISNOW+1,NSOIL\n       STC (K) = STC (K) + CI (K)\n    END DO\n\n  END SUBROUTINE HSTEP\n\n!== begin rosr12 ===================================================================================\n\n  SUBROUTINE ROSR12 (P,A,B,C,D,DELTA,NTOP,NSOIL,NSNOW)\n! ----------------------------------------------------------------------\n! SUBROUTINE ROSR12\n! ----------------------------------------------------------------------\n! INVERT (SOLVE) THE TRI-DIAGONAL MATRIX PROBLEM SHOWN BELOW:\n! ###                                            ### ###  ###   ###  ###\n! #B(1), C(1),  0  ,  0  ,  0  ,   . . .  ,    0   # #      #   #      #\n! #A(2), B(2), C(2),  0  ,  0  ,   . . .  ,    0   # #      #   #      #\n! # 0  , A(3), B(3), C(3),  0  ,   . . .  ,    0   # #      #   # D(3) #\n! # 0  ,  0  , A(4), B(4), C(4),   . . .  ,    0   # # P(4) #   # D(4) #\n! # 0  ,  0  ,  0  , A(5), B(5),   . . .  ,    0   # # P(5) #   # D(5) #\n! # .                                          .   # #  .   # = #   .  #\n! # .                                          .   # #  .   #   #   .  #\n! # .                                          .   # #  .   #   #   .  #\n! # 0  , . . . , 0 , A(M-2), B(M-2), C(M-2),   0   # #P(M-2)#   #D(M-2)#\n! # 0  , . . . , 0 ,   0   , A(M-1), B(M-1), C(M-1)# #P(M-1)#   #D(M-1)#\n! # 0  , . . . , 0 ,   0   ,   0   ,  A(M) ,  B(M) # # P(M) #   # D(M) #\n! ###                                            ### ###  ###   ###  ###\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n\n    INTEGER, INTENT(IN)   :: NTOP\n    INTEGER, INTENT(IN)   :: NSOIL,NSNOW\n    INTEGER               :: K, KK\n\n    REAL, DIMENSION(-NSNOW+1:NSOIL),INTENT(IN):: A, B, D\n    REAL, DIMENSION(-NSNOW+1:NSOIL),INTENT(INOUT):: C,P,DELTA\n\n! ----------------------------------------------------------------------\n! INITIALIZE EQN COEF C FOR THE LOWEST SOIL LAYER\n! ----------------------------------------------------------------------\n    C (NSOIL) = 0.0\n    P (NTOP) = - C (NTOP) / B (NTOP)\n! ----------------------------------------------------------------------\n! SOLVE THE COEFS FOR THE 1ST SOIL LAYER\n! ----------------------------------------------------------------------\n    DELTA (NTOP) = D (NTOP) / B (NTOP)\n! ----------------------------------------------------------------------\n! SOLVE THE COEFS FOR SOIL LAYERS 2 THRU NSOIL\n! ----------------------------------------------------------------------\n    DO K = NTOP+1,NSOIL\n       P (K) = - C (K) * ( 1.0 / (B (K) + A (K) * P (K -1)) )\n       DELTA (K) = (D (K) - A (K)* DELTA (K -1))* (1.0/ (B (K) + A (K)&\n            * P (K -1)))\n    END DO\n! ----------------------------------------------------------------------\n! SET P TO DELTA FOR LOWEST SOIL LAYER\n! ----------------------------------------------------------------------\n    P (NSOIL) = DELTA (NSOIL)\n! ----------------------------------------------------------------------\n! ADJUST P FOR SOIL LAYERS 2 THRU NSOIL\n! ----------------------------------------------------------------------\n    DO K = NTOP+1,NSOIL\n       KK = NSOIL - K + (NTOP-1) + 1\n       P (KK) = P (KK) * P (KK +1) + DELTA (KK)\n    END DO\n! ----------------------------------------------------------------------\n  END SUBROUTINE ROSR12\n\n!== begin phasechange ==============================================================================\n\n  SUBROUTINE PHASECHANGE (parameters,NSNOW   ,NSOIL   ,ISNOW   ,DT      ,FACT    , & !in\n                          DZSNSO  ,HCPCT   ,IST     ,ILOC    ,JLOC    , & !in\n                          STC     ,SNICE   ,SNLIQ   ,SNEQV   ,SNOWH   , & !inout\n                          SMC     ,SH2O    ,                            & !inout\n                          QMELT   ,IMELT   ,PONDING )                     !out\n! ----------------------------------------------------------------------\n! melting/freezing of snow water and soil water\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! inputs\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER, INTENT(IN)                             :: ILOC   !grid index\n  INTEGER, INTENT(IN)                             :: JLOC   !grid index\n  INTEGER, INTENT(IN)                             :: NSNOW  !maximum no. of snow layers [=3]\n  INTEGER, INTENT(IN)                             :: NSOIL  !No. of soil layers [=4]\n  INTEGER, INTENT(IN)                             :: ISNOW  !actual no. of snow layers [<=3]\n  INTEGER, INTENT(IN)                             :: IST    !surface type: 1->soil; 2->lake\n  REAL, INTENT(IN)                                :: DT     !land model time step (sec)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)     :: FACT   !temporary\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)     :: DZSNSO !snow/soil layer thickness [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)     :: HCPCT  !heat capacity (J/m3/k)\n\n! outputs\n  INTEGER, DIMENSION(-NSNOW+1:NSOIL), INTENT(OUT) :: IMELT  !phase change index\n  REAL,                               INTENT(OUT) :: QMELT  !snowmelt rate [mm/s]\n  REAL,                               INTENT(OUT) :: PONDING!snowmelt when snow has no layer [mm]\n\n! inputs and outputs\n\n  REAL, INTENT(INOUT) :: SNEQV\n  REAL, INTENT(INOUT) :: SNOWH\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT)  :: STC    !snow/soil layer temperature [k]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT)  :: SH2O   !soil liquid water [m3/m3]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT)  :: SMC    !total soil water [m3/m3]\n  REAL, DIMENSION(-NSNOW+1:0)    , INTENT(INOUT)  :: SNICE  !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:0)    , INTENT(INOUT)  :: SNLIQ  !snow layer liquid water [mm]\n\n! local\n\n  INTEGER                         :: J         !do loop index\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: HM        !energy residual [w/m2]\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: XM        !melting or freezing water [kg/m2]\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: WMASS0\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: WICE0\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: WLIQ0\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: MICE      !soil/snow ice mass [mm]\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: MLIQ      !soil/snow liquid water mass [mm]\n  REAL, DIMENSION(-NSNOW+1:NSOIL) :: SUPERCOOL !supercooled water in soil (kg/m2)\n  REAL                            :: HEATR     !energy residual or loss after melting/freezing\n  REAL                            :: TEMP1     !temporary variables [kg/m2]\n  REAL                            :: PROPOR\n  REAL                            :: SMP       !frozen water potential (mm)\n  REAL                            :: XMF       !total latent heat of phase change\n\n! ----------------------------------------------------------------------\n! Initialization\n\n    QMELT   = 0.\n    PONDING = 0.\n    XMF     = 0.\n\n    DO J = -NSNOW+1, NSOIL\n         SUPERCOOL(J) = 0.0\n    END DO\n\n    DO J = ISNOW+1,0       ! all layers\n         MICE(J) = SNICE(J)\n         MLIQ(J) = SNLIQ(J)\n    END DO\n\n    DO J = 1, NSOIL               ! soil\n         MLIQ(J) =  SH2O(J)            * DZSNSO(J) * 1000.\n         MICE(J) = (SMC(J) - SH2O(J))  * DZSNSO(J) * 1000.\n    END DO\n\n    DO J = ISNOW+1,NSOIL       ! all layers\n         IMELT(J)    = 0\n         HM(J)       = 0.\n         XM(J)       = 0.\n         WICE0(J)    = MICE(J)\n         WLIQ0(J)    = MLIQ(J)\n         WMASS0(J)   = MICE(J) + MLIQ(J)\n    ENDDO\n\n    if(ist == 1) then\n      DO J = 1,NSOIL\n         IF (OPT_FRZ == 1) THEN\n            IF(STC(J) < TFRZ) THEN\n               SMP = HFUS*(TFRZ-STC(J))/(GRAV*STC(J))             !(m)\n               SUPERCOOL(J) = parameters%SMCMAX(J)*(SMP/parameters%PSISAT(J))**(-1./parameters%BEXP(J))\n               SUPERCOOL(J) = SUPERCOOL(J)*DZSNSO(J)*1000.        !(mm)\n            END IF\n         END IF\n         IF (OPT_FRZ == 2) THEN\n               CALL FRH2O (parameters,J,SUPERCOOL(J),STC(J),SMC(J),SH2O(J))\n               SUPERCOOL(J) = SUPERCOOL(J)*DZSNSO(J)*1000.        !(mm)\n         END IF\n      ENDDO\n    end if\n\n    DO J = ISNOW+1,NSOIL\n         IF (MICE(J) > 0. .AND. STC(J) >= TFRZ) THEN  !melting\n             IMELT(J) = 1\n         ENDIF\n         IF (MLIQ(J) > SUPERCOOL(J) .AND. STC(J) < TFRZ) THEN\n             IMELT(J) = 2\n         ENDIF\n\n         ! If snow exists, but its thickness is not enough to create a layer\n         IF (ISNOW == 0 .AND. SNEQV > 0. .AND. J == 1) THEN\n             IF (STC(J) >= TFRZ) THEN\n                IMELT(J) = 1\n             ENDIF\n         ENDIF\n    ENDDO\n\n! Calculate the energy surplus and loss for melting and freezing\n\n    DO J = ISNOW+1,NSOIL\n         IF (IMELT(J) > 0) THEN\n             HM(J) = (STC(J)-TFRZ)/FACT(J)\n             STC(J) = TFRZ\n         ENDIF\n\n         IF (IMELT(J) == 1 .AND. HM(J) < 0.) THEN\n            HM(J) = 0.\n            IMELT(J) = 0\n         ENDIF\n         IF (IMELT(J) == 2 .AND. HM(J) > 0.) THEN\n            HM(J) = 0.\n            IMELT(J) = 0\n         ENDIF\n         XM(J) = HM(J)*DT/HFUS\n    ENDDO\n\n! The rate of melting and freezing for snow without a layer, needs more work.\n\n    IF (ISNOW == 0 .AND. SNEQV > 0. .AND. XM(1) > 0.) THEN\n        TEMP1  = SNEQV\n        SNEQV  = MAX(0.,TEMP1-XM(1))\n        PROPOR = SNEQV/TEMP1\n        SNOWH  = MAX(0.,PROPOR * SNOWH)\n        SNOWH  = MIN(MAX(SNOWH,SNEQV/500.0),SNEQV/50.0)  ! limit adjustment to a reasonable density\n        HEATR  = HM(1) - HFUS*(TEMP1-SNEQV)/DT\n        IF (HEATR > 0.) THEN\n              XM(1) = HEATR*DT/HFUS\n              HM(1) = HEATR\n        ELSE\n              XM(1) = 0.\n              HM(1) = 0.\n        ENDIF\n        QMELT   = MAX(0.,(TEMP1-SNEQV))/DT\n        XMF     = HFUS*QMELT\n        PONDING = TEMP1-SNEQV\n    ENDIF\n\n! The rate of melting and freezing for snow and soil\n\n    DO J = ISNOW+1,NSOIL\n      IF (IMELT(J) > 0 .AND. ABS(HM(J)) > 0.) THEN\n\n         HEATR = 0.\n         IF (XM(J) > 0.) THEN\n            MICE(J) = MAX(0., WICE0(J)-XM(J))\n            HEATR = HM(J) - HFUS*(WICE0(J)-MICE(J))/DT\n         ELSE IF (XM(J) < 0.) THEN\n            IF (J <= 0) THEN                             ! snow\n               MICE(J) = MIN(WMASS0(J), WICE0(J)-XM(J))\n            ELSE                                         ! soil\n               IF (WMASS0(J) < SUPERCOOL(J)) THEN\n                  MICE(J) = 0.\n               ELSE\n                  MICE(J) = MIN(WMASS0(J) - SUPERCOOL(J),WICE0(J)-XM(J))\n                  MICE(J) = MAX(MICE(J),0.0)\n               ENDIF\n            ENDIF\n            HEATR = HM(J) - HFUS*(WICE0(J)-MICE(J))/DT\n         ENDIF\n\n         MLIQ(J) = MAX(0.,WMASS0(J)-MICE(J))\n\n         IF (ABS(HEATR) > 0.) THEN\n            STC(J) = STC(J) + FACT(J)*HEATR\n            IF (J <= 0) THEN                             ! snow\n               IF (MLIQ(J)*MICE(J)>0.) STC(J) = TFRZ\n               IF (MICE(J) == 0.) THEN         ! BARLAGE\n                  STC(J) = TFRZ                ! BARLAGE\n                  HM(J+1) = HM(J+1) + HEATR    ! BARLAGE\n                  XM(J+1) = HM(J+1)*DT/HFUS    ! BARLAGE\n               ENDIF\n            END IF\n         ENDIF\n\n         XMF = XMF + HFUS * (WICE0(J)-MICE(J))/DT\n\n         IF (J < 1) THEN\n            QMELT = QMELT + MAX(0.,(WICE0(J)-MICE(J)))/DT\n         ENDIF\n      ENDIF\n    ENDDO\n\n    DO J = ISNOW+1,0             ! snow\n       SNLIQ(J) = MLIQ(J)\n       SNICE(J) = MICE(J)\n    END DO\n\n    DO J = 1, NSOIL              ! soil\n       SH2O(J) =  MLIQ(J)            / (1000. * DZSNSO(J))\n       SMC(J)  = (MLIQ(J) + MICE(J)) / (1000. * DZSNSO(J))\n    END DO\n\n  END SUBROUTINE PHASECHANGE\n\n!== begin frh2o ====================================================================================\n\n  SUBROUTINE FRH2O (parameters,ISOIL,FREE,TKELV,SMC,SH2O)\n\n! ----------------------------------------------------------------------\n! SUBROUTINE FRH2O\n! ----------------------------------------------------------------------\n! CALCULATE AMOUNT OF SUPERCOOLED LIQUID SOIL WATER CONTENT IF\n! TEMPERATURE IS BELOW 273.15K (TFRZ).  REQUIRES NEWTON-TYPE ITERATION\n! TO SOLVE THE NONLINEAR IMPLICIT EQUATION GIVEN IN EQN 17 OF KOREN ET AL\n! (1999, JGR, VOL 104(D16), 19569-19585).\n! ----------------------------------------------------------------------\n! NEW VERSION (JUNE 2001): MUCH FASTER AND MORE ACCURATE NEWTON\n! ITERATION ACHIEVED BY FIRST TAKING LOG OF EQN CITED ABOVE -- LESS THAN\n! 4 (TYPICALLY 1 OR 2) ITERATIONS ACHIEVES CONVERGENCE.  ALSO, EXPLICIT\n! 1-STEP SOLUTION OPTION FOR SPECIAL CASE OF PARAMETER CK=0, WHICH\n! REDUCES THE ORIGINAL IMPLICIT EQUATION TO A SIMPLER EXPLICIT FORM,\n! KNOWN AS THE \"FLERCHINGER EQN\". IMPROVED HANDLING OF SOLUTION IN THE\n! LIMIT OF FREEZING POINT TEMPERATURE TFRZ.\n! ----------------------------------------------------------------------\n! INPUT:\n\n!   TKELV.........TEMPERATURE (Kelvin)\n!   SMC...........TOTAL SOIL MOISTURE CONTENT (VOLUMETRIC)\n!   SH2O..........LIQUID SOIL MOISTURE CONTENT (VOLUMETRIC)\n!   B.............SOIL TYPE \"B\" PARAMETER (FROM REDPRM)\n!   PSISAT........SATURATED SOIL MATRIC POTENTIAL (FROM REDPRM)\n\n! OUTPUT:\n!   FREE..........SUPERCOOLED LIQUID WATER CONTENT [m3/m3]\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER,INTENT(IN)   :: ISOIL\n    REAL, INTENT(IN)     :: SH2O,SMC,TKELV\n    REAL, INTENT(OUT)    :: FREE\n    REAL                 :: BX,DENOM,DF,DSWL,FK,SWL,SWLK\n    INTEGER              :: NLOG,KCOUNT\n!      PARAMETER(CK = 0.0)\n    REAL, PARAMETER      :: CK = 8.0, BLIM = 5.5, ERROR = 0.005,       &\n         DICE = 920.0\n    CHARACTER(LEN=80)    :: message\n\n! ----------------------------------------------------------------------\n! LIMITS ON PARAMETER B: B < 5.5  (use parameter BLIM)\n! SIMULATIONS SHOWED IF B > 5.5 UNFROZEN WATER CONTENT IS\n! NON-REALISTICALLY HIGH AT VERY LOW TEMPERATURES.\n! ----------------------------------------------------------------------\n    BX = parameters%BEXP(ISOIL)\n! ----------------------------------------------------------------------\n! INITIALIZING ITERATIONS COUNTER AND ITERATIVE SOLUTION FLAG.\n! ----------------------------------------------------------------------\n\n    IF (parameters%BEXP(ISOIL) >  BLIM) BX = BLIM\n    NLOG = 0\n\n! ----------------------------------------------------------------------\n!  IF TEMPERATURE NOT SIGNIFICANTLY BELOW FREEZING (TFRZ), SH2O = SMC\n! ----------------------------------------------------------------------\n    KCOUNT = 0\n    IF (TKELV > (TFRZ- 1.E-3)) THEN\n       FREE = SMC\n    ELSE\n\n! ----------------------------------------------------------------------\n! OPTION 1: ITERATED SOLUTION IN KOREN ET AL, JGR, 1999, EQN 17\n! ----------------------------------------------------------------------\n! INITIAL GUESS FOR SWL (frozen content)\n! ----------------------------------------------------------------------\n       IF (CK /= 0.0) THEN\n          SWL = SMC - SH2O\n! ----------------------------------------------------------------------\n! KEEP WITHIN BOUNDS.\n! ----------------------------------------------------------------------\n          IF (SWL > (SMC -0.02)) SWL = SMC -0.02\n! ----------------------------------------------------------------------\n!  START OF ITERATIONS\n! ----------------------------------------------------------------------\n          IF (SWL < 0.) SWL = 0.\n1001      Continue\n          IF (.NOT.( (NLOG < 10) .AND. (KCOUNT == 0)))   goto 1002\n          NLOG = NLOG +1\n          DF = ALOG ( ( parameters%PSISAT(ISOIL) * GRAV / HFUS ) * ( ( 1. + CK * SWL )**2.) * &\n               ( parameters%SMCMAX(ISOIL) / (SMC - SWL) )** BX) - ALOG ( - (               &\n               TKELV - TFRZ)/ TKELV)\n          DENOM = 2. * CK / ( 1. + CK * SWL ) + BX / ( SMC - SWL )\n          SWLK = SWL - DF / DENOM\n! ----------------------------------------------------------------------\n! BOUNDS USEFUL FOR MATHEMATICAL SOLUTION.\n! ----------------------------------------------------------------------\n          IF (SWLK > (SMC -0.02)) SWLK = SMC - 0.02\n          IF (SWLK < 0.) SWLK = 0.\n\n! ----------------------------------------------------------------------\n! MATHEMATICAL SOLUTION BOUNDS APPLIED.\n! ----------------------------------------------------------------------\n          DSWL = ABS (SWLK - SWL)\n! IF MORE THAN 10 ITERATIONS, USE EXPLICIT METHOD (CK=0 APPROX.)\n! WHEN DSWL LESS OR EQ. ERROR, NO MORE ITERATIONS REQUIRED.\n! ----------------------------------------------------------------------\n          SWL = SWLK\n          IF ( DSWL <= ERROR ) THEN\n             KCOUNT = KCOUNT +1\n          END IF\n! ----------------------------------------------------------------------\n!  END OF ITERATIONS\n! ----------------------------------------------------------------------\n! BOUNDS APPLIED WITHIN DO-BLOCK ARE VALID FOR PHYSICAL SOLUTION.\n! ----------------------------------------------------------------------\n          goto 1001\n1002      continue\n          FREE = SMC - SWL\n       END IF\n! ----------------------------------------------------------------------\n! END OPTION 1\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n! OPTION 2: EXPLICIT SOLUTION FOR FLERCHINGER EQ. i.e. CK=0\n! IN KOREN ET AL., JGR, 1999, EQN 17\n! APPLY PHYSICAL BOUNDS TO FLERCHINGER SOLUTION\n! ----------------------------------------------------------------------\n       IF (KCOUNT == 0) THEN\n          write(message, '(\"Flerchinger used in NEW version. Iterations=\", I6)') NLOG\n          call wrf_message(trim(message))\n          FK = ( ( (HFUS / (GRAV * ( - parameters%PSISAT(ISOIL))))*                    &\n               ( (TKELV - TFRZ)/ TKELV))** ( -1/ BX))* parameters%SMCMAX(ISOIL)\n          IF (FK < 0.02) FK = 0.02\n          FREE = MIN (FK, SMC)\n! ----------------------------------------------------------------------\n! END OPTION 2\n! ----------------------------------------------------------------------\n       END IF\n    END IF\n! ----------------------------------------------------------------------\n  END SUBROUTINE FRH2O\n! ----------------------------------------------------------------------\n! ==================================================================================================\n! **********************End of energy subroutines***********************\n! ==================================================================================================\n\n!== begin water ====================================================================================\n\n  SUBROUTINE WATER (parameters,VEGTYP ,NSNOW  ,NSOIL  ,IMELT  ,DT     ,UU     , & !in\n                    VV     ,FCEV   ,FCTR   ,QPRECC ,QPRECL ,ELAI   , & !in\n                    ESAI   ,SFCTMP ,QVAP   ,QDEW   ,ZSOIL  ,BTRANI , & !in\n                    FICEOLD,PONDING,TG     ,IST    ,FVEG   ,ILOC   ,JLOC ,SMCEQ , & !in\n                    BDFALL ,FP     ,RAIN   ,SNOW,                    & !in  MB/AN: v3.7\n\t\t    QSNOW  ,QRAIN  ,SNOWHIN,LATHEAV,LATHEAG,frozen_canopy,frozen_ground,    & !in  MB\n                    ISNOW  ,CANLIQ ,CANICE ,TV     ,SNOWH  ,SNEQV  , & !inout\n                    SNICE  ,SNLIQ  ,STC    ,ZSNSO  ,SH2O   ,SMC    , & !inout\n                    SICE   ,ZWT    ,WA     ,WT     ,DZSNSO ,WSLAKE , & !inout\n                    SMCWTD ,DEEPRECH,RECH                          , & !inout\n                    CMC    ,ECAN   ,ETRAN  ,FWET   ,RUNSRF ,RUNSUB , & !out\n                    QIN    ,QDIS   ,PONDING1       ,PONDING2,        &\n                    QSNBOT                                           &\n#ifdef WRF_HYDRO\n                        ,sfcheadrt                     &\n#endif\n                    )  !out\n! ----------------------------------------------------------------------\n! Code history:\n! Initial code: Guo-Yue Niu, Oct. 2007\n! ----------------------------------------------------------------------\n  implicit none\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                         INTENT(IN)    :: ILOC    !grid index\n  INTEGER,                         INTENT(IN)    :: JLOC    !grid index\n  INTEGER,                         INTENT(IN)    :: VEGTYP  !vegetation type\n  INTEGER,                         INTENT(IN)    :: NSNOW   !maximum no. of snow layers\n  INTEGER                        , INTENT(IN)    :: IST     !surface type 1-soil; 2-lake\n  INTEGER,                         INTENT(IN)    :: NSOIL   !no. of soil layers\n  INTEGER, DIMENSION(-NSNOW+1:0) , INTENT(IN)    :: IMELT   !melting state index [1-melt; 2-freeze]\n  REAL,                            INTENT(IN)    :: DT      !main time step (s)\n  REAL,                            INTENT(IN)    :: UU      !u-direction wind speed [m/s]\n  REAL,                            INTENT(IN)    :: VV      !v-direction wind speed [m/s]\n  REAL,                            INTENT(IN)    :: FCEV    !canopy evaporation (w/m2) [+ to atm ]\n  REAL,                            INTENT(IN)    :: FCTR    !transpiration (w/m2) [+ to atm]\n  REAL,                            INTENT(IN)    :: QPRECC  !convective precipitation (mm/s)\n  REAL,                            INTENT(IN)    :: QPRECL  !large-scale precipitation (mm/s)\n  REAL,                            INTENT(IN)    :: ELAI    !leaf area index, after burying by snow\n  REAL,                            INTENT(IN)    :: ESAI    !stem area index, after burying by snow\n  REAL,                            INTENT(IN)    :: SFCTMP  !surface air temperature [k]\n  REAL,                            INTENT(IN)    :: QVAP    !soil surface evaporation rate[mm/s]\n  REAL,                            INTENT(IN)    :: QDEW    !soil surface dew rate[mm/s]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: ZSOIL   !depth of layer-bottom from soil surface\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: BTRANI  !soil water stress factor (0 to 1)\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: FICEOLD !ice fraction at last timestep\n!  REAL                           , INTENT(IN)    :: PONDING ![mm]\n  REAL                           , INTENT(IN)    :: TG      !ground temperature (k)\n  REAL                           , INTENT(IN)    :: FVEG    !greeness vegetation fraction (-)\n  REAL                           , INTENT(IN)    :: BDFALL   !bulk density of snowfall (kg/m3) ! MB/AN: v3.7\n  REAL                           , INTENT(IN)    :: FP       !fraction of the gridcell that receives precipitation ! MB/AN: v3.7\n  REAL                           , INTENT(IN)    :: RAIN     !rainfall (mm/s) ! MB/AN: v3.7\n  REAL                           , INTENT(IN)    :: SNOW     !snowfall (mm/s) ! MB/AN: v3.7\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: SMCEQ   !equilibrium soil water content [m3/m3] (used in m-m&f groundwater dynamics)\n  REAL                           , INTENT(IN)    :: QSNOW   !snow at ground srf (mm/s) [+]\n  REAL                           , INTENT(IN)    :: QRAIN   !rain at ground srf (mm) [+]\n  REAL                           , INTENT(IN)    :: SNOWHIN !snow depth increasing rate (m/s)\n\n! input/output\n  INTEGER,                         INTENT(INOUT) :: ISNOW   !actual no. of snow layers\n  REAL,                            INTENT(INOUT) :: CANLIQ  !intercepted liquid water (mm)\n  REAL,                            INTENT(INOUT) :: CANICE  !intercepted ice mass (mm)\n  REAL,                            INTENT(INOUT) :: TV      !vegetation temperature (k)\n  REAL,                            INTENT(INOUT) :: SNOWH   !snow height [m]\n  REAL,                            INTENT(INOUT) :: SNEQV   !snow water eqv. [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE   !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ   !snow layer liquid water [mm]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC     !snow/soil layer temperature [k]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: ZSNSO   !depth of snow/soil layer-bottom\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO  !snow/soil layer thickness [m]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O    !soil liquid water content [m3/m3]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SICE    !soil ice content [m3/m3]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SMC     !total soil water content [m3/m3]\n  REAL,                            INTENT(INOUT) :: ZWT     !the depth to water table [m]\n  REAL,                            INTENT(INOUT) :: WA      !water storage in aquifer [mm]\n  REAL,                            INTENT(INOUT) :: WT      !water storage in aquifer\n                                                            !+ stuarated soil [mm]\n  REAL,                            INTENT(INOUT) :: WSLAKE  !water storage in lake (can be -) (mm)\n  REAL                           , INTENT(INOUT) :: PONDING ![mm]\n  REAL,                            INTENT(INOUT) :: SMCWTD !soil water content between bottom of the soil and water table [m3/m3]\n  REAL,                            INTENT(INOUT) :: DEEPRECH !recharge to or from the water table when deep [m]\n  REAL,                            INTENT(INOUT) :: RECH !recharge to or from the water table when shallow [m] (diagnostic)\n\n! output\n  REAL,                            INTENT(OUT)   :: CMC     !intercepted water per ground area (mm)\n  REAL,                            INTENT(OUT)   :: ECAN    !evap of intercepted water (mm/s) [+]\n  REAL,                            INTENT(OUT)   :: ETRAN   !transpiration rate (mm/s) [+]\n  REAL,                            INTENT(OUT)   :: FWET    !wetted/snowed fraction of canopy (-)\n  REAL,                            INTENT(OUT)   :: RUNSRF  !surface runoff [mm/s]\n  REAL,                            INTENT(OUT)   :: RUNSUB  !baseflow (sturation excess) [mm/s]\n  REAL,                            INTENT(OUT)   :: QIN     !groundwater recharge [mm/s]\n  REAL,                            INTENT(OUT)   :: QDIS    !groundwater discharge [mm/s]\n  REAL,                            INTENT(OUT)   :: PONDING1\n  REAL,                            INTENT(OUT)   :: PONDING2\n  REAL,                            INTENT(OUT)   :: QSNBOT  !melting water out of snow bottom [mm/s]\n  REAL                              , INTENT(IN)   :: LATHEAV !latent heat vap./sublimation (j/kg)\n  REAL                              , INTENT(IN)   :: LATHEAG !latent heat vap./sublimation (j/kg)\n  LOGICAL                           , INTENT(IN)   :: FROZEN_GROUND ! used to define latent heat pathway\n  LOGICAL                           , INTENT(IN)   :: FROZEN_CANOPY ! used to define latent heat pathway\n\n\n! local\n  INTEGER                                        :: IZ\n  REAL                                           :: QINSUR  !water input on soil surface [m/s]\n  REAL                                           :: QSEVA   !soil surface evap rate [mm/s]\n  REAL                                           :: QSDEW   !soil surface dew rate [mm/s]\n  REAL                                           :: QSNFRO  !snow surface frost rate[mm/s]\n  REAL                                           :: QSNSUB  !snow surface sublimation rate [mm/s]\n  REAL, DIMENSION(       1:NSOIL)                :: ETRANI  !transpiration rate (mm/s) [+]\n  REAL, DIMENSION(       1:NSOIL)                :: WCND   !hydraulic conductivity (m/s)\n  REAL                                           :: QDRAIN  !soil-bottom free drainage [mm/s]\n  REAL                                           :: SNOFLOW !glacier flow [mm/s]\n  REAL                                           :: FCRMAX !maximum of FCR (-)\n\n  REAL, PARAMETER ::  WSLMAX = 5000.      !maximum lake water storage (mm)\n\n#ifdef WRF_HYDRO\n  REAL                           , INTENT(INOUT)    :: sfcheadrt\n#endif\n\n! ----------------------------------------------------------------------\n! initialize\n\n   ETRANI(1:NSOIL) = 0.\n   SNOFLOW         = 0.\n   RUNSUB          = 0.\n   QINSUR          = 0.\n\n! canopy-intercepted snowfall/rainfall, drips, and throughfall\n\n   CALL CANWATER (parameters,VEGTYP ,DT     , & !in\n                  FCEV   ,FCTR   ,ELAI   , & !in\n                  ESAI   ,TG     ,FVEG   ,ILOC   , JLOC, & !in\n                  BDFALL ,FROZEN_CANOPY  , & !in\n                  CANLIQ ,CANICE ,TV     ,                 & !inout\n                  CMC    ,ECAN   ,ETRAN  , & !out\n                  FWET      )                           !out\n\n! sublimation, frost, evaporation, and dew\n\n     QSNSUB = 0.\n     IF (SNEQV > 0.) THEN\n       QSNSUB = MIN(QVAP, SNEQV/DT)\n     ENDIF\n     QSEVA = QVAP-QSNSUB\n\n     QSNFRO = 0.\n     IF (SNEQV > 0.) THEN\n        QSNFRO = QDEW\n     ENDIF\n     QSDEW = QDEW - QSNFRO\n\n     CALL SNOWWATER (parameters,NSNOW  ,NSOIL  ,IMELT  ,DT     ,ZSOIL  , & !in\n          &          SFCTMP ,SNOWHIN,QSNOW  ,QSNFRO ,QSNSUB , & !in\n          &          QRAIN  ,FICEOLD,ILOC   ,JLOC   ,         & !in\n          &          ISNOW  ,SNOWH  ,SNEQV  ,SNICE  ,SNLIQ  , & !inout\n          &          SH2O   ,SICE   ,STC    ,ZSNSO  ,DZSNSO , & !inout\n          &          QSNBOT ,SNOFLOW,PONDING1       ,PONDING2)  !out\n\n   IF(FROZEN_GROUND) THEN\n      SICE(1) =  SICE(1) + (QSDEW-QSEVA)*DT/(DZSNSO(1)*1000.)\n      QSDEW = 0.0\n      QSEVA = 0.0\n      IF(SICE(1) < 0.) THEN\n         SH2O(1) = SH2O(1) + SICE(1)\n         SICE(1) = 0.\n      END IF\n   END IF\n\n! convert units (mm/s -> m/s)\n\n    !PONDING: melting water from snow when there is no layer\n    QINSUR = (PONDING+PONDING1+PONDING2)/DT * 0.001\n!    QINSUR = PONDING/DT * 0.001\n\n    IF(ISNOW == 0) THEN\n       QINSUR = QINSUR+(QSNBOT + QSDEW + QRAIN) * 0.001\n    ELSE\n       QINSUR = QINSUR+(QSNBOT + QSDEW) * 0.001\n    ENDIF\n\n    QSEVA  = QSEVA * 0.001\n\n    DO IZ = 1, parameters%NROOT\n       ETRANI(IZ) = ETRAN * BTRANI(IZ) * 0.001\n    ENDDO\n\n#ifdef WRF_HYDRO\n       QINSUR = QINSUR+sfcheadrt/DT*0.001  !sfcheadrt units (m)\n#endif\n\n! lake/soil water balances\n\n    IF (IST == 2) THEN                                        ! lake\n       RUNSRF = 0.\n       IF(WSLAKE >= WSLMAX) RUNSRF = QINSUR*1000.             !mm/s\n       WSLAKE = WSLAKE + (QINSUR-QSEVA)*1000.*DT -RUNSRF*DT   !mm\n    ELSE                                                      ! soil\n       CALL      SOILWATER (parameters,NSOIL  ,NSNOW  ,DT     ,ZSOIL  ,DZSNSO , & !in\n                            QINSUR ,QSEVA  ,ETRANI ,SICE   ,ILOC   , JLOC , & !in\n                            SH2O   ,SMC    ,ZWT    ,VEGTYP , & !inout\n                           SMCWTD, DEEPRECH                       , & !inout\n                            RUNSRF ,QDRAIN ,RUNSUB ,WCND   ,FCRMAX )   !out\n\n       IF(OPT_RUN == 1) THEN\n          CALL GROUNDWATER (parameters,NSNOW  ,NSOIL  ,DT     ,SICE   ,ZSOIL  , & !in\n                            STC    ,WCND   ,FCRMAX ,ILOC   ,JLOC   , & !in\n                            SH2O   ,ZWT    ,WA     ,WT     ,         & !inout\n                            QIN    ,QDIS   )                           !out\n          RUNSUB       = QDIS          !mm/s\n       END IF\n\n       IF(OPT_RUN == 3 .or. OPT_RUN == 4 .or. OPT_RUN == 7) THEN\n          RUNSUB       = RUNSUB + QDRAIN        !mm/s\n       END IF\n\n       DO IZ = 1,NSOIL\n           SMC(IZ) = SH2O(IZ) + SICE(IZ)\n       ENDDO\n\n       IF(OPT_RUN == 5) THEN\n          CALL SHALLOWWATERTABLE (parameters,NSNOW  ,NSOIL, ZSOIL, DT       , & !in\n                         DZSNSO ,SMCEQ   ,ILOC , JLOC        , & !in\n                         SMC    ,ZWT    ,SMCWTD ,RECH, QDRAIN  ) !inout\n\n          SH2O(NSOIL) = SMC(NSOIL) - SICE(NSOIL)\n          RUNSUB = RUNSUB + QDRAIN !it really comes from subroutine watertable, which is not called with the same frequency as the soil routines here\n          WA = 0.\n       ENDIF\n\n    ENDIF\n\n    RUNSUB       = RUNSUB + SNOFLOW         !mm/s\n\n  END SUBROUTINE WATER\n\n!== begin canwater =================================================================================\n\n  SUBROUTINE CANWATER (parameters,VEGTYP ,DT     , & !in\n                       FCEV   ,FCTR   ,ELAI   , & !in\n                       ESAI   ,TG     ,FVEG   ,ILOC   , JLOC , & !in\n                       BDFALL ,FROZEN_CANOPY  ,  & !in\n                       CANLIQ ,CANICE ,TV     ,                 & !inout\n                       CMC    ,ECAN   ,ETRAN  , & !out\n                       FWET      )                           !out\n\n! ------------------------ code history ------------------------------\n! canopy hydrology\n! --------------------------------------------------------------------\n  IMPLICIT NONE\n! ------------------------ input/output variables --------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,INTENT(IN)  :: ILOC    !grid index\n  INTEGER,INTENT(IN)  :: JLOC    !grid index\n  INTEGER,INTENT(IN)  :: VEGTYP  !vegetation type\n  REAL,   INTENT(IN)  :: DT      !main time step (s)\n  REAL,   INTENT(IN)  :: FCEV    !canopy evaporation (w/m2) [+ = to atm]\n  REAL,   INTENT(IN)  :: FCTR    !transpiration (w/m2) [+ = to atm]\n  REAL,   INTENT(IN)  :: ELAI    !leaf area index, after burying by snow\n  REAL,   INTENT(IN)  :: ESAI    !stem area index, after burying by snow\n  REAL,   INTENT(IN)  :: TG      !ground temperature (k)\n  REAL,   INTENT(IN)  :: FVEG    !greeness vegetation fraction (-)\n  LOGICAL                           , INTENT(IN)   :: FROZEN_CANOPY ! used to define latent heat pathway\n  REAL                           , INTENT(IN)    :: BDFALL   !bulk density of snowfall (kg/m3) ! MB/AN: v3.7\n\n! input & output\n  REAL, INTENT(INOUT) :: CANLIQ  !intercepted liquid water (mm)\n  REAL, INTENT(INOUT) :: CANICE  !intercepted ice mass (mm)\n  REAL, INTENT(INOUT) :: TV      !vegetation temperature (k)\n\n! output\n  REAL, INTENT(OUT)   :: CMC     !intercepted water (mm)\n  REAL, INTENT(OUT)   :: ECAN    !evaporation of intercepted water (mm/s) [+]\n  REAL, INTENT(OUT)   :: ETRAN   !transpiration rate (mm/s) [+]\n  REAL, INTENT(OUT)   :: FWET    !wetted or snowed fraction of the canopy (-)\n! --------------------------------------------------------------------\n\n! ------------------------ local variables ---------------------------\n  REAL                :: MAXSNO  !canopy capacity for snow interception (mm)\n  REAL                :: MAXLIQ  !canopy capacity for rain interception (mm)\n  REAL                :: QEVAC   !evaporation rate (mm/s)\n  REAL                :: QDEWC   !dew rate (mm/s)\n  REAL                :: QFROC   !frost rate (mm/s)\n  REAL                :: QSUBC   !sublimation rate (mm/s)\n  REAL                :: QMELTC  !melting rate of canopy snow (mm/s)\n  REAL                :: QFRZC   !refreezing rate of canopy liquid water (mm/s)\n  REAL                :: CANMAS  !total canopy mass (kg/m2)\n! --------------------------------------------------------------------\n! initialization\n\n      ECAN    = 0.0\n\n! --------------------------- liquid water ------------------------------\n! maximum canopy water\n\n      MAXLIQ =  parameters%CH2OP * (ELAI+ ESAI)\n\n! evaporation, transpiration, and dew\n\n      IF (.NOT.FROZEN_CANOPY) THEN             ! Barlage: change to frozen_canopy\n        ETRAN = MAX( FCTR/HVAP, 0. )\n        QEVAC = MAX( FCEV/HVAP, 0. )\n        QDEWC = ABS( MIN( FCEV/HVAP, 0. ) )\n        QSUBC = 0.\n        QFROC = 0.\n      ELSE\n        ETRAN = MAX( FCTR/HSUB, 0. )\n        QEVAC = 0.\n        QDEWC = 0.\n        QSUBC = MAX( FCEV/HSUB, 0. )\n        QFROC = ABS( MIN( FCEV/HSUB, 0. ) )\n      ENDIF\n\n! canopy water balance. for convenience allow dew to bring CANLIQ above\n! maxh2o or else would have to re-adjust drip\n\n       QEVAC = MIN(CANLIQ/DT,QEVAC)\n       CANLIQ=MAX(0.,CANLIQ+(QDEWC-QEVAC)*DT)\n       IF(CANLIQ <= 1.E-06) CANLIQ = 0.0\n\n! --------------------------- canopy ice ------------------------------\n! for canopy ice\n\n      MAXSNO = 6.6*(0.27+46./BDFALL) * (ELAI+ ESAI)\n\n      QSUBC = MIN(CANICE/DT,QSUBC)\n      CANICE= MAX(0.,CANICE + (QFROC-QSUBC)*DT)\n      IF(CANICE.LE.1.E-6) CANICE = 0.\n\n! wetted fraction of canopy\n\n      IF(CANICE.GT.0.) THEN\n           FWET = MAX(0.,CANICE) / MAX(MAXSNO,1.E-06)\n      ELSE\n           FWET = MAX(0.,CANLIQ) / MAX(MAXLIQ,1.E-06)\n      ENDIF\n      FWET = MIN(FWET, 1.) ** 0.667\n\n! phase change\n\n      QMELTC = 0.\n      QFRZC = 0.\n\n      IF(CANICE.GT.1.E-6.AND.TV.GT.TFRZ) THEN\n         QMELTC = MIN(CANICE/DT,(TV-TFRZ)*CICE*CANICE/DENICE/(DT*HFUS))\n         CANICE = MAX(0.,CANICE - QMELTC*DT)\n         CANLIQ = MAX(0.,CANLIQ + QMELTC*DT)\n         TV     = FWET*TFRZ + (1.-FWET)*TV\n      ENDIF\n\n      IF(CANLIQ.GT.1.E-6.AND.TV.LT.TFRZ) THEN\n         QFRZC  = MIN(CANLIQ/DT,(TFRZ-TV)*CWAT*CANLIQ/DENH2O/(DT*HFUS))\n         CANLIQ = MAX(0.,CANLIQ - QFRZC*DT)\n         CANICE = MAX(0.,CANICE + QFRZC*DT)\n         TV     = FWET*TFRZ + (1.-FWET)*TV\n      ENDIF\n\n! total canopy water\n\n      CMC = CANLIQ + CANICE\n\n! total canopy evaporation\n\n      ECAN = QEVAC + QSUBC - QDEWC - QFROC\n\n  END SUBROUTINE CANWATER\n\n!== begin snowwater ================================================================================\n\n  SUBROUTINE SNOWWATER (parameters,NSNOW  ,NSOIL  ,IMELT  ,DT     ,ZSOIL  , & !in\n                        SFCTMP ,SNOWHIN,QSNOW  ,QSNFRO ,QSNSUB , & !in\n                        QRAIN  ,FICEOLD,ILOC   ,JLOC   ,         & !in\n                        ISNOW  ,SNOWH  ,SNEQV  ,SNICE  ,SNLIQ  , & !inout\n                        SH2O   ,SICE   ,STC    ,ZSNSO  ,DZSNSO , & !inout\n                        QSNBOT ,SNOFLOW,PONDING1       ,PONDING2)  !out\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                         INTENT(IN)    :: ILOC   !grid index\n  INTEGER,                         INTENT(IN)    :: JLOC   !grid index\n  INTEGER,                         INTENT(IN)    :: NSNOW  !maximum no. of snow layers\n  INTEGER,                         INTENT(IN)    :: NSOIL  !no. of soil layers\n  INTEGER, DIMENSION(-NSNOW+1:0) , INTENT(IN)    :: IMELT  !melting state index [0-no melt;1-melt]\n  REAL,                            INTENT(IN)    :: DT     !time step (s)\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: ZSOIL  !depth of layer-bottom from soil surface\n  REAL,                            INTENT(IN)    :: SFCTMP !surface air temperature [k]\n  REAL,                            INTENT(IN)    :: SNOWHIN!snow depth increasing rate (m/s)\n  REAL,                            INTENT(IN)    :: QSNOW  !snow at ground srf (mm/s) [+]\n  REAL,                            INTENT(IN)    :: QSNFRO !snow surface frost rate[mm/s]\n  REAL,                            INTENT(IN)    :: QSNSUB !snow surface sublimation rate[mm/s]\n  REAL,                            INTENT(IN)    :: QRAIN  !snow surface rain rate[mm/s]\n  REAL, DIMENSION(-NSNOW+1:0)    , INTENT(IN)    :: FICEOLD!ice fraction at last timestep\n\n! input & output\n  INTEGER,                         INTENT(INOUT) :: ISNOW  !actual no. of snow layers\n  REAL,                            INTENT(INOUT) :: SNOWH  !snow height [m]\n  REAL,                            INTENT(INOUT) :: SNEQV  !snow water eqv. [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE  !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ  !snow layer liquid water [mm]\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O   !soil liquid moisture (m3/m3)\n  REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SICE   !soil ice moisture (m3/m3)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow layer temperature [k]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: ZSNSO  !depth of snow/soil layer-bottom\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO !snow/soil layer thickness [m]\n\n! output\n  REAL,                              INTENT(OUT) :: QSNBOT !melting water out of snow bottom [mm/s]\n  REAL,                              INTENT(OUT) :: SNOFLOW!glacier flow [mm]\n  REAL,                              INTENT(OUT) :: PONDING1\n  REAL,                              INTENT(OUT) :: PONDING2\n\n! local\n  INTEGER :: IZ,i\n  REAL    :: BDSNOW  !bulk density of snow (kg/m3)\n! ----------------------------------------------------------------------\n   SNOFLOW = 0.0\n   PONDING1 = 0.0\n   PONDING2 = 0.0\n\n   CALL SNOWFALL (parameters,NSOIL  ,NSNOW  ,DT     ,QSNOW  ,SNOWHIN, & !in\n                  SFCTMP ,ILOC   ,JLOC   ,                 & !in\n                  ISNOW  ,SNOWH  ,DZSNSO ,STC    ,SNICE  , & !inout\n                  SNLIQ  ,SNEQV  )                           !inout\n\n! MB: do each if block separately\n\n   IF(ISNOW < 0) &        ! when multi-layer\n   CALL  COMPACT (parameters,NSNOW  ,NSOIL  ,DT     ,STC    ,SNICE  , & !in\n                  SNLIQ  ,ZSOIL  ,IMELT  ,FICEOLD,ILOC   , JLOC ,& !in\n                  ISNOW  ,DZSNSO ,ZSNSO  )                   !inout\n\n   IF(ISNOW < 0) &        !when multi-layer\n   CALL  COMBINE (parameters,NSNOW  ,NSOIL  ,ILOC   ,JLOC   ,         & !in\n                  ISNOW  ,SH2O   ,STC    ,SNICE  ,SNLIQ  , & !inout\n                  DZSNSO ,SICE   ,SNOWH  ,SNEQV  ,         & !inout\n                  PONDING1       ,PONDING2)                  !out\n\n   IF(ISNOW < 0) &        !when multi-layer\n   CALL   DIVIDE (parameters,NSNOW  ,NSOIL  ,                         & !in\n                  ISNOW  ,STC    ,SNICE  ,SNLIQ  ,DZSNSO )   !inout\n\n   CALL  SNOWH2O (parameters,NSNOW  ,NSOIL  ,DT     ,QSNFRO ,QSNSUB , & !in\n                  QRAIN  ,ILOC   ,JLOC   ,                 & !in\n                  ISNOW  ,DZSNSO ,SNOWH  ,SNEQV  ,SNICE  , & !inout\n                  SNLIQ  ,SH2O   ,SICE   ,STC    ,         & !inout\n                  QSNBOT ,PONDING1       ,PONDING2)           !out\n\n!set empty snow layers to zero\n\n   do iz = -nsnow+1, isnow\n        snice(iz) = 0.\n        snliq(iz) = 0.\n        stc(iz)   = 0.\n        dzsnso(iz)= 0.\n        zsnso(iz) = 0.\n   enddo\n\n!to obtain equilibrium state of snow in glacier region\n\n   IF(SNEQV > parameters%SWE_LIMIT) THEN   ! 5000 mm -> maximum water depth\n      BDSNOW      = SNICE(0) / DZSNSO(0)\n      SNOFLOW     = (SNEQV - parameters%SWE_LIMIT)\n      SNICE(0)    = SNICE(0)  - SNOFLOW\n      DZSNSO(0)   = DZSNSO(0) - SNOFLOW/BDSNOW\n      SNOFLOW     = SNOFLOW / DT\n   END IF\n\n! sum up snow mass for layered snow\n\n   IF(ISNOW < 0) THEN  ! MB: only do for multi-layer\n       SNEQV = 0.\n       DO IZ = ISNOW+1,0\n             SNEQV = SNEQV + SNICE(IZ) + SNLIQ(IZ)\n       ENDDO\n   END IF\n\n! Reset ZSNSO and layer thinkness DZSNSO\n\n   DO IZ = ISNOW+1, 0\n        DZSNSO(IZ) = -DZSNSO(IZ)\n   END DO\n\n   DZSNSO(1) = ZSOIL(1)\n   DO IZ = 2,NSOIL\n        DZSNSO(IZ) = (ZSOIL(IZ) - ZSOIL(IZ-1))\n   END DO\n\n   ZSNSO(ISNOW+1) = DZSNSO(ISNOW+1)\n   DO IZ = ISNOW+2 ,NSOIL\n       ZSNSO(IZ) = ZSNSO(IZ-1) + DZSNSO(IZ)\n   ENDDO\n\n   DO IZ = ISNOW+1 ,NSOIL\n       DZSNSO(IZ) = -DZSNSO(IZ)\n   END DO\n\n  END SUBROUTINE SNOWWATER\n\n!== begin snowfall =================================================================================\n\n  SUBROUTINE SNOWFALL (parameters,NSOIL  ,NSNOW  ,DT     ,QSNOW  ,SNOWHIN , & !in\n                       SFCTMP ,ILOC   ,JLOC   ,                  & !in\n                       ISNOW  ,SNOWH  ,DZSNSO ,STC    ,SNICE   , & !inout\n                       SNLIQ  ,SNEQV  )                            !inout\n! ----------------------------------------------------------------------\n! snow depth and density to account for the new snowfall.\n! new values of snow depth & density returned.\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                            INTENT(IN) :: ILOC   !grid index\n  INTEGER,                            INTENT(IN) :: JLOC   !grid index\n  INTEGER,                            INTENT(IN) :: NSOIL  !no. of soil layers\n  INTEGER,                            INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  REAL,                               INTENT(IN) :: DT     !main time step (s)\n  REAL,                               INTENT(IN) :: QSNOW  !snow at ground srf (mm/s) [+]\n  REAL,                               INTENT(IN) :: SNOWHIN!snow depth increasing rate (m/s)\n  REAL,                               INTENT(IN) :: SFCTMP !surface air temperature [k]\n\n! input and output\n\n  INTEGER,                         INTENT(INOUT) :: ISNOW  !actual no. of snow layers\n  REAL,                            INTENT(INOUT) :: SNOWH  !snow depth [m]\n  REAL,                            INTENT(INOUT) :: SNEQV  !swow water equivalent [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO !thickness of snow/soil layers (m)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow layer temperature [k]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE  !snow layer ice [mm]\n  REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ  !snow layer liquid water [mm]\n\n! local\n\n  INTEGER :: NEWNODE            ! 0-no new layers, 1-creating new layers\n! ----------------------------------------------------------------------\n    NEWNODE  = 0\n\n! shallow snow / no layer\n\n    IF(ISNOW == 0 .and. QSNOW > 0.)  THEN\n      SNOWH = SNOWH + SNOWHIN * DT\n      SNEQV = SNEQV + QSNOW * DT\n    END IF\n\n! creating a new layer\n\n    IF(ISNOW == 0  .AND. QSNOW>0. .AND. SNOWH >= 0.025) THEN !MB: change limit\n!    IF(ISNOW == 0  .AND. QSNOW>0. .AND. SNOWH >= 0.05) THEN\n      ISNOW    = -1\n      NEWNODE  =  1\n      DZSNSO(0)= SNOWH\n      SNOWH    = 0.\n      STC(0)   = MIN(273.16, SFCTMP)   ! temporary setup\n      SNICE(0) = SNEQV\n      SNLIQ(0) = 0.\n    END IF\n\n! snow with layers\n\n    IF(ISNOW <  0 .AND. NEWNODE == 0 .AND. QSNOW > 0.) then\n         SNICE(ISNOW+1)  = SNICE(ISNOW+1)   + QSNOW   * DT\n         DZSNSO(ISNOW+1) = DZSNSO(ISNOW+1)  + SNOWHIN * DT\n    ENDIF\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SNOWFALL\n\n!== begin combine ==================================================================================\n\n  SUBROUTINE COMBINE (parameters,NSNOW  ,NSOIL  ,ILOC   ,JLOC   ,         & !in\n                      ISNOW  ,SH2O   ,STC    ,SNICE  ,SNLIQ  , & !inout\n                      DZSNSO ,SICE   ,SNOWH  ,SNEQV  ,         & !inout\n                      PONDING1       ,PONDING2)                  !out\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER, INTENT(IN)     :: ILOC\n    INTEGER, INTENT(IN)     :: JLOC\n    INTEGER, INTENT(IN)     :: NSNOW                        !maximum no. of snow layers\n    INTEGER, INTENT(IN)     :: NSOIL                        !no. of soil layers\n\n! input and output\n\n    INTEGER,                         INTENT(INOUT) :: ISNOW !actual no. of snow layers\n    REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O  !soil liquid moisture (m3/m3)\n    REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SICE  !soil ice moisture (m3/m3)\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC   !snow layer temperature [k]\n    REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE !snow layer ice [mm]\n    REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ !snow layer liquid water [mm]\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO!snow layer depth [m]\n    REAL,                            INTENT(INOUT) :: sneqv !snow water equivalent [m]\n    REAL,                            INTENT(INOUT) :: snowh !snow depth [m]\n    REAL,                            INTENT(OUT) :: PONDING1\n    REAL,                            INTENT(OUT) :: PONDING2\n\n! local variables:\n\n    INTEGER :: I,J,K,L               ! node indices\n    INTEGER :: ISNOW_OLD             ! number of top snow layer\n    INTEGER :: MSSI                  ! node index\n    INTEGER :: NEIBOR                ! adjacent node selected for combination\n    REAL    :: ZWICE                 ! total ice mass in snow\n    REAL    :: ZWLIQ                 ! total liquid water in snow\n\n    REAL    :: DZMIN(3)              ! minimum of top snow layer\n!    DATA DZMIN /0.045, 0.05, 0.2/\n    DATA DZMIN /0.025, 0.025, 0.1/  ! MB: change limit\n!-----------------------------------------------------------------------\n\n       ISNOW_OLD = ISNOW\n\n       DO J = ISNOW_OLD+1,0\n          IF (SNICE(J) <= .1) THEN\n             IF(J /= 0) THEN\n                SNLIQ(J+1) = SNLIQ(J+1) + SNLIQ(J)\n                SNICE(J+1) = SNICE(J+1) + SNICE(J)\n                DZSNSO(J+1) = DZSNSO(J+1) + DZSNSO(J)\n             ELSE\n               IF (ISNOW_OLD < -1) THEN    ! MB/KM: change to ISNOW\n                SNLIQ(J-1) = SNLIQ(J-1) + SNLIQ(J)\n                SNICE(J-1) = SNICE(J-1) + SNICE(J)\n                DZSNSO(J-1) = DZSNSO(J-1) + DZSNSO(J)\n               ELSE\n\t         IF(SNICE(J) >= 0.) THEN\n                  PONDING1 = SNLIQ(J)    ! ISNOW WILL GET SET TO ZERO BELOW; PONDING1 WILL GET\n                  SNEQV = SNICE(J)       ! ADDED TO PONDING FROM PHASECHANGE PONDING SHOULD BE\n                  SNOWH = DZSNSO(J)      ! ZERO HERE BECAUSE IT WAS CALCULATED FOR THIN SNOW\n\t\t ELSE   ! SNICE OVER-SUBLIMATED EARLIER\n\t\t  PONDING1 = SNLIQ(J) + SNICE(J)\n\t\t  IF(PONDING1 < 0.) THEN  ! IF SNICE AND SNLIQ SUBLIMATES REMOVE FROM SOIL\n\t\t   SICE(1) = MAX(0.0,SICE(1)+PONDING1/(DZSNSO(1)*1000.))\n                   PONDING1 = 0.0\n\t\t  END IF\n                  SNEQV = 0.0\n                  SNOWH = 0.0\n\t\t END IF\n                 SNLIQ(J) = 0.0\n                 SNICE(J) = 0.0\n                 DZSNSO(J) = 0.0\n               ENDIF\n!                SH2O(1) = SH2O(1)+SNLIQ(J)/(DZSNSO(1)*1000.)\n!                SICE(1) = SICE(1)+SNICE(J)/(DZSNSO(1)*1000.)\n             ENDIF\n\n             ! shift all elements above this down by one.\n             IF (J > ISNOW+1 .AND. ISNOW < -1) THEN\n                DO I = J, ISNOW+2, -1\n                   STC(I)   = STC(I-1)\n                   SNLIQ(I) = SNLIQ(I-1)\n                   SNICE(I) = SNICE(I-1)\n                   DZSNSO(I)= DZSNSO(I-1)\n                END DO\n             END IF\n             ISNOW = ISNOW + 1\n          END IF\n       END DO\n\n! to conserve water in case of too large surface sublimation\n\n       IF(SICE(1) < 0.) THEN\n          SH2O(1) = SH2O(1) + SICE(1)\n          SICE(1) = 0.\n       END IF\n\n       IF(ISNOW ==0) RETURN   ! MB: get out if no longer multi-layer\n\n       SNEQV  = 0.\n       SNOWH  = 0.\n       ZWICE  = 0.\n       ZWLIQ  = 0.\n\n       DO J = ISNOW+1,0\n             SNEQV = SNEQV + SNICE(J) + SNLIQ(J)\n             SNOWH = SNOWH + DZSNSO(J)\n             ZWICE = ZWICE + SNICE(J)\n             ZWLIQ = ZWLIQ + SNLIQ(J)\n       END DO\n\n! check the snow depth - all snow gone\n! the liquid water assumes ponding on soil surface.\n\n       IF (SNOWH < 0.025 .AND. ISNOW < 0 ) THEN ! MB: change limit\n!       IF (SNOWH < 0.05 .AND. ISNOW < 0 ) THEN\n          ISNOW  = 0\n          SNEQV = ZWICE\n          PONDING2 = ZWLIQ           ! LIMIT OF ISNOW < 0 MEANS INPUT PONDING\n          IF(SNEQV <= 0.) SNOWH = 0. ! SHOULD BE ZERO; SEE ABOVE\n       END IF\n\n!       IF (SNOWH < 0.05 ) THEN\n!          ISNOW  = 0\n!          SNEQV = ZWICE\n!          SH2O(1) = SH2O(1) + ZWLIQ / (DZSNSO(1) * 1000.)\n!          IF(SNEQV <= 0.) SNOWH = 0.\n!       END IF\n\n! check the snow depth - snow layers combined\n\n       IF (ISNOW < -1) THEN\n\n          ISNOW_OLD = ISNOW\n          MSSI     = 1\n\n          DO I = ISNOW_OLD+1,0\n             IF (DZSNSO(I) < DZMIN(MSSI)) THEN\n\n                IF (I == ISNOW+1) THEN\n                   NEIBOR = I + 1\n                ELSE IF (I == 0) THEN\n                   NEIBOR = I - 1\n                ELSE\n                   NEIBOR = I + 1\n                   IF ((DZSNSO(I-1)+DZSNSO(I)) < (DZSNSO(I+1)+DZSNSO(I))) NEIBOR = I-1\n                END IF\n\n                ! Node l and j are combined and stored as node j.\n                IF (NEIBOR > I) THEN\n                   J = NEIBOR\n                   L = I\n                ELSE\n                   J = I\n                   L = NEIBOR\n                END IF\n\n                CALL COMBO (parameters,DZSNSO(J), SNLIQ(J), SNICE(J), &\n                   STC(J), DZSNSO(L), SNLIQ(L), SNICE(L), STC(L) )\n\n                ! Now shift all elements above this down one.\n                IF (J-1 > ISNOW+1) THEN\n                   DO K = J-1, ISNOW+2, -1\n                      STC(K)   = STC(K-1)\n                      SNICE(K) = SNICE(K-1)\n                      SNLIQ(K) = SNLIQ(K-1)\n                      DZSNSO(K) = DZSNSO(K-1)\n                   END DO\n                END IF\n\n                ! Decrease the number of snow layers\n                ISNOW = ISNOW + 1\n                IF (ISNOW >= -1) EXIT\n             ELSE\n\n                ! The layer thickness is greater than the prescribed minimum value\n                MSSI = MSSI + 1\n\n             END IF\n          END DO\n\n       END IF\n\n  END SUBROUTINE COMBINE\n\n!== begin divide ===================================================================================\n\n  SUBROUTINE DIVIDE (parameters,NSNOW  ,NSOIL  ,                         & !in\n                     ISNOW  ,STC    ,SNICE  ,SNLIQ  ,DZSNSO  )  !inout\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER, INTENT(IN)                            :: NSNOW !maximum no. of snow layers [ =3]\n    INTEGER, INTENT(IN)                            :: NSOIL !no. of soil layers [ =4]\n\n! input and output\n\n    INTEGER                        , INTENT(INOUT) :: ISNOW !actual no. of snow layers\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC   !snow layer temperature [k]\n    REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNICE !snow layer ice [mm]\n    REAL, DIMENSION(-NSNOW+1:    0), INTENT(INOUT) :: SNLIQ !snow layer liquid water [mm]\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO!snow layer depth [m]\n\n! local variables:\n\n    INTEGER                                        :: J     !indices\n    INTEGER                                        :: MSNO  !number of layer (top) to MSNO (bot)\n    REAL                                           :: DRR   !thickness of the combined [m]\n    REAL, DIMENSION(       1:NSNOW)                :: DZ    !snow layer thickness [m]\n    REAL, DIMENSION(       1:NSNOW)                :: SWICE !partial volume of ice [m3/m3]\n    REAL, DIMENSION(       1:NSNOW)                :: SWLIQ !partial volume of liquid water [m3/m3]\n    REAL, DIMENSION(       1:NSNOW)                :: TSNO  !node temperature [k]\n    REAL                                           :: ZWICE !temporary\n    REAL                                           :: ZWLIQ !temporary\n    REAL                                           :: PROPOR!temporary\n    REAL                                           :: DTDZ  !temporary\n! ----------------------------------------------------------------------\n\n    DO J = 1,NSNOW\n          IF (J <= ABS(ISNOW)) THEN\n             DZ(J)    = DZSNSO(J+ISNOW)\n             SWICE(J) = SNICE(J+ISNOW)\n             SWLIQ(J) = SNLIQ(J+ISNOW)\n             TSNO(J)  = STC(J+ISNOW)\n          END IF\n    END DO\n\n       MSNO = ABS(ISNOW)\n\n       IF (MSNO == 1) THEN\n          ! Specify a new snow layer\n          IF (DZ(1) > 0.05) THEN\n             MSNO = 2\n             DZ(1)    = DZ(1)/2.\n             SWICE(1) = SWICE(1)/2.\n             SWLIQ(1) = SWLIQ(1)/2.\n             DZ(2)    = DZ(1)\n             SWICE(2) = SWICE(1)\n             SWLIQ(2) = SWLIQ(1)\n             TSNO(2)  = TSNO(1)\n          END IF\n       END IF\n\n       IF (MSNO > 1) THEN\n          IF (DZ(1) > 0.05) THEN\n             DRR      = DZ(1) - 0.05\n             PROPOR   = DRR/DZ(1)\n             ZWICE    = PROPOR*SWICE(1)\n             ZWLIQ    = PROPOR*SWLIQ(1)\n             PROPOR   = 0.05/DZ(1)\n             SWICE(1) = PROPOR*SWICE(1)\n             SWLIQ(1) = PROPOR*SWLIQ(1)\n             DZ(1)    = 0.05\n\n             CALL COMBO (parameters,DZ(2), SWLIQ(2), SWICE(2), TSNO(2), DRR, &\n                  ZWLIQ, ZWICE, TSNO(1))\n\n             ! subdivide a new layer\n             IF (MSNO <= 2 .AND. DZ(2) > 0.20) THEN  ! MB: change limit\n!             IF (MSNO <= 2 .AND. DZ(2) > 0.10) THEN\n                MSNO = 3\n                DTDZ = (TSNO(1) - TSNO(2))/((DZ(1)+DZ(2))/2.)\n                DZ(2)    = DZ(2)/2.\n                SWICE(2) = SWICE(2)/2.\n                SWLIQ(2) = SWLIQ(2)/2.\n                DZ(3)    = DZ(2)\n                SWICE(3) = SWICE(2)\n                SWLIQ(3) = SWLIQ(2)\n                TSNO(3) = TSNO(2) - DTDZ*DZ(2)/2.\n                IF (TSNO(3) >= TFRZ) THEN\n                   TSNO(3)  = TSNO(2)\n                ELSE\n                   TSNO(2) = TSNO(2) + DTDZ*DZ(2)/2.\n                ENDIF\n\n             END IF\n          END IF\n       END IF\n\n       IF (MSNO > 2) THEN\n          IF (DZ(2) > 0.2) THEN\n             DRR = DZ(2) - 0.2\n             PROPOR   = DRR/DZ(2)\n             ZWICE    = PROPOR*SWICE(2)\n             ZWLIQ    = PROPOR*SWLIQ(2)\n             PROPOR   = 0.2/DZ(2)\n             SWICE(2) = PROPOR*SWICE(2)\n             SWLIQ(2) = PROPOR*SWLIQ(2)\n             DZ(2)    = 0.2\n             CALL COMBO (parameters,DZ(3), SWLIQ(3), SWICE(3), TSNO(3), DRR, &\n                  ZWLIQ, ZWICE, TSNO(2))\n          END IF\n       END IF\n\n       ISNOW = -MSNO\n\n    DO J = ISNOW+1,0\n             DZSNSO(J) = DZ(J-ISNOW)\n             SNICE(J) = SWICE(J-ISNOW)\n             SNLIQ(J) = SWLIQ(J-ISNOW)\n             STC(J)   = TSNO(J-ISNOW)\n    END DO\n\n\n!    DO J = ISNOW+1,NSOIL\n!    WRITE(*,'(I5,7F10.3)') J, DZSNSO(J), SNICE(J), SNLIQ(J),STC(J)\n!    END DO\n\n  END SUBROUTINE DIVIDE\n\n!== begin combo ====================================================================================\n\n  SUBROUTINE COMBO(parameters,DZ,  WLIQ,  WICE, T, DZ2, WLIQ2, WICE2, T2)\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n\n! ----------------------------------------------------------------------s\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n    REAL, INTENT(IN)    :: DZ2   !nodal thickness of 2 elements being combined [m]\n    REAL, INTENT(IN)    :: WLIQ2 !liquid water of element 2 [kg/m2]\n    REAL, INTENT(IN)    :: WICE2 !ice of element 2 [kg/m2]\n    REAL, INTENT(IN)    :: T2    !nodal temperature of element 2 [k]\n    REAL, INTENT(INOUT) :: DZ    !nodal thickness of 1 elements being combined [m]\n    REAL, INTENT(INOUT) :: WLIQ  !liquid water of element 1\n    REAL, INTENT(INOUT) :: WICE  !ice of element 1 [kg/m2]\n    REAL, INTENT(INOUT) :: T     !node temperature of element 1 [k]\n\n! local\n\n    REAL                :: DZC   !total thickness of nodes 1 and 2 (DZC=DZ+DZ2).\n    REAL                :: WLIQC !combined liquid water [kg/m2]\n    REAL                :: WICEC !combined ice [kg/m2]\n    REAL                :: TC    !combined node temperature [k]\n    REAL                :: H     !enthalpy of element 1 [J/m2]\n    REAL                :: H2    !enthalpy of element 2 [J/m2]\n    REAL                :: HC    !temporary\n\n!-----------------------------------------------------------------------\n\n    DZC = DZ+DZ2\n    WICEC = (WICE+WICE2)\n    WLIQC = (WLIQ+WLIQ2)\n    H = (CICE*WICE+CWAT*WLIQ) * (T-TFRZ)+HFUS*WLIQ\n    H2= (CICE*WICE2+CWAT*WLIQ2) * (T2-TFRZ)+HFUS*WLIQ2\n\n    HC = H + H2\n    IF(HC < 0.)THEN\n       TC = TFRZ + HC/(CICE*WICEC + CWAT*WLIQC)\n    ELSE IF (HC.LE.HFUS*WLIQC) THEN\n       TC = TFRZ\n    ELSE\n       TC = TFRZ + (HC - HFUS*WLIQC) / (CICE*WICEC + CWAT*WLIQC)\n    END IF\n\n    DZ = DZC\n    WICE = WICEC\n    WLIQ = WLIQC\n    T = TC\n\n  END SUBROUTINE COMBO\n\n!== begin compact ==================================================================================\n\n  SUBROUTINE COMPACT (parameters,NSNOW  ,NSOIL  ,DT     ,STC    ,SNICE  , & !in\n                      SNLIQ  ,ZSOIL  ,IMELT  ,FICEOLD,ILOC   , JLOC , & !in\n                      ISNOW  ,DZSNSO ,ZSNSO )                    !inout\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n   INTEGER,                         INTENT(IN)    :: ILOC   !grid index\n   INTEGER,                         INTENT(IN)    :: JLOC   !grid index\n   INTEGER,                         INTENT(IN)    :: NSOIL  !no. of soil layers [ =4]\n   INTEGER,                         INTENT(IN)    :: NSNOW  !maximum no. of snow layers [ =3]\n   INTEGER, DIMENSION(-NSNOW+1:0) , INTENT(IN)    :: IMELT  !melting state index [0-no melt;1-melt]\n   REAL,                            INTENT(IN)    :: DT     !time step (sec)\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN)    :: STC    !snow layer temperature [k]\n   REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: SNICE  !snow layer ice [mm]\n   REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: SNLIQ  !snow layer liquid water [mm]\n   REAL, DIMENSION(       1:NSOIL), INTENT(IN)    :: ZSOIL  !depth of layer-bottom from soil srf\n   REAL, DIMENSION(-NSNOW+1:    0), INTENT(IN)    :: FICEOLD!ice fraction at last timestep\n\n! input and output\n   INTEGER,                         INTENT(INOUT) :: ISNOW  ! actual no. of snow layers\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO ! snow layer thickness [m]\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: ZSNSO  ! depth of snow/soil layer-bottom\n\n! local\n   REAL, PARAMETER     :: C2 = 21.e-3   ![m3/kg] ! default 21.e-3\n   REAL, PARAMETER     :: C3 = 2.5e-6   ![1/s]\n   REAL, PARAMETER     :: C4 = 0.04     ![1/k]\n   REAL, PARAMETER     :: C5 = 2.0      !\n   REAL, PARAMETER     :: DM = 100.0    !upper Limit on destructive metamorphism compaction [kg/m3]\n   REAL, PARAMETER     :: ETA0 = 0.8e+6 !viscosity coefficient [kg-s/m2]\n                                        !according to Anderson, it is between 0.52e6~1.38e6\n   REAL :: BURDEN !pressure of overlying snow [kg/m2]\n   REAL :: DDZ1   !rate of settling of snow pack due to destructive metamorphism.\n   REAL :: DDZ2   !rate of compaction of snow pack due to overburden.\n   REAL :: DDZ3   !rate of compaction of snow pack due to melt [1/s]\n   REAL :: DEXPF  !EXPF=exp(-c4*(273.15-STC)).\n   REAL :: TD     !STC - TFRZ [K]\n   REAL :: PDZDTC !nodal rate of change in fractional-thickness due to compaction [fraction/s]\n   REAL :: VOID   !void (1 - SNICE - SNLIQ)\n   REAL :: WX     !water mass (ice + liquid) [kg/m2]\n   REAL :: BI     !partial density of ice [kg/m3]\n   REAL, DIMENSION(-NSNOW+1:0) :: FICE   !fraction of ice at current time step\n\n   INTEGER  :: J\n\n! ----------------------------------------------------------------------\n    BURDEN = 0.0\n\n    DO J = ISNOW+1, 0\n\n        WX      = SNICE(J) + SNLIQ(J)\n        FICE(J) = SNICE(J) / WX\n        VOID    = 1. - (SNICE(J)/DENICE + SNLIQ(J)/DENH2O) / DZSNSO(J)\n\n        ! Allow compaction only for non-saturated node and higher ice lens node.\n        IF (VOID > 0.001 .AND. SNICE(J) > 0.1) THEN\n           BI = SNICE(J) / DZSNSO(J)\n           TD = MAX(0.,TFRZ-STC(J))\n           DEXPF = EXP(-C4*TD)\n\n           ! Settling as a result of destructive metamorphism\n\n           DDZ1 = -C3*DEXPF\n\n           IF (BI > DM) DDZ1 = DDZ1*EXP(-46.0E-3*(BI-DM))\n\n           ! Liquid water term\n\n           IF (SNLIQ(J) > 0.01*DZSNSO(J)) DDZ1=DDZ1*C5\n\n           ! Compaction due to overburden\n\n           DDZ2 = -(BURDEN+0.5*WX)*EXP(-0.08*TD-C2*BI)/ETA0 ! 0.5*WX -> self-burden\n\n           ! Compaction occurring during melt\n\n           IF (IMELT(J) == 1) THEN\n              DDZ3 = MAX(0.,(FICEOLD(J) - FICE(J))/MAX(1.E-6,FICEOLD(J)))\n              DDZ3 = - DDZ3/DT           ! sometimes too large\n           ELSE\n              DDZ3 = 0.\n           END IF\n\n           ! Time rate of fractional change in DZ (units of s-1)\n\n           PDZDTC = (DDZ1 + DDZ2 + DDZ3)*DT\n           PDZDTC = MAX(-0.5,PDZDTC)\n\n           ! The change in DZ due to compaction\n\n           DZSNSO(J) = DZSNSO(J)*(1.+PDZDTC)\n           DZSNSO(J) = max(DZSNSO(J),SNICE(J)/DENICE + SNLIQ(J)/DENH2O)\n        END IF\n\n        ! Pressure of overlying snow\n\n        BURDEN = BURDEN + WX\n\n    END DO\n\n  END SUBROUTINE COMPACT\n\n!== begin snowh2o ==================================================================================\n\n  SUBROUTINE SNOWH2O (parameters,NSNOW  ,NSOIL  ,DT     ,QSNFRO ,QSNSUB , & !in\n                      QRAIN  ,ILOC   ,JLOC   ,                 & !in\n                      ISNOW  ,DZSNSO ,SNOWH  ,SNEQV  ,SNICE  , & !inout\n                      SNLIQ  ,SH2O   ,SICE   ,STC    ,         & !inout\n                      QSNBOT ,PONDING1       ,PONDING2)          !out\n! ----------------------------------------------------------------------\n! Renew the mass of ice lens (SNICE) and liquid (SNLIQ) of the\n! surface snow layer resulting from sublimation (frost) / evaporation (dew)\n! ----------------------------------------------------------------------\n   IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n   INTEGER,                         INTENT(IN)    :: ILOC   !grid index\n   INTEGER,                         INTENT(IN)    :: JLOC   !grid index\n   INTEGER,                         INTENT(IN)    :: NSNOW  !maximum no. of snow layers[=3]\n   INTEGER,                         INTENT(IN)    :: NSOIL  !No. of soil layers[=4]\n   REAL,                            INTENT(IN)    :: DT     !time step\n   REAL,                            INTENT(IN)    :: QSNFRO !snow surface frost rate[mm/s]\n   REAL,                            INTENT(IN)    :: QSNSUB !snow surface sublimation rate[mm/s]\n   REAL,                            INTENT(IN)    :: QRAIN  !snow surface rain rate[mm/s]\n\n! output\n\n   REAL,                            INTENT(OUT)   :: QSNBOT !melting water out of snow bottom [mm/s]\n\n! input and output\n\n   INTEGER,                         INTENT(INOUT) :: ISNOW  !actual no. of snow layers\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: DZSNSO ! snow layer depth [m]\n   REAL,                            INTENT(INOUT) :: SNOWH  !snow height [m]\n   REAL,                            INTENT(INOUT) :: SNEQV  !snow water eqv. [mm]\n   REAL, DIMENSION(-NSNOW+1:0),     INTENT(INOUT) :: SNICE  !snow layer ice [mm]\n   REAL, DIMENSION(-NSNOW+1:0),     INTENT(INOUT) :: SNLIQ  !snow layer liquid water [mm]\n   REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SH2O   !soil liquid moisture (m3/m3)\n   REAL, DIMENSION(       1:NSOIL), INTENT(INOUT) :: SICE   !soil ice moisture (m3/m3)\n   REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(INOUT) :: STC    !snow layer temperature [k]\n\n! local variables:\n\n   INTEGER                     :: J         !do loop/array indices\n   REAL                        :: QIN       !water flow into the element (mm/s)\n   REAL                        :: QOUT      !water flow out of the element (mm/s)\n   REAL                        :: WGDIF     !ice mass after minus sublimation\n   REAL, DIMENSION(-NSNOW+1:0) :: VOL_LIQ   !partial volume of liquid water in layer\n   REAL, DIMENSION(-NSNOW+1:0) :: VOL_ICE   !partial volume of ice lens in layer\n   REAL, DIMENSION(-NSNOW+1:0) :: EPORE     !effective porosity = porosity - VOL_ICE\n   REAL :: PROPOR, TEMP\n   REAL :: PONDING1, PONDING2\n   REAL, PARAMETER :: max_liq_mass_fraction = 0.4\n! ----------------------------------------------------------------------\n\n!for the case when SNEQV becomes '0' after 'COMBINE'\n\n   IF(SNEQV == 0.) THEN\n      SICE(1) =  SICE(1) + (QSNFRO-QSNSUB)*DT/(DZSNSO(1)*1000.)  ! Barlage: SH2O->SICE v3.6\n      IF(SICE(1) < 0.) THEN\n         SH2O(1) = SH2O(1) + SICE(1)\n         SICE(1) = 0.\n      END IF\n   END IF\n\n! for shallow snow without a layer\n! snow surface sublimation may be larger than existing snow mass. To conserve water,\n! excessive sublimation is used to reduce soil water. Smaller time steps would tend\n! to aviod this problem.\n\n   IF(ISNOW == 0 .and. SNEQV > 0.) THEN\n      TEMP   = SNEQV\n      SNEQV  = SNEQV - QSNSUB*DT + QSNFRO*DT\n      PROPOR = SNEQV/TEMP\n      SNOWH  = MAX(0.,PROPOR * SNOWH)\n      SNOWH  = MIN(MAX(SNOWH,SNEQV/500.0),SNEQV/50.0)  ! limit adjustment to a reasonable density\n\n      IF(SNEQV < 0.) THEN\n         SICE(1) = SICE(1) + SNEQV/(DZSNSO(1)*1000.)\n         SNEQV   = 0.\n         SNOWH   = 0.\n      END IF\n      IF(SICE(1) < 0.) THEN\n         SH2O(1) = SH2O(1) + SICE(1)\n         SICE(1) = 0.\n      END IF\n   END IF\n\n   IF(SNOWH <= 1.E-8 .OR. SNEQV <= 1.E-6) THEN\n     SNOWH = 0.0\n     SNEQV = 0.0\n   END IF\n\n! for deep snow\n\n   IF ( ISNOW < 0 ) THEN !KWM added this IF statement to prevent out-of-bounds array references\n\n      WGDIF = SNICE(ISNOW+1) - QSNSUB*DT + QSNFRO*DT\n      SNICE(ISNOW+1) = WGDIF\n      IF (WGDIF < 1.e-6 .and. ISNOW <0) THEN\n         CALL  COMBINE (parameters,NSNOW  ,NSOIL  ,ILOC, JLOC   , & !in\n              ISNOW  ,SH2O   ,STC    ,SNICE  ,SNLIQ  , & !inout\n              DZSNSO ,SICE   ,SNOWH  ,SNEQV  ,         & !inout\n              PONDING1, PONDING2 )                       !out\n      ENDIF\n      !KWM:  Subroutine COMBINE can change ISNOW to make it 0 again?\n      IF ( ISNOW < 0 ) THEN !KWM added this IF statement to prevent out-of-bounds array references\n         SNLIQ(ISNOW+1) = SNLIQ(ISNOW+1) + QRAIN * DT\n         SNLIQ(ISNOW+1) = MAX(0., SNLIQ(ISNOW+1))\n      ENDIF\n\n   ENDIF !KWM  -- Can the ENDIF be moved toward the end of the subroutine (Just set QSNBOT=0)?\n\n! Porosity and partial volume\n\n   DO J = ISNOW+1, 0\n     VOL_ICE(J)      = MIN(1., SNICE(J)/(DZSNSO(J)*DENICE))\n     EPORE(J)        = 1. - VOL_ICE(J)\n   END DO\n\n   QIN = 0.\n   QOUT = 0.\n\n   DO J = ISNOW+1, 0\n     SNLIQ(J) = SNLIQ(J) + QIN\n     VOL_LIQ(J) = SNLIQ(J)/(DZSNSO(J)*DENH2O)\n     QOUT = MAX(0.,(VOL_LIQ(J)-parameters%SSI*EPORE(J))*DZSNSO(J))\n     IF(J == 0) THEN\n       QOUT = MAX((VOL_LIQ(J)- EPORE(J))*DZSNSO(J) , parameters%SNOW_RET_FAC*DT*QOUT)\n     END IF\n     QOUT = QOUT*DENH2O\n     SNLIQ(J) = SNLIQ(J) - QOUT\n     IF((SNLIQ(J)/(SNICE(J)+SNLIQ(J))) > max_liq_mass_fraction) THEN\n       QOUT = QOUT + (SNLIQ(J) - max_liq_mass_fraction/(1.0 - max_liq_mass_fraction)*SNICE(J))\n       SNLIQ(J) = max_liq_mass_fraction/(1.0 - max_liq_mass_fraction)*SNICE(J)\n     ENDIF\n     QIN = QOUT\n   END DO\n\n   DO J = ISNOW+1, 0\n     DZSNSO(J) = MAX(DZSNSO(J),SNLIQ(J)/DENH2O + SNICE(J)/DENICE)\n   END DO\n\n! Liquid water from snow bottom to soil\n\n   QSNBOT = QOUT / DT           ! mm/s\n\n  END SUBROUTINE SNOWH2O\n\n!== begin soilwater ================================================================================\n\n  SUBROUTINE SOILWATER (parameters,NSOIL  ,NSNOW  ,DT     ,ZSOIL  ,DZSNSO , & !in\n                        QINSUR ,QSEVA  ,ETRANI ,SICE   ,ILOC   , JLOC, & !in\n                        SH2O   ,SMC    ,ZWT    ,VEGTYP ,& !inout\n                        SMCWTD, DEEPRECH                       ,& !inout\n                        RUNSRF ,QDRAIN ,RUNSUB ,WCND   ,FCRMAX )   !out\n\n! ----------------------------------------------------------------------\n! calculate surface runoff and soil moisture.\n! ----------------------------------------------------------------------\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                     INTENT(IN) :: ILOC   !grid index\n  INTEGER,                     INTENT(IN) :: JLOC   !grid index\n  INTEGER,                     INTENT(IN) :: NSOIL  !no. of soil layers\n  INTEGER,                     INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  REAL,                        INTENT(IN) :: DT     !time step (sec)\n  REAL, INTENT(IN)                        :: QINSUR !water input on soil surface [mm/s]\n  REAL, INTENT(IN)                        :: QSEVA  !evap from soil surface [mm/s]\n  REAL, DIMENSION(1:NSOIL),    INTENT(IN) :: ZSOIL  !depth of soil layer-bottom [m]\n  REAL, DIMENSION(1:NSOIL),    INTENT(IN) :: ETRANI !evapotranspiration from soil layers [mm/s]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !snow/soil layer depth [m]\n  REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: SICE   !soil ice content [m3/m3]\n\n  INTEGER,                     INTENT(IN) :: VEGTYP\n\n! input & output\n  REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SH2O   !soil liquid water content [m3/m3]\n  REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SMC    !total soil water content [m3/m3]\n  REAL, INTENT(INOUT)                     :: ZWT    !water table depth [m]\n  REAL,                     INTENT(INOUT) :: SMCWTD !soil moisture between bottom of the soil and the water table [m3/m3]\n  REAL                    , INTENT(INOUT) :: DEEPRECH\n\n! output\n  REAL, INTENT(OUT)                       :: QDRAIN !soil-bottom free drainage [mm/s]\n  REAL, INTENT(OUT)                       :: RUNSRF !surface runoff [mm/s]\n  REAL, INTENT(OUT)                       :: RUNSUB !subsurface runoff [mm/s]\n  REAL, INTENT(OUT)                       :: FCRMAX !maximum of FCR (-)\n  REAL, DIMENSION(1:NSOIL), INTENT(OUT)   :: WCND   !hydraulic conductivity (m/s)\n\n! local\n  INTEGER                                 :: K,IZ   !do-loop index\n  INTEGER                                 :: ITER   !iteration index\n  REAl                                    :: DTFINE !fine time step (s)\n  REAL, DIMENSION(1:NSOIL)                :: RHSTT  !right-hand side term of the matrix\n  REAL, DIMENSION(1:NSOIL)                :: AI     !left-hand side term\n  REAL, DIMENSION(1:NSOIL)                :: BI     !left-hand side term\n  REAL, DIMENSION(1:NSOIL)                :: CI     !left-hand side term\n\n  REAL                                    :: FFF    !runoff decay factor (m-1)\n  REAL                                    :: RSBMX  !baseflow coefficient [mm/s]\n  REAL                                    :: PDDUM  !infiltration rate at surface (m/s)\n  REAL                                    :: FICE   !ice fraction in frozen soil\n  REAL                                    :: WPLUS  !saturation excess of the total soil [m]\n  REAL                                    :: RSAT   !accumulation of WPLUS (saturation excess) [m]\n  REAL                                    :: SICEMAX!maximum soil ice content (m3/m3)\n  REAL                                    :: SH2OMIN!minimum soil liquid water content (m3/m3)\n  REAL                                    :: WTSUB  !sum of WCND(K)*DZSNSO(K)\n  REAL                                    :: MH2O   !water mass removal (mm)\n  REAL                                    :: FSAT   !fractional saturated area (-)\n  REAL, DIMENSION(1:NSOIL)                :: MLIQ   !\n  REAL                                    :: XS     !\n  REAL                                    :: WATMIN !\n  REAL                                    :: QDRAIN_SAVE !\n  REAL                                    :: RUNSRF_SAVE !\n  REAL                                    :: EPORE  !effective porosity [m3/m3]\n  REAL, DIMENSION(1:NSOIL)                :: FCR    !impermeable fraction due to frozen soil\n  INTEGER                                 :: NITER  !iteration times soil moisture (-)\n  REAL                                    :: SMCTOT !2-m averaged soil moisture (m3/m3)\n  REAL                                    :: DZTOT  !2-m soil depth (m)\n  REAL, PARAMETER :: A = 4.0\n\n  REAL                                    :: imperv_eff !local impervious adjustment (fraction, 0-1)\n  REAL                                    :: WMINUS !subsurface deficit [m]\n  REAL                                    :: SUBDEF !accumulation of subsurface deficit [m]\n\n! ----------------------------------------------------------------------\n    RUNSRF = 0.0\n    PDDUM  = 0.0\n    RSAT   = 0.0\n    SUBDEF = 0.0\n    WMINUS = 0.0\n\n! for the case when snowmelt water is too large\n\n    DO K = 1,NSOIL\n       EPORE   = MAX ( 1.E-4 , ( parameters%SMCMAX(K) - SICE(K) ) )\n       RSAT    = RSAT + MAX(0.,SH2O(K)-EPORE)*DZSNSO(K)\n       SH2O(K) = MIN(EPORE,SH2O(K))\n    END DO\n\n!impermeable fraction due to frozen soil\n\n    DO K = 1,NSOIL\n       FICE    = MIN(1.0,SICE(K)/parameters%SMCMAX(K))\n       FCR(K)  = MAX(0.0,EXP(-A*(1.-FICE))- EXP(-A)) /  &\n                        (1.0              - EXP(-A))\n    END DO\n\n! maximum soil ice content and minimum liquid water of all layers\n\n    SICEMAX = 0.0\n    FCRMAX  = 0.0\n    SH2OMIN = parameters%SMCMAX(1)\n    DO K = 1,NSOIL\n       IF (SICE(K) > SICEMAX) SICEMAX = SICE(K)\n       IF (FCR(K)  > FCRMAX)  FCRMAX  = FCR(K)\n       IF (SH2O(K) < SH2OMIN) SH2OMIN = SH2O(K)\n    END DO\n\n!subsurface runoff for runoff scheme option 2\n\n    IF(OPT_RUN == 2) THEN\n        FFF   = 2.0\n        RSBMX = 4.0\n        CALL ZWTEQ (parameters,NSOIL  ,NSNOW  ,ZSOIL  ,DZSNSO ,SH2O   ,ZWT)\n        RUNSUB = (1.0-FCRMAX) * RSBMX * EXP(-parameters%TIMEAN) * EXP(-FFF*ZWT)   ! mm/s\n    END IF\n\n!surface runoff and infiltration rate using different schemes\n\n!jref impermable surface at urban\n! We are updating surface runoff adjustment as an area-mean\n! of impervious and frozen soil impermeable adjustments.\n    IF (OPT_IMPERV == 1) THEN\n       ! Use total imperviousness\n       imperv_eff = parameters%imperv\n       FCR(1) = imperv_eff + (1.0 - imperv_eff) * FCR(1)\n    ELSE IF (OPT_IMPERV == 2) THEN\n       ! Effective imperviousness from Alley & Veenhuis\n       imperv_eff = 0.0015 * ( (100. * parameters%imperv)**1.41 )\n       FCR(1) = imperv_eff + (1.0 - imperv_eff) * FCR(1)\n    ELSE IF (OPT_IMPERV == 9) THEN\n       ! Fixed value for urban type (older configuration)\n       IF ( parameters%urban_flag ) FCR(1)=0.95\n    END IF\n\n    IF(OPT_RUN == 1) THEN\n       FFF = 6.0\n       FSAT   = parameters%FSATMX*EXP(-0.5*FFF*(ZWT-2.0))\n       IF(QINSUR > 0.) THEN\n         RUNSRF = QINSUR * ( (1.0-FCR(1))*FSAT + FCR(1) )\n         PDDUM  = QINSUR - RUNSRF                          ! m/s\n       END IF\n    END IF\n\n    IF(OPT_RUN == 5) THEN\n       FFF = 6.0\n       FSAT   = parameters%FSATMX*EXP(-0.5*FFF*MAX(-2.0-ZWT,0.))\n       IF(QINSUR > 0.) THEN\n         RUNSRF = QINSUR * ( (1.0-FCR(1))*FSAT + FCR(1) )\n         PDDUM  = QINSUR - RUNSRF                          ! m/s\n       END IF\n    END IF\n\n    IF(OPT_RUN == 2) THEN\n       FFF   = 2.0\n       FSAT   = parameters%FSATMX*EXP(-0.5*FFF*ZWT)\n       IF(QINSUR > 0.) THEN\n         RUNSRF = QINSUR * ( (1.0-FCR(1))*FSAT + FCR(1) )\n         PDDUM  = QINSUR - RUNSRF                          ! m/s\n       END IF\n    END IF\n\n    IF(OPT_RUN == 3) THEN\n       CALL INFIL (parameters,NSOIL  ,DT     ,ZSOIL  ,SH2O   ,SICE   , & !in\n                   SICEMAX,QINSUR ,                         & !in\n                   PDDUM  ,RUNSRF )                           !out\n    END IF\n\n    IF(OPT_RUN == 4) THEN\n       SMCTOT = 0.\n       DZTOT  = 0.\n       DO K = 1,NSOIL\n          DZTOT   = DZTOT  + DZSNSO(K)\n          SMCTOT  = SMCTOT + SMC(K)/parameters%SMCMAX(K)*DZSNSO(K)\n          IF(DZTOT >= 2.0) EXIT\n       END DO\n       SMCTOT = SMCTOT/DZTOT\n       FSAT   = MAX(0.01,SMCTOT) ** 4.        !BATS\n\n       IF(QINSUR > 0.) THEN\n         RUNSRF = QINSUR * ((1.0-FCR(1))*FSAT+FCR(1))\n         PDDUM  = QINSUR - RUNSRF                       ! m/s\n       END IF\n    END IF\n    IF (OPT_RUN == 7) THEN\n      CALL COMPUTE_XAJ_SURFRUNOFF(parameters,DT,FCR,NSOIL,SMC,ZSOIL,QINSUR,RUNSRF,PDDUM)\n    END IF\n! determine iteration times and finer time step\n\n    NITER = 1\n\n!    IF(OPT_INF == 1) THEN    !OPT_INF =2 may cause water imbalance\n       NITER = 3\n       IF (PDDUM*DT>DZSNSO(1)*parameters%SMCMAX(1) ) THEN\n          NITER = NITER*2\n       END IF\n!    END IF\n\n    DTFINE  = DT / NITER\n\n! solve soil moisture\n\n    QDRAIN_SAVE = 0.0\n    RUNSRF_SAVE = 0.0\n    DO ITER = 1, NITER\n       IF(QINSUR > 0. .and. OPT_RUN == 3) THEN\n          CALL INFIL (parameters,NSOIL  ,DTFINE     ,ZSOIL  ,SH2O   ,SICE   , & !in\n                      SICEMAX,QINSUR ,                         & !in\n                      PDDUM  ,RUNSRF )                           !out\n       END IF\n\n       IF (QINSUR > 0. .AND. OPT_RUN == 7) THEN\n          CALL COMPUTE_XAJ_SURFRUNOFF(parameters,DTFINE,FCR,NSOIL,SMC,ZSOIL,QINSUR,& ! in\n                                      RUNSRF,PDDUM)                                  ! out\n       END IF\n\n       CALL SRT   (parameters,NSOIL  ,ZSOIL  ,DTFINE ,PDDUM  ,ETRANI , & !in\n                   QSEVA  ,SH2O   ,SMC    ,ZWT    ,FCR    , & !in\n                   SICEMAX,FCRMAX ,ILOC   ,JLOC   ,SMCWTD ,         & !in\n                   RHSTT  ,AI     ,BI     ,CI     ,QDRAIN , & !out\n                   WCND   )                                   !out\n\n       CALL SSTEP (parameters,NSOIL  ,NSNOW  ,DTFINE ,ZSOIL  ,DZSNSO , & !in\n                   SICE   ,ILOC   ,JLOC   ,ZWT            ,                 & !in\n                   SH2O   ,SMC    ,AI     ,BI     ,CI     , & !inout\n                   RHSTT  ,SMCWTD ,QDRAIN ,DEEPRECH,                                 & !inout\n                   WPLUS, WMINUS)                                     !out\n       RSAT =  RSAT + WPLUS\n       SUBDEF = SUBDEF + WMINUS\n       QDRAIN_SAVE = QDRAIN_SAVE + QDRAIN\n       RUNSRF_SAVE = RUNSRF_SAVE + RUNSRF\n    END DO\n\n    QDRAIN = QDRAIN_SAVE/NITER\n    RUNSRF = RUNSRF_SAVE/NITER\n\n    RUNSRF = RUNSRF * 1000. + RSAT * 1000./DT  ! m/s -> mm/s\n    QDRAIN = QDRAIN * 1000.\n    RUNSUB = RUNSUB - SUBDEF * 1000./DT ! mm/s\n\n!WRF_HYDRO_DJG...\n!yw    INFXSRT = RUNSRF * DT   !mm/s -> mm\n\n! removal of soil water due to groundwater flow (option 2)\n\n    IF(OPT_RUN == 2) THEN\n         WTSUB = 0.\n         DO K = 1, NSOIL\n           WTSUB = WTSUB + WCND(K)*DZSNSO(K)\n         END DO\n\n         DO K = 1, NSOIL\n           MH2O    = RUNSUB*DT*(WCND(K)*DZSNSO(K))/WTSUB       ! mm\n           SH2O(K) = SH2O(K) - MH2O/(DZSNSO(K)*1000.)\n         END DO\n    END IF\n\n! Limit MLIQ to be greater than or equal to watmin.\n! Get water needed to bring MLIQ equal WATMIN from lower layer.\n\n   IF(OPT_RUN /= 1) THEN\n      DO IZ = 1, NSOIL\n         MLIQ(IZ) = SH2O(IZ)*DZSNSO(IZ)*1000.\n      END DO\n\n      WATMIN = 0.01           ! mm\n      DO IZ = 1, NSOIL-1\n          IF (MLIQ(IZ) .LT. 0.) THEN\n             XS = WATMIN-MLIQ(IZ)\n          ELSE\n             XS = 0.\n          END IF\n          MLIQ(IZ  ) = MLIQ(IZ  ) + XS\n          MLIQ(IZ+1) = MLIQ(IZ+1) - XS\n      END DO\n\n        IZ = NSOIL\n        IF (MLIQ(IZ) .LT. WATMIN) THEN\n           XS = WATMIN-MLIQ(IZ)\n        ELSE\n           XS = 0.\n        END IF\n        MLIQ(IZ) = MLIQ(IZ) + XS\n        RUNSUB   = RUNSUB - XS/DT\n        IF(OPT_RUN == 5)DEEPRECH = DEEPRECH - XS*1.E-3\n\n      DO IZ = 1, NSOIL\n        SH2O(IZ)     = MLIQ(IZ) / (DZSNSO(IZ)*1000.)\n      END DO\n   END IF\n\n  END SUBROUTINE SOILWATER\n\n!== begin zwteq ====================================================================================\n\n  SUBROUTINE ZWTEQ (parameters,NSOIL  ,NSNOW  ,ZSOIL  ,DZSNSO ,SH2O   ,ZWT)\n! ----------------------------------------------------------------------\n! calculate equilibrium water table depth (Niu et al., 2005)\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                         INTENT(IN) :: NSOIL  !no. of soil layers\n  INTEGER,                         INTENT(IN) :: NSNOW  !maximum no. of snow layers\n  REAL, DIMENSION(1:NSOIL),        INTENT(IN) :: ZSOIL  !depth of soil layer-bottom [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !snow/soil layer depth [m]\n  REAL, DIMENSION(1:NSOIL),        INTENT(IN) :: SH2O   !soil liquid water content [m3/m3]\n\n! output\n\n  REAL,                           INTENT(OUT) :: ZWT    !water table depth [m]\n\n! locals\n\n  INTEGER :: K                      !do-loop index\n  INTEGER, PARAMETER :: NFINE = 100 !no. of fine soil layers of 6m soil\n  REAL    :: WD1                    !water deficit from coarse (4-L) soil moisture profile\n  REAL    :: WD2                    !water deficit from fine (100-L) soil moisture profile\n  REAL    :: DZFINE                 !layer thickness of the 100-L soil layers to 6.0 m\n  REAL    :: TEMP                   !temporary variable\n  REAL, DIMENSION(1:NFINE) :: ZFINE !layer-bottom depth of the 100-L soil layers to 6.0 m\n! ----------------------------------------------------------------------\n\n   WD1 = 0.\n   DO K = 1,NSOIL\n     WD1 = WD1 + (parameters%SMCMAX(1)-SH2O(K)) * DZSNSO(K) ! [m]\n   ENDDO\n\n   DZFINE = 3.0 * (-ZSOIL(NSOIL)) / NFINE\n   do K =1,NFINE\n      ZFINE(K) = FLOAT(K) * DZFINE\n   ENDDO\n\n   ZWT = -3.*ZSOIL(NSOIL) - 0.001   ! initial value [m]\n\n   WD2 = 0.\n   DO K = 1,NFINE\n     TEMP  = 1. + (ZWT-ZFINE(K))/parameters%PSISAT(1)\n     WD2   = WD2 + parameters%SMCMAX(1)*(1.-TEMP**(-1./parameters%BEXP(1)))*DZFINE\n     IF(ABS(WD2-WD1).LE.0.01) THEN\n        ZWT = ZFINE(K)\n        EXIT\n     ENDIF\n   ENDDO\n\n  END SUBROUTINE ZWTEQ\n\n!== begin infil ====================================================================================\n\n  SUBROUTINE INFIL (parameters,NSOIL  ,DT     ,ZSOIL  ,SH2O   ,SICE   , & !in\n                    SICEMAX,QINSUR ,                         & !in\n                    PDDUM  ,RUNSRF )                           !out\n! --------------------------------------------------------------------------------\n! compute inflitration rate at soil surface and surface runoff\n! --------------------------------------------------------------------------------\n    IMPLICIT NONE\n! --------------------------------------------------------------------------------\n! inputs\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                  INTENT(IN) :: NSOIL  !no. of soil layers\n  REAL,                     INTENT(IN) :: DT     !time step (sec)\n  REAL, DIMENSION(1:NSOIL), INTENT(IN) :: ZSOIL  !depth of soil layer-bottom [m]\n  REAL, DIMENSION(1:NSOIL), INTENT(IN) :: SH2O   !soil liquid water content [m3/m3]\n  REAL, DIMENSION(1:NSOIL), INTENT(IN) :: SICE   !soil ice content [m3/m3]\n  REAL,                     INTENT(IN) :: QINSUR !water input on soil surface [mm/s]\n  REAL,                     INTENT(IN) :: SICEMAX!maximum soil ice content (m3/m3)\n\n! outputs\n  REAL,                    INTENT(OUT) :: RUNSRF !surface runoff [mm/s]\n  REAL,                    INTENT(OUT) :: PDDUM  !infiltration rate at surface\n\n! locals\n  INTEGER :: IALP1, J, JJ,  K\n  REAL                     :: VAL\n  REAL                     :: DDT\n  REAL                     :: PX\n  REAL                     :: DT1, DD, DICE\n  REAL                     :: FCR\n  REAL                     :: SUM\n  REAL                     :: ACRT\n  REAL                     :: WDF\n  REAL                     :: WCND\n  REAL                     :: SMCAV\n  REAL                     :: INFMAX\n  REAL, DIMENSION(1:NSOIL) :: DMAX\n  INTEGER, PARAMETER       :: CVFRZ = 3\n  REAL                     :: imperv_eff   !effective imperviousness\n! --------------------------------------------------------------------------------\n\n    IF (QINSUR >  0.0) THEN\n       DT1 = DT /86400.\n       SMCAV = parameters%SMCMAX(1) - parameters%SMCWLT(1)\n\n! maximum infiltration rate\n\n       DMAX(1)= -ZSOIL(1) * SMCAV\n       DICE   = -ZSOIL(1) * SICE(1)\n       DMAX(1)= DMAX(1)* (1.0-(SH2O(1) + SICE(1) - parameters%SMCWLT(1))/SMCAV)\n\n       DD = DMAX(1)\n\n       DO K = 2,NSOIL\n          DICE    = DICE + (ZSOIL(K-1) - ZSOIL(K) ) * SICE(K)\n          DMAX(K) = (ZSOIL(K-1) - ZSOIL(K)) * SMCAV\n          DMAX(K) = DMAX(K) * (1.0-(SH2O(K) + SICE(K) - parameters%SMCWLT(K))/SMCAV)\n          DD      = DD + DMAX(K)\n       END DO\n\n       VAL = (1. - EXP ( - parameters%KDT * DT1))\n       DDT = DD * VAL\n       PX  = MAX(0.,QINSUR * DT)\n       INFMAX = (PX * (DDT / (PX + DDT)))/ DT\n\n! impermeable fraction due to frozen soil\n\n       FCR = 1.\n       IF (DICE >  1.E-2) THEN\n          ACRT = CVFRZ * parameters%FRZX / DICE\n          SUM = 1.\n          IALP1 = CVFRZ - 1\n          DO J = 1,IALP1\n             K = 1\n             DO JJ = J +1,IALP1\n                K = K * JJ\n             END DO\n             SUM = SUM + (ACRT ** (CVFRZ - J)) / FLOAT(K)\n          END DO\n          FCR = 1. - EXP (-ACRT) * SUM\n       END IF\n\n! correction of infiltration limitation\n\n       INFMAX = INFMAX * FCR\n\n! imperviousness adjustment\n\n       IF (OPT_IMPERV == 1) THEN\n         ! Use total imperviousness\n         imperv_eff = parameters%imperv\n       ELSE IF (OPT_IMPERV == 2) THEN\n         ! Effective imperviousness from Alley & Veenhuis\n         imperv_eff = 0.0015 * ( (100. * parameters%imperv)**1.41 )\n       ELSE ! options 0 and 9 both have no impervious adjustment\n         ! No imperviousness adjustment\n         imperv_eff = 0.0\n       END IF\n\n       RUNSRF = QINSUR * imperv_eff\n\n       CALL WDFCND2 (parameters,WDF,WCND,SH2O(1),SICEMAX,1)\n       INFMAX = MAX (INFMAX,WCND)\n       INFMAX = MIN (INFMAX,PX)\n\n       RUNSRF = RUNSRF + MAX(0., (QINSUR * (1. - imperv_eff)) - INFMAX)\n       PDDUM = QINSUR - RUNSRF\n\n    END IF\n\n  END SUBROUTINE INFIL\n\n!== begin srt ======================================================================================\n\n  SUBROUTINE SRT (parameters,NSOIL  ,ZSOIL  ,DT     ,PDDUM  ,ETRANI , & !in\n                  QSEVA  ,SH2O   ,SMC    ,ZWT    ,FCR    , & !in\n                  SICEMAX,FCRMAX ,ILOC   ,JLOC   ,SMCWTD ,         & !in\n                  RHSTT  ,AI     ,BI     ,CI     ,QDRAIN , & !out\n                  WCND   )                                   !out\n! ----------------------------------------------------------------------\n! calculate the right hand side of the time tendency term of the soil\n! water diffusion equation.  also to compute ( prepare ) the matrix\n! coefficients for the tri-diagonal matrix of the implicit time scheme.\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n!input\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER,                  INTENT(IN)  :: ILOC   !grid index\n    INTEGER,                  INTENT(IN)  :: JLOC   !grid index\n    INTEGER,                  INTENT(IN)  :: NSOIL\n    REAL, DIMENSION(1:NSOIL), INTENT(IN)  :: ZSOIL\n    REAL,                     INTENT(IN)  :: DT\n    REAL,                     INTENT(IN)  :: PDDUM\n    REAL,                     INTENT(IN)  :: QSEVA\n    REAL, DIMENSION(1:NSOIL), INTENT(IN)  :: ETRANI\n    REAL, DIMENSION(1:NSOIL), INTENT(IN)  :: SH2O\n    REAL, DIMENSION(1:NSOIL), INTENT(IN)  :: SMC\n    REAL,                     INTENT(IN)  :: ZWT    ! water table depth [m]\n    REAL, DIMENSION(1:NSOIL), INTENT(IN)  :: FCR\n    REAL, INTENT(IN)                      :: FCRMAX !maximum of FCR (-)\n    REAL,                     INTENT(IN)  :: SICEMAX!maximum soil ice content (m3/m3)\n    REAL,                     INTENT(IN)  :: SMCWTD !soil moisture between bottom of the soil and the water table\n\n! output\n\n    REAL, DIMENSION(1:NSOIL), INTENT(OUT) :: RHSTT\n    REAL, DIMENSION(1:NSOIL), INTENT(OUT) :: AI\n    REAL, DIMENSION(1:NSOIL), INTENT(OUT) :: BI\n    REAL, DIMENSION(1:NSOIL), INTENT(OUT) :: CI\n    REAL, DIMENSION(1:NSOIL), INTENT(OUT) :: WCND    !hydraulic conductivity (m/s)\n    REAL,                     INTENT(OUT) :: QDRAIN  !bottom drainage (m/s)\n\n! local\n    INTEGER                               :: K\n    REAL, DIMENSION(1:NSOIL)              :: DDZ\n    REAL, DIMENSION(1:NSOIL)              :: DENOM\n    REAL, DIMENSION(1:NSOIL)              :: DSMDZ\n    REAL, DIMENSION(1:NSOIL)              :: WFLUX\n    REAL, DIMENSION(1:NSOIL)              :: WDF\n    REAL, DIMENSION(1:NSOIL)              :: SMX\n    REAL                                  :: TEMP1\n    REAL                                  :: SMXWTD !soil moisture between bottom of the soil and water table\n    REAL                                  :: SMXBOT  !soil moisture below bottom to calculate flux\n\n! Niu and Yang (2006), J. of Hydrometeorology\n! ----------------------------------------------------------------------\n\n    IF(OPT_INF == 1) THEN\n      DO K = 1, NSOIL\n        CALL WDFCND1 (parameters,WDF(K),WCND(K),SMC(K),FCR(K),K)\n        SMX(K) = SMC(K)\n      END DO\n        IF(OPT_RUN == 5)SMXWTD=SMCWTD\n    END IF\n\n    IF(OPT_INF == 2) THEN\n      DO K = 1, NSOIL\n        CALL WDFCND2 (parameters,WDF(K),WCND(K),SH2O(K),SICEMAX,K)\n        SMX(K) = SH2O(K)\n      END DO\n          IF(OPT_RUN == 5)SMXWTD=SMCWTD*SH2O(NSOIL)/SMC(NSOIL)  !same liquid fraction as in the bottom layer\n    END IF\n\n    DO K = 1, NSOIL\n       IF(K == 1) THEN\n          DENOM(K) = - ZSOIL (K)\n          TEMP1    = - ZSOIL (K+1)\n          DDZ(K)   = 2.0 / TEMP1\n          DSMDZ(K) = 2.0 * (SMX(K) - SMX(K+1)) / TEMP1\n          WFLUX(K) = WDF(K) * DSMDZ(K) + WCND(K) - PDDUM + ETRANI(K) + QSEVA\n       ELSE IF (K < NSOIL) THEN\n          DENOM(k) = (ZSOIL(K-1) - ZSOIL(K))\n          TEMP1    = (ZSOIL(K-1) - ZSOIL(K+1))\n          DDZ(K)   = 2.0 / TEMP1\n          DSMDZ(K) = 2.0 * (SMX(K) - SMX(K+1)) / TEMP1\n          WFLUX(K) = WDF(K  ) * DSMDZ(K  ) + WCND(K  )         &\n                   - WDF(K-1) * DSMDZ(K-1) - WCND(K-1) + ETRANI(K)\n       ELSE\n          DENOM(K) = (ZSOIL(K-1) - ZSOIL(K))\n          IF(OPT_RUN == 1 .or. OPT_RUN == 2) THEN\n             QDRAIN   = 0.\n          END IF\n          IF(OPT_RUN == 3 .OR. OPT_RUN == 7) THEN\n             QDRAIN   = parameters%SLOPE*WCND(K)\n          END IF\n          IF(OPT_RUN == 4) THEN\n             QDRAIN   = (1.0-FCRMAX)*WCND(K)\n          END IF\n          IF(OPT_RUN == 5) THEN   !gmm new m-m&f water table dynamics formulation\n             TEMP1    = 2.0 * DENOM(K)\n             IF(ZWT < ZSOIL(NSOIL)-DENOM(NSOIL))THEN\n!gmm interpolate from below, midway to the water table, to the middle of the auxiliary layer below the soil bottom\n                SMXBOT = SMX(K) - (SMX(K)-SMXWTD) *  DENOM(K) * 2./ (DENOM(K) + ZSOIL(K) - ZWT)\n             ELSE\n                SMXBOT = SMXWTD\n             ENDIF\n             DSMDZ(K) = 2.0 * (SMX(K) - SMXBOT) / TEMP1\n             QDRAIN   = WDF(K  ) * DSMDZ(K  ) + WCND(K  )\n          END IF\n          WFLUX(K) = -(WDF(K-1)*DSMDZ(K-1))-WCND(K-1)+ETRANI(K) + QDRAIN\n       END IF\n    END DO\n\n    DO K = 1, NSOIL\n       IF(K == 1) THEN\n          AI(K)    =   0.0\n          BI(K)    =   WDF(K  ) * DDZ(K  ) / DENOM(K)\n          CI(K)    = - BI (K)\n       ELSE IF (K < NSOIL) THEN\n          AI(K)    = - WDF(K-1) * DDZ(K-1) / DENOM(K)\n          CI(K)    = - WDF(K  ) * DDZ(K  ) / DENOM(K)\n          BI(K)    = - ( AI (K) + CI (K) )\n       ELSE\n          AI(K)    = - WDF(K-1) * DDZ(K-1) / DENOM(K)\n          CI(K)    = 0.0\n          BI(K)    = - ( AI (K) + CI (K) )\n       END IF\n          RHSTT(K) = WFLUX(K) / (-DENOM(K))\n    END DO\n\n! ----------------------------------------------------------------------\n  END SUBROUTINE SRT\n\n!== begin sstep ====================================================================================\n\n  SUBROUTINE SSTEP (parameters,NSOIL  ,NSNOW  ,DT     ,ZSOIL  ,DZSNSO , & !in\n                    SICE   ,ILOC   ,JLOC   ,ZWT            ,                 & !in\n                    SH2O   ,SMC    ,AI     ,BI     ,CI     , & !inout\n                    RHSTT  ,SMCWTD ,QDRAIN ,DEEPRECH,                                 & !inout\n                    WPLUS, WMINUS  )                                   !out\n\n! ----------------------------------------------------------------------\n! calculate/update soil moisture content values\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n!input\n\n  type (noahmp_parameters), intent(in) :: parameters\n    INTEGER,                         INTENT(IN) :: ILOC   !grid index\n    INTEGER,                         INTENT(IN) :: JLOC   !grid index\n    INTEGER,                         INTENT(IN) :: NSOIL  !\n    INTEGER,                         INTENT(IN) :: NSNOW  !\n    REAL, INTENT(IN)                            :: DT\n    REAL, INTENT(IN)                            :: ZWT\n    REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: ZSOIL\n    REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: SICE\n    REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO ! snow/soil layer thickness [m]\n\n!input and output\n    REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SH2O\n    REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: SMC\n    REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: AI\n    REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: BI\n    REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: CI\n    REAL, DIMENSION(1:NSOIL), INTENT(INOUT) :: RHSTT\n    REAL                    , INTENT(INOUT) :: SMCWTD\n    REAL                    , INTENT(INOUT) :: QDRAIN\n    REAL                    , INTENT(INOUT) :: DEEPRECH\n\n!output\n    REAL, INTENT(OUT)                       :: WPLUS     !saturation excess water (m)\n    REAL, INTENT(OUT)                       :: WMINUS    !deficit from negative smc correction (m)\n\n!local\n    INTEGER                                 :: K\n    REAL, DIMENSION(1:NSOIL)                :: RHSTTIN\n    REAL, DIMENSION(1:NSOIL)                :: CIIN\n    REAL                                    :: STOT\n    REAL                                    :: EPORE\n    REAL                                    :: WATMIN  !minimum water content (m/m)\n\n! ----------------------------------------------------------------------\n    WPLUS = 0.0\n    WMINUS = 0.0\n\n    DO K = 1,NSOIL\n       RHSTT (K) =   RHSTT(K) * DT\n       AI (K)    =      AI(K) * DT\n       BI (K)    = 1. + BI(K) * DT\n       CI (K)    =      CI(K) * DT\n    END DO\n\n! copy values for input variables before calling rosr12\n\n    DO K = 1,NSOIL\n       RHSTTIN(k) = RHSTT(K)\n       CIIN(k)    = CI(K)\n    END DO\n\n! call ROSR12 to solve the tri-diagonal matrix\n\n    CALL ROSR12 (CI,AI,BI,CIIN,RHSTTIN,RHSTT,1,NSOIL,0)\n\n    DO K = 1,NSOIL\n        SH2O(K) = SH2O(K) + CI(K)\n    ENDDO\n\n!  excessive water above saturation in a layer is moved to\n!  its unsaturated layer like in a bucket\n\n!gmmwith opt_run=5 there is soil moisture below nsoil, to the water table\n  IF(OPT_RUN == 5) THEN\n\n!update smcwtd\n\n     IF(ZWT < ZSOIL(NSOIL)-DZSNSO(NSOIL))THEN\n!accumulate qdrain to update deep water table and soil moisture later\n        DEEPRECH =  DEEPRECH + DT * QDRAIN\n     ELSE\n        SMCWTD = SMCWTD + DT * QDRAIN  / DZSNSO(NSOIL)\n        WPLUS        = MAX((SMCWTD-parameters%SMCMAX(NSOIL)), 0.0) * DZSNSO(NSOIL)\n        WMINUS       = MAX((1.E-4-SMCWTD), 0.0) * DZSNSO(NSOIL)\n\n        SMCWTD = MAX( MIN(SMCWTD,parameters%SMCMAX(NSOIL)) , 1.E-4)\n        SH2O(NSOIL)    = SH2O(NSOIL) + WPLUS/DZSNSO(NSOIL)\n\n!reduce fluxes at the bottom boundaries accordingly\n        QDRAIN = QDRAIN - WPLUS/DT\n        DEEPRECH = DEEPRECH - WMINUS\n     ENDIF\n\n  ENDIF\n\n    DO K = NSOIL,2,-1\n      EPORE        = MAX ( 1.E-4 , ( parameters%SMCMAX(K) - SICE(K) ) )\n      WPLUS        = MAX((SH2O(K)-EPORE), 0.0) * DZSNSO(K)\n      SH2O(K)      = MIN(EPORE,SH2O(K))\n      SH2O(K-1)    = SH2O(K-1) + WPLUS/DZSNSO(K-1)\n    END DO\n\n    EPORE        = MAX ( 1.E-4 , ( parameters%SMCMAX(1) - SICE(1) ) )\n    WPLUS        = MAX((SH2O(1)-EPORE), 0.0) * DZSNSO(1)\n    SH2O(1)      = MIN(EPORE,SH2O(1))\n\n   IF(WPLUS > 0.0) THEN\n    SH2O(2)      = SH2O(2) + WPLUS/DZSNSO(2)\n    DO K = 2,NSOIL-1\n      EPORE        = MAX ( 1.E-4 , ( parameters%SMCMAX(K) - SICE(K) ) )\n      WPLUS        = MAX((SH2O(K)-EPORE), 0.0) * DZSNSO(K)\n      SH2O(K)      = MIN(EPORE,SH2O(K))\n      SH2O(K+1)    = SH2O(K+1) + WPLUS/DZSNSO(K+1)\n    END DO\n\n    EPORE        = MAX ( 1.E-4 , ( parameters%SMCMAX(NSOIL) - SICE(NSOIL) ) )\n    WPLUS        = MAX((SH2O(NSOIL)-EPORE), 0.0) * DZSNSO(NSOIL)\n    SH2O(NSOIL)  = MIN(EPORE,SH2O(NSOIL))\n   END IF\n\n   ! Negative soil moisture check\n   IF ( ANY(SH2O < 0.0) ) THEN\n#ifdef HYDRO_D\n     write(*,*) \"WARNING (SSTEP): Negative smc adjustment\"\n#endif\n     ! WATMIN: in soilwater check this is a fixed value of 0.01 mm; why not smcdry?\n     ! For this formulation, we convert 0.01mm to a soil water fraction per layer.\n     ! So WATMIN = (0.01/1000.)/DZSNSO to convert to units of m/m for each layer.\n     DO K = 1,NSOIL-1\n       WATMIN    = 0.00001/DZSNSO(K) ! fraction\n       ! Amount of water below residual soil water content\n       WMINUS    = MAX ((WATMIN-SH2O(K))*DZSNSO(K), 0.0 )  ! m\n       ! Remove from lower layer and add to current layer\n       SH2O(K)   = MAX(WATMIN, SH2O(K))\n       SH2O(K+1) = SH2O(K+1) - WMINUS/DZSNSO(K+1)\n     END DO\n     ! Check bottom layer to see if deficit still exists\n     WATMIN      = 0.00001/DZSNSO(NSOIL) ! fraction\n     WMINUS      = MAX ((WATMIN-SH2O(NSOIL))*DZSNSO(NSOIL), 0.0 )  ! m\n     SH2O(NSOIL) = MAX(WATMIN, SH2O(NSOIL))\n#ifdef HYDRO_D\n     IF (WMINUS .ne. 0) then\n        write(*,*) \"WARNING (SSTEP): SMC deficit - this water will be removed from subsurface runoff (meters).\", WMINUS\n     END IF\n#endif\n   END IF\n\n   SMC = SH2O + SICE\n\n  END SUBROUTINE SSTEP\n\n!== begin xinanjiag=================================================================================\n  SUBROUTINE COMPUTE_XAJ_SURFRUNOFF(parameters,DT,FCR,NSOIL,SMC,ZSOIL,QINSUR,RUNSRF,PDDUM)\n! ----------------------------------------------------------------------\n! Calculate the saturated area and runoff based on Xinanjiag runoff scheme.\n! Reference: Knoben, W. J., Freer, J. E., Fowler, K. J., Peel, M. C., & Woods, R. A. (2019).\n! Modular Assessment of Rainfall-Runoff Models Toolbox (MARRMoT) v1. 2:\n! an open-source, extendable framework providing implementations of 46 conceptual\n! hydrologic models as continuous state-space formulations.\n! ----------------------------------------------------------------------\n! Author: Prasanth Valayamkunnath <prasanth@ucar.edu>\n! Date: August 03, 2020\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! Inputs\n    TYPE (noahmp_parameters), INTENT(IN)   :: parameters\n    INTEGER,                  INTENT(IN)   :: NSOIL\n    REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: SMC\n    REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: ZSOIL\n    REAL, DIMENSION(1:NSOIL), INTENT(IN)   :: FCR      !fraction of imperviousness (-) = IMP\n    REAL                    , INTENT(IN)   :: QINSUR\n    REAL                    , INTENT(IN)   :: DT\n! Output\n    REAL                    , INTENT(INOUT):: RUNSRF\n    REAL                    , INTENT(INOUT):: PDDUM\n! local\n    REAL    :: WM,WM_MAX,SM,SM_MAX,IRUNOFF,PRUNOFF\n    INTEGER :: IZ\n!------------------------------------------------------------------------\n!initialize\n    WM      = 0.0\n    WM_MAX  = 0.0\n    SM      = 0.0\n    SM_MAX  = 0.0\n    IRUNOFF = 0.0\n    PRUNOFF = 0.0\n    RUNSRF  = 0.0\n\n    DO IZ=1,NSOIL-2\n       IF ((SMC(IZ)-parameters%SMCREF(IZ)) .GT. 0.) THEN ! soil moisture greater than field capacity\n          SM     = SM + (SMC(IZ) - parameters%SMCREF(IZ) )*(-1)*ZSOIL(IZ) !m\n          WM     = WM + (parameters%SMCREF(IZ)*(-1)*ZSOIL(IZ))            !m\n       ELSE\n          WM     = WM + (SMC(IZ)*(-1)*ZSOIL(IZ))\n       END IF\n       WM_MAX = WM_MAX + (parameters%SMCREF(IZ)*(-1)*ZSOIL(IZ))\n       SM_MAX = SM_MAX + (parameters%SMCMAX(IZ) - parameters%SMCREF(IZ))*(-1)*ZSOIL(IZ)\n    END DO\n\n    WM = MIN(WM,WM_MAX) ! tension water (m)\n    SM = MIN(SM,SM_MAX) ! free water (m)\n\n! impervious surface runoff R_IMP\n    IRUNOFF = FCR(1)*QINSUR*DT\n\n! solve pervious surface runoff (m) based on Eq. (310)\n    IF ((WM/WM_MAX) .LE. (0.5-parameters%AXAJ))THEN\n       PRUNOFF = (1-FCR(1))*QINSUR*DT*((0.5-parameters%AXAJ)**(1-parameters%BXAJ))*((WM/WM_MAX)**parameters%BXAJ)\n    ELSE\n       PRUNOFF = (1-FCR(1))*QINSUR*DT*(1-(((0.5+parameters%AXAJ)**(1-parameters%BXAJ))*((1-(WM/WM_MAX))**parameters%BXAJ)))\n    END IF\n\n! estimate surface runoff based on Eq. (313)\n    IF(QINSUR .EQ. 0.0) THEN\n      RUNSRF  = 0.0\n    ELSE\n      RUNSRF = PRUNOFF*(1-((1-(SM/SM_MAX))**parameters%XXAJ))+IRUNOFF\n    END IF\n    RUNSRF = RUNSRF/DT !m/s\n    RUNSRF = MAX(0.0,    RUNSRF)\n    RUNSRF = MIN(QINSUR, RUNSRF)\n    PDDUM  = QINSUR - RUNSRF\n\n  END SUBROUTINE COMPUTE_XAJ_SURFRUNOFF\n!== end xinanjiag ==================================================================================\n\n!== begin wdfcnd1 ==================================================================================\n\n  SUBROUTINE WDFCND1 (parameters,WDF,WCND,SMC,FCR,ISOIL)\n! ----------------------------------------------------------------------\n! calculate soil water diffusivity and soil hydraulic conductivity.\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n    REAL,INTENT(IN)  :: SMC\n    REAL,INTENT(IN)  :: FCR\n    INTEGER,INTENT(IN)  :: ISOIL\n\n! output\n    REAL,INTENT(OUT) :: WCND\n    REAL,INTENT(OUT) :: WDF\n\n! local\n    REAL :: EXPON\n    REAL :: FACTR\n    REAL :: VKWGT\n! ----------------------------------------------------------------------\n\n! soil water diffusivity\n\n    FACTR = MAX(0.01, SMC/parameters%SMCMAX(ISOIL))\n    EXPON = parameters%BEXP(ISOIL) + 2.0\n    WDF   = parameters%DWSAT(ISOIL) * FACTR ** EXPON\n    WDF   = WDF * (1.0 - FCR)\n\n! hydraulic conductivity\n\n    EXPON = 2.0*parameters%BEXP(ISOIL) + 3.0\n    WCND  = parameters%DKSAT(ISOIL) * FACTR ** EXPON\n    WCND  = WCND * (1.0 - FCR)\n\n  END SUBROUTINE WDFCND1\n\n!== begin wdfcnd2 ==================================================================================\n\n  SUBROUTINE WDFCND2 (parameters,WDF,WCND,SMC,SICE,ISOIL)\n! ----------------------------------------------------------------------\n! calculate soil water diffusivity and soil hydraulic conductivity.\n! ----------------------------------------------------------------------\n    IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n    REAL,INTENT(IN)  :: SMC\n    REAL,INTENT(IN)  :: SICE\n    INTEGER,INTENT(IN)  :: ISOIL\n\n! output\n    REAL,INTENT(OUT) :: WCND\n    REAL,INTENT(OUT) :: WDF\n\n! local\n    REAL :: EXPON\n    REAL :: FACTR1,FACTR2\n    REAL :: VKWGT\n! ----------------------------------------------------------------------\n\n! soil water diffusivity\n\n    FACTR1 = 0.05/parameters%SMCMAX(ISOIL)\n    FACTR2 = MAX(0.01, SMC/parameters%SMCMAX(ISOIL))\n    FACTR1 = MIN(FACTR1,FACTR2)\n    EXPON = parameters%BEXP(ISOIL) + 2.0\n    WDF   = parameters%DWSAT(ISOIL) * FACTR2 ** EXPON\n\n    IF (SICE > 0.0) THEN\n    VKWGT = 1./ (1. + (500.* SICE)**3.)\n    WDF   = VKWGT * WDF + (1.-VKWGT)*parameters%DWSAT(ISOIL)*(FACTR1)**EXPON\n    END IF\n\n! hydraulic conductivity\n\n    EXPON = 2.0*parameters%BEXP(ISOIL) + 3.0\n    WCND  = parameters%DKSAT(ISOIL) * FACTR2 ** EXPON\n\n  END SUBROUTINE WDFCND2\n\n!== begin groundwater ==============================================================================\n\n  SUBROUTINE GROUNDWATER(parameters,NSNOW  ,NSOIL  ,DT     ,SICE   ,ZSOIL  , & !in\n                         STC    ,WCND   ,FCRMAX ,ILOC   ,JLOC   , & !in\n                         SH2O   ,ZWT    ,WA     ,WT     ,         & !inout\n                         QIN    ,QDIS   )                           !out\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                         INTENT(IN) :: ILOC  !grid index\n  INTEGER,                         INTENT(IN) :: JLOC  !grid index\n  INTEGER,                         INTENT(IN) :: NSNOW !maximum no. of snow layers\n  INTEGER,                         INTENT(IN) :: NSOIL !no. of soil layers\n  REAL,                            INTENT(IN) :: DT    !timestep [sec]\n  REAL,                            INTENT(IN) :: FCRMAX!maximum FCR (-)\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: SICE  !soil ice content [m3/m3]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: ZSOIL !depth of soil layer-bottom [m]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: WCND  !hydraulic conductivity (m/s)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: STC   !snow/soil temperature (k)\n\n! input and output\n  REAL, DIMENSION(    1:NSOIL), INTENT(INOUT) :: SH2O  !liquid soil water [m3/m3]\n  REAL,                         INTENT(INOUT) :: ZWT   !the depth to water table [m]\n  REAL,                         INTENT(INOUT) :: WA    !water storage in aquifer [mm]\n  REAL,                         INTENT(INOUT) :: WT    !water storage in aquifer\n                                                           !+ saturated soil [mm]\n! output\n  REAL,                           INTENT(OUT) :: QIN   !groundwater recharge [mm/s]\n  REAL,                           INTENT(OUT) :: QDIS  !groundwater discharge [mm/s]\n\n! local\n  REAL                                        :: FFF   !runoff decay factor (m-1)\n  REAL                                        :: RSBMX !baseflow coefficient [mm/s]\n  INTEGER                                     :: IZ    !do-loop index\n  INTEGER                                     :: IWT   !layer index above water table layer\n  REAL,  DIMENSION(    1:NSOIL)               :: DZMM  !layer thickness [mm]\n  REAL,  DIMENSION(    1:NSOIL)               :: ZNODE !node depth [m]\n  REAL,  DIMENSION(    1:NSOIL)               :: MLIQ  !liquid water mass [kg/m2 or mm]\n  REAL,  DIMENSION(    1:NSOIL)               :: EPORE !effective porosity [-]\n  REAL,  DIMENSION(    1:NSOIL)               :: HK    !hydraulic conductivity [mm/s]\n  REAL,  DIMENSION(    1:NSOIL)               :: SMC   !total soil water  content [m3/m3]\n  REAL(KIND=8)                                :: S_NODE!degree of saturation of IWT layer\n  REAL                                        :: DZSUM !cumulative depth above water table [m]\n  REAL                                        :: SMPFZ !matric potential (frozen effects) [mm]\n  REAL                                        :: KA    !aquifer hydraulic conductivity [mm/s]\n  REAL                                        :: WH_ZWT!water head at water table [mm]\n  REAL                                        :: WH    !water head at layer above ZWT [mm]\n  REAL                                        :: WS    !water used to fill air pore [mm]\n  REAL                                        :: WTSUB !sum of HK*DZMM\n  REAL                                        :: WATMIN!minimum soil vol soil moisture [m3/m3]\n  REAL                                        :: XS    !excessive water above saturation [mm]\n  REAL, PARAMETER                             :: ROUS = 0.2    !specific yield [-]\n  REAL, PARAMETER                             :: CMIC = 0.20   !microprore content (0.0-1.0)\n                                                               !0.0-close to free drainage\n! -------------------------------------------------------------\n      QDIS      = 0.0\n      QIN       = 0.0\n\n! Derive layer-bottom depth in [mm]\n!KWM:  Derive layer thickness in mm\n\n      DZMM(1) = -ZSOIL(1)*1.E3\n      DO IZ = 2, NSOIL\n         DZMM(IZ)  = 1.E3 * (ZSOIL(IZ - 1) - ZSOIL(IZ))\n      ENDDO\n\n! Derive node (middle) depth in [m]\n!KWM:  Positive number, depth below ground surface in m\n      ZNODE(1) = -ZSOIL(1) / 2.\n      DO IZ = 2, NSOIL\n         ZNODE(IZ)  = -ZSOIL(IZ-1) + 0.5 * (ZSOIL(IZ-1) - ZSOIL(IZ))\n      ENDDO\n\n! Convert volumetric soil moisture \"sh2o\" to mass\n\n      DO IZ = 1, NSOIL\n         SMC(IZ)      = SH2O(IZ) + SICE(IZ)\n         MLIQ(IZ)     = SH2O(IZ) * DZMM(IZ)\n         EPORE(IZ)    = MAX(0.01,parameters%SMCMAX(IZ) - SICE(IZ))\n         HK(IZ)       = 1.E3*WCND(IZ)\n      ENDDO\n\n! The layer index of the first unsaturated layer,\n! i.e., the layer right above the water table\n\n      IWT = NSOIL\n      DO IZ = 2,NSOIL\n         IF(ZWT   .LE. -ZSOIL(IZ) ) THEN\n            IWT = IZ-1\n            EXIT\n         END IF\n      ENDDO\n\n! Groundwater discharge [mm/s]\n\n      FFF   = 6.0\n      RSBMX = 5.0\n\n      QDIS = (1.0-FCRMAX)*RSBMX*EXP(-parameters%TIMEAN)*EXP(-FFF*(ZWT-2.0))\n\n! Matric potential at the layer above the water table\n\n      S_NODE = MIN(1.0,SMC(IWT)/parameters%SMCMAX(IWT) )\n      S_NODE = MAX(S_NODE,REAL(0.01,KIND=8))\n      SMPFZ  = -parameters%PSISAT(IWT)*1000.*S_NODE**(-parameters%BEXP(IWT))   ! m --> mm\n      SMPFZ  = MAX(-120000.0,CMIC*SMPFZ)\n\n! Recharge rate qin to groundwater\n\n      KA  = HK(IWT)\n\n      WH_ZWT  = - ZWT * 1.E3                          !(mm)\n      WH      = SMPFZ  - ZNODE(IWT)*1.E3              !(mm)\n      QIN     = - KA * (WH_ZWT-WH)  /((ZWT-ZNODE(IWT))*1.E3)\n      QIN     = MAX(-10.0/DT,MIN(10./DT,QIN))\n\n! Water storage in the aquifer + saturated soil\n\n      WT  = WT + (QIN - QDIS) * DT     !(mm)\n\n      IF(IWT.EQ.NSOIL) THEN\n         WA          = WA + (QIN - QDIS) * DT     !(mm)\n         WT          = WA\n         ZWT         = (-ZSOIL(NSOIL) + 25.) - WA/1000./ROUS      !(m)\n         MLIQ(NSOIL) = MLIQ(NSOIL) - QIN * DT        ! [mm]\n\n         MLIQ(NSOIL) = MLIQ(NSOIL) + MAX(0.,(WA - 5000.))\n         WA          = MIN(WA, 5000.)\n      ELSE\n\n         IF (IWT.EQ.NSOIL-1) THEN\n            ZWT = -ZSOIL(NSOIL)                   &\n                 - (WT-ROUS*1000*25.) / (EPORE(NSOIL))/1000.\n         ELSE\n            WS = 0.   ! water used to fill soil air pores\n            DO IZ = IWT+2,NSOIL\n               WS = WS + EPORE(IZ) * DZMM(IZ)\n            ENDDO\n            ZWT = -ZSOIL(IWT+1)                  &\n                  - (WT-ROUS*1000.*25.-WS) /(EPORE(IWT+1))/1000.\n         ENDIF\n\n         WTSUB = 0.\n         DO IZ = 1, NSOIL\n           WTSUB = WTSUB + HK(IZ)*DZMM(IZ)\n         END DO\n\n         DO IZ = 1, NSOIL           ! Removing subsurface runoff\n         MLIQ(IZ) = MLIQ(IZ) - QDIS*DT*HK(IZ)*DZMM(IZ)/WTSUB\n         END DO\n      END IF\n\n      ZWT = MAX(1.5,ZWT)\n\n!\n! Limit MLIQ to be greater than or equal to watmin.\n! Get water needed to bring MLIQ equal WATMIN from lower layer.\n!\n      WATMIN = 0.01\n      DO IZ = 1, NSOIL-1\n          IF (MLIQ(IZ) .LT. 0.) THEN\n             XS = WATMIN-MLIQ(IZ)\n          ELSE\n             XS = 0.\n          END IF\n          MLIQ(IZ  ) = MLIQ(IZ  ) + XS\n          MLIQ(IZ+1) = MLIQ(IZ+1) - XS\n      END DO\n\n        IZ = NSOIL\n        IF (MLIQ(IZ) .LT. WATMIN) THEN\n           XS = WATMIN-MLIQ(IZ)\n        ELSE\n           XS = 0.\n        END IF\n        MLIQ(IZ) = MLIQ(IZ) + XS\n        WA       = WA - XS\n        WT       = WT - XS\n\n      DO IZ = 1, NSOIL\n        SH2O(IZ)     = MLIQ(IZ) / DZMM(IZ)\n      END DO\n\n  END SUBROUTINE GROUNDWATER\n\n!== begin shallowwatertable ========================================================================\n\n  SUBROUTINE SHALLOWWATERTABLE (parameters,NSNOW  ,NSOIL  ,ZSOIL, DT    , & !in\n                         DZSNSO ,SMCEQ ,ILOC   ,JLOC         , & !in\n                         SMC    ,WTD   ,SMCWTD ,RECH, QDRAIN  )  !inout\n! ----------------------------------------------------------------------\n!Diagnoses water table depth and computes recharge when the water table is within the resolved soil layers,\n!according to the Miguez-Macho&Fan scheme\n! ----------------------------------------------------------------------\n  IMPLICIT NONE\n! ----------------------------------------------------------------------\n! input\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER,                         INTENT(IN) :: NSNOW !maximum no. of snow layers\n  INTEGER,                         INTENT(IN) :: NSOIL !no. of soil layers\n  INTEGER,                         INTENT(IN) :: ILOC,JLOC\n  REAL,                            INTENT(IN) :: DT\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: ZSOIL !depth of soil layer-bottom [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO ! snow/soil layer thickness [m]\n  REAL,  DIMENSION(      1:NSOIL), INTENT(IN) :: SMCEQ  !equilibrium soil water  content [m3/m3]\n\n! input and output\n  REAL,  DIMENSION(      1:NSOIL), INTENT(INOUT) :: SMC   !total soil water  content [m3/m3]\n  REAL,                         INTENT(INOUT) :: WTD   !the depth to water table [m]\n  REAL,                         INTENT(INOUT) :: SMCWTD   !soil moisture between bottom of the soil and the water table [m3/m3]\n  REAL,                         INTENT(OUT) :: RECH ! groundwater recharge (net vertical flux across the water table), positive up\n  REAL,                         INTENT(INOUT) :: QDRAIN\n\n! local\n  INTEGER                                     :: IZ    !do-loop index\n  INTEGER                                     :: IWTD   !layer index above water table layer\n  INTEGER                                     :: KWTD   !layer index where the water table layer is\n  REAL                                        :: WTDOLD\n  REAL                                        :: DZUP\n  REAL                                        :: SMCEQDEEP\n  REAL,  DIMENSION(       0:NSOIL)            :: ZSOIL0\n! -------------------------------------------------------------\n\n\nZSOIL0(1:NSOIL) = ZSOIL(1:NSOIL)\nZSOIL0(0) = 0.\n\n!find the layer where the water table is\n     DO IZ=NSOIL,1,-1\n        IF(WTD + 1.E-6 < ZSOIL0(IZ)) EXIT\n     ENDDO\n        IWTD=IZ\n\n\n        KWTD=IWTD+1  !layer where the water table is\n        IF(KWTD.LE.NSOIL)THEN    !wtd in the resolved layers\n           WTDOLD=WTD\n           IF(SMC(KWTD).GT.SMCEQ(KWTD))THEN\n\n               IF(SMC(KWTD).EQ.parameters%SMCMAX(KWTD))THEN !wtd went to the layer above\n                      WTD=ZSOIL0(IWTD)\n                      RECH=-(WTDOLD-WTD) * (parameters%SMCMAX(KWTD)-SMCEQ(KWTD))\n                      IWTD=IWTD-1\n                      KWTD=KWTD-1\n                   IF(KWTD.GE.1)THEN\n                      IF(SMC(KWTD).GT.SMCEQ(KWTD))THEN\n                      WTDOLD=WTD\n                      WTD = MIN( ( SMC(KWTD)*DZSNSO(KWTD) &\n                        - SMCEQ(KWTD)*ZSOIL0(IWTD) + parameters%SMCMAX(KWTD)*ZSOIL0(KWTD) ) / &\n                        ( parameters%SMCMAX(KWTD)-SMCEQ(KWTD) ), ZSOIL0(IWTD))\n                      RECH=RECH-(WTDOLD-WTD) * (parameters%SMCMAX(KWTD)-SMCEQ(KWTD))\n                      ENDIF\n                   ENDIF\n               ELSE  !wtd stays in the layer\n                      WTD = MIN( ( SMC(KWTD)*DZSNSO(KWTD) &\n                        - SMCEQ(KWTD)*ZSOIL0(IWTD) + parameters%SMCMAX(KWTD)*ZSOIL0(KWTD) ) / &\n                        ( parameters%SMCMAX(KWTD)-SMCEQ(KWTD) ), ZSOIL0(IWTD))\n                      RECH=-(WTDOLD-WTD) * (parameters%SMCMAX(KWTD)-SMCEQ(KWTD))\n               ENDIF\n\n           ELSE    !wtd has gone down to the layer below\n               WTD=ZSOIL0(KWTD)\n               RECH=-(WTDOLD-WTD) * (parameters%SMCMAX(KWTD)-SMCEQ(KWTD))\n               KWTD=KWTD+1\n               IWTD=IWTD+1\n!wtd crossed to the layer below. Now adjust it there\n               IF(KWTD.LE.NSOIL)THEN\n                   WTDOLD=WTD\n                   IF(SMC(KWTD).GT.SMCEQ(KWTD))THEN\n                   WTD = MIN( ( SMC(KWTD)*DZSNSO(KWTD) &\n                   - SMCEQ(KWTD)*ZSOIL0(IWTD) + parameters%SMCMAX(KWTD)*ZSOIL0(KWTD) ) / &\n                       ( parameters%SMCMAX(KWTD)-SMCEQ(KWTD) ) , ZSOIL0(IWTD) )\n                   ELSE\n                   WTD=ZSOIL0(KWTD)\n                   ENDIF\n                   RECH = RECH - (WTDOLD-WTD) * &\n                                 (parameters%SMCMAX(KWTD)-SMCEQ(KWTD))\n\n                ELSE\n                   WTDOLD=WTD\n!restore smoi to equilibrium value with water from the ficticious layer below\n!                   SMCWTD=SMCWTD-(SMCEQ(NSOIL)-SMC(NSOIL))\n!                   QDRAIN = QDRAIN - 1000 * (SMCEQ(NSOIL)-SMC(NSOIL)) * DZSNSO(NSOIL) / DT\n!                   SMC(NSOIL)=SMCEQ(NSOIL)\n!adjust wtd in the ficticious layer below\n                   SMCEQDEEP = parameters%SMCMAX(NSOIL) * ( -parameters%PSISAT(NSOIL) / ( -parameters%PSISAT(NSOIL) - DZSNSO(NSOIL) ) ) ** (1./parameters%BEXP(NSOIL))\n                   WTD = MIN( ( SMCWTD*DZSNSO(NSOIL) &\n                   - SMCEQDEEP*ZSOIL0(NSOIL) + parameters%SMCMAX(NSOIL)*(ZSOIL0(NSOIL)-DZSNSO(NSOIL)) ) / &\n                       ( parameters%SMCMAX(NSOIL)-SMCEQDEEP ) , ZSOIL0(NSOIL) )\n                   RECH = RECH - (WTDOLD-WTD) * &\n                                 (parameters%SMCMAX(NSOIL)-SMCEQDEEP)\n                ENDIF\n\n            ENDIF\n        ELSEIF(WTD.GE.ZSOIL0(NSOIL)-DZSNSO(NSOIL))THEN\n!if wtd was already below the bottom of the resolved soil crust\n           WTDOLD=WTD\n           SMCEQDEEP = parameters%SMCMAX(NSOIL) * ( -parameters%PSISAT(NSOIL) / ( -parameters%PSISAT(NSOIL) - DZSNSO(NSOIL) ) ) ** (1./parameters%BEXP(NSOIL))\n           IF(SMCWTD.GT.SMCEQDEEP)THEN\n               WTD = MIN( ( SMCWTD*DZSNSO(NSOIL) &\n                 - SMCEQDEEP*ZSOIL0(NSOIL) + parameters%SMCMAX(NSOIL)*(ZSOIL0(NSOIL)-DZSNSO(NSOIL)) ) / &\n                     ( parameters%SMCMAX(NSOIL)-SMCEQDEEP ) , ZSOIL0(NSOIL) )\n               RECH = -(WTDOLD-WTD) * (parameters%SMCMAX(NSOIL)-SMCEQDEEP)\n           ELSE\n               RECH = -(WTDOLD-(ZSOIL0(NSOIL)-DZSNSO(NSOIL))) * (parameters%SMCMAX(NSOIL)-SMCEQDEEP)\n               WTDOLD=ZSOIL0(NSOIL)-DZSNSO(NSOIL)\n!and now even further down\n               DZUP=(SMCEQDEEP-SMCWTD)*DZSNSO(NSOIL)/(parameters%SMCMAX(NSOIL)-SMCEQDEEP)\n               WTD=WTDOLD-DZUP\n               RECH = RECH - (parameters%SMCMAX(NSOIL)-SMCEQDEEP)*DZUP\n               SMCWTD=SMCEQDEEP\n           ENDIF\n\n\n         ENDIF\n\nIF(IWTD.LT.NSOIL .AND. IWTD.GT.0) THEN\n  SMCWTD=parameters%SMCMAX(IWTD)\nELSEIF(IWTD.LT.NSOIL .AND. IWTD.LE.0) THEN\n  SMCWTD=parameters%SMCMAX(1)\nEND IF\n\nEND  SUBROUTINE SHALLOWWATERTABLE\n\n! ==================================================================================================\n! ********************* end of water subroutines ******************************************\n! ==================================================================================================\n\n!== begin carbon ===================================================================================\n\n  SUBROUTINE CARBON (parameters,NSNOW  ,NSOIL  ,VEGTYP ,DT     ,ZSOIL  , & !in\n                     DZSNSO ,STC    ,SMC    ,TV     ,TG     ,PSN    , & !in\n                     FOLN   ,BTRAN  ,APAR   ,FVEG   ,IGS    , & !in\n                     TROOT  ,IST    ,LAT    ,ILOC   ,JLOC   , & !in\n                     LFMASS ,RTMASS ,STMASS ,WOOD   ,STBLCP ,FASTCP , & !inout\n                     GPP    ,NPP    ,NEE    ,AUTORS ,HETERS ,TOTSC  , & !out\n                     TOTLB  ,XLAI   ,XSAI   )                   !out\n! ------------------------------------------------------------------------------------------\n      IMPLICIT NONE\n! ------------------------------------------------------------------------------------------\n! inputs (carbon)\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER                        , INTENT(IN) :: ILOC   !grid index\n  INTEGER                        , INTENT(IN) :: JLOC   !grid index\n  INTEGER                        , INTENT(IN) :: VEGTYP !vegetation type\n  INTEGER                        , INTENT(IN) :: NSNOW  !number of snow layers\n  INTEGER                        , INTENT(IN) :: NSOIL  !number of soil layers\n  REAL                           , INTENT(IN) :: LAT    !latitude (radians)\n  REAL                           , INTENT(IN) :: DT     !time step (s)\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: ZSOIL  !depth of layer-bottom from soil surface\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !snow/soil layer thickness [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: STC    !snow/soil temperature [k]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: SMC    !soil moisture (ice + liq.) [m3/m3]\n  REAL                           , INTENT(IN) :: TV     !vegetation temperature (k)\n  REAL                           , INTENT(IN) :: TG     !ground temperature (k)\n  REAL                           , INTENT(IN) :: FOLN   !foliage nitrogen (%)\n  REAL                           , INTENT(IN) :: BTRAN  !soil water transpiration factor (0 to 1)\n  REAL                           , INTENT(IN) :: PSN    !total leaf photosyn (umolco2/m2/s) [+]\n  REAL                           , INTENT(IN) :: APAR   !PAR by canopy (w/m2)\n  REAL                           , INTENT(IN) :: IGS    !growing season index (0=off, 1=on)\n  REAL                           , INTENT(IN) :: FVEG   !vegetation greenness fraction\n  REAL                           , INTENT(IN) :: TROOT  !root-zone averaged temperature (k)\n  INTEGER                        , INTENT(IN) :: IST    !surface type 1->soil; 2->lake\n\n! input & output (carbon)\n\n  REAL                        , INTENT(INOUT) :: LFMASS !leaf mass [g/m2]\n  REAL                        , INTENT(INOUT) :: RTMASS !mass of fine roots [g/m2]\n  REAL                        , INTENT(INOUT) :: STMASS !stem mass [g/m2]\n  REAL                        , INTENT(INOUT) :: WOOD   !mass of wood (incl. woody roots) [g/m2]\n  REAL                        , INTENT(INOUT) :: STBLCP !stable carbon in deep soil [g/m2]\n  REAL                        , INTENT(INOUT) :: FASTCP !short-lived carbon in shallow soil [g/m2]\n\n! outputs: (carbon)\n\n  REAL                          , INTENT(OUT) :: GPP    !net instantaneous assimilation [g/m2/s C]\n  REAL                          , INTENT(OUT) :: NPP    !net primary productivity [g/m2/s C]\n  REAL                          , INTENT(OUT) :: NEE    !net ecosystem exchange [g/m2/s CO2]\n  REAL                          , INTENT(OUT) :: AUTORS !net ecosystem respiration [g/m2/s C]\n  REAL                          , INTENT(OUT) :: HETERS !organic respiration [g/m2/s C]\n  REAL                          , INTENT(OUT) :: TOTSC  !total soil carbon [g/m2 C]\n  REAL                          , INTENT(OUT) :: TOTLB  !total living carbon ([g/m2 C]\n  REAL                          , INTENT(OUT) :: XLAI   !leaf area index [-]\n  REAL                          , INTENT(OUT) :: XSAI   !stem area index [-]\n!  REAL                          , INTENT(OUT) :: VOCFLX(5) ! voc fluxes [ug C m-2 h-1]\n\n! local variables\n\n  INTEGER :: J         !do-loop index\n  REAL    :: WROOT     !root zone soil water [-]\n  REAL    :: WSTRES    !water stress coeficient [-]  (1. for wilting )\n  REAL    :: LAPM      !leaf area per unit mass [m2/g]\n! ------------------------------------------------------------------------------------------\n\n   IF ( ( VEGTYP == parameters%iswater ) .OR. ( VEGTYP == parameters%ISBARREN ) .OR. &\n        ( VEGTYP == parameters%ISICE ) .or. (parameters%urban_flag) ) THEN\n      XLAI   = 0.\n      XSAI   = 0.\n      GPP    = 0.\n      NPP    = 0.\n      NEE    = 0.\n      AUTORS = 0.\n      HETERS = 0.\n      TOTSC  = 0.\n      TOTLB  = 0.\n      LFMASS = 0.\n      RTMASS = 0.\n      STMASS = 0.\n      WOOD   = 0.\n      STBLCP = 0.\n      FASTCP = 0.\n\n      RETURN\n   END IF\n\n      LAPM       = parameters%SLA / 1000.   ! m2/kg -> m2/g\n\n! water stress\n\n      WSTRES  = 1.- BTRAN\n\n      WROOT  = 0.\n      DO J=1,parameters%NROOT\n        WROOT = WROOT + SMC(J)/parameters%SMCMAX(J) *  DZSNSO(J) / (-ZSOIL(parameters%NROOT))\n      ENDDO\n\n  CALL CO2FLUX (parameters,NSNOW  ,NSOIL  ,VEGTYP ,IGS    ,DT     , & !in\n                DZSNSO ,STC    ,PSN    ,TROOT  ,TV     , & !in\n                WROOT  ,WSTRES ,FOLN   ,LAPM   ,         & !in\n                LAT    ,ILOC   ,JLOC   ,FVEG   ,         & !in\n                XLAI   ,XSAI   ,LFMASS ,RTMASS ,STMASS , & !inout\n                FASTCP ,STBLCP ,WOOD   ,                 & !inout\n                GPP    ,NPP    ,NEE    ,AUTORS ,HETERS , & !out\n                TOTSC  ,TOTLB  )                           !out\n\n!   CALL BVOC (parameters,VOCFLX,  VEGTYP,  VEGFAC,   APAR,   TV)\n!   CALL CH4\n\n  END SUBROUTINE CARBON\n\n!== begin co2flux ==================================================================================\n\n  SUBROUTINE CO2FLUX (parameters,NSNOW  ,NSOIL  ,VEGTYP ,IGS    ,DT     , & !in\n                      DZSNSO ,STC    ,PSN    ,TROOT  ,TV     , & !in\n                      WROOT  ,WSTRES ,FOLN   ,LAPM   ,         & !in\n                      LAT    ,ILOC   ,JLOC   ,FVEG   ,         & !in\n                      XLAI   ,XSAI   ,LFMASS ,RTMASS ,STMASS , & !inout\n                      FASTCP ,STBLCP ,WOOD   ,                 & !inout\n                      GPP    ,NPP    ,NEE    ,AUTORS ,HETERS , & !out\n                      TOTSC  ,TOTLB  )                           !out\n! -----------------------------------------------------------------------------------------\n! The original code is from RE Dickinson et al.(1998), modifed by Guo-Yue Niu, 2004\n! -----------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! -----------------------------------------------------------------------------------------\n\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER                        , INTENT(IN) :: ILOC   !grid index\n  INTEGER                        , INTENT(IN) :: JLOC   !grid index\n  INTEGER                        , INTENT(IN) :: VEGTYP !vegetation physiology type\n  INTEGER                        , INTENT(IN) :: NSNOW  !number of snow layers\n  INTEGER                        , INTENT(IN) :: NSOIL  !number of soil layers\n  REAL                           , INTENT(IN) :: DT     !time step (s)\n  REAL                           , INTENT(IN) :: LAT    !latitude (radians)\n  REAL                           , INTENT(IN) :: IGS    !growing season index (0=off, 1=on)\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !snow/soil layer thickness [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: STC    !snow/soil temperature [k]\n  REAL                           , INTENT(IN) :: PSN    !total leaf photosynthesis (umolco2/m2/s)\n  REAL                           , INTENT(IN) :: TROOT  !root-zone averaged temperature (k)\n  REAL                           , INTENT(IN) :: TV     !leaf temperature (k)\n  REAL                           , INTENT(IN) :: WROOT  !root zone soil water\n  REAL                           , INTENT(IN) :: WSTRES !soil water stress\n  REAL                           , INTENT(IN) :: FOLN   !foliage nitrogen (%)\n  REAL                           , INTENT(IN) :: LAPM   !leaf area per unit mass [m2/g]\n  REAL                           , INTENT(IN) :: FVEG   !vegetation greenness fraction\n\n! input and output\n\n  REAL                        , INTENT(INOUT) :: XLAI   !leaf  area index from leaf carbon [-]\n  REAL                        , INTENT(INOUT) :: XSAI   !stem area index from leaf carbon [-]\n  REAL                        , INTENT(INOUT) :: LFMASS !leaf mass [g/m2]\n  REAL                        , INTENT(INOUT) :: RTMASS !mass of fine roots [g/m2]\n  REAL                        , INTENT(INOUT) :: STMASS !stem mass [g/m2]\n  REAL                        , INTENT(INOUT) :: FASTCP !short lived carbon [g/m2]\n  REAL                        , INTENT(INOUT) :: STBLCP !stable carbon pool [g/m2]\n  REAL                        , INTENT(INOUT) :: WOOD   !mass of wood (incl. woody roots) [g/m2]\n\n! output\n\n  REAL                          , INTENT(OUT) :: GPP    !net instantaneous assimilation [g/m2/s]\n  REAL                          , INTENT(OUT) :: NPP    !net primary productivity [g/m2]\n  REAL                          , INTENT(OUT) :: NEE    !net ecosystem exchange (autors+heters-gpp)\n  REAL                          , INTENT(OUT) :: AUTORS !net ecosystem resp. (maintance and growth)\n  REAL                          , INTENT(OUT) :: HETERS !organic respiration\n  REAL                          , INTENT(OUT) :: TOTSC  !total soil carbon (g/m2)\n  REAL                          , INTENT(OUT) :: TOTLB  !total living carbon (g/m2)\n\n! local\n\n  REAL                   :: CFLUX    !carbon flux to atmosphere [g/m2/s]\n  REAL                   :: LFMSMN   !minimum leaf mass [g/m2]\n  REAL                   :: RSWOOD   !wood respiration [g/m2]\n  REAL                   :: RSLEAF   !leaf maintenance respiration per timestep [g/m2]\n  REAL                   :: RSROOT   !fine root respiration per time step [g/m2]\n  REAL                   :: NPPL     !leaf net primary productivity [g/m2/s]\n  REAL                   :: NPPR     !root net primary productivity [g/m2/s]\n  REAL                   :: NPPW     !wood net primary productivity [g/m2/s]\n  REAL                   :: NPPS     !wood net primary productivity [g/m2/s]\n  REAL                   :: DIELF    !death of leaf mass per time step [g/m2]\n\n  REAL                   :: ADDNPPLF !leaf assimil after resp. losses removed [g/m2]\n  REAL                   :: ADDNPPST !stem assimil after resp. losses removed [g/m2]\n  REAL                   :: CARBFX   !carbon assimilated per model step [g/m2]\n  REAL                   :: GRLEAF   !growth respiration rate for leaf [g/m2/s]\n  REAL                   :: GRROOT   !growth respiration rate for root [g/m2/s]\n  REAL                   :: GRWOOD   !growth respiration rate for wood [g/m2/s]\n  REAL                   :: GRSTEM   !growth respiration rate for stem [g/m2/s]\n  REAL                   :: LEAFPT   !fraction of carbon allocated to leaves [-]\n  REAL                   :: LFDEL    !maximum  leaf mass  available to change [g/m2/s]\n  REAL                   :: LFTOVR   !stem turnover per time step [g/m2]\n  REAL                   :: STTOVR   !stem turnover per time step [g/m2]\n  REAL                   :: WDTOVR   !wood turnover per time step [g/m2]\n  REAL                   :: RSSOIL   !soil respiration per time step [g/m2]\n  REAL                   :: RTTOVR   !root carbon loss per time step by turnover [g/m2]\n  REAL                   :: STABLC   !decay rate of fast carbon to slow carbon [g/m2/s]\n  REAL                   :: WOODF    !calculated wood to root ratio [-]\n  REAL                   :: NONLEF   !fraction of carbon to root and wood [-]\n  REAL                   :: ROOTPT   !fraction of carbon flux to roots [-]\n  REAL                   :: WOODPT   !fraction of carbon flux to wood [-]\n  REAL                   :: STEMPT   !fraction of carbon flux to stem [-]\n  REAL                   :: RESP     !leaf respiration [umol/m2/s]\n  REAL                   :: RSSTEM   !stem respiration [g/m2/s]\n\n  REAL                   :: FSW      !soil water factor for microbial respiration\n  REAL                   :: FST      !soil temperature factor for microbial respiration\n  REAL                   :: FNF      !foliage nitrogen adjustemt to respiration (<= 1)\n  REAL                   :: TF       !temperature factor\n  REAL                   :: RF       !respiration reduction factor (<= 1)\n  REAL                   :: STDEL\n  REAL                   :: STMSMN\n  REAL                   :: SAPM     !stem area per unit mass (m2/g)\n  REAL                   :: DIEST\n! -------------------------- constants -------------------------------\n  REAL                   :: BF       !parameter for present wood allocation [-]\n  REAL                   :: RSWOODC  !wood respiration coeficient [1/s]\n  REAL                   :: STOVRC   !stem turnover coefficient [1/s]\n  REAL                   :: RSDRYC   !degree of drying that reduces soil respiration [-]\n  REAL                   :: RTOVRC   !root turnover coefficient [1/s]\n  REAL                   :: WSTRC    !water stress coeficient [-]\n  REAL                   :: LAIMIN   !minimum leaf area index [m2/m2]\n  REAL                   :: XSAMIN   !minimum leaf area index [m2/m2]\n  REAL                   :: SC\n  REAL                   :: SD\n  REAL                   :: VEGFRAC\n\n! Respiration as a function of temperature\n\n  real :: r,x\n          r(x) = exp(0.08*(x-298.16))\n! ---------------------------------------------------------------------------------\n\n! constants\n    RTOVRC  = 2.0E-8        !original was 2.0e-8\n    RSDRYC  = 40.0          !original was 40.0\n    RSWOODC = 3.0E-10       !\n    BF      = 0.90          !original was 0.90   ! carbon to roots\n    WSTRC   = 100.0\n    LAIMIN  = 0.05\n    XSAMIN  = 0.05     ! MB: change to prevent vegetation from not growing back in spring\n\n    SAPM    = 3.*0.001      ! m2/kg -->m2/g\n    LFMSMN  = laimin/lapm\n    STMSMN  = xsamin/sapm\n! ---------------------------------------------------------------------------------\n\n! respiration\n\n     IF(IGS .EQ. 0.) THEN\n       RF = 0.5\n     ELSE\n       RF = 1.0\n     ENDIF\n\n     FNF     = MIN( FOLN/MAX(1.E-06,parameters%FOLNMX), 1.0 )\n     TF      = parameters%ARM**( (TV-298.16)/10. )\n     RESP    = parameters%RMF25 * TF * FNF * XLAI * RF * (1.-WSTRES) ! umol/m2/s\n     RSLEAF  = MIN((LFMASS-LFMSMN)/DT,RESP*12.e-6)                         ! g/m2/s\n\n     RSROOT  = parameters%RMR25*(RTMASS*1E-3)*TF *RF* 12.e-6         ! g/m2/s\n     RSSTEM  = parameters%RMS25*((STMASS-STMSMN)*1E-3)*TF *RF* 12.e-6         ! g/m2/s\n     RSWOOD  = RSWOODC * R(TV) * WOOD*parameters%WDPOOL\n\n! carbon assimilation\n! 1 mole -> 12 g carbon or 44 g CO2; 1 umol -> 12.e-6 g carbon;\n\n     CARBFX  = PSN * 12.e-6              ! umol co2 /m2/ s -> g/m2/s carbon\n\n! fraction of carbon into leaf versus nonleaf\n\n     LEAFPT = EXP(0.01*(1.-EXP(0.75*XLAI))*XLAI)\n     IF(VEGTYP == parameters%EBLFOREST) LEAFPT = EXP(0.01*(1.-EXP(0.50*XLAI))*XLAI)\n\n     NONLEF = 1.0 - LEAFPT\n     STEMPT = XLAI/10.0*LEAFPT\n     LEAFPT = LEAFPT - STEMPT\n\n!  fraction of carbon into wood versus root\n\n     IF(WOOD > 1.e-6) THEN\n        WOODF = (1.-EXP(-BF*(parameters%WRRAT*RTMASS/WOOD))/BF)*parameters%WDPOOL\n     ELSE\n        WOODF = parameters%WDPOOL\n     ENDIF\n\n     ROOTPT = NONLEF*(1.-WOODF)\n     WOODPT = NONLEF*WOODF\n\n! leaf and root turnover per time step\n\n     LFTOVR = parameters%LTOVRC*5.E-7*LFMASS\n     STTOVR = parameters%LTOVRC*5.E-7*STMASS\n     RTTOVR = RTOVRC*RTMASS\n     WDTOVR = 9.5E-10*WOOD\n\n! seasonal leaf die rate dependent on temp and water stress\n! water stress is set to 1 at permanent wilting point\n\n     SC  = EXP(-0.3*MAX(0.,TV-parameters%TDLEF)) * (LFMASS/120.)\n     SD  = EXP((WSTRES-1.)*WSTRC)\n     DIELF = LFMASS*1.E-6*(parameters%DILEFW * SD + parameters%DILEFC*SC)\n     DIEST = STMASS*1.E-6*(parameters%DILEFW * SD + parameters%DILEFC*SC)\n\n! calculate growth respiration for leaf, rtmass and wood\n\n     GRLEAF = MAX(0.0,parameters%FRAGR*(LEAFPT*CARBFX - RSLEAF))\n     GRSTEM = MAX(0.0,parameters%FRAGR*(STEMPT*CARBFX - RSSTEM))\n     GRROOT = MAX(0.0,parameters%FRAGR*(ROOTPT*CARBFX - RSROOT))\n     GRWOOD = MAX(0.0,parameters%FRAGR*(WOODPT*CARBFX - RSWOOD))\n\n! Impose lower T limit for photosynthesis\n\n     ADDNPPLF = MAX(0.,LEAFPT*CARBFX - GRLEAF-RSLEAF)\n     ADDNPPST = MAX(0.,STEMPT*CARBFX - GRSTEM-RSSTEM)\n!     ADDNPPLF = LEAFPT*CARBFX - GRLEAF-RSLEAF  ! MB: test Kjetil\n!     ADDNPPST = STEMPT*CARBFX - GRSTEM-RSSTEM  ! MB: test Kjetil\n     IF(TV.LT.parameters%TMIN) ADDNPPLF =0.\n     IF(TV.LT.parameters%TMIN) ADDNPPST =0.\n\n! update leaf, root, and wood carbon\n! avoid reducing leaf mass below its minimum value but conserve mass\n\n     LFDEL = (LFMASS - LFMSMN)/DT\n     STDEL = (STMASS - STMSMN)/DT\n     DIELF = MIN(DIELF,LFDEL+ADDNPPLF-LFTOVR)\n     DIEST = MIN(DIEST,STDEL+ADDNPPST-STTOVR)\n\n! net primary productivities\n\n     NPPL   = MAX(ADDNPPLF,-LFDEL)\n     NPPS   = MAX(ADDNPPST,-STDEL)\n     NPPR   = ROOTPT*CARBFX - RSROOT - GRROOT\n     NPPW   = WOODPT*CARBFX - RSWOOD - GRWOOD\n\n! masses of plant components\n\n     LFMASS = LFMASS + (NPPL-LFTOVR-DIELF)*DT\n     STMASS = STMASS + (NPPS-STTOVR-DIEST)*DT   ! g/m2\n     RTMASS = RTMASS + (NPPR-RTTOVR)      *DT\n\n     IF(RTMASS.LT.0.0) THEN\n           RTTOVR = NPPR\n           RTMASS = 0.0\n     ENDIF\n     WOOD = (WOOD+(NPPW-WDTOVR)*DT)*parameters%WDPOOL\n\n! soil carbon budgets\n\n     FASTCP = FASTCP + (RTTOVR+LFTOVR+STTOVR+WDTOVR+DIELF+DIEST)*DT  ! MB: add DIEST v3.7\n\n     FST = 2.0**( (STC(1)-283.16)/10. )\n     FSW = WROOT / (0.20+WROOT) * 0.23 / (0.23+WROOT)\n     RSSOIL = FSW * FST * parameters%MRP* MAX(0.,FASTCP*1.E-3)*12.E-6\n\n     STABLC = 0.1*RSSOIL\n     FASTCP = FASTCP - (RSSOIL + STABLC)*DT\n     STBLCP = STBLCP + STABLC*DT\n\n!  total carbon flux\n\n     CFLUX  = - CARBFX + RSLEAF + RSROOT + RSWOOD + RSSTEM &  ! MB: add RSSTEM,GRSTEM,0.9*RSSOIL v3.7\n          + 0.9*RSSOIL + GRLEAF + GRROOT + GRWOOD + GRSTEM    ! g/m2/s\n\n! for outputs\n\n     GPP    = CARBFX                                             !g/m2/s C\n     NPP    = NPPL + NPPW + NPPR +NPPS                           !g/m2/s C\n     AUTORS = RSROOT + RSWOOD  + RSLEAF + RSSTEM + &             !g/m2/s C  MB: add RSSTEM, GRSTEM v3.7\n              GRLEAF + GRROOT + GRWOOD + GRSTEM                  !g/m2/s C  MB: add 0.9* v3.7\n     HETERS = 0.9*RSSOIL                                         !g/m2/s C\n     NEE    = (AUTORS + HETERS - GPP)*44./12.                    !g/m2/s CO2\n     TOTSC  = FASTCP + STBLCP                                    !g/m2   C\n     TOTLB  = LFMASS + RTMASS +STMASS + WOOD                     !g/m2   C  MB: add STMASS v3.7\n\n! leaf area index and stem area index\n\n     XLAI    = MAX(LFMASS*LAPM,LAIMIN)\n     XSAI    = MAX(STMASS*SAPM,XSAMIN)\n\n  END SUBROUTINE CO2FLUX\n\n!== begin carbon_crop ==============================================================================\n\n SUBROUTINE CARBON_CROP (parameters,NSNOW  ,NSOIL  ,VEGTYP ,DT     ,ZSOIL  ,JULIAN , & !in\n                            DZSNSO ,STC    ,SMC    ,TV     ,PSN    ,FOLN   ,BTRAN  , & !in\n                            SOLDN  ,T2M    ,                                         & !in\n                            LFMASS ,RTMASS ,STMASS ,WOOD   ,STBLCP ,FASTCP ,GRAIN  , & !inout\n\t\t\t    XLAI   ,XSAI   ,GDD    ,                                 & !inout\n                            GPP    ,NPP    ,NEE    ,AUTORS ,HETERS ,TOTSC  ,TOTLB, PGS    ) !out\n! ------------------------------------------------------------------------------------------\n! Initial crop version created by Xing Liu\n! Initial crop version added by Barlage v3.8\n\n! ------------------------------------------------------------------------------------------\n      IMPLICIT NONE\n! ------------------------------------------------------------------------------------------\n! inputs (carbon)\n\n  type (noahmp_parameters), intent(in) :: parameters\n  INTEGER                        , INTENT(IN) :: NSNOW  !number of snow layers\n  INTEGER                        , INTENT(IN) :: NSOIL  !number of soil layers\n  INTEGER                        , INTENT(IN) :: VEGTYP !vegetation type\n  REAL                           , INTENT(IN) :: DT     !time step (s)\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: ZSOIL  !depth of layer-bottomfrom soil surface\n  REAL                           , INTENT(IN) :: JULIAN !Julian day of year(fractional) ( 0 <= JULIAN < YEARLEN )\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: DZSNSO !snow/soil layerthickness [m]\n  REAL, DIMENSION(-NSNOW+1:NSOIL), INTENT(IN) :: STC    !snow/soil temperature[k]\n  REAL, DIMENSION(       1:NSOIL), INTENT(IN) :: SMC    !soil moisture (ice +liq.) [m3/m3]\n  REAL                           , INTENT(IN) :: TV     !vegetation temperature(k)\n  REAL                           , INTENT(IN) :: PSN    !total leaf photosyn(umolco2/m2/s) [+]\n  REAL                           , INTENT(IN) :: FOLN   !foliage nitrogen (%)\n  REAL                           , INTENT(IN) :: BTRAN  !soil watertranspiration factor (0 to 1)\n  REAL                           , INTENT(IN) :: SOLDN  !Downward solar radiation\n  REAL                           , INTENT(IN) :: T2M    !air temperature\n\n! input & output (carbon)\n\n  REAL                        , INTENT(INOUT) :: LFMASS !leaf mass [g/m2]\n  REAL                        , INTENT(INOUT) :: RTMASS !mass of fine roots[g/m2]\n  REAL                        , INTENT(INOUT) :: STMASS !stem mass [g/m2]\n  REAL                        , INTENT(INOUT) :: WOOD   !mass of wood (incl.woody roots) [g/m2]\n  REAL                        , INTENT(INOUT) :: STBLCP !stable carbon in deepsoil [g/m2]\n  REAL                        , INTENT(INOUT) :: FASTCP !short-lived carbon inshallow soil [g/m2]\n  REAL                        , INTENT(INOUT) :: GRAIN  !mass of GRAIN [g/m2]\n  REAL                        , INTENT(INOUT) :: XLAI   !leaf area index [-]\n  REAL                        , INTENT(INOUT) :: XSAI   !stem area index [-]\n  REAL                        , INTENT(INOUT) :: GDD    !growing degree days\n\n! outout\n  REAL                          , INTENT(OUT) :: GPP    !net instantaneous assimilation [g/m2/s C]\n  REAL                          , INTENT(OUT) :: NPP    !net primary productivity [g/m2/s C]\n  REAL                          , INTENT(OUT) :: NEE    !net ecosystem exchange[g/m2/s CO2]\n  REAL                          , INTENT(OUT) :: AUTORS !net ecosystem respiration [g/m2/s C]\n  REAL                          , INTENT(OUT) :: HETERS !organic respiration[g/m2/s C]\n  REAL                          , INTENT(OUT) :: TOTSC  !total soil carbon [g/m2C]\n  REAL                          , INTENT(OUT) :: TOTLB  !total living carbon ([g/m2 C]\n\n! local variables\n\n  INTEGER :: J         !do-loop index\n  REAL    :: WROOT     !root zone soil water [-]\n  REAL    :: WSTRES    !water stress coeficient [-]  (1. for wilting )\n  INTEGER :: IPA       !Planting index\n  INTEGER :: IHA       !Havestindex(0=on,1=off)\n  INTEGER, INTENT(OUT) :: PGS       !Plant growth stage\n\n  REAL    :: PSNCROP\n\n! ------------------------------------------------------------------------------------------\n   IF ( ( VEGTYP == parameters%iswater ) .OR. ( VEGTYP == parameters%ISBARREN ) .OR. &\n        ( VEGTYP == parameters%ISICE ) .or. (parameters%urban_flag) ) THEN\n      XLAI   = 0.\n      XSAI   = 0.\n      GPP    = 0.\n      NPP    = 0.\n      NEE    = 0.\n      AUTORS = 0.\n      HETERS = 0.\n      TOTSC  = 0.\n      TOTLB  = 0.\n      LFMASS = 0.\n      RTMASS = 0.\n      STMASS = 0.\n      WOOD   = 0.\n      STBLCP = 0.\n      FASTCP = 0.\n      GRAIN  = 0.\n      RETURN\n   END IF\n\n! water stress\n\n\n   WSTRES  = 1.- BTRAN\n\n   WROOT  = 0.\n   DO J=1,parameters%NROOT\n     WROOT = WROOT + SMC(J)/parameters%SMCMAX(J) *  DZSNSO(J) / (-ZSOIL(parameters%NROOT))\n   ENDDO\n\n   CALL PSN_CROP     ( parameters,                           & !in\n                       SOLDN,   XLAI,    T2M,                & !in\n                       PSNCROP                             )   !out\n\n   CALL GROWING_GDD  (parameters,                           & !in\n                      T2M ,   DT,  JULIAN,                  & !in\n                      GDD ,                                 & !inout\n                      IPA ,  IHA,     PGS)                    !out\n\n   CALL CO2FLUX_CROP (parameters,                              & !in\n                      DT     ,STC(1) ,PSN    ,TV     ,WROOT  ,WSTRES ,FOLN   , & !in\n                      IPA    ,IHA    ,PGS    ,                                 & !in XING\n                      XLAI   ,XSAI   ,LFMASS ,RTMASS ,STMASS ,                 & !inout\n                      FASTCP ,STBLCP ,WOOD   ,GRAIN  ,GDD    ,                 & !inout\n                      GPP    ,NPP    ,NEE    ,AUTORS ,HETERS ,                 & !out\n                      TOTSC  ,TOTLB  )                                           !out\n\n  END SUBROUTINE CARBON_CROP\n\n!== begin co2flux_crop =============================================================================\n\n  SUBROUTINE CO2FLUX_CROP (parameters,                                              & !in\n                           DT     ,STC    ,PSN    ,TV     ,WROOT  ,WSTRES ,FOLN   , & !in\n                           IPA    ,IHA    ,PGS    ,                                 & !in XING\n                           XLAI   ,XSAI   ,LFMASS ,RTMASS ,STMASS ,                 & !inout\n                           FASTCP ,STBLCP ,WOOD   ,GRAIN  ,GDD,                     & !inout\n                           GPP    ,NPP    ,NEE    ,AUTORS ,HETERS ,                 & !out\n                           TOTSC  ,TOTLB  )                                           !out\n! -----------------------------------------------------------------------------------------\n! The original code from RE Dickinson et al.(1998) and Guo-Yue Niu(2004),\n! modified by Xing Liu, 2014.\n!\n! -----------------------------------------------------------------------------------------\n  IMPLICIT NONE\n! -----------------------------------------------------------------------------------------\n\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  REAL                           , INTENT(IN) :: DT     !time step (s)\n  REAL                           , INTENT(IN) :: STC    !soil temperature[k]\n  REAL                           , INTENT(IN) :: PSN    !total leaf photosynthesis (umolco2/m2/s)\n  REAL                           , INTENT(IN) :: TV     !leaf temperature (k)\n  REAL                           , INTENT(IN) :: WROOT  !root zone soil water\n  REAL                           , INTENT(IN) :: WSTRES !soil water stress\n  REAL                           , INTENT(IN) :: FOLN   !foliage nitrogen (%)\n  INTEGER                        , INTENT(IN) :: IPA\n  INTEGER                        , INTENT(IN) :: IHA\n  INTEGER                        , INTENT(IN) :: PGS\n\n! input and output\n\n  REAL                        , INTENT(INOUT) :: XLAI   !leaf  area index from leaf carbon [-]\n  REAL                        , INTENT(INOUT) :: XSAI   !stem area index from leaf carbon [-]\n  REAL                        , INTENT(INOUT) :: LFMASS !leaf mass [g/m2]\n  REAL                        , INTENT(INOUT) :: RTMASS !mass of fine roots [g/m2]\n  REAL                        , INTENT(INOUT) :: STMASS !stem mass [g/m2]\n  REAL                        , INTENT(INOUT) :: FASTCP !short lived carbon [g/m2]\n  REAL                        , INTENT(INOUT) :: STBLCP !stable carbon pool [g/m2]\n  REAL                        , INTENT(INOUT) :: WOOD   !mass of wood (incl. woody roots) [g/m2]\n  REAL                        , INTENT(INOUT) :: GRAIN  !mass of grain (XING) [g/m2]\n  REAL                        , INTENT(INOUT) :: GDD    !growing degree days (XING)\n\n! output\n\n  REAL                          , INTENT(OUT) :: GPP    !net instantaneous assimilation [g/m2/s]\n  REAL                          , INTENT(OUT) :: NPP    !net primary productivity [g/m2]\n  REAL                          , INTENT(OUT) :: NEE    !net ecosystem exchange (autors+heters-gpp)\n  REAL                          , INTENT(OUT) :: AUTORS !net ecosystem resp. (maintance and growth)\n  REAL                          , INTENT(OUT) :: HETERS !organic respiration\n  REAL                          , INTENT(OUT) :: TOTSC  !total soil carbon (g/m2)\n  REAL                          , INTENT(OUT) :: TOTLB  !total living carbon (g/m2)\n\n! local\n\n  REAL                   :: CFLUX    !carbon flux to atmosphere [g/m2/s]\n  REAL                   :: LFMSMN   !minimum leaf mass [g/m2]\n  REAL                   :: RSWOOD   !wood respiration [g/m2]\n  REAL                   :: RSLEAF   !leaf maintenance respiration per timestep[g/m2]\n  REAL                   :: RSROOT   !fine root respiration per time step [g/m2]\n  REAL                   :: RSGRAIN  !grain respiration [g/m2]\n  REAL                   :: NPPL     !leaf net primary productivity [g/m2/s]\n  REAL                   :: NPPR     !root net primary productivity [g/m2/s]\n  REAL                   :: NPPW     !wood net primary productivity [g/m2/s]\n  REAL                   :: NPPS     !wood net primary productivity [g/m2/s]\n  REAL                   :: NPPG     !grain net primary productivity [g/m2/s]\n  REAL                   :: DIELF    !death of leaf mass per time step [g/m2]\n\n  REAL                   :: ADDNPPLF !leaf assimil after resp. losses removed[g/m2]\n  REAL                   :: ADDNPPST !stem assimil after resp. losses removed[g/m2]\n  REAL                   :: CARBFX   !carbon assimilated per model step [g/m2]\n  REAL                   :: CBHYDRAFX!carbonhydrate assimilated per model step [g/m2]\n  REAL                   :: GRLEAF   !growth respiration rate for leaf [g/m2/s]\n  REAL                   :: GRROOT   !growth respiration rate for root [g/m2/s]\n  REAL                   :: GRWOOD   !growth respiration rate for wood [g/m2/s]\n  REAL                   :: GRSTEM   !growth respiration rate for stem [g/m2/s]\n  REAL                   :: GRGRAIN   !growth respiration rate for stem [g/m2/s]\n  REAL                   :: LEAFPT   !fraction of carbon allocated to leaves [-]\n  REAL                   :: LFDEL    !maximum  leaf mass  available to change[g/m2/s]\n  REAL                   :: LFTOVR   !stem turnover per time step [g/m2]\n  REAL                   :: STTOVR   !stem turnover per time step [g/m2]\n  REAL                   :: WDTOVR   !wood turnover per time step [g/m2]\n  REAL                   :: GRTOVR   !grainturnover per time step [g/m2]\n  REAL                   :: RSSOIL   !soil respiration per time step [g/m2]\n  REAL                   :: RTTOVR   !root carbon loss per time step by turnover[g/m2]\n  REAL                   :: STABLC   !decay rate of fast carbon to slow carbon[g/m2/s]\n  REAL                   :: WOODF    !calculated wood to root ratio [-]\n  REAL                   :: NONLEF   !fraction of carbon to root and wood [-]\n  REAL                   :: RESP     !leaf respiration [umol/m2/s]\n  REAL                   :: RSSTEM   !stem respiration [g/m2/s]\n\n  REAL                   :: FSW      !soil water factor for microbial respiration\n  REAL                   :: FST      !soil temperature factor for microbialrespiration\n  REAL                   :: FNF      !foliage nitrogen adjustemt to respiration(<= 1)\n  REAL                   :: TF       !temperature factor\n  REAL                   :: STDEL\n  REAL                   :: STMSMN\n  REAL                   :: SAPM     !stem area per unit mass (m2/g)\n  REAL                   :: DIEST\n  REAL                   :: STCONVERT   !stem to grain conversion [g/m2/s]\n  REAL                   :: RTCONVERT   !root to grain conversion [g/m2/s]\n! -------------------------- constants -------------------------------\n  REAL                   :: BF       !parameter for present wood allocation [-]\n  REAL                   :: RSWOODC  !wood respiration coeficient [1/s]\n  REAL                   :: STOVRC   !stem turnover coefficient [1/s]\n  REAL                   :: RSDRYC   !degree of drying that reduces soilrespiration [-]\n  REAL                   :: RTOVRC   !root turnover coefficient [1/s]\n  REAL                   :: WSTRC    !water stress coeficient [-]\n  REAL                   :: LAIMIN   !minimum leaf area index [m2/m2]\n  REAL                   :: XSAMIN   !minimum leaf area index [m2/m2]\n  REAL                   :: SC\n  REAL                   :: SD\n  REAL                   :: VEGFRAC\n  REAL                   :: TEMP\n\n! Respiration as a function of temperature\n\n  real :: r,x\n          r(x) = exp(0.08*(x-298.16))\n! ---------------------------------------------------------------------------------\n\n! constants\n    RSDRYC  = 40.0          !original was 40.0\n    RSWOODC = 3.0E-10       !\n    BF      = 0.90          !original was 0.90   ! carbon to roots\n    WSTRC   = 100.0\n    LAIMIN  = 0.05\n    XSAMIN  = 0.05\n\n    SAPM    = 3.*0.001      ! m2/kg -->m2/g\n    LFMSMN  = laimin/0.035\n    STMSMN  = xsamin/sapm\n! ---------------------------------------------------------------------------------\n\n! carbon assimilation\n! 1 mole -> 12 g carbon or 44 g CO2 or 30 g CH20\n\n     CARBFX     = PSN*12.e-6!*IPA   !umol co2 /m2/ s -> g/m2/s C\n     CBHYDRAFX  = PSN*30.e-6!*IPA\n\n! mainteinance respiration\n     FNF     = MIN( FOLN/MAX(1.E-06,parameters%FOLN_MX), 1.0 )\n     TF      = parameters%Q10MR**( (TV-298.16)/10. )\n     RESP    = parameters%LFMR25 * TF * FNF * XLAI  * (1.-WSTRES)  ! umol/m2/s\n     RSLEAF  = MIN((LFMASS-LFMSMN)/DT,RESP*30.e-6)                       ! g/m2/s\n     RSROOT  = parameters%RTMR25*(RTMASS*1E-3)*TF * 30.e-6         ! g/m2/s\n     RSSTEM  = parameters%STMR25*(STMASS*1E-3)*TF * 30.e-6         ! g/m2/s\n     RSGRAIN = parameters%GRAINMR25*(GRAIN*1E-3)*TF * 30.e-6       ! g/m2/s\n\n! calculate growth respiration for leaf, rtmass and grain\n\n     GRLEAF  = MAX(0.0,parameters%FRA_GR*(parameters%LFPT(PGS)*CBHYDRAFX  - RSLEAF))\n     GRSTEM  = MAX(0.0,parameters%FRA_GR*(parameters%STPT(PGS)*CBHYDRAFX  - RSSTEM))\n     GRROOT  = MAX(0.0,parameters%FRA_GR*(parameters%RTPT(PGS)*CBHYDRAFX  - RSROOT))\n     GRGRAIN = MAX(0.0,parameters%FRA_GR*(parameters%GRAINPT(PGS)*CBHYDRAFX  - RSGRAIN))\n\n! leaf turnover, stem turnover, root turnover and leaf death caused by soil\n! water and soil temperature stress\n\n     LFTOVR  = parameters%LF_OVRC(PGS)*1.E-6*LFMASS\n     RTTOVR  = parameters%RT_OVRC(PGS)*1.E-6*RTMASS\n     STTOVR  = parameters%ST_OVRC(PGS)*1.E-6*STMASS\n     SC  = EXP(-0.3*MAX(0.,TV-parameters%LEFREEZ)) * (LFMASS/120.)\n     SD  = EXP((WSTRES-1.)*WSTRC)\n     DIELF = LFMASS*1.E-6*(parameters%DILE_FW(PGS) * SD + parameters%DILE_FC(PGS)*SC)\n\n! Allocation of CBHYDRAFX to leaf, stem, root and grain at each growth stage\n\n\n     ADDNPPLF    = MAX(0.,parameters%LFPT(PGS)*CBHYDRAFX - GRLEAF-RSLEAF)\n     ADDNPPLF    = parameters%LFPT(PGS)*CBHYDRAFX - GRLEAF-RSLEAF\n     ADDNPPST    = MAX(0.,parameters%STPT(PGS)*CBHYDRAFX - GRSTEM-RSSTEM)\n     ADDNPPST    = parameters%STPT(PGS)*CBHYDRAFX - GRSTEM-RSSTEM\n\n\n! avoid reducing leaf mass below its minimum value but conserve mass\n\n     LFDEL = (LFMASS - LFMSMN)/DT\n     STDEL = (STMASS - STMSMN)/DT\n     LFTOVR  = MIN(LFTOVR,LFDEL+ADDNPPLF)\n     STTOVR  = MIN(STTOVR,STDEL+ADDNPPST)\n     DIELF = MIN(DIELF,LFDEL+ADDNPPLF-LFTOVR)\n\n! net primary productivities\n\n     NPPL   = MAX(ADDNPPLF,-LFDEL)\n     NPPL   = ADDNPPLF\n     NPPS   = MAX(ADDNPPST,-STDEL)\n     NPPS   = ADDNPPST\n     NPPR   = parameters%RTPT(PGS)*CBHYDRAFX - RSROOT - GRROOT\n     NPPG  =  parameters%GRAINPT(PGS)*CBHYDRAFX - RSGRAIN - GRGRAIN\n\n! masses of plant components\n\n     LFMASS = LFMASS + (NPPL-LFTOVR-DIELF)*DT\n     STMASS = STMASS + (NPPS-STTOVR)*DT   ! g/m2\n     RTMASS = RTMASS + (NPPR-RTTOVR)*DT\n     GRAIN =  GRAIN + NPPG*DT\n\n     GPP = CBHYDRAFX* 0.4 !!g/m2/s C  0.4=12/30, CH20 to C\n\n     STCONVERT = 0.0\n     RTCONVERT = 0.0\n     IF(PGS==6) THEN\n       STCONVERT = STMASS*(0.00005*DT/3600.0)\n       STMASS = STMASS - STCONVERT\n       RTCONVERT = RTMASS*(0.0005*DT/3600.0)\n       RTMASS = RTMASS - RTCONVERT\n       GRAIN  = GRAIN + STCONVERT + RTCONVERT\n     END IF\n\n     IF(RTMASS.LT.0.0) THEN\n       RTTOVR = NPPR\n       RTMASS = 0.0\n     ENDIF\n\n     IF(GRAIN.LT.0.0) THEN\n       GRAIN = 0.0\n     ENDIF\n\n ! soil carbon budgets\n\n!     IF(PGS == 1 .OR. PGS == 2 .OR. PGS == 8) THEN\n!       FASTCP=1000\n!     ELSE\n       FASTCP = FASTCP + (RTTOVR+LFTOVR+STTOVR+DIELF)*DT\n!     END IF\n     FST = 2.0**( (STC-283.16)/10. )\n     FSW = WROOT / (0.20+WROOT) * 0.23 / (0.23+WROOT)\n     RSSOIL = FSW * FST * parameters%MRP* MAX(0.,FASTCP*1.E-3)*12.E-6\n\n     STABLC = 0.1*RSSOIL\n     FASTCP = FASTCP - (RSSOIL + STABLC)*DT\n     STBLCP = STBLCP + STABLC*DT\n\n!  total carbon flux\n\n     CFLUX  = - CARBFX + RSLEAF + RSROOT  + RSSTEM &\n              + RSSOIL + GRLEAF + GRROOT                  ! g/m2/s 0.4=12/30, CH20 to C\n\n! for outputs\n                                                                 !g/m2/s C\n\n     NPP   = (NPPL + NPPS+ NPPR +NPPG)*0.4      !!g/m2/s C  0.4=12/30, CH20 to C\n\n\n     AUTORS = RSROOT + RSGRAIN  + RSLEAF +  &                     !g/m2/s C\n              GRLEAF + GRROOT + GRGRAIN                           !g/m2/s C\n\n     HETERS = RSSOIL                                             !g/m2/s C\n     NEE    = (AUTORS + HETERS - GPP)*44./30.                    !g/m2/s CO2\n     TOTSC  = FASTCP + STBLCP                                    !g/m2   C\n\n     TOTLB  = LFMASS + RTMASS + GRAIN\n\n! leaf area index and stem area index\n\n     XLAI    = MAX(LFMASS*parameters%BIO2LAI,LAIMIN)\n     XSAI    = MAX(STMASS*SAPM,XSAMIN)\n\n\n!After harversting\n!     IF(PGS == 8 ) THEN\n!       LFMASS = 0.62\n!       STMASS = 0\n!       GRAIN  = 0\n!     END IF\n\n!    IF(PGS == 1 .OR. PGS == 2 .OR. PGS == 8) THEN\n    IF(PGS == 8 .and. (GRAIN > 0. .or. LFMASS > 0 .or. STMASS > 0 .or. RTMASS > 0)) THEN\n     XLAI   = 0.05\n     XSAI   = 0.05\n     LFMASS = LFMSMN\n     STMASS = STMSMN\n     RTMASS = 0\n     GRAIN  = 0\n    END IF\n\nEND SUBROUTINE CO2FLUX_CROP\n\n!== begin growing_gdd ==============================================================================\n\n  SUBROUTINE GROWING_GDD (parameters,                         & !in\n                          T2M ,   DT, JULIAN,                 & !in\n                          GDD ,                               & !inout\n                          IPA,   IHA,     PGS)                  !out\n!===================================================================================================\n\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n   REAL                     , INTENT(IN)        :: T2M     !Air temperature\n   REAL                     , INTENT(IN)        :: DT      !time step (s)\n   REAL                     , INTENT(IN)        :: JULIAN  !Julian day of year (fractional) ( 0 <= JULIAN < YEARLEN )\n\n! input and output\n\n   REAL                     , INTENT(INOUT)     :: GDD     !growing degress days\n\n! output\n\n   INTEGER                  , INTENT(OUT)       :: IPA     !Planting index index(0=off, 1=on)\n   INTEGER                  , INTENT(OUT)       :: IHA     !Havestindex(0=on,1=off)\n   INTEGER                  , INTENT(OUT)       :: PGS     !Plant growth stage(1=S1,2=S2,3=S3)\n\n!local\n\n   REAL                                         :: GDDDAY    !gap bewtween GDD and GDD8\n   REAL                                         :: DAYOFS2   !DAYS in stage2\n   REAL                                         :: TDIFF     !temperature difference for growing degree days calculation\n   REAL                                         :: TC\n\n   TC = T2M - 273.15\n\n!Havestindex(0=on,1=off)\n\n   IPA = 1\n   IHA = 1\n\n!turn on/off the planting\n\n   IF(JULIAN < parameters%PLTDAY)  IPA = 0\n\n!turn on/off the harvesting\n    IF(JULIAN >= parameters%HSDAY) IHA = 0\n\n!Calculate the growing degree days\n\n    IF(TC <  parameters%GDDTBASE) THEN\n      TDIFF = 0.0\n    ELSEIF(TC >= parameters%GDDTCUT) THEN\n      TDIFF = parameters%GDDTCUT - parameters%GDDTBASE\n    ELSE\n      TDIFF = TC - parameters%GDDTBASE\n    END IF\n\n    GDD     = (GDD + TDIFF * DT / 86400.0) * IPA * IHA\n\n    GDDDAY  = GDD\n\n   ! Decide corn growth stage, based on Hybrid-Maize\n   !   PGS = 1 : Before planting\n   !   PGS = 2 : from tassel initiation to silking\n   !   PGS = 3 : from silking to effective grain filling\n   !   PGS = 4 : from effective grain filling to pysiological maturity\n   !   PGS = 5 : GDDM=1389\n   !   PGS = 6 :\n   !   PGS = 7 :\n   !   PGS = 8 :\n   !  GDDM = 1389\n   !  GDDM = 1555\n   ! GDDSK = 0.41*GDDM +145.4+150 !from hybrid-maize\n   ! GDDS1 = ((GDDSK-96)/38.9-4)*21\n   ! GDDS1 = 0.77*GDDSK\n   ! GDDS3 = GDDSK+170\n   ! GDDS3 = 170\n\n   PGS = 1                         ! MB: set PGS = 1 (for initialization during growing season when no GDD)\n\n   IF(GDDDAY > 0.0) PGS = 2\n\n   IF(GDDDAY >= parameters%GDDS1)  PGS = 3\n\n   IF(GDDDAY >= parameters%GDDS2)  PGS = 4\n\n   IF(GDDDAY >= parameters%GDDS3)  PGS = 5\n\n   IF(GDDDAY >= parameters%GDDS4)  PGS = 6\n\n   IF(GDDDAY >= parameters%GDDS5)  PGS = 7\n\n   IF(JULIAN >= parameters%HSDAY)  PGS = 8\n\n   IF(JULIAN <  parameters%PLTDAY) PGS = 1\n\nEND SUBROUTINE GROWING_GDD\n\n!== begin psn_crop =================================================================================\n\nSUBROUTINE PSN_CROP ( parameters,       & !in\n                      SOLDN, XLAI,T2M,  & !in\n                      PSNCROP        )    !out\n!===================================================================================================\n\n! input\n\n  type (noahmp_parameters), intent(in) :: parameters\n  REAL     , INTENT(IN)    :: SOLDN    ! downward solar radiation\n  REAL     , INTENT(IN)    :: XLAI     ! LAI\n  REAL     , INTENT(IN)    :: T2M      ! air temp\n  REAL     , INTENT(OUT)   :: PSNCROP  !\n\n!local\n\n  REAL                     :: PAR      ! photosynthetically active radiation (w/m2) 1 W m-2 = 0.0864 MJ m-2 day-1\n  REAL                     :: Amax     ! Maximum CO2 assimulation rate g/co2/s\n  REAL                     :: L1       ! Three Gaussian method\n  REAL                     :: L2       ! Three Gaussian method\n  REAL                     :: L3       ! Three Gaussian method\n  REAL                     :: I1       ! Three Gaussian method\n  REAL                     :: I2       ! Three Gaussian method\n  REAL                     :: I3       ! Three Gaussian method\n  REAL                     :: A1       ! Three Gaussian method\n  REAL                     :: A2       ! Three Gaussian method\n  REAL                     :: A3       ! Three Gaussian method\n  REAL                     :: A        ! CO2 Assimulation\n  REAL                     :: TC\n\n  TC = T2M - 273.15\n\n  PAR = parameters%I2PAR * SOLDN * 0.0036  !w to MJ m-2\n\n  IF(TC < parameters%TASSIM0) THEN\n    Amax = 1E-10\n  ELSEIF(TC >= parameters%TASSIM0 .and. TC < parameters%TASSIM1) THEN\n    Amax = (TC - parameters%TASSIM0) * parameters%Aref / (parameters%TASSIM1 - parameters%TASSIM0)\n  ELSEIF(TC >= parameters%TASSIM1 .and. TC < parameters%TASSIM2) THEN\n    Amax = parameters%Aref\n  ELSE\n    Amax= parameters%Aref - 0.2 * (T2M - parameters%TASSIM2)\n  ENDIF\n\n  Amax = max(amax,0.01)\n\n  IF(XLAI <= 0.05) THEN\n    L1 = 0.1127 * 0.05   !use initial LAI(0.05), avoid error\n    L2 = 0.5    * 0.05\n    L3 = 0.8873 * 0.05\n  ELSE\n    L1 = 0.1127 * XLAI\n    L2 = 0.5    * XLAI\n    L3 = 0.8873 * XLAI\n  END IF\n\n  I1 = parameters%k * PAR * exp(-parameters%k * L1)\n  I2 = parameters%k * PAR * exp(-parameters%k * L2)\n  I3 = parameters%k * PAR * exp(-parameters%k * L3)\n\n  I1 = max(I1,1E-10)\n  I2 = max(I2,1E-10)\n  I3 = max(I3,1E-10)\n\n  A1 = Amax * (1 - exp(-parameters%epsi * I1 / Amax))\n  A2 = Amax * (1 - exp(-parameters%epsi * I2 / Amax)) * 1.6\n  A3 = Amax * (1 - exp(-parameters%epsi * I3 / Amax))\n\n  IF (XLAI <= 0.05) THEN\n    A  = (A1+A2+A3) / 3.6 * 0.05\n  ELSEIF (XLAI > 0.05 .and. XLAI <= 4.0) THEN\n    A  = (A1+A2+A3) / 3.6 * XLAI\n  ELSE\n    A = (A1+A2+A3) / 3.6 * 4\n  END IF\n\n  A = A * parameters%PSNRF ! Attainable\n\n  PSNCROP = 6.313 * A   ! (1/44) * 1000000)/3600 = 6.313\n\nEND SUBROUTINE PSN_CROP\n\n!== begin bvocflux =================================================================================\n\n!  SUBROUTINE BVOCFLUX(parameters,VOCFLX,  VEGTYP,  VEGFRAC,  APAR,   TV )\n!\n! ------------------------------------------------------------------------------------------\n!      implicit none\n! ------------------------------------------------------------------------------------------\n!\n! ------------------------ code history ---------------------------\n! source file:       BVOC\n! purpose:           BVOC emissions\n! DESCRIPTION:\n! Volatile organic compound emission\n! This code simulates volatile organic compound emissions\n! following the algorithm presented in Guenther, A., 1999: Modeling\n! Biogenic Volatile Organic Compound Emissions to the Atmosphere. In\n! Reactive Hydrocarbons in the Atmosphere, Ch. 3\n! This model relies on the assumption that 90% of isoprene and monoterpene\n! emissions originate from canopy foliage:\n!    E = epsilon * gamma * density * delta\n! The factor delta (longterm activity factor) applies to isoprene emission\n! from deciduous plants only. We neglect this factor at the present time.\n! This factor is discussed in Guenther (1997).\n! Subroutine written to operate at the patch level.\n! IN FINAL IMPLEMENTATION, REMEMBER:\n! 1. may wish to call this routine only as freq. as rad. calculations\n! 2. may wish to place epsilon values directly in pft-physiology file\n! ------------------------ input/output variables -----------------\n! input\n!  integer                     ,INTENT(IN) :: vegtyp  !vegetation type\n!  real                        ,INTENT(IN) :: vegfrac !green vegetation fraction [0.0-1.0]\n!  real                        ,INTENT(IN) :: apar    !photosynthesis active energy by canopy (w/m2)\n!  real                        ,INTENT(IN) :: tv      !vegetation canopy temperature (k)\n!\n! output\n!  real                        ,INTENT(OUT) :: vocflx(5) ! voc fluxes [ug C m-2 h-1]\n!\n! Local Variables\n!\n!  real, parameter :: R      = 8.314    ! univ. gas constant [J K-1 mol-1]\n!  real, parameter :: alpha  = 0.0027   ! empirical coefficient\n!  real, parameter :: cl1    = 1.066    ! empirical coefficient\n!  real, parameter :: ct1    = 95000.0  ! empirical coefficient [J mol-1]\n!  real, parameter :: ct2    = 230000.0 ! empirical coefficient [J mol-1]\n!  real, parameter :: ct3    = 0.961    ! empirical coefficient\n!  real, parameter :: tm     = 314.0    ! empirical coefficient [K]\n!  real, parameter :: tstd   = 303.0    ! std temperature [K]\n!  real, parameter :: bet    = 0.09     ! beta empirical coefficient [K-1]\n!\n!  integer ivoc        ! do-loop index\n!  integer ityp        ! do-loop index\n!  real epsilon(5)\n!  real gamma(5)\n!  real density\n!  real elai\n!  real par,cl,reciprod,ct\n!\n! epsilon :\n!\n!    do ivoc = 1, 5\n!    epsilon(ivoc) = parameters%eps(VEGTYP,ivoc)\n!    end do\n!\n! gamma : Activity factor. Units [dimensionless]\n!\n!      reciprod = 1. / (R * tv * tstd)\n!      ct = exp(ct1 * (tv - tstd) * reciprod) / &\n!           (ct3 + exp(ct2 * (tv - tm) * reciprod))\n!\n!      par = apar * 4.6 ! (multiply w/m2 by 4.6 to get umol/m2/s)\n!      cl  = alpha * cl1 * par * (1. + alpha * alpha * par * par)**(-0.5)\n!\n!   gamma(1) = cl * ct ! for isoprenes\n!\n!   do ivoc = 2, 5\n!   gamma(ivoc) = exp(bet * (tv - tstd))\n!   end do\n!\n! Foliage density\n!\n! transform vegfrac to lai\n!\n!   elai    = max(0.0,-6.5/2.5*alog((1.-vegfrac)))\n!   density = elai / (parameters%slarea(VEGTYP) * 0.5)\n!\n! calculate the voc flux\n!\n!   do ivoc = 1, 5\n!   vocflx(ivoc) = epsilon(ivoc) * gamma(ivoc) * density\n!   end do\n!\n!   end subroutine bvocflux\n! ==================================================================================================\n! ********************************* end of carbon subroutines *****************************\n! ==================================================================================================\n\n!== begin noahmp_options ===========================================================================\n\n  subroutine noahmp_options(idveg     ,iopt_crs  ,iopt_btr  ,iopt_run  ,iopt_sfc  ,iopt_frz , &\n                             iopt_inf  ,iopt_rad  ,iopt_alb  ,iopt_snf  ,iopt_tbot, iopt_stc, &\n\t\t\t     iopt_rsf , iopt_soil, iopt_pedo, iopt_crop, iopt_imperv )\n\n  implicit none\n\n  INTEGER,  INTENT(IN) :: idveg     !dynamic vegetation (1 -> off ; 2 -> on) with opt_crs = 1\n  INTEGER,  INTENT(IN) :: iopt_crs  !canopy stomatal resistance (1-> Ball-Berry; 2->Jarvis)\n  INTEGER,  INTENT(IN) :: iopt_btr  !soil moisture factor for stomatal resistance (1-> Noah; 2-> CLM; 3-> SSiB)\n  INTEGER,  INTENT(IN) :: iopt_run  !runoff and groundwater (1->SIMGM; 2->SIMTOP; 3->Schaake96; 4->BATS)\n  INTEGER,  INTENT(IN) :: iopt_sfc  !surface layer drag coeff (CH & CM) (1->M-O; 2->Chen97)\n  INTEGER,  INTENT(IN) :: iopt_frz  !supercooled liquid water (1-> NY06; 2->Koren99)\n  INTEGER,  INTENT(IN) :: iopt_inf  !frozen soil permeability (1-> NY06; 2->Koren99)\n  INTEGER,  INTENT(IN) :: iopt_rad  !radiation transfer (1->gap=F(3D,cosz); 2->gap=0; 3->gap=1-Fveg)\n  INTEGER,  INTENT(IN) :: iopt_alb  !snow surface albedo (1->BATS; 2->CLASS)\n  INTEGER,  INTENT(IN) :: iopt_snf  !rainfall & snowfall (1-Jordan91; 2->BATS; 3->Noah)\n  INTEGER,  INTENT(IN) :: iopt_tbot !lower boundary of soil temperature (1->zero-flux; 2->Noah)\n\n  INTEGER,  INTENT(IN) :: iopt_stc  !snow/soil temperature time scheme (only layer 1)\n                                    ! 1 -> semi-implicit; 2 -> full implicit (original Noah)\n  INTEGER,  INTENT(IN) :: iopt_rsf  !surface resistance (1->Sakaguchi/Zeng; 2->Seller; 3->mod Sellers; 4->1+snow)\n  INTEGER,  INTENT(IN) :: iopt_soil !soil parameters set-up option\n  INTEGER,  INTENT(IN) :: iopt_pedo !pedo-transfer function (1->Saxton and Rawls)\n  INTEGER,  INTENT(IN) :: iopt_crop !crop model option (0->none; 1->Liu et al.)\n  INTEGER,  INTENT(IN) :: iopt_imperv !imperviousness infiltration adjustment (0->none; 1->total imperviousness;\n                                           !2->Alley&Veenhuis)\n\n! -------------------------------------------------------------------------------------------------\n\n  dveg = idveg\n\n  opt_crs  = iopt_crs\n  opt_btr  = iopt_btr\n  opt_run  = iopt_run\n  opt_sfc  = iopt_sfc\n  opt_frz  = iopt_frz\n  opt_inf  = iopt_inf\n  opt_rad  = iopt_rad\n  opt_alb  = iopt_alb\n  opt_snf  = iopt_snf\n  opt_tbot = iopt_tbot\n  opt_stc  = iopt_stc\n  opt_rsf  = iopt_rsf\n  opt_soil = iopt_soil\n  opt_pedo = iopt_pedo\n  opt_crop = iopt_crop\n  opt_imperv = iopt_imperv\n\n  end subroutine noahmp_options\n\nEND MODULE MODULE_SF_NOAHMPLSM\n\nMODULE NOAHMP_TABLES\n\n    IMPLICIT NONE\n\n    INTEGER, PRIVATE, PARAMETER :: MVT   = 27\n    INTEGER, PRIVATE, PARAMETER :: MBAND = 2\n    INTEGER, PRIVATE, PARAMETER :: MSC   = 8\n    INTEGER, PRIVATE, PARAMETER :: MAX_SOILTYP = 30\n    INTEGER, PRIVATE, PARAMETER :: NCROP = 5\n    INTEGER, PRIVATE, PARAMETER :: NSTAGE = 8\n\n! MPTABLE.TBL vegetation parameters\n\n    INTEGER :: ISURBAN_TABLE\n    INTEGER :: ISWATER_TABLE\n    INTEGER :: ISBARREN_TABLE\n    INTEGER :: ISICE_TABLE\n    INTEGER :: ISCROP_TABLE\n    INTEGER :: EBLFOREST_TABLE\n    INTEGER :: NATURAL_TABLE\n    INTEGER :: LOW_DENSITY_RESIDENTIAL_TABLE\n    INTEGER :: HIGH_DENSITY_RESIDENTIAL_TABLE\n    INTEGER :: HIGH_INTENSITY_INDUSTRIAL_TABLE\n\n    REAL :: CH2OP_TABLE(MVT)       !maximum intercepted h2o per unit lai+sai (mm)\n    REAL :: DLEAF_TABLE(MVT)       !characteristic leaf dimension (m)\n    REAL :: Z0MVT_TABLE(MVT)       !momentum roughness length (m)\n    REAL :: HVT_TABLE(MVT)         !top of canopy (m)\n    REAL :: HVB_TABLE(MVT)         !bottom of canopy (m)\n    REAL :: DEN_TABLE(MVT)         !tree density (no. of trunks per m2)\n    REAL :: RC_TABLE(MVT)          !tree crown radius (m)\n    REAL :: MFSNO_TABLE(MVT)       !snowmelt curve parameter ()\n    REAL :: SAIM_TABLE(MVT,12)     !monthly stem area index, one-sided\n    REAL :: LAIM_TABLE(MVT,12)     !monthly leaf area index, one-sided\n    REAL :: SLA_TABLE(MVT)         !single-side leaf area per Kg [m2/kg]\n    REAL :: DILEFC_TABLE(MVT)      !coeficient for leaf stress death [1/s]\n    REAL :: DILEFW_TABLE(MVT)      !coeficient for leaf stress death [1/s]\n    REAL :: FRAGR_TABLE(MVT)       !fraction of growth respiration  !original was 0.3\n    REAL :: LTOVRC_TABLE(MVT)      !leaf turnover [1/s]\n\n    REAL :: C3PSN_TABLE(MVT)       !photosynthetic pathway: 0. = c4, 1. = c3\n    REAL :: KC25_TABLE(MVT)        !co2 michaelis-menten constant at 25c (pa)\n    REAL :: AKC_TABLE(MVT)         !q10 for kc25\n    REAL :: KO25_TABLE(MVT)        !o2 michaelis-menten constant at 25c (pa)\n    REAL :: AKO_TABLE(MVT)         !q10 for ko25\n    REAL :: VCMX25_TABLE(MVT)      !maximum rate of carboxylation at 25c (umol co2/m**2/s)\n    REAL :: AVCMX_TABLE(MVT)       !q10 for vcmx25\n    REAL :: BP_TABLE(MVT)          !minimum leaf conductance (umol/m**2/s)\n    REAL :: MP_TABLE(MVT)          !slope of conductance-to-photosynthesis relationship\n    REAL :: QE25_TABLE(MVT)        !quantum efficiency at 25c (umol co2 / umol photon)\n    REAL :: AQE_TABLE(MVT)         !q10 for qe25\n    REAL :: RMF25_TABLE(MVT)       !leaf maintenance respiration at 25c (umol co2/m**2/s)\n    REAL :: RMS25_TABLE(MVT)       !stem maintenance respiration at 25c (umol co2/kg bio/s)\n    REAL :: RMR25_TABLE(MVT)       !root maintenance respiration at 25c (umol co2/kg bio/s)\n    REAL :: ARM_TABLE(MVT)         !q10 for maintenance respiration\n    REAL :: FOLNMX_TABLE(MVT)      !foliage nitrogen concentration when f(n)=1 (%)\n    REAL :: TMIN_TABLE(MVT)        !minimum temperature for photosynthesis (k)\n\n    REAL :: XL_TABLE(MVT)          !leaf/stem orientation index\n    REAL :: RHOL_TABLE(MVT,MBAND)  !leaf reflectance: 1=vis, 2=nir\n    REAL :: RHOS_TABLE(MVT,MBAND)  !stem reflectance: 1=vis, 2=nir\n    REAL :: TAUL_TABLE(MVT,MBAND)  !leaf transmittance: 1=vis, 2=nir\n    REAL :: TAUS_TABLE(MVT,MBAND)  !stem transmittance: 1=vis, 2=nir\n\n    REAL :: MRP_TABLE(MVT)         !microbial respiration parameter (umol co2 /kg c/ s)\n    REAL :: CWPVT_TABLE(MVT)       !empirical canopy wind parameter\n\n    REAL :: WRRAT_TABLE(MVT)       !wood to non-wood ratio\n    REAL :: WDPOOL_TABLE(MVT)      !wood pool (switch 1 or 0) depending on woody or not [-]\n    REAL :: TDLEF_TABLE(MVT)       !characteristic T for leaf freezing [K]\n\n    REAL :: NROOT_TABLE(MVT)       !number of soil layers with root present\n    REAL :: RGL_TABLE(MVT)         !Parameter used in radiation stress function\n    REAL :: RS_TABLE(MVT)          !Minimum stomatal resistance [s m-1]\n    REAL :: HS_TABLE(MVT)          !Parameter used in vapor pressure deficit function\n    REAL :: TOPT_TABLE(MVT)        !Optimum transpiration air temperature [K]\n    REAL :: RSMAX_TABLE(MVT)       !Maximal stomatal resistance [s m-1]\n\n! SOILPARM.TBL parameters\n\n    INTEGER            :: SLCATS\n\n    REAL :: BEXP_TABLE(MAX_SOILTYP)        !maximum intercepted h2o per unit lai+sai (mm)\n    REAL :: SMCDRY_TABLE(MAX_SOILTYP)      !characteristic leaf dimension (m)\n    REAL :: F1_TABLE(MAX_SOILTYP)          !momentum roughness length (m)\n    REAL :: SMCMAX_TABLE(MAX_SOILTYP)      !top of canopy (m)\n    REAL :: SMCREF_TABLE(MAX_SOILTYP)      !bottom of canopy (m)\n    REAL :: PSISAT_TABLE(MAX_SOILTYP)      !tree density (no. of trunks per m2)\n    REAL :: DKSAT_TABLE(MAX_SOILTYP)       !tree crown radius (m)\n    REAL :: DWSAT_TABLE(MAX_SOILTYP)       !monthly stem area index, one-sided\n    REAL :: SMCWLT_TABLE(MAX_SOILTYP)      !monthly leaf area index, one-sided\n    REAL :: QUARTZ_TABLE(MAX_SOILTYP)      !single-side leaf area per Kg [m2/kg]\n    REAL :: AXAJ_TABLE(MAX_SOILTYP)        !Xinanjiang: Tension water distribution inflection parameter [-]\n    REAL :: BXAJ_TABLE(MAX_SOILTYP)        !Xinanjiang: Tension water distribution shape parameter [-]\n    REAL :: XXAJ_TABLE(MAX_SOILTYP)        !Xinanjiang: Free water distribution shape parameter [-]\n! GENPARM.TBL parameters\n\n    REAL :: SLOPE_TABLE(9)    !slope factor for soil drainage\n\n    REAL :: CSOIL_TABLE       !Soil heat capacity [J m-3 K-1]\n    REAL :: REFDK_TABLE       !Parameter in the surface runoff parameterization\n    REAL :: REFKDT_TABLE      !Parameter in the surface runoff parameterization\n    REAL :: FRZK_TABLE        !Frozen ground parameter\n    REAL :: ZBOT_TABLE        !Depth [m] of lower boundary soil temperature\n    REAL :: CZIL_TABLE        !Parameter used in the calculation of the roughness length for heat\n\n! MPTABLE.TBL radiation parameters\n\n    REAL :: ALBSAT_TABLE(MSC,MBAND)   !saturated soil albedos: 1=vis, 2=nir\n    REAL :: ALBDRY_TABLE(MSC,MBAND)   !dry soil albedos: 1=vis, 2=nir\n    REAL :: ALBICE_TABLE(MBAND)       !albedo land ice: 1=vis, 2=nir\n    REAL :: ALBLAK_TABLE(MBAND)       !albedo frozen lakes: 1=vis, 2=nir\n    REAL :: OMEGAS_TABLE(MBAND)       !two-stream parameter omega for snow\n    REAL :: BETADS_TABLE              !two-stream parameter betad for snow\n    REAL :: BETAIS_TABLE              !two-stream parameter betad for snow\n    REAL :: EG_TABLE(2)               !emissivity\n\n! MPTABLE.TBL global parameters\n\n    REAL :: CO2_TABLE      !co2 partial pressure\n    REAL :: O2_TABLE       !o2 partial pressure\n    REAL :: TIMEAN_TABLE   !gridcell mean topgraphic index (global mean)\n    REAL :: FSATMX_TABLE   !maximum surface saturated fraction (global mean)\n    REAL :: Z0SNO_TABLE    !snow surface roughness length (m) (0.002)\n    REAL :: SSI_TABLE      !liquid water holding capacity for snowpack (m3/m3) (0.03)\n    REAL :: SNOW_RET_FAC_TABLE !snowpack water release timescale factor (1/s)\n    REAL :: SWEMX_TABLE    !new snow mass to fully cover old snow (mm)\n    REAL :: TAU0_TABLE          !tau0 from Yang97 eqn. 10a\n    REAL :: GRAIN_GROWTH_TABLE  !growth from vapor diffusion Yang97 eqn. 10b\n    REAL :: EXTRA_GROWTH_TABLE  !extra growth near freezing Yang97 eqn. 10c\n    REAL :: DIRT_SOOT_TABLE     !dirt and soot term Yang97 eqn. 10d\n    REAL :: BATS_COSZ_TABLE     !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n    REAL :: BATS_VIS_NEW_TABLE  !new snow visible albedo\n    REAL :: BATS_NIR_NEW_TABLE  !new snow NIR albedo\n    REAL :: BATS_VIS_AGE_TABLE  !age factor for diffuse visible snow albedo Yang97 eqn. 17\n    REAL :: BATS_NIR_AGE_TABLE  !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n    REAL :: BATS_VIS_DIR_TABLE  !cosz factor for direct visible snow albedo Yang97 eqn. 15\n    REAL :: BATS_NIR_DIR_TABLE  !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n    REAL :: RSURF_SNOW_TABLE    !surface resistance for snow(s/m)\n    REAL :: RSURF_EXP_TABLE    !exponent in the shape parameter for soil resistance option 1\n    REAL :: IMPERV_URBAN_TABLE  !imperviousness fraction\n    REAL :: SCAMAX_TABLE        !maximum fractional snow covered area (0.0-1.0)\n    REAL :: SWE_LIMIT_TABLE     !maximum SWE limit (mm)\n\n! MPTABLE.TBL crop parameters\n\n INTEGER :: DEFAULT_CROP_TABLE          ! Default crop index\n INTEGER :: PLTDAY_TABLE(NCROP)         ! Planting date\n INTEGER :: HSDAY_TABLE(NCROP)          ! Harvest date\n    REAL :: PLANTPOP_TABLE(NCROP)       ! Plant density [per ha] - used?\n    REAL :: IRRI_TABLE(NCROP)           ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n\n    REAL :: GDDTBASE_TABLE(NCROP)       ! Base temperature for GDD accumulation [C]\n    REAL :: GDDTCUT_TABLE(NCROP)        ! Upper temperature for GDD accumulation [C]\n    REAL :: GDDS1_TABLE(NCROP)          ! GDD from seeding to emergence\n    REAL :: GDDS2_TABLE(NCROP)          ! GDD from seeding to initial vegetative\n    REAL :: GDDS3_TABLE(NCROP)          ! GDD from seeding to post vegetative\n    REAL :: GDDS4_TABLE(NCROP)          ! GDD from seeding to intial reproductive\n    REAL :: GDDS5_TABLE(NCROP)          ! GDD from seeding to pysical maturity\n\n INTEGER :: C3C4_TABLE(NCROP)           ! photosynthetic pathway:  1. = c3 2. = c4\n    REAL :: AREF_TABLE(NCROP)           ! reference maximum CO2 assimulation rate\n    REAL :: PSNRF_TABLE(NCROP)          ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\n    REAL :: I2PAR_TABLE(NCROP)          ! Fraction of incoming solar radiation to photosynthetically active radiation\n    REAL :: TASSIM0_TABLE(NCROP)        ! Minimum temperature for CO2 assimulation [C]\n    REAL :: TASSIM1_TABLE(NCROP)        ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\n    REAL :: TASSIM2_TABLE(NCROP)        ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\n    REAL :: K_TABLE(NCROP)              ! light extinction coefficient\n    REAL :: EPSI_TABLE(NCROP)           ! initial light use efficiency\n\n    REAL :: Q10MR_TABLE(NCROP)          ! q10 for maintainance respiration\n    REAL :: FOLN_MX_TABLE(NCROP)        ! foliage nitrogen concentration when f(n)=1 (%)\n    REAL :: LEFREEZ_TABLE(NCROP)        ! characteristic T for leaf freezing [K]\n\n    REAL :: DILE_FC_TABLE(NCROP,NSTAGE) ! coeficient for temperature leaf stress death [1/s]\n    REAL :: DILE_FW_TABLE(NCROP,NSTAGE) ! coeficient for water leaf stress death [1/s]\n    REAL :: FRA_GR_TABLE(NCROP)         ! fraction of growth respiration\n\n    REAL :: LF_OVRC_TABLE(NCROP,NSTAGE) ! fraction of leaf turnover  [1/s]\n    REAL :: ST_OVRC_TABLE(NCROP,NSTAGE) ! fraction of stem turnover  [1/s]\n    REAL :: RT_OVRC_TABLE(NCROP,NSTAGE) ! fraction of root tunrover  [1/s]\n    REAL :: LFMR25_TABLE(NCROP)         !  leaf maintenance respiration at 25C [umol CO2/m**2  /s]\n    REAL :: STMR25_TABLE(NCROP)         !  stem maintenance respiration at 25C [umol CO2/kg bio/s]\n    REAL :: RTMR25_TABLE(NCROP)         !  root maintenance respiration at 25C [umol CO2/kg bio/s]\n    REAL :: GRAINMR25_TABLE(NCROP)      ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n\n    REAL :: LFPT_TABLE(NCROP,NSTAGE)    ! fraction of carbohydrate flux to leaf\n    REAL :: STPT_TABLE(NCROP,NSTAGE)    ! fraction of carbohydrate flux to stem\n    REAL :: RTPT_TABLE(NCROP,NSTAGE)    ! fraction of carbohydrate flux to root\n    REAL :: GRAINPT_TABLE(NCROP,NSTAGE) ! fraction of carbohydrate flux to grain\n    REAL :: BIO2LAI_TABLE(NCROP)        ! leaf are per living leaf biomass [m^2/kg]\n\n! MPTABLE.TBL optional parameters\n\n    REAL :: sr2006_theta_1500t_a        ! sand coefficient\n    REAL :: sr2006_theta_1500t_b        ! clay coefficient\n    REAL :: sr2006_theta_1500t_c        ! orgm coefficient\n    REAL :: sr2006_theta_1500t_d        ! sand*orgm coefficient\n    REAL :: sr2006_theta_1500t_e        ! clay*orgm coefficient\n    REAL :: sr2006_theta_1500t_f        ! sand*clay coefficient\n    REAL :: sr2006_theta_1500t_g        ! constant adjustment\n\n    REAL :: sr2006_theta_1500_a         ! theta_1500t coefficient\n    REAL :: sr2006_theta_1500_b         ! constant adjustment\n\n    REAL :: sr2006_theta_33t_a          ! sand coefficient\n    REAL :: sr2006_theta_33t_b          ! clay coefficient\n    REAL :: sr2006_theta_33t_c          ! orgm coefficient\n    REAL :: sr2006_theta_33t_d          ! sand*orgm coefficient\n    REAL :: sr2006_theta_33t_e          ! clay*orgm coefficient\n    REAL :: sr2006_theta_33t_f          ! sand*clay coefficient\n    REAL :: sr2006_theta_33t_g          ! constant adjustment\n\n    REAL :: sr2006_theta_33_a           ! theta_33t*theta_33t coefficient\n    REAL :: sr2006_theta_33_b           ! theta_33t coefficient\n    REAL :: sr2006_theta_33_c           ! constant adjustment\n\n    REAL :: sr2006_theta_s33t_a         ! sand coefficient\n    REAL :: sr2006_theta_s33t_b         ! clay coefficient\n    REAL :: sr2006_theta_s33t_c         ! orgm coefficient\n    REAL :: sr2006_theta_s33t_d         ! sand*orgm coefficient\n    REAL :: sr2006_theta_s33t_e         ! clay*orgm coefficient\n    REAL :: sr2006_theta_s33t_f         ! sand*clay coefficient\n    REAL :: sr2006_theta_s33t_g         ! constant adjustment\n\n    REAL :: sr2006_theta_s33_a          ! theta_s33t coefficient\n    REAL :: sr2006_theta_s33_b          ! constant adjustment\n\n    REAL :: sr2006_psi_et_a             ! sand coefficient\n    REAL :: sr2006_psi_et_b             ! clay coefficient\n    REAL :: sr2006_psi_et_c             ! theta_s33 coefficient\n    REAL :: sr2006_psi_et_d             ! sand*theta_s33 coefficient\n    REAL :: sr2006_psi_et_e             ! clay*theta_s33 coefficient\n    REAL :: sr2006_psi_et_f             ! sand*clay coefficient\n    REAL :: sr2006_psi_et_g             ! constant adjustment\n\n    REAL :: sr2006_psi_e_a              ! psi_et*psi_et coefficient\n    REAL :: sr2006_psi_e_b              ! psi_et coefficient\n    REAL :: sr2006_psi_e_c              ! constant adjustment\n\n    REAL :: sr2006_smcmax_a             ! sand adjustment\n    REAL :: sr2006_smcmax_b             ! constant adjustment\n\nCONTAINS\n\n  subroutine read_mp_veg_parameters(DATASET_IDENTIFIER)\n    implicit none\n    character(len=*), intent(in) :: DATASET_IDENTIFIER\n    integer :: ierr\n    INTEGER :: IK,IM\n    logical :: file_named\n\n    integer :: NVEG\n    character(len=256) :: VEG_DATASET_DESCRIPTION\n\n    INTEGER :: ISURBAN\n    INTEGER :: ISWATER\n    INTEGER :: ISBARREN\n    INTEGER :: ISICE\n    INTEGER :: ISCROP\n    INTEGER :: EBLFOREST\n    INTEGER :: NATURAL\n    INTEGER :: LOW_DENSITY_RESIDENTIAL\n    INTEGER :: HIGH_DENSITY_RESIDENTIAL\n    INTEGER :: HIGH_INTENSITY_INDUSTRIAL\n\n    REAL, DIMENSION(MVT) :: SAI_JAN,SAI_FEB,SAI_MAR,SAI_APR,SAI_MAY,SAI_JUN, &\n                                     SAI_JUL,SAI_AUG,SAI_SEP,SAI_OCT,SAI_NOV,SAI_DEC\n    REAL, DIMENSION(MVT) :: LAI_JAN,LAI_FEB,LAI_MAR,LAI_APR,LAI_MAY,LAI_JUN, &\n                                     LAI_JUL,LAI_AUG,LAI_SEP,LAI_OCT,LAI_NOV,LAI_DEC\n    REAL, DIMENSION(MVT) :: RHOL_VIS, RHOL_NIR, RHOS_VIS, RHOS_NIR, &\n                                     TAUL_VIS, TAUL_NIR, TAUS_VIS, TAUS_NIR\n    REAL, DIMENSION(MVT) :: CH2OP, DLEAF, Z0MVT, HVT, HVB, DEN, RC, MFSNO, XL, CWPVT, C3PSN, KC25, AKC, KO25, AKO, &\n                     AVCMX, AQE, LTOVRC,  DILEFC,  DILEFW,  RMF25 ,  SLA   ,  FRAGR ,  TMIN  ,  VCMX25,  TDLEF ,  &\n                     BP, MP, QE25, RMS25, RMR25, ARM, FOLNMX, WDPOOL, WRRAT, MRP, NROOT, RGL, RS, HS, TOPT, RSMAX, &\n\t\t     SLAREA, EPS1, EPS2, EPS3, EPS4, EPS5\n\n    NAMELIST / noahmp_usgs_veg_categories / VEG_DATASET_DESCRIPTION, NVEG\n    NAMELIST / noahmp_usgs_parameters / ISURBAN, ISWATER, ISBARREN, ISICE, ISCROP, EBLFOREST, NATURAL, &\n         LOW_DENSITY_RESIDENTIAL, HIGH_DENSITY_RESIDENTIAL, HIGH_INTENSITY_INDUSTRIAL, &\n         CH2OP, DLEAF, Z0MVT, HVT, HVB, DEN, RC, MFSNO, XL, CWPVT, C3PSN, KC25, AKC, KO25, AKO, AVCMX, AQE, &\n         LTOVRC,  DILEFC,  DILEFW,  RMF25 ,  SLA   ,  FRAGR ,  TMIN  ,  VCMX25,  TDLEF ,  BP, MP, QE25, RMS25, RMR25, ARM, &\n         FOLNMX, WDPOOL, WRRAT, MRP, NROOT, RGL, RS, HS, TOPT, RSMAX, &\n         SAI_JAN, SAI_FEB, SAI_MAR, SAI_APR, SAI_MAY, SAI_JUN,SAI_JUL,SAI_AUG,SAI_SEP,SAI_OCT,SAI_NOV,SAI_DEC, &\n         LAI_JAN, LAI_FEB, LAI_MAR, LAI_APR, LAI_MAY, LAI_JUN,LAI_JUL,LAI_AUG,LAI_SEP,LAI_OCT,LAI_NOV,LAI_DEC, &\n         RHOL_VIS, RHOL_NIR, RHOS_VIS, RHOS_NIR, TAUL_VIS, TAUL_NIR, TAUS_VIS, TAUS_NIR, SLAREA, EPS1, EPS2, EPS3, EPS4, EPS5\n\n    NAMELIST / noahmp_modis_veg_categories / VEG_DATASET_DESCRIPTION, NVEG\n    NAMELIST / noahmp_modis_parameters / ISURBAN, ISWATER, ISBARREN, ISICE, ISCROP, EBLFOREST, NATURAL, &\n         LOW_DENSITY_RESIDENTIAL, HIGH_DENSITY_RESIDENTIAL, HIGH_INTENSITY_INDUSTRIAL, &\n         CH2OP, DLEAF, Z0MVT, HVT, HVB, DEN, RC, MFSNO, XL, CWPVT, C3PSN, KC25, AKC, KO25, AKO, AVCMX, AQE, &\n         LTOVRC,  DILEFC,  DILEFW,  RMF25 ,  SLA   ,  FRAGR ,  TMIN  ,  VCMX25,  TDLEF ,  BP, MP, QE25, RMS25, RMR25, ARM, &\n         FOLNMX, WDPOOL, WRRAT, MRP, NROOT, RGL, RS, HS, TOPT, RSMAX, &\n         SAI_JAN, SAI_FEB, SAI_MAR, SAI_APR, SAI_MAY, SAI_JUN,SAI_JUL,SAI_AUG,SAI_SEP,SAI_OCT,SAI_NOV,SAI_DEC, &\n         LAI_JAN, LAI_FEB, LAI_MAR, LAI_APR, LAI_MAY, LAI_JUN,LAI_JUL,LAI_AUG,LAI_SEP,LAI_OCT,LAI_NOV,LAI_DEC, &\n         RHOL_VIS, RHOL_NIR, RHOS_VIS, RHOS_NIR, TAUL_VIS, TAUL_NIR, TAUS_VIS, TAUS_NIR, SLAREA, EPS1, EPS2, EPS3, EPS4, EPS5\n\n    ! Initialize our variables to bad values, so that if the namelist read fails, we come to a screeching halt as soon as we try to use anything.\n    CH2OP_TABLE  = -1.E36\n    DLEAF_TABLE  = -1.E36\n    Z0MVT_TABLE  = -1.E36\n    HVT_TABLE    = -1.E36\n    HVB_TABLE    = -1.E36\n    DEN_TABLE    = -1.E36\n    RC_TABLE     = -1.E36\n    MFSNO_TABLE  = -1.E36\n    RHOL_TABLE   = -1.E36\n    RHOS_TABLE   = -1.E36\n    TAUL_TABLE   = -1.E36\n    TAUS_TABLE   = -1.E36\n    XL_TABLE     = -1.E36\n    CWPVT_TABLE  = -1.E36\n    C3PSN_TABLE  = -1.E36\n    KC25_TABLE   = -1.E36\n    AKC_TABLE    = -1.E36\n    KO25_TABLE   = -1.E36\n    AKO_TABLE    = -1.E36\n    AVCMX_TABLE  = -1.E36\n    AQE_TABLE    = -1.E36\n    LTOVRC_TABLE = -1.E36\n    DILEFC_TABLE = -1.E36\n    DILEFW_TABLE = -1.E36\n    RMF25_TABLE  = -1.E36\n    SLA_TABLE    = -1.E36\n    FRAGR_TABLE  = -1.E36\n    TMIN_TABLE   = -1.E36\n    VCMX25_TABLE = -1.E36\n    TDLEF_TABLE  = -1.E36\n    BP_TABLE     = -1.E36\n    MP_TABLE     = -1.E36\n    QE25_TABLE   = -1.E36\n    RMS25_TABLE  = -1.E36\n    RMR25_TABLE  = -1.E36\n    ARM_TABLE    = -1.E36\n    FOLNMX_TABLE = -1.E36\n    WDPOOL_TABLE = -1.E36\n    WRRAT_TABLE  = -1.E36\n    MRP_TABLE    = -1.E36\n    SAIM_TABLE   = -1.E36\n    LAIM_TABLE   = -1.E36\n    NROOT_TABLE  = -1.E36\n    RGL_TABLE    = -1.E36\n    RS_TABLE     = -1.E36\n    HS_TABLE     = -1.E36\n    TOPT_TABLE   = -1.E36\n    RSMAX_TABLE  = -1.E36\n    ISURBAN_TABLE      = -99999\n    ISWATER_TABLE      = -99999\n    ISBARREN_TABLE     = -99999\n    ISICE_TABLE        = -99999\n    ISCROP_TABLE       = -99999\n    EBLFOREST_TABLE    = -99999\n    NATURAL_TABLE      = -99999\n    LOW_DENSITY_RESIDENTIAL_TABLE   = -99999\n    HIGH_DENSITY_RESIDENTIAL_TABLE  = -99999\n    HIGH_INTENSITY_INDUSTRIAL_TABLE = -99999\n\n    inquire( file='MPTABLE.TBL', exist=file_named )\n    if ( file_named ) then\n      open(15, file=\"MPTABLE.TBL\", status='old', form='formatted', action='read', iostat=ierr)\n    else\n      open(15, status='old', form='formatted', action='read', iostat=ierr)\n    end if\n\n    if (ierr /= 0) then\n       write(*,'(\"WARNING: Cannot find file MPTABLE.TBL\")')\n       call wrf_error_fatal(\"STOP in Noah-MP read_mp_veg_parameters\")\n    endif\n\n    if ( trim(DATASET_IDENTIFIER) == \"USGS\" ) then\n       read(15,noahmp_usgs_veg_categories)\n       read(15,noahmp_usgs_parameters)\n    else if ( trim(DATASET_IDENTIFIER) == \"MODIFIED_IGBP_MODIS_NOAH\" ) then\n       read(15,noahmp_modis_veg_categories)\n       read(15,noahmp_modis_parameters)\n    else\n       write(*,'(\"WARNING: Unrecognized DATASET_IDENTIFIER in subroutine READ_MP_VEG_PARAMETERS\")')\n       write(*,'(\"WARNING: DATASET_IDENTIFIER = ''\", A, \"''\")') trim(DATASET_IDENTIFIER)\n       call wrf_error_fatal(\"STOP in Noah-MP read_mp_veg_parameters\")\n    endif\n    close(15)\n\n                      ISURBAN_TABLE   = ISURBAN\n                      ISWATER_TABLE   = ISWATER\n                     ISBARREN_TABLE   = ISBARREN\n                        ISICE_TABLE   = ISICE\n                       ISCROP_TABLE   = ISCROP\n                    EBLFOREST_TABLE   = EBLFOREST\n                      NATURAL_TABLE   = NATURAL\n      LOW_DENSITY_RESIDENTIAL_TABLE   = LOW_DENSITY_RESIDENTIAL\n     HIGH_DENSITY_RESIDENTIAL_TABLE   = HIGH_DENSITY_RESIDENTIAL\n    HIGH_INTENSITY_INDUSTRIAL_TABLE   = HIGH_INTENSITY_INDUSTRIAL\n\n     CH2OP_TABLE(1:NVEG)  = CH2OP(1:NVEG)\n     DLEAF_TABLE(1:NVEG)  = DLEAF(1:NVEG)\n     Z0MVT_TABLE(1:NVEG)  = Z0MVT(1:NVEG)\n       HVT_TABLE(1:NVEG)  = HVT(1:NVEG)\n       HVB_TABLE(1:NVEG)  = HVB(1:NVEG)\n       DEN_TABLE(1:NVEG)  = DEN(1:NVEG)\n        RC_TABLE(1:NVEG)  = RC(1:NVEG)\n     MFSNO_TABLE(1:NVEG)  = MFSNO(1:NVEG)\n        XL_TABLE(1:NVEG)  = XL(1:NVEG)\n     CWPVT_TABLE(1:NVEG)  = CWPVT(1:NVEG)\n     C3PSN_TABLE(1:NVEG)  = C3PSN(1:NVEG)\n      KC25_TABLE(1:NVEG)  = KC25(1:NVEG)\n       AKC_TABLE(1:NVEG)  = AKC(1:NVEG)\n      KO25_TABLE(1:NVEG)  = KO25(1:NVEG)\n       AKO_TABLE(1:NVEG)  = AKO(1:NVEG)\n     AVCMX_TABLE(1:NVEG)  = AVCMX(1:NVEG)\n       AQE_TABLE(1:NVEG)  = AQE(1:NVEG)\n    LTOVRC_TABLE(1:NVEG)  = LTOVRC(1:NVEG)\n    DILEFC_TABLE(1:NVEG)  = DILEFC(1:NVEG)\n    DILEFW_TABLE(1:NVEG)  = DILEFW(1:NVEG)\n     RMF25_TABLE(1:NVEG)  = RMF25(1:NVEG)\n       SLA_TABLE(1:NVEG)  = SLA(1:NVEG)\n     FRAGR_TABLE(1:NVEG)  = FRAGR(1:NVEG)\n      TMIN_TABLE(1:NVEG)  = TMIN(1:NVEG)\n    VCMX25_TABLE(1:NVEG)  = VCMX25(1:NVEG)\n     TDLEF_TABLE(1:NVEG)  = TDLEF(1:NVEG)\n        BP_TABLE(1:NVEG)  = BP(1:NVEG)\n        MP_TABLE(1:NVEG)  = MP(1:NVEG)\n      QE25_TABLE(1:NVEG)  = QE25(1:NVEG)\n     RMS25_TABLE(1:NVEG)  = RMS25(1:NVEG)\n     RMR25_TABLE(1:NVEG)  = RMR25(1:NVEG)\n       ARM_TABLE(1:NVEG)  = ARM(1:NVEG)\n    FOLNMX_TABLE(1:NVEG)  = FOLNMX(1:NVEG)\n    WDPOOL_TABLE(1:NVEG)  = WDPOOL(1:NVEG)\n     WRRAT_TABLE(1:NVEG)  = WRRAT(1:NVEG)\n       MRP_TABLE(1:NVEG)  = MRP(1:NVEG)\n     NROOT_TABLE(1:NVEG)  = NROOT(1:NVEG)\n       RGL_TABLE(1:NVEG)  = RGL(1:NVEG)\n        RS_TABLE(1:NVEG)  = RS(1:NVEG)\n        HS_TABLE(1:NVEG)  = HS(1:NVEG)\n      TOPT_TABLE(1:NVEG)  = TOPT(1:NVEG)\n     RSMAX_TABLE(1:NVEG)  = RSMAX(1:NVEG)\n\n    ! Put LAI and SAI into 2d array from monthly lines in table; same for canopy radiation properties\n\n    SAIM_TABLE(1:NVEG, 1) = SAI_JAN(1:NVEG)\n    SAIM_TABLE(1:NVEG, 2) = SAI_FEB(1:NVEG)\n    SAIM_TABLE(1:NVEG, 3) = SAI_MAR(1:NVEG)\n    SAIM_TABLE(1:NVEG, 4) = SAI_APR(1:NVEG)\n    SAIM_TABLE(1:NVEG, 5) = SAI_MAY(1:NVEG)\n    SAIM_TABLE(1:NVEG, 6) = SAI_JUN(1:NVEG)\n    SAIM_TABLE(1:NVEG, 7) = SAI_JUL(1:NVEG)\n    SAIM_TABLE(1:NVEG, 8) = SAI_AUG(1:NVEG)\n    SAIM_TABLE(1:NVEG, 9) = SAI_SEP(1:NVEG)\n    SAIM_TABLE(1:NVEG,10) = SAI_OCT(1:NVEG)\n    SAIM_TABLE(1:NVEG,11) = SAI_NOV(1:NVEG)\n    SAIM_TABLE(1:NVEG,12) = SAI_DEC(1:NVEG)\n\n    LAIM_TABLE(1:NVEG, 1) = LAI_JAN(1:NVEG)\n    LAIM_TABLE(1:NVEG, 2) = LAI_FEB(1:NVEG)\n    LAIM_TABLE(1:NVEG, 3) = LAI_MAR(1:NVEG)\n    LAIM_TABLE(1:NVEG, 4) = LAI_APR(1:NVEG)\n    LAIM_TABLE(1:NVEG, 5) = LAI_MAY(1:NVEG)\n    LAIM_TABLE(1:NVEG, 6) = LAI_JUN(1:NVEG)\n    LAIM_TABLE(1:NVEG, 7) = LAI_JUL(1:NVEG)\n    LAIM_TABLE(1:NVEG, 8) = LAI_AUG(1:NVEG)\n    LAIM_TABLE(1:NVEG, 9) = LAI_SEP(1:NVEG)\n    LAIM_TABLE(1:NVEG,10) = LAI_OCT(1:NVEG)\n    LAIM_TABLE(1:NVEG,11) = LAI_NOV(1:NVEG)\n    LAIM_TABLE(1:NVEG,12) = LAI_DEC(1:NVEG)\n\n    RHOL_TABLE(1:NVEG,1)  = RHOL_VIS(1:NVEG) !leaf reflectance: 1=vis, 2=nir\n    RHOL_TABLE(1:NVEG,2)  = RHOL_NIR(1:NVEG) !leaf reflectance: 1=vis, 2=nir\n    RHOS_TABLE(1:NVEG,1)  = RHOS_VIS(1:NVEG) !stem reflectance: 1=vis, 2=nir\n    RHOS_TABLE(1:NVEG,2)  = RHOS_NIR(1:NVEG) !stem reflectance: 1=vis, 2=nir\n    TAUL_TABLE(1:NVEG,1)  = TAUL_VIS(1:NVEG) !leaf transmittance: 1=vis, 2=nir\n    TAUL_TABLE(1:NVEG,2)  = TAUL_NIR(1:NVEG) !leaf transmittance: 1=vis, 2=nir\n    TAUS_TABLE(1:NVEG,1)  = TAUS_VIS(1:NVEG) !stem transmittance: 1=vis, 2=nir\n    TAUS_TABLE(1:NVEG,2)  = TAUS_NIR(1:NVEG) !stem transmittance: 1=vis, 2=nir\n\n  end subroutine read_mp_veg_parameters\n\n  subroutine read_mp_soil_parameters()\n    IMPLICIT NONE\n    INTEGER :: IERR\n    CHARACTER*4         :: SLTYPE\n    INTEGER             :: ITMP, NUM_SLOPE, LC\n    CHARACTER(len=256)  :: message\n    logical             :: file_named\n\n\n    ! Initialize our variables to bad values, so that if the namelist read fails, we come to a screeching halt as soon as we try to use anything.\n       BEXP_TABLE = -1.E36\n     SMCDRY_TABLE = -1.E36\n         F1_TABLE = -1.E36\n     SMCMAX_TABLE = -1.E36\n     SMCREF_TABLE = -1.E36\n     PSISAT_TABLE = -1.E36\n      DKSAT_TABLE = -1.E36\n      DWSAT_TABLE = -1.E36\n     SMCWLT_TABLE = -1.E36\n     QUARTZ_TABLE = -1.E36\n      SLOPE_TABLE = -1.E36\n      CSOIL_TABLE = -1.E36\n      REFDK_TABLE = -1.E36\n     REFKDT_TABLE = -1.E36\n       FRZK_TABLE = -1.E36\n       ZBOT_TABLE = -1.E36\n       CZIL_TABLE = -1.E36\n       AXAJ_TABLE = -1.E36\n       BXAJ_TABLE = -1.E36\n       XXAJ_TABLE = -1.E36\n!\n!-----READ IN SOIL PROPERTIES FROM SOILPARM.TBL\n!\n    inquire( file='SOILPARM.TBL', exist=file_named )\n    if ( file_named ) then\n      open(21, file='SOILPARM.TBL',form='formatted',status='old',iostat=ierr)\n    else\n      open(21, form='formatted',status='old',iostat=ierr)\n    end if\n\n    IF(ierr .NE. 0 ) THEN\n      WRITE(message,FMT='(A)') 'module_sf_noahmpdrv.F: read_mp_soil_parameters: failure opening SOILPARM.TBL'\n      CALL wrf_error_fatal ( message )\n    END IF\n\n    READ (21,*)\n    READ (21,*) SLTYPE\n    READ (21,*) SLCATS\n    WRITE( message , * ) 'SOIL TEXTURE CLASSIFICATION = ', TRIM ( SLTYPE ) , ' FOUND', &\n               SLCATS,' CATEGORIES'\n#ifdef HYDRO_D\n    CALL wrf_message ( message )\n#endif\n\n    DO LC=1,SLCATS\n      READ (21,*) ITMP,BEXP_TABLE(LC),SMCDRY_TABLE(LC),F1_TABLE(LC),SMCMAX_TABLE(LC),    &\n                  SMCREF_TABLE(LC),PSISAT_TABLE(LC),DKSAT_TABLE(LC), DWSAT_TABLE(LC),   &\n                  SMCWLT_TABLE(LC), QUARTZ_TABLE(LC), AXAJ_TABLE (LC), BXAJ_TABLE (LC), &\n                  XXAJ_TABLE(LC)\n    ENDDO\n\n    CLOSE (21)\n\n!\n!-----READ IN GENERAL PARAMETERS FROM GENPARM.TBL\n!\n    inquire( file='GENPARM.TBL', exist=file_named )\n    if ( file_named ) then\n      open(22, file='GENPARM.TBL',form='formatted',status='old',iostat=ierr)\n    else\n      open(22, form='formatted',status='old',iostat=ierr)\n    end if\n\n    IF(ierr .NE. 0 ) THEN\n      WRITE(message,FMT='(A)') 'module_sf_noahlsm.F: read_mp_soil_parameters: failure opening GENPARM.TBL'\n      CALL wrf_error_fatal ( message )\n    END IF\n\n    READ (22,*)\n    READ (22,*)\n    READ (22,*) NUM_SLOPE\n\n    DO LC=1,NUM_SLOPE\n        READ (22,*) SLOPE_TABLE(LC)\n    ENDDO\n\n    READ (22,*)\n    READ (22,*)\n    READ (22,*)\n    READ (22,*)\n    READ (22,*)\n    READ (22,*) CSOIL_TABLE\n    READ (22,*)\n    READ (22,*)\n    READ (22,*)\n    READ (22,*) REFDK_TABLE\n    READ (22,*)\n    READ (22,*) REFKDT_TABLE\n    READ (22,*)\n    READ (22,*) FRZK_TABLE\n    READ (22,*)\n    READ (22,*) ZBOT_TABLE\n    READ (22,*)\n    READ (22,*) CZIL_TABLE\n    READ (22,*)\n    READ (22,*)\n    READ (22,*)\n    READ (22,*)\n\n    CLOSE (22)\n\n  end subroutine read_mp_soil_parameters\n\n  subroutine read_mp_rad_parameters()\n    implicit none\n    integer :: ierr\n    logical :: file_named\n\n    REAL :: ALBICE(MBAND),ALBLAK(MBAND),OMEGAS(MBAND),BETADS,BETAIS,EG(2)\n    REAL :: ALBSAT_VIS(MSC)\n    REAL :: ALBSAT_NIR(MSC)\n    REAL :: ALBDRY_VIS(MSC)\n    REAL :: ALBDRY_NIR(MSC)\n\n    NAMELIST / noahmp_rad_parameters / ALBSAT_VIS,ALBSAT_NIR,ALBDRY_VIS,ALBDRY_NIR,ALBICE,ALBLAK,OMEGAS,BETADS,BETAIS,EG\n\n\n    ! Initialize our variables to bad values, so that if the namelist read fails, we come to a screeching halt as soon as we try to use anything.\n    ALBSAT_TABLE     = -1.E36\n    ALBDRY_TABLE     = -1.E36\n    ALBICE_TABLE     = -1.E36\n    ALBLAK_TABLE     = -1.E36\n    OMEGAS_TABLE     = -1.E36\n    BETADS_TABLE     = -1.E36\n    BETAIS_TABLE     = -1.E36\n    EG_TABLE         = -1.E36\n\n    inquire( file='MPTABLE.TBL', exist=file_named )\n    if ( file_named ) then\n      open(15, file=\"MPTABLE.TBL\", status='old', form='formatted', action='read', iostat=ierr)\n    else\n      open(15, status='old', form='formatted', action='read', iostat=ierr)\n    end if\n\n    if (ierr /= 0) then\n       write(*,'(\"WARNING: Cannot find file MPTABLE.TBL\")')\n       call wrf_error_fatal(\"STOP in Noah-MP read_mp_rad_parameters\")\n    endif\n\n    read(15,noahmp_rad_parameters)\n    close(15)\n\n    ALBSAT_TABLE(:,1) = ALBSAT_VIS ! saturated soil albedos: 1=vis, 2=nir\n    ALBSAT_TABLE(:,2) = ALBSAT_NIR ! saturated soil albedos: 1=vis, 2=nir\n    ALBDRY_TABLE(:,1) = ALBDRY_VIS ! dry soil albedos: 1=vis, 2=nir\n    ALBDRY_TABLE(:,2) = ALBDRY_NIR ! dry soil albedos: 1=vis, 2=nir\n    ALBICE_TABLE      = ALBICE\n    ALBLAK_TABLE      = ALBLAK\n    OMEGAS_TABLE      = OMEGAS\n    BETADS_TABLE      = BETADS\n    BETAIS_TABLE      = BETAIS\n    EG_TABLE          = EG\n\n  end subroutine read_mp_rad_parameters\n\n  subroutine read_mp_global_parameters()\n    implicit none\n    integer :: ierr\n    logical :: file_named\n\n    REAL :: CO2,O2,TIMEAN,FSATMX,Z0SNO,SSI,SNOW_RET_FAC, &\n            SWEMX,TAU0,GRAIN_GROWTH,EXTRA_GROWTH,DIRT_SOOT,&\n\t    BATS_COSZ,BATS_VIS_NEW,BATS_NIR_NEW,BATS_VIS_AGE,BATS_NIR_AGE,BATS_VIS_DIR,BATS_NIR_DIR,&\n\t    RSURF_SNOW,RSURF_EXP,IMPERV_URBAN,SWE_LIMIT,SCAMAX\n\n    NAMELIST / noahmp_global_parameters / CO2,O2,TIMEAN,FSATMX,Z0SNO,SSI,SNOW_RET_FAC, &\n            SWEMX,TAU0,GRAIN_GROWTH,EXTRA_GROWTH,DIRT_SOOT,&\n\t    BATS_COSZ,BATS_VIS_NEW,BATS_NIR_NEW,BATS_VIS_AGE,BATS_NIR_AGE,BATS_VIS_DIR,BATS_NIR_DIR,&\n\t    RSURF_SNOW,RSURF_EXP,IMPERV_URBAN,SWE_LIMIT,SCAMAX\n\n\n    ! Initialize our variables to bad values, so that if the namelist read fails, we come to a screeching halt as soon as we try to use anything.\n       CO2_TABLE     = -1.E36\n        O2_TABLE     = -1.E36\n    TIMEAN_TABLE     = -1.E36\n    FSATMX_TABLE     = -1.E36\n     Z0SNO_TABLE     = -1.E36\n       SSI_TABLE     = -1.E36\nSNOW_RET_FAC_TABLE   = -1.E36\n     SWEMX_TABLE     = -1.E36\n        TAU0_TABLE   = -1.E36\nGRAIN_GROWTH_TABLE   = -1.E36\nEXTRA_GROWTH_TABLE   = -1.E36\n   DIRT_SOOT_TABLE   = -1.E36\n   BATS_COSZ_TABLE   = -1.E36\nBATS_VIS_NEW_TABLE   = -1.E36\nBATS_NIR_NEW_TABLE   = -1.E36\nBATS_VIS_AGE_TABLE   = -1.E36\nBATS_NIR_AGE_TABLE   = -1.E36\nBATS_VIS_DIR_TABLE   = -1.E36\nBATS_NIR_DIR_TABLE   = -1.E36\nRSURF_SNOW_TABLE     = -1.E36\n RSURF_EXP_TABLE     = -1.E36\nIMPERV_URBAN_TABLE   = -1.E36\n    SCAMAX_TABLE     = -1.E36\n SWE_LIMIT_TABLE     = -1.E36\n\n    inquire( file='MPTABLE.TBL', exist=file_named )\n    if ( file_named ) then\n      open(15, file=\"MPTABLE.TBL\", status='old', form='formatted', action='read', iostat=ierr)\n    else\n      open(15, status='old', form='formatted', action='read', iostat=ierr)\n    end if\n\n    if (ierr /= 0) then\n       write(*,'(\"WARNING: Cannot find file MPTABLE.TBL\")')\n       call wrf_error_fatal(\"STOP in Noah-MP read_mp_global_parameters\")\n    endif\n\n    read(15,noahmp_global_parameters)\n    close(15)\n\n       CO2_TABLE     = CO2\n        O2_TABLE     = O2\n    TIMEAN_TABLE     = TIMEAN\n    FSATMX_TABLE     = FSATMX\n     Z0SNO_TABLE     = Z0SNO\n       SSI_TABLE     = SSI\nSNOW_RET_FAC_TABLE   = SNOW_RET_FAC\n     SWEMX_TABLE     = SWEMX\n        TAU0_TABLE   = TAU0\nGRAIN_GROWTH_TABLE   = GRAIN_GROWTH\nEXTRA_GROWTH_TABLE   = EXTRA_GROWTH\n   DIRT_SOOT_TABLE   = DIRT_SOOT\n   BATS_COSZ_TABLE   = BATS_COSZ\nBATS_VIS_NEW_TABLE   = BATS_VIS_NEW\nBATS_NIR_NEW_TABLE   = BATS_NIR_NEW\nBATS_VIS_AGE_TABLE   = BATS_VIS_AGE\nBATS_NIR_AGE_TABLE   = BATS_NIR_AGE\nBATS_VIS_DIR_TABLE   = BATS_VIS_DIR\nBATS_NIR_DIR_TABLE   = BATS_NIR_DIR\nRSURF_SNOW_TABLE     = RSURF_SNOW\n RSURF_EXP_TABLE     = RSURF_EXP\nIMPERV_URBAN_TABLE   = IMPERV_URBAN\n    SCAMAX_TABLE     = SCAMAX\n SWE_LIMIT_TABLE     = SWE_LIMIT\n\n  end subroutine read_mp_global_parameters\n\n  subroutine read_mp_crop_parameters()\n    implicit none\n    integer :: ierr\n    logical :: file_named\n\n INTEGER                   :: DEFAULT_CROP\n INTEGER, DIMENSION(NCROP) :: PLTDAY\n INTEGER, DIMENSION(NCROP) :: HSDAY\n    REAL, DIMENSION(NCROP) :: PLANTPOP\n    REAL, DIMENSION(NCROP) :: IRRI\n    REAL, DIMENSION(NCROP) :: GDDTBASE\n    REAL, DIMENSION(NCROP) :: GDDTCUT\n    REAL, DIMENSION(NCROP) :: GDDS1\n    REAL, DIMENSION(NCROP) :: GDDS2\n    REAL, DIMENSION(NCROP) :: GDDS3\n    REAL, DIMENSION(NCROP) :: GDDS4\n    REAL, DIMENSION(NCROP) :: GDDS5\n INTEGER, DIMENSION(NCROP) :: C3C4\n    REAL, DIMENSION(NCROP) :: AREF\n    REAL, DIMENSION(NCROP) :: PSNRF\n    REAL, DIMENSION(NCROP) :: I2PAR\n    REAL, DIMENSION(NCROP) :: TASSIM0\n    REAL, DIMENSION(NCROP) :: TASSIM1\n    REAL, DIMENSION(NCROP) :: TASSIM2\n    REAL, DIMENSION(NCROP) :: K\n    REAL, DIMENSION(NCROP) :: EPSI\n    REAL, DIMENSION(NCROP) :: Q10MR\n    REAL, DIMENSION(NCROP) :: FOLN_MX\n    REAL, DIMENSION(NCROP) :: LEFREEZ\n    REAL, DIMENSION(NCROP) :: DILE_FC_S1,DILE_FC_S2,DILE_FC_S3,DILE_FC_S4,DILE_FC_S5,DILE_FC_S6,DILE_FC_S7,DILE_FC_S8\n    REAL, DIMENSION(NCROP) :: DILE_FW_S1,DILE_FW_S2,DILE_FW_S3,DILE_FW_S4,DILE_FW_S5,DILE_FW_S6,DILE_FW_S7,DILE_FW_S8\n    REAL, DIMENSION(NCROP) :: FRA_GR\n    REAL, DIMENSION(NCROP) :: LF_OVRC_S1,LF_OVRC_S2,LF_OVRC_S3,LF_OVRC_S4,LF_OVRC_S5,LF_OVRC_S6,LF_OVRC_S7,LF_OVRC_S8\n    REAL, DIMENSION(NCROP) :: ST_OVRC_S1,ST_OVRC_S2,ST_OVRC_S3,ST_OVRC_S4,ST_OVRC_S5,ST_OVRC_S6,ST_OVRC_S7,ST_OVRC_S8\n    REAL, DIMENSION(NCROP) :: RT_OVRC_S1,RT_OVRC_S2,RT_OVRC_S3,RT_OVRC_S4,RT_OVRC_S5,RT_OVRC_S6,RT_OVRC_S7,RT_OVRC_S8\n    REAL, DIMENSION(NCROP) :: LFMR25\n    REAL, DIMENSION(NCROP) :: STMR25\n    REAL, DIMENSION(NCROP) :: RTMR25\n    REAL, DIMENSION(NCROP) :: GRAINMR25\n    REAL, DIMENSION(NCROP) :: LFPT_S1,LFPT_S2,LFPT_S3,LFPT_S4,LFPT_S5,LFPT_S6,LFPT_S7,LFPT_S8\n    REAL, DIMENSION(NCROP) :: STPT_S1,STPT_S2,STPT_S3,STPT_S4,STPT_S5,STPT_S6,STPT_S7,STPT_S8\n    REAL, DIMENSION(NCROP) :: RTPT_S1,RTPT_S2,RTPT_S3,RTPT_S4,RTPT_S5,RTPT_S6,RTPT_S7,RTPT_S8\n    REAL, DIMENSION(NCROP) :: GRAINPT_S1,GRAINPT_S2,GRAINPT_S3,GRAINPT_S4,GRAINPT_S5,GRAINPT_S6,GRAINPT_S7,GRAINPT_S8\n    REAL, DIMENSION(NCROP) :: BIO2LAI\n\n\n    NAMELIST / noahmp_crop_parameters /DEFAULT_CROP,   PLTDAY,     HSDAY,  PLANTPOP,      IRRI,  GDDTBASE,   GDDTCUT,     GDDS1,     GDDS2, &\n                                             GDDS3,     GDDS4,     GDDS5,      C3C4,      AREF,     PSNRF,     I2PAR,   TASSIM0, &\n                                           TASSIM1,   TASSIM2,         K,      EPSI,     Q10MR,   FOLN_MX,   LEFREEZ,            &\n                                        DILE_FC_S1,DILE_FC_S2,DILE_FC_S3,DILE_FC_S4,DILE_FC_S5,DILE_FC_S6,DILE_FC_S7,DILE_FC_S8, &\n                                        DILE_FW_S1,DILE_FW_S2,DILE_FW_S3,DILE_FW_S4,DILE_FW_S5,DILE_FW_S6,DILE_FW_S7,DILE_FW_S8, &\n                                            FRA_GR,                                                                              &\n                                        LF_OVRC_S1,LF_OVRC_S2,LF_OVRC_S3,LF_OVRC_S4,LF_OVRC_S5,LF_OVRC_S6,LF_OVRC_S7,LF_OVRC_S8, &\n                                        ST_OVRC_S1,ST_OVRC_S2,ST_OVRC_S3,ST_OVRC_S4,ST_OVRC_S5,ST_OVRC_S6,ST_OVRC_S7,ST_OVRC_S8, &\n                                        RT_OVRC_S1,RT_OVRC_S2,RT_OVRC_S3,RT_OVRC_S4,RT_OVRC_S5,RT_OVRC_S6,RT_OVRC_S7,RT_OVRC_S8, &\n                                            LFMR25,    STMR25,    RTMR25, GRAINMR25,                                             &\n                                           LFPT_S1,   LFPT_S2,   LFPT_S3,   LFPT_S4,   LFPT_S5,   LFPT_S6,   LFPT_S7,   LFPT_S8, &\n                                           STPT_S1,   STPT_S2,   STPT_S3,   STPT_S4,   STPT_S5,   STPT_S6,   STPT_S7,   STPT_S8, &\n                                           RTPT_S1,   RTPT_S2,   RTPT_S3,   RTPT_S4,   RTPT_S5,   RTPT_S6,   RTPT_S7,   RTPT_S8, &\n                                        GRAINPT_S1,GRAINPT_S2,GRAINPT_S3,GRAINPT_S4,GRAINPT_S5,GRAINPT_S6,GRAINPT_S7,GRAINPT_S8, &\n                                           BIO2LAI\n\n\n    ! Initialize our variables to bad values, so that if the namelist read fails, we come to a screeching halt as soon as we try to use anything.\n DEFAULT_CROP_TABLE     = -99999\n       PLTDAY_TABLE     = -99999\n        HSDAY_TABLE     = -99999\n     PLANTPOP_TABLE     = -1.E36\n         IRRI_TABLE     = -1.E36\n     GDDTBASE_TABLE     = -1.E36\n      GDDTCUT_TABLE     = -1.E36\n        GDDS1_TABLE     = -1.E36\n        GDDS2_TABLE     = -1.E36\n        GDDS3_TABLE     = -1.E36\n        GDDS4_TABLE     = -1.E36\n        GDDS5_TABLE     = -1.E36\n         C3C4_TABLE     = -99999\n         AREF_TABLE     = -1.E36\n        PSNRF_TABLE     = -1.E36\n        I2PAR_TABLE     = -1.E36\n      TASSIM0_TABLE     = -1.E36\n      TASSIM1_TABLE     = -1.E36\n      TASSIM2_TABLE     = -1.E36\n            K_TABLE     = -1.E36\n         EPSI_TABLE     = -1.E36\n        Q10MR_TABLE     = -1.E36\n      FOLN_MX_TABLE     = -1.E36\n      LEFREEZ_TABLE     = -1.E36\n      DILE_FC_TABLE     = -1.E36\n      DILE_FW_TABLE     = -1.E36\n       FRA_GR_TABLE     = -1.E36\n      LF_OVRC_TABLE     = -1.E36\n      ST_OVRC_TABLE     = -1.E36\n      RT_OVRC_TABLE     = -1.E36\n       LFMR25_TABLE     = -1.E36\n       STMR25_TABLE     = -1.E36\n       RTMR25_TABLE     = -1.E36\n    GRAINMR25_TABLE     = -1.E36\n         LFPT_TABLE     = -1.E36\n         STPT_TABLE     = -1.E36\n         RTPT_TABLE     = -1.E36\n      GRAINPT_TABLE     = -1.E36\n      BIO2LAI_TABLE     = -1.E36\n\n\n    inquire( file='MPTABLE.TBL', exist=file_named )\n    if ( file_named ) then\n      open(15, file=\"MPTABLE.TBL\", status='old', form='formatted', action='read', iostat=ierr)\n    else\n      open(15, status='old', form='formatted', action='read', iostat=ierr)\n    end if\n\n    if (ierr /= 0) then\n       write(*,'(\"WARNING: Cannot find file MPTABLE.TBL\")')\n       call wrf_error_fatal(\"STOP in Noah-MP read_mp_crop_parameters\")\n    endif\n\n    read(15,noahmp_crop_parameters)\n    close(15)\n\n DEFAULT_CROP_TABLE      = DEFAULT_CROP\n       PLTDAY_TABLE      = PLTDAY\n        HSDAY_TABLE      = HSDAY\n     PLANTPOP_TABLE      = PLANTPOP\n         IRRI_TABLE      = IRRI\n     GDDTBASE_TABLE      = GDDTBASE\n      GDDTCUT_TABLE      = GDDTCUT\n        GDDS1_TABLE      = GDDS1\n        GDDS2_TABLE      = GDDS2\n        GDDS3_TABLE      = GDDS3\n        GDDS4_TABLE      = GDDS4\n        GDDS5_TABLE      = GDDS5\n         C3C4_TABLE      = C3C4\n         AREF_TABLE      = AREF\n        PSNRF_TABLE      = PSNRF\n        I2PAR_TABLE      = I2PAR\n      TASSIM0_TABLE      = TASSIM0\n      TASSIM1_TABLE      = TASSIM1\n      TASSIM2_TABLE      = TASSIM2\n            K_TABLE      = K\n         EPSI_TABLE      = EPSI\n        Q10MR_TABLE      = Q10MR\n      FOLN_MX_TABLE      = FOLN_MX\n      LEFREEZ_TABLE      = LEFREEZ\n      DILE_FC_TABLE(:,1) = DILE_FC_S1\n      DILE_FC_TABLE(:,2) = DILE_FC_S2\n      DILE_FC_TABLE(:,3) = DILE_FC_S3\n      DILE_FC_TABLE(:,4) = DILE_FC_S4\n      DILE_FC_TABLE(:,5) = DILE_FC_S5\n      DILE_FC_TABLE(:,6) = DILE_FC_S6\n      DILE_FC_TABLE(:,7) = DILE_FC_S7\n      DILE_FC_TABLE(:,8) = DILE_FC_S8\n      DILE_FW_TABLE(:,1) = DILE_FW_S1\n      DILE_FW_TABLE(:,2) = DILE_FW_S2\n      DILE_FW_TABLE(:,3) = DILE_FW_S3\n      DILE_FW_TABLE(:,4) = DILE_FW_S4\n      DILE_FW_TABLE(:,5) = DILE_FW_S5\n      DILE_FW_TABLE(:,6) = DILE_FW_S6\n      DILE_FW_TABLE(:,7) = DILE_FW_S7\n      DILE_FW_TABLE(:,8) = DILE_FW_S8\n       FRA_GR_TABLE      = FRA_GR\n      LF_OVRC_TABLE(:,1) = LF_OVRC_S1\n      LF_OVRC_TABLE(:,2) = LF_OVRC_S2\n      LF_OVRC_TABLE(:,3) = LF_OVRC_S3\n      LF_OVRC_TABLE(:,4) = LF_OVRC_S4\n      LF_OVRC_TABLE(:,5) = LF_OVRC_S5\n      LF_OVRC_TABLE(:,6) = LF_OVRC_S6\n      LF_OVRC_TABLE(:,7) = LF_OVRC_S7\n      LF_OVRC_TABLE(:,8) = LF_OVRC_S8\n      ST_OVRC_TABLE(:,1) = ST_OVRC_S1\n      ST_OVRC_TABLE(:,2) = ST_OVRC_S2\n      ST_OVRC_TABLE(:,3) = ST_OVRC_S3\n      ST_OVRC_TABLE(:,4) = ST_OVRC_S4\n      ST_OVRC_TABLE(:,5) = ST_OVRC_S5\n      ST_OVRC_TABLE(:,6) = ST_OVRC_S6\n      ST_OVRC_TABLE(:,7) = ST_OVRC_S7\n      ST_OVRC_TABLE(:,8) = ST_OVRC_S8\n      RT_OVRC_TABLE(:,1) = RT_OVRC_S1\n      RT_OVRC_TABLE(:,2) = RT_OVRC_S2\n      RT_OVRC_TABLE(:,3) = RT_OVRC_S3\n      RT_OVRC_TABLE(:,4) = RT_OVRC_S4\n      RT_OVRC_TABLE(:,5) = RT_OVRC_S5\n      RT_OVRC_TABLE(:,6) = RT_OVRC_S6\n      RT_OVRC_TABLE(:,7) = RT_OVRC_S7\n      RT_OVRC_TABLE(:,8) = RT_OVRC_S8\n       LFMR25_TABLE      = LFMR25\n       STMR25_TABLE      = STMR25\n       RTMR25_TABLE      = RTMR25\n    GRAINMR25_TABLE      = GRAINMR25\n         LFPT_TABLE(:,1) = LFPT_S1\n         LFPT_TABLE(:,2) = LFPT_S2\n         LFPT_TABLE(:,3) = LFPT_S3\n         LFPT_TABLE(:,4) = LFPT_S4\n         LFPT_TABLE(:,5) = LFPT_S5\n         LFPT_TABLE(:,6) = LFPT_S6\n         LFPT_TABLE(:,7) = LFPT_S7\n         LFPT_TABLE(:,8) = LFPT_S8\n         STPT_TABLE(:,1) = STPT_S1\n         STPT_TABLE(:,2) = STPT_S2\n         STPT_TABLE(:,3) = STPT_S3\n         STPT_TABLE(:,4) = STPT_S4\n         STPT_TABLE(:,5) = STPT_S5\n         STPT_TABLE(:,6) = STPT_S6\n         STPT_TABLE(:,7) = STPT_S7\n         STPT_TABLE(:,8) = STPT_S8\n         RTPT_TABLE(:,1) = RTPT_S1\n         RTPT_TABLE(:,2) = RTPT_S2\n         RTPT_TABLE(:,3) = RTPT_S3\n         RTPT_TABLE(:,4) = RTPT_S4\n         RTPT_TABLE(:,5) = RTPT_S5\n         RTPT_TABLE(:,6) = RTPT_S6\n         RTPT_TABLE(:,7) = RTPT_S7\n         RTPT_TABLE(:,8) = RTPT_S8\n      GRAINPT_TABLE(:,1) = GRAINPT_S1\n      GRAINPT_TABLE(:,2) = GRAINPT_S2\n      GRAINPT_TABLE(:,3) = GRAINPT_S3\n      GRAINPT_TABLE(:,4) = GRAINPT_S4\n      GRAINPT_TABLE(:,5) = GRAINPT_S5\n      GRAINPT_TABLE(:,6) = GRAINPT_S6\n      GRAINPT_TABLE(:,7) = GRAINPT_S7\n      GRAINPT_TABLE(:,8) = GRAINPT_S8\n      BIO2LAI_TABLE      = BIO2LAI\n\n  end subroutine read_mp_crop_parameters\n\n  subroutine read_mp_optional_parameters()\n    implicit none\n    integer :: ierr\n    logical :: file_named\n\n    NAMELIST / noahmp_optional_parameters /                                &\n         sr2006_theta_1500t_a, sr2006_theta_1500t_b, sr2006_theta_1500t_c, &\n         sr2006_theta_1500t_d, sr2006_theta_1500t_e, sr2006_theta_1500t_f, &\n         sr2006_theta_1500t_g                                            , &\n         sr2006_theta_1500_a , sr2006_theta_1500_b                       , &\n         sr2006_theta_33t_a  , sr2006_theta_33t_b  , sr2006_theta_33t_c  , &\n         sr2006_theta_33t_d  , sr2006_theta_33t_e  , sr2006_theta_33t_f  , &\n         sr2006_theta_33t_g                                              , &\n         sr2006_theta_33_a   , sr2006_theta_33_b   , sr2006_theta_33_c   , &\n         sr2006_theta_s33t_a , sr2006_theta_s33t_b , sr2006_theta_s33t_c , &\n         sr2006_theta_s33t_d , sr2006_theta_s33t_e , sr2006_theta_s33t_f , &\n         sr2006_theta_s33t_g                                             , &\n         sr2006_theta_s33_a  , sr2006_theta_s33_b                        , &\n         sr2006_psi_et_a     , sr2006_psi_et_b     , sr2006_psi_et_c     , &\n         sr2006_psi_et_d     , sr2006_psi_et_e     , sr2006_psi_et_f     , &\n         sr2006_psi_et_g                                                 , &\n         sr2006_psi_e_a      , sr2006_psi_e_b      , sr2006_psi_e_c      , &\n         sr2006_smcmax_a     , sr2006_smcmax_b\n\n    inquire( file='MPTABLE.TBL', exist=file_named )\n    if ( file_named ) then\n      open(15, file=\"MPTABLE.TBL\", status='old', form='formatted', action='read', iostat=ierr)\n    else\n      open(15, status='old', form='formatted', action='read', iostat=ierr)\n    end if\n\n    if (ierr /= 0) then\n       write(*,'(\"WARNING: Cannot find file MPTABLE.TBL\")')\n       call wrf_error_fatal(\"STOP in Noah-MP read_mp_optional_parameters\")\n    endif\n\n    read(15,noahmp_optional_parameters)\n    close(15)\n\n\n  end subroutine read_mp_optional_parameters\n\nEND MODULE NOAHMP_TABLES\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/CMakeLists.txt",
    "content": "add_library(crocus_surfex STATIC\n  ini_csts.F\n  modd_csts.F\n  modd_snow_metamo.F\n  modd_snow_par.F\n  modd_surf_atm.F\n  mode_snow3l.F\n  mode_surf_coefs.F\n  mode_thermos.F\n  tridiag_ground_snowcro.F\n)\n\nif (BUILD_CROCUS)\n  add_library(snowcro\n    module_snowcro.F\n    )\nelse()\n  add_library(snowcro\n    module_snowcro_intercept.F\n    )\nendif()\n\ntarget_link_libraries(snowcro crocus_surfex)\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/Makefile",
    "content": "#\n# Makefile\n#\n\ninclude ../../user_build_options\nSRCS := $(wildcard *.F)\nOBJS := $(SRCS:%.F=%.o)\nCPPHRLDAS = -D_HRLDAS_OFFLINE_\n\nall: $(OBJS)\n\n%.o:%.F\n\t@echo \"\"\n\t$(COMPILERF90) $(CPPINVOKE) $(CPPFLAGS) $(CPPHRLDAS) -o $@ -c -I../Utility_routines \\\n\t   $(F90FLAGS) $(LDFLAGS) $(FREESOURCE) $<\n\t@echo \"\"\n\n#\n# Dependencies:\n#\nmode_snow3l.o: modd_snow_par.o modd_csts.o modd_snow_metamo.o\nmode_thermos.o: modd_csts.o modd_snow_par.o\nmode_surf_coefs.o: modd_surf_atm.o mode_thermos.o\nini_csts.o: modd_csts.o\nmodule_snowcro.o: mode_snow3l.o modd_snow_par.o modd_csts.o modd_snow_metamo.o modd_surf_atm.o \\\n\tmode_thermos.o mode_surf_coefs.o tridiag_ground_snowcro.o\nmodule_snowcro_intercept.o:\n\n#\n# This command cleans up object (etc) files:\n#\nclean:\n\t$(RM) *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/ini_csts.F",
    "content": "MODULE MODI_INI_CSTS\n\nCONTAINS\n\n!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\n!     #########\n      SUBROUTINE INI_CSTS\n!     ##################\n!\n!!****  *INI_CSTS * - routine to initialize the module MODD_CST\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this routine is to initialize  the physical constants\n!     stored in  module MODD_CST.\n!\n!\n!!**  METHOD\n!!    ------\n!!      The physical constants are set to their numerical values\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      FMLOOK : to retrieve logical unit number associated to a file\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST     : contains physical constants\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of the documentation (module MODD_CST, routine INI_CSTS)\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Ducrocq       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    18/05/94\n!!      J. Stein    02/01/95  add the volumic mass of liquid water\n!!      J.-P. Pinty 13/12/95  add the water vapor pressure over solid ice\n!!      J. Stein    29/06/97  add XTH00\n!!      V. Masson   05/10/98  add XRHOLI\n!!      C. Mari     31/10/00  add NDAYSEC\n!!      V. Masson   01/03/03  add XCONDI\n!!      A. Voldoire 01/12/09  add XTTSI, XICEC, XTTS for ESM\n!!      J. Escobar  28/03/2014 for pb with emissivity/aerosol reset XSURF_TINY=1.0e-80 in real8 case\n!!\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\n! trude, do not think we need ini_cturbs\n!USE MODI_INI_CTURBS\n!\n! trude, do not think we need ini_ocean\n!USE MODI_INI_OCEAN_CSTS\n!\n!trude, this module read namelist. Need to move namelist options to another place \n!USE MODI_INI_SURF_CSTS\n!\nIMPLICIT NONE\n!\n!-------------------------------------------------------------------------------\n!\n!*       1.     FUNDAMENTAL CONSTANTS\n!               ---------------------\n!\nLOGICAL               :: LREPROD_OPER,LMEBREC\nREAL           :: XEVERG_RSMIN, XEVERG_VEG, XANSFRACMEL,XTEMPANS\nREAL          :: XANSMIN, XANSMAX, XAGLAMIN, XAGLAMAX, XEMISSN, XUNDEF\nREAL          :: XVAGING_NOGLACIER, XVAGING_GLACIER\n\n CHARACTER(LEN=3) :: CDGAVG, CIMPLICIT_WIND,CQSAT,CCHARNOCK\n CHARACTER(LEN=4) :: CDGDIF\n\n\n\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n\nXUNDEF=1.E+20\n\n!IF (LHOOK) CALL DR_HOOK('INI_CSTS',0,ZHOOK_HANDLE)\n\n#ifdef SFX_MNH\n#ifdef MNH_MPI_DOUBLE_PRECISION\n!XSURF_TINY    = 1.0e-80\nXSURF_TINY    = 1.0e-30\n#else\nXSURF_TINY    = TINY    (XSURF_TINY    )\n#endif\n#else\n!XSURF_TINY    = 1.0e-80\nXSURF_TINY    = 1.0e-30\n#endif\nXSURF_TINY_12 = SQRT    (XSURF_TINY    )\nXSURF_EPSILON = EPSILON (XSURF_EPSILON ) * 10.0\n\nXPI         = 2.*ASIN(1.)\nXKARMAN     = 0.4\nXBOLTZ      = 1.380658E-23\nXLIGHTSPEED = 299792458.\nXPLANCK     = 6.6260755E-34\nXAVOGADRO   = 6.0221367E+23\n!\n!-------------------------------------------------------------------------------\n!\n!*       2.     ASTRONOMICAL CONSTANTS\n!               ----------------------\n!\nXDAY   = 86400.\nXSIYEA = 365.25*XDAY*2.*XPI/ 6.283076\nXSIDAY = XDAY/(1.+XDAY/XSIYEA)\nXOMEGA = 2.*XPI/XSIDAY\nNDAYSEC = 24*3600 ! Number of seconds in a day\n!\n!-------------------------------------------------------------------------------!\n!\n!\n!*       3.     TERRESTRIAL GEOIDE CONSTANTS\n!               ----------------------------\n!\nXRADIUS = 6371229.\nXG      = 9.80665\n!\n!-------------------------------------------------------------------------------\n!\n!*       4.     REFERENCE PRESSURE\n!               -------------------\n!\nXP00 = 1.E5\nXTH00 = 300.\n!-------------------------------------------------------------------------------\n!\n!*       5.     RADIATION CONSTANTS\n!               -------------------\n!\n!JUAN OVERFLOW XSTEFAN = 2.* XPI**5 * XBOLTZ**4 / (15.* XLIGHTSPEED**2 * XPLANCK**3)\nXSTEFAN = ( 2.* XPI**5 / 15. ) * ( (XBOLTZ / XPLANCK)* XBOLTZ ) * (XBOLTZ/(XLIGHTSPEED*XPLANCK))**2 \nXI0     = 1370.\n!\n!-------------------------------------------------------------------------------\n!\n!*       6.     THERMODYNAMIC CONSTANTS\n!               -----------------------\n!\nXMD    = 28.9644E-3\nXMV    = 18.0153E-3\nXRD    = XAVOGADRO * XBOLTZ / XMD\nXRV    = XAVOGADRO * XBOLTZ / XMV\nXCPD   = 7.* XRD /2.\nXCPV   = 4.* XRV\nXRHOLW = 1000.\nXRHOLI = 917.\nXCONDI = 2.22\nXCL    = 4.218E+3\nXCI    = 2.106E+3\nXTT    = 273.16\nXTTSI  = XTT - 1.8\nXICEC  = 0.5\nXTTS   = XTT*(1-XICEC) + XTTSI*XICEC\nXLVTT  = 2.5008E+6\nXLSTT  = 2.8345E+6\nXLMTT  = XLSTT - XLVTT\nXESTT  = 611.14\nXGAMW  = (XCL - XCPV) / XRV\nXBETAW = (XLVTT/XRV) + (XGAMW * XTT)\nXALPW  = LOG(XESTT) + (XBETAW /XTT) + (XGAMW *LOG(XTT))\nXGAMI  = (XCI - XCPV) / XRV\nXBETAI = (XLSTT/XRV) + (XGAMI * XTT)\nXALPI  = LOG(XESTT) + (XBETAI /XTT) + (XGAMI *LOG(XTT))\n!\n!-------------------------------------------------------------------------------\n!\n!*       7.     TURBULENCE CONSTANTS\n!               --------------------\n!\n! trude, do not think we need ini_cturbs. Commenting this out\n! CALL INI_CTURBS\n! end trude\n!-------------------------------------------------------------------------------\n!\n!*       8.     OCEAN CONSTANTS\n!               ---------------\n!\n! trude, do not think we need ini_ocean_csts. Commenting this out\n! CALL INI_OCEAN_CSTS\n!\n!*       9.     SURFACE CONSTANTS\n!               -----------------\n!\n! trude: these constants can be changed in namelist (read by ini_surf_csts)\n! For now, I will declare the default values here, and later put them into \n!namelist for hrlds\n!-------------------------------------------------------------------------------\n\n!\n! * Reproductibility for SURFEX OPER\n!\nLREPROD_OPER = .FALSE. ! default\nLMEBREC            = .FALSE.\n!\n!\n! * Vegetation parameters for tropical forest\n!\n!XEVERG_RSMIN : old = 250. (Manzi 1993) but observations range\n!               from 140 to 180. According to Delire et al. (1997) and\n!               new tests over 6 local sites, 175. is recommended\n!               Should be the default after check with AROME/ALADIN\n!\nXEVERG_RSMIN = 175.  !Rsmin\n!\n!XEVERG_VEG : old = 0.99 (Manzi 1993) but according to Delire et al. (1997) and \n!             new tests over 6 local sites, 1.0 is recommended because 0.99\n!             induces unrealistic bare soil evaporation for Tropical forest\n!             Should be the default after check with AROME/ALADIN\n!\nXEVERG_VEG   = 1.0  !Veg fraction\n!\n! * Soil depth average\n!\n CDGAVG = 'INV'\n!\n! * Soil depth with ISBA-DF\n!\n CDGDIF = 'ROOT'\n!\n! * wind implicitation option\n!\n CIMPLICIT_WIND = 'NEW'\n!\n! * qsat computation\n!\n CQSAT = 'NEW'\n! CQSAT = 'OLD'\n!\n! * Charnock parameter\n!\n CCHARNOCK = 'NEW'\n\nIF(LMEBREC)THEN\n! Fraction of maximum value of the albedo of snow that is reached for melting\n! snow\n!\n  XANSFRACMEL = 0.85 ! (-)\n!\n! Threeshold temperature above which the snow albedo starts to decrease\n!\n  XTEMPANS = 268.15 ! (K)\n!\nENDIF\n\n\nXEMISSN     = XUNDEF\nIF(XEMISSN==XUNDEF)THEN\n  IF(LREPROD_OPER)THEN\n    XEMISSN =  1.0\n  ELSE\n    XEMISSN =  0.99\n  ENDIF\nENDIF\n\n!\n! Use recommended settings for snow albedo (FALSE = ISBA default)\n!\nLMEBREC=.FALSE.\n!\n! Fraction of maximum value of the albedo of snow that is reached for melting\n! snow\n!\nXANSFRACMEL = 1.0 ! (-)\nXANSMIN = 0.50 ! (-)\nXANSMAX = 0.85 ! (-)\n!\n! Minimum and maximum values of the albedo of permanet snow/ice:\n!\nXAGLAMIN = 0.8 ! orig 0.8 ! (-) trude test with 0.7\nXAGLAMAX = 0.85 ! (-)\n!\n! Use recommended settings for snow albedo (FALSE = ISBA default)\n!\nLMEBREC=.FALSE.\n!\n! Fraction of maximum value of the albedo of snow that is reached for melting\n! snow\n!\nXANSFRACMEL = 1.0 ! (-)\n\n! Roughness length ratio between ice and snow\n!XZ0ICEZ0SNOW = 100   ! trude try 100 instead of the original value of 10.   \n!XZ0ICEZ0SNOW = 20   !7   ! trude; 20 is what I used when shared the code\n!XZ0ICEZ0SNOW = 7  ! trude; ice was melting slighly too much. Try the original 10 instead. factor of 7 instead as backed up by obs over Hardangerjøkulen (Anreassen et al 2008)\nXZ0ICEZ0SNOW = 10  ! trude; ice was melting slighly too much. Try the original 10 instead. f\n!XZ0ICEZ0SNOW = 50  ! trude; ice was melting slighly too much. Try the original 10 instead.\n\n\n!XZ0ICEZ0SNOW = 14  ! trude; ice was melting slighly too much. Try the original 10 instead. f\n!XZ0ICEZ0SNOW = 28  ! trude; ice was melting slighly too much. Try the original 10 instead. f\n! Density threshold for ice detection kg.m-3\nXRHOTHRESHOLD_ICE = 850.\n\n! Parameters for ageing effect on albedo\nXVAGING_NOGLACIER = 60.\nXVAGING_GLACIER   = 900.\n\n\n! trude commented this out\n! CALL INI_SURF_CSTS\n!IF (LHOOK) CALL DR_HOOK('INI_CSTS',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE INI_CSTS\n\n\nEND MODULE MODI_INI_CSTS\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/modd_csts.F",
    "content": "!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\n!     ###############\n      MODULE MODD_CSTS\n!     ###############\n!\n!!****  *MODD_CSTS* - declaration of Physic constants\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this declarative module is to declare  the\n!     Physics constants.\n!\n!!\n!!**  IMPLICIT ARGUMENTS\n!!    ------------------\n!!      None\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Ducrocq   *Meteo France*\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    16/05/94\n!!      J. Stein    02/01/95  add xrholw\n!!      J.-P. Pinty 13/12/95  add XALPI,XBETAI,XGAMI\n!!      J. Stein    25/07/97  add XTH00\n!!      V. Masson   05/10/98  add XRHOLI\n!!      C. Mari     31/10/00  add NDAYSEC\n!!      J. Escobar     06/13  add XSURF_TIMY XSURF_TIMY_12 XSURF_EPSILON for REAL*4\n!-------------------------------------------------------------------------------\n!\n!*       0.   DECLARATIONS\n!             ------------\n!\nIMPLICIT NONE\nREAL,SAVE :: XPI                ! Pi\n!\nREAL,SAVE :: XDAY,XSIYEA,XSIDAY ! day duration, sideral year duration,\n                                ! sideral day duration\n!\nREAL,SAVE :: XKARMAN            ! von karman constant\nREAL,SAVE :: XLIGHTSPEED        ! light speed\nREAL,SAVE :: XPLANCK            ! Planck constant\nREAL,SAVE :: XBOLTZ             ! Boltzman constant\nREAL,SAVE :: XAVOGADRO          ! Avogadro number\n!\nREAL,SAVE :: XRADIUS,XOMEGA     ! Earth radius, earth rotation\nREAL,SAVE :: XG                 ! Gravity constant\n!\nREAL,SAVE :: XP00               ! Reference pressure\n!\nREAL,SAVE :: XSTEFAN,XI0        ! Stefan-Boltzman constant, solar constant\n!\nREAL,SAVE :: XMD,XMV            ! Molar mass of dry air and molar mass of vapor\nREAL,SAVE :: XRD,XRV            ! Gaz constant for dry air, gaz constant for vapor\nREAL,SAVE :: XCPD,XCPV          ! Cpd (dry air), Cpv (vapor)\nREAL,SAVE :: XRHOLW             ! Volumic mass of liquid water\nREAL,SAVE :: XCL,XCI            ! Cl (liquid), Ci (ice)\nREAL,SAVE :: XTT                ! Triple point temperature\nREAL,SAVE :: XTTSI              ! Temperature of ice fusion over salty sea\nREAL,SAVE :: XTTS               ! Equivalent temperature of ice fusion over a mixed of sea and sea-ice\nREAL,SAVE :: XICEC              ! Threshold fraction over which the tile is considered as only covered with ice\nREAL,SAVE :: XLVTT              ! Vaporization heat constant\nREAL,SAVE :: XLSTT              ! Sublimation heat constant\nREAL,SAVE :: XLMTT              ! Melting heat constant\nREAL,SAVE :: XESTT              ! Saturation vapor pressure  at triple point\n                                ! temperature\nREAL,SAVE :: XALPW,XBETAW,XGAMW ! Constants for saturation vapor\n                                !  pressure  function\nREAL,SAVE :: XALPI,XBETAI,XGAMI ! Constants for saturation vapor\n                                !  pressure  function over solid ice\nREAL, SAVE        :: XTH00      ! reference value  for the potential\n                                ! temperature\nREAL,SAVE :: XRHOLI             ! Volumic mass of ice\nREAL,SAVE :: XCONDI             ! thermal conductivity of ice (W m-1 K-1)\n!\nINTEGER, SAVE :: NDAYSEC        ! Number of seconds in a day\n!\nREAL,SAVE     :: XSURF_TINY          ! minimum real on this machine\nREAL,SAVE     :: XSURF_TINY_12       ! sqrt(minimum real on this machine)\nREAL,SAVE     :: XSURF_EPSILON       ! minimum space with 1.0\n\nREAL,SAVE     :: XZ0ICEZ0SNOW, XRHOTHRESHOLD_ICE\n\n\n!\nEND MODULE MODD_CSTS\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/modd_snow_metamo.F",
    "content": "!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\n! ajoutEB\n! correction de l'erreur interversion de XVTANG2 et XVTANG3\n!######################\n      MODULE MODD_SNOW_METAMO\n!     ######################\n!\n!!****  *MODD_SNOW_METAMO* - declaration of parameters related\n!!                          to snow metamorphism!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this declarative module is to specify  the\n!     parameters related to the metamorphism parameterization of snow.\n!\n!!\n!!**  IMPLICIT ARGUMENTS\n!!    ------------------\n!!      None\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Vionnet   *Meteo France*\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original       02/2008\n!-------------------------------------------------------------------------------\n!\n!*       0.   DECLARATIONS\n!             ------------\n!\nIMPLICIT NONE\n!\n!-------------------------------------------------------------------------------\n!\n! minimum snow layer thickness for thermal calculations.\n! Used to prevent numerical problems as snow becomes vanishingly thin.\nREAL, PARAMETER                 :: XSNOWDZMIN = 0.0001\n!\n! Optical diameter properties\nREAL, PARAMETER                 :: XDIAET = 1.E-4\nREAL, PARAMETER                 :: XDIAGF = 3.E-4\nREAL, PARAMETER                 :: XDIAFP = 4.E-4\n!\n! Compaction/Settling Coefficients from Crocus v2.4\n!\nREAL, PARAMETER        :: XVVISC1 = 7.62237E6   ! pre-exponential viscosity factor (UNIT : N m-2 s)\nREAL, PARAMETER        :: XVVISC3 = 0.023       ! density adjustement in the exponential correction for viscosity (UNIT : m3 kg-1)\nREAL, PARAMETER        :: XVVISC4 = .1          ! temperature adjustement in the exponential correction for viscosity (UNIT : K-1)\nREAL, PARAMETER        :: XVVISC5 = 1.          ! factor for viscosity adjustement to grain type - to be checked\nREAL, PARAMETER        :: XVVISC6 = 60.         ! factor for viscosity adjustement to grain type - to be checked \n!                                                             (especially this one ; inconsistency with Crocus v2.4)\nREAL, PARAMETER        :: XVVISC7 = 10.         ! factor for viscosity adjustement to grain type - to be checked\nREAL, PARAMETER        :: XVRO11 = 250.  ! normalization term for density dependence of the viscosity calculation (UNIT : kg m-3)\n!\n! Maximum value for TPSNOW%GRAN2\nREAL, PARAMETER                 :: XVGRAN1 = 99.\nREAL, PARAMETER                 :: XGRAN = 99.\n!\nINTEGER, PARAMETER            :: NVHIS1 = 1\nINTEGER, PARAMETER            :: NVHIS2 = 2\nINTEGER, PARAMETER            :: NVHIS3 = 3\nINTEGER, PARAMETER            :: NVHIS4 = 4\nINTEGER, PARAMETER            :: NVHIS5 = 5\n!\n! Properties of fresh snow\nREAL, PARAMETER                 :: XNDEN1 = 17.12\nREAL, PARAMETER                 :: XNDEN2 = 128.\nREAL, PARAMETER                 :: XNDEN3 = -20.\nREAL, PARAMETER                 :: XNSPH1 = 7.87\nREAL, PARAMETER                 :: XNSPH2 = 38.\nREAL, PARAMETER                 :: XNSPH3 = 50.\nREAL, PARAMETER                 :: XNSPH4 = 90.\n!\nREAL, PARAMETER                 :: XUEPSI = 1.E-8\nREAL, PARAMETER                 :: XEPSI = 1.E-8\nREAL, PARAMETER                 :: XUPOURC = 100.\n!\n! Parameters for Marbouty's function\n!\nREAL, PARAMETER                 :: XVTANG1 = 40.\nREAL, PARAMETER                 :: XVTANG2 = 6.\nREAL, PARAMETER                 :: XVTANG3 = 22.\nREAL, PARAMETER                 :: XVTANG4 = .7\nREAL, PARAMETER                 :: XVTANG5 = .3\nREAL, PARAMETER                 :: XVTANG6 = 6.\nREAL, PARAMETER                 :: XVTANG7 = 1.\nREAL, PARAMETER                 :: XVTANG8 = .8\nREAL, PARAMETER                 :: XVTANG9 = 16.\nREAL, PARAMETER                 :: XVTANGA = .2\nREAL, PARAMETER                 :: XVTANGB = .2\nREAL, PARAMETER                 :: XVTANGC = 18.\nREAL, PARAMETER                 :: XVRANG1 = 400.\nREAL, PARAMETER                 :: XVRANG2 = 150.\nREAL, PARAMETER                 :: XVGANG1 = 70.\nREAL, PARAMETER                 :: XVGANG2 = 25.\nREAL, PARAMETER                 :: XVGANG3 = 40.\nREAL, PARAMETER                 :: XVGANG4 = 50.\nREAL, PARAMETER                 :: XVGANG5 = .1\nREAL, PARAMETER                 :: XVGANG6 = 15.\nREAL, PARAMETER                 :: XVGANG7 = .1\nREAL, PARAMETER                 :: XVGANG8 = .55\nREAL, PARAMETER                 :: XVGANG9 = .65\nREAL, PARAMETER                 :: XVGANGA = .2\nREAL, PARAMETER                 :: XVGANGB = .85\nREAL, PARAMETER                 :: XVGANGC = .15\n!\n! Parameters for snow metamorphism\n!\nREAL, PARAMETER                 :: XVDENT1 = 2314.81481\nREAL, PARAMETER                 :: XVDENT2 = 7.2338E-7\nREAL, PARAMETER                 :: XVGRAN6 = 51.\nREAL, PARAMETER                 :: XVVAP1 = -6000.\nREAL, PARAMETER                 :: XVVAP2 = .4\nREAL, PARAMETER                 :: XVDIAM1 = 4.E-4\nREAL, PARAMETER                 :: XVDIAM2 = 5.E-4\nREAL, PARAMETER                 :: XVDIAM3 = 3.E-4\nREAL, PARAMETER                 :: XVDIAM4 = 2.E-4\nREAL, PARAMETER                 :: XVDIAM5 = 1.E-4\nREAL, PARAMETER                 :: XVDIAM6 = 1.E-4\nREAL, PARAMETER                 :: XVSPHE1 = 1.\nREAL, PARAMETER                 :: XVSPHE2 = 11574.074\nREAL, PARAMETER                 :: XVSPHE3 = .5\nREAL, PARAMETER                 :: XVSPHE4 = .1\nREAL, PARAMETER                 :: XVTAIL1 = 1.28E-17\nREAL, PARAMETER                 :: XVTAIL2 = 4.22E-19\nREAL, PARAMETER                 :: XVGRAT1 = 5.\nREAL, PARAMETER                 :: XVGRAT2 = 15.\nREAL, PARAMETER                 :: XVFI = 1.0417E-9\nREAL, PARAMETER                 :: XVTELV1 = 0.005\n!\nINTEGER,PARAMETER               :: NVDENT1 = 3\n!\nINTEGER :: NVARDIMS !number of dimensions of netcdf input variable\nINTEGER :: NLENDIM1,NLENDIM2,NLENDIM3\nINTEGER :: NID_VAR ! Netcdf IDs for  variable\n!\nINTEGER :: NID_FILE\nREAL, DIMENSION(:,:,:), POINTER :: XDRDT0,XTAU,XKAPPA   ! field read\n!\nEND MODULE MODD_SNOW_METAMO\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/modd_snow_par.F",
    "content": "!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\n!     ######################\n      MODULE MODD_SNOW_PAR\n!     ######################\n!\n!!****  *MODD_SNOW_PAR* - declaration of parameters related\n!!                          to the snow parameterization\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this declarative module is to specify  the\n!     parameters related to the surface parameterization of snow.\n!\n!!\n!!**  IMPLICIT ARGUMENTS\n!!    ------------------\n!!      None\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!\tV. Masson   *Meteo France*\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original       01/2004\n!! P. Samuelsson  10/2014   MEB complements\n!-------------------------------------------------------------------------------\n!\n!*       0.   DECLARATIONS\n!             ------------\n!\nIMPLICIT NONE\n!\n!--------------------------------------------------------------------------------\n! Snow on the ground: Given in ini_surf_csts and/or in NAM_SURF_CSTS\n!--------------------------------------------------------------------------------\n!\n! Snow emissivity:\n!\n!REAL, SAVE       :: XEMISSN\nREAL, PARAMETER       :: XEMISSN = 0.99   ! trude. Check  how this stands up to ini_sfc_csts. \n!\n! Minimum and maximum values of the albedo of snow:\n!\n!REAL, SAVE       :: XANSMIN\n!REAL, SAVE       :: XANSMAX\nREAL, PARAMETER     :: XANSMIN=0.50    ! (orig 0.50, trude test with 0.55 (0.6))   ! trude\nREAL, PARAMETER     :: XANSMAX =0.85  !trude\n\n\n!\n! Minimum and maximum values of the albedo of permanet snow/ice:\n!\n!REAL, SAVE       :: XAGLAMIN\n!REAL, SAVE       :: XAGLAMAX\nREAL, PARAMETER       :: XAGLAMIN = 0.8   ! trude\nREAL, PARAMETER       :: XAGLAMAX = 0.85  ! trude\n\n!\n! Use recommended settings for snow albedo (FALSE = ISBA default)\n!\nLOGICAL,SAVE     :: LMEBREC\n!\n! Fraction of maximum value of the albedo of snow that is reached for melting\n! snow\n!\nREAL, SAVE       :: XANSFRACMEL\n!\n! Threeshold temperature above which the snow albedo starts to decrease\n!\nREAL, SAVE       :: XTEMPANS\n!\n! Minimum value of the albedo of snow reached under canopy vegetation:\n!\nREAL, SAVE       :: XANSMINMEB\n!\n! Prescribed ice albedo in 3 spectral bands for glacier simulation with CROCUS scheme.\n!REAL, SAVE       :: XALBICE1,XALBICE2,XALBICE3\n!REAL, PARAMETER       :: XALBICE1 = 0.23   ! (0.23 from Gerbaux,  0.38 orig crocus)     ! trude \n!REAL, PARAMETER       :: XALBICE2 = 0.15   ! (0.15 from Gerbaux,  0.23  orig crocus)  ! trude\n!REAL, PARAMETER       :: XALBICE3 = 0.06  ! 0.06 from Gerbaux ,   0.08 orig crocus     ! trude\nREAL, PARAMETER       :: XALBICE1 = 0.38   ! (0.23 from Gerbaux,  0.38 orig crocus)     ! trude \nREAL, PARAMETER       :: XALBICE2 = 0.23   ! (0.15 from Gerbaux,  0.23  orig crocus)  ! trude\nREAL, PARAMETER       :: XALBICE3 = 0.08  ! 0.06 from Gerbaux ,   0.08 orig crocus     ! trude\n\n!REAL, PARAMETER       :: XALBICE1 = 0.67   ! (0.23 from Gerbaux,  0.38 orig crocus)     ! trude test snowalbedo instead\n!REAL, PARAMETER       :: XALBICE2 = 0.67   ! (0.15 from Gerbaux,  0.23  orig crocus)  ! trude\n!REAL, PARAMETER       :: XALBICE3 = 0.67  ! 0.06 from Gerbaux ,   0.08 orig crocus     ! trude\n\n!\n\n! Density threshold for ice detection in CROCUS scheme.\n!REAL, SAVE       :: XRHOTHRESHOLD_ICE   ! trude comment out in modd_csts\n\n!for ageing effects\n!REAL, SAVE      :: XVAGING_NOGLACIER, XVAGING_GLACIER\nREAL, PARAMETER      :: XVAGING_NOGLACIER = 60.\nREAL, PARAMETER      ::  XVAGING_GLACIER  = 900.\n\n! percentage of the total pore volume to compute the max liquid water holding capacity\n!REAL, SAVE      :: XPERCENTAGEPORE\nREAL, PARAMETER      :: XPERCENTAGEPORE = 0.03   !   5   ! trude try 3 instead of 5.\n!REAL, PARAMETER      :: XPERCENTAGEPORE = 0.05   !   5   ! trude try 3 instead of 5.\n! Height (m) of aged snow in glacier case (allows Pn=1)\n!\nREAL, SAVE       :: XHGLA\n!\n! Coefficient for calculation of snow fraction over vegetation\n!\nREAL, SAVE       :: XWSNV\n!\n! Roughness length of pure snow surface (m)\n!\n!REAL, SAVE       :: XZ0SN\n!REAL, PARAMETER       :: XZ0SN =0.00005  ! trude,  (0.05 mm)\n!REAL, PARAMETER        :: XZ0SN =0.00013  ! trude,  (0.13 mm)\nREAL, PARAMETER        :: XZ0SN =0.001  ! trude,  (1.0 mm)\n!REAL, PARAMETER        :: XZ0SN =0.0002  ! trude,  (0.2 mm)\n! Roughness length for heat of pure snow surface (m)\n!\n!REAL, SAVE       :: XZ0HSN\nREAL, PARAMETER       :: XZ0HSN   =0.00015   ! trude (test 5 mm instead of 0.5 mm)\n!REAL, PARAMETER       :: XZ0HSN   =0.0001   ! orignal in surfex is 0.0001\n\n\n! Roughness length ratio between ice and snow\n!REAL, SAVE       :: XZ0ICEZ0SNOW     ! trude comment out. declared in modd_csts\n!\n! Snow Melt timescale with D95 (s): needed to prevent time step\n! dependence of melt when snow fraction < unity.\n!\nREAL, SAVE       :: XTAU_SMELT\n!\n!--------------------------------------------------------------------------------\n! Snow on the ground: PARAMETER\n!--------------------------------------------------------------------------------\n!\n! Critical value of the equivalent water content\n! of the snow reservoir for snow fractional coverage and albedo computations\n!\nREAL, PARAMETER       :: XWCRN      = 10.0   ! (kg m-2) Veg (default value)\nREAL, PARAMETER       :: XWCRN_EXPL =  1.0   ! (kg m-2) Veg explicit\nREAL, PARAMETER       :: XWCRN_ROOF =  1.0   ! (kg m-2)  Roofs\nREAL, PARAMETER       :: XWCRN_ROAD =  1.0   ! (kg m-2)  Roads\nREAL, PARAMETER       :: XWCRN_VEG  =  1.0   ! (kg m-2)  Urban veg\n!\n! Critical value of the total snow depth for ground snow fractional coverage\n!\nREAL, PARAMETER       :: XDCRN_EXPL = 0.01  ! (m) Veg explicit\n!\n! Critical value of snow emissivity\n!\nREAL, PARAMETER       :: XEMCRIN = 0.98\n!\n! Minimum and maximum values of the albedo of snow:\n!\nREAL, PARAMETER       :: XANSMIN_ROOF = 0.30 ! (-)   Roofs\nREAL, PARAMETER       :: XANSMIN_ROAD = 0.15 ! (-)   Roads\n!\nREAL, PARAMETER       :: XANSMAX_ROOF = 0.85 ! (-)   Roofs\nREAL, PARAMETER       :: XANSMAX_ROAD = 0.85 ! (-)   Roads\n!\n! Snow aging coefficients (albedo and Force-Restore density):\n!\nREAL, PARAMETER       :: XANS_TODRY    = 0.008     ! (-) Veg (default value)\nREAL, PARAMETER       :: XANS_TODRY_ROOF = 0.008   ! (-)  Roofs\nREAL, PARAMETER       :: XANS_TODRY_ROAD = 0.008   ! (-)  Roads\nREAL, PARAMETER       :: XANS_TODRY_MEB  = 0.016   ! (-) Surface under canopy vegetation\n!\nREAL, PARAMETER       :: XANS_T        = 0.240     ! (-) Veg (default value)\nREAL, PARAMETER       :: XANS_T_ROOF     = 0.174   ! (-)  Roofs\nREAL, PARAMETER       :: XANS_T_ROAD     = 0.174   ! (-)  Roads (alley simul)\nREAL, PARAMETER       :: XANS_T_MEB    = 0.480     ! (-) Surface under canopy vegetation\n!\n! Minimum and maximum values of the density of snow\n! for Force-Restore snow option\n!\nREAL, PARAMETER       :: XRHOSMIN = 100.       ! (kg m-3)   Veg (Default value)\nREAL, PARAMETER       :: XRHOSMIN_ROOF = 100.  ! (kg m-3)   Roofs\nREAL, PARAMETER       :: XRHOSMIN_ROAD = 100.  ! (kg m-3)   Roads\n!\nREAL, PARAMETER       :: XRHOSMAX = 300.       ! (kg m-3)   Veg (Default value)\nREAL, PARAMETER       :: XRHOSMAX_ROOF = 300.  ! (kg m-3)   Roofs\nREAL, PARAMETER       :: XRHOSMAX_ROAD = 350.  ! (kg m-3)   Roads\n!\n! Minimum and maximum values of the density of snow\n! for ISBA-ES snow option\n!\nREAL, PARAMETER       :: XRHOSMIN_ES =  50.  ! (kg m-3)\nREAL, PARAMETER       :: XRHOSMAX_ES = 750.  ! (kg m-3)\n!\n! ISBA-ES Critical snow depth at which snow grid thicknesses constant\n!\nREAL, PARAMETER       :: XSNOWCRITD = 0.03  ! (m)\n!\n! ISBA-ES Minimum total snow depth for thermal calculations.\n! Used to prevent numerical problems as snow becomes vanishingly thin.\n!\nREAL, PARAMETER      :: XSNOWDMIN = 0.000001  ! (m)\n!\n! Maximum Richardson number limit for very stable conditions using the ISBA-ES 'RIL' option\n!\nREAL, PARAMETER       :: X_RI_MAX = 0.20\n!REAL, PARAMETER       :: X_RI_MAX = 0.026  !  trude test lower limit\n!\n! ISBA-ES Maximum snow liquid water holding capacity (fraction by mass) parameters:\n!\nREAL, PARAMETER       :: XWSNOWHOLDMAX2   = 0.10  ! (-)\nREAL, PARAMETER       :: XWSNOWHOLDMAX1   = 0.03  ! (-)\nREAL, PARAMETER       :: XSNOWRHOHOLD     = 200.0 ! (kg/m3)\n!\n! ISBA-ES arameters for grain size computation :\n!\nREAL, PARAMETER       :: XSNOW_AGRAIN = 1.6e-4   ! (m)\nREAL, PARAMETER       :: XSNOW_BGRAIN = 1.1e-13  ! (m13/kg4)\nREAL, PARAMETER       :: XSNOW_CGRAIN = 0.5e-4   ! (m)\nREAL, PARAMETER       :: XDSGRAIN_MAX = 2.796e-3 ! m\n!\n!--------------------------------------------------------------------------------\n! Calibration coefficients for CROCUS and ES albedo computation\n!--------------------------------------------------------------------------------\n!\nREAL, PARAMETER :: XD1 = 1., XD2 = 3., XD3 = 4., XX = 99., &\n                   XVALB2 = .96, XVALB3 = 1.58, XVALB4 = .92, XVALB5 = .90, &\n                   XVALB6 = 15.4, XVALB7 = 346.3, XVALB8 = 32.31, XVALB9 = .88, &\n                   XVALB10 = .200, XVALB11 = .65, XVDIOP1 = 2.3E-3, XVRPRE1 = .5, &\n                   XVRPRE2=1.5\n\n! trude , test XVALB11 = 0.7 instead of 0.6\n! trude , test XVALB11 = 0.65 instead of 0.6\n\n! for ageing effects:\nREAL, PARAMETER :: XVPRES1 = 87000.\n!\n! spectral bands\n!\nINTEGER, PARAMETER :: NSPEC_BAND_SNOW = 3\n!\n! for spectral distribution and thickness effects\nREAL, PARAMETER :: XVSPEC1 = .71, XVSPEC2 = .21, XVSPEC3 = .08\n!\n! for thickness effects\nREAL, PARAMETER :: XVW1 = .80, XVW2 = .20 , XVD1 = .02, XVD2 = .01\n!\n!--------------------------------------------------------------------------------\n! calibration coefficients for exctinction computation\nREAL, PARAMETER :: XVBETA1 = 1.92E-3, XVBETA2 = 40., XVBETA3 = 1.098E-2, &\n                   XVBETA4 = 100.,  XVBETA5 = 2000.\n!\n! ISBA-ES minimum cosinus of zenithal angle\nREAL, PARAMETER :: XMINCOSZEN = 0.01\n!\n!--------------------------------------------------------------------------------\n! ISBA-ES Thermal conductivity coefficients from Anderson (1976):\n! see Boone, Meteo-France/CNRM Note de Centre No. 70 (2002)\n!\nREAL, PARAMETER :: XSNOWTHRMCOND1 = 0.02    ! [W/(m K)]\nREAL, PARAMETER :: XSNOWTHRMCOND2 = 2.5E-6  ! [W m5/(kg2 K)]\n!\n! ISBA-ES Thermal conductivity: Implicit vapor diffn effects\n! (sig only for new snow OR high altitudes)\n! from Sun et al. (1999): based on data from Jordan (1991)\n! see Boone, Meteo-France/CNRM Note de Centre No. 70 (2002)\n!\nREAL, PARAMETER :: XSNOWTHRMCOND_AVAP = -0.06023 ! [W/(m K)]\nREAL, PARAMETER :: XSNOWTHRMCOND_BVAP = -2.5425  ! (W/m)\nREAL, PARAMETER :: XSNOWTHRMCOND_CVAP = -289.99  ! (K)\n!\n! Crocus thermal conducitivity coefficient from Yen (1981)\nREAL, PARAMETER :: XVRKZ6 = 1.88\n!\n!--------------------------------------------------------------------------------\n! ISBA-ES CROCUS (Pahaut 1976): snowfall density coefficients:\n!\nREAL, PARAMETER :: XSNOWFALL_A_SN = 109.0  ! kg/m3\nREAL, PARAMETER :: XSNOWFALL_B_SN =   6.0  ! kg/(m3 K)\nREAL, PARAMETER :: XSNOWFALL_C_SN =  26.0  ! kg/(m7/2 s1/2)\n!\n! Coefficients for the optimal vertical grid calculation\nREAL, PARAMETER :: XDZ1 = 0.01\nREAL, PARAMETER :: XDZ2 = 0.0125\nREAL, PARAMETER :: XDZ3 = 0.015\nREAL, PARAMETER :: XDZ3_BIS = 0.03\nREAL, PARAMETER :: XDZ4 = 0.04\nREAL, PARAMETER :: XDZ5 = 0.05\nREAL, PARAMETER :: XDZ_BASE = 0.02\nREAL, PARAMETER :: XDZ_INTERNAL = 0.07\nREAL, PARAMETER :: XSCALE_CM = 100.\nREAL,DIMENSION(5), PARAMETER :: XDZMAX_INTERNAL = (/0.5,1.,2.,4.,10./)\nREAL, PARAMETER :: XDZMIN_TOP_EXTREM = 0.0001\n!\n! Below this threshold of snowfall, new snowfall are aggregated with surface layer to avoid numerical problems\n! (0.03 mm/h)\nREAL,PARAMETER :: XSNOWFALL_THRESHOLD = 0.0333/3600.\n\n! The ratio between a new surface layer thickness and the second layer surface thickness is limited to 1/10\nREAL,PARAMETER :: XRATIO_NEWLAYER = 0.1\n\n! Coefficients for cases with very thick snowpacks\nREAL, PARAMETER :: XDEPTH_THRESHOLD1 = 3.\nREAL, PARAMETER :: XDEPTH_THRESHOLD2 = 20.\nREAL, PARAMETER :: XDEPTH_SURFACE = 3.\n!\n! Coefficients for computing the difference in 2 snow layer characteristics\nREAL, PARAMETER :: XDIFF_1 = 20.\nREAL, PARAMETER :: XDIFF_MAX = 200.\nREAL, PARAMETER :: XSCALE_DIFF = 25.\n!\n! Coeefficients for snow layer splitting\nREAL, PARAMETER :: XDZMIN_TOP = 0.01\nREAL, PARAMETER :: XDZMIN_TOP_BIS = 0.005\nREAL, PARAMETER :: XDZMIN_BOT = 0.02\nREAL, PARAMETER :: XSPLIT_COEF = 8.\n!\n! Coeefficients for snow layer agregation\nREAL, PARAMETER :: XAGREG_COEF_1 = 5.\nREAL, PARAMETER :: XAGREG_COEF_2 = 4.5\n!\n!--------------------------------------------------------------------------------\n!\n! Calibration coefficients\nREAL, PARAMETER :: XVTIME = 48*3600. ! characteristic time for\n!compaction and metamorphism by wind drift\n!\nREAL, PARAMETER :: XVROMAX = 350. !  maximum density for\n! drift compaction     UNIT : kg m-3\nREAL, PARAMETER :: XVROMIN = 50.  !  minimum density for\n! mobility computation UNIT : kg m-3\nREAL, PARAMETER :: XVMOB1 = 0.295  !  coefficient for computing\n! the mobility index\nREAL, PARAMETER :: XVMOB2 = 0.833  !  coefficient for computing\n! the mobility index\nREAL, PARAMETER :: XVMOB3 = 0.583  !  coefficient for computing\n! the mobility index\nREAL, PARAMETER :: XVMOB4 = -0.0583 !  coefficient for computing\n! the mobility index\nREAL, PARAMETER :: XVDRIFT1 = 2.868 !  coefficient for computing\n! the drift index\nREAL, PARAMETER :: XVDRIFT2 = 0.085 !  coefficient for computing\n! the drift index\nREAL, PARAMETER :: XVDRIFT3 = 3.25  !  coefficient for computing\n! the drift index\nREAL, PARAMETER :: XVSIZEMIN = 3.E-4 !  minimum size decrease\n! by drift  UNIT = m\n!\n! modif_EB pour sublim\n! a pour but de tenir compte du fait que le vent moyen est > rafales\n! on en tient compte egalement pour diminuer la duree de l'effet\nREAL, PARAMETER :: XCOEF_FF = 1.25 ! coefficient for gust diagnosis from average wind \nREAL, PARAMETER :: XCOEF_EFFECT = 1.0 ! coefficient for impact on density du drift\nREAL, PARAMETER :: XQS_REF = 2.E-5 ! valeur de reference de ZQS pour effet neige\n!\n!--------------------------------------------------------------------------------\n!\n! ISBA-ES snow grid parameters\n!\nREAL, PARAMETER, DIMENSION(3)     :: XSGCOEF1  = (/0.25, 0.50, 0.25/)\nREAL, PARAMETER, DIMENSION(2)     :: XSGCOEF2  = (/0.05, 0.34/)\nREAL, PARAMETER, DIMENSION(10)    :: XSGCOEF3  = (/0.025, 0.033, 0.043, &\n                                     0.055, 0.071, 0.091, 0.117, 0.150, &\n                                     0.193, 0.247/)\n!\n! Minimum total snow depth at which surface layer thickness is constant:\n!\nREAL, PARAMETER                   :: XSNOWTRANS = 0.20                ! (m)\nREAL, PARAMETER                   :: XSNOWTRANS1 = 0.40                ! (m)\nREAL, PARAMETER                   :: XSNOWTRANS2 = 0.6061                ! (m)\nREAL, PARAMETER                   :: XSNOWTRANS3 = 0.7143               ! (m)\nREAL, PARAMETER                   :: XSNOWTRANS4 = 0.9259                ! (m)\nREAL, PARAMETER                   :: XSNOWTRANS5 = 1.4493                ! (m)\n\n! * qsat computation\n!\n CHARACTER(LEN=3), PARAMETER :: CQSAT = 'NEW' ! qsat computation option\n!                         ! 'OLD' = do not depend on temperature\n!                         ! 'NEW' = qsat and qsati merged (recommended)\n!\nREAL,    PARAMETER :: XUNDEF = 1.E+20\n\n\n!\n!------------------------------------------------------------------------------\n!\nEND MODULE MODD_SNOW_PAR\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/modd_surf_atm.F",
    "content": "!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\n!     ####################\n      MODULE MODD_SURF_ATM\n!     ####################\n!\n!!****  *MODD_SURF_ATM - declaration of surface ATM\n!!\n!!    PURPOSE\n!!    -------\n!     Declaration of surface parameters\n!\n!!\n!!**  IMPLICIT ARGUMENTS\n!!    ------------------\n!!      None\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!    AUTHOR\n!!    ------\n!!      P. Le Moigne *Meteo France*\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original       10/2007\n!\n!*       0.   DECLARATIONS\n!             ------------\n!\n!!      B.Decharme     04/2009 Add flag used to Read/Write precipitation forcing from/into the restart file for ARPEGE/ALADIN run\n!!      B.Decharme     08/2009 Add flag used to know if you use SURFEX in the Earth System Model\n!!      B.Decharme     09/2012 New wind implicitation key option\n!!      B.Decharme     04/2013 Flag used to Read/Write some field from/into the restart file for coupling with ARPEGE/ALADIN\n!!                             Delete LRW_PRECIP, LSAVE_PRECIP\n!!                             Vertical shift for LW and Precip\n!!      R. Séférian    03/2014 Adding key for decouple CO2 for photosynthesis (XCO2UNCPL) \n!\nIMPLICIT NONE\n!\n!-----------------------------------------------------------------------------------------------------\nREAL,PARAMETER       :: XCISMIN=6.7e-5  ! minimum wind shear\nREAL,PARAMETER       :: XVMODMIN=0.0 ! minimum wind speed\nLOGICAL,PARAMETER    :: LALDTHRES=.FALSE. ! activate aladin threshold for wind\n!\nLOGICAL    :: LDRAG_COEF_ARP ! activate aladin formulation for Cd and Ch\nLOGICAL    :: LALDZ0H\n!\nLOGICAL    :: LNOSOF   ! No parameterization of Subgrid Orography effects on atmospheric Forcing  \nLOGICAL    :: LVERTSHIFT ! vertical shift from atmospheric orography to surface orography\nLOGICAL    :: LVSHIFT_LW ! vertical shift for LW\nLOGICAL    :: LVSHIFT_PRCP ! vertical shift for Precip\n!\nLOGICAL    :: LVZIUSTAR0_ARP   ! activate aladin formulation for zoh over sea\nLOGICAL    :: LRRGUST_ARP      ! activate aladin formulation for CD CH, CDN, correction due to moist gustiness\nLOGICAL    :: LCPL_ARP         ! activate aladin formulation for Cp and L\nLOGICAL    :: LQVNPLUS         ! An option for the resolution of the surface temperature equation\n!\nLOGICAL    :: LCPL_GCM         ! Flag used to Read/Write some field from/into the restart file for coupling with ARPEGE/ALADIN\n!\nREAL       :: XEDB\nREAL       :: XEDC\nREAL       :: XEDD\nREAL       :: XEDK\nREAL       :: XUSURIC\nREAL       :: XUSURID\nREAL       :: XUSURICL\nREAL       :: XVCHRNK\nREAL       :: XVZ0CM\nREAL,PARAMETER       :: XRIMAX=0.2\nREAL       :: XDELTA_MAX ! Maximum fraction of the foliage covered by intercepted water for high vegetation\n!\nREAL       :: XWINDMIN ! minimum wind speed (canopy)\n!\nREAL       :: XRZHZ0M\nREAL       :: XVZIUSTAR0\nREAL       :: XRRSCALE\nREAL       :: XRRGAMMA\nREAL       :: XUTILGUST\n!\nREAL       :: XCO2UNCPL ! uncoupled CO2 values (ppmv)\n!\n!-----------------------------------------------------------------------------------------------------\n!\nEND MODULE MODD_SURF_ATM\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/mode_snow3l.F",
    "content": "!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\n!     ##################\n      MODULE MODE_SNOW3L\n!     ##################\n!\n!!****  *MODE_SNOW * - contains explicit snow (ISBA-ES) characteristics functions\n!!                     for total liquid water holding capacity of a snow layer (m)\n!!                     and the thermal heat capacity of a layer (J K-1 m-3)\n!!\n!!    PURPOSE\n!!    -------\n!\n!!**  METHOD\n!!    ------\n!!    direct calculation\n!!\n!!    EXTERNAL\n!!    --------\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!\n!!    REFERENCE\n!!    ---------\n!!    Boone and Etchevers, J. HydroMeteor., 2001\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!\tA. Boone       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original        01/08/02\n!!      V. Masson       01/2004  add snow grid computations\n!!      V. Vionnet      06/2008 -Introduction of Crocus formulation to\n!                       calculate maximum liquid water holding capacity\n!!                              - New algorithm to compute snow grid :\n!                       10 layers\n!!                              - Routine to aggregate snow grain type\n!                       from 2 layers\n!!                              _ Routine to compute average grain\n!                       type when snow depth< 3 cm.\n!     S. Morin          02/2011 - Add routines for Crocus\n!     A. Boone          02/2012 - Add optimization of do-loops.\n!     C. Carmagnola     12/2012 - Add the case CSNOWMETAMO!='B92' in subroutine SNOW3LAVGRAIN and in function SNOW3LDIFTYP\n!     M. Lafaysse       01/2013 - Remove SNOWCROWLIQMAX routines (not used)\n!     M. Lafaysse       08/2013 - simplification of routine SNOW3LAVGRAIN (logical GDENDRITIC)\n!     B. Decharme       07/2013 - SNOW3LGRID cleanning\n!                                 New algorithm to compute snow grid for 6-L or 12-L\n!     A. Boone          10/2014 - Added snow thermal conductivity routines\n!     B. Decharme       01/2015 - Added optical snow grain size diameter\n!----------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!\n!\nINTERFACE SNOW3LWLIQMAX\n  MODULE PROCEDURE SNOW3LWLIQMAX_3D\n  MODULE PROCEDURE SNOW3LWLIQMAX_2D\n  MODULE PROCEDURE SNOW3LWLIQMAX_1D\nEND INTERFACE\n!\nINTERFACE SNOW3LHOLD\n  MODULE PROCEDURE SNOW3LHOLD_3D\n  MODULE PROCEDURE SNOW3LHOLD_2D\n  MODULE PROCEDURE SNOW3LHOLD_1D\n  MODULE PROCEDURE SNOW3LHOLD_0D\nEND INTERFACE\nINTERFACE SNOWCROHOLD\n  MODULE PROCEDURE SNOWCROHOLD_3D\n  MODULE PROCEDURE SNOWCROHOLD_2D\n  MODULE PROCEDURE SNOWCROHOLD_1D\n  MODULE PROCEDURE SNOWCROHOLD_0D\nEND INTERFACE\n!\nINTERFACE SNOW3LSCAP\n  MODULE PROCEDURE SNOW3LSCAP_3D\n  MODULE PROCEDURE SNOW3LSCAP_2D\n  MODULE PROCEDURE SNOW3LSCAP_1D\n  MODULE PROCEDURE SNOW3LSCAP_0D\nEND INTERFACE\n!\nINTERFACE SNOW3L_MARBOUTY\n  MODULE PROCEDURE SNOW3L_MARBOUTY\nEND INTERFACE\n!\nINTERFACE SNOW3LGRID\n  MODULE PROCEDURE SNOW3LGRID_2D\n  MODULE PROCEDURE SNOW3LGRID_1D\nEND INTERFACE\n!\nINTERFACE SNOW3LAGREG\n  MODULE PROCEDURE SNOW3LAGREG\nEND INTERFACE\n!\nINTERFACE SNOW3LAVGRAIN\n  MODULE PROCEDURE SNOW3LAVGRAIN\nEND INTERFACE\n!\nINTERFACE SNOW3LDIFTYP\n  MODULE PROCEDURE SNOW3LDIFTYP\nEND INTERFACE\n!\nINTERFACE GET_MASS_HEAT\n  MODULE PROCEDURE GET_MASS_HEAT\nEND INTERFACE\n!\nINTERFACE GET_DIAM\n  MODULE PROCEDURE GET_DIAM\nEND INTERFACE\n!\n!\nINTERFACE SNOW3LTHRM\n  MODULE PROCEDURE SNOW3LTHRM\nEND INTERFACE\n!\nINTERFACE SNOW3LDOPT\n  MODULE PROCEDURE SNOW3LDOPT_2D\n  MODULE PROCEDURE SNOW3LDOPT_1D\n  MODULE PROCEDURE SNOW3LDOPT_0D\nEND INTERFACE\n!\nINTERFACE SNOW3LALB\n  MODULE PROCEDURE SNOW3LALB\nEND INTERFACE\n!\n!-------------------------------------------------------------------------------\n CONTAINS\n!\n!####################################################################\n      FUNCTION SNOW3LWLIQMAX_3D(PSNOWRHO) RESULT(PWLIQMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_SNOW_PAR, ONLY : XRHOSMAX_ES, XSNOWRHOHOLD,      &\n                          XWSNOWHOLDMAX2, XWSNOWHOLDMAX1\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:,:), INTENT(IN)                                  :: PSNOWRHO ! (kg/m3)\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2),SIZE(PSNOWRHO,3)) :: PWLIQMAX ! (kg/m3)\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2),SIZE(PSNOWRHO,3)) :: ZHOLDMAXR, ZSNOWRHO\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-----------------------------------------------------------------------\n! Evaluate capacity using upper density limit:\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LWLIQMAX_3D',0,ZHOOK_HANDLE)\nZSNOWRHO(:,:,:) = MIN(XRHOSMAX_ES, PSNOWRHO(:,:,:))\n!\n! Maximum ratio of liquid to SWE:\n!\nZHOLDMAXR(:,:,:) = XWSNOWHOLDMAX1 + (XWSNOWHOLDMAX2-XWSNOWHOLDMAX1)*    &\n                  MAX(0.,XSNOWRHOHOLD-ZSNOWRHO(:,:,:))/XSNOWRHOHOLD\n!\n! Maximum liquid water holding capacity of the snow (kg/m3):\n!\nPWLIQMAX(:,:,:) = ZHOLDMAXR(:,:,:)*ZSNOWRHO(:,:,:)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LWLIQMAX_3D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LWLIQMAX_3D\n!####################################################################\n      FUNCTION SNOW3LWLIQMAX_2D(PSNOWRHO) RESULT(PWLIQMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_SNOW_PAR, ONLY : XRHOSMAX_ES, XSNOWRHOHOLD,      &\n                          XWSNOWHOLDMAX2, XWSNOWHOLDMAX1\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(IN)                   :: PSNOWRHO ! (kg/m3)\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: PWLIQMAX ! (kg/m3)\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZHOLDMAXR, ZSNOWRHO\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-----------------------------------------------------------------------\n! Evaluate capacity using upper density limit:\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LWLIQMAX_2D',0,ZHOOK_HANDLE)\nZSNOWRHO(:,:) = MIN(XRHOSMAX_ES, PSNOWRHO(:,:))\n!\n! Maximum ratio of liquid to SWE:\n!\nZHOLDMAXR(:,:) = XWSNOWHOLDMAX1 + (XWSNOWHOLDMAX2-XWSNOWHOLDMAX1)*    &\n                  MAX(0.,XSNOWRHOHOLD-ZSNOWRHO(:,:))/XSNOWRHOHOLD\n!\n! Maximum liquid water holding capacity of the snow (kg/m3):\n!\nPWLIQMAX(:,:) = ZHOLDMAXR(:,:)*ZSNOWRHO(:,:)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LWLIQMAX_2D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LWLIQMAX_2D\n!####################################################################\n      FUNCTION SNOW3LWLIQMAX_1D(PSNOWRHO) RESULT(PWLIQMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_SNOW_PAR, ONLY : XRHOSMAX_ES, XSNOWRHOHOLD,      &\n                           XWSNOWHOLDMAX2, XWSNOWHOLDMAX1\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)  :: PSNOWRHO ! (kg/m3)\n!\nREAL, DIMENSION(SIZE(PSNOWRHO)) :: PWLIQMAX ! (kg/m3)\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO)) :: ZHOLDMAXR, ZSNOWRHO\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!----------------------------------------------------------------------\n! Evaluate capacity using upper density limit:\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LWLIQMAX_1D',0,ZHOOK_HANDLE)\nZSNOWRHO(:) = MIN(XRHOSMAX_ES, PSNOWRHO(:))\n!\n! Maximum ratio of liquid to SWE:\n!\nZHOLDMAXR(:) = XWSNOWHOLDMAX1 + (XWSNOWHOLDMAX2-XWSNOWHOLDMAX1)*    &\n                  MAX(0.,XSNOWRHOHOLD-ZSNOWRHO(:))/XSNOWRHOHOLD\n!\n! Maximum liquid water holding capacity of the snow (kg/m3):\n!\nPWLIQMAX(:) = ZHOLDMAXR(:)*ZSNOWRHO(:)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LWLIQMAX_1D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LWLIQMAX_1D\n\n!####################################################################\n!####################################################################\n!####################################################################\n      FUNCTION SNOW3LHOLD_3D(PSNOWRHO,PSNOWDZ) RESULT(PWHOLDMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_CSTS,     ONLY : XRHOLW\nUSE MODD_SNOW_PAR, ONLY : XRHOSMAX_ES, XSNOWRHOHOLD,      &\n                          XWSNOWHOLDMAX2, XWSNOWHOLDMAX1\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:,:), INTENT(IN)                 :: PSNOWDZ, PSNOWRHO\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2),SIZE(PSNOWRHO,3)) :: PWHOLDMAX\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2),SIZE(PSNOWRHO,3)) :: ZHOLDMAXR, ZSNOWRHO\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------\n! Evaluate capacity using upper density limit:\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LHOLD_3D',0,ZHOOK_HANDLE)\nZSNOWRHO(:,:,:) = MIN(XRHOSMAX_ES, PSNOWRHO(:,:,:))\n!\n! Maximum ratio of liquid to SWE:\n!\nZHOLDMAXR(:,:,:) = XWSNOWHOLDMAX1 + (XWSNOWHOLDMAX2-XWSNOWHOLDMAX1)*    &\n                  MAX(0.,XSNOWRHOHOLD-ZSNOWRHO(:,:,:))/XSNOWRHOHOLD\n!\n! Maximum liquid water holding capacity of the snow (m):\n!\nPWHOLDMAX(:,:,:) = ZHOLDMAXR(:,:,:)*PSNOWDZ(:,:,:)*ZSNOWRHO(:,:,:)/XRHOLW\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LHOLD_3D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LHOLD_3D\n!####################################################################\n      FUNCTION SNOW3LHOLD_2D(PSNOWRHO,PSNOWDZ) RESULT(PWHOLDMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_CSTS,     ONLY : XRHOLW\nUSE MODD_SNOW_PAR, ONLY : XRHOSMAX_ES, XSNOWRHOHOLD,      &\n                          XWSNOWHOLDMAX2, XWSNOWHOLDMAX1\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(IN)                   :: PSNOWDZ, PSNOWRHO\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: PWHOLDMAX\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZHOLDMAXR, ZSNOWRHO\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-----------------------------------------------------------------------\n! Evaluate capacity using upper density limit:\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LHOLD_2D',0,ZHOOK_HANDLE)\nZSNOWRHO(:,:) = MIN(XRHOSMAX_ES, PSNOWRHO(:,:))\n!\n! Maximum ratio of liquid to SWE:\n!\nZHOLDMAXR(:,:) = XWSNOWHOLDMAX1 + (XWSNOWHOLDMAX2-XWSNOWHOLDMAX1)*    &\n                  MAX(0.,XSNOWRHOHOLD-ZSNOWRHO(:,:))/XSNOWRHOHOLD\n!\n! Maximum liquid water holding capacity of the snow (m):\n!\nPWHOLDMAX(:,:) = ZHOLDMAXR(:,:)*PSNOWDZ(:,:)*ZSNOWRHO(:,:)/XRHOLW\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LHOLD_2D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LHOLD_2D\n!####################################################################\n      FUNCTION SNOW3LHOLD_1D(PSNOWRHO,PSNOWDZ) RESULT(PWHOLDMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_CSTS,     ONLY : XRHOLW\nUSE MODD_SNOW_PAR, ONLY : XRHOSMAX_ES, XSNOWRHOHOLD,     &\n                          XWSNOWHOLDMAX2, XWSNOWHOLDMAX1\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)                     :: PSNOWDZ, PSNOWRHO\n!\nREAL, DIMENSION(SIZE(PSNOWRHO))                    :: PWHOLDMAX\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO))                    :: ZHOLDMAXR, ZSNOWRHO\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-----------------------------------------------------------------------\n! Evaluate capacity using upper density limit:\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LHOLD_1D',0,ZHOOK_HANDLE)\nZSNOWRHO(:) = MIN(XRHOSMAX_ES, PSNOWRHO(:))\n!\n! Maximum ratio of liquid to SWE:\n!\nZHOLDMAXR(:) = XWSNOWHOLDMAX1 + (XWSNOWHOLDMAX2-XWSNOWHOLDMAX1)*     &\n                  MAX(0.,XSNOWRHOHOLD-ZSNOWRHO(:))/XSNOWRHOHOLD\n!\n! Maximum liquid water holding capacity of the snow (m):\n!\nPWHOLDMAX(:) = ZHOLDMAXR(:)*PSNOWDZ(:)*ZSNOWRHO(:)/XRHOLW\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LHOLD_1D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LHOLD_1D\n!####################################################################\n      FUNCTION SNOW3LHOLD_0D(PSNOWRHO,PSNOWDZ) RESULT(PWHOLDMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_CSTS,     ONLY : XRHOLW\nUSE MODD_SNOW_PAR, ONLY : XRHOSMAX_ES, XSNOWRHOHOLD,     &\n                          XWSNOWHOLDMAX2, XWSNOWHOLDMAX1\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)        :: PSNOWDZ, PSNOWRHO\n!\nREAL                    :: PWHOLDMAX\n!\n!*      0.2    declarations of local variables\n!\nREAL                    :: ZHOLDMAXR, ZSNOWRHO\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n! Evaluate capacity using upper density limit:\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LHOLD_0D',0,ZHOOK_HANDLE)\nZSNOWRHO = MIN(XRHOSMAX_ES, PSNOWRHO)\n!\n! Maximum ratio of liquid to SWE:\n!\nZHOLDMAXR = XWSNOWHOLDMAX1 + (XWSNOWHOLDMAX2-XWSNOWHOLDMAX1) *     &\n                             MAX(0.,XSNOWRHOHOLD-ZSNOWRHO)/XSNOWRHOHOLD\n!\n! Maximum liquid water holding capacity of the snow (m):\n!\nPWHOLDMAX = ZHOLDMAXR*PSNOWDZ*ZSNOWRHO/XRHOLW\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LHOLD_0D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LHOLD_0D\n!####################################################################\n      FUNCTION SNOWCROHOLD_3D(PSNOWRHO,PSNOWLIQ,PSNOWDZ) RESULT(PWHOLDMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_CSTS,     ONLY : XRHOLW,XRHOLI\nUSE MODD_SNOW_PAR, ONLY : XPERCENTAGEPORE\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:,:), INTENT(IN)                 :: PSNOWDZ, PSNOWLIQ, PSNOWRHO\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2),SIZE(PSNOWRHO,3)) :: PWHOLDMAX\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n! computation of water holding capacity based on Crocus,\n!taking into account the conversion between wet and dry density -\n!S. Morin/V. Vionnet 2010 12 09\n\n! PWHOLDMAX is expressed in m water for each layer\n! In short, PWHOLDMAX = XPERCENTAGEPORE * porosity * PSNOWDZ .\n! The porosity is computed as (rho_ice - (rho_snow - lwc))/(rho_ice)\n! where everything has to be in kg m-3 units. In practice, since\n! PSNOWLIQ is expressed in m water, expressing the lwc in kg m-3\n! is achieved as PSNOWLIQ*XRHOLW/PSNOWDZ. After some rearranging one\n! obtains the equation given above.\n! Note that equation (19) in Vionnet et al., GMD 2012, is wrong,\n! because it does not take into account the fact that liquid water\n! content has to be substracted from total density to compute the\n! porosity.\n\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOWCROHOLD_3D',0,ZHOOK_HANDLE)\nPWHOLDMAX(:,:,:) = XPERCENTAGEPORE/XRHOLI * (PSNOWDZ * (XRHOLI-PSNOWRHO) + PSNOWLIQ*XRHOLW)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOWCROHOLD_3D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOWCROHOLD_3D\n!####################################################################\n      FUNCTION SNOWCROHOLD_2D(PSNOWRHO,PSNOWLIQ,PSNOWDZ) RESULT(PWHOLDMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_CSTS,     ONLY : XRHOLW,XRHOLI\nUSE MODD_SNOW_PAR, ONLY : XPERCENTAGEPORE\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(IN)                   :: PSNOWDZ, PSNOWRHO, PSNOWLIQ\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: PWHOLDMAX\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n! computation of water holding capacity based on Crocus,\n!taking into account the conversion between wet and dry density -\n!S. Morin/V. Vionnet 2010 12 09\n\n! PWHOLDMAX is expressed in m water for each layer\n! In short, PWHOLDMAX = XPERCENTAGEPORE * porosity * PSNOWDZ .\n! The porosity is computed as (rho_ice - (rho_snow - lwc))/(rho_ice)\n! where everything has to be in kg m-3 units. In practice, since\n! PSNOWLIQ is expressed in m water, expressing the lwc in kg m-3\n! is achieved as PSNOWLIQ*XRHOLW/PSNOWDZ. After some rearranging one\n! obtains the equation given above.\n! Note that equation (19) in Vionnet et al., GMD 2012, is wrong,\n! because it does not take into account the fact that liquid water\n! content has to be substracted from total density to compute the\n! porosity.\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOWCROHOLD_2D',0,ZHOOK_HANDLE)\nPWHOLDMAX(:,:) = XPERCENTAGEPORE/XRHOLI * (PSNOWDZ * (XRHOLI-PSNOWRHO) + PSNOWLIQ*XRHOLW)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOWCROHOLD_2D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOWCROHOLD_2D\n!####################################################################\n!####################################################################\n!####################################################################\n      FUNCTION SNOWCROHOLD_1D(PSNOWRHO,PSNOWLIQ,PSNOWDZ) RESULT(PWHOLDMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_CSTS,     ONLY : XRHOLW,XRHOLI\nUSE MODD_SNOW_PAR, ONLY : XPERCENTAGEPORE\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)                     :: PSNOWDZ, PSNOWRHO, PSNOWLIQ\n!\nREAL, DIMENSION(SIZE(PSNOWRHO))                    :: PWHOLDMAX\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n! computation of water holding capacity based on Crocus,\n!taking into account the conversion between wet and dry density -\n!S. Morin/V. Vionnet 2010 12 09\n\n! PWHOLDMAX is expressed in m water for each layer\n! In short, PWHOLDMAX = XPERCENTAGEPORE * porosity * PSNOWDZ .\n! The porosity is computed as (rho_ice - (rho_snow - lwc))/(rho_ice)\n! where everything has to be in kg m-3 units. In practice, since\n! PSNOWLIQ is expressed in m water, expressing the lwc in kg m-3\n! is achieved as PSNOWLIQ*XRHOLW/PSNOWDZ. After some rearranging one\n! obtains the equation given above.\n! Note that equation (19) in Vionnet et al., GMD 2012, is wrong,\n! because it does not take into account the fact that liquid water\n! content has to be substracted from total density to compute the\n! porosity.\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOWCROHOLD_1D',0,ZHOOK_HANDLE)\nPWHOLDMAX(:) = XPERCENTAGEPORE/XRHOLI * (PSNOWDZ * (XRHOLI-PSNOWRHO) + PSNOWLIQ*XRHOLW)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOWCROHOLD_1D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOWCROHOLD_1D\n!####################################################################\n      FUNCTION SNOWCROHOLD_0D(PSNOWRHO,PSNOWLIQ,PSNOWDZ) RESULT(PWHOLDMAX)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the maximum liquid water holding capacity of\n!     snow layer(s).\n!\nUSE MODD_CSTS,     ONLY : XRHOLW,XRHOLI\nUSE MODD_SNOW_PAR, ONLY : XPERCENTAGEPORE\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)        :: PSNOWDZ, PSNOWRHO, PSNOWLIQ\n!\nREAL                    :: PWHOLDMAX\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n! computation of water holding capacity based on Crocus,\n!taking into account the conversion between wet and dry density -\n!S. Morin/V. Vionnet 2010 12 09\n\n! PWHOLDMAX is expressed in m water for each layer\n! In short, PWHOLDMAX = XPERCENTAGEPORE * porosity * PSNOWDZ .\n! The porosity is computed as (rho_ice - (rho_snow - lwc))/(rho_ice)\n! where everything has to be in kg m-3 units. In practice, since\n! PSNOWLIQ is expressed in m water, expressing the lwc in kg m-3\n! is achieved as PSNOWLIQ*XRHOLW/PSNOWDZ. After some rearranging one\n! obtains the equation given above.\n! Note that equation (19) in Vionnet et al., GMD 2012, is wrong,\n! because it does not take into account the fact that liquid water\n! content has to be substracted from total density to compute the\n! porosity.\n\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOWCROHOLD_0D',0,ZHOOK_HANDLE)\nPWHOLDMAX = XPERCENTAGEPORE/XRHOLI * (PSNOWDZ * (XRHOLI-PSNOWRHO) + PSNOWLIQ*XRHOLW)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOWCROHOLD_0D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOWCROHOLD_0D\n!####################################################################\n!####################################################################\n!####################################################################\n      FUNCTION SNOW3LSCAP_3D(PSNOWRHO) RESULT(PSCAP)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the heat capacity of a snow layer.\n!\nUSE MODD_CSTS,ONLY : XCI\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:,:), INTENT(IN)                                  :: PSNOWRHO\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2),SIZE(PSNOWRHO,3)) :: PSCAP\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!     The method of Verseghy (1991), Int. J. Climat., 11, 111-133.\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LSCAP_3D',0,ZHOOK_HANDLE)\nPSCAP(:,:,:) = PSNOWRHO(:,:,:)*XCI      ! (J K-1 m-3)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LSCAP_3D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LSCAP_3D\n!####################################################################\n      FUNCTION SNOW3LSCAP_2D(PSNOWRHO) RESULT(PSCAP)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the heat capacity of a snow layer.\n!\nUSE MODD_CSTS,ONLY : XCI\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(IN)                   :: PSNOWRHO\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: PSCAP\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!     The method of Verseghy (1991), Int. J. Climat., 11, 111-133.\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LSCAP_2D',0,ZHOOK_HANDLE)\nPSCAP(:,:) = PSNOWRHO(:,:)*XCI      ! (J K-1 m-3)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LSCAP_2D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LSCAP_2D\n!####################################################################\n      FUNCTION SNOW3LSCAP_1D(PSNOWRHO) RESULT(PSCAP)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the heat capacity of a snow layer.\n!\nUSE MODD_CSTS,ONLY : XCI\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)                   :: PSNOWRHO\n!\nREAL, DIMENSION(SIZE(PSNOWRHO))                  :: PSCAP\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!     The method of Verseghy (1991), Int. J. Climat., 11, 111-133.\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LSCAP_1D',0,ZHOOK_HANDLE)\nPSCAP(:) = PSNOWRHO(:)*XCI      ! (J K-1 m-3)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LSCAP_1D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LSCAP_1D\n!####################################################################\n      FUNCTION SNOW3LSCAP_0D(PSNOWRHO) RESULT(PSCAP)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the heat capacity of a snow layer.\n!\nUSE MODD_CSTS,ONLY : XCI\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)       :: PSNOWRHO\n!\nREAL                   :: PSCAP\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!     The method of Verseghy (1991), Int. J. Climat., 11, 111-133.\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LSCAP_0D',0,ZHOOK_HANDLE)\nPSCAP = PSNOWRHO*XCI      ! (J K-1 m-3)\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LSCAP_0D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LSCAP_0D\n!\n!####################################################################\n!####################################################################\n!####################################################################\n      FUNCTION SNOW3L_MARBOUTY(PSNOWRHO,PSNOWTEMP,PGRADT) RESULT(PDANGL) \n!**** *ZDANGL* - CROISSANCE DES GRAINS NON DENDRITIQUES ET ANGULEUX .\n!              - GROWTH RATES FOR NON DENDRITIC GRAINS WITH SPHERICITY=0 \n\n\n!     OBJET.\n!     ------\n\n!**   INTERFACE.\n!     ----------\n\n!     *ZDANGL*(PST,PSRO,PGRADT)*\n\n!        *PST*     -  TEMPERATURE DE LA STRATE DE NEIGE.\n!        *PSRO*    -  MASSE VOLUMIQUE DE LA STRATE DE NEIGE.\n!        *PGRADT*  -  GRADIENT DE TEMPERATURE AFFECTANT LA STRATE DE NEIGE.\n\n!     METHODE.\n!     --------\n!     THE FUNCTION RETURN A VALUE BETWEEN 0 AND 1 WHICH IS USED IN THE DETERMINATION OF THE \n!     GROWTH RATE FOR THE CONSIDERED LAYER.\n!     THIS VALUE (WITHOUT UNIT) IS THE PRODUCT OF 3 FUNCTIONS (WHICH HAVE THEIR SOLUTIONS BETWEEN 0 AND 1) :\n!     F(TEMPERATURE) * H(DENSITY) * G(TEMPERATURE GRADIENT)\n\n!     EXTERNES.\n!     ---------\n\n!     REFERENCES.\n!     -----------\n!        MARBOUTY D (1980) AN EXPERIMENTAL STUDY OF TEMPERATURE GRADIENT \n!                          METAMORPHISM J GLACIOLOGY\n\n!     AUTEURS.\n!     --------\n!        DOMINIQUE MARBOUTY (FMARBO/GMARBO/HMARBO).\n\n!     MODIFICATIONS.\n!     --------------\n!        08/95: YANNICK DANIELOU - CODAGE A LA NORME DOCTOR.\n!        03/06: JM WILLEMET      - F90 AND SI UNITS\n!        01/08: JM WILLEMET      - ERROR ON THE FORMULATION OF G FUNCTION (WITH GRADIENT) IS CORRECTED \n\nUSE MODD_CSTS, ONLY : XTT\nUSE MODD_SNOW_METAMO\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!     DECLARATIONS.\n!     -------------\n!\nREAL ,INTENT(IN) :: PSNOWTEMP, PSNOWRHO, PGRADT\n!\nREAL             :: PDANGL\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3L_MARBOUTY',0,ZHOOK_HANDLE)\n!\nPDANGL = 0.0\n!\n! INFLUENCE DE LA TEMPERATURE /TEMPERATURE INFLUENCE.\nIF( PSNOWTEMP>=XTT-XVTANG1 ) THEN\n  !\n  IF ( PSNOWTEMP>=XTT-XVTANG2 ) THEN\n    PDANGL = XVTANG4 + XVTANG5 * (XTT-PSNOWTEMP) / XVTANG6\n  ELSEIF( PSNOWTEMP>=XTT-XVTANG3 ) THEN\n    PDANGL = XVTANG7 - XVTANG8 * (XTT-XVTANG2-PSNOWTEMP) / XVTANG9\n  ELSE\n    PDANGL = XVTANGA - XVTANGB * (XTT-XVTANG3-PSNOWTEMP) / XVTANGC\n  ENDIF\n  !\n  ! INFLUENCE DE LA MASSE VOLUMIQUE / DENSITY INFLUENCE.\n  IF ( PSNOWRHO<=XVRANG1 ) THEN\n    !\n    IF ( PSNOWRHO>XVRANG2 ) THEN\n      PDANGL = PDANGL * ( 1. - (PSNOWRHO-XVRANG2)/(XVRANG1-XVRANG2) )\n    ENDIF\n    !\n    ! INFLUENCE DU GRADIENT DE TEMPERATURE / TEMPERATURE GRADIENT INFLUENCE.\n    IF ( PGRADT<=XVGANG1 ) THEN\n      !\n      IF ( PGRADT<=XVGANG2 ) THEN\n        PDANGL = PDANGL * XVGANG5 * (PGRADT-XVGANG6)/(XVGANG2-XVGANG6)\n      ELSEIF( PGRADT<=XVGANG3 ) THEN\n        PDANGL = PDANGL * ( XVGANG7 + XVGANG8 * (PGRADT-XVGANG2)/(XVGANG3-XVGANG2) )\n      ELSEIF( PGRADT<=XVGANG4 )THEN\n        PDANGL = PDANGL * ( XVGANG9 + XVGANGA * (PGRADT-XVGANG3)/(XVGANG4-XVGANG3) )\n      ELSE\n        PDANGL = PDANGL * ( XVGANGB + XVGANGC * (PGRADT-XVGANG4)/(XVGANG1-XVGANG4) )\n      ENDIF\n      !\n    ENDIF\n    !\n  ELSE\n    !\n    PDANGL = 0.\n    !\n  ENDIF\n  !\nELSE\n  !\n  PDANGL = 0.\n  !\nENDIF\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3L_MARBOUTY',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3L_MARBOUTY\n!\n!####################################################################\n!####################################################################\n!####################################################################\n!\n      SUBROUTINE SNOW3LGRID_2D(PSNOWDZ,PSNOW,PSNOWDZ_OLD)\n!\n!!    PURPOSE\n!!    -------\n!     Once during each time step, update grid to maintain\n!     grid proportions. Similar to approach of Lynch-Steiglitz,\n!     1994, J. Clim., 7, 1842-1855. Corresponding mass and\n!     heat adjustments made directly after the call to this\n!     routine. 3 grid configurations:\n!     1) for very thin snow, constant grid spacing\n!     2) for intermediate thicknesses, highest resolution at soil/snow\n!        interface and at the snow/atmosphere interface\n!     3) for deep snow, vertical resoution finest at snow/atmosphere\n!        interface (set to a constant value) and increases with snow depth.\n!        Second layer can't be more than an order of magnitude thicker\n!        than surface layer.\n!\n!\n!USE MODD_SURF_PAR,   ONLY : XUNDEF\nUSE MODD_SNOW_PAR,   ONLY : XSNOWCRITD, XUNDEF\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:  ), INTENT(IN )           :: PSNOW\nREAL, DIMENSION(:,:), INTENT(OUT)           :: PSNOWDZ\nREAL, DIMENSION(:,:), INTENT(IN ), OPTIONAL :: PSNOWDZ_OLD\n!\n!*      0.1    declarations of local variables\n!\nINTEGER                           :: JJ, JI\n!\nINTEGER                           :: INLVLS, INI\n!\nREAL,     DIMENSION(SIZE(PSNOW))  :: ZWORK\n!\nLOGICAL , DIMENSION(SIZE(PSNOW))  :: GREGRID\n\n! ISBA-ES snow grid parameters\n!\nREAL, PARAMETER, DIMENSION(3)     :: ZSGCOEF1  = (/0.25, 0.50, 0.25/)\nREAL, PARAMETER, DIMENSION(2)     :: ZSGCOEF2  = (/0.05, 0.34/)\n!\nREAL, PARAMETER, DIMENSION(3)     :: ZSGCOEF   = (/0.3, 0.4, 0.3/)\n!\n! Minimum total snow depth at which surface layer thickness is constant:\n!\nREAL, PARAMETER                   :: ZSNOWTRANS = 0.20                ! (m)\n!\n! Minimum snow depth by layer for 6-L or 12-L configuration :\n!\nREAL, PARAMETER                   ::  ZDZ1=0.01\nREAL, PARAMETER                   ::  ZDZ2=0.05\nREAL, PARAMETER                   ::  ZDZ3=0.15\nREAL, PARAMETER                   ::  ZDZ4=0.50\nREAL, PARAMETER                   ::  ZDZ5=1.00\nREAL, PARAMETER                   ::  ZDZN0=0.02\nREAL, PARAMETER                   ::  ZDZN1=0.1\nREAL, PARAMETER                   ::  ZDZN2=0.5\nREAL, PARAMETER                   ::  ZDZN3=1.0\n!\nREAL, PARAMETER                   ::  ZCOEF1 = 0.5\nREAL, PARAMETER                   ::  ZCOEF2 = 1.5\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!-------------------------------------------------------------------------------\n!\n! 0. Initialization:\n! ------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LGRID_2D',0,ZHOOK_HANDLE)\n!\nINLVLS = SIZE(PSNOWDZ(:,:),2)\nINI    = SIZE(PSNOWDZ(:,:),1)\n!\nZWORK  (:) = 0.0\nGREGRID(:) = .TRUE.\n!\n! 1. Calculate current grid for 3-layer (default) configuration):\n! ---------------------------------------------------------------\n! Based on formulation of Lynch-Stieglitz (1994)\n! except for 3 modifications:\n! i) smooth transition here at ZSNOWTRANS\n! ii) constant ratio for very thin snow:\n! iii) ratio of layer 2 to surface layer <= 10\n!\nIF(INLVLS == 1)THEN\n!\n  DO JI=1,INI\n     PSNOWDZ(JI,1)  = PSNOW(JI)\n  ENDDO\n!\nELSEIF(INLVLS == 3)THEN\n!\n   WHERE(PSNOW <= XSNOWCRITD+0.01)\n      PSNOWDZ(:,1) = MIN(0.01, PSNOW(:)/INLVLS)\n      PSNOWDZ(:,3) = MIN(0.01, PSNOW(:)/INLVLS)\n      PSNOWDZ(:,2) = PSNOW(:) - PSNOWDZ(:,1) - PSNOWDZ(:,3)\n   END WHERE\n!\n   WHERE(PSNOW <= ZSNOWTRANS .AND. PSNOW > XSNOWCRITD+0.01)\n      PSNOWDZ(:,1) = PSNOW(:)*ZSGCOEF1(1)\n      PSNOWDZ(:,2) = PSNOW(:)*ZSGCOEF1(2)\n      PSNOWDZ(:,3) = PSNOW(:)*ZSGCOEF1(3)\n   END WHERE\n!\n   WHERE(PSNOW > ZSNOWTRANS)\n      PSNOWDZ(:,1) = ZSGCOEF2(1)\n      PSNOWDZ(:,2) = (PSNOW(:)-ZSGCOEF2(1))*ZSGCOEF2(2) + ZSGCOEF2(1)\n!\n! When using simple finite differences, limit the thickness\n! factor between the top and 2nd layers to at most 10\n!\n      PSNOWDZ(:,2) = MIN(10*ZSGCOEF2(1),  PSNOWDZ(:,2))\n      PSNOWDZ(:,3) = PSNOW(:) - PSNOWDZ(:,2) - PSNOWDZ(:,1)\n   END WHERE\n!\n!\n! 2. Calculate current grid for 6-layer :\n! ---------------------------------------------------------------\n!\nELSEIF(INLVLS == 6)THEN\n!\n! critere a satisfaire pour remaillage\n!\n  IF(PRESENT(PSNOWDZ_OLD))THEN\n    GREGRID(:) = PSNOWDZ_OLD(:,1) < ZCOEF1 * MIN(ZDZ1 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,1) > ZCOEF2 * MIN(ZDZ1 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,2) < ZCOEF1 * MIN(ZDZ2 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,2) > ZCOEF2 * MIN(ZDZ2 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,6) < ZCOEF1 * MIN(ZDZN1,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,6) > ZCOEF2 * MIN(ZDZN1,PSNOW(:)/INLVLS)\n  ENDIF\n!\n  WHERE(GREGRID(:))\n!      top layers\n       PSNOWDZ(:,1) = MIN(ZDZ1,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,2) = MIN(ZDZ2,PSNOW(:)/INLVLS)\n!      last layers\n       PSNOWDZ(:,6) = MIN(ZDZN1,PSNOW(:)/INLVLS)\n!      remaining snow for remaining layers\n       ZWORK(:)     = PSNOW(:) - PSNOWDZ(:,1) - PSNOWDZ(:,2) - PSNOWDZ(:,6)\n       PSNOWDZ(:,3) = ZWORK(:)*ZSGCOEF(1)\n       PSNOWDZ(:,4) = ZWORK(:)*ZSGCOEF(2)\n       PSNOWDZ(:,5) = ZWORK(:)*ZSGCOEF(3)\n!      layer 3 tickness >= layer 2 tickness\n       ZWORK(:)=MIN(0.0,PSNOWDZ(:,3)-PSNOWDZ(:,2))\n       PSNOWDZ(:,3)=PSNOWDZ(:,3)-ZWORK(:)\n       PSNOWDZ(:,4)=PSNOWDZ(:,4)+ZWORK(:)\n!      layer 5 tickness >= layer 6 tickness\n       ZWORK(:)=MIN(0.0,PSNOWDZ(:,5)-PSNOWDZ(:,6))\n       PSNOWDZ(:,5)=PSNOWDZ(:,5)-ZWORK(:)\n       PSNOWDZ(:,4)=PSNOWDZ(:,4)+ZWORK(:)\n  ENDWHERE\n!\n! 3. Calculate current grid for 9-layer :\n! ---------------------------------------------------------------\n!\nELSEIF(INLVLS == 9)THEN\n!\n! critere a satisfaire pour remaillage\n!\n  IF(PRESENT(PSNOWDZ_OLD))THEN\n    GREGRID(:) = PSNOWDZ_OLD(:,1) < ZCOEF1 * MIN(ZDZ1 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,1) > ZCOEF2 * MIN(ZDZ1 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,2) < ZCOEF1 * MIN(ZDZ2 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,2) > ZCOEF2 * MIN(ZDZ2 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,9) < ZCOEF1 * MIN(ZDZN0,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,9) > ZCOEF2 * MIN(ZDZN0,PSNOW(:)/INLVLS)\n  ENDIF\n!\n  WHERE(GREGRID(:))\n!      top layers\n       PSNOWDZ(:,1) = MIN(ZDZ1,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,2) = MIN(ZDZ2,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,3) = MIN(ZDZ3,PSNOW(:)/INLVLS)\n!      last layers\n       PSNOWDZ(:,9)= MIN(ZDZN0,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,8)= MIN(ZDZN1,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,7)= MIN(ZDZN2,PSNOW(:)/INLVLS)\n!      remaining snow for remaining layers\n       ZWORK(:) = PSNOW(:) - PSNOWDZ(:, 1) - PSNOWDZ(:, 2) - PSNOWDZ(:, 3) &\n                           - PSNOWDZ(:, 7) - PSNOWDZ(:, 8) - PSNOWDZ(:, 9)\n       PSNOWDZ(:,4) = ZWORK(:)*ZSGCOEF(1)\n       PSNOWDZ(:,5) = ZWORK(:)*ZSGCOEF(2)\n       PSNOWDZ(:,6) = ZWORK(:)*ZSGCOEF(3)\n!      layer 4 tickness >= layer 3 tickness\n       ZWORK(:)=MIN(0.0,PSNOWDZ(:,4)-PSNOWDZ(:,3))\n       PSNOWDZ(:,4)=PSNOWDZ(:,4)-ZWORK(:)\n       PSNOWDZ(:,5)=PSNOWDZ(:,5)+ZWORK(:)\n!      layer 6 tickness >= layer 7 tickness\n       ZWORK(:)=MIN(0.0,PSNOWDZ(:,6)-PSNOWDZ(:,7))\n       PSNOWDZ(:,6)=PSNOWDZ(:,6)-ZWORK(:)\n       PSNOWDZ(:,5)=PSNOWDZ(:,5)+ZWORK(:)\n  ENDWHERE\n!\n! 4. Calculate current grid for 12-layer :\n! ---------------------------------------------------------------\n!\nELSEIF(INLVLS == 12)THEN\n!\n! critere a satisfaire pour remaillage\n!\n  IF(PRESENT(PSNOWDZ_OLD))THEN\n    GREGRID(:) = PSNOWDZ_OLD(:, 1) < ZCOEF1 * MIN(ZDZ1 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:, 1) > ZCOEF2 * MIN(ZDZ1 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:, 2) < ZCOEF1 * MIN(ZDZ2 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:, 2) > ZCOEF2 * MIN(ZDZ2 ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,12) < ZCOEF1 * MIN(ZDZN0,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,12) > ZCOEF2 * MIN(ZDZN0,PSNOW(:)/INLVLS) \n  ENDIF\n!\n  WHERE(GREGRID(:))\n!      top layers\n       PSNOWDZ(:,1) = MIN(ZDZ1,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,2) = MIN(ZDZ2,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,3) = MIN(ZDZ3,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,4) = MIN(ZDZ4,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,5) = MIN(ZDZ5,PSNOW(:)/INLVLS)\n!      last layers\n       PSNOWDZ(:,12)= MIN(ZDZN0,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,11)= MIN(ZDZN1,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,10)= MIN(ZDZN2,PSNOW(:)/INLVLS)\n       PSNOWDZ(:, 9)= MIN(ZDZN3,PSNOW(:)/INLVLS)\n!      remaining snow for remaining layers\n       ZWORK(:) = PSNOW(:) - PSNOWDZ(:, 1) - PSNOWDZ(:, 2) - PSNOWDZ(:, 3) &\n                           - PSNOWDZ(:, 4) - PSNOWDZ(:, 5) - PSNOWDZ(:, 9) &\n                           - PSNOWDZ(:,10) - PSNOWDZ(:,11) - PSNOWDZ(:,12)\n       PSNOWDZ(:,6) = ZWORK(:)*ZSGCOEF(1)\n       PSNOWDZ(:,7) = ZWORK(:)*ZSGCOEF(2)\n       PSNOWDZ(:,8) = ZWORK(:)*ZSGCOEF(3)\n!      layer 6 tickness >= layer 5 tickness\n       ZWORK(:)=MIN(0.0,PSNOWDZ(:,6)-PSNOWDZ(:,5))\n       PSNOWDZ(:,6)=PSNOWDZ(:,6)-ZWORK(:)\n       PSNOWDZ(:,7)=PSNOWDZ(:,7)+ZWORK(:)\n!      layer 8 tickness >= layer 9 tickness\n       ZWORK(:)=MIN(0.0,PSNOWDZ(:,8)-PSNOWDZ(:,9))\n       PSNOWDZ(:,8)=PSNOWDZ(:,8)-ZWORK(:)\n       PSNOWDZ(:,7)=PSNOWDZ(:,7)+ZWORK(:)\n  ENDWHERE\n!\n! 4. Calculate other non-optimized grid :\n! ---------------------------------------\n!\nELSEIF(INLVLS<10.AND.INLVLS/=3.AND.INLVLS/=6.AND.INLVLS/=9) THEN\n!\n  DO JJ=1,INLVLS\n     DO JI=1,INI\n        PSNOWDZ(JI,JJ)  = PSNOW(JI)/INLVLS\n     ENDDO\n  ENDDO\n!\n  PSNOWDZ(:,INLVLS) = PSNOWDZ(:,INLVLS) + (PSNOWDZ(:,1) - MIN(0.05, PSNOWDZ(:,1)))\n  PSNOWDZ(:,1)      = MIN(0.05, PSNOWDZ(:,1))\n!\nELSE !(INLVLS>=10 and /=12)\n!\n! critere a satisfaire pour remaillage\n!\n  IF(PRESENT(PSNOWDZ_OLD))THEN\n    GREGRID(:) = PSNOWDZ_OLD(:,     1) < ZCOEF1 * MIN(ZDZ1         ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,     1) > ZCOEF2 * MIN(ZDZ1         ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,     2) < ZCOEF1 * MIN(ZDZ2         ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,     2) > ZCOEF2 * MIN(ZDZ2         ,PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,INLVLS) < ZCOEF1 * MIN(0.05*PSNOW(:),PSNOW(:)/INLVLS) .OR. &\n               & PSNOWDZ_OLD(:,INLVLS) > ZCOEF2 * MIN(0.05*PSNOW(:),PSNOW(:)/INLVLS) \n  ENDIF\n!\n  WHERE(GREGRID(:))\n       PSNOWDZ(:,1     ) = MIN(ZDZ1         ,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,2     ) = MIN(ZDZ2         ,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,3     ) = MIN(ZDZ3         ,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,4     ) = MIN(ZDZ4         ,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,5     ) = MIN(ZDZ5         ,PSNOW(:)/INLVLS)\n       PSNOWDZ(:,INLVLS) = MIN(0.05*PSNOW(:),PSNOW(:)/INLVLS)\n  ENDWHERE\n!\n  DO JJ=6,INLVLS-1,1\n     DO JI=1,INI\n        IF(GREGRID(JI))THEN\n          ZWORK(JI) = PSNOWDZ(JI,1)+PSNOWDZ(JI,2)+PSNOWDZ(JI,3)+PSNOWDZ(JI,4)+PSNOWDZ(JI,5)\n          PSNOWDZ(JI,JJ) = (PSNOW(JI)-ZWORK(JI)-PSNOWDZ(JI,INLVLS))/(INLVLS-6) \n        ENDIF\n     ENDDO\n  ENDDO\n!\nENDIF\n!\nDO JJ=1,INLVLS\n   DO JI=1,INI\n      IF(PSNOW(JI)==XUNDEF)THEN\n         PSNOWDZ(JI,JJ) = XUNDEF\n      ELSEIF(.NOT.GREGRID(JI))THEN\n         PSNOWDZ(JI,JJ)=PSNOWDZ_OLD(JI,JJ)\n      ENDIF\n   ENDDO\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LGRID_2D',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOW3LGRID_2D\n!####################################################################\n!####################################################################\n!####################################################################\n!\n      SUBROUTINE SNOW3LGRID_1D(PSNOWDZ,PSNOW,PSNOWDZ_OLD)\n!\n!!    PURPOSE\n!!    -------\n!     Once during each time step, update grid to maintain\n!     grid proportions. Similar to approach of Lynch-Steiglitz,\n!     1994, J. Clim., 7, 1842-1855. Corresponding mass and\n!     heat adjustments made directly after the call to this\n!     routine. 3 grid configurations:\n!     1) for very thin snow, constant grid spacing\n!     2) for intermediate thicknesses, highest resolution at soil/snow\n!        interface and at the snow/atmosphere interface\n!     3) for deep snow, vertical resoution finest at snow/atmosphere\n!        interface (set to a constant value) and increases with snow depth.\n!        Second layer can't be more than an order of magnitude thicker\n!        than surface layer.\n!\n!\n!USE MODD_SURF_PAR,   ONLY : XUNDEF\nUSE MODD_SNOW_PAR,   ONLY : XSNOWCRITD, XUNDEF\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL,               INTENT(IN )           :: PSNOW\nREAL, DIMENSION(:), INTENT(OUT)           :: PSNOWDZ\nREAL, DIMENSION(:), INTENT(IN ), OPTIONAL :: PSNOWDZ_OLD\n!\n!*      0.1    declarations of local variables\n!\nINTEGER JJ\n!\nINTEGER                           :: INLVLS\n!\nREAL                              :: ZWORK\n!\n! modif_EB pour maillage\nLOGICAL                           :: GREGRID\n\n! ISBA-ES snow grid parameters\n!\nREAL, PARAMETER, DIMENSION(3)     :: ZSGCOEF1  = (/0.25, 0.50, 0.25/)\nREAL, PARAMETER, DIMENSION(2)     :: ZSGCOEF2  = (/0.05, 0.34/)\n!\nREAL, PARAMETER, DIMENSION(3)     :: ZSGCOEF   = (/0.3, 0.4, 0.3/)\n!\n! Minimum total snow depth at which surface layer thickness is constant:\n!\nREAL, PARAMETER                   :: ZSNOWTRANS  = 0.20                ! (m)\n!\n! Minimum snow depth by layer for 6-L or 12-L configuration :\n!\nREAL, PARAMETER                   ::  ZDZ1=0.01\nREAL, PARAMETER                   ::  ZDZ2=0.05\nREAL, PARAMETER                   ::  ZDZ3=0.15\nREAL, PARAMETER                   ::  ZDZ4=0.50\nREAL, PARAMETER                   ::  ZDZ5=1.00\nREAL, PARAMETER                   ::  ZDZN0=0.02\nREAL, PARAMETER                   ::  ZDZN1=0.1\nREAL, PARAMETER                   ::  ZDZN2=0.5\nREAL, PARAMETER                   ::  ZDZN3=1.0\n!\nREAL, PARAMETER                   ::  ZCOEF1 = 0.5\nREAL, PARAMETER                   ::  ZCOEF2 = 1.5\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!-------------------------------------------------------------------------------\n!\n! 0. Initialization:\n! ------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LGRID_1D',0,ZHOOK_HANDLE)\n!\nINLVLS = SIZE(PSNOWDZ(:),1)\n!\nGREGRID = .TRUE.\n!\n! 1. Calculate current grid for 3-layer (default) configuration):\n! ---------------------------------------------------------------\n! Based on formulation of Lynch-Stieglitz (1994)\n! except for 3 modifications:\n! i) smooth transition here at ZSNOWTRANS\n! ii) constant ratio for very thin snow:\n! iii) ratio of layer 2 to surface layer <= 10\n!\nIF(INLVLS == 1)THEN\n!\n  PSNOWDZ(1) = PSNOW\n!\nELSEIF(INLVLS == 3)THEN\n!\n   IF(PSNOW <= XSNOWCRITD+0.01)THEN\n      PSNOWDZ(1) = MIN(0.01, PSNOW/INLVLS)\n      PSNOWDZ(3) = MIN(0.01, PSNOW/INLVLS)\n      PSNOWDZ(2) = PSNOW - PSNOWDZ(1) - PSNOWDZ(3)\n   ENDIF\n!\n   IF(PSNOW <= ZSNOWTRANS .AND. PSNOW > XSNOWCRITD+0.01)THEN\n      PSNOWDZ(1) = PSNOW*ZSGCOEF1(1)\n      PSNOWDZ(2) = PSNOW*ZSGCOEF1(2)\n      PSNOWDZ(3) = PSNOW*ZSGCOEF1(3)\n   ENDIF\n!\n   IF(PSNOW > ZSNOWTRANS)THEN\n      PSNOWDZ(1) = ZSGCOEF2(1)\n      PSNOWDZ(2) = (PSNOW-ZSGCOEF2(1))*ZSGCOEF2(2) + ZSGCOEF2(1)\n!\n! When using simple finite differences, limit the thickness\n! factor between the top and 2nd layers to at most 10\n!\n      PSNOWDZ(2) = MIN(10*ZSGCOEF2(1),  PSNOWDZ(2))\n      PSNOWDZ(3) = PSNOW - PSNOWDZ(2) - PSNOWDZ(1)\n   END IF\n!\n!\n! 2. Calculate current grid for 6-layer :\n! ---------------------------------------------------------------\n!\nELSEIF(INLVLS == 6)THEN\n!\n! critere a satisfaire pour remaillage\n!\n  IF(PRESENT(PSNOWDZ_OLD))THEN\n    GREGRID    = PSNOWDZ_OLD(1) < ZCOEF1 * MIN(ZDZ1 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(1) > ZCOEF2 * MIN(ZDZ1 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(2) < ZCOEF1 * MIN(ZDZ2 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(2) > ZCOEF2 * MIN(ZDZ2 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(6) < ZCOEF1 * MIN(ZDZN1,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(6) > ZCOEF2 * MIN(ZDZN1,PSNOW/INLVLS)\n  ENDIF\n!\n  IF(GREGRID)THEN\n!      top layers\n       PSNOWDZ(1) = MIN(ZDZ1,PSNOW/INLVLS)\n       PSNOWDZ(2) = MIN(ZDZ2,PSNOW/INLVLS)\n!      last layers\n       PSNOWDZ(6) = MIN(ZDZN1,PSNOW/INLVLS)\n!      remaining snow for remaining layers\n       ZWORK      = PSNOW - PSNOWDZ(1) - PSNOWDZ(2) - PSNOWDZ(6)\n       PSNOWDZ(3) = ZWORK*ZSGCOEF(1)\n       PSNOWDZ(4) = ZWORK*ZSGCOEF(2)\n       PSNOWDZ(5) = ZWORK*ZSGCOEF(3)\n!      layer 3 tickness >= layer 2 tickness\n       ZWORK=MIN(0.0,PSNOWDZ(3)-PSNOWDZ(2))\n       PSNOWDZ(3)=PSNOWDZ(3)-ZWORK\n       PSNOWDZ(4)=PSNOWDZ(4)+ZWORK\n!      layer 5 tickness >= layer 6 tickness\n       ZWORK=MIN(0.0,PSNOWDZ(5)-PSNOWDZ(6))\n       PSNOWDZ(5)=PSNOWDZ(5)-ZWORK\n       PSNOWDZ(4)=PSNOWDZ(4)+ZWORK\n  ENDIF\n!\n! 3. Calculate current grid for 9-layer :\n! ---------------------------------------------------------------\n!\nELSEIF(INLVLS == 9)THEN\n!\n! critere a satisfaire pour remaillage\n!\n  IF(PRESENT(PSNOWDZ_OLD))THEN\n    GREGRID    = PSNOWDZ_OLD(1) < ZCOEF1 * MIN(ZDZ1 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(1) > ZCOEF2 * MIN(ZDZ1 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(2) < ZCOEF1 * MIN(ZDZ2 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(2) > ZCOEF2 * MIN(ZDZ2 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(9) < ZCOEF1 * MIN(ZDZN0,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(9) > ZCOEF2 * MIN(ZDZN0,PSNOW/INLVLS)\n  ENDIF\n!\n  IF(GREGRID)THEN\n!      top layers\n       PSNOWDZ(1) = MIN(ZDZ1,PSNOW/INLVLS)\n       PSNOWDZ(2) = MIN(ZDZ2,PSNOW/INLVLS)\n       PSNOWDZ(3) = MIN(ZDZ3,PSNOW/INLVLS)\n!      last layers\n       PSNOWDZ(9)= MIN(ZDZN0,PSNOW/INLVLS)\n       PSNOWDZ(8)= MIN(ZDZN1,PSNOW/INLVLS)\n       PSNOWDZ(7)= MIN(ZDZN2,PSNOW/INLVLS)\n!      remaining snow for remaining layers\n       ZWORK = PSNOW - PSNOWDZ( 1) - PSNOWDZ( 2) - PSNOWDZ( 3) &\n                     - PSNOWDZ( 7) - PSNOWDZ( 8) - PSNOWDZ( 9)\n       PSNOWDZ(4) = ZWORK*ZSGCOEF(1)\n       PSNOWDZ(5) = ZWORK*ZSGCOEF(2)\n       PSNOWDZ(6) = ZWORK*ZSGCOEF(3)\n!      layer 4 tickness >= layer 3 tickness\n       ZWORK=MIN(0.0,PSNOWDZ(4)-PSNOWDZ(3))\n       PSNOWDZ(4)=PSNOWDZ(4)-ZWORK\n       PSNOWDZ(5)=PSNOWDZ(5)+ZWORK\n!      layer 6 tickness >= layer 7 tickness\n       ZWORK=MIN(0.0,PSNOWDZ(6)-PSNOWDZ(7))\n       PSNOWDZ(6)=PSNOWDZ(6)-ZWORK\n       PSNOWDZ(5)=PSNOWDZ(5)+ZWORK\n  ENDIF\n!\n! 4. Calculate current grid for 12-layer :\n! ---------------------------------------------------------------\n!\nELSEIF(INLVLS == 12)THEN\n!\n! modif_EB pour maillage\n! critere a satisfaire pour remaillage\n  IF(PRESENT(PSNOWDZ_OLD))THEN\n    GREGRID    = PSNOWDZ_OLD(1)  < ZCOEF1 * MIN(ZDZ1 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(1)  > ZCOEF2 * MIN(ZDZ1 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(2)  < ZCOEF1 * MIN(ZDZ2 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(2)  > ZCOEF2 * MIN(ZDZ2 ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(12) < ZCOEF1 * MIN(ZDZN0,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(12) > ZCOEF2 * MIN(ZDZN0,PSNOW/INLVLS)\n  ENDIF\n!\n  IF (GREGRID)THEN\n!    top layers\n     PSNOWDZ(1) = MIN(ZDZ1,PSNOW/INLVLS)\n     PSNOWDZ(2) = MIN(ZDZ2,PSNOW/INLVLS)\n     PSNOWDZ(3) = MIN(ZDZ3,PSNOW/INLVLS)\n     PSNOWDZ(4) = MIN(ZDZ4,PSNOW/INLVLS)\n     PSNOWDZ(5) = MIN(ZDZ5,PSNOW/INLVLS)\n!    last layers\n     PSNOWDZ(12)= MIN(ZDZN0,PSNOW/INLVLS)\n     PSNOWDZ(11)= MIN(ZDZN1,PSNOW/INLVLS)\n     PSNOWDZ(10)= MIN(ZDZN2,PSNOW/INLVLS)\n     PSNOWDZ( 9)= MIN(ZDZN3,PSNOW/INLVLS)\n!    remaining snow for remaining layers\n     ZWORK = PSNOW - PSNOWDZ( 1) - PSNOWDZ( 2) - PSNOWDZ( 3) &\n                   - PSNOWDZ( 4) - PSNOWDZ( 5) - PSNOWDZ( 9) &\n                   - PSNOWDZ(10) - PSNOWDZ(11) - PSNOWDZ(12)\n     PSNOWDZ(6) = ZWORK*ZSGCOEF(1)\n     PSNOWDZ(7) = ZWORK*ZSGCOEF(2)\n     PSNOWDZ(8) = ZWORK*ZSGCOEF(3)\n!    layer 6 tickness >= layer 5 tickness\n     ZWORK=MIN(0.0,PSNOWDZ(6)-PSNOWDZ(5))\n     PSNOWDZ(6)=PSNOWDZ(6)-ZWORK\n     PSNOWDZ(7)=PSNOWDZ(7)+ZWORK\n!    layer 8 tickness >= layer 9 tickness\n     ZWORK=MIN(0.0,PSNOWDZ(8)-PSNOWDZ(9))\n     PSNOWDZ(8)=PSNOWDZ(8)-ZWORK\n     PSNOWDZ(7)=PSNOWDZ(7)+ZWORK\n  ENDIF\n!\n! 4. Calculate other non-optimized grid to allow CROCUS PREP :\n! ------------------------------------------------------------\n!\nELSE IF(INLVLS<10.AND.INLVLS/=3.AND.INLVLS/=6.AND.INLVLS/=9) THEN\n!\n  DO JJ=1,INLVLS\n     PSNOWDZ(JJ)  = PSNOW/INLVLS\n  ENDDO\n!\n  PSNOWDZ(INLVLS) = PSNOWDZ(INLVLS) + (PSNOWDZ(1) - MIN(0.05, PSNOWDZ(1)))\n  PSNOWDZ(1)      = MIN(0.05, PSNOWDZ(1))\n!\nELSE\n!\n  IF(PRESENT(PSNOWDZ_OLD))THEN\n    GREGRID    = PSNOWDZ_OLD(     1) < ZCOEF1 * MIN(ZDZ1      ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(     1) > ZCOEF2 * MIN(ZDZ1      ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(     2) < ZCOEF1 * MIN(ZDZ2      ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(     2) > ZCOEF2 * MIN(ZDZ2      ,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(INLVLS) < ZCOEF1 * MIN(0.05*PSNOW,PSNOW/INLVLS) .OR. &\n               & PSNOWDZ_OLD(INLVLS) > ZCOEF2 * MIN(0.05*PSNOW,PSNOW/INLVLS) \n  ENDIF\n!\n  IF (GREGRID)THEN\n     PSNOWDZ(     1) = MIN(ZDZ1      ,PSNOW/INLVLS)\n     PSNOWDZ(     2) = MIN(ZDZ2      ,PSNOW/INLVLS)\n     PSNOWDZ(     3) = MIN(ZDZ3      ,PSNOW/INLVLS)\n     PSNOWDZ(     4) = MIN(ZDZ4      ,PSNOW/INLVLS)\n     PSNOWDZ(     5) = MIN(ZDZ5      ,PSNOW/INLVLS)\n     PSNOWDZ(INLVLS) = MIN(0.05*PSNOW,PSNOW/INLVLS)\n     ZWORK = SUM(PSNOWDZ(1:5))\n     DO JJ=6,INLVLS-1,1\n        PSNOWDZ(JJ) = (PSNOW - ZWORK -PSNOWDZ(INLVLS))/(INLVLS-6)\n     END DO\n  ENDIF\n!\nENDIF\n!\nDO JJ=1,INLVLS\n  IF(PSNOW==XUNDEF)THEN\n    PSNOWDZ(JJ) = XUNDEF\n  ELSEIF(.NOT.GREGRID)THEN\n    PSNOWDZ(JJ) = PSNOWDZ_OLD(JJ)\n  ENDIF\nEND DO\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LGRID_1D',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOW3LGRID_1D\n!\n!###################################################################################\n!###################################################################################\nSUBROUTINE SNOW3LAGREG(PSNOWDZN,PSNOWDZ,PSNOWRHO,PSNOWGRAN1, PSNOWGRAN2, &\n                       PSNOWHIST,PSNOWGRAN1N,PSNOWGRAN2N,PSNOWHISTN,     &\n                       KL1,KL2,PSNOWDDZ                        )\n!\nUSE MODD_SNOW_METAMO\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!       0.1 declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)  :: PSNOWDZN,PSNOWDZ,PSNOWRHO,PSNOWDDZ\n!\nREAL, DIMENSION(:), INTENT(IN)  :: PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST\nREAL, DIMENSION(:), INTENT(OUT) :: PSNOWGRAN1N,PSNOWGRAN2N,PSNOWHISTN                                              \n!\nINTEGER, INTENT(IN) :: KL1  ! Indice couche de reference (i)\nINTEGER, INTENT(IN) :: KL2 ! Indice de la couche (i-1 ou i+1) dont une\n                                ! partie est aggregee à la couche (i)\n!\n!       0.2 declaration of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1)) :: ZSNOWRHO\nREAL, DIMENSION(SIZE(PSNOWRHO,1)) :: ZDIAMD,ZDIAMV,ZSPHERD,ZSPHERV,&\n                                     ZDIAMN,ZSPHERN,ZDENT\n!\nREAL :: ZDELTA, ZCOMP\n!\nINTEGER :: IDENT, IVIEU, IL\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LAGREG',0,ZHOOK_HANDLE)\n!\nIF( KL1<KL2 ) THEN\n  ZDELTA = 0.0\n  IL = KL1\nELSE\n  ZDELTA = 1.0\n  IL = KL2\nENDIF\n!\n! Mean Properties\n!\n!       1. History\n!\nIF ( PSNOWHIST(KL1)/=PSNOWHIST(KL2) ) THEN\n  PSNOWHISTN(KL1) = 0.0\nENDIF\n!\n!       2. New grain types\n!\n!       2.1 Same grain type\n!\nIF (  PSNOWGRAN1(KL1)*PSNOWGRAN1(KL2)>0.0 .OR. &\n    ( PSNOWGRAN1(KL1)==0.0 .AND. PSNOWGRAN1(KL2)>=0.0 ) .OR. &\n    ( PSNOWGRAN1(KL2)==0.0 .AND. PSNOWGRAN1(KL1)>=0.0 ) ) THEN\n  !\n  !code original vincent          PSNOWGRAN1N(KL1)=(PSNOWGRAN1(KL1)*PSNOWRHO(KL1)&\n  !code original vincent        *(PSNOWDZN(KL1)-(1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))-ZDELTA*&\n  !code original vincent        ABS(PSNOWDDZ(KL2)))+PSNOWGRAN1(KL2)*                   &\n  !code original vincent        PSNOWRHO(KL2)*((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+        &   \n  !code original vincent        ZDELTA*ABS(PSNOWDDZ(KL2))))/((PSNOWDZN(KL1)-(1.0-ZDELTA)&\n  !code original vincent        *ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2)))*        &\n  !code original vincent        PSNOWRHO(KL1)+((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+        &   \n  !code original vincent        ZDELTA*ABS(PSNOWDDZ(KL2)))*PSNOWRHO(KL2))\n  !code original vincent !\n  !code original vincent          PSNOWGRAN2N(KL1)=(PSNOWGRAN2(KL1)*PSNOWRHO(KL1) &\n  !code original vincent        *(PSNOWDZN(KL1)-(1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))-ZDELTA* &\n  !code original vincent        ABS(PSNOWDDZ(KL2)))+PSNOWGRAN2(KL2)*                   &\n  !code original vincent        PSNOWRHO(KL2)*((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))        &\n  !code original vincent        +ZDELTA*ABS(PSNOWDDZ(KL2))))/((PSNOWDZN(KL1)-(1.0-ZDELTA)&\n  !code original vincent        *ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2)))*        &\n  !code original vincent        PSNOWRHO(KL1)+((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+        &   \n  !code original vincent        ZDELTA*ABS(PSNOWDDZ(KL2)))*PSNOWRHO(KL2))\n  !\n  !plm\n  CALL GET_AGREG(KL1,KL2,PSNOWGRAN1(KL1),PSNOWGRAN1(KL2),PSNOWGRAN1N(KL1))\n  !\n  CALL GET_AGREG(KL1,KL2,PSNOWGRAN2(KL1),PSNOWGRAN2(KL2),PSNOWGRAN2N(KL1))\n  !\n  !plm\n  !\nELSE\n  !\n  !       2.2 Different types\n  !\n  IF ( PSNOWGRAN1(KL1)<0.0 ) THEN\n    IDENT = KL1\n    IVIEU = KL2\n  ELSE\n    IDENT = KL2\n    IVIEU = KL1\n  ENDIF\n  !\n  ZDIAMD (KL1) = - PSNOWGRAN1(IDENT)/XGRAN * XDIAET + ( 1.0 + PSNOWGRAN1(IDENT)/XGRAN ) * &\n                 ( PSNOWGRAN2(IDENT)/XGRAN * XDIAGF + ( 1.0 - PSNOWGRAN2(IDENT)/XGRAN ) * XDIAFP )\n  !\n  ZSPHERD(KL1) = PSNOWGRAN2(IDENT)/XGRAN\n  ZDIAMV (KL1) = PSNOWGRAN2(IVIEU)\n  ZSPHERV(KL1) = PSNOWGRAN1(IVIEU)/XGRAN\n  !IF(KL1==1)THEN\n  !write(*,*) 'ZDD1',ZDIAMD(1),'ZSD1',ZSPHERD(1)\n  !write(*,*) 'ZDV1',ZDIAMV(1),'ZSV1',ZSPHERV(1)\n  !ENDIF\n  !\n  IF ( IDENT==KL1 ) THEN\n    !code original vincent        ZDIAMN(KL1)= (ZDIAMD(KL1)*PSNOWRHO(IDENT)*&\n    !code original vincent            (PSNOWDZN(IDENT)-(1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))-ZDELTA*      &\n    !code original vincent            ABS(PSNOWDDZ(KL2)))+ZDIAMV(KL1)*PSNOWRHO(IVIEU)*(       &\n    !code original vincent            (1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2))))/&\n    !code original vincent            ((PSNOWDZN(KL1)-(1.0-ZDELTA)*                                    &\n    !code original vincent            ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2)))*            &\n    !code original vincent            PSNOWRHO(KL1)+((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+          &   \n    !code original vincent            ZDELTA*ABS(PSNOWDDZ(KL2)))*PSNOWRHO(KL2))\n    !\n    !plm\n    CALL GET_AGREG(IDENT,IVIEU,ZDIAMD(KL1),ZDIAMV(KL1),ZDIAMN(KL1))\n    !\n    !plm\n    !\n    !code original vincent        ZSPHERN(KL1)= (ZSPHERD(KL1)*PSNOWRHO(IDENT)*&\n    !code original vincent            (PSNOWDZN(IDENT)-(1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))-ZDELTA*      &\n    !code original vincent            ABS(PSNOWDDZ(KL2)))+ZSPHERV(KL1)*PSNOWRHO(IVIEU)*(       &\n    !code original vincent            (1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2))))/&\n    !code original vincent            ((PSNOWDZN(KL1)-(1.0-ZDELTA)*                                    &\n    !code original vincent            ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2)))*            &\n    !code original vincent            PSNOWRHO(KL1)+((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+          &   \n    !code original vincent            ZDELTA*ABS(PSNOWDDZ(KL2)))*PSNOWRHO(KL2))\n\n    !plm\n    CALL GET_AGREG(IDENT,IVIEU,ZSPHERD(KL1),ZSPHERV(KL1),ZSPHERN(KL1))   \n    !plm\n    !\n  ELSE\n    !code original vincent        ZDIAMN(KL1)= (ZDIAMD(KL1)*PSNOWRHO(IDENT)*&\n    !code original vincent            ((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+ZDELTA*ABS(PSNOWDDZ(KL2)))&\n    !code original vincent            +ZDIAMV(KL1)*PSNOWRHO(IVIEU)*(PSNOWDZN(IVIEU)-(1.0-ZDELTA)*  & \n    !code original vincent            ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2))))/&\n    !code original vincent            ((PSNOWDZN(KL1)-(1.0-ZDELTA)*                          &\n    !code original vincent            ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2)))*    &\n    !code original vincent            PSNOWRHO(KL1)+((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+   &\n    !code original vincent            ZDELTA*ABS(PSNOWDDZ(KL2)))*PSNOWRHO(KL2))\n    !code original vincent!\n    !code original vincent         ZSPHERN(KL1)= (ZSPHERD(KL1)*PSNOWRHO(IDENT)*&\n    !code original vincent            ((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+ZDELTA*ABS(PSNOWDDZ(KL2)))&\n    !code original vincent            +ZSPHERV(KL1)*PSNOWRHO(IVIEU)*(PSNOWDZN(IVIEU)-(1.0-ZDELTA)* & \n    !code original vincent            ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2))))/&\n    !code original vincent            ((PSNOWDZN(KL1)-(1.0-ZDELTA)*                                    &\n    !code original vincent            ABS(PSNOWDDZ(KL1))-ZDELTA*ABS(PSNOWDDZ(KL2)))*            &\n    !code original vincent            PSNOWRHO(KL1)+((1.0-ZDELTA)*ABS(PSNOWDDZ(KL1))+          &   \n    !code original vincent            ZDELTA*ABS(PSNOWDDZ(KL2)))*PSNOWRHO(KL2))\n    !plm\n    !\n    CALL GET_AGREG(IVIEU,IDENT,ZDIAMV(KL1),ZDIAMD(KL1),ZDIAMN(KL1))\n    !\n    CALL GET_AGREG(IVIEU,IDENT,ZSPHERV(KL1),ZSPHERD(KL1),ZSPHERN(KL1))\n    !plm\n    !\n  ENDIF\n  !\n  ZCOMP = ZSPHERN(KL1) * XDIAGF + ( 1.-ZSPHERN(KL1) ) * XDIAFP\n  IF( ZDIAMN(KL1) < ZCOMP ) THEN\n    !\n    ZDENT(KL1) = ( ZDIAMN(KL1) - ZCOMP ) / ( XDIAET - ZCOMP )\n    !IF(KL1==1) write(*,*) 'ZDENT',ZDENT(1)\n    PSNOWGRAN1N(KL1) = - XGRAN * ZDENT  (KL1)\n    PSNOWGRAN2N(KL1) =   XGRAN * ZSPHERN(KL1)\n    !\n  ELSE\n    !\n    PSNOWGRAN1N(KL1) = XGRAN * ZSPHERN(KL1)\n    PSNOWGRAN2N(KL1) = ZDIAMN(KL1)\n    !\n  ENDIF\n  !\nENDIF\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LAGREG',1,ZHOOK_HANDLE)\n!\n!       3. Update snow grains parameters : GRAN1, GRAN2\n!        PSNOWGRAN1(KL1)=ZSNOWGRAN1(KL1)\n!        PSNOWGRAN2(KL1)=ZSNOWGRAN2(KL1)\n!\n CONTAINS\n!\nSUBROUTINE GET_AGREG(KID1,KID2,PFIELD1,PFIELD2,PFIELD)\n!\nINTEGER, INTENT(IN) :: KID1, KID2\nREAL, INTENT(IN) :: PFIELD1, PFIELD2\nREAL, INTENT(OUT) :: PFIELD\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LAGREG:GET_AGREG',0,ZHOOK_HANDLE)\n!\nPFIELD = ( PFIELD1 * PSNOWRHO(KID1) * ( PSNOWDZN(KID1) - ABS(PSNOWDDZ(IL)) ) &\n         + PFIELD2 * PSNOWRHO(KID2) * ABS(PSNOWDDZ(IL))                        ) / &\n         (           PSNOWRHO (KL1) * ( PSNOWDZN (KL1) - ABS(PSNOWDDZ(IL)) ) + &\n                     PSNOWRHO (KL2) * ABS(PSNOWDDZ(IL))                        ) \n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LAGREG:GET_AGREG',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_AGREG\n!\nEND SUBROUTINE SNOW3LAGREG\n!###############################################################################    \n!###############################################################################\n!\n!\n!ajout EB : ajout des arguments \"N\" pour faire idem variables d'origine\nSUBROUTINE SNOW3LAVGRAIN(PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,                &\n                         PSNOWGRAN1N,PSNOWGRAN2N,PSNOWHISTN,PNDENT,PNVIEU,&\n                         HSNOWMETAMO)\n!\nUSE MODD_SNOW_METAMO, ONLY : XVDIAM6, XUEPSI\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!       0.1 declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(INOUT)  :: PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST\n! ajout EB\nREAL, DIMENSION(:,:), INTENT(INOUT)  :: PSNOWGRAN1N,PSNOWGRAN2N,PSNOWHISTN \n!\nREAL, DIMENSION(:), INTENT(IN)    :: PNDENT, PNVIEU\n!\n CHARACTER(3), INTENT(IN)              :: HSNOWMETAMO\n!       0.2 declaration of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWGRAN1,1)) :: ZGRAN1, ZGRAN2, ZHIST\n!\nLOGICAL, DIMENSION(SIZE(PSNOWGRAN1,1),SIZE(PSNOWGRAN1,2)) :: GDENDRITIC\n!\nINTEGER :: JI, JL\nINTEGER :: INLVLS, INI\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!       0.3 initialization\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LAVGRAIN',0,ZHOOK_HANDLE)\n!\nINLVLS    = SIZE(PSNOWGRAN1,2)\nINI       = SIZE(PSNOWGRAN1,1)\n!\nZGRAN1(:) = 0.0\nZGRAN2(:) = 0.0\nZHIST (:) = 0.0\n!\nDO JI = 1,INI\n  !\n  IF ( PNDENT(JI)==0.0 .AND. PNVIEU(JI)==0.0 ) THEN\n    !\n    ZGRAN1(JI) = 1.0\n    ZGRAN2(JI) = 1.0\n    ZHIST (JI) = 1.0\n    !\n  ELSE\n    !\n    DO JL = 1,INLVLS\n      IF ( HSNOWMETAMO=='B92' ) THEN\n        GDENDRITIC(JI,JL) = ( PSNOWGRAN1(JI,JL) < 0.0 )\n      ELSE\n        GDENDRITIC(JI,JL) = ( PSNOWGRAN1(JI,JL) < XVDIAM6*(4.-PSNOWGRAN2(JI,JL)) - XUEPSI )\n      ENDIF\n    ENDDO\n    !\n    IF ( PNDENT(JI)>=PNVIEU(JI) ) THEN      ! more dendritic than non dendritic snow layer\n      !\n      DO JL = 1,INLVLS\n        IF ( GDENDRITIC(JI,JL) ) THEN\n          ZGRAN1(JI) = ZGRAN1(JI) + PSNOWGRAN1(JI,JL)\n          ZGRAN2(JI) = ZGRAN2(JI) + PSNOWGRAN2(JI,JL)\n        ENDIF\n      ENDDO\n      !\n      PSNOWGRAN1N(JI,:) = ZGRAN1(JI) / PNDENT(JI)\n      PSNOWGRAN2N(JI,:) = ZGRAN2(JI) / PNDENT(JI)\n      PSNOWHISTN (JI,:) = 0.0\n      !\n    ELSE                              ! more non dendritic than dendritic snow layers  \n      !\n      DO JL = 1,INLVLS\n        IF ( .NOT.GDENDRITIC(JI,JL) ) THEN\n          ZGRAN1(JI) = ZGRAN1(JI) + PSNOWGRAN1(JI,JL)\n          ZGRAN2(JI) = ZGRAN2(JI) + PSNOWGRAN2(JI,JL)\n          ZHIST (JI) = ZHIST (JI) + PSNOWHIST (JI,JL)\n        ENDIF\n      ENDDO\n      !\n      PSNOWGRAN1N(JI,:) = ZGRAN1(JI) / PNVIEU(JI)\n      PSNOWGRAN2N(JI,:) = ZGRAN2(JI) / PNVIEU(JI)\n      PSNOWHISTN (JI,:) = ZHIST (JI) / PNVIEU(JI)\n      !\n    ENDIF\n    !\n  ENDIF\n  !\nENDDO\n\n\n\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LAVGRAIN',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOW3LAVGRAIN\n!\n!####################################################################\n!####################################################################\n!####################################################################\nFUNCTION SNOW3LDIFTYP(PGRAIN1,PGRAIN2,PGRAIN3,PGRAIN4,HSNOWMETAMO) RESULT(ZDIFTYPE)\n!\n! à remplacer sans doute par une routine equivalente du nouveau crocus\n!*    CALCUL DE LA DIFFERENCE ENTRE DEUX TYPES DE GRAINS\n!     VALEUR ENTRE 200 ET 0\n!\nUSE MODD_SNOW_METAMO, ONLY : XGRAN, XVDIAM6, XUEPSI\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!*      0.1    declarations of arguments\nREAL, INTENT(IN) :: PGRAIN1, PGRAIN2, PGRAIN3, PGRAIN4\n CHARACTER(3), INTENT(IN)              :: HSNOWMETAMO\nREAL :: ZDIFTYPE, ZCOEF3, ZCOEF4\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n\n!*      0.2    calcul de la difference entre type de grains\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LDIFTYP',0,ZHOOK_HANDLE)\n!\nIF ( HSNOWMETAMO=='B92' ) THEN\n  !\n  IF ( ( PGRAIN1<0.  .AND. PGRAIN2>=0.) .OR. ( PGRAIN1>=0. .AND. PGRAIN2<0. ) ) THEN\n    ZDIFTYPE = 200.\n  ELSEIF ( PGRAIN1<0. ) THEN\n    ZDIFTYPE = ABS( PGRAIN1-PGRAIN2 ) * .5 + ABS( PGRAIN3-PGRAIN4 ) * .5\n  ELSE\n    ZDIFTYPE = ABS( PGRAIN1-PGRAIN2 )      + ABS( PGRAIN3-PGRAIN4 ) * 5. * 10000.\n  ENDIF\n  !\nELSE\n  !\n  ZCOEF3 = XVDIAM6 * (4.-PGRAIN3) - XUEPSI\n  ZCOEF4 = XVDIAM6 * (4.-PGRAIN4) - XUEPSI\n  IF ( ( PGRAIN1<ZCOEF3 .AND. PGRAIN2>=ZCOEF4 ) .OR. ( PGRAIN1>=ZCOEF3 .AND. PGRAIN2<ZCOEF4 ) ) THEN\n    ZDIFTYPE = 200.\n  ELSEIF ( PGRAIN1<ZCOEF3 ) THEN\n    ZDIFTYPE = ABS( (PGRAIN3-PGRAIN4)*XGRAN ) * .5 + &\n               ABS( ( (PGRAIN1/XVDIAM6 - 4. + PGRAIN3) / (PGRAIN3 - 3.) - &\n                      (PGRAIN2/XVDIAM6 - 4. + PGRAIN4) / (PGRAIN4 - 3.) ) * XGRAN ) * .5\n\n  ELSE\n    ZDIFTYPE = ABS( (PGRAIN3-PGRAIN4)*XGRAN )      + ABS( ZCOEF3-ZCOEF4 ) * 5. * 10000.\n  ENDIF\n  !\nENDIF\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LDIFTYP',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LDIFTYP\n\n!####################################################################\nSUBROUTINE GET_MASS_HEAT(KJ,KNLVLS_NEW,KNLVLS_OLD,                                &\n                         PSNOWZTOP_OLD,PSNOWZTOP_NEW,PSNOWZBOT_OLD,PSNOWZBOT_NEW, &\n                         PSNOWRHOO,PSNOWDZO,PSNOWGRAN1O,PSNOWGRAN2O,PSNOWHISTO,   &\n                         PSNOWAGEO,PSNOWHEATO,                                    &\n                         PSNOWRHON,PSNOWDZN,PSNOWGRAN1N,PSNOWGRAN2N,PSNOWHISTN,   &\n                         PSNOWAGEN, PSNOWHEATN,HSNOWMETAMO                        )\n!\nUSE MODD_SNOW_PAR, ONLY : XSNOWCRITD, XD1, XD2, XD3, XX, XVALB5, XVALB6\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\nINTEGER, INTENt(IN) :: KJ\nINTEGER, INTENT(IN) :: KNLVLS_NEW, KNLVLS_OLD\n! trude, changed from REAL, to REAL*8\nREAL*8, DIMENSION(:), INTENT(IN) :: PSNOWZTOP_OLD, PSNOWZBOT_OLD\nREAL*8, DIMENSION(:), INTENT(IN) :: PSNOWZTOP_NEW, PSNOWZBOT_NEW\nREAL*8, DIMENSION(:), INTENT(IN) :: PSNOWRHOO, PSNOWDZO, PSNOWGRAN1O, PSNOWGRAN2O, &\n                                  PSNOWHISTO, PSNOWAGEO, PSNOWHEATO\nREAL,  DIMENSION(:), INTENT(IN) :: PSNOWDZN\n CHARACTER(3), INTENT(IN)       :: HSNOWMETAMO\nREAL*8, DIMENSION(:), INTENT(OUT) :: PSNOWRHON, PSNOWGRAN1N, PSNOWGRAN2N, &\n                                   PSNOWHISTN, PSNOWAGEN, PSNOWHEATN\n!\nREAL :: ZPROPOR, ZMASDZ_OLD, ZDIAM, ZMASTOT_T07\nREAL :: ZSNOWHEAN, ZMASTOTN, ZDENTMOYN, ZSPHERMOYN, ZALBMOYN, ZHISTMOYN\nREAL :: ZAGEMOYN\n!\nINTEGER :: JST_NEW, JST_OLD\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('GET_MASS_HEAT',0,ZHOOK_HANDLE)\n!\n!      write(6,*) \"in get_mass_heat\"   ! trude\n\nPSNOWRHON  (:) = 0.\nPSNOWGRAN1N(:) = 0.\nPSNOWGRAN2N(:) = 0.\nPSNOWHISTN (:) = 0.\nPSNOWAGEN  (:) = 0.\nPSNOWHEATN (:) = 0.\n!\nDO JST_NEW = 1,KNLVLS_NEW\n  !\n  ZSNOWHEAN   = 0.\n  ZMASTOTN    = 0.\n  ZMASTOT_T07 = 0.\n  ZDENTMOYN   = 0.\n  ZSPHERMOYN  = 0.\n  ZALBMOYN    = 0.\n  ZDIAM       = 0.\n  ZHISTMOYN   = 0.\n  ZAGEMOYN    = 0.\n  !\n  ! lopp over the ols snow layers\n!   write(6,*) \"-------\"\n  DO JST_OLD = 1,KNLVLS_OLD\n!      write(6,*) \"knlvls_old \", knlvls_old, jst_old, jst_new\n!      write(6,*) PSNOWZTOP_OLD(JST_OLD), PSNOWZBOT_NEW(JST_NEW)\n!      write(6,*) PSNOWZBOT_OLD(JST_OLD), PSNOWZTOP_NEW(JST_NEW)\n    !\n    IF( PSNOWZTOP_OLD(JST_OLD)<=PSNOWZBOT_NEW(JST_NEW) ) THEN\n      ! JST_OLD lower than JJ_NEW ==> no contribution\n    ELSEIF ( PSNOWZBOT_OLD(JST_OLD)>=PSNOWZTOP_NEW(JST_NEW) ) THEN\n      ! JST_OLD higher than JJ_NEW ==> no contribution\n    ELSE\n      ! old layer contributes to the new one\n      ! computation of its contributing ratio and mass/heat\n      ZPROPOR = ( MIN( PSNOWZTOP_OLD(JST_OLD), PSNOWZTOP_NEW(JST_NEW) )   &\n                - MAX( PSNOWZBOT_OLD(JST_OLD), PSNOWZBOT_NEW(JST_NEW) ) ) &\n                 / PSNOWDZO(JST_OLD)\n      ZMASDZ_OLD = ZPROPOR * PSNOWRHOO(JST_OLD) * PSNOWDZO(JST_OLD)\n!      write(6,*) \"zpropor \", zpropor\n!      write(6,*) \"psnowrhoo \", psnowrhoo(jst_old)\n!      write(6,*) \"psnowdzo \", psnowdzo(jst_old)\n      !\n      ZMASTOTN    = ZMASTOTN + ZMASDZ_OLD\n!      write(6,*) \"zmastotn \", zmastotn\n!      write(6,*) \"zmasdz_old \", zmasdz_old\n      ZMASTOT_T07 = ZMASTOT_T07 + 1.\n      !\n      ZSNOWHEAN = ZSNOWHEAN + ZPROPOR * PSNOWHEATO(JST_OLD)\n      !\n      IF ( HSNOWMETAMO=='B92' ) THEN\n        !\n        ! contribution to the grain optical size and then to the albedo\n        IF ( PSNOWGRAN1O(JST_OLD)<0. ) THEN\n          ZDIAM = -PSNOWGRAN1O(JST_OLD)*XD1/XX + (1.+PSNOWGRAN1O(JST_OLD)/XX) * &\n                 ( PSNOWGRAN2O(JST_OLD)*XD2/XX + (1.-PSNOWGRAN2O(JST_OLD)/XX)*XD3 ) \n          ZDIAM = ZDIAM/10000.\n          ZDENTMOYN  = ZDENTMOYN  - ZMASDZ_OLD * PSNOWGRAN1O(JST_OLD) / XX\n          ZSPHERMOYN = ZSPHERMOYN + ZMASDZ_OLD * PSNOWGRAN2O(JST_OLD) / XX\n        ELSE\n          ZDIAM = PSNOWGRAN2O(JST_OLD)\n          ZDENTMOYN  = ZDENTMOYN  + ZMASDZ_OLD * 0.\n          ZSPHERMOYN = ZSPHERMOYN + ZMASDZ_OLD * PSNOWGRAN1O(JST_OLD) / XX\n        ENDIF\n        !\n      ELSE\n        !\n        ZDIAM = PSNOWGRAN1O(JST_OLD)\n        ZSPHERMOYN = ZSPHERMOYN + ZMASDZ_OLD * PSNOWGRAN2O(JST_OLD)\n        !\n      ENDIF\n      !\n      ZALBMOYN  = ZALBMOYN  + MAX( 0., ZMASDZ_OLD * (XVALB5-XVALB6*SQRT(ZDIAM)) )\n      ZHISTMOYN = ZHISTMOYN + ZMASDZ_OLD * PSNOWHISTO(JST_OLD)\n      ZAGEMOYN  = ZAGEMOYN  + ZMASDZ_OLD * PSNOWAGEO (JST_OLD)\n      !\n    ENDIF\n    !\n  ENDDO\n  !\n  ! the new layer inherits from the weihted average properties of the old ones\n  ! heat and mass\n  PSNOWHEATN(JST_NEW) = ZSNOWHEAN\n! trude test\n\n!      write(6,*) \"zmastotn \", zmastotn\n!      write(6,*) \"psnowdzn \", psnowdzn(jst_new)\n  PSNOWRHON (JST_NEW) = ZMASTOTN / PSNOWDZN(JST_NEW)\n !     write(6,*) \"psnowrhon \", psnowrhon(jst_new)\n  ! grain type and size decuced from the average albedo\n  ZALBMOYN   = ZALBMOYN / ZMASTOTN\n  ZSPHERMOYN = MAX( 0., ZSPHERMOYN/ZMASTOTN )\n  ZDENTMOYN  = MAX( 0., ZDENTMOYN /ZMASTOTN )\n  ZDIAM = ( (XVALB5-ZALBMOYN)/XVALB6 )**2\n  !\n  IF ( HSNOWMETAMO=='B92' ) THEN\n    !\n    ! size between D2 and D3 and dendricity < 0\n    ! sphericity is firts preserved, if possible. If not,\n    ! denditricity =0\n    PSNOWGRAN1N(JST_NEW) = -XX * ZDENTMOYN\n    !\n    IF ( ZDENTMOYN/=1.) THEN\n      PSNOWGRAN2N(JST_NEW) = XX * ( ( ZDIAM*10000. + PSNOWGRAN1N(JST_NEW)*XD1/XX ) &\n                                 / ( 1. + PSNOWGRAN1N(JST_NEW)/XX ) - XD3 )        &\n                             / ( XD2-XD3 )\n    ENDIF\n    !\n    ! dendricity is preserved if possible and sphericity is adjusted\n    IF ( ZDIAM < XD2/10000. - 0.0000001 ) THEN\n      !\n      IF ( ABS( PSNOWGRAN1N(JST_NEW)+XX ) < 0.01 ) THEN\n        !\n        PSNOWGRAN2N(JST_NEW) = XX * ZSPHERMOYN\n        !\n      ELSEIF ( ABS( PSNOWGRAN1N(JST_NEW) ) < 0.0001 ) THEN ! dendritic snow\n        !\n        PSNOWGRAN1N(JST_NEW) = XX * ZSPHERMOYN\n        PSNOWGRAN2N(JST_NEW) = ZDIAM\n        !\n      ELSEIF ( PSNOWGRAN2N(JST_NEW) < 0. ) THEN ! non dendritic\n        !\n        PSNOWGRAN2N(JST_NEW) = 0.\n        !\n      ELSEIF ( PSNOWGRAN2N(JST_NEW) > XX + 0.0000001 ) THEN ! non dendritic\n        !\n        PSNOWGRAN2N(JST_NEW) = XX\n        !\n      ENDIF\n      !\n    ELSEIF ( ZDIAM > XD3/10000. .OR. ZDENTMOYN <= 0. + 0.0000001 .OR. &\n             PSNOWGRAN2N(JST_NEW) < 0. .OR. PSNOWGRAN2N(JST_NEW) > XX ) THEN\n      !\n      ! dendritic snow\n      ! inconsistency with ZDIAM ==>  dendricity = 0\n      ! size between D2 and D3 and dendricity == 0\n      PSNOWGRAN1N(JST_NEW) = XX * ZSPHERMOYN\n      PSNOWGRAN2N(JST_NEW) = ZDIAM\n      !\n    ENDIF\n    !\n  ELSE\n    !\n    PSNOWGRAN1N(JST_NEW) = ZDIAM\n    PSNOWGRAN2N(JST_NEW) = MIN( 1., ZSPHERMOYN )\n    !\n  ENDIF\n  !\n  PSNOWHISTN(JST_NEW) = NINT( ZHISTMOYN/ZMASTOTN )\n  PSNOWAGEN (JST_NEW) = ZAGEMOYN / ZMASTOTN\n  !\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('GET_MASS_HEAT',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_MASS_HEAT\n!####################################################################\nSUBROUTINE GET_DIAM(PSNOWGRAN1,PSNOWGRAN2,PDIAM,HSNOWMETAMO)\n!\nUSE MODD_SNOW_PAR, ONLY : XD1, XD2, XD3, XX\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\nREAL, INTENT(IN) :: PSNOWGRAN1\nREAL, INTENT(IN) :: PSNOWGRAN2\nREAL, INTENT(OUT) :: PDIAM\n!\n CHARACTER(3), INTENT(IN)              :: HSNOWMETAMO\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('GET_DIAM',0,ZHOOK_HANDLE)\n!\nIF ( HSNOWMETAMO=='B92' ) THEN\n  !\n  IF( PSNOWGRAN1<0. ) THEN\n    PDIAM = -PSNOWGRAN1*XD1/XX + (1.+PSNOWGRAN1/XX) * &\n           ( PSNOWGRAN2*XD2/XX + (1.-PSNOWGRAN2/XX) * XD3 )\n    PDIAM = PDIAM/10000.\n  ELSE\n    PDIAM = PSNOWGRAN2*PSNOWGRAN1/XX + &\n            MAX( 0.0004, 0.5*PSNOWGRAN2 ) * ( 1.-PSNOWGRAN1/XX )\n  ENDIF\n  !\nELSE\n  !\n  PDIAM = PSNOWGRAN1\n  !\nENDIF\n!\n!IF (LHOOK) CALL DR_HOOK('GET_DIAM',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_DIAM\n!####################################################################\n!####################################################################\n!####################################################################\n!####################################################################\n!####################################################################\n!####################################################################\n      SUBROUTINE SNOW3LTHRM(PSNOWRHO,PSCOND,PSNOWTEMP,PPS)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate snow thermal conductivity from\n!     Sun et al. 1999, J. of Geophys. Res., 104, 19587-19579 (vapor)\n!     and Yen, 1981, CRREL Rep 81-10 (snow)\n!     or Anderson, 1976, NOAA Tech. Rep. NWS 19 (snow).\n!\n!\nUSE MODD_CSTS,     ONLY : XP00, XCONDI, XRHOLW\n!\nUSE MODD_SNOW_PAR, ONLY : XVRKZ6, XSNOWTHRMCOND1, &\n                          XSNOWTHRMCOND2,         &\n                          XSNOWTHRMCOND_AVAP,     &\n                          XSNOWTHRMCOND_BVAP,     &\n                          XSNOWTHRMCOND_CVAP\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PPS\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWTEMP, PSNOWRHO\n!\nREAL, DIMENSION(:,:), INTENT(OUT)   :: PSCOND\n!\n!\n!*      0.2    declarations of local variables\n!\nINTEGER                              :: JJ, JI\n!\nINTEGER                              :: INI\nINTEGER                              :: INLVLS\n!\n CHARACTER(LEN=5)                     :: YSNOWCOND !should be in namelist\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LTHRM',0,ZHOOK_HANDLE)\n!\nINI    = SIZE(PSNOWRHO(:,:),1)\nINLVLS = SIZE(PSNOWRHO(:,:),2)\n!\n! 1. Snow thermal conductivity\n! ----------------------------\n!\nYSNOWCOND='YEN81' !should be in namelist\n!\nIF(YSNOWCOND=='AND76')THEN\n!  Thermal conductivity coefficients from Anderson (1976)\n  PSCOND(:,:) = (XSNOWTHRMCOND1 + XSNOWTHRMCOND2*PSNOWRHO(:,:)*PSNOWRHO(:,:))\nELSE\n! Thermal conductivity coefficients from Yen (1981)\n  PSCOND(:,:) = XCONDI * EXP(XVRKZ6*LOG(PSNOWRHO(:,:)/XRHOLW))\nENDIF\n!\n! 2. Implicit vapor diffn effects\n! -------------------------------\n!\nDO JJ=1,INLVLS\n   DO JI=1,INI\n    PSCOND(JI,JJ) = PSCOND(JI,JJ) + MAX(0.0,(XSNOWTHRMCOND_AVAP+(XSNOWTHRMCOND_BVAP/(PSNOWTEMP(JI,JJ) &\n                                  + XSNOWTHRMCOND_CVAP)))*(XP00/PPS(JI)))\n   ENDDO\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LTHRM',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SNOW3LTHRM\n!####################################################################\n!####################################################################\n!####################################################################\nFUNCTION SNOW3LDOPT_2D(PSNOWRHO,PSNOWAGE) RESULT(PDOPT)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the optical grain diameter.\n!\nUSE MODD_SNOW_PAR, ONLY : XDSGRAIN_MAX,XSNOW_AGRAIN, &\n                          XSNOW_BGRAIN,XSNOW_CGRAIN\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(IN)                   :: PSNOWRHO,PSNOWAGE\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: PDOPT\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZAGE\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSRHO4\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LDOPT_2D',0,ZHOOK_HANDLE)\n!\nZAGE(:,:) = MIN(15.,PSNOWAGE(:,:))\n!\nZSRHO4(:,:) = PSNOWRHO(:,:)*PSNOWRHO(:,:)*PSNOWRHO(:,:)*PSNOWRHO(:,:)\n!\nPDOPT(:,:) = MIN(XDSGRAIN_MAX,XSNOW_AGRAIN+XSNOW_BGRAIN*ZSRHO4(:,:)+XSNOW_CGRAIN*ZAGE(:,:))\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LDOPT_2D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LDOPT_2D\n!####################################################################\nFUNCTION SNOW3LDOPT_1D(PSNOWRHO,PSNOWAGE) RESULT(PDOPT)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the optical grain diameter.\n!\nUSE MODD_SNOW_PAR, ONLY : XDSGRAIN_MAX,XSNOW_AGRAIN, &\n                          XSNOW_BGRAIN,XSNOW_CGRAIN\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)  :: PSNOWRHO,PSNOWAGE\n!\nREAL, DIMENSION(SIZE(PSNOWRHO)) :: PDOPT\nREAL, DIMENSION(SIZE(PSNOWRHO)) :: ZAGE\nREAL, DIMENSION(SIZE(PSNOWRHO)) :: ZSRHO4\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LDOPT_1D',0,ZHOOK_HANDLE)\n!\nZAGE(:) = MIN(15.,PSNOWAGE(:))\n!\nZSRHO4(:) = PSNOWRHO(:)*PSNOWRHO(:)*PSNOWRHO(:)*PSNOWRHO(:)\n!\nPDOPT(:) = MIN(XDSGRAIN_MAX,XSNOW_AGRAIN+XSNOW_BGRAIN*ZSRHO4(:)+XSNOW_CGRAIN*ZAGE(:))\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LDOPT_1D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LDOPT_1D\n!####################################################################\nFUNCTION SNOW3LDOPT_0D(PSNOWRHO,PSNOWAGE) RESULT(PDOPT)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the optical grain diameter.\n!\nUSE MODD_SNOW_PAR, ONLY : XDSGRAIN_MAX,XSNOW_AGRAIN, &\n                          XSNOW_BGRAIN,XSNOW_CGRAIN\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)  :: PSNOWRHO,PSNOWAGE\n!\nREAL :: PDOPT\nREAL :: ZAGE\nREAL :: ZSRHO4\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LDOPT_0D',0,ZHOOK_HANDLE)\n!\nZAGE = MIN(15.,PSNOWAGE)\n!\nZSRHO4 = PSNOWRHO*PSNOWRHO*PSNOWRHO*PSNOWRHO\n!\nPDOPT = MIN(XDSGRAIN_MAX,XSNOW_AGRAIN+XSNOW_BGRAIN*ZSRHO4+XSNOW_CGRAIN*ZAGE)\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LDOPT_0D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION SNOW3LDOPT_0D\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOW3LALB(PALBEDOSC,PSPECTRALALBEDO,PSNOWRHO,PSNOWAGE,   &\n                     PPERMSNOWFRAC,PPS)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the snow surface albedo. Use the method of\n!     CROCUS with 3 spectral albedo depending on snow density\n!     and age\n!\n!\nUSE MODD_SNOW_PAR, ONLY : XVAGING_GLACIER, XVAGING_NOGLACIER,     &\n                          XVALB2,XVALB3,XVALB4,XVALB5,XVALB6,     &\n                          XVALB7,XVALB8,XVALB9,XVALB10,XVALB11,   &\n                          XVDIOP1,XVRPRE1,XVRPRE2,XVPRES1,        &\n                          XVW1,XVW2,XVSPEC1,XVSPEC2,XVSPEC3\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PSNOWRHO\nREAL, DIMENSION(:), INTENT(IN)      :: PSNOWAGE\nREAL, DIMENSION(:), INTENT(IN)      :: PPERMSNOWFRAC\nREAL, DIMENSION(:), INTENT(IN)      :: PPS\n!\nREAL, DIMENSION(:),   INTENT(INOUT) :: PALBEDOSC\nREAL, DIMENSION(:,:), INTENT(INOUT) :: PSPECTRALALBEDO\n!\n!*      0.2    declarations of local variables\n!\nREAL, PARAMETER                 :: ZALBNIR1 = 0.3\nREAL, PARAMETER                 :: ZALBNIR2 = 0.0\n!\nREAL, DIMENSION(SIZE(PSNOWRHO)) :: ZVAGING, ZDIAM, ZAGE,  &\n                                   ZWORK, ZPRES_EFFECT\n!\nREAL, DIMENSION(SIZE(PSNOWRHO)) :: ZALB1, ZALB2, ZALB3\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LALB',0,ZHOOK_HANDLE)\n!\n! 0. Initialize:\n! ------------------\n!\n!Snow age effect parameter for Visible (small over glacier)\nZVAGING(:)=XVAGING_GLACIER*PPERMSNOWFRAC(:) + XVAGING_NOGLACIER*(1.0-PPERMSNOWFRAC(:))\n!\n!Atm pression effect parameter on albedo\nZPRES_EFFECT(:) = XVALB10*MIN(MAX(PPS(:)/XVPRES1,XVRPRE1),XVRPRE2)\n!\n! 1. Snow optical grain diameter :\n! --------------------------------\n!\n!Snow optical diameter do not depend on snow age over glacier or polar regions\nZAGE(:) = (1.0-PPERMSNOWFRAC(:))*PSNOWAGE(:)\n!\nZDIAM(:) = SNOW3LDOPT(PSNOWRHO(:),ZAGE(:))\n!\n! 2. spectral albedo over 3 bands :\n! ---------------------------------\n!\n!Snow age effect limited to 1 year\nZAGE(:) = MIN(365.,PSNOWAGE(:))\n!\nZWORK(:)=SQRT(ZDIAM(:))\n!\n! Visible\nZALB1(:)=MIN(XVALB4,XVALB2-XVALB3*ZWORK(:))\nZALB1(:)=MAX(XVALB11,ZALB1(:)-ZPRES_EFFECT(:)*ZAGE(:)/ZVAGING(:))\n!\n! near Infra-red 1\nZALB2(:)=XVALB5-XVALB6*ZWORK(:)\nZALB2(:)=MAX(ZALBNIR1,ZALB2(:))\n!\n! near Infra-red 2\nZDIAM(:)=MIN(XVDIOP1,ZDIAM(:))\nZWORK(:)=SQRT(ZDIAM(:))\nZALB3(:)=XVALB7*ZDIAM(:)-XVALB8*ZWORK(:)+XVALB9\nZALB3(:)=MAX(ZALBNIR2,ZALB3(:))\n!\nPSPECTRALALBEDO(:,1)=ZALB1(:)\nPSPECTRALALBEDO(:,2)=ZALB2(:)\nPSPECTRALALBEDO(:,3)=ZALB3(:)\n!\n! 3. total albedo :\n! -----------------\n!\nPALBEDOSC(:)=XVSPEC1*ZALB1(:)+XVSPEC2*ZALB2(:)+XVSPEC3*ZALB3(:)\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_SNOW3L:SNOW3LALB',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SNOW3LALB\n!####################################################################\n!####################################################################\n!####################################################################\nEND MODULE MODE_SNOW3L\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/mode_surf_coefs.F",
    "content": "MODULE MODE_SURF_COEFS\n\n!++Trude. To reduce the numbers of module used, I merged module modi_surface_aero_cond, modi_surface_cd and modi_surface_ri into one module. \n\n!++ Trude: Also included wind_threshold function\nCONTAINS\n\n!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\n!   ######################################################################\n    SUBROUTINE SURFACE_AERO_COND(PRI, PZREF, PUREF, PVMOD, PZ0,&\n                                     PZ0H, PAC, PRA, PCH           )\n!   ######################################################################\n!\n!!****  *SURFACE_AERO_COND*\n!!\n!!    PURPOSE\n!!    -------\n!\n!     Computes the drag coefficients for heat and momentum near the ground\n!\n!\n!!**  METHOD\n!!    ------\n!\n!\n!\n!    1 and 2 : computation of relative humidity near the ground\n!\n!    3 : richardson number\n!\n!    4 : the aerodynamical resistance for heat transfers is deduced\n!\n!    5 : the drag coefficient for momentum ZCD is computed\n!\n!\n!!    EXTERNAL\n!!    --------\n!!\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!\n!!    MODD_CST\n!!\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!\n!!      V. Masson           * Meteo-France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    20/01/98\n!!                  02/04/01 (P Jabouille) limitation of Z0 with 0.5 PUREF\n!-------------------------------------------------------------------------------\n!\n!*       0.     DECLARATIONS\n!               ------------\n!\nUSE MODD_CSTS,ONLY : XKARMAN\n!USE MODI_WIND_THRESHOLD\n!\nUSE MODE_THERMOS\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\n!\nREAL, DIMENSION(:), INTENT(IN)    :: PRI      ! Richardson number\nREAL, DIMENSION(:), INTENT(IN)    :: PVMOD    ! module of the horizontal wind\nREAL, DIMENSION(:), INTENT(IN)    :: PZREF    ! reference height of the first\n                                              ! atmospheric level\nREAL, DIMENSION(:), INTENT(IN)    :: PUREF    ! reference height of the wind\n                                              ! NOTE this is different from ZZREF\n                                              ! ONLY in stand-alone/forced mode,\n                                              ! NOT when coupled to a model (MesoNH)\nREAL, DIMENSION(:), INTENT(IN)    :: PZ0      ! roughness length for momentum\nREAL, DIMENSION(:), INTENT(IN)    :: PZ0H     ! roughness length for heat\n!\nREAL, DIMENSION(:), INTENT(OUT)   :: PAC      ! aerodynamical conductance\nREAL, DIMENSION(:), INTENT(OUT)   :: PRA      ! aerodynamical resistance\nREAL, DIMENSION(:), INTENT(OUT)   :: PCH      ! drag coefficient for heat\n!\n!*      0.2    declarations of local variables\n!\n!\nREAL, DIMENSION(SIZE(PRI)) :: ZZ0, ZZ0H, ZMU,          &\n                               ZFH, ZCHSTAR, ZPH, ZCDN, &\n                               ZSTA, ZDI, ZWORK1, ZWORK2, ZWORK3\nREAL, DIMENSION(SIZE(PRI)) :: ZVMOD\n!\nINTEGER                    :: JJ\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n! Functions:\nREAL :: X, CHSTAR, PH\n CHSTAR(X) = 3.2165 + 4.3431*X + 0.5360*X*X - 0.0781*X*X*X\nPH    (X) = 0.5802 - 0.1571*X + 0.0327*X*X - 0.0026*X*X*X\n!\n!-------------------------------------------------------------------------------\n!\n!*       4.     Surface aerodynamic resistance for heat transfers\n!               -------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('SURFACE_AERO_COND',0,ZHOOK_HANDLE)\nZVMOD(:) = WIND_THRESHOLD(PVMOD(:),PUREF(:))\n!\nDO JJ=1,SIZE(PRI)\n!write(*,*) PZ0(jj), puref(jj), zz0(jj), pz0h(jj)\n  ZZ0(JJ)  = MIN(PZ0(JJ),PUREF(JJ)*0.5)\n  ZZ0H(JJ) = MIN(ZZ0(JJ),PZ0H(JJ))\n  ZZ0H(JJ) = MIN(ZZ0H(JJ),PZREF(JJ)*0.5)\n!\n  ZWORK1(JJ)=LOG( PUREF(JJ)/ZZ0(JJ) )\n  ZWORK2(JJ)=PZREF(JJ)/ZZ0H(JJ)\n  ZWORK3(JJ)=ZVMOD(JJ)*ZVMOD(JJ)\n\n  ZMU(JJ) = MAX( LOG( ZZ0(JJ)/ZZ0H(JJ) ), 0.0 )\n  ZFH(JJ) = ZWORK1(JJ) / LOG(ZWORK2(JJ))\n!\n  ZCHSTAR(JJ) = CHSTAR(ZMU(JJ))\n  ZPH(JJ)     = PH(ZMU(JJ))\n!\n!\n  ZCDN(JJ) = (XKARMAN/ZWORK1(JJ))**2.\n!\n!\n  ZSTA(JJ) = PRI(JJ)*ZWORK3(JJ)\n!\n!\n  IF ( PRI(JJ) < 0.0 ) THEN\n    ZDI(JJ) = 1. / ( ZVMOD(JJ)                                  &\n                   +ZCHSTAR(JJ)*ZCDN(JJ)*15.                         &\n                                *ZWORK2(JJ)**ZPH(JJ)  &\n                                *ZFH(JJ) * SQRT(-ZSTA(JJ))           &\n                  )\n    PAC(JJ) = ZCDN(JJ)*(ZVMOD(JJ)-15.* ZSTA(JJ)*ZDI(JJ))*ZFH(JJ)\n\n  ELSE\n    ZDI(JJ) = SQRT(ZWORK3(JJ) + 5. * ZSTA(JJ) )\n    PAC(JJ) = ZCDN(JJ)*ZVMOD(JJ)/(1.+15.*ZSTA(JJ)*ZDI(JJ)  &\n             / ZWORK3(JJ) /ZVMOD(JJ) )*ZFH(JJ)\n  ENDIF\n!\n  PRA(JJ) = 1. / PAC(JJ)\n!\n  PCH(JJ) = 1. / (PRA(JJ) * ZVMOD(JJ))\n!\nENDDO\n!IF (LHOOK) CALL DR_HOOK('SURFACE_AERO_COND',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SURFACE_AERO_COND\n\n!   #################################################################\n    SUBROUTINE SURFACE_CD(PRI, PZREF, PUREF, PZ0EFF, PZ0H,   &\n                              PCD, PCDN)\n!   #################################################################\n!\n!!****  *SURFACE_CD*\n!!\n!!    PURPOSE\n!!    -------\n!\n!     Computes the drag coefficients for momentum near the ground\n!\n!\n!!**  METHOD\n!!    ------\n!\n!\n!\n!    1 and 2 : computation of relative humidity near the ground\n!\n!    3 : richardson number\n!\n!    4 : the aerodynamical resistance for heat transfers is deduced\n!\n!    5 : the drag coefficient for momentum ZCD is computed\n!\n!\n!!    EXTERNAL\n!!    --------\n!!\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!\n!!    MODD_CST\n!!    MODD_GROUND_PAR\n!!\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!\n!!      V. Masson           * Meteo-France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    20/01/98\n!!                  02/04/01 (P Jabouille) limitation of Z0 with 0.5 PUREF\n!-------------------------------------------------------------------------------\n!\n!*       0.     DECLARATIONS\n!               ------------\n!\nUSE MODD_CSTS,ONLY : XKARMAN\n!\nUSE MODE_THERMOS\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\n!\nREAL, DIMENSION(:), INTENT(IN)    :: PRI      ! Richardson number\nREAL, DIMENSION(:), INTENT(IN)    :: PZREF    ! reference height of the first\n                                              ! atmospheric level\nREAL, DIMENSION(:), INTENT(IN)    :: PUREF    ! reference height of the wind\n!                                             ! NOTE this is different from ZZREF\n!                                             ! ONLY in stand-alone/forced mode,\n!                                             ! NOT when coupled to a model (MesoNH)\nREAL, DIMENSION(:), INTENT(IN)    :: PZ0EFF   ! roughness length for momentum\n                                              ! with subgrid-scale orography\nREAL, DIMENSION(:), INTENT(IN)    :: PZ0H     ! roughness length for heat\n!\nREAL, DIMENSION(:), INTENT(OUT)   :: PCD      ! drag coefficient for momentum\nREAL, DIMENSION(:), INTENT(OUT)   :: PCDN     ! neutral drag coefficient for momentum\n!\n!*      0.2    declarations of local variables\n!\n!\nREAL                       :: ZZ0EFF, ZZ0H, ZMU,     &\n                               ZCMSTAR, ZPM, ZCM, ZFM\nINTEGER                    :: JJ\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n\n! Functions :\nREAL :: X, CMSTAR, PM\n CMSTAR(X) = 6.8741 + 2.6933*X - 0.3601*X*X + 0.0154*X*X*X\nPM    (X) = 0.5233 - 0.0815*X + 0.0135*X*X - 0.0010*X*X*X\n\n!-------------------------------------------------------------------------------\n!\n!*       1.     Drag coefficient for momentum transfers\n!               ---------------------------------------\n!\n\n!\n!IF (LHOOK) CALL DR_HOOK('SURFACE_CD',0,ZHOOK_HANDLE)\nDO JJ=1,SIZE(PRI)\n  ZZ0EFF = MIN(PZ0EFF(JJ),PUREF(JJ)*0.5)\n  ZZ0H   = MIN(ZZ0EFF,PZ0H(JJ))\n!\n  ZMU = LOG( MIN(ZZ0EFF/ZZ0H,200.) )\n!\n  PCDN(JJ) = (XKARMAN/LOG(PUREF(JJ)/ZZ0EFF))**2\n\n  ZCMSTAR = CMSTAR(ZMU)\n  ZPM     = PM(ZMU)\n!\n  ZCM = 10.*ZCMSTAR*PCDN(JJ)*( PUREF(JJ)/ZZ0EFF )**ZPM\n!\n  IF ( PRI(JJ) > 0.0 ) THEN\n    ZFM = 1. + 10.*PRI(JJ) / SQRT( 1.+5.*PRI(JJ) )\n    ZFM = 1. / ZFM\n  ELSE\n    ZFM = 1. - 10.*PRI(JJ) / ( 1.+ZCM*SQRT(-PRI(JJ)) )\n  ENDIF\n!\n  PCD(JJ) = PCDN(JJ)*ZFM\n!\nENDDO\n!IF (LHOOK) CALL DR_HOOK('SURFACE_CD',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SURFACE_CD\n\n!     #########\n    SUBROUTINE SURFACE_RI(PTG, PQS, PEXNS, PEXNA, PTA, PQA,   &\n                               PZREF, PUREF, PDIRCOSZW, PVMOD, PRI )\n!   ######################################################################\n!\n!!****  *SURFACE_RI*\n!!\n!!    PURPOSE\n!!    -------\n!\n!     Computes the richardson number near the ground\n!\n!\n!!**  METHOD\n!!    ------\n!\n!\n!\n!\n!!    EXTERNAL\n!!    --------\n!!\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!\n!!    MODD_CST\n!!    MODD_GROUND_PAR\n!!\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!\n!!      V. Masson           * Meteo-France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    22/09/98\n!-------------------------------------------------------------------------------\n!\n!*       0.     DECLARATIONS\n!               ------------\n!\nUSE MODD_CSTS,     ONLY : XRV, XRD, XG\nUSE MODD_SURF_ATM, ONLY : XRIMAX\n!USE MODI_WIND_THRESHOLD\n!\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\n!\nREAL, DIMENSION(:), INTENT(IN)    :: PTG      ! surface temperature\nREAL, DIMENSION(:), INTENT(IN)    :: PQS      ! surface specific humidity\nREAL, DIMENSION(:), INTENT(IN)    :: PEXNS    ! surface exner function\nREAL, DIMENSION(:), INTENT(IN)    :: PTA      ! temperature at the lowest level\nREAL, DIMENSION(:), INTENT(IN)    :: PQA      ! specific humidity\n                                              ! at the lowest level\nREAL, DIMENSION(:), INTENT(IN)    :: PEXNA    ! exner function\n                                              ! at the lowest level\nREAL, DIMENSION(:), INTENT(IN)    :: PVMOD    ! module of the horizontal wind\n!\nREAL, DIMENSION(:), INTENT(IN)    :: PZREF    ! reference height of the first\n                                              ! atmospheric level\nREAL, DIMENSION(:), INTENT(IN)    :: PUREF    ! reference height of the wind\n!                                             ! NOTE this is different from ZZREF\n!                                             ! ONLY in stand-alone/forced mode,\n!                                             ! NOT when coupled to a model (MesoNH)\nREAL, DIMENSION(:), INTENT(IN)    :: PDIRCOSZW! Cosine of the angle between\n!                                             ! the normal to the surface and\n!                                             ! the vertical\n!\nREAL, DIMENSION(:), INTENT(OUT)   :: PRI      ! Richardson number\n!\n!*      0.2    declarations of local variables\n!\n!\nREAL, DIMENSION(SIZE(PTG))   :: ZTHVA, ZTHVS\nREAL, DIMENSION(SIZE(PVMOD)) :: ZVMOD\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!       1.     Richardson number\n!              -----------------\n!\n!                                                 virtual potential        \n!                                                 temperature at the\n!                                                 first atmospheric level and\n!                                                 at the surface\n!\n!IF (LHOOK) CALL DR_HOOK('SURFACE_RI',0,ZHOOK_HANDLE)\n!\nZTHVA(:)=PTA(:)/PEXNA(:)*( 1.+(XRV/XRD-1.)*PQA(:) )\nZTHVS(:)=PTG(:)/PEXNS(:)*( 1.+(XRV/XRD-1.)*PQS(:) )\n!\nZVMOD(:) = WIND_THRESHOLD(PVMOD(:),PUREF(:))\n!\n                                                ! Richardson's number\nPRI(:) = XG * PDIRCOSZW(:) * PUREF(:) * PUREF(:)              &\n          * (ZTHVA(:)-ZTHVS(:)) / (0.5 * (ZTHVA(:)+ZTHVS(:)) )  &\n          / (ZVMOD(:)*ZVMOD(:)) /PZREF(:)\n!\nPRI(:) = MIN(PRI(:),XRIMAX)\n!\n!IF (LHOOK) CALL DR_HOOK('SURFACE_RI',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SURFACE_RI\n\n\n!     #########\n    FUNCTION WIND_THRESHOLD(PWIND,PUREF) RESULT(PWIND_NEW)\n!   ############################################################################\n!\n!!****  *WIND_THRESHOLD*\n!!\n!!    PURPOSE\n!!    -------\n!\n!     Set a minimum value to the wind for exchange coefficient computations.\n!     This minimum value depends on the forcing height\n!\n!!    AUTHOR\n!!    ------\n!!\n!!      V. Masson           * Meteo-France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    09/2007\n!-------------------------------------------------------------------------------\n!\nUSE MODD_SURF_ATM, ONLY: XCISMIN, XVMODMIN, LALDTHRES\n!\n!*       0.     DECLARATIONS\n!               ------------\n!\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\n!\nREAL, DIMENSION(:), INTENT(IN)   :: PWIND      ! wind\nREAL, DIMENSION(:), INTENT(IN)   :: PUREF      ! forcing level\n!\nREAL, DIMENSION(SIZE(PWIND))     :: PWIND_NEW  ! modified wind\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!\n!\n!*      0.2    declarations of local variables\n!\n!-------------------------------------------------------------------------------\n!\n!  wind gradient\n!\n!IF (LHOOK) CALL DR_HOOK('WIND_THRESHOLD',0,ZHOOK_HANDLE)\nIF (.NOT.LALDTHRES) THEN\n!\n!  minimum value for exchange coefficients computations : 1m/s / 10m\n   PWIND_NEW = MAX(PWIND , 0.1 * MIN(10.,PUREF) )\nELSE\n!  minimum value for exchange coefficients computations : 1m/s / 10m\n   PWIND_NEW = MAX( XVMODMIN, SQRT( PWIND**2 + (XCISMIN*PUREF)**2 ) )\nENDIF\n!IF (LHOOK) CALL DR_HOOK('WIND_THRESHOLD',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION WIND_THRESHOLD\n\n\n\n\nEND MODULE MODE_SURF_COEFS\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/mode_thermos.F",
    "content": "!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\n!     ######spl\n      MODULE MODE_THERMOS\n!     ####################\n!\n!!****  *MODE_THERMO* -\n!!\n!!    PURPOSE\n!!    -------\n!\n!\n!!\n!!**  IMPLICIT ARGUMENTS\n!!    ------------------\n!!       NONE\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Ducrocq       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    28/08/94\n!!      Modified    01/2006 : sea flux parameterization.\n!!      B. Decharme 05/2013 : Qsat function of XTT\n!!                            so, Qsat=Qsati if Tg <= XTT and inversely\n!!      S. Belamari 03/2014 : new formula (QSAT_SEAWATER2) for sat. air pressure\n!!                            over seawater (with explicit salinity dependency)\n!!\n!--------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\n!-------------------------------------------------------------------------------\n!\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\nINTERFACE PSAT\n  MODULE PROCEDURE PSAT_0D\n  MODULE PROCEDURE PSAT_1D\n  MODULE PROCEDURE PSAT_2D\nEND INTERFACE\nINTERFACE DPSAT\n  MODULE PROCEDURE DPSAT_1D\nEND INTERFACE\n\nINTERFACE QSAT\n  MODULE PROCEDURE QSATW_0D\n  MODULE PROCEDURE QSATW_1D\n  MODULE PROCEDURE QSATW_2D\nEND INTERFACE\nINTERFACE QSAT_SEAWATER\n  MODULE PROCEDURE QSATSEAW_1D\nEND INTERFACE\nINTERFACE QSAT_SEAWATER2\n  MODULE PROCEDURE QSATSEAW2_1D\nEND INTERFACE\nINTERFACE DQSAT\n  MODULE PROCEDURE DQSATW_O_DT_1D\nEND INTERFACE\nINTERFACE QSATI\n  MODULE PROCEDURE QSATI_1D\n  MODULE PROCEDURE QSATI_2D\nEND INTERFACE\nINTERFACE DQSATI\n  MODULE PROCEDURE DQSATI_O_DT_1D\nEND INTERFACE\n CONTAINS\n!-------------------------------------------------------------------------------\n!     ######################################\n      FUNCTION PSAT_0D(PT) RESULT(PPSAT)\n!     ######################################\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!++ Trude, moved CQSAT to MODD_SNOW_PAR\n!USE MODD_REPROD_OPER, ONLY : CQSAT\nUSE MODD_SNOW_PAR\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, INTENT(IN)                :: PT     ! Temperature (Kelvin)\nREAL                            :: PPSAT  ! saturation vapor\n                                          ! specific humidity\n                                          ! with respect to\n                                          ! water (kg/kg)\n!\nREAL            :: ZALP, ZBETA, ZGAM\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE                                          \n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:PSAT_0D',0,ZHOOK_HANDLE)\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\n\nZALP  = XALPW\nZBETA = XBETAW\nZGAM  = XGAMW\n!\nIF(CQSAT=='NEW'.AND.PT<=XTT)THEN\n ZALP  = XALPI\n ZBETA = XBETAI\n ZGAM  = XGAMI\nENDIF\n!\nPPSAT = EXP( ZALP - ZBETA/PT - ZGAM*LOG(PT) )\n!\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:PSAT_0D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION PSAT_0D\n!-------------------------------------------------------------------------------\n!     ######################################\n      FUNCTION PSAT_1D(PT) RESULT(PPSAT)\n!     ######################################\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!++ Trude, moved CQSAT to MODD_SNOW_PAR\n!USE MODD_REPROD_OPER, ONLY : CQSAT\nUSE MODD_SNOW_PAR\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:), INTENT(IN)                :: PT     ! Temperature (Kelvin)\nREAL, DIMENSION(SIZE(PT))                     :: PPSAT  ! saturation vapor pressure (Pa)\n!\nREAL, DIMENSION(SIZE(PT))  :: ZALP, ZBETA, ZGAM\n!\nINTEGER                         :: JJ !loop index\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:PSAT_1D',0,ZHOOK_HANDLE)\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\n\nZALP (:) = XALPW\nZBETA(:) = XBETAW\nZGAM (:) = XGAMW\n!\nIF(CQSAT=='NEW')THEN\n WHERE(PT<=XTT)\n   ZALP  (:) = XALPI\n   ZBETA (:) = XBETAI\n   ZGAM  (:) = XGAMI\n ENDWHERE\nENDIF\n!\n!cdir nodep\nDO JJ=1,SIZE(PT)\n  PPSAT(JJ) = EXP( ZALP(JJ) - ZBETA(JJ)/PT(JJ) - ZGAM(JJ)*LOG(PT(JJ)) )\nENDDO\n!\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:PSAT_1D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION PSAT_1D\n!-------------------------------------------------------------------------------\n!     ######################################\n      FUNCTION PSAT_2D(PT,KMASK) RESULT(PPSAT)\n!     ######################################\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!++ Trude, moved CQSAT to MODD_SNOW_PAR\n!USE MODD_REPROD_OPER, ONLY : CQSAT\nUSE MODD_SNOW_PAR\n\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:,:), INTENT(IN)              :: PT     ! Temperature (Kelvin)\nINTEGER, DIMENSION(:), INTENT(IN)             :: KMASK\n!\nREAL, DIMENSION(SIZE(PT,1),SIZE(PT,2))        :: PPSAT  ! saturation vapor pressure (Pa)\n!\nREAL, DIMENSION(SIZE(PT,1),SIZE(PT,2))        :: ZALP, ZBETA, ZGAM\n!\nINTEGER         :: JJ, JL, INI, INL, IWORK !loop index\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:PSAT_2D',0,ZHOOK_HANDLE)\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\n\nINI=SIZE(PT,1)\nINL=SIZE(PT,2)\n!\nPPSAT(:,:) = 0.0\n!\nZALP (:,:) = XALPW\nZBETA(:,:) = XBETAW\nZGAM (:,:) = XGAMW\n!\nIF(CQSAT=='NEW')THEN\n WHERE(PT(:,:)<=XTT)\n   ZALP  (:,:) = XALPI\n   ZBETA (:,:) = XBETAI\n   ZGAM  (:,:) = XGAMI\n ENDWHERE\nENDIF\n!\nDO JL=1,INL\n  DO JJ=1,INI\n     IWORK=KMASK(JJ)\n     IF(JL<=IWORK)THEN\n       PPSAT(JJ,JL) = EXP( ZALP(JJ,JL) - ZBETA(JJ,JL)/PT(JJ,JL) - ZGAM(JJ,JL)*LOG(PT(JJ,JL)) )\n     ENDIF\n  ENDDO\nENDDO\n!\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:PSAT_2D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION PSAT_2D\n!-------------------------------------------------------------------------------\n!     ######################################\n      FUNCTION DPSAT_1D(PT) RESULT(PDPSAT)\n!     ######################################\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!++ Trude moved CQSAT to MODD_SNOW_PAR\n!USE MODD_REPROD_OPER, ONLY : CQSAT\nUSE MODD_SNOW_PAR\n!\nIMPLICIT NONE\n\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:), INTENT(IN) :: PT      ! Temperature (Kelvin)\n!\nREAL, DIMENSION(SIZE(PT))      :: PDPSAT\n!\nREAL, DIMENSION(SIZE(PT))      :: ZBETA, ZGAM\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:DPSAT_1D',0,ZHOOK_HANDLE)\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\n\nZBETA(:) = XBETAW\nZGAM (:) = XGAMW\n!\nIF(CQSAT=='NEW')THEN\n WHERE(PT<=XTT)\n   ZBETA (:) = XBETAI\n   ZGAM  (:) = XGAMI\n ENDWHERE\nENDIF\n!\nPDPSAT(:) = ZBETA(:)/PT(:)**2 - ZGAM(:)/PT(:)\n!\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:DPSAT_1D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION DPSAT_1D\n!-------------------------------------------------------------------------------\n!     ######################################\n      FUNCTION QSATW_0D(PT,PP) RESULT(PQSAT)\n!     ######################################\n!\n!!****  *QSATW * - function to compute saturation vapor humidity from\n!!                 temperature\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT), the saturation vapor pressure es(T)\n!!    (FOES(PT)) is computed by integration of the Clapeyron equation\n!!    from the triple point temperature Tt (XTT) and the saturation vapor \n!!    pressure of the triple point es(Tt) (XESTT), i.e\n!!\n!!         es(T)= EXP( alphaw - betaw /T - gammaw Log(T) )\n!!\n!!     with :\n!!       alphaw (XALPW) = LOG(es(Tt))+ betaw/Tt + gammaw Log(Tt)\n!!       betaw (XBETAW) = Lv(Tt)/Rv + gammaw Tt\n!!       gammaw (XGAMW) = (Cl -Cpv) /Rv\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : comtains physical constants\n!!        XALPW   : Constant for saturation vapor pressure function\n!!        XBETAW  : Constant for saturation vapor pressure function\n!!        XGAMW   : Constant for saturation vapor pressure function\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of documentation of Meso-NH\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Masson       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    21/09/98\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, INTENT(IN)                :: PT     ! Temperature (Kelvin)\nREAL, INTENT(IN)                :: PP     ! Pressure (Pa)\nREAL                            :: PQSAT  ! saturation vapor\n                                                        ! specific humidity\n                                                        ! with respect to\n                                                        ! water (kg/kg)\n!\n!*       0.2   Declarations of local variables\n!\nREAL                           :: ZFOES  ! saturation vapor\n                                                        ! pressure\n                                                        ! (Pascal)\n!\nREAL                           :: ZWORK1\nREAL                           :: ZWORK2\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATW_0D',0,ZHOOK_HANDLE)\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\nZFOES  = PSAT(PT)\nZWORK1 = ZFOES/PP\nZWORK2 = XRD/XRV\n!\n!*       2.    COMPUTE SATURATION HUMIDITY\n!              ---------------------------\n!\nPQSAT = ZWORK2*ZWORK1 / (1.+(ZWORK2-1.)*ZWORK1)\n!\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATW_0D',1,ZHOOK_HANDLE)\n!\nEND FUNCTION QSATW_0D\n!-------------------------------------------------------------------------------\n!\n!     ######################################\n      FUNCTION QSATW_1D(PT,PP) RESULT(PQSAT)\n!     ######################################\n!\n!!****  *QSATW * - function to compute saturation vapor humidity from\n!!                 temperature\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT), the saturation vapor pressure es(T)\n!!    (FOES(PT)) is computed by integration of the Clapeyron equation\n!!    from the triple point temperature Tt (XTT) and the saturation vapor \n!!    pressure of the triple point es(Tt) (XESTT), i.e\n!!\n!!         es(T)= EXP( alphaw - betaw /T - gammaw Log(T) )\n!!\n!!     with :\n!!       alphaw (XALPW) = LOG(es(Tt))+ betaw/Tt + gammaw Log(Tt)\n!!       betaw (XBETAW) = Lv(Tt)/Rv + gammaw Tt\n!!       gammaw (XGAMW) = (Cl -Cpv) /Rv\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : comtains physical constants\n!!        XALPW   : Constant for saturation vapor pressure function\n!!        XBETAW  : Constant for saturation vapor pressure function\n!!        XGAMW   : Constant for saturation vapor pressure function\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of documentation of Meso-NH\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Masson       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    21/09/98\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:), INTENT(IN)                :: PT     ! Temperature\n                                                        ! (Kelvin)\nREAL, DIMENSION(:), INTENT(IN)                :: PP     ! Pressure\n                                                        ! (Pa)\nREAL, DIMENSION(SIZE(PT))                   :: PQSAT  ! saturation vapor \n                                                        ! specific humidity\n                                                        ! with respect to\n                                                        ! water (kg/kg)\n!\n!*       0.2   Declarations of local variables\n!\nREAL, DIMENSION(SIZE(PT))                   :: ZFOES  ! saturation vapor \n                                                        ! pressure\n                                                        ! (Pascal)\n!\nREAL, DIMENSION(SIZE(PT))                   :: ZWORK1\nREAL                                        :: ZWORK2\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATW_1D',0,ZHOOK_HANDLE)\n!\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\nZFOES (:) = PSAT(PT(:))\nZWORK1(:) = ZFOES(:)/PP(:)\nZWORK2    = XRD/XRV\n!\n!*       2.    COMPUTE SATURATION HUMIDITY\n!              ---------------------------\n!\nPQSAT(:) = ZWORK2*ZWORK1(:) / (1.+(ZWORK2-1.)*ZWORK1(:))\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATW_1D',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION QSATW_1D\n!\n!-------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------\n!\n!     ######################################\n      FUNCTION QSATW_2D(PT,PP,KMASK,KL) RESULT(PQSAT)\n!     ######################################\n!\n!!****  *QSATW * - function to compute saturation vapor humidity from\n!!                 temperature\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT), the saturation vapor pressure es(T)\n!!    (FOES(PT)) is computed by integration of the Clapeyron equation\n!!    from the triple point temperature Tt (XTT) and the saturation vapor \n!!    pressure of the triple point es(Tt) (XESTT), i.e\n!!\n!!         es(T)= EXP( alphaw - betaw /T - gammaw Log(T) )\n!!\n!!     with :\n!!       alphaw (XALPW) = LOG(es(Tt))+ betaw/Tt + gammaw Log(Tt)\n!!       betaw (XBETAW) = Lv(Tt)/Rv + gammaw Tt\n!!       gammaw (XGAMW) = (Cl -Cpv) /Rv\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : comtains physical constants\n!!        XALPW   : Constant for saturation vapor pressure function\n!!        XBETAW  : Constant for saturation vapor pressure function\n!!        XGAMW   : Constant for saturation vapor pressure function\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of documentation of Meso-NH\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Masson       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    21/09/98\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_SNOW_PAR,  ONLY : XUNDEF\nUSE MODD_CSTS\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:,:), INTENT(IN)              :: PT     ! Temperature\n                                                        ! (Kelvin)\nREAL, DIMENSION(:,:), INTENT(IN)              :: PP     ! Pressure\n                                                        ! (Pa)\n!\nINTEGER, DIMENSION(:), INTENT(IN), OPTIONAL   :: KMASK\n!                                                KMASK = Number of soil moisture layers (DIF option)\nINTEGER,               INTENT(IN), OPTIONAL   :: KL\n!                                                KL = Max number of soil moisture layers (DIF option)\n!\nREAL, DIMENSION(SIZE(PT,1),SIZE(PT,2))        :: PQSAT  ! saturation vapor \n                                                        ! specific humidity\n                                                        ! with respect to\n                                                        ! water (kg/kg)\n!\n!*       0.2   Declarations of local variables\n!\nREAL, DIMENSION(SIZE(PT,1),SIZE(PT,2)) :: ZFOES\n!\nINTEGER, DIMENSION(SIZE(PT,1))         :: IMASK\n!\nINTEGER         :: INL\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATW_2D',0,ZHOOK_HANDLE)\n!\nIF(PRESENT(KMASK).AND.PRESENT(KL))THEN\n  IMASK(:)=KMASK(:)\n  INL=KL\nELSE\n  IMASK(:)=SIZE(PT,2)\n  INL=SIZE(PT,2)\nENDIF\n!\n\nPQSAT(:,:)=XUNDEF\nZFOES(:,:)=0.0\n!\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\nZFOES(:,1:INL) = PSAT(PT(:,1:INL),IMASK(:))\n!\n!*       2.    COMPUTE SATURATION HUMIDITY\n!              ---------------------------\n!\nPQSAT(:,:) = XRD/XRV*ZFOES(:,:)/PP(:,:) / (1.+(XRD/XRV-1.)*ZFOES(:,:)/PP(:,:))  \n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATW_2D',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION QSATW_2D\n!\n!-------------------------------------------------------------------------------\n!\n!-------------------------------------------------------------------------------\n!\n!     ######################################\n      FUNCTION QSATSEAW_1D(PT,PP) RESULT(PQSAT)\n!     ######################################\n!\n!!****  *QSATW * - function to compute saturation vapor humidity from\n!!                 temperature\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature over saline seawater\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT), the saturation vapor pressure es(T)\n!!    (FOES(PT)) is computed by integration of the Clapeyron equation\n!!    from the triple point temperature Tt (XTT) and the saturation vapor \n!!    pressure of the triple point es(Tt) (XESTT), i.e\n!!    The reduction due to salinity is compute with the factor 0.98 (reduction of 2%)\n!!\n!!         es(T)= 0.98*EXP( alphaw - betaw /T - gammaw Log(T) )\n!!\n!!     with :\n!!       alphaw (XALPW) = LOG(es(Tt))+ betaw/Tt + gammaw Log(Tt)\n!!       betaw (XBETAW) = Lv(Tt)/Rv + gammaw Tt\n!!       gammaw (XGAMW) = (Cl -Cpv) /Rv\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : comtains physical constants\n!!        XALPW   : Constant for saturation vapor pressure function\n!!        XBETAW  : Constant for saturation vapor pressure function\n!!        XGAMW   : Constant for saturation vapor pressure function\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of documentation of Meso-NH\n!!      Zeng, X., Zhao, M., and Dickinson, R. E., 1998 : Intercomparaison of bulk\n!!      aerodynamic algorithm for the computation of sea surface fluxes using\n!!      TOGA COARE and TAO data. Journal of Climate, vol 11, n10, pp 2628--2644\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      C. Lebeaupin    * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    6/04/2005\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:), INTENT(IN)                :: PT     ! Temperature\n                                                        ! (Kelvin)\nREAL, DIMENSION(:), INTENT(IN)                :: PP     ! Pressure\n                                                        ! (Pa)\nREAL, DIMENSION(SIZE(PT))                   :: PQSAT  ! saturation vapor \n                                                        ! specific humidity\n                                                        ! with respect to\n                                                        ! water (kg/kg)\n!\n!*       0.2   Declarations of local variables\n!\nREAL, DIMENSION(SIZE(PT))                   :: ZFOES  ! saturation vapor \n                                                        ! pressure\n                                                        ! (Pascal)\n!\nREAL, DIMENSION(SIZE(PT))                   :: ZWORK1\nREAL                                        :: ZWORK2\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATSEAW_1D',0,ZHOOK_HANDLE)\n!\nZFOES (:) = PSAT(PT(:))\nZFOES (:) = 0.98*ZFOES(:)\n! vapor pressure reduction of 2% over saline seawater could have a significant \n! impact on the computation of surface latent heat flux under strong wind \n! conditions (Zeng et al, 1998).\n!\nZWORK1(:) = ZFOES(:)/PP(:)\nZWORK2    = XRD/XRV\n!\n!*       2.    COMPUTE SATURATION HUMIDITY\n!              ---------------------------\n!\nPQSAT(:) = ZWORK2*ZWORK1(:) / (1.+(ZWORK2-1.)*ZWORK1(:))\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATSEAW_1D',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION QSATSEAW_1D\n!\n!-------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------\n!\n!     ######################################\n      FUNCTION QSATSEAW2_1D(PT,PP,PSSS) RESULT(PQSAT)\n!     ######################################\n!\n!!****  *QSATW * - function to compute saturation vapor humidity from\n!!                 temperature\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature over saline seawater\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT) and salinity S (PSSS), the saturation vapor \n!!    pressure es(T,S) (FOES(PT,PSSS)) is computed following Weiss and Price\n!!    (1980).\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : contains physical constants\n!!\n!!    REFERENCE\n!!    ---------\n!!      Weiss, R.F., and Price, B.A., 1980 : Nitrous oxide solubility in water\n!!      and seawater. Marine Chemistry, n8, pp 347-359.\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      S. Belamari     * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    19/03/2014\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS, ONLY : XRD, XRV\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:), INTENT(IN)                :: PT     ! Temperature\n                                                        ! (Kelvin)\nREAL, DIMENSION(:), INTENT(IN)                :: PP     ! Pressure\n                                                        ! (Pascal)\nREAL, DIMENSION(:), INTENT(IN)                :: PSSS   ! Salinity\n                                                        ! (g/kg)\nREAL, DIMENSION(SIZE(PT))                   :: PQSAT  ! saturation vapor\n                                                        ! specific humidity\n                                                        ! with respect to\n                                                        ! water (kg/kg)\n!\n!*       0.2   Declarations of local variables\n!\nREAL, DIMENSION(SIZE(PT))                   :: ZFOES  ! saturation vapor\n                                                        ! pressure\n                                                        ! (Pascal)\n!\nREAL, DIMENSION(SIZE(PT))                   :: ZWORK1\nREAL                                        :: ZWORK2\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATSEAW2_1D',0,ZHOOK_HANDLE)\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\nZFOES(:) = EXP( 24.4543 -67.4509*(100.0/PT(:)) -4.8489*LOG(PT(:)/100.0)   &\n                -5.44E-04*(PSSS(:)/1.00472) ) !see Sharqawy et al (2010) Eq32 p368\nZFOES(:) = ZFOES(:)*1013.25E+02             !convert from atm to Pa\n!\nZWORK1(:) = ZFOES(:)/PP(:)\nZWORK2    = XRD/XRV\n!\n!*       2.    COMPUTE SATURATION SPECIFIC HUMIDITY\n!              ------------------------------------\n!\nPQSAT(:) = ZWORK2*ZWORK1(:) / (1.0+(ZWORK2-1.0)*ZWORK1(:))\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATSEAW2_1D',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION QSATSEAW2_1D\n!\n!-------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------\n!     ##############################################################\n      FUNCTION DQSATW_O_DT_1D(PT,PP,PQSAT) RESULT(PDQSAT)\n!     ##############################################################\n!\n!!****  *QSATW * - function to compute saturation vapor humidity from\n!!                 temperature\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT), the saturation vapor pressure es(T)\n!!    (FOES(PT)) is computed by integration of the Clapeyron equation\n!!    from the triple point temperature Tt (XTT) and the saturation vapor \n!!    pressure of the triple point es(Tt) (XESTT), i.e\n!!\n!!         es(T)= EXP( alphaw - betaw /T - gammaw Log(T) )\n!!\n!!     with :\n!!       alphaw (XALPW) = LOG(es(Tt))+ betaw/Tt + gammaw Log(Tt)\n!!       betaw (XBETAW) = Lv(Tt)/Rv + gammaw Tt\n!!       gammaw (XGAMW) = (Cl -Cpv) /Rv\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!      Finally, dqsat / dT  (T) is computed.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : comtains physical constants\n!!        XALPW   : Constant for saturation vapor pressure function\n!!        XBETAW  : Constant for saturation vapor pressure function\n!!        XGAMW   : Constant for saturation vapor pressure function\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of documentation of Meso-NH\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Masson       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    21/09/98\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:),  INTENT(IN)             :: PT     ! Temperature\n                                                          ! (Kelvin)\nREAL, DIMENSION(:),  INTENT(IN)             :: PP     ! Pressure\n                                                          ! (Pa)\nREAL, DIMENSION(:),  INTENT(IN)             :: PQSAT  ! saturation vapor \n                                                          ! specific humidity\n                                                          ! with respect to\n                                                          ! water (kg/kg))\nREAL, DIMENSION(SIZE(PT))                   :: PDQSAT ! derivative according\n                                                          ! to temperature of\n                                                          ! saturation vapor \n                                                          ! specific humidity\n                                                          ! with respect to\n                                                          ! water (kg/kg))\n!\n!*       0.2   Declarations of local variables\n!\nREAL, DIMENSION(SIZE(PT))  :: ZFOES  ! saturation vapor\n                                                          ! pressure\n                                                          ! (Pascal)\n!\nREAL                       :: ZWORK1\nREAL, DIMENSION(SIZE(PT))  :: ZWORK2\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:DQSATW_O_DT_1D',0,ZHOOK_HANDLE)\n!\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\nZWORK1    = XRD/XRV\nZFOES (:) = PP(:) / (1.+ZWORK1*(1./PQSAT(:)-1.))\nZWORK2(:) = DPSAT(PT(:))\n!\n!*       2.    DERIVATION ACCORDING TO TEMPERATURE\n!              -----------------------------------\n!\nPDQSAT(:) = ZWORK2(:) * PQSAT(:) / (1.+(ZWORK1-1.)*ZFOES(:)/PP(:) )\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:DQSATW_O_DT_1D',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION DQSATW_O_DT_1D\n!\n!-------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------\n!     ##############################################################\n      FUNCTION DQSATI_O_DT_1D(PT,PP,PQSAT) RESULT(PDQSAT)\n!     ##############################################################\n!\n!!****  *QSATW * - function to compute saturation vapor humidity from\n!!                 temperature (with respect to ice)\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT), the saturation vapor pressure es(T)\n!!    (FOES(PT)) is computed by integration of the Clapeyron equation\n!!    from the triple point temperature Tt (XTT) and the saturation vapor \n!!    pressure of the triple point es(Tt) (XESTT), i.e\n!!\n!!         es(T)= EXP( alphaw - betaw /T - gammaw Log(T) )\n!!\n!!     with :\n!!       alphaw (XALPW) = LOG(es(Tt))+ betaw/Tt + gammaw Log(Tt)\n!!       betaw (XBETAW) = Lv(Tt)/Rv + gammaw Tt\n!!       gammaw (XGAMW) = (Cl -Cpv) /Rv\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!      Finally, dqsat / dT  (T) is computed.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : comtains physical constants\n!!        XALPW   : Constant for saturation vapor pressure function\n!!        XBETAW  : Constant for saturation vapor pressure function\n!!        XGAMW   : Constant for saturation vapor pressure function\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of documentation of Meso-NH\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Masson       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    21/09/98\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL,    DIMENSION(:), INTENT(IN)               :: PT     ! Temperature\n                                                          ! (Kelvin)\nREAL,    DIMENSION(:), INTENT(IN)               :: PP     ! Pressure\n                                                          ! (Pa)\nREAL,    DIMENSION(:), INTENT(IN)               :: PQSAT  ! saturation vapor \n                                                          ! specific humidity\n                                                          ! with respect to\n                                                          ! water (kg/kg))\nREAL,    DIMENSION(SIZE(PT))                    :: PDQSAT ! derivative according\n                                                          ! to temperature of\n                                                          ! saturation vapor \n                                                          ! specific humidity\n                                                          ! with respect to\n                                                          ! water (kg/kg))\n!\n!*       0.2   Declarations of local variables\n!\nREAL, DIMENSION(SIZE(PT))                       :: ZFOES  ! saturation vapor \n                                                          ! pressure\n                                                          ! (Pascal)\n!\nREAL                      :: ZWORK1\nREAL, DIMENSION(SIZE(PT)) :: ZWORK2\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:DQSATI_O_DT_1D',0,ZHOOK_HANDLE)\n!\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\nZWORK1    = XRD/XRV\nZFOES (:) = PP(:) / (1.+ZWORK1*(1./PQSAT(:)-1.))\nZWORK2(:) = DPSAT(PT(:))\n!\n!*       2.    DERIVATION ACCORDING TO TEMPERATURE\n!              -----------------------------------\n!\nPDQSAT(:) = ZWORK2(:) * PQSAT(:) / (1.+(ZWORK1-1.)*ZFOES(:)/PP(:) )\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:DQSATI_O_DT_1D',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION DQSATI_O_DT_1D\n!\n!-------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------\n!\n!     ######################################\n      FUNCTION QSATI_1D(PT,PP) RESULT(PQSAT)\n!     ######################################\n!\n!!****  *QSATI * - function to compute saturation vapor humidity from\n!!                 temperature\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT), the saturation vapor pressure es(T)\n!!    (FOES(PT)) is computed by integration of the Clapeyron equation\n!!    from the triple point temperature Tt (XTT) and the saturation vapor \n!!    pressure of the triple point es(Tt) (XESTT), i.e\n!!\n!!         es(T)= EXP( alphaw - betaw /T - gammaw Log(T) )\n!!\n!!     with :\n!!       alphaw (XALPI) = LOG(es(Tt))+ betaw/Tt + gammaw Log(Tt)\n!!       betaw (XBETAI) = Lv(Tt)/Rv + gammaw Tt\n!!       gammaw (XGAMI) = (Cl -Cpv) /Rv\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : comtains physical constants\n!!        XALPI   : Constant for saturation vapor pressure function\n!!        XBETAI  : Constant for saturation vapor pressure function\n!!        XGAMI   : Constant for saturation vapor pressure function\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of documentation of Meso-NH\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Masson       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    21/09/98\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_CSTS\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:), INTENT(IN)                :: PT     ! Temperature\n                                                        ! (Kelvin)\nREAL, DIMENSION(:), INTENT(IN)                :: PP     ! Pressure\n                                                        ! (Pa)\nREAL, DIMENSION(SIZE(PT))                   :: PQSAT  ! saturation vapor \n                                                        ! specific humidity\n                                                        ! with respect to\n                                                        ! water (kg/kg)\n!\n!*       0.2   Declarations of local variables\n!\nREAL, DIMENSION(SIZE(PT))                   :: ZFOES  ! saturation vapor \n                                                        ! pressure\n                                                        ! (Pascal)\n!\nREAL, DIMENSION(SIZE(PT))                   :: ZWORK1\nREAL                                        :: ZWORK2\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATI_1D',0,ZHOOK_HANDLE)\n!\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\nZFOES (:) = PSAT(PT(:))\nZWORK1(:) = ZFOES(:)/PP(:)\nZWORK2    = XRD/XRV\n!\n!*       2.    COMPUTE SATURATION HUMIDITY\n!              ---------------------------\n!\nPQSAT(:) = ZWORK2*ZWORK1(:) / (1.+(ZWORK2-1.)*ZWORK1(:))\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATI_1D',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION QSATI_1D\n!-------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------\n!\n!     ######################################\n      FUNCTION QSATI_2D(PT,PP,KMASK,KL) RESULT(PQSAT)\n!     ######################################\n!\n!!****  *QSATI * - function to compute saturation vapor humidity from\n!!                 temperature\n!!\n!!    PURPOSE\n!!    -------\n!       The purpose of this function is to compute the saturation vapor\n!     pressure from temperature\n!\n!\n!!**  METHOD\n!!    ------\n!!       Given temperature T (PT), the saturation vapor pressure es(T)\n!!    (FOES(PT)) is computed by integration of the Clapeyron equation\n!!    from the triple point temperature Tt (XTT) and the saturation vapor \n!!    pressure of the triple point es(Tt) (XESTT), i.e\n!!\n!!         es(T)= EXP( alphaw - betaw /T - gammaw Log(T) )\n!!\n!!     with :\n!!       alphaw (XALPI) = LOG(es(Tt))+ betaw/Tt + gammaw Log(Tt)\n!!       betaw (XBETAI) = Lv(Tt)/Rv + gammaw Tt\n!!       gammaw (XGAMI) = (Cl -Cpv) /Rv\n!!\n!!      Then, the specific humidity at saturation is deduced.\n!!\n!!\n!!    EXTERNAL\n!!    --------\n!!      NONE\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!      Module MODD_CST : comtains physical constants\n!!        XALPI   : Constant for saturation vapor pressure function\n!!        XBETAI  : Constant for saturation vapor pressure function\n!!        XGAMI   : Constant for saturation vapor pressure function\n!!\n!!    REFERENCE\n!!    ---------\n!!      Book2 of documentation of Meso-NH\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      V. Masson       * Meteo France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    21/09/98\n!-------------------------------------------------------------------------------\n!\n!*       0.    DECLARATIONS\n!              ------------\n!\nUSE MODD_SNOW_PAR,  ONLY : XUNDEF\nUSE MODD_CSTS\n!\nIMPLICIT NONE\n!\n!*       0.1   Declarations of arguments and results\n!\n!\nREAL, DIMENSION(:,:), INTENT(IN)            :: PT     ! Temperature\n                                                      ! (Kelvin)\nREAL, DIMENSION(:,:), INTENT(IN)            :: PP     ! Pressure\n                                                      ! (Pa)\n!\nINTEGER, DIMENSION(:), INTENT(IN), OPTIONAL   :: KMASK\n!                                                KMASK = Number of soil moisture layers (DIF option)\nINTEGER,               INTENT(IN), OPTIONAL   :: KL\n!                                                KL = Max number of soil moisture layers (DIF option)\n!\nREAL, DIMENSION(SIZE(PT,1),SIZE(PT,2))      :: PQSAT  ! saturation vapor \n                                                      ! specific humidity\n                                                      ! with respect to\n                                                      ! water (kg/kg)\n!\n!*       0.2   Declarations of local variables\n!\nREAL, DIMENSION(SIZE(PT,1),SIZE(PT,2))      :: ZFOES  ! saturation vapor pressure (Pascal) \n!\nINTEGER, DIMENSION(SIZE(PT,1)) :: IMASK\n!\nINTEGER         :: INL\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATI_2D',0,ZHOOK_HANDLE)\n!\nIF(PRESENT(KMASK))THEN\n  IMASK(:)=KMASK(:)\n  INL=KL\nELSE\n  IMASK(:)=SIZE(PT,2)\n  INL=SIZE(PT,2)\nENDIF\n!\nPQSAT(:,:)=XUNDEF\nZFOES(:,:)=0.0\n!\n!\n!*       1.    COMPUTE SATURATION VAPOR PRESSURE\n!              ---------------------------------\n!\nZFOES(:,1:INL) = PSAT(PT(:,1:INL),IMASK(:))\n!\n!*       2.    COMPUTE SATURATION HUMIDITY\n!              ---------------------------\n!\nPQSAT(:,:) = XRD/XRV*ZFOES(:,:)/PP(:,:) / (1.+(XRD/XRV-1.)*ZFOES(:,:)/PP(:,:))  \n!\n!IF (LHOOK) CALL DR_HOOK('MODE_THERMOS:QSATI_2D',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND FUNCTION QSATI_2D\n!-------------------------------------------------------------------------------\n!-------------------------------------------------------------------------------\nEND MODULE MODE_THERMOS\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/module_snowcro.F",
    "content": "MODULE MODULE_SNOWCRO\n\n!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt\n!SFX_LIC for details. version 1.\n\n\n!    ########\n! TRUDE: replace abort1 with exitroutines used in WRF\n! TRUDE: comment out all the debug statements. To run crodebug, we need to initalize this somewhere else and requires added links\n! in the initalizeion etc. I do not think we want to adde this in WRF-hydro.\n!\n\nCONTAINS\n\n!     ##########################################################################\n!      SUBROUTINE SNOWCRO(HSNOWRES, TPTIME, OGLACIER, HIMPLICIT_WIND,     &\n      SUBROUTINE SNOWCRO(HSNOWRES, OGLACIER, HIMPLICIT_WIND,     &\n               PPEW_A_COEF, PPEW_B_COEF,                                 &\n               PPET_A_COEF, PPEQ_A_COEF, PPET_B_COEF, PPEQ_B_COEF,       &\n               PSNOWSWE,PSNOWRHO,PSNOWHEAT,PSNOWALB,                     &\n               PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,PSNOWAGE,                 &\n               PTSTEP,PPS,PSR,PRR,PPSN3L,                                &\n               PTA,PTG,PSW_RAD,PQA,PVMOD,PLW_RAD, PRHOA,                 &\n               PUREF,PEXNS,PEXNA,PDIRCOSZW,                              &\n               PZREF,PZ0,PZ0EFF,PZ0H,PALB,                               &\n               PSOILCOND,PD_G,                                           &\n               PSNOWLIQ,PSNOWTEMP,PSNOWDZ,                               &\n               PTHRUFAL,PGRNDFLUX,PEVAPCOR,PRNSNOW,PHSNOW,PGFLUXSNOW,    &\n               PHPSNOW,PLES3L,PLEL3L,PEVAP,PSNDRIFT,PRI,                 &\n               PEMISNOW,PCDSNOW,PUSTAR,PCHSNOW,PSNOWHMASS,PQS,           &\n               PPERMSNOWFRAC,PZENITH,                                    &\n               OSNOWDRIFT,OSNOWDRIFT_SUBLIM,OSNOW_ABS_ZENITH,            &\n               HSNOWMETAMO,HSNOWRAD,                                     &\n               act_level, VIS_ICEALB,                                    &\n               PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS,                   &\n               FLOW_ICE, FLOW_SNOW,                                      &\n               I,J)                  !(OUT))\n!     ##########################################################################\n!\n!!****  *SNOWCRO*\n!!\n!!    PURPOSE\n!!    -------\n!\n!     Detailed snowpack scheme Crocus, computationnally based on the\n!     3-Layer snow scheme option (Boone and Etchevers 1999)\n!     For shallow snow cover, Default method of Douville et al. (1995)\n!     used with this option: Model \"turns on\" when snow sufficiently\n!     deep/above some preset critical snow depth.\n!\n!\n!\n!\n!!**  METHOD\n!!    ------\n!\n!     Direct calculation\n!\n!!    EXTERNAL\n!!    --------\n!\n!     None\n!!\n!!    IMPLICIT ARGUMENTS\n!!    ------------------\n!!\n!!\n!!\n!!    REFERENCE\n!!    ---------\n!!\n!!    ISBA: Belair (1995)\n!!    ISBA: Noilhan and Planton (1989)\n!!    ISBA: Noilhan and Mahfouf (1996)\n!!    ISBA-ES: Boone and Etchevers (2001)\n!!    Crocus : Brun et al., 1989 (J. Glaciol.)\n!!    Crocus : Brun et al., 1992 (J. Glaciol.)\n!!    Crocus : Vionnet et al., in prep (Geosci. Mod. Devel. Discuss.)\n!!\n!!\n!!    AUTHOR\n!!    ------\n!!      A. Boone           * Meteo-France *\n!!      V. Vionnet         * Meteo-France *\n!!      E. Brun            * Meteo-France *\n!!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original    7/99\n!!      Modified by A.Boone 05/02 (code, not physics)\n!!      Modified by A.Boone 11/04 i) maximum density limit imposed (although\n!!                                rarely if ever reached), ii) check to\n!!                                see if upermost layer completely sublimates\n!!                                during a timestep (as snowpack becomes vanishly\n!!                                thin), iii) impose maximum grain size limit\n!!                                in radiation transmission computation.\n!!\n!!      Modified by B. Decharme  (03/2009): Consistency with Arpege permanent\n!!                                          snow/ice treatment (LGLACIER for alb)\n!!      Modified by A. Boone     (04/2010): Implicit coupling and replace Qsat and DQsat\n!!                                          by Qsati and DQsati, respectively.\n!!      Modified by E. Brun, V. Vionnet, S. Morin (05/2011):\n!!                                          Addition of Crocus processes and\n!!                                          parametrizations to\n!!                                          the SNOW-3L code. This includes the dynamic handling\n!!                                          of snow layers and the inclusion of snow metamorphism\n!!                                          rules similar to the original Crocus implementation.\n!!      Modified by B. Decharme  (09/2012): New wind implicitation\n!!\n!!      Modified by M. Lafaysse (07/2012) :\n!!                                          * Albedo and roughness parametrizations\n!!                                            for surface ice over glaciers\n!!                                                     MODIF 2012-10-03 : don't modify roughness if implicit coupling\n!!                                                                 (test PPEW_A_COEF == 0. )\n!!                                          * SNOWCROALB is now called by SNOWCRORAD to remove duplicated code\n!!                                          * Parameters for albedo are moved to modd_snow_par\n!!                                          * PSNOWAGE is stored as an age\n!!                                            (days since snowfall) and not as a date\n!!                                            to allow spinup simulations\n!!                                          * New rules for optimal discretization of very thick snowpacks\n!!                                          * Optional outputs for debugging\n!!\n!!       Modified by E. Brun and M. Lafaysse (07/2012) :\n!!                                          * Implement sublimation in SNOWDRIFT\n!!                                          * Flag in namelist to activate SNOWDRIFT and SNOWDRIFT_SUBLIM\n!!       Modified by E. Brun and M. Lafaysse (08/2012) :\n!!                                          * XUEPSI replaced by 0 in the if statement of case 1.3.3.2 (SNOWCROMETAMO)\n!!                                          * If SNOWDRIFT is activated the wind do not modify grain types during snowfall\n!!                                            (redundant with snowdrift)\n!!       Modified by E. Brun (24/09/2012) :\n!!                                          * Correction coupling coefficient for specific humidity in SNOWCROEBUD\n!!                                          * PSFCFRZ(:)  = 1.0 for systematic solid/vapor latent fluxes in SNOWCROEBUD\n!!       Modified by C. Carmagnola (3/2013):\n!!                                          * Dendricity and size replaced by the optical diameter\n!!                                          * Test of different evolution laws for the optical diameter\n!!\n!!       Modified by B. Decharme  (08/2013): Qsat as argument (needed for coupling with atm)\n!!                                           add PSNDRIFT\n!!\n!!\n!-------------------------------------------------------------------------------\n!\n!*       0.     DECLARATIONS\n!               ------------\n!\n!USE MODD_TYPE_DATE_SURF, ONLY: DATE_TIME\n!\nUSE MODD_CSTS, ONLY : XTT, XRHOLW, XLMTT,XLSTT,XLVTT, XCL, XCI, XPI, XRHOLI,XZ0ICEZ0SNOW, XRHOTHRESHOLD_ICE\n!USE MODD_SNOW_PAR, ONLY : XZ0ICEZ0SNOW, XRHOTHRESHOLD_ICE\nUSE MODD_SNOW_METAMO    ! trude, declare these paramters at the beginning\n!USE MODD_CONST_TARTES, ONLY: NPNIMP, XPSNOWG0, XPSNOWY0, XPSNOWW0, XPSNOWB0\n!\nUSE MODE_SNOW3L\n!USE MODE_TARTES, ONLY : SNOWCRO_TARTES\n!\n!USE MODE_CRODEBUG\n!\n!USE MODI_ABOR1_SFX\n!\n!USE YOMHOOK   ,ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1  ,ONLY : JPRB\n!\n! this module is not used anymore\n! USE MODI_GREGODSTRATI\n\nuse ieee_arithmetic, only: isnan => ieee_is_nan\n\n!\nIMPLICIT NONE\n!\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                    :: PTSTEP\n!                                      PTSTEP    = time step of the integration\n!TYPE(DATE_TIME), INTENT(IN)         :: TPTIME      ! current date and time\n!\n CHARACTER(LEN=*), INTENT(IN)       :: HSNOWRES\n!                                      HSNOWRES  = ISBA-SNOW3L turbulant exchange option\n!                                      'DEF' = Default: Louis (ISBA: Noilhan and Mahfouf 1996)\n!                                      'RIL' = Limit Richarson number under very stable\n!                                              conditions (currently testing)\nLOGICAL, INTENT(IN)                 :: OGLACIER   ! True = Over permanent snow and ice,\n!                                                     initialise WGI=WSAT,\n!                                                     Hsnow>=10m and allow 0.8<SNOALB<0.85\n                                                  ! False = No specific treatment\n!\n CHARACTER(LEN=*), INTENT(IN)       :: HIMPLICIT_WIND   ! wind implicitation option\n!                                                     ! 'OLD' = direct\n!                                                     ! 'NEW' = Taylor serie, order 1\n!\n\n! trude added\n\nINTEGER, INTENT(IN)                      :: act_level\nINTEGER, INTENT(IN)                      :: I,J\nREAL, DIMENSION(:), INTENT(IN), OPTIONAL :: VIS_ICEALB\n!end trude\n\nREAL, DIMENSION(:), INTENT(IN)      :: PPS, PTA, PSW_RAD, PQA, PVMOD, PLW_RAD, PSR, PRR\n!                                      PSW_RAD = incoming solar radiation (W/m2)\n!                                      PLW_RAD = atmospheric infrared radiation (W/m2)\n!                                      PRR     = rain rate [kg/(m2 s)]\n!                                      PSR     = snow rate (SWE) [kg/(m2 s)]\n!                                      PTA     = atmospheric temperature at level za (K)\n!                                      PVMOD   = modulus of the wind parallel to the orography (m/s)\n!                                      trude; also called Wind Weighting factor (Liston and Elder 2006).\n!                                      trude; The terrain modified wind speed: Wt=PVMOD*wind_speed.\n!                                      trude; If slope is zero, (and ignoring curvature), then PVMOD=1\n!                                      PPS     = surface pressure\n!                                      PQA     = atmospheric specific humidity\n!                                                at level za\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PTG, PSOILCOND, PD_G, PPSN3L\n!                                      PTG       = Surface soil temperature (effective\n!                                                  temperature the of layer lying below snow)\n!                                      PSOILCOND = soil thermal conductivity [W/(m K)]\n!                                      PD_G      = Assumed first soil layer thickness (m)\n!                                                  Used to calculate ground/snow heat flux\n!                                      PPSN3L    = snow fraction\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PZREF, PUREF, PEXNS, PEXNA, PDIRCOSZW, PRHOA, PZ0, PZ0EFF, &\n                                       PALB, PZ0H, PPERMSNOWFRAC\n!                                      PZ0EFF    = roughness length for momentum\n!                                      PZ0       = grid box average roughness length\n!                                      PZ0H      = grid box average roughness length for heat\n!                                      PZREF     = reference height of the first\n!                                                  atmospheric level\n!                                      PUREF     = reference height of the wind\n!                                      PRHOA     = air density\n!                                      PEXNS     = Exner function at surface\n!                                      PEXNA     = Exner function at lowest atmos level\n!                                      PDIRCOSZW = Cosinus of the angle between the\n!                                                  normal to the surface and the vertical\n!                                      PALB      = soil/vegetation albedo\n!                                      PPERMSNOWFRAC  = fraction of permanet snow/ice\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PPEW_A_COEF, PPEW_B_COEF,                   &\n                                        PPET_A_COEF, PPEQ_A_COEF, PPET_B_COEF,      &\n                                        PPEQ_B_COEF\n!                                      PPEW_A_COEF = wind coefficient (m2s/kg)\n!                                      PPEW_B_COEF = wind coefficient (m/s)\n!                                      PPET_A_COEF = A-air temperature coefficient\n!                                      PPET_B_COEF = B-air temperature coefficient\n!                                      PPEQ_A_COEF = A-air specific humidity coefficient\n!                                      PPEQ_B_COEF = B-air specific humidity coefficient\n!\nREAL, DIMENSION(:), INTENT(INOUT)   :: PSNOWALB\n!                                      PSNOWALB = Prognostic surface snow albedo\n!                                                 (does not include anything but\n!                                                 the actual snow cover)\n!\n!REAL, DIMENSION(:,:), INTENT(INOUT)  :: PSNOWHEAT, PSNOWRHO, PSNOWSWE\nREAL, DIMENSION(:,:), INTENT(INOUT)  :: PSNOWHEAT, PSNOWRHO, PSNOWSWE\n!                                      PSNOWHEAT = Snow layer(s) heat content (J/m2)\n!                                      PSNOWRHO  = Snow layer(s) averaged density (kg/m3)\n!                                      PSNOWSWE  = Snow layer(s) liquid Water Equivalent (SWE:kg m-2)\n!\nREAL, DIMENSION(:,:), INTENT(INOUT)  :: PSNOWGRAN1, PSNOWGRAN2, PSNOWHIST\n!                                      PSNOWGRAN1 = Snow layers grain feature 1\n!                                      PSNOWGRAN2 = Snow layer grain feature 2\n!                                      PSNOWHIST  = Snow layer grain historical\n!                                                   parameter (only for non\n!                                                   dendritic snow)\nREAL, DIMENSION(:,:), INTENT(INOUT)  :: PSNOWAGE  ! Snow grain age\n!\nREAL, DIMENSION(:,:), INTENT(OUT)    :: PSNOWLIQ, PSNOWTEMP, PSNOWDZ\n!                                      PSNOWLIQ  = Snow layer(s) liquid water content (m)\n!                                      PSNOWTEMP = Snow layer(s) temperature (m)\n!                                      PSNOWDZ   = Snow layer(s) thickness (m)\n!\nREAL, DIMENSION(:), INTENT(OUT)      :: PTHRUFAL, PGRNDFLUX, PEVAPCOR\n!                                      PTHRUFAL  = rate that liquid water leaves snow pack:\n!                                                  paritioned into soil infiltration/runoff\n!                                                  by ISBA [kg/(m2 s)]\n!                                      PGRNDFLUX = soil/snow interface heat flux (W/m2)\n!                                      PEVAPCOR  = evaporation/sublimation correction term:\n!                                                  extract any evaporation exceeding the\n!                                                  actual snow cover (as snow vanishes)\n!                                                  and apply it as a surface soil water\n!                                                  sink. [kg/(m2 s)]\n! ++ trude\nREAL, DIMENSION(:), INTENT(OUT)    :: FLOW_ICE,FLOW_SNOW\n! -- trude\n!\nREAL, DIMENSION(:), INTENT(OUT)      :: PRNSNOW, PHSNOW, PGFLUXSNOW, PLES3L, PLEL3L, &\n                                        PHPSNOW, PCDSNOW, PUSTAR, PEVAP, PSNDRIFT\n!                                      PLES3L      = evaporation heat flux from snow (W/m2)\n!                                      PLEL3L      = sublimation (W/m2)\n!                                      PHPSNOW     = heat release from rainfall (W/m2)\n!                                      PRNSNOW     = net radiative flux from snow (W/m2)\n!                                      PHSNOW      = sensible heat flux from snow (W/m2)\n!                                      PGFLUXSNOW  = net heat flux from snow (W/m2)\n!                                      PCDSNOW     = drag coefficient for momentum over snow\n!                                      PUSTAR      = friction velocity over snow (m/s)\n!                                      PEVAP       = total evaporative flux (kg/m2/s)\n!                                      PSNDRIFT    = blowing snow sublimation (kg/m2/s)\n!\nREAL, DIMENSION(:), INTENT(OUT)      :: PCHSNOW, PEMISNOW, PSNOWHMASS\n!                                      PEMISNOW    = snow surface emissivity\n!                                      PCHSNOW     = drag coefficient for heat over snow\n!                                      PSNOWHMASS  = heat content change due to mass\n!                                                    changes in snowpack (J/m2): for budget\n!                                                    calculations only.\n!\n!Fluxes\nREAL, DIMENSION(:), INTENT(OUT)      :: PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS\n\n\n\nREAL, DIMENSION(:), INTENT(OUT)      :: PRI, PQS\n!                                      PRI = Ridcharson number\n!                                      PQS = surface humidity\n!\nREAL, DIMENSION(:), INTENT(IN)        :: PZENITH ! solar zenith angle\n!\nLOGICAL, INTENT(IN)                   :: OSNOWDRIFT, OSNOWDRIFT_SUBLIM ! activate snowdrift, sublimation during drift\nLOGICAL, INTENT(IN)                   :: OSNOW_ABS_ZENITH ! activate parametrization of solar absorption for polar regions\n CHARACTER(3), INTENT(IN)              :: HSNOWMETAMO, HSNOWRAD\n\n\n                                         !-----------------------\n                                         ! Metamorphism scheme\n                                         ! HSNOWMETAMO=B92 Brun et al 1992\n                                         ! HSNOWMETAMO=C13 Carmagnola et al 2014\n                                         ! HSNOWMETAMO=T07 Taillandier et al 2007\n                                         ! HSNOWMETAMO=F06 Flanner et al 2006\n                                         !-----------------------\n                                         ! Radiative transfer scheme\n                                         ! HSNOWRAD=B92 Brun et al 1992\n                                         ! HSNOWRAD=TAR TARTES (Libois et al 2013)\n                                         ! HSNOWRAD=TA1 TARTES with constant impurities\n                                         ! HSNOWRAD=TA2 TARTES with constant impurities as function of ageing\n                                         !-----------------------\n!*      0.2    declarations of local variables\n!\n!REAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2),NPNIMP) :: ZSNOWIMP_DENSITY !impurities density (kg/m^3) (npoints,nlayer,ntypes_impurities)\n!REAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2),NPNIMP) :: ZSNOWIMP_CONTENT !impurities content (g/g) (npoints,nlayer,ntypes_impurities)\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSNOWTEMP, ZSCAP, ZSNOWDZN, ZSCOND, ZRADSINK\n!                                      ZSNOWTEMP  = Snow layer(s) averaged temperature (K)\n!                                      ZSCAP      = Snow layer(s) heat capacity [J/(K m3)]\n!                                      ZSNOWDZN   = Updated snow layer thicknesses (m)\n!                                      ZSCOND     = Snow layer(s) thermal conducivity [W/(m K)]\n!                                      ZRADSINK   = Snow solar Radiation source terms (W/m2)\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZWHOLDMAX\n!\n!For now these values are constant\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSNOWG0 ! asymmetry parameter of snow grains at nr=1.3 and at non absorbing wavelengths (no unit) (npoints,nlayer)\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSNOWY0 ! Value of y of snow grains at nr=1.3 (no unit\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSNOWW0 ! Value of W of snow grains at nr=1.3 (no unit)\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSNOWB0 ! absorption enhancement parameter of snow grains at nr=1.3 and at non absorbing wavelengths (no unit)\n!\n!spectral albedo (3 bands for now) :: ready to output if necessary\nREAL, DIMENSION(SIZE(PSNOWRHO,1),3) :: ZSPECTRALALBEDO\n\n!------------------\n!  trude start changing some dimensions declaration\n!REAL, DIMENSION(SIZE(PSNOWRHO,1),NPNIMP) :: ZSNOWIMP_DENSITY !impurities density (kg/m^3) (npoints,nlayer,ntypes_impurities)\n!REAL, DIMENSION(SIZE(PSNOWRHO,1),NPNIMP) :: ZSNOWIMP_CONTENT !impurities content (g/g) (npoints,nlayer,ntypes_impurities)\n!\n!REAL, DIMENSION(SIZE(PSNOWRHO,1)) :: ZSNOWTEMP, ZSCAP, ZSNOWDZN, ZSCOND, ZRADSINK\n!                                      ZSNOWTEMP  = Snow layer(s) averaged temperature (K)\n!                                      ZSCAP      = Snow layer(s) heat capacity [J/(K m3)]\n!                                      ZSNOWDZN   = Updated snow layer thicknesses (m)\n!                                      ZSCOND     = Snow layer(s) thermal conducivity [W/(m K)]\n!                                      ZRADSINK   = Snow solar Radiation source terms (W/m2)\n!\n!REAL, DIMENSION(SIZE(PSNOWRHO,1)) :: ZWHOLDMAX\n!\n!For now these values are constant\n!REAL, DIMENSION(SIZE(PSNOWRHO,1)) :: ZSNOWG0 ! asymmetry parameter of snow grains at nr=1.3 and at non absorbing wavelengths (no unit) (npoints,nlayer)\n!REAL, DIMENSION(SIZE(PSNOWRHO,1)) :: ZSNOWY0 ! Value of y of snow grains at nr=1.3 (no unit\n!REAL, DIMENSION(SIZE(PSNOWRHO,1)) :: ZSNOWW0 ! Value of W of snow grains at nr=1.3 (no unit)\n!REAL, DIMENSION(SIZE(PSNOWRHO,1)) :: ZSNOWB0 ! absorption enhancement parameter of snow grains at nr=1.3 and at non absorbing wavelengths (no unit)\n!\n!spectral albedo (3 bands for now) :: ready to output if necessary\n!REAL, DIMENSION(SIZE(PSNOWRHO,1),3) :: ZSPECTRALALBEDO\n\n! end trude\n!\n\n\n!\nREAL, DIMENSION(SIZE(PTA))          :: ZSNOWBIS\n!                                     ZSNOWBIS      = Total snow depth after snowfall\n!\nREAL, DIMENSION(SIZE(PTA))          :: ZSNOW, ZSFCFRZ, ZTSTERM1, ZTSTERM2, ZCT, ZRA, ZSNOWFLUX, ZSNOWTEMPO1\n!                                      ZSNOW      = Total snow depth (m)\n!                                      ZCT        = inverse of the product of snow heat capacity\n!                                                   and layer thickness [(m2 K)/J]\n!                                      ZRA        = Surface aerodynamic resistance\n!                                      ZTSTERM1,ZTSTERM2 = Surface energy budget coefficients\n!                                      ZSNOWFLUX  = heat flux between 1st and 2nd snow layers:\n!                                                   used during surface melting (W/m2)\n!                                      ZSNOWTEMPO1= value of uppermost snow temperature\n!                                                   before time integration (K)\n!\nREAL, DIMENSION(SIZE(PTA))          :: ZRSRA, ZDQSAT, ZQSAT, ZRADXS, ZLIQHEATXS, ZLWUPSNOW\n!                                      ZRSRA    = air density over aerodynamic resistance\n!                                      ZDQSAT   = derrivative of saturation specific humidity\n!                                      ZQSAT    = saturation specific humidity\n!                                      ZRADXS   = shortwave radiation absorbed by soil surface\n!                                                 (for thin snow sover) (W m-2)\n!                                      ZLIQHEATXS = excess snowpack heating for vanishingly thin\n!                                                 snow cover: add energy to snow/ground heat\n!                                                 flux (W m-2)\n!                                      ZLWUPSNOW = upwelling longwave raaditive flux (W m-2)\n!\nREAL, DIMENSION(SIZE(PTA))          :: ZUSTAR2_IC, ZTA_IC, ZQA_IC, &\n                                       ZPET_A_COEF_T, ZPEQ_A_COEF_T, ZPET_B_COEF_T, ZPEQ_B_COEF_T\n!                                      ZUSTAR2_IC    = implicit lowest atmospheric level friction (m2/s2)\n!                                      ZTA_IC        = implicit lowest atmospheric level air temperature\n!                                      ZQA_IC        = implicit lowest atmospheric level specific humidity\n!                                      ZPET_A_COEF_T = transformed A-air temperature coefficient\n!                                      ZPET_B_COEF_T = transformed B-air temperature coefficient\n!                                      ZPEQ_A_COEF_T = transformed A-air specific humidity coefficient\n!                                      ZPEQ_B_COEF_T = transformed B-air specific humidity coefficient\n!\nREAL, DIMENSION(SIZE(PTA))          :: ZSNOWRHOF, ZSNOWDZF, ZSNOWGRAN1F, ZSNOWGRAN2F, ZSNOWHISTF\nREAL, DIMENSION(SIZE(PTA))          :: ZSNOWAGEF\n\n! New roughness lengths in case of glaciers without snow.\nREAL, DIMENSION(SIZE(PTA))          :: ZZ0_SNOWICE, ZZ0H_SNOWICE, ZZ0EFF_SNOWICE\n!\n!To control and print eneregy balance\nREAL , DIMENSION(SIZE(PTA))         :: ZSUMMASS_INI,ZSUMHEAT_INI,ZSUMMASS_FIN,ZSUMHEAT_FIN\n!\nREAL, DIMENSION(SIZE(PTA))          :: ZMASSBALANCE, ZENERGYBALANCE, ZEVAPCOR2\n!\nINTEGER, DIMENSION(SIZE(PTA))       :: INLVLS_USE ! varying number of effective layers\n!\nLOGICAL, DIMENSION(SIZE(PTA))       :: GSNOWFALL,GMODIF_MAILLAGE\n!                                      GSNOWFALL  = FLAG if snowfall exceed PSNOW/10, used for\n!                                                   grid updating.\n!\nREAL :: ZTSTEPDAYS ! time step in days\n!\nLOGICAL :: GCOND_GRAIN, GCOND_YEN\n!\n!LOGICAL :: GCROINFOPRINT ! print daily informations\n!LOGICAL :: GCRODEBUGPRINT, GCRODEBUGDETAILSPRINT, GCRODEBUGPRINTATM ! print diagnostics for debugging\n!LOGICAL :: GCRODEBUGPRINTBALANCE\n!\nINTEGER :: JJ,JST  ! looping indexes\nINTEGER :: IPRINT  ! gridpoint number to be printed\nINTEGER :: IDEBUG\n!\n\n\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\nPFSA_CROCUS(:) = 0\nPFSR_CROCUS(:) = 0\nPFIRA_CROCUS(:) = 0\nPTHRUFAL(:)   = 0.\nFLOW_SNOW(:)   = 0.\nFLOW_ICE(:)   = 0.\n!\nZUSTAR2_IC = 0.0\nZTA_IC     = 0.0\nZQA_IC     = 0.0\n!\nGCOND_GRAIN = .TRUE.\nGCOND_YEN   = .TRUE.!FALSE. !(if TRUE : use of the Yen (1981) thermal conductivity paramztrization ;\n!                    otherwise, use the default ISBA-ES thermal conductivity parametrization)\n!\nPGRNDFLUX  = 0.\nPSNOWHMASS = 0.\nPHSNOW     = 0.\nPRNSNOW    = 0.\nPLES3L     = 0.\nPLEL3L     = 0.\nPHPSNOW    = 0.\nPEVAPCOR   = 0.\nPTHRUFAL   = 0.\n!\n! pour imprimer des diagnostics sur un des points\nIPRINT = 1\n!\n! - - ---------------------------------------------------\n!\n!       0.     Initialization\n!               --------------\n! NOTE that snow layer thickness is used throughout this code: SWE\n! is only used to diagnose the thickness at the beginning of this routine\n! and it is updated at the end of this routine.\n!\n! Initialization of the actual number of snow layers, total snow depth\n!  and layer thicknesses\n!\nZSNOWTEMP(:,:) = 0.\n!\nGSNOWFALL(:) = .FALSE.\nINLVLS_USE(:) = 0\n DO JST = 1,SIZE(PSNOWSWE(:,:),2)\n  DO JJ = 1,SIZE(ZSNOW)\n    IF ( PSNOWSWE(JJ,JST)>0. ) THEN\n      PSNOWDZ(JJ,JST) = PSNOWSWE(JJ,JST) / PSNOWRHO(JJ,JST)\n      INLVLS_USE(JJ) = JST\n    ELSE\n      PSNOWDZ(JJ,JST) = 0.\n    ENDIF\n  ENDDO  !  end loop snow layers\nENDDO    ! end loop grid points\n\n\n! Incrementation of snow layers age\nZTSTEPDAYS = PTSTEP/86400. ! time step in days\nWHERE ( PSNOWSWE>0 ) PSNOWAGE = PSNOWAGE + ZTSTEPDAYS\n!\n!***************************************PRINT IN**********************************************\n!\n!Compute total SWE and heat for energy control\n!IF ( GCRODEBUGPRINTBALANCE ) THEN\n!  DO JJ = 1,SIZE(ZSNOW)\n!    ZSUMMASS_INI(JJ) = SUM(PSNOWSWE (JJ,1:INLVLS_USE(JJ)))\n!    ZSUMHEAT_INI(JJ) = SUM(PSNOWHEAT(JJ,1:INLVLS_USE(JJ)))\n!  ENDDO    ! end loop grid points!\n!ENDIF\n!\n!  Print of some simulation characteristics\n!IF(GCROINFOPRINT) THEN\n!  CALL SNOWCROPRINTDATE()\n! WRITE(*,FMT=\"(A12,I3,A12,I4)\") 'nlayer:',INLVLS_USE(IDEBUG), ' nbpoints:', SIZE(ZSNOW)\n!   WRITE(*,*) 'PZ0H: ', PZ0H(IDEBUG)\n!  WRITE(*,*) 'Snow fraction =',PPSN3L(IDEBUG)\n!ENDIF\n!\n!***************************************PRINT OUT*********************************************\n!***************************************DEBUG IN**********************************************\n\n!IF (GCRODEBUGPRINT) THEN\n!  CALL SNOWCROPRINTDATE()\n!  CALL SNOWCROPRINTPROFILE(\"crocus initialization\",INLVLS_USE(IDEBUG),LPRINTGRAN,      &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),   &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),&\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),&\n!                           HSNOWMETAMO)\n!END IF\n!\n!IF (GCRODEBUGPRINTATM) THEN\n!  CALL SNOWCROPRINTATM(\"forcing data :\",PTA(IDEBUG),PQA(IDEBUG),PVMOD(IDEBUG),   &\n!                       PRR(IDEBUG),PSR(IDEBUG),PSW_RAD(IDEBUG),PLW_RAD(IDEBUG),  &\n!                       PTG(IDEBUG),PSOILCOND(IDEBUG),PD_G(IDEBUG),PPSN3L(IDEBUG) )\n!END IF\n!***************************************DEBUG OUT********************************************\n!\n!*       1.     Snow total depth\n!               ----------------\n!\nZSNOW(:) = 0.\nDO JJ = 1,SIZE(ZSNOW)\n  ZSNOW(JJ) = SUM(PSNOWDZ(JJ,1:INLVLS_USE(JJ)))\nENDDO\n!\nZSNOWBIS(:) = ZSNOW(:)\n!\n!*       2.     Snowfall\n!               --------\n! Calculate uppermost density and thickness changes due to snowfall,\n! and add heat content of falling snow\n!\n\n CALL SNOWNLFALL_UPGRID(OGLACIER,                                       &\n                        PTSTEP,PSR,PTA,PVMOD,ZSNOWBIS,PSNOWRHO,PSNOWDZ,         &\n                        PSNOWHEAT,PSNOWHMASS,PSNOWALB,PPERMSNOWFRAC,            &\n                        PSNOWGRAN1,PSNOWGRAN2,GSNOWFALL,ZSNOWDZN,               &\n                        ZSNOWRHOF,ZSNOWDZF,ZSNOWGRAN1F,ZSNOWGRAN2F, ZSNOWHISTF, &\n                        ZSNOWAGEF,GMODIF_MAILLAGE,INLVLS_USE,OSNOWDRIFT,PZ0EFF,PUREF,&\n                        HSNOWMETAMO)\n\n\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWFALL_UPGRID\",INLVLS_USE(IDEBUG),LPRINTGRAN,      &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),   &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),&\n!                          PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),&\n!                           HSNOWMETAMO )\n!ENDIF\n!***************************************DEBUG OUT**********************************************\n!\nZSNOW(:) = ZSNOWBIS(:)\n!\n!*       3.     Update grid/discretization\n!               --------------------------\n! Reset grid to conform to model specifications:\n!\nDO JJ=1,SIZE(ZSNOW)\n!\n  IF ( GMODIF_MAILLAGE(JJ) ) THEN\n\n\n    CALL SNOWNLGRIDFRESH_1D(JJ,ZSNOW(JJ),PSNOWDZ(JJ,:),ZSNOWDZN(JJ,:),PSNOWRHO(JJ,:),    &\n                            PSNOWHEAT(JJ,:),PSNOWGRAN1(JJ,:),PSNOWGRAN2(JJ,:),           &\n                            PSNOWHIST(JJ,:),PSNOWAGE(JJ,:),GSNOWFALL(JJ),ZSNOWRHOF(JJ),  &\n                            ZSNOWDZF(JJ),PSNOWHMASS(JJ),ZSNOWGRAN1F(JJ),ZSNOWGRAN2F(JJ), &\n                            ZSNOWHISTF(JJ),ZSNOWAGEF(JJ),INLVLS_USE(JJ),HSNOWMETAMO, I, J      )\n\n  ENDIF\n  !\n\n\nENDDO\n\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWNLGRIDFRESH_1D\",INLVLS_USE(IDEBUG),LPRINTGRAN,   &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),   &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),&\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),&\n!                           HSNOWMETAMO )\n!ENDIF\n!***************************************DEBUG OUT**********************************************\n!\n!*       4.     Liquid water content and snow temperature\n!               -----------------------------------------\n!\n! First diagnose snow temperatures and liquid\n! water portion of the snow from snow heat content:\n! update some snow layers parameters after new discretization\n!\nDO JJ = 1,SIZE(ZSNOW)\n  !\n  ! active layers\n  DO JST=1,INLVLS_USE(JJ)\n    PSNOWSWE (JJ,JST) = PSNOWDZ(JJ,JST) * PSNOWRHO(JJ,JST)\n    ZSCAP    (JJ,JST) = PSNOWRHO(JJ,JST) * XCI\n    ZSNOWTEMP(JJ,JST) = XTT + &\n                        ( ( PSNOWHEAT(JJ,JST)/PSNOWDZ(JJ,JST) + XLMTT*PSNOWRHO(JJ,JST) )/ZSCAP(JJ,JST) )\n!\n    PSNOWLIQ (JJ,JST) = MAX( 0.0, ZSNOWTEMP(JJ,JST)-XTT ) * ZSCAP(JJ,JST) * &\n                        PSNOWDZ(JJ,JST) / (XLMTT*XRHOLW)\n!\n    ZSNOWTEMP(JJ,JST) = MIN( XTT, ZSNOWTEMP(JJ,JST) )\n  ENDDO  !  end loop active snow layers\n\n  !\n  ! unactive layers\n  DO JST = INLVLS_USE(JJ)+1,SIZE(PSNOWSWE,2)\n    PSNOWSWE  (JJ,JST) = 0.0\n    PSNOWRHO  (JJ,JST) = 999.\n    PSNOWDZ   (JJ,JST) = 0.\n    PSNOWGRAN1(JJ,JST) = 0.\n    PSNOWGRAN2(JJ,JST) = 0.\n    PSNOWHIST (JJ,JST) = 0.\n    PSNOWAGE  (JJ,JST) = 0.\n    PSNOWHEAT (JJ,JST) = 0.\n    ZSNOWTEMP (JJ,JST) = XTT\n    PSNOWLIQ  (JJ,JST) = 0.\n  ENDDO  !  end loop unactive snow layers\n  !\nENDDO    ! end loop grid points\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after liquid water/temperature diagnostic\",                &\n!                           INLVLS_USE(IDEBUG),LPRINTGRAN,                              &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),   &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),&\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),&\n!                           HSNOWMETAMO )\n!ENDIF\n!***************************************DEBUG OUT**********************************************\n!\n!        4.BIS   Snow metamorphism\n!                -----------------\n!\n CALL SNOWCROMETAMO(PSNOWDZ,PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,ZSNOWTEMP, &\n                    PSNOWLIQ,PTSTEP,PSNOWSWE,INLVLS_USE,PSNOWAGE,HSNOWMETAMO       )\n\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROMETAMO\", INLVLS_USE(IDEBUG),LPRINTGRAN,       &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),   &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),&\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),&\n!                           HSNOWMETAMO )\n!ENDIF\n!***************************************DEBUG OUT**********************************************\n!\n!*       5.     Snow Compaction\n!               ---------------\n! Calculate snow density: compaction/aging: density increases\n!\n\n CALL SNOWCROCOMPACTN(PTSTEP,PSNOWRHO,PSNOWDZ,ZSNOWTEMP,ZSNOW,                      &\n                      PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,PSNOWLIQ,INLVLS_USE,PDIRCOSZW,&\n                      HSNOWMETAMO)\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROCOMPACTN\", INLVLS_USE(IDEBUG),LPRINTGRAN,     &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),   &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),&\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),&\n!                           HSNOWMETAMO )\n!ENDIF\n!***************************************DEBUG OUT**********************************************\n!\n!*       5.1    Snow Compaction and Metamorphism due to snow drift\n!               ---------------\nPSNDRIFT(:) = 0.0\nIF (OSNOWDRIFT) THEN\n\n  CALL SNOWDRIFT(PTSTEP, PVMOD, PSNOWRHO,PSNOWDZ, ZSNOW,                      &\n                 PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,INLVLS_USE,PTA,PQA,PPS,PRHOA,&\n                 PZ0EFF,PUREF,OSNOWDRIFT_SUBLIM,HSNOWMETAMO,PSNDRIFT)\n\nENDIF\n\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWDRIFT\", INLVLS_USE(IDEBUG),LPRINTGRAN,           &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),   &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),&\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),&\n!                           HSNOWMETAMO )\n!ENDIF\n!***************************************DEBUG OUT**********************************************\n!\n! Update snow heat content (J/m2) using dry density instead of total density:\n!\nDO JJ = 1,SIZE(ZSNOW)\n  DO JST = 1,INLVLS_USE(JJ)\n    ZSCAP(JJ,JST) = ( PSNOWRHO(JJ,JST) - &\n                      PSNOWLIQ(JJ,JST) * XRHOLW / MAX( PSNOWDZ(JJ,JST),XSNOWDZMIN) ) * XCI\n    PSNOWHEAT(JJ,JST) = PSNOWDZ(JJ,JST) * &\n                        ( ZSCAP(JJ,JST)*(ZSNOWTEMP(JJ,JST)-XTT) - XLMTT*PSNOWRHO(JJ,JST) ) + &\n                        XLMTT * XRHOLW * PSNOWLIQ(JJ,JST)\n ENDDO  !  end loop snow layers\nENDDO    ! end loop grid points\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after  update snow heat content\", INLVLS_USE(IDEBUG),LPRINTGRAN,&\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO      )\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n!*       6.     Solar radiation transmission\n!               -----------------------------\n!\n! Heat source (-sink) term due to shortwave\n! radiation transmission within the snowpack:\n!\nSELECT CASE (HSNOWRAD)\n!  CASE (\"TA1\")\n!    ZSNOWIMP_CONTENT(:,:,1) = 0.0\n!  CASE (\"TA2\")\n!    ZSNOWIMP_CONTENT(:,:,1) = 100.0E-9\n!  CASE (\"TAR\")\n!    ZSNOWIMP_CONTENT(:,:,1) = 2. * PSNOWAGE(:,:) * 1E-9\n  CASE DEFAULT\nEND SELECT\n!\nSELECT CASE (HSNOWRAD)\n  CASE (\"B92\")\n\n    CALL SNOWCRORAD(OGLACIER,                      &\n                    PSW_RAD,PSNOWALB,PSNOWDZ,PSNOWRHO,    &\n                    PALB,ZRADSINK,ZRADXS,                 &\n                    PSNOWGRAN1, PSNOWGRAN2, PSNOWAGE,PPS, &\n                    PZENITH, PPERMSNOWFRAC,INLVLS_USE,    &\n                    OSNOW_ABS_ZENITH,HSNOWMETAMO,VIS_ICEALB)\n\n  CASE (\"TAR\",\"TA1\",\"TA2\")\n!    CALL SNOWCRO_TARTES(PSNOWGRAN1,PSNOWGRAN2,PSNOWRHO,PSNOWDZ,ZSNOWG0,ZSNOWY0,ZSNOWW0, &\n!                        ZSNOWB0,ZSNOWIMP_DENSITY,ZSNOWIMP_CONTENT,PALB,PSW_RAD,PZENITH, &\n!                        INLVLS_USE,PSNOWALB,ZRADSINK,ZRADXS,GCRODEBUGDETAILSPRINT,HSNOWMETAMO)\n  !\n  CASE DEFAULT\n!    CALL ABOR1_SFX(\"UNKNOWN CSNOWRAD OPTION\")\n  !\nEND SELECT\n\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCRORAD\", INLVLS_USE(IDEBUG),LPRINTGRAN,               &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n!*       7.     Heat transfer and surface energy budget\n!               ---------------------------------------\n! Snow thermal conductivity:\n!\n CALL SNOWCROTHRM(PSNOWRHO,ZSCOND,ZSNOWTEMP,PPS,PSNOWLIQ,GCOND_GRAIN,GCOND_YEN)\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROTHRM\", INLVLS_USE(IDEBUG),LPRINTGRAN,              &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n! Precipitation heating term:\n! Rainfall renders it's heat to the snow when it enters\n! the snowpack:\n!\nPHPSNOW(:) = PRR(:) * XCL * ( MAX( XTT,PTA(:) ) - XTT )    ! (W/m2)\n!\n! Surface Energy Budget calculations using ISBA linearized form\n! and standard ISBA turbulent transfer formulation\n!\n\nIF ( ALL(PPEW_A_COEF==0.) ) THEN\n  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n  ! Modif Matthieu Lafaysse for glaciers\n  ! For surface ice, modify roughness lengths\n  ! Only if not implicit coupling\n  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n      WHERE( PSNOWRHO(:,1)>XRHOTHRESHOLD_ICE )\n         ZZ0_SNOWICE    = PZ0    * XZ0ICEZ0SNOW\n         ZZ0H_SNOWICE   = PZ0H   * XZ0ICEZ0SNOW\n         ZZ0EFF_SNOWICE = PZ0EFF * XZ0ICEZ0SNOW\n      ELSEWHERE\n         ZZ0_SNOWICE    = PZ0\n         ZZ0H_SNOWICE   = PZ0H\n         ZZ0EFF_SNOWICE = PZ0EFF\n      ENDWHERE\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nELSE\n! trude test increased roughnesslenght on ice, even with implicit coupling\n!++TE\n         WHERE( PSNOWRHO(:,1)>XRHOTHRESHOLD_ICE )\n            ZZ0_SNOWICE    = PZ0    * XZ0ICEZ0SNOW\n            ZZ0H_SNOWICE   = PZ0H   * XZ0ICEZ0SNOW\n            ZZ0EFF_SNOWICE = PZ0EFF * XZ0ICEZ0SNOW\n         ELSEWHERE\n!--   TE\n            ZZ0_SNOWICE    = PZ0\n            ZZ0H_SNOWICE   = PZ0H\n            ZZ0EFF_SNOWICE = PZ0EFF\n         ENDWHERE               ! trude added\nEND IF\n\n\n CALL SNOWCROEBUD(HSNOWRES, HIMPLICIT_WIND,                                    &\n                  PPEW_A_COEF, PPEW_B_COEF,                                    &\n                  PPET_A_COEF, PPEQ_A_COEF, PPET_B_COEF, PPEQ_B_COEF,          &\n                  XSNOWDZMIN,                                                  &\n                  PZREF,ZSNOWTEMP(:,1),PSNOWRHO(:,1),PSNOWLIQ(:,1),ZSCAP(:,1), &\n                  ZSCOND(:,1),ZSCOND(:,2),                                     &\n                  PUREF,PEXNS,PEXNA,PDIRCOSZW,PVMOD,                           &\n                  PLW_RAD,PSW_RAD,PTA,PQA,PPS,PTSTEP,                          &\n                  PSNOWDZ(:,1),PSNOWDZ(:,2),PSNOWALB,ZZ0_SNOWICE,              &\n                  ZZ0EFF_SNOWICE,ZZ0H_SNOWICE,                                 &\n                  ZSFCFRZ,ZRADSINK(:,1),PHPSNOW,                               &\n                  ZCT,PEMISNOW,PRHOA,ZTSTERM1,ZTSTERM2,ZRA,PCDSNOW,PCHSNOW,    &\n                  ZQSAT, ZDQSAT, ZRSRA, ZUSTAR2_IC, PRI,                       &\n                  ZPET_A_COEF_T,ZPEQ_A_COEF_T,ZPET_B_COEF_T,ZPEQ_B_COEF_T      )\n\n\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROEBUD\", INLVLS_USE(IDEBUG),LPRINTGRAN,              &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n! Heat transfer: simple diffusion along the thermal gradient\n!\nZSNOWTEMPO1(:) = ZSNOWTEMP(:,1) ! save surface snow temperature before update\n!\n CALL SNOWCROSOLVT(PTSTEP,XSNOWDZMIN,PSNOWDZ,ZSCOND,ZSCAP,PTG,                &\n                   PSOILCOND,PD_G,ZRADSINK,ZCT,ZTSTERM1,ZTSTERM2,             &\n                   ZPET_A_COEF_T,ZPEQ_A_COEF_T,ZPET_B_COEF_T,ZPEQ_B_COEF_T,   &\n                   ZTA_IC,ZQA_IC,PGRNDFLUX, ZSNOWTEMP ,ZSNOWFLUX,             &\n                   INLVLS_USE                                                 )\n\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROSOLVT\", INLVLS_USE(IDEBUG),LPRINTGRAN,             &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n\n!***************************************DEBUG OUT********************************************\n!\n!*       8.     Surface fluxes\n!               --------------\n!\n\n CALL SNOWCROFLUX(ZSNOWTEMP(:,1),PSNOWDZ(:,1),PEXNS,PEXNA,            &\n                  ZUSTAR2_IC,                                         &\n                  PTSTEP,PSNOWALB,PSW_RAD,PEMISNOW,ZLWUPSNOW,PLW_RAD, &\n                  ZTA_IC,ZSFCFRZ,ZQA_IC,PHPSNOW,                      &\n                  ZSNOWTEMPO1,ZSNOWFLUX,ZCT,ZRADSINK(:,1),            &\n                  ZQSAT,ZDQSAT,ZRSRA,                                 &\n                  PRNSNOW,PHSNOW,PGFLUXSNOW,PLES3L,PLEL3L,PEVAP,      &\n                  PUSTAR,                                                     &\n                  PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS) ! trude added\n\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROFLUX\", INLVLS_USE(IDEBUG),LPRINTGRAN,              &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n!*       9.     Snow melt\n!               ---------\n!\n! First Test to see if snow pack vanishes during this time step:\n!\n\n CALL SNOWCROGONE(PTSTEP,PLEL3L,PLES3L,PSNOWRHO,                  &\n                  PSNOWHEAT,ZRADSINK,PEVAPCOR,PTHRUFAL,PGRNDFLUX, &\n                  PGFLUXSNOW,PSNOWDZ,PSNOWLIQ,ZSNOWTEMP,ZRADXS,   &\n                  PRR,INLVLS_USE                                  )\n\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROGONE\", INLVLS_USE(IDEBUG),LPRINTGRAN,              &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n! Add radiation not absorbed by snow to soil/vegetation interface flux\n! (for thin snowpacks):\n!\nPGRNDFLUX(:) = PGRNDFLUX(:) + ZRADXS(:)\n!\n! Second Test to see if one or several snow layers vanishe during this time\n! step. In such a case, the concerned snow layers are agregated to neighbours\n\n CALL SNOWCROLAYER_GONE(PTSTEP,ZSCAP,ZSNOWTEMP,PSNOWDZ,          &\n                        PSNOWRHO,PSNOWLIQ,PSNOWGRAN1,PSNOWGRAN2, &\n                        PSNOWHIST,PSNOWAGE,PLES3L, INLVLS_USE    )\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROLAYER_GONE\", INLVLS_USE(IDEBUG),LPRINTGRAN,        &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n! For partial melt: transform excess heat content into snow liquid:\n!\n\n CALL SNOWCROMELT(ZSCAP,ZSNOWTEMP,PSNOWDZ,PSNOWRHO,PSNOWLIQ,INLVLS_USE)\n\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROMELT\", INLVLS_USE(IDEBUG),LPRINTGRAN,              &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n!*      10.     Snow water flow and refreezing\n!               ------------------------------\n! Liquid water vertical transfer and possible snowpack runoff\n! And refreezing/freezing of meltwater/rainfall (ripening of the snow)\n!\n\n CALL SNOWCROREFRZ(PTSTEP,PRR,PSNOWRHO,ZSNOWTEMP,PSNOWDZ,PSNOWLIQ,PTHRUFAL, &\n                   ZSCAP,PLEL3L,INLVLS_USE                                  )\n\n! ++ trude\n!Assign streamflow from ice versus snow for output (diagnostics)\nIF (PSNOWRHO(1,1) .ge. XRHOTHRESHOLD_ICE) THEN\n  FLOW_ICE = PTHRUFAL\nELSE\n  FLOW_SNOW= PTHRUFAL\nENDIF\n\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROREFRZ\", INLVLS_USE(IDEBUG),LPRINTGRAN,             &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n!*      11.     Snow Evaporation/Sublimation mass updates:\n!               ------------------------------------------\n!\n\n CALL SNOWCROEVAPN(PLES3L,PTSTEP,ZSNOWTEMP(:,1),PSNOWRHO(:,1), &\n                   PSNOWDZ(:,1),PEVAPCOR,PSNOWHMASS            )\n!\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROEVAPN\", INLVLS_USE(IDEBUG),LPRINTGRAN,             &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n! If all snow in uppermost layer evaporates/sublimates, re-distribute\n! grid (below could be evoked for vanishingly thin snowpacks):\n!\n\n CALL SNOWCROEVAPGONE(PSNOWHEAT,PSNOWDZ,PSNOWRHO,ZSNOWTEMP,PSNOWLIQ,PSNOWGRAN1, &\n                      PSNOWGRAN2,PSNOWHIST,PSNOWAGE,INLVLS_USE,HSNOWMETAMO      )\n\n\n!***************************************DEBUG IN**********************************************\n!IF (GCRODEBUGDETAILSPRINT) THEN\n!  CALL SNOWCROPRINTPROFILE(\"after SNOWCROEVAPGONE\", INLVLS_USE(IDEBUG),LPRINTGRAN,          &\n!                           PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),        &\n!                           PSNOWLIQ(IDEBUG,:),PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),     &\n!                           PSNOWGRAN2(IDEBUG,:),PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:),     &\n!                           HSNOWMETAMO)\n!ENDIF\n!***************************************DEBUG OUT********************************************\n!\n!*      12.     Update surface albedo:\n!               ----------------------\n! Snow clear sky albedo:\n!\nIF ( HSNOWRAD=='B92' ) THEN\n\n\n  CALL SNOWCROALB(OGLACIER,                                             &\n                  PSNOWALB,ZSPECTRALALBEDO,PSNOWDZ(:,1),PSNOWRHO(:,1:2),       &\n                  PPERMSNOWFRAC,PSNOWGRAN1(:,1),PSNOWGRAN2(:,1),               &\n                  PSNOWAGE(:,1),PSNOWGRAN1(:,2),PSNOWGRAN2(:,2),PSNOWAGE(:,2), &\n                  PPS, PZENITH, INLVLS_USE, HSNOWMETAMO,VIS_ICEALB)\n\nENDIF\n\n!\n!*      13.     Update snow heat content:\n!               -------------------------\n! Update the heat content (variable stored each time step)\n! using current snow temperature and liquid water content:\n!\n! First, make check to make sure heat content not too large\n! (this can result due to signifigant heating of thin snowpacks):\n! add any excess heat to ground flux:\n!\nDO JJ = 1,SIZE(ZSNOW)\n! active layers\n  DO JST = 1,INLVLS_USE(JJ)\n    ZWHOLDMAX (JJ,JST) = SNOWCROHOLD( PSNOWRHO(JJ,JST),PSNOWLIQ(JJ,JST),PSNOWDZ(JJ,JST) )\n! trude test with not allowing liquid if psnowrho >  XRHOTHRESHOLD_ICE  (i.e. no liquid in ice)\n!      IF (PSNOWRHO(JJ,JST).GT.XRHOTHRESHOLD_ICE)  ZWHOLDMAX (JJ,JST)=0\n! end trude test\n\n   ZLIQHEATXS(JJ)     = MAX( 0.0, (PSNOWLIQ(JJ,JST) - ZWHOLDMAX(JJ,JST)) * XRHOLW ) * XLMTT/PTSTEP\n    PSNOWLIQ  (JJ,JST) = PSNOWLIQ(JJ,JST) - ZLIQHEATXS(JJ)*PTSTEP/(XRHOLW*XLMTT)\n    PSNOWLIQ  (JJ,JST) = MAX( 0.0, PSNOWLIQ(JJ,JST) )\n    PGRNDFLUX (JJ)     = PGRNDFLUX(JJ) + ZLIQHEATXS(JJ)\n    PSNOWTEMP (JJ,JST) = ZSNOWTEMP(JJ,JST)\n!   Heat content using total density\n    ZSCAP     (JJ,JST) = PSNOWRHO(JJ,JST) * XCI\n    PSNOWHEAT (JJ,JST) = PSNOWDZ(JJ,JST) * &\n                        ( ZSCAP(JJ,JST)*(PSNOWTEMP(JJ,JST)-XTT) - XLMTT*PSNOWRHO(JJ,JST) ) + &\n                        XLMTT * XRHOLW * PSNOWLIQ(JJ,JST)\n!\n    PSNOWSWE(JJ,JST)  = PSNOWDZ(JJ,JST) * PSNOWRHO(JJ,JST)\n  ENDDO  !  end loop active snow layers\n!\n! unactive layers\n  DO JST = INLVLS_USE(JJ)+1,SIZE(PSNOWSWE,2)\n    PSNOWSWE(JJ,JST)  = 0.\n    PSNOWHEAT(JJ,JST) = 0.\n    PSNOWRHO(JJ,JST)  = 999.\n    PSNOWTEMP(JJ,JST) = XTT\n    PSNOWDZ(JJ,JST)   = 0.\n  ENDDO  !  end loop unactive snow layers\n!\nENDDO    ! end loop grid points\n!\n! print some final diagnostics\n! ! ! IF (INLVLS_USE(I)>0) THEN\n! ! !  WRITE(*,FMT=\"(I4,2I4,F4.0,A7,F5.2,A10,F7.1,A11,F6.2,A13,F6.2)\")  &\n! ! !      TPTIME%TDATE%YEAR,TPTIME%TDATE%MONTH,TPTIME%TDATE%DAY,TPTIME%TIME/3600.,&\n! ! !           'HTN= ',SUM(PSNOWDZ(I,1:INLVLS_USE(I))), 'FLUX Sol=', PGRNDFLUX(I),&\n! ! !   'Tsurf_sol=',PTG(I)-273.16, 'Tbase_neige=',PSNOWTEMP(I,INLVLS_USE(I))-273.16\n! ! ! ENDIF\n!\n!***************************************DEBUG IN*********************************************\n!IF (GCRODEBUGPRINT) THEN\n!  CALL SNOWCROPRINTDATE()\n!  CALL SNOWCROPRINTPROFILE(\"CROCUS : end of time step\",INLVLS_USE(IDEBUG),LPRINTGRAN, &\n!        PSNOWDZ(IDEBUG,:),PSNOWRHO(IDEBUG,:),PSNOWTEMP(IDEBUG,:),PSNOWLIQ(IDEBUG,:),  &\n!        PSNOWHEAT(IDEBUG,:),PSNOWGRAN1(IDEBUG,:),PSNOWGRAN2(IDEBUG,:),                &\n!        PSNOWHIST(IDEBUG,:),PSNOWAGE(IDEBUG,:), HSNOWMETAMO)\n!END IF\n!***************************************DEBUG OUT********************************************\n!***************************************PRINT IN*********************************************\n! check suspect low temperature\nDO JJ = 1,SIZE(ZSNOW)\n!IF(INLVLS_USE(JJ)>0) WRITE(*,*) 'SOL:',JJ,INLVLS_USE(JJ),PGRNDFLUX(JJ),PTG(JJ),&\n! PSNOWTEMP(jj,INLVLS_USE(JJ)),PSNOWTEMP(jj,1),PZENITH(JJ)\n  DO JST = 1,INLVLS_USE(JJ)\n    IF ( PSNOWTEMP(JJ,JST) < 100. ) THEN\n      WRITE(6,*) 'pb tempe snow :',PSNOWTEMP(JJ,JST)\n!      WRITE(6,FMT='(\"DATE:\",2(I2.2,\"/\"),I4.4,F3.0)')          &\n!        TPTIME%TDATE%DAY,TPTIME%TDATE%MONTH,TPTIME%TDATE%YEAR,TPTIME%TIME/3600.\n      WRITE(6,*) 'point',JJ,\"/\",SIZE(ZSNOW)\n      WRITE(6,*) 'layer',JST\n      WRITE(6,*) 'pressure',PPS(JJ)\n      WRITE(6,*) 'slope',ACOS(PDIRCOSZW(JJ))*(180./XPI),\"deg\"\n      WRITE(6,*) 'solar radiation=',PSW_RAD(JJ)\n      WRITE(6,*) 'INLVLS_USE(JJ):',INLVLS_USE(JJ)\n      WRITE(6,*) PSNOWDZ(JJ,1:INLVLS_USE(JJ))\n      WRITE(6,*) PSNOWRHO(JJ,1:INLVLS_USE(JJ))\n      WRITE(6,*) PSNOWTEMP(JJ,1:INLVLS_USE(JJ))\n!      CALL ABOR1_SFX('SNOWCRO: erreur tempe snow')\n    ENDIF\n  ENDDO\nENDDO\n!***************************************PRINT OUT*********************************************\n!***************************************DEBUG IN*********************************************\n!Control and print energy balance\n!IF (GCRODEBUGPRINTBALANCE) THEN\n  !\n!  ZSUMMASS_FIN(IDEBUG) = SUM( PSNOWSWE (IDEBUG,1:INLVLS_USE(IDEBUG)) )\n!  ZSUMHEAT_FIN(IDEBUG) = SUM( PSNOWHEAT(IDEBUG,1:INLVLS_USE(IDEBUG)) )\n  !\n!  CALL GET_BALANCE(ZSUMMASS_INI(IDEBUG),ZSUMHEAT_INI(IDEBUG),ZSUMMASS_FIN(IDEBUG), &\n!                   ZSUMHEAT_FIN(IDEBUG),PSR(IDEBUG),PRR(IDEBUG),PTHRUFAL(IDEBUG),  &\n!                   PEVAP(IDEBUG),PEVAPCOR(IDEBUG),PGRNDFLUX(IDEBUG),PHSNOW(IDEBUG),&\n!                   PRNSNOW(IDEBUG),PLEL3L(IDEBUG),PLES3L(IDEBUG),PHPSNOW(IDEBUG),  &\n!                   PSNOWHMASS(IDEBUG),PSNOWDZ(IDEBUG,1),PTSTEP,                    &\n!                   ZMASSBALANCE(IDEBUG),ZENERGYBALANCE(IDEBUG),ZEVAPCOR2(IDEBUG)   )\n  !\n!  CALL SNOWCROPRINTBALANCE(ZSUMMASS_INI(IDEBUG),ZSUMHEAT_INI(IDEBUG),ZSUMMASS_FIN(IDEBUG), &\n!                           ZSUMHEAT_FIN(IDEBUG),PSR(IDEBUG),PRR(IDEBUG),PTHRUFAL(IDEBUG),  &\n!                           PEVAP(IDEBUG),PEVAPCOR(IDEBUG),PGRNDFLUX(IDEBUG),PHSNOW(IDEBUG),&\n!                           PRNSNOW(IDEBUG),PLEL3L(IDEBUG),PLES3L(IDEBUG),PHPSNOW(IDEBUG),  &\n!                           PSNOWHMASS(IDEBUG),PSNOWDZ(IDEBUG,1),PTSTEP,                    &\n!                           ZMASSBALANCE(IDEBUG),ZENERGYBALANCE(IDEBUG),ZEVAPCOR2(IDEBUG))\n  !\n!ENDIF\n!\n!IF (LPSTOPBALANCE) THEN\n  !\n  ! bilan pour tous points pour test eventuel sur depassement seuil des residus\n!  DO JJ=1, SIZE(ZSNOW)\n    !\n!    ZSUMMASS_FIN(JJ) = SUM( PSNOWSWE (JJ,1:INLVLS_USE(JJ)) )\n!    ZSUMHEAT_FIN(JJ) = SUM( PSNOWHEAT(JJ,1:INLVLS_USE(JJ)) )\n    !\n!    CALL GET_BALANCE(ZSUMMASS_INI(JJ),ZSUMHEAT_INI(JJ),ZSUMMASS_FIN(JJ), &\n!                     ZSUMHEAT_FIN(JJ),PSR(JJ),PRR(JJ),PTHRUFAL(JJ),      &\n!                     PEVAP(JJ),PEVAPCOR(JJ),PGRNDFLUX(JJ),PHSNOW(JJ),    &\n!                     PRNSNOW(JJ),PLEL3L(JJ),PLES3L(JJ),PHPSNOW(JJ),      &\n!                     PSNOWHMASS(JJ),PSNOWDZ(JJ,1),PTSTEP,                &\n!                     ZMASSBALANCE(JJ),ZENERGYBALANCE(JJ),ZEVAPCOR2(JJ)   )\n!    !\n!  ENDDO    ! end loop grid points\n  !\n!  CALL SNOWCROSTOPBALANCE(ZMASSBALANCE(:),ZENERGYBALANCE(:))\n  !\n!END IF\n!***************************************DEBUG OUT********************************************\n!\nPQS(:) = ZQSAT(:)\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO',1,ZHOOK_HANDLE)\n!\n\n!END SUBROUTINE SNOWCRO\nCONTAINS\n!\n!####################################################################\n!####################################################################\n!####################################################################\n        SUBROUTINE SNOWCROCOMPACTN(PTSTEP,PSNOWRHO,PSNOWDZ,                         &\n                                   PSNOWTEMP,PSNOW,PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST, &\n                                   PSNOWLIQ,INLVLS_USE,PDIRCOSZW,HSNOWMETAMO        )\n!\n!!    PURPOSE\n!!    -------\n!     Snow compaction due to overburden and settling.\n!     Mass is unchanged: layer thickness is reduced\n!     in proportion to density increases. Method\n!     directly inherited from Crocus v2.4 and\n!     coarsely described in Brun et al., J. Glac 1989 and 1992\n!\n!     de/e = -sigma/eta * dt\n!\n!     where e is layer thickness, sigma is the vertical stress, dt is the\n!     time step and eta is the snow viscosity\n!     * sigma is currently calculated taking into account only the overburden\n!     (a term representing \"metamorphism stress\" in fresh snow may be added\n!      in the future)\n!     * eta is computed as a function of snowtype, density and temperature\n!\n!     The local slope is taken into account, through the variable PDIRCOSZW\n!     which is directly the cosine of the local slope\n!\n!\n!     HISTORY:\n!     Basic structure from ISBA-ES model (Boone and Etchevers, 2001)\n!     Implementation of Crocus laws : E. Brun, S. Morin, J.-M. Willemet July 2010.\n!     Implementation of slope effect on settling : V. Vionnet, S. Morin May 2011\n!\n!\nUSE MODD_CSTS,     ONLY : XTT, XG\nUSE MODD_SNOW_PAR, ONLY : XRHOSMAX_ES\nUSE MODD_SNOW_METAMO\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                    :: PTSTEP       ! Time step UNIT : s\nREAL, DIMENSION(:), INTENT(IN)      :: PDIRCOSZW    ! cosine of local slope\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWTEMP    ! Snow temperature UNIT : K\n!\nREAL, DIMENSION(:,:), INTENT(INOUT) :: PSNOWRHO, PSNOWDZ   ! Density UNIT : kg m-3, Layer thickness UNIT : m\n!\nREAL, DIMENSION(:), INTENT(OUT)     :: PSNOW        ! Snowheight UNIT : m\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWGRAN1, PSNOWGRAN2, PSNOWHIST, &!Snowtype variables\n                                        PSNOWLIQ     ! Snow liquid water content UNIT ???\nINTEGER, DIMENSION(:), INTENT(IN)   :: INLVLS_USE   ! Number of snow layers used\n CHARACTER(3), INTENT(IN)              :: HSNOWMETAMO ! metamorphism scheme\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSNOWRHO2,    &! work snow density UNIT : kg m-3\n                                                      ZVISCOSITY,   &! Snow viscosity UNIT : N m-2 s (= Pa s)\n                                                      ZSMASS        !, &  ! overburden mass for a given layer UNIT : kg m-2\n!                                                      ZWSNOWDZ       ! mass of each snow layer UNIT : kg m-2\n!\nINTEGER   :: JJ,JST   ! looping indexes\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!-------------------------------------------------------------------------------\n!\n! 1. Cumulative snow mass (kg/m2):\n! --------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROCOMPACTN',0,ZHOOK_HANDLE)\n!\nDO JJ = 1,SIZE(PSNOW)\n  ZSMASS(JJ,1) = 0.0\n  DO JST = 2,INLVLS_USE(JJ)\n    ZSMASS(JJ,JST) = ZSMASS(JJ,JST-1) + PSNOWDZ(JJ,JST-1) * PSNOWRHO(JJ,JST-1)\n  ENDDO\n  ZSMASS(JJ,1) = 0.5 * PSNOWDZ(JJ,1) * PSNOWRHO(JJ,1)  ! overburden of half the mass of the uppermost layer applied to itself\nENDDO\n\n!\n! 2. Compaction/Settling\n! ----------------------\n!\nDO JJ = 1,SIZE(PSNOW)\n  !\n  DO JST = 1,INLVLS_USE(JJ)\n    !\n    ! Snow viscosity basic equation (depend on temperature and density only):\n!      write(*,*) '-----'\n!      write(*,*) xvvisc1, xvvisc3, psnowrho(jj,jst), xvvisc4, xtt, psnowtemp(jj,jst), xvro11\n!      write(*,*),  XVVISC3*PSNOWRHO(JJ,JST) ,  XVVISC4*ABS(XTT-PSNOWTEMP(JJ,JST))\n    ZVISCOSITY(JJ,JST) = XVVISC1 * &\n                         EXP( XVVISC3*PSNOWRHO(JJ,JST) + XVVISC4*ABS(XTT-PSNOWTEMP(JJ,JST)) ) * &\n                         PSNOWRHO(JJ,JST) / XVRO11\n\n    !\n    ! Equations below apply changes to the basic viscosity value, based on snow microstructure properties\n    IF ( PSNOWLIQ(JJ,JST)>0.0 ) THEN\n      ZVISCOSITY(JJ,JST) = ZVISCOSITY(JJ,JST) / &\n                           ( XVVISC5 + XVVISC6*PSNOWLIQ(JJ,JST)/PSNOWDZ(JJ,JST) )\n    ENDIF\n    !\n    IF( PSNOWLIQ(JJ,JST)/PSNOWDZ(JJ,JST)<=0.01 .AND. PSNOWHIST(JJ,JST)>=NVHIS2 ) THEN\n      ZVISCOSITY(JJ,JST) = ZVISCOSITY(JJ,JST) * XVVISC7\n    ENDIF\n    !\n    IF ( PSNOWHIST(JJ,JST)==NVHIS1 ) THEN\n      !\n      IF ( HSNOWMETAMO==\"B92\" ) THEN\n        !\n        IF ( PSNOWGRAN1(JJ,JST)>=0. .AND. PSNOWGRAN1(JJ,JST)<XVGRAN6 ) THEN\n          ZVISCOSITY(JJ,JST) = ZVISCOSITY(JJ,JST) * &\n                               MIN( 4., EXP( MIN( XVDIAM1, &\n                                                  PSNOWGRAN2(JJ,JST)             -XVDIAM4 ) / XVDIAM6 ) )\n        ENDIF\n        !\n      ELSEIF ( PSNOWGRAN1(JJ,JST)>=XVDIAM6*(4.-PSNOWGRAN2(JJ,JST)) .AND. PSNOWGRAN2(JJ,JST)<XVGRAN6/XVGRAN1 ) THEN\n        ZVISCOSITY(JJ,JST) = ZVISCOSITY(JJ,JST) * &\n                             MIN( 4., EXP( MIN( XVDIAM1, &\n                                               (XVDIAM6*(4.-PSNOWGRAN2(JJ,JST)))-XVDIAM4 ) / XVDIAM6 ) )\n      ENDIF\n      !\n    ENDIF\n    !\n    ! Calculate new snow snow density: compaction from weight/over-burden\n    ZSNOWRHO2(JJ,JST) = PSNOWRHO(JJ,JST) + PSNOWRHO(JJ,JST) * PTSTEP * &\n                                           ( XG*PDIRCOSZW(JJ)*ZSMASS(JJ,JST)/ZVISCOSITY(JJ,JST) )\n    !\n    ! Calculate new grid thickness in response to density change\n    PSNOWDZ(JJ,JST) = PSNOWDZ(JJ,JST) * ( PSNOWRHO(JJ,JST)/ZSNOWRHO2(JJ,JST) )\n    !\n    !  Update density (kg m-3):\n    PSNOWRHO(JJ,JST) = ZSNOWRHO2(JJ,JST)\n    !\n  ENDDO    ! end loop snow layers\n  !\nENDDO      ! end loop grid points\n!\n!\n! 3. Update total snow depth:\n! -----------------------------------------------\n!\nDO JJ = 1,SIZE(PSNOWDZ,1)\n  PSNOW(JJ) = SUM( PSNOWDZ(JJ,1:INLVLS_USE(JJ)) )\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROCOMPACTN',1,ZHOOK_HANDLE)\n\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SNOWCROCOMPACTN\n\n\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROMETAMO(PSNOWDZ,PSNOWGRAN1, PSNOWGRAN2,         &\n                         PSNOWHIST, PSNOWTEMP, PSNOWLIQ, PTSTEP, &\n                         PSNOWSWE,INLVLS_USE, PSNOWAGE, HSNOWMETAMO)\n!\n\n!**** *METAMO* - METAMORPHOSE DES GRAINS\n!              - SNOW METAMORPHISM\n!     OBJET.\n!     ------\n!     METAMORPHOSE DU MANTEAU NEIGEUX.\n!     EVOLUTION DU TYPE DE GRAINS\n!     MISE A JOUR DES VARIABLES HISTORIQUES.\n!     METAMORPHISM OF THE SNOW GRAINS,\n!     HISTORICAL VARIABLES\n\n!**   INTERFACE.\n!     ----------\n!     FORMALISME ADOPTE POUR LA REPRESENTATION DES GRAINS :\n!     FORMALISM FOR THE REPRESENTATION OF GRAINS\n!     -----------------------------------------------------\n\n\n!                    1       - -1                 NEIGE FRAICHE\n!                   / \\      |                    -------------\n!                  /   \\     |  DENDRICITE        DECRITE EN TERME\n!                 /     \\    |  DENDRICITY        DE DENDRICITE ET\n!                /       \\   |                    SPHERICITE\n!               2---------3  -  0                 DESCRIBED WITH\n!                                                 SPHERICITY AND\n!               |---------|                       DENDRICITY\n!               0         1\n!               SPHERICITE\n!               SPHERICITY\n\n!               4---------5  -\n!               |         |  |\n!               |         |  | DIAMETRE  (OU TAILLE)\n!               |         |  | DIAMETER  (OR SIZE  )\n!               |         |  |\n!               |         |  |                   NEIGE NON DENDRITIQUE\n!               6---------7  -                   ---------------------\n\n!                                                SPHERICITE ET TAILLE\n!                                                SPHERICITY AND SIZE\n\n!              LES VARIABLES DU MODELE :\n!              -------------------------\n!              CAS DENDRITIQUE             CAS NON DENDRITIQUE\n!\n!            SGRAN1(JST) : DENDRICITE      SGRAN1(JST) : SPHERICITE\n!            SGRAN2(JST) : SPHERICITE      SGRAN2(JST) : TAILLE (EN METRE)\n!                                                        SIZE\n\n!\n!    CAS DENDRITIQUE/ DENDRITIC CASE\n!    -------------------------------\n!    SGRAN1(JST) VARIE DE -XVGRAN1 (-99 PAR DEFAUT) (ETOILE) A 0\n!  (DENDRICITY)  >D OU LA DIVISION PAR -XVGRAN1 POUR OBTENIR DES VALEURS\n!                 ENTRE 1 ET 0\n!                 VARIES FROM -XVGRAN1 (DEFAULT -99) (FRESH SNOW) TO 0\n!                 DIVISION BY -XVGRAN1 TO OBTAIN VALUES BETWEEN 0 AND 1\n\n!    SGRAN2(JST) VARIE DE 0 (CAS COMPLETEMENT ANGULEUX) A XVGRAN1\n!  (SPHERICITY)  (99 PAR DEFAUT)\n!                >D OU LA DIVISION PAR XVGRAN1 POUR OBTENIR DES VALEURS\n!                 ENTRE 0 ET 1\n!                 VARIES FROM 0 (SPHERICITY=0) TO XVGRAN1\n\n\n!    CAS NON DENDRITIQUE / NON DENDRITIC CASE\n!    ---------------------------------------\n\n!    SGRAN1(JST) VARIE DE 0 (CAS COMPLETEMENT ANGULEUX) A XVGRAN1\n!  (SPHERICITY)  (99 PAR DEFAUT) (CAS SPHERIQUE)\n!                >D OU LA DIVISION PAR XVGRAN1 POUR OBTENIR DES VALEURS\n!                 ENTRE 0 ET 1\n!                 VARIES FROM 0 TO 99\n\n!    SGRAN2(JST) EST SUPERIEUR A XVDIAM1-SPHERICITE (3.E-4 M) ET NE FAIT QUE CROITRE\n!     (SIZE)     IS GREATER THAN XVDIAM1-SPHERICITE (3.E-4 M) ALWAYS INCREASE\n\n\n!    EXEMPLES : POINTS CARACTERISTIQUES DE LA FIGURE\n!    --------\n\n!                 SGRAN1     SGRAN2    DENDRICITE  SPHERICITE  TAILLE\n!                                      DENDRICITY  SPHERICITY  SIZE\n!      --------------------------------------------------------------\n!                                                               (M)\n!        1        -XVGRAN1    VNSPH3        1           0.5\n!        2           0         0           0            0\n!        3           0       XVGRAN1        0            1\n!        4           0       XVDIAM1                     0        4.E-4\n!        5         XVGRAN1    XVDIAM1-XVSPHE1              1        3.E-4\n!        6           0         --                       0        --\n!        7         XVGRAN1      --                       1        --\n\n!     PAR DEFAUT : XVGRAN1 =99   VNSPH3=50 XVSPHE1=1. XVDIAM1=4.E-4\n\n\n!     METHODE.\n!     --------\n!     EVOLUTION DES TYPES DE GRAINS : SELON LES LOIS DECRITES\n!     DANS BRUN ET AL (1992)\n!     PLUSIEURS CAS SONT A DISTINGUER\n!      1.2 NEIGE HUMIDE\n!      1.3 METAMORPHOSE NEIGE SECHE\n!        1.3.1 FAIBLE GRADIENT\n!        1.3.2 GRADIENT MOYEN\n!        1.3.3 FORT GRADIENT\n!     DANS CHAQUE CAS ON SEPARE NEIGE DENDRITIQUE ET NON DENDRITIQUE\n!     LE PASSAGE DENDRITIQUE => NON DENDRITIQUE SE FAIT LORSQUE\n!     SGRAN1 DEVIENT > 0\n\n!     TASSEMENT : LOIS DE VISCOSITE ADAPTEE SELON LE TYPE DE GRAINS\n\n!     VARIABLES HISTORIQUES (CAS NON DENDRITIQUE SEULEMENT)\n\n!     MSHIST DEFAUT\n!        0           CAS NORMAL\n!     NVHIS1   1     GRAINS ANGULEUX\n!     NVHIS2   2     GRAINS AYANT ETE EN PRESENCE D EAU LIQUIDE\n!                    MAIS N'AYANT PAS EU DE CARATERE ANGULEUX\n!     NVHIS3   3     GRAINS AYANT ETE EN PRESENCE D EAU LIQUIDE\n!                    AYANT EU AUPARAVANT UN CARACTERE ANGULEUX\n\n!     GRAIN METAMORPHISM ACCORDING TO BRUN ET AL (1992)\n!     THE DIFFERENT CASES ARE :\n!     1.2 WET SNOW\n!     1.3 DRY SNOW\n!       1.3.1. LOW      TEMPERATURE GRADIENT\n!       1.3.2. MODERATE TEMPERATURE GRADIENT\n!       1.3.3. HIGH     TEMPERATURE GRADIENTi\n!     THE CASE OF DENTRITIC OR NON DENDRITIC SNOW IS TREATED SEPARATELY\n!     THE LIMIT DENTRITIC ==> NON DENDRITIC IS REACHED WHEN SGRAN1>0\n\n!     SNOW SETTLING : VISCOSITY DEPENDS ON THE GRAIN TYPES\n\n!     HISTORICAL VARIABLES (NON DENDRITIC CASE)\n!     MSHIST DEFAUT\n!        0           CAS NORMAL\n!     NVHIS1   1     FACETED CRISTAL\n!     NVHIS2   2     LIQUID WATER AND NO FACETED CRISTALS BEFORE\n!     NVHIS3   3     LIQUID WATER AND FACETED CRISTALS BEFORE\n\n!     EXTERNES.\n!     ---------\n\n!     REFERENCES.\n!     -----------\n\n!     AUTEURS.\n!     --------\n!        ERIC BRUN ET AL. - JOURNAL OF GLACIOLOGY 1989/1992.\n\n!     MODIFICATIONS.\n!     --------------\n!        08/95: YANNICK DANIELOU - CODAGE A LA NORME DOCTOR.\n!        09/96: ERIC MARTIN      - CORRECTION COMMENTAIRES\n!        03/06: JM Willemet      - F90 and SI units\n!        08/06: JM Willemet      - new formulation for TEL (Mwat/(Mice+Mwat) instead of Mwat/Mice.\n!                                  Threshold on the diameter increasing of the wet grains.\n!        01/07 : JM Willemet     - CORRECTION DES COUCHES SATUREES SUBISSANT DU TASSEMENT\n!                                  CORRECTION ON THE SATURATED LAYERS WHICH ARE SETTLED\n!        12/12: CM Carmagnola    - Dendricity and size replaced by the optical diameter\n!                                - Test of different evolution laws for the optical diameter\n!        08/13: M Lafaysse       - Simplification of historical parameter computation (logicals GNONDENDRITIC, GFACETED, GSPHE_LW)\n   !\nUSE MODD_SNOW_METAMO\nUSE MODD_CSTS, ONLY : XTT, XPI, XRHOLW, XRHOLI\nUSE MODD_SNOW_PAR, ONLY : XUNDEF\n!\nUSE MODE_SNOW3L\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!     0.1 declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWDZ, PSNOWTEMP, PSNOWLIQ, PSNOWSWE\n!\nREAL, DIMENSION(:,:), INTENT(INOUT) :: PSNOWGRAN1, PSNOWGRAN2, PSNOWHIST\n!\nREAL, INTENT(IN)                    :: PTSTEP\n!\nINTEGER, DIMENSION(:), INTENT(IN)   :: INLVLS_USE\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWAGE\n!\n CHARACTER(3), INTENT(IN)              :: HSNOWMETAMO ! metamorphism scheme\n!\n!     0.2 declaration of local variables\n!\nREAL :: ZGRADT, ZTELM, ZVDENT, ZDENT, ZSPHE, ZVAP, ZDANGL, &\n        ZSIZE, ZSSA, ZSSA0, ZSSA_T, ZSSA_T_DT, ZA, ZB, ZC, &\n        ZA2, ZB2, ZC2, ZOPTD, ZOPTR, ZOPTR0, ZDRDT\nREAL :: ZVDENT1, ZVDENT2, ZVSPHE, ZCOEF_SPH\nREAL :: ZDENOM1, ZDENOM2, ZFACT1, ZFACT2\nINTEGER :: INLVLS\nINTEGER :: JST,JJ                                !Loop controls\nINTEGER :: IDRHO, IDGRAD, IDTEMP           !Indices for values from Flanner 2006\nLOGICAL :: GNONDENDRITIC ,GFACETED, GSPHE_LW\nLOGICAL :: GCOND_B92, GCOND_C13, GCOND_SPH\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!     INITIALISATION\n!     --------------\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROMETAMO',0,ZHOOK_HANDLE)\n!\n\nINLVLS = SIZE(PSNOWGRAN1(:,:),2)  ! total snow layers\n!\n!*    1. METAMORPHOSES DANS LES STRATES. / METAMORPHISM\n!        -----------------------------------------------\nDO JJ = 1,SIZE(PSNOWRHO,1)\n  !\n  DO JST = 1,INLVLS_USE(JJ)\n    !\n    ! 1.1 INITIALISATION: GRADIENT DE TEMPERATURE / TEMPERATURE GRADIENT\n    IF ( JST==INLVLS_USE(JJ) ) THEN\n      ZGRADT = ABS(PSNOWTEMP(JJ,JST)   - PSNOWTEMP(JJ,JST-1))*2. / (PSNOWDZ(JJ,JST-1) + PSNOWDZ(JJ,JST))\n    ELSEIF ( JST==1 ) THEN\n      ZGRADT = ABS(PSNOWTEMP(JJ,JST+1) - PSNOWTEMP(JJ,JST)  )*2. / (PSNOWDZ(JJ,JST) + PSNOWDZ(JJ,JST+1))\n    ELSE\n      ZGRADT = ABS(PSNOWTEMP(JJ,JST+1) - PSNOWTEMP(JJ,JST-1))*2. / &\n                                            (PSNOWDZ(JJ,JST-1) + PSNOWDZ(JJ,JST)*2. + PSNOWDZ(JJ,JST+1))\n    ENDIF\n    !\n    IF ( PSNOWLIQ(JJ,JST)>XUEPSI ) THEN\n      ! 1.2 METAMORPHOSE HUMIDE. / WET SNOW METAMORPHISM\n      !\n      ! TENEUR EN EAU LIQUIDE / LIQUID WATER CONTENT\n      ZTELM  = XUPOURC * PSNOWLIQ(JJ,JST) * XRHOLW / PSNOWSWE(JJ,JST)\n      !\n      ! VITESSES DE DIMINUTION DE LA DENDRICITE / RATE OF THE DENDRICITY DECREASE\n      ZVDENT1 = MAX( XVDENT2 * ZTELM**NVDENT1, XVDENT1 * EXP(XVVAP1/XTT) )\n      ZVDENT2 = ZVDENT1\n      ! CONDITION POUR LE CAS NON DENDRITIQUE NON SPHERIQUE\n      GCOND_B92  = ( PSNOWGRAN1(JJ,JST)<XVGRAN1-XUEPSI )\n      GCOND_C13 = .TRUE. ! CONDITION POUR LE CALCUL DE SNOWGRAN1\n      ! X COEF\n      ZVSPHE = XVSPHE1\n      ! FOR C13\n      ZCOEF_SPH = 2.\n      !\n    ELSEIF ( ZGRADT<XVGRAT1 ) THEN\n      ! 1.3.1 METAMORPHOSE SECHE FAIBLE/ DRY LOW GRADIENT (0-5 DEG/M).\n      !\n      ZVAP = EXP( XVVAP1/PSNOWTEMP(JJ,JST) )\n      !\n      ! VITESSES DE DIMINUTION DE LA DENDRICITE / RATE OF THE DENDRICITY DECREASE\n      ZVDENT1 = XVDENT1 * ZVAP\n      ZVDENT2 = XVSPHE2 * ZVAP\n      ! CONDITION POUR LE CAS NON DENDRITIQUE SPHERICITE NON LIMITEE\n      GCOND_B92  = ( PSNOWHIST(JJ,JST)/=NVHIS1 .OR. PSNOWGRAN2(JJ,JST)<XVDIAM2 )\n      GCOND_C13 = ( HSNOWMETAMO=='C13' )  ! CONDITION POUR LE CALCUL DE SNOWGRAN1\n      ! X COEF\n      ZVSPHE = XVSPHE1\n      ! FOR C13\n      ZCOEF_SPH = 2.\n      !\n    ELSE\n      ! 1.3.2 METAMORPHOSE SECHE GRADIENT MOYEN / DRY MODERATE (5-15).\n      ! 1.3.3 METAMORPHOSE SECHE FORT / DRY HIGH GRADIENT\n      !\n      ZVAP = EXP( XVVAP1/PSNOWTEMP(JJ,JST) ) * (ZGRADT)**XVVAP2\n      !\n      ! VITESSES DE DIMINUTION DE LA DENDRICITE / RATE OF THE DENDRICITY DECREASE\n      ZVDENT1 = XVDENT1 * ZVAP\n      ZVDENT2 = - XVDENT1 * ZVAP\n      ! CONDITION POUR LE CAS NON DENDRITIQUE NON COMPLETEMENT ANGULEUX\n      GCOND_B92  = ( ZGRADT<XVGRAT2 .OR. PSNOWGRAN1(JJ,JST)>0. )\n      GCOND_C13 = ( HSNOWMETAMO=='C13' ) ! CONDITION POUR LE CALCUL DE SNOWGRAN1\n      ! X COEF\n      ZVSPHE = XUNDEF\n      ! FOR C13\n      ZCOEF_SPH = 3.\n      !\n    ENDIF\n    !\n    IF ( HSNOWMETAMO==\"B92\" ) THEN\n      !\n      !------------------------------------------------\n      !    BRUN et al. 1992 (B92)\n      !\n      ! -> Wet snow and dry snow\n      ! -> Evolution of dendricity, sphericity and size\n      !------------------------------------------------\n      !\n      IF ( PSNOWGRAN1(JJ,JST)<-XUEPSI ) THEN\n        ! 1.2.1 CAS DENDRITIQUE/DENDRITIC CASE.\n        !\n        ! / CALCUL NOUVELLE DENDRICITE ET SPHERICITE.\n        ZDENT = - PSNOWGRAN1(JJ,JST)/XVGRAN1 - ZVDENT1 * PTSTEP\n        ZSPHE =   PSNOWGRAN2(JJ,JST)/XVGRAN1 + ZVDENT2 * PTSTEP\n        CALL SET_THRESH(ZGRADT,PSNOWLIQ(JJ,JST),ZSPHE)\n        IF( ZDENT<=XUEPSI ) THEN\n          ! EVOLUTION DE SGRAN1 ET SGRAN2 ET TEST PASSAGE DENDRITIQUE > NON DENDRITIQUE.\n          PSNOWGRAN1(JJ,JST) =  ZSPHE * XVGRAN1\n          PSNOWGRAN2(JJ,JST) = XVDIAM1 - XVDIAM5 * MIN( ZSPHE, ZVSPHE )\n        ELSE\n          PSNOWGRAN1(JJ,JST) = -ZDENT * XVGRAN1\n          PSNOWGRAN2(JJ,JST) =  ZSPHE * XVGRAN1\n        ENDIF\n        !\n      ELSEIF ( GCOND_B92 ) THEN\n        ! 1.2.2 CAS NON DENDRITIQUE ET\n        !             NON COMPLETEMENT SPHERIQUE / NON DENDRITIC AND NOT COMPLETELY SPHERIC CASE\n        ! OU          SPHERICITE NON LIMITEE\n        ! OU          NON COMPLETEMENT ANGULEUX\n        !\n        ! . EVOLUTION DE LA SPHERICITE SEULEMENT / EVOLUTION OF SPHERICITY ONLY (NOT SIZE)\n        ZSPHE = PSNOWGRAN1(JJ,JST)/XVGRAN1 + ZVDENT2 * PTSTEP\n        CALL SET_THRESH(ZGRADT,PSNOWLIQ(JJ,JST),ZSPHE)\n        PSNOWGRAN1(JJ,JST) = ZSPHE * XVGRAN1\n        !\n      ELSEIF ( PSNOWLIQ(JJ,JST)>XUEPSI ) THEN\n        ! 1.2.3 CAS NON DENDRITIQUE ET SPHERIQUE/NON DENDRITIC AND SPHERIC EN METAMORPHOSE HUMIDE\n        !\n        ! EVOLUTION DE LA TAILLE SEULEMENT/EVOLUTION OF SIZE ONLY\n        CALL GET_GRAN(PTSTEP,ZTELM,PSNOWGRAN2(JJ,JST))\n        !\n      ELSEIF ( ZGRADT<XVGRAT1 ) THEN\n        ! 1.2.4. CAS HISTORIQUE=2 OU 3 ET GROS GRAINS SPHERICITE LIMITEE / CASE HISTORY=2 OR 3 AND BIG GRAINS LIMITED SPHERICITY\n        !\n        ZSPHE =  PSNOWGRAN1(JJ,JST)/XVGRAN1 + &\n                 ZVDENT2 * PTSTEP * EXP( MIN( 0., XVDIAM3-PSNOWGRAN2(JJ,JST) ) / XVDIAM6 )\n        ZSPHE = MIN( ZSPHE, XVSPHE3 )\n        CALL SET_THRESH(ZGRADT,PSNOWLIQ(JJ,JST),ZSPHE)\n        PSNOWGRAN1(JJ,JST) = ZSPHE * XVGRAN1\n        !\n      ELSE\n        ! 1.2.5. CAS NON DENDRITIQUE ET ANGULEUX/DENDRITIC AND SPERICITY=0.\n        !\n        ZDANGL = SNOW3L_MARBOUTY(PSNOWRHO(JJ,JST),PSNOWTEMP(JJ,JST),ZGRADT)\n        PSNOWGRAN2(JJ,JST) = PSNOWGRAN2(JJ,JST) + ZDANGL * XVFI * PTSTEP\n        !\n      ENDIF\n      !\n    ELSE\n      !\n      !------------------------------------------------\n      !    CARMAGNOLA et al. 2013 (C13)\n      !\n      ! -> Wet snow\n      ! -> Evolution of optical diameter and sphericity\n      !------------------------------------------------\n      !\n      ! SPHERICITY\n      ZSPHE = PSNOWGRAN2(JJ,JST) + ZVDENT2 * PTSTEP\n      CALL SET_THRESH(ZGRADT,PSNOWLIQ(JJ,JST),ZSPHE)\n      IF ( PSNOWLIQ(JJ,JST)>XUEPSI .OR. ZGRADT<XVGRAT1 ) THEN\n        GCOND_SPH = ( ZSPHE < 1.-XUEPSI )\n      ELSE\n        GCOND_SPH = ( ZSPHE > XUEPSI )\n      ENDIF\n      !\n      IF ( GCOND_C13 .AND. PSNOWGRAN1(JJ,JST)<XVDIAM6*(4.-ZSPHE)-XUEPSI ) THEN\n        ! 1.1.1 CAS DENDRITIQUE/DENDRITIC CASE.\n        !\n        IF ( GCOND_SPH ) THEN\n          PSNOWGRAN1(JJ,JST) = PSNOWGRAN1(JJ,JST) + XVDIAM6 * PTSTEP * &\n                               ( ZVDENT2*(PSNOWGRAN1(JJ,JST)/XVDIAM6-1.)/(ZSPHE-3.) - &\n                                 ZVDENT1*(ZSPHE-3.) )\n        ELSE\n           PSNOWGRAN1(JJ,JST) =  PSNOWGRAN1(JJ,JST) + XVDIAM6 * PTSTEP * ZVDENT1 * ZCOEF_SPH\n        ENDIF\n        !\n      ELSEIF ( GCOND_C13 .AND. GCOND_SPH ) THEN\n        ! 1.2.2 CAS NON DENDRITIQUE ET\n        !             NON COMPLETEMENT SPHERIQUE / NON DENDRITIC AND NOT COMPLETELY SPHERIC CASE\n        ! OU          NON COMPLETEMENT ANGULEUX\n        !\n        PSNOWGRAN1(JJ,JST) = PSNOWGRAN1(JJ,JST) - XVDIAM6 * PTSTEP * ZVDENT2 * 2.* ZSPHE\n        !\n      ELSEIF ( PSNOWLIQ(JJ,JST)>XUEPSI ) THEN\n        ! 1.2.3 CAS NON DENDRITIQUE ET SPHERIQUE/NON DENDRITIC AND SPHERIC EN METAMORPHOSE HUMIDE\n        !\n        ! NON DENDRITIC AND SPHERIC: EVOLUTION OF SIZE ONLY\n        CALL GET_GRAN(PTSTEP,ZTELM,PSNOWGRAN1(JJ,JST))\n        !\n      ELSEIF ( GCOND_C13 .AND. ZGRADT>=XVGRAT2 ) THEN\n        !\n        ZDANGL = SNOW3L_MARBOUTY(PSNOWRHO(JJ,JST),PSNOWTEMP(JJ,JST),ZGRADT)\n        PSNOWGRAN1(JJ,JST) = PSNOWGRAN1(JJ,JST) + 0.5 * ZDANGL * XVFI * PTSTEP\n        !\n      ENDIF\n      !\n      PSNOWGRAN2(JJ,JST) = ZSPHE\n      !\n      !---------------------------------\n      !    TAILLANDIER et al. 2007 (T07)\n      !\n      ! -> Dry snow\n      ! -> Evolution of optical diameter\n      !---------------------------------\n      !\n      IF ( PSNOWLIQ(JJ,JST)<=XUEPSI .AND. HSNOWMETAMO=='T07' ) THEN\n        !\n     !   WRITE(*,*) CSNOWMETAMO,': you are using T07 formulation!!'\n        !\n        ! Coefficients from Taillander et al. 2007\n        ZSSA0 = 6./( XRHOLI*XVDIAM6 ) * 10.\n        !\n        ZA  =  0.659*ZSSA0 - 27.2 * ( PSNOWTEMP(JJ,JST)-273.15-2.03 )      ! TG conditions\n        ZB  = 0.0961*ZSSA0 - 3.44 * ( PSNOWTEMP(JJ,JST)-273.15+1.90 )\n        ZC  = -0.341*ZSSA0 - 27.2 * ( PSNOWTEMP(JJ,JST)-273.15-2.03 )\n        ZA2 =  0.629*ZSSA0 - 15.0 * ( PSNOWTEMP(JJ,JST)-273.15-11.2 )     ! ET conditions\n        ZB2 = 0.0760*ZSSA0 - 1.76 * ( PSNOWTEMP(JJ,JST)-273.15-2.96 )\n        ZC2 = -0.371*ZSSA0 - 15.0 * ( PSNOWTEMP(JJ,JST)-273.15-11.2 )\n        !\n        ! Compute SSA (method from Jacobi, 2010)\n!   ZSSA = 6./(XRHOLI*PSNOWGRAN1(JJ,JST))*10.\n!    ZSSA_t = (0.5+0.5*TANH(0.5*(ZGRADT-10.)))*(ZA-ZB*LOG(PSNOWAGE(JJ,JST)*24+EXP(ZC/ZB))) + &\n!         (0.5-0.5*TANH(0.5*(ZGRADT-10.)))*(ZA2-ZB2*LOG(PSNOWAGE(JJ,JST)*24+EXP(ZC2/ZB2)))\n!\n!   ZSSA_t_dt = (0.5+0.5*TANH(0.5*(ZGRADT-10.)))*(ZA-ZB*LOG(PSNOWAGE(JJ,JST)*24+PTSTEP/3600.+EXP(ZC/ZB))) + &\n!             (0.5-0.5*TANH(0.5*(ZGRADT-10.)))*(ZA2-ZB2*LOG(PSNOWAGE(JJ,JST)*24+PTSTEP/3600.+EXP(ZC2/ZB2)))\n!\n!   ZSSA = ZSSA + (ZSSA_t_dt-ZSSA_t)\n!\n!   ZSSA = MAX(ZSSA,8.*10.)\n!\n!   PSNOWGRAN1(JJ,JST) = 6./(XRHOLI*ZSSA)*10.\n        !\n        ! Compute SSA (rate equation with Taylor series)\n        ZSSA = 6./( XRHOLI*PSNOWGRAN1(JJ,JST) ) * 10.\n        !\n        ZDENOM1 = (PSNOWAGE(JJ,JST)*24.) + EXP(ZC/ZB)\n        ZDENOM2 = (PSNOWAGE(JJ,JST)*24.) + EXP(ZC2/ZB2)\n        ZFACT1 = 0.5 + 0.5*TANH( 0.5*(ZGRADT-10.) )\n        ZFACT2 = 0.5 - 0.5*TANH( 0.5*(ZGRADT-10.) )\n        ZSSA = ZSSA + (PTSTEP/3600.) * (                   ZFACT1 * (-ZB/ZDENOM1)    + ZFACT2 * (-ZB2/ZDENOM2)   + &\n                                        (PTSTEP/3600.) * ( ZFACT1 * (ZB/ZDENOM1**2.) + ZFACT2 * (ZB2/ZDENOM2**2.) ) * 1./2. )\n        !ZSSA = ZSSA + (PTSTEP/3600.) * (  ZFACT1 * ZB /ZDENOM1 * ( 1./ZDENOM1 * (PTSTEP/3600.) * 1./2. - 1. ) + &\n        !                                  ZFACT2 * ZB2/ZDENOM2 * ( 1./ZDENOM2 * (PTSTEP/3600.) * 1./2. - 1. ) )\n         !\n        ZSSA = MAX( ZSSA, 8.*10. )\n        !\n        PSNOWGRAN1(JJ,JST) = 6./( XRHOLI*ZSSA ) * 10.\n        !\n      !---------------------------------\n      !    FLANNER et al. 2006 (F06)\n      !\n      ! -> Dry snow\n      ! -> Evolution of optical diameter\n      !---------------------------------\n      ELSEIF ( PSNOWLIQ(JJ,JST)<=XUEPSI .AND. HSNOWMETAMO=='F06' )THEN\n        !\n      !  WRITE(*,*) CSNOWMETAMO,': you are using F06 formulation!!'\n        !\n        ! XDRDT0(dens,gradT,T), XTAU(dens,gradT,T), XKAPPA(dens,gradT,T)\n        ! dens: [1-8 <-> 50.-400. kg/m3]\n        ! gradT: [1-31 <-> 0.-300. K/m]\n        ! T: [1-11 <-> 223.15-273.15 K]\n        !\n        !  Select indices of density, temperature gradient and temperature\n        IDRHO  = MIN( ABS( INT( (PSNOWRHO(JJ,JST)-25.)/50.        ) + 1 ), 8  )\n        IDGRAD = MIN( ABS( INT( (ZGRADT-5.)/10.+2.                )     ), 31 )\n        IDTEMP = MIN( ABS( INT( (PSNOWTEMP(JJ,JST)-225.65 )/5.+2. )     ), 11 )\n        IF ( PSNOWTEMP(JJ,JST)<221. ) IDTEMP = 1\n        !\n        ! Compute SSA\n        ZOPTR0 = XVDIAM6/2. * 10.**6.\n        ZOPTR  = PSNOWGRAN1(JJ,JST)/2. * 10.**6.\n        ZDRDT  = XDRDT0(IDRHO,IDGRAD,IDTEMP) * &\n                 ( XTAU(IDRHO,IDGRAD,IDTEMP) / &\n                   ( ZOPTR - ZOPTR0 + XTAU(IDRHO,IDGRAD,IDTEMP) ) )**(1./XKAPPA(IDRHO,IDGRAD,IDTEMP))\n        ZOPTR  = ZOPTR + ZDRDT * PTSTEP/3600.\n        ZOPTR  = MIN( ZOPTR, 3./(XRHOLI*2.) * 10.**6.)\n        !\n        PSNOWGRAN1(JJ,JST) = ZOPTR * 2./10.**6.\n        !\n      ENDIF\n      !\n    ENDIF\n    !\n  ENDDO\n  !\nENDDO\n\n!*    2. MISE A JOUR VARIABLES HISTORIQUES (CAS NON DENDRITIQUE).\n!        UPDATE OF THE HISTORICAL VARIABLES\n!        --------------------------------------------------------\nDO JJ = 1,SIZE(PSNOWRHO,1)\n  !\n  DO JST = 1,INLVLS_USE(JJ)\n    !\n    IF ( HSNOWMETAMO=='B92' ) THEN\n      !\n      !non dendritic\n      GNONDENDRITIC = ( PSNOWGRAN1(JJ,JST)>=0. )\n      IF ( GNONDENDRITIC ) THEN\n        !faceted crystals\n        GFACETED = ( PSNOWGRAN1(JJ,JST)<XVSPHE4 .AND. PSNOWHIST(JJ,JST)==0. )\n        !spheric and liquid water\n        GSPHE_LW = ( XVGRAN1-PSNOWGRAN1(JJ,JST)<XVSPHE4 .AND. PSNOWLIQ(JJ,JST)/PSNOWDZ(JJ,JST)>XVTELV1 )\n      END IF\n      !\n    ELSE\n      !\n      !non dendritic\n      GNONDENDRITIC = ( PSNOWGRAN1(JJ,JST)>=XVDIAM6*(4.-PSNOWGRAN2(JJ,JST))-XUEPSI )\n      IF ( GNONDENDRITIC ) THEN\n        !faceted crystals\n        GFACETED = ( PSNOWGRAN2(JJ,JST)<XVSPHE4/XVGRAN1 .AND. PSNOWHIST(JJ,JST)==0. )\n        !spheric and liquid water\n        GSPHE_LW = ( XVSPHE1-PSNOWGRAN2(JJ,JST)<XVSPHE4/XVGRAN1 .AND. PSNOWLIQ(JJ,JST)/PSNOWDZ(JJ,JST)>XVTELV1 )\n      END IF\n      !\n    ENDIF\n    !\n    IF ( GNONDENDRITIC ) THEN\n      !\n      IF ( GFACETED ) THEN\n        !\n        PSNOWHIST(JJ,JST) = NVHIS1\n        !\n      ELSEIF ( GSPHE_LW ) THEN\n        !\n        IF (PSNOWHIST(JJ,JST)==0.)     PSNOWHIST(JJ,JST) = NVHIS2\n        IF (PSNOWHIST(JJ,JST)==NVHIS1) PSNOWHIST(JJ,JST) = NVHIS3\n        !\n      ELSEIF ( PSNOWTEMP(JJ,JST) < XTT ) THEN\n        !\n        IF(PSNOWHIST(JJ,JST)==NVHIS2) PSNOWHIST(JJ,JST) = NVHIS4\n        IF(PSNOWHIST(JJ,JST)==NVHIS3) PSNOWHIST(JJ,JST) = NVHIS5\n        !\n      ENDIF\n      !\n    ENDIF\n    !\n  ENDDO\n  !\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROMETAMO',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROMETAMO\n!\n!####################################################################\n!####################################################################\nSUBROUTINE SET_THRESH(PGRADT,PSNOWLIQ,PSPHE)\n!\nUSE MODD_SNOW_METAMO, ONLY : XUEPSI, XVGRAT1\n!\nIMPLICIT NONE\n!\nREAL, INTENT(IN) :: PGRADT\nREAL, INTENT(IN) :: PSNOWLIQ\nREAL, INTENT(INOUT) :: PSPHE\n!\nIF ( PSNOWLIQ>XUEPSI .OR. PGRADT<XVGRAT1 ) THEN\n  PSPHE = MIN(1.,PSPHE)\nELSE\n  PSPHE = MAX(0.,PSPHE)\nENDIF\n!\nEND SUBROUTINE SET_THRESH\n!####################################################################\n!####################################################################\nSUBROUTINE GET_GRAN(PTSTEP,PTELM,PGRAN)\n!\nUSE MODD_CSTS, ONLY : XPI\nUSE MODD_SNOW_METAMO, ONLY : XVTAIL1, XVTAIL2, NVDENT1\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\nREAL, INTENT(IN)  :: PTSTEP, PTELM\nREAL, INTENT(INOUT) :: PGRAN\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_GRAN',0,ZHOOK_HANDLE)\n!\nPGRAN = 2. * ( 3./(4.*XPI) * &\n                  ( 4. * XPI/3. * (PGRAN/2.)**3 + &\n                   ( XVTAIL1 + XVTAIL2 * PTELM**NVDENT1 ) * PTSTEP ) )**(1./3.)\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_GRAN',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_GRAN\n!\n!####################################################################\n!####################################################################\n!####################################################################\n!\n!SUBROUTINE SNOWCROALB(TPTIME,OGLACIER,                            &\nSUBROUTINE SNOWCROALB(OGLACIER,                            &\n                      PALBEDOSC,PSPECTRALALBEDO,PSNOWDZ,          &\n                      PSNOWRHO,PPERMSNOWFRAC,                     &\n                      PSNOWGRAN1_TOP,PSNOWGRAN2_TOP,PSNOWAGE_TOP, &\n                      PSNOWGRAN1_BOT,PSNOWGRAN2_BOT,PSNOWAGE_BOT, &\n                      PPS, PZENITH, KNLVLS_USE ,HSNOWMETAMO,VIS_ICEALB  )\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the snow surface albedo. Use the method of original\n!     Crocus which considers a specified spectral distribution of solar\n!     solar radiation (to be replaced by an input forcing when available)\n!     In addition to original crocus, the top 2 surface snow layers are\n!     considered in the calculation, using an arbitrary weighting, in order\n!     to avoid time discontinuities due to layers agregation\n!     Ageing depends on the presence of permanent snow cover\n!\nUSE MODD_SNOW_PAR, ONLY : XANSMAX, XANSMIN,XAGLAMIN, XAGLAMAX, &\n                          XVRPRE1,XVRPRE2,XVAGING_NOGLACIER,   &\n                          XVAGING_GLACIER, XVSPEC1,XVSPEC2,    &\n                          XVSPEC3, XVW1,XVW2,XVD1,XVD2\n\n!USE MODI_INI_CSTS, ONLY: XANSMAX, XANSMIN,XAGLAMIN, XAGLAMAX, &\n!                       XVAGING_NOGLACIER,   &\n!                       XVAGING_GLACIER\n\n\n!USE MODD_TYPE_DATE_SURF, ONLY : DATE_TIME\n!\nUSE MODE_SNOW3L\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\n!TYPE(DATE_TIME), INTENT(IN)       :: TPTIME      ! current date and time\nLOGICAL, INTENT(IN)               :: OGLACIER    ! True = Over permanent snow and ice,\n!                                                   initialise WGI=WSAT,\n!                                                   Hsnow>=10m and allow 0.8<SNOALB<0.85\n                                                 ! False = No specific treatment\nREAL, DIMENSION(:), INTENT(IN)    :: PSNOWDZ,PPERMSNOWFRAC\n!\nREAL,DIMENSION(:,:), INTENT(IN)   :: PSNOWRHO ! For now only the 2 first layers are required\n!\nREAL, DIMENSION(:), INTENT(INOUT) :: PALBEDOSC\n!\nREAL, DIMENSION(:,:), INTENT(OUT) :: PSPECTRALALBEDO   ! Albedo in the different spectral bands\n!\nREAL, DIMENSION(:), INTENT(IN)    :: PSNOWGRAN1_TOP,PSNOWGRAN2_TOP,PSNOWAGE_TOP, &\n                                     PSNOWGRAN1_BOT,PSNOWGRAN2_BOT,PSNOWAGE_BOT, PPS\nINTEGER, DIMENSION(:), INTENT(IN) :: KNLVLS_USE\n!\nREAL, DIMENSION(:), INTENT(IN)    :: PZENITH ! solar zenith angle for future use\n!\n CHARACTER(3),INTENT(IN)           :: HSNOWMETAMO ! metamorphism scheme\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),3) :: ZALB_TOP, ZALB_BOT\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1))   :: ZANSMIN, ZANSMAX, ZMIN, ZMAX\nREAL, DIMENSION(SIZE(PSNOWRHO,1))   :: ZFAC_TOP, ZFAC_BOT\n!\nREAL, DIMENSION(SIZE(PALBEDOSC))  :: ZVAGE1\n!\n!REAL            :: ZAGE_NOW\n!\nINTEGER         :: JJ   ! looping indexes\n\n!++ trude, crocus\nREAL, DIMENSION(:), INTENT(IN), OPTIONAL   :: VIS_ICEALB\n!-- trude\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROALB',0,ZHOOK_HANDLE)\n!\n! 0. Initialize:\n! ------------------\n!\nIF ( OGLACIER ) THEN\n  ZANSMIN(:) = XAGLAMIN * PPERMSNOWFRAC(:) + XANSMIN * (1.0-PPERMSNOWFRAC(:))\n  ZANSMAX(:) = XAGLAMAX * PPERMSNOWFRAC(:) + XANSMAX * (1.0-PPERMSNOWFRAC(:))\n  ZVAGE1(:)  = XVAGING_GLACIER * PPERMSNOWFRAC(:) + XVAGING_NOGLACIER * (1.0-PPERMSNOWFRAC(:))\nELSE\n  ZANSMIN(:) = XANSMIN\n  ZANSMAX(:) = XANSMAX\n  ZVAGE1(:)  = XVAGING_NOGLACIER\nENDIF\n!\n! ! ! ! ! !  date computation for ageing effects\n! ! ! ! !   CALL GREGODSTRATI(TPTIME%TDATE%YEAR,TPTIME%TDATE%MONTH,TPTIME%TDATE%DAY,   &\n! ! ! ! !                       TPTIME%TIME,ZAGE_NOW)\n!\n! coherence control\n! to remove when initialization routines will be updated\nIF ( MINVAL(PSNOWAGE_BOT)<0. ) THEN\n!  CALL ABOR1_SFX('FATAL ERROR in SNOWCRO: Snow layer age inconsistent : check initialization routine. !')\nEND IF\n!\n! ! ! ! ! ! should be moved with other time controls to not compute MAXVAL(PSNOWAGE_TOP) at each time step\n! ! ! ! ! IF ((ZAGE_NOW - MAXVAL(PSNOWAGE_TOP))<-0.001) THEN\n! ! ! ! !       WRITE(*,*),\"ZAGE_NOW=\",ZAGE_NOW\n! ! ! ! !       WRITE(*,*),\"MAXVAL(PSNOWAGE_TOP)=\",MAXVAL(PSNOWAGE_TOP)\n! ! ! ! !       CALL ABOR1_SFX(&\n! ! ! ! !       'FATAL ERROR in SNOWCRO: Snow layer date inconsistent with the current day !')\n! ! ! ! ! END IF\n!\nDO JJ=1, SIZE(PALBEDOSC)\n  !\n  IF ( KNLVLS_USE(JJ)==0 ) THEN\n    ! case with no snow on the ground\n    PALBEDOSC(JJ) = ZANSMIN(JJ)\n  ELSE\n    !\n    CALL GET_ALB(JJ,PSNOWRHO(JJ,1),PPS(JJ),ZVAGE1(JJ),PSNOWGRAN1_TOP(JJ),&\n                 PSNOWGRAN2_TOP(JJ),PSNOWAGE_TOP(JJ),ZALB_TOP(JJ,:),HSNOWMETAMO,VIS_ICEALB)\n     !\n!      IF (KNLVLS_USE(JJ)>=1) THEN\n    IF ( KNLVLS_USE(JJ)>=2 ) THEN !modif ML\n      ! second surface layer when it exists\n      !\n      CALL GET_ALB(JJ,PSNOWRHO(JJ,2),PPS(JJ),ZVAGE1(JJ),PSNOWGRAN1_BOT(JJ),&\n                   PSNOWGRAN2_BOT(JJ),MIN(365.,PSNOWAGE_BOT(JJ)),ZALB_BOT(JJ,:),HSNOWMETAMO,VIS_ICEALB)\n      !\n    ELSE\n      ! when it does not exist, the second surface layer gets top layer albedo\n      ZALB_BOT(JJ,1) = ZALB_TOP(JJ,1)\n      ZALB_BOT(JJ,2) = ZALB_TOP(JJ,2)\n      ZALB_BOT(JJ,3) = ZALB_TOP(JJ,3)\n    ENDIF\n    !\n    ! computation of spectral albedo over 3 bands taking into account the respective\n    ! depths of top layers\n    ZMIN(JJ) = MIN( 1., PSNOWDZ(JJ)/XVD1 )\n    ZMAX(JJ) = MAX( 0., (PSNOWDZ(JJ)-XVD1)/XVD2 )\n    ZFAC_TOP(JJ) = XVW1 * ZMIN(JJ) + XVW2 * MIN( 1., ZMAX(JJ) )\n    ZFAC_BOT(JJ) = XVW1 * ( 1. - ZMIN(JJ) ) + XVW2 * ( 1. - MIN( 1., ZMAX(JJ) ) )\n    PSPECTRALALBEDO(JJ,1) = ZFAC_TOP(JJ) * ZALB_TOP(JJ,1) + ZFAC_BOT(JJ) * ZALB_BOT(JJ,1)\n    PSPECTRALALBEDO(JJ,2) = ZFAC_TOP(JJ) * ZALB_TOP(JJ,2) + ZFAC_BOT(JJ) * ZALB_BOT(JJ,2)\n    PSPECTRALALBEDO(JJ,3) = ZFAC_TOP(JJ) * ZALB_TOP(JJ,3) + ZFAC_BOT(JJ) * ZALB_BOT(JJ,3)\n    !\n    ! arbitrarily specified spectral distribution\n    ! to be changed when solar radiation distribution is an input variable\n    PALBEDOSC(JJ) = XVSPEC1 * PSPECTRALALBEDO(JJ,1) + &\n                    XVSPEC2 * PSPECTRALALBEDO(JJ,2) + &\n                    XVSPEC3 * PSPECTRALALBEDO(JJ,3)\n    !\n  ENDIF ! end case with snow on the ground\n  !\nENDDO ! end loop grid points\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROALB',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SNOWCROALB\n!####################################################################\nSUBROUTINE GET_ALB(KJ,PSNOWRHO_IN,PPS_IN,PVAGE1,PSNOWGRAN1,PSNOWGRAN2,PSNOWAGE,PALB,&\n                   HSNOWMETAMO,VIS_ICEALB)\n!\nUSE MODD_CSTS, ONLY :                           XRHOTHRESHOLD_ICE   ! trude, changed the location of this\nUSE MODD_SNOW_PAR, ONLY : XALBICE1, XALBICE2, XALBICE3,   &\n!                          XRHOTHRESHOLD_ICE,              &   ! trude changed location of xrhothershold_ice\n                          XVALB2, XVALB3, XVALB4, XVALB5, &\n                          XVALB6, XVALB7, XVALB8, XVALB9, &\n                          XVALB10, XVALB11, XVDIOP1,      &\n                          XVRPRE1, XVRPRE2, XVPRES1\n!\nUSE MODE_SNOW3L, ONLY : GET_DIAM\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\nINTEGER, INTENT(IN) :: KJ\nREAL, INTENT(IN) :: PSNOWRHO_IN, PPS_IN\nREAL, INTENT(IN) :: PVAGE1\nREAL, INTENT(IN) :: PSNOWGRAN1, PSNOWGRAN2, PSNOWAGE\nREAL, DIMENSION(3), INTENT(OUT) :: PALB\n!\n CHARACTER(3),INTENT(IN)::HSNOWMETAMO\n !\nREAL :: ZDIAM, ZDIAM_SQRT\n\n!++ trude, crocus\nREAL, DIMENSION(:), INTENT(IN), OPTIONAL   :: VIS_ICEALB\n!-- trude\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_ALB',0,ZHOOK_HANDLE)\n!\nIF ( PSNOWRHO_IN<XRHOTHRESHOLD_ICE ) THEN\n  ! Normal case (snow)\n  CALL GET_DIAM(PSNOWGRAN1,PSNOWGRAN2,ZDIAM,HSNOWMETAMO)\n  ZDIAM_SQRT = SQRT(ZDIAM)\n  PALB(1) = MIN( XVALB2 - XVALB3*ZDIAM_SQRT, XVALB4 )\n  PALB(2) = MAX( 0.3, XVALB5 - XVALB6*ZDIAM_SQRT )\n  ZDIAM   = MIN( ZDIAM, XVDIOP1 )\n  ZDIAM_SQRT = SQRT(ZDIAM)\n  PALB(3) = MAX( 0., XVALB7*ZDIAM - XVALB8*ZDIAM_SQRT + XVALB9 )\n ! AGE CORRECTION ONLY FOR VISIBLE BAND\n\n! ! ! ! !               PALB(1)=MAX(XVALB11,PALB(1)-MIN(MAX(PPS_IN/XVPRES1,XVRPRE1), &\n! ! ! ! !                       XVRPRE2)*XVALB10*MIN(365.,ZAGE_NOW-PSNOWAGE)/PVAGE1)\n\n\n  PALB(1) = MAX( XVALB11, PALB(1) - MIN( MAX(PPS_IN/XVPRES1,XVRPRE1), XVRPRE2 ) * &\n                   XVALB10 * PSNOWAGE / PVAGE1 )\nELSE\n  ! Prescribed spectral albedo for surface ice\n  !! ++ trude, crocus\n\n\nif (isnan(VIS_ICEALB(1))) then\n  PALB(1) = XALBICE1\n  elseif (VIS_ICEALB(1).le.0.0) THEN\n  PALB(1) = XALBICE1\nelse\n  PALB(1) = VIS_ICEALB(1)\nendif\n\n  PALB(2) = XALBICE2\n  PALB(3) = XALBICE3\nENDIF\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_ALB',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_ALB\n!\n!####################################################################\n!####################################################################\n!SUBROUTINE SNOWCRORAD(TPTIME, OGLACIER,                        &\nSUBROUTINE SNOWCRORAD(OGLACIER,                        &\n                      PSW_RAD, PSNOWALB, PSNOWDZ,              &\n                      PSNOWRHO, PALB, PRADSINK, PRADXS,        &\n                      PSNOWGRAN1, PSNOWGRAN2, PSNOWAGE,PPS,    &\n                      PZENITH, PPERMSNOWFRAC,KNLVLS_USE,       &\n                      OSNOW_ABS_ZENITH,HSNOWMETAMO,VIS_ICEALB)\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the transmission of shortwave (solar) radiation\n!     through the snowpack (using a form of Beer's Law: exponential\n!     decay of radiation with increasing snow depth).\n!     Needs a first calculation of the albedo to stay coherent with\n!     ISBA-ES ==> make sure to keep SNOWCRORAD coherent with SNOWCROALB\n!\nUSE MODD_SNOW_PAR, ONLY : XWCRN, XANSMAX, XANSMIN, XANS_TODRY,          &\n                          XSNOWDMIN, XANS_T, XAGLAMIN, XAGLAMAX,        &\n                          XD1, XD2, XD3, XX, XVSPEC1, XVSPEC2, XVSPEC3, &\n                          XVBETA1, XVBETA2, XVBETA3, XVBETA4, XVBETA5\n!USE MODD_TYPE_DATE_SURF, ONLY : DATE_TIME\n!\nUSE MODE_SNOW3L, ONLY : GET_DIAM\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\n!TYPE(DATE_TIME), INTENT(IN)       :: TPTIME      ! current date and time\nLOGICAL, INTENT(IN)               :: OGLACIER   ! True = Over permanent snow and ice,\n!                                                   initialise WGI=WSAT,\n!                                                   Hsnow>=10m and allow 0.8<SNOALB<0.85\n                                                ! False = No specific treatment\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PSW_RAD, PSNOWALB, PALB,PPERMSNOWFRAC\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWRHO, PSNOWDZ\n!\nLOGICAL, INTENT(IN)                 :: OSNOW_ABS_ZENITH ! parametrization for polar regions (not physic but better results)\n!                                                       ! default FALSE\n CHARACTER(3), INTENT(IN)            :: HSNOWMETAMO\n!\nREAL, DIMENSION(:), INTENT(OUT)     :: PRADXS\n!\nREAL, DIMENSION(:,:), INTENT(OUT)   :: PRADSINK\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWGRAN1, PSNOWGRAN2, PSNOWAGE\nREAL, DIMENSION(:), INTENT(IN)      :: PPS\nINTEGER, DIMENSION(:), INTENT(IN)   :: KNLVLS_USE\nREAL, DIMENSION(:), INTENT(IN)      :: PZENITH\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1))    :: ZRADTOT\nREAL, DIMENSION(SIZE(PSNOWRHO,1))    :: ZALB_NEW\nREAL, DIMENSION(SIZE(PSNOWRHO,1),3)  :: ZALB !albedo 3 bands\nREAL, DIMENSION(SIZE(PSNOWRHO,2))    :: ZDIAM\nREAL, DIMENSION(SIZE(PSNOWRHO,2),3)  :: ZBETA\nREAL, DIMENSION(3) :: ZOPTICALPATH, ZFACT\nREAL :: ZPROJLAT\n!\nINTEGER :: JJ,JST,JB   ! looping indexes\n\n!++ trude, crocus\n\nREAL, DIMENSION(:), INTENT(IN), OPTIONAL   :: VIS_ICEALB   !-- trude!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCRORAD',0,ZHOOK_HANDLE)\n!\n! 0. Initialization:\n! ------------------\n!\nPRADSINK(:,:) = 0.\n!\n! 1. Computation of the new albedo (see SNOWCROALB):\n! -----------------------------------\n!\n! CALL SNOWCROALB(TPTIME,OGLACIER,                                             &\nCALL SNOWCROALB(OGLACIER,                                             &\n                 ZALB_NEW,ZALB,PSNOWDZ(:,1),PSNOWRHO(:,1:2),                  &\n                 PPERMSNOWFRAC,PSNOWGRAN1(:,1),PSNOWGRAN2(:,1),               &\n                 PSNOWAGE(:,1),PSNOWGRAN1(:,2),PSNOWGRAN2(:,2),PSNOWAGE(:,2), &\n                 PPS, PZENITH, KNLVLS_USE, HSNOWMETAMO, VIS_ICEALB     )\n!\nDO JJ = 1,SIZE(PSW_RAD)\n\n  !\n  DO JST = 1,KNLVLS_USE(JJ)\n    CALL GET_DIAM(PSNOWGRAN1(JJ,JST),PSNOWGRAN2(JJ,JST),ZDIAM(JST),HSNOWMETAMO)\n  ENDDO    ! end loop snow layers\n  !\n  ! 2. Extinction of net shortwave radiation\n  ! ----------------------------------------\n  ! First calculates extinction coefficients fn of grain size and density\n  ! then calculates exctinction in the layer and increases optical path length\n  !\n  ! Coefficient for taking into account the increase of path length of rays\n  ! in snow due to zenithal angle\n  ZPROJLAT = 1. / MAX( XUEPSI, COS(PZENITH(JJ)) )\n  !\n  PRADSINK(JJ,:) = -PSW_RAD(JJ) * ( 1.-PSNOWALB(JJ) ) / ( 1.-ZALB_NEW(JJ) )\n  !\n  !   Initialize optical depth\n  ZOPTICALPATH(1) = 0.\n  ZOPTICALPATH(2) = 0.\n  ZOPTICALPATH(3) = 0.\n  !\n  DO JST = 1,KNLVLS_USE(JJ)\n    !\n    ZBETA(JST,1) = MAX( XVBETA1 * PSNOWRHO(JJ,JST) / SQRT(ZDIAM(JST)), XVBETA2 )\n    ZBETA(JST,2) = MAX( XVBETA3 * PSNOWRHO(JJ,JST) / SQRT(ZDIAM(JST)), XVBETA4 )\n    ZBETA(JST,3) = XVBETA5\n    !\n    ZFACT(:) = 0.\n    DO JB = 1,3\n      ZOPTICALPATH(JB) = ZOPTICALPATH(JB) + ZBETA(JST,JB) * PSNOWDZ(JJ,JST)\n      IF (OSNOW_ABS_ZENITH) THEN\n        !This formulation is incorrect but it compensate partly the fact that the albedo formulation does not account for zenithal angle\n        ZFACT(JB) = (1.-ZALB(JJ,JB)) * EXP( -ZOPTICALPATH(JB)*ZPROJLAT)\n      ELSE\n        ZFACT(JB) = (1.-ZALB(JJ,JB)) * EXP( -ZOPTICALPATH(JB) )\n      ENDIF\n    ENDDO\n    !\n    PRADSINK(JJ,JST) = PRADSINK(JJ,JST) * &\n                       ( XVSPEC1*ZFACT(1) + XVSPEC2*ZFACT(2) + XVSPEC3*ZFACT(3) )\n    !\n  ENDDO    ! end loop snow layers\n  !\n  ! For thin snow packs, radiation might reach base of\n  ! snowpack and the reflected energy can be absorbed by the bottom of snow layer:\n  ! THIS PROCESS IS NOT SIMULATED\n  !\n  ! 4. Excess radiation not absorbed by snowpack (W/m2)JJ\n  ! ----------------------------------------------------\n  !\n  PRADXS(JJ) = -PRADSINK( JJ,KNLVLS_USE(JJ) )\n  !\nENDDO    !end loop grid points\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRORAD',1,ZHOOK_HANDLE)\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SNOWCRORAD\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROTHRM(PSNOWRHO,PSCOND,PSNOWTEMP,PPS,PSNOWLIQ, &\n                       OCOND_GRAIN,OCOND_YEN                   )\n!\n!!    PURPOSE\n!!    -------\n!     Calculate snow thermal conductivity from\n!     Sun et al. 1999, J. of Geophys. Res., 104, 19587-19579\n!     (vapor) and Anderson, 1976, NOAA Tech. Rep. NWS 19 (snow).\n!\n!     Upon activation of flag OCOND_YEN, use the Yen (1981) formula for thermal conductivity\n!     This formula was originally used in Crocus.\n!\nUSE MODD_CSTS, ONLY : XP00, XCONDI, XRHOLW\nUSE MODD_SNOW_PAR, ONLY : XSNOWTHRMCOND1, XSNOWTHRMCOND2, XSNOWTHRMCOND_AVAP, &\n                          XSNOWTHRMCOND_BVAP, XSNOWTHRMCOND_CVAP, XVRKZ6\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PPS\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWTEMP, PSNOWRHO, PSNOWLIQ\nREAL, DIMENSION(:,:), INTENT(OUT)   :: PSCOND\nLOGICAL, INTENT(IN)                 :: OCOND_GRAIN, OCOND_YEN\n!\n!*      0.2    declarations of local variables\n!\nINTEGER :: JJ, JST ! looping indexes\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCROTHRM',0,ZHOOK_HANDLE)\n!\n! 1. Snow thermal conductivity\n! ----------------------------\n!\nDO JST = 1,SIZE(PSNOWRHO(:,:),2)\n  !\n  DO JJ = 1,SIZE(PSNOWRHO(:,:),1)\n    !\n    IF ( OCOND_YEN ) THEN\n      PSCOND(JJ,JST) = XCONDI * EXP( XVRKZ6 * LOG( PSNOWRHO(JJ,JST)/XRHOLW ) )\n    ELSE\n      PSCOND(JJ,JST) = ( XSNOWTHRMCOND1 + &\n                         XSNOWTHRMCOND2 * PSNOWRHO(JJ,JST) * PSNOWRHO(JJ,JST) ) + &\n                         MAX( 0.0, ( XSNOWTHRMCOND_AVAP + &\n                                    ( XSNOWTHRMCOND_BVAP/(PSNOWTEMP(JJ,JST) + XSNOWTHRMCOND_CVAP) ) ) &\n                                   * (XP00/PPS(JJ)) )\n    ENDIF\n    !\n    ! Snow thermal conductivity is set to be above 0.04 W m-1 K-1\n    IF ( OCOND_GRAIN ) THEN\n      PSCOND(JJ,JST) = MAX( 0.04, PSCOND(JJ,JST) )\n      ! Snow thermal conductivity is annihilated in presence of liquid water\n      IF( PSNOWLIQ(JJ,JST)>XUEPSI ) PSCOND(JJ,JST) = 0.01 * PSCOND(JJ,JST)\n    ENDIF\n     !\n   ENDDO ! end loop JST\n   !\nENDDO ! end loop JST\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROTHRM',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROTHRM\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROEBUD(HSNOWRES, HIMPLICIT_WIND,                                   &\n                       PPEW_A_COEF, PPEW_B_COEF,                                   &\n                       PPET_A_COEF, PPEQ_A_COEF, PPET_B_COEF, PPEQ_B_COEF,         &\n                       PSNOWDZMIN,                                                 &\n                       PZREF,PTS,PSNOWRHO,PSNOWLIQ,PSCAP,PSCOND1,PSCOND2,          &\n                       PUREF,PEXNS,PEXNA,PDIRCOSZW,PVMOD,                          &\n                       PLW_RAD,PSW_RAD,PTA,PQA,PPS,PTSTEP,                         &\n                       PSNOWDZ1,PSNOWDZ2,PALBT,PZ0,PZ0EFF,PZ0H,                    &\n                       PSFCFRZ,PRADSINK,PHPSNOW,                                   &\n                       PCT,PEMIST,PRHOA,PTSTERM1,PTSTERM2,PRA,PCDSNOW,PCHSNOW,     &\n                       PQSAT,PDQSAT,PRSRA,PUSTAR2_IC, PRI,                         &\n                       PPET_A_COEF_T,PPEQ_A_COEF_T,PPET_B_COEF_T,PPEQ_B_COEF_T     )\n!\n!!    PURPOSE\n!!    -------\n!     Calculate surface energy budget linearization (terms) and turbulent\n!     exchange coefficients/resistance between surface and atmosphere.\n!     (Noilhan and Planton 1989; Giordani 1993; Noilhan and Mahfouf 1996)\n!\n!!    MODIFICATIONS\n!!    -------------\n!!      Original A. Boone\n!!      Modified by E. Brun (24/09/2012) :\n!!      * Correction coupling coefficient for specific humidity in SNOWCROEBUD\n!!      * PSFCFRZ(:)  = 1.0 for systematic solid/vapor latent fluxes in SNOWCROEBUD\n!!      Modified by B. Decharme 09/12  new wind implicitation\n!\n!USE MODD_SURF_PAR, ONLY : XUNDEF\nUSE MODD_CSTS,     ONLY : XCPD, XRHOLW, XSTEFAN, XLVTT, XLSTT, XRHOLW\nUSE MODD_SNOW_PAR, ONLY : X_RI_MAX, XEMISSN,XUNDEF\n!\nUSE MODE_THERMOS\n!\n!USE MODI_SURFACE_RI\n!USE MODI_SURFACE_AERO_COND\n!USE MODI_SURFACE_CD\nUSE MODE_SURF_COEFS\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                   :: PTSTEP, PSNOWDZMIN\n!\n CHARACTER(LEN=*),     INTENT(IN)  :: HSNOWRES ! type of sfc resistance\n!                                      DEFAULT=Louis (1979), standard ISBA\n!                                      method. Option to limit Ri number\n!                                      for very stable conditions\n!\n CHARACTER(LEN=*),     INTENT(IN)  :: HIMPLICIT_WIND   ! wind implicitation option\n!                                                     ! 'OLD' = direct\n!                                                     ! 'NEW' = Taylor serie, order 1\n!\nREAL, DIMENSION(:), INTENT(IN)     :: PPEW_A_COEF, PPEW_B_COEF,                   &\n                                      PPET_A_COEF, PPEQ_A_COEF, PPET_B_COEF,      &\n                                      PPEQ_B_COEF\n!                                      PPEW_A_COEF = wind coefficient (m2s/kg)\n!                                      PPEW_B_COEF = wind coefficient (m/s)\n!                                      PPET_A_COEF = A-air temperature coefficient\n!                                      PPET_B_COEF = B-air temperature coefficient\n!                                      PPEQ_A_COEF = A-air specific humidity coefficient\n!                                      PPEQ_B_COEF = B-air specific humidity coefficient\n!\nREAL, DIMENSION(:), INTENT(IN)     :: PZREF, PTS, PSNOWDZ1, PSNOWDZ2,        &\n                                      PRADSINK, PSNOWRHO, PSNOWLIQ, PSCAP,   &\n                                      PSCOND1, PSCOND2,                      &\n                                      PZ0, PHPSNOW,                          &\n                                      PALBT, PZ0EFF, PZ0H\n!\nREAL, DIMENSION(:), INTENT(IN)     :: PSW_RAD, PLW_RAD, PTA, PQA, PPS, PRHOA\n!\nREAL, DIMENSION(:), INTENT(IN)     :: PUREF, PEXNS, PEXNA, PDIRCOSZW, PVMOD\n!\nREAL, DIMENSION(:), INTENT(OUT)    :: PTSTERM1, PTSTERM2, PEMIST, PRA,         &\n                                      PCT, PSFCFRZ, PCDSNOW, PCHSNOW,          &\n                                      PQSAT, PDQSAT, PRSRA\n!\nREAL, DIMENSION(:), INTENT(OUT)    :: PUSTAR2_IC,                      &\n                                      PPET_A_COEF_T, PPEQ_A_COEF_T,    &\n                                      PPET_B_COEF_T, PPEQ_B_COEF_T\n!\nREAL, DIMENSION(:), INTENT(OUT)    :: PRI\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PTS))        :: ZAC, ZRI,                        &\n                                     ZSCONDA, ZA, ZB, ZC,             &\n                                     ZCDN, ZSNOWDZM1, ZSNOWDZM2,      &\n                                     ZVMOD, ZUSTAR2, ZTS3, ZLVT,      &\n                                     Z_CCOEF\nREAL, DIMENSION(SIZE(PTS))        :: ZSNOWEVAPX, ZDENOM, ZNUMER\n!\nINTEGER :: JJ   ! looping indexes\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n! 1. New saturated specific humidity and derrivative:\n! ---------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROEBUD',0,ZHOOK_HANDLE)\n!\nZRI   (:) = XUNDEF\n!\nPQSAT (:) = QSATI(PTS(:),PPS(:))\nPDQSAT(:) = DQSATI(PTS(:),PPS(:),PQSAT(:))\n!\n! 2. Surface properties:\n! ----------------------\n! It might be of interest to use snow-specific roughness\n! or a temperature dependence on emissivity:\n! but for now, use ISBA defaults.\n!\nPEMIST(:) = XEMISSN\n!\n! 2. Computation of resistance and drag coefficient\n! -------------------------------------------------\n!\n CALL SURFACE_RI(PTS, PQSAT, PEXNS, PEXNA, PTA, PQA,  &\n                 PZREF, PUREF, PDIRCOSZW, PVMOD, ZRI  )\n!\n! Simple adaptation of method by Martin and Lejeune (1998)\n! to apply a lower limit to turbulent transfer coef\n! by defining a maximum Richarson number for stable\n! conditions:\n!\nIF ( HSNOWRES=='RIL' ) THEN\n  DO JJ=1,SIZE(ZRI)\n    ZRI(JJ) = MIN( X_RI_MAX, ZRI(JJ) )\n  ENDDO\nENDIF\n!\nPRI(:) = ZRI(:)\n!\n! Surface aerodynamic resistance for heat transfers\n!\n CALL SURFACE_AERO_COND(ZRI, PZREF, PUREF, PVMOD, PZ0, PZ0H, ZAC, PRA, PCHSNOW)\n!\n\nPRSRA(:) = PRHOA(:) / PRA(:)\n!\n! For atmospheric model coupling:\n!\n CALL SURFACE_CD(ZRI, PZREF, PUREF, PZ0EFF, PZ0H, PCDSNOW, ZCDN)\n!\n!\n! Modify flux-form implicit coupling coefficients:\n! - wind components:\n!\nZNUMER(:) = PCDSNOW(:)*PVMOD(:)\nZDENOM(:) = PRHOA(:) * PCDSNOW(:) * PVMOD(:) * PPEW_A_COEF(:)\nIF(HIMPLICIT_WIND=='OLD')THEN\n! old implicitation\n  ZUSTAR2(:) = ( ZNUMER(:) * PPEW_B_COEF(:) ) / ( 1.0 - ZDENOM(:) )\nELSE\n! new implicitation\n  ZUSTAR2(:) = ( ZNUMER(:) * ( 2.*PPEW_B_COEF(:) - PVMOD(:) ) ) / ( 1.0 - 2.0*ZDENOM(:) )\nENDIF\n\n!\nZVMOD(:) = PRHOA(:)*PPEW_A_COEF(:)*ZUSTAR2(:) + PPEW_B_COEF(:)\nZVMOD(:) = MAX( ZVMOD(:),0. )\n!\n\nWHERE ( PPEW_A_COEF(:)/= 0. )\n  ZUSTAR2(:) = MAX( ( ZVMOD(:) - PPEW_B_COEF(:) ) / (PRHOA(:)*PPEW_A_COEF(:)), 0. )\nENDWHERE\n!\n! implicit wind friction\nZUSTAR2(:) = MAX( ZUSTAR2(:),0. )\n!\nPUSTAR2_IC(:) = ZUSTAR2(:)\n!\n! 3. Calculate linearized surface energy budget components:\n! ---------------------------------------------------------\n! To prevent numerical difficulties for very thin snow\n! layers, limit the grid \"thinness\": this is important as\n! layers become vanishing thin:\n!\nZSNOWDZM1(:) = MAX( PSNOWDZ1(:), PSNOWDZMIN )\nZSNOWDZM2(:) = MAX( PSNOWDZ2(:), PSNOWDZMIN )\n!\n! Surface thermal inertia:\nPCT(:) = 1.0 / ( PSCAP(:)*ZSNOWDZM1(:) )\n!\n! Fraction of surface frozen (sublimation) with the remaining\n! fraction being liquid (evaporation):\n!\nPSFCFRZ(:) = 1.0\n!\n! Thermal conductivity between uppermost and lower snow layers:\n!\nZSCONDA(:) = ( ZSNOWDZM1(:)*PSCOND1(:) + ZSNOWDZM2(:)*PSCOND2(:) ) / &\n             ( ZSNOWDZM1(:)            + ZSNOWDZM2(:)            )\n!\n! Transform implicit coupling coefficients:\n! Note, surface humidity is 100% over snow.\n!\n! - specific humidity:\n!\nZ_CCOEF(:) = 1.0 - PPEQ_A_COEF(:) * PRSRA(:)\n!\nPPEQ_A_COEF_T(:) = - PPEQ_A_COEF(:) * PRSRA(:) * PDQSAT(:) / Z_CCOEF(:)\n!\nPPEQ_B_COEF_T(:) = ( PPEQ_B_COEF(:) &\n                   - PPEQ_A_COEF(:) * PRSRA(:) * (PQSAT(:) - PDQSAT(:)*PTS(:)) ) / Z_CCOEF(:)\n!\n! - air temperature:\n!   (assumes A and B correspond to potential T):\n!\nZ_CCOEF(:) = ( 1.0 - PPET_A_COEF(:) * PRSRA(:) ) / PEXNA(:)\n!\nPPET_A_COEF_T(:) = - PPET_A_COEF(:) * PRSRA(:) / ( PEXNS(:) * Z_CCOEF(:) )\n!\nPPET_B_COEF_T(:) = PPET_B_COEF(:) / Z_CCOEF(:)\n!\n!\n! Energy budget solution terms:\n!\nZTS3(:) = PEMIST(:) * XSTEFAN * PTS(:)**3\nZLVT(:) = (1.-PSFCFRZ(:))*XLVTT + PSFCFRZ(:)*XLSTT\n!\nZA(:) = 1./PTSTEP + PCT(:) * &\n         ( 4. * ZTS3(:) + PRSRA(:) * ZLVT(:) * ( PDQSAT(:) - PPEQ_A_COEF_T(:) )            &\n                        + PRSRA(:) * XCPD * ( (1./PEXNS(:))-(PPET_A_COEF_T(:)/PEXNA(:)) )  &\n                        + ( 2*ZSCONDA(:) / ( ZSNOWDZM2(:)+ZSNOWDZM1(:) ) ) )\n!\nZB(:) = 1./PTSTEP + PCT(:) * &\n         ( 3. * ZTS3(:) + PRSRA(:) * ZLVT(:) * PDQSAT(:) )\n!\nZC(:) = PCT(:) * ( - PRSRA(:) * ZLVT(:) * ( PQSAT(:) - PPEQ_B_COEF_T(:) )  &\n                   + PRSRA(:) * XCPD * PPET_B_COEF_T(:) / PEXNA(:)         &\n                   + PSW_RAD(:) * (1. - PALBT(:)) + PEMIST(:) * PLW_RAD(:) &\n                   + PHPSNOW(:) + PRADSINK(:) )\n!\n!\n! Coefficients needed for implicit solution\n! of linearized surface energy budget:\n!\nPTSTERM2(:) = 2. * ZSCONDA(:) * PCT(:) / ( ZA(:) * (ZSNOWDZM2(:)+ZSNOWDZM1(:) ) )\n!\nPTSTERM1(:) = ( PTS(:)*ZB(:) + ZC(:) ) / ZA(:)\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROEBUD',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROEBUD\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROSOLVT(PTSTEP,PSNOWDZMIN,                     &\n                        PSNOWDZ,PSCOND,PSCAP,PTG,              &\n                        PSOILCOND,PD_G,                        &\n                        PRADSINK,PCT,PTERM1,PTERM2,            &\n                        PPET_A_COEF_T,PPEQ_A_COEF_T,           &\n                        PPET_B_COEF_T,PPEQ_B_COEF_T,           &\n                        PTA_IC, PQA_IC,                        &\n                        PGBAS,PSNOWTEMP,PSNOWFLUX,             &\n                        KNLVLS_USE                             )\n!\n!!    PURPOSE\n!!    -------\n!     This subroutine solves the 1-d diffusion of 'ZSNOWTEMP' using a\n!     layer averaged set of equations which are time differenced\n!     using the backward-difference scheme (implicit).\n!     The eqs are solved rapidly by taking advantage of the\n!     fact that the matrix is tridiagonal. This is a very\n!     general routine and can be used for the 1-d diffusion of any\n!     quantity as long as the diffusity is not a function of the\n!     quantity being diffused. Aaron Boone 8-98. Soln to the eq:\n!\n!                 c  dQ    d  k dQ    dS\n!                    -- =  --   -- -  --\n!                    dt    dx   dx    dx\n!\n!     where k = k(x) (thermal conductivity), c = c(x) (heat capacity)\n!     as an eg. for temperature/heat eq. S is a sink (-source) term.\n!     Diffusivity is k/c\n!\n!!     MODIFICATIONS\n!!     -------------\n!!      Original A. Boone\n!!       05/2011: Brun  Special treatment to tackle the variable number\n!!                      of snow layers\n!\nUSE MODD_CSTS, ONLY : XTT\n!\nUSE MODI_TRIDIAG_GROUND_SNOWCRO\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                    :: PTSTEP, PSNOWDZMIN\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PTG, PSOILCOND, PD_G,        &\n                                        PCT, PTERM1, PTERM2\n\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWDZ, PSCOND, PSCAP,      &\n                                        PRADSINK\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PPET_A_COEF_T, PPEQ_A_COEF_T, &\n                                        PPET_B_COEF_T, PPEQ_B_COEF_T\n!\nREAL, DIMENSION(:,:), INTENT(INOUT) :: PSNOWTEMP\n!\nREAL, DIMENSION(:), INTENT(OUT)     :: PGBAS, PSNOWFLUX, PTA_IC, PQA_IC\n!\nINTEGER, DIMENSION(:), INTENT(IN)   :: KNLVLS_USE\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWDZ,1),SIZE(PSNOWDZ,2)) :: ZSNOWTEMP, ZDTERM, ZCTERM, &\n                                                    ZFRCV, ZAMTRX, ZBMTRX,     &\n                                                    ZCMTRX\n!\nREAL, DIMENSION(SIZE(PSNOWDZ,1),SIZE(PSNOWDZ,2)) :: ZWORK1, ZWORK2, ZDZDIF,    &\n                                                    ZSNOWDZM\n!\nREAL, DIMENSION(SIZE(PSNOWDZ,1),SIZE(PSNOWDZ,2)-1) :: ZSNOWTEMP_M,             &\n                                                      ZFRCV_M, ZAMTRX_M,       &\n                                                      ZBMTRX_M, ZCMTRX_M\n!\nREAL, DIMENSION(SIZE(PTG)) :: ZGBAS, ZSNOWTEMP_DELTA\n!\nINTEGER :: JJ, JST   ! looping indexes\nINTEGER :: INLVLS\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-----------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCROSOLVT',0,ZHOOK_HANDLE)\n!\n\n! 0. Initialize:\n! ------------------\n!\nZSNOWTEMP(:,:) = PSNOWTEMP(:,:)\nINLVLS         = SIZE(PSNOWDZ(:,:),2)\n!\n! 1. Calculate tri-diagnoal matrix coefficients:\n! ----------------------------------------------\n! For heat transfer, assume a minimum grid\n! thickness (to prevent numerical\n! problems for very thin snow cover):\n!\nDO JJ=1,SIZE(PTG)\n  !\n  DO JST = KNLVLS_USE(JJ),1,-1\n    !\n    ZSNOWDZM(JJ,JST) = MAX( PSNOWDZ(JJ,JST), PSNOWDZMIN )\n    !\n    ZWORK1(JJ,JST)   = ZSNOWDZM(JJ,JST) * PSCOND(JJ,JST)\n    !\n    IF ( JST<KNLVLS_USE(JJ) ) THEN\n      !\n      ZDZDIF(JJ,JST) = ZSNOWDZM(JJ,JST) + ZSNOWDZM(JJ,JST+1)\n      !\n      ZWORK2(JJ,JST) = ZSNOWDZM(JJ,JST+1) * PSCOND(JJ,JST+1)\n      !\n    ELSE\n      !\n      ZDZDIF(JJ,JST) = ZSNOWDZM(JJ,JST) + PD_G(JJ)\n      !\n      ZWORK2(JJ,JST) = PD_G(JJ) * PSOILCOND(JJ)\n      !\n    ENDIF\n    !\n    ZDTERM(JJ,JST) = 2.0 * ( ZWORK1(JJ,JST) + ZWORK2(JJ,JST) ) / ZDZDIF(JJ,JST)**2\n    !\n    ZCTERM(JJ,JST) = PSCAP(JJ,JST) * ZSNOWDZM(JJ,JST) / PTSTEP\n    !\n  ENDDO\n  !\nENDDO\n!\n! 2. Set up tri-diagonal matrix\n! -----------------------------\n!\nZAMTRX(:,:) = 0.\nZBMTRX(:,:) = 0.\nZCMTRX(:,:) = 0.\nZFRCV(:,:) = 0.\n! Upper BC\n!\nZAMTRX(:,1) =  0.0\nZBMTRX(:,1) =  1. / ( PCT(:)*PTSTEP )\nZCMTRX(:,1) = - PTERM2(:) * ZBMTRX(:,1)\nZFRCV (:,1) =   PTERM1(:) * ZBMTRX(:,1)\n!\nDO JJ = 1,SIZE(PTG)\n  !\n  DO JST = 2,KNLVLS_USE(JJ)\n    !\n    ! Interior Grid & Lower BC\n    ZAMTRX(JJ,JST) = -ZDTERM(JJ,JST-1)\n    ZBMTRX(JJ,JST) =  ZCTERM(JJ,JST) + ZDTERM(JJ,JST-1) + ZDTERM(JJ,JST)\n    ZFRCV (JJ,JST) =  ZCTERM(JJ,JST)*PSNOWTEMP(JJ,JST) - (PRADSINK(JJ,JST-1)-PRADSINK(JJ,JST))\n    !\n    IF ( JST<KNLVLS_USE(JJ) ) THEN\n      ZCMTRX(JJ,JST) = -ZDTERM(JJ,JST)\n    ELSE\n      ZCMTRX(JJ,JST) = 0.0\n      ZFRCV (JJ,JST) = ZFRCV(JJ,JST) + ZDTERM(JJ,JST)*PTG(JJ)\n    ENDIF\n    !\n  ENDDO\n  !\nENDDO\n!\n! 4. Compute solution vector\n! --------------------------\n!\n\nCALL TRIDIAG_GROUND_SNOWCRO(ZAMTRX,ZBMTRX,ZCMTRX,ZFRCV,ZSNOWTEMP,KNLVLS_USE,0)\n!\n! Heat flux between surface and 2nd snow layers: (W/m2)\n!\nPSNOWFLUX(:) = ZDTERM(:,1) * ( ZSNOWTEMP(:,1) - ZSNOWTEMP(:,2) )\n!\n! 5. Snow melt case\n! -----------------\n! If melting in uppermost layer, assume surface layer\n! temperature at freezing point and re-evaluate lower\n! snowpack temperatures. This is done as it is most likely\n! most signigant melting will occur within a time step in surface layer.\n! Surface energy budget (and fluxes) will\n! be re-calculated (outside of this routine):\n!\nZAMTRX_M(:,1) =  0.0\nZBMTRX_M(:,1) =  ZCTERM(:,2) + ZDTERM(:,1) + ZDTERM(:,2)\nZCMTRX_M(:,1) = -ZDTERM(:,2)\nZFRCV_M (:,1) =  ZCTERM(:,2)*PSNOWTEMP(:,2) - (PRADSINK(:,1)-PRADSINK(:,2)) + ZDTERM(:,1)*XTT\n!\nDO JJ = 1,SIZE(PTG)\n  DO JST = 2,KNLVLS_USE(JJ)-1\n    ZAMTRX_M(JJ,JST) = ZAMTRX(JJ,JST+1)\n    ZBMTRX_M(JJ,JST) = ZBMTRX(JJ,JST+1)\n    ZCMTRX_M(JJ,JST) = ZCMTRX(JJ,JST+1)\n    ZFRCV_M (JJ,JST) = ZFRCV (JJ,JST+1)\n    ZSNOWTEMP_M(JJ,JST) = PSNOWTEMP(JJ,JST+1)\n  ENDDO\nENDDO\n!\n\n CALL TRIDIAG_GROUND_SNOWCRO(ZAMTRX_M,ZBMTRX_M,ZCMTRX_M,ZFRCV_M,ZSNOWTEMP_M,KNLVLS_USE,1)\n!\n! If melting for 2 consecuative time steps, then replace current T-profile\n! with one assuming T=Tf in surface layer:\n!\nZSNOWTEMP_DELTA(:) = 0.0\n!\nWHERE( ZSNOWTEMP(:,1)>XTT .AND. PSNOWTEMP(:,1)>=XTT )\n  PSNOWFLUX(:) = ZDTERM(:,1) * ( XTT-ZSNOWTEMP_M(:,1) )\n  ZSNOWTEMP_DELTA(:) = 1.0\nEND WHERE\n!\nDO JJ = 1,SIZE(PTG)\n  DO JST = 2,KNLVLS_USE(JJ)\n    ZSNOWTEMP(JJ,JST) = ZSNOWTEMP_DELTA(JJ)       * ZSNOWTEMP_M(JJ,JST-1) + &\n                        (1.0-ZSNOWTEMP_DELTA(JJ)) * ZSNOWTEMP  (JJ,JST)\n  ENDDO\nENDDO\n!\n! 6. Lower boundary flux:\n! -----------------------\n! NOTE: evaluate this term assuming the snow layer\n! can't exceed the freezing point as this adjustment\n! is made in melting routine. Then must adjust temperature\n! to conserve energy:\n!\nDO JJ=1, SIZE(PTG)\n ZGBAS(JJ) = ZDTERM(JJ,KNLVLS_USE(JJ)) * ( ZSNOWTEMP(JJ,KNLVLS_USE(JJ))             - PTG(JJ) )\n PGBAS(JJ) = ZDTERM(JJ,KNLVLS_USE(JJ)) * ( MIN( XTT, ZSNOWTEMP(JJ,KNLVLS_USE(JJ)) ) - PTG(JJ) )\n ZSNOWTEMP(JJ,KNLVLS_USE(JJ)) = ZSNOWTEMP(JJ,KNLVLS_USE(JJ)) + &\n                                ( ZGBAS(JJ)-PGBAS(JJ) ) / ZCTERM(JJ,KNLVLS_USE(JJ))\n\nENDDO\n!\n! 7. Update temperatute profile in time:\n! --------------------------------------\n!\nDO JJ=1, SIZE(PTG)\n  PSNOWTEMP(JJ,1:KNLVLS_USE(JJ)) = ZSNOWTEMP(JJ,1:KNLVLS_USE(JJ))\nENDDO\n!\n!\n! 8. Compute new (implicit) air T and specific humidity\n! -----------------------------------------------------\n!\nPTA_IC(:) = PPET_B_COEF_T(:) + PPET_A_COEF_T(:) * PSNOWTEMP(:,1)\nPQA_IC(:) = PPEQ_B_COEF_T(:) + PPEQ_A_COEF_T(:) * PSNOWTEMP(:,1)\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROSOLVT',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROSOLVT\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROMELT(PSCAP,PSNOWTEMP,PSNOWDZ,         &\n                       PSNOWRHO,PSNOWLIQ,KNLVLS_USE     )\n!\n!!    PURPOSE\n!!    -------\n!     Calculate snow melt (resulting from surface fluxes, ground fluxes,\n!     or internal shortwave radiation absorbtion). It is used to\n!     augment liquid water content, maintain temperatures\n!     at or below freezing, and possibly reduce the mass\n!     or compact the layer(s).\n!\nUSE MODD_CSTS,ONLY : XTT, XLMTT, XRHOLW, XRHOLI\n!\nUSE MODE_SNOW3L\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSCAP\n!\nREAL, DIMENSION(:,:), INTENT(INOUT) :: PSNOWDZ, PSNOWTEMP, PSNOWRHO,   &\n                                          PSNOWLIQ\n!\nINTEGER, DIMENSION(:), INTENT(IN)   :: KNLVLS_USE\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZPHASE, ZCMPRSFACT,   &\n                                                      ZSNOWLWE,             &\n                                                      ZSNOWMELT, ZSNOWTEMP\n!\nINTEGER :: JJ, JST ! looping indexes\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCROMELT',0,ZHOOK_HANDLE)\n!\n! 0. Initialize:\n! ---------------------------\n!\nDO JJ = 1,SIZE(PSNOWDZ,1)\n   DO JST = 1,KNLVLS_USE(JJ)\n     ZPHASE    (JJ,JST) = 0.0\n     ZCMPRSFACT(JJ,JST) = 0.0\n     ZSNOWLWE  (JJ,JST) = 0.0\n     ZSNOWMELT (JJ,JST) = 0.0\n     ZSNOWTEMP (JJ,JST) = 0.0\n   ENDDO\nENDDO\n!\n! 1. Determine amount of melt in each layer:\n! ------------------------------------------\n!\nDO JJ = 1,SIZE(PSNOWDZ,1)\n  !\n   DO JST = 1,KNLVLS_USE(JJ)\n     !\n     ! Total Liquid equivalent water content of snow (m):\n     ZSNOWLWE(JJ,JST) = PSNOWRHO(JJ,JST) * PSNOWDZ(JJ,JST) / XRHOLW\n     !\n     ! Melt snow if excess energy and snow available:\n     ! Phase change (J/m2)\n     ZPHASE(JJ,JST) = MIN( PSCAP(JJ,JST) * MAX(0.0,PSNOWTEMP(JJ,JST)-XTT) * PSNOWDZ(JJ,JST), &\n                           MAX(0.0,ZSNOWLWE(JJ,JST)-PSNOWLIQ(JJ,JST)) * XLMTT * XRHOLW )\n     !\n     ! Update snow liq water content and temperature if melting:\n     ! liquid water available for next layer from melting of snow\n     ! which is assumed to be leaving the current layer (m):\n     ZSNOWMELT(JJ,JST) = ZPHASE(JJ,JST) / (XLMTT*XRHOLW)\n     !AD: Numerical precision can cause melt to slightly exceed SWE... adding cap\n     ZSNOWMELT(JJ,JST) = min(ZSNOWMELT(JJ,JST), ZSNOWLWE(JJ,JST))\n     !\n     ! Cool off snow layer temperature due to melt:\n     ZSNOWTEMP(JJ,JST) = PSNOWTEMP(JJ,JST) - ZPHASE(JJ,JST) / (PSCAP(JJ,JST)*PSNOWDZ(JJ,JST))\n     !\n     ! Difference with ISBA_ES: ZMELTXS should never be different of 0.\n     ! because of the introduction of the tests in LLAYERGONE\n     PSNOWTEMP(JJ,JST) =  ZSNOWTEMP(JJ,JST)\n     !\n   ! The control below should be suppressed after further tests\n#ifdef HYDRO_D\n     IF (PSNOWTEMP(JJ,JST)-XTT > XUEPSI) THEN\n       WRITE(*,*) 'pb dans MELT PSNOWTEMP(JJ,JST) >XTT:', JJ,JST, PSNOWTEMP(JJ,JST), XTT\n!       CALL ABOR1_SFX('SNOWCRO: pb dans MELT')\n     ENDIF\n#endif\n    !\n    ! Loss of snowpack depth: (m) and liquid equiv (m):\n    ! Compression factor for melt loss: this decreases\n    ! layer thickness and increases density thereby leaving\n    ! total SWE constant.\n    !\n    ! Difference with ISBA_ES: All melt is considered to decrease the depth\n    ! without consideration to the irreducible content\n    !\n    ZCMPRSFACT(JJ,JST) = ( ZSNOWLWE(JJ,JST) - (PSNOWLIQ(JJ,JST)+ZSNOWMELT(JJ,JST)) ) &\n                       / ( ZSNOWLWE(JJ,JST) - PSNOWLIQ(JJ,JST) )\n    PSNOWDZ   (JJ,JST) = PSNOWDZ (JJ,JST) * ZCMPRSFACT(JJ,JST)\n    if ((PSNOWDZ(JJ,JST) .eq. 0) .and. (PSNOWRHO(JJ,JST).gt.0) .and. (PSNOWRHO(JJ,JST).ne.999)) then\n      PSNOWRHO(JJ,JST) = 0\n    else\n      PSNOWRHO(JJ,JST) = ZSNOWLWE(JJ,JST) * XRHOLW / PSNOWDZ(JJ,JST)\n    endif\n    !\n    ! 2. Add snow melt to current snow liquid water content:\n    ! ------------------------------------------------------\n    !\n    PSNOWLIQ(JJ,JST) = PSNOWLIQ(JJ,JST) + ZSNOWMELT(JJ,JST)\n    !\n  ENDDO   ! loop JST active snow layers\nENDDO   ! loop JJ grid points\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROMELT',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROMELT\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROREFRZ(PTSTEP,PRR,                            &\n                        PSNOWRHO,PSNOWTEMP,PSNOWDZ,PSNOWLIQ,   &\n                        PTHRUFAL, PSCAP, PLEL3L,KNLVLS_USE     )\n!\n!!    PURPOSE\n!!    -------\n!     Calculate any freezing/refreezing of liquid water in the snowpack.\n!     Also, calculate liquid water transmission and snow runoff.\n!     Refreezing causes densification of a layer.\n!\nUSE MODD_CSTS,     ONLY : XTT, XLMTT, XRHOLW, XCI,XRHOLI,XRHOTHRESHOLD_ICE\nUSE MODD_SNOW_PAR, ONLY : XSNOWDMIN\n\n!\nUSE MODE_SNOW3L\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\n\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                      :: PTSTEP\n!\nREAL, DIMENSION(:), INTENT(IN)        :: PRR\n!\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWDZ, PSNOWTEMP, PSNOWLIQ, PSNOWRHO\n!\nREAL, DIMENSION(:), INTENT(INOUT)     :: PTHRUFAL\n!\n! modifs_EB layers\nINTEGER, DIMENSION(:), INTENT(IN)      :: KNLVLS_USE\nREAL, DIMENSION(:,:), INTENT(IN)       :: PSCAP\nREAL, DIMENSION(:), INTENT(IN)         :: PLEL3L\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZPHASE,              &\n                                                      ZSNOWLIQ, ZSNOWRHO,  &\n                                                      ZWHOLDMAX, ZSNOWDZ,  &\n                                                      ZSNOWTEMP\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),0:SIZE(PSNOWRHO,2)) :: ZFLOWLIQ\n!\nREAL :: ZDENOM, ZNUMER\n!\nINTEGER :: JJ, JST   ! looping indexes\nINTEGER :: INLVLS     ! maximum snow layers number\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCROREFRZ',0,ZHOOK_HANDLE)\n!\n! 0. Initialize:\n! --------------\n!\nINLVLS = SIZE(PSNOWDZ,2)\n!\nDO JJ=1,SIZE(PSNOWDZ,1)\n  DO JST=1,KNLVLS_USE(JJ)\n    ZSNOWRHO (JJ,JST) = PSNOWRHO(JJ,JST)\n    ZSNOWTEMP(JJ,JST) = PSNOWTEMP(JJ,JST)\n    ZWHOLDMAX(JJ,JST) = SNOWCROHOLD( PSNOWRHO(JJ,JST),PSNOWLIQ(JJ,JST),PSNOWDZ(JJ,JST) )\n! trude test with not allowing liquid if psnowrho >  XRHOTHRESHOLD_ICE  (i.e. no liquid in ice)\n!      IF (PSNOWRHO(JJ,JST).GT.XRHOTHRESHOLD_ICE)  ZWHOLDMAX (JJ,JST)=0\n! end trude test\n\n  ENDDO\nENDDO\n!\nDO JJ = 1,SIZE(PSNOWDZ,1)  ! loop JJ grid points\n  !\n  ! 1. Increases Liquid Water of top layer from rain\n  !    ---------------------------------------------\n  !\n  !  Rainfall (m) initialises the liquid flow whih feeds the top layer\n  !  and evaporation/condensation are taken into account\n  !\n  IF ( KNLVLS_USE(JJ)>0. ) THEN\n    ZFLOWLIQ(JJ,0) = PRR(JJ) * PTSTEP / XRHOLW\n    ZFLOWLIQ(JJ,0) = MAX(0., ZFLOWLIQ(JJ,0) - PLEL3L(JJ)*PTSTEP/(XLVTT*XRHOLW))\n  ELSE\n    ZFLOWLIQ(JJ,0) = 0\n  ENDIF\n  !\n  DO JST=1,KNLVLS_USE(JJ) ! loop JST active snow layers\n    !\n    ! 2. Increases Liquid Water from the upper layers flow (or rain for top layer)\n    !    -----------------------------\n    PSNOWLIQ(JJ,JST) = PSNOWLIQ(JJ,JST) + ZFLOWLIQ(JJ,JST-1)\n    !\n    ! 3. Freezes liquid water in any cold layers\n    !    ---------------------------------------\n    !\n    ! Calculate the maximum possible refreezing\n    ZPHASE(JJ,JST) = MIN( PSCAP(JJ,JST)* MAX(0.0, XTT - ZSNOWTEMP(JJ,JST)) * PSNOWDZ(JJ,JST), &\n                          PSNOWLIQ(JJ,JST) * XLMTT * XRHOLW )\n    !\n    ! Reduce liquid content if freezing occurs:\n    ZSNOWLIQ(JJ,JST) = PSNOWLIQ(JJ,JST) - ZPHASE(JJ,JST)/(XLMTT*XRHOLW)\n    !\n    ! Warm layer and reduce liquid if freezing occurs:\n    ZSNOWDZ(JJ,JST) = MAX(XSNOWDMIN/INLVLS, PSNOWDZ(JJ,JST))\n    !\n    !\n    ! Difference with ISBA-ES: a possible cooling of current refreezing water\n    !                          is taken into account to calculate temperature change\n    ZNUMER = ( ZSNOWRHO(JJ,JST) * ZSNOWDZ(JJ,JST) - ( PSNOWLIQ(JJ,JST) - ZFLOWLIQ(JJ,JST-1) ) * XRHOLW )\n    ZDENOM = ( ZSNOWRHO(JJ,JST) * ZSNOWDZ(JJ,JST) - ( ZSNOWLIQ(JJ,JST) - ZFLOWLIQ(JJ,JST-1) ) * XRHOLW )\n    !\n    PSNOWTEMP(JJ,JST) = XTT + ( ZSNOWTEMP(JJ,JST)-XTT )*ZNUMER/ZDENOM + ZPHASE(JJ,JST)/( XCI*ZDENOM )\n    !\n    ! 4. Calculate flow from the excess of holding capacity\n    !    --------------------------------------------------------------\n    !\n    ! Any water in excess of the maximum holding space for liquid water\n    ! amount is drained into next layer down.\n    ZFLOWLIQ(JJ,JST) = MAX( 0., ZSNOWLIQ(JJ,JST)-ZWHOLDMAX(JJ,JST) )\n    !\n    ZSNOWLIQ(JJ,JST) = ZSNOWLIQ(JJ,JST) - ZFLOWLIQ(JJ,JST)\n    !\n    ! 5. Density is adjusted to conserve the mass\n    !    --------------------------------------------------------------\n    ZNUMER = ( ZSNOWRHO(JJ,JST) * PSNOWDZ(JJ,JST) - ( ZFLOWLIQ(JJ,JST) - ZFLOWLIQ(JJ,JST-1) ) * XRHOLW )\n    !\n    ZSNOWRHO(JJ,JST) = ZNUMER / ZSNOWDZ(JJ,JST)\n    !\n    ! keeps snow denisty below ice density\n    IF ( ZSNOWRHO(JJ,JST)>XRHOLI ) THEN\n      PSNOWDZ (JJ,JST) = PSNOWDZ(JJ,JST) * ZSNOWRHO(JJ,JST) / XRHOLI\n      ZSNOWRHO(JJ,JST) = XRHOLI\n    ENDIF\n    !\n    ! 6. Update thickness and density and any freezing:\n    !    ----------------------------------------------\n    PSNOWRHO(JJ,JST) = ZSNOWRHO(JJ,JST)\n    PSNOWLIQ(JJ,JST) = ZSNOWLIQ(JJ,JST)\n    !\n  ENDDO ! loop JST active snow layers\n  !\n  ! Any remaining throughflow after freezing is available to\n  ! the soil for infiltration or surface runoff (m).\n  ! I.E. This is the amount of water leaving the snowpack:\n  ! Rate water leaves the snowpack [kg/(m2 s)]:\n  !\n  PTHRUFAL(JJ)  = PTHRUFAL(JJ) + ZFLOWLIQ(JJ,KNLVLS_USE(JJ)) * XRHOLW / PTSTEP\n !\nENDDO ! loop JJ grid points\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROREFRZ',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROREFRZ\n!####################################################################\nSUBROUTINE GET_RHO(PRHO_IN,PDZ,PSNOWLIQ,PFLOWLIQ,PRHO_OUT)\n!\nUSE MODD_CSTS,     ONLY : XRHOLW\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\nREAL, INTENT(IN)  :: PRHO_IN, PDZ, PSNOWLIQ,PFLOWLIQ\nREAL, INTENT(OUT) :: PRHO_OUT\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_RHO',0,ZHOOK_HANDLE)\n!\nPRHO_OUT =  ( PRHO_IN * PDZ - ( PSNOWLIQ - PFLOWLIQ ) * XRHOLW )\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_RHO',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_RHO\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROFLUX(PSNOWTEMP,PSNOWDZ,PEXNS,PEXNA,          &\n                       PUSTAR2_IC,                             &\n                       PTSTEP,PALBT,PSW_RAD,PEMIST,PLWUPSNOW,  &\n                       PLW_RAD,PTA,PSFCFRZ,PQA,PHPSNOW,        &\n                       PSNOWTEMPO1,PSNOWFLUX,PCT,PRADSINK,     &\n                       PQSAT,PDQSAT,PRSRA,                     &\n                       PRN,PH,PGFLUX,PLES3L,PLEL3L,PEVAP,      &\n                       PUSTAR,                                  &\n                       PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS) ! trude added\n!\n!!    PURPOSE\n!!    -------\n!     Calculate the surface fluxes (atmospheric/surface).\n!     (Noilhan and Planton 1989; Noilhan and Mahfouf 1996)\n!\nUSE MODD_CSTS,ONLY : XTT\n!\nUSE MODE_THERMOS\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                    :: PTSTEP\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PSNOWDZ, PSNOWTEMPO1, PSNOWFLUX, PCT, &\n                                        PRADSINK, PEXNS, PEXNA\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PALBT, PSW_RAD, PEMIST, PLW_RAD,      &\n                                        PTA, PSFCFRZ, PQA,                    &\n                                        PHPSNOW, PQSAT, PDQSAT, PRSRA,        &\n                                        PUSTAR2_IC\n!\nREAL, DIMENSION(:), INTENT(INOUT)   :: PSNOWTEMP\n!\nREAL, DIMENSION(:), INTENT(OUT)     :: PRN, PH, PGFLUX, PLES3L, PLEL3L,      &\n                                        PEVAP, PLWUPSNOW, PUSTAR\n! trude added\nREAL, DIMENSION(:), INTENT(OUT)      :: PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS\n\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWDZ))      :: ZEVAPC, ZSNOWTEMP\nREAL :: ZSMSNOW, ZGFLUX\n!\nINTEGER :: JJ\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n\n! ---trude\n!compile error : A dummy argument with an explicit INTENT(OUT) declaration is not given an explicit value.\n! It seems that PLWUPSNOW does nothing. For now I give this array a value of 0 to be able to compile\nPLWUPSNOW(:) = 0.0\n! ---\n\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCROFLUX',0,ZHOOK_HANDLE)\n!\n! 0. Initialize:\n! --------------\n!\n! 1. Flux calculations when melt not occuring at surface (W/m2):\n! --------------------------------------------------------------\n!\nDO JJ = 1,SIZE(PALBT)\n  !\n  CALL GET_FLUX(PALBT(JJ),PEMIST(JJ),PSW_RAD(JJ),PLW_RAD(JJ),   &\n                PEXNS(JJ),PEXNA(JJ),PTA(JJ),PQA(JJ),PRSRA(JJ), &\n                PQSAT(JJ),PDQSAT(JJ),PSFCFRZ(JJ),PHPSNOW(JJ),   &\n                PSNOWTEMP(JJ),PSNOWTEMPO1(JJ),                  &\n                PRN(JJ),PH(JJ),ZEVAPC(JJ),                      &\n                PLES3L(JJ),PLEL3L(JJ),ZGFLUX,               &\n                PFSA_CROCUS(JJ), PFSR_CROCUS(JJ), PFIRA_CROCUS(JJ)) ! trude added\n  !\n  IF ( PSNOWTEMP(JJ)>XTT ) THEN\n    !\n    IF ( PSNOWTEMPO1(JJ)<XTT ) THEN\n      !\n      ! 2. Initial melt adjustment\n      ! --------------------------\n      ! If energy avalabile to melt snow, then recalculate fluxes\n      ! at the freezing point and add residual heat to layer\n      ! average heat.\n      !\n      ! A) If temperature change is > 0 and passes freezing point this timestep,\n      !    then recalculate fluxes at freezing point and excess energy\n      !    will be used outside of this routine to change snow heat content:\n      !\n      ! WRITE (*,*) 'attention test LFLUX traitement XTT supprime!'\n      !\n      CALL GET_FLUX(PALBT(JJ),PEMIST(JJ),PSW_RAD(JJ),PLW_RAD(JJ),   &\n                    PEXNS(JJ),PEXNA(JJ), PTA(JJ),PQA(JJ),PRSRA(JJ), &\n                    PQSAT(JJ),PDQSAT(JJ),PSFCFRZ(JJ),PHPSNOW(JJ),   &\n                    XTT,PSNOWTEMPO1(JJ),                            &\n                    PRN(JJ),PH(JJ),ZEVAPC(JJ),                      &\n                    PLES3L(JJ),PLEL3L(JJ),PGFLUX(JJ),            &\n                    PFSA_CROCUS(JJ), PFSR_CROCUS(JJ), PFIRA_CROCUS(JJ)) ! trude added\n      !\n      ZSMSNOW = ZGFLUX - PGFLUX(JJ)\n      !\n      ! This will be used to change heat content of snow:\n      ZSNOWTEMP(JJ) = PSNOWTEMP(JJ) - ZSMSNOW * PTSTEP * PCT(JJ)\n      !\n    ELSE\n      !\n      ! 3. Ongoing melt adjustment: explicit solution\n      ! ---------------------------------------------\n      !    If temperature change is 0 and at freezing point this timestep,\n      !    then recalculate fluxes and surface temperature *explicitly*\n      !    as this is *exact* for snow at freezing point (Brun, Martin)\n      !\n      CALL GET_FLUX(PALBT(JJ),PEMIST(JJ),PSW_RAD(JJ),PLW_RAD(JJ),   &\n                    PEXNS(JJ),PEXNA(JJ), PTA(JJ),PQA(JJ),PRSRA(JJ), &\n                    PQSAT(JJ),PDQSAT(JJ),PSFCFRZ(JJ),PHPSNOW(JJ),   &\n                    XTT,XTT,                                        &\n                    PRN(JJ),PH(JJ),ZEVAPC(JJ),                      &\n                    PLES3L(JJ),PLEL3L(JJ),PGFLUX(JJ),                &\n                    PFSA_CROCUS(JJ), PFSR_CROCUS(JJ), PFIRA_CROCUS(JJ)) ! trude added\n      !\n      ZSNOWTEMP(JJ) = XTT + PTSTEP * PCT(JJ) * ( PGFLUX(JJ) + PRADSINK(JJ) - PSNOWFLUX(JJ) )\n      !\n    ENDIF\n    !\n  ELSE\n    !\n    ZSNOWTEMP(JJ) = PSNOWTEMP(JJ)\n    !\n    PGFLUX(JJ) = ZGFLUX\n    !\n  ENDIF\n  !\nENDDO\n!\n! 4. Update surface temperature:\n! ------------------------------\n!\nPSNOWTEMP(:) = ZSNOWTEMP(:)\n!\n! 5. Final evaporative flux (kg/m2/s)\n!\nPEVAP(:) = ZEVAPC(:)\n!\n! 5. Friction velocity\n! --------------------\n!\nPUSTAR(:) = SQRT(PUSTAR2_IC(:))\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROFLUX',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROFLUX\n!####################################################################\nSUBROUTINE GET_FLUX(PALBT,PEMIST,PSW_RAD,PLW_RAD,PEXNS,PEXNA,   &\n                    PTA,PQA,PRSRA,PQSAT,PDQSAT,PSFCFRZ,PHPSNOW, &\n                    PSNOWTEMP,PSNOWTEMPO1,                      &\n                    PRN,PH,PEVAPC,PLES3L,PLEL3L,PGFLUX,      &\n                    PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS) !trude added\n!\nUSE MODD_CSTS,ONLY : XSTEFAN, XCPD, XLSTT, XLVTT\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\nREAL, INTENT(IN) :: PALBT, PEMIST\nREAL, INTENT(IN) :: PSW_RAD, PLW_RAD\nREAL, INTENT(IN) :: PEXNS, PEXNA\nREAL, INTENT(IN) :: PTA, PQA, PRSRA, PQSAT, PDQSAT, PSFCFRZ, PHPSNOW\nREAL, INTENT(IN) :: PSNOWTEMP,PSNOWTEMPO1\nREAL, INTENT(OUT):: PRN, PH, PEVAPC, PLES3L, PLEL3L, PGFLUX\n! Trude added:\nREAL, INTENT(OUT):: PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS !trude added\n!\nREAL :: ZLE, ZDELTAT, ZLWUPSNOW, ZSNOWTO3\n\n!REAL ::PSNOWTEMP,PSNOWTEMPO1\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_FLUX',0,ZHOOK_HANDLE)\n!\n!trude test\n!PSNOWTEMPO1 = PSNOWTEMPO1_orig+5\n!PSNOWTEMP=PSNOWTEMP_orig+5\n! end test\n\nZSNOWTO3  = PSNOWTEMPO1**3  ! to save some CPU time, store this\n!\nZDELTAT   = PSNOWTEMP - PSNOWTEMPO1   ! surface T time change:\n!\nZLWUPSNOW = PEMIST * XSTEFAN * ZSNOWTO3 * ( PSNOWTEMPO1 + 4.*ZDELTAT )\n!\nPRN       = ( 1.-PALBT )*PSW_RAD + PEMIST*PLW_RAD - ZLWUPSNOW\n!\nPH        = PRSRA * XCPD * ( PSNOWTEMP/PEXNS - PTA/PEXNA )\n!\nPEVAPC    = PRSRA * ( (PQSAT - PQA) + PDQSAT*ZDELTAT )\n!\nPLES3L    = PSFCFRZ      * XLSTT * PEVAPC\n!\nPLEL3L    = (1.-PSFCFRZ) * XLVTT * PEVAPC\n!\nZLE       = PLES3L + PLEL3L\n!\nPGFLUX    = PRN - PH - ZLE + PHPSNOW\n\nPFSA_CROCUS= (1-PALBT)*PSW_RAD\nPFSR_CROCUS = PALBT*PSW_RAD\nPFIRA_CROCUS = ZLWUPSNOW - PEMIST*PLW_RAD\n\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_FLUX',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_FLUX\n!\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROEVAPN(PLES3L,PTSTEP,PSNOWTEMP,PSNOWRHO, &\n                       PSNOWDZ,PEVAPCOR,PSNOWHMASS        )\n!\n!!    PURPOSE\n!!    -------\n!     Remove mass from uppermost snow layer in response to\n!     evaporation (liquid) and sublimation.\n!\n!!     MODIFICATIONS\n!!     -------------\n!!      Original A. Boone\n!!      05/2011: E. Brun  Takes only into account sublimation and solid\n!!                         condensation. Evaporation and liquid condensation\n!!                         are taken into account in SNOWCROREFRZ\n!\nUSE MODD_CSTS,     ONLY : XLSTT, XLMTT, XCI, XTT\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                    :: PTSTEP\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PSNOWTEMP\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PLES3L   ! (W/m2)\n!\nREAL, DIMENSION(:), INTENT(INOUT)   :: PSNOWRHO, PSNOWDZ, PSNOWHMASS, &\n                                        PEVAPCOR\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PLES3L))       :: ZSNOWEVAPS, ZSNOWEVAP, ZSNOWEVAPX,          &\n                                       ZSNOWDZ, ZEVAPCOR\n!                                      ZEVAPCOR = for vanishingy thin snow cover,\n!                                                 allow any excess evaporation\n!                                                 to be extracted from the soil\n!                                                 to maintain an accurate water\n!                                                 balance [kg/(m2 s)]\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCROEVAPN',0,ZHOOK_HANDLE)\n!\n! 0. Initialize:\n! --------------\n!\nZEVAPCOR  (:) = 0.0\nZSNOWEVAPS(:) = 0.0\nZSNOWEVAP (:) = 0.0\nZSNOWEVAPX(:) = 0.0\nZSNOWDZ   (:) = 0.0\n!\n!++ trude. Test for rare event where snow is present, but density is zero (thin snow layer ~1e-10m)\nWHERE ( PSNOWRHO==0.0 )\n  PSNOWDZ(:)=0.0\nEND WHERE\n\nWHERE ( PSNOWDZ>0.0 )\n  !\n  ! 1. Sublimation/condensation of snow ice\n  ! ----------------------------------------\n  ! Reduce layer thickness and total snow depth\n  ! if sublimation: add to correction term if potential\n  ! sublimation exceeds available snow cover.\n  !\n  ZSNOWEVAPS(:) = PLES3L(:) * PTSTEP / ( XLSTT*PSNOWRHO(:) )\n  ZSNOWDZ(:)    = PSNOWDZ(:) - ZSNOWEVAPS(:)\n  PSNOWDZ(:)    = MAX( 0.0, ZSNOWDZ(:) )\n  ZEVAPCOR(:)   = ZEVAPCOR(:) + MAX(0.0,-ZSNOWDZ(:)) * PSNOWRHO(:) / PTSTEP\n  !\n  ! Total heat content change due to snowfall and sublimation (added here):\n  ! (for budget calculations):\n  !\n  PSNOWHMASS(:) = PSNOWHMASS(:) &\n                  - PLES3L(:) * (PTSTEP/XLSTT) * ( XCI * (PSNOWTEMP(:)-XTT) - XLMTT )\n  !\nEND WHERE\n!\n! 3. Update evaporation correction term:\n! --------------------------------------\n!\nPEVAPCOR(:) = PEVAPCOR(:) + ZEVAPCOR(:)\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROEVAPN',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE SNOWCROEVAPN\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROGONE(PTSTEP,PLEL3L,PLES3L,PSNOWRHO,                     &\n                       PSNOWHEAT,PRADSINK_2D,PEVAPCOR,PTHRUFAL,PGRNDFLUX, &\n                       PGFLUXSNOW,PSNOWDZ,PSNOWLIQ,PSNOWTEMP,PRADXS,      &\n                       PRR,KNLVLS_USE                                     )\n!\n!!    PURPOSE\n!!    -------\n!     Account for the case when the last trace of snow melts\n!     during a time step: ensure mass and heat balance of\n!     snow AND underlying surface.\n!     Original A. Boone\n!     05/2011: E. Brun  Takes into account sublimation and PGRNDFLUX\n!                       Adds rain and evaporation/liquid condensation\n!                       in PTHRUFAL\n!\nUSE MODD_CSTS,ONLY : XTT, XLSTT, XLVTT\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                    :: PTSTEP\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PLEL3L, PLES3L, PGFLUXSNOW,PRR\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PRADSINK_2D\n!\nREAL, DIMENSION(:,:), INTENT(IN)    :: PSNOWRHO, PSNOWHEAT\n!\nREAL, DIMENSION(:), INTENT(INOUT)   :: PGRNDFLUX, PRADXS\n!\nREAL, DIMENSION(:,:), INTENT(INOUT) :: PSNOWDZ, PSNOWLIQ, PSNOWTEMP\n!\nREAL, DIMENSION(:), INTENT(OUT)     :: PTHRUFAL   ! melt water [kg/(m2 s)]\n!\nREAL, DIMENSION(:), INTENT(OUT)     :: PEVAPCOR   ! [kg/(m2 s)]\n!                                      PEVAPCOR = for vanishingy thin snow cover,\n!                                                 allow any excess evaporation\n!                                                 to be extracted from the soil\n!                                                 to maintain an accurate water\n!                                                 balance.\n!\nINTEGER, DIMENSION(:), INTENT(INOUT)      :: KNLVLS_USE\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PLES3L))       :: ZRADSINK\nREAL, DIMENSION(SIZE(PLES3L))       :: ZSNOWHEATC\nINTEGER, DIMENSION(SIZE(PLES3L))    :: ISNOWGONE_DELTA\n!\nINTEGER  :: JJ\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCROGONE',0,ZHOOK_HANDLE)\n!\n! 0. Initialize:\n! --------------\n!\nPEVAPCOR(:) = 0.0\nPTHRUFAL(:) = 0.0\n!\nDO JJ = 1,SIZE(ZRADSINK)\n  ZRADSINK  (JJ) = PRADSINK_2D(JJ,INLVLS_USE(JJ))\n  ZSNOWHEATC(JJ) = SUM(PSNOWHEAT(JJ,1:INLVLS_USE(JJ))) !total heat content (J m-2)\nEND DO\n!\nISNOWGONE_DELTA(:) = 1\n!\n! 1. Simple test to see if snow vanishes:\n! ---------------------------------------\n! If so, set thicknesses (and therefore mass and heat) and liquid content\n! to zero, and adjust fluxes of water, evaporation and heat into underlying\n! surface.\n!\n! takes into account the heat content corresponding to the occasional\n! sublimation  and then PGRNDFLUX\n!\nZSNOWHEATC(:) = ZSNOWHEATC(:) + MAX( 0., PLES3L(:)*PTSTEP/XLSTT ) * XLMTT\n!\nWHERE ( PGFLUXSNOW(:)+ZRADSINK(:)-PGRNDFLUX(:) >= (-ZSNOWHEATC(:)/PTSTEP) )\n  PGRNDFLUX(:)       = PGFLUXSNOW(:) + (ZSNOWHEATC(:)/PTSTEP)\n  PEVAPCOR (:)       = PLES3L(:)/XLSTT\n  PRADXS   (:)       = 0.0\n  ISNOWGONE_DELTA(:) = 0          ! FLAG...if=0 then snow vanishes, else=1\nEND WHERE\n!\n! 2. Final update of snow state and computation of corresponding flow\n!    Only if snow vanishes\n! -----------------------------\n!\nPTHRUFAL(:) = 0.\n!\nDO JJ=1, SIZE(ZRADSINK)\n  !\n  IF(ISNOWGONE_DELTA(JJ) == 0 ) THEN\n    PTHRUFAL(JJ) = PTHRUFAL(JJ) + &\n                   SUM( PSNOWRHO(JJ,1:INLVLS_USE(JJ))*PSNOWDZ(JJ,1:INLVLS_USE(JJ)) ) / PTSTEP\n! takes into account rain and condensation/evaporation\n    PTHRUFAL(JJ) = PTHRUFAL(JJ) + PRR(JJ) - PLEL3L(JJ)/XLVTT\n    PSNOWTEMP(JJ,:) = XTT\n    PSNOWDZ  (JJ,:) = 0.\n    PSNOWLIQ (JJ,:) = 0.\n    INLVLS_USE(JJ) = 0\n  ENDIF\n  !\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROGONE',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROGONE\n!####################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROEVAPGONE(PSNOWHEAT,PSNOWDZ,PSNOWRHO,PSNOWTEMP,PSNOWLIQ,      &\n                           PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,PSNOWAGE,KNLVLS_USE,&\n                           HSNOWMETAMO)\n!\n!!    PURPOSE\n!!    -------\n!\n!     If all snow in uppermost layer evaporates/sublimates, re-distribute\n!     grid (below assumes very thin snowpacks so layer-thicknesses are\n!     constant).\n!     Original A. Boone\n!     05/2011: E. Brun  Takes into account previous changes in the energy\n!                       content\n!\n!\nUSE MODD_CSTS,     ONLY : XTT, XRHOLW, XLMTT, XCI\nUSE MODD_SNOW_PAR, ONLY : XRHOSMIN_ES, XSNOWDMIN, XRHOSMAX_ES\nUSE MODE_SNOW3L\nUSE MODD_SNOW_METAMO\n!USE MODD_TYPE_DATE_SURF\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWRHO   ! snow density profile                (kg/m3)\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWDZ    ! snow layer thickness profile        (m)\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWHEAT  ! snow heat content/enthalpy          (J/m2)\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWGRAN1 ! snow grain parameter 1              (-)\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWGRAN2 ! snow grain parameter 2              (-)\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWHIST  ! snow grain historical variable      (-)\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWAGE  ! Snow grain age\n!\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWTEMP  ! snow temperature profile            (K)\nREAL, DIMENSION(:,:), INTENT(INOUT)   :: PSNOWLIQ   ! snow liquid water profile           (m)\n!\nINTEGER, DIMENSION(:), INTENT(IN)      :: KNLVLS_USE\n CHARACTER(3), INTENT(IN)              :: HSNOWMETAMO ! metamorphism scheme\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWDZ,1)) :: ZSNOWHEAT_1D ! total heat content                (J/m2)\nREAL, DIMENSION(SIZE(PSNOWDZ,1)) :: ZSNOWRHO_1D  ! total snowpack average density    (kg/m3)\nREAL, DIMENSION(SIZE(PSNOWDZ,1)) :: ZSNOW        ! total snow depth                  (m)\nREAL, DIMENSION(SIZE(PSNOWDZ,1)) :: ZSCAP        ! Snow layer heat capacity          (J/K/m3)\nREAL, DIMENSION(SIZE(PSNOWDZ,1)) :: ZNDENT       ! Number of dendritic layers        (-)\nREAL, DIMENSION(SIZE(PSNOWDZ,1)) :: ZNVIEU       ! Number of non dendritic layers    (-)\nREAL, DIMENSION(SIZE(PSNOWDZ,1)) :: ZSNOWAGE_1D  ! total snowpack average\n!age (days)\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSNOWGRAN1N,           &\n                                                      ZSNOWGRAN2N,ZSNOWHISTN\n!\nLOGICAL :: GDENDRITIC\n!\nINTEGER :: JJ, JST          ! loop control\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWCROEVAPGONE',0,ZHOOK_HANDLE)\n!\n! Initialize:\n!\nZSNOWHEAT_1D(:) = 0.\nZSNOW(:)        = 0.\nZSNOWRHO_1D(:)  = 0.\nZNDENT(:)       = 0.\nZNVIEU(:)       = 0.\nZSNOWAGE_1D(:)  = 0.\nZSCAP(:)        = 0.\n!\n! First, determine where uppermost snow layer has completely\n! evaporated/sublimated (as it becomes thin):\nDO JJ = 1,SIZE(PSNOWRHO,1)\n   !\n   IF ( PSNOWDZ(JJ,1)==0.0 ) THEN\n     !\n     DO JST = 2,KNLVLS_USE(JJ)\n       !\n       ZSNOWHEAT_1D(JJ) = ZSNOWHEAT_1D(JJ) + PSNOWDZ(JJ,JST) * &\n                          ( PSNOWRHO(JJ,JST)*XCI * (ZSNOWTEMP(JJ,JST)-XTT) &\n                            - XLMTT * PSNOWRHO(JJ,JST) ) &\n                          + XLMTT * XRHOLW * PSNOWLIQ(JJ,JST)\n       ZSNOW       (JJ) = ZSNOW       (JJ) + PSNOWDZ(JJ,JST)\n       ZSNOWRHO_1D (JJ) = ZSNOWRHO_1D (JJ) + PSNOWDZ(JJ,JST) * PSNOWRHO(JJ,JST)\n       ZSNOWAGE_1D (JJ) = ZSNOWAGE_1D (JJ) + PSNOWDZ(JJ,JST) * PSNOWRHO(JJ,JST) * PSNOWAGE(JJ,JST)\n       !\n       ! snow grains\n       IF ( HSNOWMETAMO=='B92' ) THEN\n         GDENDRITIC = ( PSNOWGRAN1(JJ,JST)<-XEPSI )\n       ELSE\n         GDENDRITIC = ( PSNOWGRAN1(JJ,JST)<XVDIAM6*(4.-PSNOWGRAN2(JJ,JST))-XUEPSI )\n       ENDIF\n       !\n       IF ( GDENDRITIC ) THEN   ! Dendritic snow\n         ZNDENT(JJ) = ZNDENT(JJ) + 1.0\n       ELSE                                    ! Non dendritic snow\n         ZNVIEU(JJ) = ZNVIEU(JJ) + 1.0\n       ENDIF\n       !\n     ENDDO\n     !\n   ENDIF\n   !\nEND DO\n!\nZSNOWRHO_1D(:) = ZSNOWRHO_1D (:) / MAX( XSNOWDMIN, ZSNOW(:) )\nZSNOWAGE_1D(:) = ZSNOWAGE_1D (:) / MAX( XSNOWDMIN, ZSNOW(:) * ZSNOWRHO_1D(:) )\nZSNOWRHO_1D(:) = MAX( XRHOSMIN_ES, MIN( XRHOSMAX_ES, ZSNOWRHO_1D(:) ) )\n!\n! Where uppermost snow layer has vanished, redistribute vertical\n! snow mass and heat profiles (and associated quantities):\n!\n CALL SNOW3LAVGRAIN(PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,                 &\n                    ZSNOWGRAN1N,ZSNOWGRAN2N,ZSNOWHISTN,ZNDENT,ZNVIEU,&\n                    HSNOWMETAMO)\n!\nDO JJ=1,SIZE(PSNOWRHO,1)\n  !\n  IF( ZSNOW(JJ)/=0.0 ) THEN\n    !\n    PSNOWDZ  (JJ,1:KNLVLS_USE(JJ)) = ZSNOW(JJ) / KNLVLS_USE(JJ)\n    PSNOWHEAT(JJ,1:KNLVLS_USE(JJ)) = ZSNOWHEAT_1D(JJ) / KNLVLS_USE(JJ)\n    PSNOWRHO (JJ,1:KNLVLS_USE(JJ)) = ZSNOWRHO_1D(JJ)\n    !\n    ZSCAP(JJ) = ZSNOWRHO_1D(JJ) * XCI\n    !\n    DO JST = 1,KNLVLS_USE(JJ)\n      !\n      PSNOWTEMP(JJ,JST) = XTT + ( ( (PSNOWHEAT(JJ,JST)/PSNOWDZ(JJ,JST))   &\n                                    + XLMTT*PSNOWRHO(JJ,JST) ) / ZSCAP(JJ) )\n      PSNOWTEMP(JJ,JST) = MIN( XTT, PSNOWTEMP(JJ,JST) )\n      !\n      PSNOWLIQ (JJ,JST) = MAX( 0.0, PSNOWTEMP(JJ,JST)-XTT ) * ZSCAP(JJ) * &\n                                    PSNOWDZ(JJ,JST) / (XLMTT*XRHOLW)\n      !\n    ENDDO\n    !\n  ENDIF\n  !\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROEVAPGONE',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROEVAPGONE\n!\n!####################################################################\n!####################################################################\n!####################################################################\n!SUBROUTINE SNOWNLFALL_UPGRID(TPTIME, OGLACIER,PTSTEP,PSR,PTA,PVMOD,        &\nSUBROUTINE SNOWNLFALL_UPGRID(OGLACIER,PTSTEP,PSR,PTA,PVMOD,        &\n                             PSNOW,PSNOWRHO,PSNOWDZ,PSNOWHEAT,PSNOWHMASS,  &\n                             PSNOWALB,PPERMSNOWFRAC,PSNOWGRAN1,PSNOWGRAN2, &\n                             GSNOWFALL,PSNOWDZN,PSNOWRHOF,PSNOWDZF,        &\n                             PSNOWGRAN1F,PSNOWGRAN2F,PSNOWHISTF,PSNOWAGEF, &\n                             OMODIF_GRID,KNLVLS_USE,OSNOWDRIFT,PZ0EFF,PUREF,&\n                             HSNOWMETAMO)\n!\n!!    PURPOSE\n!!    -------\n! Adds new snowfall and updates the vertical grid in order to keep an\n! optimal discertisation\n!\n!!    AUTHOR\n!!    ------\n!!      E. Brun           * Meteo-France *\n!!\n!\n!!\n!!     MODIFICATIONS\n!!    ------\n!!\n!!     2014-02-05 V. Vionnet: wind speed in the parameterization for new snow\n!!                            density and characteristic of grains of new snow\n!!                            are taken at a reference height\n!!     2014-06-03 M. Lafaysse : threshold on PZ0EFF\n!!\n!USE MODD_TYPE_DATE_SURF,  ONLY: DATE_TIME\nUSE MODD_CSTS,     ONLY : XLMTT, XTT, XCI\nUSE MODD_SNOW_METAMO, ONLY : XNDEN1, XNDEN2, XNDEN3, XGRAN, &\n                             XNSPH1, XNSPH2, XNSPH3, XNSPH4\n!\nUSE MODD_SNOW_PAR, ONLY : XRHOSMIN_ES, XSNOWDMIN, XANSMAX, XAGLAMAX, XSNOWCRITD,   &\n                          XDZMIN_TOP, XDZMIN_TOP_BIS, XDZMIN_BOT, XSPLIT_COEF,     &\n                          XAGREG_COEF_1, XAGREG_COEF_2, XDZ1, XDZ2, XDZ3, XDZ3_BIS,&\n                          XDZ4, XDZ5, XDZ_BASE, XDZ_INTERNAL, XSCALE_CM,           &\n                          XDZMAX_INTERNAL, XDZMIN_TOP_EXTREM, XSNOWFALL_THRESHOLD, &\n                          XRATIO_NEWLAYER, XDEPTH_THRESHOLD1, XDEPTH_THRESHOLD2,   &\n                          XDEPTH_SURFACE, XDIFF_1, XDIFF_MAX, XSCALE_DIFF,         &\n                          XSNOWFALL_A_SN, XSNOWFALL_B_SN, XSNOWFALL_C_SN\n!\nUSE MODE_SNOW3L\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\n!TYPE(DATE_TIME), INTENT(IN)          :: TPTIME      ! current date and time\nLOGICAL, INTENT(IN)                  :: OGLACIER    ! True = Over permanent snow and ice,\n!                                                     initialise WGI=WSAT,\n!                                                     Hsnow>=10m and allow 0.8<SNOALB<0.85\n                                                    ! False = No specific treatment\n!\nREAL, INTENT(IN)                     :: PTSTEP\n!\nREAL, DIMENSION(:), INTENT(IN)       :: PSR, PTA, PVMOD, PPERMSNOWFRAC\n!\nREAL, DIMENSION(:),INTENT(IN)       :: PZ0EFF,PUREF\n!\nREAL, DIMENSION(:), INTENT(INOUT)   :: PSNOW, PSNOWALB\n!\nREAL, DIMENSION(:,:), INTENT(IN)     :: PSNOWRHO, PSNOWDZ, PSNOWHEAT\n!\nREAL, DIMENSION(:), INTENT(OUT)      :: PSNOWHMASS\n!\nREAL, DIMENSION(:,:), INTENT(IN)     :: PSNOWGRAN1, PSNOWGRAN2\n!\nLOGICAL, DIMENSION(:), INTENT(INOUT) :: GSNOWFALL\n!\n! Fresh snow characteristics\nREAL, DIMENSION(:), INTENT(OUT)      :: PSNOWRHOF, PSNOWDZF\nREAL, DIMENSION(:), INTENT(OUT)      :: PSNOWGRAN1F, PSNOWGRAN2F, PSNOWHISTF\nREAL, DIMENSION(:), INTENT(OUT)      :: PSNOWAGEF\n! New vertical grid\nREAL, DIMENSION(:,:), INTENT(OUT)    :: PSNOWDZN\n!\nLOGICAL, DIMENSION(:), INTENT(OUT)   :: OMODIF_GRID\n!\nINTEGER, DIMENSION(:), INTENT(INOUT) :: KNLVLS_USE\n\nLOGICAL,INTENT(IN) :: OSNOWDRIFT ! if snowdrift then grain types are not modified by wind\n CHARACTER(3), INTENT(IN)              :: HSNOWMETAMO ! metamorphism scheme\n!*      0.2    declarations of local variables\n!\n!\nLOGICAL, DIMENSION(SIZE(PTA))       :: GAGREG_SURF\n!\nREAL, DIMENSION(SIZE(PTA))          :: ZSNOWFALL, ZSNOWTEMP, ZSCAP, ZANSMAX\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZDZOPT\n!\nREAL :: ZZ0EFF\n!\nREAL :: ZAGE_NOW\nREAL :: ZSNOW_UPPER, ZSNOW_UPPER2 ! snow depth treatednormally (<= XDEPTH_SURFACE)\nREAL :: ZCOEF_DEPTH !coefficient for repartition of deep snow above 3 meters\nREAL :: ZTHICKNESS_INTERMEDIATE, ZTHICKNESS2\nREAL :: ZPENALTY, ZDIFTYPE_INF, ZDIFTYPE_SUP, ZCRITSIZE, ZCRITSIZE_INF, ZCRITSIZE_SUP\nREAL :: ZSNOW2L, ZCOEF\n!\nINTEGER :: INB_DEEP_LAYER, INB_UPPER_LAYER !separation between deep and upper layers\n                                           ! if snow depth below XDEPTH_SURFACE then INB_DEEP_LAYER=0\nINTEGER :: INB_MIN_LAYERS    ! why this test ?\nINTEGER :: INB_INTERMEDIATE  ! number of intermediate layers (constant optimal gridding)\nINTEGER :: IEND_INTERMEDIATE ! layer indice for bottom of intermediate layers\nINTEGER :: JSTDEEP, JSTEND\nINTEGER :: JST_1, JJ_A_AGREG_SUP, JJ_A_AGREG_INF, JJ_A_DEDOUB\nINTEGER :: INLVLS, INLVLSMIN, INLVLSMAX, JJ, JST\n!\n! Coefficient to adjust wind speed at the height used in the parameterization\n! for:\n!         - density of new snow\n!         - sphericity and dendricity of new snow\n! Default values : 10 m for new snow (Pahaut, 1976) and 5 m for characteristics\n! of snow grains (Guyomarc'h et Merindol, 1998)\nREAL, PARAMETER                    :: PPHREF_WIND_RHO   = 10.\nREAL, PARAMETER                    :: PPHREF_WIND_GRAIN = 5.\nREAL, PARAMETER                    :: PPHREF_WIND_MIN = MIN(PPHREF_WIND_RHO,PPHREF_WIND_GRAIN)*0.5\nREAL, DIMENSION(SIZE(PTA))         :: ZWIND_RHO\nREAL, DIMENSION(SIZE(PTA))         :: ZWIND_GRAIN\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!*      1.0   Initialization and snowage calculation for the present date\n!\n\n!IF (LHOOK) CALL DR_HOOK('SNOWNLFALL_UPGRID',0,ZHOOK_HANDLE)\n!\nINLVLS    = SIZE (PSNOWRHO(:,:),2)\nINLVLSMAX = SIZE (PSNOWRHO(:,:),2)\nINLVLSMIN = 3\n!\nZSNOWTEMP(:) = XTT\nZSNOWFALL(:) = 0.0 !Matthieu Lafaysse 21/09/2012\n!\nGSNOWFALL  (:) =.FALSE.\nGAGREG_SURF(:) =.FALSE.\n!\nPSNOWHMASS (:) = 0.0\nPSNOWRHOF  (:) = 0.0\nPSNOWDZF   (:) = 0.0\nPSNOWGRAN1F(:) = 0.0\nPSNOWGRAN2F(:) = 0.0\nPSNOWHISTF (:) = 0.0\nPSNOWDZN (:,:) = PSNOWDZ(:,:)\n!\nOMODIF_GRID(:) = .FALSE.\n!\n!************************************************************************************\n!*      1.1   Calculation of the optimal vertical grid size ZDZOPT\n!             as a function of maximum number of layers and of current\n!             snow depth (modified 05/06/2012 by Matthieu Lafaysse)\n!\n! KNLVLS_USE(JJ) > INB_MIN_LAYERS =>\n! KNLVLS_USE(JJ) > 2 + INLVLSMAX/3 =>\n! ( KNLVLS_USE(JJ) + INLVLSMAX ) / 6 > (2 + INLVLSMAX/3 + INLVLSMAX) / 6 =>\n! INB_DEEP_LAYER > (2 + 4*INLVLSMAX/3 ) / 6 >= 1\nINB_MIN_LAYERS = 2 + INLVLSMAX/3\n!\n DO JJ = 1,SIZE(PSNOW(:))\n  !\n  IF ( PSNOW(JJ)>XDEPTH_THRESHOLD2 .AND. KNLVLS_USE(JJ)>INB_MIN_LAYERS ) THEN\n    ! for very thick snowpack with enough snow layers\n    ! special treatment\n    ! we put the highest thickness in the lowest layers\n    ! about 1/3 of layers for all snow except XDEPTH_SURFACE=3 first meters\n    !\n    !number of \"deep layers\"\n    INB_DEEP_LAYER  = ( KNLVLS_USE(JJ) + INLVLSMAX ) / 6\n    !\n    !number of \"upper layers\"\n    INB_UPPER_LAYER = KNLVLS_USE(JJ) - INB_DEEP_LAYER\n    !\n    !thickness of \"upper layers\"\n    ZSNOW_UPPER = XDEPTH_SURFACE\n    !\n    !Arithmetic serie : 1+2+3+...+INB_DEEP_LAYER=INB_DEEP_LAYER*(INB_DEEP_LAYER+1)/2\n    ZCOEF_DEPTH = ( PSNOW(JJ) - XDEPTH_SURFACE ) * 2. / ( (INB_DEEP_LAYER+1) * INB_DEEP_LAYER )\n    !\n    ! deep layers optimal thickness :\n    ! increasing thickness with depth\n    DO JSTDEEP = 1,INB_DEEP_LAYER\n      JST = INB_UPPER_LAYER + JSTDEEP\n      ZDZOPT(JJ,JST) = ZCOEF_DEPTH * JSTDEEP\n      !This sum is equal to PSNOW(JJ)-XDEPTH_SURFACE\n    ENDDO\n    !\n  ELSE\n    !\n    INB_UPPER_LAYER = KNLVLS_USE(JJ)\n    !\n    ZSNOW_UPPER = PSNOW(JJ)\n    !\n  END IF\n  !\n  !on force le ZDZOPT des 3 premières couches à ZSNOW_UPPER/3 maximum, chacune.\n  ! => si on n'a qu'une couche, ZDZOPT(1) = ZSNOW_UPPER/3\n  ! quel que soit INB_UPPER_LAYER\n  !\n  ZSNOW_UPPER2 = ZSNOW_UPPER / MAX( INLVLSMIN, INB_UPPER_LAYER )\n  !\n  ZDZOPT(JJ,1) = MIN( XDZ1, ZSNOW_UPPER2 )\n  IF ( KNLVLS_USE(JJ)>=2 ) ZDZOPT(JJ,2) = MIN( XDZ2, ZSNOW_UPPER2 )\n  IF ( KNLVLS_USE(JJ)>=3 ) ZDZOPT(JJ,3) = MIN( XDZ3, ZSNOW_UPPER2 )\n  !\n  IF ( INB_UPPER_LAYER>0 ) THEN\n    !\n    ZSNOW_UPPER2 = ZSNOW_UPPER / INB_UPPER_LAYER\n    !\n    ! dans ce cas, à partir de la 3ème couche, on prend la fraction du nombre de\n    ! couches supérieures total, pour les couches jusqu'à 5\n    !\n    !ML : replace > by >= on 12-12-20 because the last layer was not initialised in case of thick snowpacks\n    IF ( INB_UPPER_LAYER>=3 ) ZDZOPT(JJ,3) = MIN( XDZ3_BIS, ZSNOW_UPPER2 )\n    IF ( INB_UPPER_LAYER>=4 ) ZDZOPT(JJ,4) = MIN( XDZ4    , ZSNOW_UPPER2 )\n    IF ( INB_UPPER_LAYER>=5 ) ZDZOPT(JJ,5) = MIN( XDZ5    , ZSNOW_UPPER2 )\n    !\n    IF ( INB_UPPER_LAYER==KNLVLS_USE(JJ) ) THEN\n      ! si on n'a pas de couches profondes\n      !\n      ! dans ce cas, on reprend ZSNOW_UPPER/3 maximum pour la dernière couche\n      !\n      ! last layer of' upper layers' : normal case : thin layer\n      ZDZOPT(JJ,INB_UPPER_LAYER) = MIN( XDZ_BASE, ZSNOW_UPPER/MAX(INLVLSMIN,INB_UPPER_LAYER) )\n      !\n      ! ZTHICKNESS_INTERMEDIATE contient ce qu'il reste d'épaisseur disponible\n      ! dans les couches supérieures\n      !remaining snow for remaining layers\n      ZTHICKNESS_INTERMEDIATE = ZSNOW_UPPER - SUM(ZDZOPT(JJ,1:5)) - ZDZOPT(JJ,INB_UPPER_LAYER)\n\n      IF ( ZSNOW_UPPER<=XDEPTH_THRESHOLD1 .OR. INB_UPPER_LAYER<8 ) THEN\n        INB_INTERMEDIATE  = INB_UPPER_LAYER - 6\n        IEND_INTERMEDIATE = INB_UPPER_LAYER - 1\n      ELSE\n        ! si INB_UPPER_LAYER>=8, les avant et avant-dernière couches ne sont pas\n        ! considérées commes intermédiaires\n        INB_INTERMEDIATE  = INB_UPPER_LAYER - 8\n        IEND_INTERMEDIATE = INB_UPPER_LAYER - 3\n        ! dans ce cas, on garde un peu d'épaisseur pour les deux couches restantes\n        IF ( INB_INTERMEDIATE>0 ) THEN\n          ZTHICKNESS_INTERMEDIATE = ZTHICKNESS_INTERMEDIATE * INB_INTERMEDIATE / FLOAT(INB_INTERMEDIATE+1)\n        END IF\n      END IF\n      !\n    ELSE\n      ! si on a des couches profondes, les couches intermédiaires sont celles\n      ! qui restent quand on a enlevé les 5 premières des couches supérieures\n      !\n      ! case with very thick snowpacks :\n      ! the last layer of upper layers is not an exception\n      ZTHICKNESS_INTERMEDIATE = ZSNOW_UPPER - SUM(ZDZOPT(JJ,1:5))\n      INB_INTERMEDIATE  = INB_UPPER_LAYER - 5\n      IEND_INTERMEDIATE = INB_UPPER_LAYER\n      !\n    END IF\n    !\n    ! For thick snowpack : add maximum value of optimal thickness to avoid too\n    ! large differencies between layers\n    IF ( INB_INTERMEDIATE>0 ) THEN\n      !\n      ZTHICKNESS2 = MAX( XDZ_INTERNAL, ZTHICKNESS_INTERMEDIATE/INB_INTERMEDIATE )\n      !\n      JSTEND = MIN( IEND_INTERMEDIATE,10 )\n      DO JST = 6,JSTEND\n        ZDZOPT(JJ,JST) = MIN( XDZMAX_INTERNAL(JST-5), ZTHICKNESS2 )\n      END DO\n      !\n      IF ( IEND_INTERMEDIATE>10 ) THEN\n        DO JST = 11,IEND_INTERMEDIATE\n          ZDZOPT(JJ,JST) = ZTHICKNESS2\n        END DO\n      END IF\n      !\n    END IF\n    !\n    IF ( ZSNOW_UPPER>=XDEPTH_THRESHOLD1 .AND. INB_UPPER_LAYER>=8 ) THEN\n      !Linear interpolation of optimal thickness between layers N-3 and N :\n      ZDZOPT(JJ,INB_UPPER_LAYER-2) = 0.34*ZDZOPT(JJ,INB_UPPER_LAYER) + &\n                                     0.66*ZDZOPT(JJ,INB_UPPER_LAYER-3)\n      ZDZOPT(JJ,INB_UPPER_LAYER-1) = 0.66*ZDZOPT(JJ,INB_UPPER_LAYER) + &\n                                     0.34*ZDZOPT(JJ,INB_UPPER_LAYER-3)\n    ENDIF\n    !\n  END IF\n  !\nEND DO\n!\n!************************************************************************************\n!This was the initial code for optimal layers until may 2012\n!\n! ! ! ! !\n! ! ! ! ! !*      1.1   Calculation of the optimal vertical grid size\n! ! ! ! ! !             as a function of maximum number of layers and of current\n! ! ! ! ! !             snow depth\n! ! ! ! ! !\n! ! ! ! ! DO JJ=1, SIZE(PSNOW(:))\n! ! ! ! !    ZDZOPT(JJ,1) = MIN(XDZ1,PSNOW(JJ)/MAX(INLVLSMIN,KNLVLS_USE(JJ)))\n! ! ! ! !    ZDZOPT(JJ,2) = MIN(XDZ2,PSNOW(JJ)/MAX(INLVLSMIN,KNLVLS_USE(JJ)))\n! ! ! ! !    ZDZOPT(JJ,3) = MIN(XDZ3,PSNOW(JJ)/MAX(INLVLSMIN,KNLVLS_USE(JJ)))\n! ! ! ! !    IF (KNLVLS_USE(JJ)>3)  ZDZOPT(JJ,3) = MIN(XDZ3_BIS,PSNOW(JJ)/KNLVLS_USE(JJ))\n! ! ! ! !    IF (KNLVLS_USE(JJ)>4)  ZDZOPT(JJ,4) = MIN(XDZ4,PSNOW(JJ)/KNLVLS_USE(JJ))\n! ! ! ! !    IF (KNLVLS_USE(JJ)>5)  ZDZOPT(JJ,5) = MIN(XDZ5,PSNOW(JJ)/KNLVLS_USE(JJ))\n! ! ! ! !    IF (KNLVLS_USE(JJ)>0) ZDZOPT(JJ,KNLVLS_USE(JJ))=   &\n! ! ! ! !               MIN(XDZ_BASE,PSNOW(JJ)/MAX(INLVLSMIN,KNLVLS_USE(JJ)))\n! ! ! ! !    DO JST=6,KNLVLS_USE(JJ)-1,1\n! ! ! ! !        ZDZOPT(JJ,JST) = MAX(XDZ_INTERNAL,(PSNOW(JJ) - SUM(ZDZOPT(JJ,1:5))-    &\n! ! ! ! !                          ZDZOPT(JJ,KNLVLS_USE(JJ))) /(KNLVLS_USE(JJ)-6))\n! ! ! ! !    END DO\n! ! ! ! ! END DO\n! ! ! ! ! !\n! ! ! ! !\n!\n!************************************************************************************\n!\n!*      2.0   Fresh snow characteristics\n!\n!\n!\n! Heat content of newly fallen snow (J/m2):\n! NOTE for now we assume the snowfall has\n! the temperature of the snow surface upon reaching the snow.\n! This is done as opposed to using the air temperature since\n! this flux is quite small and has little to no impact\n! on the time scales of interest. If we use the above assumption\n! then, then the snowfall advective heat flux is zero.\n!!\nDO JJ = 1,SIZE(PSNOW(:))\n  !\n  IF ( PSR(JJ)>0.0 ) THEN\n    !\n    ! newly fallen snow characteristics:\n    IF ( KNLVLS_USE(JJ)>0 ) THEN !Case of new snowfall on a previously snow-free surface\n      ZSCAP    (JJ) = XCI*PSNOWRHO(JJ,1)\n      ZSNOWTEMP(JJ) = XTT + ( PSNOWHEAT(JJ,1) + XLMTT*PSNOWRHO(JJ,1)*PSNOWDZ(JJ,1) ) / &\n                            ( ZSCAP(JJ) * MAX( XSNOWDMIN/INLVLS, PSNOWDZ(JJ,1) ) )\n    ELSE  ! case with bare ground\n      ZSNOWTEMP(JJ) = PTA(JJ)\n    ENDIF\n    ZSNOWTEMP(JJ) = MIN( XTT, ZSNOWTEMP(JJ) )\n    !\n    !\n    ! Wind speeds at reference heights for new snow density and charactristics of\n    ! grains of new snow\n    ! Computed from PVMOD at PUREF (m) assuming a log profile in the SBL\n    ! and a roughness length equal to PZ0EFF\n    !\n    ZZ0EFF=MIN(PZ0EFF(JJ),PUREF(JJ)*0.5,PPHREF_WIND_MIN)\n\n    ZWIND_RHO(JJ)   = PVMOD(JJ)*LOG(PPHREF_WIND_RHO/ZZ0EFF)/          &\n                               LOG(PUREF(JJ)/ZZ0EFF)\n    ZWIND_GRAIN(JJ) = PVMOD(JJ)*LOG(PPHREF_WIND_GRAIN/ZZ0EFF)/        &\n                               LOG(PUREF(JJ)/ZZ0EFF)\n\n    PSNOWHMASS(JJ) = PSR(JJ) * ( XCI * ( ZSNOWTEMP(JJ)-XTT ) - XLMTT ) * PTSTEP\n    !\n    PSNOWRHOF (JJ) = MAX( XRHOSMIN_ES, XSNOWFALL_A_SN + &\n                                       XSNOWFALL_B_SN * ( PTA(JJ)-XTT ) + &\n                                       XSNOWFALL_C_SN * MIN( PVMOD(JJ), SQRT(ZWIND_RHO(JJ) ) ) )\n    ZSNOWFALL (JJ) = PSR(JJ) * PTSTEP / PSNOWRHOF(JJ)    ! snowfall thickness (m)\n    PSNOW     (JJ) = PSNOW(JJ) + ZSNOWFALL(JJ)\n    PSNOWDZF  (JJ) = ZSNOWFALL(JJ)\n    !\n    IF ( HSNOWMETAMO=='B92' ) THEN\n      !\n      IF ( OSNOWDRIFT ) THEN\n        PSNOWGRAN1F(JJ) = -XGRAN\n        PSNOWGRAN2F(JJ) = XNSPH3\n      ELSE\n        PSNOWGRAN1F(JJ) = MAX( MIN( XNDEN1*ZWIND_GRAIN(JJ)-XNDEN2, XNDEN3 ), -XGRAN )\n        PSNOWGRAN2F(JJ) = MIN( MAX( XNSPH1*ZWIND_GRAIN(JJ)+XNSPH2, XNSPH3 ), XNSPH4 )\n      END IF\n      !\n    ELSE\n      !\n      IF ( OSNOWDRIFT ) THEN\n        PSNOWGRAN1F(JJ) = XVDIAM6\n        PSNOWGRAN2F(JJ) = XNSPH3/XGRAN\n      ELSE\n        PSNOWGRAN2F(JJ) = MIN( MAX( XNSPH1*ZWIND_GRAIN(JJ)+XNSPH2, XNSPH3 ), XNSPH4 ) / XGRAN\n        ZCOEF = MAX( MIN( XNDEN1*ZWIND_GRAIN(JJ)-XNDEN2, XNDEN3 ), -XGRAN ) / ( -XGRAN )\n        PSNOWGRAN1F(JJ) = XVDIAM6 * &\n                        ( ZCOEF + ( 1.- ZCOEF ) * &\n                                  ( 3.*PSNOWGRAN2F(JJ) + 4.*(1.-PSNOWGRAN2F(JJ)) ) )\n      END IF\n      !\n    ENDIF\n    !\n    PSNOWHISTF (JJ) = 0.0\n    PSNOWAGEF  (JJ) = 0.0\n    GSNOWFALL  (JJ) = .TRUE.\n    OMODIF_GRID(JJ) = .TRUE.\n    !\n  ENDIF\n  !\nENDDO\n!\n!  intialize the albedo:\n!  penser a changer 0.000001 par XUEPSI\nIF(OGLACIER)THEN\n  ZANSMAX(:) = XAGLAMAX * PPERMSNOWFRAC(:) + XANSMAX * (1.0-PPERMSNOWFRAC(:))\nELSE\n  ZANSMAX(:) = XANSMAX\nENDIF\n!\nWHERE( GSNOWFALL(:) .AND. ABS(PSNOW(:)-ZSNOWFALL(:))< 0.000001 )\n  PSNOWALB(:) = ZANSMAX(:)\nEND WHERE\n\n!\n! Computation of the new grid size\n! It starts with successive exclusive cases\n! Each case is described inside the corresponding condition\n!\n! cases with fresh snow\n!\n\nDO JJ=1,SIZE(PSNOW(:)) ! grid point loop\n  !\n  IF( .NOT.GSNOWFALL(JJ) .AND. PSNOW(JJ)>=XSNOWCRITD .AND. KNLVLS_USE(JJ)>=INLVLSMIN ) THEN\n    !\n    ! no fresh snow + deep enough snowpack + enough snow layers ==> no change\n    !\n  ELSEIF( PSNOW(JJ)<XSNOWCRITD .OR. KNLVLS_USE(JJ)<INLVLSMIN .OR. PSNOW(JJ)==ZSNOWFALL(JJ) ) THEN\n    !\n    ! too shallow snowpack or too few layers or only fresh snow\n    ! ==> uniform grid and identical snow layers / number depends on snow depth\n    OMODIF_GRID(JJ) = .TRUE.\n    KNLVLS_USE (JJ) = MAX( INLVLSMIN, MIN( INLVLSMAX, INT(PSNOW(JJ)*XSCALE_CM) ) )\n    PSNOWDZN(JJ,1:KNLVLS_USE(JJ)) = PSNOW(JJ) / KNLVLS_USE(JJ)\n    !\n  ELSE\n    !\n    ! fresh snow over snow covered ground + enough snow layers\n    OMODIF_GRID(JJ) = .TRUE.\n    ZDIFTYPE_SUP = SNOW3LDIFTYP( PSNOWGRAN1(JJ,1),PSNOWGRAN1F(JJ), &\n                                 PSNOWGRAN2(JJ,1),PSNOWGRAN2F(JJ),HSNOWMETAMO )\n    !\n    IF ( ( ZDIFTYPE_SUP<XDIFF_1        .AND. PSNOWDZ(JJ,1)<   ZDZOPT(JJ,1) ) .OR. &\n         ( PSR(JJ)<XSNOWFALL_THRESHOLD .AND. PSNOWDZ(JJ,1)<2.*ZDZOPT(JJ,1) ) .OR. &\n                                             PSNOWDZ(JJ,1)<XDZMIN_TOP_EXTREM ) THEN\n      !\n      ! Fresh snow is similar to a shallow surface layer (< ZDZOPT)\n      ! or snowfall is very low and the surface layer not too deep (< 2*ZDZOPT) [NEW CONDITION 11/2012]\n      ! or the surface layer is extremely thin (< XDZMIN_TOP_EXTREM) [NEW CONDITION 11/2012]\n      ! The two new conditions are necessary for forcings with very low precipitation\n      ! (e.g. ERA interim reanalyses, or climate models)\n      ! ==> fresh snow is agregated to the surface layer\n      PSNOWDZN(JJ,1) = PSNOWDZ(JJ,1) + PSNOWDZF(JJ)\n      DO JST = KNLVLS_USE(JJ),2,-1\n        PSNOWDZN(JJ,JST) = PSNOWDZ(JJ,JST)\n      ENDDO\n      !\n    ELSEIF ( KNLVLS_USE(JJ)<INLVLSMAX ) THEN\n      !\n      ! fresh snow is too different from the surface or the surface is too deep\n      ! and there is room for extra layers ==> we create a new layer\n      KNLVLS_USE(JJ)=KNLVLS_USE(JJ)+1\n      !\n      IF ( PSNOWDZF(JJ)>XRATIO_NEWLAYER*PSNOWDZ(JJ,2) ) THEN\n        !\n        ! Snowfall is sufficient to create a new layer not lower than 1/10 of the second layer\n        PSNOWDZN(JJ,1) = PSNOWDZF(JJ)\n        DO JST = KNLVLS_USE(JJ),2,-1\n          PSNOWDZN(JJ, JST) = PSNOWDZ(JJ,JST-1)\n        ENDDO\n        !\n      ELSE\n        ! The ratio would be lower than 1/10 : [NEW : 11/2012]\n        ! aggregate a part of the old layer with fresh snow to limit the ratio to 1/10.\n        ZSNOW2L = PSNOWDZF(JJ) + PSNOWDZ(JJ,1)\n        PSNOWDZN(JJ,1) = XRATIO_NEWLAYER      * ZSNOW2L\n        PSNOWDZN(JJ,2) = (1.-XRATIO_NEWLAYER) * ZSNOW2L\n        DO JST = KNLVLS_USE(JJ),3,-1\n          PSNOWDZN(JJ,JST) = PSNOWDZ(JJ,JST-1)\n        ENDDO\n        !\n      ENDIF\n      !\n    ELSE\n      !\n      ! fresh snow is too different from the surface or the surface is too deep\n      ! and there is no room for extra layers\n      ! ==> we agregate internal most similar snowlayers and create a new surface layer\n      JJ_A_AGREG_SUP = 1\n      JJ_A_AGREG_INF = 2\n      !\n      DO JST = 1,KNLVLS_USE(JJ)\n        !\n        IF ( JST>1 ) THEN\n          !\n          ZCRITSIZE_SUP = XSCALE_DIFF * ( PSNOWDZ(JJ,JST)  /ZDZOPT(JJ,JST)    + &\n                                          PSNOWDZ(JJ,JST-1)/ZDZOPT(JJ,JST-1) )\n          ZDIFTYPE_SUP  = SNOW3LDIFTYP( PSNOWGRAN1(JJ,JST-1),PSNOWGRAN1(JJ,JST), &\n                                        PSNOWGRAN2(JJ,JST-1),PSNOWGRAN2(JJ,JST), &\n                                        HSNOWMETAMO )\n          !\n          IF ( ZDIFTYPE_SUP+ZCRITSIZE_SUP<ZPENALTY ) THEN\n            ZPENALTY = ZDIFTYPE_SUP + ZCRITSIZE_SUP\n            JJ_A_AGREG_SUP = JST - 1\n            JJ_A_AGREG_INF = JST\n          ENDIF\n          !\n        ENDIF\n        !\n        IF ( JST<KNLVLS_USE(JJ) ) THEN\n          !\n          ZCRITSIZE_INF = XSCALE_DIFF * ( PSNOWDZ(JJ,JST)  /ZDZOPT(JJ,JST)    + &\n                                          PSNOWDZ(JJ,JST+1)/ZDZOPT(JJ,JST+1) )\n          !\n          IF ( JST==1 ) THEN\n            ZDIFTYPE_INF  = SNOW3LDIFTYP( PSNOWGRAN1(JJ,1),PSNOWGRAN1F(JJ), &\n                                          PSNOWGRAN2(JJ,1),PSNOWGRAN2F(JJ), &\n                                          HSNOWMETAMO)\n            !\n            ZPENALTY = ZDIFTYPE_INF + ZCRITSIZE_INF\n          ELSE\n            ZDIFTYPE_INF  = SNOW3LDIFTYP( PSNOWGRAN1(JJ,JST+1),PSNOWGRAN1(JJ,JST), &\n                                          PSNOWGRAN2(JJ,JST+1),PSNOWGRAN2(JJ,JST), &\n                                          HSNOWMETAMO)\n            !\n            IF ( ZDIFTYPE_INF+ZCRITSIZE_INF<ZPENALTY ) THEN\n              ZPENALTY = ZDIFTYPE_INF + ZCRITSIZE_INF\n              JJ_A_AGREG_SUP = JST\n              JJ_A_AGREG_INF = JST + 1\n            ENDIF\n          ENDIF\n          !\n        ENDIF\n        !\n      ENDDO\n      !\n      ! agregation of the similar layers and shift of upper layers\n      PSNOWDZN(JJ,JJ_A_AGREG_INF) = PSNOWDZ(JJ,JJ_A_AGREG_INF) + PSNOWDZ(JJ,JJ_A_AGREG_SUP)\n      DO JST = JJ_A_AGREG_SUP,2,-1\n        PSNOWDZN(JJ,JST) = PSNOWDZ(JJ,JST-1)\n      ENDDO\n      PSNOWDZN(JJ,1) = PSNOWDZF(JJ)\n      !\n      ! Limit the ratio between the new layer and the one beneath (ratio 1/10)\n      ! [NEW : 11/2012]\n      IF( PSNOWDZN(JJ,1)<XRATIO_NEWLAYER*PSNOWDZN(JJ,2) ) THEN\n        ZSNOW2L = PSNOWDZN(JJ,1) + PSNOWDZN(JJ,2)\n        PSNOWDZN(JJ,1) = XRATIO_NEWLAYER      * ZSNOW2L\n        PSNOWDZN(JJ,2) = (1.-XRATIO_NEWLAYER) * ZSNOW2L\n      ENDIF\n      !\n    ENDIF\n    !\n  ENDIF ! end of the case with fresh snow\nENDDO ! end loop grid points\n\n!\n! cases with no fresh snow and no previous grid resize\n!\nIF ( INLVLSMIN==INLVLSMAX ) THEN ! specific case with INLSVSMIN = INLVLSMAX  (INLVLS)\n  !\n  ! check if surface layer depth is too small\n  ! in such a case looks for an other layer to be split\n  DO JJ = 1,SIZE(PSNOW(:)) ! loop grid points\n    !\n    IF ( .NOT.OMODIF_GRID(JJ) .AND. PSNOWDZ(JJ,1)<XDZMIN_TOP ) THEN\n      OMODIF_GRID(JJ) = .TRUE.\n      CALL GET_SNOWDZN_DEB(INLVLS,PSNOWDZ(JJ,:),ZDZOPT(JJ,:),PSNOWDZN(JJ,:))\n      GAGREG_SURF(JJ) = .TRUE.\n    ENDIF\n    ! check if bottom layer depth is too small\n    ! in such a case agregation with upper layer and\n    ! looks for an other layer to be splitted\n    IF( .NOT.OMODIF_GRID(JJ) .AND. PSNOWDZ(JJ,INLVLS)<XDZMIN_TOP ) THEN\n      OMODIF_GRID(JJ) = .TRUE.\n      CALL GET_SNOWDZN_END(INLVLS,PSNOWDZ(JJ,:),ZDZOPT(JJ,:),PSNOWDZN(JJ,:))\n    ENDIF\n    !\n  ENDDO ! end grid points loop\n  !\nENDIF  ! end specific case INLSVSMIN = INLVLSMAX\n!\n! case without new snowfall and INVLS > INLVLSMIN\n!\nDO JJ=1,SIZE(PSNOW(:))\n  !\n  ! check if surface layer depth is too small\n  ! in such a case agregation with layer beneath\n  ! in case of reaching INLVLSMIN, looks for an other layer to be splitted\n  IF( .NOT.GSNOWFALL(JJ) .AND. PSNOW(JJ)>XSNOWCRITD .AND. &\n      .NOT.OMODIF_GRID(JJ) .AND. PSNOWDZ(JJ,1)<XDZMIN_TOP_BIS ) THEN ! case shallow surface layer\n    !\n    OMODIF_GRID(JJ) = .TRUE.\n    !\n    IF( KNLVLS_USE(JJ)>INLVLSMIN ) THEN ! case minimum not reached\n      KNLVLS_USE(JJ) = KNLVLS_USE(JJ) - 1\n      PSNOWDZN(JJ,1) = PSNOWDZ(JJ,1) + PSNOWDZ(JJ,2)\n      DO JST = 2,KNLVLS_USE(JJ)\n        PSNOWDZN(JJ,JST) = PSNOWDZ(JJ,JST+1)\n      ENDDO\n    ELSE ! case minimum reached\n      CALL GET_SNOWDZN_DEB(KNLVLS_USE(JJ),PSNOWDZ(JJ,:),ZDZOPT(JJ,:),PSNOWDZN(JJ,:))\n    ENDIF ! end case minimum reached end case shallow surface layer\n    !\n    GAGREG_SURF(JJ) = .TRUE.\n    !\n  ENDIF\n  !\n  ! check if bottom layer depth is too small\n  ! in such a case agregation with above layer\n  ! in case of reaching INLVLSMIN, looks for an other layer to be splitted\n  ! case shallow bottom layer\n\n  IF( .NOT.GSNOWFALL(JJ) .AND. PSNOW(JJ)> XSNOWCRITD                   .AND. &\n      .NOT.OMODIF_GRID(JJ) .AND. PSNOWDZ(JJ,KNLVLS_USE(JJ))<XDZMIN_TOP .AND. &\n      .NOT.GAGREG_SURF(JJ) ) THEN\n    !\n    OMODIF_GRID(JJ) = .TRUE.\n    !\n    IF ( KNLVLS_USE(JJ)>INLVLSMIN ) THEN ! case minimum not reached\n      KNLVLS_USE(JJ) = KNLVLS_USE(JJ) - 1\n      PSNOWDZN(JJ,KNLVLS_USE(JJ)) = PSNOWDZ(JJ,KNLVLS_USE(JJ)) + PSNOWDZ(JJ,KNLVLS_USE(JJ)+1)\n    ELSE  ! case minimum reached\n      CALL GET_SNOWDZN_END(KNLVLS_USE(JJ),PSNOWDZ(JJ,:),ZDZOPT(JJ,:),PSNOWDZN(JJ,:))\n    ENDIF ! end case minimum reached end case shallow surface layer\n    !\n  ENDIF\n  !\nENDDO ! end grid points loop\n!\n! case whithout new snow fall and without a previous grid resize\n! looks for a shallow layer to be splitted according to its depth and to\n! the optimal grid size\nDO JJ = 1,SIZE(PSNOW(:))\n  !\n  IF ( .NOT.OMODIF_GRID(JJ) .AND. INLVLS_USE(JJ)<INLVLS-3 )THEN\n    !\n    DO JST = 1,INLVLS-4\n      !\n      IF ( JST<=KNLVLS_USE(JJ) .AND. .NOT.OMODIF_GRID(JJ) ) THEN\n        !\n        IF( PSNOWDZ(JJ,JST) > &\n            ( XSPLIT_COEF - FLOAT( INLVLS-KNLVLS_USE(JJ) )/MAX( 1., FLOAT( INLVLS-INLVLSMIN ) ) ) &\n              * ZDZOPT(JJ,JST) ) THEN\n          !\n          DO JST_1 = KNLVLS_USE(JJ)+1,JST+2,-1\n            PSNOWDZN(JJ,JST_1) = PSNOWDZ(JJ,JST_1-1)\n            ZDZOPT  (JJ,JST_1) = ZDZOPT (JJ,JST_1-1)\n          ENDDO\n          !\n          ! generale case : old layer divided in two equal layers\n          IF ( JST/=1 .OR. PSNOWDZ(JJ,JST)<3.*ZDZOPT(JJ,1) ) THEN\n            PSNOWDZN(JJ,JST+1) = 0.5*PSNOWDZ(JJ,JST)\n            PSNOWDZN(JJ,JST)   = PSNOWDZN(JJ,JST+1)\n          ELSE\n            ! if thick surface layer : force the surface layer to this value to avoid successive resizing\n            ! [NEW : 11/2012]\n            PSNOWDZN(JJ,1) = 1.5 * ZDZOPT(JJ,1)\n            PSNOWDZN(JJ,2) = PSNOWDZ(JJ,JST) - PSNOWDZN(JJ,1)\n          ENDIF\n          !\n          KNLVLS_USE (JJ) = KNLVLS_USE(JJ) + 1\n          OMODIF_GRID(JJ) = .TRUE.\n          !\n        ENDIF\n        !\n      ENDIF\n      !\n    ENDDO\n    !\n  ENDIF\n  !\nENDDO\n!\n! case whithout new snow fall and without a previous grid resize\n! looks for a deep layer to be agregated to the layer beneath if similar\n! according to its depth and to the optimal grid size\n!\n!NB : allow these changes for 5 layers and more [NEW] (before : 6 layers)\n!\nDO JJ = 1,SIZE(PSNOW(:))\n  !\n  IF ( .NOT.OMODIF_GRID(JJ) ) THEN\n    !\n    DO JST = 2,INLVLS\n      !\n      IF ( JST<=KNLVLS_USE(JJ)-1 .AND. KNLVLS_USE(JJ)>INLVLSMIN+1 .AND. .NOT.OMODIF_GRID(JJ) ) THEN\n        !\n        ZDIFTYPE_INF = SNOW3LDIFTYP( PSNOWGRAN1(JJ,JST+1),PSNOWGRAN1(JJ, JST), &\n                                     PSNOWGRAN2(JJ,JST+1),PSNOWGRAN2(JJ, JST), &\n                                     HSNOWMETAMO)\n        ZDIFTYPE_INF = MAX( XDIFF_1, MIN( XDIFF_MAX, ZDIFTYPE_INF ) )\n        !\n        IF( PSNOWDZ(JJ,JST) < ZDZOPT(JJ,JST) * XAGREG_COEF_1 / ZDIFTYPE_INF .AND. &\n            PSNOWDZ(JJ,JST) + PSNOWDZ(JJ,JST+1) < &\n                XAGREG_COEF_2 * MAX( ZDZOPT(JJ,JST),ZDZOPT(JJ,JST+1) ) ) THEN\n          !\n          PSNOWDZN(JJ,JST) = PSNOWDZ(JJ,JST) + PSNOWDZ(JJ,JST+1)\n          ZDZOPT  (JJ,JST) = ZDZOPT(JJ,JST+1)\n          DO JST_1 = JST+1,KNLVLS_USE(JJ)-1\n            PSNOWDZN(JJ,JST_1) = PSNOWDZ(JJ,JST_1+1)\n            ZDZOPT  (JJ,JST_1) = ZDZOPT (JJ,JST_1+1)\n          ENDDO\n          KNLVLS_USE(JJ) = KNLVLS_USE(JJ)-1\n          OMODIF_GRID(JJ)=.TRUE.\n          !\n        ENDIF\n        !\n      ENDIF\n      !\n    ENDDO\n    !\n  ENDIF\n  !\nENDDO\n!\n! [NEW : 11/2012]\n! In case of very low snow fall checks if a new internal snow layer is too shallow\n! even if a the grid has already been resized in this time step\n! starts from bottom to INLVS_USE-3 until old and new grid differ\nDO JJ = 1,SIZE(PSNOW(:))\n  !\n  IF ( .NOT.GSNOWFALL(JJ) .OR. KNLVLS_USE(JJ)<INLVLSMIN+3 ) CYCLE ! go to next point\n  !\n  IF( ABS( PSNOWDZN(JJ,KNLVLS_USE(JJ)) - PSNOWDZ(JJ,KNLVLS_USE(JJ)) ) > XUEPSI ) CYCLE ! go to next point\n  !\n  ! bottom layer\n  IF( PSNOWDZN(JJ,KNLVLS_USE(JJ))<XDZMIN_TOP ) THEN ! case shallow bottom layer\n    !\n    KNLVLS_USE(JJ) = KNLVLS_USE(JJ)-1\n    PSNOWDZN(JJ,KNLVLS_USE(JJ)) = PSNOWDZN(JJ,KNLVLS_USE(JJ)) + PSNOWDZN(JJ,KNLVLS_USE(JJ)+1)\n    PSNOWDZN(JJ,KNLVLS_USE(JJ)+1) = 0.\n    !\n  ELSE\n    !\n    ! internal layer\n    DO JST = KNLVLS_USE(JJ)-1,4,-1\n      !\n      IF ( ABS( PSNOWDZN(JJ,JST) - PSNOWDZ(JJ,JST) ) > XUEPSI ) EXIT ! old/new grid differ ==> go to next grid point\n      !\n      IF ( PSNOWDZN(JJ,JST)> 0.001 ) CYCLE\n      !\n      ! If an internal layer is too shallow, it is merged with the upper layer\n      PSNOWDZN(JJ,JST-1) = PSNOWDZN(JJ,JST) + PSNOWDZN(JJ,JST-1)\n      KNLVLS_USE(JJ)   = KNLVLS_USE(JJ) - 1\n      !\n      ! shifts the lower layers\n      DO JST_1 = JST,INLVLS_USE(JJ)\n        PSNOWDZN(JJ,JST_1) = PSNOWDZ(JJ,JST_1+1)\n        ZDZOPT  (JJ,JST_1) = ZDZOPT (JJ,JST_1+1)\n      ENDDO\n      PSNOWDZN(JJ,INLVLS_USE(JJ)+1) = 0.\n      !\n      EXIT ! goto to next grid point\n      !\n    ENDDO ! end loop internal layers\n    !\n  ENDIF\n  !\nENDDO ! end grid loops for checking shallow layers\n!\n!final check of the consistensy of the new grid size\n!\n#ifdef DEBUG\nDO JJ = 1,SIZE(PSNOW(:))\n  !\n! trude test, increase xuepsi limit\n  IF ( ABS( SUM( PSNOWDZN(JJ,1:KNLVLS_USE(JJ)) ) - PSNOW(JJ) ) > XUEPSI*10000. ) THEN\n!  IF ( ABS( SUM( PSNOWDZN(JJ,1:KNLVLS_USE(JJ)) ) - PSNOW(JJ) ) > XUEPSI*1000. ) THEN\n    !\n    WRITE(*,*) 'error in grid resizing', JJ, KNLVLS_USE(JJ), SUM( PSNOWDZN(JJ,1:KNLVLS_USE(JJ)) ),  &\n                                         PSNOW(JJ), SUM( PSNOWDZN(JJ,1:INLVLS_USE(JJ)) )-PSNOW(JJ), &\n                                         ZSNOWFALL(JJ)\n\n!    CALL ABOR1_SFX(\"SNOWCRO: error in grid resizing\")\n    !\n  ENDIF\n  !\nENDDO\n#endif\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWNLFALL_UPGRID',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWNLFALL_UPGRID\n\n!###############################################################################\nSUBROUTINE GET_SNOWDZN_DEB(KNLVLS,PSNOWDZ,PDZOPT,PSNOWDZN)\n!\nUSE MODD_SNOW_PAR, ONLY : XDZMIN_TOP, XDZMIN_BOT\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\nINTEGER, INTENT(IN) :: KNLVLS\nREAL, DIMENSION(:), INTENT(IN)  :: PSNOWDZ, PDZOPT\nREAL, DIMENSION(:), INTENT(OUT) :: PSNOWDZN\n!\nREAL :: ZPENALTY, ZCRITSIZE\nINTEGER :: JJ_A_DEDOUB, JST\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_SNOWDZN_DEB',0,ZHOOK_HANDLE)\n!\nZPENALTY = PSNOWDZ(2) / PDZOPT(2)\nIF( PSNOWDZ(2)<XDZMIN_TOP ) ZPENALTY = 0.\nJJ_A_DEDOUB = 2\n!\nDO JST = 3,KNLVLS\n  ZCRITSIZE = PSNOWDZ(JST) / PDZOPT(JST)\n  IF ( JST==KNLVLS .AND. PSNOWDZ(JST)<XDZMIN_BOT ) ZCRITSIZE = 0.\n  IF ( ZCRITSIZE>ZPENALTY ) THEN\n    ZPENALTY    = ZCRITSIZE\n    JJ_A_DEDOUB = JST\n  ENDIF\nENDDO\n!\nIF ( JJ_A_DEDOUB==2 ) THEN ! case splitted layer == 2\n  PSNOWDZN(1) = 0.5 * ( PSNOWDZ(1) + PSNOWDZ(2) )\n  PSNOWDZN(2) = PSNOWDZN(1)\nELSE ! case splitted layer =/ 2\n  PSNOWDZN(1) = PSNOWDZ(1) + PSNOWDZ(2)\n  DO JST = 2,JJ_A_DEDOUB-2\n    PSNOWDZN(JST) = PSNOWDZ(JST+1)\n  ENDDO\n  PSNOWDZN(JJ_A_DEDOUB-1) = 0.5 * PSNOWDZ(JJ_A_DEDOUB)\n  PSNOWDZN(JJ_A_DEDOUB)   = PSNOWDZN(JJ_A_DEDOUB-1)\nENDIF ! end case splitted layer =/ 2\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_SNOWDZN_DEB',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_SNOWDZN_DEB\n!\n!###############################################################################\nSUBROUTINE GET_SNOWDZN_END(KNLVLS,PSNOWDZ,PDZOPT,PSNOWDZN)\n!\nUSE MODD_SNOW_PAR, ONLY : XDZMIN_TOP, XDZMIN_BOT\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\nINTEGER, INTENT(IN) :: KNLVLS\nREAL, DIMENSION(:), INTENT(IN)  :: PSNOWDZ, PDZOPT\nREAL, DIMENSION(:), INTENT(OUT) :: PSNOWDZN\n!\nREAL :: ZPENALTY, ZCRITSIZE\nINTEGER :: JJ_A_DEDOUB, JST\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_SNOWDZN_END',0,ZHOOK_HANDLE)\n!\nZPENALTY = PSNOWDZ(KNLVLS-2) / PDZOPT(KNLVLS-2)\nJJ_A_DEDOUB = KNLVLS - 2\n!\nDO JST = MAX(1,KNLVLS-3),1,-1\n  ZCRITSIZE = PSNOWDZ(JST) / PDZOPT(JST)\n  IF ( JST==1 .AND. PSNOWDZ(JST)<XDZMIN_BOT ) ZCRITSIZE = 0.\n  IF ( ZCRITSIZE>ZPENALTY ) THEN\n    ZPENALTY    = ZCRITSIZE\n    JJ_A_DEDOUB = JST\n  ENDIF\nENDDO\n!\nIF ( JJ_A_DEDOUB==KNLVLS-1 ) THEN ! case splitted layer == 2\n  PSNOWDZN(KNLVLS)   = 0.5 * (PSNOWDZ(KNLVLS-1)+PSNOWDZ(KNLVLS))\n  PSNOWDZN(KNLVLS-1) = PSNOWDZN(KNLVLS)\nELSE ! case splitted layer =/ 2\n  PSNOWDZN(KNLVLS) = PSNOWDZ(KNLVLS-1) + PSNOWDZ(KNLVLS)\n  DO JST = KNLVLS-1,JJ_A_DEDOUB+2,-1\n    PSNOWDZN(JST) = PSNOWDZ(JST-1)\n  ENDDO\n  PSNOWDZN(JJ_A_DEDOUB+1) = 0.5 * PSNOWDZ(JJ_A_DEDOUB)\n  PSNOWDZN(JJ_A_DEDOUB  ) = PSNOWDZN(JJ_A_DEDOUB+1)\nENDIF ! end case splitted layer =/ 2\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_SNOWDZN_END',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_SNOWDZN_END\n!\n!###############################################################################\n!################################################################################\n!################################################################################\n!\nSUBROUTINE SNOWNLGRIDFRESH_1D (KJ,PSNOW,PSNOWDZ,PSNOWDZN,                  &\n                               PSNOWRHO,PSNOWHEAT,PSNOWGRAN1,PSNOWGRAN2,   &\n                               PSNOWHIST,PSNOWAGE,GSNOWFALL,               &\n                               PSNOWRHOF, PSNOWDZF,PSNOWHEATF,PSNOWGRAN1F, &\n                               PSNOWGRAN2F, PSNOWHISTF,PSNOWAGEF,          &\n                               KNLVLS_USE, HSNOWMETAMO , I,J                    )\n!\n!!    PURPOSE\n!!    -------\n!     Snow mass,heat and characteristics redistibution in case of\n!     grid resizing. Total mass and heat content of the overall snowpack\n!     unchanged/conserved within this routine.\n!     Grain size and type of mixed layers is deduced from the conservation\n!     of the average optical size\n!\n!!    AUTHOR\n!!    ------\n!!      E. Brun           * Meteo-France *\n!!\n!\nUSE MODD_SNOW_PAR, ONLY : XD1,XD2,XD3,XX,XVALB5,XVALB6\nUSE MODE_SNOW3L, ONLY : GET_MASS_HEAT\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!\n!*      0.1    declarations of arguments\n!\n! ++ trude added\nINTEGER, INTENT(IN)             :: I,J\n! --trude\nINTEGER, INTENT(IN)               :: KJ\nREAL, INTENT(IN)                  :: PSNOW\n!\nREAL, DIMENSION(:), INTENT(INOUT) :: PSNOWHEAT, PSNOWRHO, PSNOWDZ,     &\n                                     PSNOWGRAN1, PSNOWGRAN2,  PSNOWDZN, &\n                                     PSNOWHIST\nREAL, DIMENSION(:), INTENT(INOUT) :: PSNOWAGE\nREAL,  INTENT(IN)                 :: PSNOWRHOF, PSNOWDZF,PSNOWHEATF,   &\n                                     PSNOWGRAN1F,PSNOWGRAN2F, PSNOWHISTF\nREAL, INTENT(IN)                  :: PSNOWAGEF\n!\nINTEGER, INTENT(IN)               :: KNLVLS_USE\n!\nLOGICAL, INTENT(IN)               :: GSNOWFALL\n!\n CHARACTER(3),INTENT(IN)           :: HSNOWMETAMO\n!\n!*      0.2    declarations of local variables\n!\nREAL*8, DIMENSION(SIZE(PSNOWRHO,1)+1) :: ZSNOWRHOO,ZSNOWGRAN1O,ZSNOWGRAN2O, &\n                                       ZSNOWHEATO,ZSNOWHISTO,ZSNOWDZO,    &\n                                       ZSNOWZTOP_OLD,ZSNOWZBOT_OLD\nREAL*8,DIMENSION(SIZE(PSNOWRHO,1)+1)  :: ZSNOWAGEO\n!\nREAL*8, DIMENSION(SIZE(PSNOWRHO,1)) :: ZSNOWRHON,ZSNOWGRAN1N,ZSNOWGRAN2N,   &\n                                     ZSNOWHEATN,ZSNOWHISTN,               &\n                                     ZSNOWZTOP_NEW,ZSNOWZBOT_NEW\nREAL*8,DIMENSION(SIZE(PSNOWRHO,1)) ::ZSNOWAGEN\n!\nREAL :: ZMASTOTN, ZMASTOTO, ZSNOWHEAN, ZSNOWHEAO\nREAL :: ZPSNOW_OLD, ZPSNOW_NEW\n!\nINTEGER :: INLVLS_OLD, INLVLS_NEW\nINTEGER :: JST\n!\nLOGICAL :: GDIAM\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWNLGRIDFRESH_1D',0,ZHOOK_HANDLE)\n!\n! 0. Initialization:\n! ------------------\n!\n! starts by checking the consistency between both vertical grid sizes\nINLVLS_NEW = KNLVLS_USE\nINLVLS_OLD = -1\n!\nZPSNOW_NEW = 0.\nZPSNOW_OLD = 0.\n!\nDO JST = 1,INLVLS_NEW\n  ZPSNOW_NEW = ZPSNOW_NEW + PSNOWDZN(JST)\nENDDO\n!\n\nIF ( ABS( ZPSNOW_NEW - PSNOWDZF )<XUEPSI ) THEN\n  INLVLS_OLD = 0\nELSE\n   DO JST = 1,SIZE(PSNOWRHO)\n      IF ( PSNOWDZ(JST)>=XUEPSI ) THEN\n         ZPSNOW_OLD = ZPSNOW_OLD + PSNOWDZ(JST)\n!      write(*,*) \"ABS( ZPSNOW_NEW - PSNOWDZF - ZPSNOW_OLD )\", ABS( ZPSNOW_NEW - PSNOWDZF - ZPSNOW_OLD ), inlvls_old\n! trude; Test fail, XUEPS seem to be too small. Increase XUEPSI slightly for test\n! XUEPSI test probably need to be less strict for very thick snow layers. Perhaps have a moving target?\n!      IF ( ABS( ZPSNOW_NEW - PSNOWDZF - ZPSNOW_OLD )<XUEPSI ) THEN\n         IF ( ABS( ZPSNOW_NEW - PSNOWDZF - ZPSNOW_OLD )<XUEPSI*100000. ) THEN\n            !      IF ( ABS( ZPSNOW_NEW - PSNOWDZF - ZPSNOW_OLD )<XUEPSI*1000. ) THEN\n            INLVLS_OLD = JST\n         ENDIF\n      ENDIF\n   ENDDO\n   IF ( INLVLS_OLD==-1 ) THEN\n      WRITE(*,*)'pb INLVLS_OLD INLVLS_NEW=',INLVLS_NEW\n      WRITE(*,*)'pb INLVLS_OLD',PSNOWDZF\n      WRITE(*,*)'pb INLVLS_OLD',PSNOWDZN\n      WRITE(*,*)'pb INLVLS_OLD',PSNOWDZ\n      !    CALL ABOR1_SFX('SNOWCRO: Error INLVLS_OLD')\n   ENDIF\nENDIF\n!\nIF ( GSNOWFALL ) INLVLS_OLD = INLVLS_OLD + 1\n!\nZPSNOW_OLD = PSNOW\nZPSNOW_NEW = ZPSNOW_OLD\n\n!\n! initialization of variables describing the initial snowpack + new snowfall\n!\nIF ( GSNOWFALL ) THEN\n  DO JST = 2,INLVLS_OLD\n    ZSNOWDZO   (JST) = PSNOWDZ   (JST-1)\n    ZSNOWRHOO  (JST) = PSNOWRHO  (JST-1)\n    ZSNOWHEATO (JST) = PSNOWHEAT (JST-1)\n    ZSNOWGRAN1O(JST) = PSNOWGRAN1(JST-1)\n    ZSNOWGRAN2O(JST) = PSNOWGRAN2(JST-1)\n    ZSNOWHISTO (JST) = PSNOWHIST (JST-1)\n    ZSNOWAGEO  (JST) = PSNOWAGE  (JST-1)\n  ENDDO\n  ZSNOWDZO   (1) = PSNOWDZF\n  ZSNOWRHOO  (1) = PSNOWRHOF\n  ZSNOWHEATO (1) = PSNOWHEATF\n  ZSNOWGRAN1O(1) = PSNOWGRAN1F\n  ZSNOWGRAN2O(1) = PSNOWGRAN2F\n  ZSNOWHISTO (1) = PSNOWHISTF\n  ZSNOWAGEO  (1) = PSNOWAGEF\nELSE\n  DO JST = 1,INLVLS_OLD\n    ZSNOWDZO   (JST) = PSNOWDZ   (JST)\n    ZSNOWRHOO  (JST) = PSNOWRHO  (JST)\n    ZSNOWHEATO (JST) = PSNOWHEAT (JST)\n    ZSNOWGRAN1O(JST) = PSNOWGRAN1(JST)\n    ZSNOWGRAN2O(JST) = PSNOWGRAN2(JST)\n    ZSNOWHISTO (JST) = PSNOWHIST (JST)\n    ZSNOWAGEO  (JST) = PSNOWAGE  (JST)\n  ENDDO\nENDIF\n\n\n!\n! 1. Calculate vertical grid limits (m):\n! --------------------------------------\n!\nZSNOWZTOP_OLD(1) = ZPSNOW_OLD\nZSNOWZTOP_NEW(1) = ZPSNOW_NEW\n\n      DO JST = 1,INLVLS_OLD\n         IF ( JST>1 ) ZSNOWZTOP_OLD(JST) = ZSNOWZBOT_OLD(JST-1)\n         ZSNOWZBOT_OLD(JST) = ZSNOWZTOP_OLD(JST) - ZSNOWDZO(JST)\n      ENDDO\n!\n      DO JST = 1,INLVLS_NEW\n         IF ( JST>1 ) ZSNOWZTOP_NEW(JST) = ZSNOWZBOT_NEW(JST-1)\n         ZSNOWZBOT_NEW(JST) = ZSNOWZTOP_NEW(JST) - PSNOWDZN(JST)\n      ENDDO\n\n! NBNBNBNB trude test. When zsnowzbot=zsnowztop_new there is a problem in get_mass_heat. The entire glacier layer for this\n! gridpoint is set to zero because snowrho does not get a value. This is a fast fix that needs to be evaluated.\n\n!\n! Check consistency\n! true if test:\n!IF ( INLVLS_OLD>0 ) THEN\n\nZSNOWZBOT_OLD(INLVLS_OLD) = 0.   ! trude comment. This line is included in original snowcro, but has been deleted in new WRF-Hydro code. Not sure why.\n                                                               ! Now testing with this included.\n!\nZSNOWZBOT_NEW(INLVLS_NEW) = 0.\n!\n! 3. Calculate mass, heat, charcateristics mixing due to vertical grid resizing:\n! --------------------------------------------------------------------\n!\n! loop over the new snow layers\n! Summ or avergage of the constituting quantities of the old snow layers\n! which are totally or partially inserted in the new snow layer\n\n\n CALL GET_MASS_HEAT(KJ,INLVLS_NEW,INLVLS_OLD,                                &\n                    ZSNOWZTOP_OLD,ZSNOWZTOP_NEW,ZSNOWZBOT_OLD,ZSNOWZBOT_NEW, &\n                    ZSNOWRHOO,ZSNOWDZO,ZSNOWGRAN1O,ZSNOWGRAN2O,ZSNOWHISTO,   &\n                    ZSNOWAGEO,ZSNOWHEATO,                                    &\n                    ZSNOWRHON,PSNOWDZN,ZSNOWGRAN1N,ZSNOWGRAN2N,ZSNOWHISTN,   &\n                    ZSNOWAGEN,ZSNOWHEATN,HSNOWMETAMO                         )\n!\n\n\n\n\n! check of consistency between new and old snowpacks\nZSNOWHEAN  = 0.\nZMASTOTN   = 0.\nZSNOWHEAO  = 0.\nZMASTOTO   = 0.\nZPSNOW_NEW = 0.\nZPSNOW_OLD = 0.\n!\n DO JST = 1,INLVLS_NEW\n  ZSNOWHEAN  = ZSNOWHEAN  + ZSNOWHEATN(JST)\n  ZMASTOTN   = ZMASTOTN   + ZSNOWRHON(JST) * PSNOWDZN(JST)\n  ZPSNOW_NEW = ZPSNOW_NEW + PSNOWDZN(JST)\n ENDDO\n!\n DO JST = 1,INLVLS_OLD\n  ZSNOWHEAO  = ZSNOWHEAO  + ZSNOWHEATO(JST)\n  ZMASTOTO   = ZMASTOTO   + ZSNOWRHOO(JST) * ZSNOWDZO(JST)\n  ZPSNOW_OLD = ZPSNOW_OLD + ZSNOWDZO(JST)\n ENDDO\n!\nIF ( ABS( ZSNOWHEAN-ZSNOWHEAO )>0.0001 .OR. ABS( ZMASTOTN-ZMASTOTO )>0.0001 .OR. &\n!     ABS( ZPSNOW_NEW-ZPSNOW_OLD )> 0.0001 ) THEN\n! trude test with higher limit\n      ABS( ZPSNOW_NEW-ZPSNOW_OLD )> 0.001 ) THEN\n!  WRITE(*,*) 'Warning diff', ZSNOWHEAN-ZSNOWHEAO,ZMASTOTN-ZMASTOTO,ZPSNOW_NEW-ZPSNOW_OLD\nENDIF\n!\n! 5. Update mass (density and thickness) and heat:\n! ------------------------------------------------\n!\nPSNOWDZ   (:) = PSNOWDZN   (:)\n!\nPSNOWRHO  (:) = ZSNOWRHON  (:)\nPSNOWHEAT (:) = ZSNOWHEATN (:)\nPSNOWGRAN1(:) = ZSNOWGRAN1N(:)\nPSNOWGRAN2(:) = ZSNOWGRAN2N(:)\nPSNOWHIST (:) =  ZSNOWHISTN(:)\n!\nPSNOWAGE  (:) =  ZSNOWAGEN (:)\n\n\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWNLGRIDFRESH_1D',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWNLGRIDFRESH_1D\n!####################################################################\n!####################################################################\n!###################################################################\nSUBROUTINE SNOWDRIFT(PTSTEP,PVMOD,PSNOWRHO,PSNOWDZ,PSNOW,        &\n                     PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,KNLVLS_USE, &\n                     PTA,PQA,PPS,PRHOA,PZ0EFF,PUREF,             &\n                     OSNOWDRIFT_SUBLIM,HSNOWMETAMO,PSNDRIFT      )\n!\n!!    PURPOSE\n!!    -------\n!     Snow compaction  and metamorphism due to drift\n!     Mass is unchanged: layer thickness is reduced\n!     in proportion to density increases. Method inspired from\n!     Brun et al. (1997) and Guyomarch\n!\n!     - computes a mobility index of each snow layer from its grains, density\n!                 and history\n!     - computes a drift index of each layer from its mobility and wind speed\n!     - computes a transport index with an exponential decay taking into\n!                 account its depth and the mobility of upper layers\n!     - increases density and changes grains in case of transport\n!\n!     HISTORY:\n!     Basic parameterization from Crocus/ARPEGE Coupling (1997)\n!     Implementation in V5\n!     Insertion in V6 of grains type evolution in case of dendritic snow (V.\n!     Vionnet)\n!     07/2012 (for V7.3): E. Brun, M. Lafaysse : optional sublimation of drifted snow\n!     2012-09-20 : bug correction : ZFF was not computed if LSNOWDRIFT_SUBLIM=FALSE.\n!\n!     2014-02-05 V. Vionnet: systematic use of 5m wind speed to compute drift index\n!     2014-06-03 M. Lafaysse: threshold on PZ0EFF\n\nUSE MODD_CSTS,ONLY : XTT\nUSE MODE_THERMOS\n\nUSE MODD_SNOW_PAR, ONLY : XVTIME, XVROMAX, XVROMIN, XVMOB1,  &\n                          XVMOB2, XVMOB3, XVMOB4, XVDRIFT1, XVDRIFT2, XVDRIFT3, &\n                          XVSIZEMIN, XCOEF_FF, XCOEF_EFFECT, XQS_REF\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                    :: PTSTEP\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PTA, PQA, PPS, PRHOA\n!\nREAL, DIMENSION(:), INTENT(IN)      :: PVMOD\n!\nINTEGER, DIMENSION(:), INTENT(IN)   :: KNLVLS_USE\n!\nREAL, DIMENSION(:),INTENT(IN)       :: PZ0EFF,PUREF\n!\nLOGICAL,INTENT(IN)                  :: OSNOWDRIFT_SUBLIM\n!\n CHARACTER(3), INTENT(IN)            :: HSNOWMETAMO ! metamorphism scheme\n!\nREAL, DIMENSION(:,:), INTENT(INOUT) :: PSNOWRHO, PSNOWDZ,PSNOWGRAN1, &\n                                       PSNOWGRAN2,PSNOWHIST\nREAL, DIMENSION(:), INTENT(OUT)     :: PSNOW\nREAL, DIMENSION(:), INTENT(OUT)     :: PSNDRIFT !blowing snow sublimation (kg/m2/s)\n!\n!*      0.2    declarations of local variables\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1),SIZE(PSNOWRHO,2)) :: ZSNOWRHO2\nREAL, DIMENSION(SIZE(PSNOWRHO,1)                 ) :: ZSNOWDZ1\n!\nREAL, DIMENSION(SIZE(PSNOWRHO,1))   :: ZQSATI, ZFF ! QS wrt ice, gust speed\n!\nREAL     :: ZZ0EFF\n!\nREAL     :: ZPROFEQU, ZRMOB, ZRDRIFT, ZRT, ZDRO, ZDGR1, ZDGR2\nREAL     :: ZVT ! 5m wind speed threshold for surface\n!transport\nREAL     :: ZQS_EFFECT ! effect of QS on snow\nREAL     :: ZWIND_EFFECT ! effect of wind on snow\nREAL     :: ZDRIFT_EFFECT ! effect of QS and wind on snow\n! transformation\nREAL     :: ZQS !Blowing snow sublimation (kg/m2/s)\nREAL     :: ZRHI, ZFACT\n!\nINTEGER  :: JJ,JST   ! looping indexes\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n! Reference height for wind speed used to dertermine the occurrence of blowing snow\nREAL, PARAMETER :: PPHREF_WIND=5.\nREAL, PARAMETER :: PPHREF_MIN=PPHREF_WIND/2.\n!\n!-------------------------------------------------------------------------------\n!IF (LHOOK) CALL DR_HOOK('SNOWDRIFT',0,ZHOOK_HANDLE)\n!\n! 0. Initialization:\n! ------------------\n!\nZSNOWDZ1(:) = PSNOWDZ(:,1)\n!\nDO JJ = 1,SIZE(PSNOW)\n  DO JST = 1,KNLVLS_USE(JJ)\n    ZSNOWRHO2(JJ,JST) = PSNOWRHO(JJ,JST)\n  ENDDO\nENDDO\n!\nIF ( OSNOWDRIFT_SUBLIM ) THEN\n  ZQSATI(:) = QSATI( PTA(:),PPS(:) )\nEND IF\n!\n! 1. Computation of drift and induced settling and metamorphism\n! ------------------\n!\nDO JJ=1, SIZE(PSNOW)\n  !\n  ! gust speed at 5m above the snowpack\n  ! Computed from PVMOD at PUREF (m) assuming a log profile in the SBL\n  ! and a roughness length equal to PZ0EFF\n  ZZ0EFF=MIN(PZ0EFF(JJ),PUREF(JJ)*0.5,PPHREF_MIN)\n  ZFF(JJ) = XCOEF_FF*PVMOD(JJ)*LOG(PPHREF_WIND/ZZ0EFF)/LOG(PUREF(JJ)/ZZ0EFF)\n  !\n  ! initialization decay coeff\n  ZPROFEQU = 0.\n  !\n  DO JST = 1,KNLVLS_USE(JJ)\n    !\n    ZFACT = 1.25 - 1.25 * ( MAX( PSNOWRHO(JJ,JST), XVROMIN ) - XVROMIN )/1000./XVMOB1\n    !\n    IF ( HSNOWMETAMO=='B92' ) THEN\n      !\n      !  mobility index computation of a layer as a function of its properties\n      IF( PSNOWGRAN1(JJ,JST)<0. ) THEN\n        ! dendritic case\n        ZRMOB = 0.34 * ( 0.5  - ( 0.75*PSNOWGRAN1(JJ,JST) + 0.5*PSNOWGRAN2(JJ,JST) )/99. ) + &\n                0.66 * ZFACT\n      ELSE\n        ! non dendritic case\n        ZRMOB = 0.34 * ( XVMOB2 - XVMOB2*PSNOWGRAN1(JJ,JST)/99. - XVMOB3*PSNOWGRAN2(JJ,JST)*1000. ) + &\n                0.66 * ZFACT\n      ENDIF\n      !\n    ELSE\n      !\n      IF ( PSNOWGRAN1(JJ,JST)<XVDIAM6*(4.-PSNOWGRAN2(JJ,JST))-XUEPSI ) THEN\n        ! dendritic case\n        ZRMOB = 0.34 * ( 0.5 + 0.75 * &\n               ( PSNOWGRAN1(JJ,JST)/XVDIAM6-4.+PSNOWGRAN2(JJ,JST) )/( PSNOWGRAN2(JJ,JST)-3. ) &\n                             - 0.5 * PSNOWGRAN2(JJ,JST) ) + &\n                0.66 * ZFACT\n      ELSE\n        ! non dendritic case\n        ZRMOB = 0.34 * ( XVMOB2 - XVMOB2 * PSNOWGRAN2(JJ,JST) &\n                                - XVMOB3 * (4.-PSNOWGRAN2(JJ,JST))*XVDIAM6*1000. ) + &\n                0.66 * ZFACT\n      ENDIF\n      !\n    ENDIF\n    !\n    ! correction in case of former wet snow\n    IF ( PSNOWHIST(JJ,JST) >= 2. ) ZRMOB = MIN(ZRMOB, XVMOB4)\n    !\n    ! computation of drift index supposing no overburden snow\n    ZRDRIFT = ZRMOB - ( XVDRIFT1 * EXP( -XVDRIFT2*ZFF(JJ) ) - 1.)\n    ! modif_EB exit loop if there is no drift\n    IF ( ZRDRIFT<=0. ) EXIT\n    !\n    ! update the decay coeff by half the current layer\n    ZPROFEQU = ZPROFEQU + 0.5 * PSNOWDZ(JJ,JST) * 0.1 * ( XVDRIFT3 - ZRDRIFT )\n    ! computation of the drift index inclunding the decay by overburden snow\n    ZRT = MAX( 0., ZRDRIFT * EXP( -ZPROFEQU*100 ) )\n    !\n    IF ( OSNOWDRIFT_SUBLIM .AND. JST==1 ) THEN\n      !Specific case for blowing snow sublimation\n      ! computation of wind speed threshold QSATI and RH withe respect to ice\n      ZVT  = -LOG( (ZRMOB+1.)/XVDRIFT1 ) / XVDRIFT2\n      ZRHI = PQA(JJ) / ZQSATI(JJ)\n      ! computation of sublimation rate according to Gordon's PhD\n!      trude test\n!      reduce constatn 0.0018 by a factor of 10\n      ZQS = 0.0018 * (XTT/PTA(JJ))**4 * ZVT * PRHOA(JJ) * ZQSATI(JJ) * &     ! orig\n            (1.-ZRHI) * (ZFF(JJ)/ZVT)**3.6\n\n!      ZQS = 0.00018 * (XTT/PTA(JJ))**4 * ZVT * PRHOA(JJ) * ZQSATI(JJ) * &   ! trude test, factor of 0.1\n !           (1.-ZRHI) * (ZFF(JJ)/ZVT)**3.6\n\n!      ZQS = 0.5* 0.0018 * (XTT/PTA(JJ))**4 * ZVT * PRHOA(JJ) * ZQSATI(JJ) * &   ! trude test, factor of 0.5\n!            (1.-ZRHI) * (ZFF(JJ)/ZVT)**3.6\n\n\n      ! trude, end test\n      ! WRITE(*,*) 'surface Vt vent*coef  ZRDRIFT ZRMOB :',ZVT,&\n      ! ZFF(JJ),ZRDRIFT,ZRMOB\n      ! WRITE(*,*) 'V>Vt ZQS   :',ZQS\n      ! surface depth decrease in case of blowing snow sublimation\n      ! WRITE(*,*) 'V>Vt DSWE DZ Z:',- MAX(0.,ZQS)*PTSTEP/COEF_FF,\n      ! - MAX(0.,ZQS)*PTSTEP/COEF_FF/PSNOWRHO(JJ,JST),PSNOWDZ(JJ,JST)\n      ! 2 lignes ci-dessous a valider pour avoir sublim drift\n      PSNOWDZ(JJ,JST) = MAX( 0.5*PSNOWDZ(JJ,JST), &\n                             PSNOWDZ(JJ,JST) - MAX(0.,ZQS) * PTSTEP/XCOEF_FF/PSNOWRHO(JJ,JST) )\n      PSNDRIFT(JJ) = (ZSNOWDZ1(JJ)-PSNOWDZ(JJ,JST))*PSNOWRHO(JJ,JST)/PTSTEP\n    ELSE\n      ZQS = 0.\n    END IF\n    !\n    ZQS_EFFECT    = MIN( 3., MAX( 0.,ZQS )/XQS_REF ) * ZRT\n    ZWIND_EFFECT  = XCOEF_EFFECT * ZRT\n    ZDRIFT_EFFECT = ( ZQS_EFFECT + ZWIND_EFFECT ) * PTSTEP / XCOEF_FF / XVTIME\n    ! WRITE(*,*) 'ZQS_EFFECT,ZWIND_EFFECT,ZDRIFT_EFFECT:',ZQS_EFFECT,ZWIND_EFFECT,ZDRIFT_EFFECT\n    !\n    ! settling by wind transport only in case of not too dense snow\n    IF( PSNOWRHO(JJ,JST) < XVROMAX ) THEN\n      ZDRO = ZDRIFT_EFFECT * ( XVROMAX - PSNOWRHO(JJ,JST) )\n      PSNOWRHO(JJ,JST) = MIN( XVROMAX , PSNOWRHO(JJ,JST) + ZDRO )\n      PSNOWDZ (JJ,JST) = PSNOWDZ(JJ,JST) * ZSNOWRHO2(JJ,JST) / PSNOWRHO(JJ,JST)\n    ENDIF\n    !\n    IF ( HSNOWMETAMO=='B92' ) THEN\n      !\n      ! metamorphism induced by snow drift\n      IF ( PSNOWGRAN1(JJ,JST)<0. ) THEN\n        ! dendritic case\n        ZDGR1 = ZDRIFT_EFFECT * ( -PSNOWGRAN1(JJ,JST) ) * 0.5\n        PSNOWGRAN1(JJ,JST) = PSNOWGRAN1(JJ,JST) + MIN( ZDGR1, -0.99 * PSNOWGRAN1(JJ,JST) )\n        ! modif_VV_140910\n        ZDGR2 = ZDRIFT_EFFECT * ( 99. - PSNOWGRAN2(JJ,JST) )\n        PSNOWGRAN2(JJ,JST) = MIN( 99., PSNOWGRAN2(JJ,JST) + ZDGR2 )\n        ! fin modif_VV_140910\n      ELSE\n        ! non dendritic case\n        ZDGR1 = ZDRIFT_EFFECT * ( 99. - PSNOWGRAN1(JJ,JST) )\n        ZDGR2 = ZDRIFT_EFFECT * 5. / 10000.\n        PSNOWGRAN1(JJ,JST) = MIN( 99., PSNOWGRAN1(JJ,JST) + ZDGR1 )\n        PSNOWGRAN2(JJ,JST) = MAX( XVSIZEMIN, PSNOWGRAN2(JJ,JST) - ZDGR2 )\n      ENDIF\n      !\n    ELSE\n      !\n      ! dendritic case\n      IF ( PSNOWGRAN1(JJ,JST)<XVDIAM6*(4.-PSNOWGRAN2(JJ,JST))-XUEPSI ) THEN\n        !\n        ZDGR1 = MIN( ZDRIFT_EFFECT * ( ( PSNOWGRAN1(JJ,JST)/XVDIAM6-4.+PSNOWGRAN2(JJ,JST) )/ &\n                                        (PSNOWGRAN2(JJ,JST)-3.) ) * 0.5, &\n                              0.99 * ( ( PSNOWGRAN1(JJ,JST)/XVDIAM6-4.+ PSNOWGRAN2(JJ,JST))/ &\n                                        (PSNOWGRAN2(JJ,JST)-3.) ) )\n        ZDGR2 = ZDRIFT_EFFECT * ( 1.-PSNOWGRAN2(JJ,JST) )\n        !\n        PSNOWGRAN1(JJ,JST) = PSNOWGRAN1(JJ,JST) + XVDIAM6 * &\n                             ( ZDGR2 * ( (PSNOWGRAN1(JJ,JST)/XVDIAM6-1.)/(PSNOWGRAN2(JJ,JST)-3.) ) - &\n                               ZDGR1 * ( PSNOWGRAN2(JJ,JST)-3. ) )\n          PSNOWGRAN2(JJ,JST) = MIN(1.,PSNOWGRAN2(JJ,JST)+ZDGR2)\n      ! non dendritic case\n      ELSE\n        !\n        ZDGR1 = ZDRIFT_EFFECT * 5./10000.\n        ZDGR2 = ZDRIFT_EFFECT * (1.-PSNOWGRAN2(JJ,JST))\n        !\n        PSNOWGRAN1(JJ,JST) = PSNOWGRAN1(JJ,JST) - 2. * XVDIAM6 * PSNOWGRAN2(JJ,JST) * ZDGR2\n        PSNOWGRAN2(JJ,JST) = MIN( 1., PSNOWGRAN2(JJ,JST)+ZDGR2 )\n        !\n      ENDIF\n      !\n    ENDIF\n    !\n    ! update the decay coeff by half the current layer\n    ZPROFEQU = ZPROFEQU + 0.5 * PSNOWDZ(JJ,JST) * 0.1 * ( XVDRIFT3 - ZRDRIFT )\n    !\n  ENDDO  ! snow layers loop\n  !\nENDDO    ! grid points loop\n!\n! 2. Update total snow depth:\n! -----------------------------------------------\n!\n! Compaction of total snowpack depth\n!\nDO JJ = 1,SIZE(PSNOWDZ,1)\n  PSNOW(JJ) = SUM( PSNOWDZ(JJ,1:KNLVLS_USE(JJ)) )\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWDRIFT',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWDRIFT\n!####################################################################\n!###################################################################\n!####################################################################\n!####################################################################\nSUBROUTINE SNOWCROLAYER_GONE(PTSTEP,PSCAP,PSNOWTEMP,PSNOWDZ,          &\n                             PSNOWRHO,PSNOWLIQ,PSNOWGRAN1,PSNOWGRAN2, &\n                             PSNOWHIST,PSNOWAGE,PLES3L,KNLVLS_USE     )\n!\n!\n!!    PURPOSE\n!     Account for the case when one or several snow layers melt\n!     during a time step:\n!     in that case, merge these layers with the underlying layer\n!     except for the bottom layer which is merged to the abovelying layer\n!     energy and mass are conserved\n!     a new merged layer keeps the grain, histo and age properties of the\n!     non-melted layer\n!\nUSE MODD_CSTS,ONLY : XTT, XLMTT, XRHOLW, XRHOLI, XLVTT, XCI\n!\nUSE MODE_SNOW3L\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!*      0.1    declarations of arguments\n!\nREAL, INTENT(IN)                     :: PTSTEP\n!\nREAL, DIMENSION(:,:), INTENT(INOUT)  :: PSCAP\n!\nREAL, DIMENSION(:,:), INTENT(INOUT)  :: PSNOWDZ, PSNOWTEMP, PSNOWRHO, PSNOWLIQ\nREAL, DIMENSION(:,:), INTENT(INOUT)  :: PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,PSNOWAGE\n!\nINTEGER, DIMENSION(:), INTENT(INOUT) :: KNLVLS_USE !\n!\nREAL, DIMENSION(:), INTENT(IN) :: PLES3L\n!\n!*      0.2    declarations of local variables\n!\nREAL :: ZHEAT, ZMASS, ZDZ, ZLIQ, ZSNOWLWE\n!\nINTEGER :: JJ,JST,JST_1, JST_2, JST_MAX, IDIFF_LAYER ! loop counter\nINTEGER :: ID_1, ID_2\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!-------------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROLAYER_GONE',0,ZHOOK_HANDLE)\n!\nDO JJ=1,SIZE(PSNOWRHO,1)  ! loop on gridpoints\n  !\n  JST_MAX = KNLVLS_USE(JJ)\n  !\n  IDIFF_LAYER = 0  ! used as shift counter of previously melted layers\n  !\n  DO JST_1 = JST_MAX,1-JST_MAX,-1 ! loop on 2 x layers in case of multi melt\n    !\n    JST = JST_1 + IDIFF_LAYER\n    !\n    ! Merge is possible only in case of 2 active layers or more\n    IF ( JST>=1 .AND. KNLVLS_USE(JJ)>1 ) THEN\n      !\n      ! Total Liquid equivalent water content of snow (m):\n      ZSNOWLWE = PSNOWRHO(JJ,JST) * PSNOWDZ(JJ,JST) / XRHOLW\n      !\n      ! Consideration of sublimation if any\n      IF ( JST==1 ) ZSNOWLWE = ZSNOWLWE - MAX( 0., PLES3L(JJ)*PTSTEP/(XLSTT*XRHOLW) )\n      !\n      ! Test if avalaible energy exceeds total latent heat\n      IF ( PSCAP(JJ,JST) * MAX( 0.0, PSNOWTEMP(JJ,JST)-XTT ) * PSNOWDZ(JJ,JST) >=  &\n           ( ( ZSNOWLWE-PSNOWLIQ(JJ,JST) ) * XLMTT * XRHOLW ) - XUEPSI ) THEN\n        !\n        IF ( JST==KNLVLS_USE(JJ) ) THEN\n          ID_1 = JST-1\n          ID_2 = JST\n        ELSE\n          ID_1 = JST\n          ID_2 = JST + 1\n        ENDIF\n        !\n        ! Case of a total melt of the bottom layer: merge with above layer\n        !        which keeps its grain, histo and age properties\n        ZHEAT = 0.\n        ZMASS = 0.\n        ZDZ   = 0.\n        ZLIQ  = 0.\n        DO JST_2 = ID_1,ID_2\n          ZHEAT = ZHEAT + &\n                  PSNOWDZ(JJ,JST_2) * &\n                  ( PSCAP(JJ,JST_2)*( PSNOWTEMP(JJ,JST_2)-XTT ) - XLMTT*PSNOWRHO(JJ,JST_2) ) + &\n                  XLMTT * XRHOLW * PSNOWLIQ(JJ,JST_2)\n          ZMASS = ZMASS + PSNOWDZ(JJ,JST_2) * PSNOWRHO(JJ,JST_2)\n          ZDZ   = ZDZ   + PSNOWDZ(JJ,JST_2)\n          ZLIQ  = ZLIQ  + PSNOWLIQ(JJ,JST_2)\n        ENDDO\n        !\n        PSNOWDZ  (JJ,ID_1) = ZDZ\n        PSNOWRHO (JJ,ID_1) = ZMASS / ZDZ\n        PSNOWLIQ (JJ,ID_1) = ZLIQ\n        !\n        ! Temperature of the merged layer is deduced from the heat content\n        PSCAP    (JJ,ID_1) = ( PSNOWRHO(JJ,ID_1) - &\n                               PSNOWLIQ(JJ,ID_1) * XRHOLW / &\n                               MAX( PSNOWDZ(JJ,ID_1),XSNOWDZMIN ) ) * XCI\n        PSNOWTEMP(JJ,ID_1) = XTT + &\n          ( ( ( ( ZHEAT - XLMTT*XRHOLW*PSNOWLIQ(JJ,ID_1) ) / PSNOWDZ(JJ,ID_1) ) + &\n              XLMTT*PSNOWRHO(JJ,ID_1) ) &\n            / PSCAP(JJ,ID_1) )\n        !\n        IF( JST/=KNLVLS_USE(JJ) ) THEN\n          !\n          PSNOWGRAN1(JJ,JST) = PSNOWGRAN1(JJ,JST+1)\n          PSNOWGRAN2(JJ,JST) = PSNOWGRAN2(JJ,JST+1)\n          PSNOWHIST (JJ,JST) = PSNOWHIST (JJ,JST+1)\n          PSNOWAGE  (JJ,JST) = PSNOWAGE  (JJ,JST+1)\n          !\n          ! Shift the above layers\n          DO JST_2 = JST+1,KNLVLS_USE(JJ)-1\n            PSNOWTEMP (JJ,JST_2) = PSNOWTEMP (JJ,JST_2+1)\n            PSCAP     (JJ,JST_2) = PSCAP     (JJ,JST_2+1)\n            PSNOWDZ   (JJ,JST_2) = PSNOWDZ   (JJ,JST_2+1)\n            PSNOWRHO  (JJ,JST_2) = PSNOWRHO  (JJ,JST_2+1)\n            PSNOWLIQ  (JJ,JST_2) = PSNOWLIQ  (JJ,JST_2+1)\n            PSNOWGRAN1(JJ,JST_2) = PSNOWGRAN1(JJ,JST_2+1)\n            PSNOWGRAN2(JJ,JST_2) = PSNOWGRAN2(JJ,JST_2+1)\n            PSNOWHIST (JJ,JST_2) = PSNOWHIST (JJ,JST_2+1)\n            PSNOWAGE  (JJ,JST_2) = PSNOWAGE  (JJ,JST_2+1)\n          ENDDO !  loop JST_2\n          !\n          ! Update the shift counter IDIFF_LAYER\n          IDIFF_LAYER = IDIFF_LAYER + 1\n          !\n        ENDIF ! end test of bottom layer\n        !\n        ! Decrease the number of active snow layers\n        KNLVLS_USE(JJ) = KNLVLS_USE(JJ) - 1\n        !\n      ENDIF ! end test on availibility of energy\n      !\n    ENDIF ! end test on the number of remaining active layers\n    !\n  ENDDO ! end loop on the snow layers\n  !\nENDDO ! end loop gridpoints\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROLAYER_GONE',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROLAYER_GONE\n!####################################################################\n!###################################################################\n!####################################################################\n!###################################################################\nSUBROUTINE SNOWCROPRINTPROFILE(HINFO,KLAYERS,OPRINTGRAN,PSNOWDZ,PSNOWRHO, &\n                               PSNOWTEMP,PSNOWLIQ,PSNOWHEAT,PSNOWGRAN1,   &\n                               PSNOWGRAN2,PSNOWHIST,PSNOWAGE,HSNOWMETAMO  )\n!\n! Matthieu Lafaysse 08/06/2012\n! This routine prints the snow profile of a given point for debugging\n!\n!to compute SSA\nUSE MODD_CSTS, ONLY : XRHOLI\nUSE MODD_SNOW_PAR, ONLY : XD1, XD2, XD3, XX\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n CHARACTER(*), INTENT(IN) :: HINFO\nLOGICAL,       INTENT(IN) :: OPRINTGRAN\nINTEGER,       INTENT(IN) :: KLAYERS\nREAL, DIMENSION(:), INTENT(IN) :: PSNOWDZ,PSNOWRHO,PSNOWTEMP,PSNOWLIQ, &\n                                  PSNOWHEAT,PSNOWGRAN1,PSNOWGRAN2,     &\n                                  PSNOWHIST,PSNOWAGE\n CHARACTER(3), INTENT(IN)       :: HSNOWMETAMO\n!\nREAL, DIMENSION(KLAYERS) :: ZSNOWSSA\nREAL :: ZDIAM\n!\nINTEGER :: JST\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROPRINTPROFILE',0,ZHOOK_HANDLE)\n!\nWRITE(*,*)\nWRITE(*,*)TRIM(HINFO)\n!\nIF (OPRINTGRAN) THEN\n  !\n  ! Compute SSA from SNOWGRAN1 and SNOWGRAN2\n  IF ( HSNOWMETAMO=='B92' ) THEN\n    !\n    DO JST = 1,KLAYERS\n      !\n      IF ( PSNOWGRAN1(JST)<0. ) THEN\n        ZDIAM =  -PSNOWGRAN1(JST)*XD1/XX + (1.+PSNOWGRAN1(JST)/XX) * &\n                ( PSNOWGRAN2(JST)*XD2/XX + (1.-PSNOWGRAN2(JST)/XX) * XD3 )\n        ZDIAM = ZDIAM/10000.\n      ELSE\n        ZDIAM = PSNOWGRAN2(JST)*PSNOWGRAN1(JST)/XX + &\n                MAX( 0.0004, 0.5*PSNOWGRAN2(JST) ) * ( 1.-PSNOWGRAN1(JST)/XX )\n      ENDIF\n      ZSNOWSSA(JST) = 6. / (XRHOLI*ZDIAM)\n      !\n    END DO\n    !\n  ELSE\n    !\n    ZSNOWSSA = 6. / (XRHOLI*PSNOWGRAN1)\n    !\n  ENDIF\n  !\n  WRITE(*,'(9(A12,\"|\"))')\"-------------\",\"-------------\",\"-------------\",&\n        \"-------------\",\"-------------\",\"-------------\",\"-------------\",&\n        \"-------------\",\"-------------\"\n  WRITE(*,'(9(A12,\"|\"))')\"PSNOWDZ\",\"PSNOWRHO\",\"PSNOWTEMP\",\"PSNOWLIQ\",\"PSNOWHEAT\",&\n        \"PSNOWGRAN1\",\"PSNOWGRAN2\",\"PSNOWHIST\",\"PSNOWAGE\"\n  WRITE(*,'(9(A12,\"|\"))')\"-------------\",\"-------------\",\"-------------\",&\n        \"-------------\",\"-------------\",\"-------------\",\"-------------\",&\n        \"-------------\",\"-------------\"\n  DO JST = 1,KLAYERS\n    WRITE(*,'(9(ES12.3,\"|\"),\" L\",I2.2)') PSNOWDZ(JST),PSNOWRHO(JST),PSNOWTEMP(JST),    &\n                                          PSNOWLIQ(JST),PSNOWHEAT(JST),PSNOWGRAN1(JST), &\n                                          PSNOWGRAN2(JST),PSNOWHIST(JST),PSNOWAGE(JST),JST\n  ENDDO\n  WRITE(*,'(9(A12,\"|\"))')\"-------------\",\"-------------\",\"-------------\",&\n        \"-------------\",\"-------------\",\"-------------\",\"-------------\",&\n        \"-------------\",\"-------------\"\n  !\nELSE\n  !\n  WRITE(*,'(5(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n        \"------------\",\"------------\"\n  WRITE(*,'(5(A12,\"|\"))')\"PSNOWDZ\",\"PSNOWRHO\",\"PSNOWTEMP\",\"PSNOWLIQ\",\"PSNOWHEAT\"\n  WRITE(*,'(5(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n        \"------------\",\"------------\"\n  DO JST = 1,KLAYERS\n    WRITE(*,'(5(ES12.3,\"|\"),\" L\",I2.2)') PSNOWDZ(JST),PSNOWRHO(JST),PSNOWTEMP(JST),&\n                                         PSNOWLIQ(JST),PSNOWHEAT(JST),JST\n  ENDDO\n  WRITE(*,'(5(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n        \"------------\",\"------------\"\n  !\nEND IF\n!\nWRITE(*,*)\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROPRINTPROFILE',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROPRINTPROFILE\n!####################################################################\n!###################################################################\nSUBROUTINE SNOWCROPRINTATM(CINFO,PTA,PQA,PVMOD,PRR,PSR,PSW_RAD,PLW_RAD, &\n                           PTG, PSOILCOND,PD_G,PPSN3L                 )\n\n! Matthieu Lafaysse 08/06/2012\n! This routine prints the atmospheric forcing of a given point for debugging\n! and ground data\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n\n CHARACTER(*), INTENT(IN) :: CINFO\nREAL,          INTENT(IN) :: PTA,PQA,PVMOD,PRR,PSR,PSW_RAD,PLW_RAD\nREAL,          INTENT(IN) :: PTG, PSOILCOND, PD_G, PPSN3L\n!\nINTEGER :: JST\n!\n!!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROPRINTATM',0,ZHOOK_HANDLE)\n!\n CALL SNOWCROPRINTDATE()\n!\nWRITE(*,*)\nWRITE(*,*)TRIM(CINFO)\nWRITE(*,'(4(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n\"------------\"\nWRITE(*,'(4(A12,\"|\"))')\"PTA\",\"PQA\",\"PRR\",\"PSR\"\nWRITE(*,'(4(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n\"------------\"\nWRITE(*,'(4(ES12.3,\"|\"),\" meteo1\")')PTA,PQA,PRR,PSR\nWRITE(*,'(4(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n\"------------\"\nWRITE(*,'(3(A12,\"|\"))')\"------------\",\"------------\",\"------------\"\nWRITE(*,'(3(A12,\"|\"))')\"PSW_RAD\",\"PLW_RAD\",\"PVMOD\"\nWRITE(*,'(3(A12,\"|\"))')\"------------\",\"------------\",\"------------\"\nWRITE(*,'(3(ES12.3,\"|\"),\" meteo2\")')PSW_RAD,PLW_RAD,PVMOD\nWRITE(*,'(3(A12,\"|\"))')\"------------\",\"------------\",\"------------\"\nWRITE(*,*)\nWRITE(*,*)\"Ground :\"\nWRITE(*,'(4(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n\"------------\"\nWRITE(*,'(4(A12,\"|\"))')\"PTG\",\"PSOILCOND\",\"PD_G\",\"PPSN3L\"\nWRITE(*,'(4(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n\"------------\"\nWRITE(*,'(4(ES12.3,\"|\"),\" soil\")')PTG,PSOILCOND,PD_G,PPSN3L\nWRITE(*,'(4(A12,\"|\"))')\"------------\",\"------------\",\"------------\",&\n\"------------\"\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROPRINTATM',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROPRINTATM\n!\n!####################################################################\n!SUBROUTINE SNOWCROSTOPBALANCE(PMASSBALANCE,PENERGYBALANCE)\n!\n!USE MODE_CRODEBUG, ONLY : XWARNING_MASSBALANCE, XWARNING_ENERGYBALANCE\n!\n!!USE MODI_ABOR1_SFX\n!\n!!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\n! stop if energy and mass balances are not closed\n!\n!IMPLICIT NONE\n!!\n!REAL , DIMENSION(:), INTENT(IN) :: PMASSBALANCE, PENERGYBALANCE\n!\n!REAL,DIMENSION(SIZE(PSR)) :: ZMASSBALANCE,ZENERGYBALANCE\n!\n!!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!!IF (LHOOK) CALL DR_HOOK('SNOWCROSTOPBALANCE',0,ZHOOK_HANDLE)\n!\n!IF ( ANY( PMASSBALANCE   > XWARNING_MASSBALANCE   ) ) &\n!        CALL ABOR1_SFX(\"SNOWCRO: WARNING MASS BALANCE !\")\n!IF ( ANY( PENERGYBALANCE > XWARNING_ENERGYBALANCE ) ) &\n!        CALL ABOR1_SFX(\"SNOWCRO: WARNING ENERGY BALANCE !\")\n!\n!!IF (LHOOK) CALL DR_HOOK('SNOWCROSTOPBALANCE',1,ZHOOK_HANDLE)\n!\n!END SUBROUTINE SNOWCROSTOPBALANCE\n!\n!###################################################################\nSUBROUTINE SNOWCROPRINTBALANCE(PSUMMASS_INI,PSUMHEAT_INI,PSUMMASS_FIN,PSUMHEAT_FIN, &\n                               PSR,PRR,PTHRUFAL,PEVAP,PEVAPCOR,PGRNDFLUX,PHSNOW,    &\n                               PRNSNOW,PLEL3L,PLES3L,PHPSNOW,PSNOWHMASS,PSNOWDZ,    &\n                               PTSTEP,PMASSBALANCE,PENERGYBALANCE,PEVAPCOR2         )\n!\n! Matthieu Lafaysse / Eric Brun 03/10/2012\n! Print energy and mass balances.\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\nREAL, INTENT(IN) :: PSUMMASS_INI,PSUMHEAT_INI,PSUMMASS_FIN,PSUMHEAT_FIN\nREAL, INTENT(IN) :: PSR,PRR,PTHRUFAL,PEVAP,PEVAPCOR\nREAL, INTENT(IN) :: PGRNDFLUX,PHSNOW,PRNSNOW,PLEL3L,PLES3L,PHPSNOW,PSNOWHMASS\nREAL, INTENT(IN) :: PSNOWDZ !first layer\nREAL, INTENT(IN) :: PTSTEP !time step\nREAL, INTENT(IN) :: PMASSBALANCE, PENERGYBALANCE, PEVAPCOR2\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROPRINTBALANCE',0,ZHOOK_HANDLE)\n!\nWRITE(*,*) ' '\nWRITE(*,FMT='(A1,67(\"+\"),A1)') \"+\",\"+\"\n!\n CALL SNOWCROPRINTDATE()\n!\nWRITE(*,*) ' '\n!\n! print des residus de bilan et des differents termes pour le point\nWRITE (*,FMT=\"(A25,1x,E17.10)\") 'final mass (kg/m2) =' , PSUMMASS_FIN\nWRITE (*,FMT=\"(A25,1x,E17.10)\") 'final energy (J/m2) =', ZSUMHEAT_FIN\nWRITE(*,*) ' '\n!\nWRITE(*,FMT=\"(A25,1x,E17.10)\") 'mass balance (kg/m2) =', PMASSBALANCE\n!\nWRITE(*,*) ' '\nWRITE(*,FMT=\"(A35)\") 'mass balance contribution (kg/m2) '\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'delta mass:', (PSUMMASS_FIN-PSUMMASS_INI)\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'hoar or condensation (>0 towards snow):', -PEVAP * PTSTEP\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'rain:',    PRR * PTSTEP\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'snow:',    PSR * PTSTEP\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'run-off:', PTHRUFAL * PTSTEP\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'evapcor:', PEVAPCOR * PTSTEP\n!\nWRITE(*,FMT='(A1,55(\"-\"),A1)')\"+\",\"+\"\nWRITE(*,*) ' '\n!\nWRITE(*,FMT=\"(A25,4(1x,E17.10))\") 'energy balance (W/m2)=',PENERGYBALANCE\n!\nWRITE(*,*) ' '\nWRITE(*,FMT=\"(A55)\") 'energy balance contribution (W/m2) >0 towards snow :'\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'delta heat:', (ZSUMHEAT_FIN-ZSUMHEAT_INI)/PTSTEP\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'radiation (LW + SW):', PRNSNOW\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'sensible flux :',      -PHSNOW\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'ground heat flux :',   -PGRNDFLUX\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'liquid latent flux:',  -PLEL3L\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'solid latent flux:',   -PLES3L\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'rain sensible heat:',  PHPSNOW\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'snowfall/hoar heat (sensible + melt heat):', PSNOWHMASS/PTSTEP\nWRITE(*,FMT=\"(A51,1x,E17.10)\") 'evapcor:', PEVAPCOR2\nWRITE(*,FMT='(A1,67(\"+\"),A1)')\"+\",\"+\"\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROPRINTBALANCE',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROPRINTBALANCE\n!\n!####################################################################\nSUBROUTINE GET_BALANCE(PSUMMASS_INI,PSUMHEAT_INI,PSUMMASS_FIN,PSUMHEAT_FIN, &\n                       PSR,PRR,PTHRUFAL,PEVAP,PEVAPCOR,PGRNDFLUX,PHSNOW,    &\n                       PRNSNOW,PLEL3L,PLES3L,PHPSNOW,PSNOWHMASS,PSNOWDZ,    &\n                       PTSTEP,PMASSBALANCE,PENERGYBALANCE,PEVAPCOR2         )\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\nREAL, INTENT(IN) :: PSUMMASS_INI,PSUMHEAT_INI,PSUMMASS_FIN,PSUMHEAT_FIN\nREAL, INTENT(IN) :: PSR,PRR,PTHRUFAL,PEVAP,PEVAPCOR\nREAL, INTENT(IN) :: PGRNDFLUX,PHSNOW,PRNSNOW,PLEL3L,PLES3L,PHPSNOW,PSNOWHMASS\nREAL, INTENT(IN) :: PSNOWDZ !first layer\nREAL, INTENT(IN) :: PTSTEP !time step\n!\nREAL, INTENT(OUT)  :: PMASSBALANCE, PENERGYBALANCE, PEVAPCOR2\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_BALANCE',0,ZHOOK_HANDLE)\n!\nPMASSBALANCE = PSUMMASS_FIN - PSUMMASS_INI - &\n               ( PSR + PRR - PTHRUFAL - PEVAP + PEVAPCOR ) * PTSTEP\n!\nPEVAPCOR2 = PEVAPCOR * PSNOWDZ / MAX( XUEPSI,PSNOWDZ ) *  &\n           ( ABS(PLEL3L) * XLVTT / MAX( XUEPSI,ABS(PLEL3L) ) + &\n             ABS(PLES3L) * XLSTT / MAX( XUEPSI,ABS(PLES3L) ) )\n!\nPENERGYBALANCE = ( PSUMHEAT_FIN-PSUMHEAT_INI ) / PTSTEP - &\n                 ( -PGRNDFLUX - PHSNOW + PRNSNOW - PLEL3L - PLES3L + PHPSNOW ) - &\n                 PSNOWHMASS / PTSTEP - PEVAPCOR2\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCRO:GET_BALANCE',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE GET_BALANCE\n!\n!###################################################################\nSUBROUTINE SNOWCROPRINTDATE()\n!\n!USE PARKIND1  ,ONLY : JPRB  ! trude added\n!\nIMPLICIT NONE\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROPRINTDATE',0,ZHOOK_HANDLE)\n!\n!WRITE(*,FMT='(I4.4,2(\"-\",I2.2),\" Hour=\",F5.2)') &\n!  TPTIME%TDATE%YEAR, TPTIME%TDATE%MONTH, TPTIME%TDATE%DAY, TPTIME%TIME/3600.\n!\n!IF (LHOOK) CALL DR_HOOK('SNOWCROPRINTDATE',1,ZHOOK_HANDLE)\n!\nEND SUBROUTINE SNOWCROPRINTDATE\n!####################################################################\n!###################################################################\n!\nEND SUBROUTINE SNOWCRO\n\n\nEND MODULE MODULE_SNOWCRO\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/module_snowcro_intercept.F",
    "content": "! The purpose of this module is to intercept the snowcro function and raise an\n! error if the BUILD_CROCUS compile option is off but the user chose the\n! namelist runtime option for Crocus\nmodule module_snowcro\n  implicit none\ncontains\n  subroutine snowcro(HSNOWRES, OGLACIER, HIMPLICIT_WIND,     &\n       PPEW_A_COEF, PPEW_B_COEF,                                 &\n       PPET_A_COEF, PPEQ_A_COEF, PPET_B_COEF, PPEQ_B_COEF,       &\n       PSNOWSWE,PSNOWRHO,PSNOWHEAT,PSNOWALB,                     &\n       PSNOWGRAN1,PSNOWGRAN2,PSNOWHIST,PSNOWAGE,                 &\n       PTSTEP,PPS,PSR,PRR,PPSN3L,                                &\n       PTA,PTG,PSW_RAD,PQA,PVMOD,PLW_RAD, PRHOA,                 &\n       PUREF,PEXNS,PEXNA,PDIRCOSZW,                              &\n       PZREF,PZ0,PZ0EFF,PZ0H,PALB,                               &\n       PSOILCOND,PD_G,                                           &\n       PSNOWLIQ,PSNOWTEMP,PSNOWDZ,                               &\n       PTHRUFAL,PGRNDFLUX,PEVAPCOR,PRNSNOW,PHSNOW,PGFLUXSNOW,    &\n       PHPSNOW,PLES3L,PLEL3L,PEVAP,PSNDRIFT,PRI,                 &\n       PEMISNOW,PCDSNOW,PUSTAR,PCHSNOW,PSNOWHMASS,PQS,           &\n       PPERMSNOWFRAC,PZENITH,                                    &\n       OSNOWDRIFT,OSNOWDRIFT_SUBLIM,OSNOW_ABS_ZENITH,            &\n       HSNOWMETAMO,HSNOWRAD,                                     &\n       act_level, VIS_ICEALB,                                    &\n       PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS,                   &\n       FLOW_ICE, FLOW_SNOW,                                      &\n       I,J)\n\n    real, intent(in)                    :: PTSTEP\n    character(len=*), intent(in)        :: HSNOWRES\n    logical, intent(in)                 :: OGLACIER\n    character(len=*), intent(in)        :: HIMPLICIT_WIND\n    integer, intent(in)                 :: act_level\n    integer, intent(in)                 :: I,J\n    real, dimension(:), intent(in), optional :: VIS_ICEALB\n    real, dimension(:), intent(in)      :: PPS, PTA, PSW_RAD, PQA, PVMOD, PLW_RAD, PSR, PRR\n    real, dimension(:), intent(in)      :: PTG, PSOILCOND, PD_G, PPSN3L\n    real, dimension(:), intent(in)      :: PZREF, PUREF, PEXNS, PEXNA, PDIRCOSZW, PRHOA, PZ0, &\n         PZ0EFF, PALB, PZ0H, PPERMSNOWFRAC\n    real, dimension(:), intent(in)      :: PPEW_A_COEF, PPEW_B_COEF, &\n         PPET_A_COEF, PPEQ_A_COEF, PPET_B_COEF,      &\n         PPEQ_B_COEF\n    real, dimension(:), intent(inout)   :: PSNOWALB\n    real, dimension(:,:), intent(inout) :: PSNOWHEAT, PSNOWRHO, PSNOWSWE\n    real, dimension(:,:), intent(inout) :: PSNOWGRAN1, PSNOWGRAN2, PSNOWHIST\n    real, dimension(:,:), intent(inout) :: PSNOWAGE\n    real, dimension(:,:), intent(out)   :: PSNOWLIQ, PSNOWTEMP, PSNOWDZ\n    real, dimension(:), intent(out)     :: PTHRUFAL, PGRNDFLUX, PEVAPCOR\n    real, dimension(:), intent(out)     :: FLOW_ICE,FLOW_SNOW\n    real, dimension(:), intent(out)     :: PRNSNOW, PHSNOW, PGFLUXSNOW, PLES3L, PLEL3L, &\n         PHPSNOW, PCDSNOW, PUSTAR, PEVAP, PSNDRIFT\n    real, dimension(:), intent(out)     :: PCHSNOW, PEMISNOW, PSNOWHMASS\n    real, dimension(:), intent(out)     :: PFSA_CROCUS, PFSR_CROCUS, PFIRA_CROCUS\n    real, dimension(:), intent(out)     :: PRI, PQS\n    real, dimension(:), intent(in)      :: PZENITH\n    logical, intent(in)                 :: OSNOWDRIFT, OSNOWDRIFT_SUBLIM\n    logical, intent(in)                 :: OSNOW_ABS_ZENITH\n    character(3), intent(in)            :: HSNOWMETAMO, HSNOWRAD\n\n\n    print *, \"ERROR: recompile with Crocus option turned on to run Crocus\"\n    stop \"ERROR: Crocus compile time option off\"\n  end subroutine snowcro\nend module module_snowcro\n"
  },
  {
    "path": "src/Land_models/NoahMP/phys/surfex/tridiag_ground_snowcro.F",
    "content": "!SFX_LIC Copyright 1994-2014 CNRS, Meteo-France and Universite Paul Sabatier\n!SFX_LIC This is part of the SURFEX software governed by the CeCILL-C licence\n!SFX_LIC version 1. See LICENSE, CeCILL-C_V1-en.txt and CeCILL-C_V1-fr.txt  \n!SFX_LIC for details. version 1.\nMODULE MODI_TRIDIAG_GROUND_SNOWCRO\n!\nINTERFACE TRIDIAG_GROUND_SNOWCRO\n!\nSUBROUTINE TRIDIAG_GROUND_SNOWCRO_1D(PA,PB,PC,PY,PX,KNLVLS_USE,KDIFLOOP)\nREAL,    DIMENSION(:,:), INTENT(IN)  :: PA  ! lower diag. elements of A matrix\nREAL,    DIMENSION(:,:), INTENT(IN)  :: PB  ! main  diag. elements of A matrix\nREAL,    DIMENSION(:,:), INTENT(IN)  :: PC  ! upper diag. elements of A matrix\nREAL,    DIMENSION(:,:), INTENT(IN)  :: PY  ! r.h.s. term\n!\nREAL,    DIMENSION(:,:), INTENT(OUT) :: PX  ! solution of A.X = Y\n!\nINTEGER,    DIMENSION(:), INTENT(IN) :: KNLVLS_USE ! number of effective layers \n!\nINTEGER, INTENT(IN) :: KDIFLOOP       ! shift in control loops: 0 or 1\nEND SUBROUTINE TRIDIAG_GROUND_SNOWCRO_1D\n!\nSUBROUTINE TRIDIAG_GROUND_SNOWCRO_2D(PA,PB,PC,PY,PX,KNLVLS_USE,KDIFLOOP)\nREAL,    DIMENSION(:,:,:), INTENT(IN)  :: PA  ! lower diag. elements of A matrix\nREAL,    DIMENSION(:,:,:), INTENT(IN)  :: PB  ! main  diag. elements of A matrix\nREAL,    DIMENSION(:,:,:), INTENT(IN)  :: PC  ! upper diag. elements of A matrix\nREAL,    DIMENSION(:,:,:), INTENT(IN)  :: PY  ! r.h.s. term\n!\nREAL,    DIMENSION(:,:,:), INTENT(OUT) :: PX  ! solution of A.X = Y\n!\nINTEGER,    DIMENSION(:,:), INTENT(IN) :: KNLVLS_USE ! number of effective layers \n!\nINTEGER, INTENT(IN) :: KDIFLOOP       ! shift in control loops: 0 or 1\nEND SUBROUTINE TRIDIAG_GROUND_SNOWCRO_2D\n!\nEND INTERFACE TRIDIAG_GROUND_SNOWCRO\n!\nEND MODULE MODI_TRIDIAG_GROUND_SNOWCRO\n!\n!###################################################################\n       SUBROUTINE TRIDIAG_GROUND_SNOWCRO_1D(PA,PB,PC,PY,PX,KNLVLS_USE,KDIFLOOP)\n!      #########################################\n!\n!\n!!****   *TRIDIAG_GROUND* - routine to solve a time implicit scheme\n!!\n!!\n!!     PURPOSE\n!!     -------\n!        The purpose of this routine is to resolve the linear system:\n!\n!       A.X = Y\n!\n!      where A is a tridiagonal matrix, and X and Y two vertical vectors.\n!     However, the computations are performed at the same time for all\n!     the verticals where an inversion of the system is necessary.\n!     This explain the dimansion of the input variables.\n!\n!!**   METHOD\n!!     ------\n!!\n!!        Then, the classical tridiagonal algorithm is used to invert the \n!!     implicit operator. Its matrix is given by:\n!!\n!!     (  b(1)      c(1)      0        0        0         0        0        0  )\n!!     (  a(2)      b(2)     c(2)      0  ...    0        0        0        0  ) \n!!     (   0        a(3)     b(3)     c(3)       0        0        0        0  ) \n!!      .......................................................................\n!!     (   0   ...   0      a(k)      b(k)     c(k)       0   ...  0        0  ) \n!!      .......................................................................\n!!     (   0         0        0        0        0 ...  a(n-1)   b(n-1)   c(n-1))\n!!     (   0         0        0        0        0 ...     0      a(n)     b(n) )\n!!\n!!\n!!       All these computations are purely vertical and vectorizations are \n!!     easely achieved by processing all the verticals in parallel.\n!!\n!!     EXTERNAL\n!!     --------\n!!\n!!       NONE\n!!\n!!     IMPLICIT ARGUMENTS\n!!     ------------------\n!!\n!!     REFERENCE\n!!     ---------\n!!\n!!     AUTHOR\n!!     ------\n!!       V. Masson\n!!\n!!     MODIFICATIONS\n!!     -------------\n!!       Original        May 13, 1998\n!!       05/2011: Brun  Special treatment to tackle the variable number\n!!                      of snow layers\n!!                      In case of second call, a shift of 1 snow layer\n!!                      is applied in the control loops.\n!! ---------------------------------------------------------------------\n!\n!*       0. DECLARATIONS\n!\n!USE YOMHOOK , ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1, ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*       0.1 declarations of arguments\n!\nREAL,    DIMENSION(:,:), INTENT(IN)  :: PA  ! lower diag. elements of A matrix\nREAL,    DIMENSION(:,:), INTENT(IN)  :: PB  ! main  diag. elements of A matrix\nREAL,    DIMENSION(:,:), INTENT(IN)  :: PC  ! upper diag. elements of A matrix\nREAL,    DIMENSION(:,:), INTENT(IN)  :: PY  ! r.h.s. term\n!\nREAL,    DIMENSION(:,:), INTENT(OUT) :: PX  ! solution of A.X = Y\n!\nINTEGER,    DIMENSION(:), INTENT(IN) :: KNLVLS_USE ! number of effective layers \n!\nINTEGER, INTENT(IN) :: KDIFLOOP       ! shift in control loops: 0 or 1\n!\n!*       0.2 declarations of local variables\n!\nREAL, DIMENSION(SIZE(PA,1),SIZE(PA,2)) :: ZW   ! work array\nREAL, DIMENSION(SIZE(PA,1)           ) :: ZDET ! work array\n!\n!\nINTEGER           :: JL, JJ            ! vertical loop control\nINTEGER           :: INL               ! number of vertical levels\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n! ---------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('TRIDIAG_GROUND_SNOWCRO_1D',0,ZHOOK_HANDLE)\n!\nINL = SIZE(PX,2)\n!\n!*       1.  levels going up\n!            ---------------\n!\n!*       1.1 first level\n!            -----------\n!\nZDET(:) = PB(:,1)\n!\nPX(:,1) = PY(:,1) / ZDET(:)\n!\n!*       1.2 other levels\n!            ------------\n!\nDO JL = 2,INL\n  !\n  DO JJ = 1,SIZE(PX,1)\n    !\n    IF ( JL<=KNLVLS_USE(JJ)-KDIFLOOP ) THEN\n      !\n      ZW(JJ,JL) = PC(JJ,JL-1)/ZDET(JJ)\n      ZDET(JJ)  = PB(JJ,JL  ) - PA(JJ,JL)*ZW(JJ,JL)\n      !\n      PX(JJ,JL) = ( PY(JJ,JL) - PA(JJ,JL)*PX(JJ,JL-1) ) / ZDET(JJ)\n      !\n    ENDIF\n    !\n  ENDDO\n  !\nEND DO\n!\n!-------------------------------------------------------------------------------\n!\n!*       2.  levels going down\n!            -----------------\n!\nDO JL = INL-1,1,-1\n  !\n  DO JJ = 1,SIZE(PX,1)\n    !\n    IF ( JL<=KNLVLS_USE(JJ)-1-KDIFLOOP ) THEN\n      !\n      PX(JJ,JL) = PX(JJ,JL) - ZW(JJ,JL+1)*PX(JJ,JL+1)\n      !\n    ENDIF\n    !\n  ENDDO\n  !\nEND DO\n!\n!IF (LHOOK) CALL DR_HOOK('TRIDIAG_GROUND_SNOWCRO_1D',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE TRIDIAG_GROUND_SNOWCRO_1D\n!\n!###################################################################\n       SUBROUTINE TRIDIAG_GROUND_SNOWCRO_2D(PA,PB,PC,PY,PX,KNLVLS_USE,KDIFLOOP)\n!      #########################################\n!\n!\n!!****   *TRIDIAG_GROUND* - routine to solve a time implicit scheme\n!!\n!!\n!!     PURPOSE\n!!     -------\n!        The purpose of this routine is to resolve the linear system:\n!\n!       A.X = Y\n!\n!      where A is a tridiagonal matrix, and X and Y two vertical vectors.\n!     However, the computations are performed at the same time for all\n!     the verticals where an inversion of the system is necessary.\n!     This explain the dimansion of the input variables.\n!\n!!**   METHOD\n!!     ------\n!!\n!!        Then, the classical tridiagonal algorithm is used to invert the \n!!     implicit operator. Its matrix is given by:\n!!\n!!     (  b(1)      c(1)      0        0        0         0        0        0  )\n!!     (  a(2)      b(2)     c(2)      0  ...    0        0        0        0  ) \n!!     (   0        a(3)     b(3)     c(3)       0        0        0        0  ) \n!!      .......................................................................\n!!     (   0   ...   0      a(k)      b(k)     c(k)       0   ...  0        0  ) \n!!      .......................................................................\n!!     (   0         0        0        0        0 ...  a(n-1)   b(n-1)   c(n-1))\n!!     (   0         0        0        0        0 ...     0      a(n)     b(n) )\n!!\n!!\n!!       All these computations are purely vertical and vectorizations are \n!!     easely achieved by processing all the verticals in parallel.\n!!\n!!     EXTERNAL\n!!     --------\n!!\n!!       NONE\n!!\n!!     IMPLICIT ARGUMENTS\n!!     ------------------\n!!\n!!     REFERENCE\n!!     ---------\n!!\n!!     AUTHOR\n!!     ------\n!!       V. Masson\n!!\n!!     MODIFICATIONS\n!!     -------------\n!!       Original        May 13, 1998\n!!       05/2011: Brun  Special treatment to tackle the variable number\n!!                      of snow layers\n!!                      In case of second call, a shift of 1 snow layer\n!!                      is applied in the control loops.\n!! ---------------------------------------------------------------------\n!\n!*       0. DECLARATIONS\n!\n!USE YOMHOOK , ONLY : LHOOK,   DR_HOOK\n!USE PARKIND1, ONLY : JPRB\n!\nIMPLICIT NONE\n!\n!*       0.1 declarations of arguments\n!\nREAL,    DIMENSION(:,:,:), INTENT(IN)  :: PA  ! lower diag. elements of A matrix\nREAL,    DIMENSION(:,:,:), INTENT(IN)  :: PB  ! main  diag. elements of A matrix\nREAL,    DIMENSION(:,:,:), INTENT(IN)  :: PC  ! upper diag. elements of A matrix\nREAL,    DIMENSION(:,:,:), INTENT(IN)  :: PY  ! r.h.s. term\n!\nREAL,    DIMENSION(:,:,:), INTENT(OUT) :: PX  ! solution of A.X = Y\n!\nINTEGER,    DIMENSION(:,:), INTENT(IN) :: KNLVLS_USE ! number of effective layers \n!\nINTEGER, INTENT(IN) :: KDIFLOOP       ! shift in control loops: 0 or 1\n!\n!*       0.2 declarations of local variables\n!\nREAL, DIMENSION(SIZE(PA,2)) :: ZW   ! work array\nREAL :: ZDET ! work array\n!\n!\nINTEGER           :: JL, JJ, JB     ! vertical loop control\nINTEGER           :: INL, INB            ! number of vertical levels\n!\n!REAL(KIND=JPRB) :: ZHOOK_HANDLE\n! ---------------------------------------------------------------------------\n!\n!IF (LHOOK) CALL DR_HOOK('TRIDIAG_GROUND_SNOWCRO_2D',0,ZHOOK_HANDLE)\n!\nINL = SIZE(PX,2)\nINB = SIZE(PX,3)\n!\n!*       1.  levels going up\n!            ---------------\n!\n!*       1.1 first level\n!            -----------\n!\nDO JB = 1,INB\n  !\n  DO JJ = 1,SIZE(PX,1)\n    !\n    ZDET = PB(JJ,1,JB)\n    !\n    PX(JJ,1,JB) = PY(JJ,1,JB) / ZDET\n    !\n    !*       1.2 other levels\n    !            ------------\n    !\n    DO JL = 2,INL\n      !\n      IF ( JL<=KNLVLS_USE(JJ,JB)-KDIFLOOP ) THEN\n        !\n        ZW(JL) = PC(JJ,JL-1,JB)  /ZDET\n        ZDET   = PB(JJ,JL  ,JB) - PA(JJ,JL,JB) * ZW(JL)\n        !\n        PX(JJ,JL,JB) = ( PY(JJ,JL,JB) - PA(JJ,JL,JB) * PX(JJ,JL-1,JB) ) / ZDET\n        !\n      ENDIF\n      !\n    ENDDO\n    !\n    !-------------------------------------------------------------------------------\n    !\n    !*       2.  levels going down\n    !            -----------------\n    !\n    DO JL = INL-1,1,-1\n      !\n      IF ( JL<=KNLVLS_USE(JJ,JB)-1-KDIFLOOP ) THEN\n        !\n        PX(JJ,JL,JB) = PX(JJ,JL,JB) - ZW(JL+1) * PX(JJ,JL+1,JB)\n        !\n      ENDIF\n      !\n    ENDDO\n    !\n  END DO\n  !\nENDDO\n!\n!IF (LHOOK) CALL DR_HOOK('TRIDIAG_GROUND_SNOWCRO_2D',1,ZHOOK_HANDLE)\n!\n!-------------------------------------------------------------------------------\n!\nEND SUBROUTINE TRIDIAG_GROUND_SNOWCRO_2D\n"
  },
  {
    "path": "src/Land_models/NoahMP/run/GENPARM.TBL",
    "content": "General Parameters\nSLOPE_DATA\n9\n0.1 \n0.6\n1.0\n0.35\n0.55\n0.8\n0.63\n0.0\n0.0\nSBETA_DATA\n-2.0\nFXEXP_DATA\n2.0\nCSOIL_DATA\n2.00E+6\nSALP_DATA\n2.6\nREFDK_DATA\n2.0E-6\nREFKDT_DATA\n3.0\nFRZK_DATA\n0.15\nZBOT_DATA\n-8.0\nCZIL_DATA\n0.1\nSMLOW_DATA\n0.5\nSMHIGH_DATA\n3.0\nLVCOEF_DATA\n0.5\n"
  },
  {
    "path": "src/Land_models/NoahMP/run/MPTABLE.TBL",
    "content": "&noahmp_usgs_veg_categories\n VEG_DATASET_DESCRIPTION = \"USGS\"\n NVEG = 27\n/\n&noahmp_usgs_parameters\n ! NVEG = 27\n !  1: Urban and Built-Up Land\n !  2: Dryland Cropland and Pasture\n !  3: Irrigated Cropland and Pasture\n !  4: Mixed Dryland/Irrigated Cropland and Pasture\n !  5: Cropland/Grassland Mosaic\n !  6: Cropland/Woodland Mosaic\n !  7: Grassland\n !  8: Shrubland\n !  9: Mixed Shrubland/Grassland\n ! 10: Savanna\n ! 11: Deciduous Broadleaf Forest\n ! 12: Deciduous Needleleaf Forest\n ! 13: Evergreen Broadleaf Forest\n ! 14: Evergreen Needleleaf Forest\n ! 15: Mixed Forest\n ! 16: Water Bodies\n ! 17: Herbaceous Wetland\n ! 18: Wooded Wetland\n ! 19: Barren or Sparsely Vegetated\n ! 20: Herbaceous Tundra\n ! 21: Wooded Tundra\n ! 22: Mixed Tundra\n ! 23: Bare Ground Tundra\n ! 24: Snow or Ice\n ! 25: Playa\n ! 26: Lava\n ! 27: White Sand\n\n ISURBAN                   =  1\n ISWATER                   = 16\n ISBARREN                  = 19\n ISICE                     = 24\n ISCROP                    =  2\n EBLFOREST                 = 13\n NATURAL                   =  5\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1      2      3      4      5      6      7      8      9      10     11     12     13     14     15     16     17     18     19     20     21     22     23     24     25     26    27\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,\n DLEAF =  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,\n Z0MVT =  1.00,  0.15,  0.15,  0.15,  0.14,  0.50,  0.12,  0.06,  0.09,  0.50,  0.80,  0.85,  1.10,  1.09,  0.80,  0.00,  0.12,  0.50,  0.00,  0.10,  0.30,  0.20,  0.03,  0.00,  0.01,  0.00,  0.00,\n HVT   =  15.0,  2.00,  2.00,  2.00,  1.50,  8.00,  1.00,  1.10,  1.10,  10.0,  16.0,  18.0,  20.0,  20.0,  16.0,  0.00,  0.50,  10.0,  0.00,  0.50,  4.00,  2.00,  0.50,  0.00,  0.10,  0.00,  0.00,\n HVB   =  1.00,  0.10,  0.10,  0.10,  0.10,  0.15,  0.05,  0.10,  0.10,  0.10,  11.5,  7.00,  8.00,  8.50,  10.0,  0.00,  0.05,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n DEN   =  0.01,  25.0,  25.0,  25.0,  25.0,  25.0,  100.,  10.0,  10.0,  0.02,  0.10,  0.28,  0.02,  0.28,  0.10,  0.01,  10.0,  0.10,  0.01,  1.00,  1.00,  1.00,  1.00,  0.00,  0.01,  0.01,  0.01,\n RC    =  1.00,  0.08,  0.08,  0.08,  0.08,  0.08,  0.03,  0.12,  0.12,  3.00,  1.40,  1.20,  3.60,  1.20,  1.40,  0.01,  0.10,  1.40,  0.01,  0.30,  0.30,  0.30,  0.30,  0.00,  0.01,  0.01,  0.01,\n MFSNO =  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.00,  0.11,  0.11,  0.11,  0.11,  0.11,  0.11,  0.07,  0.10,  0.10,  0.10,  0.07,  0.10,  0.07,  0.10,  0.00,  0.11,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n RHOL_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.35,  0.45,  0.45,  0.45,  0.35,  0.45,  0.35,  0.45,  0.00,  0.58,  0.45,  0.00,  0.45,  0.45,  0.45,  0.45,  0.00,  0.45,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.00,  0.36,  0.36,  0.36,  0.36,  0.36,  0.36,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.00,  0.36,  0.16,  0.00,  0.16,  0.16,  0.16,  0.16,  0.00,  0.16,  0.00,  0.00,\n RHOS_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.00,  0.58,  0.39,  0.00,  0.39,  0.39,  0.39,  0.39,  0.00,  0.39,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.00,  0.07,  0.07,  0.07,  0.07,  0.07,  0.07,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.00,  0.07,  0.05,  0.00,  0.05,  0.05,  0.05,  0.05,  0.00,  0.05,  0.00,  0.00,\n TAUL_NIR=0.00,  0.25,  0.25,  0.25,  0.25,  0.25,  0.25,  0.10,  0.10,  0.25,  0.25,  0.10,  0.25,  0.10,  0.25,  0.00,  0.25,  0.25,  0.00,  0.25,  0.25,  0.25,  0.25,  0.00,  0.25,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.00, 0.220, 0.220, 0.220, 0.220, 0.220, 0.220, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.220, 0.001, 0.000, 0.220, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n TAUS_NIR=0.00, 0.380, 0.380, 0.380, 0.380, 0.380, 0.380, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.380, 0.001, 0.000, 0.380, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n\n XL    = 0.000, -0.30, -0.30, -0.30, -0.30, -0.30, -0.30, 0.010, 0.250, 0.010, 0.250, 0.010, 0.010, 0.010, 0.250, 0.000, -0.30, 0.250, 0.000, -0.30, 0.250, 0.250, 0.250, 0.000, 0.250, 0.000, 0.000,\n CWPVT =  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,\n C3PSN =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n KC25  =  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,\n AKC   =   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,\n KO25  =  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,\n AKO   =   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,\n AVCMX =   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,\n AQE   =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n\n LTOVRC=   0.0,   1.2,   1.2,   1.2,   1.2,  1.30,  0.50,  0.65,  0.70,  0.65,  0.55,   0.2,  0.55,   0.5,   0.5,   0.0,   1.4,   1.4,   0.0,   1.2,   1.3,   1.4,   1.0,   0.0,   1.0,   0.0,   0.0,\n DILEFC=  0.00,  0.50,  0.50,  0.50,  0.35,  0.20,  0.20,  0.20,  0.50,  0.50,  0.60,  1.80,  0.50,  1.20,  0.80,  0.00,  0.40,  0.40,  0.00,  0.40,  0.30,  0.40,  0.30,  0.00,  0.30,  0.00,  0.00,\n DILEFW=  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.20,  0.50,  0.20,  0.20,  4.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.20,  0.20,  0.00,  0.20,  0.00,  0.00,\n RMF25 =  0.00,  1.00,  1.40,  1.45,  1.45,  1.45,  1.80,  0.26,  0.26,  0.80,  3.00,  4.00,  0.65,  3.00,  3.00,  0.00,  3.20,  3.20,  0.00,  3.20,  3.00,  3.00,  3.00,  0.00,  3.00,  0.00,  0.00,\n SLA   =    60,    80,    80,    80,    80,    80,    60,    60,    60,    50,    80,    80,    80,    80,    80,     0,    80,    80,     0,    80,    80,    80,    80,     0,    80,     0,     0,\n FRAGR =  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n TMIN  =     0,   273,   273,   273,   273,   273,   273,   273,   273,   273,   273,   268,   273,   265,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n VCMX25=  0.00,  80.0,  80.0,  80.0,  60.0,  70.0,  40.0,  40.0,  40.0,  40.0,  60.0,  60.0,  60.0,  50.0,  55.0,  0.00,  50.0,  50.0,  0.00,  50.0,  50.0,  50.0,  50.0,  0.00,  50.0,  0.00,  0.00,\n TDLEF =   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   268,   278,   278,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n BP    = 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3, 1.E15, 1.E15,\n MP    =    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    6.,    9.,    6.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,\n QE25  =    0.,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.00,  0.00,\n RMS25 =  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.32,  0.10,  0.64,  0.30,  0.90,  0.80,  0.00,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.00,  0.00,  0.00,  0.00,  0.00,\n RMR25 =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.20,  0.00,  0.00,  0.01,  0.01,  0.05,  0.05,  0.36,  0.03,  0.00,  0.00,  0.00,  0.00,  2.11,  2.11,  2.11,  0.00,  0.00,  0.00,  0.00,  0.00,\n ARM   =   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,\n FOLNMX=  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,  0.00,  0.00,\n WDPOOL=  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  0.00,  0.00,  1.00,  0.00,  0.00,  1.00,  1.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n WRRAT =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  3.00,  3.00,  3.00,  30.0,  30.0,  30.0,  30.0,  30.0,  0.00,  0.00,  30.0,  0.00,  0.00,  3.00,  3.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n MRP   =  0.00,  0.23,  0.23,  0.23,  0.23,  0.23,  0.17,  0.19,  0.19,  0.40,  0.40,  0.37,  0.23,  0.37,  0.30,  0.00,  0.17,  0.40,  0.00,  0.17,  0.23,  0.20,  0.00,  0.00,  0.20,  0.00,  0.00,\n NROOT =     1,     3,     3,     3,     3,     3,     3,     3,     3,     3,     4,     4,     4,     4,     4,     0,     2,     2,     1,     3,     3,     3,     2,     1,     1,     0,     0,\n RGL   = 999.0, 100.0, 100.0, 100.0, 100.0,  65.0, 100.0, 100.0, 100.0,  65.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0, 100.0,  30.0, 999.0, 100.0, 100.0, 100.0, 100.0, 999.0, 100.0, 999.0, 999.0,\n RS    = 200.0,  40.0,  40.0,  40.0,  40.0,  70.0,  40.0, 300.0, 170.0,  70.0, 100.0, 150.0, 150.0, 125.0, 125.0, 100.0,  40.0, 100.0, 999.0, 150.0, 150.0, 150.0, 200.0, 999.0,  40.0, 999.0, 999.0,\n HS    = 999.0, 36.25, 36.25, 36.25, 36.25, 44.14, 36.35, 42.00, 39.18, 54.53, 54.53, 47.35, 41.69, 47.35, 51.93, 51.75, 60.00, 51.93, 999.0, 42.00, 42.00, 42.00, 42.00, 999.0, 36.25, 999.0, 999.0,\n TOPT  = 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0,\n RSMAX = 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_FEB = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_APR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.3,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAY = 0.0,   0.2,   0.2,   0.2,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.4,   0.4,   0.0,   0.3,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUN = 0.0,   0.3,   0.3,   0.3,   0.4,   0.4,   0.4,   0.2,   0.3,   0.4,   0.4,   0.7,   0.5,   0.5,   0.4,   0.0,   0.4,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUL = 0.0,   0.4,   0.4,   0.4,   0.6,   0.6,   0.8,   0.4,   0.6,   0.8,   0.9,   1.3,   0.5,   0.5,   0.7,   0.0,   0.6,   0.6,   0.0,   0.4,   0.4,   0.4,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_AUG = 0.0,   0.5,   0.5,   0.5,   0.9,   0.9,   1.3,   0.6,   0.9,   1.2,   1.2,   1.2,   0.5,   0.6,   0.8,   0.0,   0.9,   0.9,   0.0,   0.6,   0.6,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_SEP = 0.0,   0.4,   0.4,   0.4,   0.7,   1.0,   1.1,   0.8,   1.0,   1.3,   1.6,   1.0,   0.5,   0.6,   1.0,   0.0,   0.7,   1.0,   0.0,   0.7,   0.8,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_OCT = 0.0,   0.3,   0.3,   0.3,   0.3,   0.8,   0.4,   0.7,   0.6,   0.7,   1.4,   0.8,   0.5,   0.7,   1.0,   0.0,   0.3,   0.8,   0.0,   0.5,   0.7,   0.5,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_NOV = 0.0,   0.3,   0.3,   0.3,   0.3,   0.4,   0.4,   0.3,   0.3,   0.4,   0.6,   0.6,   0.5,   0.6,   0.5,   0.0,   0.3,   0.4,   0.0,   0.3,   0.3,   0.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_DEC = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.4,   0.2,   0.3,   0.4,   0.4,   0.5,   0.5,   0.5,   0.4,   0.0,   0.3,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n LAI_JAN = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_FEB = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.3,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAR = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.0,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_APR = 0.0,   0.0,   0.0,   0.0,   0.4,   0.6,   0.7,   0.6,   0.7,   0.8,   1.2,   0.6,   4.5,   4.0,   2.6,   0.0,   0.4,   0.6,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAY = 0.0,   1.0,   1.0,   1.0,   1.1,   2.0,   1.2,   1.5,   1.4,   1.8,   3.0,   1.2,   4.5,   4.0,   3.5,   0.0,   1.1,   2.0,   0.0,   0.6,   1.7,   1.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUN = 0.0,   2.0,   2.0,   2.0,   2.5,   3.3,   3.0,   2.3,   2.6,   3.6,   4.7,   2.0,   4.5,   4.0,   4.3,   0.0,   2.5,   3.3,   0.0,   1.5,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUL = 0.0,   3.0,   3.0,   3.0,   3.2,   3.7,   3.5,   2.3,   2.9,   3.8,   4.5,   2.6,   4.5,   4.0,   4.3,   0.0,   3.2,   3.7,   0.0,   1.7,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_AUG = 0.0,   3.0,   3.0,   3.0,   2.2,   3.2,   1.5,   1.7,   1.6,   2.1,   3.4,   1.7,   4.5,   4.0,   3.7,   0.0,   2.2,   3.2,   0.0,   0.8,   1.8,   1.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_SEP = 0.0,   1.5,   1.5,   1.5,   1.1,   1.3,   0.7,   0.6,   0.7,   0.9,   1.2,   1.0,   4.5,   4.0,   2.6,   0.0,   1.1,   1.3,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_OCT = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.5,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_NOV = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.2,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_DEC = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n SLAREA=0.0228,0.0200,0.0200,0.0295,0.0223,0.0277,0.0060,0.0227,0.0188,0.0236,0.0258,0.0200,0.0200,0.0090,0.0223,0.0422,0.0390,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1   = 41.87,  0.00,  0.00,  2.52,  0.04, 17.11,  0.02, 21.62,  0.11, 22.80, 46.86,  0.00,  0.00,  0.46, 30.98,  2.31,  1.63,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS2   =  0.98,  0.00,  0.00,  0.16,  0.09,  0.28,  0.05,  0.92,  0.22,  0.59,  0.38,  0.00,  0.00,  3.34,  0.96,  1.47,  1.07,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS3   =  1.82,  0.00,  0.00,  0.23,  0.05,  0.81,  0.03,  1.73,  1.26,  1.37,  1.84,  0.00,  0.00,  1.85,  1.84,  1.70,  1.21,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS4   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS5   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n/\n\n&noahmp_modis_veg_categories\n VEG_DATASET_DESCRIPTION = \"modified igbp modis noah\"\n NVEG = 20\n/\n\n&noahmp_modis_parameters\n! 1          'Evergreen Needleleaf Forest'                       -> USGS 14\n! 2,         'Evergreen Broadleaf Forest'                        -> USGS 13\n! 3,         'Deciduous Needleleaf Forest'                       -> USGS 12\n! 4,         'Deciduous Broadleaf Forest'                        -> USGS 11\n! 5,         'Mixed Forests'                                     -> USGS 15\n! 6,         'Closed Shrublands'                                 -> USGS  8 \"shrubland\"\n! 7,         'Open Shrublands'                                   -> USGS  9 \"shrubland/grassland\"\n! 8,         'Woody Savannas'                                    -> USGS  8 \"shrubland\"\n! 9,         'Savannas'                                          -> USGS 10\n! 10,        'Grasslands'                                        -> USGS  7\n! 11         'Permanent wetlands'                                -> avg of USGS 17 and 18 (herb. wooded wetland)\n! 12,        'Croplands'                                         -> USGS  2 \"dryland cropland\"\n! 13,        'Urban and Built-Up'                                -> USGS  1\n! 14         'cropland/natural vegetation mosaic'                -> USGS  5 \"cropland/grassland\"\n! 15,        'Snow and Ice'                                      -> USGS 24\n! 16,        'Barren or Sparsely Vegetated'                      -> USGS 19\n! 17,        'Water'                                             -> USGS 16\n! 18,        'Wooded Tundra'                                     -> USGS 21\n! 19,        'Mixed Tundra'                                      -> USGS 22\n! 20,        'Barren Tundra'                                     -> USGS 23\n\n ISURBAN                   = 13\n ISWATER                   = 17\n ISBARREN                  = 16\n ISICE                     = 15\n ISCROP                    = 12\n EBLFOREST                 =  2\n NATURAL                   = 14\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1       2       3       4       5       6       7       8       9      10      11      12      13      14      15      16      17      18      19      20\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,\n DLEAF =  0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,\n Z0MVT =  1.09,   1.10,   0.85,   0.80,   0.80,   0.20,   0.06,   0.60,   0.50,   0.12,   0.30,   0.15,   1.00,   0.14,   0.00,   0.00,   0.00,   0.30,   0.20,   0.03,\n HVT   =  20.0,   20.0,   18.0,   16.0,   16.0,   1.10,   1.10,   13.0,   10.0,   1.00,   5.00,   2.00,   15.0,   1.50,   0.00,   0.00,   0.00,   4.00,   2.00,   0.50,\n HVB   =  8.50,   8.00,   7.00,   11.5,   10.0,   0.10,   0.10,   0.10,   0.10,   0.05,   0.10,   0.10,   1.00,   0.10,   0.00,   0.00,   0.00,   0.30,   0.20,   0.10,\n DEN   =  0.28,   0.02,   0.28,   0.10,   0.10,   10.0,   10.0,   10.0,   0.02,   100.,   5.05,   25.0,   0.01,   25.0,   0.00,   0.01,   0.01,   1.00,   1.00,   1.00,\n RC    =  1.20,   3.60,   1.20,   1.40,   1.40,   0.12,   0.12,   0.12,   3.00,   0.03,   0.75,   0.08,   1.00,   0.08,   0.00,   0.01,   0.01,   0.30,   0.30,   0.30,\n MFSNO =  2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.07,   0.10,   0.07,   0.10,   0.10,   0.07,   0.07,   0.07,   0.10,   0.11,  0.105,   0.11,   0.00,   0.11,   0.00,   0.00,   0.00,   0.10,   0.10,   0.10,\n RHOL_NIR=0.35,   0.45,   0.35,   0.45,   0.45,   0.35,   0.35,   0.35,   0.45,   0.58,  0.515,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.45,   0.45,   0.45,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.36,   0.26,   0.36,   0.00,   0.36,   0.00,   0.00,   0.00,   0.16,   0.16,   0.16,\n RHOS_NIR=0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.58,  0.485,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.39,   0.39,   0.39,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.07,   0.06,   0.07,   0.00,   0.07,   0.00,   0.00,   0.00,   0.05,   0.05,   0.05,\n TAUL_NIR=0.10,   0.25,   0.10,   0.25,   0.25,   0.10,   0.10,   0.10,   0.25,   0.25,   0.25,   0.25,   0.00,   0.25,   0.00,   0.00,   0.00,   0.25,   0.25,   0.25,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.220, 0.1105,  0.220,  0.000,  0.220,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n TAUS_NIR=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.380, 0.1905,  0.380,  0.000,  0.380,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n\n XL    = 0.010,  0.010,  0.010,  0.250,  0.250,  0.010,  0.010,  0.010,  0.010,  -0.30, -0.025,  -0.30,  0.000,  -0.30,  0.000,  0.000,  0.000,  0.250,  0.250,  0.250,\n! CWPVT =   3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,\n CWPVT =  0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,\n C3PSN =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n KC25  =  30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,\n AKC   =   2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,\n KO25  =  3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,\n AKO   =   1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,\n AVCMX =   2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,\n AQE   =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n\n LTOVRC=   0.5,   0.55,    0.2,   0.55,    0.5,   0.65,   0.65,   0.65,   0.65,   0.50,    1.4,    1.6,    0.0,    1.2,    0.0,    0.0,    0.0,    1.3,    1.4,    1.0,\n DILEFC=  1.20,   0.50,   1.80,   0.60,   0.80,   0.20,   0.20,   0.20,   0.50,   0.20,    0.4,   0.50,   0.00,   0.35,   0.00,   0.00,   0.00,   0.30,   0.40,   0.30,\n DILEFW=  0.20,   4.00,   0.20,   0.20,   0.20,   0.20,   0.20,   0.20,   0.50,   0.10,    0.2,   0.20,   0.00,   0.20,   0.00,   0.00,   0.00,   0.20,   0.20,   0.20,\n RMF25 =  3.00,   0.65,   4.00,   3.00,   3.00,   0.26,   0.26,   0.26,   0.80,   1.80,    3.2,   1.00,   0.00,   1.45,   0.00,   0.00,   0.00,   3.00,   3.00,   3.00,\n SLA   =    80,     80,     80,     80,     80,     60,     60,     60,     50,     60,     80,     80,     60,     80,      0,      0,      0,     80,     80,     80,\n FRAGR =  0.10,   0.20,   0.10,   0.20,   0.10,   0.20,   0.20,   0.20,   0.20,   0.20,    0.1,   0.20,   0.00,   0.20,   0.00,   0.10,   0.00,   0.10,   0.10,   0.10,\n TMIN  =   265,    273,    268,    273,    268,    273,    273,    273,    273,    273,    268,    273,      0,    273,      0,      0,      0,    268,    268,    268,\n VCMX25=  50.0,   60.0,   60.0,   60.0,   55.0,   40.0,   40.0,   40.0,   40.0,   40.0,   50.0,   80.0,   0.00,   60.0,   0.00,   0.00,   0.00,   50.0,   50.0,   50.0,\n TDLEF =   278,    278,    268,    278,    268,    278,    278,    278,    278,    278,    268,    278,    278,    278,      0,      0,      0,    268,    268,    268,\n BP    =  2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,   2.E3,   2.E3,\n MP    =    6.,     9.,     6.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,\n QE25  =  0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.00,   0.06,   0.00,   0.06,   0.00,   0.06,   0.06,   0.06,\n RMS25 =  0.90,   0.30,   0.64,   0.10,   0.80,   0.10,   0.10,   0.10,   0.32,   0.10,   0.10,   0.10,   0.00,   0.10,   0.00,   0.00,   0.00,   0.10,   0.10,   0.00,\n RMR25 =  0.36,   0.05,   0.05,   0.01,   0.03,   0.00,   0.00,   0.00,   0.01,   1.20,    0.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   2.11,   2.11,   0.00,\n ARM   =   2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,\n FOLNMX=   1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,   0.00,    1.5,   0.00,    1.5,   0.00,    1.5,    1.5,    1.5,\n WDPOOL=  1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   0.00,    0.5,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   1.00,   1.00,   0.00,\n WRRAT =  30.0,   30.0,   30.0,   30.0,   30.0,   3.00,   3.00,   3.00,   3.00,   0.00,   15.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   3.00,   3.00,   0.00,\n MRP   =  0.37,   0.23,   0.37,   0.40,   0.30,   0.19,   0.19,   0.19,   0.40,   0.17,  0.285,   0.23,   0.00,   0.23,   0.00,   0.00,   0.00,   0.23,   0.20,   0.00,\n NROOT =     4,      4,      4,      4,      4,      3,      3,      3,      3,      3,      2,      3,      1,      3,      1,      1,      0,      3,      3,      2,     \n RGL   =  30.0,   30.0,   30.0,   30.0,   30.0,  100.0,  100.0,  100.0,   65.0,  100.0,   65.0,  100.0,  999.0,  100.0,  999.0,  999.0,   30.0,  100.0,  100.0,  100.0,\n RS    = 125.0,  150.0,  150.0,  100.0,  125.0,  300.0,  170.0,  300.0,   70.0,   40.0,   70.0,   40.0,  200.0,   40.0,  999.0,  999.0,  100.0,  150.0,  150.0,  200.0,\n HS    = 47.35,  41.69,  47.35,  54.53,  51.93,  42.00,  39.18,  42.00,  54.53,  36.35,  55.97,  36.25,  999.0,  36.25,  999.0,  999.0,  51.75,  42.00,  42.00,  42.00,\n TOPT  = 298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,\n RSMAX = 5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_FEB = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAR = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_APR = 0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAY = 0.4,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_JUN = 0.5,    0.5,    0.7,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.4,    0.3,    0.0,    0.4,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n SAI_JUL = 0.5,    0.5,    1.3,    0.9,    0.7,    0.6,    0.4,    0.7,    0.8,    0.8,    0.6,    0.4,    0.0,    0.6,    0.0,    0.0,    0.0,    0.4,    0.4,    0.0,\n SAI_AUG = 0.6,    0.5,    1.2,    1.2,    0.8,    0.9,    0.6,    1.2,    1.2,    1.3,    0.9,    0.5,    0.0,    0.9,    0.0,    0.0,    0.0,    0.6,    0.6,    0.0,\n SAI_SEP = 0.6,    0.5,    1.0,    1.6,    1.0,    1.2,    0.8,    1.4,    1.3,    1.1,    0.9,    0.4,    0.0,    0.7,    0.0,    0.0,    0.0,    0.8,    0.7,    0.0,\n SAI_OCT = 0.7,    0.5,    0.8,    1.4,    1.0,    0.9,    0.7,    1.1,    0.7,    0.4,    0.6,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.7,    0.5,    0.0,\n SAI_NOV = 0.6,    0.5,    0.6,    0.6,    0.5,    0.4,    0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.3,    0.3,    0.0,\n SAI_DEC = 0.5,    0.5,    0.5,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n\n LAI_JAN = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_FEB = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_MAR = 4.0,    4.5,    0.0,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_APR = 4.0,    4.5,    0.6,    1.2,    2.6,    0.9,    0.6,    1.0,    0.8,    0.7,    0.5,    0.0,    0.0,    0.4,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_MAY = 4.0,    4.5,    1.2,    3.0,    3.5,    2.2,    1.5,    2.4,    1.8,    1.2,    1.5,    1.0,    0.0,    1.1,    0.0,    0.0,    0.0,    1.7,    1.2,    0.0,\n LAI_JUN = 4.0,    4.5,    2.0,    4.7,    4.3,    3.5,    2.3,    4.1,    3.6,    3.0,    2.9,    2.0,    0.0,    2.5,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_JUL = 4.0,    4.5,    2.6,    4.5,    4.3,    3.5,    2.3,    4.1,    3.8,    3.5,    3.5,    3.0,    0.0,    3.2,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_AUG = 4.0,    4.5,    1.7,    3.4,    3.7,    2.5,    1.7,    2.7,    2.1,    1.5,    2.7,    3.0,    0.0,    2.2,    0.0,    0.0,    0.0,    1.8,    1.3,    0.0,\n LAI_SEP = 4.0,    4.5,    1.0,    1.2,    2.6,    0.9,    0.6,    1.0,    0.9,    0.7,    1.2,    1.5,    0.0,    1.1,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_OCT = 4.0,    4.5,    0.5,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_NOV = 4.0,    4.5,    0.2,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_DEC = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n\n SLAREA=0.0090, 0.0200, 0.0200, 0.0258, 0.0223, 0.0227, 0.0188, 0.0227, 0.0236, 0.0060, 0.0295, 0.0200, 0.0228, 0.0223,   0.02,   0.02, 0.0422,   0.02,   0.02,   0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1  =  0.46,   0.00,   0.00,  46.86,  30.98,  21.62,   0.11,  21.62,  22.80,   0.02,  0.815,   0.00,  41.87,   0.04,    0.0,    0.0,   2.31,    0.0,    0.0,    0.0,\n EPS2  =  3.34,   0.00,   0.00,   0.38,   0.96,   0.92,   0.22,   0.92,   0.59,   0.05,  0.535,   0.00,   0.98,   0.09,    0.0,    0.0,   1.47,    0.0,    0.0,    0.0,\n EPS3  =  1.85,   0.00,   0.00,   1.84,   1.84,   1.73,   1.26,   1.73,   1.37,   0.03,  0.605,   0.00,   1.82,   0.05,    0.0,    0.0,   1.70,    0.0,    0.0,    0.0,\n EPS4  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n EPS5  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n\n/\n\n&noahmp_rad_parameters\n !------------------------------------------------------------------------------\n !                1       2       3       4       5       6       7       8     soil color index for soil albedo\n !------------------------------------------------------------------------------\n ALBSAT_VIS =   0.15,   0.11,   0.10,   0.09,   0.08,   0.07,   0.06,   0.05   ! saturated soil albedos\n ALBSAT_NIR =   0.30,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! saturated soil albedos\n ALBDRY_VIS =   0.27,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! dry soil albedos\n ALBDRY_NIR =   0.54,   0.44,   0.40,   0.36,   0.32,   0.28,   0.24,   0.20   ! dry soil albedos\n ALBICE     =   0.80,   0.55                                                   ! albedo land ice: 1=vis, 2=nir\n ALBLAK     =   0.60,   0.40                                                   ! albedo frozen lakes: 1=vis, 2=nir\n OMEGAS     =   0.8 ,   0.4                                                    ! two-stream parameter omega for snow\n BETADS     =   0.5                                                            ! two-stream parameter betad for snow\n BETAIS     =   0.5                                                            ! two-stream parameter betaI for snow\n EG         =   0.97,   0.98                                                   ! emissivity soil surface 1-soil;2-lake\n\n/\n\n&noahmp_global_parameters\n\n! atmospheric constituants\n\n  CO2    = 395.e-06     !co2 partial pressure\n  O2     = 0.209        !o2 partial pressure\n\n! runoff parameters used for SIMTOP and SIMGM:\n\n  TIMEAN = 10.5         !gridcell mean topgraphic index (global mean)\n  FSATMX = 0.38         !maximum surface saturated fraction (global mean)\n\n! adjustable parameters for snow processes\n\n  Z0SNO  = 0.002        !snow surface roughness length (m) (0.002)\n  SSI    = 0.03         !liquid water holding capacity for snowpack (m3/m3) (0.03)\n  SNOW_RET_FAC  = 5.e-5 !snowpack water release timescale factor (1/s)\n  SWEMX  = 1.00         !new snow mass to fully cover old snow (mm)\n                        !equivalent to 10mm depth (density = 100 kg/m3)\n  TAU0          = 1.e6  !tau0 from Yang97 eqn. 10a\n  GRAIN_GROWTH  = 5000. !growth from vapor diffusion Yang97 eqn. 10b\n  EXTRA_GROWTH  = 10.   !extra growth near freezing Yang97 eqn. 10c\n  DIRT_SOOT     = 0.3   !dirt and soot term Yang97 eqn. 10d\n  BATS_COSZ     = 2.0   !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n  BATS_VIS_NEW  = 0.95  !new snow visible albedo\n  BATS_NIR_NEW  = 0.65  !new snow NIR albedo\n  BATS_VIS_AGE  = 0.2   !age factor for diffuse visible snow albedo Yang97 eqn. 17\n  BATS_NIR_AGE  = 0.5   !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n  BATS_VIS_DIR  = 0.4   !cosz factor for direct visible snow albedo Yang97 eqn. 15\n  BATS_NIR_DIR  = 0.4   !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n  RSURF_SNOW = 50.0     !surface resistence for snow [s/m]\n  RSURF_EXP = 5.0       !exponent in the shape parameter for soil resistance option 1\n  IMPERV_URBAN = 0.95   !impervious fraction to use for urban type [0-1]\n  SCAMAX = 1.0          !maximum fractional snow covered area [0-1]\n  SWE_LIMIT = 5000.0    !maximum SWE limit [mm]\n\n/\n\n&noahmp_crop_parameters\n\n ! NCROP = 5\n !  1: Corn\n !  2: Soybean\n !  3: Sorghum\n !  4: Rice\n !  5: Winter wheat\n\nDEFAULT_CROP = 0                                      ! The default crop type(1-5); if zero, use generic dynamic vegetation \n\n!----------------------------------------------------------\n!                1       2       3       4       5\n!----------------------------------------------------------\n \nPLTDAY     =    130,    111,    111,    111,    111,  ! Planting date\nHSDAY      =    280,    300,    300,    300,    300,  ! Harvest date\nPLANTPOP   =   78.0,   78.0,   78.0,   78.0,   78.0,  ! Plant density [per ha] - used?\nIRRI       =    0.0,    0.0,    0.0,    0.0,    0.0,  ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n\nGDDTBASE   =   10.0,   10.0,   10.0,   10.0,   10.0,  ! Base temperature for GDD accumulation [C]\nGDDTCUT    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! Upper temperature for GDD accumulation [C]\nGDDS1      =   60.0,   50.0,   50.0,   50.0,   50.0,  ! GDD from seeding to emergence\nGDDS2      =  675.0,  718.0,  718.0,  718.0,  718.0,  ! GDD from seeding to initial vegetative \nGDDS3      = 1183.0,  933.0,  933.0,  933.0,  933.0,  ! GDD from seeding to post vegetative \nGDDS4      = 1253.0, 1103.0, 1103.0, 1103.0, 1103.0,  ! GDD from seeding to intial reproductive\nGDDS5      = 1605.0, 1555.0, 1555.0, 1555.0, 1555.0,  ! GDD from seeding to pysical maturity \n\nC3C4       =      2,      1,      2,      2,      2,  ! photosynthetic pathway:  1. = c3 2. = c4\nAref       =    7.0,    7.0,    7.0,    7.0,    7.0,  ! reference maximum CO2 assimulation rate \nPSNRF      =   0.85,   0.85,   0.85,   0.85,   0.85,  ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\nI2PAR      =    0.5,    0.5,    0.5,    0.5,    0.5,  ! Fraction of incoming solar radiation to photosynthetically active radiation\nTASSIM0    =    8.0,    8.0,    8.0,    8.0,    8.0,  ! Minimum temperature for CO2 assimulation [C]\nTASSIM1    =   18.0,   18.0,   18.0,   18.0,   18.0,  ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\nTASSIM2    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\nK          =   0.55,   0.55,   0.55,   0.55,   0.55,  ! light extinction coefficient\nEPSI       =   12.5,   12.5,   12.5,   12.5,   12.5,  ! initial light use efficiency\n\nQ10MR      =    2.0,    2.0,    2.0,    2.0,    2.0,  ! q10 for maintainance respiration\nFOLN_MX    =    1.5,    1.5,    1.5,    1.5,    1.5,  ! foliage nitrogen concentration when f(n)=1 (%)\nLEFREEZ    =    268,    268,    268,    268,    268,  ! characteristic T for leaf freezing [K]\n\nDILE_FC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for temperature leaf stress death [1/s]\nDILE_FC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0, \nDILE_FC_S5 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S6 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nDILE_FW_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for water leaf stress death [1/s]\nDILE_FW_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FW_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S5 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S6 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nFRA_GR     =    0.2,    0.2,    0.2,    0.2,    0.2,  ! fraction of growth respiration\n\nLF_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of leaf turnover  [1/s]\nLF_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLF_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S5 =    0.2,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S6 =    0.3,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nST_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of stem turnover  [1/s]\nST_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nST_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nST_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nST_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nRT_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of root tunrover  [1/s]\nRT_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRT_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nRT_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nRT_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n             \nLFMR25     =    1.0,    1.0,    1.0,    1.0,    1.0,  !  leaf maintenance respiration at 25C [umol CO2/m**2  /s]\nSTMR25     =   0.05,    0.1,    0.1,    0.1,    0.1,  !  stem maintenance respiration at 25C [umol CO2/kg bio/s]\nRTMR25     =   0.05,    0.0,    0.0,    0.0,    0.0,  !  root maintenance respiration at 25C [umol CO2/kg bio/s]\nGRAINMR25  =    0.0,    0.1,    0.1,    0.1,    0.1,  ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n\nLFPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to leaf\nLFPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLFPT_S3    =    0.4,    0.4,    0.4,    0.4,    0.4,\nLFPT_S4    =    0.2,    0.2,    0.2,    0.2,    0.2,\nLFPT_S5    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S6    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nSTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to stem\nSTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nSTPT_S3    =    0.2,    0.2,    0.2,    0.2,    0.2,\nSTPT_S4    =    0.5,    0.5,    0.5,    0.5,    0.5,\nSTPT_S5    =    0.0,   0.15,   0.15,   0.15,   0.15,\nSTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nSTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nSTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0, \n\nRTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to root\nRTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRTPT_S3    =   0.34,    0.4,    0.4,    0.4,    0.4,\nRTPT_S4    =    0.3,    0.3,    0.3,    0.3,    0.3,\nRTPT_S5    =   0.05,   0.05,   0.05,   0.05,   0.05,\nRTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nRTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nRTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n   \nGRAINPT_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to grain\nGRAINPT_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nGRAINPT_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S5 =   0.95,    0.8,    0.8,    0.8,    0.8,\nGRAINPT_S6 =    1.0,    0.9,    0.9,    0.9,    0.9,\nGRAINPT_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n\nBIO2LAI   =  0.035,  0.015,  0.015,  0.015,  0.015,  ! leaf are per living leaf biomass [m^2/kg]\n\n/\n\n&noahmp_optional_parameters\n\n !------------------------------------------------------------------------------\n ! Saxton and Rawls 2006 Pedo-transfer function coefficients\n !------------------------------------------------------------------------------\n\n sr2006_theta_1500t_a =   -0.024   ! sand coefficient\n sr2006_theta_1500t_b =    0.487   ! clay coefficient\n sr2006_theta_1500t_c =    0.006   ! orgm coefficient\n sr2006_theta_1500t_d =    0.005   ! sand*orgm coefficient\n sr2006_theta_1500t_e =   -0.013   ! clay*orgm coefficient\n sr2006_theta_1500t_f =    0.068   ! sand*clay coefficient\n sr2006_theta_1500t_g =    0.031   ! constant adjustment\n\n sr2006_theta_1500_a  =    0.14    ! theta_1500t coefficient\n sr2006_theta_1500_b  =   -0.02    ! constant adjustment\n\n sr2006_theta_33t_a   =   -0.251   ! sand coefficient\n sr2006_theta_33t_b   =    0.195   ! clay coefficient\n sr2006_theta_33t_c   =    0.011   ! orgm coefficient\n sr2006_theta_33t_d   =    0.006   ! sand*orgm coefficient\n sr2006_theta_33t_e   =   -0.027   ! clay*orgm coefficient\n sr2006_theta_33t_f   =    0.452   ! sand*clay coefficient\n sr2006_theta_33t_g   =    0.299   ! constant adjustment\n\n sr2006_theta_33_a    =    1.283   ! theta_33t*theta_33t coefficient\n sr2006_theta_33_b    =   -0.374   ! theta_33t coefficient\n sr2006_theta_33_c    =   -0.015   ! constant adjustment\n\n sr2006_theta_s33t_a  =    0.278   ! sand coefficient\n sr2006_theta_s33t_b  =    0.034   ! clay coefficient\n sr2006_theta_s33t_c  =    0.022   ! orgm coefficient\n sr2006_theta_s33t_d  =   -0.018   ! sand*orgm coefficient\n sr2006_theta_s33t_e  =   -0.027   ! clay*orgm coefficient\n sr2006_theta_s33t_f  =   -0.584   ! sand*clay coefficient\n sr2006_theta_s33t_g  =    0.078   ! constant adjustment\n\n sr2006_theta_s33_a   =    0.636   ! theta_s33t coefficient\n sr2006_theta_s33_b   =   -0.107   ! constant adjustment\n\n sr2006_psi_et_a      =  -21.67    ! sand coefficient\n sr2006_psi_et_b      =  -27.93    ! clay coefficient\n sr2006_psi_et_c      =  -81.97    ! theta_s33 coefficient\n sr2006_psi_et_d      =   71.12    ! sand*theta_s33 coefficient\n sr2006_psi_et_e      =    8.29    ! clay*theta_s33 coefficient\n sr2006_psi_et_f      =   14.05    ! sand*clay coefficient\n sr2006_psi_et_g      =   27.16    ! constant adjustment\n\n sr2006_psi_e_a       =    0.02    ! psi_et*psi_et coefficient\n sr2006_psi_e_b       =   -0.113   ! psi_et coefficient\n sr2006_psi_e_c       =   -0.7     ! constant adjustment\n\n sr2006_smcmax_a      =   -0.097   ! sand adjustment\n sr2006_smcmax_b      =    0.043   ! constant adjustment\n \n/\n"
  },
  {
    "path": "src/Land_models/NoahMP/run/Makefile",
    "content": ".SUFFIXES:\n.SUFFIXES: .o .f\n\nifeq ($(WRF_HYDRO_RAPID),1)\ninclude ${TAO_DIR}/bmake/tao_common\nendif\n\ninclude ../user_build_options\n\nifeq ($(WRF_HYDRO_RAPID),1)\nPHDF5_INC=-I ${TACC_HDF5_INC}\nRAPID_MACRO = ${TAO_FORTRAN_LIB} ${TAO_LIB} ${PETSC_LIB} ${PHDF5_INC} \\\n        -Wl,-rpath,${TACC_HDF5_LIB} -L${TACC_HDF5_LIB} -lhdf5 -lz\nRAPID_LIB =  -lrapid\nelse\nRAPID_MACRO =\nRAPID_LIB =\nendif\n\nOBJS_NoahMP = ../IO_code/module_NoahMP_hrldas_driver.o\n\nOBJS := \\\n\t../IO_code/main_hrldas_driver.o \\\n\t../IO_code/module_hrldas_netcdf_io.o \\\n\t../phys/module_sf_noahmpdrv.o \\\n\t../phys/module_sf_noahmplsm.o \\\n\t../phys/module_sf_noahmp_glacier.o \\\n\t../phys/module_sf_noahmp_groundwater.o \\\n\t../Utility_routines/module_wrf_utilities.o \\\n\t../Utility_routines/module_model_constants.o \\\n\t../Utility_routines/module_date_utilities.o \\\n\t../Utility_routines/kwm_string_utilities.o\\\n\t../phys/surfex/modd_csts.o\\\n\t../phys/surfex/tridiag_ground_snowcro.o\\\n\t../phys/surfex/mode_surf_coefs.o\\\n\t../phys/surfex/mode_snow3l.o\\\n\t../phys/surfex/modd_snow_par.o\\\n\t../phys/surfex/ini_csts.o\\\n\t../phys/surfex/module_snowcro.o\\\n\t../phys/surfex/module_snowcro_intercept.o\\\n\t../phys/surfex/mode_thermos.o\\\n\t../phys/surfex/modd_surf_atm.o\\\n\t../phys/surfex/modd_snow_metamo.o\n\n# Check whether or not to build Crocus\nifndef BUILD_CROCUS\nBUILD_CROCUS:=1\nendif\nifeq ($(BUILD_CROCUS), 1)\n        OBJS := $(filter-out ../phys/surfex/module_snowcro_intercept.o, $(OBJS))\nelse\n        OBJS := $(filter-out ../phys/surfex/module_snowcro.o, $(OBJS))\nendif\n\nCMD = hrldas.exe\nall:\t$(CMD)\n\n### default we create the exe based on NoahMP\nhrldas.exe: $(OBJS)\n\t@echo \"\"\n\techo \"${TAO_FORTRAN_LIB} ${TAO_LIB} ${PETSC_LIB} ${PHDF5_INC} -Wl,-rpath,${TACC_HDF5_LIB} -L${TACC_HDF5_LIB} -lhdf5 -lz\"\n# We have to include the modules built in ../IO_code\n\t$(COMPILERF90) -o $(@) -I../IO_code -I../phys $(OBJS) $(OBJS_NoahMP) $(HYDRO_LIB) $(RAPID_LIB) $(NETCDFLIB) $(RAPID_MACRO) $(LDFLAGS) $(LIBS)\n\n\t@echo \"\"\n\n# Template to create the exe file based on different land model. Such as NoahMP\nNoahMP: $(OBJS)\n\t@echo \"\"\n\t$(COMPILERF90) -o hrldas.exe -I../IO_code -I../phys $(OBJS) $(OBJS_NoahMP)  $(HYDRO_LIB) $(NETCDFLIB) $(LDFLAGS) $(LIBS)\n\t@echo \"\"\n\n# This command cleans up\nclean:\n\t$(RM) *~ $(CMD)\n"
  },
  {
    "path": "src/Land_models/NoahMP/run/SOILPARM.TBL",
    "content": "Soil Parameters\nSTAS\n19,1   'BB      DRYSMC      F11     MAXSMC   REFSMC   SATPSI  SATDK      SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     2.79,    0.010,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,   0.010,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.74,    0.047,    -0.569,   0.434,   0.312,   0.141,  5.23E-6,  8.05E-6,   0.047,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.33,    0.084,     0.162,   0.476,   0.360,   0.759,  2.81E-6,  2.39E-5,   0.084,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     3.86,    0.061,     0.162,   0.484,   0.347,   0.955,  2.18E-6,  1.66E-5,   0.061,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     6.77,    0.069,    -1.491,   0.404,   0.315,   0.135,  4.45E-6,  1.01E-5,   0.069,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     8.72,    0.120,    -1.118,   0.464,   0.387,   0.617,  2.03E-6,  2.35E-5,   0.120,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.17,    0.103,    -1.297,   0.465,   0.382,   0.263,  2.45E-6,  1.13E-5,   0.103,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.73,    0.100,    -3.209,   0.406,   0.338,   0.098,  7.22E-6,  1.87E-5,   0.100,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.39,    0.126,    -1.916,   0.468,   0.404,   0.324,  1.34E-6,  9.64E-6,   0.126,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.55,    0.138,    -2.138,   0.468,   0.412,   0.468,  9.74E-7,  1.12E-5,   0.138,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,       0.0,     1.0,     0.0,     0.0,      0.0,      0.0,     0.0,  0.60,  0.001,  0.00,  0.00, 'WATER'\n15,    2.79,    0.006,    -1.111,    0.20,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.07,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.25,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.55,    0.030,   -10.472,   0.468,   0.454,   0.468,  9.74E-7,  1.12E-5,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    2.79,    0.006,    -0.472,   0.200,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    2.79,     0.01,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,    0.01,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\nSoil Parameters\nSTAS-RUC\n19,1   'BB      DRYSMC       HC     MAXSMC   REFSMC   SATPSI  SATDK       SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     4.05,    0.002,      1.47,   0.395,   0.174,   0.121,  1.76E-4,  0.608E-6,   0.033,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.38,    0.035,      1.41,   0.410,   0.179,   0.090,  1.56E-4,  0.514E-5,   0.055,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.90,    0.041,      1.34,   0.435,   0.249,   0.218,  3.47E-5,  0.805E-5,   0.095,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.39,    0.050,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.137,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     7.12,    0.068,      1.18,   0.420,   0.299,   0.299,  6.30E-6,  0.990E-5,   0.148,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     7.75,    0.060,      1.32,   0.477,   0.357,   0.356,  1.70E-6,  0.237E-4,   0.208,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.52,    0.085,      1.23,   0.476,   0.391,   0.630,  2.45E-6,  0.113E-4,   0.230,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.40,    0.100,      1.18,   0.426,   0.316,   0.153,  2.17E-6,  0.187E-4,   0.210,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.40,    0.070,      1.15,   0.492,   0.409,   0.490,  1.03E-6,  0.964E-5,   0.250,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.40,    0.068,      1.09,   0.482,   0.400,   0.405,  1.28E-6,  0.112E-4,   0.268,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.39,    0.027,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.117,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,      4.18,   1.0,     1.0,     0.0,      0.0,       0.0,     0.0,    0.00,  0.001,  0.00,  0.00, 'WATER'\n15,    4.05,    0.004,      2.03,   0.200,   0.10 ,   0.121,  1.41E-4,  0.136E-3,   0.006,  0.60,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.90,    0.065,      2.10,   0.435,   0.249,   0.218,  3.47E-5,  0.514E-5,   0.114,  0.05,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.40,    0.030,      1.41,   0.468,   0.454,   0.468,  9.74E-7,  0.112E-4,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    4.05,    0.006,      1.41,   0.200,   0.17,    0.069,  1.41E-4,  0.136E-3,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    4.05,     0.01,      1.47,   0.339,   0.236,   0.069,  1.76E-4,  0.608E-6,   0.060,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\n\n"
  },
  {
    "path": "src/Land_models/NoahMP/version",
    "content": "<<<<<<< HEAD\nbde2fa368be5a8013cf890b5f0572fef22329bbb\nAuthor: Michael Barlage <barlage@ucar.edu>\nDate:   Fri Oct 21 10:07:26 2016 -0600\n=======\ndist_params_omp\ncommit b4512d40d44913b0cbf0c9c2f016571525de238b\nAuthor: Wei Yu <weiyu@ucar.edu>\nDate:   Wed Jan 20 14:01:29 2016 -0700\n>>>>>>> 4893aa9c026b40a44ec14148a0d659ddfab7f814\n\ncommit 2162e6bfb88f6a7397f8f6ae1da9739b5c74e854\nAuthor: Michael Barlage <barlage@ucar.edu>\nDate:   Fri Sep 30 14:33:58 2016 -0600\n\n\n"
  },
  {
    "path": "src/MPP/CMakeLists.txt",
    "content": "add_library(hydro_mpp STATIC\n        CPL_WRF.F90\n        module_mpp_GWBUCKET.F90\n        module_mpp_ReachLS.F90\n        mpp_land.F90\n        hashtable.F90\n)\n\ntarget_link_libraries(hydro_mpp PUBLIC MPI::MPI_Fortran)\ntarget_include_directories(hydro_mpp PUBLIC\n        ${MPI_Fortran_MODULE_DIR}\n)\n"
  },
  {
    "path": "src/MPP/CPL_WRF.F90",
    "content": "!   This is used as a coupler with the WRF model.\nMODULE MODULE_CPL_LAND\n\n    use mpi\n    use, intrinsic :: iso_fortran_env, only: error_unit\n\n  IMPLICIT NONE\n\n  integer, public :: HYDRO_COMM_WORLD = MPI_COMM_NULL\n  integer my_global_id\n\n  integer total_pe_num\n  integer global_ix,global_jx\n\n  integer,allocatable,dimension(:,:) :: node_info\n\n  logical initialized, cpl_land, time_step_read_rstart, &\n           time_step_write_rstart, time_step_output\n  character(len=19) cpl_outdate, cpl_rstdate\n\n  integer, public :: cartGridComm\n  integer, public :: np_up_down, np_left_right\n  integer, public :: p_up_down, p_left_right\n\n  contains\n\n  ! sets incoming communicator and then calls CPL_LAND_INIT\n  !subroutine CPL_LAND_INIT_COMM(istart,iend,jstart,jend,hydroCommunicator)\n  !  implicit none\n  !\n  !  integer :: istart,iend,jstart,jend\n  !  integer :: hydroCommunicator\n  !\n  !  HYDRO_COMM_WORLD = hydroCommunicator\n  !  call CPL_LAND_INIT(istart,iend,jstart,jend)\n  !end subroutine\n\n  subroutine CPL_LAND_INIT(istart,iend,jstart,jend)\n      implicit none\n      integer ierr\n      logical mpi_inited\n      integer istart,iend,jstart,jend\n\n      integer :: xx, ndim\n      integer, dimension(0:1) :: dims, coords\n      logical cyclic(0:1), reorder\n      data cyclic/.false.,.false./  ! not cyclic\n      data reorder/.false./\n\n      call MPI_Initialized( mpi_inited, ierr )\n      if ( .NOT. mpi_inited ) then\n        call MPI_Init(ierr)\n        if (ierr /= MPI_SUCCESS) call fatal_error_stop(\"MPI Error: MPI_Init failed\")\n        call MPI_Comm_dup(MPI_COMM_WORLD, HYDRO_COMM_WORLD, ierr)\n        if (ierr /= MPI_SUCCESS) call fatal_error_stop(\"MPI Error: MPI_Comm_dup failed\")\n      endif\n\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, my_global_id, ierr )\n      call MPI_Comm_size( HYDRO_COMM_WORLD, total_pe_num, ierr )\n      if (ierr /= MPI_SUCCESS) call fatal_error_stop(\"MPI Error: MPI_Comm_rank and/or MPI_Comm_size failed\")\n\n      allocate(node_info(9,total_pe_num))\n\n      node_info = -99\n\n! send node info to node 0\n      node_info(1,my_global_id+1) = total_pe_num\n      node_info(6,my_global_id+1) = istart\n      node_info(7,my_global_id+1) = iend\n      node_info(8,my_global_id+1) = jstart\n      node_info(9,my_global_id+1) = jend\n\n\n      call send_info()\n      call find_left()\n      call find_right()\n      call find_up()\n      call find_down()\n\n      call send_info()\n\n      ! initialize cartesian grid communicator\n      dims(0) = 0\n      dims(1) = 0\n      do xx=1,total_pe_num\n        if(node_info(2,xx) .eq. (-1)) then\n          dims(0) = dims(0)+1\n        endif\n        if(node_info(4,xx) .eq. (-1)) then\n          dims(1) = dims(1)+1\n        endif\n      enddo\n\n      ndim = 2\n      np_up_down = dims(0)\n      np_left_right = dims(1)\n\n      call MPI_Cart_create(HYDRO_COMM_WORLD, ndim, dims, &\n                          cyclic, reorder, cartGridComm, ierr)\n\n      call MPI_Cart_get(cartGridComm, 2, dims, cyclic, coords, ierr)\n\n      p_up_down = coords(0)\n      p_left_right = coords(1)\n\n      initialized = .false.  ! land model need to be initialized.\n  END subroutine CPL_LAND_INIT\n\n     subroutine send_info()\n        implicit none\n        integer,allocatable,dimension(:,:) :: tmp_info\n        integer  ierr, i,size, tag\n        integer mpp_status(MPI_STATUS_SIZE)\n        tag  = 9\n        size =  9\n\n        if(my_global_id .eq. 0) then\n           do i = 1, total_pe_num-1\n             call MPI_Recv(node_info(:,i+1),size,MPI_INTEGER,  &\n                i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n           enddo\n        else\n           call MPI_Send(node_info(:,my_global_id+1),size,   &\n               MPI_INTEGER,0,tag,HYDRO_COMM_WORLD,ierr)\n        endif\n\n        call MPI_Barrier( HYDRO_COMM_WORLD ,ierr)\n\n        size = 9 * total_pe_num\n        call MPI_Bcast(node_info,size,MPI_INTEGER,   &\n            0,HYDRO_COMM_WORLD,ierr)\n\n        call MPI_Barrier( HYDRO_COMM_WORLD ,ierr)\n\n     end  subroutine send_info\n\n     subroutine find_left()\n          implicit none\n          integer i\n\n          node_info(2,my_global_id+1) = -1\n\n          do i = 1, total_pe_num\n               if( (node_info(8,i).eq.node_info(8,my_global_id+1)) .and. &\n                   (node_info(9,i).eq.node_info(9,my_global_id+1)) .and. &\n                   ((node_info(7,i)+1).eq.node_info(6,my_global_id+1)) ) then\n                   node_info(2,my_global_id+1) = i - 1\n                   return\n               endif\n          end do\n     end subroutine find_left\n\n     subroutine find_right()\n          implicit none\n          integer i\n\n          node_info(3,my_global_id+1) = -1\n\n          do i = 1, total_pe_num\n               if( (node_info(8,i).eq.node_info(8,my_global_id+1)) .and. &\n                   (node_info(9,i).eq.node_info(9,my_global_id+1)) .and. &\n                   ((node_info(6,i)-1).eq.node_info(7,my_global_id+1)) ) then\n                   node_info(3,my_global_id+1) = i - 1\n                   return\n               endif\n          end do\n     end subroutine find_right\n\n     subroutine find_up()\n          implicit none\n          integer i\n\n          node_info(4,my_global_id+1) = -1\n\n          do i = 1, total_pe_num\n               if( (node_info(6,i).eq.node_info(6,my_global_id+1)) .and. &\n                   (node_info(7,i).eq.node_info(7,my_global_id+1)) .and. &\n                   ((node_info(8,i)-1).eq.node_info(9,my_global_id+1)) ) then\n                   node_info(4,my_global_id+1) = i - 1\n                   return\n               endif\n          end do\n     end subroutine find_up\n\n     subroutine find_down()\n          implicit none\n          integer i\n\n          node_info(5,my_global_id+1) = -1\n\n          do i = 1, total_pe_num\n               if( (node_info(6,i).eq.node_info(6,my_global_id+1)) .and. &\n                   (node_info(7,i).eq.node_info(7,my_global_id+1)) .and. &\n                   ((node_info(9,i)+1).eq.node_info(8,my_global_id+1)) ) then\n                   node_info(5,my_global_id+1) = i - 1\n                   return\n               endif\n          end do\n     end subroutine find_down\n\n    ! stop the job due to the fatal error.\n    subroutine fatal_error_stop(msg)\n        character(len=*) :: msg\n        integer :: ierr\n        write(error_unit,*) \"The job is stoped due to the fatal error. \", trim(msg)\n        call flush(error_unit)\n        CALL MPI_Abort(HYDRO_COMM_WORLD, 1, ierr)\n        call MPI_Finalize(ierr)\n    end  subroutine fatal_error_stop\nEND MODULE MODULE_CPL_LAND\n"
  },
  {
    "path": "src/MPP/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nOBJS =  hashtable.o CPL_WRF.o mpp_land.o module_mpp_ReachLS.o module_mpp_GWBUCKET.o\n\nall:\t$(OBJS)\n\nhashtable.o: hashtable.F90\n\t@echo \"\"\n\t$(RMD) $(*).o $(*).mod $(*).stb *~\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) -c $(*).F90\n\tcp hashtable.mod ../mod\n\tar -r ../lib/libHYDRO.a $(@)\n\nmpp_land.o: mpp_land.F90\n\t@echo \"\"\n\t$(RMD) $(*).o $(*).mod $(*).stb *~\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) -c $(*).F90\n\tar -r ../lib/libHYDRO.a $(@)\n\nCPL_WRF.o: CPL_WRF.F90\n\t@echo \"\"\n\t$(RMD) $(*).o $(*).mod $(*).stb *~\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -I$(NETCDFINC) -o $(@) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) $(*).F90\n\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) -c $(*).F90\n\tar -r ../lib/libHYDRO.a $(@)\n\nmodule_mpp_ReachLS.o: module_mpp_ReachLS.F90\n\t@echo \"\"\n\t$(RMD) $(*).o $(*).mod $(*).stb *~\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) -c $(*).F90\n\tar -r ../lib/libHYDRO.a $(@)\n\nmodule_mpp_GWBUCKET.o: module_mpp_GWBUCKET.F90\n\t@echo \"\"\n\t$(RMD) $(*).o $(*).mod $(*).stb *~\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) -c $(*).F90\n\tar -r ../lib/libHYDRO.a $(@)\n\nclean:\n\t$(RMD) *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/MPP/Makefile.NoahMP",
    "content": "# Makefile \n#\n.SUFFIXES:\n.SUFFIXES: .o .F\n\ninclude ../user_build_options\n\nOBJS =  CPL_WRF.o mpp_land.o \n\nall:\t$(OBJS)\nmpp_land.o: mpp_land.F\n\t@echo \"\"\n\trm -f $(*).o $(*).mod \n\t$(COMPILERF90) $(F90FLAGS) $(FREESOURCE) -c $(*).F\n\nCPL_WRF.o: CPL_WRF.F\n\t@echo \"\"\n\trm -f $(*).o $(*).mod \n\t$(COMPILERF90) $(F90FLAGS) $(FREESOURCE) -c $(*).F\nclean:\n\trm -f  *.o *.mod \n"
  },
  {
    "path": "src/MPP/hashtable.F90",
    "content": "module hashtable\n    use iso_fortran_env, only: int64\n  implicit none\n\n  type kv_type\n     integer(kind=int64) :: key\n     integer(kind=int64) :: value\n  end type kv_type\n\n  type node_type\n     type(kv_type), allocatable :: kv\n     type(node_type), pointer :: next => null()\n\n   contains\n     ! If kv is not allocated, allocate and set to the key, value passed in.\n     ! If key is present and the same as the key passed in, overwrite the value.\n     ! Otherwise, defer to the next node (allocate if not allocated)\n     procedure :: node_set\n\n     ! If kv is not allocated, fail and return 0.\n     ! If key is present and the same as the key passed in, return the value in kv.\n     ! If next pointer is associated, delegate to it.\n     ! Otherwise, fail and return 0.\n     procedure :: node_get\n\n     ! If kv is not allocated, fail and return\n     ! If key is present and node is first in bucket, set first node in bucket to \n     !   the next node of first. Return success\n     ! If key is present and the node is another member of the linked list, link the \n     !   previous node's next node to this node's next node, deallocate this node, \n     !   return success\n\n     ! Deallocate kv is allocated.\n     ! Call the clear method of the next node if the next pointer associated.\n     ! Deallocate and nullify the next pointer.\n     procedure :: node_clear\n\n     ! Return the length of the linked list start from the current node.\n     procedure :: node_depth\n  end type node_type\n\n  public\n  type hash_t\n     integer(kind=int64) :: n_buckets = 0\n     integer(kind=int64) :: n_keys = 0\n     type(node_type), allocatable :: buckets(:)\n   contains\n     procedure, public :: bucket_count\n     procedure, public :: n_collisions\n     ! Returns number of keys.\n     procedure, public :: key_count\n     ! Set the value at a given a key.\n     procedure, public :: set\n     procedure, public :: set_all\n     procedure, public :: set_all_idx\n     ! Get the value at the given key.\n     procedure, public :: get\n     ! Clear all the allocated memory (must be called to prevent memory leak).\n     procedure, public :: clear\n     ! Private hashing function\n     procedure, private :: hash\n  end type hash_t\n\ncontains\n\n  function hash(this,key_value) result(bucket)\n\n    class(hash_t), intent(inout) :: this\n    integer(kind=int64), intent(in) :: key_value\n    integer(kind=int64) bucket\n\n    bucket = key_value\n\n  end function hash\n\n  function bucket_count(this)\n    class(hash_t), intent(inout) :: this\n    integer(kind=int64) bucket_count\n\n    bucket_count = this%n_buckets\n  end function bucket_count\n\n  function n_collisions(this)\n    class(hash_t), intent(inout) :: this\n    integer(kind=int64) n_collisions\n    integer(kind=int64) i\n\n    n_collisions = 0\n    do i = 1, this%n_buckets\n       n_collisions = n_collisions + node_depth(this%buckets(i)) - 1\n    enddo\n  end function n_collisions\n\n  recursive function node_depth(this) result(depth)\n    class(node_type), intent(inout) :: this\n    integer(kind=int64) depth\n\n    if (.not. associated(this%next)) then\n       depth = 1\n    else\n       depth = 1 + node_depth(this%next)\n    endif\n  end function node_depth\n\n  pure function key_count(this)\n    class(hash_t), intent(in) :: this\n    integer(kind=int64) key_count\n\n    key_count = this%n_keys\n  end function key_count\n\n  subroutine set(this, key, value)\n    class(hash_t), intent(inout) :: this\n    integer(kind=int64), intent(in) :: key\n    integer(kind=int64), intent(in) :: value\n    integer(kind=int64) bucket_id\n    logical :: is_new\n\n    bucket_id = modulo(this%hash(key), this%n_buckets) + 1\n\n    call this%buckets(bucket_id)%node_set(key, value)\n\n    if (is_new) this%n_keys = this%n_keys + 1\n  end subroutine set\n\n  subroutine set_all_idx(this, keys, length)\n    class(hash_t), intent(inout) :: this\n    integer(kind=int64), intent(in) :: keys(:)\n    integer, optional, intent(in) :: length\n    integer(kind=int64) :: i\n    integer(kind=int64) bucket_id, n\n\n    if(present(length)) then\n       n = length\n    else\n       n = size(keys)\n    end if\n\n    this%n_buckets = n\n    allocate(this%buckets(n))\n\n    do i = 1, n\n       bucket_id = modulo(this%hash(keys(i)),this%n_buckets) + 1\n       call this%buckets(bucket_id)%node_set(keys(i), i)\n       this%n_keys = this%n_keys + 1\n    end do\n  end subroutine set_all_idx\n\n  subroutine set_all(this, keys, values)\n    class(hash_t), intent(inout) :: this\n    integer(kind=int64), intent(in) :: keys(:)\n    integer(kind=int64), intent(in) :: values(:)\n    integer(kind=int64) bucket_id, i, n\n\n    n = size(keys)\n\n    this%n_buckets = n\n    allocate(this%buckets(n))\n\n    do i = 1, n\n       bucket_id = modulo(this%hash(keys(i)), this%n_buckets) + 1\n       call this%buckets(bucket_id)%node_set(keys(i), values(i))\n       this%n_keys = this%n_keys + 1\n    end do\n  end subroutine set_all\n\n  recursive subroutine node_set(this, key, value)\n    class(node_type), intent(inout) :: this\n    integer(kind=int64), intent(in) :: key\n    integer(kind=int64), intent(in) :: value\n\n    if (.not. allocated(this%kv)) then\n       allocate(this%kv)\n       this%kv%key = key\n       this%kv%value = value\n    else if (this%kv%key == key) then\n       this%kv%value = this%kv%value\n    else\n       if (.not. associated(this%next)) then\n          allocate(this%next)\n       end if\n       call this%next%node_set(key, value)\n    endif\n  end subroutine node_set\n\n  subroutine get(this, key, value, success)\n    class(hash_t), intent(inout) :: this\n    integer(kind=int64), intent(in) :: key\n    integer(kind=int64), intent(out) :: value\n    logical, intent(out) :: success\n    integer(kind=int64) bucket_id\n\n    success = .false.\n    if(this%n_buckets == 0) return\n    bucket_id = modulo(key,this%n_buckets) + 1\n    call this%buckets(bucket_id)%node_get(key, value, success)\n  end subroutine get\n\n  recursive subroutine node_get(this, key, value, success)\n    class(node_type), intent(inout) :: this\n    integer(kind=int64), intent(in) :: key\n    integer(kind=int64), intent(out) :: value\n    logical, intent(out) :: success\n\n    success = .false.\n\n    if (.not. allocated(this%kv)) then\n       ! Not found. (Initial node in the bucket not set)\n       success = .false.\n    else if (this%kv%key == key) then\n       value = this%kv%value\n       success = .true.\n    else if (associated(this%next)) then\n       call this%next%node_get(key, value, success)\n    else\n       success = .false.\n    endif\n  end subroutine node_get\n\n  subroutine clear(this)\n    class(hash_t), intent(inout) :: this\n    integer(kind=int64) i\n\n    if (.not. allocated(this%buckets)) return\n\n    do i = 1, size(this%buckets)\n       if (associated(this%buckets(i)%next)) then\n          call this%buckets(i)%next%node_clear()\n          deallocate(this%buckets(i)%next)\n          if(allocated(this%buckets(i)%kv)) then\n             deallocate(this%buckets(i)%kv)\n          endif\n       end if\n    enddo\n    deallocate(this%buckets)\n    this%n_keys = 0\n    this%n_buckets = 0\n  end subroutine clear\n\n  recursive subroutine node_clear(this)\n    class(node_type), intent(inout) :: this\n\n    if (associated(this%next)) then\n       call this%next%node_clear()\n       deallocate(this%next)\n       deallocate(this%kv)\n       nullify(this%next)\n    endif\n  end subroutine node_clear\n\nend module hashtable\n"
  },
  {
    "path": "src/MPP/module_mpp_GWBUCKET.F90",
    "content": "!   This is used as a coupler with the WRF model.\nMODULE MODULE_mpp_GWBUCKET\n\n  use MODULE_CPL_LAND, only: HYDRO_COMM_WORLD\n  use module_mpp_land, only:  io_id, my_id, mpp_status, mpp_land_max_int1, numprocs, &\n                 mpp_land_bcast_real, sum_real8,  mpp_land_sync\n  use iso_fortran_env, only: int64\n  use mpi\n  implicit none\n\n\n\n\n  integer,allocatable,dimension(:) :: sizeInd  ! size of Basins for each tile\n  integer ::  maxSizeInd\n\n  integer :: gw_ini\n\n  contains\n\n  subroutine gwbucket_ini()\n     allocate(sizeInd(numprocs))\n     sizeInd = 0\n     gw_ini = 99\n     maxSizeInd = 0\n  end subroutine gwbucket_ini\n\n\n  subroutine collectSizeInd(numbasns)\n     implicit none\n     integer, intent(in) :: numbasns\n     integer :: i, ierr, tag, rcv\n\n      call mpp_land_sync()\n\n     if(gw_ini .ne. 99) call gwbucket_ini()\n\n     if(my_id .ne. IO_id) then\n          tag = 66\n          call MPI_Send(numbasns,1,MPI_INTEGER, IO_id,     &\n                tag,HYDRO_COMM_WORLD,ierr)\n     else\n          do i = 0, numprocs - 1\n              if(i .eq. IO_id) then\n                 sizeInd(i+1) = numbasns\n              else\n                 tag = 66\n                 call MPI_Recv(rcv,1,&\n                     MPI_INTEGER,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n\n                 sizeInd(i+1) = rcv\n              end if\n              if(sizeInd(i+1) .gt. maxSizeInd) maxSizeInd = sizeInd(i+1)\n          end do\n      end if\n  end subroutine collectSizeInd\n\n  subroutine gw_write_io_real(numbasns,inV,ind,outV)\n     implicit none\n     integer, intent(in) :: numbasns\n     integer :: i, ierr, tag, tag2,k\n     real,intent(in), dimension(numbasns) :: inV\n     integer(kind=int64), intent(in), dimension(numbasns) :: ind\n     real, dimension(:) :: outV\n     real, allocatable,dimension(:) :: vbuff\n     integer(kind=int64), allocatable,dimension(:) :: ibuff\n\n     if(gw_ini .ne. 99) then\n        stop \"FATAL ERROR: mpp_GWBUCKET not initialized.\"\n     endif\n\n     if(my_id .eq. IO_id) then\n         outV = 0.0\n         allocate(vbuff(maxSizeInd))\n         allocate(ibuff(maxSizeInd))\n     else\n         allocate(vbuff(1))\n         allocate(ibuff(1))\n     endif\n\n     if(my_id .ne. IO_id) then\n        if(numbasns .gt. 0) then\n          tag = 62\n          call MPI_Send(inV,numbasns,MPI_REAL, IO_id,     &\n                tag,HYDRO_COMM_WORLD,ierr)\n          tag2 = 63\n          call MPI_Send(ind,numbasns,MPI_INTEGER8, IO_id,     &\n                tag2,HYDRO_COMM_WORLD,ierr)\n        endif\n      else\n\n          do k = 1, numbasns\n              outV(ind(k)) = inV(k)\n          end do\n\n          do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n               if(sizeInd(i+1) .gt. 0) then\n                  tag = 62\n                  call MPI_Recv(vbuff(1:sizeInd(i+1)),sizeInd(i+1),&\n                      MPI_REAL,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                  tag2 = 63\n                  call MPI_Recv(ibuff(1:sizeInd(i+1)),sizeInd(i+1),&\n                      MPI_INTEGER8,i,tag2,HYDRO_COMM_WORLD,mpp_status,ierr)\n                  do k = 1, sizeInd(i+1)\n                     outV(ibuff(k)) = vbuff(k)\n                  end do\n               endif\n             end if\n           end do\n      end if\n      if(allocated(ibuff)) deallocate(ibuff)\n      if(allocated(vbuff)) deallocate(vbuff)\n  end subroutine gw_write_io_real\n\n  subroutine gw_write_io_int(numbasns,inV,ind,outV)\n      implicit none\n      integer, intent(in) :: numbasns\n      integer :: i, ierr, tag, tag2,k\n      integer(kind=int64),intent(in), dimension(numbasns) :: inV\n      integer(kind=int64),intent(in), dimension(numbasns) :: ind\n      integer(kind=int64), dimension(:) :: outV\n      integer(kind=int64), allocatable,dimension(:) :: vbuff\n      integer(kind=int64), allocatable,dimension(:) :: ibuff\n\n      if(gw_ini .ne. 99) then\n         stop \"FATAL ERROR: mpp_GWBUCKET not initialized.\"\n      endif\n\n      if(my_id .eq. IO_id) then\n          outV = 0.0\n          allocate(vbuff(maxSizeInd))\n          allocate(ibuff(maxSizeInd))\n      else\n          allocate(vbuff(1))\n          allocate(ibuff(1))\n      endif\n\n      if(my_id .ne. IO_id) then\n         if(numbasns .gt. 0) then\n           tag = 62\n           call MPI_Send(inV,numbasns,MPI_INTEGER8, IO_id,     &\n                 tag,HYDRO_COMM_WORLD,ierr)\n           tag2 = 63\n           call MPI_Send(ind,numbasns,MPI_INTEGER8, IO_id,     &\n                 tag2,HYDRO_COMM_WORLD,ierr)\n         endif\n       else\n\n           do k = 1, numbasns\n               outV(ind(k)) = inV(k)\n           end do\n\n           do i = 0, numprocs - 1\n             if(i .ne. IO_id) then\n                if(sizeInd(i+1) .gt. 0) then\n                   tag = 62\n                   call MPI_Recv(vbuff(1:sizeInd(i+1)),sizeInd(i+1),&\n                       MPI_INTEGER8,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                   tag2 = 63\n                   call MPI_Recv(ibuff(1:sizeInd(i+1)),sizeInd(i+1),&\n                       MPI_INTEGER8,i,tag2,HYDRO_COMM_WORLD,mpp_status,ierr)\n                   do k = 1, sizeInd(i+1)\n                      outV(ibuff(k)) = vbuff(k)\n                   end do\n                endif\n              end if\n            end do\n       end if\n       deallocate(ibuff)\n       deallocate(vbuff)\n   end subroutine gw_write_io_int\n\n  subroutine gw_decompose_real(gnumbasns,numbasns,ind,inV,outV)\n     implicit none\n     integer, intent(in) :: numbasns, gnumbasns\n     integer :: i, ierr, tag, bas\n     real,intent(in), dimension(:) :: inV\n     integer(kind=int64),intent(in), dimension(:) :: ind\n     real, dimension(:) :: outV\n     real, dimension(gnumbasns) :: buff\n\n     outV = 0\n     if(gnumbasns .lt. 0) return\n\n     if(my_id .eq. io_id) buff = inV\n     call mpp_land_bcast_real(gnumbasns,buff)\n\n     do i = 1, numbasns\n        bas = ind(i)\n        outV(i) = buff(bas)\n     end do\n  end subroutine gw_decompose_real\n\n   subroutine gw_sum_real(vinout,nsize,gsize,ind)\n       implicit none\n       integer nsize,i,j,tag,ierr,gsize, k\n       real*8, dimension(nsize):: vinout\n       integer(kind=int64), dimension(nsize) :: ind\n       real*8, dimension(gsize) :: vbuff\n\n       vbuff = 0\n       do k = 1, nsize\n          vbuff(ind(k)) = vinout(k)\n       end do\n       call sum_real8(vbuff,gsize)\n       do k = 1, nsize\n          vinout(k) = vbuff(ind(k))\n       end do\n    end subroutine gw_sum_real\n\n\n\nend MODULE MODULE_mpp_GWBUCKET\n"
  },
  {
    "path": "src/MPP/module_mpp_ReachLS.F90",
    "content": "!   This is used as a coupler with the WRF model.\nMODULE MODULE_mpp_ReachLS\n\n  use module_mpp_land, only:  io_id, my_id, mpp_status, mpp_land_max_int1, mpp_land_sync, HYDRO_COMM_WORLD\n  use hashtable\n  use mpi\n  implicit none\n\n\n  TYPE Grid2ReachMap\n      real,allocatable, dimension(:) :: sv\n      real,allocatable, dimension(:) :: rv\n      real,allocatable, dimension(:) :: rvId\n      real,allocatable, dimension(:) :: snId\n  end TYPE Grid2ReachMap\n\n  interface ReachLS_decomp\n     module procedure ReachLS_decompReal\n     module procedure ReachLS_decompReal8\n     module procedure ReachLS_decompInt\n     module procedure ReachLS_decompInt8\n     module procedure ReachLS_decompChar\n  end interface\n\n  interface ReachLS_write_io\n     module procedure ReachLS_wReal\n     module procedure ReachLS_wReal2\n     module procedure ReachLS_wReal8\n     module procedure ReachLS_wInt\n     module procedure ReachLS_wInt2\n     module procedure ReachLS_wInt8\n     module procedure ReachLS_wChar\n  end interface\n\n  interface gBcastValue\n     module procedure gbcastReal\n     module procedure gbcastInt\n     module procedure gbcastReal2\n     module procedure gbcastInt8\n  end interface\n\n  interface updateLinkV\n     module procedure updateLinkV8_mem\n     module procedure updateLinkV4_mem\n  end interface\n\n\n\n\n  integer,allocatable,dimension(:) :: sDataRec  ! sending data size\n  integer,allocatable,dimension(:) :: rDataRec  ! receiving data size\n  integer,allocatable,dimension(:) :: linkls_s  ! receiving data size\n  integer,allocatable,dimension(:) :: linkls_e  ! receiving data size\n  integer,allocatable,dimension(:) :: ToInd  ! size of toInd\n\n  integer ::  numprocs\n  integer, allocatable, dimension(:) :: LLINKIDINDX, aLinksl\n  integer :: LLINKLEN, gNlinksl, tmpnlinksl, l_nlinksl, max_nlinkSL\n\n  contains\n\n\n  subroutine updateLinkV8_mem(LinkV, outV)\n! for big memory data\n     implicit none\n     real, dimension(:) :: outV\n     real*8, dimension(:) :: LinkV\n     real, allocatable, dimension(:) :: gLinkV_r4\n     real*8, allocatable,dimension(:) ::  tmpBuf, gLinkV_r8\n     integer :: ierr, i, tag, k,m,lsize\n     integer, allocatable,dimension(:) :: lindex\n     if(my_id .eq. io_id) then\n           allocate(gLinkV_r4(gnlinksl))\n           allocate(gLinkV_r8(gnlinksl))\n           gLinkV_r4 = 0.0\n           gLinkV_r8 = 0.0\n           do i = 1, LLINKLEN\n               gLinkV_r8(LLINKIDINDX(i)) = LinkV(i)\n           end do\n     endif\n\n     if(my_id .ne. IO_id) then\n\n          tag = 101\n          call MPI_Send(LLINKLEN,1,MPI_INTEGER, IO_id,     &\n                tag,HYDRO_COMM_WORLD,ierr)\n          if(LLINKLEN .gt. 0) then\n              tag = 102\n              call MPI_Send(LLINKIDINDX,LLINKLEN,MPI_INTEGER, IO_id,     &\n                    tag,HYDRO_COMM_WORLD,ierr)\n              tag = 103\n              call MPI_Send(LinkV,LLINKLEN,MPI_DOUBLE_PRECISION, IO_id,     &\n                   tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      else\n          do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n                tag = 101\n                call MPI_Recv(lsize,1,MPI_INTEGER, i,     &\n                            tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                if(lsize .gt. 0) then\n                      allocate(lindex(lsize) )\n                      allocate(tmpBuf(lsize) )\n                      tag = 102\n                      call MPI_Recv(lindex,lsize,MPI_INTEGER, i,     &\n                            tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                      tag = 103\n                      call MPI_Recv(tmpBuf,lsize,&\n                            MPI_DOUBLE_PRECISION,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                      do k = 1, lsize\n                          gLinkV_r8(lindex(k)) = gLinkV_r8(lindex(k)) + tmpBuf(k)\n                      end do\n                      if(allocated(lindex)) deallocate(lindex)\n                      if(allocated(tmpBuf)) deallocate(tmpBuf)\n               endif\n            end if\n          end do\n          gLinkV_r4 = gLinkV_r8\n          if(allocated(gLinkV_r8)) deallocate(gLinkV_r8)\n      end if\n\n      call ReachLS_decompReal(gLinkV_r4,outV)\n\n      if(my_id .eq. io_id) then\n         if(allocated(gLinkV_r4))  deallocate(gLinkV_r4)\n      endif\n  end subroutine updateLinkV8_mem\n\n  subroutine updateLinkV4_mem(LinkV, outV)\n! for big memory data\n     implicit none\n     real, dimension(:) :: outV\n     real, dimension(:) :: LinkV\n     real, allocatable, dimension(:) :: gLinkV_r4\n     real, allocatable,dimension(:) ::  tmpBuf\n     integer :: ierr, i, tag, k,m,lsize\n     integer, allocatable,dimension(:) :: lindex\n     if(my_id .eq. io_id) then\n           allocate(gLinkV_r4(gnlinksl))\n           gLinkV_r4 = 0.0\n           do i = 1, LLINKLEN\n               gLinkV_r4(LLINKIDINDX(i)) = LinkV(i)\n           end do\n     endif\n\n     if(my_id .ne. IO_id) then\n\n          tag = 101\n          call MPI_Send(LLINKLEN,1,MPI_INTEGER, IO_id,     &\n                tag,HYDRO_COMM_WORLD,ierr)\n          if(LLINKLEN .gt. 0) then\n              tag = 102\n              call MPI_Send(LLINKIDINDX,LLINKLEN,MPI_INTEGER, IO_id,     &\n                    tag,HYDRO_COMM_WORLD,ierr)\n              tag = 103\n              call MPI_Send(LinkV,LLINKLEN,MPI_REAL, IO_id,     &\n                   tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      else\n          do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n                tag = 101\n                call MPI_Recv(lsize,1,MPI_INTEGER, i,     &\n                            tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                if(lsize .gt. 0) then\n                      allocate(lindex(lsize) )\n                      allocate(tmpBuf(lsize) )\n                      tag = 102\n                      call MPI_Recv(lindex,lsize,MPI_INTEGER, i,     &\n                            tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                      tag = 103\n                      call MPI_Recv(tmpBuf,lsize,&\n                            MPI_REAL,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                      do k = 1, lsize\n                          gLinkV_r4(lindex(k)) = gLinkV_r4(lindex(k)) + tmpBuf(k)\n                      end do\n                      if(allocated(lindex)) deallocate(lindex)\n                      if(allocated(tmpBuf)) deallocate(tmpBuf)\n               endif\n            end if\n          end do\n      end if\n\n      call ReachLS_decompReal(gLinkV_r4,outV)\n\n      if(my_id .eq. io_id) then\n          if(allocated(gLinkV_r4)) deallocate(gLinkV_r4)\n      endif\n  end subroutine updateLinkV4_mem\n\n\n  subroutine updateLinkV8(LinkV, outV)\n     implicit none\n     real, dimension(:) :: outV\n     real*8, dimension(:) :: LinkV\n     real*8, dimension(gNlinksl) :: gLinkV,gLinkV_r\n     real, dimension(gNlinksl) :: gLinkV_r4\n     integer :: ierr, i, tag\n     gLinkV = 0.0\n     gLinkV_r = 0.0\n     do i = 1, LLINKLEN\n         gLinkV(LLINKIDINDX(i)) = LinkV(i)\n     end do\n\n     if(my_id .ne. IO_id) then\n          tag = 102\n          call MPI_Send(gLinkV,gnlinksl,MPI_DOUBLE_PRECISION, IO_id,     &\n                tag,HYDRO_COMM_WORLD,ierr)\n      else\n          gLinkV_r = gLinkV\n          do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n               tag = 102\n               call MPI_Recv(gLinkV,gnlinksl,&\n                   MPI_DOUBLE_PRECISION,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               gLinkV_r = gLinkV_r + gLinkV\n            end if\n          end do\n      end if\n      gLinkV_r4 = gLinkV_r\n\n      call ReachLS_decompReal(gLinkV_r4,outV)\n  end subroutine updateLinkV8\n\n  subroutine updateLinkV4(LinkV, outV)\n     implicit none\n     real, dimension(:) :: outV\n     real, dimension(:) :: LinkV\n     real, dimension(gNlinksl) :: gLinkV,gLinkV_r\n     real, dimension(gNlinksl) :: gLinkV_r4\n     integer :: ierr, i, tag\n     gLinkV = 0.0\n     gLinkV_r = 0.0\n     do i = 1, LLINKLEN\n         gLinkV(LLINKIDINDX(i)) = LinkV(i)\n     end do\n\n     if(my_id .ne. IO_id) then\n          tag = 102\n          call MPI_Send(gLinkV,gnlinksl,MPI_REAL, IO_id,     &\n                tag,HYDRO_COMM_WORLD,ierr)\n      else\n          gLinkV_r = gLinkV\n          do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n               tag = 102\n               call MPI_Recv(gLinkV,gnlinksl,&\n                   MPI_REAL,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               gLinkV_r = gLinkV_r + gLinkV\n            end if\n          end do\n      end if\n      gLinkV_r4 = gLinkV_r\n      call ReachLS_decompReal(gLinkV_r4,outV)\n  end subroutine updateLinkV4\n\n  subroutine gbcastReal(inV, outV)\n     implicit none\n     real, dimension(:) :: outV\n     real, dimension(:) :: inV\n     integer :: ierr\n     call ReachLS_write_io(inV,outV)\n     call MPI_Bcast(outV(1:gnlinksl),gnlinksl,MPI_REAL,   &\n            IO_id,HYDRO_COMM_WORLD,ierr)\n  end subroutine gbcastReal\n\n  subroutine gbcastReal2_old(index,size1,inV, insize, outV)\n     implicit none\n     integer :: size1, insize\n     integer,dimension(:) :: index\n     real, dimension(:) :: outV\n     real, dimension(:) :: inV\n     real, dimension(max_nlinkSL) :: tmpV\n     integer :: ierr, k, i, m, j, bsize\n     outV = 0\n     do i = 0, numprocs -1\n            bsize = linkls_e(i+1) - linkls_s(i+1) + 1\n         if(linkls_e(i+1) .gt. 0) then\n            if(my_id .eq. i) tmpV(1:bsize) = inV(1:bsize)\n            call MPI_Bcast(tmpV(1:bsize),bsize,MPI_REAL,   &\n                i,HYDRO_COMM_WORLD,ierr)\n            do j = 1, size1\n                do k = 1, bsize\n                   if(index(j) .eq. (linkls_s(i+1) + k -1) ) then\n                      outV(j) = tmpV(k)\n                      goto  100\n                   endif\n                end do\n 100            continue\n            end do\n\n         endif\n     end do\n  end subroutine gbcastReal2_old\n\n  subroutine gbcastReal2(index,size1,inV, insize, outV)\n     implicit none\n     integer :: size1, insize\n     integer,dimension(:) :: index\n     real, dimension(:) :: outV\n     real, dimension(:) :: inV\n!     real, dimension(max_nlinkSL) :: tmpV\n     real, dimension(gnlinksl) :: gbuf\n     integer :: ierr, k, i, m, j, bsize\n     outV = 0\n     call ReachLS_write_io(inV,gbuf)\n     call MPI_Bcast(gbuf,gnlinksl,MPI_REAL,   &\n            IO_id,HYDRO_COMM_WORLD,ierr)\n     do j = 1, size1\n        outV(j) = gbuf(index(j))\n     end do\n  end subroutine gbcastReal2\n\n\n\n\n  subroutine gbcastInt(inV, outV)\n     implicit none\n     integer, dimension(:) :: outV\n     integer, dimension(:) :: inV\n     integer :: ierr\n     call ReachLS_write_io(inV,outV)\n     call MPI_Bcast(outV(1:gnlinksl),gnlinksl,MPI_INTEGER,   &\n            IO_id,HYDRO_COMM_WORLD,ierr)\n  end subroutine gbcastInt\n\n  subroutine gbcastInt8(inV, outV)\n      implicit none\n      integer(kind=int64), dimension(:) :: outV\n      integer(kind=int64), dimension(:) :: inV\n      integer :: ierr\n      call ReachLS_write_io(inV,outV)\n      call MPI_Bcast(outV(1:gnlinksl),gnlinksl,MPI_INTEGER8,   &\n              IO_id,HYDRO_COMM_WORLD,ierr)\n  end subroutine gbcastInt8\n\n  subroutine getLocalIndx(glinksl,LINKID, LLINKID)\n       implicit none\n       integer(kind=int64), dimension(:) :: LINKID, LLINKID\n       integer :: i,k, glinksl, ierr\n       integer(kind=int64) :: gLinkId(glinksl)\n\n       LLINKLEN = size(LLINKID,1)\n       allocate(LLINKIDINDX(LLINKLEN))\n       LLINKIDINDX = 0\n       gNlinksl = glinksl\n\n       call ReachLS_write_io(LINKID,gLinkId)\n\n       call MPI_Bcast(gLinkId(1:glinksl),glinksl,MPI_INTEGER8,   &\n            IO_id,HYDRO_COMM_WORLD,ierr)\n\n       ! The following loops are replaced by a hashtable-based algorithm\n       !        do i = 1, LLINKLEN\n       !           do k = 1, glinksl\n       !              if(LLINKID(i) .eq. gLinkId(k)) then\n       !                 LLINKIDINDX(i) = k\n       !                 goto 1001\n       !              endif\n       !           end do\n       ! 1001      continue\n       !     end do\n\n       block\n         type(hash_t) :: hash_table\n         integer(kind=int64) :: val,it\n         logical :: found\n\n         call hash_table%set_all_idx(LLINKID,LLINKLEN)\n         do it=1, glinksl\n            call hash_table%get(gLinkId(it), val, found)\n            if(found .eqv. .true.) then\n               llinkidindx(val) = it\n            end if\n         end do\n         call hash_table%clear()\n       end block\n\n       call mpp_land_sync()\n  end subroutine getLocalIndx\n\n  subroutine ReachLS_ini(glinksl,nlinksl,linklsS, linklsE)\n     implicit none\n     integer, intent(in) :: glinksl\n     integer, intent(out) :: nlinksl, linklsS, linklsE\n     integer :: i, ii, ierr\n\n! get my_id and numprocs\n     call MPI_Comm_rank( HYDRO_COMM_WORLD, my_id, ierr )\n     call MPI_Comm_size( HYDRO_COMM_WORLD, numprocs, ierr )\n\n\n     nlinksl = glinksl / numprocs\n     allocate(linkls_s(numprocs))\n     allocate(linkls_e(numprocs))\n     allocate(aLinksl(numprocs))\n     allocate(ToInd(numprocs))\n\n     ToInd = -1\n\n     linkls_s(1) = 1\n     linkls_e(1) = nlinksl\n     aLinksl = nlinksl\n\n     do i = 2, mod(glinksl, numprocs)+1\n         aLinksl(i) = aLinksl(i) + 1\n     end do\n     do i = 2, numprocs\n        linkls_s(i) = linkls_e(i-1)+1\n        linkls_e(i) = linkls_s(i) + aLinksl(i)-1\n     end do\n\n     nlinksl = aLinksl(my_id+1)\n\n     linklsS = linkls_s(my_id+1)\n     linklsE = linkls_e(my_id+1)\n     tmpnlinksl = aLinksl(my_id+1)\n     l_nlinksl = nlinksl\n\n     max_nlinksl = l_nlinksl\n     call mpp_land_max_int1(max_nlinksl)\n\n     gNlinksl = glinksl\n  end subroutine ReachLS_ini\n\n  subroutine MapGrid2ReachIni(in2d)\n     implicit none\n     integer, intent(in),dimension(:,:) :: in2d\n     integer :: ix, jx, i,j,n,ntotal, ierr\n     integer, dimension(numprocs) :: tmpS\n\n     allocate(sDataRec(numprocs))\n     allocate(rDataRec(numprocs))\n\n     ntotal = 0\n     sDataRec = 0\n     rDataRec = 0\n     ix = size(in2d,1)\n     jx = size(in2d,2)\n     do j = 1, jx\n        do i = 1, ix\n           if(in2d(i,j) .gt. 0) then\n              do n = 1, numprocs\n                  if((in2d(i,j) .ge. linkls_s(n)) .and. (in2d(i,j) .le. linkls_e(n)) ) then\n                              sDataRec(n) = sDataRec(n) + 1\n                  endif\n              end do\n           endif\n        enddo\n     enddo\n\n     do n = 1, numprocs\n         if(my_id .eq. n-1) then\n             tmpS = sDataRec\n         endif\n         call MPI_Bcast(tmpS,numprocs,MPI_INTEGER,   &\n            n-1,HYDRO_COMM_WORLD,ierr)\n         rDataRec(n) = tmpS(n)\n     enddo\n\n  end subroutine MapGrid2ReachIni\n\n\n  subroutine ReachLS_decompReal(inV,outV)\n      implicit none\n      real,INTENT(in),dimension(:) :: inV\n      real,INTENT(out),dimension(:) :: outV\n      integer ::  i, ierr, tag\n      tag = 11\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            if(i-1 .eq. io_id) then\n                if(alinksl(i) .gt. 0) then\n                   outV(1:(linkls_e(i)-linkls_s(i)+1) ) = inV(linkls_s(i):linkls_e(i))\n                endif\n            else\n                if(aLinksl(i) .gt. 0) then\n                    call MPI_Send(inV(linkls_s(i):linkls_e(i)), &\n                        aLinksl(i), &\n                        MPI_REAL, i-1 ,tag,HYDRO_COMM_WORLD,ierr)\n                endif\n            endif\n         end do\n      else\n         if(aLinksl(my_id+1) .gt. 0) then\n             call MPI_Recv(outV(1:(linkls_e(my_id+1)-linkls_s(my_id+1)+1) ), &  !! this one has +1!\n              aLinksl(my_id+1),                                        &\n              MPI_REAL, io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n         endif\n      endif\n      call mpp_land_sync()\n  END subroutine ReachLS_decompReal\n\n  subroutine ReachLS_decompReal8(inV,outV)\n      implicit none\n      real*8,intent(in),dimension(:) :: inV\n      real*8,intent(out),dimension(:) :: outV\n      integer ::  i, ierr, tag\n      tag = 11\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            if(i-1 .eq. io_id) then\n                if(alinksl(i) .gt. 0) then\n                   outV(1:(linkls_e(i)-linkls_s(i)+1) ) = inV(linkls_s(i):linkls_e(i))\n                endif\n            else\n                if(aLinksl(i) .gt. 0) then\n                    call MPI_Send(inV(linkls_s(i):linkls_e(i)), &\n                        aLinksl(i), &\n                        MPI_REAL8, i-1 ,tag,HYDRO_COMM_WORLD,ierr)\n                endif\n            endif\n         end do\n      else\n         if(aLinksl(my_id+1) .gt. 0) then\n             call MPI_Recv(outV(1:(linkls_e(my_id+1)-linkls_s(my_id+1)+1) ), &  !! this one has +1!\n              aLinksl(my_id+1),                                        &\n              MPI_REAL8, io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n         endif\n      endif\n      call mpp_land_sync()\n      end subroutine ReachLS_decompReal8\n\n  subroutine ReachLS_decompInt(inV,outV)\n      implicit none\n      integer,INTENT(in),dimension(:) :: inV\n      integer,INTENT(out),dimension(:) :: outV\n      integer ::  i, ierr, tag\n      tag = 11\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            if(i-1 .eq. io_id) then\n                if(alinksl(i) .gt. 0) then\n                    outV(1:linkls_e(i)-linkls_s(i)+1) = inV(linkls_s(i):linkls_e(i))\n                endif\n            else\n               if(aLinksl(i) .gt. 0) then\n                  call MPI_Send(inV(linkls_s(i):linkls_e(i)), &\n                      aLinksl(i),                &\n                      MPI_INTEGER, i-1,tag,HYDRO_COMM_WORLD,ierr)\n               endif\n            endif\n         end do\n      else\n          if(aLinksl(my_id+1) .gt. 0) then\n               call MPI_Recv(outV(1:linkls_e(my_id+1)-linkls_s(my_id+1)+1), &\n                    alinksl(my_id+1),                           &\n                    MPI_INTEGER, io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n          endif\n     endif\n\n      call mpp_land_sync()\n\n  END subroutine ReachLS_decompInt\n\n  subroutine ReachLS_decompInt8(inV,outV)\n      implicit none\n      integer(kind=int64), INTENT(in),  dimension(:) :: inV\n      integer(kind=int64), INTENT(out), dimension(:) :: outV\n      integer ::  i, ierr, tag\n      tag = 11\n      if(my_id .eq. io_id) then\n          do i = 1, numprocs\n              if(i-1 .eq. io_id) then\n                  if(alinksl(i) .gt. 0) then\n                      outV(1:linkls_e(i)-linkls_s(i)+1) = inV(linkls_s(i):linkls_e(i))\n                  endif\n              else\n                  if(aLinksl(i) .gt. 0) then\n                      call MPI_Send(inV(linkls_s(i):linkls_e(i)), &\n                              aLinksl(i),                &\n                              MPI_INTEGER8, i-1,tag,HYDRO_COMM_WORLD,ierr)\n                  endif\n              endif\n          end do\n      else\n          if(aLinksl(my_id+1) .gt. 0) then\n              call MPI_Recv(outV(1:linkls_e(my_id+1)-linkls_s(my_id+1)+1), &\n                      alinksl(my_id+1),                           &\n                      MPI_INTEGER8, io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n          endif\n      endif\n\n      call mpp_land_sync()\n\n  END subroutine ReachLS_decompInt8\n\n\n  subroutine ReachLS_decompChar(inV,outV)\n     implicit none\n     character(len=*),intent(in), dimension(:) :: inV\n     character(len=*),intent(out),dimension(:) :: outV\n     integer ::  i, ierr, tag\n     integer :: strLen\n     strLen = len(inV(1))\n     tag = 11\n     if(my_id .eq. io_id) then\n        do i = 1, numprocs\n           if(i-1 .eq. io_id) then\n              if(alinksl(i) .gt. 0) then\n                 outV(1:(linkls_e(i)-linkls_s(i)+1)) = inV(linkls_s(i):linkls_e(i))\n              endif\n           else\n              if(aLinksl(i) .gt. 0) then\n                 ! The MPI_Send takes what you give it and THEN treats each caracter as an array element.\n                 call MPI_Send(inV(linkls_s(i):linkls_e(i)),       &\n                      strLen*aLinksl(i),                           &\n                      MPI_CHARACTER, i-1, tag, HYDRO_COMM_WORLD, ierr)\n              endif\n           endif\n        end do\n     else\n        if(aLinksl(my_id+1) .gt. 0) then\n           ! The MPI_Recv treats each caracter as an array element.\n           call MPI_Recv(outV(1 : (linkls_e(my_id+1)-linkls_s(my_id+1)+1) ), &  !jlm should have +1\n                strLen*alinksl(my_id+1),                                              &\n                MPI_CHARACTER, io_id, tag, HYDRO_COMM_WORLD, mpp_status,ierr          )\n        endif\n     endif\n     call mpp_land_sync()\n  end subroutine ReachLS_decompChar\n\n\n  subroutine ReachLS_wReal(inV,outV)\n      implicit none\n      real,INTENT(in),dimension(:) :: inV\n      real,INTENT(out),dimension(:) :: outV\n      integer :: i, ierr, tag, ss  , mm\n      outV = 0\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            tag = 12\n            if(i-1 .eq. io_id) then\n                if(alinksl(i) .gt. 0) then\n                   outV(linkls_s(i):linkls_e(i)) = inV(1:linkls_e(i)-linkls_s(i)+1)\n                endif\n            else\n                if(aLinksl(i) .gt. 0) then\n\n                    call MPI_Recv(outV(linkls_s(i):linkls_e(i)), &\n                         aLinksl(i),                            &\n                         MPI_REAL,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                endif\n            endif\n         end do\n      else\n          if(aLinksl(my_id+1) .gt. 0) then\n               tag = 12\n               ss = size(inv,1)\n               call MPI_Send(inV(1:aLinksl(my_id+1) ), &\n                      aLinksl(my_id+1),                      &\n                      MPI_REAL,io_id,tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      endif\n      call mpp_land_sync()\n  END subroutine ReachLS_wReal\n\n  subroutine ReachLS_wReal8(inV,outV)\n      implicit none\n      real*8,intent(in),dimension(:)  :: inV\n      real*8,intent(out),dimension(:) :: outV\n      integer :: i, ierr, tag, ss  , mm\n      outV = 0\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            tag = 12\n            if(i-1 .eq. io_id) then\n                if(alinksl(i) .gt. 0) then\n                   outV(linkls_s(i):linkls_e(i)) = inV(1:linkls_e(i)-linkls_s(i)+1)\n                endif\n            else\n                if(aLinksl(i) .gt. 0) then\n\n                    call MPI_Recv(outV(linkls_s(i):linkls_e(i)), &\n                         aLinksl(i),                            &\n                         MPI_REAL8,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                endif\n            endif\n         end do\n      else\n          if(aLinksl(my_id+1) .gt. 0) then\n               tag = 12\n               ss = size(inv,1)\n               call MPI_Send(inV(1:aLinksl(my_id+1) ), &\n                      aLinksl(my_id+1),                      &\n                      MPI_REAL8,io_id,tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      endif\n      call mpp_land_sync()\n  END subroutine ReachLS_wReal8\n\n\n  subroutine ReachLS_wInt(inV,outV)\n      implicit none\n      integer,INTENT(in),dimension(:) :: inV\n      integer,INTENT(out),dimension(:) :: outV\n      integer :: i, ierr, tag\n      outV = 0\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            if(i-1 .eq. io_id) then\n                if(alinksl(i) .gt. 0) then\n                   outV(linkls_s(i):linkls_e(i)) = inV(1:linkls_e(i)-linkls_s(i)+1)\n                endif\n            else\n               if(aLinksl(i) .gt. 0) then\n                  tag = 12\n                  call MPI_Recv(outV(linkls_s(i):linkls_e(i)), &\n                       aLinksl(i),                             &\n                       MPI_INTEGER,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               endif\n            endif\n         end do\n      else\n           if(aLinksl(my_id+1) .gt. 0) then\n                tag = 12\n                call MPI_Send(inV(1:aLinksl(my_id+1) ), &\n                      aLinksl(my_id+1),                      &\n                      MPI_INTEGER,io_id,tag,HYDRO_COMM_WORLD,ierr)\n           endif\n      endif\n      call mpp_land_sync()\n  END subroutine ReachLS_wInt\n\n  subroutine ReachLS_wInt8(inV,outV)\n      implicit none\n      integer(kind=int64), intent(in), dimension(:)  :: inV\n      integer(kind=int64), intent(out), dimension(:) :: outV\n      integer :: i, ierr, tag\n      outV = 0\n      if(my_id .eq. io_id) then\n          do i = 1, numprocs\n              if(i-1 .eq. io_id) then\n                  if(alinksl(i) .gt. 0) then\n                      outV(linkls_s(i):linkls_e(i)) = inV(1:linkls_e(i)-linkls_s(i)+1)\n                  endif\n              else\n                  if(aLinksl(i) .gt. 0) then\n                      tag = 12\n                      call MPI_Recv(outV(linkls_s(i):linkls_e(i)), &\n                              aLinksl(i),                             &\n                              MPI_INTEGER8,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                  endif\n              endif\n          end do\n      else\n          if(aLinksl(my_id+1) .gt. 0) then\n              tag = 12\n              call MPI_Send(inV(1:aLinksl(my_id+1) ), &\n                      aLinksl(my_id+1),                      &\n                      MPI_INTEGER8,io_id,tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      endif\n      call mpp_land_sync()\n  END subroutine ReachLS_wInt8\n\n  subroutine ReachLS_wInt2(inV,outV,len,glen)\n      implicit none\n      integer  :: len, glen\n      integer,INTENT(in),dimension(len) :: inV\n      integer,INTENT(out),dimension(glen) :: outV\n      integer :: i, ierr, tag\n      outV = 0\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            if(i-1 .eq. io_id) then\n                if(alinksl(i) .gt. 0) then\n                   outV(linkls_s(i):linkls_e(i)) = inV(1:linkls_e(i)-linkls_s(i)+1)\n                endif\n            else\n               if(aLinksl(i) .gt. 0) then\n                  tag = 12\n                  call MPI_Recv(outV(linkls_s(i):linkls_e(i)), &\n                       aLinksl(i),                             &\n                       MPI_INTEGER,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               endif\n            endif\n         end do\n      else\n           if(aLinksl(my_id+1) .gt. 0) then\n                tag = 12\n                call MPI_Send(inV(1:aLinksl(my_id+1) ), &\n                      aLinksl(my_id+1),                      &\n                      MPI_INTEGER,io_id,tag,HYDRO_COMM_WORLD,ierr)\n           endif\n      endif\n      call mpp_land_sync()\n  END subroutine ReachLS_wInt2\n\n  subroutine ReachLS_wReal2(inV,outV,len,glen)\n      implicit none\n      integer :: len, glen\n      real,INTENT(in),dimension(len) :: inV\n      real,INTENT(out),dimension(glen) :: outV\n      integer :: i, ierr, tag\n      outV = 0\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            if(i-1 .eq. io_id) then\n                if(alinksl(i) .gt. 0) then\n                   outV(linkls_s(i):linkls_e(i)) = inV(1:linkls_e(i)-linkls_s(i)+1)\n                endif\n            else\n                if(aLinksl(i) .gt. 0) then\n                    tag = 12\n                    call MPI_Recv(outV(linkls_s(i):linkls_e(i)), &\n                         aLinksl(i),                            &\n                         MPI_REAL,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                endif\n            endif\n         end do\n      else\n          if(aLinksl(my_id+1) .gt. 0) then\n               tag = 12\n               call MPI_Send(inV(1:aLinksl(my_id+1) ), &\n                      aLinksl(my_id+1),                      &\n                      MPI_REAL,io_id,tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      endif\n      call mpp_land_sync()\n  END subroutine ReachLS_wReal2\n\n  subroutine ReachLS_wChar(inV,outV)\n     implicit none\n     character(len=*), intent(in), dimension(:)  :: inV\n     character(len=*) ,intent(out),dimension(:) :: outV\n     integer :: i, ierr, tag\n     integer :: strLen\n     strLen = len(inV(1))\n     if(my_id .eq. io_id) then\n        do i = 1, numprocs\n           if(i-1 .eq. io_id) then\n              if(alinksl(i) .gt. 0) then\n                 outV(linkls_s(i):linkls_e(i)) = inV(1:linkls_e(i)-linkls_s(i)+1)\n              endif\n           else\n              if(aLinksl(i) .gt. 0) then\n                 tag = 12\n                 ! ? seems asymmetric with ReachLS_decompChar\n                 call MPI_Recv(outV( linkls_s(i) : linkls_e(i) ), &\n!                 call MPI_Recv(outV( ((linkls_s(i)-1)+1) : (linkls_e(i)) ), &\n                      aLinksl(i),                                                  &\n                      MPI_CHARACTER, i-1, tag, HYDRO_COMM_WORLD, mpp_status, ierr           )\n              endif\n           endif\n        end do\n     else\n        if(aLinksl(my_id+1) .gt. 0) then\n           tag = 12\n           ! The MPI_Send takes what you give it and THEN treats each caracter as an array element.\n           call MPI_Send(inV(1:aLinksl(my_id+1)),              &\n                aLinksl(my_id+1),                       &\n                MPI_CHARACTER, io_id, tag, HYDRO_COMM_WORLD, ierr)\n        endif\n     endif\n     call mpp_land_sync()\n  end subroutine ReachLS_wChar\n\n\n  subroutine getFromInd(linkid,to,ind,indLen)\n      integer,dimension(:) :: linkid, to\n      integer, allocatable, dimension(:) ::ind\n      integer :: k, m, kk, mm,indLen\n      integer, dimension(gnlinksl) :: glinkid\n      call ReachLS_write_io(linkid,glinkid)\n      mm = size(to,1)\n      kk = 0\n      do k = 1, gnlinksl\n          do m = 1, mm\n             if(glinkid(k) .eq. to(m) ) then\n                 kk = kk +1\n                 goto 2001\n             endif\n          end do\n2001      continue\n      end do\n      allocate(ind(kk))\n      kk = 0\n      do k = 1, gnlinksl\n          do m = 1, mm\n             if(glinkid(k) .eq. to(m) ) then\n                 kk = kk +1\n                 ind(kk) = glinkid(k)\n                 goto 2002\n             endif\n          end do\n2002      continue\n      end do\n      indLen = kk\n\n  end subroutine getFromInd\n\n  subroutine getToInd(from,to,ind,indLen,gToNodeOut)\n      implicit none\n\n    integer(kind=int64),dimension(:) :: from, to\n    integer, allocatable, dimension(:) ::ind\n    integer(kind=int64), allocatable, dimension(:,:) :: gToNodeOut\n    integer :: k, m, kk, mm,indLen, i, ierr\n    integer(kind=int64), dimension(gnlinksl) :: gto\n    integer :: maxNum, num\n\n    call gBcastValue(to, gto)\n\n    !      mm = size(from,1)\n    mm = l_nlinksl\n\n    kk = 0\n    maxNum = 0\n\n    ! The following loops are replaced by a hashtable-based algorithm\n    ! do m = 1, mm\n    !    num = 0\n    !    do k = 1, gnlinksl\n    !       if(gto(k) .eq. from(m) ) then\n    !          kk = kk +1\n    !          num = num + 1\n    !       endif\n    !    end do\n    !    if(num .gt. maxNum) maxNum = num\n    ! end do\n\n    block\n      type(hash_t) :: hash_table\n      integer(kind=int64) :: val,it\n      integer(kind=int64), allocatable :: num_a(:)\n      logical :: found\n\n      allocate(num_a(mm))\n      num_a = 0\n      kk = 0\n\n      call hash_table%set_all_idx(from, mm)\n      do it=1, gnlinksl\n         call hash_table%get(gto(it), val, found)\n         if(found .eqv. .true.) then\n            kk = kk + 1\n            num_a(val) = num_a(val) + 1\n         end if\n      end do\n      maxNum = maxval(num_a)\n\n\n      allocate(ind(kk))\n      allocate(gToNodeOut(mm,maxNum+1))\n      gToNodeOut = -99\n\n      indLen = kk\n\n      kk = 0\n      num_a = 1\n\n      ! The following loops are replaced by a hashtable-based algorithm\n      ! do m = 1, mm\n      !    num = 1\n      !    do k = 1, gnlinksl\n      !        if(gto(k) .eq. from(m) ) then\n      !            kk = kk +1\n      !            !yw ind(kk) = gto(k)\n      !            ind(kk) = k\n      !            !! gToNodeOut(m,num+1) = gto(k)\n      !            gToNodeOut(m,num+1) = kk\n      !            gToNodeOut(m,1) = num\n      !            num = num + 1\n      !        endif\n      !     end do\n      ! end do\n\n      do it=1, gnlinksl\n         call hash_table%get(gto(it), val, found)\n         if(found .eqv. .true.) then\n            kk = kk + 1\n            ind(kk) = it\n            gToNodeOut(val,num_a(val)+1) = kk\n            gToNodeOut(val,1) = num_a(val)\n            num_a(val) = num_a(val) + 1\n         end if\n      end do\n\n      deallocate(num_a)\n      call hash_table%clear()\n\n    end block\n\n    ToInd(my_id+1) = kk\n    do i = 0, numprocs - 1\n       call MPI_Bcast(ToInd(i+1),1,MPI_INTEGER8,   &\n            i,HYDRO_COMM_WORLD,ierr)\n    end do\n\n  end subroutine getToInd\n\n  subroutine com_decomp1dInt(inV,gsize,outV,lsize)\n!     output outV and lsize\n      implicit none\n      integer,INTENT(in),dimension(:) :: inV\n      integer,allocatable,dimension(:) :: outV\n      integer ::  i, ierr, tag, imod, ncomsize\n      integer :: lsize, ssize,start, gsize, end\n      tag = 19\n      ncomsize = gsize/numprocs\n      imod = mod(gsize,numprocs)\n\n\n      if(my_id .eq. io_id) then\n         start = 0\n         end = 0\n         do i = 1, numprocs\n            if(i-1 .lt. imod) then\n                  ssize = ncomsize + 1\n            else\n                  ssize = ncomsize\n            endif\n\n            start = end + 1\n            end = start + ssize - 1\n\n            if(i-1 .eq. io_id) then\n                if(ssize .gt. 0) then\n                    allocate(outV(ssize) )\n                    outV(1:ssize) = inV(1:ssize)\n                    lsize = ssize\n                else\n                    lsize = 0\n                endif\n            else\n                if(ssize .gt. 0 ) then\n                   call MPI_Send(inV(start:start+ssize-1), ssize,       &\n                      MPI_INTEGER, i-1,tag,HYDRO_COMM_WORLD,ierr)\n                endif\n            endif\n         end do\n      else\n              if(my_id .lt. imod) then\n                   lsize = ncomsize + 1\n              else\n                   lsize = ncomsize\n              endif\n              if( lsize .gt. 0) then\n                  allocate(outV(lsize) )\n                  call MPI_Recv(outV,lsize,                           &\n                        MPI_INTEGER, io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n              endif\n      endif\n      call mpp_land_sync()\n\n\n  END subroutine com_decomp1dInt\n\n  subroutine com_decomp1dInt8(inV,gsize,outV,lsize)\n      !     output outV and lsize\n      implicit none\n      integer(kind=int64),intent(in),dimension(:) :: inV\n      integer(kind=int64),allocatable,dimension(:) :: outV\n      integer ::  i, ierr, tag, imod, ncomsize\n      integer :: lsize, ssize,start, gsize, end\n      tag = 19\n      ncomsize = gsize/numprocs\n      imod = mod(gsize,numprocs)\n\n\n      if(my_id .eq. io_id) then\n          start = 0\n          end = 0\n          do i = 1, numprocs\n              if(i-1 .lt. imod) then\n                  ssize = ncomsize + 1\n              else\n                  ssize = ncomsize\n              endif\n\n              start = end + 1\n              end = start + ssize - 1\n\n              if(i-1 .eq. io_id) then\n                  if(ssize .gt. 0) then\n                      allocate(outV(ssize) )\n                      outV(1:ssize) = inV(1:ssize)\n                      lsize = ssize\n                  else\n                      lsize = 0\n                  endif\n              else\n                  if(ssize .gt. 0 ) then\n                      call MPI_Send(inV(start:start+ssize-1), ssize,       &\n                              MPI_INTEGER8, i-1,tag,HYDRO_COMM_WORLD,ierr)\n                  endif\n              endif\n          end do\n      else\n          if(my_id .lt. imod) then\n              lsize = ncomsize + 1\n          else\n              lsize = ncomsize\n          endif\n          if( lsize .gt. 0) then\n              allocate(outV(lsize) )\n              call MPI_Recv(outV,lsize,                           &\n                      MPI_INTEGER8, io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n          endif\n      endif\n      call mpp_land_sync()\n\n\n  END subroutine com_decomp1dInt8\n\n  subroutine com_write1dInt(inV,lsize,outV,gsize)\n!     output outV and lsize\n      implicit none\n      integer,INTENT(in),dimension(:) :: inV\n      integer,dimension(:) :: outV\n      integer ::  i, ierr, tag, imod, ncomsize\n      integer :: lsize, rsize,start, gsize, end\n      tag = 18\n      ncomsize = gsize/numprocs\n      imod = mod(gsize,numprocs)\n\n      if(my_id .eq. io_id) then\n            start = 0\n            end = 0\n         do i = 1, numprocs\n            if(i-1 .lt. imod) then\n                  rsize = ncomsize + 1\n            else\n                  rsize = ncomsize\n            endif\n\n            start = end + 1\n            end = start + rsize - 1\n\n            if(i-1 .eq. io_id) then\n                if(rsize .gt. 0) then\n                    outV(1:rsize) = inV(1:rsize)\n                endif\n            else\n                if(rsize .gt. 0 ) then\n                  call MPI_Recv(outV(start:start+rsize-1), rsize,          &\n                        MPI_INTEGER, i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                endif\n            endif\n         end do\n      else\n              if(my_id .lt. imod) then\n                   lsize = ncomsize + 1\n              else\n                   lsize = ncomsize\n              endif\n              if( lsize .gt. 0) then\n                   call MPI_Send(inV, lsize,       &\n                      MPI_INTEGER, io_id,tag,HYDRO_COMM_WORLD,ierr)\n              endif\n      endif\n\n      call mpp_land_sync()\n\n  END subroutine com_write1dInt\n\n  subroutine com_write1dInt8(inV,lsize,outV,gsize)\n      !     output outV and lsize\n      implicit none\n      integer(kind=int64), intent(in),dimension(:) :: inV\n      integer(kind=int64), dimension(:) :: outV\n      integer ::  i, ierr, tag, imod, ncomsize\n      integer :: lsize, rsize,start, gsize, end\n      tag = 18\n      ncomsize = gsize/numprocs\n      imod = mod(gsize,numprocs)\n\n      if(my_id .eq. io_id) then\n          start = 0\n          end = 0\n          do i = 1, numprocs\n              if(i-1 .lt. imod) then\n                  rsize = ncomsize + 1\n              else\n                  rsize = ncomsize\n              endif\n\n              start = end + 1\n              end = start + rsize - 1\n\n              if(i-1 .eq. io_id) then\n                  if(rsize .gt. 0) then\n                      outV(1:rsize) = inV(1:rsize)\n                  endif\n              else\n                  if(rsize .gt. 0 ) then\n                      call MPI_Recv(outV(start:start+rsize-1), rsize,          &\n                              MPI_INTEGER8, i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                  endif\n              endif\n          end do\n      else\n          if(my_id .lt. imod) then\n              lsize = ncomsize + 1\n          else\n              lsize = ncomsize\n          endif\n          if( lsize .gt. 0) then\n              call MPI_Send(inV, lsize,       &\n                      MPI_INTEGER8, io_id,tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      endif\n\n      call mpp_land_sync()\n\n  END subroutine com_write1dInt8\n\n  subroutine pack_decomp_int(g1bufid, ndata, nprocs_map, lnsizes, istart,bufid)\n     implicit none\n     integer :: ndata\n     integer, dimension(:) :: g1bufid,  nprocs_map, lnsizes, bufid\n     integer :: i,j,k, tag, ierr\n     integer, allocatable,dimension(:) :: buf\n     integer, dimension(:) :: istart\n     integer, dimension(numprocs) :: count\n     ! pack data\n\n\n     if(my_id .eq. io_id) then\n         allocate(buf(ndata))\n         count = 0\n         do i = 1, ndata\n            k = nprocs_map(i)\n            if( k .gt. 0) then\n               buf(istart(k) + count(k)) = g1bufid(i)\n               count(k) = count(k) + 1\n            end if\n         end do\n!         write(6,*) \" count = \", count\n!         write(6,*) \" istart = \", istart\n!         write(6,*) \" lnsizes = \", lnsizes\n      end if\n      !finish packing\n\n      call mpp_land_sync()\n!      call hydro_finish()\n\n      if(my_id .ne. IO_id) then\n          tag = 72\n          if(lnsizes(my_id + 1) .gt. 0) then\n             call MPI_Recv(bufid,lnsizes(my_id + 1),&\n                   MPI_INTEGER,io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n          endif\n      else\n          do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               tag = 72\n               if(lnsizes(i+1) .gt. 0) then\n                  call MPI_Send(buf(istart(i+1):istart(i+1)+lnsizes(i+1)-1),  &\n                      lnsizes(i+1),MPI_INTEGER,i, tag,HYDRO_COMM_WORLD,ierr)\n               endif\n            else\n                if(lnsizes(i+1) .gt. 0) then\n                   bufid = buf(istart(i+1):istart(i+1)+lnsizes(i+1)-1)\n                endif\n            end if\n          end do\n       end if\n       if(my_id .eq. io_id) then\n          if(allocated(buf)) deallocate(buf)\n       endif\n  end subroutine pack_decomp_int\n\n  subroutine pack_decomp_int8(g1bufid, ndata, nprocs_map, lnsizes, istart,bufid)\n      implicit none\n      integer :: ndata\n      integer, dimension(:) :: nprocs_map, lnsizes\n      integer :: i,j,k, tag, ierr\n      integer(kind=int64), allocatable,dimension(:) :: buf, bufid, g1bufid\n      integer, dimension(:) :: istart\n      integer, dimension(numprocs) :: count\n      ! pack data\n\n\n      if(my_id .eq. io_id) then\n          allocate(buf(ndata))\n          count = 0\n          do i = 1, ndata\n              k = nprocs_map(i)\n              if( k .gt. 0) then\n                  buf(istart(k) + count(k)) = g1bufid(i)\n                  count(k) = count(k) + 1\n              end if\n          end do\n          !         write(6,*) \" count = \", count\n          !         write(6,*) \" istart = \", istart\n          !         write(6,*) \" lnsizes = \", lnsizes\n      end if\n      !finish packing\n\n      call mpp_land_sync()\n      !      call hydro_finish()\n\n      if(my_id .ne. IO_id) then\n          tag = 72\n          if(lnsizes(my_id + 1) .gt. 0) then\n              call MPI_Recv(bufid,lnsizes(my_id + 1),&\n                      MPI_INTEGER8,io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n          endif\n      else\n          do i = 0, numprocs - 1\n              if(i .ne. my_id) then\n                  tag = 72\n                  if(lnsizes(i+1) .gt. 0) then\n                      call MPI_Send(buf(istart(i+1):istart(i+1)+lnsizes(i+1)-1),  &\n                              lnsizes(i+1),MPI_INTEGER8,i, tag,HYDRO_COMM_WORLD,ierr)\n                  endif\n              else\n                  if(lnsizes(i+1) .gt. 0) then\n                      bufid = buf(istart(i+1):istart(i+1)+lnsizes(i+1)-1)\n                  endif\n              end if\n          end do\n      end if\n      if(my_id .eq. io_id) then\n          if(allocated(buf)) deallocate(buf)\n      endif\n  end subroutine pack_decomp_int8\n\n  subroutine pack_decomp_real8(g1bufid, ndata, nprocs_map, lnsizes, istart,bufid)\n     implicit none\n     integer :: ndata\n     real*8, dimension(:) :: g1bufid, bufid\n     integer,dimension(:) ::  nprocs_map, lnsizes\n     integer :: i,j,k, tag, ierr\n     real*8, allocatable,dimension(:) :: buf\n     integer, dimension(:) :: istart\n     integer, dimension(numprocs) :: count\n     ! pack data\n     if(my_id .eq. io_id) then\n         allocate(buf(ndata))\n         count = 0\n         do i = 1, ndata\n            k = nprocs_map(i)\n            if( k .gt. 0) then\n              buf(istart(k) + count(k)) = g1bufid(i)\n              count(k) = count(k) + 1\n            endif\n         end do\n      end if\n       call mpp_land_sync()\n      if(my_id .ne. IO_id) then\n          tag = 72\n          if(lnsizes(my_id + 1) .gt. 0) then\n             call MPI_Recv(bufid,lnsizes(my_id + 1),&\n                   MPI_DOUBLE_PRECISION,io_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n          endif\n      else\n          do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               tag = 72\n               if(lnsizes(i+1) .gt. 0) then\n                  call MPI_Send(buf(istart(i+1):istart(i+1)+lnsizes(i+1)-1),  &\n                      lnsizes(i+1),MPI_DOUBLE_PRECISION,i, tag,HYDRO_COMM_WORLD,ierr)\n               endif\n            else\n                if(lnsizes(my_id + 1) .gt. 0) then\n                   bufid = buf(istart(i + 1):istart(i+1)+lnsizes(i+1)-1)\n                endif\n            end if\n          end do\n       end if\n     if(my_id .eq. io_id) then\n         if(allocated(buf))  deallocate(buf)\n     endif\n  end subroutine pack_decomp_real8\n\n! this is used for nhdPlus with Lake.\n! resolve the data from TO_NODE grids, and update back to NLINKSL grids.\n  subroutine TONODE2RSL (ind,inVar,size,gNLINKSL,NLINKSL,ioVar,flag)\n    implicit none\n    integer,intent(in) :: size,gNLINKSL,NLINKSL  !\n    integer,intent(in) , dimension(size) :: ind, inVar\n    integer,intent(inout), dimension(nlinksl) :: ioVar\n    integer, allocatable, dimension(:) :: gvar, buf, tmpInd\n    integer :: i,j,k, tag, ierr, tmpSize, flag\n\n    if(gNLINKSL .le. 0) return\n\n    if(my_id .eq. io_id) then\n       allocate(gvar(gNLINKSL))\n    else\n       allocate(gvar(1))\n    endif\n    call ReachLS_wInt(ioVar,gvar)\n\n      if(my_id .eq. io_id) then\n         do i = 1, numprocs\n            if(i-1 .eq. io_id) then\n                do k = 1, size\n                   if(inVar(k) .ne. flag) then\n                      gvar(ind(k)) = inVar(k)\n                   endif\n                end do\n            else\n                  tag = 82\n                  call MPI_Recv(tmpSize,1,MPI_INTEGER,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                  if(tmpSize .gt. 0) then\n                      allocate(buf(tmpSize))\n                      allocate(tmpInd(tmpSize))\n                      tag = 83\n                      call MPI_Recv(tmpInd, tmpSize , &\n                           MPI_INTEGER,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                      tag = 84\n                      call MPI_Recv(buf, tmpSize , &\n                           MPI_INTEGER,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                      do k = 1, tmpSize\n                         if(buf(k) .ne. flag) then\n                             gvar(tmpInd(k)) = buf(k)\n                         endif\n                      end do\n                      if(allocated(buf))  deallocate(buf)\n                      if(allocated(tmpInd)) deallocate(tmpInd)\n                  endif\n            endif\n         end do\n      else\n          tag = 82\n          call MPI_Send(size,1,MPI_INTEGER,io_id,tag,HYDRO_COMM_WORLD,ierr)\n          if(size .gt. 0) then\n             tag = 83\n             call MPI_Send(ind(1:size),size, &\n                 MPI_INTEGER,io_id,tag,HYDRO_COMM_WORLD,ierr)\n             tag = 84\n             call MPI_Send(inVar(1:size),size, &\n                 MPI_INTEGER,io_id,tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      endif\n      call ReachLS_decomp(gvar, ioVar)\n      if(allocated(gvar)) deallocate(gvar)\n  end subroutine TONODE2RSL\n\n  subroutine TONODE2RSL8 (ind,inVar,size,gNLINKSL,NLINKSL,ioVar,flag)\n      implicit none\n      integer, intent(in) :: size,gNLINKSL,NLINKSL  !\n      integer, intent(in) , dimension(size) :: ind\n      integer(kind=int64), intent(in) , dimension(size) ::inVar\n      integer(kind=int64), intent(inout), dimension(nlinksl) :: ioVar\n      integer, allocatable, dimension(:) :: tmpInd\n      integer(kind=int64), allocatable, dimension(:) :: gvar, buf\n      integer :: i,j,k, tag, ierr, tmpSize, flag\n\n      if(gNLINKSL .le. 0) return\n\n      if(my_id .eq. io_id) then\n          allocate(gvar(gNLINKSL))\n      else\n          allocate(gvar(1))\n      endif\n      call ReachLS_wInt8(ioVar,gvar)\n\n      if(my_id .eq. io_id) then\n          do i = 1, numprocs\n              if(i-1 .eq. io_id) then\n                  do k = 1, size\n                      if(inVar(k) .ne. flag) then\n                          gvar(ind(k)) = inVar(k)\n                      endif\n                  end do\n              else\n                  tag = 82\n                  call MPI_Recv(tmpSize,1,MPI_INTEGER,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                  if(tmpSize .gt. 0) then\n                      allocate(buf(tmpSize))\n                      allocate(tmpInd(tmpSize))\n                      tag = 83\n                      call MPI_Recv(tmpInd, tmpSize , &\n                              MPI_INTEGER,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                      tag = 84\n                      call MPI_Recv(buf, tmpSize , &\n                              MPI_INTEGER8,i-1,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                      do k = 1, tmpSize\n                          if(buf(k) .ne. flag) then\n                              gvar(tmpInd(k)) = buf(k)\n                          endif\n                      end do\n                      if(allocated(buf))  deallocate(buf)\n                      if(allocated(tmpInd)) deallocate(tmpInd)\n                  endif\n              endif\n          end do\n      else\n          tag = 82\n          call MPI_Send(size,1,MPI_INTEGER,io_id,tag,HYDRO_COMM_WORLD,ierr)\n          if(size .gt. 0) then\n              tag = 83\n              call MPI_Send(ind(1:size),size, &\n                      MPI_INTEGER,io_id,tag,HYDRO_COMM_WORLD,ierr)\n              tag = 84\n              call MPI_Send(inVar(1:size),size, &\n                      MPI_INTEGER8,io_id,tag,HYDRO_COMM_WORLD,ierr)\n          endif\n      endif\n      call ReachLS_decomp(gvar, ioVar)\n      if(allocated(gvar)) deallocate(gvar)\n  end subroutine TONODE2RSL8\n\nEND MODULE MODULE_mpp_ReachLS\n"
  },
  {
    "path": "src/MPP/mpp_land.F90",
    "content": "!#### This is a module for parallel Land model.\nMODULE MODULE_MPP_LAND\n\n   use MODULE_CPL_LAND\n   use mpi\n   use iso_fortran_env, only: int64\n\n   IMPLICIT NONE\n   !integer, public :: HYDRO_COMM_WORLD ! communicator for WRF-Hydro - moved to MODULE_CPL_LAND\n   integer, public :: left_id,right_id,up_id,down_id,my_id\n   integer, public :: left_right_np,up_down_np ! define total process in two dimensions.\n   integer, public :: left_right_p ,up_down_p ! the position of the current process in the logical topography.\n   integer, public :: IO_id   ! the number for IO. (Last processor for IO)\n   integer, public :: global_nx, global_ny, local_nx,local_ny\n   integer, public :: global_rt_nx, global_rt_ny\n   integer, public :: local_rt_nx,local_rt_ny,rt_AGGFACTRT\n   integer, public :: numprocs   ! total process, get by MPI initialization.\n   integer :: local_startx, local_starty\n   integer :: local_startx_rt, local_starty_rt, local_endx_rt, local_endy_rt\n\n   integer mpp_status(MPI_STATUS_SIZE)\n\n   integer  overlap_n\n   integer, allocatable, DIMENSION(:), public :: local_nx_size,local_ny_size\n   integer, allocatable, DIMENSION(:), public :: local_rt_nx_size,local_rt_ny_size\n   integer, allocatable, DIMENSION(:), public :: startx,starty\n   integer, allocatable, DIMENSION(:), public :: mpp_nlinks\n\n   !dwj offset vectors and size vectors for scatterv and gatherv\n   integer, allocatable, dimension(:), public :: offset_vectors, offset_vectors_rt\n   integer, allocatable, dimension(:), public :: size_vectors, size_vectors_rt\n\n   interface check_land\n      module procedure check_landreal1\n      module procedure check_landreal1d\n      module procedure check_landreal2d\n      module procedure check_landreal3d\n   end interface\n\n   interface write_io_land\n      module procedure write_io_real3d\n   end interface\n\n   interface mpp_land_bcast\n      module procedure mpp_land_bcast_real2\n      module procedure mpp_land_bcast_real_1d\n      module procedure mpp_land_bcast_real8_1d\n      module procedure mpp_land_bcast_real1\n      module procedure mpp_land_bcast_real1_double\n      module procedure mpp_land_bcast_char1d\n      module procedure mpp_land_bcast_char1\n      module procedure mpp_land_bcast_int1\n      module procedure mpp_land_bcast_int1d\n      module procedure mpp_land_bcast_int2d\n      module procedure mpp_land_bcast_logical\n   end interface\n\ncontains\n\n   subroutine LOG_MAP2d()\n      implicit none\n      integer :: ndim, ierr\n      integer, dimension(0:1) :: dims, coords\n\n      logical cyclic(0:1), reorder\n      data cyclic/.false.,.false./  ! not cyclic\n      data reorder/.false./\n\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, my_id, ierr )\n      call MPI_Comm_size( HYDRO_COMM_WORLD, numprocs, ierr )\n\n      call getNX_NY(numprocs, left_right_np,up_down_np)\n      if(my_id.eq.IO_id) then\n#ifdef HYDRO_D\n         write(6,*) \"\"\n         write(6,*) \"total process:\",numprocs\n         write(6,*) \"left_right_np =\", left_right_np,&\n            \"up_down_np=\",up_down_np\n#endif\n      end if\n\n!   ### get the row and column of the current process in the logical topography.\n!   ### left --> right, 0 -->left_right_np -1\n!   ### up --> down, 0 --> up_down_np -1\n      left_right_p = mod(my_id , left_right_np)\n      up_down_p = my_id / left_right_np\n\n!   ### get the neighbors.  -1 means no neighbor.\n      down_id = my_id - left_right_np\n      up_id =   my_id + left_right_np\n      if( up_down_p .eq. 0) down_id = -1\n      if( up_down_p .eq. (up_down_np-1) ) up_id = -1\n\n      left_id = my_id - 1\n      right_id = my_id + 1\n      if( left_right_p .eq. 0) left_id = -1\n      if( left_right_p .eq. (left_right_np-1) ) right_id =-1\n\n!    ### the IO node is the last processor.\n!yw        IO_id = numprocs - 1\n      IO_id = 0\n\n! print the information for debug.\n\n! BF  setup virtual cartesian grid topology\n      ndim = 2\n\n      dims(0) = up_down_np      ! rows\n      dims(1) = left_right_np   ! columns\n!\n      call MPI_Cart_create(HYDRO_COMM_WORLD, ndim, dims, &\n         cyclic, reorder, cartGridComm, ierr)\n\n      call MPI_Cart_get(cartGridComm, 2, dims, cyclic, coords, ierr)\n\n      p_up_down = coords(0)\n      p_left_right = coords(1)\n      np_up_down = up_down_np\n      np_left_right = left_right_np\n\n   end  subroutine log_map2d\n\n   subroutine MPP_LAND_INIT(in_global_nx,in_global_ny)\n!    ### initialize the land model logically based on the two D method.\n!    ### Call this function directly if it is nested with WRF.\n      implicit none\n      integer, optional :: in_global_nx, in_global_ny\n      integer :: ierr, provided\n      logical mpi_inited\n\n      if (present(in_global_nx) .and. present(in_global_ny)) then\n         global_nx = in_global_nx\n         global_ny = in_global_ny\n      end if\n\n      call MPI_Initialized( mpi_inited, ierr )\n      if ( .not. mpi_inited ) then\n         call MPI_Init_thread( MPI_THREAD_FUNNELED, provided, ierr )\n         if (ierr /= MPI_SUCCESS) call fatal_error_stop(\"MPI Error: MPI_Init failed\")\n         call MPI_Comm_dup(MPI_COMM_WORLD, HYDRO_COMM_WORLD, ierr)\n         if (ierr /= MPI_SUCCESS) call fatal_error_stop(\"MPI Error: MPI_Comm_dup failed\")\n      endif\n\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, my_id, ierr )\n      call MPI_Comm_size( HYDRO_COMM_WORLD, numprocs, ierr )\n      if (ierr /= MPI_SUCCESS) call fatal_error_stop(\"MPI Error: MPI_Comm_rank and/or MPI_Comm_size failed\")\n\n      !     create 2d logical mapping of the CPU.\n      call log_map2d()\n   end   subroutine MPP_LAND_INIT\n\n\n   subroutine MPP_LAND_PAR_INI(over_lap,in_global_nx,in_global_ny,AGGFACTRT)\n      integer in_global_nx,in_global_ny, AGGFACTRT\n      integer :: over_lap   ! the overlaped grid number. (default is 1)\n      integer :: i\n\n      global_nx = in_global_nx\n      global_ny = in_global_ny\n      rt_AGGFACTRT = AGGFACTRT\n      global_rt_nx = in_global_nx*AGGFACTRT\n      global_rt_ny = in_global_ny *AGGFACTRT\n      !overlap_n = 1\n!ywold        local_nx = global_nx / left_right_np\n!ywold        if(left_right_p .eq. (left_right_np-1) ) then\n!ywold              local_nx = global_nx   &\n!ywold                    -int(global_nx/left_right_np)*(left_right_np-1)\n!ywold        end if\n!ywold        local_ny = global_ny / up_down_np\n!ywold        if(  up_down_p .eq. (up_down_np-1) ) then\n!ywold           local_ny = global_ny  &\n!ywold                 -int(global_ny/up_down_np)*(up_down_np -1)\n!ywold       end if\n\n      local_nx = int(global_nx / left_right_np)\n      !if(global_nx .ne. (local_nx*left_right_np) ) then\n      if(mod(global_nx, left_right_np) .ne. 0) then\n         do i = 1, mod(global_nx, left_right_np)\n            if(left_right_p .eq. i ) then\n               local_nx = local_nx + 1\n            end if\n         end do\n      end if\n\n      local_ny = int(global_ny / up_down_np)\n      !if(global_ny .ne. (local_ny * up_down_np) ) then\n      if(mod(global_ny,up_down_np) .ne. 0 ) then\n         do i = 1, mod(global_ny,up_down_np)\n            if( up_down_p .eq. i) then\n               local_ny = local_ny + 1\n            end if\n         end do\n      end if\n\n      local_rt_nx=local_nx*AGGFACTRT+2\n      local_rt_ny=local_ny*AGGFACTRT+2\n      if(left_id.lt.0) local_rt_nx = local_rt_nx -1\n      if(right_id.lt.0) local_rt_nx = local_rt_nx -1\n      if(up_id.lt.0) local_rt_ny = local_rt_ny -1\n      if(down_id.lt.0) local_rt_ny = local_rt_ny -1\n\n      call get_local_size(local_nx, local_ny,local_rt_nx,local_rt_ny)\n      call calculate_start_p()\n      call calculate_offset_vectors()\n\n      in_global_nx = local_nx\n      in_global_ny = local_ny\n#ifdef HYDRO_D\n      write(6,*) \"my_id=\",my_id,\"global_rt_nx=\",global_rt_nx\n      write(6,*) \"my_id=\",my_id,\"global_rt_nx=\",global_rt_ny\n      write(6,*) \"my_id=\",my_id,\"global_nx=\",global_nx\n      write(6,*) \"my_id=\",my_id,\"global_nx=\",global_ny\n#endif\n   end  subroutine MPP_LAND_PAR_INI\n\n   subroutine MPP_LAND_LR_COM(in_out_data,NX,NY,flag)\n!   ### Communicate message on left right direction.\n      integer NX,NY\n      real in_out_data(nx,ny),data_r(2,ny)\n      integer count,size,tag,  ierr\n      integer flag   ! 99 replace the boundary, else get the sum.\n\n      if(flag .eq. 99) then ! replace the data\n         if(right_id .ge. 0) then  !   ### send to right first.\n            tag = 11\n            size = ny\n            call MPI_Send(in_out_data(nx-1,:),size,MPI_REAL,   &\n               right_id,tag,HYDRO_COMM_WORLD,ierr)\n         end if\n         if(left_id .ge. 0) then !   receive from left\n            tag = 11\n            size = ny\n            call MPI_Recv(in_out_data(1,:),size,MPI_REAL,  &\n               left_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n         endif\n\n         if(left_id .ge. 0 ) then !   ### send to left second.\n            size = ny\n            tag = 21\n            call MPI_Send(in_out_data(2,:),size,MPI_REAL,   &\n               left_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(right_id .ge. 0) then !   receive from  right\n            tag = 21\n            size = ny\n            call MPI_Recv(in_out_data(nx,:),size,MPI_REAL,&\n               right_id,tag,HYDRO_COMM_WORLD, mpp_status,ierr)\n         endif\n\n      else   ! get the sum\n\n         if(right_id .ge. 0) then !   ### send to right first.\n            tag = 11\n            size = 2*ny\n            call MPI_Send(in_out_data(nx-1:nx,:),size,MPI_REAL,   &\n               right_id,tag,HYDRO_COMM_WORLD,ierr)\n         end if\n         if(left_id .ge. 0) then !   receive from left\n            tag = 11\n            size = 2*ny\n            call MPI_Recv(data_r,size,MPI_REAL,left_id,tag, &\n               HYDRO_COMM_WORLD,mpp_status,ierr)\n            in_out_data(1,:) = in_out_data(1,:) + data_r(1,:)\n            in_out_data(2,:) = in_out_data(2,:) + data_r(2,:)\n         endif\n\n         if(left_id .ge. 0 ) then !   ### send to left second.\n            size = 2*ny\n            tag = 21\n            call MPI_Send(in_out_data(1:2,:),size,MPI_REAL,   &\n               left_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(right_id .ge. 0) then !   receive from  right\n            tag = 21\n            size = 2*ny\n            call MPI_Recv(in_out_data(nx-1:nx,:),size,MPI_REAL,&\n               right_id,tag,HYDRO_COMM_WORLD, mpp_status,ierr)\n         endif\n      endif   ! end if black for flag.\n\n   end subroutine MPP_LAND_LR_COM\n\n   subroutine MPP_LAND_LR_COM8(in_out_data,NX,NY,flag)\n!   ### Communicate message on left right direction.\n      integer NX,NY\n      real*8 in_out_data(nx,ny),data_r(2,ny)\n      integer count,size,tag,  ierr\n      integer flag   ! 99 replace the boundary, else get the sum.\n\n      if(flag .eq. 99) then ! replace the data\n         if(right_id .ge. 0) then  !   ### send to right first.\n            tag = 11\n            size = ny\n            call MPI_Send(in_out_data(nx-1,:),size,MPI_DOUBLE_PRECISION,   &\n               right_id,tag,HYDRO_COMM_WORLD,ierr)\n         end if\n         if(left_id .ge. 0) then !   receive from left\n            tag = 11\n            size = ny\n            call MPI_Recv(in_out_data(1,:),size,MPI_DOUBLE_PRECISION,  &\n               left_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n         endif\n\n         if(left_id .ge. 0 ) then !   ### send to left second.\n            size = ny\n            tag = 21\n            call MPI_Send(in_out_data(2,:),size,MPI_DOUBLE_PRECISION,   &\n               left_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(right_id .ge. 0) then !   receive from  right\n            tag = 21\n            size = ny\n            call MPI_Recv(in_out_data(nx,:),size,MPI_DOUBLE_PRECISION,&\n               right_id,tag,HYDRO_COMM_WORLD, mpp_status,ierr)\n         endif\n\n      else   ! get the sum\n\n         if(right_id .ge. 0) then !   ### send to right first.\n            tag = 11\n            size = 2*ny\n            call MPI_Send(in_out_data(nx-1:nx,:),size,MPI_DOUBLE_PRECISION,   &\n               right_id,tag,HYDRO_COMM_WORLD,ierr)\n         end if\n         if(left_id .ge. 0) then !   receive from left\n            tag = 11\n            size = 2*ny\n            call MPI_Recv(data_r,size,MPI_DOUBLE_PRECISION,left_id,tag, &\n               HYDRO_COMM_WORLD,mpp_status,ierr)\n            in_out_data(1,:) = in_out_data(1,:) + data_r(1,:)\n            in_out_data(2,:) = in_out_data(2,:) + data_r(2,:)\n         endif\n\n         if(left_id .ge. 0 ) then !   ### send to left second.\n            size = 2*ny\n            tag = 21\n            call MPI_Send(in_out_data(1:2,:),size,MPI_DOUBLE_PRECISION,   &\n               left_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(right_id .ge. 0) then !   receive from  right\n            tag = 21\n            size = 2*ny\n            call MPI_Recv(in_out_data(nx-1:nx,:),size,MPI_DOUBLE_PRECISION,&\n               right_id,tag,HYDRO_COMM_WORLD, mpp_status,ierr)\n         endif\n      endif   ! end if black for flag.\n\n   end subroutine MPP_LAND_LR_COM8\n\n\n   subroutine get_local_size(local_nx, local_ny,rt_nx,rt_ny)\n      integer local_nx, local_ny, rt_nx,rt_ny\n      integer i,status,ierr, tag\n      integer tmp_nx,tmp_ny\n!   ### if it is IO node, get the local_size of the x and y direction\n!   ### for all other tasks.\n      integer s_r(2)\n\n!   if(my_id .eq. IO_id) then\n      if(.not. allocated(local_nx_size) ) allocate(local_nx_size(numprocs),stat = status)\n      if(.not. allocated(local_ny_size) ) allocate(local_ny_size(numprocs),stat = status)\n      if(.not. allocated(local_rt_nx_size) ) allocate(local_rt_nx_size(numprocs),stat = status)\n      if(.not. allocated(local_rt_ny_size) ) allocate(local_rt_ny_size(numprocs),stat = status)\n!   end if\n\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               !block receive  from other node.\n               tag = 1\n               call MPI_Recv(s_r,2,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               local_nx_size(i+1) = s_r(1)\n               local_ny_size(i+1) = s_r(2)\n            else\n               local_nx_size(i+1) = local_nx\n               local_ny_size(i+1) = local_ny\n            end if\n         end do\n      else\n         tag =  1\n         s_r(1) = local_nx\n         s_r(2) = local_ny\n         call MPI_Send(s_r,2,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n\n\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               !block receive  from other node.\n               tag = 2\n               call MPI_Recv(s_r,2,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               local_rt_nx_size(i+1) = s_r(1)\n               local_rt_ny_size(i+1) = s_r(2)\n            else\n               local_rt_nx_size(i+1) = rt_nx\n               local_rt_ny_size(i+1) = rt_ny\n            end if\n         end do\n      else\n         tag =  2\n         s_r(1) = rt_nx\n         s_r(2) = rt_ny\n         call MPI_Send(s_r,2,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n\n   end  subroutine get_local_size\n\n\n   subroutine MPP_LAND_UB_COM(in_out_data,NX,NY,flag)\n!   ### Communicate message on up down direction.\n      integer NX,NY\n      real in_out_data(nx,ny),data_r(nx,2)\n      integer count,size,tag, status, ierr\n      integer flag  ! 99 replace the boundary , else get the sum of the boundary\n\n\n      if(flag .eq. 99) then  ! replace the boundary data.\n\n         if(up_id .ge. 0 ) then !   ### send to up first.\n            tag = 31\n            size = nx\n            call MPI_Send(in_out_data(:,ny-1),size,MPI_REAL,   &\n               up_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(down_id .ge. 0 ) then !   receive from down\n            tag = 31\n            size = nx\n            call MPI_Recv(in_out_data(:,1),size,MPI_REAL, &\n               down_id,tag,HYDRO_COMM_WORLD, mpp_status,ierr)\n         endif\n\n         if(down_id .ge. 0 ) then !   send down.\n            tag = 41\n            size = nx\n            call MPI_Send(in_out_data(:,2),size,MPI_REAL,      &\n               down_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(up_id .ge. 0 ) then !   receive from upper\n            tag = 41\n            size = nx\n            call MPI_Recv(in_out_data(:,ny),size,MPI_REAL, &\n               up_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n         endif\n\n      else  ! flag = 1\n\n         if(up_id .ge. 0 ) then !   ### send to up first.\n            tag = 31\n            size = nx*2\n            call MPI_Send(in_out_data(:,ny-1:ny),size,MPI_REAL,   &\n               up_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(down_id .ge. 0 ) then !   receive from down\n            tag = 31\n            size = nx*2\n            call MPI_Recv(data_r,size,MPI_REAL, &\n               down_id,tag,HYDRO_COMM_WORLD, mpp_status,ierr)\n            in_out_data(:,1) = in_out_data(:,1) + data_r(:,1)\n            in_out_data(:,2) = in_out_data(:,2) + data_r(:,2)\n         endif\n\n         if(down_id .ge. 0 ) then !   send down.\n            tag = 41\n            size = nx*2\n            call MPI_Send(in_out_data(:,1:2),size,MPI_REAL,      &\n               down_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(up_id .ge. 0 ) then !   receive from upper\n            tag = 41\n            size = nx * 2\n            call MPI_Recv(in_out_data(:,ny-1:ny),size,MPI_REAL, &\n               up_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n         endif\n      endif  ! end of block  flag\n   end  subroutine MPP_LAND_UB_COM\n\n   subroutine MPP_LAND_UB_COM8(in_out_data,NX,NY,flag)\n!   ### Communicate message on up down direction.\n      integer NX,NY\n      real*8 in_out_data(nx,ny),data_r(nx,2)\n      integer count,size,tag, status, ierr\n      integer flag  ! 99 replace the boundary , else get the sum of the boundary\n\n\n      if(flag .eq. 99) then  ! replace the boundary data.\n\n         if(up_id .ge. 0 ) then !   ### send to up first.\n            tag = 31\n            size = nx\n            call MPI_Send(in_out_data(:,ny-1),size,MPI_DOUBLE_PRECISION,   &\n               up_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(down_id .ge. 0 ) then !   receive from down\n            tag = 31\n            size = nx\n            call MPI_Recv(in_out_data(:,1),size,MPI_DOUBLE_PRECISION, &\n               down_id,tag,HYDRO_COMM_WORLD, mpp_status,ierr)\n         endif\n\n         if(down_id .ge. 0 ) then !   send down.\n            tag = 41\n            size = nx\n            call MPI_Send(in_out_data(:,2),size,MPI_DOUBLE_PRECISION,      &\n               down_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(up_id .ge. 0 ) then !   receive from upper\n            tag = 41\n            size = nx\n            call MPI_Recv(in_out_data(:,ny),size,MPI_DOUBLE_PRECISION, &\n               up_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n         endif\n\n      else  ! flag = 1\n\n         if(up_id .ge. 0 ) then !   ### send to up first.\n            tag = 31\n            size = nx*2\n            call MPI_Send(in_out_data(:,ny-1:ny),size,MPI_DOUBLE_PRECISION,   &\n               up_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(down_id .ge. 0 ) then !   receive from down\n            tag = 31\n            size = nx*2\n            call MPI_Recv(data_r,size,MPI_DOUBLE_PRECISION, &\n               down_id,tag,HYDRO_COMM_WORLD, mpp_status,ierr)\n            in_out_data(:,1) = in_out_data(:,1) + data_r(:,1)\n            in_out_data(:,2) = in_out_data(:,2) + data_r(:,2)\n         endif\n\n         if(down_id .ge. 0 ) then !   send down.\n            tag = 41\n            size = nx*2\n            call MPI_Send(in_out_data(:,1:2),size,MPI_DOUBLE_PRECISION,      &\n               down_id,tag,HYDRO_COMM_WORLD,ierr)\n         endif\n         if(up_id .ge. 0 ) then !   receive from upper\n            tag = 41\n            size = nx * 2\n            call MPI_Recv(in_out_data(:,ny-1:ny),size,MPI_DOUBLE_PRECISION, &\n               up_id,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n         endif\n      endif  ! end of block  flag\n   end  subroutine MPP_LAND_UB_COM8\n\n   subroutine calculate_start_p()\n! calculate startx and starty\n      integer :: i,status, ierr, tag\n      integer :: r_s(2)\n      integer ::  t_nx, t_ny\n\n      if(.not. allocated(starty) ) allocate(starty(numprocs),stat = ierr)\n      if(.not. allocated(startx) ) allocate(startx(numprocs),stat = ierr)\n\n      local_startx = int(global_nx/left_right_np) * left_right_p+1\n      local_starty = int(global_ny/up_down_np) * up_down_p+1\n\n!ywold\n      t_nx = 0\n      do i = 1, mod(global_nx,left_right_np)\n         if(left_right_p .gt. i ) then\n            t_nx = t_nx + 1\n         end if\n      end do\n      local_startx = local_startx + t_nx\n\n      t_ny = 0\n      do i = 1, mod(global_ny,up_down_np)\n         if( up_down_p .gt. i) then\n            t_ny = t_ny + 1\n         end if\n      end do\n      local_starty = local_starty + t_ny\n\n\n      if(left_id .lt. 0) local_startx = 1\n      if(down_id .lt. 0) local_starty = 1\n\n\n      if(my_id .eq. IO_id) then\n         startx(my_id+1) = local_startx\n         starty(my_id+1) = local_starty\n      end if\n\n      r_s(1) = local_startx\n      r_s(2) = local_starty\n\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            ! block receive  from other node.\n            if(i.ne.my_id) then\n               tag = 1\n               call MPI_Recv(r_s,2,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               startx(i+1) = r_s(1)\n               starty(i+1) = r_s(2)\n            end if\n         end do\n      else\n         tag =  1\n         call MPI_Send(r_s,2,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n\n! calculate the routing land start x and y\n      local_startx_rt = local_startx*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n      if(local_startx_rt.gt.1) local_startx_rt=local_startx_rt - 1\n      local_starty_rt = local_starty*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n      if(local_starty_rt.gt.1) local_starty_rt=local_starty_rt - 1\n\n      local_endx_rt   = local_startx_rt + local_rt_nx -1\n      local_endy_rt   = local_starty_rt + local_rt_ny -1\n\n   end subroutine calculate_start_p\n\n   subroutine calculate_offset_vectors()\n      !calculate the size and offset vectors needed by scatterv and gatherv\n      integer :: i, ierr, last_offset\n\n      ! first make sure the arrays have been allocated\n      if ( .not. allocated(offset_vectors) ) allocate(offset_vectors(numprocs),stat = ierr)\n      if ( .not. allocated(offset_vectors_rt) ) allocate(offset_vectors_rt(numprocs),stat = ierr)\n      if ( .not. allocated(size_vectors)   ) allocate(size_vectors(numprocs),stat = ierr)\n      if ( .not. allocated(size_vectors_rt)   ) allocate(size_vectors_rt(numprocs),stat = ierr)\n\n      ! calculate the size and offsets using local_nx_size and local_ny_size\n      last_offset = 0\n      do i=1, numprocs\n         size_vectors(i) = local_ny_size(i) * local_nx_size(i)\n         offset_vectors(i) = last_offset\n         last_offset = last_offset + size_vectors(i)\n      end do\n\n      ! calculate the RT size and offsets using local_rt_nx_size and local_rt_ny_size\n      last_offset = 0\n      do i=1, numprocs\n         size_vectors_rt(i) = local_rt_ny_size(i) * local_rt_nx_size(i)\n         offset_vectors_rt(i) = last_offset\n         last_offset = last_offset + size_vectors_rt(i)\n      end do\n\n   end subroutine calculate_offset_vectors\n\n   subroutine decompose_data_real3d (in_buff,out_buff,klevel)\n      implicit none\n      integer:: klevel, k\n      real,dimension(:,:,:) ::  in_buff,out_buff\n      do k = 1, klevel\n         call decompose_data_real(in_buff(:,k,:),out_buff(:,k,:))\n      end do\n   end subroutine decompose_data_real3d\n\n   subroutine decompose_data_real (in_buff,out_buff)\n      ! usage: all of the cpu call this subroutine.\n      ! the IO node will distribute the data to rest of the node.\n      real,intent(in), dimension(:,:) :: in_buff\n      real,intent(out), dimension(:,:), volatile :: out_buff\n      real, dimension(:), allocatable :: send_buff\n      integer tag, i, ii, jj, pos, status, ierr,size\n      integer ibegin,iend,jbegin,jend\n\n      if(my_id .eq. IO_id) then\n\n         ! allocate the buffer to hold data as required by MPI_Scatterv\n         ! be careful with the index range if using array prepared for MPI in fortran (offset_vectors)\n         allocate(send_buff(0: (global_nx*global_ny) -1),stat = ierr)\n\n         ! for each sub region in the global buffer linearize the data and place it in the\n         ! correct send buffer location\n         do i = 1, numprocs\n            ibegin = startx(i)\n            iend   = startx(i)+local_nx_size(i) -1\n            jbegin = starty(i)\n            jend   = starty(i)+local_ny_size(i) -1\n\n            !write (6,*) offset_vectors(i), offset_vectors(i) +size_vectors(i) -1, ibegin, iend, jbegin, jend\n\n            ! we may want use this direct loop to avoid array temps\n            pos = offset_vectors(i)\n            do jj = jbegin, jend\n               do ii = ibegin, iend\n                  send_buff(pos) = in_buff(ii,jj)\n                  pos = pos + 1\n               end do\n            end do\n\n            ! this is much more readable\n            ! send_buff(offset_vectors(i): offset_vectors(i) + size_vectors(i) - 1) = &\n            !    reshape(in_buff(ibegin:iend,jbegin:jend), (/size_vectors(i)/) )\n         end do\n\n         ! send the to each process size_vector(mpi_rank+1) data elements\n         ! and store the results in out_buff\n         call MPI_Scatterv(send_buff, size_vectors, offset_vectors, MPI_REAL, &\n            out_buff, size_vectors(my_id+1), MPI_REAL, IO_id, HYDRO_COMM_WORLD, ierr)\n\n         ! remove the send buffer\n         deallocate(send_buff)\n\n      else\n         ! other processes only need to make MPI_Scatterv call\n         call MPI_Scatterv(send_buff, size_vectors, offset_vectors, MPI_REAL, &\n            out_buff, local_nx*local_ny, MPI_REAL, IO_id, HYDRO_COMM_WORLD, ierr)\n      end if\n\n   end subroutine decompose_data_real\n\n\n   subroutine decompose_data_int (in_buff,out_buff)\n! usage: all of the cpu call this subroutine.\n! the IO node will distribute the data to rest of the node.\n      integer,dimension(:,:) ::  in_buff,out_buff\n      integer tag, i, status, ierr,size\n      integer ibegin,iend,jbegin,jend\n\n      tag = 2\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            ibegin = startx(i+1)\n            iend   = startx(i+1)+local_nx_size(i+1) -1\n            jbegin = starty(i+1)\n            jend   = starty(i+1)+local_ny_size(i+1) -1\n            if(my_id .eq. i) then\n               out_buff=in_buff(ibegin:iend,jbegin:jend)\n            else\n               ! send data to the rest process.\n               size = local_nx_size(i+1)*local_ny_size(i+1)\n               call MPI_Send(in_buff(ibegin:iend,jbegin:jend),size,&\n                  MPI_INTEGER, i,tag,HYDRO_COMM_WORLD,ierr)\n            end if\n         end do\n      else\n         size = local_nx*local_ny\n         call MPI_Recv(out_buff,size,MPI_INTEGER,IO_id, &\n            tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n      end if\n   end subroutine decompose_data_int\n\n   subroutine write_IO_int(in_buff,out_buff)\n! the IO node will receive the data from the rest process.\n      integer,dimension(:,:):: in_buff,  out_buff\n      integer tag, i, status, ierr,size\n      integer ibegin,iend,jbegin,jend\n      if(my_id .ne. IO_id) then\n         size = local_nx*local_ny\n         tag = 2\n         call MPI_Send(in_buff,size,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      else\n         do i = 0, numprocs - 1\n            ibegin = startx(i+1)\n            iend   = startx(i+1)+local_nx_size(i+1) -1\n            jbegin = starty(i+1)\n            jend   = starty(i+1)+local_ny_size(i+1) -1\n            if(i .eq. IO_id) then\n               out_buff(ibegin:iend,jbegin:jend) = in_buff\n            else\n               size = local_nx_size(i+1)*local_ny_size(i+1)\n               tag = 2\n               call MPI_Recv(out_buff(ibegin:iend,jbegin:jend),size,&\n                  MPI_INTEGER,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n            end if\n         end do\n      end if\n   end subroutine write_IO_int\n\n   subroutine write_IO_char_head(in, out, imageHead)\n      !! JLM 2015-11-30\n      !! for i is image number (starting from 0),\n      !! this routine writes\n      !! in(1:imageHead(i+1))\n      !! to\n      !! out( (sum(imageHead(i+1-1))+1) : ((sum(imageHead(i+1-1))+1)+imageHead(i+1)) )\n      !! where out is on the IO node.\n      character(len=*), intent(in),  dimension(:) :: in\n      character(len=*), intent(out), dimension(:) :: out\n      integer,   intent(in),  dimension(:) :: imageHead\n      integer :: tag, i, status, ierr, size\n      integer :: ibegin,iend,jbegin,jend\n      integer :: lenSize, theStart, theEnd\n      tag = 2\n      if(my_id .ne. IO_id) then\n         lenSize = imageHead(my_id+1)*len(in(1))  !! some times necessary for character arrays?\n         if(lenSize .eq. 0) return\n         call MPI_Send(in,lenSize,MPI_CHARACTER,IO_id,tag,HYDRO_COMM_WORLD,ierr)\n      else\n         do i = 0, numprocs-1\n            lenSize  = imageHead(i+1)*len(in(1))  !! necessary?\n            if(lenSize .eq. 0) cycle\n            if(i .eq. 0) then\n               theStart = 1\n            else\n               theStart = sum(imageHead(1:(i+1-1))) +1\n            end if\n            theEnd   = theStart + imageHead(i+1) -1\n            if(i .eq. IO_id) then\n               out(theStart:theEnd) = in(1:imageHead(i+1))\n            else\n               call MPI_Recv(out(theStart:theEnd),lenSize,&\n                  MPI_CHARACTER,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n            end if\n         end do\n      end if\n   end subroutine write_IO_char_head\n\n\n   subroutine write_IO_real3d(in_buff,out_buff,klevel)\n      implicit none\n! the IO node will receive the data from the rest process.\n      integer klevel, k\n      real,dimension(:,:,:):: in_buff, out_buff\n      do k = 1, klevel\n         call write_IO_real(in_buff(:,k,:),out_buff(:,k,:))\n      end do\n   end subroutine write_IO_real3d\n\n   subroutine write_IO_real(in_buff,out_buff)\n! the IO node will receive the data from the rest process.\n      real,dimension(:,:):: in_buff, out_buff\n      integer tag, i, status, ierr,size\n      integer ibegin,iend,jbegin,jend\n      if(my_id .ne. IO_id) then\n         size = local_nx*local_ny\n         tag = 2\n         call MPI_Send(in_buff,size,MPI_REAL, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      else\n         do i = 0, numprocs - 1\n            ibegin = startx(i+1)\n            iend   = startx(i+1)+local_nx_size(i+1) -1\n            jbegin = starty(i+1)\n            jend   = starty(i+1)+local_ny_size(i+1) -1\n            if(i .eq. IO_id) then\n               out_buff(ibegin:iend,jbegin:jend) = in_buff\n            else\n               size = local_nx_size(i+1)*local_ny_size(i+1)\n               tag = 2\n               call MPI_Recv(out_buff(ibegin:iend,jbegin:jend),size,&\n                  MPI_REAL,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n            end if\n         end do\n      end if\n   end subroutine write_IO_real\n\n!   subroutine write_IO_RT_real_prev(in_buff,out_buff)\n! ! the IO node will receive the data from the rest process.\n!       real,dimension(:,:) ::  in_buff, out_buff\n!       integer tag, i, status, ierr,size\n!       integer ibegin,iend,jbegin,jend\n!       if(my_id .ne. IO_id) then\n!          size = local_rt_nx*local_rt_ny\n!          tag = 2\n!          call MPI_Send(in_buff,size,MPI_REAL, IO_id,     &\n!             tag,HYDRO_COMM_WORLD,ierr)\n!       else\n!          do i = 0, numprocs - 1\n!             ibegin = startx(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n!             if(ibegin.gt.1) ibegin=ibegin - 1\n!             iend   = ibegin + local_rt_nx_size(i+1) -1\n!             jbegin = starty(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n!             if(jbegin.gt.1) jbegin=jbegin - 1\n!             jend   = jbegin + local_rt_ny_size(i+1) -1\n!             if(i .eq. IO_id) then\n!                out_buff(ibegin:iend,jbegin:jend) = in_buff\n!             else\n!                size = local_rt_nx_size(i+1)*local_rt_ny_size(i+1)\n!                tag = 2\n!                call MPI_Recv(out_buff(ibegin:iend,jbegin:jend),size,&\n!                   MPI_REAL,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n!             end if\n!          end do\n!       end if\n!    end subroutine write_IO_RT_real_prev\n\n   subroutine write_IO_RT_real (in_buff,out_buff)\n      ! usage: all of the cpu call this subroutine.\n      ! the IO node will recieve data from rest of the node.\n            real,intent(in), dimension(:,:) :: in_buff\n            real,intent(inout), dimension(:,:) :: out_buff\n            real, dimension(:), allocatable :: recv_buff\n            integer tag, i, ii, jj, pos, status, ierr,size\n            integer ibegin,iend,jbegin,jend,rt_startx,rt_starty\n\n            if(my_id .eq. IO_id) then\n\n               ! allocate the buffer to hold data as required by MPI_Scatterv\n               ! (this will be larger than out_buff due to halo cell overlap)\n               ! be careful with the index range if using array prepared for MPI in fortran (offset_vectors)\n               allocate(recv_buff(0: sum(size_vectors_rt) -1),stat = ierr)\n\n               ! recieve from each process size_vector(mpi_rank+1) data elements\n               ! and store the results in recv_buffer\n               call MPI_Gatherv(in_buff, size_vectors_rt(my_id+1), MPI_REAL, &\n                                recv_buff, size_vectors_rt, offset_vectors_rt, MPI_REAL, &\n                                IO_id, HYDRO_COMM_WORLD, ierr)\n\n               ! for each sub region in the recv buffer create a correct shapped array\n               ! and assign it to the output buffer\n               do i = 1, numprocs\n                  ibegin = startx(i)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n                  if (ibegin > 1) ibegin=ibegin - 1\n                  iend   = ibegin + local_rt_nx_size(i) - 1\n                  jbegin = starty(i)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n                  if (jbegin > 1) jbegin=jbegin - 1\n                  jend   = jbegin + local_rt_ny_size(i) - 1\n\n                  ! this is much more readable\n                  out_buff(ibegin:iend,jbegin:jend) = &\n                      reshape(recv_buff(offset_vectors_rt(i): offset_vectors_rt(i) + size_vectors_rt(i) - 1), &\n                      (/local_rt_nx_size(i), local_rt_ny_size(i)/) )\n               end do\n\n               ! remove the send buffer\n               deallocate(recv_buff)\n\n            else\n               ! other processes only need to make MPI_Gatherv call\n               call MPI_Gatherv(in_buff, local_rt_nx*local_rt_ny, MPI_REAL, &\n                                recv_buff, size_vectors_rt, offset_vectors_rt, MPI_REAL, &\n                                IO_id, HYDRO_COMM_WORLD, ierr)\n            end if\n   end subroutine write_IO_RT_real\n\n   subroutine write_IO_RT_int (in_buff,out_buff)\n      ! usage: all of the cpu call this subroutine.\n      ! the IO node will recieve data from rest of the node.\n            integer, intent(in), dimension(:,:) :: in_buff\n            integer, intent(inout), dimension(:,:) :: out_buff\n            integer, dimension(:), allocatable :: recv_buff\n            integer tag, i, ii, jj, pos, status, ierr,size\n            integer ibegin,iend,jbegin,jend,rt_startx,rt_starty\n\n            if(my_id .eq. IO_id) then\n\n               ! allocate the buffer to hold data as required by MPI_Scatterv\n               ! (this will be larger than out_buff due to halo cell overlap)\n               ! be careful with the index range if using array prepared for MPI in fortran (offset_vectors)\n               allocate(recv_buff(0: sum(size_vectors_rt) -1),stat = ierr)\n\n               ! recieve from each process size_vector(mpi_rank+1) data elements\n               ! and store the results in recv_buffer\n               call MPI_Gatherv(in_buff, size_vectors_rt(my_id+1), MPI_REAL, &\n                                recv_buff, size_vectors_rt, offset_vectors_rt, MPI_REAL, &\n                                IO_id, HYDRO_COMM_WORLD, ierr)\n\n               ! for each sub region in the recv buffer create a correct shapped array\n               ! and assign it to the output buffer\n               do i = 1, numprocs\n                  ibegin = startx(i)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n                  if (ibegin > 1) ibegin=ibegin - 1\n                  iend   = ibegin + local_rt_nx_size(i) - 1\n                  jbegin = starty(i)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n                  if (jbegin > 1) jbegin=jbegin - 1\n                  jend   = jbegin + local_rt_ny_size(i) - 1\n\n                  ! this is much more readable\n                  out_buff(ibegin:iend,jbegin:jend) = &\n                      reshape(recv_buff(offset_vectors_rt(i): offset_vectors_rt(i) + size_vectors_rt(i) - 1), &\n                      (/local_rt_nx_size(i), local_rt_ny_size(i)/) )\n               end do\n\n               ! remove the send buffer\n               deallocate(recv_buff)\n\n            else\n               ! other processes only need to make MPI_Gatherv call\n               call MPI_Gatherv(in_buff, local_rt_nx*local_rt_ny, MPI_INTEGER, &\n                                recv_buff, size_vectors_rt, offset_vectors_rt, MPI_INTEGER, &\n                                IO_id, HYDRO_COMM_WORLD, ierr)\n            end if\n   end subroutine write_IO_RT_int\n\n!    subroutine write_IO_RT_int (in_buff,out_buff)\n! ! the IO node will receive the data from the rest process.\n!       integer,intent(in),dimension(:,:) :: in_buff\n!       integer,intent(out),dimension(:,:) ::  out_buff\n!       integer tag, i, status, ierr,size\n!       integer ibegin,iend,jbegin,jend\n!       if(my_id .ne. IO_id) then\n!          size = local_rt_nx*local_rt_ny\n!          tag = 2\n!          call MPI_Send(in_buff,size,MPI_INTEGER, IO_id,     &\n!             tag,HYDRO_COMM_WORLD,ierr)\n!       else\n!          do i = 0, numprocs - 1\n!             ibegin = startx(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n!             if(ibegin.gt.1) ibegin=ibegin - 1\n!             iend   = ibegin + local_rt_nx_size(i+1) -1\n!             jbegin = starty(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n!             if(jbegin.gt.1) jbegin=jbegin - 1\n!             jend   = jbegin + local_rt_ny_size(i+1) -1\n!             if(i .eq. IO_id) then\n!                out_buff(ibegin:iend,jbegin:jend) = in_buff\n!             else\n!                size = local_rt_nx_size(i+1)*local_rt_ny_size(i+1)\n!                tag = 2\n!                call MPI_Recv(out_buff(ibegin:iend,jbegin:jend),size,&\n!                   MPI_INTEGER,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n!             end if\n!          end do\n!       end if\n!    end subroutine write_IO_RT_int\n\n   subroutine write_IO_RT_int8(in_buff,out_buff)\n      ! the IO node will receive the data from the rest process.\n      integer(kind=int64),intent(in),dimension(:,:) :: in_buff\n      integer(kind=int64),intent(out),dimension(:,:) ::  out_buff\n      integer tag, i, status, ierr,size\n      integer ibegin,iend,jbegin,jend\n      if(my_id .ne. IO_id) then\n         size = local_rt_nx*local_rt_ny\n         tag = 2\n         call MPI_Send(in_buff,size,MPI_INTEGER8, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      else\n         do i = 0, numprocs - 1\n            ibegin = startx(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n            if(ibegin.gt.1) ibegin=ibegin - 1\n            iend   = ibegin + local_rt_nx_size(i+1) -1\n            jbegin = starty(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n            if(jbegin.gt.1) jbegin=jbegin - 1\n            jend   = jbegin + local_rt_ny_size(i+1) -1\n            if(i .eq. IO_id) then\n               out_buff(ibegin:iend,jbegin:jend) = in_buff\n            else\n               size = local_rt_nx_size(i+1)*local_rt_ny_size(i+1)\n               tag = 2\n               call MPI_Recv(out_buff(ibegin:iend,jbegin:jend),size,&\n                  MPI_INTEGER8,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n            end if\n         end do\n      end if\n   end subroutine write_IO_RT_int8\n\n   subroutine mpp_land_bcast_log1(inout)\n      logical inout\n      integer ierr\n      call MPI_Bcast(inout,1,MPI_LOGICAL,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_log1\n\n\n   subroutine mpp_land_bcast_int(size,inout)\n      integer size\n      integer inout(size)\n      integer ierr\n      call MPI_Bcast(inout,size,MPI_INTEGER,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_int\n\n   subroutine mpp_land_bcast_int8(size,inout)\n      integer size\n      integer(kind=int64) inout(size)\n      integer ierr\n      call MPI_Bcast(inout,size,MPI_INTEGER8,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_int8\n\n   subroutine mpp_land_bcast_int8_1d(inout)\n      integer len\n      integer(kind=int64) inout(:)\n      integer ierr\n      len = size(inout,1)\n      call MPI_Bcast(inout,len,MPI_INTEGER8,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_int8_1d\n\n   subroutine mpp_land_bcast_int1d(inout)\n      integer len\n      integer inout(:)\n      integer ierr\n      len = size(inout,1)\n      call MPI_Bcast(inout,len,MPI_INTEGER,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_int1d\n\n   subroutine mpp_land_bcast_int1d_root(inout, rootId)\n      integer len\n      integer inout(:)\n      integer, intent(in) :: rootId\n      integer ierr\n      len = size(inout,1)\n      call MPI_Bcast(inout,len,MPI_INTEGER,rootId,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_int1d_root\n\n   subroutine mpp_land_bcast_int1(inout)\n      integer inout\n      integer ierr\n      call MPI_Bcast(inout,1,MPI_INTEGER,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_int1\n\n   subroutine mpp_land_bcast_int1_root(inout, rootId)\n      integer inout\n      integer ierr\n      integer, intent(in) :: rootId\n      call MPI_Bcast(inout,1,MPI_INTEGER,rootId,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_int1_root\n\n   subroutine mpp_land_bcast_logical(inout)\n      logical ::  inout\n      integer ierr\n      call MPI_Bcast(inout,1,MPI_LOGICAL,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_logical\n\n   subroutine mpp_land_bcast_logical_root(inout, rootId)\n      logical ::  inout\n      integer, intent(in) :: rootId\n      integer ierr\n      call MPI_Bcast(inout,1,MPI_LOGICAL,rootId,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_logical_root\n\n   subroutine mpp_land_bcast_real1(inout)\n      real inout\n      integer ierr\n      call MPI_Bcast(inout,1,MPI_REAL,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_real1\n\n   subroutine mpp_land_bcast_real1_double(inout)\n      real*8 inout\n      integer ierr\n      call MPI_Bcast(inout,1,MPI_REAL8, &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_real1_double\n\n   subroutine mpp_land_bcast_real_1d(inout)\n      integer len\n      real inout(:)\n      integer ierr\n      len = size(inout,1)\n      call MPI_Bcast(inout,len,MPI_REAL,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_real_1d\n\n   subroutine mpp_land_bcast_real_1d_root(inout, rootId)\n      integer len\n      real inout(:)\n      integer, intent(in) :: rootId\n      integer ierr\n      len = size(inout,1)\n      call MPI_Bcast(inout,len,MPI_REAL,rootId,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_real_1d_root\n\n   subroutine mpp_land_bcast_real8_1d(inout)\n      integer len\n      real*8 inout(:)\n      integer ierr\n      len = size(inout,1)\n      call MPI_Bcast(inout,len,MPI_DOUBLE,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_real8_1d\n\n   subroutine mpp_land_bcast_real(size1,inout)\n      integer size1\n      ! real inout(size1)\n      real , dimension(:) :: inout\n      integer ierr, len\n      call MPI_Bcast(inout,size1,MPI_REAL,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_real\n\n   subroutine mpp_land_bcast_int2d(inout)\n      integer length1, k,length2\n      integer inout(:,:)\n      integer ierr\n      length1 = size(inout,1)\n      length2 = size(inout,2)\n      do k = 1, length2\n         call MPI_Bcast(inout(:,k),length1,MPI_INTEGER,   &\n            IO_id,HYDRO_COMM_WORLD,ierr)\n      end do\n   end subroutine mpp_land_bcast_int2d\n\n   subroutine mpp_land_bcast_real2(inout)\n      integer length1, k,length2\n      real inout(:,:)\n      integer ierr\n      length1 = size(inout,1)\n      length2 = size(inout,2)\n      do k = 1, length2\n         call MPI_Bcast(inout(:,k),length1,MPI_REAL,   &\n            IO_id,HYDRO_COMM_WORLD,ierr)\n      end do\n   end subroutine mpp_land_bcast_real2\n\n   subroutine mpp_land_bcast_real3d(inout)\n      integer j, k, length1, length2, length3\n      real inout(:,:,:)\n      integer ierr\n      length1 = size(inout,1)\n      length2 = size(inout,2)\n      length3 = size(inout,3)\n      do k = 1, length3\n         do j = 1, length2\n            call MPI_Bcast(inout(:,j,k), length1, MPI_REAL, &\n               IO_id, HYDRO_COMM_WORLD, ierr)\n         end do\n      end do\n   end subroutine mpp_land_bcast_real3d\n\n   subroutine mpp_land_bcast_rd(size,inout)\n      integer size\n      real*8 inout(size)\n      integer ierr\n      call MPI_Bcast(inout,size,MPI_REAL8,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_rd\n\n   subroutine mpp_land_bcast_char(size,inout)\n      integer size\n      character inout(*)\n      integer ierr\n      call MPI_Bcast(inout,size,MPI_CHARACTER,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_char\n\n   subroutine mpp_land_bcast_char_root(size,inout,rootId)\n      integer size\n      character inout(*)\n      integer, intent(in) :: rootId\n      integer ierr\n      call MPI_Bcast(inout,size,MPI_CHARACTER,rootId,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_char_root\n\n   subroutine mpp_land_bcast_char1d(inout)\n      character(len=*) :: inout(:)\n      integer :: lenSize\n      integer :: ierr\n      lenSize = size(inout,1)*len(inout)\n      call MPI_Bcast(inout,lenSize,MPI_CHARACTER,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_char1d\n\n   subroutine mpp_land_bcast_char1d_root(inout,rootId)\n      character(len=*) :: inout(:)\n      integer, intent(in) :: rootId\n      integer :: lenSize\n      integer :: ierr\n      lenSize = size(inout,1)*len(inout)\n      call MPI_Bcast(inout,lenSize,MPI_CHARACTER,rootId,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_char1d_root\n\n   subroutine mpp_land_bcast_char1(inout)\n      integer len\n      character(len=*) inout\n      integer ierr\n      len = LEN_TRIM(inout)\n      call MPI_Bcast(inout,len,MPI_CHARACTER,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine mpp_land_bcast_char1\n\n   subroutine MPP_LAND_COM_REAL(in_out_data,NX,NY,flag)\n!   ### Communicate message on left right and up bottom directions.\n      integer NX,NY\n      integer flag != 99  test only for land model. (replace the boundary).\n      != 1   get the sum of the boundary value.\n      real in_out_data(nx,ny)\n\n      call MPP_LAND_LR_COM(in_out_data,NX,NY,flag)\n      call MPP_LAND_UB_COM(in_out_data,NX,NY,flag)\n\n   end subroutine MPP_LAND_COM_REAL\n\n   subroutine MPP_LAND_COM_REAL8(in_out_data,NX,NY,flag)\n!   ### Communicate message on left right and up bottom directions.\n      integer NX,NY\n      integer flag != 99  test only for land model. (replace the boundary).\n      != 1   get the sum of the boundary value.\n      real*8 in_out_data(nx,ny)\n\n      call MPP_LAND_LR_COM8(in_out_data,NX,NY,flag)\n      call MPP_LAND_UB_COM8(in_out_data,NX,NY,flag)\n\n   end subroutine MPP_LAND_COM_REAL8\n\n   subroutine MPP_LAND_COM_INTEGER(data,NX,NY,flag)\n!   ### Communicate message on left right and up bottom directions.\n      integer NX,NY\n      integer flag != 99  test only for land model. (replace the boundary).\n      != 1   get the sum of the boundary value.\n      integer data(nx,ny)\n      real in_out_data(nx,ny)\n\n      in_out_data = data + 0.0\n      call MPP_LAND_LR_COM(in_out_data,NX,NY,flag)\n      call MPP_LAND_UB_COM(in_out_data,NX,NY,flag)\n      data = in_out_data + 0\n\n   end subroutine MPP_LAND_COM_INTEGER\n\n\n   subroutine MPP_LAND_COM_INTEGER8(data,NX,NY,flag)\n      !   ### Communicate message on left right and up bottom directions.\n      integer NX,NY\n      integer flag != 99  test only for land model. (replace the boundary).\n      != 1   get the sum of the boundary value.\n      integer(kind=int64) data(nx,ny)\n      real in_out_data(nx,ny)\n\n      in_out_data = data + 0.0\n      call MPP_LAND_LR_COM(in_out_data,NX,NY,flag)\n      call MPP_LAND_UB_COM(in_out_data,NX,NY,flag)\n      data = in_out_data + 0\n\n   end subroutine MPP_LAND_COM_INTEGER8\n\n   subroutine read_restart_3(unit,nz,out)\n      integer unit,nz,i\n      real buf3(global_nx,global_ny,nz),&\n         out(local_nx,local_ny,3)\n      if(my_id.eq.IO_id) read(unit) buf3\n      do i = 1,nz\n         call decompose_data_real (buf3(:,:,i),out(:,:,i))\n      end do\n   end subroutine read_restart_3\n\n   subroutine read_restart_2(unit,out)\n      integer unit,ierr2\n      real  buf2(global_nx,global_ny),&\n         out(local_nx,local_ny)\n\n      if(my_id.eq.IO_id) read(unit,IOSTAT=ierr2) buf2\n      call mpp_land_bcast_int1(ierr2)\n      if(ierr2 .ne. 0) return\n\n      call decompose_data_real (buf2,out)\n   end subroutine read_restart_2\n\n   subroutine read_restart_rt_2(unit,out)\n      integer unit,ierr2\n      real  buf2(global_rt_nx,global_rt_ny),&\n         out(local_rt_nx,local_rt_ny)\n\n      if(my_id.eq.IO_id) read(unit,IOSTAT=ierr2) buf2\n      call mpp_land_bcast_int1(ierr2)\n      if(ierr2.ne.0) return\n\n      call decompose_RT_real(buf2,out, &\n         global_rt_nx,global_rt_ny,local_rt_nx,local_rt_ny)\n   end subroutine read_restart_rt_2\n\n   subroutine read_restart_rt_3(unit,nz,out)\n      integer unit,nz,i,ierr2\n      real buf3(global_rt_nx,global_rt_ny,nz),&\n         out(local_rt_nx,local_rt_ny,3)\n\n      if(my_id.eq.IO_id) read(unit,IOSTAT=ierr2) buf3\n      call mpp_land_bcast_int1(ierr2)\n      if(ierr2.ne.0) return\n\n      do i = 1,nz\n         call decompose_RT_real (buf3(:,:,i),out(:,:,i),&\n            global_rt_nx,global_rt_ny,local_rt_nx,local_rt_ny)\n      end do\n   end subroutine read_restart_rt_3\n\n   subroutine write_restart_3(unit,nz,in)\n      integer unit,nz,i\n      real buf3(global_nx,global_ny,nz),&\n         in(local_nx,local_ny,nz)\n      do i = 1,nz\n         call write_IO_real(in(:,:,i),buf3(:,:,i))\n      end do\n      if(my_id.eq.IO_id) write(unit) buf3\n   end subroutine write_restart_3\n\n   subroutine write_restart_2(unit,in)\n      integer unit\n      real  buf2(global_nx,global_ny),&\n         in(local_nx,local_ny)\n      call write_IO_real(in,buf2)\n      if(my_id.eq.IO_id) write(unit) buf2\n   end subroutine write_restart_2\n\n   subroutine write_restart_rt_2(unit,in)\n      integer unit\n      real  buf2(global_rt_nx,global_rt_ny), &\n         in(local_rt_nx,local_rt_ny)\n      call write_IO_RT_real(in,buf2)\n      if(my_id.eq.IO_id) write(unit) buf2\n   end subroutine write_restart_rt_2\n\n   subroutine write_restart_rt_3(unit,nz,in)\n      integer unit,nz,i\n      real buf3(global_rt_nx,global_rt_ny,nz),&\n         in(local_rt_nx,local_rt_ny,nz)\n      do i = 1,nz\n         call write_IO_RT_real(in(:,:,i),buf3(:,:,i))\n      end do\n      if(my_id.eq.IO_id) write(unit) buf3\n   end subroutine write_restart_rt_3\n\n   subroutine decompose_RT_real (in_buff,out_buff,g_nx,g_ny,nx,ny)\n! usage: all of the cpu call this subroutine.\n! the IO node will distribute the data to rest of the node.\n      integer g_nx,g_ny,nx,ny\n      real,intent(in),dimension(:,:) :: in_buff\n      real,intent(out),dimension(:,:) :: out_buff\n      integer tag, i, status, ierr,size\n      integer ibegin,iend,jbegin,jend\n\n      tag = 2\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            ibegin = startx(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n            if(ibegin.gt.1) ibegin=ibegin - 1\n            iend   = ibegin + local_rt_nx_size(i+1) -1\n            jbegin = starty(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n            if(jbegin.gt.1) jbegin=jbegin - 1\n            jend   = jbegin + local_rt_ny_size(i+1) -1\n\n            if(my_id .eq. i) then\n               out_buff=in_buff(ibegin:iend,jbegin:jend)\n            else\n               ! send data to the rest process.\n               size = (iend-ibegin+1)*(jend-jbegin+1)\n               call MPI_Send(in_buff(ibegin:iend,jbegin:jend),size,&\n                  MPI_REAL, i,tag,HYDRO_COMM_WORLD,ierr)\n            end if\n         end do\n      else\n         size = nx*ny\n         call MPI_Recv(out_buff,size,MPI_REAL,IO_id, &\n            tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n      end if\n   end subroutine decompose_RT_real\n\n   subroutine decompose_RT_int (in_buff,out_buff,g_nx,g_ny,nx,ny)\n! usage: all of the cpu call this subroutine.\n! the IO node will distribute the data to rest of the node.\n      integer g_nx,g_ny,nx,ny\n      integer,intent(in),dimension(:,:) ::  in_buff\n      integer,intent(out),dimension(:,:) :: out_buff\n      integer tag, i, status, ierr,size\n      integer ibegin,iend,jbegin,jend\n\n      tag = 2\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            ibegin = startx(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n            if(ibegin.gt.1) ibegin=ibegin - 1\n            iend   = ibegin + local_rt_nx_size(i+1) -1\n            jbegin = starty(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n            if(jbegin.gt.1) jbegin=jbegin - 1\n            jend   = jbegin + local_rt_ny_size(i+1) -1\n\n            if(my_id .eq. i) then\n               out_buff=in_buff(ibegin:iend,jbegin:jend)\n            else\n               ! send data to the rest process.\n               size = (iend-ibegin+1)*(jend-jbegin+1)\n               call MPI_Send(in_buff(ibegin:iend,jbegin:jend),size,&\n                  MPI_INTEGER, i,tag,HYDRO_COMM_WORLD,ierr)\n            end if\n         end do\n      else\n         size = nx*ny\n         call MPI_Recv(out_buff,size,MPI_INTEGER,IO_id, &\n            tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n      end if\n   end subroutine decompose_RT_int\n\n   subroutine decompose_RT_int8 (in_buff,out_buff,g_nx,g_ny,nx,ny)\n      ! usage: all of the cpu call this subroutine.\n      ! the IO node will distribute the data to rest of the node.\n      integer g_nx,g_ny,nx,ny\n      integer(kind=int64),intent(in),dimension(:,:) ::  in_buff\n      integer(kind=int64),intent(out),dimension(:,:) :: out_buff\n      integer tag, i, status, ierr,size\n      integer ibegin,iend,jbegin,jend\n\n      tag = 2\n      if(my_id == IO_id) then\n         do i = 0, numprocs - 1\n            ibegin = startx(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n            if(ibegin > 1) ibegin=ibegin - 1\n            iend   = ibegin + local_rt_nx_size(i+1) -1\n            jbegin = starty(i+1)*rt_AGGFACTRT - (rt_AGGFACTRT-1)\n            if(jbegin > 1) jbegin=jbegin - 1\n            jend   = jbegin + local_rt_ny_size(i+1) -1\n\n            if(my_id == i) then\n               out_buff=in_buff(ibegin:iend,jbegin:jend)\n            else\n               ! send data to the rest process.\n               size = (iend-ibegin+1)*(jend-jbegin+1)\n               call MPI_Send(in_buff(ibegin:iend,jbegin:jend),size,&\n                  MPI_INTEGER8, i,tag,HYDRO_COMM_WORLD,ierr)\n            end if\n         end do\n      else\n         size = nx*ny\n         call MPI_Recv(out_buff,size,MPI_INTEGER8,IO_id, &\n            tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n      end if\n   end subroutine decompose_RT_int8\n\n   subroutine getNX_NY(nprocs,nx,ny)\n      ! calculate the nx and ny based on the total nprocs.\n      integer nprocs, nx, ny, n\n      integer i, j, max\n\n      n = global_nx * global_ny\n      if( nprocs .ge. n ) then\n         call fatal_error_stop(\"Error: number of processes greater than number of cells in the land grid\")\n      end if\n\n      max = nprocs\n      do j = 1, nprocs\n         if( mod(nprocs,j) .eq. 0 ) then\n            i = nprocs/j\n            if( i .le. global_nx ) then\n               if( abs(i-j) .lt. max) then\n                  if( j .le. global_ny ) then\n                     max = abs(i-j)\n                     nx = i\n                     ny = j\n                  end if\n               end if\n            end if\n         end if\n      end do\n   end subroutine getNX_NY\n\n   subroutine pack_global_22(in,   &\n      out,k)\n      integer ix,jx,k,i\n      real out(global_nx,global_ny,k)\n      real  in(local_nx,local_ny,k)\n      do i = 1, k\n         call write_IO_real(in(:,:,i),out(:,:,i))\n      enddo\n   end subroutine pack_global_22\n\n\n   subroutine wrf_LAND_set_INIT(info,total_pe,AGGFACTRT)\n      implicit none\n      integer total_pe\n      integer info(9,total_pe),AGGFACTRT\n      integer :: ierr, status\n      integer i\n\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, my_id, ierr )\n      call MPI_Comm_size( HYDRO_COMM_WORLD, numprocs, ierr )\n\n      if(numprocs .ne. total_pe) then\n         write(6,*) \"FATAL ERROR: In wrf_LAND_set_INIT() - numprocs .ne. total_pe \",numprocs, total_pe\n         call mpp_land_abort()\n      endif\n\n\n!   ### get the neighbors.  -1 means no neighbor.\n      left_id = info(2,my_id+1)\n      right_id = info(3,my_id+1)\n      up_id =   info(4,my_id+1)\n      down_id = info(5,my_id+1)\n      IO_id = 0\n\n      allocate(local_nx_size(numprocs),stat = status)\n      allocate(local_ny_size(numprocs),stat = status)\n      allocate(local_rt_nx_size(numprocs),stat = status)\n      allocate(local_rt_ny_size(numprocs),stat = status)\n      allocate(starty(numprocs),stat = ierr)\n      allocate(startx(numprocs),stat = ierr)\n\n      i = my_id + 1\n      local_nx = info(7,i) - info(6,i) + 1\n      local_ny = info(9,i) - info(8,i) + 1\n\n      global_nx = 0\n      global_ny = 0\n      do i = 1, numprocs\n         global_nx = max(global_nx,info(7,i))\n         global_ny = max(global_ny,info(9,i))\n      enddo\n\n      local_rt_nx = local_nx*AGGFACTRT+2\n      local_rt_ny = local_ny*AGGFACTRT+2\n      if(left_id.lt.0) local_rt_nx = local_rt_nx -1\n      if(right_id.lt.0) local_rt_nx = local_rt_nx -1\n      if(up_id.lt.0) local_rt_ny = local_rt_ny -1\n      if(down_id.lt.0) local_rt_ny = local_rt_ny -1\n\n      global_rt_nx = global_nx*AGGFACTRT\n      global_rt_ny = global_ny*AGGFACTRT\n      rt_AGGFACTRT = AGGFACTRT\n\n      do i =1,numprocs\n         local_nx_size(i) = info(7,i) - info(6,i) + 1\n         local_ny_size(i) = info(9,i) - info(8,i) + 1\n         startx(i)        = info(6,i)\n         starty(i)        = info(8,i)\n\n         local_rt_nx_size(i) = (info(7,i) - info(6,i) + 1)*AGGFACTRT+2\n         local_rt_ny_size(i) = (info(9,i) - info(8,i) + 1 )*AGGFACTRT+2\n         if(info(2,i).lt.0) local_rt_nx_size(i) = local_rt_nx_size(i) -1\n         if(info(3,i).lt.0) local_rt_nx_size(i) = local_rt_nx_size(i) -1\n         if(info(4,i).lt.0) local_rt_ny_size(i) = local_rt_ny_size(i) -1\n         if(info(5,i).lt.0) local_rt_ny_size(i) = local_rt_ny_size(i) -1\n      enddo\n      call calculate_offset_vectors()\n\n   end   subroutine wrf_LAND_set_INIT\n\n   subroutine getMy_global_id()\n      integer ierr\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, my_id, ierr )\n   end subroutine getMy_global_id\n\n   subroutine MPP_CHANNEL_COM_REAL(Link_location,ix,jy,Link_V,size,flag)\n      ! communicate the data for channel routine.\n      implicit none\n      integer ix,jy,size\n      integer(kind=int64) Link_location(ix,jy)\n      integer i,j, flag\n      real Link_V(size), tmp_inout(ix,jy)\n\n      tmp_inout = -999\n\n      if(size .eq. 0) then\n         tmp_inout = -999\n      else\n\n         !     map the Link_V data to tmp_inout(ix,jy)\n         do i = 1,ix\n            if(Link_location(i,1) .gt. 0) &\n               tmp_inout(i,1) = Link_V(Link_location(i,1))\n            if(Link_location(i,2) .gt. 0) &\n               tmp_inout(i,2) = Link_V(Link_location(i,2))\n            if(Link_location(i,jy-1) .gt. 0) &\n               tmp_inout(i,jy-1) = Link_V(Link_location(i,jy-1))\n            if(Link_location(i,jy) .gt. 0) &\n               tmp_inout(i,jy) = Link_V(Link_location(i,jy))\n         enddo\n         do j = 1,jy\n            if(Link_location(1,j) .gt. 0) &\n               tmp_inout(1,j) = Link_V(Link_location(1,j))\n            if(Link_location(2,j) .gt. 0) &\n               tmp_inout(2,j) = Link_V(Link_location(2,j))\n            if(Link_location(ix-1,j) .gt. 0) &\n               tmp_inout(ix-1,j) = Link_V(Link_location(ix-1,j))\n            if(Link_location(ix,j) .gt. 0) &\n               tmp_inout(ix,j) = Link_V(Link_location(ix,j))\n         enddo\n      endif\n\n!   commu nicate tmp_inout\n      call MPP_LAND_COM_REAL(tmp_inout, ix,jy,flag)\n\n!map the data back to Link_V\n      if(size .eq. 0) return\n      do j = 1,jy\n         if( (Link_location(1,j) .gt. 0) .and. (tmp_inout(1,j) .ne. -999) ) &\n            Link_V(Link_location(1,j)) = tmp_inout(1,j)\n         if((Link_location(2,j) .gt. 0) .and. (tmp_inout(2,j) .ne. -999) ) &\n            Link_V(Link_location(2,j)) = tmp_inout(2,j)\n         if((Link_location(ix-1,j) .gt. 0) .and. (tmp_inout(ix-1,j) .ne. -999)) &\n            Link_V(Link_location(ix-1,j)) = tmp_inout(ix-1,j)\n         if((Link_location(ix,j) .gt. 0) .and. (tmp_inout(ix,j) .ne. -999) )&\n            Link_V(Link_location(ix,j)) = tmp_inout(ix,j)\n      enddo\n      do i = 1,ix\n         if((Link_location(i,1) .gt. 0) .and. (tmp_inout(i,1) .ne. -999) )&\n            Link_V(Link_location(i,1)) = tmp_inout(i,1)\n         if( (Link_location(i,2) .gt. 0) .and. (tmp_inout(i,2) .ne. -999) )&\n            Link_V(Link_location(i,2)) = tmp_inout(i,2)\n         if((Link_location(i,jy-1) .gt. 0) .and. (tmp_inout(i,jy-1) .ne. -999) ) &\n            Link_V(Link_location(i,jy-1)) = tmp_inout(i,jy-1)\n         if((Link_location(i,jy) .gt. 0) .and. (tmp_inout(i,jy) .ne. -999) ) &\n            Link_V(Link_location(i,jy)) = tmp_inout(i,jy)\n      enddo\n   end subroutine MPP_CHANNEL_COM_REAL\n\n\n   subroutine MPP_CHANNEL_COM_REAL8(Link_location,ix,jy,Link_V,size,flag)\n      ! communicate the data for channel routine.\n      implicit none\n      integer ix,jy,size\n      integer(kind=int64) Link_location(ix,jy)\n      integer i,j, flag\n      real*8 ::  Link_V(size), tmp_inout(ix,jy)\n\n      tmp_inout = -999\n\n      if(size .eq. 0) then\n         tmp_inout = -999\n      else\n\n         !     map the Link_V data to tmp_inout(ix,jy)\n         do i = 1,ix\n            if(Link_location(i,1) .gt. 0) &\n               tmp_inout(i,1) = Link_V(Link_location(i,1))\n            if(Link_location(i,2) .gt. 0) &\n               tmp_inout(i,2) = Link_V(Link_location(i,2))\n            if(Link_location(i,jy-1) .gt. 0) &\n               tmp_inout(i,jy-1) = Link_V(Link_location(i,jy-1))\n            if(Link_location(i,jy) .gt. 0) &\n               tmp_inout(i,jy) = Link_V(Link_location(i,jy))\n         enddo\n         do j = 1,jy\n            if(Link_location(1,j) .gt. 0) &\n               tmp_inout(1,j) = Link_V(Link_location(1,j))\n            if(Link_location(2,j) .gt. 0) &\n               tmp_inout(2,j) = Link_V(Link_location(2,j))\n            if(Link_location(ix-1,j) .gt. 0) &\n               tmp_inout(ix-1,j) = Link_V(Link_location(ix-1,j))\n            if(Link_location(ix,j) .gt. 0) &\n               tmp_inout(ix,j) = Link_V(Link_location(ix,j))\n         enddo\n      endif\n\n!   commu nicate tmp_inout\n      call MPP_LAND_COM_REAL8(tmp_inout, ix,jy,flag)\n\n!map the data back to Link_V\n      if(size .eq. 0) return\n      do j = 1,jy\n         if( (Link_location(1,j) .gt. 0) .and. (tmp_inout(1,j) .ne. -999) ) &\n            Link_V(Link_location(1,j)) = tmp_inout(1,j)\n         if((Link_location(2,j) .gt. 0) .and. (tmp_inout(2,j) .ne. -999) ) &\n            Link_V(Link_location(2,j)) = tmp_inout(2,j)\n         if((Link_location(ix-1,j) .gt. 0) .and. (tmp_inout(ix-1,j) .ne. -999)) &\n            Link_V(Link_location(ix-1,j)) = tmp_inout(ix-1,j)\n         if((Link_location(ix,j) .gt. 0) .and. (tmp_inout(ix,j) .ne. -999) )&\n            Link_V(Link_location(ix,j)) = tmp_inout(ix,j)\n      enddo\n      do i = 1,ix\n         if((Link_location(i,1) .gt. 0) .and. (tmp_inout(i,1) .ne. -999) )&\n            Link_V(Link_location(i,1)) = tmp_inout(i,1)\n         if( (Link_location(i,2) .gt. 0) .and. (tmp_inout(i,2) .ne. -999) )&\n            Link_V(Link_location(i,2)) = tmp_inout(i,2)\n         if((Link_location(i,jy-1) .gt. 0) .and. (tmp_inout(i,jy-1) .ne. -999) ) &\n            Link_V(Link_location(i,jy-1)) = tmp_inout(i,jy-1)\n         if((Link_location(i,jy) .gt. 0) .and. (tmp_inout(i,jy) .ne. -999) ) &\n            Link_V(Link_location(i,jy)) = tmp_inout(i,jy)\n      enddo\n   end subroutine MPP_CHANNEL_COM_REAL8\n\n   subroutine MPP_CHANNEL_COM_INT(Link_location,ix,jy,Link_V,size,flag)\n      ! communicate the data for channel routine.\n      implicit none\n      integer ix,jy,size\n      integer(kind=int64) Link_location(ix,jy)\n      integer i,j, flag\n      integer(kind=int64) Link_V(size), tmp_inout(ix,jy)\n\n      if(size .eq. 0) then\n         tmp_inout = -999\n      else\n\n         !     map the Link_V data to tmp_inout(ix,jy)\n         do i = 1,ix\n            if(Link_location(i,1) .gt. 0) &\n               tmp_inout(i,1) = Link_V(Link_location(i,1))\n            if(Link_location(i,2) .gt. 0) &\n               tmp_inout(i,2) = Link_V(Link_location(i,2))\n            if(Link_location(i,jy-1) .gt. 0) &\n               tmp_inout(i,jy-1) = Link_V(Link_location(i,jy-1))\n            if(Link_location(i,jy) .gt. 0) &\n               tmp_inout(i,jy) = Link_V(Link_location(i,jy))\n         enddo\n         do j = 1,jy\n            if(Link_location(1,j) .gt. 0) &\n               tmp_inout(1,j) = Link_V(Link_location(1,j))\n            if(Link_location(2,j) .gt. 0) &\n               tmp_inout(2,j) = Link_V(Link_location(2,j))\n            if(Link_location(ix-1,j) .gt. 0) &\n               tmp_inout(ix-1,j) = Link_V(Link_location(ix-1,j))\n            if(Link_location(ix,j) .gt. 0) &\n               tmp_inout(ix,j) = Link_V(Link_location(ix,j))\n         enddo\n      endif\n\n\n\n!   commu nicate tmp_inout\n      call MPP_LAND_COM_INTEGER8(tmp_inout, ix,jy,flag)\n\n!map the data back to Link_V\n      if(size .eq. 0) return\n      do j = 1,jy\n         if( (Link_location(1,j) .gt. 0) .and. (tmp_inout(1,j) .ne. -999) ) &\n            Link_V(Link_location(1,j)) = tmp_inout(1,j)\n         if((Link_location(2,j) .gt. 0) .and. (tmp_inout(2,j) .ne. -999) ) &\n            Link_V(Link_location(2,j)) = tmp_inout(2,j)\n         if((Link_location(ix-1,j) .gt. 0) .and. (tmp_inout(ix-1,j) .ne. -999)) &\n            Link_V(Link_location(ix-1,j)) = tmp_inout(ix-1,j)\n         if((Link_location(ix,j) .gt. 0) .and. (tmp_inout(ix,j) .ne. -999) )&\n            Link_V(Link_location(ix,j)) = tmp_inout(ix,j)\n      enddo\n      do i = 1,ix\n         if((Link_location(i,1) .gt. 0) .and. (tmp_inout(i,1) .ne. -999) )&\n            Link_V(Link_location(i,1)) = tmp_inout(i,1)\n         if( (Link_location(i,2) .gt. 0) .and. (tmp_inout(i,2) .ne. -999) )&\n            Link_V(Link_location(i,2)) = tmp_inout(i,2)\n         if((Link_location(i,jy-1) .gt. 0) .and. (tmp_inout(i,jy-1) .ne. -999) ) &\n            Link_V(Link_location(i,jy-1)) = tmp_inout(i,jy-1)\n         if((Link_location(i,jy) .gt. 0) .and. (tmp_inout(i,jy) .ne. -999) ) &\n            Link_V(Link_location(i,jy)) = tmp_inout(i,jy)\n      enddo\n   end subroutine MPP_CHANNEL_COM_INT\n\n\n   subroutine print_2(unit,in,fm)\n      integer unit\n      character(len=*) fm\n      real  buf2(global_nx,global_ny),&\n         in(local_nx,local_ny)\n      call write_IO_real(in,buf2)\n      if(my_id.eq.IO_id) write(unit,*) buf2\n   end subroutine print_2\n\n   subroutine print_rt_2(unit,in)\n      integer unit\n      real  buf2(global_nx,global_ny),&\n         in(local_nx,local_ny)\n      call write_IO_real(in,buf2)\n      if(my_id.eq.IO_id) write(unit,*) buf2\n   end subroutine print_rt_2\n\n   subroutine mpp_land_max_int1(v)\n      implicit none\n      integer v, r1, max\n      integer i, ierr, tag\n      if(my_id .eq. IO_id) then\n         max = v\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               !block receive  from other node.\n               tag = 101\n               call MPI_Recv(r1,1,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               if(max <= r1) max = r1\n            end if\n         end do\n      else\n         tag =  101\n         call MPI_Send(v,1,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n      call mpp_land_bcast_int1(max)\n      v = max\n   end subroutine mpp_land_max_int1\n\n   subroutine mpp_land_max_real1(v)\n      implicit none\n      real v, r1, max\n      integer i, ierr, tag\n      if(my_id .eq. IO_id) then\n         max = v\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               !block receive  from other node.\n               tag = 101\n               call MPI_Recv(r1,1,MPI_REAL,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               if(max <= r1) max = r1\n            end if\n         end do\n      else\n         tag =  101\n         call MPI_Send(v,1,MPI_REAL, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n      call mpp_land_bcast_real1(max)\n      v = max\n   end subroutine mpp_land_max_real1\n\n   subroutine mpp_same_int1(v)\n      implicit none\n      integer v,r1\n      integer i, ierr, tag\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               !block receive  from other node.\n               tag = 109\n               call MPI_Recv(r1,1,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               if(v .ne. r1) v = -99\n            end if\n         end do\n      else\n         tag =  109\n         call MPI_Send(v,1,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n      call mpp_land_bcast_int1(v)\n   end subroutine mpp_same_int1\n\n\n\n   subroutine write_chanel_real(v,map_l2g,gnlinks,nlinks,g_v)\n      implicit none\n      integer  gnlinks,nlinks, map_l2g(nlinks)\n      real recv(nlinks), v(nlinks)\n      ! real g_v(gnlinks), tmp_v(gnlinks)\n      integer i, ierr, tag, k\n      integer length, node, message_len\n      integer,allocatable,dimension(:) :: tmp_map\n      real, allocatable, dimension(:) :: tmp_v\n      real, dimension(:) :: g_v\n\n      if(my_id .eq. io_id) then\n         allocate(tmp_map(gnlinks))\n         allocate(tmp_v(gnlinks))\n         if(nlinks .le. 0) then\n            tmp_map = -999\n         else\n            tmp_map(1:nlinks) = map_l2g(1:nlinks)\n         endif\n      else\n         allocate(tmp_map(1))\n         allocate(tmp_v(1))\n      endif\n\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            message_len = mpp_nlinks(i+1)\n            if(i .ne. my_id) then\n               !block receive  from other node.\n\n               tag = 109\n               call MPI_Recv(tmp_map(1:message_len),message_len,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               tag = 119\n\n               call MPI_Recv(tmp_v(1:message_len),message_len,MPI_REAL,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n\n               do k = 1,message_len\n                  node = tmp_map(k)\n                  if(node .gt. 0) then\n                     g_v(node) = tmp_v(k)\n                  else\n#ifdef HYDRO_D\n                     write(6,*) \"Maping infor k=\",k,\" node=\", node\n#endif\n                  endif\n               enddo\n            else\n               do k = 1,nlinks\n                  node = map_l2g(k)\n                  if(node .gt. 0) then\n                     g_v(node) = v(k)\n                  else\n#ifdef HYDRO_D\n                     write(6,*) \"local Maping infor k=\",k,\" node=\",node\n#endif\n                  endif\n               enddo\n            end if\n\n         end do\n      else\n         tag =  109\n         call MPI_Send(map_l2g,nlinks,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n         tag = 119\n         call MPI_Send(v,nlinks,MPI_REAL,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n\n      end if\n      if(allocated(tmp_map)) deallocate(tmp_map)\n      if(allocated(tmp_v)) deallocate(tmp_v)\n   end subroutine write_chanel_real\n\n   subroutine write_chanel_int(v,map_l2g,gnlinks,nlinks,g_v)\n      implicit none\n      integer gnlinks,nlinks, map_l2g(nlinks)\n      integer ::  recv(nlinks), v(nlinks)\n      integer, allocatable, dimension(:) :: tmp_map , tmp_v\n      integer, dimension(:) :: g_v\n      integer i, ierr, tag, k\n      integer length, node, message_len\n\n      if(my_id .eq. io_id) then\n         allocate(tmp_map(gnlinks))\n         allocate(tmp_v(gnlinks))\n         if(nlinks .le. 0) then\n            tmp_map = -999\n         else\n            tmp_map(1:nlinks) = map_l2g(1:nlinks)\n         endif\n      else\n         allocate(tmp_map(1))\n         allocate(tmp_v(1))\n      endif\n\n\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            message_len = mpp_nlinks(i+1)\n            if(i .ne. my_id) then\n               !block receive  from other node.\n\n               tag = 109\n               call MPI_Recv(tmp_map(1:message_len),message_len,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               tag = 119\n\n               call MPI_Recv(tmp_v(1:message_len),message_len,MPI_INTEGER,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n\n               do k = 1,message_len\n                  if(tmp_map(k) .gt. 0) then\n                     node = tmp_map(k)\n                     g_v(node) = tmp_v(k)\n                  else\n#ifdef HYDRO_D\n                     write(6,*) \"Maping infor k=\",k,\" node=\",tmp_v(k)\n#endif\n                  endif\n               enddo\n            else\n               do k = 1,nlinks\n                  if(map_l2g(k) .gt. 0) then\n                     node = map_l2g(k)\n                     g_v(node) = v(k)\n                  else\n#ifdef HYDRO_D\n                     write(6,*) \"Maping infor k=\",k,\" node=\",map_l2g(k)\n#endif\n                  endif\n               enddo\n            end if\n\n         end do\n      else\n         tag =  109\n         call MPI_Send(map_l2g,nlinks,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n         tag = 119\n         call MPI_Send(v,nlinks,MPI_INTEGER,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n      if(allocated(tmp_map)) deallocate(tmp_map)\n      if(allocated(tmp_v)) deallocate(tmp_v)\n   end subroutine write_chanel_int\n\n   subroutine write_chanel_int8(v,map_l2g,gnlinks,nlinks,g_v)\n      implicit none\n      integer gnlinks,nlinks, map_l2g(nlinks)\n      integer(kind=int64) ::  recv(nlinks), v(nlinks)\n      integer(kind=int64), allocatable, dimension(:) :: tmp_v\n      integer, allocatable, dimension(:) :: tmp_map\n      integer(kind=int64), dimension(:) :: g_v\n      integer i, ierr, tag, k\n      integer length, node, message_len\n\n      if(my_id .eq. io_id) then\n         allocate(tmp_map(gnlinks))\n         allocate(tmp_v(gnlinks))\n         if(nlinks .le. 0) then\n            tmp_map = -999\n         else\n            tmp_map(1:nlinks) = map_l2g(1:nlinks)\n         endif\n      else\n         allocate(tmp_map(1))\n         allocate(tmp_v(1))\n      endif\n\n\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            message_len = mpp_nlinks(i+1)\n            if(i .ne. my_id) then\n               !block receive  from other node.\n\n               tag = 109\n               call MPI_Recv(tmp_map(1:message_len),message_len,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               tag = 119\n               call MPI_Recv(tmp_v(1:message_len),message_len,MPI_INTEGER8,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n\n               do k = 1,message_len\n                  if(tmp_map(k) .gt. 0) then\n                     node = tmp_map(k)\n                     g_v(node) = tmp_v(k)\n                  else\n#ifdef HYDRO_D\n                     write(6,*) \"Maping infor k=\",k,\" node=\",tmp_v(k)\n#endif\n                  endif\n               enddo\n            else\n               do k = 1,nlinks\n                  if(map_l2g(k) .gt. 0) then\n                     node = map_l2g(k)\n                     g_v(node) = v(k)\n                  else\n#ifdef HYDRO_D\n                     write(6,*) \"Maping infor k=\",k,\" node=\",map_l2g(k)\n#endif\n                  endif\n               enddo\n            end if\n\n         end do\n      else\n         tag =  109\n         call MPI_Send(map_l2g,nlinks,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n         tag = 119\n         call MPI_Send(v,nlinks,MPI_INTEGER8,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n      if(allocated(tmp_map)) deallocate(tmp_map)\n      if(allocated(tmp_v)) deallocate(tmp_v)\n   end subroutine write_chanel_int8\n\n\n   subroutine write_lake_real(v,nodelist_in,nlakes)\n      implicit none\n      real recv(nlakes), v(nlakes)\n      integer nodelist(nlakes), nlakes, nodelist_in(nlakes)\n      integer i, ierr, tag, k\n      integer length, node\n\n      nodelist = nodelist_in\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               !block receive  from other node.\n               tag = 129\n               call MPI_Recv(nodelist,nlakes,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               tag = 139\n               call MPI_Recv(recv(:),nlakes,MPI_REAL,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n\n               do k = 1,nlakes\n                  if(nodelist(k) .gt. -99) then\n                     node = nodelist(k)\n                     v(node) = recv(node)\n                  endif\n               enddo\n            end if\n         end do\n      else\n         tag =  129\n         call MPI_Send(nodelist,nlakes,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n         tag = 139\n         call MPI_Send(v,nlakes,MPI_REAL,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n   end subroutine write_lake_real\n\n\n   subroutine write_lake_char(v,nodelist_in,nlakes)\n      implicit none\n      character(len=256) recv(nlakes), v(nlakes)\n      integer nodelist(nlakes), nlakes, nodelist_in(nlakes)\n      integer i, ierr, tag, k, in_len\n      integer length, node\n\n      in_len = size(v, 1)*len(v)\n\n      nodelist = nodelist_in\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               !block receive  from other node.\n               tag = 129\n               call MPI_Recv(nodelist,nlakes,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               tag = 139\n               call MPI_Recv(recv(:),in_len,MPI_CHARACTER,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n\n               do k = 1,nlakes\n                  if(nodelist(k) .gt. -99) then\n                     node = nodelist(k)\n                     v(node) = recv(node)\n                  endif\n               enddo\n            end if\n         end do\n      else\n         tag =  129\n         call MPI_Send(nodelist,nlakes,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n         tag = 139\n         call MPI_Send(v,in_len,MPI_CHARACTER,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n   end subroutine write_lake_char\n\n\n   subroutine read_rst_crt_r(unit,out,size)\n      implicit none\n      integer unit, size, ierr,ierr2\n      real  out(size),out1(size)\n      if(my_id.eq.IO_id) then\n         read(unit,IOSTAT=ierr2,end=99) out1\n         if(ierr2.eq.0) out=out1\n      endif\n99    continue\n      call mpp_land_bcast_int1(ierr2)\n      if(ierr2 .ne. 0) return\n      call MPI_Bcast(out,size,MPI_REAL,   &\n         IO_id,HYDRO_COMM_WORLD,ierr)\n   end subroutine read_rst_crt_r\n\n   subroutine write_rst_crt_r(unit,cd,map_l2g,gnlinks,nlinks)\n      integer :: unit,gnlinks,nlinks,map_l2g(nlinks)\n      real cd(nlinks)\n      real g_cd (gnlinks)\n      call write_chanel_real(cd,map_l2g,gnlinks,nlinks, g_cd)\n      write(unit) g_cd\n   end subroutine write_rst_crt_r\n\n   subroutine sum_int1d(vin,nsize)\n      implicit none\n      integer nsize,i,j,tag,ierr\n      integer, dimension(nsize):: vin,recv\n      tag = 319\n      if(nsize .le. 0) return\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               call MPI_Recv(recv,nsize,MPI_INTEGER,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               vin(:) = vin(:) + recv(:)\n            endif\n         end do\n      else\n         call MPI_Send(vin,nsize,MPI_INTEGER,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      endif\n      call mpp_land_bcast_int1d(vin)\n   end subroutine sum_int1d\n\n   subroutine combine_int1d(vin,nsize, flag)\n      implicit none\n      integer nsize,i,j,tag,ierr, flag, k\n      integer, dimension(nsize):: vin,recv\n      tag = 319\n      if(nsize .le. 0) return\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               call MPI_Recv(recv,nsize,MPI_INTEGER,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               do k = 1, nsize\n                  if(recv(k) .ne. flag) then\n                     vin(k) = recv(k)\n                  endif\n               enddo\n            endif\n         end do\n      else\n         call MPI_Send(vin,nsize,MPI_INTEGER,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      endif\n      call mpp_land_bcast_int1d(vin)\n   end subroutine combine_int1d\n\n   subroutine combine_int8_1d(vin,nsize, flag)\n      implicit none\n      integer nsize,i,j,tag,ierr, flag, k\n      integer(kind=int64), dimension(nsize):: vin,recv\n      tag = 319\n      if(nsize .le. 0) return\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               call MPI_Recv(recv,nsize,MPI_INTEGER8,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               do k = 1, nsize\n                  if(recv(k) .ne. flag) then\n                     vin(k) = recv(k)\n                  endif\n               enddo\n            endif\n         end do\n      else\n         call MPI_Send(vin,nsize,MPI_INTEGER8,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      endif\n      call mpp_land_bcast_int8_1d(vin)\n   end subroutine combine_int8_1d\n\n   subroutine sum_real1d(vin,nsize)\n      implicit none\n      integer  :: nsize\n      real,dimension(nsize) :: vin\n      real*8,dimension(nsize) :: vin8\n      vin8=vin\n      call sum_real8(vin8,nsize)\n      vin=vin8\n   end subroutine sum_real1d\n\n   subroutine sum_real8(vin,nsize)\n      implicit none\n      integer nsize,i,j,tag,ierr\n      real*8, dimension(nsize):: vin,recv\n      real, dimension(nsize):: v\n      tag = 319\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               call MPI_Recv(recv,nsize,MPI_DOUBLE_PRECISION,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               vin(:) = vin(:) + recv(:)\n            endif\n         end do\n         v = vin\n      else\n         call MPI_Send(vin,nsize,MPI_DOUBLE_PRECISION,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      endif\n      call mpp_land_bcast_real(nsize,v)\n      vin = v\n   end subroutine sum_real8\n\n!  subroutine get_globalDim(ix,g_ix)\n!     implicit none\n!     integer ix,g_ix, ierr\n!\n!     if ( my_id .eq. IO_id ) then\n!           g_ix = ix\n!        call MPI_Reduce( MPI_IN_PLACE, g_ix, 4, MPI_INTEGER, &\n!             MPI_SUM, 0, HYDRO_COMM_WORLD, ierr )\n!     else\n!        call MPI_Reduce( ix,       0,      4, MPI_INTEGER, &\n!             MPI_SUM,  0, HYDRO_COMM_WORLD, ierr )\n!     endif\n!      call mpp_land_bcast_int1(g_ix)\n!\n!\n!  end subroutine get_globalDim\n\n   subroutine gather_1d_real_tmp(vl,s_in,e_in,vg,sg)\n      integer sg, s,e, size, s_in, e_in\n      integer index_s(2)\n      integer tag, ierr,i\n!   s: start index, e: end index\n      real  vl(e_in-s_in+1), vg(sg)\n      s = s_in\n      e = e_in\n\n      if(my_id .eq. IO_id) then\n         vg(s:e) = vl\n      end if\n\n      index_s(1) = s\n      index_s(2) = e\n      size = e - s + 1\n\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               !block receive  from other node.\n               tag = 202\n               call MPI_Recv(index_s,2,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n\n               tag = 203\n               e = index_s(2)\n               s = index_s(1)\n               size = e - s + 1\n               call MPI_Recv(vg(s:e),size,MPI_REAL,  &\n                  i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n            endif\n         end do\n      else\n         tag =  202\n         call MPI_Send(index_s,2,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n\n         tag =  203\n         call MPI_Send(vl,size,MPI_REAL,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      end if\n\n   end  subroutine gather_1d_real_tmp\n\n   subroutine sum_real1(inout)\n      implicit none\n      real:: inout, send\n      integer :: ierr\n      send = inout\n      call MPI_Allreduce(send,inout,1,MPI_REAL,MPI_SUM,HYDRO_COMM_WORLD,ierr)\n   end subroutine sum_real1\n\n   subroutine sum_double(inout)\n      implicit none\n      real*8:: inout, send\n      integer :: ierr\n      send = inout\n      !yw call MPI_Allreduce(send,inout,1,MPI_DOUBLE,MPI_SUM,HYDRO_COMM_WORLD,ierr)\n      call MPI_Allreduce(send,inout,1,MPI_DOUBLE_PRECISION,MPI_SUM,HYDRO_COMM_WORLD,ierr)\n   end subroutine sum_double\n\n   subroutine mpp_chrt_nlinks_collect(nlinks)\n      ! collect the nlinks\n      implicit none\n      integer :: nlinks\n      integer :: i, ierr, status, tag\n      allocate(mpp_nlinks(numprocs),stat = status)\n      tag = 138\n      mpp_nlinks = 0\n      if(my_id .eq. IO_id) then\n         do i = 0,numprocs -1\n            if(i .ne. my_id) then\n               call MPI_Recv(mpp_nlinks(i+1),1,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n            else\n               mpp_nlinks(i+1) = 0\n            end if\n         end do\n      else\n         call MPI_Send(nlinks,1,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      endif\n\n\n   end subroutine mpp_chrt_nlinks_collect\n\n   subroutine  getLocalXY(ix,jx,startx,starty,endx,endy)\n!!! this is for NoahMP only\n      implicit none\n      integer:: ix,jx,startx,starty,endx,endy\n      startx = local_startx\n      starty = local_starty\n      endx = startx + ix -1\n      endy = starty + jx -1\n   end subroutine getLocalXY\n\n   subroutine check_landreal1(unit, inVar)\n      implicit none\n      integer :: unit\n      real :: inVar\n      if(my_id .eq. IO_id) then\n         write(unit,*) inVar\n         call flush(unit)\n      endif\n   end subroutine check_landreal1\n\n   subroutine check_landreal1d(unit, inVar)\n      implicit none\n      integer :: unit\n      real :: inVar(:)\n      if(my_id .eq. IO_id) then\n         write(unit,*) inVar\n         call flush(unit)\n      endif\n   end subroutine check_landreal1d\n   subroutine check_landreal2d(unit, inVar)\n      implicit none\n      integer :: unit\n      real :: inVar(:,:)\n      real :: g_var(global_nx,global_ny)\n      call write_io_real(inVar,g_var)\n      if(my_id .eq. IO_id) then\n         write(unit,*) g_var\n         call flush(unit)\n      endif\n   end subroutine check_landreal2d\n\n   subroutine check_landreal3d(unit, inVar)\n      implicit none\n      integer :: unit, k, klevel\n      real :: inVar(:,:,:)\n      real :: g_var(global_nx,global_ny)\n      klevel = size(inVar,2)\n      do k = 1, klevel\n         call write_io_real(inVar(:,k,:),g_var)\n         if(my_id .eq. IO_id) then\n            write(unit,*) g_var\n            call flush(unit)\n         endif\n      end do\n   end subroutine check_landreal3d\n\n   subroutine mpp_collect_1d_int(nlinks,vinout)\n      ! collect the nlinks\n      implicit none\n      integer :: nlinks\n      integer :: i, ierr, status, tag\n      integer, dimension(nlinks) :: vinout\n      integer, dimension(nlinks) :: buf\n      tag = 139\n      if(my_id .eq. IO_id) then\n         do i = 0,numprocs -1\n            if(i .ne. my_id) then\n               call MPI_Recv(buf,nlinks,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               vinout = vinout + buf\n            end if\n         end do\n      else\n         call MPI_Send(vinout,nlinks,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      endif\n      call mpp_land_bcast_int1d(vinout)\n\n   end subroutine mpp_collect_1d_int\n\n   subroutine mpp_collect_1d_int_mem(nlinks,vinout)\n      ! consider the memory and big size data transport\n      ! collect the nlinks\n      implicit none\n      integer :: nlinks\n      integer :: i, ierr, status, tag\n      integer, dimension(nlinks) :: vinout, tmpIn\n      integer, dimension(nlinks) :: buf\n      integer :: lsize, k,m\n      integer, allocatable, dimension(:) :: tmpBuf\n\n      if(my_id .eq. IO_id) then\n         allocate (tmpBuf(nlinks))\n         do i = 0,numprocs -1\n            if(i .ne. my_id) then\n               tag = 120\n               call MPI_Recv(lsize,1,MPI_INTEGER,i, &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               if(lsize .gt. 0) then\n                  tag = 121\n                  call MPI_Recv(tmpBuf(1:lsize),lsize,MPI_INTEGER,i, &\n                     tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n                  do k = 1, lsize\n                     m = tmpBuf(k)\n                     vinout(m) = 1\n                  end do\n               endif\n            end if\n         end do\n         if(allocated(tmpBuf)) deallocate(tmpBuf)\n      else\n         lsize = 0\n         do k = 1, nlinks\n            if(vinout(k) .gt. 0) then\n               lsize = lsize + 1\n               tmpIn(lsize) = k\n            end if\n         end do\n         tag = 120\n         call MPI_Send(lsize,1,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n         if(lsize .gt. 0) then\n            tag = 121\n            call MPI_Send(tmpIn(1:lsize),lsize,MPI_INTEGER, IO_id,     &\n               tag,HYDRO_COMM_WORLD,ierr)\n         endif\n      endif\n      call mpp_land_bcast_int1d(vinout)\n\n   end subroutine mpp_collect_1d_int_mem\n\n   subroutine updateLake_seqInt(in,nsize,in0)\n      implicit none\n      integer :: nsize\n      integer, dimension(nsize) :: in\n      integer, dimension(nsize) :: tmp\n      integer, dimension(:) :: in0\n      integer tag, i, status, ierr, k\n      if(nsize .le. 0) return\n\n      tag = 29\n      if(my_id .ne. IO_id) then\n         call MPI_Send(in,nsize,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      else\n         do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n               call MPI_Recv(tmp,nsize,&\n                  MPI_INTEGER,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               do k = 1, nsize\n                  if(in0(k) .ne. tmp(k)) in(k) = tmp(k)\n               end do\n            end if\n         end do\n      end if\n      call mpp_land_bcast_int1d(in)\n\n   end subroutine updateLake_seqInt\n\n   subroutine updateLake_seqInt8(in,nsize,in0)\n      implicit none\n      integer :: nsize\n      integer(kind=int64), dimension(nsize) :: in\n      integer(kind=int64), dimension(nsize) :: tmp\n      integer(kind=int64), dimension(:) :: in0\n      integer tag, i, status, ierr, k\n      if(nsize .le. 0) return\n\n      tag = 29\n      if(my_id .ne. IO_id) then\n         call MPI_Send(in,nsize,MPI_INTEGER8, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      else\n         do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n               call MPI_Recv(tmp,nsize,&\n                  MPI_INTEGER8,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               do k = 1, nsize\n                  if(in0(k) .ne. tmp(k)) in(k) = tmp(k)\n               end do\n            end if\n         end do\n      end if\n      call mpp_land_bcast_int8_1d(in)\n\n   end subroutine updateLake_seqInt8\n\n\n   subroutine updateLake_seq(in,nsize,in0)\n      implicit none\n\n      integer :: nsize\n      real, dimension(:), intent(inout), asynchronous :: in\n      real, dimension(:), intent(in) :: in0\n\n      real, dimension(nsize) :: tmp\n      real, dimension(:), allocatable, asynchronous :: prev\n      real, dimension(:), allocatable :: adjustment\n      logical new\n      integer tag, i, status, ierr, k\n\n      if (nsize .le. 0) return\n\n      allocate(adjustment(nsize))\n      allocate(prev(nsize))\n\n      if (my_id == IO_id) prev = in0\n      call MPI_Bcast(prev, nsize, MPI_REAL, IO_id, HYDRO_COMM_WORLD, ierr)\n\n      if (my_id == IO_id) then\n         adjustment = in\n      else\n         adjustment = in - prev\n      end if\n\n      call MPI_Allreduce(adjustment, in, nsize, MPI_REAL, MPI_SUM, HYDRO_COMM_WORLD, ierr)  ! TODO: check ierr!\n\n      deallocate(adjustment)\n      deallocate(prev)\n\n   end subroutine updateLake_seq\n\n\n   subroutine updateLake_seq_char(in,nsize,in0)\n      implicit none\n      integer :: nsize\n      character(len=256), dimension(nsize) :: in\n      character(len=256), dimension(nsize) :: tmp\n      character(len=256), dimension(:) :: in0\n      integer tag, i, status, ierr, k, in_len\n      if(nsize .le. 0) return\n\n      in_len = size(in, 1)*len(in)\n\n      tag = 29\n      if(my_id .ne. IO_id) then\n         call MPI_Send(in,in_len,MPI_CHARACTER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      else\n         do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n               call MPI_Recv(tmp,in_len,&\n                  MPI_CHARACTER,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               do k = 1, nsize\n                  if(in0(k) .ne. tmp(k)) in(k) = tmp(k)\n               end do\n            end if\n         end do\n      end if\n      call mpp_land_bcast_char1d(in)\n\n   end subroutine updateLake_seq_char\n\n\n   subroutine updateLake_grid(in,nsize,lake_index)\n      implicit none\n      integer :: nsize\n      real, dimension(nsize) :: in\n      integer, dimension(nsize) :: lake_index\n      real, dimension(nsize) :: tmp\n      integer tag, i, status, ierr, k\n      if(nsize .le. 0) return\n\n      if(my_id .ne. IO_id) then\n         tag = 29\n         call MPI_Send(in,nsize,MPI_REAL, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n         tag = 30\n         call MPI_Send(lake_index,nsize,MPI_INTEGER, IO_id,     &\n            tag,HYDRO_COMM_WORLD,ierr)\n      else\n         do i = 0, numprocs - 1\n            if(i .ne. IO_id) then\n               tag = 29\n               call MPI_Recv(tmp,nsize,&\n                  MPI_REAL,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               tag = 30\n               call MPI_Recv(lake_index,nsize,&\n                  MPI_INTEGER,i,tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               do k = 1, nsize\n                  if(lake_index(k) .gt. 0) in(k) = tmp(k)\n               end do\n            end if\n         end do\n      end if\n      call mpp_land_bcast_real_1d(in)\n\n   end subroutine updateLake_grid\n\n\n!subroutine match1dLake:\n!global lake. Find the same lake and mark as flag\n! default of win is 0\n   subroutine match1dLake(vin,nsize,flag)\n      implicit none\n      integer nsize,i,j,tag,ierr, flag, k\n      integer, dimension(nsize):: vin,recv\n      tag = 319\n      if(nsize .le. 0) return\n      if(my_id .eq. IO_id) then\n         do i = 0, numprocs - 1\n            if(i .ne. my_id) then\n               call MPI_Recv(recv,nsize,MPI_INTEGER,i,  &\n                  tag,HYDRO_COMM_WORLD,mpp_status,ierr)\n               do k = 1, nsize\n                  if(recv(k) .eq. flag) vin(k) = flag\n                  if(vin(k) .ne. flag) then\n                     if(vin(k) .gt. 0 .and. recv(k) .gt. 0) then\n                        vin(k) = flag\n                     else\n                        if(recv(k) .gt. 0) vin(k) = recv(k)\n                     endif\n                  endif\n               end do\n            endif\n         end do\n      else\n         call MPI_Send(vin,nsize,MPI_INTEGER,IO_id,   &\n            tag,HYDRO_COMM_WORLD,ierr)\n      endif\n      call mpp_land_bcast_int1d(vin)\n   end subroutine match1dLake\n\n   subroutine mpp_land_abort()\n      implicit none\n      integer ierr\n      call MPI_Abort(HYDRO_COMM_WORLD,1,ierr)\n   end subroutine mpp_land_abort ! mpp_land_abort\n\n   subroutine mpp_land_sync()\n      implicit none\n      integer ierr\n      call MPI_Barrier( HYDRO_COMM_WORLD ,ierr)\n      if(ierr .ne. 0) call mpp_land_abort()\n   end subroutine mpp_land_sync ! mpp_land_sync\n\n   subroutine mpp_comm_scalar_real(scalar, fromImage, toImage)\n      implicit none\n      real,    intent(inout) :: scalar\n      integer, intent(in)    :: fromImage, toImage\n      integer:: ierr, tag\n      tag=2\n      if(my_id .eq. fromImage) &\n         call MPI_Send(scalar, 1, MPI_REAL, &\n         toImage, tag, HYDRO_COMM_WORLD, ierr)\n      if(my_id .eq. toImage) &\n         call MPI_Recv(scalar, 1, MPI_REAL, &\n         fromImage, tag, HYDRO_COMM_WORLD, mpp_status, ierr)\n   end subroutine mpp_comm_scalar_real\n\n   subroutine mpp_comm_scalar_char(scalar, fromImage, toImage)\n      implicit none\n      character(len=*), intent(inout) :: scalar\n      integer,          intent(in)    :: fromImage, toImage\n      integer:: ierr, tag, length\n      tag=2\n      length=len(scalar)\n      if(my_id .eq. fromImage) &\n         call MPI_Send(scalar, length, MPI_CHARACTER, &\n         toImage, tag, HYDRO_COMM_WORLD, ierr)\n      if(my_id .eq. toImage) &\n         call MPI_Recv(scalar, length, MPI_CHARACTER, &\n         fromImage, tag, HYDRO_COMM_WORLD, mpp_status, ierr)\n   end subroutine mpp_comm_scalar_char\n\n\n   subroutine mpp_comm_1d_real(vector, fromImage, toImage)\n      implicit none\n      real,    dimension(:), intent(inout) :: vector\n      integer,               intent(in)    :: fromImage, toImage\n      integer:: ierr, tag\n      integer:: my_id, numprocs\n      tag=2\n      call MPI_Comm_rank(HYDRO_COMM_WORLD,my_id,ierr)\n      call MPI_Comm_size(HYDRO_COMM_WORLD,numprocs,ierr)\n      if(numprocs > 1) then\n         if(my_id .eq. fromImage) &\n            call MPI_Send(vector, size(vector), MPI_REAL, &\n            toImage, tag, HYDRO_COMM_WORLD, ierr)\n         if(my_id .eq. toImage) &\n            call MPI_Recv(vector, size(vector), MPI_REAL, &\n            fromImage, tag, HYDRO_COMM_WORLD, mpp_status, ierr)\n      endif\n   end subroutine mpp_comm_1d_real\n\n\n   subroutine mpp_comm_1d_char(vector, fromImage, toImage)\n      implicit none\n      character(len=*), dimension(:), intent(inout) :: vector\n      integer,                        intent(in)    :: fromImage, toImage\n      integer:: ierr, tag, totalLength\n      integer:: my_id,numprocs\n      tag=2\n      call MPI_Comm_rank(HYDRO_COMM_WORLD,my_id,ierr)\n      call MPI_Comm_size(HYDRO_COMM_WORLD,numprocs,ierr)\n      totalLength=len(vector(1))*size(vector,1)\n      if(numprocs > 1) then\n         if(my_id .eq. fromImage) &\n            call MPI_Send(vector, totalLength, MPI_CHARACTER, &\n            toImage, tag, HYDRO_COMM_WORLD, ierr)\n         if(my_id .eq. toImage) &\n            call MPI_Recv(vector, totalLength, MPI_CHARACTER, &\n            fromImage, tag, HYDRO_COMM_WORLD, mpp_status, ierr)\n      endif\n   end subroutine mpp_comm_1d_char\n\n\nEND MODULE MODULE_MPP_LAND\n"
  },
  {
    "path": "src/Makefile",
    "content": "# Makefile\n#\nCMD = Run/wrf_hydro\n.PHONY: $(CMD)\n\nall: $(CMD)\n\n$(CMD):\n\t@if [ ! -d \"Run\" ]; then \\\n\t\t(mkdir Run);\\\n\tfi\n\t(rm -f Run/wrf_hydro   )\n\t(make -f Makefile.comm BASIC)\n\t@if [ -d \"LandModel_cpl\" ]; then \\\n\t(cd LandModel_cpl; make) \\\n\tfi\n\tif [ $(WRF_HYDRO_RAPID) -eq 1 ]; then \\\n\t\t(cd lib;rm -f librapid.a); \\\n\tfi\n\tif [ $(WRF_HYDRO_RAPID) -eq 1 ]; then \\\n\t\t(cd Rapid_routing; make -f makefile.cpl rapid); \\\n\tfi\n\n\t@if [ -d \"LandModel\" ]; then \\\n\t(cd LandModel; make ) \\\n\tfi\n\ndebug::\n\t@echo 'F90FLAGS := $$(DEBUGFLAGS) $$(F90FLAGS)' >> ./macros\n\t@echo 'F90FLAGS := $$(DEBUGFLAGS) $$(F90FLAGS)' >> ./LandModel/user_build_options\ndebug:: $(CMD)\n\ninstall:\n\t-rm -f ./Run/wrf_hydro\n\tmv LandModel/run/hrldas.exe  ./Run/wrf_hydro\ntest:\n\t@echo \"No libraries or utilities are built, skip testing.\"\nclean:\n\t@if [ -d \"LandModel_cpl\" ]; then \\\n\t(cd LandModel_cpl; make clean) \\\n\tfi\n\t(make -f Makefile.comm clean)\n\t@if [ -d \"LandModel\" ]; then \\\n\t(cd LandModel; make clean) \\\n\tfi\n\t@if [ \"$(WRF_HYDRO_RAPID)\" = \"1\" ]; then \\\n\t(cd Rapid_routing; make -f makefile.cpl clean); \\\n\tfi\n\t(rm -f */*.mod */*.o lib/*.a Run/wrf_hydro)\n"
  },
  {
    "path": "src/OrchestratorLayer/CMakeLists.txt",
    "content": "# build the orchestrator static library\nadd_library(hydro_orchestrator STATIC\n        config.F90\n        io_manager.F90\n        orchestrator.F90\n)\n\nadd_dependencies(hydro_orchestrator\n        hydro_netcdf_layer\n        hydro_utils\n)\n\ntarget_link_libraries(hydro_orchestrator PRIVATE\n        hydro_netcdf_layer\n        hydro_utils\n)\n"
  },
  {
    "path": "src/OrchestratorLayer/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nOBJS = \\\n\torchestrator.o \\\n\tconfig.o \\\n\tio_manager.o\n\nall:\t$(OBJS)\n\n#module_RT.o: module_RT.F\n#\t@echo \"\"\n#\t$(CPP) $(CPPFLAGS) $(*).F > $(*).f\n#\t$(COMPILER90) -o $(@) $(F90FLAGS) $(MODFLAG)  $(*).f\n#\t$(RMD) $(*).f\n#\t@echo \"\"\n#\tcp *.mod ../mod\n\n.F90.o:\n\t@echo \"Orchestrator Makefile:\"\n#\t$(COMPILER90) -o $(@) $(F90FLAGS) $(MODFLAG) $(*).f\n\t$(COMPILER90) $(CPPINVOKE) -o $(@) $(CPPFLAGS) $(FPPFLAGS) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) $(*).F90\n#\t$(RMD) $(*).f\n\t@echo \"\"\n\tar -r ../lib/libHYDRO.a $(@)\n\tcp *.mod ../mod\n\n#\n# Dependencies:\n#\nio_manager.o: ../IO/netcdf_layer.o\n\norchestrator.o: io_manager.o config.o\n\nclean:\n\trm -f *.o *.mod *.stb *~ *.f\n"
  },
  {
    "path": "src/OrchestratorLayer/config.F90",
    "content": "module config_base\n  !use netcdf_layer_base\n\n  use module_hydro_stop, only:HYDRO_stop\n\n  implicit none\n\n  integer, PARAMETER    :: MAX_SOIL_LEVELS = 10   ! maximum soil levels in namelist\n  !REAL                  ::  DTBL      ! timestep [s]\n\n  type NOAHLSM_OFFLINE_\n     character(len=256) :: indir\n     integer            :: nsoil ! number of soil layers\n     integer            :: crocus_opt = 0\n     integer            :: act_lev    = 0\n     integer            :: forcing_timestep\n     integer            :: noah_timestep\n     integer            :: start_year\n     integer            :: start_month\n     integer            :: start_day\n     integer            :: start_hour\n     integer            :: start_min\n     character(len=256) :: outdir = \".\"\n     character(len=256) :: restart_filename_requested = \" \"\n     integer            :: restart_frequency_hours\n     integer            :: output_timestep\n     integer            :: dynamic_veg_option\n     integer            :: canopy_stomatal_resistance_option\n     integer            :: btr_option\n     integer            :: runoff_option\n     integer            :: surface_drag_option\n     integer            :: supercooled_water_option\n     integer            :: frozen_soil_option\n     integer            :: radiative_transfer_option\n     integer            :: snow_albedo_option\n     integer            :: pcp_partition_option\n     integer            :: tbot_option\n     integer            :: temp_time_scheme_option\n     integer            :: glacier_option\n     integer            :: surface_resistance_option\n\n     character(len=256) :: forcing_name_T\n     character(len=256) :: forcing_name_Q\n     character(len=256) :: forcing_name_U\n     character(len=256) :: forcing_name_V\n     character(len=256) :: forcing_name_P\n     character(len=256) :: forcing_name_LW\n     character(len=256) :: forcing_name_SW\n     character(len=256) :: forcing_name_PR\n     character(len=256) :: forcing_name_SN\n     character(len=256) :: forcing_name_LF\n\n     integer            :: soil_data_option = 1\n     integer            :: pedotransfer_option = 0\n     integer            :: crop_option = 0\n     integer            :: imperv_option = 9\n\n     integer            :: split_output_count = 1\n     integer            :: khour\n     integer            :: kday = -999\n     real               :: zlvl\n     character(len=256) :: hrldas_setup_file = \" \"\n     character(len=256) :: mmf_runoff_file = \" \"\n     character(len=256) :: external_veg_filename_template = \" \"\n     character(len=256) :: external_lai_filename_template = \" \"\n     integer            :: xstart = 1\n     integer            :: ystart = 1\n     integer            :: xend = 0\n     integer            :: yend = 0\n     REAL, DIMENSION(MAX_SOIL_LEVELS) :: soil_thick_input       ! depth to soil interfaces from namelist [m]\n     integer :: rst_bi_out, rst_bi_in !0: default netcdf format. 1: binary write/read by each core.\n     CHARACTER(LEN = 256) :: spatial_filename\n  end type NOAHLSM_OFFLINE_\n\n  type WRF_HYDRO_OFFLINE_\n     integer  :: finemesh\n     integer  :: finemesh_factor\n     integer  :: forc_typ\n     integer  :: snow_assim\n  end type WRF_HYDRO_OFFLINE_\n\n  TYPE namelist_rt_\n\n     integer :: nsoil, SOLVEG_INITSWC\n     integer :: act_lev = 0\n     real,allocatable,dimension(:) :: ZSOIL8\n     real*8  :: out_dt, rst_dt\n     real    :: dt  !! dt is NOAH_TIMESTEP\n     integer :: START_YEAR, START_MONTH, START_DAY, START_HOUR, START_MIN\n     character(len=256)  :: restart_file = \"\"\n     integer             :: split_output_count\n     integer :: igrid\n     integer :: rst_bi_in   ! used for parallel io with large restart file.\n     integer :: rst_bi_out   ! used for parallel io with large restart file.\n     ! each process will output the restart tile.\n     character(len=256) :: geo_static_flnm = \"\"\n     character(len=1024) :: land_spatial_meta_flnm = \"\"\n     integer :: DEEPGWSPIN\n     integer ::  order_to_write, rst_typ\n     character(len=256)  :: upmap_file = \"\"    ! user defined mapping file for NHDPLUS\n     character(len=256)  :: hydrotbl_f = \"\"    ! hydrotbl file\n\n     !      additional character\n     character :: hgrid\n     character(len=19) :: olddate=\"123456\"\n     character(len=19) :: startdate=\"123456\"\n     character(len=19) :: sincedate=\"123456\"\n\n     integer :: io_config_outputs  ! used for NCEP REALTIME OUTPUT\n     integer :: io_form_outputs ! Flag to turn specify level of internal compression\n     integer :: t0OutputFlag\n     integer :: channel_only, channelBucket_only\n     integer :: output_channelBucket_influx ! used for FORCE_TYPE 9 and 10\n\n     integer:: RT_OPTION, CHANRTSWCRT, channel_option, &\n          SUBRTSWCRT,OVRTSWCRT,AGGFACTRT, &\n          GWBASESWCRT,  GW_RESTART,RSTRT_SWC,TERADJ_SOLAR, &\n          sys_cpl, gwChanCondSw, GwPreCycles, GwSpinCycles, GwPreDiagInterval, &\n          gwsoilcpl, UDMP_OPT\n     logical:: GwPreDiag, GwSpinUp\n     real:: DTRT_TER,DTRT_CH, DTCT, dxrt0,  gwChanCondConstIn, gwChanCondConstOut, gwIhShift\n     character(len=256) :: route_topo_f=\"\"\n     character(len=256) :: route_chan_f=\"\"\n     character(len=256) :: route_link_f=\"\"\n     character(len=256) :: route_lake_f=\"\"\n     integer            :: lake_option\n     character(len=256) :: diversions_file=\"\"\n     logical            :: reservoir_persistence_usgs\n     logical            :: reservoir_persistence_usace\n     character(len=256) :: reservoir_parameter_file=\"\"\n     character(len=256) :: reservoir_usgs_timeslice_path=\"\"\n     character(len=256) :: reservoir_usace_timeslice_path=\"\"\n     integer            :: reservoir_observation_lookback_hours = 18\n     integer            :: reservoir_observation_update_time_interval_seconds = 86400\n     logical            :: reservoir_rfc_forecasts\n     character(len=256) :: reservoir_rfc_forecasts_time_series_path=\"\"\n     integer            :: reservoir_rfc_forecasts_lookback_hours\n     logical            :: reservoir_type_specified\n     character(len=256) :: route_direction_f=\"\"\n     character(len=256) :: route_order_f=\"\"\n     character(len=256) :: gwbasmskfil =\"\"\n     character(len=256) :: gwstrmfil =\"\"\n     character(len=256) :: geo_finegrid_flnm =\"\"\n     character(len=256) :: udmap_file =\"\"\n     character(len=256) :: GWBUCKPARM_file = \"\"\n     integer :: reservoir_data_ingest ! STUB FOR USE OF REALTIME RESERVOIR DISCHARGE DATA. CURRENTLY NOT IN USE.\n     character(len=1024) :: reservoir_obs_dir = \"\"\n\n     logical :: compound_channel\n     integer ::frxst_pts_out            ! ASCII point timeseries output at user specified points\n     integer ::CHRTOUT_DOMAIN           ! Netcdf point timeseries output at all channel points\n     integer ::CHRTOUT_GRID                ! Netcdf grid of channel streamflow values\n     integer ::CHANOBS_DOMAIN             ! NetCDF point timeseries of output at forecast/gage points\n     integer ::LSMOUT_DOMAIN              ! Netcdf grid of variables passed between LSM and routing components\n     integer ::RTOUT_DOMAIN                ! Netcdf grid of terrain routing variables on routing grid\n     integer ::output_gw                   ! Netcdf grid of GW\n     integer ::outlake                   ! Netcdf grid of lake\n     integer :: rtFlag\n     integer ::khour\n\n     integer :: channel_loss_option = 0\n\n     character(len=256) :: nudgingParamFile\n     character(len=256) :: netwkReExFile\n     logical            :: readTimesliceParallel\n     logical            :: temporalPersistence\n     logical            :: persistBias\n     logical            :: biasWindowBeforeT0\n     character(len=256) :: nudgingLastObsFile\n     integer            :: minNumPairsBiasPersist\n     integer            :: maxAgePairsBiasPersist\n     logical            :: invDistTimeWeightBias\n     logical            :: noConstInterfBias\n     character(len=256) :: timeSlicePath = \"./nudgingTimeSliceObs/\"\n     integer            :: nLastObs\n     integer            :: bucket_loss\n     integer            :: imperv_adj\n\n     logical            :: channel_bypass = .FALSE.\n\n   contains\n\n     procedure, pass(self) :: check => rt_nlst_check\n\n  END TYPE namelist_rt_\n\n  type, public :: Configuration_\n   contains\n     procedure, nopass :: init => config_init\n     procedure, nopass :: init_nlst => init_namelist_rt_field\n  end type Configuration_\n\n  type crocus_options\n     integer :: crocus_opt = 0\n     integer :: act_lev = 0\n  end type crocus_options\n\n  integer, parameter :: max_domain = 5\n\n  type(NOAHLSM_OFFLINE_), protected, save :: noah_lsm\n  type(WRF_HYDRO_OFFLINE_), protected, save :: wrf_hydro\n  type(namelist_rt_), dimension(max_domain), save :: nlst\n\ncontains\n\n  subroutine config_init()\n    implicit none\n\n    integer, parameter :: did = 1\n\n    call init_noah_lsm_and_wrf_hydro()\n\n  end subroutine config_init\n\n  subroutine rt_nlst_check(self)\n    ! Subroutine to check namelist options specified by the user.\n    implicit none\n\n    class(namelist_rt_) self\n\n    ! Local variables\n    logical :: fileExists = .false.\n    integer :: i\n\n    !  ! Go through and make some logical checks for each hydro.namelist option.\n    !  ! Some of these checks will depend on specific options chosen by the user.\n\n   if ( (self%sys_cpl .lt. 1) .or. (self%sys_cpl .gt. 4) ) then\n       call hydro_stop(\"hydro.namelist ERROR: Invalid sys_cpl value specified.\")\n   endif\n\n   if (len(trim(self%geo_static_flnm)) .eq. 0) then\n      call hydro_stop(\"hydro.namelist ERROR: Please specify a GEO_STATIC_FLNM file.\")\n   else\n      inquire(file=trim(self%geo_static_flnm),exist=fileExists)\n      if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: GEO_STATIC_FLNM not found.')\n   endif\n\n   if (len(trim(self%geo_finegrid_flnm)) .eq. 0) then\n      call hydro_stop(\"hydro.namelist ERROR: Please specify a GEO_FINEGRID_FLNM file.\")\n   else\n      inquire(file=trim(self%geo_finegrid_flnm),exist=fileExists)\n      if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: GEO_FINEGRID_FLNM not found.')\n   endif\n\n   !if(len(trim(self%land_spatial_meta_flnm)) .eq. 0) then\n   !   call hydro_stop(\"hydro.namelist ERROR: Please specify a LAND_SPATIAL_META_FLNM file.\")\n   !else\n   !   inquire(file=trim(self%land_spatial_meta_flnm),exist=fileExists)\n   !   if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: LAND_SPATIAL_META_FLNM not found.')\n   !endif\n\n   if (len(trim(self%RESTART_FILE)) .ne. 0) then\n      inquire(file=trim(self%RESTART_FILE),exist=fileExists)\n      if (.not. fileExists) call hydro_stop('hydro.namelist ERROR:= Hydro RESTART_FILE not found.')\n   endif\n\n   if (self%igrid .le. 0) call hydro_stop('hydro.namelist ERROR: Invalid IGRID specified.')\n\n   if (self%out_dt .le. 0) call hydro_stop('hydro_namelist ERROR: Invalid out_dt specified.')\n\n   if ((self%split_output_count .lt. 0 ) .or. (self%split_output_count .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid SPLIT_OUTPUT_COUNT specified')\n   endif\n\n   if ((self%rst_typ .lt. 0 ) .or. (self%rst_typ .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid rst_typ specified')\n   endif\n\n   if ((self%rst_bi_in .lt. 0 ) .or. (self%rst_bi_in .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid rst_bi_in specified')\n   endif\n\n   if ((self%rst_bi_out .lt. 0 ) .or. (self%rst_bi_out .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid rst_bi_out specified')\n   endif\n\n   if ((self%RSTRT_SWC .lt. 0 ) .or. (self%RSTRT_SWC .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid RSTRT_SWC specified')\n   endif\n\n   if ((self%GW_RESTART .lt. 0 ) .or. (self%GW_RESTART .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid GW_RESTART specified')\n   endif\n\n   if ((self%order_to_write .lt. 1 ) .or. (self%order_to_write .gt. 12) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid order_to_write specified')\n   endif\n\n   if ((self%io_form_outputs .lt. 0 ) .or. (self%io_form_outputs .gt. 4) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid io_form_outputs specified')\n   endif\n\n   if ((self%io_config_outputs .lt. 0 ) .or. (self%io_config_outputs .gt. 6) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid io_config_outputs specified')\n   endif\n\n   if ((self%t0OutputFlag .lt. 0 ) .or. (self%t0OutputFlag .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid t0OutputFlag specified')\n   endif\n\n   if ((self%output_channelBucket_influx .lt. 0 ) .or. (self%output_channelBucket_influx .gt. 3) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid output_channelBucket_influx specified')\n   endif\n\n   if ((self%CHRTOUT_DOMAIN .lt. 0 ) .or. (self%CHRTOUT_DOMAIN .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid CHRTOUT_DOMAIN specified')\n   endif\n\n   if ((self%CHANOBS_DOMAIN .lt. 0 ) .or. (self%CHANOBS_DOMAIN .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid CHANOBS_DOMAIN specified')\n   endif\n\n   if ((self%CHRTOUT_GRID .lt. 0 ) .or. (self%CHRTOUT_GRID .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid CHRTOUT_GRID specified')\n   endif\n\n   if ((self%LSMOUT_DOMAIN .lt. 0 ) .or. (self%LSMOUT_DOMAIN .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid LSMOUT_DOMAIN specified')\n   endif\n\n   if ((self%RTOUT_DOMAIN .lt. 0 ) .or. (self%RTOUT_DOMAIN .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid RTOUT_DOMAIN specified')\n   endif\n\n   if ((self%output_gw .lt. 0 ) .or. (self%output_gw .gt. 2) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid output_gw specified')\n   endif\n\n   if ((self%outlake .lt. 0 ) .or. (self%outlake .gt. 2) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid outlake specified')\n   endif\n\n   if ((self%frxst_pts_out .lt. 0 ) .or. (self%frxst_pts_out .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid frxst_pts_out specified')\n   endif\n\n   if (self%TERADJ_SOLAR .ne. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid TERADJ_SOLAR specified')\n   endif\n\n   ! The default value of nsoil == -999. When channel-only is used,\n   ! nsoil ==  -999999. In the case of channel-only, skip following block of code.\n   if (self%NSOIL .le. 0 .and. self%NSOIL .ne. -999999) then\n      call hydro_stop('hydro.namelist ERROR: Invalid NSOIL specified.')\n   endif\n\n   do i = 1,self%NSOIL\n      if (self%ZSOIL8(i) .gt. 0) then\n          call hydro_stop('hydro.namelist ERROR: Invalid ZSOIL layer depth specified.')\n      endif\n      if (i .gt. 1) then\n         if (self%ZSOIL8(i) .ge. self%ZSOIL8(i-1)) then\n            call hydro_stop('hydro.namelist ERROR: Invalid ZSOIL layer depth specified.')\n         endif\n      endif\n   end do\n\n   if (self%NSOIL .le. 0 .and. self%NSOIL .ne. -999999) then\n      call hydro_stop('hydro.namelist ERROR: Invalid NSOIL specified.')\n   endif\n\n   if (self%dxrt0 .le. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid DXRT specified.')\n   endif\n\n   if (self%AGGFACTRT .le. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid AGGFACTRT specified.')\n   endif\n\n   if (self%DTRT_CH .le. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid DTRT_CH specified.')\n   endif\n\n   if (self%DTRT_TER .le. 0) then\n      call hydro_stop('hydro.namelist ERROR: Invalid DTRT_TER specified.')\n   endif\n\n   if ((self%SUBRTSWCRT .lt. 0 ) .or. (self%SUBRTSWCRT .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid SUBRTSWCRT specified')\n   endif\n\n   if ((self%OVRTSWCRT .lt. 0 ) .or. (self%OVRTSWCRT .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid OVRTSWCRT specified')\n   endif\n\n   if ((self%OVRTSWCRT .eq. 1 ) .or. (self%SUBRTSWCRT .eq. 1) ) then\n      if( (self%rt_option .lt. 1 ) .or. (self%rt_option .gt. 2) ) then\n      !if(self%rt_option .ne. 1) then\n         call hydro_stop('hydro.namelist ERROR: Invalid rt_option specified')\n      endif\n   endif\n\n   if ((self%CHANRTSWCRT .lt. 0 ) .or. (self%CHANRTSWCRT .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid CHANRTSWCRT specified')\n   endif\n\n   if (self%CHANRTSWCRT .eq. 1) then\n      if (self%channel_option .eq. 5 ) then\n         self%channel_option = 2\n         self%channel_bypass = .TRUE.\n      endif\n      if ((self%channel_option .lt. 1 ) .or. (self%channel_option .gt. 3) ) then\n         call hydro_stop('hydro.namelist ERROR: Invalid channel_option specified')\n      endif\n   endif\n\n   if ((self%CHANRTSWCRT .eq. 1) .and. (self%channel_option .lt. 3) ) then\n      if (len(trim(self%route_link_f)) .eq. 0) then\n         call hydro_stop(\"hydro.namelist ERROR: Please specify a route_link_f file.\")\n      else\n         inquire(file=trim(self%route_link_f),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: route_link_f not found.')\n      endif\n   endif\n\n   if ((self%bucket_loss .lt. 0 ) .or. (self%bucket_loss .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid bucket_loss specified')\n   endif\n\n   if ((self%bucket_loss .eq. 1 ) .and. (self%UDMP_OPT .ne. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Bucket loss only available when UDMP=1')\n   endif\n\n   if ((self%GWBASESWCRT .lt. 0 ) .or. (self%GWBASESWCRT .gt. 4) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid GWBASESWCRT specified')\n   endif\n\n   if ((self%GWBASESWCRT .eq. 1 ) .or. (self%GWBASESWCRT .eq. 4) ) then\n      if(len(trim(self%GWBUCKPARM_file)) .eq. 0) then\n         call hydro_stop(\"hydro.namelist ERROR: Please specify a GWBUCKPARM_file file.\")\n      else\n         inquire(file=trim(self%GWBUCKPARM_file),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: GWBUCKPARM_file not found.')\n      endif\n   endif\n\n   if ((self%GWBASESWCRT .gt. 0) .and. (self%UDMP_OPT .ne. 1) ) then\n      if(len(trim(self%gwbasmskfil)) .eq. 0) then\n         call hydro_stop(\"hydro.namelist ERROR: Please specify a gwbasmskfil file.\")\n      else\n         inquire(file=trim(self%gwbasmskfil),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: gwbasmskfil not found.')\n      endif\n   endif\n\n   if ((self%UDMP_OPT .lt. 0 ) .or. (self%UDMP_OPT .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid UDMP_OPT specified')\n   endif\n\n   if (self%UDMP_OPT .gt. 0) then\n      if(len(trim(self%udmap_file)) .eq. 0) then\n         call hydro_stop(\"hydro.namelist ERROR: Please specify a udmap_file file.\")\n      else\n         inquire(file=trim(self%udmap_file),exist=fileExists)\n         if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: udmap_file not found.')\n      endif\n   endif\n\n   if ((self%UDMP_OPT .eq. 1) .and. (self%CHANRTSWCRT .eq. 0) ) then\n         call hydro_stop('hydro.namelist ERROR: User-defined mapping requires channel routing on.')\n   endif\n\n   if ((self%outlake .ne. 0) .or. (self%lake_option > 0)) then\n      if (len(trim(self%route_lake_f)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a route_lake_f to output and/or run lakes.')\n      endif\n   endif\n\n   if (len(trim(self%route_lake_f)) .ne. 0) then\n      inquire(file=trim(self%route_lake_f),exist=fileExists)\n      if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: specified route_lake_f ('//trim(self%route_lake_f)//') not found.')\n   endif\n\n   if ((self%channel_option .eq. 3) .and. (self%compound_channel)) then\n      call hydro_stop(\"Compound channel option not available for diffusive wave routing. \")\n   end if\n\n   if ((self%lake_option .lt. 0) .or. (self%lake_option .gt. 3)) then\n      print *, self%lake_option\n      call hydro_stop(\"Lake Option must be 0 [lakes off], 1 [level pool], or 2 [passthrough], or 3 [reservoir DA]\")\n   end if\n\n   if (self%reservoir_type_specified) then\n      if (len(trim(self%reservoir_parameter_file)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_parameter_file for &\n         inputs to reservoirs that are not level pool type.')\n      endif\n      if (len(trim(self%reservoir_parameter_file)) .ne. 0) then\n        inquire(file=trim(self%reservoir_parameter_file),exist=fileExists)\n        if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: reservoir_parameter_file not found.')\n      endif\n   end if\n\n   if (self%reservoir_persistence_usgs) then\n      if (len(trim(self%reservoir_usgs_timeslice_path)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_usgs_timeslice_path for &\n         reservoir USGS persistence capability.')\n      endif\n      if (len(trim(self%reservoir_parameter_file)) .ne. 0) then\n        inquire(file=trim(self%reservoir_parameter_file),exist=fileExists)\n        if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: reservoir_parameter_file not found.')\n      endif\n    end if\n\n   if (self%reservoir_persistence_usace) then\n      if (len(trim(self%reservoir_usace_timeslice_path)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_usace_timeslice_path for &\n         reservoir USACE persistence capability.')\n      endif\n      if (len(trim(self%reservoir_parameter_file)) .ne. 0) then\n        inquire(file=trim(self%reservoir_parameter_file),exist=fileExists)\n        if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: reservoir_parameter_file not found.')\n      endif\n    end if\n\n   if (self%reservoir_rfc_forecasts) then\n      if (len(trim(self%reservoir_parameter_file)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_parameter_file for inputs to rfc forecast type reservoirs.')\n      endif\n      if (len(trim(self%reservoir_rfc_forecasts_time_series_path)) .eq. 0) then\n         call hydro_stop('hydro.namelist ERROR: You MUST specify a reservoir_rfc_forecasts_time_series_path for reservoir rfc forecast capability.')\n      endif\n      if (len(trim(self%reservoir_parameter_file)) .ne. 0) then\n        inquire(file=trim(self%reservoir_parameter_file),exist=fileExists)\n        if (.not. fileExists) call hydro_stop('hydro.namelist ERROR: reservoir_parameter_file not found.')\n      endif\n   end if\n\n   if ((self%imperv_adj .lt. 0 ) .or. (self%imperv_adj .gt. 1) ) then\n      call hydro_stop('hydro.namelist ERROR: Invalid imperv_adj specified')\n   endif\n\n  end subroutine rt_nlst_check\n\n  subroutine init_namelist_rt_field(did)\n    implicit none\n\n    integer, intent(in) :: did\n\n    integer ierr\n    character(len=512) :: msg\n\n    integer:: RT_OPTION, CHANRTSWCRT, channel_option, &\n         SUBRTSWCRT,OVRTSWCRT,AGGFACTRT, &\n         GWBASESWCRT,  GW_RESTART,RSTRT_SWC,TERADJ_SOLAR, &\n         sys_cpl, rst_typ, rst_bi_in, rst_bi_out, &\n         gwChanCondSw, GwPreCycles, GwSpinCycles, GwPreDiagInterval, gwsoilcpl, &\n         UDMP_OPT, io_form_outputs, bucket_loss, imperv_adj\n    real:: DTRT_TER,DTRT_CH,dxrt, gwChanCondConstIn, gwChanCondConstOut, gwIhShift\n    character(len=256) :: route_topo_f=\"\"\n    character(len=256) :: route_chan_f=\"\"\n    character(len=256) :: route_link_f=\"\"\n    logical            :: compound_channel\n    integer            :: channel_loss_option = 0\n    character(len=256) :: route_lake_f=\"\"\n    integer            :: lake_option  !0: lakes off 1: level pool 2: passthrough, 3: reservoir da\n    character(len=256) :: diversions_file=\"\"\n    logical            :: reservoir_persistence_usgs\n    logical            :: reservoir_persistence_usace\n    character(len=256) :: reservoir_parameter_file=\"\"\n    character(len=256) :: reservoir_usgs_timeslice_path=\"\"\n    character(len=256) :: reservoir_usace_timeslice_path=\"\"\n    integer            :: reservoir_observation_lookback_hours = 24\n    integer            :: reservoir_observation_update_time_interval_seconds = 86400\n    logical            :: reservoir_rfc_forecasts\n    character(len=256) :: reservoir_rfc_forecasts_time_series_path=\"\"\n    integer            :: reservoir_rfc_forecasts_lookback_hours = 28\n    logical            :: reservoir_type_specified\n    character(len=256) :: route_direction_f=\"\"\n    character(len=256) :: route_order_f=\"\"\n    character(len=256) :: gwbasmskfil =\"\"\n    character(len=256) :: gwstrmfil =\"\"\n    character(len=256) :: geo_finegrid_flnm =\"\"\n    character(len=256) :: udmap_file =\"\"\n    character(len=256) :: GWBUCKPARM_file = \"\"\n    integer :: reservoir_data_ingest ! STUB FOR USE OF REALTIME RESERVOIR DISCHARGE DATA. CURRENTLY NOT IN USE.\n    integer :: SOLVEG_INITSWC\n    real*8 :: out_dt, rst_dt\n    character(len=256)  :: RESTART_FILE = \"\"\n    character(len=256)  :: hydrotbl_f   = \"\"\n    logical            :: GwPreDiag, GwSpinUp\n    integer            :: split_output_count, order_to_write\n    integer :: igrid, io_config_outputs, t0OutputFlag, output_channelBucket_influx\n    character(len=256) :: geo_static_flnm = \"\"\n    character(len=1024) :: land_spatial_meta_flnm = \"\"\n    integer  :: DEEPGWSPIN\n\n    integer :: i\n\n    integer ::CHRTOUT_DOMAIN           ! Netcdf point timeseries output at all channel points\n    integer ::CHRTOUT_GRID                ! Netcdf grid of channel streamflow values\n    integer ::LSMOUT_DOMAIN              ! Netcdf grid of variables passed between LSM and routing components\n    integer ::RTOUT_DOMAIN                ! Netcdf grid of terrain routing variables on routing grid\n    integer  :: output_gw\n    integer  :: outlake\n    integer :: frxst_pts_out            ! ASCII text file of streamflow at forecast points\n    integer :: CHANOBS_DOMAIN           ! NetCDF point timeseries output at forecast points.\n\n!!! add the following two dummy variables\n    integer  :: NSOIL\n    real :: ZSOIL8(8)\n    type(crocus_options) :: crocus_opts\n\n    logical            :: dir_e\n    character(len=1024) :: reservoir_obs_dir\n#ifdef WRF_HYDRO_NUDGING\n    character(len=256) :: nudgingParamFile\n    character(len=256) :: netwkReExFile\n    logical            :: readTimesliceParallel\n    logical            :: temporalPersistence\n    logical            :: persistBias\n    logical            :: biasWindowBeforeT0\n    character(len=256) :: nudgingLastObsFile\n    character(len=256) :: timeSlicePath\n    integer            :: nLastObs\n    integer            :: minNumPairsBiasPersist\n    integer            :: maxAgePairsBiasPersist\n    logical            :: invDistTimeWeightBias\n    logical            :: noConstInterfBias\n#endif\n\n    namelist /HYDRO_nlist/ NSOIL, ZSOIL8,&\n         RESTART_FILE,SPLIT_OUTPUT_COUNT,IGRID,&\n         geo_static_flnm, &\n         land_spatial_meta_flnm, &\n         out_dt, rst_dt, &\n         DEEPGWSPIN, SOLVEG_INITSWC, &\n         RT_OPTION, CHANRTSWCRT, channel_option, &\n         SUBRTSWCRT,OVRTSWCRT,AGGFACTRT, dtrt_ter,dtrt_ch,dxrt,&\n         GwSpinCycles, GwPreCycles, GwSpinUp, GwPreDiag, GwPreDiagInterval, gwIhShift, &\n         GWBASESWCRT, gwChanCondSw, gwChanCondConstIn, gwChanCondConstOut , &\n         route_topo_f,route_chan_f,route_link_f, compound_channel, channel_loss_option, lake_option, route_lake_f,  diversions_file, &\n         route_direction_f,route_order_f,gwbasmskfil, &\n         geo_finegrid_flnm, gwstrmfil,GW_RESTART,RSTRT_SWC,TERADJ_SOLAR, sys_cpl, &\n         order_to_write , rst_typ, rst_bi_in, rst_bi_out, gwsoilcpl, &\n         CHRTOUT_DOMAIN,CHANOBS_DOMAIN,CHRTOUT_GRID,LSMOUT_DOMAIN,&\n         RTOUT_DOMAIN, output_gw, outlake, &\n         frxst_pts_out, udmap_file, UDMP_OPT, GWBUCKPARM_file, bucket_loss, &\n         io_config_outputs, io_form_outputs, hydrotbl_f, t0OutputFlag, output_channelBucket_influx, imperv_adj\n\n   namelist /reservoir_nlist/ &\n      reservoir_persistence_usgs, reservoir_persistence_usace, reservoir_parameter_file, reservoir_usgs_timeslice_path, &\n      reservoir_usace_timeslice_path, reservoir_observation_lookback_hours, reservoir_observation_update_time_interval_seconds, &\n      reservoir_rfc_forecasts, reservoir_rfc_forecasts_time_series_path, reservoir_rfc_forecasts_lookback_hours, &\n      reservoir_type_specified\n\n#ifdef WRF_HYDRO_NUDGING\n    namelist /NUDGING_nlist/ nudgingParamFile,       netwkReExFile,          &\n         readTimesliceParallel,  temporalPersistence,    &\n         persistBias,            nudgingLastObsFile,     &\n         timeSlicePath,          nLastObs,               &\n         minNumPairsBiasPersist, maxAgePairsBiasPersist, &\n         biasWindowBeforeT0,     invDistTimeWeightBias,  &\n         noConstInterfBias\n#endif\n\n    !! ---- End definitions ----\n\n    ! Default values for HYDRO_nlist\n    UDMP_OPT = 0\n    rst_bi_in = 0\n    rst_bi_out = 0\n    io_config_outputs = 0\n    io_form_outputs = 0\n    frxst_pts_out = 0\n    CHANOBS_DOMAIN = 0\n    t0OutputFlag = 1\n    output_channelBucket_influx = 0\n    TERADJ_SOLAR = 0\n    reservoir_data_ingest = 0 ! STUB FOR USE OF REALTIME RESERVOIR DISCHARGE DATA. CURRENTLY NOT IN USE.\n    compound_channel = .FALSE.\n    channel_loss_option = 0\n    bucket_loss = 0\n    lake_option = -99\n    reservoir_persistence_usgs = .FALSE.\n    reservoir_persistence_usace = .FALSE.\n    reservoir_observation_lookback_hours = 18\n    reservoir_observation_update_time_interval_seconds = 86400\n    reservoir_rfc_forecasts = .FALSE.\n    reservoir_rfc_forecasts_lookback_hours = 24\n    reservoir_type_specified = .FALSE.\n    imperv_adj = 0\n\n#ifdef WRF_HYDRO_NUDGING\n    ! Default values for NUDGING_nlist\n    nudgingParamFile = \"DOMAIN/nudgingParams.nc\"\n    netwkReExFile    = \"DOMAIN/netwkReExFile.nc\"\n    readTimesliceParallel  = .true.\n    temporalPersistence    = .true.\n    persistBias            = .false.\n    biasWindowBeforeT0     = .false.\n    nudgingLastObsFile     = \"\"\n    timeSlicePath          = \"./nudgingTimeSliceObs/\"\n    nLastObs               = 960\n    minNumPairsBiasPersist = 8\n    maxAgePairsBiasPersist = -99999\n    invDistTimeWeightBias  = .false.\n    noConstInterfBias      = .false.\n#endif\n\n! #ifdef MPP_LAND\n!     if(IO_id .eq. my_id) then\n! #endif\n#ifndef NCEP_WCOSS\n    open(12, file=\"hydro.namelist\", form=\"FORMATTED\")\n#else\n    open(12, form=\"FORMATTED\")\n#endif\n    read(12, HYDRO_nlist, iostat=ierr, iomsg=msg)\n    if(ierr .ne. 0) call hydro_stop(\"HYDRO_nlst namelist error in read_rt_nlst: \" // trim(msg))\n\n    if (lake_option == 3) then\n      read(12, reservoir_nlist, iostat=ierr, iomsg=msg)\n      if (ierr /= 0) call hydro_stop(\"reservoir_nlist namelist error in read_rt_nlst: \" // trim(msg))\n    end if\n\n#ifdef WRF_HYDRO_NUDGING\n    read(12, NUDGING_nlist, iostat=ierr, iomsg=msg)\n    if(ierr .ne. 0) call hydro_stop(\"NUDGING_nlst namelist error in read_rt_nlst: \" // trim(msg))\n    !! Conditional default values for nuding_nlist\n    if(maxAgePairsBiasPersist .eq. -99999) maxAgePairsBiasPersist = -1*nLastObs\n#endif\n    close(12)\n\n    call read_crocus_namelist(crocus_opts)\n! #ifdef MPP_LAND\n!     endif\n! #endif\n\n    ! ADCHANGE: move these checks to more universal namelist checks...\n    if ( io_config_outputs .eq. 4 ) RTOUT_DOMAIN = 0\n\n    if(output_channelBucket_influx .ne. 0) then\n       if(nlst(did)%dt .ne. out_dt*60) &\n            call hydro_stop(\"read_rt_nlst:: output_channelBucket_influx =! 0 inconsistent with out_dt and NOAH_TIMESTEP choices.\")\n       if(output_channelBucket_influx .eq. 2 .and. GWBASESWCRT .ne. 1 .and. GWBASESWCRT .ne. 2 .and. GWBASESWCRT .ne. 4) &\n            call hydro_stop(\"read_rt_nlst:: output_channelBucket_influx = 2 but GWBASESWCRT != 1 or 2.\")\n    end if\n\n    if(CHANRTSWCRT .eq. 0 .and. channel_option .lt. 3) channel_option = 3\n\n    !used to be broadcasted with MPI\n    !nlst(did)%NSOIL = NSOIL\n    !allocate(nlst(did)%ZSOIL8(NSOIL))\n    !nlst(did)%ZSOIL8 = ZSOIL8\n\n    nlst(did)%RESTART_FILE = RESTART_FILE\n    nlst(did)%hydrotbl_f = trim(hydrotbl_f)\n    nlst(did)%SPLIT_OUTPUT_COUNT = SPLIT_OUTPUT_COUNT\n    nlst(did)%IGRID = IGRID\n    nlst(did)%io_config_outputs = io_config_outputs\n    nlst(did)%io_form_outputs = io_form_outputs\n    nlst(did)%t0OutputFlag = t0OutputFlag\n    nlst(did)%output_channelBucket_influx = output_channelBucket_influx\n    nlst(did)%geo_static_flnm = geo_static_flnm\n    nlst(did)%land_spatial_meta_flnm = land_spatial_meta_flnm\n    nlst(did)%out_dt = out_dt\n    nlst(did)%rst_dt = rst_dt\n    nlst(did)%DEEPGWSPIN = DEEPGWSPIN\n    nlst(did)%SOLVEG_INITSWC = SOLVEG_INITSWC\n    nlst(did)%reservoir_obs_dir = \"testDirectory\"\n\n    if (lake_option == 3) then\n      if (reservoir_persistence_usgs .or. reservoir_persistence_usace .or. reservoir_rfc_forecasts) then\n         reservoir_type_specified = .TRUE.\n      else\n         print *, \"WARNING: lake_option = 3 (Reservoir DA), but no specific DA option was enabled. Setting lake_option to 1.\"\n      end if\n      lake_option = 1      ! set to 1 either way\n    end if\n\n    if (lake_option == -99) then\n      if (route_lake_f /= \"\") then\n         print *, \"WARNING: lake_option not specified, but route_lake_f specified. Setting lake_option to 1.\"\n         lake_option = 1\n      else\n         lake_option = 0\n      end if\n    end if\n\n    nlst(did)%lake_option = lake_option\n    nlst(did)%reservoir_persistence_usgs = reservoir_persistence_usgs\n    nlst(did)%reservoir_persistence_usace = reservoir_persistence_usace\n    nlst(did)%reservoir_parameter_file = reservoir_parameter_file\n    nlst(did)%reservoir_usgs_timeslice_path = reservoir_usgs_timeslice_path\n    nlst(did)%reservoir_usace_timeslice_path = reservoir_usace_timeslice_path\n    nlst(did)%reservoir_observation_lookback_hours = reservoir_observation_lookback_hours\n    nlst(did)%reservoir_observation_update_time_interval_seconds = reservoir_observation_update_time_interval_seconds\n    nlst(did)%reservoir_rfc_forecasts = reservoir_rfc_forecasts\n    nlst(did)%reservoir_rfc_forecasts_time_series_path = reservoir_rfc_forecasts_time_series_path\n    nlst(did)%reservoir_rfc_forecasts_lookback_hours = reservoir_rfc_forecasts_lookback_hours\n\n    nlst(did)%reservoir_type_specified = reservoir_type_specified\n\n    write(nlst(did)%hgrid,'(I1)') igrid\n\n    if(RESTART_FILE .eq. \"\") rst_typ = 0\n\n    if(rst_bi_out .eq. 1) then\n       ! This part works for intel not pgi\n       !     inquire(directory='restart', exist=dir_e)\n       inquire(file='restart/.', exist=dir_e)\n       if(.not. dir_e) then\n          call system('mkdir restart')\n       endif\n    endif\n\n    if(channel_option .eq. 4) then\n       CHANRTSWCRT = 0\n       OVRTSWCRT = 0\n       SUBRTSWCRT = 0\n    endif\n\n    nlst(did)%CHRTOUT_DOMAIN = CHRTOUT_DOMAIN\n    nlst(did)%CHANOBS_DOMAIN = CHANOBS_DOMAIN\n    nlst(did)%output_gw      = output_gw\n    nlst(did)%outlake      = outlake\n    nlst(did)%frxst_pts_out = frxst_pts_out\n    nlst(did)%CHRTOUT_GRID = CHRTOUT_GRID\n    nlst(did)%LSMOUT_DOMAIN = LSMOUT_DOMAIN\n    nlst(did)%RTOUT_DOMAIN = RTOUT_DOMAIN\n    nlst(did)%RT_OPTION = RT_OPTION\n    nlst(did)%CHANRTSWCRT = CHANRTSWCRT\n    nlst(did)%GW_RESTART  = GW_RESTART\n    nlst(did)%RSTRT_SWC   = RSTRT_SWC\n    nlst(did)%channel_option = channel_option\n    nlst(did)%DTRT_TER   = DTRT_TER\n    nlst(did)%DTRT_CH   = DTRT_CH\n    nlst(did)%DTCT      = DTRT_CH   ! small time step for grid based channel routing\n\n    ! Some fields haven't been initialized yet (e.g. DT)\n\n    if(nlst(did)%DT .lt. DTRT_CH) then\n          print*, \"nlst(did)%DT,  DTRT_CH = \",nlst(did)%DT,  DTRT_CH\n          print*, \"reset DTRT_CH=nlst(did)%DT \"\n          DTRT_CH=nlst(did)%DT\n    endif\n    if(nlst(did)%DT .lt. DTRT_TER) then\n          print*, \"nlst(did)%DT,  DTRT_TER = \",nlst(did)%DT,  DTRT_TER\n          print*, \"reset DTRT_TER=nlst(did)%DT \"\n          DTRT_TER=nlst(did)%DT\n    endif\n    if (modulo(nlst(did)%DT, DTRT_TER) /= 0) then\n         print*, \"nlst(did)%DT,  DTRT_TER = \",nlst(did)%DT,  DTRT_TER\n         call hydro_stop(\"module_namelist: DT not a multiple of DTRT_TER\")\n    endif\n    if (modulo(nlst(did)%DT, DTRT_CH) /= 0) then\n         print*, \"nlst(did)%DT,  DTRT_CH = \",nlst(did)%DT,  DTRT_CH\n         call hydro_stop(\"module_namelist: DT not a multiple of DTRT_CH\")\n    endif\n\n    nlst(did)%act_lev = crocus_opts%act_lev\n    nlst(did)%SUBRTSWCRT = SUBRTSWCRT\n    nlst(did)%OVRTSWCRT = OVRTSWCRT\n    nlst(did)%dxrt0 = dxrt\n    nlst(did)%AGGFACTRT = AGGFACTRT\n    nlst(did)%GWBASESWCRT = GWBASESWCRT\n    nlst(did)%bucket_loss = bucket_loss\n    nlst(did)%GWSOILCPL= GWSOILCPL\n    nlst(did)%gwChanCondSw = gwChanCondSw\n    nlst(did)%gwChanCondConstIn = gwChanCondConstIn\n    nlst(did)%gwChanCondConstOut = gwChanCondConstOut\n    nlst(did)%gwIhShift = gwIhShift\n    nlst(did)%GwSpinCycles = GwSpinCycles\n    nlst(did)%GwPreCycles = GwPreCycles\n    nlst(did)%GwPreDiag = GwPreDiag\n    nlst(did)%GwSpinUp = GwSpinUp\n    nlst(did)%GwPreDiagInterval = GwPreDiagInterval\n    nlst(did)%TERADJ_SOLAR = TERADJ_SOLAR\n    nlst(did)%sys_cpl = sys_cpl\n    nlst(did)%rst_typ = rst_typ\n    nlst(did)%rst_bi_in = rst_bi_in\n    nlst(did)%rst_bi_out = rst_bi_out\n    nlst(did)%order_to_write = order_to_write\n    nlst(did)%compound_channel = compound_channel\n    nlst(did)%channel_loss_option = channel_loss_option\n    nlst(did)%imperv_adj = imperv_adj\n    ! files\n    nlst(did)%route_topo_f = route_topo_f\n    nlst(did)%route_chan_f = route_chan_f\n    nlst(did)%route_link_f = route_link_f\n    nlst(did)%route_lake_f = route_lake_f\n\n    nlst(did)%diversions_file = diversions_file\n\n    nlst(did)%reservoir_persistence_usgs = reservoir_persistence_usgs\n    nlst(did)%reservoir_persistence_usace = reservoir_persistence_usace\n    nlst(did)%reservoir_parameter_file = reservoir_parameter_file\n    nlst(did)%reservoir_usgs_timeslice_path = reservoir_usgs_timeslice_path\n    nlst(did)%reservoir_usace_timeslice_path = reservoir_usace_timeslice_path\n    nlst(did)%reservoir_observation_lookback_hours = reservoir_observation_lookback_hours\n    nlst(did)%reservoir_observation_update_time_interval_seconds = reservoir_observation_update_time_interval_seconds\n    nlst(did)%reservoir_rfc_forecasts = reservoir_rfc_forecasts\n    nlst(did)%reservoir_rfc_forecasts_time_series_path = reservoir_rfc_forecasts_time_series_path\n    nlst(did)%reservoir_rfc_forecasts_lookback_hours = reservoir_rfc_forecasts_lookback_hours\n\n    nlst(did)%route_direction_f =  route_direction_f\n    nlst(did)%route_order_f =  route_order_f\n    nlst(did)%gwbasmskfil =  gwbasmskfil\n    nlst(did)%gwstrmfil =  gwstrmfil\n    nlst(did)%geo_finegrid_flnm =  geo_finegrid_flnm\n    nlst(did)%udmap_file =  udmap_file\n    nlst(did)%UDMP_OPT = UDMP_OPT\n    nlst(did)%GWBUCKPARM_file =  GWBUCKPARM_file\n    nlst(did)%reservoir_data_ingest = 0 ! STUB FOR USE OF REALTIME RESERVOIR DISCHARGE DATA. CURRENTLY NOT IN USE.\n    nlst(did)%reservoir_obs_dir = 'testDirectory'\n#ifdef WRF_HYDRO_NUDGING\n    nlst(did)%nudgingParamFile       = nudgingParamFile\n    write(*,*) 'Nudging param file ',nudgingParamFile\n    nlst(did)%netWkReExFile          = netWkReExFile\n    nlst(did)%readTimesliceParallel  = readTimesliceParallel\n    nlst(did)%temporalPersistence    = temporalPersistence\n    nlst(did)%persistBias            = persistBias\n    nlst(did)%biasWindowBeforeT0     = biasWindowBeforeT0\n    nlst(did)%nudgingLastObsFile     = nudgingLastObsFile\n    nlst(did)%timeSlicePath          = timeSlicePath\n    nlst(did)%nLastObs               = nLastObs\n    nlst(did)%minNumPairsBiasPersist = minNumPairsBiasPersist\n    nlst(did)%maxAgePairsBiasPersist = maxAgePairsBiasPersist\n    nlst(did)%invDistTimeWeightBias  = invDistTimeWeightBias\n    nlst(did)%noConstInterfBias      = noConstInterfBias\n#endif\n\n    ! if lakes have been disabled (lake_option == 0), clear the route_lake_f and output_lakes options\n    if (nlst(did)%lake_option == 0) then\n      nlst(did)%route_lake_f = ''\n      nlst(did)%outlake = 0\n    end if\n\n    call nlst(did)%check()\n\n    ! derive rtFlag\n    nlst(did)%rtFlag = 1\n    if(channel_option .eq. 4) nlst(did)%rtFlag = 0\n    !      if(CHANRTSWCRT .eq. 0 .and.  SUBRTSWCRT .eq. 0 .and. OVRTSWCRT .eq. 0 .and. GWBASESWCRT .eq. 0) nlst(did)%rtFlag = 0\n    if(SUBRTSWCRT .eq. 0 .and. OVRTSWCRT .eq. 0 .and. GWBASESWCRT .eq. 0) nlst(did)%rtFlag = 0\n\n  end subroutine init_namelist_rt_field\n\n  subroutine init_wrf_hydro()\n    implicit none\n\n    integer  :: ierr\n    integer  :: finemesh, finemesh_factor\n    integer  :: forc_typ, snow_assim\n\n    namelist /WRF_HYDRO_OFFLINE/ &\n         !LRK - Remove HRLDAS_ini_typ and GEO_STATIC_FLNM for WRF-Hydro\n         finemesh,finemesh_factor,forc_typ, snow_assim\n    !finemesh,finemesh_factor,forc_typ, snow_assim , GEO_STATIC_FLNM, HRLDAS_ini_typ\n\n#ifndef NCEP_WCOSS\n    read(30, NML=WRF_HYDRO_OFFLINE, iostat=ierr)\n#else\n    read(11, NML=WRF_HYDRO_OFFLINE, iostat=ierr)\n#endif\n    if (ierr /= 0) then\n       write(*,'(/,\" ***** ERROR: Problem reading namelist WRF_HYDRO_OFFLINE\",/)')\n       call hydro_stop (\" FATAL ERROR: Problem reading namelist WRF_HYDRO_OFFLINE\")\n    endif\n\n#ifndef NCEP_WCOSS\n    close(30)\n#else\n    close(11)\n#endif\n\n    wrf_hydro%finemesh = finemesh\n    wrf_hydro%finemesh_factor = finemesh_factor\n    wrf_hydro%forc_typ = forc_typ\n    wrf_hydro%snow_assim = snow_assim\n\n  end subroutine init_wrf_hydro\n\n  subroutine init_noah_lsm_and_wrf_hydro()\n    implicit none\n     character(len=256) :: indir\n     integer            :: nsoil ! number of soil layers\n     type(crocus_options) :: crocus_opts\n     integer            :: forcing_timestep\n     integer            :: noah_timestep\n     integer            :: start_year\n     integer            :: start_month\n     integer            :: start_day\n     integer            :: start_hour\n     integer            :: start_min\n     character(len=256) :: outdir = \".\"\n     character(len=256) :: restart_filename_requested = \" \"\n     integer            :: restart_frequency_hours\n     integer            :: output_timestep\n     character(len=256) :: forcing_name_T = \"T2D\"\n     character(len=256) :: forcing_name_Q = \"Q2D\"\n     character(len=256) :: forcing_name_U = \"U2D\"\n     character(len=256) :: forcing_name_V = \"V2D\"\n     character(len=256) :: forcing_name_P = \"PSFC\"\n     character(len=256) :: forcing_name_LW = \"LWDOWN\"\n     character(len=256) :: forcing_name_SW = \"SWDOWN\"\n     character(len=256) :: forcing_name_PR = \"RAINRATE\"\n     character(len=256) :: forcing_name_SN = \"\"\n     character(len=256) :: forcing_name_LF = \"\"\n     integer            :: dynamic_veg_option\n     integer            :: canopy_stomatal_resistance_option\n     integer            :: btr_option\n     integer            :: runoff_option\n     integer            :: surface_drag_option\n     integer            :: supercooled_water_option\n     integer            :: frozen_soil_option\n     integer            :: radiative_transfer_option\n     integer            :: snow_albedo_option\n     integer            :: pcp_partition_option\n     integer            :: tbot_option\n     integer            :: temp_time_scheme_option\n     integer            :: glacier_option\n     integer            :: surface_resistance_option\n     integer            :: soil_data_option = 1\n     integer            :: pedotransfer_option = 0\n     integer            :: crop_option = 0\n     integer            :: imperv_option = 9\n     integer            :: split_output_count = 1\n     integer            :: khour = -999\n     integer            :: kday = -999\n     real               :: zlvl\n     character(len=256) :: hrldas_setup_file = \" \"\n     character(len=256) :: mmf_runoff_file = \" \"\n     character(len=256) :: external_veg_filename_template = \" \"\n     character(len=256) :: external_lai_filename_template = \" \"\n     integer            :: xstart = 1\n     integer            :: ystart = 1\n     integer            :: xend = 0\n     integer            :: yend = 0\n     REAL, DIMENSION(MAX_SOIL_LEVELS) :: soil_thick_input       ! depth to soil interfaces from namelist [m]\n     integer :: rst_bi_out, rst_bi_in !0: default netcdf format. 1: binary write/read by each core.\n     CHARACTER(LEN = 256)                    ::  spatial_filename\n     integer :: ierr = 0\n\n    integer  :: finemesh, finemesh_factor\n    integer  :: forc_typ, snow_assim\n\n    namelist / NOAHLSM_OFFLINE /    &\n         indir, nsoil, soil_thick_input, forcing_timestep, noah_timestep, &\n         start_year, start_month, start_day, start_hour, start_min, &\n         outdir, &\n         restart_filename_requested, restart_frequency_hours, output_timestep, &\n\n         forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n         forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN,forcing_name_LF, &\n\n         dynamic_veg_option, canopy_stomatal_resistance_option, &\n         btr_option, runoff_option, surface_drag_option, supercooled_water_option, &\n         frozen_soil_option, radiative_transfer_option, snow_albedo_option, &\n         pcp_partition_option, tbot_option, temp_time_scheme_option, &\n         glacier_option, surface_resistance_option, &\n\n         soil_data_option, pedotransfer_option, crop_option, &\n         imperv_option, &\n\n         split_output_count, &\n         khour, kday, zlvl, hrldas_setup_file, mmf_runoff_file, &\n         spatial_filename, &\n         external_veg_filename_template, external_lai_filename_template, &\n         xstart, xend, ystart, yend, rst_bi_out, rst_bi_in\n\n    namelist /WRF_HYDRO_OFFLINE/ &\n         finemesh,finemesh_factor,forc_typ, snow_assim\n\n    noah_lsm%nsoil                   = -999\n    noah_lsm%soil_thick_input        = -999\n    ! dtbl                             = -999\n    noah_lsm%start_year              = -999\n    noah_lsm%start_month             = -999\n    noah_lsm%start_day               = -999\n    noah_lsm%start_hour              = -999\n    noah_lsm%start_min               = -999\n    noah_lsm%khour                   = -999\n    noah_lsm%kday                    = -999\n    noah_lsm%zlvl                    = -999\n    noah_lsm%forcing_timestep        = -999\n    noah_lsm%noah_timestep           = -999\n    noah_lsm%output_timestep         = -999\n    noah_lsm%restart_frequency_hours = -999\n\n    write(*,*) 'Calling config noahlsm_offline'\n\n#ifndef NCEP_WCOSS\n    open(30, file=\"namelist.hrldas\", form=\"FORMATTED\")\n    read(30, NML=NOAHLSM_OFFLINE, iostat=ierr)\n#else\n    open(11, form=\"FORMATTED\")\n    read(11, NML=NOAHLSM_OFFLINE, iostat=ierr)\n#endif\n\n    if (ierr /= 0) then\n       write(*,'(/,\" ***** ERROR: Problem reading namelist NOAHLSM_OFFLINE\",/)')\n#ifndef NCEP_WCOSS\n       rewind(30)\n       read(30, NOAHLSM_OFFLINE)\n#else\n            rewind(11)\n            read(11, NOAHLSM_OFFLINE)\n#endif\n       stop \"FATAL ERROR: Problem reading namelist NOAHLSM_OFFLINE\"\n    endif\n\n#ifndef NCEP_WCOSS\n    read(30, NML=WRF_HYDRO_OFFLINE, iostat=ierr)\n#else\n    read(11, NML=WRF_HYDRO_OFFLINE, iostat=ierr)\n#endif\n    if (ierr /= 0) then\n       write(*,'(/,\" ***** ERROR: Problem reading namelist WRF_HYDRO_OFFLINE\",/)')\n       call hydro_stop (\" FATAL ERROR: Problem reading namelist WRF_HYDRO_OFFLINE\")\n    endif\n\n#ifndef NCEP_WCOSS\n    call read_crocus_namelist(crocus_opts, 30)\n#else\n    call read_crocus_namelist(crocus_opts, 11)\n#endif\n\n#ifndef NCEP_WCOSS\n    close(30)\n#else\n    close(11)\n#endif\n\n    wrf_hydro%finemesh = 0!finemesh\n    wrf_hydro%finemesh_factor = 0!finemesh_factor\n    wrf_hydro%forc_typ = forc_typ\n    wrf_hydro%snow_assim = 0!snow_assim\n\n    noah_lsm%indir = indir\n    noah_lsm%nsoil = nsoil ! number of soil layers\n    noah_lsm%crocus_opt = crocus_opts%crocus_opt\n    noah_lsm%act_lev = crocus_opts%act_lev\n    noah_lsm%forcing_timestep = forcing_timestep\n    noah_lsm%noah_timestep = noah_timestep\n    noah_lsm%start_year = start_year\n    noah_lsm%start_month = start_month\n    noah_lsm%start_day = start_day\n    noah_lsm%start_hour = start_hour\n    noah_lsm%start_min = start_min\n    noah_lsm%outdir = outdir\n    noah_lsm%restart_filename_requested = restart_filename_requested\n    noah_lsm%restart_frequency_hours = restart_frequency_hours\n    noah_lsm%output_timestep = output_timestep\n    noah_lsm%forcing_name_T = forcing_name_T\n    noah_lsm%forcing_name_Q = forcing_name_Q\n    noah_lsm%forcing_name_U = forcing_name_U\n    noah_lsm%forcing_name_V = forcing_name_V\n    noah_lsm%forcing_name_P = forcing_name_P\n    noah_lsm%forcing_name_LW = forcing_name_LW\n    noah_lsm%forcing_name_SW = forcing_name_SW\n    noah_lsm%forcing_name_PR = forcing_name_PR\n    noah_lsm%forcing_name_SN = forcing_name_SN\n    noah_lsm%forcing_name_LF = forcing_name_LF\n    noah_lsm%dynamic_veg_option = dynamic_veg_option\n    noah_lsm%canopy_stomatal_resistance_option = canopy_stomatal_resistance_option\n    noah_lsm%btr_option = btr_option\n    noah_lsm%runoff_option = runoff_option\n    noah_lsm%surface_drag_option = surface_drag_option\n    noah_lsm%supercooled_water_option = supercooled_water_option\n    noah_lsm%frozen_soil_option = frozen_soil_option\n    noah_lsm%radiative_transfer_option = radiative_transfer_option\n    noah_lsm%snow_albedo_option = snow_albedo_option\n    noah_lsm%pcp_partition_option = pcp_partition_option\n    noah_lsm%tbot_option = tbot_option\n    noah_lsm%temp_time_scheme_option = temp_time_scheme_option\n    noah_lsm%glacier_option = glacier_option\n    noah_lsm%surface_resistance_option = surface_resistance_option\n\n    noah_lsm%soil_data_option = soil_data_option\n    noah_lsm%pedotransfer_option = pedotransfer_option\n    noah_lsm%crop_option = crop_option\n    noah_lsm%imperv_option = imperv_option\n\n    noah_lsm%split_output_count = split_output_count\n\n    if (kday > 0) then\n        if (khour > 0) then\n            write(*, '(\"WARNING: Check Namelist: KHOUR and KDAY both defined, KHOUR will take precedence.\")')\n            kday = -999\n        else\n            write(*, '(\"WARNING: KDAY is deprecated and may be removed in a future version, please use KHOUR.\")')\n            khour = -999\n        end if\n    end if\n    noah_lsm%kday = kday\n    noah_lsm%khour = khour\n\n    noah_lsm%zlvl = zlvl\n    noah_lsm%hrldas_setup_file = hrldas_setup_file\n    noah_lsm%mmf_runoff_file = \" \"!mmf_runoff_file\n    noah_lsm%external_veg_filename_template = \" \"!external_veg_filename_template\n    noah_lsm%external_lai_filename_template = \" \"!external_lai_filename_template\n    noah_lsm%xstart = 1!xstart\n    noah_lsm%ystart = 1!ystart\n    noah_lsm%xend = 0!xend\n    noah_lsm%yend = 0!yend\n    noah_lsm%soil_thick_input = soil_thick_input\n    noah_lsm%rst_bi_out = rst_bi_out\n    noah_lsm%rst_bi_in = rst_bi_in\n    noah_lsm%spatial_filename = spatial_filename\n\n  end subroutine init_noah_lsm_and_wrf_hydro\n\n  subroutine read_crocus_namelist(opt, f_in)\n    type(crocus_options), intent(OUT) :: opt\n    integer, intent(IN), optional :: f_in\n    character(len=15) :: filename = \"namelist.hrldas\"\n    logical :: f_exists\n    integer :: crocus_opt, act_lev\n    integer :: ierr, f_local\n    namelist /CROCUS_nlist/ &\n         crocus_opt, act_lev\n\n    ! check if file is opened\n    if (present(f_in)) then\n       rewind(f_in)\n       read(f_in, NML=CROCUS_nlist, iostat=ierr)\n    else\n       ! check that file exists\n       inquire(file=filename, exist=f_exists)\n       if (f_exists .eqv. .false.) &\n           call hydro_stop (\" FATAL ERROR: namelist.hrldas does not exist\")\n       open(newunit=f_local, file=filename, form=\"FORMATTED\", iostat=ierr)\n       read(f_local, NML=CROCUS_nlist, iostat=ierr)\n       close(f_local)\n    end if\n\n    if ((ierr .ne. 0) .or. (crocus_opt .eq. 0)) &\n         return\n    if ((act_lev .gt. 50) .or. (act_lev .lt. 0)) then\n       call hydro_stop (\" FATAL ERROR: Crocus act_lev out of range of 0-50 \")\n    end if\n\n    opt%crocus_opt = crocus_opt\n    if (crocus_opt == 0) then\n       opt%act_lev = 0\n    else\n       opt%act_lev = act_lev\n    end if\n  end subroutine read_crocus_namelist\n\nend module config_base\n"
  },
  {
    "path": "src/OrchestratorLayer/io_manager.F90",
    "content": "module io_manager_base\n  use netcdf_layer_base\n  implicit none\n\n  type :: IOManager_\n     logical :: parallel = .false.\n     class(NetCDF_layer_),allocatable :: netcdf_layer\n   contains\n  end type IOManager_\n\n  interface IOManager_\n     module procedure IOManager_init\n  end interface IOManager_\n\ncontains\n\n  type(IOManager_) function IOManager_init(parallel)\n    implicit none\n\n    logical, optional, intent(in) :: parallel\n\n    if(.not.present(parallel)) then\n       IOManager_init%parallel = .false.\n    else\n       IOManager_init%parallel = parallel\n    end if\n\n    if( IOManager_init%parallel .eqv. .false.) then\n       allocate(NetCDF_serial_ :: IOManager_init%netcdf_layer)\n       IOManager_init%netcdf_layer%open_file => nf90_open\n    else\n       allocate(NetCDF_parallel_ :: IOManager_init%netcdf_layer)\n       IOManager_init%netcdf_layer%open_file => nf90_open\n    end if\n\n  end function IOManager_init\n\nend module io_manager_base\n"
  },
  {
    "path": "src/OrchestratorLayer/orchestrator.F90",
    "content": "module orchestrator_base\n  use io_manager_base\n  use config_base\n  implicit none\n\n  ! interface orchestrator_\n  !    procedure orchestrator_init\n  ! end interface orchestrator_\n\n  type orchestrator_\n\n     !class(FluxAggregator_) :: flux_aggregator\n     !class(Groundwater_) :: groundwater\n     !class(TimeManager_) :: time_manager\n     type(IOManager_) :: IO_manager\n     type(Configuration_) :: config\n     !class(SpatialObject_) :: spatial_object\n\n   contains\n\n     procedure, public, pass(self) :: init => orchestrator_init\n\n  end type orchestrator_\n\n  type(orchestrator_), save :: orchestrator\n\ncontains\n\n  !We may want routines to access the various components\n\n  subroutine orchestrator_init(self)\n    class (orchestrator_) :: self\n\n    self%config = Configuration_()\n\n    call self%config%init()\n    ! Read configuration and decide how to assemble the various components\n    ! Assuming IO_Manager_serial_ selected\n    self%IO_manager = IOManager_()\n\n  end subroutine orchestrator_init\n\nend module orchestrator_base\n"
  },
  {
    "path": "src/README.build.md",
    "content": "# Standalone WRF-Hydro Build Instructions\nDetails regarding the model as well as documentation and user guides can be\nfound on the project website:\nhttps://ral.ucar.edu/projects/wrf_hydro\n\n## Requirements\n* A supported Fortran compiler:\n  - GNU (gfortran)\n  - Cray (ftn)\n  - Intel (ifort)\n  - NVidia (nvfortran)\n* MPI library (MPICH, Open MPI, etc.)\n* NetCDF C & Fortran libraries v4.0+\n\nPlease note that these libraries need to be compiled with the same set of\ncompilers that will be used to compile WRF-Hydro\n\n## Building WRF-Hydro\n\n1. Obtain the source code\n\nThe source code for the latest WRF-Hydro release can be obtained here:\nhttps://github.com/NCAR/wrf_hydro_nwm_public/releases/latest\n\nDownload and unpack the source code and navigate to the directory where you\nwill compile the code:\n\n```\n$ wget https://github.com/NCAR/wrf_hydro_nwm_public/archive/refs/tags/v5.3.0.tar.gz\n$ tar zxf v5.3.0.tar.gz\n$ cd wrf_hydro_nwm_public-5.3.0/src\n```\n\n2. Compile using CMake\n\nCreate build directory, configure with CMake, and then compile.\nSee the [CMake Build link](https://github.com/NCAR/wrf_hydro_nwm_public/blob/main/docs/BUILD.md#cmake-build)\nfor a table of WRF-Hydro specific configuration options.\nThe user can enable debug mode, nudging, etc.\n\n```\n$ mkdir build\n$ cd build\n$ cmake ..\n$ make -j 4\n```\n\nThis should result in the creation of a 'Run' directory populated with the\nappropriate template parameter tables and namelists for the land surface model\nselected as well as a model executable that is then symlinked to `wrf_hydro`.\n\nNote that, as mentioned above, passing the environment variable file as an\nargument to the compile script is optional. However, if this is not passed the\ndesired environment variables must be set prior to running the compile script.\n"
  },
  {
    "path": "src/Rapid_routing/.gitignore",
    "content": "#*******************************************************************************\n#.gitignore\n#*******************************************************************************\n\n#Purpose:\n#The git program is informed here to ignore the following files while performing \n#its distributed revision control and source code management. \n#Author:\n#Cedric H. David, 2014\n\n\n#*******************************************************************************\n#List of files that git will ignore\n#*******************************************************************************\n\n#-------------------------------------------------------------------------------\n#Initial releases of RAPID included batch submission scripts for supercomputers\n#-------------------------------------------------------------------------------\njob_*\n\n#-------------------------------------------------------------------------------\n#Legacy name for BSD 3-clause license of RAPID between 20120831 - 20131113 \n#-------------------------------------------------------------------------------\nrapid_license.txt\n"
  },
  {
    "path": "src/Rapid_routing/LICENSE",
    "content": "Copyright (c) 2007-2013, Cedric H. David\r\n\r\nAll rights reserved. \r\n\r\nRedistribution and use in source and binary forms, with or without modification,\r\nare permitted provided that the following conditions are met: \r\n* Redistributions of source code must retain the above copyright notice, this \r\n  list of conditions and the following disclaimer. \r\n* Redistributions in binary form must reproduce the above copyright notice, this \r\n  list of conditions and the following disclaimer in the documentation and/or \r\n  other materials provided with the distribution.\r\n* The name Cedric H. David may not be used to endorse or promote products \r\n  derived from this software without specific prior written permission. \r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \r\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \r\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \r\nDISCLAIMED. IN NO EVENT SHALL CEDRIC H. DAVID BE LIABLE FOR ANY DIRECT, \r\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \r\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \r\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \r\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \r\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \r\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \r\n"
  },
  {
    "path": "src/Rapid_routing/README",
    "content": "The Routing Application for Parallel computatIon of Discharge (RAPID) is a river\nnetwork routing model. Given surface and groundwater inflow to rivers, this \nmodel can compute flow and volume of water everywhere in river networks made out \nof many thousands of reaches. \n\nFor further information on RAPID including peer-reviewed publications, a manual, \nsample input/output data, sample processing scripts and animations of model \nresults, please go to: \nhttp://www.ucchm.org/david/rapid.htm\n"
  },
  {
    "path": "src/Rapid_routing/hrldas_RAPID_drv.F90",
    "content": "program main_program\n  use hrldas_RAPID_wrapper , only : hrldas_RAPID_ini,hrldas_RAPID_exe\n  implicit none\n\n  integer, parameter :: ii = 224\n  integer, parameter :: jj = 242\n  real,dimension(ii,jj) :: runoff\n  integer ITIME, NTIME\n!  character(len=100) :: Qout_nc_file = './RAPID.with.WRF_hydro.0000.nc'\n\n  call hrldas_RAPID_ini(NTIME)\n\n  do ITIME=1,NTIME\n    call hrldas_RAPID_exe(runoff,ii,jj)\n  end do\n! end loop for calling RAPID programs\n\n  end\n"
  },
  {
    "path": "src/Rapid_routing/hrldas_RAPID_wrapper.F90",
    "content": "module hrldas_RAPID_wrapper\n!---This Wrapper provides an interface for WRF-Hydro to call RAPID--\n!\tIf not initialized, do initialization first\n!\tIf initialized, continue RAPID computation\n!---The Wrapper also contains RAPID coupler, which defines where\n!\tLSM runoff is mapped into vector-based river reaches\n!---Author:\n!---Peirong Lin, 2014-2015---------------------------------------\n\nuse rapid_var, only : namelist_file,                                  &\n                      Qout_file,                                      &\n                      ZV_read_riv_tot,ZV_read_obs_tot,ZV_read_hum_tot,&\n                      IS_riv_tot,IS_riv_bas,JS_riv_tot,               &\n                      IV_riv_bas_id,IV_riv_index,IV_riv_loc1,         &\n                      ierr,stage,rank,                                &\n                      ZS_TauR\n\n#include \"finclude/petscsys.h\"\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n#include \"finclude/petscmat.h\"\n#include \"finclude/petscksp.h\"\n#include \"finclude/petscpc.h\"\n#include \"finclude/petscviewer.h\"\n#include \"finclude/petsclog.h\"\n#ifndef NO_TAO\n#include \"finclude/taosolver.h\"\n#endif\n\n!--LPR defined variables for RAPID loop---------\ninteger cnt_rapid_run\nlogical initialized\ncharacter(len=100) :: str\ncharacter(len=100) :: Qout_nc_dir\ncharacter(len=100) :: Qout_nc_file  !---LPR: RAPID output file name--\ninteger, dimension(:), allocatable :: IV_i_index\ninteger, dimension(:), allocatable :: IV_j_index\nreal, dimension(:), allocatable :: ZV_areakm !--LPR: size depending on rivers\n\nCONTAINS\n\n!---SUBROUTINE TO LINK WITH WRF-HYDRO-----------------\n  subroutine hrldas_RAPID_ini(ntime)\n!    use rapid_main , only : rapid_ini\n    implicit none\n    integer :: ntime\n\n    if (rank==0) then\n      print *,'RAPID initialized = ',initialized\n      if(initialized)  return  !If not first time initialization\n\n      print *,'***********************************************************'\n      print *,'*******Initialize RAPID model******************************'\n      print *,'***********************************************************'\n      call rapid_ini(ntime)\n      initialized = .True.\n    end if\n\n    call PetscLogStageRegister('Read Comp Write',stage,ierr)\n    call PetscLogStagePush(stage,ierr)\n  end subroutine hrldas_RAPID_ini\n\n\n\n!---SUBROUTINE TO LINK WITH WRF-HYDRO & DRIVE RAPID -----------------\n  subroutine hrldas_RAPID_exe(runoff,ii,jj)\n!    use rapid_main , only : rapid_main_exe\n    implicit none\n    real,dimension(ii,jj) :: runoff\n    integer :: ii,jj\n\n    !---LPR: convert LSM runoff to mm/hour (previous: mm, total runoff in a time step)\n    runoff = runoff/ZS_TauR*3600  !if LSM=3hrly, original runoff is in\n\n    !---LPR: MPI debug information------------------\n    !write(70+rank,*) \"yywww test inside the rapid \"\n    !call flush(70+rank)\n\n    if (rank==0) then\n      if(cnt_rapid_run==0) then\n        Qout_nc_dir = Qout_file !---define RAPID output director--------\n      end if\n      cnt_rapid_run = cnt_rapid_run + 1\n      !---LPR: define RAPID output filenames----------------------------\n      if (cnt_rapid_run < 10) then\n        write(str,100) cnt_rapid_run\n100     format('0000',i1)\n      else if (cnt_rapid_run < 100) then\n        write(str,200) cnt_rapid_run\n200     format('000',i2)\n      else if (cnt_rapid_run < 1000) then\n        write(str,300) cnt_rapid_run\n300     format('00',i3)\n      else if (cnt_rapid_run < 10000) then\n        write(str,400) cnt_rapid_run\n400     format('0',i4)\n      else\n        write(str,'(i5)') cnt_rapid_run\n      end if\n      Qout_nc_file = trim(Qout_nc_dir)//'RAPID.with.WRF_hydro.'//trim(str)//'.nc'\n      print *,'RAPID output Qout_nc_file = ',trim(Qout_nc_file)\n    end if\n\n    call rapid_main(1,runoff,ii,jj,Qout_nc_file)\n\n    !--LPR: add to test runoff in RESTART run mode, can remove this later-----------\n    !if(cnt_rapid_run == 2) then\n    !    write(81,*) runoff\n    !endif\n\n  end subroutine hrldas_RAPID_exe\n\n\n\n!-----------RAPID initialization call----------------------------------------------\n  subroutine rapid_ini(NTIME)\n    implicit none\n    integer NTIME\n    namelist_file='./rapid_namelist'\n\n    if (rank==0) then\n      print *,'First time RAPID initialization ... &\n          May take a while depending on size of river network ... &\n          ... Wait ...'\n      call rapid_init\n    end if\n\n  end subroutine rapid_ini\n\n\n\n!--------------RAPID coupler: gridded runoff to vector runoff-----------------------\n  subroutine rapid_runoff_to_inflow(ZM_runoff,ZV_Vlat,cnt_rapid_run)\n    implicit none\n\n    real, dimension(:,:), intent(in) :: ZM_runoff\n    Vec, intent(out) :: ZV_Vlat\n    integer :: cnt_rapid_run\n    integer :: JS_lon,JS_lat\n    character(len=100) :: rapid_coupling_file='./rapid_input_tx/RAPID_coupling_WRF_hydro.csv'\n    !---LPR: need to optimize code-----\n\n    !----------tease out weird runoff values-----------\n    if (rank==0) then\n      if (maxval(ZM_runoff)>1000) stop 'Runoff exceeds 1000'\n      if (minval(ZM_runoff)<0) stop 'Negative runoff'\n    !print *, 'Maximum value for ZM_runoff is:', maxval(ZM_runoff)\n    end if\n\n    !----------COUPLING START----------------------------\n    if (rank==0) then\n      !---initialize river reaches--------------------------------------\n      do JS_riv_tot=1,IS_riv_tot\n        ZV_read_riv_tot(JS_riv_tot) = 0.\n      end do\n\n      if (cnt_rapid_run==1) then\n        allocate(IV_i_index(IS_riv_tot))\n        allocate(IV_j_index(IS_riv_tot))\n        allocate(ZV_areakm(IS_riv_tot))\n        !If first time RAPID call: read coupling files\n        !----------OPTION 1: Catchment centroid-based coupling-----------\n        open(88,file=rapid_coupling_file,status='old')\n        do JS_riv_tot=1,IS_riv_tot\n          read(88,*) IV_riv_bas_id(JS_riv_tot),ZV_areakm(JS_riv_tot), &\n                   IV_i_index(JS_riv_tot),IV_j_index(JS_riv_tot)\n        end do\n        close(88)\n        print *,' LPR CHECK river 30000 ',IV_riv_bas_id(30000),ZV_areakm(30000), &\n                IV_i_index(30000),IV_j_index(30000)\n        !---------END OPTION 1----------------------------------\n\n        !---------OPTION 2: Area-weighted coupling----------------------\n\n        !--------END OPTION 2-----------------------------------\n\n        print *,'****First time: RAPID read coupling file successfully************'\n      end if !---LPR: only read coupling inforamtion once---------------\n\n      !---LPR: actual coupling (mapping runoff from LSM to rivers)------------\n      do JS_riv_tot=1,IS_riv_tot\n        JS_lon=IV_i_index(JS_riv_tot)\n        JS_lat=IV_j_index(JS_riv_tot)\n        !print *,'Location ::: ',JS_lon,JS_lat\n        !print *,'Values ::: ',ZM_runoff(JS_lon,JS_lat),ZV_areakm(JS_riv_tot)\n        ZV_read_riv_tot(JS_riv_tot)=ZM_runoff(JS_lon,JS_lat) &\n              *ZV_areakm(JS_riv_tot)*1000\n        !with runoff in kg/m2=mm and area in km2\n        !----LPR CHECK POINTS------------\n        if(JS_riv_tot .eq. 30000) then\n          print *,'***LPR CHECK*** m3_riv value = ',ZV_read_riv_tot(JS_riv_tot)\n        end if\n      end do\n\n      print *, '************************************************************'\n      print *, '***** LPR: RAPID coupling successful! **********************'\n      print *, '************************************************************'\n    end if\n\n    !------write to PETSC vector---------------------------\n    if (rank==0) then\n      print *,' number of river reaches  = ',IS_riv_bas\n      call VecSetValues(ZV_Vlat,IS_riv_bas,IV_riv_loc1,&\n               ZV_read_riv_tot(IV_riv_index),INSERT_VALUES,ierr)\n    end if\n    call VecAssemblyBegin(ZV_Vlat,ierr)\n    call VecAssemblyEnd(ZV_Vlat,ierr)\n  end subroutine rapid_runoff_to_inflow\n\nend module hrldas_RAPID_wrapper\n"
  },
  {
    "path": "src/Rapid_routing/makefile",
    "content": "#*******************************************************************************\n#makefile\n#*******************************************************************************\n\n#Purpose:\n#This file, along with the make utility allows compiling/linking RAPID\n#Author:\n#Cedric H. David, 2008-2015\n\n\n#*******************************************************************************\n#PETSc and TAO rules and variables (where environment variables and options are)\n#*******************************************************************************\n\n#-------------------------------------------------------------------------------\n#Default RAPID - includes optimization with TAO\n#-------------------------------------------------------------------------------\n#FPPFLAGS=\n#include ${TAO_DIR}/conf/tao_base\n\n#-------------------------------------------------------------------------------\n#If want to use RAPID without TAO, in which case the optimization is unavailable\n#-------------------------------------------------------------------------------\nFPPFLAGS=-D NO_TAO\ninclude ${PETSC_DIR}/conf/variables\ninclude ${PETSC_DIR}/conf/rules\n#include ${PETSC_DIR}/lib/petsc/conf/variables\n#include ${PETSC_DIR}/lib/petsc/conf/rules\n\n#*******************************************************************************\n#Location of netCDF include and lib directories\n#*******************************************************************************\nNETCDF_LIB=-L ${TACC_NETCDF_LIB} -lnetcdf\nNETCDF_INCLUDE=-I ${TACC_NETCDF_INC}\n\n\n#*******************************************************************************\n#makefile instructions\n#*******************************************************************************\n\n#-------------------------------------------------------------------------------\n#Test that environment variables are properly read by make\n#-------------------------------------------------------------------------------\ndummy:\n\techo ${FLINKER} ${FPPFLAGS}\n\n#-------------------------------------------------------------------------------\n#Link RAPID main\n#-------------------------------------------------------------------------------\nrapid:\trapid_main.o \\\n\trapid_init.o \\\n\trapid_read_namelist.o \\\n\trapid_arrays.o \\\n\trapid_create_obj.o \\\n\trapid_create_Qout_file.o \\\n\trapid_open_Qout_file.o \\\n\trapid_open_Vlat_file.o \\\n\trapid_open_Qobs_file.o \\\n\trapid_open_Qfor_file.o \\\n\trapid_open_Qhum_file.o \\\n\trapid_write_Qout_file.o \\\n\trapid_read_Vlat_file.o \\\n\trapid_read_Qobs_file.o \\\n\trapid_read_Qfor_file.o \\\n\trapid_read_Qhum_file.o \\\n\trapid_close_Qout_file.o \\\n\trapid_close_Vlat_file.o \\\n\trapid_close_Qobs_file.o \\\n\trapid_close_Qfor_file.o \\\n\trapid_close_Qhum_file.o \\\n\trapid_get_Qdam.o \\\n\trapid_set_Qext0.o \\\n\trapid_hsh_mat.o \\\n\trapid_net_mat.o \\\n\trapid_net_mat_brk.o \\\n\trapid_obs_mat.o \\\n\trapid_routing.o \\\n\trapid_routing_param.o \\\n\trapid_phiroutine.o \\\n\trapid_destro_obj.o \\\n\trapid_final.o \\\n\trapid_var.o \\\n\thrldas_RAPID_wrapper.o \\\n\thrldas_RAPID_drv.o\n\t${FLINKER} ${FPPFLAGS} -o \\\n\trapid \\\n\trapid_main.o \\\n\trapid_init.o \\\n\trapid_read_namelist.o \\\n\trapid_arrays.o \\\n\trapid_create_obj.o \\\n\trapid_create_Qout_file.o \\\n\trapid_open_Qout_file.o \\\n\trapid_open_Vlat_file.o \\\n\trapid_open_Qobs_file.o \\\n\trapid_open_Qfor_file.o \\\n\trapid_open_Qhum_file.o \\\n\trapid_write_Qout_file.o \\\n\trapid_read_Vlat_file.o \\\n\trapid_read_Qobs_file.o \\\n\trapid_read_Qfor_file.o \\\n\trapid_read_Qhum_file.o \\\n\trapid_close_Qout_file.o \\\n\trapid_close_Vlat_file.o \\\n\trapid_close_Qobs_file.o \\\n\trapid_close_Qfor_file.o \\\n\trapid_close_Qhum_file.o \\\n\trapid_get_Qdam.o \\\n\trapid_set_Qext0.o \\\n\trapid_hsh_mat.o \\\n\trapid_net_mat.o \\\n\trapid_net_mat_brk.o \\\n\trapid_routing.o \\\n\trapid_routing_param.o \\\n\trapid_obs_mat.o \\\n\trapid_phiroutine.o \\\n\trapid_destro_obj.o \\\n\trapid_final.o \\\n\trapid_var.o \\\n\thrldas_RAPID_wrapper.o \\\n\thrldas_RAPID_drv.o \\\n\t${TAO_FORTRAN_LIB} ${TAO_LIB} ${PETSC_LIB} ${NETCDF_LIB}\n\t${RM} *.o *.mod\n#\tln -sf ../src/rapid ../run/rapid\n#\tln -sf ../src/rapid ../rtk/rapid\n#----LPR: uncomment the link because no RAPID executable will be generated when\n#---------coupled with WRF-Hydro\n\n#-------------------------------------------------------------------------------\n#Compile RAPID\n#-------------------------------------------------------------------------------\nrapid_final.o:\t\trapid_final.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_final.F90 ${PETSC_FC_INCLUDES}\n\nrapid_destro_obj.o: \trapid_destro_obj.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_destro_obj.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_phiroutine.o: \trapid_phiroutine.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_phiroutine.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_routing.o: \trapid_routing.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_routing.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_init.o: \t\trapid_read_namelist.o rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_init.F90 ${PETSC_FC_INCLUDES}\n\nrapid_routing_param.o: \trapid_routing_param.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_routing_param.F90 ${PETSC_FC_INCLUDES}\n\nrapid_obs_mat.o: \trapid_obs_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_obs_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_net_mat_brk.o: \trapid_net_mat_brk.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_net_mat_brk.F90 ${PETSC_FC_INCLUDES}\n\nrapid_net_mat.o: \trapid_net_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_net_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_hsh_mat.o: \trapid_hsh_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_hsh_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_get_Qdam.o: \trapid_get_Qdam.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_get_Qdam.F90 ${PETSC_FC_INCLUDES}\n\nrapid_set_Qext0.o: \trapid_set_Qext0.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_set_Qext0.F90 ${PETSC_FC_INCLUDES}\n\nrapid_close_Qfor_file.o: \trapid_close_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qfor_file.F90\n\nrapid_close_Qhum_file.o: \trapid_close_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qhum_file.F90\n\nrapid_close_Qobs_file.o: \trapid_close_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qobs_file.F90\n\nrapid_close_Vlat_file.o: \trapid_close_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Vlat_file.F90 ${NETCDF_INCLUDE}\n\nrapid_close_Qout_file.o: \trapid_close_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qout_file.F90 ${NETCDF_INCLUDE}\n\nrapid_read_Qfor_file.o: \trapid_read_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qfor_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Qhum_file.o: \trapid_read_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qhum_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Qobs_file.o: \trapid_read_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qobs_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Vlat_file.o: \trapid_read_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Vlat_file.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_write_Qout_file.o: \trapid_write_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_write_Qout_file.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_open_Qfor_file.o: \trapid_open_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qfor_file.F90\n\nrapid_open_Qhum_file.o: \trapid_open_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qhum_file.F90\n\nrapid_open_Qobs_file.o: \trapid_open_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qobs_file.F90\n\nrapid_open_Vlat_file.o: \trapid_open_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Vlat_file.F90 ${NETCDF_INCLUDE}\n\nrapid_open_Qout_file.o: \trapid_open_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qout_file.F90 ${NETCDF_INCLUDE}\n\nrapid_create_Qout_file.o: \trapid_create_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_create_Qout_file.F90 ${NETCDF_INCLUDE}\n\nrapid_create_obj.o: \trapid_create_obj.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_create_obj.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_arrays.o:\trapid_arrays.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_arrays.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_namelist.o:\trapid_read_namelist.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_namelist.F90\n\nrapid_var.o rapid_var.mod:\trapid_var.F90\n\t${FLINKER} ${FPPFLAGS} -c rapid_var.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nhrldas_RAPID_wrapper.mod hrldas_RAPID_wrapper.o:     hrldas_RAPID_wrapper.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c hrldas_RAPID_wrapper.F90  ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_main.o:   rapid_main.F90 rapid_var.mod hrldas_RAPID_wrapper.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_main.F90 ${PETSC_FC_INCLUDES} \\\n\t\t\t\t\t\t${TAO_INCLUDE} ${NETCDF_INCLUDE}\n\nhrldas_RAPID_drv.o:     hrldas_RAPID_drv.F90 hrldas_RAPID_wrapper.mod\n\t${FLINKER} ${FPPFLAGS} -c hrldas_RAPID_drv.F90  ${PETSC_FC_INCLUDE} ${TAO_INCLUDE}\n\n#-------------------------------------------------------------------------------\n#Clean\n#-------------------------------------------------------------------------------\nclean::\n\t${RM} *.o *.mod rapid ../run/rapid ../rtk/rapid\n"
  },
  {
    "path": "src/Rapid_routing/makefile.cpl",
    "content": "#*******************************************************************************\n#makefile\n#*******************************************************************************\n\n#Purpose:\n#This file, along with the make utility allows compiling/linking RAPID\n#Author:\n#Cedric H. David, 2008-2015\n\n\n#*******************************************************************************\n#PETSc and TAO rules and variables (where environment variables and options are)\n#*******************************************************************************\n\n#-------------------------------------------------------------------------------\n#Default RAPID - includes optimization with TAO \n#-------------------------------------------------------------------------------\n#FPPFLAGS=\n#include ${TAO_DIR}/conf/tao_base\n\n#-------------------------------------------------------------------------------\n#If want to use RAPID without TAO, in which case the optimization is unavailable\n#-------------------------------------------------------------------------------\nFPPFLAGS=-D NO_TAO\ninclude ${PETSC_DIR}/conf/variables\ninclude ${PETSC_DIR}/conf/rules\n\n\n#*******************************************************************************\n#Location of netCDF include and lib directories\n#*******************************************************************************\nNETCDF_LIB=-L ${TACC_NETCDF_LIB} -lnetcdf\nNETCDF_INCLUDE=-I ${TACC_NETCDF_INC}\n\n#*******************************************************************************\n#makefile instructions \n#*******************************************************************************\n\n#-------------------------------------------------------------------------------\n#Test that environment variables are properly read by make\n#-------------------------------------------------------------------------------\ndummy: \n\techo ${FLINKER} ${FPPFLAGS}\n\n#-------------------------------------------------------------------------------\n#Link RAPID main\n#-------------------------------------------------------------------------------\nrapid:\trapid_main.o \\\n\trapid_init.o \\\n\trapid_read_namelist.o \\\n\trapid_arrays.o \\\n\trapid_create_obj.o \\\n\trapid_create_Qout_file.o \\\n\trapid_open_Qout_file.o \\\n\trapid_open_Vlat_file.o \\\n\trapid_open_Qobs_file.o \\\n\trapid_open_Qfor_file.o \\\n\trapid_open_Qhum_file.o \\\n\trapid_write_Qout_file.o \\\n\trapid_read_Vlat_file.o \\\n\trapid_read_Qobs_file.o \\\n\trapid_read_Qfor_file.o \\\n\trapid_read_Qhum_file.o \\\n\trapid_close_Qout_file.o \\\n\trapid_close_Vlat_file.o \\\n\trapid_close_Qobs_file.o \\\n\trapid_close_Qfor_file.o \\\n\trapid_close_Qhum_file.o \\\n\trapid_get_Qdam.o \\\n\trapid_set_Qext0.o \\\n\trapid_hsh_mat.o \\\n\trapid_net_mat.o \\\n\trapid_net_mat_brk.o \\\n\trapid_obs_mat.o \\\n\trapid_routing.o \\\n\trapid_routing_param.o \\\n\trapid_phiroutine.o \\\n\trapid_destro_obj.o \\\n\trapid_final.o \\\n\trapid_var.o \\\n\thrldas_RAPID_wrapper.o\n\tar -r ../lib/librapid.a *.o\n\tcp *.mod ../mod/.\n#\t${RM} *.o *.mod \n\n#-------------------------------------------------------------------------------\n#Compile RAPID\n#-------------------------------------------------------------------------------\nrapid_final.o:\t\trapid_final.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_final.F90 ${PETSC_FC_INCLUDES}\n\nrapid_destro_obj.o: \trapid_destro_obj.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_destro_obj.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_phiroutine.o: \trapid_phiroutine.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_phiroutine.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE} \n\nrapid_routing.o: \trapid_routing.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_routing.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_init.o: \t\trapid_read_namelist.o rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_init.F90 ${PETSC_FC_INCLUDES}\n\nrapid_routing_param.o: \trapid_routing_param.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_routing_param.F90 ${PETSC_FC_INCLUDES}\n\nrapid_obs_mat.o: \trapid_obs_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_obs_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_net_mat_brk.o: \trapid_net_mat_brk.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_net_mat_brk.F90 ${PETSC_FC_INCLUDES}\n\nrapid_net_mat.o: \trapid_net_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_net_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_hsh_mat.o: \trapid_hsh_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_hsh_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_get_Qdam.o: \trapid_get_Qdam.F90 rapid_var.mod \n\t${FLINKER} ${FPPFLAGS} -c rapid_get_Qdam.F90 ${PETSC_FC_INCLUDES}\n\nrapid_set_Qext0.o: \trapid_set_Qext0.F90 rapid_var.mod \n\t${FLINKER} ${FPPFLAGS} -c rapid_set_Qext0.F90 ${PETSC_FC_INCLUDES}\n\nrapid_close_Qfor_file.o: \trapid_close_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qfor_file.F90\n\nrapid_close_Qhum_file.o: \trapid_close_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qhum_file.F90\n\nrapid_close_Qobs_file.o: \trapid_close_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qobs_file.F90\n\nrapid_close_Vlat_file.o: \trapid_close_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Vlat_file.F90 ${NETCDF_INCLUDE} \n\nrapid_close_Qout_file.o: \trapid_close_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qout_file.F90 ${NETCDF_INCLUDE} \n\nrapid_read_Qfor_file.o: \trapid_read_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qfor_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Qhum_file.o: \trapid_read_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qhum_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Qobs_file.o: \trapid_read_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qobs_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Vlat_file.o: \trapid_read_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Vlat_file.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_write_Qout_file.o: \trapid_write_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_write_Qout_file.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_open_Qfor_file.o: \trapid_open_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qfor_file.F90 \n\nrapid_open_Qhum_file.o: \trapid_open_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qhum_file.F90 \n\nrapid_open_Qobs_file.o: \trapid_open_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qobs_file.F90 \n\nrapid_open_Vlat_file.o: \trapid_open_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Vlat_file.F90 ${NETCDF_INCLUDE}\n\nrapid_open_Qout_file.o: \trapid_open_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qout_file.F90 ${NETCDF_INCLUDE}\n\nrapid_create_Qout_file.o: \trapid_create_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_create_Qout_file.F90 ${NETCDF_INCLUDE}\n\nrapid_create_obj.o: \trapid_create_obj.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_create_obj.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_arrays.o:\trapid_arrays.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_arrays.F90 ${PETSC_FC_INCLUDES}\n\t\nrapid_read_namelist.o:\trapid_read_namelist.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_namelist.F90\n\t\nrapid_var.o rapid_var.mod:\trapid_var.F90\n\t${FLINKER} ${FPPFLAGS} -c rapid_var.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE} \n\nhrldas_RAPID_wrapper.mod hrldas_RAPID_wrapper.o:     hrldas_RAPID_wrapper.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c hrldas_RAPID_wrapper.F90  ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_main.o:   rapid_main.F90 rapid_var.mod hrldas_RAPID_wrapper.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_main.F90 ${PETSC_FC_INCLUDES} \\\n                                                ${TAO_INCLUDE} ${NETCDF_INCLUDE}\n\t\n#-------------------------------------------------------------------------------\n#Clean\n#-------------------------------------------------------------------------------\nclean::\n\t${RM} *.o *.mod rapid ../run/rapid ../rtk/rapid\n\n"
  },
  {
    "path": "src/Rapid_routing/makefile.orig",
    "content": "#*******************************************************************************\n#makefile\n#*******************************************************************************\n\n#Purpose:\n#This file, along with the make utility allows compiling/linking RAPID\n#Author:\n#Cedric H. David, 2008-2015\n\n\n#*******************************************************************************\n#PETSc and TAO rules and variables (where environment variables and options are)\n#*******************************************************************************\n\n#-------------------------------------------------------------------------------\n#Default RAPID - includes optimization with TAO \n#-------------------------------------------------------------------------------\n#FPPFLAGS=\n#include ${TAO_DIR}/conf/tao_base\n\n#-------------------------------------------------------------------------------\n#If want to use RAPID without TAO, in which case the optimization is unavailable\n#-------------------------------------------------------------------------------\nFPPFLAGS=-D NO_TAO\ninclude ${PETSC_DIR}/conf/variables\ninclude ${PETSC_DIR}/conf/rules\n\n\n#*******************************************************************************\n#Location of netCDF include and lib directories\n#*******************************************************************************\nNETCDF_LIB=-L ${TACC_NETCDF_LIB} -lnetcdf\nNETCDF_INCLUDE=-I ${TACC_NETCDF_INC}\n\n\n#*******************************************************************************\n#makefile instructions \n#*******************************************************************************\n\n#-------------------------------------------------------------------------------\n#Test that environment variables are properly read by make\n#-------------------------------------------------------------------------------\ndummy: \n\techo ${FLINKER} ${FPPFLAGS}\n\n#-------------------------------------------------------------------------------\n#Link RAPID main\n#-------------------------------------------------------------------------------\nrapid:\trapid_main.o \\\n\trapid_init.o \\\n\trapid_read_namelist.o \\\n\trapid_arrays.o \\\n\trapid_create_obj.o \\\n\trapid_create_Qout_file.o \\\n\trapid_open_Qout_file.o \\\n\trapid_open_Vlat_file.o \\\n\trapid_open_Qobs_file.o \\\n\trapid_open_Qfor_file.o \\\n\trapid_open_Qhum_file.o \\\n\trapid_write_Qout_file.o \\\n\trapid_read_Vlat_file.o \\\n\trapid_read_Qobs_file.o \\\n\trapid_read_Qfor_file.o \\\n\trapid_read_Qhum_file.o \\\n\trapid_close_Qout_file.o \\\n\trapid_close_Vlat_file.o \\\n\trapid_close_Qobs_file.o \\\n\trapid_close_Qfor_file.o \\\n\trapid_close_Qhum_file.o \\\n\trapid_get_Qdam.o \\\n\trapid_set_Qext0.o \\\n\trapid_hsh_mat.o \\\n\trapid_net_mat.o \\\n\trapid_net_mat_brk.o \\\n\trapid_obs_mat.o \\\n\trapid_routing.o \\\n\trapid_routing_param.o \\\n\trapid_phiroutine.o \\\n\trapid_destro_obj.o \\\n\trapid_final.o \\\n\trapid_var.o\n\t${FLINKER} ${FPPFLAGS} -o \\\n\trapid \\\n\trapid_main.o \\\n\trapid_init.o \\\n\trapid_read_namelist.o \\\n\trapid_arrays.o \\\n\trapid_create_obj.o \\\n\trapid_create_Qout_file.o \\\n\trapid_open_Qout_file.o \\\n\trapid_open_Vlat_file.o \\\n\trapid_open_Qobs_file.o \\\n\trapid_open_Qfor_file.o \\\n\trapid_open_Qhum_file.o \\\n\trapid_write_Qout_file.o \\\n\trapid_read_Vlat_file.o \\\n\trapid_read_Qobs_file.o \\\n\trapid_read_Qfor_file.o \\\n\trapid_read_Qhum_file.o \\\n\trapid_close_Qout_file.o \\\n\trapid_close_Vlat_file.o \\\n\trapid_close_Qobs_file.o \\\n\trapid_close_Qfor_file.o \\\n\trapid_close_Qhum_file.o \\\n\trapid_get_Qdam.o \\\n\trapid_set_Qext0.o \\\n\trapid_hsh_mat.o \\\n\trapid_net_mat.o \\\n\trapid_net_mat_brk.o \\\n\trapid_routing.o \\\n\trapid_routing_param.o \\\n\trapid_obs_mat.o \\\n\trapid_phiroutine.o \\\n\trapid_destro_obj.o \\\n\trapid_final.o \\\n\trapid_var.o \\\n\t${TAO_FORTRAN_LIB} ${TAO_LIB} ${PETSC_LIB} ${NETCDF_LIB}\n\t${RM} *.o *.mod \n\tln -sf ../src/rapid ../run/rapid\n\tln -sf ../src/rapid ../rtk/rapid\n\n#-------------------------------------------------------------------------------\n#Compile RAPID\n#-------------------------------------------------------------------------------\nrapid_main.o: \trapid_main.F90 rapid_var.mod \n\t${FLINKER} ${FPPFLAGS} -c rapid_main.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE} \n\nrapid_final.o:\t\trapid_final.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_final.F90 ${PETSC_FC_INCLUDES}\n\nrapid_destro_obj.o: \trapid_destro_obj.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_destro_obj.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_phiroutine.o: \trapid_phiroutine.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_phiroutine.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE} \n\nrapid_routing.o: \trapid_routing.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_routing.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_init.o: \t\trapid_read_namelist.o rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_init.F90 ${PETSC_FC_INCLUDES}\n\nrapid_routing_param.o: \trapid_routing_param.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_routing_param.F90 ${PETSC_FC_INCLUDES}\n\nrapid_obs_mat.o: \trapid_obs_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_obs_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_net_mat_brk.o: \trapid_net_mat_brk.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_net_mat_brk.F90 ${PETSC_FC_INCLUDES}\n\nrapid_net_mat.o: \trapid_net_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_net_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_hsh_mat.o: \trapid_hsh_mat.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_hsh_mat.F90 ${PETSC_FC_INCLUDES}\n\nrapid_get_Qdam.o: \trapid_get_Qdam.F90 rapid_var.mod \n\t${FLINKER} ${FPPFLAGS} -c rapid_get_Qdam.F90 ${PETSC_FC_INCLUDES}\n\nrapid_set_Qext0.o: \trapid_set_Qext0.F90 rapid_var.mod \n\t${FLINKER} ${FPPFLAGS} -c rapid_set_Qext0.F90 ${PETSC_FC_INCLUDES}\n\nrapid_close_Qfor_file.o: \trapid_close_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qfor_file.F90\n\nrapid_close_Qhum_file.o: \trapid_close_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qhum_file.F90\n\nrapid_close_Qobs_file.o: \trapid_close_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qobs_file.F90\n\nrapid_close_Vlat_file.o: \trapid_close_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Vlat_file.F90 ${NETCDF_INCLUDE} \n\nrapid_close_Qout_file.o: \trapid_close_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_close_Qout_file.F90 ${NETCDF_INCLUDE} \n\nrapid_read_Qfor_file.o: \trapid_read_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qfor_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Qhum_file.o: \trapid_read_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qhum_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Qobs_file.o: \trapid_read_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Qobs_file.F90 ${PETSC_FC_INCLUDES}\n\nrapid_read_Vlat_file.o: \trapid_read_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_Vlat_file.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_write_Qout_file.o: \trapid_write_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_write_Qout_file.F90 ${PETSC_FC_INCLUDES} ${NETCDF_INCLUDE}\n\nrapid_open_Qfor_file.o: \trapid_open_Qfor_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qfor_file.F90 \n\nrapid_open_Qhum_file.o: \trapid_open_Qhum_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qhum_file.F90 \n\nrapid_open_Qobs_file.o: \trapid_open_Qobs_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qobs_file.F90 \n\nrapid_open_Vlat_file.o: \trapid_open_Vlat_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Vlat_file.F90 ${NETCDF_INCLUDE}\n\nrapid_open_Qout_file.o: \trapid_open_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_open_Qout_file.F90 ${NETCDF_INCLUDE}\n\nrapid_create_Qout_file.o: \trapid_create_Qout_file.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_create_Qout_file.F90 ${NETCDF_INCLUDE}\n\nrapid_create_obj.o: \trapid_create_obj.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_create_obj.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE}\n\nrapid_arrays.o:\trapid_arrays.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_arrays.F90 ${PETSC_FC_INCLUDES}\n\t\nrapid_read_namelist.o:\trapid_read_namelist.F90 rapid_var.mod\n\t${FLINKER} ${FPPFLAGS} -c rapid_read_namelist.F90\n\t\nrapid_var.o rapid_var.mod:\trapid_var.F90\n\t${FLINKER} ${FPPFLAGS} -c rapid_var.F90 ${PETSC_FC_INCLUDES} ${TAO_INCLUDE} \n\t\n#-------------------------------------------------------------------------------\n#Clean\n#-------------------------------------------------------------------------------\nclean::\n\t${RM} *.o *.mod rapid ../run/rapid ../rtk/rapid\n\n"
  },
  {
    "path": "src/Rapid_routing/rapid_arrays.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_arrays\n!*******************************************************************************\nsubroutine rapid_arrays\n\n!Purpose:\n!Create arrays from input files that are useful for RAPID.\n!for all simulations, RAPID can run on a subset of all available river reaches\n!of the domain.\n!Three Fortran vectors are useful here:\n! - IV_riv_bas_id(IS_riv_bas) allows to know the IDs of the subbasin studied\n! - IV_riv_bas_index(IS_riv_bas) allows to know where the flow values are\n!   located in Vlat_file using the 1-based ZV_read_riv_tot\n! - IV_riv_bas_loc1(IS_riv_bas) allows to know where to ad dthe flow values in\n!   the current modeling domain using the 0-based ZV_Qout\n!When human-induced option is activated, the flow entering each given river ID\n!is read from a file and added to the inflow the corresponding river.\n!Three Fortran vectors are useful here:\n! - IV_hum_bas_id(IS_hum_bas) allows to know the IDs of the humand-induced flows\n!   locations into the subbasin\n! - IV_hum_index(IS_hum_bas) allows to know where the flow values are\n!   located in Qhum_file using the 1-based ZV_read_hum_tot\n! - IV_hum_loc1(IS_hum_bas) allows to know where to add the flow values\n!   in the current modeling domain using the 0-based ZV_Qhum\n!When forcing option is activated, the flow exiting each given river ID is\n!read from a file and added to the inflow of its downstream river.\n!Three Fortran vectors are useful here:\n! - IV_for_bas_id(IS_for_bas) allows to know the IDs of the forcing locations\n!   flowing into the subbasin\n! - IV_for_index(IS_for_bas) allows to know where the flow values are\n!   located in Qfor_file using the 1-based ZV_read_for_tot\n! - IV_for_loc2(IS_for_bas) allows to know where to add the flow values\n!   in the current modeling domain using the 0-based ZV_Qfor\n!When dam option is activated, the flow exiting each given river ID is\n!obtained from a model and added to the inflow of its downstream river.\n!Four Fortran vectors are useful here:\n! - IV_dam_bas_id(IS_dam_bas) allows to know the IDs of the dam locations\n!   in the subbasin\n! - IV_dam_index(IS_dam_bas) allows to know where the flow values are\n!   located in dam model array using the 1-based ZV_read_dam_tot\n! - IV_dam_loc2(IS_dam_bas) allows to know where to add the flow values\n!   in the current modeling domain using the 0-based ZV_Qdam\n! - IV_dam_pos(IS_dam_bas) allows to know where to read the flow values for the\n!   dam model in the current modeling domain using the 0-based ZV_Qdam\n!When RAPID is run in optimization mode, the flow measured at each given river\n!ID is read from a file and compared to computations.\n!Three Fortran vectors are useful here:\n! - IV_obs_bas_id(IS_obs_bas) allows to know the IDs of the observations\n! - IV_obs_index(IS_obs_bas) allows to know where the flow values are\n!   located in Qobs_file using the 1-based ZV_read_obs_tot\n! - IV_obs_loc1(IS_obs_bas) allows to know where to put the flow values\n!   in the current modeling domain using the 0-based ZV_Qobs\n!Author:\n!Cedric H. David, 2014-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   rapid_connect_file,                                         &\n                   IS_riv_tot,JS_riv_tot,JS_up,                                &\n                   IV_riv_tot_id,IV_down,IV_nbup,IM_up,IM_index_up,            &\n                   riv_bas_id_file,                                            &\n                   IS_riv_bas,JS_riv_bas,JS_riv_bas2,                          &\n                   ZM_hsh_tot,ZM_hsh_bas,                                      &\n                   IV_riv_bas_id,IV_riv_index,IV_riv_loc1,                     &\n                   BS_opt_hum,                                                 &\n                   hum_tot_id_file,                                            &\n                   IS_hum_tot,JS_hum_tot,                                      &\n                   IV_hum_tot_id,                                              &\n                   hum_use_id_file,                                            &\n                   IV_hum_use_id,                                              &\n                   IS_hum_use,JS_hum_use,                                      &\n                   IS_hum_bas,JS_hum_bas,                                      &\n                   IV_hum_bas_id,IV_hum_index,IV_hum_loc1,                     &\n                   BS_opt_for,                                                 &\n                   for_tot_id_file,                                            &\n                   IS_for_tot,JS_for_tot,                                      &\n                   IV_for_tot_id,                                              &\n                   for_use_id_file,                                            &\n                   IV_for_use_id,                                              &\n                   IS_for_use,JS_for_use,                                      &\n                   IS_for_bas,JS_for_bas,                                      &\n                   IV_for_bas_id,IV_for_index,IV_for_loc2,IV_dam_pos,          &\n                   BS_opt_dam,                                                 &\n                   dam_tot_id_file,                                            &\n                   IS_dam_tot,JS_dam_tot,                                      &\n                   IV_dam_tot_id,                                              &\n                   dam_use_id_file,                                            &\n                   IV_dam_use_id,                                              &\n                   IS_dam_use,JS_dam_use,                                      &\n                   IS_dam_bas,JS_dam_bas,                                      &\n                   IV_dam_bas_id,IV_dam_index,IV_dam_loc2,                     &\n                   IS_opt_run,                                                 &\n                   obs_tot_id_file,                                            &\n                   IS_obs_tot,JS_obs_tot,                                      &\n                   IV_obs_tot_id,                                              &\n                   obs_use_id_file,                                            &\n                   IV_obs_use_id,                                              &\n                   IS_obs_use,JS_obs_use,                                      &\n                   IS_obs_bas,JS_obs_bas,                                      &\n                   IV_obs_index,IV_obs_loc1,                                   &\n                   BS_logical,temp_char,rank,ierr,IS_one,ZS_val\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n#include \"finclude/petsclog.h\"\n!PETSc log\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Relationship between entire domain and study basin\n!*******************************************************************************\n\n!-------------------------------------------------------------------------------\n!Read data files\n!-------------------------------------------------------------------------------\nopen(10,file=rapid_connect_file,status='old')\ndo JS_riv_tot=1,IS_riv_tot\n     read(10,*) IV_riv_tot_id(JS_riv_tot), IV_down(JS_riv_tot),                &\n                IV_nbup(JS_riv_tot), IM_up(JS_riv_tot,:)\nenddo\nclose(10)\n\nopen(11,file=riv_bas_id_file,status='old')\ndo JS_riv_bas=1,IS_riv_bas\n     read(11,*) IV_riv_bas_id(JS_riv_bas)\nend do\nclose(11)\n\n!-------------------------------------------------------------------------------\n!Populate hashtable-like matrices\n!-------------------------------------------------------------------------------\ncall rapid_hsh_mat\n\n!-------------------------------------------------------------------------------\n!Calculate IS_riv_bas\n!-------------------------------------------------------------------------------\n!This is actually given in the namelist\n\n!-------------------------------------------------------------------------------\n!Allocate and initialize IV_riv_index, IV_riv_loc1, and IM_index_up\n!-------------------------------------------------------------------------------\n!Allocation is actually done in rapid_init.F90\nIV_riv_index=0\nIV_riv_loc1=0\nIM_index_up=0\n\n!-------------------------------------------------------------------------------\n!Populate IV_riv_index\n!-------------------------------------------------------------------------------\ndo JS_riv_bas=1,IS_riv_bas\n     ZS_val=-999\n     call MatGetValues(ZM_hsh_tot,                                             &\n                       IS_one,rank,                                            &\n                       IS_one,IV_riv_bas_id(JS_riv_bas)-1,                     &\n                       ZS_val,ierr)\n     CHKERRQ(ierr)\n     JS_riv_tot=int(ZS_val)\n     if (JS_riv_tot>0) then\n          IV_riv_index(JS_riv_bas)=JS_riv_tot\n     else\n          write(temp_char,'(i10)') IV_riv_bas_id(JS_riv_bas)\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           'ERROR: reach ID' // temp_char //                   &\n                           ' not included in domain' // char(10),ierr)\n          stop\n     end if\nend do\n!vector with (Fortran, 1-based) indexes corresponding to reaches of basin\n!within whole network\n!IV_riv_index has two advantages.  1) it is needed in order to read inflow\n!data (Vlat for ex).  2) It allows to avoid one other nested loop in the\n!following, which reduces tremendously the computation time.\n\n!-------------------------------------------------------------------------------\n!Populate IV_riv_loc1\n!-------------------------------------------------------------------------------\ndo JS_riv_bas=1,IS_riv_bas\n     IV_riv_loc1(JS_riv_bas)=JS_riv_bas-1\nenddo\n!vector with zero-base index corresponding to one-base index\n\n!-------------------------------------------------------------------------------\n!Populate IM_index_up\n!-------------------------------------------------------------------------------\ndo JS_riv_bas2=1,IS_riv_bas\ndo JS_up=1, IV_nbup(IV_riv_index(JS_riv_bas2))\n     ZS_val=-999\n     call MatGetValues(ZM_hsh_bas,                                             &\n                       IS_one,rank,                                            &\n                       IS_one,IM_up(IV_riv_index(JS_riv_bas2),JS_up)-1,        &\n                       ZS_val,ierr)\n     CHKERRQ(ierr)\n     JS_riv_bas=int(ZS_val)\n     if (JS_riv_bas>0) IM_index_up(JS_riv_bas2,JS_up)=JS_riv_bas\nend do\nend do\n!Used in traditional Muskingum method and to quicken matrix prealloc. & creation\n\n!-------------------------------------------------------------------------------\n!Optional, display IV_riv_loc1, IV_riv_index, and IM_index_up\n!-------------------------------------------------------------------------------\n!if (rank==0) then\n!     print *, IV_riv_loc1\n!     print *, IV_riv_index\n!     do JS_riv_bas=1,IS_riv_bas\n!          print *, IM_index_up(JS_riv_bas,:)\n!     end do\n!end if\n\n\n!*******************************************************************************\n!If human-induced flows are used\n!*******************************************************************************\nif (BS_opt_hum) then\ncall PetscPrintf(PETSC_COMM_WORLD,'WARNING: Human-induced option activated' // &\n                 char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Read data files\n!-------------------------------------------------------------------------------\nopen(14,file=hum_tot_id_file,status='old')\nread(14,*) IV_hum_tot_id\nclose(14)\n\nopen(15,file=hum_use_id_file,status='old')\nread(15,*) IV_hum_use_id\nclose(15)\n\n!-------------------------------------------------------------------------------\n!Calculate IS_hum_bas\n!-------------------------------------------------------------------------------\nwrite(temp_char,'(i10)') IS_hum_tot\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of human-induced ' // &\n                 'IDs in hum_tot_id_file:' // temp_char // char(10),ierr)\n\nwrite(temp_char,'(i10)') IS_hum_use\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of human-induced ' // &\n                 'IDs in hum_use_id_file:' // temp_char // char(10),ierr)\n\nIS_hum_bas=0\n!initialize to zero\n\ndo JS_hum_use=1,IS_hum_use\n     do JS_riv_bas=1,IS_riv_bas\n          if (IV_hum_use_id(JS_hum_use)==IV_riv_bas_id(JS_riv_bas)) then\n               IS_hum_bas=IS_hum_bas+1\n          end if\n     end do\nend do\n\nwrite(temp_char,'(i10)') IS_hum_bas\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of human-induced ' // &\n                 'IDs in this simulation:' // temp_char // char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Allocate and initialize IV_hum_bas_id, IV_hum_index, IV_hum_loc1\n!-------------------------------------------------------------------------------\nallocate(IV_hum_bas_id(IS_hum_bas))\nallocate(IV_hum_index(IS_hum_bas))\nallocate(IV_hum_loc1(IS_hum_bas))\n\nIV_hum_bas_id=0\nIV_hum_index=0\nIV_hum_loc1=0\n\n!-------------------------------------------------------------------------------\n!Populate IV_hum_bas_id\n!-------------------------------------------------------------------------------\nif (IS_hum_bas>0) then\n\nJS_hum_bas=0\ndo JS_hum_use=1,IS_hum_use\ndo JS_riv_bas=1,IS_riv_bas\n     if (IV_hum_use_id(JS_hum_use)==IV_riv_bas_id(JS_riv_bas)) then\n          JS_hum_bas=JS_hum_bas+1\n          IV_hum_bas_id(JS_hum_bas)=IV_riv_bas_id(JS_riv_bas)\n     end if\nend do\nend do\n\nend if\n\n!-------------------------------------------------------------------------------\n!Populate IV_hum_index\n!-------------------------------------------------------------------------------\ndo JS_hum_bas=1,IS_hum_bas\ndo JS_hum_tot=1,IS_hum_tot\n     if (IV_hum_bas_id(JS_hum_bas)==IV_hum_tot_id(JS_hum_tot)) then\n          IV_hum_index(JS_hum_bas)=JS_hum_tot\n     end if\nend do\nend do\n\n!-------------------------------------------------------------------------------\n!Populate IV_hum_loc1\n!-------------------------------------------------------------------------------\ndo JS_hum_bas=1,IS_hum_bas\ndo JS_riv_bas=1,IS_riv_bas\n     if (IV_riv_bas_id(JS_riv_bas)==IV_hum_bas_id(JS_hum_bas)) then\n          IV_hum_loc1(JS_hum_bas)=JS_riv_bas-1\n     end if\nend do\nend do\n\n!-------------------------------------------------------------------------------\n!Print warning when human-induced is used\n!-------------------------------------------------------------------------------\nif (rank==0 .and. IS_hum_bas>0) then\n     print *, '        Human-induced flows added to computed flows, using:'\n     !print *, '        IV_hum_tot_id   =', IV_hum_tot_id\n     print *, '        IV_hum_use_id   =', IV_hum_use_id\n     print *, '        IV_hum_bas_id   =', IV_hum_bas_id\n     print *, '        IV_hum_index    =', IV_hum_index\n     print *, '        IV_hum_loc1     =', IV_hum_loc1\nend if\n!Warning about human-induced flows\n\n!-------------------------------------------------------------------------------\n!End if human-induced is used\n!-------------------------------------------------------------------------------\nend if\n\n\n!*******************************************************************************\n!If forcing is used\n!*******************************************************************************\nif (BS_opt_for) then\ncall PetscPrintf(PETSC_COMM_WORLD,'WARNING: Forcing option activated'//        &\n                 char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Read data files\n!-------------------------------------------------------------------------------\nopen(16,file=for_tot_id_file,status='old')\nread(16,*) IV_for_tot_id\nclose(16)\n\nopen(17,file=for_use_id_file,status='old')\nread(17,*) IV_for_use_id\nclose(17)\n\n!-------------------------------------------------------------------------------\n!Calculate IS_for_bas\n!-------------------------------------------------------------------------------\nwrite(temp_char,'(i10)') IS_for_tot\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of forcing IDs in ' //&\n                 'for_tot_id_file:' // temp_char // char(10),ierr)\n\nwrite(temp_char,'(i10)') IS_for_use\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of forcing IDs in ' //&\n                 'for_use_id_file:' // temp_char // char(10),ierr)\n\nIS_for_bas=0\n!initialize to zero\n\ndo JS_for_use=1,IS_for_use\n     do JS_riv_tot=1,IS_riv_tot\n          if (IV_for_use_id(JS_for_use)==IV_riv_tot_id(JS_riv_tot)) then\n\n     do JS_riv_bas=1,IS_riv_bas\n          if (IV_down(JS_riv_tot)==IV_riv_bas_id(JS_riv_bas)) then\n               IS_for_bas=IS_for_bas+1\n          end if\n     end do\n\n          end if\n     end do\nend do\n\nwrite(temp_char,'(i10)') IS_for_bas\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of forcing IDs in ' //&\n                 'this simulation:' // temp_char // char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Allocate and initialize the vectors IV_for_index and IV_for_loc2\n!-------------------------------------------------------------------------------\nallocate(IV_for_bas_id(IS_for_bas))\nallocate(IV_for_index(IS_for_bas))\nallocate(IV_for_loc2(IS_for_bas))\n\nIV_for_bas_id=0\nIV_for_index=0\nIV_for_loc2=0\n\n!-------------------------------------------------------------------------------\n!Populate IV_for_bas_id\n!-------------------------------------------------------------------------------\nif (IS_for_bas>0) then\n\nJS_for_bas=0\n!initialize to zero\n\ndo JS_for_use=1,IS_for_use\n     do JS_riv_tot=1,IS_riv_tot\n          if (IV_for_use_id(JS_for_use)==IV_riv_tot_id(JS_riv_tot)) then\n\n     do JS_riv_bas=1,IS_riv_bas\n          if (IV_down(JS_riv_tot)==IV_riv_bas_id(JS_riv_bas)) then\n               JS_for_bas=JS_for_bas+1\n               IV_for_bas_id(JS_for_bas)=IV_for_use_id(JS_for_use)\n          end if\n     end do\n\n          end if\n     end do\nend do\n\nend if\n\n!-------------------------------------------------------------------------------\n!Populate IV_for_index\n!-------------------------------------------------------------------------------\ndo JS_for_bas=1,IS_for_bas\ndo JS_for_tot=1,IS_for_tot\n     if (IV_for_bas_id(JS_for_bas)==IV_for_tot_id(JS_for_tot)) then\n          IV_for_index(JS_for_bas)=JS_for_tot\n     end if\nend do\nend do\n\n!-------------------------------------------------------------------------------\n!Populate IV_for_loc2\n!-------------------------------------------------------------------------------\ndo JS_for_bas=1,IS_for_bas\ndo JS_riv_tot=1,IS_riv_tot\n     if (IV_for_bas_id(JS_for_bas)==IV_riv_tot_id(JS_riv_tot)) then\n          do JS_riv_bas=1,IS_riv_bas\n\nif (IV_down(JS_riv_tot)==IV_riv_bas_id(JS_riv_bas)) then\n     IV_for_loc2(JS_for_bas)=IV_riv_loc1(JS_riv_bas)\nend if\n\n          end do\n     end if\nend do\nend do\n\n!-------------------------------------------------------------------------------\n!Print warning when forcing is used\n!-------------------------------------------------------------------------------\nif (rank==0 .and. IS_for_bas>0) then\n     print *, '        Forcing flows replace computed flows, using:'\n     !print *, '        IV_for_tot_id   =', IV_for_tot_id\n     print *, '        IV_for_use_id   =', IV_for_use_id\n     print *, '        IV_for_bas_id   =', IV_for_bas_id\n     print *, '        IV_for_index    =', IV_for_index\n     print *, '        IV_for_loc2     =', IV_for_loc2\nend if\n!Warning about forcing downstream basins\n\n!-------------------------------------------------------------------------------\n!End if forcing is used\n!-------------------------------------------------------------------------------\nend if\n\n\n!*******************************************************************************\n!If dam model is used\n!*******************************************************************************\nif (BS_opt_dam) then\ncall PetscPrintf(PETSC_COMM_WORLD,'WARNING: Dam option activated'//            &\n                 char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Read data files\n!-------------------------------------------------------------------------------\nopen(18,file=dam_tot_id_file,status='old')\nread(18,*) IV_dam_tot_id\nclose(18)\n\nopen(19,file=dam_use_id_file,status='old')\nread(19,*) IV_dam_use_id\nclose(19)\n\n!-------------------------------------------------------------------------------\n!Calculate IS_dam_bas\n!-------------------------------------------------------------------------------\nwrite(temp_char,'(i10)') IS_dam_tot\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of dam IDs in ' //    &\n                 'dam_tot_id_file:' // temp_char // char(10),ierr)\n\nwrite(temp_char,'(i10)') IS_dam_use\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of dam IDs in ' //    &\n                 'dam_use_id_file:' // temp_char // char(10),ierr)\n\nIS_dam_bas=0\n\ndo JS_dam_use=1,IS_dam_use\ndo JS_riv_bas=1,IS_riv_bas\n     if (IV_dam_use_id(JS_dam_use)==IV_riv_tot_id(IV_riv_index(JS_riv_bas)))then\n          IS_dam_bas=IS_dam_bas+1\n     end if\nend do\nend do\n\nwrite(temp_char,'(i10)') IS_dam_bas\ncall PetscPrintf(PETSC_COMM_WORLD,'         Total number of dam IDs in ' //    &\n                 'this simulation:' // temp_char // char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Allocate and initialize IV_dam_bas_id, IV_dam_index, IV_dam_loc2, IV_dam_pos\n!-------------------------------------------------------------------------------\nallocate(IV_dam_bas_id(IS_dam_bas))\nallocate(IV_dam_index(IS_dam_bas))\nallocate(IV_dam_loc2(IS_dam_bas))\nallocate(IV_dam_pos(IS_dam_tot))\n\nIV_dam_bas_id=0\nIV_dam_index=0\nIV_dam_loc2=0\nIV_dam_pos=0\n\n!-------------------------------------------------------------------------------\n!Populate IV_dam_bas_id\n!-------------------------------------------------------------------------------\nif (IS_dam_bas>0) then\n\nJS_dam_bas=0\n\ndo JS_dam_use=1,IS_dam_use\ndo JS_riv_bas=1,IS_riv_bas\n     if (IV_dam_use_id(JS_dam_use)==IV_riv_tot_id(IV_riv_index(JS_riv_bas)))then\n          JS_dam_bas=JS_dam_bas+1\n          IV_dam_bas_id(JS_dam_bas)=IV_riv_tot_id(IV_riv_index(JS_riv_bas))\n     end if\nend do\nend do\n\nend if\n\n!-------------------------------------------------------------------------------\n!Populate IV_dam_index\n!-------------------------------------------------------------------------------\ndo JS_dam_bas=1,IS_dam_bas\ndo JS_dam_tot=1,IS_dam_tot\n     if (IV_dam_bas_id(JS_dam_bas)==IV_dam_tot_id(JS_dam_tot)) then\n          IV_dam_index(JS_dam_bas)=JS_dam_tot\n     end if\nend do\nend do\n\n!-------------------------------------------------------------------------------\n!Populate IV_dam_loc2\n!-------------------------------------------------------------------------------\ndo JS_dam_bas=1,IS_dam_bas\ndo JS_riv_tot=1,IS_riv_tot\n     if (IV_dam_bas_id(JS_dam_bas)==IV_riv_tot_id(JS_riv_tot)) then\n          do JS_riv_bas=1,IS_riv_bas\n\nif (IV_riv_bas_id(JS_riv_bas)==IV_down(JS_riv_tot)) then\n          IV_dam_loc2(JS_dam_bas)=JS_riv_bas-1\nend if\n          end do\n     end if\nend do\nend do\n\n!-------------------------------------------------------------------------------\n!Populate IV_dam_pos\n!-------------------------------------------------------------------------------\ndo JS_dam_tot=1,IS_dam_tot\ndo JS_riv_bas=1,IS_riv_bas\n     if (IV_dam_tot_id(JS_dam_tot)==IV_riv_bas_id(JS_riv_bas)) then\n          IV_dam_pos(JS_dam_tot)=JS_riv_bas\n     end if\nend do\nend do\n\n!-------------------------------------------------------------------------------\n!Print warning when dam model is used\n!-------------------------------------------------------------------------------\nif (rank==0 .and. IS_dam_bas>0) then\n     print *, '        Dam flows replace computed flows, using:'\n     !print *, '        IV_dam_tot_id   =', IV_dam_tot_id\n     print *, '        IV_dam_use_id   =', IV_dam_use_id\n     print *, '        IV_dam_bas_id   =', IV_dam_bas_id\n     print *, '        IV_dam_index    =', IV_dam_index\n     print *, '        IV_dam_loc2     =', IV_dam_loc2\nend if\n\nif (rank==0 .and. IS_dam_tot>0) then\n     print *, '        IV_dam_pos      =', IV_dam_pos\nend if\n!Warning about forcing downstream basins\n\n!-------------------------------------------------------------------------------\n!End if dam model is used\n!-------------------------------------------------------------------------------\nend if\n\n\n!*******************************************************************************\n!If optimization mode is selected\n!*******************************************************************************\nif (IS_opt_run==2) then\n\n!-------------------------------------------------------------------------------\n!Read data files\n!-------------------------------------------------------------------------------\nopen(12,file=obs_tot_id_file,status='old')\nread(12,*) IV_obs_tot_id\nclose(12)\n\nopen(13,file=obs_use_id_file,status='old')\nread(13,*) IV_obs_use_id\nclose(13)\n\n!-------------------------------------------------------------------------------\n!Calculate IS_obs_bas\n!-------------------------------------------------------------------------------\nwrite(temp_char,'(i10)') IS_obs_tot\ncall PetscPrintf(PETSC_COMM_WORLD,'Number of gage IDs in obs_tot_file '    //  &\n                 '                  :' // temp_char // char(10),ierr)\nwrite(temp_char,'(i10)') IS_obs_use\ncall PetscPrintf(PETSC_COMM_WORLD,'Number of gage IDs in obs_use_file '    //  &\n                 '                  :' // temp_char // char(10),ierr)\n\nIS_obs_bas=0\n!initialize to zero\n\ndo JS_obs_use=1,IS_obs_use\n     do JS_riv_bas=1,IS_riv_bas\n          if (IV_obs_use_id(JS_obs_use)==IV_riv_bas_id(JS_riv_bas)) then\n               IS_obs_bas=IS_obs_bas+1\n          end if\n     end do\nend do\n\nwrite(temp_char,'(i10)') IS_obs_bas\ncall PetscPrintf(PETSC_COMM_WORLD,'Number of gage IDs in '                 //  &\n                 'this simulation                :'//temp_char // char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Allocate and initialize the vectors IV_obs_index and IV_obs_loc1\n!-------------------------------------------------------------------------------\nallocate(IV_obs_index(IS_obs_bas))\nallocate(IV_obs_loc1(IS_obs_bas))\n!allocate vector size\n\ndo JS_obs_bas=1,IS_obs_bas\n     IV_obs_index(JS_obs_bas)=0\n     IV_obs_loc1(JS_obs_bas)=0\nend do\n!Initialize both vectors to zero\n\n!-------------------------------------------------------------------------------\n!Populate the vectors IV_obs_index and IV_obs_loc1\n!-------------------------------------------------------------------------------\nJS_obs_bas=1\ndo JS_obs_use=1,IS_obs_use\ndo JS_riv_bas=1,IS_riv_bas\n     if (IV_obs_use_id(JS_obs_use)==IV_riv_bas_id(JS_riv_bas)) then\n          do JS_obs_tot=1,IS_obs_tot\n               if (IV_obs_use_id(JS_obs_use)==IV_obs_tot_id(JS_obs_tot)) then\n                    IV_obs_index(JS_obs_bas)=JS_obs_tot\n               end if\n          end do\n          IV_obs_loc1(JS_obs_bas)=JS_riv_bas-1\n          JS_obs_bas=JS_obs_bas+1\n     end if\nend do\nend do\n!Create vector IV_obs_index and IV_obs_loc1\n\n!-------------------------------------------------------------------------------\n!Optional - Display vectors\n!-------------------------------------------------------------------------------\n!if (rank==0) then\n!     print *, 'IV_obs_index=', IV_obs_index\n!     print *, 'IV_obs_loc1  =', IV_obs_loc1\n!end if\n\n!-------------------------------------------------------------------------------\n!End if optimization mode is selected\n!-------------------------------------------------------------------------------\nend if\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\ncall PetscPrintf(PETSC_COMM_WORLD,'Arrays created'//char(10),ierr)\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\nend subroutine rapid_arrays\n"
  },
  {
    "path": "src/Rapid_routing/rapid_close_Qfor_file.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_close_Qfor_file\r\n!*******************************************************************************\r\nsubroutine rapid_close_Qfor_file\r\n\r\n!Purpose:\r\n!Close Qfor_file from Fortran.\r\n!Author:\r\n!Cedric H. David, 2013-2015.\r\n\r\n\r\n!*******************************************************************************\r\n!Global variables\r\n!*******************************************************************************\r\nuse rapid_var, only :                                                          &\r\n                   rank\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Intent (in/out), and local variables\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Close file\r\n!*******************************************************************************\r\nif (rank==0) close(34)\r\n\r\n!*******************************************************************************\r\n!End subroutine\r\n!*******************************************************************************\r\nend subroutine rapid_close_Qfor_file\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_close_Qhum_file.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_close_Qhum_file\r\n!*******************************************************************************\r\nsubroutine rapid_close_Qhum_file\r\n\r\n!Purpose:\r\n!Close Qhum_file from Fortran.\r\n!Author:\r\n!Cedric H. David, 2014-2015.\r\n\r\n\r\n!*******************************************************************************\r\n!Global variables\r\n!*******************************************************************************\r\nuse rapid_var, only :                                                          &\r\n                   rank\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Intent (in/out), and local variables\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Close file\r\n!*******************************************************************************\r\nif (rank==0) close(36)\r\n\r\n!*******************************************************************************\r\n!End subroutine\r\n!*******************************************************************************\r\nend subroutine rapid_close_Qhum_file\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_close_Qobs_file.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_close_Qobs_file\r\n!*******************************************************************************\r\nsubroutine rapid_close_Qobs_file\r\n\r\n!Purpose:\r\n!Close Qobs_file from Fortran.\r\n!Author:\r\n!Cedric H. David, 2013-2015.\r\n\r\n\r\n!*******************************************************************************\r\n!Global variables\r\n!*******************************************************************************\r\nuse rapid_var, only :                                                          &\r\n                   rank\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Intent (in/out), and local variables\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Close file\r\n!*******************************************************************************\r\nif (rank==0) close(33)\r\n\r\n!*******************************************************************************\r\n!End subroutine\r\n!*******************************************************************************\r\nend subroutine rapid_close_Qobs_file\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_close_Qout_file.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_close_Qout_file\r\n!*******************************************************************************\r\nsubroutine rapid_close_Qout_file\r\n\r\n!Purpose:\r\n!Close Qout_file from Fortran/netCDF.\r\n!Author:\r\n!Cedric H. David, 2013-2015.\r\n\r\n\r\n!*******************************************************************************\r\n!Global variables\r\n!*******************************************************************************\r\nuse netcdf\r\nuse rapid_var, only :                                                          &\r\n                   rank,IS_nc_status,IS_nc_id_fil_Qout\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Intent (in/out), and local variables\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Close file\r\n!*******************************************************************************\r\nif (rank==0) IS_nc_status=NF90_CLOSE(IS_nc_id_fil_Qout)\r\n\r\n\r\n!*******************************************************************************\r\n!End subroutine\r\n!*******************************************************************************\r\nend subroutine rapid_close_Qout_file\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_close_Vlat_file.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_close_Vlat_file\r\n!*******************************************************************************\r\nsubroutine rapid_close_Vlat_file\r\n\r\n!Purpose:\r\n!Close Qobs_file from Fortran/netCDF.\r\n!Author:\r\n!Cedric H. David, 2013-2015.\r\n\r\n\r\n!*******************************************************************************\r\n!Global variables\r\n!*******************************************************************************\r\nuse netcdf\r\nuse rapid_var, only :                                                          &\r\n                   rank,IS_nc_status,IS_nc_id_fil_Vlat\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Intent (in/out), and local variables\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n\r\n\r\n!*******************************************************************************\r\n!Close file\r\n!*******************************************************************************\r\nif (rank==0) IS_nc_status=NF90_CLOSE(IS_nc_id_fil_Vlat)\r\n\r\n\r\n!*******************************************************************************\r\n!End subroutine\r\n!*******************************************************************************\r\nend subroutine rapid_close_Vlat_file\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_create_Qout_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_create_Qout_file\n!*******************************************************************************\nsubroutine rapid_create_Qout_file(Qout_file)\n\n!Purpose:\n!Create Qout_file from Fortran/netCDF.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse netcdf\nuse rapid_var, only :                                                          &\n                   rank,                                                       &\n                   IS_nc_status,IS_nc_id_fil_Qout,                             &\n                   IS_nc_id_dim_time,IS_nc_id_dim_comid,IV_nc_id_dim,          &\n                   IS_nc_id_var_Qout,IS_nc_id_var_comid,                       &\n                   IV_riv_bas_id,IS_riv_bas\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\ncharacter(len=100), intent(in):: Qout_file\n\n\n!*******************************************************************************\n!Open file\n!*******************************************************************************\nif (rank==0) then\n\n     IS_nc_status=NF90_CREATE(Qout_file,NF90_CLOBBER,IS_nc_id_fil_Qout)\n     IS_nc_status=NF90_DEF_DIM(IS_nc_id_fil_Qout,'Time',NF90_UNLIMITED,        &\n                               IS_nc_id_dim_time)\n     IS_nc_status=NF90_DEF_DIM(IS_nc_id_fil_Qout,'COMID',IS_riv_bas,           &\n                               IS_nc_id_dim_comid)\n     IS_nc_status=NF90_DEF_VAR(IS_nc_id_fil_Qout,'COMID',NF90_INT,             &\n                               IS_nc_id_dim_comid,IS_nc_id_var_comid)\n     IV_nc_id_dim(1)=IS_nc_id_dim_comid\n     IV_nc_id_dim(2)=IS_nc_id_dim_time\n     IS_nc_status=NF90_DEF_VAR(IS_nc_id_fil_Qout,'Qout',NF90_REAL,             &\n                               IV_nc_id_dim,IS_nc_id_var_Qout)\n     IS_nc_status=NF90_ENDDEF(IS_nc_id_fil_Qout)\n     IS_nc_status=NF90_PUT_VAR(IS_nc_id_fil_Qout,IS_nc_id_var_comid,           &\n                               IV_riv_bas_id)\n     IS_nc_status=NF90_CLOSE(IS_nc_id_fil_Qout)\n\nend if\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_create_Qout_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_create_obj.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_create_obj\n!*******************************************************************************\nsubroutine rapid_create_obj\n\n!Purpose:\n!All PETSc and TAO objects need be created (requirement of both mathematical\n!libraries).  PETSc and TAO also need be initialized.  This is what's done here.\n!Author:\n!Cedric H. David, 2008-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   IS_riv_bas,                                                 &\n                   ZM_hsh_tot,ZM_hsh_bas,IS_riv_id_max,                        &\n                   ZM_Net,ZM_A,ZM_T,ZM_TC1,                                    &\n                   ZM_Obs,ZV_Qobs,ZV_temp1,ZV_temp2,ZV_kfac,                   &\n                   ZV_k,ZV_x,ZV_p,ZV_pnorm,ZV_pfac,                            &\n                   ZV_C1,ZV_C2,ZV_C3,ZV_Cdenom,                                &\n                   ZV_b,ZV_babsmax,ZV_bhat,                                    &\n                   ZV_Qext,ZV_Qfor,ZV_Qlat,ZV_Qhum,ZV_Qdam,                    &\n                   ZV_Vext,ZV_Vfor,ZV_Vlat,                                    &\n                   ZV_VinitM,ZV_QoutinitM,ZV_QoutinitO,ZV_QoutbarO,            &\n                   ZV_QoutR,ZV_QoutinitR,ZV_QoutprevR,ZV_QoutbarR,ZV_QinbarR,  &\n                   ZV_QoutRabsmin,ZV_QoutRabsmax,ZV_QoutRhat,                  &\n                   ZV_VR,ZV_VinitR,ZV_VprevR,ZV_VbarR,ZV_VoutR,                &\n                   ZV_Qobsbarrec,                                              &\n                   ierr,ksp,vecscat,ZV_SeqZero,ZS_one,ZV_one,IS_one,ncore,rank\n\n#ifndef NO_TAO\nuse rapid_var, only :                                                          &\n                   tao,reason,ZV_1stIndex,ZV_2ndIndex\n#endif\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n\n#ifndef NO_TAO\n#include \"finclude/taosolver.h\"\n!TAO solver\n#endif\n\n\n!*******************************************************************************\n!Initialize PETSc and TAO, and create all the objects\n!*******************************************************************************\n\n!Initialize PETSc --------------------------------------------------------------\ncall PetscInitialize(PETSC_NULL_CHARACTER,ierr)\n\n!Determine number associated with each processor -------------------------------\ncall MPI_Comm_rank(PETSC_COMM_WORLD,rank,ierr)\n\n!Determine total number of cores used ------------------------------------------\ncall MPI_Comm_size(PETSC_COMM_WORLD,ncore,ierr)\n\n!Create PETSc object that manages all Krylov methods ---------------------------\ncall KSPCreate(PETSC_COMM_WORLD,ksp,ierr)\n\n!Matrices-----------------------------------------------------------------------\ncall MatCreate(PETSC_COMM_WORLD,ZM_Net,ierr)\ncall MatSetSizes(ZM_Net,PETSC_DECIDE,PETSC_DECIDE,IS_riv_bas,IS_riv_bas,ierr)\ncall MatSetFromOptions(ZM_Net,ierr)\ncall MatSetUp(ZM_Net,ierr)\n\ncall MatCreate(PETSC_COMM_WORLD,ZM_A,ierr)\ncall MatSetSizes(ZM_A,PETSC_DECIDE,PETSC_DECIDE,IS_riv_bas,IS_riv_bas,ierr)\ncall MatSetFromOptions(ZM_A,ierr)\ncall MatSetUp(ZM_A,ierr)\n\ncall MatCreate(PETSC_COMM_WORLD,ZM_T,ierr)\ncall MatSetSizes(ZM_T,PETSC_DECIDE,PETSC_DECIDE,IS_riv_bas,IS_riv_bas,ierr)\ncall MatSetFromOptions(ZM_T,ierr)\ncall MatSetUp(ZM_T,ierr)\n\ncall MatCreate(PETSC_COMM_WORLD,ZM_TC1,ierr)\ncall MatSetSizes(ZM_TC1,PETSC_DECIDE,PETSC_DECIDE,IS_riv_bas,IS_riv_bas,ierr)\ncall MatSetFromOptions(ZM_TC1,ierr)\ncall MatSetUp(ZM_TC1,ierr)\n\ncall MatCreate(PETSC_COMM_WORLD,ZM_Obs,ierr)\ncall MatSetSizes(ZM_Obs,PETSC_DECIDE,PETSC_DECIDE,IS_riv_bas,IS_riv_bas,ierr)\ncall MatSetFromOptions(ZM_Obs,ierr)\ncall MatSetUp(ZM_Obs,ierr)\n!These matrices are all square of size IS_riv_bas.  PETSC_DECIDE allows PETSc\n!to determine the local sizes on its own. MatSetFromOptions allows to use many\n!different options at runtime, such as \"-mat_type aijmumps\".\n\ncall MatCreate(PETSC_COMM_WORLD,ZM_hsh_tot,ierr)\ncall MatSetSizes(ZM_hsh_tot,PETSC_DECIDE,PETSC_DECIDE,ncore,IS_riv_id_max,ierr)\ncall MatSetFromOptions(ZM_hsh_tot,ierr)\ncall MatSetUp(ZM_hsh_tot,ierr)\n\ncall MatCreate(PETSC_COMM_WORLD,ZM_hsh_bas,ierr)\ncall MatSetSizes(ZM_hsh_bas,PETSC_DECIDE,PETSC_DECIDE,ncore,IS_riv_id_max,ierr)\ncall MatSetFromOptions(ZM_hsh_bas,ierr)\ncall MatSetUp(ZM_hsh_bas,ierr)\n!These matrices are all mostly flat with size IS_riv_id_max*ncore and will store\n!the same row over all columns\n\n!Vectors of size IS_riv_bas-----------------------------------------------------\n!call VecCreateMPI(PETSC_COMM_WORLD,PETSC_DECIDE,IS_riv_bas,ZV_k,ierr)\ncall VecCreate(PETSC_COMM_WORLD,ZV_k,ierr)\ncall VecSetSizes(ZV_k,PETSC_DECIDE,IS_riv_bas,ierr)\ncall VecSetFromOptions(ZV_k,ierr)\n!same remarks as above for sizes\n\ncall VecDuplicate(ZV_k,ZV_x,ierr)\ncall VecDuplicate(ZV_k,ZV_C1,ierr)\ncall VecDuplicate(ZV_k,ZV_C2,ierr)\ncall VecDuplicate(ZV_k,ZV_C3,ierr)\ncall VecDuplicate(ZV_k,ZV_Cdenom,ierr)\n\ncall VecDuplicate(ZV_k,ZV_b,ierr)\ncall VecDuplicate(ZV_k,ZV_babsmax,ierr)\ncall VecDuplicate(ZV_k,ZV_bhat,ierr)\n\ncall VecDuplicate(ZV_k,ZV_Qext,ierr)\ncall VecDuplicate(ZV_k,ZV_Qfor,ierr)\ncall VecDuplicate(ZV_k,ZV_Qlat,ierr)\ncall VecDuplicate(ZV_k,ZV_Qhum,ierr)\ncall VecDuplicate(ZV_k,ZV_Qdam,ierr)\ncall VecDuplicate(ZV_k,ZV_Vext,ierr)\ncall VecDuplicate(ZV_k,ZV_Vfor,ierr)\ncall VecDuplicate(ZV_k,ZV_Vlat,ierr)\n\ncall VecDuplicate(ZV_k,ZV_QoutinitM,ierr)\ncall VecDuplicate(ZV_k,ZV_QoutinitO,ierr)\ncall VecDuplicate(ZV_k,ZV_QoutbarO,ierr)\n\ncall VecDuplicate(ZV_k,ZV_QoutR,ierr)\ncall VecDuplicate(ZV_k,ZV_QoutinitR,ierr)\ncall VecDuplicate(ZV_k,ZV_QoutprevR,ierr)\ncall VecDuplicate(ZV_k,ZV_QoutbarR,ierr)\ncall VecDuplicate(ZV_k,ZV_QinbarR,ierr)\ncall VecDuplicate(ZV_k,ZV_QoutRabsmin,ierr)\ncall VecDuplicate(ZV_k,ZV_QoutRabsmax,ierr)\ncall VecDuplicate(ZV_k,ZV_QoutRhat,ierr)\n\ncall VecDuplicate(ZV_k,ZV_VinitM,ierr)\n\ncall VecDuplicate(ZV_k,ZV_VR,ierr)\ncall VecDuplicate(ZV_k,ZV_VinitR,ierr)\ncall VecDuplicate(ZV_k,ZV_VprevR,ierr)\ncall VecDuplicate(ZV_k,ZV_VbarR,ierr)\ncall VecDuplicate(ZV_k,ZV_VoutR,ierr)\n\ncall VecDuplicate(ZV_k,ZV_temp1,ierr)\ncall VecDuplicate(ZV_k,ZV_temp2,ierr)\ncall VecDuplicate(ZV_k,ZV_Qobs,ierr)\ncall VecDuplicate(ZV_k,ZV_kfac,ierr)\ncall VecDuplicate(ZV_k,ZV_Qobsbarrec,ierr)\n!all the other vector objects are duplicates of the first one\n\n\n!Vectors of parameters----------------------------------------------------------\n!call VecCreateMPI(PETSC_COMM_WORLD,PETSC_DECIDE,IS_one*2,ZV_p,ierr)\ncall VecCreate(PETSC_COMM_WORLD,ZV_p,ierr)\ncall VecSetSizes(ZV_p,PETSC_DECIDE,2*IS_one,ierr)\ncall VecSetFromOptions(ZV_p,ierr)\n!same remarks as above for sizes\n\ncall VecDuplicate(ZV_p,ZV_pnorm,ierr)\ncall VecDuplicate(ZV_p,ZV_pfac,ierr)\n\n\n!Vectors and objects useful for PETSc programming-------------------------------\ncall VecDuplicate(ZV_k,ZV_one,ierr)\ncall VecSet(ZV_one,ZS_one,ierr)\n!this is a vector with ones a each row, used for computations\n\ncall VecScatterCreateToZero(ZV_k,vecscat,ZV_SeqZero,ierr)\n!create scatter context from a distributed vector to a sequential vector on the\n!zeroth processor.  Also creates the vector ZV_SeqZero\n\n\n!TAO specific-------------------------------------------------------------------\n#ifndef NO_TAO\ncall TaoInitialize(PETSC_NULL_CHARACTER,ierr)\n!Initialize TAO\n\ncall TaoCreate(PETSC_COMM_WORLD,tao,ierr)\ncall TaoSetType(tao,'tao_nm',ierr)\n!Create TAO App\n\ncall VecDuplicate(ZV_p,ZV_1stIndex,ierr)\ncall VecSetValues(ZV_1stIndex,IS_one,0*IS_one,ZS_one,INSERT_VALUES,ierr)\ncall VecAssemblyBegin(ZV_1stIndex,ierr)\ncall VecAssemblyEnd(ZV_1stIndex,ierr)\n!ZV_1stindex=[1;0]\n\ncall VecDuplicate(ZV_p,ZV_2ndIndex,ierr)\ncall VecSetValues(ZV_2ndIndex,IS_one,IS_one,ZS_one,INSERT_VALUES,ierr)\ncall VecAssemblyBegin(ZV_2ndIndex,ierr)\ncall VecAssemblyEnd(ZV_2ndIndex,ierr)\n!ZV_2ndindex=[0;1]\n#endif\n\nend subroutine rapid_create_obj\n"
  },
  {
    "path": "src/Rapid_routing/rapid_destro_obj.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_destro_obj\n!*******************************************************************************\nsubroutine rapid_destro_obj\n\n!Purpose:\n!All PETSc and TAO objects need be destroyed (requirement of both mathematical\n!libraries).  PETSc and TAO also need be finalized.  This is what's done here\n!Note: only finilized here, need to add destroy of vectors.\n!Author:\n!Cedric H. David, 2008-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   IS_riv_bas,                                                 &\n                   ZM_hsh_tot,ZM_hsh_bas,                                      &\n                   ZM_Net,ZM_A,ZM_T,ZM_TC1,                                    &\n                   ZM_Obs,ZV_Qobs,ZV_temp1,ZV_temp2,ZV_kfac,                   &\n                   ZV_k,ZV_x,ZV_p,ZV_pnorm,ZV_pfac,                            &\n                   ZV_C1,ZV_C2,ZV_C3,ZV_Cdenom,                                &\n                   ZV_b,ZV_babsmax,ZV_bhat,                                    &\n                   ZV_Qext,ZV_Qfor,ZV_Qlat,ZV_Qhum,ZV_Qdam,                    &\n                   ZV_Vext,ZV_Vfor,ZV_Vlat,                                    &\n                   ZV_VinitM,ZV_QoutinitM,ZV_QoutinitO,ZV_QoutbarO,            &\n                   ZV_QoutR,ZV_QoutinitR,ZV_QoutprevR,ZV_QoutbarR,ZV_QinbarR,  &\n                   ZV_QoutRabsmin,ZV_QoutRabsmax,ZV_QoutRhat,                  &\n                   ZV_VR,ZV_VinitR,ZV_VprevR,ZV_VbarR,ZV_VoutR,                &\n                   ZV_Qobsbarrec,                                              &\n                   ierr,ksp,vecscat,ZV_SeqZero,ZS_one,ZV_one,IS_one\n\n#ifndef NO_TAO\nuse rapid_var, only :                                                          &\n                   tao,reason,ZV_1stIndex,ZV_2ndIndex\n#endif\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n\n#ifndef NO_TAO\n#include \"finclude/taosolver.h\"\n!TAO solver\n#endif\n\n\n!*******************************************************************************\n!Destruct all objects and finalize PETSc and TAO\n!*******************************************************************************\n!TAO specific-------------------------------------------------------------------\n#ifndef NO_TAO\ncall VecDestroy(ZV_1stIndex,ierr)\ncall VecDestroy(ZV_2ndIndex,ierr)\ncall TaoDestroy(tao,ierr)\ncall TaoFinalize(ierr)\n#endif\n\ncall KSPDestroy(ksp,ierr)\n\ncall MatDestroy(ZM_hsh_tot,ierr)\ncall MatDestroy(ZM_hsh_bas,ierr)\n\ncall MatDestroy(ZM_A,ierr)\ncall MatDestroy(ZM_Net,ierr)\ncall MatDestroy(ZM_T,ierr)\ncall MatDestroy(ZM_TC1,ierr)\ncall MatDestroy(ZM_Obs,ierr)\n\ncall VecDestroy(ZV_k,ierr)\ncall VecDestroy(ZV_x,ierr)\ncall VecDestroy(ZV_C1,ierr)\ncall VecDestroy(ZV_C2,ierr)\ncall VecDestroy(ZV_C3,ierr)\ncall VecDestroy(ZV_Cdenom,ierr)\n\ncall VecDestroy(ZV_b,ierr)\ncall VecDestroy(ZV_babsmax,ierr)\ncall VecDestroy(ZV_bhat,ierr)\n\ncall VecDestroy(ZV_Qext,ierr)\ncall VecDestroy(ZV_Qfor,ierr)\ncall VecDestroy(ZV_Qlat,ierr)\ncall VecDestroy(ZV_Qhum,ierr)\ncall VecDestroy(ZV_Qdam,ierr)\ncall VecDestroy(ZV_Vext,ierr)\ncall VecDestroy(ZV_Vfor,ierr)\ncall VecDestroy(ZV_Vlat,ierr)\n\ncall VecDestroy(ZV_QoutinitM,ierr)\ncall VecDestroy(ZV_QoutinitO,ierr)\ncall VecDestroy(ZV_QoutbarO,ierr)\n\ncall VecDestroy(ZV_QoutR,ierr)\ncall VecDestroy(ZV_QoutinitR,ierr)\ncall VecDestroy(ZV_QoutprevR,ierr)\ncall VecDestroy(ZV_QoutbarR,ierr)\ncall VecDestroy(ZV_QinbarR,ierr)\ncall VecDestroy(ZV_QoutRabsmin,ierr)\ncall VecDestroy(ZV_QoutRabsmax,ierr)\ncall VecDestroy(ZV_QoutRhat,ierr)\n\ncall VecDestroy(ZV_VinitM,ierr)\n\ncall VecDestroy(ZV_VR,ierr)\ncall VecDestroy(ZV_VinitR,ierr)\ncall VecDestroy(ZV_VprevR,ierr)\ncall VecDestroy(ZV_VbarR,ierr)\ncall VecDestroy(ZV_VoutR,ierr)\n\ncall VecDestroy(ZV_temp1,ierr)\ncall VecDestroy(ZV_temp2,ierr)\ncall VecDestroy(ZV_Qobs,ierr)\ncall VecDestroy(ZV_kfac,ierr)\ncall VecDestroy(ZV_Qobsbarrec,ierr)\n\ncall VecDestroy(ZV_one,ierr)\n\ncall VecDestroy(ZV_p,ierr)\ncall VecDestroy(ZV_pnorm,ierr)\ncall VecDestroy(ZV_pfac,ierr)\n\ncall VecDestroy(ZV_SeqZero,ierr)\ncall VecScatterDestroy(vecscat,ierr)\n!Need to be destroyed separately even though created together\n\ncall PetscFinalize(ierr)\n\n\nend subroutine rapid_destro_obj\n"
  },
  {
    "path": "src/Rapid_routing/rapid_final.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_final\r\n!*******************************************************************************\r\nsubroutine rapid_final\r\n\r\n!Purpose:\r\n!This subroutine allows to finalize RAPID for both regular runs and\r\n!optimization runs, by performing slightly different tasks depending on what\r\n!option is chosen.\r\n!Finalization Initialization tasks specific to Option 1\r\n!     -Output final instantaneous flow\r\n!     -Output babsmax, QoutRabsmin and QoutRabsmax\r\n!Finalization Initialization tasks specific to Option 2\r\n!     -N/A\r\n!Finalization tasks common to all RAPID options:\r\n!     -Prints some information about the types of objects used during simulation\r\n!     -Destroy all PETSc and TAO objects\r\n!Author:\r\n!Cedric H. David, 2012-2015.\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables\r\n!*******************************************************************************\r\nuse rapid_var, only :                                                          &\r\n                   IS_riv_bas,JS_riv_bas,                                      &\r\n                   IS_opt_routing,IS_opt_run,                                  &\r\n                   BS_opt_Qfinal,BS_opt_influence,                             &\r\n                   Qfinal_file,babsmax_file,QoutRabsmin_file,QoutRabsmax_file, &\r\n                   ksp,vecscat,ZV_babsmax,ZV_QoutR,ZV_SeqZero,ierr,            &\r\n                   ZV_pointer,rank,ZV_k,temp_char,                             &\r\n                   ZV_QoutRabsmin,ZV_QoutRabsmax,                              &\r\n                   temp_char2,ZM_A,pc,                                         &\r\n                   IS_ksp_iter_max\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n#include \"finclude/petscsys.h\"\r\n!base PETSc routines\r\n#include \"finclude/petscvec.h\"\r\n#include \"finclude/petscvec.h90\"\r\n!vectors, and vectors in Fortran90\r\n#include \"finclude/petscmat.h\"\r\n!matrices\r\n#include \"finclude/petscksp.h\"\r\n!Krylov subspace methods\r\n#include \"finclude/petscpc.h\"\r\n!preconditioners\r\n#include \"finclude/petscviewer.h\"\r\n!viewers (allows writing results in file for example)\r\n#include \"finclude/petsclog.h\"\r\n!PETSc log\r\n\r\n\r\n!*******************************************************************************\r\n!Finalization procedure for OPTION 1\r\n!*******************************************************************************\r\nif (IS_opt_run==1) then\r\n\r\n!-------------------------------------------------------------------------------\r\n!Output final instantaneous Q (ZV_QoutR)\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_Qfinal) then\r\ncall VecScatterBegin(vecscat,ZV_QoutR,ZV_SeqZero,                              &\r\n                     INSERT_VALUES,SCATTER_FORWARD,ierr)\r\ncall VecScatterEnd(vecscat,ZV_QoutR,ZV_SeqZero,                                &\r\n                        INSERT_VALUES,SCATTER_FORWARD,ierr)\r\ncall VecGetArrayF90(ZV_SeqZero,ZV_pointer,ierr)\r\nif (rank==0) then\r\n     open(31,file=Qfinal_file)\r\n     do JS_riv_bas=1,IS_riv_bas\r\n          write(31,*) ZV_pointer(JS_riv_bas)\r\n     end do\r\n     close(31)\r\nend if\r\ncall VecRestoreArrayF90(ZV_SeqZero,ZV_pointer,ierr)\r\nend if\r\n\r\n!-------------------------------------------------------------------------------\r\n!Output maximum absolute values of vector b (right-hand side of linear system)\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_influence) then\r\ncall VecScatterBegin(vecscat,ZV_babsmax,ZV_SeqZero,                            &\r\n                     INSERT_VALUES,SCATTER_FORWARD,ierr)\r\ncall VecScatterEnd(vecscat,ZV_babsmax,ZV_SeqZero,                              &\r\n                        INSERT_VALUES,SCATTER_FORWARD,ierr)\r\ncall VecGetArrayF90(ZV_SeqZero,ZV_pointer,ierr)\r\nif (rank==0) then\r\n     open(42,file=babsmax_file)\r\n     do JS_riv_bas=1,IS_riv_bas\r\n          write(42,*) ZV_pointer(JS_riv_bas)\r\n     end do\r\n     close(42)\r\nend if\r\ncall VecRestoreArrayF90(ZV_SeqZero,ZV_pointer,ierr)\r\nend if\r\n\r\n!-------------------------------------------------------------------------------\r\n!Output minimum absolute values of instantaneous flow\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_influence) then\r\ncall VecScatterBegin(vecscat,ZV_QoutRabsmin,ZV_SeqZero,                        &\r\n                     INSERT_VALUES,SCATTER_FORWARD,ierr)\r\ncall VecScatterEnd(vecscat,ZV_QoutRabsmin,ZV_SeqZero,                          &\r\n                        INSERT_VALUES,SCATTER_FORWARD,ierr)\r\ncall VecGetArrayF90(ZV_SeqZero,ZV_pointer,ierr)\r\nif (rank==0) then\r\n     open(43,file=QoutRabsmin_file)\r\n     do JS_riv_bas=1,IS_riv_bas\r\n          write(43,*) ZV_pointer(JS_riv_bas)\r\n     end do\r\n     close(43)\r\nend if\r\ncall VecRestoreArrayF90(ZV_SeqZero,ZV_pointer,ierr)\r\nend if\r\n\r\n!-------------------------------------------------------------------------------\r\n!Output maximum absolute values of instantaneous flow\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_influence) then\r\ncall VecScatterBegin(vecscat,ZV_QoutRabsmax,ZV_SeqZero,                        &\r\n                     INSERT_VALUES,SCATTER_FORWARD,ierr)\r\ncall VecScatterEnd(vecscat,ZV_QoutRabsmax,ZV_SeqZero,                          &\r\n                        INSERT_VALUES,SCATTER_FORWARD,ierr)\r\ncall VecGetArrayF90(ZV_SeqZero,ZV_pointer,ierr)\r\nif (rank==0) then\r\n     open(44,file=QoutRabsmax_file)\r\n     do JS_riv_bas=1,IS_riv_bas\r\n          write(44,*) ZV_pointer(JS_riv_bas)\r\n     end do\r\n     close(44)\r\nend if\r\ncall VecRestoreArrayF90(ZV_SeqZero,ZV_pointer,ierr)\r\nend if\r\n\r\n!-------------------------------------------------------------------------------\r\n!End of initialization procedure for OPTION 1\r\n!-------------------------------------------------------------------------------\r\nend if\r\n\r\n\r\n!*******************************************************************************\r\n!Some information about types of objects used within RAPID run\r\n!*******************************************************************************\r\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\r\ncall VecGetType(ZV_k,temp_char,ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,'type of vector: '//temp_char//char(10),ierr)\r\ncall MatGetType(ZM_A,temp_char,ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,'type of matrix: '//temp_char//char(10),ierr)\r\nif (IS_opt_routing==1 .or. IS_opt_routing==3) then\r\n     call KSPGetType(ksp,temp_char,ierr)\r\nelse\r\n     temp_char='No KSP'\r\nend if\r\ncall PetscPrintf(PETSC_COMM_WORLD,'type of KSP   : '//temp_char//char(10),ierr)\r\nif (IS_opt_routing==1 .or. IS_opt_routing==3) then\r\n     call KSPGetPC(ksp,pc,ierr)\r\n     call PCGetType(pc,temp_char,ierr)\r\nelse\r\n     temp_char='No PC'\r\nend if\r\ncall PetscPrintf(PETSC_COMM_WORLD,'type of PC    : '//temp_char//char(10),ierr)\r\n#ifdef NO_TAO\r\ncall PetscPrintf(PETSC_COMM_WORLD,char(10),ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,'RAPID compiled and run without TAO',ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,char(10),ierr)\r\n#endif\r\nwrite(temp_char ,'(i10)') rank\r\nwrite(temp_char2,'(i10)') IS_ksp_iter_max\r\ncall PetscSynchronizedPrintf(PETSC_COMM_WORLD,'Rank     :'//temp_char //', '// &\r\n                                              'Max KSP  :'//temp_char2//       &\r\n                                               char(10),ierr)\r\ncall PetscSynchronizedFlush(PETSC_COMM_WORLD,ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,char(10)//char(10)//char(10)//char(10),ierr)\r\n\r\n!*******************************************************************************\r\n!Destroy all objects\r\n!*******************************************************************************\r\ncall rapid_destro_obj\r\n!destroy PETSc and TAO objects (Mat,Vec,taoapp...), finalizes the libraries\r\n\r\n\r\n!*******************************************************************************\r\n!End subroutine\r\n!*******************************************************************************\r\nend subroutine rapid_final\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_get_Qdam.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_get_Qdam\n!*******************************************************************************\nsubroutine rapid_get_Qdam\n\n!Purpose:\n!Communicate with a dam subroutine to exchange inflows and outflows.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   rank,ierr,vecscat,ZV_pointer,ZV_SeqZero,ZS_one,             &\n                   ZM_Net,ZV_Qext,ZV_Qdam,ZV_QoutbarR,ZV_QinbarR,              &\n                   IS_dam_bas,IV_dam_index,IV_dam_loc2,                        &\n                   IV_dam_pos\n\nuse rapid_var, only :                                                          &\n                   ZV_Qin_dam,ZV_Qout_dam,ZV_Qin_dam_prev,ZV_Qout_dam_prev\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n#include \"finclude/petsclog.h\"\n!PETSc log\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Compute previous inflow from river network and outside of river network to dams\n!*******************************************************************************\n!-------------------------------------------------------------------------------\n!Compute inflow into dams from previous river flow\n!-------------------------------------------------------------------------------\ncall MatMult(ZM_Net,ZV_QoutbarR,ZV_QinbarR,ierr)\ncall VecAXPY(ZV_QinbarR,ZS_one,ZV_Qext,ierr)\n!QinbarR=Net*QoutbarR+Qext\n\n!-------------------------------------------------------------------------------\n!Set values from PETSc vector into Fortran vector\n!-------------------------------------------------------------------------------\nif (rank==0) ZV_Qin_dam_prev=0\ncall VecScatterBegin(vecscat,ZV_QinbarR,ZV_SeqZero,                            &\n                     INSERT_VALUES,SCATTER_FORWARD,ierr)\ncall VecScatterEnd(vecscat,ZV_QinbarR,ZV_SeqZero,                              &\n                        INSERT_VALUES,SCATTER_FORWARD,ierr)\ncall VecGetArrayF90(ZV_SeqZero,ZV_pointer,ierr)\nif (rank==0) ZV_Qin_dam_prev=ZV_pointer(IV_dam_pos)\ncall VecRestoreArrayF90(ZV_SeqZero,ZV_pointer,ierr)\n!Get values from ZV_QinbarR (PETSc) into ZV_Qin_dam_prev (Fortran)\n\n\n!*******************************************************************************\n!Compute outflow from dams\n!*******************************************************************************\n!-------------------------------------------------------------------------------\n!If dam module does not exist, outflow is computed from this subroutine\n!-------------------------------------------------------------------------------\nif (rank==0) then\n     ZV_Qout_dam=ZV_Qin_dam_prev\nend if\n\n!-------------------------------------------------------------------------------\n!If dam module does exist, use it\n!-------------------------------------------------------------------------------\n!if (rank==0) then\n!     call dam_linear(ZV_Qin_dam_prev,ZV_Qout_dam_prev,ZV_Qout_dam)\n!end if\n\n\n!*******************************************************************************\n!Optional - Write information in stdout\n!*******************************************************************************\n!if (rank==0) print *, 'Qin_dam_prev  =', ',', ZV_Qin_dam_prev\n!if (rank==0) print *, 'Qin_dam_prev  =', ',', ZV_Qin_dam_prev(1)\n!if (rank==0) print *, 'Qout_dam_prev =', ',', ZV_Qout_dam_prev\n!if (rank==0) print *, 'Qout_dam_prev =', ',', ZV_Qout_dam_prev(1)\n!if (rank==0) print *, ZV_Qin_dam_prev(1), ',', ZV_Qout_dam_prev(1)\n!call VecView(ZV_Qdam,PETSC_VIEWER_STDOUT_WORLD,ierr)\n\n\n!*******************************************************************************\n!Set values from Fortran vector into PETSc vector\n!*******************************************************************************\nif (rank==0) then\n     call VecSetValues(ZV_Qdam,IS_dam_bas,IV_dam_loc2,                         &\n                       ZV_Qout_dam(IV_dam_index),INSERT_VALUES,ierr)\nend if\n\ncall VecAssemblyBegin(ZV_Qdam,ierr)\ncall VecAssemblyEnd(ZV_Qdam,ierr)\n\n\n!*******************************************************************************\n!Update ZV_Qout_dam_prev - After calling dam_linear to not override init. values\n!*******************************************************************************\nif (rank==0) then\n     ZV_Qout_dam_prev=ZV_Qout_dam\nend if\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_get_Qdam\n"
  },
  {
    "path": "src/Rapid_routing/rapid_hsh_mat.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_hsh_mat\n!*******************************************************************************\nsubroutine rapid_hsh_mat\n\n!Purpose:\n!This creates two hashtable-like sparse matrices:\n! - IM_hsh_tot contains the index over the domain (JS_riv_tot) corresponding to\n!   each reach ID and is the same for each row\n! - IM_hsh_bas contains the index over the basin (JS_riv_bas) corresponding to\n!   each reach ID and is the same for each row\n!The choice of matrices to mimic hashtables is possible because the \"keys\" (i.e.\n!the reach IDs) are all integers, and the sparse structure allows to keep memory\n!usage minimal because the number of unique reach IDs is far inferior to the\n!maximum integer value of reach ID.  Implementing a C++ hashtable within Fortran\n!would have required much more intrusive modifications to RAPID.\n!Thank you to Chris A. Mattmann and to Si Liu who both suggested the use of\n!hashtables to decrease model setup time.\n!Author:\n!Cedric H. David, 2015-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   IS_riv_tot,IS_riv_bas,                                      &\n                   JS_riv_tot,JS_riv_bas,                                      &\n                   IV_riv_tot_id,IV_riv_bas_id,                                &\n                   IS_riv_id_max,                                              &\n                   ZM_hsh_tot,ZM_hsh_bas,                                      &\n                   IS_ownfirst,IS_ownlast,                                     &\n                   IS_one,ZS_one,temp_char,temp_char2,ierr,rank,ncore\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\nPetscInt, dimension(ncore)  :: IS_nz, IS_dnz, IS_onz\nPetscInt, dimension(IS_riv_tot) :: IV_tot_tmp1, IV_tot_tmp2\nPetscInt, dimension(IS_riv_bas) :: IV_bas_tmp1, IV_bas_tmp2\n\n\n!*******************************************************************************\n!Check that reach IDs are within the allowed range\n!*******************************************************************************\nwrite(temp_char2,'(i10)') IS_riv_id_max\n\ndo JS_riv_tot=1,IS_riv_tot\n     if (IV_riv_tot_id(JS_riv_tot) > IS_riv_id_max) then\n          write(temp_char,'(i10)') IV_riv_tot_id(JS_riv_tot)\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           'ERROR: reach ID' // temp_char // ' in domain' //   &\n                           ' has an integer value greater than the maximum' // &\n                           ' allowed of' // temp_char2 // char(10),ierr)\n          stop\n     end if\n     if (IV_riv_tot_id(JS_riv_tot) == 0) then\n          write(temp_char,'(i10)') JS_riv_tot\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           'ERROR: reach ID located at index'// temp_char//    &\n                           ' in domain has a null value for ID'//char(10),ierr)\n          stop\n     end if\nend do\n\ndo JS_riv_bas=1,IS_riv_bas\n     if (IV_riv_bas_id(JS_riv_bas) > IS_riv_id_max) then\n          write(temp_char,'(i10)') IV_riv_bas_id(JS_riv_bas)\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           'ERROR: reach ID' // temp_char // ' in basin' //    &\n                           ' has an integer value greater than the maximum' // &\n                           ' allowed of' // temp_char2 // char(10),ierr)\n          stop\n     end if\n     if (IV_riv_bas_id(JS_riv_bas) == 0) then\n          write(temp_char,'(i10)') JS_riv_bas\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           'ERROR: reach ID located at index'// temp_char//    &\n                           ' in basin has a null value for ID'//char(10),ierr)\n          stop\n     end if\nend do\n\n\n!*******************************************************************************\n!Matrix preallocation\n!*******************************************************************************\ncall MatGetOwnershipRangeColumn(ZM_hsh_tot,IS_ownfirst,IS_ownlast,ierr)\n\n!-------------------------------------------------------------------------------\n!ZM_hsh_tot\n!-------------------------------------------------------------------------------\nIS_nz=0\nIS_dnz=0\nIS_onz=0\n\nIS_nz=IS_riv_tot\ndo JS_riv_tot=1,IS_riv_tot\n     if (IV_riv_tot_id(JS_riv_tot) -1 >= IS_ownfirst .and.                     &\n         IV_riv_tot_id(JS_riv_tot) -1 <  IS_ownlast) then\n          IS_dnz=IS_dnz+1\n     end if\n     IS_onz=IS_nz-IS_dnz\nend do\n\ncall MatSeqAIJSetPreallocation(ZM_hsh_tot,PETSC_NULL_INTEGER,IS_nz,ierr)\ncall MatMPIAIJSetPreallocation(ZM_hsh_tot,                                     &\n                               PETSC_NULL_INTEGER,                             &\n                               IS_dnz,                                         &\n                               PETSC_NULL_INTEGER,                             &\n                               IS_onz,ierr)\n!print *, 'rank', rank, 'IS_ownfirst', IS_ownfirst, 'IS_ownlast', IS_ownlast,   &\n!         'IS_nz', IS_nz, 'IS_dnz', IS_dnz, 'IS_onz', IS_onz\n\n!-------------------------------------------------------------------------------\n!ZM_hsh_bas\n!-------------------------------------------------------------------------------\nIS_nz=0\nIS_dnz=0\nIS_onz=0\n\nIS_nz=IS_riv_bas\ndo JS_riv_bas=1,IS_riv_bas\n     if (IV_riv_bas_id(JS_riv_bas) -1 >= IS_ownfirst .and.                     &\n         IV_riv_bas_id(JS_riv_bas) -1 <  IS_ownlast) then\n          IS_dnz=IS_dnz+1\n     end if\n     IS_onz=IS_nz-IS_dnz\nend do\n\ncall MatSeqAIJSetPreallocation(ZM_hsh_bas,PETSC_NULL_INTEGER,IS_nz,ierr)\ncall MatMPIAIJSetPreallocation(ZM_hsh_bas,                                     &\n                               PETSC_NULL_INTEGER,                             &\n                               IS_dnz,                                         &\n                               PETSC_NULL_INTEGER,                             &\n                               IS_onz,ierr)\n!print *, 'rank', rank, 'IS_ownfirst', IS_ownfirst, 'IS_ownlast', IS_ownlast,   &\n!         'IS_nz', IS_nz, 'IS_dnz', IS_dnz, 'IS_onz', IS_onz\n\n!-------------------------------------------------------------------------------\n!Done with preallocation\n!-------------------------------------------------------------------------------\ncall PetscPrintf(PETSC_COMM_WORLD,'Hashtable-like matrices preallocated'       &\n                 //char(10),ierr)\n\n\n!*******************************************************************************\n!Creates hashtable-like matrices\n!*******************************************************************************\n\n!-------------------------------------------------------------------------------\n!ZM_hsh_tot\n!-------------------------------------------------------------------------------\ndo JS_riv_tot=1,IS_riv_tot\n     IV_tot_tmp1(JS_riv_tot)=IV_riv_tot_id(JS_riv_tot)\n     IV_tot_tmp2(JS_riv_tot)=JS_riv_tot\nend do\ncall PetscSortIntWithArray(IS_riv_tot,IV_tot_tmp1(:),IV_tot_tmp2(:),ierr)\n!Populating ZM_hsh_* below much faster w/ sorted arrays than w/ IV_riv_*_id\n\ndo JS_riv_tot=1,IS_riv_tot\n     call MatSetValues(ZM_hsh_tot,                                             &\n                       IS_one,rank,                                            &\n                       IS_one,IV_tot_tmp1(JS_riv_tot)-1,                       &\n                       ZS_one*IV_tot_tmp2(JS_riv_tot),INSERT_VALUES,ierr)\n     CHKERRQ(ierr)\nend do\n\n!-------------------------------------------------------------------------------\n!ZM_hsh_bas\n!-------------------------------------------------------------------------------\ndo JS_riv_bas=1,IS_riv_bas\n     IV_bas_tmp1(JS_riv_bas)=IV_riv_bas_id(JS_riv_bas)\n     IV_bas_tmp2(JS_riv_bas)=JS_riv_bas\nend do\ncall PetscSortIntWithArray(IS_riv_bas,IV_bas_tmp1(:),IV_bas_tmp2(:),ierr)\n!Populating ZM_hsh_* below much faster w/ sorted arrays than w/ IV_riv_*_id\n\ndo JS_riv_bas=1,IS_riv_bas\n     call MatSetValues(ZM_hsh_bas,                                             &\n                       IS_one,rank,                                            &\n                       IS_one,IV_bas_tmp1(JS_riv_bas)-1,                       &\n                       ZS_one*IV_bas_tmp2(JS_riv_bas),INSERT_VALUES,ierr)\n     CHKERRQ(ierr)\nend do\n\n!-------------------------------------------------------------------------------\n!Assemble matrices\n!-------------------------------------------------------------------------------\ncall MatAssemblyBegin(ZM_hsh_tot,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_hsh_tot,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyBegin(ZM_hsh_bas,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_hsh_bas,MAT_FINAL_ASSEMBLY,ierr)\n!sparse matrices need be assembled once their elements have been filled\ncall PetscPrintf(PETSC_COMM_WORLD,'Hashtable-like matrices created'//char(10), &\n                 ierr)\n\n\n!*******************************************************************************\n!Display matrices on stdout\n!*******************************************************************************\n!call PetscPrintf(PETSC_COMM_WORLD,'ZM_hsh_tot'//char(10),ierr)\n!call MatView(ZM_hsh_tot,PETSC_VIEWER_STDOUT_WORLD,ierr)\n!\n!call PetscPrintf(PETSC_COMM_WORLD,'ZM_hsh_bas'//char(10),ierr)\n!call MatView(ZM_hsh_bas,PETSC_VIEWER_STDOUT_WORLD,ierr)\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\n\n\nend subroutine rapid_hsh_mat\n"
  },
  {
    "path": "src/Rapid_routing/rapid_init.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_init\r\n!*******************************************************************************\r\nsubroutine rapid_init\r\n\r\n!Purpose:\r\n!This subroutine allows to initialize RAPID for both regular runs and\r\n!optimization runs, by performing slightly different tasks depending on what\r\n!option is chosen.\r\n!Initialization tasks common to all RAPID options:\r\n!     -Read namelist file (sizes of domain, duration, file names, options, etc.)\r\n!     -Compute number of time steps based on durations\r\n!     -Allocate Fortran arrays\r\n!     -Create all PETSc and TAO objects\r\n!     -Print information and warnings\r\n!     -Determine IDs for various computing cores\r\n!     -Compute helpful arrays\r\n!     -Compute the network matrix\r\n!     -Initialize values of flow and volume for main procedure\r\n!Initialization tasks specific to Option 1\r\n!     -Copy main initial flow and vol to routing initial flow and vol\r\n!     -Read k and x\r\n!     -Compute linear system matrix\r\n!Initialization tasks specific to Option 2\r\n!     -Copy main initial flow to optimization initial flow\r\n!     -Compute the observation matrix\r\n!     -Read kfac and Qobsbarrec\r\n!     -Set initial values for the vector pnorm\r\n!Author:\r\n!Cedric H. David, 2012-2015.\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables\r\n!*******************************************************************************\r\nuse rapid_var, only :                                                          &\r\n                   IS_riv_tot,IS_riv_bas,                                      &\r\n                   IV_riv_bas_id,IV_riv_index,IV_riv_loc1,IV_riv_tot_id,       &\r\n                   IV_down,IV_nbup,IM_up,IM_index_up,IS_max_up,                &\r\n                   IV_nz,IV_dnz,IV_onz,                                        &\r\n                   BS_opt_Qinit,BS_opt_Qfinal,BS_opt_influence,                &\r\n                   BS_opt_dam,BS_opt_for,BS_opt_hum,                           &\r\n                   IS_opt_run,IS_opt_routing,IS_opt_phi,                       &\r\n                   ZV_read_riv_tot,ZV_read_obs_tot,ZV_read_hum_tot,            &\r\n                   ZV_read_for_tot,ZV_read_dam_tot,                            &\r\n                   ZS_TauM,ZS_TauO,ZS_TauR,ZS_dtO,ZS_dtR,ZS_dtM,ZS_dtF,ZS_dtH, &\r\n                   IS_obs_tot,IS_obs_use,IS_obs_bas,                           &\r\n                   IV_obs_tot_id,IV_obs_use_id,                                &\r\n                   IV_obs_index,IV_obs_loc1,                                   &\r\n                   IS_hum_tot,IS_hum_use,                                      &\r\n                   IV_hum_tot_id,IV_hum_use_id,                                &\r\n                   IS_for_tot,IS_for_use,                                      &\r\n                   IV_for_tot_id,IV_for_use_id,                                &\r\n                   IS_dam_tot,IS_dam_use,                                      &\r\n                   IV_dam_tot_id,IV_dam_use_id,                                &\r\n                   ZV_Qin_dam,ZV_Qout_dam,ZV_Qin_dam_prev,ZV_Qout_dam_prev,    &\r\n                   ZV_Qin_dam0,ZV_Qout_dam0,                                   &\r\n                   ZV_QoutinitM,ZV_QoutinitO,ZV_QoutinitR,                     &\r\n                   ZV_VinitM,ZV_VinitR,                                        &\r\n                   ZV_babsmax,ZV_QoutRabsmin,ZV_QoutRabsmax,                   &\r\n                   IS_M,IS_O,IS_R,IS_RpO,IS_RpM,IS_RpF,IS_RpH,                 &\r\n                   kfac_file,x_file,k_file,Vlat_file,Qinit_file,               &\r\n                   Qobsbarrec_file,                                            &\r\n                   ZS_Qout0,ZS_V0,                                             &\r\n                   ZV_Qobsbarrec,                                              &\r\n                   ZV_k,ZV_x,ZV_kfac,ZV_p,ZV_pnorm,ZV_pfac,                    &\r\n                   ZS_knorm_init,ZS_xnorm_init,ZS_kfac,ZS_xfac,                &\r\n                   ZV_C1,ZV_C2,ZV_C3,ZM_A,                                     &\r\n                   ierr,ksp,rank,ncore,IS_one,ZS_one\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n#include \"finclude/petscsys.h\"\r\n!base PETSc routines\r\n#include \"finclude/petscvec.h\"\r\n#include \"finclude/petscvec.h90\"\r\n!vectors, and vectors in Fortran90\r\n#include \"finclude/petscmat.h\"\r\n!matrices\r\n#include \"finclude/petscksp.h\"\r\n!Krylov subspace methods\r\n#include \"finclude/petscpc.h\"\r\n!preconditioners\r\n#include \"finclude/petscviewer.h\"\r\n!viewers (allows writing results in file for example)\r\n#include \"finclude/petsclog.h\"\r\n!PETSc log\r\n\r\n!*******************************************************************************\r\n!Initialization procedure common to all options\r\n!*******************************************************************************\r\n\r\n!-------------------------------------------------------------------------------\r\n!Read name list, allocate Fortran arrays\r\n!-------------------------------------------------------------------------------\r\ncall rapid_read_namelist\r\n\r\nprint *,'!!!LPR enter rapid_init'\r\n\r\nallocate(IV_riv_bas_id(IS_riv_bas))\r\nallocate(IV_riv_index(IS_riv_bas))\r\nallocate(IV_riv_loc1(IS_riv_bas))\r\n\r\nallocate(IV_riv_tot_id(IS_riv_tot))\r\nallocate(IV_down(IS_riv_tot))\r\nallocate(IV_nbup(IS_riv_tot))\r\nallocate(IM_up(IS_riv_tot,IS_max_up))\r\nallocate(IM_index_up(IS_riv_tot,IS_max_up))\r\n\r\nallocate(IV_nz(IS_riv_bas))\r\nallocate(IV_dnz(IS_riv_bas))\r\nallocate(IV_onz(IS_riv_bas))\r\n\r\nallocate(ZV_read_riv_tot(IS_riv_tot))\r\n\r\nprint *,'!!!LPR passed several allocation'\r\n\r\nif (IS_opt_run==2) then\r\n     allocate(IV_obs_tot_id(IS_obs_tot))\r\n     allocate(IV_obs_use_id(IS_obs_use))\r\n     allocate(ZV_read_obs_tot(IS_obs_tot))\r\nend if\r\n\r\nif (BS_opt_hum) then\r\n     allocate(IV_hum_tot_id(IS_hum_tot))\r\n     allocate(IV_hum_use_id(IS_hum_use))\r\n     allocate(ZV_read_hum_tot(IS_hum_tot))\r\nend if\r\n\r\nif (BS_opt_for) then\r\n     allocate(IV_for_tot_id(IS_for_tot))\r\n     allocate(IV_for_use_id(IS_for_use))\r\n     allocate(ZV_read_for_tot(IS_for_tot))\r\nend if\r\n\r\nif (BS_opt_dam) then\r\n     allocate(IV_dam_tot_id(IS_dam_tot))\r\n     allocate(IV_dam_use_id(IS_dam_use))\r\n     allocate(ZV_read_dam_tot(IS_dam_tot))\r\n     allocate(ZV_Qin_dam(IS_dam_tot))\r\n     allocate(ZV_Qin_dam_prev(IS_dam_tot))\r\n     allocate(ZV_Qout_dam(IS_dam_tot))\r\n     allocate(ZV_Qout_dam_prev(IS_dam_tot))\r\n     allocate(ZV_Qin_dam0(IS_dam_tot))\r\n     allocate(ZV_Qout_dam0(IS_dam_tot))\r\nend if\r\n\r\n!-------------------------------------------------------------------------------\r\n!Make sure some Fortran arrays are initialized to zero\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_dam) then\r\n     ZV_Qin_dam0 =0\r\n     ZV_Qout_dam0=0\r\nend if\r\n!These are not populated anywhere before being used and hold meaningless values\r\n\r\n!-------------------------------------------------------------------------------\r\n!Compute number of time steps\r\n!-------------------------------------------------------------------------------\r\nIS_M=int(ZS_TauM/ZS_dtM)\r\nIS_O=int(ZS_TauO/ZS_dtO)\r\nIS_R=int(ZS_TauR/ZS_dtR)\r\nIS_RpO=int(ZS_dtO/ZS_TauR)\r\nIS_RpM=int(ZS_dtM/ZS_TauR)\r\nIS_RpF=int(ZS_dtF/ZS_TauR)\r\nIS_RpH=int(ZS_dtH/ZS_TauR)\r\n\r\n!-------------------------------------------------------------------------------\r\n!Initialize libraries and create objects common to all options\r\n!-------------------------------------------------------------------------------\r\nprint *,'!!!LPR before create obj'\r\ncall rapid_create_obj\r\nprint *,'!!!LPR after create obj'\r\n!Initialize libraries and create PETSc and TAO objects (Mat,Vec,taoapp...)\r\n\r\n!-------------------------------------------------------------------------------\r\n!Prints information about current model run based on info from namelist\r\n!-------------------------------------------------------------------------------\r\nif (rank==0 .and. .not. BS_opt_Qinit)                      print '(a70)',      &\r\n       'Not reading initial flows from a file                                  '\r\nif (rank==0 .and. BS_opt_Qinit)                            print '(a70)',      &\r\n       'Reading initial flows from a file                                      '\r\nif (rank==0 .and. .not. BS_opt_Qfinal .and. IS_opt_run==1) print '(a70)',      &\r\n       'Not writing final flows into a file                                    '\r\nif (rank==0 .and. BS_opt_Qfinal .and. IS_opt_run==1)       print '(a70)',      &\r\n       'Writing final flows into a file                                        '\r\nif (rank==0 .and. .not. BS_opt_for)                        print '(a70)',      &\r\n       'Not using forcing                                                      '\r\nif (rank==0 .and. BS_opt_for)                              print '(a70)',      &\r\n       'Using forcing                                                          '\r\nif (rank==0 .and. .not. BS_opt_hum)                        print '(a70)',      &\r\n       'Not using human-induced flows                                          '\r\nif (rank==0 .and. BS_opt_hum)                              print '(a70)',      &\r\n       'Using human-induced flows                                              '\r\nif (rank==0 .and. IS_opt_routing==1)                       print '(a70)',      &\r\n       'Routing with matrix-based Muskingum method                             '\r\nif (rank==0 .and. IS_opt_routing==2)                       print '(a70)',      &\r\n       'Routing with traditional Muskingum method                              '\r\nif (rank==0 .and. IS_opt_routing==3)                       print '(a70)',      &\r\n       'Routing with matrix-based Muskingum method using transboundary matrix  '\r\nif (rank==0 .and. IS_opt_run==1)                           print '(a70)',      &\r\n       'RAPID mode: computing flowrates                                        '\r\nif (rank==0 .and. IS_opt_run==2 .and. IS_opt_phi==1)       print '(a70)',      &\r\n       'RAPID mode: optimizing parameters, using phi1                          '\r\nif (rank==0 .and. IS_opt_run==2 .and. IS_opt_phi==2)       print '(a70)',      &\r\n       'RAPID mode: optimizing parameters, using phi2                          '\r\nif (rank==0)                                               print '(a10,a60)',  &\r\n       'Using    :', Vlat_file\r\nif (rank==0 .and. IS_opt_run==1)                           print '(a10,a60)',  &\r\n       'Using    :',k_file\r\nif (rank==0 .and. IS_opt_run==1)                           print '(a10,a60)',  &\r\n       'Using    :',x_file\r\nif (rank==0 .and. IS_opt_run==2)                           print '(a10,a60)',  &\r\n       'Using    :',kfac_file\r\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\r\n\r\n!-------------------------------------------------------------------------------\r\n!Calculate helpful arrays  !--LPR: hash-table used to increase efficiency-------\r\n!-------------------------------------------------------------------------------\r\ncall rapid_arrays\r\n!print *,'!!!LPR after rapid_arrays'\r\n\r\n!-------------------------------------------------------------------------------\r\n!Calculate Network matrix\r\n!-------------------------------------------------------------------------------\r\ncall rapid_net_mat\r\n!print *,'!!!LPR after rapid_net_mat'\r\n\r\n!-------------------------------------------------------------------------------\r\n!Breaks connections in Network matrix\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_for .or. BS_opt_dam) call rapid_net_mat_brk\r\n\r\n!-------------------------------------------------------------------------------\r\n!calculates or set initial flows and volumes\r\n!-------------------------------------------------------------------------------\r\nif (.not. BS_opt_Qinit) then\r\ncall VecSet(ZV_QoutinitM,ZS_Qout0,ierr)\r\nend if\r\n\r\nif (BS_opt_Qinit) then\r\nprint *, 'LPR: RAPID reading its own initialization file ......'\r\nopen(30,file=Qinit_file,status='old')\r\nread(30,*) ZV_read_riv_tot\r\nclose(30)\r\ncall VecSetValues(ZV_QoutinitM,IS_riv_bas,IV_riv_loc1,                          &\r\n                  ZV_read_riv_tot(IV_riv_index),INSERT_VALUES,ierr)\r\n                  !here we use the output of a simulation as the intitial\r\n                  !flow rates.  The simulation has to be made on the entire\r\n                  !domain, the initial value is taken only for the considered\r\n                  !basin thanks to the vector IV_riv_index\r\ncall VecAssemblyBegin(ZV_QoutinitM,ierr)\r\ncall VecAssemblyEnd(ZV_QoutinitM,ierr)\r\nend if\r\n\r\ncall VecSet(ZV_VinitM,ZS_V0,ierr)\r\n!Set initial volumes for Main procedure\r\n\r\n!-------------------------------------------------------------------------------\r\n!Initialize default values for ZV_QoutRabsmin, ZV_QoutRabsmax and ZV_babsmax\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_influence) then\r\ncall VecSet(ZV_babsmax    ,ZS_one*0        ,ierr)\r\ncall VecSet(ZV_QoutRabsmin,ZS_one*999999999,ierr)\r\ncall VecSet(ZV_QoutRabsmax,ZS_one*0        ,ierr)\r\nend if\r\n\r\n\r\n!*******************************************************************************\r\n!Initialization procedure for OPTION 1\r\n!*******************************************************************************\r\nif (IS_opt_run==1) then\r\n\r\n!-------------------------------------------------------------------------------\r\n!copy main initial values into routing initial values\r\n!-------------------------------------------------------------------------------\r\ncall VecCopy(ZV_QoutinitM,ZV_QoutinitR,ierr)\r\ncall VecCopy(ZV_VinitM,ZV_VinitR,ierr)\r\n\r\n!-------------------------------------------------------------------------------\r\n!Read/set k and x\r\n!-------------------------------------------------------------------------------\r\nopen(20,file=k_file,status='old')\r\nread(20,*) ZV_read_riv_tot\r\ncall VecSetValues(ZV_k,IS_riv_bas,IV_riv_loc1,                                 &\r\n                  ZV_read_riv_tot(IV_riv_index),INSERT_VALUES,ierr)\r\ncall VecAssemblyBegin(ZV_k,ierr)\r\ncall VecAssemblyEnd(ZV_k,ierr)\r\nclose(20)\r\n!get values for k in a file and create the corresponding ZV_k vector\r\n\r\nopen(21,file=x_file,status='old')\r\nread(21,*) ZV_read_riv_tot\r\ncall VecSetValues(ZV_x,IS_riv_bas,IV_riv_loc1,                                 &\r\n                  ZV_read_riv_tot(IV_riv_index),INSERT_VALUES,ierr)\r\ncall VecAssemblyBegin(ZV_x,ierr)\r\ncall VecAssemblyEnd(ZV_x,ierr)\r\nclose(21)\r\n!get values for x in a file and create the corresponding ZV_x vector\r\n\r\n!-------------------------------------------------------------------------------\r\n!Compute routing parameters and linear system matrix\r\n!-------------------------------------------------------------------------------\r\ncall rapid_routing_param(ZV_k,ZV_x,ZV_C1,ZV_C2,ZV_C3,ZM_A)\r\n!calculate Muskingum parameters and matrix ZM_A\r\n\r\ncall KSPSetOperators(ksp,ZM_A,ZM_A,DIFFERENT_NONZERO_PATTERN,ierr)\r\ncall KSPSetType(ksp,KSPRICHARDSON,ierr)                    !default=richardson\r\n!call KSPSetInitialGuessNonZero(ksp,PETSC_TRUE,ierr)\r\n!call KSPSetInitialGuessKnoll(ksp,PETSC_TRUE,ierr)\r\ncall KSPSetFromOptions(ksp,ierr)                           !if runtime options\r\nif (IS_opt_routing==3) call KSPSetType(ksp,KSPPREONLY,ierr)!default=preonly\r\n\r\n!-------------------------------------------------------------------------------\r\n!End of initialization procedure for OPTION 1\r\n!-------------------------------------------------------------------------------\r\nend if\r\n\r\n\r\n!*******************************************************************************\r\n!Initialization procedure for OPTION 2\r\n!*******************************************************************************\r\nif (IS_opt_run==2) then\r\n#ifndef NO_TAO\r\n\r\n!-------------------------------------------------------------------------------\r\n!Create observation matrix\r\n!-------------------------------------------------------------------------------\r\ncall rapid_obs_mat\r\n!Create observation matrix\r\n\r\n!-------------------------------------------------------------------------------\r\n!copy main initial values into optimization initial values\r\n!-------------------------------------------------------------------------------\r\ncall VecCopy(ZV_QoutinitM,ZV_QoutinitO,ierr)\r\n!copy initial main variables into initial optimization variables\r\n\r\n!-------------------------------------------------------------------------------\r\n!Read/set kfac, xfac and Qobsbarrec\r\n!-------------------------------------------------------------------------------\r\nopen(22,file=kfac_file,status='old')\r\nread(22,*) ZV_read_riv_tot\r\nclose(22)\r\ncall VecSetValues(ZV_kfac,IS_riv_bas,IV_riv_loc1,                              &\r\n                  ZV_read_riv_tot(IV_riv_index),INSERT_VALUES,ierr)\r\n                  !only looking at basin, doesn't have to be whole domain here\r\ncall VecAssemblyBegin(ZV_kfac,ierr)\r\ncall VecAssemblyEnd(ZV_kfac,ierr)\r\n!reads kfac and assigns to ZV_kfac\r\n\r\nif (IS_opt_phi==2) then\r\nopen(35,file=Qobsbarrec_file,status='old')\r\nread(35,*) ZV_read_obs_tot\r\nclose(35)\r\ncall VecSetValues(ZV_Qobsbarrec,IS_obs_bas,IV_obs_loc1,                        &\r\n                  ZV_read_obs_tot(IV_obs_index),INSERT_VALUES,ierr)\r\n                  !here we only look at the observations within the basin\r\n                  !studied\r\ncall VecAssemblyBegin(ZV_Qobsbarrec,ierr)\r\ncall VecAssemblyEnd(ZV_Qobsbarrec,ierr)\r\n!reads Qobsbarrec and assigns to ZV_Qobsbarrec\r\nend if\r\n\r\n!-------------------------------------------------------------------------------\r\n!Set pnorm, pfac and p\r\n!-------------------------------------------------------------------------------\r\ncall VecSetValues(ZV_pnorm,IS_one,IS_one-1,ZS_knorm_init,INSERT_VALUES,ierr)\r\ncall VecSetValues(ZV_pnorm,IS_one,IS_one,ZS_xnorm_init,INSERT_VALUES,ierr)\r\ncall VecAssemblyBegin(ZV_pnorm,ierr)\r\ncall VecAssemblyEnd(ZV_pnorm,ierr)\r\n!set pnorm to pnorm=(knorm,xnorm)\r\n\r\n!call VecSetValues(ZV_pfac,IS_one,IS_one-1,ZS_kfac,INSERT_VALUES,ierr)\r\n!call VecSetValues(ZV_pfac,IS_one,IS_one,ZS_xfac,INSERT_VALUES,ierr)\r\n!call VecAssemblyBegin(ZV_pnorm,ierr)\r\n!call VecAssemblyEnd(ZV_pnorm,ierr)\r\n!!set pfac to pfac=(kfac,xfac)\r\n\r\n!call VecPointWiseMult(ZV_p,ZV_pfac,ZV_pnorm,ierr)\r\n!!set p to p=pfac.*pnorm\r\n\r\n!-------------------------------------------------------------------------------\r\n!End of OPTION 2\r\n!-------------------------------------------------------------------------------\r\n#endif\r\nend if\r\n\r\n\r\n!*******************************************************************************\r\n!End of subroutine\r\n!*******************************************************************************\r\nend subroutine rapid_init\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_main.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_main\r\n!*******************************************************************************\r\nsubroutine rapid_main(ITIME,runoff,ii,jj,Qout_nc_file)\r\n!Purpose:\r\n!Allows to route water through a river network, and to estimate optimal\r\n!parameters using the inverse method\r\n!Author:\r\n!Cedric H. David, 2008-2015.\r\n!Peirong Lin, modified starting from June 2014 to satisfy WRF-Hydro needs\r\n\r\nuse netcdf\r\n\r\n!---LPR: added variable use from module Wrapper---------------------\r\nuse hrldas_RAPID_wrapper, only: cnt_rapid_run,rapid_runoff_to_inflow\r\n\r\n!*******************************************************************************\r\n!Declaration of variables\r\n!*******************************************************************************\r\nuse rapid_var, only :                                                          &\r\n                   namelist_file,                                              &\r\n                   Vlat_file,Qfor_file,Qhum_file,                              &\r\n                   Qout_file,                                                  &\r\n                   IS_M,JS_M,JS_RpM,IS_RpM,IS_RpF,IS_RpH,                      &\r\n                   ZS_TauR,                                                    &\r\n                   ZV_pnorm,                                                   &\r\n                   ZV_C1,ZV_C2,ZV_C3,                                          &\r\n                   ZV_Qext,ZV_Qfor,ZV_Qlat,ZV_Qhum,ZV_Qdam,                    &\r\n                   ZV_Vlat,                                                    &\r\n                   ZV_QoutR,ZV_QoutinitR,ZV_QoutbarR,                          &\r\n                   ZV_VR,ZV_VinitR,ZV_VbarR,                                   &\r\n                   ZS_phi,                                                     &\r\n                   ierr,rank,stage,temp_char,temp_char2,                       &\r\n                   ZS_one,                                                     &\r\n                   IS_riv_tot,IS_riv_bas,IS_for_bas,IS_dam_bas,IS_hum_bas,     &\r\n                   ZS_time1,ZS_time2,ZS_time3,                                 &\r\n                   IV_nc_start,IV_nc_count,IV_nc_count2,                       &\r\n                   BS_opt_for,BS_opt_hum,BS_opt_dam,IS_opt_run\r\n\r\n#ifndef NO_TAO\r\nuse rapid_var, only :                                                          &\r\n                   tao\r\n#endif\r\n\r\nimplicit none\r\nexternal rapid_phiroutine\r\n!because the subroutine is called by a function\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n#include \"finclude/petscsys.h\"\r\n!base PETSc routines\r\n#include \"finclude/petscvec.h\"\r\n#include \"finclude/petscvec.h90\"\r\n!vectors, and vectors in Fortran90\r\n#include \"finclude/petscmat.h\"\r\n!matrices\r\n#include \"finclude/petscksp.h\"\r\n!Krylov subspace methods\r\n#include \"finclude/petscpc.h\"\r\n!preconditioners\r\n#include \"finclude/petscviewer.h\"\r\n!viewers (allows writing results in file for example)\r\n#include \"finclude/petsclog.h\"\r\n!PETSc log\r\n\r\n#ifndef NO_TAO\r\n#include \"finclude/taosolver.h\"\r\n!TAO solver\r\n#endif\r\n\r\ninteger ITIME\r\ninteger ii,jj\r\nreal,dimension(ii,jj) :: runoff\r\nreal,dimension(ii,jj) :: ZM_runoff\r\ncharacter(len=100) :: Qout_nc_file  !---LPR: RAPID output file name--\r\n\r\nZM_runoff = runoff  !---LPR: pass runoff calculated by WRF-Hydro to RAPID------\r\nQout_file = Qout_nc_file !---LPR: new output filename defined by Wrapper-------\r\n\r\n!*******************************************************************************\r\n!Initialize\r\n!*******************************************************************************\r\n!namelist_file='./rapid_namelist' !---LPR: initialize done in Wrapper----------\r\n!call rapid_init\r\n\r\n!*******************************************************************************\r\n!OPTION 1 - use to calculate flows and volumes and generate output data\r\n!*******************************************************************************\r\nif (IS_opt_run==1) then\r\n\r\n!-------------------------------------------------------------------------------\r\n!Create Qout file\r\n!-------------------------------------------------------------------------------\r\ncall rapid_create_Qout_file(Qout_file)\r\n\r\n!-------------------------------------------------------------------------------\r\n!Open files\r\n!-------------------------------------------------------------------------------\r\ncall rapid_open_Qout_file(Qout_file)\r\n!---LPR: IMPORTANT uncomment this sentence because runoff is NOT read from Vlat\r\n!call rapid_open_Vlat_file(Vlat_file)\r\n!---LPR: IMPORTANT uncomment this sentence because runoff is NOT read from Vlat\r\nif (BS_opt_for) call rapid_open_Qfor_file(Qfor_file)\r\nif (BS_opt_hum) call rapid_open_Qhum_file(Qhum_file)\r\n\r\n!-------------------------------------------------------------------------------\r\n!Make sure the vectors potentially used for inflow to dams are initially null\r\n!-------------------------------------------------------------------------------\r\ncall VecSet(ZV_Qext,0*ZS_one,ierr)                         !Qext=0\r\ncall VecSet(ZV_QoutbarR,0*ZS_one,ierr)                     !QoutbarR=0\r\n!This should be done by PETSc but just to be safe\r\n\r\n!-------------------------------------------------------------------------------\r\n!Set initial value of Qext from Qout_dam0\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_dam .and. IS_dam_bas>0) then\r\n     call rapid_set_Qext0                                  !Qext from Qout_dam0\r\n     !call VecView(ZV_Qext,PETSC_VIEWER_STDOUT_WORLD,ierr)\r\nend if\r\n\r\n!-------------------------------------------------------------------------------\r\n!Read, compute and write\r\n!-------------------------------------------------------------------------------\r\n!---LPR: IMPORTANT uncomment the next two->defined in RAPID initialization stage\r\n!call PetscLogStageRegister('Read Comp Write',stage,ierr)\r\n!call PetscLogStagePush(stage,ierr)\r\n\r\nZS_time3=0\r\n\r\nIV_nc_start=(/1,1/)\r\nIV_nc_count=(/IS_riv_tot,1/)\r\nIV_nc_count2=(/IS_riv_bas,1/)\r\n\r\n!---LPR uncomment this because loop is done within WRF-Hydro call--------------\r\n!do JS_M=1,IS_M\r\n!do JS_RpM=1,IS_RpM\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Read/set surface and subsurface volumes\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!call rapid_read_Vlat_file  !---LPR: do not read Vlat file, but get Vlat from WRF-Hydro\r\n\r\n!---LPR: IMPORTANT new subroutine added in the Wrapper-----------------\r\ncall rapid_runoff_to_inflow(ZM_runoff,ZV_Vlat,cnt_rapid_run)\r\n!---LPR: IMPORTANT new subroutine added in the Wrapper-----------------\r\n\r\ncall VecCopy(ZV_Vlat,ZV_Qlat,ierr)            !Qlat=Vlat\r\ncall VecScale(ZV_Qlat,1/ZS_TauR,ierr)         !Qlat=Qlat/TauR\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Read/set upstream forcing\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nif (BS_opt_for .and. IS_for_bas>0                                              &\r\n                   .and. mod((JS_M-1)*IS_RpM+JS_RpM,IS_RpF)==1) then\r\n\r\ncall rapid_read_Qfor_file\r\n\r\nend if\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Run dam model based on previous values of QoutbarR and Qext to get Qdam\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nif (BS_opt_dam .and. IS_dam_bas>0) then\r\n\r\ncall rapid_get_Qdam\r\n\r\nend if\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Read/set human induced flows\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nif (BS_opt_hum .and. IS_hum_bas>0                                              &\r\n                   .and. mod((JS_M-1)*IS_RpM+JS_RpM,IS_RpH)==1) then\r\n\r\ncall rapid_read_Qhum_file\r\n\r\nend if\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!calculation of Qext\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ncall VecCopy(ZV_Qlat,ZV_Qext,ierr)                            !Qext=Qlat\r\nif (BS_opt_for) call VecAXPY(ZV_Qext,ZS_one,ZV_Qfor,ierr)     !Qext=Qext+1*Qfor\r\nif (BS_opt_dam) call VecAXPY(ZV_Qext,ZS_one,ZV_Qdam,ierr)     !Qext=Qext+1*Qdam\r\nif (BS_opt_hum) call VecAXPY(ZV_Qext,ZS_one,ZV_Qhum,ierr)     !Qext=Qext+1*Qhum\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Routing procedure\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ncall PetscTime(ZS_time1,ierr)\r\ncall rapid_routing(ZV_C1,ZV_C2,ZV_C3,ZV_Qext,                                  &\r\n                   ZV_QoutinitR,ZV_VinitR,                                     &\r\n                   ZV_QoutR,ZV_QoutbarR,ZV_VR,ZV_VbarR)\r\ncall PetscTime(ZS_time2,ierr)\r\nZS_time3=ZS_time3+ZS_time2-ZS_time1\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Update variables\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ncall VecCopy(ZV_QoutR,ZV_QoutinitR,ierr)\r\ncall VecCopy(ZV_VR,ZV_VinitR,ierr)\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!write outputs\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ncall rapid_write_Qout_file\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Update netCDF location\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nif (rank==0) IV_nc_start(2)=IV_nc_start(2)+1\r\n!do not comment out if writing directly from the routing subroutine\r\n\r\n!end do\r\n!end do  !---LPR uncomment because loop if done in WRF-Hydro\r\n\r\n!-------------------------------------------------------------------------------\r\n!Performance statistics\r\n!-------------------------------------------------------------------------------\r\ncall PetscPrintf(PETSC_COMM_WORLD,'Cumulative time for routing only'           &\r\n                                  //char(10),ierr)\r\nwrite(temp_char ,'(i10)')   rank\r\nwrite(temp_char2,'(f10.2)') ZS_time3\r\ncall PetscSynchronizedPrintf(PETSC_COMM_WORLD,'Rank     :'//temp_char //', '// &\r\n                                              'Time     :'//temp_char2//       &\r\n                                               char(10),ierr)\r\ncall PetscSynchronizedFlush(PETSC_COMM_WORLD,ierr)\r\n!---LPR: uncomment sentence below to avoid potential PETSC Stack Empty error-----\r\n!call PetscLogStagePop(ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,'Output data created'//char(10),ierr)\r\n\r\n!-------------------------------------------------------------------------------\r\n!Close files\r\n!-------------------------------------------------------------------------------\r\ncall rapid_close_Qout_file\r\n!---LPR: IMPORTANT uncomment setence below-------\r\n!call rapid_close_Vlat_file\r\nif (BS_opt_for) call rapid_close_Qfor_file(Qfor_file)\r\nif (BS_opt_hum) call rapid_close_Qhum_file(Qhum_file)\r\n\r\n\r\n!-------------------------------------------------------------------------------\r\n!End of OPTION 1\r\n!-------------------------------------------------------------------------------\r\nend if\r\n\r\n\r\n!*******************************************************************************\r\n!OPTION 2 - Optimization\r\n!*******************************************************************************\r\nif (IS_opt_run==2) then\r\n#ifndef NO_TAO\r\n\r\n!-------------------------------------------------------------------------------\r\n!Only one computation of phi - For testing purposes only\r\n!-------------------------------------------------------------------------------\r\n!call PetscLogStageRegister('One comp of phi',stage,ierr)\r\n!call PetscLogStagePush(stage,ierr)\r\n!!do JS_M=1,5\r\n!call rapid_phiroutine(tao,ZV_pnorm,ZS_phi,PETSC_NULL,ierr)\r\n!!enddo\r\n!call PetscLogStagePop(ierr)\r\n\r\n!-------------------------------------------------------------------------------\r\n!Optimization procedure\r\n!-------------------------------------------------------------------------------\r\ncall PetscLogStageRegister('Optimization   ',stage,ierr)\r\ncall PetscLogStagePush(stage,ierr)\r\ncall TaoSetObjectiveRoutine(tao,rapid_phiroutine,PETSC_NULL_OBJECT,ierr)\r\ncall TaoSetInitialVector(tao,ZV_pnorm,ierr)\r\ncall TaoSetTolerances(tao,1.0d-4,1.0d-4,PETSC_NULL_OBJECT,PETSC_NULL_OBJECT,   &\r\n                      PETSC_NULL_OBJECT,ierr)\r\ncall TaoSolve(tao,ierr)\r\n\r\ncall TaoView(tao,PETSC_VIEWER_STDOUT_WORLD,ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,'final normalized p=(k,x)'//char(10),ierr)\r\ncall VecView(ZV_pnorm,PETSC_VIEWER_STDOUT_WORLD,ierr)\r\ncall PetscLogStagePop(ierr)\r\n\r\n!-------------------------------------------------------------------------------\r\n!End of OPTION 2\r\n!-------------------------------------------------------------------------------\r\n#else\r\nif (rank==0)                                         print '(a70)',            &\r\n        'ERROR: The optimization mode requires RAPID to be compiled with TAO   '\r\n#endif\r\nend if\r\n\r\n\r\n!*******************************************************************************\r\n!Finalize\r\n!*******************************************************************************\r\n!call rapid_final !---LPR: no need to finalize, write RAPID output each time step\r\n\r\n!*******************************************************************************\r\n!End\r\n!*******************************************************************************\r\nend subroutine rapid_main\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_namelist",
    "content": "&NL_namelist\r\n!*******************************************************************************\r\n!Runtime options \r\n!*******************************************************************************\r\nBS_opt_Qinit       =.false.\r\n!.false. --> no initialization       .true. --> initialization\r\n\r\nBS_opt_forcing     =.false.\r\n!.false. --> no forcing              .true. --> forcing\r\n\r\nIS_opt_routing     =1\r\n!1       --> matrix-based Muskingum  2      --> traditional Muskingum\r\n\r\nIS_opt_run         =1\r\n!1       --> regular run             2      --> parameter optimization\r\n\r\nIS_opt_phi         =1\r\n!1       --> phi1                    2      --> phi2\r\n\r\n!*******************************************************************************\r\n!Temporal information\r\n!*******************************************************************************\r\nZS_TauM=252460800\r\n!315619200 !3600*24*3652days NASA-project !San-Gua 2004-2007 Case!3600*24*1460=126144000\r\n!3600*24*4527\r\n!ZS_TauM=26092800 !Texas 2013.12.03-2014.09.30 Case, lpr 2014-03-12\r\n!3600*24*302\r\n!ZS_dtM=86400\r\n\r\n!modified on 2014/04/03\r\n!3600*24=86400\r\nZS_dtM=86400\r\n!3600*3=10800\r\n\r\n\r\nZS_TauO=315532800      !15724800\r\n!3600*24*182=15724800\r\nZS_dtO=86400\r\n!ZS_dtO=10800\r\n!3600*24=86400\r\n\r\nZS_TauR=10800\r\n!3600*3=10800\r\nZS_dtR=900\r\n\r\n!*******************************************************************************\r\n!Domain in which input data is available\r\n!*******************************************************************************\r\nIS_reachtot        =68143 !for Texas; 5175 for San-Gua\r\nmodcou_connect_file='./forecast_input_tx/rapid_connect_Reg12.csv'\r\nIS_max_up          =4\r\nm3_nc_file         ='./forecast_input_tx/m3_riv_2000_2007_NoahMP_Texas.nc'\r\n\r\n!*******************************************************************************\r\n!Domain in which model runs\r\n!*******************************************************************************\r\nIS_reachbas        =68143 !5175\r\nbasin_id_file      ='./forecast_input_tx/basin_id_Reg12_hydroseq.csv'\r\n\r\n!*******************************************************************************\r\n!Initialization\r\n!*******************************************************************************\r\nQinit_file         =''\r\n\r\n!*******************************************************************************\r\n!Available forcing data\r\n!*******************************************************************************\r\n!IS_forcingtot      =3\r\n!forcingtot_id_file ='./input_San_Guad/forcingtot_id_dam_springs.csv'\r\n!Qfor_file          ='./input_San_Guad/Qfor_dam_springs_2004_2007.csv'     \r\n\r\n!*******************************************************************************\r\n!Forcing data used as model runs\r\n!*******************************************************************************\r\n!IS_forcinguse      =3\r\n!forcinguse_id_file ='./input_San_Guad/forcinguse_id_dam_springs.csv'\r\n\r\n!*******************************************************************************\r\n!Regular model run\r\n!*******************************************************************************\r\nk_file             ='./forecast_input_tx/k_Reg12_Noah_MP_pb0.csv'\r\nx_file             ='./forecast_input_tx/x_Reg12_Noah_MP_pb0.csv'\r\nQout_nc_file       ='./output_forecast_tx/Texas.2000.2007.NoahMP.Calibed.nc'\r\n\r\n!*******************************************************************************\r\n!Optimization\r\n!*******************************************************************************\r\n!ZS_phifac          =0.001\r\n!------------------------------------------------------------------------------\r\n!Routing parameters\r\n!------------------------------------------------------------------------------\r\n!kfac_file          ='./input_tx_noahmp_00_12_opt/kfac_TX_1km_hour.csv'   \r\n!xfac_file          ='' \r\n!ZS_knorm_init      =4 \r\n!ZS_xnorm_init      =1\r\n!------------------------------------------------------------------------------\r\n!Gage observations\r\n!------------------------------------------------------------------------------\r\n!IS_gagetot         =248\r\n!gagetot_id_file    ='./input_tx_noahmp_00_12_opt/gage_id_Reg12_2000_2007_full.csv'\r\n!Qobs_file          ='./input_tx_noahmp_00_12_opt/Qobs_Reg12_2000_2007_full.csv'\r\n!Qobsbarrec_file    =''     \r\n!IS_gageuse         =248\r\n!gageuse_id_file    ='./input_tx_noahmp_00_12_opt/gage_id_Reg12_2000_2007_full.csv'\r\n!IS_strt_opt        =1\r\n!*******************************************************************************\r\n!End name list\r\n!*******************************************************************************\r\n/\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_net_mat.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_net_mat\n!*******************************************************************************\nsubroutine rapid_net_mat\n\n!Purpose:\n!This creates a sparse network matrix.  \"1\" is recorded at Net(i,j) if the reach\n!in column j flows into the reach in line i. If some connections are missing\n!between the subbasin and the entire domain, gives warnings.\n!A transboundary matrix is also created whose elements in the diagonal blocks\n!are all null and the elements in the off-diagonal blocks are equal to those of\n!the network matrix.\n!Author:\n!Cedric H. David, 2008-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   IS_riv_tot,IS_riv_bas,                                      &\n                   JS_riv_tot,JS_riv_bas,JS_riv_bas2,                          &\n                   IV_riv_bas_id,IV_riv_index,ZM_hsh_bas,                      &\n                   ZM_Net,ZM_A,ZM_T,ZM_TC1,BS_logical,IV_riv_tot_id,           &\n                   IV_down,IV_nbup,IM_up,JS_up,IM_index_up,                    &\n                   ierr,rank,ZS_val,                                           &\n                   IS_one,ZS_one,temp_char,IV_nz,IV_dnz,IV_onz,                &\n                   IS_ownfirst,IS_ownlast,IS_opt_routing\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n\n\n!*******************************************************************************\n!Prepare for matrix preallocation\n!*******************************************************************************\nIS_ownfirst=0\nIS_ownlast=0\ndo JS_riv_bas=1,IS_riv_bas\n     IV_nz(JS_riv_bas)=0\n     IV_dnz(JS_riv_bas)=0\n     IV_onz(JS_riv_bas)=0\nend do\n!Initialize to zero\n\ncall MatGetOwnershipRange(ZM_Net,IS_ownfirst,IS_ownlast,ierr)\n\ndo JS_riv_bas2=1,IS_riv_bas\ndo JS_up=1,IV_nbup(IV_riv_index(JS_riv_bas2))\nif (IM_index_up(JS_riv_bas2,JS_up)/=0) then\n\n     JS_riv_bas=IM_index_up(JS_riv_bas2,JS_up)\n     !Here JS_riv_bas is determined upstream of JS_riv_bas2\n     !both IS_riv_bas2 and IS_riv_bas are used here because the location\n     !of nonzeros depends on row and column in an parallel matrix\n\n     IV_nz(JS_riv_bas2)=IV_nz(JS_riv_bas2)+1\n     !The size of IV_nz is IS_riv_bas, IV_nz is the same across computing cores\n\n     if ((JS_riv_bas >=IS_ownfirst+1 .and.  JS_riv_bas< IS_ownlast+1) .and.    &\n         (JS_riv_bas2>=IS_ownfirst+1 .and. JS_riv_bas2< IS_ownlast+1)) then\n          IV_dnz(JS_riv_bas2)=IV_dnz(JS_riv_bas2)+1\n     end if\n     if ((JS_riv_bas < IS_ownfirst+1 .or.  JS_riv_bas >=IS_ownlast+1) .and.    &\n         (JS_riv_bas2>=IS_ownfirst+1 .and. JS_riv_bas2< IS_ownlast+1)) then\n          IV_onz(JS_riv_bas2)=IV_onz(JS_riv_bas2)+1\n     end if\n     !The size of IV_dnz and of IV_onz is IS_riv_bas. The values of IV_dnz and\n     !IV_onz are not the same across computing cores.  For each core, the\n     !only the values located in the range (IS_ownfirst+1:IS_ownlast) are\n     !correct but only these are used in the preallocation below.\n\nend if\nend do\nend do\n\n!print *, 'rank', rank, 'IV_nz(:)' , IV_nz(:)\n!print *, 'rank', rank, 'IV_dnz(:)', IV_dnz(:)\n!print *, 'rank', rank, 'IV_onz(:)', IV_onz(:)\n\n\n!*******************************************************************************\n!Matrix preallocation\n!*******************************************************************************\n!call MatSeqAIJSetPreallocation(ZM_Net,3*IS_one,PETSC_NULL_INTEGER,ierr)\n!call MatMPIAIJSetPreallocation(ZM_Net,3*IS_one,PETSC_NULL_INTEGER,2*IS_one,    &\n!                               PETSC_NULL_INTEGER,ierr)\n!call MatSeqAIJSetPreallocation(ZM_A,4*IS_one,PETSC_NULL_INTEGER,ierr)\n!call MatMPIAIJSetPreallocation(ZM_A,4*IS_one,PETSC_NULL_INTEGER,2*IS_one,      &\n!                               PETSC_NULL_INTEGER,ierr)\n!call MatSeqAIJSetPreallocation(ZM_T,4*IS_one,PETSC_NULL_INTEGER,ierr)\n!call MatMPIAIJSetPreallocation(ZM_T,4*IS_one,PETSC_NULL_INTEGER,2*IS_one,      &\n!                               PETSC_NULL_INTEGER,ierr)\n!call MatSeqAIJSetPreallocation(ZM_TC1,4*IS_one,PETSC_NULL_INTEGER,ierr)\n!call MatMPIAIJSetPreallocation(ZM_TC1,4*IS_one,PETSC_NULL_INTEGER,2*IS_one,    &\n!                               PETSC_NULL_INTEGER,ierr)\n!Very basic preallocation assuming no more than 3 upstream elements anywhere\n!Not used here because proper preallocation is done below\n\ncall MatSeqAIJSetPreallocation(ZM_Net,PETSC_NULL_INTEGER,IV_nz,ierr)\ncall MatMPIAIJSetPreallocation(ZM_Net,                                         &\n                               PETSC_NULL_INTEGER,                             &\n                               IV_dnz(IS_ownfirst+1:IS_ownlast),               &\n                               PETSC_NULL_INTEGER,                             &\n                               IV_onz(IS_ownfirst+1:IS_ownlast),ierr)\ncall MatSeqAIJSetPreallocation(ZM_A,PETSC_NULL_INTEGER,IV_nz+1,ierr)\ncall MatMPIAIJSetPreallocation(ZM_A,                                           &\n                               PETSC_NULL_INTEGER,                             &\n                               IV_dnz(IS_ownfirst+1:IS_ownlast)+1,             &\n                               PETSC_NULL_INTEGER,                             &\n                               IV_onz(IS_ownfirst+1:IS_ownlast),ierr)\ncall MatSeqAIJSetPreallocation(ZM_T,PETSC_NULL_INTEGER,0*IV_nz,ierr)\ncall MatMPIAIJSetPreallocation(ZM_T,                                           &\n                               PETSC_NULL_INTEGER,                             &\n                               0*IV_dnz(IS_ownfirst+1:IS_ownlast),             &\n                               PETSC_NULL_INTEGER,                             &\n                               IV_onz(IS_ownfirst+1:IS_ownlast),ierr)\ncall MatSeqAIJSetPreallocation(ZM_TC1,PETSC_NULL_INTEGER,0*IV_nz,ierr)\ncall MatMPIAIJSetPreallocation(ZM_TC1,                                         &\n                               PETSC_NULL_INTEGER,                             &\n                               0*IV_dnz(IS_ownfirst+1:IS_ownlast),             &\n                               PETSC_NULL_INTEGER,                             &\n                               IV_onz(IS_ownfirst+1:IS_ownlast),ierr)\ncall PetscPrintf(PETSC_COMM_WORLD,'Network matrix preallocated'//char(10),ierr)\n\n\n!*******************************************************************************\n!Creates network matrix\n!*******************************************************************************\nif (rank==0) then\n!only first processor sets values\n\ndo JS_riv_bas2=1,IS_riv_bas\ndo JS_up=1,IV_nbup(IV_riv_index(JS_riv_bas2))\nif (IM_index_up(JS_riv_bas2,JS_up)/=0) then\n\n     JS_riv_bas=IM_index_up(JS_riv_bas2,JS_up)\n     !Here JS_riv_bas is determined upstream of JS_riv_bas2\n     !both IS_riv_bas2 and IS_riv_bas are used here because the location\n     !of nonzeros depends on row and column in a parallel matrix\n\n     call MatSetValues(ZM_Net,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas-1,        &\n                       ZS_one,INSERT_VALUES,ierr)\n     CHKERRQ(ierr)\n     !Actual values used for ZM_Net\n\n     call MatSetValues(ZM_A  ,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas-1,        &\n                       0*ZS_one,INSERT_VALUES,ierr)\n     CHKERRQ(ierr)\n     !zeros (instead of -C1is) are used here on the off-diagonal of ZM_A because\n     !C1is are not yet computed, because ZM_A will later be populated based on\n     !ZM_Net, and because ZM_Net may be later modified for forcing or dams.\n     !Also when running RAPID in optimization mode, it is necessary to recreate\n     !ZM_A from scratch every time the parameters C1is are updated\n\nend if\nend do\ncall MatSetValues(ZM_A  ,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas2-1,            &\n                  0*ZS_one,INSERT_VALUES,ierr)\nCHKERRQ(ierr)\n!zeros (instead of ones) are used on the main diagonal of ZM_A because ZM_A will\n!be diagonally scaled by ZV_C1 before the diagonal is populated by ones.\nend do\n\nend if\n\ncall MatAssemblyBegin(ZM_Net,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_Net,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyBegin(ZM_A  ,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_A  ,MAT_FINAL_ASSEMBLY,ierr)\n!sparse matrices need be assembled once their elements have been filled\ncall PetscPrintf(PETSC_COMM_WORLD,'Network matrix created'//char(10),ierr)\n\n\n!*******************************************************************************\n!Creates transboundary matrix\n!*******************************************************************************\nif (IS_opt_routing==3) then\n\ndo JS_riv_bas2=1,IS_riv_bas\ndo JS_up=1,IV_nbup(IV_riv_index(JS_riv_bas2))\nif (IM_index_up(JS_riv_bas2,JS_up)/=0) then\n\n     JS_riv_bas=IM_index_up(JS_riv_bas2,JS_up)\n     !Here JS_riv_bas is determined upstream of JS_riv_bas2\n     !both IS_riv_bas2 and IS_riv_bas are used here because the location\n     !of nonzeros depends on row and column in a parallel matrix\n\n     if ((JS_riv_bas < IS_ownfirst+1 .or.  JS_riv_bas >=IS_ownlast+1) .and.    &\n         (JS_riv_bas2>=IS_ownfirst+1 .and. JS_riv_bas2< IS_ownlast+1)) then\n\n     call MatSetValues(ZM_T,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas-1,          &\n                       ZS_one,INSERT_VALUES,ierr)\n     CHKERRQ(ierr)\n     !Actual values (ones) used for ZM_T\n\n     call MatSetValues(ZM_TC1,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas-1,        &\n                       0*ZS_one,INSERT_VALUES,ierr)\n     CHKERRQ(ierr)\n     !zeros (instead of C1is) are used here everywhere in ZM_TC1 because\n     !C1is are not yet computed, because ZM_TC1 will later be populated based on\n     !ZM_T, and because ZM_T may be later modified for forcing or dams.\n     !Also when running RAPID in optimization mode, it is necessary to recreate\n     !ZM_TC1 from scratch every time the parameters C1is are updated\n\n     end if\n\nend if\nend do\nend do\n\ncall MatAssemblyBegin(ZM_T,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_T,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyBegin(ZM_TC1,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_TC1,MAT_FINAL_ASSEMBLY,ierr)\ncall PetscPrintf(PETSC_COMM_WORLD,'Transboundary matrix created'//char(10),ierr)\n\nend if\n\n\n!*******************************************************************************\n!Checks for missing connections and gives warning\n!*******************************************************************************\ndo JS_riv_tot=1,IS_riv_tot\n     ZS_val=-999\n     call MatGetValues(ZM_hsh_bas,                                             &\n                       IS_one,rank,                                            &\n                       IS_one,IV_riv_tot_id(JS_riv_tot)-1,                     &\n                       ZS_val,ierr)\n     CHKERRQ(ierr)\n     JS_riv_bas2=int(ZS_val)\n     if (JS_riv_bas2>0) then\n          !print *, 'Reach ID', IV_riv_tot_id(JS_riv_tot), 'is in basin'\n     else\n          !print *, 'Reach ID', IV_riv_tot_id(JS_riv_tot), 'is not in basin'\n\n!-------------------------------------------------------------------------------\n!Looking for missing upstream connections\n!-------------------------------------------------------------------------------\nZS_val=-999\ncall MatGetValues(ZM_hsh_bas,                                                  &\n                  IS_one,rank,                                                 &\n                  IS_one,IV_down(JS_riv_tot)-1,                                &\n                  ZS_val,ierr)\nCHKERRQ(ierr)\nJS_riv_bas=int(ZS_val)\nif(JS_riv_bas>0) then\n     write(temp_char,'(i10)') IV_riv_tot_id(JS_riv_tot)\n     call PetscPrintf(PETSC_COMM_WORLD,                                        &\n                      'WARNING: reach ID' // temp_char,ierr)\n     write(temp_char,'(i10)') IV_riv_bas_id(JS_riv_bas)\n     call PetscPrintf(PETSC_COMM_WORLD,                                        &\n                      ' should be connected upstream of reach ID'              &\n                      // temp_char // char(10),ierr)\n     call PetscPrintf(PETSC_COMM_WORLD,                                        &\n                      '         Make sure upstream forcing is available'       &\n                      // char(10),ierr)\nend if\n!-------------------------------------------------------------------------------\n!Looking for missing upstream connections\n!-------------------------------------------------------------------------------\ndo JS_up=1,IV_nbup(JS_riv_tot)\nZS_val=-999\ncall MatGetValues(ZM_hsh_bas,                                                  &\n                  IS_one,rank,                                                 &\n                  IS_one,IM_up(JS_riv_tot,JS_up)-1,                            &\n                  ZS_val,ierr)\nCHKERRQ(ierr)\nJS_riv_bas=int(ZS_val)\nif (JS_riv_bas>0) then\n     write(temp_char,'(i10)') IV_riv_tot_id(JS_riv_tot)\n     call PetscPrintf(PETSC_COMM_WORLD,                                        &\n                      'WARNING: reach ID' // temp_char,ierr)\n     write(temp_char,'(i10)') IV_riv_bas_id(JS_riv_bas)\n     call PetscPrintf(PETSC_COMM_WORLD,                                        &\n                      ' should be connected downstream of reach ID'            &\n                      // temp_char // char(10),ierr)\nend if\nend do\n!-------------------------------------------------------------------------------\n!Done looking\n!-------------------------------------------------------------------------------\n\n     end if\nend do\ncall PetscPrintf(PETSC_COMM_WORLD,'Checked for missing connections between '// &\n                 'basin studied and rest of domain'//char(10),ierr)\n\n\n!*******************************************************************************\n!Display matrices on stdout\n!*******************************************************************************\n!call PetscPrintf(PETSC_COMM_WORLD,'ZM_Net'//char(10),ierr)\n!call MatView(ZM_Net,PETSC_VIEWER_STDOUT_WORLD,ierr)\n!\n!call PetscPrintf(PETSC_COMM_WORLD,'ZM_A'//char(10),ierr)\n!call MatView(ZM_A,PETSC_VIEWER_STDOUT_WORLD,ierr)\n!\n!if (IS_opt_routing==3) then\n!     call PetscPrintf(PETSC_COMM_WORLD,'ZM_T'//char(10),ierr)\n!     call MatView(ZM_T,PETSC_VIEWER_STDOUT_WORLD,ierr)\n!\n!     call PetscPrintf(PETSC_COMM_WORLD,'ZM_TC1'//char(10),ierr)\n!     call MatView(ZM_TC1,PETSC_VIEWER_STDOUT_WORLD,ierr)\n!end if\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\n\n\nend subroutine rapid_net_mat\n"
  },
  {
    "path": "src/Rapid_routing/rapid_net_mat_brk.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_net_mat_brk\n!*******************************************************************************\nsubroutine rapid_net_mat_brk\n\n!Purpose:\n!This subroutine modifies the network and transboundary matrices based on a list\n!of river IDs.\n!The connectivity is broken between each given river ID and its downstream\n!river.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   IS_riv_bas,JS_riv_bas,JS_riv_bas2,                          &\n                   IV_riv_bas_id,IV_riv_index,                                 &\n                   ZM_Net,ZM_T,IV_down,IV_nbup,JS_up,IM_index_up,              &\n                   IS_for_bas,JS_for_bas,IV_for_bas_id,                        &\n                   IS_dam_bas,JS_dam_bas,IV_dam_bas_id,                        &\n                   ierr,rank,                                                  &\n                   IS_one,ZS_one,temp_char,                                    &\n                   IS_ownfirst,IS_ownlast,                                     &\n                   BS_opt_for,BS_opt_dam,IS_opt_routing\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n\n\n!*******************************************************************************\n!If forcing is used\n!*******************************************************************************\nif (BS_opt_for) then\n\n!-------------------------------------------------------------------------------\n!Breaks Net matrix connectivity in case forcing used is inside basin studied\n!-------------------------------------------------------------------------------\nif (IS_for_bas>0) then\ncall PetscPrintf(PETSC_COMM_WORLD,'Modifying network matrix'//char(10),ierr)\nend if\n\nif (rank==0) then\n!only first processor sets values\ndo JS_for_bas=1,IS_for_bas\n     do JS_riv_bas=1,IS_riv_bas\n          if (IV_for_bas_id(JS_for_bas)==IV_riv_bas_id(JS_riv_bas)) then\n\n     do JS_riv_bas2=1,IS_riv_bas\n          if (IV_down(IV_riv_index(JS_riv_bas))==IV_riv_bas_id(JS_riv_bas2))then\n          !here JS_riv_bas2 is determined as directly downstream of JS_riv_bas\n          !and the connection between both needs be broken\n\n          call MatSetValues(ZM_Net,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas-1,   &\n                            0*ZS_one,INSERT_VALUES,ierr)\n          CHKERRQ(ierr)\n          !Breaks connection for matrix-based Muskingum method\n\n          do JS_up=1,IV_nbup(IV_riv_index(JS_riv_bas2))\n               if (IM_index_up(JS_riv_bas2,JS_up)==JS_riv_bas) then\n                    IM_index_up(JS_riv_bas2,JS_up)=0\n               end if\n          end do\n          !Breaks connection for traditional Muskingum method\n\n          write(temp_char,'(i10)') IV_riv_bas_id(JS_riv_bas)\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           '         connection broken downstream of reach ID' &\n                            // temp_char,ierr)\n          write(temp_char,'(i10)') IV_riv_bas_id(JS_riv_bas2)\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           ' forcing data will be used for reach ID'           &\n                           // temp_char // char(10),ierr)\n          !Writes information on connection that was just broken in stdout\n\n          end if\n     end do\n\n          end if\n     end do\nend do\nend if\ncall MatAssemblyBegin(ZM_Net,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_Net,MAT_FINAL_ASSEMBLY,ierr)\n!!sparse matrices need be assembled once their elements have been filled\ncall PetscPrintf(PETSC_COMM_WORLD,'Network matrix modified for forcing'//      &\n                 char(10),ierr)\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Breaks T matrix connectivity in case forcing is used inside basin studied\n!-------------------------------------------------------------------------------\nif (IS_opt_routing==3) then\n\nif (IS_for_bas>0) then\ncall PetscPrintf(PETSC_COMM_WORLD,'Modifying transboundary matrix'//           &\n                 char(10),ierr)\nend if\n\ndo JS_for_bas=1,IS_for_bas\n     do JS_riv_bas=1,IS_riv_bas\n          if (IV_for_bas_id(JS_for_bas)==IV_riv_bas_id(JS_riv_bas)) then\n\n     do JS_riv_bas2=1,IS_riv_bas\n          if (IV_down(IV_riv_index(JS_riv_bas))==IV_riv_bas_id(JS_riv_bas2))then\n          !here JS_riv_bas2 is determined as directly downstream of JS_riv_bas\n          !and the connection between both needs be broken\n\nif ((JS_riv_bas < IS_ownfirst+1 .or.  JS_riv_bas >=IS_ownlast+1) .and.         &\n    (JS_riv_bas2>=IS_ownfirst+1 .and. JS_riv_bas2< IS_ownlast+1)) then\n\n     call MatSetValues(ZM_T,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas-1,          &\n                       0*ZS_one,INSERT_VALUES,ierr)\n     CHKERRQ(ierr)\n     !Breaks connection of transboundary matrix\n\nend if\n\n          end if\n     end do\n\n          end if\n     end do\nend do\ncall MatAssemblyBegin(ZM_T,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_T,MAT_FINAL_ASSEMBLY,ierr)\n!!sparse matrices need be assembled once their elements have been filled\ncall PetscPrintf(PETSC_COMM_WORLD,'Transboundary matrix modified for forcing'//&\n                 char(10),ierr)\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\n\nend if\n\n!-------------------------------------------------------------------------------\n!End if forcing is used\n!-------------------------------------------------------------------------------\nend if\n\n\n!*******************************************************************************\n!If dam model is used\n!*******************************************************************************\nif (BS_opt_dam) then\n\n!-------------------------------------------------------------------------------\n!Breaks matrix connectivity in case dam model is used inside basin studied\n!-------------------------------------------------------------------------------\nif (IS_dam_bas>0) then\ncall PetscPrintf(PETSC_COMM_WORLD,'Modifying network matrix'//char(10),ierr)\nend if\n\nif (rank==0) then\n!only first processor sets values\ndo JS_dam_bas=1,IS_dam_bas\n     do JS_riv_bas=1,IS_riv_bas\n          if (IV_dam_bas_id(JS_dam_bas)==IV_riv_bas_id(JS_riv_bas)) then\n\n     do JS_riv_bas2=1,IS_riv_bas\n          if (IV_down(IV_riv_index(JS_riv_bas))==IV_riv_bas_id(JS_riv_bas2))then\n          !here JS_riv_bas2 is determined as directly downstream of JS_riv_bas\n          !and the connection between both needs be broken\n\n          call MatSetValues(ZM_Net,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas-1,   &\n                            0*ZS_one,INSERT_VALUES,ierr)\n          CHKERRQ(ierr)\n          !Breaks connection for matrix-based Muskingum method\n\n          do JS_up=1,IV_nbup(IV_riv_index(JS_riv_bas2))\n               if (IM_index_up(JS_riv_bas2,JS_up)==JS_riv_bas) then\n                    IM_index_up(JS_riv_bas2,JS_up)=0\n               end if\n          end do\n          !Breaks connection for traditional Muskingum method\n\n\n          write(temp_char,'(i10)') IV_riv_bas_id(JS_riv_bas)\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           '         connection broken downstream of reach ID' &\n                            // temp_char,ierr)\n          write(temp_char,'(i10)') IV_riv_bas_id(JS_riv_bas2)\n          call PetscPrintf(PETSC_COMM_WORLD,                                   &\n                           ' dam data will be used for reach ID'           &\n                           // temp_char // char(10),ierr)\n          !Writes information on connection that was just broken in stdout\n\n          end if\n     end do\n\n          end if\n     end do\nend do\nend if\ncall MatAssemblyBegin(ZM_Net,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_Net,MAT_FINAL_ASSEMBLY,ierr)\n!sparse matrices need be assembled once their elements have been filled\ncall PetscPrintf(PETSC_COMM_WORLD,'Network matrix modified for dams'//         &\n                 char(10),ierr)\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\n\n!-------------------------------------------------------------------------------\n!Breaks T matrix connectivity in case dam model is used inside basin studied\n!-------------------------------------------------------------------------------\nif (IS_opt_routing==3) then\n\nif (IS_dam_bas>0) then\ncall PetscPrintf(PETSC_COMM_WORLD,'Modifying transboundary matrix'//           &\n                 char(10),ierr)\nend if\n\ndo JS_dam_bas=1,IS_dam_bas\n     do JS_riv_bas=1,IS_riv_bas\n          if (IV_dam_bas_id(JS_dam_bas)==IV_riv_bas_id(JS_riv_bas)) then\n\n     do JS_riv_bas2=1,IS_riv_bas\n          if (IV_down(IV_riv_index(JS_riv_bas))==IV_riv_bas_id(JS_riv_bas2))then\n          !here JS_riv_bas2 is determined as directly downstream of JS_riv_bas\n          !and the connection between both needs be broken\n\nif ((JS_riv_bas < IS_ownfirst+1 .or.  JS_riv_bas >=IS_ownlast+1) .and.         &\n    (JS_riv_bas2>=IS_ownfirst+1 .and. JS_riv_bas2< IS_ownlast+1)) then\n\n     call MatSetValues(ZM_T,IS_one,JS_riv_bas2-1,IS_one,JS_riv_bas-1,          &\n                       0*ZS_one,INSERT_VALUES,ierr)\n     CHKERRQ(ierr)\n     !Breaks connection of transboundary matrix\n\nend if\n\n          end if\n     end do\n\n          end if\n     end do\nend do\ncall MatAssemblyBegin(ZM_T,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_T,MAT_FINAL_ASSEMBLY,ierr)\n!!sparse matrices need be assembled once their elements have been filled\ncall PetscPrintf(PETSC_COMM_WORLD,'Transboundary matrix modified for dams'//   &\n                 char(10),ierr)\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\n\nend if\n\n!-------------------------------------------------------------------------------\n!End if dam model is used\n!-------------------------------------------------------------------------------\nend if\n\n\n!*******************************************************************************\n!Display matrix on stdout\n!*******************************************************************************\n!call PetscPrintf(PETSC_COMM_WORLD,'ZM_Net'//char(10),ierr)\n!call MatView(ZM_Net,PETSC_VIEWER_STDOUT_WORLD,ierr)\n!\n!if (IS_opt_routing==3) then\n!     call PetscPrintf(PETSC_COMM_WORLD,'ZM_T'//char(10),ierr)\n!     call MatView(ZM_T,PETSC_VIEWER_STDOUT_WORLD,ierr)\n!end if\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\n\nend subroutine rapid_net_mat_brk\n"
  },
  {
    "path": "src/Rapid_routing/rapid_obs_mat.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_obs_mat\n!*******************************************************************************\nsubroutine rapid_obs_mat\n\n!Purpose:\n!Creates a kronecker-type diagonal sparse matrix.  \"1\" is recorded at the row\n!and column where observations are available.\n!Author:\n!Cedric H. David, 2008-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   IS_riv_bas,JS_riv_bas,                                      &\n                   IS_obs_bas,JS_obs_bas,                                      &\n                   IV_riv_bas_id,IV_obs_tot_id,                                &\n                   IV_obs_index,                                               &\n                   ZM_Obs,ZS_norm,                                             &\n                   ierr,                                                       &\n                   IS_one,ZS_one,temp_char\n\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n\n\n!*******************************************************************************\n!Preallocation of the observation matrix\n!*******************************************************************************\ncall MatSeqAIJSetPreallocation(ZM_Obs,1*IS_one,PETSC_NULL_INTEGER,ierr)\ncall MatMPIAIJSetPreallocation(ZM_Obs,1*IS_one,PETSC_NULL_INTEGER,0*IS_one,    &\n                               PETSC_NULL_INTEGER,ierr)\n!Very basic preallocation assuming that all reaches have one gage.  Cannot use\n!IV_obs_loc1 for preallocation because it is of size IS_obs_bas and not\n!IS_riv_bas. To do a better preallocation one needs to count the diagonal\n!elements in a new vector\n\n!call PetscPrintf(PETSC_COMM_WORLD,'Observation matrix preallocated'//char(10), &\n!                 ierr)\n\n\n!*******************************************************************************\n!Creation of the observation matrix\n!*******************************************************************************\ndo JS_riv_bas=1,IS_riv_bas\n     do JS_obs_bas=1,IS_obs_bas\n\nif (IV_obs_tot_id(IV_obs_index(JS_obs_bas))==IV_riv_bas_id(JS_riv_bas)) then\n          call MatSetValues(ZM_Obs,IS_one,JS_riv_bas-1,IS_one,JS_riv_bas-1,    &\n                            ZS_one,INSERT_VALUES,ierr)\nend if\n\n     enddo\nenddo\n\ncall MatAssemblyBegin(ZM_Obs,MAT_FINAL_ASSEMBLY,ierr)\ncall MatAssemblyEnd(ZM_Obs,MAT_FINAL_ASSEMBLY,ierr)\n!sparse matrices need be assembled once their elements have been filled\n\n\n!*******************************************************************************\n!Optional: calculation of number of gaging stations used in subbasin\n!*******************************************************************************\ncall MatNorm(ZM_Obs,NORM_FROBENIUS,ZS_norm,ierr)\nZS_norm=ZS_norm*ZS_norm\nwrite(temp_char,'(f10.1)') ZS_norm\ncall PetscPrintf(PETSC_COMM_WORLD,'Number of gage IDs in '           //        &\n                 'this simulation (based on norm):' // temp_char // char(10),  &\n                 ierr)\n\n\n!*******************************************************************************\n!Display matrix on stdout\n!*******************************************************************************\n!call PetscPrintf(PETSC_COMM_WORLD,'ZM_Obs:'//char(10),ierr)\n!call MatView(ZM_Obs,PETSC_VIEWER_STDOUT_WORLD,ierr)\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\ncall PetscPrintf(PETSC_COMM_WORLD,'Observation matrix created'//char(10),ierr)\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\n\n\nend subroutine rapid_obs_mat\n"
  },
  {
    "path": "src/Rapid_routing/rapid_open_Qfor_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_open_Qfor\n!*******************************************************************************\nsubroutine rapid_open_Qfor_file(Qfor_file)\n\n!Purpose:\n!Open Qfor_file from Fortran.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   rank\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\ncharacter(len=100), intent(in):: Qfor_file\n\n\n!*******************************************************************************\n!Open file\n!*******************************************************************************\nif (rank==0) open(34,file=Qfor_file,status='old')\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_open_Qfor_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_open_Qhum_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_open_Qhum\n!*******************************************************************************\nsubroutine rapid_open_Qhum_file(Qhum_file)\n\n!Purpose:\n!Open Qhum_file from Fortran.\n!Author:\n!Cedric H. David, 2014-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   rank\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\ncharacter(len=100), intent(in):: Qhum_file\n\n\n!*******************************************************************************\n!Open file\n!*******************************************************************************\nif (rank==0) open(36,file=Qhum_file,status='old')\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_open_Qhum_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_open_Qobs_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_open_Qobs\n!*******************************************************************************\nsubroutine rapid_open_Qobs_file(Qobs_file)\n\n!Purpose:\n!Open Qobs_file from Fortran.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   rank\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\ncharacter(len=100), intent(in):: Qobs_file\n\n\n!*******************************************************************************\n!Open file\n!*******************************************************************************\nif (rank==0) open(33,file=Qobs_file,status='old')\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_open_Qobs_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_open_Qout_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_open_Qout_file\n!*******************************************************************************\nsubroutine rapid_open_Qout_file(Qout_file)\n\n!Purpose:\n!Open Qout_file from Fortran/netCDF.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse netcdf\nuse rapid_var, only :                                                          &\n                   rank,IS_nc_status,IS_nc_id_fil_Qout,IS_nc_id_var_Qout\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\ncharacter(len=100), intent(in):: Qout_file\n\n\n!*******************************************************************************\n!Open file\n!*******************************************************************************\nif (rank==0) then\n     close(99)\n     open(99,file=Qout_file,status='old')\n     close(99)\n     IS_nc_status=NF90_OPEN(Qout_file,NF90_WRITE,IS_nc_id_fil_Qout)\n     IS_nc_status=NF90_INQ_VARID(IS_nc_id_fil_Qout,'Qout',IS_nc_id_var_Qout)\nend if\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_open_Qout_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_open_Vlat_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_open_Vlat_file\n!*******************************************************************************\nsubroutine rapid_open_Vlat_file(Vlat_file)\n\n!Purpose:\n!Open Vlat_file from Fortran/netCDF.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse netcdf\nuse rapid_var, only :                                                          &\n                   rank,IS_nc_status,IS_nc_id_fil_Vlat,IS_nc_id_var_Vlat\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\ncharacter(len=100), intent(in):: Vlat_file\n\n\n!*******************************************************************************\n!Open file\n!*******************************************************************************\nif (rank==0) then\n     open(99,file=Vlat_file,status='old')\n     close(99)\n     IS_nc_status=NF90_OPEN(Vlat_file,NF90_NOWRITE,IS_nc_id_fil_Vlat)\n     IS_nc_status=NF90_INQ_VARID(IS_nc_id_fil_Vlat,'m3_riv',IS_nc_id_var_Vlat)\nend if\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_open_Vlat_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_phiroutine.F90",
    "content": "!*******************************************************************************\r\n!Subroutine - rapid_phiroutine\r\n!*******************************************************************************\r\n#ifndef NO_TAO\r\nsubroutine rapid_phiroutine(tao,ZV_pnorm,ZS_phi,IS_dummy,ierr)\r\n\r\n!Purpose:\r\n!Calculates a cost function phi as a function of model parameters, using means\r\n!over a given period of time.  The cost function represents the square error\r\n!between calculated flows and observed flows where observations are available.\r\n!Author:\r\n!Cedric H. David, 2008-2015.\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables\r\n!*******************************************************************************\r\nuse rapid_var, only :                                                          &\r\n                   Vlat_file,Qobs_file,Qfor_file,Qhum_file,                    &\r\n                   JS_O,IS_O,JS_RpO,IS_RpO,ZS_TauR,IS_RpF,IS_RpH,              &\r\n                   ZM_Obs,ZV_Qobs,                                             &\r\n                   ZV_temp1,ZV_temp2,ZS_phitemp,ZS_phifac,ZV_kfac,             &\r\n                   IS_riv_tot,IS_for_bas,IS_hum_bas,                           &\r\n                   ZS_knorm,ZS_xnorm,ZV_k,ZV_x,ZS_xfac,                        &\r\n                   ZV_1stIndex,ZV_2ndIndex,                                    &\r\n                   ZV_C1,ZV_C2,ZV_C3,ZM_A,                                     &\r\n                   ZV_QoutinitO,ZV_QoutinitR,                                  &\r\n                   ZV_QoutbarO,ZV_VinitR,ZV_VR,ZV_VbarR,                       &\r\n                   ZV_QoutR,ZV_QoutbarR,                                       &\r\n                   ZV_Vlat,ZV_Qlat,ZV_Qfor,ZV_Qext,                            &\r\n                   ZV_Qobsbarrec,                                              &\r\n                   ksp,                                                        &\r\n                   ZS_one,temp_char,                                           &\r\n                   IV_nc_start,IV_nc_count,                                    &\r\n                   IS_opt_phi,BS_opt_for,IS_strt_opt,IS_opt_routing,           &\r\n                   BS_opt_dam,IS_dam_bas,ZV_Qdam,BS_opt_hum,ZV_Qhum\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n#include \"finclude/petscsys.h\"\r\n!base PETSc routines\r\n#include \"finclude/petscvec.h\"\r\n#include \"finclude/petscvec.h90\"\r\n!vectors, and vectors in Fortran90\r\n#include \"finclude/petscmat.h\"\r\n!matrices\r\n#include \"finclude/petscksp.h\"\r\n!Krylov subspace methods\r\n#include \"finclude/petscpc.h\"\r\n!preconditioners\r\n#include \"finclude/petscviewer.h\"\r\n!viewers (allows writing results in file for example)\r\n#include \"finclude/taosolver.h\"\r\n!TAO solver\r\n\r\n\r\n!*******************************************************************************\r\n!Intent (in/out), and local variables\r\n!*******************************************************************************\r\nVec, intent(in) :: ZV_pnorm\r\nTaoSolver, intent(inout)  :: tao\r\nPetscErrorCode, intent(out) :: ierr\r\nPetscScalar, intent(out):: ZS_phi\r\nPetscInt, intent (in) :: IS_dummy\r\n\r\n\r\n!*******************************************************************************\r\n!Set linear system corresponding to current ZV_pnorm and set initial flowrates\r\n!*******************************************************************************\r\nZS_phi=0\r\n!initialize phi to zero\r\n\r\ncall VecDot(ZV_pnorm,ZV_1stIndex,ZS_knorm,ierr)\r\ncall VecDot(ZV_pnorm,ZV_2ndIndex,ZS_xnorm,ierr)\r\ncall VecCopy(ZV_kfac,ZV_k,ierr)\r\ncall VecScale(ZV_k,ZS_knorm,ierr)\r\ncall VecSet(ZV_x,ZS_xfac,ierr)\r\ncall VecScale(ZV_x,ZS_xnorm,ierr)\r\n!compute ZV_k and ZV_x based on ZV_pnorm and ZV_kfac\r\n\r\ncall rapid_routing_param(ZV_k,ZV_x,ZV_C1,ZV_C2,ZV_C3,ZM_A)\r\n!calculate Muskingum parameters and matrix ZM_A\r\n\r\ncall KSPSetOperators(ksp,ZM_A,ZM_A,DIFFERENT_NONZERO_PATTERN,ierr)\r\ncall KSPSetType(ksp,KSPRICHARDSON,ierr)                    !default=richardson\r\ncall KSPSetFromOptions(ksp,ierr)                           !if runtime options\r\n!Set KSP to use matrix ZM_A\r\nif (IS_opt_routing==3) call KSPSetType(ksp,KSPPREONLY,ierr)!default=preonly\r\n\r\n\r\n!*******************************************************************************\r\n!Set initial values to assure subroutine always starts from same conditions\r\n!*******************************************************************************\r\n\r\n!-------------------------------------------------------------------------------\r\n!Set initial value of instantaneous flow\r\n!-------------------------------------------------------------------------------\r\ncall VecCopy(ZV_QoutinitO,ZV_QoutinitR,ierr)\r\n!copy initial optimization variables into initial routing variables\r\n\r\n!-------------------------------------------------------------------------------\r\n!Make sure the vectors potentially used for inflow to dams are initially null\r\n!-------------------------------------------------------------------------------\r\ncall VecSet(ZV_Qext,0*ZS_one,ierr)                         !Qext=0\r\ncall VecSet(ZV_QoutbarR,0*ZS_one,ierr)                     !QoutbarR=0\r\n!This matters only if rapid_get_Qdam is called because it uses these values\r\n\r\n!-------------------------------------------------------------------------------\r\n!Set initial value of Qext from Qout_dam0\r\n!-------------------------------------------------------------------------------\r\nif (BS_opt_dam .and. IS_dam_bas>0) then\r\n     call rapid_set_Qext0                                  !Qext from Qout_dam0\r\n     !call VecView(ZV_Qext,PETSC_VIEWER_STDOUT_WORLD,ierr)\r\nend if\r\n\r\n\r\n!*******************************************************************************\r\n!Calculate objective function for the whole period ZS_TauO\r\n!*******************************************************************************\r\n\r\n!-------------------------------------------------------------------------------\r\n!Open files\r\n!-------------------------------------------------------------------------------\r\ncall rapid_open_Vlat_file(Vlat_file)\r\ncall rapid_open_Qobs_file(Qobs_file)\r\nif (BS_opt_for) call rapid_open_Qfor_file(Qfor_file)\r\nif (BS_opt_hum) call rapid_open_Qhum_file(Qhum_file)\r\n\r\n\r\n!-------------------------------------------------------------------------------\r\n!Read and compute\r\n!-------------------------------------------------------------------------------\r\nIV_nc_start=(/1,IS_strt_opt/)\r\nIV_nc_count=(/IS_riv_tot,1/)\r\n\r\n\r\ndo JS_O=1,IS_O\r\n\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\n!calculate mean daily flow\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\ncall VecSet(ZV_QoutbarO,0*ZS_one,ierr)                 !QoutbarO=0\r\n\r\ndo JS_RpO=1,IS_RpO   !loop needed here since Vlat is more frequent than Qobs\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Read/set surface and subsurface volumes\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ncall rapid_read_Vlat_file\r\n\r\ncall VecCopy(ZV_Vlat,ZV_Qlat,ierr)            !Qlat=Vlat\r\ncall VecScale(ZV_Qlat,1/ZS_TauR,ierr)         !Qlat=Qlat/TauR\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Read/set upstream forcing\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nif (BS_opt_for .and. IS_for_bas>0                                              &\r\n                   .and. mod((JS_O-1)*IS_RpO+JS_RpO,IS_RpF)==1) then\r\n\r\ncall rapid_read_Qfor_file\r\n\r\nend if\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Run dam model based on previous values of QoutbarR and Qext to get Qdam\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nif (BS_opt_dam .and. IS_dam_bas>0) then\r\n\r\ncall rapid_get_Qdam\r\n\r\nend if\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Read/set human induced flows\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nif (BS_opt_hum .and. IS_hum_bas>0                                              &\r\n                   .and. mod((JS_O-1)*IS_RpO+JS_RpO,IS_RpH)==1) then\r\n\r\ncall rapid_read_Qhum_file\r\n\r\nend if\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!calculation of Qext\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ncall VecCopy(ZV_Qlat,ZV_Qext,ierr)                            !Qext=Qlat\r\nif (BS_opt_for) call VecAXPY(ZV_Qext,ZS_one,ZV_Qfor,ierr)     !Qext=Qext+1*Qfor\r\nif (BS_opt_dam) call VecAXPY(ZV_Qext,ZS_one,ZV_Qdam,ierr)     !Qext=Qext+1*Qdam\r\nif (BS_opt_hum) call VecAXPY(ZV_Qext,ZS_one,ZV_Qhum,ierr)     !Qext=Qext+1*Qhum\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Routing procedure\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ncall rapid_routing(ZV_C1,ZV_C2,ZV_C3,ZV_Qext,                                  &\r\n                   ZV_QoutinitR,ZV_VinitR,                                     &\r\n                   ZV_QoutR,ZV_QoutbarR,ZV_VR,ZV_VbarR)\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Update variables\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\ncall VecCopy(ZV_QoutR,ZV_QoutinitR,ierr)\r\n\r\ncall VecAXPY(ZV_QoutbarO,ZS_one/IS_RpO,ZV_QoutbarR,ierr)\r\n!Qoutbar=QoutbarO+QoutbarR/IS_RpO\r\n\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n!Update netCDF location\r\n!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\nIV_nc_start(2)=IV_nc_start(2)+1\r\n\r\n\r\nenddo                !end of loop to account for forcing more frequent than obs\r\n\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\n!Calculate objective function for current day\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\ncall rapid_read_Qobs_file\r\n\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\n!Objective function #1 - for current day - square error\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\nif (IS_opt_phi==1) then\r\ncall VecWAXPY(ZV_temp1,-ZS_one,ZV_Qobs,ZV_QoutbarO,ierr)  !temp1=Qoutbar-Qobs\r\ncall VecScale(ZV_temp1,ZS_phifac,ierr)                    !if phi too big\r\ncall MatMult(ZM_Obs,ZV_temp1,ZV_temp2,ierr)               !temp2=Obs*temp1\r\ncall VecDot(ZV_temp1,ZV_temp2,ZS_phitemp,ierr)            !phitemp=temp1.temp2\r\n!result phitemp=(Qoutbar-Qobs)^T*Obs*(Qoutbar-Qobs)\r\nend if\r\n\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\n!Objective function #2 - for current day - square error normalized by avg flow\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\nif (IS_opt_phi==2) then\r\ncall VecWAXPY(ZV_temp1,-ZS_one,ZV_Qobs,ZV_QoutbarO,ierr)  !temp1=Qoutbar-Qobs\r\ncall VecPointWiseMult(ZV_temp1,ZV_temp1,ZV_Qobsbarrec,ierr)!temp1=temp1.*Qobsbarrec\r\ncall MatMult(ZM_Obs,ZV_temp1,ZV_temp2,ierr)               !temp2=Obs*temp1\r\ncall VecDot(ZV_temp1,ZV_temp2,ZS_phitemp,ierr)            !phitemp=temp1.temp2\r\n!result phitemp=[(Qoutbar-Qobs).*Qobsbarrec]^T*Obs*[(Qoutbar-Qobs).*Qobsbarrec]\r\nend if\r\n\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\n!adds daily objective function to total objective function\r\n!- + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - +\r\nZS_phi=ZS_phi+ZS_phitemp\r\n!increments phi for each time step during the desired period of optimization\r\n\r\nenddo\r\n\r\n!-------------------------------------------------------------------------------\r\n!Close files\r\n!-------------------------------------------------------------------------------\r\ncall rapid_close_Vlat_file\r\ncall rapid_close_Qobs_file\r\ncall rapid_close_Qfor_file\r\ncall rapid_close_Qhum_file\r\n\r\n\r\n!*******************************************************************************\r\n!Write outputs (parameters and calculated objective function)\r\n!*******************************************************************************\r\ncall PetscPrintf(PETSC_COMM_WORLD,'current normalized p=(k,x)',ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,char(10),ierr)\r\ncall VecView(ZV_pnorm,PETSC_VIEWER_STDOUT_WORLD,ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,'corresponding value of phi',ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,char(10),ierr)\r\nwrite(temp_char,'(f10.3)') ZS_phi\r\ncall PetscPrintf(PETSC_COMM_WORLD,temp_char // char(10),ierr)\r\ncall PetscPrintf(PETSC_COMM_WORLD,'--------------------------'//char(10),ierr)\r\n\r\n\r\nend subroutine rapid_phiroutine\r\n#endif\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_read_Qfor_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_read_Qfor_file\n!*******************************************************************************\nsubroutine rapid_read_Qfor_file\n\n!Purpose:\n!Read Qfor_file from Fortran.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   rank,ierr,ZV_read_for_tot,                                  &\n                   ZV_Qfor,IS_for_bas,IV_for_loc2,IV_for_index,ZV_read_for_tot\n\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n#include \"finclude/petsclog.h\"\n!PETSc log\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Read file\n!*******************************************************************************\nif (rank==0) read(34,*) ZV_read_for_tot\n\n\n!*******************************************************************************\n!Set values in PETSc vector\n!*******************************************************************************\nif (rank==0) then\ncall VecSetValues(ZV_Qfor,IS_for_bas,IV_for_loc2,                              &\n                  ZV_read_for_tot(IV_for_index),INSERT_VALUES,ierr)\n                  !here we only look at the forcing within the basin studied\nend if\n\n!*******************************************************************************\n!Assemble PETSc vector\n!*******************************************************************************\ncall VecAssemblyBegin(ZV_Qfor,ierr)\ncall VecAssemblyEnd(ZV_Qfor,ierr)\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_read_Qfor_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_read_Qhum_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_read_Qhum_file\n!*******************************************************************************\nsubroutine rapid_read_Qhum_file\n\n!Purpose:\n!Read Qhum_file from Fortran.\n!Author:\n!Cedric H. David, 2014-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   rank,ierr,ZV_read_hum_tot,                                  &\n                   ZV_Qhum,IS_hum_bas,IV_hum_loc1,IV_hum_index,ZV_read_hum_tot\n\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n#include \"finclude/petsclog.h\"\n!PETSc log\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Read file\n!*******************************************************************************\nif (rank==0) read(36,*) ZV_read_hum_tot\n\n\n!*******************************************************************************\n!Set values in PETSc vector\n!*******************************************************************************\nif (rank==0) then\ncall VecSetValues(ZV_Qhum,IS_hum_bas,IV_hum_loc1,                              &\n                  ZV_read_hum_tot(IV_hum_index),INSERT_VALUES,ierr)\n                  !here we only look at the human-induced flows within the basin\n                  !studied\nend if\n\n!*******************************************************************************\n!Assemble PETSc vector\n!*******************************************************************************\ncall VecAssemblyBegin(ZV_Qhum,ierr)\ncall VecAssemblyEnd(ZV_Qhum,ierr)\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_read_Qhum_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_read_Qobs_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_read_Qobs_file\n!*******************************************************************************\nsubroutine rapid_read_Qobs_file\n\n!Purpose:\n!Read Qobs_file from Fortran.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   rank,ierr,                                                  &\n                   ZV_Qobs,IS_obs_bas,IV_obs_loc1,IV_obs_index,ZV_read_obs_tot\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n#include \"finclude/petsclog.h\"\n!PETSc log\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Read file\n!*******************************************************************************\nif (rank==0) read(33,*) ZV_read_obs_tot\n\n\n!*******************************************************************************\n!Set values in PETSc vector\n!*******************************************************************************\nif (rank==0) then\ncall VecSetValues(ZV_Qobs,IS_obs_bas,IV_obs_loc1,                              &\n                  ZV_read_obs_tot(IV_obs_index),INSERT_VALUES,ierr)\n                  !here we only look at the observations within the basin\n                  !studied\nend if\n\n\n!*******************************************************************************\n!Assemble PETSc vector\n!*******************************************************************************\ncall VecAssemblyBegin(ZV_Qobs,ierr)\ncall VecAssemblyEnd(ZV_Qobs,ierr)\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_read_Qobs_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_read_Vlat_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_read_Vlat_file\n!*******************************************************************************\nsubroutine rapid_read_Vlat_file\n\n!Purpose:\n!Read Vlat_file from Fortran.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse netcdf\nuse rapid_var, only :                                                          &\n                   rank,ierr,                                                  &\n                   IS_nc_status,IS_nc_id_fil_Vlat,IS_nc_id_var_Vlat,           &\n                   IV_nc_start,IV_nc_count,                                    &\n                   IS_riv_bas,IV_riv_loc1,IV_riv_index,ZV_read_riv_tot,ZV_Vlat\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n#include \"finclude/petsclog.h\"\n!PETSc log\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Read file\n!*******************************************************************************\nif (rank==0) then\n     IS_nc_status=NF90_GET_VAR(IS_nc_id_fil_Vlat,IS_nc_id_var_Vlat,            &\n                               ZV_read_riv_tot,IV_nc_start,IV_nc_count)\nend if\n\n\n!*******************************************************************************\n!Set values in PETSc vector\n!*******************************************************************************\nif (rank==0) then\n     call VecSetValues(ZV_Vlat,IS_riv_bas,IV_riv_loc1,                         &\n                       ZV_read_riv_tot(IV_riv_index),INSERT_VALUES,ierr)\nend if\n\n\n!*******************************************************************************\n!Assemble PETSc vector\n!*******************************************************************************\ncall VecAssemblyBegin(ZV_Vlat,ierr)\ncall VecAssemblyEnd(ZV_Vlat,ierr)\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_read_Vlat_file\n"
  },
  {
    "path": "src/Rapid_routing/rapid_read_namelist.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_read_namelist\n!*******************************************************************************\nsubroutine rapid_read_namelist\n\n!Purpose:\n!This subroutine allows to read the RAPID namelist and hence to run the model\n!multiple times without ever have to recompile.  Some information on the options\n!used is also printed in the stdout.\n!Author:\n!Cedric H. David, 2011-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                     NL_namelist,namelist_file\n\n\nimplicit none\n\n\n!*******************************************************************************\n!Read namelist file\n!*******************************************************************************\nopen(88,file=namelist_file,status='old',form='formatted')\nread(88, NL_namelist)\nclose(88)\n\n\n!*******************************************************************************\n!Optional prints what was read\n!*******************************************************************************\n!print *, namelist_file\n\n\nend subroutine rapid_read_namelist\n"
  },
  {
    "path": "src/Rapid_routing/rapid_routing.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_routing\n!*******************************************************************************\nsubroutine rapid_routing(ZV_C1,ZV_C2,ZV_C3,ZV_Qext,                            &\n                         ZV_QoutinitR,ZV_VinitR,                               &\n                         ZV_QoutR,ZV_QoutbarR,ZV_VR,ZV_VbarR)\n\n!Purpose:\n!Performs flow calculation in each reach of a river network using the Muskingum\n!method (McCarthy 1938).  Also calculates the volume of each reach using a\n!simple first order approximation\n!Author:\n!Cedric H. David, 2008-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse netcdf\nuse rapid_var, only :                                                          &\n                   ZS_dtR,IS_R,JS_R,                                           &\n                   ZM_Net,ZM_TC1,                                              &\n                   ZV_b,ZV_babsmax,ZV_bhat,                                    &\n                   ZV_QoutprevR,ZV_VprevR,ZV_QoutRabsmin,ZV_QoutRabsmax,       &\n                   ZV_QoutRhat,                                                &\n                   ZV_VoutR,ZV_Vext,                                           &\n                   ierr,ksp,                                                   &\n                   ZS_one,IS_ksp_iter,IS_ksp_iter_max,                         &\n                   vecscat,ZV_SeqZero,ZV_pointer,rank,                         &\n                   IS_nc_status,IS_nc_id_fil_Qout,IS_nc_id_var_Qout,           &\n                   IV_nc_start,IV_nc_count2,                                   &\n                   IS_riv_bas,JS_riv_bas,IM_index_up,                          &\n                   IS_opt_routing,IV_nbup,IV_riv_index,                        &\n                   BS_opt_influence\n\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\nVec, intent(in)    :: ZV_C1,ZV_C2,ZV_C3,ZV_Qext,                               &\n                      ZV_QoutinitR,ZV_VinitR\nVec, intent(out)   :: ZV_QoutR,ZV_QoutbarR\nVec                :: ZV_VR,ZV_VbarR\n\nPetscInt :: IS_localsize,JS_localsize\nPetscScalar, pointer :: ZV_QoutR_p(:),ZV_QoutprevR_p(:),ZV_QoutinitR_p(:),     &\n                        ZV_QoutbarR_p(:),ZV_Qext_p(:),ZV_C1_p(:),ZV_C2_p(:),   &\n                        ZV_C3_p(:),ZV_b_p(:),                                  &\n                        ZV_babsmax_p(:),ZV_QoutRabsmin_p(:),ZV_QoutRabsmax_p(:)\n\n\n!*******************************************************************************\n!Get local sizes for vectors\n!*******************************************************************************\ncall VecGetLocalSize(ZV_QoutR,IS_localsize,ierr)\n\n\n!*******************************************************************************\n!Set mean values to zero initialize QoutprevR with QoutinitR\n!*******************************************************************************\ncall VecSet(ZV_QoutbarR,0*ZS_one,ierr)                     !Qoutbar=0\n!call VecSet(ZV_VbarR,0*ZS_one,ierr)                        !Vbar=0\n!set the means to zero at beginning of iterations over routing time step\n\ncall VecCopy(ZV_QoutinitR,ZV_QoutprevR,ierr)               !QoutprevR=QoutinitR\n!call VecCopy(ZV_VinitR,ZV_VprevR,ierr)                     !VprevR=VinitR\n!set the previous value to the initial value given as input to subroutine\n\n\n!*******************************************************************************\n!Temporal loop\n!*******************************************************************************\ncall VecGetArrayF90(ZV_C1,ZV_C1_p,ierr)\ncall VecGetArrayF90(ZV_C2,ZV_C2_p,ierr)\ncall VecGetArrayF90(ZV_C3,ZV_C3_p,ierr)\ncall VecGetArrayF90(ZV_Qext,ZV_Qext_p,ierr)\n\ndo JS_R=1,IS_R\n!-------------------------------------------------------------------------------\n!Update mean\n!-------------------------------------------------------------------------------\ncall VecAXPY(ZV_QoutbarR,ZS_one/IS_R,ZV_QoutprevR,ierr)\n!Qoutbar=Qoutbar+Qoutprev/IS_R\n\n!call VecAXPY(ZV_VbarR,ZS_one/IS_R,ZV_VprevR,ierr)\n!Vbar=Vbar+Vprev/IS_R\n\n!-------------------------------------------------------------------------------\n!Calculation of the right hand size, b\n!-------------------------------------------------------------------------------\ncall MatMult(ZM_Net,ZV_QoutprevR,ZV_b,ierr)                !b2=Net*Qoutprev\n\ncall VecGetArrayF90(ZV_b,ZV_b_p,ierr)\ncall VecGetArrayF90(ZV_QoutprevR,ZV_QoutprevR_p,ierr)\n\ndo JS_localsize=1,IS_localsize\n     ZV_b_p(JS_localsize)=ZV_b_p(JS_localsize)*ZV_C2_p(JS_localsize)           &\n                         +(ZV_C1_p(JS_localsize)+ZV_C2_p(JS_localsize))        &\n                         *ZV_Qext_p(JS_localsize)                              &\n                         +ZV_C3_p(JS_localsize)*ZV_QoutprevR_p(JS_localsize)\nend do\n\ncall VecRestoreArrayF90(ZV_QoutprevR,ZV_QoutprevR_p,ierr)\ncall VecRestoreArrayF90(ZV_b,ZV_b_p,ierr)\n\n!-------------------------------------------------------------------------------\n!Routing with PETSc using a matrix method\n!-------------------------------------------------------------------------------\nif (IS_opt_routing==1) then\n\ncall KSPSolve(ksp,ZV_b,ZV_QoutR,ierr)                      !solves A*Qout=b\ncall KSPGetIterationNumber(ksp,IS_ksp_iter,ierr)\nif (IS_ksp_iter>IS_ksp_iter_max) IS_ksp_iter_max=IS_ksp_iter\n\nend if\n\n!-------------------------------------------------------------------------------\n!Routing with Fortran using the traditional Muskingum method\n!-------------------------------------------------------------------------------\nif (IS_opt_routing==2) then\n\ncall VecGetArrayF90(ZV_QoutR,ZV_QoutR_p,ierr)\ncall VecGetArrayF90(ZV_QoutprevR,ZV_QoutprevR_p,ierr)\ncall VecGetArrayF90(ZV_b,ZV_b_p,ierr)\n\ndo JS_riv_bas=1,IS_riv_bas\n     ZV_QoutR_p(JS_riv_bas)=ZV_b_p(JS_riv_bas)                                 &\n                            +sum(ZV_C1_p(JS_riv_bas)                           &\n                                  *ZV_QoutR_p(IM_index_up(JS_riv_bas,1:        &\n                                   IV_nbup(IV_riv_index(JS_riv_bas)))))\nend do\n!Taking into account the knowledge of how many upstream locations exist.\n!Similar to exact preallocation of network matrix\n\ncall VecRestoreArrayF90(ZV_QoutR,ZV_QoutR_p,ierr)\ncall VecRestoreArrayF90(ZV_QoutprevR,ZV_QoutprevR_p,ierr)\ncall VecRestoreArrayF90(ZV_b,ZV_b_p,ierr)\nend if\n\n!-------------------------------------------------------------------------------\n!Routing with PETSc using a matrix method with transboundary matrix\n!-------------------------------------------------------------------------------\nif (IS_opt_routing==3) then\n\ncall KSPSolve(ksp,ZV_b,ZV_QoutRhat,ierr)                     !solves A*Qouthat=b\ncall KSPGetIterationNumber(ksp,IS_ksp_iter,ierr)\nif (IS_ksp_iter>IS_ksp_iter_max) IS_ksp_iter_max=IS_ksp_iter\n\ncall MatMult(ZM_TC1,ZV_QoutRhat,ZV_bhat,ierr)\ncall VecAYPX(ZV_bhat,ZS_one,ZV_b,ierr)\n\ncall KSPSolve(ksp,ZV_bhat,ZV_QoutR,ierr)                     !solves A*Qout=bhat\ncall KSPGetIterationNumber(ksp,IS_ksp_iter,ierr)\nif (IS_ksp_iter>IS_ksp_iter_max) IS_ksp_iter_max=IS_ksp_iter\n\nend if\n\n\n!-------------------------------------------------------------------------------\n!Calculation of babsmax, QoutRabsmin and QoutRabsmax\n!-------------------------------------------------------------------------------\nif (BS_opt_influence) then\n\ncall VecGetArrayF90(ZV_b,ZV_b_p,ierr)\ncall VecGetArrayF90(ZV_babsmax,ZV_babsmax_p,ierr)\ndo JS_localsize=1,IS_localsize\n     if (ZV_babsmax_p(JS_localsize)<=abs(ZV_b_p(JS_localsize))) then\n         ZV_babsmax_p(JS_localsize) =abs(ZV_b_p(JS_localsize))\n     end if\nend do\ncall VecRestoreArrayF90(ZV_b,ZV_b_p,ierr)\ncall VecRestoreArrayF90(ZV_babsmax,ZV_babsmax_p,ierr)\n\ncall VecGetArrayF90(ZV_QoutR,ZV_QoutR_p,ierr)\ncall VecGetArrayF90(ZV_QoutRabsmin,ZV_QoutRabsmin_p,ierr)\ncall VecGetArrayF90(ZV_QoutRabsmax,ZV_QoutRabsmax_p,ierr)\ndo JS_localsize=1,IS_localsize\n     if (ZV_QoutRabsmin_p(JS_localsize)>=abs(ZV_QoutR_p(JS_localsize))) then\n         ZV_QoutRabsmin_p(JS_localsize) =abs(ZV_QoutR_p(JS_localsize))\n     end if\n     if (ZV_QoutRabsmax_p(JS_localsize)<=abs(ZV_QoutR_p(JS_localsize))) then\n         ZV_QoutRabsmax_p(JS_localsize) =abs(ZV_QoutR_p(JS_localsize))\n     end if\nend do\ncall VecRestoreArrayF90(ZV_QoutR,ZV_QoutR_p,ierr)\ncall VecRestoreArrayF90(ZV_QoutRabsmin,ZV_QoutRabsmin_p,ierr)\ncall VecRestoreArrayF90(ZV_QoutRabsmax,ZV_QoutRabsmax_p,ierr)\n\nend if\n\n!-------------------------------------------------------------------------------\n!Calculation of V (this part can be commented to accelerate parameter\n!estimation in calibration mode)\n!-------------------------------------------------------------------------------\n!call VecCopy(ZV_QoutR,ZV_VoutR,ierr)                      !Vout=Qout\n!call VecScale(ZV_VoutR,ZS_dtR,ierr)                       !Vout=Vout*dt\n!!result Vout=Qout*dt\n!\n!call VecCopy(ZV_Qext,ZV_Vext,ierr)                        !Vext=Qext\n!call VecScale(ZV_Vext,ZS_dtR,ierr)                        !Vext=Vext*dt\n!!result Vext=Qext*dt\n!\n!call MatMult(ZM_Net,ZV_VoutR,ZV_VR,ierr)                  !V=Net*Vout\n!call VecAXPY(ZV_VR,ZS_one,ZV_Vext,ierr)                   !V=V+Vext\n!call VecAXPY(ZV_VR,-ZS_one,ZV_VoutR,ierr)                 !V=V-Vout\n!call VecAXPY(ZV_VR,ZS_one,ZV_VprevR,ierr)                 !V=V+Vprev\n!!result V=Vprev+(Net*Vout+Vext)-Vout\n\n\n!-------------------------------------------------------------------------------\n!Reset previous\n!-------------------------------------------------------------------------------\ncall VecCopy(ZV_QoutR,ZV_QoutprevR,ierr)              !Qoutprev=Qout\n!call VecCopy(ZV_VR,ZV_VprevR,ierr)                    !Vprev=V\n!reset previous\n\n\n!-------------------------------------------------------------------------------\n!optional write outputs\n!-------------------------------------------------------------------------------\n!call VecScatterBegin(vecscat,ZV_QoutR,ZV_SeqZero,                              &\n!                     INSERT_VALUES,SCATTER_FORWARD,ierr)\n!call VecScatterEnd(vecscat,ZV_QoutR,ZV_SeqZero,                                &\n!                        INSERT_VALUES,SCATTER_FORWARD,ierr)\n!call VecGetArrayF90(ZV_SeqZero,ZV_pointer,ierr)\n!!if (rank==0) write (99,'(10e10.3)') ZV_pointer\n!if (rank==0) IS_nc_status=NF90_PUT_VAR(IS_nc_id_fil_Qout,IS_nc_id_var_Qout,    &\n!                                       ZV_pointer,                             &\n!                     [IV_nc_start(1),(IV_nc_start(2)-1)*IS_R+JS_R],IV_nc_count2)\n!call VecRestoreArrayF90(ZV_SeqZero,ZV_pointer,ierr)\n\n\n!-------------------------------------------------------------------------------\n!End temporal loop\n!-------------------------------------------------------------------------------\nend do\n\ncall VecRestoreArrayF90(ZV_C1,ZV_C1_p,ierr)\ncall VecRestoreArrayF90(ZV_C2,ZV_C2_p,ierr)\ncall VecRestoreArrayF90(ZV_C3,ZV_C3_p,ierr)\ncall VecRestoreArrayF90(ZV_Qext,ZV_Qext_p,ierr)\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\nend subroutine rapid_routing\n"
  },
  {
    "path": "src/Rapid_routing/rapid_routing_param.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_routing_param\n!*******************************************************************************\nsubroutine rapid_routing_param(ZV_k,ZV_x,                                      &\n                               ZV_C1,ZV_C2,ZV_C3,ZM_A)\n\n!Purpose:\n!Calculates the Muskingum method (McCarthy 1938) parameters C1, C2 and C3.\n!Also calculates the matrix A used for linear system solver.\n!Author:\n!Cedric H. David, 2010-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only :                                                          &\n                   ZM_Net,ZM_T,ZM_TC1,                                         &\n                   ZV_Cdenom,ZS_dtR,                                           &\n                   ierr,ZS_one,ZV_one,IS_opt_routing\n\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\nVec, intent(in)    :: ZV_k,ZV_x\nVec, intent(out)   :: ZV_C1,ZV_C2,ZV_C3,ZM_A\n\n\n!*******************************************************************************\n!Calculation of the Muskingum method constants (C1,C2,C3) and of the matrix A\n!used in the linear system A*Qout=b\n!*******************************************************************************\ncall VecCopy(ZV_x,ZV_Cdenom,ierr)\ncall VecScale(ZV_Cdenom,-ZS_one,ierr)\ncall VecShift(ZV_Cdenom,ZS_one,ierr)\ncall VecPointwiseMult(ZV_Cdenom,ZV_Cdenom,ZV_k,ierr)\ncall VecShift(ZV_Cdenom,ZS_dtR/2,ierr)\n!Cdenom=k*(1-x)+dtR/2\n\ncall VecPointwiseMult(ZV_C1,ZV_k,ZV_x,ierr)\ncall VecScale(ZV_C1,-ZS_one,ierr)\ncall VecShift(ZV_C1,ZS_dtR/2,ierr)\ncall VecPointwiseDivide(ZV_C1,ZV_C1,ZV_Cdenom,ierr)\n!C1=(-k*x+dtR/2)/Cdenom\n\ncall VecPointwiseMult(ZV_C2,ZV_k,ZV_x,ierr)\ncall VecShift(ZV_C2,ZS_dtR/2,ierr)\ncall VecPointwiseDivide(ZV_C2,ZV_C2,ZV_Cdenom,ierr)\n!C2=(k*x+dtR/2)/Cdenom\n\ncall VecCopy(ZV_x,ZV_C3,ierr)\ncall VecScale(ZV_C3,-ZS_one,ierr)\ncall VecShift(ZV_C3,ZS_one,ierr)\ncall VecPointwiseMult(ZV_C3,ZV_C3,ZV_k,ierr)\ncall VecShift(ZV_C3,-ZS_dtR/2,ierr)\ncall VecPointwiseDivide(ZV_C3,ZV_C3,ZV_Cdenom,ierr)\n!C3=(k*(1-x)-dtR/2)/Cdenom\n!C1, C2 and C3 completed\n\n\ncall MatCopy(ZM_Net,ZM_A,DIFFERENT_NONZERO_PATTERN,ierr)   !A=Net\ncall MatDiagonalScale(ZM_A,ZV_C1,ZV_one,ierr)              !A=diag(C1)*A\ncall MatScale(ZM_A,-ZS_one,ierr)                           !A=-A\ncall MatShift(ZM_A,ZS_one,ierr)                            !A=A+1*I\n!Result:A=I-diag(C1)*Net\n\nif (IS_opt_routing==3) then\ncall MatCopy(ZM_T,ZM_TC1,DIFFERENT_NONZERO_PATTERN,ierr)        !TC1=T\ncall MatDiagonalScale(ZM_TC1,ZV_C1,ZV_one,ierr)            !TC1=diag(C1)*TC1\n!Result:TC1=T*diag(C1)\nend if\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_routing_param\n"
  },
  {
    "path": "src/Rapid_routing/rapid_script.sh",
    "content": "FILE=$(date +\"%Y-%m-%d_%H-%M-%S_rapid_stdout.txt\")\n/usr/bin/time mpiexec                  \\\n              -n 1                     \\\n              ./rapid                  \\\n              -ksp_type richardson     \\\n              1>$FILE 2>>$FILE\n\n#FILE is a name created based on the time when the model started running\n#FILE contains stdout from running the model (through 1), but also stderr \n#(through 2).  The output of the time function is also included because \n#it is located in located in 2.\n"
  },
  {
    "path": "src/Rapid_routing/rapid_set_Qext0.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_set_Qext0\n!*******************************************************************************\nsubroutine rapid_set_Qext0\n\n!Purpose:\n!This subroutine is only useful if a dam model is used and its goal is to\n!properly initialize the flow of water into the dams.\n!The inflow of water ZV_Qin_dam_prev from the river network and from outside of\n!the river network into the dams is computed based on ZV_QoutbarR and ZV_Qext\n!in the subroutine rapid_get_Qdam.F90.\n!Therefore, one has to inject the initial value of ZV_Qin_dam_prev (ZV_Qin_dam0)\n!into either ZV_QoutbarR or ZV_Qext otherwise the initial value will be\n!overwritten in rapid_get_Qdam.F90. The latter is used here (through ZV_Qdam)\n!since the modifications made on the network matrix make it difficult to use\n!ZV_Qin_dam_prev without creating a new variable.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Declaration of variables\n!*******************************************************************************\nuse rapid_var, only:                                                           &\n                   rank,ierr,IS_one,ZS_one,                                    &\n                   ZV_Qdam,ZV_Qext,                                            &\n                   IS_dam_tot,JS_dam_tot,IV_dam_pos\n\nuse rapid_var, only:                                                           &\n                   ZV_Qin_dam_prev,ZV_Qin_dam0,                                &\n                   ZV_Qout_dam_prev,ZV_Qout_dam0\n\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n#include \"finclude/petsclog.h\"\n!PETSc log\n\n\n!*******************************************************************************\n!Set Qdam to zero, because this is called at the beginning of every phiroutine\n!*******************************************************************************\ncall VecSet(ZV_Qdam,0*ZS_one,ierr)                            !Qdam=0\n!call VecView(ZV_Qdam,PETSC_VIEWER_STDOUT_WORLD,ierr)\n\n\n!*******************************************************************************\n!Set values of Qin_dam0 into Qdam to allow proper initialization\n!*******************************************************************************\nif (rank==0) then\n     do JS_dam_tot=1,IS_dam_tot\n\nif (IV_dam_pos(JS_dam_tot)/=0) then\n     call VecSetValues(ZV_Qdam,IS_one,IV_dam_pos(JS_dam_tot)-1,                &\n                       ZV_Qin_dam0(JS_dam_tot),INSERT_VALUES,ierr)\n     !print *, IV_dam_pos(JS_dam_tot)-1, ZV_Qin_dam0(JS_dam_tot)\nend if\n\n     end do\nend if\n\ncall VecAssemblyBegin(ZV_Qdam,ierr)\ncall VecAssemblyEnd(ZV_Qdam,ierr)\n!call VecView(ZV_Qdam,PETSC_VIEWER_STDOUT_WORLD,ierr)\n!the values of Qindam0 are set here where the dams are, not downstream of them\n\n\n!*******************************************************************************\n!Copy Qdam into Qext and reset Qdam to zero\n!*******************************************************************************\ncall VecCopy(ZV_Qdam,ZV_Qext,ierr)                            !Qext=Qdam\ncall VecSet(ZV_Qdam,0*ZS_one,ierr)                            !Qdam=0\n!call VecView(ZV_Qext,PETSC_VIEWER_STDOUT_WORLD,ierr)\n\n\n!*******************************************************************************\n!Initialize Qout_dam_prev again or its values differ with each phiroutine call\n!*******************************************************************************\nif (rank==0) then\n     ZV_Qout_dam_prev=ZV_Qout_dam0\nend if\n\n!*******************************************************************************\n!End\n!*******************************************************************************\nend subroutine rapid_set_Qext0\n"
  },
  {
    "path": "src/Rapid_routing/rapid_var.F90",
    "content": "!*******************************************************************************\r\n!Module - rapid_var\r\n!*******************************************************************************\r\nmodule rapid_var\r\n\r\n!Purpose:\r\n!Module where all the variables are defined.\r\n!Author:\r\n!Cedric H. David, 2008-2015.\r\n\r\n\r\nimplicit none\r\n\r\n\r\n!*******************************************************************************\r\n!Includes\r\n!*******************************************************************************\r\n#include \"finclude/petscsys.h\"\r\n!base PETSc routines\r\n#include \"finclude/petscvec.h\"\r\n#include \"finclude/petscvec.h90\"\r\n!vectors, and Fortran90-specific vectors\r\n#include \"finclude/petscmat.h\"\r\n!matrices\r\n#include \"finclude/petscksp.h\"\r\n!Krylov subspace methods\r\n#include \"finclude/petscpc.h\"\r\n!preconditioners\r\n#include \"finclude/petscviewer.h\"\r\n!viewers (allows writing results in file for example)\r\n!#include \"finclude/petsclog.h\"\r\n!Profiling log\r\n\r\n#ifndef NO_TAO\r\n#include \"finclude/taosolver.h\"\r\n!TAO solver\r\n#endif\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - runtime options\r\n!*******************************************************************************\r\nlogical :: BS_opt_Qinit\r\n!.false. --> no read initial flow    .true. --> read initial flow\r\nlogical :: BS_opt_Qfinal\r\n!.false. --> no write final flow     .true. --> write final flow\r\nlogical :: BS_opt_hum\r\n!.false. --> no human-induced flows  .true. --> human-induced flows\r\nlogical :: BS_opt_for\r\n!.false. --> no forcing              .true. --> forcing\r\nlogical :: BS_opt_dam\r\n!.false. --> no dam model used       .true. --> dam model used\r\nlogical :: BS_opt_influence\r\n!.false. --> no output influence     .true. --> output influence\r\nPetscInt :: IS_opt_routing\r\n!1       --> matrix-based Muskingum  2      --> traditional Muskingum\r\n!3       --> Transbnd. matrix-based\r\nPetscInt :: IS_opt_run\r\n!1       --> regular run             2      --> parameter optimization\r\nPetscInt :: IS_opt_phi\r\n!1       --> phi1                    2      --> phi2\r\n\r\n\r\n!! LPR: add the path for coupling file in NAMELIST\r\n!character(len=120) :: rapid_coupling_file\r\n!unit 88 - file that contains coupling information for WRF-Hydro\r\n!*******************************************************************************\r\n!Declaration of variables - input and output files\r\n!*******************************************************************************\r\ncharacter(len=120) :: rapid_connect_file\r\n!unit 10 - file with connectivity information using RAPID connectivity format\r\ncharacter(len=120) :: riv_bas_id_file\r\n!unit 11 - file with all the IDs of the reaches in _riv considered\r\ncharacter(len=120) :: obs_tot_id_file\r\n!unit 12 - file with all the IDs of the all reaches with gage measurements\r\ncharacter(len=120) :: obs_use_id_file\r\n!unit 13 - file with all the IDs of the reaches used\r\ncharacter(len=120) :: hum_tot_id_file\r\n!unit 14 - file with all the IDs of the reaches with human-induced flow added\r\ncharacter(len=120) :: hum_use_id_file\r\n!unit 15 - file with all the IDs of the reaches used\r\ncharacter(len=120) :: for_tot_id_file\r\n!unit 16 - file with all the IDs where flows can be used as forcing to their\r\n!corresponding downstream reach\r\ncharacter(len=120) :: for_use_id_file\r\n!unit 17 - file with all the IDs of the reaches used\r\ncharacter(len=120) :: dam_tot_id_file\r\n!unit 18 - file with all the IDs of the reaches where the dam model runs and\r\n!flows to their corresponding downstream reach\r\ncharacter(len=120) :: dam_use_id_file\r\n!unit 19 - file with all the IDs of the reaches used\r\n\r\ncharacter(len=120) :: k_file\r\n!unit 20 - file with values for k (possibly from previous param. estim.)\r\ncharacter(len=120) :: x_file\r\n!unit 21 - file with values for x (possibly from previous param. estim.)\r\ncharacter(len=120) :: kfac_file\r\n!unit 22 - file with kfac for all reaches of the domain\r\ncharacter(len=120) :: xfac_file\r\n!unit 23 - file with xfac for all reaches of the domain\r\n\r\ncharacter(len=120) :: Qinit_file\r\n!unit 30 - file where initial flowrates can be stored to run the model with them\r\ncharacter(len=120) :: Qfinal_file\r\n!unit 31 - file where final flowrates can be stored at the end of model run\r\ncharacter(len=120) :: Vlat_file\r\n\r\ncharacter(len=120) :: Qobs_file\r\n!unit 33 - file where the flowrates observations are given\r\ncharacter(len=120) :: Qfor_file\r\n!unit 34 - file where forcing flowrates are stored.  Forcing is taken as the\r\n!flow coming from upstream reach.\r\ncharacter(len=120) :: Qobsbarrec_file\r\n!unit 35 - file where the reciprocal (1/xi) of the average obs are stored.\r\ncharacter(len=120) :: Qhum_file\r\n!unit 36 - file where human-induced flowrates are stored.  These flows are added\r\n!upstream.\r\n\r\ncharacter(len=120) :: V_file\r\n!unit 41 - file where model-calculated volumes are stored\r\ncharacter(len=120) :: babsmax_file\r\n!unit 42 - file where the maximum of the absolute values of the right-hand-side\r\n!are stored\r\ncharacter(len=120) :: QoutRabsmin_file\r\n!unit 43 - file where the minimum of the absolute values of the instantaneous\r\n!flows are stored\r\ncharacter(len=120) :: QoutRabsmax_file\r\n!unit 44 - file where the maximum of the absolute values of the instantaneous\r\n!flows are stored\r\ncharacter(len=120) :: Qout_file\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - temporal parameters\r\n!*******************************************************************************\r\nPetscScalar :: ZS_TauM\r\n!Duration of main procedure, in seconds\r\nPetscScalar :: ZS_dtM\r\n!Time step of main procedure, in seconds\r\nPetscInt :: IS_M\r\n!Number of time steps within the main precedure\r\nPetscInt :: JS_M\r\n!Index of main procedure\r\n\r\nPetscScalar :: ZS_TauO\r\n!Duration of optimization procedure, in seconds\r\nPetscScalar :: ZS_dtO\r\n!Time step of optimization procedure, in seconds\r\nPetscInt :: IS_O\r\n!Number of time steps within the optimization precedure\r\nPetscInt :: JS_O\r\n!Index of optimization procedure\r\n\r\nPetscScalar :: ZS_TauR\r\n!Duration of river routing procedure, in seconds\r\nPetscScalar :: ZS_dtR\r\n!Time step of river routing procedure, in seconds\r\nPetscInt :: IS_R\r\n!Number of time steps within the river routing procedure\r\nPetscInt :: JS_R\r\n!Index of river routing procedure\r\n\r\nPetscScalar :: ZS_dtF\r\n!Time step of forcing data, in seconds\r\nPetscScalar :: ZS_dtH\r\n!Time step of human-induced data, in seconds\r\n\r\nPetscInt :: IS_RpO, JS_RpO\r\n!Number routing procedures needed per optimization time step, and index\r\nPetscInt :: IS_RpM, JS_RpM\r\n!Number routing procedures needed per main time step, and index\r\nPetscInt :: IS_RpF\r\n!Number routing procedures needed per forcing time step\r\nPetscInt :: IS_RpH\r\n!Number routing procedures needed per human-induced time step\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - River flow variables\r\n!*******************************************************************************\r\nPetscInt :: IS_riv_tot,JS_riv_tot,JS_riv_tot2\r\n!total number of river reaches, corresponds to the size of rapid_connect_file\r\nPetscInt :: IS_riv_bas,JS_riv_bas,JS_riv_bas2\r\n!size of the matrix and the vectors in this _riv, corresponds to the number of\r\n!reaches in the _riv\r\nPetscInt, dimension(:), allocatable :: IV_riv_tot_id\r\n!unique IDs of reaches in rapid_connect_file\r\nPetscInt, dimension(:), allocatable :: IV_down\r\n!vector of the downstream river reach of each river reach\r\nPetscInt, dimension(:), allocatable :: IV_nbup\r\n!vector of the number of direct upstream river reach of each river reach\r\nPetscInt :: IS_max_up\r\n!maximum number of upstream river reaches for each river reach\r\nPetscInt, dimension(:,:), allocatable :: IM_up\r\n!matrix with the ID of the upstream river reaches of each river reach\r\nPetscInt :: JS_up\r\n!JS_up for the corresponding upstream reaches\r\nPetscInt :: IS_row,IS_col\r\n!index of rows and columns used to fill up the network matrix\r\nPetscInt,dimension (:,:), allocatable :: IM_index_up\r\n!matrix with the index of the upstream river reaches of each river reach\r\n!index goes from 1 to IS_riv_bas\r\nPetscInt, dimension(:),allocatable :: IV_riv_bas_id\r\n!unique IDs in riv_bas_id_file, of length IS_riv_bas\r\nPetscInt, dimension(:), allocatable :: IV_riv_index\r\n!indexes (Fortran, 1-based) of the reaches in the _riv within the whole network\r\n!size IS_riv_bas\r\nPetscInt,dimension(:), allocatable :: IV_riv_loc1\r\n!vector giving the zero-base index corresponding to the river reaches within\r\n!the _riv studied only, to be used in VecSetValues. size IS_riv_bas\r\nMat :: ZM_hsh_tot\r\n!flat matrix with size IS_riv_id_max*ncore that serves a hashtable-like purpose\r\n!in which the index over the domain (JS_riv_tot) is stored at the location of\r\n!each reach ID. Each row contains the exact same data.\r\nMat :: ZM_hsh_bas\r\n!flat matrix with size IS_riv_id_max*ncore that serves a hashtable-like purpose\r\n!in which the index over the basin (JS_riv_bas) is stored at the location of\r\n!each reach ID. Each row contains the exact same data.\r\nPetscInt :: IS_riv_id_max=1000000000\r\n!Maximum value allowed for the unique integer IDs corresponding to each reach\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - Observation flow variables\r\n!*******************************************************************************\r\nPetscInt :: IS_obs_tot, JS_obs_tot\r\n!total number of reaches that have observations (gaged reaches), corresponds to\r\n!the number of lines in obs_tot_id_file\r\nPetscInt :: IS_obs_use, JS_obs_use\r\n!Number of gages available in obs_use_id_file\r\nPetscInt :: IS_obs_bas, JS_obs_bas\r\n!Number of gages within _riv studied.  Will be calculated based on\r\n!obs_tot_id_file, obs_use_id_file and riv_bas_id_file\r\nPetscInt, dimension(:), allocatable :: IV_obs_tot_id\r\n!vector where are stored the river ID of each gage available\r\nPetscInt, dimension(:), allocatable :: IV_obs_use_id\r\n!vector where are stored the river ID of each gage used in current run\r\nPetscInt, allocatable, dimension(:) :: IV_obs_index\r\n!vector where the Fortran 1-based indexes of the gages within the Qobs_file.\r\n!Will be allocated size IS_obs_bas\r\nPetscInt, allocatable, dimension(:) :: IV_obs_loc1\r\n!vector where the C (0-based) vector indexes of where gages are. This is\r\n!within the _riv only, not all domain. Will be used in VecSet.  Will be\r\n!allocated size IS_obs_bas\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - Human-induced flow variables\r\n!*******************************************************************************\r\nPetscInt :: IS_hum_tot, JS_hum_tot\r\n!total number of reaches where human-induced flow data are available.\r\nPetscInt :: IS_hum_use, JS_hum_use\r\n!total number of reaches where human-induced will be used if in sub_riv\r\nPetscInt :: IS_hum_bas, JS_hum_bas\r\n!number of reaches with human-induced flow, within _riv. Calculated on the fly\r\n!from hum_tot_if_file, hum_use_id_file and riv_bas_id_file\r\nPetscInt, dimension(:), allocatable :: IV_hum_tot_id\r\n!IDs of the reaches where human-induced flow data are available\r\nPetscInt, dimension(:), allocatable :: IV_hum_use_id\r\n!IDs of the reaches where human-induced flow data will be used if in sub_riv\r\nPetscInt, dimension(:), allocatable :: IV_hum_bas_id\r\n!IDs of the reaches where human-indeced flow data to be used is in sub_riv\r\nPetscInt, allocatable, dimension(:) :: IV_hum_index\r\n!vector where the Fortran 1-based indexes of the human-induced flow data are\r\n!stored. This is of size IS_hum_bas and its elements belong to [1,IS_hum_tot].\r\nPetscInt, allocatable, dimension(:) :: IV_hum_loc1\r\n!vector where the C (0-based) vector indexes of where the above human-induced\r\n!flow data are going to be applied. This is of size IS_hum_bas and its elements\r\n!belong to [0,IS_riv_bas-1]. Applied on the river ID itself.\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - Forcing flow variables\r\n!*******************************************************************************\r\nPetscInt :: IS_for_tot, JS_for_tot\r\n!total number of reaches where forcing flow data are available.\r\nPetscInt :: IS_for_use, JS_for_use\r\n!total number of reaches where forcing will be used if in sub_riv\r\nPetscInt :: IS_for_bas, JS_for_bas\r\n!number of reaches forced by observations, within _riv. Calculated on the fly\r\n!from for_tot_id_file, for_use_id_file and riv_bas_id_file\r\nPetscInt, dimension(:), allocatable :: IV_for_tot_id\r\n!IDs of the reaches where forcing flow data are available\r\nPetscInt, dimension(:), allocatable :: IV_for_use_id\r\n!IDs of the reaches where forcing flow data will be used if in sub_riv\r\nPetscInt, dimension(:), allocatable :: IV_for_bas_id\r\n!IDs of the reaches where forcing flow data to be used is in sub_riv\r\nPetscInt, allocatable, dimension(:) :: IV_for_index\r\n!vector where the Fortran 1-based indexes of the forcing flow data are\r\n!available. This is of size IS_for_bas and its elements belong to [1,IS_for_tot]\r\nPetscInt, allocatable, dimension(:) :: IV_for_loc2\r\n!vector where the C (0-based) vector indexes of where the above forcing\r\n!flow data are going to be applied. This is of size IS_for_bas and its elements\r\n!belong to [0,IS_riv_bas-1]. Applied on the river ID downstream.\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - dam model flow variables\r\n!*******************************************************************************\r\nPetscInt :: IS_dam_tot, JS_dam_tot\r\n!total number of reaches where dam model flow data are available.\r\nPetscInt :: IS_dam_use, JS_dam_use\r\n!total number of reaches where dam model will be used if in sub_riv\r\nPetscInt :: IS_dam_bas, JS_dam_bas\r\n!number of reaches forced by observations, within _riv. Calculated on the fly\r\n!from dam_tot_id_file, dam_use_id_file and riv_bas_id_file.\r\nPetscInt, dimension(:), allocatable :: IV_dam_tot_id\r\n!IDs of the reaches where dam model flow data are available\r\nPetscInt, dimension(:), allocatable :: IV_dam_use_id\r\n!IDs of the reaches where dam model flow data will be used if in sub_riv\r\nPetscInt, dimension(:), allocatable :: IV_dam_bas_id\r\n!IDs of the reaches where dam model flow data to be used is in sub_riv\r\nPetscInt, allocatable, dimension(:) :: IV_dam_index\r\n!vector where the Fortran 1-based indexes of the dam model flow data are\r\n!available. This is of size IS_dam_bas and its elements belong to [1,IS_dam_tot]\r\nPetscInt, allocatable, dimension(:) :: IV_dam_loc2\r\n!vector where the C (0-based) vector indexes of where the above dam model\r\n!flow data are going to be applied. This is of size IS_dam_bas and its elements\r\n!belong to [0,IS_riv_bas-1]. Applied on the river ID downstream.\r\nPetscInt, allocatable, dimension(:) :: IV_dam_pos\r\n!vector where the Fortran 1-based vector indexes of where flows will be given to\r\n!the above dam model. This is of size IS_dam_tot and its elements belong to\r\n![1,IS_riv_bas] except when a dam ID is outside of basin studied where it is 0.\r\n!Applied on the river ID itself.\r\n\r\nPetscScalar, allocatable, dimension(:) :: ZV_Qin_dam,ZV_Qin_dam_prev\r\nPetscScalar, allocatable, dimension(:) :: ZV_Qout_dam,ZV_Qout_dam_prev\r\nPetscScalar, allocatable, dimension(:) :: ZV_Qin_dam0,ZV_Qout_dam0\r\n!Fortran vectors where the inflows and outflows for the dam module are saved.\r\n!These will be allocated to size IS_dam_tot\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - Network matrix variables and routing variables\r\n!*******************************************************************************\r\nMat :: ZM_Net\r\n!Network matrix\r\nMat :: ZM_A\r\n!Matrix used to solve linear system\r\nMat :: ZM_T\r\n!Transboundary matrix\r\nMat :: ZM_TC1\r\n!Matrix used as a trick to solve linear system faster\r\nLogical :: BS_logical\r\n!Boolean used during network matrix creation to give warnings if connectivity pb\r\n\r\nVec :: ZV_k,ZV_x\r\n!Muskingum expression constants vectors, k in seconds, x has no dimension\r\nVec :: ZV_p, ZV_pnorm,ZV_pfac\r\n!vector of the problem parameters, p=(k,x).  normalized version and\r\n!corresponding factors p=pnorm*pfac\r\nVec :: ZV_C1,ZV_C2,ZV_C3,ZV_Cdenom\r\n!Muskingum method constants (last is the common denominator, for calculations)\r\nVec :: ZV_b,ZV_babsmax,ZV_bhat\r\n!Used for linear system A*Qout=b\r\n\r\n!Input variables (contribution)\r\nVec :: ZV_Qext,ZV_Qfor,ZV_Qlat,ZV_Qhum,ZV_Qdam\r\n!flowrates Qext is the sum of forced and lateral\r\nVec :: ZV_Vext,ZV_Vfor,ZV_Vlat\r\n!volumes (same as above)\r\n\r\n!Main only variables\r\nVec :: ZV_QoutM,ZV_QoutinitM,ZV_QoutprevM,ZV_QoutbarM\r\nVec :: ZV_VM,ZV_VinitM,ZV_VprevM,ZV_VbarM\r\n\r\n!Optimization only variables\r\nVec :: ZV_QoutO,ZV_QoutinitO,ZV_QoutprevO,ZV_QoutbarO\r\nVec :: ZV_VO,ZV_VinitO,ZV_VprevO,ZV_VbarO\r\n\r\n!Routing only variables\r\nVec :: ZV_QoutR,ZV_QoutinitR,ZV_QoutprevR,ZV_QoutbarR,ZV_QoutRhat,ZV_QinbarR\r\nVec :: ZV_QoutRabsmin,ZV_QoutRabsmax\r\nVec :: ZV_VR,ZV_VinitR,ZV_VprevR,ZV_VbarR\r\nVec :: ZV_VoutR\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - Observation matrix and optimization variables\r\n!*******************************************************************************\r\nMat :: ZM_Obs\r\n!Observation matrix\r\nVec :: ZV_Qobs\r\n!Observation vector\r\nPetscScalar :: ZS_norm\r\n!norm of matrix ZM_Obs, used to calculate the number of gaging stations used\r\n\r\nPetscScalar :: ZS_phi,ZS_phitemp\r\n!cost function\r\nPetscInt :: IS_Iter\r\n!number of iterations needed for optimization procedure to end\r\nVec :: ZV_temp1,ZV_temp2\r\n!temporary vectors, used for calculations\r\nPetscScalar :: ZS_phifac\r\nPetscInt :: IS_strt_opt\r\n!first time step at which Vlat data is read during optimization\r\n\r\nVec :: ZV_kfac\r\n!Vector of size IS_riv_bas a multiplication factor for k for all river reaches\r\n!in _riv\r\nVec :: ZV_Qobsbarrec\r\n!Vector with the reciprocal (1/xi) of the average observations\r\n\r\nPetscScalar :: ZS_knorm, ZS_xnorm\r\n!constants (k,x) in Muskingum expression, normalized\r\nPetscScalar :: ZS_knorm_init, ZS_xnorm_init\r\n!constants (k,x) in Muskingum expression, normalized, initial values for opt.\r\nPetscScalar, parameter :: ZS_kfac=3600,ZS_xfac=0.1\r\n!corresponding factors, k in seconds, x has no dimension\r\nPetscScalar :: ZS_k,ZS_x\r\n!constants (k,x) in Muskingum expression.  k in seconds, x has no dimension\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - routing parameters and initial values\r\n!*******************************************************************************\r\nPetscScalar :: ZS_V0=10000,ZS_Qout0=0\r\n!values to be used in the intitial state of V and Qout for river routing\r\n!initial volume for each reach (m^3), initial outflow for each reach (m^3/s)\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - PETSc specific objects and variables\r\n!*******************************************************************************\r\nPetscErrorCode :: ierr\r\n!needed for error check of PETSc functions\r\nKSP :: ksp\r\n!object used for linear system solver\r\nPC :: pc\r\n!preconditioner object\r\nPetscMPIInt :: rank\r\n!integer where the number of each processor is stored, 0 will be main processor\r\nPetscMPIInt :: ncore\r\n!integer where the number of cores used is stored\r\nVecScatter :: vecscat\r\n!Allows for scattering and gathering vectors from in parallel environement\r\nPetscLogEvent :: stage\r\n!Stage for investigating performance\r\n\r\nPetscInt :: IS_ksp_iter, IS_ksp_iter_max\r\n!integer where the number of iterations in KSP is solved\r\nPetscInt :: IS_one=1\r\n!integer of value 1.  to be used in MatSetValues and VecSet. Directly using\r\n!the value 1 in the functions crashes PETSc\r\nPetscScalar :: ZS_one=1\r\n!Scalars of values 1 and 0, same remark as above\r\nPetscScalar :: ZS_val\r\n!Temporary scalar used to store the results of MatGetValues()\r\nVec :: ZV_one\r\n!vector with only ones, useful for creation of matrices here\r\nVec :: ZV_SeqZero\r\n!Sequential vector of size IS_riv_bas, allows for gathering data on zeroth\r\n!precessor before writing in file\r\n\r\nPetscScalar,dimension(:), allocatable :: ZV_read_riv_tot\r\n!temp vector that stores information from a 'read', before setting the value\r\n!in the object, this vector has the size of the total number of reaches\r\nPetscScalar,dimension(:), allocatable :: ZV_read_obs_tot\r\n!same as previous, with size IS_obs_tot\r\nPetscScalar,dimension(:), allocatable :: ZV_read_hum_tot\r\n!same as previous, with size IS_hum_tot\r\nPetscScalar,dimension(:), allocatable :: ZV_read_for_tot\r\n!same as previous, with size IS_for_tot\r\nPetscScalar,dimension(:), allocatable :: ZV_read_dam_tot\r\n!same as previous, with size IS_dam_tot\r\nPetscScalar :: ZS_time1, ZS_time2, ZS_time3\r\n!to estimate computing time\r\n\r\nPetscScalar, pointer :: ZV_pointer(:)\r\n!used to point to a PETSc vector and to output formatted as needed in a file\r\ncharacter(len=10) :: temp_char,temp_char2\r\n!usefull to print variables on output.  write a variable in this character and\r\n!then use PetscPrintf\r\n\r\nPetscInt, dimension(:), allocatable :: IV_nz, IV_dnz, IV_onz\r\n!number of nonzero elements per row for network matrix.  nz for sequential, dnz\r\n!and onz for distributed matrix (diagonal and off-diagonal elements)\r\nPetscInt :: IS_ownfirst, IS_ownlast\r\n!Ownership of each processor\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - TAO specific objects and variables\r\n!*******************************************************************************\r\n#ifndef NO_TAO\r\nTaoSolver :: tao\r\n!TAO solver object\r\nTaoSolverTerminationReason :: reason\r\n!TAO terminate reason object\r\nVec :: ZV_1stIndex, ZV_2ndIndex\r\n!ZV_1stIndex=[1;0], ZV_2ndIndex=[0,1].  Used with VecDot to extract first and\r\n!second indexes of the vector of parameter\r\n#endif\r\n\r\n\r\n!*******************************************************************************\r\n!Declaration of variables - netCDF variables\r\n!*******************************************************************************\r\nPetscInt :: IS_nc_status\r\nPetscInt :: IS_nc_id_fil_Vlat,IS_nc_id_fil_Qout\r\nPetscInt :: IS_nc_id_var_Vlat,IS_nc_id_var_Qout,IS_nc_id_var_comid\r\nPetscInt :: IS_nc_id_dim_comid,IS_nc_id_dim_time\r\nPetscInt, parameter :: IS_nc_ndim=2\r\nPetscInt, dimension(IS_nc_ndim) :: IV_nc_id_dim, IV_nc_start, IV_nc_count,     &\r\n                                   IV_nc_count2\r\n\r\n\r\n!*******************************************************************************\r\n!Namelist\r\n!*******************************************************************************\r\nnamelist /NL_namelist/                                                         &\r\n                       BS_opt_Qinit,BS_opt_Qfinal,                             &\r\n                       BS_opt_hum,BS_opt_for,BS_opt_dam,BS_opt_influence,      &\r\n                       IS_opt_routing,IS_opt_run,IS_opt_phi,                   &\r\n                       IS_riv_tot,rapid_connect_file,Vlat_file,IS_max_up,      &\r\n                       iS_riv_bas,riv_bas_id_file,                             &\r\n                       Qinit_file,Qfinal_file,                                 &\r\n                       Qhum_file,                                              &\r\n                       IS_hum_tot,hum_tot_id_file,                             &\r\n                       IS_hum_use,hum_use_id_file,                             &\r\n                       IS_for_tot,for_tot_id_file,                             &\r\n                       Qfor_file,                                              &\r\n                       IS_for_use,for_use_id_file,                             &\r\n                       IS_dam_tot,dam_tot_id_file,                             &\r\n                       IS_dam_use,dam_use_id_file,                             &\r\n                       babsmax_file,QoutRabsmin_file,QoutRabsmax_file,         &\r\n                       k_file,x_file,Qout_file,                                &\r\n                       kfac_file,xfac_file,ZS_knorm_init,ZS_xnorm_init,        &\r\n                       IS_obs_tot,obs_tot_id_file,IS_obs_use,obs_use_id_file,  &\r\n                       Qobs_file,Qobsbarrec_file,                              &\r\n                       ZS_TauM,ZS_dtM,ZS_TauO,ZS_dtO,ZS_TauR,ZS_dtR,           &\r\n                       ZS_dtF,ZS_dtH,                                          &\r\n                       ZS_phifac,IS_strt_opt\r\n\r\ncharacter(len=120) :: namelist_file\r\n!unit 88 - Namelist\r\n\r\n\r\nend module rapid_var\r\n"
  },
  {
    "path": "src/Rapid_routing/rapid_write_Qout_file.F90",
    "content": "!*******************************************************************************\n!Subroutine - rapid_write_Qout_file\n!*******************************************************************************\nsubroutine rapid_write_Qout_file\n\n!Purpose:\n!Write into Qout_file from Fortran/netCDF.\n!Author:\n!Cedric H. David, 2013-2015.\n\n\n!*******************************************************************************\n!Global variables\n!*******************************************************************************\nuse netcdf\nuse rapid_var, only :                                                          &\n                   rank,ierr,vecscat,ZV_SeqZero,ZV_pointer,                    &\n                   IS_nc_status,IS_nc_id_fil_Qout,IS_nc_id_var_Qout,           &\n                   IV_nc_start,IV_nc_count2,                                   &\n                   ZV_QoutbarR\n\nimplicit none\n\n\n!*******************************************************************************\n!Includes\n!*******************************************************************************\n#include \"finclude/petscsys.h\"\n!base PETSc routines\n#include \"finclude/petscvec.h\"\n#include \"finclude/petscvec.h90\"\n!vectors, and vectors in Fortran90\n#include \"finclude/petscmat.h\"\n!matrices\n#include \"finclude/petscksp.h\"\n!Krylov subspace methods\n#include \"finclude/petscpc.h\"\n!preconditioners\n#include \"finclude/petscviewer.h\"\n!viewers (allows writing results in file for example)\n#include \"finclude/petsclog.h\"\n!PETSc log\n\n\n!*******************************************************************************\n!Intent (in/out), and local variables\n!*******************************************************************************\n\n\n!*******************************************************************************\n!Gather PETSc vector on processor zero\n!*******************************************************************************\ncall VecScatterBegin(vecscat,ZV_QoutbarR,ZV_SeqZero,                           &\n                     INSERT_VALUES,SCATTER_FORWARD,ierr)\ncall VecScatterEnd(vecscat,ZV_QoutbarR,ZV_SeqZero,                             &\n                        INSERT_VALUES,SCATTER_FORWARD,ierr)\n\n\n!*******************************************************************************\n!Get array from PETSc vector\n!*******************************************************************************\nif (rank==0) call VecGetArrayF90(ZV_SeqZero,ZV_pointer,ierr)\n\n\n!*******************************************************************************\n!Write data\n!*******************************************************************************\nif (rank==0) IS_nc_status=NF90_PUT_VAR(IS_nc_id_fil_Qout,IS_nc_id_var_Qout,    &\n                                       ZV_pointer,IV_nc_start,IV_nc_count2)\n\n\n!*******************************************************************************\n!Restore array to PETSc vector\n!*******************************************************************************\nif (rank==0) call VecRestoreArrayF90(ZV_SeqZero,ZV_pointer,ierr)\n\n\n!*******************************************************************************\n!End\n!*******************************************************************************\n\nend subroutine rapid_write_Qout_file\n"
  },
  {
    "path": "src/Routing/CMakeLists.txt",
    "content": "add_library(hydro_routing STATIC\n        module_UDMAP.F90\n        module_channel_routing.F90\n        module_date_utilities_rt.F90\n        module_GW_baseflow.F90\n        module_gw_gw2d.F90\n        module_HYDRO_io.F90\n        module_HYDRO_utils.F90\n        module_lsm_forcing.F90\n        module_noah_chan_param_init_rt.F90\n        module_NWM_io_dict.F90\n        module_NWM_io.F90\n        module_reservoir_routing.F90\n        module_RT.F90\n        Noah_distr_routing.F90\n        Noah_distr_routing_overland.F90\n        Noah_distr_routing_subsurface.F90\n)\n\ntarget_link_libraries(hydro_routing\n       PRIVATE\n       MPI::MPI_Fortran\n       hydro_mpp\n       hydro_utils\n       hydro_orchestrator\n       hydro_routing_overland\n       hydro_routing_subsurface\n       hydro_routing_reservoirs\n       hydro_routing_reservoirs_levelpool\n       hydro_routing_reservoirs_hybrid\n       hydro_data_rec\n       hydro_routing_reservoirs_rfc\n       hydro_routing_diversions\n)\n\nif (WRF_HYDRO_NUDGING_IO STREQUAL \"1\")\n  target_link_libraries(hydro_routing\n    PRIVATE\n    hydro_nudging_io\n  )\nendif()\n"
  },
  {
    "path": "src/Routing/Diversions/CMakeLists.txt",
    "content": "add_library(hydro_routing_diversions STATIC\n    module_diversions.F90\n    module_diversions_timeslice.F90\n)\n\nadd_dependencies(hydro_routing_diversions hydro_orchestrator)\nadd_dependencies(hydro_routing_diversions fortglob)\n\ntarget_link_libraries(hydro_routing_diversions PUBLIC hydro_orchestrator)\ntarget_link_libraries(hydro_routing_diversions PUBLIC fortglob)\n"
  },
  {
    "path": "src/Routing/Diversions/Makefile",
    "content": "# Makefile\n#\ninclude ../../macros\n\nOBJS = \\\n\tmodule_diversions_timeslice.o \\\n\tmodule_diversions.o\n\nall:\t$(OBJS)\n\n%.o: %.F90\n\t@echo \"Routing Diversions Makefile:\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -o $(@) $(F90FLAGS) $(LDFLAGS) -I\"../../mod\" -I$(NETCDFINC) $(*).F90  \n\t@echo \"\"\n\tar -r ../../lib/libHYDRO.a $(@)\n\tcp *.mod ../../mod\n\n\nfortglob_dir:\n\tmake -C ../../utils/fortglob\n\nmodule_diversions_timeslice.o: fortglob_dir\n\nmodule_diversions.o: module_diversions_timeslice.o\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Routing/Diversions/module_diversions.F90",
    "content": "module module_channel_diversions\n    use netcdf\n    use iso_fortran_env, only: int8, int16, int64\n    use ieee_arithmetic, only: ieee_is_nan\n\n    use module_diversions_timeslice, only: get_flow_for_gage, init_timeslices\n    use module_hydro_stop, only: hydro_stop\n\n    implicit none\n\n    type diversion_t\n        character(len=128) :: name\n\n        character(len=16)  :: da_src, da_dest\n        integer(kind=int8)  :: type_div, type_src, type_dest\n        integer(kind=int64) :: id_src, id_dest, src_index, dest_index\n        real :: capacity, fraction\n        integer(kind=int16) :: lookback\n\n        real :: persisted_flow_src, persisted_flow_dest\n    end type\n\n    logical :: diversions_active = .false.\n    integer :: ndivs = 0\n\n    type(diversion_t), allocatable :: diversions(:)\n\n    character(*), parameter :: free = '(*(g0,1x))'\n\ncontains\n    subroutine init_diversions(diversions_file, timeslice_path)\n        character(*), intent(in) :: diversions_file\n        character(*), intent(in) :: timeslice_path\n\n        integer :: g, i, ierr = 0\n        character(len=20) :: istr\n        character(len=256) :: char_tmp\n\n        integer :: ncid, dimid\n        integer :: name_vid, type_div_vid, type_src_vid, type_dest_vid, da_src_vid, da_dest_vid\n        integer :: id_src_vid, id_dest_vid, capacity_vid, fraction_vid, lookback_vid\n\n        if (len_trim(diversions_file) > 0) then\n            print *, \"Loading diversions data from \" // trim(diversions_file)\n            ierr = nf90_open(trim(diversions_file), NF90_NOWRITE, ncid)\n            if (ierr /= 0) call hydro_stop(\"Could not open diversions file: \" // trim(diversions_file))\n            ierr = nf90_inq_dimid(ncid, \"diversion\", dimid)\n            if (ierr /= 0) call hydro_stop(\"Error reading diversions file: \" // trim(diversions_file))\n            ierr = nf90_inquire_dimension(ncid, dimid, len=ndivs)\n            if (ierr /= 0) call hydro_stop(\"Error reading diversions file: \" // trim(diversions_file))\n\n            write (istr, *) ndivs\n            print *, \"Diversions file has \" // trim(adjustl(istr)) // \" diversions\"\n\n            ! get fields\n            ierr = 0\n            ierr = ierr + nf90_inq_varid(ncid, \"Diversion_Name\", name_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"DivType\", type_div_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"FromType\", type_src_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"ToType\", type_dest_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"DA_Src\", da_src_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"DA_Dest\", da_dest_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"DivFrom\", id_src_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"DivTo\", id_dest_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"DivCap\", capacity_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"DivFrac\", fraction_vid)\n            ierr = ierr + nf90_inq_varid(ncid, \"Lookback\", lookback_vid)\n\n            if (ierr /= 0) then\n                print free, \"WARNING: error occurred accessing diversion file variables, will disable diversions\"\n                return\n            end if\n\n            if (ndivs > 0) then\n                ! Read the timeslice data\n                ierr = init_timeslices(timeslice_path)\n                if (ierr /= 0) then\n                    print free, \"WARNING: No timeslice files available when initializing diversions, will disable diversions\"\n                    return\n                end if\n\n                diversions_active = .true.\n\n                allocate(diversions(ndivs))\n                do i = 1, ndivs\n                    associate (div => diversions(i))\n                        div = diversion_t('', '', '', -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)\n\n                        ierr = 0\n                        !ierr = ierr + nf_get_var1(ncid, name_vid, i, div%name)  !! can't read string with Fortran :-(\n\n                        ierr = ierr + nf90_get_var(ncid, da_src_vid, div%da_src, start=(/i/), count=(/15/))\n                        div%persisted_flow_src = get_flow_for_gage(div%da_src)\n                        ierr = ierr + nf90_get_var(ncid, da_dest_vid, div%da_dest, start=(/i/), count=(/15/))\n                        div%persisted_flow_dest = get_flow_for_gage(div%da_dest)\n\n                        ierr = ierr + nf90_get_var(ncid, type_div_vid, div%type_div, start=(/i/))\n                        ierr = ierr + nf90_get_var(ncid, type_src_vid, div%type_src, start=(/i/))\n                        ierr = ierr + nf90_get_var(ncid, type_dest_vid, div%type_dest, start=(/i/))\n                        ierr = ierr + nf90_get_var(ncid, id_src_vid, div%id_src, start=(/i/))\n                        ierr = ierr + nf90_get_var(ncid, id_dest_vid, div%id_dest, start=(/i/))\n                        ierr = ierr + nf90_get_var(ncid, capacity_vid, div%capacity, start=(/i/))\n                        ierr = ierr + nf90_get_var(ncid, fraction_vid, div%fraction, start=(/i/))\n                        ierr = ierr + nf90_get_var(ncid, lookback_vid, div%lookback, start=(/i/))\n\n                        if (ierr /= 0) then\n                            print free, \"WARNING: error occurred reading diversion variables from diversion file, will disable diversions\"\n                            diversions_active = .false.\n                            return\n                        end if\n                    end associate\n                end do\n\n            end if\n        end if\n\n    end subroutine\n\n    subroutine calculate_diversion(src_link_in, qlink_src_in, diversion_quantity_out, diversion_quantity_in)\n        integer(kind=int64), intent(in) :: src_link_in\n        ! integer(kind=int64), intent(out) :: dst_out\n        real, intent(in) :: qlink_src_in\n        real, intent(out) :: diversion_quantity_out, diversion_quantity_in\n\n        integer :: i\n\n        diversion_quantity_out = 0\n        diversion_quantity_in = 0\n\n        ! bail if we're inactive\n        if (.not. diversions_active) return\n\n        ! link to gage\n        ! look to see what type of diversion it is\n        ! call into sub-procedure to handle type=1, type=2, type=3, etc\n\n        do i = 1, ndivs\n            if (src_link_in == diversions(i)%id_src) then\n                if (diversions(i)%type_div /= 3) then\n                    print free, \"!!! UNSUPPORTED DIVERSION TYPE (\", diversions(i)%type_div, \"), skipping\"\n                else\n                    call gage_assisted_diversion(src_link_in, diversions(i), qlink_src_in, diversion_quantity_out)\n                    ! dst_out = diversions(i)%id_dest\n                end if\n            end if\n\n            if (src_link_in == diversions(i)%id_dest) then\n                if (diversions(i)%type_div /= 3) then\n                    print free, \"!!! UNSUPPORTED DIVERSION TYPE (\", diversions(i)%type_div, \"), skipping\"\n                else\n                    if (.not. ieee_is_nan(diversions(i)%persisted_flow_dest)) &\n                        diversion_quantity_in = diversions(i)%persisted_flow_dest\n                end if\n            end if\n        end do\n\n        ! subtract dst_out from source gage\n\n    end subroutine\n\n    subroutine gage_assisted_diversion(src_link, diversion, qlink_src, div_gage_flow)\n        integer(kind=int64), intent(in) :: src_link\n        type(diversion_t), intent(in) :: diversion\n        real, intent(in) :: qlink_src\n        real, intent(out) :: div_gage_flow\n\n        real :: fraction\n\n        ! This is the so-called \"Type 3\" diversion. We take the observed flow from div_gage,\n        ! and subtract it from the upstream qlink_src, if it's a valid flow (not-NaN).\n        !\n        ! If it's not a valid flow, we try to use the Fraction property of the diversion,\n        ! and if -that's- not available, we just leave the flow untouched.\n\n        div_gage_flow = diversion%persisted_flow_dest\n        if (ieee_is_nan(div_gage_flow)) then\n            fraction = diversion%fraction\n            if (fraction == -1) then\n                print free, \"WARNING: No fractional diversion value specified for diversion at gage '\" // trim(adjustl(diversion%da_dest)) // \"', skipping\"\n                fraction = 0\n            else\n                print free, \"INFO: No gage discharge available for diversion '\" // trim(adjustl(diversion%da_dest)) // \"', using fixed fractional diversion of\", fraction\n            end if\n            div_gage_flow = qlink_src * fraction\n        end if\n    end subroutine\n\nend module\n"
  },
  {
    "path": "src/Routing/Diversions/module_diversions_timeslice.F90",
    "content": "module module_diversions_timeslice\n    use fortglob, only: glob_t, globfiles\n    use module_hydro_stop, only: hydro_stop\n\n    use netcdf\n    use ieee_arithmetic, only: ieee_value, ieee_quiet_nan, ieee_is_nan\n    implicit none\n\n    integer, parameter :: PATH_MAX = 4096\n    type(glob_t) :: timeslice_files\n\n    character(*), parameter :: free = '(*(g0,1x))'\n\n    contains\n\n    integer function init_timeslices(timeslice_path) result(ierr)\n        character(*), intent(in) :: timeslice_path\n        character(len=PATH_MAX) :: tslice_glob\n\n        ierr = 0\n        tslice_glob = trim(adjustl(timeslice_path)) // '/' // \"*.15min.usgsTimeSlice.ncdf\"\n        timeslice_files = globfiles(tslice_glob)\n\n        if (timeslice_files%nfiles == 0) ierr = 1\n    end function\n\n    real function get_flow_for_gage(gage) result(flow)\n        character(len=15), intent(in) :: gage\n\n        integer :: i, ierr=0, ncid, dimid, varid, num_stns, found(1)\n        real    :: discharge(1)\n        character(len=15), allocatable :: gage_ids(:)\n\n        flow = ieee_value(flow, ieee_quiet_nan)\n\n        if (gage(1:4) == 'None') then\n            return\n        end if\n\n        ! start looking at files, going backward from most recent\n        do i = timeslice_files%nfiles, 1, -1\n            ierr = nf90_open(trim(timeslice_files%filenames(i)), NF90_NOWRITE, ncid)\n\n            ! look for gage\n            ierr = ierr + nf90_inq_dimid(ncid, 'stationIdInd', dimid)\n            ierr = ierr + nf90_inquire_dimension(ncid, dimid, len=num_stns)\n\n            allocate(gage_ids(num_stns))\n            ierr = ierr + nf90_inq_varid(ncid, 'stationId', varid)\n            ierr = ierr + nf90_get_var(ncid, varid, gage_ids)\n\n            if (ierr /= 0) call hydro_stop(\"Error occurred reading gage data from \" // trim(timeslice_files%filenames(i)))\n\n            found = findloc(gage_ids, gage)\n            if (found(1) /= 0) then\n#ifdef HYDRO_D\n                print free, \"DEBUG: Reading diversion discharge for gage \" // trim(adjustl(gage)) // \" from \" // trim(timeslice_files%filenames(i))\n#endif\n                ierr = ierr + nf90_inq_varid(ncid, 'discharge', varid)\n                ierr = ierr + nf90_get_var(ncid, varid, discharge, start=found, count=(/1/))\n                if (ierr /= 0) call hydro_stop(\"Error occurred reading gage data from \" // trim(timeslice_files%filenames(i)))\n\n                if (discharge(1) >= 0) then\n                    flow = discharge(1)\n                    deallocate(gage_ids)\n                    return\n#ifdef HYDRO_D\n                else\n                    print free, \"DEBUG: Diversion discharge value invalid, continuing search if able\"\n#endif\n                end if\n            end if\n\n            deallocate(gage_ids)\n            ierr = nf90_close(ncid)\n        end do\n\n        print free, \"WARNING: Valid gage discharge not found in any timeslice file, falling back to fractional diversion\"\n    end function\n\nend module"
  },
  {
    "path": "src/Routing/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nOBJS = \\\n\tmodule_date_utilities_rt.o \\\n\tmodule_UDMAP.o \\\n\tmodule_HYDRO_utils.o \\\n\tmodule_noah_chan_param_init_rt.o \\\n\tmodule_GW_baseflow.o \\\n\tmodule_gw_gw2d.o \\\n\tmodule_HYDRO_io.o \\\n\tmodule_RT.o \\\n\tNoah_distr_routing.o \\\n\tNoah_distr_routing_overland.o \\\n\tNoah_distr_routing_subsurface.o \\\n\tmodule_channel_routing.o \\\n\tmodule_lsm_forcing.o \\\n\tmodule_date_utilities_rt.o \\\n\tmodule_NWM_io_dict.o \\\n\tmodule_NWM_io.o \\\n        module_reservoir_routing.o\n\nall:\t$(OBJS)\n\n#module_RT.o: module_RT.F90\n#\t@echo \"\"\n#\t$(CPP) $(CPPFLAGS) $(*).F90 > $(*).f90\n#\t$(COMPILER90) -o $(@) $(F90FLAGS) $(MODFLAG)  $(*).f90\n#\t$(RMD) $(*).f90\n#\t@echo \"\"\n#\tcp *.mod ../mod\n\n.F90.o:\n\t@echo \"Routing Makefile:\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -o $(@) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) $(*).F90\n\t@echo \"\"\n\tar -r ../lib/libHYDRO.a $(@)\n\tcp *.mod ../mod\n\n#\n# Dependencies:\n#\nmodule_gw_gw2d.o: ../Data_Rec/module_gw_gw2d_data.o module_HYDRO_io.o\n\nifneq ($(WRF_HYDRO_NUDGING),-DWRF_HYDRO_NUDGING)\nmodule_HYDRO_io.o:  module_HYDRO_utils.o \\\n\t            module_date_utilities_rt.o \\\n                    ../Data_Rec/module_namelist.o \\\n\t \t    ../Data_Rec/module_RT_data.o\nelse\nmodule_HYDRO_io.o:  module_HYDRO_utils.o \\\n\t            module_date_utilities_rt.o \\\n\t\t    ../nudging/module_date_utils_nudging.o \\\n\t            ../nudging/module_nudging_io.o \\\n                    ../Data_Rec/module_namelist.o \\\n\t \t    ../Data_Rec/module_RT_data.o\nendif\n\nmodule_NWM_io_dict: ../Data_Rec/module_namelist.o ../utils/module_version.o\n\nmodule_NWM_io: module_HYDRO_utils.o \\\n               module_NWM_io_dict.o \\\n               module_HYDRO_io.o \\\n               module_date_utilities_rt.o \\\n\t       ../OrchestratorLayer/orchestrator.o \\\n               ../Data_Rec/module_namelist.o \\\n               ../Data_Rec/module_RT_data.o \\\n\t       ../utils/module_version.o\n\nmodule_reservoir_routing: ../Data_Rec/module_namelist.o\n\nmodule_HYDRO_utils.o: ../Data_Rec/module_namelist.o ../Data_Rec/module_RT_data.o\n\nmodule_lsm_forcing.o: module_HYDRO_io.o\n\nifneq ($(WRF_HYDRO_NUDGING),-DWRF_HYDRO_NUDGING)\nmodule_RT.o: module_GW_baseflow.o \\\n\t     module_HYDRO_utils.o \\\n             module_HYDRO_io.o \\\n             module_noah_chan_param_init_rt.o \\\n\t     module_UDMAP.o \\\n             module_channel_routing.o \\\n\t     ../Data_Rec/module_namelist.o \\\n\t     ../Data_Rec/module_RT_data.o \\\n\t     ../Data_Rec/module_gw_gw2d_data.o\nelse\nmodule_RT.o: module_GW_baseflow.o \\\n\t     module_HYDRO_utils.o \\\n             module_HYDRO_io.o \\\n             module_noah_chan_param_init_rt.o \\\n\t     module_UDMAP.o \\\n\t     ../Data_Rec/module_namelist.o \\\n\t     ../Data_Rec/module_RT_data.o \\\n\t     ../Data_Rec/module_gw_gw2d_data.o \\\n             ../nudging/module_date_utils_nudging.o \\\n             ../nudging/module_nudging_io.o\nendif\n\nmodule_UDMAP.o: ../Data_Rec/module_namelist.o ../Data_Rec/module_RT_data.o\n\nifneq ($(WRF_HYDRO_NUDGING),-DWRF_HYDRO_NUDGING)\nmodule_channel_routing.o: module_UDMAP.o \\\n\t\t\t  Diversions/module_diversions.o\nelse\nmodule_channel_routing.o: module_UDMAP.o \\\n\t\t\t  Diversions/module_diversions.o \\\n\t\t\t  ../nudging/module_date_utils_nudging.o \\\n\t\t          ../nudging/module_nudging_utils.o \\\n\t\t\t  ../nudging/module_stream_nudging.o\nendif\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/Routing/Noah_distr_routing.F90",
    "content": "!DJG ------------------------------------------------\n!DJG   SUBROUTINE RT_PARM\n!DJG ------------------------------------------------\n\nSUBROUTINE RT_PARM(IX,JY,IXRT,JXRT,VEGTYP,RETDP,OVRGH,  &\n        AGGFACTR)\n#ifdef MPP_LAND\n    use module_mpp_land, only: left_id,down_id,right_id,&\n        up_id,mpp_land_com_real,MPP_LAND_UB_COM, &\n        MPP_LAND_LR_COM,mpp_land_com_integer\n#endif\n\n    IMPLICIT NONE\n\n    !DJG -------- DECLARATIONS -----------------------\n\n    INTEGER, INTENT(IN) :: IX,JY,IXRT,JXRT,AGGFACTR\n\n    INTEGER, INTENT(IN), DIMENSION(IX,JY)\t:: VEGTYP\n    REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)\t:: RETDP\n    REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)\t:: OVRGH\n\n\n    !DJG Local Variables\n\n    INTEGER\t:: I,J,IXXRT,JYYRT\n    INTEGER :: AGGFACYRT,AGGFACXRT\n\n\n    !DJG Assign RETDP and OVRGH based on VEGTYP...\n\n    do J=1,JY\n        do I=1,IX\n\n            do AGGFACYRT=AGGFACTR-1,0,-1\n                do AGGFACXRT=AGGFACTR-1,0,-1\n\n                    IXXRT=I*AGGFACTR-AGGFACXRT\n                    JYYRT=J*AGGFACTR-AGGFACYRT\n#ifdef MPP_LAND\n                    if(left_id.ge.0) IXXRT=IXXRT+1\n                    if(down_id.ge.0) JYYRT=JYYRT+1\n#else\n                    !yw ????\n                    !       IXXRT=IXXRT+1\n                    !       JYYRT=JYYRT+1\n#endif\n\n                    !        if(AGGFACTR .eq. 1) then\n                    !            IXXRT=I\n                    !            JYYRT=J\n                    !        endif\n\n\n\n                    !DJG Urban, rock, playa, snow/ice...\n                    IF (VEGTYP(I,J).EQ.1.OR.VEGTYP(I,J).EQ.26.OR.   &\n                            VEGTYP(I,J).EQ.26.OR.VEGTYP(I,J).EQ.24) THEN\n                        RETDP(IXXRT,JYYRT)=1.3\n                        OVRGH(IXXRT,JYYRT)=0.1\n                        !DJG Wetlands and water bodies...\n                    ELSE IF (VEGTYP(I,J).EQ.17.OR.VEGTYP(I,J).EQ.18.OR.  &\n                            VEGTYP(I,J).EQ.19.OR.VEGTYP(I,J).EQ.16) THEN\n                        RETDP(IXXRT,JYYRT)=10.0\n                        OVRGH(IXXRT,JYYRT)=0.2\n                        !DJG All other natural covers...\n                    ELSE\n                        RETDP(IXXRT,JYYRT)=5.0\n                        OVRGH(IXXRT,JYYRT)=0.2\n                    END IF\n\n                end do\n            end do\n\n        end do\n    end do\n#ifdef MPP_LAND\n    call MPP_LAND_COM_REAL(RETDP,IXRT,JXRT,99)\n    call MPP_LAND_COM_REAL(OVRGH,IXRT,JXRT,99)\n#endif\n\n    !DJG ----------------------------------------------------------------\nEND SUBROUTINE RT_PARM\n!DJG ----------------------------------------------------------------\n\n\n!DJG ----------------------------------------------------------------\nSUBROUTINE GETMAX8DIR(IXX0,JYY0,I,J,H,RETENT_DEP,sox,tmp_gsize,max,XX,YY)\n    implicit none\n    INTEGER:: IXX0,JYY0,IXX8,JYY8, XX, YY\n    INTEGER, INTENT(IN) :: I,J\n\n    REAL,INTENT(IN) :: H(XX,YY),RETENT_DEP(XX,YY),sox(XX,YY,8),tmp_gsize(9)\n    REAL  max\n    IXX0 = -1\n    max = 0\n    if (h(I,J).LE.retent_dep(I,J)) return\n\n    IXX8 = I\n    JYY8 = J+1\n    call GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox(:,:,1),IXX0,JYY0,max,tmp_gsize(1),XX,YY)\n\n    IXX8 = I+1\n    JYY8 = J+1\n    call GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox(:,:,2),IXX0,JYY0,max,tmp_gsize(2),XX,YY)\n\n    IXX8 = I+1\n    JYY8 = J\n    call GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox(:,:,3),IXX0,JYY0,max,tmp_gsize(3),XX,YY)\n\n    IXX8 = I+1\n    JYY8 = J-1\n    call GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox(:,:,4),IXX0,JYY0,max,tmp_gsize(4),XX,YY)\n\n    IXX8 = I\n    JYY8 = J-1\n    call GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox(:,:,5),IXX0,JYY0,max,tmp_gsize(5),XX,YY)\n\n    IXX8 = I-1\n    JYY8 = J-1\n    call GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox(:,:,6),IXX0,JYY0,max,tmp_gsize(6),XX,YY)\n\n    IXX8 = I-1\n    JYY8 = J\n    call GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox(:,:,7),IXX0,JYY0,max,tmp_gsize(7),XX,YY)\n\n    IXX8 = I-1\n    JYY8 = J+1\n    call GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox(:,:,8),IXX0,JYY0,max,tmp_gsize(8),XX,YY)\nEND SUBROUTINE GETMAX8DIR\n\nSUBROUTINE GET8DIR(IXX8,JYY8,I,J,H,RETENT_DEP,sox   &\n        ,IXX0,JYY0,max,tmp_gsize,XX,YY)\n    implicit none\n    integer,INTENT(INOUT) ::IXX0,JYY0\n    INTEGER, INTENT(IN) :: I,J,IXX8,JYY8,XX,YY\n    REAL,INTENT(IN) :: H(XX,YY),RETENT_DEP(XX,YY),sox(XX,YY)\n    REAL, INTENT(INOUT) ::max\n    real, INTENT(IN) :: tmp_gsize\n    real :: sfx\n\n    sfx = sox(i,j)-(h(IXX8,JYY8)-h(i,j))*0.001/tmp_gsize\n    if(sfx .le. 0 ) return\n    if(max < sfx ) then\n        IXX0 = IXX8\n        JYY0 = JYY8\n        max = sfx\n    end if\n\nEND SUBROUTINE GET8DIR\n\n!DJG------------------------------------------------------------\n\n\nSUBROUTINE GETSUB8(I, J, XX, YY, wattbl, terrslpNeighbors, distNeighbors, &\n                   maxneighI, maxneighJ, maxneighIndx, maxneighSlp)\n   implicit none\n   integer, intent(in)    :: I, J ! i, j indices for cell of interest\n   integer, intent(in)    :: XX, YY ! rt domain dimensions\n   real, intent(in)       :: wattbl(XX, YY) ! water table depth domain array (m)\n   real, intent(in)       :: terrslpNeighbors(XX, YY, 8)\n                             ! terrain slope 2d domain array for all 8 neighbors (m/m)\n   real, intent(in)       :: distNeighbors(9)\n                             ! lateral distance array for all 8 neighbors of I,J cell (m)\n   integer, intent(inout) :: maxneighI, maxneighJ ! i, j for max terrain+head slope neighbor\n   integer, intent(inout) :: maxneighIndx\n                             ! neighbor cell direction index for max terrain+head slope neighbor\n   real, intent(inout)    :: maxneighSlp ! terrain+head slope for max slope neighbor (m/m)\n\n   ! Local variables\n   integer                :: neighIndx ! local neighbor direction index (1-8)\n   integer                :: neighI(8), neighJ(8) ! arrays of neighbor i, j indices\n\n   ! Initialize maxslp vars to negative in case max cannot be found\n   maxneighSlp = -1\n\n   ! Setup i, j arrays for neighbors, starting north and rotating clockwise\n   neighI = (/ I,   I+1, I+1, I+1, I,   I-1, I-1, I-1 /)\n   neighJ = (/ J+1, J+1, J,   J-1, J-1, J-1, J,   J+1 /)\n\n   ! Loop through all neighbors to update max elev+head slope neighbor\n   do neighIndx = 1, 8\n      call GETSUB8DIR(I, J, wattbl(I, J), &\n                      neighI(neighIndx), neighJ(neighIndx), neighIndx, &\n                      wattbl(neighI(neighIndx), neighJ(neighIndx)), &\n                      terrslpNeighbors(I,J,neighIndx), distNeighbors(neighIndx), &\n                      maxneighI, maxneighJ, maxneighIndx, maxneighSlp)\n   enddo\nEND SUBROUTINE GETSUB8\n\nSUBROUTINE GETSUB8DIR(I, J, selfWattbl, &\n                      neighI, neighJ, neighIndx, neighWattbl, &\n                      neighTerrslp, neighDist, &\n                      maxneighI, maxneighJ, maxneighIndx, maxneighSlp)\n   implicit none\n   integer, intent(in)    :: I, J ! i, j indices for cell of interest\n   real, intent(in)       :: selfWattbl ! water table depth for cell of interest (m)\n   integer, intent(in)    :: neighI, neighJ ! neighbor cell i, j indices\n   integer, intent(in)    :: neighIndx ! neighbor cell direction index (1-8)\n   real, intent(in)       :: neighWattbl ! water table depth for specified neighbor index (m)\n   real, intent(in)       :: neighTerrslp\n                             ! terrain slope for specified neighbor index (m/m)\n   real, intent(in)       :: neighDist\n                             ! lateral distance for specified neighbor index (m)\n   integer, intent(inout) :: maxneighI, maxneighJ ! i, j for max terrain+head slope neighbor\n   integer, intent(inout) :: maxneighIndx\n                             ! neighbor cell direction index for max terrain+head slope neighbor\n   real, intent(inout)    :: maxneighSlp\n                             ! terrain+head slope for max terrain+head slope neighbor (m/m)\n\n   ! Local variables\n   real                   :: dzdx ! subsurface head slope (m/m)\n   real                   :: beta ! total terrain+head slope (m/m)\n\n   ! Calculate total head slope\n   ! NOTE: wattbl is depth of water table from surface (e.g., 0m if saturated column,\n   ! 2m if no water table present). So total head slope should be:\n   !    beta = ( (elev - wattbl) - (elev_neigh - wattbl_neigh) ) / distance\n   !         = neighTerrslp - dzdx\n   dzdx = ( selfWattbl - neighWattbl ) / neighDist\n   beta = neighTerrslp - dzdx\n   ! Check if this is max and update tracking variables\n   if ( maxneighSlp < beta ) then\n      maxneighI = neighI\n      maxneighJ = neighJ\n      maxneighSlp = beta\n      maxneighIndx = neighIndx\n   end if\nEND SUBROUTINE GETSUB8DIR\n\n\n!DJG-----------------------------------------------------------------------\n!DJG SUBROUTINE TER_ADJ_SOL    - Terrain adjustment of incoming solar radiation\n!DJG-----------------------------------------------------------------------\nSUBROUTINE TER_ADJ_SOL(IX,JX,SO8LD_D,TSLP,SHORT,XLAT,XLONG,olddate,DT)\n\n#ifdef MPP_LAND\n    use module_mpp_land, only:  my_id, io_id, &\n        mpp_land_bcast_int1\n#endif\n    implicit none\n    integer,INTENT(IN)     :: IX,JX\n    INTEGER,INTENT(in), DIMENSION(IX,JX,3)   :: SO8LD_D\n    real,INTENT(IN), DIMENSION(IX,JX)  :: XLAT,XLONG\n    real,INTENT(IN) :: DT\n    real,INTENT(INOUT), DIMENSION(IX,JX)  :: SHORT\n    character(len=19) :: olddate\n\n    ! Local Variables...\n    real, dimension(IX,JX) ::TSLP,TAZI\n    real, dimension(IX,JX) ::SOLDN\n    real :: SOLDEC,DGRD,ITIME2,HRANGLE\n    real :: BINSH,SOLZANG,SOLAZI,INCADJ\n    real :: TAZIR,TSLPR,LATR,LONR,SOLDNADJ\n    integer :: JULDAY0,HHTIME0,MMTIME0,YYYY0,MM0,DD0\n    integer :: JULDAY,HHTIME,MMTIME,YYYY,MM,DD\n    integer :: I,J\n\n\n    !----------------------------------------------------------------------\n    !  SPECIFY PARAMETERS and VARIABLES\n    !----------------------------------------------------------------------\n\n    JULDAY = 0\n    SOLDN = SHORT\n    DGRD = 3.14159/180.\n\n    ! Set up time variables...\n#ifdef MPP_LAND\n    if(my_id .eq. IO_id) then\n#endif\n        read(olddate(1:4),\"(I4)\") YYYY0 ! real-time year (GMT)\n        read(olddate(6:7),\"(I2.2)\") MM0 ! real-time month (GMT)\n        read(olddate(9:10),\"(I2.2)\") DD0 ! real-time day (GMT)\n        read(olddate(12:13),\"(I2.2)\") HHTIME0 ! real-time hour (GMT)\n        read(olddate(15:16),\"(I2.2)\") MMTIME0 ! real-time minutes (GMT)\n#ifdef MPP_LAND\n    endif\n    call mpp_land_bcast_int1(YYYY0)\n    call mpp_land_bcast_int1(MM0)\n    call mpp_land_bcast_int1(DD0)\n    call mpp_land_bcast_int1(HHTIME0)\n    call mpp_land_bcast_int1(MMTIME0)\n#endif\n\n\n    ! Set up terrain variables...(returns TSLP&TAZI in radians)\n    call SLOPE_ASPECT(IX,JX,SO8LD_D,TAZI)\n\n    !----------------------------------------------------------------------\n    !  BEGIN LOOP THROUGH GRID\n    !----------------------------------------------------------------------\n    DO J=1,JX\n        DO I=1,IX\n            YYYY = YYYY0\n            MM  = MM0\n            DD  = DD0\n            HHTIME = HHTIME0\n            MMTIME = MMTIME0\n            call GMT2LOCAL(1,1,XLONG(i,j),YYYY,MM,DD,HHTIME,MMTIME,DT)\n            call JULDAY_CALC(YYYY,MM,DD,JULDAY)\n\n            ! Convert to radians...\n            LATR = XLAT(I,J)   !send solsub local lat in deg\n            LONR = XLONG(I,J)   !send solsub local lon in deg\n            TSLPR = TSLP(I,J)/DGRD !send solsub local slp in deg\n            TAZIR = TAZI(I,J)/DGRD !send solsub local azim in deg\n\n            !Call SOLSUB to return terrain adjusted incoming solar radiation...\n            ! SOLSUB taken from Whiteman and Allwine, 1986, Environ. Software.\n\n            call SOLSUB(LONR,LATR,TAZIR,TSLPR,SOLDN(I,J),YYYY,MM,         &\n                DD,HHTIME,MMTIME,SOLDNADJ,SOLZANG,SOLAZI,INCADJ)\n\n            SOLDN(I,J)=SOLDNADJ\n\n        ENDDO\n    ENDDO\n\n    SHORT = SOLDN\n\nend SUBROUTINE TER_ADJ_SOL\n!DJG-----------------------------------------------------------------------\n!DJG END SUBROUTINE TER_ADJ_SOL\n!DJG-----------------------------------------------------------------------\n\n\n!DJG-----------------------------------------------------------------------\n!DJG SUBROUTINE GMT2LOCAL\n!DJG-----------------------------------------------------------------------\nsubroutine GMT2LOCAL(IX,JX,XLONG,YY,MM,DD,HH,MIN,DT)\n\n    implicit none\n\n    !!! Declare Passed Args.\n\n    INTEGER, INTENT(INOUT) :: yy,mm,dd,hh,min\n    INTEGER, INTENT(IN) :: IX,JX\n    REAL,INTENT(IN), DIMENSION(IX,JX)  :: XLONG\n    REAL,INTENT(IN) :: DT\n\n    !!! Declare local variables\n\n    integer :: i,j,minflag,hhflag,ddflag,mmflag,yyflag\n    integer :: adj_min,lst_adj_min,lst_adj_hh,adj_hh\n    real, dimension(IX,JX) :: TDIFF\n    real :: tmp\n    integer :: yyinit,mminit,ddinit,hhinit,mininit\n\n    !!! Initialize flags\n    hhflag=0\n    ddflag=0\n    mmflag=0\n    yyflag=0\n\n    !!! Set up constants...\n    yyinit = yy\n    mminit = mm\n    ddinit = dd\n    hhinit = hh\n    mininit = min\n\n\n    ! Loop through data...\n    do j=1,JX\n        do i=1,IX\n\n            ! Reset yy,mm,dd...\n            yy = yyinit\n            mm = mminit\n            dd = ddinit\n            hh = hhinit\n            min = mininit\n\n            !!! Set up adjustments...\n            !   - assumes +E , -W  longitude and 0.06667 hr/deg (=24/360)\n            TDIFF(I,J) = XLONG(I,J)*0.06667   ! time offset in hr\n            tmp = TDIFF(I,J)\n            lst_adj_hh = INT(tmp)\n            lst_adj_min = NINT(MOD(int(tmp),1)*60.) + int(DT/2./60.)  ! w/ 1/2 timestep adjustment...\n\n            !!! Process Minutes...\n            adj_min = min+lst_adj_min\n            if (adj_min.lt.0) then\n                min=60+adj_min\n                lst_adj_hh = lst_adj_hh - 1\n            else if (adj_min.ge.0.AND.adj_min.lt.60) then\n                min=adj_min\n            else if (adj_min.ge.60) then\n                min=adj_min-60\n                lst_adj_hh = lst_adj_hh + 1\n            end if\n\n            !!! Process Hours\n            adj_hh = hh+lst_adj_hh\n            if (adj_hh.lt.0) then\n                hh = 24+adj_hh\n                ddflag=1\n            else if (adj_hh.ge.0.AND.adj_hh.lt.24) then\n                hh=adj_hh\n            else if (adj_hh.ge.24) then\n                hh=adj_hh-24\n                ddflag = 2\n            end if\n\n\n\n            !!! Process Days, Months, Years\n            ! Subtract a day\n            if (ddflag.eq.1) then\n                if (dd.gt.1) then\n                    dd=dd-1\n                else\n                    if (mm.eq.1) then\n                        mm=12\n                        yy=yy-1\n                    else\n                        mm=mm-1\n                    end if\n                    if ((mm.eq.1).or.(mm.eq.3).or.(mm.eq.5).or. &\n                            (mm.eq.7).or.(mm.eq.8).or.(mm.eq.10).or. &\n                            (mm.eq.12)) then\n                        dd=31\n                    else\n\n                        !!! Adjustment for leap years!!!\n                        if(mm.eq.2) then\n                            if(MOD(yy,4).eq.0) then\n                                dd=29\n                            else\n                                dd=28\n                            end if\n                        end if\n                        if(mm.ne.2) dd=30\n                    end if\n                end if\n            end if\n\n            ! Add a day\n            if (ddflag.eq.2) then\n                if ((mm.eq.1).or.(mm.eq.3).or.(mm.eq.5).or. &\n                        (mm.eq.7).or.(mm.eq.8).or.(mm.eq.10).or. &\n                        (mm.eq.12)) then\n                    if (dd.eq.31) then\n                        dd=1\n                        if (mm.eq.12) then\n                            mm=1\n                            yy=yy+1\n                        else\n                            mm=mm+1\n                        end if\n                    else\n                        dd=dd+1\n                    end if\n\n                    !!! Adjustment for leap years!!!\n                else if (mm.eq.2) then\n                    if(MOD(yy,4).eq.0) then\n                        if (dd.eq.29) then\n                            dd=1\n                            mm=3\n                        else\n                            dd=dd+1\n                        end if\n                    else\n                        if (dd.eq.28) then\n                            dd=1\n                            mm=3\n                        else\n                            dd=dd+1\n                        end if\n                    end if\n                else\n                    if (dd.eq.30) then\n                        dd=1\n                        mm=mm+1\n                    else\n                        dd=dd+1\n                    end if\n                end if\n\n            end if\n\n        end do   !i-loop\n    end do   !j-loop\n\nend subroutine\n\n!DJG-----------------------------------------------------------------------\n!DJG END SUBROUTINE GMT2LOCAL\n!DJG-----------------------------------------------------------------------\n\n\n\n!DJG-----------------------------------------------------------------------\n!DJG SUBROUTINE JULDAY_CALC\n!DJG-----------------------------------------------------------------------\nsubroutine JULDAY_CALC(YYYY,MM,DD,JULDAY)\n\n    implicit none\n    integer,intent(in) :: YYYY,MM,DD\n    integer,intent(out) :: JULDAY\n\n    integer :: resid\n    integer julm(13)\n    DATA JULM/0, 31, 59, 90, 120, 151, 181, 212, 243, 273, &\n        304, 334, 365 /\n\n    integer LPjulm(13)\n    DATA LPJULM/0, 31, 60, 91, 121, 152, 182, 213, 244, 274, &\n        305, 335, 366 /\n\n    resid = MOD(YYYY,4) !Set up leap year check...\n\n    if (resid.ne.0) then    !If not a leap year....\n        JULDAY = JULM(MM) + DD\n    else                    !If a leap year...\n        JULDAY = LPJULM(MM) + DD\n    end if\n\nEND subroutine JULDAY_CALC\n!DJG-----------------------------------------------------------------------\n!DJG END SUBROUTINE JULDAY\n!DJG-----------------------------------------------------------------------\n\n!DJG-----------------------------------------------------------------------\n!DJG SUBROUTINE SLOPE_ASPECT\n!DJG-----------------------------------------------------------------------\nsubroutine SLOPE_ASPECT(IX,JX,SO8LD_D,TAZI)\n\n    implicit none\n    integer, INTENT(IN)\t\t   :: IX,JX\n    !\treal,INTENT(in),DIMENSION(IX,JX)   :: TSLP  !terrain slope (m/m)\n    real,INTENT(OUT),DIMENSION(IX,JX)   :: TAZI  !terrain aspect (deg)\n\n    INTEGER, DIMENSION(IX,JX,3)   :: SO8LD_D\n    real :: DGRD\n    integer :: i,j\n\n    !\tTSLP = 0.  !Initialize as flat\n    TAZI = 0.  !Initialize as north facing\n\n    ! Find steepest descent slope and direction...\n    do j=1,JX\n        do i=1,IX\n            !\tTSLP(I,J) = TANH(Vmax(i,j)) ! calculate slope in radians...\n\n            ! Convert steepest slope and aspect to radians...\n            IF (SO8LD_D(i,j,3).eq.1) then\n                TAZI(I,J) = 0.0\n            ELSEIF (SO8LD_D(i,j,3).eq.2) then\n                TAZI(I,J) = 45.0\n            ELSEIF (SO8LD_D(i,j,3).eq.3) then\n                TAZI(I,J) = 90.0\n            ELSEIF (SO8LD_D(i,j,3).eq.4) then\n                TAZI(I,J) = 135.0\n            ELSEIF (SO8LD_D(i,j,3).eq.5) then\n                TAZI(I,J) = 180.0\n            ELSEIF (SO8LD_D(i,j,3).eq.6) then\n                TAZI(I,J) = 225.0\n            ELSEIF (SO8LD_D(i,j,3).eq.7) then\n                TAZI(I,J) = 270.0\n            ELSEIF (SO8LD_D(i,j,3).eq.8) then\n                TAZI(I,J) = 315.0\n            END IF\n\n            DGRD = 3.141593/180.\n            TAZI(I,J) = TAZI(I,J)*DGRD ! convert azimuth to radians...\n\n        END DO\n    END DO\n\nEND  subroutine SLOPE_ASPECT\n!DJG-----------------------------------------------------------------------\n!DJG END SUBROUTINE SLOPE_ASPECT\n!DJG-----------------------------------------------------------------------\n\n!DJG----------------------------------------------------------------\n!DJG    SUBROUTINE SOLSUB\n!DJG----------------------------------------------------------------\nSUBROUTINE SOLSUB(LONG,LAT,AZ,IN,SC,YY,MO,IDA,IHR,MM,OUT1, &\n        OUT2,OUT3,INCADJ)\n\n\n    ! Notes....\n\n    implicit none\n    logical               :: daily, first\n    integer               :: yy,mo,ida,ihr,mm,d\n    integer,dimension(12) :: nday\n    real                  :: lat,long,longcor,longsun,in,inslo\n    real :: az,sc,out1,out2,out3,cosbeta,dzero,eccent,pi,calint\n    real :: rtod,decmax,omega,onehr,omd,omdzero,rdvecsq,sdec\n    real :: declin,cdec,arg,declon,sr,stdmrdn,b,em,timnoon,azslo\n    real :: slat,clat,caz,saz,sinc,cinc,hinc,h,cosz,extra,extslo\n    real :: t1,z,cosa,a,cosbeta_flat,INCADJ\n    integer :: HHTIME,MMTIME,i,ik\n    real, dimension(4) :: ACOF,BCOF\n\n    ! Constants\n    daily=.FALSE.\n    ACOF(1) = 0.00839\n    ACOF(2) = -0.05391\n    ACOF(3) = -0.00154\n    ACOF(4) = -0.0022\n    BCOF(1) = -0.12193\n    BCOF(2) = -0.15699\n    BCOF(3) = -0.00657\n    BCOF(4) = -0.00370\n    DZERO = 80.\n    ECCENT = 0.0167\n    PI = 3.14159\n    CALINT = 1.\n    RTOD = PI / 180.\n    DECMAX=(23.+26./60.)*RTOD\n    OMEGA=2*PI/365.\n    ONEHR=15.*RTOD\n\n    ! Calculate Julian Day...\n    D = 0\n    call JULDAY_CALC(YY,MO,IDA,D)\n\n    ! Ratio of radius vectors squared...\n    OMD=OMEGA*D\n    OMDZERO=OMEGA*DZERO\n    !       RDVECSQ=1./(1.-ECCENT*COS(OMD))**2\n    RDVECSQ = 1.    ! no adjustment for orbital changes when coupled to HRLDAS...\n\n    ! Declination of sun...\n    LONGSUN=OMEGA*(D-Dzero)+2.*ECCENT*(SIN(OMD)-SIN(OMDZERO))\n    DECLIN=ASIN(SIN(DECMAX)*SIN(LONGSUN))\n    SDEC=SIN(DECLIN)\n    CDEC=COS(DECLIN)\n\n    ! Check for Polar Day/night...\n    ARG=((PI/2.)-ABS(DECLIN))/RTOD\n    IF(ABS(LAT).GT.ARG) THEN\n        IF((LAT.GT.0..AND.DECLIN.LT.0) .OR.       &\n                (LAT.LT.0..AND.DECLON.GT.0.)) THEN\n            OUT1 = 0.\n            OUT2 = 0.\n            OUT3 = 0.\n            RETURN\n        ENDIF\n        SR=-1.*PI\n    ELSE\n\n        ! Calculate sunrise hour angle...\n        SR=-1.*ABS(ACOS(-1.*TAN(LAT*RTOD)*TAN(DECLIN)))\n    END IF\n\n    ! Find standard meridian for site\n    STDMRDN=NINT(LONG/15.)*15.\n    LONGCOR=(LONG-STDMRDN)/15.\n\n    ! Compute time correction from equation of time...\n    B=2.*PI*(D-.4)/365\n    EM=0.\n    DO I=1,4\n        EM=EM+(BCOF(I)*SIN(I*B)+ACOF(I)*COS(I*B))\n    END DO\n\n    ! Compute time of solar noon...\n    TIMNOON=12.-EM-LONGCOR\n\n    ! Set up a few more terms...\n    AZSLO=AZ*RTOD\n    INSLO=IN*RTOD\n    SLAT=SIN(LAT*RTOD)\n    CLAT=COS(LAT*RTOD)\n    CAZ=COS(AZSLO)\n    SAZ=SIN(AZSLO)\n    SINC=SIN(INSLO)\n    CINC=COS(INSLO)\n\n    ! Begin solar radiation calculations...daily first, else instantaneous...\n    IF (DAILY) THEN   ! compute daily integrated values...(Not used in HRLDAS!)\n        IHR=0\n        MM=0\n        HINC=CALINT*ONEHR/60.\n        IK=(2.*ABS(SR)/HINC)+2.\n        FIRST=.TRUE.\n        OUT1=0.\n        DO I=1,IK\n            H=SR+HINC*FLOAT(I-1)\n            COSZ=SLAT*SDEC+CLAT*CDEC*COS(H)\n            COSBETA=CDEC*((SLAT*COS(H))*(-1.*CAZ*SINC)- &\n                SIN(H)*(SAZ*SINC)+(CLAT*COS(H))*CINC)+ &\n                SDEC*(CLAT*(CAZ*SINC)+SLAT*CINC)\n            EXTRA=SC*RDVECSQ*COSZ\n            IF(EXTRA.LE.0.) EXTRA=0.\n            EXTSLO=SC*RDVECSQ*COSBETA\n            IF(EXTRA.LE.0. .OR. EXTSLO.LT.0.) EXTSLO=0.\n            IF(FIRST .AND. EXTSLO.GT.0.) THEN\n                OUT2=(H-HINC)/ONEHR+TIMNOON\n                FIRST = .FALSE.\n            END IF\n            IF(.NOT.FIRST .AND. EXTSLO.LE.0.) OUT3=H/ONEHR+TIMNOON\n            OUT1=EXTSLO+OUT1\n        END DO\n        OUT1=OUT1*CALINT*60./1000000.\n\n    ELSE   ! Compute instantaneous values...(Is used in HRLDAS!)\n\n        T1=FLOAT(IHR)+FLOAT(MM)/60.\n        H=ONEHR*(T1-TIMNOON)\n        COSZ=SLAT*SDEC+CLAT*CDEC*COS(H)\n\n        ! Assuming HRLDAS forcing already accounts for season, time of day etc,\n        ! subtract out the component of adjustment that would occur for\n        ! a flat surface, this should leave only the sloped component remaining\n\n        COSBETA=CDEC*((SLAT*COS(H))*(-1.*CAZ*SINC)-  &\n            SIN(H)*(SAZ*SINC)+(CLAT*COS(H))*CINC)+ &\n            SDEC*(CLAT*(CAZ*SINC)+SLAT*CINC)\n\n        COSBETA_FLAT=CDEC*CLAT*COS(H)+SDEC*SLAT\n\n        INCADJ = COSBETA+(1-COSBETA_FLAT)\n\n        EXTRA=SC*RDVECSQ*COSZ\n        IF(EXTRA.LE.0.) EXTRA=0.\n        EXTSLO=SC*RDVECSQ*INCADJ\n        !         IF(EXTRA.LE.0. .OR. EXTSLO.LT.0.) EXTSLO=0.  !remove check for HRLDAS.\n        OUT1=EXTSLO\n        Z=ACOS(COSZ)\n        COSA=(SLAT*COSZ-SDEC)/(CLAT*SIN(Z))\n        IF(COSA.LT.-1.) COSA=-1.\n        IF(COSA.GT.1.) COSA=1.\n        A=ABS(ACOS(COSA))\n        IF(H.LT.0.) A=-A\n        OUT2=Z/RTOD\n        OUT3=A/RTOD+180\n\n    END IF    ! End if for daily vs instantaneous values...\n\n    !DJG-----------------------------------------------------------------------\nEND SUBROUTINE SOLSUB\n!DJG-----------------------------------------------------------------------\n\nsubroutine seq_land_SO8(SO8LD_D,Vmax,TERR,dx,ix,jx)\n    implicit none\n    integer :: ix,jx,i,j\n    REAL, DIMENSION(IX,JX,8)      :: SO8LD\n    INTEGER, DIMENSION(IX,JX,3)   :: SO8LD_D\n    real,DIMENSION(IX,JX)      :: TERR\n    real                       :: dx(ix,jx,9),Vmax(ix,jx)\n    SO8LD_D = -1\n    do j = 2, jx -1\n        do i = 2, ix -1\n            SO8LD(i,j,1) = (TERR(i,j)-TERR(i,j+1))/dx(i,j,1)\n            SO8LD_D(i,j,1) = i\n            SO8LD_D(i,j,2) = j + 1\n            SO8LD_D(i,j,3) = 1\n            Vmax(i,j) = SO8LD(i,j,1)\n\n            SO8LD(i,j,2) = (TERR(i,j)-TERR(i+1,j+1))/DX(i,j,2)\n            if(SO8LD(i,j,2) .gt. Vmax(i,j) ) then\n                SO8LD_D(i,j,1) = i + 1\n                SO8LD_D(i,j,2) = j + 1\n                SO8LD_D(i,j,3) = 2\n                Vmax(i,j) = SO8LD(i,j,2)\n            end if\n            SO8LD(i,j,3) = (TERR(i,j)-TERR(i+1,j))/DX(i,j,3)\n            if(SO8LD(i,j,3) .gt. Vmax(i,j) ) then\n                SO8LD_D(i,j,1) = i + 1\n                SO8LD_D(i,j,2) = j\n                SO8LD_D(i,j,3) = 3\n                Vmax(i,j) = SO8LD(i,j,3)\n            end if\n            SO8LD(i,j,4) = (TERR(i,j)-TERR(i+1,j-1))/DX(i,j,4)\n            if(SO8LD(i,j,4) .gt. Vmax(i,j) ) then\n                SO8LD_D(i,j,1) = i + 1\n                SO8LD_D(i,j,2) = j - 1\n                SO8LD_D(i,j,3) = 4\n                Vmax(i,j) = SO8LD(i,j,4)\n            end if\n            SO8LD(i,j,5) = (TERR(i,j)-TERR(i,j-1))/DX(i,j,5)\n            if(SO8LD(i,j,5) .gt. Vmax(i,j) ) then\n                SO8LD_D(i,j,1) = i\n                SO8LD_D(i,j,2) = j - 1\n                SO8LD_D(i,j,3) = 5\n                Vmax(i,j) = SO8LD(i,j,5)\n            end if\n            SO8LD(i,j,6) = (TERR(i,j)-TERR(i-1,j-1))/DX(i,j,6)\n            if(SO8LD(i,j,6) .gt. Vmax(i,j) ) then\n                SO8LD_D(i,j,1) = i - 1\n                SO8LD_D(i,j,2) = j - 1\n                SO8LD_D(i,j,3) = 6\n                Vmax(i,j) = SO8LD(i,j,6)\n            end if\n            SO8LD(i,j,7) = (TERR(i,j)-TERR(i-1,j))/DX(i,j,7)\n            if(SO8LD(i,j,7) .gt. Vmax(i,j) ) then\n                SO8LD_D(i,j,1) = i - 1\n                SO8LD_D(i,j,2) = j\n                SO8LD_D(i,j,3) = 7\n                Vmax(i,j) = SO8LD(i,j,7)\n            end if\n            SO8LD(i,j,8) = (TERR(i,j)-TERR(i-1,j+1))/DX(i,j,8)\n            if(SO8LD(i,j,8) .gt. Vmax(i,j) ) then\n                SO8LD_D(i,j,1) = i - 1\n                SO8LD_D(i,j,2) = j + 1\n                SO8LD_D(i,j,3) = 8\n                Vmax(i,j) = SO8LD(i,j,8)\n            end if\n        enddo\n    enddo\n    Vmax = TANH(Vmax)\nend  subroutine seq_land_SO8\n\n#ifdef MPP_LAND\nsubroutine MPP_seq_land_SO8(SO8LD_D,Vmax,TERRAIN,dx,ix,jx,&\n        global_nx,global_ny)\n\n    use module_mpp_land, only:  my_id, io_id, &\n        write_io_real,decompose_data_int,decompose_data_real\n\n    implicit none\n    integer,intent(in) :: ix,jx,global_nx,global_ny\n    INTEGER, intent(inout),DIMENSION(IX,JX,3)   :: SO8LD_D\n    !         real,intent(in), DIMENSION(IX,JX)   :: TERRAIN\n    real,DIMENSION(IX,JX)   :: TERRAIN\n    real,intent(out),dimension(ix,jx) ::  Vmax\n    real,intent(in)                     :: dx(ix,jx,9)\n    real                     :: g_dx(ix,jx,9)\n\n    real,DIMENSION(global_nx,global_ny)      :: g_TERRAIN\n    real,DIMENSION(global_nx,global_ny)      :: g_Vmax\n    integer,DIMENSION(global_nx,global_ny,3)      :: g_SO8LD_D\n    integer :: k\n\n    g_SO8LD_D = 0\n    g_Vmax    = 0\n\n    do k = 1, 9\n        call write_IO_real(dx(:,:,k),g_dx(:,:,k))\n    end do\n\n    call write_IO_real(TERRAIN,g_TERRAIN)\n    if(my_id .eq. IO_id) then\n        call seq_land_SO8(g_SO8LD_D,g_Vmax,g_TERRAIN,g_dx,global_nx,global_ny)\n    endif\n    call decompose_data_int(g_SO8LD_D(:,:,3),SO8LD_D(:,:,3))\n    call decompose_data_real(g_Vmax,Vmax)\nend subroutine MPP_seq_land_SO8\n\n#endif\n\n\nsubroutine disaggregateDomain_drv(did)\n   use module_RT_data, only: rt_domain\n   use config_base, only: nlst, noah_lsm\n   integer :: did\n   call disaggregateDomain( RT_DOMAIN(did)%IX, RT_DOMAIN(did)%JX, nlst(did)%NSOIL, &\n                            RT_DOMAIN(did)%IXRT, RT_DOMAIN(did)%JXRT, nlst(did)%AGGFACTRT, &\n                            RT_DOMAIN(did)%SICE, RT_DOMAIN(did)%SMC, RT_DOMAIN(did)%SH2OX, &\n                            RT_DOMAIN(did)%INFXSRT, rt_domain(did)%dist_lsm(:,:,9), &\n                            RT_DOMAIN(did)%SMCMAX1, RT_DOMAIN(did)%SMCREF1, &\n                            RT_DOMAIN(did)%SMCWLT1, RT_DOMAIN(did)%VEGTYP, RT_DOMAIN(did)%LKSAT, &\n                            RT_DOMAIN(did)%NEXP, &\n                            rt_domain(did)%overland%properties%distance_to_neighbor, &\n                            RT_DOMAIN(did)%INFXSWGT, &\n                            RT_DOMAIN(did)%LKSATFAC, &\n                            rt_domain(did)%overland%streams_and_lakes%ch_netrt, &\n                            RT_DOMAIN(did)%SH2OWGT, &\n                            RT_DOMAIN(did)%subsurface%grid_transform%smcrefrt, &\n                            rt_domain(did)%overland%control%infiltration_excess, &\n                            RT_DOMAIN(did)%subsurface%grid_transform%smcmaxrt, &\n                            RT_DOMAIN(did)%subsurface%grid_transform%smcwltrt, &\n                            rt_domain(did)%subsurface%grid_transform%smcrt, &\n                            rt_domain(did)%overland%streams_and_lakes%lake_mask, &\n                            rt_domain(did)%subsurface%properties%lksatrt, &\n                            rt_domain(did)%subsurface%properties%nexprt, &\n                            RT_DOMAIN(did)%subsurface%properties%sldpth, &\n                            RT_DOMAIN(did)%soiltypRT, RT_DOMAIN(did)%soiltyp, &\n                            rt_domain(did)%ELRT, RT_DOMAIN(did)%iswater, &\n                            rt_domain(did)%IMPERVFRAC, nlst(did)%imperv_adj)\nend subroutine disaggregateDomain_drv\n\n!===================================================================================================\n! Subroutine Name:\n!   subroutine disaggregateDomain\n! Author(s)/Contact(s):\n!   D. Gochis and W. Yu <gochis><ucar><edu>\n! Abstract:\n!   Disaggregates states and parameters from coarse grid to fine grid\n! History Log:\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\n!===================================================================================================\nsubroutine disaggregateDomain(IX, JX, NSOIL, IXRT, JXRT, AGGFACTRT, &\n                              SICE, SMC, SH2OX, INFXSRT, area_lsm, SMCMAX1, SMCREF1, &\n                              SMCWLT1, VEGTYP, LKSAT, NEXP, dist, INFXSWGT, &\n                              LKSATFAC, CH_NETRT, SH2OWGT, SMCREFRT, INFXSUBRT, SMCMAXRT, &\n                              SMCWLTRT, SMCRT, LAKE_MSKRT, LKSATRT, NEXPRT,  &\n                              SLDPTH, soiltypRT, soiltyp, elrt, iswater, impervfrac, imperv_adj)\n#ifdef MPP_LAND\n   use module_mpp_land, only: left_id,down_id,right_id, &\n                              up_id,mpp_land_com_real, my_id, io_id, numprocs, &\n                              mpp_land_sync,mpp_land_com_integer,mpp_land_max_int1, &\n                              sum_real1\n   use module_hydro_stop, only:HYDRO_stop\n#endif\n\n   implicit none\n\n   ! Input Variables ------------------------------------------------------------------------\n   ! General geometry/domain info:\n   integer, intent(in)                           :: IX,JX ! coarse grid i,j dims\n   integer, intent(in)                           :: IXRT,JXRT ! fine grid i,j dims\n   integer, intent(in)                           :: AGGFACTRT ! aggregation factor between grids\n   integer, intent(in)                           :: NSOIL ! number of soil layers\n   integer, intent(in)                           :: iswater ! water veg class (from geogrid attrib)\n   real, intent(in), dimension(NSOIL)            :: SLDPTH ! array soil layer depth intervals (m)\n   integer, intent(in)                           :: imperv_adj ! impervious configuration option from hydro.namelist\n   ! LSM grid parameters:\n   real, intent(in),  dimension(IX,JX)           :: area_lsm ! cell area on the coarse grid (m2)\n   integer, intent(in), dimension(IX,JX)         :: VEGTYP, soiltyp ! coarse grid veg and soil types\n   real, intent(in),  dimension(IX,JX)           :: SMCMAX1 ! coarse grid porosity\n   real, intent(in),  dimension(IX,JX)           :: SMCREF1 ! coarse grid field capacity\n   real, intent(in),  dimension(IX,JX)           :: SMCWLT1 ! coarse grid wilting point\n   real, intent(in),  dimension(IX,JX)           :: LKSAT ! coarse grid lateral ksat (m/s)\n   real, intent(in),  dimension(IX,JX)           :: NEXP ! coarse grid n exponent\n   ! LSM states:\n   real, intent(in),  dimension(IX,JX,NSOIL)     :: SMC ! total soil moisture (m3/m3)\n   real, intent(in),  dimension(IX,JX,NSOIL)     :: SH2OX ! liquid soil moisture (m3/m3)\n   real, intent(in),  dimension(IX,JX)           :: INFXSRT\n                                                    ! infiltration excess on coarse grid (mm)\n   ! Routing grid parameters:\n   real, intent(in), dimension(IXRT,JXRT,9)      :: dist\n                                                    ! routing grid cell distances (m) and area (m2)\n                                                    ! TODO: can we just pass in area since we don't need other distances?\n   real, intent(in), dimension(IXRT,JXRT)        :: LKSATFAC ! lateral ksat adj factor\n   real, intent(in), dimension(IXRT,JXRT)        :: elrt ! elevation grid (m)\n   integer, intent(in), dimension(IXRT,JXRT)     :: CH_NETRT ! channel network routing grid\n   real, intent(in), dimension(IXRT,JXRT)        :: impervfrac ! impervious fraction\n   ! Routing states:\n   real, intent(in), dimension(IXRT,JXRT)        :: INFXSWGT ! infiltration excess weighting grid\n   real, intent(in), dimension(IXRT,JXRT,NSOIL)  :: SH2OWGT ! soil moisture weighting grid\n\n   ! Update Variables ------------------------------------------------------------------------\n   integer, intent(inout), dimension(IXRT,JXRT)  :: LAKE_MSKRT ! lake mask on the routing grid\n\n   ! Output Variables ------------------------------------------------------------------------\n   ! Parameters:\n   integer, intent(out), dimension(IXRT,JXRT)    :: soiltypRT ! soil type on the routing grid\n   real, intent(out), dimension(IXRT,JXRT,NSOIL) :: SMCMAXRT ! porosity on routing grid\n   real, intent(out), dimension(IXRT,JXRT,NSOIL) :: SMCREFRT ! field capacity on routing grid\n   real, intent(out), dimension(IXRT,JXRT,NSOIL) :: SMCWLTRT ! wilting point on routing grid\n   real, intent(out), dimension(IXRT,JXRT)       :: LKSATRT ! lateral ksat on the routing grid (m/s)\n   real, intent(out), dimension(IXRT,JXRT)       :: NEXPRT ! n exponent on the routing grid\n   ! States:\n   real, intent(out), dimension(IX,JX,NSOIL)     :: SICE ! soil ice content on coarse grid (m3/m3)\n   real, intent(out), dimension(IXRT,JXRT,NSOIL) :: SMCRT\n                                                    ! soil moisture contant on routing grid (m3/m3)\n   real, intent(out), dimension(IXRT,JXRT)       :: INFXSUBRT\n                                                    ! infiltration excess on routing grid (mm)\n\n   ! Local Variables ------------------------------------------------------------------------\n   integer                    :: i, j ! coarse grid loop indices\n   integer                    :: AGGFACYRT, AGGFACXRT ! fine grid aggregation factors\n   integer                    :: IXXRT, JYYRT ! fine grid i,j coordinates\n   integer                    :: KRT, KF ! soil layer loop indixes\n   real                       :: LSMVOL ! total infiltration excess volume per LSM cell (mm * m2)\n   real                       :: SMCEXCS ! excess soil moisture (m3/m3)\n   real                       :: WATHOLDCAP ! water holding capacity, smcmax - smcwlt (m3/m3)\n   real                       :: smScaleFact ! soil moisture scaling factor for ksat (0-1)\n   real, dimension(IXRT,JXRT) :: OCEAN_INFXSUBRT\n                                 ! dummy variable to dump infiltration excess over ocean cells\n#ifdef HYDRO_D\n   ! For water budget calcs\n   integer :: ii, jj, kk ! local loop indices\n   real    :: smctot1,smcrttot2 ! total soil moisture, start and finish\n   real    :: sicetot1 ! total ice, start and finish\n   real    :: suminfxs1,suminfxsrt2 ! total infiltration excess, start and finish\n#endif\n\n   ! Initialize variables\n   SICE = SMC - SH2OX\n   SMCREFRT = 0.0\n   ! ADCHANGE: Initialize ocean infxsubrt var to 0. Currently just a dump\n   ! variable but could be used for future ocean model coupling\n   OCEAN_INFXSUBRT = 0.0\n\n   !DJG First, Disaggregate a few key fields for routing...\n   !DJG Debug...\n#ifdef HYDRO_D\n   print *, \"Beginning Disaggregation...\"\n#endif\n\n   !DJG Mass balance check for disagg...\n#ifdef HYDRO_D\n   ! ADCHANGE: START Initial water balance variables\n   ! ALL VARS in MM\n   suminfxs1 = 0.\n   smctot1 = 0.\n   sicetot1 = 0.\n   do ii=1,IX\n      do jj=1,JX\n         suminfxs1 = suminfxs1 + INFXSRT(ii,jj) / float(IX*JX)\n         do kk=1,NSOIL\n            smctot1 = smctot1 + SMC(ii,jj,kk)*SLDPTH(kk)*1000. / float(IX*JX)\n            sicetot1 = sicetot1 + SICE(ii,jj,kk)*SLDPTH(kk)*1000. / float(IX*JX)\n         end do\n      end do\n   end do\n#ifdef MPP_LAND\n   ! not tested\n   CALL sum_real1(suminfxs1)\n   CALL sum_real1(smctot1)\n   CALL sum_real1(sicetot1)\n   suminfxs1 = suminfxs1/float(numprocs)\n   smctot1 = smctot1/float(numprocs)\n   sicetot1 = sicetot1/float(numprocs)\n#endif\n   ! END Initial water balance variables\n#endif\n\n   !DJG Weighting alg. alteration...(prescribe wghts if time = 1)\n\n   do J=1,JX ! Start coarse grid j loop\n      do I=1,IX ! Start coarse grid i loop\n\n         !DJG Weighting alg. alteration...\n         LSMVOL = INFXSRT(I,J) * area_lsm(I,J) ! mm * m2\n\n         do AGGFACYRT=AGGFACTRT-1,0,-1 ! Start disagg fine grid j loop\n            do AGGFACXRT=AGGFACTRT-1,0,-1 ! Start disagg fine grid i loop\n\n               IXXRT = I * AGGFACTRT - AGGFACXRT ! Define fine grid i\n               JYYRT = J * AGGFACTRT - AGGFACYRT ! Define fine grid j\n#ifdef MPP_LAND\n               if(left_id.ge.0) IXXRT = IXXRT+1\n               if(down_id.ge.0) JYYRT = JYYRT+1\n#endif\n               ! Initial redistribution of total coarse grid cell infiltration excess\n               ! based on subgrid weight factor and current volume of water (mm * m2 / m2 = mm)\n               INFXSUBRT(IXXRT,JYYRT) = LSMVOL *     &\n                                        INFXSWGT(IXXRT,JYYRT) / dist(IXXRT,JYYRT,9)\n\n               do KRT=1,NSOIL ! Soil layer loop\n\n                  ! Adjustments for soil ice\n                  IF (SICE(I,J,KRT) .gt. 0) then\n                     !DJG Adjust SMCMAX for SICE when subsfc routing...make 3d variable\n                     SMCMAXRT(IXXRT,JYYRT,KRT) = SMCMAX1(I,J) - SICE(I,J,KRT)\n                     SMCREFRT(IXXRT,JYYRT,KRT) = SMCREF1(I,J) - SICE(I,J,KRT) !TODO: This can be negative! e.g., when almost saturated and fully frozen\n                     WATHOLDCAP = SMCMAX1(I,J) - SMCWLT1(I,J)\n                     IF (SICE(I,J,KRT) .le. WATHOLDCAP)    then\n                        SMCWLTRT(IXXRT,JYYRT,KRT) = SMCWLT1(I,J)\n                     else\n                        if (SICE(I,J,KRT) .lt. SMCMAX1(I,J)) then\n                           SMCWLTRT(IXXRT,JYYRT,KRT) = SMCWLT1(I,J) - &\n                                                       (SICE(I,J,KRT) - WATHOLDCAP)\n                        endif\n                        if (SICE(I,J,KRT) .ge. SMCMAX1(I,J)) then\n                           SMCWLTRT(IXXRT,JYYRT,KRT) = 0.\n                        endif\n                     endif\n                  ELSE ! no ice\n                     SMCMAXRT(IXXRT,JYYRT,KRT) = SMCMAX1(I,J)\n                     SMCREFRT(IXXRT,JYYRT,KRT) = SMCREF1(I,J)\n                     WATHOLDCAP = SMCMAX1(I,J) - SMCWLT1(I,J) !TODO: Not used again so can delete\n                     SMCWLTRT(IXXRT,JYYRT,KRT) = SMCWLT1(I,J)\n                  ENDIF   ! endif adjust for soil ice\n\n                  !Now Adjust soil moisture\n                  !DJG Use SH2O instead of SMC for 'liquid' water...\n                  IF (SMCMAXRT(IXXRT,JYYRT,KRT) .GT. 0) THEN !Check for smcmax data (=0 over water)\n                     SMCRT(IXXRT,JYYRT,KRT) = SH2OX(I,J,KRT) * SH2OWGT(IXXRT,JYYRT,KRT)\n                     !old SMCRT(IXXRT,JYYRT,KRT)=SMC(I,J,KRT)\n                  ELSE\n                     !TODO: Double-check the values for water cells\n                     SMCRT(IXXRT,JYYRT,KRT) = 0.001  !will be skipped w/ landmask\n                     SMCMAXRT(IXXRT,JYYRT,KRT) = 0.001\n                  END IF\n\n                  !DJG Check/Adjust so that subgrid cells do not exceed saturation...\n                  IF (SMCRT(IXXRT,JYYRT,KRT) .GT. SMCMAXRT(IXXRT,JYYRT,KRT)) THEN\n                     SMCEXCS = (SMCRT(IXXRT,JYYRT,KRT) - SMCMAXRT(IXXRT,JYYRT,KRT)) &\n                               * SLDPTH(KRT) * 1000.  !Excess soil water in units of (mm)\n                     SMCRT(IXXRT,JYYRT,KRT) = SMCMAXRT(IXXRT,JYYRT,KRT)\n                     DO KF = KRT-1,1,-1  !loop back upward to redistribute excess water from disagg.\n                        SMCRT(IXXRT,JYYRT,KF) = SMCRT(IXXRT,JYYRT,KF) + SMCEXCS/(SLDPTH(KF)*1000.)\n                        !Recheck new lyr sat.\n                        IF (SMCRT(IXXRT,JYYRT,KF) .GT. SMCMAXRT(IXXRT,JYYRT,KF)) THEN\n                           SMCEXCS = (SMCRT(IXXRT,JYYRT,KF) - SMCMAXRT(IXXRT,JYYRT,KF)) &\n                                     * SLDPTH(KF) * 1000.  !Excess soil water in units of (mm)\n                           SMCRT(IXXRT,JYYRT,KF) = SMCMAXRT(IXXRT,JYYRT,KF)\n                        ELSE  ! Excess soil water expired\n                           SMCEXCS = 0.\n                           EXIT\n                        END IF\n                     END DO\n                     IF (SMCEXCS .GT. 0) THEN  !If not expired by sfc then add to Infil. Excess\n                        INFXSUBRT(IXXRT,JYYRT) = INFXSUBRT(IXXRT,JYYRT) + SMCEXCS\n                        SMCEXCS = 0.\n                     END IF\n                  END IF  !End if for soil moisture saturation excess\n\n               end do !End do for soil profile loop\n\n               ! Debug loop\n               do KRT=1,NSOIL\n                  IF (SMCRT(IXXRT,JYYRT,KRT) .GT. SMCMAXRT(IXXRT,JYYRT,KRT)) THEN\n                     print *, \"FATAL ERROR: SMCMAX exceeded upon disaggregation3...\", &\n                              ixxrt, jyyrt, krt, &\n                              SMCRT(IXXRT,JYYRT,KRT),SMCMAXRT(IXXRT,JYYRT,KRT)\n                     call hydro_stop(\"In disaggregateDomain() - SMCMAX exceeded upon disaggregation3\")\n                  ELSE IF (SMCRT(IXXRT,JYYRT,KRT).LE.0.) THEN\n                     print *, \"SMCRT fully depleted upon disaggregation...\", &\n                         ixxrt,jyyrt,krt,&\n                         \"SMCRT=\",SMCRT(IXXRT,JYYRT,KRT),\"SH2OWGT=\",SH2OWGT(IXXRT,JYYRT,KRT),&\n                         \"SH2O=\",SH2OX(I,J,KRT)\n                     print*, \"SMC=\", SMC(i,j,KRT), \"SICE =\", sice(i,j,KRT)\n                     print *, \"VEGTYP = \", VEGTYP(I,J)\n                     print *, \"i,j,krt, nsoil\",i,j,krt,nsoil\n                     ! ADCHANGE: If values are close but not exact, end up with a crash.\n                     ! Force values to match.\n                     !IF (SMC(i,j,KRT).EQ.sice(i,j,KRT)) THEN\n                     IF (ABS(SMC(i,j,KRT) - sice(i,j,KRT)) .LE. 0.00001) THEN\n                        print *, \"SMC = SICE, soil layer totally frozen, proceeding...\"\n                        SMCRT(IXXRT,JYYRT,KRT) = 0.001\n                        sice(i,j,KRT) = SMC(i,j,KRT)\n                     ELSE\n                        call hydro_stop(\"In disaggregateDomain() - SMCRT depleted\")\n                     END IF\n                  END IF\n               end do !debug loop\n\n               ! Now do simple grid remapping tasks\n\n               ! Lateral ksat\n               !DJG 6.12.08 Map lateral hydraulic conductivity and apply distributed scaling\n               ! ---        factor that will be read in from hires terrain file\n               !              LKSATRT(IXXRT,JYYRT) = LKSAT(I,J) * LKSATFAC(IXXRT,JYYRT) * &  !Apply scaling factor...\n               ! ...and scale from max to 0 when SMC decreases from SMCMAX to SMCREF...\n               !!DJG error found from KIT,improper scaling       ((SMCMAXRT(IXXRT,JYYRT,NSOIL) - SMCRT(IXXRT,JYYRT,NSOIL)) / &\n               !                                    (max(0.,(SMCMAXRT(IXXRT,JYYRT,NSOIL) - SMCRT(IXXRT,JYYRT,NSOIL))) / &\n               !                                    (SMCMAXRT(IXXRT,JYYRT,NSOIL)-SMCREFRT(IXXRT,JYYRT,NSOIL)) )\n               ! AD_CHANGE:\n               ! Corrected to scale from 0 at SMCREF to full LKSAT*LKSATFAC at SMCMAX.\n               ! This is a linear simplification of the true k to smc relationship to cover the\n               ! range of conditions between smcmax and smcref. The DHSVM lateral routing\n               ! scheme assumes saturated conditions (and therfore ksat), but we are extending\n               ! that slightly to route water up until smcref.\n               smScaleFact = (SMCRT(IXXRT,JYYRT,NSOIL) - SMCREFRT(IXXRT,JYYRT,NSOIL)) / &\n                                (SMCMAXRT(IXXRT,JYYRT,NSOIL) - SMCREFRT(IXXRT,JYYRT, NSOIL))\n               smScaleFact = max(0., smScaleFact) !becomes 0 if less than SMCREF\n               smScaleFact = min(1., smScaleFact) !make sure scale factor doesn't go over 1\n               LKSATRT(IXXRT,JYYRT) = LKSAT(I,J) * LKSATFAC(IXXRT,JYYRT) * smScaleFact\n\n               ! n exponent for subsurface routing\n               nexprt(ixxrt,jyyrt) = nexp(i,j)\n\n               ! Lake mask\n               !DJG set up lake mask...\n               !--- modify to make lake mask large here, but not one of the routed lakes!!!\n               !--            IF (VEGTYP(I,J).eq.16) then\n               IF (VEGTYP(I,J) .eq. iswater .and. CH_NETRT(IXXRT,JYYRT).le.0) then\n                  !--LAKE_MSKRT(IXXRT,JYYRT) = 1\n                  !yw  LAKE_MSKRT(IXXRT,JYYRT) = 9999\n                  LAKE_MSKRT(IXXRT,JYYRT) = -9999\n               end if\n\n               ! Soil type\n               ! BF disaggregate soiltype information for gw-soil-coupling\n               ! TODO: move this disaggregation code line to lsm_init section because soiltype is time-invariant\n               soiltypRT(ixxrt,jyyrt) = soiltyp(i,j)\n\n            end do ! end disagg fine grid i loop\n         end do ! end disagg fine grid j loop\n\n      end do ! end coarse grid i loop\n   end do ! end coarse fine grid j loop\n\n   ! AD: Add new zeroing out of -9999 elevation cells which are ocean\n   where (ELRT .lt. -9998)\n      OCEAN_INFXSUBRT = INFXSUBRT\n      INFXSUBRT = 0.0\n   endwhere\n\n#ifdef HYDRO_D\n   ! ADCHANGE: START Final water balance variables\n   ! ALL VARS in MM\n   suminfxsrt2 = 0.\n   smcrttot2 = 0.\n   do ii=1,IXRT\n      do jj=1,JXRT\n         suminfxsrt2 = suminfxsrt2 + INFXSUBRT(ii,jj) / float(IXRT*JXRT)\n         do kk=1,NSOIL\n            smcrttot2 = smcrttot2 + SMCRT(ii,jj,kk)*SLDPTH(kk)*1000. / float(IXRT*JXRT)\n         end do\n      end do\n   end do\n#ifdef MPP_LAND\n   ! not tested\n   CALL sum_real1(suminfxsrt2)\n   CALL sum_real1(smcrttot2)\n   suminfxsrt2 = suminfxsrt2/float(numprocs)\n   smcrttot2 = smcrttot2/float(numprocs)\n#endif\n#ifdef MPP_LAND\n   if (my_id .eq. IO_id) then\n#endif\n      print *, \"Disagg Mass Bal: \"\n      print *, \"WB_DISAG!InfxsDiff\", suminfxsrt2-suminfxs1\n      print *, \"WB_DISAG!Infxs1\", suminfxs1\n      print *, \"WB_DISAG!Infxs2\", suminfxsrt2\n      print *, \"WB_DISAG!SMCDIff\", smcrttot2-(smctot1-sicetot1)\n      print *, \"WB_DISAG!SMC1\", smctot1\n      print *, \"WB_DISAG!SICE1\", sicetot1\n      print *, \"WB_DISAG!SMC2\", smcrttot2\n      print *, \"WB_DISAG!Residual\", (suminfxsrt2-suminfxs1) + (smcrttot2-(smctot1-sicetot1))\n#ifdef MPP_LAND\n   endif\n#endif\n   ! END Final water balance variables\n#endif\n\n#ifdef HYDRO_D\n   print *, \"After Disaggregation...\"\n#endif\n#ifdef MPP_LAND\n   call MPP_LAND_COM_REAL(INFXSUBRT,IXRT,JXRT,99)\n   call MPP_LAND_COM_REAL(LKSATRT,IXRT,JXRT,99)\n   call MPP_LAND_COM_REAL(NEXPRT,IXRT,JXRT,99)\n   call MPP_LAND_COM_INTEGER(LAKE_MSKRT,IXRT,JXRT,99)\n   do i = 1, NSOIL\n      call MPP_LAND_COM_REAL(SMCMAXRT(:,:,i),IXRT,JXRT,99)\n      call MPP_LAND_COM_REAL(SMCRT(:,:,i),IXRT,JXRT,99)\n      call MPP_LAND_COM_REAL(SMCWLTRT(:,:,i),IXRT,JXRT,99)\n   end DO\n#endif\n\nend subroutine disaggregateDomain\n!===================================================================================================\n\n\nsubroutine SubsurfaceRouting_drv(did)\n\n    use module_RT_data, only: rt_domain\n    use config_base, only: nlst\n\n    implicit none\n    integer :: did\n    IF (nlst(did)%SUBRTSWCRT.EQ.1) THEN\n        call subsurfaceRouting ( rt_domain(did)%subsurface, &\n            rt_domain(did)%subsurface_static, &\n            rt_domain(did)%subsurface_input, &\n            rt_domain(did)%subsurface_output, &\n            rt_domain(did)%overland%control%infiltration_excess)\n    endif\n\nend subroutine SubsurfaceRouting_drv\n\n\n\nsubroutine OverlandRouting_drv(did)\n    use module_RT_data, only: rt_domain\n    use config_base, only: nlst\n\n    implicit none\n    integer :: did\n    if(nlst(did)%OVRTSWCRT .eq. 1) then\n        !call OverlandRouting (nlst_rt(did)%DT, nlst_rt(did)%DTRT_TER, nlst_rt(did)%rt_option, &\n            !         rt_domain(did)%ixrt, rt_domain(did)%jxrt,rt_domain(did)%overland%streams_and_lakes%lake_mask, &\n            !         rt_domain(did)%overland%control%infiltration_excess, rt_domain(did)%overland%properties%retention_depth,rt_domain(did)%overland%properties%roughness, &\n            !         rt_domain(did)%overland%properties%surface_slope_x, rt_domain(did)%overland%properties%surface_slope_y, rt_domain(did)%overland%control%surface_water_head_routing,  &\n            !         rt_domain(did)%overland%control%dhrt, rt_domain(did)%overland%streams_and_lakes%ch_netrt, rt_domain(did)%overland%streams_and_lakes%surface_water_to_channel,&\n            !         rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake,rt_domain(did)%overland%control%boundary_flux, &\n            !         rt_domain(did)%overland%streams_and_lakes%accumulated_surface_water_to_channel,rt_domain(did)%overland%control%boundary_flux_total, rt_domain(did)%overland%streams_and_lakes%accumulated_surface_water_to_lake,&\n            !         rt_domain(did)%q_sfcflx_x,rt_domain(did)%q_sfcflx_y, &\n            !         rt_domain(did)%overland%properties%distance_to_neighbor, rt_domain(did)%overland%properties%surface_slope, rt_domain(did)%overland%properties%max_surface_slope_index , &\n            !         rt_domain(did)%overland%mass_balance%post_soil_moisture_content,rt_domain(did)%overland%mass_balance%pre_infiltration_excess,rt_domain(did)%overland%mass_balance%post_infiltration_excess, &\n            !         rt_domain(did)%overland%mass_balance%pre_soil_moisture_content,rt_domain(did)%overland%mass_balance%accumulated_change_in_soil_moisture )\n        call OverlandRouting( &\n            rt_domain(did)%overland, &\n            nlst(did)%DT, &\n            nlst(did)%DTRT_TER, &\n            nlst(did)%rt_option, &\n            rt_domain(did)%ixrt, &\n            rt_domain(did)%jxrt, &\n            rt_domain(did)%q_sfcflx_x, &\n            rt_domain(did)%q_sfcflx_y &\n            )\n        ! ADCHANGE: If overland routing is called, INFXSUBRT is moved to SFCHEADSUBRT, so\n        !           zeroing out just in case\n        rt_domain(did)%overland%control%infiltration_excess = 0.0\n    endif\nend subroutine OverlandRouting_drv\n\n\n\n\n\n\nsubroutine time_seconds(i3)\n    integer time_array(8)\n    real*8 i3\n    call date_and_time(values=time_array)\n    i3 = time_array(4)*24*3600+time_array(5) * 3600 + time_array(6) * 60 + &\n        time_array(7) + 0.001 * time_array(8)\nend subroutine time_seconds\n"
  },
  {
    "path": "src/Routing/Noah_distr_routing_overland.F90",
    "content": "!DJG ------------------------------------------------\n!DJG   SUBROUTINE OverlandRouting\n!DJG ------------------------------------------------\n\n!subroutine OverlandRouting (DT, DTRT_TER, rt_option, ixrt, jxrt,LAKE_MSKRT, &\n    !           INFXSUBRT, RETDEPRT,OVROUGHRT,SOXRT, SOYRT, SFCHEADSUBRT,DHRT, &\n    !           CH_NETRT, QSTRMVOLRT,LAKE_INFLORT,QBDRYRT, &\n    !           QSTRMVOLTRT,QBDRYTRT, LAKE_INFLOTRT, q_sfcflx_x,q_sfcflx_y, &\n    !           dist, SO8RT, SO8RT_D, &\n    !           SMCTOT2,suminfxs1,suminfxsrt,smctot1,dsmctot )\n\n\nsubroutine OverlandRouting( &\n    ovrt_data, & ! overland data structure\n    DT, &\n    DTRT_TER, &\n    rt_option, &\n    ixrt, &       ! routing grid x size\n    jxrt, &      ! routing grid y size\n    q_sfcflx_x, &! accumulated x flux\n    q_sfcflx_y  &! accumulated y flux\n    )\n#ifdef MPP_LAND\n    use module_mpp_land, only:  mpp_land_max_int1,  sum_real1, my_id, io_id, numprocs\n    use overland_data\n#endif\n    implicit none\n\n    type (overland_struct), intent(inout) :: ovrt_data\n    REAL, INTENT(IN) :: DT, DTRT_TER\n    integer, INTENT(IN) :: ixrt, jxrt, rt_option\n    !REAL, INTENT(out), DIMENSION(IXRT,JXRT)   :: SFCHEADSUBRT  ! moved into overland_data%control\n    real, dimension(IXRT,JXRT), intent(inout) :: q_sfcflx_x,q_sfcflx_y\n\n    ! REMOVED VARIABLES\n    !INTEGER, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: LAKE_MSKRT\n\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)   :: INFXSUBRT,  &\n        !          RETDEPRT,OVROUGHRT,SOXRT, SOYRT\n    !REAL, INTENT(OUT), DIMENSION(IXRT,JXRT) :: SFCHEADSUBRT,DHRT\n    !INTEGER, INTENT(IN), DIMENSION(IXRT,JXRT) :: CH_NETRT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: QSTRMVOLRT,LAKE_INFLORT,QBDRYRT, &\n        !         QSTRMVOLTRT,QBDRYTRT, LAKE_INFLOTRT, q_sfcflx_x,q_sfcflx_y\n\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT,9):: dist\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT,8)  :: SO8RT\n    !INTEGER SO8RT_D(IXRT,JXRT,3)\n\n    integer  :: i,j\n\n\n    !real            :: smctot2,smctot1,dsmctot\n    !real            :: suminfxsrt,suminfxs1\n    ! local variable\n    real            :: chan_in1,chan_in2\n    real            :: lake_in1,lake_in2\n    real            :: qbdry1,qbdry2\n    integer :: sfcrt_flag\n\n\n\n    !DJG Third, Call Overland Flow Routing Routine...\n#ifdef HYDRO_D\n    print *, \"Beginning OV_routing...\"\n    print *, \"Routing method is \",rt_option, \" direction.\"\n#endif\n\n    !DJG debug...OV Routing...\n    ovrt_data%mass_balance%pre_infiltration_excess = 0.\n    chan_in1=0.\n    lake_in1=0.\n    qbdry1=0.\n    do i=1,IXRT\n        do j=1,JXRT\n            ovrt_data%mass_balance%pre_infiltration_excess = &\n                ovrt_data%mass_balance%pre_infiltration_excess + ( ovrt_data%control%infiltration_excess(I,J)/float(IXRT*JXRT) )\n            chan_in1 = chan_in1 + ( ovrt_data%streams_and_lakes%surface_water_to_channel(I,J)/float(IXRT*JXRT) )\n            lake_in1 = lake_in1 + ( ovrt_data%streams_and_lakes%surface_water_to_lake(I,J)/float(IXRT*JXRT) )\n            qbdry1 = qbdry1 + ( ovrt_data%control%boundary_flux(I,J)/float(IXRT*JXRT) )\n        end do\n    end do\n\n#ifdef MPP_LAND\n    ! not tested\n    CALL sum_real1(ovrt_data%mass_balance%pre_infiltration_excess)\n    CALL sum_real1(chan_in1)\n    CALL sum_real1(lake_in1)\n    CALL sum_real1(qbdry1)\n    ovrt_data%mass_balance%pre_infiltration_excess = ovrt_data%mass_balance%pre_infiltration_excess/float(numprocs)\n    chan_in1 = chan_in1/float(numprocs)\n    lake_in1 = lake_in1/float(numprocs)\n    qbdry1 = qbdry1/float(numprocs)\n#endif\n\n\n    !DJG.7.20.2007 - Global check for infxs>retdep & skip if not...(set sfcrt_flag)\n    !DJG.7.20.2007 - this check will skip ov rtng when no flow is present...\n\n    sfcrt_flag = 0\n\n    do j=1,jxrt\n        do i=1,ixrt\n            if( ovrt_data%control%infiltration_excess(i,j) .gt. ovrt_data%properties%retention_depth(i,j) ) then\n                sfcrt_flag = 1\n                exit\n            end if\n        end do\n        if(sfcrt_flag .eq. 1) exit\n    end do\n\n#ifdef MPP_LAND\n    call mpp_land_max_int1(sfcrt_flag)\n#endif\n    !DJG.7.20.2007 - Global check for infxs>retdep & skip if not...(IF)\n\n    if (sfcrt_flag.eq.1) then  !If/then for sfc_rt check...\n#ifdef HYDRO_D\n        write(6,*) \"calling OV_RTNG \"\n#endif\n        CALL OV_RTNG(           &\n            ovrt_data, &\n            DT,                   &\n            DTRT_TER,             &\n            IXRT,                 &\n            JXRT,                 &\n            rt_option,            &\n            q_sfcflx_x,           &\n            q_sfcflx_y)\n    else\n        ovrt_data%control%surface_water_head_routing = ovrt_data%control%infiltration_excess\n#ifdef HYDRO_D\n        print *, \"No water to route overland...\"\n#endif\n    end if  !Endif for sfc_rt check...\n\n    !DJG.7.20.2007 - Global check for infxs>retdep & skip if not...(ENDIF)\n\n#ifdef HYDRO_D\n    print *, \"OV routing called and returned...\"\n#endif\n\n    !DJG Debug...OV Routing...\n    ovrt_data%mass_balance%post_infiltration_excess = 0.\n    chan_in2=0.\n    lake_in2=0.\n    qbdry2=0.\n    do i=1,IXRT\n        do j=1,JXRT\n            ovrt_data%mass_balance%post_infiltration_excess = &\n                ovrt_data%mass_balance%post_infiltration_excess + (ovrt_data%control%surface_water_head_routing(I,J)/float(IXRT*JXRT))\n            chan_in2=chan_in2 + (ovrt_data%streams_and_lakes%surface_water_to_channel(I,J)/float(IXRT*JXRT))\n            lake_in2=lake_in2 + (ovrt_data%streams_and_lakes%surface_water_to_lake(I,J)/float(IXRT*JXRT))\n            qbdry2=qbdry2 + (ovrt_data%control%boundary_flux(I,J)/float(IXRT*JXRT))\n        end do\n    end do\n#ifdef MPP_LAND\n    ! not tested\n    CALL sum_real1(ovrt_data%mass_balance%post_infiltration_excess)\n    CALL sum_real1(chan_in2)\n    CALL sum_real1(lake_in2)\n    CALL sum_real1(qbdry2)\n    ovrt_data%mass_balance%post_infiltration_excess = ovrt_data%mass_balance%post_infiltration_excess/float(numprocs)\n    chan_in2 = chan_in2/float(numprocs)\n    lake_in2 = lake_in2/float(numprocs)\n    qbdry2 = qbdry2/float(numprocs)\n#endif\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\n    if(my_id .eq. IO_id) then\n#endif\n        print *, \"OV Routing Mass Bal: \"\n        print *, \"WB_OV!InfxsDiff\", ovrt_data%mass_balance%post_infiltration_excess - ovrt_data%mass_balance%pre_infiltration_excess\n        print *, \"WB_OV!Infxs1\", ovrt_data%mass_balance%pre_infiltration_excess\n        print *, \"WB_OV!Infxs2\", ovrt_data%mass_balance%post_infiltration_excess\n        print *, \"WB_OV!ChaninDiff\", chan_in2-chan_in1\n        print *, \"WB_OV!Chanin1\", chan_in1\n        print *, \"WB_OV!Chanin2\", chan_in2\n        print *, \"WB_OV!LakeinDiff\", lake_in2-lake_in1\n        print *, \"WB_OV!Lakein1\", lake_in1\n        print *, \"WB_OV!Lakein2\", lake_in2\n        print *, \"WB_OV!QbdryDiff\", qbdry2-qbdry1\n        print *, \"WB_OV!Qbdry1\", qbdry1\n        print *, \"WB_OV!Qbdry2\", qbdry2\n        print *, \"WB_OV!Residual\", (ovrt_data%mass_balance%post_infiltration_excess - ovrt_data%mass_balance%pre_infiltration_excess)&\n            -(chan_in2-chan_in1) -(lake_in2 - lake_in1) - (qbdry2 - qbdry1)\n#ifdef MPP_LAND\n    endif\n#endif\n#endif\n\n\nend subroutine OverlandRouting\n\n!DJG ------------------------------------------------\n!DJG   SUBROUTINE OV_RTNG\n!DJG ------------------------------------------------\n\n!SUBROUTINE OV_RTNG(DT,DTRT_TER,IXRT,JXRT,INFXSUBRT,      &\n    !  SFCHEADSUBRT,DHRT,CH_NETRT,RETDEPRT,OVROUGHRT,      &\n    !  QSTRMVOLRT,QBDRYRT,QSTRMVOLTRT,QBDRYTRT,SOXRT,     &\n    !  SOYRT,dist,LAKE_MSKRT,LAKE_INFLORT,LAKE_INFLOTRT,  &\n    !  SO8RT,SO8RT_D,rt_option,q_sfcflx_x,q_sfcflx_y)\n\nsubroutine ov_rtng( &\n        ovrt_data, &\n        DT, &\n        DTRT_TER, &\n        IXRT, &\n        JXRT, &\n        rt_option, &\n        q_sfcflx_x, &\n        q_sfcflx_y &\n        )\n\n    !yyww\n#ifdef MPP_LAND\n    use module_mpp_land, only: left_id,down_id,right_id, &\n        up_id,mpp_land_com_real, my_id, &\n        mpp_land_sync\n#endif\n    use overland_data\n    IMPLICIT NONE\n\n    !DJG --------DECLARATIONS----------------------------\n\n    type (overland_struct), intent(inout) :: ovrt_data\n    INTEGER, INTENT(IN)\t\t\t:: IXRT,JXRT\n    REAL, INTENT(IN)\t\t\t:: DT,DTRT_TER\n    integer, intent(in) :: rt_option\n\n    !INTEGER, INTENT(IN), DIMENSION(IXRT,JXRT) :: CH_NETRT\n    !INTEGER, INTENT(IN), DIMENSION(IXRT,JXRT) :: LAKE_MSKRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)\t:: INFXSUBRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)\t:: SOXRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)\t:: SOYRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT,9):: dist\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT)\t:: RETDEPRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)\t:: OVROUGHRT\n\n    !REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)\t:: SFCHEADSUBRT\n    !REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)\t:: DHRT\n\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: QSTRMVOLRT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: LAKE_INFLORT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: QBDRYRT\n    REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: q_sfcflx_x,q_sfcflx_y\n    !REAL, INTENT(INOUT)     :: QSTRMVOLTRT,QBDRYTRT,LAKE_INFLOTRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT,8)  :: SO8RT\n\n    !DJG Local Variables\n\n    INTEGER :: KRT,I,J,ct\n\n    REAL, DIMENSION(IXRT,JXRT)\t:: INFXS_FRAC\n    REAL\t:: DT_FRAC,SUM_INFXS,sum_head\n    !INTEGER SO8RT_D(IXRT,JXRT,3), rt_option\n\n    !DJG ----------------------------------------------------------------------\n    ! DJG BEGIN 1-D or 2-D OVERLAND FLOW ROUTING LOOP\n    !DJG ---------------------------------------------------------------------\n    !DJG  Loop over 'routing time step'\n    !DJG  Compute the number of time steps based on NOAH DT and routing DTRT_TER\n\n    DT_FRAC=INT(DT/DTRT_TER)\n\n#ifdef HYDRO_D\n    write(6,*) \"OV_RTNG  DT_FRAC, DT, DTRT_TER\",DT_FRAC, DT, DTRT_TER\n    write(6,*) \"IXRT, JXRT = \",ixrt,jxrt\n#endif\n\n    !DJG NOTE: Applying all infiltration excess water at once then routing\n    !DJG       Pre-existing SFHEAD gets combined with Precip. in the\n    !DJG       calculation of INFXS1 during subroutine SRT.f.\n    !DJG debug\n\n\n    !DJG Assign all infiltration excess to surface head...\n    ovrt_data%control%surface_water_head_routing=ovrt_data%control%infiltration_excess\n\n    !DJG Divide infiltration excess over all routing time-steps\n    !\t     INFXS_FRAC=INFXSUBRT/(DT/DTRT_TER)\n\n    !DJG Set flux accumulation fields to 0. before each loop...\n    q_sfcflx_x = 0.\n    q_sfcflx_y = 0.\n    ct =0\n\n\n    !DJG Execute routing time-step loop...\n\n\n    DO KRT=1,DT_FRAC\n\n        DO J=1,JXRT\n            DO I=1,IXRT\n\n                !DJG Removed 4_29_05, sfhead now updated in route_overland subroutine...\n                !           SFCHEADSUBRT(I,J)=SFCHEADSUBRT(I,J)+DHRT(I,J)\n                !!           SFCHEADSUBRT(I,J)=SFCHEADSUBRT(I,J)+DHRT(I,J)+INFXS_FRAC(I,J)\n                !           DHRT(I,J)=0.\n\n                !DJG ERROR Check...\n\n                IF (ovrt_data%control%surface_water_head_routing(I,J).lt.0.) THEN\n#ifdef HYDRO_D\n                    print *, \"ywcheck 2 ERROR!!!: Neg. Surface Head Value at (i,j):\",    &\n                        i,j,ovrt_data%control%surface_water_head_routing(I,J)\n                    print *, \"RETDEPRT(I,J) = \",ovrt_data%properties%retention_depth(I,J), \"KRT=\",KRT\n                    print *, \"INFXSUBRT(i,j)=\",ovrt_data%control%infiltration_excess(i,j)\n                    print *, \"jxrt=\",jxrt,\" ixrt=\",ixrt\n#endif\n                END IF\n\n                !DJG Remove surface water from channel cells\n                !DJG Channel inflo cells specified as nonzeros from CH_NET\n                !DJG 9/16/04  Channel Extractions Removed until stream model implemented...\n\n\n\n                !yw            IF (CH_NETRT(I,J).ne.-9999) THEN\n                IF (ovrt_data%streams_and_lakes%CH_NETRT(I,J).ge.0) THEN\n                    ct = ct +1\n\n                    !DJG Temporary test to up the retention depth of channel grid cells to 'soak'\n                    !more water into valleys....set retdep = retdep*100 (=5 mm)\n\n                    !\t     RETDEPRT(I,J) = RETDEPRT(I,J) * 100.0    !DJG TEMP HARDWIRE!!!!\n                    !\t     RETDEPRT(I,J) = 10.0    !DJG TEMP HARDWIRE!!!!\n\n                    ! AD hardwire to force channel retention depth to be 5mm.\n                    ovrt_data%properties%retention_depth(I,J) = 5.0\n\n                    IF (ovrt_data%control%surface_water_head_routing(I,J) .GT. ovrt_data%properties%retention_depth(I,J)) THEN\n                        !!               QINFLO(CH_NET(I,J)=QINFLO(CH_NET(I,J)+SFCHEAD(I,J) - RETDEPRT(I,J)\n                        ovrt_data%streams_and_lakes%accumulated_surface_water_to_channel = ovrt_data%streams_and_lakes%accumulated_surface_water_to_channel + &\n                            (ovrt_data%control%surface_water_head_routing(I,J) - ovrt_data%properties%retention_depth(I,J))\n                        ovrt_data%streams_and_lakes%surface_water_to_channel(I,J) = ovrt_data%streams_and_lakes%surface_water_to_channel(I,J) + &\n                            (ovrt_data%control%surface_water_head_routing(I,J) - ovrt_data%properties%retention_depth(I,J))\n\n                        ! if(QSTRMVOLRT(I,J) .gt. 0) then\n                        !     print *, \"QSTRVOL GT 0\", QSTRMVOLRT(I,J),I,J\n                        !  endif\n\n                        ovrt_data%control%surface_water_head_routing(I,J) = ovrt_data%properties%retention_depth(I,J)\n                    END IF\n                END IF\n\n                !DJG Lake inflow withdrawl from surface head...(4/29/05)\n\n\n                IF (ovrt_data%streams_and_lakes%lake_mask(I,J) .gt. 0) THEN\n                    IF (ovrt_data%control%surface_water_head_routing(I,J) .GT. ovrt_data%properties%retention_depth(I,J)) THEN\n                        ovrt_data%streams_and_lakes%accumulated_surface_water_to_lake = ovrt_data%streams_and_lakes%accumulated_surface_water_to_lake + &\n                            (ovrt_data%control%surface_water_head_routing(I,J) - ovrt_data%properties%retention_depth(I,J))\n                        ovrt_data%streams_and_lakes%surface_water_to_lake(I,J) = ovrt_data%streams_and_lakes%surface_water_to_lake(I,J) + &\n                            (ovrt_data%control%surface_water_head_routing(I,J)- ovrt_data%properties%retention_depth(I,J))\n                        ovrt_data%control%surface_water_head_routing(I,J) = ovrt_data%properties%retention_depth(I,J)\n                    END IF\n                END IF\n\n\n\n            END DO\n        END DO\n\n        !yw check         call MPP_LAND_COM_REAL(QSTRMVOLRT,IXRT,JXRT,99)\n        !DJG----------------------------------------------------------------------\n        !DJG CALL OVERLAND FLOW ROUTING SUBROUTINE\n        !DJG----------------------------------------------------------------------\n\n        !DJG Debug...\n\n\n        if(rt_option .eq. 1) then\n            CALL ROUTE_OVERLAND1(DTRT_TER, &\n                ovrt_data%properties%distance_to_neighbor, &\n                ovrt_data%control%surface_water_head_routing, &\n                ovrt_data%control%DHRT, &\n                ovrt_data%properties%surface_slope_x,   &\n                ovrt_data%properties%surface_slope_y, &\n                ovrt_data%properties%retention_depth, &\n                ovrt_data%properties%roughness, &\n                IXRT, JXRT, &\n                ovrt_data%control%boundary_flux, &\n                ovrt_data%control%boundary_flux_total,    &\n                ovrt_data%properties%surface_slope, &\n                ovrt_data%properties%max_surface_slope_index, &\n                q_sfcflx_x, q_sfcflx_y)\n        else\n            CALL ROUTE_OVERLAND2(DTRT_TER, &\n                ovrt_data%properties%distance_to_neighbor, &\n                ovrt_data%control%surface_water_head_routing, &\n                ovrt_data%control%DHRT, &\n                ovrt_data%properties%surface_slope_x, &\n                ovrt_data%properties%surface_slope_y, &\n                ovrt_data%properties%retention_depth, &\n                ovrt_data%properties%roughness, &\n                IXRT, JXRT, &\n                ovrt_data%control%boundary_flux, &\n                ovrt_data%control%boundary_flux_total,  &\n                q_sfcflx_x,q_sfcflx_y)\n        end if\n\n    END DO          ! END routing time steps\n\n#ifdef HYDRO_D\n    print *, \"End of OV_routing call...\"\n#endif\n\n    !----------------------------------------------------------------------\n    ! END OVERLAND FLOW ROUTING LOOP\n    !     CHANNEL ROUTING TO FOLLOW\n    !----------------------------------------------------------------------\n\n    !DJG ----------------------------------------------------------------\nEND SUBROUTINE OV_RTNG\n\n!DJG ----------------------------------------------------------------\n\n!DJG     SUBROUTINE ROUTE_OVERLAND1\n!DJG ----------------------------------------------------------------\n\nSUBROUTINE ROUTE_OVERLAND1(dt,                                &\n        &          gsize,h,qsfc,sox,soy,                                   &\n        &     retent_dep,dist_rough,XX,YY,QBDRY,QBDRYT,SO8RT,SO8RT_D,      &\n        &     q_sfcflx_x,q_sfcflx_y)\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    !\n    !  Subroutine to route excess rainfall over the watershed\n    !     using a 2d diffusion routing scheme.\n    !\n    !  Called from: main.f\n    !\n    !      Will try to formulate this to be called from NOAH\n    !\n    !  Returns: qsfc=DQOV   which in turn becomes DH in head calc.\n    !\n    !  Created:  Adaptded from CASC2D source code\n    !  NOTE: dh from original code has been replaced by qsfc\n    !        dhh replaced by qqsfc\n    !\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n#ifdef MPP_LAND\n    use module_mpp_land, only: left_id,down_id,right_id, &\n        up_id,mpp_land_com_real, my_id, mpp_land_com_real8,&\n        mpp_land_sync\n#endif\n\n    IMPLICIT NONE\n\n\n    !! Declare Passed variables\n\n    INTEGER, INTENT(IN) :: XX,YY\n    REAL, INTENT(IN) :: dt, gsize(xx,yy,9)\n\n    !! Declare passed arrays\n\n    REAL, INTENT(INOUT), DIMENSION(XX,YY) :: h\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: qsfc\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: sox\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: soy\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: retent_dep\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: dist_rough\n    REAL, INTENT(INOUT), DIMENSION(XX,YY) :: QBDRY\n    REAL, INTENT(INOUT), DIMENSION(XX,YY) :: q_sfcflx_x, q_sfcflx_y\n    REAL, INTENT(INOUT) :: QBDRYT\n    REAL, INTENT(IN), DIMENSION(XX,YY,8) :: SO8RT\n    REAL*8, DIMENSION(XX,YY) :: QBDRY_tmp, DH\n    REAL*8, DIMENSION(XX,YY) :: DH_tmp\n    REAL, DIMENSION(XX,YY) :: edge_adjust ! mm\n\n    !!! Declare Local Variables\n\n    REAL :: dhdx,dhdy,alfax,alfay\n    REAL :: hh53,qqsfc,hh,dt_new,hmax\n    REAL :: sfx,sfy\n    REAL :: tmp_adjust\n\n    INTEGER :: i,j\n    REAL IXX8,IYY8\n    INTEGER  IXX0,JYY0,index, SO8RT_D(XX,YY,3)\n    REAL :: tmp_gsize, hsum, tmp_gsize_arr(9)\n\n    !!! Initialize variables\n\n\n\n    !!! Begin Routing of Excess Rainfall over the Watershed\n\n    DH=0.\n    DH_tmp=0.\n    QBDRY_tmp =0.\n\n    !!! Loop to route water\n    do j=2,YY-1\n        do i=2,XX-1\n            if (h(I,J).GT.retent_dep(I,J)) then\n                IXX0 = SO8RT_D(i,j,1)\n                JYY0 = SO8RT_D(i,j,2)\n                index = SO8RT_D(i,j,3)\n                tmp_gsize = 1.0/gsize(i,j,index)\n                sfx = so8RT(i,j,index)-(h(IXX0,JYY0)-h(i,j))*0.001*tmp_gsize\n                hmax = h(i,j)*0.001  !Specify max head for mass flux limit...\n                if(sfx .lt. 1E-20) then\n                    tmp_gsize_arr = gsize(i,j,:)\n                    call GETMAX8DIR(IXX0,JYY0,I,J,H,RETENT_DEP,so8rt,tmp_gsize_arr,sfx,XX,YY)\n                end if\n                if(IXX0 > 0) then  ! do the rest if the lowest grid can be found.\n                    if(sfx .lt. 1E-20) then\n#ifdef HYDRO_D\n                        print*, \"Message: sfx reset to 1E-20. sfx =\",sfx\n                        print*, \"i,j,index,IXX0,JYY0\",i,j,index,IXX0,JYY0\n                        print*, \"so8RT(i,j,index), h(IXX0,JYY0), h(i,j), gsize(i,j,index) \", &\n                            so8RT(i,j,index), h(IXX0,JYY0), h(i,j), gsize(i,j,index)\n#endif\n                        sfx = 1E-20\n                    end if\n                    alfax = sqrt(sfx) / dist_rough(i,j)\n                    hh=(h(i,j)-retent_dep(i,j)) * 0.001\n                    hh53=hh**(5./3.)\n\n                    ! Calculate q-flux...\n                    qqsfc = alfax*hh53*dt * tmp_gsize\n\n                    !Courant check (simple mass limit on overland flow)...\n                    if (qqsfc.ge.(hmax*dt*tmp_gsize)) qqsfc = hmax*dt*tmp_gsize\n\n                    ! Accumulate directional fluxes on routing subgrid...\n                    if (IXX0.gt.i) then\n                        q_sfcflx_x(I,J) = q_sfcflx_x(I,J) + qqsfc * &\n                            (1.0 - 0.5 * (ABS(j-JYY0)))\n                    else if (IXX0.lt.i) then\n                        q_sfcflx_x(I,J) = q_sfcflx_x(I,J) - 1.0 * &\n                            qqsfc * (1.0 - 0.5 * (ABS(j-JYY0)))\n                    else\n                        q_sfcflx_x(I,J) = q_sfcflx_x(I,J) + 0.\n                    end if\n                    if (JYY0.gt.j) then\n                        q_sfcflx_y(I,J) = q_sfcflx_y(I,J) + qqsfc * &\n                            (1.0 - 0.5 * (ABS(i-IXX0)))\n                    elseif (JYY0.lt.j) then\n                        q_sfcflx_y(I,J) = q_sfcflx_y(I,J) - 1.0 * &\n                            qqsfc * (1.0 - 0.5 * (ABS(i-IXX0)))\n                    else\n                        q_sfcflx_y(I,J) = q_sfcflx_y(I,J) + 0.\n                    end if\n\n                    !DJG put adjustment in for (h) due to qqsfc\n\n                    !yw changed as following:\n                    tmp_adjust=qqsfc*1000\n\n                    if((h(i,j) - tmp_adjust) <0 )  then\n#ifdef HYDRO_D\n                        print*, \"Error Warning: surface head is negative:  \",i,j,ixx0,jyy0, &\n                            h(i,j) - tmp_adjust\n#endif\n                        tmp_adjust = h(i,j)\n                    end if\n                    DH(i,j) = DH(i,j)-tmp_adjust\n                    DH_tmp(ixx0,jyy0) = DH_tmp(ixx0,jyy0) + tmp_adjust\n                    !yw end change\n\n                    !DG Boundary adjustments here\n                    !DG Constant Flux Condition\n#ifdef MPP_LAND\n                    if( ((ixx0.eq.XX).and.(right_id .lt. 0)) .or. &\n                            ((ixx0.eq.1) .and.(left_id  .lt. 0)) .or. &\n                            ((jyy0.eq.1) .and.(down_id  .lt. 0)) .or. &\n                            ((JYY0.eq.YY).and.(up_id    .lt. 0)) ) then\n                        !QBDRY_tmp(IXX0,JYY0)=QBDRY_tmp(IXX0,JYY0) - qqsfc*1000.\n#else\n                        if ((ixx0.eq.XX).or.(ixx0.eq.1).or.(jyy0.eq.1)   &\n                                .or.(JYY0.eq.YY )) then\n                            !QBDRY(IXX0,JYY0)=QBDRY(IXX0,JYY0) - qqsfc*1000.\n#endif\n                            QBDRY_tmp(IXX0,JYY0)=QBDRY_tmp(IXX0,JYY0) - qqsfc*1000.\n                            QBDRYT=QBDRYT - qqsfc\n                            DH_tmp(IXX0,JYY0)= DH_tmp(IXX0,JYY0)-tmp_adjust\n\n                        end if\n                    end if\n\n                    !! End loop to route sfc water\n                end if\n\n        end do\n    end do\n\n#ifdef MPP_LAND\n    ! use double precision to solve the underflow problem.\n    call MPP_LAND_COM_REAL8(DH_tmp,XX,YY,1)\n    call MPP_LAND_COM_REAL8(QBDRY_tmp,XX,YY,1)\n#endif\n    QBDRY = QBDRY + QBDRY_tmp\n    DH = DH+DH_tmp\n\n#ifdef MPP_LAND\n    call MPP_LAND_COM_REAL8(DH,XX,YY,99)\n    call MPP_LAND_COM_REAL(QBDRY,XX,YY,99)\n#endif\n\n    H = H + DH\n\n!!! Scrape the outermost edges\nedge_adjust = 0.0\ndo j=1,YY,YY-1\n   do i=1,XX\n#ifdef MPP_LAND\n      if( ((i.eq.XX).and.(right_id .lt. 0)) .or. &\n          ((i.eq.1) .and.(left_id  .lt. 0)) .or. &\n          ((j.eq.1) .and.(down_id  .lt. 0)) .or. &\n          ((j.eq.YY).and.(up_id    .lt. 0)) ) then\n#else\n          if ((i.eq.XX).or.(i.eq.1).or.(j.eq.1)   &\n               .or.(j.eq.YY )) then\n#endif\n              if (h(i,j) .GT. retent_dep(i,j)) then\n                 edge_adjust(i,j) = h(i,j) - retent_dep(i,j) ! positive mm\n              end if\n\n          end if\n   end do\nend do\n\ndo i=1,XX,XX-1\n   do j=1,YY\n#ifdef MPP_LAND\n      if( ((i.eq.XX).and.(right_id .lt. 0)) .or. &\n          ((i.eq.1) .and.(left_id  .lt. 0)) .or. &\n          ((j.eq.1) .and.(down_id  .lt. 0)) .or. &\n          ((j.eq.YY).and.(up_id    .lt. 0)) ) then\n#else\n          if ((i.eq.XX).or.(i.eq.1).or.(j.eq.1)   &\n               .or.(j.eq.YY )) then\n#endif\n              if (h(i,j) .GT. retent_dep(i,j)) then\n                 edge_adjust(i,j) = h(i,j) - retent_dep(i,j) ! positive mm\n              end if\n\n          end if\n   end do\nend do\n\n\n#ifdef MPP_LAND\n    call MPP_LAND_COM_REAL(edge_adjust,XX,YY,99)\n#endif\n    QBDRY = QBDRY - edge_adjust ! making this negative term more negative\n    H = H - edge_adjust ! making this positive term less positive\n!!! End outermost edge scrape\n\n    return\n\n    !DJG ----------------------------------------------------------------------\nend subroutine ROUTE_OVERLAND1\n\n!DJG ----------------------------------------------------------------------\n\n!DJG     SUBROUTINE ROUTE_OVERLAND2\n!DJG ----------------------------------------------------------------\n\nSUBROUTINE ROUTE_OVERLAND2 (dt,                               &\n        &          dist,h,qsfc,sox,soy,                                   &\n        &          retent_dep,dist_rough,XX,YY,QBDRY,QBDRYT,               &\n        &          q_sfcflx_x,q_sfcflx_y)\n\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    !\n    !  Subroutine to route excess rainfall over the watershed\n    !     using a 2d diffusion routing scheme.\n    !\n    !  Called from: main.f\n    !\n    !      Will try to formulate this to be called from NOAH\n    !\n    !  Returns: qsfc=DQOV   which in turn becomes DH in head calc.\n    !\n    !  Created:  Adaptded from CASC2D source code\n    !  NOTE: dh from original code has been replaced by qsfc\n    !        dhh replaced by qqsfc\n    !\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n#ifdef MPP_LAND\n    use module_mpp_land, only: left_id,down_id,right_id,&\n        up_id,mpp_land_com_real,MPP_LAND_UB_COM, &\n        MPP_LAND_LR_COM,mpp_land_com_integer\n#endif\n\n    IMPLICIT NONE\n\n\n    !! Declare Passed variables\n\n    real :: gsize\n    INTEGER, INTENT(IN) :: XX,YY\n    REAL, INTENT(IN) :: dt , dist(XX,YY,9)\n\n    !! Declare passed arrays\n\n    REAL, INTENT(INOUT), DIMENSION(XX,YY) :: h\n    REAL, INTENT(INOUT), DIMENSION(XX,YY) :: qsfc\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: sox\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: soy\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: retent_dep\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: dist_rough\n    REAL, INTENT(INOUT), DIMENSION(XX,YY) :: QBDRY\n    REAL, INTENT(INOUT), DIMENSION(XX,YY) :: q_sfcflx_x,q_sfcflx_y\n    REAL, INTENT(INOUT) :: QBDRYT\n    REAL  :: DH(XX,YY)\n\n    !!! Declare Local Variables\n\n    REAL :: dhdx,dhdy,alfax,alfay\n    REAL :: hh53,qqsfc,hh,dt_new\n    REAL :: sfx,sfy\n    REAL :: tmp_adjust\n\n    INTEGER :: i,j\n\n    !!! Initialize variables\n\n\n\n\n    !!! Begin Routing of Excess Rainfall over the Watershed\n\n\n    DH = 0\n    !!! Loop to route water in x-direction\n    do j=1,YY\n        do i=1,XX\n            ! check for boundary gridpoint?\n            if (i.eq.XX) GOTO 998\n            gsize = dist(i,j,3)\n\n            ! check for detention storage?\n            if (h(i,j).lt.retent_dep(i,j).AND.     &\n                h(i+1,j).lt.retent_dep(i+1,j)) GOTO 998\n\n            dhdx = (h(i+1,j)/1000. - h(i,j)/1000.) / gsize  ! gisze-(m),h-(mm)\n\n            sfx = (sox(i,j)-dhdx+1E-30)\n            if (abs(sfx).lt.1E-20) sfx=1E-20\n            alfax = ((abs(sfx))**0.5)/dist_rough(i,j)\n            if (sfx.lt.0.) then\n                hh=(h(i+1,j)-retent_dep(i+1,j))/1000.\n            else\n                hh=(h(i,j)-retent_dep(i,j))/1000.\n            end if\n\n            if ((retent_dep(i,j).gt.0.).AND.(hh.le.0.)) GOTO 998\n            if (hh.lt.0.) then\n                GOTO 998\n            end if\n\n            hh53=hh**(5./3.)\n\n            ! Calculate q-flux... (units (m))\n            qqsfc = (sfx/abs(sfx))*alfax*hh53*dt/gsize\n            q_sfcflx_x(I,J) = q_sfcflx_x(I,J) + qqsfc\n\n            !DJG put adjustment in for (h) due to qqsfc\n\n            !yw changed as following:\n            tmp_adjust=qqsfc*1000\n            if(tmp_adjust .le. 0 ) GOTO 998\n            if((h(i,j) - tmp_adjust) <0 )  then\n#ifdef HYDRO_D\n                print*, \"WARNING: surface head is negative:  \",i,j\n#endif\n                tmp_adjust = h(i,j)\n            end if\n            if((h(i+1,j) + tmp_adjust) <0) then\n#ifdef HYDRO_D\n                print*, \"WARNING: surface head is negative: \",i+1,j\n#endif\n                tmp_adjust = -1*h(i+1,j)\n            end if\n            Dh(i,j) = Dh(i,j)-tmp_adjust\n            Dh(i+1,j) = Dh(i+1,j) + tmp_adjust\n            !yw end change\n\n\n\n            !DG Boundary adjustments here\n            !DG Constant Flux Condition\n#ifdef MPP_LAND\n            if ((i.eq.1).AND.(sfx.lt.0).and. &\n                    (left_id .lt. 0) ) then\n#else\n                if ((i.eq.1).AND.(sfx.lt.0)) then\n#endif\n                    Dh(i,j) = Dh(i,j) + qqsfc*1000.\n                    QBDRY(I,J)=QBDRY(I,J) + qqsfc*1000.\n                    QBDRYT=QBDRYT + qqsfc*1000.\n#ifdef MPP_LAND\n                else if ( (i.eq.(XX-1)).AND.(sfx.gt.0) &\n                        .and. (right_id .lt. 0) ) then\n#else\n                else if ((i.eq.(XX-1)).AND.(sfx.gt.0)) then\n#endif\n                    tmp_adjust = qqsfc*1000.\n                    if(h(i+1,j).lt.tmp_adjust) tmp_adjust = h(i+1,j)\n                    Dh(i+1,j) = Dh(i+1,j) - tmp_adjust\n                    !DJG Re-assign h(i+1) = 0.0 when <0.0 (from rounding/truncation error)\n                    QBDRY(I+1,J)=QBDRY(I+1,J) - tmp_adjust\n                    QBDRYT=QBDRYT - tmp_adjust\n                end if\n\n\n                998     continue\n\n                !! End loop to route sfc water in x-direction\n        end do\n    end do\n\n    H = H + DH\n#ifdef MPP_LAND\n    call MPP_LAND_LR_COM(H,XX,YY,99)\n    call MPP_LAND_LR_COM(QBDRY,XX,YY,99)\n#endif\n\n\n    DH = 0\n    !!!! Loop to route water in y-direction\n    do j=1,YY\n        do i=1,XX\n\n            !! check for boundary grid point?\n            if (j.eq.YY) GOTO 999\n            gsize = dist(i,j,1)\n\n\n            !! check for detention storage?\n            if (h(i,j).lt.retent_dep(i,j).AND.     &\n                h(i,j+1).lt.retent_dep(i,j+1)) GOTO 999\n\n            dhdy = (h(i,j+1)/1000. - h(i,j)/1000.) / gsize\n\n            sfy = (soy(i,j)-dhdy+1E-30)\n            if (abs(sfy).lt.1E-20) sfy=1E-20\n            alfay = ((abs(sfy))**0.5)/dist_rough(i,j)\n            if (sfy.lt.0.) then\n                hh=(h(i,j+1)-retent_dep(i,j+1))/1000.\n            else\n                hh=(h(i,j)-retent_dep(i,j))/1000.\n            end if\n\n            if ((retent_dep(i,j).gt.0.).AND.(hh.le.0.)) GOTO 999\n            if (hh.lt.0.) then\n                GOTO 999\n            end if\n\n            hh53=hh**(5./3.)\n\n            ! Calculate q-flux...\n            qqsfc = (sfy/abs(sfy))*alfay*hh53*dt / gsize\n            q_sfcflx_y(I,J) = q_sfcflx_y(I,J) + qqsfc\n\n\n            !DJG put adjustment in for (h) due to qqsfc\n            !yw\t  h(i,j) = h(i,j)-qqsfc*1000.\n            !yw          h(i,j+1) = h(i,j+1) + qqsfc*1000.\n            !yw changed as following:\n            tmp_adjust=qqsfc*1000\n            if(tmp_adjust .le. 0 ) GOTO 999\n\n            if((h(i,j) - tmp_adjust) <0 )  then\n#ifdef HYDRO_D\n                print *, \"WARNING: surface head is negative:  \",i,j\n#endif\n                tmp_adjust = h(i,j)\n            end if\n            if((h(i,j+1) + tmp_adjust) <0) then\n#ifdef HYDRO_D\n                print *, \"WARNING: surface head is negative: \",i,j+1\n#endif\n                tmp_adjust = -1*h(i,j+1)\n            end if\n            Dh(i,j) = Dh(i,j)-tmp_adjust\n            Dh(i,j+1) = Dh(i,j+1) + tmp_adjust\n            !yw end change\n\n            !qsfc(i,j) = qsfc(i,j)-qqsfc\n            !qsfc(i,j+1) = qsfc(i,j+1) + qqsfc\n            !!DG Boundary adjustments here\n            !!DG Constant Flux Condition\n#ifdef MPP_LAND\n            if ((j.eq.1).AND.(sfy.lt.0)   &\n                    .and. (down_id .lt. 0) ) then\n#else\n                if ((j.eq.1).AND.(sfy.lt.0)) then\n#endif\n                    Dh(i,j) = Dh(i,j) + qqsfc*1000.\n                    QBDRY(I,J)=QBDRY(I,J) + qqsfc*1000.\n                    QBDRYT=QBDRYT + qqsfc*1000.\n#ifdef MPP_LAND\n                else if ((j.eq.(YY-1)).AND.(sfy.gt.0) &\n                        .and. (up_id .lt. 0) ) then\n#else\n                else if ((j.eq.(YY-1)).AND.(sfy.gt.0)) then\n#endif\n                    tmp_adjust = qqsfc*1000.\n                    if(h(i,j+1).lt.tmp_adjust) tmp_adjust = h(i,j+1)\n                    Dh(i,j+1) = Dh(i,j+1) - tmp_adjust\n                    !DJG Re-assign h(j+1) = 0.0 when <0.0 (from rounding/truncation error)\n                    QBDRY(I,J+1)=QBDRY(I,J+1) - tmp_adjust\n                    QBDRYT=QBDRYT - tmp_adjust\n                end if\n\n                999     continue\n\n                !!!! End loop to route sfc water in y-direction\n        end do\n    end do\n\n    H = H +DH\n#ifdef MPP_LAND\n    call MPP_LAND_UB_COM(H,XX,YY,99)\n    call MPP_LAND_UB_COM(QBDRY,XX,YY,99)\n#endif\n    return\n\n    !DJG ----------------------------------------------------------------------\nend subroutine ROUTE_OVERLAND2\n"
  },
  {
    "path": "src/Routing/Noah_distr_routing_subsurface.F90",
    "content": "subroutine subsurfaceRouting ( subrt_data, subrt_static, subrt_input, subrt_output)\n#ifdef MPP_LAND\n    use module_mpp_land, only:  mpp_land_com_real, mpp_land_com_integer\n    use module_subsurface_data\n    use module_subsurface_static_data\n    use module_subsurface_input\n    use module_subsurface_output\n#endif\n    implicit none\n    type (subsurface_struct), intent(inout) :: subrt_data\n    type (subsurface_static_interface), intent(inout) :: subrt_static\n    type (subsurface_input_interface), intent(inout) :: subrt_input\n    type (subsurface_output_interface), intent(inout) :: subrt_output\n    !integer, INTENT(IN) :: ixrt, jxrt , nsoil, rt_option\n    !REAL, INTENT(IN)                          :: DT\n    !real,INTENT(IN), DIMENSION(NSOIL)      :: SLDPTH\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT) :: sub_resid\n    !real,INTENT(INOUT), DIMENSION(subrt_static%IXRT,subrt_static%JXRT)::INFXSUBRT\n    !real,INTENT(INOUT) :: QSUBBDRYTRT\n    !REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)   :: QSUBBDRYRT, QSUBRT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT,NSOIL) :: SMCRT, SMCWLTRT, SMCMAXRT, SMCREFRT\n\n\n    !INTEGER :: SO8RT_D(IXRT,JXRT,3)\n    !REAL :: SO8RT(IXRT,JXRT,8)\n    !REAL, INTENT(IN)                          :: dist(ixrt,jxrt,9)\n    !  -----local array ----------\n    !REAL, DIMENSION(IXRT,JXRT)   :: ZWATTABLRT\n    REAL, DIMENSION(subrt_static%ixrt,subrt_static%jxrt)   :: CWATAVAIL\n    INTEGER, DIMENSION(subrt_static%ixrt,subrt_static%jxrt) :: SATLYRCHK\n\n    CWATAVAIL = 0.\n    CALL FINDZWAT(subrt_static%ixrt,subrt_static%jxrt,subrt_static%NSOIL, &\n        subrt_data%grid_transform%smcrt, &\n        subrt_data%grid_transform%smcmaxrt, &\n        subrt_data%grid_transform%smcrefrt, &\n        subrt_data%grid_transform%smcwltrt, subrt_data%properties%zsoil,SATLYRCHK,subrt_data%properties%zwattablrt, &\n        CWATAVAIL,subrt_data%properties%sldpth)\n#ifdef MPP_LAND\n    call MPP_LAND_COM_REAL(subrt_data%properties%zwattablrt,subrt_static%ixrt,subrt_static%jxrt,99)\n    call MPP_LAND_COM_REAL(CWATAVAIL,subrt_static%ixrt,subrt_static%jxrt,99)\n    call MPP_LAND_COM_INTEGER(SATLYRCHK,subrt_static%ixrt,subrt_static%jxrt,99)\n#endif\n\n\n    !DJG Second, Call subsurface routing routine...\n#ifdef HYDRO_D\n    print *, \"Beginning SUB_routing...\"\n    print *, \"Routing method is \",subrt_static%rt_option, \" direction.\"\n#endif\n\n    !!!! Find saturated layer depth...\n    ! Loop through domain to determine sat. layers and assign wat tbl depth...\n    !    and water available for subsfc routing (CWATAVAIL)...\n    ! This subroutine returns: ZWATTABLRT, CWATAVAIL and SATLYRCHK\n\n\n    CALL SUBSFC_RTNG( subrt_data, subrt_static, subrt_input, subrt_output, CWATAVAIL, SATLYRCHK)\n\n#ifdef HYDRO_D\n    print *, \"SUBROUTE routing called and returned...\"\n#endif\n\nend subroutine subsurfaceRouting\n\n!DJG ------------------------------------------------\n!DJG   SUBROUTINE SUBSFC_RTNG\n!DJG ------------------------------------------------\n\nSUBROUTINE SUBSFC_RTNG(subrt_data, subrt_static, subrt_input, subrt_output, CWATAVAIL, SATLYRCHK)\n\n    !       use module_mpp_land, only: write_restart_rt_3, write_restart_rt_2, &\n        !            my_id\n#ifdef MPP_LAND\n    use module_mpp_land, only: MPP_LAND_COM_REAL, sum_real1, &\n        my_id, io_id, numprocs\n    use module_subsurface_data\n    use module_subsurface_static_data\n    use module_subsurface_input\n    use module_subsurface_output\n    use module_hydro_stop, only:HYDRO_stop\n#endif\n    IMPLICIT NONE\n\n    !DJG -------- DECLARATIONS ------------------------\n\n    type (subsurface_struct), intent(inout) :: subrt_data\n    type (subsurface_static_interface), intent(inout) :: subrt_static\n    type (subsurface_input_interface), intent(inout) :: subrt_input\n    type (subsurface_output_interface), intent(inout) :: subrt_output\n\n    !INTEGER, INTENT(IN) :: IXRT,JXRT,NSOIL\n    !INTEGER, INTENT(IN) :: IXRT,JXRT\n\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: SOXRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: SOYRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: LATKSATRT\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: SOLDEPRT\n\n    !REAL, INTENT(IN), DIMENSION(IXRT,JXRT)   :: ZWATTABLRT\n    REAL, INTENT(IN), DIMENSION(subrt_static%ixrt,subrt_static%jxrt)   :: CWATAVAIL\n    INTEGER, INTENT(IN), DIMENSION(subrt_static%ixrt,subrt_static%jxrt) :: SATLYRCHK\n\n\n    !REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)   :: QSUBRT\n    !REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)   :: QSUBBDRYRT\n\n    !REAL, INTENT(IN)                          :: dist(ixrt,jxrt,9)\n    !REAL, INTENT(IN)                          :: DT\n    !REAL, INTENT(IN), DIMENSION(subrt_static%nsoil)        :: ZSOIL\n    !REAL, INTENT(IN), DIMENSION(subrt_static%nsoil) \t  :: SLDPTH\n    !REAL, INTENT(INOUT)                       :: QSUBBDRYTRT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: INFXSUBRT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT,subrt_static%nsoil) :: SMCMAXRT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT,subrt_static%nsoil) :: SMCREFRT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT,subrt_static%nsoil) :: SMCRT\n    !REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT,subrt_static%nsoil) :: SMCWLTRT\n\n    REAL, DIMENSION(subrt_static%IXRT,subrt_static%JXRT)\t:: ywtmp\n    !DJG Local Variables\n\n    INTEGER\t:: I,J,KK\n    !djg        INTEGER, DIMENSION(IXRT,JXRT) :: SATLYRCHK\n\n    REAL \t:: GRDAREA\n    REAL\t:: SUBFLO\n    REAL\t:: WATAVAIL\n\n    !INTEGER :: SO8RT_D(IXRT,JXRT,3)\n    !REAL :: SO8RT(IXRT,JXRT,8)\n    !INTEGER, INTENT(IN)  ::  rt_option\n    integer  ::  index\n\n    INTEGER :: DT_STEPS             !-- number of timestep in routing\n    REAL :: SUBDT                !-- subsurface routing timestep\n    INTEGER :: KRT                  !-- routing counter\n    REAL, DIMENSION(subrt_static%IXRT,subrt_static%JXRT,subrt_static%nsoil) :: SMCTMP  !--temp store of SMC\n    REAL, DIMENSION(subrt_static%IXRT,subrt_static%JXRT) :: ZWATTABLRTTMP ! temp store of ZWAT\n    REAL, DIMENSION(subrt_static%IXRT,subrt_static%JXRT) :: INFXSUBRTTMP ! temp store of infilx\n    !djg        REAL, DIMENSION(IXRT,JXRT) :: CWATAVAIL ! temp specif. of wat avial\n\n\n\n    !DJG Debug Variables...\n    REAL :: qsubchk,qsubbdrytmp\n    REAL :: junk1,junk2,junk3,junk5,junk6,junk7\n    INTEGER, PARAMETER :: double=8\n    REAL (KIND=double) :: smctot1a,smctot2a\n    INTEGER :: kx,count\n\n#ifdef HYDRO_D\n    ! ADCHANGE: Water balance variables\n    real   :: smctot1,smctot2\n    real   :: suminfxsrt1,suminfxsrt2\n    real   :: qbdry1,qbdry2\n    real   :: sumqsubrt1, sumqsubrt2\n#endif\n\n    !DJG -----------------------------------------------------------------\n    !DJG  SUBSURFACE ROUTING LOOP\n    !DJG    - SUBSURFACE ROUTING RUN ON NOAH TIMESTEP\n    !DJG    - SUBSURFACE ROUITNG ONLY PERFORMED ON SATURATED LAYERS\n    !DJG -----------------------------------------------------------------\n\n    !Z. Cui -----------------------------------------------------------------\n    !Move SUBDT initialization up to avoid crash when HYDRO_D is defined\n    SUBDT = subrt_static%dt                !-- initialize the routing timestep to DT\n    !Z. Cui -----------------------------------------------------------------\n#ifdef HYDRO_D\n    ! ADCHANGE: START Initial water balance variables\n    ! ALL VARS in MM\n    suminfxsrt1 = 0.\n    qbdry1 = 0.\n    smctot1 = 0.\n    sumqsubrt1 = 0.\n    do i=1,subrt_static%IXRT\n        do j=1,subrt_static%JXRT\n            suminfxsrt1 = suminfxsrt1 + subrt_input%infiltration_excess(I,J) / float(subrt_static%IXRT*subrt_static%JXRT)\n            qbdry1 = qbdry1 + subrt_data%state%qsubbdryrt(i,j) / subrt_data%properties%distance_to_neighbor(i,j,9)*SUBDT*1000. / float(subrt_static%IXRT*subrt_static%JXRT)\n            sumqsubrt1 = sumqsubrt1 + subrt_data%state%qsubrt(i,j) / subrt_data%properties%distance_to_neighbor(i,j,9)*SUBDT*1000. / float(subrt_static%IXRT*subrt_static%JXRT)\n            do kk=1,subrt_static%nsoil\n                smctot1 = smctot1 + subrt_data%grid_transform%smcrt(I,J,KK)*subrt_data%properties%sldpth(KK)*1000. / float(subrt_static%IXRT*subrt_static%JXRT)\n            end do\n        end do\n    end do\n\n#ifdef MPP_LAND\n    ! not tested\n    CALL sum_real1(suminfxsrt1)\n    CALL sum_real1(qbdry1)\n    CALL sum_real1(sumqsubrt1)\n    CALL sum_real1(smctot1)\n    suminfxsrt1 = suminfxsrt1/float(numprocs)\n    qbdry1 = qbdry1/float(numprocs)\n    sumqsubrt1 = sumqsubrt1/float(numprocs)\n    smctot1 = smctot1/float(numprocs)\n#endif\n    ! END Initial water balance variables\n#endif\n\n\n    !yw GRDAREA=DXRT*DXRT\n    ! GRDAREA=subrt_data%properties%distance_to_neighbor(i,j,9)\n\n\n    !DJG debug subsfc...\n    subflo = 0.0\n\n    !DJG Set up mass balance checks...\n    !         CWATAVAIL = 0.            !-- initialize subsurface watavail\n\n\n    !!!! Find saturated layer depth...\n    ! Loop through domain to determine sat. layers and assign wat tbl depth...\n    !    and water available for subsfc routing (CWATAVAIL)...\n    !\n    !   This function call appears to have been moved to SubsurfaceRouting()\n    !\n    !\n    !         CALL FINDZWAT(IXRT,JXRT,subrt_static%nsoil,SMCRT,SMCMAXRT,SMCREFRT, &\n        !                             SMCWLTRT,ZSOIL,SATLYRCHK,subrt_data%properties%zwattablrt, &\n        !                             CWATAVAIL,SLDPTH)\n\n\n\n\n    !DJG debug variable...\n\n    !DJG Courant check temp variable setup...\n    ZWATTABLRTTMP = subrt_data%properties%zwattablrt !-- temporary storage of water table level\n\n\n\n\n    !!!! Call subsurface routing subroutine...\n#ifdef HYDRO_D\n    print *, \"calling subsurface routing subroutine...Opt. \",subrt_static%rt_option\n#endif\n\n    ! ADCHANGE: IMPORTANT!\n    ! 2D subsurface option currently has bug so forcing to option 1 in this routine to\n    ! allow users to still have option to use 2d overland (both are controlled by same\n    ! rt_option flag). Remove this hard-coded option when rt_option=2 is fixed for subsurface.\n    !     if(subrt_static%rt_option .eq. 1) then\n    CALL ROUTE_SUBSURFACE1(subrt_data%properties%distance_to_neighbor, &\n                           subrt_data%properties%zwattablrt, &\n                           subrt_data%properties%lksatrt, subrt_data%properties%nexprt, &\n                           subrt_data%properties%soldeprt, &\n                           subrt_static%IXRT, subrt_static%JXRT, &\n                           subrt_data%properties%surface_slope, &\n                           subrt_data%properties%max_surface_slope_index, &\n                           CWATAVAIL, SUBDT, &\n                           subrt_data%state%qsubbdryrt, subrt_data%state%qsubbdrytrt, &\n                           subrt_data%state%qsubrt)\n    !     else\n    !        CALL ROUTE_SUBSURFACE2(subrt_data%properties%distance_to_neighbor,subrt_data%properties%zwattablrt, &\n        !               subrt_data%state%qsubrt, subrt_data%properties%surface_slope_x, subrt_data%properties%surface_slope_y, &\n        !               subrt_data%properties%lksatrt, subrt_data%properties%soldeprt, subrt_static%IXRT, subrt_static%JXRT, subrt_data%state%qsubbdryrt, subrt_data%state%qsubbdrytrt, &\n        !               CWATAVAIL,SUBDT)\n    !     end if\n\n#ifdef HYDRO_D\n    write(6,*) \"finish calling ROUTE_SUBSURFACE \", subrt_static%rt_option\n#endif\n\n\n    !!!! Update soil moisture fields with subsurface flow...\n\n    !!!! Loop through subsurface routing domain...\n    DO I=1,subrt_static%IXRT\n        DO J=1,subrt_static%JXRT\n\n            !!DJG Check for courant condition violation...put limit on qsub\n            !!DJG QSUB HAS units of m^3/s SUBFLO has units of m\n\n            ! ADCHANGE: Moved this constraint to the ROUTE_SUBSURFACE routines\n            !IF (CWATAVAIL(i,j).le.ABS(qsubrt(i,j))/subrt_data%properties%distance_to_neighbor(i,j,9)*SUBDT) THEN\n            !  subrt_data%state%qsubrt(i,j) = -1.0*CWATAVAIL(i,j)\n            !  SUBFLO = subrt_data%state%qsubrt(i,j)  !Units of qsubrt converted via CWATAVAIL\n            !ELSE\n            SUBFLO = subrt_data%state%qsubrt(i,j) / subrt_data%properties%distance_to_neighbor(i,j,9) * SUBDT !Convert qsubrt from m^3/s to m\n            !END IF\n\n            WATAVAIL = 0.  !Initialize to 0. for every cell...\n\n\n            !!DJG Begin loop through soil profile to adjust soil water content\n            !!DJG based on subsfc flow (SUBFLO)...\n\n            IF (SUBFLO.GT.0) THEN ! Increase soil moist for +SUBFLO (Inflow)\n\n                ! Loop through soil layers from bottom to top\n                DO KK=subrt_static%nsoil,1,-1\n\n\n                    ! Check for saturated layers\n                    IF (subrt_data%grid_transform%smcrt(I,J,KK) .GE. subrt_data%grid_transform%smcmaxrt(I,J,KK)) THEN\n                        IF (subrt_data%grid_transform%smcrt(I,J,KK) .GT. subrt_data%grid_transform%smcmaxrt(I,J,KK)) THEN\n                            print *, \"FATAL ERROR: Subsfc acct. SMCMAX exceeded...\", &\n                                subrt_data%grid_transform%smcrt(I,J,KK), subrt_data%grid_transform%smcmaxrt(I,J,KK),KK,i,j\n                            call hydro_stop(\"In SUBSFC_RTNG() - SMCMAX exceeded\")\n                        ELSE\n                        END IF\n                    ELSE\n                        WATAVAIL = (subrt_data%grid_transform%smcmaxrt(I,J,KK)-subrt_data%grid_transform%smcrt(I,J,KK))*subrt_data%properties%sldpth(KK)\n                        IF (WATAVAIL.GE.SUBFLO) THEN\n                            subrt_data%grid_transform%smcrt(I,J,KK) = subrt_data%grid_transform%smcrt(I,J,KK) + SUBFLO/subrt_data%properties%sldpth(KK)\n                            SUBFLO = 0.\n                        ELSE\n                            SUBFLO = SUBFLO - WATAVAIL\n                            subrt_data%grid_transform%smcrt(I,J,KK) = subrt_data%grid_transform%smcmaxrt(I,J,KK)\n                        END IF\n                    END IF\n\n                    IF (SUBFLO.EQ.0.) EXIT\n                    !                IF (SUBFLO.EQ.0.) goto 669\n\n                END DO      ! END DO FOR SOIL LAYERS\n\n                669           continue\n\n                ! If all layers sat. add remaining subflo to infilt. excess...\n                IF (KK.eq.0.AND.SUBFLO.gt.0.) then\n                    subrt_input%infiltration_excess(I,J) = subrt_input%infiltration_excess(I,J) + SUBFLO*1000.    !Units = mm\n                    SUBFLO=0.\n                END IF\n\n                !DJG Error trap...\n                if (subflo.ne.0.) then\n#ifdef HYDRO_D\n                    print *, \"Subflo (+) not expired...:\",subflo, i, j, kk, subrt_data%grid_transform%smcrt(i,j,1), &\n                        subrt_data%grid_transform%smcrt(i,j,2), subrt_data%grid_transform%smcrt(i,j,3), &\n                        subrt_data%grid_transform%smcrt(i,j,4), subrt_data%grid_transform%smcrt(i,j,5), &\n                        subrt_data%grid_transform%smcrt(i,j,6), subrt_data%grid_transform%smcrt(i,j,7), &\n                        subrt_data%grid_transform%smcrt(i,j,8), \"SMCMAX\", subrt_data%grid_transform%smcmaxrt(i,j,1)\n#endif\n                end if\n\n\n            ELSE IF (SUBFLO.LT.0) THEN    ! Decrease soil moist for -SUBFLO (Drainage)\n\n\n                !DJG loop from satlyr back down and subtract out subflo as necess...\n                !    now set to SMCREF, 8/24/07\n                !DJG and then using unsat cond as opposed to Ksat...\n\n                DO KK=SATLYRCHK(I,J),subrt_static%nsoil\n                    WATAVAIL = (subrt_data%grid_transform%smcrt(I,J,KK) - subrt_data%grid_transform%smcrefrt(I,J,KK)) * subrt_data%properties%sldpth(KK)\n                    IF (WATAVAIL.GE.ABS(SUBFLO)) THEN\n                        !?yw mod                 IF (WATAVAIL.GE.(ABS(SUBFLO)+0.000001) ) THEN\n                        subrt_data%grid_transform%smcrt(I,J,KK) = subrt_data%grid_transform%smcrt(I,J,KK) + SUBFLO/subrt_data%properties%sldpth(KK)\n                        SUBFLO=0.\n                    ELSE     ! Since subflo is small on a time-step following is unlikely...\n                        subrt_data%grid_transform%smcrt(I,J,KK) = subrt_data%grid_transform%smcrefrt(I,J,KK)\n                        SUBFLO=SUBFLO+WATAVAIL\n                    END IF\n                    IF (SUBFLO.EQ.0.) EXIT\n                    !                IF (SUBFLO.EQ.0.) goto 668\n\n                END DO  ! END DO FOR SOIL LAYERS\n                668        continue\n\n\n                !DJG Error trap...\n                if(abs(subflo) .le. 1.E-7 )  subflo = 0.0  !truncate residual to 1E-7 prec.\n\n                if (subflo.ne.0.) then\n#ifdef HYDRO_D\n                    print *, \"Subflo (-) not expired:\",i,j,subflo,CWATAVAIL(i,j)\n                    print *, \"zwatabl = \", subrt_data%properties%zwattablrt(i,j)\n                    print *, \"QSUBRT(I,J)=\",subrt_data%state%qsubrt(i,j)\n                    print *, \"WATAVAIL = \",WATAVAIL, \"kk=\",kk\n                    print *\n#endif\n                end if\n\n\n\n            END IF  ! end if for +/- SUBFLO soil moisture accounting...\n\n\n\n\n        END DO        ! END DO X dim\n    END DO          ! END DO Y dim\n    !!!! End loop through subsurface routing domain...\n\n#ifdef MPP_LAND\n    do i = 1, subrt_static%nsoil\n        call MPP_LAND_COM_REAL(subrt_data%grid_transform%smcrt(:,:,i),subrt_static%IXRT,subrt_static%JXRT,99)\n    end DO\n#endif\n\n#ifdef HYDRO_D\n    ! ADCHANGE: START Final water balance variables\n    ! ALL VARS in MM\n    suminfxsrt2 = 0.\n    qbdry2 = 0.\n    smctot2 = 0.\n    sumqsubrt2 = 0.\n    do i=1,subrt_static%IXRT\n        do j=1,subrt_static%JXRT\n            suminfxsrt2 = suminfxsrt2 + subrt_input%infiltration_excess(I,J) / float(subrt_static%IXRT*subrt_static%JXRT)  !\n            qbdry2 = qbdry2 + subrt_data%state%qsubbdryrt(i,j)/subrt_data%properties%distance_to_neighbor(i,j,9)*SUBDT*1000. / float(subrt_static%IXRT*subrt_static%JXRT)\n            sumqsubrt2 = sumqsubrt2 + subrt_data%state%qsubrt(i,j)/subrt_data%properties%distance_to_neighbor(i,j,9)*SUBDT*1000. / float(subrt_static%IXRT*subrt_static%JXRT)\n            do kk=1,subrt_static%nsoil\n                smctot2 = smctot2 + subrt_data%grid_transform%smcrt(I,J,KK)*subrt_data%properties%sldpth(KK)*1000. / float(subrt_static%IXRT*subrt_static%JXRT)\n            end do\n        end do\n    end do\n\n#ifdef MPP_LAND\n    ! not tested\n    CALL sum_real1(suminfxsrt2)\n    CALL sum_real1(qbdry2)\n    CALL sum_real1(sumqsubrt2)\n    CALL sum_real1(smctot2)\n    suminfxsrt2 = suminfxsrt2/float(numprocs)\n    qbdry2 = qbdry2/float(numprocs)\n    sumqsubrt2 = sumqsubrt2/float(numprocs)\n    smctot2 = smctot2/float(numprocs)\n#endif\n\n#ifdef MPP_LAND\n    if (my_id .eq. IO_id) then\n#endif\n        print *, \"SUBSFC Routing Mass Bal: \"\n        print *, \"WB_SUB!QsubDiff\", sumqsubrt2-sumqsubrt1\n        print *, \"WB_SUB!Qsub1\", sumqsubrt1\n        print *, \"WB_SUB!Qsub2\", sumqsubrt2\n        print *, \"WB_SUB!InfxsDiff\", suminfxsrt2-suminfxsrt1\n        print *, \"WB_SUB!Infxs1\", suminfxsrt1\n        print *, \"WB_SUB!Infxs2\", suminfxsrt2\n        print *, \"WB_SUB!QbdryDiff\", qbdry2-qbdry1\n        print *, \"WB_SUB!Qbdry1\", qbdry1\n        print *, \"WB_SUB!Qbdry2\", qbdry2\n        print *, \"WB_SUB!SMCDiff\", smctot2-smctot1\n        print *, \"WB_SUB!SMC1\", smctot1\n        print *, \"WB_SUB!SMC2\", smctot2\n        print *, \"WB_SUB!Residual\", sumqsubrt1 - ( (suminfxsrt2-suminfxsrt1) &\n            + (smctot2-smctot1) )\n#ifdef MPP_LAND\n    endif\n#endif\n    ! END Final water balance variables\n#endif\n\n\n    !DJG ----------------------------------------------------------------\nEND SUBROUTINE SUBSFC_RTNG\n!DJG ----------------------------------------------------------------\n\n\n!DJG ------------------------------------------------------------------------\n!DJG  SUBSURFACE FINDZWAT\n!DJG ------------------------------------------------------------------------\nSUBROUTINE FINDZWAT(IXRT,JXRT,NSOIL,SMCRT,SMCMAXRT,SMCREFRT, &\n        SMCWLTRT,ZSOIL,SATLYRCHK,ZWATTABLRT,CWATAVAIL,&\n        SLDPTH)\n\n    IMPLICIT NONE\n\n    !DJG -------- DECLARATIONS ------------------------\n\n    INTEGER, INTENT(IN) :: IXRT,JXRT,NSOIL\n    REAL, INTENT(IN), DIMENSION(IXRT,JXRT,NSOIL) :: SMCMAXRT\n    REAL, INTENT(IN), DIMENSION(IXRT,JXRT,NSOIL) :: SMCREFRT\n    REAL, INTENT(IN), DIMENSION(IXRT,JXRT,NSOIL) :: SMCRT\n    REAL, INTENT(IN), DIMENSION(IXRT,JXRT,NSOIL) :: SMCWLTRT\n    REAL, INTENT(IN), DIMENSION(NSOIL)        :: ZSOIL\n    REAL, INTENT(IN), DIMENSION(NSOIL)        :: SLDPTH\n    REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)   :: ZWATTABLRT\n    REAL, INTENT(OUT), DIMENSION(IXRT,JXRT)   :: CWATAVAIL\n    INTEGER, INTENT(OUT), DIMENSION(IXRT,JXRT) :: SATLYRCHK\n\n    !DJG Local Variables\n    INTEGER :: KK,i,j\n\n    !!!! Find saturated layer depth...\n    ! Loop through domain to determine sat. layers and assign wat tbl depth...\n\n\n    SATLYRCHK = 0  !set flag for sat. layers\n    CWATAVAIL = 0.  !set wat avail for subsfc rtng = 0.\n\n    DO J=1,JXRT\n        DO I=1,IXRT\n\n            ! Loop through soil layers from bottom to top\n            DO KK=NSOIL,1,-1\n\n                ! Check for saturated layers\n                ! Add additional logical check to ensure water is 'available' for routing,\n                !  (i.e. not 'frozen' or otherwise immobile)\n                !                IF (SMCRT(I,J,KK).GE.SMCMAXRT(I,J,KK).AND.SMCMAXRT(I,J,KK) &\n                    !                  .GT.SMCWLTRT(I,J,KK)) THEN\n                IF ( (SMCRT(I,J,KK).GE.SMCREFRT(I,J,KK)).AND.(SMCREFRT(I,J,KK) &\n                        .GT.SMCWLTRT(I,J,KK)) ) THEN\n                    ! Add additional check to ensure saturation from bottom up only...8/8/05\n                    IF((SATLYRCHK(I,J).EQ.KK+1) .OR. (KK.EQ.NSOIL) ) SATLYRCHK(I,J) = KK\n                END IF\n\n            END DO\n\n\n            ! Designate ZWATTABLRT based on highest sat. layer and\n            ! Define amount of water avail for subsfc routing on each gridcell (CWATAVAIL)\n            !  note: using a 'field capacity' value of SMCREF as lower limit...\n\n            IF (SATLYRCHK(I,J).ne.0) then\n                IF (SATLYRCHK(I,J).ne.1) then  ! soil column is partially sat.\n                    ZWATTABLRT(I,J) = -ZSOIL(SATLYRCHK(I,J)-1)\n                    !DJG 2/16/2016 fix                  DO KK=SATLYRCHK(I,J),NSOIL\n                    !old                   CWATAVAIL(I,J) = (SMCRT(I,J,SATLYRCHK(I,J))-&\n                        !old                                    SMCREFRT(I,J,SATLYRCHK(I,J))) * &\n                        !old                                    (ZSOIL(SATLYRCHK(I,J)-1)-ZSOIL(NSOIL))\n                    !DJG 2/16/2016 fix                    CWATAVAIL(I,J) = CWATAVAIL(I,J)+(SMCRT(I,J,KK)- &\n                        !DJG 2/16/2016 fix                                     SMCREFRT(I,J,KK))*SLDPTH(KK)\n                    !DJG 2/16/2016 fix                  END DO\n\n\n                ELSE  ! soil column is fully saturated to sfc.\n                    ZWATTABLRT(I,J) = 0.\n                    !DJG 2/16/2016 fix                  DO KK=SATLYRCHK(I,J),NSOIL\n                    !DJG 2/16/2016 fix                    CWATAVAIL(I,J) = (SMCRT(I,J,KK)-SMCREFRT(I,J,KK))*SLDPTH(KK)\n                    !DJG 2/16/2016 fix                  END DO\n                END IF\n                !DJG 2/16/2016 fix accumulation of CWATAVAIL...\n                DO KK=SATLYRCHK(I,J),NSOIL\n                    CWATAVAIL(I,J) = CWATAVAIL(I,J)+(SMCRT(I,J,KK)- &\n                        SMCREFRT(I,J,KK))*SLDPTH(KK)\n                END DO\n            ELSE  ! no saturated layers...\n                ZWATTABLRT(I,J) = -ZSOIL(NSOIL)\n                SATLYRCHK(I,J) = NSOIL + 1\n            END IF\n\n        END DO\n    END DO\n\n\n    !DJG ----------------------------------------------------------------\nEND SUBROUTINE FINDZWAT\n!DJG ----------------------------------------------------------------\n\n!===================================================================================================\n! Subroutine Name:\n!   subroutine ROUTE_SUBSURFACE1\n! Author(s)/Contact(s):\n!   D. Gochis <gochis><ucar><edu>\n! Abstract:\n!   Calculates single direction (steepest slope) subsurface flow\n! History Log:\n!   3/27/03 -Created, DG.\n!   1/05/04 -Modified, DG.\n!   1/07/19 -Modified, AD.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\n!  - Adapted from Wigmosta, 1994\n!  - Returns qsub=DQSUB which in turn becomes SUBFLO in head calc.\n!===================================================================================================\nSUBROUTINE ROUTE_SUBSURFACE1(dist, z, latksat, nexp, soldep, &\n                             XX, YY, SO8RT, SO8RT_D, &\n                             CWATAVAIL, SUBDT, QSUBDRY, QSUBDRYT, qsub)\n#ifdef MPP_LAND\n   use module_mpp_land, only: left_id, down_id, right_id, up_id, &\n                              mpp_land_com_real8, my_id, mpp_land_com_real\n#endif\n   use module_hydro_stop, only:HYDRO_stop\n\n   implicit none\n\n   ! Passed variables\n   integer, intent(in) :: XX,YY\n   ! Passed arrays\n   real, intent(in), dimension(XX,YY,9)    :: dist ! distance to neighbor cells (m)\n   real, intent(in), dimension(XX,YY)      :: z ! depth to water table (m)\n   real, intent(in), dimension(XX,YY)      :: latksat\n                                              ! lateral saturated hydraulic conductivity (m/s)\n   real, intent(in), dimension(XX,YY)      :: nexp ! latksat decay coefficient\n   real, intent(in), dimension(XX,YY)      :: soldep ! soil depth (m)\n   real, intent(in), dimension(XX,YY,8)    :: SO8RT ! terrain slope in all directions (m/m)\n   integer, intent(in), dimension(XX,YY,3) :: SO8RT_D ! steepest terrain slope cell (i, j, index)\n   real, intent(in), dimension(XX,YY)      :: CWATAVAIL ! water available for routing (m)\n   real, intent(in)                        :: SUBDT ! subsurface routing timestep (s)\n   real, intent(inout), dimension(XX,YY)   :: QSUBDRY ! subsurface flow at domain boundary (m3/s)\n   real, intent(inout)                     :: QSUBDRYT\n                                              ! total subsurface flow outside of domain (m3/s)\n   real, intent(out), dimension(XX,YY)     :: qsub ! subsurface flow outside of cell (m3/s)\n\n   ! Local variables\n   integer :: i, j ! indices for local loops\n   integer :: IXX0, JYY0, index ! i, j, and direction index for steepest slope neighbor\n   real    :: beta ! total head slope (m/m)\n   real    :: hh ! interim variable for subsurface solution per DHSVM (dimensionless)\n   real    :: gamma ! interim variable for subsurface solution per DHSVM (m3/s)\n   real    :: ksat ! saturated hydraulic conductivity (m/s)\n   real    :: qqsub ! net subsurface flow out of cell (m3/s?)\n   real    :: waterToRoute ! total water to route from cell (m)\n   ! Local arrays\n   real*8, DIMENSION(XX,YY) :: qsub_tmp, QSUBDRY_tmp ! temp trackers for fluxes (m3/s)\n   ! Local parameters\n   real :: tmp_dist(9)\n\n   ! Initialize temp variables\n   qsub_tmp = 0.\n   QSUBDRY_tmp = 0.\n\n#ifdef HYDRO_D\n   write(6,*) \"call subsurface routing xx= , yy =\", yy, xx\n#endif\n\n   do j=2,YY-1 ! start j loop\n\n      do i=2,XX-1 ! start i loop\n\n         if (i.ge.2.AND.i.le.XX-1.AND.j.ge.2.AND.j.le.YY-1) then !if grdcl chk\n            ! check for boundary grid point?\n\n            ! Set initial guess values for steepest slope neighbor based on terrain\n            IXX0 = SO8RT_D(i,j,1)\n            JYY0 = SO8RT_D(i,j,2)\n            index = SO8RT_D(i,j,3)\n            !beta = -1.0\n\n            ! ADCHANGE: Always call routine to check for steepest elev+head slope\n            ! Updates IXX0, JYY0, index, and beta for steepest slope neighbor.\n            ! Note that beta will be -1 if steepest slope cannot be found.\n            tmp_dist = dist(i,j,:)\n            call GETSUB8(i, j, XX, YY, Z, so8rt, tmp_dist, &\n                         IXX0, JYY0, index, beta)\n\n            if (dist(i,j,index) .le. 0) then\n                write(6,*) \"FATAL ERROR: dist(i,j,index) is <= zero \"\n                call hydro_stop(\"In ROUTE_SUBSURFACE1() - dist(i,j,index) is <= zero \")\n            endif\n            if (soldep(i,j) .eq. 0) then\n                call hydro_stop(\"In ROUTE_SUBSURFACE1() - soldep is = zero\")\n            endif\n\n            if (beta .gt. 0) then            !if-then for flux calc\n               if (beta .lt. 1E-20 ) then\n#ifdef HYDRO_D\n                  print*, \"Message: beta need to be reset to 1E-20. beta = \",beta\n#endif\n                  beta = 1E-20\n               endif\n\n               ! Do the rest if the lowest grid can be found.\n               hh = ( 1 - ( z(i,j) / soldep(i,j) ) ) ** nexp(i,j)\n               ksat = latksat(i,j)\n\n               if (hh .lt. 0.) then\n                  print *, \"hsub<0 at gridcell...\", i,j,hh,z(i+1,j),z(i,j), &\n                       soldep(i,j)\n                  call hydro_stop(\"In ROUTE_SUBSURFACE1() - hsub<0 at gridcell \")\n               endif\n\n               ! Calculate flux from cell\n               ! AD_NOTE: gamma and qqsub are negative when flow is out of cell\n               gamma = -1.0 * ( (dist(i,j,index) * ksat * soldep(i,j)) / nexp(i,j) ) * beta\n               qqsub = gamma * hh\n\n               ! AD_NOTE: Moved this water available constraint from outside qsub calc loop\n               ! to inside to better account for adjustments to adjacent cells.\n               ! Calculate total water to route (where dist(i,j,9) is cell area):\n               waterToRoute = ABS(qqsub) / dist(i,j,9) * SUBDT\n               if ( (qqsub .le. 0.0) .and. (CWATAVAIL(i,j) .lt. waterToRoute) ) THEN\n                  qqsub = -1.0 * CWATAVAIL(i,j) * dist(i,j,9) / SUBDT\n               endif\n\n               ! Remove from cell qsub to track net fluxes over full i, j loop\n               ! (remember: qqsub is negative when flow is out of cell!)\n               qsub(i,j) = qsub(i,j) + qqsub\n               ! Add to neighbor cell qsub to track net fluxes over full i, j loop\n               qsub_tmp(ixx0,jyy0) = qsub_tmp(ixx0,jyy0) - qqsub\n\n               !DJG Error Checks...\n               if (qqsub .gt. 0) then\n                  print*, \"FATAL ERROR: qqsub should be negative, qqsub =\",qqsub,&\n                     \"gamma=\",gamma,\"hh=\",hh,\"beta=\",beta,&\n                     \"so8RT=\",so8RT(i,j,index),\"latksat=\",ksat, &\n                     \"tan(beta)=\",tan(beta),i,j,z(i,j),z(IXX0,JYY0)\n                  print*, \"ixx0=\",ixx0, \"jyy0=\",jyy0\n                  print*, \"soldep =\", soldep(i,j), \"nexp=\",nexp(i,j)\n                  call hydro_stop(\"In ROUTE_SUBSURFACE1() - qqsub should be negative\")\n               endif\n\n               ! Make boundary adjustments if cells are on edge of local domain\n#ifdef MPP_LAND\n               if ( ((ixx0.eq.XX).and.(right_id .lt. 0)) .or. &\n                  ((ixx0.eq.1) .and.(left_id  .lt. 0)) .or. &\n                  ((jyy0.eq.1) .and.(down_id  .lt. 0)) .or. &\n                  ((JYY0.eq.YY).and.(up_id    .lt. 0)) ) then\n#else\n               if ((ixx0.eq.1).or.(ixx0.eq.xx).or.(jyy0.eq.1).or.(jyy0.eq.yy)) then\n#endif\n                  ! If on edge, move flux tracking BACK from neighbor cell qsub and into\n                  ! boundary qsub (note: qsubdry is negative and qqsub is negative, so we\n                  ! are making it a bigger sink here)\n                  qsub_tmp(ixx0,jyy0) = qsub_tmp(ixx0,jyy0) + qqsub\n                  QSUBDRY_tmp(ixx0,jyy0) = QSUBDRY_tmp(ixx0,jyy0) + qqsub\n                  ! Add to total BOUNDARY qsub\n                  QSUBDRYT = QSUBDRYT + qqsub\n               endif\n\n            endif  ! end if for flux calc\n\n         endif   ! end if for gridcell check\n\n      end do  ! end i loop\n\n   end do   ! end j loop\n\n#ifdef MPP_LAND\n   call MPP_LAND_COM_REAL8(qsub_tmp,XX,YY,1)\n   call MPP_LAND_COM_REAL8(QSUBDRY_tmp,XX,YY,1)\n#endif\n\n   ! Sum grids to get net of self and neighbor fluxes after looping through all cells\n   ! (i.e., net of out-flux from one cell and in-flux from its neighbor cell)\n   qsub = qsub + qsub_tmp\n   QSUBDRY = QSUBDRY + QSUBDRY_tmp\n\n\n#ifdef MPP_LAND\n   call MPP_LAND_COM_REAL(qsub,XX,YY,99)\n   call MPP_LAND_COM_REAL(QSUBDRY,XX,YY,99)\n#endif\n\n   return\n\nend subroutine ROUTE_SUBSURFACE1\n\n!===================================================================================================\n\n\n\n!DJG ----------------------------------------------------------------\n!DJG     SUBROUTINE ROUTE_SUBSURFACE2\n!DJG ----------------------------------------------------------------\n\nSUBROUTINE ROUTE_SUBSURFACE2(                                 &\n        dist,z,qsub,sox,soy,                                   &\n        latksat,soldep,XX,YY,QSUBDRY,QSUBDRYT,CWATAVAIL,   &\n        SUBDT)\n\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    !\n    !  Subroutine to route subsurface flow through the watershed\n    !DJG ----------------------------------------------------------------\n    !\n    !  Called from: main.f (Noah_router_driver)\n    !\n    !  Returns: qsub=DQSUB   which in turn becomes SUBFLO in head calc.\n    !\n    !  Created:    D. Gochis                           3/27/03\n    !              Adaptded from Wigmosta, 1994\n    !\n    !  Modified:   D. Gochis                           1/05/04\n    !\n    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n#ifdef MPP_LAND\n    use module_mpp_land, only: left_id,down_id,right_id,&\n        up_id,mpp_land_com_real,MPP_LAND_UB_COM, &\n        MPP_LAND_LR_COM,mpp_land_com_integer\n#endif\n    use module_hydro_stop, only:HYDRO_stop\n\n    IMPLICIT NONE\n\n\n    !! Declare Passed variables\n\n    INTEGER, INTENT(IN) :: XX,YY\n\n    !! Declare passed arrays\n\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: z\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: sox\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: soy\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: latksat\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: CWATAVAIL\n    REAL, INTENT(IN), DIMENSION(XX,YY) :: soldep\n    REAL, INTENT(OUT), DIMENSION(XX,YY) :: qsub\n    REAL, INTENT(INOUT), DIMENSION(XX,YY) :: QSUBDRY\n    REAL, INTENT(INOUT) :: QSUBDRYT\n    REAL, INTENT(IN) :: SUBDT\n    real, intent(in), dimension(xx,yy,9) :: dist\n\n    !!! Declare Local Variables\n\n    REAL :: dzdx,dzdy,beta,gamma\n    REAL :: qqsub,hh,ksat, gsize\n\n    INTEGER :: i,j\n    !!! Initialize variables\n    REAL, PARAMETER :: nexp=1.0      ! local power law exponent\n    qsub = 0.                        ! initialize flux = 0. !DJG 5 May 2014\n\n    !yw        soldep = 2.\n\n\n    ! Begin Subsurface routing\n\n    !!! Loop to route water in x-direction\n    do j=1,YY\n        do i=1,XX\n            ! check for boundary grid point?\n            if (i.eq.XX) GOTO 998\n            gsize = dist(i,j,3)\n\n            dzdx= (z(i,j) - z(i+1,j))/gsize\n            beta=sox(i,j) + dzdx + 1E-30\n            if (abs(beta) .lt. 1E-20) beta=1E-20\n            if (beta.lt.0) then\n                !yw            hh=(1-(z(i+1,j)/soldep(i,j)))**nexp\n                hh=(1-(z(i+1,j)/soldep(i+1,j)))**nexp\n                ! Change later to use mean Ksat of two cells\n                ksat=latksat(i+1,j)\n            else\n                hh=(1-(z(i,j)/soldep(i,j)))**nexp\n                ksat=latksat(i,j)\n            end if\n\n            if (hh .lt. 0.) then\n                print *, \"hsub<0 at gridcell...\", i,j,hh,z(i+1,j),z(i,j), &\n                    soldep(i,j),nexp\n                call hydro_stop(\"In ROUTE_SUBSURFACE2() - hsub<0 at gridcell\")\n            end if\n\n            !Err. tan slope          gamma=-1.*((gsize*ksat*soldep(i,j))/nexp)*tan(beta)\n            !AD_CHANGE: beta is already a slope so no tan (consistent with ROUTE_SUBSURFACE1)\n            gamma=-1.*((gsize*ksat*soldep(i,j))/nexp)*beta\n            !DJG lacks tan(beta) of original Wigmosta version          gamma=-1.*((gsize*ksat*soldep(i,j))/nexp)*beta\n\n            qqsub = gamma * hh\n            qsub(i,j) = qsub(i,j) + qqsub\n            qsub(i+1,j) = qsub(i+1,j) - qqsub\n\n            ! Boundary adjustments\n#ifdef MPP_LAND\n            if ((i.eq.1).AND.(beta.lt.0.).and.(left_id.lt.0)) then\n#else\n                if ((i.eq.1).AND.(beta.lt.0.)) then\n#endif\n                    qsub(i,j) = qsub(i,j) - qqsub\n                    QSUBDRY(i,j) = QSUBDRY(i,j) - qqsub\n                    QSUBDRYT = QSUBDRYT - qqsub\n#ifdef MPP_LAND\n                else if ((i.eq.(xx-1)).AND.(beta.gt.0.) &\n                        .and.(right_id.lt.0) ) then\n#else\n                else if ((i.eq.(xx-1)).AND.(beta.gt.0.)) then\n#endif\n                    qsub(i+1,j) = qsub(i+1,j) + qqsub\n                    QSUBDRY(i+1,j) = QSUBDRY(i+1,j) + qqsub\n                    QSUBDRYT = QSUBDRYT + qqsub\n                end if\n\n                998       continue\n\n                !! End loop to route sfc water in x-direction\n        end do\n    end do\n\n#ifdef MPP_LAND\n    call MPP_LAND_LR_COM(qsub,XX,YY,99)\n    call MPP_LAND_LR_COM(QSUBDRY,XX,YY,99)\n#endif\n\n\n    !!! Loop to route water in y-direction\n    do j=1,YY\n        do i=1,XX\n            ! check for boundary grid point?\n            if (j.eq.YY) GOTO 999\n            gsize = dist(i,j,1)\n\n            dzdy= (z(i,j) - z(i,j+1))/gsize\n            beta=soy(i,j) + dzdy + 1E-30\n            if (abs(beta) .lt. 1E-20) beta=1E-20\n            if (beta.lt.0) then\n                !yw            hh=(1-(z(i,j+1)/soldep(i,j)))**nexp\n                hh=(1-(z(i,j+1)/soldep(i,j+1)))**nexp\n                ksat=latksat(i,j+1)\n            else\n                hh=(1-(z(i,j)/soldep(i,j)))**nexp\n                ksat=latksat(i,j)\n            end if\n\n            if (hh .lt. 0.) GOTO 999\n\n            !Err. tan slope          gamma=-1.*((gsize*ksat*soldep(i,j))/nexp)*tan(beta)\n            gamma=-1.*((gsize*ksat*soldep(i,j))/nexp)*beta\n\n            qqsub = gamma * hh\n            qsub(i,j) = qsub(i,j) + qqsub\n            qsub(i,j+1) = qsub(i,j+1) - qqsub\n\n            ! Boundary adjustments\n\n#ifdef MPP_LAND\n            if ((j.eq.1).AND.(beta.lt.0.).and.(down_id.lt.0)) then\n#else\n            if ((j.eq.1).AND.(beta.lt.0.)) then\n#endif\n                qsub(i,j) = qsub(i,j) - qqsub\n                QSUBDRY(i,j) = QSUBDRY(i,j) - qqsub\n                QSUBDRYT = QSUBDRYT - qqsub\n#ifdef MPP_LAND\n            else if ((j.eq.(yy-1)).AND.(beta.gt.0.)  &\n                .and. (up_id.lt.0) ) then\n#else\n            else if ((j.eq.(yy-1)).AND.(beta.gt.0.)) then\n#endif\n                qsub(i,j+1) = qsub(i,j+1) + qqsub\n                QSUBDRY(i,j+1) = QSUBDRY(i,j+1) + qqsub\n                QSUBDRYT = QSUBDRYT + qqsub\n            end if\n\n            999       continue\n\n                !! End loop to route sfc water in y-direction\n        end do\n    end do\n\n#ifdef MPP_LAND\n    call MPP_LAND_UB_COM(qsub,XX,YY,99)\n    call MPP_LAND_UB_COM(QSUBDRY,XX,YY,99)\n#endif\n\n    return\n    !DJG------------------------------------------------------------\nend subroutine ROUTE_SUBSURFACE2\n!DJG------------------------------------------------------------\n"
  },
  {
    "path": "src/Routing/Overland/CMakeLists.txt",
    "content": "add_library(hydro_routing_overland STATIC\n        module_overland_control.F90\n        module_overland_mass_balance.F90\n        module_overland_streams_and_lakes.F90\n        module_overland_routing_properties.F90\n        module_overland.F90\n)\n"
  },
  {
    "path": "src/Routing/Overland/Makefile",
    "content": "#simple compilation test for modules in overland routing\n\ninclude ../../macros\n\n# Settings for testing with ifort\nFC=ifort\nFFLAGS=-c -free -O3\n\n# Setting for testing with gfortran\n#FC=gfortran\n#FFLAGS=-c --free-form -std=f2003 -O3\n\nFLFLAGS=\n\n.PHONY: all mod test\n\nall: mod\n\nmod:\n\t#Build each sub module then build the module that depends on all sub modules\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) $(F90FLAGS) $(LDFLAGS) $(MODFLAGS) -I$(NETCDFINC) module_overland_control.F90\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) $(F90FLAGS) $(LDFLAGS) $(MODFLAGS) -I$(NETCDFINC) module_overland_streams_and_lakes.F90\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) $(F90FLAGS) $(LDFLAGS) $(MODFLAGS) -I$(NETCDFINC) module_overland_routing_properties.F90\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) $(F90FLAGS) $(LDFLAGS) $(MODFLAGS) -I$(NETCDFINC) module_overland_mass_balance.F90\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) $(F90FLAGS) $(LDFLAGS) $(MODFLAGS) -I$(NETCDFINC) module_overland.F90\n\tar -r ../../lib/libHYDRO.a module_overland_control.o\n\tar -r ../../lib/libHYDRO.a module_overland_streams_and_lakes.o\n\tar -r ../../lib/libHYDRO.a module_overland_routing_properties.o\n\tar -r ../../lib/libHYDRO.a module_overland_mass_balance.o\n\tar -r ../../lib/libHYDRO.a module_overland.o\n\n\tcp *.mod ../../mod\ntest:\n\t$(COMPILER90) $(FFLAGS) overland_tests.F90\n\t$(COMPILER90) -o overland_tests \\\n\t\tmodule_overland_control.o \\\n\t\tmodule_overland_streams_and_lakes.o \\\n\t\tmodule_overland_routing_properties.o \\\n\t\tmodule_overland_mass_balance.o \\\n\t\tmodule_overland.o \\\n\t\toverland_tests.o\nclean:\n\trm -f *.o\n\trm -f *.mod\n\trm -f overland_tests\n"
  },
  {
    "path": "src/Routing/Overland/module_overland.F90",
    "content": "! module overland_data.F\n! Purpose: This module contains the overland struct class and its\n!          sub types. This types hold and catagorize the variables used\n!          in the overland routing code\n! National Water Center\n! Responsibility: Donald W Johnson donald.w.johnson@noaa.gov\n! Authors: Donald W Johnson, Nels Frazier\n\n\nmodule overland_data\n\n    use overland_control\n    use overland_stream_and_lake_interface\n    use overland_routing_properties\n    use overland_mass_balance\n\n    implicit none\n\n    ! hold all variables used in overland routing\n    type overland_struct\n\n        type (overland_control_struct), pointer :: control => null()                             ! i/o and control variables\n        type (overland_stream_and_lake_interface_struct), pointer :: streams_and_lakes => null() ! channel and lake related\n        type (overland_routing_properties_struct), pointer :: properties => null()               ! properties used in routing code\n        type (overland_mass_balance_struct), pointer :: mass_balance => null()                   ! mass balance variables\n\n        ! unused pointer are in an undefined state\n        ! this means the result of calling associated(<pointer>)\n        ! on a pointer that has not been set is unknown\n        ! therefore associated can not be used as a guard\n        ! in inital pointer allocation\n        logical, private :: pointer_allocation_guard = .false.\n\n    contains\n        procedure :: init => overland_struct_init\n        procedure :: destroy => overland_struct_destroy\n    end type overland_struct\n\ncontains\n\n! this procedure allocates the overland_struct\nsubroutine overland_struct_init(this,lsm_ix,lsm_jx,rt_ix,rt_jx)\n    implicit none\n    class(overland_struct), intent(inout) :: this ! the type object being initalized\n    integer, intent(in) :: lsm_ix                    ! lsm x grid size\n    integer, intent(in) :: lsm_jx                    ! lsm y grid size\n    integer, intent(in) :: rt_ix                     ! x grid size\n    integer, intent(in) :: rt_jx                     ! y grid size    allocate( thist%control )\n\n    if (this%pointer_allocation_guard .eqv. .false. ) then\n        this%pointer_allocation_guard = .true.\n        allocate( this%control )\n        if ( .not. associated( this%control) ) then\n            write(0,*) \"Failure to allocate overland control structure\"\n        else\n            call this%control%init(lsm_ix,lsm_jx,rt_ix,rt_jx)\n        end if\n\n        ! allocate the streams and lakes structure\n        allocate( this%streams_and_lakes )\n        if ( .not. associated( this%streams_and_lakes) ) then\n            write(0,*) \"Failure to allocate overland lakes and streams structure\"\n        else\n            call this%streams_and_lakes%init(rt_ix,rt_jx)\n        end if\n\n        ! allocate the properties structure\n        allocate( this%properties )\n        if ( .not. associated( this%properties) ) then\n            write(0,*) \"Failure to allocate overland properties structure\"\n        else\n            call this%properties%init(rt_ix,rt_jx)\n        end if\n\n        ! allocate the mass balance structure\n        allocate( this%mass_balance)\n        if ( .not. associated( this%mass_balance) ) then\n            write(0,*) \"Failure to allocate overland mass balance structure\"\n        else\n            call this%mass_balance%init\n        end if\n    else\n        write(0,*) \"Warning: Attempt to double allocated overland_struct (overland_struct_init)\"\n    end if\n\nend subroutine overland_struct_init\n\n! safely deallocate data from the overland struct\nsubroutine overland_struct_destroy(this)\n    implicit none\n    ! call the destructors\n    class (overland_struct), intent(inout) :: this\n\n    logical :: status = .true.\n\n    if ( associated(this%control ) ) then\n        call this%control%destroy\n        deallocate( this%control )\n    else\n        status = .false.\n    end if\n\n    if ( associated(this%streams_and_lakes) )then\n        call this%streams_and_lakes%destroy\n        deallocate( this%streams_and_lakes )\n    else\n        status = .false.\n    end if\n\n    if ( associated(this%properties) ) then\n        call this%properties%destroy\n        deallocate( this%properties )\n    else\n        status = .false.\n    end if\n\n    if ( associated(this%mass_balance) ) then\n        call this%mass_balance%destroy\n        deallocate( this%mass_balance )\n    else\n        status = .false.\n    end if\n\n    this%pointer_allocation_guard = .false.\n\n    if ( status .eqv. .false. ) then\n        write(0,*) \"Warning: Attempt to double free one or more pointers in (overland_struct_destroy)\"\n    end if\n\nend subroutine overland_struct_destroy\n\nend module overland_data\n"
  },
  {
    "path": "src/Routing/Overland/module_overland_control.F90",
    "content": "! module overland_control_data.F\n! Purpose: This module contains the overland_control_struct class. This types holds\n! the control variables used in the overland routing code\n! National Water Center\n! Responsibility: Donald W Johnson donald.w.johnson@noaa.gov\n! Authors: Donald W Johnson, Nels Frazier\n\nmodule overland_control\n   !type that holds the variables that are inputs to or outputs of the routing code\n   ! along with book keeping variables\n\n   !TODO change output integers to variables that are set dependant on the running system\n   ! example WCOSS\n\n   type overland_control_struct\n      ! outputs\n      !FIXME surface_water_head* should be moved to surface_water_depth since head != depth.  head is elevation + pressure/energy, not depth (FRED and TREY meeting feb 27, 2018)\n      ! replaced with surface_water_head_lsm\n      !real, allocatable, dimension(:,:) :: sfcheadrt\n      ! depth of water on the surface (after routing), passed to the land surface model (mm) on the land surface grid.\n      ! LSM combines this with canopy water for infiltration excess at the next time step.\n      real, allocatable, dimension(:,:) :: surface_water_head_lsm\n\n      ! replaced with surface_water_head_routing\n      !real, allocatable, dimension(:,:) :: sfcheadsubrt\n      ! surface head on the routing grid during integration, input to surface_water_head_lsm for the next time step\n      real, allocatable, dimension(:,:) :: surface_water_head_routing\n\n      !PROPOSED Decouple the surface_water_head_lsm and surface_water_head_routing into a cleaner interface (only one surface_water_head in overland)\n      !This will have to be done once the land surface interface is better hashed out.\n\n      ! inputs\n      !FIXME infiltration_excess is a DEPTH (mm) so be explicit and call it infiltration_excess_depth (FRED and TREY meeting feb 27, 2018)\n      ! replaced with infiltration_excess\n      !real, allocatable, dimension(:,:) :: infxsubrt\n      ! infiltration excess from the land surface model (mm) on the routing grid\n      real, pointer, dimension(:,:) :: infiltration_excess => null()\n\n      ! miscellaneous bookkeeping\n\n      ! DEPRECATE TODO NJF and DJG Feb 13, 2018.  Remove for fall 2019 release\n      ! Is passed around overland routing as an output var, renamed to qsfc in route_overland<1,2>\n      ! qsfc in overland1 is intent(in), overland2 intent(inout). qsfc NEVER USED\n      real, allocatable, dimension(:,:) :: dhrt\n\n      ! replaced with boundary_flux\n      !FIXME NOT A FLUX!!!! rename to a better descriptor (FRED and TREY meeting feb 27, 2018)\n      !real, allocatable, dimension(:,:) :: qbdryrt\n      ! flux of boundary cells at a given time step, + into the domain, - out of the domain (mm)\n      real, allocatable, dimension(:,:) :: boundary_flux\n\n      ! replaced with boundary_flux_total\n      !real :: qbdrytrt\n      ! accumulation of all boundary cell fluxes per time step (<mm>)\n      real :: boundary_flux_total\n\n\n      contains\n      procedure :: init => overland_control_init\n      procedure :: destroy => overland_control_destroy\n      end type overland_control_struct\n\n    contains\n\n! this procedure allocates memory for an overland_control structure that has not been allocated\n! if the structure has been allocated an error will be logged\n\nsubroutine overland_control_init(this,lsm_ix,lsm_jx,rt_ix,rt_jx)\n    implicit none\n    class(overland_control_struct), intent(inout) :: this ! the type object being initalized\n    integer, intent(in) :: lsm_ix                    ! land surface x size\n    integer, intent(in) :: lsm_jx                    ! land surface y size\n    integer, intent(in) :: rt_ix                     ! routing grid x size\n    integer, intent(in) :: rt_jx                     ! routing grid y size\n\n    logical :: allocation_error = .false.\n\n   this%boundary_flux_total = 0.0\n\n    ! allocate surface head\n    if ( .not. allocated(this%surface_water_head_lsm) ) then\n        allocate( this%surface_water_head_lsm(lsm_ix,lsm_jx) )\n        this%surface_water_head_lsm = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate surface head\n\n    if ( .not. allocated(this%surface_water_head_routing) ) then\n        allocate( this%surface_water_head_routing(rt_ix,rt_jx) )\n        this%surface_water_head_routing = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate inflitration excess\n    if ( .not. associated(this%infiltration_excess) ) then\n        allocate( this%infiltration_excess(rt_ix,rt_jx) )\n        this%infiltration_excess = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! DEPRECATE TODO NJF and DJG Feb 13, 2018.  Remove for fall 2019 release\n    ! Is passed around overland routing as an output var, renamed to qsfc in route_overland<1,2>\n    ! qsfc in overland1 is intent(in), overland2 intent(inout). qsfc NEVER USED\n    ! allocate dhrt\n    if ( .not. allocated(this%dhrt) ) then\n         allocate( this%dhrt(rt_ix,rt_jx) )\n         this%dhrt = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate qbdryrt\n    if ( .not. allocated(this%boundary_flux) ) then\n         allocate( this%boundary_flux(rt_ix,rt_jx) )          ! allocate qbdryrt\n         this%boundary_flux = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    if ( allocation_error ) &\n        write(0,*) \"attempt to allocate data in members of overland control structure&\n        &that where allready allocated. The allocated members where not changed\"\n\nend subroutine overland_control_init\n\n! this procedure deallocates and overland_control structure that was initalized with\n! overland_control_init\n\nsubroutine overland_control_destroy(this)\n    implicit none\n    class(overland_control_struct), intent(inout) :: this ! the type object being destroyed\n\n    logical :: allocation_error = .false.\n\n    ! deallocate surface head\n    if ( allocated(this%surface_water_head_lsm) ) then\n        deallocate( this%surface_water_head_lsm )\n    else\n        allocation_error = .true.\n    end if\n\n    ! deallocate surface head\n    if ( allocated(this%surface_water_head_routing) ) then\n        deallocate( this%surface_water_head_routing )\n    else\n        allocation_error = .true.\n    end if\n\n    ! deallocate inflitration excess\n    if ( associated(this%infiltration_excess) ) then\n        deallocate( this%infiltration_excess)\n    else\n        allocation_error = .true.\n    end if\n\n    ! deallocate dhrt\n    if ( allocated(this%dhrt) ) then\n         deallocate( this%dhrt )\n    else\n        allocation_error = .true.\n    end if\n\n    ! deallocate qbdryrt\n    if ( allocated(this%boundary_flux) ) then\n         deallocate( this%boundary_flux )          ! deallocate boundary_flux\n    else\n        allocation_error = .true.\n    end if\n\n    if ( allocation_error ) &\n        write(0,*) \"attempt to deallocate data in members of overland control structure&\n        &that where not allready allocated. The unallocated members where not changed\"\nend subroutine overland_control_destroy\nend module overland_control\n"
  },
  {
    "path": "src/Routing/Overland/module_overland_mass_balance.F90",
    "content": "! module overland_routing_properties_data.F\n! Purpose: This module contains the overland_control_struct class. This types holds\n! the mass blance variables used in the overland routing code\n! National Water Center\n! Responsibility: Donald W Johnson donald.w.johnson@noaa.gov\n! Authors: Donald W Johnson, Nels Frazier\n\nmodule overland_mass_balance\nimplicit none\n\n   ! holds variables used for mass balance\n   type overland_mass_balance_struct\n      ! mass balance\n\n      ! replaced with accumulated_change_in_soil_moisture\n      !real(kind=8) :: dsmctot\n      ! total difference in soil moisture each timestep\n      real(kind=8) :: accumulated_change_in_soil_moisture\n\n      ! replaced with pre_soil_mosture_content\n      !real(kind=8) :: smctot1     ! NEED VARIABLE INFO\n      ! Pre time step soil moisture content accumulator  (mm) TODO verify unit\n      real(kind=8) :: pre_soil_moisture_content\n\n      ! replaced with post_soil_moisture_content\n      !real(kind=8) :: smctot2     ! NEED VARIABLE INFO\n      ! Post time step soil moisture content accumulator (mm) TODO verify unit\n      real(kind=8) :: post_soil_moisture_content\n\n      ! replaced with pre_infiltration_excess\n      !real(kind=8) :: suminfxs1  ! NEED VARIABLE INFO\n\n      ! Pre time step infiltration excess accumulator    (mm) TODO verify unit\n      ! FIX ME -- this variable was declared as real(kind=8) as mis match with parameter specification\n      ! in Noah_distributed_routing.F:OverlandRouting matched it with parameter specified as real(kind=4)\n      ! this caused an implicit cast to single percision float which was required as the value was then used\n      ! in the sum_real mpi call which required single percision. Does this variable need to be a double?\n      real :: pre_infiltration_excess\n\n      ! replaced with post_infiltration_excess\n      !real(kind=8) :: suminfxsrt  ! NEED VARIABLE INFO\n      ! Post time step infiltration excess accumulator   (mm) TODO verify unit\n      ! FIX ME -- this variable was declared as real(kind=8) as mis match with parameter specification\n      ! in Noah_distributed_routing.F:OverlandRouting matched it with parameter specified as real(kind=4)\n      ! this caused an implicit cast to single percision float which was required as the value was then used\n      ! in the sum_real mpi call which required single percision. Does this variable need to be a double?\n      real :: post_infiltration_excess\n\n   contains\n        procedure :: init => overland_mass_balance_init\n        procedure :: destroy => overland_mass_balance_destroy\n    end type overland_mass_balance_struct\n\n    contains\n\n! initalize the mass balance variables\nsubroutine overland_mass_balance_init(this)\n    implicit none\n    class(overland_mass_balance_struct), intent(inout) :: this ! the type object being initalized\n    this%accumulated_change_in_soil_moisture = 0.0\n    this%pre_soil_moisture_content = 0.0\n    this%post_soil_moisture_content = 0.0\n    this%pre_infiltration_excess = 0.0\n    this%post_infiltration_excess = 0.0\nend subroutine overland_mass_balance_init\n\n! none of the mass balance variables are dynamicly allocated if such are added\n! they should be deallocated here\nsubroutine overland_mass_balance_destroy(this)\n    implicit none\n    class(overland_mass_balance_struct), intent(inout) :: this ! the type object being destroyed\nend subroutine overland_mass_balance_destroy\n\n\nend module overland_mass_balance\n"
  },
  {
    "path": "src/Routing/Overland/module_overland_routing_properties.F90",
    "content": "! module overland_routing_properties_data.F\n! Purpose: This module contains the overland_control_struct class. This types holds\n! the physical property variables used in the overland routing code\n! National Water Center\n! Responsibility: Donald W Johnson donald.w.johnson@noaa.gov\n! Authors: Donald W Johnson, Nels Frazier\n\nmodule overland_routing_properties\n    implicit none\n\n   ! holds proprties of the the routing grid needed by overland routing algs\n   type overland_routing_properties_struct\n      integer :: ixrt                                            ! number of cells in x direction on the routing grid\n      integer :: jxrt                                            ! number of cells in y direction on the routing grid\n\n      ! PROPOSED a more logical representation of the grid that is relative to the module would be nice.\n      ! Currently, we are leaving the legacy ixrt/jxrt names to simplify the interaction of these variables in other places in the code.\n      ! At the very least, we need to drop the rt quantifier when we can, since these are clearly ix/jx in the overland_routing structure\n      ! Once the subsurface interface is identified, I think we should revisit these.  And if possible, get away from the x notation, a more clear\n      ! name might be something like these:\n      !integer :: rows                                           ! number of cells in x direction on the routing grid\n      !integer :: columns                                        ! number of cells in y direction on the routing grid\n\n      ! replaced with surface_slope_x\n      !real, allocatable, dimension(:,:) :: soxrt\n      ! terrian slope in the x direction (m/m)\n      real, pointer, dimension(:,:) :: surface_slope_x => null()\n\n      ! replaced with surface_slope_y\n      !real, allocatable, dimension(:,:) :: soyrt\n      ! terrian slope in the y direction (m/m)\n      real, pointer, dimension(:,:) :: surface_slope_y => null()\n\n      ! reaplaced with roughness\n      !real, allocatable, dimension(:,:) :: ovroughrt\n      ! surface roughness parameter for Manning's equation; dissagregated from the land surface model, with adjustment factor applied (none)\n      real, allocatable, dimension(:,:) :: roughness\n\n      ! replaced with retention_depth\n      !real, allocatable, dimension(:,:) :: retdeprt\n      ! minimum amount of surface water required before water is routed as overland flow (mm)\n      real, allocatable, dimension(:,:) :: retention_depth\n\n      ! replaced with surface_slope\n      !real, allocatable, dimension(:,:,:) :: so8rt\n      ! terrain surface slope in 8 ordinal directions (m/m)                                                                  !\n      ! TODO verify this correct, check with Wei?\n      !                      1\n      !                      |\n      !                  8       2\n      !                    \\   /\n      !                 7__     __ 3\n      !\n      !                    /   \\\n      !                   6     4\n      !                      |\n      !                      5\n      !\n      real, pointer, dimension(:,:,:) :: surface_slope => null()\n\n      ! replaced with max_surface_slope_index\n      !integer, allocatable, dimension(:,:,:) :: so8rt_d\n      ! index of neighboring cell in the direction of steepest terrain surface slope, used with surface_slope\n      integer, pointer, dimension(:,:,:) :: max_surface_slope_index => null()\n\n      ! replaced with distance_to_neighbor\n      !real, allocatable, dimension(:,:,:) :: dist\n      ! centerpoint distance to each neighbor (m)\n      real, pointer, dimension(:,:,:) :: distance_to_neighbor => null()\n      ! PROPOSED\n      ! For a regular grid, distance_to_neighbor should be pretty static, right?\n      ! neighbors 1,3,5,7 dist = grid_size\n      ! neighbors 2,4,6,8 dist = sqrt( grid_size^2 + grid_size^2)\n      ! would suggest eliminating this and using two static variables for square grids.\n      ! i.e. direct_neighbor_distance = grid_size\n      !      diagonal_neighbor_distance = sqrt( 2*(grid_size^2) )\n\n      contains\n         procedure :: init => overland_properties_init\n         procedure :: destroy => overland_properties_destory\n   end type overland_routing_properties_struct\n\n   contains\n\n! this procedure allocates memory for an overland_routing_properties structure that has not been allocated\n! if the structure has been allocated an error will be logged\n\nsubroutine overland_properties_init(this,ix,jx)\n    implicit none\n    class(overland_routing_properties_struct), intent(inout) :: this ! the type object being initalized\n    integer, intent(in) :: ix                     ! x grid size\n    integer, intent(in) :: jx                     ! y grid size\n\n    logical :: allocation_error = .false.\n\n    ! record the grid dimensions\n    ! TODO find a better place for this to be stored\n    this%ixrt = ix\n    this%jxrt = jx\n\n    ! allocate x slope\n    if ( .not. associated(this%surface_slope_x) ) then\n        allocate( this%surface_slope_x(ix,jx) )\n        this%surface_slope_x = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate y slope\n    if ( .not. associated(this%surface_slope_y) ) then\n        allocate( this%surface_slope_y(ix,jx) )\n        this%surface_slope_y = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate 8 directional slope\n    if ( .not. associated(this%surface_slope) ) then\n        allocate( this%surface_slope(ix,jx,8) )\n        this%surface_slope = -999\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate slope index\n    if ( .not. associated(this%max_surface_slope_index) ) then\n        allocate( this%max_surface_slope_index(ix,jx,3) )\n        this%max_surface_slope_index = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate surface roughness\n    if ( .not. allocated(this%roughness) ) then\n        allocate( this%roughness(ix,jx) )\n        this%roughness = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate retention depth\n    if ( .not. allocated(this%retention_depth) ) then\n        allocate( this%retention_depth(ix,jx) )\n        this%retention_depth = 0.001   ! units (mm)\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate dist\n    if ( .not. associated(this%distance_to_neighbor) ) then\n        allocate( this%distance_to_neighbor(ix,jx,9) )\n        this%distance_to_neighbor = -999\n    else\n        allocation_error = .true.\n    end if\n\n    if ( allocation_error ) &\n        write(0,*) \"attempt to allocate data in members of overland properties structure&\n        &that where allready allocated. The allocated members where not changed\"\nend subroutine overland_properties_init\n\n! this procedure deallocates and overland_routing_properties structure that was initalized with\n! overland_properties_init\n\nsubroutine overland_properties_destory(this)\n    implicit none\n    class(overland_routing_properties_struct), intent(inout) :: this ! the type object being destroyed\n\n    logical :: allocation_error = .false.\n\n    ! deallocate x slope\n    if ( associated(this%surface_slope_x) ) then\n        deallocate( this%surface_slope_x )\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate y slope\n    if ( associated(this%surface_slope_y) ) then\n        deallocate( this%surface_slope_y )\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate water surface slope\n    if ( associated(this%surface_slope) ) then\n        deallocate( this%surface_slope )\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate slope index\n    if ( associated(this%max_surface_slope_index) ) then\n        deallocate( this%max_surface_slope_index )\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate surface roughness\n    if ( allocated(this%roughness) ) then\n        deallocate( this%roughness )\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate retention depth\n    if ( allocated(this%retention_depth ) ) then\n        deallocate( this%retention_depth )\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate dist\n    if ( associated(this%distance_to_neighbor) ) then\n        deallocate( this%distance_to_neighbor )\n    else\n        allocation_error = .true.\n    end if\n\n    if ( allocation_error ) &\n        write(0,*) \"attempt to deallocate data in members of overland properties structure&\n        &that where not allocated. The unallocated members where not changed\"\nend subroutine overland_properties_destory\n\n\nend module overland_routing_properties\n"
  },
  {
    "path": "src/Routing/Overland/module_overland_streams_and_lakes.F90",
    "content": "! module overland_stream_and_lake_interface_data.F\n! Purpose: This module contains the overland_control_struct class. This types holds\n! the lakes and stream related variables used in the overland routing code\n! National Water Center\n! Responsibility: Donald W Johnson donald.w.johnson@noaa.gov\n! Authors: Donald W Johnson, Nels Frazier\n\nmodule overland_stream_and_lake_interface\n    implicit none\n\n    ! type that hold inputs and outputs for stream and channels as well as\n    ! variables used to interface with channels and lakes\n    type overland_stream_and_lake_interface_struct\n        !real :: qstrmvoltrt     ! total of qstrmvolrt\n        !Accumulated water contribution form surface cells to channel cells throughout the simulation (mm)\n        real :: accumulated_surface_water_to_channel\n         !FIXME maybe move ^^^ to mass balance\n\n        !real :: lake_inflotrt   ! lake inflow from surface head\n        !Accumulated water contribution from surface cells to lake cells throught the simulation (mm)\n        real :: accumulated_surface_water_to_lake\n        !FIXME maybe move ^^^ to mass balance\n\n        integer, allocatable, dimension(:,:) :: ch_netrt      ! keeps trake of the 0-1 channel network\n        !Mask of the grid cells to indicate which cells are part of the channel network, 1 for channel, 0 for not\n        !If the mask value is negative on gridded channel routing, then no channel routing occurs for that cell\n        integer, allocatable, dimension(:,:) :: channel_mask\n\n        !integer, allocatable, dimension(:,:) :: lake_mskrt ! mask for identifing lake elements in channel network\n        !Mask for the grid cells to indicate which cells are part of lakes, 0 for no lake\n        !other values range from 1-N, indicating the index to the lake objects represented by the cells with the\n        !same values (i.e, all lask_mask cells with a value of 1 make up the gridded representation of lake object 1)\n        integer, allocatable, dimension(:,:) :: lake_mask\n\n        !real, allocatable, dimension(:,:) :: qstrmvolrt     ! accumulated channel inflow\n        !Depth of water on the surface cell that will go into a channel cell from overland routing, depth (mm)\n        real, allocatable, dimension(:,:) :: surface_water_to_channel\n\n\n        !real, allocatable, dimension(:,:) :: lake_inflort   ! NEED VARIABLE INFO\n        !Depth of water on the surface cell that will go into a lake cell from overland routing, depth (mm)\n        real, allocatable, dimension(:,:) :: surface_water_to_lake\n    contains\n        procedure :: init => overland_stream_and_lake_interface_init\n        procedure :: destroy => overland_stream_and_lake_interface_destroy\n    end type overland_stream_and_lake_interface_struct\n\n    contains\n\n! this structure allocates and initalizes the members of an overland_stream_and_lake_interface strucutre\n! if members have allready been initalized they will not be altered and an error will be logged\n\nsubroutine overland_stream_and_lake_interface_init(this,ix,jx)\n    implicit none\n    class(overland_stream_and_lake_interface_struct), intent(inout) :: this ! the type object being initalized\n    integer, intent(in) :: ix                     ! x grid size\n    integer, intent(in) :: jx                     ! y grid size\n\n    logical :: allocation_error = .false.\n\n    this%accumulated_surface_water_to_channel = 0.0\n    this%accumulated_surface_water_to_lake = 0.0\n\n    ! allocate the stream network\n    if ( .not. allocated(this%ch_netrt) ) then\n        allocate( this%ch_netrt(ix,jx) )\n        this%ch_netrt = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate the lake mask\n    if ( .not. allocated(this%lake_mask) ) then\n        allocate( this%lake_mask(ix,jx) )\n        this%lake_mask = -9999\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate qstrmvolrt\n    if ( .not. allocated(this%surface_water_to_channel) ) then\n        allocate( this%surface_water_to_channel(ix,jx) )\n        this%surface_water_to_channel = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    ! allocate lake_inflort\n    if ( .not. allocated(this%surface_water_to_lake) ) then\n        allocate( this%surface_water_to_lake(ix,jx) )\n        this%surface_water_to_lake = 0.0\n    else\n        allocation_error = .true.\n    end if\n\n    if ( allocation_error ) &\n        write(0,*) \"attempt to allocate data in members of overland lakes and streams structure&\n        &that where allready allocated. The allocated members where not changed\"    \nend subroutine overland_stream_and_lake_interface_init\n\n! this procedure deallocates and overland_stream_and_lake_interface structure that was initalized with\n! overland_stream_and_lake_interface_init\n\nsubroutine overland_stream_and_lake_interface_destroy(this)\n    implicit none\n    class(overland_stream_and_lake_interface_struct), intent(inout) :: this ! the type object being destroyed\n\n    logical :: allocation_error = .false.\n\n    ! deallocate channel network\n    if ( allocated(this%ch_netrt) ) then\n        deallocate( this%ch_netrt )\n    else\n        allocation_error = .true.\n    end if\n\n    ! deallocate the lake mask\n    if ( allocated(this%lake_mask) ) then\n        deallocate( this%lake_mask)\n    else\n        allocation_error = .true.\n    end if\n\n    ! deallocate qstrmvolrt\n    if ( allocated(this%surface_water_to_channel) ) then\n         deallocate( this%surface_water_to_channel )\n    else\n        allocation_error = .true.\n    end if\n\n    ! deallocate qbdryrt\n    if ( allocated(this%surface_water_to_lake) ) then\n         deallocate( this%surface_water_to_lake )          ! allocate qbdryrt\n    else\n        allocation_error = .true.\n    end if\n\n    if ( allocation_error ) &\n        write(0,*) \"attempt to deallocate data in members of overland streams and lakes structure&\n        &that where not allready allocated. The unallocated members where not changed\"   \nend subroutine overland_stream_and_lake_interface_destroy\n\nend module overland_stream_and_lake_interface\n"
  },
  {
    "path": "src/Routing/Overland/overland.md",
    "content": "# Overland Main Page {#overland}\n\n"
  },
  {
    "path": "src/Routing/Overland/overland_tests.F90",
    "content": "! overland_tests.F\n! Purpose: This program contains unit tests for the module overland_data\n! National Water Center\n! Responsibility: Donald W Johnson donald.w.johnson@noaa.gov\n! Authors: Donald W Johnson\n\nprogram overland_tests\n    use overland_data\n    implicit none\n\n    logical :: rv\n\n    write(6,*) \"Running Test 1\"\n    write(6,*) \"Test that the allocation and deallocation functions work correctly\"\n    rv = init_delete_test(100,100)\n    write(6,*) \"Test Complete\"\n\n    write(6,*) \"Running Test 2\"\n    write(6,*) \"Testing scaling\"\n    rv = scale_tests()\n    write(6,*) \"Test Complete\"\n\n    write(6,*) \"Running Test 3\"\n    write(6,*) \"Testing double init\"\n    rv = double_init_test()\n    write(6,*) \"Test Complete\"\n\n    write(6,*) \"Running Test 4\"\n    write(6,*) \"Testing double destroy\"\n    rv = double_destroy_test()\n    write(6,*) \"Test Complete\"\n    contains\n\n    function init_delete_test(ix,jx) result(rv)\n        implicit none\n\n        integer, intent(in) :: ix\n        integer, intent(in) :: jx\n        logical:: rv\n\n        logical :: status = .true.\n\n        type (overland_struct) :: overland_data\n\n        ! initalize the structure\n        call overland_data%init(ix,jx,ix,jx)\n\n        ! test to see if control was associated\n        if ( associated(overland_data%control) ) then\n            !write(6,*) \"control type was associated\"\n        else\n            !write(6,*) \"control type not associated\"\n            status = .false.\n        end if\n\n        ! test to see if streams_and_lakes was associated\n        if ( associated(overland_data%streams_and_lakes) ) then\n            !write(6,*) \"streams and lakes type was associated\"\n        else\n            !write(6,*) \"streams and lakes type not associated\"\n            status = .false.\n        end if\n\n        ! test to see if streams_and_lakes was associated\n        if ( associated(overland_data%properties) ) then\n            !write(6,*) \"properties type was associated\"\n        else\n            !write(6,*) \"properties type not associated\"\n            status = .false.\n        end if\n\n        ! test to see if streams_and_lakes was associated\n        if ( associated(overland_data%mass_balance) ) then\n            !write(6,*) \"mass_balance type was associated\"\n        else\n            !write(6,*) \"mass_balance type not associated\"\n            status = .false.\n        end if\n\n        ! destroy the structure\n        call overland_data%destroy\n\n        ! test to see if control was associated\n        if ( .not. associated(overland_data%control) ) then\n            !write(6,*) \"control type was disassociated\"\n        else\n            !write(6,*) \"control type not disassociated\"\n            status = .false.\n        end if\n\n        ! test to see if streams_and_lakes was associated\n        if ( .not. associated(overland_data%streams_and_lakes) ) then\n            !write(6,*) \"streams and lakes type was disassociated\"\n        else\n            !write(6,*) \"streams and lakes type not disassociated\"\n            status = .false.\n        end if\n\n        ! test to see if streams_and_lakes was associated\n        if ( .not. associated(overland_data%properties) ) then\n            !write(6,*) \"properties type was disassociated\"\n        else\n            !write(6,*) \"properties type not disassociated\"\n            status = .false.\n        end if\n\n        ! test to see if streams_and_lakes was associated\n        if ( .not. associated(overland_data%mass_balance) ) then\n            !write(6,*) \"mass_balance type was disassociated\"\n        else\n            !write(6,*) \"mass_balance type not disassociated\"\n            status = .false.\n        end if\n\n        ! write final test results\n        if ( status ) then\n            write(6,*) \"Test Passed\"\n        else\n            write(6,*) \"Test Failed\"\n        end if\n\n        rv = status\n    end function init_delete_test\n\n    function scale_tests() result(rv)\n        logical :: rv\n\n        logical, dimension(4) :: results\n        results = .false.\n\n        write(6,*) \"Running Test for (10,10)\"\n        results(1) = init_delete_test(10,10)\n        write(6,*) \"Running Test for (100,100)\"\n        results(2) = init_delete_test(100,100)\n        write(6,*) \"Running Test for (1000,1000)\"\n        results(3) = init_delete_test(1000,1000)\n        write(6,*) \"Running Test for (5000,5000)\"\n        results(4) = init_delete_test(5000,5000)\n\n        if ( all(results) ) then\n            rv = .true.\n            write(6,*) \"All Sub-Test Passed\"\n        else\n            rv = .false.\n            write(6,*) \"At Least One Sub-Test Failed\"\n        end if\n\n    end function scale_tests\n\n    function double_init_test() result(rv)\n        implicit none\n        logical :: rv\n\n        type (overland_struct) :: overland_data\n\n        call overland_data%init(100,100,100,100)\n        call overland_data%init(100,100,100,100)\n        call overland_data%destroy\n\n        write(6,*) \"Test Passed\"\n        rv = .true.\n    end function double_init_test\n\n    function double_destroy_test() result(rv)\n        implicit none\n        logical :: rv\n\n        type (overland_struct) :: overland_data\n\n        call overland_data%init(100,100,100,100)\n        call overland_data%destroy\n        call overland_data%destroy\n\n        write(6,*) \"Test Passed\"\n        rv = .true.\n    end function double_destroy_test\n\nend program overland_tests\n"
  },
  {
    "path": "src/Routing/Reservoirs/.gitignore",
    "content": "resevoir_tests\n"
  },
  {
    "path": "src/Routing/Reservoirs/CMakeLists.txt",
    "content": "add_library(hydro_routing_reservoirs STATIC\n        module_reservoir.F90\n        module_reservoir_read_timeslice_data.F90\n        module_reservoir_read_rfc_time_series_data.F90\n        module_reservoir_utilities.F90\n)\n\nadd_subdirectory(\"Level_Pool\")\nadd_subdirectory(\"Persistence_Level_Pool_Hybrid\")\nadd_subdirectory(\"RFC_Forecasts\")\n\nadd_dependencies(hydro_routing_reservoirs hydro_utils)\n"
  },
  {
    "path": "src/Routing/Reservoirs/Level_Pool/CMakeLists.txt",
    "content": "add_library(hydro_routing_reservoirs_levelpool STATIC\n        module_levelpool.F90\n        module_levelpool_state.F90\n        module_levelpool_properties.F90\n)\n\nadd_dependencies(hydro_routing_reservoirs_levelpool hydro_routing_reservoirs)\n"
  },
  {
    "path": "src/Routing/Reservoirs/Level_Pool/Makefile",
    "content": "\ninclude ../../../macros\n\nMODFLAG := -I ../../../MPP -I ../../../mod\n\n%.o : %.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) $<\n\n.PHONY: all mod test\n\nall: mod\n\nmod:\n\t#Build each sub module then build the module that depends on all sub modules\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_levelpool_properties.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_levelpool_state.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_levelpool.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_levelpool_tests.F90\n\tar -r ../../../lib/libHYDRO.a module_levelpool_properties.o\n\tar -r ../../../lib/libHYDRO.a module_levelpool_state.o\n\tar -r ../../../lib/libHYDRO.a module_levelpool.o\n\tar -r ../../../lib/libHYDRO.a module_levelpool_tests.o\n\n\tcp *.mod ../../../mod\n\nclean:\n\trm -f *.o\n\trm -f *.mod\n"
  },
  {
    "path": "src/Routing/Reservoirs/Level_Pool/module_levelpool.F90",
    "content": "! This module defines and instantiates objects\n! for a level pool type reservoir. The level\n! pool reservoir type inherits input and\n! output types from the reservoir base\n! module and calls instantiation of these into\n! sub-objects. The level pool reservoir type\n! also points to types for level pool properties\n! and state and calls instantiation of these into\n! sub-objects. This module also contains the\n! subroutine to run level pool reservoir that is\n! derived from the reservoir base type interface\n! to run reservoir. Running level pool will\n! then call the LEVELPOOL_PHYSICS subroutine, which\n! processes the given inputs, properties, and\n! state for a particular level pool reservoir and\n! returns the output/outflow.\n\nmodule module_levelpool\n\n    use module_levelpool_properties, only: levelpool_properties_interface\n    use module_levelpool_state, only: levelpool_state_interface\n    use module_reservoir, only: reservoir, reservoir_input, &\n                                     reservoir_output\n    use module_hydro_stop, only: HYDRO_stop\n    use iso_fortran_env, only: int64\n\n#ifdef RESERVOIR_D\n    use module_reservoir_utilities, only: create_levelpool_diagnostic_log_file, &\n                                          log_levelpool_diagnostic_data\n#endif\n\n    implicit none\n\n    ! Extend/derive level pool type from the abstract base\n    ! type for reservoirs.\n    type, extends(reservoir) :: levelpool\n\n        ! Define pointers to sub-types / sub-objects to and\n        ! held by a level pool reservoir object.\n        type (levelpool_properties_interface), pointer :: properties => null()\n        type (levelpool_state_interface), pointer :: state => null()\n\n        logical :: pointer_allocation_guard = .false.\n\n    contains\n\n        procedure :: init => levelpool_init\n        procedure :: destroy => levelpool_destroy\n        procedure :: run => run_levelpool_reservoir\n\n    end type levelpool\n\ncontains\n\n    !Level Pool Constructor\n    subroutine levelpool_init(this, water_elevation,  &\n        lake_area, weir_elevation, weir_coeffecient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, &\n        orifice_area, max_depth, lake_number, lake_opt)\n\n        implicit none\n        class(levelpool), intent(inout) :: this ! object being initialized\n        real, intent(inout) :: water_elevation           ! meters AMSL\n        real, intent(in)    :: lake_area                 ! area of lake (km^2)\n        real, intent(in)    :: weir_elevation            ! bottom of weir elevation (meters AMSL)\n        real, intent(in)    :: weir_coeffecient          ! weir coefficient\n        real, intent(in)    :: weir_length               ! weir length (meters)\n        real, intent(in)    :: dam_length                ! dam length (meters)\n        real, intent(in)    :: orifice_elevation         ! orifice elevation (meters AMSL)\n        real, intent(in)    :: orifice_coefficient       ! orifice coefficient\n        real, intent(in)    :: orifice_area              ! orifice area (meters^2)\n        real, intent(in)    :: max_depth                 ! max depth of reservoir before overtop (meters)\n        integer(kind=int64), intent(in) :: lake_number   ! lake number\n        integer, intent(in) :: lake_opt                  ! bypass lake physics (2 to use pass-through)\n\n        character(len=15)   :: lake_number_string\n\n#ifdef RESERVOIR_D\n        ! Create diagnostic log file only for development/debugging purposes\n        call create_levelpool_diagnostic_log_file(lake_number)\n#endif\n\n        if (this%pointer_allocation_guard .eqv. .false. ) then\n            ! try to allocate input\n            allocate ( this%input )\n            if ( .not. associated(this%input) ) then\n                ! if the input structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate level pool input structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize the input structure\n                call this%input%init()\n            end if\n\n            ! try to allocate output\n            allocate ( this%output )\n            if ( .not. associated(this%output) ) then\n                ! if the output structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate level pool output structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize the output structure\n                call this%output%init()\n            end if\n\n            ! try to allocate properties\n            allocate ( this%properties )\n            if ( .not. associated(this%properties) ) then\n                ! if the properties structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate levelpool properties structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize levelpool properties\n                call this%properties%init( lake_area,  &\n                    weir_elevation, weir_coeffecient, weir_length, dam_length, &\n                    orifice_elevation, orifice_coefficient, &\n                    orifice_area, max_depth, lake_number, lake_opt )\n            end if\n            this%pointer_allocation_guard = .true.\n\n            ! try to allocate state\n            allocate ( this%state )\n            if ( .not. associated(this%state) ) then\n                ! if the state structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate state properties structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize levelpool state\n                call this%state%init( water_elevation )\n            end if\n            this%pointer_allocation_guard = .true.\n        end if\n\n    end subroutine levelpool_init\n\n\n    !Level Pool Destructor\n    subroutine levelpool_destroy(this)\n        implicit none\n        class(levelpool), intent(inout) :: this ! object being destroyed\n    end subroutine levelpool_destroy\n\n\n    ! Subroutine for running a level pool reservoir,\n    ! which will then call the LEVELPOOL method/subroutine for processing the\n    ! inputs and returning the output.\n    subroutine run_levelpool_reservoir(this, previous_timestep_inflow, inflow, &\n        lateral_inflow, water_elevation, outflow, routing_period, dynamic_reservoir_type, &\n        assimilated_value, assimilated_source_file)\n        implicit none\n        class(levelpool), intent(inout) :: this\n        real, intent(in)    :: previous_timestep_inflow ! cubic meters per second (cms)\n        real, intent(in)    :: inflow                   ! cubic meters per second (cms)\n        real, intent(in)    :: lateral_inflow           ! cubic meters per second (cms)\n        real, intent(inout) :: water_elevation          ! meters\n        real, intent(out)   :: outflow                  ! cubic meters per second (cms)\n        real, intent(in)    :: routing_period           ! seconds\n        integer, intent(out):: dynamic_reservoir_type   ! dynamic reservoir type sent to lake out files\n        real, intent(out)   :: assimilated_value        ! value assimilated from observation or forecast\n        character(len=256), intent(out) :: assimilated_source_file ! source file of assimilated value\n\n\n        ! Update input variables\n        this%input%inflow = inflow\n        this%input%lateral_inflow = lateral_inflow\n\n        ! Update state variables\n        this%state%water_elevation = water_elevation\n\n        call LEVELPOOL_PHYSICS(this%properties%lake_number,                  &\n                               this%properties%lake_opt,                   &\n                               previous_timestep_inflow,                     &\n                               this%input%inflow,                            &\n                               this%output%outflow,                          &\n                               this%input%lateral_inflow,                    &\n                               routing_period,                               &\n                               this%state%water_elevation,                   &\n                               this%properties%lake_area,                    &\n                               this%properties%weir_elevation,               &\n                               this%properties%max_depth,                    &\n                               this%properties%weir_coeffecient,             &\n                               this%properties%weir_length,                  &\n                               this%properties%dam_length,                   &\n                               this%properties%orifice_elevation,            &\n                               this%properties%orifice_coefficient,          &\n                               this%properties%orifice_area                  &\n        )\n\n        ! Update output variable returned from this subroutine\n        outflow = this%output%outflow\n\n        ! Set current inflow to previous_timestep_inflow\n        this%input%previous_timestep_inflow = inflow\n\n        ! Update water_elevation variable returned from this subroutine\n        water_elevation = this%state%water_elevation\n\n        ! The dynamic reservoir type is always set to 1 for level pool in this module because\n        ! it cannot change reservoir types\n        dynamic_reservoir_type = 1\n\n        ! The assimilated value would always be a sentinel of -9999.0 because level pool does\n        ! not assimilate any external observations or forecasts\n        assimilated_value = -9999.0\n\n        ! The assimilated source file would always be an empty string\n        assimilated_source_file = \"\"\n\n#ifdef RESERVOIR_D\n        ! Log diagnostic data only for development/debugging purposes\n        call log_levelpool_diagnostic_data(this%properties%lake_number, inflow, water_elevation, outflow)\n#endif\n\n    end subroutine run_levelpool_reservoir\n\n    ! ------------------------------------------------\n    !   SUBROUTINE LEVELPOOL\n    ! ------------------------------------------------\n\n    subroutine LEVELPOOL_PHYSICS(ln,lake_opt,qi0,qi1,qo1,ql,dt,H,ar,we,maxh,wc,wl,dl,oe,oc,oa)\n\n        !! ----------------------------  argument variables\n        !! All elevations should be relative to a common base (often belev(k))\n\n        real, intent(INOUT) :: H       ! water elevation height (m)\n        real, intent(IN)    :: dt      ! routing period [s]\n        real, intent(IN)    :: qi0     ! inflow at previous timestep (cms)\n        real, intent(IN)    :: qi1     ! inflow at current timestep (cms)\n        real, intent(OUT)   :: qo1     ! outflow at current timestep\n        real, intent(IN)    :: ql      ! lateral inflow\n        real, intent(IN)    :: ar      ! area of reservoir (km^2)\n        real, intent(IN)    :: we      ! bottom of weir elevation\n        real, intent(IN)    :: wc      ! weir coeff.\n        real, intent(IN)    :: wl      ! weir length (m)\n        real, intent(IN)    :: dl      ! dam length(m)\n        real, intent(IN)    :: oe      ! orifice elevation\n        real, intent(IN)    :: oc      ! orifice coeff.\n        real, intent(IN)    :: oa      ! orifice area (m^2)\n        real, intent(IN)    :: maxh    ! max depth of reservoir before overtop (m)\n        integer(kind=int64), intent(IN) :: ln      ! lake number\n        integer, intent(in) :: lake_opt ! reservoir physics options (1: levelpool, 2: passthrough)\n\n        real    :: Htmp                ! Temporary assign of incoming lake el. (m)\n\n        !! ----------------------------  local variables\n        real :: sap                    ! local surface area values\n        real :: discharge              ! storage discharge m^3/s\n        real :: tmp1, tmp2\n        real :: dh, dh1, dh2, dh3      ! Depth in weir, and height function for 3 order RK\n        real :: It, Itdt_3, Itdt_2_3   ! inflow hydrographs\n        real :: maxWeirDepth           !maximum capacity of weir\n        !real :: hdiff_vol, qdiff_vol   ! water balance check variables\n        !! ----------------------------  subroutine body: from chow, mad mays. pg. 252\n        !! -- determine from inflow hydrograph\n\n        Htmp = H   !temporary set of incoming lake water elevation...\n        !hdiff_vol = 0.0\n        !qdiff_vol = 0.0\n\n        !!DJG IF-block for lake model option  1 - outflow=inflow, 2 - Chow et al level\n        !pool, .....\n        if (LAKE_OPT == 2) then     ! If-block for simple pass through scheme....\n#ifdef RESERVOIR_D\n           write(6,*) \"LEVELPOOL LAKE_OPT=2, using reservoir passthrough\"\n#endif\n           qo1 = qi1                 ! Set outflow equal to inflow at current time\n           H = Htmp                  ! Set new lake water elevation to incoming lake el.\n\n        else if (LAKE_OPT == 1) then   ! If-block for Chow et al level pool scheme\n\n           It = qi0\n           Itdt_3   = qi0 + ((qi1 + ql - qi0) * 0.33)\n           Itdt_2_3 = qi0 + ((qi1 + ql - qi0) * 0.67)\n           maxWeirDepth =  maxh - we\n\n           !assume vertically walled reservoir\n           !remove this when moving to a variable head area volume\n           sap = ar * 1.0E6\n\n           !-- determine Q(dh) from elevation-discharge relationship\n           !-- and dh1\n           dh = H - we\n           if (dh > maxWeirDepth) then\n              dh = maxWeirDepth\n           endif\n\n           tmp1 = oc * oa * sqrt(2. * 9.81 * ( H - oe )) !orifice at capacity\n           tmp2 = wc * wl * (dh ** (3./2.))  !weir flows at capacity\n\n           !determine the discharge based on current height\n           if(H > maxh) then\n             discharge =  tmp1 + tmp2 + (wc* (wl*dl) * (H-maxh)**(3./2.)) !overtop\n           else if (dh > 0.0 ) then              !! orifice and weir discharge\n             discharge = tmp1 + tmp2\n           else if ( H > oe ) then     !! only orifice flow\n             discharge = oc * oa * sqrt(2. * 9.81 * ( H - oe ) )\n           else\n             discharge = 0.0   !in the dead pool\n           endif\n\n           if (sap > 0) then\n              dh1 = ((It - discharge)/sap)*dt\n           else\n              dh1 = 0.0\n           endif\n\n           !-- determine Q(H + dh1/3) from elevation-discharge relationship\n           !-- dh2\n           dh = (H+dh1/3) - we\n           if (dh > maxWeirDepth) then\n              dh = maxWeirDepth\n           endif\n\n           tmp1 = oc * oa * sqrt(2. * 9.81 * ( (H+dh1/3.) - oe ) )\n           tmp2 = wc * wl * (dh ** (3./2.))\n\n           !determine the discharge based on current height\n           if(H > maxh) then\n             discharge =  tmp1 + tmp2 + (wc* (wl*dl) * (H-maxh)**(3./2.)) !overtop\n           else if (dh > 0.0 ) then              !! orifice and weir discharge\n             discharge = tmp1 + tmp2\n           else if ( (H+dh1/3) > oe ) then     !! only orifice flow,not full\n             discharge = oc * oa * sqrt(2. * 9.81 * ( (H+dh1/3.) - oe ) )\n           else\n             discharge = 0.0\n            endif\n\n\n           if (sap > 0.0) then\n              dh2 = ((Itdt_3 - discharge)/sap)*dt\n           else\n              dh2 = 0.0\n           endif\n\n           !-- determine Q(H + 2/3 dh2) from elevation-discharge relationship\n           !-- dh3\n           dh = (H + (0.667*dh2)) - we\n           if (dh > maxWeirDepth) then\n              dh = maxWeirDepth\n           endif\n\n           tmp1 = oc * oa * sqrt(2. * 9.81 * ( (H+dh2*0.667) - oe ) )\n           tmp2 = wc * wl * (dh ** (3./2.))\n\n           !determine the discharge based on current height\n           if(H > maxh) then  ! overtop condition, not good!\n              discharge =  tmp1 + tmp2 + (wc* (wl*dl) * (H-maxh)**(3./2.)) !overtop\n           else if (dh > 0.0 ) then              !! orifice and weir discharge\n              discharge = tmp1 + tmp2\n           else if ( (H+dh2*0.667) > oe ) then     !! only orifice flow,not full\n              discharge = oc * oa * sqrt(2. * 9.81 * ( (H+dh2*0.667) - oe ) )\n           else\n              discharge = 0.0\n           endif\n\n           if (sap > 0.0) then\n              dh3 = ((Itdt_2_3 - discharge)/sap)*dt\n           else\n              dh3 = 0.0\n           endif\n\n           !-- determine dh and H\n           dh = (dh1/4.) + (0.75*dh3)\n           H = H + dh\n\n           !-- compute final discharge\n           dh = H - we\n           if (dh > maxWeirDepth) then\n              dh = maxWeirDepth\n           endif\n\n           tmp1 = oc * oa * sqrt(2. * 9.81 * ( H - oe ) )\n           tmp2 = wc * wl * (dh ** (3./2.))\n\n           !determine the discharge based on current height\n           if(H > maxh) then  ! overtop condition, not good!\n              discharge =  tmp1 + tmp2 + (wc* (wl*dl) * (H-maxh)**(3./2.)) !overtop\n           else if (dh > 0.0 ) then              !! orifice and overtop discharge\n              discharge = tmp1 + tmp2\n           else if ( H > oe ) then     !! only orifice flow,not full\n              discharge = oc * oa * sqrt(2. * 9.81 * ( H - oe ) )\n           else\n              discharge = 0.0\n           endif\n\n           qo1  = discharge  ! return the flow rate from reservoir\n\n        !#ifdef HYDRO_D\n        !#ifndef NCEP_WCOSS\n        !   ! Water balance check\n        !   qdiff_vol = (qi1+ql-qo1)*dt !m3\n        !   hdiff_vol = (H-Htmp)*sap    !m3\n        !22 format(f8.4,2x,f8.4,2x,f8.4,2x,f8.4,2x,f8.4,2x,f6.0,2x,f20.1,2x,f20.1)\n        !   open (unit=67, &\n        !     file='lake_massbalance_out.txt', status='unknown',position='append')\n        !   write(67,22) Htmp, H, qi1, ql, qo1, dt, qdiff_vol, hdiff_vol\n        !   close(67)\n        !#endif\n        !#endif\n\n        !23 format('botof H dh orf wr Q',f8.4,2x,f8.4,2x,f8.3,2x,f8.3,2x,f8.2)\n        !24 format('ofonl H dh sap Q ',f8.4,2x,f8.4,2x,f8.0,2x,f8.2)\n\n\n        else   ! ELSE for LAKE_OPT....\n         call hydro_stop(\"Invalid lake option supplied to LEVELPOOL_PHYSICS()\")\n        endif  ! ENDIF for LAKE_OPT....\n\n        return\n\n    ! ----------------------------------------------------------------\n    end subroutine LEVELPOOL_PHYSICS\n    ! ----------------------------------------------------------------\n\nend module module_levelpool\n"
  },
  {
    "path": "src/Routing/Reservoirs/Level_Pool/module_levelpool_properties.F90",
    "content": "! This module defines and instantiates objects\n! for a level pool type reservoir's\n! parameters/properties. Properties holds\n! static/unchanging variables that are\n! set when the given reservoir object is\n! initialized/instantiated.\nmodule module_levelpool_properties\n\n    use module_reservoir, only: reservoir_properties\n    use iso_fortran_env, only: int64\n    implicit none\n\n    ! Extend/derive level pool properties from the abstract base\n    ! type for reservoir properties.\n    type, extends(reservoir_properties) :: levelpool_properties_interface\n        real :: lake_area                ! area of lake (km^2)\n        real :: weir_elevation           ! bottom of weir elevation (meters AMSL)\n        real :: weir_coeffecient         ! weir coefficient\n        real :: weir_length              ! weir length (meters)\n        real :: dam_length               ! dam length (meters)\n        real :: orifice_elevation        ! orifice elevation (meters AMSL)\n        real :: orifice_coefficient      ! orifice coefficient\n        real :: orifice_area             ! orifice area (meters^2)\n        real :: max_depth                ! max depth of reservoir before overtop (meters)\n        integer(kind=int64) :: lake_number           ! lake number\n        integer :: lake_opt              ! reservoir physics options (1: levelpool, 2: passthrough)\n\n    contains\n\n        procedure :: init => levelpool_properties_init\n        procedure :: destroy => levelpool_properties_destroy\n\n    end type levelpool_properties_interface\n\ncontains\n\n    !Level Pool Properties Constructor\n    subroutine levelpool_properties_init(this, lake_area, &\n        weir_elevation, weir_coeffecient, weir_length, dam_length, orifice_elevation, &\n        orifice_coefficient, orifice_area, max_depth, lake_number, lake_opt)\n        implicit none\n        class(levelpool_properties_interface), intent(inout) :: this ! the type object being initialized\n        real, intent(in)    :: lake_area      \t        ! area of lake (km^2)\n        real, intent(in)    :: weir_elevation           ! bottom of weir elevation (meters AMSL)\n        real, intent(in)    :: weir_coeffecient         ! weir coefficient\n        real, intent(in)    :: weir_length              ! weir length (meters)\n        real, intent(in)    :: dam_length               ! dam length (meters)\n        real, intent(in)    :: orifice_elevation        ! orifice elevation (meters AMSL)\n        real, intent(in)    :: orifice_coefficient      ! orifice coefficient\n        real, intent(in)    :: orifice_area             ! orifice area (meters^2)\n        real, intent(in)    :: max_depth                ! max depth of reservoir before overtop (meters)\n        integer(kind=int64), intent(in) :: lake_number              ! lake number\n        integer             :: lake_opt                 ! reservoir physics options (1: levelpool, 2: passthrough)\n\n        ! Assign the values passed in to a particular level pool reservoir\n        ! properties object's variables.\n        this%lake_area = lake_area\n        this%weir_elevation = weir_elevation\n        this%weir_coeffecient = weir_coeffecient\n        this%weir_length = weir_length\n        this%orifice_elevation = orifice_elevation\n        this%orifice_coefficient = orifice_coefficient\n        this%orifice_area = orifice_area\n        this%max_depth = max_depth\n        this%lake_number = lake_number\n        this%dam_length = dam_length\n        this%lake_opt = lake_opt\n\n    end subroutine levelpool_properties_init\n\n    !Level Pool Properties Destructor\n    subroutine levelpool_properties_destroy(this)\n        implicit none\n        class(levelpool_properties_interface), intent(inout) :: this ! the type object being destroyed\n    end subroutine levelpool_properties_destroy\n\nend module module_levelpool_properties\n"
  },
  {
    "path": "src/Routing/Reservoirs/Level_Pool/module_levelpool_state.F90",
    "content": "! This module defines and instantiates objects\n! for a level pool type reservoir's state.\n! State holds and tracks dynamic/changing variables\n! that are only relevant to the given level pool\n! reservoir object and not other modules or areas\n! of the system.\nmodule module_levelpool_state\n\n    use module_reservoir, only: reservoir_state\n    implicit none\n\n    ! Extend/derive level pool state from the abstract base\n    ! type for reservoir state.\n    type, extends(reservoir_state) :: levelpool_state_interface\n        real :: water_elevation                 ! meters AMSL\n\n    contains\n\n        procedure :: init => levelpool_state_init\n        procedure :: destroy => levelpool_state_destroy\n\n    end type levelpool_state_interface\n\ncontains\n\n    !Level Pool State Constructor\n    subroutine levelpool_state_init(this, water_elevation)\n        implicit none\n        class(levelpool_state_interface), intent(inout) :: this ! the type object being initialized\n        real, intent(inout) :: water_elevation     ! meters AMSL\n\n        ! Assign the water elevation value passed in to a particular level pool reservoir\n        ! state object's variable for water elevation\n        this%water_elevation = water_elevation\n\n    end subroutine levelpool_state_init\n\n    !Level Pool State Destructor\n    subroutine levelpool_state_destroy(this)\n        implicit none\n        class(levelpool_state_interface), intent(inout) :: this ! the type object being destroyed\n\n    end subroutine levelpool_state_destroy\n\nend module module_levelpool_state\n"
  },
  {
    "path": "src/Routing/Reservoirs/Level_Pool/module_levelpool_tests.F90",
    "content": "! This module holds tests for initialization of\n! various attributes of a levelpool reservoir.\nmodule module_levelpool_tests\n    use module_levelpool\n\ncontains\n\n    function levelpool_data_info(levelpool_data) result(data_info_result)\n    implicit none\n    type (levelpool) :: levelpool_data\n    logical  :: data_info_result\n    logical, dimension(4) :: ptr_state\n    logical, dimension(4) :: data_state\n\n    data_info_result = .false.\n\n    ! Check to see if the levelpool_state data structure exists\n    print *, \"Checking pointer association on data%state \"\n    if ( associated(levelpool_data%state) ) then\n        print *, \"PASSED\"\n        ptr_state(1) = .true.\n    else\n        print *, \"FAILED\"\n        ptr_state(1) = .false.\n    end if\n\n    ! Check to see if the levelpool_properties data structure exists\n    print *, \"Checking pointer association on data%properties \"\n    if ( associated(levelpool_data%properties) ) then\n        print *, \"PASSED\"\n        ptr_state(2) = .true.\n    else\n        print *, \"FAILED\"\n        ptr_state(2) = .false.\n    end if\n\n    ! Check to see if the levelpool_input data structure exists\n    print *, \"Checking pointer association on data%input \"\n    if ( associated(levelpool_data%input) ) then\n        print *, \"PASSED\"\n        ptr_state(3) = .true.\n    else\n        print *, \"FAILED\"\n        ptr_state(3) = .false.\n    end if\n\n    ! Check to see if the levelpool_output data structure exists\n    print *, \"Checking pointer association on data%output \"\n    if ( associated(levelpool_data%output) ) then\n        print *, \"PASSED\"\n        ptr_state(4) = .true.\n    else\n        print *, \"FAILED\"\n        ptr_state(4) = .false.\n    end if\n\n    ! Now check the data members of each substructure\n    if ( ptr_state(1) ) then\n        data_state(1) = test_levelpool_state(levelpool_data%state)\n    end if\n\n    if ( ptr_state(2) ) then\n        data_state(2) = test_levelpool_properties(levelpool_data%properties)\n    end if\n\n    if ( ptr_state(3) ) then\n        data_state(3) = test_input(levelpool_data%input)\n    end if\n\n    if ( ptr_state(4) ) then\n        data_state(4) = test_output(levelpool_data%output)\n    end if\n\n\n    if ( all(ptr_state) .and. all(data_state) ) then\n        data_info_result = .true.\n        print *, \"========================================================================\"\n        print *, \"All Level Pool Tests Passed\"\n        print *, \"========================================================================\"\n\n    else\n        data_info_result = .false.\n        print *, \"========================================================================\"\n        print *, \"Not All Level Pool Tests Passed\"\n        print *, \"========================================================================\"\n    end if\n\n    end function levelpool_data_info\n\n\n    ! Test to see that each member of the input structure is correctly allocated and readable\n    function test_input(o) result(rv)\n        type (reservoir_input), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the input structure\"\n        print *, \" \"\n\n        print *, \"Checking read on inflow\"\n        print *, o%inflow\n        if ( o%inflow .lt. 0.0 - epsilon(0.0) .or. o%inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lateral_inflow\"\n        print *, o%lateral_inflow\n        if ( o%lateral_inflow .lt. 0.0 - epsilon(0.0) .or. o%lateral_inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on previous_timestep_inflow\"\n        print *, o%previous_timestep_inflow\n        if ( o%previous_timestep_inflow .lt. 0.0 - epsilon(0.0) .or. o%previous_timestep_inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_input\n\n    ! Test to see that each member of the output structure is correctly allocated and readable\n    function test_output(o) result(rv)\n        type (reservoir_output), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the output structure\"\n        print *, \" \"\n\n        print *, \"Checking read on outflow\"\n        print *, o%outflow\n        if ( o%outflow .lt. 0.0 - epsilon(0.0) .or. o%outflow .gt. 0.0 + epsilon(0.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_output\n\n    ! Test to see that each member of the state structure is correctly allocated and readable\n    function test_levelpool_state(o) result(rv)\n        type (levelpool_state_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the level pool state data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on water_elevation\"\n        print *, o%water_elevation\n        if ( o%water_elevation .lt. 2.0 - epsilon(2.0) .or. o%water_elevation .gt. 2.0 + epsilon(2.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_levelpool_state\n\n\n    ! Test to see that each member of the properties structure is correctly allocated and readable\n    function test_levelpool_properties(o) result(rv)\n        type (levelpool_properties_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the level pool properties data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on lake_area\"\n        print *, o%lake_area\n        if ( o%lake_area .lt. 4.0 - epsilon(4.0) .or. o%lake_area .gt. 4.0 + epsilon(4.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_elevation\"\n        print *, o%weir_elevation\n        if ( o%weir_elevation .lt. 6.0 - epsilon(6.0) .or. o%weir_elevation .gt. 6.0 + epsilon(6.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_coeffecient\"\n        print *, o%weir_coeffecient\n        if ( o%weir_coeffecient .lt. 8.0 - epsilon(8.0) .or. o%weir_coeffecient .gt. 8.0 + epsilon(8.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_length\"\n        print *, o%weir_length\n        if ( o%weir_length .lt. 10.0 - epsilon(10.0) .or. o%weir_length .gt. 10.0 + epsilon(10.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_elevation\"\n        print *, o%orifice_elevation\n        if ( o%orifice_elevation .lt. 12.0 - epsilon(12.0) .or. o%orifice_elevation .gt. 12.0 + epsilon(12.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_coefficient\"\n        print *, o%orifice_coefficient\n        if ( o%orifice_coefficient .lt. 14.0 - epsilon(14.0) .or. o%orifice_coefficient .gt. 14.0 + epsilon(14.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_area\"\n        print *, o%orifice_area\n        if ( o%orifice_area .lt. 16.0 - epsilon(16.0) .or. o%orifice_area .gt. 16.0 + epsilon(16.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on max_depth\"\n        print *, o%max_depth\n        if ( o%max_depth .lt. 18.0 - epsilon(18.0) .or. o%max_depth .gt. 18.0 + epsilon(18.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lake_number\"\n        print *, o%lake_number\n        if ( o%lake_number .ne. 20) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_levelpool_properties\n\nend module\n"
  },
  {
    "path": "src/Routing/Reservoirs/Makefile",
    "content": "\ninclude ../../macros\n\nMODFLAG := $(MODFLAG) -I ../../mod\n\n%.o : %.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) $<\n\n.PHONY: all mod test\n\nall: mod\n\n../../MPP/mpp_land.mod:\n\t\tmake -C ../../MPP\n\n../../utils/module_hydro_stop.mod:\n\t\tmake -C ../../utils\n\nmod: ../../MPP/module_mpp_land.mod ../../utils/module_hydro_stop.mod\n\t#Build each sub module then build the module that depends on all sub modules\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_reservoir_utilities.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_reservoir.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_reservoir_read_timeslice_data.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_reservoir_read_rfc_time_series_data.F90\n\n\tar -r ../../lib/libHYDRO.a module_reservoir_utilities.o\n\tar -r ../../lib/libHYDRO.a module_reservoir.o\n\tar -r ../../lib/libHYDRO.a module_reservoir_read_timeslice_data.o\n\tar -r ../../lib/libHYDRO.a module_reservoir_read_rfc_time_series_data.o\n\n\tcp *.mod ../../mod\n\n\t#Build the modules\n\tmake -C Level_Pool\n\tmake -C Persistence_Level_Pool_Hybrid\n\tmake -C RFC_Forecasts\n\n\ntest: ../../MPP/module_mpp_land.mod ../../utils/module_hydro_stop.mod\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_reservoir_utilities.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_reservoir.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_reservoir_read_timeslice_data.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_reservoir_read_rfc_time_series_data.F90\n\n\n\tmake -C Level_Pool\n\tmake -C Persistence_Level_Pool_Hybrid\n\tmake -C RFC_Forecasts\n\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) reservoir_tests.F90\n\n\n\t$(COMPILER90) $(NETCDFLIB) -o reservoir_tests \\\n\t\t../../MPP/mpp_land.o \\\n\t\t../../MPP/CPL_WRF.o \\\n\t\t../../utils/module_hydro_stop.o \\\n\t\tmodule_reservoir_utilities.o \\\n\t\tmodule_reservoir.o \\\n\t\tmodule_reservoir_read_timeslice_data.o \\\n\t\tmodule_reservoir_read_rfc_time_series_data.o \\\n\t\tLevel_Pool/module_levelpool_properties.o \\\n\t\tLevel_Pool/module_levelpool_state.o \\\n\t\tLevel_Pool/module_levelpool_tests.o \\\n\t\tLevel_Pool/module_levelpool.o \\\n\t\tPersistence_Level_Pool_Hybrid/module_persistence_levelpool_hybrid_properties.o \\\n\t\tPersistence_Level_Pool_Hybrid/module_persistence_levelpool_hybrid_state.o \\\n\t\tPersistence_Level_Pool_Hybrid/module_persistence_levelpool_hybrid_tests.o \\\n\t\tPersistence_Level_Pool_Hybrid/module_persistence_levelpool_hybrid.o \\\n\t\tRFC_Forecasts/module_rfc_forecasts_properties.o \\\n\t\tRFC_Forecasts/module_rfc_forecasts_state.o \\\n\t\tRFC_Forecasts/module_rfc_forecasts_tests.o \\\n\t\tRFC_Forecasts/module_rfc_forecasts.o \\\n\t\treservoir_tests.o\n\n\nclean:\n\trm -f *.o\n\trm -f *.mod\n\trm -f reservoir_tests\n\n\tmake -C Level_Pool clean\n\tmake -C Persistence_Level_Pool_Hybrid clean\n\tmake -C RFC_Forecasts clean\n"
  },
  {
    "path": "src/Routing/Reservoirs/Persistence_Level_Pool_Hybrid/CMakeLists.txt",
    "content": "add_library(hydro_routing_reservoirs_hybrid STATIC\n        module_persistence_levelpool_hybrid.F90\n        module_persistence_levelpool_hybrid_state.F90\n        module_persistence_levelpool_hybrid_properties.F90\n)\n\nadd_dependencies(hydro_routing_reservoirs_hybrid hydro_routing_reservoirs)\n"
  },
  {
    "path": "src/Routing/Reservoirs/Persistence_Level_Pool_Hybrid/Makefile",
    "content": "\ninclude ../../../macros\n\nMODFLAG := -I ../../../MPP -I ../../../mod\n\n%.o : %.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) $<\n\n.PHONY: all mod test\n\nall: mod\n\nmod:\n\t#Build each sub module then build the module that depends on all sub modules\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_persistence_levelpool_hybrid_properties.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_persistence_levelpool_hybrid_state.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_persistence_levelpool_hybrid.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_persistence_levelpool_hybrid_tests.F90\n\tar -r ../../../lib/libHYDRO.a module_persistence_levelpool_hybrid_properties.o\n\tar -r ../../../lib/libHYDRO.a module_persistence_levelpool_hybrid_state.o\n\tar -r ../../../lib/libHYDRO.a module_persistence_levelpool_hybrid.o\n\tar -r ../../../lib/libHYDRO.a module_persistence_levelpool_hybrid_tests.o\n\n\tcp *.mod ../../../mod\n\nclean:\n\trm -f *.o\n\trm -f *.mod\n"
  },
  {
    "path": "src/Routing/Reservoirs/Persistence_Level_Pool_Hybrid/module_persistence_levelpool_hybrid.F90",
    "content": "! This module defines and instantiates objects\n! for a hybrid persistence levelpool type\n! reservoir. The hybrid reservoir type\n! inherits input and output types from the\n! reservoir base module and calls instantiation\n! of these into sub-objects. The hybrid\n! reservoir type also points to types for\n! hybrid properties and state and calls\n! instantiation of these into sub-objects.\n! A pointer to a levelpool reservoir object\n! is also held in state, and this module\n! instantiates that levelpool object. There\n! is also a subroutine to run hybrid reservoir\n! that is derived from the reservoir base\n! type interface to run reservoir.\n\nmodule module_persistence_levelpool_hybrid\n\n    use module_persistence_levelpool_hybrid_properties, only: hybrid_properties_interface\n    use module_persistence_levelpool_hybrid_state, only: hybrid_state_interface\n    use module_levelpool, only: levelpool\n    use module_reservoir_utilities, only: modify_for_projected_storage, warn_negative_inflow, &\n                                          create_hybrid_diagnostic_log_file, &\n                                          log_hybrid_diagnostic_data\n    use module_reservoir, only: reservoir, reservoir_input, reservoir_output\n    use module_reservoir_read_timeslice_data, only: usgs_timeslice_data, usace_timeslice_data, timeslice_data_type\n    use module_hydro_stop, only: HYDRO_stop\n    use iso_fortran_env, only: int64\n    implicit none\n\n    ! Extend/derive hybrid type from the abstract base\n    ! type for reservoirs.\n    type, extends(reservoir) :: persistence_levelpool_hybrid\n\n        ! Define pointers to sub-types / sub-objects to and\n        ! held by a level pool reservoir object.\n        type (hybrid_properties_interface), pointer :: properties => null()\n        type (hybrid_state_interface), pointer :: state => null()\n        type (timeslice_data_type), pointer :: timeslice_data => null()\n\n        logical :: pointer_allocation_guard = .false.\n\n    contains\n\n        procedure :: init => hybrid_init\n        procedure :: destroy => hybrid_destroy\n        procedure :: run => run_hybrid_reservoir\n\n    end type persistence_levelpool_hybrid\n\n#ifndef NCEP_WCOSS\n    integer, parameter :: log_warning = 6\n#else\n    integer, parameter :: log_warning = 78\n#endif\n\ncontains\n\n    ! Hybrid Constructor\n    subroutine hybrid_init(this, water_elevation,  &\n        lake_area, weir_elevation, weir_coeffecient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, &\n        orifice_area, lake_max_water_elevation, initial_fractional_depth, &\n        lake_number, reservoir_type, reservoir_parameter_file, start_date, &\n        usgs_timeslice_path, usace_timeslice_path, observation_lookback_hours, &\n        observation_update_time_interval_seconds)\n        implicit none\n        class(persistence_levelpool_hybrid), intent(inout) :: this ! object being initialized\n        real,    intent(inout) :: water_elevation           ! meters AMSL\n        real,    intent(in)    :: lake_area      \t\t    ! area of lake (km^2)\n        real,    intent(in)    :: weir_elevation            ! bottom of weir elevation (meters AMSL)\n        real,    intent(in)    :: weir_coeffecient          ! weir coefficient\n        real,    intent(in)    :: weir_length               ! weir length (meters)\n        real,    intent(in)    :: dam_length                ! dam length (meters)\n        real,    intent(in)    :: orifice_elevation         ! orifice elevation (meters AMSL)\n        real,    intent(in)    :: orifice_coefficient       ! orifice coefficient\n        real,    intent(in)    :: orifice_area              ! orifice area (meters^2)\n        real,    intent(in)    :: lake_max_water_elevation  ! max water elevation (meters)\n        real,    intent(in)    :: initial_fractional_depth  ! initial fraction water depth\n        integer(kind=int64), intent(in)    :: lake_number               ! lake number\n        integer, intent(in)    :: reservoir_type            ! reservoir type\n        character(len=*),   intent(in) :: reservoir_parameter_file\n        character(len=19),  intent(in) :: start_date\n        character(len=256), intent(in) :: usgs_timeslice_path\n        character(len=256), intent(in) :: usace_timeslice_path\n        integer,            intent(in) :: observation_lookback_hours\n        integer,            intent(in) :: observation_update_time_interval_seconds\n        character(len=15)              :: lake_number_string\n        character(len=15)              :: reservoir_type_string\n\n\n#ifdef RESERVOIR_D\n        ! Create diagnostic log file only for development/debugging purposes\n        call create_hybrid_diagnostic_log_file(lake_number)\n#endif\n\n        if (this%pointer_allocation_guard .eqv. .false. ) then\n\n            ! Call to initialize timeslice data object. This object is a singleton for either\n            ! USGS (U.S. Geological Survey) or USACE (U.S. Army Corps of Engineers) data source,\n            ! so if another reservoir has already initialized the object of a particular data\n            ! source, it will return immediately.\n            if (reservoir_type == 2) then\n                call usgs_timeslice_data%init(start_date, usgs_timeslice_path, &\n                reservoir_parameter_file, \"usgs\", observation_lookback_hours)\n\n                ! Assign pointer to usgs_timeslice_data object\n                this%timeslice_data=>usgs_timeslice_data\n\n            else if (reservoir_type == 3) then\n                call usace_timeslice_data%init(start_date, usace_timeslice_path, &\n                reservoir_parameter_file, \"usace\", observation_lookback_hours)\n\n                ! Assign pointer to usace_timeslice_data object\n                this%timeslice_data=>usace_timeslice_data\n\n            else\n                ! Call hydro_stop if reservoir_type is not USGS or USACE because the\n                ! data source is not available.\n                write(lake_number_string, \"(I15)\") lake_number\n                write(reservoir_type_string, \"(I15)\") reservoir_type\n                call hydro_stop(\"ERROR: Incorrect reservoir type for reservoir \" // trim(ADJUSTL(lake_number_string)) // &\n                \". Expected reservoir type 2 or 3 and instead received reservoir type \"  &\n                // trim(ADJUSTL(reservoir_type_string)) // \".\" )\n            end if\n\n            ! try to allocate input\n            allocate ( this%input )\n            if ( .not. associated(this%input) ) then\n                ! if the input structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate hybrid input structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize the input structure\n                call this%input%init()\n            end if\n\n            ! try to allocate output\n            allocate ( this%output )\n            if ( .not. associated(this%output) ) then\n                ! if the output structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate hybrid output structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize the output structure\n                call this%output%init()\n            end if\n\n            ! try to allocate properties\n            allocate ( this%properties )\n            if ( .not. associated(this%properties) ) then\n                ! if the properties structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate hybrid properties structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize hybrid properties\n                call this%properties%init(lake_area, lake_max_water_elevation, orifice_elevation, lake_number, &\n                reservoir_type, observation_lookback_hours, observation_update_time_interval_seconds, &\n                reservoir_parameter_file)\n            end if\n            this%pointer_allocation_guard = .true.\n\n            ! try to allocate state\n            allocate ( this%state )\n            if ( .not. associated(this%state) ) then\n                ! if the state structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate hybrid state structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize hybrid state\n                call this%state%init(water_elevation, lake_area, lake_max_water_elevation, orifice_elevation, &\n                initial_fractional_depth, reservoir_type)\n            end if\n            this%pointer_allocation_guard = .true.\n\n            ! Initialize persistence weight index to be out of bounds of the persistence weights array\n            this%state%persistence_weight_index = SIZE(this%properties%persistence_weighted_coefficients) + 1\n\n            ! Output warning if the initial storage is greater than max storage or less than zero.\n            if (this%state%current_storage > this%properties%max_storage) then\n                this%state%current_storage = this%properties%max_storage\n                write(lake_number_string, \"(I15)\") lake_number\n                write(log_warning,*) \"WARNING: initial storage exceeds max storage for reservoir \", lake_number_string, &\n                \". Setting initial storage to max storage.\"\n\n            else if (this%state%current_storage < this%properties%min_storage) then\n                this%state%current_storage = this%properties%min_storage\n                write(lake_number_string, \"(I15)\") lake_number\n                write(log_warning,*) \"WARNING: initial storage is less than zero for reservoir \", lake_number_string, &\n                \". Setting initial storage to zero.\"\n\n            end if\n\n            ! Allocate a single level pool reservoir\n            allocate(levelpool :: this%state%levelpool_ptr)\n\n            ! Initialize level pool reservoir\n            call this%state%levelpool_ptr%init(water_elevation, lake_area, &\n            weir_elevation, weir_coeffecient, weir_length, dam_length, orifice_elevation, &\n            orifice_coefficient, orifice_area, lake_max_water_elevation, lake_number, 1)\n\n        end if\n    end subroutine hybrid_init\n\n\n    ! Hybrid Destructor\n    subroutine hybrid_destroy(this)\n        implicit none\n        class(persistence_levelpool_hybrid), intent(inout) :: this ! object being destroyed\n    end subroutine hybrid_destroy\n\n\n    ! Subroutine for running reservoir for a hybrid reservoir\n    subroutine run_hybrid_reservoir(this, previous_timestep_inflow, inflow, &\n        lateral_inflow, water_elevation, outflow, routing_period, dynamic_reservoir_type, &\n        assimilated_value, assimilated_source_file)\n        implicit none\n        class(persistence_levelpool_hybrid), intent(inout) :: this\n        real, intent(in)    :: previous_timestep_inflow ! cubic meters per second (cms)\n        real, intent(in)    :: inflow                   ! cubic meters per second (cms)\n        real, intent(in)    :: lateral_inflow           ! cubic meters per second (cms)\n        real, intent(inout) :: water_elevation          ! meters\n        real, intent(out)   :: outflow                  ! cubic meters per second (cms)\n        real, intent(in)    :: routing_period           ! seconds\n        integer, intent(out):: dynamic_reservoir_type   ! dynamic reservoir type sent to lake out files\n        real, intent(out)   :: assimilated_value        ! value assimilated from observation\n        character(len=256), intent(out) :: assimilated_source_file ! source file of assimilated value\n        real                :: delta_storage            ! timestep change in storage (cubic meters)\n        real                :: local_water_elevation    ! water elevation passed to levelpool (meters AMSL)\n        real                :: levelpool_outflow        ! cubic meters per second (cms)\n        logical             :: max_storage_reached      ! flag for when max storage is reached\n        integer             :: gage_lookback_seconds    ! seconds between current model\n                                                        ! time and the time a gage\n                                                        ! discharge is read\n\n        max_storage_reached = .false.\n        gage_lookback_seconds = 0\n\n        ! Update input variables\n        this%input%inflow = inflow\n        this%input%lateral_inflow = lateral_inflow\n\n        ! The initialization and management of water elevation might diverge between the global state of the model\n        ! and the internal state. The global state water elevation is passed to/from this subroutine at every\n        ! timestep. This check is to help guard against an external piece of code adjusting the global state water\n        ! elevation, which would cause it to no longer be synchronized with internal state water elevation. This\n        ! check also allows this module to borrow from the existing restart capability by initializing reservoirs\n        ! to some default water elevation and storage and then waiting for the first timestep to receive the\n        ! initial condition, so that the reservoir would not need to manage its own restart. If water elevation\n        ! is refactored to no longer be a global state, then this check is not necessary.\n        if (this%state%water_elevation .ne. water_elevation) then\n\n            ! Update state variables\n            this%state%water_elevation = water_elevation\n\n            this%state%current_storage = (this%state%water_elevation - this%properties%orifice_elevation) * &\n            this%properties%lake_area\n\n        end if\n\n        local_water_elevation = this%state%water_elevation\n\n        ! If update time to read new timeslice gage discharges. In forecast modes, the update time automatically is set to\n        ! 1,000,000 to ensure that gage discharges are only read at the first timestep. For analysis runs, a timeslice\n        ! update time is set as a namelist parameter. A typical update time for an analysis run would be 3600 seconds\n        ! (1 hour), at which time new observations would be retrieved. The first reservoir for each processor to reach an\n        ! update time will call the function to read a new timeslice file, and these timeslice discharges will be held in\n        ! memory for the subsequent reservoirs to use at that timestep.\n        if (this%state%current_time >= this%state%timeslice_update_time) then\n\n            ! Read new timeslice gage discharges\n            call this%timeslice_data%setup_read_timeslice(this%properties%observation_update_time_interval_seconds, &\n            this%state%current_time, this%properties%gage_id, gage_lookback_seconds, this%state%gage_discharge, &\n            this%state%assimilated_source_file)\n\n            ! If no good quality gage discharge was found in the given lookback period, the gage discharge is returned\n            ! as -1.0. The persistence weight index will be set out of bounds larger than the array. This causes the\n            ! the weight update logic to set the persistence weight to 0.0. Therefore, only levelpool calculations will be used.\n            if (this%state%gage_discharge < 0.0) then\n\n                ! If at weight update time, then increment persistence weight index.\n                ! Otherwise, continue using previous persistence weight index.\n                if (this%state%current_time >= this%state%weight_update_time) then\n                    ! Increment weight index\n                    this%state%persistence_weight_index = this%state%persistence_weight_index + 1\n\n                    ! Set next weight update time\n                    this%state%weight_update_time = this%state%weight_update_time + this%properties%weight_update_time_interval\n                end if\n\n                ! If out of bounds of array, then set persistence weight to 0.0. Otherwise, set persistence weight from array's indexed value.\n                if (this%state%persistence_weight_index > SIZE(this%properties%persistence_weighted_coefficients)) then\n                    this%state%persistence_current_weight = 0.0\n\n                else\n                    this%state%persistence_current_weight = this%properties%persistence_weighted_coefficients(this%state%persistence_weight_index)\n                end if\n\n            else\n\n                ! Set persisted outflow to gage discharge\n                this%state%persisted_outflow = this%state%gage_discharge\n\n                ! Set assimilated value to gage discharge\n                this%state%assimilated_value = this%state%gage_discharge\n\n                ! Start persistence weight index at 1\n                this%state%persistence_weight_index = 1\n\n                ! Grab first persistence weight at index 1 from array\n                this%state%persistence_current_weight = this%properties%persistence_weighted_coefficients(this%state%persistence_weight_index)\n\n                ! Set weight update time offset by how long back a timeslice discharge was read. For instance, if the weight update interval is\n                ! 24 hours, and the gage discharge was read 2 hours back, then the weight update time will be set to 22 hours after the current time.\n                this%state%weight_update_time = this%state%current_time + this%properties%weight_update_time_interval - gage_lookback_seconds\n\n            end if\n\n            ! Calculate levelpool weight\n            this%state%levelpool_current_weight = 1.0 - this%state%persistence_current_weight\n\n            ! Set timeslice update time\n            this%state%timeslice_update_time = this%state%timeslice_update_time + this%properties%observation_update_time_interval_seconds\n\n        ! If update time to change persistence weights\n        else if (this%state%current_time >= this%state%weight_update_time) then\n\n            ! Increment weight index\n            this%state%persistence_weight_index = this%state%persistence_weight_index + 1\n\n            ! Boundary check to not exceed the size of the persistence weights array\n            if (this%state%persistence_weight_index <= SIZE(this%properties%persistence_weighted_coefficients)) then\n\n                ! Grab indexed persistence weight from array\n                this%state%persistence_current_weight = this%properties%persistence_weighted_coefficients(this%state%persistence_weight_index)\n\n            else\n                ! If boundary of persistence weights array has been exceeded, then set all persistence weights to 0.0\n                this%state%persistence_current_weight = 0.0\n\n            end if\n\n            ! Calculate levelpool weight\n            this%state%levelpool_current_weight = 1.0 - this%state%persistence_current_weight\n\n            ! Set next weight update time\n            this%state%weight_update_time = this%state%weight_update_time + this%properties%weight_update_time_interval\n\n        end if\n\n        ! Referencing issue https://github.com/NCAR/wrf_hydro_nwm_public/issues/326 for the uncertainty about\n        ! previous_timestep_inflow. Further understanding of the exact timing of inflow and previous timestep\n        ! inflow might affect which values are passed to this calling of levelpool and subsequent mass/balance\n        ! calculations.\n        ! Run levelpool reservoir\n        call this%state%levelpool_ptr%run(previous_timestep_inflow, inflow, &\n        lateral_inflow, local_water_elevation, levelpool_outflow, routing_period, this%state%levelpool_reservoir_type, &\n        this%state%levelpool_assimilated_value, this%state%levelpool_assimilated_source_file)\n\n        ! If the levelpool weight is within epsilon of 1.0\n        if (this%state%levelpool_current_weight .ge. 1.0 - epsilon(1.0)) then\n\n            ! Set dynamic_reservoir_type to levelpool type\n            this%state%dynamic_reservoir_type = this%state%levelpool_reservoir_type\n\n            ! Set the assimilated_value to sentinel, -9999.0\n            this%state%assimilated_value = -9999.0\n\n            ! Set the assimilated_source_file to empty string\n            this%state%assimilated_source_file = \"\"\n        else\n\n            ! Set dynamic_reservoir_type to given USGS or USACE type\n            this%state%dynamic_reservoir_type = this%properties%reservoir_type\n        end if\n\n        ! Calculate outflow weighted between persistence and levelpool\n        this%output%outflow = this%state%persistence_current_weight &\n        * this%state%persisted_outflow + this%state%levelpool_current_weight &\n        * levelpool_outflow\n\n        ! Warn if there is a negative inflow\n        call warn_negative_inflow(this%input%inflow, this%properties%lake_number, this%state%current_time)\n\n        ! Modify if exceeding storage boundary conditions\n        call modify_for_projected_storage(this%input%inflow, &\n        this%state%current_storage, this%properties%min_storage, &\n        this%properties%max_storage, this%properties%lake_number, &\n        this%state%current_time, int(routing_period), this%output%outflow, max_storage_reached)\n\n        ! If max storage has been reached, release greater of persistence or levelpool\n        if (max_storage_reached .and. this%output%outflow < levelpool_outflow) then\n            this%output%outflow = levelpool_outflow\n\n            ! Set dynamic_reservoir_type to levelpool type\n            this%state%dynamic_reservoir_type = this%state%levelpool_reservoir_type\n\n            ! Set the assimilated_value to sentinel, -9999.0\n            this%state%assimilated_value = -9999.0\n\n            ! Set the assimilated_source_file to empty string\n            this%state%assimilated_source_file = \"\"\n        end if\n\n        ! Calculate change in storage\n        delta_storage = (this%input%inflow - this%output%outflow) * routing_period\n\n        ! Update storage from the most recent model states\n        this%state%current_storage = this%state%current_storage + delta_storage\n\n        ! Calculate new water elevation. Delta storage is used as opposed to calculating from current storage in\n        ! order to minimize floating point error because current storage is a much larger magnitude than water elevation.\n        this%state%water_elevation = this%state%water_elevation + delta_storage / this%properties%lake_area\n\n        ! Update output variable returned from this subroutine\n        outflow = this%output%outflow\n\n        ! Set current inflow to previous_timestep_inflow\n        this%input%previous_timestep_inflow = inflow\n\n        ! Update water_elevation variable returned from this subroutine\n        water_elevation = this%state%water_elevation\n\n        ! Update the dynamic_reservoir_type returned from this subroutine\n        dynamic_reservoir_type = this%state%dynamic_reservoir_type\n\n        ! Update the assimilated_value returned from this subroutine\n        assimilated_value = this%state%assimilated_value\n\n        ! Update the assimilated_source_file returned from this subroutine\n        assimilated_source_file = this%state%assimilated_source_file\n\n        ! Update the current time\n        this%state%current_time = this%state%current_time + int(routing_period)\n\n#ifdef RESERVOIR_D\n        ! Log diagnostic data only for development/debugging purposes\n        call log_hybrid_diagnostic_data(this%properties%lake_number, this%state%current_time, &\n        this%state%timeslice_update_time, this%state%weight_update_time, gage_lookback_seconds, &\n        this%properties%gage_id, this%state%persistence_weight_index, &\n        this%state%persistence_current_weight, this%input%inflow, this%state%current_storage, &\n        this%state%water_elevation, this%state%gage_discharge, this%state%persisted_outflow, &\n        levelpool_outflow, this%output%outflow)\n#endif\n\n    end subroutine run_hybrid_reservoir\n\nend module module_persistence_levelpool_hybrid\n"
  },
  {
    "path": "src/Routing/Reservoirs/Persistence_Level_Pool_Hybrid/module_persistence_levelpool_hybrid_properties.F90",
    "content": "! This module defines and instantiates objects\n! for a hybrid type reservoir's\n! parameters/properties. Properties holds\n! static/unchanging variables that are\n! set when the given reservoir object is\n! initialized/instantiated.\n\nmodule module_persistence_levelpool_hybrid_properties\n    use module_reservoir_utilities, only: read_netcdf_lake_id, &\n                                          read_persistence_netcdf_gage_id, &\n                                          read_persistence_netcdf_real_2D_parameters, &\n                                          handle_err\n    use module_reservoir, only: reservoir_properties\n    use netcdf\n    use iso_fortran_env, only: int64\n    implicit none\n\n    ! Extend/derive hybrid properties from the abstract base\n    ! type for reservoir properties.\n    type, extends(reservoir_properties) :: hybrid_properties_interface\n        real    :: min_storage                  ! minimum storage (cubic meters)\n        real    :: max_storage                  ! maximum storage (cubic meters)\n        real    :: lake_area                    ! area of reservoir (meters^2)\n        real    :: orifice_elevation            ! orifice elevation (meters AMSL)\n        integer :: lake_number                  ! lake number\n        integer :: reservoir_type               ! reservoir type\n        character(len=15) :: gage_id\n        integer :: observation_lookback_hours\n        integer :: observation_update_time_interval_seconds\n        integer :: weight_update_time_interval\n        real, allocatable, dimension(:) :: persistence_weighted_coefficients\n\n    contains\n\n        procedure :: init => hybrid_properties_init\n        procedure :: destroy => hybrid_properties_destroy\n\n    end type hybrid_properties_interface\n\n    integer, parameter :: seconds_in_day = 86400\n\ncontains\n\n    ! Hybrid Properties Constructor\n    subroutine hybrid_properties_init(this, lake_area, lake_max_water_elevation, orifice_elevation, lake_number, &\n        reservoir_type, observation_lookback_hours, observation_update_time_interval_seconds, reservoir_parameter_file)\n        implicit none\n        class(hybrid_properties_interface), intent(inout) :: this ! the type object being initialized\n        real,    intent(in)          :: lake_area                    ! area of lake (km^2)\n        real,    intent(in)          :: lake_max_water_elevation     ! max water elevation (meters)\n        real,    intent(in)          :: orifice_elevation            ! orifice elevation (meters AMSL)\n        integer(kind=int64), intent(in)  :: lake_number                  ! lake number\n        integer, intent(in)          :: reservoir_type               ! reservoir type\n        integer, intent(in)          :: observation_lookback_hours\n        integer, intent(in)          :: observation_update_time_interval_seconds\n        character(len=*), intent(in) :: reservoir_parameter_file\n        integer                      :: ncid, var_id, lake_id_index\n        integer                      :: status                        ! status of reading NetCDF\n        integer                      :: number_of_weights, number_of_lakes\n        real, allocatable, dimension(:,:) :: temp_real_2D_array\n\n        ! Convert from km^2 to meters^2\n        this%lake_area = lake_area * 1.0E6\n\n        this%orifice_elevation = orifice_elevation\n\n        this%lake_number = lake_number\n\n        this%reservoir_type = reservoir_type\n\n        this%observation_lookback_hours = observation_lookback_hours\n\n        this%observation_update_time_interval_seconds = observation_update_time_interval_seconds\n\n        this%weight_update_time_interval = seconds_in_day\n\n        this%min_storage = 0.0\n\n        this%max_storage = (lake_max_water_elevation - orifice_elevation) * lake_area * 1.0E6\n\n        ! Open Reservoir Parameter NetCDF file\n        status = nf90_open(path = reservoir_parameter_file, mode = nf90_nowrite, ncid = ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not open reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        ! Read relevant properties from Reservoir Parameter NetCDF\n        ! If reservoir_type is 2, then look for USGS parameters\n        if (this%reservoir_type == 2) then\n\n            call read_netcdf_lake_id(ncid, lake_number, \"usgs_lake_id\", reservoir_parameter_file, lake_id_index)\n\n            call read_persistence_netcdf_gage_id(ncid, lake_id_index, \"usgs_gage_id\", reservoir_parameter_file, this%gage_id)\n\n            call read_persistence_netcdf_real_2D_parameters(ncid, lake_id_index, \"usgs_persistence_coefficients\", &\n            reservoir_parameter_file, var_id, number_of_weights, number_of_lakes)\n\n            allocate(this%persistence_weighted_coefficients(number_of_weights))\n\n            allocate(temp_real_2D_array(number_of_weights, number_of_lakes))\n\n            status = nf90_get_var(ncid, var_id, temp_real_2D_array)\n            if (status /= nf90_noerr) call handle_err(status, \"Error reading usgs_persistence_coefficients from \" &\n            // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        ! If reservoir_type is 3, then look for ACE parameters\n        else if (this%reservoir_type == 3) then\n\n            call read_netcdf_lake_id(ncid, lake_number, \"usace_lake_id\", reservoir_parameter_file, lake_id_index)\n\n            call read_persistence_netcdf_gage_id(ncid, lake_id_index, \"usace_gage_id\", reservoir_parameter_file, this%gage_id)\n\n            call read_persistence_netcdf_real_2D_parameters(ncid, lake_id_index, \"usace_persistence_coefficients\", &\n            reservoir_parameter_file, var_id, number_of_weights, number_of_lakes)\n\n            allocate(this%persistence_weighted_coefficients(number_of_weights))\n\n            allocate(temp_real_2D_array(number_of_weights, number_of_lakes))\n\n            status = nf90_get_var(ncid, var_id, temp_real_2D_array)\n            if (status /= nf90_noerr) call handle_err(status, \"Error reading usace_persistence_coefficients from \" &\n            // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        end if\n\n        this%persistence_weighted_coefficients(:) = temp_real_2D_array(:, lake_id_index)\n\n        if(allocated(temp_real_2D_array)) deallocate(temp_real_2D_array)\n\n        status = nf90_close(ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not close reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n    end subroutine hybrid_properties_init\n\n    ! Hybrid Properties Destructor\n    subroutine hybrid_properties_destroy(this)\n        implicit none\n        class(hybrid_properties_interface), intent(inout) :: this ! the type object being destroyed\n    end subroutine hybrid_properties_destroy\n\nend module module_persistence_levelpool_hybrid_properties\n"
  },
  {
    "path": "src/Routing/Reservoirs/Persistence_Level_Pool_Hybrid/module_persistence_levelpool_hybrid_state.F90",
    "content": "! This module defines and instantiates objects\n! for a hybrid type reservoir's state.\n! State holds and tracks dynamic/changing variables\n! that are only relevant to the given hybrid\n! reservoir object and not other modules or areas\n! of the system.\n\nmodule module_persistence_levelpool_hybrid_state\n\n    use module_levelpool, only: levelpool\n    use module_reservoir, only: reservoir_state\n    implicit none\n\n    ! Extend/derive hybrid state from the abstract base\n    ! type for reservoir state.\n    type, extends(reservoir_state) :: hybrid_state_interface\n        real    :: water_elevation              ! meters AMSL\n        real*4  :: current_storage              ! cubic meters\n        real    :: gage_discharge               ! cubic meters per second (cms)\n        real    :: persisted_outflow            ! cubic meters per second (cms)\n        integer :: weight_update_time           ! seconds\n        integer :: timeslice_update_time        ! seconds\n        integer :: current_time                 ! seconds\n        integer :: persistence_weight_index\n        real    :: levelpool_current_weight\n        real    :: persistence_current_weight\n        integer :: dynamic_reservoir_type       ! dynamic reservoir type sent to lake out files\n        real    :: assimilated_value\n        character(len=256) :: assimilated_source_file\n        integer :: levelpool_reservoir_type     ! reservoir type for levelpool\n        real    :: levelpool_assimilated_value  ! levelpool assimilated sentinel value\n        character(len=256) :: levelpool_assimilated_source_file ! none for levelpool assimilated source\n\n        type (levelpool), pointer :: levelpool_ptr   ! pointer to levelpool object\n\n    contains\n\n        procedure :: init => hybrid_state_init\n        procedure :: destroy => hybrid_state_destroy\n\n    end type hybrid_state_interface\n\n    integer, parameter :: seconds_in_day = 86400\n\ncontains\n\n    !Hybrid State Constructor\n    subroutine hybrid_state_init(this, water_elevation, lake_area, lake_max_water_elevation, orifice_elevation, &\n        initial_fractional_depth, reservoir_type)\n        implicit none\n        class(hybrid_state_interface), intent(inout) :: this ! the type object being initialized\n        real, intent(in)    :: water_elevation           ! meters AMSL\n        real, intent(in)    :: lake_area                 ! area of lake (km^2)\n        real, intent(in)    :: lake_max_water_elevation  ! max water elevation (meters)\n        real, intent(in)    :: orifice_elevation         ! orifice elevation (meters AMSL)\n        real, intent(in)    :: initial_fractional_depth  ! initial fraction water depth\n        integer, intent(in) :: reservoir_type            ! reservoir type\n\n        ! Initialize the state water elevation in same manner as in module_RT.F\n        this%water_elevation = orifice_elevation + ((lake_max_water_elevation - orifice_elevation) * initial_fractional_depth)\n\n        this%current_storage = (this%water_elevation - orifice_elevation) * lake_area * 1.0E6\n\n        this%gage_discharge = 0.0\n        this%persisted_outflow = 0.0\n\n        this%weight_update_time = 0\n        this%timeslice_update_time = 0\n        this%current_time = 0\n\n        this%persistence_weight_index = 0\n        this%levelpool_current_weight = 0.0\n        this%persistence_current_weight = 0.0\n\n        ! If reservoir_type is set to 2 for USGS type, then set the dynamic_reservoir_type also to 2.\n        if (reservoir_type == 2) then\n            this%dynamic_reservoir_type = 2\n\n        ! If reservoir_type is set to 3 for USACE type, then set the dynamic_reservoir_type also to 3.\n        else if (reservoir_type == 3) then\n            this%dynamic_reservoir_type = 3\n        end if\n\n        ! Initialize to default sentinel, -9999.0\n        this%assimilated_value = -9999.0\n\n        ! Initialize to default empty string\n        this%assimilated_source_file = \"\"\n\n        ! Levelpool reservoir type set to 1\n        this%levelpool_reservoir_type = 1\n\n        ! Set to default sentinel, -999.0\n        this%levelpool_assimilated_value = -9999.0\n\n        ! Set to default string\n        this%levelpool_assimilated_source_file = \"\"\n\n    end subroutine hybrid_state_init\n\n    !Hybrid State Destructor\n    subroutine hybrid_state_destroy(this)\n        implicit none\n        class(hybrid_state_interface), intent(inout) :: this ! the type object being destroyed\n\n    end subroutine hybrid_state_destroy\n\nend module module_persistence_levelpool_hybrid_state\n"
  },
  {
    "path": "src/Routing/Reservoirs/Persistence_Level_Pool_Hybrid/module_persistence_levelpool_hybrid_tests.F90",
    "content": "! This module holds tests for initialization of\n! various attributes of a persistence levelpool\n! hybrid reservoir.\nmodule module_persistence_levelpool_hybrid_tests\n    use module_persistence_levelpool_hybrid\n\ncontains\n\n    ! Testing\n    function persistence_levelpool_hybrid_data_info(hybrid_data) result(rv)\n        implicit none\n        type (persistence_levelpool_hybrid) :: hybrid_data\n        logical :: rv\n        logical, dimension(8) :: ptr_state\n        logical, dimension(8) :: data_state\n\n        rv = .false.\n\n        ! Check to see if the hybrid_state data structure exists\n        print *, \"Checking pointer association on hybrid_data%state \"\n        if ( associated(hybrid_data%state) ) then\n            print *, \"PASSED\"\n            ptr_state(1) = .true.\n       else\n            print *, \"FAILED\"\n            ptr_state(1) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the hybrid_properties data structure exists\n        print *, \"Checking pointer association on hybrid_data%properties \"\n        if ( associated(hybrid_data%properties) ) then\n            print *, \"PASSED\"\n            ptr_state(2) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(2) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the hybrid_input data structure exists\n        print *, \"Checking pointer association on hybrid_data%input \"\n        if ( associated(hybrid_data%input) ) then\n            print *, \"PASSED\"\n            ptr_state(3) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(3) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the hybrid_output data structure exists\n        print *, \"Checking pointer association on hybrid_data%output \"\n        if ( associated(hybrid_data%output) ) then\n            print *, \"PASSED\"\n            ptr_state(4) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(4) = .false.\n        end if\n        print *, \" \"\n\n\n        ! Test levelpool structure\n        ! Check to see if the hybrid levelpool_state data structure exists\n        print *, \"Checking pointer association on hybrid_data%levelpool_state for hybrid reservoirs\"\n        if ( associated(hybrid_data%state%levelpool_ptr%state) ) then\n            print *, \"PASSED\"\n            ptr_state(5) = .true.\n       else\n            print *, \"FAILED\"\n            ptr_state(5) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the hybrid levelpool_properties data structure exists\n        print *, \"Checking pointer association on data%levelpool_properties for hybrid reservoirs\"\n        if ( associated(hybrid_data%state%levelpool_ptr%properties) ) then\n            print *, \"PASSED\"\n            ptr_state(6) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(6) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the hybrid levelpool_input data structure exists\n        print *, \"Checking pointer association on data%levelpool_input for hybrid reservoirs\"\n        if ( associated(hybrid_data%state%levelpool_ptr%input) ) then\n            print *, \"PASSED\"\n            ptr_state(7) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(7) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the hybrid levelpool_output data structure exists\n        print *, \"Checking pointer association on data%levelpool_output for hybrid reservoirs\"\n        if ( associated(hybrid_data%state%levelpool_ptr%output) ) then\n            print *, \"PASSED\"\n            ptr_state(8) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(8) = .false.\n        end if\n        print *, \" \"\n\n\n        ! Now check the data members of each substructure\n        if ( ptr_state(1) ) then\n            data_state(1) = test_persistence_levelpool_hybrid_state(hybrid_data%state)\n        end if\n\n        if ( ptr_state(2) ) then\n            data_state(2) = test_persistence_levelpool_hybrid_properties(hybrid_data%properties)\n        end if\n\n        if ( ptr_state(3) ) then\n            data_state(3) = test_input_persistence_levelpool_hybrid(hybrid_data%input)\n        end if\n\n        if ( ptr_state(4) ) then\n            data_state(4) = test_output_persistence_levelpool_hybrid(hybrid_data%output)\n        end if\n\n        ! Test Levelpool Substructures\n        if ( ptr_state(5) ) then\n            data_state(5) = test_hybrid_levelpool_state(hybrid_data%state)\n        end if\n\n        if ( ptr_state(6) ) then\n            data_state(6) = test_hybrid_levelpool_properties(hybrid_data%state)\n        end if\n\n        if ( ptr_state(7) ) then\n            data_state(7) = test_hybrid_levelpool_input(hybrid_data%state%levelpool_ptr%input)\n        end if\n\n        if ( ptr_state(8) ) then\n            data_state(8) = test_hybrid_levelpool_output(hybrid_data%state%levelpool_ptr%output)\n        end if\n\n\n        if ( all(ptr_state) .and. all(data_state) ) then\n            print *, \"========================================================================\"\n            print *, \"All Hybrid Object Tests Passed\"\n            print *, \"========================================================================\"\n            rv = .true.\n\n        else\n            print *, \"========================================================================\"\n            print *, \"Not All Hybrid Object Tests Passed\"\n            print *, \"========================================================================\"\n\n        end if\n\n        flush(6)\n    end function persistence_levelpool_hybrid_data_info\n\n\n    ! Test to see that each member of the input structure is correctly allocated and readable\n    function test_input_persistence_levelpool_hybrid(o) result(rv)\n        type (reservoir_input), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the input structure\"\n        print *, \" \"\n\n        print *, \"Checking read on inflow\"\n        print *, o%inflow\n        if ( o%inflow .lt. 0.0 - epsilon(0.0) .or. o%inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lateral_inflow\"\n        print *, o%lateral_inflow\n        if ( o%lateral_inflow .lt. 0.0 - epsilon(0.0) .or. o%lateral_inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on previous_timestep_inflow\"\n        print *, o%previous_timestep_inflow\n        if ( o%previous_timestep_inflow .lt. 0.0 - epsilon(0.0) .or. o%previous_timestep_inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_input_persistence_levelpool_hybrid\n\n    ! Test to see that each member of the output structure is correctly allocated and readable\n    function test_output_persistence_levelpool_hybrid(o) result(rv)\n        type (reservoir_output), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the output structure\"\n        print *, \" \"\n\n        print *, \"Checking read on outflow\"\n        print *, o%outflow\n        if ( o%outflow .lt. 0.0 - epsilon(0.0) .or. o%outflow .gt. 0.0 + epsilon(0.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_output_persistence_levelpool_hybrid\n\n    ! Test to see that each member of the state structure is correctly allocated and readable\n    function test_persistence_levelpool_hybrid_state(o) result(rv)\n        type (hybrid_state_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the hybrid state data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on water_elevation\"\n        print *, o%water_elevation\n        if ( o%water_elevation .lt. 1333.10938 - epsilon(1333.109380) .or. o%water_elevation .gt. 1333.10938 + epsilon(1333.10938) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on current_storage\"\n        print *, o%current_storage\n        if ( o%current_storage .lt. 3.90669926E+09 - epsilon(3.90669926E+09) .or. o%current_storage .gt. 3.90669926E+09 + epsilon(3.90669926E+09) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on gage_discharge\"\n        print *, o%gage_discharge\n        if ( o%gage_discharge .lt. 0.0 - epsilon(0.0) .or. o%gage_discharge .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on persisted_outflow\"\n        print *, o%persisted_outflow\n        if ( o%persisted_outflow .lt. 0.0 - epsilon(0.0) .or. o%persisted_outflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weight_update_time\"\n        print *, o%weight_update_time\n        if ( o%weight_update_time .ne. 0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on timeslice_update_time\"\n        print *, o%timeslice_update_time\n        if ( o%timeslice_update_time .ne. 0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on current_time\"\n        print *, o%current_time\n        if ( o%current_time .ne. 0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on persistence_weight_index\"\n        print *, o%persistence_weight_index\n        if ( o%persistence_weight_index .ne. 12) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on levelpool_current_weight\"\n        print *, o%levelpool_current_weight\n        if ( o%levelpool_current_weight .lt. 0.0 - epsilon(0.0) .or. o%levelpool_current_weight .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on persistence_current_weight\"\n        print *, o%persistence_current_weight\n        if ( o%persistence_current_weight .lt. 0.0 - epsilon(0.0) .or. o%persistence_current_weight .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_persistence_levelpool_hybrid_state\n\n\n    ! Test to see that each member of the properties structure is correctly allocated and readable\n    function test_persistence_levelpool_hybrid_properties(o) result(rv)\n        type (hybrid_properties_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the hybrid properties data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on min_storage\"\n        print *, o%min_storage\n        if ( o%min_storage .lt. 0.0 - epsilon(0.0) .or. o%min_storage .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on max_storage\"\n        print *, o%max_storage\n        if ( o%max_storage .lt. 4.34078003E+09 - epsilon(4.34078003E+09) .or. o%max_storage .gt. 4.34078003E+09 + epsilon(4.34078003E+09) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lake_area\"\n        print *, o%lake_area\n        if ( o%lake_area .lt. 209632000.0 - epsilon(209632000.0) .or. o%lake_area .gt. 209632000.0 + epsilon(209632000.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_elevation\"\n        print *, o%orifice_elevation\n        if ( o%orifice_elevation .lt. 1314.47339 - epsilon(1314.47339) .or. o%orifice_elevation .gt. 1314.47339 + epsilon(1314.47339) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lake_number\"\n        print *, o%lake_number\n        if ( o%lake_number .ne. 402142) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on gage_id\"\n        print *, o%gage_id\n        if ( ADJUSTL(trim(o%gage_id)) .ne. '07198000') then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on observation_lookback_hours\"\n        print *, o%observation_lookback_hours\n        if ( o%observation_lookback_hours .ne. 12) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on observation_update_time_interval_seconds\"\n        print *, o%observation_update_time_interval_seconds\n        if ( o%observation_update_time_interval_seconds .ne. 1000000000) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weight_update_time_interval\"\n        print *, o%weight_update_time_interval\n        if ( o%weight_update_time_interval .ne. 86400) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on persistence_weighted_coefficients\"\n        print *, o%persistence_weighted_coefficients\n        if ( o%persistence_weighted_coefficients(1) .lt. 1.0 - epsilon(1.0) .or. o%persistence_weighted_coefficients(1) .gt. 1.0 + epsilon(1.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_persistence_levelpool_hybrid_properties\n\n\n    ! Levelpool data tests\n    ! Test to see that each member of the levelpool input structure is correctly allocated and readable\n    function test_hybrid_levelpool_input(o) result(rv)\n        type (reservoir_input), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the hybrid levelpool input structure\"\n        print *, \" \"\n\n        print *, \"Checking read on inflow\"\n        print *, o%inflow\n        if ( o%inflow .lt. 0.0 - epsilon(0.0) .or. o%inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lateral_inflow\"\n        print *, o%lateral_inflow\n        if ( o%lateral_inflow .lt. 0.0 - epsilon(0.0) .or. o%lateral_inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on previous_timestep_inflow\"\n        print *, o%previous_timestep_inflow\n        if ( o%previous_timestep_inflow .lt. 0.0 - epsilon(0.0) .or. o%previous_timestep_inflow .gt. 0.0 + epsilon(0.0) )then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_hybrid_levelpool_input\n\n    ! Test to see that each member of the levelpool output structure is correctly allocated and readable\n    function test_hybrid_levelpool_output(o) result(rv)\n        type (reservoir_output), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the hybrid levelpool output structure\"\n        print *, \" \"\n\n        print *, \"Checking read on outflow\"\n        print *, o%outflow\n        if ( o%outflow .lt. 0.0 - epsilon(0.0) .or. o%outflow .gt. 0.0 + epsilon(0.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_hybrid_levelpool_output\n\n    ! Test to see that each member of the levelpool state structure is correctly allocated and readable\n    function test_hybrid_levelpool_state(o) result(rv)\n        type (hybrid_state_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the hybrid levelpool state data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on water_elevation\"\n        print *, o%levelpool_ptr%state%water_elevation\n        if ( o%levelpool_ptr%state%water_elevation .lt. 0.0 - epsilon(0.0) .or. o%levelpool_ptr%state%water_elevation .gt. 0.0 + epsilon(0.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_hybrid_levelpool_state\n\n\n    ! Test to see that each member of the levelpool properties structure is correctly allocated and readable\n    function test_hybrid_levelpool_properties(o) result(rv)\n        type (hybrid_state_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the hybrid levelpool properties data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on lake_area\"\n        print *, o%levelpool_ptr%properties%lake_area\n        if ( o%levelpool_ptr%properties%lake_area .lt. 209.632004 - epsilon(209.632004) .or. o%levelpool_ptr%properties%lake_area .gt. 209.632004 + epsilon(209.632004) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_elevation\"\n        print *, o%levelpool_ptr%properties%weir_elevation\n        if ( o%levelpool_ptr%properties%weir_elevation .lt. 1332.07410 - epsilon(1332.07410) .or. o%levelpool_ptr%properties%weir_elevation .gt. 1332.07410 + epsilon(1332.07410) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_coeffecient\"\n        print *, o%levelpool_ptr%properties%weir_coeffecient\n        if ( o%levelpool_ptr%properties%weir_coeffecient .lt. 0.400000006 - epsilon(0.400000006) .or. o%levelpool_ptr%properties%weir_coeffecient .gt. 0.400000006 + epsilon(0.400000006) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_length\"\n        print *, o%levelpool_ptr%properties%weir_length\n        if ( o%levelpool_ptr%properties%weir_length .lt. 10.0 - epsilon(10.0) .or. o%levelpool_ptr%properties%weir_length .gt. 10.0 + epsilon(10.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_elevation\"\n        print *, o%levelpool_ptr%properties%orifice_elevation\n        if ( o%levelpool_ptr%properties%orifice_elevation .lt. 1314.47339 - epsilon(1314.47339) .or. o%levelpool_ptr%properties%orifice_elevation .gt. 1314.47339 + epsilon(1314.47339) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_coefficient\"\n        print *, o%levelpool_ptr%properties%orifice_coefficient\n        if ( o%levelpool_ptr%properties%orifice_coefficient .lt. 0.100000001 - epsilon(0.100000001) .or. o%levelpool_ptr%properties%orifice_coefficient .gt. 0.100000001 + epsilon(0.100000001) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_area\"\n        print *, o%levelpool_ptr%properties%orifice_area\n        if ( o%levelpool_ptr%properties%orifice_area .lt. 1.0 - epsilon(1.0) .or. o%levelpool_ptr%properties%orifice_area .gt. 1.0 + epsilon(1.0) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on max_depth\"\n        print *, o%levelpool_ptr%properties%max_depth\n        if ( o%levelpool_ptr%properties%max_depth .lt. 1335.18005 - epsilon(1335.18005) .or. o%levelpool_ptr%properties%max_depth .gt. 1335.18005 + epsilon(1335.18005) ) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lake_number\"\n        print *, o%levelpool_ptr%properties%lake_number\n        if ( o%levelpool_ptr%properties%lake_number .ne. 402142) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_hybrid_levelpool_properties\n\nend module\n"
  },
  {
    "path": "src/Routing/Reservoirs/Persistence_Level_Pool_Hybrid_Module_README.md",
    "content": "# Peristence-Level Pool Hybrid Module\n\n### General Purpose and Functionality\n\nThe purpose of this module is to persist observed reservoir discharges in order to improve the accuracy of discharge predictions. This\nmodule replaces the normal Level Pool object for a particular reservoir that is selected to run as Persistence type though it does\ninstantiate a Level Pool object as a member. The Hybrid object simultaneously runs this Level Pool member to calculate a release\nand combines that release with an observed discharge to produce a final release at each timestep.\n\nThe observed discharge and the calculated\nlevel pool release are each multiplied by a fractional weight and then summed to give a final calculated release. The fractional weights\nare determined by the length of model time between the observed discharge and the current release calculation. For example, if a release\nis calculated 12 hours in model time after an observation is read, then a weight of 1.0 might be applied to this observed discharge, and\na corresponding weight of 0.0 would be applied to the level pool calculated release. The resulting summed release would be the same as\nthe observed discharge. If a release is calculated 5 days in model time after an observation is read, then a weight of 0.2 might be\napplied to the observed discharge, and a corresponding weight of 0.8 would be applied to the level pool calculated release. These weighted\nvalues would then be summed to give a final release. If observations are missing or are not good quality for a given time window, then\nfull weight of 1.0 is given to the level pool release.\n\nPartial autocorrelation is performed in advance from historical reservoir data to determine the appropriate weights for each reservoir.\nThese weights are read in from a reservoir persistence parameter file whenever a reservoir of this type is initialized.\n\nBefore the final calculated release/outflow is returned from this module back to the model at each timestep, mass balance checks are\nperformed to ensure the calculated release does not cause the reservoir storage to fall below the minimum or exceed the max, and the\nrelease is modified accordingly.\n\n\n### Module Architecture\n\nThis module builds off of the same class structure and architecture of the Level Pool module. As in Level Pool, each reservoir in this\nmodule is instantiated into an object at model initialization. The **Persistence_Level_Pool_Hybrid** directory contains the following files:\n\n* **module_persistence_levelpool_hybrid.F** defines and instantiates objects for a hybrid persistence levelpool type\nreservoir. **module_RT.F** will call and pass properties to the constructor in this module to instantiate the hybrid reservoir\nobject and its sub-objects. The hybrid reservoir type inherits input and output types from the reservoir base module and calls\ninstantiation of these into sub-objects. The hybrid reservoir type also points to types for hybrid properties and state and calls\ninstantiation of these into sub-objects. A pointer to a levelpool reservoir object is also held in state, and this module\ninstantiates that levelpool object. There is also a subroutine to run hybrid reservoir that is derived from the reservoir base\ntype interface to run reservoir. The run reservoir function will periodically call a function in **module_reservoir_read_timeslice_data.F**\nthat will read a timeslice file and return a corresponding observed discharge. The\ntimeslice files will be read at a particular update time. For a particular timestep, the first hybrid reservoir on each processor to\nreach an update time at that timestep will call the function to read the timeslice files, which will read the observations for every\nreservoir and store those values in an array. Each subsequent reservoir held by the same processor at that timestep that reaches its\nupdate time will read its corresponding observation from the array. The run reservoir function also performs the functionality described\nabove including calling level pool run reservoir along with weighting and combining that release with the weighted observed discharge,\nand finally calling mass balance checks before returning the release/outflow back to the model.\n\n* **module_persistence_levelpool_hybrid_properties.F** defines and instantiates objects for a hybrid type reservoir's\nparameters/properties. Properties holds static/unchanging variables that are set when the given reservoir object is\ninitialized/instantiated.\n\n* **module_persistence_levelpool_hybrid_state.F** defines and instantiates objects for a hybrid type reservoir's state.\nState holds and tracks dynamic/changing variables that are only relevant to the given hybrid reservoir object and not other\nmodules or areas of the system.\n\n* **module_persistence_levelpool_hybrid_tests.F** holds unit tests that test for all components of a hybrid reservoir\nare properly initialized.\n\n* **module_reservoir_read_timeslice_data.F** within the **Reservoirs** directory, reads USGS (U.S. Geological Survey) or\nUSACE (U.S. Army Corps of Engineers) timeslice files to get gage discharge values that will be used by reservoirs. An\nobservation lookback period is passed in to determine how far back in time from the current model time the module will\nlook for timeslice files. The observation resolution determines the time increments the module will look back. For instance,\na standard lookback period would be 24 hours with an observation resolution of 15 minutes, where a model current time of\n8:00 PM would search for timeslice files at every 15 minute increment between 8:00 PM that day and 8:00 PM the day before. The module will\nfirst search for the most recent timeslice files and grab the discharge for a particular lake/reservoir if the gage quality\nstandard is met at that time. If a gage discharge is missing or if the gage quality standard is not met for any particular\nlake/reservoir in the given timeslice file, the module will continue to look back at every observation resolution increment\nuntil either all lakes/reservoirs have a good quality discharge or the end of the lookback period is reached. The total\nlookback seconds from current model time that the discharge is read will also be returned.\n\n* **module_reservoir_utilities.F**, also within the **Reservoirs** directory,\ncontains multiple functions used by the Hybrid module. The modify_for_projected_storage function is called from the\nhybrid run reservoir function and modifies the outflow if a projected storage falls below the minimum or exceeds the\nmaximum for the reservoir. There are also multiple functions used for reading variables from the reservoir\npersistence parameter and timeslice NetCDF files.\n\n\n### Input Parameters\n\nThis module requires six input parameters that are set in hydro.namelist.\n\n* ```reservoir_persistence_usgs``` is a boolean parameter that will need to be set to ```.TRUE.``` for this module to be activated for USGS persistence. This will set\nthe model variable ```reservoir_type_specified``` to ```TRUE``` and cause the model to read the reservoir_type variable from the reservoir parameter file.\nThe reservoir_type for a USGS hybrid persistence reservoir is currently set to '2' in the reservoir parameter file.\n\n* ```reservoir_persistence_usace``` is a boolean parameter that will need to be set to ```.TRUE.``` for this module to be activated for USACE. This will set\nthe model variable ```reservoir_type_specified``` to ```TRUE``` and cause the model to read the reservoir_type variable from the reservoir parameter file.\nThe reservoir_type for a USCAE hybrid persistence reservoir is currently set to '3' in the reservoir parameter file.\n\n* ```reservoir_parameter_file``` is the NetCDF parameter file that holds the weights and corresponding gage ID for each lake ID.\n\n* ```reservoir_usgs_timeslice_path``` is the path to all USGS\ntimeslice files used by this module.\n\n* ```reservoir_usace_timeslice_path``` is the path to all USACE\ntimeslice files used by this module.\n\n* ```reservoir_observation_lookback_hours``` is an integer parameter that specifies how many hours before the model start time the module will\nsearch for a corresponding timeslice file, and '24' would be a typical value and is the default.\n\n* ```reservoir_observation_update_time_interval_seconds``` is an integer parameter that determines how often the reservoirs will look for a new timeslice\nobservation, and '86400', the number of seconds in a day, is the default. This should be set to 1,000,000,000 seconds for Short-Range\nand Medium-Range Forecasts in order to prevent the module from reading any new timeslice observations after the first timestep. It should be set to 3600\nseconds for Standard and Extended AnA simulations.\n\n\n### Testing\n\nTo compile and run the unit tests, first go to the NDHMS directory and type\n```\n./compile_offline_NoahMP.sh template/setEnvar.sh\n```\n\nand hit enter. Then go to the Reservoir directory in the terminal and type\n\n```\nmake\n```\n\nand hit enter. Then type\n\n```\nmake test\n```\n\nand hit enter. Then type\n\n```\n./reservoir_tests\n```\n\nand hit enter.\nThe user should see \"All Reservoir Tests Passed\".\n"
  },
  {
    "path": "src/Routing/Reservoirs/RFC_Forecasts/CMakeLists.txt",
    "content": "add_library(hydro_routing_reservoirs_rfc STATIC\n        module_rfc_forecasts.F90\n        module_rfc_forecasts_state.F90\n        module_rfc_forecasts_properties.F90\n)\n\nadd_dependencies(hydro_routing_reservoirs_rfc\n        hydro_routing_reservoirs\n        hydro_routing_reservoirs_levelpool\n)\n"
  },
  {
    "path": "src/Routing/Reservoirs/RFC_Forecasts/Makefile",
    "content": "\ninclude ../../../macros\n\nMODFLAG := -I ../../../MPP -I ../../../mod\n\n%.o : %.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) $<\n\n.PHONY: all mod test\n\nall: mod\n\nmod:\n\t#Build each sub module then build the module that depends on all sub modules\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_rfc_forecasts_properties.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_rfc_forecasts_state.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_rfc_forecasts.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_rfc_forecasts_tests.F90\n\tar -r ../../../lib/libHYDRO.a module_rfc_forecasts_properties.o\n\tar -r ../../../lib/libHYDRO.a module_rfc_forecasts_state.o\n\tar -r ../../../lib/libHYDRO.a module_rfc_forecasts.o\n\tar -r ../../../lib/libHYDRO.a module_rfc_forecasts_tests.o\n\n\tcp *.mod ../../../mod\n\nclean:\n\trm -f *.o\n\trm -f *.mod\n"
  },
  {
    "path": "src/Routing/Reservoirs/RFC_Forecasts/module_rfc_forecasts.F90",
    "content": "! This module defines and instantiates objects\n! for a RFC Forecasts type reservoir. The RFC\n! Forecasts reservoir type inherits input and\n! output types from the reservoir base module\n! and calls instantiation of these into\n! sub-objects. The RFC Forecasts reservoir\n! type also points to types for RFC Forecasts\n! properties and state and calls instantiation\n! of these into sub-objects. There is also a\n! subroutine to run RFC Forecasts reservoir\n! that is derived from the reservoir base\n! type interface to run reservoir.\n\nmodule module_rfc_forecasts\n\n    use module_rfc_forecasts_properties, only: rfc_forecasts_properties_interface\n    use module_rfc_forecasts_state, only: rfc_forecasts_state_interface\n    use module_levelpool, only: levelpool\n    use module_reservoir_utilities, only: create_rfc_forecasts_diagnostic_log_file, &\n                                          log_rfc_forecasts_diagnostic_data\n    use module_reservoir, only: reservoir, reservoir_input, reservoir_output\n    use module_reservoir_read_rfc_time_series_data, only: time_series_data\n    use module_hydro_stop, only: HYDRO_stop\n    use iso_fortran_env, only: int64\n    implicit none\n\n    ! Extend/derive rfc forecasts type from the abstract base\n    ! type for reservoirs.\n    type, extends(reservoir) :: rfc_forecasts\n\n        ! Define pointers to sub-types / sub-objects to and\n        ! held by an rfc reservoir object.\n        type (rfc_forecasts_properties_interface), pointer :: properties => null()\n        type (rfc_forecasts_state_interface), pointer :: state => null()\n\n        logical :: pointer_allocation_guard = .false.\n\n    contains\n\n        procedure :: init => rfc_forecasts_init\n        procedure :: destroy => rfc_forecasts_destroy\n        procedure :: run => run_rfc_forecasts_reservoir\n\n    end type rfc_forecasts\n\n#ifndef NCEP_WCOSS\n    integer, parameter :: log_warning = 6\n#else\n    integer, parameter :: log_warning = 78\n#endif\n\ncontains\n\n    ! RFC Forecasts Constructor\n    subroutine rfc_forecasts_init(this, water_elevation,  &\n        lake_area, weir_elevation, weir_coeffecient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, &\n        orifice_area, lake_max_water_elevation, initial_fractional_depth, &\n        lake_number, reservoir_type, reservoir_parameter_file, start_date, &\n        time_series_path, forecast_lookback_hours)\n\n        implicit none\n        class(rfc_forecasts), intent(inout) :: this ! object being initialized\n        real,    intent(inout) :: water_elevation           ! meters AMSL\n        real,    intent(in)    :: lake_area      \t\t    ! area of lake (km^2)\n        real,    intent(in)    :: weir_elevation            ! bottom of weir elevation (meters AMSL)\n        real,    intent(in)    :: weir_coeffecient          ! weir coefficient\n        real,    intent(in)    :: weir_length               ! weir length (meters)\n        real,    intent(in)    :: dam_length                ! dam length (meters)\n        real,    intent(in)    :: orifice_elevation         ! orifice elevation (meters AMSL)\n        real,    intent(in)    :: orifice_coefficient       ! orifice coefficient\n        real,    intent(in)    :: orifice_area              ! orifice area (meters^2)\n        real,    intent(in)    :: lake_max_water_elevation  ! max water elevation (meters)\n        real,    intent(in)    :: initial_fractional_depth  ! initial fraction water depth\n        integer(kind=int64), intent(in)    :: lake_number               ! lake number\n        integer, intent(in)    :: reservoir_type            ! reservoir type\n        character(len=*),   intent(in) :: reservoir_parameter_file\n        character(len=19),  intent(in) :: start_date\n        character(len=256), intent(in) :: time_series_path\n        integer,            intent(in) :: forecast_lookback_hours\n        integer                        :: update_offset_seconds\n        character(len=15)              :: lake_number_string\n        character(len=15)              :: reservoir_type_string\n\n#ifdef RESERVOIR_D\n        ! Create diagnostic log file only for development/debugging purposes\n        call create_rfc_forecasts_diagnostic_log_file(lake_number)\n#endif\n\n        if (this%pointer_allocation_guard .eqv. .false. ) then\n\n            if (reservoir_type .ne. 4 .and. reservoir_type .ne. 5) then\n                ! Call hydro_stop if reservoir_type is not RFC Forecast.\n                write(lake_number_string, \"(I15)\") lake_number\n                write(reservoir_type_string, \"(I15)\") reservoir_type\n                call hydro_stop(\"ERROR: Incorrect reservoir type for reservoir \" // trim(ADJUSTL(lake_number_string)) // &\n                \". Expected reservoir type 4 or 5 and instead received reservoir type \" // reservoir_type_string // \".\" )\n            end if\n\n            ! try to allocate input\n            allocate ( this%input )\n            if ( .not. associated(this%input) ) then\n                ! if the input structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate rfc forecasts input structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize the input structure\n                call this%input%init()\n            end if\n\n            ! try to allocate output\n            allocate ( this%output )\n            if ( .not. associated(this%output) ) then\n                ! if the output structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate rfc forecasts output structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize the output structure\n                call this%output%init()\n            end if\n\n            ! try to allocate properties\n            allocate ( this%properties )\n            if ( .not. associated(this%properties) ) then\n                ! if the properties structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate rfc forecasts properties structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize rfc forecasts properties\n                call this%properties%init(lake_area, lake_max_water_elevation, lake_number, reservoir_type, reservoir_parameter_file)\n            end if\n            this%pointer_allocation_guard = .true.\n\n            ! try to allocate state\n            allocate ( this%state )\n            if ( .not. associated(this%state) ) then\n                ! if the state structure could not be created, call hydro_stop.\n                write(lake_number_string, \"(I15)\") lake_number\n                call hydro_stop(\"ERROR: Failure to allocate rfc forecasts state structure for reservoir \" &\n                // trim(ADJUSTL(lake_number_string)) // \".\")\n            else\n                ! initialize rfc forecasts state\n                call this%state%init(water_elevation, lake_area, lake_max_water_elevation, &\n                orifice_elevation, initial_fractional_depth)\n            end if\n            this%pointer_allocation_guard = .true.\n\n        end if\n\n        ! Allocate a single level pool reservoir\n        allocate(levelpool :: this%state%levelpool_ptr)\n\n        ! Initialize level pool reservoir\n        call this%state%levelpool_ptr%init(water_elevation, lake_area, &\n        weir_elevation, weir_coeffecient, weir_length, dam_length, orifice_elevation, &\n        orifice_coefficient, orifice_area, lake_max_water_elevation, lake_number, 1)\n\n        ! Call to initialize time series data object\n        call time_series_data%init(start_date, time_series_path, forecast_lookback_hours, &\n        this%properties%rfc_timeslice_offset_hours, this%properties%rfc_gage_id, &\n        this%properties%lake_number, this%properties%lookback_seconds, this%properties%total_counts, &\n        this%properties%observed_counts, this%properties%time_step_seconds, this%state%discharges, &\n        this%state%forecast_found, this%state%all_discharges_synthetic, this%properties%time_series_file_name)\n\n        ! If the forecast was found and returned a discharge array\n        if (this%state%forecast_found) then\n\n            ! Set the assimilated_source_file\n            this%state%assimilated_source_file = this%properties%time_series_file_name\n\n            ! Use modulo to calculate the offset seconds in between the hourly time-step to set the update time\n            ! for shifting values in the discharge array.\n            update_offset_seconds = mod(this%properties%lookback_seconds, this%properties%time_step_seconds)\n\n            this%state%time_series_update_time = this%properties%time_step_seconds - update_offset_seconds\n\n            ! Set starting index in the time series discharge array depending on the lookback seconds to when\n            ! the RFC time series file was found, the number of observed values to offset from the beginning of\n            ! discharge array to reach the T0 issue time, and the offset hours that the model searched in the future\n            ! of model start time to for the time series file issue time.\n            this%state%time_series_index = this%properties%lookback_seconds / this%properties%time_step_seconds + 1 &\n            + this%properties%observed_counts - this%properties%rfc_timeslice_offset_hours\n\n            ! Check if starting index is out of range of discharge array and set forecast_found to false if out of range.\n            if (this%state%time_series_index .le. 0 .or. this%state%time_series_index .ge. this%properties%total_counts) then\n                this%state%forecast_found = .false.\n\n                this%state%time_series_index = 1\n            end if\n        end if\n\n    end subroutine rfc_forecasts_init\n\n    ! RFC Forecasts Destructor\n    subroutine rfc_forecasts_destroy(this)\n        implicit none\n        class(rfc_forecasts), intent(inout) :: this ! object being destroyed\n    end subroutine rfc_forecasts_destroy\n\n    ! Subroutine for running reservoir for a rfc forecasts reservoir\n    subroutine run_rfc_forecasts_reservoir(this, previous_timestep_inflow, inflow, &\n        lateral_inflow, water_elevation, outflow, routing_period, dynamic_reservoir_type, &\n        assimilated_value, assimilated_source_file)\n        implicit none\n        class(rfc_forecasts), intent(inout) :: this\n        real, intent(in)    :: previous_timestep_inflow ! cubic meters per second (cms)\n        real, intent(in)    :: inflow                   ! cubic meters per second (cms)\n        real, intent(in)    :: lateral_inflow           ! cubic meters per second (cms)\n        real, intent(inout) :: water_elevation          ! meters\n        real, intent(out)   :: outflow                  ! cubic meters per second (cms)\n        real, intent(in)    :: routing_period           ! seconds\n        integer, intent(out):: dynamic_reservoir_type   ! dynamic reservoir type sent to lake out files\n        real, intent(out)   :: assimilated_value        ! value assimilated from observation or forecast\n        character(len=256), intent(out) :: assimilated_source_file ! source file of assimilated value\n        real                :: levelpool_outflow        ! cubic meters per second (cms)\n        integer\t\t        :: missing_outflow_index\n        character(len=15)   :: lake_number_string\n\n        ! If first timestep, then check forecast aspects\n        if (this%state%current_time == 0) then\n            if (this%state%forecast_found) then\n\n                ! If all of the values are synthetic or any of the values are less than 0.0\n                ! or greater than or equal to the MS river historical peak, then\n                ! do not use the time series discharge array and revert to level pool.\n                ! Otherwise, if forecast was not found, also revert to level pool.\n                if (this%state%all_discharges_synthetic) then\n                    this%state%forecast_found = .false.\n\n                    write(lake_number_string, \"(I15)\") this%properties%lake_number\n                    write(log_warning,*) \"WARNING: RFC Forecast Time Series discharges for reservoir \", &\n                    trim(ADJUSTL(lake_number_string)), \" using time series file \", &\n                    trim(ADJUSTL(this%properties%time_series_file_name)), &\n                    \" are all synthetic. This reservoir will use level pool calculations instead.\"\n\n                else if (minval(this%state%discharges) < 0.0) then\n                    this%state%forecast_found = .false.\n\n                    write(lake_number_string, \"(I15)\") this%properties%lake_number\n                    write(log_warning,*) \"WARNING: RFC Forecast Time Series discharges for reservoir \", &\n                    trim(ADJUSTL(lake_number_string)), \" using time series file \", &\n                    trim(ADJUSTL(this%properties%time_series_file_name)), &\n                    \" contains missing or negative values. This reservoir will use level pool calculations instead.\"\n\n                !! peak flow on MS river *2\n                !! http://nwis.waterdata.usgs.gov/nwis/peak?site_no=07374000&agency_cd=USGS&format=html\n                !! baton rouge 1945: 1,473,000cfs=41,711cms, multiply it roughly by 2\n                else if (maxval(this%state%discharges) .ge. 90000.0) then\n                    this%state%forecast_found = .false.\n\n                    write(lake_number_string, \"(I15)\") this%properties%lake_number\n                    write(log_warning,*) \"WARNING: RFC Forecast Time Series discharges for reservoir \", &\n                    trim(ADJUSTL(lake_number_string)), \" using time series file \", &\n                    trim(ADJUSTL(this%properties%time_series_file_name)), &\n                    \" contain one or more values greater than or equal to 90,000 Cubic Meters per Second\", &\n                    \" (twice the Mississippi River historical peak flow). These values are assumed to be incorrect.\", &\n                    \" This reservoir will use level pool calculations instead.\"\n                end if\n\n            else\n                write(lake_number_string, \"(I15)\") this%properties%lake_number\n                write(log_warning,*) \"WARNING: RFC Forecast Time Series file for reservoir \", trim(ADJUSTL(lake_number_string)), &\n                \" is not available. This reservoir will use level pool calculations instead.\"\n            end if\n        end if\n\n        ! Update the current time\n        this%state%current_time = this%state%current_time + int(routing_period)\n\n        ! Update input variables\n        this%input%inflow = inflow\n        this%input%lateral_inflow = lateral_inflow\n\n        ! Update state water elevation\n        this%state%water_elevation = water_elevation\n        this%state%levelpool_water_elevation = water_elevation\n\n        ! Run levelpool reservoir\n        call this%state%levelpool_ptr%run(previous_timestep_inflow, inflow, &\n        lateral_inflow, this%state%levelpool_water_elevation, levelpool_outflow, routing_period, this%state%levelpool_reservoir_type, &\n        this%state%levelpool_assimilated_value, this%state%levelpool_assimilated_source_file)\n\n        ! Check if Routing Period is greater than 1 hour, and if true, set forecast_found to false.\n        if (routing_period .gt. 3600) then\n            this%state%forecast_found = .false.\n\n            write(lake_number_string, \"(I15)\") this%properties%lake_number\n            write(log_warning,*) \"WARNING: the routing period is greater than one hour. Therefore, the RFC forecasts\", &\n            \" cannot be used for reservoir \", trim(ADJUSTL(lake_number_string)), &\n            \". This reservoir will use level pool calculations instead.\"\n        end if\n\n        ! If a forecast is found and the current time is less than the max time an RFC Forecast is persisted\n        if (this%state%forecast_found .and. this%state%current_time .le. this%properties%rfc_forecast_persist_seconds) then\n\n            ! If current time is at or past the update time to cycle to the next value in the discharge array and the number\n            ! forecast counts has not yet been reached\n            if (this%state%current_time .ge. this%state%time_series_update_time .and. this%state%time_series_index &\n            .lt. this%properties%total_counts) then\n\n                ! Increment time series index\n                this%state%time_series_index = this%state%time_series_index + 1\n\n                ! Set next update time\n                this%state%time_series_update_time = this%state%time_series_update_time + this%properties%time_step_seconds\n\n            end if\n\n            ! If reservoir_type is 4 for CONUS RFC reservoirs\n            if (this%properties%reservoir_type == 4) then\n\n                ! Set outflow to corresponding discharge from array\n                this%output%outflow = this%state%discharges(this%state%time_series_index)\n\n            ! Else reservoir_type 5 for for Alaska RFC glacier outflows\n            else\n\n                ! Set outflow to sum inflow and corresponding discharge from array\n                this%output%outflow = this%input%inflow + this%state%discharges(this%state%time_series_index)\n            end if\n\n            ! Update water elevation\n            this%state%water_elevation = this%state%water_elevation + &\n            ((this%input%inflow - this%output%outflow) / this%properties%lake_area) * routing_period\n\n            ! Ensure that the water elevation is within the minimum and maximum elevation\n            if (this%state%water_elevation < 0.0) then\n                this%state%water_elevation = 0.0\n\n            else if (this%state%water_elevation > this%properties%max_water_elevation) then\n                this%state%water_elevation = this%properties%max_water_elevation\n\n            end if\n\n            ! Set dynamic_reservoir_type to RFC Forecasts Type\n            this%state%dynamic_reservoir_type = this%properties%reservoir_type\n\n            ! Set the assimilated_value to corresponding discharge from array\n            this%state%assimilated_value = this%state%discharges(this%state%time_series_index)\n\n            ! Check for outflows less than 0 and cycle backwards in the array until a\n            ! non-negative value is found. If all previous values are negative, then\n            ! use level pool outflow.\n            if (this%output%outflow < 0) then\n                missing_outflow_index = this%state%time_series_index\n\n                do while (this%output%outflow < 0 .and. missing_outflow_index > 1)\n                    missing_outflow_index = missing_outflow_index - 1\n\n                    this%output%outflow = this%state%discharges(missing_outflow_index)\n                end do\n\n                if (this%output%outflow < 0) then\n\n                    ! If reservoir_type is 4 for CONUS RFC reservoirs\n                    if (this%properties%reservoir_type == 4) then\n                        this%output%outflow = levelpool_outflow\n\n                    ! Else reservoir_type 5 for for Alaska RFC glacier outflows\n                    else\n                        this%output%outflow = this%input%inflow\n                    end if\n\n                    ! Update water elevation to levelpool water elevation\n                    this%state%water_elevation = this%state%levelpool_water_elevation\n\n                    ! Set dynamic_reservoir_type to levelpool type\n                    this%state%dynamic_reservoir_type = this%state%levelpool_reservoir_type\n\n                    ! Set the assimilated_value to sentinel, -9999.0\n                    this%state%assimilated_value = -9999.0\n\n                    ! Set the assimilated_source_file to empty string\n                    this%state%assimilated_source_file = \"\"\n                end if\n\n            end if\n\n        else\n            ! If reservoir_type is 4 for CONUS RFC reservoirs\n            if (this%properties%reservoir_type == 4) then\n                this%output%outflow = levelpool_outflow\n\n            ! Else reservoir_type 5 for for Alaska RFC glacier outflows\n            else\n                this%output%outflow = this%input%inflow\n            end if\n\n            ! Update water elevation to levelpool water elevation\n            this%state%water_elevation = this%state%levelpool_water_elevation\n\n            ! Set dynamic_reservoir_type to levelpool type\n            this%state%dynamic_reservoir_type = this%state%levelpool_reservoir_type\n\n            ! Set the assimilated_value to sentinel, -9999.0\n            this%state%assimilated_value = -9999.0\n\n            ! Set the assimilated_source_file to empty string\n            this%state%assimilated_source_file = \"\"\n        end if\n\n        ! Update output variable returned from this subroutine\n        outflow = this%output%outflow\n\n        ! Set current inflow to previous_timestep_inflow\n        this%input%previous_timestep_inflow = inflow\n\n        ! Update water_elevation variable returned from this subroutine\n        water_elevation = this%state%water_elevation\n\n        ! Update the dynamic_reservoir_type returned from this subroutine\n        dynamic_reservoir_type = this%state%dynamic_reservoir_type\n\n        ! Update the assimilated_value returned from this subroutine\n        assimilated_value = this%state%assimilated_value\n\n        ! Update the assimilated_source_file returned from this subroutine\n        assimilated_source_file = this%state%assimilated_source_file\n\n#ifdef RESERVOIR_D\n        ! Log diagnostic data only for development/debugging purposes\n        call log_rfc_forecasts_diagnostic_data(this%properties%lake_number, this%state%current_time, &\n        this%properties%time_step_seconds, this%state%time_series_update_time, this%properties%lookback_seconds, &\n        this%state%time_series_index, this%properties%rfc_gage_id, this%input%inflow, this%state%water_elevation, &\n        levelpool_outflow, this%output%outflow)\n#endif\n\n    end subroutine run_rfc_forecasts_reservoir\n\nend module module_rfc_forecasts\n"
  },
  {
    "path": "src/Routing/Reservoirs/RFC_Forecasts/module_rfc_forecasts_properties.F90",
    "content": "! This module defines and instantiates objects\n! for an rfc forecasts type reservoir's\n! parameters/properties. Properties holds\n! static/unchanging variables that are\n! set when the given reservoir object is\n! initialized/instantiated.\n\nmodule module_rfc_forecasts_properties\n    use module_reservoir_utilities, only: read_netcdf_lake_id, &\n                                          read_reservoir_parameters_netcdf_rfc_gage_id, &\n                                          read_reservoir_parameters_netcdf_rfc_integer, &\n                                          handle_err\n    use module_reservoir, only: reservoir_properties\n    use netcdf\n    use iso_fortran_env, only: int64\n\n    implicit none\n\n    ! Extend/derive rfc forecasts properties from the abstract base\n    ! type for reservoir properties.\n    type, extends(reservoir_properties) :: rfc_forecasts_properties_interface\n        real              :: lake_area                    ! area of reservoir (meters^2)\n        real              :: max_water_elevation          ! max water elevation (meters)\n        integer           :: lake_number                  ! lake number\n        integer           :: reservoir_type               ! reservoir type\n        character(len=5)  :: rfc_gage_id\n        integer           :: lookback_seconds\n        integer           :: total_counts\n        integer           :: observed_counts\n        integer           :: time_step_seconds\n        integer           :: rfc_forecast_persist_days\n        integer           :: rfc_forecast_persist_seconds\n        integer           :: rfc_timeslice_offset_hours\n        integer           :: observation_hours\n        character(len=256):: time_series_file_name\n\n    contains\n\n        procedure :: init => rfc_forecasts_properties_init\n        procedure :: destroy => rfc_forecasts_properties_destroy\n\n    end type rfc_forecasts_properties_interface\n\n    integer, parameter :: seconds_in_day = 86400\n    integer, parameter :: observation_hours = 48\n\ncontains\n\n    ! RFC Forecasts Properties Constructor\n    subroutine rfc_forecasts_properties_init(this, lake_area, lake_max_water_elevation, lake_number, reservoir_type, reservoir_parameter_file)\n        implicit none\n        class(rfc_forecasts_properties_interface), intent(inout) :: this ! the type object being initialized\n        real,    intent(in)          :: lake_area                    ! area of lake (km^2)\n        real,    intent(in)          :: lake_max_water_elevation     ! max water elevation (meters)\n        integer(kind=int64), intent(in)          :: lake_number                  ! lake number\n        integer, intent(in)          :: reservoir_type                ! reservoir type\n        character(len=*), intent(in) :: reservoir_parameter_file\n        integer                      :: ncid, var_id, lake_id_index\n        integer                      :: status                       ! status of reading NetCDF\n\n        ! Convert from km^2 to meters^2\n        this%lake_area = lake_area * 1.0E6\n\n        this%max_water_elevation = lake_max_water_elevation\n\n        this%lake_number = lake_number\n\n        ! reservoir_type set to 4 for CONUS RFC type forecasts\n        ! reservoir_type set to 5 for Alaska RFC type glacier forecasts\n        this%reservoir_type = reservoir_type\n\n        this%observation_hours = observation_hours\n\n        this%time_series_file_name = \"\"\n\n        ! Open Reservoir Parameter NetCDF file\n        status = nf90_open(path = reservoir_parameter_file, mode = nf90_nowrite, ncid = ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not open reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        ! Read relevant properties from Persistence Parameter NetCDF\n        call read_netcdf_lake_id(ncid, lake_number, \"rfc_lake_id\", reservoir_parameter_file, lake_id_index)\n\n        call read_reservoir_parameters_netcdf_rfc_gage_id(ncid, lake_id_index, \"rfc_gage_id\", &\n        reservoir_parameter_file, this%rfc_gage_id)\n\n        call read_reservoir_parameters_netcdf_rfc_integer(ncid, lake_id_index, \"rfc_forecast_persist\", &\n        reservoir_parameter_file, this%rfc_forecast_persist_days)\n\n        this%rfc_forecast_persist_seconds = this%rfc_forecast_persist_days * seconds_in_day\n\n        call read_reservoir_parameters_netcdf_rfc_integer(ncid, lake_id_index, \"rfc_timeslice_offset\", &\n        reservoir_parameter_file, this%rfc_timeslice_offset_hours)\n\n        ! Close Reservoir Parameter NetCDF file\n        status = nf90_close(ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not close reservoir parameter file\" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n    end subroutine rfc_forecasts_properties_init\n\n    ! RFC Forecasts Properties Destructor\n    subroutine rfc_forecasts_properties_destroy(this)\n        implicit none\n        class(rfc_forecasts_properties_interface), intent(inout) :: this ! the type object being destroyed\n    end subroutine rfc_forecasts_properties_destroy\n\nend module module_rfc_forecasts_properties\n"
  },
  {
    "path": "src/Routing/Reservoirs/RFC_Forecasts/module_rfc_forecasts_state.F90",
    "content": "! This module defines and instantiates objects\n! for an rfc forecasts type reservoir's state.\n! State holds and tracks dynamic/changing variables\n! that are only relevant to the given rfc forecasts\n! reservoir object and not other modules or areas\n! of the system.\n\nmodule module_rfc_forecasts_state\n\n    use module_levelpool, only: levelpool\n    use module_reservoir, only: reservoir_state\n    implicit none\n\n    ! Extend/derive rfc forecasts state from the abstract base\n    ! type for reservoir state.\n    type, extends(reservoir_state) :: rfc_forecasts_state_interface\n        real                               :: water_elevation           ! meters AMSL\n        real                               :: levelpool_water_elevation ! meters AMSL\n        real, allocatable, dimension(:)    :: discharges\n        logical, allocatable, dimension(:) :: synthetic_values\n        integer                         :: time_series_update_time  ! seconds\n        integer                         :: current_time             ! seconds\n        integer                         :: time_series_index\n        logical                         :: forecast_found\n        logical                         :: all_discharges_synthetic\n        integer                         :: dynamic_reservoir_type    ! dynamic reservoir type sent to lake out files\n        real                            :: assimilated_value\n        character(len=256)              :: assimilated_source_file\n        integer                         :: levelpool_reservoir_type    ! reservoir type for levelpool\n        real                            :: levelpool_assimilated_value ! levelpool assimilated sentinel value\n        character(len=256)              :: levelpool_assimilated_source_file ! empty string for levelpool assimilated source\n\n        type (levelpool), pointer :: levelpool_ptr   ! pointer to levelpool object\n\n    contains\n\n        procedure :: init => rfc_forecasts_state_init\n        procedure :: destroy => rfc_forecasts_state_destroy\n\n    end type rfc_forecasts_state_interface\n\ncontains\n\n    ! RFC Forecasts State Constructor\n    subroutine rfc_forecasts_state_init(this, water_elevation, lake_area, lake_max_water_elevation, orifice_elevation, initial_fractional_depth)\n        implicit none\n        class(rfc_forecasts_state_interface), intent(inout) :: this ! the type object being initialized\n        real, intent(in) :: water_elevation           ! meters AMSL\n        real, intent(in) :: lake_area                 ! area of lake (km^2)\n        real, intent(in) :: lake_max_water_elevation  ! max water elevation (meters)\n        real, intent(in) :: orifice_elevation         ! orifice elevation (meters AMSL)\n        real, intent(in) :: initial_fractional_depth  ! initial fraction water depth\n\n        ! Initialize the state water elevation in same manner as in module_RT.F\n        this%water_elevation = orifice_elevation + ((lake_max_water_elevation - orifice_elevation) * initial_fractional_depth)\n        this%levelpool_water_elevation = this%water_elevation\n        this%time_series_update_time = 0\n        this%current_time = 0\n        this%time_series_index = 1\n        this%forecast_found = .FALSE.\n        this%all_discharges_synthetic = .FALSE.\n\n        ! Initialize dynamic_reservoir_type to 4 for RFC type reservoir\n        this%dynamic_reservoir_type = 4\n\n        ! Initialize to default sentinel, -9999.0\n        this%assimilated_value = -9999.0\n\n        ! Initialize to default empty string\n        this%assimilated_source_file = \"\"\n\n        ! Levelpool reservoir type set to 1\n        this%levelpool_reservoir_type = 1\n\n        ! Set to default sentinel, -999.0\n        this%levelpool_assimilated_value = -9999.0\n\n        ! Set to default string\n        this%levelpool_assimilated_source_file = \"\"\n\n    end subroutine rfc_forecasts_state_init\n\n    ! RFC Forecasts State Destructor\n    subroutine rfc_forecasts_state_destroy(this)\n        implicit none\n        class(rfc_forecasts_state_interface), intent(inout) :: this ! the type object being destroyed\n\n    end subroutine rfc_forecasts_state_destroy\n\nend module module_rfc_forecasts_state\n"
  },
  {
    "path": "src/Routing/Reservoirs/RFC_Forecasts/module_rfc_forecasts_tests.F90",
    "content": "! This module holds tests for initialization of\n! various attributes of an RFC forecasts reservoir.\nmodule module_rfc_forecasts_tests\n    use module_rfc_forecasts\n    use module_reservoir_read_rfc_time_series_data\n\ncontains\n\n    ! Testing\n    function rfc_forecasts_data_info(rfc_forecasts_reservoir_data) result(data_info_result)\n        implicit none\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        logical :: data_info_result\n        logical, dimension(8) :: ptr_state\n        logical, dimension(8) :: data_state\n\n        data_info_result = .false.\n\n        ! Check to see if the rfc_forecasts_state data structure exists\n        print *, \"Checking pointer association on data%state for rfc forecasts reservoirs\"\n        if ( associated(rfc_forecasts_reservoir_data%state) ) then\n            print *, \"PASSED\"\n            ptr_state(1) = .true.\n       else\n            print *, \"FAILED\"\n            ptr_state(1) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the rfc_forecasts_properties data structure exists\n        print *, \"Checking pointer association on data%properties for rfc forecasts reservoirs\"\n        if ( associated(rfc_forecasts_reservoir_data%properties) ) then\n            print *, \"PASSED\"\n            ptr_state(2) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(2) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the rfc_forecasts_input data structure exists\n        print *, \"Checking pointer association on data%input for rfc forecasts reservoirs\"\n        if ( associated(rfc_forecasts_reservoir_data%input) ) then\n            print *, \"PASSED\"\n            ptr_state(3) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(3) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the rfc_forecasts_output data structure exists\n        print *, \"Checking pointer association on data%output for rfc forecasts reservoirs\"\n        if ( associated(rfc_forecasts_reservoir_data%output) ) then\n            print *, \"PASSED\"\n            ptr_state(4) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(4) = .false.\n        end if\n        print *, \" \"\n\n        ! Test levelpool structure\n        ! Check to see if the rfc_forecasts levelpool_state data structure exists\n        print *, \"Checking pointer association on data%levelpool_state for rfc forecasts reservoirs\"\n        if ( associated(rfc_forecasts_reservoir_data%state%levelpool_ptr%state) ) then\n            print *, \"PASSED\"\n            ptr_state(5) = .true.\n       else\n            print *, \"FAILED\"\n            ptr_state(5) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the rfc_forecasts levelpool_properties data structure exists\n        print *, \"Checking pointer association on data%levelpool_properties for rfc forecasts reservoirs\"\n        if ( associated(rfc_forecasts_reservoir_data%state%levelpool_ptr%properties) ) then\n            print *, \"PASSED\"\n            ptr_state(6) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(6) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the rfc_forecasts levelpool_input data structure exists\n        print *, \"Checking pointer association on data%levelpool_input for rfc forecasts reservoirs\"\n        if ( associated(rfc_forecasts_reservoir_data%state%levelpool_ptr%input) ) then\n            print *, \"PASSED\"\n            ptr_state(7) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(7) = .false.\n        end if\n        print *, \" \"\n\n        ! Check to see if the rfc_forecasts levelpool_output data structure exists\n        print *, \"Checking pointer association on data%levelpool_output for rfc forecasts reservoirs\"\n        if ( associated(rfc_forecasts_reservoir_data%state%levelpool_ptr%output) ) then\n            print *, \"PASSED\"\n            ptr_state(8) = .true.\n        else\n            print *, \"FAILED\"\n            ptr_state(8) = .false.\n        end if\n        print *, \" \"\n\n\n        ! Now check the data members of each substructure\n        if ( ptr_state(1) ) then\n            data_state(1) = test_rfc_forecasts_state(rfc_forecasts_reservoir_data%state)\n        end if\n\n        if ( ptr_state(2) ) then\n            data_state(2) = test_rfc_forecasts_properties(rfc_forecasts_reservoir_data%properties)\n        end if\n\n        if ( ptr_state(3) ) then\n            data_state(3) = test_input_rfc_forecasts(rfc_forecasts_reservoir_data%input)\n        end if\n\n        if ( ptr_state(4) ) then\n            data_state(4) = test_output_rfc_forecasts(rfc_forecasts_reservoir_data%output)\n        end if\n\n        ! Test Levelpool Substructures\n        if ( ptr_state(5) ) then\n            data_state(5) = test_rfc_forecasts_levelpool_state(rfc_forecasts_reservoir_data%state)\n        end if\n\n        if ( ptr_state(6) ) then\n            data_state(6) = test_rfc_forecasts_levelpool_properties(rfc_forecasts_reservoir_data%state)\n        end if\n\n        if ( ptr_state(7) ) then\n            data_state(7) = test_rfc_forecasts_levelpool_input(rfc_forecasts_reservoir_data%state%levelpool_ptr%input)\n        end if\n\n        if ( ptr_state(8) ) then\n            data_state(8) = test_rfc_forecasts_levelpool_output(rfc_forecasts_reservoir_data%state%levelpool_ptr%output)\n        end if\n\n        if ( all(ptr_state) .and. all(data_state) ) then\n            data_info_result = .true.\n            print *, \"========================================================================\"\n            print *, \"All RFC Forecast Reservoir Object Tests Passed\"\n            print *, \"========================================================================\"\n\n        else\n            data_info_result = .false.\n            print *, \"========================================================================\"\n            print *, \"Not All RFC Forecast Reservoir Object Tests Passed\"\n            print *, \"========================================================================\"\n\n        end if\n\n    end function rfc_forecasts_data_info\n\n    ! Test to see that each member of the input structure is correctly allocated and readable\n    function test_input_rfc_forecasts(o) result(rv)\n        type (reservoir_input), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the input structure\"\n        print *, \" \"\n\n        print *, \"Checking read on inflow\"\n        print *, o%inflow\n        if ( o%inflow .ne. 0.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lateral_inflow\"\n        print *, o%lateral_inflow\n        if ( o%lateral_inflow .ne. 0.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on previous_timestep_inflow\"\n        print *, o%previous_timestep_inflow\n        if ( o%previous_timestep_inflow .ne. 0.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_input_rfc_forecasts\n\n    ! Test to see that each member of the output structure is correctly allocated and readable\n    function test_output_rfc_forecasts(o) result(rv)\n        type (reservoir_output), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the output structure\"\n        print *, \" \"\n\n        print *, \"Checking read on outflow\"\n        print *, o%outflow\n        if ( o%outflow .ne. 0.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_output_rfc_forecasts\n\n    ! Test to see that each member of the state structure is correctly allocated and readable\n    function test_rfc_forecasts_state(o) result(rv)\n        type (rfc_forecasts_state_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the rfc_forecasts state data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on water_elevation\"\n        print *, o%water_elevation\n        if ( o%water_elevation .ne. 17.3999996) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_rfc_forecasts_state\n\n\n    ! Test to see that each member of the properties structure is correctly allocated and readable\n    function test_rfc_forecasts_properties(o) result(rv)\n        type (rfc_forecasts_properties_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the rfc_forecasts properties data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on lake_number\"\n        print *, o%lake_number\n        if ( o%lake_number .ne. 3745478) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on rfc_gage_id\"\n        print *, o%rfc_gage_id\n        if ( o%rfc_gage_id .ne. \"DIEA4\") then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_rfc_forecasts_properties\n\n\n    ! Levelpool data tests\n    ! Test to see that each member of the levelpool input structure is correctly allocated and readable\n    function test_rfc_forecasts_levelpool_input(o) result(rv)\n        type (reservoir_input), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the rfc forecasts levelpool input structure\"\n        print *, \" \"\n\n        print *, \"Checking read on inflow\"\n        print *, o%inflow\n        if ( o%inflow .ne. 0.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lateral_inflow\"\n        print *, o%lateral_inflow\n        if ( o%lateral_inflow .ne. 0.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on previous_timestep_inflow\"\n        print *, o%previous_timestep_inflow\n        if ( o%previous_timestep_inflow .ne. 0.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_rfc_forecasts_levelpool_input\n\n    ! Test to see that each member of the levelpool output structure is correctly allocated and readable\n    function test_rfc_forecasts_levelpool_output(o) result(rv)\n        type (reservoir_output), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the rfc forecasts levelpool output structure\"\n        print *, \" \"\n\n        print *, \"Checking read on outflow\"\n        print *, o%outflow\n        if ( o%outflow .ne. 0.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_rfc_forecasts_levelpool_output\n\n    ! Test to see that each member of the levelpool state structure is correctly allocated and readable\n    function test_rfc_forecasts_levelpool_state(o) result(rv)\n        type (rfc_forecasts_state_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the rfc forecasts levelpool state data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on water_elevation\"\n        print *, o%levelpool_ptr%state%water_elevation\n        if ( o%levelpool_ptr%state%water_elevation .ne. 2.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_rfc_forecasts_levelpool_state\n\n\n    ! Test to see that each member of the levelpool properties structure is correctly allocated and readable\n    function test_rfc_forecasts_levelpool_properties(o) result(rv)\n        type (rfc_forecasts_state_interface), intent(in) :: o\n        logical rv\n\n        rv = .true.\n\n        print *, \"========================================================================\"\n        print *, \"Checking the values of the rfc forecasts levelpool properties data structure\"\n        print *, \" \"\n\n        print *, \"Checking read on lake_area\"\n        print *, o%levelpool_ptr%properties%lake_area\n        if ( o%levelpool_ptr%properties%lake_area .ne. 4.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_elevation\"\n        print *, o%levelpool_ptr%properties%weir_elevation\n        if ( o%levelpool_ptr%properties%weir_elevation .ne. 6.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_coeffecient\"\n        print *, o%levelpool_ptr%properties%weir_coeffecient\n        if ( o%levelpool_ptr%properties%weir_coeffecient .ne. 8.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on weir_length\"\n        print *, o%levelpool_ptr%properties%weir_length\n        if ( o%levelpool_ptr%properties%weir_length .ne. 10.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_elevation\"\n        print *, o%levelpool_ptr%properties%orifice_elevation\n        if ( o%levelpool_ptr%properties%orifice_elevation .ne. 12.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_coefficient\"\n        print *, o%levelpool_ptr%properties%orifice_coefficient\n        if ( o%levelpool_ptr%properties%orifice_coefficient .ne. 14.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on orifice_area\"\n        print *, o%levelpool_ptr%properties%orifice_area\n        if ( o%levelpool_ptr%properties%orifice_area .ne. 16.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on max_depth\"\n        print *, o%levelpool_ptr%properties%max_depth\n        if ( o%levelpool_ptr%properties%max_depth .ne. 18.0) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n        print *, \"Checking read on lake_number\"\n        print *, o%levelpool_ptr%properties%lake_number\n        if ( o%levelpool_ptr%properties%lake_number .ne. 3745478) then\n            rv = .false.\n            print *, \"FAILED\"\n        end if\n        print *, \" \"\n\n    end function test_rfc_forecasts_levelpool_properties\n\nend module\n"
  },
  {
    "path": "src/Routing/Reservoirs/RFC_Forecasts_Module_README.md",
    "content": "# RFC Forecasts Module\n\n### General Purpose and Functionality\n\nThe purpose of this module is to integrate RFC (River Forecast Center) produced forecasts for individual reservoirs into\nthe Reservoir module in real-time. This utilizes the expertise that each RFC has for forecasting reservoirs in their domain.\nThis module replaces the normal Level Pool object for a particular reservoir that is selected to run as RFC_Forecast.\n\n\n### Module Architecture\n\nThis module builds off of the same class structure and architecture of the Level Pool module. As in Level Pool, each reservoir in this\nmodule is instantiated into an object at model initialization. The **RFC_Forecasts** directory contains the following files:\n\n* **module_rfc_forecasts.F** defines and instantiates objects for an rfc forecasts type\nreservoir. **module_RT.F** will call and pass parameters to the constructor in this module to instantiate the rfc forecasts reservoir\nobject and its sub-objects. The rfc forecasts reservoir type inherits input and output types from the reservoir base module and calls\ninstantiation of these into sub-objects. The rfc forecasts reservoir type also points to types for parameters and state and calls\ninstantiation of these into sub-objects. This reservoir type will also point to and instantiate a corresponding level pool reservoir, that\nalso runs at every timestep. The run function will output the corresponding discharges from the RFC time series discharge array. If the\ncorresponding RFC time series file is not found or the array values are unusable, then the level pool output will be used instead.\n\n* **module_rfc_forecasts_properties.F** defines and instantiates objects for an rfc forecasts type reservoir's\nproperties. Properties holds static/unchanging variables that are set when the given reservoir object is\ninitialized/instantiated.\n\n* **module_rfc_forecasts_state.F** defines and instantiates objects for an rfc forecasts type reservoir's state.\nState holds and tracks dynamic/changing variables that are only relevant to the given reservoir object and not other\nmodules or areas of the system.\n\n* **module_rfc_forecasts_tests.F** holds unit tests that test for all components of an rfc forecasts reservoir\nare properly initialized.\n\n* **module_reservoir_read_rfc_time_series_data.F**, within the **Reservoirs** directory, searches for and reads RFC time series\nforecast files for an array of time series forecast values.\n\n### Input Parameters\n\nThis module requires four input parameters that are set in hydro.namelist.\n\n* ```reservoir_rfc_forecasts``` is a boolean parameter that will need to be set to ```.TRUE.``` for this module to be activated.\nThis will set the model variable ```reservoir_type_specified``` to ```TRUE``` and cause the model to read the reservoir_type variable from the\nreservoir parameter file. The reservoir_type for a RFC (River Forecast Center) Forecast reservoir is currently set to '4' in the reservoir\nparameter file.\n\n* ```reservoir_rfc_forecasts_time_series_path``` is the path to all the\nRFC time series files used by this module.\n\n* ```reservoir_rfc_forecasts_lookback_hours``` is an integer parameter that specifies how many hours before the model start time the module will\nsearch for a corresponding time series file, and '28' would be a typical value and is the default.\n\n* ```reservoir_parameter_file``` is the NetCDF parameter file that holds the corresponding gage ID for each lake ID.\n\n### Testing\n\nTo compile and run the unit tests, first go to the NDHMS directory and type\n```\n./compile_offline_NoahMP.sh template/setEnvar.sh\n```\n\nand hit enter. Then go to the Reservoir directory in the terminal and type\n\n```\nmake\n```\n\nand hit enter. Then type\n\n```\nmake test\n```\n\nand hit enter. Then type\n\n```\n./reservoir_tests\n```\n\nand hit enter.\nThe user should see \"All Reservoir Tests Passed\".\n"
  },
  {
    "path": "src/Routing/Reservoirs/module_reservoir.F90",
    "content": "! This module is the base module for reservoirs that defines\n! abstract types for a reservoir base, reservoir state, and\n! reservoir properties. It also defines types for the inputs\n! and outputs common to all sub-types of reservoirs. Finally,\n! it defines a pointer to a reservoir object and an interface\n! for running a reservoir.\nmodule module_reservoir\n\n    ! Defines the reservoir base state type that sub-types of\n    ! reservoirs will derive from. Since this is abstract, an instance\n    ! of reservoir state cannot be created but only derived to sub-types\n    ! of reservoirs. State holds and tracks dynamic/changing variables\n    ! that are only relevant to the given reservoir object and not other\n    ! modules or areas of the system.\n    type, abstract :: reservoir_state\n\n    end type\n\n    ! Defines the reservoir base properties/parameters type that\n    ! sub-types of reservoirs will derive from. Since this is abstract,\n    ! an instance of reservoir properties cannot be created but only\n    ! derived to sub-types of reservoirs. Properties holds\n    ! static/unchanging variables that are set when the given reservoir\n    ! object is initialized/instantiated.\n    type, abstract :: reservoir_properties\n\n    end type\n\n    ! Defines the input base type which holds the same inputs that all\n    ! sub-types of reservoirs will derive from. Therefore, all types of\n    ! reservoirs will hold the inputs defined below. These are\n    ! dynamic/changing variables that will receive values passed into the\n    ! object's methods/subroutines at runtime.\n    type :: reservoir_input\n\n        real :: inflow                      ! cubic meters per second (cms)\n        real :: lateral_inflow              ! cubic meters per second (cms)\n        real :: previous_timestep_inflow    ! cubic meters per second (cms)\n\n    contains\n\n        procedure :: init => reservoir_input_init\n        procedure :: destroy => reservoir_input_destroy\n\n    end type\n\n    ! Defines the output base type which holds the same output(s) that all\n    ! sub-types of reservoirs will derive from. Therefore, all types of\n    ! reservoirs will hold the output(s) defined below. These are\n    ! dynamic/changing variables that will receive values returned from the\n    ! object's methods/subroutines at runtime.\n    type :: reservoir_output\n\n        real :: outflow                     ! cubic meters per second (cms)\n\n    contains\n\n        procedure :: init => reservoir_output_init\n        procedure :: destroy => reservoir_output_destroy\n\n    end type\n\n    ! Defines the reservoir base type that sub-types of reservoirs\n    ! will derive from. Since this is abstract, an instance of reservoir\n    ! cannot be created but only derived to sub-types of reservoirs.\n    ! Derived sub-types of reservoirs of this base type will create a\n    ! reservoir object that will hold state, properties/parameters,\n    ! inputs, and outputs as sub-objects.\n    type, abstract :: reservoir\n\n        type(reservoir_input), pointer :: input\n        type(reservoir_output), pointer :: output\n\n    contains\n\n        ! Defines procedure to call run reservoir for a type of reservoir,\n        ! which will then call methods/subroutines for processing the\n        ! inputs and returning the outputs. Since this is deferred,\n        ! it cannot be implemented for a base reservoir but only for\n        ! a sub-type of reservoir.\n        procedure (run_reservoir_interface), deferred :: run\n\n    end type\n\n    ! Defines a pointer to a reservoir base type\n    type :: reservoir_container\n        class (reservoir), pointer :: ptr\n    end type\n\n    ! Defines the abstract implementation of run_reservoir that all\n    ! reservoir sub-types will derive from with the same given\n    ! inputs and outputs.\n    abstract interface\n        subroutine run_reservoir_interface(this, previous_timestep_inflow, inflow, &\n            lateral_inflow, water_elevation, outflow, routing_period, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n            import reservoir\n            class(reservoir), intent(inout) :: this\n            real, intent(in)    :: previous_timestep_inflow ! cubic meters per second (cms)\n            real, intent(in)    :: inflow                   ! cubic meters per second (cms)\n            real, intent(in)    :: lateral_inflow           ! cubic meters per second (cms)\n            real, intent(inout) :: water_elevation          ! meters AMSL\n            real, intent(out)   :: outflow                  ! cubic meters per second (cms)\n            real, intent(in)    :: routing_period           ! seconds\n            integer, intent(out):: dynamic_reservoir_type   ! dynamic reservoir type sent to lake out files\n            real, intent(out)   :: assimilated_value        ! value assimilated from observation or forecast\n            character(len=256), intent(out) :: assimilated_source_file ! source file of assimilated value\n\n        end subroutine run_reservoir_interface\n\n    end interface\n\ncontains\n\n    ! Constructor the reservoir input type\n    subroutine reservoir_input_init(this)\n        implicit none\n    \tclass (reservoir_input), intent(inout) :: this ! object being initialized\n        this%inflow = 0.0\n        this%lateral_inflow = 0.0\n        this%previous_timestep_inflow = 0.0\n\n    end subroutine reservoir_input_init\n\n\n    ! Destructor for the reservoir input type\n    subroutine reservoir_input_destroy(this)\n        implicit none\n        class (reservoir_input), intent(inout) :: this ! object being destroyed\n\n    end subroutine reservoir_input_destroy\n\n\n    ! Constructor for the reservoir output type\n    subroutine reservoir_output_init(this)\n        implicit none\n    \tclass (reservoir_output), intent(inout) :: this ! object being initialized\n        this%outflow = 0.0\n\n    end subroutine reservoir_output_init\n\n\n    ! Destructor for the reservoir output type\n    subroutine reservoir_output_destroy(this)\n        implicit none\n        class (reservoir_output), intent(inout) :: this ! object being destroyed\n\n    end subroutine reservoir_output_destroy\n\nend module module_reservoir\n"
  },
  {
    "path": "src/Routing/Reservoirs/module_reservoir_read_rfc_time_series_data.F90",
    "content": "! This module searches for and reads RFC Time Series files\n! to get an array of observed and forecasted discharges that\n! will be used by reservoirs. The forecast lookback hours\n! period is passed in to determine how far back in time from\n! the current model time plus another offset time to search\n! ahead of model time the module will look for time series files.\n! The forecast_file_resolution_minutes determines the time\n! increments the module will look back.\nmodule module_reservoir_read_rfc_time_series_data\n    use module_reservoir_utilities, only: read_timeslice_netcdf_integer_variables, &\n                                          read_timeslice_netcdf_real_1D_variables, &\n                                          read_timeslice_netcdf_integer_1D_variables, &\n                                          geth_newdate, &\n                                          handle_err\n    use netcdf\n    implicit none\n\n    type :: time_series_data_type\n\n        character(len=19)                  :: start_date\n        character(len=19)                  :: current_date\n        character(len=256)                 :: time_series_path\n        character(len=256)                 :: time_series_file_name\n        integer                            :: forecast_lookback_hours\n        integer                            :: timeslice_offset_hours\n        integer                            :: current_lookback_seconds\n        character(len=5)                   :: rfc_gage_id\n        integer                            :: total_counts\n        integer                            :: observed_counts\n        integer                            :: time_step_seconds\n        real, allocatable, dimension(:)    :: discharges\n        integer, allocatable, dimension(:) :: synthetic_values\n        logical, allocatable, dimension(:) :: synthetic_values_logical\n        logical                            :: forecast_found\n        logical                            :: all_discharges_synthetic\n\n    contains\n\n        procedure :: init => time_series_data_init\n        procedure :: destroy => time_series_data_destroy\n        procedure :: setup_read_time_series => setup_read_time_series\n        procedure :: read_time_series_file => read_time_series_file\n\n    end type time_series_data_type\n\n    type (time_series_data_type) :: time_series_data\n\n    integer, parameter :: forecast_file_resolution_minutes = 60\n\ncontains\n\n   ! Time Series Data Type Constructor\n    subroutine time_series_data_init(this, start_date, time_series_path, forecast_lookback_hours, &\n        timeslice_offset_hours, rfc_gage_id, lake_number, lookback_seconds, total_counts, &\n        observed_counts, time_step_seconds, discharges, forecast_found, all_discharges_synthetic, &\n        time_series_file_name)\n        implicit none\n        class(time_series_data_type), intent(inout) :: this ! object being initialized\n        character(len=19),  intent(in)                  :: start_date\n        character(len=256), intent(in)                  :: time_series_path\n        integer,            intent(in)                  :: forecast_lookback_hours\n        integer,            intent(in)                  :: timeslice_offset_hours\n        character(len=5),   intent(in)                  :: rfc_gage_id\n        integer,            intent(in)                  :: lake_number\n        integer,            intent(out)                 :: lookback_seconds\n        integer,            intent(out)                 :: total_counts\n        integer,            intent(out)                 :: observed_counts\n        integer,            intent(out)                 :: time_step_seconds\n        real, allocatable, dimension(:), intent(inout)  :: discharges\n        logical,            intent(inout)               :: forecast_found\n        logical,            intent(inout)               :: all_discharges_synthetic\n        character(len=256), intent(out)                 :: time_series_file_name\n        character(len=15)                               :: lake_number_string\n\n        this%forecast_found = .false.\n        this%all_discharges_synthetic = .false.\n        this%start_date = start_date\n        this%current_date = start_date\n        this%time_series_path = time_series_path\n        this%forecast_lookback_hours = forecast_lookback_hours\n        this%timeslice_offset_hours = timeslice_offset_hours\n        this%rfc_gage_id = rfc_gage_id\n        this%time_series_file_name = \"\"\n\n        this%current_lookback_seconds = 0\n        this%total_counts = 0\n        this%observed_counts = 0\n        this%time_step_seconds = 0\n\n        ! Call subroutine to search for and read an RFC time series file\n        call this%setup_read_time_series()\n\n        lookback_seconds = this%current_lookback_seconds\n        total_counts = this%total_counts\n        observed_counts = this%observed_counts\n        time_step_seconds = this%time_step_seconds\n\n        ! If the time series forecast is found\n        if (this%forecast_found) then\n            allocate(discharges(total_counts))\n\n            discharges = this%discharges\n\n            ! Check if all of the values are synthetic\n            if ( all(this%synthetic_values_logical) .eqv. .true.) then\n                this%all_discharges_synthetic = .true.\n            end if\n\n            ! Deallocate forecast arrays\n            if(allocated(this%discharges)) deallocate(this%discharges)\n            if(allocated(this%synthetic_values)) deallocate(this%synthetic_values)\n            if(allocated(this%synthetic_values_logical)) deallocate(this%synthetic_values_logical)\n\n        end if\n\n        forecast_found = this%forecast_found\n        all_discharges_synthetic = this%all_discharges_synthetic\n        time_series_file_name = this%time_series_file_name\n\n    end subroutine time_series_data_init\n\n\n    ! Time Series Data Type Destructor\n    subroutine time_series_data_destroy(this)\n\n        implicit none\n        class(time_series_data_type), intent(inout) :: this ! object being destroyed\n\n    end subroutine time_series_data_destroy\n\n\n    ! Set up list of time series files to read\n    subroutine setup_read_time_series(this)\n        implicit none\n\n        class(time_series_data_type), intent(inout) :: this\n        character(len=256)   :: time_series_file_name\n        character(len=19)    :: old_date, new_date\n        character(len=13)    :: old_date_trimmed\n        character(len=2)     :: forecast_file_resolution_string\n        integer :: total_time_series_file_periods, time_series_file_index\n        integer :: forecast_file_minute, forecast_file_resolution_seconds, timeslice_offset_seconds\n        logical :: file_exists\n\n        this%current_lookback_seconds = 0\n\n        ! Determine the total number of time series files to search for\n        total_time_series_file_periods = this%forecast_lookback_hours * (60 / forecast_file_resolution_minutes)\n\n        timeslice_offset_seconds = this%timeslice_offset_hours * 3600\n\n        old_date = this%current_date\n\n        ! Get the new date-time ahead of model start time to start searching\n        ! for time series files if the timeslice_offset_seconds is greater than 0.\n        call geth_newdate(new_date, old_date, timeslice_offset_seconds)\n        old_date = new_date\n\n        write(forecast_file_resolution_string, \"(I2)\") forecast_file_resolution_minutes\n\n        ! Negative for going back in time\n        forecast_file_resolution_seconds = forecast_file_resolution_minutes * 60 * (-1)\n\n        ! Loop through the total time series periods to look for and read time series files\n        do time_series_file_index = 1, total_time_series_file_periods\n\n            old_date_trimmed = trim(old_date(:13))\n\n            time_series_file_name = trim(this%time_series_path) // \"/\" // old_date_trimmed // \".\" // &\n                            forecast_file_resolution_string // 'min.' // this%rfc_gage_id // '.RFCTimeSeries.ncdf'\n\n            ! Check if file exists\n            inquire(FILE = time_series_file_name, EXIST = file_exists)\n            if (file_exists) then\n\n                ! Call subroutine to read a particular time series file\n                call this%read_time_series_file(time_series_file_name)\n\n                this%time_series_file_name = old_date_trimmed // \".\" // &\n                            forecast_file_resolution_string // 'min.' // this%rfc_gage_id // '.RFCTimeSeries.ncdf'\n\n                exit\n            end if\n\n            ! Call subroutine to get the date from one forecast file resolution back in time\n            call geth_newdate(new_date, old_date, forecast_file_resolution_seconds)\n            old_date = new_date\n\n            ! Lookback seconds to account for how long back a time series file was read\n            this%current_lookback_seconds = this%current_lookback_seconds - forecast_file_resolution_seconds\n\n        end do\n\n    end subroutine setup_read_time_series\n\n    ! Read given time series file to get gage discharges\n    subroutine read_time_series_file(this, time_series_file)\n        implicit none\n        class(time_series_data_type), intent(inout) :: this\n        character(len=256), intent(in) :: time_series_file\n        integer*8, allocatable, dimension(:) :: gage_ids_integer_array\n        integer :: reservoir_rfc_gage_index, time_series_rfc_gage_index\n        integer :: ncid, status\n\n        ! Open Time Series NetCDF file\n        status = nf90_open(path = trim(time_series_file), mode = nf90_nowrite, ncid = ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not open RFC time series file \" &\n        // trim(ADJUSTL(time_series_file)) // \".\")\n\n        call read_timeslice_netcdf_integer_variables(ncid, 'totalCounts', time_series_file, this%total_counts)\n\n        allocate (this%discharges(this%total_counts))\n\n        allocate (this%synthetic_values(this%total_counts))\n\n        allocate (this%synthetic_values_logical(this%total_counts))\n\n        call read_timeslice_netcdf_integer_variables(ncid, 'observedCounts', time_series_file, this%observed_counts)\n\n        call read_timeslice_netcdf_integer_variables(ncid, 'timeSteps', time_series_file, this%time_step_seconds)\n\n        call read_timeslice_netcdf_real_1D_variables(ncid, 'discharges', time_series_file, this%discharges)\n\n        call read_timeslice_netcdf_integer_1D_variables(ncid, 'synthetic_values', time_series_file, this%synthetic_values)\n\n        this%synthetic_values_logical = (this%synthetic_values /= 0)\n\n        this%forecast_found = .true.\n\n        ! Close Time Series NetCDF file\n        status = nf90_close(ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not close RFC time series file \" &\n        // trim(ADJUSTL(time_series_file)) // \".\")\n\n    end subroutine read_time_series_file\n\nend module module_reservoir_read_rfc_time_series_data\n"
  },
  {
    "path": "src/Routing/Reservoirs/module_reservoir_read_timeslice_data.F90",
    "content": "! This module reads USGS (U.S. Geological Survey) or USACE\n! (U.S. Army Corps of Engineers) timeslice files to get gage discharge\n! values that will be used by reservoirs. An observation lookback\n! period is passed in to determine how far back in time from the\n! current model time the module will look for timeslice files.\n! The observation resolution determines the time increments the\n! module will look back. For instance, a standard lookback period\n! would be 18 hours with an observation resolution of 15 minutes,\n! where a model current time of 8:00 PM would search for timeslice\n! files at every 15 minute increment between 2:00 AM and 8:00 PM\n! that day. The module will first search for the most recent\n! timeslice files and grab the discharge for a particular\n! lake/reservoir if the gage quality standard is met at that time.\n! If a gage discharge is missing or if the gage quality standard\n! is not met for any particular lake/reservoir in the given\n! timeslice file, the module will continue to look back at every\n! observation resolution increment until either all\n! lakes/reservoirs have a good quality discharge or the end of\n! the lookback period is reached. The total lookback seconds\n! from current model time that the discharge is read will also\n! be returned.\n\nmodule module_reservoir_read_timeslice_data\n    use module_reservoir_utilities, only: get_timeslice_array_dimension, &\n                                          read_timeslice_gage_ids, &\n                                          read_timeslice_netcdf_real_1D_variables, &\n                                          read_persistence_netcdf_gage_ids_all, &\n                                          geth_newdate, &\n                                          handle_err\n    use netcdf\n    implicit none\n\n    ! The timeslice_data is a singleton in that the object is instantiated only once per\n    ! processor by the first reservoir on that processor that needs it. The object is then used\n    ! by every other reservoir on that processor that needs it.\n    type :: timeslice_data_type\n\n        character(len=19)                             :: start_date\n        character(len=19)                             :: current_date\n        character(len=256)                            :: timeslice_path\n        character(len=15)                             :: data_source\n        integer                                       :: number_of_reservoir_gages\n        integer                                       :: observation_lookback_hours\n        integer                                       :: current_lookback_seconds\n        integer                                       :: last_update_time_seconds\n        integer,            allocatable, dimension(:) :: gage_lookback_seconds\n        character(len=15),  allocatable, dimension(:) :: reservoir_gage_ids\n        real,               allocatable, dimension(:) :: reservoir_gage_discharges\n        character(len=256), allocatable, dimension(:) :: timeslice_file_names\n        character(len=15),  allocatable, dimension(:) :: gage_id\n        real,               allocatable, dimension(:) :: gage_discharge\n        real,               allocatable, dimension(:) :: gage_quality\n        logical                                       :: initialized = .FALSE.\n\n    contains\n\n        procedure :: init => timeslice_data_init\n        procedure :: destroy => timeslice_data_destroy\n        procedure :: setup_read_timeslice => setup_read_timeslice\n        procedure :: read_timeslice_file => read_timeslice_file\n\n    end type timeslice_data_type\n\n    type (timeslice_data_type), target :: usgs_timeslice_data, usace_timeslice_data\n\n    integer, parameter :: observation_resolution_minutes = 15\n    real,    parameter :: gage_quality_threshold = 0.9\n\ncontains\n\n    ! Timeslice Data Type Constructor\n    subroutine timeslice_data_init(this, start_date, timeslice_path, &\n        reservoir_parameter_file, data_source, observation_lookback_hours)\n        implicit none\n        class(timeslice_data_type), intent(inout) :: this ! object being initialized\n        character(len=19),  intent(in)                   :: start_date\n        character(len=256), intent(in)                   :: timeslice_path\n        character(len=*),   intent(in)                   :: reservoir_parameter_file\n        character(len=*),   intent(in)                   :: data_source\n        integer,            intent(in)                   :: observation_lookback_hours\n        integer                                          :: ncid, var_id\n        integer                                          :: status  ! status of reading NetCDF\n        integer                                          :: timeslice_gage_index\n        character(len=15), allocatable, dimension(:)     :: gage_ids_string_array\n        character(len=15)                                :: gage_id_string, gage_id_string_trimmed\n        integer                                          :: gage_id_integer\n        integer                                          :: char_index, number_counter, temp_val\n        character(len=1)                                 :: temp_char\n\n        ! Return from subroutine if this singleton is already initialized\n        if (this%initialized) return\n        this%initialized = .true.\n\n        this%data_source = ADJUSTL(trim(data_source))\n\n        status = nf90_open(path = reservoir_parameter_file, mode = nf90_nowrite, ncid = ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not open reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        call read_persistence_netcdf_gage_ids_all(ncid, ADJUSTL(trim(this%data_source)) // \"_gage_id\", &\n        reservoir_parameter_file, var_id, this%number_of_reservoir_gages)\n\n        allocate (this%reservoir_gage_ids(this%number_of_reservoir_gages))\n        allocate (gage_ids_string_array(this%number_of_reservoir_gages))\n\n        status = nf90_get_var(ncid, var_id, gage_ids_string_array)\n        if (status /= nf90_noerr) call handle_err(status, \"Error reading \" // ADJUSTL(trim(this%data_source)) &\n         // \"_gage_id from \" // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_close(ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not close reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        ! Convert gage ids to integers\n        do timeslice_gage_index = 1, this%number_of_reservoir_gages\n            gage_id_string = gage_ids_string_array(timeslice_gage_index)\n\n            do char_index = 1, 15\n                temp_val = ichar(gage_id_string(char_index:char_index))\n\n                ! Check if null character, then pad with a space\n                if (temp_val == 0) then\n                    gage_id_string(char_index:char_index) = ' '\n                end if\n            end do\n\n            gage_id_string_trimmed = ADJUSTL(trim(gage_id_string))\n\n            this%reservoir_gage_ids(timeslice_gage_index) = gage_id_string_trimmed\n\n        end do\n\n        if(allocated(gage_ids_string_array)) deallocate(gage_ids_string_array)\n\n        this%start_date = start_date\n        this%current_date = start_date\n        this%timeslice_path = timeslice_path\n        this%observation_lookback_hours = observation_lookback_hours\n\n        this%last_update_time_seconds = -999\n\n        ! Allocate lookback, dishcharge, and timeslice name arrays\n        allocate (this%gage_lookback_seconds(this%number_of_reservoir_gages))\n        allocate (this%reservoir_gage_discharges(this%number_of_reservoir_gages))\n        allocate(this%timeslice_file_names(this%number_of_reservoir_gages))\n\n    end subroutine timeslice_data_init\n\n\n    ! Timeslice Data Type Destructor\n    subroutine timeslice_data_destroy(this)\n\n        implicit none\n        class(timeslice_data_type), intent(inout) :: this ! object being destroyed\n\n    end subroutine timeslice_data_destroy\n\n\n    ! Set up list of timeslice files to read\n    ! The timeslices are read only once on each processor at each timeslice update time\n    subroutine setup_read_timeslice(this, update_interval_seconds, current_reservoir_time_seconds, &\n        reservoir_gage_id, gage_lookback_seconds, reservoir_gage_discharge, reservoir_timeslice_file_name)\n        implicit none\n\n        class(timeslice_data_type), intent(inout) :: this\n        integer, intent(in)  :: update_interval_seconds\n        integer, intent(in)  :: current_reservoir_time_seconds\n        character(len=*), intent(in)  :: reservoir_gage_id\n        integer, intent(out) :: gage_lookback_seconds\n        real, intent(out)    :: reservoir_gage_discharge\n        character(len=256), intent(out)   :: reservoir_timeslice_file_name\n        character(len=256)   :: timeslice_file_name\n        character(len=256)   :: timeslice_file_name_full\n        character(len=19)    :: old_date, new_date\n        character(len=2)     :: observation_resolution_string\n        integer :: total_timeslice_time_periods, timeslice_file_index, reservoir_subset_index, lake_index\n        integer :: observation_minute, observation_resolution_seconds\n        logical :: file_exists\n\n        ! This check ensures that the timeslice is read only once for each processor at each timeslice update time\n        if (current_reservoir_time_seconds .ne. this%last_update_time_seconds) then\n\n            ! Checks if not the first timestep, then update date.\n            if (this%last_update_time_seconds .ne. -999) then\n                call geth_newdate(this%current_date, this%current_date, update_interval_seconds)\n            end if\n\n            this%last_update_time_seconds = current_reservoir_time_seconds\n\n            ! Set gage discharges of subset lakes to default -1.0\n            this%reservoir_gage_discharges = -1.0\n\n            this%gage_lookback_seconds = 0\n            this%current_lookback_seconds = 0\n\n            ! Set timeslice file names to empty strings by default\n            this%timeslice_file_names = \"\"\n\n            total_timeslice_time_periods = this%observation_lookback_hours * (60 / observation_resolution_minutes)\n\n            old_date = this%current_date\n\n            read (old_date(15:16), *) observation_minute\n\n            ! Match minutes to proper observation resolution interval\n            observation_minute = observation_minute / observation_resolution_minutes * observation_resolution_minutes\n\n            ! Formatting for writing minutes\n            if (observation_minute < 10) then\n                old_date(15:16) = \"00\"\n            else\n                write(old_date(15:16), \"(I2)\") observation_minute\n            end if\n\n            ! Zero out seconds\n            old_date(18:19) = \"00\"\n\n            write(observation_resolution_string, \"(I2)\") observation_resolution_minutes\n\n            ! Negative for going back in time\n            observation_resolution_seconds = observation_resolution_minutes * 60 * (-1)\n\n            ! Loop through the total timeslice periods to look for and read timeslice files\n            do timeslice_file_index = 1, total_timeslice_time_periods\n\n                ! Use below for timeslice files with colons in the time\n                old_date = old_date(:13) // ':' // old_date(15:16) // ':' // old_date(18:)\n\n                ! If any gages that still have discharges equal to -1.0, read the previous\n                ! time timeslice file available.\n                if ( any(this%reservoir_gage_discharges == -1.0)) then\n\n                    ! Construct timeslice filename\n                    timeslice_file_name = old_date // \".\" // &\n                            observation_resolution_string // 'min.' // ADJUSTL(trim(this%data_source)) // 'TimeSlice.ncdf'\n\n                    ! Add path to timeslice filename\n                    timeslice_file_name_full = trim(this%timeslice_path) // \"/\" // ADJUSTL(trim(timeslice_file_name))\n\n                    ! Check if file exists\n                    inquire(FILE = timeslice_file_name_full, EXIST = file_exists)\n                    if (file_exists) then\n                        ! Call subroutine to read a particular timeslice file\n                        call this%read_timeslice_file(timeslice_file_name_full, timeslice_file_name)\n                    end if\n\n                    ! Call subroutine to get the date from one observation resolution back in time\n                    call geth_newdate(new_date, old_date, observation_resolution_seconds)\n                    old_date = new_date\n\n                    ! Lookback seconds to account for how long back a timeslice file was read\n                    this%current_lookback_seconds = this%current_lookback_seconds - observation_resolution_seconds\n\n                else\n                    exit\n                end if\n            end do\n\n        end if\n\n        ! Loop through gages to return gage lookback seconds and gage discharge for a given reservoir\n        do reservoir_subset_index = 1, this%number_of_reservoir_gages\n            if (this%reservoir_gage_ids(reservoir_subset_index) .eq. reservoir_gage_id) then\n                gage_lookback_seconds = this%gage_lookback_seconds(reservoir_subset_index)\n                reservoir_gage_discharge = this%reservoir_gage_discharges(reservoir_subset_index)\n                reservoir_timeslice_file_name = this%timeslice_file_names(reservoir_subset_index)\n            end if\n        end do\n\n    end subroutine setup_read_timeslice\n\n\n    ! Read given timeslice file to get gage discharges\n    subroutine read_timeslice_file(this, timeslice_file_full, timeslice_file)\n        implicit none\n        class(timeslice_data_type), intent(inout) :: this\n        character(len=256), intent(in) :: timeslice_file_full\n        character(len=256), intent(in) :: timeslice_file\n        integer :: reservoir_gage_index, timeslice_gage_index, number_of_gages\n        integer :: ncid, status\n\n        ! Open Timeslice NetCDF file\n        status = nf90_open(path = trim(timeslice_file_full), mode = nf90_nowrite, ncid = ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not open timeslice file \" &\n        // trim(ADJUSTL(timeslice_file_full)) // \".\")\n\n        ! Get dimension of gage arrays\n        call get_timeslice_array_dimension(ncid, 'discharge', timeslice_file_full, number_of_gages)\n\n        ! Allocate gage info arrays\n        allocate(this%gage_id(number_of_gages))\n        allocate(this%gage_discharge(number_of_gages))\n        allocate(this%gage_quality(number_of_gages))\n\n        ! Get gage ids\n        call read_timeslice_gage_ids(ncid, 'stationId', timeslice_file_full, this%gage_id)\n\n        ! Get gage discharges\n        call read_timeslice_netcdf_real_1D_variables(ncid, 'discharge', timeslice_file_full, this%gage_discharge)\n\n        ! Get gage qualities\n        call read_timeslice_netcdf_real_1D_variables(ncid, 'discharge_quality', timeslice_file_full, this%gage_quality)\n\n        ! Normalize gage qualities to 1\n        this%gage_quality = this%gage_quality/100\n\n        ! First, quality check on the quality flag\n        where(this%gage_quality .lt. 0 .or. this%gage_quality .gt. 1) this%gage_quality=0\n\n        ! Currently using line below that would set quality to 0 if there is a negative\n        ! discharge but there may actually be a deficit in flow, i.e. no flow available\n        ! at all that the transducer has given us a negative pressure. We do not account\n        ! for that case here but may need to consider this later.\n        where(this%gage_discharge .lt. 0.000) this%gage_quality=0\n\n        ! Currently not using line below instead of above line that sets quality to 0 for negative discharge\n        !where(this%gage_discharge .le. 0.000) this%gage_discharge = 0.0\n\n        !! peak flow on MS river *2\n        !! http://nwis.waterdata.usgs.gov/nwis/peak?site_no=07374000&agency_cd=USGS&format=html\n        !! baton rouge 1945: 1,473,000cfs=41,711cms, multiply it roughly by 2\n        where(this%gage_discharge .ge. 90000.0) this%gage_quality=0\n\n        ! Loop through reservoir gage array to look for gages that still have discharges set to -1.0.\n        ! Match gage ids from the timeslice file gage id arrays to gage ids in the reservoir gage subset\n        ! array. If the matched gage is good quality, then set that reservoir gage subset discharge to\n        ! the discharge read from the timeslice file along with the total lookback seconds from current\n        ! model time that the gage discharge is read from a timeslice file.\n        do reservoir_gage_index = 1, this%number_of_reservoir_gages\n            if (this%reservoir_gage_discharges(reservoir_gage_index) == -1.0) then\n                do timeslice_gage_index = 1, number_of_gages\n                    if (ADJUSTL(trim(this%gage_id(timeslice_gage_index))) &\n                    .eq. ADJUSTL(trim(this%reservoir_gage_ids(reservoir_gage_index)))) then\n                        if (this%gage_quality(timeslice_gage_index) .gt. gage_quality_threshold) then\n                            this%reservoir_gage_discharges(reservoir_gage_index) = this%gage_discharge(timeslice_gage_index)\n                            this%gage_lookback_seconds(reservoir_gage_index) = this%current_lookback_seconds\n                            this%timeslice_file_names(reservoir_gage_index) = ADJUSTL(trim(timeslice_file))\n                        end if\n                        exit\n                    end if\n                end do\n            end if\n        end do\n\n    ! Close timeslice NetCDF file\n    status = nf90_close(ncid)\n    if (status /= nf90_noerr) call handle_err(status, \"Could not close timeslice file \" // trim(ADJUSTL(timeslice_file_full)) // \".\")\n\n    ! Deallocate gage arrays\n    if(allocated(this%gage_id)) deallocate(this%gage_id)\n    if(allocated(this%gage_discharge)) deallocate(this%gage_discharge)\n    if(allocated(this%gage_quality)) deallocate(this%gage_quality)\n\n    end subroutine read_timeslice_file\n\nend module module_reservoir_read_timeslice_data\n"
  },
  {
    "path": "src/Routing/Reservoirs/module_reservoir_utilities.F90",
    "content": "! This module contains a variety of subroutines/functions\n! used by reservoir objects.\n\nmodule module_reservoir_utilities\n    use netcdf\n    use module_hydro_stop, only: HYDRO_stop\n    use iso_fortran_env, only: int64\n    implicit none\n\n#ifndef NCEP_WCOSS\n    integer, parameter :: log_warning = 6\n#else\n    integer, parameter :: log_warning = 78\n#endif\n\ncontains\n\n    ! Checks and warns for boundary conditions of negative inflow\n    subroutine warn_negative_inflow(inflow, lake_number, current_time)\n        real, intent(in)    :: inflow\n        integer, intent(in) :: lake_number, current_time\n\n        if (inflow < 0.0) then\n            write(log_warning,*) \"WARNING: Current inflow \", inflow, &\n            \" cubic meters per second has reached below zero for reservoir \", &\n            lake_number, \" at \", current_time, \" seconds after model start time.\"\n        end if\n\n    end subroutine warn_negative_inflow\n\n\n    ! Checks and warns for boundary conditions of exceeding max or min storage\n    subroutine warn_storage_boundaries(inflow, end_time_storage, min_storage, max_storage, lake_number, current_time)\n        real, intent(in)    :: inflow, end_time_storage, min_storage, max_storage\n        integer, intent(in) :: lake_number, current_time\n\n        ! Also have option to set the end_time_storage to the max_storage and change the outflow accordingly.\n        if (end_time_storage > max_storage) then\n\n            write(log_warning,*) \"WARNING: Calculated storage for this timestep, \", end_time_storage, &\n            \" cubic meters, will exceed the maximum storage boundary of: \", max_storage, &\n            \" cubic meters, for reservoir \", lake_number,\" at \", current_time, \" seconds after model start time.\"\n            write(log_warning,*) \"Current inflow is \", inflow, \" cubic meters per second.\"\n\n        ! Also have option to set the end_time_storage to the min_storage and change the outflow accordingly.\n        else if (end_time_storage < min_storage .and. end_time_storage > 0.0) then\n\n            write(log_warning,*) \"WARNING: Calculated storage for this timestep, \", end_time_storage, &\n            \" cubic meters, will fall below the minimum storage requirement of: \", min_storage, &\n            \" cubic meters, for reservoir \", lake_number, \" at \", current_time, \" seconds after model start time.\"\n            write(log_warning,*) \"Current inflow is \", inflow, \" cubic meters per second.\"\n\n        end if\n\n    end subroutine warn_storage_boundaries\n\n\n    ! Checks and modifies for boundary conditions of negative storage\n    subroutine modify_negative_storage(inflow, previous_time_storage, routing_period, lake_number, current_time, &\n        update_time, end_time_storage, outflow)\n        real, intent(in)    :: inflow, previous_time_storage, routing_period\n        integer, intent(in) :: lake_number, current_time, update_time\n        real, intent(inout) :: end_time_storage, outflow\n\n        ! Note to user:\n        ! In order to conserve mass, when a reservoir's storage would become 0.0 or less, the release\n        ! must be adjusted to avoid releasing water that is not available in the reservoir. To determine\n        ! conditions when this could happen, this function calculates the projected by the end of the\n        ! timestep (dt) based on the latest known conditions of the storage, inflow, and release values.\n\n        ! If the current conditions would cause the storage to become less than or equal to 0.0 cubic meters,\n        ! then the outflow/release will be altered to provide the available storage over the timestep\n        ! (given as R = (S + I*dt)/dt ). This will cause storage at the end of the timestep to be 0.0. From\n        ! this point, the outflow/release is bounded by the inflow provided until the next update time when\n        ! the machine learning model will be run again.\n\n        ! Therefore, the user's choice of time_interval has a significant impact on this simulated outflow/release\n        ! behavior in this edge case.  Release cannot increase again until the next update time occurs. This does,\n        ! however, allow the reservoir to fill back up once inflow increases to exceed current outflow/release\n        ! since storage would then become > 0.0.\n\n        ! If one wants to allow the release to continue to rise as inflow rises, you can set R = I*dt once storage\n        ! has been depleted. This passes on inflow to outflow until an update time occurs, in which case the ML\n        ! model and its post conditions are responsible for calculating an appropriate release.\n\n        ! The logical 'and' below is not necessary because if otherwise this check updates outflow and\n        ! end_time_storage before an update time, those variables would be overwritten after a new release\n        ! is calculated from the machine learning model. The logical 'and' is left here for emphasis on\n        ! the importance it has on timesteps that are not also update times.\n        if (end_time_storage <= 0.0 .AND. current_time < update_time) then\n\n            write(log_warning,*) \"WARNING: End time storage, \", end_time_storage, &\n            \" cubic meters, has reached at or below 0.0 cubic meters for reservoir \", lake_number, &\n            \" at \", current_time, \" seconds after model start time.\"\n            write(log_warning,*) \"Current inflow is \", inflow, \" cubic meters per second.\"\n\n            outflow = (previous_time_storage + inflow * routing_period) / routing_period\n\n            end_time_storage = 0.0\n\n            if (outflow < 0.0) outflow = 0.0\n\n        end if\n\n    end subroutine modify_negative_storage\n\n\n    ! Checks and modifies for boundary conditions of negative inflow\n    subroutine modify_negative_inflow(inflow)\n        real, intent(inout) :: inflow\n\n        if (inflow < 0.0) inflow = 0.0\n\n    end subroutine modify_negative_inflow\n\n\n    ! Checks and modifies for boundary conditions of negative outflow or exceeding min or max storage\n    subroutine modify_for_projected_storage(inflow, previous_time_storage, min_storage, max_storage, &\n        lake_number, current_time, time_interval, outflow, max_storage_reached)\n        real, intent(in)        :: inflow, previous_time_storage, min_storage, max_storage\n        integer, intent(in)     :: lake_number, current_time, time_interval\n        real, intent(inout)     :: outflow\n        logical, intent(inout)  :: max_storage_reached\n        real                    :: excess, projected_next_time_interval_storage\n\n        if (outflow < 0.0) then\n            write(log_warning,*) \"WARNING: Calculations return a negative outflow for reservoir \", lake_number\n            write(log_warning,*) \"at \", current_time, \" seconds after model start time.\"\n            outflow = 0.0\n        end if\n\n        ! The projected_next_time_interval_storage is only calculated as a boundary condition to update the release\n        ! and this storage is calculated assuming a constant flow rate over the time interval. If the time interval\n        ! is too large relative to the channel routing period, this may not be an appropriate calculation.\n        projected_next_time_interval_storage = previous_time_storage + (inflow - outflow) * time_interval\n\n        if (projected_next_time_interval_storage > max_storage) then\n\n            max_storage_reached = .true.\n\n            write(log_warning,*) \"WARNING: Modified release to prevent maximum storage exceedance\", &\n            \" for reservoir \", lake_number\n            write(log_warning,*) \"at \", current_time, \" seconds after model start time.\"\n\n        else if (projected_next_time_interval_storage < min_storage &\n            .AND. projected_next_time_interval_storage > 0.0) then\n\n            outflow = (projected_next_time_interval_storage - min_storage) / time_interval + outflow\n\n            write(log_warning,*) \"WARNING: Modified release to maintain minimum storage for reservoir \", lake_number\n            write(log_warning,*) \"at \", current_time, \" seconds after model start time.\"\n\n        else if (projected_next_time_interval_storage <= 0.0) then\n\n            outflow = inflow\n\n            write(log_warning,*)  \"WARNING: Modified release to prevent storage deficit for reservoir \", lake_number\n            write(log_warning,*) \"at \", current_time, \" seconds after model start time.\"\n\n        end if\n\n        if (outflow < 0.0) outflow = 0.0\n\n    end subroutine modify_for_projected_storage\n\n    ! Reads the reservoir_type form the reservoir parameter file. This subroutine first checks to ensure that\n    ! the lake_id array in the reservoir parameter file matches the lake_id array in the lake parameter file and\n    ! calls hydro_stop if they do not match.\n    subroutine read_reservoir_type(reservoir_parameter_file, lake_parameter_lake_ids, number_of_lake_parameter_lakes, &\n        reservoir_types)\n        character(len=*), intent(in) :: reservoir_parameter_file\n        integer(kind=int64), dimension(:), intent(in) :: lake_parameter_lake_ids\n        integer, intent(in) :: number_of_lake_parameter_lakes\n        integer, dimension(:), intent(inout) :: reservoir_types\n        integer(kind=int64), allocatable, dimension(:) :: reservoir_parameter_lake_ids\n\n        integer, dimension(nf90_max_var_dims) :: dim_ids\n        integer :: ncid, var_id, lake_index, number_of_reservoirs, number_of_reservoir_types\n        integer :: status                        ! status of reading NetCDF\n\n        ! Open Reservoir Parameter NetCDF file\n        status = nf90_open(path = reservoir_parameter_file, mode = nf90_nowrite, ncid = ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not open reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inq_varid(ncid, \"lake_id\", var_id)\n        if (status /= nf90_noerr) call handle_err(status, \"lake_id read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, \"lake_id read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_dimension(ncid, dim_ids(1), len = number_of_reservoirs)\n        if(status /= nf90_NoErr) call handle_err(status, \"lake_id read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        allocate(reservoir_parameter_lake_ids(number_of_reservoirs))\n\n        status = nf90_get_var(ncid, var_id, reservoir_parameter_lake_ids)\n        if (status /= nf90_noerr) call handle_err(status, \"lake_id read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        ! Check to ensure that the lake_id array size in the reservoir parameter file matches the lake_id array\n        ! size in the lake parameter file\n        if (number_of_lake_parameter_lakes .ne. number_of_reservoirs) then\n            call hydro_stop(\"ERROR: Reservoir ID array in the reservoir parameter file does not match the Lake ID array &\n            in the lake parameter file.\")\n\n        else\n            ! Check to ensure that each lake id in the lake_id array in the reservoir parameter file matches\n            ! each lake id in the lake_id array in the lake parameter file\n            do lake_index = 1, number_of_reservoirs\n\n                if (lake_parameter_lake_ids(lake_index) .ne. reservoir_parameter_lake_ids(lake_index)) then\n                    call hydro_stop(\"Reservoir ID array in the reservoir parameter file does not match the Lake ID array &\n                    in the lake parameter file.\")\n                end if\n            end do\n        end if\n\n        status = nf90_inq_varid(ncid, \"reservoir_type\", var_id)\n        if (status /= nf90_noerr) call handle_err(status, \"reservoir_type read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, \"reservoir_type read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_dimension(ncid, dim_ids(1), len = number_of_reservoir_types)\n        if(status /= nf90_NoErr) call handle_err(status, \"reservoir_type read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        ! Check to ensure that the reservoir_type array size matches the lake_id array size.\n        if (number_of_reservoir_types .ne. number_of_lake_parameter_lakes) then\n            call hydro_stop(\"ERROR: Reservoir Type array size in the reservoir parameter file does not match the Lake ID array size &\n            in the lake parameter file.\")\n        end if\n\n        status = nf90_get_var(ncid, var_id, reservoir_types)\n        if (status /= nf90_noerr) call handle_err(status, \"reservoir_type read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        ! Close Reservoir Parameter NetCDF file\n        status = nf90_close(ncid)\n        if (status /= nf90_noerr) call handle_err(status, \"Could not close reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        if(allocated(reservoir_parameter_lake_ids)) deallocate(reservoir_parameter_lake_ids)\n\n    end subroutine read_reservoir_type\n\n\n    ! Gets the dimensions of the gage arrays from the timeslice file\n    subroutine get_timeslice_array_dimension(ncid, netcdf_array_name, timeslice_file, number_of_gages)\n        integer, intent(in) :: ncid\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=256), intent(in) :: timeslice_file\n        integer, intent(out) :: number_of_gages\n        integer :: var_id, status\n        integer, dimension(nf90_max_var_dims) :: dim_ids\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n        status = nf90_inquire_dimension(ncid, dim_ids(1), len = number_of_gages)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n    end subroutine get_timeslice_array_dimension\n\n\n    ! Read gage id array from the timeslice NetCDF\n    subroutine read_timeslice_gage_ids(ncid, netcdf_array_name, timeslice_file, gage_id_var_array)\n        integer, intent(in) :: ncid\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=256), intent(in) :: timeslice_file\n        character(len=*), dimension(:), intent(out) :: gage_id_var_array\n        integer :: var_id, status\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n        status = nf90_get_var(ncid, var_id, gage_id_var_array)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n    end subroutine read_timeslice_gage_ids\n\n\n    ! Read real one dimension parameter arrays from the timeslice NetCDF\n    subroutine read_timeslice_netcdf_real_1D_variables(ncid, netcdf_array_name, timeslice_file, real_var_array)\n        integer, intent(in) :: ncid\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=256), intent(in) :: timeslice_file\n        real, dimension(:), intent(out) :: real_var_array\n        integer :: var_id, status\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n        status = nf90_get_var(ncid, var_id, real_var_array)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n    end subroutine read_timeslice_netcdf_real_1D_variables\n\n\n    ! Read integer one dimension parameter arrays from the timeslice NetCDF\n    subroutine read_timeslice_netcdf_integer_1D_variables(ncid, netcdf_array_name, timeslice_file, integer_var_array)\n        integer, intent(in) :: ncid\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=256), intent(in) :: timeslice_file\n        integer, dimension(:), intent(out) :: integer_var_array\n        integer :: var_id, status\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n        status = nf90_get_var(ncid, var_id, integer_var_array)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n    end subroutine read_timeslice_netcdf_integer_1D_variables\n\n\n    ! Read all gage ids from reservoir parameter file\n    subroutine read_persistence_netcdf_gage_ids_all(ncid, netcdf_array_name, reservoir_parameter_file, var_id, number_of_gages)\n        integer, intent(in) :: ncid\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=*), intent(in) :: reservoir_parameter_file\n        integer, intent(out) ::  var_id, number_of_gages\n        integer :: status\n        integer, dimension(nf90_max_var_dims) :: dim_ids\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_dimension(ncid, dim_ids(2), len = number_of_gages)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n    end subroutine read_persistence_netcdf_gage_ids_all\n\n\n    ! Read lake id from reservoir parameter file and determine the lake_id_index, which\n    ! is the index of the particular reservoir's values in all of the parameter arrays.\n    subroutine read_netcdf_lake_id(ncid, lake_number, netcdf_array_name, reservoir_parameter_file, lake_id_index)\n        integer, intent(in)          :: ncid\n        integer(kind=int64), intent(in)  :: lake_number\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=*), intent(in) :: reservoir_parameter_file\n        integer, intent(out) :: lake_id_index\n        integer, allocatable, dimension(:) :: temp_lake_id_array\n        integer :: var_id, status, number_of_lakes, lake_index\n        integer, dimension(nf90_max_var_dims) :: dim_ids\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name)\n\n        status = nf90_inquire_dimension(ncid, dim_ids(1), len = number_of_lakes)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        allocate(temp_lake_id_array(number_of_lakes))\n\n        status = nf90_get_var(ncid, var_id, temp_lake_id_array)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        do lake_index = 1, number_of_lakes\n            if (temp_lake_id_array(lake_index) == lake_number) then\n                lake_id_index = lake_index\n            end if\n        end do\n\n        if(allocated(temp_lake_id_array)) deallocate(temp_lake_id_array)\n\n    end subroutine read_netcdf_lake_id\n\n\n    ! Read gage id array from reservoir parameter file\n    subroutine read_persistence_netcdf_gage_id(ncid, lake_id_index, netcdf_array_name, reservoir_parameter_file, gage_id)\n        integer, intent(in) :: ncid, lake_id_index\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=*), intent(in) :: reservoir_parameter_file\n        character(len=*), intent(out) :: gage_id\n        character(len=15) :: gage_id_string, gage_id_string_trimmed\n        character(len=15), allocatable, dimension(:) :: temp_gage_id_array\n        integer :: var_id, status, number_of_lakes\n        integer, dimension(nf90_max_var_dims) :: dim_ids\n        integer        :: char_index, number_counter, temp_val\n        character(len=1)   :: temp_char\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_dimension(ncid, dim_ids(2), len = number_of_lakes)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        allocate(temp_gage_id_array(number_of_lakes))\n\n        status = nf90_get_var(ncid, var_id, temp_gage_id_array)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        gage_id_string = temp_gage_id_array(lake_id_index)\n\n        do char_index = 1, 15\n            temp_val = ichar(gage_id_string(char_index:char_index))\n\n            ! Check if null character, then pad with a space\n            if (temp_val == 0) then\n                gage_id_string(char_index:char_index) = ' '\n            end if\n        end do\n\n        gage_id_string_trimmed = ADJUSTL(trim(gage_id_string))\n\n        gage_id = gage_id_string_trimmed\n\n        if(allocated(temp_gage_id_array)) deallocate(temp_gage_id_array)\n\n    end subroutine read_persistence_netcdf_gage_id\n\n\n    ! Read rfc gage id array from the reservoir parameters file\n    subroutine read_reservoir_parameters_netcdf_rfc_gage_id(ncid, lake_id_index, &\n        netcdf_array_name, reservoir_parameter_file, rfc_gage_id)\n        integer, intent(in) :: ncid, lake_id_index\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=*), intent(in) :: reservoir_parameter_file\n        character(len=5), intent(out) :: rfc_gage_id\n        character(len=5) :: gage_id_string, gage_id_string_trimmed\n        character(len=5), allocatable, dimension(:) :: temp_gage_id_array\n        integer :: var_id, status, number_of_lakes\n        integer, dimension(nf90_max_var_dims) :: dim_ids\n        integer        :: char_index, number_counter\n        character(len=1)   :: temp_char\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n         // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name)\n\n        status = nf90_inquire_dimension(ncid, dim_ids(2), len = number_of_lakes)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        allocate(temp_gage_id_array(number_of_lakes))\n\n        status = nf90_get_var(ncid, var_id, temp_gage_id_array)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        gage_id_string = temp_gage_id_array(lake_id_index)\n\n        gage_id_string_trimmed = ADJUSTL(trim(gage_id_string))\n\n        rfc_gage_id = gage_id_string_trimmed\n\n        if(allocated(temp_gage_id_array)) deallocate(temp_gage_id_array)\n\n    end subroutine read_reservoir_parameters_netcdf_rfc_gage_id\n\n\n    ! Read an RFC forecast integer variable for a corresponding lake id from the reservoir parameter file\n    subroutine read_reservoir_parameters_netcdf_rfc_integer(ncid, lake_id_index, &\n        netcdf_array_name, reservoir_parameter_file, integer_var)\n        integer, intent(in) :: ncid, lake_id_index\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=*), intent(in) :: reservoir_parameter_file\n        integer, intent(out) :: integer_var\n        integer, allocatable, dimension(:) :: temp_integer_array\n        integer :: var_id, status, number_of_lakes\n        integer, dimension(nf90_max_var_dims) :: dim_ids\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_dimension(ncid, dim_ids(1), len = number_of_lakes)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        allocate(temp_integer_array(number_of_lakes))\n\n        status = nf90_get_var(ncid, var_id, temp_integer_array)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        integer_var = temp_integer_array(lake_id_index)\n\n        if(allocated(temp_integer_array)) deallocate(temp_integer_array)\n\n    end subroutine read_reservoir_parameters_netcdf_rfc_integer\n\n\n    ! Read real two dimension parameter arrays from the reservoir parameter file\n    subroutine read_persistence_netcdf_real_2D_parameters(ncid, lake_id_index, &\n        netcdf_array_name, reservoir_parameter_file, var_id, number_of_weights, number_of_lakes)\n        integer, intent(in) :: ncid, lake_id_index\n        character(len=*), intent(in) :: netcdf_array_name\n        character(len=*), intent(in) :: reservoir_parameter_file\n        integer, intent(out) :: var_id, number_of_weights, number_of_lakes\n        integer :: status\n        integer, dimension(nf90_max_var_dims) :: dim_ids\n\n        status = nf90_inq_varid(ncid, netcdf_array_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_variable(ncid, var_id, dimids = dim_ids)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_dimension(ncid, dim_ids(1), len = number_of_weights)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n        status = nf90_inquire_dimension(ncid, dim_ids(2), len = number_of_lakes)\n        if(status /= nf90_NoErr) call handle_err(status, netcdf_array_name // \" read error in reservoir parameter file \" &\n        // trim(ADJUSTL(reservoir_parameter_file)) // \".\")\n\n    end subroutine read_persistence_netcdf_real_2D_parameters\n\n\n    ! Read integer parameters from the RFC Time Series NetCDF\n    subroutine read_timeslice_netcdf_integer_variables(ncid, netcdf_variable_name, timeslice_file, integer_variable)\n        integer, intent(in) :: ncid\n        character(len=*), intent(in) :: netcdf_variable_name\n        character(len=256), intent(in) :: timeslice_file\n        integer, intent(out) :: integer_variable\n        integer :: var_id, status\n\n        status = nf90_inq_varid(ncid, netcdf_variable_name, var_id)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_variable_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n        status = nf90_get_var(ncid, var_id, integer_variable)\n        if (status /= nf90_noerr) call handle_err(status, netcdf_variable_name // \" read error in timeslice file \" &\n        // trim(ADJUSTL(timeslice_file)) // \".\")\n\n    end subroutine read_timeslice_netcdf_integer_variables\n\n\n    ! Handle NetCDF error\n    subroutine handle_err(status, variable_error)\n        implicit none\n        integer, intent (in) :: status\n        character (len=*), intent(in) :: variable_error\n        if(status /= nf90_noerr) then\n            call hydro_stop(\"ERROR: \" // trim(nf90_strerror(status)) // ': ' // variable_error)\n        end if\n\n    end subroutine handle_err\n\n\n    ! Create Persistence Levelpool Hybrid Reservoir Function Diagnostic Log CSV File\n    subroutine create_hybrid_diagnostic_log_file(lake_number)\n        integer, intent(in) :: lake_number\n        character(len=15)   :: lake_number_string, lake_number_string_trimmed\n        character(len=50)   :: filename_string\n\n        write(lake_number_string, \"(I15)\") lake_number\n        lake_number_string_trimmed = ADJUSTL(trim(lake_number_string))\n        filename_string = \"hybrid_logs_\"//ADJUSTL(trim(lake_number_string_trimmed))//\".csv\"\n\n        open (113, file=filename_string, status=\"unknown\")\n\n        write (113, \"(A256)\") \"Current Time, Timeslice Update Time, Weight Update Time, &\n        Gage Lookback Seconds, Gage ID, Current Persistence Weight Index, &\n        Current Persistence Weight, Inflow, Storage, Water Elevation, Gage Discharge, &\n        Persisted Outflow, Levelpool Outflow, Weighted Outflow\"\n\n        close(113)\n\n    end subroutine create_hybrid_diagnostic_log_file\n\n\n    ! Log data to Persistence Levelpool Hybrid Reservoir Function Diagnostic Log CSV File\n    subroutine log_hybrid_diagnostic_data(lake_number, current_time, timeslice_update_time, &\n        weight_update_time, gage_lookback_seconds, gage_id, persistence_weight_index, &\n        persistence_current_weight, inflow, current_storage, water_elevation, gage_discharge, &\n        persisted_outflow, levelpool_outflow, outflow)\n        integer, intent(in) :: lake_number, current_time, timeslice_update_time\n        integer, intent(in) :: weight_update_time, gage_lookback_seconds\n        integer, intent(in) :: persistence_weight_index\n        real,    intent(in) :: persistence_current_weight, inflow, current_storage\n        real,    intent(in) :: water_elevation, gage_discharge, persisted_outflow\n        real,    intent(in) :: levelpool_outflow, outflow\n        character(len=*), intent(in) :: gage_id\n        character(len=15)   :: lake_number_string, lake_number_string_trimmed\n        character(len=50)   :: filename_string\n\n        write(lake_number_string, \"(I15)\") lake_number\n        lake_number_string_trimmed = ADJUSTL(trim(lake_number_string))\n        filename_string = \"hybrid_logs_\"//ADJUSTL(trim(lake_number_string_trimmed))//\".csv\"\n\n        open (113, file=filename_string, status=\"unknown\", position = 'append')\n\n        write (113, \"(I20, A1, I20, A1, I20, A1, I20, A1, A15, A1, I20, A1, F15.5, A1, F15.5, &\n        A1, F15.15, A1, F15.5, A1, F15.5, A1, F15.5, A1, F15.5, A1, F15.5)\") &\n        current_time, ',', timeslice_update_time, ',', weight_update_time, ',', &\n        gage_lookback_seconds, ',', gage_id, ',', persistence_weight_index, ',', &\n        persistence_current_weight, ',', inflow, ',', current_storage, ',', &\n        water_elevation, ',', gage_discharge, ',', persisted_outflow, ',', levelpool_outflow, &\n        ',', outflow\n\n        close (113)\n\n    end subroutine log_hybrid_diagnostic_data\n\n\n    ! Create RFC Forecasts Reservoir Function Diagnostic Log CSV File\n    subroutine create_rfc_forecasts_diagnostic_log_file(lake_number)\n        integer, intent(in) :: lake_number\n        character(len=15)   :: lake_number_string, lake_number_string_trimmed\n        character(len=50)   :: filename_string\n\n        write(lake_number_string, \"(I15)\") lake_number\n        lake_number_string_trimmed = ADJUSTL(trim(lake_number_string))\n        filename_string = \"rfc_forecasts_logs_\"//ADJUSTL(trim(lake_number_string_trimmed))//\".csv\"\n\n        open (113, file=filename_string, status=\"unknown\")\n\n        write (113, \"(A256)\") \"Current_Time, Time_Step, Time_Series_Update_Time, &\n        Lookback_Seconds, Time_Series_Index, Gage_ID, Inflow, Water_Elevation, &\n        Levelpool_Outflow, Outflow\"\n\n        close(113)\n\n    end subroutine create_rfc_forecasts_diagnostic_log_file\n\n\n    ! Log data to RFC Forecasts Reservoir Function Diagnostic Log CSV File\n    subroutine log_rfc_forecasts_diagnostic_data(lake_number, current_time, time_step, &\n        time_series_update_time, lookback_seconds, time_series_index, gage_id,  &\n        inflow, water_elevation, levelpool_outflow, outflow)\n        integer, intent(in) :: lake_number, current_time, time_step, time_series_update_time\n        integer, intent(in) :: lookback_seconds, time_series_index\n        character(len=*), intent(in) :: gage_id\n        real,    intent(in) :: inflow, water_elevation, levelpool_outflow, outflow\n        character(len=15)   :: lake_number_string, lake_number_string_trimmed\n        character(len=50)   :: filename_string\n\n        write(lake_number_string, \"(I15)\") lake_number\n        lake_number_string_trimmed = ADJUSTL(trim(lake_number_string))\n        filename_string = \"rfc_forecasts_logs_\"//ADJUSTL(trim(lake_number_string_trimmed))//\".csv\"\n\n        open (113, file=filename_string, status=\"unknown\", position = 'append')\n\n        write (113, \"(I20, A1, I20, A1, I20, A1, I20, A1, I20, A1, A5, A1, F15.5, A1, &\n        F15.5, A1, F15.5, A1, F15.5)\") &\n        current_time, ',', time_step, ',', time_series_update_time, ',', &\n        lookback_seconds, ',', time_series_index, ',', gage_id, ',', &\n        inflow, ',', water_elevation, ',', levelpool_outflow, ',', outflow\n\n        close (113)\n\n    end subroutine log_rfc_forecasts_diagnostic_data\n\n\n    ! Create Levelpool Reservoir Function Diagnostic Log CSV File\n    subroutine create_levelpool_diagnostic_log_file(lake_number)\n        integer, intent(in) :: lake_number\n        character(len=15)   :: lake_number_string, lake_number_string_trimmed\n        character(len=50)   :: filename_string\n\n        write(lake_number_string, \"(I15)\") lake_number\n        lake_number_string_trimmed = ADJUSTL(trim(lake_number_string))\n\n        filename_string = \"levelpool_logs_\"//ADJUSTL(trim(lake_number_string_trimmed))//\".csv\"\n\n        open (113, file=filename_string, status=\"unknown\")\n\n        write (113, \"(A256)\") \"Inflow, Water Elevation, Outflow\"\n\n        close(113)\n\n    end subroutine create_levelpool_diagnostic_log_file\n\n\n    ! Log data to Levelpool Reservoir Function Diagnostic Log CSV File\n    subroutine log_levelpool_diagnostic_data(lake_number, inflow, water_elevation, outflow)\n        integer, intent(in) :: lake_number\n        real,    intent(in) :: inflow\n        real,    intent(in) :: water_elevation\n        real,    intent(in) :: outflow\n        character(len=15)   :: lake_number_string, lake_number_string_trimmed\n        character(len=50)   :: filename_string\n\n        write(lake_number_string, \"(I15)\") lake_number\n        lake_number_string_trimmed = ADJUSTL(trim(lake_number_string))\n        filename_string = \"levelpool_logs_\"//ADJUSTL(trim(lake_number_string_trimmed))//\".csv\"\n\n        open (113, file=filename_string, status=\"unknown\", position = 'append')\n\n        write (113, \"(F15.8, A1, F15.8, A1, F15.8)\") &\n        inflow, ',', water_elevation, ',', outflow\n\n        close (113)\n\n    end subroutine log_levelpool_diagnostic_data\n\n\n    ! Get a new date given an existing date and time interval\n    subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n    !  From old date (\"YYYY-MM-DD HH:MM:SS.ffff\" or \"YYYYMMDDHHMMSSffff\") and\n    !  delta-time, compute the new date.\n\n    !  on entry     -  odate  -  the old hdate.\n    !                  idt    -  the change in time\n\n    !  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n    !  Local Variables\n\n    !  yrold    -  indicates the year associated with \"odate\"\n    !  moold    -  indicates the month associated with \"odate\"\n    !  dyold    -  indicates the day associated with \"odate\"\n    !  hrold    -  indicates the hour associated with \"odate\"\n    !  miold    -  indicates the minute associated with \"odate\"\n    !  scold    -  indicates the second associated with \"odate\"\n\n    !  yrnew    -  indicates the year associated with \"ndate\"\n    !  monew    -  indicates the month associated with \"ndate\"\n    !  dynew    -  indicates the day associated with \"ndate\"\n    !  hrnew    -  indicates the hour associated with \"ndate\"\n    !  minew    -  indicates the minute associated with \"ndate\"\n    !  scnew    -  indicates the second associated with \"ndate\"\n\n    !  mday     -  a list assigning the number of days in each month\n\n    !  i        -  loop counter\n    !  nday     -  the integer number of days represented by \"idt\"\n    !  nhour    -  the integer number of hours in \"idt\" after taking out\n    !              all the whole days\n    !  nmin     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days and whole hours.\n    !  nsec     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days, whole hours, and whole minutes.\n\n    integer :: newlen, oldlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n    logical :: punct\n    integer :: yrstart, yrend, mostart, moend, dystart, dyend\n    integer :: hrstart, hrend, mistart, miend, scstart, scend, frstart\n    integer :: units\n    integer, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n\n    ! Determine if odate is \"YYYY-MM-DD_HH ... \" or \"YYYYMMDDHH....\"\n    if (odate(5:5) == \"-\") then\n       punct = .TRUE.\n    else\n       punct = .FALSE.\n    endif\n\n    !  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    oldlen = LEN(odate)\n    if (punct) then\n       yrstart = 1\n       yrend = 4\n       mostart = 6\n       moend = 7\n       dystart = 9\n       dyend = 10\n       hrstart = 12\n       hrend = 13\n       mistart = 15\n       miend = 16\n       scstart = 18\n       scend = 19\n       frstart = 21\n       select case (oldlen)\n       case (10)\n          ! Days\n          units = 1\n       case (13)\n          ! Hours\n          units = 2\n       case (16)\n          ! Minutes\n          units = 3\n       case (19)\n          ! Seconds\n          units = 4\n       case (21)\n          ! Tenths\n          units = 5\n       case (22)\n          ! Hundredths\n          units = 6\n       case (23)\n          ! Thousandths\n          units = 7\n       case (24)\n          ! Ten thousandths\n          units = 8\n       case default\n\n          write(*,*) 'FATAL ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n          call hydro_stop(\"geth_newdate\")\n\n       end select\n\n       if (oldlen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n\n    else\n\n       yrstart = 1\n       yrend = 4\n       mostart = 5\n       moend = 6\n       dystart = 7\n       dyend = 8\n       hrstart = 9\n       hrend = 10\n       mistart = 11\n       miend = 12\n       scstart = 13\n       scend = 14\n       frstart = 15\n\n       select case (oldlen)\n       case (8)\n          ! Days\n          units = 1\n       case (10)\n          ! Hours\n          units = 2\n       case (12)\n          ! Minutes\n          units = 3\n       case (14)\n          ! Seconds\n          units = 4\n       case (15)\n          ! Tenths\n          units = 5\n       case (16)\n          ! Hundredths\n          units = 6\n       case (17)\n          ! Thousandths\n          units = 7\n       case (18)\n          ! Ten thousandths\n          units = 8\n       case default\n\n          write(*,*) 'FATAL ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n          call hydro_stop(\"geth_newdate\")\n\n       end select\n    endif\n\n    !  Use internal READ statements to convert the CHARACTER string\n    !  date into INTEGER components.\n\n    read(odate(yrstart:yrend),  '(i4)') yrold\n    read(odate(mostart:moend),  '(i2)') moold\n    read(odate(dystart:dyend), '(i2)') dyold\n    if (units.ge.2) then\n       read(odate(hrstart:hrend),'(i2)') hrold\n       if (units.ge.3) then\n          read(odate(mistart:miend),'(i2)') miold\n          if (units.ge.4) then\n             read(odate(scstart:scend),'(i2)') scold\n             if (units.ge.5) then\n                read(odate(frstart:oldlen),*) frold\n             end if\n          end if\n       end if\n    end if\n\n    !  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n    !  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n    !  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n       opass = .FALSE.\n    end if\n\n    !  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n       opass = .FALSE.\n    end if\n\n    !  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n       opass = .FALSE.\n    end if\n\n    !  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n       opass = .FALSE.\n    end if\n\n    !  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n       opass = .FALSE.\n    end if\n\n    !  Check that the fractional part  of ODATE makes sense.\n\n\n    if (.not.opass) then\n\n       write(*,*) 'FATAL ERROR: Crazy ODATE: ', odate(1:oldlen), oldlen\n       stop\n\n    end if\n\n    !  Date Checks are completed.  Continue.\n\n\n    !  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (units.ge.5) then !idt should be in fractions of seconds\n       ifrc = oldlen-(frstart)+1\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (units.eq.4) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (units.eq.3) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.2) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.1) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n\n       write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            oldlen\n       write(*,*) '#'//odate(1:oldlen)//'#'\n       call hydro_stop(\"geth_newdate\")\n\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n    !  Now construct the new mdate\n\n    newlen = LEN(ndate)\n\n    if (punct) then\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n    19    format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n    16    format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n    13    format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,10) yrnew, monew, dynew\n    10    format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n    else\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n    119   format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,116) yrnew, monew, dynew, hrnew, minew\n    116   format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,113) yrnew, monew, dynew, hrnew\n    113   format(i4,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,110) yrnew, monew, dynew\n    110   format(i4,i2.2,i2.2)\n\n       end if\n\n    endif\n\n    if (punct .and. (oldlen.ge.11) .and. (newlen.ge.11)) ndate(11:11) = sp\n\n    end subroutine geth_newdate\n\n    integer function nfeb(year)\n    !\n    ! Compute the number of days in February for the given year.\n    !\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n    end function nfeb\n\nend module module_reservoir_utilities\n"
  },
  {
    "path": "src/Routing/Reservoirs/reservoir_tests.F90",
    "content": "! This program unit tests the various reservoir implementations along with edge cases.\n! It is important to run these unit tests whenever making any changes to code in this\n! module to ensure nothing is broken. If nothing is broken, the user will see\n! \"All Reservoir Tests Passed\". To compile and run these tests, go to the Reservoir\n! directory in the terminal and type \"make\" and then \"make test\". Then type \"./reservoir_tests\".\n\nprogram reservoir_unit_tests\n    use module_levelpool_tests\n    use module_persistence_levelpool_hybrid_tests\n    use module_rfc_forecasts_tests\n\n    implicit none\n\n    logical :: rv1 = .false.\n    logical :: rv2 = .false.\n    logical :: rv3 = .false.\n    logical :: rv4 = .false.\n    logical :: rv5 = .false.\n    logical :: rv6 = .false.\n    logical :: rv7 = .false.\n    logical :: rv8 = .false.\n    logical :: rv9 = .false.\n    logical :: rv10 = .false.\n    logical :: rv11 = .false.\n    logical :: rv12 = .false.\n    logical :: rv13 = .false.\n    logical :: rv14 = .false.\n    logical :: rv15 = .false.\n    logical :: rv16 = .false.\n    logical :: rv17 = .false.\n\n    real, dimension(120) :: inflow_array\n\n    inflow_array = (/189.22899, 189.27005, 189.31049, 189.35042, 189.38965, 189.42819, 189.46588, 189.50273, &\n    189.53859, 189.57346, 189.60719, 189.63979, 189.6711, 189.7011, 189.72968, &\n    189.75679, 189.7823, 189.80617, 189.82822, 189.84842, 189.86653, 189.88255, 189.89622, &\n    189.90752, 189.91612, 189.922, 189.92482, 189.92447, 189.92067, 189.91319, 189.90175, &\n    189.88611, 189.86592, 189.84088, 189.81064, 189.77487, 189.73317, 189.6852, 189.63051, &\n    189.56873, 189.49939, 189.42207, 189.33635, 189.24176, 189.13782, 189.02408, &\n    188.90009, 188.76535, 188.61945, 188.46188, 188.29224, 188.11006, 187.91493, 187.70644, &\n    187.48419, 187.24779, 186.9969, 186.73119, 186.45035, 186.15407, 185.84213, 185.51424, &\n    185.17023, 184.80989, 184.43312, 184.03975, 183.62973, 183.20296, 182.75943, 182.29909, &\n    181.82205, 181.32828, 180.81792, 80.29099, 179.74774, 179.1882, 178.61267, 178.02129, &\n    177.41437, 176.79207, 176.15475, 175.50269, 174.83627, 174.15576, 173.46162, &\n    172.75417, 172.03389, 171.3011, 170.55634, 169.79997, 169.03255, 168.25441, 167.46616, &\n    166.66815, 165.86099, 165.04509, 164.22101, 163.38913, 162.55011, 161.70428, 160.85229, &\n    159.99452, 159.13156, 158.26382, 157.39188, 156.51611, 155.63715, 154.75531, 153.8712, 152.98517, &\n    152.09779, 151.2094, 150.32057, 149.43166, 148.54315, 147.6554, 146.76892, 145.88405, 145.00128, 144.12091/)\n\n    rv1 = test_levelpool()\n\n    rv2 = test_levelpool_overflow_max_height()\n\n    rv3 = test_persistence_levelpool_hybrid_usgs()\n\n    rv4 = test_persistence_levelpool_hybrid_usace()\n\n    rv5 = test_rfc_forecasts_object()\n\n    rv6 = test_rfc_forecasts_time_series_object()\n\n    rv7 = test_rfc_forecasts_levelpool_fallback()\n\n    rv8 = test_rfc_forecasts_time_series_output_with_lookback_and_offset()\n\n    rv9 = test_rfc_forecasts_time_series_output_with_negative_data()\n\n    rv10 = test_rfc_forecasts_time_series_output_all_synthetic_data()\n\n    rv11 = test_rfc_forecasts_data_exceeding_max_range()\n\n    rv12 = test_rfc_forecasts_with_offset_for_extended_AnA()\n\n    rv13 = test_persistence_levelpool_hybrid_usace_overtop()\n\n    rv14 = test_persistence_levelpool_hybrid_usace_no_timeslice_available()\n\n    rv15 = test_ak_rfc_forecasts_pass_through_fallback()\n\n    rv16 = test_ak_rfc_forecasts_time_series_with_lookback_and_offset()\n\n    rv17 = test_rfc_forecasts_over_max_water_elevation()\n\n    if (rv1 .and. rv2 .and. rv3 .and. rv4 .and. rv5 .and. rv6 .and. rv7 .and. rv8 .and. rv9 .and. &\n    rv10 .and. rv11 .and. rv12 .and. rv13 .and. rv14 .and. rv15 .and. rv16 .and. rv17) then\n        print *, \"========================================================================\"\n        print *, 'All Reservoir Tests Passed'\n        print *, \"========================================================================\"\n\n    else\n        print *, \"========================================================================\"\n        print *, 'Not All Reservoir Tests Passed'\n        print *, \"========================================================================\"\n    end if\n\n    contains\n\n    !------------------------------------------------------------------------------!\n    !                              test_levelpool()                                !\n    ! this function verifies that the constructor for the levelpool type correctly !\n    ! initializes all data members                                                 !\n    !------------------------------------------------------------------------------!\n\n    function test_levelpool() result(rv)\n        implicit none\n\n        logical rv                        ! test result\n        logical :: call_status\n\n        type (levelpool) :: levelpool_reservoir_data\n        real :: water_elevation = 2.\n\n        integer(kind=int64):: lake_number = 20\n\n        call_status = .false.\n\n        print *, \"calling init for levelpool\"\n        call levelpool_reservoir_data%init(water_elevation, 4., 6., 8., 10., 11., 12., 14., 16., 18., lake_number)\n\n        print *, \"testing data in levelpool\"\n        call_status = levelpool_data_info(levelpool_reservoir_data)\n\n        if (call_status) then\n            rv = .true.\n        end if\n\n    end function test_levelpool\n\n\n    ! This tests the Persistence Levelpool Hybrid Module run reservoir function for USGS reservoirs.\n    ! It also reads the USGS persistence parameters from the provided reservoir parameter file and\n    ! a gage discharge from the provided USGS Timeslice file.\n    function test_persistence_levelpool_hybrid_usgs() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (persistence_levelpool_hybrid) :: persistence_levelpool_hybrid_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        rv1 = .false.\n        rv2 = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 402142\n        reservoir_type = 2\n\n        print *, \"calling init for persistence_levelpool_hybrid USGS type reservoir\"\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call persistence_levelpool_hybrid_reservoir_data%init(water_elevation, lake_area, weir_elevation, &\n        weir_coefficient, weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, &\n        initial_fractional_depth, lake_number, reservoir_type, \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", &\n        \"2010-10-01_07:00:00\", cwd_full, cwd_full, 12, 1000000000)\n\n        print *, \"testing data in persistence_levelpool_hybrid\"\n        rv1 = persistence_levelpool_hybrid_data_info(persistence_levelpool_hybrid_reservoir_data)\n\n        print *, \"calling reservoir run for persistence_levelpool_hybrid USGS type reservoir\"\n\n        water_elevation = 1331.18005\n\n        do timestep_count = 1, 120\n\n            inflow = inflow_array(timestep_count)\n            call persistence_levelpool_hybrid_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 13.73367 - epsilon(13.73367) .and. outflow .le. 13.73367 + epsilon(13.73367) &\n        .and. dynamic_reservoir_type == 2 .and. assimilated_value .ge. 13.73367 - epsilon(13.73367) &\n        .and. assimilated_value .le. 13.73367 + epsilon(13.73367) .and. &\n        assimilated_source_file == \"2010-10-01_06:00:00.15min.usgsTimeSlice.ncdf\") then\n            rv2 = .true.\n            print *, \"========================================================================\"\n            print *, 'Persistence Levelpool Hybrid Run USGS Reservoir Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'Persistence Levelpool Hybrid Run USGS reservoir Test Failed'\n            print *, 'Outflow should be 13.7336712'\n            print *, 'dynamic_reservoir_type needs to be 2 for USGS persistence output'\n            print *, \"========================================================================\"\n            print *, outflow\n        end if\n\n        if (rv1 .and. rv2) then\n            rv = .true.\n        end if\n\n    end function test_persistence_levelpool_hybrid_usgs\n\n\n    ! This tests the Persistence Levelpool Hybrid Module run reservoir function for U.S. Army Corps of Engineers (USACE)\n    ! type reservoirs. It also reads the USACE persistence parameters from the provided reservoir parameter file\n    ! and a gage discharge from the provided USACE Timeslice file.\n    function test_persistence_levelpool_hybrid_usace() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (persistence_levelpool_hybrid) :: persistence_levelpool_hybrid_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        rv2 = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 4672717\n        reservoir_type = 3\n\n        print *, \"calling init for persistence_levelpool_hybrid USACE type reservoir\"\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call persistence_levelpool_hybrid_reservoir_data%init(water_elevation, lake_area, weir_elevation, &\n        weir_coefficient, weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, &\n        max_depth, initial_fractional_depth, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", &\n        \"2016-10-10_02:00:00\", cwd_full, cwd_full, 12, 1000000000)\n\n        print *, \"calling reservoir run for persistence_levelpool_hybrid for USACE type reservoir\"\n\n        water_elevation = 1331.18005\n\n        do timestep_count = 1, 120\n\n            inflow = inflow_array(timestep_count)\n            call persistence_levelpool_hybrid_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 16.0820713 - epsilon(16.0820713) .and. outflow .le. 16.0820713 + epsilon(16.0820713) &\n        .and. dynamic_reservoir_type == 3 .and. assimilated_value .ge. 16.082071 - epsilon(16.082071) &\n        .and. assimilated_value .le. 16.082071 + epsilon(16.082071) .and. &\n        assimilated_source_file == \"2016-10-10_00:00:00.15min.usaceTimeSlice.ncdf\") then\n            rv2 = .true.\n            print *, \"========================================================================\"\n            print *, 'Persistence Levelpool Hybrid Run USACE Reservoir Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'Persistence Levelpool Hybrid Run USACE Reservoir Test Failed'\n            print *, 'Outflow should be 16.08207'\n            print *, 'dynamic_reservoir_type needs to be 3 for USACE persistence output'\n            print *, \"========================================================================\"\n            print *, outflow\n        end if\n\n        if (rv2) then\n            rv = .true.\n        end if\n\n    end function test_persistence_levelpool_hybrid_usace\n\n\n    ! This tests the Persistence Levelpool Hybrid Module run reservoir function USACE\n    ! type reservoirs to output level pool whenever it reaches the overtop condition.\n    function test_persistence_levelpool_hybrid_usace_overtop() result(rv)\n\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (persistence_levelpool_hybrid) :: persistence_levelpool_hybrid_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coeffecient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        rv2 = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coeffecient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 4672717\n        reservoir_type = 3\n\n        print *, \"calling init for persistence_levelpool_hybrid USACE type reservoir\"\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call persistence_levelpool_hybrid_reservoir_data%init(water_elevation, lake_area, weir_elevation, &\n        weir_coeffecient, weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, &\n        max_depth, initial_fractional_depth, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", &\n        \"2016-10-10_02:00:00\", cwd_full, cwd_full, 12, 1000000000)\n\n        print *, \"calling reservoir run for persistence_levelpool_hybrid for USACE type reservoir\"\n\n        ! This initial water elevation sets to reservoir overtop\n        water_elevation = 1338.18005\n\n        do timestep_count = 1, 120\n\n            inflow = inflow_array(timestep_count)\n            call persistence_levelpool_hybrid_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 229.226059 - epsilon(229.226059) .and. outflow .le. 229.226059 + epsilon(229.226059) &\n        .and. dynamic_reservoir_type == 1 .and. assimilated_value .ge. -9999.0 - epsilon(-9999.0) &\n        .and. assimilated_value .le. -9999.0 + epsilon(-9999.0) .and. &\n        assimilated_source_file == \"\") then\n            rv2 = .true.\n            print *, \"========================================================================\"\n            print *, 'Persistence Levelpool Hybrid Run USACE Reservoir Overflow Max Height Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'Persistence Levelpool Hybrid Run USACE Reservoir Overflow Max Height Test Failed'\n            print *, 'Outflow should be 16.08207'\n            print *, 'dynamic_reservoir_type needs to be 1 because reservoir outputs level pool instead of USACE persistence'\n            print *, \"========================================================================\"\n            print *, outflow\n        end if\n\n        if (rv2) then\n            rv = .true.\n        end if\n\n    end function test_persistence_levelpool_hybrid_usace_overtop\n\n\n    ! This tests the Persistence Levelpool Hybrid Module run reservoir function USACE\n    ! type reservoirs to output level pool whenever no timeslices are available.\n    function test_persistence_levelpool_hybrid_usace_no_timeslice_available() result(rv)\n\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (persistence_levelpool_hybrid) :: persistence_levelpool_hybrid_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coeffecient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        rv2 = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coeffecient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 347987  ! the corresponding USACE gage id is CA00265\n        reservoir_type = 3\n\n        print *, \"calling init for persistence_levelpool_hybrid USACE type reservoir\"\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call persistence_levelpool_hybrid_reservoir_data%init(water_elevation, lake_area, weir_elevation, &\n        weir_coeffecient, weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, &\n        max_depth, initial_fractional_depth, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", &\n        \"2016-10-12_02:00:00\", cwd_full, cwd_full, 12, 1000000000)\n\n        print *, \"calling reservoir run for persistence_levelpool_hybrid for USACE type reservoir\"\n\n        water_elevation = 1331.18005\n\n        do timestep_count = 1, 120\n\n            inflow = inflow_array(timestep_count)\n            call persistence_levelpool_hybrid_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 1.81549609 - epsilon(1.81549609) .and. outflow .le. 1.81549609 + epsilon(1.81549609) &\n        .and. dynamic_reservoir_type == 1 .and. assimilated_value .ge. -9999.0 - epsilon(-9999.0) &\n        .and. assimilated_value .le. -9999.0 + epsilon(-9999.0) .and. &\n        assimilated_source_file == \"\") then\n            rv2 = .true.\n            print *, \"========================================================================\"\n            print *, 'Persistence Levelpool Hybrid Run USACE Reservoir No Timeslice Available Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'Persistence Levelpool Hybrid Run USACE Reservoir No Timeslice Available Test Failed'\n            print *, 'Outflow should be 1.81549609'\n            print *, 'dynamic_reservoir_type needs to be 1 because reservoir outputs level pool instead of USACE persistence'\n            print *, \"========================================================================\"\n            print *, outflow\n        end if\n\n        if (rv2) then\n            rv = .true.\n        end if\n\n    end function test_persistence_levelpool_hybrid_usace_no_timeslice_available\n\n\n    ! This tests the reservoir function of the level pool module under the specific condition\n    ! where the water elevation reaches the max height.\n    function test_levelpool_overflow_max_height() result(rv)\n\n        implicit none\n        logical rv                       ! test result\n        type (levelpool) :: levelpool_reservoir_data\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation\n        real :: orifice_coefficient, orifice_area, max_depth\n        integer(kind=int64):: lake_number\n        real :: inflow, prev_time_inflow, outflow, water_elevation\n        real, dimension(108) :: inflow_array_overflow\n        integer :: timestep_count\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        rv = .false.\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n\n        lake_area = 1.509490013122558594e+01\n        weir_elevation = 9.626000022888183238e+00\n        weir_coefficient = 0.4\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 7.733333269755045869e+00\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 9.960000038146972656e+00\n        lake_number = 16944276\n\n        inflow_array_overflow = (/91.27196, 91.7394, 92.15904, 92.1518, 91.84663, &\n        91.38554, 90.86131, 90.32736, 89.81273, 89.3325, 88.89427, 88.5025, 88.16228, &\n        87.41539, 86.80043, 86.03979, 85.3849, 85.33451, 86.84274, 91.6084, 101.81398, &\n        118.85916, 143.99232, 177.7355, 219.2348, 267.22351, 319.90402, 374.54324, 428.86066, &\n        480.92096, 529.23584, 572.77673, 610.93237, 643.4389, 670.28516, 691.67767, 707.96088, &\n        719.57312, 726.96997, 730.63269, 731.03186, 728.61438, 723.79578, 716.9549, 708.43268, &\n        698.53247, 687.52112, 675.63123, 663.06421, 649.99976, 636.57898, 622.92926, 609.1745, &\n        595.40369, 581.68799, 568.08588, 554.64484, 541.4032, 528.39185, 515.63513, 503.14838, &\n        490.95123, 479.05109, 467.45493, 456.16663, 445.18753, 434.51706, 424.15311,414.0921, &\n        404.32956, 394.86014, 385.67789, 376.77621, 368.14966, 359.78958, 351.68875, 343.83972, &\n        336.23505, 328.86719, 321.7287, 314.81219, 308.11047, 301.61646, 295.32312, 289.22369, &\n        283.31207, 277.5813, 272.02521, 266.63776, 261.41315, 256.34564, 251.42978, 246.66023, &\n        242.03192, 237.53989, 233.17944, 228.94595, 224.83511, 220.84265, 216.96449, 213.19672, &\n        209.53554, 205.97734, 202.51857, 199.1559, 195.88605, 192.70595, 189.61255 /)\n\n        call levelpool_reservoir_data%init(water_elevation, lake_area, weir_elevation, &\n        weir_coefficient, weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, lake_number)\n\n        water_elevation = 9.73733330\n\n        print *, \"outflow\"\n\n        do timestep_count = 1, 108\n            inflow = inflow_array_overflow(timestep_count)\n            call levelpool_reservoir_data%run(inflow, inflow, 0.0, water_elevation, outflow, 300.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 17.0451450 - epsilon(17.0451450) .and. outflow .le. 17.0451450 + epsilon(17.0451450) &\n        .and. dynamic_reservoir_type == 1 .and. assimilated_value .ge. -9999.0 - epsilon(-9999.0) &\n        .and. assimilated_value .le. -9999.0 + epsilon(-9999.0) .and. &\n        assimilated_source_file == \"\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'Levelpool Overflow Max Height Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'Levelpool Overflow Max Height Test Failed'\n            print *, 'Final outflow should be 17.0451450'\n             print *, 'dynamic_reservoir_type needs to be 1 for level pool type'\n            print *, \"========================================================================\"\n        end if\n\n    end function test_levelpool_overflow_max_height\n\n\n    ! This tests the basic object creation of an RFC Forecast type reservoir.\n    function test_rfc_forecasts_object() result(rv)\n        implicit none\n\n        logical rv                        ! test result\n        logical :: call_status\n\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        type (time_series_data_type) :: time_series_data\n        character*256 :: cwd_full\n        integer(kind=int64):: lake_number\n\n        real :: water_elevation = 2.\n\n        lake_number = 3745478\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call_status = .false.\n\n        print *, \"calling init for rfc_forecasts\"\n        call rfc_forecasts_reservoir_data%init(water_elevation, 4., 6., 8., 10., 11., 12., 14., 16., 18., 0.9, lake_number, 4, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", \"2019-08-18_07:00:00\", cwd_full, 24)\n\n        print *, \"testing data in rfc_forecasts\"\n\n        call_status = rfc_forecasts_data_info(rfc_forecasts_reservoir_data)\n\n        if (call_status) then\n            rv = .true.\n        end if\n\n    end function test_rfc_forecasts_object\n\n\n    ! This tests the object creation and function of the RFC Forecasts Time Series Reader.\n    function test_rfc_forecasts_time_series_object() result(rv)\n        implicit none\n\n        logical rv                        ! test result\n        logical :: call_status\n        type (time_series_data_type) :: time_series_data, time_series_data_second\n        character*256 :: cwd_full\n        integer :: lookback_seconds, total_counts, observed_counts, time_step_seconds\n        integer :: timeslice_offset_hours\n        real, allocatable, dimension(:) :: forecast_discharges\n        logical :: forecast_found\n        logical :: all_discharges_synthetic\n        character(len=256):: time_series_file_name\n        integer :: lake_number\n\n        lake_number = 3745478\n\n        call_status = .false.\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        forecast_found = .false.\n\n        all_discharges_synthetic = .false.\n\n        timeslice_offset_hours = 3\n\n        call time_series_data%init(\"2019-08-18_07:00:00\", cwd_full, 24, timeslice_offset_hours, \"CCHC1\", lake_number, &\n        lookback_seconds, total_counts, observed_counts, time_step_seconds, forecast_discharges, forecast_found, &\n        all_discharges_synthetic, time_series_file_name)\n\n        print *, \"Checking reading of time series file\"\n        if ( forecast_discharges(8) .ge. 0.8 - epsilon(0.8) .and. forecast_discharges(8) .le. 0.8 + epsilon(0.8) ) then\n            print *, \"========================================================================\"\n            print *, \"All RFC Forecast Reservoir Time Series Object Tests Passed\"\n            print *, \"========================================================================\"\n            rv = .true.\n        else\n            print *, \"========================================================================\"\n            print *, \"Not All RFC Forecast Reservoir Time Series Object Tests Passed\"\n            print *, '8th discharge in the discharge array should be 0.8'\n            print *, \"========================================================================\"\n        end if\n\n    end function test_rfc_forecasts_time_series_object\n\n\n    ! This tests an RFC Forecasts Reservoir functionality to run levelpool whenever it does\n    ! not find its corresponding time series file within a given lookback window.\n    function test_rfc_forecasts_levelpool_fallback() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        rv2 = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 3745478\n        reservoir_type = 4\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.9, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", \"2019-05-01_22:00:00\", cwd_full, 24)\n\n        water_elevation = 1331.18005\n\n        do timestep_count = 1, 120\n\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 1.81549609 - epsilon(1.81549609) .and. outflow .le. 1.81549609 + epsilon(1.81549609) &\n        .and. dynamic_reservoir_type == 1 .and. assimilated_value .ge. -9999.0 - epsilon(-9999.0) &\n        .and. assimilated_value .le. -9999.0 + epsilon(-9999.0) .and. &\n        assimilated_source_file == \"\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Levelpool Fallback Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Levelpool Fallback Test Failed'\n            print *, 'Outflow should be 1.81549609'\n            print *, 'dynamic_reservoir_type needs to be 1 because reservoir outputs level pool instead of RFC forecast'\n            print *, \"========================================================================\"\n\n        end if\n\n    end function test_rfc_forecasts_levelpool_fallback\n\n\n    ! This tests an RFC Forecast Reservoirs functionality to offset 3 hours in the future\n    ! and look back up to 24 hours to find a time series file and output the appropriate\n    ! discharge in the array that matches up with model time as would be done in a standard\n    ! analysis and assimilation run.\n    function test_rfc_forecasts_time_series_output_with_lookback_and_offset() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 17609317\n        reservoir_type = 4\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.9, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", \"2019-08-18_09:00:00\", cwd_full, 24)\n\n        water_elevation = 1331.18005\n\n        do timestep_count = 1, 80\n\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 3600.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 3.6 - epsilon(3.6) .and. outflow .le. 3.6 + epsilon(3.6) .and. &\n        water_elevation .ge. 1331.43604 - epsilon(1331.43604) .and. water_elevation .le. 1331.43604 + epsilon(1331.43604) .and. &\n        dynamic_reservoir_type == 4 .and. assimilated_value .ge. 3.6 - epsilon(3.6) &\n        .and. assimilated_value .le. 3.6 + epsilon(3.6) .and. &\n        assimilated_source_file == \"2019-08-18_00.60min.CCHC1.RFCTimeSeries.ncdf\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output Test Failed'\n            print *, 'Outflow should be 3.6'\n            print *, 'dynamic_reservoir_type needs to be 4 for RFC forecast output'\n            print *, \"========================================================================\"\n\n        end if\n\n    end function test_rfc_forecasts_time_series_output_with_lookback_and_offset\n\n\n    ! This tests an RFC Forecast Reservoir's functionality to run levelpool if\n    ! it receives any values from a Time Series Forecast file that are negative.\n    function test_rfc_forecasts_time_series_output_with_negative_data() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 17609317\n        reservoir_type = 4\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.9, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", \"2019-09-18_09:00:00\", cwd_full, 24)\n        water_elevation = 1331.18005\n        do timestep_count = 1, 120\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n            prev_time_inflow = inflow\n            print *, outflow\n        end do\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n        if (outflow .ge. 1.81549609 - epsilon(1.81549609) .and. outflow .le. 1.81549609 + epsilon(1.81549609) &\n        .and. dynamic_reservoir_type == 1 .and. assimilated_value .ge. -9999.0 - epsilon(-9999.0) &\n        .and. assimilated_value .le. -9999.0 + epsilon(-9999.0) .and. &\n        assimilated_source_file == \"\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output Negative Data Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output Negative Data Test Failed'\n            print *, 'Outflow should be 1.81549609'\n            print *, 'dynamic_reservoir_type needs to be 1 because reservoir outputs level pool instead of RFC forecast'\n            print *, \"========================================================================\"\n        end if\n    end function test_rfc_forecasts_time_series_output_with_negative_data\n    ! This tests an RFC Forecast Reservoir's functionality to run levelpool if\n    ! it receives all synthetic values from a Time Series Forecast file.\n    function test_rfc_forecasts_time_series_output_all_synthetic_data() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 17609317\n        reservoir_type = 4\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.9, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", \"2019-10-18_09:00:00\", cwd_full, 24)\n\n        water_elevation = 1331.18005\n\n        do timestep_count = 1, 120\n\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 1.81549609 - epsilon(1.81549609) .and. outflow .le. 1.81549609 + epsilon(1.81549609) &\n        .and. dynamic_reservoir_type == 1 .and. assimilated_value .ge. -9999.0 - epsilon(-9999.0) &\n        .and. assimilated_value .le. -9999.0 + epsilon(-9999.0) .and. &\n        assimilated_source_file == \"\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output All Synthetic Data Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output All Synthetic Data Test Failed'\n            print *, 'Outflow should be 1.81549609'\n            print *, 'dynamic_reservoir_type needs to be 1 because reservoir outputs level pool instead of RFC forecast'\n            print *, \"========================================================================\"\n\n        end if\n\n    end function test_rfc_forecasts_time_series_output_all_synthetic_data\n\n\n    ! This tests an RFC Forecast Reservoir's functionality to run levelpool if\n    ! it receives any values from a Time Series Forecast file that are greater than the max\n    ! historical MS river flow.\n    function test_rfc_forecasts_data_exceeding_max_range() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 17609317\n        reservoir_type = 4\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.9, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", \"2019-11-18_09:00:00\", cwd_full, 24)\n        water_elevation = 1331.18005\n        do timestep_count = 1, 120\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n            prev_time_inflow = inflow\n            print *, outflow\n        end do\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n        if (outflow .ge. 1.81549609 - epsilon(1.81549609) .and. outflow .le. 1.81549609 + epsilon(1.81549609) &\n        .and. dynamic_reservoir_type == 1 .and. assimilated_value .ge. -9999.0 - epsilon(-9999.0) &\n        .and. assimilated_value .le. -9999.0 + epsilon(-9999.0) .and. &\n        assimilated_source_file == \"\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output Data Exceeding Max Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output Data Exceeding Max Test Failed'\n            print *, 'Outflow should be 1.81549609'\n            print *, 'dynamic_reservoir_type needs to be 1 because reservoir outputs level pool instead of RFC forecast'\n            print *, \"========================================================================\"\n        end if\n    end function test_rfc_forecasts_data_exceeding_max_range\n    ! This tests an RFC Forecast Reservoirs functionality to offset 28 hours in the future\n    ! and look back up to 24 hours to find a time series file and output the appropriate\n    ! discharge in the array that matches up with model time as would be done in an extended\n    ! analysis and assimilation run.\n    function test_rfc_forecasts_with_offset_for_extended_AnA() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 17609317\n        reservoir_type = 4\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.9, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_AnA_represents_Extended_MR.nc\", &\n        \"2019-12-18_03:00:00\", cwd_full, 24)\n        water_elevation = 1331.18005\n        do timestep_count = 1, 35\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 3600.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n            prev_time_inflow = inflow\n            print *, outflow\n        end do\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n        if (outflow .ge. 7.8 - epsilon(7.8) .and. outflow .le. 7.8 + epsilon(7.8) &\n        .and. dynamic_reservoir_type == 4 .and. assimilated_value .ge. 7.8 - epsilon(7.8) &\n        .and. assimilated_value .le. 7.8 + epsilon(7.8) .and. &\n        assimilated_source_file == \"2019-12-19_05.60min.CCHC1.RFCTimeSeries.ncdf\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output For Extended AnA Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output For Extended AnA Test Failed'\n            print *, 'Outflow should be 7.8'\n            print *, 'dynamic_reservoir_type needs to be 4 for RFC forecast output'\n            print *, \"========================================================================\"\n        end if\n    end function test_rfc_forecasts_with_offset_for_extended_AnA\n\n    ! This tests an Alaska RFC Forecasts Reservoir/Glacier functionality to pass inflow directly to\n    ! outflow whenever it does not find its corresponding time series file within a given\n    ! lookback window.\n    function test_ak_rfc_forecasts_pass_through_fallback() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n        rv2 = .false.\n        lake_area = 0.0\n        weir_elevation = 0.0\n        weir_coefficient = 0.0\n        weir_length = 0.0\n        dam_length = 0.0\n        orifice_elevation = 0.0\n        orifice_coefficient = 0.0\n        orifice_area = 0.0\n        max_depth = 0.0\n        initial_fractional_depth = 0.0\n        lake_number = 1\n        reservoir_type = 5\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.0, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_Standard_AnA_APRFC_GDLs.nc\", \"2019-05-01_22:00:00\", cwd_full, 24)\n        water_elevation = 0.0\n        do timestep_count = 1, 120\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 900.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n            prev_time_inflow = inflow\n            print *, outflow\n        end do\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n        if (outflow .ge. inflow - epsilon(inflow) .and. outflow .le. inflow + epsilon(inflow) &\n        .and. water_elevation .ge. 0.0 - epsilon(0.0) .and. water_elevation .le. 0.0 + epsilon(0.0) &\n        .and. dynamic_reservoir_type == 1 .and. assimilated_value .ge. -9999.0 - epsilon(-9999.0) &\n        .and. assimilated_value .le. -9999.0 + epsilon(-9999.0) .and. &\n        assimilated_source_file == \"\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'AK RFC Forecasts Pass Through Fallback Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'AK RFC Forecasts Pass Throug Fallback Test Failed'\n            print *, 'Outflow should be 144.120911'\n            print *, 'dynamic_reservoir_type needs to be 1 because reservoir outputs level pool instead of RFC forecast'\n            print *, \"========================================================================\"\n        end if\n    end function test_ak_rfc_forecasts_pass_through_fallback\n\n    ! This tests an Alaska RFC Forecast Reservoir/Glacier functionality to offset 3 hours in the future\n    ! and look back up to 24 hours to find a time series file and output the appropriate\n    ! discharge in the array that matches up with model time as would be done in a standard\n    ! analysis and assimilation run.\n    function test_ak_rfc_forecasts_time_series_with_lookback_and_offset() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer(kind=int64):: lake_number\n        integer :: reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n\n        lake_area = 0.0\n        weir_elevation = 0.0\n        weir_coefficient = 0.0\n        weir_length = 0.0\n        dam_length = 0.0\n        orifice_elevation = 0.0\n        orifice_coefficient = 0.0\n        orifice_area = 0.0\n        max_depth = 0.0\n        initial_fractional_depth = 0.0\n        lake_number = 1\n        reservoir_type = 5\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.0, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_Standard_AnA_APRFC_GDLs.nc\", \"2019-08-18_09:00:00\", cwd_full, 24)\n        water_elevation = 0.0\n        do timestep_count = 1, 80\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 3600.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n            prev_time_inflow = inflow\n            print *, outflow\n        end do\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n        if (outflow .ge. 180.392075 - epsilon(180.392075) .and. outflow .le. 180.392075 + epsilon(180.392075) &\n        .and. water_elevation .ge. 0.0 - epsilon(0.0) .and. water_elevation .le. 0.0 + epsilon(0.0) &\n        .and. dynamic_reservoir_type == 5 .and. assimilated_value .ge. 3.6 - epsilon(3.6) &\n        .and. assimilated_value .le. 3.6 + epsilon(3.6) .and. &\n        assimilated_source_file == \"2019-08-18_00.60min.SNOA2.RFCTimeSeries.ncdf\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'AK RFC Forecasts Time Series Output Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'AK RFC Forecasts Time Series Output Test Failed'\n            print *, 'Outflow should be 180.392075'\n            print *, 'dynamic_reservoir_type needs to be 5 for AK RFC forecast output'\n            print *, \"========================================================================\"\n        end if\n    end function test_ak_rfc_forecasts_time_series_with_lookback_and_offset\n\n    ! This tests an RFC Forecast Reservoirs functionality to correct water elevation going\n    ! over max water elevation\n    function test_rfc_forecasts_over_max_water_elevation() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer :: lake_number, reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 17609317\n        reservoir_type = 4\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.9, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_short_range.nc\", \"2019-08-18_09:00:00\", cwd_full, 24)\n\n        !water_elevation = 1331.18005\n\n        water_elevation = 1.335180053710937500e+03\n\n        do timestep_count = 1, 80\n\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 3600.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 3.6 - epsilon(3.6) .and. outflow .le. 3.6 + epsilon(3.6) .and. &\n        water_elevation .ge. 1335.18005 - epsilon(1335.18005) .and. water_elevation .le. 1335.18005 + epsilon(1335.18005) .and. &\n        dynamic_reservoir_type == 4 .and. assimilated_value .ge. 3.6 - epsilon(3.6) &\n        .and. assimilated_value .le. 3.6 + epsilon(3.6) .and. &\n        assimilated_source_file == \"2019-08-18_00.60min.CCHC1.RFCTimeSeries.ncdf\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Over Max Water Elevation Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Over Max Water Elevation Test Failed'\n            print *, 'Outflow should be 3.6'\n            print *, 'Water Elevation should be 1335.18005'\n            print *, 'dynamic_reservoir_type needs to be 4 for RFC forecast output'\n            print *, \"========================================================================\"\n\n        end if\n\n    end function test_rfc_forecasts_over_max_water_elevation\n\n\n    ! This tests an RFC Forecast Reservoirs functionality to offset 12 hours in the future\n    ! and look back up to 24 hours to find a time series file and output the appropriate\n    ! discharge in the array that matches up with model time as would be done in a long range\n    ! analysis and assimilation run.\n    function test_rfc_forecasts_with_offset_for_long_range_AnA() result(rv)\n        implicit none\n        logical rv, rv1, rv2                        ! test result\n        type (rfc_forecasts) :: rfc_forecasts_reservoir_data\n        real :: outflow, inflow\n        real :: water_elevation\n        real :: prev_time_inflow\n        real :: lake_area, weir_elevation, weir_coefficient\n        real :: weir_length, dam_length, orifice_elevation, orifice_coefficient\n        real :: orifice_area, max_depth, initial_fractional_depth\n        integer :: lake_number, reservoir_type\n        integer :: timestep_count\n        character*256 :: cwd_full\n        integer :: dynamic_reservoir_type\n        real :: assimilated_value\n        character(len=256) :: assimilated_source_file\n\n        prev_time_inflow = 0.0\n        timestep_count = 0\n        water_elevation = 0.0\n        rv = .false.\n\n        lake_area = 2.096320037841796875e+02\n        weir_elevation = 1.332074047851562455e+03\n        weir_coefficient = 4.000000000000000222e-01\n        weir_length = 1.000000000000000000e+01\n        dam_length = 10.0\n        orifice_elevation = 1.314473347981770758e+03\n        orifice_coefficient = 1.000000000000000056e-01\n        orifice_area = 1.0\n        max_depth = 1.335180053710937500e+03\n        initial_fractional_depth = 8.999999761581420898e-01\n        lake_number = 17609317\n        reservoir_type = 4\n\n        cwd_full = \"../../../../tests/local/reservoir_testing_files/\"\n\n        call rfc_forecasts_reservoir_data%init(water_elevation, lake_area, weir_elevation, weir_coefficient, &\n        weir_length, dam_length, orifice_elevation, orifice_coefficient, orifice_area, max_depth, 0.9, lake_number, reservoir_type, &\n        \"../../../../tests/local/reservoir_testing_files/reservoir_index_Long_Range_AnA.nc\", &\n        \"2019-12-18_19:00:00\", cwd_full, 24)\n\n        water_elevation = 1331.18005\n\n        do timestep_count = 1, 19\n\n            inflow = inflow_array(timestep_count)\n            call rfc_forecasts_reservoir_data%run(inflow, &\n            inflow, 0.0, water_elevation, outflow, 3600.0, dynamic_reservoir_type, &\n            assimilated_value, assimilated_source_file)\n\n            prev_time_inflow = inflow\n\n            print *, outflow\n        end do\n\n        print *, 'dynamic_reservoir_type: ', dynamic_reservoir_type\n\n        if (outflow .ge. 7.8 - epsilon(7.8) .and. outflow .le. 7.8 + epsilon(7.8) &\n        .and. dynamic_reservoir_type == 4 .and. assimilated_value .ge. 7.8 - epsilon(7.8) &\n        .and. assimilated_value .le. 7.8 + epsilon(7.8) .and. &\n        assimilated_source_file == \"2019-12-19_05.60min.CCHC1.RFCTimeSeries.ncdf\") then\n            rv = .true.\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output For Long Range AnA Test Passed'\n            print *, \"========================================================================\"\n        else\n            print *, \"========================================================================\"\n            print *, 'RFC Forecasts Time Series Output For Long Range AnA Test Failed'\n            print *, 'Outflow should be 7.8'\n            print *, 'dynamic_reservoir_type needs to be 4 for RFC forecast output'\n            print *, \"========================================================================\"\n\n        end if\n\n    end function test_rfc_forecasts_with_offset_for_long_range_AnA\n\nend program\n"
  },
  {
    "path": "src/Routing/Subsurface/CMakeLists.txt",
    "content": "add_library(hydro_routing_subsurface STATIC\n        module_subsurface_input.F90\n        module_subsurface_output.F90\n        module_subsurface_static_data.F90\n        module_subsurface_grid_transform.F90\n        module_subsurface_properties.F90\n        module_subsurface_state.F90\n        module_subsurface.F90\n)\n\ntarget_link_libraries(hydro_routing_subsurface PRIVATE hydro_routing_overland)\n"
  },
  {
    "path": "src/Routing/Subsurface/Makefile",
    "content": "#simple compilation test for modules in overland routing\n\ninclude ../../macros\n\n# Settings for testing with ifort\nFC=ifort\nFFLAGS=-c -free -O3\n\n# Setting for testing with gfortran\n#FC=gfortran\n#FFLAGS=-c --free-form -std=f2003 -O3\n\nFLFLAGS=\n\nMODFLAG := $(MODFLAG) -I ../../mod\n\n.PHONY: all mod test\n\nall: mod\n\nmod:\n\t#Build each sub module then build the module that depends on all sub modules\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_subsurface_grid_transform.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_subsurface_properties.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_subsurface_state.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_subsurface.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_subsurface_static_data.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_subsurface_output.F90\n\t$(COMPILER90) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) module_subsurface_input.F90\n\tar -r ../../lib/libHYDRO.a module_subsurface_grid_transform.o\n\tar -r ../../lib/libHYDRO.a module_subsurface_properties.o\n\tar -r ../../lib/libHYDRO.a module_subsurface_state.o\n\tar -r ../../lib/libHYDRO.a module_subsurface.o\n\tar -r ../../lib/libHYDRO.a module_subsurface_static_data.o\n\tar -r ../../lib/libHYDRO.a module_subsurface_output.o\n\tar -r ../../lib/libHYDRO.a module_subsurface_input.o\n\n\tcp *.mod ../../mod\ntest:\n\t$(COMPILER90) $(F90FLAGS) $(MODFLAG) subsurface_tests.F90\n\t$(COMPILER90) -o subsurface_tests \\\n\t\tmodule_subsurface_grid_transform.o \\\n\t\tmodule_subsurface_properties.o \\\n\t\tmodule_subsurface_state.o \\\n\t\tmodule_subsurface.o \\\n\t\t../Overland/module_overland.o \\\n\t\t../Overland/module_overland_control.o \\\n\t\t../Overland/module_overland_routing_properties.o \\\n\t\t../Overland/module_overland_mass_balance.o \\\n\t\t../Overland/module_overland_streams_and_lakes.o \\\n\t\t../Overland/module_subsurface_static_data.o \\\n\t\t../Overland/module_subsurface_output.o \\\n\t\t../Overland/module_subsurface_input.o \\\n\t\tsubsurface_tests.o\nclean:\n\trm -f *.o\n\trm -f *.mod\n\trm -f subsurface_tests\n"
  },
  {
    "path": "src/Routing/Subsurface/module_subsurface.F90",
    "content": "module module_subsurface_data\n\n    use module_subsurface_state\n    use module_subsurface_properties\n    use module_subsurface_grid_transform\n\n    ! included to allow properties to be shared between overland and subsurface code\n    use overland_data\n\n    implicit none\n\n    type subsurface_struct\n\n        type ( subsurface_state_interface), pointer :: state => null()\n        type ( subsurface_properties_interface), pointer :: properties => null()\n        type ( subsurface_grid_transform_interface), pointer :: grid_transform => null()\n\n        ! unused pointer are in an undefined state\n        ! this means the result of calling associated(<pointer>)\n        ! on a pointer that has not been set is unknown\n        ! therefore associated can not be used as a guard\n        ! in inital pointer allocation\n        logical, private :: pointer_allocation_guard = .false.\n\n        contains\n\n        procedure :: init => subsurface_struct_init\n        procedure :: destroy => subsurface_struct_destroy\n\n    end type subsurface_struct\n\n    contains\n\n    subroutine subsurface_struct_init(this,ix,jx,nsoil,overland_data)\n        implicit none\n        class(subsurface_struct), intent(inout) :: this ! the type object being initialized\n        integer, intent(in) :: ix                     ! x grid size\n        integer, intent(in) :: jx                     ! y grid size\n        integer, intent(in) :: nsoil                  ! number of soil layers\n        type(overland_struct), intent(inout) :: overland_data        ! overland data strucuture\n\n    if (this%pointer_allocation_guard .eqv. .false. ) then\n        this%pointer_allocation_guard = .true.\n        ! allocate the io interface\n        allocate( this%state )\n        if ( .not. associated( this%state) ) then\n            write(0,*) \"Failure to allocate subsurface io interface\"\n        else\n            !write(0,*) \"Allocating io structure\"\n            call this%state%init(ix,jx)\n        end if\n\n        ! allocate the properties interface\n        allocate( this%properties )\n        if ( .not. associated( this%properties) ) then\n            write(0,*) \"Failure to allocate subsurface io interface\"\n        else\n            !write(0,*) \"Allocating properties structure\"\n            call this%properties%init(ix,jx,nsoil,overland_data)\n        end if\n\n        ! allocate the grid_transfrom interface\n        allocate( this%grid_transform )\n        if ( .not. associated( this%grid_transform) ) then\n            write(0,*) \"Failure to allocate grid transform interface\"\n        else\n            !write(0,*) \"Allocating grid transform structure\"\n            call this%grid_transform%init(ix,jx,nsoil)\n        end if\n    else\n        write(0,*)  \"Attempt to double allocate subsurface_struct\"\n    end if\n\n    end subroutine subsurface_struct_init\n\n    subroutine subsurface_struct_destroy(this)\n        implicit none\n        class(subsurface_struct), intent(inout) :: this ! the type object being initialized\n\n        if ( this%pointer_allocation_guard .eqv. .true.) then\n            !write(0,*) \"Testing pointers for deallocation\"\n            if ( associated( this%state ) ) then\n                call this%state%destroy\n                deallocate( this%state )\n            end if\n\n            if (associated( this%properties ) )then\n                call this%properties%destroy\n                deallocate( this%properties )\n            end if\n\n            if (associated( this%grid_transform ) ) then\n                call this%grid_transform%destroy\n                deallocate( this%grid_transform )\n            end if\n\n            this%pointer_allocation_guard = .false.\n        else\n            write(0,*)  \"Attempt to double delete subsurface_struct\"\n        end if\n\n    end subroutine subsurface_struct_destroy\n\nend module module_subsurface_data\n"
  },
  {
    "path": "src/Routing/Subsurface/module_subsurface_grid_transform.F90",
    "content": "module module_subsurface_grid_transform\n    implicit none\n\n    type subsurface_grid_transform_interface\n\n        ! temp array? field capacity disaggregated to routing grid, for each soil layer\n        real, allocatable, dimension(:,:,:) :: smcrefrt\n\n        ! Soil Moisture Content -- ???\n        real, allocatable, dimension(:,:,:) :: smcrt\n\n        ! Soil Moisture Content -- ??? Porosity\n        real, allocatable, dimension(:,:,:) :: smcmaxrt\n\n        ! Soil Moisture Content -- ??? Wilting Point\n        real, allocatable, dimension(:,:,:) :: smcwltrt\n    contains\n        procedure :: init => subsurface_grid_transform_init\n        procedure :: destroy => subsurface_grid_transfrom_destroy\n    end type\n\n    contains\n\n    subroutine subsurface_grid_transform_init(this,ix,jx,nsoil)\n        implicit none\n        class(subsurface_grid_transform_interface), intent(inout) :: this ! the type object being initialized\n        integer, intent(in) :: ix                     ! x grid size\n        integer, intent(in) :: jx                     ! y grid size\n        integer, intent(in) :: nsoil                  ! number of soil layers\n\n        logical :: allocation_error = .false.\n\n        ! check allocation status of smcrefrt\n        if ( .not. allocated(this%smcrefrt) ) then\n            allocate( this%smcrefrt(ix,jx,nsoil) )\n            !no initialization on this variable?\n            !this%smcrefrt = 0.0\n        else\n            allocation_error = .true.\n        end if\n\n        ! check to see if smcrt is allocated\n        if ( .not. allocated(this%smcrt) ) then\n            allocate( this%smcrt(ix,jx,nsoil) )\n            this%smcrt = 0.0\n        else\n            allocation_error = .true.\n        end if\n\n        ! check to see if smcmaxrt is allocated\n        if ( .not. allocated(this%smcmaxrt) ) then\n            allocate( this%smcmaxrt(ix,jx,nsoil) )\n            this%smcmaxrt = 0.0\n        end if\n\n        ! check to see if smcwltrt is allocated\n        if ( .not. allocated(this%smcwltrt) ) then\n            allocate( this%smcwltrt(ix,jx,nsoil) )\n            this%smcwltrt = 0.0\n        else\n            allocation_error = .true.\n        end if\n\n        if ( allocation_error ) &\n            write(0,*) \"attempt to allocate data in members of subsurface grid transform structure&\n            &that where already allocated. The allocated members where not changed\"\n\n    end subroutine subsurface_grid_transform_init\n\n    subroutine subsurface_grid_transfrom_destroy(this)\n        implicit none\n        class(subsurface_grid_transform_interface), intent(inout) :: this ! the type object being initialized\n\n        logical :: allocation_error = .false.\n\n        ! check allocation status of smcrefrt\n        if ( allocated(this%smcrefrt) ) then\n            deallocate( this%smcrefrt )\n        else\n            allocation_error = .true.\n        end if\n\n        ! check to see if smcrt is allocated\n        if ( allocated(this%smcrt) ) then\n            deallocate( this%smcrt )\n        else\n            allocation_error = .true.\n        end if\n\n        ! check to see if smcmaxrt is allocated\n        if ( allocated(this%smcmaxrt) ) then\n            deallocate( this%smcmaxrt )\n        else\n            allocation_error = .true.\n        end if\n\n        ! check to see if smcwltrt is allocated\n        if ( allocated(this%smcwltrt) ) then\n            deallocate( this%smcwltrt )\n        else\n            allocation_error = .true.\n        end if\n\n        if ( allocation_error ) &\n            write(0,*) \"attempt to deallocate data in members of subsurface grid transform structure&\n            &that where not allocated. The unallocated members where not changed\"\n\n    end subroutine\n\nend module module_subsurface_grid_transform\n"
  },
  {
    "path": "src/Routing/Subsurface/module_subsurface_input.F90",
    "content": "module module_subsurface_input\n    implicit none\n\n    type subsurface_input_interface\n\n        ! infiltration excess from the land surface model (mm) on the routing grid\n        real, pointer, dimension(:,:) :: infiltration_excess\n    contains\n        procedure :: init => subsurface_input_init\n        procedure :: destroy => subsurface_input_destroy\n    end type subsurface_input_interface\n\n    contains\n\n    subroutine subsurface_input_init(this, ix, jx, infiltration_excess)\n        implicit none\n        class(subsurface_input_interface), intent(inout) :: this ! the type object being initialized\n        integer, intent(in) :: ix                     ! x grid size\n        integer, intent(in) :: jx                     ! y grid size\n        real, pointer, dimension(:,:) :: infiltration_excess\n\n        this%infiltration_excess => infiltration_excess\n\n    end subroutine subsurface_input_init\n\n    subroutine subsurface_input_destroy(this)\n        implicit none\n        class(subsurface_input_interface), intent(inout) :: this ! the type object being initialized\n\n    end subroutine subsurface_input_destroy\n\nend module module_subsurface_input\n"
  },
  {
    "path": "src/Routing/Subsurface/module_subsurface_output.F90",
    "content": "module module_subsurface_output\n    implicit none\n\n    type subsurface_output_interface\n\n        ! infiltration excess from the land surface model (mm) on the routing grid\n        real, pointer, dimension(:,:) :: infiltration_excess\n    contains\n        procedure :: init => subsurface_output_init\n        procedure :: destroy => subsurface_output_destroy\n    end type subsurface_output_interface\n\n    contains\n\n    subroutine subsurface_output_init(this, ix, jx, infiltration_excess)\n        implicit none\n        class(subsurface_output_interface), intent(inout) :: this ! the type object being initialized\n        integer, intent(in) :: ix                     ! x grid size\n        integer, intent(in) :: jx                     ! y grid size\n        real, pointer, dimension(:,:) :: infiltration_excess\n\n        this%infiltration_excess => infiltration_excess                   ! y grid size\n\n    end subroutine subsurface_output_init\n\n    subroutine subsurface_output_destroy(this)\n        implicit none\n        class(subsurface_output_interface), intent(inout) :: this ! the type object being initialized\n\n    end subroutine subsurface_output_destroy\n\nend module module_subsurface_output\n"
  },
  {
    "path": "src/Routing/Subsurface/module_subsurface_properties.F90",
    "content": "module module_subsurface_properties\n    use overland_data\n    implicit none\n\n    type subsurface_properties_interface\n        ! disaggregated lateral hydraulic conductivity, on the routing grid, with adjustment factor applied (Noah_distr_routing.F: 2641*) LKSAT*LKSATFAC*[0..1]\n        real, allocatable, dimension(:,:) :: lksatrt\n\n        ! water table depth (meters) (module_HYDRO_io.F: 1962*)\n        real, allocatable, dimension(:,:) :: zwattablrt\n\n        ! soil depth on routing grid\n        real, allocatable, dimension(:,:) :: soldeprt\n\n        !soil depth by layer\n        real, allocatable, dimension(:) :: sldpth\n\n        ! need info\n        real, dimension(100) :: zsoil\n\n        ! shared properties -- the following variables are shared from overland properties module\n\n        ! terrian slope in the x direction (m/m)\n        real, pointer, dimension(:,:) :: surface_slope_x => null()\n\n        ! terrian slope in the y direction (m/m)\n        real, pointer, dimension(:,:) :: surface_slope_y => null()\n\n        ! terrain surface slope in 8 ordinal directions (m/m)                                                                  !\n        ! TODO verify this correct, check with Wei?\n        !                      1\n        !                      |\n        !                  8       2\n        !                    \\   /\n        !                 7__     __ 3\n        !\n        !                    /   \\\n        !                   6     4\n        !                      |\n        !                      5\n        !\n        real, pointer, dimension(:,:,:) :: surface_slope => null()\n\n        ! index of neighboring cell in the direction of steepest terrain surface slope, used with surface_slope\n        integer, pointer, dimension(:,:,:) :: max_surface_slope_index => null()\n\n        ! centerpoint distance to each neighbor (m)\n        real, pointer, dimension(:,:,:) :: distance_to_neighbor => null()\n\n        ! disaggregated lksat decay exponent\n        real, allocatable, dimension(:,:) :: nexprt\n\n    contains\n\n        procedure :: init => subsurface_properties_init\n        procedure :: destroy => subsurface_properties_destroy\n    end type subsurface_properties_interface\n\ncontains\n\n    subroutine subsurface_properties_init(this,ix,jx,nsoil,overland_data)\n        implicit none\n        class(subsurface_properties_interface), intent(inout) :: this ! the type object being initalized\n        integer, intent(in) :: ix                     ! x grid size\n        integer, intent(in) :: jx                     ! y grid size\n        integer, intent(in) :: nsoil                  ! number of soil layers\n        class(overland_struct), intent(inout) :: overland_data\n\n        logical :: allocation_error = .false.\n\n        ! allocate the array only if not already allocated\n        if ( .not. allocated(this%lksatrt) ) then\n            allocate( this%lksatrt(ix,jx) )\n            this%lksatrt = 0.0\n        else\n            allocation_error = .true.\n        end if\n\n        ! allocate the array only if not already allocated\n        if ( .not. allocated(this%zwattablrt) ) then\n            allocate( this%zwattablrt(ix,jx) )\n            this%zwattablrt = 0.0\n        else\n            allocation_error = .true.\n        end if\n\n        ! allocate the array only if not already allocated\n        if ( .not. allocated(this%soldeprt) ) then\n            allocate( this%soldeprt(ix,jx) )\n            this%soldeprt = 0.0\n        else\n            allocation_error = .true.\n        end if\n\n        !allocate storage for sldpth\n        if ( .not. allocated(this%sldpth) ) then\n            allocate( this%sldpth(nsoil) )\n            this%sldpth = 0.0\n        else\n            allocation_error = .true.\n        endif\n\n        this%zsoil = 0.0\n\n        ! now initalize the shared properties from overland data\n\n        if ( associated(overland_data%properties%surface_slope_x) ) then\n            this%surface_slope_x => overland_data%properties%surface_slope_x\n        else\n            allocation_error = .true.\n        end if\n\n        if ( associated(overland_data%properties%surface_slope_y) ) then\n            this%surface_slope_y => overland_data%properties%surface_slope_y\n        else\n            allocation_error = .true.\n        end if\n\n        if ( associated(overland_data%properties%surface_slope) ) then\n            this%surface_slope => overland_data%properties%surface_slope\n        else\n            allocation_error = .true.\n        end if\n\n        if ( associated(overland_data%properties%max_surface_slope_index) ) then\n            this%max_surface_slope_index => overland_data%properties%max_surface_slope_index\n        else\n            allocation_error = .true.\n        end if\n\n        if ( associated(overland_data%properties%distance_to_neighbor) ) then\n            this%distance_to_neighbor => overland_data%properties%distance_to_neighbor\n        else\n            allocation_error = .true.\n        end if\n\n        ! allocate the array only if not already allocated\n        if ( .not. allocated(this%nexprt) ) then\n            allocate( this%nexprt(ix,jx) )\n            this%nexprt = 1.0\n        else\n            allocation_error = .true.\n        end if\n\n        if ( allocation_error ) &\n            write(0,*) \"attempt to allocate data in members of subsurface properties structure&\n            &that where already allocated. The allocated members where not changed\"\n\n    end subroutine subsurface_properties_init\n\n    subroutine subsurface_properties_destroy(this)\n        implicit none\n        class(subsurface_properties_interface), intent(inout) :: this ! the type object being destroyed\n\n        logical :: allocation_error = .false.\n\n        ! only deallocated if already allocated\n        if ( allocated(this%lksatrt) ) then\n            deallocate( this%lksatrt)\n        else\n            allocation_error = .true.\n        end if\n\n        ! only deallocated if already allocated\n        if ( allocated(this%zwattablrt) ) then\n            deallocate( this%zwattablrt)\n        else\n            allocation_error = .true.\n        end if\n\n        ! only deallocated if already allocated\n        if ( allocated(this%soldeprt) ) then\n            deallocate( this%soldeprt)\n        else\n            allocation_error = .true.\n        end if\n\n        ! only deallocated if already allocated\n        if ( allocated(this%sldpth) ) then\n            deallocate( this%sldpth)\n        else\n            allocation_error = .true.\n        end if\n\n\n        ! now release the shared properties from overland data\n\n        if ( associated(this%surface_slope_x) ) then\n            this%surface_slope_x => null()\n        else\n            allocation_error = .true.\n        end if\n\n        if ( associated(this%surface_slope_y) ) then\n            this%surface_slope_y => null()\n        else\n            allocation_error = .true.\n        end if\n\n        if ( associated(this%surface_slope) ) then\n            this%surface_slope => null()\n        else\n            allocation_error = .true.\n        end if\n\n        if ( associated(this%max_surface_slope_index) ) then\n            this%max_surface_slope_index => null()\n        else\n            allocation_error = .true.\n        end if\n\n        if ( associated(this%distance_to_neighbor) ) then\n            this%distance_to_neighbor => null()\n        else\n            allocation_error = .true.\n        end if\n\n        ! only deallocated if already allocated\n        if ( allocated(this%nexprt) ) then\n            deallocate( this%nexprt)\n        else\n            allocation_error = .true.\n        end if\n\n        if ( allocation_error ) &\n            write(0,*) \"attempt to deallocate data in members of subsurface properties structure&\n            &that where not allocated. The unallocated members where not changed\"\n\n    end subroutine subsurface_properties_destroy\n\nend module module_subsurface_properties\n"
  },
  {
    "path": "src/Routing/Subsurface/module_subsurface_state.F90",
    "content": "module module_subsurface_state\n    implicit none\n\n    type subsurface_state_interface\n        ! total flow from boundary cells to outside of domain; on routing grid\n        real :: qsubbdrytrt\n\n        ! subsurface flow (m^3/s)\n        real, allocatable, dimension(:,:) :: qsubrt\n\n        ! flow from boundary cells to outside of domain on routing grid\n        real, allocatable, dimension(:,:) :: qsubbdryrt\n    contains\n        procedure :: init => subsurface_state_init\n        procedure :: destroy => subsurface_state_destroy\n    end type subsurface_state_interface\n\n    contains\n\n    subroutine subsurface_state_init(this, ix, jx)\n        implicit none\n        class(subsurface_state_interface), intent(inout) :: this ! the type object being initialized\n        integer, intent(in) :: ix                     ! x grid size\n        integer, intent(in) :: jx                     ! y grid size\n\n        logical :: allocation_error = .false.\n\n        this%qsubbdrytrt = 0.0\n\n        if ( .not. allocated(this%qsubrt) ) then\n            allocate( this%qsubrt(ix,jx) )\n            this%qsubrt = 0.0\n        else\n            allocation_error = .true.\n        end if\n\n        if ( .not. allocated(this%qsubbdryrt) ) then\n            allocate( this%qsubbdryrt(ix,jx) )\n            this%qsubbdryrt = 0.0\n        else\n            allocation_error = .true.\n        end if\n\n        if ( allocation_error ) &\n            write(0,*) \"attempt to allocate data in members of subsurface io structure&\n            &that where already allocated. The allocated members where not changed\"\n\n    end subroutine subsurface_state_init\n\n    subroutine subsurface_state_destroy(this)\n        implicit none\n        class(subsurface_state_interface), intent(inout) :: this ! the type object being initialized\n\n        logical :: allocation_error = .false.\n\n        if ( allocated(this%qsubrt) ) then\n            deallocate( this%qsubrt )\n        else\n            allocation_error = .true.\n        end if\n\n        if ( allocated(this%qsubbdryrt) ) then\n            deallocate( this%qsubbdryrt )\n        else\n            allocation_error = .true.\n        end if\n\n        if ( allocation_error ) &\n            write(0,*) \"attempt to deallocate data in members of subsurface io structure&\n            &that where not allocated. The unallocated members where not changed\"\n\n    end subroutine subsurface_state_destroy\n\nend module module_subsurface_state\n"
  },
  {
    "path": "src/Routing/Subsurface/module_subsurface_static_data.F90",
    "content": "module module_subsurface_static_data\n    implicit none\n\n    type subsurface_static_interface\n\n    integer :: ixrt\n    integer :: jxrt\n    integer :: nsoil\n    real :: dt\n    integer :: rt_option\n\n    contains\n        procedure :: init => subsurface_static_data_init\n        procedure :: destroy => subsurface_static_data_destroy\n    end type subsurface_static_interface\n\n    contains\n\n    subroutine subsurface_static_data_init(this, ixrt, jxrt, nsoil, dt, rt_option)\n        implicit none\n        class(subsurface_static_interface), intent(inout) :: this ! the type object being initialized\n        integer, intent(in) :: ixrt                     ! x routing grid size\n        integer, intent(in) :: jxrt                     ! y routing grid size\n        integer, intent(in) :: nsoil                    ! nsoil\n        real, intent(in) :: dt\n        integer, intent(in) :: rt_option\n\n        logical :: allocation_error = .false.\n\n        this%ixrt = ixrt\n        this%jxrt = jxrt\n        this%nsoil = nsoil\n        this%dt = dt\n        this%rt_option = rt_option\n\n        if ( allocation_error ) &\n            write(0,*) \"attempt to allocate data in members of subsurface io structure&\n            &that where already allocated. The allocated members where not changed\"\n\n    end subroutine subsurface_static_data_init\n\n    subroutine subsurface_static_data_destroy(this)\n        implicit none\n        class(subsurface_static_interface), intent(inout) :: this ! the type object being initialized\n\n        logical :: allocation_error = .false.\n\n        if ( allocation_error ) &\n            write(0,*) \"attempt to deallocate data in members of subsurface io structure&\n            &that where not allocated. The unallocated members where not changed\"\n\n    end subroutine subsurface_static_data_destroy\n\nend module module_subsurface_static_data\n"
  },
  {
    "path": "src/Routing/Subsurface/subsurface_tests.F90",
    "content": "\nprogram subsurface_tests\n    use module_subsurface_data\n\n    implicit none\n\n    logical rv\n\n    write(6,*) \"Running Test 1\"\n    write(6,*) \"Test that the allocation and deallocation functions work correctly\"\n    rv = init_delete_test(100,100,5)\n    write(6,*) \"Test Complete\"\n\n    write(6,*) \"Running Test 2\"\n    write(6,*) \"Test Scaling\"\n    rv = scale_tests()\n    write(6,*) \"Test Complete\"\n\n    write(6,*) \"Running Test 3\"\n    write(6,*) \"Testing Double Delete\"\n    rv = double_delete_test()\n    write(6,*) \"Test Complete\"\n\n    write(6,*) \"Running Test 4\"\n    write(6,*) \"Testing Double Init\"\n    rv = double_init_test()\n    write(6,*) \"Test Complete\"\n    contains\n\n    function init_delete_test(ix,jx,nsoil) result(rv)\n        use module_subsurface_data\n        use overland_data\n\n        implicit none\n\n        integer, intent(in) :: ix ! horizontal resolution\n        integer, intent(in) :: jx ! vertical resolution\n        integer, intent(in) :: nsoil ! number of soil layers\n        logical :: rv ! test result\n\n        logical :: status_val = .true.\n\n        type (subsurface_struct) :: subsurface_data\n        type (overland_struct) :: ov_data\n\n        ! end of variable declarations\n\n        write(0,*) \"ix = \", ix\n        write(0,*) \"jx = \", jx\n        write(0,*) \"nsoil = \", nsoil\n\n        call ov_data%init(ix,jx,ix,jx)\n        call subsurface_data%init(ix,jx,nsoil,ov_data)\n\n        ! check to see that io was allocated\n        if ( associated(subsurface_data%io) ) then\n            write(6,*) \"io type was associated\"\n        else\n            write(6,*) \"io type was not associated\"\n            status_val = .false.\n        end if\n\n        ! check to see that properties was allocated\n        if ( associated(subsurface_data%properties) ) then\n            write(6,*) \"properties type was associated\"\n        else\n            write(6,*) \"properties type was not associated\"\n            status_val = .false.\n        end if\n\n        ! check to see that grid transform was allocated\n        if ( associated(subsurface_data%grid_transform) ) then\n            write(6,*) \"grid_transfrom type was associated\"\n        else\n            write(6,*) \"grid_transfrom type was not associated\"\n            status_val = .false.\n        end if\n\n        call subsurface_data%destroy\n\n         ! check to see that io was deallocated\n        if ( .not. associated(subsurface_data%io) ) then\n            write(6,*) \"io type was disassociated\"\n        else\n            write(6,*) \"io type was not disassociated\"\n            status_val = .false.\n        end if\n\n        ! check to see that properties was allocated\n        if ( .not. associated(subsurface_data%properties) ) then\n            write(6,*) \"properties type was disassociated\"\n        else\n            write(6,*) \"properties type was not disassociated\"\n            status_val = .false.\n        end if\n\n        ! check to see that grid transform was allocated\n        if ( .not. associated(subsurface_data%grid_transform) ) then\n            write(6,*) \"grid_transfrom type was disassociated\"\n        else\n            write(6,*) \"grid_transfrom type was not disassociated\"\n            status_val = .false.\n        end if\n\n        ! write final test results\n        if ( status_val ) then\n            write(6,*) \"Test Passed\"\n        else\n            write(6,*) \"Test Failed\"\n        end if\n\n        rv = status_val\n\n    end function init_delete_test\n\n    function scale_tests() result(rv)\n        logical :: rv\n\n        logical, dimension(4) :: results\n        results = .false.\n\n        write(6,*) \"Running Test for (10,10,5)\"\n        results(1) = init_delete_test(10,10,5)\n        write(6,*) \"Running Test for (100,100,5)\"\n        results(2) = init_delete_test(100,100,5)\n        write(6,*) \"Running Test for (1000,1000)\"\n        results(3) = init_delete_test(1000,1000,5)\n        write(6,*) \"Running Test for (5000,5000,5)\"\n        results(4) = init_delete_test(5000,5000,5)\n\n        if ( all(results) ) then\n            rv = .true.\n            write(6,*) \"All Sub-Test Passed\"\n        else\n            rv = .false.\n            write(6,*) \"At Least One Sub-Test Failed\"\n        end if\n\n    end function scale_tests\n\n    function double_delete_test() result(rv)\n        logical :: rv\n\n        type (subsurface_struct) :: subsurface_data\n        type (overland_struct) :: ov_data\n\n        call ov_data%init(100,100,100,100)\n        call subsurface_data%init(100,100,5,ov_data)\n        call subsurface_data%destroy\n        call subsurface_data%destroy\n\n        rv = .true.\n\n    end function double_delete_test\n\n    function double_init_test() result(rv)\n        logical :: rv\n\n        type (subsurface_struct) :: subsurface_data\n        type (overland_struct) :: ov_data\n\n        call ov_data%init(100,100,100,100)\n        call subsurface_data%init(100,100,5,ov_data)\n        call subsurface_data%init(100,100,5,ov_data)\n        call subsurface_data%destroy\n\n        rv = .true.\n\n    end function double_init_test\n\nend program\n"
  },
  {
    "path": "src/Routing/module_GW_baseflow.F90",
    "content": "module module_GW_baseflow\n\n!   use overland_data\n#ifdef MPP_LAND\n   use module_mpp_land\n   use MODULE_mpp_GWBUCKET, only: gw_sum_real, gw_write_io_real\n   use MODULE_mpp_ReachLS, only : updatelinkv\n#endif\n   use iso_fortran_env, only: int64\n   implicit none\n\n!#include \"rt_include.inc\"\n!yw #include \"namelist.inc\"\ncontains\n\n!------------------------------------------------------------------------------\n!DJG   Simple GW Bucket Model\n!      for NHDPLUS mapping\n!------------------------------------------------------------------------------\n\n   subroutine simp_gw_buck_nhd(           &\n        ix,            jx,                &\n        ixrt,          jxrt,              &\n        numbasns,      AGGFACTRT,         &\n        DT,            INFXSWGT,          &\n        runoff1x_in,   runoff2x_in,       &\n        cellArea,      area_lsm,          &\n        c,             ex,                &\n        loss_fraction,                    &\n        z_mx,          z_gwsubbas_tmp,    &\n        qout_gwsubbas, qin_gwsubbas,      &\n        qloss_gwsubbas,                   &\n        GWBASESWCRT,   OVRTSWCRT,         &\n        LNLINKSL,                         &\n        basns_area,                       &\n        nhdBuckMask,   bucket_loss,       &\n        channelBucket_only )\n\n   use module_UDMAP, only: LNUMRSL, LUDRSL\n\n   implicit none\n\n!!!Declarations...\n   integer, intent(in)                               :: ix,jx,ixrt,jxrt\n   integer, intent(in)                               :: numbasns, lnlinksl\n   real, intent(in), dimension(ix,jx)                :: runoff2x_in\n   real, dimension(ixrt,jxrt)                            :: runoff2x , runoff1x\n   real, intent(in), dimension(ix,jx)                :: runoff1x_in, area_lsm\n   real, intent(in)                                  :: cellArea(ixrt,jxrt),DT\n   real, intent(in),dimension(numbasns)              :: C,ex,loss_fraction\n   real, intent(inout),dimension(numbasns)              :: z_mx\n   real, intent(out),dimension(numbasns)             :: qout_gwsubbas\n   !! intent inout for channelBucket_only .eq. 1\n   real, intent(inout),dimension(numbasns)           :: qin_gwsubbas\n   real, intent(out),dimension(numbasns)             :: qloss_gwsubbas\n   real*8                                            :: z_gwsubbas(numbasns)\n   real                                              :: qout_max, qout_spill, z_gw_spill\n   real, intent(inout),dimension(:)                  :: z_gwsubbas_tmp\n   real, intent(in),dimension(ixrt,jxrt)             :: INFXSWGT\n   integer, intent(in)                               :: GWBASESWCRT\n   integer, intent(in)                               :: OVRTSWCRT\n   real, intent(in), dimension(numbasns)             :: basns_area\n   integer, intent(in)                               :: channelBucket_only\n   integer, intent(in)                               :: bucket_loss\n\n   real, dimension(numbasns)                         :: net_perc\n   integer, dimension(numbasns)                      :: nhdBuckMask\n\n   integer                                           :: i,j,bas, k, m, ii,jj\n\n   integer :: AGGFACYRT, AGGFACTRT, AGGFACXRT, IXXRT, JYYRT\n   real*8,  dimension(LNLINKSL) :: LQLateral\n\n   real, parameter :: one         = 1.000000000000000\n   real, parameter :: m_to_mm     = 1000.000000000000\n   real, parameter :: mm_to_m     = one/m_to_mm\n   real, parameter :: sqm_to_sqkm = one/1000000.0000000000\n\n\n!!!Initialize variables...\n   net_perc = 0.\n   qout_gwsubbas = 0.\n   if (bucket_loss .eq. 1) then\n      qloss_gwsubbas = 0.\n   endif\n   z_gwsubbas(1:numbasns) = z_gwsubbas_tmp(1:numbasns)\n\n   if(channelBucket_only .eq. 0) then\n\n      !! Initialize if not passed in\n      qin_gwsubbas = 0.\n\n!Assign local value of runoff2 (drainage) for flux caluclation to buckets...\n\n        do J=1,JX\n        do I=1,IX\n             do AGGFACYRT=AGGFACTRT-1,0,-1\n             do AGGFACXRT=AGGFACTRT-1,0,-1\n               IXXRT=I*AGGFACTRT-AGGFACXRT\n               JYYRT=J*AGGFACTRT-AGGFACYRT\n#ifdef MPP_LAND\n       if(left_id.ge.0) IXXRT=IXXRT+1\n       if(down_id.ge.0) JYYRT=JYYRT+1\n!              if(AGGFACTRT .eq. 1) then\n!                  IXXRT=I\n!                  JYYRT=J\n!             endif\n#endif\n!DJG Implement subgrid weighting routine...\n               if( (runoff1x_in(i,j) .lt. 0) .or. (runoff1x_in(i,j) .gt. 1000) ) then\n                    runoff1x(IXXRT,JYYRT) = 0\n               else\n                    runoff1x(IXXRT,JYYRT)=runoff1x_in(i,j)*area_lsm(I,J)     &\n                        *INFXSWGT(IXXRT,JYYRT)/cellArea(IXXRT,JYYRT)\n               endif\n\n               if( (runoff2x_in(i,j) .lt. 0) .or. (runoff2x_in(i,j) .gt. 1000) ) then\n                    runoff2x(IXXRT,JYYRT) = 0\n               else\n                  runoff2x(IXXRT,JYYRT)=runoff2x_in(i,j)*area_lsm(I,J)     &\n                      *INFXSWGT(IXXRT,JYYRT)/cellArea(IXXRT,JYYRT)\n               endif\n             enddo\n             enddo\n        enddo\n        enddo\n\n\n       LQLateral = 0\n       do k = 1, LNUMRSL\n              ! get from land grid runoff\n               do m = 1, LUDRSL(k)%ncell\n                   ii =  LUDRSL(k)%cell_i(m)\n                   jj =  LUDRSL(k)%cell_j(m)\n                   if(ii .gt. 0 .and. jj .gt. 0) then\n                           LQLateral(k) = LQLateral(k)+runoff2x(ii,jj)*LUDRSL(k)%cellWeight(m) * mm_to_m &\n                               *cellArea(ii,jj)\n                   endif\n               end do\n       end do\n\n\n#ifdef MPP_LAND\n       call updateLinkV(LQLateral, net_perc)      ! m^3\n\n#else\n       net_perc = LQLateral        ! m^3\n#endif\n\n    endif !! if channelBucket_only .eq. 0 else\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!Loop through GW basins to adjust for inflow/outflow\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n\n   DO bas=1,numbasns     ! Loop for GW bucket calcs...\n      if(nhdBuckMask(bas) .eq. 1) then     ! if the basn is masked\n\n         if(channelBucket_only .eq. 0) then\n            !! If not using channelBucket_only, save qin_gwsubbas\n            qin_gwsubbas(bas) = net_perc(bas)             !units (m^3)\n         else\n            !! If using channelBucket_only, get net_perc from the passed qin_gwsubbas\n            net_perc(bas)     = qin_gwsubbas(bas)         !units (m^3)\n         end if\n\n         ! !Adjust level of GW depth...(conceptual GW bucket units (mm))\n         z_gwsubbas(bas) = z_gwsubbas(bas) + net_perc(bas) / basns_area(bas)   ! m\n\n         ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n         !Calculate baseflow as a function of GW bucket depth...\n         ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n         if( (GWBASESWCRT.eq.1) .or. (GWBASESWCRT.eq.4) ) then  !active bucket model\n\n            !DJG...Estimation of bucket 'overflow' (qout_spill) if/when bucket gets filled...\n            qout_spill = 0.\n            z_gw_spill = 0.\n\n            !!DJG...convert z_mx to millimeters...for v2 and later...\n            !yw  added by Wei Yu...If block is to accomodate old parameter file...\n            !                    if(z_mx(bas) .gt. 5) then\n            !                         z_mx(bas) = z_mx(bas) * mm_to_m    ! change from mm to meters\n            !                    endif\n\n               if (z_gwsubbas(bas).gt.z_mx(bas) * mm_to_m) then  !If/then for bucket overflow case...\n\n                    z_gw_spill = z_gwsubbas(bas) - z_mx(bas) * mm_to_m    ! meters\n                    z_gwsubbas(bas) = z_mx(bas) * mm_to_m    ! meters\n\n               else\n                      z_gw_spill = 0.\n               end if   ! End if for bucket overflow case...\n\n               qout_spill = z_gw_spill*(basns_area(bas))/DT  !amount spilled from bucket overflow...units (m^3/s)\n\n!DJG...Maximum estimation of bucket outlfow that is limited by total quantity in bucket...\n               qout_max = z_gwsubbas(bas)*(basns_area(bas))/DT   ! (m^3/s)   ! Estimate max bucket disharge limit to total volume in bucket...(m^3/s)\n\n\n! Assume exponential relation between z/zmax and Q...\n!DJG force asymptote to zero to prevent 'overdraft'...\n               if(GWBASESWCRT.eq.1) then ! Exponential model\n                   qout_gwsubbas(bas) = C(bas)*(exp(ex(bas)*z_gwsubbas(bas)/(z_mx(bas) * mm_to_m))-1) ! q_out (m^3/s)\n\n               elseif(GWBASESWCRT.eq.4) then ! Updated exponential model normalized by area\n                   qout_gwsubbas(bas) = C(bas)*(basns_area(bas)*sqm_to_sqkm)*(exp(ex(bas)*z_gwsubbas(bas)/(z_mx(bas)*mm_to_m))-1) ! q_out (m^3/s)\n\n               end if\n\n!DJG...Calculation of max bucket outlfow that is limited by total quantity in bucket...\n               qout_gwsubbas(bas) = MIN(qout_max,qout_gwsubbas(bas))   ! Limit bucket discharge to max. bucket limit   (m^3/s)\n\n               if (bucket_loss .eq. 1) then\n                    qloss_gwsubbas(bas) = qout_gwsubbas(bas)*loss_fraction(bas)\n                    qout_gwsubbas(bas) = qout_gwsubbas(bas)-qloss_gwsubbas(bas)\n               endif\n\n          elseif (GWBASESWCRT.eq.2) then  !Pass through/steady-state bucket\n\n! Assuming a steady-state (inflow=outflow) model...\n!DJG convert input and output units to cms...       qout_gwsubbas(bas) = qin_gwsubbas(bas)  !steady-state model...(m^3)\n               qout_gwsubbas(bas) = qin_gwsubbas(bas)/DT  !steady-state model...(m^3/s)\n\n          end if    ! End if for bucket model discharge type....\n\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!Adjust level of GW depth in bucket...\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n          if (bucket_loss .eq. 1) then\n             z_gwsubbas(bas) = z_gwsubbas(bas) - (qout_gwsubbas(bas)+qloss_gwsubbas(bas))*DT/( basns_area(bas) )   ! units (meters)\n          else\n             z_gwsubbas(bas) = z_gwsubbas(bas) - (qout_gwsubbas(bas))*DT/( basns_area(bas) )   ! units (meters)\n          endif\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!Combine calculated bucket discharge and amount spilled from bucket...\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n          qout_gwsubbas(bas) = qout_gwsubbas(bas) + qout_spill   ! units (m^3/s)\n      else\n          qout_gwsubbas(bas) = 0.0\n      endif   ! the basns is masked\n\n\n   END DO                 ! End loop for GW bucket calcs...\n\n   z_gwsubbas_tmp(1:numbasns) = z_gwsubbas(1:numbasns)     ! units (meters)\n\n\n!------------------------------------------------------------------------------\n   End subroutine simp_gw_buck_nhd\n!------------------------------------------------------------------------------\n!------------------------------------------------------------------------------\n!DJG   Simple GW Bucket Model\n!------------------------------------------------------------------------------\n\n   subroutine simp_gw_buck(ix,jx,ixrt,jxrt,numbasns,gnumbasns,basns_area,basnsInd,gw_strm_msk_lind,&\n                            gwsubbasmsk, runoff1x_in, runoff2x_in, z_gwsubbas_tmp, qin_gwsubbas,&\n                            qout_gwsubbas,qinflowbase,gw_strm_msk,gwbas_pix_ct,dist,DT,&\n                            C,ex,z_mx,GWBASESWCRT,OVRTSWCRT)\n   implicit none\n\n!!!Declarations...\n   integer, intent(in)                               :: ix,jx,ixrt,jxrt\n   integer, intent(in)                               :: numbasns, gnumbasns\n   integer, intent(in), dimension(ix,jx)             :: gwsubbasmsk\n   real, intent(in), dimension(ix,jx)                :: runoff2x_in\n   real, dimension(ix,jx)                            :: runoff2x\n   real, intent(in), dimension(ix,jx)                :: runoff1x_in\n   real, dimension(ix,jx)                            :: runoff1x\n   real, intent(in)                                  :: basns_area(numbasns),dist(ixrt,jxrt,9),DT\n   integer(kind=int64), intent(in)                   :: basnsInd(numbasns)\n   real, intent(in),dimension(numbasns)              :: C,ex,z_mx\n   real, intent(out),dimension(numbasns)             :: qout_gwsubbas\n   real, intent(out),dimension(numbasns)             :: qin_gwsubbas\n   real, dimension(numbasns)                         :: qin_gwsubbas_surf\n   real*8                                            :: z_gwsubbas(numbasns)\n   real                                              :: qout_max, qout_spill, z_gw_spill\n   real, intent(inout),dimension(numbasns)           :: z_gwsubbas_tmp\n   real, intent(out),dimension(ixrt,jxrt)            :: qinflowbase\n   integer, intent(in),dimension(ixrt,jxrt)          :: gw_strm_msk, gw_strm_msk_lind\n   integer, intent(in)                               :: GWBASESWCRT\n   integer, intent(in)                               :: OVRTSWCRT\n\n\n   real*8, dimension(numbasns)                      :: sum_perc8, ct_bas8, sum_perc8_surf\n   real, dimension(numbasns)                        :: sum_perc, sum_perc_surf\n   real, dimension(numbasns)                        :: net_perc, net_perc_surf\n\n   real, dimension(numbasns)                        :: ct_bas\n   real, dimension(numbasns)                        :: gwbas_pix_ct\n   integer                                          :: i,j,bas, k\n   character(len=19)\t\t\t\t    :: header\n   character(len=1)\t\t\t\t    :: jnk\n\n\n!!!Initialize variables...\n   ct_bas8 = 0\n   sum_perc8 = 0.\n   sum_perc8_surf = 0.\n   net_perc = 0.\n   net_perc_surf = 0.\n   qout_gwsubbas = 0.\n   qin_gwsubbas = 0.\n   qin_gwsubbas_surf = 0.\n   z_gwsubbas = z_gwsubbas_tmp\n\n!Assign local value of runoff2 (drainage) for flux caluclation to buckets...\n   runoff2x = runoff2x_in\n   runoff1x = runoff1x_in\n\n\n\n\n!!!Calculate aggregated percolation from deep runoff into GW basins...\n   do i=1,ix\n     do j=1,jx\n\n!!DJG 4/15/2015...reset runoff2x, runoff1x, values to 0 where extreme values exist...(<0 or\n!> 1000)\n       if((runoff2x(i,j).lt.0.).OR.(runoff2x(i,j).gt.1000.)) then\n         runoff2x(i,j)=0.\n       end if\n       if((runoff1x(i,j).lt.0.).OR.(runoff1x(i,j).gt.1000.)) then\n         runoff1x(i,j)=0.\n       end if\n\n       do bas=1,numbasns\n         if(gwsubbasmsk(i,j).eq.basnsInd(bas) ) then\n           !ADCHANGE: Separate surface input from subsurface\n           if(OVRTSWCRT.eq.0) then\n             sum_perc8_surf(bas) = sum_perc8_surf(bas)+runoff1x(i,j)\n           end if\n           sum_perc8(bas) = sum_perc8(bas)+runoff2x(i,j)  !Add only drainage to bucket...runoff2x in (mm)\n           ct_bas8(bas) = ct_bas8(bas) + 1\n         end if\n       end do\n     end do\n   end do\n\n#ifdef MPP_LAND\n    call gw_sum_real(sum_perc8,numbasns,gnumbasns,basnsInd)\n    call gw_sum_real(sum_perc8_surf,numbasns,gnumbasns,basnsInd)\n    call gw_sum_real(ct_bas8,numbasns,gnumbasns,basnsInd)\n#endif\n   sum_perc = sum_perc8\n   sum_perc_surf = sum_perc8_surf\n   ct_bas = ct_bas8\n\n\n\n\n!!!Loop through GW basins to adjust for inflow/outflow\n\n   DO bas=1,numbasns     ! Loop for GW bucket calcs...\n! #ifdef MPP_LAND\n!      if(ct_bas(bas) .gt. 0) then\n! #endif\n\n     net_perc(bas) = sum_perc(bas) / ct_bas(bas)   !units (mm)\n!DJG...old change to cms     qin_gwsubbas(bas) = net_perc(bas)/1000. * ct_bas(bas) * basns_area(bas) !units (m^3)\n     qin_gwsubbas(bas) = net_perc(bas)/1000.* &\n                         ct_bas(bas)*basns_area(bas)/DT    !units (m^3/s)\n\n!ADCHANGE: Separate tracking for surface runoff term to push straight to pass-through\n     net_perc_surf(bas) = sum_perc_surf(bas) / ct_bas(bas)   !units (mm)\n     qin_gwsubbas_surf(bas) = net_perc_surf(bas)/1000.* &\n                         ct_bas(bas)*basns_area(bas)/DT    !units (m^3/s)\n\n!Adjust level of GW depth...(conceptual GW bucket units (mm))\n!DJG...old change to cms inflow...     z_gwsubbas(bas) = z_gwsubbas(bas) + net_perc(bas) / 1000.0   ! (m)\n\n!DJG...debug    write (6,*) \"DJG...before\",C(bas),ex(bas),z_gwsubbas(bas),z_mx(bas),z_gwsubbas(bas)/z_mx(bas)\n\n     z_gwsubbas(bas) = z_gwsubbas(bas) + qin_gwsubbas(bas)*DT/( &\n                       ct_bas(bas)*basns_area(bas))*1000.   !  units (mm)\n\n\n\n\n\n!Calculate baseflow as a function of GW bucket depth...\n\n     if(GWBASESWCRT.eq.1) then  !active exponential bucket... if/then for bucket model discharge type...\n\n!DJG...Estimation of bucket 'overflow' (qout_spill) if/when bucket gets filled...\n     qout_spill = 0.\n     z_gw_spill = 0.\n     if (z_gwsubbas(bas).gt.z_mx(bas)) then  !If/then for bucket overflow case...\n       z_gw_spill = z_gwsubbas(bas) - z_mx(bas)\n       z_gwsubbas(bas) = z_mx(bas)\n#ifdef HYDRO_D\n       write (6,*) \"Bucket spilling...\", bas, z_gwsubbas(bas), z_mx(bas), z_gw_spill\n#endif\n     else\n       z_gw_spill = 0.\n     end if   ! End if for bucket overflow case...\n\n     qout_spill = z_gw_spill/1000.*(ct_bas(bas)*basns_area(bas))/DT  !amount spilled from bucket overflow...units (cms)\n\n\n!DJG...Maximum estimation of bucket outlfow that is limited by total quantity in bucket...\n     qout_max = z_gwsubbas(bas)/1000.*(ct_bas(bas)*basns_area(bas))/DT   ! Estimate max bucket disharge limit to total volume in bucket...(m^3/s)\n\n\n! Assume exponential relation between z/zmax and Q...\n!DJG...old...creates non-asymptotic flow...   qout_gwsubbas(bas) = C(bas)*EXP(ex(bas)*z_gwsubbas(bas)/z_mx(bas)) !Exp.model. q_out (m^3/s)\n!DJG force asymptote to zero to prevent 'overdraft'...\n!DJG debug hardwire test...       qout_gwsubbas(bas) = 1*(EXP(7.0*10./100.)-1) !Exp.model. q_out (m^3/s)\n     qout_gwsubbas(bas) = C(bas)*(EXP(ex(bas)*z_gwsubbas(bas)/z_mx(bas))-1) !Exp.model. q_out (m^3/s)\n\n!DJG...Calculation of max bucket outlfow that is limited by total quantity in bucket...\n     qout_gwsubbas(bas) = MIN(qout_max,qout_gwsubbas(bas))   ! Limit bucket discharge to max. bucket limit\n\n!DJG...debug...     write (6,*) \"DJG-exp bucket...during\",C(bas),ex(bas),z_gwsubbas(bas),qin_gwsubbas(bas),z_mx(bas),z_gwsubbas(bas)/z_mx(bas), qout_gwsubbas(bas), qout_max, qout_spill\n\n\n\n     elseif (GWBASESWCRT.eq.2) then  !Pass through/steady-state bucket\n\n! Assuming a steady-state (inflow=outflow) model...\n!DJG convert input and output units to cms...       qout_gwsubbas(bas) = qin_gwsubbas(bas)  !steady-state model...(m^3)\n       qout_gwsubbas(bas) = qin_gwsubbas(bas)  !steady-state model...(m^3/s)\n\n!DJG...debug       write (6,*) \"DJG-pass through...during\",C(bas),ex(bas),qin_gwsubbas(bas), z_gwsubbas(bas),z_mx(bas),z_gwsubbas(bas)/z_mx(bas), qout_gwsubbas(bas), qout_max\n\n     end if    ! End if for bucket model discharge type....\n\n\n\n\n!Adjust level of GW depth...\n!DJG bug adjust output to be mm and correct area bug...       z_gwsubbas(bas) = z_gwsubbas(bas) - qout_gwsubbas(bas)*DT &\n!DJG bug adjust output to be mm and correct area bug...                       / (ct_bas(bas)*basns_area(bas))   !units(m)\n\n     z_gwsubbas(bas) = z_gwsubbas(bas) - qout_gwsubbas(bas)*DT/( &\n                       ct_bas(bas)*basns_area(bas))*1000.   ! units (mm)\n\n!DJG...Combine calculated bucket discharge and amount spilled from bucket...\n!ADCHANGE: Add in surface runoff as direct pass-through\n     qout_gwsubbas(bas) = qout_gwsubbas(bas) + qout_spill + qin_gwsubbas_surf(bas)  ! units (cms)\n\n\n!DJG...debug     write (6,*) \"DJG...after\",C(bas),ex(bas),z_gwsubbas(bas),z_mx(bas),z_gwsubbas(bas)/z_mx(bas), qout_gwsubbas(bas), qout_spill\n!DJG...debug     write (6,*) \"DJG...after...calc\",bas,ct_bas(bas),ct_bas(bas)*basns_area(bas),basns_area(bas),DT\n\n\n\n\n! #ifdef MPP_LAND\n!      endif\n! #endif\n   END DO                 ! End loop for GW bucket calcs...\n\n   z_gwsubbas_tmp = z_gwsubbas\n\n\n!!!Distribute basin integrated baseflow to stream pixels as stream 'inflow'...\n\n      qinflowbase = 0.\n\n\n      do i=1,ixrt\n        do j=1,jxrt\n!!!    -simple uniform disaggregation (8.31.06)\n           if (gw_strm_msk_lind(i,j).gt.0) then\n\n             qinflowbase(i,j) = qout_gwsubbas(gw_strm_msk_lind(i,j))*1000.*DT/ &\n                gwbas_pix_ct(gw_strm_msk_lind(i,j))/dist(i,j,9)     ! units (mm) that gets passed into chan routing as stream inflow\n\n           end if\n        end do\n      end do\n\n\n!!!    - weighted redistribution...(need to pass accum weights (slope) in...)\n!        NOT FINISHED just BASIC framework...\n!         do bas=1,numbasns\n!           do k=1,gwbas_pix_ct(bas)\n!             qinflowbase(i,j) = k*slope\n!           end do\n!         end do\n\n        z_gwsubbas = z_gwsubbas_tmp\n\n\n!------------------------------------------------------------------------------\n   End subroutine simp_gw_buck\n!------------------------------------------------------------------------------\n\n\n\n\n#ifdef MPP_LAND\n   subroutine pix_ct_1(in_gw_strm_msk,ixrt,jxrt,gwbas_pix_ct,numbasns,gnumbasns,basnsInd)\n      USE module_mpp_land\n      implicit none\n      integer ::    i,j,ixrt,jxrt,numbasns, bas, gnumbasns, k\n      integer,dimension(ixrt,jxrt) :: in_gw_strm_msk\n      integer,dimension(global_rt_nx,global_rt_ny) :: gw_strm_msk\n      real,dimension(numbasns) :: gwbas_pix_ct\n      real,dimension(gnumbasns) :: tmp_gwbas_pix_ct\n      integer(kind=int64), intent(in), dimension(:) :: basnsInd\n\n      gw_strm_msk = 0\n\n\n      call write_IO_rt_int(in_gw_strm_msk, gw_strm_msk)\n\n      call mpp_land_sync()\n\n      if(my_id .eq. IO_id) then\n!        tmp_gwbas_pix_ct = 0.0\n!         do bas = 1,gnumbasns\n!         do i=1,global_rt_nx\n!           do j=1,global_rt_ny\n!             if(gw_strm_msk(i,j) .eq. bas) then\n!                tmp_gwbas_pix_ct(bas) = tmp_gwbas_pix_ct(bas) + 1.0\n!             endif\n!           end do\n!         end do\n!         end do\n\n            tmp_gwbas_pix_ct = 0.0\n            do i=1,global_rt_nx\n              do j=1,global_rt_ny\n                if(gw_strm_msk(i,j) .gt. 0) then\n                   bas = gw_strm_msk(i,j)\n                   tmp_gwbas_pix_ct(bas) = tmp_gwbas_pix_ct(bas) + 1.0\n               endif\n              end do\n            end do\n      end if\n\n      call mpp_land_sync()\n\n      if(gnumbasns .gt. 0) then\n         call mpp_land_bcast_real(gnumbasns,tmp_gwbas_pix_ct)\n      endif\n      do k = 1, numbasns\n         bas = basnsInd(k)\n         gwbas_pix_ct(k) = tmp_gwbas_pix_ct(bas)\n      end do\n\n\n   end subroutine pix_ct_1\n#endif\n\n\n\n\n\nend module module_GW_baseflow\n"
  },
  {
    "path": "src/Routing/module_HYDRO_io.F90",
    "content": "module module_HYDRO_io\n#ifdef MPP_LAND\n     use module_mpp_land\n     use module_mpp_reachls,  only: ReachLS_decomp, reachls_wreal, ReachLS_write_io, &\n                                    ReachLS_wInt, reachls_wreal2, TONODE2RSL, TONODE2RSL8, gbcastvalue\n     use MODULE_mpp_GWBUCKET, only: gw_write_io_real, gw_write_io_int\n#endif\n   use Module_Date_utilities_rt, only: geth_newdate\n   use module_HYDRO_utils, only: get_dist_ll\n   use config_base, only: nlst\n   use module_RT_data, only: rt_domain\n   use module_gw_gw2d_data, only: gw2d\n   use module_reservoir_utilities, only: read_reservoir_type\n   use netcdf\n   use module_hydro_stop, only:HYDRO_stop\n   use hashtable\n   use iso_fortran_env, only: int64, compiler_version\n\n   implicit none\n\n   interface w_rst_crt_reach\n      module procedure w_rst_crt_reach_real\n      module procedure w_rst_crt_reach_real8\n   end interface\n\n   interface read_rst_crt_reach_nc\n      module procedure read_rst_crt_reach_nc_real\n      module procedure read_rst_crt_reach_nc_real8\n   end interface\n\n   integer, parameter :: did=1\n   integer :: logUnit\n\n     contains\n\n        integer function get2d_real(var_name,out_buff,ix,jx,fileName, fatalErr)\n          implicit none\n          integer :: ivar, iret,varid,ncid,ix,jx\n          real out_buff(ix,jx)\n          character(len=*), intent(in) :: var_name\n          character(len=*), intent(in) :: fileName\n          logical, optional, intent(in) :: fatalErr\n          logical :: fatalErr_local\n          character(len=256) :: errMsg\n\n          fatalErr_local = .false.\n          if(present(fatalErr)) fatalErr_local=fatalErr\n\n          get2d_real = -1\n\n          iret = nf90_open(trim(fileName), NF90_NOWRITE, ncid)\n          if (iret .ne. 0) then\n             errMsg = \"get2d_real: failed to open the netcdf file: \" // trim(fileName)\n             print*, trim(errMsg)\n             if(fatalErr_local) call hydro_stop(trim(errMsg))\n             out_buff = -9999.\n             return\n          endif\n\n          ivar = nf90_inq_varid(ncid,trim(var_name),  varid)\n          if(ivar .ne. 0) then\n             ivar = nf90_inq_varid(ncid,trim(var_name//\"_M\"),  varid)\n             if(ivar .ne. 0) then\n                errMsg = \"WARNING: get2d_real: failed to find the variables: \" //      &\n                         trim(var_name) // ' and ' // trim(var_name//\"_M\") // &\n                         ' in ' // trim(fileName)\n                write(6,*) errMsg\n                if(fatalErr_local) call hydro_stop(errMsg)\n                return\n             endif\n          end if\n\n          iret = nf90_get_var(ncid, varid, out_buff)\n          if(iret .ne. 0) then\n             errMsg = \"WARNING: get2d_real: failed to read the variable: \" // &\n                      trim(var_name) // ' or ' // trim(var_name//\"_M\") // &\n                      ' in ' // trim(fileName)\n             print*,trim(errMsg)\n             if(fatalErr_local) call hydro_stop(trim(errMsg))\n             return\n          endif\n\n          iret = nf90_close(ncid)\n          if(iret .ne. 0) then\n             errMsg = \"WARNING: get2d_real: failed to close the file: \" // &\n                      trim(fileName)\n             print*,trim(errMsg)\n             if(fatalErr_local) call hydro_stop(trim(errMsg))\n          endif\n\n          get2d_real =  ivar\n      end function get2d_real\n\n\n     subroutine get2d_lsm_real(var_name,out_buff,ix,jx,fileName)\n         implicit none\n         integer ix,jx, status\n         character (len=*),intent(in) :: var_name, fileName\n         real,dimension(ix,jx):: out_buff\n\n\n#ifdef MPP_LAND\n#ifdef PARALLELIO\n         status = get2d_real(var_name,out_buff,ix,jx,fileName)\n#else\n         real,allocatable, dimension(:,:) :: buff_g\n\n\n#ifdef HYDRO_D\n         write(6,*) \"start to read variable \", var_name\n#endif\n         if(my_id .eq. IO_id) then\n            allocate(buff_g (global_nx,global_ny) )\n            status = get2d_real(var_name,buff_g,global_nx,global_ny,fileName)\n         else\n            allocate(buff_g (1,1) )\n         end if\n         call decompose_data_real(buff_g,out_buff)\n         if(allocated(buff_g)) deallocate(buff_g)\n#endif\n#else\n         status = get2d_real(var_name,out_buff,ix,jx,fileName)\n#endif\n#ifdef HYDRO_D\n         write(6,*) \"finish reading variable \", var_name\n#endif\n     end subroutine get2d_lsm_real\n\n     subroutine get2d_lsm_vegtyp(out_buff,ix,jx,fileName)\n         implicit none\n         integer ix,jx, status,land_cat, iret, dimid,ncid\n         character (len=*),intent(in) :: fileName\n         character (len=256) units\n         integer,dimension(ix,jx):: out_buff\n         real, dimension(ix,jx) :: xdum\n#ifdef MPP_LAND\n         real,allocatable, dimension(:,:) :: buff_g\n\n\n#ifndef PARALLELIO\n         if(my_id .eq. IO_id) then\n            allocate(buff_g (global_nx,global_ny) )\n         else\n            allocate(buff_g (1,1) )\n         endif\n         if(my_id .eq. IO_id) then\n#endif\n#endif\n                ! Open the NetCDF file.\n              iret = nf90_open(fileName, NF90_NOWRITE, ncid)\n              if (iret /= 0) then\n                 write(*,'(\"Problem opening geo_static file: ''\", A, \"''\")') &\n                      trim(fileName)\n                 call hydro_stop(\"In get2d_lsm_vegtyp() - Problem opening geo_static file\")\n              endif\n\n            iret = nf90_inq_dimid(ncid, \"land_cat\", dimid)\n            if (iret /= 0) then\n              call hydro_stop(\"In get2d_lsm_vegtyp() - nf90_inq_dimid:  land_cat problem \")\n             endif\n\n            iret = nf90_inquire_dimension(ncid, dimid, len = land_cat)\n            if (iret /= 0) then\n               call hydro_stop(\"In get2d_lsm_vegtyp() - nf90_inquire_dimension:  land_cat problem\")\n            endif\n\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n            call get_landuse_netcdf(ncid, buff_g, units, global_nx ,global_ny, land_cat)\n         end if\n         call decompose_data_real(buff_g,xdum)\n         if(allocated(buff_g)) deallocate(buff_g)\n#else\n          call get_landuse_netcdf(ncid, xdum,   units, ix, jx, land_cat)\n#endif\n          iret = nf90_close(ncid)\n\n#else\n          call get_landuse_netcdf(ncid, xdum,   units, ix, jx, land_cat)\n          iret = nf90_close(ncid)\n#endif\n         out_buff = nint(xdum)\n     end subroutine get2d_lsm_vegtyp\n\n\n\n     subroutine get_file_dimension(fileName, ix,jx)\n            implicit none\n            character(len=*) fileName\n            integer ncid , iret, ix,jx, dimid\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n            if(my_id .eq. IO_id) then\n#endif\n#endif\n            iret = nf90_open(fileName, NF90_NOWRITE, ncid)\n            if (iret /= 0) then\n               write(*,'(\"Problem opening geo_static file: ''\", A, \"''\")') &\n                    trim(fileName)\n               call hydro_stop(\"In get_file_dimension() - Problem opening geo_static file\")\n            endif\n\n            iret = nf90_inq_dimid(ncid, \"west_east\", dimid)\n\n            if (iret /= 0) then\n               call hydro_stop(\"In get_file_dimension() - nf90_inq_dimid:  west_east problem\")\n            endif\n\n            iret = nf90_inquire_dimension(ncid, dimid, len = ix)\n            if (iret /= 0) then\n               call hydro_stop(\"In get_file_dimension() - nf90_inquire_dimension:  west_east problem\")\n            endif\n\n            iret = nf90_inq_dimid(ncid, \"south_north\", dimid)\n            if (iret /= 0) then\n               call hydro_stop(\"In get_file_dimension() - nf90_inq_dimid:  south_north problem.\")\n            endif\n\n            iret = nf90_inquire_dimension(ncid, dimid, len = jx)\n            if (iret /= 0) then\n               call hydro_stop(\"In get_file_dimension() - nf90_inquire_dimension:  south_north problem\")\n            endif\n            iret = nf90_close(ncid)\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n            endif\n            call mpp_land_bcast_int1(ix)\n            call mpp_land_bcast_int1(jx)\n#endif\n#endif\n\n     end subroutine get_file_dimension\n\nsubroutine get_file_globalatts(fileName, iswater, islake, isurban, isoilwater)\n  implicit none\n  character(len=*) fileName\n  integer iswater, islake, isurban, isoilwater\n  integer ncid, iret, istmp\n#ifdef MPP_LAND\n#ifndef PARALLELIO\nif (my_id .eq. IO_id) then\n#endif\n#endif\n\n  iret = nf90_open(fileName, nf90_nowrite, ncid)\n  if (iret /= NF90_NOERR) then\n    write(*,'(\"Problem opening geo file: ''\", A, \"''\")') trim(fileName)\n    write(*,*) \"Using default (USGS) values for urban and water land use types.\"\n  else\n    iret = nf90_get_att(ncid, NF90_GLOBAL, 'ISWATER', istmp)\n    if (iret .eq. NF90_NOERR) then\n      iswater = istmp\n    else\n      write(*,*) \"Using default (USGS) values for water land use types.\"\n      iswater = 16\n    endif\n    iret = nf90_get_att(ncid, NF90_GLOBAL, 'ISLAKE', istmp)\n    if (iret .eq. NF90_NOERR) then\n      islake = istmp\n    else\n      write(*,*) \"Using default (USGS) values for lake land use types.\"\n      islake = -1\n    endif\n    iret = nf90_get_att(ncid, NF90_GLOBAL, 'ISURBAN', istmp)\n    if (iret .eq. NF90_NOERR) then\n      isurban = istmp\n    else\n      write(*,*) \"Using default (USGS) values for urban land use types.\"\n      isurban = 1\n    endif\n    iret = nf90_get_att(ncid, NF90_GLOBAL, 'ISOILWATER', istmp)\n    if (iret .eq. NF90_NOERR) then\n      isoilwater = istmp\n    else\n      write(*,*) \"Using default (USGS) values for water soil types.\"\n      isoilwater = 14\n    endif\n    iret = nf90_close(ncid)\n  endif\n\n#ifdef HYDRO_D\n#ifndef NCEP_WCOSS\n  write(6, *) \"get_file_globalatts: ISWATER ISLAKE ISURBAN ISOILWATER\", iswater, islake, isurban, isoilwater\n#endif\n#endif\n\n#ifdef MPP_LAND\n#ifndef PARALLELIO\nendif\ncall mpp_land_bcast_int1(iswater)\ncall mpp_land_bcast_int1(islake)\ncall mpp_land_bcast_int1(isurban)\ncall mpp_land_bcast_int1(isoilwater)\n#endif\n#endif\n\nend subroutine get_file_globalatts\n\n\n     subroutine get2d_lsm_soltyp(out_buff,ix,jx,fileName)\n         implicit none\n         integer ix,jx, status,land_cat, iret, dimid,ncid\n         character (len=*),intent(in) :: fileName\n         character (len=256) units\n         integer,dimension(ix,jx):: out_buff\n         real, dimension(ix,jx) :: xdum\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n         real,allocatable, dimension(:,:) :: buff_g\n\n\n         if(my_id .eq. IO_id) then\n              allocate(buff_g (global_nx,global_ny) )\n#endif\n#endif\n                ! Open the NetCDF file.\n            iret = nf90_open(fileName, NF90_NOWRITE, ncid)\n              if (iret /= 0) then\n                 write(*,'(\"Problem opening geo_static file: ''\", A, \"''\")') &\n                      trim(fileName)\n                 call hydro_stop(\"In get2d_lsm_soltyp() - problem to open geo_static file.\")\n              endif\n\n            iret = nf90_inq_dimid(ncid, \"soil_cat\", dimid)\n            if (iret /= 0) then\n                call hydro_stop(\"In get2d_lsm_soltyp() - nf90_inq_dimid:  soil_cat problem\")\n            endif\n\n            iret = nf90_inquire_dimension(ncid, dimid, len = land_cat)\n            if (iret /= 0) then\n               call hydro_stop(\"In get2d_lsm_soltyp() - nf90_inquire_dimension:  soil_cat problem\")\n            endif\n\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n            call get_soilcat_netcdf(ncid, buff_g, units, global_nx ,global_ny, land_cat)\n         end if\n         call decompose_data_real(buff_g,xdum)\n         if(my_id .eq. io_id) then\n           if(allocated(buff_g)) deallocate(buff_g)\n         endif\n#else\n          call get_soilcat_netcdf(ncid, xdum,   units, ix, jx, land_cat)\n#endif\n          iret = nf90_close(ncid)\n#else\n          call get_soilcat_netcdf(ncid, xdum,   units, ix, jx, land_cat)\n          iret = nf90_close(ncid)\n#endif\n          out_buff = nint(xdum)\n     end subroutine get2d_lsm_soltyp\n\n\n  subroutine get_landuse_netcdf(ncid, array, units, idim, jdim, ldim)\n    implicit none\n    integer, intent(in) :: ncid\n    integer, intent(in) :: idim, jdim, ldim\n    real, dimension(idim,jdim), intent(out) :: array\n    character(len=256), intent(out) :: units\n    integer :: iret, varid\n!    real, dimension(idim,jdim,ldim) :: xtmp\n!    integer, dimension(1) :: mp\n!    integer :: i, j, l\n!    character(len=24), parameter :: name = \"LANDUSEF\"\n    character(len=24), parameter :: name = \"LU_INDEX\"\n\n    units = \"\"\n\n!    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n!    if (iret /= 0) then\n!       print*, 'name = \"', trim(name)//'\"'\n!       call hydro_stop(\"In get_landuse_netcdf() - nf90_inq_varid problem\")\n!    endif\n\n!    iret = nf90_get_var(ncid, varid, xtp)\n!    if (iret /= 0) then\n!       print*, 'name = \"', trim(name)//'\"'\n!       call hydro_stop(\"In get_landuse_netcdf() - nf90_get_var problem\")\n!    endif\n!\n!    do i = 1, idim\n!       do j = 1, jdim\n!          mp = maxloc(xtmp(i,j,:))\n!          array(i,j) = mp(1)\n!          do l = 1,ldim\n!            if(xtmp(i,j,l).lt.0) array(i,j) = -9999.0\n!          enddo\n!       enddo\n!    enddo\n\n!!! START AD_CHANGE\n! Using LU_INDEX direct from WPS for consistency with the LSMs\n    iret = nf90_inq_varid(ncid,  name,  varid)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       call hydro_stop(\"In get_landuse_netcdf() - nf90_inq_varid problem\")\n    endif\n\n    iret = nf90_get_var(ncid, varid, array)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       call hydro_stop(\"In get_landuse_netcdf() - nf90_get_var problem\")\n    endif\n!!! END AD_CHANGE\n\n  end subroutine get_landuse_netcdf\n\n\n  subroutine get_soilcat_netcdf(ncid, array, units, idim, jdim, ldim)\n    implicit none\n\n    integer, intent(in) :: ncid\n    integer, intent(in) :: idim, jdim, ldim\n    real, dimension(idim,jdim), intent(out) :: array\n    character(len=256), intent(out) :: units\n    integer :: iret, varid\n!    real, dimension(idim,jdim,ldim) :: xtmp\n!    integer, dimension(1) :: mp\n!    integer :: i, j, did\n!    character(len=24), parameter :: name = \"SOILCTOP\"\n    character(len=24), parameter :: name = \"SCT_DOM\"\n\n!    did = 1\n    units = \"\"\n\n!    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n!    if (iret /= 0) then\n!       print*, 'name = \"', trim(name)//'\"'\n!       call hydro_stop(\"In get_soilcat_netcdf() - nf90_inq_varid problem\")\n!    endif\n!\n!    iret = nf90_get_var(ncid, varid, xtmp)\n!    if (iret /= 0) then\n!       print*, 'name = \"', trim(name)//'\"'\n!       call hydro_stop(\"In get_soilcat_netcdf() - nf90_get_var problem\")\n!    endif\n!\n!    do i = 1, idim\n!       do j = 1, jdim\n!          mp = maxloc(xtmp(i,j,:))\n!          array(i,j) = mp(1)\n!       enddo\n!    enddo\n\n!     if(nlst_rt(did)%GWBASESWCRT .ne. 3) then\n!        where (array == 14) array = 1   ! DJG remove all 'water' soils...\n!     endif\n\n!!! START AD_CHANGE\n! Using SCT_DOM direct from WPS for consistency with the LSMs\n    iret = nf90_inq_varid(ncid,  name,  varid)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       call hydro_stop(\"In get_soilcat_netcdf() - nf90_inq_varid problem\")\n    endif\n\n    iret = nf90_get_var(ncid, varid, array)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       call hydro_stop(\"In get_soilcat_netcdf() - nf90_get_var problem\")\n    endif\n !!! END AD_CHANGE\n\n  end subroutine get_soilcat_netcdf\n\n\nsubroutine get_greenfrac_netcdf(ncid, array3, units, idim, jdim, ldim,mm,dd)\n    implicit none\n    integer, intent(in) :: ncid,mm,dd\n    integer, intent(in) :: idim, jdim, ldim\n    real, dimension(idim,jdim) :: array\n    real, dimension(idim,jdim) :: array2\n    real, dimension(idim,jdim) :: diff\n    real, dimension(idim,jdim), intent(out) :: array3\n    character(len=256), intent(out) :: units\n    integer :: iret, varid\n    real, dimension(idim,jdim,ldim) :: xtmp\n    integer, dimension(1) :: mp\n    integer :: i, j, mm2,daytot\n    real :: ddfrac\n    character(len=24), parameter :: name = \"GREENFRAC\"\n\n    units = \"fraction\"\n\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       call hydro_stop(\"In get_greenfrac_netcdf() - nf90_inq_varid problem\")\n    endif\n\n    iret = nf90_get_var(ncid, varid, xtmp)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       call hydro_stop(\"In get_greenfrac_netcdf() - nf90_get_var problem\")\n    endif\n\n\n    if (mm.lt.12) then\n      mm2 = mm+1\n    else\n      mm2 = 1\n    end if\n\n!DJG_DES Set up dates for daily interpolation...\n          if (mm.eq.1.OR.mm.eq.3.OR.mm.eq.5.OR.mm.eq.7.OR.mm.eq.8.OR.mm.eq.10.OR.mm.eq.12) then\n             daytot = 31\n          else if (mm.eq.4.OR.mm.eq.6.OR.mm.eq.9.OR.mm.eq.11) then\n             daytot = 30\n          else if (mm.eq.2) then\n             daytot = 28\n          end if\n          ddfrac = float(dd)/float(daytot)\n          if (ddfrac.gt.1.0) ddfrac = 1.0   ! Assumes Feb. 29th change is same as Feb 28th\n\n#ifdef HYDRO_D\n    print *,\"DJG_DES Made it past netcdf read...month = \",mm,mm2,dd,daytot,ddfrac\n\n#endif\n    do i = 1, idim\n       do j = 1, jdim\n          array(i,j) = xtmp(i,j,mm)   !GREENFRAC in geogrid in units of fraction from month 1\n          array2(i,j) = xtmp(i,j,mm2)   !GREENFRAC in geogrid in units of fraction from month 1\n          diff(i,j) = array2(i,j) - array(i,j)\n          array3(i,j) = array(i,j) + ddfrac * diff(i,j)\n       enddo\n    enddo\n\nend subroutine get_greenfrac_netcdf\n\n\n\nsubroutine get_albedo12m_netcdf(ncid, array3, units, idim, jdim, ldim,mm,dd)\n    implicit none\n    integer, intent(in) :: ncid,mm,dd\n    integer, intent(in) :: idim, jdim, ldim\n    real, dimension(idim,jdim) :: array\n    real, dimension(idim,jdim) :: array2\n    real, dimension(idim,jdim) :: diff\n    real, dimension(idim,jdim), intent(out) :: array3\n    character(len=256), intent(out) :: units\n    integer :: iret, varid\n    real, dimension(idim,jdim,ldim) :: xtmp\n    integer, dimension(1) :: mp\n    integer :: i, j, mm2,daytot\n    real :: ddfrac\n    character(len=24), parameter :: name = \"ALBEDO12M\"\n\n\n    units = \"fraction\"\n\n    iret = nf90_inq_varid(ncid,  trim(name),  varid)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       call hydro_stop(\"In get_albedo12m_netcdf() - nf90_inq_varid problem\")\n    endif\n\n    iret = nf90_get_var(ncid, varid, xtmp)\n    if (iret /= 0) then\n       print*, 'name = \"', trim(name)//'\"'\n       call hydro_stop(\"In get_albedo12m_netcdf() - nf90_get_var problem\")\n    endif\n\n    if (mm.lt.12) then\n      mm2 = mm+1\n    else\n      mm2 = 1\n    end if\n\n!DJG_DES Set up dates for daily interpolation...\n          if (mm.eq.1.OR.mm.eq.3.OR.mm.eq.5.OR.mm.eq.7.OR.mm.eq.8.OR.mm.eq.10.OR.mm.eq.12) then\n             daytot = 31\n          else if (mm.eq.4.OR.mm.eq.6.OR.mm.eq.9.OR.mm.eq.11) then\n             daytot = 30\n          else if (mm.eq.2) then\n             daytot = 28\n          end if\n          ddfrac = float(dd)/float(daytot)\n          if (ddfrac.gt.1.0) ddfrac = 1.0   ! Assumes Feb. 29th change is same as Feb 28th\n\n#ifdef HYDRO_D\n    print *,\"DJG_DES Made it past netcdf read...month = \",mm,mm2,dd,daytot,ddfrac\n#endif\n\n    do i = 1, idim\n       do j = 1, jdim\n          array(i,j) = xtmp(i,j,mm) / 100.0   !Convert ALBEDO12M from % to fraction...month 1\n          array2(i,j) = xtmp(i,j,mm2) / 100.0   !Convert ALBEDO12M from % to fraction... month 2\n          diff(i,j) = array2(i,j) - array(i,j)\n          array3(i,j) = array(i,j) + ddfrac * diff(i,j)\n       enddo\n    enddo\n\nend subroutine get_albedo12m_netcdf\n\n\n\n\n  subroutine get_2d_netcdf(name, ncid, array, units, idim, jdim, &\n       fatal_if_error, ierr)\n\n    implicit none\n\n    character(len=*), intent(in) :: name\n    integer, intent(in) :: ncid\n    integer, intent(in) :: idim, jdim\n    real, dimension(idim,jdim), intent(inout) :: array\n    character(len=256), intent(out) :: units\n    ! fatal_IF_ERROR:  an input code value:\n    !      .TRUE. if an error in reading the data should stop the program.\n    !      Otherwise the, IERR error flag is set, but the program continues.\n    logical, intent(in) :: fatal_if_error\n    integer, intent(out) :: ierr\n\n    integer :: iret, varid\n    real    :: scale_factor,   add_offset\n\n    units = \"\"\n\n    iret = nf90_inq_varid(ncid,  name,  varid)\n    if (iret /= 0) then\n       if (fatal_IF_ERROR) then\n          print*, 'name = \"', trim(name)//'\"'\n          call hydro_stop(\"In get_2d_netcdf() - nf90_inq_varid problem\")\n       else\n          ierr = iret\n          return\n       endif\n    endif\n\n    iret = nf90_get_var(ncid, varid, array)\n    if (iret /= 0) then\n       if (fatal_IF_ERROR) then\n          print*, 'name = \"', trim(name)//'\"'\n          call hydro_stop(\"In get_2d_netcdf() - nf90_get_var problem\")\n       else\n          ierr = iret\n          return\n       endif\n    endif\n\n    iret = nf90_get_att(ncid, varid, 'scale_factor', scale_factor)\n    if(iret .eq. 0) array = array * scale_factor\n    iret = nf90_get_att(ncid, varid, 'add_offset', add_offset)\n    if(iret .eq. 0) array = array + add_offset\n\n    ierr = 0;\n\n  end subroutine get_2d_netcdf\n\n\n      subroutine get_2d_netcdf_cows(var_name,ncid,var, &\n            ix,jx,tlevel,fatal_if_error,ierr)\n          character(len=*), intent(in) :: var_name\n          integer,intent(in) ::  ncid,ix,jx,tlevel\n          real, intent(out):: var(ix,jx)\n          logical, intent(in) :: fatal_if_error\n          integer ierr, iret\n          integer varid\n          integer start(4),count(4)\n          data count /1,1,1,1/\n          data start /1,1,1,1/\n          count(1) = ix\n          count(2) = jx\n          start(4) = tlevel\n      iret = nf90_inq_varid(ncid,  var_name,  varid)\n\n      if (iret /= 0) then\n        if (fatal_IF_ERROR) then\n           call hydro_stop(\"In get_2d_netcdf_cows() - nf90_inq_varid problem\")\n        else\n          ierr = iret\n          return\n        endif\n      endif\n      iret = nf90_get_var(ncid, varid, var, start, count)\n\n      end subroutine get_2d_netcdf_cows\n\n!---------------------------------------------------------\n!DJG Subroutinesfor inputting routing fields...\n!DNY   first reads the files to get the size of the\n!DNY   LINKS arrays\n!DJG   - Currently only hi-res topo is read\n!DJG   - At a future time, use this routine to input\n!DJG     subgrid land-use classification or routing\n!DJG     parameters 'overland roughness' and 'retention\n!DJG     depth'\n!\n!DJG,DNY - Update this subroutine to read in channel and lake\n!           parameters if activated       11.20.2005\n!---------------------------------------------------------\n\n       SUBROUTINE READ_ROUTEDIM(IXRT,JXRT,route_chan_f,route_link_f, &\n            route_direction_f, NLINKS, &\n            CH_NETLNK, channel_option, geo_finegrid_flnm, NLINKSL, UDMP_OPT,NLAKES)\n\n         implicit none\n        INTEGER                                      :: I,J,channel_option,jj\n        INTEGER, INTENT(INOUT)                       :: NLINKS, NLINKSL\n        INTEGER, INTENT(IN)                          :: IXRT,JXRT\n        INTEGER                                      :: CHNID,cnt\n        INTEGER, DIMENSION(IXRT,JXRT)                :: CH_NETRT   !- binary channel mask\n        INTEGER, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: CH_NETLNK  !- each node gets unique id\n        INTEGER, DIMENSION(IXRT,JXRT)                :: DIRECTION  !- flow direction\n        INTEGER, DIMENSION(IXRT,JXRT)                :: LAKE_MSKRT\n        REAL, DIMENSION(IXRT,JXRT)                   :: LAT, LON\n        INTEGER(kind=int64), DIMENSION(IXRT,JXRT)                :: CH_LNKRT   !- link routing ID\n        integer, INTENT(IN)                          :: UDMP_OPT\n        integer                                      :: NLAKES\n\n\n!!Dummy read in grids for inverted y-axis\n\n\n        CHARACTER(len=*)         :: route_chan_f, route_link_f,route_direction_f\n        CHARACTER(len=*)       :: geo_finegrid_flnm\n        CHARACTER(len=256)       :: var_name\n\n        ! variables for handling netcdf dimensions\n        integer :: iRet, ncid, dimId\n        logical :: routeLinkNetcdf\n\n        NLINKS = 0\n        CH_NETRT = -9999\n        CH_NETLNK = -9999\n\n        NLINKSL   = 0\n        CH_LNKRT  = -9999\n\n\n\n        cnt = 0\n#ifdef HYDRO_D\n       print *, \"Channel Option in Routedim is \", channel_option\n#endif\n\n\n        if (channel_option .eq. 4) return  ! it will run Rapid\n\n\n!-- will always read channel grid       IF(channel_option.eq.3) then  !get maxnodes and links from grid\n\n         var_name = \"CHANNELGRID\"\n         call readRT2d_int(var_name,CH_NETRT,ixrt,jxrt,&\n                   trim(geo_finegrid_flnm))\n\n\n!-- new link id variable to handle link routing\n         var_name = \"LINKID\"\n#ifdef MPP_LAND\n#ifdef HYDRO_D\n    write(6,*) \"read LINKID for CH_LNKRT from \", trim(geo_finegrid_flnm)\n#endif\n#endif\n!!!! LINKID is used for reach based method.  ?\n     IF(channel_option.ne.3 .and. UDMP_OPT.ne.1) then  !get maxnodes and links from grid\n         call readRT2d_int8(var_name,CH_LNKRT,ixrt,jxrt,&\n                   trim(geo_finegrid_flnm), fatalErr=.TRUE.)\n     endif\n\n\n\n         var_name = \"FLOWDIRECTION\"\n         call readRT2d_int(var_name,DIRECTION,ixrt,jxrt,&\n                   trim(geo_finegrid_flnm))\n\n!note that this is not used for link routing\n         var_name = \"LAKEGRID\"\n         call readRT2d_int(var_name,LAKE_MSKRT,ixrt,jxrt,&\n                   trim(geo_finegrid_flnm))\n\n\n        var_name = \"LATITUDE\"\n        call readRT2d_real(var_name,LAT,ixrt,jxrt,&\n                     trim(geo_finegrid_flnm))\n        var_name = \"LONGITUDE\"\n        call readRT2d_real(var_name,LON,ixrt,jxrt,&\n                     trim(geo_finegrid_flnm))\n\n! temp fix for buggy Arc export...\n        do j=1,jxrt\n          do i=1,ixrt\n            if(DIRECTION(i,j).eq.-128) DIRECTION(i,j)=128\n          end do\n        end do\n\n!DJG inv         do j=jxrt,1,-1\n         do j=1,jxrt\n             do i = 1, ixrt\n!               if (CH_NETRT(i,j) .ge.0.AND.CH_NETRT(i,j).lt.100) then\n                if (CH_NETRT(i,j) .ge.0) then\n                 NLINKS = NLINKS + 1\n                 if( UDMP_OPT .eq. 1) CH_NETLNK(i,j) = 2\n               endif\n            end do\n         end do\n#ifdef HYDRO_D\n         print *, \"NLINKS IS \", NLINKS\n#endif\n     if( UDMP_OPT .eq. 1) then\n         return\n     endif\n\n!DJG inv         DO j = JXRT,1,-1  !rows\n         DO j = 1,JXRT  !rows\n          DO i = 1 ,IXRT   !colsumns\n           If (CH_NETRT(i, j) .ge. 0) then !get its direction\n            If ((DIRECTION(i, j) .EQ. 64) .AND. (j+1 .LE. JXRT) ) then !North\n               if(CH_NETRT(i,j+1) .ge.0) then\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n                endif\n            else if ((DIRECTION(i, j) .EQ. 128) .AND. (i + 1 .LE. IXRT) &\n               .AND. (j + 1 .LE. JXRT) ) then !North East\n                if(CH_NETRT(i+1,j+1) .ge.0) then\n                   cnt = cnt + 1\n                   CH_NETLNK(i,j) = cnt\n                endif\n            else if ((DIRECTION(i, j) .EQ. 1) .AND. (i + 1 .LE. IXRT)) then !East\n                if(CH_NETRT(i+1,j) .ge. 0) then\n                   cnt = cnt + 1\n                   CH_NETLNK(i,j) = cnt\n                endif\n            else if ((DIRECTION(i, j) .EQ. 2) .AND. (i + 1 .LE. IXRT) &\n                    .AND. (j - 1 .NE. 0)) then !south east\n                 if(CH_NETRT(i+1,j-1).ge.0) then\n                     cnt = cnt + 1\n                     CH_NETLNK(i,j) = cnt\n                 endif\n            else if ((DIRECTION(i, j) .EQ. 4).AND.(j - 1 .NE. 0)) then !due south\n                 if(CH_NETRT(i,j-1).ge.0) then\n                         cnt = cnt + 1\n                         CH_NETLNK(i,j) = cnt\n                 endif\n            else if ((DIRECTION(i, j) .EQ. 8) .AND. (i - 1 .GT. 0) &\n                    .AND. (j - 1 .NE. 0)  ) then !south west\n                if(CH_NETRT(i-1,j-1).ge.0) then\n                     cnt = cnt + 1\n                     CH_NETLNK(i,j) = cnt\n                endif\n            else if ((DIRECTION(i, j) .EQ. 16) .AND. (i - 1 .GT. 0)) then !West\n                 if(CH_NETRT(i-1,j).ge.0) then\n                       cnt = cnt + 1\n                       CH_NETLNK(i,j) = cnt\n                 endif\n            else if ((DIRECTION(i, j) .EQ. 32) .AND. (i - 1 .GT. 0) &\n                    .AND. (j + 1 .LE. JXRT) ) then !North West\n                 if(CH_NETRT(i-1,j+1).ge.0) then\n                        cnt = cnt + 1\n                        CH_NETLNK(i,j) = cnt\n                 endif\n           else\n#ifdef HYDRO_D\n             write(*,135) \"PrPt/LkIn\", CH_NETRT(i,j), DIRECTION(i,j), LON(i,j), LAT(i,j),i,j\n#endif\n135             FORMAT(A9,1X,I3,1X,I3,1X,F10.5,1X,F9.5,1X,I4,1X,I4)\n             if (DIRECTION(i,j) .eq. 0) then\n#ifdef HYDRO_D\n               print *, \"Direction i,j \",i,j,\" of point \", cnt, \"is invalid\"\n#endif\n             endif\n\n           End If\n         End If !CH_NETRT check for this node\n        END DO\n       END DO\n#ifdef HYDRO_D\n       print *, \"found type 0 nodes\", cnt\n#endif\n!Find out if the boundaries are on an edge or flow into a lake\n!DJG inv       DO j = JXRT,1,-1\n       DO j = 1,JXRT\n         DO i = 1 ,IXRT\n          If (CH_NETRT(i, j) .ge. 0) then !get its direction\n\n           If ( (DIRECTION(i, j).EQ. 64) )then\n              if( j + 1 .GT. JXRT) then           !-- 64's can only flow north\n                 cnt = cnt + 1\n                 CH_NETLNK(i,j) = cnt\n              elseif(CH_NETRT(i,j+1) .lt. 0) then !North\n                 cnt = cnt + 1\n                 CH_NETLNK(i,j) = cnt\n#ifdef HYDRO_D\n                  print *, \"Boundary Pour Point N\", cnt,CH_NETRT(i,j), i,j\n#endif\n              endif\n           else if ( DIRECTION(i, j) .EQ. 128) then\n               if ((i + 1 .GT. IXRT) .or. (j + 1 .GT. JXRT))  then    !-- 128's can flow out of the North or East edge\n                   cnt = cnt + 1\n                   CH_NETLNK(i,j) = cnt\n                                                                      !   this is due north edge\n               elseif(CH_NETRT(i + 1, j + 1).lt.0) then !North East\n                   cnt = cnt + 1\n                   CH_NETLNK(i,j) = cnt\n#ifdef HYDRO_D\n              print *, \"Boundary Pour Point NE\", cnt, CH_NETRT(i,j),i,j\n#endif\n               endif\n           else if (DIRECTION(i, j) .EQ. 1) then\n                if (i + 1 .GT. IXRT) then      !-- 1's can only flow due east\n                   cnt = cnt + 1\n                   CH_NETLNK(i,j) = cnt\n                elseif(CH_NETRT(i + 1, j) .lt. 0) then !East\n                   cnt = cnt + 1\n                   CH_NETLNK(i,j) = cnt\n#ifdef HYDRO_D\n              print *, \"Boundary Pour Point E\", cnt,CH_NETRT(i,j), i,j\n#endif\n                endif\n           else if (DIRECTION(i, j) .EQ. 2) then\n               !-- 2's can flow out of east or south edge\n              if( (i + 1 .GT. IXRT) .OR.  (j - 1 .EQ. 0)) then            !-- this is the south edge\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n              elseif(CH_NETRT(i + 1, j - 1) .lt.0) then !south east\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n#ifdef HYDRO_D\n                  print *, \"Boundary Pour Point SE\", cnt,CH_NETRT(i,j), i,j\n#endif\n              endif\n           else if ( DIRECTION(i, j) .EQ. 4) then\n              if( (j - 1 .EQ. 0))  then            !-- 4's can only flow due south\n                 cnt = cnt + 1\n                 CH_NETLNK(i,j) = cnt\n              elseif (CH_NETRT(i, j - 1) .lt. 0) then !due south\n                 cnt = cnt + 1\n                 CH_NETLNK(i,j) = cnt\n#ifdef HYDRO_D\n                 print *, \"Boundary Pour Point S\", cnt,CH_NETRT(i,j), i,j\n#endif\n              endif\n           else if ( DIRECTION(i, j) .EQ. 8) then\n          !-- 8's can flow south or west\n              if( (i - 1 .eq. 0) .OR. ( j - 1 .EQ. 0)) then             !-- this is the south edge\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n              elseif  (CH_NETRT(i - 1, j - 1).lt.0) then !south west\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n#ifdef HYDRO_D\n                  print *, \"Boundary Pour Point SW\", cnt,CH_NETRT(i,j), i,j\n#endif\n              endif\n           else if ( DIRECTION(i, j) .EQ. 16) then\n              if(i - 1 .eq. 0) then              !-- 16's can only flow due west\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n              elseif (CH_NETRT(i - 1, j).lt.0) then !West\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n#ifdef HYDRO_D\n              print *, \"Boundary Pour Point W\", cnt,CH_NETRT(i,j), i,j\n#endif\n              endif\n           else if ( DIRECTION(i, j) .EQ. 32)  then\n              if ( (i - 1 .eq. 0)      &      !-- 32's can flow either west or north\n               .OR.   (j .eq. JXRT))  then         !-- this is the north edge\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n              elseif (CH_NETRT(i - 1, j + 1).lt.0) then !North West\n                  cnt = cnt + 1\n                  CH_NETLNK(i,j) = cnt\n#ifdef HYDRO_D\n                  print *, \"Boundary Pour Point NW\", cnt,CH_NETRT(i,j), i,j\n#endif\n              endif\n           endif\n          endif !CH_NETRT check for this node\n         END DO\n       END DO\n\n#ifdef HYDRO_D\n       print *, \"total number of channel elements\", cnt\n       print *, \"total number of NLINKS          \", NLINKS\n#endif\n\n\n\n      !-- get the number of lakes\n       if (cnt .ne. NLINKS) then\n         print *, \"Apparent error in network topology\", cnt, NLINKS\n         print* , \"ixrt =\", ixrt, \"jxrt =\", jxrt\n         call hydro_stop(\"READ_ROUTEDIM\")\n       endif\n\n!!-- no longer find the lakes from the 2-d hi res grid\n!DJG inv       do j=jxrt,1,-1\n! follwoing is modified by Wei Yu 03/24/2017\n     if(UDMP_OPT .eq. 0) then\n        NLAKES = 0\n        do j=1,jxrt\n           do i = 1,ixrt\n            if (LAKE_MSKRT(i,j) .gt. NLAKES) then\n              NLAKES = LAKE_MSKRT(i,j)\n            endif\n         end do\n        end do\n#ifdef HYDRO_D\n        write(6,*) \"finish read_red ..  Total Number of Lakes in Domain = \", NLAKES\n#endif\n     endif\n\n\n!-- don't return here--!  return\n\n     END SUBROUTINE READ_ROUTEDIM\n\n!!! This subroutine gets the NLINKSL\n     subroutine get_NLINKSL(NLINKSL, channel_option, route_link_f)\n        implicit none\n        CHARACTER(len=*)         :: route_link_f\n        integer :: NLINKSL, channel_option\n        CHARACTER(len=256)         :: route_link_f_r\n        integer :: lenRouteLinkFR\n        logical :: routeLinkNetcdf\n        CHARACTER(len=256)       :: InputLine\n        if (channel_option.ne.3) then  ! overwrite the NLINKS\n!-IF is now commented above   else  ! get nlinks from the ascii file of links\n#ifdef HYDRO_D\n           write(6,*) \"read file to get NLINKSL from\", trim(route_link_f)\n           call flush(6)\n#endif\n       !! is RouteLink file netcdf (*.nc) or csv (*.csv)\n           route_link_f_r = adjustr(route_link_f)\n           lenRouteLinkFR = len(route_link_f_r)\n           routeLinkNetcdf = route_link_f_r( (lenRouteLinkFR-2):lenRouteLinkFR) .eq.  '.nc'\n\n           if(routeLinkNetcdf) then\n              NLINKSL = -99\n              NLINKSL = get_netcdf_dim(trim(route_link_f), 'feature_id',  &\n                                   'READ_ROUTEDIM', fatalErr=.false.)\n              if(NLINKSL .eq. -99) then\n                 ! We were unsucessful in getting feature_id, try linkDim\n                 NLINKSL = get_netcdf_dim(trim(route_link_f), 'linkDim',  &\n                                         'READ_ROUTEDIM', fatalErr=.false.)\n              endif\n              if(NLINKSL .eq. -99) then\n                 ! Neither the feature_id or linkDim dimensions were found in\n                 ! the RouteLink file. Throw an error...\n                 call hydro_stop(\"Could not find either feature_id or linkDim in RouteLink file.\")\n              endif\n           else\n              open(unit=17,file=trim(route_link_f),          & !link\n                   form='formatted',status='old')\n\n1011          read(17,*,end= 1999) InputLine\n              NLINKSL = NLINKSL + 1\n              goto 1011\n1999          continue\n              NLINKSL = NLINKSL - 1 !-- first line is a comment\n              close(17)\n           end if ! routeLinkNetcdf\n\n#ifdef HYDRO_D\n            print *, \"Number of Segments or Links on sparse network\", NLINKSL\n            write(6,*) \"NLINKSL = \", NLINKSL\n            call flush(6)\n#endif\n\n      end if !end-if is now for channel_option just above, not IF from further up\n\n     end subroutine get_NLINKSL\n\n     subroutine nreadRT2d_real(var_name, inv, ixrt, jxrt, fileName, fatalErr)\n         implicit none\n         INTEGER :: iret\n         INTEGER, INTENT(IN) :: ixrt,jxrt\n         INTEGER :: i, j, ii,jj\n         CHARACTER(len=*):: var_name,fileName\n         real, INTENT(OUT), dimension(ixrt,jxrt) :: inv\n#ifndef MPP_LAND\n         real, dimension(ixrt,jxrt) :: inv_tmp\n#endif\n         logical, optional, intent(in) :: fatalErr\n         logical :: fatalErr_local\n#ifdef MPP_LAND\n         real, allocatable,dimension(:,:) :: g_inv_tmp, g_inv\n#endif\n         fatalErr_local = .FALSE.\n         if(present(fatalErr)) fatalErr_local=fatalErr\n\n#ifdef MPP_LAND\n         if(my_id .eq. io_id) then\n\n              allocate(g_inv_tmp(global_rt_nx,global_rt_ny))\n              allocate(g_inv(global_rt_nx,global_rt_ny))\n\n              g_inv_tmp = -9999.9\n              iret =  get2d_real(var_name,g_inv_tmp,global_rt_nx,global_rt_ny,&\n                     trim(fileName), fatalErr=fatalErr_local)\n\n              jj = global_rt_ny\n              do j = 1, global_rt_ny\n                 g_inv(:,j) = g_inv_tmp(:,jj)\n                 jj = global_rt_ny - j\n              end do\n\n              if(allocated(g_inv_tmp)) deallocate(g_inv_tmp)\n         else\n              allocate(g_inv(1,1))\n         endif\n         call decompose_RT_real(g_inv,inv,global_rt_nx,global_rt_ny,IXRT,JXRT)\n         if(allocated(g_inv)) deallocate(g_inv)\n#else\n         inv_tmp = -9999.9\n         iret =  get2d_real(var_name,inv_tmp,ixrt,jxrt,&\n                     trim(fileName), fatalErr=fatalErr_local)\n         do i=1,ixrt\n            jj=jxrt\n         do j=1,jxrt\n           inv(i,j)=inv_tmp(i,jj)\n           jj=jxrt-j\n         end do\n        end do\n#endif\n\n\n     end SUBROUTINE nreadRT2d_real\n\n     subroutine nreadRT2d_int(var_name, inv, ixrt, jxrt, fileName, fatalErr)\n         implicit none\n         INTEGER, INTENT(IN) :: ixrt,jxrt\n         INTEGER :: i, j, ii,jj, iret\n         CHARACTER(len=*):: var_name,fileName\n         integer, INTENT(OUT), dimension(ixrt,jxrt) :: inv\n         integer, dimension(ixrt,jxrt) :: inv_tmp\n         logical, optional, intent(in) :: fatalErr\n         logical :: fatalErr_local\n#ifdef MPP_LAND\n         integer, allocatable,dimension(:,:) :: g_inv_tmp, g_inv\n#endif\n         fatalErr_local = .FALSE.\n         if(present(fatalErr)) fatalErr_local=fatalErr\n\n#ifdef MPP_LAND\n         if(my_id .eq. io_id) then\n              allocate(g_inv_tmp(global_rt_nx,global_rt_ny))\n              allocate(g_inv(global_rt_nx,global_rt_ny))\n              g_inv_tmp = -9999.9\n              call  get2d_int(var_name,g_inv_tmp,global_rt_nx,global_rt_ny,&\n                     trim(fileName), fatalErr=fatalErr_local)\n\n              jj = global_rt_ny\n              do j = 1, global_rt_ny\n                 g_inv(:,j) = g_inv_tmp(:,jj)\n                 jj = global_rt_ny - j\n              end do\n         else\n              allocate(g_inv_tmp(1,1))\n              allocate(g_inv(1,1))\n         endif\n         call decompose_RT_int(g_inv,inv,global_rt_nx,global_rt_ny,IXRT,JXRT)\n         if(allocated(g_inv_tmp)) deallocate(g_inv_tmp)\n         if(allocated(g_inv)) deallocate(g_inv)\n#else\n         call  get2d_int(var_name,inv_tmp,ixrt,jxrt,&\n                     trim(fileName), fatalErr=fatalErr_local)\n         do i=1,ixrt\n            jj=jxrt\n         do j=1,jxrt\n           inv(i,j)=inv_tmp(i,jj)\n           jj=jxrt-j\n         end do\n        end do\n#endif\n     end SUBROUTINE nreadRT2d_int\n\n\n     subroutine nreadRT2d_int8(var_name, inv, ixrt, jxrt, fileName, fatalErr)\n         implicit none\n         INTEGER, INTENT(IN) :: ixrt,jxrt\n         INTEGER :: i, j, ii,jj, iret\n         CHARACTER(len=*):: var_name,fileName\n         integer(kind=int64), INTENT(OUT), dimension(ixrt,jxrt) :: inv\n         integer(kind=int64), dimension(ixrt,jxrt) :: inv_tmp\n         logical, optional, intent(in) :: fatalErr\n         logical :: fatalErr_local\n#ifdef MPP_LAND\n     integer(kind=int64), allocatable,dimension(:,:) :: g_inv_tmp, g_inv\n#endif\n         fatalErr_local = .FALSE.\n         if(present(fatalErr)) fatalErr_local=fatalErr\n\n#ifdef MPP_LAND\n     if(my_id .eq. io_id) then\n          allocate(g_inv_tmp(global_rt_nx,global_rt_ny))\n          allocate(g_inv(global_rt_nx,global_rt_ny))\n          g_inv_tmp = -9999.9\n          call  get2d_int8(var_name,g_inv_tmp,global_rt_nx,global_rt_ny,&\n                 trim(fileName), fatalErr=fatalErr_local)\n\n          jj = global_rt_ny\n          do j = 1, global_rt_ny\n             g_inv(:,j) = g_inv_tmp(:,jj)\n             jj = global_rt_ny - j\n          end do\n     else\n          allocate(g_inv_tmp(1,1))\n          allocate(g_inv(1,1))\n     endif\n     call decompose_RT_int8(g_inv,inv,global_rt_nx,global_rt_ny,IXRT,JXRT)\n     if(allocated(g_inv_tmp)) deallocate(g_inv_tmp)\n     if(allocated(g_inv)) deallocate(g_inv)\n#else\n         call  get2d_int(var_name,inv_tmp,ixrt,jxrt,&\n                 trim(fileName), fatalErr=fatalErr_local)\n         do i=1,ixrt\n             jj=jxrt\n             do j=1,jxrt\n                 inv(i,j)=inv_tmp(i,jj)\n                 jj=jxrt-j\n             end do\n         end do\n#endif\n     end SUBROUTINE nreadRT2d_int8\n\n         !---------------------------------------------------------\n!DJG -----------------------------------------------------\n\n     subroutine readRT2d_real(var_name, inv, ixrt, jxrt, fileName, fatalErr)\n         implicit none\n         INTEGER :: iret\n         INTEGER, INTENT(IN) :: ixrt,jxrt\n         INTEGER :: i, j, ii,jj\n         CHARACTER(len=*):: var_name,fileName\n         real, INTENT(OUT), dimension(ixrt,jxrt) :: inv\n         real, dimension(ixrt,jxrt) :: inv_tmp\n         logical, optional, intent(in) :: fatalErr\n         logical :: fatalErr_local\n         fatalErr_local = .FALSE.\n         if(present(fatalErr)) fatalErr_local=fatalErr\n         inv_tmp = -9999.9\n         iret =  get2d_real(var_name,inv_tmp,ixrt,jxrt,&\n                     trim(fileName), fatalErr=fatalErr_local)\n\n         jj = jxrt\n         do j = 1, jxrt\n            inv(:,j) = inv_tmp(:,jj)\n            jj = jxrt - j\n         end do\n\n     end SUBROUTINE readRT2d_real\n\n     subroutine readRT2d_int(var_name, inv, ixrt, jxrt, fileName, fatalErr)\n         implicit none\n         INTEGER, INTENT(IN) :: ixrt,jxrt\n         INTEGER :: i, j, ii,jj\n         CHARACTER(len=*):: var_name,fileName\n         integer, INTENT(OUT), dimension(ixrt,jxrt) :: inv\n         integer, dimension(ixrt,jxrt) :: inv_tmp\n         logical, optional, intent(in) :: fatalErr\n         logical :: fatalErr_local\n         fatalErr_local = .FALSE.\n         if(present(fatalErr)) fatalErr_local=fatalErr\n         call  get2d_int(var_name,inv_tmp,ixrt,jxrt,&\n                     trim(fileName), fatalErr=fatalErr_local)\n\n         jj = jxrt\n         do j = 1, jxrt\n            inv(:,j) = inv_tmp(:,jj)\n            jj = jxrt - j\n         end do\n\n     end SUBROUTINE readRT2d_int\n\n     subroutine readRT2d_int8(var_name, inv, ixrt, jxrt, fileName, fatalErr)\n         implicit none\n         INTEGER, INTENT(IN) :: ixrt,jxrt\n         INTEGER :: i, j, ii,jj\n         CHARACTER(len=*):: var_name,fileName\n         integer(kind=int64), INTENT(OUT), dimension(ixrt,jxrt) :: inv\n         integer(kind=int64), dimension(ixrt,jxrt) :: inv_tmp\n         logical, optional, intent(in) :: fatalErr\n         logical :: fatalErr_local\n         fatalErr_local = .FALSE.\n         if(present(fatalErr)) fatalErr_local=fatalErr\n         call  get2d_int8(var_name,inv_tmp,ixrt,jxrt,&\n                 trim(fileName), fatalErr=fatalErr_local)\n\n         jj = jxrt\n         do j = 1, jxrt\n             inv(:,j) = inv_tmp(:,jj)\n             jj = jxrt - j\n         end do\n\n     end SUBROUTINE readRT2d_int8\n\n!---------------------------------------------------------\n!DJG -----------------------------------------------------\n\n#ifdef MPP_LAND\n  subroutine MPP_READ_SIMP_GW(IX,JX,IXRT,JXRT,GWSUBBASMSK,gwbasmskfil,&\n          gw_strm_msk,numbasns,ch_netrt,AGGFACTRT)\n\n   USE module_mpp_land\n\n    integer, intent(in)                     :: IX,JX,IXRT,JXRT,AGGFACTRT\n    integer, intent(out)                    :: numbasns\n    integer, intent(out), dimension(IX,JX)  :: GWSUBBASMSK\n    integer, intent(out), dimension(IXRT,JXRT)  :: gw_strm_msk\n    integer, intent(in), dimension(IXRT,JXRT)  :: ch_netrt\n    character(len=*)                      :: gwbasmskfil\n    !integer,dimension(global_nX,global_ny) ::  g_GWSUBBASMSK\n    !yw integer,dimension(global_rt_nx, global_rt_ny) ::  g_gw_strm_msk,g_ch_netrt\n\n    integer,allocatable,dimension(:,:) ::  g_GWSUBBASMSK\n    integer,allocatable,dimension(:, :) ::  g_gw_strm_msk,g_ch_netrt\n\n     if(my_id .eq. IO_id) then\n          allocate(g_gw_strm_msk(global_rt_nx, global_rt_ny))\n          allocate(g_ch_netrt(global_rt_nx, global_rt_ny))\n          allocate(g_GWSUBBASMSK(global_nX,global_ny))\n     else\n          allocate(g_gw_strm_msk(1,1))\n          allocate(g_ch_netrt(1,1))\n          allocate(g_GWSUBBASMSK(1,1))\n     endif\n\n\n     call write_IO_rt_int(ch_netrt,g_ch_netrt)\n\n     if(my_id .eq. IO_id) then\n       call READ_SIMP_GW(global_nX,global_ny,global_rt_nx,global_rt_ny,&\n             g_GWSUBBASMSK,gwbasmskfil,g_gw_strm_msk,numbasns,&\n             g_ch_netrt,AGGFACTRT)\n     endif\n     call decompose_data_int(g_GWSUBBASMSK,GWSUBBASMSK)\n     call decompose_RT_int(g_gw_strm_msk,gw_strm_msk,  &\n          global_rt_nx, global_rt_ny,ixrt,jxrt)\n     call mpp_land_bcast_int1(numbasns)\n\n     if(allocated(g_gw_strm_msk))  deallocate(g_gw_strm_msk)\n     if(allocated(g_ch_netrt)) deallocate(g_ch_netrt)\n     if(allocated(g_GWSUBBASMSK))  deallocate(g_GWSUBBASMSK)\n\n  end subroutine MPP_READ_SIMP_GW\n#endif\n\n!DJG -----------------------------------------------------\n!   SUBROUTINE READ_SIMP_GW\n!DJG -----------------------------------------------------\n\n  subroutine READ_SIMP_GW(IX,JX,IXRT,JXRT,GWSUBBASMSK,gwbasmskfil,&\n          gw_strm_msk,numbasns,ch_netrt,AGGFACTRT)\n    implicit none\n\n    integer, intent(in)                     :: IX,JX,IXRT,JXRT,AGGFACTRT\n    integer, intent(in), dimension(IXRT,JXRT)  :: ch_netrt\n    integer, intent(out)                    :: numbasns\n    integer, intent(out), dimension(IX,JX)  :: GWSUBBASMSK\n    integer, intent(out), dimension(IXRT,JXRT)  :: gw_strm_msk\n    character(len=*)                      :: gwbasmskfil\n    integer                                 :: i,j,aggfacxrt,aggfacyrt,ixxrt,jyyrt\n    integer :: iret, ncid\n    logical :: fexist\n    integer, allocatable, dimension(:,:)  :: GWSUBBASMSK_tmp\n\n    numbasns = 0\n    gw_strm_msk = -9999\n\n    inquire (file=trim(gwbasmskfil), exist=fexist)\n    if(.not. fexist) then\n        call hydro_stop(\"Cound not find file : \"//trim(gwbasmskfil))\n    endif\n\n    iret = nf90_open(trim(gwbasmskfil), NF90_NOWRITE, ncid)\n    if( iret .eq. 0 ) then\n       iret = nf90_close(ncid)\n       print*, \"read gwbasmskfil as nc format: \", trim(gwbasmskfil)\n         allocate(GWSUBBASMSK_tmp(ix,jx))\n         call get2d_int(\"BASIN\",GWSUBBASMSK_tmp,ix,jx,trim(gwbasmskfil), .true.)\n         do j = jx, 1, -1\n              GWSUBBASMSK(:,j) = GWSUBBASMSK_tmp (:,jx-j+1)\n         end do\n         deallocate(GWSUBBASMSK_tmp)\n    else\n       print*, \"read gwbasmskfil as txt format: \", trim(gwbasmskfil)\n       open(unit=18,file=trim(gwbasmskfil),          &\n            form='formatted',status='old')\n       do j=jx,1,-1\n             read (18,*) (GWSUBBASMSK(i,j),i=1,ix)\n       end do\n       close(18)\n    endif\n\n!Loop through to count number of basins and assign basin indices to chan grid\n        do J=1,JX\n          do I=1,IX\n!Determine max number of basins...(assumes basins are numbered\n!   sequentially from 1 to max number of basins...)\n           if (GWSUBBASMSK(i,j).gt.numbasns) then\n             numbasns = GWSUBBASMSK(i,j)   ! get count of basins...\n           end if\n\n!Assign gw basin index values to channel grid...\n           do AGGFACYRT=AGGFACTRT-1,0,-1\n             do AGGFACXRT=AGGFACTRT-1,0,-1\n\n                IXXRT=I*AGGFACTRT-AGGFACXRT\n                JYYRT=J*AGGFACTRT-AGGFACYRT\n                IF(ch_netrt(IXXRT,JYYRT).ge.0) then  !If channel grid cell\n                  gw_strm_msk(IXXRT,JYYRT) = GWSUBBASMSK(i,j)  ! assign coarse grid basn indx to chan grid\n                END IF\n\n              end do !AGGFACXRT\n            end do !AGGFACYRT\n\n         end do   !I-ix\n       end do    !J-jx\n\n#ifdef HYDRO_D\n      write(6,*) \"numbasns = \", numbasns\n#endif\n\n\n!DJG -----------------------------------------------------\n   END SUBROUTINE READ_SIMP_GW\n!DJG -----------------------------------------------------\n\n!Wei Yu\n  subroutine get_gw_strm_msk_lind (ixrt,jxrt,gw_strm_msk,numbasns,basnsInd,gw_strm_msk_lind)\n      implicit none\n      integer, intent(in) :: ixrt,jxrt, numbasns\n      integer, dimension(:,:) :: gw_strm_msk, gw_strm_msk_lind\n      integer(kind=int64), dimension(:) :: basnsInd\n      integer:: i,j,k,bas\n      gw_strm_msk_lind = -999\n      do j = 1, jxrt\n         do i = 1, ixrt\n             if(gw_strm_msk(i,j) .gt. 0) then\n                  do k = 1, numbasns\n                     if(gw_strm_msk(i,j) .eq. basnsInd(k)) then\n                          gw_strm_msk_lind(i,j) = k\n                     endif\n                  end do\n             end if\n         end do\n      end do\n\n  end subroutine get_gw_strm_msk_lind\n\n  subroutine SIMP_GW_IND(ix,jx,GWSUBBASMSK,numbasns,gnumbasns,basnsInd)\n! create an index of basin mask so that it is faster for parallel computation.\n     implicit none\n     integer, intent(in) ::  ix,jx\n     integer, intent(in),dimension(ix,jx) ::  GWSUBBASMSK\n     integer, intent(out):: gnumbasns\n     integer, intent(inout):: numbasns\n     integer(kind=int64), intent(inout),allocatable,dimension(:):: basnsInd\n\n     integer,dimension(numbasns):: tmpbuf\n\n     integer :: i,j,k\n\n\n     gnumbasns = numbasns\n     numbasns = 0\n     tmpbuf = -999.\n\n     do j = 1,jx\n        do i = 1, ix\n           if(GWSUBBASMSK(i,j) .gt.0) then\n                tmpbuf(GWSUBBASMSK(i,j)) = GWSUBBASMSK(i,j)\n           endif\n        end do\n     end do\n     do k = 1, gnumbasns\n         if(tmpbuf(k) .gt. 0) numbasns = numbasns + 1\n     end do\n\n     allocate(basnsInd(numbasns))\n\n     i = 1\n     do k = 1, gnumbasns\n         if(tmpbuf(k) .gt. 0) then\n             basnsInd(i) = tmpbuf(k)\n             i = i + 1\n         endif\n     end do\n#ifdef HYDRO_D\n     write(6,*) \"check numbasns, gnumbasns : \", numbasns, gnumbasns\n#endif\n\n  end subroutine SIMP_GW_IND\n\n  subroutine read_GWBUCKPARM (inFile, numbasns, gnumbasns, basnsInd, &\n                 gw_buck_coeff, gw_buck_exp, gw_buck_loss, &\n                 z_max, z_gwsubbas, bas_id, basns_area)\n! read GWBUCKPARM file\n\n   implicit none\n   integer, intent(in) :: gnumbasns, numbasns\n   integer(kind=int64), intent(in),  dimension(numbasns) :: basnsInd\n   real,    intent(out), dimension(numbasns) :: gw_buck_coeff, gw_buck_exp\n   real,    intent(out), dimension(:), allocatable :: gw_buck_loss\n   real,    intent(out), dimension(numbasns) :: z_max, z_gwsubbas, basns_area\n   integer, intent(out), dimension(numbasns) :: bas_id\n   real, dimension(gnumbasns) :: tmp_buck_coeff, tmp_buck_exp, tmp_buck_loss\n   real, dimension(gnumbasns) :: tmp_z_max, tmp_z_gwsubbas,  tmp_basns_area\n   integer, dimension(gnumbasns) :: tmp_bas_id\n   CHARACTER(len=100)                     :: header\n   CHARACTER(len=1)                       :: jnk\n   character(len=*) :: inFile\n   integer :: bas,k\n   integer :: iret, ncid\n   logical :: fexist\n\n#ifdef MPP_LAND\n   if(my_id .eq. IO_id) then\n#endif\n     inquire (file=trim(inFile), exist=fexist)\n     if(.not. fexist) then\n        call hydro_stop(\"Cound not find file : \"//trim(inFile))\n     endif\n     iret = nf90_open(trim(inFile), NF90_NOWRITE, ncid)\n     if(iret .eq. 0 ) then\n        print*, \"read GWBUCKPARM file as nc format: \" , trim(inFile)\n        call get_1d_netcdf_int(ncid, \"Basin\", tmp_bas_id, \"read GWBUCKPARM\", .true.)\n        call get_1d_netcdf_real(ncid, \"Coeff\",tmp_buck_coeff , \"read GWBUCKPARM\", .true.)\n        call get_1d_netcdf_real(ncid, \"Expon\",tmp_buck_exp   , \"read GWBUCKPARM\", .true.)\n        if(nlst(did)%bucket_loss .eq. 1) then\n           call get_1d_netcdf_real(ncid, \"Loss\",tmp_buck_loss, \"read GWBUCKPARM\", .true.)\n        endif\n        call get_1d_netcdf_real(ncid, \"Zmax\" ,tmp_z_max      , \"read GWBUCKPARM\", .true.)\n        call get_1d_netcdf_real(ncid, \"Zinit\",tmp_z_gwsubbas , \"read GWBUCKPARM\", .true.)\n        call get_1d_netcdf_real(ncid, \"Area_sqkm\",tmp_basns_area , \"read GWBUCKPARM\", .true.)\n        iret = nf90_close(ncid)\n     else\n        !iret = nf90_close(ncid)\n        print*, \"read GWBUCKPARM file as TBL format : \"\n#ifndef NCEP_WCOSS\n!yw        OPEN(81, FILE='GWBUCKPARM.TBL',FORM='FORMATTED',STATUS='OLD')\n        OPEN(81, FILE=trim(inFile),FORM='FORMATTED',STATUS='OLD')\n        read(81,811) header\n#else\n        OPEN(24, FORM='FORMATTED',STATUS='OLD')\n        read(24,811) header\n#endif\n811      FORMAT(A19)\n\n\n#ifndef NCEP_WCOSS\n        do bas = 1,gnumbasns\n           read(81,812) tmp_bas_id(bas),jnk,tmp_buck_coeff(bas),jnk,tmp_buck_exp(bas) , &\n                 jnk,tmp_z_max(bas), jnk,tmp_z_gwsubbas(bas)\n\n        end do\n812       FORMAT(I8,A1,F6.4,A1,F6.3,A1,F6.2,A1,F7.4)\n        close(81)\n#else\n        do bas = 1,gnumbasns\n            read(24,812) tmp_bas_id(bas),jnk,tmp_buck_coeff(bas),jnk,tmp_buck_exp(bas) , &\n                jnk,tmp_z_max(bas), jnk,tmp_z_gwsubbas(bas)\n        end do\n812      FORMAT(I8,A1,F6.4,A1,F6.3,A1,F6.2,A1,F7.4)\n        close(24)\n#endif\n     endif\n#ifdef MPP_LAND\n   endif\n\n   if(gnumbasns .gt. 0 ) then\n      call mpp_land_bcast_real(gnumbasns,tmp_buck_coeff)\n      call mpp_land_bcast_real(gnumbasns,tmp_buck_exp  )\n      if(nlst(did)%bucket_loss .eq. 1) then\n         call mpp_land_bcast_real(gnumbasns,tmp_buck_loss   )\n      endif\n      call mpp_land_bcast_real(gnumbasns,tmp_z_max   )\n      call mpp_land_bcast_real(gnumbasns,tmp_z_gwsubbas   )\n      call mpp_land_bcast_real(gnumbasns,tmp_basns_area   )\n      call mpp_land_bcast_int(gnumbasns,tmp_bas_id)\n   endif\n#endif\n\n    do k = 1, numbasns\n       bas = basnsInd(k)\n       gw_buck_coeff(k) = tmp_buck_coeff(bas)\n       gw_buck_exp(k) = tmp_buck_exp(bas)\n       if(nlst(did)%bucket_loss .eq. 1) then\n          gw_buck_loss(k) = tmp_buck_loss(bas)\n       endif\n       z_max(k) = tmp_z_max(bas)\n       z_gwsubbas(k) = tmp_z_gwsubbas(bas)\n       basns_area(k) = tmp_basns_area(bas)\n       bas_id(k) = tmp_bas_id(bas)\n    end do\n  end subroutine read_GWBUCKPARM\n\n\n\n  ! BF read the static input fields needed for the 2D GW scheme\n  subroutine readGW2d(ix, jx, hc, ihead, botelv, por, ltype, ihShift)\n  implicit none\n  integer, intent(in) :: ix, jx\n  real, intent(in) :: ihShift\n  integer, dimension(ix,jx), intent(inout)::   ltype\n  real, dimension(ix,jx), intent(inout)   ::   hc, ihead, botelv, por\n\n#ifdef MPP_LAND\n  integer, dimension(:,:), allocatable ::  gLtype\n  real, dimension(:,:), allocatable    ::  gHC, gIHEAD, gBOTELV, gPOR\n#endif\n  integer :: i\n\n\n#ifdef MPP_LAND\n  if(my_id .eq. IO_id) then\n      allocate(gHC(global_rt_nx, global_rt_ny))\n      allocate(gIHEAD(global_rt_nx, global_rt_ny))\n      allocate(gBOTELV(global_rt_nx, global_rt_ny))\n      allocate(gPOR(global_rt_nx, global_rt_ny))\n      allocate(gLtype(global_rt_nx, global_rt_ny))\n  else\n      allocate(gHC(1, 1))\n      allocate(gIHEAD(1, 1))\n      allocate(gBOTELV(1, 1))\n      allocate(gPOR(1, 1))\n      allocate(gLtype(1, 1))\n  endif\n\n#ifndef PARALLELIO\n  if(my_id .eq. IO_id) then\n#endif\n#ifdef HYDRO_D\n  print*, \"2D GW-Scheme selected, retrieving files from gwhires.nc ...\"\n#endif\n#endif\n\n\n        ! hydraulic conductivity\n        i = get2d_real(\"HC\", &\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n                       gHC, global_nx, global_ny,  &\n#else\n                       hc, ix, jx,  &\n#endif\n#else\n                       hc, ix, jx,  &\n#endif\n                       trim(\"./gwhires.nc\"))\n\n        ! initial head\n        i = get2d_real(\"IHEAD\", &\n#ifdef MPP_LAND\n                       gIHEAD, global_nx, global_ny, &\n#else\n                       ihead,  ix, jx, &\n#endif\n                       trim(\"./gwhires.nc\"))\n\n        ! aquifer bottom elevation\n        i = get2d_real(\"BOTELV\", &\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n                       gBOTELV, global_nx, global_ny, &\n#else\n                       botelv, ix, jx,  &\n#endif\n#else\n                       botelv, ix, jx,  &\n#endif\n                       trim(\"./gwhires.nc\"))\n\n\t! aquifer porosity\n        i = get2d_real(\"POR\", &\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n                       gPOR, global_nx, global_ny, &\n#else\n                       por, ix, jx,  &\n#endif\n#else\n                       por, ix, jx,  &\n#endif\n                       trim(\"./gwhires.nc\"))\n\n\n\t! groundwater model mask (0 no aquifer, aquifer > 0\n        call get2d_int(\"LTYPE\", &\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n                       gLtype, global_nx, global_ny, &\n#else\n                       ltype, ix, jx, &\n#endif\n#else\n                       ltype, ix, jx,  &\n#endif\n                       trim(\"./gwhires.nc\"))\n\n\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n       gLtype(1,:) = 2\n       gLtype(:,1) = 2\n       gLtype(global_rt_nx,:) = 2\n       gLtype(:,global_rt_ny) = 2\n#else\n! BF TODO parallel io for gw ltype\n#endif\n#else\n       ltype(1,:) = 2\n       ltype(:,1) = 2\n       ltype(ix,:)= 2\n       ltype(:,jx)= 2\n#endif\n\n#ifdef MPP_LAND\n#ifndef PARALLELIO\n  endif\n     call decompose_rt_int (gLtype, ltype, global_rt_nx, global_rt_ny, ix, jx)\n     call decompose_rt_real(gHC,hc,global_rt_nx, global_rt_ny, ix, jx)\n     call decompose_rt_real(gIHEAD,ihead,global_rt_nx, global_rt_ny, ix, jx)\n     call decompose_rt_real(gBOTELV,botelv,global_rt_nx, global_rt_ny, ix, jx)\n     call decompose_rt_real(gPOR,por,global_rt_nx, global_rt_ny, ix, jx)\n     if(allocated(gLtype)) deallocate(gLtype)\n     if(allocated(gHC)) deallocate(gHC)\n     if(allocated(gIHEAD)) deallocate(gIHEAD)\n     if(allocated(gBOTELV)) deallocate(gBOTELV)\n     if(allocated(gPOR)) deallocate(gPOR)\n#endif\n#endif\n\n\n  ihead = ihead + ihShift\n\n  where(ltype .eq. 0)\n   hc = 0.\n!yw   por = 10**21\n   por = 10E21\n  end where\n\n\n  !bftodo: make filename accessible in namelist\n  end subroutine readGW2d\n  !BF\n\n  subroutine output_rt(igrid, split_output_count, ixrt, jxrt, nsoil, &\n       startdate, date, QSUBRT,ZWATTABLRT,SMCRT,SUB_RESID,       &\n       q_sfcflx_x,q_sfcflx_y,soxrt,soyrt,QSTRMVOLRT,SFCHEADSUBRT, &\n       geo_finegrid_flnm,dt,sldpth,LATVAL,LONVAL,dist,CHRTOUT_GRID,  &\n       QBDRYRT,  &\n       io_config_outputs &\n       )\n\n!output the routing variables over routing grid.\n    implicit none\n\n    integer,                                  intent(in) :: igrid\n\n    integer,                                  intent(in) :: io_config_outputs\n    integer,                                  intent(in) :: split_output_count\n    integer,                                  intent(in) :: ixrt,jxrt\n    real,                                     intent(in) :: dt\n    real,                                     intent(in) :: dist(ixrt,jxrt,9)\n    integer,                                  intent(in) :: nsoil\n    integer,                                  intent(in) :: CHRTOUT_GRID\n    character(len=*),                         intent(in) :: startdate\n    character(len=*),                         intent(in) :: date\n    character(len=*),          intent(in)                :: geo_finegrid_flnm\n    real,             dimension(nsoil),       intent(in) :: sldpth\n    real, allocatable, DIMENSION(:,:)                   :: xdumd  !-- decimated variable\n    real*8, allocatable, DIMENSION(:)                   :: xcoord_d\n    real*8, allocatable, DIMENSION(:)                   :: ycoord_d, ycoord\n\n    integer, save :: ncid,ncstatic\n    integer, save :: output_count\n    real,    dimension(nsoil) :: asldpth\n\n    integer :: dimid_ix, dimid_jx, dimid_times, dimid_datelen, varid, n\n    integer :: iret, dimid_soil, i,j,ii,jj\n    character(len=256) :: output_flnm\n    character(len=19)  :: date19\n    character(len=32)  :: convention\n    character(len=34)  :: sec_since_date\n    character(len=34)  :: sec_valid_date\n\n    character(len=30)  :: soilm\n\n    real                                :: long_cm,lat_po,fe,fn, chan_in\n    real, dimension(2)                  :: sp\n\n    real, dimension(ixrt,jxrt) :: xdum,QSUBRT,ZWATTABLRT,SUB_RESID\n    real, dimension(ixrt,jxrt) :: q_sfcflx_x,q_sfcflx_y\n    real, dimension(ixrt,jxrt) :: QSTRMVOLRT\n    real, dimension(ixrt,jxrt) :: SFCHEADSUBRT\n    real, dimension(ixrt,jxrt) :: soxrt,soyrt\n    real, dimension(ixrt,jxrt) :: LATVAL,LONVAL, QBDRYRT\n    real, dimension(ixrt,jxrt,nsoil) :: SMCRT\n\n    character(len=2) :: strTmp\n\n    integer :: seconds_since, decimation, ixrtd,jxrtd, hires_flag\n    sec_since_date = 'seconds since '//date(1:4)//'-'//date(6:7)//'-'//date(9:10)//' '//date(12:13)//':'//date(15:16)//' UTC'\n    seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n    sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                  //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n    decimation = 1 !-- decimation factor\n#ifdef MPP_LAND\n    ixrtd = int(global_rt_nx/decimation)\n    jxrtd = int(global_rt_ny/decimation)\n#else\n    ixrtd = int(ixrt/decimation)\n    jxrtd = int(jxrt/decimation)\n#endif\n\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n       allocate(xdumd(ixrtd,jxrtd))\n       allocate(xcoord_d(ixrtd))\n       allocate(ycoord_d(jxrtd))\n       allocate(ycoord(jxrtd))\n\n       xdumd = -999\n       xcoord_d = -999\n       ycoord_d = -999\n       ycoord = -999\n#ifdef MPP_LAND\n    else\n       allocate(xdumd(1,1))\n       allocate(xcoord_d(1))\n       allocate(ycoord_d(1))\n       allocate(ycoord(1))\n    endif\n#endif\n    ii = 0\n\n!DJG Dump timeseries for channel inflow accum. for calibration...(8/28/09)\n    chan_in = 0.0\n    do j=1,jxrt\n      do i=1,ixrt\n        chan_in=chan_in+QSTRMVOLRT(I,J)/1000.0*(dist(i,j,9))  !(units m^3)\n      enddo\n    enddo\n#ifdef MPP_LAND\n      call sum_real1(chan_in)\n#endif\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n#ifdef NCEP_WCOSS\n       open (unit=54, form='formatted', status='unknown', position='append')\n        write (54,713) chan_in\n       close (54)\n#else\n       if (io_config_outputs .le. 0) then\n         open (unit=46,file='qstrmvolrt_accum.txt',form='formatted',&\n             status='unknown',position='append')\n         write (46,713) chan_in\n         close (46)\n       endif\n#endif\n#ifdef MPP_LAND\n    endif\n#endif\n713 FORMAT (F20.7)\n!    return\n!DJG end dump of channel inflow for calibration....\n\n    if (CHRTOUT_GRID.eq.0) return  ! return if hires flag eq 1, if =2 output full grid\n\n    if (output_count == 0) then\n\n   !-- Open the  finemesh static files to obtain projection information\n#ifdef HYDRO_D\n      write(*,'(\"geo_finegrid_flnm: ''\", A, \"''\")') trim(geo_finegrid_flnm)\n#endif\n\n#ifdef MPP_LAND\n   if(my_id .eq. io_id) then\n#endif\n      iret = nf90_open(trim(geo_finegrid_flnm), NF90_NOWRITE, ncstatic)\n#ifdef MPP_LAND\n   endif\n   call mpp_land_bcast_int1(iret)\n#endif\n\n      if (iret /= 0) then\n         write(*,'(\"Problem opening geo_finegrid file: ''\", A, \"''\")') &\n         trim(geo_finegrid_flnm)\n         write(*,*) \"HIRES_OUTPUT will not be georeferenced...\"\n        hires_flag = 0\n      else\n        hires_flag = 1\n      endif\n\n#ifdef MPP_LAND\n   if(my_id .eq. io_id) then\n#endif\n\n     if(hires_flag.eq.1) then !if/then hires_georef\n      ! Get Latitude (X)\n      iret = NF90_INQ_VARID(ncstatic,'x',varid)\n      if(iret .eq. 0) iret = nf90_get_var(ncstatic, varid, xcoord_d)\n      ! Get Longitude (Y)\n      iret = NF90_INQ_VARID(ncstatic,'y',varid)\n      if(iret .eq. 0) iret = nf90_get_var(ncstatic, varid, ycoord)\n     else\n      ycoord_d = 0.\n      xcoord_d = 0.\n     end if  !endif hires_georef\n\n     jj = 0\n#ifdef MPP_LAND\n     do j=global_rt_ny,1,-1*decimation\n#else\n     do j=jxrt,1,-1*decimation\n#endif\n        jj = jj+1\n        if (jj<= jxrtd) then\n         ycoord_d(jj) = ycoord(j)\n        endif\n     enddo\n\n   if (io_config_outputs .le. 0) then\n     if(hires_flag.eq.1) then !if/then hires_georef\n      ! Get projection information from finegrid netcdf file\n      iret = NF90_INQ_VARID(ncstatic,'lambert_conformal_conic',varid)\n      if(iret .eq. 0) iret = nf90_get_att(ncstatic, varid, 'longitude_of_central_meridian', long_cm)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'latitude_of_projection_origin', lat_po)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'false_easting', fe)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'false_northing', fn)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'standard_parallel', sp)  !-- read it from the static file\n     end if  !endif hires_georef\n      iret = nf90_close(ncstatic)\n   endif\n\n!-- create the fine grid routing file\n       write(output_flnm, '(A12,\".RTOUT_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n#ifdef HYDRO_D\n       print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n       iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n       if (iret /= 0) then\n         call hydro_stop(\"In output_rt() - Problem nf90_create\")\n       endif\n\n       iret = nf90_def_dim(ncid, \"time\", NF90_UNLIMITED, dimid_times)\n       iret = nf90_def_dim(ncid, \"x\", ixrtd, dimid_ix)  !-- make a decimated grid\n       iret = nf90_def_dim(ncid, \"y\", jxrtd, dimid_jx)\n     if (io_config_outputs .le. 0) then\n       iret = nf90_def_dim(ncid, \"depth\", nsoil, dimid_soil)  !-- 3-d soils\n     endif\n\n!--- define variables\n!     !- time definition, timeObs\n         iret = nf90_def_var(ncid, \"time\", NF90_INT, (/dimid_times/), varid)\n         iret = nf90_put_att(ncid, varid, 'long_name', 'valid output time')\n         iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n\nif (io_config_outputs .le. 0) then\n       !- x-coordinate in cartesian system\n        iret = nf90_def_var(ncid, \"x\", NF90_DOUBLE, (/dimid_ix/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'x coordinate of projection')\n        iret = nf90_put_att(ncid, varid, 'standard_name', 'projection_x_coordinate')\n        iret = nf90_put_att(ncid, varid, 'units', 'Meter')\n\n       !- y-coordinate in cartesian ssystem\n          iret = nf90_def_var(ncid, \"y\", NF90_DOUBLE, (/dimid_jx/), varid)\n          iret = nf90_put_att(ncid, varid, 'long_name', 'y coordinate of projection')\n          iret = nf90_put_att(ncid, varid, 'standard_name', 'projection_y_coordinate')\n          iret = nf90_put_att(ncid, varid, 'units', 'Meter')\n\n       !- LATITUDE\n        iret = nf90_def_var(ncid, \"LATITUDE\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'LATITUDE')\n        iret = nf90_put_att(ncid, varid, 'standard_name', 'LATITUDE')\n        iret = nf90_put_att(ncid, varid, 'units', 'deg North')\n\n       !- LONGITUDE\n          iret = nf90_def_var(ncid, \"LONGITUDE\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          iret = nf90_put_att(ncid, varid, 'long_name', 'LONGITUDE')\n          iret = nf90_put_att(ncid, varid, 'standard_name', 'LONGITUDE')\n          iret = nf90_put_att(ncid, varid, 'units', 'deg east')\n\n       !-- z-level is soil\n        iret = nf90_def_var(ncid, \"depth\", NF90_FLOAT, (/dimid_soil/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'cm')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'depth of soil layer')\n\n         do n = 1, NSOIL\n             write(strTmp,'(I2)') n\n             iret = nf90_def_var(ncid, \"SOIL_M\"//trim(strTmp), NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n         end do\n            iret = nf90_put_att(ncid, varid, 'units', 'm^3/m^3')\n            iret = nf90_put_att(ncid, varid, 'description', 'moisture content')\n            iret = nf90_put_att(ncid, varid, 'long_name', soilm)\n!           iret = nf90_put_att(ncid, varid, 'coordinates', 'x y z')\n            iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n            iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n!      iret = nf90_def_var(ncid, \"ESNOW2D\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n\n!       iret = nf90_def_var(ncid, \"QSUBRT\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n!       iret = nf90_put_att(ncid, varid, 'units', 'm3 s-1')\n!       iret = nf90_put_att(ncid, varid, 'long_name', 'subsurface flow')\n!       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n!       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n!       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\nendif\n\n! All but long range\nif ( io_config_outputs .ne. 4 ) then\n\n   iret = nf90_def_var(ncid, \"zwattablrt\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n   iret = nf90_put_att(ncid, varid, 'units', 'm')\n   iret = nf90_put_att(ncid, varid, 'long_name', 'water table depth')\n   iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n   iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n   iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n   !iret = nf90_def_var(ncid, \"Q_SFCFLX_X\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n   !iret = nf90_put_att(ncid, varid, 'units', 'm3 s-1')\n   !iret = nf90_put_att(ncid, varid, 'long_name', 'surface flux x')\n   !iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n   !iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n   !iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n   !iret = nf90_def_var(ncid, \"Q_SFCFLX_Y\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n   !iret = nf90_put_att(ncid, varid, 'units', 'm3 s-1')\n   !iret = nf90_put_att(ncid, varid, 'long_name', 'surface flux y')\n   !iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n   !iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n   !iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n   iret = nf90_def_var(ncid, \"sfcheadsubrt\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n   iret = nf90_put_att(ncid, varid, 'units', 'mm')\n   iret = nf90_put_att(ncid, varid, 'long_name', 'surface head')\n   iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n   iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n   iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\nendif\n\nif (io_config_outputs .le. 0) then\n       iret = nf90_def_var(ncid, \"QSTRMVOLRT\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'mm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'accum channel inflow')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n!      iret = nf90_def_var(ncid, \"SOXRT\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n!      iret = nf90_put_att(ncid, varid, 'units', '1')\n!      iret = nf90_put_att(ncid, varid, 'long_name', 'slope x')\n!      iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n!      iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n!      iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n!      iret = nf90_def_var(ncid, \"SOYRT\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n!      iret = nf90_put_att(ncid, varid, 'units', '1')\n!      iret = nf90_put_att(ncid, varid, 'long_name', 'slope 7')\n!      iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n!      iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n!      iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n!       iret = nf90_def_var(ncid, \"SUB_RESID\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n\n       iret = nf90_def_var(ncid, \"QBDRYRT\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'mm')\n       iret = nf90_put_att(ncid,varid,'long_name',&\n          'accumulated value of the boundary flux, + into domain, - out of domain')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n!-- place projection information\n     if(hires_flag.eq.1) then !if/then hires_georef\n      iret = nf90_def_var(ncid, \"lambert_conformal_conic\", NF90_INT, 0, varid)\n      iret = nf90_put_att(ncid, varid, 'grid_mapping_name', 'lambert_conformal_conic')\n      iret = nf90_put_att(ncid, varid, 'longitude_of_central_meridian', long_cm)\n      iret = nf90_put_att(ncid, varid, 'latitude_of_projection_origin', lat_po)\n      iret = nf90_put_att(ncid, varid, 'false_easting', fe)\n      iret = nf90_put_att(ncid, varid, 'false_northing', fn)\n      iret = nf90_put_att(ncid, varid, 'standard_parallel', sp)\n     end if   !endif hires_georef\nendif\n\n!      iret = nf90_def_var(ncid, \"Date\", NF90_CHAR, (/dimid_datelen,dimid_times/), varid)\n\n      date19(1:19) = \"0000-00-00_00:00:00\"\n      date19(1:len_trim(startdate)) = startdate\n      convention(1:32) = \"CF-1.0\"\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"output_decimation_factor\", decimation)\n\n       ! iret = nf90_redef(ncid)\n       iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n       ! iret = nf90_enddef(ncid)\n\n      iret = nf90_enddef(ncid)\n\nif (io_config_outputs .le. 0) then\n!!-- write latitude and longitude locations\n         iret = nf90_inq_varid(ncid,\"x\", varid)\n         iret = nf90_put_var(ncid, varid, xcoord_d, (/1/), (/ixrtd/)) !-- 1-d array\n\n         iret = nf90_inq_varid(ncid,\"y\", varid)\n         iret = nf90_put_var(ncid, varid, ycoord_d, (/1/), (/jxrtd/)) !-- 1-d array\nendif\n\n#ifdef MPP_LAND\n    endif\n#endif\n\niret = nf90_inq_varid(ncid,\"time\", varid)\niret = nf90_put_var(ncid, varid, seconds_since, (/1/))\n\nif (io_config_outputs .le. 0) then\n#ifdef MPP_LAND\n        call write_IO_rt_real(LATVAL,xdumd)\n    if( my_id .eq. io_id) then\n#else\n        xdumd = LATVAL\n#endif\n        iret = nf90_inq_varid(ncid,\"LATITUDE\", varid)\n        iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n\n\n#ifdef MPP_LAND\n    endif   !!! end if block of my_id .eq. io_id\n\n        call write_IO_rt_real(LONVAL,xdumd)\n\n    if( my_id .eq. io_id) then\n#else\n        xdumd = LONVAL\n#endif\n        iret = nf90_inq_varid(ncid,\"LONGITUDE\", varid)\n        iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n\n#ifdef MPP_LAND\n    endif\n\n    if( my_id .eq. io_id) then\n#endif\n\n       do n = 1,nsoil\n        if(n == 1) then\n         asldpth(n) = -sldpth(n)\n        else\n         asldpth(n) = asldpth(n-1) - sldpth(n)\n        endif\n       enddo\n\n       iret = nf90_inq_varid(ncid,\"depth\", varid)\n       iret = nf90_put_var(ncid, varid, asldpth, (/1/), (/nsoil/))\n!yw       iret = nf90_close(ncstatic)\n#ifdef MPP_LAND\n    endif  ! end of my_id .eq. io_id\n#endif\nendif\n\n   endif !!! end of if block output_count == 0\n    output_count = output_count + 1\n\nif (io_config_outputs .le. 0) then\n!-- 3-d soils\n     do n = 1, nsoil\n#ifdef MPP_LAND\n          call write_IO_rt_real(smcrt(:,:,n),xdumd)\n#else\n          xdumd(:,:) = smcrt(:,:,n)\n#endif\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n          write(strTmp,'(I2)') n\n          iret = nf90_inq_varid(ncid,  \"SOIL_M\"//trim(strTmp), varid)\n          iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n#ifdef MPP_LAND\n    endif\n#endif\n    enddo !-n soils\nendif\n\n! All but long range\nif ( (io_config_outputs .ge. 0) .and. (io_config_outputs .ne. 4) ) then\n#ifdef MPP_LAND\n   call write_IO_rt_real(ZWATTABLRT,xdumd)\n#else\n   xdumd(:,:) = ZWATTABLRT(:,:)\n#endif\n#ifdef MPP_LAND\n   if (my_id .eq. io_id) then\n#endif\n      iret = nf90_inq_varid(ncid,  \"zwattablrt\", varid)\n      iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n#ifdef MPP_LAND\n   endif\n#endif\nendif\n\nif (io_config_outputs .le. 0) then\n#ifdef MPP_LAND\n          call write_IO_rt_real(QBDRYRT,xdumd)\n#else\n          xdumd(:,:) = QBDRYRT(:,:)\n#endif\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n     iret = nf90_inq_varid(ncid,  \"QBDRYRT\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n#ifdef MPP_LAND\n     endif\n#endif\n\n#ifdef MPP_LAND\n          call write_IO_rt_real(QSTRMVOLRT,xdumd)\n#else\n          xdumd(:,:) = QSTRMVOLRT(:,:)\n#endif\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n     iret = nf90_inq_varid(ncid,  \"QSTRMVOLRT\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n#ifdef MPP_LAND\n     endif\n#endif\nendif\n\n! All but long range\nif ( io_config_outputs .ne. 4 ) then\n#ifdef MPP_LAND\n   call write_IO_rt_real(SFCHEADSUBRT,xdumd)\n#else\n   xdumd(:,:) = SFCHEADSUBRT(:,:)\n#endif\n#ifdef MPP_LAND\n   if (my_id .eq. io_id) then\n#endif\n      iret = nf90_inq_varid(ncid,  \"sfcheadsubrt\", varid)\n      iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n#ifdef MPP_LAND\n   endif\n#endif\nendif\n\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n\n\n!yw      iret = nf90_sync(ncid)\n      if (output_count == split_output_count) then\n        output_count = 0\n        iret = nf90_close(ncid)\n      endif\n#ifdef MPP_LAND\n     endif\n     call mpp_land_bcast_int1(output_count)\n#endif\n\n     if(allocated(xdumd))  deallocate(xdumd)\n     if(allocated(xcoord_d))  deallocate(xcoord_d)\n     if(allocated(ycoord_d)) deallocate(ycoord_d)\n     if(allocated(ycoord))  deallocate(ycoord)\n\n#ifdef HYDRO_D\n     write(6,*) \"end of output_rt\"\n#endif\n\n  end subroutine output_rt\n\n\n!BF output section for gw2d model\n!bftodo: clean up an customize for GW usage\n\n  subroutine output_gw_spinup(igrid, split_output_count, ixrt, jxrt, &\n       startdate, date, HEAD, convgw, excess, &\n       geo_finegrid_flnm,dt,LATVAL,LONVAL,dist,output_gw)\n\n#ifdef MPP_LAND\n       USE module_mpp_land\n#endif\n!output the routing variables over routing grid.\n    implicit none\n\n    integer,                                  intent(in) :: igrid\n    integer,                                  intent(in) :: split_output_count\n    integer,                                  intent(in) :: ixrt,jxrt\n    real,                                     intent(in) :: dt\n    real,                                     intent(in) :: dist(ixrt,jxrt,9)\n    integer,                                  intent(in) ::  output_gw\n    character(len=*),                         intent(in) :: startdate\n    character(len=*),                         intent(in) :: date\n    character(len=*),          intent(in)                :: geo_finegrid_flnm\n    real, allocatable, DIMENSION(:,:)                   :: xdumd  !-- decimated variable\n    real*8, allocatable, DIMENSION(:)                   :: xcoord_d, xcoord\n    real*8, allocatable, DIMENSION(:)                   :: ycoord_d, ycoord\n\n    integer, save :: ncid,ncstatic\n    integer, save :: output_count\n\n    integer :: dimid_ix, dimid_jx, dimid_times, dimid_datelen, varid, n\n    integer :: iret, dimid_soil, i,j,ii,jj\n    character(len=256) :: output_flnm\n    character(len=19)  :: date19\n    character(len=32)  :: convention\n    character(len=34)  :: sec_since_date\n    character(len=34)  :: sec_valid_date\n\n    character(len=30)  :: soilm\n\n    real                                :: long_cm,lat_po,fe,fn, chan_in\n    real, dimension(2)                  :: sp\n\n    real, dimension(ixrt,jxrt) :: head, convgw, excess, &\n                                  latval, lonval\n\n    integer :: seconds_since, decimation, ixrtd,jxrtd, hires_flag\n\n#ifdef MPP_LAND\n    real, dimension(global_rt_nx,global_rt_ny) :: gHead, gConvgw, gExcess\n    real, dimension(global_rt_nx,global_rt_ny) :: gLatval, gLonval\n#endif\n\n#ifdef MPP_LAND\n    call MPP_LAND_COM_REAL(convgw, ixrt, jxrt, 99)\n    call write_IO_rt_real(latval,gLatval)\n    call write_IO_rt_real(lonval,gLonval)\n    call write_IO_rt_real(head,gHead)\n    call write_IO_rt_real(convgw,gConvgw)\n    call write_IO_rt_real(excess,gExcess)\n\n\n   if(my_id.eq.IO_id) then\n\n\n#endif\n    seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n    sec_since_date = 'seconds since '//date(1:4)//'-'//date(6:7)//'-'//date(9:10)//' '//date(12:13)//':'//date(15:16)//' UTC'\n    sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                  //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n    decimation = 1 !-- decimation factor\n#ifdef MPP_LAND\n    ixrtd = int(global_rt_nx/decimation)\n    jxrtd = int(global_rt_ny/decimation)\n#else\n    ixrtd = int(ixrt/decimation)\n    jxrtd = int(jxrt/decimation)\n#endif\n    allocate(xdumd(ixrtd,jxrtd))\n    allocate(xcoord_d(ixrtd))\n    allocate(ycoord_d(jxrtd))\n    allocate(xcoord(ixrtd))\n    allocate(ycoord(jxrtd))\n    ii = 0\n    jj = 0\n\n    if (output_gw.eq.0) return  ! return if hires flag eq 0, if =1 output full grid\n\n    if (output_count == 0) then\n\n   !-- Open the  finemesh static files to obtain projection information\n#ifdef HYDRO_D\n      write(*,'(\"geo_finegrid_flnm: ''\", A, \"''\")') trim(geo_finegrid_flnm)\n\n#endif\n      iret = nf90_open(trim(geo_finegrid_flnm), NF90_NOWRITE, ncstatic)\n\n      if (iret /= 0) then\n#ifdef HYDRO_D\n         write(*,'(\"Problem opening geo_finegrid file: ''\", A, \"''\")') &\n         trim(geo_finegrid_flnm)\n         write(*,*) \"HIRES_OUTPUT will not be georeferenced...\"\n#endif\n        hires_flag = 0\n      else\n        hires_flag = 1\n      endif\n\n     if(hires_flag.eq.1) then !if/then hires_georef\n      ! Get Latitude (X)\n      iret = NF90_INQ_VARID(ncstatic,'x',varid)\n      if(iret .eq. 0) iret = nf90_get_var(ncstatic, varid, xcoord)\n      ! Get Longitude (Y)\n      iret = NF90_INQ_VARID(ncstatic,'y',varid)\n      if(iret .eq. 0) iret = nf90_get_var(ncstatic, varid, ycoord)\n     else\n      xcoord_d = 0.\n      ycoord_d = 0.\n     end if  !endif hires_georef\n\n     do j=jxrtd,1,-1*decimation\n        jj = jj+1\n        if (jj<= jxrtd) then\n         ycoord_d(jj) = ycoord(j)\n        endif\n     enddo\n\n!yw     do i = 1,ixrt,decimation\n!yw        ii = ii + 1\n!yw        if (ii <= ixrtd) then\n!yw         xcoord_d(ii) = xcoord(i)\n         xcoord_d = xcoord\n!yw        endif\n!yw     enddo\n\n\n     if(hires_flag.eq.1) then !if/then hires_georef\n      ! Get projection information from finegrid netcdf file\n      iret = NF90_INQ_VARID(ncstatic,'lambert_conformal_conic',varid)\n      if(iret .eq. 0) iret = nf90_get_att(ncstatic, varid, 'longitude_of_central_meridian', long_cm)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'latitude_of_projection_origin', lat_po)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'false_easting', fe)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'false_northing', fn)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'standard_parallel', sp)  !-- read it from the static file\n     end if  !endif hires_georef\n      iret = nf90_close(ncstatic)\n\n!-- create the fine grid routing file\n       write(output_flnm, '(A12,\".GW_SPINUP\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n#ifdef HYDRO_D\n       print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n\n       iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n       if (iret /= 0) then\n         call hydro_stop(\"In output_gw_spinup() - Problem nf90_create\")\n       endif\n\n       iret = nf90_def_dim(ncid, \"time\", NF90_UNLIMITED, dimid_times)\n       iret = nf90_def_dim(ncid, \"x\", ixrtd, dimid_ix)  !-- make a decimated grid\n       iret = nf90_def_dim(ncid, \"y\", jxrtd, dimid_jx)\n\n!--- define variables\n       !- time definition, timeObs\n       iret = nf90_def_var(ncid, \"time\", NF90_INT, (/dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n\n       !- x-coordinate in cartesian system\n       iret = nf90_def_var(ncid, \"x\", NF90_DOUBLE, (/dimid_ix/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'x coordinate of projection')\n       iret = nf90_put_att(ncid, varid, 'standard_name', 'projection_x_coordinate')\n       iret = nf90_put_att(ncid, varid, 'units', 'Meter')\n\n       !- y-coordinate in cartesian ssystem\n       iret = nf90_def_var(ncid, \"y\", NF90_DOUBLE, (/dimid_jx/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'y coordinate of projection')\n       iret = nf90_put_att(ncid, varid, 'standard_name', 'projection_y_coordinate')\n       iret = nf90_put_att(ncid, varid, 'units', 'Meter')\n\n       !- LATITUDE\n       iret = nf90_def_var(ncid, \"LATITUDE\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'LATITUDE')\n       iret = nf90_put_att(ncid, varid, 'standard_name', 'LATITUDE')\n       iret = nf90_put_att(ncid, varid, 'units', 'deg North')\n\n       !- LONGITUDE\n       iret = nf90_def_var(ncid, \"LONGITUDE\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'LONGITUDE')\n       iret = nf90_put_att(ncid, varid, 'standard_name', 'LONGITUDE')\n       iret = nf90_put_att(ncid, varid, 'units', 'deg east')\n\n\n       iret = nf90_def_var(ncid, \"GwHead\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'groundwater head')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n       iret = nf90_def_var(ncid, \"GwConv\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'mm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'groundwater convergence')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n       iret = nf90_def_var(ncid, \"GwExcess\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'surface excess groundwater')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n!-- place projection information\n     if(hires_flag.eq.1) then !if/then hires_georef\n      iret = nf90_def_var(ncid, \"lambert_conformal_conic\", NF90_INT, 0, varid)\n      iret = nf90_put_att(ncid, varid, 'grid_mapping_name', 'lambert_conformal_conic')\n      iret = nf90_put_att(ncid, varid, 'longitude_of_central_meridian', long_cm)\n      iret = nf90_put_att(ncid, varid, 'latitude_of_projection_origin', lat_po)\n      iret = nf90_put_att(ncid, varid, 'false_easting', fe)\n      iret = nf90_put_att(ncid, varid, 'false_northing', fn)\n      iret = nf90_put_att(ncid, varid, 'standard_parallel', sp)\n     end if   !endif hires_georef\n\n!      iret = nf90_def_var(ncid, \"Date\", NF90_CHAR, (/dimid_datelen,dimid_times/), varid)\n\n      date19(1:19) = \"0000-00-00_00:00:00\"\n      date19(1:len_trim(startdate)) = startdate\n      convention(1:32) = \"CF-1.0\"\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"output_decimation_factor\", decimation)\n\n      iret = nf90_enddef(ncid)\n\n!!-- write latitude and longitude locations\n!       xdumd = LATVAL\n        iret = nf90_inq_varid(ncid,\"x\", varid)\n!       iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n\tiret = nf90_put_var(ncid, varid, xcoord_d, (/1/), (/ixrtd/)) !-- 1-d array\n\n!       xdumd = LONVAL\n        iret = nf90_inq_varid(ncid,\"y\", varid)\n!       iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n        iret = nf90_put_var(ncid, varid, ycoord_d, (/1/), (/jxrtd/)) !-- 1-d array\n\n#ifdef MPP_LAND\n        xdumd = gLATVAL\n#else\n        xdumd = LATVAL\n#endif\n        iret = nf90_inq_varid(ncid,\"LATITUDE\", varid)\n        iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n\n#ifdef MPP_LAND\n        xdumd = gLONVAL\n#else\n        xdumd = LONVAL\n#endif\n        iret = nf90_inq_varid(ncid,\"LONGITUDE\", varid)\n        iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n\n\n    endif\n\n    output_count = output_count + 1\n\n!!-- time\n        iret = nf90_inq_varid(ncid,\"time\", varid)\n        iret = nf90_put_var(ncid, varid, seconds_since, (/output_count/))\n\n\n#ifdef MPP_LAND\n        xdumd = gHead\n#else\n        xdumd = head\n#endif\n\n     iret = nf90_inq_varid(ncid,  \"GwHead\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n\n#ifdef MPP_LAND\n        xdumd = gConvgw\n#else\n        xdumd = convgw\n#endif\n     iret = nf90_inq_varid(ncid,  \"GwConv\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n\n\n#ifdef MPP_LAND\n     xdumd = gExcess\n#else\n     xdumd = excess\n#endif\n     iret = nf90_inq_varid(ncid,  \"GwExcess\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n\n\n!!time in seconds since startdate\n\n     iret = nf90_redef(ncid)\n     date19(1:len_trim(date)) = date\n     iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n     iret = nf90_enddef(ncid)\n     iret = nf90_sync(ncid)\n     if (output_count == split_output_count) then\n        output_count = 0\n        iret = nf90_close(ncid)\n     endif\n\n     if(allocated(xdumd))  deallocate(xdumd)\n     if(allocated(xcoord_d)) deallocate(xcoord_d)\n     if(allocated(xcoord)) deallocate(xcoord)\n     if(allocated(ycoord_d)) deallocate(ycoord_d)\n     if(allocated(ycoord)) deallocate(ycoord)\n\n#ifdef MPP_LAND\n    endif\n#endif\n\n  end subroutine output_gw_spinup\n\n\nsubroutine sub_output_gw(igrid, split_output_count, ixrt, jxrt, nsoil, &\n       startdate, date, HEAD, SMCRT, convgw, excess, qsgwrt, qgw_chanrt, &\n       geo_finegrid_flnm,dt,sldpth,LATVAL,LONVAL,dist,output_gw)\n\n#ifdef MPP_LAND\n       USE module_mpp_land\n#endif\n!output the routing variables over routing grid.\n    implicit none\n\n    integer,                                  intent(in) :: igrid\n    integer,                                  intent(in) :: split_output_count\n    integer,                                  intent(in) :: ixrt,jxrt\n    real,                                     intent(in) :: dt\n    real,                                     intent(in) :: dist(ixrt,jxrt,9)\n    integer,                                  intent(in) :: nsoil\n    integer,                                  intent(in) ::  output_gw\n    character(len=*),                         intent(in) :: startdate\n    character(len=*),                         intent(in) :: date\n    character(len=*),          intent(in)                :: geo_finegrid_flnm\n    real,             dimension(nsoil),       intent(in) :: sldpth\n    real, allocatable, DIMENSION(:,:)                   :: xdumd  !-- decimated variable\n    real*8, allocatable, DIMENSION(:)                   :: xcoord_d, xcoord\n    real*8, allocatable, DIMENSION(:)                   :: ycoord_d, ycoord\n\n    integer, save :: ncid,ncstatic\n    integer, save :: output_count\n    real,    dimension(nsoil) :: asldpth\n\n    integer :: dimid_ix, dimid_jx, dimid_times, dimid_datelen, varid, n\n    integer :: iret, dimid_soil, i,j,ii,jj\n    character(len=256) :: output_flnm\n    character(len=19)  :: date19\n    character(len=32)  :: convention\n    character(len=34)  :: sec_since_date\n    character(len=34)  :: sec_valid_date\n\n    character(len=30)  :: soilm\n\n    real                                :: long_cm,lat_po,fe,fn, chan_in\n    real, dimension(2)                  :: sp\n\n    real, dimension(ixrt,jxrt) :: head, convgw, excess, &\n                                  qsgwrt, qgw_chanrt, &\n                                  latval, lonval\n    real, dimension(ixrt,jxrt,nsoil) :: SMCRT\n\n    integer :: seconds_since, decimation, ixrtd,jxrtd, hires_flag\n\n#ifdef MPP_LAND\n    real, dimension(global_rt_nx,global_rt_ny) :: gHead, gConvgw, gqsgwrt, gExcess, &\n                                                  gQgw_chanrt\n    real, dimension(global_rt_nx,global_rt_ny) :: gLatval, gLonval\n    real, dimension(global_rt_nx,global_rt_ny,nsoil) :: gSMCRT\n#endif\n\n#ifdef MPP_LAND\n    call MPP_LAND_COM_REAL(convgw, ixrt, jxrt, 99)\n    call MPP_LAND_COM_REAL(qsgwrt, ixrt, jxrt, 99)\n    call MPP_LAND_COM_REAL(qgw_chanrt, ixrt, jxrt, 99)\n    call write_IO_rt_real(latval,gLatval)\n    call write_IO_rt_real(lonval,gLonval)\n    call write_IO_rt_real(qsgwrt,gqsgwrt)\n    call write_IO_rt_real(qgw_chanrt,gQgw_chanrt)\n    call write_IO_rt_real(head,gHead)\n    call write_IO_rt_real(convgw,gConvgw)\n    call write_IO_rt_real(excess,gExcess)\n\n    do i = 1, NSOIL\n     call MPP_LAND_COM_REAL(smcrt(:,:,i), ixrt, jxrt, 99)\n     call write_IO_rt_real(SMCRT(:,:,i),gSMCRT(:,:,i))\n    end do\n\n   if(my_id.eq.IO_id) then\n\n\n#endif\n    seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n    sec_since_date = 'seconds since '//date(1:4)//'-'//date(6:7)//'-'//date(9:10)//' '//date(12:13)//':'//date(15:16)//' UTC'\n    sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                  //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n    decimation = 1 !-- decimation factor\n#ifdef MPP_LAND\n    ixrtd = int(global_rt_nx/decimation)\n    jxrtd = int(global_rt_ny/decimation)\n#else\n    ixrtd = int(ixrt/decimation)\n    jxrtd = int(jxrt/decimation)\n#endif\n    allocate(xdumd(ixrtd,jxrtd))\n    allocate(xcoord_d(ixrtd))\n    allocate(ycoord_d(jxrtd))\n    allocate(xcoord(ixrtd))\n    allocate(ycoord(jxrtd))\n    ii = 0\n    jj = 0\n\n    if (output_gw.eq.0) return  ! return if hires flag eq 0, if =1 output full grid\n\n    if (output_count == 0) then\n\n   !-- Open the  finemesh static files to obtain projection information\n#ifdef HYDRO_D\n      write(*,'(\"geo_finegrid_flnm: ''\", A, \"''\")') trim(geo_finegrid_flnm)\n\n#endif\n      iret = nf90_open(trim(geo_finegrid_flnm), NF90_NOWRITE, ncstatic)\n\n      if (iret /= 0) then\n#ifdef HYDRO_D\n         write(*,'(\"Problem opening geo_finegrid file: ''\", A, \"''\")') &\n         trim(geo_finegrid_flnm)\n         write(*,*) \"HIRES_OUTPUT will not be georeferenced...\"\n#endif\n        hires_flag = 0\n      else\n        hires_flag = 1\n      endif\n\n     if(hires_flag.eq.1) then !if/then hires_georef\n      ! Get Latitude (X)\n      iret = NF90_INQ_VARID(ncstatic,'x',varid)\n      if(iret .eq. 0) iret = nf90_get_var(ncstatic, varid, xcoord)\n      ! Get Longitude (Y)\n      iret = NF90_INQ_VARID(ncstatic,'y',varid)\n      if(iret .eq. 0) iret = nf90_get_var(ncstatic, varid, ycoord)\n     else\n      xcoord_d = 0.\n      ycoord_d = 0.\n     end if  !endif hires_georef\n\n     do j=jxrtd,1,-1*decimation\n        jj = jj+1\n        if (jj<= jxrtd) then\n         ycoord_d(jj) = ycoord(j)\n        endif\n     enddo\n\n!yw     do i = 1,ixrt,decimation\n!yw        ii = ii + 1\n!yw        if (ii <= ixrtd) then\n!yw         xcoord_d(ii) = xcoord(i)\n         xcoord_d = xcoord\n!yw        endif\n!yw     enddo\n\n\n     if(hires_flag.eq.1) then !if/then hires_georef\n      ! Get projection information from finegrid netcdf file\n      iret = NF90_INQ_VARID(ncstatic,'lambert_conformal_conic',varid)\n      if(iret .eq. 0) iret = nf90_get_att(ncstatic, varid, 'longitude_of_central_meridian', long_cm)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'latitude_of_projection_origin', lat_po)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'false_easting', fe)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'false_northing', fn)  !-- read it from the static file\n      iret = nf90_get_att(ncstatic, varid, 'standard_parallel', sp)  !-- read it from the static file\n     end if  !endif hires_georef\n      iret = nf90_close(ncstatic)\n\n!-- create the fine grid routing file\n       write(output_flnm, '(A12,\".GW_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n#ifdef HYDRO_D\n       print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n\n       iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n       if (iret /= 0) then\n         call hydro_stop(\"In output_gw_spinup() - Problem nf90_create\")\n       endif\n\n       iret = nf90_def_dim(ncid, \"time\", NF90_UNLIMITED, dimid_times)\n       iret = nf90_def_dim(ncid, \"x\", ixrtd, dimid_ix)  !-- make a decimated grid\n       iret = nf90_def_dim(ncid, \"y\", jxrtd, dimid_jx)\n       iret = nf90_def_dim(ncid, \"depth\", nsoil, dimid_soil)  !-- 3-d soils\n\n!--- define variables\n       !- time definition, timeObs\n       iret = nf90_def_var(ncid, \"time\", NF90_INT, (/dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n\n       !- x-coordinate in cartesian system\n       iret = nf90_def_var(ncid, \"x\", NF90_DOUBLE, (/dimid_ix/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'x coordinate of projection')\n       iret = nf90_put_att(ncid, varid, 'standard_name', 'projection_x_coordinate')\n       iret = nf90_put_att(ncid, varid, 'units', 'Meter')\n\n       !- y-coordinate in cartesian ssystem\n       iret = nf90_def_var(ncid, \"y\", NF90_DOUBLE, (/dimid_jx/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'y coordinate of projection')\n       iret = nf90_put_att(ncid, varid, 'standard_name', 'projection_y_coordinate')\n       iret = nf90_put_att(ncid, varid, 'units', 'Meter')\n\n       !- LATITUDE\n       iret = nf90_def_var(ncid, \"LATITUDE\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'LATITUDE')\n       iret = nf90_put_att(ncid, varid, 'standard_name', 'LATITUDE')\n       iret = nf90_put_att(ncid, varid, 'units', 'deg North')\n\n       !- LONGITUDE\n       iret = nf90_def_var(ncid, \"LONGITUDE\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'LONGITUDE')\n       iret = nf90_put_att(ncid, varid, 'standard_name', 'LONGITUDE')\n       iret = nf90_put_att(ncid, varid, 'units', 'deg east')\n\n       !-- z-level is soil\n       iret = nf90_def_var(ncid, \"depth\", NF90_FLOAT, (/dimid_soil/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'cm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'depth of soil layer')\n\n       iret = nf90_def_var(ncid, \"SOIL_M\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_soil,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'kg m-2')\n       iret = nf90_put_att(ncid, varid, 'description', 'moisture content')\n       iret = nf90_put_att(ncid, varid, 'long_name', soilm)\n!      iret = nf90_put_att(ncid, varid, 'coordinates', 'x y z')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n       iret = nf90_def_var(ncid, \"HEAD\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'groundwater head')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n       iret = nf90_def_var(ncid, \"CONVGW\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'mm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'channel flux')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n       iret = nf90_def_var(ncid, \"GwExcess\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'mm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'surface excess groundwater')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n       iret = nf90_def_var(ncid, \"QSGWRT\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'mm')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'surface head')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n       iret = nf90_def_var(ncid, \"QGW_CHANRT\", NF90_FLOAT, (/dimid_ix,dimid_jx,dimid_times/), varid)\n       iret = nf90_put_att(ncid, varid, 'units', 'm3 s-1')\n       iret = nf90_put_att(ncid, varid, 'long_name', 'surface head')\n       iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n       iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n       iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n!-- place projection information\n     if(hires_flag.eq.1) then !if/then hires_georef\n      iret = nf90_def_var(ncid, \"lambert_conformal_conic\", NF90_INT, 0, varid)\n      iret = nf90_put_att(ncid, varid, 'grid_mapping_name', 'lambert_conformal_conic')\n      iret = nf90_put_att(ncid, varid, 'longitude_of_central_meridian', long_cm)\n      iret = nf90_put_att(ncid, varid, 'latitude_of_projection_origin', lat_po)\n      iret = nf90_put_att(ncid, varid, 'false_easting', fe)\n      iret = nf90_put_att(ncid, varid, 'false_northing', fn)\n      iret = nf90_put_att(ncid, varid, 'standard_parallel', sp)\n     end if   !endif hires_georef\n\n!      iret = nf90_def_var(ncid, \"Date\", NF90_CHAR, (/dimid_datelen,dimid_times/), varid)\n\n      date19(1:19) = \"0000-00-00_00:00:00\"\n      date19(1:len_trim(startdate)) = startdate\n      convention(1:32) = \"CF-1.0\"\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"output_decimation_factor\", decimation)\n\n      iret = nf90_enddef(ncid)\n\n!!-- write latitude and longitude locations\n!       xdumd = LATVAL\n        iret = nf90_inq_varid(ncid,\"x\", varid)\n!       iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n\tiret = nf90_put_var(ncid, varid, xcoord_d, (/1/), (/ixrtd/)) !-- 1-d array\n\n!       xdumd = LONVAL\n        iret = nf90_inq_varid(ncid,\"y\", varid)\n!       iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n        iret = nf90_put_var(ncid, varid, ycoord_d, (/1/), (/jxrtd/)) !-- 1-d array\n\n#ifdef MPP_LAND\n        xdumd = gLATVAL\n#else\n        xdumd = LATVAL\n#endif\n        iret = nf90_inq_varid(ncid,\"LATITUDE\", varid)\n        iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n\n#ifdef MPP_LAND\n        xdumd = gLONVAL\n#else\n        xdumd = LONVAL\n#endif\n        iret = nf90_inq_varid(ncid,\"LONGITUDE\", varid)\n        iret = nf90_put_var(ncid, varid, xdumd, (/1,1/), (/ixrtd,jxrtd/))\n\n       do n = 1,nsoil\n        if(n == 1) then\n         asldpth(n) = -sldpth(n)\n        else\n         asldpth(n) = asldpth(n-1) - sldpth(n)\n        endif\n       enddo\n\n       iret = nf90_inq_varid(ncid,\"depth\", varid)\n       iret = nf90_put_var(ncid, varid, asldpth, (/1/), (/nsoil/))\n!yw       iret = nf90_close(ncstatic)\n\n    endif\n\n    output_count = output_count + 1\n\n!!-- time\n        iret = nf90_inq_varid(ncid,\"time\", varid)\n        iret = nf90_put_var(ncid, varid, seconds_since, (/output_count/))\n\n!-- 3-d soils\n     do n = 1, nsoil\n#ifdef MPP_LAND\n        xdumd = gSMCRT(:,:,n)\n#else\n        xdumd = SMCRT(:,:,n)\n#endif\n! !DJG inv      jj = int(jxrt/decimation)\n!       jj = 1\n!       ii = 0\n! !DJG inv      do j = jxrt,1,-decimation\n!        do j = 1,jxrt,decimation\n!        do i = 1,ixrt,decimation\n!         ii = ii + 1\n!         if(ii <= ixrtd .and. jj <= jxrtd .and. jj >0) then\n!          xdumd(ii,jj) = smcrt(i,j,n)\n!         endif\n!       enddo\n!        ii = 0\n! !DJG inv       jj = jj -1\n!        jj = jj + 1\n!      enddo\n!       where (vegtyp(:,:) == 16) xdum = -1.E33\n          iret = nf90_inq_varid(ncid,  \"SOIL_M\", varid)\n          iret = nf90_put_var(ncid, varid, xdumd, (/1,1,n,output_count/), (/ixrtd,jxrtd,1,1/))\n    enddo !-n soils\n\n#ifdef MPP_LAND\n        xdumd = gHead\n#else\n        xdumd = head\n#endif\n\n     iret = nf90_inq_varid(ncid,  \"HEAD\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n\n#ifdef MPP_LAND\n        xdumd = gConvgw\n#else\n        xdumd = convgw\n#endif\n     iret = nf90_inq_varid(ncid,  \"CONVGW\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n\n\n#ifdef MPP_LAND\n        xdumd = gExcess\n#else\n        xdumd = excess\n#endif\n     iret = nf90_inq_varid(ncid,  \"GwExcess\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n\n\n#ifdef MPP_LAND\n        xdumd = gqsgwrt\n#else\n        xdumd = qsgwrt\n#endif\n\n     iret = nf90_inq_varid(ncid,  \"QSGWRT\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n\n#ifdef MPP_LAND\n        xdumd = gQgw_chanrt\n#else\n        xdumd = qgw_chanrt\n#endif\n\n     iret = nf90_inq_varid(ncid,  \"QGW_CHANRT\", varid)\n     iret = nf90_put_var(ncid, varid, xdumd, (/1,1,output_count/), (/ixrtd,jxrtd,1/))\n\n\n!!time in seconds since startdate\n\n     iret = nf90_redef(ncid)\n     date19(1:len_trim(date)) = date\n     iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n     iret = nf90_enddef(ncid)\n     iret = nf90_sync(ncid)\n     if (output_count == split_output_count) then\n        output_count = 0\n        iret = nf90_close(ncid)\n     endif\n\n     if(allocated(xdumd)) deallocate(xdumd)\n     if(allocated(xcoord_d)) deallocate(xcoord_d)\n     if(allocated(xcoord)) deallocate(xcoord)\n     if(allocated(ycoord_d)) deallocate(ycoord_d)\n     if(allocated(ycoord)) deallocate(ycoord)\n\n#ifdef HYDRO_D\n     write(6,*) \"end of output_ge\"\n#endif\n#ifdef MPP_LAND\n    endif\n#endif\n\n  end subroutine sub_output_gw\n\n!NOte: output_chrt is the old version comparing to \"output_chrt_bak\".\n\n   subroutine output_chrt(igrid, split_output_count, NLINKS, ORDER,             &\n        startdate, date, chlon, chlat, hlink, zelev, qlink, dtrt_ch, K,         &\n        STRMFRXSTPTS, order_to_write, NLINKSL, channel_option, gages, gageMiss, &\n        lsmDt                                       &\n#ifdef WRF_HYDRO_NUDGING\n        , nudge                                     &\n#endif\n        , accSfcLatRunoff, accBucket                      &\n        ,   qSfcLatRunoff,   qBucket, qBtmVertRunoff      &\n        ,        UDMP_OPT                                 &\n        )\n\n     implicit none\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid,K,channel_option\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLINKS, NLINKSL\n     real, dimension(:),                  intent(in) :: chlon,chlat\n     real, dimension(:),                  intent(in) :: hlink,zelev\n     integer, dimension(:),               intent(in) :: ORDER\n     integer, dimension(:),               intent(inout) :: STRMFRXSTPTS\n     character(len=15), dimension(:),     intent(inout) :: gages\n     character(len=15),                        intent(in) :: gageMiss\n     real,                                     intent(in) :: lsmDt\n\n     real,                                     intent(in) :: dtrt_ch\n     real, dimension(:,:),                intent(in) :: qlink\n#ifdef WRF_HYDRO_NUDGING\n     real, dimension(:),                  intent(in) :: nudge\n#endif\n\n     integer, intent(in)  :: UDMP_OPT\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n     real, allocatable, DIMENSION(:)            :: chanlat,chanlon\n     real, allocatable, DIMENSION(:)            :: chanlatO,chanlonO\n\n     real, allocatable, DIMENSION(:)            :: elevation\n     real, allocatable, DIMENSION(:)            :: elevationO\n\n     integer, allocatable, DIMENSION(:)         :: station_id\n     integer, allocatable, DIMENSION(:)         :: station_idO\n\n     integer, allocatable, DIMENSION(:)         :: rec_num_of_station\n     integer, allocatable, DIMENSION(:)         :: rec_num_of_stationO\n\n     integer, allocatable, DIMENSION(:)         :: lOrder !- local stream order\n     integer, allocatable, DIMENSION(:)         :: lOrderO !- local stream order\n\n     integer, save  :: output_count\n     integer, save  :: ncid,ncid2\n\n     integer :: stationdim, dimdata, varid, charid, n\n     integer :: obsdim, dimdataO, charidO\n     integer :: timedim, timedim2\n     character(len=34) :: sec_valid_date\n\n     integer :: iret,i, start_pos, prev_pos, order_to_write!-- order_to_write is the lowest stream order to output\n     integer :: start_posO, prev_posO, nlk\n\n     integer :: previous_pos  !-- used for the station model\n     character(len=256) :: output_flnm,output_flnm2\n     character(len=19)  :: date19,date19start, hydroTime\n     character(len=34)  :: sec_since_date\n     integer :: seconds_since,nstations,cnt,ObsStation,nobs\n     character(len=32)  :: convention\n     character(len=11),allocatable, DIMENSION(:)  :: stname\n     character(len=15),allocatable, DIMENSION(:)  :: stnameO\n\n    !--- all this for writing the station id string\n     INTEGER   TDIMS, TXLEN\n     PARAMETER (TDIMS=2)    ! number of TX dimensions\n     PARAMETER (TXLEN = 11) ! length of example string\n     INTEGER  TIMEID        ! record dimension id\n     INTEGER  TXID          ! variable ID\n     INTEGER  TXDIMS(TDIMS) ! variable shape\n     INTEGER  TSTART(TDIMS), TCOUNT(TDIMS)\n\n     !--  observation point  ids\n     INTEGER   OTDIMS, OTXLEN\n     PARAMETER (OTDIMS=2)    ! number of TX dimensions\n     PARAMETER (OTXLEN = 15) ! length of example string\n     INTEGER  OTIMEID        ! record dimension id\n     INTEGER  OTXID          ! variable ID\n     INTEGER  OTXDIMS(OTDIMS) ! variable shape\n     INTEGER  OTSTART(OTDIMS), OTCOUNT(OTDIMS)\n\n     real*8, dimension(:), intent(in) :: accSfcLatRunoff, accBucket\n     real,   dimension(:), intent(in) ::   qSfcLatRunoff,   qBucket, qBtmVertRunoff\n\n     !! currently, this is the time of the hydro model, it's\n     !! lsm time (olddate) plus one lsm timestep\n     !call geth_newdate(hydroTime, date, nint(lsmDt))\n     hydroTime=date\n\n     seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n     sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                   //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n!    order_to_write = 2  !-- 1 all; 6 fewest\n      nstations = 0  ! total number of channel points to display\n      nobs      = 0  ! number of observation points\n\n     if(channel_option .ne. 3) then\n        nlk = NLINKSL\n     else\n        nlk = NLINKS\n     endif\n\n\n!-- output only the higher oder streamflows  and only observation points\n     do i=1,nlk\n        if(ORDER(i) .ge. order_to_write) nstations = nstations + 1\n        if(channel_option .ne. 3) then\n           if(trim(gages(i)) .ne. trim(gageMiss)) nobs = nobs + 1\n        else\n           if(STRMFRXSTPTS(i) .ne. -9999) nobs = nobs + 1\n        endif\n     enddo\n\n     if (nobs .eq. 0) then ! let's at least make one obs point\n        nobs = 1\n        if(channel_option .ne. 3) then\n           !           123456789012345\n           gages(1) = '          dummy'\n        else\n           STRMFRXSTPTS(1) = 1\n        endif\n     endif\n\n       allocate(chanlat(nstations))\n       allocate(chanlon(nstations))\n       allocate(elevation(nstations))\n       allocate(lOrder(nstations))\n       allocate(stname(nstations))\n       allocate(station_id(nstations))\n       allocate(rec_num_of_station(nstations))\n\n       allocate(chanlatO(nobs))\n       allocate(chanlonO(nobs))\n       allocate(elevationO(nobs))\n       allocate(lOrderO(nobs))\n       allocate(stnameO(nobs))\n       allocate(station_idO(nobs))\n       allocate(rec_num_of_stationO(nobs))\n\n       if(output_count == 0) then\n!-- have moved sec_since_date from above here..\n        sec_since_date = 'seconds since '//startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10) &\n                  //' '//startdate(12:13)//':'//startdate(15:16)//' UTC'\n\n        date19start(1:len_trim(startdate)) = startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10)//'_' &\n                  //startdate(12:13)//':'//startdate(15:16)//':00'\n\n        nstations = 0\n        nobs = 0\n\n        write(output_flnm, '(A12,\".CHRTOUT_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n        write(output_flnm2,'(A12,\".CHANOBS_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n\n#ifdef HYDRO_D\n        print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n        iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n        if (iret /= 0) then\n           call hydro_stop(\"In output_chrt() - Problem nf90_create points\")\n        endif\n\n        iret = nf90_create(trim(output_flnm2), OR(NF90_CLOBBER, NF90_NETCDF4), ncid2)\n        if (iret /= 0) then\n           call hydro_stop(\"In output_chrt() - Problem nf90_create observation\")\n        endif\n\n       do i=1,nlk\n        if(ORDER(i) .ge. order_to_write) then\n         nstations = nstations + 1\n         chanlat(nstations) = chlat(i)\n         chanlon(nstations) = chlon(i)\n         elevation(nstations) = zelev(i)\n         lOrder(nstations) = ORDER(i)\n         station_id(nstations) = i\n         if(STRMFRXSTPTS(nstations) .eq. -9999) then\n           ObsStation = 0\n         else\n           ObsStation = 1\n         endif\n         write(stname(nstations),'(I6,\"_\",I1,\"_S\",I1)') nstations,lOrder(nstations),ObsStation\n        endif\n       enddo\n\n\n       do i=1,nlk\n          if(channel_option .ne. 3) then\n             if(trim(gages(i)) .ne. trim(gageMiss)) then\n                nobs = nobs + 1\n                chanlatO(nobs) = chlat(i)\n                chanlonO(nobs) = chlon(i)\n                elevationO(nobs) = zelev(i)\n                lOrderO(nobs) = ORDER(i)\n                station_idO(nobs) = i\n                stnameO(nobs) = gages(i)\n             endif\n          else\n             if(STRMFRXSTPTS(i) .ne. -9999) then\n                nobs = nobs + 1\n                chanlatO(nobs) = chlat(i)\n                chanlonO(nobs) = chlon(i)\n                elevationO(nobs) = zelev(i)\n                lOrderO(nobs) = ORDER(i)\n                station_idO(nobs) = i\n                write(stnameO(nobs),'(I6,\"_\",I1)') nobs,lOrderO(nobs)\n#ifdef HYDRO_D\n                !        print *,\"stationobservation name\",  stnameO(nobs)\n#endif\n             endif\n          endif\n       enddo\n\n       iret = nf90_def_dim(ncid, \"recNum\", NF90_UNLIMITED, dimdata)  !--for linked list approach\n       iret = nf90_def_dim(ncid, \"station\", nstations, stationdim)\n       iret = nf90_def_dim(ncid, \"time\", 1, timedim)\n\n\n       iret = nf90_def_dim(ncid2, \"recNum\", NF90_UNLIMITED, dimdataO)  !--for linked list approach\n       iret = nf90_def_dim(ncid2, \"station\", nobs, obsdim)\n       iret = nf90_def_dim(ncid2, \"time\", 1, timedim2)\n\n      !- station location definition all,  lat\n        iret = nf90_def_var(ncid, \"latitude\", NF90_FLOAT, (/stationdim/), varid)\n#ifdef HYDRO_D\n       write(6,*) \"iret 2.1,  \", iret, stationdim\n#endif\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station latitude')\n#ifdef HYDRO_D\n       write(6,*) \"iret 2.2\", iret\n#endif\n        iret = nf90_put_att(ncid, varid, 'units', 'degrees_north')\n#ifdef HYDRO_D\n       write(6,*) \"iret 2.3\", iret\n#endif\n\n\n      !- station location definition obs,  lat\n        iret = nf90_def_var(ncid2, \"latitude\", NF90_FLOAT, (/obsdim/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Observation latitude')\n        iret = nf90_put_att(ncid2, varid, 'units', 'degrees_north')\n\n\n      !- station location definition,  long\n        iret = nf90_def_var(ncid, \"longitude\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station longitude')\n        iret = nf90_put_att(ncid, varid, 'units', 'degrees_east')\n\n\n      !- station location definition, obs long\n        iret = nf90_def_var(ncid2, \"longitude\", NF90_FLOAT, (/obsdim/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Observation longitude')\n        iret = nf90_put_att(ncid2, varid, 'units', 'degrees_east')\n\n\n!     !-- elevation is ZELEV\n        iret = nf90_def_var(ncid, \"altitude\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station altitude')\n        iret = nf90_put_att(ncid, varid, 'units', 'meters')\n\n\n!     !-- elevation is obs ZELEV\n        iret = nf90_def_var(ncid2, \"altitude\", NF90_FLOAT, (/obsdim/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Observation altitude')\n        iret = nf90_put_att(ncid2, varid, 'units', 'meters')\n\n\n!     !--  gage observation\n!       iret = nf90_def_var(ncid, \"gages\", NF90_FLOAT, (/stationdim/), varid)\n!       iret = nf90_put_att(ncid, varid, 'long_name', 'Stream Gage Location')\n!       iret = nf90_put_att(ncid, varid, 'units', 'none')\n\n!-- parent index\n        iret = nf90_def_var(ncid, \"parent_index\", NF90_INT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'index of the station for this record')\n\n        iret = nf90_def_var(ncid2, \"parent_index\", NF90_INT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'index of the station for this record')\n\n     !-- prevChild\n        iret = nf90_def_var(ncid, \"prevChild\", NF90_INT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'record number of the previous record for the same station')\n!ywtmp        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n        iret = nf90_def_var(ncid2, \"prevChild\", NF90_INT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'record number of the previous record for the same station')\n!ywtmp        iret = nf90_put_att(ncid2, varid, '_FillValue', -1)\n        iret = nf90_put_att(ncid2, varid, '_FillValue', -1)\n\n     !-- lastChild\n        iret = nf90_def_var(ncid, \"lastChild\", NF90_INT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'latest report for this station')\n!ywtmp        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n        iret = nf90_def_var(ncid2, \"lastChild\", NF90_INT, (/obsdim/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'latest report for this station')\n!ywtmp        iret = nf90_put_att(ncid2, varid, '_FillValue', -1)\n        iret = nf90_put_att(ncid2, varid, '_FillValue', -1)\n\n!     !- flow definition, var\n\n        if(UDMP_OPT .eq. 1) then\n\n           !! FLUXES to channel\n           if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n              nlst(did)%output_channelBucket_influx .eq. 2      ) then\n              iret = nf90_def_var(ncid, \"qSfcLatRunoff\", NF90_FLOAT, (/dimdata/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              if(nlst(did)%OVRTSWCRT .eq. 1) then              !123456789112345678921234567\n                 iret = nf90_put_att(ncid, varid, 'long_name', 'runoff from terrain routing')\n              else\n                 iret = nf90_put_att(ncid, varid, 'long_name', 'runoff')\n              end if\n              iret = nf90_def_var(ncid, \"qBucket\", NF90_FLOAT, (/dimdata/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              iret = nf90_put_att(ncid, varid, 'long_name', 'flux from gw bucket')\n           end if\n\n           !! Bucket influx\n           if(nlst(did)%output_channelBucket_influx .eq. 2) then\n              iret = nf90_def_var(ncid, \"qBtmVertRunoff\", NF90_FLOAT, (/dimdata/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              iret = nf90_put_att(ncid, varid, 'long_name', 'runoff from bottom of soil to bucket')\n           end if\n\n           !! ACCUMULATIONS\n           if(nlst(did)%output_channelBucket_influx .eq. 3) then\n                 iret = nf90_def_var(ncid, \"accSfcLatRunoff\", NF90_DOUBLE, (/dimdata/), varid)\n                 iret = nf90_put_att(ncid, varid, 'units', 'meter^3')\n                 if(nlst(did)%OVRTSWCRT .eq. 1) then\n                    iret = nf90_put_att(ncid,varid,'long_name',&\n                                           'ACCUMULATED runoff from terrain routing')\n                 else\n                    iret = nf90_put_att(ncid, varid, 'long_name', 'ACCUMULATED runoff from land')\n                 end if\n              iret = nf90_def_var(ncid, \"accBucket\", NF90_DOUBLE, (/dimdata/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3')\n              iret = nf90_put_att(ncid, varid, 'long_name', 'ACCUMULATED runoff from gw bucket')\n           endif\n        endif\n\n        iret = nf90_def_var(ncid, \"streamflow\", NF90_FLOAT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'River Flow')\n\n        iret = nf90_def_var(ncid2, \"streamflow\", NF90_FLOAT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'River Flow')\n\n#ifdef WRF_HYDRO_NUDGING\n        iret = nf90_def_var(ncid, \"nudge\", NF90_FLOAT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Amount of stream flow alteration')\n\n        iret = nf90_def_var(ncid2, \"nudge\", NF90_FLOAT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Amount of stream flow alteration')\n#endif\n\n!     !- flow definition, var\n!       iret = nf90_def_var(ncid, \"pos_streamflow\", NF90_FLOAT, (/dimdata/), varid)\n!       iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n!       iret = nf90_put_att(ncid, varid, 'long_name', 'abs streamflow')\n\n!     !- head definition, var\n        iret = nf90_def_var(ncid, \"head\", NF90_FLOAT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'River Stage')\n\n        iret = nf90_def_var(ncid2, \"head\", NF90_FLOAT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'units', 'meter')\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'River Stage')\n\n!     !- order definition, var\n        iret = nf90_def_var(ncid, \"order\", NF90_INT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Strahler Stream Order')\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n        iret = nf90_def_var(ncid2, \"order\", NF90_INT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Strahler Stream Order')\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n     !-- station  id\n     ! define character-position dimension for strings of max length 11\n         iret = NF90_DEF_DIM(ncid, \"id_len\", 11, charid)\n         TXDIMS(1) = charid   ! define char-string variable and position dimension first\n         TXDIMS(2) = stationdim\n         iret = nf90_def_var(ncid, \"station_id\", NF90_CHAR, TXDIMS, varid)\n         iret = nf90_put_att(ncid, varid, 'long_name', 'Station id')\n\n\n         iret = NF90_DEF_DIM(ncid2, \"id_len\", 15, charidO)\n         OTXDIMS(1) = charidO   ! define char-string variable and position dimension first\n         OTXDIMS(2) = obsdim\n         iret = nf90_def_var(ncid2, \"station_id\", NF90_CHAR, OTXDIMS, varid)\n         iret = nf90_put_att(ncid2, varid, 'long_name', 'Observation id')\n\n\n!     !- time definition, timeObs\n\t iret = nf90_def_var(ncid, \"time\", NF90_INT, (/timedim/), varid)\n\t iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n         iret = nf90_put_att(ncid, varid, 'long_name', 'valid output time')\n\n\t iret = nf90_def_var(ncid2, \"time\", NF90_INT, (/timedim2/), varid)\n         iret = nf90_put_att(ncid2, varid, 'units', sec_valid_date)\n         iret = nf90_put_att(ncid2, varid, 'long_name', 'valid output time')\n\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"Conventions\", convention)\n\n         convention(1:32) = \"Unidata Observation Dataset v1.0\"\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"cdm_datatype\", \"Station\")\n\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_max\", \"90.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_min\", \"-90.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_max\", \"180.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_min\", \"-180.0\")\n\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"station_dimension\", \"station\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"stream_order_output\", order_to_write)\n\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"Conventions\", convention)\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"cdm_datatype\", \"Station\")\n\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"geospatial_lat_max\", \"90.0\")\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"geospatial_lat_min\", \"-90.0\")\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"geospatial_lon_max\", \"180.0\")\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"geospatial_lon_min\", \"-180.0\")\n\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"station_dimension\", \"station\")\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"missing_value\", -9E15)\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"stream_order_output\", order_to_write)\n\n         iret = nf90_enddef(ncid)\n         iret = nf90_enddef(ncid2)\n\n        !-- write latitudes\n         iret = nf90_inq_varid(ncid,\"latitude\", varid)\n         iret = nf90_put_var(ncid, varid, chanlat, (/1/), (/nstations/))\n\n         iret = nf90_inq_varid(ncid2,\"latitude\", varid)\n         iret = nf90_put_var(ncid2, varid, chanlatO, (/1/), (/nobs/))\n\n        !-- write longitudes\n         iret = nf90_inq_varid(ncid,\"longitude\", varid)\n         iret = nf90_put_var(ncid, varid, chanlon, (/1/), (/nstations/))\n\n         iret = nf90_inq_varid(ncid2,\"longitude\", varid)\n         iret = nf90_put_var(ncid2, varid, chanlonO, (/1/), (/nobs/))\n\n        !-- write elevations\n         iret = nf90_inq_varid(ncid,\"altitude\", varid)\n         iret = nf90_put_var(ncid, varid, elevation, (/1/), (/nstations/))\n\n         iret = nf90_inq_varid(ncid2,\"altitude\", varid)\n         iret = nf90_put_var(ncid2, varid, elevationO, (/1/), (/nobs/))\n\n      !-- write gage location\n!      iret = nf90_inq_varid(ncid,\"gages\", varid)\n!      iret = nf90_put_var(ncid, varid, STRMFRXSTPTS, (/1/), (/nstations/))\n\n        !-- write number_of_stations, OPTIONAL\n      !!  iret = nf90_inq_varid(ncid,\"number_stations\", varid)\n      !!  iret = nf90_put_var_int(ncid, varid, nstations)\n\n        !-- write station id's\n         do i=1,nstations\n          TSTART(1) = 1\n          TSTART(2) = i\n          TCOUNT(1) = TXLEN\n          TCOUNT(2) = 1\n          iret = nf90_inq_varid(ncid,\"station_id\", varid)\n          iret = nf90_put_var(ncid, varid, stname(i), TSTART, TCOUNT)\n         enddo\n\n        !-- write observation id's\n         do i=1, nobs\n          OTSTART(1) = 1\n          OTSTART(2) = i\n          OTCOUNT(1) = OTXLEN\n          OTCOUNT(2) = 1\n          iret = nf90_inq_varid(ncid2,\"station_id\", varid)\n          iret = nf90_put_var(ncid2, varid, stnameO(i), OTSTART, OTCOUNT)\n         enddo\n\n     endif\n\n     output_count = output_count + 1\n\n     open (unit=55, &\n#ifndef NCEP_WCOSS\n     file='frxst_pts_out.txt', &\n#endif\n     status='unknown',position='append')\n\n     cnt=0\n     do i=1,nlk\n\n       if(ORDER(i) .ge. order_to_write) then\n         start_pos = (cnt+1)+(nstations*(output_count-1))\n\n         !!--time in seconds since startdate\n          iret = nf90_inq_varid(ncid,\"time\", varid)\n          iret = nf90_put_var(ncid, varid, seconds_since, (/1/))\n\n         if(UDMP_OPT .eq. 1) then\n            !! FLUXES to channel\n             if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n                nlst(did)%output_channelBucket_influx .eq. 2      ) then\n                iret = nf90_inq_varid(ncid,\"qSfcLatRunoff\", varid)\n                iret = nf90_put_var(ncid, varid, qSfcLatRunoff(i), (/start_pos/))\n\n                iret = nf90_inq_varid(ncid,\"qBucket\", varid)\n                iret = nf90_put_var(ncid, varid, qBucket(i), (/start_pos/))\n             end if\n\n             !! FLUXES to bucket\n             if(nlst(did)%output_channelBucket_influx .eq. 2) then\n                iret = nf90_inq_varid(ncid,\"qBtmVertRunoff\", varid)\n                iret = nf90_put_var(ncid, varid, qBtmVertRunoff(i), (/start_pos/))\n             end if\n\n            !! ACCUMULATIONS\n             if(nlst(did)%output_channelBucket_influx .eq. 3) then\n                iret = nf90_inq_varid(ncid,\"accSfcLatRunoff\", varid)\n                iret = nf90_put_var(ncid, varid, accSfcLatRunoff(i), (/start_pos/))\n\n                iret = nf90_inq_varid(ncid,\"accBucket\", varid)\n                iret = nf90_put_var(ncid, varid, accBucket(i), (/start_pos/))\n             end if\n          endif\n\n         iret = nf90_inq_varid(ncid,\"streamflow\", varid)\n         iret = nf90_put_var(ncid, varid, qlink(i,1), (/start_pos/))\n\n#ifdef WRF_HYDRO_NUDGING\n         iret = nf90_inq_varid(ncid,\"nudge\", varid)\n         iret = nf90_put_var(ncid, varid, nudge(i), (/start_pos/))\n#endif\n\n!        iret = nf90_inq_varid(ncid,\"pos_streamflow\", varid)\n!        iret = nf90_put_var(ncid, varid, abs(qlink(i,1), (/start_pos/)))\n\n         iret = nf90_inq_varid(ncid,\"head\", varid)\n         iret = nf90_put_var(ncid, varid, hlink(i), (/start_pos/))\n\n         iret = nf90_inq_varid(ncid,\"order\", varid)\n         iret = nf90_put_var(ncid, varid, ORDER(i), (/start_pos/))\n\n         !-- station index.. will repeat for every timesstep\n         iret = nf90_inq_varid(ncid,\"parent_index\", varid)\n         iret = nf90_put_var(ncid, varid, cnt, (/start_pos/))\n\n          !--record number of previous record for same station\n!obsolete format         prev_pos = cnt+(nstations*(output_count-1))\n         prev_pos = cnt+(nobs*(output_count-2))\n         if(output_count.ne.1) then !-- only write next set of records\n           iret = nf90_inq_varid(ncid,\"prevChild\", varid)\n           iret = nf90_put_var(ncid, varid, prev_pos, (/start_pos/))\n         endif\n         cnt=cnt+1  !--indices are 0 based\n         rec_num_of_station(cnt) = start_pos-1  !-- save position for last child, 0-based!!\n\n\n       endif\n    enddo\n!    close(999)\n\n    !-- output  only observation points\n    cnt=0\n    do i=1,nlk\n       if(channel_option .ne. 3) then\n          ! jlm this verry repetitiuos, oh well.\n          if(trim(gages(i)) .ne. trim(gageMiss)) then\n\n             start_posO = (cnt+1)+(nobs * (output_count-1))\n             !Write frxst_pts to text file...\n             !yw          write(55,117) seconds_since,trim(date),cnt,chlon(i),chlat(i), &\n118          FORMAT(I8,\",\",A10,1X,A8,\", \",A15,\",\",F10.5,\",\",F8.5,\",\",F9.3,\",\",F12.3,\",\",F6.3)\n             !write(55,118) seconds_since, date(1:10), date(12:19), &\n\n             write(55,118) seconds_since, hydroTime(1:10), hydroTime(12:19), &\n                  gages(i), chlon(i), chlat(i),                               &\n                  qlink(i,1), qlink(i,1)*35.314666711511576, hlink(i)\n\n             !yw 117 FORMAT(I8,1X,A25,1X,I7,1X,F10.5,1X,F8.5,1X,F9.3,1x,F12.3,1X,F6.3)\n             !yw 117 FORMAT(I8,1X,A10,1X,A8,1x,I7,1X,F10.5,1X,F8.5,1X,F9.3,1x,F12.3,1X,F6.3)\n\n             !!--time in seconds since startdate\n             iret = nf90_inq_varid(ncid2,\"time\", varid)\n             iret = nf90_put_var(ncid2, varid, seconds_since, (/1/))\n\n             iret = nf90_inq_varid(ncid2,\"streamflow\", varid)\n             iret = nf90_put_var(ncid2, varid, qlink(i,1), (/start_posO/))\n\n#ifdef WRF_HYDRO_NUDGING\n             iret = nf90_inq_varid(ncid2,\"nudge\", varid)\n             iret = nf90_put_var(ncid2, varid, nudge(i), (/start_posO/))\n#endif\n\n             iret = nf90_inq_varid(ncid2,\"head\", varid)\n             iret = nf90_put_var(ncid2, varid, hlink(i), (/start_posO/))\n\n             iret = nf90_inq_varid(ncid,\"order\", varid)\n             iret = nf90_put_var(ncid2, varid, ORDER(i), (/start_posO/))\n\n             !-- station index.. will repeat for every timesstep\n             iret = nf90_inq_varid(ncid2,\"parent_index\", varid)\n             iret = nf90_put_var(ncid2, varid, cnt, (/start_posO/))\n\n             !--record number of previous record for same station\n             !obsolete format          prev_posO = cnt+(nobs*(output_count-1))\n             prev_posO = cnt+(nobs*(output_count-2))\n             if(output_count.ne.1) then !-- only write next set of records\n                iret = nf90_inq_varid(ncid2,\"prevChild\", varid)\n                iret = nf90_put_var(ncid2, varid, prev_posO, (/start_posO/))\n\n                !IF block to add -1 to last element of prevChild array to designate end of list...\n                !           if(cnt+1.eq.nobs.AND.output_count.eq.split_output_count) then\n                !             iret = nf90_put_vara_int(ncid2, varid, (/start_posO/), (/1/), -1)\n                !           else\n                !             iret = nf90_put_var(ncid2, varid, prev_posO, (/start_posO/))\n                !           endif\n\n             endif\n             cnt=cnt+1  !--indices are 0 based\n             rec_num_of_stationO(cnt) = start_posO - 1  !-- save position for last child, 0-based!!\n          endif\n\n\n       else !! channel options 3 below\n\n          if(STRMFRXSTPTS(i) .ne. -9999) then\n             start_posO = (cnt+1)+(nobs * (output_count-1))\n             !Write frxst_pts to text file...\n             !yw          write(55,117) seconds_since,trim(date),cnt,chlon(i),chlat(i), &\n117          FORMAT(I8,\",\",A10,1X,A8,\",\",I7,\",\",F10.5,\",\",F8.5,\",\",F9.3,\",\",F12.3,\",\",F6.3)\n             !write(55,117) seconds_since,date(1:10),date(12:19),cnt,chlon(i),chlat(i), &\n             !     qlink(i,1), qlink(i,1)*35.315,hlink(i)\n             ! JLM: makes more sense to output the value in frxstpts incase they have meaning,\n             ! as below, but I'm not going to make this change until I'm working with gridded\n             ! streamflow again.\n             write(55,117) seconds_since, hydroTime(1:10), hydroTime(12:19), &\n                  strmfrxstpts(i), chlon(i), chlat(i),                        &\n                  qlink(i,1), qlink(i,1)*35.314666711511576, hlink(i)\n\n             !!--time in seconds since startdate\n             iret = nf90_inq_varid(ncid2,\"time\", varid)\n             iret = nf90_put_var(ncid2, varid, seconds_since, (/1/))\n\n             iret = nf90_inq_varid(ncid2,\"streamflow\", varid)\n             iret = nf90_put_var(ncid2, varid, qlink(i,1), (/start_posO/))\n\n             iret = nf90_inq_varid(ncid2,\"head\", varid)\n             iret = nf90_put_var(ncid2, varid, hlink(i), (/start_posO/))\n\n             iret = nf90_inq_varid(ncid,\"order\", varid)\n             iret = nf90_put_var(ncid2, varid, ORDER(i), (/start_posO/))\n\n             !-- station index.. will repeat for every timesstep\n             iret = nf90_inq_varid(ncid2,\"parent_index\", varid)\n             iret = nf90_put_var(ncid2, varid, cnt, (/start_posO/))\n\n             !--record number of previous record for same station\n             !obsolete format          prev_posO = cnt+(nobs*(output_count-1))\n             prev_posO = cnt+(nobs*(output_count-2))\n             if(output_count.ne.1) then !-- only write next set of records\n                iret = nf90_inq_varid(ncid2,\"prevChild\", varid)\n                iret = nf90_put_var(ncid2, varid, prev_posO, (/start_posO/))\n\n                !IF block to add -1 to last element of prevChild array to designate end of list...\n                !           if(cnt+1.eq.nobs.AND.output_count.eq.split_output_count) then\n                !             iret = nf90_put_vara_int(ncid2, varid, (/start_posO/), (/1/), -1)\n                !           else\n                !             iret = nf90_put_var(ncid2, varid, prev_posO, (/start_posO/))\n                !           endif\n\n             endif\n             cnt=cnt+1  !--indices are 0 based\n             rec_num_of_stationO(cnt) = start_posO - 1  !-- save position for last child, 0-based!!\n          endif\n\n       endif\n\n    enddo\n    close(55)\n\n      !-- lastChild variable gives the record number of the most recent report for the station\n      iret = nf90_inq_varid(ncid,\"lastChild\", varid)\n      iret = nf90_put_var(ncid, varid, rec_num_of_station, (/1/), (/nstations/))\n\n      !-- lastChild variable gives the record number of the most recent report for the station\n      iret = nf90_inq_varid(ncid2,\"lastChild\", varid)\n      iret = nf90_put_var(ncid2, varid, rec_num_of_stationO, (/1/), (/nobs/))\n\n      iret = nf90_redef(ncid)\n      date19(1:19) = \"0000-00-00_00:00:00\"\n      date19(1:len_trim(date)) = date\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n\n      iret = nf90_redef(ncid2)\n      iret = nf90_put_att(ncid2, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n\n      iret = nf90_enddef(ncid)\n      iret = nf90_sync(ncid)\n\n      iret = nf90_enddef(ncid2)\n      iret = nf90_sync(ncid2)\n\n      if (output_count == split_output_count) then\n        output_count = 0\n        iret = nf90_close(ncid)\n        iret = nf90_close(ncid2)\n     endif\n\n     deallocate(chanlat)\n     deallocate(chanlon)\n     deallocate(elevation)\n     deallocate(station_id)\n     deallocate(lOrder)\n     deallocate(rec_num_of_station)\n     deallocate(stname)\n\n     deallocate(chanlatO)\n     deallocate(chanlonO)\n     deallocate(elevationO)\n     deallocate(station_idO)\n     deallocate(lOrderO)\n     deallocate(rec_num_of_stationO)\n     deallocate(stnameO)\n#ifdef HYDRO_D\n     print *, \"Exited Subroutine output_chrt\"\n#endif\n     close(16)\n\n20 format(i8,',',f12.7,',',f10.7,',',f6.2,',',i3)\n\nend subroutine output_chrt\n!-- output the channel route in an IDV 'station' compatible format\n!Note: This version has pool output performance need to be\n!solved. We renamed it from output_chrt to be output_chrt_bak.\n   subroutine output_chrt_bak(igrid, split_output_count, NLINKS, ORDER,             &\n        startdate, date, chlon, chlat, hlink, zelev, qlink, dtrt_ch, K,         &\n        STRMFRXSTPTS, order_to_write, NLINKSL, channel_option, gages, gageMiss, &\n        lsmDt                                       &\n#ifdef WRF_HYDRO_NUDGING\n        , nudge                                     &\n#endif\n        , accSfcLatRunoff, accBucket                      &\n        ,   qSfcLatRunoff,   qBucket, qBtmVertRunoff      &\n        ,        UDMP_OPT                                 &\n        )\n\n     implicit none\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid,K,channel_option\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLINKS, NLINKSL\n     real, dimension(:),                  intent(in) :: chlon,chlat\n     real, dimension(:),                  intent(in) :: hlink,zelev\n     integer, dimension(:),               intent(in) :: ORDER\n     integer, dimension(:),               intent(inout) :: STRMFRXSTPTS\n     character(len=15), dimension(:),     intent(inout) :: gages\n     character(len=15),                        intent(in) :: gageMiss\n     real,                                     intent(in) :: lsmDt\n\n     real,                                     intent(in) :: dtrt_ch\n     real, dimension(:,:),                intent(in) :: qlink\n#ifdef WRF_HYDRO_NUDGING\n     real, dimension(:),                  intent(in) :: nudge\n#endif\n\n     integer, intent(in)  :: UDMP_OPT\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n     real, allocatable, DIMENSION(:)            :: chanlat,chanlon\n     real, allocatable, DIMENSION(:)            :: chanlatO,chanlonO\n\n     real, allocatable, DIMENSION(:)            :: elevation\n     real, allocatable, DIMENSION(:)            :: elevationO\n\n     integer, allocatable, DIMENSION(:)         :: station_id\n     integer, allocatable, DIMENSION(:)         :: station_idO\n\n     integer, allocatable, DIMENSION(:)         :: rec_num_of_station\n     integer, allocatable, DIMENSION(:)         :: rec_num_of_stationO\n\n     integer, allocatable, DIMENSION(:)         :: lOrder !- local stream order\n     integer, allocatable, DIMENSION(:)         :: lOrderO !- local stream order\n\n     integer, save  :: output_count\n     integer, save  :: ncid,ncid2\n\n     integer :: stationdim, dimdata, varid, charid, n\n     integer :: obsdim, dimdataO, charidO\n     integer :: timedim, timedim2\n     character(len=34) :: sec_valid_date\n\n     integer :: iret,i, start_pos, prev_pos, order_to_write!-- order_to_write is the lowest stream order to output\n     integer :: start_posO, prev_posO, nlk\n\n     integer :: previous_pos  !-- used for the station model\n     character(len=256) :: output_flnm,output_flnm2\n     character(len=19)  :: date19,date19start, hydroTime\n     character(len=34)  :: sec_since_date\n     integer :: seconds_since,nstations,cnt,ObsStation,nobs\n     character(len=32)  :: convention\n     character(len=11),allocatable, DIMENSION(:)  :: stname\n     character(len=15),allocatable, DIMENSION(:)  :: stnameO\n\n    !--- all this for writing the station id string\n     INTEGER   TDIMS, TXLEN\n     PARAMETER (TDIMS=2)    ! number of TX dimensions\n     PARAMETER (TXLEN = 11) ! length of example string\n     INTEGER  TIMEID        ! record dimension id\n     INTEGER  TXID          ! variable ID\n     INTEGER  TXDIMS(TDIMS) ! variable shape\n     INTEGER  TSTART(TDIMS), TCOUNT(TDIMS)\n\n     !--  observation point  ids\n     INTEGER   OTDIMS, OTXLEN\n     PARAMETER (OTDIMS=2)    ! number of TX dimensions\n     PARAMETER (OTXLEN = 15) ! length of example string\n     INTEGER  OTIMEID        ! record dimension id\n     INTEGER  OTXID          ! variable ID\n     INTEGER  OTXDIMS(OTDIMS) ! variable shape\n     INTEGER  OTSTART(OTDIMS), OTCOUNT(OTDIMS)\n\n     real*8, dimension(:), intent(in) :: accSfcLatRunoff, accBucket\n     real,   dimension(:), intent(in) ::   qSfcLatRunoff,   qBucket, qBtmVertRunoff\n\n     !! currently, this is the time of the hydro model, it's\n     !! lsm time (olddate) plus one lsm timestep\n     !call geth_newdate(hydroTime, date, nint(lsmDt))\n     hydroTime=date\n\n     seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n     sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                   //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n!    order_to_write = 2  !-- 1 all; 6 fewest\n      nstations = 0  ! total number of channel points to display\n      nobs      = 0  ! number of observation points\n\n     if(channel_option .ne. 3) then\n        nlk = NLINKSL\n     else\n        nlk = NLINKS\n     endif\n\n\n!-- output only the higher oder streamflows  and only observation points\n     do i=1,nlk\n        if(ORDER(i) .ge. order_to_write) nstations = nstations + 1\n        if(channel_option .ne. 3) then\n           if(trim(gages(i)) .ne. trim(gageMiss)) nobs = nobs + 1\n        else\n           if(STRMFRXSTPTS(i) .ne. -9999) nobs = nobs + 1\n        endif\n     enddo\n\n     if (nobs .eq. 0) then ! let's at least make one obs point\n        nobs = 1\n        if(channel_option .ne. 3) then\n           !           123456789012345\n           gages(1) = '          dummy'\n        else\n           STRMFRXSTPTS(1) = 1\n        endif\n     endif\n\n       allocate(chanlat(nstations))\n       allocate(chanlon(nstations))\n       allocate(elevation(nstations))\n       allocate(lOrder(nstations))\n       allocate(stname(nstations))\n       allocate(station_id(nstations))\n       allocate(rec_num_of_station(nstations))\n\n       allocate(chanlatO(nobs))\n       allocate(chanlonO(nobs))\n       allocate(elevationO(nobs))\n       allocate(lOrderO(nobs))\n       allocate(stnameO(nobs))\n       allocate(station_idO(nobs))\n       allocate(rec_num_of_stationO(nobs))\n\n       if(output_count == 0) then\n!-- have moved sec_since_date from above here..\n        sec_since_date = 'seconds since '//startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10) &\n                  //' '//startdate(12:13)//':'//startdate(15:16)//' UTC'\n\n        date19start(1:len_trim(startdate)) = startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10)//'_' &\n                  //startdate(12:13)//':'//startdate(15:16)//':00'\n\n        nstations = 0\n        nobs = 0\n\n        write(output_flnm, '(A12,\".CHRTOUT_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n        write(output_flnm2,'(A12,\".CHANOBS_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n\n#ifdef HYDRO_D\n        print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n       iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n       if (iret /= 0) then\n           call hydro_stop(\"In output_chrt() - Problem nf90_create points\")\n       endif\n\n       iret = nf90_create(trim(output_flnm2), OR(NF90_CLOBBER, NF90_NETCDF4), ncid2)\n       if (iret /= 0) then\n           call hydro_stop(\"In output_chrt() - Problem nf90_create observation\")\n       endif\n\n       do i=1,nlk\n        if(ORDER(i) .ge. order_to_write) then\n         nstations = nstations + 1\n         chanlat(nstations) = chlat(i)\n         chanlon(nstations) = chlon(i)\n         elevation(nstations) = zelev(i)\n         lOrder(nstations) = ORDER(i)\n         station_id(nstations) = i\n         if(STRMFRXSTPTS(nstations) .eq. -9999) then\n           ObsStation = 0\n         else\n           ObsStation = 1\n         endif\n         write(stname(nstations),'(I6,\"_\",I1,\"_S\",I1)') nstations,lOrder(nstations),ObsStation\n        endif\n       enddo\n\n\n       do i=1,nlk\n          if(channel_option .ne. 3) then\n             if(trim(gages(i)) .ne. trim(gageMiss)) then\n                nobs = nobs + 1\n                chanlatO(nobs) = chlat(i)\n                chanlonO(nobs) = chlon(i)\n                elevationO(nobs) = zelev(i)\n                lOrderO(nobs) = ORDER(i)\n                station_idO(nobs) = i\n                stnameO(nobs) = gages(i)\n             endif\n          else\n             if(STRMFRXSTPTS(i) .ne. -9999) then\n                nobs = nobs + 1\n                chanlatO(nobs) = chlat(i)\n                chanlonO(nobs) = chlon(i)\n                elevationO(nobs) = zelev(i)\n                lOrderO(nobs) = ORDER(i)\n                station_idO(nobs) = i\n                write(stnameO(nobs),'(I6,\"_\",I1)') nobs,lOrderO(nobs)\n#ifdef HYDRO_D\n                !        print *,\"stationobservation name\",  stnameO(nobs)\n#endif\n             endif\n          endif\n       enddo\n\n       iret = nf90_def_dim(ncid, \"recNum\", NF90_UNLIMITED, dimdata)  !--for linked list approach\n       iret = nf90_def_dim(ncid, \"station\", nstations, stationdim)\n       iret = nf90_def_dim(ncid, \"time\", 1, timedim)\n\n\n       iret = nf90_def_dim(ncid2, \"recNum\", NF90_UNLIMITED, dimdataO)  !--for linked list approach\n       iret = nf90_def_dim(ncid2, \"station\", nobs, obsdim)\n       iret = nf90_def_dim(ncid2, \"time\", 1, timedim2)\n\n      !- station location definition all,  lat\n        iret = nf90_def_var(ncid, \"latitude\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station latitude')\n        iret = nf90_put_att(ncid, varid, 'units', 'degrees_north')\n\n      !- station location definition obs,  lat\n        iret = nf90_def_var(ncid2, \"latitude\", NF90_FLOAT, (/obsdim/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Observation latitude')\n        iret = nf90_put_att(ncid2, varid, 'units', 'degrees_north')\n\n\n      !- station location definition,  long\n        iret = nf90_def_var(ncid, \"longitude\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station longitude')\n        iret = nf90_put_att(ncid, varid, 'units', 'degrees_east')\n\n\n      !- station location definition, obs long\n        iret = nf90_def_var(ncid2, \"longitude\", NF90_FLOAT, (/obsdim/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Observation longitude')\n        iret = nf90_put_att(ncid2, varid, 'units', 'degrees_east')\n\n\n!     !-- elevation is ZELEV\n        iret = nf90_def_var(ncid, \"altitude\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station altitude')\n        iret = nf90_put_att(ncid, varid, 'units', 'meters')\n\n\n!     !-- elevation is obs ZELEV\n        iret = nf90_def_var(ncid2, \"altitude\", NF90_FLOAT, (/obsdim/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Observation altitude')\n        iret = nf90_put_att(ncid2, varid, 'units', 'meters')\n\n\n!     !--  gage observation\n!       iret = nf90_def_var(ncid, \"gages\", NF90_FLOAT, (/stationdim/), varid)\n!       iret = nf90_put_att(ncid, varid, 'long_name', 'Stream Gage Location')\n!       iret = nf90_put_att(ncid, varid, 'units', 'none')\n\n!-- parent index\n        iret = nf90_def_var(ncid, \"parent_index\", NF90_INT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'index of the station for this record')\n\n        iret = nf90_def_var(ncid2, \"parent_index\", NF90_INT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'index of the station for this record')\n\n     !-- prevChild\n        iret = nf90_def_var(ncid, \"prevChild\", NF90_INT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'record number of the previous record for the same station')\n!ywtmp        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n        iret = nf90_def_var(ncid2, \"prevChild\", NF90_INT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'record number of the previous record for the same station')\n!ywtmp        iret = nf90_put_att(ncid2, varid, '_FillValue', -1)\n        iret = nf90_put_att(ncid2, varid, '_FillValue', -1)\n\n     !-- lastChild\n        iret = nf90_def_var(ncid, \"lastChild\", NF90_INT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'latest report for this station')\n!ywtmp        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n        iret = nf90_def_var(ncid2, \"lastChild\", NF90_INT, (/obsdim/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'latest report for this station')\n!ywtmp        iret = nf90_put_att(ncid2, varid, '_FillValue', -1)\n        iret = nf90_put_att(ncid2, varid, '_FillValue', -1)\n\n!     !- flow definition, var\n\n        if(UDMP_OPT .eq. 1) then\n\n           !! FLUXES to channel\n           if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n              nlst(did)%output_channelBucket_influx .eq. 2      ) then\n              iret = nf90_def_var(ncid, \"qSfcLatRunoff\", NF90_FLOAT, (/dimdata/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              if(nlst(did)%OVRTSWCRT .eq. 1) then              !123456789112345678921234567\n                 iret = nf90_put_att(ncid, varid, 'long_name', 'runoff from terrain routing')\n              else\n                 iret = nf90_put_att(ncid, varid, 'long_name', 'runoff')\n              end if\n              iret = nf90_def_var(ncid, \"qBucket\", NF90_FLOAT, (/dimdata/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              iret = nf90_put_att(ncid, varid, 'long_name', 'flux from gw bucket')\n           end if\n\n           !! Bucket influx\n           if(nlst(did)%output_channelBucket_influx .eq. 2) then\n              iret = nf90_def_var(ncid, \"qBtmVertRunoff\", NF90_FLOAT, (/dimdata/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              iret = nf90_put_att(ncid, varid, 'long_name', 'runoff from bottom of soil to bucket')\n           end if\n\n           !! ACCUMULATIONS\n           if(nlst(did)%output_channelBucket_influx .eq. 3) then\n                 iret = nf90_def_var(ncid, \"accSfcLatRunoff\", NF90_DOUBLE, (/dimdata/), varid)\n                 iret = nf90_put_att(ncid, varid, 'units', 'meter^3')\n                 if(nlst(did)%OVRTSWCRT .eq. 1) then\n                    iret = nf90_put_att(ncid,varid,'long_name', &\n                                           'ACCUMULATED runoff from terrain routing')\n                 else\n                    iret = nf90_put_att(ncid, varid, 'long_name', 'ACCUMULATED runoff from land')\n                 end if\n              iret = nf90_def_var(ncid, \"accBucket\", NF90_DOUBLE, (/dimdata/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3')\n              iret = nf90_put_att(ncid, varid, 'long_name', 'ACCUMULATED runoff from gw bucket')\n           endif\n        endif\n\n        iret = nf90_def_var(ncid, \"streamflow\", NF90_FLOAT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'River Flow')\n\n        iret = nf90_def_var(ncid2, \"streamflow\", NF90_FLOAT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'River Flow')\n\n#ifdef WRF_HYDRO_NUDGING\n        iret = nf90_def_var(ncid, \"nudge\", NF90_FLOAT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Amount of stream flow alteration')\n\n        iret = nf90_def_var(ncid2, \"nudge\", NF90_FLOAT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Amount of stream flow alteration')\n#endif\n\n!     !- flow definition, var\n!       iret = nf90_def_var(ncid, \"pos_streamflow\", NF90_FLOAT, (/dimdata/), varid)\n!       iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n!       iret = nf90_put_att(ncid, varid, 'long_name', 'abs streamflow')\n\n!     !- head definition, var\n        iret = nf90_def_var(ncid, \"head\", NF90_FLOAT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'River Stage')\n\n        iret = nf90_def_var(ncid2, \"head\", NF90_FLOAT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'units', 'meter')\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'River Stage')\n\n!     !- order definition, var\n        iret = nf90_def_var(ncid, \"order\", NF90_INT, (/dimdata/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Strahler Stream Order')\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n        iret = nf90_def_var(ncid2, \"order\", NF90_INT, (/dimdataO/), varid)\n        iret = nf90_put_att(ncid2, varid, 'long_name', 'Strahler Stream Order')\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n     !-- station  id\n     ! define character-position dimension for strings of max length 11\n         iret = NF90_DEF_DIM(ncid, \"id_len\", 11, charid)\n         TXDIMS(1) = charid   ! define char-string variable and position dimension first\n         TXDIMS(2) = stationdim\n         iret = nf90_def_var(ncid, \"station_id\", NF90_CHAR, TXDIMS, varid)\n         iret = nf90_put_att(ncid, varid, 'long_name', 'Station id')\n\n\n         iret = NF90_DEF_DIM(ncid2, \"id_len\", 15, charidO)\n         OTXDIMS(1) = charidO   ! define char-string variable and position dimension first\n         OTXDIMS(2) = obsdim\n         iret = nf90_def_var(ncid2, \"station_id\", NF90_CHAR, OTXDIMS, varid)\n         iret = nf90_put_att(ncid2, varid, 'long_name', 'Observation id')\n\n\n!     !- time definition, timeObs\n\t iret = nf90_def_var(ncid, \"time\", NF90_INT, (/timedim/), varid)\n\t iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n         iret = nf90_put_att(ncid, varid, 'long_name', 'valid output time')\n\n\t iret = nf90_def_var(ncid2, \"time\", NF90_INT, (/timedim2/), varid)\n         iret = nf90_put_att(ncid2, varid, 'units', sec_valid_date)\n         iret = nf90_put_att(ncid2, varid, 'long_name', 'valid output time')\n\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"Conventions\", convention)\n\n         convention(1:32) = \"Unidata Observation Dataset v1.0\"\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"cdm_datatype\", \"Station\")\n\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_max\", \"90.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_min\", \"-90.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_max\", \"180.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_min\", \"-180.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"station_dimension\", \"station\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"stream_order_output\", order_to_write)\n\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"Conventions\", convention)\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"cdm_datatype\", \"Station\")\n\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"geospatial_lat_max\", \"90.0\")\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"geospatial_lat_min\", \"-90.0\")\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"geospatial_lon_max\", \"180.0\")\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"geospatial_lon_min\", \"-180.0\")\n\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"station_dimension\", \"station\")\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"missing_value\", -9E15)\n         iret = nf90_put_att(ncid2, NF90_GLOBAL, \"stream_order_output\", order_to_write)\n\n         iret = nf90_enddef(ncid)\n         iret = nf90_enddef(ncid2)\n\n        !-- write latitudes\n         iret = nf90_inq_varid(ncid,\"latitude\", varid)\n         iret = nf90_put_var(ncid, varid, chanlat, (/1/), (/nstations/))\n\n         iret = nf90_inq_varid(ncid2,\"latitude\", varid)\n         iret = nf90_put_var(ncid2, varid, chanlatO, (/1/), (/nobs/))\n\n        !-- write longitudes\n         iret = nf90_inq_varid(ncid,\"longitude\", varid)\n         iret = nf90_put_var(ncid, varid, chanlon, (/1/), (/nstations/))\n\n         iret = nf90_inq_varid(ncid2,\"longitude\", varid)\n         iret = nf90_put_var(ncid2, varid, chanlonO, (/1/), (/nobs/))\n\n        !-- write elevations\n         iret = nf90_inq_varid(ncid,\"altitude\", varid)\n         iret = nf90_put_var(ncid, varid, elevation, (/1/), (/nstations/))\n\n         iret = nf90_inq_varid(ncid2,\"altitude\", varid)\n         iret = nf90_put_var(ncid2, varid, elevationO, (/1/), (/nobs/))\n\n      !-- write gage location\n!      iret = nf90_inq_varid(ncid,\"gages\", varid)\n!      iret = nf90_put_var(ncid, varid, STRMFRXSTPTS, (/1/), (/nstations/))\n\n        !-- write number_of_stations, OPTIONAL\n      !!  iret = nf90_inq_varid(ncid,\"number_stations\", varid)\n      !!  iret = nf90_put_var_int(ncid, varid, nstations)\n\n        !-- write station id's\n         do i=1,nstations\n          TSTART(1) = 1\n          TSTART(2) = i\n          TCOUNT(1) = TXLEN\n          TCOUNT(2) = 1\n          iret = nf90_inq_varid(ncid,\"station_id\", varid)\n          iret = nf90_put_var(ncid, varid, stname(i), TSTART, TCOUNT)\n         enddo\n\n        !-- write observation id's\n         do i=1, nobs\n          OTSTART(1) = 1\n          OTSTART(2) = i\n          OTCOUNT(1) = OTXLEN\n          OTCOUNT(2) = 1\n          iret = nf90_inq_varid(ncid2,\"station_id\", varid)\n          iret = nf90_put_var(ncid2, varid, stnameO(i), OTSTART, OTCOUNT)\n         enddo\n\n     endif\n\n     output_count = output_count + 1\n\n     open (unit=55, &\n#ifndef NCEP_WCOSS\n     file='frxst_pts_out.txt', &\n#endif\n     status='unknown',position='append')\n\n     cnt=0\n     do i=1,nlk\n\n       if(ORDER(i) .ge. order_to_write) then\n         start_pos = (cnt+1)+(nstations*(output_count-1))\n\n         !!--time in seconds since startdate\n          iret = nf90_inq_varid(ncid,\"time\", varid)\n          iret = nf90_put_var(ncid, varid, seconds_since, (/1/))\n\n         if(UDMP_OPT .eq. 1) then\n            !! FLUXES to channel\n             if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n                nlst(did)%output_channelBucket_influx .eq. 2      ) then\n                iret = nf90_inq_varid(ncid,\"qSfcLatRunoff\", varid)\n                iret = nf90_put_var(ncid, varid, qSfcLatRunoff(i), (/start_pos/))\n\n                iret = nf90_inq_varid(ncid,\"qBucket\", varid)\n                iret = nf90_put_var(ncid, varid, qBucket(i), (/start_pos/))\n             end if\n\n             !! FLUXES to bucket\n             if(nlst(did)%output_channelBucket_influx .eq. 2) then\n                iret = nf90_inq_varid(ncid,\"qBtmVertRunoff\", varid)\n                iret = nf90_put_var(ncid, varid, qBtmVertRunoff(i), (/start_pos/))\n             end if\n\n            !! ACCUMULATIONS\n             if(nlst(did)%output_channelBucket_influx .eq. 3) then\n                iret = nf90_inq_varid(ncid,\"accSfcLatRunoff\", varid)\n                iret = nf90_put_var(ncid, varid, accSfcLatRunoff(i), (/start_pos/))\n\n                iret = nf90_inq_varid(ncid,\"accBucket\", varid)\n                iret = nf90_put_var(ncid, varid, accBucket(i), (/start_pos/))\n             end if\n          endif\n\n         iret = nf90_inq_varid(ncid,\"streamflow\", varid)\n         iret = nf90_put_var(ncid, varid, qlink(i,1), (/start_pos/))\n\n#ifdef WRF_HYDRO_NUDGING\n         iret = nf90_inq_varid(ncid,\"nudge\", varid)\n         iret = nf90_put_var(ncid, varid, nudge(i), (/start_pos/))\n#endif\n\n!        iret = nf90_inq_varid(ncid,\"pos_streamflow\", varid)\n!        iret = nf90_put_var(ncid, varid, abs(qlink(i,1), (/start_pos/)))\n\n         iret = nf90_inq_varid(ncid,\"head\", varid)\n         iret = nf90_put_var(ncid, varid, hlink(i), (/start_pos/))\n\n         iret = nf90_inq_varid(ncid,\"order\", varid)\n         iret = nf90_put_var(ncid, varid, ORDER(i), (/start_pos/))\n\n         !-- station index.. will repeat for every timesstep\n         iret = nf90_inq_varid(ncid,\"parent_index\", varid)\n         iret = nf90_put_var(ncid, varid, cnt, (/start_pos/))\n\n          !--record number of previous record for same station\n!obsolete format         prev_pos = cnt+(nstations*(output_count-1))\n         prev_pos = cnt+(nobs*(output_count-2))\n         if(output_count.ne.1) then !-- only write next set of records\n           iret = nf90_inq_varid(ncid,\"prevChild\", varid)\n           iret = nf90_put_var(ncid, varid, prev_pos, (/start_pos/))\n         endif\n         cnt=cnt+1  !--indices are 0 based\n         rec_num_of_station(cnt) = start_pos-1  !-- save position for last child, 0-based!!\n\n\n       endif\n    enddo\n!    close(999)\n\n    !-- output  only observation points\n    cnt=0\n    do i=1,nlk\n       if(channel_option .ne. 3) then\n          ! jlm this verry repetitiuos, oh well.\n          if(trim(gages(i)) .ne. trim(gageMiss)) then\n\n             start_posO = (cnt+1)+(nobs * (output_count-1))\n             !Write frxst_pts to text file...\n             !yw          write(55,117) seconds_since,trim(date),cnt,chlon(i),chlat(i), &\n118          FORMAT(I8,\",\",A10,1X,A8,\", \",A15,\",\",F10.5,\",\",F8.5,\",\",F9.3,\",\",F12.3,\",\",F6.3)\n             !write(55,118) seconds_since, date(1:10), date(12:19), &\n\n             write(55,118) seconds_since, hydroTime(1:10), hydroTime(12:19), &\n                  gages(i), chlon(i), chlat(i),                               &\n                  qlink(i,1), qlink(i,1)*35.314666711511576, hlink(i)\n\n             !yw 117 FORMAT(I8,1X,A25,1X,I7,1X,F10.5,1X,F8.5,1X,F9.3,1x,F12.3,1X,F6.3)\n             !yw 117 FORMAT(I8,1X,A10,1X,A8,1x,I7,1X,F10.5,1X,F8.5,1X,F9.3,1x,F12.3,1X,F6.3)\n\n             !!--time in seconds since startdate\n             iret = nf90_inq_varid(ncid2,\"time\", varid)\n             iret = nf90_put_var(ncid2, varid, seconds_since, (/1/))\n\n             iret = nf90_inq_varid(ncid2,\"streamflow\", varid)\n             iret = nf90_put_var(ncid2, varid, qlink(i,1), (/start_posO/))\n\n#ifdef WRF_HYDRO_NUDGING\n             iret = nf90_inq_varid(ncid2,\"nudge\", varid)\n             iret = nf90_put_var(ncid2, varid, nudge(i), (/start_posO/))\n#endif\n\n             iret = nf90_inq_varid(ncid2,\"head\", varid)\n             iret = nf90_put_var(ncid2, varid, hlink(i), (/start_posO/))\n\n             iret = nf90_inq_varid(ncid,\"order\", varid)\n             iret = nf90_put_var(ncid2, varid, ORDER(i), (/start_posO/))\n\n             !-- station index.. will repeat for every timesstep\n             iret = nf90_inq_varid(ncid2,\"parent_index\", varid)\n             iret = nf90_put_var(ncid2, varid, cnt, (/start_posO/))\n\n             !--record number of previous record for same station\n             !obsolete format          prev_posO = cnt+(nobs*(output_count-1))\n             prev_posO = cnt+(nobs*(output_count-2))\n             if(output_count.ne.1) then !-- only write next set of records\n                iret = nf90_inq_varid(ncid2,\"prevChild\", varid)\n                iret = nf90_put_var(ncid2, varid, prev_posO, (/start_posO/))\n\n                !IF block to add -1 to last element of prevChild array to designate end of list...\n                !           if(cnt+1.eq.nobs.AND.output_count.eq.split_output_count) then\n                !             iret = nf90_put_vara_int(ncid2, varid, (/start_posO/), (/1/), -1)\n                !           else\n                !             iret = nf90_put_var(ncid2, varid, prev_posO, (/start_posO/))\n                !           endif\n\n             endif\n             cnt=cnt+1  !--indices are 0 based\n             rec_num_of_stationO(cnt) = start_posO - 1  !-- save position for last child, 0-based!!\n          endif\n\n\n       else !! channel options 3 below\n\n          if(STRMFRXSTPTS(i) .ne. -9999) then\n             start_posO = (cnt+1)+(nobs * (output_count-1))\n             !Write frxst_pts to text file...\n             !yw          write(55,117) seconds_since,trim(date),cnt,chlon(i),chlat(i), &\n117          FORMAT(I8,\",\",A10,1X,A8,\",\",I7,\",\",F10.5,\",\",F8.5,\",\",F9.3,\",\",F12.3,\",\",F6.3)\n             !write(55,117) seconds_since,date(1:10),date(12:19),cnt,chlon(i),chlat(i), &\n             !     qlink(i,1), qlink(i,1)*35.315,hlink(i)\n             ! JLM: makes more sense to output the value in frxstpts incase they have meaning,\n             ! as below, but I'm not going to make this change until I'm working with gridded\n             ! streamflow again.\n             write(55,117) seconds_since, hydroTime(1:10), hydroTime(12:19), &\n                  strmfrxstpts(i), chlon(i), chlat(i),                        &\n                  qlink(i,1), qlink(i,1)*35.314666711511576, hlink(i)\n\n             !!--time in seconds since startdate\n             iret = nf90_inq_varid(ncid2,\"time\", varid)\n             iret = nf90_put_var(ncid2, varid, seconds_since, (/1/))\n\n             iret = nf90_inq_varid(ncid2,\"streamflow\", varid)\n             iret = nf90_put_var(ncid2, varid, qlink(i,1), (/start_posO/))\n\n             iret = nf90_inq_varid(ncid2,\"head\", varid)\n             iret = nf90_put_var(ncid2, varid, hlink(i), (/start_posO/))\n\n             iret = nf90_inq_varid(ncid,\"order\", varid)\n             iret = nf90_put_var(ncid2, varid, ORDER(i), (/start_posO/))\n\n             !-- station index.. will repeat for every timesstep\n             iret = nf90_inq_varid(ncid2,\"parent_index\", varid)\n             iret = nf90_put_var(ncid2, varid, cnt, (/start_posO/))\n\n             !--record number of previous record for same station\n             !obsolete format          prev_posO = cnt+(nobs*(output_count-1))\n             prev_posO = cnt+(nobs*(output_count-2))\n             if(output_count.ne.1) then !-- only write next set of records\n                iret = nf90_inq_varid(ncid2,\"prevChild\", varid)\n                iret = nf90_put_var(ncid2, varid, prev_posO, (/start_posO/))\n\n                !IF block to add -1 to last element of prevChild array to designate end of list...\n                !           if(cnt+1.eq.nobs.AND.output_count.eq.split_output_count) then\n                !             iret = nf90_put_vara_int(ncid2, varid, (/start_posO/), (/1/), -1)\n                !           else\n                !             iret = nf90_put_var(ncid2, varid, prev_posO, (/start_posO/))\n                !           endif\n\n             endif\n             cnt=cnt+1  !--indices are 0 based\n             rec_num_of_stationO(cnt) = start_posO - 1  !-- save position for last child, 0-based!!\n          endif\n\n       endif\n\n    enddo\n    close(55)\n\n      !-- lastChild variable gives the record number of the most recent report for the station\n      iret = nf90_inq_varid(ncid,\"lastChild\", varid)\n      iret = nf90_put_var(ncid, varid, rec_num_of_station, (/1/), (/nstations/))\n\n      !-- lastChild variable gives the record number of the most recent report for the station\n      iret = nf90_inq_varid(ncid2,\"lastChild\", varid)\n      iret = nf90_put_var(ncid2, varid, rec_num_of_stationO, (/1/), (/nobs/))\n\n      iret = nf90_redef(ncid)\n      date19(1:19) = \"0000-00-00_00:00:00\"\n      date19(1:len_trim(date)) = date\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n\n      iret = nf90_redef(ncid2)\n      iret = nf90_put_att(ncid2, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n\n      iret = nf90_enddef(ncid)\n      iret = nf90_sync(ncid)\n\n      iret = nf90_enddef(ncid2)\n      iret = nf90_sync(ncid2)\n\n      if (output_count == split_output_count) then\n        output_count = 0\n        iret = nf90_close(ncid)\n        iret = nf90_close(ncid2)\n     endif\n\n     if(allocated(chanlat))  deallocate(chanlat)\n     if(allocated(chanlon))  deallocate(chanlon)\n     if(allocated(elevation))  deallocate(elevation)\n     if(allocated(station_id))  deallocate(station_id)\n     if(allocated(lOrder))  deallocate(lOrder)\n     if(allocated(rec_num_of_station))  deallocate(rec_num_of_station)\n     if(allocated(stname))  deallocate(stname)\n\n     if(allocated(chanlatO))  deallocate(chanlatO)\n     if(allocated(chanlonO))  deallocate(chanlonO)\n     if(allocated(elevationO))  deallocate(elevationO)\n     if(allocated(station_idO))  deallocate(station_idO)\n     if(allocated(lOrderO))  deallocate(lOrderO)\n     if(allocated(rec_num_of_stationO))  deallocate(rec_num_of_stationO)\n     if(allocated(stnameO))  deallocate(stnameO)\n#ifdef HYDRO_D\n     print *, \"Exited Subroutine output_chrt\"\n#endif\n     close(16)\n\n20 format(i8,',',f12.7,',',f10.7,',',f6.2,',',i3)\n\nend subroutine output_chrt_bak\n\n#ifdef MPP_LAND\n!-- output the channel route in an IDV 'station' compatible format\n   subroutine mpp_output_chrt(gnlinks,gnlinksl,map_l2g,igrid,                  &\n        split_output_count, NLINKS, ORDER,                                     &\n        startdate, date, chlon, chlat, hlink,zelev,qlink,dtrt_ch,              &\n        K,STRMFRXSTPTS,order_to_write,NLINKSL,channel_option, gages, gageMiss, &\n        lsmDt                                       &\n#ifdef WRF_HYDRO_NUDGING\n        , nudge                                     &\n#endif\n        , accSfcLatRunoff, accBucket                 &\n        ,   qSfcLatRunoff,   qBucket, qBtmVertRunoff &\n        ,        UDMP_OPT                            &\n        )\n\n       USE module_mpp_land\n\n       implicit none\n\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid,K,channel_option,NLINKSL\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLINKS\n     real, dimension(:),               intent(in) :: chlon,chlat\n     real, dimension(:),                  intent(in) :: hlink,zelev\n\n     integer, dimension(:),               intent(in) :: ORDER\n     integer, dimension(:),               intent(inout) :: STRMFRXSTPTS\n     character(len=15), dimension(:),     intent(inout) :: gages\n     character(len=15),                   intent(in) :: gageMiss\n     real,                                intent(in) :: lsmDt\n\n     real,                                     intent(in) :: dtrt_ch\n     real, dimension(:,:),                intent(in) :: qlink\n#ifdef WRF_HYDRO_NUDGING\n     real, dimension(:),                  intent(in) :: nudge\n#endif\n\n     integer, intent(in) :: UDMP_OPT\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n      integer  :: gnlinks, map_l2g(nlinks), order_to_write, gnlinksl\n      real, allocatable,dimension(:) :: g_chlon,g_chlat, g_hlink,g_zelev\n#ifdef WRF_HYDRO_NUDGING\n      real, allocatable,dimension(:) :: g_nudge\n#endif\n      integer, allocatable,dimension(:) :: g_order,g_STRMFRXSTPTS\n      real,allocatable,dimension(:,:) :: g_qlink\n      integer  :: gsize\n      character(len=15),allocatable,dimension(:) :: g_gages\n      real*8, dimension(:), intent(in) ::   accSfcLatRunoff,   accBucket\n      real  , dimension(:), intent(in) ::     qSfcLatRunoff,     qBucket, qBtmVertRunoff\n      real*8,allocatable,dimension(:)  :: g_accSfcLatRunoff, g_accBucket\n      real  ,allocatable,dimension(:)  ::   g_qSfcLatRunoff,   g_qBucket, g_qBtmVertRunoff\n\n        gsize = gNLINKS\n        if(gnlinksl .gt. gsize) gsize = gnlinksl\n     if(my_id .eq. io_id ) then\n        allocate(g_chlon(gsize  ))\n        allocate(g_chlat(gsize  ))\n        allocate(g_hlink(gsize  ))\n        allocate(g_zelev(gsize  ))\n        allocate(g_qlink(gsize  ,2))\n#ifdef WRF_HYDRO_NUDGING\n        allocate(g_nudge(gsize))\n#endif\n        allocate(g_order(gsize  ))\n        allocate(g_STRMFRXSTPTS(gsize  ))\n        allocate(g_gages(gsize))\n\n        if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n           nlst(did)%output_channelBucket_influx .eq. 2      ) then\n           allocate(g_qSfcLatRunoff(  gsize ))\n           allocate(g_qBucket(        gsize ))\n        endif\n\n        if(nlst(did)%output_channelBucket_influx .eq. 2) &\n             allocate(g_qBtmVertRunoff(  gsize ))\n\n        if(nlst(did)%output_channelBucket_influx .eq. 3) then\n           allocate(g_accSfcLatRunoff(gsize ))\n           allocate(g_accBucket(      gsize ))\n        endif\n\n     else\n\n        if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n           nlst(did)%output_channelBucket_influx .eq. 2      ) then\n           allocate(g_qSfcLatRunoff(  1))\n           allocate(g_qBucket(        1))\n        end if\n\n        if(nlst(did)%output_channelBucket_influx .eq. 2) &\n             allocate(g_qBtmVertRunoff(  1))\n\n        if(nlst(did)%output_channelBucket_influx .eq. 3) then\n           allocate(g_accSfcLatRunoff(1))\n           allocate(g_accBucket(      1))\n        end if\n\n        allocate(g_chlon(1))\n        allocate(g_chlat(1))\n        allocate(g_hlink(1))\n        allocate(g_zelev(1))\n        allocate(g_qlink(1,2))\n#ifdef WRF_HYDRO_NUDGING\n        allocate(g_nudge(1))\n#endif\n        allocate(g_order(1))\n        allocate(g_STRMFRXSTPTS(1))\n        allocate(g_gages(1))\n     endif\n\n     call mpp_land_sync()\n\n     if(channel_option .eq. 1 .or. channel_option .eq. 2) then\n        g_qlink = 0\n        g_gages = gageMiss\n        call ReachLS_write_io(qlink(:,1), g_qlink(:,1))\n        call ReachLS_write_io(qlink(:,2), g_qlink(:,2))\n#ifdef WRF_HYDRO_NUDGING\n        g_nudge=0\n        call ReachLS_write_io(nudge,g_nudge)\n#endif\n        call ReachLS_write_io(order, g_order)\n        call ReachLS_write_io(chlon, g_chlon)\n        call ReachLS_write_io(chlat, g_chlat)\n        call ReachLS_write_io(zelev, g_zelev)\n\n        call ReachLS_write_io(gages, g_gages)\n        call ReachLS_write_io(STRMFRXSTPTS, g_STRMFRXSTPTS)\n        call ReachLS_write_io(hlink, g_hlink)\n\n        if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n           nlst(did)%output_channelBucket_influx .eq. 2      ) then\n           call ReachLS_write_io(qSfcLatRunoff, g_qSfcLatRunoff)\n           call ReachLS_write_io(qBucket, g_qBucket)\n        end if\n\n        if(nlst(did)%output_channelBucket_influx .eq. 2) &\n             call ReachLS_write_io(qBtmVertRunoff, g_qBtmVertRunoff)\n\n        if(nlst(did)%output_channelBucket_influx .eq. 3) then\n           call ReachLS_write_io(accSfcLatRunoff, g_accSfcLatRunoff)\n           call ReachLS_write_io(accBucket, g_accBucket)\n        end if\n\n     else\n        call write_chanel_real(qlink(:,1),map_l2g,gnlinks,nlinks,g_qlink(:,1))\n        call write_chanel_real(qlink(:,2),map_l2g,gnlinks,nlinks,g_qlink(:,2))\n        call write_chanel_int(order,map_l2g,gnlinks,nlinks,g_order)\n        call write_chanel_real(chlon,map_l2g,gnlinks,nlinks,g_chlon)\n        call write_chanel_real(chlat,map_l2g,gnlinks,nlinks,g_chlat)\n        call write_chanel_real(zelev,map_l2g,gnlinks,nlinks,g_zelev)\n        call write_chanel_int(STRMFRXSTPTS,map_l2g,gnlinks,nlinks,g_STRMFRXSTPTS)\n        call write_chanel_real(hlink,map_l2g,gnlinks,nlinks,g_hlink)\n     endif\n\n\n     if(my_id .eq. IO_id) then\n       call output_chrt(igrid, split_output_count, GNLINKS, g_ORDER,                &\n          startdate, date, g_chlon, g_chlat, g_hlink,g_zelev,g_qlink,dtrt_ch,K,     &\n          g_STRMFRXSTPTS,order_to_write,gNLINKSL,channel_option, g_gages, gageMiss, &\n          lsmDt                                                                     &\n#ifdef WRF_HYDRO_NUDGING\n          , g_nudge                                     &\n#endif\n          , g_accSfcLatRunoff, g_accBucket                   &\n          , g_qSfcLatRunoff,   g_qBucket,   g_qBtmVertRunoff &\n          , UDMP_OPT                                         &\n          )\n\n    end if\n     call mpp_land_sync()\n    if(allocated(g_order)) deallocate(g_order)\n    if(allocated(g_STRMFRXSTPTS)) deallocate(g_STRMFRXSTPTS)\n    if(allocated(g_chlon)) deallocate(g_chlon)\n    if(allocated(g_chlat)) deallocate(g_chlat)\n    if(allocated(g_hlink)) deallocate(g_hlink)\n    if(allocated(g_zelev)) deallocate(g_zelev)\n    if(allocated(g_qlink)) deallocate(g_qlink)\n    if(allocated(g_gages)) deallocate(g_gages)\n#ifdef WRF_HYDRO_NUDGING\n    if(allocated(g_nudge)) deallocate(g_nudge)\n#endif\n    if(allocated(g_qSfcLatRunoff))   deallocate(g_qSfcLatRunoff)\n    if(allocated(g_qBucket))         deallocate(g_qBucket)\n    if(allocated(g_qBtmVertRunoff))  deallocate(g_qBtmVertRunoff)\n    if(allocated(g_accSfcLatRunoff)) deallocate(g_accSfcLatRunoff)\n    if(allocated(g_accBucket))       deallocate(g_accBucket)\n\nend subroutine mpp_output_chrt\n\n!---------  lake netcdf output -----------------------------------------\n!-- output the ilake info an IDV 'station' compatible format -----------\n   subroutine mpp_output_lakes(lake_index,igrid, split_output_count, NLAKES, &\n        startdate, date, latlake, lonlake, elevlake, &\n        qlakei,qlakeo, resht,dtrt_ch,K)\n\n   USE module_mpp_land\n\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid, K\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLAKES\n     real, dimension(NLAKES),                  intent(in) :: latlake,lonlake,elevlake,resht\n     real, dimension(NLAKES),                  intent(in) :: qlakei,qlakeo  !-- inflow and outflow of lake\n     real,                                     intent(in) :: dtrt_ch\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n     integer lake_index(nlakes)\n\n\n     call write_lake_real(latlake,lake_index,nlakes)\n     call write_lake_real(lonlake,lake_index,nlakes)\n     call write_lake_real(elevlake,lake_index,nlakes)\n     call write_lake_real(resht,lake_index,nlakes)\n     call write_lake_real(qlakei,lake_index,nlakes)\n     call write_lake_real(qlakeo,lake_index,nlakes)\n     if(my_id.eq. IO_id) then\n        call output_lakes(igrid, split_output_count, NLAKES, &\n           startdate, date, latlake, lonlake, elevlake, &\n           qlakei,qlakeo, resht,dtrt_ch,K)\n     end if\n     call mpp_land_sync()\n     end subroutine mpp_output_lakes\n\n   subroutine mpp_output_lakes2(lake_index,igrid, split_output_count, NLAKES, &\n        startdate, date, latlake, lonlake, elevlake, &\n        qlakei,qlakeo, resht,dtrt_ch,K, LAKEIDM)\n\n   USE module_mpp_land\n\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid, K\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLAKES\n     real, dimension(NLAKES),                  intent(inout) :: latlake,lonlake,elevlake,resht\n     real, dimension(NLAKES),                  intent(inout) :: qlakei,qlakeo  !-- inflow and outflow of lake\n     real,                                     intent(in) :: dtrt_ch\n     integer(kind=int64), dimension(NLAKES),   intent(in) :: LAKEIDM     ! lake id\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n     integer lake_index(nlakes)\n\n     call write_lake_real(latlake,lake_index,nlakes)\n     call write_lake_real(lonlake,lake_index,nlakes)\n     call write_lake_real(elevlake,lake_index,nlakes)\n     call write_lake_real(resht,lake_index,nlakes)\n     call write_lake_real(qlakei,lake_index,nlakes)\n     call write_lake_real(qlakeo,lake_index,nlakes)\n\n     if(my_id.eq. IO_id) then\n        call output_lakes2(igrid, split_output_count, NLAKES, &\n           startdate, date, latlake, lonlake, elevlake, &\n           qlakei,qlakeo, resht,dtrt_ch,K, LAKEIDM)\n     end if\n     call mpp_land_sync()\n     end subroutine mpp_output_lakes2\n#endif\n\n!----------------------------------- lake netcdf output\n!-- output the ilake info an IDV 'station' compatible format\n   subroutine output_lakes(igrid, split_output_count, NLAKES, &\n        startdate, date, latlake, lonlake, elevlake, &\n        qlakei,qlakeo, resht,dtrt_ch,K)\n\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid, K\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLAKES\n     real, dimension(NLAKES),                  intent(in) :: latlake,lonlake,elevlake,resht\n     real, dimension(NLAKES),                  intent(in) :: qlakei,qlakeo  !-- inflow and outflow of lake\n     real,                                     intent(in) :: dtrt_ch\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n     integer, allocatable, DIMENSION(:)                   :: station_id\n     integer, allocatable, DIMENSION(:)                   :: rec_num_of_lake\n\n     integer, save  :: output_count\n     integer, save :: ncid\n\n     integer :: stationdim, dimdata, varid, charid, n\n     integer :: iret,i, start_pos, prev_pos  !--\n     integer :: previous_pos        !-- used for the station model\n     character(len=256) :: output_flnm\n     character(len=19)  :: date19, date19start\n     character(len=34)  :: sec_since_date\n     integer :: seconds_since,cnt\n     character(len=32)  :: convention\n     character(len=6),allocatable, DIMENSION(:)  :: stname\n     integer :: timedim\n     character(len=34) :: sec_valid_date\n\n    !--- all this for writing the station id string\n     INTEGER   TDIMS, TXLEN\n     PARAMETER (TDIMS=2)    ! number of TX dimensions\n     PARAMETER (TXLEN = 6) ! length of example string\n     INTEGER  TIMEID        ! record dimension id\n     INTEGER  TXID          ! variable ID\n     INTEGER  TXDIMS(TDIMS) ! variable shape\n     INTEGER  TSTART(TDIMS), TCOUNT(TDIMS)\n\n!    sec_since_date = 'seconds since '//date(1:4)//'-'//date(6:7)//'-'//date(9:10)//' '//date(12:13)//':'//date(15:16)//' UTC'\n!    seconds_since = int(dtrt_ch)*output_count\n     seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n     sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                     //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n\n     allocate(station_id(NLAKES))\n     allocate(rec_num_of_lake(NLAKES))\n     allocate(stname(NLAKES))\n\n     if (output_count == 0) then\n\n!-- have moved sec_since_date from above here..\n      sec_since_date = 'seconds since '//startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10) &\n                  //' '//startdate(12:13)//':'//startdate(15:16)//' UTC'\n\n      date19start(1:len_trim(startdate)) = startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10)//'_' &\n                  //startdate(12:13)//':'//startdate(15:16)//':00'\n\n      write(output_flnm, '(A12,\".LAKEOUT_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n#ifdef HYDRO_D\n      print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n      iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n      if (iret /= 0) then\n         call hydro_stop(\"In output_lakes() - Problem nf90_create\")\n      endif\n\n      do i=1,NLAKES\n         station_id(i) = i\n         write(stname(i),'(I6)') i\n      enddo\n\n      iret = nf90_def_dim(ncid, \"recNum\", NF90_UNLIMITED, dimdata)  !--for linked list approach\n      iret = nf90_def_dim(ncid, \"station\", nlakes, stationdim)\n      iret = nf90_def_dim(ncid, \"time\", 1, timedim)\n\n!#ifndef HYDRO_REALTIME\n      !- station location definition,  lat\n      iret = nf90_def_var(ncid, \"latitude\", NF90_FLOAT, (/stationdim/), varid)\n      iret = nf90_put_att(ncid, varid, 'long_name', 'Lake latitude')\n      iret = nf90_put_att(ncid, varid, 'units', 'degrees_north')\n\n      !- station location definition,  long\n      iret = nf90_def_var(ncid, \"longitude\", NF90_FLOAT, (/stationdim/), varid)\n      iret = nf90_put_att(ncid, varid, 'long_name', 'Lake longitude')\n      iret = nf90_put_att(ncid, varid, 'units', 'degrees_east')\n\n!     !-- lake's phyical elevation\n!     iret = nf90_def_var(ncid, \"altitude\", NF90_FLOAT, (/stationdim/), varid)\n!     iret = nf90_put_att(ncid, varid, 'long_name', 'Lake altitude')\n!     iret = nf90_put_att(ncid, varid, 'units', 'meters')\n!#endif\n\n     !-- parent index\n!     iret = nf90_def_var(ncid, \"parent_index\", NF90_INT, (/dimdata/), varid)\n!     iret = nf90_put_att(ncid, varid, 'long_name', 'index of the lake for this record')\n\n     !-- prevChild\n!     iret = nf90_def_var(ncid, \"prevChild\", NF90_INT, (/dimdata/), varid)\n!     iret = nf90_put_att(ncid, varid, 'long_name', 'record number of the previous record for the same lake')\n!ywtmp      iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n!     iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n     !-- lastChild\n!     iret = nf90_def_var(ncid, \"lastChild\", NF90_INT, (/stationdim/), varid)\n!     iret = nf90_put_att(ncid, varid, 'long_name', 'latest report for this lake')\n!ywtmp      iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n!     iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n!     !- water surface elevation\n      iret = nf90_def_var(ncid, \"wse\", NF90_FLOAT, (/dimdata/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'meters')\n      iret = nf90_put_att(ncid, varid, 'long_name', 'Water Surface Elevation')\n\n!     !- inflow to lake\n      iret = nf90_def_var(ncid, \"inflow\", NF90_FLOAT, (/dimdata/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n\n!     !- outflow to lake\n      iret = nf90_def_var(ncid, \"outflow\", NF90_FLOAT, (/dimdata/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n\n     !-- station  id\n     ! define character-position dimension for strings of max length 6\n         iret = NF90_DEF_DIM(ncid, \"id_len\", 6, charid)\n         TXDIMS(1) = charid   ! define char-string variable and position dimension first\n         TXDIMS(2) = stationdim\n         iret = nf90_def_var(ncid, \"station_id\", NF90_CHAR, TXDIMS, varid)\n         iret = nf90_put_att(ncid, varid, 'long_name', 'Station id')\n\n!     !- time definition, timeObs\n         iret = nf90_def_var(ncid, \"time\", NF90_INT, (/timedim/), varid)\n         iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n         iret = nf90_put_att(ncid, varid, 'long_name', 'valid output time')\n\n!       date19(1:19) = \"0000-00-00_00:00:00\"\n!       date19(1:len_trim(startdate)) = startdate\n!       iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n!\n        date19(1:19) = \"0000-00-00_00:00:00\"\n        date19(1:len_trim(startdate)) = startdate\n        convention(1:32) = \"Unidata Observation Dataset v1.0\"\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"cdm_datatype\", \"Station\")\n!#ifndef HYDRO_REALTIME\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_max\", \"90.0\")\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_min\", \"-90.0\")\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_max\", \"180.0\")\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_min\", \"-180.0\")\n!#endif\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"station_dimension\", \"station\")\n!!       iret = nf90_put_att(ncid, NF90_GLOBAL, \"observation_dimension\", \"recNum\")\n!!        iret = nf90_put_att(ncid, NF90_GLOBAL, \"time_coordinate\", \"time_observation\")\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n        iret = nf90_enddef(ncid)\n\n!#ifndef HYDRO_REALTIME\n        !-- write latitudes\n        iret = nf90_inq_varid(ncid,\"latitude\", varid)\n        iret = nf90_put_var(ncid, varid, LATLAKE, (/1/), (/NLAKES/))\n\n        !-- write longitudes\n        iret = nf90_inq_varid(ncid,\"longitude\", varid)\n        iret = nf90_put_var(ncid, varid, LONLAKE, (/1/), (/NLAKES/))\n\n        !-- write physical height of lake\n!       iret = nf90_inq_varid(ncid,\"altitude\", varid)\n!       iret = nf90_put_var(ncid, varid, elevlake, (/1/), (/NLAKES/))\n!#endif\n\n        !-- write station id's\n         do i=1,nlakes\n          TSTART(1) = 1\n          TSTART(2) = i\n          TCOUNT(1) = TXLEN\n          TCOUNT(2) = 1\n          iret = nf90_inq_varid(ncid,\"station_id\", varid)\n          iret = nf90_put_var(ncid, varid, stname(i), TSTART, TCOUNT)\n         enddo\n\n     endif\n\n     iret = nf90_inq_varid(ncid,\"time\", varid)\n     iret = nf90_put_var(ncid, varid, seconds_since, (/1/))\n\n     output_count = output_count + 1\n\n     cnt=0\n     do i=1,NLAKES\n\n         start_pos = (cnt+1)+(nlakes*(output_count-1))\n\n         !!--time in seconds since startdate\n         iret = nf90_inq_varid(ncid,\"time_observation\", varid)\n         iret = nf90_put_var(ncid, varid, seconds_since, (/start_pos/))\n\n         iret = nf90_inq_varid(ncid,\"wse\", varid)\n         iret = nf90_put_var(ncid, varid, resht(i), (/start_pos/))\n\n         iret = nf90_inq_varid(ncid,\"inflow\", varid)\n         iret = nf90_put_var(ncid, varid, qlakei(i), (/start_pos/))\n\n         iret = nf90_inq_varid(ncid,\"outflow\", varid)\n         iret = nf90_put_var(ncid, varid, qlakeo(i), (/start_pos/))\n\n         !-- station index.. will repeat for every timesstep\n!        iret = nf90_inq_varid(ncid,\"parent_index\", varid)\n!        iret = nf90_put_var(ncid, varid, cnt, (/start_pos/))\n\n          !--record number of previous record for same station\n!        prev_pos = cnt+(nlakes*(output_count-1))\n!        if(output_count.ne.1) then !-- only write next set of records\n!          iret = nf90_inq_varid(ncid,\"prevChild\", varid)\n!          iret = nf90_put_var(ncid, varid, prev_pos, (/start_pos/))\n!        endif\n\n         cnt=cnt+1  !--indices are 0 based\n         rec_num_of_lake(cnt) = start_pos-1  !-- save position for last child, 0-based!!\n\n    enddo\n\n      !-- lastChild variable gives the record number of the most recent report for the station\n      iret = nf90_inq_varid(ncid,\"lastChild\", varid)\n      iret = nf90_put_var(ncid, varid, rec_num_of_lake, (/1/), (/nlakes/))\n\n     !-- number of children reported for this station, OPTIONAL\n     !--  iret = nf90_inq_varid(ncid,\"numChildren\", varid)\n     !--  iret = nf90_put_var(ncid, varid, rec_num_of_lake, (/1/), (/nlakes/))\n\n    iret = nf90_redef(ncid)\n    iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n    iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n    iret = nf90_enddef(ncid)\n\n    iret = nf90_sync(ncid)\n     if (output_count == split_output_count) then\n        output_count = 0\n        iret = nf90_close(ncid)\n     endif\n\n     if(allocated(station_id)) deallocate(station_id)\n     if(allocated(rec_num_of_lake)) deallocate(rec_num_of_lake)\n     if(allocated(stname)) deallocate(stname)\n#ifdef HYDRO_D\n     print *, \"Exited Subroutine output_lakes\"\n#endif\n     close(16)\n\n end subroutine output_lakes\n\n!----------------------------------- lake netcdf output\n!-- output the lake as regular netcdf file format for better performance than point netcdf file.\n   subroutine output_lakes2(igrid, split_output_count, NLAKES, &\n        startdate, date, latlake, lonlake, elevlake, &\n        qlakei,qlakeo, resht,dtrt_ch,K,LAKEIDM)\n\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid, K\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLAKES\n     real, dimension(NLAKES),                  intent(in) :: latlake,lonlake,elevlake,resht\n     real, dimension(NLAKES),                  intent(in) :: qlakei,qlakeo  !-- inflow and outflow of lake\n     integer(kind=int64), dimension(NLAKES),       intent(in) :: LAKEIDM        !-- LAKE ID\n     real,                                     intent(in) :: dtrt_ch\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n\n     integer, save  :: output_count\n     integer, save :: ncid\n\n     integer :: stationdim, varid,  n\n     integer :: iret,i    !--\n     character(len=256) :: output_flnm\n     character(len=19)  :: date19, date19start\n     character(len=32)  :: convention\n     integer :: timedim\n     integer :: seconds_since\n     character(len=34) :: sec_valid_date\n     sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                         //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n     seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n\n     if (output_count == 0) then\n\n      date19start(1:len_trim(startdate)) = startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10)//'_' &\n                  //startdate(12:13)//':'//startdate(15:16)//':00'\n\n      write(output_flnm, '(A12,\".LAKEOUT_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n#ifdef HYDRO_D\n      print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n      iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n      if (iret /= 0) then\n         call hydro_stop(\"In output_lakes() - Problem nf90_create\")\n      endif\n\n      iret = nf90_def_dim(ncid, \"station\", nlakes, stationdim)\n\n      iret = nf90_def_dim(ncid, \"time\", 1, timedim)\n\n!#ifndef HYDRO_REALTIME\n      !- station location definition,  lat\n      iret = nf90_def_var(ncid, \"latitude\", NF90_FLOAT, (/stationdim/), varid)\n      iret = nf90_put_att(ncid, varid, 'long_name', 'Lake latitude')\n      iret = nf90_put_att(ncid, varid, 'units', 'degrees_north')\n!#endif\n\n      !- station location definition,  LAKEIDM\n      iret = nf90_def_var(ncid, \"lake_id\", NF90_INT, (/stationdim/), varid)\n      iret = nf90_put_att(ncid, varid, 'long_name', 'Lake COMMON ID')\n\n!#ifndef HYDRO_REALTIME\n      !- station location definition,  long\n      iret = nf90_def_var(ncid, \"longitude\", NF90_FLOAT, (/stationdim/), varid)\n      iret = nf90_put_att(ncid, varid, 'long_name', 'Lake longitude')\n      iret = nf90_put_att(ncid, varid, 'units', 'degrees_east')\n\n!     !-- lake's phyical elevation\n!     iret = nf90_def_var(ncid, \"altitude\", NF90_FLOAT, (/stationdim/), varid)\n!     iret = nf90_put_att(ncid, varid, 'long_name', 'Lake altitude')\n!     iret = nf90_put_att(ncid, varid, 'units', 'meters')\n!#endif\n\n!     !- water surface elevation\n      iret = nf90_def_var(ncid, \"wse\", NF90_FLOAT, (/stationdim/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'meters')\n      iret = nf90_put_att(ncid, varid, 'long_name', 'Water Surface Elevation')\n\n!     !- inflow to lake\n      iret = nf90_def_var(ncid, \"inflow\", NF90_FLOAT, (/stationdim/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n\n!     !- outflow to lake\n      iret = nf90_def_var(ncid, \"outflow\", NF90_FLOAT, (/stationdim/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n\n      ! Time variable\n      iret = nf90_def_var(ncid, \"time\", NF90_INT, (/timeDim/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n      iret = nf90_put_att(ncid, varid, 'long_name', 'valid output time')\n\n        date19(1:19) = \"0000-00-00_00:00:00\"\n        date19(1:len_trim(startdate)) = startdate\n!#ifndef HYDRO_REALTIME\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_max\", \"90.0\")\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_min\", \"-90.0\")\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_max\", \"180.0\")\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_min\", \"-180.0\")\n!#endif\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n        iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n        iret = nf90_enddef(ncid)\n\n        iret = nf90_inq_varid(ncid,\"time\", varid)\n        iret = nf90_put_var(ncid, varid, seconds_since, (/1/))\n\n!#ifndef HYDRO_REALTIME\n        !-- write latitudes\n        iret = nf90_inq_varid(ncid,\"latitude\", varid)\n        iret = nf90_put_var(ncid, varid, LATLAKE, (/1/), (/NLAKES/))\n\n        !-- write longitudes\n        iret = nf90_inq_varid(ncid,\"longitude\", varid)\n        iret = nf90_put_var(ncid, varid, LONLAKE, (/1/), (/NLAKES/))\n\n        !-- write physical height of lake\n!       iret = nf90_inq_varid(ncid,\"altitude\", varid)\n!       iret = nf90_put_var(ncid, varid, elevlake, (/1/), (/NLAKES/))\n!#endif\n\n        !-- write elevation  of lake\n        iret = nf90_inq_varid(ncid,\"wse\", varid)\n        iret = nf90_put_var(ncid, varid, resht, (/1/), (/NLAKES/))\n\n        !-- write elevation  of inflow\n        iret = nf90_inq_varid(ncid,\"inflow\", varid)\n        iret = nf90_put_var(ncid, varid, qlakei, (/1/), (/NLAKES/))\n\n        !-- write elevation  of inflow\n        iret = nf90_inq_varid(ncid,\"outflow\", varid)\n        iret = nf90_put_var(ncid, varid, qlakeo, (/1/), (/NLAKES/))\n\n        !-- write lake id\n        iret = nf90_inq_varid(ncid,\"lake_id\", varid)\n        iret = nf90_put_var(ncid, varid, LAKEIDM, (/1/), (/NLAKES/))\n\n     endif\n\n     output_count = output_count + 1\n\n    iret = nf90_redef(ncid)\n    iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n    iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n    iret = nf90_enddef(ncid)\n\n    iret = nf90_sync(ncid)\n     if (output_count == split_output_count) then\n        output_count = 0\n        iret = nf90_close(ncid)\n     endif\n\n end subroutine output_lakes2\n!----------------------------------- lake netcdf output\n\n#ifdef MPP_LAND\n\n!-- output the channel route in an IDV 'grid' compatible format\n   subroutine mpp_output_chrtgrd(igrid, split_output_count, ixrt,jxrt, &\n        NLINKS,CH_NETLNK_in, startdate, date, &\n        qlink, dt, geo_finegrid_flnm, gnlinks,map_l2g,g_ixrt,g_jxrt )\n\n   USE module_mpp_land\n\n     implicit none\n     integer g_ixrt,g_jxrt\n     integer,                                  intent(in) :: igrid\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLINKS,ixrt,jxrt\n     real,                                     intent(in) :: dt\n     real, dimension(:,:),                intent(in) :: qlink\n     integer(kind=int64), dimension(IXRT,JXRT),            intent(in) :: CH_NETLNK_in\n     character(len=*),          intent(in)     :: geo_finegrid_flnm\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n     integer::  gnlinks , map_l2g(nlinks)\n\n     integer(kind=int64), allocatable,dimension(:,:)         :: CH_NETLNK\n     real, allocatable,dimension(:,:)                :: g_qlink\n\n     if(my_id .eq. io_id) then\n        allocate(CH_NETLNK(g_IXRT,g_JXRT))\n        allocate(g_qlink(gNLINKS,2) )\n     else\n        allocate(CH_NETLNK(1,1))\n        allocate(g_qlink(1,2) )\n     endif\n\n     call write_chanel_real(qlink(:,1),map_l2g,gnlinks,nlinks,g_qlink(:,1))\n     call write_chanel_real(qlink(:,2),map_l2g,gnlinks,nlinks,g_qlink(:,2))\n\n     call write_IO_rt_int8(CH_NETLNK_in, CH_NETLNK)\n\n    if(my_id.eq.IO_id) then\n        call  output_chrtgrd(igrid, split_output_count, g_ixrt,g_jxrt, &\n           GNLINKS, CH_NETLNK, startdate, date, &\n           g_qlink, dt, geo_finegrid_flnm)\n    endif\n\n     if(allocated(g_qlink)) deallocate(g_qlink)\n     if(allocated(CH_NETLNK)) deallocate(CH_NETLNK)\n     end subroutine mpp_output_chrtgrd\n#endif\n\n!-- output the channel route in an IDV 'grid' compatible format\n   subroutine output_chrtgrd(igrid, split_output_count, ixrt,jxrt, &\n        NLINKS, CH_NETLNK, startdate, date, &\n        qlink, dt, geo_finegrid_flnm)\n\n     integer,                                  intent(in) :: igrid\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLINKS,ixrt,jxrt\n     real,                                     intent(in) :: dt\n     real, dimension(:,:),                intent(in) :: qlink\n     integer(kind=int64), dimension(IXRT,JXRT), intent(in) :: CH_NETLNK\n     character(len=*),          intent(in)     :: geo_finegrid_flnm\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n     character(len=32)  :: convention\n     integer,save  :: output_count\n     integer, save :: ncid,ncstatic\n     real, dimension(IXRT,JXRT)          :: tmpflow\n     real, dimension(IXRT)            :: xcoord\n     real, dimension(JXRT)            :: ycoord\n     real                                :: long_cm,lat_po,fe,fn\n     real, dimension(2)                  :: sp\n\n    integer :: varid, n\n    integer :: jxlatdim,ixlondim,timedim !-- dimension ids\n    integer :: timedim2\n    character(len=34) :: sec_valid_date\n\n    integer :: iret,i,j\n    character(len=256) :: output_flnm\n    character(len=19)  :: date19\n    character(len=34)  :: sec_since_date\n\n\n    integer :: seconds_since\n\n    seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n    sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                 //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n\n      tmpflow = -9E15\n\n\n        write(output_flnm, '(A12,\".CHRTOUT_GRID\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n#ifdef HYDRO_D\n        print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n\n!--- define dimension\n        iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n        if (iret /= 0) then\n           call hydro_stop(\"In output_chrtgrd() - Problem nf90_create\")\n        endif\n\n        iret = nf90_def_dim(ncid, \"time\", NF90_UNLIMITED, timedim)\n        iret = nf90_def_dim(ncid, \"x\", ixrt, ixlondim)\n        iret = nf90_def_dim(ncid, \"y\", jxrt, jxlatdim)\n\n!--- define variables\n!     !- time definition, timeObs\n\n       !- x-coordinate in cartesian system\n!yw         iret = nf90_def_var(ncid, \"x\", NF90_DOUBLE, (/ixlondim/), varid)\n!yw         iret = nf90_put_att(ncid, varid, 'long_name', 'x coordinate of projection')\n!yw         iret = nf90_put_att(ncid, varid, 'standard_name', 'projection_x_coordinate')\n!yw         iret = nf90_put_att(ncid, varid, 'units', 'Meter')\n\n       !- y-coordinate in cartesian ssystem\n!yw         iret = nf90_def_var(ncid, \"y\", NF90_DOUBLE, (/jxlatdim/), varid)\n!yw         iret = nf90_put_att(ncid, varid, 'long_name', 'y coordinate of projection')\n!yw         iret = nf90_put_att(ncid, varid, 'standard_name', 'projection_y_coordinate')\n!yw         iret = nf90_put_att(ncid, varid, 'units', 'Meter')\n\n!     !- flow definition, var\n        iret = nf90_def_var(ncid, \"streamflow\", NF90_REAL, (/ixlondim,jxlatdim,timedim/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'm3 s-1')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'water flow rate')\n        iret = nf90_put_att(ncid, varid, 'coordinates', 'x y')\n        iret = nf90_put_att(ncid, varid, 'grid_mapping', 'lambert_conformal_conic')\n        iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n        iret = nf90_def_var(ncid, \"index\", NF90_INT, (/ixlondim,jxlatdim/), varid)\n        iret = nf90_def_var(ncid, \"time\", NF90_INT, (/timedim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'valid output time')\n        iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n\n\n!-- place prjection information\n\n\n      date19(1:19) = \"0000-00-00_00:00:00\"\n      date19(1:len_trim(startdate)) = startdate\n      convention(1:32) = \"CF-1.0\"\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n      iret = nf90_enddef(ncid)\n\n      iret = nf90_inq_varid(ncid,\"time\", varid)\n      iret = nf90_put_var(ncid, varid, seconds_since, (/1/))\n\n!!-- write latitude and longitude locations\n\n!DJG inv    do j=jxrt,1,-1\n    do j=1,jxrt\n     do i=1,ixrt\n       if(CH_NETLNK(i,j).GE.0) then\n         tmpflow(i,j) = qlink(CH_NETLNK(i,j),1)\n       else\n         tmpflow(i,j) = -9E15\n       endif\n     enddo\n    enddo\n\n!!time in seconds since startdate\n    iret = nf90_inq_varid(ncid,\"index\", varid)\n    iret = nf90_put_var(ncid, varid, CH_NETLNK, (/1,1/), (/ixrt,jxrt/))\n\n    iret = nf90_inq_varid(ncid,\"streamflow\", varid)\n    iret = nf90_put_var(ncid, varid, tmpflow, (/1,1,1/), (/ixrt,jxrt,1/))\n\n    iret = nf90_close(ncid)\n\n\n\n end subroutine output_chrtgrd\n\n\n subroutine read_chan_forcing( &\n       indir,olddate,startdate,hgrid,&\n       ixrt,jxrt,QSTRMVOLRT_ACC,QINFLOWBASE,QSUBRT)\n! This subrouting is going to read channel forcing for\n!  the old, channel-only simulations (ie when CHANRTSWCRT = 2)\n!  forced by RTOUT_DOMAIN files.\n\n   implicit none\n   ! in variable\n   character(len=*) :: olddate,hgrid,indir,startdate\n   character(len=256) :: filename\n   integer :: ixrt,jxrt\n   real,dimension(ixrt,jxrt):: QSTRMVOLRT_ACC,QINFLOWBASE,QSUBRT\n   ! tmp variable\n   character(len=256) :: inflnm, product\n   integer  :: i,j,mmflag\n   character(len=256) :: units\n   integer :: ierr\n   integer :: ncid\n\n\n!DJG Create filename...\n        inflnm = trim(indir)//\"/\"//&\n             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n             olddate(15:16)//\".RTOUT_DOMAIN\"//hgrid\n#ifdef HYDRO_D\n        print *, \"Channel forcing file...\",inflnm\n#endif\n\n\n!DJG Open NetCDF file...\n    ierr = nf90_open(inflnm, NF90_NOWRITE, ncid)\n    if (ierr /= 0) then\n       write(*,'(\"READFORC_chan Problem opening netcdf file: ''\", A, \"''\")') trim(inflnm)\n       call hydro_stop(\"In read_chan_forcing() - Problem opening netcdf file\")\n    endif\n\n!DJG read data...\n    call get_2d_netcdf(\"QSTRMVOLRT\",  ncid, QSTRMVOLRT_ACC, units, ixrt, jxrt, .TRUE., ierr)\n!DJG TBC    call get_2d_netcdf(\"T2D\", ncid, t,     units, ixrt, jxrt, .TRUE., ierr)\n!DJG TBC    call get_2d_netcdf(\"T2D\", ncid, t,     units, ixrt, jxrt, .TRUE., ierr)\n\n    ierr = nf90_close(ncid)\n\n end subroutine read_chan_forcing\n\n\n\n subroutine get2d_int(var_name,out_buff,ix,jx,fileName, fatalErr)\n    implicit none\n    integer :: iret,varid,ncid,ix,jx\n    integer out_buff(ix,jx)\n    character(len=*), intent(in) :: var_name\n    character(len=*), intent(in) :: fileName\n    logical, optional, intent(in) :: fatalErr\n    logical :: fatalErr_local\n    character(len=256) :: errMsg\n\n    fatalErr_local = .false.\n    if(present(fatalErr)) fatalErr_local=fatalErr\n\n    iret = nf90_open(trim(fileName), NF90_NOWRITE, ncid)\n    if (iret .ne. 0) then\n       errMsg = \"get2d_int: failed to open the netcdf file: \" // trim(fileName)\n       print*, trim(errMsg)\n       if(fatalErr_local) call hydro_stop(trim(errMsg))\n    endif\n\n    iret = nf90_inq_varid(ncid,trim(var_name),  varid)\n    if(iret .ne. 0) then\n       errMsg = \"get2d_int: failed to find the variable: \" // &\n                 trim(var_name) // ' in ' // trim(fileName)\n       print*, trim(errMsg)\n       if(fatalErr_local) call hydro_stop(errMsg)\n    endif\n\n    iret = nf90_get_var(ncid, varid, out_buff)\n    if(iret .ne. 0) then\n       errMsg = \"get2d_int: failed to read the variable: \" // &\n                trim(var_name) // \" in \" //trim(fileName)\n       print*,trim(errMsg)\n       if(fatalErr_local) call hydro_stop(trim(errMsg))\n    endif\n\n    iret = nf90_close(ncid)\n    if(iret .ne. 0) then\n       errMsg = \"get2d_int: failed to close the file: \" // &\n                trim(fileName)\n       print*,trim(errMsg)\n       if(fatalErr_local) call hydro_stop(trim(errMsg))\n    endif\n\n  end subroutine get2d_int\n\n    subroutine get2d_int8(var_name,out_buff,ix,jx,fileName, fatalErr)\n        implicit none\n        integer :: iret,varid,ncid,ix,jx\n        integer(kind=int64) out_buff(ix,jx)\n        character(len=*), intent(in) :: var_name\n        character(len=*), intent(in) :: fileName\n        logical, optional, intent(in) :: fatalErr\n        logical :: fatalErr_local\n        character(len=256) :: errMsg\n\n        fatalErr_local = .false.\n        if(present(fatalErr)) fatalErr_local=fatalErr\n\n        iret = nf90_open(trim(fileName), NF90_NOWRITE, ncid)\n        if (iret .ne. 0) then\n            errMsg = \"get2d_int: failed to open the netcdf file: \" // trim(fileName)\n            print*, trim(errMsg)\n            if(fatalErr_local) call hydro_stop(trim(errMsg))\n        endif\n\n        iret = nf90_inq_varid(ncid,trim(var_name),  varid)\n        if(iret .ne. 0) then\n            errMsg = \"get2d_int: failed to find the variable: \" // &\n                    trim(var_name) // ' in ' // trim(fileName)\n            print*, trim(errMsg)\n            if(fatalErr_local) call hydro_stop(errMsg)\n        endif\n\n        iret = nf90_get_var(ncid, varid, out_buff)\n        if(iret .ne. 0) then\n            errMsg = \"get2d_int: failed to read the variable: \" // &\n                    trim(var_name) // \" in \" //trim(fileName)\n            print*,trim(errMsg)\n            if(fatalErr_local) call hydro_stop(trim(errMsg))\n        endif\n\n        iret = nf90_close(ncid)\n        if(iret .ne. 0) then\n            errMsg = \"get2d_int: failed to close the file: \" // &\n                    trim(fileName)\n            print*,trim(errMsg)\n            if(fatalErr_local) call hydro_stop(trim(errMsg))\n        endif\n\n    end subroutine get2d_int8\n\n#ifdef MPP_LAND\n      SUBROUTINE MPP_READ_ROUTEDIM(did,g_IXRT,g_JXRT, GCH_NETLNK,GNLINKS,IXRT,JXRT, &\n            route_chan_f,route_link_f, &\n            route_direction_f, NLINKS, &\n            CH_NETLNK, channel_option, geo_finegrid_flnm, NLINKSL, UDMP_OPT,NLAKES)\n\n         USE module_mpp_land\n\n         implicit none\n        INTEGER                                      :: channel_option, did\n        INTEGER                                      :: g_IXRT,g_JXRT\n        INTEGER, INTENT(INOUT)                       :: NLINKS, GNLINKS,NLINKSL\n        INTEGER, INTENT(IN)                          :: IXRT,JXRT\n        INTEGER                                      :: CHNID,cnt\n        INTEGER, DIMENSION(IXRT,JXRT)                :: CH_NETRT   !- binary channel mask\n        INTEGER, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: CH_NETLNK  !- each node gets unique id\n        INTEGER, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: GCH_NETLNK  !- each node gets unique id based on global domain\n        ! INTEGER, DIMENSION(g_IXRT,g_JXRT) :: g_CH_NETLNK  ! temp array\n        INTEGER, allocatable,DIMENSION(:,:) :: g_CH_NETLNK  ! temp array\n        INTEGER, DIMENSION(IXRT,JXRT)                :: DIRECTION  !- flow direction\n        INTEGER, DIMENSION(IXRT,JXRT)                :: LAKE_MSKRT\n        REAL, DIMENSION(IXRT,JXRT)                   :: LAT, LON\n        INTEGER, INTENT(IN)                          :: UDMP_OPT\n        integer:: i,j, NLAKES\n\n        CHARACTER(len=*)       :: route_chan_f, route_link_f,route_direction_f\n        CHARACTER(len=*)       :: geo_finegrid_flnm\n!       CHARACTER(len=*)       :: geo_finegrid_flnm\n\n!       integer, allocatable, dimension(:) :: tmp_int\n        integer :: ywcount\n\n\n\n        if(my_id .eq. IO_id) then\n           allocate(g_CH_NETLNK(g_IXRT,g_JXRT))\n           g_CH_NETLNK = -9999\n           CALL READ_ROUTEDIM(g_IXRT, g_JXRT, route_chan_f, route_link_f, &\n              route_direction_f, GNLINKS, &\n              g_CH_NETLNK, channel_option,geo_finegrid_flnm,NLINKSL, UDMP_OPT,nlakes)\n           call get_NLINKSL(NLINKSL, channel_option, route_link_f)\n        else\n           allocate(g_CH_NETLNK(1,1))\n        endif\n\n        call mpp_land_bcast_int1(GNLINKS)\n        call mpp_land_bcast_int1(NLINKSL)\n        call mpp_land_bcast_int1(NLAKES)\n\n\n        call decompose_RT_int(g_CH_NETLNK,GCH_NETLNK,g_IXRT,g_JXRT,ixrt,jxrt)\n        if(allocated(g_CH_NETLNK)) deallocate(g_CH_NETLNK)\n        ywcount = 0\n        CH_NETLNK = -9999\n        do j = 1, jxrt\n           do i = 1, ixrt\n                  if(GCH_NETLNK(i,j) .gt. 0) then\n                       ywcount = ywcount + 1\n                       CH_NETLNK(i,j) = ywcount\n                  endif\n           end do\n        end do\n        NLINKS = ywcount\n\n\n!ywcheck\n!        CH_NETLNK = GCH_NETLNK\n\n\n        allocate(rt_domain(did)%map_l2g(NLINKS))\n\n        rt_domain(did)%map_l2g = -1\n        do j = 1, jxrt\n           do i = 1, ixrt\n              if(CH_NETLNK(i,j) .gt. 0) then\n                  rt_domain(did)%map_l2g(CH_NETLNK(i,j)) = GCH_NETLNK(i,j)\n              endif\n           end do\n        end do\n\n        call mpp_chrt_nlinks_collect(NLINKS)\n\n      end SUBROUTINE MPP_READ_ROUTEDIM\n\n\n\n\n#endif\n\n      SUBROUTINE READ_ROUTING_seq(IXRT,JXRT,ELRT,CH_NETRT,CH_LNKRT,LKSATFAC,route_topo_f,    &\n            route_chan_f, geo_finegrid_flnm,OVROUGHRTFAC,RETDEPRTFAC,IMPERVFRAC, &\n            channel_option, UDMP_OPT, imperv_adj)\n\n\n        INTEGER, INTENT(IN) :: IXRT,JXRT\n        REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: ELRT,LKSATFAC\n        INTEGER, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: CH_NETRT\n        INTEGER(kind=int64), INTENT(INOUT), DIMENSION(IXRT,JXRT) :: CH_LNKRT\n!Dummy inverted grids\n        REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: OVROUGHRTFAC\n        REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: RETDEPRTFAC\n        REAL, INTENT(INOUT), DIMENSION(IXRT,JXRT) :: IMPERVFRAC\n\n        integer         :: I,J, iret, jj, channel_option, UDMP_OPT, imperv_adj\n        CHARACTER(len=256)        :: var_name\n        CHARACTER(len=*  )       :: route_topo_f\n        CHARACTER(len=*  )       :: route_chan_f\n        CHARACTER(len=*  )       :: geo_finegrid_flnm\n\n        var_name = \"TOPOGRAPHY\"\n\n        call nreadRT2d_real(var_name,ELRT,ixrt,jxrt,&\n                     trim(geo_finegrid_flnm))\n\n     IF(channel_option .ne. 3 .and. UDMP_OPT .ne. 1) then  !get maxnodes and links from grid\n        var_name = \"LINKID\"\n        call nreadRT2d_int8(var_name,CH_LNKRT,ixrt,jxrt,&\n               trim(geo_finegrid_flnm), fatalErr=.true.)\n     endif\n\n\n\n#ifdef HYDRO_D\n        write(6,*) \"read linkid grid CH_LNKRT \",var_name\n#endif\n\n!!!DY to be fixed ... 6/27/08\n!        var_name = \"BED_ELEVATION\"\n!        iret = get2d_real(var_name,ELRT,ixrt,jxrt,&\n!                     trim(geo_finegrid_flnm))\n\n        var_name = \"CHANNELGRID\"\n        call nreadRT2d_int(var_name,CH_NETRT,ixrt,jxrt,&\n               trim(geo_finegrid_flnm))\n\n#ifdef HYDRO_D\n        write(6,*) \"read \",var_name\n#endif\n\n        var_name = \"LKSATFAC\"\n        LKSATFAC = -9999.9\n        call nreadRT2d_real(var_name,LKSATFAC,ixrt,jxrt,&\n               trim(geo_finegrid_flnm))\n\n#ifdef HYDRO_D\n        write(6,*) \"read \",var_name\n#endif\n\n           where (LKSATFAC == -9999.9) LKSATFAC = 1000.0  !specify LKSAFAC if no term avail...\n\n\n!1.12.2012...Read in routing calibration factors...\n        var_name = \"RETDEPRTFAC\"\n        call nreadRT2d_real(var_name,RETDEPRTFAC,ixrt,jxrt,&\n                     trim(geo_finegrid_flnm))\n        where (RETDEPRTFAC < 0.) RETDEPRTFAC = 1.0  ! reset grid to = 1.0 if non-valid value exists\n\n        var_name = \"OVROUGHRTFAC\"\n        call nreadRT2d_real(var_name,OVROUGHRTFAC,ixrt,jxrt,&\n                     trim(geo_finegrid_flnm))\n        where (OVROUGHRTFAC <= 0.) OVROUGHRTFAC = 1.0 ! reset grid to = 1.0 if non-valid value exists\n\n!Read in new optional impervious layer\n        var_name = \"IMPERVFRAC\"\n        IMPERVFRAC = -9999.9\n        if (imperv_adj > 0) then\n          call nreadRT2d_real(var_name,IMPERVFRAC,ixrt,jxrt,&\n                     trim(geo_finegrid_flnm), fatalErr=.true.)\n          where (IMPERVFRAC < 0.) IMPERVFRAC = 0.0  ! reset grid to = 0.0 if non-valid value exists\n        else\n          IMPERVFRAC = 0.0\n        endif\n\n#ifdef HYDRO_D\n        write(6,*) \"finish READ_ROUTING_seq\"\n#endif\n\n\n!DJG -----------------------------------------------------\n   END SUBROUTINE READ_ROUTING_seq\n\n!DJG _____________________________\n   subroutine output_lsm(outFile,did)\n\n\n   implicit none\n\n   integer did\n\n   character(len=*) outFile\n\n    integer :: ncid,irt, dimid_ix, dimid_jx,  &\n             dimid_ixrt, dimid_jxrt, varid, &\n             dimid_links, dimid_basns, dimid_soil\n    integer :: iret, n\n    character(len=2) tmpStr\n\n\n\n#ifdef MPP_LAND\n     if(IO_id.eq.my_id) &\n#endif\n\n       iret = nf90_create(trim(outFile), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n\n#ifdef MPP_LAND\n       call mpp_land_bcast_int1(iret)\n#endif\n\n       if (iret /= 0) then\n          call hydro_stop(\"In output_lsm() - Problem nf90_create\")\n       endif\n\n\n#ifdef MPP_LAND\n     if(IO_id.eq.my_id) then\n#endif\n#ifdef HYDRO_D\n         write(6,*) \"output file \", outFile\n#endif\n! define dimension for variables\n          iret = nf90_def_dim(ncid, \"depth\", nlst(did)%nsoil, dimid_soil)  !-- 3-d soils\n#ifdef MPP_LAND\n          iret = nf90_def_dim(ncid, \"ix\", global_nx, dimid_ix)  !-- make a decimated grid\n          iret = nf90_def_dim(ncid, \"iy\", global_ny, dimid_jx)\n#else\n          iret = nf90_def_dim(ncid, \"ix\", rt_domain(did)%ix, dimid_ix)  !-- make a decimated grid\n          iret = nf90_def_dim(ncid, \"iy\", rt_domain(did)%jx, dimid_jx)\n#endif\n\n!define variables\n          do n = 1, nlst(did)%nsoil\n             if( n .lt. 10) then\n                write(tmpStr, '(i1)') n\n             else\n                write(tmpStr, '(i2)') n\n             endif\n             iret = nf90_def_var(ncid, \"stc\"//trim(tmpStr), NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n             iret = nf90_def_var(ncid, \"smc\"//trim(tmpStr), NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n             iret = nf90_def_var(ncid, \"sh2ox\"//trim(tmpStr), NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          end do\n\n          !iret = nf90_def_var(ncid, \"smcmax1\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          !iret = nf90_def_var(ncid, \"smcref1\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          !iret = nf90_def_var(ncid, \"smcwlt1\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          iret = nf90_def_var(ncid, \"infxsrt\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          iret = nf90_def_var(ncid, \"sfcheadrt\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n\n          iret = nf90_enddef(ncid)\n\n#ifdef MPP_LAND\n    endif\n#endif\n        call w_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%stc,\"stc\")\n        call w_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%smc,\"smc\")\n        call w_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%sh2ox,\"sh2ox\")\n        !call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCMAX1,\"smcmax1\")\n        !call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCREF1,\"smcref1\" )\n        !call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCWLT1,\"smcwlt1\"  )\n        call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%INFXSRT,\"infxsrt\"  )\n        call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%overland%control%surface_water_head_lsm,\"sfcheadrt\" )\n\n\n#ifdef MPP_LAND\n     if(IO_id.eq.my_id) then\n#endif\n\n        iret = nf90_close(ncid)\n#ifdef HYDRO_D\n        write(6,*) \"finish writing outFile : \", outFile\n#endif\n\n#ifdef MPP_LAND\n    endif\n#endif\n\n        end subroutine output_lsm\n\n\n   subroutine RESTART_OUT_nc(outFile,did)\n\n\n   implicit none\n\n   integer did\n   integer :: n\n   character(len=2) :: tmpStr\n   character(len=*) outFile\n\n    integer :: ncid,irt, dimid_ix, dimid_jx,  &\n             dimid_ixrt, dimid_jxrt, varid, &\n             dimid_links, dimid_basns, dimid_soil, dimid_lakes\n    integer :: iret\n\n\n#ifdef MPP_LAND\n     if(IO_id.eq.my_id) &\n#endif\n\n       iret = nf90_create(trim(outFile), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n\n#ifdef MPP_LAND\n       call mpp_land_bcast_int1(iret)\n#endif\n\n       if (iret /= 0) then\n          call hydro_stop(\"In RESTART_OUT_nc() - Problem nf90_create\")\n       endif\n\n#ifdef MPP_LAND\n     if(IO_id.eq.my_id) then\n#endif\n\n   if( nlst(did)%channel_only       .eq. 0 .and. &\n       nlst(did)%channelBucket_only .eq. 0         ) then\n\n! define dimension for variables\n          iret = nf90_def_dim(ncid, \"depth\", nlst(did)%nsoil, dimid_soil)  !-- 3-d soils\n#ifdef MPP_LAND\n          iret = nf90_def_dim(ncid, \"ix\", global_nx, dimid_ix)  !-- make a decimated grid\n          iret = nf90_def_dim(ncid, \"iy\", global_ny, dimid_jx)\n          iret = nf90_def_dim(ncid, \"ixrt\", global_rt_nx , dimid_ixrt)  !-- make a decimated grid\n          iret = nf90_def_dim(ncid, \"iyrt\", global_rt_ny, dimid_jxrt)\n#else\n          iret = nf90_def_dim(ncid, \"ix\", rt_domain(did)%ix, dimid_ix)  !-- make a decimated grid\n          iret = nf90_def_dim(ncid, \"iy\", rt_domain(did)%jx, dimid_jx)\n          iret = nf90_def_dim(ncid, \"ixrt\", rt_domain(did)%ixrt , dimid_ixrt)  !-- make a decimated grid\n          iret = nf90_def_dim(ncid, \"iyrt\", rt_domain(did)%jxrt, dimid_jxrt)\n#endif\n\n       endif ! neither channel_only nor channelBucket_only\n\n       if(nlst(did)%channel_option .eq. 3) then\n          iret = nf90_def_dim(ncid, \"links\", rt_domain(did)%gnlinks, dimid_links)\n       else\n          iret = nf90_def_dim(ncid, \"links\", rt_domain(did)%gnlinksl, dimid_links)\n       endif\n       iret = nf90_def_dim(ncid, \"basns\", rt_domain(did)%gnumbasns, dimid_basns)\n       if(rt_domain(did)%nlakes .gt. 0) then\n          iret = nf90_def_dim(ncid, \"lakes\", rt_domain(did)%nlakes, dimid_lakes)\n       endif\n\n       !define variables\n       if( nlst(did)%channel_only       .eq. 0 .and. &\n            nlst(did)%channelBucket_only .eq. 0         ) then\n\n          do n = 1, nlst(did)%nsoil\n             if( n .lt. 10) then\n                write(tmpStr, '(i1)') n\n             else\n                write(tmpStr, '(i2)') n\n             endif\n             iret = nf90_def_var(ncid, \"stc\"//trim(tmpStr), NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n             iret = nf90_def_var(ncid, \"smc\"//trim(tmpStr), NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n             iret = nf90_def_var(ncid, \"sh2ox\"//trim(tmpStr), NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          end do\n\n          !iret = nf90_def_var(ncid, \"smcmax1\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          !iret = nf90_def_var(ncid, \"smcref1\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          !iret = nf90_def_var(ncid, \"smcwlt1\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          iret = nf90_def_var(ncid, \"infxsrt\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          iret = nf90_def_var(ncid, \"soldrain\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n          iret = nf90_def_var(ncid, \"sfcheadrt\", NF90_FLOAT, (/dimid_ix,dimid_jx/), varid)\n\n       end if  ! neither channel_only nor channelBucket_only\n\n   if(nlst(did)%SUBRTSWCRT  .eq. 1 .or. &\n      nlst(did)%OVRTSWCRT   .eq. 1 .or. &\n      nlst(did)%GWBASESWCRT .ne. 0       ) then\n\n      if( nlst(did)%channel_only       .eq. 0 .and. &\n           nlst(did)%channelBucket_only .eq. 0         ) then\n\n            iret = nf90_def_var(ncid, \"QBDRYRT\", NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n            iret = nf90_def_var(ncid, \"infxswgt\", NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n            iret = nf90_def_var(ncid, \"sfcheadsubrt\", NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n          do n = 1, nlst(did)%nsoil\n             if( n .lt. 10) then\n                write(tmpStr, '(i1)') n\n             else\n                write(tmpStr, '(i2)') n\n             endif\n             iret = nf90_def_var(ncid, \"sh2owgt\"//trim(tmpStr), NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n          end do\n            iret = nf90_def_var(ncid, \"qstrmvolrt\", NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n            !AD_CHANGE: Not needed in RESTART\n            !iret = nf90_def_var(ncid, \"RETDEPRT\", NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n\n      end if  ! neither channel_only nor channelBucket_only\n\n      if(nlst(did)%CHANRTSWCRT.eq.1) then\n\n!yw based on Laura request, hlink will do the restart for reach method.\n!         if(nlst(did)%channel_option .eq. 3) &\n         iret = nf90_def_var(ncid, \"hlink\", NF90_FLOAT, (/dimid_links/), varid)\n         iret = nf90_def_var(ncid, \"qlink1\", NF90_FLOAT, (/dimid_links/), varid)\n         iret = nf90_def_var(ncid, \"qlink2\", NF90_FLOAT, (/dimid_links/), varid)\n         if(nlst(did)%channel_option .eq. 3) &\n              iret = nf90_def_var(ncid, \"cvol\", NF90_FLOAT, (/dimid_links/), varid)\n         if(rt_domain(did)%nlakes .gt. 0) then\n            iret = nf90_def_var(ncid, \"resht\", NF90_FLOAT, (/dimid_lakes/), varid)\n            iret = nf90_def_var(ncid, \"qlakeo\", NF90_FLOAT, (/dimid_lakes/), varid)\n            iret = nf90_def_var(ncid, \"qlakei\", NF90_FLOAT, (/dimid_lakes/), varid)\n         endif\n\n         if( nlst(did)%channel_only       .eq. 0 .and. &\n             nlst(did)%channelBucket_only .eq. 0         ) &\n             iret = nf90_def_var(ncid, \"lake_inflort\", NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n\n         !! JLM: who wants these? They can be put back if someone cares.\n         !! But just calculate accQLateral locally so the redundant variable isnt held in\n         !! memory with all the other variables\n         !if(nlst_rt(did)%UDMP_OPT .eq. 1) then\n         !       iret = nf90_def_var(ncid, \"accSfcLatRunoff\", NF90_DOUBLE, (/dimid_links/), varid)\n         !       iret = nf90_def_var(ncid, \"accQLateral\", NF90_DOUBLE, (/dimid_links/), varid)\n         !       iret = nf90_def_var(ncid, \"qSfcLatRunoff\", NF90_DOUBLE, (/dimid_links/), varid)\n         !       iret = nf90_def_var(ncid, \"accBucket\", NF90_DOUBLE, (/dimid_links/), varid)\n         !endif\n\n      end if ! CHANRTSWCRT .eq. 1\n\n      if(nlst(did)%GWBASESWCRT.eq.1 .or. nlst(did)%GWBASESWCRT.ge.4) then\n\n         if( nlst(did)%channel_only .eq. 0) then\n\n            if(nlst(did)%UDMP_OPT .eq. 1) then\n               iret = nf90_def_var(ncid, \"z_gwsubbas\", NF90_FLOAT, (/dimid_links/), varid)\n            else\n               iret = nf90_def_var(ncid, \"z_gwsubbas\", NF90_FLOAT, (/dimid_basns/), varid)\n            endif\n\n         end if ! not channel_only : dont use buckets in channel only runs\n\n!yw test bucket model\n!             iret = nf90_def_var(ncid, \"gwbas_pix_ct\", NF90_FLOAT, (/dimid_basns/), varid)\n!             iret = nf90_def_var(ncid, \"gw_buck_exp\", NF90_FLOAT, (/dimid_basns/), varid)\n!             iret = nf90_def_var(ncid, \"z_max\", NF90_FLOAT, (/dimid_basns/), varid)\n!             iret = nf90_def_var(ncid, \"gw_buck_coeff\", NF90_FLOAT, (/dimid_basns/), varid)\n!             iret = nf90_def_var(ncid, \"qin_gwsubbas\", NF90_FLOAT, (/dimid_basns/), varid)\n!             iret = nf90_def_var(ncid, \"qinflowbase\", NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n!             iret = nf90_def_var(ncid, \"qout_gwsubbas\", NF90_FLOAT, (/dimid_basns/), varid)\n      end if ! GWBASESWCRT .eq.1 .or. GWBASESWCRT .ge. 4\n\n      !! What is this option??\n      if(nlst(did)%gwBaseSwCRT .eq. 3)then\n         iret = nf90_def_var(ncid, \"HEAD\", NF90_FLOAT, (/dimid_ixrt,dimid_jxrt/), varid)\n      end if\n\n   end if  !  end if(nlst(did)%SUBRTSWCRT  .eq. 1 .or. &\n!                    nlst(did)%OVRTSWCRT   .eq. 1 .or. &\n!                    nlst(did)%GWBASESWCRT .ne. 0       )\n\n   !         put global attribute\n   iret = nf90_put_att(ncid, NF90_GLOBAL, \"compiler_version\", compiler_version())\n   iret = nf90_put_att(ncid, NF90_GLOBAL, \"his_out_counts\", rt_domain(did)%his_out_counts)\n   iret = nf90_put_att(ncid, NF90_GLOBAL, \"Restart_Time\", nlst(did)%olddate(1:19))\n   iret = nf90_put_att(ncid, NF90_GLOBAL, \"Since_Date\", nlst(did)%sincedate(1:19))\n   iret = nf90_put_att(ncid, NF90_GLOBAL, \"DTCT\", nlst(did)%DTCT)\n   iret = nf90_put_att(ncid, NF90_GLOBAL, \"channel_only\", nlst(did)%channel_only)\n   iret = nf90_put_att(ncid, NF90_GLOBAL, \"channelBucket_only\", nlst(did)%channelBucket_only)\n\n   !! end definition\n   iret = nf90_enddef(ncid)\n\n\n#ifdef MPP_LAND\nendif  ! my_id .eq. io_id\n#endif\n\nif( nlst(did)%channel_only       .eq. 0 .and. &\n     nlst(did)%channelBucket_only .eq. 0         ) then\n\n   call w_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%stc,\"stc\")\n   call w_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%smc,\"smc\")\n   call w_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%sh2ox,\"sh2ox\")\n\n   !call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCMAX1,\"smcmax1\")\n   !call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCREF1,\"smcref1\" )\n   !call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCWLT1,\"smcwlt1\"  )\n   call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%INFXSRT,\"infxsrt\"  )\n   call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%soldrain,\"soldrain\"  )\n   call w_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%overland%control%surface_water_head_lsm,\"sfcheadrt\"  )\n\nend if ! neither channel_only nor channelBucket_only\n\nif(nlst(did)%SUBRTSWCRT  .eq. 1 .or. &\n   nlst(did)%OVRTSWCRT   .eq. 1 .or. &\n   nlst(did)%GWBASESWCRT .ne. 0       ) then\n\n   if( nlst(did)%channel_only       .eq. 0 .and. &\n       nlst(did)%channelBucket_only .eq. 0         ) then\n      call w_rst_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%overland%control%boundary_flux, \"QBDRYRT\" )\n      call w_rst_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%INFXSWGT, \"infxswgt\" )\n      call w_rst_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%overland%control%surface_water_head_routing, \"sfcheadsubrt\" )\n      call w_rst_rt_nc3(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,nlst(did)%nsoil,rt_domain(did)%SH2OWGT, \"sh2owgt\" )\n      call w_rst_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%QSTRMVOLRT_ACC, \"qstrmvolrt\" )\n      !AD_CHANGE: Not needed in RESTART\n      !call w_rst_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%overland%properties%retention_depth, \"RETDEPRT\" )\n   end if ! neither channel_only nor channelBucket_only\n\n   if(nlst(did)%CHANRTSWCRT.eq.1) then\n\n\n      if(nlst(did)%channel_option .eq. 3) then\n         call w_rst_crt_nc1(ncid,rt_domain(did)%nlinks,rt_domain(did)%HLINK,\"hlink\" &\n#ifdef MPP_LAND\n              ,rt_domain(did)%map_l2g, rt_domain(did)%gnlinks  &\n#endif\n              )\n      else\n         call w_rst_crt_reach(ncid,rt_domain(did)%HLINK, \"hlink\"  &\n#ifdef MPP_LAND\n              ,rt_domain(did)%gnlinksl&\n#endif\n              )\n        !call checkReach(99,rt_domain(did)%HLINK)\n      endif\n\n      if(nlst(did)%channel_option .eq. 3) then\n         call w_rst_crt_nc1(ncid,rt_domain(did)%nlinks,rt_domain(did)%QLINK(:,1),\"qlink1\" &\n#ifdef MPP_LAND\n              ,rt_domain(did)%map_l2g, rt_domain(did)%gnlinks  &\n#endif\n              )\n      else\n         call w_rst_crt_reach(ncid,rt_domain(did)%QLINK(:,1), \"qlink1\"  &\n#ifdef MPP_LAND\n              ,rt_domain(did)%gnlinksl &\n#endif\n              )\n      endif\n\n      if(nlst(did)%channel_option .eq. 3) then\n         call w_rst_crt_nc1(ncid,rt_domain(did)%nlinks,rt_domain(did)%QLINK(:,2),\"qlink2\" &\n#ifdef MPP_LAND\n              ,rt_domain(did)%map_l2g, rt_domain(did)%gnlinks  &\n#endif\n              )\n      else\n         call w_rst_crt_reach(ncid,rt_domain(did)%QLINK(:,2), \"qlink2\"  &\n#ifdef MPP_LAND\n              ,rt_domain(did)%gnlinksl &\n#endif\n              )\n\n!! JLM If someone really wants the accumulated fluxes in the restart file, you can add them back.\n!! But Calculate accQLateral locally\n!                    if(nlst_rt(did)%UDMP_OPT .eq. 1) then\n!                        call w_rst_crt_reach(ncid,rt_domain(did)%accSfcLatRunoff, \"accSfcLatRunoff\"  &\n!#ifdef MPP_LAND\n!                                ,rt_domain(did)%gnlinksl &\n!#endif\n!                              )\n!                        call w_rst_crt_reach(ncid,rt_domain(did)%accQLateral, \"accQLateral\"  &\n!#ifdef MPP_LAND\n!                                ,rt_domain(did)%gnlinksl &\n!#endif\n!                              )\n!                        call w_rst_crt_reach(ncid,rt_domain(did)%qSfcLatRunoff, \"qSfcLatRunoff\"  &\n!#ifdef MPP_LAND\n!                                ,rt_domain(did)%gnlinksl &\n!#endif\n!                              )\n!                        call w_rst_crt_reach(ncid,rt_domain(did)%accBucket, \"accBucket\"  &\n!#ifdef MPP_LAND\n!                                ,rt_domain(did)%gnlinksl &\n!#endif\n!                              )\n!                    endif   ! end if of UDMP_OPT .eq. 1\n      endif  ! channel_option .eq. 3\n\n\n      !! Cvol is not prognostic for Musk-cunge.\n      if(nlst(did)%channel_option .eq. 3) then\n         call w_rst_crt_nc1(ncid,rt_domain(did)%nlinks,rt_domain(did)%cvol,\"cvol\" &\n#ifdef MPP_LAND\n              ,rt_domain(did)%map_l2g, rt_domain(did)%gnlinks  &\n#endif\n              )\n!      else\n!         call w_rst_crt_reach(ncid,rt_domain(did)%cvol, \"cvol\"  &\n!#ifdef MPP_LAND\n!              ,rt_domain(did)%gnlinksl &\n!#endif\n!              )\n      endif\n\n\n!              call w_rst_crt_nc1(ncid,rt_domain(did)%nlinks,rt_domain(did)%resht,\"resht\" &\n!#ifdef MPP_LAND\n!                 ,rt_domain(did)%map_l2g, rt_domain(did)%gnlinks  &\n!#endif\n!                  )\n\n\n      call w_rst_crt_nc1_lake(ncid,rt_domain(did)%nlakes,rt_domain(did)%resht,\"resht\" &\n#ifdef MPP_LAND\n           ,rt_domain(did)%lake_index  &\n#endif\n           )\n\n      call w_rst_crt_nc1_lake(ncid,rt_domain(did)%nlakes,rt_domain(did)%qlakeo,\"qlakeo\" &\n#ifdef MPP_LAND\n           ,rt_domain(did)%lake_index  &\n#endif\n           )\n\n      call w_rst_crt_nc1_lake(ncid,rt_domain(did)%nlakes,rt_domain(did)%qlakei,\"qlakei\" &\n#ifdef MPP_LAND\n           ,rt_domain(did)%lake_index  &\n#endif\n           )\n\n      if( nlst(did)%channel_only       .eq. 0 .and. &\n          nlst(did)%channelBucket_only .eq. 0         ) &\n\n          call w_rst_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake,\"lake_inflort\")\n\n   end if  !    if(nlst_rt(did)%CHANRTSWCRT.eq.1)\n\n   if(nlst(did)%GWBASESWCRT.eq.1 .or. nlst(did)%GWBASESWCRT.ge.4) then\n\n      !call w_rst_crt_nc1g(ncid,rt_domain(did)%numbasns,rt_domain(did)%z_gwsubbas,\"z_gwsubbas\" )\n      if( nlst(did)%channel_only .eq. 0) then\n\n         if(nlst(did)%UDMP_OPT .eq. 1) then\n\n            call w_rst_crt_reach(ncid,rt_domain(did)%z_gwsubbas, \"z_gwsubbas\"  &\n#ifdef MPP_LAND\n                 ,rt_domain(did)%gnlinksl  &\n#endif\n                 )\n         else\n            call w_rst_gwbucket_real(ncid,rt_domain(did)%numbasns,rt_domain(did)%gnumbasns, &\n                 rt_domain(did)%basnsInd, rt_domain(did)%z_gwsubbas,\"z_gwsubbas\" )\n         endif\n\n      end if ! not channel_only : dont use buckets in channel only runs\n\n!yw test bucket model\n!             call w_rst_crt_nc1g(ncid,rt_domain(did)%numbasns,rt_domain(did)%gwbas_pix_ct,\"gwbas_pix_ct\" )\n!             call w_rst_crt_nc1g(ncid,rt_domain(did)%numbasns,rt_domain(did)%gw_buck_exp,\"gw_buck_exp\" )\n!             call w_rst_crt_nc1g(ncid,rt_domain(did)%numbasns,rt_domain(did)%z_max,\"z_max\" )\n!             call w_rst_crt_nc1g(ncid,rt_domain(did)%numbasns,rt_domain(did)%gw_buck_coeff,\"gw_buck_coeff\" )\n!             call w_rst_crt_nc1g(ncid,rt_domain(did)%numbasns,rt_domain(did)%qin_gwsubbas,\"qin_gwsubbas\" )\n!             call w_rst_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%qinflowbase,\"qinflowbase\")\n!             call w_rst_crt_nc1g(ncid,rt_domain(did)%numbasns,rt_domain(did)%qout_gwsubbas,\"qout_gwsubbas\" )\n   end if ! GWBASESWCRT .eq. 1 .or. GWBASESWCRT .ge. 4\n\n   if(nlst(did)%GWBASESWCRT.eq.3) then\n      if( nlst(did)%channel_only       .eq. 0 .and. &\n          nlst(did)%channelBucket_only .eq. 0         ) &\n          call w_rst_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,gw2d(did)%ho, \"HEAD\" )\n   end if\n\nend if  ! end if(nlst_rt(did)%SUBRTSWCRT  .eq. 1 .or. &\n!                nlst_rt(did)%OVRTSWCRT   .eq. 1 .or. &\n!                nlst_rt(did)%GWBASESWCRT .ne. 0       )\n\n\n#ifdef MPP_LAND\n        if(IO_id.eq.my_id) &\n#endif\n        iret = nf90_close(ncid)\n\n        end subroutine RESTART_OUT_nc\n\n#ifdef MPP_LAND\n\n   subroutine RESTART_OUT_bi(outFile,did)\n\n\n   implicit none\n\n   integer did\n\n   character(len=*) outFile\n\n    integer :: iunit\n    integer  :: i0,ie, i, istep, mkdirStatus\n\n\n    call mpp_land_sync()\n\n    iunit = 81\n istep = 64\n i0 = 0\n ie = istep\n do i = 0, numprocs,istep\n   if(my_id .ge. i0 .and. my_id .lt. ie) then\n     open(iunit, file = \"restart/\"//trim(outFile), form=\"unformatted\",ERR=101, access=\"sequential\")\n          write(iunit,ERR=101) rt_domain(did)%his_out_counts\n!         write(iunit,ERR=101) nlst(did)%olddate(1:19)\n          write(iunit,ERR=101) nlst(did)%sincedate(1:19)\n!         write(iunit,ERR=101) nlst_rt(did)%DTCT\n          write(iunit,ERR=101) rt_domain(did)%stc\n          write(iunit,ERR=101) rt_domain(did)%smc\n          write(iunit,ERR=101) rt_domain(did)%sh2ox\n          write(iunit,ERR=101) rt_domain(did)%SMCMAX1\n          write(iunit,ERR=101) rt_domain(did)%SMCREF1\n          write(iunit,ERR=101) rt_domain(did)%SMCWLT1\n          write(iunit,ERR=101) rt_domain(did)%INFXSRT\n          write(iunit,ERR=101) rt_domain(did)%soldrain\n          write(iunit,ERR=101) rt_domain(did)%overland%control%surface_water_head_lsm\n\n          if(nlst(did)%SUBRTSWCRT.EQ.1.OR.nlst(did)%OVRTSWCRT.EQ.1 .or. nlst(did)%GWBASESWCRT .ne. 0) then\n                if(nlst(did)%CHANRTSWCRT.EQ.1) then\n                   write(iunit,ERR=101) rt_domain(did)%HLINK\n                   write(iunit,ERR=101) rt_domain(did)%QLINK(:,1)\n                   write(iunit,ERR=101) rt_domain(did)%QLINK(:,2)\n                   write(iunit,ERR=101) rt_domain(did)%cvol\n                   write(iunit,ERR=101) rt_domain(did)%resht\n                   write(iunit,ERR=101) rt_domain(did)%qlakeo\n                   write(iunit,ERR=101) rt_domain(did)%qlakei\n                   write(iunit,ERR=101) rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake\n                end if\n\n                if(nlst(did)%GWBASESWCRT.EQ.1.OR.nlst(did)%GWBASESWCRT.GE.4) then\n                     write(iunit,ERR=101) rt_domain(did)%z_gwsubbas\n                end if\n                if(nlst(did)%SUBRTSWCRT.EQ.1.OR.nlst(did)%OVRTSWCRT.EQ.1) then\n                    write(iunit,ERR=101) rt_domain(did)%overland%control%boundary_flux\n                    write(iunit,ERR=101) rt_domain(did)%INFXSWGT\n                    write(iunit,ERR=101) rt_domain(did)%overland%control%surface_water_head_routing\n                    write(iunit,ERR=101) rt_domain(did)%SH2OWGT\n                    write(iunit,ERR=101) rt_domain(did)%QSTRMVOLRT_ACC\n                    !AD_CHANGE: Not needed in RESTART\n                    !write(iunit,ERR=101) rt_domain(did)%RETDEPRT\n                endif\n          end if\n\n        close(iunit)\n    endif\n    call mpp_land_sync()\n    i0 = i0 + istep\n    ie = ie + istep\n  end do ! end do of i loop\n\n        return\n101     continue\n        call hydro_stop(\"FATAL ERROR: failed to output the hydro restart file.\")\n        end subroutine RESTART_OUT_bi\n\n   subroutine RESTART_in_bi(inFileTmp,did)\n\n\n   implicit none\n\n   integer did\n\n   character(len=*) inFileTmp\n   character(len=256) inFile\n   character(len=19) str_tmp\n\n    integer :: iunit\n    logical :: fexist\n    integer  :: i0,ie, i, istep\n\n    iunit = 81\n\n             if(my_id .lt. 10) then\n                write(str_tmp,'(I1)') my_id\n             else if(my_id .lt. 100) then\n                write(str_tmp,'(I2)') my_id\n             else if(my_id .lt. 1000) then\n                write(str_tmp,'(I3)') my_id\n             else if(my_id .lt. 10000) then\n                write(str_tmp,'(I4)') my_id\n             else if(my_id .lt. 100000) then\n                write(str_tmp,'(I5)') my_id\n             endif\n\n    inFile = trim(inFileTmp)//\".\"//str_tmp\n\n    inquire (file=trim(inFile), exist=fexist)\n    if(.not. fexist) then\n        call hydro_stop(\"In RESTART_in_bi()- Could not find restart file \"//trim(inFile))\n    endif\n\n istep = 64\n i0 = 0\n ie = istep\n do i = 0, numprocs,istep\n   if(my_id .ge. i0 .and. my_id .lt. ie) then\n    open(iunit, file = inFile, form=\"unformatted\",ERR=101,access=\"sequential\")\n          read(iunit,ERR=101) rt_domain(did)%his_out_counts\n!         read(iunit,ERR=101) nlst_rt(did)%olddate(1:19)\n          read(iunit,ERR=101) nlst(did)%sincedate(1:19)\n!         read(iunit,ERR=101) nlst_rt(did)%DTCT\n          read(iunit,ERR=101) rt_domain(did)%stc\n          read(iunit,ERR=101) rt_domain(did)%smc\n          read(iunit,ERR=101) rt_domain(did)%sh2ox\n          read(iunit,ERR=101) rt_domain(did)%SMCMAX1\n          read(iunit,ERR=101) rt_domain(did)%SMCREF1\n          read(iunit,ERR=101) rt_domain(did)%SMCWLT1\n          read(iunit,ERR=101) rt_domain(did)%INFXSRT\n          read(iunit,ERR=101) rt_domain(did)%soldrain\n          read(iunit,ERR=101) rt_domain(did)%overland%control%surface_water_head_lsm\n          if(nlst(did)%SUBRTSWCRT.EQ.0.and.nlst(did)%OVRTSWCRT.EQ.0) rt_domain(did)%overland%control%surface_water_head_lsm = 0\n\n          if(nlst(did)%SUBRTSWCRT.EQ.1.OR.nlst(did)%OVRTSWCRT.EQ.1 .or. nlst(did)%GWBASESWCRT .ne. 0) then\n                if(nlst(did)%CHANRTSWCRT.EQ.1) then\n                   read(iunit,ERR=101) rt_domain(did)%HLINK\n                   read(iunit,ERR=101) rt_domain(did)%QLINK(:,1)\n                   read(iunit,ERR=101) rt_domain(did)%QLINK(:,2)\n                   read(iunit,ERR=101) rt_domain(did)%cvol\n                   read(iunit,ERR=101) rt_domain(did)%resht\n                   read(iunit,ERR=101) rt_domain(did)%qlakeo\n                   read(iunit,ERR=101) rt_domain(did)%qlakei\n                   read(iunit,ERR=101) rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake\n                end if\n\n                if(nlst(did)%GWBASESWCRT.EQ.1 .OR. nlst(did)%GWBASESWCRT.GE.4) then\n                     read(iunit,ERR=101) rt_domain(did)%z_gwsubbas\n                end if\n                if(nlst(did)%SUBRTSWCRT.EQ.1.OR.nlst(did)%OVRTSWCRT.EQ.1) then\n                   read(iunit,ERR=101) rt_domain(did)%overland%control%boundary_flux\n                   read(iunit,ERR=101) rt_domain(did)%INFXSWGT\n                   read(iunit,ERR=101) rt_domain(did)%overland%control%surface_water_head_routing\n                   read(iunit,ERR=101) rt_domain(did)%SH2OWGT\n                   read(iunit,ERR=101) rt_domain(did)%QSTRMVOLRT_ACC\n                   !AD_CHANGE: This is overwriting the RETDEPRTFAC version, so causes issues when changing that factor.\n                   !No need to have in restart since live calculated.\n                   !read(iunit,ERR=101) rt_domain(did)%RETDEPRT\n                endif\n          end if\n\n        close(iunit)\n    endif\n    call mpp_land_sync()\n    i0 = i0 + istep\n    ie = ie + istep\n  end do ! end do of i loop\n\n        return\n101     continue\n        call hydro_stop(\"In RESTART_in_bi() - failed to read the hydro restart file \"//trim(inFile))\n        end subroutine RESTART_in_bi\n#endif\n\n        subroutine w_rst_rt_nc2(ncid,ix,jx,inVar,varName)\n           implicit none\n           integer:: ncid,ix,jx,varid , iret\n           character(len=*) varName\n           real, dimension(ix,jx):: inVar\n#ifdef MPP_LAND\n           real, allocatable, dimension(:,:) :: varTmp\n           if(my_id .eq. io_id ) then\n               allocate(varTmp(global_rt_nx, global_rt_ny))\n           else\n               allocate(varTmp(1,1))\n           endif\n           call write_IO_rt_real(inVar,varTmp)\n           if(my_id .eq. IO_id) then\n              iret = nf90_inq_varid(ncid,varName, varid)\n              if(iret .eq. 0) then\n                 iret = nf90_put_var(ncid, varid, varTmp, (/1,1/), (/global_rt_nx,global_rt_ny/))\n              else\n                 write(6,*) \"Error: variable not defined in rst file before write: \", varName\n              endif\n           endif\n           if(allocated(varTmp))  deallocate(varTmp)\n#else\n           iret = nf90_inq_varid(ncid,varName, varid)\n           if(iret .eq. 0) then\n              iret = nf90_put_var(ncid, varid, inVar, (/1,1/), (/ix,jx/))\n           else\n              write(6,*) \"Error : variable not defined in rst file before write: \", varName\n           endif\n#endif\n\n        end subroutine w_rst_rt_nc2\n\n        subroutine w_rst_rt_nc3(ncid,ix,jx,NSOIL,inVar, varName)\n           implicit none\n           integer:: ncid,ix,jx,varid , iret, nsoil\n           character(len=*) varName\n           real,dimension(ix,jx,nsoil):: inVar\n           character(len=2) tmpStr\n           integer k\n#ifdef MPP_LAND\n           real varTmp(global_rt_nx,global_rt_ny)\n           do k = 1, nsoil\n              call write_IO_rt_real(inVar(:,:,k),varTmp(:,:))\n              if(my_id .eq. IO_id) then\n                 if( k .lt. 10) then\n                    write(tmpStr, '(i1)') k\n                 else\n                    write(tmpStr, '(i2)') k\n                 endif\n                 iret = nf90_inq_varid(ncid,varName//trim(tmpStr), varid)\n                 iret = nf90_put_var(ncid, varid, varTmp, (/1,1/), (/global_rt_nx,global_rt_ny/))\n              endif\n           end do\n#else\n           do k = 1, nsoil\n                 if( k .lt. 10) then\n                    write(tmpStr, '(i1)') k\n                 else\n                    write(tmpStr, '(i2)') k\n                 endif\n              iret = nf90_inq_varid(ncid,varName//trim(tmpStr), varid)\n              iret = nf90_put_var(ncid, varid, inVar(:,:,k), (/1,1/), (/ix,jx/))\n           end do\n#endif\n        end subroutine w_rst_rt_nc3\n\n        subroutine w_rst_nc2(ncid,ix,jx,inVar,varName)\n           implicit none\n           integer:: ncid,ix,jx,varid , iret\n           character(len=*) varName\n           real inVar(ix,jx)\n\n#ifdef MPP_LAND\n           real varTmp(global_nx,global_ny)\n           call write_IO_real(inVar,varTmp)\n           if(my_id .eq. IO_id) then\n              iret = nf90_inq_varid(ncid,varName, varid)\n              iret = nf90_put_var(ncid, varid, varTmp, (/1,1/), (/global_nx,global_ny/))\n           endif\n#else\n           iret = nf90_inq_varid(ncid,varName, varid)\n           iret = nf90_put_var(ncid, varid, invar, (/1,1/), (/ix,jx/))\n#endif\n\n        end subroutine w_rst_nc2\n\n        subroutine w_rst_nc3(ncid,ix,jx,NSOIL,inVar, varName)\n           implicit none\n           integer:: ncid,ix,jx,varid , iret, nsoil\n           character(len=*) varName\n           real inVar(ix,jx,nsoil)\n           integer k\n           character(len=2) tmpStr\n\n#ifdef MPP_LAND\n           real varTmp(global_nx,global_ny)\n           do k = 1, nsoil\n              call write_IO_real(inVar(:,:,k),varTmp(:,:))\n              if(my_id .eq. IO_id) then\n                 if( k .lt. 10) then\n                    write(tmpStr, '(i1)') k\n                 else\n                    write(tmpStr, '(i2)') k\n                 endif\n                iret = nf90_inq_varid(ncid,varName//trim(tmpStr), varid)\n                iret = nf90_put_var(ncid, varid, varTmp, (/1,1/), (/global_nx,global_ny/))\n              endif\n           end do\n#else\n           do k = 1, nsoil\n                 if( k .lt. 10) then\n                    write(tmpStr, '(i1)') k\n                 else\n                    write(tmpStr, '(i2)') k\n                 endif\n             iret = nf90_inq_varid(ncid,varName//trim(tmpStr), varid)\n             iret = nf90_put_var(ncid, varid, inVar(:,:,k), (/1,1/), (/ix,jx/))\n           end do\n#endif\n        end subroutine w_rst_nc3\n\n        subroutine w_rst_crt_nc1_lake(ncid,n,inVar,varName &\n#ifdef MPP_LAND\n                 ,nodelist     &\n#endif\n                  )\n           implicit none\n           integer:: ncid,n,varid , iret\n           character(len=*) varName\n           real inVar(n)\n#ifdef MPP_LAND\n           integer:: nodelist(n)\n           if(n .eq. 0) return\n\n           call write_lake_real(inVar,nodelist,n)\n           if(my_id .eq. IO_id) then\n#endif\n              iret = nf90_inq_varid(ncid,varName, varid)\n              iret = nf90_put_var(ncid, varid, inVar, (/1/), (/n/))\n#ifdef MPP_LAND\n           endif\n#endif\n        end subroutine w_rst_crt_nc1_lake\n\n        subroutine w_rst_crt_reach_real(ncid,inVar,varName &\n#ifdef MPP_LAND\n                 , gnlinksl&\n#endif\n                  )\n           implicit none\n           integer:: ncid,varid , iret, n\n           character(len=*) varName\n           real, dimension(:) :: inVar\n\n#ifdef MPP_LAND\n           integer:: gnlinksl\n           real,allocatable,dimension(:) :: g_var\n           if(my_id .eq. io_id) then\n                allocate(g_var(gnlinksl))\n                g_var  = 0\n           else\n                allocate(g_var(1) )\n           endif\n\n           call ReachLS_write_io(inVar, g_var)\n           if(my_id .eq. IO_id) then\n              iret = nf90_inq_varid(ncid,varName, varid)\n              iret = nf90_put_var(ncid, varid, g_var, (/1/), (/gnlinksl/))\n           endif\n           if(allocated(g_var)) deallocate(g_var)\n#else\n           n = size(inVar,1)\n           iret = nf90_inq_varid(ncid,varName, varid)\n           iret = nf90_put_var(ncid, varid, inVar, (/1/), (/n/))\n#endif\n        end subroutine w_rst_crt_reach_real\n\n\n        subroutine w_rst_crt_reach_real8(ncid,inVar,varName &\n#ifdef MPP_LAND\n                 , gnlinksl&\n#endif\n                  )\n           implicit none\n           integer:: ncid,varid , iret, n\n           character(len=*) varName\n           real*8, dimension(:) :: inVar\n\n#ifdef MPP_LAND\n           integer:: gnlinksl\n           real*8,allocatable,dimension(:) :: g_var\n           if(my_id .eq. io_id) then\n                allocate(g_var(gnlinksl))\n                g_var  = 0\n           else\n                allocate(g_var(1) )\n           endif\n\n           call ReachLS_write_io(inVar, g_var)\n           if(my_id .eq. IO_id) then\n              iret = nf90_inq_varid(ncid,varName, varid)\n              iret = nf90_put_var(ncid, varid, g_var, (/1/), (/gnlinksl/))\n           endif\n           if(allocated(g_var)) deallocate(g_var)\n#else\n           n = size(inVar,1)\n           iret = nf90_inq_varid(ncid,varName, varid)\n           iret = nf90_put_var(ncid, varid, inVar, (/1/), (/n/))\n#endif\n        end subroutine w_rst_crt_reach_real8\n\n\n\n        subroutine w_rst_crt_nc1(ncid,n,inVar,varName &\n#ifdef MPP_LAND\n                 ,map_l2g, gnlinks&\n#endif\n                  )\n           implicit none\n           integer:: ncid,n,varid , iret\n           character(len=*) varName\n           real inVar(n)\n#ifdef MPP_LAND\n           integer:: gnlinks, map_l2g(n)\n           real g_var(gnlinks)\n           call write_chanel_real(inVar,map_l2g,gnlinks,n,g_var)\n           if(my_id .eq. IO_id) then\n              iret = nf90_inq_varid(ncid,varName, varid)\n              iret = nf90_put_var(ncid, varid, g_var, (/1/), (/gnlinks/))\n#else\n              iret = nf90_inq_varid(ncid,varName, varid)\n              iret = nf90_put_var(ncid, varid, inVar, (/1/), (/n/))\n#endif\n#ifdef MPP_LAND\n           endif\n#endif\n        end subroutine w_rst_crt_nc1\n\n        subroutine w_rst_crt_nc1g(ncid,n,inVar,varName)\n           implicit none\n           integer:: ncid,n,varid , iret\n           character(len=*) varName\n           real,dimension(:) ::  inVar\n#ifdef MPP_LAND\n           if(my_id .eq. IO_id) then\n#endif\n              iret = nf90_inq_varid(ncid,varName, varid)\n              iret = nf90_put_var(ncid, varid, inVar, (/1/), (/n/))\n#ifdef MPP_LAND\n           endif\n#endif\n        end subroutine w_rst_crt_nc1g\n\n   subroutine w_rst_gwbucket_real(ncid,numbasns,gnumbasns, &\n                       basnsInd, inV,vName )\n      implicit none\n      integer :: ncid,numbasns,gnumbasns\n      integer(kind=int64), dimension(:) :: basnsInd\n      real, dimension(:) :: inV\n      character(len=*) :: vName\n      integer i, j, k\n      real, allocatable,dimension(:) :: buf\n#ifdef MPP_LAND\n      if (my_id .eq. IO_id) then\n        allocate(buf(gnumbasns))\n      else\n        allocate(buf(1))\n      endif\n      call gw_write_io_real(numbasns,inV,basnsInd,buf)\n#else\n      allocate(buf(gnumbasns))\n      do k = 1, numbasns\n        buf(basnsInd(k)) = inV(k)\n      end do\n#endif\n      call w_rst_crt_nc1g(ncid,gnumbasns,buf,vName)\n      if(allocated(buf)) deallocate(buf)\n   end subroutine w_rst_gwbucket_real\n\n   subroutine read_rst_gwbucket_real(ncid,outV,numbasns,&\n                       gnumbasns,basnsInd, vName)\n      implicit none\n      integer :: ncid,numbasns,gnumbasns\n      integer(kind=int64), dimension(:) :: basnsInd\n      real, dimension(:) :: outV\n      character(len=*) :: vName\n      integer i, j,k\n      real, dimension(gnumbasns) :: buf\n      call read_rst_crt_nc(ncid,buf,gnumbasns,vName)\n      do k = 1, numbasns\n         outV(k) = buf(basnsInd(k))\n      end do\n   end subroutine read_rst_gwbucket_real\n\n\nsubroutine RESTART_IN_NC(inFile,did)\n\nimplicit none\ncharacter(len=*) inFile\ninteger :: ierr, iret,ncid, did\ninteger :: channel_only_in, channelBucket_only_in\ninteger :: i, j\n\n\n#ifdef MPP_LAND\nif(IO_id .eq. my_id) then\n#endif\n!open a netcdf file\n   iret = nf90_open(trim(inFile), NF90_NOWRITE, ncid)\n#ifdef MPP_LAND\nendif\ncall mpp_land_bcast_int1(iret)\n#endif\nif (iret /= 0) then\n   write(*,'(\"Problem opening file: ''\", A, \"''\")') &\n        trim(inFile)\n   call hydro_stop(\"In RESTART_IN_NC() - Problem opening file\")\nendif\n\n#ifdef MPP_LAND\nif(IO_id .eq. my_id) then\n#endif\n\n   !! Dont use a restart from a channel_only run if you're not running channel_only\n   iret = nf90_get_att(ncid, NF90_GLOBAL, \"channel_only\", channel_only_in)\n   if(iret .eq. 0) then !! If channel_only attribute prsent, then proceed with this logic\n\n      iret = nf90_get_att(ncid, NF90_GLOBAL, \"channelBucket_only\", channelBucket_only_in)\n\n      iret=0 ! borrow the variable for our own error flagging\n      !! Hierarchy of model restarting ability.\n      !! 1) Full model restarts: all model runs (full, channel_only and channelBucket_only)\n      !! No test needed here.\n\n      !! 2) channelBucket_only restarts: channelBucket_only and channel_only runs\n      if(channelBucket_only_in .eq. 1) then\n         if(nlst(did)%channel_only .eq. 0 .and. nlst(did)%channelBucket_only .eq. 0) iret=1\n      end if\n\n      !! 3) channel_only restarts: only channel_only runs\n      if(channel_only_in .eq. 1) then\n         if(nlst(did)%channel_only .eq. 0) iret=1\n      end if\n\n      if(iret .eq. 1) then\n\n         !! JLM Why dont we adopt this strategy elsewhere, e.g. define logUnit as a module variable.\n         !! JLM Would massively cut down on #ifdefs and repetitive code in certain parts of the code.\n#ifdef NCEP_WCOSS\n         logUnit=78\n#else\n         logUnit=6\n#endif\n\n         write(logUnit,*) 'Restart is not respecting the hierarchy of model restarting ability:'\n         write(logUnit,*) '1) Full model restarts: all model runs (full, channel_only and channelBucket_only),'\n         write(logUnit,*) '2) channelBucket_only restarts: channelBucket_only and channel_only runs,'\n         write(logUnit,*) '3) channel_only restarts: only channel_only runs.'\n         write(logUnit,*) 'Diagnostics:'\n         write(logUnit,*) 'channel_only restart present:', channel_only_in\n         write(logUnit,*) 'channel_only run:', nlst(did)%channel_only\n         write(logUnit,*) 'channelBucket_only restart present:', channelBucket_only_in\n         write(logUnit,*) 'channelBucket_only run:', nlst(did)%channelBucket_only\n         call flush(logUnit)\n         call hydro_stop('Channel Only: Restart file in consistent with forcing type.')\n      end if\n   end if\n\n   iret = nf90_get_att(ncid, NF90_GLOBAL, 'his_out_counts', rt_domain(did)%his_out_counts)\n   iret = nf90_get_att(ncid, NF90_GLOBAL, 'DTCT', nlst(did)%DTCT)\n   iret = nf90_get_att(ncid,NF90_GLOBAL,\"Since_Date\",nlst(did)%sincedate(1:19))\n!   if( nlst(did)%channel_only       .eq. 1 .or. &\n!       nlst(did)%channelBucket_only .eq. 1         ) &\n!       iret = nf90_get_att(ncid,NF90_GLOBAL,\"Restart_Time\",nlst(did)%olddate(1:19))\n   if(iret /= 0) nlst(did)%sincedate = nlst(did)%startdate\n   if(nlst(did)%DTCT .gt. 0) then\n      nlst(did)%DTCT = min(nlst(did)%DTCT, nlst(did)%DTRT_CH)\n   else\n      nlst(did)%DTCT = nlst(did)%DTRT_CH\n   endif\n\n#ifdef MPP_LAND\nendif\n\n!yw call mpp_land_bcast_int1(rt_domain(did)%out_counts)\n! Not sure what caused the problem. added out_counts = 1 as a temporary fix for the hydro output.\nrt_domain(did)%out_counts = 1\n\ncall mpp_land_bcast_real1(nlst(did)%DTCT)\n!if( nlst_rt(did)%channel_only       .eq. 1 .or. &\n!    nlst_rt(did)%channelBucket_only .eq. 1         ) &\n!    call mpp_land_bcast_char(19, nlst_rt(did)%olddate)\n!! call mpp_land_bcast_char(19, nlst_rt(did)%sincedate) ! why not? we read it in.\n#endif\n\n#ifdef HYDRO_D\nwrite(6,*) \"nlst(did)%nsoil=\",nlst(did)%nsoil\n#endif\n\nif( nlst(did)%channel_only       .eq. 0 .and. &\n    nlst(did)%channelBucket_only .eq. 0         ) then\n\n   if(nlst(did)%rst_typ .eq. 1 ) then\n      call read_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%stc,\"stc\")\n      call read_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%smc,\"smc\")\n      call read_rst_nc3(ncid,rt_domain(did)%ix,rt_domain(did)%jx,nlst(did)%nsoil,rt_domain(did)%sh2ox,\"sh2ox\")\n      call read_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%INFXSRT,\"infxsrt\")\n      call read_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%overland%control%surface_water_head_lsm,\"sfcheadrt\")\n      call read_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%soldrain,\"soldrain\")\n\n   end if ! rst_typ .eq. 1\n   !yw check\n\n   !call read_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCMAX1,\"smcmax1\")\n   !call read_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCREF1,\"smcref1\")\n   !call read_rst_nc2(ncid,rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%SMCWLT1,\"smcwlt1\")\n\nendif ! neither channel_only nor channelBucket_only\n\nif(nlst(did)%SUBRTSWCRT  .eq. 1 .or. &\n   nlst(did)%OVRTSWCRT   .eq. 1 .or. &\n   nlst(did)%GWBASESWCRT .ne. 0       ) then\n   !! JLM ?? restarting channel depends on these options?\n\n   if( nlst(did)%channel_only       .eq. 0 .and. &\n       nlst(did)%channelBucket_only .eq. 0         ) then\n\n      if(nlst(did)%SUBRTSWCRT.eq.1.or.nlst(did)%OVRTSWCRT.eq.1) then\n\n         call read_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%INFXSWGT,\"infxswgt\")\n         call read_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%overland%control%surface_water_head_routing,\"sfcheadsubrt\")\n         call read_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%overland%control%boundary_flux,\"QBDRYRT\")\n         call read_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%QSTRMVOLRT_ACC,\"qstrmvolrt\")\n         !AD_CHANGE: This is overwriting the RETDEPRTFAC version, so causes issues when changing that factor.\n         !No need to have in restart since live calculated.\n         !call read_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%overland%properties%retention_depth,\"RETDEPRT\")\n         call read_rst_rt_nc3(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,nlst(did)%nsoil,rt_domain(did)%SH2OWGT,\"sh2owgt\")\n      endif\n\n   end if ! neither channel_only nor channelBucket_only\n\n   if(nlst(did)%CHANRTSWCRT.eq.1) then\n      if(nlst(did)%channel_option .eq. 3) then\n         !! Have not setup channel_only for gridded routing YET\n         call read_rst_crt_stream_nc(ncid,rt_domain(did)%HLINK,rt_domain(did)%NLINKS,\"hlink\",rt_domain(did)%GNLINKS,rt_domain(did)%map_l2g)\n         call read_rst_crt_stream_nc(ncid,rt_domain(did)%QLINK(:,1),rt_domain(did)%NLINKS,\"qlink1\",rt_domain(did)%GNLINKS,rt_domain(did)%map_l2g)\n         call read_rst_crt_stream_nc(ncid,rt_domain(did)%QLINK(:,2),rt_domain(did)%NLINKS,\"qlink2\",rt_domain(did)%GNLINKS,rt_domain(did)%map_l2g)\n         call read_rst_crt_stream_nc(ncid,rt_domain(did)%CVOL,rt_domain(did)%NLINKS,\"cvol\",rt_domain(did)%GNLINKS,rt_domain(did)%map_l2g)\n      else\n         call read_rst_crt_reach_nc(ncid,rt_domain(did)%HLINK,\"hlink\",rt_domain(did)%GNLINKSL,fatalErr=.FALSE.)\n         call read_rst_crt_reach_nc(ncid,rt_domain(did)%QLINK(:,1),\"qlink1\",rt_domain(did)%GNLINKSL)\n         call read_rst_crt_reach_nc(ncid,rt_domain(did)%QLINK(:,2),\"qlink2\",rt_domain(did)%GNLINKSL)\n         !call read_rst_crt_reach_nc(ncid,rt_domain(did)%CVOL,\"cvol\",rt_domain(did)%GNLINKSL)\n         !if(nlst_rt(did)%UDMP_OPT .eq. 1) then\n         ! read in the statistic value\n         !call read_rst_crt_reach_nc(ncid,rt_domain(did)%accSfcLatRunoff,\"accSfcLatRunoff\",rt_domain(did)%GNLINKSL)\n         !call read_rst_crt_reach_nc(ncid,rt_domain(did)%accQLateral,\"accQLateral\",rt_domain(did)%GNLINKSL)\n         !call read_rst_crt_reach_nc(ncid,rt_domain(did)%qSfcLatRunoff,\"qSfcLatRunoff\",rt_domain(did)%GNLINKSL)\n         !call read_rst_crt_reach_nc(ncid,rt_domain(did)%accBucket,\"accBucket\",rt_domain(did)%GNLINKS)\n         !endif\n      endif\n\n      if(rt_domain(did)%NLAKES .gt. 0) then\n         call read_rst_crt_nc(ncid,rt_domain(did)%RESHT,rt_domain(did)%NLAKES,\"resht\")\n         call read_rst_crt_nc(ncid,rt_domain(did)%QLAKEO,rt_domain(did)%NLAKES,\"qlakeo\")\n         call read_rst_crt_nc(ncid,rt_domain(did)%QLAKEI,rt_domain(did)%NLAKES,\"qlakei\")\n      endif\n\n      if( nlst(did)%channel_only       .eq. 0 .and. &\n           nlst(did)%channelBucket_only .eq. 0         ) then\n\n         if(nlst(did)%SUBRTSWCRT.eq.1.or.nlst(did)%OVRTSWCRT.eq.1) then\n            call read_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake,\"lake_inflort\")\n         endif\n      end if\n\n   end if  !  end if(nlst_rt(did)%CHANRTSWCRT.eq.1)\n\n   if((nlst(did)%GWBASESWCRT .eq. 1 .or.  &\n      nlst(did)%GWBASESWCRT .ge. 4) .and. &\n      nlst(did)%GW_RESTART  .ne. 0 .and.  &\n      rt_domain(did)%gnumbasns .gt. 0) then\n\n      if(nlst(did)%channel_only .eq. 0) then\n         if(nlst(did)%UDMP_OPT .eq. 1) then\n            call read_rst_crt_reach_nc(ncid,rt_domain(did)%z_gwsubbas,\"z_gwsubbas\",rt_domain(did)%GNLINKSL)\n         else\n            call read_rst_gwbucket_real(ncid,rt_domain(did)%z_gwsubbas,rt_domain(did)%numbasns,&\n                 rt_domain(did)%gnumbasns,rt_domain(did)%basnsInd, \"z_gwsubbas\")\n         endif\n\n      end if !       if( nlst_rt(did)%channel_only .eq. 0 ) then\n\n   end if  ! end    if((nlst_rt(did)%GWBASESWCRT .eq. 1 .or. nlst_rt(did)%GWBASESWCRT .ge. 4) .and. &\n!                      nlst_rt(did)%GW_RESTART  .ne. 0 .and. &\n!                      rt_domain(did)%gnumbasns .gt. 0        )\n\n   !! JLM: WHat is this option??\n   if(nlst(did)%GWBASESWCRT.eq.3) then\n      if(nlst(did)%SUBRTSWCRT.eq.1.or.nlst(did)%OVRTSWCRT.eq.1) then\n         call read_rt_nc2(ncid,rt_domain(did)%ixrt,rt_domain(did)%jxrt,gw2d(did)%ho,\"HEAD\")\n      endif\n   end if\n\nend if  !  end if(nlst_rt(did)%SUBRTSWCRT  .eq. 1 .or. &\n!                 nlst_rt(did)%OVRTSWCRT   .eq. 1 .or. &\n!                 nlst_rt(did)%GWBASESWCRT .ne. 0       )\n\n!! Resetting these after writing the t=0 output file instead so that no information is\n!! lost.\n!if(nlst_rt(did)%rstrt_swc.eq.1) then  !Switch for rest of restart accum vars...\n!#ifdef HYDRO_D\n!            print *, \"1 Resetting RESTART Accumulation Variables to 0...\",nlst_rt(did)%rstrt_swc\n!#endif\n!! JLM:\n!! Reset of accumulation variables move to end of subroutine\n!!   Routing/module_HYDRO_drv.F: HYDRO_ini\n!! See comments there.\n!! Conensed, commented code:\n!! rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake=0.!rt_domain(did)%surface_water_to_channel=0.\n!end if\n\n#ifdef MPP_LAND\nif(my_id .eq. IO_id) &\n#endif\n     iret =  nf90_close(ncid)\n#ifdef HYDRO_D\nwrite(6,*) \"end of RESTART_IN\"\ncall flush(6)\n#endif\n\nend subroutine RESTART_IN_nc\n\n\n      subroutine read_rst_nc3(ncid,ix,jx,NSOIL,var,varStr)\n         implicit none\n         integer ::  ix,jx,nsoil, ireg, ncid, varid, iret\n         real,dimension(ix,jx,nsoil) ::  var\n         character(len=*) :: varStr\n         character(len=2) :: tmpStr\n         integer :: n\n         integer i\n#ifdef MPP_LAND\n         real,dimension(global_nx,global_ny) :: xtmp\n#endif\n\n         do i = 1, nsoil\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) then\n#endif\n                 if( i .lt. 10) then\n                    write(tmpStr, '(i1)') i\n                 else\n                    write(tmpStr, '(i2)') i\n                 endif\n           iret = nf90_inq_varid(ncid,  trim(varStr)//trim(tmpStr),  varid)\n#ifdef MPP_LAND\n         endif\n         call mpp_land_bcast_int1(iret)\n#endif\n\n         if (iret /= 0) then\n#ifdef HYDRO_D\n            print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n            return\n         endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr//trim(tmpStr)\n#endif\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) &\n            iret = nf90_get_var(ncid, varid, xtmp)\n\n            call decompose_data_real(xtmp(:,:), var(:,:,i))\n#else\n            iret = nf90_get_var(ncid, varid, var(:,:,i))\n#endif\n         end do\n\n      end subroutine read_rst_nc3\n\n      subroutine read_rst_nc2(ncid,ix,jx,var,varStr)\n         implicit none\n         integer ::  ix,jx,ireg, ncid, varid, iret\n         real,dimension(ix,jx) ::  var\n         character(len=*) :: varStr\n#ifdef MPP_LAND\n         real,dimension(global_nx,global_ny) :: xtmp\n         if(my_id .eq. IO_id) &\n#endif\n           iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n\n#ifdef MPP_LAND\n         call mpp_land_bcast_int1(iret)\n#endif\n\n         if (iret /= 0) then\n#ifdef HYDRO_D\n            print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n            return\n         endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr\n#endif\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) &\n            iret = nf90_get_var(ncid, varid, xtmp)\n\n         call decompose_data_real(xtmp, var)\n#else\n            var = 0.0\n            iret = nf90_get_var(ncid, varid, var)\n#endif\n      end subroutine read_rst_nc2\n\n      subroutine read_rst_rt_nc3(ncid,ix,jx,NSOIL,var,varStr)\n         implicit none\n         integer ::  ix,jx,nsoil, ireg, ncid, varid, iret\n         real,dimension(ix,jx,nsoil) ::  var\n         character(len=*) :: varStr\n         character(len=2) :: tmpStr\n         integer i\n#ifdef MPP_LAND\n         real,dimension(global_rt_nx,global_rt_ny) :: xtmp\n#endif\n         do i = 1, nsoil\n                 if( i .lt. 10) then\n                    write(tmpStr, '(i1)') i\n                 else\n                    write(tmpStr, '(i2)') i\n                 endif\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) &\n#endif\n            iret = nf90_inq_varid(ncid,  trim(varStr)//trim(tmpStr),  varid)\n#ifdef MPP_LAND\n         call mpp_land_bcast_int1(iret)\n#endif\n         if (iret /= 0) then\n#ifdef HYDRO_D\n            print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n            return\n         endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr//trim(tmpStr)\n#endif\n#ifdef MPP_LAND\n         iret = nf90_get_var(ncid, varid, xtmp)\n            call decompose_RT_real(xtmp(:,:),var(:,:,i),global_rt_nx,global_rt_ny,ix,jx)\n#else\n         iret = nf90_get_var(ncid, varid, var(:,:,i))\n#endif\n         end do\n      end subroutine read_rst_rt_nc3\n\n      subroutine read_rst_rt_nc2(ncid,ix,jx,var,varStr)\n         implicit none\n         integer ::  ix,jx,ireg, ncid, varid, iret\n         real,dimension(ix,jx) ::  var\n         character(len=*) :: varStr\n#ifdef MPP_LAND\n         real,dimension(global_rt_nx,global_rt_ny) :: xtmp\n#endif\n         iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n#ifdef MPP_LAND\n         call mpp_land_bcast_int1(iret)\n#endif\n         if (iret /= 0) then\n#ifdef HYDRO_D\n            print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n            return\n         endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr\n#endif\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) &\n             iret = nf90_get_var(ncid, varid, xtmp)\n         call decompose_RT_real(xtmp,var,global_rt_nx,global_rt_ny,ix,jx)\n#else\n            iret = nf90_get_var(ncid, varid, var)\n#endif\n      end subroutine read_rst_rt_nc2\n\n      subroutine read_rt_nc2(ncid,ix,jx,var,varStr)\n         implicit none\n         integer ::  ix,jx, ncid, varid, iret\n         real,dimension(ix,jx) ::  var\n         character(len=*) :: varStr\n\n#ifdef MPP_LAND\n         real,allocatable, dimension(:,:) :: xtmp\n!yw         real,dimension(global_rt_nx,global_rt_ny) :: xtmp\n         if(my_id .eq. io_id ) then\n             allocate(xtmp(global_rt_nx,global_rt_ny))\n         else\n             allocate(xtmp(1,1))\n         endif\n         xtmp = 0.0\n#endif\n            iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n#ifdef MPP_LAND\n         call mpp_land_bcast_int1(iret)\n#endif\n            if (iret /= 0) then\n#ifdef HYDRO_D\n               print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n               return\n            endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr\n#endif\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) then\n            iret = nf90_get_var(ncid, varid, xtmp)\n         endif\n         call decompose_RT_real(xtmp,var,global_rt_nx,global_rt_ny,ix,jx)\n\n         if(allocated(xtmp)) deallocate(xtmp)\n\n#else\n            iret = nf90_get_var(ncid, varid, var)\n#endif\n      end subroutine read_rt_nc2\n\n      subroutine read_rst_crt_nc(ncid,var,n,varStr)\n         implicit none\n         integer ::  ireg, ncid, varid, n, iret\n         real,dimension(n) ::  var\n         character(len=*) :: varStr\n\n         if( n .le. 0)  return\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) &\n#endif\n            iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n#ifdef MPP_LAND\n         call mpp_land_bcast_int1(iret)\n#endif\n            if (iret /= 0) then\n#ifdef HYDRO_D\n               print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n               return\n            endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr\n#endif\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) then\n#endif\n            iret = nf90_get_var(ncid, varid, var)\n#ifdef MPP_LAND\n         endif\n         if(n .gt. 0) then\n             call mpp_land_bcast_real(n,var)\n         endif\n#endif\n      end subroutine read_rst_crt_nc\n\n      subroutine read_rst_crt_stream_nc(ncid,var_out,n,varStr,gnlinks,map_l2g)\n         implicit none\n         integer ::  ncid, varid, n, iret, gnlinks\n         integer, intent(in), dimension(:) :: map_l2g\n         character(len=*) :: varStr\n         integer :: l, g\n         real,intent(out) , dimension(:) ::  var_out\n#ifdef MPP_LAND\n         real,dimension(gnlinks) ::  var\n#else\n         real,dimension(n) ::  var\n#endif\n\n\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) &\n#endif\n            iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n#ifdef MPP_LAND\n         call mpp_land_bcast_int1(iret)\n#endif\n            if (iret /= 0) then\n#ifdef HYDRO_D\n               print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n               return\n            endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr\n#endif\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) then\n#endif\n            var = 0.0\n            iret = nf90_get_var(ncid, varid, var)\n#ifdef MPP_LAND\n         endif\n         if(gnlinks .gt. 0) then\n            call mpp_land_bcast_real(gnlinks,var)\n         endif\n\n         if(n .le. 0) return\n         var_out = 0\n\n         do l = 1, n\n            g = map_l2g(l)\n            var_out(l) = var(g)\n         end do\n#else\n         var_out = var\n#endif\n      end subroutine read_rst_crt_stream_nc\n\n      subroutine read_rst_crt_reach_nc_real(ncid,var_out,varStr,gnlinksl, fatalErr)\n         implicit none\n         integer ::  ncid, varid, n, iret, gnlinksl\n         character(len=*) :: varStr\n         integer :: l, g\n         real, dimension(:) ::  var_out\n         logical, optional, intent(in) :: fatalErr\n         logical :: fatalErr_local\n         real :: scale_factor, add_offset\n         integer :: ovrtswcrt_in, ss\n         real,allocatable,dimension(:) ::  var, varTmp\n\n         fatalErr_local = .false.\n         if(present(fatalErr)) fatalErr_local=fatalErr\n\n         n = size(var_out,1)\n\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) then\n              allocate(var(gnlinksl))\n         else\n              allocate(var(1))\n         endif\n#else\n              allocate(var(n))\n#endif\n\n\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) then\n            iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n         endif\n         call mpp_land_bcast_int1(iret)\n         if (iret /= 0) then\n#ifdef HYDRO_D\n            print*, 'read_rst_crt_reach_nc: variable not found: name = \"', trim(varStr)//'\"'\n#endif\n\n            if(allocated(var))  deallocate(var)\n\n            !! JLM: is this desirable?\n            !! JLM I think so, maybe an option to this routine specifying if errors are fatal?\n            if (fatalErr_local) &\n                 call hydro_stop(\"read_rst_crt_reach_nc: variable not found: \"//trim(varStr))\n\n            return\n         endif\n\n         if(my_id .eq. IO_id) then\n#ifdef HYDRO_D\n            print*, \"read restart variable \", varStr\n            call flush(6)\n#endif\n\n            var = 0.0\n            iret = nf90_get_var(ncid, varid, var)\n            !! JLM: need a check here.\n\n            iret = nf90_get_att(ncid, varid, 'scale_factor', scale_factor)\n            if(iret .eq. 0) var = var * scale_factor\n            iret = nf90_get_att(ncid, varid, 'add_offset', add_offset)\n            if(iret .eq. 0) var = var + add_offset\n\n            !! NWM channel-only forcings have to be \"decoded\"/unshuffled.\n            !! As of NWM1.2 the following global attribute is different/identifiable\n            !! for files created when io_form_outputs=1,2 (not 0).\n            iret = nf90_get_att(ncid, NF90_GLOBAL, 'dev_OVRTSWCRT', ovrtswcrt_in)\n            if((nlst(did)%channel_only .eq. 1 .or. nlst(did)%channelBucket_only .eq. 1) .and. &\n               iret .eq. 0) then\n               allocate(varTmp(gnlinksl))\n               do ss=1,gnlinksl\n                  varTmp(rt_domain(did)%ascendIndex(ss)+1)=var(ss)\n               end do\n               var=varTmp\n               deallocate(varTmp)\n            end if\n         endif\n\n         call ReachLS_decomp(var,   var_out)\n         if(allocated(var)) deallocate(var)\n#else\n            iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n           if (iret /= 0) then\n#ifdef HYDRO_D\n               print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n               if(allocated(var)) deallocate(var)\n               return\n            endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr\n#endif\n         iret = nf90_get_var(ncid, varid, var_out)\n         if(allocated(var)) deallocate(var)\n#endif\n\n         end subroutine read_rst_crt_reach_nc_real\n\n\n      subroutine read_rst_crt_reach_nc_real8(ncid, var_out, varStr, gnlinksl, fatalErr)\n         implicit none\n         integer, intent(in)          ::  ncid, gnlinksl\n         real*8, dimension(:), intent(inout) ::  var_out\n         character(len=*), intent(in) :: varStr\n         logical, optional, intent(in)       ::  fatalErr\n\n         integer :: varid, n, iret, l, g\n         logical :: fatalErr_local\n         real*8,allocatable,dimension(:) ::  var\n         real :: scale_factor, add_offset\n\n         fatalErr_local = .false.\n         if(present(fatalErr)) fatalErr_local=fatalErr\n\n         n = size(var_out,1)\n\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) then\n              allocate(var(gnlinksl))\n         else\n              allocate(var(1))\n         endif\n#else\n              allocate(var(n))\n#endif\n#ifdef MPP_LAND\n         if(my_id .eq. IO_id) then\n            iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n         endif\n         call mpp_land_bcast_int1(iret)\n         if (iret /= 0) then\n#ifdef HYDRO_D\n            print*, 'read_rst_crt_reach_nc: variable not found: name = \"', trim(varStr)//'\"'\n#endif\n\n            if(allocated(var))  deallocate(var)\n\n            !! JLM: is this desirable?\n            !! JLM I think so, maybe an option to this routine specifying if errors are fatal?\n            if (fatalErr_local) &\n                 call hydro_stop(\"read_rst_crt_reach_nc: variable not found: \"//trim(varStr))\n\n            return\n         endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr\n         call flush(6)\n#endif\n         if(my_id .eq. IO_id) then\n            var = 0.0\n            iret = nf90_get_var(ncid, varid, var)\n            !! JLM need a check here...\n\n            iret = nf90_get_att(ncid, varid, 'scale_factor', scale_factor)\n            if(iret .eq. 0) var = var * scale_factor\n            iret = nf90_get_att(ncid, varid, 'add_offset', add_offset)\n            if(iret .eq. 0) var = var + add_offset\n\n         endif\n         call ReachLS_decomp(var,   var_out)\n         if(allocated(var)) deallocate(var)\n#else\n            iret = nf90_inq_varid(ncid,  trim(varStr),  varid)\n           if (iret /= 0) then\n#ifdef HYDRO_D\n               print*, 'variable not found: name = \"', trim(varStr)//'\"'\n#endif\n               if(allocated(var)) deallocate(var)\n               return\n            endif\n#ifdef HYDRO_D\n         print*, \"read restart variable \", varStr\n#endif\n         iret = nf90_get_var(ncid, varid, var_out)\n         if(allocated(var)) deallocate(var)\n#endif\n         end subroutine read_rst_crt_reach_nc_real8\n\n\n      subroutine hrldas_out()\n      end subroutine hrldas_out\n\n\nsubroutine READ_CHROUTING1( &\n     IXRT,         JXRT,              fgDEM,        CH_NETRT, &\n     CH_LNKRT,     LAKE_MSKRT,        FROM_NODE,    TO_NODE,  &\n     TYPEL,        ORDER,             MAXORDER,     NLINKS,   &\n     NLAKES,       CHANLEN,           MannN,        So,       &\n     ChSSlp,       Bw,                Tw,                     &\n     Tw_CC,        n_CC,              ChannK,       HRZAREA,      LAKEMAXH, &\n     WEIRH,        WEIRC,             WEIRL,        DAML,     &\n     ORIFICEC,     ORIFICEA,          ORIFICEE,               &\n     reservoir_type_specified,        reservoir_type,         &\n     reservoir_parameter_file,        LATLAKE,      LONLAKE,  &\n     ELEVLAKE,     dist,              ZELEV,        LAKENODE, &\n     CH_NETLNK,    CHANXI,            CHANYJ,       CHLAT,    &\n     CHLON,        channel_option,    LATVAL,       LONVAL,   &\n     STRMFRXSTPTS, geo_finegrid_flnm, route_lake_f, LAKEIDM,  &\n     UDMP_OPT                                                 & !! no comma at end\n#ifdef MPP_LAND\n    ,Link_Location                                         &\n#endif\n    )\n\n#ifdef MPP_LAND\nuse module_mpp_land, only:  my_id, io_id\n#endif\ninteger, intent(IN)                          :: IXRT,JXRT, UDMP_OPT\ninteger                                      :: CHANRTSWCRT, NLINKS, NLAKES\nreal, intent(IN), dimension(IXRT,JXRT)       :: fgDEM\ninteger, dimension(IXRT,JXRT)                :: DIRECTION\ninteger, dimension(IXRT,JXRT)                :: GSTRMFRXSTPTS\ninteger, intent(IN), dimension(IXRT,JXRT)    :: CH_NETRT\ninteger(kind=int64), intent(IN), dimension(IXRT,JXRT)    :: CH_LNKRT\ninteger, intent(INOUT), dimension(IXRT,JXRT) :: LAKE_MSKRT\ninteger,                dimension(IXRT,JXRT) :: GORDER  !-- gridded stream orderk\n#ifdef MPP_LAND\ninteger(kind=int64),    dimension(IXRT,JXRT) :: Link_Location !-- gridded stream orderk\ninteger :: LNLINKSL\n#endif\ninteger                                      :: I,J,K,channel_option\nreal, intent(OUT), dimension(IXRT,JXRT)      :: LATVAL, LONVAL\ncharacter(len=28)                            :: dir\n!Dummy inverted grids from arc\n\n!----DJG,DNY New variables for channel and lake routing\ncharacter(len=155)\t :: header\ninteger(kind=int64), intent(INOUT),  dimension(NLINKS)   :: FROM_NODE\nreal, intent(INOUT),  dimension(NLINKS)      :: ZELEV\nreal, intent(INOUT),  dimension(NLINKS)      :: CHLAT,CHLON\n\ninteger(kind=int64), intent(INOUT),  dimension(NLINKS)   :: TO_NODE\ninteger, intent(INOUT),  dimension(NLINKS)   :: TYPEL\ninteger, intent(INOUT),  dimension(NLINKS)   :: ORDER\ninteger, intent(INOUT),  dimension(NLINKS)   :: STRMFRXSTPTS\n\ninteger, intent(INOUT)                       :: MAXORDER\nreal, intent(INOUT),  dimension(NLINKS)      :: CHANLEN   !channel length\nreal, intent(INOUT),  dimension(NLINKS)      :: MannN, So !mannings N\ninteger(kind=int64), intent(INOUT),  dimension(NLINKS)   :: LAKENODE !,LINKID   ! identifies which nodes pour into which lakes\nreal, intent(IN)                             :: dist(ixrt,jxrt,9)\n\ninteger(kind=int64), intent(IN), dimension(IXRT,JXRT)    :: CH_NETLNK\nreal,  dimension(IXRT,JXRT)                  :: ChSSlpG,BwG,TwG,MannNG  !channel properties\nreal,  dimension(IXRT,JXRT)                  :: Tw_CCG,n_CCG            !channel properties of compound\nreal,  dimension(IXRT,JXRT)                  :: ChannKG                 !Channel Infiltration\nreal,  dimension(IXRT,JXRT)                  :: chanDepth, elrt\n\n\n!-- store the location x,y location of the channel element\ninteger, intent(INOUT), dimension(NLINKS)   :: CHANXI, CHANYJ\ninteger(kind=int64), dimension(:) ::  LAKEIDM\n\n!--reservoir/lake attributes\nlogical, intent(IN)\t\t\t            :: reservoir_type_specified\nreal, intent(INOUT),  dimension(:)      :: HRZAREA\n\nreal, intent(INOUT),  dimension(:)      :: LAKEMAXH, WEIRH\nreal, intent(INOUT),  dimension(:)      :: WEIRC\nreal, intent(INOUT),  dimension(:)      :: WEIRL\nreal, intent(INOUT),  dimension(:)      :: DAML\nreal, intent(INOUT),  dimension(:)      :: ORIFICEC\nreal, intent(INOUT),  dimension(:)      :: ORIFICEA\nreal, intent(INOUT),  dimension(:)      :: ORIFICEE\ninteger, intent(INOUT), dimension(:)    :: reservoir_type\ncharacter(len=*), intent(in)            :: reservoir_parameter_file\nreal, intent(INOUT),  dimension(:)      :: LATLAKE,LONLAKE,ELEVLAKE\nreal, intent(INOUT),  dimension(:)      :: ChSSlp, Bw, Tw\nreal, intent(INOUT),  dimension(:)      :: Tw_CC, n_CC, ChannK ! channel properties of compund\n\n\ncharacter(len=*  )                           :: geo_finegrid_flnm, route_lake_f\ncharacter(len=256)                           :: var_name\n\ninteger                                      :: tmp, cnt, ncid, iret, jj,ct\ninteger \t\t\t             :: IOstatus\ninteger(kind=int64)              :: OUTLAKEID\n\nreal                                         :: gc,n\ninteger :: did\nlogical :: fexist\n\ndid = 1\n\n!---------------------------------------------------------\n! End Declarations\n!---------------------------------------------------------\n\n\n!LAKEIDX  = -999\n!LAKELINKID = 0\nMAXORDER = -9999\n!initialize GSTRM\nGSTRMFRXSTPTS = -9999\n\n!yw initialize the array.\nto_node =   MAXORDER\nfrom_node = MAXORDER\n#ifdef MPP_LAND\nLink_location = MAXORDER\n#endif\n\nvar_name = \"LATITUDE\"\ncall nreadRT2d_real  (   &\n     var_name,LATVAL,ixrt,jxrt,trim(geo_finegrid_flnm))\n\nvar_name = \"LONGITUDE\"\ncall nreadRT2d_real(   &\n     var_name,LONVAL,ixrt,jxrt,trim(geo_finegrid_flnm))\n\nvar_name = \"LAKEGRID\"\ncall nreadRT2d_int(&\n     var_name,LAKE_MSKRT,ixrt,jxrt,trim(geo_finegrid_flnm))\n\nvar_name = \"FLOWDIRECTION\"\ncall nreadRT2d_int(&\n     var_name,DIRECTION,ixrt,jxrt,trim(geo_finegrid_flnm))\n\nvar_name = \"STREAMORDER\"\ncall nreadRT2d_int(&\n     var_name,GORDER,ixrt,jxrt,trim(geo_finegrid_flnm))\n\n\nvar_name = \"frxst_pts\"\ncall nreadRT2d_int(&\n     var_name,GSTRMFRXSTPTS,ixrt,jxrt,trim(geo_finegrid_flnm))\n\n!!!Flip y-dimension of highres grids from exported Arc files...\n\nvar_name = \"CHAN_DEPTH\"\ncall nreadRT2d_real(   &\n     var_name,chanDepth,ixrt,jxrt,trim(geo_finegrid_flnm))\n\nif(nlst(did)%GWBASESWCRT .eq. 3) then\n   elrt = fgDEM - chanDepth\nelse\n   elrt = fgDEM     !ywtmp\nendif\n\nct = 0\n\n! temp fix for buggy Arc export...\ndo j=1,jxrt\n   do i=1,ixrt\n      if(DIRECTION(i,j).eq.-128) DIRECTION(i,j)=128\n   end do\nend do\n\ncnt    = 0\nBwG    = 0.0\nTwG    = 0.0\nTw_CCG = 0.0\nn_CCG  = 0.0\n\n\nChSSlpG = 0.0\nMannNG  = 0.0\nTYPEL   = 0\nMannN   = 0.0\nBw      = 0.0\nTw      = 0.0\nTw_CC   = 0.0\nn_CC    = 0.0\nChSSlp  = 0.0\nChannK  = 0.0\nChannKG = 0.0\n\n\nif (channel_option .eq. 3) then\n\n#ifdef MPP_LAND\n  if(my_id .eq. IO_id) then\n#endif\n\n    if (NLAKES .gt. 0) then\n      inquire (file=trim(route_lake_f), exist=fexist)\n      if(fexist) then\n        ! use netcdf lake file of LAKEPARM.nc\n        iret = nf90_open(trim(route_lake_f), NF90_NOWRITE, ncid)\n        if( iret .eq. 0 ) then\n          iret = nf90_close(ncid)\n          write(6,*) \"Before read LAKEPARM from NetCDF \", trim(route_lake_f)\n          write(6,*) \"NLAKES = \", NLAKES\n          call flush(6)\n          call read_route_lake_netcdf(trim(route_lake_f),HRZAREA, &\n                LAKEMAXH, WEIRH, WEIRC,WEIRL, DAML, ORIFICEC,       &\n                ORIFICEA,  ORIFICEE, reservoir_type_specified, reservoir_type, &\n                reservoir_parameter_file, LAKEIDM, latlake, lonlake, ELEVLAKE, NLAKES)\n        else\n          open(unit=79,file=trim(route_lake_f), form='formatted',status='old')\n          write(6,*) \"Before read LAKEPARM from text \", trim(route_lake_f)\n          write(6,*) \"NLAKES = \", NLAKES\n          call flush(6)\n          read(79,*)  header  !-- read the lake file\n          do i=1, NLAKES\n            read (79,*,err=5101) tmp, HRZAREA(i),LAKEMAXH(i), &\n            WEIRC(i), WEIRL(i), ORIFICEC(i), ORIFICEA(i), ORIFICEE(i),&\n            LATLAKE(i), LONLAKE(i),ELEVLAKE(i), WEIRH(i), reservoir_type(i)\n          enddo\n5101      continue\n          close(79)\n        endif !endif for iret\n      else ! lake parm files does not exist\n        call hydro_stop(\"Fatal error: route_lake_f must be specified in the hydro.namelist\")\n        !write(6,*) \"ERROR: route_lake_f required for lakes\"\n        !write(6,*) \"NLAKES = \", NLAKES\n        !call flush(6)\n      endif !endif for fexist\n    endif ! endif for nlakes\n\n#ifdef MPP_LAND\n   endif\n\n   if (NLAKES > 0) then\n      call mpp_land_bcast_real(NLAKES,HRZAREA)\n      call mpp_land_bcast_real(NLAKES,LAKEMAXH)\n      call mpp_land_bcast_real(NLAKES,WEIRH  )\n      call mpp_land_bcast_real(NLAKES,WEIRC  )\n      call mpp_land_bcast_real(NLAKES,WEIRL  )\n      call mpp_land_bcast_real(NLAKES,DAML)\n      call mpp_land_bcast_real(NLAKES,ORIFICEC)\n      call mpp_land_bcast_real(NLAKES,ORIFICEA)\n      call mpp_land_bcast_real(NLAKES,ORIFICEE)\n      call mpp_land_bcast_real(NLAKES,LATLAKE )\n      call mpp_land_bcast_real(NLAKES,LONLAKE )\n      call mpp_land_bcast_real(NLAKES,ELEVLAKE)\n      call mpp_land_bcast_int(NLAKES, reservoir_type)\n   endif\n#endif\nend if  !! channel_option .eq. 3\n\nif (UDMP_OPT .eq. 1) return\n\n!DJG inv       DO j = JXRT,1,-1  !rows\ndo j = 1,JXRT  !rows\n   do i = 1 ,IXRT   !colsumns\n\n      if (CH_NETRT(i, j) .ge. 0) then !get its direction and assign its elevation and order\n\n         if ((DIRECTION(i, j) .eq. 64) .and. (j + 1 .le. JXRT) ) then !North\n            if(CH_NETRT(i,j+1).ge.0) then\n#ifdef MPP_LAND\n               cnt = CH_NETLNK(i,j)\n#else\n               cnt = cnt + 1\n#endif\n               ORDER(cnt) = GORDER(i,j)\n               STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n               ZELEV(cnt) = ELRT(i,j)\n               MannN(cnt) = MannNG(i,j)\n               ChSSlp(cnt) = ChSSlpG(i,j)\n               Bw(cnt) = BwG(i,j)\n               ChannK(cnt) = ChannKG(i,j)\n               Tw(cnt) = TwG(i,j)\n               Tw_CC(cnt) = Tw_CCG(i,j)\n               n_CC(cnt) = n_CCG(i,j)\n               CHLAT(cnt) = LATVAL(i,j)\n               CHLON(cnt) = LONVAL(i,j)\n               FROM_NODE(cnt) = CH_NETLNK(i, j)\n               TO_NODE(cnt) = CH_NETLNK(i, j + 1)\n               CHANLEN(cnt) = dist(i,j,1)\n               CHANXI(cnt) = i\n               CHANYJ(cnt) = j\n#ifdef MPP_LAND\n               Link_Location(i,j) = cnt\n#endif\n            endif\n\n         else if ((DIRECTION(i, j) .eq. 128) .and. (i + 1 .le. IXRT) &\n              .and. (j + 1 .le. JXRT)  ) then !North East\n\n            if(CH_NETRT(i+1,j+1).ge.0) then\n#ifdef MPP_LAND\n               cnt = CH_NETLNK(i,j)\n#else\n               cnt = cnt + 1\n#endif\n               ORDER(cnt) = GORDER(i,j)\n               STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n               ZELEV(cnt) = ELRT(i,j)\n               MannN(cnt) = MannNG(i,j)\n               ChSSlp(cnt) = ChSSlpG(i,j)\n               Bw(cnt) = BwG(i,j)\n               ChannK(cnt) = ChannKG(i,j)\n               Tw(cnt) = TwG(i,j)\n               Tw_CC(cnt) = Tw_CCG(i,j)\n               n_CC(cnt) = n_CCG(i,j)\n               CHLAT(cnt) = LATVAL(i,j)\n               CHLON(cnt) = LONVAL(i,j)\n               FROM_NODE(cnt) = CH_NETLNK(i, j)\n               TO_NODE(cnt) = CH_NETLNK(i + 1, j + 1)\n               CHANLEN(cnt) = dist(i,j,2)\n               CHANXI(cnt) = i\n               CHANYJ(cnt) = j\n#ifdef MPP_LAND\n               Link_Location(i,j) = cnt\n#endif\n            endif\n\n         else if ((DIRECTION(i, j) .eq. 1) .and. (i + 1 .le. IXRT) ) then !East\n\n            if(CH_NETRT(i+1,j).ge.0) then\n#ifdef MPP_LAND\n               cnt = CH_NETLNK(i,j)\n#else\n               cnt = cnt + 1\n#endif\n               ORDER(cnt) = GORDER(i,j)\n               STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n               ZELEV(cnt) = ELRT(i,j)\n               MannN(cnt) = MannNG(i,j)\n               ChSSlp(cnt) = ChSSlpG(i,j)\n               Bw(cnt) = BwG(i,j)\n               ChannK(cnt) = ChannKG(i,j)\n               Tw(cnt) = TwG(i,j)\n               Tw_CC(cnt) = Tw_CCG(i,j)\n               n_CC(cnt) = n_CCG(i,j)\n               CHLAT(cnt) = LATVAL(i,j)\n               CHLON(cnt) = LONVAL(i,j)\n               FROM_NODE(cnt) = CH_NETLNK(i, j)\n               TO_NODE(cnt) = CH_NETLNK(i + 1, j)\n               CHANLEN(cnt) = dist(i,j,3)\n               CHANXI(cnt) = i\n               CHANYJ(cnt) = j\n#ifdef MPP_LAND\n               Link_Location(i,j) = cnt\n#endif\n            endif\n\n         else if ((DIRECTION(i, j) .eq. 2) .and. (i + 1 .le. IXRT) &\n              .and. (j - 1 .ne. 0)  ) then !south east\n\n            if(CH_NETRT(i+1,j-1).ge.0) then\n#ifdef MPP_LAND\n               cnt = CH_NETLNK(i,j)\n#else\n               cnt = cnt + 1\n#endif\n               ORDER(cnt) = GORDER(i,j)\n               STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n               ZELEV(cnt) = ELRT(i,j)\n               MannN(cnt) = MannNG(i,j)\n               ChSSlp(cnt) = ChSSlpG(i,j)\n               Bw(cnt) = BwG(i,j)\n               ChannK(cnt) = ChannKG(i,j)\n               Tw(cnt) = TwG(i,j)\n               Tw_CC(cnt) = Tw_CCG(i,j)\n               n_CC(cnt) = n_CCG(i,j)\n               CHLAT(cnt) = LATVAL(i,j)\n               CHLON(cnt) = LONVAL(i,j)\n               FROM_NODE(cnt) = CH_NETLNK(i, j)\n               TO_NODE(cnt) = CH_NETLNK(i + 1, j - 1)\n               CHANLEN(cnt) = dist(i,j,4)\n               CHANXI(cnt) = i\n               CHANYJ(cnt) = j\n#ifdef MPP_LAND\n               Link_Location(i,j) = cnt\n#endif\n            endif\n\n         else if ((DIRECTION(i, j) .eq. 4) .and. (j - 1 .ne. 0) ) then !due south\n\n            if(CH_NETRT(i,j-1).ge.0) then\n#ifdef MPP_LAND\n               cnt = CH_NETLNK(i,j)\n#else\n               cnt = cnt + 1\n#endif\n               ORDER(cnt) = GORDER(i,j)\n               STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n               ZELEV(cnt) = ELRT(i,j)\n               MannN(cnt) = MannNG(i,j)\n               ChSSlp(cnt) = ChSSlpG(i,j)\n               Bw(cnt) = BwG(i,j)\n               ChannK(cnt) = ChannKG(i,j)\n               Tw(cnt) = TwG(i,j)\n               Tw_CC(cnt) = Tw_CCG(i,j)\n               n_CC(cnt) = n_CCG(i,j)\n               CHLAT(cnt) = LATVAL(i,j)\n               CHLON(cnt) = LONVAL(i,j)\n               FROM_NODE(cnt) = CH_NETLNK(i, j)\n               TO_NODE(cnt) = CH_NETLNK(i, j - 1)\n               CHANLEN(cnt) = dist(i,j,5)\n               CHANXI(cnt) = i\n               CHANYJ(cnt) = j\n#ifdef MPP_LAND\n               Link_Location(i,j) = cnt\n#endif\n            endif\n\n         else if ((DIRECTION(i, j) .eq. 8) .and. (i - 1 .gt. 0) &\n              .and. (j - 1 .ne. 0) ) then !south west\n\n            if(CH_NETRT(i-1,j-1).ge.0) then\n#ifdef MPP_LAND\n               cnt = CH_NETLNK(i,j)\n#else\n               cnt = cnt + 1\n#endif\n               ORDER(cnt) = GORDER(i,j)\n               STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n               ZELEV(cnt) = ELRT(i,j)\n               MannN(cnt) = MannNG(i,j)\n               ChSSlp(cnt) = ChSSlpG(i,j)\n               Bw(cnt) = BwG(i,j)\n               ChannK(cnt) = ChannKG(i,j)\n               Tw(cnt) = TwG(i,j)\n               Tw_CC(cnt) = Tw_CCG(i,j)\n               n_CC(cnt) = n_CCG(i,j)\n               CHLAT(cnt) = LATVAL(i,j)\n               CHLON(cnt) = LONVAL(i,j)\n               FROM_NODE(cnt) = CH_NETLNK(i,j)\n               TO_NODE(cnt) = CH_NETLNK(i - 1, j - 1)\n               CHANLEN(cnt) = dist(i,j,6)\n               CHANXI(cnt) = i\n               CHANYJ(cnt) = j\n#ifdef MPP_LAND\n               Link_Location(i,j) = cnt\n#endif\n            endif\n\n         else if ((DIRECTION(i, j) .eq. 16) .and. (i - 1 .gt. 0) ) then !West\n\n            if(CH_NETRT(i-1,j).ge.0) then\n#ifdef MPP_LAND\n               cnt = CH_NETLNK(i,j)\n#else\n               cnt = cnt + 1\n#endif\n               FROM_NODE(cnt) = CH_NETLNK(i, j)\n               ORDER(cnt) = GORDER(i,j)\n               STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n               ZELEV(cnt) = ELRT(i,j)\n               MannN(cnt) = MannNG(i,j)\n               ChSSlp(cnt) = ChSSlpG(i,j)\n               Bw(cnt) = BwG(i,j)\n               ChannK(cnt) = ChannKG(i,j)\n               Tw(cnt) = TwG(i,j)\n               Tw_CC(cnt) = Tw_CCG(i,j)\n               n_CC(cnt) = n_CCG(i,j)\n               CHLAT(cnt) = LATVAL(i,j)\n               CHLON(cnt) = LONVAL(i,j)\n               TO_NODE(cnt) = CH_NETLNK(i - 1, j)\n               CHANLEN(cnt) = dist(i,j,7)\n               CHANXI(cnt) = i\n               CHANYJ(cnt) = j\n#ifdef MPP_LAND\n               Link_Location(i,j) = cnt\n#endif\n            endif\n\n         else if ((DIRECTION(i, j) .eq. 32) .and. (i - 1 .gt. 0) &\n              .and. (j + 1 .le. JXRT)  ) then !North West\n\n            if(CH_NETRT(i-1,j+1).ge.0) then\n#ifdef MPP_LAND\n               cnt = CH_NETLNK(i,j)\n#else\n               cnt = cnt + 1\n#endif\n               ORDER(cnt) = GORDER(i,j)\n               STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n               ZELEV(cnt) = ELRT(i,j)\n               MannN(cnt) = MannNG(i,j)\n               ChSSlp(cnt) = ChSSlpG(i,j)\n               Bw(cnt) = BwG(i,j)\n               ChannK(cnt) = ChannKG(i,j)\n               Tw(cnt) = TwG(i,j)\n               Tw_CC(cnt) = Tw_CCG(i,j)\n               n_CC(cnt) = n_CCG(i,j)\n               CHLAT(cnt) = LATVAL(i,j)\n               CHLON(cnt) = LONVAL(i,j)\n               FROM_NODE(cnt) = CH_NETLNK(i, j)\n               TO_NODE(cnt) = CH_NETLNK(i - 1, j + 1)\n               CHANLEN(cnt) = dist(i,j,8)\n               CHANXI(cnt) = i\n               CHANYJ(cnt) = j\n#ifdef MPP_LAND\n               Link_Location(i,j) = cnt\n#endif\n            endif\n         else\n#ifdef HYDRO_D\n            !print *, \"NO MATCH\", i,j,CH_NETLNK(i,j),DIRECTION(i,j),i + 1,j - 1 !south east\n#endif\n         end if\n\n      end if !CH_NETRT check for this node\n\n   end do\nend do\n\n#ifdef HYDRO_D\nprint *, \"after exiting the channel, this many nodes\", cnt\nwrite(*,*) \" \"\n#endif\n\n\n!Find out if the boundaries are on an edge\n!DJG inv       DO j = JXRT,1,-1\ndo j = 1,JXRT\n   do i = 1 ,IXRT\n      if (CH_NETRT(i, j) .ge. 0) then !get its direction\n\n         if (DIRECTION(i, j).eq. 64) then\n            if( j + 1 .gt. JXRT)  then         !-- 64's can only flow north\n               goto 101\n\n            elseif ( CH_NETRT(i,j+1) .lt. 0) then !North\n\n               goto 101\n            endif\n            goto 102\n101         continue\n#ifdef MPP_LAND\n            cnt = CH_NETLNK(i,j)\n#else\n            cnt = cnt + 1\n#endif\n            ORDER(cnt) = GORDER(i,j)\n            STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n            ZELEV(cnt) = ELRT(i,j)\n            MannN(cnt) = MannNG(i,j)\n            ChSSlp(cnt) = ChSSlpG(i,j)\n            Bw(cnt) = BwG(i,j)\n            ChannK(cnt) = ChannKG(i,j)\n            Tw(cnt) = TwG(i,j)\n            Tw_CC(cnt) = Tw_CCG(i,j)\n            n_CC(cnt) = n_CCG(i,j)\n            CHLAT(cnt) = LATVAL(i,j)\n            CHLON(cnt) = LONVAL(i,j)\n            if(j+1 .gt. JXRT) then !-- an edge\n               TYPEL(cnt) = 1\n            elseif(LAKE_MSKRT(i,j+1).gt.0) then\n               TYPEL(cnt) = 2\n               LAKENODE(cnt) = LAKE_MSKRT(i,j+1)\n            else\n               TYPEL(cnt) = 1\n            endif\n            FROM_NODE(cnt) = CH_NETLNK(i, j)\n            CHANLEN(cnt) = dist(i,j,1)\n            CHANXI(cnt) = i\n            CHANYJ(cnt) = j\n#ifdef MPP_LAND\n            Link_Location(i,j) = cnt\n#endif\n#ifdef HYDRO_D\n            !                print *, \"Pour Point N\", TYPEL(cnt), LAKENODE(cnt), CHANLEN(cnt), cnt\n#endif\n102         continue\n\n         else if ( DIRECTION(i, j) .eq. 128) then\n\n            !-- 128's can flow out of the North or East edge\n            if ((i + 1 .gt. IXRT)   .or.  (j + 1 .gt. JXRT))  then !   this is due north edge\n               goto 201\n            elseif (CH_NETRT(i + 1, j + 1).lt.0) then !North East\n               goto 201\n            endif\n!#endif\n            goto 202\n201         continue\n#ifdef MPP_LAND\n            cnt = CH_NETLNK(i,j)\n#else\n            cnt = cnt + 1\n#endif\n            ORDER(cnt) = GORDER(i,j)\n            STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n            ZELEV(cnt) = ELRT(i,j)\n            MannN(cnt) = MannNG(i,j)\n            ChSSlp(cnt) = ChSSlpG(i,j)\n            Bw(cnt) = BwG(i,j)\n            ChannK(cnt) = ChannKG(i,j)\n            Tw(cnt) = TwG(i,j)\n            Tw_CC(cnt) = Tw_CCG(i,j)\n            n_CC(cnt) = n_CCG(i,j)\n            CHLAT(cnt) = LATVAL(i,j)\n            CHLON(cnt) = LONVAL(i,j)\n            if((i+1 .gt. IXRT) .or. (j+1 .gt. JXRT))  then ! an edge\n               TYPEL(cnt) = 1\n            elseif(LAKE_MSKRT(i+1,j+1).gt.0) then\n               TYPEL(cnt) = 2\n               LAKENODE(cnt) = LAKE_MSKRT(i+1,j+1)\n            else\n               TYPEL(cnt) = 1\n            endif\n            FROM_NODE(cnt) = CH_NETLNK(i, j)\n            CHANLEN(cnt) = dist(i,j,2)\n            CHANXI(cnt) = i\n            CHANYJ(cnt) = j\n#ifdef MPP_LAND\n            Link_Location(i,j) = cnt\n#endif\n#ifdef HYDRO_D\n            !print *, \"Pour Point NE\", TYPEL(cnt), LAKENODE(cnt), CHANLEN(cnt), cnt\n#endif\n202         continue\n\n         else if (DIRECTION(i, j) .eq. 1) then\n\n            if(i + 1 .gt. IXRT) then     !-- 1's can only flow due east\n               goto 301\n            elseif(CH_NETRT(i + 1, j) .lt. 0) then !East\n               goto 301\n            endif\n            goto 302\n301         continue\n#ifdef MPP_LAND\n            cnt = CH_NETLNK(i,j)\n#else\n            cnt = cnt + 1\n#endif\n            ORDER(cnt) = GORDER(i,j)\n            STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n            ZELEV(cnt) = ELRT(i,j)\n            MannN(cnt) = MannNG(i,j)\n            ChSSlp(cnt) = ChSSlpG(i,j)\n            Bw(cnt) = BwG(i,j)\n            ChannK(cnt) = ChannKG(i,j)\n            Tw(cnt) = TwG(i,j)\n            Tw_CC(cnt) = Tw_CCG(i,j)\n            n_CC(cnt) = n_CCG(i,j)\n            CHLAT(cnt) = LATVAL(i,j)\n            CHLON(cnt) = LONVAL(i,j)\n            if(i+1 .gt. IXRT) then  !an edge\n               TYPEL(cnt) = 1\n            elseif(LAKE_MSKRT(i+1,j).gt.0) then\n               TYPEL(cnt) = 2\n               LAKENODE(cnt) = LAKE_MSKRT(i+1,j)\n            else\n               TYPEL(cnt) = 1\n            endif\n            FROM_NODE(cnt) = CH_NETLNK(i, j)\n            CHANLEN(cnt) = dist(i,j,3)\n            CHANXI(cnt) = i\n            CHANYJ(cnt) = j\n#ifdef MPP_LAND\n            Link_Location(i,j) = cnt\n#endif\n#ifdef HYDRO_D\n            !print *, \"Pour Point E\", TYPEL(cnt), LAKENODE(cnt), CHANLEN(cnt), cnt\n#endif\n302         continue\n\n         else if (DIRECTION(i, j) .eq. 2) then\n\n            !-- 2's can flow out of east or south edge\n            if((i + 1 .gt. IXRT) .or.  (j - 1 .eq. 0)) then     !-- this is the south edge\n               goto 401\n            elseif (CH_NETRT(i + 1, j - 1) .lt.0) then !south east\n               goto 401\n            endif\n            goto 402\n401         continue\n#ifdef MPP_LAND\n            cnt = CH_NETLNK(i,j)\n#else\n            cnt = cnt + 1\n#endif\n            ORDER(cnt) = GORDER(i,j)\n            STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n            ZELEV(cnt) = ELRT(i,j)\n            MannN(cnt) = MannNG(i,j)\n            ChSSlp(cnt) = ChSSlpG(i,j)\n            Bw(cnt) = BwG(i,j)\n            ChannK(cnt) = ChannKG(i,j)\n            Tw(cnt) = TwG(i,j)\n            Tw_CC(cnt) = Tw_CCG(i,j)\n            n_CC(cnt) = n_CCG(i,j)\n            CHLAT(cnt) = LATVAL(i,j)\n            CHLON(cnt) = LONVAL(i,j)\n            if((i+1 .gt. IXRT) .or. (j-1 .eq. 0)) then !an edge\n               TYPEL(cnt) = 1\n            elseif(LAKE_MSKRT(i+1,j-1).gt.0) then\n               TYPEL(cnt) = 2\n               LAKENODE(cnt) = LAKE_MSKRT(i+1,j-1)\n            else\n               TYPEL(cnt) = 1\n            endif\n            FROM_NODE(cnt) = CH_NETLNK(i, j)\n            CHANLEN(cnt) = dist(i,j,4)\n            CHANXI(cnt) = i\n            CHANYJ(cnt) = j\n#ifdef MPP_LAND\n            Link_Location(i,j) = cnt\n#endif\n#ifdef HYDRO_D\n            !print *, \"Pour Point SE\", TYPEL(cnt), LAKENODE(cnt), CHANLEN(cnt), cnt\n#endif\n402         continue\n\n         else if (DIRECTION(i, j) .eq. 4)  then\n\n            if(j - 1 .eq. 0) then         !-- 4's can only flow due south\n               goto 501\n            elseif (CH_NETRT(i, j - 1) .lt. 0) then !due south\n               goto 501\n            endif\n            goto 502\n501         continue\n#ifdef MPP_LAND\n            cnt = CH_NETLNK(i,j)\n#else\n            cnt = cnt + 1\n#endif\n            ORDER(cnt) = GORDER(i,j)\n            STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n            ZELEV(cnt) = ELRT(i,j)\n            MannN(cnt) = MannNG(i,j)\n            ChSSlp(cnt) = ChSSlpG(i,j)\n            Bw(cnt) = BwG(i,j)\n            ChannK(cnt) = ChannKG(i,j)\n            Tw(cnt) = TwG(i,j)\n            Tw_CC(cnt) = Tw_CCG(i,j)\n            n_CC(cnt) = n_CCG(i,j)\n            CHLAT(cnt) = LATVAL(i,j)\n            CHLON(cnt) = LONVAL(i,j)\n            if(j-1 .eq. 0) then !- an edge\n               TYPEL(cnt) =1\n            elseif(LAKE_MSKRT(i,j-1).gt.0) then\n               TYPEL(cnt) = 2\n               LAKENODE(cnt) = LAKE_MSKRT(i,j-1)\n            else\n               TYPEL(cnt) = 1\n            endif\n            FROM_NODE(cnt) = CH_NETLNK(i, j)\n            CHANLEN(cnt) = dist(i,j,5)\n            CHANXI(cnt) = i\n            CHANYJ(cnt) = j\n#ifdef MPP_LAND\n            Link_Location(i,j) = cnt\n#endif\n#ifdef HYDRO_D\n            !print *, \"Pour Point S\", TYPEL(cnt), LAKENODE(cnt), CHANLEN(cnt), cnt\n#endif\n502         continue\n\n         else if ( DIRECTION(i, j) .eq. 8) then\n\n            !-- 8's can flow south or west\n            if( (i - 1 .le. 0) .or.  (j - 1 .eq. 0)) then        !-- this is the south edge\n               goto 601\n            elseif (CH_NETRT(i - 1, j - 1).lt.0) then !south west\n               goto 601\n            endif\n            goto 602\n601         continue\n#ifdef MPP_LAND\n            cnt = CH_NETLNK(i,j)\n#else\n            cnt = cnt + 1\n#endif\n            ORDER(cnt) = GORDER(i,j)\n            STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n            ZELEV(cnt) = ELRT(i,j)\n            MannN(cnt) = MannNG(i,j)\n            ChSSlp(cnt) = ChSSlpG(i,j)\n            Bw(cnt) = BwG(i,j)\n            ChannK(cnt) = ChannKG(i,j)\n            Tw(cnt) = TwG(i,j)\n            Tw_CC(cnt) = Tw_CCG(i,j)\n            n_CC(cnt) = n_CCG(i,j)\n            CHLAT(cnt) = LATVAL(i,j)\n            CHLON(cnt) = LONVAL(i,j)\n            if( (i-1 .eq. 0) .or. (j-1 .eq. 0) ) then !- an edge\n               TYPEL(cnt) = 1\n            elseif(LAKE_MSKRT(i-1,j-1).gt.0) then\n               TYPEL(cnt) = 2\n               LAKENODE(cnt) = LAKE_MSKRT(i-1,j-1)\n            else\n               TYPEL(cnt) = 1\n            endif\n            FROM_NODE(cnt) = CH_NETLNK(i, j)\n            CHANLEN(cnt) = dist(i,j,6)\n            CHANXI(cnt) = i\n            CHANYJ(cnt) = j\n#ifdef MPP_LAND\n            Link_Location(i,j) = cnt\n#endif\n#ifdef HYDRO_D\n            !print *, \"Pour Point SW\", TYPEL(cnt), LAKENODE(cnt), CHANLEN(cnt), cnt\n#endif\n602         continue\n\n         else if (DIRECTION(i, j) .eq. 16) then\n\n            if( i - 1 .le.0) then                 !16's can only flow due west\n               goto 701\n            elseif( CH_NETRT(i - 1, j).lt.0) then !West\n               goto 701\n            endif\n            goto 702\n701         continue\n#ifdef MPP_LAND\n            cnt = CH_NETLNK(i,j)\n#else\n            cnt = cnt + 1\n#endif\n            ORDER(cnt) = GORDER(i,j)\n            STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n            ZELEV(cnt) = ELRT(i,j)\n            MannN(cnt) = MannNG(i,j)\n            ChSSlp(cnt) = ChSSlpG(i,j)\n            Bw(cnt) = BwG(i,j)\n            ChannK(cnt) = ChannKG(i,j)\n            Tw(cnt) = TwG(i,j)\n            Tw_CC(cnt) = Tw_CCG(i,j)\n            n_CC(cnt) = n_CCG(i,j)\n            CHLAT(cnt) = LATVAL(i,j)\n            CHLON(cnt) = LONVAL(i,j)\n            if(i-1 .eq. 0) then !-- an edge\n               TYPEL(cnt) = 1\n            elseif(LAKE_MSKRT(i-1,j).gt.0) then\n               TYPEL(cnt) = 2\n               LAKENODE(cnt) = LAKE_MSKRT(i-1,j)\n            else\n               TYPEL(cnt) = 1\n            endif\n            FROM_NODE(cnt) = CH_NETLNK(i, j)\n            CHANLEN(cnt) = dist(i,j,7)\n            CHANXI(cnt) = i\n            CHANYJ(cnt) = j\n#ifdef MPP_LAND\n            Link_Location(i,j) = cnt\n#endif\n#ifdef HYDRO_D\n            !             print *, \"Pour Point W\", TYPEL(cnt), LAKENODE(cnt), CHANLEN(cnt), cnt\n#endif\n702         continue\n\n         else if ( DIRECTION(i, j) .eq. 32) then\n\n            !-- 32's can flow either west or north\n            if( (i - 1 .le. 0) .or.  (j + 1 .gt. JXRT)) then     !-- this is the north edge\n               goto 801\n            elseif (CH_NETRT(i - 1, j + 1).lt.0) then !North West\n               goto 801\n            endif\n            goto 802\n801         continue\n#ifdef MPP_LAND\n            cnt = CH_NETLNK(i,j)\n#else\n            cnt = cnt + 1\n#endif\n            ORDER(cnt) = GORDER(i,j)\n            STRMFRXSTPTS(cnt) = GSTRMFRXSTPTS(i,j)\n            ZELEV(cnt) = ELRT(i,j)\n            MannN(cnt) = MannNG(i,j)\n            ChSSlp(cnt) = ChSSlpG(i,j)\n            Bw(cnt) = BwG(i,j)\n            ChannK(cnt) = ChannKG(i,j)\n            Tw(cnt) = TwG(i,j)\n            Tw_CC(cnt) = Tw_CCG(i,j)\n            n_CC(cnt) = n_CCG(i,j)\n            CHLAT(cnt) = LATVAL(i,j)\n            CHLON(cnt) = LONVAL(i,j)\n            if( (i-1 .eq. 0) .or. (j+1 .gt. JXRT)) then !-- an edge\n               TYPEL(cnt) = 1\n            elseif(LAKE_MSKRT(i-1,j+1).gt.0) then\n               TYPEL(cnt) = 2\n               LAKENODE(cnt) = LAKE_MSKRT(i-1,j+1)\n            else\n               TYPEL(cnt) = 1\n            endif\n            FROM_NODE(cnt) = CH_NETLNK(i, j)\n            CHANLEN(cnt) = dist(i,j,8)\n            CHANXI(cnt) = i\n            CHANYJ(cnt) = j\n#ifdef MPP_LAND\n            Link_Location(i,j) = cnt\n#endif\n#ifdef HYDRO_D\n            !print *, \"Pour Point NW\", TYPEL(cnt), LAKENODE(cnt), CHANLEN(cnt), cnt\n#endif\n802         continue\n\n         endif\n      endif !CH_NETRT check for this node\n   end do\nend do\n\n#ifdef MPP_LAND\n#ifdef HYDRO_D\nprint*, \"my_id=\",my_id, \"cnt = \", cnt\n#endif\n#endif\n\n#ifdef MPP_LAND\nLink_location = CH_NETLNK\ncall MPP_CHANNEL_COM_INT(Link_location,ixrt,jxrt,int(TYPEL, int64),NLINKS,99)\ncall MPP_CHANNEL_COM_INT(Link_location,ixrt,jxrt,LAKENODE,NLINKS,99)\n#endif\n\nend subroutine READ_CHROUTING1\n\n\n!! Author JLM.\n!! Separate the 2D channel routing memory from the vector/routelink channel routing memory.\nsubroutine read_routelink(&\n     TO_NODE,      TYPEL,        ORDER,    MAXORDER,   &\n     NLAKES,       MUSK,         MUSX,                 &\n     QLINK,        CHANLEN,      MannN,    So,         &\n     ChSSlp,       Bw,           Tw,       Tw_CC,      &\n     n_CC,         ChannK,       LAKEIDA,  HRZAREA,    &\n     LAKEMAXH,     WEIRH,        WEIRC,   WEIRL, DAML, &\n     ORIFICEC,     ORIFICEA,     ORIFICEE,             &\n     reservoir_type_specified,   reservoir_type,       &\n     reservoir_parameter_file,   LATLAKE,              &\n     LONLAKE,      ELEVLAKE,     LAKEIDM,  LAKEIDX,    &\n     route_link_f, route_lake_f, ZELEV,    CHLAT,      &\n     CHLON,        NLINKSL,      LINKID,   GNLINKSL,   &\n     NLINKS,       gages,        gageMiss               )\n\ninteger, intent(INOUT),  dimension(NLINKS) :: TYPEL, ORDER\ninteger, intent(INOUT)                     :: MAXORDER\ninteger                                    :: NLAKES\nreal,    intent(INOUT),  dimension(NLINKS) :: MUSK, MUSX\nreal,    intent(INOUT),  dimension(:,:)    :: QLINK  !channel flow\nreal,    intent(INOUT),  dimension(NLINKS) :: CHANLEN, MannN, So\nreal,    intent(INOUT),  dimension(:)      :: ChSSlp, Bw, Tw !added Top Width LKR/DY\nreal,    intent(INOUT),  dimension(:)      :: Tw_CC, n_CC !compound chnannel params\nreal,    intent(INOUT),  dimension(:)      :: ChannK !added ChanLoss\nreal,    intent(INOUT),  dimension(:)      :: HRZAREA\nreal,    intent(INOUT),  dimension(:)      :: LAKEMAXH, WEIRH, WEIRC, WEIRL, DAML\nreal,    intent(INOUT),  dimension(:)      :: ORIFICEC, ORIFICEA, ORIFICEE\nlogical, intent(IN)                        :: reservoir_type_specified\ninteger, intent(INOUT),  dimension(:)      :: reservoir_type\ncharacter(len=*), intent(in)               :: reservoir_parameter_file\nreal,    intent(INOUT),  dimension(:)      :: LATLAKE, LONLAKE, ELEVLAKE\ninteger(kind=int64), intent(INOUT), dimension(:)  :: LAKEIDM !lake id in LAKEPARM table (.nc or .tbl)\ninteger(kind=int64), intent(INOUT), dimension(:)  :: LAKEIDA !lake COMid 4all link on full nlinks database\ninteger, intent(INOUT),  dimension(:)      :: LAKEIDX !seq index of lakes(1:Nlakes) mapped to COMID\ncharacter(len=256)                         :: route_link_f, route_lake_f\nreal,    intent(INOUT),  dimension(NLINKS) :: ZELEV, CHLAT, CHLON\ninteger                                    :: NLINKS, NLINKSL\ninteger(kind=int64), intent(INOUT),  dimension(NLINKS) :: TO_NODE, LINKID   !  which nodes pour into which lakes\ninteger                                    :: GNLINKSL\ncharacter(len=15), intent(inout), dimension(nlinks) :: gages  !! need to respect the default values\ncharacter(len=15), intent(in)              :: gageMiss\ninteger :: did\n\n!! local variables\ninteger(kind=int64), dimension(NLAKES)         :: LAKELINKID !temporarily store the outlet index for each modeled lake\n\ndid = 1\nLAKELINKID = 0\n\ncall readLinkSL( GNLINKSL,NLINKSL,route_link_f, route_lake_f,maxorder, &\n     LINKID, TO_NODE, TYPEL, ORDER , &\n     QLINK,CHLON, CHLAT, ZELEV, MUSK, MUSX, CHANLEN, &\n     MannN, So, ChSSlp, Bw, Tw, Tw_CC, n_CC, ChannK, LAKEIDA, HRZAREA,  &\n     LAKEMAXH, WEIRH, WEIRC, WEIRL, DAML, ORIFICEC, &\n     ORIFICEA, ORIFICEE, reservoir_type_specified, reservoir_type, reservoir_parameter_file, &\n     gages, gageMiss, LAKEIDM, NLAKES, latlake, lonlake,ELEVLAKE)\n\n!--- get the lake configuration here.\n#ifdef MPP_LAND\ncall nhdLakeMap_mpp(NLAKES,  NLINKSL, TYPEL,   LAKELINKID, LAKEIDX, &\n                    TO_NODE, LINKID,  LAKEIDM, LAKEIDA,    GNLINKSL  )\n!call nhdLakeMap(NLAKES, NLINKSL, TYPEL, LAKELINKID, LAKEIDX, TO_NODE,LINKID, LAKEIDM, LAKEIDA\n#else\ncall nhdLakeMap(NLAKES, NLINKSL, TYPEL, LAKELINKID, LAKEIDX, TO_NODE,LINKID, LAKEIDM, LAKEIDA)\n#endif\n\n#ifdef MPP_LAND\nif (NLAKES > 0) then\n   !         call mpp_land_bcast_int(NLINKSL,LAKEIDA)\n   !         call mpp_land_bcast_int(NLINKSL,LAKEIDX)\n   call mpp_land_bcast_real(NLAKES,HRZAREA)\n   call mpp_land_bcast_int8(NLAKES,LAKEIDM)\n   call mpp_land_bcast_real(NLAKES,LAKEMAXH)\n   call mpp_land_bcast_real(NLAKES,WEIRH  )\n   call mpp_land_bcast_real(NLAKES,WEIRC  )\n   call mpp_land_bcast_real(NLAKES,WEIRL  )\n   call mpp_land_bcast_real(NLAKES,DAML)\n   call mpp_land_bcast_real(NLAKES,ORIFICEC)\n   call mpp_land_bcast_real(NLAKES,ORIFICEA)\n   call mpp_land_bcast_real(NLAKES,ORIFICEE)\n   call mpp_land_bcast_real(NLAKES,LATLAKE )\n   call mpp_land_bcast_real(NLAKES,LONLAKE )\n   call mpp_land_bcast_real(NLAKES,ELEVLAKE)\n   call mpp_land_bcast_int(NLAKES, reservoir_type)\nendif\n#endif\n\nend subroutine read_routelink\n\n\n\n   subroutine readLinkSL( GNLINKSL,NLINKSL,route_link_f, route_lake_f, maxorder, &\n                   LINKID, TO_NODE, TYPEL, ORDER , &\n                   QLINK,CHLON, CHLAT, ZELEV, MUSK, MUSX, CHANLEN, &\n                   MannN, So, ChSSlp, Bw, Tw, Tw_CC, n_CC, ChannK, LAKEIDA, HRZAREA,  &\n                   LAKEMAXH,WEIRH,  WEIRC, WEIRL, DAML, ORIFICEC, &\n                   ORIFICEA, ORIFICEE, reservoir_type_specified, reservoir_type, reservoir_parameter_file, &\n                   gages, gageMiss, LAKEIDM,NLAKES, latlake, lonlake, ELEVLAKE)\n\n        implicit none\n        character(len=*) :: route_link_f,route_lake_f\n        integer  :: GNLINKSL, NLINKSL, tmp_from_node,NLAKES\n\n        INTEGER, INTENT(INOUT)                     :: MAXORDER\n        integer(kind=int64), intent(out), dimension(:) :: LAKEIDA, LINKID, TO_NODE\n        INTEGER, intent(out), dimension(:)         :: TYPEL, ORDER\n\n        real,dimension(:,:)  :: QLINK\n        real, intent(out), dimension(:) ::  CHLON, CHLAT, ZELEV, MUSK, MUSX, CHANLEN\n        real, intent(out), dimension(:) ::  MannN, So, ChSSlp, Bw, Tw, latlake, lonlake, Tw_CC, n_CC\n        real, intent(out), dimension(:) ::  ChannK\n\n        character(len=15), dimension(:), intent(inout) :: gages\n        character(len=15), intent(in) :: gageMiss\n\n!NLAKES\n        integer(kind=int64), intent(out), dimension(:)  ::  LAKEIDM\n        integer, intent(out), dimension(:)  ::  reservoir_type\n        logical, intent(in)\t\t            ::  reservoir_type_specified\n        character(len=*), intent(in)        ::  reservoir_parameter_file\n        REAL, intent(out), dimension(:) :: HRZAREA,LAKEMAXH, WEIRC, WEIRL, DAML, ORIFICEC, WEIRH, &\n                   ORIFICEA, ORIFICEE, ELEVLAKE\n!end NLAKES\n\n        INTEGER(kind=int64), dimension(GNLINKSL) ::  tmpLAKEIDA, tmpLINKID,  tmpTO_NODE\n        INTEGER, dimension(GNLINKSL) ::  tmpTYPEL, tmpORDER\n        character(len=15), dimension(gnlinksl) :: tmpGages\n        CHARACTER(len=155)\t :: header\n        integer :: i\n\n        character(len=256) :: route_link_f_r,route_lake_f_r\n        integer :: lenRouteLinkFR,lenRouteLakeFR ! so the preceeding chan be changed without changing code\n        logical :: routeLinkNetcdf, routeLakeNetcdf\n\n#ifdef MPP_LAND\n        real :: tmpQLINK(GNLINKSL,2)\n        real, allocatable, dimension(:) ::  tmpCHLON, tmpCHLAT, tmpZELEV, tmpMUSK, tmpMUSX, tmpCHANLEN\n        real, allocatable, dimension(:) ::  tmpMannN, tmpSo, tmpChSSlp, tmpBw, tmpTw, tmpTw_CC, tmpn_CC\n        real, allocatable, dimension(:) ::  tmpChannK\n#endif\n\n        !! is RouteLink file netcdf (*.nc) or csv (*.csv)\n        route_link_f_r = adjustr(route_link_f)\n        lenRouteLinkFR = len(route_link_f_r)\n        routeLinkNetcdf = route_link_f_r( (lenRouteLinkFR-2):lenRouteLinkFR) .eq. '.nc'\n\n        !! is RouteLake file netcdf (*.nc) or .TBL\n        route_lake_f_r = adjustr(route_lake_f)\n        lenRouteLakeFR = len(route_lake_f_r)\n        routeLakeNetcdf = route_lake_f_r( (lenRouteLakeFR-2):lenRouteLakeFR) .eq. '.nc'\n\n#ifdef MPP_LAND\n       tmpQLINK = 0\n       tmpGages = gageMiss\n\n       if(my_id .eq. IO_id) then\n\n          allocate(tmpCHLON(GNLINKSL))\n          allocate(tmpCHLAT(GNLINKSL))\n          allocate(tmpZELEV(GNLINKSL))\n          allocate(tmpMUSK(GNLINKSL))\n          allocate(tmpMUSX(GNLINKSL))\n          allocate(tmpCHANLEN(GNLINKSL))\n          allocate(tmpMannN(GNLINKSL))\n          allocate(tmpSo(GNLINKSL))\n          allocate(tmpChSSlp(GNLINKSL))\n          allocate(tmpBw(GNLINKSL))\n          allocate(tmpTw(GNLINKSL))\n          allocate(tmpTw_CC(GNLINKSL))\n          allocate(tmpn_CC(GNLINKSL))\n          allocate(tmpChannK(GNLINKSL))\n\n          if(routeLinkNetcdf) then\n\n             call read_route_link_netcdf(                                &\n                  route_link_f,                                          &\n                  tmpLINKID,     tmpTO_NODE,   tmpCHLON,                 &\n                  tmpCHLAT,      tmpZELEV,     tmpTYPEL,    tmpORDER,    &\n                  tmpQLINK(:,1), tmpMUSK,      tmpMUSX,     tmpCHANLEN,  &\n                  tmpMannN,      tmpSo,        tmpChSSlp,   tmpBw,       &\n                  tmpTw,         tmpTw_CC,     tmpn_CC,     tmpChannK,   &\n                  tmpGages,      tmpLAKEIDA                         )\n\n          else\n\n             open(unit=17,file=trim(route_link_f),form='formatted',status='old')\n             read(17,*)  header\n#ifdef HYDRO_D\n             print *, \"header \", header, \"NLINKSL = \", NLINKSL, GNLINKSL\n#endif\n             call flush(6)\n             do i=1,GNLINKSL\n                read (17,*) tmpLINKID(i),   tmp_from_node,   tmpTO_NODE(i), tmpCHLON(i),    &\n                            tmpCHLAT(i),    tmpZELEV(i),     tmpTYPEL(i),   tmpORDER(i),    &\n                            tmpQLINK(i,1),  tmpMUSK(i),      tmpMUSX(i),    tmpCHANLEN(i),  &\n                            tmpMannN(i),    tmpSo(i),        tmpChSSlp(i),  tmpBw(i),       &\n                            tmpTw(i),       tmpTw_CC(i),     tmpn_CC(i),    tmpChannK(i)\n\n                ! if (So(i).lt.0.005) So(i) = 0.005  !-- impose a minimum slope requireement\n                if (tmpORDER(i) .gt. MAXORDER) MAXORDER = tmpORDER(i)\n             end do\n             close(17)\n\n          end if  ! routeLinkNetcdf\n\n          if(routeLakeNetcdf) then\n             call read_route_lake_netcdf(route_lake_f,HRZAREA, &\n                LAKEMAXH, WEIRH, WEIRC, WEIRL, DAML, ORIFICEC,       &\n                ORIFICEA,  ORIFICEE, reservoir_type_specified, reservoir_type, reservoir_parameter_file, &\n                LAKEIDM, latlake, lonlake, ELEVLAKE, NLAKES)\n          endif\n\n!!- initialize channel  if missing in input\n           do i=1,GNLINKSL\n              if(tmpQLINK(i,1) .le. 1e-3) then\n                 tmpQLINK(i,1) = 20.0 * (1.0/(float(MAXORDER+1) - float(tmpORDER(i))))**3\n                tmpQLINK(i,2) = tmpQLINK(i,1) !## initialize the current flow at each link\n              endif\n           end do\n\n       endif ! my_id .eq. IO_id\n\n        call ReachLS_decomp(tmpLINKID,  LINKID )\n        call ReachLS_decomp(tmpLAKEIDA, LAKEIDA )\n\n        call ReachLS_decomp(tmpTO_NODE, TO_NODE)\n        call ReachLS_decomp(tmpCHLON,    CHLON  )\n        call ReachLS_decomp(tmpCHLAT,    CHLAT  )\n        call ReachLS_decomp(tmpZELEV,    ZELEV  )\n        call ReachLS_decomp(tmpTYPEL,   TYPEL  )\n        call ReachLS_decomp(tmpORDER,   ORDER  )\n        call ReachLS_decomp(tmpQLINK(:,1), QLINK(:,1))\n        call ReachLS_decomp(tmpQLINK(:,2), QLINK(:,2))\n        call ReachLS_decomp(tmpMUSK,    MUSK   )\n        call ReachLS_decomp(tmpMUSX,     MUSX   )\n        call ReachLS_decomp(tmpCHANLEN,  CHANLEN)\n        call ReachLS_decomp(tmpMannN,    MannN  )\n        call ReachLS_decomp(tmpSo,       So     )\n        call ReachLS_decomp(tmpChSSlp,   ChSSlp )\n        call ReachLS_decomp(tmpBw,       Bw     )\n        call ReachLS_decomp(tmpTw,       Tw     )\n        call ReachLS_decomp(tmpTw_CC,    Tw_CC  )\n        call ReachLS_decomp(tmpn_CC,     n_CC   )\n        call ReachLS_decomp(tmpChannK,   ChannK )\n\n!       call ReachLS_decomp(tmpHRZAREA,  HRZAREA)\n!       call ReachLS_decomp(tmpLAKEMAXH, LAKEMAXH)\n!       call ReachLS_decomp(tmpWEIRC,    WEIRC  )\n!       call ReachLS_decomp(tmpWEIRL,    WEIRL  )\n!       call ReachLS_decomp(tmpORIFICEC, ORIFICEC)\n!       call ReachLS_decomp(tmpORIFICEA, ORIFICEA)\n!       call ReachLS_decomp(tmpORIFICEE, ORIFICEE)\n\n        call ReachLS_decomp(tmpGages,    gages)\n        call mpp_land_bcast_int1(MAXORDER)\n\n        if (NLAKES > 0) then\n           call mpp_land_bcast_real(NLAKES, HRZAREA)\n           call mpp_land_bcast_real(NLAKES, LAKEMAXH)\n           call mpp_land_bcast_real(NLAKES, WEIRH)\n           call mpp_land_bcast_real(NLAKES, WEIRC)\n           call mpp_land_bcast_real(NLAKES, WEIRL)\n           call mpp_land_bcast_real(NLAKES, DAML)\n           call mpp_land_bcast_real(NLAKES, ORIFICEC)\n           call mpp_land_bcast_real(NLAKES, ORIFICEA)\n           call mpp_land_bcast_real(NLAKES, ORIFICEE)\n           call mpp_land_bcast_int8(NLAKES, LAKEIDM)\n           call mpp_land_bcast_real(NLAKES, ELEVLAKE)\n           call mpp_land_bcast_int(NLAKES, reservoir_type)\n        endif\n\n\n        if(my_id .eq. io_id ) then\n           if(allocated(tmpCHLON)) deallocate(tmpCHLON)\n           if(allocated(tmpCHLAT)) deallocate(tmpCHLAT)\n           if(allocated(tmpZELEV)) deallocate(tmpZELEV)\n           if(allocated(tmpMUSK)) deallocate(tmpMUSK)\n           if(allocated(tmpMUSX)) deallocate(tmpMUSX)\n           if(allocated(tmpCHANLEN)) deallocate(tmpCHANLEN)\n           if(allocated(tmpMannN)) deallocate(tmpMannN)\n           if(allocated(tmpSo)) deallocate(tmpSo)\n           if(allocated(tmpChSSlp)) deallocate(tmpChSSlp)\n           if(allocated(tmpBw)) deallocate(tmpBw)\n           if(allocated(tmpTw)) deallocate(tmpTw)\n           if(allocated(tmpTw_CC)) deallocate(tmpTw_CC)\n           if(allocated(tmpn_CC)) deallocate(tmpn_CC)\n           if(allocated(tmpChannK)) deallocate(tmpChannK)\n!, tmpHRZAREA,&\n!                  tmpLAKEMAXH, tmpWEIRC, tmpWEIRL, tmpORIFICEC, &\n!                  tmpORIFICEA,tmpORIFICEE)\n        endif\n\n#else\n       QLINK = 0\n        if(routeLinkNetcdf) then\n\n          call read_route_link_netcdf(                      &\n                 route_link_f,                              &\n                 LINKID,     TO_NODE, CHLON,                &\n                 CHLAT,      ZELEV,     TYPEL,    ORDER,    &\n                 QLINK(:,1), MUSK,      MUSX,     CHANLEN,  &\n                 MannN,      So,        ChSSlp,   Bw,       &\n                 Tw,         Tw_CC,     n_CC,     ChannK, gages,    &\n                 LAKEIDA                                     )\n\n        else\n\n          open(unit=17,file=trim(route_link_f),form='formatted',status='old')\n          read(17,*)  header\n#ifdef HYDRO_D\n          print *, \"header \", header, \"NLINKSL = \", NLINKSL\n#endif\n          do i=1,NLINKSL\n              read (17,*) LINKID(i), tmp_from_node, TO_NODE(i), CHLON(i),CHLAT(i),ZELEV(i), &\n                   TYPEL(i), ORDER(i), QLINK(i,1), MUSK(i), MUSX(i), CHANLEN(i), &\n                   MannN(i), So(i), ChSSlp(i), Bw(i), Tw(i), Tw_CC(i), n_CC(i), ChannK(i)\n\n              ! if (So(i).lt.0.005) So(i) = 0.005  !-- impose a minimum slope requireement\n              if (ORDER(i) .gt. MAXORDER) MAXORDER = ORDER(i)\n          end do\n          close(17)\n\n        end if  ! routeLinkNetcdf\n\n!!- initialize channel according to order if missing in input\n        do i=1,NLINKSL\n            if(QLINK(i,1) .le. 1e-3) then\n              QLINK(i,1) = 20.0 * (1/(float(MAXORDER+1) - float(ORDER(i))))**3\n              QLINK(i,2) = QLINK(i,1) !## initialize the current flow at each link\n            endif\n        end do\n\n!!================================\n!!! need to add the sequential lake read here\n!!=================================\n\n\n#endif\n\n        do i=1,NLINKSL\n!           if(So(i) .lt. 0.001) So(i) = 0.001\n           So(i) = max(So(i), 0.00001)\n        end do\n\n#ifdef HYDRO_D\n       write(6,*) \"finish read readLinkSL \"\n       call flush(6)\n\n#endif\n   end subroutine readLinkSL\n\n\n\n\n#ifdef MPP_LAND\n\n!yw continue\n\nsubroutine MPP_READ_CHROUTING_new(&\n     IXRT,         JXRT,              ELRT,           CH_NETRT,  &\n     CH_LNKRT,     LAKE_MSKRT,        FROM_NODE,      TO_NODE,   &\n     TYPEL,        ORDER,             MAXORDER,       NLINKS,    &\n     NLAKES,       CHANLEN,           MannN,          So,        &\n     ChSSlp,       Bw,                Tw,             Tw_CC,     &\n     n_CC,         ChannK,            HRZAREA,        LAKEMAXH,  &\n     WEIRH,        WEIRC,             WEIRL,          DAML,      &\n     ORIFICEC,     ORIFICEA,          ORIFICEE,                  &\n     reservoir_type_specified,        reservoir_type,            &\n     reservoir_parameter_file,        LATLAKE,        LONLAKE,   &\n     ELEVLAKE,     dist,              ZELEV,          LAKENODE,  &\n     CH_NETLNK,    CHANXI,            CHANYJ,         CHLAT,     &\n     CHLON,        channel_option,    LATVAL,         LONVAL,    &\n     STRMFRXSTPTS, geo_finegrid_flnm, route_lake_f,   LAKEIDM,   &\n     UDMP_OPT,     g_ixrt,            g_jxrt,         gnlinks,   &\n     GCH_NETLNK,   map_l2g,           link_location,  yw_mpp_nlinks, &\n     lake_index,   nlinks_index                                       )\n\nimplicit none\ninteger, intent(IN)                          :: IXRT,JXRT,g_IXRT,g_JXRT, GNLINKS, UDMP_OPT\ninteger                                      :: CHANRTSWCRT, NLINKS, NLAKES\ninteger                                      :: I,J,channel_option\ncharacter(len=28)                            :: dir\n\ncharacter(len=155)\t :: header\ninteger(kind=int64), intent(INOUT),  dimension(NLINKS)   :: FROM_NODE\nreal, intent(INOUT),  dimension(NLINKS)      :: ZELEV\nreal, intent(INOUT),  dimension(NLINKS)      :: CHLAT,CHLON\n\ninteger(kind=int64), intent(INOUT),  dimension(NLINKS)   :: TO_NODE\ninteger, intent(INOUT),  dimension(NLINKS)   :: TYPEL\ninteger, intent(INOUT),  dimension(NLINKS)   :: ORDER\ninteger, intent(INOUT),  dimension(NLINKS)   :: STRMFRXSTPTS\n\ninteger, intent(INOUT)                       :: MAXORDER\nreal, intent(INOUT),  dimension(NLINKS)      :: CHANLEN   !channel length\nreal, intent(INOUT),  dimension(NLINKS)      :: MannN, So !mannings N\ninteger(kind=int64), intent(INOUT),  dimension(NLINKS)   :: LAKENODE  ! identifies which nodes pour into which lakes\nreal, intent(IN)                             :: dist(ixrt,jxrt,9)\ninteger, intent(INOUT),  dimension(NLINKS)   :: map_l2g\n\n!-- store the location x,y location of the channel element\ninteger, intent(INOUT), dimension(NLINKS)   :: CHANXI, CHANYJ\n\nlogical, intent(IN)                          :: reservoir_type_specified\nreal, intent(INOUT),  dimension(NLAKES)      :: HRZAREA\nreal, intent(INOUT),  dimension(NLAKES)      :: LAKEMAXH, WEIRH\nreal, intent(INOUT),  dimension(NLAKES)      :: WEIRC\nreal, intent(INOUT),  dimension(NLAKES)      :: WEIRL\nreal, intent(INOUT),  dimension(NLAKES)      :: DAML\nreal, intent(INOUT),  dimension(NLAKES)      :: ORIFICEC\nreal, intent(INOUT),  dimension(NLAKES)      :: ORIFICEA\nreal, intent(INOUT),  dimension(NLAKES)      :: ORIFICEE\ninteger, intent(INOUT), dimension(NLAKES)    :: reservoir_type\ncharacter(len=*), intent(in)                 :: reservoir_parameter_file\nreal, intent(INOUT),  dimension(NLAKES)      :: LATLAKE,LONLAKE,ELEVLAKE\nreal, intent(INOUT), dimension(NLINKS)       :: ChSSlp, Bw, Tw\nreal, intent(INOUT), dimension(NLINKS)       :: Tw_CC, n_CC, ChannK\n\ncharacter(len=*  )                           :: geo_finegrid_flnm, route_lake_f\ncharacter(len=256)                           :: var_name\n\ninteger                                      :: tmp, cnt, ncid\nreal                                         :: gc,n\n\ninteger(kind=int64), intent(IN), dimension(IXRT,JXRT)    :: CH_NETLNK,GCH_NETLNK\nreal, intent(IN), dimension(IXRT,JXRT)       :: ELRT\ninteger, intent(IN), dimension(IXRT,JXRT)    :: CH_NETRT\ninteger(kind=int64), intent(IN), dimension(IXRT,JXRT) :: CH_LNKRT\ninteger, intent(OUT), dimension(IXRT,JXRT) :: LAKE_MSKRT\ninteger(kind=int64), intent(OUT), dimension(IXRT,JXRT) :: link_location\nreal, intent(OUT), dimension(IXRT,JXRT)    :: latval,lonval\ninteger :: k\ninteger, dimension(nlinks)            :: node_table, nlinks_index\ninteger, dimension(nlakes)            :: lake_index\ninteger(kind=int64), dimension(nlakes)    :: LAKEIDM\ninteger :: yw_mpp_nlinks , l, mpp_nlinks\n\n\ncall READ_CHROUTING1( &\n     IXRT,         JXRT,              ELRT,      CH_NETRT,&\n     CH_LNKRT,     LAKE_MSKRT,        FROM_NODE, TO_NODE, &\n     TYPEL,        ORDER,             MAXORDER,  NLINKS,  &\n     NLAKES,       CHANLEN,           MannN,     So,      &\n     ChSSlp,       Bw,                Tw,        Tw_CC,   &\n     n_CC,         ChannK,            HRZAREA,   LAKEMAXH, &\n     WEIRH,        WEIRC,             WEIRL,     DAML,    &\n     ORIFICEC,     ORIFICEA,          ORIFICEE,           &\n     reservoir_type_specified,        reservoir_type,     &\n     reservoir_parameter_file,        LATLAKE,   LONLAKE, &\n     ELEVLAKE,     dist,              ZELEV,     LAKENODE,&\n     CH_NETLNK,    CHANXI,            CHANYJ,    CHLAT,   &\n     CHLON,        channel_option,    LATVAL,    LONVAL,  &\n     STRMFRXSTPTS, geo_finegrid_flnm, route_lake_f, LAKEIDM, UDMP_OPT            &\n#ifdef MPP_LAND\n     ,Link_Location  &\n#endif\n     )\n\ncall mpp_land_max_int1(MAXORDER)\n\nif(MAXORDER .eq. 0)  MAXORDER = -9999\n\nlake_index = -99\nif(channel_option .eq. 3) then\n   do j = 1, jxrt\n      do i = 1, ixrt\n         if (LAKE_MSKRT(i,j) .gt. 0) then\n            lake_index(LAKE_MSKRT(i,j)) = LAKE_MSKRT(i,j)\n         endif\n      enddo\n   enddo\nendif\n\n\nCHANXI = 0\nCHANYj = 0\ndo j = 1, jxrt\n   do i = 1, ixrt\n      if(CH_NETLNK(i,j) .gt. 0) then\n         CHANXI(CH_NETLNK(i,j)) = i\n         CHANYJ(CH_NETLNK(i,j)) = j\n      endif\n   end do\nend do\n\nnode_table = 0\nyw_mpp_nlinks = 0\ndo j = 1, jxrt\n   do i = 1, ixrt\n      if(CH_NETLNK(i,j) .ge. 0) then\n         if( (i.eq.1) .and. (left_id .ge. 0) ) then\n            continue\n         elseif ( (i.eq. ixrt) .and. (right_id .ge. 0) ) then\n            continue\n         elseif ( (j.eq. 1) .and. (down_id .ge. 0) ) then\n            continue\n         elseif ( (j.eq. jxrt) .and. (up_id .ge. 0) ) then\n            continue\n         else\n            l = CH_NETLNK(i,j)\n            ! if(from_node(l) .gt. 0 .and. to_node(l) .gt. 0) then\n            yw_mpp_nlinks = yw_mpp_nlinks + 1\n            nlinks_index(yw_mpp_nlinks) = l\n            ! endif\n         endif\n      endif\n   end do\nend do\n\n#ifdef HYDRO_D\nwrite(6,*) \"nlinks=\", nlinks, \" yw_mpp_nlinks=\", yw_mpp_nlinks,\" nlakes=\", nlakes\ncall flush(6)\n#endif\nif (NLAKES > 0) then\n   call mpp_land_bcast_real(NLAKES,HRZAREA)\n   call mpp_land_bcast_real(NLAKES,LAKEMAXH)\n   call mpp_land_bcast_real(NLAKES,WEIRC)\n   call mpp_land_bcast_real(NLAKES,WEIRC)\n   call mpp_land_bcast_real(NLAKES,WEIRL)\n   call mpp_land_bcast_real(NLAKES,DAML)\n   call mpp_land_bcast_real(NLAKES,ORIFICEC)\n   call mpp_land_bcast_real(NLAKES,ORIFICEA)\n   call mpp_land_bcast_real(NLAKES,ORIFICEE)\n   call mpp_land_bcast_real(NLAKES,LATLAKE)\n   call mpp_land_bcast_real(NLAKES,LONLAKE)\n   call mpp_land_bcast_real(NLAKES,ELEVLAKE)\n   call mpp_land_bcast_int(NLAKES, reservoir_type)\nendif\n\nlink_location = CH_NETLNK\n\n\nend subroutine MPP_READ_CHROUTING_new\n\n#endif\n\n\n#ifdef MPP_LAND\n       subroutine out_day_crt(dayMean,outFile)\n           implicit none\n           integer :: did\n           real ::  dayMean(:)\n           character(len=*) :: outFile\n           integer:: ywflag\n           ywflag = -999\n           did = 1\n           if((nlst(did)%olddate(12:13) .eq. \"00\") .and. (nlst(did)%olddate(15:16) .eq. \"00\") ) ywflag = 99\n           call mpp_land_bcast_int1(ywflag)\n           if(ywflag <0) return\n           ! output daily\n           call out_obs_crt(did,dayMean,outFile)\n       end subroutine out_day_crt\n\n       subroutine out_obs_crt(did,dayMean,outFile)\n           implicit none\n           integer did, i, cnt\n           real ::  dayMean(:)\n           character(len=*) :: outFile\n           real,dimension(rt_domain(did)%gnlinks) :: g_dayMean, chlat, chlon\n           integer,dimension(rt_domain(did)%gnlinks) :: STRMFRXSTPTS\n\n           g_dayMean = -999\n           chlat = -999\n           chlon = -999\n           STRMFRXSTPTS = 0\n\n           call write_chanel_int(RT_DOMAIN(did)%STRMFRXSTPTS,rt_domain(did)%map_l2g,rt_domain(did)%gnlinks,rt_domain(did)%nlinks,STRMFRXSTPTS)\n\n           call write_chanel_real(dayMean,rt_domain(did)%map_l2g,rt_domain(did)%gnlinks,rt_domain(did)%nlinks,g_dayMean)\n\n           call write_chanel_real(RT_DOMAIN(did)%CHLON,rt_domain(did)%map_l2g,rt_domain(did)%gnlinks,rt_domain(did)%nlinks,chlon)\n\n           call write_chanel_real(RT_DOMAIN(did)%CHLAT,rt_domain(did)%map_l2g,rt_domain(did)%gnlinks,rt_domain(did)%nlinks,chlat)\n\n\n           open (unit=75,file=outFile,status='unknown',position='append')\n           cnt = 0\n           do i = 1, rt_domain(did)%gnlinks\n              if(STRMFRXSTPTS(i) .gt. 0) then\n                   write(75,114) nlst(did)%olddate(1:4),nlst(did)%olddate(6:7),nlst(did)%olddate(9:10), nlst(did)%olddate(12:13), &\n                         cnt,chlon(i),chlat(i),g_dayMean(i)\n                   cnt = cnt + 1\n              endif\n           end do\n           close(75)\n114 FORMAT(1x,A4,A2,A2,A2,\",\",I7,\", \",F10.5,\",\",F10.5,\",\",F12.3)\n       end subroutine out_obs_crt\n#endif\n\n    subroutine outPutChanInfo(fromNode,toNode,chlon,chlat)\n        implicit none\n        integer, dimension(:) :: fromNode,toNode\n        real, dimension(:) :: chlat,chlon\n        integer :: iret, nodes, i, ncid, dimid_n, varid\n\n        nodes = size(chlon,1)\n\n       iret = nf90_create(\"nodeInfor.nc\", OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n       iret = nf90_def_dim(ncid, \"node\", nodes, dimid_n)  !-- make a decimated grid\n!  define the varialbes\n       iret = nf90_def_var(ncid, \"fromNode\", NF90_INT, (/dimid_n/), varid)\n       iret = nf90_def_var(ncid, \"toNode\", NF90_INT, (/dimid_n/), varid)\n       iret = nf90_def_var(ncid, \"chlat\", NF90_FLOAT, (/dimid_n/), varid)\n          iret = nf90_put_att(ncid, varid, 'long_name', 'node latitude')\n       iret = nf90_def_var(ncid, \"chlon\", NF90_FLOAT, (/dimid_n/), varid)\n          iret = nf90_put_att(ncid, varid, 'long_name', 'node longitude')\n       iret = nf90_enddef(ncid)\n!write to the file\n           iret = nf90_inq_varid(ncid,\"fromNode\", varid)\n           iret = nf90_put_var(ncid, varid, fromNode, (/1/), (/nodes/))\n           iret = nf90_inq_varid(ncid,\"toNode\", varid)\n           iret = nf90_put_var(ncid, varid, toNode, (/1/), (/nodes/))\n           iret = nf90_inq_varid(ncid,\"chlat\", varid)\n           iret = nf90_put_var(ncid, varid, chlat, (/1/), (/nodes/))\n           iret = nf90_inq_varid(ncid,\"chlon\", varid)\n           iret = nf90_put_var(ncid, varid, chlon, (/1/), (/nodes/))\n          iret = nf90_close(ncid)\n    end subroutine outPutChanInfo\n\n\n!===================================================================================================\n! Program Name: read_route_link_netcdf\n! Author(s)/Contact(s): James L McCreight <jamesmcc><ucar><edu>\n! Abstract: Read in the \"RouteLink.nc\" netcdf file specifing the channel topology.\n! History Log:\n! 7/17/15 -Created, JLM.\n! Usage:\n! Parameters: <Specify typical arguments passed>\n! Input Files: netcdf file RouteLink.nc or other name.\n! Output Files: None.\n! Condition codes: Currently incomplete error handling.\n!\n! If appropriate, descriptive troubleshooting instructions or\n! likely causes for failures could be mentioned here with the\n! appropriate error code\n!\n! User controllable options: None.\n\nsubroutine read_route_link_netcdf( route_link_file,                         &\n                                   LINKID,   TO_NODE,   CHLON,              &\n                                   CHLAT,    ZELEV,     TYPEL,    ORDER,    &\n                                   QLINK,    MUSK,      MUSX,     CHANLEN,  &\n                                   MannN,    So,        ChSSlp,   Bw,       &\n                                   Tw,       Tw_CC,     n_CC,     ChannK,   &\n                                   gages,   LAKEIDA                         )\n\nimplicit none\ncharacter(len=*),        intent(in)  :: route_link_file\ninteger(kind=int64), dimension(:),   intent(out) :: LAKEIDA, LINKID, TO_NODE\nreal,    dimension(:),   intent(out) :: CHLON, CHLAT, ZELEV\ninteger, dimension(:),   intent(out) :: TYPEL, ORDER\nreal,    dimension(:),   intent(out) :: QLINK\nreal,    dimension(:),   intent(out) :: MUSK, MUSX, CHANLEN\nreal,    dimension(:),   intent(out) :: MannN, So, ChSSlp, Bw, Tw\nreal,    dimension(:),   intent(out) :: Tw_CC, n_CC, ChannK\n\ncharacter(len=15), dimension(:), intent(inout) :: gages\n\ninteger :: iRet, ncid, ii, varid\nlogical :: fatal_if_error\nfatal_if_error = .TRUE.  !! was thinking this would be a global variable...could become an input.\n\n#ifdef HYDRO_D\nprint*,\"start read_route_link_netcdf\"\n#endif\n\niRet = nf90_open(trim(route_link_file), nf90_nowrite, ncid)\nif (iRet /= nf90_noErr) then\n   write(*,'(\"read_route_link_netcdf: Problem opening: ''\", A, \"''\")') trim(route_link_file)\n   if (fatal_IF_ERROR) call hydro_stop(\"read_route_link_netcdf: Problem opening file.\")\nendif\n\n\ncall get_1d_netcdf_int64(ncid,  'link',     LINKID,    'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_int64(ncid,  'NHDWaterbodyComID',  LAKEIDA, 'read_route_link_netcdf', .FALSE.)\ncall get_1d_netcdf_int64(ncid,  'to',       TO_NODE,   'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'lon',      CHLON,     'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'lat',      CHLAT,     'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'alt',      ZELEV,     'read_route_link_netcdf', .TRUE.)\n!yw call get_1d_netcdf_int(ncid,  'type',     TYPEL,     'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_int(ncid,  'order',    ORDER,     'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'Qi',       QLINK,     'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'MusK',     MUSK,      'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'MusX',     MUSX,      'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'Length',   CHANLEN,   'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'n',        MannN,     'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'So',       So,        'read_route_link_netcdf', .TRUE.)\n!! impose a minimum as this sometimes fails in the file.\nwhere(So .lt. 0.00001) So=0.00001\ncall get_1d_netcdf_real(ncid, 'ChSlp',    ChSSlp,    'read_route_link_netcdf', .TRUE.)\ncall get_1d_netcdf_real(ncid, 'BtmWdth',  Bw,        'read_route_link_netcdf', .TRUE.)\n!! Loads channel infiltration, by default is zero, my need to add namelist option in future\ncall get_1d_netcdf_real(ncid, 'Kchan',  ChannK,     'read_route_link_netcdf', .TRUE.)\n\n! Compound channel variables, contingent on nlst_rt(did)%compound_channel option\nif(nlst(did)%compound_channel) then\n   print*, \"compound_channel is TRUE in hydro.namelist.\"\n   print*, \"Variables are all required in route link: TopWdth, TopWdthCC, nCC.\"\n   ! the fatal_if_error option is tru for all of these. An error in any will be a fatal error.\n   call get_1d_netcdf_real(ncid, 'TopWdth',   Tw,     'read_route_link_netcdf', .true.)\n   call get_1d_netcdf_real(ncid, 'TopWdthCC', Tw_CC,  'read_route_link_netcdf', .true.)\n   call get_1d_netcdf_real(ncid, 'nCC',       n_CC,   'read_route_link_netcdf', .true.)\nelse\n   print*, \"compound_channel is FALSE in hydro.namelist.\"\n   Tw = 0.0  !force top width to 0.0, this deactivates the compound channel formulation.\nend if\n\n\n! gages is optional, only get it if it's defined in the file.\niRet = nf90_inq_varid(ncid, 'gages', varid)\nif (iret .eq. nf90_NoErr) then\n   call get_1d_netcdf_text(ncid, 'gages', gages,  'read_route_link_netcdf', .true.)\nend if\n\niRet = nf90_close(ncId)\nif (iRet /= nf90_noErr) then\n   write(*,'(\"read_route_link_netcdf: Problem closing: ''\", A, \"''\")') trim(route_link_file)\n   if (fatal_IF_ERROR) call hydro_stop(\"read_route_link_netcdf: Problem closing file.\")\nend if\n\n#ifdef HYDRO_D\nii = size(LINKID)\nprint*,'last index=',ii\nprint*, 'CHLON', CHLON(ii), 'CHLAT', CHLAT(ii), 'ZELEV', ZELEV(ii)\nprint*,'TYPEL', TYPEL(ii), 'ORDER', ORDER(ii), 'QLINK', QLINK(ii), 'MUSK', MUSK(ii)\nprint*, 'MUSX', MUSX(ii), 'CHANLEN', CHANLEN(ii), 'MannN', MannN(ii)\nprint*,'So', So(ii), 'ChSSlp', ChSSlp(ii), 'Bw', Bw(ii), 'Tw', Tw(ii)\nprint*,'TwCompund', Tw_CC(ii), 'Mann Compund', n_CC(ii), 'ChannK', ChannK(ii)\n\nprint*,'gages(ii): ',trim(gages(ii))\nprint*,\"finish read_route_link_netcdf\"\n#endif\n\nend subroutine read_route_link_netcdf\n\n\n!===================================================================================================\n! Program Name: read_route_lake_netcdf\n! Abstract: Read in the \"LAKEPARM.nc\" netcdf file specifing the channel topology.\n! History Log:\n! 7/17/15 -Created, JLM., then used by DNY\n! Usage:\n! Parameters: <Specify typical arguments passed>\n! Input Files: netcdf file RouteLink.nc or other name.\n! Output Files: None.\n! Condition codes: Currently incomplete error handling.\n!\nsubroutine read_route_lake_netcdf(route_lake_file,                         &\n                                   HRZAREA,  LAKEMAXH, WEIRH,  WEIRC,    WEIRL, DAML,   &\n                                   ORIFICEC, ORIFICEA,  ORIFICEE,  reservoir_type_specified, &\n                                   reservoir_type, reservoir_parameter_file, &\n                                   LAKEIDM, lakelat, lakelon, ELEVLAKE, NLAKES)\n\n    implicit none\n    character(len=*),              intent(in)  :: route_lake_file\n    integer,                       intent(in)  :: NLAKES\n    logical,                       intent(in)  :: reservoir_type_specified\n    character(len=*),              intent(in)  :: reservoir_parameter_file\n    integer(kind=int64), dimension(:), intent(out) :: LAKEIDM\n    real,    dimension(:),         intent(out) :: HRZAREA,  LAKEMAXH, WEIRC,    WEIRL, WEIRH, DAML\n    real,    dimension(:),         intent(out) :: ORIFICEC, ORIFICEA, ORIFICEE, lakelat, lakelon\n    real,    dimension(:),         intent(out) :: ELEVLAKE\n    integer, dimension(:),         intent(out) :: reservoir_type\n\n    integer :: iRet, ncid, ii, varid\n    logical :: fatal_if_error\n    fatal_if_error = .TRUE.  !! was thinking this would be a global variable...could become an input.\n\n#ifdef HYDRO_D\n    print*,\"start read_route_lake_netcdf\"\n#endif\n\n    iRet = nf90_open(trim(route_lake_file), nf90_nowrite, ncid)\n    if (iRet /= nf90_noErr) then\n       write(*,'(\"read_route_lake_netcdf: Problem opening: ''\", A, \"''\")') trim(route_lake_file)\n       if (fatal_IF_ERROR) call hydro_stop(\"read_route_lake_netcdf: Problem opening file.\")\n    endif\n\n    call get_1d_netcdf_int64(ncid,  'lake_id',  LAKEIDM, 'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'LkArea',   HRZAREA,   'read_route_lake_netcdf', .TRUE.)\n    !rename the LAKEPARM input vars for Elev instead of Ht, 08/23/17 LKR/DY\n    call get_1d_netcdf_real(ncid, 'LkMxE',    LAKEMAXH,  'read_route_lake_netcdf', .TRUE.)\n    !rename WeirH to WeirE\n    call get_1d_netcdf_real(ncid, 'WeirE',    WEIRH,     'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'WeirC',    WEIRC,     'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'WeirL',    WEIRL,     'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'Dam_Length', DAML,    'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'OrificeC', ORIFICEC,  'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'OrificeA', ORIFICEA,  'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'OrificeE', ORIFICEE,  'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'lat', lakelat,        'read_route_lake_netcdf', .TRUE.)\n    call get_1d_netcdf_real(ncid, 'lon', lakelon,        'read_route_lake_netcdf', .TRUE.)\n    !remove the alt var. and add initial fractional depth var. LKR/DY\n    call get_1d_netcdf_real(ncid, 'ifd', ELEVLAKE,       'read_route_lake_netcdf', .FALSE.)\n\n    iRet = nf90_close(ncId)\n    if (iRet /= nf90_noErr) then\n       write(*,'(\"read_route_lake_netcdf: Problem closing: ''\", A, \"''\")') trim(route_lake_file)\n       if (fatal_IF_ERROR) call hydro_stop(\"read_route_lake_netcdf: Problem closing file.\")\n    end if\n\n   ! If reservoir_type_specified is set to true, then call function to read reservoir_type\n   ! from the reservoir parameter file\n   if (reservoir_type_specified) then\n       call read_reservoir_type(reservoir_parameter_file, LAKEIDM, NLAKES, reservoir_type)\n   end if\n\n#ifdef HYDRO_D\n    ii = size(LAKEIDM)\n    print*,'last index=',ii\n    print*,'HRZAREA', HRZAREA(ii)\n    print*,'LAKEMAXH', LAKEMAXH(ii), 'WEIRC', WEIRC(ii), 'WEIRL', WEIRL(ii), 'DAML', DAML(ii)\n    print*,'ORIFICEC', ORIFICEC(ii), 'ORIFICEA', ORIFICEA(ii), 'ORIFICEE', ORIFICEE(ii)\n    print*,\"finish read_route_lake_netcdf\"\n#endif\n\nend subroutine read_route_lake_netcdf\n\n!===================================================================================================\n! Program Names: get_1d_netcdf_real, get_1d_netcdf_int, get_1d_netcdf_text\n! Author(s)/Contact(s): James L McCreight <jamesmcc><ucar><edu>\n! Abstract: Read a variable of real or integer type from an open netcdf file, respectively.\n! History Log:\n! 7/17/15 -Created, JLM.\n! Usage:\n! Parameters: See definitions.\n! Input Files: This file is refered to by it's \"ncid\" obtained from nc_open\n!              prior to calling this routine.\n! Output Files: None.\n! Condition codes: hydro_stop is passed \"get_1d_netcdf\".\n!\n! If appropriate, descriptive troubleshooting instructions or\n! likely causes for failures could be mentioned here with the\n! appropriate error code\n!\n! User controllable options: None.\n\n!! could define an interface for these.\nsubroutine get_1d_netcdf_int(ncid, varName, var, callingRoutine, fatal_if_error)\ninteger,               intent(in)  :: ncid !! the file identifier\ncharacter(len=*),      intent(in)  :: varName\ninteger, dimension(:), intent(out) :: var\ncharacter(len=*),      intent(in)  :: callingRoutine\nlogical,               intent(in)  :: fatal_if_error\ninteger :: varid, iret\niRet = nf90_inq_varid(ncid, varName, varid)\nif (iret /= nf90_noErr) then\n   if (fatal_IF_ERROR) then\n      print*, trim(callingRoutine) // \": get_1d_netcdf_real: variable: \" // trim(varName)\n      call hydro_stop(\"get_1d_netcdf\")\n   end if\nend if\niRet = nf90_get_var(ncid, varid, var)\nif (iRet /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_int: values: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_int\")\nend if\nend subroutine get_1d_netcdf_int\n\n    subroutine get_1d_netcdf_int64(ncid, varName, var, callingRoutine, fatal_if_error)\n        integer,                       intent(in)  :: ncid !! the file identifier\n        character(len=*),              intent(in)  :: varName\n        integer(kind=int64), dimension(:), intent(out) :: var\n        character(len=*),              intent(in)  :: callingRoutine\n        logical,                       intent(in)  :: fatal_if_error\n        integer :: varid, iret\n        iRet = nf90_inq_varid(ncid, varName, varid)\n        if (iret /= nf90_noErr) then\n            if (fatal_IF_ERROR) then\n                print*, trim(callingRoutine) // \": get_1d_netcdf_real: variable: \" // trim(varName)\n                call hydro_stop(\"get_1d_netcdf\")\n            end if\n        end if\n        iRet = nf90_get_var(ncid, varid, var)\n        if (iRet /= nf90_NoErr) then\n            print*, trim(callingRoutine) // \": get_1d_netcdf_int: values: \" // trim(varName)\n            if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_int\")\n        end if\n    end subroutine get_1d_netcdf_int64\n\nsubroutine get_1d_netcdf_real(ncid, varName, var, callingRoutine, fatal_if_error)\ninteger,            intent(in)  :: ncid !! the file identifier\ncharacter(len=*),   intent(in)  :: varName\nreal, dimension(:), intent(out) :: var\ncharacter(len=*),   intent(in)  :: callingRoutine\nlogical,            intent(in)  :: fatal_if_error\n\ninteger :: varid, iret\niRet = nf90_inq_varid(ncid, varName, varid)\nif (iret /= nf90_noErr) then\n   if (fatal_IF_ERROR) then\n      print*, trim(callingRoutine) // \": get_1d_netcdf_real: variable: \" // trim(varName)\n      call hydro_stop(\"get_1d_netcdf\")\n   end if\nend if\niRet = nf90_get_var(ncid, varid, var)\nif (iRet /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_real: values: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_real\")\nend if\nend subroutine get_1d_netcdf_real\n\nsubroutine get_1d_netcdf_text(ncid, varName, var, callingRoutine, fatal_if_error)\ninteger,                        intent(in)  :: ncid !! the file identifier\ncharacter(len=*),               intent(in)  :: varName\ncharacter(len=*), dimension(:), intent(out) :: var\ncharacter(len=*),               intent(in)  :: callingRoutine\nlogical,                        intent(in)  :: fatal_if_error\ninteger :: varId, iRet\niRet = nf90_inq_varid(ncid, varName, varid)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_text: variable: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_text\")\nend if\niRet = nf90_get_var(ncid, varid, var)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_text: values: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_text\")\nend if\nend subroutine get_1d_netcdf_text\n\n!===================================================================================================\n! Program Names:\n!   get_netcdf_dim\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Get the length of a provided dimension.\n! History Log:\n!   7/23/15 -Created, JLM.\n! Usage:\n! Parameters:\n!   file: character, the file to query\n!   dimName: character, the name of the dimension\n!   callingRoutine: character, the name of the calling routine for error messages\n!   fatalErr: Optional, Logical - all errors are fatal, calling hydro_stop()\n! Input Files:\n!   Specified argument.\n! Output Files:\n! Condition codes:\n!   hydro_stop is called. .\n! User controllable options:\n! Notes:\n\nfunction get_netcdf_dim(file, dimName, callingRoutine, fatalErr)\nimplicit none\ninteger :: get_netcdf_dim  !! return value\ncharacter(len=*), intent(in)   :: file, dimName, callingRoutine\ninteger :: ncId, dimId, iRet\nlogical, optional, intent(in) :: fatalErr\nlogical :: fatalErr_local\ncharacter(len=256) :: errMsg\n\nfatalErr_local = .false.\nif(present(fatalErr)) fatalErr_local=fatalErr\n\nwrite(*,'(\"getting dimension from file: \", A)') trim(file)\niRet = nf90_open(trim(file), nf90_NOWRITE, ncId)\nif (iret /= nf90_noerr) then\n   write(*,'(\"Problem opening file: \", A)') trim(file)\n   if(fatalErr_local) call hydro_stop(trim(callingRoutine) // ': get_netcdf_dim')\n   if(.not. fatalErr_local) get_netcdf_dim = -99\n   if(.not. fatalErr_local) return\nendif\n\niRet = nf90_inq_dimid(ncId, trim(dimName), dimId)\nif (iret /= nf90_noerr) then\n   write(*,'(\"Problem getting the dimension ID \", A)') &\n        '\"' // trim(dimName) // '\" in file: ' // trim(file)\n   if(fatalErr_local) call hydro_stop(trim(callingRoutine) // ': get_netcdf_dim')\n   if(.not. fatalErr_local) get_netcdf_dim = -99\n   if(.not. fatalErr_local) return\nendif\n\niRet = nf90_inquire_dimension(ncId, dimId, len= get_netcdf_dim)\nif (iret /= nf90_noerr) then\n   write(*,'(\"Problem getting the dimension length of \", A)') &\n        '\"' // trim(dimName) // '\" in file: ' // trim(file)\n   if(fatalErr_local) call hydro_stop(trim(callingRoutine) // ': get_netcdf_dim')\n   if(.not. fatalErr_local) get_netcdf_dim = -99\n   if(.not. fatalErr_local) return\nendif\n\niRet = nf90_close(ncId)\nif (iret /= nf90_noerr) then\n   write(*,'(\"Problem closing file: \", A)') trim(file)\n   if(fatalErr_local) call hydro_stop(trim(callingRoutine) // ': get_netcdf_dim')\n   if(.not. fatalErr_local) get_netcdf_dim = -99\n   if(.not. fatalErr_local) return\nendif\nend function get_netcdf_dim\n\n\n! read the GWBUCKET Parm for NHDPlus\nsubroutine readBucket_nhd(infile, numbasns, gw_buck_coeff, gw_buck_exp, &\n                gw_buck_loss, z_max, z_init, LINKID, nhdBuckMask)\n    implicit none\n    integer, intent(in) :: numbasns\n    integer(kind=int64), dimension(numbasns) :: LINKID\n    real, dimension(numbasns) :: gw_buck_coeff, gw_buck_exp, gw_buck_loss\n    real, dimension(numbasns) :: z_max, z_init\n    integer, dimension(numbasns) :: nhdBuckMask\n    character(len=*), intent(in) :: infile\n!   define temp array\n    integer, volatile :: i,j,k, gnid, ncid, varid, ierr, dimid, iret\n    integer(kind=int64), allocatable, dimension(:) :: tmpLinkid\n    real, allocatable, dimension(:) :: tmpCoeff, tmpExp, tmpLoss\n    real, allocatable, dimension(:) :: tmpz_max, tmpz_init\n\n!   get gnid\n    gnid = 0\n#ifdef MPP_LAND\n    if(my_id .eq. io_id ) then\n#endif\n       iret = nf90_open(trim(infile), NF90_NOWRITE, ncid)\n#ifdef MPP_LAND\n       if(iret .ne. 0) then\n           call hydro_stop(\"Failed to open GWBUCKET Parameter file.\")\n       endif\n       iret = nf90_inq_dimid(ncid, \"BasinDim\", dimid)\n       if (iret /= 0) then\n               !print*, \"nf90_inq_dimid:  BasinDim\"\n               call hydro_stop(\"Failed read GBUCKETPARM - nf90_inq_dimid:  BasinDim\")\n       endif\n       iret = nf90_inquire_dimension(ncid, dimid, len=gnid)\n    endif\n    call mpp_land_bcast_int1(gnid)\n#endif\n    allocate(tmpLinkid(gnid))\n    allocate(tmpCoeff(gnid))\n    allocate(tmpExp(gnid))\n    allocate(tmpLoss(gnid))\n    allocate(tmpz_max(gnid))\n    allocate(tmpz_init(gnid))\n#ifdef MPP_LAND\n    if(my_id .eq. io_id ) then\n#endif\n!      read the file data.\n          iret = nf90_inq_varid(ncid,\"Coeff\",  varid)\n          if(iret /= 0) then\n               print * , \"could not find Coeff from \", infile\n               call hydro_stop(\"Failed to read BUCKETPARM\")\n          endif\n          iret = nf90_get_var(ncid, varid, tmpCoeff)\n\n          iret = nf90_inq_varid(ncid,\"Expon\",  varid)\n          if(iret /= 0) then\n               print * , \"could not find Expon from \", infile\n               call hydro_stop(\"Failed to read BUCKETPARM\")\n          endif\n          iret = nf90_get_var(ncid, varid, tmpExp)\n\n          if(nlst(did)%bucket_loss .eq. 1) then\n               iret = nf90_inq_varid(ncid,\"Loss\",  varid)\n               if(iret /= 0) then\n                    print * , \"could not find Loss from \", infile\n                    call hydro_stop(\"Failed to read BUCKETPARM\")\n               endif\n               iret = nf90_get_var(ncid, varid, tmpLoss)\n          endif\n\n          iret = nf90_inq_varid(ncid,\"Zmax\",  varid)\n          if(iret /= 0) then\n               print * , \"could not find Zmax from \", infile\n               call hydro_stop(\"Failed to read BUCKETPARM\")\n          endif\n          iret = nf90_get_var(ncid, varid, tmpz_max)\n\n          iret = nf90_inq_varid(ncid,\"Zinit\",  varid)\n          if(iret /= 0) then\n               print * , \"could not find Zinit from \", infile\n               call hydro_stop(\"Failed to read BUCKETPARM\")\n          endif\n          iret = nf90_get_var(ncid, varid, tmpz_init)\n\n          iret = nf90_inq_varid(ncid, \"ComID\",  varid)\n          if(iret /= 0) then\n               print * , \"could not find ComID from \", infile\n               call hydro_stop(\"Failed to read BUCKETPARM\")\n          endif\n          iret = nf90_get_var(ncid, varid, tmpLinkID)\n#ifdef MPP_LAND\n    endif\n       if(gnid .gt. 0) then\n          call mpp_land_bcast_real_1d(tmpCoeff)\n          call mpp_land_bcast_real_1d(tmpExp)\n          if(nlst(did)%bucket_loss .eq. 1) then\n             call mpp_land_bcast_real_1d(tmpLoss)\n          endif\n          call mpp_land_bcast_real_1d(tmpz_max)\n          call mpp_land_bcast_real_1d(tmpz_init)\n          call mpp_land_bcast_int8(gnid ,tmpLinkid)\n       endif\n#endif\n\n       nhdBuckMask = -999\n\n       ! The following loops are replaced by a hashtable-based algorithm\n       !   do k = 1, numbasns\n       !         do i = 1, gnid\n       !             if(LINKID(k) .eq. tmpLinkid(i)) then\n       !                gw_buck_coeff(k) = tmpCoeff(i)\n       !                gw_buck_exp(k) = tmpExp(i)\n       !                z_max(k) = tmpz_max(i)\n       !                z_init(k) = tmpz_init(i)\n       !                nhdBuckMask(k) = 1\n       !                goto 301\n       !             endif\n       !         end do\n       ! 301     continue\n       !     end do\n\n       block\n         type(hash_t) :: hash_table\n         integer(kind=int64) :: val,it\n         logical :: found\n\n         call hash_table%set_all_idx(LINKID,numbasns)\n         do it=1, gnid\n            call hash_table%get(tmpLinkid(it), val, found)\n            if((found .eqv. .true.)) then\n               if((nhdBuckMask(val) == -999)) then\n                  gw_buck_coeff(val) = tmpCoeff(it)\n                  gw_buck_exp(val) = tmpExp(it)\n                  if(nlst(did)%bucket_loss == 1) then\n                     gw_buck_loss(val) = tmpLoss(it)\n                  end if\n                  z_max(val) = tmpz_max(it)\n                  z_init(val) = tmpz_init(it)\n                  nhdBuckMask(val) = 1\n               end if\n            end if\n         end do\n         call hash_table%clear()\n       end block\n\n    if(allocated(tmpCoeff)) deallocate(tmpCoeff)\n    if(allocated(tmpExp)) deallocate(tmpExp)\n    if(allocated(tmpLoss)) deallocate(tmpLoss)\n    if(allocated(tmpz_max)) deallocate(tmpz_max)\n    if(allocated(tmpz_init)) deallocate(tmpz_init)\n    if(allocated(tmpLinkid)) deallocate(tmpLinkid)\nend subroutine readBucket_nhd\n\n!-- output the channel routine for fast output.\n!   subroutine mpp_output_chrt2(gnlinks,gnlinksl,map_l2g,igrid,                  &\n!        split_output_count, NLINKS, ORDER,                                     &\n!        startdate, date, chlon, chlat, hlink,zelev,qlink,dtrt_ch,              &\n!        K,STRMFRXSTPTS,order_to_write,NLINKSL,channel_option, gages, gageMiss, &\n!        lsmDt                                                                  &\n!        )\n\n#ifdef MPP_LAND\n   subroutine mpp_output_chrt2(                      &\n        gnlinks,   gnlinksl,           map_l2g,      &\n        igrid,     split_output_count,               &\n        NLINKS,    ORDER,                            &\n        startdate, date,                             &\n        chlon,     chlat,                            &\n        hlink,     zelev,                            &\n        qlink,     dtrt_ch,  K,                      &\n        NLINKSL,  channel_option,                    &\n        linkid                                       &\n#ifdef WRF_HYDRO_NUDGING\n        , nudge                                      &\n#endif\n        ,         QLateral,    io_config_outputs               &\n        ,                     velocity               &\n        ,  accSfcLatRunoff,  accBucket               &\n        ,    qSfcLatRunoff,    qBucket               &\n        ,   qBtmVertRunoff,   UDMP_OPT               &\n        )\n\n       USE module_mpp_land\n\n       implicit none\n\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid,K,NLINKSL\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLINKS\n     real, dimension(:),               intent(in) :: chlon,chlat\n     real, dimension(:),                  intent(in) :: hlink,zelev\n\n     integer, dimension(:),               intent(in) :: ORDER\n     integer(kind=int64), dimension(:),       intent(in) :: linkid\n\n     real,                                     intent(in) :: dtrt_ch\n     real, dimension(:,:),                intent(in) :: qlink\n#ifdef WRF_HYDRO_NUDGING\n     real, dimension(:),                  intent(in) :: nudge\n#endif\n     real, dimension(:), intent(in) :: QLateral, velocity\n     integer, intent(in) :: io_config_outputs\n     real*8, dimension(:), intent(in) :: accSfcLatRunoff, accBucket\n     real  , dimension(:), intent(in) ::   qSfcLatRunoff,   qBucket, qBtmVertRunoff\n     integer, intent(in) :: UDMP_OPT\n\n     integer :: channel_option\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n      integer  :: gnlinks, map_l2g(nlinks),  gnlinksl\n      real, allocatable,dimension(:) :: g_chlon,g_chlat, g_hlink,g_zelev\n#ifdef WRF_HYDRO_NUDGING\n      real, allocatable,dimension(:) :: g_nudge\n#endif\n      integer, allocatable,dimension(:) :: g_order\n      integer(kind=int64), allocatable, dimension(:) :: g_linkid\n      real,allocatable,dimension(:,:) :: g_qlink\n      integer  :: gsize\n      real*8, allocatable, dimension(:) :: g_accSfcLatRunoff, g_accBucket\n      real  , allocatable, dimension(:) ::    g_qSfcLatRunoff,  g_qBucket, g_qBtmVertRunoff\n      real, allocatable, dimension(:)   :: g_QLateral, g_velocity\n\n        gsize = gNLINKS\n        if(gnlinksl .gt. gsize) gsize = gnlinksl\n\n\n     if(my_id .eq. io_id ) then\n        allocate(g_chlon(gsize  ))\n        allocate(g_chlat(gsize  ))\n        allocate(g_hlink(gsize  ))\n        allocate(g_zelev(gsize  ))\n        allocate(g_qlink(gsize  ,2))\n#ifdef WRF_HYDRO_NUDGING\n        allocate(g_nudge(gsize))\n#endif\n        allocate(g_order(gsize  ))\n        allocate(g_linkid(gsize  ))\n\n        if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n           nlst(did)%output_channelBucket_influx .eq. 2      ) then\n           allocate(g_qSfcLatRunoff(  gsize  ))\n           allocate(g_qBucket(        gsize  ))\n        end if\n\n        if(nlst(did)%output_channelBucket_influx .eq. 2) &\n             allocate(g_qBtmVertRunoff(  gsize  ))\n\n        if(nlst(did)%output_channelBucket_influx .eq. 3) then\n           allocate(g_accSfcLatRunoff(gsize  ))\n           allocate(g_accBucket(      gsize  ))\n        end if\n\n        allocate(g_QLateral(gsize  ))\n        allocate(g_velocity(gsize  ))\n\n     else\n\n        if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n           nlst(did)%output_channelBucket_influx .eq. 2      ) then\n           allocate(g_qSfcLatRunoff(  1))\n           allocate(g_qBucket(        1))\n        end if\n\n        if(nlst(did)%output_channelBucket_influx .eq. 2) &\n             allocate(g_qBtmVertRunoff(  1))\n\n        if(nlst(did)%output_channelBucket_influx .eq. 3) then\n           allocate(g_accSfcLatRunoff(1))\n           allocate(g_accBucket(      1))\n        end if\n\n       allocate(g_QLateral(1))\n       allocate(g_velocity(1))\n\n        allocate(g_chlon(1))\n        allocate(g_chlat(1))\n        allocate(g_hlink(1))\n        allocate(g_zelev(1))\n        allocate(g_qlink(1,2))\n#ifdef WRF_HYDRO_NUDGING\n        allocate(g_nudge(1))\n#endif\n        allocate(g_order(1))\n        allocate(g_linkid(1))\n     endif\n\n     call mpp_land_sync()\n     if(channel_option .eq. 1 .or. channel_option .eq. 2) then\n        g_qlink = 0\n        call ReachLS_write_io(qlink(:,1), g_qlink(:,1))\n        call ReachLS_write_io(qlink(:,2), g_qlink(:,2))\n#ifdef WRF_HYDRO_NUDGING\n        g_nudge=0\n        call ReachLS_write_io(nudge,g_nudge)\n#endif\n        call ReachLS_write_io(order, g_order)\n        call ReachLS_write_io(linkid, g_linkid)\n        call ReachLS_write_io(chlon, g_chlon)\n        call ReachLS_write_io(chlat, g_chlat)\n        call ReachLS_write_io(zelev, g_zelev)\n\n        if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n           nlst(did)%output_channelBucket_influx .eq. 2      ) then\n           call ReachLS_write_io(qSfcLatRunoff, g_qSfcLatRunoff)\n           call ReachLS_write_io(qBucket,       g_qBucket)\n        end if\n\n        if(nlst(did)%output_channelBucket_influx .eq. 2) &\n             call ReachLS_write_io(qBtmVertRunoff, g_qBtmVertRunoff)\n\n        if(nlst(did)%output_channelBucket_influx .eq. 3) then\n           call ReachLS_write_io(accSfcLatRunoff, g_accSfcLatRunoff)\n           call ReachLS_write_io(accBucket,       g_accBucket)\n        end if\n\n\tcall ReachLS_write_io(QLateral, g_QLateral)\n\tcall ReachLS_write_io(velocity, g_velocity)\n       !yw call write_chanel_real(hlink,map_l2g,gnlinks,nlinks,g_hlink)\n       call  ReachLS_write_io(hlink,g_hlink)\n\n     else\n\n        call write_chanel_real(qlink(:,1),map_l2g,gnlinks,nlinks,g_qlink(:,1))\n        call write_chanel_real(qlink(:,2),map_l2g,gnlinks,nlinks,g_qlink(:,2))\n        call write_chanel_int(order,map_l2g,gnlinks,nlinks,g_order)\n        call write_chanel_int8(linkid,map_l2g,gnlinks,nlinks,g_linkid)\n        call write_chanel_real(chlon,map_l2g,gnlinks,nlinks,g_chlon)\n        call write_chanel_real(chlat,map_l2g,gnlinks,nlinks,g_chlat)\n        call write_chanel_real(zelev,map_l2g,gnlinks,nlinks,g_zelev)\n        call write_chanel_real(hlink,map_l2g,gnlinks,nlinks,g_hlink)\n     endif\n\n\n     if(my_id .eq. IO_id) then\n       call output_chrt2(igrid, split_output_count, GNLINKS, g_ORDER,                &\n          startdate, date, g_chlon, g_chlat, g_hlink,g_zelev,g_qlink,dtrt_ch,K,     &\n          gNLINKSL,channel_option, g_linkid  &\n#ifdef WRF_HYDRO_NUDGING\n          , g_nudge                                     &\n#endif\n          ,        g_QLateral,     io_config_outputs,      g_velocity  &\n          , g_accSfcLatRunoff, g_accBucket                   &\n          ,   g_qSfcLatRunoff,   g_qBucket, g_qBtmVertRunoff &\n          ,          UDMP_OPT                                &\n\t  )\n     end if\n\n     call mpp_land_sync()\n    if(allocated(g_order)) deallocate(g_order)\n    if(allocated(g_chlon)) deallocate(g_chlon)\n    if(allocated(g_chlat)) deallocate(g_chlat)\n    if(allocated(g_hlink)) deallocate(g_hlink)\n    if(allocated(g_zelev)) deallocate(g_zelev)\n    if(allocated(g_qlink)) deallocate(g_qlink)\n    if(allocated(g_linkid)) deallocate(g_linkid)\n\n#ifdef WRF_HYDRO_NUDGING\n    if(allocated(g_nudge)) deallocate(g_nudge)\n#endif\n\n    if(allocated(g_QLateral)) deallocate(g_QLateral)\n    if(allocated(g_velocity)) deallocate(g_velocity)\n\n    if(allocated(g_qSfcLatRunoff)) deallocate(g_qSfcLatRunoff)\n    if(allocated(g_qBucket)) deallocate(g_qBucket)\n    if(allocated(g_qBtmVertRunoff)) deallocate(g_qBtmVertRunoff)\n    if(allocated(g_accSfcLatRunoff)) deallocate(g_accSfcLatRunoff)\n    if(allocated(g_accBucket)) deallocate(g_accBucket)\n\nend subroutine mpp_output_chrt2\n\n#endif\n\n\n!subroutine output_chrt2\n!For realtime output only when CHRTOUT_GRID = 2.\n!   subroutine output_chrt2(igrid, split_output_count, NLINKS, ORDER,             &\n!        startdate, date, chlon, chlat, hlink, zelev, qlink, dtrt_ch, K,         &\n!        STRMFRXSTPTS, order_to_write, NLINKSL, channel_option, gages, gageMiss, &\n!        lsmDt                                                                   &\n!        )\n   subroutine output_chrt2(igrid, split_output_count, NLINKS, ORDER,             &\n        startdate, date, chlon, chlat, hlink, zelev, qlink, dtrt_ch, K,         &\n        NLINKSL, channel_option ,linkid &\n#ifdef WRF_HYDRO_NUDGING\n        , nudge                                     &\n#endif\n        ,        QLateral,   io_config_outputs,       velocity &\n        , accSfcLatRunoff, accBucket                 &\n        ,   qSfcLatRunoff,   qBucket, qBtmVertRunoff &\n        ,        UDMP_OPT                            &\n        )\n\n     implicit none\n!!output the routing variables over just channel\n     integer,                                  intent(in) :: igrid,K,channel_option\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: NLINKS, NLINKSL\n     real, dimension(:),                  intent(in) :: chlon,chlat\n     real, dimension(:),                  intent(in) :: hlink,zelev\n     integer, dimension(:),               intent(in) :: ORDER\n\n     real,                                     intent(in) :: dtrt_ch\n     real, dimension(:,:),                intent(in) :: qlink\n#ifdef WRF_HYDRO_NUDGING\n     real, dimension(:),                  intent(in) :: nudge\n#endif\n     real, dimension(:), intent(in) :: QLateral, velocity\n     integer, intent(in) :: io_config_outputs\n     real*8, dimension(nlinks), intent(in) :: accSfcLatRunoff, accBucket\n     real  , dimension(nlinks), intent(in) ::   qSfcLatRunoff,   qBucket, qBtmVertRunoff\n     integer  :: UDMP_OPT\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n\n\n     integer(kind=int64), allocatable, dimension(:) :: linkid\n\n     integer, allocatable, DIMENSION(:)         :: rec_num_of_station\n     integer, allocatable, DIMENSION(:)         :: rec_num_of_stationO\n\n     integer, allocatable, DIMENSION(:)         :: lOrder !- local stream order\n\n     integer, save  :: output_count\n     integer, save  :: ncid\n\n     integer :: stationdim, dimdata, varid, charid, n\n     integer :: timedim\n\n     integer :: iret,i !-- order_to_write is the lowest stream order to output\n     integer :: start_posO, prev_posO, nlk\n\n     integer :: previous_pos  !-- used for the station model\n     character(len=256) :: output_flnm\n     character(len=34)  :: sec_since_date\n     integer :: seconds_since,nstations,cnt,ObsStation\n     character(len=32)  :: convention\n     character(len=11),allocatable, DIMENSION(:)  :: stname\n\n     character(len=34) :: sec_valid_date\n\n    !--- all this for writing the station id string\n     INTEGER   TDIMS, TXLEN\n     PARAMETER (TDIMS=2)    ! number of TX dimensions\n     PARAMETER (TXLEN = 11) ! length of example string\n     INTEGER  TIMEID        ! record dimension id\n     INTEGER  TXID          ! variable ID\n     INTEGER  TXDIMS(TDIMS) ! variable shape\n     INTEGER  TSTART(TDIMS), TCOUNT(TDIMS)\n\n     !--  observation point  ids\n     INTEGER   OTDIMS, OTXLEN\n     PARAMETER (OTDIMS=2)    ! number of TX dimensions\n     PARAMETER (OTXLEN = 15) ! length of example string\n     INTEGER  OTIMEID        ! record dimension id\n     INTEGER  OTXID          ! variable ID\n     INTEGER  OTXDIMS(OTDIMS) ! variable shape\n     INTEGER  OTSTART(OTDIMS), OTCOUNT(OTDIMS)\n     character(len=19)  :: date19, date19start\n\n\n     seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n\n\n     if(channel_option .ne. 3) then\n        nstations = NLINKSL\n     else\n        nstations = NLINKS\n     endif\n\n       if(split_output_count .ne. 1 ) then\n            write(6,*) \"WARNING: split_output_count need to be 1 for this output option.\"\n       endif\n!-- have moved sec_since_date from above here..\n        sec_since_date = 'seconds since '//startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10) &\n                  //' '//startdate(12:13)//':'//startdate(15:16)//' UTC'\n\n        date19start(1:len_trim(startdate)) = startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10)//'_' &\n                  //startdate(12:13)//':'//startdate(15:16)//':00'\n\n        seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n        sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                      //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n        write(output_flnm, '(A12,\".CHRTOUT_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n\n#ifdef HYDRO_D\n        print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n       iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n       if (iret /= 0) then\n           print*,  \"Problem nf90_create points\"\n           call hydro_stop(\"In output_chrt2() - Problem nf90_create points.\")\n       endif\n\n       iret = nf90_def_dim(ncid, \"station\", nstations, stationdim)\n       iret = nf90_def_dim(ncid, \"time\", 1, timedim)\n\nif (io_config_outputs .le. 0) then\n      !- station location definition all,  lat\n        iret = nf90_def_var(ncid, \"latitude\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station latitude')\n        iret = nf90_put_att(ncid, varid, 'units', 'degrees_north')\n\n      !- station location definition,  long\n        iret = nf90_def_var(ncid, \"longitude\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station longitude')\n        iret = nf90_put_att(ncid, varid, 'units', 'degrees_east')\n\n!     !-- elevation is ZELEV\n        iret = nf90_def_var(ncid, \"altitude\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station altitude')\n        iret = nf90_put_att(ncid, varid, 'units', 'meters')\n\n!-- parent index\n!        iret = nf90_def_var(ncid, \"parent_index\", NF90_INT, (/stationdim/), varid)\n!        iret = nf90_put_att(ncid, varid, 'long_name', 'index of the station for this record')\n\n\n     !-- prevChild\n!        iret = nf90_def_var(ncid, \"prevChild\", NF90_INT, (/stationdim/), varid)\n!        iret = nf90_put_att(ncid, varid, 'long_name', 'record number of the previous record for the same station')\n!        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\n\n     !-- lastChild\n!        iret = nf90_def_var(ncid, \"lastChild\", NF90_INT, (/stationdim/), varid)\n!        iret = nf90_put_att(ncid, varid, 'long_name', 'latest report for this station')\n!        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\nendif\n\n        iret = nf90_def_var(ncid, \"time\", NF90_INT, (/timedim/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'valid output time')\n\n        !- flow definition, var\n        iret = nf90_def_var(ncid, \"streamflow\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'River Flow')\n\n#ifdef WRF_HYDRO_NUDGING\n        !- nudge definition\n        iret = nf90_def_var(ncid, \"nudge\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Amount of stream flow alteration')\n#endif\n\n\n!     !- head definition, var\n      if(channel_option .eq. 3) then\n        iret = nf90_def_var(ncid, \"head\", NF90_FLOAT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'units', 'meter')\n        iret = nf90_put_att(ncid, varid, 'long_name', 'River Stage')\n      endif\n!#ifdef HYDRO_REALTIME\n!      if ( (channel_option .ne. 3) .and. (io_config_outputs .ge. 0) ) then\n!\tiret = nf90_def_var(ncid, \"head\", NF90_FLOAT, (/stationdim/), varid)\n!        iret = nf90_put_att(ncid, varid, 'units', 'meter')\n!        iret = nf90_put_att(ncid, varid, 'long_name', 'River Stage')\n!      endif\n!#endif\n\n\n\t!-- NEW lateral inflow definition, var\n\tif ( (channel_option .ne. 3) .and. (io_config_outputs .ge. 0) ) then\n\t        iret = nf90_def_var(ncid, \"q_lateral\", NF90_FLOAT, (/stationdim/), varid)\n       \t\tiret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n                iret = nf90_put_att(ncid, varid, 'long_name', 'Runoff into channel reach')\n\tendif\n\n        !-- NEW velocity definition, var\n        if ( (channel_option .ne. 3) .and. (io_config_outputs .ge. 0) .and. (io_config_outputs .ne. 4) ) then\n        \tiret = nf90_def_var(ncid, \"velocity\", NF90_FLOAT, (/stationdim/), varid)\n        \tiret = nf90_put_att(ncid, varid, 'units', 'meter/sec')\n        \tiret = nf90_put_att(ncid, varid, 'long_name', 'River Velocity')\n\tendif\n\nif (io_config_outputs .le. 0) then\n!     !- order definition, var\n        iret = nf90_def_var(ncid, \"order\", NF90_INT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Strahler Stream Order')\n        iret = nf90_put_att(ncid, varid, '_FillValue', -1)\nendif\n\n     !-- station  id\n     ! define character-position dimension for strings of max length 11\n        iret = nf90_def_var(ncid, \"station_id\", NF90_INT, (/stationdim/), varid)\n        iret = nf90_put_att(ncid, varid, 'long_name', 'Station id')\n\n       !! JLM: Write/define a global attribute of the file as the LSM timestep. Enforce\n       !! JLM: force_type=9 only reads these discharges to the channel if the LSM timesteps match.\n\n        if(UDMP_OPT .eq. 1 .and. nlst(did)%output_channelBucket_influx .ne. 0) then\n           !! channel & channelBucketOnly global atts\n           iret = nf90_put_att(ncid, NF90_GLOBAL, 'OVRTSWCRT', nlst(1)%OVRTSWCRT )\n           iret = nf90_put_att(ncid, NF90_GLOBAL, 'NOAH_TIMESTEP', int(nlst(1)%dt) )\n           iret = nf90_put_att(ncid, NF90_GLOBAL, \"channel_only\", nlst(did)%channel_only )\n           iret = nf90_put_att(ncid, NF90_GLOBAL, \"channelBucket_only\", nlst(did)%channelBucket_only )\n\n           !! FLUXES to channel\n           if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n              nlst(did)%output_channelBucket_influx .eq. 2      ) then\n              iret = nf90_def_var(ncid, \"qSfcLatRunoff\", NF90_FLOAT, (/stationdim/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              if(nlst(did)%OVRTSWCRT .eq. 1) then              !123456789112345678921234567\n                 iret = nf90_put_att(ncid, varid, 'long_name', 'runoff from terrain routing')\n              else\n                 iret = nf90_put_att(ncid, varid, 'long_name', 'runoff')\n              end if\n              iret = nf90_def_var(ncid, \"qBucket\", NF90_FLOAT, (/stationdim/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              !                                                 1234567891234567892\n              iret = nf90_put_att(ncid, varid, 'long_name', 'flux from gw bucket')\n           end if\n\n           !! Bucket influx\n           !! In channel_only mode, there are not valie qBtmVertRunoff values\n           if(nlst(did)%output_channelBucket_influx .eq. 2 .and. &\n              nlst(did)%channel_only                .eq. 0         ) then\n              iret = nf90_def_var(ncid, \"qBtmVertRunoff\", NF90_FLOAT, (/stationdim/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3/s')\n              iret = nf90_put_att(ncid, varid, 'long_name', 'runoff from bottom of soil to bucket')\n           endif\n\n           !! ACCUMULATIONS\n           if(nlst(did)%output_channelBucket_influx .eq. 3) then\n              iret = nf90_def_var(ncid, \"accSfcLatRunoff\", NF90_DOUBLE, (/stationdim/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3')\n              if(nlst(did)%OVRTSWCRT .eq. 1) then\n                 iret = nf90_put_att(ncid,varid,'long_name',&\n                                        'ACCUMULATED runoff from terrain routing')\n              else\n                 iret = nf90_put_att(ncid, varid, 'long_name', 'ACCUMULATED runoff from land')\n              end if\n\n              iret = nf90_def_var(ncid, \"accBucket\", NF90_DOUBLE, (/stationdim/), varid)\n              iret = nf90_put_att(ncid, varid, 'units', 'meter^3')\n              iret = nf90_put_att(ncid, varid, 'long_name', 'ACCUMULATED flux from gw bucket')\n           endif\n        endif\n\n         convention(1:32) = \"Unidata Observation Dataset v1.0\"\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"Conventions\", convention)\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"cdm_datatype\", \"Station\")\n\nif (io_config_outputs .le. 0) then\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_max\", \"90.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lat_min\", \"-90.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_max\", \"180.0\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"geospatial_lon_min\", \"-180.0\")\nendif\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"station_dimension\", \"station\")\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n         iret = nf90_put_att(ncid, NF90_GLOBAL, \"stream_order_output\", 1)\n\n        !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n        !! END DEF\n         iret = nf90_enddef(ncid)\n\n         iret = nf90_inq_varid(ncid,\"time\", varid)\n         iret = nf90_put_var(ncid, varid, seconds_since, (/1/))\n\nif (io_config_outputs .le. 0) then\n        !-- write latitudes\n         iret = nf90_inq_varid(ncid,\"latitude\", varid)\n         iret = nf90_put_var(ncid, varid, chlat, (/1/), (/nstations/))\n\n        !-- write longitudes\n         iret = nf90_inq_varid(ncid,\"longitude\", varid)\n         iret = nf90_put_var(ncid, varid, chlon, (/1/), (/nstations/))\n\n        !-- write elevations\n         iret = nf90_inq_varid(ncid,\"altitude\", varid)\n         iret = nf90_put_var(ncid, varid, zelev, (/1/), (/nstations/))\n\n        !-- write order\n         iret = nf90_inq_varid(ncid,\"order\", varid)\n         iret = nf90_put_var(ncid, varid, ORDER, (/1/), (/nstations/))\nendif\n\n        !-- write stream flow\n         iret = nf90_inq_varid(ncid,\"streamflow\", varid)\n         iret = nf90_put_var(ncid, varid, qlink(:,1), (/1/), (/nstations/))\n\n#ifdef WRF_HYDRO_NUDGING\n        !-- write nudge\n         iret = nf90_inq_varid(ncid,\"nudge\", varid)\n         iret = nf90_put_var(ncid, varid, nudge, (/1/), (/nstations/))\n#endif\n\n\t!-- write head\n     \tif(channel_option .eq. 3) then\n           iret = nf90_inq_varid(ncid,\"head\", varid)\n           iret = nf90_put_var(ncid, varid, hlink, (/1/), (/nstations/))\n\tendif\n!#ifdef HYDRO_REALTIME\n!\tif ( (channel_option .ne. 3) .and. (io_config_outputs .ge. 0) ) then\n!\t      ! dummy value for now\n!              iret = nf90_inq_varid(ncid,\"head\", varid)\n!              iret = nf90_put_vara_real(ncid, varid, (/1/), (/nstations/), chlon*0.-9999.)\n!        endif\n!#endif\n\n        !-- write lateral inflow\n\tif ( (channel_option .ne. 3) .and. (io_config_outputs .ge. 0) ) then\n\t        iret = nf90_inq_varid(ncid,\"q_lateral\", varid)\n       \t\tiret = nf90_put_var(ncid, varid, QLateral, (/1/), (/nstations/))\n        endif\n\n        !-- writelvelocity (dummy value for now)\n        if ( (channel_option .ne. 3) .and. (io_config_outputs .ge. 0) .and. (io_config_outputs .ne. 4) ) then\n        \tiret = nf90_inq_varid(ncid,\"velocity\", varid)\n         \tiret = nf90_put_var(ncid, varid, velocity, (/1/), (/nstations/))\n\tendif\n\n       !! JLM: Write/define a global attribute of the file as the LSM timestep. Enforce\n       !! JLM:   force_type=9 only reads these discharges to the channel if the LSM timesteps match.\n       if(UDMP_OPT .eq. 1 .and. nlst(did)%output_channelBucket_influx .ne. 0) then\n             !! FLUXES\n             if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n                nlst(did)%output_channelBucket_influx .eq. 2      ) then\n                iret = nf90_inq_varid(ncid,\"qSfcLatRunoff\", varid)\n                iret = nf90_put_var(ncid, varid, qSfcLatRunoff, (/1/), (/nstations/))\n\n                iret = nf90_inq_varid(ncid,\"qBucket\", varid)\n                iret = nf90_put_var(ncid, varid, qBucket, (/1/), (/nstations/))\n             end if\n\n             !! Bucket model influxes\n             if(nlst(did)%output_channelBucket_influx .eq. 2 .and. &\n                nlst(did)%channel_only                .eq. 0         ) then\n                iret = nf90_inq_varid(ncid,\"qBtmVertRunoff\", varid)\n                iret = nf90_put_var(ncid, varid, qBtmVertRunoff, (/1/), (/nstations/))\n             endif\n\n            !! ACCUMULATIONS\n            if(nlst(did)%output_channelBucket_influx .eq. 3) then\n               iret = nf90_inq_varid(ncid,\"accSfcLatRunoff\", varid)\n               iret = nf90_put_var(ncid, varid, accSfcLatRunoff, (/1/), (/nstations/))\n\n               iret = nf90_inq_varid(ncid,\"accBucket\", varid)\n               iret = nf90_put_var(ncid, varid, accBucket, (/1/), (/nstations/))\n            end if\n         endif\n\n\t!-- write id\n        iret = nf90_inq_varid(ncid,\"station_id\", varid)\n        iret = nf90_put_var(ncid, varid, linkid, (/1/), (/nstations/))\n\n\n      iret = nf90_redef(ncid)\n      date19(1:19) = \"0000-00-00_00:00:00\"\n      date19(1:len_trim(date)) = date\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n      iret = nf90_enddef(ncid)\n\n      iret = nf90_sync(ncid)\n      iret = nf90_close(ncid)\n\n#ifdef HYDRO_D\n     print *, \"Exited Subroutine output_chrt\"\n#endif\n\n\nend subroutine output_chrt2\n\n\n   subroutine output_GW_Diag(did)\n       implicit none\n       integer :: i , did, gnbasns\n\n#ifdef MPP_LAND\n       real, allocatable, dimension(:) :: g_qin_gwsubbas, g_qout_gwsubbas, g_z_gwsubbas\n       integer(kind=int64), allocatable, dimension(:) :: g_basnsInd\n       if(my_id .eq. io_id) then\n          if(nlst(did)%GWBASESWCRT.EQ.1 .OR. nlst(did)%GWBASESWCRT.GE.4) then\n               allocate(g_qin_gwsubbas(rt_domain(did)%gnumbasns))\n               allocate(g_qout_gwsubbas(rt_domain(did)%gnumbasns))\n               allocate(g_z_gwsubbas(rt_domain(did)%gnumbasns))\n               allocate(g_basnsInd(rt_domain(did)%gnumbasns))\n               gnbasns = rt_domain(did)%gnumbasns\n          else\n               allocate(g_qin_gwsubbas(rt_domain(did)%gnlinksl))\n               allocate(g_qout_gwsubbas(rt_domain(did)%gnlinksl))\n               allocate(g_z_gwsubbas(rt_domain(did)%gnlinksl))\n               allocate(g_basnsInd(rt_domain(did)%gnlinksl))\n               gnbasns = rt_domain(did)%gnlinksl\n          endif\n       endif\n\n       if(nlst(did)%channel_option .ne. 3) then\n          call ReachLS_write_io(rt_domain(did)%qin_gwsubbas,g_qin_gwsubbas)\n          call ReachLS_write_io(rt_domain(did)%qout_gwsubbas,g_qout_gwsubbas)\n          call ReachLS_write_io(rt_domain(did)%z_gwsubbas,g_z_gwsubbas)\n          call ReachLS_write_io(rt_domain(did)%linkid,g_basnsInd)\n       else\n          call gw_write_io_real(rt_domain(did)%numbasns,rt_domain(did)%qin_gwsubbas,  &\n                 rt_domain(did)%basnsInd,g_qin_gwsubbas)\n          call gw_write_io_real(rt_domain(did)%numbasns,rt_domain(did)%qout_gwsubbas,  &\n                 rt_domain(did)%basnsInd,g_qout_gwsubbas)\n          call gw_write_io_real(rt_domain(did)%numbasns,rt_domain(did)%z_gwsubbas,  &\n                 rt_domain(did)%basnsInd,g_z_gwsubbas)\n          call gw_write_io_int(rt_domain(did)%numbasns,rt_domain(did)%basnsInd,  &\n                 rt_domain(did)%basnsInd,g_basnsInd)\n       endif\n       if(my_id .eq. io_id) then\n!          open (unit=51,file='GW_inflow.txt',form='formatted',&\n!                status='unknown',position='append')\n!          open (unit=52,file='GW_outflow.txt',form='formatted',&\n!                status='unknown',position='append')\n!          open (unit=53,file='GW_zlev.txt',form='formatted',&\n!                status='unknown',position='append')\n!          do i=1,RT_DOMAIN(did)%gnumbasns\n!             write (51,951) i,nlst_rt(did)%olddate,g_qin_gwsubbas(i)\n951        FORMAT(I3,1X,A19,1X,F11.3)\n!            write (52,951) i,nlst_rt(did)%olddate,g_qout_gwsubbas(i)\n!            write (53,951) i,nlst_rt(did)%olddate,g_z_gwsubbas(i)\n!         end do\n!         close(51)\n!         close(52)\n!         close(53)\n\n          call   output_gw_netcdf( nlst(did)%igrid, nlst(did)%split_output_count, gnbasns, &\n                  trim(nlst(did)%sincedate), trim(nlst(did)%olddate), &\n                  g_basnsInd,g_qin_gwsubbas, g_qout_gwsubbas, g_z_gwsubbas )\n          deallocate(g_qin_gwsubbas, g_qout_gwsubbas, g_z_gwsubbas, g_basnsInd)\n\n       endif\n          if(allocated(g_qin_gwsubbas))  deallocate(g_qin_gwsubbas)\n          if(allocated(g_qout_gwsubbas))  deallocate(g_qout_gwsubbas)\n          if(allocated(g_z_gwsubbas))  deallocate(g_z_gwsubbas)\n\n# else\n!       open (unit=51,file='GW_inflow.txt',form='formatted',&\n!             status='unknown',position='append')\n!       open (unit=52,file='GW_outflow.txt',form='formatted',&\n!             status='unknown',position='append')\n!       open (unit=53,file='GW_zlev.txt',form='formatted',&\n!             status='unknown',position='append')\n!       do i=1,RT_DOMAIN(did)%numbasns\n!          write (51,951) i,nlst_rt(did)%olddate,rt_domain(did)%qin_gwsubbas(i)\n951        FORMAT(I3,1X,A19,1X,F11.3)\n!          write (52,951) i,nlst_rt(did)%olddate,rt_domain(did)%qout_gwsubbas(i)\n!          write (53,951) i,nlst_rt(did)%olddate,rt_domain(did)%z_gwsubbas(i)\n!       end do\n!       close(51)\n!       close(52)\n!       close(53)\n        if(nlst(did)%GWBASESWCRT.EQ.1 .OR. nlst(did)%GWBASESWCRT.GE.4) then\n          call   output_gw_netcdf( nlst(did)%igrid, nlst(did)%split_output_count, RT_DOMAIN(did)%numbasns, &\n                  trim(nlst(did)%sincedate), trim(nlst(did)%olddate), &\n                  rt_domain(did)%basnsInd,rt_domain(did)%qin_gwsubbas, &\n                  rt_domain(did)%qout_gwsubbas, rt_domain(did)%z_gwsubbas  )\n        else\n          call   output_gw_netcdf( nlst(did)%igrid, nlst(did)%split_output_count, RT_DOMAIN(did)%nlinksl, &\n                  trim(nlst(did)%sincedate), trim(nlst(did)%olddate), &\n                  rt_domain(did)%linkid,rt_domain(did)%qin_gwsubbas, &\n                  rt_domain(did)%qout_gwsubbas, rt_domain(did)%z_gwsubbas  )\n        endif\n#endif\n    end subroutine output_GW_Diag\n\n\n!----------------------------------- gw netcdf output\n\n   subroutine output_gw_netcdf(igrid, split_output_count, nbasns, &\n        startdate, date, &\n        gw_id_var, gw_in_var, gw_out_var, gw_z_var)\n\n     integer,                                  intent(in) :: igrid\n     integer,                                  intent(in) :: split_output_count\n     integer,                                  intent(in) :: nbasns\n     real, dimension(:),                  intent(in) :: gw_in_var, gw_out_var, gw_z_var\n     integer(kind=int64), dimension(:),               intent(in) :: gw_id_var\n\n     character(len=*),                         intent(in) :: startdate\n     character(len=*),                         intent(in) :: date\n\n\n     integer, save  :: output_count\n     integer, save :: ncid\n\n     integer :: basindim, varid,  n, nstations\n     integer :: iret,i    !--\n     character(len=256) :: output_flnm\n     character(len=19)  :: date19, date19start\n     character(len=32)  :: convention\n     integer :: timedim\n     integer :: seconds_since\n     character(len=34)  :: sec_since_date\n     character(len=34)  :: sec_valid_date\n\n     if(split_output_count .ne. 1 ) then\n            write(6,*) \"WARNING: split_output_count need to be 1 for this output option.\"\n     endif\n\n     sec_since_date = 'seconds since '//startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10) &\n                  //' '//startdate(12:13)//':'//startdate(15:16)//' UTC'\n\n     date19start(1:len_trim(startdate)) = startdate(1:4)//'-'//startdate(6:7)//'-'//startdate(9:10)//'_' &\n                  //startdate(12:13)//':'//startdate(15:16)//':00'\n\n     seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n\n     sec_valid_date = 'seconds since '//nlst(1)%startdate(1:4)//'-'//nlst(1)%startdate(6:7)//'-'//nlst(1)%startdate(9:10) &\n                      //' '//nlst(1)%startdate(12:13)//':'//nlst(1)%startdate(15:16)//' UTC'\n\n     write(output_flnm, '(A12,\".GWOUT_DOMAIN\",I1)') date(1:4)//date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n\n#ifdef HYDRO_D\n      print*, 'output_flnm = \"'//trim(output_flnm)//'\"'\n#endif\n\n      iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n\n      if (iret /= 0) then\n          print*, \"Problem nf90_create\"\n          call hydro_stop(\"output_gw_netcdf\")\n      endif\n\n!!! Define dimensions\n\n        nstations =nbasns\n\n      iret = nf90_def_dim(ncid, \"basin\", nstations, basindim)\n\n      iret = nf90_def_dim(ncid, \"time\", 1, timedim)\n\n!!! Define variables\n\n\n      !- gw basin ID\n      iret = nf90_def_var(ncid, \"gwbas_id\", NF90_INT, (/basindim/), varid)\n      iret = nf90_put_att(ncid, varid, 'long_name', 'GW basin ID')\n\n      !- gw inflow\n      iret = nf90_def_var(ncid, \"gw_inflow\", NF90_FLOAT, (/basindim/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n\n      !- gw outflow\n      iret = nf90_def_var(ncid, \"gw_outflow\", NF90_FLOAT, (/basindim/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'meter^3 / sec')\n\n      !- depth in gw bucket\n      iret = nf90_def_var(ncid, \"gw_zlev\", NF90_FLOAT, (/basindim/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', 'mm')\n\n      ! Time variable\n      iret = nf90_def_var(ncid, \"time\", NF90_INT, (/timeDim/), varid)\n      iret = nf90_put_att(ncid, varid, 'units', sec_valid_date)\n      iret = nf90_put_att(ncid, varid, 'long_name', 'valid output time')\n\n      date19(1:19) = \"0000-00-00_00:00:00\"\n      date19(1:len_trim(startdate)) = startdate\n\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_initialization_time\", trim(nlst(1)%startdate))\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"model_output_valid_time\", trim(nlst(1)%olddate))\n      iret = nf90_put_att(ncid, NF90_GLOBAL, \"missing_value\", -9E15)\n\n      iret = nf90_enddef(ncid)\n\n!!! Input variables\n\n        !-- write lake id\n        iret = nf90_inq_varid(ncid,\"gwbas_id\", varid)\n        iret = nf90_put_var(ncid, varid, gw_id_var, (/1/), (/nstations/))\n\n        !-- write gw inflow\n        iret = nf90_inq_varid(ncid,\"gw_inflow\", varid)\n        iret = nf90_put_var(ncid, varid, gw_in_var, (/1/), (/nstations/))\n\n        !-- write elevation  of inflow\n        iret = nf90_inq_varid(ncid,\"gw_outflow\", varid)\n        iret = nf90_put_var(ncid, varid, gw_out_var, (/1/), (/nstations/))\n\n        !-- write elevation  of inflow\n        iret = nf90_inq_varid(ncid,\"gw_zlev\", varid)\n        iret = nf90_put_var(ncid, varid, gw_z_var, (/1/), (/nstations/))\n\n        !-- write time variable\n        iret = nf90_inq_varid(ncid,\"time\", varid)\n        iret = nf90_put_var(ncid, varid, seconds_since, (/1/))\n\n        iret = nf90_close(ncid)\n\n    end subroutine output_gw_netcdf\n\n!------------------------------- end gw netcdf output\n\n    subroutine read_NSIMLAKES(NLAKES,route_lake_f)\n        integer                     :: NLAKES\n        CHARACTER(len=*  )          :: route_lake_f\n\n        character(len=256)          :: route_lake_f_r\n        integer                     :: lenRouteLakeFR, iRet, ncid, dimId\n        logical                     :: routeLakeNetcdf\n\n      !! is RouteLake file netcdf (*.nc) or  from the LAKEPARM.TBL ascii\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n      route_lake_f_r = adjustr(route_lake_f)\n      lenRouteLakeFR = len(route_Lake_f_r)\n      routeLakeNetcdf = route_lake_f_r( (lenRouteLakeFR-2):lenRouteLakeFR) .eq. '.nc'\n\n\n      write(6,'(\"getting NLAKES from: ''\", A, \"''\")') trim(route_lake_f)\n      write(6,*) \"routeLakeNetcdf TF Name Len\",routeLakeNetcdf, route_lake_f,lenRouteLakeFR\n      call flush(6)\n\n       if(routeLakeNetcdf) then\n          write(6,'(\"getting NLAKES from: ''\", A, \"''\")') trim(route_lake_f)\n          NLAKES = -99\n          NLAKES = get_netcdf_dim(trim(route_lake_f), 'feature_id',  &\n                                   'read_NSIMLAKES', fatalErr=.false.)\n          if (NLAKES .eq. -99) then\n                 ! We were unsucessful in getting feature_id, try linkDim\n                 NLAKES = get_netcdf_dim(trim(route_lake_f), 'nlakes',  &\n                                   'read_NSIMLAKES', fatalErr=.false.)\n          endif\n          if (NLAKES .eq. -99) then\n                 ! Neither the feature_id nor nlakes dimensions were found in\n                 ! the LAKEPARM file. Throw an error...\n                 call hydro_stop(\"Could not find either feature_id or nlakes in LAKEPARM netcdf file.\")\n          endif\n       else\n!yw for IOC reach based routing, if netcdf lake file is not set from the hydro.namelist,\n!    we will assume that no lake will be assimilated.\n          write(6,*) \"Lakes have been disabled -- NLAKES will be set to zero.\"\n          NLAKES = 0\n      endif\n#ifdef MPP_LAND\n    endif ! end if block of my_id .eq. io_id\n         call mpp_land_bcast_int1(NLAKES)\n#endif\n\n    end subroutine read_NSIMLAKES\n\n! sequential code: not used.!!!!!!\n    subroutine nhdLakeMap(NLAKES, NLINKSL, TYPEL, LAKELINKID, LAKEIDX, gTO_NODE,LINKID, LAKEIDM, LAKEIDA)\n        !--- get the lake configuration here.\n        implicit none\n        integer, dimension(:),         intent(inout) :: TYPEL, LAKEIDX\n        integer(kind=int64), dimension(:), intent(inout) :: LINKID, LAKEIDA, LAKELINKID, LAKEIDM, gTO_NODE\n        integer, intent(in) :: NLAKES, NLINKSL\n        integer, dimension(NLINKSL) :: OUTLAKEID\n        integer :: i,j,k, kk\n\n        TYPEL = -999\n\n!! find the links that flow into lakes (e.g. TYPEL = 3), and update the TO_NODE, so that links flow into the lake reach\n#ifdef MPP_LAND\n     call nhdLakeMap_scan(NLAKES, NLINKSL, LAKELINKID, gTO_NODE,LINKID, LAKEIDM, LAKEIDA,NLINKSL)\n#endif\n\n        OUTLAKEID = gTO_NODE\n        DO i = 1, NLAKES\n          DO j = 1, NLINKSL\n            DO k = 1, NLINKSL\n\n              if( (gTO_NODE(j) .eq. LINKID(k) ) .and. &\n                  (LAKEIDA(k) .lt. 0 .and. LAKEIDA(j) .eq. LAKEIDM(i))) then\n                  TYPEL(j) = 1  !this is the link flowing out of the lake\n                  OUTLAKEID(j) = LAKEIDA(j) ! LINKID(j)\n                  LAKELINKID(i) = j\n!                    write(61,*) gTO_NODE(j),LAKEIDA(j),LAKEIDA(k),LAKELINKID(i) , j\n!                    call flush(61)\n              elseif( (gTO_NODE(j) .eq. LINKID(k)) .and. &\n                  (LAKEIDA(j) .lt. 0 .and. LAKEIDA(k) .gt. 0) .and. &\n                  (LAKEIDA(k) .eq. LAKEIDM(i)) ) then\n                  TYPEL(j) = 3 !type_3 inflow link to lake\n                  OUTLAKEID(j) = LAKEIDM(i)\n              elseif (LAKEIDA(j) .eq. LAKEIDM(i) .and. .not. TYPEL(j) .eq. 1) then\n                  TYPEL(j) = 2 ! internal lake linkd\n              endif\n            END DO\n          END DO\n       END DO\n\n       DO i = 1, NLAKES\n            if(LAKELINKID(i) .gt. 0) then\n                LAKEIDX(LAKELINKID(i)) = i\n            endif\n       ENDDO\n\n ! assign the the inflow nodes to the lank with a new TO_NODE id, which is the outflow link\n       DO i = 1, NLINKSL\n        DO j = 1, NLINKSL\n            if(TYPEL(i) .eq. 3 .and. TYPEL(j) .eq. 1 .and. (OUTLAKEID(j) .eq. OUTLAKEID(i))) then\n              gTO_NODE(i) = LINKID(j)  !   OUTLAKEID(i)\n            endif\n        ENDDO\n       ENDDO\n\n!     do k = 1, NLINKSL\n!         write(60+my_id,*) \"k, typel, lakeidx\", k, typel(k), lakeidx(k)\n!         call flush(60+my_id)\n!     end do\n\n!     DO i = 1, NLINKSL\n!        write(61,*) i,LAKEIDX(i), TYPEL(i)\n!     end do\n!     DO i = 1, NLAKES\n!        write(62,*) i,LAKELINKID(i)\n!        write(63,*) i,LAKEIDM(i)\n!     end do\n!     close(61)\n!     close(62)\n!     close(63)\n!     call hydro_finish()\n\n!   write(60,*) TYPEL\n!   write(63,*) LAKELINKID, LAKEIDX\n!   write(64,*) gTO_NODE\n!   write(61,*) LINKID\n!   write(62,*) LAKEIDM, LAKEIDA\n!   close(60)\n!   close(61)\n!   close(62)\n!   close(63)\n!   close(64)\n!   call hydro_finish()\n\n\n    end subroutine nhdLakeMap\n\n#ifdef MPP_LAND\n    subroutine nhdLakeMap_mpp(NLAKES, NLINKSL, TYPEL, LAKELINKID, LAKEIDX, TO_NODE,LINKID, LAKEIDM, LAKEIDA,GNLINKSL)\n        !--- get the lake configuration here.\n        implicit none\n        integer, dimension(:),           intent(out)   :: TYPEL\n        integer, dimension(:),   intent(out)   :: LAKEIDX\n        integer(kind=int64), dimension(:),   intent(inout) :: TO_NODE\n        integer(kind=int64), dimension(:),   intent(out)   :: LAKELINKID\n        integer(kind=int64), dimension(:),   intent(in)    :: LINKID, LAKEIDA\n        integer(kind=int64), dimension(:),   intent(inout) :: LAKEIDM\n        integer, intent(in) :: NLAKES, NLINKSL ,GNLINKSL\n!yw        integer, dimension(NLINKSL) :: OUTLAKEID\n        integer(kind=int64), allocatable, dimension(:) :: OUTLAKEID\n        integer :: i,size2 ,j,k, kk, num, maxNum, m, mm, tmpSize\n        integer, allocatable, dimension(:) :: tmpTYPEL, ind, gLAKEIDX\n        integer(kind=int64), allocatable, dimension(:) :: gLINKID, tmpLINKID, tmplakeida, tmpoutlakeid, gLAKEIDA\n        integer(kind=int64), allocatable, dimension(:,:) :: gtonodeout\n\n        integer, allocatable, dimension(:) ::  gTYPEL\n        integer(kind=int64), allocatable, dimension(:) ::  tmpLAKELINKID, gOUTLAKEID, tmpTO_NODE, gto\n\n      integer(kind=int64) tmpBuf(GNLINKSL)\n\n      tmpSize = size(TO_NODE,1)\n      allocate(OUTLAKEID(tmpSize))\n\n      allocate (gto(GNLINKSL))\n\n      if(my_id .eq. io_id) then\n         allocate (tmpLAKELINKID(nlakes) )\n      else\n         allocate (tmpLAKELINKID(1))\n      endif\n\n\n!     prescan the data and remove the LAKEIDM which point to two links.\n#ifdef MPP_LAND\n     call nhdLakeMap_scan(NLAKES, NLINKSL, LAKELINKID, TO_NODE,LINKID, LAKEIDM, LAKEIDA,GNLINKSL)\n#endif\n\n      call gBcastValue(TO_NODE,gto)\n\n      maxNum = 0\n      kk = 0\n\n            ! The following loops are replaced by a hashtable-based algorithm\n      ! do m = 1, NLINKSL\n      !       num = 0\n      !       do k = 1, gnlinksl\n      !          if(gto(k) .eq. LINKID(m) ) then\n      !              kk = kk +1\n      !              num = num + 1\n      !          endif\n      !       end do\n      !       if(num .gt. maxNum) maxNum = num\n      ! end do\n\n\n\n      block\n        type(hash_t) :: hash_table\n        integer(kind=int64) :: val,it\n        integer(kind=int64), allocatable :: num_a(:)\n        logical :: found\n\n        allocate(num_a(NLINKSL))\n        num_a = 0\n        kk = 0\n\n        call hash_table%set_all_idx(linkid, NLINKSL)\n        do it=1, gnlinksl\n           call hash_table%get(gto(it), val, found)\n           if(found .eqv. .true.) then\n              kk = kk + 1\n              num_a(val) = num_a(val) + 1\n           end if\n        end do\n        maxNum = maxval(num_a)\n        num_a = 1\n\n        allocate(ind(kk))\n        allocate(gToNodeOut(NLINKSL,maxNum+1))\n        gToNodeOut = -99\n        allocate(tmpTYPEL(kk))\n        allocate(tmpLINKID(kk))\n        allocate(tmpLAKEIDA(kk))\n        allocate(tmpOUTLAKEID(kk))\n        allocate(tmpTO_NODE(kk))\n\n        if(kk .gt. 0) then\n           tmpOUTLAKEID = -999\n           tmpTYPEL = -999\n           tmpTO_NODE = -999\n        endif\n        if(NLINKSL .gt. 0) then\n           OUTLAKEID = -999\n           TYPEL = -999\n        endif\n\n        kk = 0\n\n        ! The following loops are replaced by a hashtable-based algorithm\n        ! do m = 1, NLINKSL\n        !          num = 1\n        !          do k = 1, gnlinksl\n        !              if(gto(k) .eq. LINKID(m) ) then\n        !                  kk = kk +1\n        !                  ind(kk) = k\n        !                  tmpTO_NODE(kk) = gto(k)\n        !                  gToNodeOut(m,num+1) = kk\n        !                  gToNodeOut(m,1) = num\n        !                  num = num + 1\n        !              endif\n        !           end do\n        ! enddo\n\n        do it=1, gnlinksl\n           call hash_table%get(gto(it), val, found)\n           if(found .eqv. .true.) then\n              kk = kk + 1\n              ind(kk) = it\n              tmpTO_NODE(kk) = gto(it)\n              gToNodeOut(val,num_a(val)+1) = kk\n              gToNodeOut(val,1) = num_a(val)\n              num_a(val) = num_a(val) + 1\n           end if\n        end do\n\n        deallocate(num_a)\n        call hash_table%clear()\n\n      end block\n\n      size2 = kk\n      deallocate (gto)\n\n      allocate(gLINKID(gnlinksl))\n      call gBcastValue(LINKID,gLINKID)\n      do i = 1, size2\n            k = ind(i)\n            tmpLINKID(i) = gLINKID(k)\n      enddo\n\n      allocate(gLAKEIDA(gnlinksl))\n      call gBcastValue(LAKEIDA(1:NLINKSL),gLAKEIDA(1:gnlinksl) )\n      do i = 1, size2\n            k = ind(i)\n            tmpLAKEIDA(i) = gLAKEIDA(k)\n      enddo\n      if(allocated(gLAKEIDA)) deallocate(gLAKEIDA)\n\n!yw LAKELINKID = 0\n      tmpLAKELINKID = LAKELINKID\n      tmpOUTLAKEID  = tmpTO_NODE\n      OUTLAKEID(1:NLINKSL)  = TO_NODE(1:NLINKSL)\n\n !! find the links that flow into lakes (e.g. TYPEL = 3), and update the TO_NODE, so that links flow into the lake reach\n        DO i = 1, NLAKES\n          DO k = 1, NLINKSL\n             do m = 1, gToNodeOut(k,1)\n                 j = gToNodeOut(k,m+1)\n                 if( (tmpTO_NODE(j) .eq. LINKID(k) ) .and. &\n                     (LAKEIDA(k) .lt. 0 .and. tmpLAKEIDA(j) .eq. LAKEIDM(i))) then\n                     tmpTYPEL(j) = 1  !this is the link flowing out of the lake\n                     tmpOUTLAKEID(j) = tmpLAKEIDA(j) !tmpLINKID(j) ! Wei Check\n                     LAKELINKID(i) = ind(j)\n!                    write(61,*) tmpTO_NODE(j),tmpLAKEIDA(j),LAKEIDA(k),LAKELINKID(i)\n!                    call flush(61)\n                 elseif( (tmpTO_NODE(j) .eq. LINKID(k)) .and. &\n                     (tmpLAKEIDA(j) .lt. 0 .and. LAKEIDA(k) .gt. 0) .and. &\n                     (LAKEIDA(k) .eq. LAKEIDM(i)) ) then\n                     tmpTYPEL(j) = 3 !type_3 inflow link to lake\n                     tmpOUTLAKEID(j) = LAKEIDM(i) !Wei Check\n!                    write(62,*) tmpTO_NODE(j),tmpOUTLAKEID(j),LAKEIDM(i)\n!                    call flush(62)\n                 elseif (tmpLAKEIDA(j) .eq. LAKEIDM(i) .and. tmpTYPEL(j) .ne. 1) then\n                     tmpTYPEL(j) = 2 ! internal lake linkd\n                     !! print the following to get the list of links which are ignored bc they are internal to lakes.\n                     !print*,'Ndg: tmpLAKEIDA(j):', tmpLAKEIDA(j)\n                 endif\n            END DO\n          END DO\n       END DO\n\n!yw       call sum_int1d(LAKELINKID, NLAKES)\n       call updateLake_seqInt8(LAKELINKID,nlakes,tmpLAKELINKID)\n\n       if(allocated(tmplakelinkid))  deallocate(tmpLAKELINKID)\n\n       if(gNLINKSL .gt. 0) then\n          if(my_id .eq. 0) then\n              allocate(gLAKEIDX(gNLINKSL))\n              gLAKEIDX = -999\n              DO i = 1, NLAKES\n                   if(LAKELINKID(i) .gt. 0) then\n                      gLAKEIDX(LAKELINKID(i)) = i\n                   endif\n              ENDDO\n          else\n              allocate(gLAKEIDX(1))\n          endif\n          call ReachLS_decomp(gLAKEIDX, LAKEIDX)\n          if(allocated(gLAKEIDX)) deallocate(gLAKEIDX)\n       endif\n\n!     do k = 1, size\n!         write(70+my_id,*) \"k, ind(k), typel, lakeidx\", k, ind(k),tmpTYPEL(k), lakeidx(ind(k))\n!         call flush(70+my_id)\n!     end do\n\n       call TONODE2RSL(ind,tmpTYPEL,size2,gNLINKSL,NLINKSL,TYPEL(1:NLINKSL), -999 )\n       call TONODE2RSL8(ind,tmpOUTLAKEID,size2,gNLINKSL,NLINKSL,OUTLAKEID(1:NLINKSL), -999 )\n\n\n ! assign the the inflow nodes to the lank with a new TO_NODE id, which is the outflow link\n!yw       DO i = 1, NLINKSL\n!yw 105\n!     DO k = 1, NLINKSL\n!       do m = 1, gToNodeOut(k,1)\n!                i = gToNodeOut(k,m+1)\n!          DO j = 1, NLINKSL\n!             if (tmpTYPEL(i) .eq. 3 .and. TYPEL(j) .eq. 1 .and. (OUTLAKEID(j) .eq. tmpOUTLAKEID(i)) &\n!                  .and. tmpOUTLAKEID(i) .ne. -999) then\n!                    !yw tmpTO_NODE(i) = tmpOUTLAKEID(i)  !Wei Check\n!                    tmpTO_NODE(i) = LINKID(j)  !Wei Check\n!             endif\n!          END DO\n!        END DO\n!     END DO\n!     call TONODE2RSL(ind,tmpTO_NODE,size,gNLINKSL,NLINKSL,TO_NODE(1:NLINKSL), -999 )\n\n ! assign the the inflow nodes to the lank with a new TO_NODE id, which is the outflow link\n      allocate(gTYPEL(gNLINKSL))\n      allocate(gOUTLAKEID(gNLINKSL))\n      call gBcastValue(TYPEL,gTYPEL)\n      call gBcastValue(OUTLAKEID,gOUTLAKEID)\n       DO i = 1, NLINKSL\n        DO j = 1, gNLINKSL\n            if(TYPEL(i) .eq. 3 .and. gTYPEL(j) .eq. 1 .and. (gOUTLAKEID(j) .eq. OUTLAKEID(i))) then\n              TO_NODE(i) = gLINKID(j)  !   OUTLAKEID(i)\n            endif\n        ENDDO\n       ENDDO\n      deallocate(gLINKID)\n      deallocate(gTYPEL)\n      deallocate(gOUTLAKEID)\n\n      deallocate(tmpTYPEL,tmpLINKID, tmpTO_NODE, tmpLAKEIDA, tmpOUTLAKEID,OUTLAKEID)\n\n\n!     do k = 1, NLINKSL\n!         write(60+my_id,*) \"k, typel, lakeidx\", k, typel(k), lakeidx(k)\n!         call flush(60+my_id)\n!     end do\n\n\n!     call ReachLS_write_io(TO_NODE(1:NLINKSL), tmpBuf(1:gNLINKSL) )\n!     if(my_id .eq. io_id ) then\n!       write(70,*) tmpBuf(1:gNLINKSL)\n!       call flush(70)\n!     endif\n!     call ReachLS_write_io(TYPEL(1:NLINKSL), tmpBuf(1:gNLINKSL) )\n!     if(my_id .eq. io_id ) then\n!       write(71,*) tmpBuf\n!       call flush(71)\n!     endif\n!     call ReachLS_write_io(LAKEIDX(1:NLINKSL), tmpBuf(1:gNLINKSL))\n!     if(my_id .eq. io_id ) then\n!       write(72,*) tmpBuf\n!       call flush(72)\n!       close(72)\n!     endif\n!     call ReachLS_write_io(OUTLAKEID(1:NLINKSL), tmpBuf(1:gNLINKSL))\n!     if(my_id .eq. io_id ) then\n!       write(73,*) tmpBuf\n!       call flush(73)\n!     endif\n!     call hydro_finish()\n\n!     DO i = 1, NLINKSL\n!        write(61,*) i,LAKEIDX(i), TYPEL(i)\n!     end do\n!     DO i = 1, NLAKES\n!        write(63,*) i,LAKEIDM(i)\n!        write(62,*) i,LAKELINKID(i)\n!     end do\n!     close(61)\n!     close(62)\n!     close(63)\n\n!   write(60,*) TYPEL\n!   write(63,*) LAKELINKID, LAKEIDX\n!   write(64,*) TO_NODE\n!   write(61,*) LINKID\n!   write(62,*) LAKEIDM, LAKEIDA\n!   close(60)\n!   close(61)\n!   close(62)\n!   close(63)\n!   close(64)\n!   call hydro_finish()\n\n    end subroutine nhdLakeMap_mpp\n\n    subroutine nhdLakeMap_scan(NLAKES, NLINKSL, LAKELINKID, TO_NODE,LINKID, LAKEIDM, LAKEIDA,GNLINKSL)\n        !--- get the lake configuration here.\n        implicit none\n        integer(kind=int64), dimension(:), intent(in) :: TO_NODE\n        integer(kind=int64), dimension(NLAKES) :: LAKELINKID\n        integer(kind=int64), dimension(:),   intent(in) :: LINKID, LAKEIDA\n        integer(kind=int64), dimension(:),   intent(inout) :: LAKEIDM\n        integer, intent(in) :: NLAKES, NLINKSL ,GNLINKSL\n        integer :: i,size ,j,k, kk, num, maxNum, m, mm\n        integer(kind=int64), allocatable, dimension(:) :: tmplakeida, tmpoutlakeid, gLAKEIDA, tmpTO_NODE, gto\n        integer(kind=int64), allocatable, dimension(:) :: ind\n        integer(kind=int64), allocatable, dimension(:,:) :: gtonodeout\n        integer(kind=int64), allocatable, dimension(:) ::  tmpLAKELINKID, gtoLakeId_g, gtoLakeId\n\n!       integer tmpBuf(GNLINKSL)\n        integer, dimension(nlakes) :: lakemask\n        integer ii\n\n      allocate (gto(GNLINKSL))\n      allocate (gtoLakeId_g(GNLINKSL))\n      allocate (gtoLakeId(NLINKSL))\n      if(my_id .eq. io_id) then\n         allocate(tmpLAKELINKID(nlakes))\n      else\n         allocate(tmpLAKELINKID(1))\n      endif\n\n      gtoLakeId_g=-999\n\n      call gBcastValue(TO_NODE,gto)\n\n      maxNum = 0\n      kk = 0\n\n      ! The following loops are replaced by a hashtable-based algorithm\n      ! do m = 1, NLINKSL\n      !    num = 0\n      !    do k = 1, gnlinksl\n      !       if(gto(k) .eq. LINKID(m) ) then\n      !          gtoLakeId_g(k) = lakeida(m)\n      !          kk = kk +1\n      !          num = num + 1\n      !       endif\n      !    end do\n      !    if(num .gt. maxNum) maxNum = num\n      ! end do\n\n      block\n        type(hash_t) :: hash_table\n        integer(kind=int64) :: val,it\n        integer(kind=int64), allocatable :: num_a(:)\n        logical :: found\n\n        allocate(num_a(NLINKSL))\n        num_a = 0\n        kk = 0\n\n        call hash_table%set_all_idx(linkid, NLINKSL)\n        do it=1, gnlinksl\n           call hash_table%get(gto(it), val, found)\n           if(found .eqv. .true.) then\n              gtoLakeId_g(it) = lakeida(val)\n              kk = kk + 1\n              num_a(val) = num_a(val) + 1\n           end if\n        end do\n        maxNum = maxval(num_a)\n        num_a = 1\n\n        allocate(ind(kk))\n        allocate(gToNodeOut(NLINKSL,maxNum+1))\n        gToNodeOut = -99\n        allocate(tmpLAKEIDA(kk))\n        allocate(tmpTO_NODE(kk))\n\n        kk = 0\n\n        ! The following loops are replaced by a hashtable-based algorithm\n        ! do m = 1, NLINKSL\n        !    num = 1\n        !    do k = 1, gnlinksl\n        !       if(gto(k) .eq. LINKID(m) ) then\n        !          kk = kk +1\n        !          ind(kk) = k\n        !          tmpTO_NODE(kk) = gto(k)\n        !          gToNodeOut(m,num+1) = kk\n        !          gToNodeOut(m,1) = num\n        !          num = num + 1\n        !       endif\n        !    end do\n        ! end do\n\n        do it=1, gnlinksl\n           call hash_table%get(gto(it), val, found)\n           if(found .eqv. .true.) then\n              kk = kk + 1\n              ind(kk) = it\n              tmpTO_NODE(kk) = gto(it)\n              gToNodeOut(val,num_a(val)+1) = kk\n              gToNodeOut(val,1) = num_a(val)\n              num_a(val) = num_a(val) + 1\n           end if\n        end do\n\n        deallocate(num_a)\n        call hash_table%clear()\n\n      end block\n\n      size = kk\n      if(allocated(gto)) deallocate (gto)\n\n\n      allocate(gLAKEIDA(gnlinksl))\n      call gBcastValue(LAKEIDA(1:NLINKSL),gLAKEIDA(1:gnlinksl) )\n      do i = 1, size\n            k = ind(i)\n            tmpLAKEIDA(i) = gLAKEIDA(k)\n      enddo\n      if(allocated(gLAKEIDA)) deallocate(gLAKEIDA)\n\n        tmpLAKELINKID = LAKELINKID\n!       LAKELINKID = 0\n        DO i = 1, NLAKES\n          DO k = 1, NLINKSL\n             do m = 1, gToNodeOut(k,1)\n                 j = gToNodeOut(k,m+1)\n                 if( (tmpTO_NODE(j) .eq. LINKID(k) ) .and. &\n                     (LAKEIDA(k) .lt. 0 .and. tmpLAKEIDA(j) .eq. LAKEIDM(i))) then\n                     if(LAKELINKID(i) .gt. 0) then\n                         LAKELINKID(i) = -999\n#ifdef HYDRO_D\n                         write(6,*) \"remove the lake  LAKEIDM(i) \", i, LAKEIDM(i)\n                         call flush(6)\n#endif\n                     endif\n                     if(LAKELINKID(i) .eq. 0) LAKELINKID(i) = ind(j)\n                 endif\n            END DO\n          END DO\n       END DO\n!yw        call match1dLake(LAKELINKID, NLAKES, -999)\n\n!yw double check\n      call combine_int8_1d(gtoLakeId_g,gnlinksl, -999)\n      call ReachLS_decomp(gtoLakeId_g,gtoLakeId)\n\n       lakemask = 0\n       DO k = 1, NLINKSL\n          if(LAKEIDA(k) .gt. 0) then\n             DO i = 1, NLAKES\n                if(gtoLakeId(k) .eq. LAKEIDM(i) )  then\n                    goto 992\n                endif\n             enddo\n             DO i = 1, NLAKES\n                if(LAKEIDA(k) .eq. LAKEIDM(i) )  then\n                     lakemask(i) = lakemask(i) + 1\n                      goto 992\n                endif\n             enddo\n992          continue\n          endif\n       enddo\n\n       if(allocated(gtoLakeId_g)) deallocate(gtoLakeId_g)\n       if(allocated(gtoLakeId)) deallocate(gtoLakeId)\n       call sum_int1d(lakemask, NLAKES)\n\n       do i = 1, nlakes\n           if(lakemask(i) .ne. 1) then\n               LAKELINKID(i) = -999\n#ifdef HYDRO_D\n               if(my_id .eq. IO_id) then\n                  write(6,*) \"double check remove the lake : \",LAKEIDM(i)\n                  call flush(6)\n               endif\n#endif\n           endif\n       enddo\n\n\n!end double check\n\n\n       call updateLake_seqInt8(LAKELINKID,nlakes,tmpLAKELINKID)\n\n!      if(my_id .eq. 0) then\n!          write(65,*) \"check LAKEIDM   *****,\"\n!          write(65,*) LAKEIDM\n!          call flush(6)\n!      endif\n\n       do k = 1, NLAKES\n           if(LAKELINKID(k) .eq. -999) LAKEIDM(k) = -999\n       end do\n\n!      if(my_id .eq. 0) then\n!          write(65,*) \"check LAKEIDM   *****,\"\n!          write(65,*) LAKEIDM\n!          call flush(6)\n!      endif\n\n       close(65)\n      if(allocated(tmpTO_NODE)) deallocate(tmpTO_NODE)\n      if(allocated(tmpLAKEIDA)) deallocate(tmpLAKEIDA)\n      if(allocated(tmplakelinkid)) deallocate(tmplakelinkid)\n\n    end subroutine nhdLakeMap_scan\n#endif\n\n!ADCHANGE: New output lake types routine\n    subroutine output_lake_types( inNLINKS, inLINKID, inTYPEL )\n\n#ifdef MPP_LAND\n    use module_mpp_land\n#endif\n\n    implicit none\n\n    integer, dimension(:),  intent(in) :: inTYPEL\n    integer(kind=int64), dimension(:), intent(in) :: inLINKID\n    integer, intent(in) :: inNLINKS\n\n    integer            :: iret\n    integer            :: ncid, varid\n    integer            :: linkdim\n    character(len=256), parameter :: output_flnm = \"LAKE_TYPES.nc\"\n\n    integer, allocatable, dimension(:) :: typeL\n    integer(kind=int64), allocatable, dimension(:) :: linkId\n\n#ifdef MPP_LAND\n\n    if(my_id .eq. io_id) then\n       allocate( linkId(inNLINKS)  )\n       allocate( typeL(inNLINKS)   )\n    else\n       allocate(linkId(1), typeL(1))\n    end if\n\n    call mpp_land_sync()\n    call ReachLS_write_io(inLINKID, linkId)\n    call ReachLS_write_io(inTYPEL, typeL)\n\n#else\n\n    allocate( linkId(inNLINKS) )\n    allocate( typeL(inNLINKS)  )\n\n    linkId    = inLINKID\n    typeL     = inTYPEL\n\n#endif\n\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n\n       ! Create the channel connectivity file\n#ifdef HYDRO_D\n       print*,'Lakes: output_flnm = \"'//trim(output_flnm)//'\"'\n       flush(6)\n#endif\n\n       iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n\n       if (iret /= 0) then\n          print*,\"Lakes: Problem nf90_create\"\n          call hydro_stop(\"output_lake_types\")\n       endif\n\n       iret = nf90_def_dim(ncid, \"link\", inNLINKS, linkdim)\n\n       !-- link  id\n       iret = nf90_def_var(ncid, \"LINKID\", NF90_INT64, (/linkdim/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'Link ID')\n\n       !- lake reach type, var\n       iret = nf90_def_var(ncid, \"TYPEL\", NF90_INT, (/linkdim/), varid)\n       iret = nf90_put_att(ncid, varid, 'long_name', 'Lake reach type')\n\n       iret = nf90_enddef(ncid)\n\n       !-- write id\n       iret = nf90_inq_varid(ncid,\"LINKID\", varid)\n       iret = nf90_put_var(ncid, varid, linkId, (/1/), (/inNLINKS/))\n\n       !-- write type\n       iret = nf90_inq_varid(ncid,\"TYPEL\", varid)\n       iret = nf90_put_var(ncid, varid, typeL, (/1/), (/inNLINKS/))\n\n       iret = nf90_close(ncid)\n\n#ifdef MPP_LAND\n    endif\n#endif\n    if(allocated(linkId)) deallocate(linkId)\n    if(allocated(typeL)) deallocate(typeL)\n\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n#endif\n#ifdef HYDRO_D\n    write(6,*) \"end of output_lake_types\"\n    flush(6)\n#endif\n#ifdef MPP_LAND\n    endif\n#endif\n\nend subroutine output_lake_types\n\nsubroutine hdtbl_out_nc(did,ncid,count,count_flag,varName,varIn,descrip,ixd,jxd)\n   implicit none\n   integer :: did, iret, ncid, ixd,jxd, ix,jx, err_flag,count_flag, count,varid\n   real, allocatable, dimension(:,:) :: xdump\n   real, dimension(:,:) :: varIn\n   character(len=*) :: descrip\n   character(len=*) ::varName\n\n#ifdef MPP_LAND\n   ix=global_nx\n   jx=global_ny\n#else\n   ix=RT_DOMAIN(did)%ix\n   jx=RT_DOMAIN(did)%jx\n#endif\n   if( count == 0 .and. count_flag == 0) then\n      count_flag = 1\n#ifdef MPP_LAND\n     if(my_id .eq. IO_id) then\n#endif\n     iret = nf90_create(trim(nlst(did)%hydrotbl_f), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n#ifdef MPP_LAND\n     endif\n     call mpp_land_bcast_int1(iret)\n#endif\n       if (iret /= 0) then\n          call hydro_stop(\"FATAL ERROR:   - Problem nf90_create  in nc of hydrotab_f file\")\n       endif\n\n#ifdef MPP_LAND\n     if(my_id .eq. IO_id) then\n#endif\n       iret = nf90_def_dim(ncid, \"west_east\", ix, ixd)  !-- make a decimated grid\n       iret = nf90_def_dim(ncid, \"south_north\", jx, jxd)\n#ifdef MPP_LAND\n     endif\n#endif\n   endif ! count == 0\n\n\n   if( count == 1 ) then  ! define variables\n#ifdef MPP_LAND\n     if(my_id .eq. io_id) then\n#endif\n       iret = nf90_def_var(ncid, trim(varName), NF90_FLOAT, (/ixd,jxd/), varid)\n       ! iret = nf90_put_att(ncid, varid, 'description', trim(descrip))\n       iret = nf90_put_att(ncid, varid, 'description', \"test\")\n#ifdef MPP_LAND\n     endif\n#endif\n   endif  !!! end of count == 1\n\n   if (count == 2) then ! write out the variables\n       if(count_flag == 2) iret = nf90_enddef(ncid)\n       count_flag = 3\n#ifdef MPP_LAND\n     if(my_id .eq. io_id) then\n#endif\n       allocate (xdump(ix, jx))\n#ifdef MPP_LAND\n     else\n       allocate (xdump(1, 1))\n     endif\n#endif\n\n#ifdef MPP_LAND\n     call write_io_real(varIn,xdump)\n     if(my_id .eq. io_id) iret = nf90_inq_varid(ncid,trim(varName), varid)\n     if(my_id .eq. io_id)  iret = nf90_put_var(ncid, varid, xdump, (/1,1/), (/ix,jx/))\n#else\n     iret = nf90_inq_varid(ncid,trim(varName), varid)\n     iret = nf90_put_var(ncid, varid, varIn, (/1,1/), (/ix,jx/))\n#endif\n\n      deallocate(xdump)\n    endif !! end of count == 2\n    if(count == 3 .and. count_flag == 3) then\n       count_flag = 4\n#ifdef MPP_LAND\n       if(my_id .eq. io_id ) &\n#endif\n       iret = nf90_close(ncid)\n    endif !! end of count == 3\n\n\nend subroutine hdtbl_out_nc\nsubroutine hdtbl_out(did)\n   implicit none\n   integer :: did, ncid, count,count_flag, i, ixd,jxd\n   do i = 0,3\n      count = i\n      count_flag = i\n      call hdtbl_out_nc(did,ncid, count,count_flag,\"SMCMAX1\",rt_domain(did)%SMCMAX1,\"\",ixd,jxd)\n      call hdtbl_out_nc(did,ncid, count,count_flag,\"SMCREF1\",rt_domain(did)%SMCREF1,\"\",ixd,jxd)\n      call hdtbl_out_nc(did,ncid, count,count_flag,\"SMCWLT1\",rt_domain(did)%SMCWLT1,\"\",ixd,jxd)\n      call hdtbl_out_nc(did,ncid, count,count_flag,\"OV_ROUGH2D\",rt_domain(did)%OV_ROUGH2D,\"\",ixd,jxd)\n      call hdtbl_out_nc(did,ncid, count,count_flag,\"LKSAT\",rt_domain(did)%LKSAT,\"\",ixd,jxd)\n      call hdtbl_out_nc(did,ncid, count,count_flag,\"NEXP\",rt_domain(did)%NEXP,\"\",ixd,jxd)\n   end do\nend subroutine hdtbl_out\n\nsubroutine hdtbl_in_nc(did)\n   implicit none\n   integer :: did\n   integer :: ierr\n   call read2dlsm(did,trim(nlst(did)%hydrotbl_f),\"SMCMAX1\",rt_domain(did)%SMCMAX1,ierr)\n   call read2dlsm(did,trim(nlst(did)%hydrotbl_f),\"SMCREF1\",rt_domain(did)%SMCREF1,ierr)\n   call read2dlsm(did,trim(nlst(did)%hydrotbl_f),\"SMCWLT1\",rt_domain(did)%SMCWLT1,ierr)\n   call read2dlsm(did,trim(nlst(did)%hydrotbl_f),\"OV_ROUGH2D\",rt_domain(did)%overland%properties%roughness,ierr, rt=.true.)\n   call read2dlsm(did,trim(nlst(did)%hydrotbl_f),\"LKSAT\",rt_domain(did)%LKSAT,ierr)\n   call read2dlsm(did,trim(nlst(did)%hydrotbl_f),\"NEXP\",rt_domain(did)%NEXP,ierr)\n   ! Letting this variable be optional and setting to global default value if not found\n   if (ierr /= 0) then\n     write(6,*)  \"WARNING (hydtbl_in_nc): NEXP not found so setting to global 1.0\"\n     rt_domain(did)%NEXP = 1.0\n   endif\nend subroutine hdtbl_in_nc\n\nsubroutine read2dlsm(did,file,varName,varOut,ierr,rt)\nuse module_mpp_land,only: mpp_land_bcast_int1\n  implicit none\n  integer :: did, ncid , iret\n  character(len=*) :: file,varName\n  real,dimension(:,:) :: varOut\n  character(len=256) :: units\n  integer, intent(out) :: ierr\n  logical, optional, intent(in) :: rt\n  logical :: regrid\n\n  real,allocatable,dimension(:,:) :: tmpArr\n\n#ifdef MPP_LAND\n  if(my_id .eq. io_id) then\n#endif\n     allocate(tmpArr(global_nx,global_ny))\n     iret = nf90_open(trim(file), NF90_NOWRITE, ncid)\n     call get_2d_netcdf(trim(varName), ncid, tmpArr, units, global_nx, global_ny, &\n          .false., ierr)\n     iret = nf90_close(ncid)\n#ifdef MPP_LAND\n  else\n     allocate(tmpArr(1,1))\n  endif\n#endif\n\n  if (present(rt)) then\n    regrid = rt\n  else\n    regrid = .false.\n  endif\n\n  if (regrid) then\n    call regrid_lowres_to_highres(did, tmpArr, varOut, rt_domain(did)%ixrt, rt_domain(did)%jxrt)\n  else\n    call decompose_data_real (tmpArr,varOut)\n  endif\n\n#ifdef MPP_LAND\n  call mpp_land_bcast_int1(ierr)\n#endif\n\n  deallocate(tmpArr)\nend subroutine read2dlsm\n\nsubroutine regrid_lowres_to_highres(did, lowres_grid, highres_grid, ixrt, jxrt)\n\n  implicit none\n  integer :: did\n  integer :: ixrt, jxrt\n  real, dimension(global_nx, global_ny) :: lowres_grid\n  real, dimension(ixrt,jxrt) :: highres_grid\n  ! Local variables\n  integer :: i, j, irt, jrt, aggfacxrt, aggfacyrt\n\n#ifdef MPP_LAND\n  real,allocatable,dimension(:,:) :: tmpArr\n  if(my_id .eq. io_id) then\n     allocate(tmpArr(global_rt_nx, global_rt_ny))\n#endif\n\n      do j = 1,global_ny ! Start coarse grid j loop\n         do i = 1,global_nx ! Start coarse grid i loop\n\n            do aggfacyrt = nlst(did)%AGGFACTRT-1,0,-1 ! Start disagg fine grid j loop\n            do aggfacxrt = nlst(did)%AGGFACTRT-1,0,-1 ! Start disagg fine grid i loop\n\n               irt = i * nlst(did)%AGGFACTRT - aggfacxrt ! Define fine grid i\n               jrt = j * nlst(did)%AGGFACTRT - aggfacyrt ! Define fine grid j\n#ifdef MPP_LAND\n               ! if(left_id.ge.0) irt = irt + 1\n               ! if(down_id.ge.0) jrt = jrt + 1\n               tmpArr(irt,jrt) = lowres_grid(i,j)\n#else\n               highres_grid(irt,jrt) = lowres_grid(i,j)\n#endif\n\n            end do\n            end do\n\n         end do\n      end do\n\n#ifdef MPP_LAND\n  else\n     allocate(tmpArr(1,1))\n  endif\n  call decompose_RT_real(tmpArr, highres_grid, global_rt_nx, global_rt_ny, ixrt, jxrt)\n  deallocate(tmpArr)\n#endif\n\nend subroutine regrid_lowres_to_highres\n\nsubroutine read_channel_only (olddateIn, hgrid, indir, dtbl)\n!use module_HYDRO_io, only: read_rst_crt_reach_nc\nuse module_RT_data, only: rt_domain\nuse module_mpp_land,only: mpp_land_bcast_int1, my_id, io_id\nuse Module_Date_utilities_rt, only: geth_newdate\nuse config_base, only: nlst\nimplicit none\ninteger :: iret, did, len, ncid\ninteger :: dtbl\ncharacter :: hgrid\ncharacter(len=*):: olddateIn,indir\ncharacter(len=19) :: olddate\ncharacter(len=256):: fileName\nreal*8, allocatable, dimension(:):: accBucket_in, accSfcLatRunoff_in\nreal  , allocatable, dimension(:)::   qBucket_in,   qSfcLatRunoff_in\ninteger, parameter :: r8 = selected_real_kind(8)\nreal*8,  parameter :: zeroDbl=0.0000000000000000000_r8\ninteger :: ovrtswcrt_in, noah_timestep_in, channel_only_in, channelBucket_only_in\ncharacter(len=86) :: attNotInFileMsg\n\ndid = 1\nlen = size(rt_domain(did)%QLATERAL,1)\n!! if len is .le. 0, this whole thing is pointless. huh?\n\nif(my_id .eq. io_id) then\n   call geth_newdate(olddate,olddateIn,dtbl)\n   fileName = trim(indir)//\"/\"//&\n        olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n        olddate(15:16)//\".CHRTOUT_DOMAIN\"//hgrid\n#ifdef HYDRO_D\n   print*, \" Channel only input forcing file: \",trim(fileName)\n#endif /* HYDRO_D */\n   iret = nf90_open(trim(fileName), NF90_NOWRITE, ncid)\nendif\n\ncall mpp_land_bcast_int1(iret)\nif (iret .ne. 0) then\n   call hydro_stop( \"FATAL ERROR: read forcing data for CHANNEL_ONLY failed. \")\nendif\n\n!! ---------------------------------------------------------------------------\n!! Consistency checks - global att checking.\nif(my_id .eq. io_id) then\n\n   attNotInFileMsg=&  !! lenght fixed above\n        'Fatal error for channel only: the following global attribute not in the forcing file: '\n\n   !! 1) overland routing v squeegee??\n   !!if(nlst_rt(did)%OVRTSWCRT .eq. 1) then\n   iret = nf90_get_att(ncid, NF90_GLOBAL, 'OVRTSWCRT', ovrtswcrt_in)\n   if(iret .ne. 0) iret = nf90_get_att(ncid, NF90_GLOBAL, 'dev_OVRTSWCRT', ovrtswcrt_in)\n   if(iret .ne. 0) call hydro_stop(attNotInFileMsg // 'OVRTSWCRT & dev_OVRTSWCRT not in ' // trim(fileName) )\n   if(nlst(1)%ovrtswcrt .ne. ovrtswcrt_in) &\n        call hydro_stop('Channel only: OVRTSWCRT or dev_OVRSWCRT in forcing file does not match run config.')\n\n   !! 2) NOAH_TIMESTEP same?\n   iret = nf90_get_att(ncid, NF90_GLOBAL, 'NOAH_TIMESTEP', noah_timestep_in)\n   if(iret .ne. 0) iret = nf90_get_att(ncid, NF90_GLOBAL, 'dev_NOAH_TIMESTEP', noah_timestep_in)\n   if(iret .ne. 0) call hydro_stop(attNotInFileMsg // 'NOAH_TIMESTEP & dev_NOAH_TIMESTEP not in ' // trim(fileName) )\n   if(nlst(1)%dt .ne. noah_timestep_in) &\n        call hydro_stop('Channel only: NOAH_TIMESTEP or dev_NOAH_TIMESTEP in forcing file does not match run config.')\n\n   !! 3) channel_only or channelBucket_only?\n   iret = nf90_get_att(ncid, NF90_GLOBAL, \"channel_only\",       channel_only_in)\n   if(iret .ne. 0) iret = nf90_get_att(ncid, NF90_GLOBAL, \"dev_channel_only\",       channel_only_in)\n   if(iret .ne. 0) call hydro_stop(attNotInFileMsg // 'channel_only not in ' // trim(fileName) )\n\n   iret = nf90_get_att(ncid, NF90_GLOBAL, \"channelBucket_only\", channelBucket_only_in)\n   if(iret .ne. 0) iret = nf90_get_att(ncid, NF90_GLOBAL, \"dev_channelBucket_only\", channel_only_in)\n   if(iret .ne. 0) call hydro_stop(attNotInFileMsg // 'channelBucket_only not in ' // trim(fileName) )\n   !! See table of fatal combinations on wiki: https://wiki.ucar.edu/display/wrfhydro/Channel+Only\n   !! First row: Can it even get to this combination? NO.\n   !if( (nlst_rt(did)%channel_only .eq. 0 .and. nlst_rt(did)%channelBucket_only .eq. 0) .and. &\n   !    (channel_only_in .eq. 1 .or.  channelBucket_only_in .eq. 1)        ) &\n   !    call hydro_stop('Channel Only: Forcing files in consistent with forcing type.')\n   !! Second row:\n   if(nlst(did)%channel_only .eq. 1 .and. channelBucket_only_in .eq. 1) &\n        write(6,*) \"Warning: channelBucket_only output forcing channel_only run\"\n\nend if\n\n   !! ---------------------------------------------------------------------------\n   !! FLUXES or accumulations? NOT SUPPORTING accumulations to be read in.\n!! FLUXES\nif(nlst(did)%channel_only       .eq. 1 .or. &\n   nlst(did)%channelBucket_only .eq. 1      ) then\n\n   allocate(qBucket_in(len))\n   allocate(qSfcLatRunoff_in(len))\n   qBucket_in   = 0.0\n   qSfcLatRunoff_in = 0.0\n\n   !! Surface Lateral Fluxes (currenly include exfiltration from subsurface)\n   call read_rst_crt_reach_nc(ncid, qSfcLatRunoff_in, \"qSfcLatRunoff\", &\n                              rt_domain(did)%GNLINKSL, fatalErr=.true. )\n\n   !! Fluxes from (channel only) or to (channelBucket only) bucket?\n   !! Fluxes from bucket.\n   if(nlst(did)%channel_only .eq. 1) then\n      call read_rst_crt_reach_nc(ncid, qBucket_in, \"qBucket\",            &\n                                 rt_domain(did)%GNLINKSL, fatalErr=.true.)\n      rt_domain(did)%qout_gwsubbas = qBucket_in\n      rt_domain(did)%QLateral      = qBucket_in + qSfcLatRunoff_in\n   endif\n\n   !! Fluxes to bucket\n   if(nlst(did)%channelBucket_only .eq. 1) then\n      call read_rst_crt_reach_nc(ncid, qBucket_in, \"qBtmVertRunoff\",     &\n                                 rt_domain(did)%GNLINKSL, fatalErr=.true.)\n      rt_domain(did)%qin_gwsubbas = qBucket_in\n      rt_domain(did)%QLateral     = qSfcLatRunoff_in\n   end if\n\n   deallocate(qBucket_in, qSfcLatRunoff_in)\nend if\n\n!! Accumulations - NOT SUPPORTED, MAY NEVER BE.\n!! How to figure out if fluxes or accums force??\nif(.FALSE.) then\n   allocate(accBucket_in(len))\n   allocate(accSfcLatRunoff_in(len))\n   accBucket_in   = zeroDbl\n   accSfcLatRunoff_in = zeroDbl\n\n   call read_rst_crt_reach_nc(ncid, accSfcLatRunoff_in, \"accSfcLatRunoff\", &\n        rt_domain(did)%GNLINKSL, fatalErr=.true.)\n   !! Could worry about bucket being off or not output...\n   call read_rst_crt_reach_nc(ncid, accBucket_in,         \"accBucket\",       &\n        rt_domain(did)%GNLINKSL, fatalErr=.true.)\n\n   !! Calculate the current\n   if(len .gt. 0) then  !! would the length be zero on some images?\n      rt_domain(did)%qout_gwsubbas = &\n           real( (accBucket_in - rt_domain(did)%accBucket)/nlst(did)%DT )\n      rt_domain(did)%QLateral      = &\n           real( rt_domain(did)%qout_gwsubbas +     &\n                 (accSfcLatRunoff_in - rt_domain(did)%accSfcLatRunoff)/nlst(did)%DT )\n\n      !! Negative accumulations imply accumulations were zeroed, e.g. the code was restarted\n      if(any(rt_domain(did)%QLateral .lt. 0)) &\n           rt_domain(did)%QLateral      = real( (accSfcLatRunoff_in)/nlst(did)%DT )\n      if(any(rt_domain(did)%qout_gwsubbas .lt. 0)) &\n           rt_domain(did)%qout_gwsubbas = real( (accBucket_in)/nlst(did)%DT )\n\n      !! /\\ ORDER MATTERS \\/ because the pre-input accumulations are needed above.\n      !! else below would be zero.\n      rt_domain(did)%accBucket     = accBucket_in\n      rt_domain(did)%accSfcLatRunoff = accSfcLatRunoff_in\n\n   end if\n\n   deallocate(accBucket_in, accSfcLatRunoff_in)\nend if\n\nif(my_id .eq. io_id) then\n   iret = nf90_close(ncid)\n#ifdef HYDRO_D\n   print*, \"finish read channel only forcing \"\n#endif /* HYDRO_D */\nendif\ncall flush(6)\n\nend subroutine read_channel_only\n\n\n!---------------------------------------------------------------------------\nend module module_HYDRO_io\n"
  },
  {
    "path": "src/Routing/module_HYDRO_utils.F90",
    "content": "module module_HYDRO_utils\n  use module_RT_data, only: rt_domain\n  use config_base, only: nlst\n  use iso_fortran_env, only: int64\n#ifdef MPP_LAND\n  use module_mpp_land, only: global_nx, global_ny, my_id, IO_id, &\n       decompose_data_real, write_io_real, MPP_LAND_COM_REAL, &\n       write_io_int, mpp_land_bcast_real, global_rt_nx, global_rt_ny, &\n       decompose_rt_real, write_io_rt_real\n  use MODULE_mpp_GWBUCKET, only: gw_decompose_real\n#endif\n\n\n  implicit none\n  logical lr_dist_flag    !land routing distance calculated or not.\n\ncontains\n\n  integer function get2d_real(var_name,out_buff,ix,jx,fileName)\n    implicit none\n#         include \"netcdf.inc\"\n    integer :: ivar, iret,varid,ncid,ix,jx\n    real out_buff(ix,jx)\n    character(len=*), intent(in) :: var_name\n    character(len=*), intent(in) :: fileName\n    get2d_real = -1\n\n    iret = nf_open(trim(fileName), NF_NOWRITE, ncid)\n    if (iret .ne. 0) then\n#ifdef HYDRO_D\n       print*,\"Failed to open the netcdf file: \",trim(fileName)\n#endif\n       out_buff = -9999.\n       return\n    endif\n    ivar = nf_inq_varid(ncid,trim(var_name),  varid)\n    if(ivar .ne. 0) then\n       ivar = nf_inq_varid(ncid,trim(var_name//\"_M\"),  varid)\n       if(ivar .ne. 0) then\n#ifdef HYDRO_D\n          write(6,*) \"Read Error: could not find \",var_name\n#endif\n          return\n       endif\n    end if\n    iret = nf_get_var_real(ncid, varid, out_buff)\n    iret = nf_close(ncid)\n    get2d_real =  ivar\n  end function get2d_real\n\n\n! this module create the distance dx, dy and diagnoal for routing\n! 8 direction as the slop:\n! 1: i,j+1\n! 2: i+1, j+1\n! 3: i+1, j\n! 4: i+1, j-1\n! 5: i, j-1\n! 6: i-1, j-1\n! 7: i-1, j\n! 8: i-1, j+1\n   real function get_dy(i,j,v,ix,jx)\n      ! south north\n       integer :: i,j,ix,jx\n       real,dimension(ix,jx,9) :: v\n       if( v(i,j,1) .le. 0) then\n          get_dy = v(i,j,5)\n       else if( v(i,j,5) .le. 0) then\n          get_dy = v(i,j,1)\n       else\n          get_dy = (v(i,j,1) + v(i,j,5) ) / 2\n       endif\n       return\n   end function get_dy\n\n   real function get_dx(i,j,v,ix,jx)\n      ! east-west\n       integer :: i,j, ix,jx\n       real,dimension(ix,jx,9) :: v\n       if( v(i,j,3) .le. 0) then\n          get_dx = v(i,j,7)\n       else if( v(i,j,7) .le. 0) then\n          get_dx = v(i,j,3)\n       else\n          get_dx = (v(i,j,3) + v(i,j,7) ) / 2\n       endif\n       return\n   end function get_dx\n\n   real function get_ll_d(lat1_in, lat2_in, lon1_in, lon2_in)\n     implicit none\n     real:: lat1, lat2, lon1, lon2\n     real:: lat1_in, lat2_in, lon1_in, lon2_in\n     real::  r, pai, a,c, dlat, dlon, b1,b2\n     pai = 3.14159\n     lat1 = lat1_in * pai/180\n     lat2 = lat2_in * pai/180\n     lon1 = lon1_in * pai/180\n     lon2 = lon2_in * pai/180\n     r = 6378.1*1000\n     dlat = lat2 -lat1\n     dlon = lon2 -lon1\n     a = sin(dlat/2)*sin(dlat/2) + cos(lat1)*cos(lat2)*sin(dlon/2)*sin(dlon/2)\n     b1 = sqrt(a)\n     b2 = sqrt(1-a)\n     c = 2.0*atan2(b1,b2)\n     get_ll_d = R*c\n     return\n\n   end function get_ll_d\n\n   real function get_ll_d_tmp(lat1_in, lat2_in, lon1_in, lon2_in)\n     implicit none\n     real:: lat1, lat2, lon1, lon2\n     real:: lat1_in, lat2_in, lon1_in, lon2_in\n     real::  r, pai\n     pai = 3.14159\n     lat1 = lat1_in * pai/180\n     lat2 = lat2_in * pai/180\n     lon1 = lon1_in * pai/180\n     lon2 = lon2_in * pai/180\n     r = 6371*1000\n     get_ll_d_tmp = acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon2-lon1))*r\n     return\n\n   end function get_ll_d_tmp\n\n   subroutine get_rt_dxdy_ll(did)\n!   use the land lat and lon to derive the routing distrt\n      implicit none\n      integer:: did, k\n      integer iret\n!     external get2d_real\n!     real get2d_real\n#ifdef MPP_LAND\n      real, dimension(global_rt_nx,global_rt_ny):: latrt, lonrt\n      real, dimension(global_rt_nx,global_rt_ny,9):: dist\n      if(my_id .eq. IO_id) then\n ! read the lat and lon.\n         iret =  get2d_real(\"LONGITUDE\",lonrt,global_rt_nx,global_rt_ny,&\n                     trim(nlst(did)%GEO_FINEGRID_FLNM ))\n         iret =  get2d_real(\"LATITUDE\",latrt,global_rt_nx,global_rt_ny,&\n                     trim(nlst(did)%GEO_FINEGRID_FLNM ))\n         call get_dist_ll(dist,latrt,lonrt,global_rt_nx,global_rt_ny)\n      end if\n     do k = 1 , 9\n        call decompose_RT_real(dist(:,:,k),rt_domain(did)%overland%properties%distance_to_neighbor(:,:,k), &\n                global_rt_nx,global_rt_ny,rt_domain(did)%ixrt,rt_domain(did)%jxrt)\n     end do\n#else\n      real, dimension(rt_domain(did)%ixrt,rt_domain(did)%jxrt):: latrt, lonrt\n ! read the lat and lon.\n         iret =  get2d_real(\"LONGITUDE\",lonrt,rt_domain(did)%ixrt,rt_domain(did)%jxrt,&\n                     trim(nlst(did)%GEO_FINEGRID_FLNM ))\n         iret =  get2d_real(\"LATITUDE\",latrt,rt_domain(did)%ixrt,rt_domain(did)%jxrt,&\n                     trim(nlst(did)%GEO_FINEGRID_FLNM ))\n         call get_dist_ll(rt_domain(did)%overland%properties%distance_to_neighbor,latrt,lonrt,rt_domain(did)%ixrt,rt_domain(did)%jxrt)\n#endif\n\n   end subroutine get_rt_dxdy_ll\n\n!  get dx and dy of lat and lon\n   subroutine get_dist_ll(dist,lat,lon,ix,jx)\n      implicit none\n      integer:: ix,jx\n      real, dimension(ix,jx,9):: dist\n      real, dimension(ix,jx):: lat, lon\n      integer:: i,j\n      real x,y\n      dist = -1\n      do j = 1, jx\n        do i = 1, ix\n          if(j .lt. jx) dist(i,j,1) = &\n             get_ll_d(lat(i,j), lat(i,j+1), lon(i,j), lon(i,j+1))\n          if(j .lt. jx .and. i .lt. ix) dist(i,j,2) =  &\n             get_ll_d(lat(i,j), lat(i+1,j+1), lon(i,j), lon(i+1,j+1))\n          if(i .lt. ix) dist(i,j,3) = &\n             get_ll_d(lat(i,j), lat(i+1,j), lon(i,j), lon(i+1,j))\n          if(j .gt. 1 .and. i .lt. ix) dist(i,j,4) = &\n             get_ll_d(lat(i,j), lat(i+1,j-1), lon(i,j), lon(i+1,j-1))\n          if(j .gt. 1 ) dist(i,j,5) = &\n             get_ll_d(lat(i,j), lat(i,j-1), lon(i,j), lon(i,j-1))\n          if(j .gt. 1 .and. i .gt. 1) dist(i,j,6) = &\n             get_ll_d(lat(i,j), lat(i-1,j-1), lon(i,j), lon(i-1,j-1))\n          if(i .gt. 1) dist(i,j,7) = &\n             get_ll_d(lat(i,j), lat(i-1,j), lon(i,j), lon(i-1,j))\n          if(j .lt. jx .and. i .gt. 1) dist(i,j,8) = &\n             get_ll_d(lat(i,j), lat(i-1,j+1), lon(i,j), lon(i-1,j+1))\n        end do\n      end do\n      do j = 1, jx\n        do i = 1, ix\n            if(j.eq.1) then\n               y =  get_ll_d(lat(i,j), lat(i,j+1), lon(i,j), lon(i,j+1))\n            else if(j.eq.jx) then\n               y =  get_ll_d(lat(i,j-1), lat(i,j), lon(i,j-1), lon(i,j))\n            else\n               y =  get_ll_d(lat(i,j-1), lat(i,j+1), lon(i,j-1), lon(i,j+1))/2.0\n            endif\n\n            if(i.eq.ix) then\n                x =  get_ll_d(lat(i,j), lat(i-1,j), lon(i,j), lon(i-1,j))\n            else if(i.eq.1) then\n                x =  get_ll_d(lat(i,j), lat(i+1,j), lon(i,j), lon(i+1,j))\n            else\n                x =  get_ll_d(lat(i-1,j), lat(i+1,j), lon(i-1,j), lon(i+1,j))/2.0\n            endif\n            dist(i,j,9) = x * y\n        end do\n      end do\n#ifdef HYDRO_D\n      write(6,*) \"finished get_dist_ll\"\n#endif\n   end subroutine get_dist_ll\n\n!  get dx and dy of map projected\n   subroutine get_dxdy_mp(dist,ix,jx,dx,dy)\n      implicit none\n      integer:: ix,jx\n      real :: dx,dy\n      integer:: i,j\n      real :: v1\n      ! out variable\n      real, dimension(ix,jx,9)::dist\n      dist = -1\n      v1 = sqrt(dx*dx + dy*dy)\n      do j = 1, jx\n        do i = 1, ix\n          if(j .lt. jx) dist(i,j,1) = dy\n          if(j .lt. jx .and. i .lt. ix) dist(i,j,2) = v1\n          if(i .lt. ix) dist(i,j,3) = dx\n          if(j .gt. 1 .and. i .lt. ix) dist(i,j,4) = v1\n          if(j .gt. 1 ) dist(i,j,5) = dy\n          if(j .gt. 1 .and. i .gt. 1) dist(i,j,6) = v1\n          if(i .gt. 1) dist(i,j,7) = dx\n          if(j .lt. jx .and. i .gt. 1) dist(i,j,8) = v1\n          dist(i,j,9) = dx * dy\n        end do\n      end do\n#ifdef HYDRO_D\n      write(6,*) \"finished get_dxdy_mp \"\n#endif\n   end subroutine get_dxdy_mp\n\n   subroutine get_dist_lsm(did)\n     integer did\n#ifdef MPP_LAND\n     integer ix,jx,ixrt,jxrt, k\n     real , dimension(global_nx,global_ny):: latitude,longitude\n     real, dimension(global_nx,global_ny,9):: dist\n     if(nlst(did)%dxrt0 .lt. 0) then\n           ! lat and lon grid\n          call write_io_real(rt_domain(did)%lat_lsm,latitude)\n          call write_io_real(rt_domain(did)%lon_lsm,longitude)\n          if(my_id.eq.IO_id) then\n               call get_dist_ll(dist,latitude,longitude,  &\n                         global_nx,global_ny)\n          endif\n\n     else\n           ! mapp projected grid.\n          if(my_id.eq.IO_id) then\n              call get_dxdy_mp(dist,global_nx,global_ny, &\n                 nlst(did)%dxrt0*nlst(did)%AGGFACTRT,nlst(did)%dxrt0*nlst(did)%AGGFACTRT)\n          endif\n     endif\n     do k = 1 , 9\n        call decompose_data_real(dist(:,:,k),rt_domain(did)%dist_lsm(:,:,k))\n     end do\n#else\n     if(nlst(did)%dxrt0 .lt. 0) then\n        ! lat and lon grid\n        call get_dist_ll(rt_domain(did)%dist_lsm,rt_domain(did)%lat_lsm,rt_domain(did)%lon_lsm,  &\n                      rt_domain(did)%ix,rt_domain(did)%jx)\n     else\n        ! mapp projected grid.\n        call get_dxdy_mp(rt_domain(did)%dist_lsm,rt_domain(did)%ix,rt_domain(did)%jx, &\n              nlst(did)%dxrt0*nlst(did)%AGGFACTRT,nlst(did)%dxrt0*nlst(did)%AGGFACTRT)\n     endif\n#endif\n\n\n   end subroutine get_dist_lsm\n\n   subroutine get_dist_lrt(did)\n     integer did, k\n\n!     real :: tmp_dist(global_rt_nx, global_rt_ny,9)\n\n! calculate the distance for land routing from the lat /lon of land surface model\n     if(nlst(did)%dxrt0 .lt. 0) then\n        ! using lat and lon grid when channel routing is off\n        call get_rt_dxdy_ll(did)\n     else\n        ! mapp projected grid.\n         call get_dxdy_mp(rt_domain(did)%overland%properties%distance_to_neighbor,rt_domain(did)%ixrt,rt_domain(did)%jxrt, &\n              nlst(did)%dxrt0,nlst(did)%dxrt0)\n#ifdef MPP_LAND\n        do k = 1, 9\n           call MPP_LAND_COM_REAL(rt_domain(did)%overland%properties%distance_to_neighbor(:,:,k),rt_domain(did)%IXRT,rt_domain(did)%JXRT,99)\n        end do\n#endif\n     endif\n\n\n   end subroutine get_dist_lrt\n\n!   subroutine get_dist_crt(did)\n!      integer did, k\n! calculate the distance from channel routing\n!     if(nlst_rt(did)%dxrt0 .lt. 0) then\n!        ! lat and lon grid\n!        if(rt_domain(did)%overland%properties%distance_to_neighbor(1,1,9) .eq. -999)   &\n!           call get_dist_ll(rt_domain(did)%overland%properties%distance_to_neighbor,rt_domain(did)%latval,rt_domain(did)%lonval,  &\n!                      rt_domain(did)%ixrt,rt_domain(did)%jxrt)\n!     else\n!        ! mapp projected grid.\n!        if(rt_domain(did)%overland%properties%distance_to_neighbor(1,1,9) .eq. -999)   &\n!           call get_dxdy_mp(rt_domain(did)%overland%properties%distance_to_neighbor,rt_domain(did)%ixrt,rt_domain(did)%jxrt, &\n!              nlst_rt(did)%dxrt0,nlst_rt(did)%dxrt0)\n!     endif\n!#ifdef MPP_LAND\n!     do k = 1, 9\n!       call MPP_LAND_COM_REAL(rt_domain(did)%overland%properties%distance_to_neighbor(:,:,k),rt_domain(did)%IXRT,rt_domain(did)%JXRT,99)\n!     end do\n!#endif\n!   end subroutine get_dist_crt\n\n   subroutine get_basn_area(did)\n      implicit none\n      integer :: did, ix,jx, k\n      real :: basns_area(rt_domain(did)%gnumbasns)\n#ifdef MPP_LAND\n      integer :: mask(global_nx, global_ny)\n      real :: dist_lsm(global_nx, global_ny,9)\n#else\n      integer :: mask(rt_domain(did)%ix, rt_domain(did)%jx)\n      real :: dist_lsm(rt_domain(did)%ix, rt_domain(did)%jx,9)\n#endif\n#ifdef MPP_LAND\n      ix = global_nx\n      jx = global_ny\n      call write_IO_int(rt_domain(did)%GWSUBBASMSK,mask)\n      do k = 1,  9\n         call write_IO_real(rt_domain(did)%dist_lsm(:,:,k),dist_lsm(:,:,k)) \n      end do\n#else\n      ix = rt_domain(did)%ix\n      jx = rt_domain(did)%jx\n      mask = rt_domain(did)%GWSUBBASMSK\n      dist_lsm = rt_domain(did)%dist_lsm\n#endif\n\n#ifdef MPP_LAND\n      if(my_id .eq. IO_id) then\n         call get_area_g(basns_area,mask, rt_domain(did)%gnumbasns,ix,jx,dist_lsm)\n      end if\n!      call mpp_land_bcast_real(rt_domain(did)%numbasns,rt_domain(did)%basns_area)\n\n      call gw_decompose_real(rt_domain(did)%gnumbasns, rt_domain(did)%numbasns, &\n           rt_domain(did)%basnsInd, basns_area,rt_domain(did)%basns_area)\n#else\n      call get_area_g(rt_domain(did)%basns_area,mask, rt_domain(did)%gnumbasns,ix,jx,dist_lsm)\n#endif\n   end subroutine get_basn_area\n\n   subroutine get_area_g(basns_area,GWSUBBASMSK, numbasns,ix,jx,dist)\n      integer :: i,j, n, ix,jx, numbasns\n      integer :: count(numbasns)\n      real :: basns_area(numbasns) , dist(ix,jx,9)\n      integer :: GWSUBBASMSK(ix,jx)\n      basns_area = 0\n      count = 0\n      do  j = 1, jx\n        do  i = 1, ix\n           n = GWSUBBASMSK(i,j)\n           if(n .gt. 0) then\n              basns_area(n) = basns_area(n)+dist(i,j,9)\n              count(n) = count(n) + 1\n           endif\n        end do\n      end do\n      do i = 1, numbasns\n         if(count(i) .gt. 0) then\n             basns_area(i) = basns_area(i) / count(i)\n         end if\n      end do\n   end subroutine get_area_g\n\n    subroutine get_area_g8(basns_area,GWSUBBASMSK, numbasns,ix,jx,dist)\n        integer :: i,j, n, ix,jx, numbasns\n        integer :: count(numbasns)\n        real :: basns_area(numbasns) , dist(ix,jx,9)\n        integer(kind=int64) :: GWSUBBASMSK(ix,jx)\n        basns_area = 0\n        count = 0\n        do  j = 1, jx\n            do  i = 1, ix\n                n = GWSUBBASMSK(i,j)\n                if(n .gt. 0) then\n                    basns_area(n) = basns_area(n)+dist(i,j,9)\n                    count(n) = count(n) + 1\n                endif\n            end do\n        end do\n        do i = 1, numbasns\n            if(count(i) .gt. 0) then\n                basns_area(i) = basns_area(i) / count(i)\n            end if\n        end do\n    end subroutine get_area_g8\n\n   subroutine get_node_area(did)\n       integer :: did\n\n       call get_area_g8(rt_domain(did)%node_area, rt_domain(did)%CH_NETLNK, &\n         rt_domain(did)%NLINKS,rt_domain(did)%ixrt, rt_domain(did)%jxrt, rt_domain(did)%overland%properties%distance_to_neighbor)\n   end subroutine get_node_area\n\n\nend module module_HYDRO_utils\n"
  },
  {
    "path": "src/Routing/module_NWM_io.F90",
    "content": "! Module for handling National Water Model streamflow, land surface,\n! gridded routing, lake, and groundwater output.\n\n! Logan Karsten, NCAR, RAL\n\nmodule module_NWM_io\n\nuse module_version, only: get_code_version, get_nwm_version\nuse orchestrator_base\nuse module_hydro_stop, only: HYDRO_stop\nuse iso_fortran_env, only: int64, compiler_version\n\nimplicit none\n\n! Module-wide variables\ninteger, private :: ftnNoahMP ! Private NetCDF file handle since output routine\n                              ! called multiple times for one file.\ncontains\n\n!==============================================================================\n! Program Name: output_chrt_NWM\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Output routine for channel points for the National Water Model.\n! History Log:\n! 3/6/17 -Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files: None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\n\n! To add some information as global attribute for the model configuration\n! here we get a character variable for the io_config_outputs\nfunction GetModelConfigType (io_config_outputs) result(modelConfigType)\n   integer io_config_outputs\n   character (len=64) :: modelConfigType\n   if (io_config_outputs .eq. 0) then\n      ! All\n       modelConfigType = \"default\"\n   else if (io_config_outputs .eq. 1) then\n      ! Analysis and Assimilation\n      modelConfigType = \"analysis_and_assimilation\"\n   else if (io_config_outputs .eq. 2) then\n      ! Short Range\n      modelConfigType = \"short_range\"\n   else if (io_config_outputs .eq. 3) then\n      ! Medium Range\n      modelConfigType = \"medium_range\"\n   else if (io_config_outputs .eq. 4) then\n      ! Long Range\n      modelConfigType = \"long_range\"\n   else if (io_config_outputs .eq. 5) then\n      ! Retrospective\n      modelConfigType = \"retrospective\"\n   else if (io_config_outputs .eq. 6) then\n      ! Diagnostic\n      modelConfigType = \"diagnostic\"\n   else\n   !   call nwmCheck(diagFlag,1,'ERROR: Invalid IOC flag provided by namelist file.')\n   endif\nend function GetModelConfigType\n\nsubroutine output_chrt_NWM(domainId)\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst\n   use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n   use module_NWM_io_dict\n   use netcdf\n#ifdef MPP_LAND\n   use module_mpp_land\n   use module_mpp_reachls,  only: ReachLS_write_io\n#endif\n   implicit none\n\n   ! Pass in \"did\" value from hydro driving program.\n   integer, intent(in) :: domainId\n\n   ! Derived types.\n   type(chrtMeta) :: fileMeta\n\n   ! Local variables\n   integer :: nudgeFlag, mppFlag, diagFlag\n   integer :: minSinceSim ! Number of minutes since beginning of simulation.\n   integer :: minSinceEpoch1 ! Number of minutes from EPOCH to the beginning of the model simulation.\n   integer :: minSinceEpoch ! Number of minutes from EPOCH to the current model valid time.\n   character(len=16) :: epochDate ! EPOCH represented as a string.\n   character(len=16) :: startDate ! Start of model simulation, represented as a string.\n   character(len=256) :: output_flnm ! CHRTOUT_DOMAIN filename\n   integer :: iret ! NetCDF return statuses\n   integer :: ftn ! NetCDF file handle\n   character(len=256) :: validTime ! Global attribute time string\n   character(len=256) :: initTime ! Global attribute time string\n   integer :: dimId(3) ! Dimension ID values created during NetCDF created.\n   integer :: varId ! Variable ID value created as NetCDF variables are created and populated.\n   integer :: timeId ! Dimension ID for the time dimension.\n   integer :: refTimeId ! Dimension ID for the reference time dimension.\n   integer :: coordVarId ! Variable to hold crs\n   integer :: featureVarId, elevVarId, orderVarId ! Misc NetCDF variable id values\n   integer :: latVarId, lonVarId ! Lat/lon NetCDF variable id values.\n   integer :: varRange(2) ! Local storage of min/max valid range values.\n   real :: varRangeReal(2) ! Local storage of min/max valid range values.\n   integer :: gSize ! Global size of channel point array.\n   integer :: indVarId,ftnRt ! values related to extraction of ascending order index values from the RouteLink file.\n   integer :: iTmp, indTmp ! Misc integer values.\n   integer :: ierr, myId ! MPI return status, process ID\n   integer :: ascFlag ! Flag for if ascendingIndex is present\n   ! Establish local, allocatable arrays\n   ! These are used to hold global output arrays, and global output arrays after\n   ! sorting has taken place by ascending feature_id value.\n   real, allocatable, dimension(:) :: strFlowLocal,velocityLocal,qlossLocal\n   real, allocatable, dimension(:,:) :: g_qlink\n   integer, allocatable, dimension(:) :: g_order\n   integer(kind=int64), allocatable, dimension(:) :: g_linkid\n   real, allocatable, dimension(:) :: g_chlat,g_chlon,g_hlink,g_zelev\n   real, allocatable, dimension(:) :: g_QLateral,g_velocity,g_qloss\n   real, allocatable, dimension(:) :: g_nudge,g_qSfcLatRunoff\n   real, allocatable, dimension(:) :: g_qBucket,g_qBtmVertRunoff,g_accBucket\n   real*8, allocatable, dimension(:) :: g_accSfcLatRunoff\n   real, allocatable, dimension(:,:) :: g_qlinkOut\n   integer, allocatable, dimension(:) :: g_orderOut\n   integer(kind=int64), allocatable, dimension(:) :: g_linkidOut\n   real, allocatable, dimension(:) :: g_chlatOut,g_chlonOut,g_hlinkOut,g_zelevOut\n   real, allocatable, dimension(:) :: g_QLateralOut,g_velocityOut,g_qlossOut\n   real, allocatable, dimension(:) :: g_nudgeOut,g_qSfcLatRunoffOut\n   real, allocatable, dimension(:) :: g_qBucketOut,g_qBtmVertRunoffOut,g_accBucketOut\n   real*8, allocatable, dimension(:) :: g_accSfcLatRunoffOut\n   real, allocatable, dimension(:,:) :: varOutReal   ! Array holding output variables in real format\n   integer, allocatable, dimension(:) :: varOutInt ! Array holding output variables after\n                                                     ! scale_factor/add_offset have been applied.\n   integer, allocatable, dimension(:) :: chIndArray ! Array of index values for\n   !each channel point. feature_id will need to be sorted in ascending order once\n   !data is collected into the global array. From there, the index values are\n   !re-sorted, and used to re-sort output arrays.\n   integer, allocatable, dimension(:) :: g_outInd ! Array of index values for strahler order.\n   integer :: numPtsOut\n   real, allocatable, dimension(:,:) :: varMetaReal\n   integer, allocatable, dimension(:,:) :: varMetaInt\n   integer(kind=int64), allocatable, dimension(:,:) :: varMetaInt8\n\n   character (len=64) :: modelConfigType ! This is character verion (long name) for the io_config_outputs\n\n   ! Initialize the ascFlag to 1\n   ascFlag = 1\n\n   ! Establish macro variables to hlep guide this subroutine.\n#ifdef WRF_HYDRO_NUDGING\n   nudgeFlag = 1\n#else\n   nudgeFlag = 0\n#endif\n\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   if(nlst(domainId)%CHRTOUT_DOMAIN .eq. 0) then\n      ! No output requested here, return to parent calling program/subroutine.\n      return\n   endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Initialize NWM dictionary derived type containing all the necessary metadat\n   ! for the output file.\n   call initChrtDict(fileMeta,diagFlag,myId)\n\n   ! Depending on the NWM forecast config, we will be outputting different\n   ! varibles. DO NOT MODIFY THESE ARRAYS WITHOUT CONSULTING NCAR OR\n   ! OWP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n   if (nlst(1)%io_config_outputs .eq. 0) then\n      ! All\n      fileMeta%outFlag(:) = [1,1,1,1,1,0,0,0,0,0,0]\n   else if (nlst(1)%io_config_outputs .eq. 1) then\n      ! Analysis and Assimilation\n      fileMeta%outFlag(:) = [1,0,0,1,0,0,0,0,0,0,0]\n   else if (nlst(1)%io_config_outputs .eq. 2) then\n      ! Short Range\n      fileMeta%outFlag(:) = [1,0,0,1,0,0,0,0,0,0,0]\n   else if (nlst(1)%io_config_outputs .eq. 3) then\n      ! Medium Range\n      fileMeta%outFlag(:) = [1,0,0,1,0,0,0,0,0,0,0]\n   else if (nlst(1)%io_config_outputs .eq. 4) then\n      ! Long Range\n      fileMeta%outFlag(:) = [1,0,0,1,0,0,0,0,0,0,0]\n   else if (nlst(1)%io_config_outputs .eq. 5) then\n      ! Retrospective\n      fileMeta%outFlag(:) = [1,0,1,1,0,0,0,0,0,0,0]\n   else if (nlst(1)%io_config_outputs .eq. 6) then\n      ! Diagnostics\n      fileMeta%outFlag(:) = [1,0,1,1,0,0,0,0,0,0,0]\n   else\n      call nwmCheck(diagFlag,1,'ERROR: Invalid IOC flag provided by namelist file.')\n   endif\n\n   ! Turn off streamflow, velocity, head for special external channel routing config\n   if (nlst(domainId)%channel_bypass) then\n      fileMeta%outFlag(1) = 0\n      fileMeta%outFlag(2) = 0\n      fileMeta%outFlag(4) = 0\n      fileMeta%outFlag(5) = 0\n   endif\n\n   ! call the GetModelConfigType function\n   modelConfigType = GetModelConfigType(nlst(1)%io_config_outputs)\n\n   ! First step is to collect and assemble all data that will be written to the\n   ! NetCDF file. If we are not using MPI, we bypass the collection step through\n   ! MPI.\n   if(mppFlag .eq. 1) then\n      if(nlst(domainId)%channel_option .ne. 3) then\n         gsize = rt_domain(domainId)%gnlinksl\n      else\n         gsize = rt_domain(domainId)%gnlinks\n      endif\n\n      if(myId .eq. 0) then\n         ! Allocate memory for output.\n         allocate(g_chlon(gsize))\n         allocate(g_chlat(gsize))\n         allocate(g_hlink(gsize))\n         allocate(g_zelev(gsize))\n         allocate(g_qlink(gsize,2))\n         allocate(g_order(gsize))\n         allocate(g_linkid(gsize))\n         allocate(g_QLateral(gsize))\n         allocate(g_velocity(gsize))\n         allocate(g_nudge(gsize))\n         allocate(g_qSfcLatRunoff(gsize))\n         allocate(g_qBucket(gsize))\n         allocate(g_qBtmVertRunoff(gsize))\n         allocate(g_accSfcLatRunoff(gsize))\n         allocate(g_accBucket(gsize))\n         allocate(g_chlonOut(gsize))\n         allocate(g_chlatOut(gsize))\n         allocate(g_hlinkOut(gsize))\n         allocate(g_zelevOut(gsize))\n         allocate(g_qlinkOut(gsize,2))\n         allocate(g_orderOut(gsize))\n         allocate(g_QLateralOut(gsize))\n         allocate(g_velocityOut(gsize))\n         allocate(g_nudgeOut(gsize))\n         allocate(g_qSfcLatRunoffOut(gsize))\n         allocate(g_qBucketOut(gsize))\n         allocate(g_qBtmVertRunoffOut(gsize))\n         allocate(g_accSfcLatRunoffOut(gsize))\n         allocate(g_accBucketOut(gsize))\n         allocate(chIndArray(gsize))\n         allocate(g_linkidOut(gsize))\n         allocate(g_outInd(gsize))\n         if (nlst(domainId)%channel_loss_option > 0) then\n            allocate(g_qloss(gsize))\n            allocate(g_qlossOut(gsize))\n         end if\n      else\n         allocate(g_chlon(1))\n         allocate(g_chlat(1))\n         allocate(g_hlink(1))\n         allocate(g_zelev(1))\n         allocate(g_qlink(1,2))\n         allocate(g_order(1))\n         allocate(g_linkid(1))\n         allocate(g_QLateral(1))\n         allocate(g_velocity(1))\n         allocate(g_nudge(1))\n         allocate(g_qSfcLatRunoff(1))\n         allocate(g_qBucket(1))\n         allocate(g_qBtmVertRunoff(1))\n         allocate(g_accSfcLatRunoff(1))\n         allocate(g_accBucket(1))\n         allocate(g_chlonOut(1))\n         allocate(g_chlatOut(1))\n         allocate(g_hlinkOut(1))\n         allocate(g_zelevOut(1))\n         allocate(g_qlinkOut(1,2))\n         allocate(g_orderOut(1))\n         allocate(g_QLateralOut(1))\n         allocate(g_velocityOut(1))\n         allocate(g_nudgeOut(1))\n         allocate(g_qSfcLatRunoffOut(1))\n         allocate(g_qBucketOut(1))\n         allocate(g_qBtmVertRunoffOut(1))\n         allocate(g_accSfcLatRunoffOut(1))\n         allocate(g_accBucketOut(1))\n         allocate(chIndArray(1))\n         allocate(g_linkidOut(1))\n         allocate(g_outInd(1))\n         if (nlst(domainId)%channel_option == 2 .and. nlst(domainId)%channel_loss_option > 0) then\n            allocate(g_qloss(1))\n            allocate(g_qlossOut(1))\n         end if\n      endif\n\n      ! Allocate local streamflow and velocity arrays. We need to do a check to\n      ! for lake_type 2. However, we cannot set the values in the global array\n      ! to missing as this causes the model to crash.\n      allocate(strFlowLocal(RT_DOMAIN(domainId)%NLINKS))\n      allocate(velocityLocal(RT_DOMAIN(domainId)%NLINKS))\n      strFlowLocal = RT_DOMAIN(domainId)%QLINK(:,1)\n      velocityLocal = RT_DOMAIN(domainId)%velocity\n      ! TML: Add qloss allocation and compute variable, only for channel\n      ! option #2, where qloss is active (muskingum-cunge).\n      if(nlst(domainId)%channel_option == 2 .and. nlst(domainId)%channel_loss_option > 0) then\n         allocate(qlossLocal(RT_DOMAIN(domainId)%NLINKS))\n         qlossLocal = RT_DOMAIN(domainId)%qloss !TML temp fix to test code\n      endif\n\n      ! Loop through all the local links on this processor. For lake_type\n      ! of 2, we need to manually set the streamflow and velocity values\n      ! to the model NDV value.\n      if (RT_DOMAIN(domainId)%NLAKES .gt. 0) then\n         do iTmp=1,RT_DOMAIN(domainId)%NLINKS\n            if (RT_DOMAIN(domainId)%TYPEL(iTmp) .eq. 2) then\n               strFlowLocal(iTmp) = fileMeta%modelNdv\n               velocityLocal(iTmp) = fileMeta%modelNdv\n               if(nlst(domainId)%channel_option == 2 .and. nlst(domainId)%channel_loss_option > 0) then\n                  qlossLocal(iTmp) = fileMeta%modelNdv\n               endif\n            endif\n         end do\n      endif\n\n      ! Collect arrays from various processors through MPI, and\n      ! assemble into global arrays previously allocated.\n      if(nlst(domainId)%channel_option .ne. 3) then\n         ! Reach-based routing collection\n#ifdef MPP_LAND\n         call ReachLS_write_io(strFlowLocal,g_qlink(:,1))\n         call ReachLS_write_io(RT_DOMAIN(domainId)%QLINK(:,2),g_qlink(:,2))\n         call ReachLS_write_io(RT_DOMAIN(domainId)%ORDER,g_order)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%linkid,g_linkid)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%CHLAT,g_chlat)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%CHLON,g_chlon)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%ZELEV,g_zelev)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%QLateral,g_QLateral)\n         call ReachLS_write_io(velocityLocal,g_velocity)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%HLINK,g_hlink)\n         ! Optional outputs\n         if(nudgeFlag .eq. 1)then\n#ifdef WRF_HYDRO_NUDGING\n            fileMeta%outFlag(2) = 1 ! Set output flag to on.\n            call ReachLS_write_io(RT_DOMAIN(domainID)%nudge,g_nudge)\n#endif\n         else\n            fileMeta%outFlag(2) = 0 ! Set output flag to off.\n         endif\n         ! TML: Only produce qloss output if routing option 2 is selected\n         if(nlst(domainId)%channel_option .eq. 2 .and. nlst(domainId)%channel_loss_option > 0) then\n            fileMeta%outFlag(11) = 1\n            call ReachLS_write_io(qlossLocal,g_qloss)\n         endif\n         if(nlst(domainId)%UDMP_OPT .eq. 1) then\n            ! Currently, we only allow channel-only outputs to be produced for\n            ! NWM configurations.\n            if(nlst(domainId)%output_channelBucket_influx .eq. 1 .or. &\n               nlst(domainId)%output_channelBucket_influx .eq. 2) then\n               fileMeta%outFlag(6) = 1\n               fileMeta%outFlag(7) = 1\n               call ReachLS_write_io(RT_DOMAIN(domainId)%qSfcLatRunoff,g_qSfcLatRunoff)\n               call ReachLS_write_io(RT_DOMAIN(domainId)%qBucket,g_qBucket)\n            endif\n            if(nlst(domainId)%output_channelBucket_influx .eq. 2 .and. &\n               nlst(domainId)%channel_only                .eq. 0         ) then\n               fileMeta%outFlag(8) = 1\n               call ReachLS_write_io(RT_DOMAIN(domainId)%qin_gwsubbas,g_qBtmVertRunoff)\n            endif\n            if(nlst(domainId)%output_channelBucket_influx .eq. 3) then\n               !! JLM: unsure the following will work... but this is caveated in namelist.\n               fileMeta%outFlag(9) = 1\n               fileMeta%outFlag(10) = 1\n               call ReachLS_write_io(RT_DOMAIN(domainId)%accSfcLatRunoff,g_accSfcLatRunoff)\n               call ReachLS_write_io(RT_DOMAIN(domainId)%qBucket,g_accBucket)\n            endif\n         else\n            if(nlst(domainId)%output_channelBucket_influx .ne. 0) then\n               ! For reach-based routing (non-NWM), we currently do not support\n               ! these outputs. Politely alert the user.....\n               call postDiagMsg(diagFlag,'WARNING: Channel-only outputs not available for UDMPT = 0 on reach-based routing.')\n            endif\n         endif\n#endif\n      else\n         ! Gridded routing collection\n         call write_chanel_real(strFlowLocal,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_qlink(:,1))\n         call write_chanel_real(RT_DOMAIN(domainId)%QLINK(:,2),rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_qlink(:,2))\n         call write_chanel_real(RT_DOMAIN(domainId)%CHLAT,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_chlat)\n         call write_chanel_real(RT_DOMAIN(domainId)%CHLON,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_chlon)\n         call write_chanel_real(RT_DOMAIN(domainId)%HLINK,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_hlink)\n         call write_chanel_int(RT_DOMAIN(domainId)%ORDER,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_order)\n         call write_chanel_int8(RT_DOMAIN(domainId)%linkid,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_linkid)\n         call write_chanel_real(RT_DOMAIN(domainId)%ZELEV,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_zelev)\n         call write_chanel_real(RT_DOMAIN(domainId)%QLateral,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_QLateral)\n         call write_chanel_real(velocityLocal,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_velocity)\n         if(nlst(domainId)%output_channelBucket_influx .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: This channelBucket_influx only available for reach-based routing.')\n         endif\n         if(nudgeFlag .eq. 1)then\n#ifdef WRF_HYDRO_NUDGING\n            fileMeta%outFlag(2) = 1 ! Set output flag to on.\n            call write_chanel_real(RT_DOMAIN(domainID)%nudge,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_nudge)\n#endif\n         else\n            fileMeta%outFlag(2) = 0 ! Set output flag to off.\n         endif\n      endif\n\n   else\n      gSize = rt_domain(domainId)%nlinksl\n      ! No MPI - We are running on a single processor\n      allocate(g_chlon(gsize))\n      allocate(g_chlat(gsize))\n      allocate(g_hlink(gsize))\n      allocate(g_zelev(gsize))\n      allocate(g_qlink(gsize,2))\n      allocate(g_order(gsize))\n      allocate(g_linkid(gsize))\n      allocate(g_QLateral(gsize))\n      allocate(g_velocity(gsize))\n      allocate(g_nudge(gsize))\n      allocate(g_qSfcLatRunoff(gsize))\n      allocate(g_qBucket(gsize))\n      allocate(g_qBtmVertRunoff(gsize))\n      allocate(g_accSfcLatRunoff(gsize))\n      allocate(g_accBucket(gsize))\n      allocate(g_chlonOut(gsize))\n      allocate(g_chlatOut(gsize))\n      allocate(g_hlinkOut(gsize))\n      allocate(g_zelevOut(gsize))\n      allocate(g_qlinkOut(gsize,2))\n      allocate(g_orderOut(gsize))\n      allocate(g_QLateralOut(gsize))\n      allocate(g_velocityOut(gsize))\n      allocate(g_nudgeOut(gsize))\n      allocate(g_qSfcLatRunoffOut(gsize))\n      allocate(g_qBucketOut(gsize))\n      allocate(g_qBtmVertRunoffOut(gsize))\n      allocate(g_accSfcLatRunoffOut(gsize))\n      allocate(g_accBucketOut(gsize))\n      allocate(chIndArray(gsize))\n      allocate(g_linkidOut(gsize))\n      allocate(g_outInd(gsize))\n      g_chlon = RT_DOMAIN(domainId)%CHLON\n      g_chlat = RT_DOMAIN(domainId)%CHLAT\n      g_zelev = RT_DOMAIN(domainId)%ZELEV\n      g_order = RT_DOMAIN(domainId)%ORDER\n      g_linkid = RT_DOMAIN(domainId)%linkid\n      g_hlink = RT_DOMAIN(domainId)%HLINK\n      g_qlink = RT_DOMAIN(domainId)%QLINK\n      g_QLateral = RT_DOMAIN(domainId)%QLateral\n      g_velocity = RT_DOMAIN(domainId)%velocity\n      ! Optional outputs\n      if(nudgeFlag .eq. 1)then\n#ifdef WRF_HYDRO_NUDGING\n         fileMeta%outFlag(2) = 1 ! Set output flag to on.\n         g_nudge = RT_DOMAIN(domainID)%nudge\n#endif\n      endif\n      ! TML: Only produce qloss output if routing option 2 is selected\n      if(nlst(domainId)%channel_option == 2 .and. nlst(domainId)%channel_loss_option > 0) then\n         allocate(g_qloss(gsize))\n         allocate(g_qlossOut(gsize))\n         fileMeta%outFlag(11) = 1\n         g_qloss = RT_DOMAIN(domainId)%qloss\n      endif\n      if(nlst(domainId)%UDMP_OPT .eq. 1) then\n         ! Currently, we only allow channel-only outputs to be produced for\n         ! NWM configurations.\n         if(nlst(domainId)%output_channelBucket_influx .eq. 1 .or. &\n            nlst(domainId)%output_channelBucket_influx .eq. 2) then\n            fileMeta%outFlag(6) = 1\n            fileMeta%outFlag(7) = 1\n            g_qSfcLatRunoff = RT_DOMAIN(domainId)%qSfcLatRunoff\n            g_qBucket = RT_DOMAIN(domainId)%qBucket\n         endif\n         if(nlst(domainId)%output_channelBucket_influx .eq. 2) then\n            fileMeta%outFlag(8) = 1\n            g_qBtmVertRunoff = RT_DOMAIN(domainId)%qin_gwsubbas\n         endif\n         if(nlst(domainId)%output_channelBucket_influx .eq. 3) then\n            fileMeta%outFlag(9) = 1\n            fileMeta%outFlag(10) = 1\n            g_accSfcLatRunoff = RT_DOMAIN(domainId)%accSfcLatRunoff\n            g_accBucket = RT_DOMAIN(domainId)%qBucket\n         endif\n      else\n         if(nlst(domainId)%output_channelBucket_influx .ne. 0) then\n            ! For reach-based routing (non-NWM), we currently do not support\n            ! these outputs. Politely alert the user.....\n            call postDiagMsg(diagFlag,'WARNING: Channel-only outputs not available for UDMPT = 0 on reach-based routing.')\n         endif\n      endif\n   endif\n\n   ! Calculate datetime information.\n   ! First compose strings of EPOCH and simulation start date.\n   epochDate = trim(\"1970-01-01 00:00\")\n   startDate = trim(nlst(domainId)%startdate(1:4)//\"-\"//&\n                    nlst(domainId)%startdate(6:7)//&\n                    &\"-\"//nlst(domainId)%startdate(9:10)//\" \"//&\n                    nlst(domainId)%startdate(12:13)//\":\"//&\n                    nlst(domainId)%startdate(15:16))\n   ! Second, utilize NoahMP date utilities to calculate the number of minutes\n   ! from EPOCH to the beginning of the model simulation.\n   call geth_idts(startDate,epochDate,minSinceEpoch1)\n   ! Third, calculate the number of minutes since the beginning of the\n   ! simulation.\n   minSinceSim = int(nlst(1)%out_dt*(rt_domain(1)%out_counts-1))\n   ! Fourth, calculate the total number of minutes from EPOCH to the current\n   ! model time step.\n   minSinceEpoch = minSinceEpoch1 + minSinceSim\n   ! Fifth, compose global attribute time strings that will be used.\n   validTime = trim(nlst(domainId)%olddate(1:4)//'-'//&\n                    nlst(domainId)%olddate(6:7)//'-'//&\n                    nlst(domainId)%olddate(9:10)//'_'//&\n                    nlst(domainId)%olddate(12:13)//':'//&\n                    nlst(domainId)%olddate(15:16)//&\n                    &':00')\n   initTime = trim(nlst(domainId)%startdate(1:4)//'-'//&\n                  nlst(domainId)%startdate(6:7)//'-'//&\n                  nlst(domainId)%startdate(9:10)//'_'//&\n                  nlst(domainId)%startdate(12:13)//':'//&\n                  nlst(domainId)%startdate(15:16)//&\n                  &':00')\n   ! Replace default values in the dictionary.\n   fileMeta%initTime = trim(initTime)\n   fileMeta%validTime = trim(validTime)\n\n   ! calculate the minimum and maximum time\n   fileMeta%timeValidMin = minSinceEpoch1 + nlst(1)%out_dt\n   fileMeta%timeValidMax = minSinceEpoch1 + int(nlst(1)%khour * 60/nlst(1)%out_dt) * nlst(1)%out_dt\n\n   ! calculate total_valid_time\n   fileMeta%totalValidTime = int(nlst(1)%khour * 60 / nlst(1)%out_dt)  ! # number of valid time (#of output files)\n\n   ! Compose output file name.\n   write(output_flnm, '(A12,\".CHRTOUT_DOMAIN\",I1)')nlst(domainId)%olddate(1:4)//&\n         nlst(domainId)%olddate(6:7)//nlst(domainId)%olddate(9:10)//&\n         nlst(domainId)%olddate(12:13)//nlst(domainId)%olddate(15:16), nlst(domainId)%igrid\n\n   ! Only run NetCDF library calls to output data if we are on the master\n   ! processor.\n   if(myId .eq. 0) then\n      if(nlst(domainId)%channel_option .ne. 3) then\n         ! Read in index values from Routelink that will be used to sort output\n         ! variables by ascending feature_id.\n         iret = orchestrator%IO_Manager%netcdf_layer%open_file(trim(nlst(1)%route_link_f),NF90_NOWRITE,ncid=ftnRt)\n         !iret = nf90_open(trim(nlst(1)%route_link_f),NF90_NOWRITE,ncid=ftnRt)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to open RouteLink file for index extraction')\n         iret = nf90_inq_varid(ftnRt,'ascendingIndex',indVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: ascendingIndex not found in RouteLink file. No resorting will take place.')\n            ascFlag = 0\n         endif\n         if(ascFlag .eq. 1) then\n            iret = nf90_get_var(ftnRt,indVarId,chIndArray)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to extract ascendingIndex from RouteLink file.')\n         endif\n         iret = nf90_close(ftnRt)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close RouteLink file.')\n      else\n         ascFlag = 0\n      endif\n      ! Place all output arrays into one real array that will be looped over\n      ! during conversion to compressed integer format.\n      if(ascFlag .eq. 1) then\n         ! Sort feature_id values by ascending values using the index array\n         ! extracted from the RouteLink file.\n         do iTmp=1,gSize\n            indTmp = chIndArray(iTmp)\n            indTmp = indTmp + 1 ! Python starts index values at 0, so we need to add one.\n            g_linkidOut(iTmp) = g_linkid(indTmp)\n            g_qlinkOut(iTmp,1) = g_qlink(indTmp,1)\n            g_nudgeOut(iTmp) = g_nudge(indTmp)\n            g_QLateralOut(iTmp) = g_QLateral(indTmp)\n            g_velocityOut(iTmp) = g_velocity(indTmp)\n            g_hlinkOut(iTmp) = g_hlink(indTmp)\n            g_qSfcLatRunoffOut(iTmp) = g_qSfcLatRunoff(indTmp)\n            g_qBucketOut(iTmp) = g_qBucket(indTmp)\n            g_qBtmVertRunoffOut(iTmp) = g_qBtmVertRunoff(indTmp)\n            g_accSfcLatRunoffOut(iTmp) = g_accSfcLatRunoff(indTmp)\n            g_accBucketOut(iTmp) = g_accBucket(indTmp)\n            g_chlatOut(iTmp) = g_chlat(indTmp)\n            g_chlonOut(iTmp) = g_chlon(indTmp)\n            g_orderOut(iTmp) = g_order(indTmp)\n            g_zelevOut(iTmp) = g_zelev(indTmp)\n            if(nlst(domainId)%channel_option == 2 .and. nlst(domainId)%channel_loss_option > 0) then\n               g_qlossOut(iTmp) = g_qloss(indTmp)\n            end if\n         end do\n      else\n         g_linkidOut = g_linkid\n         g_qlinkOut(:,1) = g_qlink(:,1)\n         g_nudgeOut = g_nudge\n         g_QLateralOut = g_QLateral\n         g_velocityOut = g_velocity\n         g_hlinkOut = g_hlink\n         g_qSfcLatRunoffOut = g_qSfcLatRunoff\n         g_qBucketOut = g_qBucket\n         g_qBtmVertRunoffOut = g_qBtmVertRunoff\n         g_accSfcLatRunoffOut = g_accSfcLatRunoff\n         g_accBucketOut = g_accBucket\n         g_chlatOut = g_chlat\n         g_chlonOut = g_chlon\n         g_orderOut = g_order\n         g_zelevOut = g_zelev\n         if(nlst(domainId)%channel_option == 2 .and. nlst(domainId)%channel_loss_option > 0) then\n            g_qlossOut = g_qloss\n         end if\n      endif\n\n      ! Calculate index values based on minimum strahler order to write.\n      ! Initialize the index array to 0\n      g_outInd = 0\n\n      where(g_orderOut .ge. nlst(domainId)%order_to_write) g_outInd = 1\n      numPtsOut = sum(g_outInd)\n\n      if(numPtsOut .eq. 0) then\n         ! Write warning message to user showing there are NO channel points to\n         ! write. Simply return to the main calling function.\n         call postDiagMsg(diagFlag,\"WARNING: No channel points found for CHRTOUT.\")\n         return\n      endif\n\n      ! Loop through all channel points if we are running gridded routing.\n      ! Assign an arbitrary index value as the linkid field is read in as 0 from\n      ! the Fulldom file.\n      if(nlst(domainId)%channel_option .eq. 3) then\n         do iTmp=1,gSize\n            g_linkidOut(iTmp) = iTmp\n         end do\n      endif\n\n      allocate(varOutReal(fileMeta%numVars,numPtsOut))\n      allocate(varOutInt(numPtsOut))\n      allocate(varMetaReal(3,numPtsOut))\n      allocate(varMetaInt(1,numPtsOut))\n      allocate(varMetaInt8(1,numPtsOut))\n\n      varOutReal(1,:) = PACK(g_qlinkOut(:,1),g_outInd == 1)\n      varOutReal(2,:) = PACK(g_nudgeOut,g_outInd == 1)\n      varOutReal(3,:) = PACK(g_QLateralOut,g_outInd == 1)\n      varOutReal(4,:) = PACK(g_velocityOut,g_outInd == 1)\n      varOutReal(5,:) = PACK(g_hlinkOut,g_outInd == 1)\n      varOutReal(6,:) = PACK(g_qSfcLatRunoffOut,g_outInd == 1)\n      varOutReal(7,:) = PACK(g_qBucketOut,g_outInd == 1)\n      varOutReal(8,:) = PACK(g_qBtmVertRunoffOut,g_outInd == 1)\n      varOutReal(9,:) = PACK(g_accSfcLatRunoffOut,g_outInd == 1)\n      varOutReal(10,:) = PACK(g_accBucketOut,g_outInd == 1)\n      if(nlst(domainId)%channel_option == 2 .and. nlst(domainId)%channel_loss_option > 0) then\n         varOutReal(11,:) = PACK(g_qlossOut,g_outInd == 1)\n      end if\n\n      varMetaReal(1,:) = PACK(g_chlatOut,g_outInd == 1)\n      varMetaReal(2,:) = PACK(g_chlonOut,g_outInd == 1)\n      varMetaReal(3,:) = PACK(g_zelevOut,g_outInd == 1)\n      varMetaInt(1,:) = PACK(g_orderOut,g_outInd == 1)\n      varMetaInt8(1,:) = PACK(g_linkidOut,g_outInd == 1)\n\n      ! Mask out missing values\n      where ( varOutReal == fileMeta%modelNdv ) varOutReal = -9999.0\n\n      ! Open output NetCDF file for writing.\n      iret = nf90_create(trim(output_flnm),cmode=NF90_NETCDF4,ncid = ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create CHRTOUT NetCDF file.')\n\n      ! Write global attributes.\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"TITLE\",trim(fileMeta%title))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create TITLE attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"compiler_version\",compiler_version())\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create compiler_version attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"featureType\",trim(fileMeta%fType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create featureType attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"proj4\",trim(fileMeta%proj4))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create proj4 attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_initialization_time\",trim(fileMeta%initTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model init attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"station_dimension\",trim(fileMeta%stDim))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create st. dimension attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_valid_time\",trim(fileMeta%validTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model valid attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_total_valid_times\",fileMeta%totalValidTime)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model total valid time attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"stream_order_output\",fileMeta%stOrder)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create order attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"cdm_datatype\",trim(fileMeta%cdm))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create CDM attribute')\n      !iret = nf90_put_att(ftn,NF90_GLOBAL,\"esri_pe_string\",trim(fileMeta%esri))\n      !call nwmCheck(diagFlag,iret,'ERROR: Unable to create ESRI attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"Conventions\",trim(fileMeta%conventions))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create conventions attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"code_version\",trim(get_code_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create code_version attribute')\n#ifdef NWM_META\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"NWM_version_number\",trim(get_nwm_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create NWM_version_number attribute')\n#endif\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_type\",trim(fileMeta%modelOutputType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_output_type attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_configuration\",modelConfigType)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_configuration attribute')\n\n      ! Create global attributes specific to running output through the\n      ! channel-only configuration of the model.\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"dev_OVRTSWCRT\",nlst(domainId)%OVRTSWCRT)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev_OVRTSWCRT attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"dev_NOAH_TIMESTEP\",int(nlst(domainId)%dt))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev_NOAH_TIMESTEP attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"dev_channel_only\",nlst(domainId)%channel_only)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev_channel_only attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"dev_channelBucket_only\",nlst(domainId)%channelBucket_only)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev_channelBucket_only attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'dev','dev_ prefix indicates development/internal meta data')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev attribute')\n\n      ! Create dimensions\n      !iret = nf90_def_dim(ftn,\"feature_id\",gSize,dimId(1))\n      iret = nf90_def_dim(ftn,\"feature_id\",numPtsOut,dimId(1))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create feature_id dimension')\n      iret = nf90_def_dim(ftn,\"time\",NF90_UNLIMITED,dimId(2))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time dimension')\n      iret = nf90_def_dim(ftn,\"reference_time\",1,dimId(3))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time dimension')\n\n      ! Create and populate reference_time and time variables.\n      iret = nf90_def_var(ftn,\"time\",nf90_int,dimId(2),timeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time variable')\n      iret = nf90_put_att(ftn,timeId,'long_name',trim(fileMeta%timeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'standard_name',trim(fileMeta%timeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'units',trim(fileMeta%timeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_min',fileMeta%timeValidMin)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_min attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_max',fileMeta%timeValidMax)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_max attribute into time variable')\n      iret = nf90_def_var(ftn,\"reference_time\",nf90_int,dimId(3),refTimeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'long_name',trim(fileMeta%rTimeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'standard_name',trim(fileMeta%rTimeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'units',trim(fileMeta%rTimeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reference_time variable')\n\n      ! Create a crs variable.\n      ! NOTE - For now, we are hard-coding in for lat/lon points. However, this\n      ! may be more flexible in future iterations.\n      iret = nf90_def_var(ftn,'crs',nf90_char,varid=coordVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'transform_name','latitude longitude')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place transform_name attribute into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'grid_mapping_name','latitude longitude')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping_name attribute into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'esri_pe_string','GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",&\n                                          &SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",&\n                                          &0.0174532925199433]];-400 -400 1000000000;&\n                                          &-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place esri_pe_string into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'spatial_ref','GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",&\n                                          &SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",&\n                                          &0.0174532925199433]];-400 -400 1000000000;&\n                                          &-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place spatial_ref into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'long_name','CRS definition')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'longitude_of_prime_meridian',0.0)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place longitude_of_prime_meridian into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'_CoordinateAxes','latitude longitude')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place _CoordinateAxes into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'semi_major_axis',6378137.0)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place semi_major_axis into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'semi_minor_axis',6356752.31424518)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place semi_minor_axis into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'inverse_flattening',298.257223563)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place inverse_flattening into crs variable.')\n\n      ! Create feature_id variable\n      iret = nf90_def_var(ftn,\"feature_id\",nf90_int64,dimId(1),featureVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create feature_id variable.')\n      iret = nf90_put_att(ftn,featureVarId,'long_name',trim(fileMeta%featureIdLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Uanble to place long_name attribute into feature_id variable')\n      iret = nf90_put_att(ftn,featureVarId,'comment',trim(fileMeta%featureIdComment))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place comment attribute into feature_id variable')\n      iret = nf90_put_att(ftn,featureVarId,'cf_role',trim(fileMeta%cfRole))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place cf_role attribute into feature_id variable')\n\n#ifndef NWM_META\n      ! Create channel lat/lon variables\n      ! NOTE: NWM current operations do not permit the output of latitude and longitude for streamflow.\n      iret = nf90_def_var(ftn,\"latitude\",nf90_float,dimId(1),latVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create latitude variable.')\n      iret = nf90_put_att(ftn,latVarId,'long_name',trim(fileMeta%latLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into latitude variable')\n      iret = nf90_put_att(ftn,latVarId,'standard_name',trim(fileMeta%latStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into latitude variable')\n      iret = nf90_put_att(ftn,latVarId,'units',trim(fileMeta%latUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into latitude variable')\n      iret = nf90_def_var(ftn,\"longitude\",nf90_float,dimId(1),lonVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create longitude variable.')\n      iret = nf90_put_att(ftn,lonVarId,'long_name',trim(fileMeta%lonLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Uanble to place long_name attribute into longitude variable')\n      iret = nf90_put_att(ftn,lonVarId,'standard_name',trim(fileMeta%lonStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into longitude variable')\n      iret = nf90_put_att(ftn,lonVarId,'units',trim(fileMeta%lonUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into longitude variable')\n\n      ! Create channel order variable\n      iret = nf90_def_var(ftn,\"order\",nf90_int,dimId(1),orderVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create order variable.')\n      iret = nf90_put_att(ftn,orderVarId,'long_name',trim(fileMeta%orderLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into order variable')\n      iret = nf90_put_att(ftn,orderVarId,'standard_name',trim(fileMeta%orderStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into order variable')\n\n      ! Create channel elevation variable\n      iret = nf90_def_var(ftn,\"elevation\",nf90_float,dimId(1),elevVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create elevation variable.')\n      iret = nf90_put_att(ftn,elevVarId,'long_name',trim(fileMeta%elevLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into elevation variable')\n      iret = nf90_put_att(ftn,elevVarId,'standard_name',trim(fileMeta%elevStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into elevation variable')\n      iret = nf90_put_att(ftn,elevVarId,'units',trim(fileMeta%elevUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into elevation variable')\n#endif\n\n      ! Define deflation levels for these meta-variables. For now, we are going to\n      ! default to a compression level of 2. Only compress if io_form_outputs is set to 1.\n      if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n         iret = nf90_def_var_deflate(ftn,timeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for time.')\n         iret = nf90_def_var_deflate(ftn,featureVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for feature_id.')\n         iret = nf90_def_var_deflate(ftn,refTimeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reference_time.')\n#ifndef NWM_META\n         iret = nf90_def_var_deflate(ftn,latVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for latitude.')\n         iret = nf90_def_var_deflate(ftn,lonVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for longitude.')\n         iret = nf90_def_var_deflate(ftn,orderVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for order.')\n         iret = nf90_def_var_deflate(ftn,elevVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for elevation.')\n#endif\n      endif\n\n      ! Allocate memory for the output variables, then place the real output\n      ! variables into a single array. This array will be accessed throughout the\n      ! output looping below for conversion to compressed integer values.\n      ! Loop through and create each output variable, create variable attributes,\n      ! and insert data.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            ! First create variable\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_int,dimId(1),varId)\n            else\n               iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_float,dimId(1),varId)\n            endif\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to create variable:'//trim(fileMeta%varNames(iTmp)))\n\n            ! Extract valid range into a 1D array for placement.\n            varRange(1) = fileMeta%validMinComp(iTmp)\n            varRange(2) = fileMeta%validMaxComp(iTmp)\n            varRangeReal(1) = real(fileMeta%validMinDbl(iTmp))\n            varRangeReal(2) = real(fileMeta%validMaxDbl(iTmp))\n\n            ! Establish a compression level for the variables. For now we are using a\n            ! compression level of 2. In addition, we are choosing to turn the shuffle\n            ! filter off for now. Kelley Eicher did some testing with this and\n            ! determined that the benefit wasn't worth the extra time spent writing\n            ! output. Only compress if io_form_outputs is set to 1.\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n               iret = nf90_def_var_deflate(ftn,varId,0,1,2)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression for: '//trim(fileMeta%varNames(iTmp)))\n            endif\n\n            ! Create variable attributes\n            iret = nf90_put_att(ftn,varId,'long_name',trim(fileMeta%longName(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'units',trim(fileMeta%units(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'coordinates',trim(fileMeta%coordNames(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place coordinates attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'grid_mapping','crs')\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'scale_factor',fileMeta%scaleFactor(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place scale_factor attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'add_offset',fileMeta%addOffset(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place add_offset attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRange)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            else\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRangeReal)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            endif\n         endif\n      end do\n\n      ! Remove NetCDF file from definition mode.\n      iret = nf90_enddef(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to take CHRTOUT file out of definition mode')\n\n      ! Loop through all possible output variables, and convert floating points\n      ! to integers via prescribed scale_factor/add_offset, then write to the\n      ! NetCDF variable.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            ! We are outputing this variable.\n            ! Convert reals to integer. If this is time zero, check to see if we\n            ! need to convert all data to NDV\n            if(minSinceSim .eq. 0 .and. fileMeta%timeZeroFlag(iTmp) .eq. 0) then\n               varOutInt(:) = fileMeta%fillComp(iTmp)\n               varOutReal(iTmp,:) = fileMeta%fillReal(iTmp)\n            else\n               varOutInt(:) = NINT((varOutReal(iTmp,:)-fileMeta%addOffset(iTmp))/fileMeta%scaleFactor(iTmp))\n            endif\n            ! Get NetCDF variable id.\n            iret = nf90_inq_varid(ftn,trim(fileMeta%varNames(iTmp)),varId)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find variable ID for var: '//trim(fileMeta%varNames(iTmp)))\n            ! Put data into NetCDF file\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_var(ftn,varId,varOutInt)\n            else\n               iret = nf90_put_var(ftn,varId,varOutReal(iTmp,:))\n            endif\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into output variable: '//trim(fileMeta%varNames(iTmp)))\n         endif\n      end do\n\n      ! Place link ID values into the NetCDF file\n      iret = nf90_inq_varid(ftn,'feature_id',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate feature_id in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,varMetaInt8(1,:))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into feature_id output variable.')\n\n#ifndef NWM_META\n      iret = nf90_inq_varid(ftn,'latitude',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate latitude in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,varMetaReal(1,:))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into latitude output variable.')\n\n      iret = nf90_inq_varid(ftn,'longitude',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate longitude in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,varMetaReal(2,:))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into longitude output variable.')\n\n      iret = nf90_inq_varid(ftn,'order',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate order in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,varMetaInt(1,:))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into order output variable.')\n\n      iret = nf90_inq_varid(ftn,'elevation',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate elevation in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,varMetaReal(3,:))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into elevation output variable.')\n#endif\n\n      ! Place time values into time variables.\n      iret = nf90_inq_varid(ftn,'time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into time variable')\n      iret = nf90_inq_varid(ftn,'reference_time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reference_time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch1)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into reference_time variable')\n\n      ! Close the output file\n      iret = nf90_close(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close CHRTOUT file.')\n\n   endif ! End if we are on master processor.\n\n   ! Deallocate all memory.\n   if(myId .eq. 0) then\n      deallocate(varOutReal)\n      deallocate(varOutInt)\n      deallocate(varMetaReal)\n      deallocate(varMetaInt)\n      deallocate(varMetaInt8)\n   endif\n   deallocate(g_chlonOut)\n   deallocate(g_chlatOut)\n   deallocate(g_hlinkOut)\n   deallocate(g_zelevOut)\n   deallocate(g_qlinkOut)\n   deallocate(g_orderOut)\n   deallocate(g_QLateralOut)\n   deallocate(g_velocityOut)\n   deallocate(g_nudgeOut)\n   deallocate(g_qSfcLatRunoffOut)\n   deallocate(g_qBucketOut)\n   deallocate(g_qBtmVertRunoffOut)\n   deallocate(g_accSfcLatRunoffOut)\n   deallocate(g_accBucketOut)\n   deallocate(chIndArray)\n   deallocate(g_linkidOut)\n   deallocate(g_chlon)\n   deallocate(g_chlat)\n   deallocate(g_hlink)\n   deallocate(g_zelev)\n   deallocate(g_qlink)\n   deallocate(g_order)\n   deallocate(g_linkid)\n   deallocate(g_QLateral)\n   deallocate(g_nudge)\n   deallocate(g_qSfcLatRunoff)\n   deallocate(g_qBucket)\n   deallocate(g_qBtmVertRunoff)\n   deallocate(g_accSfcLatRunoff)\n   deallocate(g_accBucket)\n   deallocate(strFlowLocal)\n   deallocate(velocityLocal)\n   if (allocated(qlossLocal)) then\n      deallocate(qlossLocal)\n   end if\n   if (allocated(g_qlossOut)) then\n      deallocate(g_qlossOut)\n   end if\n\n   deallocate(g_outInd)\n\nend subroutine output_chrt_NWM\n\n!==============================================================================\n! Program Name: output_NoahMP_NWM\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Output routine for NoahMP grids for the National Water Model.\n! History Log:\n! 3/6/17 -Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files: None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\n\nsubroutine output_NoahMP_NWM(outDir,iGrid,output_timestep,itime,startdate,date,ixPar,jxPar,zNum,varReal,vegTyp,varInd)\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst, noah_lsm\n   use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n   use module_NWM_io_dict\n   use netcdf\n#ifdef MPP_LAND\n     use module_mpp_land\n#endif\n   implicit none\n\n   ! Subroutine arguments\n   character(len=*), intent(in) :: outDir ! Output directory to place output.\n   integer, intent(in) :: iGrid ! Grid number\n   integer, intent(in) :: output_timestep ! Output timestep we are on.\n   integer, intent(in) :: itime ! the noalMP time step we are in\n   character(len=19),intent(in) :: startdate ! Model simulation start date\n   character(len=19),intent(in) :: date ! Current model date\n   integer, intent(in) :: ixPar,jxPar ! I/J dimensions of local grid.\n   integer, intent(in) :: zNum ! Number of vertical layers (most of the time 1)\n   real, intent(in) :: varReal(ixPar,zNum,jxPar) ! Variable data to be written.\n   integer, intent(inout) :: vegTyp(ixPar,jxPar) ! Vegetation type grid used to mask out variables.\n   integer, intent(in) :: varInd ! Variable index used to extact meta-data from.\n\n   ! Derived types.\n   type(ldasMeta) :: fileMeta\n\n   ! Local variables\n   integer :: minSinceSim ! Number of minutes since beginning of simulation.\n   integer :: minSinceEpoch1 ! Number of minutes from EPOCH to the beginning of the model simulation.\n   integer :: minSinceEpoch ! Number of minutes from EPOCH to the current model valid time.\n   character(len=16) :: epochDate ! EPOCH represented as a string.\n   character(len=16) :: startDateTmp ! Start of model simulation, represented as a string.\n   character(len=256) :: validTime ! Global attribute time string\n   character(len=256) :: initTime ! Global attribute time string\n   integer :: mppFlag, diagFlag\n   character(len=1024) :: output_flnm ! Output file name\n   integer :: iret ! NetCDF return status\n   integer :: ftn  ! NetCDF file handle\n   integer :: dimId(8) ! NetCDF dimension ID values\n   integer :: varId ! NetCDF variable ID value\n   integer :: timeId ! NetCDF time variable ID\n   integer :: refTimeId ! NetCDF reference_time variable ID\n   integer :: coordVarId ! NetCDF coordinate variable ID\n   integer :: xVarId,yVarId ! NetCDF x/y variable ID\n   integer :: ierr, myId ! MPI related values\n   integer :: varRange(2) ! Local storage of valid min/max values\n   real :: varRangeReal(2) ! Local storage of valid min/max values\n   integer :: iTmp,jTmp,zTmp,jTmp2,iTmp2\n   integer :: ftnGeo,geoXVarId,geoYVarId\n   integer :: waterVal ! Value in HRLDAS in WRFINPUT file used to define water bodies for masking\n   integer :: sfcflag\n   ! Allocatable arrays to hold global output arrays, and local arrays for\n   ! conversion to integers.\n   integer, allocatable, dimension(:,:) :: localCompTmp, globalCompTmp\n   integer, allocatable, dimension(:,:,:) :: globalOutComp\n   real, allocatable, dimension(:,:,:) :: globalOutReal\n   real, allocatable, dimension(:,:) :: globalRealTmp\n   real*8, allocatable, dimension(:) :: yCoord,xCoord,yCoord2\n   real, allocatable, dimension(:,:,:) :: varRealTmp\n   character (len=64) :: modelConfigType ! This is character verion (long name) for the io_config_outputs\n\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Initialize water type to 16.\n   ! NOTE THIS MAY CHANGE IN THE FUTURE!!!!!\n   waterVal = rt_domain(1)%iswater\n\n   ! Initialize overland routing flag for SFCRNOFF outputs\n   sfcflag = 1\n   if (nlst(1)%OVRTSWCRT > 0) then\n     sfcflag = 0\n   endif\n\n   ! Initialize NWM dictionary derived type containing all the necessary\n   ! metadata for the output file.\n   call initLdasDict(fileMeta,myId,diagFlag)\n\n   ! Calculate necessary datetime information that will go into the output file.\n   ! First compose strings of EPOCH and simulation start date.\n   epochDate = trim(\"1970-01-01 00:00\")\n   startDateTmp = trim(nlst(1)%startdate(1:4)//\"-\"//&\n                       nlst(1)%startdate(6:7)//&\n                       &\"-\"//nlst(1)%startdate(9:10)//\" \"//&\n                       nlst(1)%startdate(12:13)//\":\"//&\n                       nlst(1)%startdate(15:16))\n   ! Second, utilize NoahMP date utilities to calculate the number of minutes\n   ! from EPOCH to the beginning of the model simulation.\n   call geth_idts(startDateTmp,epochDate,minSinceEpoch1)\n   ! Third, calculate the number of minutes since the beginning of the\n   ! simulation.\n   minSinceSim = int(itime * nlst(1)%dt / 60)\n   ! Fourth, calculate the total number of minutes from EPOCH to the current\n   ! model time step.\n   minSinceEpoch = minSinceEpoch1 + minSinceSim\n   ! Fifth, compose global attribute time strings that will be used.\n   validTime = trim(nlst(1)%olddate(1:4)//'-'//&\n                    nlst(1)%olddate(6:7)//'-'//&\n                    nlst(1)%olddate(9:10)//'_'//&\n                    nlst(1)%olddate(12:13)//':'//&\n                    nlst(1)%olddate(15:16)//&\n                    &':00')\n   initTime = trim(nlst(1)%startdate(1:4)//'-'//&\n                  nlst(1)%startdate(6:7)//'-'//&\n                  nlst(1)%startdate(9:10)//'_'//&\n                  nlst(1)%startdate(12:13)//':'//&\n                  nlst(1)%startdate(15:16)//&\n                  &':00')\n\n   ! Replace default values in the dictionary.\n   fileMeta%initTime = trim(initTime)\n   fileMeta%validTime = trim(validTime)\n\n   ! calculate the minimum and maximum time\n   fileMeta%timeValidMin = minSinceEpoch1 + output_timestep / 60  !  output_timestep is in seconds\n   fileMeta%timeValidMax = minSinceEpoch1 + int(nlst(1)%khour * 3600 / output_timestep ) * output_timestep / 60\n\n   ! calculate total_valid_time\n   fileMeta%totalValidTime = int(nlst(1)%khour * 3600 / output_timestep )  ! # number of valid time (#of output files)\n\n   ! Depending on the NWM forecast config, we will be outputting different\n   ! varibles. DO NOT MODIFY THESE ARRAYS WITHOUT CONSULTING NCAR OR\n   ! OWP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n   if(nlst(1)%io_config_outputs .eq. 0) then\n      ! All\n      fileMeta%outFlag(:) = [1,1,1,1,1,1,1,1,1,1,& !1-10\n                             1,1,1,1,1,1,1,1,1,1,& !11-20\n                             sfcflag,1,1,1,1,1,1,1,1,1,& !21-30\n                             1,1,1,1,1,1,1,1,1,1,& !31-40\n                             1,1,1,1,1,1,1,1,1,1,& !41-50\n                             1,1,1,1,1,1,1,1,1,1,& !51-60\n                             1,1,1,1,1,1,1,1,1,1,& !61-70\n                             1,1,1,1,1,1,1,1,1,1,& !71-80\n                             1,1,1,1,1,1,1,1,1,1,& !81-90\n                             1,1,1,1,1,1,1,1,&     !91-98\n                             1,1,1,&               !99-101\n                             1,1,1,&               !102-104\n                             1,1,1,&               !105-107\n                             1,1,1,&               !108-110\n                             1,1,1,&               !111-113\n                             1,1,1]                !114\n\n  else if(nlst(1)%io_config_outputs .eq. 1) then\n      ! Analysis and Assimilation\n      fileMeta%outFlag(:) = [0,0,0,0,0,0,0,0,0,0,& !1-10\n                             0,0,0,0,0,0,1,0,0,0,& !11-20\n                             0,0,0,0,0,0,0,0,0,0,& !21-30\n                             0,0,0,0,0,0,0,0,0,0,& !31-40\n                             0,0,0,0,0,0,0,0,0,0,& !41-50\n                             0,0,0,0,0,0,0,0,1,1,& !51-60\n                             0,0,1,1,1,1,1,1,0,1,& !61-70\n                             0,0,0,0,0,0,0,0,0,0,& !71-80\n                             0,0,0,0,0,0,0,0,0,1,& !81-90\n                             0,1,1,0,1,0,0,1,&     !91-98\n                             0,0,0,&               !99-101\n                             0,0,0,&               !102-104\n                             0,0,0,&               !105-107\n                             0,0,0,&               !108-110\n                             0,0,0,&               !111-113\n                             0,0,0]                !114\n\n   else if(nlst(1)%io_config_outputs .eq. 2) then\n      ! Short Range\n      fileMeta%outFlag(:) = [0,0,0,0,0,0,0,0,0,0,& !1-10\n                             0,0,0,0,0,0,0,0,0,0,& !11-20\n                             0,0,0,0,0,0,0,0,0,0,& !21-30\n                             0,0,0,0,0,0,0,0,0,0,& !31-40\n                             0,0,0,0,0,0,0,0,0,0,& !41-50\n                             0,0,0,0,0,0,0,0,0,0,& !51-60\n                             0,0,0,1,1,0,0,1,0,0,& !61-70\n                             0,0,0,0,0,0,0,0,0,0,& !71-80\n                             0,0,0,0,0,0,0,0,0,1,& !81-90\n                             0,0,1,0,1,0,0,0,&     !91-98\n                             0,0,0,&               !99-101\n                             0,0,0,&               !102-104\n                             0,0,0,&               !105-107\n                             0,0,0,&               !108-110\n                             0,0,0,&               !111-113\n                             0,0,0]                !114\n\n   else if(nlst(1)%io_config_outputs .eq. 3) then\n      ! Medium Range\n      fileMeta%outFlag(:) = [0,0,0,0,0,0,0,0,0,0,& !1-10\n                             1,1,1,1,1,0,0,0,0,1,& !11-20\n                             0,0,0,0,0,0,0,1,1,1,& !21-30\n                             0,0,0,0,0,0,0,0,0,0,& !31-40\n                             0,0,0,0,1,0,0,0,0,0,& !41-50\n                             0,0,0,0,0,0,0,0,1,1,& !51-60\n                             0,0,1,1,1,0,1,1,0,1,& !61-70\n                             0,0,0,0,0,0,0,0,0,0,& !71-80\n                             0,0,0,0,0,0,0,0,0,1,& !81-90\n                             1,1,1,0,1,0,0,0,&     !91-98\n                             0,0,0,&               !99-101\n                             0,0,0,&               !102-104\n                             0,0,0,&               !105-107\n                             0,0,0,&               !108-110\n                             0,0,0,&               !111-113\n                             0,0,0]                !114\n\n   else if(nlst(1)%io_config_outputs .eq. 4) then\n      ! Long Range\n      fileMeta%outFlag(:) = [0,0,0,0,0,0,0,0,0,0,& !1-10\n                             0,0,0,0,0,0,0,0,0,1,& !11-20\n                             sfcflag,0,0,0,0,0,0,0,0,0,& !21-30\n                             0,0,0,0,0,0,0,0,0,0,& !31-40\n                             0,0,0,0,0,0,0,0,0,0,& !41-50\n                             0,0,0,0,0,0,0,0,0,0,& !51-60\n                             0,0,0,0,1,0,0,0,0,1,& !61-70\n                             0,0,0,0,0,0,0,0,0,0,& !71-80\n                             0,0,0,0,0,0,0,0,0,1,& !81-90\n                             1,0,1,1,0,0,0,0,&     !91-98\n                             0,0,0,&               !99-101\n                             0,0,0,&               !102-104\n                             0,0,0,&               !105-107\n                             0,0,0,&               !108-110\n                             0,0,0,&               !111-113\n                             0,0,0]                !114\n\n   else if(nlst(1)%io_config_outputs .eq. 5) then\n      ! Retrospective\n      fileMeta%outFlag(:) = [0,0,0,0,0,0,1,0,0,0,& !1-10\n                             1,1,0,1,1,0,1,1,0,1,& !11-20\n                             sfcflag,0,0,0,0,0,0,0,0,0,& !21-30\n                             0,0,0,0,0,0,0,0,0,0,& !31-40\n                             0,0,0,0,1,0,0,0,0,0,& !41-50\n                             0,0,0,0,0,0,0,0,0,0,& !51-60\n                             1,0,1,1,1,1,0,1,1,1,& !61-70\n                             0,0,0,0,0,0,0,0,0,0,& !71-80\n                             0,0,0,0,0,0,0,0,0,1,& !81-90\n                             0,0,0,0,0,1,1,1,&     !91-98\n                             0,0,0,&               !99-101\n                             0,0,0,&               !102-104\n                             0,0,0,&               !105-107\n                             1,1,0,&               !108-110\n                             1,0,0,&               !111-113\n                             1,1,1]                !114\n\n   else if(nlst(1)%io_config_outputs .eq. 6) then\n      ! Diagnostics\n      fileMeta%outFlag(:) = [0,0,0,0,0,0,1,0,0,0,& !1-10\n                             1,1,1,1,1,0,1,1,0,1,& !11-20\n                             sfcflag,0,0,0,0,0,0,1,1,1,& !21-30\n                             0,0,0,0,0,0,0,0,0,0,& !31-40\n                             0,0,0,0,1,0,0,0,0,0,& !41-50\n                             0,0,0,0,0,0,0,0,1,1,& !51-60\n                             1,0,1,1,1,1,1,1,1,1,& !61-70\n                             0,0,0,0,0,0,0,0,0,0,& !71-80\n                             0,0,0,0,0,0,0,0,0,1,& !81-90\n                             1,1,1,1,1,1,1,1,&     !91-98\n                             0,0,0,&               !99-101\n                             0,0,0,&               !102-104\n                             0,0,0,&               !105-107\n                             1,1,0,&               !108-110\n                             1,0,0,&               !111-113\n                             1,1,1]                !114\n   else\n      call nwmCheck(diagFlag,1,'ERROR: Invalid IOC flag provided by namelist file.')\n   endif\n\n   ! ! If crocus is off, these should not be outputted\n   if (noah_lsm%crocus_opt == 0) then\n      fileMeta%outFlag(101) = 0\n      fileMeta%outFlag(102) = 0\n      fileMeta%outFlag(103) = 0\n      fileMeta%outFlag(104) = 0\n      fileMeta%outFlag(108) = 0\n      fileMeta%outFlag(109) = 0\n      fileMeta%outFlag(111) = 0\n      fileMeta%outFlag(114) = 0\n      fileMeta%outFlag(115) = 0\n      fileMeta%outFlag(116) = 0\n      fileMeta%numVars = numLdasVars_crocus_off ! 98\n   end if\n\n   ! call the GetModelConfigType function\n   modelConfigType = GetModelConfigType(nlst(1)%io_config_outputs)\n\n   if(varInd .eq. 1) then\n      ! We are on the first variable, we need to create the output file with\n      ! attributes first.\n      if(myId .eq. 0) then\n         ! We are on the I/O node. Create output file.\n         if (mod(output_timestep,3600) == 0) then\n            write(output_flnm, '(A,\"/\",A12,\".LDASOUT_DOMAIN\",I1)') outdir,date(1:4)//&\n                  date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n         elseif (mod(output_timestep,60) == 0) then\n            write(output_flnm, '(A,\"/\",A12,\".LDASOUT_DOMAIN\",I1)') outdir,date(1:4)//&\n                  date(6:7)//date(9:10)//date(12:13)//date(15:16), igrid\n         else\n            write(output_flnm, '(A,\"/\",A14,\".LDASOUT_DOMAIN\",I1)') outdir,date(1:4)//&\n                  date(6:7)//date(9:10)//date(12:13)//date(15:16)//date(18:19), igrid\n         endif\n\n         iret = nf90_create(trim(output_flnm),cmode=NF90_NETCDF4,ncid = ftn)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create LDASOUT NetCDF file.')\n         ftnNoahMP = ftn\n\n         ! Write global attributes\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,'TITLE',trim(fileMeta%title))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place TITLE attribute into LDASOUT file.')\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,\"compiler_version\",compiler_version())\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create compiler_version attribute')\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,'model_initialization_time',trim(fileMeta%initTime))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place model init time attribute into LDASOUT file.')\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,'model_output_valid_time',trim(fileMeta%validTime))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place model output time attribute into LDASOUT file.')\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,'model_total_valid_times',fileMeta%totalValidTime)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place model total_valid_times attribute into LDASOUT file.')\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,'Conventions',trim(fileMeta%conventions))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place CF conventions attribute into LDASOUT file.')\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,\"code_version\",trim(get_code_version()))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create code_version attribute')\n#ifdef NWM_META\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,\"NWM_version_number\",trim(get_nwm_version()))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create NWM_version_number attribute')\n#endif\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_type\",trim(fileMeta%modelOutputType))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_output_type attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_configuration\",modelConfigType)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_configuration attribute')\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,\"proj4\",trim(fileMeta%proj4))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create proj4 attribute')\n         iret = nf90_put_att(ftnNoahMP,NF90_GLOBAL,\"GDAL_DataType\",\"Generic\")\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create GDAL_DataType attribute')\n\n         ! Create dimensions\n         iret = nf90_def_dim(ftnNoahMP,'time',NF90_UNLIMITED,dimId(1))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define time dimension')\n         iret = nf90_def_dim(ftnNoahMP,'x',global_nx,dimId(2))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define x dimension')\n         iret = nf90_def_dim(ftnNoahMP,'y',global_ny,dimId(3))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define y dimension')\n         iret = nf90_def_dim(ftnNoahMP,'soil_layers_stag',fileMeta%numSoilLayers,dimId(4))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define soil_layers_stag dimension')\n         iret = nf90_def_dim(ftnNoahMP,'snow_layers',fileMeta%numSnowLayers,dimId(5))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define snow_layers dimension')\n         iret = nf90_def_dim(ftnNoahMP,'reference_time',1,dimId(6))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define reference_time dimension')\n         if (noah_lsm%crocus_opt == 1) &\n              iret = nf90_def_dim(ftnNoahMP,'glacier_levels',fileMeta%act_lev,dimId(8))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define act_layers dimension')\n         ! Only create vis_nir if we are outputting the two snow albedo variables.\n         ! Otherwise these are unecessary dimensions.\n         if ((fileMeta%outFlag(96) .eq. 1) .or. (fileMeta%outFlag(96) .eq. 1)) then\n         iret = nf90_def_dim(ftnNoahMP,'vis_nir',fileMeta%numSpectrumBands,dimId(7))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define vis_nir dimension')\n         endif\n\n         ! Create and populate reference_time and time variables.\n         iret = nf90_def_var(ftnNoahMP,\"time\",nf90_int,dimId(1),timeId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create time variable')\n         iret = nf90_put_att(ftnNoahMP,timeId,'long_name',trim(fileMeta%timeLName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into time variable')\n         iret = nf90_put_att(ftnNoahMP,timeId,'standard_name',trim(fileMeta%timeStName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into time variable')\n         iret = nf90_put_att(ftnNoahMP,timeId,'units',trim(fileMeta%timeUnits))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into time variable')\n         iret = nf90_put_att(ftn,timeId,'valid_min',fileMeta%timeValidMin)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_min attribute into time variable')\n         iret = nf90_put_att(ftn,timeId,'valid_max',fileMeta%timeValidMax)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_max attribute into time variable')\n         iret = nf90_def_var(ftnNoahMP,\"reference_time\",nf90_int,dimId(6),refTimeId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time variable')\n         iret = nf90_put_att(ftnNoahMP,refTimeId,'long_name',trim(fileMeta%rTimeLName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into reference_time variable')\n         iret = nf90_put_att(ftnNoahMP,refTimeId,'standard_name',trim(fileMeta%rTimeStName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into reference_time variable')\n         iret = nf90_put_att(ftnNoahMP,refTimeId,'units',trim(fileMeta%rTimeUnits))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reference_time variable')\n\n         ! Create x/y coordinate variables\n         iret = nf90_def_var(ftnNoahMP,'x',nf90_double,dimId(2),xVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create x coordinate variable')\n         do iTmp=1,fileMeta%nxRealAtts\n            iret = nf90_put_att(ftnNoahMP,xVarId,trim(fileMeta%xFloatAttNames(iTmp)),&\n                                fileMeta%xRealAttVals(iTmp,1:fileMeta%xRealAttLen(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place x floating point attributes into LDASOUT file.')\n         end do\n         do iTmp=1,fileMeta%nxCharAtts\n            iret = nf90_put_att(ftnNoahMP,xVarId,trim(fileMeta%xCharAttNames(iTmp)),trim(fileMeta%xCharAttVals(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place x string point attributes into LDASOUT file.')\n         end do\n         iret = nf90_def_var(ftnNoahMP,'y',nf90_double,dimId(3),yVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create y coordinate variable')\n         do iTmp=1,fileMeta%nyRealAtts\n            iret = nf90_put_att(ftnNoahMP,yVarId,trim(fileMeta%yFloatAttNames(iTmp)),&\n                                fileMeta%yRealAttVals(iTmp,1:fileMeta%yRealAttLen(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place y floating point attributes into LDASOUT file.')\n         end do\n         do iTmp=1,fileMeta%nyCharAtts\n            iret = nf90_put_att(ftnNoahMP,yVarId,trim(fileMeta%yCharAttNames(iTmp)),trim(fileMeta%yCharAttVals(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place y string point attributes into LDASOUT file.')\n         end do\n\n         ! Define compression if chosen.\n         if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n            iret = nf90_def_var_deflate(ftn,timeId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for time.')\n            iret = nf90_def_var_deflate(ftn,refTimeId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reference_time.')\n            iret = nf90_def_var_deflate(ftn,xVarId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for x.')\n            iret = nf90_def_var_deflate(ftn,yVarId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for y.')\n         endif\n\n         ! Translate crs variable info from land spatial metadata file to output\n         ! file.\n         iret = nf90_def_var(ftnNoahMP,'crs',nf90_char,varid=coordVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create crs variable in LDASOUT file.')\n         do iTmp=1,fileMeta%nCrsRealAtts\n            iret = nf90_put_att(ftnNoahMP,coordVarId,trim(fileMeta%crsFloatAttNames(iTmp)),&\n                                fileMeta%crsRealAttVals(iTmp,1:fileMeta%crsRealAttLen(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place crs floating point attributes into LDASOUT file.')\n         end do\n         do iTmp=1,fileMeta%nCrsCharAtts\n            iret = nf90_put_att(ftnNoahMP,coordVarId,trim(fileMeta%crsCharAttNames(iTmp)),trim(fileMeta%crsCharAttVals(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place crs string point attributes into LDASOUT file.')\n         end do\n\n         ! Loop through all possible variables and create them, along with their\n         ! metadata attributes.\n         do iTmp=1,fileMeta%numVars\n            if(fileMeta%outFlag(iTmp) .eq. 1) then\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n                  if(fileMeta%numLev(iTmp) .eq. fileMeta%numSoilLayers) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(4),dimId(3),dimId(1)/),varId)\n                  else if(fileMeta%numLev(iTmp) .eq. fileMeta%numSnowLayers) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(5),dimId(3),dimId(1)/),varId)\n                  else if(noah_lsm%crocus_opt == 1 .and. fileMeta%numLev(iTmp) .eq. fileMeta%act_lev) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(8),dimId(3),dimId(1)/),varId)\n                  else if(fileMeta%numLev(iTmp) .eq. fileMeta%numSpectrumBands) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(7),dimId(3),dimId(1)/),varId)\n                  else if(fileMeta%numLev(iTmp) .eq. 1) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(3),dimId(1)/),varId)\n                  endif\n               else\n                  if(fileMeta%numLev(iTmp) .eq. fileMeta%numSoilLayers) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(4),dimId(3),dimId(1)/),varId)\n                  else if(fileMeta%numLev(iTmp) .eq. fileMeta%numSnowLayers) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(5),dimId(3),dimId(1)/),varId)\n                  else if(noah_lsm%crocus_opt == 1 .and. fileMeta%numLev(iTmp) .eq. fileMeta%act_lev) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(8),dimId(3),dimId(1)/),varId)\n                  else if(fileMeta%numLev(iTmp) .eq. fileMeta%numSpectrumBands) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(7),dimId(3),dimId(1)/),varId)\n                  else if(fileMeta%numLev(iTmp) .eq. 1) then\n                     iret = nf90_def_var(ftnNoahMP,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(3),dimId(1)/),varId)\n                  endif\n               endif\n               call nwmCheck(diagFlag,iret,\"ERROR: Unable to create variable: \"//trim(fileMeta%varNames(iTmp)))\n\n               ! Extract valid range into a 1D array for placement.\n               varRange(1) = fileMeta%validMinComp(iTmp)\n               varRange(2) = fileMeta%validMaxComp(iTmp)\n               varRangeReal(1) = real(fileMeta%validMinDbl(iTmp))\n               varRangeReal(2) = real(fileMeta%validMaxDbl(iTmp))\n\n               ! Establish a compression level for the variables. For now we are using a\n               ! compression level of 2. In addition, we are choosing to turn the shuffle\n               ! filter off for now. Kelley Eicher did some testing with this and\n               ! determined that the benefit wasn't worth the extra time spent writing output.\n               ! Only compress if io_form_outputs is set to 1.\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n                  iret = nf90_def_var_deflate(ftnNoahMP,varId,0,1,2)\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression for: '//trim(fileMeta%varNames(iTmp)))\n               endif\n\n               ! Create variable attributes\n               iret = nf90_put_att(ftnNoahMP,varId,'long_name',trim(fileMeta%longName(iTmp)))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftnNoahMP,varId,'units',trim(fileMeta%units(iTmp)))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftnNoahMP,varId,'grid_mapping','crs')\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping attribute into variable: '//trim(fileMeta%varNames(iTmp)))\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n                  iret = nf90_put_att(ftnNoahMP,varId,'_FillValue',fileMeta%fillComp(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftnNoahMP,varId,'missing_value',fileMeta%missingComp(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftnNoahMP,varId,'scale_factor',fileMeta%scaleFactor(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place scale_factor attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftnNoahMP,varId,'add_offset',fileMeta%addOffset(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place add_offset attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftnNoahMP,varId,'valid_range',varRange)\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               else\n                  iret = nf90_put_att(ftnNoahMP,varId,'_FillValue',fileMeta%fillReal(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftnNoahMP,varId,'missing_value',fileMeta%missingReal(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftnNoahMP,varId,'valid_range',varRangeReal)\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               endif\n               ! Place necessary geospatial attributes into the variable.\n               do iTmp2=1,fileMeta%nCrsCharAtts\n                  if(trim(fileMeta%crsCharAttNames(iTmp2)) .eq. 'esri_pe_string') then\n                     iret = nf90_put_att(ftnNoahMP,varId,trim(fileMeta%crsCharAttNames(iTmp2)),trim(fileMeta%crsCharAttVals(iTmp2)))\n                     call nwmCheck(diagFlag,iret,'ERROR: Unable to place esri_pe_string attribute into '//trim(fileMeta%varNames(iTmp)))\n                  endif\n               end do\n            endif ! End if output flag is on\n         end do ! end looping through variable output list.\n\n         ! Remove NetCDF file from definition mode.\n         iret = nf90_enddef(ftnNoahMP)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to take LDASOUT file out of definition mode')\n\n         ! Read in coordinates from GeoGrid file. These will be placed into the\n         ! output file coordinate variables.\n         allocate(xCoord(global_nx))\n         allocate(yCoord(global_ny))\n         allocate(yCoord2(global_ny))\n         iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnGeo)\n         if(iret .ne. 0) then\n            ! Spatial metadata file not found for land grid. Warn the user no\n            ! file was found, and set x/y coordinates to -9999.0\n            call postDiagMsg(diagFlag,'WARNING: Unable to find LAND spatial metadata file')\n            xCoord = -9999.0\n            yCoord = -9999.0\n            yCoord2 = -9999.0\n         else\n            iret = nf90_inq_varid(ftnGeo,'x',geoXVarId)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find x coordinate in geoGrid file')\n            iret = nf90_get_var(ftnGeo,geoXVarId,xCoord)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to extract x coordinate from geoGrid file')\n            iret = nf90_inq_varid(ftnGeo,'y',geoYVarId)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find y coordinate in geoGrid file')\n            iret = nf90_get_var(ftnGeo,geoYVarId,yCoord)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to extract y coordinate from geoGrid file')\n\n            iret = nf90_close(ftnGeo)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to close geoGrid file.')\n            ! Reverse Y coordinates. They are read in reverse.\n            jTmp2 = 0\n            do jTmp = global_ny,1,-1\n               jTmp2 = jTmp2 + 1\n               yCoord2(jTmp2) = yCoord(jTmp)\n            end do\n         endif\n\n         ! Place coordinate values into output file\n         iret = nf90_inq_varid(ftnNoahMP,'x',varId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to locate x coordinate variable.')\n         iret = nf90_put_var(ftnNoahMP,varId,xCoord)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into x coordinate variable')\n         iret = nf90_inq_varid(ftnNoahMP,'y',varId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to locate y coordinate variable')\n         iret = nf90_put_var(ftnNoahMP,varId,yCoord2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into y coordinate variable')\n         deallocate(xCoord)\n         deallocate(yCoord)\n         deallocate(yCoord2)\n\n         ! Place time values into time variables.\n         iret = nf90_inq_varid(ftnNoahMP,'time',varId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time variable')\n         iret = nf90_put_var(ftnNoahMP,varId,minSinceEpoch)\n         call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into time variable')\n         iret = nf90_inq_varid(ftnNoahMP,'reference_time',varId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reference_time variable')\n         iret = nf90_put_var(ftnNoahMP,varId,minSinceEpoch1)\n         call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into reference_time variable')\n\n      end if ! End if we are on the I/O processor.\n   endif ! End if we are on the first variable\n\n   ! Place data into NetCDF file. This involves a few steps:\n   ! 1.) Allocate an integer array of local grid size.\n   ! 2.) Allocate an integer array of global grid size.\n   ! 3.) Make a copy of the floating point grid so it can be\n   !     masked out where water bodies exist, or missing NoahMP values\n   !     exist.\n   ! 4.) Loop through real local grid, convert floating point\n   !     values to integer via scale_factor/add_offset. If\n   !     missing value found, assign FillValue caluclated\n   !     in the dictionary.\n   ! 5.) Use MPP utilities to collect local integer arrays\n   !     into global integer array.\n   ! 6.) Write global integer array into output file.\n   if(fileMeta%outFlag(varInd) .eq. 1) then\n      ! Output flag on for this variable.\n      ! Allocate memory\n      if(myId .eq. 0) then\n         allocate(globalOutComp(global_nx,fileMeta%numLev(varInd),global_ny))\n         allocate(globalCompTmp(global_nx,global_ny))\n         allocate(globalOutReal(global_nx,fileMeta%numLev(varInd),global_ny))\n         allocate(globalRealTmp(global_nx,global_ny))\n      else\n         allocate(globalOutComp(1,1,1))\n         allocate(globalCompTmp(1,1))\n         allocate(globalOutReal(1,1,1))\n         allocate(globalRealTmp(1,1))\n      endif\n      allocate(localCompTmp(ixPar,jxPar))\n      allocate(varRealTmp(ixPar,fileMeta%numLev(varInd),jxPar))\n      globalOutComp = fileMeta%fillComp(varInd)\n      globalOutReal = fileMeta%fillReal(varInd)\n\n      varRealTmp = varReal\n      ! Reset any missing values that may exist.\n      where ( varRealTmp .eq. fileMeta%modelNdv ) varRealTmp = fileMeta%fillReal(varInd)\n      where ( varRealTmp .eq. fileMeta%modelNdvInt ) varRealTmp = fileMeta%fillReal(varInd)\n      where ( varRealTmp .eq. fileMeta%modelNdv2 ) varRealTmp = fileMeta%fillReal(varInd)\n      where ( varRealTmp .eq. fileMeta%modelNdv3 ) varRealTmp = fileMeta%fillReal(varInd)\n      where (varRealTmp .ne. varRealTmp) varRealTmp = fileMeta%fillReal(varInd)\n      do zTmp = 1,fileMeta%numLev(varInd)\n         localCompTmp = fileMeta%fillComp(varInd)\n         globalCompTmp = fileMeta%fillComp(varInd)\n         globalRealTmp = fileMeta%fillReal(varInd)\n         where ( vegTyp .eq. waterVal) varRealTmp(:,zTmp,:) = fileMeta%fillReal(varInd)\n         ! Check to see if we are on time 0. If the flag is set to 0 for time 0\n         ! outputs, convert all data to a fill. If we are time 0, make sure we\n         ! don't need to fill the grid in with NDV values.\n         if(minSinceSim .eq. 0 .and. fileMeta%timeZeroFlag(varInd) .eq. 0) then\n            localCompTmp = fileMeta%fillComp(varInd)\n            varRealTmp = fileMeta%fillReal(varInd)\n         else\n            localCompTmp = NINT((varRealTmp(:,zTmp,:)-fileMeta%addOffset(varInd))/fileMeta%scaleFactor(varInd))\n         endif\n\n         if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n            call write_IO_int(localCompTmp,globalCompTmp)\n            call write_IO_real(varRealTmp(:,zTmp,:),globalRealTmp)\n#endif\n         else\n            globalCompTmp = localCompTmp\n            globalRealTmp = varRealTmp(:,zTmp,:)\n         endif\n\n         ! Place output into global array to be written to NetCDF file.\n         if(myId .eq. 0) then\n            globalOutComp(:,zTmp,:) = globalCompTmp\n            globalOutReal(:,zTmp,:) = globalRealTmp\n         endif\n      end do\n\n      ! Write array out to NetCDF file.\n      if(myId .eq. 0) then\n      !   write(*,*) 'trude foo1'\n      !   write(*,*) 'variable name : ', fileMeta%varNames(varInd)\n      !   write(*,*) 'varind :', varind\n      !   write(*,*) 'varid :', varid\n      !   write(*,*) 'ftnNoahMP :', ftnNoahMP\n      !   write(*,*) 'num lev :', fileMeta%numLev(varInd)\n         iret = nf90_inq_varid(ftnNoahMP,trim(fileMeta%varNames(varInd)),varId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find variable ID for var: '//trim(fileMeta%varNames(varInd)))\n!         write(*,*) 'trude foo2'\n         if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n            if(fileMeta%numLev(varInd) .eq. 1) then\n               iret = nf90_put_var(ftnNoahMP,varId,globalOutComp,(/1,1,1/),(/global_nx,global_ny,1/))\n            else\n               iret = nf90_put_var(ftnNoahMP,varId,globalOutComp,(/1,1,1,1/),(/global_nx,fileMeta%numLev(varInd),global_ny,1/))\n            endif\n         else\n            if(fileMeta%numLev(varInd) .eq. 1) then\n               iret = nf90_put_var(ftnNoahMP,varId,globalOutReal,(/1,1,1/),(/global_nx,global_ny,1/))\n            else\n               iret = nf90_put_var(ftnNoahMP,varId,globalOutReal,(/1,1,1,1/),(/global_nx,fileMeta%numLev(varInd),global_ny,1/))\n            endif\n         endif\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into output variable: '//trim(fileMeta%varNames(varInd)))\n      endif\n\n      ! Deallocate memory for this variable.\n      deallocate(globalOutComp)\n      deallocate(globalCompTmp)\n      deallocate(globalOutReal)\n      deallocate(globalRealTmp)\n      deallocate(localCompTmp)\n      deallocate(varRealTmp)\n\n   endif\n\n   if(myId .eq. 0) then\n      ! Only close the file if we are finished with the very last variable.\n      if(varInd .eq. fileMeta%numVars) then\n         ! Close the output file\n         iret = nf90_close(ftnNoahMP)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close LDASOUT file.')\n      endif\n   endif\n\n\nend subroutine output_NoahMP_NWM\n\n!==============================================================================\n! Program Name: output_rt_NWM\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Output routine for terrain routing variables\n!           for the National Water Model.\n! History Log:\n! 3/6/17 -Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files: None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\n\nsubroutine output_rt_NWM(domainId,iGrid)\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst\n   use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n   use module_NWM_io_dict\n   use netcdf\n#ifdef MPP_LAND\n     use module_mpp_land\n#endif\n   implicit none\n\n   ! subroutine arguments\n   integer, intent(in) :: domainId\n   integer, intent(in) :: iGrid\n\n   ! Derived types.\n   type(rtDomainMeta) :: fileMeta\n\n   ! Local variables\n   integer :: mppFlag, diagFlag\n   integer :: minSinceSim ! Number of minutes since beginning of simulation.\n   integer :: minSinceEpoch1 ! Number of minutes from EPOCH to the beginning of the model simulation.\n   integer :: minSinceEpoch ! Number of minutes from EPOCH to the current model valid time.\n   character(len=16) :: epochDate ! EPOCH represented as a string.\n   character(len=16) :: startDate ! Start of model simulation, represented as a string.\n   character(len=256) :: output_flnm ! CHRTOUT_DOMAIN filename\n   integer :: iret ! NetCDF return statuses\n   integer :: ftn ! NetCDF file handle\n   character(len=256) :: validTime ! Global attribute time string\n   character(len=256) :: initTime ! Global attribute time string\n   integer :: dimId(5) ! Dimension ID values created during NetCDF created.\n   integer :: varId ! Variable ID value created as NetCDF variables are created and populated.\n   integer :: timeId ! Dimension ID for the time dimension.\n   integer :: refTimeId ! Dimension ID for the reference time dimension.\n   integer :: xVarId,yVarId,coordVarId ! Coordinate variable NC ID values\n   integer :: varRange(2) ! Local storage for valid min/max ranges\n   real :: varRangeReal(2) ! Local storage for valid min/max ranges\n   integer :: ierr, myId ! MPI return status, process ID\n   integer :: iTmp,jTmp,jTmp2,iTmp2,zTmp\n   real :: varRealTmp ! Local copy of floating point lake value\n   integer :: ftnGeo,geoXVarId,geoYVarId\n   ! Allocatable arrays to hold either x/y coordinate information,\n   ! or the grid of output values to be converted to integer via scale_factor\n   ! and add_offset.\n   integer, allocatable, dimension(:,:) :: localCompTmp\n   integer, allocatable, dimension(:,:,:) :: globalOutComp\n   real, allocatable, dimension(:,:) :: localRealTmp\n   real, allocatable, dimension(:,:,:) :: globalOutReal\n   real*8, allocatable, dimension(:) :: yCoord,xCoord,yCoord2\n   integer :: numLev ! This will be 4 for soil moisture, and 1 for all other variables.\n   character (len=64) :: modelConfigType ! This is character verion (long name) for the io_config_outputs\n   real :: scaleFactorReciprocal\n! Establish macro variables to hlep guide this subroutine.\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Some sanity checking here.\n   if(nlst(domainId)%RTOUT_DOMAIN .eq. 0) then\n      ! No output requested here. Return to the parent calling program.\n      return\n   endif\n\n   ! Initialize NWM dictionary derived type containing all the necessary metadat\n   ! for the output file.\n   call initRtDomainDict(fileMeta,myId,diagFlag)\n\n   if(nlst(domainId)%io_config_outputs .eq. 0) then\n      ! All\n      fileMeta%outFlag(:) = [1,1,1,1,1]\n   else if(nlst(domainId)%io_config_outputs .eq. 1) then\n      ! Analysis and Assimilation\n      fileMeta%outFlag(:) = [1,1,0,0,0]\n   else if(nlst(domainId)%io_config_outputs .eq. 2) then\n      ! Short Range\n      fileMeta%outFlag(:) = [1,1,0,0,0]\n   else if(nlst(domainId)%io_config_outputs .eq. 3) then\n      ! Medium Range\n      fileMeta%outFlag(:) = [1,1,0,0,0]\n   else if(nlst(domainId)%io_config_outputs .eq. 4) then\n      ! Long Range\n      fileMeta%outFlag(:) = [1,1,0,0,0]\n   else if(nlst(domainId)%io_config_outputs .eq. 5) then\n      ! Retrospective\n      fileMeta%outFlag(:) = [1,1,0,0,0]\n   else if(nlst(domainId)%io_config_outputs .eq. 6) then\n      ! Diagnostics\n      fileMeta%outFlag(:) = [1,1,0,0,0]\n   else\n      call nwmCheck(diagFlag,1,'ERROR: Invalid IOC flag provided by namelist file.')\n   endif\n\n   ! call the GetModelConfigType function\n   modelConfigType = GetModelConfigType(nlst(1)%io_config_outputs)\n\n   ! Calculate datetime information.\n   ! First compose strings of EPOCH and simulation start date.\n   epochDate = trim(\"1970-01-01 00:00\")\n   startDate = trim(nlst(domainId)%startdate(1:4)//\"-\"//&\n                    nlst(domainId)%startdate(6:7)//&\n                    &\"-\"//nlst(domainId)%startdate(9:10)//\" \"//&\n                    nlst(domainId)%startdate(12:13)//\":\"//&\n                    nlst(domainId)%startdate(15:16))\n   ! Second, utilize NoahMP date utilities to calculate the number of minutes\n   ! from EPOCH to the beginning of the model simulation.\n   call geth_idts(startDate,epochDate,minSinceEpoch1)\n   ! Third, calculate the number of minutes since the beginning of the\n   ! simulation.\n   minSinceSim = int(nlst(1)%out_dt*(rt_domain(1)%out_counts-1))\n   ! Fourth, calculate the total number of minutes from EPOCH to the current\n   ! model time step.\n   minSinceEpoch = minSinceEpoch1 + minSinceSim\n   ! Fifth, compose global attribute time strings that will be used.\n   validTime = trim(nlst(domainId)%olddate(1:4)//'-'//&\n                    nlst(domainId)%olddate(6:7)//'-'//&\n                    nlst(domainId)%olddate(9:10)//'_'//&\n                    nlst(domainId)%olddate(12:13)//':'//&\n                    nlst(domainId)%olddate(15:16)//&\n                    &':00')\n   initTime = trim(nlst(domainId)%startdate(1:4)//'-'//&\n                  nlst(domainId)%startdate(6:7)//'-'//&\n                  nlst(domainId)%startdate(9:10)//'_'//&\n                  nlst(domainId)%startdate(12:13)//':'//&\n                  nlst(domainId)%startdate(15:16)//&\n                  &':00')\n   ! Replace default values in the dictionary.\n   fileMeta%initTime = trim(initTime)\n   fileMeta%validTime = trim(validTime)\n\n   ! calculate the minimum and maximum time\n   fileMeta%timeValidMin = minSinceEpoch1 + nlst(1)%out_dt\n   fileMeta%timeValidMax = minSinceEpoch1 + int(nlst(1)%khour * 60/nlst(1)%out_dt) * nlst(1)%out_dt\n\n   ! calculate total_valid_time\n   if(nlst(domainId)%io_config_outputs .ne. 3 .and. nlst(domainId)%io_config_outputs .ne. 5) then\n       fileMeta%totalValidTime = int(nlst(1)%khour * 60 / nlst(1)%out_dt)  ! # number of valid time (#of output files)\n   else\n       fileMeta%totalValidTime = int(nlst(1)%khour * 60 / nlst(1)%out_dt / 3)  ! # number of valid time (#of output files)\n   endif\n\n   ! Create output filename\n   write(output_flnm, '(A12,\".RTOUT_DOMAIN\",I1)') nlst(domainId)%olddate(1:4)//&\n                       nlst(domainId)%olddate(6:7)//&\n                       nlst(domainId)%olddate(9:10)//&\n                       nlst(domainId)%olddate(12:13)//&\n                       nlst(domainId)%olddate(15:16), igrid\n\n   if(myId .eq. 0) then\n      ! Create output NetCDF file for writing.\n      iret = nf90_create(trim(output_flnm),cmode=NF90_NETCDF4,ncid = ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create RT_DOMAIN NetCDF file.')\n\n      ! Write global attributes\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'TITLE',trim(fileMeta%title))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create TITLE attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"compiler_version\",compiler_version())\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create compiler_version attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'model_initialization_time',trim(fileMeta%initTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model init time attribute into RT_DOMAIN file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'model_output_valid_time',trim(fileMeta%validTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model output time attribute into RT_DOMAIN file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'model_total_valid_times',fileMeta%totalValidTime)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model total valid times attribute into RT_DOMAIN file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'Conventions',trim(fileMeta%conventions))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place CF conventions attribute into RT_DOMAIN file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"code_version\",trim(get_code_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create code_version attribute')\n#ifdef NWM_META\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"NWM_version_number\",trim(get_nwm_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create NWM_version_number attribute')\n#endif\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_type\",trim(fileMeta%modelOutputType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_output_type attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_configuration\",modelConfigType)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_configuration attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"proj4\",trim(fileMeta%proj4))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create proj4 attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"GDAL_DataType\",\"Generic\")\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create GDAL_DataType attribute')\n\n      ! Create dimensions\n      iret = nf90_def_dim(ftn,'time',NF90_UNLIMITED,dimId(1))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define time dimension')\n      iret = nf90_def_dim(ftn,'x',RT_DOMAIN(domainId)%g_ixrt,dimId(2))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define x dimension')\n      iret = nf90_def_dim(ftn,'y',RT_DOMAIN(domainId)%g_jxrt,dimId(3))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define y dimension')\n      iret = nf90_def_dim(ftn,'reference_time',1,dimId(4))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define reference_time dimension')\n      ! Only create soil layers stag dimension if we are outputting to the soil moisture grid.\n      ! Otherwise this creates unused dimensions.\n      if (fileMeta%outFlag(5) .eq. 1) then\n      iret = nf90_def_dim(ftn,'soil_layers_stag',fileMeta%numSoilLayers,dimId(5))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define soil_layers_stag dimension')\n      endif\n\n      ! Create and populate reference_time and time variables.\n      iret = nf90_def_var(ftn,\"time\",nf90_int,dimId(1),timeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time variable')\n      iret = nf90_put_att(ftn,timeId,'long_name',trim(fileMeta%timeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'standard_name',trim(fileMeta%timeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'units',trim(fileMeta%timeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_min',fileMeta%timeValidMin)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_min attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_max',fileMeta%timeValidMax)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_max attribute into time variable')\n      iret = nf90_def_var(ftn,\"reference_time\",nf90_int,dimId(4),refTimeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'long_name',trim(fileMeta%rTimeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'standard_name',trim(fileMeta%rTimeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'units',trim(fileMeta%rTimeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reference_time variable')\n\n      ! Create x/y coordinate variables\n      iret = nf90_def_var(ftn,'x',nf90_double,dimId(2),xVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create x coordinate variable')\n      do iTmp=1,fileMeta%nxRealAtts\n         iret = nf90_put_att(ftn,xVarId,trim(fileMeta%xFloatAttNames(iTmp)),&\n                             fileMeta%xRealAttVals(iTmp,1:fileMeta%xRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place x floating point attributes into RTDOMAIN file.')\n      end do\n      do iTmp=1,fileMeta%nxCharAtts\n         iret = nf90_put_att(ftn,xVarId,trim(fileMeta%xCharAttNames(iTmp)),trim(fileMeta%xCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place x string point attributes into RTDOMAIN file.')\n      end do\n      iret = nf90_def_var(ftn,'y',nf90_double,dimId(3),yVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create y coordinate variable')\n      do iTmp=1,fileMeta%nyRealAtts\n         iret = nf90_put_att(ftn,yVarId,trim(fileMeta%yFloatAttNames(iTmp)),&\n                             fileMeta%yRealAttVals(iTmp,1:fileMeta%yRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place y floating point attributes into RTDOMAIN file.')\n      end do\n      do iTmp=1,fileMeta%nyCharAtts\n         iret = nf90_put_att(ftn,yVarId,trim(fileMeta%yCharAttNames(iTmp)),trim(fileMeta%yCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place y string point attributes into RTDOMAIN file.')\n      end do\n\n      ! Define compression for meta-variables only if io_form_outputs is set to 1.\n      if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n         iret = nf90_def_var_deflate(ftn,timeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for time.')\n         iret = nf90_def_var_deflate(ftn,refTimeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reference_time.')\n         iret = nf90_def_var_deflate(ftn,xVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for x.')\n         iret = nf90_def_var_deflate(ftn,yVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for y.')\n      endif\n\n      ! Translate crs variable info from land spatial metadata file to output\n      ! file.\n      iret = nf90_def_var(ftn,'crs',nf90_char,varid=coordVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create crs variable in RT_DOMAIN file.')\n      do iTmp=1,fileMeta%nCrsRealAtts\n         iret = nf90_put_att(ftn,coordVarId,trim(fileMeta%crsFloatAttNames(iTmp)),&\n                             fileMeta%crsRealAttVals(iTmp,1:fileMeta%crsRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place crs floating point attributes into RT_DOMAIN file.')\n      end do\n      do iTmp=1,fileMeta%nCrsCharAtts\n         iret = nf90_put_att(ftn,coordVarId,trim(fileMeta%crsCharAttNames(iTmp)),trim(fileMeta%crsCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place crs string point attributes into RT_DOMAIN file.')\n      end do\n\n      ! Loop through all possible variables and create them, along with their\n      ! metadata attributes.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            if(iTmp .eq. 5) then\n               ! Soil Moisture\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n                  iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(5),dimId(3),dimId(1)/),varId)\n               else\n                  iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(5),dimId(3),dimId(1)/),varId)\n               endif\n            else\n               ! All other variables\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n                  iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(3),dimId(1)/),varId)\n               else\n                  iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(3),dimId(1)/),varId)\n               endif\n            endif\n            call nwmCheck(diagFlag,iret,\"ERROR: Unable to create variable: \"//trim(fileMeta%varNames(iTmp)))\n\n            ! Extract valid range into a 1D array for placement.\n            varRange(1) = fileMeta%validMinComp(iTmp)\n            varRange(2) = fileMeta%validMaxComp(iTmp)\n            varRangeReal(1) = real(fileMeta%validMinDbl(iTmp))\n            varRangeReal(2) = real(fileMeta%validMaxDbl(iTmp))\n\n            ! Establish a compression level for the variables. For now we are using a\n            ! compression level of 2. In addition, we are choosing to turn the shuffle\n            ! filter off for now. Kelley Eicher did some testing with this and\n            ! determined that the benefit wasn't worth the extra time spent writing output.\n            ! Only compress if io_form_outputs is set to 1.\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n               iret = nf90_def_var_deflate(ftn,varId,0,1,2)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression for: '//trim(fileMeta%varNames(iTmp)))\n            endif\n\n            ! Create variable attributes\n            iret = nf90_put_att(ftn,varId,'long_name',trim(fileMeta%longName(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'units',trim(fileMeta%units(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'grid_mapping','crs')\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping attribute into variable: '//trim(fileMeta%varNames(iTmp)))\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'scale_factor',fileMeta%scaleFactor(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place scale_factor attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'add_offset',fileMeta%addOffset(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place add_offset attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRange)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            else\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRangeReal)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            endif\n            ! Place necessary geospatial attributes into the variable.\n            do iTmp2=1,fileMeta%nCrsCharAtts\n               if(trim(fileMeta%crsCharAttNames(iTmp2)) .eq. 'esri_pe_string') then\n                  iret = nf90_put_att(ftn,varId,trim(fileMeta%crsCharAttNames(iTmp2)),trim(fileMeta%crsCharAttVals(iTmp2)))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place esri_pe_string attribute into '//trim(fileMeta%varNames(iTmp)))\n               endif\n            end do\n         endif\n      end do ! end looping through variable output list.\n\n      ! Remove NetCDF file from definition mode.\n      iret = nf90_enddef(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to take RT_DOMAIN file out of definition mode')\n\n      ! Read in coordinates from FullDom file. These will be placed into the\n      ! output file coordinate variables.\n      allocate(xCoord(RT_DOMAIN(domainId)%g_ixrt))\n      allocate(yCoord(RT_DOMAIN(domainId)%g_jxrt))\n      allocate(yCoord2(RT_DOMAIN(domainId)%g_jxrt))\n      iret = nf90_open(trim(nlst(domainId)%geo_finegrid_flnm),NF90_NOWRITE,ncid=ftnGeo)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to open FullDom file')\n      iret = nf90_inq_varid(ftnGeo,'x',geoXVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to find x coordinate in FullDom file')\n      iret = nf90_get_var(ftnGeo,geoXVarId,xCoord)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to extract x coordinate from FullDom file')\n      iret = nf90_inq_varid(ftnGeo,'y',geoYVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to find y coordinate in FullDom file')\n      iret = nf90_get_var(ftnGeo,geoYVarId,yCoord)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to extract y coordinate from FullDom file')\n      iret = nf90_close(ftnGeo)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close geoGrid file.')\n\n      ! Reverse Y coordinates. They are read in reverse.\n      jTmp2 = 0\n      do jTmp = RT_DOMAIN(domainId)%g_jxrt,1,-1\n         jTmp2 = jTmp2 + 1\n         yCoord2(jTmp2) = yCoord(jTmp)\n      end do\n      ! Place coordinate values into output file\n      iret = nf90_inq_varid(ftn,'x',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate x coordinate variable.')\n      iret = nf90_put_var(ftn,varId,xCoord)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into x coordinate variable')\n      iret = nf90_inq_varid(ftn,'y',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate y coordinate variable')\n      iret = nf90_put_var(ftn,varId,yCoord2)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into y coordinate variable')\n      deallocate(xCoord)\n      deallocate(yCoord)\n      deallocate(yCoord2)\n\n      ! Place time values into time variables.\n      iret = nf90_inq_varid(ftn,'time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into time variable')\n      iret = nf90_inq_varid(ftn,'reference_time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reference_time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch1)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into reference_time variable')\n\n   endif ! End if statement if on I/O ID\n\n   ! Loop through each variable, collect local routing grid variables into a\n   ! global routing grid and output through the master I/O process.\n   do iTmp2=1,fileMeta%numVars\n\n      ! Specify the number of vertical levels we are dealing with\n      if(iTmp2 .eq. 5) then\n         numLev = 4\n      else\n         numLev = 1\n      endif\n\n      scaleFactorReciprocal = 1/fileMeta%scaleFactor(iTmp2)\n\n      if(fileMeta%outFlag(iTmp2) .eq. 1) then\n         !Allocate memory necessary\n         if(myId .eq. 0) then\n            allocate(globalOutComp(RT_DOMAIN(domainId)%g_ixrt,numLev,RT_DOMAIN(domainId)%g_jxrt))\n            allocate(globalOutReal(RT_DOMAIN(domainId)%g_ixrt,numLev,RT_DOMAIN(domainId)%g_jxrt))\n         else\n            allocate(globalOutComp(1,1,1))\n            allocate(globalOutReal(1,1,1))\n         endif\n         ! Allocate local memory\n         allocate(localCompTmp(RT_DOMAIN(domainId)%ixrt,RT_DOMAIN(domainId)%jxrt))\n         allocate(localRealTmp(RT_DOMAIN(domainId)%ixrt,RT_DOMAIN(domainId)%jxrt))\n         ! Initialize arrays to prescribed NDV value.\n         globalOutComp = fileMeta%fillComp(iTmp2)\n         globalOutReal = fileMeta%fillReal(iTmp2)\n\n         ! Loop through the number of levels.\n         do zTmp=1,numLev\n            ! Initialize arrays to prescribed NDV value.\n            localCompTmp = fileMeta%fillComp(iTmp2)\n            localRealTmp = fileMeta%fillReal(iTmp2)\n\n            ! Loop through output array and convert floating point values to\n            ! integers via scale_factor/add_offset.\n            do iTmp = 1,RT_DOMAIN(domainId)%ixrt\n               do jTmp = 1,RT_DOMAIN(domainId)%jxrt\n                  if(iTmp2 .eq. 1) then\n                     varRealTmp = rt_domain(domainId)%subsurface%properties%zwattablrt(iTmp,jTmp)\n                  else if(iTmp2 .eq. 2) then\n                     varRealTmp = RT_DOMAIN(domainId)%overland%control%surface_water_head_routing(iTmp,jTmp)\n                  else if(iTmp2 .eq. 3) then\n                     varRealTmp = RT_DOMAIN(domainId)%QSTRMVOLRT_ACC(iTmp,jTmp)\n                  else if(iTmp2 .eq. 4) then\n                     varRealTmp = RT_DOMAIN(domainId)%overland%control%boundary_flux(iTmp,jTmp)\n                  else if(iTmp2 .eq. 5) then\n                     varRealTmp = rt_domain(domainId)%subsurface%grid_transform%smcrt(iTmp,jTmp,zTmp)\n                  endif\n\n                  ! Run a quick gross check on values to ensure they aren't outside our\n                  ! defined limits.\n                  !if(varRealTmp .lt. fileMeta%validMinDbl(iTmp2)) then\n                  !   varRealTmp = fileMeta%fillReal(iTmp2)\n                  !endif\n                  !if(varRealTmp .gt. fileMeta%validMaxDbl(iTmp2)) then\n                  !   varRealTmp = fileMeta%fillReal(iTmp2)\n                  !endif\n                  if(varRealTmp .ne. varRealTmp) then\n                     varRealTmp = fileMeta%fillReal(iTmp2)\n                  endif\n                  ! If we are on time 0, make sure we don't need to fill in the\n                  ! grid with NDV values.\n                  if(minSinceSim .eq. 0 .and. fileMeta%timeZeroFlag(iTmp2) .eq. 0) then\n                     localCompTmp(iTmp,jTmp) = fileMeta%fillComp(iTmp2)\n                     localRealTmp(iTmp,jTmp) = fileMeta%fillReal(iTmp2)\n                  else\n                     if(varRealTmp .eq. fileMeta%modelNdv) then\n                        localCompTmp(iTmp,jTmp) = INT(fileMeta%fillComp(iTmp2))\n                        localRealTmp(iTmp,jTmp) = fileMeta%fillReal(iTmp2)\n                     else\n                        localCompTmp(iTmp,jTmp) = NINT((varRealTmp-fileMeta%addOffset(iTmp2))*scaleFactorReciprocal)\n                        localRealTmp(iTmp,jTmp) = varRealTmp\n                     endif\n                  endif\n               end do\n            end do\n            ! Collect local integer arrays into the global integer grid to be\n            ! written out.\n            if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n               call write_IO_rt_int(localCompTmp,globalOutComp(:,zTmp,:))\n               call write_IO_rt_real(localRealTmp,globalOutReal(:,zTmp,:))\n#endif\n            else\n               globalOutComp(:,zTmp,:) = localCompTmp\n               globalOutReal(:,zTmp,:) = localRealTmp\n            endif\n         end do ! End looping through levels\n\n         ! Write output to NetCDF file.\n         if(myId .eq. 0) then\n            iret = nf90_inq_varid(ftn,trim(fileMeta%varNames(iTmp2)),varId)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find variable ID for var: '//trim(fileMeta%varNames(iTmp2)))\n            if(numLev .eq. 1) then\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n                  iret = nf90_put_var(ftn,varId,globalOutComp,(/1,1,1/),(/RT_DOMAIN(domainId)%g_ixrt,RT_DOMAIN(domainId)%g_jxrt,1/))\n               else\n                  iret = nf90_put_var(ftn,varId,globalOutReal,(/1,1,1/),(/RT_DOMAIN(domainId)%g_ixrt,RT_DOMAIN(domainId)%g_jxrt,1/))\n               endif\n            else\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n                  iret = nf90_put_var(ftn,varId,globalOutComp,(/1,1,1,1/),(/RT_DOMAIN(domainId)%g_ixrt,numLev,RT_DOMAIN(domainId)%g_jxrt,1/))\n               else\n                  iret = nf90_put_var(ftn,varId,globalOutReal,(/1,1,1,1/),(/RT_DOMAIN(domainId)%g_ixrt,numLev,RT_DOMAIN(domainId)%g_jxrt,1/))\n               endif\n            endif\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into output variable: '//trim(fileMeta%varNames(iTmp2)))\n         endif\n\n         ! Deallocate memory for this variable.\n         deallocate(globalOutComp)\n         deallocate(localCompTmp)\n         deallocate(globalOutReal)\n         deallocate(localRealTmp)\n      endif\n   end do\n\n   if(myId .eq. 0) then\n      ! Close the output file\n      iret = nf90_close(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close RT_DOMAIN file.')\n   endif\n\n\nend subroutine output_rt_NWM\n\n!==============================================================================\n! Program Name: output_lakes_NWM\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Output routine for lake points for the National Water Model.\n! History Log:\n! 3/6/17 -Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files: None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\n\nsubroutine output_lakes_NWM(domainId,iGrid)\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst\n   use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n   use module_NWM_io_dict\n   use netcdf\n#ifdef MPP_LAND\n     use module_mpp_land\n#endif\n   implicit none\n\n   integer, intent(in) :: domainId\n   integer, intent(in) :: iGrid\n\n   ! Derived types.\n   type(lakeMeta) :: fileMeta\n\n   ! Local variables\n   integer :: mppFlag, diagFlag\n   integer :: minSinceSim ! Number of minutes since beginning of simulation.\n   integer :: minSinceEpoch1 ! Number of minutes from EPOCH to the beginning of the model simulation.\n   integer :: minSinceEpoch ! Number of minutes from EPOCH to the current model valid time.\n   character(len=16) :: epochDate ! EPOCH represented as a string.\n   character(len=16) :: startDate ! Start of model simulation, represented as a string.\n   character(len=256) :: output_flnm ! CHRTOUT_DOMAIN filename\n   integer :: iret ! NetCDF return statuses\n   integer :: ftn ! NetCDF file handle\n   character(len=256) :: validTime ! Global attribute time string\n   character(len=256) :: initTime ! Global attribute time string\n   integer :: dimId(4) ! Dimension ID values created during NetCDF created.\n   integer :: varId ! Variable ID value created as NetCDF variables are created and populated.\n   integer :: timeId ! Dimension ID for the time dimension.\n   integer :: refTimeId ! Dimension ID for the reference time dimension.\n   integer :: coordVarId ! Variable to hold crs\n   integer :: featureVarId ! feature_id NetCDF variable ID\n   integer :: reservoirTypeVarId ! reservoir_type netCDF variable ID\n   integer :: reservoirAssimilatedValueVarId ! reservoir_assimilated_value netCDF variable ID\n   integer :: reservoirAssimilatedSourceFileVarId ! reservoir_assimilated_source_file netCDF variable ID\n   integer :: latVarId, lonVarId ! lat/lon NetCDF variable ID values\n   integer :: elevVarId ! elevation NetCDF variable ID\n   integer :: varRange(2) ! Local storage of valid min/max values\n   real :: varRangeReal(2) ! Local storage of valid min/max values\n   integer :: gSize ! Global size of lake out arrays\n   integer :: iTmp\n   integer :: ftnRt,indVarId,indTmp ! For the feature_id sorting process.\n   integer :: ierr, myId ! MPI return status, process ID\n   integer :: ascFlag ! Flag for resorting timeseries output by feature_id.\n   ! Allocatable arrays to hold output variables.\n   real, allocatable, dimension(:) :: g_lakeLat,g_lakeLon,g_lakeElev\n   real, allocatable, dimension(:) :: g_lakeInflow,g_lakeOutflow\n   real, allocatable, dimension(:) :: g_lakeType\n   real, allocatable, dimension(:) :: g_lake_assimilated_value\n   character(len=256), allocatable, dimension(:) :: g_lake_assimilated_source_file\n   integer(kind=int64), allocatable, dimension(:) :: g_lakeid\n   real, allocatable, dimension(:) :: g_lakeLatOut,g_lakeLonOut,g_lakeElevOut\n   real, allocatable, dimension(:) :: g_lakeInflowOut,g_lakeOutflowOut\n   integer(kind=int64), allocatable, dimension(:) :: g_lakeTypeOut, g_lakeidOut\n   real, allocatable, dimension(:) :: g_lake_assimilated_valueOut\n   character(len=256), allocatable, dimension(:) :: g_lake_assimilated_source_fileOut\n   real, allocatable, dimension(:,:) :: varOutReal   ! Array holding output variables in real format\n   integer, allocatable, dimension(:) :: varOutInt ! Array holding output variables after\n                                                     ! scale_factor/add_offset\n                                                     ! have been applied.\n   integer, allocatable, dimension(:) :: chIndArray ! Array of index values for\n   character (len=64) :: modelConfigType ! This is character verion (long name) for the io_config_outputs\n\n   !each channel point. feature_id will need to be sorted in ascending order once\n   !data is collected into the global array. From there, the index values are\n   !re-sorted, and used to re-sort output arrays.\n\n   ! Initialize the ascFlag.\n   ascFlag = 1\n\n   ! Establish macro variables to hlep guide this subroutine.\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Some sanity checking here.\n   if(nlst(domainId)%outlake .eq. 0) then\n      ! No output requested here. Return to the parent calling program.\n      return\n   endif\n\n   ! Initialize NWM dictionary derived type containing all the necessary metadat\n   ! for the output file.\n   call initLakeDict(fileMeta,myId,diagFlag)\n\n   if(nlst(1)%io_config_outputs .eq. 0) then\n      ! All\n      fileMeta%outFlag(:) = [1,1]\n   else if(nlst(1)%io_config_outputs .eq. 1) then\n      ! Analysis and Assimilation\n      fileMeta%outFlag(:) = [1,1]\n   else if(nlst(1)%io_config_outputs .eq. 2) then\n      ! Short Range\n      fileMeta%outFlag(:) = [1,1]\n   else if(nlst(1)%io_config_outputs .eq. 3) then\n      ! Medium Range\n      fileMeta%outFlag(:) = [1,1]\n   else if(nlst(1)%io_config_outputs .eq. 4) then\n      ! Long Range\n      fileMeta%outFlag(:) = [1,1]\n   else if(nlst(1)%io_config_outputs .eq. 5) then\n      ! Retrospective\n      fileMeta%outFlag(:) = [1,1]\n   else if(nlst(1)%io_config_outputs .eq. 6) then\n      ! Diagnostics\n      fileMeta%outFlag(:) = [1,1]\n   else\n      call nwmCheck(diagFlag,1,'ERROR: Invalid IOC flag provided by namelist file.')\n   endif\n\n   ! call the GetModelConfigType function\n   modelConfigType = GetModelConfigType(nlst(1)%io_config_outputs)\n\n   ! First step is to collect and assemble all data that will be written to the\n   ! NetCDF file. If we are not using MPI, we bypass the collection step through\n   ! MPI.\n   if(mppFlag .eq. 1) then\n      gSize = rt_domain(domainId)%NLAKES\n\n      allocate(g_lakeLon(gsize))\n      allocate(g_lakeLat(gsize))\n      allocate(g_lakeElev(gsize))\n      allocate(g_lakeInflow(gsize))\n      allocate(g_lakeOutflow(gsize))\n      allocate(g_lakeType(gsize))\n      allocate(g_lake_assimilated_value(gsize))\n      allocate(g_lake_assimilated_source_file(gsize))\n      allocate(g_lakeid(gsize))\n\n      if(myId == 0) then\n         allocate(g_lakeLonOut(gsize))\n         allocate(g_lakeLatOut(gsize))\n         allocate(g_lakeElevOut(gsize))\n         allocate(g_lakeInflowOut(gsize))\n         allocate(g_lakeOutflowOut(gsize))\n         allocate(g_lakeTypeOut(gsize))\n         allocate(g_lake_assimilated_valueOut(gsize))\n         allocate(g_lake_assimilated_source_fileOut(gsize))\n         allocate(g_lakeidOut(gsize))\n         allocate(chIndArray(gsize))\n      endif\n\n      g_lakeLat = RT_DOMAIN(domainID)%LATLAKE\n      g_lakeLon = RT_DOMAIN(domainID)%LONLAKE\n      g_lakeElev = RT_DOMAIN(domainID)%RESHT\n      g_lakeInflow = RT_DOMAIN(domainID)%QLAKEI\n      g_lakeOutflow = RT_DOMAIN(domainID)%QLAKEO\n      g_lakeid = RT_DOMAIN(domainId)%LAKEIDM\n      g_lakeType = RT_DOMAIN(domainID)%final_reservoir_type\n      g_lake_assimilated_value = RT_DOMAIN(domainID)%reservoir_assimilated_value\n      g_lake_assimilated_source_file = RT_DOMAIN(domainID)%reservoir_assimilated_source_file\n\n      ! Collect arrays from various processors through MPI, and\n      ! assemble into global arrays previously allocated.\n#ifdef MPP_LAND\n      call write_lake_real(g_lakeLat,RT_DOMAIN(domainId)%lake_index,gsize)\n      call write_lake_real(g_lakeLon,RT_DOMAIN(domainId)%lake_index,gsize)\n      call write_lake_real(g_lakeElev,RT_DOMAIN(domainId)%lake_index,gsize)\n      call write_lake_real(g_lakeInflow,RT_DOMAIN(domainId)%lake_index,gsize)\n      call write_lake_real(g_lakeOutflow,RT_DOMAIN(domainId)%lake_index,gsize)\n      call write_lake_real(g_lakeType,RT_DOMAIN(domainId)%lake_index,gsize)\n      call write_lake_real(g_lake_assimilated_value,RT_DOMAIN(domainId)%lake_index,gsize)\n      !call write_lake_char(g_lake_assimilated_source_file,RT_DOMAIN(domainId)%lake_index,gsize)\n\n#endif\n   else\n      gSize = rt_domain(domainId)%NLAKES\n      ! No MPI - single processor\n      allocate(g_lakeLon(gsize))\n      allocate(g_lakeLat(gsize))\n      allocate(g_lakeElev(gsize))\n      allocate(g_lakeInflow(gsize))\n      allocate(g_lakeOutflow(gsize))\n      allocate(g_lakeid(gsize))\n      allocate(g_lakeLonOut(gsize))\n      allocate(g_lakeLatOut(gsize))\n      allocate(g_lakeElevOut(gsize))\n      allocate(g_lakeInflowOut(gsize))\n      allocate(g_lakeOutflowOut(gsize))\n      allocate(g_lakeidOut(gsize))\n      allocate(g_lakeTypeOut(gsize))\n      allocate(g_lake_assimilated_valueOut(gsize))\n      allocate(g_lake_assimilated_source_fileOut(gsize))\n      allocate(chIndArray(gsize))\n      g_lakeLat = RT_DOMAIN(domainID)%LATLAKE\n      g_lakeLon = RT_DOMAIN(domainID)%LONLAKE\n      g_lakeElev = RT_DOMAIN(domainID)%RESHT\n      g_lakeInflow = RT_DOMAIN(domainID)%QLAKEI\n      g_lakeOutflow = RT_DOMAIN(domainID)%QLAKEO\n      g_lakeid = RT_DOMAIN(domainId)%LAKEIDM\n      g_lakeType = RT_DOMAIN(domainId)%final_reservoir_type\n      g_lake_assimilated_value = RT_DOMAIN(domainID)%reservoir_assimilated_value\n      g_lake_assimilated_source_file = RT_DOMAIN(domainID)%reservoir_assimilated_source_file\n   endif\n\n   ! Calculate datetime information.\n   ! First compose strings of EPOCH and simulation start date.\n   epochDate = trim(\"1970-01-01 00:00\")\n   startDate = trim(nlst(domainId)%startdate(1:4)//\"-\"//&\n                    nlst(domainId)%startdate(6:7)//&\n                    &\"-\"//nlst(domainId)%startdate(9:10)//\" \"//&\n                    nlst(domainId)%startdate(12:13)//\":\"//&\n                    nlst(domainId)%startdate(15:16))\n   ! Second, utilize NoahMP date utilities to calculate the number of minutes\n   ! from EPOCH to the beginning of the model simulation.\n   call geth_idts(startDate,epochDate,minSinceEpoch1)\n   ! Third, calculate the number of minutes since the beginning of the\n   ! simulation.\n   minSinceSim = int(nlst(1)%out_dt*(rt_domain(1)%out_counts-1))\n   ! Fourth, calculate the total number of minutes from EPOCH to the current\n   ! model time step.\n   minSinceEpoch = minSinceEpoch1 + minSinceSim\n   ! Fifth, compose global attribute time strings that will be used.\n   validTime = trim(nlst(domainId)%olddate(1:4)//'-'//&\n                    nlst(domainId)%olddate(6:7)//'-'//&\n                    nlst(domainId)%olddate(9:10)//'_'//&\n                    nlst(domainId)%olddate(12:13)//':'//&\n                    nlst(domainId)%olddate(15:16)//&\n                    &':00')\n   initTime = trim(nlst(domainId)%startdate(1:4)//'-'//&\n                  nlst(domainId)%startdate(6:7)//'-'//&\n                  nlst(domainId)%startdate(9:10)//'_'//&\n                  nlst(domainId)%startdate(12:13)//':'//&\n                  nlst(domainId)%startdate(15:16)//&\n                  &':00')\n   ! Replace default values in the dictionary.\n   fileMeta%initTime = trim(initTime)\n   fileMeta%validTime = trim(validTime)\n\n   ! calculate the minimum and maximum time\n   fileMeta%timeValidMin = minSinceEpoch1 + nlst(1)%out_dt\n   fileMeta%timeValidMax = minSinceEpoch1 + int(nlst(1)%khour * 60/nlst(1)%out_dt) * nlst(1)%out_dt\n\n   ! calculate total_valid_time\n   fileMeta%totalValidTime = int(nlst(1)%khour * 60 / nlst(1)%out_dt)  ! # number of valid time (#of output files)\n\n   ! Compose output file name.\n   write(output_flnm, '(A12,\".LAKEOUT_DOMAIN\",I1)')nlst(domainId)%olddate(1:4)//&\n         nlst(domainId)%olddate(6:7)//nlst(domainId)%olddate(9:10)//&\n         nlst(domainId)%olddate(12:13)//nlst(domainId)%olddate(15:16),nlst(domainId)%igrid\n\n   ! Only run NetCDF library calls to output data if we are on the master\n   ! processor.\n   if(myId .eq. 0) then\n      ! Read in index values from Routelink that will be used to sort output\n      ! variables by ascending feature_id.\n      iret = nf90_open(trim(nlst(1)%route_lake_f),NF90_NOWRITE,ncid=ftnRt)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to open LAKEPARM file for index extraction')\n      iret = nf90_inq_varid(ftnRt,'ascendingIndex',indVarId)\n      if(iret .ne. 0) then\n         call postDiagMsg(diagFlag,'WARNING: ascendingIndex not found in LAKEPARM file. No resorting will take place.')\n         ascFlag = 0\n      endif\n      if(ascFlag .eq. 1) then\n         iret = nf90_get_var(ftnRt,indVarId,chIndArray)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract ascendingIndex from LAKEPARM file.')\n      endif\n      iret = nf90_close(ftnRt)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAKEPARM file.')\n\n      ! Place all output arrays into one real array that will be looped over\n      ! during conversion to compressed integer format.\n      allocate(varOutReal(fileMeta%numVars,gSize))\n      allocate(varOutInt(gSize))\n      if(ascFlag .eq. 1) then\n         ! Sort feature_id values by ascending values using the index array\n         ! extracted from the RouteLink file.\n         do iTmp=1,gSize\n            indTmp = chIndArray(iTmp)\n            indTmp = indTmp + 1 ! Python starts index values at 0, so we need to add one.\n            g_lakeInflowOut(iTmp) = g_lakeInflow(indTmp)\n            g_lakeOutflowOut(iTmp) = g_lakeOutflow(indTmp)\n            g_lakeLonOut(iTmp) = g_lakeLon(indTmp)\n            g_lakeLatOut(iTmp) = g_lakeLat(indTmp)\n            g_lakeElevOut(iTmp) = g_lakeElev(indTmp)\n            g_lakeTypeOut(iTmp) = g_lakeType(indTmp)\n            g_lake_assimilated_valueOut(iTmp) = g_lake_assimilated_value(indTmp)\n            g_lake_assimilated_source_fileOut(iTmp) = g_lake_assimilated_source_file(indTmp)\n            g_lakeidOut(iTmp) = g_lakeid(indTmp)\n         end do\n      else\n         g_lakeInflowOut = g_lakeInflow\n         g_lakeOutflowOut = g_lakeOutflow\n         g_lakeLonOut = g_lakeLon\n         g_lakeLatOut = g_lakeLat\n         g_lakeElevOut = g_lakeElev\n         g_lakeTypeOut = g_lakeType\n         g_lake_assimilated_valueOut = g_lake_assimilated_value\n         g_lake_assimilated_source_fileOut = g_lake_assimilated_source_file\n         g_lakeidOut = g_lakeid\n      endif\n      varOutReal(1,:) = g_lakeInflowOut(:)\n      varOutReal(2,:) = g_lakeOutflowOut(:)\n\n      ! Mask out missing values\n      where ( varOutReal == fileMeta%modelNdv ) varOutReal = -9999.0\n\n      iret = nf90_create(trim(output_flnm),cmode=NF90_NETCDF4,ncid = ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create LAKEOUT NetCDF file.')\n\n      ! Write global attributes.\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"TITLE\",trim(fileMeta%title))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create TITLE attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"compiler_version\",compiler_version())\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create compiler_version attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"featureType\",trim(fileMeta%fType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create featureType attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"proj4\",trim(fileMeta%proj4))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create proj4 attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_initialization_time\",trim(fileMeta%initTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model init attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"station_dimension\",trim(fileMeta%lakeDim))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create st. dimension attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_valid_time\",trim(fileMeta%validTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model valid attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_total_valid_times\",fileMeta%totalValidTime)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model total valid times attribute')\n      !iret = nf90_put_att(ftn,NF90_GLOBAL,\"esri_pe_string\",trim(fileMeta%esri))\n      !call nwmCheck(diagFlag,iret,'ERROR: Unable to create ESRI attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"Conventions\",trim(fileMeta%conventions))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create conventions attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"code_version\",trim(get_code_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create code_version attribute')\n#ifdef NWM_META\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"NWM_version_number\",trim(get_nwm_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create NWM_version_number attribute')\n#endif\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_type\",trim(fileMeta%modelOutputType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_output_type attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_configuration\",modelConfigType)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_configuration attribute')\n\n      ! Create dimensions\n      iret = nf90_def_dim(ftn,\"feature_id\",gSize,dimId(1))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create feature_id dimension')\n      iret = nf90_def_dim(ftn,\"time\",NF90_UNLIMITED,dimId(2))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time dimension')\n      iret = nf90_def_dim(ftn,\"reference_time\",1,dimId(3))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time dimension')\n      !iret = nf90_def_dim(ftn,\"string_length\",256,dimId(4))\n      !call nwmCheck(diagFlag,iret,'ERROR: Unable to create string length dimension')\n\n      ! Create and populate reference_time and time variables.\n      iret = nf90_def_var(ftn,\"time\",nf90_int,dimId(2),timeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time variable')\n      iret = nf90_put_att(ftn,timeId,'long_name',trim(fileMeta%timeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'standard_name',trim(fileMeta%timeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'units',trim(fileMeta%timeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_min',fileMeta%timeValidMin)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_min attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_max',fileMeta%timeValidMax)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_max attribute into time variable')\n      iret = nf90_def_var(ftn,\"reference_time\",nf90_int,dimId(3),refTimeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'long_name',trim(fileMeta%rTimeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'standard_name',trim(fileMeta%rTimeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'units',trim(fileMeta%rTimeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reference_time variable')\n\n      ! Create a crs variable.\n      ! NOTE - For now, we are hard-coding in for lat/lon points. However, this\n      ! may be more flexible in future iterations.\n      iret = nf90_def_var(ftn,'crs',nf90_char,varid=coordVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'transform_name','latitude longitude')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place transform_name attribute into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'grid_mapping_name','latitude longitude')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping_name attribute into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'esri_pe_string','GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",&\n                                          &SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",&\n                                          &0.0174532925199433]];-400 -400 1000000000;&\n                                          &-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place esri_pe_string into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'spatial_ref','GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",&\n                                          &SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",&\n                                          &0.0174532925199433]];-400 -400 1000000000;&\n                                          &-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place spatial_ref into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'long_name','CRS definition')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'longitude_of_prime_meridian',0.0)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place longitude_of_prime_meridian into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'_CoordinateAxes','latitude longitude')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place _CoordinateAxes into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'semi_major_axis',6378137.0)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place semi_major_axis into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'semi_minor_axis',6356752.31424518)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place semi_minor_axis into crs variable.')\n      iret = nf90_put_att(ftn,coordVarId,'inverse_flattening',298.257223563)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place inverse_flattening into crs variable.')\n\n      ! Create feature_id variable\n      iret = nf90_def_var(ftn,\"feature_id\",nf90_int64,dimId(1),featureVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create feature_id variable.')\n      iret = nf90_put_att(ftn,featureVarId,'long_name',trim(fileMeta%featureIdLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Uanble to place long_name attribute into feature_id variable')\n      iret = nf90_put_att(ftn,featureVarId,'comment',trim(fileMeta%featureIdComment))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place comment attribute into feature_id variable')\n      iret = nf90_put_att(ftn,featureVarId,'cf_role',trim(fileMeta%cfRole))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place cf_role attribute into feature_id variable')\n\n      ! Create reservoir_type variable\n      iret = nf90_def_var(ftn, \"reservoir_type\", nf90_int, dimId(1), reservoirTypeVarId)\n      call nwmCheck(diagFlag, iret, 'ERROR: Unable to create reservoir_type variable.')\n      iret = nf90_put_att(ftn, reservoirTypeVarId, 'long_name', trim(fileMeta%reservoirTypeLName))\n      call nwmCheck(diagFlag, iret, 'ERROR: Unable to place long_name attribute into reservoir_type variable')\n      iret = nf90_put_att(ftn, reservoirTypeVarId, 'flag_values', fileMeta%reservoirTypeFlagValues)\n      call nwmCheck(diagFlag, iret, 'ERROR: Unable to place flag_values attribute into reservoir_type variable')\n      iret = nf90_put_att(ftn, reservoirTypeVarId, 'flag_meanings', trim(fileMeta%reservoirTypeFlagMeanings))\n      call nwmCheck(diagFlag, iret, 'ERROR: Unable to place flag_meanings attribute into reservoir_type variable')\n\n      ! Create reservoir_assimilated_value variable\n      iret = nf90_def_var(ftn, \"reservoir_assimilated_value\", nf90_float, dimId(1), reservoirAssimilatedValueVarId)\n      call nwmCheck(diagFlag, iret, 'ERROR: Unable to create reservoir_assimilated_value variable.')\n      iret = nf90_put_att(ftn, reservoirAssimilatedValueVarId, 'long_name', trim(fileMeta%reservoirAssimilatedValueLName))\n      call nwmCheck(diagFlag, iret, 'ERROR: Unable to place long_name attribute into reservoir_assimilated_value variable')\n      iret = nf90_put_att(ftn,reservoirAssimilatedValueVarId,'units',trim(fileMeta%reservoirAssimilatedValueUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reservoir_assimilated_value variable')\n\n      ! Create reservoir_assimilated_source_file variable\n      !iret = nf90_def_var(ftn, \"reservoir_assimilated_source_file\", nf90_char, [dimId(4), dimId(1)], reservoirAssimilatedSourceFileVarId)\n      !call nwmCheck(diagFlag, iret, 'ERROR: Unable to create reservoir_assimilated_source_file variable.')\n      !iret = nf90_put_att(ftn, reservoirAssimilatedSourceFileVarId, 'long_name', trim(fileMeta%reservoirAssimilatedSourceFileLName))\n      !call nwmCheck(diagFlag, iret, 'ERROR: Unable to place long_name attribute into reservoir_assimilated_source_file variable')\n      !iret = nf90_def_var_fill(ftn, reservoirAssimilatedSourceFileVarId, 0, 0);\n      !call nwmCheck(diagFlag, iret, 'ERROR: Unable to place _FillValue attribute into reservoir_assimilated_source_file variable')\n\n      ! Create lake lat/lon variables\n      iret = nf90_def_var(ftn,\"latitude\",nf90_float,dimId(1),latVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create latitude variable.')\n      iret = nf90_put_att(ftn,latVarId,'long_name',trim(fileMeta%latLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into latitude variable')\n      iret = nf90_put_att(ftn,latVarId,'standard_name',trim(fileMeta%latStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into latitude variable')\n      iret = nf90_put_att(ftn,latVarId,'units',trim(fileMeta%latUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into latitude variable')\n      iret = nf90_def_var(ftn,\"longitude\",nf90_float,dimId(1),lonVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create longitude variable.')\n      iret = nf90_put_att(ftn,lonVarId,'long_name',trim(fileMeta%lonLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Uanble to place long_name attribute into longitude variable')\n      iret = nf90_put_att(ftn,lonVarId,'standard_name',trim(fileMeta%lonStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into longitude variable')\n      iret = nf90_put_att(ftn,lonVarId,'units',trim(fileMeta%lonUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into longitude variable')\n\n      ! Create channel elevation variable\n      iret = nf90_def_var(ftn,\"water_sfc_elev\",nf90_float,dimId(1),elevVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create water_sfc_elev variable.')\n      iret = nf90_put_att(ftn,elevVarId,'long_name',trim(fileMeta%elevLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into water_sfc_elev variable')\n      iret = nf90_put_att(ftn,elevVarId,'units',trim(fileMeta%elevUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into water_sfc_elev variable')\n      iret = nf90_put_att(ftn,elevVarId,'comment',trim(fileMeta%elevComment))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place comment attribute into water_sfc_elev variable')\n\n      ! Define deflation levels for these meta-variables. For now, we are going to\n      ! default to a compression level of 2. Only compress if io_form_outputs is set to 1.\n      if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n         iret = nf90_def_var_deflate(ftn,timeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for time.')\n         iret = nf90_def_var_deflate(ftn,featureVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for feature_id.')\n         iret = nf90_def_var_deflate(ftn,reservoirTypeVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reservoir_type.')\n         iret = nf90_def_var_deflate(ftn,refTimeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reference_time.')\n         iret = nf90_def_var_deflate(ftn,latVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for latitude.')\n         iret = nf90_def_var_deflate(ftn,lonVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for longitude.')\n         iret = nf90_def_var_deflate(ftn,elevVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for elevation.')\n      endif\n\n      ! Allocate memory for the output variables, then place the real output\n      ! variables into a single array. This array will be accessed throughout the\n      ! output looping below for conversion to compressed integer values.\n      ! Loop through and create each output variable, create variable attributes,\n      ! and insert data.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            ! First create variable\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_int,dimId(1),varId)\n            else\n               iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_float,dimId(1),varId)\n            endif\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to create variable:'//trim(fileMeta%varNames(iTmp)))\n\n            ! Extract valid range into a 1D array for placement.\n            varRange(1) = fileMeta%validMinComp(iTmp)\n            varRange(2) = fileMeta%validMaxComp(iTmp)\n            varRangeReal(1) = real(fileMeta%validMinDbl(iTmp))\n            varRangeReal(2) = real(fileMeta%validMaxDbl(iTmp))\n\n            ! Establish a compression level for the variables. For now we are using a\n            ! compression level of 2. In addition, we are choosing to turn the shuffle\n            ! filter off for now. Kelley Eicher did some testing with this and\n            ! determined that the benefit wasn't worth the extra time spent writing output.\n            ! Only compress if io_form_outputs is set to 1.\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n               iret = nf90_def_var_deflate(ftn,varId,0,1,2)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression for: '//trim(fileMeta%varNames(iTmp)))\n            endif\n\n            ! Create variable attributes\n            iret = nf90_put_att(ftn,varId,'long_name',trim(fileMeta%longName(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'units',trim(fileMeta%units(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'coordinates',trim(fileMeta%coordNames(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place coordinates attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'grid_mapping','crs')\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'scale_factor',fileMeta%scaleFactor(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place scale_factor attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'add_offset',fileMeta%addOffset(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place add_offset attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRange)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            else\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRangeReal)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            endif\n         endif\n      end do\n\n      ! Remove NetCDF file from definition mode.\n      iret = nf90_enddef(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to take LAKETOUT file out of definition mode')\n\n      ! Place lake ID, elevation, lat, and lon values into appropriate\n      ! variables.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            ! We are outputing this variable.\n            ! Convert reals to integer. If we are on time 0, make sure we don't\n            ! need to fill in with NDV values.\n            if(minSinceSim .eq. 0 .and. fileMeta%timeZeroFlag(iTmp) .eq. 0) then\n               varOutInt(:) = fileMeta%fillComp(iTmp)\n               varOutReal(iTmp,:) = fileMeta%fillReal(iTmp)\n            else\n               varOutInt(:) = NINT((varOutReal(iTmp,:)-fileMeta%addOffset(iTmp))/fileMeta%scaleFactor(iTmp))\n            endif\n            ! Get NetCDF variable id.\n            iret = nf90_inq_varid(ftn,trim(fileMeta%varNames(iTmp)),varId)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find variable ID for var: '//trim(fileMeta%varNames(iTmp)))\n            ! Put data into NetCDF file\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_var(ftn,varId,varOutInt)\n            else\n               iret = nf90_put_var(ftn,varId,varOutReal(iTmp,:))\n            endif\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into output variable: '//trim(fileMeta%varNames(iTmp)))\n         endif\n      end do\n\n      ! Place link ID values into the NetCDF file\n      iret = nf90_inq_varid(ftn,'feature_id',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate feature_id in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_lakeidOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into feature_id output variable.')\n\n      ! Place reservoir_type values into the NetCDF file\n      iret = nf90_inq_varid(ftn,'reservoir_type',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reservoir_type in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_lakeTypeOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into reservoir_type output variable.')\n\n      ! Place reservoir_assimilated_value values into the NetCDF file\n      iret = nf90_inq_varid(ftn,'reservoir_assimilated_value',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reservoir_assimilated_value in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_lake_assimilated_valueOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into reservoir_assimilated_value output variable.')\n\n      ! Place reservoir_assimilated_source_file values into the NetCDF file\n      !iret = nf90_inq_varid(ftn,'reservoir_assimilated_source_file',varId)\n      !call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reservoir_assimilated_source_file in NetCDF file.')\n      !do iTmp = 1, gSize\n      !   iret = nf90_put_var(ftn,varId,trim(g_lake_assimilated_source_fileOut(iTmp)), start=[1,iTmp])\n      !   call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into reservoir_assimilated_source_file output variable.')\n      !end do\n\n      ! Place lake metadata into NetCDF file\n      iret = nf90_inq_varid(ftn,'water_sfc_elev',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate water_sfc_elev in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_lakeElevOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into water_sfc_elev output variable.')\n\n      iret = nf90_inq_varid(ftn,'latitude',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate latitude in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_lakeLatOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into latitude output variable.')\n\n      iret = nf90_inq_varid(ftn,'longitude',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate longitude in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_lakeLonOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into longitude output variable.')\n\n      ! Place time values into time variables.\n      iret = nf90_inq_varid(ftn,'time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into time variable')\n      iret = nf90_inq_varid(ftn,'reference_time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reference_time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch1)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into reference_time variable')\n\n      ! Close the output file\n      iret = nf90_close(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAKE file.')\n\n   endif ! End if we are on master processor.\n\n   ! Deallocate all memory\n   if(myId .eq. 0) then\n      deallocate(varOutReal)\n      deallocate(varOutInt)\n   endif\n   deallocate(g_lakeLon)\n   deallocate(g_lakeLat)\n   deallocate(g_lakeElev)\n   deallocate(g_lakeInflow)\n   deallocate(g_lakeOutflow)\n   deallocate(g_lakeid)\n   deallocate(g_lakeType)\n   deallocate(g_lake_assimilated_value)\n   deallocate(g_lake_assimilated_source_file)\n\n   if(myId .eq. 0) then\n      deallocate(g_lakeLonOut)\n      deallocate(g_lakeLatOut)\n      deallocate(g_lakeElevOut)\n      deallocate(g_lakeInflowOut)\n      deallocate(g_lakeOutflowOut)\n      deallocate(g_lakeidOut)\n      deallocate(g_lakeTypeOut)\n      deallocate(g_lake_assimilated_valueOut)\n      deallocate(g_lake_assimilated_source_fileOut)\n      deallocate(chIndArray)\n   endif\n\n\nend subroutine output_lakes_NWM\n\n!==================================================================\n! Program Name: output_chrtout_grd_NWM\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Ouptut routine for gridden streamflow variables\n!           for non-reach based routing.\n! History Log:\n! 8/6/17 - Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files: None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\n\nsubroutine output_chrtout_grd_NWM(domainId,iGrid)\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst\n   use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n   use module_NWM_io_dict\n   use netcdf\n#ifdef MPP_LAND\n   use module_mpp_land\n   use module_mpp_reachls,  only: ReachLS_write_io\n#endif\n   implicit none\n\n   ! subroutine arguments\n   integer, intent(in) :: domainId\n   integer, intent(in) :: iGrid\n\n   ! Derived types.\n   type(chrtGrdMeta) :: fileMeta\n\n   ! Local variables\n   integer :: mppFlag, diagFlag\n   integer :: minSinceSim ! Number of minutes since beginning of simulation.\n   integer :: minSinceEpoch1 ! Number of minutes from EPOCH to the beginning of the model simulation.\n   integer :: minSinceEpoch ! Number of minutes from EPOCH to the current model valid time.\n   character(len=16) :: epochDate ! EPOCH represented as a string.\n   character(len=16) :: startDate ! Start of model simulation, represented as a string.\n   character(len=256) :: output_flnm ! CHRTOUT_GRID filename\n   integer :: iret ! NetCDF return statuses\n   integer :: ftn ! NetCDF file handle\n   character(len=256) :: validTime ! Global attribute time string\n   character(len=256) :: initTime ! Global attribute time string\n   integer :: dimId(4) ! Dimension ID values created during NetCDF created.\n   integer :: varId ! Variable ID value created as NetCDF variables are created and populated.\n   integer :: timeId ! Dimension ID for the time dimension.\n   integer :: refTimeId ! Dimension ID for the reference time dimension.\n   integer :: xVarId,yVarId,coordVarId ! Coordinate variable NC ID values\n   integer :: varRange(2) ! Local storage for valid min/max ranges\n   real :: varRangeReal(2) ! Local storage for valid min/max ranges\n   integer :: ierr, myId ! MPI return status, process ID\n   integer :: ftnGeo,geoXVarId,geoYVarId\n   integer :: iTmp,jTmp,jTmp2,iTmp2\n   integer :: gNumLnks,lNumLnks\n   integer :: indexVarId\n   ! Allocatable array to hold temporary streamflow for checking\n   real, allocatable, dimension(:) :: strFlowLocal\n   ! Allocatable array to hold global qlink values\n   real, allocatable, dimension(:,:) :: g_qlink\n   ! Allocatable array to hold streamflow index values\n   integer(kind=int64), allocatable, dimension(:,:) :: CH_NETLNK\n   ! allocatable global array to hold grid of output streamflow values\n   integer, allocatable, dimension(:,:) :: tmpFlow\n   real, allocatable, dimension(:,:) :: tmpFlowReal\n   ! allocatable arrays to hold coordinate values\n   real*8, allocatable, dimension(:) :: yCoord,xCoord,yCoord2\n\n   character (len=64) :: modelConfigType ! This is character verion (long name) for the io_config_outputs\n\n! Establish macro variables to hlep guide this subroutine.\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   ! We will print a warning to the user if they request CHRTOUT_GRID under\n   ! reach-based routing. Currently, this is not supported as we don't have a\n   ! way to map reaches to individual cells on the channel grid in the Fulldom\n   ! file.\n   if(nlst(domainId)%CHRTOUT_GRID .eq. 1) then\n      if(nlst(domainId)%channel_option .ne. 3) then\n         call postDiagMsg(diagFlag,'WARNING: CHRTOUT_GRID only available for gridded channel routing, not reach-based routing.')\n         return\n      endif\n   endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Some sanity checking here.\n   if(nlst(domainId)%CHRTOUT_GRID .eq. 0) then\n      ! No output requested here. Return to the parent calling program.\n      return\n   endif\n\n   ! Initialize qlink arrays and collect data from processors for output.\n   gNumLnks = rt_domain(domainId)%gnlinks\n   lNumLnks = rt_domain(domainId)%NLINKS\n   if(myId .eq. 0) then\n      ! Channel index values\n      allocate(CH_NETLNK(RT_DOMAIN(domainId)%g_ixrt,RT_DOMAIN(domainId)%g_jxrt))\n      ! Global qlink values\n      allocate(g_qlink(gNumLnks,2) )\n      ! Grid of global streamflow values via scale_factor/add_offset\n      allocate(tmpFlow(RT_DOMAIN(domainId)%g_ixrt,RT_DOMAIN(domainId)%g_jxrt))\n      allocate(tmpFlowReal(RT_DOMAIN(domainId)%g_ixrt,RT_DOMAIN(domainId)%g_jxrt))\n   else\n      allocate(CH_NETLNK(1,1))\n      allocate(g_qlink(1,2) )\n      allocate(tmpFlow(1,1))\n      allocate(tmpFlowReal(1,1))\n   endif\n   ! Allocate local streamflow array. We need to do a check to\n   ! for lake_type 2. However, we cannot set the values in the global array\n   ! to missing as this causes the model to crash.\n   allocate(strFlowLocal(RT_DOMAIN(domainId)%NLINKS))\n   strFlowLocal = RT_DOMAIN(domainId)%QLINK(:,1)\n   ! Loop through all the local links on this processor. For lake_type\n   ! of 2, we need to manually set the streamflow values\n   ! to the model NDV value.\n   if (RT_DOMAIN(domainId)%NLAKES .gt. 0) then\n      do iTmp=1,RT_DOMAIN(domainId)%NLINKS\n         if (RT_DOMAIN(domainId)%TYPEL(iTmp) .eq. 2) then\n            strFlowLocal(iTmp) = fileMeta%modelNdv\n         endif\n      end do\n   endif\n   if(nlst(domainId)%channel_option .eq. 3) then\n      call write_chanel_real(strFlowLocal,RT_DOMAIN(domainId)%map_l2g,gNumLnks,lNumLnks,g_qlink(:,1))\n      call write_chanel_real(RT_DOMAIN(domainId)%qlink(:,2),RT_DOMAIN(domainId)%map_l2g,gNumLnks,lNumLnks,g_qlink(:,2))\n   endif\n   call write_IO_rt_int8(RT_DOMAIN(domainId)%GCH_NETLNK, CH_NETLNK)\n\n   ! Initialize NWM dictionary derived type containing all the necessary metadat\n   ! for the output file.\n   call initChrtGrdDict(fileMeta,myId,diagFlag)\n\n   ! For now, we will default to outputting all variables until further notice.\n   fileMeta%outFlag(:) = [1]\n\n   ! Calculate datetime information.\n   ! First compose strings of EPOCH and simulation start date.\n   epochDate = trim(\"1970-01-01 00:00\")\n   startDate = trim(nlst(domainId)%startdate(1:4)//\"-\"//&\n                    nlst(domainId)%startdate(6:7)//&\n                    &\"-\"//nlst(domainId)%startdate(9:10)//\" \"//&\n                    nlst(domainId)%startdate(12:13)//\":\"//&\n                    nlst(domainId)%startdate(15:16))\n   ! Second, utilize NoahMP date utilities to calculate the number of minutes\n   ! from EPOCH to the beginning of the model simulation.\n   call geth_idts(startDate,epochDate,minSinceEpoch1)\n   ! Third, calculate the number of minutes since the beginning of the\n   ! simulation.\n   minSinceSim = int(nlst(1)%out_dt*(rt_domain(1)%out_counts-1))\n   ! Fourth, calculate the total number of minutes from EPOCH to the current\n   ! model time step.\n   minSinceEpoch = minSinceEpoch1 + minSinceSim\n   ! Fifth, compose global attribute time strings that will be used.\n   validTime = trim(nlst(domainId)%olddate(1:4)//'-'//&\n                    nlst(domainId)%olddate(6:7)//'-'//&\n                    nlst(domainId)%olddate(9:10)//'_'//&\n                    nlst(domainId)%olddate(12:13)//':'//&\n                    nlst(domainId)%olddate(15:16)//&\n                    &':00')\n   initTime = trim(nlst(domainId)%startdate(1:4)//'-'//&\n                  nlst(domainId)%startdate(6:7)//'-'//&\n                  nlst(domainId)%startdate(9:10)//'_'//&\n                  nlst(domainId)%startdate(12:13)//':'//&\n                  nlst(domainId)%startdate(15:16)//&\n                  &':00')\n   ! Replace default values in the dictionary.\n   fileMeta%initTime = trim(initTime)\n   fileMeta%validTime = trim(validTime)\n\n   ! calculate the minimum and maximum time\n   fileMeta%timeValidMin = minSinceEpoch1 + nlst(1)%out_dt\n   fileMeta%timeValidMax = minSinceEpoch1 + int(nlst(1)%khour * 60/nlst(1)%out_dt) * nlst(1)%out_dt\n\n   ! calculate total_valid_time\n   fileMeta%totalValidTime = int(nlst(1)%khour * 60 / nlst(1)%out_dt)  ! # number of valid time (#of output files)\n\n   ! Create output filename\n   write(output_flnm, '(A12,\".CHRTOUT_GRID\",I1)') nlst(domainId)%olddate(1:4)//&\n                       nlst(domainId)%olddate(6:7)//&\n                       nlst(domainId)%olddate(9:10)//&\n                       nlst(domainId)%olddate(12:13)//&\n                       nlst(domainId)%olddate(15:16), igrid\n\n   ! call the GetModelConfigType function\n   modelConfigType = GetModelConfigType(nlst(1)%io_config_outputs)\n\n   if(myId .eq. 0) then\n      ! Create output NetCDF file for writing.\n      iret = nf90_create(trim(output_flnm),cmode=NF90_NETCDF4,ncid = ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create RT_DOMAIN NetCDF file.')\n\n      ! Write global attributes\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'TITLE',trim(fileMeta%title))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create TITLE attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"compiler_version\",compiler_version())\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create compiler_version attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'model_initialization_time',trim(fileMeta%initTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model init time attribute into RT_DOMAIN file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'model_output_valid_time',trim(fileMeta%validTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model output time attribute into RT_DOMAIN file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'model_total_valid_times',fileMeta%totalValidTime)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model total valid times attribute into RT_DOMAIN file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'Conventions',trim(fileMeta%conventions))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place CF conventions attribute into RT_DOMAIN file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"code_version\",trim(get_code_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create code_version attribute')\n#ifdef NWM_META\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"NWM_version_number\",trim(get_nwm_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create NWM_version_number attribute')\n#endif\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_type\",trim(fileMeta%modelOutputType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_output_type attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_configuration\",modelConfigType)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_configuration attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"proj4\",trim(fileMeta%proj4))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create proj4 attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"GDAL_DataType\",\"Generic\")\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create GDAL_DataType attribute')\n\n      ! Create dimensions\n      iret = nf90_def_dim(ftn,'time',NF90_UNLIMITED,dimId(1))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define time dimension')\n      iret = nf90_def_dim(ftn,'x',RT_DOMAIN(domainId)%g_ixrt,dimId(2))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define x dimension')\n      iret = nf90_def_dim(ftn,'y',RT_DOMAIN(domainId)%g_jxrt,dimId(3))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define y dimension')\n      iret = nf90_def_dim(ftn,'reference_time',1,dimId(4))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define reference_time dimension')\n\n      ! Create and populate reference_time and time variables.\n      iret = nf90_def_var(ftn,\"time\",nf90_int,dimId(1),timeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time variable')\n      iret = nf90_put_att(ftn,timeId,'long_name',trim(fileMeta%timeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'standard_name',trim(fileMeta%timeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'units',trim(fileMeta%timeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_min',fileMeta%timeValidMin)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_min attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_max',fileMeta%timeValidMax)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_max attribute into time variable')\n      iret = nf90_def_var(ftn,\"reference_time\",nf90_int,dimId(4),refTimeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'long_name',trim(fileMeta%rTimeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'standard_name',trim(fileMeta%rTimeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'units',trim(fileMeta%rTimeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reference_time variable')\n\n      ! Create x/y coordinate variables\n      iret = nf90_def_var(ftn,'x',nf90_double,dimId(2),xVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create x coordinate variable')\n      do iTmp=1,fileMeta%nxRealAtts\n         iret = nf90_put_att(ftn,xVarId,trim(fileMeta%xFloatAttNames(iTmp)),&\n                             fileMeta%xRealAttVals(iTmp,1:fileMeta%xRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place x floating point attributes into CHRTOUT_GRID file.')\n      end do\n      do iTmp=1,fileMeta%nxCharAtts\n         iret = nf90_put_att(ftn,xVarId,trim(fileMeta%xCharAttNames(iTmp)),trim(fileMeta%xCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place x string point attributes into CHRTOUT_GRID file.')\n      end do\n      iret = nf90_def_var(ftn,'y',nf90_double,dimId(3),yVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create y coordinate variable')\n      do iTmp=1,fileMeta%nyRealAtts\n         iret = nf90_put_att(ftn,yVarId,trim(fileMeta%yFloatAttNames(iTmp)),&\n                             fileMeta%yRealAttVals(iTmp,1:fileMeta%yRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place y floating point attributes into CHRTOUT_GRID file.')\n      end do\n      do iTmp=1,fileMeta%nyCharAtts\n         iret = nf90_put_att(ftn,yVarId,trim(fileMeta%yCharAttNames(iTmp)),trim(fileMeta%yCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place y string point attributes into CHRTOUT_GRID file.')\n      end do\n\n      ! Define compression for meta-variables only if io_form_outputs is set to 1.\n      if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n         iret = nf90_def_var_deflate(ftn,timeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for time.')\n         iret = nf90_def_var_deflate(ftn,refTimeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reference_time.')\n         iret = nf90_def_var_deflate(ftn,xVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for x.')\n         iret = nf90_def_var_deflate(ftn,yVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for y.')\n      endif\n\n      ! Translate crs variable info from land spatial metadata file to output\n      ! file.\n      iret = nf90_def_var(ftn,'crs',nf90_char,varid=coordVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create crs variable in CHRTOUT_GRID file.')\n      do iTmp=1,fileMeta%nCrsRealAtts\n         iret = nf90_put_att(ftn,coordVarId,trim(fileMeta%crsFloatAttNames(iTmp)),&\n                             fileMeta%crsRealAttVals(iTmp,1:fileMeta%crsRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place crs floating point attributes into CHRTOUT_GRID file.')\n      end do\n      do iTmp=1,fileMeta%nCrsCharAtts\n         iret = nf90_put_att(ftn,coordVarId,trim(fileMeta%crsCharAttNames(iTmp)),trim(fileMeta%crsCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place crs string point attributes into CHRTOUT_GRID file.')\n      end do\n\n      ! Create channel index variable.\n      iret = nf90_def_var(ftn,'index',nf90_int,(/dimId(2),dimId(3)/),varid=indexVarId)\n      iret = nf90_put_att(ftn,indexVarId,'_FillValue',-9999)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable index')\n      iret = nf90_put_att(ftn,indexVarId,'missing_value',-9999)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable index')\n      iret = nf90_put_att(ftn,indexVarId,'long_name','Streamflow Index Value')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable index')\n      iret = nf90_put_att(ftn,indexVarId,'units','-')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable index')\n      iret = nf90_put_att(ftn,indexVarId,'grid_mapping','crs')\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping attribute into variable: index')\n      ! Place necessary geospatial attributes into the variable.\n      do iTmp2=1,fileMeta%nCrsCharAtts\n         if(trim(fileMeta%crsCharAttNames(iTmp2)) .eq. 'esri_pe_string') then\n            iret = nf90_put_att(ftn,indexVarId,trim(fileMeta%crsCharAttNames(iTmp2)),trim(fileMeta%crsCharAttVals(iTmp2)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place esri_pe_string attribute into '//trim(fileMeta%varNames(iTmp)))\n         endif\n      end do\n      ! Define compression for meta-variables only if io_form_outputs is set to 1.\n      if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n         iret = nf90_def_var_deflate(ftn,indexVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for index.')\n      endif\n\n      ! Loop through all possible variables and create them, along with their\n      ! metadata attributes.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(3),dimId(1)/),varId)\n            else\n               iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(3),dimId(1)/),varId)\n            endif\n            call nwmCheck(diagFlag,iret,\"ERROR: Unable to create variable: \"//trim(fileMeta%varNames(iTmp)))\n\n            ! Extract valid range into a 1D array for placement.\n            varRange(1) = fileMeta%validMinComp(iTmp)\n            varRange(2) = fileMeta%validMaxComp(iTmp)\n            varRangeReal(1) = real(fileMeta%validMinDbl(iTmp))\n            varRangeReal(2) = real(fileMeta%validMaxDbl(iTmp))\n\n            ! Establish a compression level for the variables. For now we are\n            ! using a\n            ! compression level of 2. In addition, we are choosing to turn the\n            ! shuffle\n            ! filter off for now. Kelley Eicher did some testing with this and\n            ! determined that the benefit wasn't worth the extra time spent\n            ! writing output.\n            ! Only compress if io_form_outputs is set to 1.\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n               iret = nf90_def_var_deflate(ftn,varId,0,1,2)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression for: '//trim(fileMeta%varNames(iTmp)))\n            endif\n\n            ! Create variable attributes\n            iret = nf90_put_att(ftn,varId,'long_name',trim(fileMeta%longName(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'units',trim(fileMeta%units(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'grid_mapping','crs')\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping attribute into variable: '//trim(fileMeta%varNames(iTmp)))\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'scale_factor',fileMeta%scaleFactor(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place scale_factor attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'add_offset',fileMeta%addOffset(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place add_offset attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRange)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            else\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRangeReal)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            endif\n            ! Place necessary geospatial attributes into the variable.\n            do iTmp2=1,fileMeta%nCrsCharAtts\n               if(trim(fileMeta%crsCharAttNames(iTmp2)) .eq. 'esri_pe_string') then\n                  iret = nf90_put_att(ftn,varId,trim(fileMeta%crsCharAttNames(iTmp2)),trim(fileMeta%crsCharAttVals(iTmp2)))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place esri_pe_string attribute into '//trim(fileMeta%varNames(iTmp)))\n               endif\n            end do\n         endif\n      end do ! end looping through variable output list.\n\n      ! Remove NetCDF file from definition mode.\n      iret = nf90_enddef(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to take RT_DOMAIN file out of definition mode')\n\n      ! Read in coordinates from FullDom file. These will be placed into the\n      ! output file coordinate variables.\n      allocate(xCoord(RT_DOMAIN(domainId)%g_ixrt))\n      allocate(yCoord(RT_DOMAIN(domainId)%g_jxrt))\n      allocate(yCoord2(RT_DOMAIN(domainId)%g_jxrt))\n      iret = nf90_open(trim(nlst(domainId)%geo_finegrid_flnm),NF90_NOWRITE,ncid=ftnGeo)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to open FullDom file')\n      iret = nf90_inq_varid(ftnGeo,'x',geoXVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to find x coordinate in FullDom file')\n      iret = nf90_get_var(ftnGeo,geoXVarId,xCoord)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to extract x coordinate from FullDom file')\n      iret = nf90_inq_varid(ftnGeo,'y',geoYVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to find y coordinate in FullDom file')\n      iret = nf90_get_var(ftnGeo,geoYVarId,yCoord)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to extract y coordinate from FullDom file')\n      iret = nf90_close(ftnGeo)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close geoGrid file.')\n\n      ! Reverse Y coordinates. They are read in reverse.\n      jTmp2 = 0\n      do jTmp = RT_DOMAIN(domainId)%g_jxrt,1,-1\n         jTmp2 = jTmp2 + 1\n         yCoord2(jTmp2) = yCoord(jTmp)\n      end do\n      ! Place coordinate values into output file\n      iret = nf90_inq_varid(ftn,'x',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate x coordinate variable.')\n      iret = nf90_put_var(ftn,varId,xCoord)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into x coordinate variable')\n      iret = nf90_inq_varid(ftn,'y',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate y coordinate variable')\n      iret = nf90_put_var(ftn,varId,yCoord2)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into y coordinate variable')\n      deallocate(xCoord)\n      deallocate(yCoord)\n      deallocate(yCoord2)\n\n      ! Place streamflow index values into output file.\n      iret = nf90_inq_varid(ftn,'index',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate index variable.')\n      iret = nf90_put_var(ftn,varId,CH_NETLNK,(/1,1/),(/RT_DOMAIN(domainId)%g_ixrt,RT_DOMAIN(domainId)%g_jxrt/))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place CH_NETLNK values into index variable.')\n\n      ! Place time values into time variables.\n      iret = nf90_inq_varid(ftn,'time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into time variable')\n      iret = nf90_inq_varid(ftn,'reference_time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reference_time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch1)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into reference_time variable')\n\n      ! Since the only variable we are \"looping\" over for output is streamflow,\n      ! handle below. If other variables are added later, we can modify this\n      ! section.\n      do jTmp=1,RT_DOMAIN(domainId)%g_jxrt\n         do iTmp=1,RT_DOMAIN(domainId)%g_ixrt\n            if(CH_NETLNK(iTmp,jTmp).GE.0) then\n               tmpFlow(iTmp,jTmp) = NINT((g_qlink(CH_NETLNK(iTmp,jTmp),1)-fileMeta%addOffset(1))/fileMeta%scaleFactor(1))\n               tmpFlowReal(iTmp,jTmp) = g_qlink(CH_NETLNK(iTmp,jTmp),1)\n            else\n                tmpFlow(iTmp,jTmp) = fileMeta%fillComp(1)\n                tmpFlowReal(iTmp,jTmp) = fileMeta%fillReal(1)\n            endif\n         enddo\n      enddo\n\n      ! Place streamflow grid into output file.\n      iret = nf90_inq_varid(ftn,'streamflow',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate streamflow variable.')\n      if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n         iret = nf90_put_var(ftn,varId,tmpFlow,(/1,1,1/),(/RT_DOMAIN(domainId)%g_ixrt,RT_DOMAIN(domainId)%g_jxrt,1/))\n      else\n         iret = nf90_put_var(ftn,varId,tmpFlowReal,(/1,1,1/),(/RT_DOMAIN(domainId)%g_ixrt,RT_DOMAIN(domainId)%g_jxrt,1/))\n      endif\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place streamflow values into CHRTOUT_GRID')\n\n   endif ! End if statement if on I/O ID\n\n   if(myId .eq. 0) then\n      ! Close the output file\n      iret = nf90_close(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close RT_DOMAIN file.')\n   endif\n\n   ! Deallocate memory as needed\n   deallocate(g_qlink, CH_NETLNK, tmpFlow, tmpFlowReal, strFlowLocal)\n\nend subroutine output_chrtout_grd_NWM\n\n!===============================================================================\n! Program Name: output_lsmOut_NWM\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Output routine fro diagnostic LSM grids.\n! History Log:\n! 8/9/17 -Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files. None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\n\nsubroutine output_lsmOut_NWM(domainId)\n  use module_rt_data, only: rt_domain\n  use config_base, only: nlst\n  use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n  use module_NWM_io_dict\n  use netcdf\n#ifdef MPP_LAND\n  use module_mpp_land\n#endif\n  implicit none\n\n   ! Subroutine arguments\n   integer, intent(in) :: domainId\n\n   ! Derived types.\n   type(lsmMeta) :: fileMeta\n\n   ! Local variables\n   integer :: minSinceSim ! Number of minutes since beginning of simulation.\n   integer :: minSinceEpoch1 ! Number of minutes from EPOCH to the beginning of the model simulation.\n   integer :: minSinceEpoch ! Number of minutes from EPOCH to the current model valid time.\n   character(len=16) :: epochDate ! EPOCH represented as a string.\n   character(len=16) :: startDateTmp ! Start of model simulation, represented as a string.\n   character(len=256) :: validTime ! Global attribute time string\n   character(len=256) :: initTime ! Global attribute time string\n   integer :: mppFlag, diagFlag\n   character(len=1024) :: output_flnm ! Output file name\n   integer :: iret ! NetCDF return status\n   integer :: ftn  ! NetCDF file handle\n   integer :: dimId(4) ! NetCDF dimension ID values\n   integer :: varId ! NetCDF variable ID value\n   integer :: timeId ! NetCDF time variable ID\n   integer :: refTimeId ! NetCDF reference_time variable ID\n   integer :: coordVarId ! NetCDF coordinate variable ID\n   integer :: xVarId,yVarId ! NetCDF x/y variable ID\n   integer :: ierr, myId ! MPI related values\n   !integer :: varRange(2) ! Local storage of valid min/max values\n   real :: varRange(2) ! Local storage of valid min/max values\n   integer :: iTmp,jTmp,iTmp2,jTmp2\n   integer :: ftnGeo,geoXVarId,geoYVarId\n   integer :: waterVal ! Value in HRLDAS in WRFINPUT file used to define water bodies for masking\n   real*8, allocatable, dimension(:) :: yCoord,xCoord,yCoord2\n   real :: varRealTmp\n   real, allocatable, dimension(:,:) :: localRealTmp, globalOutReal\n   !integer, allocatable, dimension(:,:) :: globalCompTmp, localCompTmp\n\n   character (len=64) :: modelConfigType ! This is character verion (long name) for the io_config_outputs\n\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Some sanity checking here.\n   if(nlst(domainId)%LSMOUT_DOMAIN .eq. 0) then\n      ! No output requested here. Return to the parent calling program.\n      return\n   endif\n\n   ! Call routine to initialize metadata structure\n   call initLsmOutDict(fileMeta,myId,diagFlag)\n\n   ! Initialize the water type\n   waterVal = rt_domain(domainId)%iswater\n\n   ! Calculate necessary datetime information that will go into the output file.\n   ! First compose strings of EPOCH and simulation start date.\n   epochDate = trim(\"1970-01-01 00:00\")\n   startDateTmp = trim(nlst(1)%startdate(1:4)//\"-\"//&\n                       nlst(1)%startdate(6:7)//&\n                       &\"-\"//nlst(1)%startdate(9:10)//\" \"//&\n                       nlst(1)%startdate(12:13)//\":\"//&\n                       nlst(1)%startdate(15:16))\n   ! Second, utilize NoahMP date utilities to calculate the number of minutes\n   ! from EPOCH to the beginning of the model simulation.\n   call geth_idts(startDateTmp,epochDate,minSinceEpoch1)\n   ! Third, calculate the number of minutes since the beginning of the\n   ! simulation.\n   minSinceSim = int(nlst(1)%out_dt*(rt_domain(1)%out_counts-1))\n   ! Fourth, calculate the total number of minutes from EPOCH to the current\n   ! model time step.\n   minSinceEpoch = minSinceEpoch1 + minSinceSim\n   ! Fifth, compose global attribute time strings that will be used.\n   validTime = trim(nlst(1)%olddate(1:4)//'-'//&\n                    nlst(1)%olddate(6:7)//'-'//&\n                    nlst(1)%olddate(9:10)//'_'//&\n                    nlst(1)%olddate(12:13)//':'//&\n                    nlst(1)%olddate(15:16)//&\n                    &':00')\n   initTime = trim(nlst(1)%startdate(1:4)//'-'//&\n                  nlst(1)%startdate(6:7)//'-'//&\n                  nlst(1)%startdate(9:10)//'_'//&\n                  nlst(1)%startdate(12:13)//':'//&\n                  nlst(1)%startdate(15:16)//&\n                  &':00')\n   ! Replace default values in the dictionary.\n   fileMeta%initTime = trim(initTime)\n   fileMeta%validTime = trim(validTime)\n\n   ! calculate the minimum and maximum time\n   fileMeta%timeValidMin = minSinceEpoch1 + nlst(1)%out_dt\n   fileMeta%timeValidMax = minSinceEpoch1 + int(nlst(1)%khour * 60/nlst(1)%out_dt) * nlst(1)%out_dt\n\n   ! calculate total_valid_time\n   fileMeta%totalValidTime = int(nlst(1)%khour * 60 / nlst(1)%out_dt)  ! # number of valid time (#of output files)\n\n   ! For now, will always default to outputting all available\n   ! variables since the nature of this output file is\n   ! diagnostic in nature.\n   fileMeta%outFlag(:) = [1,1,1,1,1,1,1,1,1,1,1,1,1,1]\n\n   ! call the GetModelConfigType function\n   modelConfigType = GetModelConfigType(nlst(1)%io_config_outputs)\n\n   if(myId .eq. 0) then\n      ! We are on the I/O node. Create output file.\n      write(output_flnm,'(A12,\".LSMOUT_DOMAIN\",I1)') nlst(domainId)%olddate(1:4)//&\n            nlst(domainId)%olddate(6:7)//nlst(domainId)%olddate(9:10)//&\n            nlst(domainId)%olddate(12:13)//nlst(domainId)%olddate(15:16),&\n            nlst(domainId)%igrid\n\n      iret = nf90_create(trim(output_flnm),cmode=NF90_NETCDF4,ncid = ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create LSMOUT NetCDF file.')\n\n      ! Write global attributes\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'TITLE',trim(fileMeta%title))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place TITLE attribute into LSMOUT file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"compiler_version\",compiler_version())\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create compiler_version attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'model_initialization_time',trim(fileMeta%initTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model init time attribute into LSMOUT file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'model_output_valid_time',trim(fileMeta%validTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model output time attribute into LSMOUT file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'modle_total_valid_time',fileMeta%totalValidTime)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place model total valid time attribute into LSMOUT file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,'Conventions',trim(fileMeta%conventions))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place CF conventions attribute into LSMOUT file.')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"code_version\",trim(get_code_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create code_version attribute')\n#ifdef NWM_META\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"NWM_version_number\",trim(get_nwm_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create NWM_version_number attribute')\n#endif\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_type\",trim(fileMeta%modelOutputType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_output_type attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_configuration\",modelConfigType)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_configuration attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"proj4\",trim(fileMeta%proj4))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create proj4 attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"GDAL_DataType\",\"Generic\")\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create GDAL_DataType attribute')\n\n      ! Create dimensions\n      iret = nf90_def_dim(ftn,'time',NF90_UNLIMITED,dimId(1))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define time dimension')\n      iret = nf90_def_dim(ftn,'x',global_nx,dimId(2))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define x dimension')\n      iret = nf90_def_dim(ftn,'y',global_ny,dimId(3))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define y dimension')\n      iret = nf90_def_dim(ftn,'reference_time',1,dimId(4))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to define reference_time dimension')\n\n      ! Create and populate reference_time and time variables.\n      iret = nf90_def_var(ftn,\"time\",nf90_int,dimId(1),timeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time variable')\n      iret = nf90_put_att(ftn,timeId,'long_name',trim(fileMeta%timeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'standard_name',trim(fileMeta%timeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'units',trim(fileMeta%timeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_min',fileMeta%timeValidMin)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_min attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_max',fileMeta%timeValidMax)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_max attribute into time variable')\n      iret = nf90_def_var(ftn,\"reference_time\",nf90_int,dimId(4),refTimeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'long_name',trim(fileMeta%rTimeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'standard_name',trim(fileMeta%rTimeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'units',trim(fileMeta%rTimeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reference_time variable')\n\n      ! Create x/y coordinate variables\n      iret = nf90_def_var(ftn,'x',nf90_double,dimId(2),xVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create x coordinate variable')\n      do iTmp=1,fileMeta%nxRealAtts\n         iret = nf90_put_att(ftn,xVarId,trim(fileMeta%xFloatAttNames(iTmp)),&\n                             fileMeta%xRealAttVals(iTmp,1:fileMeta%xRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place x floating point attributes into LSMOUT file.')\n      end do\n      do iTmp=1,fileMeta%nxCharAtts\n         iret = nf90_put_att(ftn,xVarId,trim(fileMeta%xCharAttNames(iTmp)),trim(fileMeta%xCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place x string point attributes into LSMOUT file.')\n      end do\n      iret = nf90_def_var(ftn,'y',nf90_double,dimId(3),yVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create y coordinate variable')\n      do iTmp=1,fileMeta%nyRealAtts\n         iret = nf90_put_att(ftn,yVarId,trim(fileMeta%yFloatAttNames(iTmp)),&\n                             fileMeta%yRealAttVals(iTmp,1:fileMeta%yRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place y floating point attributes into LSMOUT file.')\n      end do\n      do iTmp=1,fileMeta%nyCharAtts\n         iret = nf90_put_att(ftn,yVarId,trim(fileMeta%yCharAttNames(iTmp)),trim(fileMeta%yCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place y string point attributes into LSMOUT file.')\n      end do\n\n      ! Define compression for meta-variables. Only compress if io_form_outputs is set\n      ! to 1.\n      if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n         iret = nf90_def_var_deflate(ftn,timeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for time.')\n         iret = nf90_def_var_deflate(ftn,refTimeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reference_time.')\n         iret = nf90_def_var_deflate(ftn,xVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for x.')\n         iret = nf90_def_var_deflate(ftn,yVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for y.')\n      endif\n\n      ! Translate crs variable info from land spatial metadata file to output\n      ! file.\n      iret = nf90_def_var(ftn,'crs',nf90_char,varid=coordVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create crs variable in LSMOUT file.')\n      do iTmp=1,fileMeta%nCrsRealAtts\n         iret = nf90_put_att(ftn,coordVarId,trim(fileMeta%crsFloatAttNames(iTmp)),&\n                             fileMeta%crsRealAttVals(iTmp,1:fileMeta%crsRealAttLen(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place crs floating point attributes into LSMOUT file.')\n      end do\n      do iTmp=1,fileMeta%nCrsCharAtts\n         iret = nf90_put_att(ftn,coordVarId,trim(fileMeta%crsCharAttNames(iTmp)),trim(fileMeta%crsCharAttVals(iTmp)))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place crs string point attributes into LSMOUT file.')\n      end do\n\n      ! Loop through all possible variables and create them, along with their\n      ! metadata attributes.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            !iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_int,(/dimId(2),dimId(3),dimId(1)/),varId)\n            iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_float,(/dimId(2),dimId(3),dimId(1)/),varId)\n            call nwmCheck(diagFlag,iret,\"ERROR: Unable to create variable: \"//trim(fileMeta%varNames(iTmp)))\n\n            ! Extract valid range into a 1D array for placement.\n            varRange(1) = fileMeta%validMinDbl(iTmp)\n            varRange(2) = fileMeta%validMaxDbl(iTmp)\n\n            ! Establish a compression level for the variables. For now we are using a\n            ! compression level of 2. In addition, we are choosing to turn the shuffle\n            ! filter off for now. Kelley Eicher did some testing with this and\n            ! determined that the benefit wasn't worth the extra time spent writing output.\n            ! Only compress if io_form_outputs is set to 1.\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n               iret = nf90_def_var_deflate(ftn,varId,0,1,2)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression for: '//trim(fileMeta%varNames(iTmp)))\n            endif\n\n            ! Create variable attributes\n            iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillReal(iTmp))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingReal(iTmp))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'long_name',trim(fileMeta%longName(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'units',trim(fileMeta%units(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'grid_mapping','crs')\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping attribute into variable: '//trim(fileMeta%varNames(iTmp)))\n            ! Place necessary geospatial attributes into the variable.\n            do iTmp2=1,fileMeta%nCrsCharAtts\n               if(trim(fileMeta%crsCharAttNames(iTmp2)) .eq. 'esri_pe_string') then\n                  iret = nf90_put_att(ftn,varId,trim(fileMeta%crsCharAttNames(iTmp2)),trim(fileMeta%crsCharAttVals(iTmp2)))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place esri_pe_string attribute into '//trim(fileMeta%varNames(iTmp)))\n               endif\n            end do\n         endif ! End if output flag is on\n      end do ! end looping through variable output list.\n\n      ! Remove NetCDF file from definition mode.\n      iret = nf90_enddef(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to take LSMOUT file out of definition mode')\n\n      ! Read in coordinates from GeoGrid file. These will be placed into the\n      ! output file coordinate variables.\n      allocate(xCoord(global_nx))\n      allocate(yCoord(global_ny))\n      allocate(yCoord2(global_ny))\n      iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnGeo)\n      if(iret .ne. 0) then\n         ! Spatial metadata file not found for land grid. Warn the user no\n         ! file was found, and set x/y coordinates to -9999.0\n         call postDiagMsg(diagFlag,'WARNING: Unable to find LAND spatial metadata file')\n         xCoord = -9999.0\n         yCoord = -9999.0\n         yCoord2 = -9999.0\n      else\n         iret = nf90_inq_varid(ftnGeo,'x',geoXVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find x coordinate in geoGrid file')\n         iret = nf90_get_var(ftnGeo,geoXVarId,xCoord)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract x coordinate from geoGrid file')\n         iret = nf90_inq_varid(ftnGeo,'y',geoYVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find y coordinate in geoGrid file')\n         iret = nf90_get_var(ftnGeo,geoYVarId,yCoord)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract y coordinate from geoGrid file')\n         iret = nf90_close(ftnGeo)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close geoGrid file.')\n         ! Reverse Y coordinates. They are read in reverse.\n         jTmp2 = 0\n         do jTmp = global_ny,1,-1\n            jTmp2 = jTmp2 + 1\n            yCoord2(jTmp2) = yCoord(jTmp)\n         end do\n      endif\n\n      ! Place coordinate values into output file\n      iret = nf90_inq_varid(ftn,'x',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate x coordinate variable.')\n      iret = nf90_put_var(ftn,varId,xCoord)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into x coordinate variable')\n      iret = nf90_inq_varid(ftn,'y',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate y coordinate variable')\n      iret = nf90_put_var(ftn,varId,yCoord2)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into y coordinate variable')\n      deallocate(xCoord)\n      deallocate(yCoord)\n      deallocate(yCoord2)\n\n      ! Place time values into time variables.\n      iret = nf90_inq_varid(ftn,'time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into time variable')\n      iret = nf90_inq_varid(ftn,'reference_time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reference_time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch1)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into reference_time variable')\n\n   end if ! End if we are on the I/O processor.\n\n   ! Allocate temporary local memory\n   allocate(localRealTmp(rt_domain(domainId)%ix,rt_domain(domainId)%jx))\n\n   ! Loop through all possible variables to output. Collect the data to the\n   ! global grid and output to the necessary NetCDF variable.\n   do iTmp=1,fileMeta%numVars\n      if(fileMeta%outFlag(iTmp) .eq. 1) then\n         ! Allocate memory necessary\n         if(myId .eq. 0) then\n            allocate(globalOutReal(global_nx,global_ny))\n         else\n            allocate(globalOutReal(1,1))\n         endif\n\n         ! Loop through the local array and convert floating point values\n         ! to integer via scale_factor/add_offset. If the pixel value\n         ! falls within a water class value, leave as ndv.\n         do iTmp2 = 1,rt_domain(domainId)%ix\n            do jTmp2 = 1,rt_domain(domainId)%jx\n               if(iTmp .eq. 1) then\n                  varRealTmp = rt_domain(domainId)%stc(iTmp2,jTmp2,1)\n               else if(iTmp .eq. 2) then\n                  varRealTmp = rt_domain(domainId)%smc(iTmp2,jTmp2,1)\n               else if(iTmp .eq. 3) then\n                  varRealTmp = rt_domain(domainId)%sh2ox(iTmp2,jTmp2,1)\n               else if(iTmp .eq. 4) then\n                  varRealTmp = rt_domain(domainId)%stc(iTmp2,jTmp2,2)\n               else if(iTmp .eq. 5) then\n                  varRealTmp = rt_domain(domainId)%smc(iTmp2,jTmp2,2)\n               else if(iTmp .eq. 6) then\n                  varRealTmp = rt_domain(domainId)%sh2ox(iTmp2,jTmp2,2)\n               else if(iTmp .eq. 7) then\n                  varRealTmp = rt_domain(domainId)%stc(iTmp2,jTmp2,3)\n               else if(iTmp .eq. 8) then\n                  varRealTmp = rt_domain(domainId)%smc(iTmp2,jTmp2,3)\n               else if(iTmp .eq. 9) then\n                  varRealTmp = rt_domain(domainId)%sh2ox(iTmp2,jTmp2,3)\n               else if(iTmp .eq. 10) then\n                  varRealTmp = rt_domain(domainId)%stc(iTmp2,jTmp2,4)\n               else if(iTmp .eq. 11) then\n                  varRealTmp = rt_domain(domainId)%smc(iTmp2,jTmp2,4)\n               else if(iTmp .eq. 12) then\n                  varRealTmp = rt_domain(domainId)%sh2ox(iTmp2,jTmp2,4)\n               else if(iTmp .eq. 13) then\n                  varRealTmp = rt_domain(domainId)%INFXSRT(iTmp2,jTmp2)\n               else if(iTmp .eq. 14) then\n                  varRealTmp = rt_domain(domainId)%overland%control%surface_water_head_lsm(iTmp2,jTmp2) ! updated to use new location of sfcheadrt\n               endif\n\n               ! For now, we are foregoing converting these variables to integer\n               ! via scale_factor/add_offset. This file is meant for diagnostic\n               ! purposes, so we want to keep full precision.\n               localRealTmp(iTmp2,jTmp2) = varRealTmp\n\n               ! If we are on time 0, make sure we don't need to fill in the\n               ! grid with NDV values.\n               !if(minSinceSim .eq. 0 .and. fileMeta%timeZeroFlag(iTmp) .eq. 0) then\n               !   localCompTmp(iTmp2,jTmp2) = fileMeta%fillComp(iTmp)\n               !else\n               !   if(varRealTmp .eq. fileMeta%modelNdv) then\n               !      localCompTmp(iTmp2,jTmp2) = INT(fileMeta%fillComp(iTmp))\n               !   else\n               !      localCompTmp(iTmp2,jTmp2) = NINT((varRealTmp-fileMeta%addOffset(iTmp))/fileMeta%scaleFactor(iTmp))\n               !   endif\n               !   if(vegTyp(iTmp2,jTmp2) .eq. waterVal) then\n               !      localCompTmp(iTmp2,jTmp2) = INT(fileMeta%fillComp(iTmp))\n               !   endif\n               !endif\n            enddo\n         enddo\n         ! Collect local 2D arrays to global 2D array\n         if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n            call write_IO_real(localRealTmp,globalOutReal)\n#endif\n         else\n            globalOutReal = localRealTmp\n         endif\n\n         ! Write array out to NetCDF file\n         if(myId .eq. 0) then\n            iret = nf90_inq_varid(ftn,trim(fileMeta%varNames(iTmp)),varId)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find variable ID for var: '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_var(ftn,varId,globalOutReal,(/1,1,1/),(/global_nx,global_ny,1/))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into output variable: '//trim(fileMeta%varNames(iTmp)))\n         endif\n\n         deallocate(globalOutReal)\n      endif\n   enddo\n\n   if(myId .eq. 0) then\n      ! Close the output file\n      iret = nf90_close(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close LSMOUT_DOMAIN file.')\n   endif\n\n   deallocate(localRealTmp)\n\nend subroutine output_lsmOut_NWM\n\n!==============================================================================\n! Program Name: output_frxstPts\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Output frxstPts ASCII file from streamflow at forecast points\n! defined in the Fulldom file.\n! History Log:\n! 9/18/17 -Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files: None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\nsubroutine output_frxstPts(domainId)\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst\n   use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n   use module_NWM_io_dict\n#ifdef MPP_LAND\n   use module_mpp_land\n   use module_mpp_reachls,  only: ReachLS_write_io\n#endif\nimplicit none\n\n   ! Pass in \"did\" value from hydro driving program.\n   integer, intent(in) :: domainId\n\n   ! Local variables\n   integer :: mppFlag, diagFlag, ierr, myId\n   integer :: seconds_since\n   integer :: gSize, iTmp, numPtsOut\n   integer, allocatable, dimension(:) :: g_STRMFRXSTPTS, g_outInd\n   real, allocatable, dimension(:,:) :: g_qlink, g_qlinkOut\n   real, allocatable, dimension(:) :: g_chlat, g_chlon, g_hlink, strFlowLocal\n   integer, allocatable, dimension(:) :: frxstPtsLocal, g_STRMFRXSTPTSOut\n   real, allocatable, dimension(:) :: g_chlatOut, g_chlonOut, g_hlinkOut\n   integer(kind=int64), allocatable, dimension(:) :: g_linkid, g_linkidOut\n\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   if(nlst(domainId)%frxst_pts_out .eq. 0) then\n      ! No output requested here, return to parent calling program/subroutine.\n      return\n   endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Calculate datetime information\n   seconds_since = int(nlst(1)%out_dt*60*(rt_domain(1)%out_counts-1))\n\n   ! First step is to allocate a global array of index values. This \"index\"\n   ! array will be used to subset after collection has taken place. Also,\n   ! the sum of this array will be used to determine the size of the output\n   ! arrays.\n   if(mppFlag .eq. 1) then\n      if(nlst(domainId)%channel_option .ne. 3) then\n         gSize = rt_domain(domainId)%gnlinksl\n      else\n         gSize = rt_domain(domainId)%gnlinks\n      endif\n\n      if(myId .eq. 0) then\n         allocate(g_STRMFRXSTPTS(gSize))\n         allocate(g_outInd(gSize))\n         allocate(g_qlink(gSize,2))\n         allocate(g_chlat(gSize))\n         allocate(g_chlon(gSize))\n         allocate(g_hlink(gSize))\n         allocate(g_linkid(gSize))\n      else\n         allocate(g_STRMFRXSTPTS(1))\n         allocate(g_outInd(1))\n         allocate(g_qlink(1,2))\n         allocate(g_chlat(1))\n         allocate(g_chlon(1))\n         allocate(g_hlink(1))\n         allocate(g_linkid(1))\n      endif\n\n      ! Initialize the index array to 0\n      g_outInd = 0\n\n      ! Allocate local streamflow arrays. We need to do a check to\n      ! for lake_type 2. However, we cannot set the values in the global array\n      ! to missing as this causes the model to crash.\n      allocate(strFlowLocal(RT_DOMAIN(domainId)%NLINKS))\n      allocate(frxstPtsLocal(RT_DOMAIN(domainId)%NLINKS))\n      strFlowLocal = RT_DOMAIN(domainId)%QLINK(:,1)\n      frxstPtsLocal = rt_domain(domainId)%STRMFRXSTPTS\n\n      ! Loop through all the local links on this processor. For lake_type\n      ! of 2, we need to manually set the streamflow values\n      ! to the model NDV value.\n      if (RT_DOMAIN(domainId)%NLAKES .gt. 0) then\n         do iTmp=1,RT_DOMAIN(domainId)%NLINKS\n            if (RT_DOMAIN(domainId)%TYPEL(iTmp) .eq. 2) then\n               !strFlowLocal(iTmp) = fileMeta%modelNdv\n               strFlowLocal(iTmp) = -9.E15\n               frxstPtsLocal(iTmp) = -9999\n            endif\n         end do\n      endif\n\n      ! Collect arrays from various processors\n      if(nlst(domainId)%channel_option .eq. 3) then\n         call write_chanel_int(frxstPtsLocal,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_STRMFRXSTPTS)\n         call write_chanel_real(strFlowLocal,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_qlink(:,1))\n         call write_chanel_real(RT_DOMAIN(domainId)%QLINK(:,2),rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_qlink(:,2))\n         call write_chanel_real(RT_DOMAIN(domainId)%CHLAT,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_chlat)\n         call write_chanel_real(RT_DOMAIN(domainId)%CHLON,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_chlon)\n         call write_chanel_real(RT_DOMAIN(domainId)%HLINK,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_hlink)\n      else\n         call ReachLS_write_io(strFlowLocal,g_qlink(:,1))\n         call ReachLS_write_io(RT_DOMAIN(domainId)%QLINK(:,2),g_qlink(:,2))\n         call ReachLS_write_io(RT_DOMAIN(domainId)%linkid,g_linkid)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%CHLAT,g_chlat)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%CHLON,g_chlon)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%HLINK,g_hlink)\n      endif\n\n      deallocate(strFlowLocal)\n      deallocate(frxstPtsLocal)\n\n   else\n      ! Running sequentially on a single processor.\n      gSize = rt_domain(domainId)%nlinks\n      allocate(g_STRMFRXSTPTS(gSize))\n      allocate(g_outInd(gSize))\n      allocate(g_chlon(gSize))\n      allocate(g_chlat(gSize))\n      allocate(g_hlink(gSize))\n      allocate(g_qlink(gSize,2))\n      allocate(g_linkid(gSize))\n\n      ! Initialize the index array to 0\n      g_outInd = 0\n\n      g_STRMFRXSTPTS = rt_domain(domainId)%STRMFRXSTPTS\n      g_chlon = RT_DOMAIN(domainId)%CHLON\n      g_chlat = RT_DOMAIN(domainId)%CHLAT\n      g_hlink = RT_DOMAIN(domainId)%HLINK\n      g_qlink = RT_DOMAIN(domainId)%QLINK\n      g_linkid = RT_DOMAIN(domainId)%linkid\n   endif\n\n   if(myId .eq. 0) then\n      ! Set index values to 1 where we have forecast points.\n      if(nlst(domainId)%channel_option .eq. 3) then\n         where(g_STRMFRXSTPTS .ne. -9999) g_outInd = 1\n      endif\n\n      if(nlst(domainId)%channel_option .ne. 3) then\n         ! Check to see if we have any gages that need to be added for reach-based\n         ! routing.\n         call checkRouteGages(diagFlag,gSize,g_outInd)\n      endif\n\n      ! Filter out any missing values that may have filtered through to this\n      ! point.\n      where(g_qlink(:,1) .le. -9999) g_outInd = 0\n\n      ! Allocate output arrays based on size of number of forecast points.\n      numPtsOut = SUM(g_outInd)\n\n      if(numPtsOut .eq. 0) then\n         ! Write warning message to user showing there are NO forecast points to\n         ! write. Simply return to the main calling function.\n         call postDiagMsg(diagFlag,'WARNING: No forecast or gage points found for frxstPtsOut. No file will be created.')\n         return\n      endif\n\n      ! Allocate output arrays based on number of output forecast points.\n      allocate(g_STRMFRXSTPTSOut(numPtsOut))\n      allocate(g_chlonOut(numPtsOut))\n      allocate(g_chlatOut(numPtsOut))\n      allocate(g_hlinkOut(numPtsOut))\n      allocate(g_qlinkOut(numPtsOut,2))\n      allocate(g_linkidOut(numPtsOut))\n\n      ! Subset global arrays for forecast points.\n      g_STRMFRXSTPTSOut = PACK(g_STRMFRXSTPTS,g_outInd == 1)\n      g_chlonOut = PACK(g_chlon,g_outInd == 1)\n      g_chlatOut = PACK(g_chlat,g_outInd == 1)\n      g_hlinkOut = PACK(g_hlink,g_outInd == 1)\n      g_qlinkOut(:,1) = PACK(g_qlink(:,1),g_outInd == 1)\n      g_qlinkOut(:,2) = PACK(g_qlink(:,2),g_outInd == 1)\n      g_linkidOut = PACK(g_linkid,g_outInd == 1)\n\n      ! Open the output file.\n      open (unit=55,file='frxst_pts_out.txt',status='unknown',position='append')\n\n      ! Loop through forecast points and write output.\n      do iTmp=1,numPtsOut\n         if(nlst(domainId)%channel_option .eq. 3) then\n            ! Instead of a gage ID, we are simply going to output the forecast\n            ! point number assigned during the pre-processing.\n117         FORMAT(I8,\",\",A10,1X,A8,\",\",I12,\",\",F10.5,\",\",F8.5,\",\",F15.3,\",\",F18.3,\",\",F6.3)\n            write(55,117) seconds_since, nlst(domainId)%olddate(1:18),&\n                          nlst(domainId)%olddate(12:19),&\n                          g_STRMFRXSTPTSOut(iTmp),g_chlonOut(iTmp),&\n                          g_chlatOut(iTmp),g_qlinkOut(iTmp,1),&\n                          g_qlinkOut(iTmp,1)*35.314666711511576,&\n                          g_hlinkOut(iTmp)\n         else\n            write(55,117) seconds_since, nlst(domainId)%olddate(1:18),&\n                          nlst(domainId)%olddate(12:19),&\n                          g_linkidOut(iTmp),g_chlonOut(iTmp),&\n                          g_chlatOut(iTmp),g_qlinkOut(iTmp,1),&\n                          g_qlinkOut(iTmp,1)*35.314666711511576,&\n                          g_hlinkOut(iTmp)\n         endif\n      end do\n\n      ! Close the output file\n      close(55)\n   else\n      allocate(g_STRMFRXSTPTSOut(1))\n      allocate(g_chlonOut(1))\n      allocate(g_chlatOut(1))\n      allocate(g_hlinkOut(1))\n      allocate(g_qlinkOut(1,2))\n      allocate(g_linkidOut(1))\n   endif\n\n   ! Deallocate memory\n   deallocate(g_STRMFRXSTPTS)\n   deallocate(g_STRMFRXSTPTSOut)\n   deallocate(g_chlonOut)\n   deallocate(g_chlatOut)\n   deallocate(g_hlinkOut)\n   deallocate(g_qlinkOut)\n   deallocate(g_linkidOut)\n   deallocate(g_chlat)\n   deallocate(g_chlon)\n   deallocate(g_hlink)\n   deallocate(g_qlink)\n   deallocate(g_outInd)\n   deallocate(g_linkid)\n\nend subroutine output_frxstPts\n\n!==============================================================================\n! Program Name: output_chanObs_NWM\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Output routine for channel points at predefined forecast points.\n! History Log:\n! 9/19/17 -Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files: None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\nsubroutine output_chanObs_NWM(domainId)\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst\n   use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n   use module_NWM_io_dict\n   use netcdf\n#ifdef MPP_LAND\n   use module_mpp_land\n   use module_mpp_reachls,  only: ReachLS_write_io\n#endif\n   implicit none\n\n   ! Pass in \"did\" value from hydro driving program.\n   integer, intent(in) :: domainId\n\n   ! Derived types.\n   type(chObsMeta) :: fileMeta\n\n   ! Local variables\n   logical :: single_output_file, single_output_file_exists\n   integer :: nudgeFlag, mppFlag, diagFlag\n   integer :: minSinceSim ! Number of minutes since beginning of simulation.\n   integer :: minSinceEpoch1 ! Number of minutes from EPOCH to the beginning of the model simulation.\n   integer :: minSinceEpoch ! Number of minutes from EPOCH to the current model valid time.\n   integer, dimension(1) :: minSinceEpochVect\n   character(len=16) :: epochDate ! EPOCH represented as a string.\n   character(len=16) :: startDate ! Start of model simulation, represented as a string.\n   character(len=256) :: output_flnm ! CHRTOUT_DOMAIN filename\n   integer :: iret ! NetCDF return statuses\n   integer :: ftn ! NetCDF file handle\n   character(len=256) :: validTime ! Global attribute time string\n   character(len=256) :: initTime ! Global attribute time string\n   integer :: dimId(3) ! Dimension ID values created during NetCDF created.\n   integer :: varId ! Variable ID value created as NetCDF variables are created and populated.\n   integer :: timeId ! Dimension ID for the time dimension.\n   integer :: tmpDimId, n_times, n_feature_ids\n   integer :: refTimeId ! Dimension ID for the reference time dimension.\n   integer :: coordVarId ! Variable to hold crs\n   integer :: featureVarId, elevVarId, orderVarId ! Misc NetCDF variable id values\n   integer :: latVarId, lonVarId ! Lat/lon NetCDF variable id values.\n   integer :: varRange(2) ! Local storage of min/max valid range values.\n   real :: varRangeReal(2) ! Local storage of min/max valid range values.\n   integer :: gSize ! Global size of channel point array.\n   integer :: numPtsOut ! Number of forecast/gage points\n   integer :: iTmp, indTmp ! Misc integer values.\n   integer :: ierr, myId ! MPI return status, process ID\n   ! Establish local, allocatable arrays\n   ! These are used to hold global output arrays, and global output arrays after\n   ! sorting has taken place by ascending feature_id value.\n   real, allocatable, dimension(:) :: strFlowLocal,velocityLocal\n   real, allocatable, dimension(:,:) :: g_qlink\n   integer, allocatable, dimension(:) :: g_order\n   integer(kind=int64), allocatable, dimension(:) :: g_linkid\n   real, allocatable, dimension(:) :: g_chlat,g_chlon,g_hlink,g_zelev\n   real, allocatable, dimension(:,:) :: g_qlinkOut\n   integer, allocatable, dimension(:) :: g_orderOut\n   integer(kind=int64), allocatable, dimension(:) :: g_linkidOut\n   real, allocatable, dimension(:) :: g_chlatOut,g_chlonOut,g_hlinkOut,g_zelevOut\n   real, allocatable, dimension(:,:) :: varOutReal   ! Array holding output variables in real format\n   integer, allocatable, dimension(:) :: varOutInt ! Array holding output variables after\n                                                     ! scale_factor/add_offset\n                                                     ! have been applied.\n   integer, allocatable, dimension(:) :: g_STRMFRXSTPTS, g_outInd\n   integer, allocatable, dimension(:) :: frxstPtsLocal, g_STRMFRXSTPTSOut\n   character (len=64) :: modelConfigType ! This is character verion (long name) for the io_config_outputs\n\n   ! Establish macro variables to hlep guide this subroutine.\n#ifdef WRF_HYDRO_NUDGING\n   nudgeFlag = 1\n#else\n   nudgeFlag = 0\n#endif\n\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   if(nlst(domainId)%CHANOBS_DOMAIN .eq. 0) then\n      ! No output requested here, return to parent calling program/subroutine.\n      return\n   endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Initialize NWM dictionary derived type containing all the necessary metadat\n   ! for the output file.\n   call initChanObsDict(fileMeta, diagFlag, myId)\n\n   ! For now, keep all output variables on, regardless of IOC flag\n   fileMeta%outFlag(:) = [1]\n\n   ! Calculate datetime information.\n   ! First compose strings of EPOCH and simulation start date.\n   epochDate = trim(\"1970-01-01 00:00\")\n   startDate = trim(nlst(domainId)%startdate(1:4)//\"-\"//&\n                    nlst(domainId)%startdate(6:7)//&\n                    &\"-\"//nlst(domainId)%startdate(9:10)//\" \"//&\n                    nlst(domainId)%startdate(12:13)//\":\"//&\n                    nlst(domainId)%startdate(15:16))\n   ! Second, utilize NoahMP date utilities to calculate the number of minutes\n   ! from EPOCH to the beginning of the model simulation.\n   call geth_idts(startDate,epochDate,minSinceEpoch1)\n   ! Third, calculate the number of minutes since the beginning of the\n   ! simulation.\n   minSinceSim = int(nlst(1)%out_dt*(rt_domain(1)%out_counts-1))\n   ! Fourth, calculate the total number of minutes from EPOCH to the current\n   ! model time step.\n   minSinceEpoch = minSinceEpoch1 + minSinceSim\n   minSinceEpochVect(1) = minSinceEpoch\n   ! Fifth, compose global attribute time strings that will be used.\n   validTime = trim(nlst(domainId)%olddate(1:4)//'-'//&\n                    nlst(domainId)%olddate(6:7)//'-'//&\n                    nlst(domainId)%olddate(9:10)//'_'//&\n                    nlst(domainId)%olddate(12:13)//':'//&\n                    nlst(domainId)%olddate(15:16)//&\n                    &':00')\n   initTime = trim(nlst(domainId)%startdate(1:4)//'-'//&\n                  nlst(domainId)%startdate(6:7)//'-'//&\n                  nlst(domainId)%startdate(9:10)//'_'//&\n                  nlst(domainId)%startdate(12:13)//':'//&\n                  nlst(domainId)%startdate(15:16)//&\n                  &':00')\n   ! Replace default values in the dictionary.\n   fileMeta%initTime = trim(initTime)\n   fileMeta%validTime = trim(validTime)\n\n   ! calculate the minimum and maximum time\n   fileMeta%timeValidMin = minSinceEpoch1 + nlst(1)%out_dt\n   fileMeta%timeValidMax = minSinceEpoch1 + int(nlst(1)%khour * 60/nlst(1)%out_dt) * nlst(1)%out_dt\n\n   ! calculate total_valid_time\n   fileMeta%totalValidTime = int(nlst(1)%khour * 60 / nlst(1)%out_dt)  ! # number of valid time (#of output files)\n\n   ! Compose output file name.\n   ! 0 means do not split = single output file\n   single_output_file = nlst(domainId)%split_output_count .eq. 0\n   if(single_output_file) then\n      write(output_flnm,'(\"CHANOBS_DOMAIN\",I1,\".nc\")') nlst(domainId)%igrid\n   else\n      write(output_flnm,'(A12,\".CHANOBS_DOMAIN\",I1)')nlst(domainId)%olddate(1:4)//&\n           nlst(domainId)%olddate(6:7)//nlst(domainId)%olddate(9:10)//&\n           nlst(domainId)%olddate(12:13)//nlst(domainId)%olddate(15:16),&\n           nlst(domainId)%igrid\n   endif\n\n   ! First step is to allocate a global array of index values. This \"index\"\n   ! array will be used to subset after collection has taken place. Also,\n   ! the sum of this array will be used to determine the size of the output\n   ! arrays.\n   if(mppFlag .eq. 1) then\n      if(nlst(domainId)%channel_option .ne. 3) then\n         gSize = rt_domain(domainId)%gnlinksl\n      else\n         gSize = rt_domain(domainId)%gnlinks\n      endif\n\n      if(myId .eq. 0) then\n         allocate(g_STRMFRXSTPTS(gSize))\n         allocate(g_outInd(gSize))\n         allocate(g_qlink(gSize,2))\n         allocate(g_chlat(gSize))\n         allocate(g_chlon(gSize))\n         allocate(g_hlink(gSize))\n         allocate(g_zelev(gSize))\n         allocate(g_order(gSize))\n         allocate(g_linkid(gSize))\n      else\n         allocate(g_STRMFRXSTPTS(1))\n         allocate(g_outInd(1))\n         allocate(g_qlink(1,2))\n         allocate(g_chlat(1))\n         allocate(g_chlon(1))\n         allocate(g_hlink(1))\n         allocate(g_zelev(1))\n         allocate(g_order(1))\n         allocate(g_linkid(1))\n      endif\n\n      ! Initialize the index array to 0\n      g_outInd = 0\n\n      ! Allocate local streamflow arrays. We need to do a check to\n      ! for lake_type 2. However, we cannot set the values in the global array\n      ! to missing as this causes the model to crash.\n      allocate(strFlowLocal(RT_DOMAIN(domainId)%NLINKS))\n      allocate(frxstPtsLocal(RT_DOMAIN(domainId)%NLINKS))\n      strFlowLocal = RT_DOMAIN(domainId)%QLINK(:,1)\n      frxstPtsLocal = rt_domain(domainId)%STRMFRXSTPTS\n\n      ! Loop through all the local links on this processor. For lake_type\n      ! of 2, we need to manually set the streamflow values\n      ! to the model NDV value.\n      if (RT_DOMAIN(domainId)%NLAKES .gt. 0) then\n         do iTmp=1,RT_DOMAIN(domainId)%NLINKS\n            if (RT_DOMAIN(domainId)%TYPEL(iTmp) .eq. 2) then\n               !strFlowLocal(iTmp) = fileMeta%modelNdv\n               strFlowLocal(iTmp) = -9.E15\n               frxstPtsLocal(iTmp) = -9999\n            endif\n         end do\n      endif\n\n      ! Collect arrays from various processors\n      if(nlst(domainId)%channel_option .eq. 3) then\n         call write_chanel_int(frxstPtsLocal,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_STRMFRXSTPTS)\n         call write_chanel_real(strFlowLocal,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_qlink(:,1))\n         call write_chanel_real(RT_DOMAIN(domainId)%QLINK(:,2),rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_qlink(:,2))\n         call write_chanel_real(RT_DOMAIN(domainId)%CHLAT,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_chlat)\n         call write_chanel_real(RT_DOMAIN(domainId)%CHLON,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_chlon)\n         call write_chanel_real(RT_DOMAIN(domainId)%HLINK,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_hlink)\n         call write_chanel_int8(RT_DOMAIN(domainId)%linkid,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_linkid)\n         call write_chanel_int(RT_DOMAIN(domainId)%ORDER,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_order)\n         call write_chanel_real(RT_DOMAIN(domainId)%ZELEV,rt_domain(domainId)%map_l2g,gSize,rt_domain(domainId)%nlinks,g_zelev)\n      else\n         call ReachLS_write_io(frxstPtsLocal,g_STRMFRXSTPTS)\n         call ReachLS_write_io(strFlowLocal,g_qlink(:,1))\n         call ReachLS_write_io(RT_DOMAIN(domainId)%QLINK(:,2),g_qlink(:,2))\n         call ReachLS_write_io(RT_DOMAIN(domainId)%ORDER,g_order)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%linkid,g_linkid)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%CHLAT,g_chlat)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%CHLON,g_chlon)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%ZELEV,g_zelev)\n         call ReachLS_write_io(RT_DOMAIN(domainId)%HLINK,g_hlink)\n      endif\n\n      deallocate(strFlowLocal)\n      deallocate(frxstPtsLocal)\n\n   else\n      ! Running sequentially on a single processor.\n      gSize = rt_domain(domainId)%nlinks\n      allocate(g_STRMFRXSTPTS(gSize))\n      allocate(g_outInd(gSize))\n      allocate(g_chlon(gSize))\n      allocate(g_chlat(gSize))\n      allocate(g_hlink(gSize))\n      allocate(g_qlink(gSize,2))\n      allocate(g_linkid(gSize))\n      allocate(g_order(gSize))\n      allocate(g_zelev(gSize))\n\n      ! Initialize the index array to 0\n      g_outInd = 0\n\n      g_STRMFRXSTPTS = rt_domain(domainId)%STRMFRXSTPTS\n      g_chlon = RT_DOMAIN(domainId)%CHLON\n      g_chlat = RT_DOMAIN(domainId)%CHLAT\n      g_hlink = RT_DOMAIN(domainId)%HLINK\n      g_qlink = RT_DOMAIN(domainId)%QLINK\n      g_linkid = RT_DOMAIN(domainId)%linkid\n      g_order = RT_DOMAIN(domainId)%ORDER\n      g_zelev = RT_DOMAIN(domainId)%ZELEV\n   endif\n\n   if(myId .eq. 0) then\n      ! Set index values to 1 where we have forecast points.\n      if(nlst(domainId)%channel_option .eq. 3) then\n         where(g_STRMFRXSTPTS .ne. -9999) g_outInd = 1\n      endif\n\n      if(nlst(domainId)%channel_option .ne. 3) then\n         ! Check to see if we have any gages that need to be added for\n         ! reach-based routing.\n         call checkRouteGages(diagFlag,gSize,g_outInd)\n      endif\n\n      ! Filter out any missing values that may have filtered through to this\n      ! point.\n      where(g_qlink(:,1) .le. -9999) g_outInd = 0\n\n      ! Allocate output arrays based on size of number of forecast points.\n      numPtsOut = sum(g_outInd)\n\n      if(numPtsOut .eq. 0) then\n         ! Write warning message to user showing there are NO forecast points to\n         ! write. Simply return to the main calling function.\n         call postDiagMsg(diagFlag,'WARNING: No forecast or gage points found for CHANOBS. No file will be created.')\n         return\n      endif\n\n      ! Allocate output arrays based on number of output forecast points.\n      allocate(g_STRMFRXSTPTSOut(numPtsOut))\n      allocate(g_chlonOut(numPtsOut))\n      allocate(g_chlatOut(numPtsOut))\n      allocate(g_hlinkOut(numPtsOut))\n      allocate(g_qlinkOut(numPtsOut,2))\n      allocate(g_linkidOut(numPtsOut))\n      allocate(g_orderOut(numPtsOut))\n      allocate(g_zelevOut(numPtsOut))\n\n      ! Subset global arrays for forecast points.\n      g_STRMFRXSTPTSOut = pack(g_STRMFRXSTPTS,g_outInd == 1)\n      g_chlonOut = pack(g_chlon,g_outInd == 1)\n      g_chlatOut = pack(g_chlat,g_outInd == 1)\n      g_hlinkOut = pack(g_hlink,g_outInd == 1)\n      g_qlinkOut(:,1) = pack(g_qlink(:,1),g_outInd == 1)\n      g_qlinkOut(:,2) = pack(g_qlink(:,2),g_outInd == 1)\n      g_linkidOut = pack(g_linkid,g_outInd == 1)\n      g_orderOut = pack(g_order,g_outInd == 1)\n      g_zelevOut = pack(g_zelev,g_outInd == 1)\n\n      allocate(varOutReal(fileMeta%numVars,numPtsOut))\n      allocate(varOutInt(numPtsOut))\n\n      varOutReal(1,:) = g_qlinkOut(:,1)\n\n      ! Mask out missing values\n      where ( varOutReal == fileMeta%modelNdv ) varOutReal = -9999.0\n\n      ! call the GetModelConfigType function\n      modelConfigType = GetModelConfigType(nlst(1)%io_config_outputs)\n\n      ! Create NetCDF for output?\n\n      inquire(file=trim(output_flnm), exist=single_output_file_exists)\n      if ((.not. single_output_file) .or. (.not. single_output_file_exists)) then\n         iret = nf90_create(trim(output_flnm), cmode=nf90_netcdf4, ncid=ftn)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create CHANOBS NetCDF file.')\n\n      ! Write global attributes.\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"TITLE\",trim(fileMeta%title))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create TITLE attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"compiler_version\",compiler_version())\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create compiler_version attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"featureType\",trim(fileMeta%fType))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create featureType attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"proj4\",trim(fileMeta%proj4))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create proj4 attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_initialization_time\",trim(fileMeta%initTime))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create model init attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"station_dimension\",trim(fileMeta%stDim))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create st. dimension attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_valid_time\",trim(fileMeta%validTime))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create model valid attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_total_valid_times\",fileMeta%totalValidTime)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create model total valid times attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"stream_order_output\",fileMeta%stOrder)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create order attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"cdm_datatype\",trim(fileMeta%cdm))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create CDM attribute')\n         !iret = nf90_put_att(ftn,NF90_GLOBAL,\"esri_pe_string\",trim(fileMeta%esri))\n         !call nwmCheck(diagFlag,iret,'ERROR: Unable to create ESRI attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"Conventions\",trim(fileMeta%conventions))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create conventions attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"code_version\",trim(get_code_version()))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create code_version attribute')\n#ifdef NWM_META\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"NWM_version_number\",trim(get_nwm_version()))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create NWM_version_number attribute')\n#endif\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_type\",trim(fileMeta%modelOutputType))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_output_type attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_configuration\",modelConfigType)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_configuration attribute')\n\n         ! Create global attributes specific to running output through the\n         ! channel-only configuration of the model.\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"dev_OVRTSWCRT\",nlst(domainId)%OVRTSWCRT)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev_OVRTSWCRT attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"dev_NOAH_TIMESTEP\",int(nlst(domainId)%dt))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev_NOAH_TIMESTEP attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"dev_channel_only\",nlst(domainId)%channel_only)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev_channel_only attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,\"dev_channelBucket_only\",nlst(domainId)%channelBucket_only)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev_channelBucket_only attribute')\n         iret = nf90_put_att(ftn,NF90_GLOBAL,'dev','dev_ prefix indicates development/internal meta data')\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create dev attribute')\n\n         ! Create dimensions\n         iret = nf90_def_dim(ftn,\"feature_id\",numPtsOut,dimId(1))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create feature_id dimension')\n         iret = nf90_def_dim(ftn,\"time\",NF90_UNLIMITED,dimId(2))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create time dimension')\n         iret = nf90_def_dim(ftn,\"reference_time\",1,dimId(3))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time dimension')\n\n         ! Create and populate reference_time and time variables.\n         iret = nf90_def_var(ftn,\"time\",nf90_int,dimId(2),timeId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create time variable')\n         iret = nf90_put_att(ftn,timeId,'long_name',trim(fileMeta%timeLName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into time variable')\n         iret = nf90_put_att(ftn,timeId,'standard_name',trim(fileMeta%timeStName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into time variable')\n         iret = nf90_put_att(ftn,timeId,'units',trim(fileMeta%timeUnits))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into time variable')\n         if(.not. single_output_file) then\n            iret = nf90_put_att(ftn,timeId,'valid_min',fileMeta%timeValidMin)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_min attribute into time variable')\n            iret = nf90_put_att(ftn,timeId,'valid_max',fileMeta%timeValidMax)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_max attribute into time variable')\n         endif\n\n         iret = nf90_def_var(ftn,\"reference_time\",nf90_int,dimId(3),refTimeId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time variable')\n         iret = nf90_put_att(ftn,refTimeId,'long_name',trim(fileMeta%rTimeLName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into reference_time variable')\n         iret = nf90_put_att(ftn,refTimeId,'standard_name',trim(fileMeta%rTimeStName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into reference_time variable')\n         iret = nf90_put_att(ftn,refTimeId,'units',trim(fileMeta%rTimeUnits))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reference_time variable')\n\n         ! Create a crs variable.\n         ! NOTE - For now, we are hard-coding in for lat/lon points. However, this\n         ! may be more flexible in future iterations.\n         iret = nf90_def_var(ftn,'crs',nf90_char,varid=coordVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'transform_name','latitude longitude')\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place transform_name attribute into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'grid_mapping_name','latitude longitude')\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping_name attribute into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'esri_pe_string','GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",&\n              &SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",&\n              &0.0174532925199433]];-400 -400 1000000000;&\n              &-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision')\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place esri_pe_string into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'spatial_ref','GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",&\n              &SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",&\n              &0.0174532925199433]];-400 -400 1000000000;&\n              &-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision')\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place spatial_ref into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'long_name','CRS definition')\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'longitude_of_prime_meridian',0.0)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place longitude_of_prime_meridian into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'_CoordinateAxes','latitude longitude')\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place _CoordinateAxes into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'semi_major_axis',6378137.0)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place semi_major_axis into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'semi_minor_axis',6356752.31424518)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place semi_minor_axis into crs variable.')\n         iret = nf90_put_att(ftn,coordVarId,'inverse_flattening',298.257223563)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place inverse_flattening into crs variable.')\n\n         ! Create feature_id variable\n         iret = nf90_def_var(ftn,\"feature_id\",nf90_int64,dimId(1),featureVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create feature_id variable.')\n         ! Specify these attributes based on channel routing methods specified by\n         ! user.\n         if(nlst(domainId)%channel_option .eq. 3) then\n            iret = nf90_put_att(ftn,featureVarId,'long_name','User Specified Forecast Points')\n            call nwmCheck(diagFlag,iret,'ERROR: Uanble to place long_name attribute into feature_id variable')\n            iret = nf90_put_att(ftn,featureVarId,'comment','Forecast Points Specified in Fulldom file')\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place comment attribute into feature_id variable')\n         else\n            iret = nf90_put_att(ftn,featureVarId,'long_name',trim(fileMeta%featureIdLName))\n            call nwmCheck(diagFlag,iret,'ERROR: Uanble to place long_name attribute into feature_id variable')\n            iret = nf90_put_att(ftn,featureVarId,'comment',trim(fileMeta%featureIdComment))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place comment attribute into feature_id variable')\n         endif\n         iret = nf90_put_att(ftn,featureVarId,'cf_role',trim(fileMeta%cfRole))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place cf_role attribute into feature_id variable')\n\n         ! Create channel lat/lon variables\n         iret = nf90_def_var(ftn,\"latitude\",nf90_float,dimId(1),latVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create latitude variable.')\n         iret = nf90_put_att(ftn,latVarId,'long_name',trim(fileMeta%latLName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into latitude variable')\n         iret = nf90_put_att(ftn,latVarId,'standard_name',trim(fileMeta%latStName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into latitude variable')\n         iret = nf90_put_att(ftn,latVarId,'units',trim(fileMeta%latUnits))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into latitude variable')\n         iret = nf90_def_var(ftn,\"longitude\",nf90_float,dimId(1),lonVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create longitude variable.')\n         iret = nf90_put_att(ftn,lonVarId,'long_name',trim(fileMeta%lonLName))\n         call nwmCheck(diagFlag,iret,'ERROR: Uanble to place long_name attribute into longitude variable')\n         iret = nf90_put_att(ftn,lonVarId,'standard_name',trim(fileMeta%lonStName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into longitude variable')\n         iret = nf90_put_att(ftn,lonVarId,'units',trim(fileMeta%lonUnits))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into longitude variable')\n\n         ! Create channel order variable\n         iret = nf90_def_var(ftn,\"order\",nf90_int,dimId(1),orderVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create order variable.')\n         iret = nf90_put_att(ftn,orderVarId,'long_name',trim(fileMeta%orderLName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into order variable')\n         iret = nf90_put_att(ftn,orderVarId,'standard_name',trim(fileMeta%orderStName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into order variable')\n\n         ! Create channel elevation variable\n         iret = nf90_def_var(ftn,\"elevation\",nf90_float,dimId(1),elevVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to create elevation variable.')\n         iret = nf90_put_att(ftn,elevVarId,'long_name',trim(fileMeta%elevLName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into elevation variable')\n         iret = nf90_put_att(ftn,elevVarId,'standard_name',trim(fileMeta%elevStName))\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place stndard_name attribute into elevation variable')\n\n         ! Define deflation levels for these meta-variables. For now, we are going\n         ! to default to a compression level of 2. Only compress if io_form_outputs is set to 1.\n         if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n            iret = nf90_def_var_deflate(ftn,timeId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for time.')\n            iret = nf90_def_var_deflate(ftn,featureVarId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for feature_id.')\n            iret = nf90_def_var_deflate(ftn,refTimeId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reference_time.')\n            iret = nf90_def_var_deflate(ftn,latVarId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for latitude.')\n            iret = nf90_def_var_deflate(ftn,lonVarId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for longitude.')\n            iret = nf90_def_var_deflate(ftn,orderVarId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for order.')\n            iret = nf90_def_var_deflate(ftn,elevVarId,0,1,2)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for elevation.')\n         endif\n\n         ! Allocate memory for the output variables, then place the real output\n         ! variables into a single array. This array will be accessed throughout\n         ! the output looping below for conversion to compressed integer values.\n         ! Loop through and create each output variable, create variable\n         ! attributes, and insert data.\n         do iTmp=1,fileMeta%numVars\n            if(fileMeta%outFlag(iTmp) .eq. 1) then\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n                  iret = nf90_def_var( &\n                       ftn, trim(fileMeta%varNames(iTmp)), nf90_int, &\n                       (/ dimId(1), dimId(2) /), varId)\n               else\n                  iret = nf90_def_var( &\n                       ftn, trim(fileMeta%varNames(iTmp)), nf90_float, &\n                       (/ dimId(1), dimId(2) /), varId)\n               endif\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to create variable:'//trim(fileMeta%varNames(iTmp)))\n\n               ! Extract valid range into a 1D array for placement.\n               varRange(1) = fileMeta%validMinComp(iTmp)\n               varRange(2) = fileMeta%validMaxComp(iTmp)\n               varRangeReal(1) = real(fileMeta%validMinDbl(iTmp))\n               varRangeReal(2) = real(fileMeta%validMaxDbl(iTmp))\n\n               ! Establish a compression level for the variables. For now we are\n               ! using a compression level of 2. In addition, we are choosing to turn the\n               ! shuffle filter off for now. Kelley Eicher did some testing with this and\n               ! determined that the benefit wasn't worth the extra time spent\n               ! writing output. Only compress if io_form_outputs is set to 1.\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n                  iret = nf90_def_var_deflate(ftn,varId,0,1,2)\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression for: '//trim(fileMeta%varNames(iTmp)))\n               endif\n\n               ! Create variable attributes\n               iret = nf90_put_att(ftn,varId,'long_name',trim(fileMeta%longName(iTmp)))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'units',trim(fileMeta%units(iTmp)))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'coordinates',trim(fileMeta%coordNames(iTmp)))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place coordinates attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'grid_mapping','crs')\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place grid_mapping attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n                  iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillComp(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingComp(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftn,varId,'scale_factor',fileMeta%scaleFactor(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place scale_factor attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftn,varId,'add_offset',fileMeta%addOffset(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place add_offset attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftn,varId,'valid_range',varRange)\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               else\n                  iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillReal(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingReal(iTmp))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n                  iret = nf90_put_att(ftn,varId,'valid_range',varRangeReal)\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               endif\n            endif\n         end do\n\n         ! Remove NetCDF file from definition mode.\n         iret = nf90_enddef(ftn)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to take CHANOBS file out of definition mode')\n\n      else\n\n         iret = nf90_open(trim(output_flnm), nf90_write, ftn)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to open CHANOBS_DOMAIN.nc file.')\n\n      endif ! if((.not. single_output_file) .or. (.not. single_output_file_exists)) then\n\n      ! Time: length and write\n      iret =  nf90_inq_dimid(ftn, 'time', tmpDimId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time dimension.')\n      iret = nf90_inquire_dimension(ftn, tmpDimId, len=n_times)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to to get length of time dimension.')\n\n      iret = nf90_inq_varid(ftn, 'time', varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time variable')\n      iret = nf90_put_var(ftn, varId, minSinceEpochVect, start=(/n_times+1/), count = (/1/))\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into time variable')\n\n      ! Feature_id: just length\n      iret =  nf90_inq_dimid(ftn, 'feature_id', tmpDimId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time dimension.')\n      iret = nf90_inquire_dimension(ftn, tmpDimId, len=n_feature_ids)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to to get length of time dimension.')\n\n      ! Loop through all possible output variables, and convert floating points\n      ! to integers via prescribed scale_factor/add_offset, then write to the\n      ! NetCDF variable.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            ! We are outputing this variable.\n            ! Convert reals to integer. If this is time zero, check to see if we\n            ! need to convert all data to NDV\n            if(minSinceSim .eq. 0 .and. fileMeta%timeZeroFlag(iTmp) .eq. 0) then\n               varOutInt(:) = fileMeta%fillComp(iTmp)\n               varOutReal(iTmp,:) = fileMeta%fillReal(iTmp)\n            else\n               varOutInt(:) = NINT((varOutReal(iTmp,:)-fileMeta%addOffset(iTmp))/fileMeta%scaleFactor(iTmp))\n            endif\n            ! Get NetCDF variable id.\n            iret = nf90_inq_varid(ftn,trim(fileMeta%varNames(iTmp)),varId)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find variable ID for var: '//trim(fileMeta%varNames(iTmp)))\n            ! Put data into NetCDF file\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_var(ftn, varId, &\n                    reshape(varOutInt, (/n_feature_ids, 1/)), &\n                    start=(/1, n_times+1/), count=(/n_feature_ids, 1/))\n            else\n               iret = nf90_put_var( &\n                    ftn, varId, &\n                    reshape(varOutReal(iTmp,:), (/n_feature_ids, 1/)), &\n                    start=(/1, n_times+1/), count=(/n_feature_ids, 1/))\n            endif\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into output variable: '//trim(fileMeta%varNames(iTmp)))\n         endif\n      end do\n\n      ! Place link ID values into the NetCDF file\n      iret = nf90_inq_varid(ftn,'feature_id',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate feature_id in NetCDF file.')\n      ! If we are running gridded routing, output the user-specified forecast\n      ! point numbers. Otherwise, output the reach ID values.\n      if(nlst(domainId)%channel_option .eq. 3) then\n         iret = nf90_put_var(ftn,varId,g_STRMFRXSTPTSOut)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into feature_id output variable.')\n      else\n         iret = nf90_put_var(ftn,varId,g_linkidOut)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into feature_id output variable.')\n      endif\n\n      iret = nf90_inq_varid(ftn,'latitude',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate latitude in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_chlatOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into latitude output variable.')\n\n      iret = nf90_inq_varid(ftn,'longitude',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate longitude in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_chlonOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into longitude output variable.')\n\n      iret = nf90_inq_varid(ftn,'order',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate order in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_orderOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into order output variable.')\n\n      iret = nf90_inq_varid(ftn,'elevation',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate elevation in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_zelevOut)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into elevation output variable.')\n\n      ! Place reference time value\n      iret = nf90_inq_varid(ftn,'reference_time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reference_time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch1)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into reference_time variable')\n\n      ! Close the output file\n      iret = nf90_close(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close CHANOBS file.')\n\n      deallocate(varOutReal)\n      deallocate(varOutInt)\n\n   else\n\n      allocate(g_STRMFRXSTPTSOut(1))\n      allocate(g_chlonOut(1))\n      allocate(g_chlatOut(1))\n      allocate(g_hlinkOut(1))\n      allocate(g_qlinkOut(1,2))\n      allocate(g_linkidOut(1))\n      allocate(g_zelevOut(1))\n      allocate(g_orderOut(1))\n\n   endif\n\n   ! Deallocate memory\n   deallocate(g_STRMFRXSTPTS)\n   deallocate(g_STRMFRXSTPTSOut)\n   deallocate(g_chlonOut)\n   deallocate(g_chlatOut)\n   deallocate(g_hlinkOut)\n   deallocate(g_qlinkOut)\n   deallocate(g_linkidOut)\n   deallocate(g_zelevOut)\n   deallocate(g_orderOut)\n   deallocate(g_chlat)\n   deallocate(g_chlon)\n   deallocate(g_hlink)\n   deallocate(g_qlink)\n   deallocate(g_outInd)\n   deallocate(g_linkid)\n   deallocate(g_zelev)\n   deallocate(g_order)\n\nend subroutine output_chanObs_NWM\n\n!==============================================================================\n! Program Name: output_gw_NWM\n! Author(s)/Contact(s): Logan R Karsten <karsten><ucar><edu>\n! Abstract: Output routine for groundwater buckets.\n! History Log:\n! 9/22/17 -Created, LRK.\n! Usage:\n! Parameters: None.\n! Input Files: None.\n! Output Files: None.\n! Condition codes: None.\n!\n! User controllable options: None.\nsubroutine output_gw_NWM(domainId,iGrid)\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst\n   use Module_Date_utilities_rt, only: geth_newdate, geth_idts\n   use module_NWM_io_dict\n   use netcdf\n#ifdef MPP_LAND\n   use MODULE_mpp_GWBUCKET, only: gw_write_io_real, gw_write_io_int\n   use module_mpp_land\n   use module_mpp_reachls,  only: ReachLS_write_io\n#endif\n   implicit none\n\n   integer, intent(in) :: domainId\n   integer, intent(in) :: iGrid\n\n   ! Derived types.\n   type(gwMeta) :: fileMeta\n\n   ! Local variables\n   integer :: mppFlag, diagFlag\n   integer :: minSinceSim ! Number of minutes since beginning of simulation.\n   integer :: minSinceEpoch1 ! Number of minutes from EPOCH to the beginning of the model simulation.\n   integer :: minSinceEpoch ! Number of minutes from EPOCH to the current model valid time.\n   character(len=16) :: epochDate ! EPOCH represented as a string.\n   character(len=16) :: startDate ! Start of model simulation, represented as a string.\n   character(len=256) :: output_flnm ! CHRTOUT_DOMAIN filename\n   integer :: iret ! NetCDF return statuses\n   integer :: ftn ! NetCDF file handle\n   character(len=256) :: validTime ! Global attribute time string\n   character(len=256) :: initTime ! Global attribute time string\n   integer :: dimId(3) ! Dimension ID values created during NetCDF created.\n   integer :: varId ! Variable ID value created as NetCDF variables are created and populated.\n   integer :: timeId ! Dimension ID for the time dimension.\n   integer :: refTimeId ! Dimension ID for the reference time dimension.\n   integer :: featureVarId ! feature_id NetCDF variable ID\n   integer :: varRange(2) ! Local storage of valid min/max values\n   real :: varRangeReal(2) ! Local storage of valid min/max values\n   integer :: gSize ! Global size of lake out arrays\n   integer :: iTmp\n   integer :: indVarId,indTmp ! For the feature_id sorting process.\n   integer :: ierr, myId ! MPI return status, process ID\n   integer :: gnbasns\n   ! Allocatable arrays to hold output variables.\n   real, allocatable, dimension(:) :: g_qin_gwsubbas,g_qout_gwsubbas,g_qloss_gwsubbas,g_z_gwsubbas\n   integer(kind=int64), allocatable, dimension(:) :: g_basnsInd\n   real, allocatable, dimension(:,:) :: varOutReal   ! Array holding output variables in real format\n   integer, allocatable, dimension(:) :: varOutInt ! Array holding output variables after\n                                                     ! scale_factor/add_offset\n                                                     ! have been applied.\n   character (len=64) :: modelConfigType ! This is character verion (long name) for the io_config_outputs\n\n   ! Establish macro variables to hlep guide this subroutine.\n#ifdef MPP_LAND\n   mppFlag = 1\n#else\n   mppFlag = 0\n#endif\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Some sanity checking here.\n   if(nlst(domainId)%output_gw .eq. 0) then\n      ! No output requested here. Return to the parent calling program.\n      return\n   endif\n\n   ! Initialize NWM dictionary derived type containing all the necessary metadat\n   ! for the output file.\n   call initGwDict(fileMeta)\n\n   if(nlst(1)%io_config_outputs .eq. 0) then\n      ! All\n      fileMeta%outFlag(:) = [1,1,0,1]\n   else if(nlst(1)%io_config_outputs .eq. 1) then\n      ! Analysis and Assimilation\n      fileMeta%outFlag(:) = [1,1,0,1]\n   else if(nlst(1)%io_config_outputs .eq. 2) then\n      ! Short Range\n      fileMeta%outFlag(:) = [1,1,0,1]\n   else if(nlst(1)%io_config_outputs .eq. 3) then\n      ! Medium Range\n      fileMeta%outFlag(:) = [1,1,0,1]\n   else if(nlst(1)%io_config_outputs .eq. 4) then\n      ! Long Range\n      fileMeta%outFlag(:) = [1,1,0,1]\n   else if(nlst(1)%io_config_outputs .eq. 5) then\n      ! Retrospective\n      fileMeta%outFlag(:) = [1,1,0,1]\n   else if(nlst(1)%io_config_outputs .eq. 6) then\n      ! Diagnostics\n      fileMeta%outFlag(:) = [1,1,0,1]\n   else\n      call nwmCheck(diagFlag,1,'ERROR: Invalid IOC flag provided by namelist file.')\n   endif\n\n   ! call the GetModelConfigType function\n   modelConfigType = GetModelConfigType(nlst(1)%io_config_outputs)\n\n   gnbasns = rt_domain(domainId)%gnumbasns\n   gSize = gnbasns\n\n   ! Collect and assemble local groundwater bucket arrays to a global array for\n   ! output.\n   if(mppFlag .eq. 1) then\n\n      if(myId .eq. 0) then\n         allocate(g_qin_gwsubbas(rt_domain(domainId)%gnumbasns))\n         allocate(g_qout_gwsubbas(rt_domain(domainId)%gnumbasns))\n         allocate(g_qloss_gwsubbas(rt_domain(domainId)%gnumbasns))\n         allocate(g_z_gwsubbas(rt_domain(domainId)%gnumbasns))\n         allocate(g_basnsInd(rt_domain(domainId)%gnumbasns))\n      else\n         allocate(g_qin_gwsubbas(1))\n         allocate(g_qout_gwsubbas(1))\n         allocate(g_qloss_gwsubbas(1))\n         allocate(g_z_gwsubbas(1))\n         allocate(g_basnsInd(1))\n      endif\n\n      if(nlst(domainId)%UDMP_OPT .eq. 1) then\n         ! This is ONLY for NWM configuration with NHD channel routing. NCAR\n         ! reach-based routing has the GW physics initialized the same as with\n         ! gridded routing.\n         !ADCHANGE: Note units conversion from m3 to m3/s for UPDMP=1 only\n         call ReachLS_write_io(rt_domain(domainId)%qin_gwsubbas/nlst(domainId)%DT,g_qin_gwsubbas)\n         call ReachLS_write_io(rt_domain(domainId)%qout_gwsubbas,g_qout_gwsubbas)\n         !ADCHANGE: Note units conversion from m to mm for UPDMP=1 only\n         call ReachLS_write_io(rt_domain(domainId)%z_gwsubbas*1000.,g_z_gwsubbas)\n         call ReachLS_write_io(rt_domain(domainId)%linkid,g_basnsInd)\n         if(nlst(domainId)%bucket_loss .eq. 1) then\n            fileMeta%outFlag(3) = 1\n            call ReachLS_write_io(rt_domain(domainId)%qloss_gwsubbas,g_qloss_gwsubbas)\n         endif\n      else\n         call gw_write_io_real(rt_domain(domainId)%numbasns,rt_domain(domainId)%qin_gwsubbas,  &\n                               rt_domain(domainId)%basnsInd,g_qin_gwsubbas)\n         call gw_write_io_real(rt_domain(domainId)%numbasns,rt_domain(domainId)%qout_gwsubbas,  &\n                               rt_domain(domainId)%basnsInd,g_qout_gwsubbas)\n         call gw_write_io_real(rt_domain(domainId)%numbasns,rt_domain(domainId)%z_gwsubbas,  &\n                               rt_domain(domainId)%basnsInd,g_z_gwsubbas)\n         call gw_write_io_int(rt_domain(domainId)%numbasns,rt_domain(domainId)%basnsInd, &\n                              rt_domain(domainId)%basnsInd,g_basnsInd)\n         if(nlst(domainId)%bucket_loss .eq. 1) then\n             fileMeta%outFlag(3) = 1\n             call gw_write_io_real(rt_domain(domainId)%numbasns,rt_domain(domainId)%qloss_gwsubbas, &\n                                   rt_domain(domainId)%basnsInd,g_qloss_gwsubbas)\n         endif\n      endif\n\n   else\n      allocate(g_qin_gwsubbas(rt_domain(domainId)%gnumbasns))\n      allocate(g_qout_gwsubbas(rt_domain(domainId)%gnumbasns))\n      allocate(g_qloss_gwsubbas(rt_domain(domainId)%gnumbasns))\n      allocate(g_z_gwsubbas(rt_domain(domainId)%gnumbasns))\n      allocate(g_basnsInd(rt_domain(domainId)%gnumbasns))\n\n      !ADCHANGE: Note units conversion from m3 to m3/s for UPDMP=1 only\n      g_qin_gwsubbas = rt_domain(domainId)%qin_gwsubbas/nlst(domainId)%DT\n      g_qout_gwsubbas = rt_domain(domainId)%qout_gwsubbas\n      g_z_gwsubbas = rt_domain(domainId)%z_gwsubbas\n      !ADCHANGE: Note units conversion from m to mm for UPDMP=1 only\n      if(nlst(domainId)%UDMP_OPT .eq. 1) g_z_gwsubbas = g_z_gwsubbas * 1000.\n      g_basnsInd = rt_domain(domainId)%linkid\n      if(nlst(domainId)%bucket_loss .eq. 1) then\n         fileMeta%outFlag(3) = 1\n         g_qloss_gwsubbas = rt_domain(domainId)%qloss_gwsubbas\n      endif\n   endif\n\n   ! Calculate datetime information.\n   ! First compose strings of EPOCH and simulation start date.\n   epochDate = trim(\"1970-01-01 00:00\")\n   startDate = trim(nlst(domainId)%startdate(1:4)//\"-\"//&\n                    nlst(domainId)%startdate(6:7)//&\n                    &\"-\"//nlst(domainId)%startdate(9:10)//\" \"//&\n                    nlst(domainId)%startdate(12:13)//\":\"//&\n                    nlst(domainId)%startdate(15:16))\n   ! Second, utilize NoahMP date utilities to calculate the number of minutes\n   ! from EPOCH to the beginning of the model simulation.\n   call geth_idts(startDate,epochDate,minSinceEpoch1)\n   ! Third, calculate the number of minutes since the beginning of the\n   ! simulation.\n   minSinceSim = int(nlst(1)%out_dt*(rt_domain(1)%out_counts-1))\n   ! Fourth, calculate the total number of minutes from EPOCH to the current\n   ! model time step.\n   minSinceEpoch = minSinceEpoch1 + minSinceSim\n   ! Fifth, compose global attribute time strings that will be used.\n   validTime = trim(nlst(domainId)%olddate(1:4)//'-'//&\n                    nlst(domainId)%olddate(6:7)//'-'//&\n                    nlst(domainId)%olddate(9:10)//'_'//&\n                    nlst(domainId)%olddate(12:13)//':'//&\n                    nlst(domainId)%olddate(15:16)//&\n                    &':00')\n   initTime = trim(nlst(domainId)%startdate(1:4)//'-'//&\n                  nlst(domainId)%startdate(6:7)//'-'//&\n                  nlst(domainId)%startdate(9:10)//'_'//&\n                  nlst(domainId)%startdate(12:13)//':'//&\n                  nlst(domainId)%startdate(15:16)//&\n                  &':00')\n   ! Replace default values in the dictionary.\n   fileMeta%initTime = trim(initTime)\n   fileMeta%validTime = trim(validTime)\n\n   ! calculate the minimum and maximum time\n   fileMeta%timeValidMin = minSinceEpoch1 + nlst(1)%out_dt\n   fileMeta%timeValidMax = minSinceEpoch1 + int(nlst(1)%khour * 60/nlst(1)%out_dt) * nlst(1)%out_dt\n\n   ! calculate total_valid_time\n   fileMeta%totalValidTime = int(nlst(1)%khour * 60 / nlst(1)%out_dt)  ! # number of valid time (#of output files)\n\n   ! Compose output file name.\n   write(output_flnm,'(A12,\".GWOUT_DOMAIN\",I1)')nlst(domainId)%olddate(1:4)//&\n         nlst(domainId)%olddate(6:7)//nlst(domainId)%olddate(9:10)//&\n         nlst(domainId)%olddate(12:13)//nlst(domainId)%olddate(15:16),nlst(domainId)%igrid\n\n   ! Only run NetCDF library calls to output data if we are on the master\n   ! processor.\n   if(myId .eq. 0) then\n      ! Place all output arrays into one real array that will be looped over\n      ! during conversion to compressed integer format.\n      allocate(varOutReal(fileMeta%numVars,gSize))\n      allocate(varOutInt(gSize))\n\n      varOutReal(1,:) = g_qin_gwsubbas\n      varOutReal(2,:) = g_qout_gwsubbas\n      varOutReal(3,:) = g_qloss_gwsubbas\n      varOutReal(4,:) = g_z_gwsubbas\n\n      ! Mask out missing values\n      where ( varOutReal == fileMeta%modelNdv ) varOutReal = -9999.0\n\n      iret = nf90_create(trim(output_flnm),cmode=NF90_NETCDF4,ncid = ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create GWOUT NetCDF file.')\n\n      ! Write global attributes.\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"TITLE\",trim(fileMeta%title))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create TITLE attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"compiler_version\",compiler_version())\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create compiler_version attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"featureType\",trim(fileMeta%fType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create featureType attribute')\n      !iret = nf90_put_att(ftn,NF90_GLOBAL,\"proj4\",trim(fileMeta%proj4))\n      !call nwmCheck(diagFlag,iret,'ERROR: Unable to create proj4 attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_initialization_time\",trim(fileMeta%initTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model init attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"station_dimension\",trim(fileMeta%gwDim))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create st. dimension attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_valid_time\",trim(fileMeta%validTime))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model valid attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_total_valid_times\",fileMeta%totalValidTime)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model total valid times attribute')\n      !iret = nf90_put_att(ftn,NF90_GLOBAL,\"esri_pe_string\",trim(fileMeta%esri))\n      !call nwmCheck(diagFlag,iret,'ERROR: Unable to create ESRI attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"Conventions\",trim(fileMeta%conventions))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create conventions attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"code_version\",trim(get_code_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create code_version attribute')\n#ifdef NWM_META\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"NWM_version_number\",trim(get_nwm_version()))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create NWM_version_number attribute')\n#endif\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_output_type\",trim(fileMeta%modelOutputType))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_output_type attribute')\n      iret = nf90_put_att(ftn,NF90_GLOBAL,\"model_configuration\",modelConfigType)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create model_configuration attribute')\n\n      ! Create dimensions\n      iret = nf90_def_dim(ftn,\"feature_id\",gSize,dimId(1))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create feature_id dimension')\n      iret = nf90_def_dim(ftn,\"time\",NF90_UNLIMITED,dimId(2))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time dimension')\n      iret = nf90_def_dim(ftn,\"reference_time\",1,dimId(3))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time dimension')\n\n      ! Create and populate reference_time and time variables.\n      iret = nf90_def_var(ftn,\"time\",nf90_int,dimId(2),timeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create time variable')\n      iret = nf90_put_att(ftn,timeId,'long_name',trim(fileMeta%timeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'standard_name',trim(fileMeta%timeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'units',trim(fileMeta%timeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_min',fileMeta%timeValidMin)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_min attribute into time variable')\n      iret = nf90_put_att(ftn,timeId,'valid_max',fileMeta%timeValidMax)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_max attribute into time variable')\n      iret = nf90_def_var(ftn,\"reference_time\",nf90_int,dimId(3),refTimeId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'long_name',trim(fileMeta%rTimeLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'standard_name',trim(fileMeta%rTimeStName))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place standard_name attribute into reference_time variable')\n      iret = nf90_put_att(ftn,refTimeId,'units',trim(fileMeta%rTimeUnits))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into reference_time variable')\n\n      ! Create feature_id variable\n      iret = nf90_def_var(ftn,\"feature_id\",nf90_int64,dimId(1),featureVarId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to create feature_id variable.')\n      iret = nf90_put_att(ftn,featureVarId,'long_name',trim(fileMeta%featureIdLName))\n      call nwmCheck(diagFlag,iret,'ERROR: Uanble to place long_name attribute into feature_id variable')\n      iret = nf90_put_att(ftn,featureVarId,'comment',trim(fileMeta%featureIdComment))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place comment attribute into feature_id variable')\n      iret = nf90_put_att(ftn,featureVarId,'cf_role',trim(fileMeta%cfRole))\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place cf_role attribute into feature_id variable')\n\n      ! Define deflation levels for these meta-variables. For now, we are going\n      ! to\n      ! default to a compression level of 2. Only compress if io_form_outputs is set to 1.\n      if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n         iret = nf90_def_var_deflate(ftn,timeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for time.')\n         iret = nf90_def_var_deflate(ftn,featureVarId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for feature_id.')\n         iret = nf90_def_var_deflate(ftn,refTimeId,0,1,2)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression level for reference_time.')\n      endif\n\n      ! Allocate memory for the output variables, then place the real output\n      ! variables into a single array. This array will be accessed throughout\n      ! the\n      ! output looping below for conversion to compressed integer values.\n      ! Loop through and create each output variable, create variable\n      ! attributes,\n      ! and insert data.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            ! First create variable\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_int,dimId(1),varId)\n            else\n               iret = nf90_def_var(ftn,trim(fileMeta%varNames(iTmp)),nf90_float,dimId(1),varId)\n            endif\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to create variable:'//trim(fileMeta%varNames(iTmp)))\n\n            ! Extract valid range into a 1D array for placement.\n            varRange(1) = fileMeta%validMinComp(iTmp)\n            varRange(2) = fileMeta%validMaxComp(iTmp)\n            varRangeReal(1) = real(fileMeta%validMinDbl(iTmp))\n            varRangeReal(2) = real(fileMeta%validMaxDbl(iTmp))\n\n            ! Establish a compression level for the variables. For now we are using a\n            ! compression level of 2. In addition, we are choosing to turn the shuffle\n            ! filter off for now. Kelley Eicher did some testing with this and\n            ! determined that the benefit wasn't worth the extra time spent writing output.\n            ! Only compress if io_form_outputs is set to 1.\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 3)) then\n               iret = nf90_def_var_deflate(ftn,varId,0,1,2)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to define compression for: '//trim(fileMeta%varNames(iTmp)))\n            endif\n\n            ! Create variable attributes\n            iret = nf90_put_att(ftn,varId,'long_name',trim(fileMeta%longName(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place long_name attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            iret = nf90_put_att(ftn,varId,'units',trim(fileMeta%units(iTmp)))\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place units attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingComp(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'scale_factor',fileMeta%scaleFactor(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place scale_factor attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'add_offset',fileMeta%addOffset(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place add_offset attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRange)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            else\n               iret = nf90_put_att(ftn,varId,'_FillValue',fileMeta%fillReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place Fill value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'missing_value',fileMeta%missingReal(iTmp))\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place missing value attribute into variable '//trim(fileMeta%varNames(iTmp)))\n               iret = nf90_put_att(ftn,varId,'valid_range',varRangeReal)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to place valid_range attribute into variable '//trim(fileMeta%varNames(iTmp)))\n            endif\n         endif\n      end do\n\n      ! Remove NetCDF file from definition mode.\n      iret = nf90_enddef(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to take GWOUT file out of definition mode')\n\n      ! Place groundwater bucket ID, lat, and lon values into appropriate\n      ! variables.\n      do iTmp=1,fileMeta%numVars\n         if(fileMeta%outFlag(iTmp) .eq. 1) then\n            ! We are outputing this variable.\n            ! Convert reals to integer. If we are on time 0, make sure we don't\n            ! need to fill in with NDV values.\n            if(minSinceSim .eq. 0 .and. fileMeta%timeZeroFlag(iTmp) .eq. 0) then\n               varOutInt(:) = fileMeta%fillComp(iTmp)\n               varOutReal(iTmp,:) = fileMeta%fillReal(iTmp)\n            else\n               varOutInt(:) = NINT((varOutReal(iTmp,:)-fileMeta%addOffset(iTmp))/fileMeta%scaleFactor(iTmp))\n            endif\n            ! Get NetCDF variable id.\n            iret = nf90_inq_varid(ftn,trim(fileMeta%varNames(iTmp)),varId)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find variable ID for var: '//trim(fileMeta%varNames(iTmp)))\n            ! Put data into NetCDF file\n            if((nlst(1)%io_form_outputs .eq. 1) .or. (nlst(1)%io_form_outputs .eq. 2)) then\n               iret = nf90_put_var(ftn,varId,varOutInt)\n            else\n               iret = nf90_put_var(ftn,varId,varOutReal(iTmp,:))\n            endif\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into output variable: '//trim(fileMeta%varNames(iTmp)))\n         endif\n      end do\n\n      ! Place link ID values into the NetCDF file\n      iret = nf90_inq_varid(ftn,'feature_id',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate feature_id in NetCDF file.')\n      iret = nf90_put_var(ftn,varId,g_basnsInd)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to place data into feature_id output variable.')\n\n      ! Place time values into time variables.\n      iret = nf90_inq_varid(ftn,'time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into time variable')\n      iret = nf90_inq_varid(ftn,'reference_time',varId)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to locate reference_time variable')\n      iret = nf90_put_var(ftn,varId,minSinceEpoch1)\n      call nwmCheck(diagFlag,iret,'ERROR: Failure to place data into reference_time variable')\n\n      ! Close the output file\n      iret = nf90_close(ftn)\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close GWOUT file.')\n   endif\n\n   ! Deallocate all memory\n   if(myId .eq. 0) then\n      deallocate(varOutReal)\n      deallocate(varOutInt)\n   endif\n   deallocate(g_qin_gwsubbas)\n   deallocate(g_qout_gwsubbas)\n   deallocate(g_qloss_gwsubbas)\n   deallocate(g_z_gwsubbas)\n   deallocate(g_basnsInd)\nend subroutine output_gw_NWM\n\nsubroutine postDiagMsg(diagFlag,diagMsg)\n   implicit none\n\n   ! Subroutine arguments.\n   integer, intent(in) :: diagFlag\n   character(len=*), intent(in) :: diagMsg\n\n   ! Only write out message if the diagnostic WRF_HYDRO_D flag was\n   ! set to 1\n   if (diagFlag .eq. 1) then\n      print*, trim(diagMsg)\n   end if\nend subroutine postDiagMsg\n\nsubroutine nwmCheck(diagFlag,iret,msg)\n   implicit none\n\n   ! Subroutine arguments.\n   integer, intent(in) :: diagFlag,iret\n   character(len=*), intent(in) :: msg\n\n   ! Check status. If status of command is not 0, then post the error message\n   ! if WRF_HYDRO_D was set to be 1.\n   if (iret .ne. 0) then\n      call hydro_stop(trim(msg))\n   end if\n\nend subroutine nwmCheck\n\nsubroutine checkRouteGages(diagFlag,nElements,indexArray)\n  use config_base, only: nlst\n  use netcdf\n  use module_HYDRO_io, only : get_1d_netcdf_text\n  implicit none\n\n   ! Subroutine arguments.\n   integer, intent(in) :: diagFlag\n   integer, intent(in) :: nElements\n   integer, intent(inout), dimension(nElements) :: indexArray\n   character(len=15), dimension(nElements) :: gages\n\n   ! Local variables\n   integer :: iret, ftnRt, gageVarId\n\n   ! This subroutine will check for a Routelink file, then check for a \"gages\"\n   ! variable. If any gages are found, the indexArray is updated and passed back\n   ! to the calling subroutine.\n   iret = nf90_open(trim(nlst(1)%route_link_f),NF90_NOWRITE,ncid=ftnRt)\n   if(iret .ne. 0) then\n      call postDiagMsg(diagFlag,'WARNING: Did not find Routelink file for gage location in output routines.')\n      ! No Routelink file found. Simply return to the parent calling subroutine.\n      return\n   endif\n\n   iret = nf90_inq_varid(ftnRt,'gages',gageVarId)\n   if(iret .ne. 0) then\n      call postDiagMsg(diagFlag,'WARNING: Did not find gages in Routelink for forecast points output.')\n      ! No gages variable found. Simply return to the parent calling routine.'\n      return\n   endif\n\n   call get_1d_netcdf_text(ftnRt, 'gages', gages,  'checkRouteGages',.true.)\n\n   ! Loop over gages. If a non-empty string is found, then change the indexArray\n   ! value for that element from 0 to 1.\n   where(gages .ne. '               ') indexArray = 1\n   where(gages .eq. '') indexArray = 0\n\n   iret = nf90_close(ftnRt)\n\n   if(iret .ne. 0) then\n      call nwmCheck(diagFlag,iret,'ERROR: Unable to close Routelink file for gages extraction.')\n   endif\n\nend subroutine checkRouteGages\n\nend module module_NWM_io\n"
  },
  {
    "path": "src/Routing/module_NWM_io_dict.F90",
    "content": "! Module for handling all associated scale_factor, add_offset, and\n! attributes for individual files across various possible\n! National Water Model output files. In the future, this will move to a\n! table that the user will be able to switch on/off variables for\n! outputting. For now, attributes, etc will be stored here.\n\n! Logan Karsten\n! National Center for Atmospheric Research\n! Research Applications Laboratory\n! karsten at ucar dot edu\n\nmodule module_NWM_io_dict\n\n  use module_version, only: get_model_version\n  use config_base, only: nlst\n  use module_hydro_stop, only: HYDRO_stop\n\nimplicit none\n\n! Declare parameter values for module.\ninteger, parameter :: numChVars = 11\ninteger, parameter :: numLdasVars = 116\n! Note: if more ldas variables are added the logic will need to be changed in\n!       module_NWM_io.F:output_NoahMP_NWM for when to close the restart file\ninteger, parameter :: numLdasVars_crocus_off = 98\n\ninteger, parameter :: numRtDomainVars = 5\ninteger, parameter :: numLakeVars = 2\ninteger, parameter :: numChGrdVars = 1\ninteger, parameter :: numLsmVars = 14\ninteger, parameter :: numChObsVars = 1\ninteger, parameter :: numGwVars = 4\ninteger :: i\n!integer :: nsoil = nlst_rt(1)%nsoil\ninteger :: nsoil\n\n! Declare public types that will hold metadata\npublic :: chrtMeta ! Public CHRTOUT metadata for NWM output.\npublic :: ldasMeta ! Public LDASOUT metadata for NWM output.\npublic :: rtDomainMeta ! Public RT_DOMAIN metadata for NWM output.\npublic :: lakeMeta ! Public lake metadata for NWM output\npublic :: chrtGrdMeta ! Public CHRTOUT_GRID metadata for NWM output.\npublic :: lsmMeta ! Public metadata for LSMOUT output.\npublic :: chObsMeta ! Public CHANOBS metadata for NWM output.\npublic :: gwMeta ! Public groundwater metadata.\n\nreal*8 :: one_dbl = 1.0d0\n\n! Establish types for each output type\ntype chrtMeta\n   ! Variable names\n   character (len=64), dimension(numChVars) :: varNames\n   integer :: numVars = numChVars\n   character (len=512) :: modelOutputType = \"channel_rt\"\n   character (len=64) :: modelConfigType\n   ! Output variable attributes\n   real, dimension(numChVars) :: scaleFactor ! scale_factor values used for each\n                                                  ! variable to converte from real to\n                                                  ! integer.\n   real, dimension(numChVars)             :: addOffset   ! add_offset values for each variable.\n   character (len=64), dimension(numChVars) :: longName  ! Long names for each variable.\n   character (len=64), dimension(numChVars) :: units ! Units for each variable.\n   character (len=64), dimension(numChVars) :: coordNames ! Coordinate names for each variable.\n   integer(kind=4), dimension(numChVars) :: validMinComp ! Valid min (after conversion to integer)\n   integer(kind=4), dimension(numChVars) :: validMaxComp ! Valid max (after conversion to integer)\n   real*8, dimension(numChVars) :: validMinDbl ! Valid minimum (before conversion to integer)\n   real*8, dimension(numChVars) :: validMaxDbl ! Valid maximum (before converstion to integer)\n   integer(kind=4), dimension(numChVars) :: missingComp ! Missing value attribute (after conversion to integer)\n   real, dimension(numChVars) :: missingReal ! Missing value attribute (before conversion to integer)\n   real, dimension(numChVars) :: fillReal ! Fill value (before conversion to integer)\n   integer(kind=4), dimension(numChVars) :: fillComp ! Fill value (after conversion to integer)\n   integer, dimension(numChVars) :: outFlag ! 0/1 flag to turn outputting off/on\n   integer, dimension(numChVars) :: timeZeroFlag ! 0/1 flag to either set variable to all NDV values or output\n                                                 ! the actual data. This was done because time 0\n                                                 ! output does not all contain valid data.\n   real :: modelNdv ! NDV value represented within the model code\n   ! Time variable attribues\n   character (len=64) :: timeLName ! long_name - usually valid output time\n   character (len=64) :: timeUnits ! Usually seconds since 1/1/1970\n   character (len=64) :: timeStName ! standard_name - usually time\n   integer :: timeValidMin ! the minimum time each configuration can have, time of the first output file\n   integer :: timeValidMax ! the maximum time each configuration can have, time of the last output file\n   ! Reference time attributes\n   character (len=64) :: rTimeLName ! long_name - usually model initialization time\n   character (len=64) :: rTimeStName ! standard_name - usually forecast_reference_time\n   character (len=64) :: rTimeUnits ! Usually seconds since 1/1/1970\n   ! feature_id attributes\n   character (len=256) :: featureIdLName ! long_name - usually Reach ID\n   character (len=256) :: featureIdComment ! Comment attribute\n   character (len=64) :: cfRole ! cf_role attribute\n   ! latitude variable attributes\n   character (len=64) :: latLName ! long_name\n   character (len=64) :: latUnits ! units\n   character (len=64) :: latStName ! Standard Name\n   ! longitude variable attributes\n   character (len=64) :: lonLName ! long_name\n   character (len=64) :: lonUnits ! units\n   character (len=64) :: lonStName ! Standard Name\n   ! Elevation variable attributes\n   character (len=64) :: elevLName ! long_name\n   character (len=64) :: elevUnits ! units\n   character (len=64) :: elevStName ! Standard Name\n\n   ! Order variable attributes\n   character (len=64) :: orderLName ! long_name\n   character (len=64) :: orderStName ! Standard Name\n   ! Global attributes\n   character (len=128) :: title ! file title\n   character (len=128) :: fType ! featureType attribute\n   character (len=128) :: proj4 ! proj4 attribute\n   character (len=128) :: initTime ! model_initialization_time attribute\n   character (len=128) :: validTime ! model_output_valid_time attribute\n   character (len=128) :: stDim ! station_dimension attribute\n   integer :: stOrder ! stream_order_output attribute\n   character (len=128) :: cdm ! cdm_datatype attribute\n   character (len=1024) :: esri ! esri_pe_string attribute\n   character (len=128) :: conventions ! Conventions string\n   integer             :: totalValidTime ! # number of valid time (#of output files)\n\n\nend type chrtMeta\n\ntype ldasMeta\n   ! Variable names\n   character (len=64), dimension(numLdasVars) :: varNames\n   integer :: numVars = numLdasVars\n   integer :: numSnowLayers = 3\n   integer :: numSoilLayers                       ! Fill from Namelist\n   integer :: act_lev\n   integer :: numSpectrumBands = 2\n   character (len=512) :: modelOutputType = \"land\"\n   character (len=64) :: modelConfigType\n\n   ! Output variable attributes\n   real, dimension(numLdasVars) :: scaleFactor ! scale_factor values used for each\n                                                  ! variable to converte from\n                                                  ! real to\n                                                  ! integer\n   real, dimension(numLdasVars)             :: addOffset   ! add_offset values for each variable.\n   character (len=128), dimension(numLdasVars) :: longName  ! Long names for each variable.\n   character (len=64), dimension(numLdasVars) :: units ! Units for each variable.\n   integer, dimension(numLdasVars) :: numLev ! Number of levels for each variable.\n   integer(kind=4), dimension(numLdasVars) :: validMinComp ! Valid min (after conversion to integer)\n   integer(kind=4), dimension(numLdasVars) :: validMaxComp ! Valid max (after conversion to integer)\n   real*8, dimension(numLdasVars) :: validMinDbl ! Valid minimum (before conversion to integer)\n   real*8, dimension(numLdasVars) :: validMaxDbl ! Valid maximum (before converstion to integer)\n   integer(kind=4), dimension(numLdasVars) :: missingComp ! Missing value attribute (after conversion to integer)\n   real, dimension(numLdasVars) :: missingReal ! Missing value attribute (before conversion to integer)\n   real, dimension(numLdasVars) :: fillReal ! Fill value (before conversion to integer)\n   integer(kind=4), dimension(numLdasVars) :: fillComp ! Fill value (after conversion to integer)\n   integer, dimension(numLdasVars) :: outFlag ! 0/1 flag to turn outputting off/on\n   integer, dimension(numLdasVars) :: timeZeroFlag ! 0/1 flag to either set variable to all NDV values or output\n                                                   ! the actual data. This was done because time 0\n                                                   ! output does not all contain valid data.\n   real :: modelNdv ! NDV value represented within the model code\n   real :: modelNdv2 ! Alternative NDV value in NoahMP\n   real :: modelNdv3 ! Alternative NDV value in NoahMP\n   integer :: modelNdvInt ! NDV value represented in model as integer\n   ! Time variable attribues\n   character (len=64) :: timeLName ! long_name - usually valid output time\n   character (len=64) :: timeUnits ! Usually seconds since 1/1/1970\n   character (len=64) :: timeStName ! standard_name - usually time\n   integer :: timeValidMin ! the minimum time each configuration can have, time of the first output file\n   integer :: timeValidMax ! the maximum time each configuration can have, time of the last output file\n\n   ! Reference time attributes\n   character (len=64) :: rTimeLName ! long_name - usually model initialization time\n   character (len=64) :: rTimeStName ! standard_name - usually forecast_reference_time\n   character (len=64) :: rTimeUnits ! Usually seconds since 1/1/1970\n   ! Establish a proj4 string\n   character (len=1024) :: proj4\n   ! Establish crs-related variables.\n   character(len=1024), dimension(20) :: crsCharAttNames,crsFloatAttNames\n   character(len=1024), dimension(20) :: crsCharAttVals\n   real, dimension(20,20) :: crsRealAttVals\n   integer, dimension(20) :: crsRealAttLen\n   integer :: nCrsRealAtts, nCrsCharAtts\n   ! Establish x/y related variables.\n   character(len=1024), dimension(20) :: xCharAttNames,xFloatAttNames\n   character(len=1024), dimension(20) :: xCharAttVals\n   real, dimension(20,20) :: xRealAttVals\n   integer, dimension(20) :: xRealAttLen\n   integer :: nxRealAtts, nxCharAtts\n   character(len=1024), dimension(20) :: yCharAttNames,yFloatAttNames\n   character(len=1024), dimension(20) :: yCharAttVals\n   real, dimension(20,20) :: yRealAttVals\n   integer, dimension(20) :: yRealAttLen\n   integer :: nyRealAtts, nyCharAtts\n\n   ! Global attributes\n   character (len=128) :: title ! file title\n   character (len=128) :: initTime ! model_initialization_time attribute\n   character (len=128) :: validTime ! model_output_valid_time attribute\n   character (len=128) :: conventions ! Conventions string\n   integer             :: totalValidTime ! # number of valid time (#of output files)\n\nend type ldasMeta\n\ntype rtDomainMeta\n   ! Variable names\n   character (len=64), dimension(numRtDomainVars) :: varNames\n   integer :: numVars = numRtDomainVars\n   integer :: numSoilLayers                       ! Fill from Namelist\n   character (len=512) :: modelOutputType = \"terrain_rt\"\n   character (len=64) :: modelConfigType\n\n   ! Output variable attributes\n   real, dimension(numRtDomainVars) :: scaleFactor ! scale_factor values used for each\n                                                  ! variable to converte from\n                                                  ! real to\n                                                  ! integer.\n   real, dimension(numRtDomainVars)             :: addOffset   ! add_offset values for each variable.\n   character (len=64), dimension(numRtDomainVars) :: longName  ! Long names for each variable.\n   character (len=64), dimension(numRtDomainVars) :: units ! Units for each variable.\n   character (len=64), dimension(numRtDomainVars) :: coordNames ! Coordinate names for each variable.\n   integer(kind=4), dimension(numRtDomainVars) :: validMinComp ! Valid min (after conversion to integer)\n   integer(kind=4), dimension(numRtDomainVars) :: validMaxComp ! Valid max (after conversion to integer)\n   real*8, dimension(numRtDomainVars) :: validMinDbl ! Valid minimum (before conversion to integer)\n   real*8, dimension(numRtDomainVars) :: validMaxDbl ! Valid maximum (before converstion to integer)\n   integer(kind=4), dimension(numRtDomainVars) :: missingComp ! Missing value attribute (after conversion to integer)\n   real, dimension(numRtDomainVars) :: missingReal ! Missing value attribute (before conversion to integer)\n   real, dimension(numRtDomainVars) :: fillReal ! Fill value (before conversion to integer)\n   integer(kind=4), dimension(numRtDomainVars) :: fillComp ! Fill value (after conversion to integer)\n   integer, dimension(numRtDomainVars) :: outFlag ! 0/1 flag to turn outputting off/on\n   integer, dimension(numRtDomainVars) :: timeZeroFlag ! 0/1 flag to either set variable to all NDV values or output\n                                                       ! the actual data. This was done because time 0\n                                                       ! output does not all contain valid data.\n   real :: modelNdv ! NDV value represented within the model code\n   ! Time variable attribues\n   character (len=64) :: timeLName ! long_name - usually valid output time\n   character (len=64) :: timeUnits ! Usually seconds since 1/1/1970\n   character (len=64) :: timeStName ! standard_name - usually time\n   integer :: timeValidMin ! the minimum time each configuration can have, time of the first output file\n   integer :: timeValidMax ! the maximum time each configuration can have, time of the last output file\n   ! Reference time attributes\n   character (len=64) :: rTimeLName ! long_name - usually model initialization time\n   character (len=64) :: rTimeStName ! standard_name - usually forecast_reference_time\n   character (len=64) :: rTimeUnits ! Usually seconds since 1/1/1970\n   real :: yRes, xRes ! Resoltution in meters\n\n   ! Establish a proj4 string\n   character (len=1024) :: proj4\n   ! Establish crs-related variables.\n   character(len=1024), dimension(20) :: crsCharAttNames,crsFloatAttNames\n   character(len=1024), dimension(20) :: crsCharAttVals\n   real, dimension(20,20) :: crsRealAttVals\n   integer, dimension(20) :: crsRealAttLen\n   integer :: nCrsRealAtts, nCrsCharAtts\n   ! Establish x/y related variables.\n   character(len=1024), dimension(20) :: xCharAttNames,xFloatAttNames\n   character(len=1024), dimension(20) :: xCharAttVals\n   real, dimension(20,20) :: xRealAttVals\n   integer, dimension(20) :: xRealAttLen\n   integer :: nxRealAtts, nxCharAtts\n   character(len=1024), dimension(20) :: yCharAttNames,yFloatAttNames\n   character(len=1024), dimension(20) :: yCharAttVals\n   real, dimension(20,20) :: yRealAttVals\n   integer, dimension(20) :: yRealAttLen\n   integer :: nyRealAtts, nyCharAtts\n\n   ! Global attributes\n   integer :: decimation ! Decimation factor\n   character (len=128) :: title ! file title\n   character (len=128) :: initTime ! model_initialization_time attribute\n   character (len=128) :: validTime ! model_output_valid_time attribute\n   character (len=128) :: conventions ! Conventions string\n   integer             :: totalValidTime ! # number of valid time (#of output files)\n\nend type rtDomainMeta\n\ntype lakeMeta\n   ! Variable names\n   character (len=64), dimension(numLakeVars) :: varNames\n   integer :: numVars = numLakeVars\n   character (len=512) :: modelOutputType = \"reservoir\"\n   character (len=64) :: modelConfigType\n\n   ! Output variable attributes\n   real, dimension(numLakeVars) :: scaleFactor ! scale_factor values used for each\n                                               ! variable to converte from\n                                               ! real to\n                                               ! integer.\n   real, dimension(numLakeVars)             :: addOffset   ! add_offset values for each variable.\n   character (len=64), dimension(numLakeVars) :: longName  ! Long names for each variable.\n   character (len=64), dimension(numLakeVars) :: units ! Units for each variable.\n   character (len=64), dimension(numLakeVars) :: coordNames ! Coordinate names for each variable.\n   integer(kind=4), dimension(numLakeVars) :: validMinComp ! Valid min (after conversion to integer)\n   integer(kind=4), dimension(numLakeVars) :: validMaxComp ! Valid max (after conversion to integer)\n   real*8, dimension(numLakeVars) :: validMinDbl ! Valid minimum (before conversion to integer)\n   real*8, dimension(numLakeVars) :: validMaxDbl ! Valid maximum (before converstion to integer)\n   integer(kind=4), dimension(numLakeVars) :: missingComp ! Missing value attribute (after conversion to integer)\n   real, dimension(numLakeVars) :: missingReal ! Missing value attribute (before conversion to integer)\n   real, dimension(numLakeVars) :: fillReal ! Fill value (before conversion to integer)\n   integer(kind=4), dimension(numLakeVars) :: fillComp ! Fill value (after conversion to integer)\n   integer, dimension(numLakeVars) :: outFlag ! 0/1 flag to turn outputting off/on\n   integer, dimension(numLakeVars) :: timeZeroFlag ! 0/1 flag to either set variable to all NDV values or output\n                                                   ! the actual data. This was done because time 0\n                                                   ! output does not all contain valid data.\n   real :: modelNdv ! NDV value represented within the model code\n   ! Time variable attribues\n   character (len=64) :: timeLName ! long_name - usually valid output time\n   character (len=64) :: timeUnits ! Usually seconds since 1/1/1970\n   character (len=64) :: timeStName ! standard_name - usually time\n   integer :: timeValidMin ! the minimum time each configuration can have, time of the first output file\n   integer :: timeValidMax ! the maximum time each configuration can have, time of the last output file\n   ! Reference time attributes\n   character (len=64) :: rTimeLName ! long_name - usually model initialization time\n   character (len=64) :: rTimeStName ! standard_name - usually forecast_reference_time\n   character (len=64) :: rTimeUnits ! Usually seconds since 1/1/1970\n   ! lake_id attributes\n   character (len=64) :: lakeIdLName ! long_name - usually Lake COMMON ID\n   character (len=256) :: LakeIdComment ! Comment attribute\n   ! feature_id attributes\n   character (len=256) :: featureIdLName ! long_name - usually lake COMMON ID\n   character (len=256) :: featureIdComment ! Comment attribute\n   character (len=64) :: cfRole ! cf_role attribute\n   ! reservoir_type attributes\n   character (len=64) :: reservoirTypeLName ! long_name - usually \"reservoir_type\"\n   integer, dimension(4) :: reservoirTypeFlagValues ! valid flags attribute\n   character (len=64) :: reservoirTypeFlagMeanings ! flag meanings attribute\n   ! reservoir_assimilated_value attributes\n   character (len=64) :: reservoirAssimilatedValueLName ! long_name - usually \"reservoir_assimilated_value, m3 s-1\"\n   character (len=64) :: reservoirAssimilatedValueUnits ! units\n   ! reservoir_assimilated_source_file attributes\n   character (len=64) :: reservoirAssimilatedSourceFileLName ! long_name - usually \"reservoir_assimilated_source_file\"\n   ! latitude variable attributes\n   character (len=64) :: latLName ! long_name\n   character (len=64) :: latUnits ! units\n   character (len=64) :: latStName ! Standard Name\n   ! longitude variable attributes\n   character (len=64) :: lonLName ! long_name\n   character (len=64) :: lonUnits ! units\n   character (len=64) :: lonStName ! Standard Name\n   ! elevation variable attributes\n   character (len=64) :: elevLName ! long_name\n   character (len=64) :: elevUnits ! units\n   character (len=64) :: elevStName ! Standard Name\n   character (len=256) :: elevComment ! Comment\n   ! Global attributes\n   character (len=128) :: title ! file title\n   character (len=128) :: fType ! featureType attribute\n   character (len=128) :: proj4 ! proj4 attribute\n   character (len=128) :: initTime ! model_initialization_time attribute\n   character (len=128) :: validTime ! model_output_valid_time attribute\n   character (len=128) :: lakeDim ! lake_dimension attribute\n   character (len=128) :: cdm ! cdm_datatype attribute\n   character (len=1024) :: esri ! esri_pe_string attribute\n   character (len=128) :: conventions ! Conventions string\n   integer             :: totalValidTime ! # number of valid time (#of output files)\n\nend type lakeMeta\n\ntype chrtGrdMeta\n   ! Variable names\n   character (len=64), dimension(numChGrdVars) :: varNames\n   integer :: numVars = numChGrdVars\n   character (len=512) :: modelOutputType = \"channel_rt\"\n   character (len=64) :: modelConfigType\n\n   ! Output variable attributes\n   real, dimension(numChGrdVars) :: scaleFactor ! scale_factor values for each\n                                                ! variable to convert from\n                                                ! real to integer\n   real, dimension(numChGrdVars) :: addOffset ! add_offset values for each variable.\n   character (len=64), dimension(numChGrdVars) :: longName ! longname for each variable\n   character (len=64), dimension(numChGrdVars) :: units ! Units for each variable.\n   character (len=64), dimension(numChGrdVars) :: coordNames ! Coordinate names for each variable.\n   integer(kind=4), dimension(numChGrdVars) :: validMinComp ! Valid min (after conversion to integer)\n   integer(kind=4), dimension(numChGrdVars) :: validMaxComp ! Valid max (after conversion to integer)\n   real*8, dimension(numChGrdVars) :: validMinDbl ! Valid minimum (before conversion to integer)\n   real*8, dimension(numChGrdVars) :: validMaxDbl ! Valid maximum (before converstion to integer)\n   integer(kind=4), dimension(numChGrdVars) :: missingComp ! Missing value attribute (after conversion to integer)\n   real, dimension(numChGrdVars) :: missingReal ! Missing value attribute (before conversion to integer)\n   real, dimension(numChGrdVars) :: fillReal ! Fill value (before conversion to integer)\n   integer(kind=4), dimension(numChGrdVars) :: fillComp ! Fill value (after conversion to integer)\n   integer, dimension(numChGrdVars) :: outFlag ! 0/1 flag to turn outputting off/on\n   integer, dimension(numChGrdVars) :: timeZeroFlag ! 0/1 flag to either set variable to all NDV values or output\n                                                       ! the actual data. This\n                                                       ! was done because time 0\n                                                       ! output does not all\n                                                       ! contain valid data.\n   real :: modelNdv ! NDV value represented within the model code\n   ! Time variable attribues\n   character (len=64) :: timeLName ! long_name - usually valid output time\n   character (len=64) :: timeUnits ! Usually seconds since 1/1/1970\n   character (len=64) :: timeStName ! standard_name - usually time\n   integer :: timeValidMin ! the minimum time each configuration can have, time of the first output file\n   integer :: timeValidMax ! the maximum time each configuration can have, time of the last output file\n   ! Reference time attributes\n   character (len=64) :: rTimeLName ! long_name - usually model initialization time\n   character (len=64) :: rTimeStName ! standard_name - usually forecast_reference_time\n   character (len=64) :: rTimeUnits ! Usually seconds since 1/1/1970\n   real :: yRes, xRes ! Resoltution in meters\n\n   ! Establish a proj4 string\n   character (len=1024) :: proj4\n   ! Establish crs-related variables.\n   character(len=1024), dimension(20) :: crsCharAttNames,crsFloatAttNames\n   character(len=1024), dimension(20) :: crsCharAttVals\n   real, dimension(20,20) :: crsRealAttVals\n   integer, dimension(20) :: crsRealAttLen\n   integer :: nCrsRealAtts, nCrsCharAtts\n   ! Establish x/y related variables.\n   character(len=1024), dimension(20) :: xCharAttNames,xFloatAttNames\n   character(len=1024), dimension(20) :: xCharAttVals\n   real, dimension(20,20) :: xRealAttVals\n   integer, dimension(20) :: xRealAttLen\n   integer :: nxRealAtts, nxCharAtts\n   character(len=1024), dimension(20) :: yCharAttNames,yFloatAttNames\n   character(len=1024), dimension(20) :: yCharAttVals\n   real, dimension(20,20) :: yRealAttVals\n   integer, dimension(20) :: yRealAttLen\n   integer :: nyRealAtts, nyCharAtts\n\n   ! Global attributes\n   integer :: decimation ! Decimation factor\n   character (len=128) :: title ! file title\n   character (len=128) :: initTime ! model_initialization_time attribute\n   character (len=128) :: validTime ! model_output_valid_time attribute\n   character (len=128) :: conventions ! Conventions string\n   integer             :: totalValidTime ! # number of valid time (#of output files)\n\nend type chrtGrdMeta\n\ntype lsmMeta\n   ! Variable names\n   character (len=64), dimension(numLsmVars) :: varNames\n   integer :: numVars = numLsmVars\n   integer :: numSnowLayers = 3\n   integer :: numSoilLayers                       ! Fill from Namelist\n   integer :: act_lev\n   character (len=512) :: modelOutputType = \"land\"\n   character (len=64) :: modelConfigType\n\n   ! Output variable attributes\n   real, dimension(numLsmVars) :: scaleFactor ! scale_factor values used for each\n                                                  ! variable to converte from\n                                                  ! real to\n                                                  ! integer\n   real, dimension(numLsmVars)             :: addOffset   ! add_offset values for each variable.\n   character (len=64), dimension(numLsmVars) :: longName  ! Long names for each variable.\n   character (len=64), dimension(numLsmVars) :: units ! Units for each variable.\n   integer, dimension(numLsmVars) :: numLev ! Number of levels for each variable.\n   integer(kind=4), dimension(numLsmVars) :: validMinComp ! Valid min (after conversion to integer)\n   integer(kind=4), dimension(numLsmVars) :: validMaxComp ! Valid max (after conversion to integer)\n   real*8, dimension(numLsmVars) :: validMinDbl ! Valid minimum (before conversion to integer)\n   real*8, dimension(numLsmVars) :: validMaxDbl ! Valid maximum (before converstion to integer)\n   integer(kind=4), dimension(numLsmVars) :: missingComp ! Missing value attribute (after conversion to integer)\n   real, dimension(numLsmVars) :: missingReal ! Missing value attribute (before conversion to integer)\n   real, dimension(numLsmVars) :: fillReal ! Fill value (before conversion to integer)\n   integer(kind=4), dimension(numLsmVars) :: fillComp ! Fill value (after conversion to integer)\n   integer, dimension(numLsmVars) :: outFlag ! 0/1 flag to turn outputting off/on\n   integer, dimension(numLsmVars) :: timeZeroFlag ! 0/1 flag to either set variable to all NDV values or output\n                                                   ! the actual data. This was\n                                                   ! done because time 0\n                                                   ! output does not all contain\n                                                   ! valid data.\n   real :: modelNdv ! NDV value represented within the model code\n   integer :: modelNdvInt ! NDV value represented in model as integer\n   ! Time variable attribues\n   character (len=64) :: timeLName ! long_name - usually valid output time\n   character (len=64) :: timeUnits ! Usually seconds since 1/1/1970\n   character (len=64) :: timeStName ! standard_name - usually time\n   integer :: timeValidMin ! the minimum time each configuration can have, time of the first output file\n   integer :: timeValidMax ! the maximum time each configuration can have, time of the last output file\n   ! Reference time attributes\n   character (len=64) :: rTimeLName ! long_name - usually model initialization time\n   character (len=64) :: rTimeStName ! standard_name - usually forecast_reference_time\n   character (len=64) :: rTimeUnits ! Usually seconds since 1/1/1970\n\n   ! Establish a proj4 string\n   character (len=1024) :: proj4\n   ! Establish crs-related variables.\n   character(len=1024), dimension(20) :: crsCharAttNames,crsFloatAttNames\n   character(len=1024), dimension(20) :: crsCharAttVals\n   real, dimension(20,20) :: crsRealAttVals\n   integer, dimension(20) :: crsRealAttLen\n   integer :: nCrsRealAtts, nCrsCharAtts\n   ! Establish x/y related variables.\n   character(len=1024), dimension(20) :: xCharAttNames,xFloatAttNames\n   character(len=1024), dimension(20) :: xCharAttVals\n   real, dimension(20,20) :: xRealAttVals\n   integer, dimension(20) :: xRealAttLen\n   integer :: nxRealAtts, nxCharAtts\n   character(len=1024), dimension(20) :: yCharAttNames,yFloatAttNames\n   character(len=1024), dimension(20) :: yCharAttVals\n   real, dimension(20,20) :: yRealAttVals\n   integer, dimension(20) :: yRealAttLen\n   integer :: nyRealAtts, nyCharAtts\n\n   ! Global attributes\n   character (len=128) :: title ! file title\n   character (len=128) :: initTime ! model_initialization_time attribute\n   character (len=128) :: validTime ! model_output_valid_time attribute\n   character (len=128) :: conventions ! Conventions string\n   integer             :: totalValidTime ! # number of valid time (#of output files)\n\nend type lsmMeta\n\ntype chObsMeta\n   ! Variable names\n   character (len=64), dimension(numChObsVars) :: varNames\n   integer :: numVars = numChObsVars\n   character (len=512) :: modelOutputType = \"channel_rt\"\n   character (len=64) :: modelConfigType\n\n   ! Output variable attributes\n   real, dimension(numChObsVars) :: scaleFactor ! scale_factor values used for\n                                                 ! each variable to convert\n                                                 ! from real to integer\n   real, dimension(numChObsVars)             :: addOffset   ! add_offset values for each variable.\n   character (len=64), dimension(numChObsVars) :: longName  ! Long names for each variable.\n   character (len=64), dimension(numChObsVars) :: units ! Units for each variable.\n   character (len=64), dimension(numChObsVars) :: coordNames ! Coordinate names for each variable.\n   integer(kind=4), dimension(numChObsVars) :: validMinComp ! Valid min (after conversion to integer)\n   integer(kind=4), dimension(numChObsVars) :: validMaxComp ! Valid max (after conversion to integer)\n   real*8, dimension(numChObsVars) :: validMinDbl ! Valid minimum (before conversion to integer)\n   real*8, dimension(numChObsVars) :: validMaxDbl ! Valid maximum (before converstion to integer)\n   integer(kind=4), dimension(numChObsVars) :: missingComp ! Missing value attribute (after conversion to integer)\n   real, dimension(numChObsVars) :: missingReal ! Missing value attribute (before conversion to integer)\n   real, dimension(numChObsVars) :: fillReal ! Fill value (before conversion to integer)\n   integer(kind=4), dimension(numChObsVars) :: fillComp ! Fill value (after conversion to integer)\n   integer, dimension(numChObsVars) :: outFlag ! 0/1 flag to turn outputting off/on\n   integer, dimension(numChObsVars) :: timeZeroFlag ! 0/1 flag to either set variable to all NDV values or output\n                                                 ! the actual data. This was\n                                                 ! done because time 0\n                                                 ! output does not all contain valid data.\n   real :: modelNdv ! NDV value represented within the model code\n   ! Time variable attribues\n   character (len=64) :: timeLName ! long_name - usually valid output time\n   character (len=64) :: timeUnits ! Usually seconds since 1/1/1970\n   character (len=64) :: timeStName ! standard_name - usually time\n   integer :: timeValidMin ! the minimum time each configuration can have, time of the first output file\n   integer :: timeValidMax ! the maximum time each configuration can have, time of the last output file\n   ! Reference time attributes\n   character (len=64) :: rTimeLName ! long_name - usually model initialization time\n   character (len=64) :: rTimeStName ! standard_name - usually forecast_reference_time\n   character (len=64) :: rTimeUnits ! Usually seconds since 1/1/1970\n   ! feature_id attributes\n   character (len=256) :: featureIdLName ! long_name - usually Reach ID\n   character (len=256) :: featureIdComment ! Comment attribute\n   character (len=64) :: cfRole ! cf_role attribute\n   ! latitude variable attributes\n   character (len=64) :: latLName ! long_name\n   character (len=64) :: latUnits ! units\n   character (len=64) :: latStName ! Standard Name\n   ! longitude variable attributes\n   character (len=64) :: lonLName ! long_name\n   character (len=64) :: lonUnits ! units\n   character (len=64) :: lonStName ! Standard Name\n   ! Elevation variable attributes\n   character (len=64) :: elevLName ! long_name\n   character (len=64) :: elevUnits ! units\n   character (len=64) :: elevStName ! Standard Name\n   ! Order variable attributes\n   character (len=64) :: orderLName ! long_name\n   character (len=64) :: orderStName ! Standard Name\n   ! Global attributes\n   character (len=128) :: title ! file title\n   character (len=128) :: fType ! featureType attribute\n   character (len=128) :: proj4 ! proj4 attribute\n   character (len=128) :: initTime ! model_initialization_time attribute\n   character (len=128) :: validTime ! model_output_valid_time attribute\n   character (len=128) :: stDim ! station_dimension attribute\n   integer :: stOrder ! stream_order_output attribute\n   character (len=128) :: cdm ! cdm_datatype attribute\n   character (len=1024) :: esri ! esri_pe_string attribute\n   character (len=128) :: conventions ! Conventions string\n   integer             :: totalValidTime ! # number of valid time (#of output files)\n\nend type chObsMeta\n\ntype gwMeta\n   ! Variable names\n   character (len=64), dimension(numGwVars) :: varNames\n   integer :: numVars = numGwVars\n   character (len=512) :: modelOutputType = \"groundwater_rt\"\n   character (len=64) :: modelConfigType\n\n   ! Output variable attributes\n   real, dimension(numGwVars) :: scaleFactor ! scale_factor values used for each\n                                               ! variable to converte from\n                                               ! real to\n                                               ! integer.\n   real, dimension(numGwVars)             :: addOffset   ! add_offset values for each variable.\n   character (len=64), dimension(numGwVars) :: longName  ! Long names for each variable.\n   character (len=64), dimension(numGwVars) :: units ! Units for each variable.\n   !character (len=64), dimension(numGwVars) :: coordNames ! Coordinate names for each variable.\n   integer(kind=4), dimension(numGwVars) :: validMinComp ! Valid min (after conversion to integer)\n   integer(kind=4), dimension(numGwVars) :: validMaxComp ! Valid max (after conversion to integer)\n   real*8, dimension(numGwVars) :: validMinDbl ! Valid minimum (before conversion to integer)\n   real*8, dimension(numGwVars) :: validMaxDbl ! Valid maximum (before converstion to integer)\n   integer(kind=4), dimension(numGwVars) :: missingComp ! Missing value attribute (after conversion to integer)\n   real, dimension(numGwVars) :: missingReal ! Missing value attribute (before conversion to integer)\n   real, dimension(numGwVars) :: fillReal ! Fill value (before conversion to integer)\n   integer(kind=4), dimension(numGwVars) :: fillComp ! Fill value (after conversion to integer)\n   integer, dimension(numGwVars) :: outFlag ! 0/1 flag to turn outputting off/on\n   integer, dimension(numGwVars) :: timeZeroFlag ! 0/1 flag to either set variable to all NDV values or output\n                                                   ! the actual data. This was\n                                                   ! done because time 0\n                                                   ! output does not all contain\n                                                   ! valid data.\n   real :: modelNdv ! NDV value represented within the model code\n   ! Time variable attribues\n   character (len=64) :: timeLName ! long_name - usually valid output time\n   character (len=64) :: timeUnits ! Usually seconds since 1/1/1970\n   character (len=64) :: timeStName ! standard_name - usually time\n   integer :: timeValidMin ! the minimum time each configuration can have, time of the first output file\n   integer :: timeValidMax ! the maximum time each configuration can have, time of the last output file\n   ! Reference time attributes\n   character (len=64) :: rTimeLName ! long_name - usually model initialization time\n   character (len=64) :: rTimeStName ! standard_name - usually forecast_reference_time\n   character (len=64) :: rTimeUnits ! Usually seconds since 1/1/1970\n   ! gw_id attributes\n   character (len=64) :: gwIdLName ! long_name - usually gw bucket ID\n   character (len=256) :: gwIdComment ! Comment attribute\n   ! feature_id attributes\n   character (len=256) :: featureIdLName ! long_name - usually gw bucket ID\n   character (len=256) :: featureIdComment ! Comment attribute\n   character (len=64) :: cfRole ! cf_role attribute\n   ! latitude variable attributes\n   !character (len=64) :: latLName ! long_name\n   !character (len=64) :: latUnits ! units\n   !character (len=64) :: latStName ! Standard Name\n   ! longitude variable attributes\n   !character (len=64) :: lonLName ! long_name\n   !character (len=64) :: lonUnits ! units\n   !character (len=64) :: lonStName ! Standard Name\n   ! elevation variable attributes\n   !character (len=64) :: elevLName ! long_name\n   !character (len=64) :: elevUnits ! units\n   !character (len=64) :: elevStName ! Standard Name\n   ! Global attributes\n   character (len=128) :: title ! file title\n   character (len=128) :: fType ! featureType attribute\n   !character (len=128) :: proj4 ! proj4 attribute\n   character (len=128) :: initTime ! model_initialization_time attribute\n   character (len=128) :: validTime ! model_output_valid_time attribute\n   character (len=128) :: gwDim ! gw_dimension attribute\n   !character (len=128) :: cdm ! cdm_datatype attribute\n   !character (len=1024) :: esri ! esri_pe_string attribute\n   character (len=128) :: conventions ! Conventions string\n   integer             :: totalValidTime ! # number of valid time (#of output files)\n\nend type gwMeta\n\ncontains\n\nsubroutine initChrtDict(chrtOutDict,diagFlag,procId)\n  use config_base, only: nlst\n  use netcdf\n  implicit none\n\n   type(chrtMeta), intent(inout) :: chrtOutDict\n   integer, intent(inout) :: diagFlag\n   integer, intent(inout) :: procId\n\n   ! Local variables\n   integer :: ftnMeta,iret\n   integer :: projVarId\n\n   chrtOutDict%modelNdv = -9.E15\n   ! CHRTOUT FILES\n\n   ! Pull spatial metadata information about the modeling domain from the land\n   ! spatial metadata file.\n   if(procId .eq. 0) then\n      iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnMeta)\n      if(iret .ne. 0) then\n         ! Spatial metadata file not found for land grid.\n         call postDiagMsg(diagFlag,'WARNING: Unable to open LAND spatial metadata file.')\n         chrtOutDict%proj4 = ''\n         chrtOutDict%esri = ''\n      else\n         ! First pull metadata on coordinate system.\n         iret = nf90_inq_varid(ftnMeta,'crs',projVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to find crs in LAND spatial metadata file')\n            chrtOutDict%proj4 = ''\n            chrtOutDict%esri = ''\n         else\n            iret = nf90_get_att(ftnMeta,projVarId,'esri_pe_string',chrtOutDict%esri)\n            if(iret .ne. 0) then\n               call postDiagMsg(diagFlag,'WARNING: Unable to find esri_pe_string in LAND spatial metadata file.')\n               chrtOutDict%esri = ''\n            endif\n            iret = nf90_get_att(ftnMeta,NF90_GLOBAL,'proj4',chrtOutDict%proj4)\n            ! We are going to put a relaxed constraint on the proj4 string.\n            if(iret .ne. 0) then\n               call postDiagMsg(diagFlag,'WARNING: proj4 string not found. Defaulting to blank string.')\n               chrtOutDict%proj4 = ''\n            endif\n         endif\n         ! Close the file\n         iret = nf90_close(ftnMeta)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAND spatial metadata file.')\n      endif\n   endif\n\n   ! NOTE !!!!! If you see PLC, this means OWP has no desire to output these,\n   !            which means meta-data standards have yet to be determined\n   !            for these variables. Fill in if it's desired to output....\n   ! First establish global attributes for the channel output files\n   chrtOutDict%title = \"OUTPUT FROM \" // trim(get_model_version())\n   chrtOutDict%fType = 'timeSeries'\n   chrtOutDict%initTime = '1970-01-01_00:00:00' ! This will be calculated in I/O code\n   chrtOutDict%validTime = '1970-01-01_00:00:00' ! This will be calculated in I/O code\n   chrtOutDict%stDim = 'feature_id'\n   chrtOutDict%stOrder = 1\n   chrtOutDict%cdm = 'Station'\n   chrtOutDict%conventions = 'CF-1.6'\n\n   ! Next establish time attribues\n   chrtOutDict%timeLName = 'valid output time'\n   chrtOutDict%timeUnits = 'minutes since 1970-01-01 00:00:00 UTC'\n   chrtOutDict%timeStName = 'time'\n   chrtOutDict%rTimeLName = 'model initialization time'\n   chrtOutDict%rTimeStName = 'forecast_reference_time'\n   chrtOutDict%rTimeUnits = 'minutes since 1970-01-01 00:00:00 UTC'\n\n   ! Esatablish lat/lon attributes\n   chrtOutDict%latLName = \"Feature latitude\"\n   chrtOutDict%latUnits = \"degrees_north\"\n   chrtOutDict%latStName = \"latitude\"\n   chrtOutDict%lonLName = \"Feature longitude\"\n   chrtOutDict%lonUnits = \"degrees_east\"\n   chrtOutDict%lonStName = \"longitude\"\n\n   ! Establish streamflw order attributes\n   chrtOutDict%orderLName = \"Streamflow Order\"\n   chrtOutDict%orderStName = \"order\"\n\n   ! Establish point elevation attributes\n   chrtOutDict%elevLName = \"Feature Elevation\"\n   chrtOutDict%elevUnits = \"meters\"\n   chrtOutDict%elevStName = \"Elevation\"\n\n   ! Next establish feature_id attributes. Given this is merged community, we\n   chrtOutDict%featureIdLName = 'Reach ID'\n   chrtOutDict%featureIdComment = 'NHDPlusv2 ComIDs within CONUS, arbitrary Reach IDs outside of CONUS'\n   chrtOutDict%cfRole = 'timeseries_id'\n\n   ! Now establish attributes for output variables.\n   !chrtOutDict%varNames(:) = (/\"streamflow\",\"nudge\",\"q_lateral\",\"velocity\",&\n   !                            \"Head\",\"qSfcLatRunoff\",\"qBucket\",&\n   !                            \"qBtmVertRunoff\",\"AccSfcLatRunoff\",\"accBucket\"/)\n   chrtOutDict%varNames(:) = [character(len=64) :: \"streamflow\",\"nudge\",\"q_lateral\",\"velocity\",&\n                              \"Head\",\"qSfcLatRunoff\",\"qBucket\",&\n                              \"qBtmVertRunoff\",\"AccSfcLatRunoff\",\"accBucket\",\"qloss\"]\n   chrtOutDict%longName(:) = [character(len=64) :: \"River Flow\",\"Amount of stream flow alteration\",&\n                              \"Runoff into channel reach\",\"River Velocity\",&\n                              \"River Stage\",\"Runoff from terrain routing\",&\n                              \"Flux from gw bucket\",&\n                              \"Runoff from bottom of soil to bucket\",&\n                              \"Accumulated runoff from terrain routing\",&\n                              \"Accumulated runoff from gw bucket\",&\n                              \"Channel Infiltration\"]\n   chrtOutDict%units(:) = [character(len=64) :: \"m3 s-1\",\"m3 s-1\",\"m3 s-1\",\"m s-1\",&\n                                                \"meter\",\"m3 s-1\",\"m3 s-1\",&\n                                                \"m3\",\"m3\",\"m3\",\"m3 s-1\"]\n   chrtOutDict%coordNames(:) = [character(len=64) :: \"latitude longitude\",\"latitude longitude\",&\n                                 \"latitude longitude\",\"latitude longitude\",&\n                                 \"latitude longitude\",\"latitude longitude\",&\n                                 \"latitude longitude\",\"latitude longitude\",&\n                                 \"latitude longitude\",\"latitude longitude\",&\n                                 \"latitude longitude\"]\n   chrtOutDict%scaleFactor(:) = [0.01,0.01,0.1,0.01,0.01,0.00001,0.00001,0.001,&\n                                 0.01,0.01,0.1]\n   chrtOutDict%addOffset(:) = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,&\n                               0.0,0.0]\n   ! Initialize all output flags to 0. Modify (if absolutely necessary) in the\n   ! output subroutine.\n   chrtOutDict%outFlag(:) = [0,0,0,0,0,0,0,0,0,0,0]\n   chrtOutDict%timeZeroFlag(:) = [1,1,1,1,1,1,1,1,1,1,1]\n   chrtOutDict%fillReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,&\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0]\n   chrtOutDict%missingReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,&\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0,&\n                                 -9999.0]\n   chrtOutDict%validMinDbl(:) = [0.0d0, -50000.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, &\n                                  0.0d0, 0.0d0, 0.0d0]\n   chrtOutDict%validMaxDbl(:) = [50000.0d0, 50000.0d0, 50000.0d0, 50000.0d0, 50000.0d0, &\n                                  20000.0d0, 20000.0d0, 20000.0d0, 50000.0d0, &\n                                  50000.0d0, 50000.0d0]\n   ! Loop through and calculate missing/fill/min/max values that will be placed\n   ! into the NetCDF attributes after scale_factor/add_offset are applied.\n   do i=1,numChVars\n      chrtOutDict%fillComp(i) = &\n           nint((chrtOutDict%fillReal(i)     + chrtOutDict%addOffset(i)), 8) * &\n           nint(one_dbl / chrtOutDict%scaleFactor(i), 8)\n      chrtOutDict%missingComp(i) = &\n           nint((chrtOutDict%missingReal(i)  + chrtOutDict%addOffset(i)), 8) * &\n           nint(one_dbl / chrtOutDict%scaleFactor(i), 8)\n      chrtOutDict%validMinComp(i) = &\n           nint((chrtOutDict%validMinDbl(i) + chrtOutDict%addOffset(i)) * &\n                nint(one_dbl / chrtOutDict%scaleFactor(i), 8), 8)\n      chrtOutDict%validMaxComp(i) = &\n           nint((chrtOutDict%validMaxDbl(i) + chrtOutDict%addOffset(i)) * &\n                nint(one_dbl / chrtOutDict%scaleFactor(i), 8), 8)\n   end do\nend subroutine initChrtDict\n\nsubroutine initLdasDict(ldasOutDict,procId,diagFlag)\n  use config_base, only: nlst\n  use netcdf\n  implicit none\n\n   type(ldasMeta), intent(inout) :: ldasOutDict\n   integer, intent(inout) :: procId\n   integer, intent(inout) :: diagFlag\n   integer :: ftnMeta,projVarId,xVarId,yVarId\n   integer :: iret\n   integer :: crsRealAttCnt,xRealAttCnt,yRealAttCnt\n   integer :: crsCharAttCnt,xCharAttCnt,yCharAttCnt\n   integer :: i, nCrsAtts,nxAtts,nyAtts\n   integer :: charFlag\n   integer :: floatFlag\n   character(len=512) :: tmpAttName\n   integer :: xtypeTmp\n   integer :: tmpLen\n\n   ! LDASOUT FILES\n\n   ldasOutDict%numSoilLayers = nlst(1)%nsoil\n   ldasOutDict%act_lev = nlst(1)%act_lev\n\n\n   ldasOutDict%modelNdv = 9.9692099683868690E36\n   ldasOutDict%modelNdv2 = -1.E33\n   ldasOutDict%modelNdv3 = -1.E36\n   ldasOutDict%modelNdvInt = -2147483647\n\n   ! First establish global attributes.\n   ldasOutDict%title = \"OUTPUT FROM \" // trim(get_model_version())\n   ldasOutDict%initTime = \"1970-01-01_00:00:00\" ! This will be calculated in I/O code.\n   ldasOutDict%validTime = \"1970-01-01_00:00:00\" ! This will be calculated in I/O code.\n   ldasOutDict%conventions = \"CF-1.6\"\n\n   ! Next establish time attributes\n   ldasOutDict%timeLName = \"valid output time\"\n   ldasOutDict%timeUnits = \"minutes since 1970-01-01 00:00:00 UTC\"\n   ldasOutDict%timeStName = \"time\"\n   ldasOutDict%rTimeLName = \"model initialization time\"\n   ldasOutDict%rTimeUnits = \"minutes since 1970-01-01 00:00:00 UTC\"\n   ldasOutDict%rTimeStName = \"forecast_reference_time\"\n\n   crsRealAttCnt = 0\n   crsCharAttCnt = 0\n   xRealAttCnt = 0\n   xCharAttCnt = 0\n   yRealAttCnt = 0\n   yCharAttCnt = 0\n\n   ! Pull spatial metadata information about the modeling domain from the land\n   ! spatial metadata file.\n   if(procId .eq. 0) then\n      iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnMeta)\n      if(iret .ne. 0) then\n         ! Spatial metadata file not found for land grid.\n         call postDiagMsg(diagFlag,'WARNING: Unable to open LAND spatial metadata file. No crs variable or attributes will be created.')\n         ldasOutDict%nCrsCharAtts = 0\n         ldasOutDict%nCrsRealAtts = 0\n         ldasOutDict%nxCharAtts = 0\n         ldasOutDict%nxRealAtts = 0\n         ldasOutDict%nyCharAtts = 0\n         ldasOutDict%nyRealAtts = 0\n         ldasOutDict%proj4 = ''\n      else\n         iret = nf90_get_att(ftnMeta,NF90_GLOBAL,'proj4',ldasOutDict%proj4)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to find proj4 global attribute. Defaulting to blank string.')\n            ldasOutDict%proj4 = ''\n         endif\n         charFlag = 0\n         floatFlag = 0\n         ! Find the crs variable and pull out the attributes, their names, and\n         ! their values. This will be translated to output files.\n         iret = nf90_inq_varid(ftnMeta,'crs',projVarId)\n         ! For now we are going to allow the code to move forward without\n         ! finding this variable. In the future, we will probably restrict the\n         ! code to ensure things are more seamless.\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the crs variable. No crs variable or attributes will be created.')\n            ldasOutDict%nCrsCharAtts = 0\n            ldasOutDict%nCrsRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,projVarId,nAtts=nCrsAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find crs number of attributes')\n            do i =1,nCrsAtts\n               iret = nf90_inq_attname(ftnMeta,projVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from crs variable.')\n               iret = nf90_inquire_attribute(ftnMeta,projVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from crs variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  ldasOutDict%crsCharAttNames(crsCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,projVarId,trim(tmpAttName),ldasOutDict%crsCharAttVals(crsCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull crs attributes')\n                  crsCharAttCnt = crsCharAttCnt + 1\n               else\n                  ldasOutDict%crsFloatAttNames(crsRealAttCnt+1) = trim(tmpAttName)\n                  ldasOutDict%crsRealAttLen(crsRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,projVarId,trim(tmpAttName),ldasOutDict%crsRealAttVals(crsRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull crs attributes')\n                  crsRealAttCnt = crsRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            ldasOutDict%nCrsRealAtts = crsRealAttCnt\n            ldasOutDict%nCrsCharAtts = crsCharAttCnt\n\n         endif\n\n         ! Next pull the attributes from the x/y dimensions\n         charFlag = 0\n         floatFlag = 0\n         iret = nf90_inq_varid(ftnMeta,'x',xVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the x variable. No x variable or attributes will be created.')\n            ldasOutDict%nxCharAtts = 0\n            ldasOutDict%nxRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,xVarId,nAtts=nxAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find x number of attributes')\n            do i =1,nxAtts\n               iret = nf90_inq_attname(ftnMeta,xVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from x variable.')\n               iret = nf90_inquire_attribute(ftnMeta,xVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from x variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  ldasOutDict%xCharAttNames(xCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,xVarId,trim(tmpAttName),ldasOutDict%xCharAttVals(xCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull x attributes')\n                  xCharAttCnt = xCharAttCnt + 1\n               else\n                  ldasOutDict%xFloatAttNames(xRealAttCnt+1) = trim(tmpAttName)\n                  ldasOutDict%xRealAttLen(xRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,xVarId,trim(tmpAttName),ldasOutDict%xRealAttVals(xRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull x attributes')\n                  xRealAttCnt = xRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            ldasOutDict%nxRealAtts = xRealAttCnt\n            ldasOutDict%nxCharAtts = xCharAttCnt\n\n         endif\n\n         charFlag = 0\n         floatFlag = 0\n         iret = nf90_inq_varid(ftnMeta,'y',yVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the y variable. No y variable or attributes will be created.')\n            ldasOutDict%nyCharAtts = 0\n            ldasOutDict%nyRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,yVarId,nAtts=nyAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find y number of attributes')\n            do i =1,nyAtts\n               iret = nf90_inq_attname(ftnMeta,yVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from y variable.')\n               iret = nf90_inquire_attribute(ftnMeta,yVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from y variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  ldasOutDict%yCharAttNames(yCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,yVarId,trim(tmpAttName),ldasOutDict%yCharAttVals(yCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull y attributes')\n                  yCharAttCnt = yCharAttCnt + 1\n               else\n                  ldasOutDict%yFloatAttNames(yRealAttCnt+1) = trim(tmpAttName)\n                  ldasOutDict%yRealAttLen(yRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,yVarId,trim(tmpAttName),ldasOutDict%yRealAttVals(yRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull y attributes')\n                  yRealAttCnt = yRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            ldasOutDict%nyRealAtts = yRealAttCnt\n            ldasOutDict%nyCharAtts = yCharAttCnt\n\n         endif\n         ! Close the file\n         iret = nf90_close(ftnMeta)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAND spatial metadata file.')\n      endif\n   endif\n\n   ! Now establish metadata attributes for variables. ESRI string is defined\n   ! above and applies to all gridded variables for LDASOUT.\n   ldasOutDict%varNames(:) = [character(len=64) :: &\n                               \"IVGTYP\",\"ISLTYP\",\"FVEG\",\"LAI\",\"SAI\", &                   !1-5\n                               \"SWFORC\",\"COSZ\",\"LWFORC\",\"RAINRATE\",\"EMISS\", &            !6-10\n                               \"FSA\",\"FIRA\",\"GRDFLX\",\"HFX\",\"LH\", &                       !11-15\n                               \"ECAN\",\"EDIR\",\"ALBEDO\",\"ETRAN\",\"UGDRNOFF\", &              !16-20\n                               \"SFCRNOFF\",\"CANLIQ\",\"CANICE\",\"ZWT\",\"WA\", &                !21-25\n                               \"WT\",\"ACCPRCP\",\"ACCECAN\",\"ACCEDIR\",\"ACCETRAN\", &          !26-30\n                               \"SAV\",\"TR\",\"EVC\",\"IRC\",\"SHC\", &                           !31-35\n                               \"IRG\",\"SHG\",\"EVG\",\"GHV\",\"SAG\", &                          !36-40\n                               \"IRB\",\"SHB\",\"EVB\",\"GHB\",\"TRAD\", &                         !41-45\n                               \"TG\",\"TV\",\"TAH\",\"TGV\",\"TGB\", &                            !46-50\n                               \"T2MV\",\"T2MB\",\"Q2MV\",\"Q2MB\",\"EAH\", &                      !51-55\n                               \"FWET\",\"ZSNSO_SN\",\"SNICE\",\"SNLIQ\",\"SOIL_T\", &             !56-60\n                               \"SOIL_W\",\"SNOW_T\",\"SOIL_M\",\"SNOWH\",\"SNEQV\", &             !60-65\n                               \"QSNOW\",\"ISNOW\",\"FSNO\",\"ACSNOW\",\"ACSNOM\", &               !66-70\n                               \"CM\",\"CH\",\"CHV\",\"CHB\",\"CHLEAF\", &                         !71-75\n                               \"CHUC\",\"CHV2\",\"CHB2\",\"LFMASS\",\"RTMASS\", &                 !76-80\n                               \"STMASS\",\"WOOD\",\"STBLCP\",\"FASTCP\",\"NEE\", &                !81-85\n                               \"GPP\",\"NPP\",\"PSN\",\"APAR\",\"ACCET\", &                       !86-90\n                               \"CANWAT\",\"SOILICE\",\"SOILSAT_TOP\",\"SOILSAT\",\"SNOWT_AVG\", & !91-95\n                               \"ALBSND\",\"ALBSNI\",\"QRAIN\",&                               !96-98\n                               \"glacier\", \"glacier_thickness\" ,\"PSNOWALB\",&              !99-101\n                               \"PSNOWTHRUFAL\" ,\"PSNOWHEIGHT\",\"PSNOWTOTSWE\" ,&            !102-104\n                               \"PSNOWGRAN1\",\"PSNOWGRAN2\",\"PSNOWAGE\",&                    !105-107\n                               \"PSNOWTEMP\",\"PSNOWDZ\",\"PSNOWHIST\",&                       !108-110\n                               \"PSNOWLIQ\",\"PSNOWHEAT\",\"PSNOWRHO\",&                       !111-113\n                               \"PSNOWSWE\", \"FLOW_ICE\", \"FLOW_SNOW\"]                      !114-116\n\n  ldasOutDict%longName(:) = [character(len=128) :: &\n                              \"Dominant vegetation category\",&          !1\n                              \"Dominant soil category\",&                !2\n                              \"Green Vegetation Fraction\",&             !3\n                              \"Leaf area index\",&                       !4\n                              \"Stem area index\",&                       !5\n                              \"Shortwave forcing\",&                     !6\n                              \"Cosine of zenith angle\",&                !7\n                              \"Longwave forcing\",&                      !8\n                              \"Precipitation rate\",&                    !9\n                              \"Grid emissivity\",&                       !10\n                              \"Total absorbed SW radiation\",&           !11\n                              \"Total net LW radiation to atmosphere\",&  !12\n                              \"Heat flux into the soil\",&               !13\n                              \"Total sensible heat to the atmosphere\",& !14\n                              \"Total latent heat to the atmosphere\",&   !15\n                              \"Canopy water evaporation rate\",&         !16\n                              \"Direct from soil evaporation rate\",&     !17\n                              \"Surface albedo\",&                        !18\n                              \"Transpiration rate\",&                    !19\n                              \"Accumulated underground runoff\",&        !20\n                              \"Accumulated surface runoff\",&            !21\n                              \"Canopy liquid water content\",&           !22\n                              \"Canopy ice water content\",&              !23\n                              \"Depth to water table\",&                  !24\n                              \"Water in aquifer\",&                      !25\n                              \"Water in aquifer and saturated soil\",&   !26\n                              \"Accumulated precip\",&                    !27\n                              \"Accumulated canopy evap\",&               !28\n                              \"Accumulated direct soil evap\",&          !29\n                              \"Accumulated transpiration\",&             !30\n                              \"Solar radiative heat flux absorbed by vegetation\",& !31\n                              \"Transpiration heat\",&                    !32\n                              \"Canopy evap heat\",&                      !33\n                              \"Canopy net LW rad\",&                     !34\n                              \"Canopy sensible heat\",&                  !35\n                              \"Ground net LW rad\",&                     !36\n                              \"Ground sensible heat\",&                  !37\n                              \"Ground evap heat\",&                      !38\n                              \"Ground heat flux + to soil vegetated\",&  !39\n                              \"Solar radiative heat flux absorbed by ground\",& !40\n                              \"Net LW rad to atm bare\",&                !41\n                              \"Sensible heat atm bare\",&                !42\n                              \"Evaporation heat to atm bare\",&          !43\n                              \"Ground heat flux + to soil bare\",&       !44\n                              \"Surface radiative temperature\",&         !45\n                              \"Ground temperature\",&                    !46\n                              \"Vegetation temperature\",&                !47\n                              \"Canopy air temperature\",&                !48\n                              \"Ground surface Temp vegetated\",&         !49\n                              \"Ground surface Temp bare\",&              !50\n                              \"2m Air Temp vegetated\",&                 !51\n                              \"2m Air Temp bare\",&                      !52\n                              \"2m mixing ratio vegetated\",&             !53\n                              \"2m mixing ratio bare\",&                  !54\n                              \"Canopy air vapor pressure\",&             !55\n                              \"Wetted or snowed fraction of canopy\",&   !56\n                              \"Snow layer depths from snow surface\",&   !57\n                              \"Snow layer ice\",&                        !58\n                              \"Snow layer liquid water\",&               !59\n                              \"soil temperature\",&                      !60\n                              \"liquid volumetric soil moisture\",&       !61\n                              \"snow temperature\",&                      !62\n                              \"volumetric soil moisture, the dimensionless ratio of water volume (m3) to soil volume (m3)\",& !63\n                              \"Snow depth\",&                            !64\n                              \"Snow water equivalent\",&                 !65\n                              \"Snowfall rate on the ground\",&           !66\n                              \"Number of snow layers\",&                 !67\n                              \"Snow-cover fraction on the ground\",&     !68\n                              \"accumulated snow fall\",&                 !69\n                              \"accumulated melting water out of snow bottom\",& !70\n                              \"Momentum drag coefficient\",&             !71\n                              \"Sensible heat exchange coefficient\",&    !72\n                              \"Exchange coefficient vegetated\",&        !73\n                              \"Exchange coefficient bare\",&             !74\n                              \"Exchange coefficient leaf\",&             !75\n                              \"Exchange coefficient bare\",&             !76\n                              \"Exchange coefficient 2-meter vegetated\",&!77\n                              \"Exchange coefficient 2-meter bare\",&     !78\n                              \"Leaf mass\",&                             !79\n                              \"Mass of fine roots\",&                    !80\n                              \"Stem mass\",&                             !81\n                              \"Mass of wood and woody roots\",&          !82\n                              \"Stable carbon in deep soil\",&            !83\n                              \"Short-lived carbon in shallow soil\",&    !84\n                              \"Net ecosystem exchange\",&                !85\n                              \"Net instantaneous assimilation\",&        !86\n                              \"Net primary productivity\",&              !87\n                              \"Total photosynthesis\",&                  !88\n                              \"Photosynthesis active energy by canopy\",&!89\n                              \"Accumulated total ET\",&                  !90\n                              \"Total canopy water (liquid + ice)\",&     !91\n                              \"fraction of soil moisture that is ice\",& !92\n                              \"fraction of soil saturation, top 2 layers\",& !93\n                              \"fraction of soil saturation, column integrated\",& !94\n                              \"average snow temperature (by layer mass)\",& !95\n                              \"snowpack albedo, direct\",&               !96\n                              \"snowpack albedo, diffuse\",&              !97\n                              \"Rainfall rate on the ground\",&           !98\n                              \"Glacier grid point\",&                    !99\n                              \"Glacier height\",&                        !100\n                              \"Snow albedo\",&                           !101\n                              \"Runoff from glacier\",&                   !102\n                              \"Total snow height\",&                     !103\n                              \"Total snow swe\", &                       !104\n                               \"Snow gran 1, optiacal diameter\",&       !105\n                               \"Snow gran 2, sphericity\",&              !106\n                               \"Snow age\",&                             !107\n                               \"Snow temperature\",&                     !108\n                               \"Snow thickness\",&                       !109\n                               \"Snow history\",&                         !110\n                               \"Liquid in snow\",&                       !111\n                               \"Snow heat\",&                            !112\n                               \"Snow density\",&                         !113\n                               \"Snow water equivalent\", &               !114\n                               \"Accumulated glacier melt from ice\", &   !115\n                               \"Accumulated glacier melt from snow\"]    !116\n\n   ldasOutDict%units(:) = [character(len=64) :: &\n                            \"category\",\"category\",\"-\",\"-\",\"-\", &               !1-5\n                            \"W m-2\",\"-\",\"W m-2\",\"kg m-2 s-1\",\"-\", &            !6-10\n                            \"W m-2\",\"W m-2\",\"W m-2\",\"W m-2\",\"W m-2\", &         !11-15\n                            \"kg m-2 s-1\",\"kg m-2 s-1\",\"-\",\"kg m-2 s-1\",\"mm\", & !16-20\n                            \"mm\",\"mm\",\"mm\",\"m\",\"kg m-2\", &                     !21-25\n                            \"kg m-2\",\"mm\",\"mm\",\"mm\",\"mm\", &                    !26-30\n                            \"W m-2\",\"W m-2\",\"W m-2\",\"W m-2\",\"W m-2\", &         !31-35\n                            \"W m-2\",\"W m-2\",\"W m-2\",\"W m-2\",\"W m-2\", &         !36-40\n                            \"W m-2\",\"W m-2\",\"W m-2\",\"W m-2\",\"K\", &             !41-45\n                            \"K\",\"K\",\"K\",\"K\",\"K\", &                             !46-50\n                            \"K\",\"K\",\"kg/kg\",\"kg/kg\",\"Pa\", &                    !51-55\n                            \"fraction\",\"m\",\"mm\",\"mm\",\"K\", &                    !56-60\n                            \"m3 m-3\",\"K\",\"m3 m-3\",\"m\",\"kg m-2\", &              !61-65\n                            \"mm s-1\",\"count\",\"1\",\"mm\",\"mm\", &                  !66-70\n                            \"-\",\"-\",\"m s-1\",\"m s-1\",\"m s-1\", &                 !71-75\n                            \"m s-1\",\"m s-1\",\"m s-1\",\"g m-2\",\"g m-2\", &         !76-80\n                            \"g m-2\",\"g m-2\",\"g m-2\",\"g m-2\",\"g m-2s-1 CO2\", &  !81-85\n                            \"g m-2s-1 C\",\"g m-2s-1 C\",\"umol CO2 m-2 s-1\",\"W m-2\",\"mm\", & !86-90\n                            \"mm\",\"1\",\"1\",\"1\",\"K\", &                            !91-95\n                            \"-\",\"-\",\"mm s-1\",&                                 !96-98\n                            \"-\",\"m\",\"-\", &                                     !99-101\n                            \"kg/(m2 s)\",\"m\",\"kg m-2\",&                         !102-104\n                            \"m\",\"-\",\"days since snowfall\",&                    !105-107\n                            \"K\",\"m\",\"-\",&                                      !108-110\n                            \"kg/m3\",\"J/m2\",\"m\",&                               !111-113\n                            \"kg m-2\",\"kg/m2\",\"kg/m2\"]                          !114-116\n\n   ldasOutDict%scaleFactor(:) = [1.0, 1.0, 0.01, 0.1, 0.1, &                   !1-5\n                                 0.1, 0.01, 0.1, 0.00001, 0.01, &              !6-10\n                                 0.1, 0.1, 0.1, 0.1, 0.1, &                    !11-15\n                                 0.00001, 0.00001, 0.01, 0.00001, 0.01, &      !16-20\n                                 0.001, 0.01, 0.01, 0.00001, 0.01, &           !21-25\n                                 0.01, 0.01, 0.01, 0.01, 0.01, &               !26-30\n                                 0.1, 0.1, 0.1, 0.1, 0.1, &                    !31-35\n                                 0.1, 0.1, 0.1, 0.1, 0.1, &                    !36-40\n                                 0.1, 0.1, 0.1, 0.1, 0.1, &                    !41-45\n                                 0.1, 0.1, 0.1, 0.1, 0.1, &                    !46-50\n                                 0.1, 0.1, 0.0001, 0.0001, 0.1, &              !51-55\n                                 0.01, 0.00001, 0.01, 0.01, 0.1, &             !56-60\n                                 0.01, 0.1, 0.01, 0.0001, 0.1, &               !61-65\n                                 0.00001, 1.0, 0.001, 0.01, 0.01, &            !66-70\n                                 0.00001, 0.00001, 0.00001, 0.00001, 0.00001, &!71-75\n                                 0.00001, 0.00001, 0.00001, 0.01, 0.01, &      !76-80\n                                 0.01, 0.01, 0.01, 0.01, 0.01, &               !81-85\n                                 0.01, 0.01, 0.01, 0.01, 0.01, &               !86-90\n                                 0.01, 0.01, 0.001, 0.001, 0.1, &              !91-95\n                                 0.01, 0.01, 0.00001, &                        !96-98\n                                 1.0, 0.1, 0.01, &                             !99-101\n                                 0.0001, 0.0001, 0.1, &                        !102-104\n                                 0.01, 0.01, 0.01, &                           !105-107\n                                 0.1, 0.0001, 0.01, &                          !108-110\n                                 0.001, 1000.0, 0.1, &                         !111-113\n                                 0.1, 0.001, 0.001 ]                           !114-116\n\n   ldasOutDict%addOffset(:) = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !1-10\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !11-20\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !21-30\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !31-40\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !41-50\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !51-60\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !61-70\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !71-80\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, & !81-90\n                               0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0, &         !91-98\n                               0.0,0.0,0.0, &                             !99-101\n                               0.0,0.0,0.0, &                             !102-104\n                               0.0,0.0,0.0, &                             !105-107\n                               0.0,0.0,0.0, &                             !108-110\n                               0.0,0.0,0.0, &                             !111-113\n                               0.0,0.0,0.0]                               !114-116\n\n   ! Note that output flags will be set in the the output routine, and will vary\n   ! by the IOC flag specified in hydro.namelist.\n   ldasOutDict%outFlag(:) = [0,0,0,0,0,0,0,0,0,0, & !1-10\n                             1,0,0,0,0,0,0,0,0,0, & !11-20\n                             0,0,0,0,0,0,0,0,0,0, & !21-30\n                             0,0,0,0,0,0,0,0,0,0, & !31-40\n                             0,0,0,0,0,0,0,0,0,0, & !41-50\n                             0,0,0,0,0,0,0,0,0,0, & !51-60\n                             0,0,0,0,0,0,0,0,0,0, & !61-70\n                             0,0,0,0,0,0,0,0,0,0, & !71-80\n                             0,0,0,0,0,0,0,0,0,0, & !81-90\n                             0,0,0,0,0,0,0,0, &     !91-98\n                             0,0,0, &               !99-101\n                             0,0,0, &               !102-104\n                             0,0,0, &               !105-107\n                             0,0,0, &               !108-110\n                             0,0,0, &               !111-103\n                             0,0,0]                 !114-116\n\n   ldasOutDict%timeZeroFlag(:) = [1,1,1,1,1,1,1,1,1,1, & !1-10\n                                  1,1,1,1,1,1,1,1,1,1, & !11-20\n                                  1,1,1,1,1,1,1,1,1,1, & !21-30\n                                  1,1,1,1,1,1,1,1,1,1, & !31-40\n                                  1,1,1,1,1,1,1,1,1,1, & !41-50\n                                  1,1,1,1,1,1,1,1,1,1, & !51-60\n                                  1,1,1,1,1,1,1,1,1,1, & !61-70\n                                  1,1,1,1,1,1,1,1,1,1, & !71-80\n                                  1,1,1,1,1,1,1,1,1,1, & !81-90\n                                  1,1,1,1,1,1,1,1, &     !91-98\n                                  1,1,1, &               !99-101\n                                  1,1,1, &               !102-104\n                                  1,1,1, &               !105-107\n                                  1,1,1, &               !108-110\n                                  1,1,1, &               !111-113\n                                  1,1,1]                 !114-116\n\n   ldasOutDict%numLev(:) = [1,1,1,1,1,1,1,1,1,1, &  !1-10\n                            1,1,1,1,1,1,1,1,1,1, &  !11-20\n                            1,1,1,1,1,1,1,1,1,1, &  !21-30\n                            1,1,1,1,1,1,1,1,1,1, &  !31-40\n                            1,1,1,1,1,1,1,1,1,1, &  !41-50\n                            1,1,1,1,1,1,3,3,3,4, &  !51-60\n                            4,3,4,1,1,1,1,1,1,1, &  !61-70\n                            1,1,1,1,1,1,1,1,1,1, &  !71-80\n                            1,1,1,1,1,1,1,1,1,1, &  !81-90\n                            1,1,1,1,1,2,2,1, &      !91-98\n                            1,1,1, &                !99-101\n                            1,1,1, &                !102-104\n                            40,40,40, &             !105-107\n                            40,40,40, &             !108-110\n                            40,40,40, &             !111-113\n                            40,1,1]                 !114-116\n   ldasOutDict%numLev(105:114) = ldasOutDict%act_lev ! Set crocus levels to number from namelist\n\n   ldasOutDict%missingReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !1-5\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !6-10\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !11-15\n                                 -9999.0, -999.0,-9999.0,-9999.0,-9999.0, & !16-20\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !21-25\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !26-30\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !31-35\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !36-40\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !41-45\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !46-50\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !51-55\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !56-60\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !61-65\n                                  -999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !66-70\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !71-75\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !76-80\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !81-85\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !86-90\n                                 -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !91-95\n                                 -9999.0,-9999.0,-999.0,                  & !96-98\n                                 -9999.0,-9999.0,-9999.0,                 & !99-101\n                                 -9999.0,-9999.0,-9999.0,                 & !102-104\n                                 -9999.0,-9999.0,-9999.0,                 & !105-107\n                                 -9999.0,-9999.0,-9999.0,                 & !108-110\n                                 -9999.0, 9999000.0,-9999.0,                 & !111-113\n                                 -9999.0,-9999.0,-9999.0 ]                  !114-116\n\n   ldasOutDict%fillReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !1-5\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !6-10\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !11-15\n                              -9999.0, -999.0,-9999.0,-9999.0,-9999.0, & !16-20\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !21-25\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !26-30\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !31-35\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !36-40\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !41-45\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !46-50\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !51-55\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !56-60\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !61-65\n                               -999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !66-70\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !71-75\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !76-80\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !81-85\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !86-90\n                              -9999.0,-9999.0,-9999.0,-9999.0,-9999.0, & !91-95\n                              -9999.0,-9999.0,-999.0,                  & !96-98\n                              -9999.0,-9999.0,-9999.0,                 & !99-101\n                              -9999.0,-9999.0,-9999.0,                 & !102-104\n                              -9999.0,-9999.0,-9999.0,                 & !105-107\n                              -9999.0,-9999.0,-9999.0,                 & !108-110\n                              -9999.0, 9999000.0,-9999.0,                 & !111-113\n                              -9999.0,-9999.0,-9999.0 ]                  !114-116\n\n   ldasOutDict%validMinDbl(:) = [0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, &                     !1-5\n                                 -1000.0d0, -1.0d0, -1500.0d0, 0.0d0, 0.0d0, &            !6-10\n                                 -1500.0d0, -1500.0d0, -1500.0d0, -1500.0d0, -1500.0d0, & !11-15\n                                 -100.0d0, -100.0d0, 0.0d0, -100.0d0, -100.0d0, &         !16-20\n                                 0.0d0, -5.0d0, -5.0d0, 0.0d0, 0.0d0, &                   !21-25\n                                 0.0d0, 0.0d0, -100.0d0, -100.0d0, -100.0d0, &            !26-30\n                                 -1500.0d0, -1500.0d0, -1500.0d0, -1500.0d0, -1500.0d0, & !31-35\n                                 -1500.0d0, -1500.0d0, -1500.0d0, -1500.0d0, -1500.0d0, & !36-40\n                                 -1500.0d0, -1500.0d0, -1500.0d0, -1500.0d0, 0.0d0, &     !41-45\n                                 0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, &                     !46-50\n                                 0.0d0, 0.0d0, 0.0d0, 0.0d0, -1000.0d0, &                 !51-55\n                                 0.0d0, -100.0d0, 0.0d0, 0.0d0, 0.0d0, &                  !56-60\n                                 0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, &                     !61-65\n                                 0.0d0, -10.d0, 0.0d0, 0.0d0, 0.0d0, &                    !66-70\n                                 -5.0d0, -5.0d0, -5.0d0, -5.0d0, -5.0d0, &                !71-75\n                                 -5.0d0, -5.0d0, -5.0d0, 0.0d0, 0.0d0, &                  !76-80\n                                 0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, &                     !81-85\n                                 0.0d0, 0.0d0, 0.0d0, 0.0d0, -1000.0d0, &                 !86-90\n                                 -5.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, &                    !91-95\n                                 0.0d0, 0.0d0, 0.0d0,&                                    !96-98\n   !! NBNB Check these values\n                                 0.0d0, 0.0d0, 0.0d0, &                                   !99-101\n                                 0.0d0, 0.0d0, 0.0d0, &                                   !102-104\n                                 -1.0d2, 0.0d0, 0.0d0, &                                  !105-107\n                                 0.0d0, 0.0d0, 0.0d0, &                                   !108-110\n                                 0.0d0, -2.0d12, 0.0d0, &                                  !111-113\n                                 0.0d0, 0.0d0, 0.0d0 ]                                    !114-116\n\n   ldasOutDict%validMaxDbl(:) = [100.0d0, 100.0d0, 1.0d0, 20.0d0, 20.0d0, &             !1-5\n                                 3000.0d0, 1.0d0, 1500.0d0, 100.0d0, 1.0d0, &           !6-10\n                                 1500.0d0, 1500.0d0, 1500.0d0, 1500.0d0, 1500.0d0, &    !11-15\n                                 100.0d0, 100.0d0, 1.0d0, 100.0d0, 100000.0d0, &        !16-20\n                                 100000.0d0, 30000.0d0, 30000.0d0, 10.0d0, 10000.0d0, & !21-25\n                                 10000.0d0, 1.0D+6, 1.0D+6, 1.0D+6, 1.0D+6, &           !26-30\n                                 1500.0d0, 1500.0d0, 1500.0d0, 1500.0d0, 1500.0d0, &    !31-35\n                                 1500.0d0, 1500.0d0, 1500.0d0, 1500.0d0, 1500.0d0, &    !36-40\n                                 1500.0d0, 1500.0d0, 1500.0d0, 1500.0d0, 400.0d0, &     !41-45\n                                 400.0d0, 400.0d0, 400.0d0, 400.0d0, 400.0d0, &         !46-50\n                                 400.0d0, 400.0d0, 1.0d0, 1.0d0, 100000.0d0, &          !51-55\n                                 1.0d0, 100.0d0, 100000.0d0, 100000.0d0, 400.0d0, &     !56-60\n                                 1.0d0, 400.0d0, 1.0d0, 10000.0d0, 100000000.0d0, &     !61-65\n                                 100.0d0, 10.0d0, 1.0d0, 1.0D+6, 100000.0d0, &          !66-70\n                                 5.0d0, 5.0d0, 5.0d0, 5.0d0, 5.0d0, &                   !71-76\n                                 5.0d0, 5.0d0, 5.0d0, 1000.0d0, 1000.0d0, &             !76-80\n                                 1000.0d0, 1000.0d0, 5000.0d0, 5000.0d0, 1000.0d0, &    !81-85\n                                 1000.0d0, 1000.0d0, 1000.0d0, 1000.0d0, 1.0D+6, &      !86-90\n                                 30000.0d0, 1.0d0, 1.0d0, 1.0d0, 400.0d0, &             !91-95\n                                 1.0d0, 1.0d0, 100.0d0,&                                !96-98\n   ! NBNB Check these values\n                                 1.0d0, 1.0d4, 1.0d0, &                                 !99-101\n                                 1.0d5, 1.0d4, 1.0d8, &                                 !102-104\n                                 1.0D2, 1.0D2, 1.0d5, &                                 !105-107\n                                 300.0d0, 1.0d4, 1.0d2, &                               !108-110\n                                 1.0d5, 0.0d0, 1.0d3, &                                 !111-113\n                                 1.0d6, 1.d5, 1.d5]                                     !114-116\n\n   ! Loop through and calculate missing/fill/min/max values that will be placed\n   ! into the NetCDF attributes after scale_factor/add_offset are applied.\n   do i=1,numLdasVars\n      if (ldasOutDict%scaleFactor(i) .le. 1. .and. ldasOutDict%scaleFactor(i) .gt. 0.) then\n        ldasOutDict%fillComp(i) = &\n           nint((ldasOutDict%fillReal(i)     + ldasOutDict%addOffset(i)), 4) * &\n           nint(one_dbl / ldasOutDict%scaleFactor(i), 4)\n        ldasOutDict%missingComp(i) = &\n           nint((ldasOutDict%missingReal(i)  + ldasOutDict%addOffset(i)), 4) * &\n           nint(one_dbl / ldasOutDict%scaleFactor(i), 4)\n        ldasOutDict%validMinComp(i) = &\n           nint((ldasOutDict%validMinDbl(i) + ldasOutDict%addOffset(i)) * &\n                nint(one_dbl / ldasOutDict%scaleFactor(i), 4), 4)\n        ldasOutDict%validMaxComp(i) = &\n           nint((ldasOutDict%validMaxDbl(i) + ldasOutDict%addOffset(i)) * &\n                nint(one_dbl / ldasOutDict%scaleFactor(i), 4), 4)\n      else if (ldasOutDict%scaleFactor(i) .gt. 1.) then\n        ldasOutDict%fillComp(i) = &\n           nint( (ldasOutDict%fillReal(i) + ldasOutDict%addOffset(i)) * &\n                 (one_dbl / ldasOutDict%scaleFactor(i)), 4 )\n        ldasOutDict%missingComp(i) = &\n           nint( (ldasOutDict%missingReal(i) + ldasOutDict%addOffset(i)) * &\n                 (one_dbl / ldasOutDict%scaleFactor(i)), 4 )\n        ldasOutDict%validMinComp(i) = &\n           nint( (ldasOutDict%validMinDbl(i) + ldasOutDict%addOffset(i)) * &\n                 (one_dbl / ldasOutDict%scaleFactor(i)), 4 )\n        ldasOutDict%validMaxComp(i) = &\n           nint( (ldasOutDict%validMaxDbl(i) + ldasOutDict%addOffset(i)) * &\n                 (one_dbl / ldasOutDict%scaleFactor(i)), 4 )\n      end if\n   end do\n\nend subroutine initLdasDict\n\nsubroutine initRtDomainDict(rtDomainDict,procId,diagFlag)\n  use config_base, only: nlst\n  use netcdf\n  implicit none\n\n   type(rtDomainMeta), intent(inout) :: rtDomainDict\n   integer, intent(inout) :: procId,diagFlag\n   integer :: ftnMeta,projVarId,xVarId,yVarId,ftnGeo\n   integer :: xDimId,numColLand,numColHydro\n   real :: resLand,resHydro,aggFactor\n   integer :: iret\n   integer :: crsRealAttCnt,xRealAttCnt,yRealAttCnt\n   integer :: crsCharAttCnt,xCharAttCnt,yCharAttCnt\n   integer :: i, nCrsAtts,nxAtts,nyAtts\n   integer :: charFlag\n   integer :: floatFlag\n   character(len=512) :: tmpAttName\n   integer :: xtypeTmp\n   integer :: tmpLen\n   ! RT_DOMAIN files\n\n   rtDomainDict%numSoilLayers = nlst(1)%nsoil\n\n   rtDomainDict%modelNdv = -9.E15\n\n   ! First establish global attributes.\n   rtDomainDict%title = \"OUTPUT FROM \" // trim(get_model_version())\n   rtDomainDict%initTime = \"1970-01-01_00:00:00\" ! This will be calculated in I/O code.\n   rtDomainDict%validTime = \"1970-01-01_00:00:00\" ! This will be calculated in I/O code.\n   rtDomainDict%decimation = 1\n   rtDomainDict%conventions = \"CF-1.6\"\n\n   ! Next establish time attributes\n   rtDomainDict%timeLName = \"valid output time\"\n   rtDomainDict%timeUnits = \"minutes since 1970-01-01 00:00:00 UTC\"\n   rtDomainDict%timeStName = \"time\"\n   rtDomainDict%rTimeLName = \"model initialization time\"\n   rtDomainDict%rTimeUnits = \"minutes since 1970-01-01 00:00:00 UTC\"\n   rtDomainDict%rTimeStName = \"forecast_reference_time\"\n\n   crsRealAttCnt = 0\n   crsCharAttCnt = 0\n   xRealAttCnt = 0\n   xCharAttCnt = 0\n   yRealAttCnt = 0\n   yCharAttCnt = 0\n\n   ! Pull spatial metadata information about the modeling domain from the\n   ! Fulldom file.\n   if(procId .eq. 0) then\n      iret = nf90_open(trim(nlst(1)%geo_finegrid_flnm),NF90_NOWRITE,ncid=ftnMeta)\n      if(iret .ne. 0) then\n         ! Spatial metadata file not found for hydro grid.\n         call postDiagMsg(diagFlag,'WARNING: Unable to open Fulldom metadata file. No crs variable or attributes will be created.')\n         rtDomainDict%nCrsCharAtts = 0\n         rtDomainDict%nCrsRealAtts = 0\n         rtDomainDict%nxCharAtts = 0\n         rtDomainDict%nxRealAtts = 0\n         rtDomainDict%nyCharAtts = 0\n         rtDomainDict%nyRealAtts = 0\n         rtDomainDict%proj4 = ''\n      else\n         iret = nf90_get_att(ftnMeta,NF90_GLOBAL,'proj4',rtDomainDict%proj4)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to find proj4 global attribute. Defaulting to blank string.')\n            rtDomainDict%proj4 = ''\n         endif\n         charFlag = 0\n         floatFlag = 0\n         ! Find the crs variable and pull out the attributes, their names, and\n         ! their values. This will be translated to output files.\n         iret = nf90_inq_varid(ftnMeta,'crs',projVarId)\n         ! For now we are going to allow the code to move forward without\n         ! finding this variable. In the future, we will probably restrict the\n         ! code to ensure things are more seamless.\n\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the crs variable. No crs variable or attributes will be created.')\n            rtDomainDict%nCrsCharAtts = 0\n            rtDomainDict%nCrsRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,projVarId,nAtts=nCrsAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find crs number of attributes')\n            do i =1,nCrsAtts\n               iret = nf90_inq_attname(ftnMeta,projVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from crs variable.')\n               iret = nf90_inquire_attribute(ftnMeta,projVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from crs variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  rtDomainDict%crsCharAttNames(crsCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,projVarId,trim(tmpAttName),rtDomainDict%crsCharAttVals(crsCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull crs attributes')\n                  crsCharAttCnt = crsCharAttCnt + 1\n               else\n                  rtDomainDict%crsFloatAttNames(crsRealAttCnt+1) = trim(tmpAttName)\n                  rtDomainDict%crsRealAttLen(crsRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,projVarId,trim(tmpAttName),rtDomainDict%crsRealAttVals(crsRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull crs attributes')\n                  crsRealAttCnt = crsRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            rtDomainDict%nCrsRealAtts = crsRealAttCnt\n            rtDomainDict%nCrsCharAtts = crsCharAttCnt\n\n         endif\n\n         ! Next pull the attributes from the x/y dimensions\n         charFlag = 0\n         floatFlag = 0\n         iret = nf90_inq_varid(ftnMeta,'x',xVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the x variable. No x variable or attributes will be created.')\n            rtDomainDict%nxCharAtts = 0\n            rtDomainDict%nxRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,xVarId,nAtts=nxAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find x number of attributes')\n            do i =1,nxAtts\n               iret = nf90_inq_attname(ftnMeta,xVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from x variable.')\n               iret = nf90_inquire_attribute(ftnMeta,xVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from x variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  rtDomainDict%xCharAttNames(xCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,xVarId,trim(tmpAttName),rtDomainDict%xCharAttVals(xCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull x attributes')\n                  xCharAttCnt = xCharAttCnt + 1\n               else\n                  rtDomainDict%xFloatAttNames(xRealAttCnt+1) = trim(tmpAttName)\n                  rtDomainDict%xRealAttLen(xRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,xVarId,trim(tmpAttName),rtDomainDict%xRealAttVals(xRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull x attributes')\n                  xRealAttCnt = xRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            rtDomainDict%nxRealAtts = xRealAttCnt\n            rtDomainDict%nxCharAtts = xCharAttCnt\n\n         endif\n\n         charFlag = 0\n         floatFlag = 0\n         iret = nf90_inq_varid(ftnMeta,'y',yVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the y variable. No y variable or attributes will be created.')\n            rtDomainDict%nyCharAtts = 0\n            rtDomainDict%nyRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,yVarId,nAtts=nyAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find y number of attributes')\n            do i =1,nyAtts\n               iret = nf90_inq_attname(ftnMeta,yVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from y variable.')\n               iret = nf90_inquire_attribute(ftnMeta,yVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from y variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  rtDomainDict%yCharAttNames(yCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,yVarId,trim(tmpAttName),rtDomainDict%yCharAttVals(yCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull y attributes')\n                  yCharAttCnt = yCharAttCnt + 1\n               else\n                  rtDomainDict%yFloatAttNames(yRealAttCnt+1) = trim(tmpAttName)\n                  rtDomainDict%yRealAttLen(yRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,yVarId,trim(tmpAttName),rtDomainDict%yRealAttVals(yRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull y attributes')\n                  yRealAttCnt = yRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            rtDomainDict%nyRealAtts = yRealAttCnt\n            rtDomainDict%nyCharAtts = yCharAttCnt\n         endif\n         ! Close the file\n         iret = nf90_close(ftnMeta)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close Fulldom file.')\n      endif\n\n      ! Next get the number of columns on the land grid. This will be used to\n      ! calculate the resolution of the routing grid in meters and aggfactor.\n      iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnGeo)\n      if(iret .ne. 0) then\n         call postDiagMsg(diagFlag,'WARNING: Unable to open LAND Spatial Metadata file. Defaulting to missing values.')\n         numColLand = -9999\n         resLand = -9999\n      else\n         iret = nf90_inq_dimid(ftnGeo,'x',xDimId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find x dimension in LAND spatial Metadata file')\n         iret = nf90_inquire_dimension(ftnGeo,xDimId,len=numColLand)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to retrieve number of columns in the LAND spatial metadata file')\n         iret = nf90_inq_varid(ftnGeo,'x',xVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find x variable in LAND spatial metadata file')\n         iret = nf90_get_att(ftnGeo,xVarId,'resolution',resLand)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to get x resolution in LAND spatial metadata file')\n         iret = nf90_close(ftnGeo)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close the LAND spatial metadata file')\n      endif\n\n      ! Next get the number of columns on the high-resolution routing grid.\n      ! This will be used to calculate the resolution of the routing grid in\n      ! meters.\n      iret = nf90_open(trim(nlst(1)%geo_finegrid_flnm),NF90_NOWRITE,ncid=ftnGeo)\n      if(iret .ne. 0) then\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to open Fulldom file')\n      else\n         iret = nf90_inq_dimid(ftnGeo,'x',xDimId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find x dimension in Fulldom file')\n         iret = nf90_inquire_dimension(ftnGeo,xDimId,len=numColHydro)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to retrieve number of columns in the Fulldom file')\n         iret = nf90_close(ftnGeo)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close the Fulldom file')\n      endif\n\n      ! Calculate the aggregation factor and resolution of the hydro routing\n      ! grid.\n      if(numColLand .ne. -9999) then\n         aggFactor = float(numColHydro/numColLand)\n         resHydro = resLand/aggFactor\n      else\n         resHydro = -9999\n      endif\n\n      rtDomainDict%xRes = resHydro\n      rtDomainDict%yRes = resHydro\n\n   endif\n\n   rtDomainDict%varNames(:) = [character(len=64) :: \"zwattablrt\",\"sfcheadsubrt\",\"QSTRMVOLRT\",&\n                               \"QBDRYRT\",\"SOIL_M\"]\n   rtDomainDict%longName(:) = [character(len=64) :: \"depth to saturation, rounded to highest saturated layer\",&\n                               \"surface head\",\"channel inflow\",&\n                               \"accumulated value of the boundary flux, + into domain - out of domain\",&\n                               \"volumetric soil moisture\"]\n   rtDomainDict%units(:) = [character(len=64) :: \"m\",\"mm\",\"mm\",\"mm\",\"m3 m-3\"]\n   rtDomainDict%scaleFactor(:) = [0.1,1.0,1.0,1.0,0.01]\n   rtDomainDict%addOffset(:) = [0.0,0.0,0.0,0.0,0.0]\n   rtDomainDict%outFlag(:) = [0,0,0,0,0]\n   rtDomainDict%timeZeroFlag(:) = [1,1,1,1,1]\n   rtDomainDict%missingReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0,-9999.0]\n   rtDomainDict%fillReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0,-9999.0]\n   rtDomainDict%validMinDbl(:) = [0.0d0, 0.0d0, 0.0d0, -1000000.0d0, 0.0d0]\n   rtDomainDict%validMaxDbl(:) = [100.0d0, 1000000.0d0, 1000000.0d0, 1000000.0d0, 100.0d0]\n\n   ! Loop through and calculate missing/fill/min/max values that will be placed\n   ! into the NetCDF attributes after scale_factor/add_offset are applied.\n   do i=1,numRtDomainVars\n      rtDomainDict%fillComp(i) = &\n           nint((rtDomainDict%fillReal(i)     + rtDomainDict%addOffset(i)), 8) * &\n           nint(one_dbl / rtDomainDict%scaleFactor(i), 8)\n      rtDomainDict%missingComp(i) = &\n           nint((rtDomainDict%missingReal(i)  + rtDomainDict%addOffset(i)), 8) * &\n           nint(one_dbl / rtDomainDict%scaleFactor(i), 8)\n      rtDomainDict%validMinComp(i) = &\n           nint((rtDomainDict%validMinDbl(i) + rtDomainDict%addOffset(i)) * &\n                nint(one_dbl / rtDomainDict%scaleFactor(i), 8), 8)\n      rtDomainDict%validMaxComp(i) = &\n           nint((rtDomainDict%validMaxDbl(i) + rtDomainDict%addOffset(i)) * &\n                nint(one_dbl / rtDomainDict%scaleFactor(i), 8), 8)\n   end do\n\nend subroutine initRtDomainDict\n\nsubroutine initLakeDict(lakeOutDict,procId,diagFlag)\n  use config_base, only: nlst\n  use netcdf\n  implicit none\n\n   type(lakeMeta), intent(inout) :: lakeOutDict\n   integer, intent(inout) :: diagFlag\n   integer, intent(inout) :: procId\n\n   ! Local variables\n   integer :: ftnMeta,iret\n   integer :: projVarId\n\n   lakeOutDict%modelNdv = -9.E15\n   ! LAKE FILES\n   ! NOTE !!!!! If you see PLC, this means OWP has no desire to output these,\n   !            which means meta-data standards have yet to be determined\n   !            for these variables. Fill in if it's desired to output....\n   ! First establish global attributes for the channel output files\n   lakeOutDict%title = \"OUTPUT FROM \" // trim(get_model_version())\n   lakeOutDict%fType = 'timeSeries'\n   lakeOutDict%initTime = '1970-01-01_00:00:00' ! This will be calculated in I/O code\n   lakeOutDict%validTime = '1970-01-01_00:00:00' ! This will be calculated in I/O code\n   lakeOutDict%lakeDim = 'lake_id'\n   lakeOutDict%cdm = 'PLACEHOLDER'\n   lakeOutDict%conventions = 'CF-1.6'\n\n   ! Pull spatial metadata information about the modeling domain from the land\n   ! spatial metadata file.\n   if(procId .eq. 0) then\n      iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnMeta)\n      if(iret .ne. 0) then\n         ! Spatial metadata file not found for land grid.\n         call postDiagMsg(diagFlag,'WARNING: Unable to open LAND spatial metadata file.')\n         lakeOutDict%proj4 = ''\n         lakeOutDict%esri = ''\n      else\n         ! First pull metadata on coordinate system.\n         iret = nf90_inq_varid(ftnMeta,'crs',projVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to find crs in LAND spatial metadata file')\n            lakeOutDict%proj4 = ''\n            lakeOutDict%esri = ''\n         else\n            iret = nf90_get_att(ftnMeta,projVarId,'esri_pe_string',lakeOutDict%esri)\n            if(iret .ne. 0) then\n               call postDiagMsg(diagFlag,'WARNING: Unable to find esri_pe_string in LAND spatial metadata file.')\n               lakeOutDict%esri = ''\n            endif\n            iret = nf90_get_att(ftnMeta,NF90_GLOBAL,'proj4',lakeOutDict%proj4)\n            ! We are going to put a relaxed constraint on the proj4 string.\n            if(iret .ne. 0) then\n               call postDiagMsg(diagFlag,'WARNING: proj4 string not found. Defaulting to blank string.')\n               lakeOutDict%proj4 = ''\n            endif\n         endif\n         ! Close the file\n         iret = nf90_close(ftnMeta)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAND spatial metadata file.')\n      endif\n   endif\n\n   ! Next establish time attribues\n   lakeOutDict%timeLName = 'valid output time'\n   lakeOutDict%timeUnits = 'minutes since 1970-01-01 00:00:00 UTC'\n   lakeOutDict%timeStName = 'time'\n   lakeOutDict%rTimeLName = 'model initialization time'\n   lakeOutDict%rTimeStName = 'forecast_reference_time'\n   lakeOutDict%rTimeUnits = 'minutes since 1970-01-01 00:00:00 UTC'\n\n   ! Establish elevation variable attributes\n   lakeOutDict%elevLName = \"Water Surface Elevation\"\n   lakeOutDict%elevUnits = \"m\" ! meters\n   lakeOutDict%elevComment = \"If reservoir_type = 4, \" &\n       // \"water_sfc_elev is invalid because this value corresponds only to level pool\"\n\n   ! Establish feature_id attributes\n   lakeOutDict%featureIdLName = \"Lake ComID\"\n   lakeOutDict%featureIdComment = \"ComID from NHDPlusV2 waterbody layer\"\n   lakeOutDict%cfRole = 'timeseries_id'\n\n   ! Establish reservoir_type attributes\n   lakeOutDict%reservoirTypeLName = \"reservoir_type\"\n   lakeOutDict%reservoirTypeFlagValues = [1,2,3,4]\n   lakeOutDict%reservoirTypeFlagMeanings = \"Level_pool USGS-persistence USACE-persistence RFC-forecasts\"\n\n   ! Establish reservoir_assimilated_value attributes\n   lakeOutDict%reservoirAssimilatedValueLName = \"reservoir_assimilated_value\"\n   lakeOutDict%reservoirAssimilatedValueUnits = \"m3 s-1\"\n\n   ! Establish reservoir_assimilated_source_file attributes\n   lakeOutDict%reservoirAssimilatedSourceFileLName= \"reservoir_assimilated_source_file\"\n\n  ! Esatablish lat/lon attributes\n   lakeOutDict%latLName = \"Lake latitude\"\n   lakeOutDict%latUnits = \"degrees_north\"\n   lakeOutDict%latStName = \"latitude\"\n   lakeOutDict%lonLName = \"Lake longitude\"\n   lakeOutDict%lonUnits = \"degrees_east\"\n   lakeOutDict%lonStName = \"longitude\"\n\n   lakeOutDict%varNames(:) = [character(len=64) :: 'inflow','outflow']\n   lakeOutDict%longName(:) = [character(len=64) :: 'Lake Inflow','Lake Outflow']\n   lakeOutDict%units(:) = [character(len=64) :: 'm3 s-1','m3 s-1']\n   lakeOutDict%coordNames(:) = [character(len=64) :: 'latitude longitude','latitude longitude']\n   lakeOutDict%scaleFactor(:) = [0.01,0.01]\n   lakeOutDict%addOffset(:) = [0.0,0.0]\n   lakeOutDict%outFlag(:) = [0,0]\n   lakeOutDict%timeZeroFlag(:) = [1,1]\n   lakeOutDict%fillReal(:) = [-9999.0,-9999.0]\n   lakeOutDict%missingReal(:) = [-9999.0,-9999.0]\n   lakeOutDict%validMinDbl(:) = [-10000.0d0, -10000.0d0]\n   lakeOutDict%validMaxDbl(:) = [10000.0d0, 10000.0d0]\n\n   ! Loop through and calculate missing/fill/min/max values that will be placed\n   ! into the NetCDF attributes after scale_factor/add_offset are applied.\n   do i=1,numLakeVars\n      lakeOutDict%fillComp(i) = &\n           nint((lakeOutDict%fillReal(i)     + lakeOutDict%addOffset(i)), 8) * &\n           nint(one_dbl / lakeOutDict%scaleFactor(i), 8)\n      lakeOutDict%missingComp(i) = &\n           nint((lakeOutDict%missingReal(i)  + lakeOutDict%addOffset(i)), 8) * &\n           nint(one_dbl / lakeOutDict%scaleFactor(i), 8)\n      lakeOutDict%validMinComp(i) = &\n           nint((lakeOutDict%validMinDbl(i) + lakeOutDict%addOffset(i)) * &\n                nint(one_dbl / lakeOutDict%scaleFactor(i), 8), 8)\n      lakeOutDict%validMaxComp(i) = &\n           nint((lakeOutDict%validMaxDbl(i) + lakeOutDict%addOffset(i)) * &\n                nint(one_dbl / lakeOutDict%scaleFactor(i), 8), 8)\n   end do\n\nend subroutine initLakeDict\n\nsubroutine initChrtGrdDict(chrtGrdDict,procId,diagFlag)\n  use config_base, only: nlst\n  use netcdf\n  implicit none\n\n   type(chrtGrdMeta), intent(inout) :: chrtGrdDict\n   integer, intent(inout) :: procId,diagFlag\n   integer :: ftnMeta,projVarId,xVarId,yVarId,ftnGeo\n   integer :: xDimId,numColLand,numColHydro\n   real :: resLand,resHydro,aggFactor\n   integer :: iret\n   integer :: crsRealAttCnt,xRealAttCnt,yRealAttCnt\n   integer :: crsCharAttCnt,xCharAttCnt,yCharAttCnt\n   integer :: i, nCrsAtts,nxAtts,nyAtts\n   integer :: charFlag\n   integer :: floatFlag\n   character(len=512) :: tmpAttName\n   integer :: xtypeTmp\n   integer :: tmpLen\n   !CHRTOUT_GRID files\n\n   chrtGrdDict%modelNdv = -9.E15\n\n   ! First establish global attributes.\n   chrtGrdDict%title = \"OUTPUT FROM \" // trim(get_model_version())\n   chrtGrdDict%initTime = \"1970-01-01_00:00:00\" ! This will be calculated in I/O code.\n   chrtGrdDict%validTime = \"1970-01-01_00:00:00\" ! This will be calculated in I/O code.\n   chrtGrdDict%decimation = 1\n   chrtGrdDict%conventions = \"CF-1.6\"\n\n   ! Next establish time attributes\n   chrtGrdDict%timeLName = \"valid output time\"\n   chrtGrdDict%timeUnits = \"minutes since 1970-01-01 00:00:00 UTC\"\n   chrtGrdDict%timeStName = \"time\"\n   chrtGrdDict%rTimeLName = \"model initialization time\"\n   chrtGrdDict%rTimeUnits = \"minutes since 1970-01-01 00:00:00 UTC\"\n   chrtGrdDict%rTimeStName = \"forecast_reference_time\"\n\n   crsRealAttCnt = 0\n   crsCharAttCnt = 0\n   xRealAttCnt = 0\n   xCharAttCnt = 0\n   yRealAttCnt = 0\n   yCharAttCnt = 0\n\n   ! Pull spatial metadata information about the modeling domain from the\n   ! Fulldom file.\n   if(procId .eq. 0) then\n      iret = nf90_open(trim(nlst(1)%geo_finegrid_flnm),NF90_NOWRITE,ncid=ftnMeta)\n      if(iret .ne. 0) then\n         ! Spatial metadata file not found for hydro grid.\n         call postDiagMsg(diagFlag,'WARNING: Unable to open Fulldom file. No crs variable or attributes will be created.')\n         chrtGrdDict%nCrsCharAtts = 0\n         chrtGrdDict%nCrsRealAtts = 0\n         chrtGrdDict%nxCharAtts = 0\n         chrtGrdDict%nxRealAtts = 0\n         chrtGrdDict%nyCharAtts = 0\n         chrtGrdDict%nyRealAtts = 0\n         chrtGrdDict%proj4 = ''\n      else\n         iret = nf90_get_att(ftnMeta,NF90_GLOBAL,'proj4',chrtGrdDict%proj4)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to find proj4 global attribute. Defaulting to blank string.')\n            chrtGrdDict%proj4 = ''\n         endif\n         charFlag = 0\n         floatFlag = 0\n         ! Find the crs variable and pull out the attributes, their names, and\n         ! their values. This will be translated to output files.\n         iret = nf90_inq_varid(ftnMeta,'crs',projVarId)\n         ! For now we are going to allow the code to move forward without\n         ! finding this variable. In the future, we will probably restrict the\n         ! code to ensure things are more seamless.\n\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the crs variable. No crs variable or attributes will be created.')\n            chrtGrdDict%nCrsCharAtts = 0\n            chrtGrdDict%nCrsRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,projVarId,nAtts=nCrsAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find crs number of attributes')\n            do i =1,nCrsAtts\n               iret = nf90_inq_attname(ftnMeta,projVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from crs variable.')\n               iret = nf90_inquire_attribute(ftnMeta,projVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from crs variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  chrtGrdDict%crsCharAttNames(crsCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,projVarId,trim(tmpAttName),chrtGrdDict%crsCharAttVals(crsCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull crs attributes')\n                  crsCharAttCnt = crsCharAttCnt + 1\n               else\n                  chrtGrdDict%crsFloatAttNames(crsRealAttCnt+1) = trim(tmpAttName)\n                  chrtGrdDict%crsRealAttLen(crsRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,projVarId,trim(tmpAttName),chrtGrdDict%crsRealAttVals(crsRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull crs attributes')\n                  crsRealAttCnt = crsRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            chrtGrdDict%nCrsRealAtts = crsRealAttCnt\n            chrtGrdDict%nCrsCharAtts = crsCharAttCnt\n         endif\n\n         ! Next pull the attributes from the x/y dimensions\n         charFlag = 0\n         floatFlag = 0\n         iret = nf90_inq_varid(ftnMeta,'x',xVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the x variable. No x variable or attributes will be created.')\n            chrtGrdDict%nxCharAtts = 0\n            chrtGrdDict%nxRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,xVarId,nAtts=nxAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find x number of attributes')\n            do i =1,nxAtts\n               iret = nf90_inq_attname(ftnMeta,xVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from x variable.')\n               iret = nf90_inquire_attribute(ftnMeta,xVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from x variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  chrtGrdDict%xCharAttNames(xCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,xVarId,trim(tmpAttName),chrtGrdDict%xCharAttVals(xCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull x attributes')\n                  xCharAttCnt = xCharAttCnt + 1\n               else\n                  chrtGrdDict%xFloatAttNames(xRealAttCnt+1) = trim(tmpAttName)\n                  chrtGrdDict%xRealAttLen(xRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,xVarId,trim(tmpAttName),chrtGrdDict%xRealAttVals(xRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull x attributes')\n                  xRealAttCnt = xRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            chrtGrdDict%nxRealAtts = xRealAttCnt\n            chrtGrdDict%nxCharAtts = xCharAttCnt\n         endif\n\n         charFlag = 0\n         floatFlag = 0\n         iret = nf90_inq_varid(ftnMeta,'y',yVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the y variable. No y variable or attributes will be created.')\n            chrtGrdDict%nyCharAtts = 0\n            chrtGrdDict%nyRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,yVarId,nAtts=nyAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find y number of attributes')\n            do i =1,nyAtts\n               iret = nf90_inq_attname(ftnMeta,yVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from y variable.')\n               iret = nf90_inquire_attribute(ftnMeta,yVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from y variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  chrtGrdDict%yCharAttNames(yCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,yVarId,trim(tmpAttName),chrtGrdDict%yCharAttVals(yCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull y attributes')\n                  yCharAttCnt = yCharAttCnt + 1\n               else\n                  chrtGrdDict%yFloatAttNames(yRealAttCnt+1) = trim(tmpAttName)\n                  chrtGrdDict%yRealAttLen(yRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,yVarId,trim(tmpAttName),chrtGrdDict%yRealAttVals(yRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull y attributes')\n                  yRealAttCnt = yRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            chrtGrdDict%nyRealAtts = yRealAttCnt\n            chrtGrdDict%nyCharAtts = yCharAttCnt\n         endif\n         ! Close the file\n         iret = nf90_close(ftnMeta)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAND spatial metadata file.')\n\n      endif\n\n      ! Next get the number of columns on the land grid. This will be used to\n      ! calculate the resolution of the routing grid in meters and aggfactor.\n      iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnGeo)\n      if(iret .ne. 0) then\n         call postDiagMsg(diagFlag,'WARNING: Unable to open LAND Spatial Metadata file. Defaulting to missing values.')\n         numColLand = -9999\n         resLand = -9999\n      else\n         iret = nf90_inq_dimid(ftnGeo,'x',xDimId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find x dimension in LAND spatial Metadata file')\n         iret = nf90_inquire_dimension(ftnGeo,xDimId,len=numColLand)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to retrieve number of columns in the LAND spatial metadata file')\n         iret = nf90_inq_varid(ftnGeo,'x',xVarId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find x variable in LAND spatial metadata file')\n         iret = nf90_get_att(ftnGeo,xVarId,'resolution',resLand)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to get x resolution in LAND spatial metadata file')\n         iret = nf90_close(ftnGeo)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close the LAND spatial metadata file')\n      endif\n\n      ! Next get the number of columns on the high-resolution routing grid.\n      ! This will be used to calculate the resolution of the routing grid in\n      ! meters.\n      iret = nf90_open(trim(nlst(1)%geo_finegrid_flnm),NF90_NOWRITE,ncid=ftnGeo)\n      if(iret .ne. 0) then\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to open Fulldom file')\n      else\n         iret = nf90_inq_dimid(ftnGeo,'x',xDimId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find x dimension in Fulldom file')\n         iret = nf90_inquire_dimension(ftnGeo,xDimId,len=numColHydro)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to retrieve number of columns in the Fulldom file')\n         iret = nf90_close(ftnGeo)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close the Fulldom file')\n      endif\n\n      ! Calculate the aggregation factor and resolution of the hydro routing\n      ! grid.\n      if(numColLand .ne. -9999) then\n         aggFactor = float(numColHydro/numColLand)\n         resHydro = resLand/aggFactor\n      else\n         resHydro = -9999\n      endif\n\n      chrtGrdDict%xRes = resHydro\n      chrtGrdDict%yRes = resHydro\n\n   endif\n\n   chrtGrdDict%varNames(:) = [character(len=64) :: \"streamflow\"]\n   chrtGrdDict%longName(:) = [character(len=64) :: \"River Flow\"]\n   chrtGrdDict%units(:) = [character(len=64) :: \"m3 s-1\"]\n   chrtGrdDict%scaleFactor(:) = [0.1]\n   chrtGrdDict%addOffset(:) = [0.0]\n   chrtGrdDict%outFlag(:) = [0]\n   chrtGrdDict%timeZeroFlag(:) = [1]\n   chrtGrdDict%missingReal(:) = [-9999.0]\n   chrtGrdDict%fillReal(:) = [-9999.0]\n   chrtGrdDict%validMinDbl(:) = [0.0d0]\n   chrtGrdDict%validMaxDbl(:) = [50000.0d0]\n\n   ! Loop through and calculate missing/fill/min/max values that will be placed\n   ! into the NetCDF attributes after scale_factor/add_offset are applied.\n   do i=1,numChGrdVars\n      chrtGrdDict%fillComp(i) = &\n           nint((chrtGrdDict%fillReal(i)     + chrtGrdDict%addOffset(i)), 8) * &\n           nint(one_dbl / chrtGrdDict%scaleFactor(i), 8)\n      chrtGrdDict%missingComp(i) = &\n           nint((chrtGrdDict%missingReal(i)  + chrtGrdDict%addOffset(i)), 8) * &\n           nint(one_dbl / chrtGrdDict%scaleFactor(i), 8)\n      chrtGrdDict%validMinComp(i) = &\n           nint((chrtGrdDict%validMinDbl(i) + chrtGrdDict%addOffset(i)) * &\n                nint(one_dbl / chrtGrdDict%scaleFactor(i), 8), 8)\n      chrtGrdDict%validMaxComp(i) = &\n           nint((chrtGrdDict%validMaxDbl(i) + chrtGrdDict%addOffset(i)) * &\n                nint(one_dbl / chrtGrdDict%scaleFactor(i), 8), 8)\n   end do\n\nend subroutine initChrtGrdDict\n\nsubroutine initLsmOutDict(lsmOutDict,procId,diagFlag)\n  use config_base, only: nlst\n  use netcdf\n  implicit none\n\n   type(lsmMeta), intent(inout) :: lsmOutDict\n   integer, intent(inout) :: procId\n   integer, intent(inout) :: diagFlag\n   integer :: ftnMeta,projVarId,xVarId,yVarId\n   integer :: iret\n   integer :: crsRealAttCnt,xRealAttCnt,yRealAttCnt\n   integer :: crsCharAttCnt,xCharAttCnt,yCharAttCnt\n   integer :: i, nCrsAtts,nxAtts,nyAtts\n   integer :: charFlag\n   integer :: floatFlag\n   character(len=512) :: tmpAttName\n   integer :: xtypeTmp\n   integer :: tmpLen\n   !LSMOUT files\n\n   lsmOutDict%numSoilLayers = nlst(1)%nsoil\n   lsmOutDict%act_lev = nlst(1)%act_lev\n\n   lsmOutDict%modelNdv = 9.9692099683868690E36\n   lsmOutDict%modelNdvInt = -2147483647\n\n   ! First establish global attributes.\n   lsmOutDict%title = \"OUTPUT FROM \" // trim(get_model_version())\n   lsmOutDict%initTime = \"1970-01-01_00:00:00\" ! This will be calculated in I/O code.\n   lsmOutDict%validTime = \"1970-01-01_00:00:00\" ! This will be calculated in I/O code.\n   lsmOutDict%conventions = \"CF-1.6\"\n\n   ! Next establish time attributes\n   lsmOutDict%timeLName = \"valid output time\"\n   lsmOutDict%timeUnits = \"minutes since 1970-01-01 00:00:00 UTC\"\n   lsmOutDict%timeStName = \"time\"\n   lsmOutDict%rTimeLName = \"model initialization time\"\n   lsmOutDict%rTimeUnits = \"minutes since 1970-01-01 00:00:00 UTC\"\n   lsmOutDict%rTimeStName = \"forecast_reference_time\"\n\n   crsRealAttCnt = 0\n   crsCharAttCnt = 0\n   xRealAttCnt = 0\n   xCharAttCnt = 0\n   yRealAttCnt = 0\n   yCharAttCnt = 0\n\n   ! Pull spatial metadata information about the modeling domain from the land\n   ! spatial metadata file.\n   if(procId .eq. 0) then\n      iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnMeta)\n      if(iret .ne. 0) then\n         ! Spatial metadata file not found for land grid.\n         call postDiagMsg(diagFlag,'WARNING: Unable to open LAND spatial metadata file. No crs variable or attributes will be created.')\n         lsmOutDict%nCrsCharAtts = 0\n         lsmOutDict%nCrsRealAtts = 0\n         lsmOutDict%nxCharAtts = 0\n         lsmOutDict%nxRealAtts = 0\n         lsmOutDict%nyCharAtts = 0\n         lsmOutDict%nyRealAtts = 0\n         lsmOutDict%proj4 = ''\n      else\n         iret = nf90_get_att(ftnMeta,NF90_GLOBAL,'proj4',lsmOutDict%proj4)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to find proj4 global attribute. Defaulting to blank string.')\n            lsmOutDict%proj4 = ''\n         endif\n         charFlag = 0\n         floatFlag = 0\n         ! Find the crs variable and pull out the attributes, their names, and\n         ! their values. This will be translated to output files.\n         iret = nf90_inq_varid(ftnMeta,'crs',projVarId)\n         ! For now we are going to allow the code to move forward without\n         ! finding this variable. In the future, we will probably restrict the\n         ! code to ensure things are more seamless.\n\n         ! code to ensure things are more seamless.\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the crs variable. No crs variable or attributes will be created.')\n            lsmOutDict%nCrsCharAtts = 0\n            lsmOutDict%nCrsRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,projVarId,nAtts=nCrsAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find crs number of attributes')\n            do i =1,nCrsAtts\n               iret = nf90_inq_attname(ftnMeta,projVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from crs variable.')\n               iret = nf90_inquire_attribute(ftnMeta,projVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from crs variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  lsmOutDict%crsCharAttNames(crsCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,projVarId,trim(tmpAttName),lsmOutDict%crsCharAttVals(crsCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull crs attributes')\n                  crsCharAttCnt = crsCharAttCnt + 1\n               else\n                  lsmOutDict%crsFloatAttNames(crsRealAttCnt+1) = trim(tmpAttName)\n                  lsmOutDict%crsRealAttLen(crsRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,projVarId,trim(tmpAttName),lsmOutDict%crsRealAttVals(crsRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull crs attributes')\n                  crsRealAttCnt = crsRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            lsmOutDict%nCrsRealAtts = crsRealAttCnt\n            lsmOutDict%nCrsCharAtts = crsCharAttCnt\n\n         endif\n\n         ! Next pull the attributes from the x/y dimensions\n         charFlag = 0\n         floatFlag = 0\n         iret = nf90_inq_varid(ftnMeta,'x',xVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the x variable. No x variable or attributes will be created.')\n            lsmOutDict%nxCharAtts = 0\n            lsmOutDict%nxRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,xVarId,nAtts=nxAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find x number of attributes')\n            do i =1,nxAtts\n               iret = nf90_inq_attname(ftnMeta,xVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from x variable.')\n               iret = nf90_inquire_attribute(ftnMeta,xVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from x variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  lsmOutDict%xCharAttNames(xCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,xVarId,trim(tmpAttName),lsmOutDict%xCharAttVals(xCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull x attributes')\n                  xCharAttCnt = xCharAttCnt + 1\n               else\n                  lsmOutDict%xFloatAttNames(xRealAttCnt+1) = trim(tmpAttName)\n                  lsmOutDict%xRealAttLen(xRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,xVarId,trim(tmpAttName),lsmOutDict%xRealAttVals(xRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull x attributes')\n                  xRealAttCnt = xRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            lsmOutDict%nxRealAtts = xRealAttCnt\n            lsmOutDict%nxCharAtts = xCharAttCnt\n\n         endif\n\n         charFlag = 0\n         floatFlag = 0\n         iret = nf90_inq_varid(ftnMeta,'y',yVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to locate the y variable. No y variable or attributes will be created.')\n            lsmOutDict%nyCharAtts = 0\n            lsmOutDict%nyRealAtts = 0\n         else\n            iret = nf90_inquire_variable(ftnMeta,yVarId,nAtts=nyAtts)\n            call nwmCheck(diagFlag,iret,'ERROR: Unable to find y number of attributes')\n            do i =1,nyAtts\n               iret = nf90_inq_attname(ftnMeta,yVarId,i,name=tmpAttName)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to extract attribute names from y variable.')\n               iret = nf90_inquire_attribute(ftnMeta,yVarId,trim(tmpAttName),xtype=xtypeTmp,len=tmpLen)\n               call nwmCheck(diagFlag,iret,'ERROR: Unable to find attribute types from y variable.')\n               select case (xtypeTmp)\n                  case (NF90_FLOAT)\n                     floatFlag = 1\n                  case (NF90_CHAR)\n                     charFlag = 1\n                  case (NF90_SHORT)\n                     floatFlag = 1\n                  case (NF90_USHORT)\n                     floatFlag = 1\n                  case (NF90_INT)\n                     floatFlag = 1\n                  case (NF90_UINT)\n                     floatFlag = 1\n                  case (NF90_INT64)\n                     floatFlag = 1\n                  case (NF90_UINT64)\n                     floatFlag = 1\n                  case (NF90_DOUBLE)\n                     floatFlag = 1\n                  case (NF90_STRING)\n                     charFlag = 1\n               end select\n               if(charFlag .eq. 1) then\n                  lsmOutDict%yCharAttNames(yCharAttCnt+1) = trim(tmpAttName)\n                  iret = nf90_get_att(ftnMeta,yVarId,trim(tmpAttName),lsmOutDict%yCharAttVals(yCharAttCnt+1))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull y attributes')\n                  yCharAttCnt = yCharAttCnt + 1\n               else\n                  lsmOutDict%yFloatAttNames(yRealAttCnt+1) = trim(tmpAttName)\n                  lsmOutDict%yRealAttLen(yRealAttCnt+1) = tmpLen\n                  iret = nf90_get_att(ftnMeta,yVarId,trim(tmpAttName),lsmOutDict%yRealAttVals(yRealAttCnt+1,1:tmpLen))\n                  call nwmCheck(diagFlag,iret,'ERROR: Unable to pull y attributes')\n                  yRealAttCnt = yRealAttCnt + 1\n               endif\n               charFlag = 0\n               floatFlag = 0\n            end do\n            lsmOutDict%nyRealAtts = yRealAttCnt\n            lsmOutDict%nyCharAtts = yCharAttCnt\n\n         endif\n         ! Close the file\n         iret = nf90_close(ftnMeta)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAND spatial metadata file.')\n      endif\n\n   endif\n\n   lsmOutDict%varNames(:) = [character(len=64) :: \"stc1\",\"smc1\",\"sh2ox1\",\"stc2\",&\n                             \"smc2\",\"sh2ox2\",\"stc3\",\"smc3\",\"sh2ox3\",\"stc4\",&\n                             \"smc4\",\"sh2ox4\",\"infxsrt\",\"sfcheadrt\"]\n   lsmOutDict%longName(:) = [character(len=64) :: \"Soil temperature in the top layer\",&\n                             \"Soil moisture in the top layer\",&\n                             \"Volumetric soil moisture in the top layer\",&\n                             \"Soil temperature in the second layer\",&\n                             \"Soil moisture in the second layer\",&\n                             \"Volumetric soil moisture in the second layer\",&\n                             \"Soil temperature in the third layer\",&\n                             \"Soil moisture in the third layer\",&\n                             \"Volumetric soil moisture in the third layer\",&\n                             \"Soil temperature in the fourth layer\",&\n                             \"Soil moisture in the fourth layer\",&\n                             \"Volumetric soil moisture in the fourth layer\",&\n                             \"Infiltration excess\",\"Surface head\"]\n   lsmOutDict%units(:) = [character(len=64) :: \"K\",\"fraction\",\"fraction\",&\n                          \"K\",\"fraction\",\"fraction\",\"K\",\"fraction\",&\n                          \"fraction\",\"K\",\"fraction\",\"fraction\",&\n                          \"mm\",\"mm\"]\n   lsmOutDict%scaleFactor(:) = [0.1,0.01,0.01,0.1,0.01,0.01,0.1,0.01,0.01,&\n                                0.1,0.01,0.01,1.0,1.0]\n   lsmOutDict%addOffset(:) = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,&\n                              0.0,0.0,0.0,0.0]\n   lsmOutDict%timeZeroFlag(:) = [1,1,1,1,1,1,1,1,1,1,1,1,1,1]\n   lsmOutDict%numLev(:) = [1,1,1,1,1,1,1,1,1,1,1,1,1,1]\n   lsmOutDict%missingReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,&\n                                -9999.0,-9999.0,-9999.0,-9999.0]\n   lsmOutDict%fillReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,-9999.0,&\n                             -9999.0,-9999.0,-9999.0,-9999.0]\n   lsmOutDict%validMinDbl(:) = [150.0d0, 0.0d0, 0.0d0, 150.0d0, 0.0d0, 0.0d0, 150.0d0, 0.0d0, 0.0d0, &\n                                 150.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0]\n   lsmOutDict%validMaxDbl(:) = [400.0d0, 1.0d0, 1.0d0, 400.0d0, 1.0d0, 1.0d0, 400.0d0, 1.0d0, 1.0d0, &\n                                 400.0d0, 1.0d0, 1.0d0, 100000.0d0, 100000.0d0]\n   ! Loop through and calculate missing/fill/min/max values that will be placed\n   ! into the NetCDF attributes after scale_factor/add_offset are applied.\n   do i=1,numLsmVars\n      lsmOutDict%fillComp(i) = &\n           nint((lsmOutDict%fillReal(i)     + lsmOutDict%addOffset(i)), 8) * &\n           nint(one_dbl / lsmOutDict%scaleFactor(i), 8)\n      lsmOutDict%missingComp(i) = &\n           nint((lsmOutDict%missingReal(i)  + lsmOutDict%addOffset(i)), 8) * &\n           nint(one_dbl / lsmOutDict%scaleFactor(i), 8)\n      lsmOutDict%validMinComp(i) = &\n           nint((lsmOutDict%validMinDbl(i) + lsmOutDict%addOffset(i)) * &\n                nint(one_dbl / lsmOutDict%scaleFactor(i), 8), 8)\n      lsmOutDict%validMaxComp(i) = &\n           nint((lsmOutDict%validMaxDbl(i) + lsmOutDict%addOffset(i)) * &\n                nint(one_dbl / lsmOutDict%scaleFactor(i), 8), 8)\n   end do\n\nend subroutine initLsmOutDict\n\nsubroutine initChanObsDict(chObsDict,diagFlag,procId)\n  use config_base, only: nlst\n  use netcdf\n  implicit none\n\n   type(chObsMeta), intent(inout) :: chObsDict\n   integer, intent(inout) :: diagFlag\n   integer, intent(inout) :: procId\n\n   ! Local variables\n   integer :: ftnMeta, iret\n   integer :: projVarId\n\n   chObsDict%modelNdv = -9.E15\n   !CHANOBS FILES\n\n   ! Pull spatial metadata information about the modeling domain from the land\n   ! spatial metadata file.\n   if(procId .eq. 0) then\n      iret = nf90_open(trim(nlst(1)%land_spatial_meta_flnm),NF90_NOWRITE,ncid=ftnMeta)\n      if(iret .ne. 0) then\n         ! Spatial metadata file not found for land grid.\n         call postDiagMsg(diagFlag,'WARNING: Unable to open LAND spatial metadata file.')\n         chObsDict%proj4 = ''\n         chObsDict%esri = ''\n      else\n         ! First pull metadata on coordinate system.\n         iret = nf90_inq_varid(ftnMeta,'crs',projVarId)\n         if(iret .ne. 0) then\n            call postDiagMsg(diagFlag,'WARNING: Unable to find crs in LAND spatial metadata file')\n            chObsDict%proj4 = ''\n            chObsDict%esri = ''\n         else\n            iret = nf90_get_att(ftnMeta,projVarId,'esri_pe_string',chObsDict%esri)\n            if(iret .ne. 0) then\n               call postDiagMsg(diagFlag,'WARNING: Unable to find esri_pe_string in LAND spatial metadata file.')\n               chObsDict%esri = ''\n            endif\n            iret = nf90_get_att(ftnMeta,NF90_GLOBAL,'proj4',chObsDict%proj4)\n            ! We are going to put a relaxed constraint on the proj4 string.\n            if(iret .ne. 0) then\n               call postDiagMsg(diagFlag,'WARNING: proj4 string not found. Defaulting to blank string.')\n               chObsDict%proj4 = ''\n            endif\n         endif\n         ! Close the file\n         iret = nf90_close(ftnMeta)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAND spatial metadata file.')\n      endif\n   endif\n\n   chObsDict%title = \"OUTPUT FROM \" // trim(get_model_version())\n   chObsDict%fType = 'timeSeries'\n   chObsDict%initTime = '1970-01-01_00:00:00' ! This will be calculated in I/O code\n   chObsDict%validTime = '1970-01-01_00:00:00' ! This will be calculated in I/O code\n   chObsDict%stDim = 'feature_id'\n   chObsDict%stOrder = 1\n   chObsDict%cdm = 'Station'\n   chObsDict%conventions = 'CF-1.6'\n\n   ! Next establish time attribues\n   chObsDict%timeLName = 'valid output time'\n   chObsDict%timeUnits = 'minutes since 1970-01-01 00:00:00 UTC'\n   chObsDict%timeStName = 'time'\n   chObsDict%rTimeLName = 'model initialization time'\n   chObsDict%rTimeStName = 'forecast_reference_time'\n   chObsDict%rTimeUnits = 'minutes since 1970-01-01 00:00:00 UTC'\n\n   ! Esatablish lat/lon attributes\n   chObsDict%latLName = \"Feature latitude\"\n   chObsDict%latUnits = \"degrees_north\"\n   chObsDict%latStName = \"latitude\"\n   chObsDict%lonLName = \"Feature longitude\"\n   chObsDict%lonUnits = \"degrees_east\"\n   chObsDict%lonStName = \"longitude\"\n\n   ! Establish streamflw order attributes\n   chObsDict%orderLName = \"Streamflow Order\"\n   chObsDict%orderStName = \"order\"\n\n   ! Establish point elevation attributes\n   chObsDict%elevLName = \"Feature Elevation\"\n   chObsDict%elevUnits = \"meters\"\n   chObsDict%elevStName = \"Elevation\"\n\n   ! Next establish feature_id attributes\n   chObsDict%featureIdLName = 'Reach ID'\n   chObsDict%featureIdComment = 'NHDPlusv2 ComIDs within CONUS, arbitrary Reach IDs outside of CONUS'\n   chObsDict%cfRole = 'timeseries_id'\n\n   chObsDict%varNames(:) = [character(len=64) :: \"streamflow\"]\n   chObsDict%longName(:) = [character(len=64) :: \"River Flow\"]\n   chObsDict%units(:) = [character(len=64) :: \"m3 s-1\"]\n   chObsDict%coordNames(:) = [character(len=64) :: \"latitude longitude\"]\n   chObsDict%scaleFactor(:) = [0.01]\n   chObsDict%addOffset(:) = [0.0]\n   ! Initialize all output flags to 0. Modify (if absolutely necessary) in the\n   ! output subroutine.\n   chObsDict%outFlag(:) = [0]\n   chObsDict%timeZeroFlag(:) = [1]\n   chObsDict%fillReal(:) = [-9999.0]\n   chObsDict%missingReal(:) = [-9999.0]\n   chObsDict%validMinDbl(:) = [0.0d0]\n   chObsDict%validMaxDbl(:) = [50000.0d0]\n   ! Loop through and calculate missing/fill/min/max values that will be placed\n   ! into the NetCDF attributes after scale_factor/add_offset are applied.\n   do i=1,numChObsVars\n      chObsDict%fillComp(i) = &\n           nint((chObsDict%fillReal(i)     + chObsDict%addOffset(i)), 8) * &\n           nint(one_dbl / chObsDict%scaleFactor(i), 8)\n      chObsDict%missingComp(i) = &\n           nint((chObsDict%missingReal(i)  + chObsDict%addOffset(i)), 8) * &\n           nint(one_dbl / chObsDict%scaleFactor(i), 8)\n      chObsDict%validMinComp(i) = &\n           nint((chObsDict%validMinDbl(i) + chObsDict%addOffset(i)) * &\n                nint(one_dbl / chObsDict%scaleFactor(i), 8), 8)\n      chObsDict%validMaxComp(i) = &\n           nint((chObsDict%validMaxDbl(i) + chObsDict%addOffset(i)) * &\n                nint(one_dbl / chObsDict%scaleFactor(i), 8), 8)\n   end do\n\nend subroutine initChanObsDict\n\nsubroutine initGwDict(gwOutDict)\n   implicit none\n\n   type(gwMeta), intent(inout) :: gwOutDict\n\n\n   gwOutDict%modelNdv = -9.E15\n\n   gwOutDict%title = \"OUTPUT FROM \" // trim(get_model_version())\n   gwOutDict%fType = 'timeSeries'\n   !gwOutDict%proj4 = '+proj=longlat +datum=NAD83 +no_defs'\n   gwOutDict%initTime = '1970-01-01_00:00:00' ! This will be calculated in I/O code\n   gwOutDict%validTime = '1970-01-01_00:00:00' ! This will be calculated in I/O code\n   gwOutDict%gwDim = 'gw_id'\n   !gwOutDict%cdm = 'PLACEHOLDER'\n   !gwOutDict%esri = 'GEOGCS[GCS_North_American_1983,DATUM[D_North_American_1983,&\n   !                   &SPHEROID[GRS_1980,6378137.0,298.257222101]],&\n   !                   &PRIMEM[Greenwich,0.0],UNIT[Degree,0.017453292519943295]]'\n   gwOutDict%conventions = 'CF-1.6'\n\n   ! Next establish time attribues\n   gwOutDict%timeLName = 'valid output time'\n   gwOutDict%timeUnits = 'minutes since 1970-01-01 00:00:00 UTC'\n   gwOutDict%timeStName = 'time'\n   gwOutDict%rTimeLName = 'model initialization time'\n   gwOutDict%rTimeStName = 'forecast_reference_time'\n   gwOutDict%rTimeUnits = 'minutes since 1970-01-01 00:00:00 UTC'\n\n   ! Establish elevation variable attributes\n   !gwOutDict%elevLName = \"Water Surface Elevation\"\n   !gwOutDict%elevUnits = \"meters\"\n\n   ! Establish feature_id attributes\n   gwOutDict%featureIdLName = \"Groundwater Bucket ID\"\n   gwOutDict%featureIdComment = \"Groundwater Bucket ID\"\n   gwOutDict%cfRole = 'timeseries_id'\n\n   ! Esatablish lat/lon attributes\n   !gwOutDict%latLName = \"Groundwater Bucket latitude\"\n   !gwOutDict%latUnits = \"degrees_north\"\n   !gwOutDict%latStName = \"latitude\"\n   !gwOutDict%lonLName = \"Groundwater Bucket longitude\"\n   !gwOutDict%lonUnits = \"degrees_east\"\n   !gwOutDict%lonStName = \"longitude\"\n\n   gwOutDict%varNames(:) = [character(len=64) :: 'inflow','outflow','loss','depth']\n   gwOutDict%longName(:) = [character(len=64) :: 'Bucket Inflow','Bucket Outflow','Bucket Loss','Bucket Depth']\n   gwOutDict%units(:) = [character(len=64) :: 'm3 s-1','m3 s-1','m3 s-1','mm']\n   !gwOutDict%coordNames(:) = [character(len=64) :: 'latitude longitude','latitude longitude','latitude longitude','latitude longitude']\n   gwOutDict%scaleFactor(:) = [0.001,0.001,0.001,0.1]\n   gwOutDict%addOffset(:) = [0.0,0.0,0.0,0.0]\n   gwOutDict%outFlag(:) = [0,0,0,0]\n   gwOutDict%timeZeroFlag(:) = [0,0,0,1]\n   gwOutDict%fillReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0]\n   gwOutDict%missingReal(:) = [-9999.0,-9999.0,-9999.0,-9999.0]\n   gwOutDict%validMinDbl(:) = [0.0d0, 0.0d0, 0.0d0, 0.0d0]\n   gwOutDict%validMaxDbl(:) = [50000.0d0, 50000.0d0, 50000.0d0, 10000.0d0]\n\n   ! Loop through and calculate missing/fill/min/max values that will be placed\n   ! into the NetCDF attributes after scale_factor/add_offset are applied.\n   do i=1,numGwVars\n      gwOutDict%fillComp(i) = &\n           nint((gwOutDict%fillReal(i)     + gwOutDict%addOffset(i)), 8) * &\n           nint(one_dbl / gwOutDict%scaleFactor(i), 8)\n      gwOutDict%missingComp(i) = &\n           nint((gwOutDict%missingReal(i)  + gwOutDict%addOffset(i)), 8) * &\n           nint(one_dbl / gwOutDict%scaleFactor(i), 8)\n      gwOutDict%validMinComp(i) = &\n           nint((gwOutDict%validMinDbl(i) + gwOutDict%addOffset(i)) * &\n                nint(one_dbl / gwOutDict%scaleFactor(i), 8), 8)\n      gwOutDict%validMaxComp(i) = &\n           nint((gwOutDict%validMaxDbl(i) + gwOutDict%addOffset(i)) * &\n                nint(one_dbl / gwOutDict%scaleFactor(i), 8), 8)\n   end do\n\nend subroutine initGwDict\n\nsubroutine postDiagMsg(diagFlag,diagMsg)\n   implicit none\n\n   ! Subroutine arguments.\n   integer, intent(in) :: diagFlag\n   character(len=*), intent(in) :: diagMsg\n\n   ! Only write out message if the diagnostic WRF_HYDRO_D flag was\n   ! set to 1\n   if (diagFlag .eq. 1) then\n      print*, trim(diagMsg)\n   end if\n\nend subroutine postDiagMsg\n\nsubroutine nwmCheck(diagFlag,iret,msg)\n   implicit none\n\n   ! Subroutine arguments.\n   integer, intent(in) :: diagFlag,iret\n   character(len=*), intent(in) :: msg\n\n   ! Check status. If status of command is not 0, then post the error message\n   ! if WRF_HYDRO_D was set to be 1.\n   if (iret .ne. 0) then\n      call hydro_stop(trim(msg))\n   end if\n\nend subroutine nwmCheck\n\nend module module_NWM_io_dict\n"
  },
  {
    "path": "src/Routing/module_RT.F90",
    "content": "MODULE module_Routing\n#ifdef MPP_LAND\n   use module_gw_baseflow, only: pix_ct_1\n   use module_HYDRO_io, only: mpp_read_routedim, read_routing_seq, mpp_read_chrouting_new, &\n                              mpp_read_simp_gw, read_routelink, get_nlinksl\n   use MODULE_mpp_ReachLS, only: ReachLS_ini, getlocalindx,  getToInd\n   USE module_mpp_land, only : left_id, up_id, right_id, down_id, mpp_land_com_integer, &\n                               mpp_land_bcast_int, mpp_land_bcast_int1, &\n                               updateLake_seq\n   use module_mpp_GWBUCKET, only : collectSizeInd\n#else\n   !yw use module_HYDRO_io, only: read_routedim, read_routing_old, read_chrouting,read_simp_gw\n   use module_HYDRO_io, only: read_routedim, read_routing_seq, read_chrouting1,read_simp_gw, get_nlinksl\n#endif\n   use module_HYDRO_io, only: readgw2d, simp_gw_ind,read_GWBUCKPARM, get_gw_strm_msk_lind, readBucket_nhd, read_NSIMLAKES\n   use module_HYDRO_utils\n\n   use module_UDMAP, only: LNUMRSL, LUDRSL, UDMP_ini\n   use module_levelpool, only: levelpool\n   use module_persistence_levelpool_hybrid, only: persistence_levelpool_hybrid\n   use module_rfc_forecasts, only: rfc_forecasts\n   use module_hydro_stop, only: HYDRO_stop\n   use hashtable\n   use iso_fortran_env, only: int64\n#ifdef OUTPUT_CHAN_CONN\n#ifdef MPP_LAND\n   use mpi\n#endif\n#endif\n\n   IMPLICIT NONE\n\n\n   integer, parameter :: r8 = selected_real_kind(8)\n   real*8,  parameter :: zeroDbl=0.0000000000000000000_r8\n   integer, parameter :: r4 = selected_real_kind(4)\n   real  ,  parameter :: zeroFlt=0.0000000000000000000_r4\n\nCONTAINS\n\n   subroutine rt_allocate(did,ix,jx,ixrt,jxrt,nsoil,CHANRTSWCRT)\n      use module_RT_data, only: rt_domain\n      use config_base, only: nlst\n\n      implicit none\n      integer ixrt,jxrt, ix,jx,nsoil,NLINKS, CHANRTSWCRT, NLAKES, NLINKSL\n      integer istatus, did, nsizes\n\n      if(rt_domain(did)%allo_status .eq. 1) return\n      rt_domain(did)%allo_status = 1\n\n      rt_domain(did)%ix = ix\n      rt_domain(did)%jx = jx\n      rt_domain(did)%ixrt = ixrt\n      rt_domain(did)%jxrt = jxrt\n!     ixrt = rt_domain(did)%ixrt\n!     jxrt = rt_domain(did)%jxrt\n\n      ! allocate overland data structures\n      call rt_domain(did)%overland%init(ix, jx, ixrt, jxrt)\n\n      ! allocate subsurface data structures\n      call rt_domain(did)%subsurface%init(ixrt, jxrt, nsoil, rt_domain(did)%overland)\n\n      ! allocate susurface static data structure\n      call rt_domain(did)%subsurface_static%init(ixrt, jxrt, nsoil, nlst(did)%DT, nlst(did)%rt_option)\n\n      ! allocate subsurface input structure\n      call rt_domain(did)%subsurface_output%init(ixrt, jxrt, rt_domain(did)%overland%control%infiltration_excess)\n\n      !allocate subsurface output structure\n      call rt_domain(did)%subsurface_input%init(ixrt, jxrt, rt_domain(did)%overland%control%infiltration_excess)\n\n!     if( nlst_rt(did)%channel_option .eq. 1  .or. nlst_rt(did)%channel_option .eq. 2 ) then\n!         rt_domain(did)%NLINKS = rt_domain(did)%NLINKSL\n!     endif\n      if(nlst(did)%UDMP_OPT .eq. 1) then\n          if(rt_domain(did)%NLINKS .lt. rt_domain(did)%NLINKSL) then\n              rt_domain(did)%NLINKS = rt_domain(did)%NLINKSL\n          endif\n      endif\n\n\n      NLINKS = rt_domain(did)%NLINKS\n      NLAKES = rt_domain(did)%NLAKES\n      NLINKSL = rt_domain(did)%NLINKSL\n\n      if(NLINKSL .gt. NLINKS) then\n         nsizes = nlinksl\n      else\n         nsizes = nlinks\n!           write(6,*) \"Fatal Error: NLINKSL .gt. NLINKS .. \"\n!           call hydro_stop(\"not solved, contact WRF-Hydro group. \")\n      endif\n      rt_domain(did)%nlinksize = nsizes\n\n\n      if(rt_domain(did)%NLINKS .eq. 0) NLINKS = 1\n      if(rt_domain(did)%NLAKES .eq. 0) NLAKES = 1\n      if(rt_domain(did)%NLINKSL .eq. 0) NLINKSL = 1\n\n      rt_domain(did)%iswater = 0\n      rt_domain(did)%isurban = 0\n      rt_domain(did)%isoilwater = 0\n\n!DJG Allocate routing and disaggregation arrays\n\n#ifdef HYDRO_D\n  write(6,*) \"  rt_allocate ***** ixrt,jxrt, nsoil\", ixrt,jxrt, nsoil\n#endif\n\n  if(nlst(did)%channel_only       .eq. 0 .and. &\n     nlst(did)%channelBucket_only .eq. 0        ) then\n\n     allocate( rt_domain(did)%DSMC   \t(NSOIL) )\n     rt_domain(did)%dsmc = 0\n     allocate( rt_domain(did)%SMCRTCHK    \t(NSOIL) )\n     rt_domain(did)%SMCRTCHK = 0\n     allocate( rt_domain(did)%SH2OAGGRT   \t(NSOIL) )\n     rt_domain(did)%SH2OAGGRT = 0\n     allocate( rt_domain(did)%STCAGGRT   \t(NSOIL) )\n     rt_domain(did)%STCAGGRT = 0\n     allocate( rt_domain(did)%SMCAGGRT   \t(NSOIL) )\n     rt_domain(did)%SMCAGGRT = 0\n\n     if(nlst(did)%UDMP_OPT .eq. 1) then\n        allocate ( RT_DOMAIN(did)%landRunOff (ixrt,jxrt) )\n     endif\n\n     !allocate( rt_domain(did)%subsurface%grid_transform%smcrt   \t(IXRT,JXRT,NSOIL) )\n     !rt_domain(did)%subsurface%grid_transform%smcrt   \t= 0.0\n     allocate( rt_domain(did)%soiltypRT   \t(IXRT,JXRT) )\n     !!\n\n     !allocate( rt_domain(did)%overland%properties%surface_slope_x  \t(IXRT,JXRT) )\n     !rt_domain(did)%overland%properties%surface_slope_x  \t= 0.0\n     !allocate( rt_domain(did)%overland%properties%surface_slope_y   \t(IXRT,JXRT) )\n     !rt_domain(did)%overland%properties%surface_slope_y   \t= 0.0\n     !allocate( rt_domain(did)%overland%properties%surface_slope   \t(IXRT,JXRT,8) )\n     !rt_domain(did)%overland%properties%surface_slope   \t= -999\n     !allocate( rt_domain(did)%overland%properties%max_surface_slope_index   \t(IXRT,JXRT,3) )\n     !rt_domain(did)%overland%properties%max_surface_slope_index   \t= 0.0\n     !allocate( rt_domain(did)%overland%properties%roughness   (IXRT,JXRT) )\n     !\n\n     !allocate( rt_domain(did)%QSUBBDRYTRT   (IXRT,JXRT) )\n     !rt_domain(did)%QSUBBDRYTRT = 0.0\n     allocate( rt_domain(did)%OVROUGHRTFAC   (IXRT,JXRT) )\n     !rt_domain(did)%overland%properties%roughness   = 0.0\n     !allocate( rt_domain(did)%overland%properties%retention_depth    (IXRT,JXRT) )\n     !\n\n     allocate( rt_domain(did)%RETDEPRTFAC    (IXRT,JXRT) )\n     !\n\n     !allocate( rt_domain(did)%overland%control%surface_water_head_routing(IXRT,JXRT) )\n     !rt_domain(did)%overland%control%surface_water_head_routing= 0.0\n     !allocate( rt_domain(did)%overland%control%infiltration_excess   (IXRT,JXRT) )\n     !rt_domain(did)%overland%control%infiltration_excess   = 0.0\n     allocate( rt_domain(did)%INFXSWGT    (IXRT,JXRT) )\n     rt_domain(did)%INFXSWGT    = 0.0\n     !allocate( rt_domain(did)%LKSATRT     (IXRT,JXRT) )\n     !rt_domain(did)%LKSATRT     = 0.0\n     allocate( rt_domain(did)%LKSATFAC    (IXRT,JXRT) )\n     rt_domain(did)%LKSATFAC    = 0.0\n\n     allocate( rt_domain(did)%IMPERVFRAC    (IXRT,JXRT) )\n     rt_domain(did)%IMPERVFRAC    = 0.0\n\n     !allocate( rt_domain(did)%subsurface%state%qsubrt      (IXRT,JXRT) )\n     !rt_domain(did)%subsurface%state%qsubrt      = 0.0\n     !allocate( rt_domain(did)%subsurface%properties%zwattablrt  (IXRT,JXRT) )\n     !rt_domain(did)%subsurface%properties%zwattablrt  = 0.0\n     !allocate( rt_domain(did)%QSUBBDRYRT  (IXRT,JXRT) )\n     !rt_domain(did)%QSUBBDRYRT  = 0.0\n     !allocate( rt_domain(did)%subsurface%properties%soldeprt    (IXRT,JXRT) )\n     !rt_domain(did)%subsurface%properties%soldeprt    = 0.0\n     allocate( rt_domain(did)%q_sfcflx_x  (IXRT,JXRT) )\n     rt_domain(did)%q_sfcflx_x  = 0.0\n     allocate( rt_domain(did)%q_sfcflx_y  (IXRT,JXRT) )\n     rt_domain(did)%q_sfcflx_y  = 0.0\n     !allocate( rt_domain(did)%subsurface%grid_transform%smcmaxrt   \t(IXRT,JXRT,NSOIL) )\n     !rt_domain(did)%subsurface%grid_transform%smcmaxrt   \t= 0.0\n     !allocate( rt_domain(did)%subsurface%grid_transform%smcwltrt   \t(IXRT,JXRT,NSOIL) )\n     !rt_domain(did)%subsurface%grid_transform%smcwltrt   \t= 0.0\n     allocate( rt_domain(did)%SH2OWGT   \t(IXRT,JXRT,NSOIL) )\n     rt_domain(did)%SH2OWGT     = 0.0\n     allocate( rt_domain(did)%INFXSAGGRT \t(IXRT,JXRT) )\n     rt_domain(did)%INFXSAGGRT \t= 0.0\n     !allocate( rt_domain(did)%overland%control%dhrt   \t(IXRT,JXRT) ) ! moved to overland control\n     !rt_domain(did)%overland%control%dhrt   \t= 0.0                 ! moved to overland control\n     !allocate( rt_domain(did)%overland%streams_and_lakes%surface_water_to_channel (IXRT,JXRT) )              ! moved to overland streams and lakes\n     !rt_domain(did)%overland%streams_and_lakes%surface_water_to_channel = 0.0                                ! moved to overland streams and lakes\n     allocate( rt_domain(did)%QSTRMVOLRT_TS  (IXRT,JXRT) )\n     rt_domain(did)%QSTRMVOLRT_TS  = 0.0\n     allocate( rt_domain(did)%QSTRMVOLRT_ACC  (IXRT,JXRT) )\n     rt_domain(did)%QSTRMVOLRT_ACC  = 0.0\n     !allocate( rt_domain(did)%overland%control%boundary_flux   \t(IXRT,JXRT) )\n     !rt_domain(did)%overland%control%boundary_flux   \t= 0.0\n     allocate( rt_domain(did)%SUB_RESID (ixrt,jxrt) )\n     rt_domain(did)%SUB_RESID = 0.0\n\n     ! tmp array\n     !allocate( rt_domain(did)%subsurface%grid_transform%smcrefrt    \t(IXRT,JXRT,NSOIL) )\n     ! tmp\n\n     !! Variables (formerly?) needed for channel_only\n     allocate( rt_domain(did)%ELRT   \t(IXRT,JXRT) )\n     rt_domain(did)%ELRT   \t= 0.0\n     !allocate( rt_domain(did)%overland%streams_and_lakes%lake_mask \t(IXRT,JXRT) ) ! moved to overland%stream_and_lakes\n     !rt_domain(did)%overland%streams_and_lakes%lake_mask \t= -9999               ! moved to overland%streams_and_lakes\n     !allocate( rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake(IXRT,JXRT) )                              ! moved to overland%streams_and_lakes\n     !!rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake= 0.0                                               ! moved to overland%streams_and_lakes\n     allocate( rt_domain(did)%LAKE_INFLORT_TS(IXRT,JXRT) )\n     allocate( rt_domain(did)%LAKE_INFLORT_DUM(IXRT,JXRT) )\n     rt_domain(did)%LAKE_INFLORT_DUM= 0.0\n     allocate( rt_domain(did)%LATVAL (ixrt,jxrt) )\n     allocate( rt_domain(did)%LONVAL (ixrt,jxrt) )\n     rt_domain(did)%LONVAL = 0.0\n     rt_domain(did)%LATVAL = 0.0\n\n\n  !DJG Allocate routing and disaggregation arrays\n  allocate(rt_domain(did)%qinflowbase  (IXRT,JXRT) )\n  rt_domain(did)%qinflowbase = 0.0\n\n  allocate(rt_domain(did)%gw_strm_msk  (IXRT,JXRT) )\n           rt_domain(did)%gw_strm_msk   = 0\n  allocate(rt_domain(did)%gw_strm_msk_lind  (IXRT,JXRT) )\n\n  ! allocate land surface grid variables\n  allocate( rt_domain(did)%SMC  (IX,JX,NSOIL) )\n            rt_domain(did)%SMC   = 0.25\n  allocate( rt_domain(did)%SICE (IX,JX,NSOIL) )\n            rt_domain(did)%SICE  = 0.\n  ! allocate( rt_domain(did)%dist_lsm (ixrt,jxrt,9) )\n  ! allocate( rt_domain(did)%lat_lsm (ixrt,jxrt) )\n  ! allocate( rt_domain(did)%lon_lsm (ixrt,jxrt) )\n\n  ! allocate( rt_domain(did)%SICE  (IX,JX,NSOIL) )\n  allocate( rt_domain(did)%SMCMAX1  (IX,JX) )\n            rt_domain(did)%SMCMAX1   = 0.0\n           !rt_domain(did)%SMCMAX1   = 0.434\n  allocate( rt_domain(did)%STC  (IX,JX,NSOIL) )\n            rt_domain(did)%STC   = 282.0\n  allocate( rt_domain(did)%SH2OX(IX,JX,NSOIL) )\n            rt_domain(did)%SH2OX = rt_domain(did)%SMC\n  allocate( rt_domain(did)%SMCWLT1  (IX,JX) )\n            rt_domain(did)%SMCWLT1   = 0.0\n  allocate( rt_domain(did)%SMCREF1  (IX,JX) )\n            rt_domain(did)%SMCREF1   = 0.0\n  allocate( rt_domain(did)%VEGTYP   (IX,JX) )\n            rt_domain(did)%VEGTYP    = 0\n\n  allocate( rt_domain(did)%OV_ROUGH2d   (IX,JX) )\n\n  allocate( rt_domain(did)%SOILTYP   (IX,JX) )\n\n  allocate( rt_domain(did)%GWSUBBASMSK   (IX,JX) )\n            rt_domain(did)%GWSUBBASMSK    = 0\n  !allocate( rt_domain(did)%subsurface%properties%sldpth(NSOIL) )\n  !          rt_domain(did)%subsurface%properties%sldpth = 0.0\n  allocate( rt_domain(did)%SO8LD_D   (IX,JX,3) )\n            rt_domain(did)%SO8LD_D    = 0.0\n  allocate( rt_domain(did)%SO8LD_Vmax   (IX,JX) )\n            rt_domain(did)%SO8LD_Vmax    = 0.0\n  !allocate( rt_domain(did)%sfcheadrt   (IX,JX) ) !moved to overland control structure\n  !          rt_domain(did)%sfcheadrt    = 0.0    !moved to overland control structure\n  allocate( rt_domain(did)%INFXSRT   (IX,JX) )\n            rt_domain(did)%INFXSRT    = 0.0\n  allocate( rt_domain(did)%TERRAIN   (IX,JX) )\n            rt_domain(did)%TERRAIN    = 0.0\n  allocate( rt_domain(did)%LKSAT   (IX,JX) )\n            rt_domain(did)%LKSAT    = 0.0\n  allocate( rt_domain(did)%SOLDRAIN   (IX,JX) )\n            rt_domain(did)%SOLDRAIN    = 0.0\n\n  allocate( rt_domain(did)%NEXP   (IX,JX) )\n            rt_domain(did)%NEXP    = 1.0\n\n  end if ! neither channel_only nor channelBucket_only\n\n\n  !! needed regardless\n  allocate( rt_domain(did)%dist_lsm (ix,jx,9) )\n            rt_domain(did)%dist_lsm = 0.0\n  allocate( rt_domain(did)%lat_lsm (ix,jx) )\n  allocate( rt_domain(did)%lon_lsm (ix,jx) )\n  rt_domain(did)%timestep_flag = 1    ! default is cold start\n  !allocate( rt_domain(did)%overland%properties%distance_to_neighbor (ixrt,jxrt,9) ) ! moved to overland%properties\n  !rt_domain(did)%overland%properties%distance_to_neighbor = -999                    ! moved to overland%properties\n\n  !! This is needed for channelBucket_only\n  !! because the bucket area (basns_area) depends on the initialization of the\n  !! UDMP code, this is a required variable.\n  !! JLM: could these be deallocated under channel_only\n  if(nlst(did)%channel_only       .eq. 0) then\n     !allocate( rt_domain(did)%overland%streams_and_lakes%ch_netrt   \t(IXRT,JXRT) ) !moved to overland%streams_and_lakes\n     !rt_domain(did)%overland%streams_and_lakes%ch_netrt   \t= 0.0                 !moved to overland%streams_and_lakes\n     allocate( rt_domain(did)%CH_LNKRT (IXRT,JXRT) )\n     rt_domain(did)%CH_LNKRT = 0.0\n  endif\n\n\n  if (CHANRTSWCRT.eq.1 .or. CHANRTSWCRT .eq. 2) then  !IF/then for channel routing\n\n     !! JLM TODO: clean up this section for routing options, group 2D variables.\n\n     allocate( rt_domain(did)%CH_NETLNK (IXRT,JXRT) )\n     rt_domain(did)%CH_NETLNK = 0.0\n     allocate( rt_domain(did)%GCH_NETLNK (IXRT,JXRT) )\n     rt_domain(did)%GCH_NETLNK = 0.0\n\n#ifdef MPP_LAND\n     allocate( rt_domain(did)%LAKE_INDEX(NLAKES) )\n     rt_domain(did)%lake_index = -99\n     allocate( rt_domain(did)%nlinks_INDEX(nsizes) )\n     allocate( rt_domain(did)%Link_location(ixrt,jxrt) )\n#endif\n\n     allocate( rt_domain(did)%CH_LNKRT_SL (IXRT,JXRT) )\n     rt_domain(did)%CH_LNKRT_SL = -99\n     rt_domain(did)%MAXORDER = -9999\n\n!tmp  if( nlst_rt(did)%channel_option .eq. 1  .or. nlst_rt(did)%channel_option .eq. 3 ) then\n!tmp       NLINKS = rt_domain(did)%NLINKSL\n!tmp       NLAKES = rt_domain(did)%NLINKSL\n!tmp  endif\n\n     allocate( rt_domain(did)%LINKID(nsizes) )\n     allocate( rt_domain(did)%gages(nsizes) )\n     allocate( rt_domain(did)%TO_NODE(nsizes) )\n     allocate( rt_domain(did)%FROM_NODE(nsizes) )\n     allocate( rt_domain(did)%CHLAT(nsizes) )   !-latitutde of channel grid point\n     allocate( rt_domain(did)%CHLON(nsizes) )   !-longitude of channel grid point\n     allocate( rt_domain(did)%ZELEV(nsizes) )\n     allocate( rt_domain(did)%TYPEL(nsizes) )\n     allocate( rt_domain(did)%ORDER(nsizes) )\n     allocate( rt_domain(did)%QLINK(nsizes,2) )\n\n#ifdef WRF_HYDRO_NUDGING\n     allocate( rt_domain(did)%nudge(nsizes) )\n#endif\n     allocate( rt_domain(did)%MUSK(nsizes) )\n     allocate( rt_domain(did)%MUSX(nsizes) )\n     allocate( rt_domain(did)%CHANLEN(nsizes) )\n     allocate( rt_domain(did)%MannN(nsizes))\n     allocate( rt_domain(did)%So(nsizes) )\n     allocate( rt_domain(did)%ChSSlp(nsizes) )\n     allocate( rt_domain(did)%Bw(nsizes) )\n     allocate( rt_domain(did)%Tw(nsizes) )\n     allocate( rt_domain(did)%Tw_CC(nsizes) )\n     allocate( rt_domain(did)%n_CC(nsizes) )\n     allocate( rt_domain(did)%ChannK(nsizes) )\n     allocate( rt_domain(did)%LAKEIDA(nsizes) )\n     allocate( rt_domain(did)%LAKEIDX(nsizes) )\n\n     if(NLAKES .gt. 0) then\n\n        allocate ( rt_domain(did)%reservoirs(NLAKES) )    ! allocate array of pointers to reservoirs\n        allocate ( rt_domain(did)%reservoir_type(NLAKES) )        ! allocate array to specify type of reservoir\n        allocate ( rt_domain(did)%final_reservoir_type(NLAKES) )  ! allocate array to specify final type of reservoir\n        allocate ( rt_domain(did)%reservoir_assimilated_value(NLAKES) )  ! allocate array to specify assimilated value to reservoir discharge\n        allocate ( rt_domain(did)%reservoir_assimilated_source_file(NLAKES) )  ! allocate array to specify assimilated source file\n        allocate( rt_domain(did)%LAKEIDM(NLAKES) )\n        allocate( rt_domain(did)%HRZAREA(NLAKES) )\n        allocate( rt_domain(did)%LAKEMAXH(NLAKES) )\n        allocate( rt_domain(did)%ELEVLAKE(NLAKES) )\n        allocate( rt_domain(did)%WEIRH(NLAKES) )\n        allocate( rt_domain(did)%WEIRC(NLAKES) )\n        allocate( rt_domain(did)%WEIRL(NLAKES) )\n        allocate( rt_domain(did)%DAML(NLAKES) )\n        allocate( rt_domain(did)%ORIFICEC(NLAKES) )\n        allocate( rt_domain(did)%ORIFICEA(NLAKES) )\n        allocate( rt_domain(did)%ORIFICEE(NLAKES) )\n\n         rt_domain(did)%HRZAREA = 0.0\n         rt_domain(did)%WEIRH = 0.0\n         rt_domain(did)%WEIRC = 0.0\n         rt_domain(did)%WEIRL = 0.0\n         rt_domain(did)%DAML  = 0.0\n         rt_domain(did)%LAKEMAXH = 0.0\n         rt_domain(did)%ELEVLAKE= 0.0\n         rt_domain(did)%ORIFICEC = 0.0\n         rt_domain(did)%ORIFICEA = 0.0\n         rt_domain(did)%ORIFICEE = 0.0\n         rt_domain(did)%reservoir_type = 1\n         rt_domain(did)%final_reservoir_type = 1\n         rt_domain(did)%reservoir_assimilated_value = -9999.0\n         rt_domain(did)%reservoir_assimilated_source_file = repeat(char(0), 256)\n     endif\n\n\n!    allocate( rt_domain(did)%LAKEMAXH(nsizes) )\n!    allocate( rt_domain(did)%WEIRC(nsizes) )\n!    allocate( rt_domain(did)%WEIRL(nsizes) )\n!    allocate( rt_domain(did)%ORIFICEC(nsizes) )\n!    allocate( rt_domain(did)%ORIFICEA(nsizes) )\n!    allocate( rt_domain(did)%ORIFICEE(nsizes) )\n\n     if(nsizes .gt. 0) then\n        if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n           nlst(did)%output_channelBucket_influx .eq. 2      ) then\n           allocate( rt_domain(did)%accSfcLatRunoff(1) )\n           allocate( rt_domain(did)%accBucket(      1) )\n           allocate( rt_domain(did)%qSfcLatRunoff(  nsizes) )\n           allocate( rt_domain(did)%qBucket(        nsizes) )\n        endif\n\n        if(nlst(did)%output_channelBucket_influx .eq. 1 .or. &\n           nlst(did)%output_channelBucket_influx .eq. 3      ) &\n           allocate( rt_domain(did)%qBtmVertRunoff(     1) )\n        if(nlst(did)%output_channelBucket_influx .eq. 2) then\n             allocate( rt_domain(did)%qBtmVertRunoff(nsizes) )\n             rt_domain(did)%qBtmVertRunoff  = zeroFlt\n        endif\n\n        if(nlst(did)%output_channelBucket_influx .eq. 3) then\n           allocate( rt_domain(did)%accSfcLatRunoff(nsizes) )\n           allocate( rt_domain(did)%accBucket(      nsizes) )\n           allocate( rt_domain(did)%qSfcLatRunoff(       1) )\n           allocate( rt_domain(did)%qBucket(             1) )\n           rt_domain(did)%accSfcLatRunoff = zeroDbl\n           rt_domain(did)%accBucket       = zeroDbl\n           rt_domain(did)%qSfcLatRunoff   = zeroFlt\n           rt_domain(did)%qBucket         = zeroFlt\n        endif\n\n\tallocate( rt_domain(did)%QLateral(nsizes) )\n\tallocate( rt_domain(did)%velocity(nsizes) )\n\trt_domain(did)%QLateral  = zeroFlt\n\trt_domain(did)%velocity  = zeroFlt\n        if( nlst(did)%channel_option .eq. 2 ) then\n           allocate( rt_domain(did)%qloss(nsizes) )\n           rt_domain(did)%qloss = zeroFlt\n        endif\n     endif\n\n  if( nlst(did)%channel_option .eq. 1  .or. nlst(did)%channel_option .eq. 2 ) then\n       NLINKS = rt_domain(did)%NLINKS\n       NLAKES = rt_domain(did)%NLAKES\n  endif\n\n     allocate( rt_domain(did)%LINK(nsizes) )\n     allocate( rt_domain(did)%STRMFRXSTPTS(nsizes) )\n     allocate( rt_domain(did)%CHANXI(nsizes) )\n     allocate( rt_domain(did)%CHANYJ(nsizes) )\n     allocate( rt_domain(did)%CVOL(nsizes) )\n     allocate( rt_domain(did)%LATLAKE(NLAKES) )\n     allocate( rt_domain(did)%LONLAKE(NLAKES) )\n!    allocate( rt_domain(did)%ELEVLAKE(NLAKES) )\n     allocate( rt_domain(did)%LAKENODE(nsizes) )\n     allocate( rt_domain(did)%RESHT(NLAKES),STAT=istatus )\n     allocate( rt_domain(did)%QLAKEI(NLAKES),STAT=istatus )\n     allocate( rt_domain(did)%QLAKEO(NLAKES),STAT=istatus )\n\n     allocate( rt_domain(did)%HLINK(nsizes) )  !--used for diffusion only\n\n     allocate( rt_domain(did)%node_area(nsizes) )\n\n!!!! tmp\n      if(nsizes .gt. 0) then\n      rt_domain(did)%LINK = 0.0\n      rt_domain(did)%gages = rt_domain(did)%gageMiss\n      rt_domain(did)%TO_NODE = 0.0\n      rt_domain(did)%FROM_NODE = 0\n      rt_domain(did)%TYPEL = -999\n      rt_domain(did)%ORDER = 0.0\n      rt_domain(did)%STRMFRXSTPTS = 0.0\n      rt_domain(did)%MUSK = 0.0\n      rt_domain(did)%MUSX = 0.0\n      rt_domain(did)%CHANXI = 0.0\n      rt_domain(did)%CHANYJ = 0.0\n      rt_domain(did)%CHLAT = 0.0         !-latitutde of channel grid point\n      rt_domain(did)%CHLON = 0.0         !-longitude of channel grid point\n      rt_domain(did)%CHANLEN = 0.0\n      rt_domain(did)%ChSSlp = 0.0\n      rt_domain(did)%Bw = 0.0\n      rt_domain(did)%Tw = 0.0\n      rt_domain(did)%Tw_CC = 0.0\n      rt_domain(did)%n_CC = 0.0\n      rt_domain(did)%ChannK = 0.0\n\n\n      rt_domain(did)%ZELEV = 0.0\n      rt_domain(did)%CVOL = 0.0\n      rt_domain(did)%LAKEIDA = 0\n      rt_domain(did)%LAKEIDX = 0\n\n      rt_domain(did)%LATLAKE = 0.0\n      rt_domain(did)%LONLAKE = 0.0\n!     rt_domain(did)%ELEVLAKE = 0.0\n      rt_domain(did)%LAKENODE = 0.0\n      rt_domain(did)%RESHT = 0.0\n      rt_domain(did)%QLAKEI = 0.0\n      rt_domain(did)%QLAKEO = 0.0\n      rt_domain(did)%QLINK = 0\n#ifdef WRF_HYDRO_NUDGING\n      rt_domain(did)%nudge = 0\n#endif\n      rt_domain(did)%HLINK = -999.  !--default to -999 if not found in the restart.\n      rt_domain(did)%MannN = 0.0\n      rt_domain(did)%LINKID = 0.0\n\n      rt_domain(did)%So = 0.01\n     endif\n\n     rt_domain(did)%restQSTRM = .true.\n\n  END IF   !IF/then for channel routing\n\n  rt_domain(did)%out_counts = 0\n  rt_domain(did)%his_out_counts = 0\n  rt_domain(did)%rst_counts = 1\n\n#ifdef HYDRO_D\n  write(6,*) \"***** finish rt_allocate \"\n#endif\n\nend subroutine rt_allocate\n\n\nsubroutine getChanDim(did)\n  use config_base, only: nlst\n  use module_RT_data, only: rt_domain\n  implicit none\n\n  integer ixrt,jxrt, ix,jx, did, i,j\n  integer, allocatable,dimension(:,:) :: CH_NETLNK, GCH_NETLNK\n  !INTEGER, dimension( rt_domain(did)%ixrt,GCH_NETLNK(ixrt,jxrt)) :: GCH_NETLNK, CH_NETLNK\n\n  real :: Vmax\n\n  ix = rt_domain(did)%ix\n  jx = rt_domain(did)%jx\n  ixrt = rt_domain(did)%ixrt\n  jxrt = rt_domain(did)%jxrt\n\n  if(nlst(did)%rtFlag .eq. 0) return\n\n  if(nlst(did)%channel_only       .eq. 1 .or. &\n       nlst(did)%channelBucket_only .eq. 1        ) then\n\n   !! Try to avoid some of the 2-d initialization.\n   !! if this is successful, it most likely will not work for gridded channel (opt 3)\n\n   if(my_id .eq. io_id) then\n      call get_NLINKSL(rt_domain(did)%NLINKSL, nlst(did)%channel_option, nlst(did)%route_link_f)\n   end if\n   call mpp_land_bcast_int1(rt_domain(did)%NLINKSL)\n\n\n   if(nlst(did)%channel_option .eq. 1 .or. nlst(did)%channel_option .eq. 2) then\n      rt_domain(did)%GNLINKSL = rt_domain(did)%NLINKSL\n\n      call ReachLS_ini(rt_domain(did)%GNLINKSL,rt_domain(did)%nlinksl,   &\n           rt_domain(did)%linklsS, rt_domain(did)%linklsE )\n   else\n      rt_domain(did)%GNLINKSL = 1\n      rt_domain(did)%NLINKSL = 1\n   endif\n   if(nlst(did)%UDMP_OPT .eq. 1 .or. nlst(did)%channel_option .eq. 1 .or. nlst(did)%channel_option .eq. 2) &\n        call read_NSIMLAKES(rt_domain(did)%NLAKES,nlst(did)%route_lake_f)\n\n   call rt_allocate(did,rt_domain(did)%ix,rt_domain(did)%jx,&\n        rt_domain(did)%ixrt,rt_domain(did)%jxrt, nlst(did)%nsoil,nlst(did)%CHANRTSWCRT)\n\n   return\n\n  endif\n\n\nallocate(CH_NETLNK(ixrt,jxrt))\nallocate(GCH_NETLNK(ixrt,jxrt))\n\nif (nlst(did)%CHANRTSWCRT.eq.1 .or. nlst(did)%CHANRTSWCRT .eq. 2) then  !IF/then for channel routing\n#ifdef MPP_LAND\n   call MPP_READ_ROUTEDIM(did, rt_domain(did)%g_IXRT,rt_domain(did)%g_JXRT, &\n                          GCH_NETLNK, rt_domain(did)%GNLINKS, &\n#else\n   call READ_ROUTEDIM( &\n#endif\n              IXRT, JXRT, nlst(did)%route_chan_f, nlst(did)%route_link_f, &\n              nlst(did)%route_direction_f, &\n              rt_domain(did)%NLINKS, &\n              CH_NETLNK, nlst(did)%channel_option, nlst(did)%geo_finegrid_flnm, &\n              rt_domain(did)%NLINKSL, nlst(did)%udmp_opt , rt_domain(did)%nlakes)\n#ifndef MPP_LAND\n   call get_NLINKSL(rt_domain(did)%NLINKSL, nlst(did)%channel_option, nlst(did)%route_link_f)\n#endif\n\nif (nlst(did)%lake_option == 0) then\n   write(6,*) \"Lakes have been disabled -- NLAKES will be set to zero.\"\n   rt_domain(did)%nlakes = 0\nend if\n\n#ifdef HYDRO_D\n   write(6,*) \"before rt_allocate after READ_ROUTEDIM\"\n#endif\n\n   if(nlst(did)%channel_option .eq. 1 .or. nlst(did)%channel_option .eq. 2) then\n\n      rt_domain(did)%GNLINKSL = rt_domain(did)%NLINKSL\n\n#ifdef MPP_LAND\n      call ReachLS_ini(rt_domain(did)%GNLINKSL,rt_domain(did)%nlinksl,   &\n           rt_domain(did)%linklsS, rt_domain(did)%linklsE )\n#else\n      rt_domain(did)%linklsS = 1\n      rt_domain(did)%linklsE = rt_domain(did)%NLINKSL\n#endif\n   else\n      rt_domain(did)%GNLINKSL = 1\n      rt_domain(did)%NLINKSL = 1\n   endif\n\n#ifndef MPP_LAND\n   GCH_NETLNK = CH_NETLNK\n#endif\n\nendif\n\nif(nlst(did)%UDMP_OPT .eq. 1 .or. nlst(did)%channel_option .eq. 1 .or. nlst(did)%channel_option .eq. 2) then\n   call read_NSIMLAKES(rt_domain(did)%NLAKES,nlst(did)%route_lake_f)\nendif\n\ncall rt_allocate(did,rt_domain(did)%ix,rt_domain(did)%jx,&\n     rt_domain(did)%ixrt,rt_domain(did)%jxrt, nlst(did)%nsoil,nlst(did)%CHANRTSWCRT)\n\n\nif (nlst(did)%CHANRTSWCRT.eq.1 .or. nlst(did)%CHANRTSWCRT .eq. 2) then  !IF/then for channel routing\n   rt_domain(did)%CH_NETLNK = CH_NETLNK\n   rt_domain(did)%GCH_NETLNK = GCH_NETLNK\nendif\n\nif(allocated(CH_NETLNK)) deallocate(CH_NETLNK)\nif(allocated(GCH_NETLNK)) deallocate(GCH_NETLNK)\n\nend subroutine getChanDim\n\n!===================================================================================================\nsubroutine LandRT_ini(did)\n\n  use module_noah_chan_param_init_rt\n  use config_base, only: nlst, noah_lsm\n  use module_RT_data, only: rt_domain\n  use module_gw_gw2d_data, only: gw2d\n  use module_HYDRO_io, only: regrid_lowres_to_highres\n#ifdef HYDRO_D\n  use module_HYDRO_io, only: output_lake_types\n#endif\n\n#ifdef OUTPUT_CHAN_CONN\n  use module_nudging_io,        only: output_chan_connectivity\n#endif\n\n  implicit none\n\n  integer :: did\n  real    :: Vmax\n\n  integer :: bas\n  character(len=19)                      :: header\n  character(len=1)                       :: jnk\n\n  integer :: lake_index, NLAKES_total\n\n  real,  dimension(50)     :: BOTWID, TOPWID, HLINK_INIT, CHAN_SS, CHMann !Channel parms from table\n  real,  dimension(50)     :: TOPWIDCC, NCC    !channnel params of compound\n  real,  dimension(50)     :: CHANN_K ! Channel infiltration param\n  integer :: i,j,k, ll, count\n\n  integer, allocatable, dimension(:) :: tmp_int\n  real, allocatable, dimension(:) :: tmp_real\n  integer, allocatable, dimension(:) :: buf\n  real, allocatable, dimension(:) :: tmpRESHT\n  integer :: new_start_i, new_start_j, new_end_i, new_end_j\n\n#ifdef OUTPUT_CHAN_CONN\n  real :: connCalcTimeStart, connCalcTimeEnd\n#endif\n!------------------------------------------------------------------------\n!DJG Routing Processing\n!------------------------------------------------------------------------\n!DJG IF/then to get routing terrain fields if either routing module is\n!DJG   activated\n\n  if(nlst(did)%rtFlag .eq. 0) return\n\n  if (nlst(did)%SUBRTSWCRT  .eq.1 .or. &\n       nlst(did)%OVRTSWCRT   .eq.1 .or. &\n       nlst(did)%GWBASESWCRT .ne. 0) then\n\n     if(nlst(did)%channel_only       .eq. 0 .and. &\n          nlst(did)%channelBucket_only .eq. 0        ) then\n\n#ifdef HYDRO_D\n        print *, \"Terrain routing initialization...\"\n#endif\n\n        call READ_ROUTING_seq  (  &\n             rt_domain(did)%IXRT,rt_domain(did)%JXRT,rt_domain(did)%ELRT,rt_domain(did)%overland%streams_and_lakes%ch_netrt, &\n             rt_domain(did)%CH_LNKRT, &\n             rt_domain(did)%LKSATFAC,trim(nlst(did)%route_topo_f),&\n             nlst(did)%route_chan_f,nlst(did)%geo_finegrid_flnm  ,  &\n             rt_domain(did)%OVROUGHRTFAC,rt_domain(did)%RETDEPRTFAC, rt_domain(did)%IMPERVFRAC, &\n             nlst(did)%channel_option, nlst(did)%udmp_opt, nlst(did)%imperv_adj)\n\n\n   !yw CALL READ_ROUTING_old(rt_domain(did)%IXRT,rt_domain(did)%JXRT,rt_domain(did)%ELRT,rt_domain(did)%overland%streams_and_lakes%ch_netrt, &\n\n        if (nlst(did)%CHANRTSWCRT.eq.1 .or. nlst(did)%CHANRTSWCRT .eq. 2) then  !IF/then for channel routing\n\n#ifdef MPP_LAND\n           call MPP_READ_CHROUTING_new(    &\n#else\n                call READ_CHROUTING1( &  !! NOT TESTED\n#endif\n             rt_domain(did)%IXRT,         rt_domain(did)%JXRT,       &\n             rt_domain(did)%ELRT,         rt_domain(did)%overland%streams_and_lakes%ch_netrt,        &\n             rt_domain(did)%CH_LNKRT,     rt_domain(did)%overland%streams_and_lakes%lake_mask, &\n             rt_domain(did)%FROM_NODE,    rt_domain(did)%TO_NODE, &\n             rt_domain(did)%TYPEL,        rt_domain(did)%ORDER, &\n             rt_domain(did)%MAXORDER,     rt_domain(did)%NLINKS, &\n             rt_domain(did)%NLAKES,       rt_domain(did)%CHANLEN, &\n             rt_domain(did)%MannN,        rt_domain(did)%So, &\n             rt_domain(did)%ChSSlp,       rt_domain(did)%Bw, &\n             rt_domain(did)%Tw,                              &\n             rt_domain(did)%Tw_CC,                           &\n             rt_domain(did)%n_CC,                            &\n             rt_domain(did)%ChannK,                          &\n             rt_domain(did)%HRZAREA,      rt_domain(did)%LAKEMAXH, &\n             rt_domain(did)%WEIRH,        rt_domain(did)%WEIRC, &\n             rt_domain(did)%WEIRL,        rt_domain(did)%DAML, &\n             rt_domain(did)%ORIFICEC,     rt_domain(did)%ORIFICEA, &\n             rt_domain(did)%ORIFICEE,                           &\n             nlst(did)%reservoir_type_specified, rt_domain(did)%reservoir_type, &\n             nlst(did)%reservoir_parameter_file,    &\n             rt_domain(did)%LATLAKE,      rt_domain(did)%LONLAKE, &\n             rt_domain(did)%ELEVLAKE,     rt_domain(did)%overland%properties%distance_to_neighbor, &\n             rt_domain(did)%ZELEV,        rt_domain(did)%LAKENODE,        &\n             rt_domain(did)%CH_NETLNK,    rt_domain(did)%CHANXI,          &\n             rt_domain(did)%CHANYJ,       rt_domain(did)%CHLAT,           &\n             rt_domain(did)%CHLON,        nlst(did)%channel_option,    &\n             rt_domain(did)%latval,       rt_domain(did)%lonval,          &\n             rt_domain(did)%STRMFRXSTPTS, nlst(did)%geo_finegrid_flnm, &\n             nlst(did)%route_lake_f, rt_domain(did)%LAKEIDM,nlst(did)%UDMP_OPT   & !! no comma\n#ifdef MPP_LAND\n                ,rt_domain(did)%g_IXRT,      rt_domain(did)%g_JXRT      &\n                ,rt_domain(did)%gnlinks,     rt_domain(did)%GCH_NETLNK  &\n                ,rt_domain(did)%map_l2g,     rt_domain(did)%link_location, &\n                rt_domain(did)%yw_mpp_nlinks,rt_domain(did)%lake_index, &\n                rt_domain(did)%nlinks_index &\n#endif\n             )\n\n      end if  !! CHANRTSWCRT 1 or 2\n\n   end if  !! neither channel_only nor channelBucket_only\n\n\n   if((nlst(did)%CHANRTSWCRT    .eq. 1 .or. nlst(did)%CHANRTSWCRT    .eq. 2) .and. &\n      (nlst(did)%channel_option .eq. 1 .or. nlst(did)%channel_option .eq. 2)        ) then\n      call read_routelink( &\n           rt_domain(did)%TO_NODE,       rt_domain(did)%TYPEL,      &\n           rt_domain(did)%ORDER,         rt_domain(did)%MAXORDER,   &\n           rt_domain(did)%NLAKES,        rt_domain(did)%MUSK,       &\n           rt_domain(did)%MUSX,                                     &\n           rt_domain(did)%QLINK,         rt_domain(did)%CHANLEN,    &\n           rt_domain(did)%MannN,         rt_domain(did)%So,         &\n           rt_domain(did)%ChSSlp,        rt_domain(did)%Bw,         &\n           rt_domain(did)%Tw,                                       &\n           rt_domain(did)%Tw_CC,                                    &\n           rt_domain(did)%n_CC,                                     &\n           rt_domain(did)%ChannK,                                   &\n           rt_domain(did)%LAKEIDA,       rt_domain(did)%HRZAREA,    &\n           rt_domain(did)%LAKEMAXH,      rt_domain(did)%WEIRH,      &\n           rt_domain(did)%WEIRC,         rt_domain(did)%WEIRL,      &\n           rt_domain(did)%DAML,                                     &\n           rt_domain(did)%ORIFICEC,      rt_domain(did)%ORIFICEA,   &\n           rt_domain(did)%ORIFICEE,                                 &\n           nlst(did)%reservoir_type_specified,                      &\n           rt_domain(did)%reservoir_type,                           &\n           nlst(did)%reservoir_parameter_file,                      &\n           rt_domain(did)%LATLAKE,                                  &\n           rt_domain(did)%LONLAKE,       rt_domain(did)%ELEVLAKE,   &\n           rt_domain(did)%LAKEIDM,       rt_domain(did)%LAKEIDX,    &\n           nlst(did)%route_link_f,       nlst(did)%route_lake_f, &\n           rt_domain(did)%ZELEV,         rt_domain(did)%CHLAT,      &\n           rt_domain(did)%CHLON,         rt_domain(did)%NLINKSL,    &\n           rt_domain(did)%LINKID,        rt_domain(did)%GNLINKSL,   &\n           rt_domain(did)%NLINKS,        rt_domain(did)%gages,      &\n           rt_domain(did)%gageMiss                                   )\n   end if\n\n   NLAKES_total = rt_domain(did)%NLAKES\n\n   do lake_index = 1, NLAKES_total\n     nullify(rt_domain(did)%reservoirs(lake_index)%ptr)\n\n   end do\n\n   ! For loop to cycle array of pointers to reservoirs\n   do lake_index = 1, NLAKES_total\n\n       if (rt_domain(did)%reservoir_type(lake_index) == 1) then\n          allocate( levelpool :: rt_domain(did)%reservoirs(lake_index)%ptr)\n\n       else if (rt_domain(did)%reservoir_type(lake_index) == 2 .and. nlst(did)%reservoir_persistence_usgs) then\n          allocate(persistence_levelpool_hybrid :: rt_domain(did)%reservoirs(lake_index)%ptr)\n\n       else if (rt_domain(did)%reservoir_type(lake_index) == 3 .and. nlst(did)%reservoir_persistence_usace) then\n          allocate(persistence_levelpool_hybrid :: rt_domain(did)%reservoirs(lake_index)%ptr)\n\n       else if (rt_domain(did)%reservoir_type(lake_index) == 4 .and. nlst(did)%reservoir_rfc_forecasts) then\n          allocate(rfc_forecasts :: rt_domain(did)%reservoirs(lake_index)%ptr)\n\n       else if (rt_domain(did)%reservoir_type(lake_index) == 5 .and. nlst(did)%reservoir_rfc_forecasts) then\n          allocate(rfc_forecasts :: rt_domain(did)%reservoirs(lake_index)%ptr)\n\n       else\n          allocate( levelpool :: rt_domain(did)%reservoirs(lake_index)%ptr)\n\n       end if\n\n       ! Dynamically type reservoir to initialize.\n       select type (reservoir => rt_domain(did)%reservoirs(lake_index)%ptr)\n\n          type is (levelpool)\n               call reservoir%init(                               &\n                     rt_domain(did)%RESHT(lake_index),            &\n                     rt_domain(did)%HRZAREA(lake_index),          &\n                     rt_domain(did)%WEIRH(lake_index),            &\n                     rt_domain(did)%WEIRC(lake_index),            &\n                     rt_domain(did)%WEIRL(lake_index),            &\n                     rt_domain(did)%DAML(lake_index),             &\n                     rt_domain(did)%ORIFICEE(lake_index),         &\n                     rt_domain(did)%ORIFICEC(lake_index),         &\n                     rt_domain(did)%ORIFICEA(lake_index),         &\n                     rt_domain(did)%LAKEMAXH(lake_index),         &\n                     rt_domain(did)%LAKEIDM(lake_index),          &\n                     nlst(did)%lake_option)\n\n          type is (persistence_levelpool_hybrid)\n              call reservoir%init(                                     &\n                    rt_domain(did)%RESHT(lake_index),                  &\n                    rt_domain(did)%HRZAREA(lake_index),                &\n                    rt_domain(did)%WEIRH(lake_index),                  &\n                    rt_domain(did)%WEIRC(lake_index),                  &\n                    rt_domain(did)%WEIRL(lake_index),                  &\n                    rt_domain(did)%DAML(lake_index),                   &\n                    rt_domain(did)%ORIFICEE(lake_index),               &\n                    rt_domain(did)%ORIFICEC(lake_index),               &\n                    rt_domain(did)%ORIFICEA(lake_index),               &\n                    rt_domain(did)%LAKEMAXH(lake_index),               &\n                    rt_domain(did)%ELEVLAKE(lake_index),               &\n                    rt_domain(did)%LAKEIDM(lake_index),                &\n                    rt_domain(did)%reservoir_type(lake_index),         &\n                    nlst(did)%reservoir_parameter_file,                &\n                    nlst(did)%startdate(1:19),                         &\n                    nlst(did)%reservoir_usgs_timeslice_path,           &\n                    nlst(did)%reservoir_usace_timeslice_path,          &\n                    nlst(did)%reservoir_observation_lookback_hours,    &\n                    nlst(did)%reservoir_observation_update_time_interval_seconds)\n\n          type is (rfc_forecasts)\n              call reservoir%init(                                      &\n                    rt_domain(did)%RESHT(lake_index),                   &\n                    rt_domain(did)%HRZAREA(lake_index),                 &\n                    rt_domain(did)%WEIRH(lake_index),                   &\n                    rt_domain(did)%WEIRC(lake_index),                   &\n                    rt_domain(did)%WEIRL(lake_index),                   &\n                    rt_domain(did)%DAML(lake_index),                    &\n                    rt_domain(did)%ORIFICEE(lake_index),                &\n                    rt_domain(did)%ORIFICEC(lake_index),                &\n                    rt_domain(did)%ORIFICEA(lake_index),                &\n                    rt_domain(did)%LAKEMAXH(lake_index),                &\n                    rt_domain(did)%ELEVLAKE(lake_index),                &\n                    rt_domain(did)%LAKEIDM(lake_index),                 &\n                    rt_domain(did)%reservoir_type(lake_index),          &\n                    nlst(did)%reservoir_parameter_file,                 &\n                    nlst(did)%startdate(1:19),                          &\n                    nlst(did)%reservoir_rfc_forecasts_time_series_path, &\n                    nlst(did)%reservoir_rfc_forecasts_lookback_hours)\n\n           end select\n\n   end do\n\n   !ADCHANGE: Add lake reach output\n#ifdef HYDRO_D\n     if(nlst(did)%UDMP_OPT .eq. 1) then\n        call output_lake_types( rt_domain(did)%GNLINKSL, rt_domain(did)%LINKID, rt_domain(did)%TYPEL )\n     endif\n#endif\n\n#ifdef OUTPUT_CHAN_CONN\n#ifdef MPP_LAND\n     connCalcTimeEnd = MPI_Wtime()\n#else\n     call cpu_time(connCalcTimeEnd)\n#endif\n     if ((nlst(did)%CHANRTSWCRT .eq. 1) .and. (nlst(did)%channel_option .eq. 3)) then\n        call output_chan_connectivity(       &\n             rt_domain(did)%CHLAT,     &   !! Channel grid lat\n             rt_domain(did)%CHLON,     &   !! Channel grid lat\n             rt_domain(did)%CHANLEN,   &   !! The distance between channel grid centers in m.\n             rt_domain(did)%FROM_NODE, &   !! Index of a given cell and ...\n             rt_domain(did)%TO_NODE,   &   !!   ... the index which it flows to.\n             rt_domain(did)%CHANXI,    &   !! Index on fine/routing\n             rt_domain(did)%CHANYJ,    &   !!   grid of grid cells.\n             rt_domain(did)%TYPEL,     &   !! Link type\n             rt_domain(did)%LAKENODE   &   !! Lake indexing\n             )\n     end if\n\n     !if(my_id .eq. io_id) &\n     print '(\"Time to calculate channel connectivity= \",f6.3,\" seconds.\")', &\n          connCalcTimeEnd-connCalcTimeStart\n     call exit(17)  !! bail if you're just calculating output connectivity.\n#endif\n     ! end OUTPUT_CHAN_CONN\n\n\n     ! The UDMP_ini effectively sets the nhd gw bucket area (that field is not used from the file)\n     !   this may be the only dependence of the nhd_routing on the UDMAPING in channelBucket_only\n     if(nlst(did)%channel_only .eq. 0) then\n\n        if(nlst(did)%UDMP_OPT .eq. 1) then\n           ! get NHDPLUS mapping function.\n           !          call UDMP_ini(rt_domain(did)%GNLINKSL,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%CH_LNKRT , &\n           call UDMP_ini( rt_domain(did)%GNLINKSL, rt_domain(did)%ixrt,      &\n                rt_domain(did)%jxrt,     rt_domain(did)%overland%streams_and_lakes%ch_netrt , &\n                nlst(did)%OVRTSWCRT,  nlst(did)%SUBRTSWCRT,  &\n                rt_domain(did)%overland%properties%distance_to_neighbor(:,:,9)                         )\n#ifdef HYDRO_D\n           write(6,*) \"after UDMP_ini \"\n           call flush(6)\n#endif\n        endif\n\n     end if ! end not channel_only\n\n     if ( (nlst(did)%CHANRTSWCRT .eq. 1) .and. &\n          (nlst(did)%channel_option .eq. 1 .or. nlst(did)%channel_option .eq. 2) ) then\n#ifdef MPP_LAND\n\n        if(nlst(did)%UDMP_OPT .eq. 1) then\n           ! NHDPLUS\n           rt_domain(did)%LNLINKSL = LNUMRSL\n           allocate(rt_domain(did)%LLINKID(rt_domain(did)%LNLINKSL))\n           do k = 1,LNUMRSL\n              rt_domain(did)%LLINKID(k) = LUDRSL(k)%myid\n           end do\n\n        else\n\n           allocate (buf(rt_domain(did)%GNLINKS) )\n           buf = -99\n           do j = 1, rt_domain(did)%jxrt\n              do i = 1, rt_domain(did)%ixrt\n                 if( .not. ( (i .eq. 1 .and. left_id .ge. 0) .or. (i .eq. rt_domain(did)%ixrt .and. right_id .ge. 0) .or.  &\n                      (j .eq. 1 .and. down_id .ge. 0) .or. (j .eq. rt_domain(did)%jxrt .and. up_id .ge. 0)    )   ) then\n                    if(rt_domain(did)%CH_LNKRT(i,j) .gt. 0) then\n                       k = rt_domain(did)%CH_LNKRT(i,j)\n                       buf(k) = k\n                    endif\n                 endif\n              end do\n           end do\n\n           rt_domain(did)%LNLINKSL = 0\n           do k = 1, rt_domain(did)%GNLINKS\n              if(buf(k) .gt. 0) then\n                 rt_domain(did)%LNLINKSL = rt_domain(did)%LNLINKSL + 1\n              endif\n           end do\n\n#ifdef HYDRO_D\n           write(6,*) \"LNLINKSL, NLINKS, GNLINKS =\",rt_domain(did)%LNLINKSL,rt_domain(did)%NLINKSL,rt_domain(did)%GNLINKSL\n           call flush(6)\n#endif\n\n           allocate(rt_domain(did)%LLINKID(rt_domain(did)%LNLINKSL))\n\n           k = 0\n           do i = 1, rt_domain(did)%GNLINKS\n              if(buf(i) .gt. 0) then\n                 k = k + 1\n                 rt_domain(did)%LLINKID(k) = buf(i)\n              endif\n           end do\n\n           if(allocated(buf)) deallocate(buf)\n\n        endif  ! end if block for UDMP_OPT\n\n        !-------------------------------------------\n        ! Z.Cui: Changed new_start_i to 0, otherwise, it crashes with\n        !        an out-of-bounds error when the '-check all' is enabled\n        !        for the ifort compiler.\n        !        The reason is that CH_LNKRT and CH_LNKRT_SL is defined as\n        !        1:IXRT and 1:JXRT. Now new_start_i is changed to start from 1.\n        !-------------------------------------------\n        new_start_i = 1; new_start_j = 1\n        new_end_i = rt_domain(did)%ixrt; new_end_j = rt_domain(did)%jxrt\n\n        if(left_id .ge. 0) new_start_i = 1\n        if(right_id .ge. 0) new_end_i = rt_domain(did)%ixrt - 1\n        if(down_id .ge. 0) new_start_j = 2\n        if(up_id .ge. 0) new_end_j = rt_domain(did)%jxrt - 1\n\n                ! The following loops are replaced by a hashtable-based algorithm\n        ! do k = 1, rt_domain(did)%LNLINKSL\n        !    do j = new_start_j, new_end_j\n        !       do i = new_start_i, new_end_i\n        !          if(rt_domain(did)%CH_LNKRT(i,j) .eq. rt_domain(did)%LLINKID(k) ) then\n        !             rt_domain(did)%CH_LNKRT_SL(i,j) = k   !! mapping\n        !          endif\n        !       end  do\n        !    end do\n        ! end do\n\n        block\n          type(hash_t) :: hash_table\n          integer(kind=int64) :: val,ii,jj\n          logical :: found\n\n          call hash_table%set_all_idx(rt_domain(did)%LLINKID, rt_domain(did)%LNLINKSL)\n          do jj = new_start_j, new_end_j\n             do ii = new_start_i, new_end_i\n                call hash_table%get(rt_domain(did)%CH_LNKRT(ii,jj), val, found)\n                if(found .eqv. .true.) then\n                   rt_domain(did)%CH_LNKRT_SL(ii,jj) = val\n                end if\n             end do\n          end do\n          call hash_table%clear()\n        end block\n\n        call getLocalIndx(rt_domain(did)%gnlinksl,rt_domain(did)%LINKID, rt_domain(did)%LLINKID)\n\n        call getToInd(rt_domain(did)%LINKID,rt_domain(did)%to_node,rt_domain(did)%toNodeInd,rt_domain(did)%nToInd,rt_domain(did)%gtoNode)\n#else\n        do k = 1, rt_domain(did)%NLINKSL\n           do j = 1, rt_domain(did)%jxrt\n              do i = 1, rt_domain(did)%ixrt\n                 if(rt_domain(did)%CH_LNKRT(i,j) .eq. rt_domain(did)%LINKID(k) ) then\n                    rt_domain(did)%CH_LNKRT_SL(i,j) = k   !! mapping\n                 endif\n              end do\n           end do\n        end do\n#endif\n\n!!$        ! use gage information in RouteLink like strmfrxstpts\n!!$        rt_domain(did)%STRMFRXSTPTS = -9999  !! existing info useless for link-based routing\n!!$        count = 1\n!!$        do ll=1,rt_domain(did)%NLINKSL\n!!$           if(trim(rt_domain(did)%gages(ll)) .ne. trim(rt_domain(did)%gageMiss)) then\n!!$              rt_domain(did)%STRMFRXSTPTS(count) = ll\n!!$              count = count + 1\n!!$           end if\n!!$        end do\n\n     endif ! end of if (nlst_rt(did)%channel_option .eq. 1 .or. nlst_rt(did)%channel_option .eq. 2)\n\n  end if ! end of if (nlst_rt(did)%SUBRTSWCRT  .eq.1 .or. &    nlst_rt(did)%OVRTSWCRT   .eq.1 .or. &\n!            nlst_rt(did)%GWBASESWCRT .ne. 0) then\n\n\n\n!yw       allocate(tmp_int(rt_domain(did)%GNLINKS))\n!yw       allocate(tmp_real(rt_domain(did)%GNLINKS))\n\n\n  if(nlst(did)%channel_only       .eq. 0 .and. &\n       nlst(did)%channelBucket_only .eq. 0        ) then\n\n     !DJG Temporary hardwire of RETDEPRT,RETDEP_CHAN\n     !DJG    will later make this a function of SOLTYP and VEGTYP\n     !            OVROUGHRT(i,j) = 0.01\n\n     rt_domain(did)%overland%properties%retention_depth = 0.001   ! units (mm)\n     rt_domain(did)%RETDEP_CHAN = 0.001\n\n\n     !DJG Need to insert call for acquiring routing fields here...\n     !DJG     include as a subroutine in module module_Noahlsm_wrfcode_input.F\n     !DJG  Calculate terrain slopes 'SOXRT,SOYRT' from subgrid elevation 'ELRT'\n\n     rt_domain(did)%overland%properties%surface_slope = -999\n     Vmax = 0.0\n     do j=2,rt_domain(did)%JXRT-1\n        do i=2,rt_domain(did)%IXRT-1\n           rt_domain(did)%overland%properties%surface_slope_x(i,j)=(rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i+1,j))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,3)\n           rt_domain(did)%overland%properties%surface_slope_y(i,j)=(rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i,j+1))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,1)\n           !DJG Introduce reduction in retention depth as a linear function of terrain slope\n           if (nlst(did)%RT_OPTION.eq.2) then\n              if (rt_domain(did)%overland%properties%surface_slope_x(i,j).gt.rt_domain(did)%overland%properties%surface_slope_y(i,j)) then\n                 Vmax=rt_domain(did)%overland%properties%surface_slope_x(i,j)\n              else\n                 Vmax=rt_domain(did)%overland%properties%surface_slope_y(i,j)\n              end if\n\n              if (Vmax.gt.0.1) then\n                 rt_domain(did)%overland%properties%retention_depth(i,j)=0.\n              else\n                 rt_domain(did)%RETDEPFRAC=Vmax/0.1\n                 rt_domain(did)%overland%properties%retention_depth(i,j)=rt_domain(did)%overland%properties%retention_depth(i,j)*(1.-rt_domain(did)%RETDEPFRAC)\n                 if (rt_domain(did)%overland%properties%retention_depth(i,j).lt.0.) rt_domain(did)%overland%properties%retention_depth(i,j)=0.\n              end if\n           end if\n\n           rt_domain(did)%overland%properties%surface_slope(i,j,1) = &\n                (rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i,j+1))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,1)\n           rt_domain(did)%overland%properties%max_surface_slope_index(i,j,1) = i\n           rt_domain(did)%overland%properties%max_surface_slope_index(i,j,2) = j + 1\n           rt_domain(did)%overland%properties%max_surface_slope_index(i,j,3) = 1\n           Vmax = rt_domain(did)%overland%properties%surface_slope(i,j,1)\n\n           rt_domain(did)%overland%properties%surface_slope(i,j,2) = &\n                (rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i+1,j+1))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,2)\n           if(rt_domain(did)%overland%properties%surface_slope(i,j,2) .gt. Vmax ) then\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,1) = i + 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,2) = j + 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,3) = 2\n              Vmax = rt_domain(did)%overland%properties%surface_slope(i,j,2)\n           end if\n\n           rt_domain(did)%overland%properties%surface_slope(i,j,3) = &\n                (rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i+1,j))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,3)\n           if(rt_domain(did)%overland%properties%surface_slope(i,j,3) .gt. Vmax ) then\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,1) = i + 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,2) = j\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,3) = 3\n              Vmax = rt_domain(did)%overland%properties%surface_slope(i,j,3)\n           end if\n\n           rt_domain(did)%overland%properties%surface_slope(i,j,4) = &\n                (rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i+1,j-1))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,4)\n           if(rt_domain(did)%overland%properties%surface_slope(i,j,4) .gt. Vmax ) then\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,1) = i + 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,2) = j - 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,3) = 4\n              Vmax = rt_domain(did)%overland%properties%surface_slope(i,j,4)\n           end if\n\n           rt_domain(did)%overland%properties%surface_slope(i,j,5) = &\n                (rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i,j-1))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,5)\n           if(rt_domain(did)%overland%properties%surface_slope(i,j,5) .gt. Vmax ) then\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,1) = i\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,2) = j - 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,3) = 5\n              Vmax = rt_domain(did)%overland%properties%surface_slope(i,j,5)\n           end if\n\n           rt_domain(did)%overland%properties%surface_slope(i,j,6) = &\n                (rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i-1,j-1))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,6)\n           if(rt_domain(did)%overland%properties%surface_slope(i,j,6) .gt. Vmax ) then\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,1) = i - 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,2) = j - 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,3) = 6\n              Vmax = rt_domain(did)%overland%properties%surface_slope(i,j,6)\n           end if\n\n           rt_domain(did)%overland%properties%surface_slope(i,j,7) = &\n                (rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i-1,j))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,7)\n           if(rt_domain(did)%overland%properties%surface_slope(i,j,7) .gt. Vmax ) then\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,1) = i - 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,2) = j\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,3) = 7\n              Vmax = rt_domain(did)%overland%properties%surface_slope(i,j,7)\n           end if\n\n           rt_domain(did)%overland%properties%surface_slope(i,j,8) = &\n                (rt_domain(did)%ELRT(i,j)-rt_domain(did)%ELRT(i-1,j+1))/rt_domain(did)%overland%properties%distance_to_neighbor(i,j,8)\n           if(rt_domain(did)%overland%properties%surface_slope(i,j,8) .gt. Vmax ) then\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,1) = i - 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,2) = j + 1\n              rt_domain(did)%overland%properties%max_surface_slope_index(i,j,3) = 8\n              Vmax = rt_domain(did)%overland%properties%surface_slope(i,j,8)\n           end if\n\n           !DJG Introduce reduction in retention depth as a linear function of terrain slope\n           if (nlst(did)%RT_OPTION.eq.1) then\n              if (Vmax.gt.0.75) then\n                 rt_domain(did)%overland%properties%retention_depth(i,j)=0.\n              else\n                 rt_domain(did)%RETDEPFRAC=Vmax/0.75\n                 rt_domain(did)%overland%properties%retention_depth(i,j)=rt_domain(did)%overland%properties%retention_depth(i,j)*(1.-rt_domain(did)%RETDEPFRAC)\n                 if (rt_domain(did)%overland%properties%retention_depth(i,j).lt.0.) rt_domain(did)%overland%properties%retention_depth(i,j)=0.\n              end if\n           end if\n        end do\n     end do\n\n     !Apply impervious adjustment to retdeprt (AD)\n     if (nlst(did)%imperv_adj .ne. 0) then\n       rt_domain(did)%overland%properties%retention_depth = rt_domain(did)%overland%properties%retention_depth*(1.-rt_domain(did)%impervfrac)\n     end if\n\n     !Apply calibration scaling factors to sfc roughness and retention depth here...\n     rt_domain(did)%overland%properties%retention_depth = rt_domain(did)%overland%properties%retention_depth * rt_domain(did)%RETDEPRTFAC\n     rt_domain(did)%overland%properties%roughness = rt_domain(did)%overland%properties%roughness * rt_domain(did)%OVROUGHRTFAC\n\n   !ADCHANGE: Moved this channel cell setting from OV_RTNG so it is outside\n   !of overland routine (frequently called) and time loop.\n   !Force channel retention depth to be 5mm.\n   ! JLM: for DWJ I'm leaving this next line for you to verify as\n   !      it's the one I translated to the following line,\n   !where (rt_domain(did)%CH_NETRT .ge. 0) rt_domain(did)%RETDEPRT = 5.0\n     where (rt_domain(did)%overland%streams_and_lakes%ch_netrt .ge. 0) &\n          rt_domain(did)%overland%properties%retention_depth = 5.0\n\n   ! calculate the slope for boundary\n#ifdef MPP_LAND\n     if(right_id .lt. 0) rt_domain(did)%overland%properties%surface_slope_x(rt_domain(did)%IXRT,:)= &\n        rt_domain(did)%overland%properties%surface_slope_x(rt_domain(did)%IXRT-1,:)\n     if(left_id  .lt. 0) rt_domain(did)%overland%properties%surface_slope_x(1,:)=rt_domain(did)%overland%properties%surface_slope_x(2,:)\n     if(up_id    .lt. 0) rt_domain(did)%overland%properties%surface_slope_y(:,rt_domain(did)%JXRT)= &\n          rt_domain(did)%overland%properties%surface_slope_y(:,rt_domain(did)%JXRT-1)\n     if(down_id  .lt. 0) rt_domain(did)%overland%properties%surface_slope_y(:,1)=rt_domain(did)%overland%properties%surface_slope_y(:,2)\n#else\n     rt_domain(did)%overland%properties%surface_slope_x(rt_domain(did)%IXRT,:)=rt_domain(did)%overland%properties%surface_slope_x(rt_domain(did)%IXRT-1,:)\n     rt_domain(did)%overland%properties%surface_slope_x(1,:)=rt_domain(did)%overland%properties%surface_slope_x(2,:)\n     rt_domain(did)%overland%properties%surface_slope_y(:,rt_domain(did)%JXRT)=rt_domain(did)%overland%properties%surface_slope_y(:,rt_domain(did)%JXRT-1)\n     rt_domain(did)%overland%properties%surface_slope_y(:,1)=rt_domain(did)%overland%properties%surface_slope_y(:,2)\n#endif\n\n#ifdef MPP_LAND\n   ! communicate the value to\n     call MPP_LAND_COM_REAL(rt_domain(did)%overland%properties%retention_depth,rt_domain(did)%IXRT,rt_domain(did)%JXRT,99)\n     call MPP_LAND_COM_REAL(rt_domain(did)%overland%properties%roughness,rt_domain(did)%IXRT,rt_domain(did)%JXRT,99)\n     call MPP_LAND_COM_REAL(rt_domain(did)%overland%properties%surface_slope_x,rt_domain(did)%IXRT,rt_domain(did)%JXRT,99)\n     call MPP_LAND_COM_REAL(rt_domain(did)%overland%properties%surface_slope_y,rt_domain(did)%IXRT,rt_domain(did)%JXRT,99)\n     do i = 1, 8\n        call MPP_LAND_COM_REAL(rt_domain(did)%overland%properties%surface_slope(:,:,i),rt_domain(did)%IXRT,rt_domain(did)%JXRT,99)\n     end do\n     do i = 1, 3\n        call MPP_LAND_COM_INTEGER(rt_domain(did)%overland%properties%max_surface_slope_index(:,:,i),rt_domain(did)%IXRT,rt_domain(did)%JXRT,99)\n     end do\n#endif\n\n  end if ! end of neither channel_only nor channelBucket_only\n\n  if(nlst(did)%UDMP_OPT .eq. 1) then\n\n     allocate (rt_domain(did)%qout_gwsubbas (rt_domain(did)%nlinksL))\n     rt_domain(did)%qout_gwsubbas = 0\n     ! use different baseflow for NHDPlus\n     if (nlst(did)%GWBASESWCRT.ge.1) then\n        rt_domain(did)%numbasns = rt_domain(did)%NLINKSL\n        RT_DOMAIN(did)%gnumbasns = rt_domain(did)%gNLINKSL\n\n        allocate (rt_domain(did)%z_gwsubbas (rt_domain(did)%numbasns  ))\n        allocate (rt_domain(did)%nhdBuckMask(rt_domain(did)%numbasns  ))  ! default is -999\n\n        allocate (rt_domain(did)%qin_gwsubbas (rt_domain(did)%numbasns))\n        allocate (rt_domain(did)%gwbas_pix_ct (rt_domain(did)%numbasns))\n        allocate (rt_domain(did)%ct2_bas (rt_domain(did)%numbasns))\n        allocate (rt_domain(did)%bas_pcp (rt_domain(did)%numbasns))\n        allocate (rt_domain(did)%gw_buck_coeff (rt_domain(did)%numbasns))\n        allocate (rt_domain(did)%bas_id (rt_domain(did)%numbasns))\n        allocate (rt_domain(did)%gw_buck_exp(rt_domain(did)%numbasns))\n        allocate (rt_domain(did)%z_max (rt_domain(did)%numbasns))\n        allocate (rt_domain(did)%basns_area (rt_domain(did)%numbasns))\n\n        if(nlst(did)%bucket_loss .eq. 1) then\n           allocate(rt_domain(did)%qloss_gwsubbas(rt_domain(did)%numbasns))\n           allocate(rt_domain(did)%gw_buck_loss(rt_domain(did)%numbasns))\n\n           rt_domain(did)%qloss_gwsubbas = 0\n           rt_domain(did)%gw_buck_loss = 0\n        endif\n\n        rt_domain(did)%qin_gwsubbas = 0\n        rt_domain(did)%z_gwsubbas = 0\n        rt_domain(did)%gwbas_pix_ct = 0\n        rt_domain(did)%bas_pcp = 0\n\n        rt_domain(did)%gw_buck_coeff = 0.04\n        rt_domain(did)%gw_buck_exp  = 0.2\n        rt_domain(did)%z_max = 0.1\n\n        !Temporary hardwire...\n        rt_domain(did)%z_gwsubbas = 0.05   ! This gets updated with spun-up GW level in GWBUCKPARM.TBL\n\n        call readBucket_nhd(trim(nlst(did)%GWBUCKPARM_file), rt_domain(did)%numbasns, &\n             rt_domain(did)%gw_buck_coeff, rt_domain(did)%gw_buck_exp, rt_domain(did)%gw_buck_loss, &\n             rt_domain(did)%z_max, rt_domain(did)%z_gwsubbas, rt_domain(did)%LINKID(1:rt_domain(did)%numbasns),  &\n             rt_domain(did)%nhdBuckMask )\n\n      !ADCHANGE: Added in read for z_init from GWBUCKPARM. Units coming in are mm but z_gwsubbas is in m\n      !for UDMP=1 so we convert units.\n        rt_domain(did)%z_gwsubbas = rt_domain(did)%z_gwsubbas/1000.\n\n#ifdef HYDRO_D\n        write(6,*) \"finish readBucket_nhd \"\n        call flush(6)\n#endif\n     endif\n\n  else\n\n   !---------------------------------------------------------------------\n   !DJG  If GW/Baseflow activated...Read in req'd fields...\n   !----------------------------------------------------------------------\n     if (nlst(did)%GWBASESWCRT.ge.1) then\n        if (nlst(did)%GWBASESWCRT.eq.1.or.nlst(did)%GWBASESWCRT.eq.2 .or. nlst(did)%GWBASESWCRT.ge.4) then\n#ifdef HYDRO_D\n           print *, \"new Simple GW-Bucket Scheme selected, retrieving files...\"\n#endif\n#ifdef MPP_LAND\n           call MPP_READ_SIMP_GW(              &\n#else\n                call READ_SIMP_GW(                  &\n#endif\n                rt_domain(did)%IX,rt_domain(did)%JX,rt_domain(did)%IXRT,&\n                rt_domain(did)%JXRT,rt_domain(did)%GWSUBBASMSK,nlst(did)%gwbasmskfil,&\n                rt_domain(did)%gw_strm_msk,rt_domain(did)%numbasns,rt_domain(did)%overland%streams_and_lakes%ch_netrt,nlst(did)%AGGFACTRT)\n\n\n           call SIMP_GW_IND(rt_domain(did)%ix,rt_domain(did)%jx,rt_domain(did)%GWSUBBASMSK,  &\n                rt_domain(did)%numbasns,rt_domain(did)%gnumbasns,rt_domain(did)%basnsInd)\n\n#ifdef HYDRO_D\n           write(6,*) \"rt_domain(did)%gnumbasns, rt_domain(did)%numbasns, \", rt_domain(did)%gnumbasns , rt_domain(did)%numbasns\n\n#endif\n#ifdef MPP_LAND\n           call collectSizeInd(rt_domain(did)%numbasns)\n#endif\n\n           call get_gw_strm_msk_lind (rt_domain(did)%IXRT, rt_domain(did)%JXRT, rt_domain(did)%gw_strm_msk,&\n                rt_domain(did)%numbasns,rt_domain(did)%basnsInd,rt_domain(did)%gw_strm_msk_lind)\n\n           allocate (rt_domain(did)%qout_gwsubbas (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%qin_gwsubbas (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%z_gwsubbas (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%gwbas_pix_ct (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%ct2_bas (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%bas_pcp (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%gw_buck_coeff (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%bas_id (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%gw_buck_exp(rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%z_max (rt_domain(did)%numbasns))\n           allocate (rt_domain(did)%basns_area (rt_domain(did)%numbasns))\n\n#ifdef HYDRO_D\n           write(6,*)  \"end Simple GW-Bucket ...\"\n           print *, \"Simple GW-Bucket Scheme selected, retrieving files...\"\n#endif\n\n           !Temporary hardwire...\n           rt_domain(did)%z_gwsubbas = 1.     ! This gets updated with spun-up GW level in GWBUCKPARM.TBL\n\n           call read_GWBUCKPARM(trim(nlst(did)%GWBUCKPARM_file),rt_domain(did)%numbasns,   &\n                rt_domain(did)%gnumbasns, rt_domain(did)%basnsInd, &\n                rt_domain(did)%gw_buck_coeff, rt_domain(did)%gw_buck_exp, rt_domain(did)%gw_buck_loss, &\n                rt_domain(did)%z_max, rt_domain(did)%z_gwsubbas, rt_domain(did)%bas_id, &\n                rt_domain(did)%basns_area)\n\n!!! Determine number of stream pixels per GW basin for distribution...\n#ifdef MPP_LAND\n           call pix_ct_1(rt_domain(did)%gw_strm_msk,rt_domain(did)%ixrt,rt_domain(did)%jxrt,rt_domain(did)%gwbas_pix_ct,rt_domain(did)%numbasns, &\n                rt_domain(did)%gnumbasns,rt_domain(did)%basnsInd)\n#else\n           rt_domain(did)%gwbas_pix_ct = 0.\n         !         do k = 1, rt_domain(did)%numbasns\n         !            bas = rt_domain(did)%basnsInd(k)\n           do i=1,rt_domain(did)%ixrt\n              do j=1,rt_domain(did)%jxrt\n                 if (rt_domain(did)%gw_strm_msk(i,j).gt.0) then\n                    bas = rt_domain(did)%gw_strm_msk(i,j)\n                    rt_domain(did)%gwbas_pix_ct(bas) = &\n                         rt_domain(did)%gwbas_pix_ct(bas)  + 1.0\n                 endif\n              end do\n           end do\n           !         end do\n#endif\n\n#ifdef HYDRO_D\n           print *, \"Starting GW basin levels...\",rt_domain(did)%z_gwsubbas\n#endif\n\n         ! BF gw2d model\n        elseif (nlst(did)%GWBASESWCRT.eq.3) then\n\n           call readGW2d(gw2d(did)%ix, gw2d(did)%jx,     &\n                gw2d(did)%hycond, gw2d(did)%ho, &\n                gw2d(did)%bot, gw2d(did)%poros, &\n                gw2d(did)%ltype, nlst(did)%gwIhShift)\n\n           gw2d(did)%elev = rt_domain(did)%elrt\n\n        end if ! end if (nlst_rt(did)%GWBASESWCRT.eq.1.or.nlst_rt(did)%GWBASESWCRT.eq.2)\n\n     end if ! end if (nlst_rt(did)%GWBASESWCRT.ge.1)\n\n!---------------------------------------------------------------------\n!DJG  End if GW/Baseflow activated...\n!----------------------------------------------------------------------\n  endif   !!! end if block for UDMP_OPT .eq. 1\n\n\n\n!---------------------------------------------------------------------\n!DJG,DNY  If channel routing activated...\n!----------------------------------------------------------------------\n\n  if (nlst(did)%CHANRTSWCRT.eq.1 .or. nlst(did)%CHANRTSWCRT .eq. 2) then\n\n   !---------------------------------------------------------------------\n   !DJG,DNY  Initalize lake and channel heights, this may be overwritten by RESTART\n   !--------------------------------------------------------------------\n     if (nlst(did)%channel_option .eq. 3) then\n#ifdef MPP_LAND\n      ! JLM: Currently compound channel does not work for diffusive wave/gridded channel.\n      ! This conflict of options is caught in Data_Rec/module_namelist.F\n      ! Some of the code for reading/using top-width-necessary params from CHANPARM.TBL are available\n      ! but commented out in the code, since they were a bridge to nowhere.\n        call mpp_CHAN_PARM_INIT (BOTWID,CHANN_K,HLINK_INIT,CHAN_SS,CHMann)  !Read chan parms from table...\n      !call mpp_CHAN_PARM_INIT (BOTWID,TOPWID,HLINK_INIT,CHAN_SS,CHMann,TOPWIDCC,NCC)  !Read chan parms from table...\n#else\n        call CHAN_PARM_INIT (BOTWID,CHANN_K,HLINK_INIT,CHAN_SS,CHMann) !,TOPWIDCC,NCC)  !Read chan parms from table...\n#endif\n     end if\n\n     if (nlst(did)%channel_option .ne. 3) then\n\n#ifdef MPP_LAND\n        if(my_id .eq. io_id) then\n#endif\n           allocate(tmpRESHT(rt_domain(did)%nlakes))\n           tmpRESHT = rt_domain(did)%RESHT\n#ifdef MPP_LAND\n        endif\n#endif\n\n#ifdef MPP_LAND\n        call updateLake_seq(rt_domain(did)%RESHT, rt_domain(did)%NLAKES,tmpRESHT)\n        if(my_id .eq. io_id) then\n           if(allocated(tmpRESHT)) deallocate(tmpRESHT)\n        endif\n#endif\n\n     else       !-- parameterize according to order of diffusion scheme, or if read from hi res file, use its value\n                !--  put condition within the if/then structure, which will assign a value if something is missing in hi res\n\n        do j=1,rt_domain(did)%NLINKS\n\n           if (rt_domain(did)%ORDER(j) .eq. 1) then    !-- smallest stream reach\n              if(rt_domain(did)%Bw(j) .eq. 0.0) then\n                 rt_domain(did)%Bw(j) = BOTWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw(j) .eq. 0.0) then\n                 rt_domain(did)%Tw(j) = TOPWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw_CC(j) .eq. 0.0) then\n                 rt_domain(did)%Tw_CC(j) = TOPWIDCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%n_CC(j) .eq. 0.0) then\n                 rt_domain(did)%n_CC(j) = NCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%ChSSlp(j) .eq. 0.0) then  !if id didn't get set from the hi res file, use the  CHANPARAM\n                 rt_domain(did)%ChSSlp(j) = CHAN_SS(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%MannN(j) .eq. 0.0) then\n                 rt_domain(did)%MannN(j) = CHMann(rt_domain(did)%ORDER(j))\n              endif\n              rt_domain(did)%HLINK(j) = HLINK_INIT(rt_domain(did)%ORDER(j))\n           elseif (rt_domain(did)%ORDER(j) .eq. 2) then\n              if(rt_domain(did)%Bw(j) .eq. 0.0) then\n                 rt_domain(did)%Bw(j) = BOTWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw(j) .eq. 0.0) then\n                 rt_domain(did)%Tw(j) = TOPWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw_CC(j) .eq. 0.0) then\n                 rt_domain(did)%Tw_CC(j) = TOPWIDCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%n_CC(j) .eq. 0.0) then\n                 rt_domain(did)%n_CC(j) = NCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%ChSSlp(j) .eq. 0.0) then  !if id didn't get set from the hi res file, use the  CHANPARAM\n                 rt_domain(did)%ChSSlp(j) = CHAN_SS(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%MannN(j) .eq. 0.0) then\n                 rt_domain(did)%MannN(j) = CHMann(rt_domain(did)%ORDER(j))\n              endif\n              rt_domain(did)%HLINK(j) = HLINK_INIT(rt_domain(did)%ORDER(j))\n           elseif (rt_domain(did)%ORDER(j) .eq. 3) then\n              if(rt_domain(did)%Bw(j) .eq. 0.0) then\n                 rt_domain(did)%Bw(j) = BOTWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw(j) .eq. 0.0) then\n                 rt_domain(did)%Tw(j) = TOPWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw_CC(j) .eq. 0.0) then\n                 rt_domain(did)%Tw_CC(j) = TOPWIDCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%n_CC(j) .eq. 0.0) then\n                 rt_domain(did)%n_CC(j) = NCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%ChSSlp(j) .eq. 0.0) then  !if id didn't get set from the hi res file, use the  CHANPARAM\n                 rt_domain(did)%ChSSlp(j) = CHAN_SS(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%MannN(j) .eq. 0.0) then\n                 rt_domain(did)%MannN(j) = CHMann(rt_domain(did)%ORDER(j))\n              endif\n              rt_domain(did)%HLINK(j) = HLINK_INIT(rt_domain(did)%ORDER(j))\n           elseif (rt_domain(did)%ORDER(j) .eq. 4) then\n              if(rt_domain(did)%Bw(j) .eq. 0.0) then\n                 rt_domain(did)%Bw(j) = BOTWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw(j) .eq. 0.0) then\n                 rt_domain(did)%Tw(j) = TOPWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw_CC(j) .eq. 0.0) then\n                 rt_domain(did)%Tw_CC(j) = TOPWIDCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%n_CC(j) .eq. 0.0) then\n                 rt_domain(did)%n_CC(j) = NCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%ChSSlp(j) .eq. 0.0) then  !if id didn't get set from the hi res file, use the  CHANPARAM\n                 rt_domain(did)%ChSSlp(j) = CHAN_SS(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%MannN(j) .eq. 0.0) then\n                 rt_domain(did)%MannN(j) = CHMann(rt_domain(did)%ORDER(j))\n              endif\n              rt_domain(did)%HLINK(j) = HLINK_INIT(rt_domain(did)%ORDER(j))\n           elseif (rt_domain(did)%ORDER(j) .eq. 5) then\n              if(rt_domain(did)%Bw(j) .eq. 0.0) then\n                 rt_domain(did)%Bw(j) = BOTWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw(j) .eq. 0.0) then\n                 rt_domain(did)%Tw(j) = TOPWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw_CC(j) .eq. 0.0) then\n                 rt_domain(did)%Tw_CC(j) = TOPWIDCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%n_CC(j) .eq. 0.0) then\n                 rt_domain(did)%n_CC(j) = NCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%ChSSlp(j) .eq. 0.0) then  !if id didn't get set from the hi res file, use the  CHANPARAM\n                 rt_domain(did)%ChSSlp(j) = CHAN_SS(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%MannN(j) .eq. 0.0) then\n                 rt_domain(did)%MannN(j) = CHMann(rt_domain(did)%ORDER(j))\n              endif\n              rt_domain(did)%HLINK(j) = HLINK_INIT(rt_domain(did)%ORDER(j))\n           elseif (rt_domain(did)%ORDER(j) .eq. 6) then\n              if(rt_domain(did)%Bw(j) .eq. 0.0) then\n                 rt_domain(did)%Bw(j) = BOTWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw(j) .eq. 0.0) then\n                 rt_domain(did)%Tw(j) = TOPWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw_CC(j) .eq. 0.0) then\n                 rt_domain(did)%Tw_CC(j) = TOPWIDCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%n_CC(j) .eq. 0.0) then\n                 rt_domain(did)%n_CC(j) = NCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%ChSSlp(j) .eq. 0.0) then  !if id didn't get set from the hi res file, use the  CHANPARAM\n                 rt_domain(did)%ChSSlp(j) = CHAN_SS(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%MannN(j) .eq. 0.0) then\n                 rt_domain(did)%MannN(j) = CHMann(rt_domain(did)%ORDER(j))\n              endif\n              rt_domain(did)%HLINK(j) = HLINK_INIT(rt_domain(did)%ORDER(j))\n           elseif (rt_domain(did)%ORDER(j) .ge. 7) then\n              if(rt_domain(did)%Bw(j) .eq. 0.0) then\n                 rt_domain(did)%Bw(j) = BOTWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw(j) .eq. 0.0) then\n                 rt_domain(did)%Tw(j) = TOPWID(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%Tw_CC(j) .eq. 0.0) then\n                 rt_domain(did)%Tw_CC(j) = TOPWIDCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%n_CC(j) .eq. 0.0) then\n                 rt_domain(did)%n_CC(j) = NCC(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%ChSSlp(j) .eq. 0.0) then  !if id didn't get set from the hi res file, use the  CHANPARAM\n                 rt_domain(did)%ChSSlp(j) = CHAN_SS(rt_domain(did)%ORDER(j))\n              endif\n              if(rt_domain(did)%MannN(j) .eq. 0.0) then\n                 rt_domain(did)%MannN(j) = CHMann(rt_domain(did)%ORDER(j))\n              endif\n              rt_domain(did)%HLINK(j) = HLINK_INIT(rt_domain(did)%ORDER(j))\n           else   !-- the outlets won't have orders since there's no nodes, so\n              !-- assign the order 5 values\n\n              if(rt_domain(did)%Bw(j) .eq. 0.0) then\n                 rt_domain(did)%Bw(j) = BOTWID(5)\n              endif\n\n              if(rt_domain(did)%Tw(j) .eq. 0.0) then\n                 rt_domain(did)%Tw(j) = TOPWID(5)\n              endif\n              if(rt_domain(did)%Tw_CC(j) .eq. 0.0) then\n                 rt_domain(did)%Tw_CC(j) = TOPWIDCC(5)\n              endif\n              if(rt_domain(did)%n_CC(j) .eq. 0.0) then\n                 rt_domain(did)%n_CC(j) = NCC(5)\n              endif\n              if(rt_domain(did)%ChSSlp(j) .eq. 0.0) then  !if id didn't get set from the hi res file, use the  CHANPARAM\n                 rt_domain(did)%ChSSlp(j) = CHAN_SS(5)\n              endif\n              if(rt_domain(did)%MannN(j) .eq. 0.0) then\n                 rt_domain(did)%MannN(j) = CHMann(5)\n              endif\n              rt_domain(did)%HLINK(j) = HLINK_INIT(5)\n           endif\n\n           rt_domain(did)%CVOL(j) = (rt_domain(did)%Bw(j)+ 1/rt_domain(did)%ChSSLP(j)*rt_domain(did)%HLINK(j))*rt_domain(did)%HLINK(j)*rt_domain(did)%CHANLEN(j) !-- initalize channel volume\n        end do\n\n     endif  !End if channel option eq 3; else;\n\n\n     ! Initialize Lake Elevations for Gridded and NWM routing.\n     do j=1,rt_domain(did)%NLAKES\n        rt_domain(did)%RESHT(j) = rt_domain(did)%ORIFICEE(j) + &\n             ((rt_domain(did)%LAKEMAXH(j) - rt_domain(did)%ORIFICEE(j) )* rt_domain(did)%ELEVLAKE(j))\n     end do\n\n  end if     ! Endif for channel routing setup\n!-----------------------------------------------------------------------\n\n  if(nlst(did)%channel_only       .eq. 0 .and. &\n       nlst(did)%channelBucket_only .eq. 0        ) then\n\n     rt_domain(did)%INFXSWGT = 1./(nlst(did)%AGGFACTRT*nlst(did)%AGGFACTRT)\n     rt_domain(did)%SH2OWGT = 1.\n     rt_domain(did)%subsurface%properties%soldeprt = -1.0 * nlst(did)%ZSOIL8(nlst(did)%NSOIL)\n     rt_domain(did)%subsurface%state%qsubrt = 0.0\n     rt_domain(did)%subsurface%properties%zwattablrt = 0.0\n     rt_domain(did)%subsurface%state%qsubbdryrt = 0.0\n     rt_domain(did)%overland%streams_and_lakes%surface_water_to_channel = 0.0\n     rt_domain(did)%overland%control%boundary_flux = 0.0\n     rt_domain(did)%overland%control%surface_water_head_routing = 0.0\n     rt_domain(did)%overland%control%infiltration_excess = 0.0\n     rt_domain(did)%overland%control%dhrt = 0.0\n     rt_domain(did)%overland%streams_and_lakes%surface_water_to_lake = 0.0\n     rt_domain(did)%LAKE_CT = 0\n     rt_domain(did)%STRM_CT = 0\n     rt_domain(did)%SOLDRAIN = 0.0\n     rt_domain(did)%qinflowbase = 0.0\n\n   !  rt_domain(did)%BASIN_MSK = 1\n   ! !DJG Initialize mass balance check variables...\n     rt_domain(did)%SMC_INIT=0.\n     rt_domain(did)%DSMC=0.\n     rt_domain(did)%DACRAIN=0.\n     rt_domain(did)%DSFCEVP=0.\n     rt_domain(did)%DCANEVP=0.\n     rt_domain(did)%DEDIR=0.\n     rt_domain(did)%DETT=0.\n     rt_domain(did)%DEPND=0.\n     rt_domain(did)%DESNO=0.\n     rt_domain(did)%DSFCRNFF=0.\n     rt_domain(did)%DQBDRY=0.\n     rt_domain(did)%overland%mass_balance%pre_infiltration_excess=0.\n\n  end if ! end of neither channel_only nor channelBucket_only\n\n   ! Deallocate existing arrays that contain reservoir parameters/properties\n   if(allocated(rt_domain(did)%HRZAREA)) deallocate(rt_domain(did)%HRZAREA)\n   if(allocated(rt_domain(did)%WEIRH)) deallocate(rt_domain(did)%WEIRH)\n   if(allocated(rt_domain(did)%WEIRC)) deallocate(rt_domain(did)%WEIRC)\n   if(allocated(rt_domain(did)%WEIRL)) deallocate(rt_domain(did)%WEIRL)\n   if(allocated(rt_domain(did)%DAML)) deallocate(rt_domain(did)%DAML)\n   if(allocated(rt_domain(did)%ORIFICEE)) deallocate(rt_domain(did)%ORIFICEE)\n   if(allocated(rt_domain(did)%ORIFICEC)) deallocate(rt_domain(did)%ORIFICEC)\n   if(allocated(rt_domain(did)%ORIFICEA)) deallocate(rt_domain(did)%ORIFICEA)\n   if(allocated(rt_domain(did)%LAKEMAXH)) deallocate(rt_domain(did)%LAKEMAXH)\n\nend subroutine LandRT_ini\n\nsubroutine deriveFromNode(did)\n  implicit none\n  integer :: did\n  integer :: i,j, kk, maxv\n  integer :: tmp(rt_domain(did)%nlinks)\n  tmp = 0\n  maxv = 1\n  do i = 1, rt_domain(did)%nlinks\n     if(rt_domain(did)%to_node(i) .gt. 0) then\n        kk = rt_domain(did)%to_node(i)\n        tmp(kk) = tmp(kk) + 1\n        if(maxv .lt. tmp(kk)) maxv = tmp(kk)\n     end if\n  end do\n  allocate(rt_domain(did)%pnode(rt_domain(did)%nlinks,maxv+1) )\n  rt_domain(did)%maxv_p = maxv+1\n  rt_domain(did)%pnode = -99\n  rt_domain(did)%pnode(:,1) = 1\n  do i = 1, rt_domain(did)%nlinks\n     if(rt_domain(did)%to_node(i) .gt. 0) then\n        j = rt_domain(did)%to_node(i)\n        rt_domain(did)%pnode(j,1) = rt_domain(did)%pnode(j,1) + 1\n        kk = rt_domain(did)%pnode(j,1)\n        rt_domain(did)%pnode(j,kk) = i\n     end if\n  end do\n\nend subroutine deriveFromNode\n\nEND MODULE module_Routing\n"
  },
  {
    "path": "src/Routing/module_UDMAP.F90",
    "content": "! This subrouting includs the data structure and tools used for NHDPlus network mapping.\nmodule module_UDMAP\n\n  use config_base, only: nlst\n#ifdef MPP_LAND\n  use module_mpp_land, only: my_id, local_startx_rt, local_starty_rt,  &\n       local_endx_rt,local_endy_rt, left_id, right_id, down_id, up_id, mpp_collect_1d_int_mem, &\n       IO_id , numprocs\n  use module_mpp_land, only: mpp_land_bcast_int, mpp_land_bcast_real8_1d, mpp_land_bcast_int1, mpp_land_bcast_int8\n\n  use module_mpp_land, only: sum_int1d, global_rt_nx, global_rt_ny, write_IO_rt_int, MPP_LAND_COM_INTEGER\n\n  use MODULE_mpp_ReachLS, only : updatelinkv, ReachLS_write_io, com_write1dInt, &\n       com_decomp1dInt, pack_decomp_int, pack_decomp_real8, &\n       com_decomp1dint8, pack_decomp_int8, com_write1dInt8\n  use module_hydro_stop, only:HYDRO_stop\n  use hashtable\n\n  use iso_fortran_env, only: int64\n#endif\n\n  implicit none\n\n#ifndef MPP_LAND\n    integer, parameter :: numprocs=1\n#endif\n\n#include <netcdf.inc>\n\ntype userDefineMapping\n    integer, allocatable, dimension(:) :: grid_i, grid_j\n    real, allocatable, dimension(:) :: weight, nodeArea, cellArea\n    integer :: ngrids\n    integer(kind=int64) :: myid\n!   for bucket model definition\n    real, allocatable, dimension(:) :: cellWeight\n    integer, allocatable, dimension(:) :: cell_i, cell_j\n    integer :: ncell\nend type userDefineMapping\n\nTYPE ( userDefineMapping ), allocatable, DIMENSION (:) :: LUDRSL\n\ninteger(kind=int64), allocatable, dimension(:) :: bufid\nreal*8 , allocatable, dimension(:) :: bufw\ninteger :: LNUMRSL  ! number of local links\ninteger :: ter_rt_flag\nreal*8, allocatable, dimension(:) :: basns_area\ninteger :: gnpid, lnsize\ninteger, allocatable, dimension(:) :: bufi,bufj\n\ncontains\n    subroutine UDMP_ini(nlinksl,ixrt,jxrt,rtmask, OVRTSWCRT, SUBRTSWCRT,cell_area)\n!This is the driver for user defined mapping file funciton application.\n        integer :: ixrt, jxrt, OVRTSWCRT, SUBRTSWCRT, nlinksl\n        integer, intent(in), dimension(ixrt,jxrt):: rtmask\n        integer :: npid    !local variable.\n        real,dimension(:,:) :: cell_area\n        ter_rt_flag = 0\n        if(OVRTSWCRT .eq. 1 .or. SUBRTSWCRT .eq. 1) then\n            ter_rt_flag = 1\n        endif\n        call readUDMP(ixrt,jxrt,npid,nlinksl)\n        call UDMP2LOCAL(npid,ixrt,jxrt,rtmask, ter_rt_flag)\n        call getUDMP_area(cell_area)\n    end subroutine UDMP_ini\n\n    subroutine readUDMP(ixrt,jxrt,npid, nlinksl)\n        implicit none\n        integer :: i,j,Ndata, did, Npid, nlinksl, k, m, kk\n        integer,allocatable,dimension(:) ::  nprocs_map, lnsizes, istart\n        integer(kind=int64), allocatable, dimension(:) :: g1bufid, gbufid, linkid, bufid_tmp, bufidflag\n        integer :: ix_bufid, ii, ixrt,jxrt\n        integer, allocatable, dimension(:) :: gbufi,gbufj,bufsize\n        real*8 , allocatable, dimension(:) :: gbufw\n\n        did = 1\n        call get_dimension(trim(nlst(did)%UDMAP_FILE), ndata, npid)\n\n#ifdef MPP_LAND\n        gnpid = npid\n        allocate (lnsizes(numprocs))\n        if(my_id .eq. io_id) then\n           allocate (istart(numprocs))\n           allocate (nprocs_map(ndata))\n           allocate(gbufi(ndata))\n           allocate(gbufj(ndata))\n           call get1d_int(trim(nlst(did)%UDMAP_FILE),\"i_index\",gbufi)\n           call get1d_int(trim(nlst(did)%UDMAP_FILE),\"j_index\",gbufj)\n        endif\n           call get_nprocs_map(ixrt,jxrt,gbufi,gbufj,nprocs_map,ndata)\n\n        if(my_id .eq. io_id) then\n           lnsizes = 0\n           do i =1 , ndata\n               if(nprocs_map(i) .gt. 0) then\n                  lnsizes(nprocs_map(i)) = lnsizes(nprocs_map(i)) + 1\n               endif\n           enddo\n        endif\n        call mpp_land_bcast_int(numprocs,lnsizes)\n\n     if(my_id .eq. io_id ) then\n        kk = 0\n        do i = 1, numprocs\n           kk = kk + lnsizes(i)\n        end do\n     end if\n\n      if(my_id .eq. IO_id) then\n          ii = 1\n          do i = 1, numprocs\n             istart(i) = ii\n             if(lnsizes(i) .gt. 0) then\n                ii = lnsizes(i) + ii\n             else\n                istart(i) = -999\n             endif\n          end do\n      endif\n\n      if(lnsizes(my_id+1) .gt. 0)  allocate(bufi(lnsizes(my_id+1) ))\n      call pack_decomp_int(gbufi, ndata, nprocs_map, lnsizes, istart,bufi)\n      if(my_id .eq. io_id) then\n           if(allocated(gbufi))  deallocate(gbufi)\n      endif\n\n\n      if(lnsizes(my_id+1) .gt. 0) allocate(bufj(lnsizes(my_id+1) ))\n      call pack_decomp_int(gbufj, ndata, nprocs_map, lnsizes, istart,bufj)\n      if(my_id .eq. io_id)  then\n         if(allocated(gbufj)) deallocate(gbufj)\n      endif\n\n\n! check bufid\n!      check  polyid and linkid\n        allocate(linkid(nlinksl))\n        if(my_id .eq. io_id) then\n            call get1d_int64(trim(nlst(did)%route_link_f),\"link\",linkid)\n            allocate(gbufid(npid))\n            call get1d_int64(trim(nlst(did)%UDMAP_FILE),\"polyid\",gbufid)\n        endif\n#ifdef MPP_LAND\n       if(nlinksl .gt. 0) then\n          call mpp_land_bcast_int8(nlinksl,linkid)\n       endif\n       call com_decomp1dInt8(gbufid,npid,bufid_tmp,ix_bufid)\n#endif\n       if(ix_bufid .gt. 0) then\n          allocate(bufidflag(ix_bufid))\n          bufidflag = -999\n       endif\n\n       ! The following loops are replaced by a hashtable-based algorithm\n       !  do i = 1, ix_bufid\n       !           do j = 1, nlinksl\n       !                if(bufid_tmp(i) .eq. linkid(j)) then\n       !                   bufidflag(i) = bufid_tmp(i)\n       !                   goto 102\n       !                endif\n       !           end do\n       ! 102       continue\n       !        end do\n\n       block\n         type(hash_t) :: hash_table\n         integer(kind=int64) :: val,it\n         logical :: found\n\n         call hash_table%set_all_idx(bufid_tmp, ix_bufid)\n         do it = 1, nlinksl\n            call hash_table%get(linkid(it), val, found)\n            if(found .eqv. .true.) then\n               bufidflag(val) = bufid_tmp(val)\n            end if\n         end do\n         call hash_table%clear()\n       end block\n\n#ifdef MPP_LAND\n      call com_write1dInt8(bufidflag,ix_bufid,gbufid,npid)\n#endif\n      if(ix_bufid .gt. 0) then\n          if(allocated(bufidflag)) deallocate(bufidflag)\n          if(allocated(bufid_tmp)) deallocate(bufid_tmp)\n      endif\n      if(allocated(linkid)) deallocate(linkid)\n      if(my_id .eq. io_id) then\n          allocate(bufsize(npid))\n          allocate(g1bufid(ndata))\n          call get1d_int(trim(nlst(did)%UDMAP_FILE),\"overlaps\",bufsize)\n          g1bufid = -999\n          i = 1\n          do k = 1, npid\n               do j = 1, bufsize(k)\n                 g1bufid(i) = gbufid(k)\n                 i = i + 1\n               end do\n          enddo\n          if(allocated(bufsize))  deallocate(bufsize)\n      endif\n\n\n      if(my_id .eq. io_id) then\n           if(allocated(gbufid)) deallocate(gbufid)\n      endif\n\n\n      if(lnsizes(my_id+1) .gt. 0) allocate(bufid(lnsizes(my_id+1) ))\n      call pack_decomp_int8(g1bufid, ndata, nprocs_map, lnsizes, istart,bufid)\n      if(my_id .eq. io_id) then\n            if(allocated(g1bufid)) deallocate(g1bufid)\n      endif\n\n\n      if(my_id .eq. io_id) then\n          allocate(gbufw(ndata))\n          call get1d_real8(trim(nlst(did)%UDMAP_FILE),\"regridweight\",gbufw)\n      endif\n      if(lnsizes(my_id+1) .gt. 0) allocate(bufw(lnsizes(my_id+1) ))\n      call pack_decomp_real8(gbufw, ndata, nprocs_map, lnsizes, istart,bufw)\n      if(my_id .eq. io_id) then\n          if(allocated(gbufw))     deallocate(gbufw)\n      endif\n\n\n        if(my_id .eq. io_id) then\n           if(allocated(nprocs_map)) deallocate (nprocs_map)\n           if(allocated(istart)) deallocate (istart)\n        endif\n        lnsize = lnsizes(my_id + 1)\n        if(allocated(lnsizes)) deallocate(lnsizes)\n#else\n       call hydro_stop(\"FATAL ERROR in UDMP : sequential not defined.\")\n#endif\n\n    end subroutine readUDMP\n\n    subroutine UDMP2LOCAL(npid,ix,jx,rtmask, ter_rt_flag)\n        implicit none\n        integer :: i,j,k, ngrids, ix,jx, starti,startj, endi,endj, ii,jj, npid, kk\n        integer, intent(in), dimension(ix,jx) :: rtmask\n        integer, dimension(lnsize) :: lndflag,gridflag , tmpgridflag\n        integer :: ter_rt_flag, m, c\n\n\n!   find ngrids is 0 so that we need to mapping from subsurface runoff.\n#ifdef MPP_LAND\n        if(left_id .ge. 0) then\n           starti = local_startx_rt  + 1\n        else\n           starti = local_startx_rt\n        endif\n        if(down_id .ge. 0) then\n           startj = local_starty_rt  + 1\n        else\n           startj = local_starty_rt\n        endif\n        if(right_id .ge. 0) then\n           endi = local_startx_rt + ix -2\n        else\n           endi = local_startx_rt + ix -1\n        endif\n        if(up_id .ge. 0) then\n           endj = local_starty_rt + jx -2\n        else\n           endj = local_starty_rt + jx -1\n        endif\n#else\n        starti = 1\n        startj = 1\n        endi = ix\n        endj = jx\n#endif\n        gridflag = 0\n        lndflag = 0\n\n#ifdef MPP_LAND\n        k = 0\n        do i = 1, lnsize\n           if(bufid(i) .gt. 0) then\n                if(bufi(i) .ge. starti .and. bufj(i) .ge. startj .and. &\n                    bufi(i) .le. endi   .and. bufj(i) .le. endj) then\n                    if(k .eq. 0) then\n                       k = 1\n                    else\n                       if(bufid(i) .ne. bufid(i-1)) k = k + 1\n                    endif\n                    lndflag(k) = lndflag(k) + 1\n                    if(ter_rt_flag .eq. 1) then\n                        if(rtmask(bufi(i)-local_startx_rt+1,bufj(i)-local_starty_rt+1) .ge. 0) then\n                             gridflag(k) = gridflag(k) + 1\n                        endif\n                    endif\n                 endif\n           endif\n        end do\n\n! decide how many mapping land grids on current domain\n!       tmpgridflag = gridflag\n#ifdef MPP_LAND\n!       call mpp_collect_1d_int_mem(npid,tmpgridflag)\n#endif\n\n! decide how many user defined links on current domain\n        kk = k\n        LNUMRSL = 0\n        do k = 1, lnsize\n           if(lndflag(k) .gt. 0) LNUMRSL = LNUMRSL + 1\n        enddo\n\n\n        if(LNUMRSL .gt. 0) then\n\n               allocate(LUDRSL(LNUMRSL))\n               allocate( basns_area(LNUMRSL) )\n        else\n! When MPI is performed,for every subdomain in each process, all the links\n! are listed and if there is no link in the subdomain then it is calling\n! cleanBuf (memory cleaning purposes), this used to print a warning\n! that is not necessary for the user to see it, therefore it is been commented out here\n!               write(6,*) \"Warning: no routing links found.\"\n               call cleanBuf()\n               return\n        endif\n\n        kk = 0\n        do k = 1, lnsize\n           if( bufid(k) .ge. 0 ) then\n             if (bufi(k) .ge. starti .and. bufj(k) .ge. startj .and. &\n                    bufi(k) .le. endi   .and. bufj(k) .le. endj ) then\n                 if(kk .eq. 0) then\n                       kk = 1\n                 else\n                       if(bufid(k) .ne. bufid(k-1)) kk = kk + 1\n                 endif\n                 LUDRSL(kk)%myid = bufid(k)\n                 LUDRSL(kk)%ngrids = -999\n                 if(gridflag(kk) .gt. 0) then\n                   LUDRSL(kk)%ngrids = gridflag(kk)\n                   if(.not. allocated(LUDRSL(kk)%weight) ) then\n                         allocate( LUDRSL(kk)%weight(LUDRSL(kk)%ngrids ))\n                         allocate( LUDRSL(kk)%grid_i(LUDRSL(kk)%ngrids ))\n                         allocate( LUDRSL(kk)%grid_j(LUDRSL(kk)%ngrids ))\n                         allocate( LUDRSL(kk)%nodeArea(LUDRSL(kk)%ngrids ))\n                   endif\n                 endif\n!  define bucket variables\n                 LUDRSL(kk)%ncell = lndflag(kk)\n                 if(.not. allocated(LUDRSL(kk)%cellweight) ) then\n                     allocate( LUDRSL(kk)%cellweight(LUDRSL(kk)%ncell))\n                     allocate( LUDRSL(kk)%cell_i(LUDRSL(kk)%ncell))\n                     allocate( LUDRSL(kk)%cell_j(LUDRSL(kk)%ncell))\n                     allocate( LUDRSL(kk)%cellArea(LUDRSL(kk)%ncell))\n                 endif\n             endif\n           endif\n        enddo\n\n\n! maping grid_i, grid_j and weight\n        kk = 0\n        m  = 1\n        c  = 1\n        do i = 1, lnsize\n               if( (bufid(i) .ge. 0)  ) then\n                   if(bufi(i) .ge. starti .and. bufj(i) .ge. startj .and. &\n                      bufi(i) .le. endi   .and. bufj(i) .le. endj) then\n                      if(kk .eq. 0) then\n                         kk = 1\n                      else\n                         if(bufid(i) .ne. bufid(i-1)) then\n                             kk = kk + 1\n                             m  = 1\n                             c  = 1\n                         endif\n                      endif\n\n                      if(LUDRSL(kk)%ngrids .gt. 0) then\n                          if(rtmask(bufi(i)-local_startx_rt+1,bufj(i)-local_starty_rt+1) .ge. 0) then\n                             LUDRSL(kk)%grid_i(m) = bufi(i) - local_startx_rt+1\n                             LUDRSL(kk)%grid_j(m) = bufj(i) - local_starty_rt+1\n                             LUDRSL(kk)%weight(m) = bufw(i)\n                             m  = m  + 1\n                          endif\n                      endif\n!! begin define bucket variables\n                          LUDRSL(kk)%cell_i(c) = bufi(i) - local_startx_rt+1\n                          LUDRSL(kk)%cell_j(c) = bufj(i) - local_starty_rt+1\n                          LUDRSL(kk)%cellWeight(c) = bufw(i)\n                          c  = c  + 1\n!! end define bucket variables\n                   endif\n                endif\n        end do\n\n        call cleanBuf()\n\n#else\n        call hydro_stop(\"FATAL ERROR in UDMP: Sequential not work.\")\n#endif\n\n    end subroutine UDMP2LOCAL\n\n    subroutine cleanBuf()\n        if(allocated(bufi))  deallocate(bufi)\n        if(allocated(bufj))  deallocate(bufj)\n        if(allocated(bufw))  deallocate(bufw)\n        if(allocated(bufid))  deallocate(bufid)\n    end subroutine cleanBuf\n\n     subroutine get_dimension(fileName, ndata,npid)\n            implicit none\n            character(len=*) fileName\n            integer ncid , iret, ndata,npid, dimid\n#ifdef MPP_LAND\n            if(my_id .eq. IO_id) then\n#endif\n               iret = nf_open(fileName, NF_NOWRITE, ncid)\n               if (iret /= 0) then\n                  write(*,'(\"FATAL ERROR: Problem opening mapping file: ''\", A, \"''\")') &\n                       trim(fileName)\n                  call hydro_stop(\"In get_dimension() - Problem opening mapping file.\")\n               endif\n\n               iret = nf_inq_dimid(ncid, \"polyid\", dimid)\n\n               if (iret /= 0) then\n                  print*, \"nf_inq_dimid:  polyid\"\n                  call hydro_stop(\"In get_dimension() - nf_inq_dimid:  polyid\")\n               endif\n\n               iret = nf_inq_dimlen(ncid, dimid, npid)\n\n               iret = nf_inq_dimid(ncid, \"data\", dimid)\n               if (iret /= 0) then\n                          print*, \"nf_inq_dimid:  data\"\n                          call hydro_stop(\"In get_file_dimension() - nf_inq_dimid:  data\")\n               endif\n\n               iret = nf_inq_dimlen(ncid, dimid, ndata)\n               iret = nf_close(ncid)\n#ifdef MPP_LAND\n            endif\n            call mpp_land_bcast_int1(ndata)\n            call mpp_land_bcast_int1(npid)\n#endif\n     end subroutine get_dimension\n\n       subroutine get1d_real8(fileName,var_name,out_buff)\n          implicit none\n          integer :: ivar, iret,varid,ncid\n          real*8 out_buff(:)\n          character(len=*), intent(in) :: var_name\n          character(len=*), intent(in) :: fileName\n\n          iret = nf_open(trim(fileName), NF_NOWRITE, ncid)\n          if (iret .ne. 0) then\n            print*,\"failed to open the netcdf file: \",trim(fileName)\n            call hydro_stop(\"In get1d_real8() - failed to open the netcdf file.\")\n            return\n          endif\n          ivar = nf_inq_varid(ncid,trim(var_name),  varid)\n          if(ivar .ne. 0) then\n               write(6,*) \"Read Variable Error file: \",trim(fileName)\n               write(6,*) \"Read Error: could not find \",trim(var_name)\n               call hydro_stop(\"In get1d_real8() - failed to read netcdf varialbe name. \")\n          end if\n          iret = nf_get_var_double(ncid, varid, out_buff)\n          iret = nf_close(ncid)\n      end subroutine get1d_real8\n\n       subroutine get1d_int(fileName,var_name,out_buff)\n          implicit none\n          integer :: ivar, iret,varid,ncid\n          integer out_buff(:)\n          character(len=*), intent(in) :: var_name\n          character(len=*), intent(in) :: fileName\n\n          iret = nf_open(trim(fileName), NF_NOWRITE, ncid)\n          if (iret .ne. 0) then\n            print*,\"FATAL ERROR: Failed to open the netcdf file: \",trim(fileName)\n            call hydro_stop(\"In get1d_int() -  Failed to open the netcdf file\")\n            return\n          endif\n          ivar = nf_inq_varid(ncid,trim(var_name),  varid)\n          if(ivar .ne. 0) then\n               write(6,*) \"Read Variable Error file: \",trim(fileName)\n               write(6,*) \"Read Error: could not find \",trim(var_name)\n               call hydro_stop(\"In get1d_int() - failed to read netcdf variable name.\")\n          end if\n          iret = nf_get_var_int(ncid, varid, out_buff)\n          iret = nf_close(ncid)\n      end subroutine get1d_int\n\n    subroutine get1d_int64(fileName,var_name,out_buff)\n        implicit none\n        integer :: ivar, iret,varid,ncid\n        integer(kind=int64) out_buff(:)\n        character(len=*), intent(in) :: var_name\n        character(len=*), intent(in) :: fileName\n\n        iret = nf_open(trim(fileName), NF_NOWRITE, ncid)\n        if (iret .ne. 0) then\n            print*,\"FATAL ERROR: Failed to open the netcdf file: \",trim(fileName)\n            call hydro_stop(\"In get1d_int() -  Failed to open the netcdf file\")\n            return\n        endif\n        ivar = nf_inq_varid(ncid,trim(var_name),  varid)\n        if(ivar .ne. 0) then\n            write(6,*) \"Read Variable Error file: \",trim(fileName)\n            write(6,*) \"Read Error: could not find \",trim(var_name)\n            call hydro_stop(\"In get1d_int() - failed to read netcdf variable name.\")\n        end if\n        iret = nf_get_var_int64(ncid, varid, out_buff)\n        iret = nf_close(ncid)\n    end subroutine get1d_int64\n\n      subroutine getUDMP_area(cell_area)\n         implicit none\n         integer i,j,k, m\n         real, dimension(:,:) :: cell_area\n         do k  = 1, LNUMRSL\n            if(LUDRSL(k)%ngrids .gt. 0) then\n                do m = 1, LUDRSL(k)%ngrids\n                    LUDRSL(k)%nodeArea(m) = cell_area(LUDRSL(k)%grid_i(m),LUDRSL(k)%grid_j(m))\n                enddo\n            endif\n                do m = 1, LUDRSL(k)%ncell\n                    LUDRSL(k)%cellArea(m) = cell_area(LUDRSL(k)%cell_i(m),LUDRSL(k)%cell_j(m))\n                enddo\n\n            basns_area(k) = 0\n            do m = 1, LUDRSL(k)%ncell\n                    basns_area(k) = basns_area(k) + &\n                          cell_area(LUDRSL(k)%cell_i(m),LUDRSL(k)%cell_j(m)) * LUDRSL(k)%cellWeight(m)\n            enddo\n\n         end do\n      end subroutine getUDMP_area\n\n      subroutine get_basn_area_nhd(inOut)\n         implicit none\n         real, dimension(:) :: inOut\n         real, dimension(gnpid) :: buf\n#ifdef MPP_LAND\n         call updateLinkV(basns_area, inOut)\n#else\n         inOut = basns_area\n#endif\n\n\n      end subroutine get_basn_area_nhd\n\n      subroutine get_nprocs_map(ix,jx,bufi,bufj,nprocs_map,ndata)\n          implicit none\n          integer,dimension(:)  :: bufi, bufj,nprocs_map\n!          integer, allocatable, dimension(:) ::  lbufi,lbufj, lmap\n          integer  :: ndata, lsize, ix,jx\n          integer, dimension(ix,jx) :: mask\n          integer, allocatable,dimension(:,:) :: gmask\n\n        integer :: i,j,k, starti,startj, endi,endj, ii,jj, npid, kk\n#ifdef MPP_LAND\n\n          mask = my_id + 1\n          if(my_id .eq. IO_id) allocate(gmask(global_rt_nx, global_rt_ny))\n\n          call MPP_LAND_COM_INTEGER(mask,IX,JX,99)\n          call write_IO_rt_int(mask, gmask)\n\n          if(my_id .eq. io_id ) then\n             nprocs_map = -999\n             do i = 1, ndata\n                  if( (bufi(i) .gt. 0 .and. bufi(i) .le. global_rt_nx) .and.  &\n                     (bufj(i) .gt. 0 .and. bufj(i) .le. global_rt_ny) ) then\n                     nprocs_map(i) = gmask(bufi(i), bufj(i))\n                     if( gmask(bufi(i), bufj(i)) .lt. 0) then\n                         write(6,*) \"mapping error in gmask : \", bufi(i) ,bufj(i)\n                     endif\n                  else\n                      write(6,*) \"no mapping for i,j : \", bufi(i) ,bufj(i)\n                  endif\n             end do\n\n             if(allocated(gmask)) deallocate(gmask)\n          endif\n#else\n        call hydro_stop(\"FATAL ERROR in UDMP: Sequential not work.\")\n#endif\n\n\n      end subroutine get_nprocs_map\n\n\nend module module_UDMAP\n"
  },
  {
    "path": "src/Routing/module_channel_routing.F90",
    "content": "MODULE module_channel_routing\n#ifdef MPP_LAND\nuse module_mpp_land\nuse MODULE_mpp_ReachLS, only : updatelinkv,                   &\n                               ReachLS_write_io, gbcastvalue, &\n                               gbcastreal2,      linkls_s\n\n\nuse module_reservoir, only: reservoir\nuse module_RT_data, only: rt_domain\nuse module_hydro_stop, only: HYDRO_stop\n\nuse iso_fortran_env, only: int64\n\n#endif\nimplicit none\n\ncontains\n\n! ------------------------------------------------\n!   FUNCTION MUSKING\n! ------------------------------------------------\nreal function MUSKING(idx,qup,quc,qdp,dt,Km,X)\n\nimplicit none\n\n!--local variables\nreal    :: C1, C2, C3\nreal    :: Km         !K travel time in hrs in reach\nreal    :: X          !weighting factors 0<=X<=0.5\nreal    :: dt         !routing period in hrs\nreal    :: avgbf      !average base flow for initial condition\nreal    :: qup        !inflow from previous timestep\nreal    :: quc        !inflow  of current timestep\nreal    :: qdp        !outflow of previous timestep\nreal    :: dth        !timestep in hours\ninteger :: idx        ! index\n\ndth = dt/3600.    !hours in timestep\nC1 = (dth - 2.0 *Km*X)/(2.0*Km*(1.0-X)+dth)\nC2 = (dth+2.0*Km*X)/(2.0*Km*(1.0-X)+dth)\nC3 = (2.0*Km*(1.0-X)-dth)/(2.0*Km*(1.0-X)+dth)\nMUSKING = (C1*quc)+(C2*qup)+(C3*qdp)\n\n! ----------------------------------------------------------------\nend function MUSKING\n! ----------------------------------------------------------------\n\n\n! ------------------------------------------------\n!   FUNCTION Diffusive wave\n! ------------------------------------------------\nreal function DIFFUSION(nod,z1,z20,h1,h2,dx,n, &\n     Bw, Cs)\nimplicit none\n!-- channel geometry and characteristics\nreal    :: Bw         !-bottom width (meters)\nreal    :: Cs         !-Channel side slope slope\nreal    :: dx         !-channel lngth (m)\nreal,intent(in)    :: n          !-mannings coefficient\nreal    :: R          !-Hydraulic radius\nreal    :: AREA       !- wetted area\nreal    :: h1,h2      !-tmp height variables\nreal    :: z1,z2      !-z1 is 'from', z2 is 'to' elevations\nreal    :: z          !-channel side distance\nreal    :: w          !-upstream weight\nreal    :: Ku,Kd      !-upstream and downstream conveyance\nreal    :: Kf         !-final face conveyance\nreal    :: Sf         !-friction slope\nreal    :: sgn        !-0 or 1\ninteger :: nod         !- node\nreal ::  z20, dzx\n\n! added by Wei Yu for bad data.\n\ndzx = (z1 - z20)/dx\nif(dzx .lt. 0.002) then\n   z2 = z1 - dx*0.002\nelse\n   z2 = z20\nendif\n!end\n\nif (n.le.0.0.or.Cs.le.0.or.Bw.le.0) then\n   print *, \"Error in Diffusion function ->channel coefficients\"\n   print *, \"nod, n, Cs, Bw\", nod, n, Cs, Bw\n   call hydro_stop(\"In DIFFUSION() - Error channel coefficients.\")\nendif\n\n!        Sf = ((z1+h1)-(z2+h2))/dx  !-- compute the friction slope\n!if(z1 .eq. z2) then\n! Sf = ((z1-(z2-0.01))+(h1-h2))/dx  !-- compute the friction slope\n!else\n!         Sf = ((z1-z2)+(h1-h2))/dx  !-- compute the friction slope\n!endif\n\n!modifieed by Wei Yu for false geography data\nif(abs(z1-z2) .gt. 1.0E5) then\n#ifdef HYDRO_D\n   print*, \"WARNING: huge slope rest to 0 for channel grid.\", z1,z2\n#endif\n   Sf = ((h1-h2))/dx  !-- compute the friction slope\nelse\n   Sf = ((z1-z2)+(h1-h2))/dx  !-- compute the friction slope\nendif\n!end  modfication\n\nsgn = SGNf(Sf)             !-- establish sign\n\nw = 0.5*(sgn + 1.)         !-- compute upstream or downstream weighting\n\nz = 1.0/Cs                   !--channel side distance (m)\nR = ((Bw + z*h1)*h1) / (Bw+ 2.0*h1*sqrt(1.0 + z*z)) !-- Hyd Radius\nAREA = (Bw + z*h1)*h1        !-- Flow area\nKu = (1.0/n)*(R**(2./3.))*AREA     !-- convenyance\n\nR = ((Bw + z*h2)*h2)/(Bw + 2.0*h2*sqrt(1.0 + z*z)) !-- Hyd Radius\nAREA = (Bw + z*h2)*h2        !-- Flow area\nKd = (1.0/n)*(R**(2.0/3.0))*AREA     !-- convenyance\n\nKf =  (1.0-w)*Kd + w*Ku      !-- conveyance\nDIFFUSION = Kf * sqrt(abs(Sf))*sgn\n\n\n100 format('z1,z2,h1,h2,kf,Dif, Sf, sgn  ',f8.3,2x,f8.3,2x,f8.4,2x,f8.4,2x,f8.3,2x,f8.3,2x,f8.3,2x,f8.0)\n\nend function DIFFUSION\n! ----------------------------------------------------------------\n\nsubroutine SUBMUSKINGCUNGE(    &\n     qdc, vel, qloss, idx, qup,  quc, &\n     qdp, ql,   dt,  So,   dx, &\n     n,   Cs,   Bw,  Tw, TwCC, &\n     nCC, depth, ChannK        )\n\n#ifdef HYDRO_D\nuse module_RT_data, only: rt_domain  !! JLM: this is only used in a c3 paramter diagnostic print\n#endif\n\n        IMPLICIT NONE\n\n        REAL, intent(IN)       :: dt         ! routing period in  seconds\n        REAL, intent(IN)       :: qup        ! flow upstream previous timestep\n        REAL, intent(IN)       :: quc        ! flow upstream current timestep\n        REAL, intent(IN)       :: qdp        ! flow downstream previous timestep\n        REAL, intent(INOUT)    :: qdc        ! flow downstream current timestep\n        REAL, intent(IN)       :: ql         ! lateral inflow through reach (m^3/sec)\n        REAL, intent(IN)       :: Bw         ! bottom width (meters)\n        REAL, intent(IN)       :: Tw         ! top width before bankfull (meters)\n        REAL, intent(IN)       :: TwCC       ! top width of Compund (meters)\n        REAL, intent(IN)       :: nCC        ! mannings of compund\n        REAL, intent(IN)       :: ChannK     ! Channel conductivity (m/s)\n        REAL, intent(IN)       :: Cs         ! Channel side slope slope\n        REAL, intent(IN)       :: So         ! Channel bottom slope %\n        REAL, intent(IN)       :: dx         ! channel lngth (m)\n        REAL, intent(IN)       :: n          ! mannings coefficient\n        REAL, intent(INOUT)    :: vel        ! velocity (m/s)\n        REAL, intent(INOUT)    :: qloss      ! channel infiltration (m^3/sec)\n        integer(kind=int64), intent(IN)    :: idx        ! channel id\n        REAL, intent(INOUT)    :: depth      ! depth of flow in channel\n\n!--local variables\n        REAL    :: C1, C2, C3, C4\n        REAL    :: Km             !K travel time in hrs in reach\n        REAL    :: X              !weighting factors 0<=X<=0.5\n        REAL    :: Ck             ! wave celerity (m/s)\n\n!-- channel geometry and characteristics, local variables\n        REAL    :: Twl            ! top width at simulated flow (m)\n        REAL    :: AREA,AREAC     ! Cross sectional area channel and compound m^2\n        REAL    :: Z              ! trapezoid distance (m)\n        REAL    :: R,RC           ! Hydraulic radius of channel and compound\n        REAL    :: WP,WPC         ! wetted perimmeter of channel and compound\n        REAL    :: h              ! depth of flow in channel\n        REAL    :: h_0,h_1        ! secant method estimates\n        REAL    :: bfd            ! bankfull depth (m)\n        REAL    :: Qj_0           ! secant method estimates\n        REAL    :: Qj             ! intermediate flow estimate\n        REAL    :: D,D1           ! diffusion coeff\n        REAL    :: dtr            ! required timestep, minutes\n        REAL    :: aerror,rerror  ! absolute and relative error\n        REAL    :: hp             ! courant, previous height\n        INTEGER :: iter, maxiter  ! maximum number of iterations\n\n!-- additional channel infiltration parameters\n        REAL    :: WPk        ! KINEROS2 modified wetted perimeter\n        REAL    :: modK       ! KINEROS2 constant (set to 0.15, line )\n\n!-- local variables.. needed if channel is sub-divded\n        REAL    :: a,b,c,F\n        REAL    :: mindepth   !  minimum depth in channel\n        INTEGER :: i,tries    !-- channel segment counter\n\n        !TML-- Hard code KINEROS2 Modification Parameter\n        !TML-- Set to 0.15, consistent with USDA-ARS\n        modK = 0.15\n\n        c = 0.52           !-- coefficnets for finding dx/Ckdt\n        b = 1.15\n        a = 0.0\n        maxiter  = 100\n        mindepth = 0.01\n        aerror = 0.01\n        rerror = 1.0\n        tries = 0\n\n!-------------  locals\n        if(Cs .eq. 0.00000000) then\n         z = 1.0\n        else\n         z = 1.0/Cs          !channel side distance (m)\n        endif\n\n        if(Bw .gt. Tw) then   !effectively infinite deep bankful\n           bfd = Bw/0.00001\n        elseif (Bw .eq. Tw) then\n          bfd =  Bw/(2.0*z)  !bankfull depth is effectively\n        else\n          bfd =  (Tw - Bw)/(2.0*z)  !bankfull depth (m)\n        endif\n        !qC = quc + ql !current upstream in reach\n\n        if (n .le. 0.0 .or. So .le. 0.0 .or. z .le. 0.0 .or. Bw .le. 0.0) then\n          print*, \"Error in channel coefficients -> Muskingum cunge\", n, So, z, Bw\n          call hydro_stop(\"In MUSKINGCUNGE() - Error in channel coefficients\")\n        end if\n\n!-------------  Secant Method\n        depth = max(depth, 0.0)\n        h     = (depth * 1.33) + mindepth !1.50 of  depth\n        h_0   = (depth * 0.67)            !0.50 of depth\n\n        if(ql .gt. 0.0 .or. qup .gt. 0.0 .or. qdp .gt. 0.0) then  !only solve if there's water to flux\n\n110     continue\n\n        Qj_0  = 0.0                       !- initial flow of lower interval\n        iter   = 0\n\n        do while (rerror .gt. 0.01 .and. aerror .ge. mindepth .and. iter .le. maxiter)\n\n           WPC    = 0.0\n           AREAC  = 0.0\n\n          !----- lower interval  --------------------\n\n           Twl = Bw + 2.0*z*h_0      !--top surface water width of the channel inflow\n\n            if ( (h_0 .gt. bfd) .and. (TwCC .gt. 0.0) .and. (nCC .gt. 0.0) ) then !water outside of defined channel\n             AREA =  (Bw + bfd * z) * bfd\n             AREAC = (TwCC * (h_0 -bfd)) !assume compound component is rect. chan, that's 3 times the Tw\n             WP = (Bw + 2.0 * bfd * sqrt(1.0 + z*z))\n             WPC = TwCC + (2.0 * (h_0-bfd)) !WPC is 2 times the Tw\n             WPk = WP + WPC*MIN((h_0/(modK*SQRT(Bw))),1.0)  ! KINEROS2 Mod.\n             R   = (AREA + AREAC)/(WP +WPC)  ! hydraulic radius\n            else\n              AREA = (Bw + h_0 * z ) * h_0\n              WP = (Bw + 2.0 * h_0 * sqrt(1.0 + z*z))\n              WPk = WP*MIN((h_0/(modK*SQRT(Bw))),1.0)  ! KINEROS2 Mod.\n              if(WP .gt. 0.0) then\n               R = AREA/ WP\n              else\n               R = 0.0\n              endif\n\n            endif\n\n          if ( (h_0 .gt. bfd) .and. (TwCC .gt. 0.0) .and. (nCC .gt. 0.0) ) then !water outside of defined channel\n            !weight the celerity by the contributing area, and assume that the mannings\n            !of the spills is 2x the manning of the channel\n                Ck = max(0.0,((sqrt(So)/n)*((5./3.)*R**(2./3.) - &\n                ((2./3.)*R**(5./3.)*(2.0*sqrt(1.0 + z*z)/(Bw+2.0*bfd*z))))*AREA &\n                + ((sqrt(So)/(nCC))*(5./3.)*(h_0-bfd)**(2./3.))*AREAC)/(AREA+AREAC))\n          else\n               if(h_0 .gt. 0.0) then\n                 Ck = max(0.0,(sqrt(So)/n)*((5./3.)*R**(2./3.) - &\n                 ((2./3.)*R**(5./3.)*(2.0*sqrt(1.0 + z*z)/(Bw+2.0*h_0*z)))))\n                else\n                 Ck = 0.0\n                endif\n          endif\n\n          if(Ck .gt. 0.000000) then\n            Km = max(dt,dx/Ck)\n          else\n            Km = dt\n          endif\n\n          if ( (h_0 .gt. bfd) .and. (TwCC .gt. 0.0) .and. (nCC .gt. 0.0) .and. (Ck .gt. 0.0) ) then\n          !water outside of defined channel\n             X = min(0.5,max(0.0,0.5*(1-(Qj_0/(2.0*TwCC*So*Ck*dx)))))\n          else\n            if(Ck .gt. 0.0) then\n              X = min(0.5,max(0.0,0.5*(1-(Qj_0/(2.0*Twl*So*Ck*dx)))))\n            else\n              X = 0.5\n            endif\n          endif\n\n           D = (Km*(1.000 - X) + dt/2.0000)              !--seconds\n            if(D .eq. 0.0) then\n              print *, \"FATAL ERROR: D is 0 in MUSKINGCUNGE\", Km, X, dt,D\n              call hydro_stop(\"In MUSKINGCUNGE() - D is 0.\")\n           endif\n\n           C1 =  (Km*X + dt/2.000000)/D\n           C2 =  (dt/2.0000 - Km*X)/D\n           C3 =  (Km*(1.00000000-X)-dt/2.000000)/D\n!          C1 =  max(0.0,min(1.0,1.0-C3))\n           if(ChannK .le. 0.0) then ! Disable channel loss for zero ChannK\n             C4 =  (ql*dt)/D\n           else\n             !C4 =  (ql*dt)/D - (ChannK * dx * WPk)  !-- DY & LKR lat inflow + channel loss\n             C4 =  ((ql - (ChannK * dx * WPk))*dt)/D  !-- TML: Loss adjusted by dt/D, closes water balance\n           endif\n\n           if((WP+WPC) .gt. 0.0) then  !avoid divide by zero\n! Another sanity check, prevent channel loss from exceeding flow\n             if( (C4 .lt. 0.0) .and. (abs(C4) .gt. (C1*qup)+(C2*quc)+(C3*qdp)) )  then\n              C4 = -((C1*qup)+(C2*quc)+(C3*qdp))\n             endif\n             Qj_0 =  ((C1*qup)+(C2*quc)+(C3*qdp) + C4) - ((1/(((WP*n)+(WPC*nCC))/(WP+WPC))) * &\n                    (AREA+AREAC) * (R**(2./3.)) * sqrt(So)) !f0(x)\n           endif\n!           WPk = WP*MIN((h/(modK*SQRT(Bw))),1.0)  ! KINEROS2 Mod. This shouldn't be HERE.\n\n           !--upper interval -----------\n           WPC    = 0.0\n           AREAC  = 0.0\n\n           Twl = Bw + 2.0*z*h                    !--top width of the channel inflow\n\n           if ( (h .gt. bfd) .and. (TwCC .gt. 0.0) .and. (nCC .gt. 0.0) ) then !water outside of defined channel\n             AREA =  (Bw + bfd * z) * bfd\n             AREAC = (TwCC * (h-bfd)) !assume compound component is rect. chan, that's 3 times the Tw\n             WP = (Bw + 2.0 * bfd * sqrt(1.0 + z*z))\n             WPC = TwCC + (2.0*(h-bfd)) !the additional wetted perimeter\n             WPk = WP + WPC*MIN((h/(modK*SQRT(Bw))),1.0)  ! KINEROS2 Mod.\n             R   = (AREA + AREAC)/(WP +WPC)\n            ! RC  = AREAC/WPC\n           else\n              AREA = (Bw + h * z ) * h\n              WP = (Bw + 2.0 * h * sqrt(1.000000 + z*z))\n              WPk = WP*MIN((h/(modK*SQRT(Bw))),1.0)  ! KINEROS2 Mod.\n              if(WP .gt. 0.0) then\n               R = AREA/WP\n              else\n               R = 0.0\n              endif\n           endif\n\n          if ( (h .gt. bfd) .and. (TwCC .gt. 0.0) .and. (nCC .gt. 0.0) ) then\n          !water outside of defined channel, assumed rectangular, 3x TW and n = 3x\n                Ck = max(0.0,((sqrt(So)/n)*((5./3.)*R**(2./3.) - &\n                ((2./3.)*R**(5./3.)*(2.0*sqrt(1.0 + z*z)/(Bw + 2.0*bfd*z))))*AREA &\n                + ((sqrt(So)/(nCC))*(5./3.)*(h-bfd)**(2./3.))*AREAC)/(AREA+AREAC))\n          else\n               if(h .gt. 0.0) then !avoid divide by zero\n                 Ck = max(0.0,(sqrt(So)/n)*((5./3.)*R**(2./3.) - &\n                 ((2./3.)*R**(5./3.)*(2.0 * sqrt(1.0 + z*z)/(Bw + 2.0*h*z)))))\n               else\n                 Ck = 0.0\n               endif\n          endif\n\n           if(Ck .gt. 0.0) then\n            Km = max(dt,dx/Ck)\n           else\n            Km = dt\n           endif\n\n          if ( (h .gt. bfd) .and. (TwCC .gt. 0.0) .and. (nCC .gt. 0.0) .and. (Ck .gt. 0.0) ) then\n          !water outside of defined channel\n            X = min(0.5,max(0.25,0.5*(1-(((C1*qup)+(C2*quc)+(C3*qdp) + C4)/(2.0*TwCC*So*Ck*dx)))))\n          else\n            if(Ck .gt. 0.0) then\n             X = min(0.5,max(0.25,0.5*(1-(((C1*qup)+(C2*quc)+(C3*qdp) + C4)/(2.0*Twl*So*Ck*dx)))))\n            else\n             X = 0.5\n            endif\n          endif\n\n           D = (Km*(1 - X) + dt/2)              !--seconds\n            if(D .eq. 0.0) then\n              print *, \"FATAL ERROR: D is 0 in MUSKINGCUNGE\", Km, X, dt,D\n              call hydro_stop(\"In MUSKINGCUNGE() - D is 0.\")\n           endif\n\n           C1 =  (Km*X + dt/2.000000)/D\n           C2 =  (dt/2.000000 - Km*X)/D\n           C3 =  (Km*(1.000000-X)-dt/2.000000)/D\n!          C1 =  max(0.0,min(1.0,1.0-C3)) !! eliminate influence of upstream current\n           if(ChannK .le. 0.0) then ! Disable channel loss for zero ChannK\n             C4 =  (ql*dt)/D\n           else\n             !C4 =  (ql*dt)/D  - (ChannK * dx * WPk)  !-- (loss units: m/s * m * m)\n             C4 =  ((ql - (ChannK * dx * WPk))*dt)/D  !-- TML: Loss adjusted by dt/D, closes water balance\n           endif\n\n           if( (C4 .lt. 0.0) .and. (abs(C4) .gt. (C1*qup)+(C2*quc)+(C3*qdp)))  then\n            C4 = -((C1*qup)+(C2*quc)+(C3*qdp))\n           endif\n\n           if((WP+WPC) .gt. 0.0) then\n            if( (C4 .lt. 0.0) .and. (abs(C4) .gt. (C1*qup)+(C2*quc)+(C3*qdp)))  then\n               C4 = -((C1*qup)+(C2*quc)+(C3*qdp))\n            endif\n            Qj =  ((C1*qup)+(C2*quc)+(C3*qdp) + C4) - ((1.0000000/(((WP*n)+(WPC*nCC))/(WP+WPC))) * &\n                    (AREA+AREAC) * (R**(2./3.)) * sqrt(So)) !f(x)\n           endif\n\n           if(Qj_0-Qj .ne. 0.0) then\n             h_1 = h - ((Qj * (h_0 - h))/(Qj_0 - Qj)) !update h, 3rd estimate\n              if(h_1 .lt. 0.0) then\n                h_1 = h\n              endif\n           else\n             h_1 = h\n           endif\n\n           if(h .gt. 0.0) then\n             rerror = abs((h_1 - h)/h) !relative error is new estatimate and 2nd estimate\n             aerror = abs(h_1 -h)      !absolute error\n           else\n             rerror = 0.0\n             aerror = 0.9\n           endif\n\n!          if(idx .eq. 6276407) then\n!            print*, \"err,itr,hs\", rerror, iter, depth, h_0, h, h_1\n!          endif\n\n           h_0  = max(0.0,h)\n           h    = max(0.0,h_1)\n           iter = iter + 1\n\n           if( h .lt. mindepth) then  ! exit loop if depth is very small\n             goto 111\n           endif\n\n         end do\n\n!          if(idx .eq.  6276407) then\n!            print*, \"id,itr,err,h\", idx, iter, rerror, h\n!          endif\n\n111      continue\n\n         if(iter .ge. maxiter) then\n\n           tries = tries + 1\n           if(tries .le. 4) then  ! expand the search space\n             h     =  h * 1.33\n             h_0   =  h_0 * 0.67\n             maxiter = maxiter + 25 !and increase the number of allowable iterations\n            goto 110\n           endif\n\n           print*, \"Musk Cunge WARNING: Failure to converge\"\n           print*, 'RouteLink index:', idx + linkls_s(my_id+1) - 1\n           print*, \"id,err,iters,tries\", idx, rerror, iter, tries\n           print*, \"Ck,X,dt,Km\",Ck,X,dt,Km\n           print*, \"So,dx,h\",So,dx,h\n           print*, \"qup,quc,qdp,ql\", qup,quc,qdp,ql\n           print*, \"bfd,Bw,Tw,Twl\", bfd,Bw,Tw,Twl\n           print*, \"Qmc,Qmn\", (C1*qup)+(C2*quc)+(C3*qdp) + C4,((1/(((WP*n)+(WPC*nCC))/(WP+WPC))) * &\n                    (AREA+AREAC) * (R**(2./3.)) * sqrt(So))\n         endif\n\n\n#ifdef HYDRO_D\n      !! Getting information on c3.\n      !if(rt_domain(1)%gages(idx + linkls_s(my_id+1) - 1) .ne. rt_domain(1)%gageMiss) then\n      !   print*, rt_domain(1)%gages(idx+linkls_s(my_id+1)-1)\n!     if(rt_domain(1)%gages(idx) .ne. rt_domain(1)%gageMiss) then\n!        print*, rt_domain(1)%gages(idx)\n!        print*,'JLM submuskcunge idx, C3, C, D:', idx + linkls_s(my_id+1) - 1, C3, dt/(2*Km), X\n!     end if\n#endif\n\n!yw added for test\n      !DY and LKR Added to update for channel loss\n        if(((C1*qup)+(C2*quc)+(C3*qdp) + C4) .lt. 0.0) then\n!       MUSKINGCUNGE =  MAX( ( (C1*qup)+(C2*quc) + C4),((C1*qup)+(C3*qdp) + C4) )\n           if( (C4 .lt. 0.0) .and. (abs(C4) .gt. (C1*qup)+(C2*quc)+(C3*qdp)) )  then ! channel loss greater than water in chan\n             qdc = 0.0\n           else\n             qdc = MAX( ( (C1*qup)+(C2*quc) + C4),((C1*qup)+(C3*qdp) + C4) )\n           endif\n        else\n!       MUSKINGCUNGE =  ((C1*qup)+(C2*quc)+(C3*qdp) + C4) !-- pg 295 Bedient huber\n          qdc =  ((C1*qup)+(C2*quc)+(C3*qdp) + C4) !-- pg 295 Bedient huber\n\n        endif\n\n        Twl = Bw + (2.0*z*h)\n        R = (h*(Bw + Twl) / 2.0) / (Bw + 2.0*(((Twl - Bw) / 2.0)**2.0 + h**2)**0.5)\n        vel =  (1./n) * (R **(2.0/3.0)) * sqrt(So)  ! average velocity in m/s\n        depth = h\n\n      else   ! no flow to route\n       qdc = 0.0\n       depth = 0.0\n     endif\n\n      qloss = (ChannK * dx * WPk) ! TML -- Compute qloss to pass\n\n      !TML:Added print statement to test qlos function;\n      !comment out to prevent excessive file sizes when running model\n      !print*, \"qloss,dx,WP,WPk,depth,ChannK,qdc,ql,dt,D\", qloss,dx,WP,WPk,depth,ChannK,qdc,ql,dt,D\n      if((qloss*dt)/D > ((ql*dt)/D - C4)) then\n         qloss = ql - C4*(D/dt)\n         if ((qloss < 0) .and. (ChannK /= 0)) then\n            print*, 'WARNING CHANNEL LOSS IS NEGATIVE',qloss\n         endif\n      endif\n\n! ----------------------------------------------------------------\nEND SUBROUTINE SUBMUSKINGCUNGE\n! ----------------------------------------------------------------\n\n! ------------------------------------------------\n!   FUNCTION KINEMATIC\n! ------------------------------------------------\n\tREAL FUNCTION KINEMATIC()\n\n\tIMPLICIT NONE\n\n! -------- DECLARATIONS -----------------------\n\n!\tREAL, INTENT(OUT), DIMENSION(IXRT,JXRT)\t:: OVRGH\n\n        KINEMATIC = 1\n!----------------------------------------------------------------\n  END FUNCTION KINEMATIC\n!----------------------------------------------------------------\n\n\n! ------------------------------------------------\n!   SUBROUTINE drive_CHANNEL\n! ------------------------------------------------\n! ------------------------------------------------\n     Subroutine drive_CHANNEL(did, latval,lonval,KT, IXRT,JXRT, SUBRTSWCRT, &\n       QSUBRT, LAKEINFLORT, QSTRMVOLRT, TO_NODE, FROM_NODE, &\n       TYPEL, ORDER, MAXORDER, NLINKS, CH_NETLNK, CH_NETRT, CH_LNKRT, &\n       LAKE_MSKRT, DT, DTCT, DTRT_CH,MUSK, MUSX, QLINK, &\n       QLateral, &\n       HLINK, ELRT, CHANLEN, MannN, So, ChSSlp, Bw, Tw, Tw_CC, n_CC,  &\n       ChannK, RESHT, HRZAREA, LAKEMAXH, WEIRH, WEIRC, WEIRL, ORIFICEC, ORIFICEA, ORIFICEE, &\n       ZELEV, CVOL, NLAKES, QLAKEI, QLAKEO, LAKENODE, &\n       dist, QINFLOWBASE, CHANXI, CHANYJ, channel_option, RETDEP_CHAN, &\n       NLINKSL, LINKID, node_area, lake_lookup  &\n#ifdef MPP_LAND\n       , lake_index,link_location,mpp_nlinks,nlinks_index,yw_mpp_nlinks  &\n       , LNLINKSL, LLINKID  &\n       , gtoNode,toNodeInd,nToNodeInd &\n#endif\n       , CH_LNKRT_SL &\n       ,gwBaseSwCRT, gwHead, qgw_chanrt, gwChanCondSw, gwChanCondConstIn, &\n       gwChanCondConstOut, velocity, qloss)\n\n\n       IMPLICIT NONE\n\n        ! -------- DECLARATIONS ------------------------\n        INTEGER, INTENT(IN) :: did, IXRT,JXRT,channel_option\n        INTEGER, INTENT(IN) :: NLINKS,NLAKES, NLINKSL\n        integer, INTENT(INOUT) :: KT   ! flag of cold start (1) or continue run.\n        REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: QSUBRT\n        REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: QSTRMVOLRT\n        REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: LAKEINFLORT\n        REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: ELRT\n        REAL, INTENT(IN), DIMENSION(IXRT,JXRT)    :: QINFLOWBASE\n        INTEGER(kind=int64), INTENT(IN), DIMENSION(IXRT,JXRT) :: CH_NETLNK\n\n        INTEGER, INTENT(IN), DIMENSION(IXRT,JXRT) :: CH_NETRT\n        INTEGER(kind=int64), INTENT(IN), DIMENSION(IXRT,JXRT) :: CH_LNKRT\n        INTEGER(kind=int64), INTENT(IN), DIMENSION(IXRT,JXRT) :: CH_LNKRT_SL\n\n       real , dimension(ixrt,jxrt):: latval,lonval\n\n        INTEGER, INTENT(IN), DIMENSION(IXRT,JXRT) :: LAKE_MSKRT\n        INTEGER, INTENT(IN), DIMENSION(NLINKS)    :: ORDER, TYPEL !--link\n        INTEGER(kind=int64), INTENT(IN), DIMENSION(NLINKS)    :: TO_NODE, FROM_NODE\n        INTEGER, INTENT(IN), DIMENSION(NLINKS)    :: CHANXI, CHANYJ\n        REAL,    INTENT(IN), DIMENSION(NLINKS)    :: ZELEV  !--elevation of nodes\n        REAL, INTENT(INOUT), DIMENSION(NLINKS)    :: CVOL\n        REAL, INTENT(IN), DIMENSION(NLINKS)       :: MUSK, MUSX\n        REAL, INTENT(IN), DIMENSION(NLINKS)       :: CHANLEN\n        REAL, INTENT(IN), DIMENSION(NLINKS)       :: So, MannN\n        REAL, INTENT(IN), DIMENSION(NLINKS)       :: ChSSlp,Bw,Tw  !--properties of nodes or links\n        REAL, INTENT(IN), DIMENSION(NLINKS)       :: Tw_CC, n_CC  !properties of compund channel\n        REAL, INTENT(IN), DIMENSION(NLINKS)       :: ChannK  !--Channel Infiltration\n        REAL                                      :: Km, X\n        REAL , INTENT(INOUT), DIMENSION(:,:) :: QLINK\n        REAL ,  DIMENSION(NLINKS,2) :: tmpQLINK\n        REAL , INTENT(INOUT), DIMENSION(NLINKS)   :: HLINK\n        REAL, dimension(NLINKS), intent(inout)    :: QLateral !--lateral flow\n        REAL, INTENT(IN)                          :: DT    !-- model timestep\n        REAL, INTENT(IN)                          :: DTRT_CH  !-- routing timestep\n        REAL, INTENT(INOUT)                       :: DTCT\n        real                                      :: minDTCT !BF minimum routing timestep\n        REAL                                      :: dist(ixrt,jxrt,9)\n        REAL                                      :: RETDEP_CHAN\n        INTEGER, INTENT(IN)                       :: MAXORDER, SUBRTSWCRT, &\n                                                     gwBaseSwCRT, gwChanCondSw\n        real, intent(in)                          :: gwChanCondConstIn, gwChanCondConstOut ! aquifer-channel conductivity constant from namelist\n        REAL , INTENT(IN), DIMENSION(NLINKS)      :: node_area\n        real, dimension(:), INTENT(inout)         :: velocity, qloss\n\n\n!DJG GW-chan coupling variables...\n        REAL, DIMENSION(NLINKS)                   :: dzGwChanHead\n        REAL, DIMENSION(NLINKS)                   :: Q_GW_CHAN_FLUX     !DJG !!! Change 'INTENT' to 'OUT' when ready to update groundwater state...\n        REAL, DIMENSION(IXRT,JXRT)                :: ZWATTBLRT          !DJG !!! Match with subsfce/gw routing & Change 'INTENT' to 'INOUT' when ready to update groundwater state...\n        REAL, INTENT(INOUT), DIMENSION(:,:), allocatable :: gwHead      !DJG !!! groundwater head from Fersch-2d gw implementation...units (m ASL)\n        REAL, INTENT(INOUT), DIMENSION(:,:), allocatable :: qgw_chanrt  !DJG !!! Channel-gw flux as used in Fersch 2d gw implementation...units (m^3/s)...Change 'INTENT' to 'OUT' when ready to update groundwater state...\n\n\n\n        !-- lake params\n        REAL, INTENT(IN), DIMENSION(NLAKES)       :: HRZAREA  !-- horizontal area (km^2)\n        REAL, INTENT(IN), DIMENSION(NLAKES)       :: LAKEMAXH !-- maximum lake depth  (m^2)\n        REAL, INTENT(IN), DIMENSION(NLAKES)       :: WEIRH    !-- lake depth  (m^2)\n        REAL, INTENT(IN), DIMENSION(NLAKES)       :: WEIRC    !-- weir coefficient\n        REAL, INTENT(IN), DIMENSION(NLAKES)       :: WEIRL    !-- weir length (m)\n        REAL, INTENT(IN), DIMENSION(NLAKES)       :: ORIFICEC !-- orrifice coefficient\n        REAL, INTENT(IN), DIMENSION(NLAKES)       :: ORIFICEA !-- orrifice area (m^2)\n        REAL, INTENT(IN), DIMENSION(NLAKES)       :: ORIFICEE !-- orrifce elevation (m)\n\n        REAL, INTENT(INOUT), DIMENSION(NLAKES)    :: RESHT    !-- reservoir height (m)\n        REAL*8,  DIMENSION(NLAKES)    :: QLAKEI8   !-- lake inflow (cms)\n        REAL, INTENT(INOUT), DIMENSION(NLAKES)    :: QLAKEI   !-- lake inflow (cms)\n        REAL,                DIMENSION(NLAKES)    :: QLAKEIP  !-- lake inflow previous timestep (cms)\n        REAL, INTENT(INOUT), DIMENSION(NLAKES)    :: QLAKEO   !-- outflow from lake used in diffusion scheme\n        INTEGER(kind=int64), INTENT(IN), DIMENSION(NLINKS)    :: LAKENODE !-- outflow from lake used in diffusion scheme\n        INTEGER(kind=int64), INTENT(IN), DIMENSION(NLINKS)    :: LINKID   !--  id of channel elements for linked scheme\n        !REAL, DIMENSION(NLINKS)                   :: QLateral !--lateral flow\n        REAL, DIMENSION(NLINKS)                   :: QSUM     !--mass bal of node\n        REAL*8, DIMENSION(NLINKS)                   :: QSUM8     !--mass bal of node\n        REAL, DIMENSION(NLAKES)                   :: QLLAKE   !-- lateral inflow to lake in diffusion scheme\n        REAL*8, DIMENSION(NLAKES)                   :: QLLAKE8   !-- lateral inflow to lake in diffusion scheme\n\n        integer, intent(in), dimension(:)     :: lake_lookup  !-- inverse lake index for k->lake mapping\n\n!-- Local Variables\n        INTEGER                     :: i,j,k,t,m,jj,kk,KRT,node,l_idx, lakeid\n        INTEGER                     :: DT_STEPS               !-- number of timestep in routing\n        REAL                        :: Qup,Quc                !--Q upstream Previous, Q Upstream Current, downstream Previous\n        REAL                        :: bo                     !--critical depth, bnd outflow just for testing\n        REAL                        :: AREA,WP                !--wetted area and perimiter for MuskingC. routing\n\n        REAL ,DIMENSION(NLINKS)     :: HLINKTMP,CVOLTMP       !-- temporarily store head values and volume values\n        REAL ,DIMENSION(NLINKS)     :: CD                     !-- critical depth\n        real, DIMENSION(IXRT,JXRT)  :: tmp\n        real, dimension(nlinks)     :: tmp2\n\n#ifdef MPP_LAND\n        integer lake_index(nlakes)\n        integer nlinks_index(nlinks)\n        integer mpp_nlinks, iyw, yw_mpp_nlinks\n        integer(kind=int64) link_location(ixrt,jxrt)\n        real     ywtmp(ixrt,jxrt)\n        integer LNLINKSL\n        integer(kind=int64), dimension(LNLINKSL) :: LLINKID\n        real(kind=8),  dimension(LNLINKSL) :: LQLateral\n        integer, dimension(:) ::  toNodeInd\n        integer(kind=int64), dimension(:,:) ::  gtoNode\n        integer  :: nToNodeInd\n        real, dimension(nToNodeInd,2) :: gQLINK\n        real, allocatable,dimension(:) :: tmpQLAKEO, tmpQLAKEI, tmpRESHT\n#else\n        real(kind=8), dimension(NLINKS)                   :: LQLateral !--lateral flow\n#endif\n        integer flag\n\n        integer :: n, kk2, nt, nsteps  ! tmp\n\n#ifdef MPP_LAND\n       if(my_id == io_id) then\n#endif\n           allocate(tmpQLAKEO(NLAKES))\n           allocate(tmpQLAKEI(NLAKES))\n           allocate(tmpRESHT(NLAKES))\n#ifdef MPP_LAND\n        endif\n#endif\n        QLAKEIP = 0\n        QLAKEI8 = 0\n        HLINKTMP = 0\n        CVOLTMP = 0\n        CD = 0\n        node = 1\n        QLateral = 0\n        QSUM     = 0\n        QLLAKE   = 0\n\n\n!yw      print *, \"DRIVE_channel,option,nlinkl,nlinks!!\", channel_option,NLINKSL,NLINKS\n!      print *, \"DRIVE_channel, RESHT\", RESHT\n\n\n      dzGwChanHead = 0.\n\n   IF(channel_option .ne. 3) then   !--muskingum methods ROUTE ON DT timestep, not DTRT!!\n\n         nsteps = (DT+0.5)/DTRT_CH\n\n#ifdef MPP_LAND\n         LQLateral = 0          !-- initial lateral flow to 0 for this reach\n         DO iyw = 1,yw_MPP_NLINKS\n         jj = nlinks_index(iyw)\n          !--------river grid points, convert depth in mm to rate across reach in m^3/sec\n              if( .not. (  (CHANXI(jj) .eq. 1 .and. left_id .ge. 0) .or. &\n                           (CHANXI(jj) .eq. ixrt .and. right_id .ge. 0) .or. &\n                           (CHANYJ(jj) .eq. 1 .and. down_id .ge. 0) .or. &\n                           (CHANYJ(jj) .eq. jxrt .and. up_id .ge. 0)      &\n                   ) ) then\n                  if (CH_LNKRT_SL(CHANXI(jj),CHANYJ(jj)) .gt. 0) then\n                     k = CH_LNKRT_SL(CHANXI(jj),CHANYJ(jj))\n                     LQLateral(k) = LQLateral(k)+((QSTRMVOLRT(CHANXI(jj),CHANYJ(jj))+QINFLOWBASE(CHANXI(jj),CHANYJ(jj)))/1000 &\n                            *node_area(jj)/DT)\n                  elseif ( (LAKE_MSKRT(CHANXI(jj),CHANYJ(jj)) .gt. 0)) then !-lake grid\n                      k = LAKE_MSKRT(CHANXI(jj),CHANYJ(jj))\n                      LQLateral(k) = LQLateral(k) +((LAKEINFLORT(CHANXI(jj),CHANYJ(jj))+QINFLOWBASE(CHANXI(jj),CHANYJ(jj)))/1000 &\n                               *node_area(jj)/DT)\n                  endif\n              endif\n         end do  ! jj\n\n\n!   assign LQLATERAL to QLATERAL\n       call updateLinkV(LQLateral, QLateral(1:NLINKSL))\n\n#else\n\n         LQLateral = 0          !-- initial lateral flow to 0 for this reach\n         do jj = 1, NLINKS\n          !--------river grid points, convert depth in mm to rate across reach in m^3/sec\n\n                  if (CH_LNKRT_SL(CHANXI(jj),CHANYJ(jj)) .gt. 0 ) then\n                     k = CH_LNKRT_SL(CHANXI(jj),CHANYJ(jj))\n                     LQLateral(k) = LQLateral(k)+((QSTRMVOLRT(CHANXI(jj),CHANYJ(jj))+QINFLOWBASE(CHANXI(jj),CHANYJ(jj)))/1000 &\n                            *node_area(jj)/DT)\n                  elseif ( (LAKE_MSKRT(CHANXI(jj),CHANYJ(jj)) .gt. 0)) then !-lake grid\n                      k = LAKE_MSKRT(CHANXI(jj),CHANYJ(jj))\n                      LQLateral(k) = LQLateral(k) +((LAKEINFLORT(CHANXI(jj),CHANYJ(jj))+QINFLOWBASE(CHANXI(jj),CHANYJ(jj)))/1000 &\n                               *node_area(jj)/DT)\n                  endif\n\n          end do  ! jj\n          QLateral = LQLateral\n\n#endif\n\n!       QLateral = QLateral / nsteps\n\n   do nt = 1, nsteps\n\n!Per Yates, this check is not needed. Commenting out for now.\n!----------  route order 1 reaches which have no upstream inflow\n!        do k=1, NLINKSL\n!           if (ORDER(k) .eq. 1) then  !-- first order stream has no headflow\n\n\n!              if(TYPEL(k) .eq. 1) then    !-- level pool route of reservoir\n!                  !CALL LEVELPOOL(1,0.0, 0.0, qd, QLINK(k,2), QLateral(k), &\n!                  ! DT, RESHT(k), HRZAREA(k), LAKEMAXH(k), &\n!                  ! WEIRC(k), WEIRL(k), ORIFICEE(i), ORIFICEC(k), ORIFICEA(k) )\n!              elseif (channel_option .eq. 1) then\n!                   Km  = MUSK(k)\n!                   X   = MUSX(k)\n!                   QLINK(k,2) = MUSKING(k,0.0, QLateral(k), QLINK(k,1), DTRT_CH, Km, X) !--current outflow\n!              elseif (channel_option .eq. 2) then !-- upstream is assumed constant initial condition\n\n!                   call SUBMUSKINGCUNGE(QLINK(k,2), velocity(k), k,  &\n!                    0.0,0.0, QLINK(k,1), QLateral(k),   DTRT_CH, So(k), &\n!                    CHANLEN(k), MannN(k), ChSSlp(k), Bw(k), Tw(k) )\n\n!              else\n!                  print *, \"FATAL ERROR: No channel option selected\"\n!                  call hydro_stop(\"In drive_CHANNEL() -No channel option selected \")\n!              endif\n!           endif\n!        end do\n\n#ifdef MPP_LAND\n       gQLINK = 0.000\n       call gbcastReal2(toNodeInd,nToNodeInd,QLINK(1:NLINKSL,2), NLINKSL, gQLINK(:,2))\n       call gbcastReal2(toNodeInd,nToNodeInd,QLINK(1:NLINKSL,1), NLINKSL, gQLINK(:,1))\n#endif\n\n      !---------- route other reaches, with upstream inflow\n       tmpQlink = 0.0\n#ifdef MPP_LAND\n       if(my_id .eq. io_id) then\n#endif\n            tmpQLAKEO = QLAKEO\n            tmpQLAKEI = QLAKEI\n            tmpRESHT = RESHT\n#ifdef MPP_LAND\n       endif\n#endif\n       do k = 1,NLINKSL\n!          if (ORDER(k) .gt. 1 ) then  !-- exclude first order stream\n             Quc  = 0.0\n             Qup  = 0.0\n\n#ifdef MPP_LAND\n!using mapping index\n               do n = 1, gtoNODE(k,1)\n                  m = gtoNODE(k,n+1)\n!yw                  if (LINKID(k) .eq. m) then\n                    Quc = Quc + gQLINK(m,2)  !--accum of upstream inflow of current timestep (2)\n                    Qup = Qup + gQLINK(m,1)  !--accum of upstream inflow of previous timestep (1)\n\n                      !     if(LINKID(k) .eq. 3259 .or. LINKID(k) .eq. 3316 .or. LINKID(k) .eq. 3219) then\n                      !       write(6,*) \"id,Uc,Up\",LINKID(k),Quc,Qup\n                      !       call flush(6)\n                      !     endif\n\n!yw                  endif\n                end do ! do i\n\n#else\n               do m = 1, NLINKSL\n                  if (LINKID(k) .eq. TO_NODE(m)) then\n                    Quc = Quc + QLINK(m,2)  !--accum of upstream inflow of current timestep (2)\n                    Qup = Qup + QLINK(m,1)  !--accum of upstream inflow of previous timestep (1)\n                  endif\n               end do ! do m\n#endif\n\n                if(TYPEL(k) == 1) then   !--link is a reservoir\n                    l_idx = lake_lookup(k)\n                    if (l_idx >= 0) then     !-- -999 if not a reservoir in the lookup table (belt-and-suspenders check)\n                        call rt_domain(did)%reservoirs(l_idx)%ptr%run(Qup, Quc, 0.0, &\n                              RESHT(l_idx), QLINK(k,2), DTRT_CH, rt_domain(did)%final_reservoir_type(l_idx), &\n                              rt_domain(did)%reservoir_assimilated_value(l_idx), rt_domain(did)%reservoir_assimilated_source_file(l_idx))\n\n                        QLAKEO(l_idx)  = QLINK(k,2)     !save outflow to lake\n                        QLAKEI(l_idx)  = Quc            !save inflow to lake\n                    end if\n                elseif (channel_option .eq. 1) then  !muskingum routing\n                       Km = MUSK(k)\n                       X = MUSX(k)\n                       tmpQLINK(k,2) = MUSKING(k,Qup,(Quc+QLateral(k)),QLINK(k,1),DTRT_CH,Km,X) !upstream plus lateral inflow\n                   elseif (channel_option .eq. 2) then ! muskingum cunge\n\n                   call SUBMUSKINGCUNGE(tmpQLINK(k,2), velocity(k), qloss(k), LINKID(k),  &\n                    Qup,Quc, QLINK(k,1), QLateral(k),   DTRT_CH, So(k), &\n                    CHANLEN(k), MannN(k), ChSSlp(k), Bw(k), Tw(k),Tw_CC(k), n_CC(k),  HLINK(k), ChannK(k) )\n\n                else\n                    print *, \"FATAL ERROR: no channel option selected\"\n                    call hydro_stop(\"In drive_CHANNEL() - no channel option selected\")\n                   endif\n!            endif !!! order(1) .ne. 1\n         end do       !--k links\n\n#ifdef MPP_LAND\n         call updateLake_seq(RESHT,nlakes,tmpRESHT)\n         call updateLake_seq(QLAKEO,nlakes,tmpQLAKEO)\n         call updateLake_seq(QLAKEI,nlakes,tmpQLAKEI)\n#endif\n\n!yw check\n!        gQLINK = 0.0\n!        call ReachLS_write_io(tmpQLINK(:,2), gQLINK(:,2))\n!        call ReachLS_write_io(tmpQLINK(:,1), gQLINK(:,1))\n!        write(6,*) \" io_id = \", io_id\n!        if(my_id .eq. io_id) then\n!            write(71,*) gQLINK(:,1)\n!            call flush(71)\n!            call flush(72)\n!        endif\n\n          do k = 1, NLINKSL\n            if(TYPEL(k) .ne. 1) then\n               QLINK(k,2) = tmpQLINK(k,2)\n            endif\n            QLINK(k,1) = QLINK(k,2)    !assing link flow of current to be previous for next time step\n         end do\n\n   end do ! nsteps\n\n#ifdef HYDRO_D\n          print *, \"END OF ALL REACHES...\",KRT,DT_STEPS\n#endif\n\n!    END DO !-- krt timestep for muksingumcunge routing\n\n   elseif(channel_option .eq. 3) then   !--- route using the diffusion scheme on nodes not links\n\n#ifdef MPP_LAND\n         call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,HLINK,NLINKS,99)\n         call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,CVOL,NLINKS,99)\n#endif\n\n         KRT = 0                  !-- initialize the time counter\n         minDTCT = 0.01           ! define minimum routing sub-timestep (s), simulation will end with smaller timestep\n         DTCT = min(max(DTCT*2.0, minDTCT),DTRT_CH)\n\n         HLINKTMP = HLINK         !-- temporary storage of the water elevations (m)\n         CVOLTMP = CVOL           !-- temporary storage of the volume of water in channel (m^3)\n         QLAKEIP = QLAKEI         !-- temporary lake inflow from previous timestep  (cms)\n\n!        call check_channel(77,HLINKTMP,1,nlinks)\n!        call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,ZELEV,NLINKS,99)\n crnt:   DO                      !-- loop on the courant condition\n          QSUM     = 0.              !-- initialize the total flow out of each cell to zero\n          QSUM8     = 0.              !-- initialize the total flow out of each cell to zero\n          QLAKEI8  = 0.              !-- set the lake inflow as zero\n          QLAKEI   = 0.              !-- set the lake inflow as zero\n          QLLAKE   = 0.              !-- initialize each lake's lateral inflow to zero\n          QLLAKE8   = 0.              !-- initialize each lake's lateral inflow to zero\n          DT_STEPS = INT(DT/DTCT)   !-- fix the timestep\n          QLateral = 0.\n!DJG GW-chan coupling variables...\n          if(gwBaseSwCRT == 3) then\n\t  Q_GW_CHAN_FLUX = 0.\n\t  qgw_chanrt     = 0.\n          end if\n\n!         ZWATTBLRT=1.0   !--HARDWIRE, remove this and pass in from subsfc/gw routing routines...\n\n\n!-- vectorize\n!---------------------\n#ifdef MPP_LAND\n         DO iyw = 1,yw_MPP_NLINKS\n         i = nlinks_index(iyw)\n#else\n         DO i = 1,NLINKS\n#endif\n\n           if(node_area(i) .eq. 0) then\n               write(6,*) \"FATAL ERROR: node_area(i) is zero. i=\", i\n               call hydro_stop(\"In drive_CHANNEL() - Error node_area\")\n           endif\n\n\n\nnodeType:if((CH_NETRT(CHANXI(i), CHANYJ(i) ) .eq. 0) .and. &\n              (LAKE_MSKRT(CHANXI(i),CHANYJ(i)) .lt.0) ) then !--a reg. node\n\ngwOption:   if(gwBaseSwCRT == 3) then\n\n             ! determine potential gradient between groundwater head and channel stage\n             ! units in (m)\n             dzGwChanHead(i) = gwHead(CHANXI(i),CHANYJ(i)) - (HLINK(i)+ZELEV(i))\n\n             if(gwChanCondSw .eq. 0) then\n\n                qgw_chanrt(CHANXI(i),CHANYJ(i)) = 0.\n\n             else if(gwChanCondSw .eq. 1 .and. dzGwChanHead(i) > 0) then\n\n\t       ! channel bed interface, units in (m^3/s), flux into channel...\n\t       ! BF todo: consider channel width\n                qgw_chanrt(CHANXI(i),CHANYJ(i)) = gwChanCondConstIn * dzGwChanHead(i) &\n                                                * CHANLEN(i) * 2.\n\n             else if(gwChanCondSw .eq. 1 .and. dzGwChanHead(i) < 0) then\n\n\t       ! channel bed interface, units in (m^3/s), flux out of channel...\n\t       ! BF todo: consider channel width\n                qgw_chanrt(CHANXI(i),CHANYJ(i)) = max(-0.005, gwChanCondConstOut * dzGwChanHead(i) &\n                                                * CHANLEN(i) * 2.)\n!              else if(gwChanCondSw .eq. 2 .and. dzGwChanHead(i) > 0) then  TBD: exponential dependency\n!              else if(gwChanCondSw .eq. 2 .and. dzGwChanHead(i) > 0) then\n\n             else\n\n\t        qgw_chanrt(CHANXI(i),CHANYJ(i)) = 0.\n\n             end if\n\n             Q_GW_CHAN_FLUX(i) = qgw_chanrt(CHANXI(i),CHANYJ(i))\n!             if ( i .eq. 1001 ) then\n!                print *, Q_GW_CHAN_FLUX(i), dzGwChanHead(i), ELRT(CHANXI(i),CHANYJ(i)), HLINK(i), ZELEV(i)\n!             end if\n!              if ( Q_GW_CHAN_FLUX(i) .lt. 0. ) then   !-- temporary hardwire for only allowing flux into channel...REMOVE later...\n!                 Q_GW_CHAN_FLUX(i) = 0.\n! \t        qgw_chanrt(CHANXI(i),CHANYJ(i)) = 0.\n!              end if\n\n            else\n\t      Q_GW_CHAN_FLUX(i) = 0.\n\t    end if gwOption\n\n\n              QLateral(CH_NETLNK(CHANXI(i),CHANYJ(i))) =  &\n!DJG  awaiting gw-channel exchg...  Q_GW_CHAN_FLUX(i)+& ...obsolete-> ((QSUBRT(CHANXI(i),CHANYJ(i))+&\n                Q_GW_CHAN_FLUX(i)+&\n                ((QSTRMVOLRT(CHANXI(i),CHANYJ(i))+&\n                 QINFLOWBASE(CHANXI(i),CHANYJ(i))) &\n                   /DT_STEPS*node_area(i)/1000/DTCT)\n\t       if((QLateral(CH_NETLNK(CHANXI(i),CHANYJ(i))).lt.0.) .and. (gwChanCondSw == 0)) then\n#ifdef HYDRO_D\n               print*, \"i, CHANXI(i),CHANYJ(i) = \", i, CHANXI(i),CHANYJ(i)\n               print *, \"NEGATIVE Lat inflow...\",QLateral(CH_NETLNK(CHANXI(i),CHANYJ(i))), &\n                         QSUBRT(CHANXI(i),CHANYJ(i)),QSTRMVOLRT(CHANXI(i),CHANYJ(i)), &\n                         QINFLOWBASE(CHANXI(i),CHANYJ(i))\n#endif\n               elseif (QLateral(CH_NETLNK(CHANXI(i),CHANYJ(i))) .gt. 1.0) then\n!#ifdef HYDRO_D\n!               print *, \"LatIn(Ql,Qsub,Qstrmvol)..\",i,QLateral(CH_NETLNK(CHANXI(i),CHANYJ(i))), &\n!                          QSUBRT(CHANXI(i),CHANYJ(i)),QSTRMVOLRT(CHANXI(i),CHANYJ(i))\n!#endif\n               end if\n\n         elseif(LAKE_MSKRT(CHANXI(i),CHANYJ(i)) .gt. 0 .and. &\n!               (LAKE_MSKRT(CHANXI(i),CHANYJ(i)) .ne. -9999)) then !--a lake node\n                (CH_NETRT(CHANXI(i),CHANYJ(i)) .le. 0)) then !--a lake node\n              QLLAKE8(LAKE_MSKRT(CHANXI(i),CHANYJ(i))) = &\n                 QLLAKE8(LAKE_MSKRT(CHANXI(i),CHANYJ(i))) + &\n                 (LAKEINFLORT(CHANXI(i),CHANYJ(i))+ &\n                 QINFLOWBASE(CHANXI(i),CHANYJ(i))) &\n                 /DT_STEPS*node_area(i)/1000/DTCT\n         elseif(CH_NETRT(CHANXI(i),CHANYJ(i)) .gt. 0) then  !pour out of lake\n                 QLateral(CH_NETLNK(CHANXI(i),CHANYJ(i))) =  &\n                   QLAKEO(CH_NETRT(CHANXI(i),CHANYJ(i)))  !-- previous timestep\n         endif nodeType\n\n        ENDDO\n\n\n#ifdef MPP_LAND\n    call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,QLateral,NLINKS,99)\n    if(NLAKES .gt. 0) then\n       !yw call MPP_CHANNEL_COM_REAL(LAKE_MSKRT   ,ixrt,jxrt,QLLAKE,NLAKES,99)\n       call sum_real8(QLLAKE8,NLAKES)\n       QLLAKE = QLLAKE8\n    endif\n#endif\n\n          !-- compute conveyances, with known depths (just assign to QLINK(,1)\n          !--QLINK(,2) will not be used), QLINK is the flow across the node face\n          !-- units should be m3/second.. consistent with QL (lateral flow)\n\n#ifdef MPP_LAND\n         DO iyw = 1,yw_MPP_NLINKS\n         i = nlinks_index(iyw)\n#else\n           DO i = 1,NLINKS\n#endif\n           if (TYPEL(i) .eq. 0 .AND. HLINKTMP(FROM_NODE(i)) .gt. RETDEP_CHAN) then\n               if(from_node(i) .ne. to_node(i) .and. (to_node(i) .gt. 0) .and.(from_node(i) .gt. 0) ) &  ! added by Wei Yu\n                   QLINK(i,1)=DIFFUSION(i,ZELEV(FROM_NODE(i)),ZELEV(TO_NODE(i)), &\n                     HLINKTMP(FROM_NODE(i)),HLINKTMP(TO_NODE(i)), &\n                     CHANLEN(i), MannN(i), Bw(i), ChSSlp(i))\n            else !--  we are just computing critical depth for outflow points\n               QLINK(i,1) =0.\n            endif\n          ENDDO\n\n#ifdef MPP_LAND\n    call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,QLINK(:,1),NLINKS,99)\n#endif\n\n\n          !-- compute total flow across face, into node\n#ifdef MPP_LAND\n         DO iyw = 1,yw_mpp_nlinks\n         i = nlinks_index(iyw)\n#else\n          DO i = 1,NLINKS                                                 !-- inflow to node across each face\n#endif\n           if(TYPEL(i) .eq. 0) then                                       !-- only regular nodes have to attribute\n              QSUM8(TO_NODE(i)) = QSUM8(TO_NODE(i)) + QLINK(i,1)\n           endif\n          END DO\n\n#ifdef MPP_LAND\n    call MPP_CHANNEL_COM_REAL8(Link_location,ixrt,jxrt,qsum8,NLINKS,0)\n#endif\n    qsum = qsum8\n\n\n\n#ifdef MPP_LAND\n         do iyw = 1,yw_mpp_nlinks\n         i = nlinks_index(iyw)\n#else\n         do i = 1,NLINKS                                                 !-- outflow from node across each face\n#endif\n            QSUM(FROM_NODE(i)) = QSUM(FROM_NODE(i)) - QLINK(i,1)\n         end do\n#ifdef MPP_LAND\n    call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,qsum,NLINKS,99)\n#endif\n\n\n         flag = 99\n\n\n#ifdef MPP_LAND\n         do iyw = 1,yw_MPP_NLINKS\n             i = nlinks_index(iyw)\n#else\n         do i = 1, NLINKS                                                !--- compute volume and depth at each node\n#endif\n\n           if( TYPEL(i).eq.0 .and. CVOLTMP(i) .ge. 0.001 .and.(CVOLTMP(i)-QSUM(i)*DTCT)/CVOLTMP(i) .le. -0.01 ) then\n            flag = -99\n#ifdef HYDRO_D\n            write(6,*) \"******* start diag ***************\"\n            write(6,*) \"Unstable at node \",i, \"i=\",CHANXI(i),\"j=\",CHANYJ(i)\n            write(6,*) \"Unstatble at node \",i, \"lat=\",latval(CHANXI(i),CHANYJ(i)), \"lon=\",lonval(CHANXI(i),CHANYJ(i))\n            write(6,*) \"TYPEL, CVOLTMP, QSUM, QSUM*DTCT\",TYPEL(i), CVOLTMP(i), QSUM(i), QSUM(i)*DTCT\n            write(6,*) \"qsubrt, qstrmvolrt,qlink\",QSUBRT(CHANXI(i),CHANYJ(i)),QSTRMVOLRT(CHANXI(i),CHANYJ(i)),qlink(i,1),qlink(i,2)\n!              write(6,*) \"current nodes, z, h\", ZELEV(FROM_NODE(i)),HLINKTMP(FROM_NODE(i))\n!           if(TO_NODE(i) .gt. 0) then\n!              write(6,*) \"to nodes, z, h\", ZELEV(TO_NODE(i)), HLINKTMP(TO_NODE(i))\n!           else\n!              write(6,*) \"no to nodes   \"\n!           endif\n               write(6,*) \"CHANLEN(i), MannN(i), Bw(i), ChSSlp(i) \", CHANLEN(i), MannN(i), Bw(i), ChSSlp(i)\n            write(6,*) \"*******end of  diag ***************\"\n#endif\n\n            goto 999\n            endif\n          enddo\n\n999 continue\n#ifdef MPP_LAND\n        call mpp_same_int1(flag)\n#endif\n\n\n        if(flag < 0  .and. DTCT >0.1)   then\n\n             ! call smoth121(HLINK,nlinks,maxv_p,pnode,to_node)\n\n             if(DTCT .gt. minDTCT) then                !-- timestep in seconds\n              DTCT = max(DTCT/2 , minDTCT)             !-- 1/2 timestep\n              KRT = 0                                  !-- restart counter\n              HLINKTMP = HLINK                         !-- set head and vol to start value of timestep\n              CVOLTMP = CVOL\n              CYCLE crnt                               !-- start cycle over with smaller timestep\n             else\n              write(6,*) \"Courant error with smallest routing timestep DTCT: \",DTCT\n!              call hydro_stop(\"drive_CHANNEL\")\n              DTCT = 0.1\n              HLINKTMP = HLINK                          !-- set head and volume to start values of timestep\n              CVOLTMP  = CVOL\n              goto 998\n             end if\n        endif\n\n998 continue\n\n\n#ifdef MPP_LAND\n        do iyw = 1,yw_MPP_NLINKS\n            i = nlinks_index(iyw)\n#else\n        do i = 1, NLINKS                                                !--- compute volume and depth at each node\n#endif\n\n           if(TYPEL(i) .eq. 0) then                   !--  regular channel grid point, compute volume\n              CVOLTMP(i) = CVOLTMP(i) + (QSUM(i) + QLateral(i) )* DTCT\n              if((CVOLTMP(i) .lt. 0) .and. (gwChanCondSw == 0)) then\n#ifdef HYDRO_D\n                print *, \"WARNING! channel volume less than 0:i,CVOL,QSUM,QLat\", &\n                               i, CVOLTMP(i),QSUM(i),QLateral(i),HLINK(i)\n#endif\n                CVOLTMP(i) =0\n              endif\n\n           elseif(TYPEL(i) .eq. 1) then               !-- pour point, critical depth downstream\n\n              if (QSUM(i)+QLateral(i) .lt. 0) then\n              else\n\n!DJG remove to have const. flux b.c....   CD(i) =CRITICALDEPTH(i,abs(QSUM(i)+QLateral(i)), Bw(i), 1./ChSSlp(i))\n                  CD(i) = HLINKTMP(i)  !This is a temp hardwire for flow depth for the pour point...\n              endif\n\n               ! change in volume is inflow, lateral flow, and outflow\n               !yw DIFFUSION(i,ZELEV(i),ZELEV(i)-(So(i)*DXRT),HLINKTMP(i), &\n                   CVOLTMP(i) = CVOLTMP(i) + (QSUM(i) + QLateral(i) - &\n                       DIFFUSION(i,ZELEV(i),ZELEV(i)-(So(i)*CHANLEN(i)),HLINKTMP(i), &\n                       CD(i),CHANLEN(i), MannN(i), Bw(i), ChSSlp(i)) ) * DTCT\n          elseif (TYPEL(i) .eq. 2) then              !--- into a reservoir, assume critical depth\n              if ((QSUM(i)+QLateral(i) .lt. 0) .and. (gwChanCondSw == 0)) then\n#ifdef HYDRO_D\n               print *, i, 'CrtDpth Qsum+QLat into lake< 0',QSUM(i), QLateral(i)\n#endif\n             else\n!DJG remove to have const. flux b.c....    CD(i) =CRITICALDEPTH(i,abs(QSUM(i)+QLateral(i)), Bw(i), 1./ChSSlp(i))\n               CD(i) = HLINKTMP(i)  !This is a temp hardwire for flow depth for the pour point...\n             endif\n\n              !-- compute volume in reach (m^3)\n                   CVOLTMP(i) = CVOLTMP(i) + (QSUM(i) + QLateral(i) - &\n                          DIFFUSION(i,ZELEV(i),ZELEV(i)-(So(i)*CHANLEN(i)),HLINKTMP(i), &\n                             CD(i) ,CHANLEN(i), MannN(i), Bw(i), ChSSlp(i)) ) * DTCT\n          else\n              print *, \"FATAL ERROR: This node does not have a type.. error TYPEL =\", TYPEL(i)\n              call hydro_stop(\"In drive_CHANNEL() - error TYPEL\")\n          endif\n\n          if(TYPEL(i) == 0) then !-- regular channel node, finalize head and flow\n              HLINKTMP(i) = HEAD(i, CVOLTMP(i)/CHANLEN(i),Bw(i),1/ChSSlp(i))  !--updated depth\n          else\n              HLINKTMP(i) = CD(i)  !!!   CRITICALDEPTH(i,QSUM(i)+QLateral(i), Bw(i), 1./ChSSlp(i)) !--critical depth is head\n          endif\n\n          if(TO_NODE(i) .gt. 0) then\n             if(LAKENODE(TO_NODE(i)) .gt. 0) then\n                  QLAKEI8(LAKENODE(TO_NODE(i))) = QLAKEI8(LAKENODE(TO_NODE(i))) + QLINK(i,1)\n             endif\n          endif\n\n        END DO  !--- done processing all the links\n\n#ifdef MPP_LAND\n    call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,CVOLTMP,NLINKS,99)\n    call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,CD,NLINKS,99)\n    if(NLAKES .gt. 0) then\n!       call MPP_CHANNEL_COM_REAL(LAKE_MSKRT,ixrt,jxrt,QLAKEI,NLAKES,99)\n        call sum_real8(QLAKEI8,NLAKES)\n        QLAKEI = QLAKEI8\n    endif\n    call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,HLINKTMP,NLINKS,99)\n#endif\n!   call check_channel(83,CVOLTMP,1,nlinks)\n!   call check_channel(84,CD,1,nlinks)\n!   call check_channel(85,HLINKTMP,1,nlinks)\n!   call check_lake(86,QLAKEI,lake_index,nlakes)\n\n           do i = 1, NLAKES !-- mass balances of lakes\n#ifdef MPP_LAND\n            if(lake_index(i) .gt. 0)  then\n#endif\n\n              ! Calls run for a single reservoir depending on its type as\n              ! in whether it uses level pool, machine learning, or persistence.\n              ! Inflow, lateral inflow, water elevation, and the routing period\n              ! are passed in. Updated outflow and water elevation are returned.\n              call rt_domain(did)%reservoirs(i)%ptr%run(QLAKEIP(i), QLAKEI(i), &\n                   QLLAKE(i), RESHT(i), QLAKEO(i), DTCT, rt_domain(did)%final_reservoir_type(i), &\n                   rt_domain(did)%reservoir_assimilated_value(i), rt_domain(did)%reservoir_assimilated_source_file(i))\n\n              ! TODO: Encapsulate the lake state variable for water elevation (RESHT(i))\n              !       inside the reservoir module, but it requires a redesign of the lake\n              !       MPI communication model.\n\n              QLAKEIP(i) = QLAKEI(i)  !-- store total lake inflow for this timestep\n\n\n#ifdef MPP_LAND\n            endif\n#endif\n           enddo\n#ifdef MPP_LAND\n    if(NLAKES .gt. 0) then\n!yw       call MPP_CHANNEL_COM_REAL(LAKE_MSKRT,ixrt,jxrt,QLLAKE,NLAKES,99)\n!yw       call MPP_CHANNEL_COM_REAL(LAKE_MSKRT,ixrt,jxrt,RESHT,NLAKES,99)\n!yw      call MPP_CHANNEL_COM_REAL(LAKE_MSKRT,ixrt,jxrt,QLAKEO,NLAKES,99)\n!yw      call MPP_CHANNEL_COM_REAL(LAKE_MSKRT,ixrt,jxrt,QLAKEI,NLAKES,99)\n!yw      call MPP_CHANNEL_COM_REAL(LAKE_MSKRT,ixrt,jxrt,QLAKEIP,NLAKES,99)\n\n         ! TODO: Change updateLake_grid calls below to updated distributed reservoir\n         !       objects and not arrays as currently implemented.\n         call updateLake_grid(QLLAKE, nlakes,lake_index)\n         call updateLake_grid(RESHT,  nlakes,lake_index)\n         call updateLake_grid(QLAKEO, nlakes,lake_index)\n         call updateLake_grid(QLAKEI, nlakes,lake_index)\n         call updateLake_grid(QLAKEIP,nlakes,lake_index)\n    endif\n#endif\n\n\n#ifdef MPP_LAND\n         do iyw = 1,yw_MPP_NLINKS\n            i = nlinks_index(iyw)\n#else\n         do i = 1, NLINKS                                                !--- compute volume and depth at each node\n#endif\n            if(TYPEL(i) == 0) then !-- regular channel node, finalize head and flow\n                   QLINK(i,1)=DIFFUSION(i,ZELEV(FROM_NODE(i)),ZELEV(TO_NODE(i)), &\n                      HLINKTMP(FROM_NODE(i)),HLINKTMP(TO_NODE(i)), &\n                      CHANLEN(i), MannN(i), Bw(i), ChSSlp(i))\n            endif\n         enddo\n\n#ifdef MPP_LAND\n          call MPP_CHANNEL_COM_REAL(Link_location,ixrt,jxrt,QLINK(:,1),NLINKS,99)\n#endif\n\n           KRT = KRT + 1                     !-- iterate on the timestep\n           if(KRT .eq. DT_STEPS) exit crnt   !-- up to the maximum time in interval\n\n          end do crnt   !--- DTCT timestep of DT_STEPS\n\n           HLINK = HLINKTMP                 !-- update head based on final solution in timestep\n           CVOL  = CVOLTMP                  !-- update volume\n        else                                !-- no channel option apparently selected\n         print *, \"FATAL ERROR: no channel option selected\"\n         call hydro_stop(\"In drive_CHANNEL() - no channel option selected\")\n        endif\n\n#ifdef HYDRO_D\n         write(6,*) \"finished call drive_CHANNEL\"\n#endif\n\n        if (KT .eq. 1) KT = KT + 1\n\n#ifdef MPP_LAND\n       if (my_id == io_id) then\n           if(allocated(tmpRESHT))  deallocate(tmpRESHT)\n           if(allocated(tmpQLAKEO))  deallocate(tmpQLAKEO)\n           if(allocated(tmpQLAKEI))  deallocate(tmpQLAKEI)\n       endif\n#endif\nend subroutine drive_CHANNEL\n! ----------------------------------------------------------------\n\n!-=======================================\n     REAL FUNCTION AREAf(AREA,Bw,h,z)\n     REAL :: AREA, Bw, z, h\n       AREAf = (Bw+z*h)*h-AREA       !-- Flow area\n     END FUNCTION AREAf\n\n!-====critical depth function  ==========\n     REAL FUNCTION CDf(Q,Bw,h,z)\n     REAL :: Q, Bw, z, h\n       if(h .le. 0) then\n         print *, \"FATAL ERROR: head is zero, will get division by zero error\"\n         call hydro_stop(\"In CDf() - head is zero\")\n       else\n       CDf = (Q/((Bw+z*h)*h))/(sqrt(9.81*(((Bw+z*h)*h)/(Bw + 2.0*z*h)))) - 1.0  !--critical depth function\n       endif\n     END FUNCTION CDf\n\n!=======find flow depth in channel with bisection Chapra pg. 131\n    REAL FUNCTION HEAD(idx,AREA,Bw,z)  !-- find the water elevation given wetted area,\n                                         !--bottom widith and side channel.. index was for debuggin\n     REAL :: Bw,z,AREA,test\n     REAL :: hl, hu, hr, hrold\n     REAL :: fl, fr,error                !-- function evaluation\n     INTEGER :: maxiter, idx\n\n     error = 1.0\n     maxiter = 0\n     hl = 0.00001   !-- minimum depth is small\n     hu = 30.  !-- assume maximum depth is 30 meters\n\n    if (AREA .lt. 0.00001) then\n     hr = 0.\n    else\n       ! JLM: .gt. \"0\" is somewhat alarming. We really should have a constant like zero_r4\n      do while ((AREAf(AREA,BW,hl,z)*AREAf(AREA,BW,hu,z)) .gt. 0.0 .and. maxiter .lt. 100)\n       !-- allows for larger , smaller heads\n       if(AREA .lt. 1.) then\n        hl=hl/2\n       else\n        hu = hu * 2\n       endif\n       maxiter = maxiter + 1\n\n      end do\n\n      maxiter =0\n      hr = 0\n      fl = AREAf(AREA,Bw,hl,z)\n      do while (error .gt. 0.0001 .and. maxiter < 1000)\n        hrold = hr\n        hr = (hl+hu)/2\n        fr =  AREAf(AREA,Bw,hr,z)\n        maxiter = maxiter + 1\n         if (hr .ne. 0) then\n          error = abs((hr - hrold)/hr)\n         endif\n        test = fl * fr\n         if (test.lt.0) then\n           hu = hr\n         elseif (test.gt.0) then\n           hl=hr\n           fl = fr\n         else\n           error = 0.0\n         endif\n      end do\n     endif\n     HEAD = hr\n\n22   format(\"i,hl,hu,Area\",i5,2x,f12.8,2x,f6.3,2x,f6.3,2x,f6.3,2x,f9.1,2x,i5)\n\n    END FUNCTION HEAD\n!=================================\n     REAL FUNCTION MANNING(h1,n,Bw,Cs)\n\n     REAL :: Bw,h1,Cs,n\n     REAL :: z, AREA,R,Kd\n\n     z = 1.0/Cs\n     R = ((Bw + z*h1)*h1)/(Bw + 2.0*h1*sqrt(1.0 + z*z)) !-- Hyd Radius\n     AREA = (Bw + z*h1)*h1        !-- Flow area\n     Kd = (1.0/n) * (R**(2.0/3.0))*AREA     !-- convenyance\n#ifdef HYDRO_D\n     print *,\"head, kd\",  h1,Kd\n#endif\n     MANNING = Kd\n\n     END FUNCTION MANNING\n\n!=======find flow depth in channel with bisection Chapra pg. 131\n     REAL FUNCTION CRITICALDEPTH(lnk, Q, Bw, z)  !-- find the critical depth\n     REAL :: Bw, z, Q, test\n     REAL :: hl, hu, hr, hrold\n     REAL :: fl, fr, error   !-- function evaluation\n     INTEGER :: maxiter\n     INTEGER :: lnk\n\n     error = 1.0\n     maxiter = 0\n     hl = 1.0e-5   !-- minimum depth is 0.00001 meters\n!    hu = 35.       !-- assume maximum  critical depth 25 m\n     hu = 100.       !-- assume maximum  critical depth 25 m\n\n     if(CDf(Q, BW, hl, z) * CDf(Q, BW, hu, z) .gt. 0.0) then\n      if(Q .gt. 0.001) then\n#ifdef HYDRO_D\n        print *, \"interval won't work to find CD of lnk \", lnk\n        print *, \"Q, hl, hu\", Q, hl, hu\n        print *, \"cd lwr, upr\", CDf(Q, BW, hl, z), CDf(Q, BW, hu, z)\n        ! call hydro_stop(\"In CRITICALDEPTH()\")\n        CRITICALDEPTH = -9999\n        return\n#endif\n      else\n        Q = 0.0\n      endif\n     endif\n\n     hr = 0.\n     fl = CDf(Q, Bw, hl, z)\n\n     if (Q .eq. 0.0) then\n       hr = 0.\n     else\n      do while (error .gt. 0.0001 .and. maxiter < 1000)\n        hrold = hr\n        hr = (hl+hu)/2.0\n        fr =  CDf(Q, Bw, hr, z)\n        maxiter = maxiter + 1\n         if (hr .ne. 0.0) then\n          error = abs((hr - hrold)/hr)\n         endif\n        test = fl * fr\n         if (test .lt. 0) then\n           hu = hr\n         elseif (test .gt. 0) then\n           hl=hr\n           fl = fr\n         else\n           error = 0.0\n         endif\n\n       end do\n      endif\n\n     CRITICALDEPTH = hr\n     END FUNCTION CRITICALDEPTH\n\n\n     REAL FUNCTION SGNf(val)  !-- function to return the sign of a number\n     REAL:: val\n\n     if (val .lt. 0) then\n       SGNf= -1.\n     elseif (val.gt.0) then\n       SGNf= 1.\n     else\n       SGNf= 0.\n     endif\n\n     END FUNCTION SGNf\n!================================================\n\n     REAL FUNCTION fnDX(qp,Tw,So,Ck,dx,dt) !-- find channel sub-length for MK method\n     REAL    :: qp,Tw,So,Ck,dx, dt,test\n     REAL    :: dxl, dxu, dxr, dxrold\n     REAL    :: fl, fr, error\n     REAL    :: X\n     INTEGER :: maxiter\n\n     error = 1.0\n     maxiter =0\n     dxl = dx*0.9  !-- how to choose dxl???\n     dxu = dx\n     dxr=0\n\n     do while (fnDXCDT(qp,Tw,So,Ck,dxl,dt)*fnDXCDT(qp,Tw,So,Ck,dxu,dt) .gt. 0 &\n               .and. dxl .gt. 10)  !-- don't let dxl get too small\n      dxl = dxl/1.1\n     end do\n\n\n     fl = fnDXCDT(qp,Tw,So,Ck,dxl,dt)\n     do while (error .gt. 0.0001 .and. maxiter < 1000)\n        dxrold = dxr\n        dxr = (dxl+dxu)/2\n        fr =  fnDXCDT(qp,Tw,So,Ck,dxr,dt)\n        maxiter = maxiter + 1\n         if (dxr .ne. 0) then\n          error = abs((dxr - dxrold)/dxr)\n         endif\n        test = fl * fr\n         if (test.lt.0) then\n           dxu = dxr\n         elseif (test.gt.0) then\n           dxl=dxr\n           fl = fr\n         else\n           error = 0.0\n         endif\n      end do\n     FnDX = dxr\n\n    END FUNCTION fnDX\n!================================================\n     REAL FUNCTION fnDXCDT(qp,Tw,So,Ck,dx,dt) !-- function to help find sub-length for MK method\n     REAL    :: qp,Tw,So,Ck,dx,dt,X\n     REAL    :: c,b  !-- coefficients on dx/cdt log approximation function\n\n     c = 0.2407\n     b = 1.16065\n     X = 0.5-(qp/(2.0*Tw*So*Ck*dx))\n     if (X .le. 0.0) then\n      fnDXCDT = -1.0 !0.115\n     else\n      fnDXCDT = (dx/(Ck*dt)) - (c*LOG(X)+b)  !-- this function needs to converge to 0\n     endif\n     END FUNCTION fnDXCDT\n! ----------------------------------------------------------------------\n\n    subroutine check_lake(unit,cd,lake_index,nlakes)\n         use module_RT_data, only: rt_domain\n         implicit none\n         integer :: unit,nlakes,i,lake_index(nlakes)\n         real cd(nlakes)\n#ifdef MPP_LAND\n         call write_lake_real(cd,lake_index,nlakes)\n#endif\n         write(unit,*) cd\n          call flush(unit)\n    end subroutine check_lake\n\n    subroutine check_channel(unit,cd,did,nlinks)\n         use module_RT_data, only: rt_domain\n#ifdef MPP_LAND\n  USE module_mpp_land\n#endif\n         implicit none\n         integer :: unit,nlinks,i, did\n         real cd(nlinks)\n#ifdef MPP_LAND\n         real g_cd(rt_domain(did)%gnlinks)\n         call write_chanel_real(cd,rt_domain(did)%map_l2g,rt_domain(did)%gnlinks,nlinks,g_cd)\n         if(my_id .eq. IO_id) then\n            write(unit,*) \"rt_domain(did)%gnlinks = \",rt_domain(did)%gnlinks\n           write(unit,*) g_cd\n         endif\n#else\n           write(unit,*) cd\n#endif\n          call flush(unit)\n          close(unit)\n    end subroutine check_channel\n    subroutine smoth121(var,nlinks,maxv_p,from_node,to_node)\n        implicit none\n        integer,intent(in) ::  nlinks, maxv_p\n        integer, intent(in), dimension(nlinks):: to_node\n        integer, intent(in), dimension(nlinks):: from_node(nlinks,maxv_p)\n        real, intent(inout), dimension(nlinks) :: var\n        real, dimension(nlinks) :: vartmp\n        integer :: i,j  , k, from,to\n        integer :: plen\n              vartmp = 0\n              do i = 1, nlinks\n                 to = to_node(i)\n                 plen = from_node(i,1)\n                 if(plen .gt. 1) then\n                     do k = 1, plen-1\n                         from = from_node(i,k+1)\n                         if(to .gt. 0) then\n                            vartmp(i) = vartmp(i)+0.25*(var(from)+2.*var(i)+var(to))\n                         else\n                            vartmp(i) = vartmp(i)+(2.*var(i)+var(from))/3.0\n                         endif\n                     end do\n                     vartmp(i) = vartmp(i) /(plen-1)\n                 else\n                         if(to .gt. 0) then\n                            vartmp(i) = vartmp(i)+(2.*var(i)+var(to)/3.0)\n                         else\n                            vartmp(i) = var(i)\n                         endif\n                 endif\n              end do\n              var = vartmp\n    end subroutine smoth121\n\n!   SUBROUTINE drive_CHANNEL for NHDPLUS\n! ------------------------------------------------\n\n     subroutine drive_CHANNEL_RSL(did, UDMP_OPT,KT, IXRT,JXRT,  &\n        LAKEINFLORT, QSTRMVOLRT, TO_NODE, FROM_NODE, &\n        TYPEL, ORDER, MAXORDER,   CH_LNKRT, &\n        LAKE_MSKRT, DT, DTCT, DTRT_CH,MUSK, MUSX, QLINK, &\n        CHANLEN, MannN, So, ChSSlp, Bw, Tw, Tw_CC, n_CC, &\n        ChannK, RESHT, CVOL, QLAKEI, QLAKEO, LAKENODE, &\n        QINFLOWBASE, CHANXI, CHANYJ, channel_option,  &\n        nlinks,NLINKSL, LINKID, node_area, qout_gwsubbas, &\n        LAKEIDA, LAKEIDM, NLAKES, LAKEIDX, &\n#ifdef MPP_LAND\n        nlinks_index,mpp_nlinks,yw_mpp_nlinks, &\n        LNLINKSL, &\n        gtoNode,toNodeInd,nToNodeInd,   &\n#endif\n         CH_LNKRT_SL, landRunOff  &\n#ifdef WRF_HYDRO_NUDGING\n       , nudge &\n#endif\n       , accSfcLatRunoff, accBucket                  &\n       , qSfcLatRunoff,     qBucket                  &\n       , QLateral, velocity, qloss                   &\n       , HLINK                                       &\n       , nsize , OVRTSWCRT, SUBRTSWCRT, channel_only, channelBucket_only, &\n       channel_bypass)\n\n       use module_UDMAP, only: LNUMRSL, LUDRSL\n       use config_base, only: nlst\n\n#ifdef WRF_HYDRO_NUDGING\n       use module_RT_data, only: rt_domain\n       use module_stream_nudging,  only: setup_stream_nudging,               &\n                                         nudge_term_all,                     &\n                                         nudgeWAdvance,                      &\n                                         nudge_apply_upstream_muskingumCunge\n#endif\n      use module_channel_diversions, only: calculate_diversion\n      use ieee_arithmetic, only: ieee_is_nan\n\n       implicit none\n\n! -------- DECLARATIONS ------------------------\n       integer, intent(IN) :: did, IXRT,JXRT,channel_option, OVRTSWCRT, SUBRTSWCRT\n       integer, intent(IN) :: NLAKES, NLINKSL, nlinks\n       integer, intent(INOUT) :: KT   ! flag of cold start (1) or continue run.\n       real, intent(IN), dimension(IXRT,JXRT)    :: QSTRMVOLRT\n       real, intent(IN), dimension(IXRT,JXRT)    :: LAKEINFLORT\n       real, intent(IN), dimension(IXRT,JXRT)    :: QINFLOWBASE\n       real, dimension(ixrt,jxrt) :: landRunOff\n\n       integer(kind=int64), intent(IN), dimension(IXRT,JXRT) :: CH_LNKRT\n       integer(kind=int64), intent(IN), dimension(IXRT,JXRT) :: CH_LNKRT_SL\n\n       integer, intent(IN), dimension(IXRT,JXRT) :: LAKE_MSKRT\n       integer, intent(IN), dimension(:)         :: ORDER, TYPEL !--link\n       integer(kind=int64), intent(in), dimension(:)     :: TO_NODE, FROM_NODE\n       integer, intent(IN), dimension(:)     :: CHANXI, CHANYJ\n       real, intent(IN), dimension(:)        :: MUSK, MUSX\n       real, intent(IN), dimension(:)        :: CHANLEN\n       real, intent(IN), dimension(:)        :: So, MannN\n       real, intent(IN), dimension(:)        :: ChSSlp,Bw,Tw  !--properties of nodes or links\n       real, intent(IN), dimension(:)        :: Tw_CC, n_CC   ! properties of compound channel\n       real, intent(IN), dimension(:)        :: ChannK  !--channel infiltration\n       real                                      :: Km, X\n       real , intent(INOUT), dimension(:,:)  :: QLINK\n       real , intent(INOUT), dimension(:)    :: HLINK\n\n       logical, intent(in) :: channel_bypass\n\n#ifdef WRF_HYDRO_NUDGING\n       !! inout for applying previous nudge to upstream components of flow at gages\n       real, intent(inout),    dimension(:)    :: nudge\n#endif\n\n       real, dimension(:), intent(inout)     :: QLateral !--lateral flow\n       real, dimension(:), intent(out)       :: velocity, qloss\n       real*8, dimension(:), intent(inout)     :: accSfcLatRunoff, accBucket\n       real  , dimension(:), intent(out)     :: qSfcLatRunoff  ,   qBucket\n\n       real ,  dimension(NLINKSL,2) :: tmpQLINK\n       real, intent(IN)                          :: DT    !-- model timestep\n       real, intent(IN)                          :: DTRT_CH  !-- routing timestep\n       real, intent(INOUT)                       :: DTCT\n       real                                      :: minDTCT !BF minimum routing timestep\n       integer, intent(IN)                       :: MAXORDER\n       real , intent(IN), dimension(:)   :: node_area\n\n       !DJG GW-chan coupling variables...\n       real, dimension(NLINKS)                   :: dzGwChanHead\n       real, dimension(NLINKS)                   :: Q_GW_CHAN_FLUX     !DJG !!! Change 'INTENT' to 'OUT' when ready to update groundwater state...\n       real, dimension(IXRT,JXRT)                :: ZWATTBLRT          !DJG !!! Match with subsfce/gw routing & Change 'INTENT' to 'INOUT' when ready to update groundwater state...\n\n       !-- lake params\n       integer(kind=int64), intent(IN), dimension(:)    :: LAKEIDM  !-- NHDPLUS lakeid for lakes to be modeled\n\n       real, intent(INOUT), dimension(:)    :: RESHT    !-- reservoir height (m)\n       real, intent(INOUT), dimension(:)    :: QLAKEI   !-- lake inflow (cms)\n       real,                dimension(NLAKES)    :: QLAKEIP  !-- lake inflow previous timestep (cms)\n       real, intent(INOUT), dimension(NLAKES)    :: QLAKEO   !-- outflow from lake used in diffusion scheme\n\n       integer(kind=int64), intent(IN), dimension(:)    :: LAKENODE !-- outflow from lake used in diffusion scheme\n       integer(kind=int64), intent(IN), dimension(:)   :: LINKID   !--  id of channel elements for linked scheme\n       integer(kind=int64), intent(IN), dimension(:)   :: LAKEIDA  !--  (don't need) NHDPLUS lakeid for all lakes in domain\n       integer, intent(IN), dimension(:)   :: LAKEIDX  !--  the sequential index of the lakes id by com id\n\n       real, dimension(NLINKS)                   :: QSUM     !--mass bal of node\n       real, dimension(NLAKES)                   :: QLLAKE   !-- lateral inflow to lake in diffusion scheme\n       integer :: nsize\n\n       !-- Local Variables\n       integer                      :: i,j,k,t,m,jj,ii,lakeid, kk,KRT,node, UDMP_OPT\n       integer                      :: DT_STEPS               !-- number of timestep in routing\n       real                         :: Qup,Quc                !--Q upstream Previous, Q Upstream Current, downstream Previous\n       real                         :: bo                     !--critical depth, bnd outflow just for testing\n\n       real ,dimension(NLINKS)                          :: CD    !-- critical depth\n       real, dimension(IXRT,JXRT)                       :: tmp\n       real, dimension(nlinks)                          :: tmp2\n       real, intent(INOUT), dimension(:)           :: CVOL\n\n#ifdef MPP_LAND\n       real*8,  dimension(LNLINKSL) :: LQLateral\n       real*8,  dimension(LNLINKSL) :: tmpLQLateral\n       real,  dimension(NLINKSL)    :: tmpQLateral\n\n       integer nlinks_index(:)\n       integer  iyw, yw_mpp_nlinks, mpp_nlinks\n       real     ywtmp(ixrt,jxrt)\n       integer LNLINKSL\n       integer, dimension(:)         ::  toNodeInd\n       integer(kind=int64), dimension(:,:)       ::  gtoNode\n       integer  :: nToNodeInd\n       real, dimension(nToNodeInd,2) :: gQLINK\n#else\n       real*8,  dimension(NLINKS) :: tmpLQLateral\n       real,  dimension(NLINKSL) :: tmpQLateral\n       real,  dimension(NLINKSL) :: LQLateral\n#endif\n       integer flag\n       integer, intent(in) :: channel_only, channelBucket_only\n\n       integer :: n, kk2, nt, nsteps  ! tmp\n       real, intent(in), dimension(:) :: qout_gwsubbas\n       real, allocatable,dimension(:) :: tmpQLAKEO, tmpQLAKEI, tmpRESHT\n       integer, allocatable, dimension(:) :: tmpFinalResType\n       real, allocatable,dimension(:) :: tmpAssimilatedValue\n       character(len=256), allocatable,dimension(:) :: tmpAssimilatedSourceFile\n\n       ! diversions\n       real :: div_src, div_dst\n       character(*), parameter :: free = '(*(g0,1x))'\n\n#ifdef MPP_LAND\n       if(my_id .eq. io_id) then\n#endif\n            allocate(tmpQLAKEO(NLAKES))\n            allocate(tmpQLAKEI(NLAKES))\n            allocate(tmpRESHT(NLAKES))\n            allocate(tmpFinalResType(nlakes))\n#ifdef MPP_LAND\n        endif\n#endif\n\n        QLAKEIP = 0\n        CD = 0\n        node = 1\n        QSUM     = 0\n        QLLAKE   = 0\n        dzGwChanHead = 0.\n        nsteps = (DT+0.5)/DTRT_CH\n\n#ifdef WRF_HYDRO_NUDGING\n         !! Initialize nudging for the current timestep.\n         !! This establishes the data structure used to solve the nudges.\n         call setup_stream_nudging(0)  !! always zero b/c at beginning of hydro timestep\n#endif /* WRF_HYDRO_NUDGING */\n\n!---------------------------------------------\nif(channel_only .eq. 1 .or. channelBucket_only .eq. 1) then\n#ifdef HYDRO_D\n   write(6,*)  \"channel_only or channelBucket_only is not zero. Special flux calculations.\"\n   call flush(6)\n#endif /* HYDRO_D */\n\n!   if(nlst_rt(1)%output_channelBucket_influx .eq. 1 .or. &\n!        nlst_rt(1)%output_channelBucket_influx .eq. 2       ) &\n!        !! qScfLatRunoff = qLateral - qBucket\n!        qSfcLatRunoff(1:NLINKSL) = qLateral(1:NLINKSL) - qout_gwsubbas(1:NLINKSL)\n\n   if(nlst(1)%output_channelBucket_influx .eq. 1 .or. &\n      nlst(1)%output_channelBucket_influx .eq. 2       ) then\n\n      if(channel_only .eq. 1) &\n        !! qScfLatRunoff = qLateral - qBucket\n        qSfcLatRunoff(1:NLINKSL) = qLateral(1:NLINKSL) - qout_gwsubbas(1:NLINKSL)\n\n      if(channelBucket_only .eq. 1) &\n        !! qScfLatRunoff = qLateral - qBucket\n        qSfcLatRunoff(1:NLINKSL) = qLateral(1:NLINKSL)\n\n   end if\n\n   if(nlst(1)%output_channelBucket_influx .eq. 3) &\n        accSfcLatRunoff(1:NLINKSL) = qSfcLatRunoff * DT\n\nelse\n\n   QLateral = 0 !! the variable solved in this section. Channel only knows this already.\n   LQLateral = 0          !-- initial lateral flow to 0 for this reach\n\n   tmpQLateral = 0  !! WHY DOES THIS tmp variable EXIST?? Only for accumulations??\n   tmpLQLateral = 0\n\n   ! NHDPLUS maping\n   if(OVRTSWCRT .eq. 0)      then\n      do k = 1, LNUMRSL\n         ! get from land grid runoff\n         do m = 1, LUDRSL(k)%ncell\n            ii =  LUDRSL(k)%cell_i(m)\n            jj =  LUDRSL(k)%cell_j(m)\n            LQLateral(k) = LQLateral(k)+landRunOff(ii,jj)*LUDRSL(k)%cellweight(m)/1000 &\n                 *LUDRSL(k)%cellArea(m)/DT\n            tmpLQLateral(k) = tmpLQLateral(k)+landRunOff(ii,jj)*LUDRSL(k)%cellweight(m)/1000 &\n                 *LUDRSL(k)%cellArea(m)/DT\n         end do\n      end do\n\n#ifdef MPP_LAND\n      call updateLinkV(tmpLQLateral, tmpQLateral)\n#endif\n      if(NLINKSL .gt. 0) then\n         if (nlst(1)%output_channelBucket_influx .eq. 1 .or. &\n             nlst(1)%output_channelBucket_influx .eq. 2      ) &\n               qSfcLatRunoff(1:NLINKSL) = tmpQLateral(1:NLINKSL)\n         if (nlst(1)%output_channelBucket_influx .eq. 3) &\n              accSfcLatRunoff(1:NLINKSL) = accSfcLatRunoff(1:NLINKSL) + tmpQLateral(1:NLINKSL) * DT\n      endif\n      tmpLQLateral = 0  !! JLM:: These lines imply that squeege runoff does not count towards\n      tmpQLateral = 0   !! JLM:: accumulated runoff to be output but it does for internal QLateral?\n      !! JLM: But then the next accumulation is added to the amt before zeroing? result\n      !! JLM: should be identical to LQLateral.... I'm totally mystified.\n   endif\n\n   !! JLM:: if ovrtswcrt=0 and subrtswcrt=1, then this accumulation is calculated twice for LQLateral???\n   !! This impiles that if overland routing is off and subsurface routing is on, that\n   !! qstrmvolrt represents only the subsurface contribution to the channel.\n   if(OVRTSWCRT .ne. 0 .or. SUBRTSWCRT .ne. 0 ) then\n      do k = 1, LNUMRSL\n         ! get from channel grid\n         do m = 1, LUDRSL(k)%ngrids\n            ii =  LUDRSL(k)%grid_i(m)\n            jj =  LUDRSL(k)%grid_j(m)\n            LQLateral(k) = LQLateral(k) + QSTRMVOLRT(ii,jj)*LUDRSL(k)%weight(m)/1000 &\n                 *LUDRSL(k)%nodeArea(m)/DT\n            tmpLQLateral(k) = tmpLQLateral(k) + QSTRMVOLRT(ii,jj)*LUDRSL(k)%weight(m)/1000 &\n                 *LUDRSL(k)%nodeArea(m)/DT\n         end do\n      end do\n\n#ifdef MPP_LAND\n      call updateLinkV(tmpLQLateral, tmpQLateral)\n#endif\n\n      !! JLM:: again why output in this conditional ?? why not just output QLateral\n      !! after this section ????\n      if(NLINKSL .gt. 0) then\n         if(nlst(1)%output_channelBucket_influx .eq. 1 .OR. &\n            nlst(1)%output_channelBucket_influx .eq. 2       ) &\n              qSfcLatRunoff(1:NLINKSL) = tmpQLateral(1:NLINKSL)\n         if(nlst(1)%output_channelBucket_influx .eq. 3) &\n              accSfcLatRunoff(1:NLINKSL) = accSfcLatRunoff(1:NLINKSL) + tmpQLateral(1:NLINKSL) * DT\n      end if\n\n   endif\n\n#ifdef MPP_LAND\n   call updateLinkV(LQLateral, QLateral(1:NLINKSL))\n#else\n   call hydro_stop(\"fatal error: NHDPlus only works for parallel now.\")\n   QLateral = LQLateral\n#endif\nendif !! (channel_only .eq. 1 .or. channelBucket_only .eq. 1) then; else; endif\n\n\n!---------------------------------------------\n!! If not running channelOnly, here is where the bucket model is picked up\nif(channel_only .eq. 1) then\n#ifdef HYDRO_D\n   write(6,*)  \"channel_only is not zero. No bucket.\"\n   call flush(6)\n#endif /* HYDRO_D */\nelse\n   !! REQUIRE BUCKET MODEL ON HERE?\n   if(NLINKSL .gt. 0) QLateral(1:NLINKSL) = QLateral(1:NLINKSL) + qout_gwsubbas(1:NLINKSL)\nendif  !! if(channel_only .eq. 1) then; else; endif\n\nif(nlst(1)%output_channelBucket_influx .eq. 1 .or. &\n   nlst(1)%output_channelBucket_influx .eq. 2       ) &\n      qBucket(1:NLINKSL) = qout_gwsubbas(1:NLINKSL)\n\nif(nlst(1)%output_channelBucket_influx .eq. 3) &\n     accBucket(1:NLINKSL) = accBucket(1:NLINKSL) + qout_gwsubbas(1:NLINKSL) * DT\n\n! Skip this section if we are NOT running any actual channel routing\nif (.not. channel_bypass) then\n\n!---------------------------------------------\n!       QLateral = QLateral / nsteps\ndo nt = 1, nsteps\n\n#ifdef MPP_LAND\n   gQLINK = 0\n   call gbcastReal2(toNodeInd,nToNodeInd,QLINK(1:NLINKSL,2), NLINKSL, gQLINK(:,2))\n   call gbcastReal2(toNodeInd,nToNodeInd,QLINK(1:NLINKSL,1), NLINKSL, gQLINK(:,1))\n   !---------- route other reaches, with upstream inflow\n#endif\n\n   tmpQlink = 0\n#ifdef MPP_LAND\n   if(my_id .eq. io_id) then\n#endif\n      tmpQLAKEO = QLAKEO\n      tmpQLAKEI = QLAKEI\n      tmpRESHT = RESHT\n      tmpFinalResType = rt_domain(did)%final_reservoir_type\n      tmpAssimilatedValue = rt_domain(did)%reservoir_assimilated_value\n      tmpAssimilatedSourceFile = rt_domain(did)%reservoir_assimilated_source_file\n\n#ifdef MPP_LAND\n   endif\n#endif\n\n   do k = 1,NLINKSL\n\n      Quc  = 0\n      Qup  = 0\n\n      !process as standard link or a lake inflow link, or lake outflow link\n      ! link flowing out of lake, accumulate all the inflows with the revised TO_NODEs\n      ! TYPEL = -999 stnd; TYPEL=1 outflow from lake; TYPEL = 3 inflow to a lake\n\n      if(TYPEL(k) .ne. 2) then ! don't process internal lake links only\n\n#ifdef MPP_LAND\n         !using mapping index\n         do n = 1, gtoNODE(k,1)\n            m = gtoNODE(k,n+1)\n            !! JLM - I think gQLINK(,2) is actually previous. Global array never sees current. Seeing\n            !! current would require global communication at the end of each loop through k\n            !! (=kth reach). Additionally, how do you synchronize to make sure the upstream are all\n            !! done before doing the downstream?\n            if(gQLINK(m,2) .gt. 0)   Quc = Quc + gQLINK(m,2)  !--accum of upstream inflow of current timestep (2)\n            if(gQLINK(m,1) .gt. 0)   Qup = Qup + gQLINK(m,1)  !--accum of upstream inflow of previous timestep (1)\n         end do ! do i\n#else\n         do m = 1, NLINKSL\n            if (LINKID(k) .eq. TO_NODE(m)) then\n               Quc = Quc + QLINK(m,2)  !--accum of upstream inflow of current timestep (2)\n               Qup = Qup + QLINK(m,1)  !--accum of upstream inflow of previous timestep (1)\n            endif\n         end do ! do m\n#endif\n      endif !note that we won't process type 2 links, since they are internal to a lake\n\n\n      !yw ### process each link k,\n      !       There is a situation that different k point to the same LAKEIDX\n      !        if(TYPEL(k) .eq. 1 .and. LAKEIDX(k) .gt. 0) then   !--link is a reservoir\n      if(TYPEL(k) .eq. 1 ) then   !--link is a reservoir\n\n         lakeid = LAKEIDX(k)\n         if(lakeid .ge. 0) then\n\n            ! Calls run for a single reservoir depending on its type as\n            ! in whether it uses level pool, machine learning, or persistence.\n            ! Inflow, lateral inflow, water elevation, and the routing period\n            ! are passed in. Updated outflow and water elevation are returned.\n            call rt_domain(did)%reservoirs(lakeid)%ptr%run(Qup, Quc, 0.0, &\n                 RESHT(lakeid), tmpQLINK(k,2), DTRT_CH, rt_domain(did)%final_reservoir_type(lakeid), &\n                 rt_domain(did)%reservoir_assimilated_value(lakeid), rt_domain(did)%reservoir_assimilated_source_file(lakeid))\n\n            ! TODO: Encapsulate the lake state variable for water elevation (RESHT(lakeid))\n            !       inside the reservoir module, but it requires a redesign of the lake\n            !       MPI communication model.\n\n            QLAKEO(lakeid)  = tmpQLINK(k,2) !save outflow to lake\n            QLAKEI(lakeid)  = Quc           !save inflow to lake\n         endif\n105      continue\n\n\n      elseif (channel_option .eq. 1) then  !muskingum routing\n         Km = MUSK(k)\n         X = MUSX(k)\n         tmpQLINK(k,2) = MUSKING(k,Qup,(Quc+QLateral(k)),QLINK(k,1),DTRT_CH,Km,X) !upstream plust lateral inflow\n\n      elseif (channel_option .eq. 2) then ! muskingum cunge, don't process internal lake nodes TYP=2\n         !              tmpQLINK(k,2) = MUSKINGCUNGE(k,Qup, Quc, QLINK(k,1), &\n         !                  QLateral(k), DTRT_CH, So(k),  CHANLEN(k), &\n         !                  MannN(k), ChSSlp(k), Bw(k), Tw(k) )\n\n         ! HANDLE DIVERSIONS\n\n         call calculate_diversion(LINKID(k), Quc, div_src, div_dst)\n\n         if (div_src /= 0) then\n            ! remove from upstream\n#ifdef HYDRO_D\n            print free, \"DEBUG: diverting\", div_src, \"of\", Quc, \"from link id =\", LINKID(k) !, \"on processor\", my_id\n            if (div_src > Quc) &\n               print free, \"DEBUG WARNING: diverted flow (\", div_src, \") exceeds total flow, zeroing.\"\n#endif\n            Quc = max(0.0, Quc - div_src)\n            Qup = max(0.0, Qup - div_src)\n         end if\n\n         if (div_dst /= 0) then\n            ! apply observed value to downstream\n#ifdef HYDRO_D\n            print free, \"DEBUG: diverting\", div_dst, \"to link id =\", LINKID(k) !, \"on processor\", my_id\n#endif\n            Qup = div_dst\n            Quc = div_dst\n            tmpQLINK(k,2) = div_dst\n\n            ! reset any NaNs that got through\n            if (ieee_is_nan(div_dst)) then\n               ! fallback to zero if div_dst is NaN\n               if (ieee_is_nan(QLINK(k,1))) QLINK(k,1) = 0.0\n               if (ieee_is_nan(QLINK(k,2))) QLINK(k,2) = 0.0\n            else\n               if (ieee_is_nan(QLINK(k,1))) QLINK(k,1) = tmpQLINK(k,2)\n               if (ieee_is_nan(QLINK(k,2))) QLINK(k,2) = tmpQLINK(k,2)\n            end if\n         end if\n\n#ifdef WRF_HYDRO_NUDGING\n         call nudge_apply_upstream_muskingumCunge( Qup,  Quc,  nudge(k),  k )\n#endif\n\n         call SUBMUSKINGCUNGE(&\n              tmpQLINK(k,2), velocity(k), qloss(k), LINKID(k),     Qup,        Quc, QLINK(k,1), &\n              QLateral(k),   DTRT_CH,     So(k), CHANLEN(k),                  &\n              MannN(k),      ChSSlp(k),   Bw(k), Tw(k), Tw_CC(k), n_CC(k), HLINK(k), ChannK(k) )\n\n      else\n#ifdef HYDRO_D\n         print *, \" no channel option selected\"\n#endif\n         call hydro_stop(\"drive_CHANNEL\")\n      endif\n\n   end do  !--k links\n\n\n#ifdef MPP_LAND\n   call updateLake_seq(QLAKEO,nlakes,tmpQLAKEO)\n   call updateLake_seq(QLAKEI,nlakes,tmpQLAKEI)\n   call updateLake_seq(RESHT,nlakes,tmpRESHT)\n   call updateLake_seqInt(rt_domain(did)%final_reservoir_type, nlakes, tmpFinalResType)\n   call updateLake_seq(rt_domain(did)%reservoir_assimilated_value, nlakes, tmpAssimilatedValue)\n   !call updateLake_seq_char(rt_domain(did)%reservoir_assimilated_source_file, nlakes, tmpAssimilatedSourceFile)\n#endif\n\n   do k = 1, NLINKSL !tmpQLINK?\n      if(TYPEL(k) .ne. 2) then   !only the internal lake nodes don't have info.. but need to save QLINK of lake out too\n         QLINK(k,2) = tmpQLINK(k,2)\n      endif\n      QLINK(k,1) = QLINK(k,2)    !assigng link flow of current to be previous for next time step\n   end do\n\n\n#ifdef WRF_HYDRO_NUDGING\n   if(.not. nudgeWAdvance) call nudge_term_all(qlink, nudge, int(nt*dtrt_ch))\n#endif /* WRF_HYDRO_NUDGING */\n\n\n!#ifdef HYDRO_D\n!   print *, \"END OF ALL REACHES...\",KRT,DT_STEPS\n!#endif\n\nend do  ! nsteps\n\nendif ! channel_bypass\n\nif (KT .eq. 1) KT = KT + 1\n\n#ifdef MPP_LAND\nif(my_id .eq. io_id)      then\n   if(allocated(tmpQLAKEO))  deallocate(tmpQLAKEO)\n   if(allocated(tmpQLAKEI))  deallocate(tmpQLAKEI)\n   if(allocated(tmpRESHT))  deallocate(tmpRESHT)\n   if(allocated(tmpFinalResType)) deallocate(tmpFinalResType)\nendif\n#endif\n\nif (KT .eq. 1) KT = KT + 1  ! redundant?\n\nend subroutine drive_CHANNEL_RSL\n\n! ----------------------------------------------------------------\n\nend module module_channel_routing\n\n!! Is this outside the module scope on purpose?\n#ifdef MPP_LAND\n subroutine checkReach(ii,  inVar)\n   use module_mpp_land\n   use module_RT_data, only: rt_domain\n   use MODULE_mpp_ReachLS, only : updatelinkv,                   &\n                                 ReachLS_write_io, gbcastvalue, &\n                                 gbcastreal2\n   implicit none\n   integer :: ii\n   real,dimension(rt_domain(1)%nlinksl) :: inVar\n   real:: g_var(rt_domain(1)%gnlinksl)\n   call ReachLS_write_io(inVar, g_var)\n   if(my_id .eq. io_id) then\n      write(ii,*) g_var\n      call flush(ii)\n   endif\n end subroutine checkReach\n#endif\n"
  },
  {
    "path": "src/Routing/module_date_utilities_rt.F90",
    "content": "module Module_Date_utilities_rt\n    use module_hydro_stop, only: HYDRO_stop\ncontains\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n    !  From old date (\"YYYY-MM-DD HH:MM:SS.ffff\" or \"YYYYMMDDHHMMSSffff\") and\n    !  delta-time, compute the new date.\n\n    !  on entry     -  odate  -  the old hdate.\n    !                  idt    -  the change in time\n\n    !  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n    !  Local Variables\n\n    !  yrold    -  indicates the year associated with \"odate\"\n    !  moold    -  indicates the month associated with \"odate\"\n    !  dyold    -  indicates the day associated with \"odate\"\n    !  hrold    -  indicates the hour associated with \"odate\"\n    !  miold    -  indicates the minute associated with \"odate\"\n    !  scold    -  indicates the second associated with \"odate\"\n\n    !  yrnew    -  indicates the year associated with \"ndate\"\n    !  monew    -  indicates the month associated with \"ndate\"\n    !  dynew    -  indicates the day associated with \"ndate\"\n    !  hrnew    -  indicates the hour associated with \"ndate\"\n    !  minew    -  indicates the minute associated with \"ndate\"\n    !  scnew    -  indicates the second associated with \"ndate\"\n\n    !  mday     -  a list assigning the number of days in each month\n\n    !  i        -  loop counter\n    !  nday     -  the integer number of days represented by \"idt\"\n    !  nhour    -  the integer number of hours in \"idt\" after taking out\n    !              all the whole days\n    !  nmin     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days and whole hours.\n    !  nsec     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days, whole hours, and whole minutes.\n\n    integer :: newlen, oldlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n    logical :: punct\n    integer :: yrstart, yrend, mostart, moend, dystart, dyend\n    integer :: hrstart, hrend, mistart, miend, scstart, scend, frstart\n    integer :: units\n    integer, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n\n    ! Determine if odate is \"YYYY-MM-DD_HH ... \" or \"YYYYMMDDHH....\"\n    if (odate(5:5) == \"-\") then\n       punct = .TRUE.\n    else\n       punct = .FALSE.\n    endif\n\n    !  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    oldlen = LEN(odate)\n    if (punct) then\n       yrstart = 1\n       yrend = 4\n       mostart = 6\n       moend = 7\n       dystart = 9\n       dyend = 10\n       hrstart = 12\n       hrend = 13\n       mistart = 15\n       miend = 16\n       scstart = 18\n       scend = 19\n       frstart = 21\n       select case (oldlen)\n       case (10)\n          ! Days\n          units = 1\n       case (13)\n          ! Hours\n          units = 2\n       case (16)\n          ! Minutes\n          units = 3\n       case (19)\n          ! Seconds\n          units = 4\n       case (21)\n          ! Tenths\n          units = 5\n       case (22)\n          ! Hundredths\n          units = 6\n       case (23)\n          ! Thousandths\n          units = 7\n       case (24)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n          call hydro_stop(\"In geth_newdate() odd length\")\n       end select\n\n       if (oldlen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n\n    else\n\n       yrstart = 1\n       yrend = 4\n       mostart = 5\n       moend = 6\n       dystart = 7\n       dyend = 8\n       hrstart = 9\n       hrend = 10\n       mistart = 11\n       miend = 12\n       scstart = 13\n       scend = 14\n       frstart = 15\n\n       select case (oldlen)\n       case (8)\n          ! Days\n          units = 1\n       case (10)\n          ! Hours\n          units = 2\n       case (12)\n          ! Minutes\n          units = 3\n       case (14)\n          ! Seconds\n          units = 4\n       case (15)\n          ! Tenths\n          units = 5\n       case (16)\n          ! Hundredths\n          units = 6\n       case (17)\n          ! Thousandths\n          units = 7\n       case (18)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n          call hydro_stop(\"In geth_newdate() - odd length\")\n       end select\n    endif\n\n    !  Use internal READ statements to convert the CHARACTER string\n    !  date into INTEGER components.\n\n    read(odate(yrstart:yrend),  '(i4)') yrold\n    read(odate(mostart:moend),  '(i2)') moold\n    read(odate(dystart:dyend), '(i2)') dyold\n    if (units.ge.2) then\n       read(odate(hrstart:hrend),'(i2)') hrold\n       if (units.ge.3) then\n          read(odate(mistart:miend),'(i2)') miold\n          if (units.ge.4) then\n             read(odate(scstart:scend),'(i2)') scold\n             if (units.ge.5) then\n                read(odate(frstart:oldlen),*) frold\n             end if\n          end if\n       end if\n    end if\n\n    !  Set the number of days in February for that year.\n\n    mday(2) = nfeb(yrold)\n\n    !  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n    !  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the fractional part  of ODATE makes sense.\n\n\n    if (.not.opass) then\n#ifdef HYDRO_D\n       write(*,*) 'Crazy ODATE: ', odate(1:oldlen), oldlen\n       call hydro_stop(\"In geth_newdate() - Crazy ODATE\")\n#endif\n    end if\n\n    !  Date Checks are completed.  Continue.\n\n\n    !  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (units.ge.5) then !idt should be in fractions of seconds\n       ifrc = oldlen-(frstart)+1\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (units.eq.4) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (units.eq.3) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.2) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.1) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            oldlen\n       write(*,*) '#'//odate(1:oldlen)//'#'\n       call hydro_stop(\"In geth_newdate()\")\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n    !  Now construct the new mdate\n\n    newlen = LEN(ndate)\n\n    if (punct) then\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n    else\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n119       format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,116) yrnew, monew, dynew, hrnew, minew\n116       format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,113) yrnew, monew, dynew, hrnew\n113       format(i4,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,110) yrnew, monew, dynew\n110       format(i4,i2.2,i2.2)\n\n       end if\n\n    endif\n\n    if (punct .and. (oldlen.ge.11) .and. (newlen.ge.11)) ndate(11:11) = sp\n\n  end subroutine geth_newdate\n\n  subroutine geth_idts (newdate, olddate, idt)\n    implicit none\n\n    !  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n    !  compute the time difference.\n\n    !  on entry     -  newdate  -  the new hdate.\n    !                  olddate  -  the old hdate.\n\n    !  on exit      -  idt    -  the change in time.\n    !                            Units depend on length of date strings.\n\n    character (len=*) , intent(in) :: newdate, olddate\n    integer           , intent(out)   :: idt\n\n\n    !  Local Variables\n\n    !  yrnew    -  indicates the year associated with \"ndate\"\n    !  yrold    -  indicates the year associated with \"odate\"\n    !  monew    -  indicates the month associated with \"ndate\"\n    !  moold    -  indicates the month associated with \"odate\"\n    !  dynew    -  indicates the day associated with \"ndate\"\n    !  dyold    -  indicates the day associated with \"odate\"\n    !  hrnew    -  indicates the hour associated with \"ndate\"\n    !  hrold    -  indicates the hour associated with \"odate\"\n    !  minew    -  indicates the minute associated with \"ndate\"\n    !  miold    -  indicates the minute associated with \"odate\"\n    !  scnew    -  indicates the second associated with \"ndate\"\n    !  scold    -  indicates the second associated with \"odate\"\n    !  i        -  loop counter\n    !  mday     -  a list assigning the number of days in each month\n\n    ! ndate, odate: local values of newdate and olddate\n    character(len=24) :: ndate, odate\n\n    integer :: oldlen, newlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: i, newdys, olddys\n    logical :: npass, opass\n    integer :: timesign\n    integer :: ifrc\n    integer, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n    logical :: punct\n    integer :: yrstart, yrend, mostart, moend, dystart, dyend\n    integer :: hrstart, hrend, mistart, miend, scstart, scend, frstart\n    integer :: units\n\n    oldlen = len(olddate)\n    newlen = len(newdate)\n    if (newlen.ne.oldlen) then\n       write(*,'(\"GETH_IDTS: NEWLEN /= OLDLEN: \", A, 3x, A)') newdate(1:newlen), olddate(1:oldlen)\n       call hydro_stop(\"In geth_idts() - NEWLEN /= OLDLEN\")\n    endif\n\n    if (olddate.gt.newdate) then\n       timesign = -1\n\n       ifrc = oldlen\n       oldlen = newlen\n       newlen = ifrc\n\n       ndate = olddate\n       odate = newdate\n    else\n       timesign = 1\n       ndate = newdate\n       odate = olddate\n    end if\n\n    ! Break down old hdate into parts\n\n    ! Determine if olddate is punctuated or not\n    if (odate(5:5) == \"-\") then\n       punct = .TRUE.\n       if (ndate(5:5) /= \"-\") then\n          write(*,'(\"GETH_IDTS: Dates appear to be different formats: \", A, 3x, A)') &\n               ndate(1:newlen), odate(1:oldlen)\n          call hydro_stop(\"In geth_idts() - Dates appear to be different formats\")\n       endif\n    else\n       punct = .FALSE.\n       if (ndate(5:5) == \"-\") then\n          write(*,'(\"GETH_IDTS: Dates appear to be different formats: \", A, 3x, A)') &\n               ndate(1:newlen), odate(1:oldlen)\n          call hydro_stop(\"In geth_idts() - Dates appear to be different formats\")\n       endif\n    endif\n\n    if (punct) then\n       yrstart = 1\n       yrend = 4\n       mostart = 6\n       moend = 7\n       dystart = 9\n       dyend = 10\n       hrstart = 12\n       hrend = 13\n       mistart = 15\n       miend = 16\n       scstart = 18\n       scend = 19\n       frstart = 21\n       select case (oldlen)\n       case (10)\n          ! Days\n          units = 1\n       case (13)\n          ! Hours\n          units = 2\n       case (16)\n          ! Minutes\n          units = 3\n       case (19)\n          ! Seconds\n          units = 4\n       case (21)\n          ! Tenths\n          units = 5\n       case (22)\n          ! Hundredths\n          units = 6\n       case (23)\n          ! Thousandths\n          units = 7\n       case (24)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_idts:  odd length: #'//trim(odate)//'#'\n          call hydro_stop(\"In geth_idts() - odd length\")\n       end select\n    else\n\n       yrstart = 1\n       yrend = 4\n       mostart = 5\n       moend = 6\n       dystart = 7\n       dyend = 8\n       hrstart = 9\n       hrend = 10\n       mistart = 11\n       miend = 12\n       scstart = 13\n       scend = 14\n       frstart = 15\n\n       select case (oldlen)\n       case (8)\n          ! Days\n          units = 1\n       case (10)\n          ! Hours\n          units = 2\n       case (12)\n          ! Minutes\n          units = 3\n       case (14)\n          ! Seconds\n          units = 4\n       case (15)\n          ! Tenths\n          units = 5\n       case (16)\n          ! Hundredths\n          units = 6\n       case (17)\n          ! Thousandths\n          units = 7\n       case (18)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_idts:  odd length: #'//trim(odate)//'#'\n          call hydro_stop(\"In geth_idts() - odd length\")\n       end select\n    endif\n\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n\n    read(odate(yrstart:yrend), '(i4)') yrold\n    read(odate(mostart:moend), '(i2)') moold\n    read(odate(dystart:dyend), '(i2)') dyold\n    if (units.ge.2) then\n       read(odate(hrstart:hrend),'(i2)') hrold\n       if (units.ge.3) then\n          read(odate(mistart:miend),'(i2)') miold\n          if (units.ge.4) then\n             read(odate(scstart:scend),'(i2)') scold\n             if (units.ge.5) then\n                read(odate(frstart:oldlen),*) frold\n             end if\n          end if\n       end if\n    end if\n\n    !  Break down new hdate into parts\n\n    hrnew = 0\n    minew = 0\n    scnew = 0\n    frnew = 0\n\n    read(ndate(yrstart:yrend), '(i4)') yrnew\n    read(ndate(mostart:moend), '(i2)') monew\n    read(ndate(dystart:dyend), '(i2)') dynew\n    if (units.ge.2) then\n       read(ndate(hrstart:hrend),'(i2)') hrnew\n       if (units.ge.3) then\n          read(ndate(mistart:miend),'(i2)') minew\n          if (units.ge.4) then\n             read(ndate(scstart:scend),'(i2)') scnew\n             if (units.ge.5) then\n                read(ndate(frstart:newlen),*) frnew\n             end if\n          end if\n       end if\n    end if\n\n    !  Check that the dates make sense.\n\n    npass = .true.\n    opass = .true.\n\n    !  Check that the month of NDATE makes sense.\n\n    if ((monew.gt.12).or.(monew.lt.1)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_IDTS:  Month of NDATE = ', monew\n#endif\n       npass = .false.\n    end if\n\n    !  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n#ifdef HYDRO_D\n       print*, 'GETH_IDTS:  Month of ODATE = ', moold\n#endif\n       opass = .false.\n    end if\n\n    !  Check that the day of NDATE makes sense.\n\n    if (monew.ne.2) then\n       ! ...... For all months but February\n       if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n#ifdef HYDRO_D\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n#endif\n          npass = .false.\n       end if\n    else if (monew.eq.2) then\n       ! ...... For February\n       if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n#ifdef HYDRO_D\n          print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n#endif\n          npass = .false.\n       end if\n    endif\n\n    !  Check that the day of ODATE makes sense.\n\n    if (moold.ne.2) then\n       ! ...... For all months but February\n       if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n#ifdef HYDRO_D\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n#endif\n          opass = .false.\n       end if\n    else if (moold.eq.2) then\n       ! ....... For February\n       if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n#ifdef HYDRO_D\n          print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n#endif\n          opass = .false.\n       end if\n    end if\n\n    !  Check that the hour of NDATE makes sense.\n\n    if ((hrnew.gt.23).or.(hrnew.lt.0)) then\n#ifdef HYDRO_D\n       print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n#endif\n       npass = .false.\n    end if\n\n    !  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n#ifdef HYDRO_D\n       print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n#endif\n       opass = .false.\n    end if\n\n    !  Check that the minute of NDATE makes sense.\n\n    if ((minew.gt.59).or.(minew.lt.0)) then\n#ifdef HYDRO_D\n       print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n#endif\n       npass = .false.\n    end if\n\n    !  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n#ifdef HYDRO_D\n       print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n#endif\n       opass = .false.\n    end if\n\n    !  Check that the second of NDATE makes sense.\n\n    if ((scnew.gt.59).or.(scnew.lt.0)) then\n#ifdef HYDRO_D\n       print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n#endif\n       npass = .false.\n    end if\n\n    !  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n#ifdef HYDRO_D\n       print*, 'GETH_IDTS:  Second of ODATE = ', scold\n#endif\n       opass = .false.\n    end if\n\n    if (.not. npass) then\n       print*, 'Screwy NDATE: ', ndate(1:newlen)\n       call hydro_stop(\"In geth_idts() - Screwy NDATE \")\n    end if\n\n    if (.not. opass) then\n       print*, 'Screwy ODATE: ', odate(1:oldlen)\n       call hydro_stop(\"In geth_idts() - Screwy ODATE \")\n    end if\n\n    !  Date Checks are completed.  Continue.\n\n    !  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n    !  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n    !  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\n    newdys = 0\n    do i = yrold, yrnew - 1\n       newdys = newdys + 337 + nfeb(i)\n    end do\n\n    if (monew .gt. 1) then\n       mday(2) = nfeb(yrnew)\n       do i = 1, monew - 1\n          newdys = newdys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    newdys = newdys + dynew - 1\n\n    !  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n    !  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\n    olddys = 0\n\n    if (moold .gt. 1) then\n       mday(2) = nfeb(yrold)\n       do i = 1, moold - 1\n          olddys = olddys + mday(i)\n       end do\n       mday(2) = 28\n    end if\n\n    olddys = olddys + dyold -1\n\n    !  Determine the time difference\n\n    idt = (newdys - olddys)\n    if (units.ge.2) then\n       idt = idt*24 + (hrnew - hrold)\n       if (units.ge.3) then\n          idt = idt*60 + (minew - miold)\n          if (units.ge.4) then\n             idt = idt*60 + (scnew - scold)\n             if (units.ge.5) then\n                ifrc = oldlen-(frstart-1)\n                ifrc = 10**ifrc\n                idt = idt * ifrc + (frnew-frold)\n             endif\n          endif\n       endif\n    endif\n\n    if (timesign .eq. -1) then\n       idt = idt * timesign\n    end if\n\n  end subroutine geth_idts\n\n\n  integer function nfeb(year)\n    !\n    ! Compute the number of days in February for the given year.\n    !\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb\n\n  integer function nmdays(hdate)\n    !\n    ! Compute the number of days in the month of given date hdate.\n    !\n    implicit none\n    character(len=*), intent(in) :: hdate\n\n    integer :: year, month\n    integer, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\n    read(hdate(1:7), '(I4,1x,I2)') year, month\n\n    if (month == 2) then\n       nmdays = nfeb(year)\n    else\n       nmdays = ndays(month)\n    endif\n  end function nmdays\n\n  function monthabbr_to_mm(mon) result(mm)\n    implicit none\n\n    character(len=3), intent(in) :: mon\n\n    integer :: mm\n\n    if (mon == \"Jan\") then\n       mm = 1\n    elseif (mon == \"Feb\") then\n       mm = 2\n    elseif (mon == \"Mar\") then\n       mm = 3\n    elseif (mon == \"Apr\") then\n       mm = 4\n    elseif (mon == \"May\") then\n       mm = 5\n    elseif (mon == \"Jun\") then\n       mm = 6\n    elseif (mon == \"Jul\") then\n       mm = 7\n    elseif (mon == \"Aug\") then\n       mm = 8\n    elseif (mon == \"Sep\") then\n       mm = 9\n    elseif (mon == \"Oct\") then\n       mm = 10\n    elseif (mon == \"Nov\") then\n       mm = 11\n    elseif (mon == \"Dec\") then\n       mm = 12\n    else\n       write(*, '(\"Function monthabbr_to_mm:  mon = <\",A,\">\")') mon\n       print*,  \"Function monthabbr_to_mm:  Unrecognized mon\"\n       call hydro_stop(\"In monthabbr_to_mm() - Unrecognized mon\")\n    endif\n  end function monthabbr_to_mm\n\n  subroutine swap_date_format(indate, outdate)\n    implicit none\n    character(len=*), intent(in)  :: indate\n    character(len=*), intent(out) :: outdate\n    integer :: inlen\n\n    inlen = len(indate)\n    if (indate(5:5) == \"-\") then\n       select case (inlen)\n       case (10)\n          ! YYYY-MM-DD\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)\n       case (13)\n          ! YYYY-MM-DD_HH\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)\n       case (16)\n          ! YYYY-MM-DD_HH:mm\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)\n       case (19)\n          ! YYYY-MM-DD_HH:mm:ss\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)//&\n               indate(18:19)\n       case (21,22,23,24)\n          ! YYYY-MM-DD_HH:mm:ss.f[f[f[f]]]\n          outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)//&\n               indate(18:19)//indate(21:inlen)\n       case default\n          write(*,'(\"Unrecognized length: <\", A,\">\")') indate\n         call hydro_stop(\"In swap_date_format() - Unrecognized length\")\n       end select\n    else\n       select case (inlen)\n       case (8)\n          ! YYYYMMDD\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)\n       case (10)\n          ! YYYYMMDDHH\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)\n       case (12)\n          ! YYYYMMDDHHmm\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)\n       case (14)\n          ! YYYYMMDDHHmmss\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)//\":\"//indate(13:14)\n       case (15,16,17,18)\n          ! YYYYMMDDHHmmssf[f[f[f]]]\n          outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n               indate(9:10)//\":\"//indate(11:12)//\":\"//indate(13:14)//\".\"//indate(15:inlen)\n       case default\n          write(*,'(\"Unrecognized length: <\", A,\">\")') indate\n          call hydro_stop(\"In swap_date_format() - Unrecognized length\")\n       end select\n    endif\n\n  end subroutine swap_date_format\n\n  character(len=3) function mm_to_monthabbr(ii) result(mon)\n    implicit none\n    integer, intent(in) :: ii\n    character(len=3), parameter, dimension(12) :: month = (/ &\n         \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", &\n         \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" /)\n    if (ii > 0 .and. ii < 13 ) then\n       mon = month(ii)\n    else\n!       print*, \"mm_to_monthabbr\"\n       call hydro_stop(\"In mm_to_monthabbr() - mm_to_monthabbr\")\n    endif\n  end function mm_to_monthabbr\n\nend module Module_Date_utilities_rt\n"
  },
  {
    "path": "src/Routing/module_gw_gw2d.F90",
    "content": "!------------------------------------------------------------------------------\n! Benjamin Fersch  2d groundwater model\n!------------------------------------------------------------------------------\n\n\nmodule module_gw_gw2d\n\n\n#ifdef MPP_LAND\n   use module_mpp_land\n#endif\n   use module_gw_gw2d_data, only: gw2d, gw_field\n   use module_rt_data, only: rt_domain\n   use config_base, only: nlst\n\n   implicit none\n\n\n#ifdef MPP_LAND\n integer, private :: ierr\n integer, parameter :: rowshift = 0\n integer, parameter :: colshift = 1\n#endif\n\n\n contains\n\n\n   subroutine gw2d_ini(did,dt,dx)\n\n     use module_HYDRO_io, only: output_gw_spinup\n\n     implicit none\n     integer did\n     real dt,dx\n     integer :: jj, ii, iter, itermax\n\n\n\n\n      itermax = nlst(did)%GwPreCycles\n\t   gw2d(did)%dx=dx\n           gw2d(did)%dt=dt\n\n           gw2d(did)%qgw_chanrt = 0.\n           gw2d(did)%qsgwrt = 0.\n           gw2d(did)%qdarcyRT = 0.\n           gw2d(did)%excess = 0.\n\n           gw2d(did)%compres=0. ! currently not implemented\n           gw2d(did)%istep=0 ! initialize time step\n           ! reset cells with undefined hydraulic conductivity\n           where(gw2d(did)%hycond .eq. 100) gw2d(did)%hycond = 5E-4\n\n          do iter=1,itermax\n#ifdef HYDRO_D\n#ifdef MPP_LAND\n          if(my_id .eq. IO_id) &\n#endif\n          write(6,*) \"       GW Pre-cycle\", iter, \"of\", itermax\n#endif\n           call gwstep(gw2d(did)%ix, gw2d(did)%jx, gw2d(did)%dx, &\n             gw2d(did)%ltype, gw2d(did)%elev, gw2d(did)%bot, &\n             gw2d(did)%hycond, gw2d(did)%poros, gw2d(did)%compres, &\n             gw2d(did)%ho, gw2d(did)%h, gw2d(did)%convgw, gw2d(did)%excess, &\n             gw2d(did)%ebot, gw2d(did)%eocn, gw2d(did)%dt, &\n             iter)\n\n\t     gw2d(did)%ho = gw2d(did)%h\n\n\t  if((nlst(did)%GwPreDiag .and. iter==1) .or. &\n\t      nlst(did)%GwPreDiag .and. (mod(iter, nlst(did)%GwPreDiagInterval) .eq. 0) ) then\n           call output_gw_spinup(nlst(did)%igrid, 1000000,                &\n                            RT_DOMAIN(did)%ixrt, RT_DOMAIN(did)%jxrt,   &\n                            nlst(did)%startdate, nlst(did)%olddate, &\n                            gw2d(did)%ho, gw2d(did)%convgw, gw2d(did)%excess,  &\n                            nlst(did)%geo_finegrid_flnm,nlst(did)%DT,     &\n                            RT_DOMAIN(did)%LATVAL,        &\n                            RT_DOMAIN(did)%LONVAL,rt_domain(did)%overland%properties%distance_to_neighbor,          &\n                            nlst(did)%output_gw)\n\t   end if\n\n\n          end do\n\n   end subroutine gw2d_ini\n\n   subroutine gw2d_allocate(did, ix, jx, nsoil)\n\n      implicit none\n      integer ix, jx, nsoil\n      integer istatus, did\n\n      if(gw2d(did)%allo_status .eq. 1) return\n      gw2d(did)%allo_status = 1\n\n      gw2d(did)%ix = ix\n      gw2d(did)%jx = jx\n\n#ifdef MPP_LAND\n      if(down_id == -1)  then !  if south border\n       gw2d(did)%jts = 1\n      else\n       gw2d(did)%jts = 2\n      endif\n\n      if(up_id == -1)    then !if north border\n        gw2d(did)%jte = jx\n      else\n        gw2d(did)%jte = jx-1\n      endif\n\n      if(left_id == -1)  then !if west border\n        gw2d(did)%its = 1\n      else\n        gw2d(did)%its = 2\n      endif\n\n      if(right_id == -1) then ! if east border\n        gw2d(did)%ite = ix\n      else\n        gw2d(did)%ite = ix-1\n      endif\n\n#else\n      gw2d(did)%its = 1\n      gw2d(did)%ite = ix\n      gw2d(did)%jts = 1\n      gw2d(did)%jte = jx\n#endif\n\n      allocate(gw2d(did)%ltype  (ix,jx))\n      allocate(gw2d(did)%elev   (ix,jx))\n      allocate(gw2d(did)%bot    (ix,jx))\n      allocate(gw2d(did)%hycond (ix,jx))\n      allocate(gw2d(did)%poros  (ix,jx))\n      allocate(gw2d(did)%compres(ix,jx))\n      allocate(gw2d(did)%ho     (ix,jx))\n      allocate(gw2d(did)%h      (ix,jx))\n      allocate(gw2d(did)%convgw (ix,jx))\n      allocate(gw2d(did)%excess (ix,jx))\n\n      allocate(gw2d(did)%qgw_chanrt (ix,jx))\n\n\n      ! TODO allocate only if gwSoilCoupling is active\n      allocate(gw2d(did)%qsgwrt   (ix,jx))\n      allocate(gw2d(did)%qsgw     (rt_domain(did)%ix,rt_domain(did)%jx))\n      allocate(gw2d(did)%qdarcyRT (ix,jx))\n\n    end subroutine gw2d_allocate\n\n\n    subroutine gwstep(ix, jx, dx,              &\n\t\t      ltype, elev, bot,        &\n\t\t      hycond, poros, compres,  &\n                      ho, h, convgw, excess,   &\n                      ebot, eocn,              &\n\t\t      dt, istep)\n\n! New (volug): calling routines use change in head, convgw = d(h-ho)/dt.\n\n! Steps ground-water hydrology (head) through one timestep.\n! Modified from Prickett and Lonnquist (1971), basic one-layer aquifer\n! simulation program, with mods by Zhongbo Yu(1997).\n! Solves S.dh/dt = d/dx(T.dh/dx) + d/dy(T.dh/dy) + \"external sources\"\n! for a single layer, where h is head, S is storage coeff and T is\n! transmissivity. 3-D arrays in main program (hycond,poros,h,bot)\n! are 2-D here, since only a single (uppermost) layer is solved.\n! Uses an iterative time-implicit ADI method.\n\n! use module_hms_constants\n\n\n\n      integer, intent(in) :: ix, jx\n\n      integer, intent(in), dimension(ix,jx) ::  ltype     ! land-sfc type  (supp)\n      real,    intent(in), dimension(ix,jx) ::  &\n        elev,           &  ! elev/bathymetry of sfc rel to sl (m) (supp)\n        bot,            &  ! elev. aquifer bottom rel to sl (m)   (supp)\n        hycond,         &  ! hydraulic conductivity (m/s per m/m) (supp)\n        poros,          &  ! porosity (m3/m3)                     (supp)\n        compres,        &  ! compressibility (1/Pa)               (supp)\n        ho                 ! head at start of timestep (m)        (supp)\n\n      real,    intent(inout), dimension(ix,jx) ::  &\n        h,              &  ! head, after ghmcompute (m)           (ret)\n        convgw,         &  ! convergence due to gw flow (m/s)     (ret)\n        excess\n\n      real, intent(inout) :: ebot, eocn\n\n\n\n      integer ::  istep !, dt\n      real, intent(in) :: dt, dx\n\n! #endif\n!       eocn  = mean spurious sink for h_ocn = sealev fix (m/s)(ret)\n!               This equals the total ground-water flow across\n!               land->ocean boundaries.\n!       ebot  = mean spurious source for \"bot\" fix (m/s) (returned)\n!       time  = elapsed time from start of run (sec)\n!       dt = timestep length (sec)\n!       istep = timestep counter\n\n! Local arrays:\n\n      real, dimension(ix,jx)   :: sf2    ! storage coefficient (m3 of h2o / bulk m3)\n      real, dimension(ix,jx,2) ::   t    ! transmissivity (m2/s)..1 for N-S,..2 for E-W\n\n#ifdef MPP_LAND\n      real, dimension(:,:), allocatable :: aa, &         ! tridiagonal matrix lower diagonal\n                                           bb, &         ! tridiagonal matrix main diagonal\n                                           cc, &         ! tridiagonal matrix upper diagonal\n                                           dd, &         ! right hand side\n                                           b2, &\n                                           c2, &\n                                           rhs, &\n                                           wk, &\n                                           hh\n      real, dimension(:), allocatable ::   xfac, &\n                                           zfac\n#else\n      real, dimension(:), allocatable :: aa, &         ! tridiagonal matrix lower diagonal\n                                         bb, &         ! tridiagonal matrix main diagonal\n                                         cc, &         ! tridiagonal matrix upper diagonal\n                                         dd, &         ! right hand side\n                                         hh            ! solution vector\n#endif\n      real, parameter    :: botinc = 0.01  ! re-wetting increment to fix h < bot\n!     parameter (botinc = 0.  )  ! re-wetting increment to fix h < bot\n                                 ! (m); else no flow into dry cells\n      real, parameter    :: delskip = 0.005 ! av.|dhead| value for iter.skip out(m)\n      integer, parameter :: itermax = 1    ! maximum number of iterations\n      integer, parameter :: itermin = 1    ! minimum number of iterations\n      real, parameter    :: sealev = 1000.     ! sea-level elevation (m)\n\n      integer            :: its, ite, jts, jte, ifs, ife, jfs, jfe, &\n                            xdim, ydim, fxdim, fydim\n\n! die müssen noch sortiert, geprüft und aufgeräumt werden\n      integer ::                &\n        iter,                   &\n        j,                      &\n        i,                      &\n        jp,                     &\n        ip,                     &\n        n,                      &\n        ierr,                   &\n        ier,                    &\n        ioffs,                  &\n        joffs\n\n!       real :: su, sc, shp, bb, aa, cc, w, zz, tareal, dtoa, dtot\n      real ::                   &\n        dy,                     &\n        e,                      &\n        su,                     &\n        sc,                     &\n        shp,                    &\n        w,                      &\n        ha,                     &\n        delcur,                 &\n        dtot,                   &\n        dtoa,                   &\n        darea,                  &\n        tareal,                 &\n        zz\n\n#ifdef MPP_LAND\n      real ::        mpiDelcur, &\n                     gdtot,     &\n                     gdtoa,     &\n                     geocn,     &\n                     gebot\n      integer mpiSize\n#endif\n\n\n\ndy = dx\ndarea = dx*dy\n\n! define indexes for parallel execution\n\n#ifdef MPP_LAND\nif(down_id == -1)  then !  if south border\n  jts = 1\nelse\n  jts = 2\nendif\n\nif(up_id == -1)    then !if north border\n  jte = jx\nelse\n  jte = jx-1\nendif\n\nif(left_id == -1)  then !if west border\n  its = 1\nelse\n  its = 2\nendif\n\nif(right_id == -1) then ! if east border\n  ite = ix\nelse\n  ite = ix-1\nendif\n\n#else\nits = 1\nite = ix\njts = 1\njte = jx\n#endif\n\nifs = 1\nife = ix\njfs = 1\njfe = jx\n\n\nfxdim = ife-ifs+1\nfydim = jfe-jfs+1\n xdim = ite-its+1\n ydim = jte-jts+1\n\n\n      call scopy (fxdim*fydim, ho(ifs:ife,jfs:jfe), 1,    &\n                  h(ifs:ife,jfs:jfe), 1)\n\n\n!       Top of iterative loop for (not anymore ADI) solution\n\n      iter = 0\n!~~~~~~~~~~~~~\n   80 continue\n!~~~~~~~~~~~~~\n      iter = iter+1\n\n\n#ifdef MPP_LAND\n\n       call MPP_LAND_COM_REAL(h, fxdim, fydim, 99)\n\n#endif\n      e    = 0.       ! absolute changes in head (for iteration control)\n!      eocn = 0.       ! accumulated fixes for h = 0 over ocean (diag)\n!      ebot = 0.       ! accumulated fixes for h < bot (diagnostic)\n\n!       Set storage coefficient (sf2)\n\n\n\n    tareal = 0.\n      do j=jts,jte\n        do i=its,ite\n\n\n        if(ltype(i,j) .ge. 1) tareal = tareal + darea\n\n!         unconfined water table (h < e): V = poros*(h-b)\n!                                         dV/dh = poros\n!         saturated to surface (h >= e) : V = poros*(e-b) + (h-e)\n!                                         dV/dh = 1\n!         (compressibility is ignored)\n!\n!         su = poros(i,j)*(1.-theta(i,j))    ! old (pre-volug)\n          su = poros(i,j)                    ! new (volug)\n          sc = 1.\n\n!           if      (ho(i,j).le.elev(i,j) .and. h(i,j).le.elev(i,j)) then\n            sf2(i,j) = su\n!           else if (ho(i,j).ge.elev(i,j) .and. h(i,j).ge.elev(i,j)) then\n!             sf2(i,j) = sc\n!           else if (ho(i,j).le.elev(i,j) .and. h(i,j).ge.elev(i,j)) then\n!             shp = sf2(i,j) * (h(i,j) - ho(i,j))\n!             sf2(i,j) = shp * sc / (shp - (su-sc)*(elev(i,j)-ho(i,j)))\n!           else if (ho(i,j).ge.elev(i,j) .and. h(i,j).le.elev(i,j)) then\n!             shp = sf2(i,j) * (ho(i,j) - h(i,j))\n!             sf2(i,j) = shp * su / (shp + (su-sc)*(ho(i,j)-elev(i,j)))\n!           endif\n\n        enddo\n      enddo\n\n#ifdef MPP_LAND\n       ! communicate storage coefficient\n       call MPP_LAND_COM_REAL(sf2, fxdim, fydim, 99)\n\n#endif\n\n!==========================\n!       Column calculations\n!==========================\n\n!       Set transmissivities. Use min(h,elev)-bot instead of h-bot,\n!       since if h > elev, thickness of groundwater flow is just\n!       elev-bot. (uses geometric mean)\n\n\n      do j=jts,jte\n        jp = min (j+1,jfe)\n        do i=its,ite\n          ip = min (i+1,ife)\n\n          t(i,j,2) = sqrt( abs(                                           &\n                        hycond(i, j)*(min(h(i ,j),elev(i ,j))-bot(i ,j))  &\n                       *hycond(ip,j)*(min(h(ip,j),elev(ip,j))-bot(ip,j))  &\n                         )    )                                           &\n                   * (0.5*(dy+dy)) & ! in WRF the dx and dy are usually equal\n                   / (0.5*(dx+dx))\n\n          t(i,j,1) = sqrt( abs(                                           &\n                        hycond(i,j )*(min(h(i,j ),elev(i,j ))-bot(i,j ))  &\n                       *hycond(i,jp)*(min(h(i,jp),elev(i,jp))-bot(i,jp))  &\n                         )    )                                           &\n                   * (0.5*(dx+dx))  &\n                   / (0.5*(dy+dy))\n\n\n        enddo\n      enddo\n\n\n\n\n\n#ifdef MPP_LAND\n      ! communicate transmissivities in x and y direction\n       call MPP_LAND_COM_REAL(t(:,:,1), fxdim, fydim, 99)\n       call MPP_LAND_COM_REAL(t(:,:,2), fxdim, fydim, 99)\n\n\n       allocate(aa(jts:jte,its:ite))\n       allocate(bb(jts:jte,its:ite))\n       allocate(cc(jts:jte,its:ite))\n       allocate(dd(jts:jte,its:ite))\n       allocate(c2(1:ydim,1:xdim))\n       allocate(b2(1:ydim,1:xdim))\n       allocate(wk(1:ydim,1:xdim))\n       allocate(hh(0:ydim+1,0:xdim+1))\n       allocate(xfac(1:ydim))\n       allocate(zfac(1:ydim))\n#else\n  allocate(aa(jfs:jfe))\n  allocate(bb(jfs:jfe))\n  allocate(cc(jfs:jfe))\n  allocate(dd(jfs:jfe))\n  allocate(hh(jfs:jfe))\n\n!-------------------\n      do i=ifs,ife\n!-------------------\n\n!>>>>>>>>>>>>>>>>>>>>\n        do j=jfs,jfe\n!>>>>>>>>>>>>>>>>>>>>\n#endif\n#ifndef MPP_LAND\n          bb(j) = (sf2(i,j)/dt) * darea\n          dd(j) = ( ho(i,j)*sf2(i,j)/dt ) * darea\n          aa(j) = 0.0\n          cc(j) = 0.0\n\n          if ((j-jfs) /= 0) then\n           aa(j) = -t(i,j-1,1)\n           bb(j) = bb(j) + t(i,j-1,1)\n\t  endif\n\n          if ((j-jfe) /= 0) then\n           cc(j) = -t(i,j,1)\n           bb(j) = bb(j) + t(i,j,1)\n\t  endif\n\n          if ((i-ifs) /= 0) then\n           bb(j) = bb(j) + t(i-1,j,2)\n           dd(j) = dd(j) + h(i-1,j)*t(i-1,j,2)\n\t  endif\n\n          if ((i-ife) /= 0) then\n           bb(j) = bb(j) + t(i,j,2)\n           dd(j) = dd(j) + h(i+1,j)*t(i,j,2)\n\t  endif\n\n!>>>>>>>>>>>>>>>\n\tend do\n!>>>>>>>>>>>>>>>\n\n  call trdiagSolve(aa, bb, cc, dd, hh, fydim)\n\n  h(i,:) = hh\n  end do\n\ndeallocate(aa)\ndeallocate(bb)\ndeallocate(cc)\ndeallocate(dd)\ndeallocate(hh)\n\n#else\n!-------------------\n      do i=its,ite\n!-------------------\n\n!>>>>>>>>>>>>>>>>>>>>\n        do j=jts,jte\n!>>>>>>>>>>>>>>>>>>>>\n          bb(j,i) = (sf2(i,j)/dt) * darea\n          dd(j,i) = ( ho(i,j)*sf2(i,j)/dt ) * darea\n          aa(j,i) = 0.0\n          cc(j,i) = 0.0\n\n          if (((j-jfs) /= 0)) then\n           aa(j,i) = -t(i,j-1,1)\n           bb(j,i) = bb(j,i) + t(i,j-1,1)\n\t  endif\n\n          if (((j-jfe) /= 0)) then\n           cc(j,i) = -t(i,j,1)\n           bb(j,i) = bb(j,i) + t(i,j,1)\n\t  endif\n\n          if (((i-ifs) /= 0)) then\n           bb(j,i) = bb(j,i) + t(i-1,j,2)\n           dd(j,i) = dd(j,i) + h(i-1,j)*t(i-1,j,2)\n\t  endif\n\n          if (((i-ife) /= 0)) then\n           bb(j,i) = bb(j,i) + t(i,j,2)\n           dd(j,i) = dd(j,i) + h(i+1,j)*t(i,j,2)\n\t  endif\n\n!>>>>>>>>>>>>>>>\n\tend do\n!>>>>>>>>>>>>>>>\n\n!-------------\n  end do\n!-------------\n\n    if(np_up_down .gt. 1) then\n        call sub_n_form(xdim, ydim, aa, &\n                        bb, cc, &\n                        dd, &\n                        c2, b2, hh, wk, xfac, zfac, &\n                        p_up_down+1, np_up_down, 2)\n\n\n\tcall parysolv1(c2, b2, hh, 1., my_id+1, p_up_down+1, &\n\t                xdim, ydim, np_left_right, np_up_down)\n\n    else\n        call sub_tri_solv(xdim,ydim,aa(jts:jte,its:ite), &\n                          bb(jts:jte,its:ite), cc(jts:jte,its:ite), &\n                          dd(jts:jte,its:ite), &\n                          hh, wk,xfac,zfac,2)\n    endif\n\nioffs = its-1\njoffs = jts-1\n!-------------------\n      do i=its,ite\n!-------------------\n\n!>>>>>>>>>>>>>>>>>>>>\n        do j=jts,jte\n!>>>>>>>>>>>>>>>>>>>>\n\n              h(i,j) = hh(j-joffs,i-ioffs)\n\n\t end do\n     end do\n\n#endif\n\n#ifdef MPP_LAND\n\n       call MPP_LAND_COM_REAL(h, fxdim, fydim, 99)\n\n#endif\n\n\n!=======================\n!       Row calculations\n!=======================\n\n!       set transmissivities (same as above)\n\n\n      do j=jts,jte\n        jp = min (j+1,jfe)\n        do i=its,ite\n          ip = min (i+1,ife)\n          t(i,j,2) = sqrt( abs(                                            &\n                        hycond(i, j)*(min(h(i ,j),elev(i ,j))-bot(i ,j))   &\n                       *hycond(ip,j)*(min(h(ip,j),elev(ip,j))-bot(ip,j))   &\n                         )    )                                            &\n                   * (0.5*(dy+dy))                                         &\n                   / (0.5*(dx+dx))\n\n          t(i,j,1) = sqrt( abs(                                            &\n                        hycond(i,j )*(min(h(i,j ),elev(i,j ))-bot(i,j ))   &\n                       *hycond(i,jp)*(min(h(i,jp),elev(i,jp))-bot(i,jp))   &\n                         )    )                                            &\n                   * (0.5*(dx+dx))                                         &\n                   / (0.5*(dy+dy))\n\n\n        enddo\n      enddo\n\n#ifdef MPP_LAND\n      ! communicate transmissivities in x and y direction\n       call MPP_LAND_COM_REAL(t(:,:,1), fxdim, fydim, 99)\n       call MPP_LAND_COM_REAL(t(:,:,2), fxdim, fydim, 99)\n#endif\n\n#ifndef MPP_LAND\nallocate(aa(ifs:ife))\nallocate(bb(ifs:ife))\nallocate(cc(ifs:ife))\nallocate(dd(ifs:ife))\nallocate(hh(ifs:ife))\n\n\n!-------------------\n      do j=jfs,jfe\n!-------------------\n\n\n!>>>>>>>>>>>>>>>>>>>>\n        do i=ifs,ife\n!>>>>>>>>>>>>>>>>>>>>\n          bb(i) = (sf2(i,j)/dt) * darea\n          dd(i) = ( ho(i,j)*sf2(i,j)/dt ) * darea\n          aa(i) = 0.0\n          cc(i) = 0.0\n\n          if ((j-jfs) /= 0) then\n           bb(i) = bb(i) + t(i,j-1,1)\n           dd(i) = dd(i) + h(i,j-1)*t(i,j-1,1)\n\t  endif\n\n          if ((j-jfe) /= 0) then\n           dd(i) = dd(i) + h(i,j+1)*t(i,j,1)\n           bb(i) = bb(i) + t(i,j,1)\n\t  endif\n\n          if ((i-ifs) /= 0) then\n           bb(i) = bb(i) + t(i-1,j,2)\n           aa(i) = -t(i-1,j,2)\n\t  endif\n\n          if ((i-ife) /= 0) then\n           bb(i) = bb(i) + t(i,j,2)\n           cc(i) = -t(i,j,2)\n\t  endif\n\n!>>>>>>>>>>>>>>>\n\tend do\n!>>>>>>>>>>>>>>>\n\n  call trdiagSolve(aa, bb, cc, dd, hh, fxdim)\n\n  h(:,j) = hh\n  end do\n\n#else\n!-------------------\n      do i=its,ite\n!-------------------\n\n!>>>>>>>>>>>>>>>>>>>>\n        do j=jts,jte\n!>>>>>>>>>>>>>>>>>>>>\n          bb(j,i) = (sf2(i,j)/dt) * darea\n          dd(j,i) = ( ho(i,j)*sf2(i,j)/dt ) * darea\n          aa(j,i) = 0.0\n          cc(j,i) = 0.0\n\n          if (((j-jfs) /= 0)) then\n           bb(j,i) = bb(j,i) + t(i,j-1,1)\n           dd(j,i) = dd(j,i) + h(i,j-1)*t(i,j-1,1)\n\t  endif\n\n          if (((j-jfe) /= 0)) then\n           dd(j,i) = dd(j,i) + h(i,j+1)*t(i,j,1)\n           bb(j,i) = bb(j,i) + t(i,j,1)\n\t  endif\n\n          if (((i-ifs) /= 0)) then\n           bb(j,i) = bb(j,i) + t(i-1,j,2)\n           aa(j,i) = -t(i-1,j,2)\n\t  endif\n\n          if (((i-ife) /= 0)) then\n           bb(j,i) = bb(j,i) + t(i,j,2)\n           cc(j,i) = -t(i,j,2)\n\t  endif\n\n!>>>>>>>>>>>>>>>\n\tend do\n!>>>>>>>>>>>>>>>\n\n!-------------\nend do\n!-------------\n\n    if(np_left_right .gt. 1) then\n\n! 3 c(,)  -- subdiagonal elements of tridiagonal systems\n! 4 a(,)  -- diagonal elements of tridiagonal systems\n! 5 b(,)  -- superdiagonal elements of tridiagonal systems\n! 6 r(,)  -- right-hand side elements of tridiagonal systems\n! 7 c2(,) -- front-leg elements of N-systems\n! 8 b2(,) -- back-leg elements of N-systems\n! 9 r2(,) -- right-hand side elements of N-systems (0:ydim+1,0:xdim+1)\n! 10 wk(,) -- work array with same dimensions as a, b, c, etc.\n\n        call sub_n_form(xdim, ydim, aa, &\n                        bb, cc, &\n                        dd, &\n                        c2, b2, hh, wk, xfac, zfac, &\n                        p_left_right+1, np_left_right, 1)\n\n        call parxsolv1(c2, b2, hh, 1., my_id+1, p_left_right+1, &\n\t                xdim, ydim, np_left_right, np_up_down)\n\n    else\n        call sub_tri_solv(xdim,ydim,aa, &\n                          bb, cc, &\n                          dd, &\n                          hh, wk,xfac,zfac,1)\n    endif\nioffs = its-1\njoffs = jts-1\n!-------------------\n      do i=its,ite\n!-------------------\n\n!>>>>>>>>>>>>>>>>>>>>\n        do j=jts,jte\n!>>>>>>>>>>>>>>>>>>>>\n\n               h(i,j) = hh(j-joffs,i-ioffs)\n\n      end do\n     end do\n\ndeallocate(b2)\ndeallocate(c2)\ndeallocate(wk)\ndeallocate(xfac)\ndeallocate(zfac)\n#endif\ndeallocate(aa)\ndeallocate(bb)\ndeallocate(cc)\ndeallocate(dd)\ndeallocate(hh)\n\n! fix head < bottom of aquifer\n\n      do j=jts,jte\n        do i=its,ite\n          if (ltype(i,j).eq.1 .and. h(i,j).le.bot(i,j)+botinc) then\n\n            e = e +  bot(i,j) + botinc - h(i,j)\n!             ebot = ebot + (bot(i,j)+botinc-h(i,j))*sf2(i,j)*darea(i,j)\n            ebot = ebot + (bot(i,j)+botinc-h(i,j))*sf2(i,j)*darea\n\n            h(i,j) = bot(i,j) + botinc\n          endif\n        enddo\n      enddo\n!        maintain head = sea level for ocean (only for adjacent ocean,\n!        rest has hycond=0)\n\n      do j=jts,jte\n        do i=its,ite\n          if (ltype(i,j).eq.2) then\n\n\t    eocn = eocn + (h(i,j)-sealev)*sf2(i,j)*darea\n!             eocn = eocn + (h(i,j)-sealev)*sf2(i,j)*darea(i,j)\n\n!             h(i,j) = sealev (no update of outer boundary cells)\n          endif\n        enddo\n      enddo\n\n!        Loop back for next ADI iteration\n\n!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n      delcur = e/(xdim*ydim)\n\n!       print*, 'delcur before mpi:', delcur\n\n#ifdef MPP_LAND\n\ncall MPI_Reduce(delcur, mpiDelcur, 1, MPI_REAL, MPI_SUM, 0, HYDRO_COMM_WORLD, ierr)\ncall MPI_Comm_size( HYDRO_COMM_WORLD, mpiSize, ierr )\n\nif(my_id .eq. IO_id) delcur = mpiDelcur/mpiSize\n\ncall MPI_Bcast(delcur, 1, MPI_REAL, 0, HYDRO_COMM_WORLD, ierr)\n\n#endif\n\n!       if ( (delcur.gt.delskip*dt/86400. .and. iter.lt.itermax)      &\n      if ( (delcur.gt.delskip .and. iter.lt.itermax)      &\n           .or. iter.lt.itermin ) then\n\n#ifdef HYDRO_D\n\n#ifdef MPP_LAND\nif(my_id .eq. IO_id)  write(6,*) \"Iteration\", iter, \"of\", itermax, \"error:\", delcur\n#else\n                      write(6,*) \"Iteration\", iter, \"of\", itermax, \"error:\", delcur\n#endif\n\n#endif\n\n      goto 80\n      endif\n\n#ifdef MPP_LAND\n\n       call MPP_LAND_COM_REAL(h, fxdim, fydim, 99)\n\n#endif\n\n\n\n!     Compute exfiltration amount and\n!     convergence rate due to ground water\n!     flow\n\n      do j=jts,jte\n        do i=its,ite\n\n\t  if((elev(i,j) - h(i,j)) .lt. 0.) then\n\t    excess(i,j) = sf2(i,j)*(h(i,j) - elev(i,j))\n                 h(i,j) = elev(i,j)\n          else\n\t    excess(i,j) = 0.\n\t  end if\n\n          if(ltype(i,j).eq.1) then\n            convgw(i,j) = sf2(i,j) * (h(i,j)-ho(i,j)) / dt\n          else\n            convgw(i,j) = 0.\n          endif\n        enddo\n      enddo\n\n!      call MPP_LAND_COM_REAL(convgw, fxdim, fydim, 99)\n\n!        Diagnostic water conservation check for this timestep\n\n      dtot = 0.     ! total change in water storage (m3)\n      dtoa = 0.\n\n      do j=jts,jte\n        do i=its,ite\n          if (ltype(i,j).eq.1) then\n\n\t    dtot = dtot + sf2(i,j) *(h(i,j)-ho(i,j)) * darea\n            dtoa = dtoa + sf2(i,j) * abs(h(i,j)-ho(i,j)) * darea\n\n!             dtot = dtot + sf2(i,j) *(h(i,j)-ho(i,j)) * darea(i,j)\n!             dtoa = dtoa + sf2(i,j) * abs(h(i,j)-ho(i,j)) * darea(i,j)\n          endif\n        enddo\n      enddo\n\n      dtot = (dtot/tareal)/dt   ! convert to m/s, rel to land area\n      dtoa = (dtoa/tareal)/dt\n      eocn = (eocn/tareal)/dt\n      ebot = (ebot/tareal)/dt\n\n      zz = 1.e3 * 86400.                    ! convert printout to mm/day\n#ifdef HYDRO_D\n#ifdef MPP_LAND\n\n      call MPI_Reduce(dtot,gdtot,1, MPI_REAL, MPI_SUM, IO_id, HYDRO_COMM_WORLD, ierr)\n      call MPI_Reduce(dtoa,gdtoa,1, MPI_REAL, MPI_SUM, IO_id, HYDRO_COMM_WORLD, ierr)\n      call MPI_Reduce(eocn,geocn,1, MPI_REAL, MPI_SUM, IO_id, HYDRO_COMM_WORLD, ierr)\n      call MPI_Reduce(ebot,gebot,1, MPI_REAL, MPI_SUM, IO_id, HYDRO_COMM_WORLD, ierr)\n\n      if(my_id .eq. IO_id) then\n        write (*,900)                         &\n          gdtot*zz, gdtoa*zz, -geocn*zz, gebot*zz,     &\n          (gdtot-(-geocn+gebot))*zz\n       endif\n\n#else\n\n        write (*,900)                         &\n          dtot*zz, dtoa*zz, -eocn*zz, ebot*zz,     &\n          (dtot-(-eocn+ebot))*zz\n#endif\n#endif\n  900 format                                       &\n        (3x,'    dh/dt       |dh/dt|        ocnflx        botfix',&\n            '        ghmerror'  &\n!         /3x,4f9.4,2(9x),e14.4)\n        /3x,5(e14.4))\n\n      end subroutine gwstep\n\n\n      SUBROUTINE SCOPY (NT, ARR, INCA, BRR, INCB)\n!\n!        Copies array ARR to BRR, incrementing by INCA and INCB\n!        respectively, up to a total length of NT words of ARR.\n!        (Same as Cray SCOPY.)\n!\n      real, DIMENSION(*) :: ARR, BRR\n      integer :: ia, nt, inca, incb, ib\n!\n      IB = 1\n      DO 10 IA=1,NT,INCA\n         BRR(IB) = ARR(IA)\n         IB = IB + INCB\n   10 CONTINUE\n!\n      END SUBROUTINE SCOPY\n\n\nsubroutine trdiagSolve(a,b,c,rhs,x,n)\n\n      implicit none\n\n      integer,intent(in) :: n\n      real,dimension(n),intent(in) :: a, b, c, rhs\n      real,dimension(n),intent(out) :: x\n      real,dimension(n) :: cp, dp\n      real :: m\n      integer i\n\n! initialize c-prime and d-prime\n        cp(1) = c(1)/b(1)\n        dp(1) = rhs(1)/b(1)\n! solve for vectors c-prime and d-prime\n         do i = 2,n\n           m = b(i)-cp(i-1)*a(i)\n           cp(i) = c(i)/m\n           dp(i) = (rhs(i)-dp(i-1)*a(i))/m\n         enddo\n! initialize x\n         x(n) = dp(n)\n! solve for x from the vectors c-prime and d-prime\n        do i = n-1, 1, -1\n          x(i) = dp(i)-cp(i)*x(i+1)\n        end do\n\n\nend subroutine trdiagSolve\n\n\nsubroutine gwSoilFlux(did)\n\n\n  implicit none\n\n  integer, intent(in)\t:: did\n\n\n  real, dimension(rt_domain(did)%ixrt,rt_domain(did)%jxrt) :: smcrel, ztrans, headChange\n  real :: frac, zres\n  integer :: nsoil, i, j, k\n\n  gw2d(did)%qsgwrt = 0.\n  gw2d(did)%qdarcyRT = 0.\n\n! Step 1, collect data\n\n! relative soil moisture content of lowest soil layer (1 = saturated)\n  nsoil = nlst(did)%nsoil\n  smcrel = rt_domain(did)%subsurface%grid_transform%smcrt(:,:,nsoil) / RT_DOMAIN(did)%subsurface%grid_transform%smcmaxrt(:,:,nsoil)\n\n! depth of transition zone from lowest soil layer to groundwater head (in cm)\n! postivie ztrans -> head below LSM soil layer\n! negative ztrans -> head within LSM soil layers\n  ztrans = (rt_domain(did)%elrt + nlst(did)%zsoil8(nsoil)) - gw2d(did)%ho\n  ztrans = ztrans * 100\n\n  ! darcyGwSoil not defined for ztran = 0\n  where(ztrans == 0) ztrans = -5\n\n! Step 2, compute flux either up or down\n\n  do j=gw2d(did)%jts, gw2d(did)%jte\n    do i=gw2d(did)%its, gw2d(did)%ite\n\n        if((ztrans(i,j) > 0) .and. (rt_domain(did)%soiltypRT(i,j) < 13)) then\n        ! if groundwater head < soil layers\n\t  call  darcyGwSoil(ztrans(i,j), smcrel(i,j), rt_domain(did)%soiltypRT(i,j), gw2d(did)%qdarcyRT(i,j))\n\n\t  gw2d(did)%qsgwrt(i,j) = gw2d(did)%qdarcyRT(i,j)\n\n\t  ! check and correct for mass balance\n\t  if(((gw2d(did)%ho(i,j)-gw2d(did)%bot(i,j)) &\n\t    *gw2d(did)%poros(i,j)) < (gw2d(did)%qsgwrt(i,j)*gw2d(did)%dt)) then\n\n\t        gw2d(did)%qdarcyRT(i,j) = 0.\n\t        gw2d(did)%qsgwrt(i,j) = 0.\n\n\t   end if\n\n\telse if(ztrans(i,j) < 0 .and. (rt_domain(did)%soiltypRT(i,j) < 13)) then\n\t! if groundwater head > soil layers\n\t  zres = -ztrans(i,j)\n\t  do k=nsoil,1,-1\n\n\t     if(zres >= rt_domain(did)%subsurface%properties%sldpth(k)*100.) then\n\t     ! complete filling of a LSM soil layer if groundwater head > layer top\n\n! \t       gw2d(did)%qsgwrt(i,j) = (rt_domain(did)%subsurface%properties%sldpth(k) &\n! \t                               * (rt_domain(did)%subsurface%grid_transform%smcmaxrt(i,j,k) - RT_DOMAIN(did)%subsurface%grid_transform%smcrt(i,j,k)) &\n! \t\t\t\t       + gw2d(did)%qsgwrt(i,j)) / gw2d(did)%dt\n\n\t       rt_domain(did)%subsurface%grid_transform%smcrt(i,j,k) = RT_DOMAIN(did)%subsurface%grid_transform%smcmaxrt(i,j,k)\n\n\t       zres = zres - rt_domain(did)%subsurface%properties%sldpth(k)*100.\n\n\t     else\n\t     ! partial filling of a soil layer if not completely below groundwater head\n\n\t       if(zres > (0.5 * rt_domain(did)%subsurface%properties%sldpth(k)*100.)) then\n\n\t\t frac = zres / (rt_domain(did)%subsurface%properties%sldpth(k) * 100.)\n\n\n! \t          gw2d(did)%qsgwrt(i,j) = (rt_domain(did)%subsurface%properties%sldpth(k) &\n! \t                                * (rt_domain(did)%subsurface%grid_transform%smcmaxrt(i,j,k) - RT_DOMAIN(did)%subsurface%grid_transform%smcrt(i,j,k)) &\n! \t\t\t\t\t* frac + gw2d(did)%qsgwrt(i,j)) / gw2d(did)%dt\n\n\t          rt_domain(did)%subsurface%grid_transform%smcrt(i,j,k) = RT_DOMAIN(did)%subsurface%grid_transform%smcmaxrt(i,j,k) * frac\n\n\t       end if\n\n\t     end if\n\t  end do\n\tend if\n    end do\n  end do\n\n          ! sign convention\n          ! qsgwrt < 0 -> downward flux\n          ! qsgwrt > 0 -> upward flux\n\n! TOcheck Step 3, adapt groundwater head (assuming not time lag for percolation / capillary rise flow)\n\n! \t   modify gw-head before gwstep call with respect to specific yield of the\n! \t   aquifer and the computed flux (qsgwrt)\n\n\n headChange = (-gw2d(did)%qdarcyRT) * gw2d(did)%dt / gw2d(did)%poros\n gw2d(did)%ho = gw2d(did)%ho + headChange\n\nend subroutine gwSoilFlux\n\nsubroutine darcyGwSoil(Z, s, soil, q_darcy)\n\nimplicit none\n\nINTEGER, INTENT (IN)  :: soil ! soiltype\n\nREAL :: sig_a, sig_b, sig_c\n\nREAL, DIMENSION(9)    :: k_para\nREAL, INTENT (IN)     :: Z, s\nREAL, INTENT (OUT)    :: q_darcy\nreal                  :: beta,alpha,q_cap,b,ks,aep,c,q_grav,y,fac\n\nreal, dimension(9,12) :: &\n      k_soil = reshape((/&\n0.0778, 3.9939, 0.2913, 4.0801, 0.1386, 4.0500, -12.10, 0.3950, 1.0560,&\n0.0924, 4.8822, 0.2674, 3.8915, 0.1365, 4.3800, -09.00, 0.4100, 0.9380,&\n0.0367, 4.5259, 0.2446, 4.2849, 0.1208, 4.9000, -21.80, 0.4350, 0.2080,&\n0.0101, 3.6896, 0.2153, 4.2765, 0.0887, 5.3000, -78.60, 0.4850, 0.0432,&\n0.0101, 3.6896, 0.2153, 4.2765, 0.0887, 5.3000, -78.60, 0.4850, 0.0432,&\n0.0169, 2.9936, 0.2858, 4.3738, 0.1026, 5.3900, -47.80, 0.4510, 0.0417,&\n0.0271, 4.4743, 0.2587, 3.9055, 0.0920, 7.1200, -29.90, 0.4200, 0.0378,&\n0.0227, 4.3768, 0.2658, 3.8234, 0.0843, 7.7500, -35.60, 0.4770, 0.0102,&\n0.0127, 6.6836, 0.1725, 3.7512, 0.0703, 8.5200, -63.00, 0.4760, 0.0147,&\n0.0530, 9.2423, 0.1859, 3.3688, 0.0728, 10.400, -15.30, 0.4260, 0.0130,&\n0.0165, 5.3972, 0.2479, 3.5549, 0.0641, 10.400, -49.00, 0.4920, 0.0062,&\n0.0200, 6.0106, 0.2474, 3.4788, 0.0622, 11.400, -40.50, 0.4820, 0.0077/),(/9,12/))\n\n\n\n k_para  = k_soil(:,soil)\n sig_a   = 1 - exp( -1 * k_para(1) * Z)\n sig_b   = k_para(2) * Z**k_para(3)\n sig_c   = k_para(4) * exp( -1 * Z**k_para(5))\n y       = sig_a/(1  + exp(sig_b * (s - sig_c))) !solving equation (20) in Boogart et al.\n\n b   =   k_para(6)\n ks  =   k_para(9)\n aep =  -k_para(7)\n\n c      =  2 * b  + 3\n q_grav = -1 * ks * s**c\n\n! alp is constant from equation (13) of paper\nbeta  = 2 + 3 / b\nalpha = 1 + 1.5 /  (beta - 1)\nq_cap = ks * alpha * (aep / Z)**beta\n\n\nq_darcy = y * q_cap + q_grav ![cm/min]\n\n! limit for exteme gradients with q >> saturated hydraulic conductivity\n! if(q_cap > ks) q_cap = ks\n! if(q_grav < -ks) q_grav = -ks\n\n! if(q_darcy > ks) q_darcy = ks\n! if(q_darcy < ks) q_darcy = -ks\n\n\nfac     = 1./6000.\nq_darcy = q_darcy * fac\nq_cap   = q_cap   * fac\nq_grav  = q_grav  * fac\n\n!returns q_darcy in [m/s]\n\nend subroutine darcyGwSoil\n\n\n\nsubroutine aggregateQsgw(did)\n\n\n\n  implicit none\n\n   integer, intent(in) :: did\n   integer :: j,i, ixxRT, jyyRT, m,n\n   real :: agg\n\n\n    do j=1,rt_domain(did)%jx\n     do i=1,rt_domain(did)%ix\n\n       agg= 0.\n\n       do m=nlst(did)%aggfactRT-1,0,-1\n         do n=nlst(did)%aggfactRT-1,0,-1\n\n\n\t    ixxRT = i * nlst(did)%aggfactRT-n\n\t    jyyRT = j * nlst(did)%aggfactRT-m\n\n\n#ifdef MPP_LAND\n\t    if(left_id.ge.0) ixxRT=ixxRT+1\n\t    if(down_id.ge.0) jyyRT=jyyRT+1\n#endif\n             agg = agg + gw2d(did)%qdarcyRT(ixxRT, jyyRT)\n           end do\n         end do\n\n            gw2d(did)%qsgw(i,j) = agg/(nlst(did)%aggfactRT**2)\n       end do\n     end do\n\n\n\nend subroutine aggregateQsgw\n\n! Parallel tridiagonal solver useful for domain decomposed ADI\n! Author(s): Mike Lambert\n! Year: 1996\n! Institution: Lawrence Livermore National Laboratory\n! Publication: Lambert, Rodrigue, and Hewett, \"A parallel DSDADI method\n!                      for solution of the steady state diffusion equation\",\n!                      Parallel Computing 23 (1997) 2041-2065\n! Ported to MPI by Benjamin Fersch, Karlsruhe Institute of Technology (2013)\n\n#ifdef MPP_LAND\n      subroutine parysolv1(c,b,r,ct,pid,z_pid, &\n\t                    xsps, zsps, xdns, zdns)\n\n      implicit none\n\n      integer, intent(in) :: XSPS, &\n                             ZSPS, &\n                             XDNS, &\n                             ZDNS\n\n      real, dimension(ZSPS, XSPS), intent(inout) ::  c, &\n                                                     b\n      real\tCLK_PER\n      parameter\t(CLK_PER = 6.66666667e-9)\n\n      real, dimension(0:ZSPS+1, 0:XSPS+1), intent(inout) ::  r\n\n      real, dimension(XSPS,2) :: zn, zntmp\n\n      real, dimension(XSPS)   :: t1, t2, fac\n\n      real :: clockdt, click\n      real :: ct, ti, tf, dt\n\n      integer :: pid, z_pid\n      integer :: i, j, sndr_pid, msg_type, cnt, ackn\n      integer :: sendReq, recvReq\n\n      integer\tZN_REC\n      parameter\t(ZN_REC = 46)\n\n      integer :: source, dest\n#ifdef TIMING\n      dt = clockdt()\n#endif\n\n      cnt = 2*XSPS\n\n      if (z_pid .eq. 1) then\n\n! Load (ZSPS,j)th equations into passing arrays.\n        do 10 j = 1, XSPS\n          zntmp(j,1) = b(ZSPS,j)\n          zntmp(j,2) = r(ZSPS,j)\n   10   continue\n\n\n#ifdef TIMING\n        ti = click()\n#endif\n\n! ! Send (ZSPS,j)th equations.\n! ! Receive (ZSPS+1,j)th equations.\n\n call MPI_Cart_shift(cartGridComm, rowshift, 1, source, dest, ierr)\n call MPI_Isend(zntmp, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, sendReq, ierr)\n call MPI_Irecv(   zn, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(sendReq, mpp_status, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n        do 20 j = 1, XSPS\n! Backward elimination in (ZSPS,j)th equations to get\n! r(ZSPS,j).\n        fac(j) = 1./(1. - b(ZSPS,j)*zn(j,1))\n\tr(ZSPS,j) = (r(ZSPS,j)-b(ZSPS,j)*zn(j,2))*fac(j)\n! Forward elimination in (ZSPS+1,j)th equations to get\n! r(ZSPS+1,j).\n        r(ZSPS+1,j) = zn(j,2) - zn(j,1)*r(ZSPS,j)\n! Completion of backward elimination to get remaining unknowns.\n        do 30 i = 1, ZSPS-1\n          r(i,j) = r(i,j) - b(i,j)*r(ZSPS,j)\n   30   continue\n   20   continue\n\n      else if (z_pid .le. ZDNS/2) then\n\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Receive (0,j)th equations.\n\n call MPI_Cart_shift(cartGridComm, rowshift, -1, source, dest, ierr)\n call MPI_Irecv(   zn, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n! Forward elimination in (j,1)th equations.\n\tdo 40 j = 1, XSPS\n          fac(j) = 1./(1. - c(1,j)*zn(j,1))\n! Check for singular matrix (debugging only)\n          b(1,j) = b(1,j)*fac(j)\n          r(1,j) = (r(1,j) - c(1,j)*zn(j,2))*fac(j)\n! Forward elimination in (ZSPS,j)th equations.\n          fac(j) = 1./(1. - c(ZSPS,j)*b(1,j))\n! Check for singular matrix (debugging only)\n          b(ZSPS,j) = b(ZSPS,j)*fac(j)\n          r(ZSPS,j) = (r(ZSPS,j)-c(ZSPS,j)*r(1,j))*fac(j)\n! Store (0,j)th equations for later recovery of r(0,j).\n          t1(j) = zn(j,1)\n          t2(j) = zn(j,2)\n! Load (ZSPS,j)th equations into passing arrays.\n          zntmp(j,1) = b(ZSPS,j)\n          zntmp(j,2) = r(ZSPS,j)\n   40   continue\n\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (ZSPS,j)th equations.\n! ! Receive (ZSPS+1,j)th equations.\n\n call MPI_Cart_shift(cartGridComm, rowshift, 1, source, dest, ierr)\n call MPI_Isend(zntmp, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, sendReq, ierr)\n call MPI_Irecv(   zn, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(sendReq, mpp_status, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n        do 50 j = 1, XSPS\n! Backward elimination in (ZSPS,j)th equations.\n          fac(j) = 1./(1. - b(ZSPS,j)*zn(j,1))\n! Check for singular matrix (debugging only)\n          r(ZSPS,j) = (r(ZSPS,j) - b(ZSPS,j)*zn(j,2))*fac(j)\n! Backward elimination in (ZSPS+1,j)th equations.\n          r(ZSPS+1,j) = zn(j,2) - zn(j,1)*r(ZSPS,j)\n! Backward elimination in (ZSPS,j)th equations.\n          r(1,j) = r(1,j) - b(1,j)*r(ZSPS,j)\n! Load (1,j)th equations into passing arrays.\n          zntmp(j,1) = 0.\n          zntmp(j,2) = r(1,j)\n   50   continue\n\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (1,j)th equations.\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n call MPI_Cart_shift(cartGridComm, rowshift, -1, source, dest, ierr)\n call MPI_Isend(zntmp, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, sendReq, ierr)\n\n        do 60 j = 1, XSPS\n! Backward elimination in (0,j)th equations.\n\tr(0,j) = t2(j) - t1(j)*r(1,j)\n        do 70 i = 2, ZSPS-1\n! Completion of forward and backward elimination to get remaining\n! unknowns.\n          r(i,j) = r(i,j) - b(i,j)*r(ZSPS,j) - c(i,j)*r(1,j)\n   70   continue\n   60   continue\n\n call MPI_Wait(sendReq, mpp_status, ierr)\n\n\n      else if (z_pid .lt. ZDNS) then\n\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Receive (ZSPS+1,j)th equations.\n\n call MPI_Cart_shift(cartGridComm, rowshift, 1, source, dest, ierr)\n call MPI_Irecv(   zn, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n\tdo 80 j = 1, XSPS\n! Backward elimination in (ZSPS,j)th equations.\n          fac(j) = 1./(1. - b(ZSPS,j)*zn(j,1))\n! Check for singular matrix (debugging only)\n          c(ZSPS,j) = c(ZSPS,j)*fac(j)\n          r(ZSPS,j) = (r(ZSPS,j)-b(ZSPS,j)*zn(j,2))*fac(j)\n! Backward elimination in (1,j)th equations.\n          fac(j) = 1./(1. - b(1,j)*c(ZSPS,j))\n! Check for singular matrix (debugging only)\n          c(1,j) = c(1,j)*fac(j)\n          r(1,j) = (r(1,j) - b(1,j)*r(ZSPS,j))*fac(j)\n! Store (ZSPS+1,j)th equations for later recovery of\n! r(ZSPS+1,j).\n          t1(j) = zn(j,1)\n          t2(j) = zn(j,2)\n! Load passing arrays with (1,j)th equations.\n          zntmp(j,1) = c(1,j)\n          zntmp(j,2) = r(1,j)\n   80   continue\n\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (1,j)th equations.\n! ! Receive (0,j)th equations.\n\n call MPI_Cart_shift(cartGridComm, rowshift, -1, source, dest, ierr)\n call MPI_Isend(zntmp, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, sendReq, ierr)\n call MPI_Irecv(   zn, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(sendReq, mpp_status, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n\tdo 90 j = 1, XSPS\n! Forward elimination in (1,j)th equations\n          fac(j) = 1./(1. - c(1,j)*zn(j,1))\n! Check for singular matrix (debugging only)\n          r(1,j) = (r(1,j) - c(1,j)*zn(j,2))*fac(j)\n! Backward elimination in (0,j)th equations.\n          r(0,j) = zn(j,2) - zn(j,1)*r(1,j)\n! Forward elimination in (ZSPS,j)th equations.\n          r(ZSPS,j) = r(ZSPS,j) - c(ZSPS,j)*r(1,j)\n! Load (ZSPS,j)th equations into passing arrays.\n          zntmp(j,1) = 0.\n          zntmp(j,2) = r(ZSPS,j)\n   90   continue\n\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (ZSPS,j)th equations.\n\n call MPI_Cart_shift(cartGridComm, rowshift, 1, source, dest, ierr)\n call MPI_Isend(zntmp, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, sendReq, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n        do 100 j = 1, XSPS\n! Forward elimination in (ZSPS+1,j)th equations to get\n! r(ZSPS+1,j).\n\tr(ZSPS+1,j) = t2(j) - t1(j)*r(ZSPS,j)\n        do 110 i = 2, ZSPS-1\n! Completion of forward and backward elimination to get remaining unknowns.\n          r(i,j) = r(i,j) - c(i,j)*r(1,j) - b(i,j)*r(ZSPS,j)\n  110   continue\n  100   continue\n\n call MPI_Wait(sendReq, mpp_status, ierr)\n\n      else\n\n! Load (1,j)th equations into passing arrays.\n\tdo 120 j = 1, XSPS\n          zntmp(j,1) = c(1,j)\n          zntmp(j,2) = r(1,j)\n  120   continue\n\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (1,j)th equations.\n! ! Receive (0,j)th equations.\n\n call MPI_Cart_shift(cartGridComm, rowshift, -1, source, dest, ierr)\n call MPI_Isend(zntmp, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, sendReq, ierr)\n call MPI_Irecv(   zn, cnt, MPI_REAL, dest, ZN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(sendReq, mpp_status, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n        do 130 j = 1, XSPS\n! Forward elimination in (1,j)th equations to get r(1,j).\n\tfac(j) = 1./(1. - c(1,j)*zn(j,1))\n! Check for singular matrix (debugging only)\n        r(1,j) = (r(1,j) - c(1,j)*zn(j,2))*fac(j)\n! Backward elimination in (0,j)th equations to get remaining unknowns.\n        r(0,j) = zn(j,2) - zn(j,1)*r(1,j)\n\tdo 140 i = 2, ZSPS\n! Completion of forward elimination to get remaining unknowns.\n          r(i,j) = r(i,j) - c(i,j)*r(1,j)\n  140   continue\n  130   continue\n\n      endif\n\n      end subroutine\n\n\n! Parallel tridiagonal solver useful for domain decomposed ADI\n! Author(s): Mike Lambert\n! Year: 1996\n! Institution: Lawrence Livermore National Laboratory\n! Publication: Lambert, Rodrigue, and Hewett, \"A parallel DSDADI method\n!                      for solution of the steady state diffusion equation\",\n!                      Parallel Computing 23 (1997) 2041-2065\n! Ported to MPI by Benjamin Fersch, Karlsruhe Institute of Technology (2013)\n\n      subroutine parxsolv1(c,b,r,ct,pid,x_pid, &\n\t                    xsps, zsps, xdns, zdns)\n\n      implicit none\n\n       integer, intent(in) :: XSPS, &\n                              ZSPS, &\n                              XDNS, &\n                              ZDNS\n\n      real, dimension(ZSPS, XSPS), intent(inout) ::  c, &\n                                                     b\n\n\n      real, dimension(0:ZSPS+1, 0:XSPS+1), intent(inout) ::  r\n\n      real, dimension(ZSPS,2) :: xn, xntmp\n\n      integer\tXN_REC\n      parameter\t(XN_REC = 45)\n\n      real, dimension(ZSPS)   :: t1, t2, fac\n      real :: clockdt, click\n      real :: ct, ti, tf, dt\n\n      integer :: pid, x_pid\n      integer :: i, j, sndr_pid, msg_type, cnt, ackn\n      integer :: sendReq, recvReq\n\n      integer :: source, dest\n\n\n#ifdef TIMING\n      dt = clockdt()\n#endif\n\n      if (x_pid .eq. 1) then\n\n! Load passing (i,XSPS)th equations into passing arrays.\n        do 10 i = 1, ZSPS\n          xntmp(i,1) = b(i,XSPS)\n          xntmp(i,2) = r(i,XSPS)\n   10   continue\n\n        cnt = 2*ZSPS\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (i,XSPS)th equations.\n! ! Receive (i,(XSPS + 1))th equations.\n\n call MPI_Cart_shift(cartGridComm, colshift, 1, source, dest, ierr)\n call MPI_Isend(xntmp, cnt, MPI_REAL, dest, XN_REC, cartGridComm, sendReq, ierr)\n call MPI_Irecv(   xn, cnt, MPI_REAL, dest, XN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(sendReq, mpp_status, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n        do 20 i = 1, ZSPS\n! Backward elimination in (i,XSPS)th equations to get\n! r(i,XSPS)\n          fac(i) = 1./(1. - b(i,XSPS)*xn(i,1))\n          r(i,XSPS) = (r(i,XSPS)-b(i,XSPS)*xn(i,2))*fac(i)\n! Forward elimination in (i,XSPS+1)th equations to get\n! r(i,XSPS+1)\n          r(i,XSPS+1) = xn(i,2) - xn(i,1)*r(i,XSPS)\n   20   continue\n\n! Completion of backward elimination to get remaining unknowns.\n        do 30 j = 1, XSPS-1\n        do 30 i = 1, ZSPS\n          r(i,j) = r(i,j) - b(i,j)*r(i,XSPS)\n   30   continue\n\n      else if (x_pid .le. XDNS/2) then\n\n        cnt = 2*ZSPS\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Receive (i,0)th equations.\n\n call MPI_Cart_shift(cartGridComm, colshift, -1, source, dest, ierr)\n call MPI_Irecv(   xn, cnt, MPI_REAL, dest, XN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n! Forward elimination in (i,1)th equations of subdomain.\n\tdo 40 i = 1, ZSPS\n          fac(i) = 1./(1. - c(i,1)*xn(i,1))\n          b(i,1) = b(i,1)*fac(i)\n          r(i,1) = (r(i,1) - c(i,1)*xn(i,2))*fac(i)\n! Forward elimination in (i,XSPS)th equations of subdomain.\n          fac(i) = 1./(1. - c(i,XSPS)*b(i,1))\n          b(i,XSPS) = b(i,XSPS)*fac(i)\n          r(i,XSPS)=(r(i,XSPS)-c(i,XSPS)*r(i,1))*fac(i)\n! Store (i,0)th equations for later recovery of r(i,0).\n          t1(i) = xn(i,1)\n          t2(i) = xn(i,2)\n! Load (i,XSPS)th equations into passing arrays.\n          xntmp(i,1) = b(i,XSPS)\n          xntmp(i,2) = r(i,XSPS)\n   40   continue\n\n        cnt = 2*ZSPS\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (i,XSPS)th equations.\n! ! Receive (i,(XSPS + 1))th equations.\n\n call MPI_Cart_shift(cartGridComm, colshift, 1, source, dest, ierr)\n call MPI_Isend(xntmp, cnt, MPI_REAL, dest, XN_REC, cartGridComm, sendReq, ierr)\n call MPI_Irecv(   xn, cnt, MPI_REAL, dest, XN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(sendReq, mpp_status, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n        do 50 i = 1, ZSPS\n! Backward elimination in (i,XSPS)th equations.\n          fac(i) = 1./(1. - b(i,XSPS)*xn(i,1))\n          r(i,XSPS) = (r(i,XSPS) - b(i,XSPS)*xn(i,2))*fac(i)\n! Backward elimination in (i,XSPS+1)th equations.\n          r(i,XSPS+1) = xn(i,2) - xn(i,1)*r(i,XSPS)\n! Backward elimination in (i,1)th equations to get r(i,1).\n          r(i,1) = r(i,1) - b(i,1)*r(i,XSPS)\n! Load (i,1)th equations into passing array.\n          xntmp(i,1) = 0.\n          xntmp(i,2) = r(i,1)\n   50   continue\n\n        cnt = 2*ZSPS\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (i,1)th equations.\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n call MPI_Cart_shift(cartGridComm, colshift, -1, source, dest, ierr)\n call MPI_Isend(xntmp, cnt, MPI_REAL, dest, XN_REC, cartGridComm, sendReq, ierr)\n\n        do 60 i = 1, ZSPS\n! Backward elimination in (i,0)th equations.\n          r(i,0) = t2(i) - t1(i)*r(i,1)\n   60   continue\n\n! Completion of forward and backward elimination for solution of\n! unknowns.\n        do 70 j = 2, XSPS-1\n        do 70 i = 1, ZSPS\n          r(i,j) = r(i,j) - b(i,j)*r(i,XSPS) - c(i,j)*r(i,1)\n   70   continue\n\n call MPI_Wait(sendReq, mpp_status, ierr)\n\n      else if (x_pid .lt. XDNS) then\n\n        cnt = 2*ZSPS\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Receive (i,XSPS+1)th equations.\n\n call MPI_Cart_shift(cartGridComm, colshift, 1, source, dest, ierr)\n call MPI_Irecv(   xn, cnt, MPI_REAL, dest, XN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n        do 80 i = 1, ZSPS\n! Backward elimination in (i,XSPS)th equations.\n          fac(i) = 1./(1. - b(i,XSPS)*xn(i,1))\n          c(i,XSPS) = c(i,XSPS)*fac(i)\n          r(i,XSPS) = (r(i,XSPS) - b(i,XSPS)*xn(i,2))*fac(i)\n! Backward elimination in (i,1)th equations.\n          fac(i) = 1./(1. - b(i,1)*c(i,XSPS))\n          c(i,1) = c(i,1)*fac(i)\n          r(i,1) = (r(i,1) - b(i,1)*r(i,XSPS))*fac(i)\n! Store (i,XSPS+1)th equations for later recovery of r(i,XSPS+1).\n          t1(i) = xn(i,1)\n          t2(i) = xn(i,2)\n! Load passing arrays with (i,1)th equations.\n          xntmp(i,1) = c(i,1)\n          xntmp(i,2) = r(i,1)\n   80   continue\n\n        cnt = 2*ZSPS\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (i,1)th equations.\n! ! Receive (i,0)th equations.\n call MPI_Cart_shift(cartGridComm, colshift, -1, source, dest, ierr)\n call MPI_Isend(xntmp, cnt, MPI_REAL, dest, XN_REC, cartGridComm, sendReq, ierr)\n call MPI_Irecv(   xn, cnt, MPI_REAL, dest, XN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(sendReq, mpp_status, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n        do 90 i = 1, ZSPS\n! Forward elimination in (i,1)th equations\n          fac(i) = 1./(1. - c(i,1)*xn(i,1))\n          r(i,1) = (r(i,1) - c(i,1)*xn(i,2))*fac(i)\n! Backward elimination in (i,0)th equations.\n          r(i,0) = xn(i,2) - xn(i,1)*r(i,1)\n! Forward elimination in (i,XSPS)th equations.\n          r(i,XSPS) = r(i,XSPS) - c(i,XSPS)*r(i,1)\n! Load (i,XSPS)th equations into passing arrays.\n          xntmp(i,1) = 0.\n          xntmp(i,2) = r(i,XSPS)\n   90   continue\n\n        cnt = 2*ZSPS\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (i,XSPS)th equations.\n\n call MPI_Cart_shift(cartGridComm, colshift, 1, source, dest, ierr)\n call MPI_Isend(xntmp, cnt, MPI_REAL, dest, XN_REC, cartGridComm, sendReq, ierr)\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n! Forward elimination in (i,XSPS)th equations to get\n! r(i,XSPS+1).\n        do 100 i = 1, ZSPS\n          r(i,XSPS+1) = t2(i) - t1(i)*r(i,XSPS)\n  100   continue\n\n! Completion of forward and backward elimination to get remaining unknowns.\n        do 110 j = 2, XSPS-1\n\tdo 110 i = 1, ZSPS\n          r(i,j) = r(i,j) - c(i,j)*r(i,1) - b(i,j)*r(i,XSPS)\n  110   continue\n\n call MPI_Wait(sendReq, mpp_status, ierr)\n\n      else\n\n! Load (i,1)th equations into passing arrays.\n\tdo 120 i = 1, ZSPS\n          xntmp(i,1) = c(i,1)\n          xntmp(i,2) = r(i,1)\n  120   continue\n\n        cnt = 2*ZSPS\n#ifdef TIMING\n        ti = click()\n#endif\n! ! Send (i,1)th equations.\n! ! Receive (i,0)th equations.\n\n call MPI_Cart_shift(cartGridComm, colshift, -1, source, dest, ierr)\n call MPI_Isend(xntmp, cnt, MPI_REAL, dest, XN_REC, cartGridComm, sendReq, ierr)\n call MPI_Irecv(   xn, cnt, MPI_REAL, dest, XN_REC, cartGridComm, recvReq, ierr)\n call MPI_Wait(sendReq, mpp_status, ierr)\n call MPI_Wait(recvReq, mpp_status, ierr)\n\n#ifdef TIMING\n        tf = click()\n        call add_dt(ct,tf,ti,dt)\n#endif\n\n\tdo 130 i = 1, ZSPS\n! Forward elimination in (i,1)th equations to get r(i,1).\n          fac(i) = 1./(1. - c(i,1)*xn(i,1))\n          r(i,1) = (r(i,1) - c(i,1)*xn(i,2))*fac(i)\n! Backward elimination in (i,0)th equations to get r(i,0).\n          r(i,0) = xn(i,2) - xn(i,1)*r(i,1)\n  130   continue\n\n! Completion of forward elimination to get remaining unknowns.\n        do 140 j = 2, XSPS\n        do 140 i = 1, ZSPS\n          r(i,j) = r(i,j) - c(i,j)*r(i,1)\n  140   continue\n\n      endif\n\n      end subroutine\n\n\n! Parallel tridiagonal solver useful for domain decomposed ADI\n! Author(s): Mike Lambert\n! Year: 1996\n! Institution: Lawrence Livermore National Laboratory\n! Publication: Lambert, Rodrigue, and Hewett, \"A parallel DSDADI method\n!                      for solution of the steady state diffusion equation\",\n!                      Parallel Computing 23 (1997) 2041-2065\n\n      subroutine sub_n_form(n_xs,n_zs,c,a,b,r,c2,b2,r2,wk,xfac,zfac, &\n                            dpid,dn_subs,dir)\n\n      implicit none\n\n      integer n_xs,n_zs\n\n!  c(,)  -- subdiagonal elements of tridiagonal systems\n!  a(,)  -- diagonal elements of tridiagonal systems\n!  b(,)  -- superdiagonal elements of tridiagonal systems\n!  r(,)  -- right-hand side elements of tridiagonal systems\n!  c2(,) -- front-leg elements of N-systems\n!  b2(,) -- back-leg elements of N-systems\n!  r2(,) -- right-hand side elements of N-systems\n!  wk(,) -- work array with same dimensions as a, b, c, etc.\n      real c(n_zs,n_xs)\n      real a(n_zs,n_xs)\n      real b(n_zs,n_xs)\n      real r(n_zs,n_xs)\n      real c2(n_zs,n_xs)\n      real b2(n_zs,n_xs)\n      real r2(0:n_zs+1,0:n_xs+1)\n      real wk(n_zs,n_xs)\n      real fac\n      real xfac(n_zs)\n      real zfac(n_xs)\n\n      integer dpid,dn_subs,dir\n      integer i, j, XDIR, ZDIR\n      parameter (XDIR = 1, ZDIR = 2)\n\n      if (dir .eq. XDIR) then\n\n! Forward elimination of subdiagonal elements\n\tif (dpid .eq. 1) then\n\n          do 10 i = 1, n_zs\n            xfac(i) = 1./a(i,1)\n            c2(i,1) = 0.\n            r2(i,1) = r(i,1)*xfac(i)\n   10     continue\n\n          do 20 j = 2, n_xs\n\t  do 20 i = 1, n_zs\n            wk(i,j-1) = b(i,j-1)*xfac(i)\n            xfac(i) = 1./(a(i,j) - c(i,j)*wk(i,j-1))\n            c2(i,j) = 0.\n            r2(i,j) = (r(i,j) - c(i,j)*r2(i,j-1))*xfac(i)\n   20     continue\n\n\t  do 40 i = 1, n_zs\n            b2(i,n_xs) = b(i,n_xs)*xfac(i)\n   40     continue\n\n\telse\n\n          do 50 i = 1, n_zs\n            xfac(i) = 1./a(i,1)\n            c2(i,1) = c(i,1)*xfac(i)\n\t    wk(i,1) = b(i,1)*xfac(i)\n            r2(i,1) = r(i,1)*xfac(i)\n\t    xfac(i) = 1./a(i,2)\n\t    c2(i,2) = c(i,2)*xfac(i)\n\t    r2(i,2) = r(i,2)*xfac(i)\n   50     continue\n\n          do 60 j = 3, n_xs\n\t  do 60 i = 1, n_zs\n            wk(i,j-1) = b(i,j-1)*xfac(i)\n            xfac(i) = 1./(a(i,j) - c(i,j)*wk(i,j-1))\n            c2(i,j) = -c(i,j)*c2(i,j-1)*xfac(i)\n            r2(i,j) = (r(i,j) - c(i,j)*r2(i,j-1))*xfac(i)\n   60     continue\n\n\t  do 80 i = 1, n_zs\n            b2(i,n_xs) = b(i,n_xs)*xfac(i)\n   80     continue\n\n\tendif\n\n! Backward elimination of superdiagonal elements\n        if (dpid .eq. dn_subs) then\n\n          do 90 j = n_xs-1, 2, -1\n          do 90 i = 1, n_zs\n            c2(i,j) = c2(i,j) - wk(i,j)*c2(i,j+1)\n            b2(i,j) = 0.\n            r2(i,j) = r2(i,j) - wk(i,j)*r2(i,j+1)\n   90     continue\n\n\t  do 100 i = 1, n_zs\n            fac = 1./(1. - wk(i,1)*c2(i,2))\n            c2(i,1) = c2(i,1)*fac\n            b2(i,1) = 0.\n            r2(i,1) = (r2(i,1) - wk(i,1)*r2(i,2))*fac\n  100     continue\n\n        else\n\n          do 110 i = 1, n_zs\n            b2(i,n_xs-1) = wk(i,n_xs-1)\n  110     continue\n\n          do 120 j = n_xs-2, 2, -1\n\t  do 120 i = 1, n_zs\n            c2(i,j) = c2(i,j) - wk(i,j)*c2(i,j+1)\n            b2(i,j) = -wk(i,j)*b2(i,j+1)\n            r2(i,j) = r2(i,j) - wk(i,j)*r2(i,j+1)\n  120     continue\n\n! If only 2 points in X-direction, do not execute these statements.\n          if (n_xs .gt. 2) then\n\t    do 130 i = 1, n_zs\n              fac = 1./(1. - wk(i,1)*c2(i,2))\n              c2(i,1) = c2(i,1)*fac\n              r2(i,1) = (r2(i,1) - wk(i,1)*r2(i,2))*fac\n              b2(i,1) = -wk(i,1)*b2(i,2)*fac\n  130       continue\n\t  endif\n\n        endif\n\n      else if (dir .eq. ZDIR) then\n\n! Forward elimination of subdiagonal elements\n\tif (dpid .eq. 1) then\n\n          do 140 j = 1, n_xs\n            zfac(j) = 1./a(1,j)\n            c2(1,j) = 0.\n            r2(1,j) = r(1,j)*zfac(j)\n  140     continue\n\n          do 150 i = 2, n_zs\n          do 150 j = 1, n_xs\n            wk(i-1,j) = b(i-1,j)*zfac(j)\n            zfac(j) = 1./(a(i,j) - c(i,j)*wk(i-1,j))\n            c2(i,j) = 0.\n            r2(i,j) = (r(i,j) - c(i,j)*r2(i-1,j))*zfac(j)\n  150     continue\n\n          do 170 j = 1, n_xs\n            b2(n_zs,j) = b(n_zs,j)*zfac(j)\n  170     continue\n\n        else\n\n          do 180 j = 1, n_xs\n            zfac(j) = 1./a(1,j)\n            c2(1,j) = c(1,j)*zfac(j)\n            wk(1,j) = b(1,j)*zfac(j)\n            r2(1,j) = r(1,j)*zfac(j)\n            zfac(j) = 1./a(2,j)\n            c2(2,j) = c(2,j)*zfac(j)\n            r2(2,j) = r(2,j)*zfac(j)\n  180     continue\n\n          do 190 i = 3, n_zs\n          do 190 j = 1, n_xs\n            wk(i-1,j) = b(i-1,j)*zfac(j)\n            zfac(j) = 1./(a(i,j) - c(i,j)*wk(i-1,j))\n            c2(i,j) = -c(i,j)*c2(i-1,j)*zfac(j)\n            r2(i,j) = (r(i,j) - c(i,j)*r2(i-1,j))*zfac(j)\n  190     continue\n\n          do 210 j = 1, n_xs\n            b2(n_zs,j) = b(n_zs,j)*zfac(j)\n  210     continue\n\n        endif\n\n! Backward elimination of superdiagonal elements\n        if (dpid .eq. dn_subs) then\n\n          do 220 j = 1, n_xs\n          do 220 i = n_zs - 1, 2, -1\n            c2(i,j) = c2(i,j) - wk(i,j)*c2(i+1,j)\n            b2(i,j) = 0.\n            r2(i,j) = r2(i,j) - wk(i,j)*r2(i+1,j)\n  220     continue\n\n\t  do 230 j = 1, n_xs\n            fac = 1./(1. - wk(1,j)*c2(2,j))\n            c2(1,j) = c2(1,j)*fac\n            b2(1,j) = 0.\n            r2(1,j) = (r2(1,j) - wk(1,j)*r2(2,j))*fac\n  230     continue\n\n        else\n\n          do 240 j = 1, n_xs\n            b2(n_zs-1,j) = wk(n_zs-1,j)\n  240     continue\n\n          do 250 j = 1, n_xs\n          do 250 i = n_zs - 2, 2, -1\n            c2(i,j) = c2(i,j) - wk(i,j)*c2(i+1,j)\n            b2(i,j) = -wk(i,j)*b2(i+1,j)\n            r2(i,j)  = r2(i,j) - wk(i,j)*r2(i+1,j)\n  250     continue\n\n! If only 2 points in Z-direction, do not execute these statements.\n          if (n_zs .gt. 2) then\n\t    do 260 j = 1, n_xs\n\t      fac = 1./(1. - wk(1,j)*c2(2,j))\n\t      c2(1,j) = c2(1,j)*fac\n\t      r2(1,j) = (r2(1,j) - wk(1,j)*r2(2,j))*fac\n              b2(1,j) = -wk(1,j)*b2(2,j)*fac\n  260       continue\n\t  endif\n\n        endif\n\n! Announce bad direction specifier (debugging only)\n!     else\n!       write(*,*) 'sub_n_form:  What direction?'\n!       stop\n      endif\n\n      end subroutine\n#endif\n\n! Tridiagonal solver useful for domain decomposed ADI\n! Author(s): Mike Lambert\n! Year: 1996\n! Institution: Lawrence Livermore National Laboratory\n! Publication: Lambert, Rodrigue, and Hewett, \"A parallel DSDADI method\n!                      for solution of the steady state diffusion equation\",\n!                      Parallel Computing 23 (1997) 2041-2065\n\n      subroutine sub_tri_solv(n_xs,n_zs,c,a,b,r,x,wk,xfac,zfac,dir)\n\n      implicit none\n\n      integer n_xs,n_zs\n\n!  c(,)  -- subdiagonal elements of tridiagonal systems\n!  a(,)  -- diagonal elements of tridiagonal systems\n!  b(,)  -- superdiagonal elements of tridiagonal systems\n!  r(,)  -- right-hand side elements of tridiagonal systems\n!  x(,)  -- solutions\n!  wk(,) -- work array w/ same dimensions as c, a, b, etc.\n\n      real c(n_zs,n_xs)\n      real a(n_zs,n_xs)\n      real b(n_zs,n_xs)\n      real r(n_zs,n_xs)\n      real x(0:n_zs+1,0:n_xs+1)\n      real wk(n_zs,n_xs)\n      real xfac(n_zs)\n      real zfac(n_xs)\n\n      integer dir\n      integer i,j,XDIR,ZDIR\n\n      parameter (XDIR = 1, ZDIR = 2)\n\n      if (dir .eq. XDIR) then\n\n        do 10 i = 1, n_zs\n! Check for need to pivot (debugging only)\n        xfac(i) = 1./a(i,1)\n        x(i,1)  = r(i,1)*xfac(i)\n   10   continue\n\n! Forward subdiagonal elimination\n        do 20 j = 2, n_xs\n\tdo 20 i = 1, n_zs\n        wk(i,j-1) = b(i,j-1)*xfac(i)\n        xfac(i) = 1./(a(i,j) - c(i,j)*wk(i,j-1))\n! Check for need to pivot (debugging only)\n        x(i,j) = (r(i,j) - c(i,j)*x(i,j-1))*xfac(i)\n   20   continue\n\n! Backsubstitution\n        do 30 j = n_xs - 1, 1, -1\n\tdo 30 i = 1, n_zs\n        x(i,j)  = x(i,j) - wk(i,j)*x(i,j+1)\n   30   continue\n\n\n      else if (dir .eq. ZDIR) then\n\n       do j = 1, n_xs\n! Check for need to pivot (debugging only)\n        zfac(j) = 1./a(1,j)\n        x(1,j)  = r(1,j)*zfac(j)\n       end do\n\n! Forward subdiagonal elimination\n      do j = 1, n_xs\n       do i = 2, n_zs\n        wk(i-1,j) = b(i-1,j)*zfac(j)\n        zfac(j) = 1./(a(i,j) - c(i,j)*wk(i-1,j))\n! Check for need to pivot (debugging only)\n        x(i,j) = (r(i,j) - c(i,j)*x(i-1,j))*zfac(j)\n       end do\n      end do\n\n! Backsubstitution\n      do j = 1, n_xs\n       do i = n_zs - 1, 1, -1\n        x(i,j)  =  x(i,j) - wk(i,j)*x(i+1,j)\n       end do\n      end do\n\n! Announce bad direction specifier (debugging only)\n!     else\n!       write(*,*) 'sub_tri_solv:  What direction?'\n!       stop\n      endif\n\n      end  subroutine\n\n\nend module module_gw_gw2d\n"
  },
  {
    "path": "src/Routing/module_lsm_forcing.F90",
    "content": "module module_lsm_forcing\n\n#ifdef MPP_LAND\n    use module_mpp_land\n#endif\n    use module_HYDRO_io, only: get_2d_netcdf, get_soilcat_netcdf, get2d_int\n    use module_hydro_stop, only:HYDRO_stop\n    use netcdf\n\nimplicit none\n    integer :: i_forcing\ncharacter(len=19) out_date\n\ninterface read_hydro_forcing\n#ifdef MPP_LAND\n   !yw module procedure read_hydro_forcing_mpp\n   module procedure read_hydro_forcing_mpp1\n#else\n   module procedure read_hydro_forcing_seq\n#endif\nend interface\n\nContains\n\n  subroutine READFORC_WRF(flnm,ix,jx,target_date,t,q,u,v,p,lw,sw,pcp,lai,fpar)\n\n    implicit none\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    character(len=*),                   intent(in)  :: target_date\n    real,             dimension(ix,jx) :: t,q,u,v,p,lw,sw,pcp,pcpc, lai,fpar\n    integer   tlevel\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n\n    tlevel = 1\n\n    pcp = 0\n    pcpc = 0\n\n    ! Open the NetCDF file.\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READFORC_WRF Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READFORC_WRF() - Problem opening netcdf file\")\n    endif\n\n    call get_2d_netcdf_ruc(\"T2\",     ncid, t,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"Q2\",     ncid, q,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"U10\",    ncid, u,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"V10\",    ncid, v,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"PSFC\",   ncid, p,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"GLW\",    ncid, lw,    ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"SWDOWN\", ncid, sw,    ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"RAINC\",  ncid, pcpc,  ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"RAINNC\", ncid, pcp,   ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"VEGFRA\", ncid, fpar,  ix, jx,tlevel, .true., ierr)\n    if(ierr == 0) then\n        if(maxval(fpar) .gt. 10 .and. (maxval(fpar) .lt. 10000) ) fpar = fpar*0.01\n    endif\n    call get_2d_netcdf_ruc(\"LAI\", ncid, lai,  ix, jx,tlevel, .true., ierr)\n\n    ierr = nf90_close(ncid)\n\n!DJG  Add the convective and non-convective rain components (note: conv. comp=0\n!for cloud resolving runs...)\n!DJG  Note that for WRF these are accumulated values to be adjusted to rates in\n!driver...\n\n    pcp=pcp+pcpc   ! assumes pcpc=0 for resolved convection...\n\n  end subroutine READFORC_WRF\n\n  subroutine read_hrldas_hdrinfo(geo_static_flnm, ix, jx, land_cat, soil_cat)\n    ! Simply return the dimensions of the grid.\n    implicit none\n    character(len=*),          intent(in)  :: geo_static_flnm\n    integer, intent(out) :: ix, jx, land_cat, soil_cat ! dimensions\n\n    integer :: iret, ncid, dimid\n\n    ! Open the NetCDF file.\n    iret = nf90_open(geo_static_flnm, NF90_NOWRITE, ncid)\n    if (iret /= 0) then\n       write(*,'(\"Problem opening geo_static file: ''\", A, \"''\")') &\n            trim(geo_static_flnm)\n       call hydro_stop(\"In read_hrldas_hdrinfo() - Problem opening geo_static file\")\n    endif\n\n    iret = nf90_inq_dimid(ncid, \"west_east\", dimid)\n\n    if (iret /= 0) then\n!       print*, \"nf90_inq_dimid:  west_east\"\n       call hydro_stop(\"In read_hrldas_hdrinfo() - nf90_inq_dimid:  west_east problem\")\n    endif\n\n    iret = nf90_inquire_dimension(ncid, dimid, len=ix)\n    if (iret /= 0) then\n!       print*, \"nf90_inq_dimlen:  west_east\"\n       call hydro_stop(\"In read_hrldas_hdrinfo() - nf90_inq_dimlen:  west_east problem\")\n    endif\n\n    iret = nf90_inq_dimid(ncid, \"south_north\", dimid)\n    if (iret /= 0) then\n!       print*, \"nf90_inq_dimid:  south_north\"\n       call hydro_stop(\"In read_hrldas_hdrinfo() - nf90_inq_dimid:  south_north problem\")\n    endif\n\n    iret = nf90_inquire_dimension(ncid, dimid, len=jx)\n    if (iret /= 0) then\n !      print*, \"nf90_inq_dimlen:  south_north\"\n       call hydro_stop(\"In read_hrldas_hdrinfo() - nf90_inq_dimlen:  south_north problem\")\n    endif\n\n    iret = nf90_inq_dimid(ncid, \"land_cat\", dimid)\n    if (iret /= 0) then\n !      print*, \"nf90_inq_dimid:  land_cat\"\n       call hydro_stop(\"In read_hrldas_hdrinfo() - nf90_inq_dimid:  land_cat problem\")\n    endif\n\n    iret = nf90_inquire_dimension(ncid, dimid, len=land_cat)\n    if (iret /= 0) then\n       print*, \"nf90_inq_dimlen:  land_cat\"\n       call hydro_stop(\"In read_hrldas_hdrinfo() - nf90_inq_dimlen:  land_cat problem\")\n    endif\n\n    iret = nf90_inq_dimid(ncid, \"soil_cat\", dimid)\n    if (iret /= 0) then\n !      print*, \"nf90_inq_dimid:  soil_cat\"\n       call hydro_stop(\"In read_hrldas_hdrinfo() - nf90_inq_dimid:  soil_cat problem\")\n    endif\n\n    iret = nf90_inquire_dimension(ncid, dimid, len=soil_cat)\n    if (iret /= 0) then\n !      print*, \"nf90_inq_dimlen:  soil_cat\"\n       call hydro_stop(\"In read_hrldas_hdrinfo() - nf90_inq_dimlen:  soil_cat problem\")\n    endif\n\n    iret = nf90_close(ncid)\n\n  end subroutine read_hrldas_hdrinfo\n\n\n\n  subroutine readland_hrldas(geo_static_flnm,ix,jx,land_cat,soil_cat,vegtyp,soltyp, &\n                  terrain,latitude,longitude,SOLVEG_INITSWC)\n    implicit none\n    character(len=*),          intent(in)  :: geo_static_flnm\n    integer,                   intent(in)  :: ix, jx, land_cat, soil_cat,SOLVEG_INITSWC\n    integer, dimension(ix,jx), intent(out) :: vegtyp, soltyp\n    real,    dimension(ix,jx), intent(out) :: terrain, latitude, longitude\n\n    character(len=256) :: units\n    integer :: ierr,i,j,jj\n    integer :: ncid,varid\n    real, dimension(ix,jx) :: xdum\n    integer, dimension(ix,jx) :: vegtyp_inv, soiltyp_inv,xdum_int\n    integer flag ! flag = 1 from wrfsi, flag =2 from WPS.\n    CHARACTER(len=256)       :: var_name\n    integer :: islake, iswater, isoilwater\n\n    ! Open the NetCDF file.\n    ierr = nf90_open(geo_static_flnm, NF90_NOWRITE, ncid)\n\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"Problem opening geo_static file: ''\", A, \"''\")') trim(geo_static_flnm)\n       call hydro_stop(\"In readland_hrldas() - Problem opening geo_static file\")\n    endif\n\n    flag = -99\n    ierr = nf90_inq_varid(ncid,\"XLAT\", varid)\n    flag = 1\n    if(ierr .ne. 0) then\n        ierr = nf90_inq_varid(ncid,\"XLAT_M\", varid)\n        if(ierr .ne. 0) then\n!            write(6,*) \"XLAT not found from wrfstatic file. \"\n            call hydro_stop(\"In readland_hrldas() - XLAT not found from wrfstatic file\")\n        endif\n        flag = 2\n    endif\n\n    ! Get Latitude (lat)\n    if(flag .eq. 1) then\n       call get_2d_netcdf(\"XLAT\", ncid, latitude,  units, ix, jx, .TRUE., ierr)\n    else\n      call get_2d_netcdf(\"XLAT_M\", ncid, latitude,  units, ix, jx, .TRUE., ierr)\n    endif\n\n    ! Get Longitude (lon)\n    if(flag .eq. 1) then\n        call get_2d_netcdf(\"XLONG\", ncid, longitude, units, ix, jx, .TRUE., ierr)\n    else\n        call get_2d_netcdf(\"XLONG_M\", ncid, longitude, units, ix, jx, .TRUE., ierr)\n    endif\n\n    ! Get Terrain (avg)\n    if(flag .eq. 1) then\n       call get_2d_netcdf(\"HGT\", ncid, terrain,   units, ix, jx, .TRUE., ierr)\n    else\n        call get_2d_netcdf(\"HGT_M\", ncid, terrain,   units, ix, jx, .TRUE., ierr)\n    endif\n\n\n    if (SOLVEG_INITSWC.eq.0) then\n!      ! Get Dominant Land Use categories (use)\n!      call get_landuse_netcdf(ncid, xdum ,   units, ix, jx, land_cat)\n!      vegtyp = nint(xdum)\n\n     var_name = \"LU_INDEX\"\n         call get2d_int(var_name,xdum_int,ix,jx,&\n               trim(geo_static_flnm))\n         vegtyp = xdum_int\n\n      ! Get Dominant Soil Type categories in the top layer (stl)\n      call get_soilcat_netcdf(ncid, xdum ,   units, ix, jx, soil_cat)\n      soltyp = nint(xdum)\n\n    else if (SOLVEG_INITSWC.eq.1) then\n       var_name = \"VEGTYP\"\n       call get2d_int(var_name,VEGTYP_inv,ix,jx,&\n              trim(geo_static_flnm))\n\n       var_name = \"SOILTYP\"\n       call get2d_int(var_name,SOILTYP_inv,ix,jx,&\n              trim(geo_static_flnm))\n       do i=1,ix\n         jj=jx\n         do j=1,jx\n           VEGTYP(i,j)=VEGTYP_inv(i,jj)\n           SOLTYP(i,j)=SOILTYP_inv(i,jj)\n           jj=jx-j\n         end do\n       end do\n\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, 'ISWATER', iswater)\n    if (ierr /= NF90_NOERR) then\n       call hydro_stop(\"In readland_hrldas() - Attribute ISWATER unable to be read from geo_static_flnm\")\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, 'ISOILWATER', isoilwater)\n    if (ierr /= NF90_NOERR) then\n       call hydro_stop(\"In readland_hrldas() - Attribute ISOILWATER unable to be read from geo_static_flnm\")\n    endif\n\n    ierr = nf90_get_att(ncid, NF90_GLOBAL, 'ISLAKE', islake)\n    if (ierr /= NF90_NOERR) then\n       call hydro_stop(\"In readland_hrldas() - Attribute ISLAKE unable to be read from geo_static_flnm\")\n    endif\n\n    ! Close the NetCDF file\n    ierr = nf90_close(ncid)\n    if (ierr /= NF90_NOERR) then\n       print*, \"MODULE_NOAHLSM_HRLDAS_INPUT:  READLAND_HRLDAS:  NF90_CLOSE\"\n       call hydro_stop(\"In readland_hrldas() - NF90_CLOSE problem\")\n    endif\n\n write(6, *) \"readland_hrldas: ISLAKE ISWATER ISOILWATER\", islake, iswater, isoilwater\n\n    ! Make sure vegtyp and soltyp are consistent when it comes to water points,\n    ! by setting soil category to water when vegetation category is water, and\n    ! vice-versa.\n    where (vegtyp == islake) vegtyp = iswater\n    where (vegtyp == iswater) soltyp = isoilwater\n    where (soltyp == isoilwater) vegtyp = iswater\n\n!DJG test for deep gw function...\n!    where (soltyp <> 14) soltyp = 1\n\n  end subroutine readland_hrldas\n\n\n      subroutine get_2d_netcdf_ruc(var_name,ncid,var, &\n            ix,jx,tlevel,fatal_if_error,ierr)\n          character(len=*), intent(in) :: var_name\n          integer,intent(in) ::  ncid,ix,jx,tlevel\n          real, intent(out):: var(ix,jx)\n          logical, intent(in) :: fatal_if_error\n          integer dims(4), dim_len(4)\n          integer ierr,iret\n          integer varid\n           integer start(4),count(4)\n           data count /1,1,1,1/\n           data start /1,1,1,1/\n          count(1) = ix\n          count(2) = jx\n          start(4) = tlevel\n      ierr = nf90_inq_varid(ncid,  var_name,  varid)\n\n      if (ierr /= NF90_NOERR) then\n        if (fatal_IF_ERROR) then\n           print*, \"MODULE_NOAHLSM_HRLDAS_INPUT: get_2d_netcdf_ruc:nf90_inq_varid \", trim(var_name)\n           call hydro_stop(\"In get_2d_netcdf_ruc() - nf90_inq_varid problem\")\n        else\n          return\n        endif\n      endif\n\n      ierr = nf90_get_var(ncid, varid, var, start, count)\n\n\n      end subroutine get_2d_netcdf_ruc\n\n\n      subroutine get_2d_netcdf_cows(var_name,ncid,var, &\n            ix,jx,tlevel,fatal_if_error,ierr)\n          character(len=*), intent(in) :: var_name\n          integer,intent(in) ::  ncid,ix,jx,tlevel\n          real, intent(out):: var(ix,jx)\n          logical, intent(in) :: fatal_if_error\n          integer ierr, iret\n          integer varid\n          integer start(4),count(4)\n          data count /1,1,1,1/\n          data start /1,1,1,1/\n          count(1) = ix\n          count(2) = jx\n          start(4) = tlevel\n      iret = nf90_inq_varid(ncid,  var_name,  varid)\n\n      if (iret /= 0) then\n        if (fatal_IF_ERROR) then\n           print*, \"MODULE_NOAHLSM_HRLDAS_INPUT: get_2d_netcdf_cows:nf90_inq_varid\"\n           call hydro_stop(\"In get_2d_netcdf_cows() - nf90_inq_varid problem\")\n        else\n          ierr = iret\n          return\n        endif\n      endif\n      iret = nf90_get_var(ncid, varid, var, start,count)\n\n      end subroutine get_2d_netcdf_cows\n\n\n\n\n\n  subroutine readinit_hrldas(netcdf_flnm, ix, jx, nsoil, target_date, &\n       smc, stc, sh2o, cmc, t1, weasd, snodep)\n    implicit none\n    character(len=*),                intent(in)  :: netcdf_flnm\n    integer,                         intent(in)  :: ix\n    integer,                         intent(in)  :: jx\n    integer,                         intent(in)  :: nsoil\n    character(len=*),                intent(in)  :: target_date\n    real,    dimension(ix,jx,nsoil), intent(out) :: smc\n    real,    dimension(ix,jx,nsoil), intent(out) :: stc\n    real,    dimension(ix,jx,nsoil), intent(out) :: sh2o\n    real,    dimension(ix,jx),       intent(out) :: cmc\n    real,    dimension(ix,jx),       intent(out) :: t1\n    real,    dimension(ix,jx),       intent(out) :: weasd\n    real,    dimension(ix,jx),       intent(out) :: snodep\n\n    character(len=256) :: units\n    character(len=8) :: name\n    integer :: ix_read, jx_read,i,j\n\n    integer :: ierr, ncid, ierr_snodep\n    integer :: idx\n\n    logical :: found_canwat, found_skintemp, found_weasd, found_stemp, found_smois\n\n    ! Open the NetCDF file.\n    ierr = nf90_open(netcdf_flnm, NF90_NOWRITE, ncid)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READINIT Problem opening netcdf file: ''\", A, \"''\")') &\n            trim(netcdf_flnm)\n       call hydro_stop(\"In readinit_hrldas()- Problem opening netcdf file\")\n    endif\n\n    call get_2d_netcdf(\"CANWAT\",     ncid, cmc,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"SKINTEMP\",   ncid, t1,      units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"WEASD\",      ncid, weasd,   units, ix, jx, .TRUE., ierr)\n\n    if (trim(units) == \"m\") then\n       ! No conversion necessary\n    else if (trim(units) == \"mm\") then\n       ! convert WEASD from mm to m\n       weasd = weasd * 1.E-3\n    else\n       print*, 'units = \"'//trim(units)//'\"'\n!       print*, \"Unrecognized units on WEASD\"\n       call hydro_stop(\"In readinit_hrldas() - Unrecognized units on WEASD\")\n    endif\n\n    call get_2d_netcdf(\"SNODEP\",     ncid, snodep,   units, ix, jx, .FALSE., ierr_snodep)\n    call get_2d_netcdf(\"STEMP_1\",    ncid, stc(:,:,1), units,  ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"STEMP_2\",    ncid, stc(:,:,2), units,  ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"STEMP_3\",    ncid, stc(:,:,3), units,  ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"STEMP_4\",    ncid, stc(:,:,4), units,  ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"SMOIS_1\",    ncid, smc(:,:,1), units,  ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"SMOIS_2\",    ncid, smc(:,:,2), units,  ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"SMOIS_3\",    ncid, smc(:,:,3), units,  ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"SMOIS_4\",    ncid, smc(:,:,4), units,  ix, jx, .TRUE., ierr)\n\n\n    if (ierr_snodep /= 0) then\n       ! Quick assumption regarding snow depth.\n       snodep = weasd * 10.\n    endif\n\n\n!DJG check for erroneous neg WEASD or SNOWD due to offline interpolation...\n       do i=1,ix\n         do j=1,jx\n           if (WEASD(i,j).lt.0.) WEASD(i,j)=0.0  !set lower bound to correct bi-lin interp err...\n           if (snodep(i,j).lt.0.) snodep(i,j)=0.0  !set lower bound to correct bi-lin interp err...\n         end do\n       end do\n\n\n    sh2o = smc\n\n    ierr = nf90_close(ncid)\n  end subroutine readinit_hrldas\n\n\n\n\n  subroutine READFORC_HRLDAS(flnm,ix,jx,target_date, &\n       forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n       forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n       t,q,u,v,p,lw,sw,pcp,lai,snowbl,fpar)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    character(len=*),                   intent(in)  :: target_date\n    character(len=256), intent(in)  :: forcing_name_T\n    character(len=256), intent(in)  :: forcing_name_Q\n    character(len=256), intent(in)  :: forcing_name_U\n    character(len=256), intent(in)  :: forcing_name_V\n    character(len=256), intent(in)  :: forcing_name_P\n    character(len=256), intent(in)  :: forcing_name_LW\n    character(len=256), intent(in)  :: forcing_name_SW\n    character(len=256), intent(in)  :: forcing_name_PR\n    character(len=256), intent(in)  :: forcing_name_SN\n    character(len=256), intent(in)  :: forcing_name_LF\n    real,             dimension(ix,jx), intent(out) :: t\n    real,             dimension(ix,jx), intent(out) :: q\n    real,             dimension(ix,jx), intent(out) :: u\n    real,             dimension(ix,jx), intent(out) :: v\n    real,             dimension(ix,jx), intent(out) :: p\n    real,             dimension(ix,jx), intent(out) :: lw\n    real,             dimension(ix,jx), intent(out) :: sw\n    real,             dimension(ix,jx), intent(out) :: pcp\n    real,             dimension(ix,jx), intent(inout) :: lai\n    real,             dimension(ix,jx), intent(inout) :: fpar\n    real,             dimension(ix,jx), intent(inout) :: snowbl\n    real,             dimension(:,:),   allocatable   :: liqfrac\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n\n    ! Open the NetCDF file.\n    ierr = nf90_open(trim(flnm), NF90_NOWRITE, ncid)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READFORC Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READFORC_HRLDAS() - Problem opening netcdf file\")\n    endif\n\n    call get_2d_netcdf(trim(forcing_name_T),     ncid, t,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_Q),     ncid, q,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_U),     ncid, u,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_V),     ncid, v,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_P),    ncid, p,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_lw),  ncid, lw,    units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_sw),  ncid, sw,    units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_pr),ncid, pcp,   units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"VEGFRA\",  ncid, fpar,  units, ix, jx, .FALSE., ierr)\n    if (ierr == 0) then\n      if(maxval(fpar) .gt. 10 .and. maxval(fpar) .lt. 10000)  fpar = fpar * 1.E-2\n    endif\n\n    call get_2d_netcdf(\"LAI\",     ncid, lai,   units, ix, jx, .FALSE., ierr)\n    call get_2d_netcdf(trim(forcing_name_SN),    ncid, snowbl,units, ix, jx, .FALSE., ierr)\n    if (ierr /= NF90_NOERR) then\n       allocate(liqfrac(ix,jx))\n       call get_2d_netcdf(trim(forcing_name_LF), ncid, liqfrac, units, ix, jx, .FALSE., ierr)\n       if (ierr == 0) then\n          snowbl = (1.0 - liqfrac) * pcp\n       else\n          snowbl = 0.0 ! since is liqfrac is not present it is equal to 1.0\n       end if\n       deallocate(liqfrac)\n    end if\n\n    ierr = nf90_close(ncid)\n\n  end subroutine READFORC_HRLDAS\n\n\n\n  subroutine READFORC_DMIP(flnm,ix,jx,var)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    real,       dimension(ix,jx), intent(out)       :: var\n    character(len=13)                               :: head\n    integer                          :: ncols, nrows, cellsize\n    real                             :: xllc, yllc, no_data\n    integer                          :: i,j\n    character(len=256)                              ::junk\n\n    open (77,file=trim(flnm),form=\"formatted\",status=\"old\")\n\n!    read(77,732) head,ncols\n!    read(77,732) head,nrows\n!732        FORMAT(A13,I4)\n!    read(77,733) head,xllc\n!    read(77,733) head,yllc\n!733        FORMAT(A13,F16.9)\n!    read(77,732) head,cellsize\n!    read(77,732) head,no_data\n\n    read(77,*) junk\n    read(77,*) junk\n    read(77,*) junk\n    read(77,*) junk\n    read(77,*) junk\n    read(77,*) junk\n\n    do j=jx,1,-1\n      read(77,*) (var(I,J),I=1,ix)\n    end do\n    close(77)\n\n  end subroutine READFORC_DMIP\n\n\n\n  subroutine READFORC_MDV(flnm,ix,jx,pcp,mmflag,ierr_flg)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    integer,                            intent(out)  :: ierr_flg\n    integer :: it,jew,zsn\n    real,             dimension(ix,jx), intent(out) :: pcp\n\n    character(len=256) :: units\n    integer :: ierr,i,j,i2,j2,varid\n    integer :: ncid,mmflag\n    real, dimension(ix,jx) :: temp\n\n    mmflag = 0   ! flag for units spec. (0=mm, 1=mm/s)\n\n\n!open NetCDF file...\n        ierr_flg = nf90_open(flnm, NF90_NOWRITE, ncid)\n        if (ierr_flg /= 0) then\n#ifdef HYDRO_D\n          write(*,'(\"READFORC_MDV Problem opening netcdf file: ''\",A,\"''\")') &\n                trim(flnm)\n#endif\n           return\n        end if\n\n        ierr = nf90_inq_varid(ncid,  \"precip\",  varid)\n        if(ierr /= NF90_NOERR) ierr_flg = ierr\n        if (ierr /= NF90_NOERR) then\n          ierr = nf90_inq_varid(ncid,  \"precip_rate\",  varid)   !recheck variable name...\n          if (ierr /= NF90_NOERR) then\n            ierr = nf90_inq_varid(ncid,  \"RAINRATE\",  varid)   !recheck variable name...\n            if (ierr /= NF90_NOERR) then\n#ifdef HYDRO_D\n              write(*,'(\"READFORC_MDV Problem reading precip netcdf file: ''\", A,\"''\")') &\n                 trim(flnm)\n#endif\n            end if\n          end if\n          ierr_flg = ierr\n          mmflag = 1\n        end if\n        ierr = nf90_get_var(ncid, varid, pcp)\n        ierr = nf90_close(ncid)\n\n        if (ierr /= NF90_NOERR) then\n#ifdef HYDRO_D\n          write(*,'(\"READFORC_MDV Problem reading netcdf file: ''\", A,\"''\")') trim(flnm)\n#endif\n        end if\n\n  end subroutine READFORC_MDV\n\n\n\n  subroutine READFORC_NAMPCP(flnm,ix,jx,pcp,k,product)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    integer,                            intent(in)  :: k\n    character(len=*),                   intent(in)  :: product\n    integer :: it,jew,zsn\n    parameter(it =  496,jew = 449, zsn = 499)   ! domain 1\n!    parameter(it =  496,jew = 74, zsn = 109)   ! domain 2\n    real,             dimension(it,jew,zsn) :: buf\n    real,             dimension(ix,jx), intent(out) :: pcp\n\n    character(len=256) :: units\n    integer :: ierr,i,j,i2,j2,varid\n    integer :: ncid\n    real, dimension(ix,jx) :: temp\n\n!      varname = trim(product)\n\n!open NetCDF file...\n      if (k.eq.1.) then\n        ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n        if (ierr /= NF90_NOERR) then\n          write(*,'(\"READFORC_NAMPCP1 Problem opening netcdf file: ''\",A, \"''\")') &\n              trim(flnm)\n          call hydro_stop(\"In READFORC_NAMPCP() - Problem opening netcdf file\")\n        end if\n\n        ierr = nf90_inq_varid(ncid,  trim(product),  varid)\n        ierr = nf90_get_var(ncid, varid, buf)\n        ierr = nf90_close(ncid)\n\n        if (ierr /= NF90_NOERR) then\n          write(*,'(\"READFORC_NAMPCP2 Problem reading netcdf file: ''\", A,\"''\")') &\n             trim(flnm)\n          call hydro_stop(\"In READFORC_NAMPCP() - Problem reading netcdf file\")\n        end if\n      endif\n#ifdef HYDRO_D\n      print *, \"Data read in...\",it,ix,jx,k\n#endif\n\n! Extract single time slice from dataset...\n\n      do i=1,ix\n        do j=1,jx\n          pcp(i,j) = buf(k,i,j)\n        end do\n      end do\n\n!      call get_2d_netcdf_ruc(\"trmm\",ncid, pcp, jx, ix,k, .true., ierr)\n\n  end subroutine READFORC_NAMPCP\n\n\n\n\n  subroutine READFORC_COWS(flnm,ix,jx,target_date, t,q,u,p,lw,sw,pcp,tlevel)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    character(len=*),                   intent(in)  :: target_date\n    real,             dimension(ix,jx), intent(out) :: t\n    real,             dimension(ix,jx), intent(out) :: q\n    real,             dimension(ix,jx), intent(out) :: u\n    real,             dimension(ix,jx) :: v\n    real,             dimension(ix,jx), intent(out) :: p\n    real,             dimension(ix,jx), intent(out) :: lw\n    real,             dimension(ix,jx), intent(out) :: sw\n    real,             dimension(ix,jx), intent(out) :: pcp\n    integer   tlevel\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n\n    ! Open the NetCDF file.\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READFORC_COWS Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READFORC_COWS() - Problem opening netcdf file\")\n    endif\n\n    call get_2d_netcdf_cows(\"TA2\",     ncid, t,     ix, jx,tlevel, .TRUE., ierr)\n    call get_2d_netcdf_cows(\"QV2\",     ncid, q,     ix, jx,tlevel, .TRUE., ierr)\n    call get_2d_netcdf_cows(\"WSPD10\",  ncid, u,     ix, jx,tlevel, .TRUE., ierr)\n    call get_2d_netcdf_cows(\"PRES\",    ncid, p,     ix, jx,tlevel, .TRUE., ierr)\n    call get_2d_netcdf_cows(\"GLW\",     ncid, lw,    ix, jx,tlevel, .TRUE., ierr)\n    call get_2d_netcdf_cows(\"RSD\",     ncid, sw,    ix, jx,tlevel, .TRUE., ierr)\n    call get_2d_netcdf_cows(\"RAIN\",    ncid, pcp,   ix, jx,tlevel, .TRUE., ierr)\n!yw   call get_2d_netcdf_cows(\"V2D\",     ncid, v,     ix, jx,tlevel, .TRUE., ierr)\n\n    ierr = nf90_close(ncid)\n\n  end subroutine READFORC_COWS\n\n\n\n\n  subroutine READFORC_RUC(flnm,ix,jx,target_date,t,q,u,v,p,lw,sw,pcp)\n\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    character(len=*),                   intent(in)  :: target_date\n    real,             dimension(ix,jx) :: t,q,u,v,p,lw,sw,pcp,pcpc\n    integer   tlevel\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n\n    tlevel = 1\n\n    ! Open the NetCDF file.\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READFORC_RUC Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READFORC_RUC() - Problem opening netcdf file\")\n    endif\n\n    call get_2d_netcdf_ruc(\"T2\",     ncid, t,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"Q2\",     ncid, q,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"U10\",    ncid, u,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"V10\",    ncid, v,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"PSFC\",   ncid, p,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"GLW\",    ncid, lw,    ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"SWDOWN\", ncid, sw,    ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"RAINC\",  ncid, pcpc,  ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"RAINNC\", ncid, pcp,   ix, jx,tlevel, .true., ierr)\n\n    ierr = nf90_close(ncid)\n\n\n!DJG  Add the convective and non-convective rain components (note: conv. comp=0\n!for cloud resolving runs...)\n!DJG  Note that for RUC these are accumulated values to be adjusted to rates in\n!driver...\n\n    pcp=pcp+pcpc   ! assumes pcpc=0 for resolved convection...\n\n  end subroutine READFORC_RUC\n\n\n\n\n  subroutine READSNOW_FORC(flnm,ix,jx,weasd,snodep)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    real,             dimension(ix,jx), intent(out) :: weasd\n    real,             dimension(ix,jx), intent(out) :: snodep\n    real, dimension(ix,jx) :: tmp\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid,i,j\n\n    ! Open the NetCDF file.\n\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READSNOW Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READSNOW_FORC() - Problem opening netcdf file\")\n    endif\n\n    call get_2d_netcdf(\"WEASD\",  ncid, tmp,   units, ix, jx, .FALSE., ierr)\n    if (ierr /= NF90_NOERR) then\n         call get_2d_netcdf(\"SNOW\",  ncid, tmp,   units, ix, jx, .FALSE., ierr)\n         if (ierr == 0) then\n            units = \"mm\"\n            print *, \"read WEASD from wrfoutput ...... \"\n            weasd = tmp * 1.E-3\n         endif\n    else\n         weasd = tmp\n         if (trim(units) == \"m\") then\n            ! No conversion necessary\n         else if (trim(units) == \"mm\") then\n            ! convert WEASD from mm to m\n            weasd = weasd * 1.E-3\n         endif\n    endif\n\n    if (ierr /= NF90_NOERR) then\n       print *, \"!!!!! NO WEASD present in input file...initialize to 0.\"\n    endif\n\n    call get_2d_netcdf(\"SNODEP\",     ncid, tmp,   units, ix, jx, .FALSE., ierr)\n    if (ierr /= NF90_NOERR) then\n       ! Quick assumption regarding snow depth.\n       call get_2d_netcdf(\"SNOWH\",     ncid, tmp,   units, ix, jx, .FALSE., ierr)\n       if(ierr .eq. 0) then\n            print *, \"read snow depth from wrfoutput ... \"\n            snodep = tmp\n       endif\n    else\n       snodep = tmp\n    endif\n\n    if (ierr /= NF90_NOERR) then\n       ! Quick assumption regarding snow depth.\n!yw       snodep = weasd * 10.\n       where(snodep .lt. weasd) snodep = weasd*10  !set lower bound to correct bi-lin interp err...\n    endif\n\n!DJG check for erroneous neg WEASD or SNOWD due to offline interpolation...\n       where(snodep .lt. 0) snodep = 0\n       where(weasd .lt. 0) weasd = 0\n    ierr = nf90_close(ncid)\n\n  end subroutine READSNOW_FORC\n\n    subroutine get2d_hrldas(inflnm,ix,jx,nsoil,smc,stc,sh2ox,cmc,t1,weasd,snodep)\n          implicit none\n          integer :: iret,varid,ncid,ix,jx,nsoil,ierr\n          real,dimension(ix,jx):: weasd,snodep,cmc,t1\n          real,dimension(ix,jx,nsoil):: smc,stc,sh2ox\n          character(len=*), intent(in) :: inflnm\n          character(len=256)::   units\n          iret = nf90_open(trim(inflnm), NF90_NOWRITE, ncid)\n          if(iret .ne. 0 )then\n              write(6,*) \"Error: failed to open file :\",trim(inflnm)\n             call hydro_stop(\"In get2d_hrldas() - failed to open file\")\n          endif\n\n          call get2d_hrldas_real(\"CMC\",     ncid, cmc,     ix, jx)\n          call get2d_hrldas_real(\"TSKIN\",   ncid, t1,      ix, jx)\n          call get2d_hrldas_real(\"SWE\",      ncid, weasd,   ix, jx)\n          call get2d_hrldas_real(\"SNODEP\",     ncid, snodep,   ix, jx)\n\n    call get2d_hrldas_real(\"SOIL_T_1\",    ncid, stc(:,:,1),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_T_2\",    ncid, stc(:,:,2),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_T_3\",    ncid, stc(:,:,3),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_T_4\",    ncid, stc(:,:,4),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_T_5\",    ncid, stc(:,:,5),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_T_6\",    ncid, stc(:,:,6),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_T_7\",    ncid, stc(:,:,7),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_T_8\",    ncid, stc(:,:,8),  ix, jx)\n\n    call get2d_hrldas_real(\"SOIL_M_1\",    ncid, SMC(:,:,1),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_M_2\",    ncid, SMC(:,:,2),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_M_3\",    ncid, SMC(:,:,3),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_M_4\",    ncid, SMC(:,:,4),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_M_5\",    ncid, SMC(:,:,5),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_M_6\",    ncid, SMC(:,:,6),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_M_7\",    ncid, SMC(:,:,7),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_M_8\",    ncid, SMC(:,:,8),  ix, jx)\n\n    call get2d_hrldas_real(\"SOIL_W_1\",    ncid, SH2OX(:,:,1),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_W_2\",    ncid, SH2OX(:,:,2),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_W_3\",    ncid, SH2OX(:,:,3),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_W_4\",    ncid, SH2OX(:,:,4),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_W_5\",    ncid, SH2OX(:,:,5),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_W_6\",    ncid, SH2OX(:,:,6),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_W_7\",    ncid, SH2OX(:,:,7),  ix, jx)\n    call get2d_hrldas_real(\"SOIL_W_8\",    ncid, SH2OX(:,:,8),  ix, jx)\n\n          iret = nf90_close(ncid)\n      end subroutine get2d_hrldas\n\n      subroutine get2d_hrldas_real(var_name,ncid,out_buff,ix,jx)\n          implicit none\n          integer ::iret,varid,ncid,ix,jx\n          real out_buff(ix,jx)\n          character(len=*), intent(in) :: var_name\n          iret = nf90_inq_varid(ncid,trim(var_name),  varid)\n          iret = nf90_get_var(ncid, varid, out_buff)\n      end subroutine get2d_hrldas_real\n\n    subroutine read_stage4(flnm,IX,JX,pcp)\n        integer IX,JX,ierr,ncid,i,j\n        real pcp(IX,JX),buf(ix,jx)\n        character(len=*),  intent(in)  :: flnm\n        character(len=256) :: units\n\n        ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n\n        if(ierr .ne. 0) then\n            call hydro_stop(\"In read_stage4() - failed to open stage4 file.\")\n        endif\n\n        call get_2d_netcdf(\"RAINRATE\",ncid, buf,   units, ix, jx, .TRUE., ierr)\n        ierr = nf90_close(ncid)\n        do j = 1, jx\n        do i = 1, ix\n            if(buf(i,j) .lt. 0) then\n                 buf(i,j) = pcp(i,j)\n            end if\n        end do\n        end do\n        pcp = buf\n    END subroutine read_stage4\n\n\n\n\n subroutine read_hydro_forcing_seq( &\n       indir,olddate,hgrid, &\n       ix,jx,forc_typ,snow_assim,  &\n       forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n       forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n       T2,q2x,u,v,pres,xlong,short,prcp1,&\n       lai,snowbl,fpar,snodep,dt,k,prcp_old)\n! This subrouting is going to read different forcing.\n   implicit none\n   ! in variable\n   character(len=*) :: olddate,hgrid,indir\n   character(len=256) :: filename\n   integer :: ix,jx,forc_typ,k,snow_assim  ! k is time loop\n   character(len=256), intent(in)  :: forcing_name_T\n   character(len=256), intent(in)  :: forcing_name_Q\n   character(len=256), intent(in)  :: forcing_name_U\n   character(len=256), intent(in)  :: forcing_name_V\n   character(len=256), intent(in)  :: forcing_name_P\n   character(len=256), intent(in)  :: forcing_name_LW\n   character(len=256), intent(in)  :: forcing_name_SW\n   character(len=256), intent(in)  :: forcing_name_PR\n   character(len=256), intent(in)  :: forcing_name_SN\n   character(len=256), intent(in)  :: forcing_name_LF\n   real,dimension(ix,jx):: T2,q2x,u,v,pres,xlong,short,prcp1,&\n          prcpnew,weasd,snodep,prcp0,prcp2,prcp_old\n   real ::  dt, wrf_dt\n   ! tmp variable\n   character(len=256) :: inflnm, inflnm2, product\n   integer  :: i,j,mmflag,ierr_flg\n   real,dimension(ix,jx):: lai,snowbl,fpar\n   character(len=4) nwxst_t\n   logical :: fexist\n\n        inflnm = trim(indir)//\"/\"//&\n             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n             \".LDASIN_DOMAIN\"//hgrid\n!!!DJG... Call READFORC_(variable) Subroutine for forcing data...\n!!!DJG HRLDAS Format Forcing with hour format filename (NOTE: precip must be in mm/s!!!)\n   if(FORC_TYP.eq.1) then\n!!Create forcing data filename...\n        call geth_newdate(out_date,olddate,nint(dt))\n        inflnm = trim(indir)//\"/\"//&\n             out_date(1:4)//out_date(6:7)//out_date(9:10)//out_date(12:13)//&\n             \".LDASIN_DOMAIN\"//hgrid\n\n        inquire (file=trim(inflnm), exist=fexist)\n        if ( .not. fexist ) then\n           print*, \"no forcing data found\", inflnm\n           call hydro_stop(\"In read_hydro_forcing_seq\")\n        endif\n\n        CALL READFORC_HRLDAS(inflnm,IX,JX,OLDDATE, &\n             forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n             forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n             T2,Q2X,U,V,   &\n             PRES,XLONG,SHORT,PRCP1,LAI,snowbl,FPAR)\n   end if\n\n\n\n\n!!!DJG HRLDAS Forcing with minute format filename (NOTE: precip must be in mm/s!!!)\n   if(FORC_TYP.eq.2) then\n!!Create forcing data filename...\n        call geth_newdate(out_date,olddate,nint(dt))\n        inflnm = trim(indir)//\"/\"//&\n             out_date(1:4)//out_date(6:7)//out_date(9:10)//out_date(12:13)//&\n             out_date(15:16)//\".LDASIN_DOMAIN\"//hgrid\n        inquire (file=trim(inflnm), exist=fexist)\n        if ( .not. fexist ) then\n           print*, \"no forcing data found\", inflnm\n           call hydro_stop(\"In read_hydro_forcing_seq() - no forcing data found\")\n        endif\n        CALL READFORC_HRLDAS(inflnm,IX,JX,OLDDATE, &\n             forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n             forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n             T2,Q2X,U,V,   &\n             PRES,XLONG,SHORT,PRCP1,LAI,snowbl,FPAR)\n   end if\n\n\n\n\n\n!!!DJG WRF Output File Direct Ingest Forcing...\n     if(FORC_TYP.eq.3) then\n!!Create forcing data filename...\n        inflnm = trim(indir)//\"/\"//&\n             \"wrfout_d0\"//hgrid//\"_\"//&\n             olddate(1:4)//\"-\"//olddate(6:7)//\"-\"//olddate(9:10)//&\n             \"_\"//olddate(12:13)//\":00:00\"\n\n        inquire (file=trim(inflnm), exist=fexist)\n        if ( .not. fexist ) then\n           print*, \"no forcing data found\", inflnm\n           call hydro_stop(\"In read_hydro_forcing_seq() - no forcing data found\")\n        endif\n\n        do i_forcing = 1, int(24*3600/dt)\n           wrf_dt = i_forcing*dt\n           call geth_newdate(out_date,olddate,nint(wrf_dt))\n           inflnm2 = trim(indir)//\"/\"//&\n             \"wrfout_d0\"//hgrid//\"_\"//&\n             out_date(1:4)//\"-\"//out_date(6:7)//\"-\"//out_date(9:10)//&\n             \"_\"//out_date(12:13)//\":00:00\"\n           inquire (file=trim(inflnm2), exist=fexist)\n           if (fexist ) goto 991\n        end do\n991     continue\n\n        if(.not. fexist) then\n           write(6,*) \"FATAL ERROR: could not find file \",trim(inflnm2)\n           call hydro_stop(\"In read_hydro_forcing_seq() - could not find file \")\n        endif\n#ifdef HYDRO_D\n           print*, \"read WRF forcing data: \", trim(inflnm)\n           print*, \"read WRF forcing data: \", trim(inflnm2)\n#endif\n       CALL READFORC_WRF(inflnm2,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n          PRES,XLONG,SHORT,PRCPnew,lai,fpar)\n       CALL READFORC_WRF(inflnm,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n          PRES,XLONG,SHORT,prcp0,lai,fpar)\n        PRCP1=(PRCPnew-prcp0)/wrf_dt   !Adjustment to convert accum to rate...(mm/s)\n\n     end if\n\n!!!DJG CONSTant, idealized forcing...\n     if(FORC_TYP.eq.4) then\n! Impose a fixed diurnal cycle...\n! assumes model timestep is 1 hr\n! assumes K=1 is 12z (Ks or ~ sunrise)\n! First Precip...\n       IF (K.EQ.2) THEN\n       PRCP1 =25.4/3600.0      !units mm/s  (Simulates 1\"/hr for first time step...)\n!       PRCP1 =0./3600.0      !units mm/s  (Simulates <1\"/hr for first 10 hours...)\n       ELSEIF (K.GT.1) THEN\n!        PRCP1 =0./3600.0      !units mm/s\n!       ELSE\n         PRCP1 = 0.\n       END IF\n!       PRCP1 = 0.\n!       PRCP1 =10./3600.0      !units mm/s\n! Other Met. Vars...\n       T2=290.0 + 3.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n       Q2X = 0.01\n       U = 1.0\n       V = 1.0\n       PRES = 100000.0\n       XLONG=400.0 + 25.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n       SHORT=450.0 + 450.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n\n!      print *, \"PCP\", PRCP1\n\n    end if\n\n!!!DJG  Idealized Met. w/ Specified Precip. Forcing Data...(Note: input precip units here are in 'mm/hr')\n!   This option uses hard-wired met forcing EXCEPT precipitation which is read in\n!   from a single, separate input file called 'YYYYMMDDHHMM.PRECIP_FORCING.nc'\n!\n    if(FORC_TYP.eq.5) then\n! Standard Met. Vars...\n       T2=290.0 + 3.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n       Q2X = 0.01\n       U = 1.0\n       V = 1.0\n       PRES = 100000.0\n       XLONG=400.0 + 25.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n       SHORT=450.0 + 450.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n\n!Get specified precip....\n!!!VIP, dimensions of grid are currently hardwired in input subroutine!!!\n!       product = \"trmm\"\n!       inflnm = trim(indir)//\"/\"//\"sat_domain1.nc\"\n!!Create forcing data filename...\n        inflnm = trim(indir)//\"/\"//&\n                olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n                olddate(15:16)//\".PRECIP_FORCING.nc\"\n        inquire (file=trim(inflnm), exist=fexist)\n        if ( .not. fexist ) then\n           print*, \"no specified precipitation data found\", inflnm\n           call hydro_stop(\"In read_hydro_forcing_seq() - no specified precipitation data found\")\n        endif\n\n       PRCP1 = 0.\n       PRCP_old = PRCP1\n\n#ifdef HYDRO_D\n      print *, \"Opening supplemental precipitation forcing file...\",inflnm\n#endif\n       CALL READFORC_MDV(inflnm,IX,JX,   &\n          PRCP2,mmflag,ierr_flg)\n\n!If radar or spec. data is ok use if not, skip to original NARR data...\n      IF (ierr_flg.eq.0) then   ! use spec. precip\n!Convert units if necessary\n        IF (mmflag.eq.0) then    !Convert pcp grid to units of mm/s...\n           PRCP1=PRCP2/DT     !convert from mm to mm/s\n#ifdef HYDRO_D\n           print*, \"Supplemental pcp is accumulated pcp/dt. \"\n#endif\n        else\n           PRCP1=PRCP2   !assumes PRCP2 is in mm/s\n#ifdef HYDRO_D\n           print*, \"Supplemental pcp is rate. \"\n#endif\n        END IF  ! Endif mmflag\n      ELSE   ! either stop or default to original forcing data...\n#ifdef HYDRO_D\n        print *,\"Current RADAR precip data not found !!! Using previous available file...\"\n#endif\n        PRCP1 = PRCP_old\n      END IF  ! Endif ierr_flg\n\n! Loop through data to screen for plausible values\n       do i=1,ix\n         do j=1,jx\n           if (PRCP1(i,j).lt.0.) PRCP1(i,j)= PRCP_old(i,j)\n           if (PRCP1(i,j).gt.0.138889) PRCP1(i,j)=0.138889  !set max pcp intens = 500 mm/h\n         end do\n       end do\n\n    end if\n\n\n\n\n\n!!!DJG HRLDAS Forcing with hourly format filename with specified precipitation forcing...\n!   This option uses HRLDAS-formatted met forcing EXCEPT precipitation which is read in\n!   from a single, separate input file called 'YYYYMMDDHHMM.PRECIP_FORCING.nc'\n\n   if(FORC_TYP.eq.6) then\n\n!!Create forcing data filename...\n        inflnm = trim(indir)//\"/\"//&\n             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n             \".LDASIN_DOMAIN\"//hgrid\n\n        inquire (file=trim(inflnm), exist=fexist)\n\n        if ( .not. fexist ) then\n          do i_forcing = 1, nint(12*3600/dt)\n           call geth_newdate(out_date,olddate,nint(i_forcing*dt))\n           inflnm = trim(indir)//\"/\"//&\n              olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n              olddate(15:16)//\".LDASIN_DOMAIN\"//hgrid\n           inquire (file=trim(inflnm), exist=fexist)\n            if(fexist) goto 201\n          end do\n201       continue\n        endif\n\n\n        if ( .not. fexist ) then\n#ifdef HYDRO_D\n           print*, \"no ATM forcing data found at this time\", inflnm\n#endif\n        else\n#ifdef HYDRO_D\n           print*, \"reading forcing data at this time\", inflnm\n#endif\n\n           CALL READFORC_HRLDAS(inflnm,IX,JX,OLDDATE,&\n                forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n                forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n                T2,Q2X,U,V,   &\n                PRES,XLONG,SHORT,PRCP1,LAI,snowbl,FPAR)\n           PRCP_old = PRCP1  ! This assigns new precip to last precip as a fallback for missing data...\n        endif\n\n\n!Get specified precip....\n!!!VIP, dimensions of grid are currently hardwired in input subroutine!!!\n!!Create forcing data filename...\n        inflnm = trim(indir)//\"/\"//&\n                 olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n                 olddate(15:16)//\".PRECIP_FORCING.nc\"\n        inquire (file=trim(inflnm), exist=fexist)\n#ifdef HYDRO_D\n        if(fexist) then\n            print*, \"using specified pcp forcing: \",trim(inflnm)\n        else\n            print*, \"no specified pcp forcing: \",trim(inflnm)\n        endif\n#endif\n        if ( .not. fexist ) then\n           prcp1 = PRCP_old ! for missing pcp data use analysis/model input\n        else\n           CALL READFORC_MDV(inflnm,IX,JX,   &\n              PRCP2,mmflag,ierr_flg)\n!If radar or spec. data is ok use if not, skip to original NARR data...\n           if(ierr_flg .ne. 0) then\n#ifdef HYDRO_D\n               print*, \"WARNING: pcp reading problem: \", trim(inflnm)\n#endif\n               PRCP1=PRCP_old\n           else\n               PRCP1=PRCP2   !assumes PRCP2 is in mm/s\n               IF (mmflag.eq.0) then    !Convert pcp grid to units of mm/s...\n                PRCP1=PRCP2/DT     !convert from mm to mm/s\n               END IF  ! Endif mmflag\n#ifdef HYDRO_D\n               print*, \"replace pcp successfully! \",trim(inflnm)\n#endif\n           endif\n        endif\n\n\n! Loop through data to screen for plausible values\n       where(PRCP1 .lt. 0) PRCP1=PRCP_old\n       where(PRCP1 .gt. 10 ) PRCP1= PRCP_old\n       do i=1,ix\n         do j=1,jx\n           if (PRCP1(i,j).lt.0.) PRCP1(i,j)=0.0\n           if (PRCP1(i,j).gt.0.138889) PRCP1(i,j)=0.138889  !set max pcp intens = 500 mm/h\n         end do\n       end do\n\n   end if\n\n\n!!!! FORC_TYP 7: uses WRF forcing data plus additional pcp forcing.\n\n   if(FORC_TYP.eq.7) then\n\n!!Create forcing data filename...\n        inflnm = trim(indir)//\"/\"//&\n             \"wrfout_d0\"//hgrid//\"_\"//&\n             olddate(1:4)//\"-\"//olddate(6:7)//\"-\"//olddate(9:10)//&\n             \"_\"//olddate(12:13)//\":00:00\"\n\n        inquire (file=trim(inflnm), exist=fexist)\n\n\n        if ( .not. fexist ) then\n#ifdef HYDRO_D\n           print*, \"no forcing data found\", inflnm\n#endif\n        else\n           do i_forcing = 1, int(24*3600/dt)\n              wrf_dt = i_forcing*dt\n              call geth_newdate(out_date,olddate,nint(wrf_dt))\n              inflnm2 = trim(indir)//\"/\"//&\n                \"wrfout_d0\"//hgrid//\"_\"//&\n                out_date(1:4)//\"-\"//out_date(6:7)//\"-\"//out_date(9:10)//&\n                \"_\"//out_date(12:13)//\":00:00\"\n              inquire (file=trim(inflnm2), exist=fexist)\n              if (fexist ) goto 992\n           end do\n992        continue\n\n#ifdef HYDRO_D\n           print*, \"read WRF forcing data: \", trim(inflnm)\n           print*, \"read WRF forcing data: \", trim(inflnm2)\n#endif\n           CALL READFORC_WRF(inflnm2,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n                   PRES,XLONG,SHORT,PRCPnew,lai,fpar)\n           CALL READFORC_WRF(inflnm,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n                   PRES,XLONG,SHORT,prcp0,lai,fpar)\n           PRCP1=(PRCPnew-prcp0)/wrf_dt   !Adjustment to convert accum to rate...(mm/s)\n           PRCP_old = PRCP1\n        endif\n\n!Get specified precip....\n!!!VIP, dimensions of grid are currently hardwired in input subroutine!!!\n!!Create forcing data filename...\n        inflnm = trim(indir)//\"/\"//&\n                 olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n                 olddate(15:16)//\".PRECIP_FORCING.nc\"\n        inquire (file=trim(inflnm), exist=fexist)\n#ifdef HYDRO_D\n        if(fexist) then\n            print*, \"using specified pcp forcing: \",trim(inflnm)\n        else\n            print*, \"no specified pcp forcing: \",trim(inflnm)\n        endif\n#endif\n        if ( .not. fexist ) then\n           prcp1 = PRCP_old ! for missing pcp data use analysis/model input\n        else\n           CALL READFORC_MDV(inflnm,IX,JX,   &\n              PRCP2,mmflag,ierr_flg)\n!If radar or spec. data is ok use if not, skip to original NARR data...\n           if(ierr_flg .ne. 0) then\n#ifdef HYDRO_D\n               print*, \"WARNING: pcp reading problem: \", trim(inflnm)\n#endif\n               PRCP1=PRCP_old\n           else\n               PRCP1=PRCP2   !assumes PRCP2 is in mm/s\n               IF (mmflag.eq.0) then    !Convert pcp grid to units of mm/s...\n#ifdef HYDRO_D\n                 write(6,*) \"using supplemental pcp time interval \", DT\n#endif\n                PRCP1=PRCP2/DT     !convert from mm to mm/s\n               else\n#ifdef HYDRO_D\n                 write(6,*) \"using supplemental pcp rates \"\n#endif\n               END IF  ! Endif mmflag\n#ifdef HYDRO_D\n               print*, \"replace pcp successfully! \",trim(inflnm)\n#endif\n           endif\n        endif\n\n\n! Loop through data to screen for plausible values\n       where(PRCP1 .lt. 0) PRCP1=PRCP_old\n       where(PRCP1 .gt. 10 ) PRCP1= PRCP_old ! set maximum to be 500 mm/h\n       where(PRCP1 .gt. 0.138889) PRCP1= 0.138889 ! set maximum to be 500 mm/h\n   end if\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!The other forcing data types below here are obsolete and left for reference...\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n!!!DJG HRLDAS Single Input with Multiple Input Times File Forcing...\n!     if(FORC_TYP.eq.6) then\n!!Create forcing data filename...\n!     if (len_trim(range) == 0) then\n!      inflnm = trim(indir)//\"/\"//&\n!             startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n!             olddate(15:16)//\".LDASIN_DOMAIN\"//hgrid//\"_multiple\"\n!!        \"MET_LIS_CRO_2D_SANTEE_LU_1KM.\"//&\n!!        \".156hrfcst.radar\"\n!     else\n!     endif\n!     CALL READFORC_HRLDAS_mult(inflnm,IX,JX,OLDDATE,T2,Q2X,U,   &\n!          PRES,XLONG,SHORT,PRCP1,K)\n!\n!!       IF (K.GT.0.AND.K.LT.10) THEN\n!!         PRCP1 = 10.0/3600.0            ! units mm/s\n!!          PRCP1 = 0.254/3600.0\n!!       ELSE\n!!         PRCP1 = 0.\n!!       END IF\n!      endif\n\n\n\n!!!!!DJG  NARR Met. w/ NARR Precip. Forcing Data...\n!! Assumes standard 3-hrly NARR data has been resampled to NDHMS grid...\n!! Assumes one 3hrly time-step per forcing data file\n!! Input precip units here are in 'mm' accumulated over 3 hrs...\n!    if(FORC_TYP.eq.7) then  !NARR Met. w/ NARR Precip.\n!!!Create forcing data filename...\n!      if (len_trim(range) == 0) then\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!             \".LDASIN_DOMAIN\"//hgrid\n!      else\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!             \".LDASIN_DOMAIN\"//hgrid//\".\"//trim(range)\n!      endif\n!      CALL READFORC_HRLDAS(inflnm,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n!          PRES,XLONG,SHORT,PRCP1,LAI,FPAR)\n!      PRCP1=PRCP1/(3.0*3600.0)  ! convert from 3hr accum to mm/s which is what NDHMS expects\n!    end if  !NARR Met. w/ NARR Precip.\n\n\n\n\n\n\n!!!!DJG  NARR Met. w/ Specified Precip. Forcing Data...\n!    if(FORC_TYP.eq.8) then !NARR Met. w/ Specified Precip.\n!\n!!Check to make sure if Noah time step is 3 hrs as is NARR...\n!\n!        PRCP_old = PRCP1\n!\n!     if(K.eq.1.OR.(MOD((K-1)*INT(DT),10800)).eq.0) then   !if/then 3 hr check\n!!!Create forcing data filename...\n!      if (len_trim(range) == 0) then\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!             \".LDASIN_DOMAIN\"//hgrid\n!!        startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n!!        \".48hrfcst.ncf\"\n!      else\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!             \".LDASIN_DOMAIN\"//hgrid//\".\"//trim(range)\n!      endif\n!      CALL READFORC_HRLDAS(inflnm,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n!          PRES,XLONG,SHORT,PRCP1,LAI,FPAR)\n!!       PRCP1=PRCP1/(3.0*3600.0)     !NARR 3hrly precip product in mm\n!       PRCP1=PRCP1     !NAM model data in mm/s\n!    end if    !3 hr check\n!\n!\n!!Get spec. precip....\n!! NAM Remote sensing...\n!!!!VIP, dimensions of grid are currently hardwired in input subroutine!!!\n!!       product = \"trmm\"\n!!       inflnm = trim(indir)//\"/\"//\"sat_domain1.nc\"\n!!!       inflnm = trim(indir)//\"/\"//\"sat_domain2.nc\"\n!!       PRCP1 = 0.\n!!       CALL READFORC_NAMPCP(inflnm,IX,JX,   &\n!!          PRCP2,K,product)\n!!       ierr_flg = 0\n!!       mmflag = 0\n!!!Convert pcp grid to units of mm/s...\n!!       PRCP1=PRCP1/(3.0*3600.0)     !3hrly precip product\n!\n!!Read from filelist (NAME HE...,others)...\n!!        if (K.eq.1) then\n!!          open(unit=93,file=\"filelist.txt\",form=\"formatted\",status=\"old\")\n!!        end if\n!!        read (93,*) filename\n!!        inflnm = trim(indir)//\"/\"//trim(filename)\n!!\n!!\n!!Front Range MDV Radar...\n!\n!!         inflnm = \"/ptmp/weiyu/rt_2008/radar_obs/\"//&\n!!             inflnm = \"/d3/hydrolab/HRLDAS_forcing/FRNG_research/20080809/\"//&\n!!              olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!!              olddate(15:16)//\"_radar.nc\"\n!!              olddate(15:16)//\"_chill.nc\"\n!\n!!        inflnm = \"/d2/hydrolab/HRLDAS/forcing/FRNG/Big_Thomp_04/\"//&\n!!       inflnm = \"/d2/hydrolab/HRLDAS/forcing/FRNG/RT_2008/radar_obs/\"//&\n!!             inflnm = \"/d3/hydrolab/HRLDAS_forcing/FRNG_research/20080809/\"//&\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//\"_\"//olddate(12:13)//&\n!!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!!             olddate(15:16)//\"00_Pcp60min.nc\"\n!!             olddate(15:16)//\"00_Pcp30min.nc\"\n!!             olddate(15:16)//\"00_30min.nc\"\n!             olddate(15:16)//\"00_Pcp5min.nc\"\n!!              olddate(15:16)//\"_chill.nc\"\n!\n!!         inflnm = \"/d2/hydrolab/HRLDAS/forcing/COWS/\"//&\n!!             olddate(1:4)//olddate(6:7)//olddate(9:10)//\"_\"//olddate(12:13)//&\n!!             olddate(15:16)//\"00_Pcp5min.nc\"\n!!              olddate(15:16)//\"00_5.nc\"\n!\n!!         inflnm = \"\"     ! use this for NAM frxst runs with 30 min time-step\n!!\n!\n!\n!!        if (K.le.6) then   ! use for 30min nowcast...\n!!          if (K.eq.1) then\n!!             open(unit=94,file=\"start_file.txt\",form=\"formatted\",status=\"replace\")\n!!!             inflnm2 = \"/d2/hydrolab/HRLDAS/forcing/FRNG/RT_2008/radar_obs/\"//&\n!!             inflnm2 = \"/d3/hydrolab/HRLDAS_forcing/FRNG_research/\"//&\n!!             olddate(1:4)//olddate(6:7)//olddate(9:10)//\"_\"//olddate(12:13)//&\n!!             olddate(15:16)//\"00_\"\n!!             close(94)\n!!             nwxst_t = \"5\"! calc minutes from timestep and convert to char...\n!!             inflnm = trim(inflnm2)//trim(nwxst_t)//\".nc\"\n!!          end if\n!!          if (K.eq.2) then\n!!             nwxst_t = \"10\" ! calc minutes from timestep and convert to char...\n!!             open(unit=94,file=\"start_file.txt\",form=\"formatted\",status=\"old\")\n!!             read (94,*) inflnm2\n!!             close(94)\n!!             inflnm = trim(inflnm2)//trim(nwxst_t)//\".nc\"\n!!          end if\n!!          if (K.eq.3) then\n!!             nwxst_t = \"15\" ! calc minutes from timestep and convert to char...\n!!             open(unit=94,file=\"start_file.txt\",form=\"formatted\",status=\"old\")\n!!             read (94,*) inflnm\n!!             close(94)\n!!             inflnm = trim(inflnm2)//trim(nwxst_t)//\".nc\"\n!!          end if\n!!          if (K.eq.4) then\n!!             nwxst_t = \"20\" ! calc minutes from timestep and convert to char...\n!!             open(unit=94,file=\"start_file.txt\",form=\"formatted\",status=\"old\")\n!!             read (94,*) inflnm\n!!             close(94)\n!!             inflnm = trim(inflnm2)//trim(nwxst_t)//\".nc\"\n!!          end if\n!!          if (K.eq.5) then\n!!             nwxst_t = \"25\" ! calc minutes from timestep and convert to char...\n!!             open(unit=94,file=\"start_file.txt\",form=\"formatted\",status=\"old\")\n!!             read (94,*) inflnm\n!!             close(94)\n!!             inflnm = trim(inflnm2)//trim(nwxst_t)//\".nc\"\n!!          end if\n!!          if (K.eq.6) then\n!!             nwxst_t = \"30\" ! calc minutes from timestep and convert to char...\n!!             open(unit=94,file=\"start_file.txt\",form=\"formatted\",status=\"old\")\n!!             read (94,*) inflnm\n!!             close(94)\n!!             inflnm = trim(inflnm2)//trim(nwxst_t)//\".nc\"\n!!          end if\n!!        else\n!!          inflnm = \"\"     ! use this for NAM frxst runs with 30 min time-step\n!!        end if\n!\n!!             olddate(1:4)//olddate(6:7)//olddate(9:10)//\"_\"//olddate(12:13)//&\n!!             olddate(15:16)//\"00_Pcp30minMerge.nc\"\n!\n!       CALL READFORC_MDV(inflnm,IX,JX,   &\n!          PRCP2,mmflag,ierr_flg)\n!\n!!If radar or spec. data is ok use if not, skip to original NARR data...\n!      IF (ierr_flg.eq.0) then   ! use spec. precip\n!         PRCP1=PRCP2   !assumes PRCP2 is in mm/s\n!!Convert units if necessary\n!        IF (mmflag.eq.0) then    !Convert pcp grid to units of mm/s...\n!          PRCP1=PRCP2/DT     !convert from mm to mm/s\n!        END IF  ! Endif mmflag\n!      ELSE   ! either stop or default to original forcing data...\n!        PRCP1 = PRCP_old\n!      END IF  ! Endif ierr_flg\n!\n!! Loop through data to screen for plausible values\n!       do i=1,ix\n!         do j=1,jx\n!           if (PRCP1(i,j).lt.0.) PRCP1(i,j)=0.0\n!           if (PRCP1(i,j).gt.0.0555) PRCP1(i,j)=0.0555  !set max pcp intens = 200 mm/h\n!!          PRCP1(i,j) = 0.\n!!          PRCP1(i,j) = 0.02   !override w/ const. precip for gw testing only...\n!         end do\n!       end do\n!\n!!        if (K.eq.1) then  ! quick dump for site specific precip...\n!          open(unit=94,file=\"Christman_accumpcp.txt\",form=\"formatted\",status=\"new\")\n!        end if\n!\n!\n!    end if  !NARR Met. w/ Specified Precip.\n\n\n\n\n\n!!!!DJG  NLDAS Met. w/ NLDAS Precip. Forcing Data...\n!! Assumes standard hrly NLDAS data has been resampled to NDHMS grid...\n!! Assumes one 1-hrly time-step per forcing data file\n!! Input precip units here are in 'mm' accumulated over 1 hr...\n!    if(FORC_TYP.eq.9) then  !NLDAS Met. w/ NLDAS Precip.\n!!!Create forcing data filename...\n!      if (len_trim(range) == 0) then\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!!Use this for minute forcing...             olddate(15:16)//\".LDASIN_DOMAIN\"//hgrid\n!             \".LDASIN_DOMAIN\"//hgrid\n!      else\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!             \".LDASIN_DOMAIN\"//hgrid//\".\"//trim(range)\n!      endif\n!      CALL READFORC_HRLDAS(inflnm,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n!          PRES,XLONG,SHORT,PRCP1,LAI,FPAR)\n!      PRCP1=PRCP1/(1.0*3600.0)  ! convert hourly NLDAS hourly accum pcp to mm/s which is what NDHMS expects\n!    end if  !NLDAS Met. w/ NLDAS Precip.\n\n\n\n\n\n!!!!DJG  NARR Met. w/ DMIP Precip. & Temp. Forcing Data...\n!    if(FORC_TYP.eq.10) then  ! If/Then for DMIP forcing data...\n!!Check to make sure if Noah time step is 3 hrs as is NARR...\n!\n!     if(K.eq.1.OR.(MOD((K-1)*INT(DT),10800)).eq.0) then   !if/then 3 hr check\n!!!Create forcing data filename...\n!      if (len_trim(range) == 0) then\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!             \".LDASIN_DOMAIN\"//hgrid\n!!        startdate(1:4)//startdate(6:7)//startdate(9:10)//startdate(12:13)//&\n!!        \".48hrfcst.ncf\"\n!      else\n!        inflnm = trim(indir)//\"/\"//&\n!             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!             \".LDASIN_DOMAIN\"//hgrid//\".\"//trim(range)\n!      endif\n!      CALL READFORC_HRLDAS(inflnm,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n!          PRES,XLONG,SHORT,PRCP1,LAI,FPAR)\n!          PRCP1=PRCP1/(3.0*3600.0)  ! convert to mm/s which is what HRLDAS expects\n!    end if    !3 hr check\n!\n!!Get DMIP Precip...\n!!       inflnm = \"/d3/gochis/HRLDAS/forcing/DMIP_II/PRECIP_HRAP/precip_finished\"//\"/\"//&\n!       inflnm = \"/d2/hydrolab/HRLDAS/forcing/DMIP_II_AmerR/PRECIP_HRAP\"//\"/\"//&\n!           \"proj.xmrg\"//&\n!           olddate(6:7)//olddate(9:10)//olddate(1:4)//olddate(12:13)//&\n!           \"z.asc\"\n!        PRCP1 = 0.\n!        CALL READFORC_DMIP(inflnm,IX,JX,PRCP1)\n!          PRCP1 = PRCP1 / 100.0    ! Convert from native hundreths of mm to mm\n!!       IF (K.LT.34) THEN\n!!        PRCP1 = 5.0/3600.0            ! units mm/s\n!!!       ELSE\n!!!         PRCP1 = 0.\n!!       END IF\n!\n!!Get DMIP Temp...\n!!       inflnm = \"/d3/gochis/HRLDAS/forcing/DMIP_II/TEMP_HRAP/tair_finished\"//\"/\"//&\n!       inflnm = \"/d2/hydrolab/HRLDAS/forcing/DMIP_II_AmerR/TEMP_HRAP\"//\"/\"//&\n!           \"proj.tair\"//&\n!           olddate(6:7)//olddate(9:10)//olddate(1:4)//olddate(12:13)//&\n!           \"z.asc\"\n!        CALL READFORC_DMIP(inflnm,IX,JX,T2)\n!          T2 = (5./9.)*(T2-32.0) + 273.15         !Convert from deg F to deg K\n!\n!    end if  !End if for DMIP forcing data...\n!\n!\n!\n!! : add reading forcing precipitation data\n!!       ywinflnm = \"/ptmp/weiyu/hrldas/v2/st4\"//\"/\"//&\n!!            olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n!!            \".LDASIN_DOMAIN2\"\n!!       call read_stage4(ywinflnm,IX,JX,PRCP1)\n!!end yw\n!\n!\n!!!!DJG Check for snow data assimilation...\n\n   if (SNOW_ASSIM .eq. 1) then\n\n! Every 24 hours, update the snow field from analyses.\n     if(forc_typ .ne. 3 .or. forc_typ .ne. 6) then\n         if ( OLDDATE(12:13) == \"00\") then\n            CALL READSNOW_FORC(inflnm,IX,JX,WEASD,SNODEP)\n         endif\n     else\n        CALL READSNOW_FORC(inflnm,IX,JX,WEASD,SNODEP)\n     endif\n\n   end if\n\n#ifdef PRECIP_DOUBLE\n#ifdef HYDRO_D\n   print*,'PRECIP DOUBLE'\n#endif\n   PRCP1 = PRCP1 * 2.0\n#endif\n\n end subroutine read_hydro_forcing_seq\n\n\n#ifdef MPP_LAND\n    subroutine mpp_readland_hrldas(geo_static_flnm,&\n          ix,jx,land_cat,soil_cat,&\n          vegtyp,soltyp,terrain,latitude,longitude,&\n          global_nx,global_ny,SOLVEG_INITSWC)\n    implicit none\n    character(len=*),          intent(in)  :: geo_static_flnm\n    integer,                   intent(in)  :: ix, jx, land_cat, soil_cat, &\n              global_nx,global_ny,SOLVEG_INITSWC\n    integer, dimension(ix,jx), intent(out) :: vegtyp, soltyp\n    real,    dimension(ix,jx), intent(out) :: terrain, latitude, longitude\n    real, dimension(global_nx,global_ny) ::g_terrain, g_latitude, g_longitude\n    integer, dimension(global_nx,global_ny) :: g_vegtyp, g_soltyp\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid,varid\n    real, dimension(ix,jx) :: xdum\n    integer flag ! flag = 1 from wrfsi, flag =2 from WPS.\n     if(my_id.eq.IO_id) then\n        CALL READLAND_HRLDAS(geo_static_flnm,global_nx,  &\n               global_ny,LAND_CAT,SOIL_CAT,      &\n               g_VEGTYP,g_SOLTYP,g_TERRAIN,g_LATITUDE,g_LONGITUDE, SOLVEG_INITSWC)\n     end if\n  ! distribute the data to computation node.\n     call mpp_land_bcast_int1(LAND_CAT)\n     call mpp_land_bcast_int1(SOIL_CAT)\n     call decompose_data_int(g_VEGTYP,VEGTYP)\n     call decompose_data_int(g_SOLTYP,SOLTYP)\n     call decompose_data_real(g_TERRAIN,TERRAIN)\n     call decompose_data_real(g_LATITUDE,LATITUDE)\n     call decompose_data_real(g_LONGITUDE,LONGITUDE)\n      end subroutine mpp_readland_hrldas\n\n\n      subroutine MPP_READSNOW_FORC(flnm,ix,jx,OLDDATE,weasd,snodep,&\n                 global_nX, global_ny)\n        implicit none\n\n        character(len=*),                   intent(in)  :: flnm,OLDDATE\n        integer,  intent(in)  :: ix, global_nx,global_ny\n        integer,                            intent(in)  :: jx\n        real,             dimension(ix,jx), intent(out) :: weasd\n        real,             dimension(ix,jx), intent(out) :: snodep\n\n        real,dimension(global_nX, global_ny):: g_weasd, g_snodep\n\n        character(len=256) :: units\n        integer :: ierr\n        integer :: ncid,i,j\n\n        if(my_id .eq. IO_id) then\n          CALL READSNOW_FORC(trim(flnm),global_nX, global_ny,g_WEASD,g_SNODEP)\n       endif\n       call decompose_data_real(g_WEASD,WEASD)\n       call decompose_data_real(g_SNODEP,SNODEP)\n\n        end  subroutine MPP_READSNOW_FORC\n\n      subroutine MPP_DEEPGW_HRLDAS(ix,jx,in_SMCMAX,&\n                 global_nX, global_ny,nsoil,out_SMC,out_SH2OX)\n        implicit none\n\n        integer,  intent(in)  :: ix,global_nx,global_ny\n        integer,  intent(in)  :: jx,nsoil\n        real,             dimension(ix,jx), intent(in) :: in_smcmax\n        real,             dimension(ix,jx,nsoil), intent(out) :: out_smc,out_sh2ox\n\n        real,dimension(global_nX, global_ny,nsoil):: g_smc, g_sh2ox\n        real,dimension(global_nX, global_ny):: g_smcmax\n        integer   :: i,j,k\n\n\n          call write_IO_real(in_smcmax,g_smcmax)  ! get global grid of smcmax\n\n#ifdef HYDRO_D\n          write (*,*) \"In deep GW...\", nsoil\n#endif\n\n!loop to overwrite soils to saturation...\n        do i=1,global_nx\n         do j=1,global_ny\n            g_smc(i,j,1:NSOIL) = g_smcmax(i,j)\n            g_sh2ox(i,j,1:NSOIL) = g_smcmax(i,j)\n         end do\n        end do\n\n!decompose global grid to parallel tiles...\n       do k=1,nsoil\n        call decompose_data_real(g_smc(:,:,k),out_smc(:,:,k))\n        call decompose_data_real(g_sh2ox(:,:,k),out_sh2ox(:,:,k))\n       end do\n\n        end  subroutine MPP_DEEPGW_HRLDAS\n\n\n subroutine read_hydro_forcing_mpp( &\n       indir,olddate,hgrid, &\n       ix,jx,forc_typ,snow_assim,  &\n       forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n       forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n       T2,q2x,u,v,pres,xlong,short,prcp1,&\n       lai,snowbl,fpar,snodep,dt,k,prcp_old)\n! This subrouting is going to read different forcing.\n\n\n   implicit none\n   ! in variable\n   character(len=*) :: olddate,hgrid,indir\n   character(len=256) :: filename\n   integer :: ix,jx,forc_typ,k,snow_assim  ! k is time loop\n   character(len=256), intent(in)  :: forcing_name_T\n   character(len=256), intent(in)  :: forcing_name_Q\n   character(len=256), intent(in)  :: forcing_name_U\n   character(len=256), intent(in)  :: forcing_name_V\n   character(len=256), intent(in)  :: forcing_name_P\n   character(len=256), intent(in)  :: forcing_name_LW\n   character(len=256), intent(in)  :: forcing_name_SW\n   character(len=256), intent(in)  :: forcing_name_PR\n   character(len=256), intent(in)  :: forcing_name_SN\n   character(len=256), intent(in)  :: forcing_name_LF\n   real,dimension(ix,jx):: T2,q2x,u,v,pres,xlong,short,prcp1,&\n          prcpnew,lai,snowbl,fpar,snodep,prcp_old\n   real ::  dt\n   ! tmp variable\n   character(len=256) :: inflnm, product\n   integer  :: i,j,mmflag\n   real,dimension(global_nx,global_ny):: g_T2,g_Q2X,g_U,g_V,g_XLONG, &\n             g_SHORT,g_PRCP1,g_PRES,g_lai,g_snowbl,g_snodep,g_prcp_old, g_fpar\n   integer flag\n\n\n\n     call write_io_real(T2,g_T2)\n     call write_io_real(Q2X,g_Q2X)\n     call write_io_real(U,g_U)\n     call write_io_real(V,g_V)\n     call write_io_real(XLONG,g_XLONG)\n     call write_io_real(SHORT,g_SHORT)\n     call write_io_real(PRCP1,g_PRCP1)\n     call write_io_real(PRES,g_PRES)\n     call write_io_real(prcp_old,g_PRCP_old)\n\n     call write_io_real(lai,g_lai)\n     call write_io_real(snowbl,g_snowbl)\n     call write_io_real(fpar,g_fpar)\n     call write_io_real(snodep,g_snodep)\n\n\n\n   if(my_id .eq. IO_id) then\n      call read_hydro_forcing_seq( &\n        indir,olddate,hgrid,&\n        global_nx,global_ny,forc_typ,snow_assim,  &\n        forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n        forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n        g_T2,g_q2x,g_u,g_v,g_pres,g_xlong,g_short,g_prcp1,&\n        g_lai,g_snowbl,g_fpar,g_snodep,dt,k,g_prcp_old)\n#ifdef HYDRO_D\n     write(6,*) \"finish read forcing,olddate \",olddate\n#endif\n   end if\n\n     call decompose_data_real(g_T2,T2)\n     call decompose_data_real(g_Q2X,Q2X)\n     call decompose_data_real(g_U,U)\n     call decompose_data_real(g_V,V)\n     call decompose_data_real(g_XLONG,XLONG)\n     call decompose_data_real(g_SHORT,SHORT)\n     call decompose_data_real(g_PRCP1,PRCP1)\n     call decompose_data_real(g_prcp_old,prcp_old)\n     call decompose_data_real(g_PRES,PRES)\n\n     call decompose_data_real(g_lai,lai)\n     call decompose_data_real(g_fpar,fpar)\n     call decompose_data_real(g_snodep,snodep)\n\n   end subroutine read_hydro_forcing_mpp\n#endif\n\n  integer function nfeb_yw(year)\n    !\n    ! Compute the number of days in February for the given year.\n    !\n    implicit none\n    integer, intent(in) :: year ! Four-digit year\n\n    nfeb_yw = 28 ! By default, February has 28 days ...\n    if (mod(year,4).eq.0) then\n       nfeb_yw = 29  ! But every four years, it has 29 days ...\n       if (mod(year,100).eq.0) then\n          nfeb_yw = 28  ! Except every 100 years, when it has 28 days ...\n          if (mod(year,400).eq.0) then\n             nfeb_yw = 29  ! Except every 400 years, when it has 29 days ...\n             if (mod(year,3600).eq.0) then\n                nfeb_yw = 28  ! Except every 3600 years, when it has 28 days.\n             endif\n          endif\n       endif\n    endif\n  end function nfeb_yw\n\n  subroutine geth_newdate (ndate, odate, idt)\n    implicit none\n\n    !  From old date (\"YYYY-MM-DD HH:MM:SS.ffff\" or \"YYYYMMDDHHMMSSffff\") and\n    !  delta-time, compute the new date.\n\n    !  on entry     -  odate  -  the old hdate.\n    !                  idt    -  the change in time\n\n    !  on exit      -  ndate  -  the new hdate.\n\n    integer, intent(in)           :: idt\n    character (len=*), intent(out) :: ndate\n    character (len=*), intent(in)  :: odate\n\n    !  Local Variables\n\n    !  yrold    -  indicates the year associated with \"odate\"\n    !  moold    -  indicates the month associated with \"odate\"\n    !  dyold    -  indicates the day associated with \"odate\"\n    !  hrold    -  indicates the hour associated with \"odate\"\n    !  miold    -  indicates the minute associated with \"odate\"\n    !  scold    -  indicates the second associated with \"odate\"\n\n    !  yrnew    -  indicates the year associated with \"ndate\"\n    !  monew    -  indicates the month associated with \"ndate\"\n    !  dynew    -  indicates the day associated with \"ndate\"\n    !  hrnew    -  indicates the hour associated with \"ndate\"\n    !  minew    -  indicates the minute associated with \"ndate\"\n    !  scnew    -  indicates the second associated with \"ndate\"\n\n    !  mday     -  a list assigning the number of days in each month\n\n    !  i        -  loop counter\n    !  nday     -  the integer number of days represented by \"idt\"\n    !  nhour    -  the integer number of hours in \"idt\" after taking out\n    !              all the whole days\n    !  nmin     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days and whole hours.\n    !  nsec     -  the integer number of minutes in \"idt\" after taking out\n    !              all the whole days, whole hours, and whole minutes.\n\n    integer :: newlen, oldlen\n    integer :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\n    integer :: yrold, moold, dyold, hrold, miold, scold, frold\n    integer :: nday, nhour, nmin, nsec, nfrac, i, ifrc\n    logical :: opass\n    character (len=10) :: hfrc\n    character (len=1) :: sp\n    logical :: punct\n    integer :: yrstart, yrend, mostart, moend, dystart, dyend\n    integer :: hrstart, hrend, mistart, miend, scstart, scend, frstart\n    integer :: units\n    integer, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n!yw    integer nfeb_yw\n\n    ! Determine if odate is \"YYYY-MM-DD_HH ... \" or \"YYYYMMDDHH....\"\n    if (odate(5:5) == \"-\") then\n       punct = .TRUE.\n    else\n       punct = .FALSE.\n    endif\n\n    !  Break down old hdate into parts\n\n    hrold = 0\n    miold = 0\n    scold = 0\n    frold = 0\n    oldlen = LEN(odate)\n    if (punct) then\n       yrstart = 1\n       yrend = 4\n       mostart = 6\n       moend = 7\n       dystart = 9\n       dyend = 10\n       hrstart = 12\n       hrend = 13\n       mistart = 15\n       miend = 16\n       scstart = 18\n       scend = 19\n       frstart = 21\n       select case (oldlen)\n       case (10)\n          ! Days\n          units = 1\n       case (13)\n          ! Hours\n          units = 2\n       case (16)\n          ! Minutes\n          units = 3\n       case (19)\n          ! Seconds\n          units = 4\n       case (21)\n          ! Tenths\n          units = 5\n       case (22)\n          ! Hundredths\n          units = 6\n       case (23)\n          ! Thousandths\n          units = 7\n       case (24)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n          call hydro_stop(\"In geth_newdate() - error odd length\")\n       end select\n\n       if (oldlen.ge.11) then\n          sp = odate(11:11)\n       else\n          sp = ' '\n       end if\n\n    else\n\n       yrstart = 1\n       yrend = 4\n       mostart = 5\n       moend = 6\n       dystart = 7\n       dyend = 8\n       hrstart = 9\n       hrend = 10\n       mistart = 11\n       miend = 12\n       scstart = 13\n       scend = 14\n       frstart = 15\n\n       select case (oldlen)\n       case (8)\n          ! Days\n          units = 1\n       case (10)\n          ! Hours\n          units = 2\n       case (12)\n          ! Minutes\n          units = 3\n       case (14)\n          ! Seconds\n          units = 4\n       case (15)\n          ! Tenths\n          units = 5\n       case (16)\n          ! Hundredths\n          units = 6\n       case (17)\n          ! Thousandths\n          units = 7\n       case (18)\n          ! Ten thousandths\n          units = 8\n       case default\n          write(*,*) 'ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n           call hydro_stop(\"In geth_newdate() - error odd length\")\n       end select\n    endif\n\n    !  Use internal READ statements to convert the CHARACTER string\n    !  date into INTEGER components.\n\n    read(odate(yrstart:yrend),  '(i4)') yrold\n    read(odate(mostart:moend),  '(i2)') moold\n    read(odate(dystart:dyend), '(i2)') dyold\n    if (units.ge.2) then\n       read(odate(hrstart:hrend),'(i2)') hrold\n       if (units.ge.3) then\n          read(odate(mistart:miend),'(i2)') miold\n          if (units.ge.4) then\n             read(odate(scstart:scend),'(i2)') scold\n             if (units.ge.5) then\n                read(odate(frstart:oldlen),*) frold\n             end if\n          end if\n       end if\n    end if\n\n    !  Set the number of days in February for that year.\n\n    mday(2) = nfeb_yw(yrold)\n\n    !  Check that ODATE makes sense.\n\n    opass = .TRUE.\n\n    !  Check that the month of ODATE makes sense.\n\n    if ((moold.gt.12).or.(moold.lt.1)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the day of ODATE makes sense.\n\n    if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the hour of ODATE makes sense.\n\n    if ((hrold.gt.23).or.(hrold.lt.0)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the minute of ODATE makes sense.\n\n    if ((miold.gt.59).or.(miold.lt.0)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the second of ODATE makes sense.\n\n    if ((scold.gt.59).or.(scold.lt.0)) then\n#ifdef HYDRO_D\n       write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n#endif\n       opass = .FALSE.\n    end if\n\n    !  Check that the fractional part  of ODATE makes sense.\n    if (.not.opass) then\n       write(*,*) 'Crazy ODATE: ', odate(1:oldlen), oldlen\n       call hydro_stop(\"In geth_newdate\")\n    end if\n\n    !  Date Checks are completed.  Continue.\n\n\n    !  Compute the number of days, hours, minutes, and seconds in idt\n\n    if (units.ge.5) then !idt should be in fractions of seconds\n       ifrc = oldlen-(frstart)+1\n       ifrc = 10**ifrc\n       nday   = abs(idt)/(86400*ifrc)\n       nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n       nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n       nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n       nfrac = mod(abs(idt), ifrc)\n    else if (units.eq.4) then  !idt should be in seconds\n       ifrc = 1\n       nday   = abs(idt)/86400 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),86400)/3600\n       nmin   = mod(abs(idt),3600)/60\n       nsec   = mod(abs(idt),60)\n       nfrac  = 0\n    else if (units.eq.3) then !idt should be in minutes\n       ifrc = 1\n       nday   = abs(idt)/1440 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),1440)/60\n       nmin   = mod(abs(idt),60)\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.2) then !idt should be in hours\n       ifrc = 1\n       nday   = abs(idt)/24 ! integer number of days in delta-time\n       nhour  = mod(abs(idt),24)\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else if (units.eq.1) then !idt should be in days\n       ifrc = 1\n       nday   = abs(idt)    ! integer number of days in delta-time\n       nhour  = 0\n       nmin   = 0\n       nsec   = 0\n       nfrac  = 0\n    else\n       write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n            oldlen\n       write(*,*) '#'//odate(1:oldlen)//'#'\n       call hydro_stop(\"In geth_newdate\")\n    end if\n\n    if (idt.ge.0) then\n\n       frnew = frold + nfrac\n       if (frnew.ge.ifrc) then\n          frnew = frnew - ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold + nsec\n       if (scnew .ge. 60) then\n          scnew = scnew - 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold + nmin\n       if (minew .ge. 60) then\n          minew = minew - 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold + nhour\n       if (hrnew .ge. 24) then\n          hrnew = hrnew - 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew + 1\n          if (dynew.gt.mday(monew)) then\n             dynew = dynew - mday(monew)\n             monew = monew + 1\n             if (monew .gt. 12) then\n                monew = 1\n                yrnew = yrnew + 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb_yw(yrnew)\n             end if\n          end if\n       end do\n\n    else if (idt.lt.0) then\n\n       frnew = frold - nfrac\n       if (frnew .lt. 0) then\n          frnew = frnew + ifrc\n          nsec = nsec + 1\n       end if\n\n       scnew = scold - nsec\n       if (scnew .lt. 00) then\n          scnew = scnew + 60\n          nmin  = nmin + 1\n       end if\n\n       minew = miold - nmin\n       if (minew .lt. 00) then\n          minew = minew + 60\n          nhour  = nhour + 1\n       end if\n\n       hrnew = hrold - nhour\n       if (hrnew .lt. 00) then\n          hrnew = hrnew + 24\n          nday  = nday + 1\n       end if\n\n       dynew = dyold\n       monew = moold\n       yrnew = yrold\n       do i = 1, nday\n          dynew = dynew - 1\n          if (dynew.eq.0) then\n             monew = monew - 1\n             if (monew.eq.0) then\n                monew = 12\n                yrnew = yrnew - 1\n                ! If the year changes, recompute the number of days in February\n                mday(2) = nfeb_yw(yrnew)\n             end if\n             dynew = mday(monew)\n          end if\n       end do\n    end if\n\n    !  Now construct the new mdate\n\n    newlen = LEN(ndate)\n\n    if (punct) then\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n19        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16        format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,13) yrnew, monew, dynew, hrnew\n13        format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,10) yrnew, monew, dynew\n10        format(i4,'-',i2.2,'-',i2.2)\n\n       end if\n\n    else\n\n       if (newlen.gt.frstart) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n          write(hfrc,'(i10)') frnew+1000000000\n          ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n       else if (newlen.eq.scend) then\n          write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n119       format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.miend) then\n          write(ndate,116) yrnew, monew, dynew, hrnew, minew\n116       format(i4,i2.2,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.hrend) then\n          write(ndate,113) yrnew, monew, dynew, hrnew\n113       format(i4,i2.2,i2.2,i2.2)\n\n       else if (newlen.eq.dyend) then\n          write(ndate,110) yrnew, monew, dynew\n110       format(i4,i2.2,i2.2)\n\n       end if\n\n    endif\n\n    if (punct .and. (oldlen.ge.11) .and. (newlen.ge.11)) ndate(11:11) = sp\n\n  end subroutine geth_newdate\n\n\nsubroutine read_hydro_forcing_mpp1( &\n     indir,olddate,hgrid, &\n     ix,jx,forc_typ,snow_assim,  &\n     forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n     forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n     T2,q2x,u,v,pres,xlong,short,prcp1,&\n     lai,snowbl,fpar,snodep,dt,k,prcp_old)\n! This subrouting is going to read different forcing.\nimplicit none\n! in variable\ncharacter(len=*) :: olddate,hgrid,indir\ncharacter(len=256) :: filename\ninteger :: ix,jx,forc_typ,k,snow_assim  ! k is time loop\ncharacter(len=256), intent(in)  :: forcing_name_T\ncharacter(len=256), intent(in)  :: forcing_name_Q\ncharacter(len=256), intent(in)  :: forcing_name_U\ncharacter(len=256), intent(in)  :: forcing_name_V\ncharacter(len=256), intent(in)  :: forcing_name_P\ncharacter(len=256), intent(in)  :: forcing_name_LW\ncharacter(len=256), intent(in)  :: forcing_name_SW\ncharacter(len=256), intent(in)  :: forcing_name_PR\ncharacter(len=256), intent(in)  :: forcing_name_SN\ncharacter(len=256), intent(in)  :: forcing_name_LF\nreal,dimension(ix,jx):: T2,q2x,u,v,pres,xlong,short,prcp1,&\n     prcpnew,weasd,snodep,prcp0,prcp2,prcp_old\nreal ::  dt, wrf_dt\n! tmp variable\ncharacter(len=256) :: inflnm, inflnm2, product\ninteger  :: i,j,mmflag,ierr_flg\nreal,dimension(ix,jx):: lai,snowbl,fpar\ncharacter(len=4) nwxst_t\nlogical :: fexist\n\ninflnm = trim(indir)//\"/\"//&\n         olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n         \".LDASIN_DOMAIN\"//hgrid\n\n\n!!!DJG... Call READFORC_(variable) Subroutine for forcing data...\n!!!DJG HRLDAS Format Forcing with hour format filename (NOTE: precip must be in mm/s!!!)\n\n!!! FORC_TYPE 1 ============================================================================\nif(FORC_TYP.eq.1) then\n   !!Create forcing data filename...\n   call geth_newdate(out_date,olddate,nint(dt))\n   inflnm = trim(indir)//\"/\"//&\n        out_date(1:4)//out_date(6:7)//out_date(9:10)//out_date(12:13)//&\n        \".LDASIN_DOMAIN\"//hgrid\n\n   inquire (file=trim(inflnm), exist=fexist)\n\n#ifdef MPP_LAND\n   call mpp_land_bcast_logical(fexist)\n#endif\n   if ( .not. fexist ) then\n      print*, \"no forcing data found\", inflnm\n      call hydro_stop(\"In read_hydro_forcing_mpp1() - no forcing data found\")\n   endif\n\n#ifdef HYDRO_D\n   print*, \"read forcing data at \", OLDDATE,  trim(inflnm)\n#endif\n   call READFORC_HRLDAS_mpp(inflnm,IX,JX,OLDDATE, &\n        forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n        forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n        T2,Q2X,U,V,   &\n        PRES,XLONG,SHORT,PRCP1,LAI,snowbl,FPAR)\n\n   where(PRCP1 .lt. 0) PRCP1= 0  ! set minimum to be 0\n   where(PRCP1 .gt. 0.138889) PRCP1= 0.138889 ! set maximum to be 500 mm/h\n\nend if\n\n\n!!! FORC_TYPE 2 ============================================================================\n!!!DJG HRLDAS Forcing with minute format filename (NOTE: precip must be in mm/s!!!)\nif(FORC_TYP.eq.2) then\n\n!!Create forcing data filename...\n   call geth_newdate(out_date,olddate,nint(dt))\n   inflnm = trim(indir)//\"/\"//&\n        out_date(1:4)//out_date(6:7)//out_date(9:10)//out_date(12:13)//&\n        out_date(15:16)//\".LDASIN_DOMAIN\"//hgrid\n   inquire (file=trim(inflnm), exist=fexist)\n#ifdef MPP_LAND\n   call mpp_land_bcast_logical(fexist)\n#endif\n   if ( .not. fexist ) then\n      print*, \"no forcing data found\", inflnm\n      call hydro_stop(\"In read_hydro_forcing_mpp1() - no forcing data found\")\n   endif\n   call READFORC_HRLDAS_mpp(inflnm,IX,JX,OLDDATE,&\n        forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n        forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n        T2,Q2X,U,V,   &\n        PRES,XLONG,SHORT,PRCP1,LAI,snowbl,FPAR)\n\n   where(PRCP1 .lt. 0) PRCP1= 0  ! set minimum to be 0\n   where(PRCP1 .gt. 0.138889) PRCP1= 0.138889 ! set maximum to be 500 mm/h\n\nend if\n\n\n!!! FORC_TYPE 3 ============================================================================\n!!!DJG WRF Output File Direct Ingest Forcing...\nif(FORC_TYP.eq.3) then\n   !!Create forcing data filename...\n   inflnm = trim(indir)//\"/\"//&\n        \"wrfout_d0\"//hgrid//\"_\"//&\n        olddate(1:4)//\"-\"//olddate(6:7)//\"-\"//olddate(9:10)//&\n        \"_\"//olddate(12:13)//\":00:00\"\n\n   inquire (file=trim(inflnm), exist=fexist)\n#ifdef MPP_LAND\n   call mpp_land_bcast_logical(fexist)\n#endif\n   if ( .not. fexist ) then\n      print*, \"no forcing data found\", inflnm\n      call hydro_stop(\"read_hydro_forcing_seq\")\n   endif\n\n   do i_forcing = 1, int(24*3600/dt)\n      wrf_dt = i_forcing*dt\n      call geth_newdate(out_date,olddate,nint(wrf_dt))\n      inflnm2 = trim(indir)//\"/\"//&\n           \"wrfout_d0\"//hgrid//\"_\"//&\n           out_date(1:4)//\"-\"//out_date(6:7)//\"-\"//out_date(9:10)//&\n           \"_\"//out_date(12:13)//\":00:00\"\n      inquire (file=trim(inflnm2), exist=fexist)\n#ifdef MPP_LAND\n      call mpp_land_bcast_logical(fexist)\n#endif\n      if (fexist ) goto 991\n   end do\n991 continue\n\n   if(.not. fexist) then\n      write(6,*) \"Error: could not find file \",trim(inflnm2)\n      call hydro_stop(\"In read_hydro_forcing_mpp1() - could not find WRF forcing file\")\n   endif\n#ifdef HYDRO_D\n   print*, \"read WRF forcing data: \", trim(inflnm)\n   print*, \"read WRF forcing data: \", trim(inflnm2)\n#endif\n\n\n   call READFORC_WRF_mpp(inflnm2,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n        PRES,XLONG,SHORT,PRCPnew,lai,fpar)\n   call READFORC_WRF_mpp(inflnm,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n        PRES,XLONG,SHORT,prcp0,lai,fpar)\n   PRCP1=(PRCPnew-prcp0)/wrf_dt   !Adjustment to convert accum to rate...(mm/s)\n\nend if\n\n\n!!! FORC_TYPE4 ============================================================================\n!!!DJG CONSTant, idealized forcing...\nif(FORC_TYP.eq.4) then\n   ! Impose a fixed diurnal cycle...\n   ! assumes model timestep is 1 hr\n   ! assumes K=1 is 12z (Ks or ~ sunrise)\n   ! First Precip...\n   !       IF (K.GE.1 .and. K.LE.2) THEN\n   if (K.eq.1) then\n      PRCP1 =25.4/3600.0      !units mm/s  (Simulates 1\"/hr for first time step...)\n   elseif (K.gt.1) then\n      PRCP1 = 0.\n   end if\n   ! Other Met. Vars...\n   T2=290.0 + 3.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n   Q2X = 0.01\n   U = 1.0\n   V = 1.0\n   PRES = 100000.0\n   XLONG=400.0 + 25.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n   SHORT=450.0 + 450.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\nend if\n\n\n!!! FORC_TYPE 5 ============================================================================\n!!!DJG  Idealized Met. w/ Specified Precip. Forcing Data...(Note: input precip units here are in 'mm/hr')\n!   This option uses hard-wired met forcing EXCEPT precipitation which is read in\n!   from a single, separate input file called 'YYYYMMDDHHMM.PRECIP_FORCING.nc'\n!\nif(FORC_TYP.eq.5) then\n   ! Standard Met. Vars...\n   T2=290.0 + 3.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n   Q2X = 0.01\n   U = 1.0\n   V = 1.0\n   PRES = 100000.0\n   XLONG=400.0 + 25.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n   SHORT=450.0 + 450.0*(cos((2*3.1416*K/24.0)-12.0*2*3.1416/24.0))\n\n   !Get specified precip....\n!!!VIP, dimensions of grid are currently hardwired in input subroutine!!!\n   !       product = \"trmm\"\n   !       inflnm = trim(indir)//\"/\"//\"sat_domain1.nc\"\n   !!Create forcing data filename...\n   inflnm = trim(indir)//\"/\"//&\n        olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n        olddate(15:16)//\".PRECIP_FORCING.nc\"\n   inquire (file=trim(inflnm), exist=fexist)\n#ifdef MPP_LAND\n   call mpp_land_bcast_logical(fexist)\n#endif\n   if ( .not. fexist ) then\n      print*, \"no specified precipitation data found\", inflnm\n      call hydro_stop(\"In read_hydro_forcing_mpp1() - no specified precipitation data found\")\n   endif\n\n   PRCP1 = 0.\n   PRCP_old = PRCP1\n\n#ifdef HYDRO_D\n   print *, \"Opening supplemental precipitation forcing file...\",inflnm\n#endif\n   call READFORC_MDV_mpp(inflnm,IX,JX,   &\n        PRCP2,mmflag,ierr_flg)\n\n   !If radar or spec. data is ok use if not, skip to original NARR data...\n   if (ierr_flg.eq.0) then   ! use spec. precip\n      !Convert units if necessary\n      if (mmflag.eq.0) then    !Convert pcp grid to units of mm/s...\n         PRCP1=PRCP2/DT     !convert from mm to mm/s\n#ifdef HYDRO_D\n         print*, \"Supplemental pcp is accumulated pcp/dt. \"\n#endif\n      else\n         PRCP1=PRCP2   !assumes PRCP2 is in mm/s\n#ifdef HYDRO_D\n         print*, \"Supplemental pcp is rate. \"\n#endif\n      end if  ! Endif mmflag\n   else   ! either stop or default to original forcing data...\n#ifdef HYDRO_D\n      print *,\"Current RADAR precip data not found !!! Using previous available file...\"\n#endif\n      PRCP1 = PRCP_old\n   end if  ! Endif ierr_flg\n\n   ! Loop through data to screen for plausible values\n   do i=1,ix\n      do j=1,jx\n         if (PRCP1(i,j).lt.0.) PRCP1(i,j)= PRCP_old(i,j)\n         if (PRCP1(i,j).gt.0.138889) PRCP1(i,j)=0.138889  !set max pcp intens = 500 mm/h\n      end do\n   end do\n\nend if\n\n\n!!! FORC_TYPE 6 ============================================================================\n!!!DJG HRLDAS Forcing with hourly format filename with specified precipitation forcing...\n!   This option uses HRLDAS-formatted met forcing EXCEPT precipitation which is read in\n!   from a single, separate input file called 'YYYYMMDDHHMM.PRECIP_FORCING.nc'\n\nif(FORC_TYP.eq.6) then\n\n   !!Create forcing data filename...\n\n#ifdef MPP_LAND\n   if(my_id .eq. io_id) then\n#endif\n      do i_forcing = 1, nint(3600*12/dt)\n         call geth_newdate(out_date,olddate,nint(dt*i_forcing))\n         inflnm = trim(indir)//\"/\"//&\n              out_date(1:4)//out_date(6:7)//out_date(9:10)//out_date(12:13)//&\n              \".LDASIN_DOMAIN\"//hgrid\n\n         inquire (file=trim(inflnm), exist=fexist)\n         if(fexist) goto 101\n      enddo\n101   continue\n#ifdef MPP_LAND\n   endif\n   call mpp_land_bcast_logical(fexist)\n#endif\n\n   if ( .not. fexist ) then\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n#endif\n         do i_forcing = 1, nint(3600*12/dt)\n            call geth_newdate(out_date,olddate,nint(dt*i_forcing))\n            inflnm = trim(indir)//\"/\"//&\n                 out_date(1:4)//out_date(6:7)//out_date(9:10)//out_date(12:13)//&\n                 out_date(15:16)//\".LDASIN_DOMAIN\"//hgrid\n            inquire (file=trim(inflnm), exist=fexist)\n            if(fexist) goto 102\n         end do\n102      continue\n#ifdef MPP_LAND\n      endif\n      call mpp_land_bcast_logical(fexist)\n#endif\n   endif\n\n\n   if ( .not. fexist ) then\n#ifdef HYDRO_D\n      print*, \"no ATM forcing data found at this time\", inflnm\n#endif\n   else\n#ifdef HYDRO_D\n      print*, \"reading forcing data at this time\", inflnm\n#endif\n\n      call READFORC_HRLDAS_mpp(inflnm,IX,JX,OLDDATE,&\n           forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n           forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n           T2,Q2X,U,V,   &\n           PRES,XLONG,SHORT,PRCP1,LAI,snowbl,FPAR)\n      PRCP_old = PRCP1  ! This assigns new precip to last precip as a fallback for missing data...\n   endif\n\n\n   !Get specified precip....\n   !VIP, dimensions of grid are currently hardwired in input subroutine!!!\n   !!Create forcing data filename...\n   call geth_newdate(out_date,olddate,nint(dt))\n   inflnm = trim(indir)//\"/\"//&\n        out_date(1:4)//out_date(6:7)//out_date(9:10)//out_date(12:13)//&\n        out_date(15:16)//\".PRECIP_FORCING.nc\"\n   inquire (file=trim(inflnm), exist=fexist)\n#ifdef MPP_LAND\n   call mpp_land_bcast_logical(fexist)\n#endif\n#ifdef HYDRO_D\n   if(my_id .eq. io_id) then\n      if(fexist) then\n         print*, \"using specified pcp forcing: \",trim(inflnm)\n      else\n         print*, \"no specified pcp forcing: \",trim(inflnm)\n      endif\n   endif\n#endif\n   if ( .not. fexist ) then\n      prcp1 = PRCP_old ! for missing pcp data use analysis/model input\n   else\n      call READFORC_MDV_mpp(inflnm,IX,JX,   &\n           PRCP2,mmflag,ierr_flg)\n      !If radar or spec. data is ok use if not, skip to original NARR data...\n      if(ierr_flg .ne. 0) then\n#ifdef HYDRO_D\n         print*, \"WARNING: pcp reading problem: \", trim(inflnm)\n#endif\n         PRCP1=PRCP_old\n      else\n         PRCP1=PRCP2   !assumes PRCP2 is in mm/s\n         if (mmflag.eq.0) then    !Convert pcp grid to units of mm/s...\n            PRCP1=PRCP2/DT     !convert from mm to mm/s\n         end if  ! Endif mmflag\n#ifdef HYDRO_D\n         if(my_id .eq. io_id) then\n            print*, \"replace pcp successfully! \",trim(inflnm)\n         endif\n#endif\n      endif\n   endif\n\n\n   ! Loop through data to screen for plausible values\n   where(PRCP1 .lt. 0) PRCP1=PRCP_old\n   where(PRCP1 .gt. 10 ) PRCP1= PRCP_old\n   do i=1,ix\n      do j=1,jx\n         if (PRCP1(i,j).lt.0.) PRCP1(i,j)=0.0\n         if (PRCP1(i,j).gt.0.138889) PRCP1(i,j)=0.138889  !set max pcp intens = 500 mm/h\n      end do\n   end do\n   !       write(80,*) prcp1\n\nend if\n\n\n!!! FORC_TYPE 7 ============================================================================\n!!!! FORC_TYP 7: uses WRF forcing data plus additional pcp forcing.\n\nif(FORC_TYP.eq.7) then\n\n   !!Create forcing data filename...\n   inflnm = trim(indir)//\"/\"//&\n        \"wrfout_d0\"//hgrid//\"_\"//&\n        olddate(1:4)//\"-\"//olddate(6:7)//\"-\"//olddate(9:10)//&\n        \"_\"//olddate(12:13)//\":00:00\"\n\n   inquire (file=trim(inflnm), exist=fexist)\n#ifdef MPP_LAND\n   call mpp_land_bcast_logical(fexist)\n#endif\n\n\n   if ( .not. fexist ) then\n#ifdef HYDRO_D\n      print*, \"no forcing data found\", inflnm\n#endif\n   else\n      do i_forcing = 1, int(24*3600/dt)\n         wrf_dt = i_forcing*dt\n         call geth_newdate(out_date,olddate,nint(wrf_dt))\n         inflnm2 = trim(indir)//\"/\"//&\n              \"wrfout_d0\"//hgrid//\"_\"//&\n              out_date(1:4)//\"-\"//out_date(6:7)//\"-\"//out_date(9:10)//&\n              \"_\"//out_date(12:13)//\":00:00\"\n         inquire (file=trim(inflnm2), exist=fexist)\n#ifdef MPP_LAND\n         call mpp_land_bcast_logical(fexist)\n#endif\n         if (fexist ) goto 992\n      end do\n992   continue\n\n#ifdef HYDRO_D\n      print*, \"read WRF forcing data: \", trim(inflnm)\n      print*, \"read WRF forcing data: \", trim(inflnm2)\n#endif\n      call READFORC_WRF_mpp(inflnm2,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n           PRES,XLONG,SHORT,PRCPnew,lai,fpar)\n      call READFORC_WRF_mpp(inflnm,IX,JX,OLDDATE,T2,Q2X,U,V,   &\n           PRES,XLONG,SHORT,prcp0,lai,fpar)\n      PRCP1=(PRCPnew-prcp0)/wrf_dt   !Adjustment to convert accum to rate...(mm/s)\n      PRCP_old = PRCP1\n   endif\n\n   !Get specified precip....\n   !VIP, dimensions of grid are currently hardwired in input subroutine!!!\n   !!Create forcing data filename...\n   inflnm = trim(indir)//\"/\"//&\n        olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n        olddate(15:16)//\".PRECIP_FORCING.nc\"\n   inquire (file=trim(inflnm), exist=fexist)\n#ifdef MPP_LAND\n   call mpp_land_bcast_logical(fexist)\n#endif\n#ifdef HYDRO_D\n   if(fexist) then\n      print*, \"using specified pcp forcing: \",trim(inflnm)\n   else\n      print*, \"no specified pcp forcing: \",trim(inflnm)\n   endif\n#endif\n   if ( .not. fexist ) then\n      prcp1 = PRCP_old ! for missing pcp data use analysis/model input\n   else\n      call READFORC_MDV_mpp(inflnm,IX,JX,   &\n           PRCP2,mmflag,ierr_flg)\n      !If radar or spec. data is ok use if not, skip to original NARR data...\n      if(ierr_flg .ne. 0) then\n#ifdef HYDRO_D\n         print*, \"WARNING: pcp reading problem: \", trim(inflnm)\n#endif\n         PRCP1=PRCP_old\n      else\n         PRCP1=PRCP2   !assumes PRCP2 is in mm/s\n         if (mmflag.eq.0) then    !Convert pcp grid to units of mm/s...\n            write(6,*) \"using supplemental pcp time interval \", DT\n            PRCP1=PRCP2/DT     !convert from mm to mm/s\n         else\n            write(6,*) \"using supplemental pcp rates \"\n         end if  ! Endif mmflag\n#ifdef HYDRO_D\n         print*, \"replace pcp successfully! \",trim(inflnm)\n#endif\n      endif\n   endif\n\n\n   ! Loop through data to screen for plausible values\n   where(PRCP1 .lt. 0) PRCP1=PRCP_old\n   where(PRCP1 .gt. 10 ) PRCP1= PRCP_old ! set maximum to be 500 mm/h\n   where(PRCP1 .gt. 0.138889) PRCP1= 0.138889 ! set maximum to be 500 mm/h\nend if\n\n\n\n!!!!DJG Check for snow data assimilation...\nif (SNOW_ASSIM .eq. 1) then\n\n   ! Every 24 hours, update the snow field from analyses.\n   if(forc_typ .ne. 3 .or. forc_typ .ne. 6) then\n      if ( OLDDATE(12:13) == \"00\") then\n         call READSNOW_FORC_mpp(inflnm,IX,JX,WEASD,SNODEP)\n      endif\n   else\n      call READSNOW_FORC_mpp(inflnm,IX,JX,WEASD,SNODEP)\n   endif\n\nend if\n\n#ifdef PRECIP_DOUBLE\n#ifdef HYDRO_D\nprint*,'PRECIP DOUBLE'\n#endif\nPRCP1 = PRCP1 * 2.0\n#endif\n\nend subroutine read_hydro_forcing_mpp1\n\n\n\n    subroutine READFORC_HRLDAS_mpp(flnm,ix,jx,target_date, &\n         forcing_name_T,forcing_name_Q,forcing_name_U,forcing_name_V,forcing_name_P, &\n         forcing_name_LW,forcing_name_SW,forcing_name_PR,forcing_name_SN, forcing_name_LF,&\n         t,q,u,v,p,lw,sw,pcp,lai,snowbl,fpar)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    character(len=*),                   intent(in)  :: target_date\n    character(len=256), intent(in)  :: forcing_name_T\n    character(len=256), intent(in)  :: forcing_name_Q\n    character(len=256), intent(in)  :: forcing_name_U\n    character(len=256), intent(in)  :: forcing_name_V\n    character(len=256), intent(in)  :: forcing_name_P\n    character(len=256), intent(in)  :: forcing_name_LW\n    character(len=256), intent(in)  :: forcing_name_SW\n    character(len=256), intent(in)  :: forcing_name_PR\n    character(len=256), intent(in)  :: forcing_name_SN\n    character(len=256), intent(in)  :: forcing_name_LF\n    real,             dimension(ix,jx), intent(out) :: t\n    real,             dimension(ix,jx), intent(out) :: q\n    real,             dimension(ix,jx), intent(out) :: u\n    real,             dimension(ix,jx), intent(out) :: v\n    real,             dimension(ix,jx), intent(out) :: p\n    real,             dimension(ix,jx), intent(out) :: lw\n    real,             dimension(ix,jx), intent(out) :: sw\n    real,             dimension(ix,jx), intent(out) :: pcp\n    real,             dimension(ix,jx), intent(inout) :: lai\n    real,             dimension(ix,jx), intent(inout) :: snowbl\n    real,             dimension(ix,jx), intent(inout) :: fpar\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n\n    ! Open the NetCDF file.\n#ifdef MPP_LAND\n    real, allocatable, dimension(:,:):: buf2\n    real, allocatable, dimension(:,:) :: liqfrac\n\n    if(my_id .eq. io_id) then\n        allocate(buf2(global_nx,global_ny))\n    else\n        allocate(buf2(1,1))\n    endif\n    if(my_id .eq. io_id) then\n        ierr = nf90_open(trim(flnm), NF90_NOWRITE, ncid)\n    endif\n    call mpp_land_bcast_int1(ierr)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READFORC Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READFORC_HRLDAS_mpp() - Problem opening netcdf file\")\n    endif\n\n\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_T), ncid,buf2, units, global_nx, global_ny, .TRUE., ierr)\n    call decompose_data_real (buf2,t)\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_Q), ncid,buf2, units, global_nx, global_ny, .TRUE., ierr)\n    call decompose_data_real (buf2,q)\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_U), ncid,buf2, units, global_nx, global_ny, .TRUE., ierr)\n    call decompose_data_real (buf2,u)\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_V), ncid,buf2, units, global_nx, global_ny, .TRUE., ierr)\n    call decompose_data_real (buf2,v)\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_P), ncid,buf2, units, global_nx, global_ny, .TRUE., ierr)\n    call decompose_data_real (buf2,p)\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_LW), ncid,buf2, units, global_nx, global_ny, .TRUE., ierr)\n    call decompose_data_real (buf2,lw)\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_SW), ncid,buf2, units, global_nx, global_ny, .TRUE., ierr)\n    call decompose_data_real (buf2,sw)\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_PR), ncid,buf2, units, global_nx, global_ny, .TRUE., ierr)\n    call decompose_data_real (buf2,pcp)\n    if(my_id .eq. io_id ) then\n          call get_2d_netcdf(\"VEGFRA\", ncid,buf2, units, global_nx, global_ny, .FALSE., ierr)\n          if (ierr == 0) then\n            if(maxval(buf2) .gt. 10 .and. maxval(buf2) .lt. 10000)  buf2 = buf2 * 1.E-2\n          endif\n    endif\n    call mpp_land_bcast_int1(ierr)\n    if(ierr == 0) call decompose_data_real (buf2,fpar)\n    if(my_id .eq. io_id ) call get_2d_netcdf(\"LAI\",     ncid, buf2,   units, global_nx, global_ny, .FALSE., ierr)\n    call mpp_land_bcast_int1(ierr)\n    if(ierr == 0) call decompose_data_real (buf2,lai)\n    if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_SN), ncid, buf2, units, global_nx, global_ny, .FALSE., ierr)\n    call mpp_land_bcast_int1(ierr)\n    if (ierr == 0) then\n       call decompose_data_real (buf2,snowbl)\n    else\n       if(my_id .eq. io_id ) call get_2d_netcdf(trim(forcing_name_LF), ncid, buf2, units, global_nx, global_ny, .FALSE., ierr)\n       call mpp_land_bcast_int1(ierr)\n       if(ierr == 0) then\n          allocate(liqfrac(ix,jx))\n          call decompose_data_real (buf2,liqfrac)\n          snowbl = (1.0 - liqfrac) * pcp\n          deallocate(liqfrac)\n       else\n          snowbl = 0.0 ! since if liqfrac is not present it defaults to 1.0\n       end if\n    end if\n\n    deallocate(buf2)\n#else\n    ierr = nf90_open(trim(flnm), NF90_NOWRITE, ncid)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READFORC Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"READFORC_HRLDAS\")\n    endif\n    call get_2d_netcdf(trim(forcing_name_T),     ncid, t,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_Q),     ncid, q,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_U),     ncid, u,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_V),     ncid, v,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_P),    ncid, p,     units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_LW),  ncid, lw,    units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_SW),  ncid, sw,    units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(trim(forcing_name_PR),ncid, pcp,   units, ix, jx, .TRUE., ierr)\n    call get_2d_netcdf(\"VEGFRA\",  ncid, fpar,  units, ix, jx, .FALSE., ierr)\n\n    if (ierr == 0) then\n      if(maxval(fpar) .gt. 10 .and. maxval(fpar) .lt. 10000)  fpar = fpar * 1.E-2\n    endif\n\n    call get_2d_netcdf(\"LAI\",     ncid, lai,   units, ix, jx, .FALSE., ierr)\n    call get_2d_netcdf(trim(forcing_name_SN),    ncid, snowbl,units, ix, jx, .FALSE., ierr)\n    if (ierr /= NF90_NOERR) then\n       allocate(liqfrac(ix,jx))\n       call get_2d_netcdf(trim(forcing_name_LF), ncid, liqfrac, units, ix, jx, .FALSE., ierr)\n       if (ierr == 0) then\n          snowbl = (1.0 - liqfrac) * pcp\n       else\n          snowbl = 0.0 ! since if liqfrac is not present it is set to 1.0\n       end if\n       deallocate(liqfrac)\n    end if\n\n#endif\n\n    ierr = nf90_close(ncid)\n  end subroutine READFORC_HRLDAS_mpp\n\n  subroutine READFORC_WRF_mpp(flnm,ix,jx,target_date,t,q,u,v,p,lw,sw,pcp,lai,fpar)\n\n    implicit none\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    character(len=*),                   intent(in)  :: target_date\n    real,             dimension(ix,jx) :: t,q,u,v,p,lw,sw,pcp,pcpc, lai,fpar\n    integer   tlevel\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid\n#ifdef MPP_LAND\n    real, allocatable, dimension(:,:) :: buf2\n#endif\n\n    tlevel = 1\n\n    pcpc = 0\n\n#ifdef MPP_LAND\n    if(my_id .eq. io_id) then\n          allocate(buf2(global_nx, global_ny) )\n    else\n          allocate(buf2(1, 1) )\n    endif\n\n    ! Open the NetCDF file.\n\n    if(my_id .eq. io_id) ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    call mpp_land_bcast_int1(ierr)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READFORC_WRF Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READFORC_WRF_mpp() - Problem opening netcdf file\")\n    endif\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"T2\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,t)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"Q2\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,q)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"U10\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,u)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"V10\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,v)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"PSFC\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,p)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"GLW\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,lw)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"SWDOWN\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,sw)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"RAINC\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,pcpc)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"RAINNC\",     ncid, buf2, global_nx, global_ny,tlevel, .true., ierr)\n    call decompose_data_real (buf2,pcp)\n    if(my_id .eq. io_id) call get_2d_netcdf_ruc(\"LAI\",     ncid, buf2, global_nx, global_ny,tlevel, .false., ierr)\n    call mpp_land_bcast_int1(ierr)\n    if(ierr == 0) call decompose_data_real (buf2,lai)\n    if(my_id .eq. io_id) then\n       call get_2d_netcdf_ruc(\"VEGFRA\", ncid, buf2, global_nx, global_ny, tlevel, .true., ierr)\n       if(ierr == 0) then\n          if(maxval(buf2) .gt. 10 .and. maxval(buf2) .lt. 10000)  buf2 = buf2 * 1.E-2\n       endif\n    endif\n    call mpp_land_bcast_int1(ierr)\n    if(ierr == 0) call decompose_data_real (buf2,fpar)\n    deallocate(buf2)\n#else\n\n    ! Open the NetCDF file.\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READFORC_WRF Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READFORC_WRF_mpp() - Problem opening netcdf file\")\n    endif\n    call get_2d_netcdf_ruc(\"T2\",     ncid, t,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"Q2\",     ncid, q,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"U10\",    ncid, u,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"V10\",    ncid, v,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"PSFC\",   ncid, p,     ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"GLW\",    ncid, lw,    ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"SWDOWN\", ncid, sw,    ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"RAINC\",  ncid, pcpc,  ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"RAINNC\", ncid, pcp,   ix, jx,tlevel, .true., ierr)\n    call get_2d_netcdf_ruc(\"VEGFRA\", ncid, fpar,  ix, jx,tlevel, .false., ierr)\n    if(ierr == 0) then\n        if(maxval(fpar) .gt. 10 .and. (maxval(fpar) .lt. 10000) ) fpar = fpar * 0.01\n    endif\n    call get_2d_netcdf_ruc(\"LAI\", ncid, lai,  ix, jx,tlevel, .false., ierr)\n\n#endif\n\n\n    pcp=pcp+pcpc   ! assumes pcpc=0 for resolved convection...\n    ierr = nf90_close(ncid)\n\n\n  end subroutine READFORC_WRF_mpp\n\n  subroutine READFORC_MDV_mpp(flnm,ix,jx,pcp,mmflag,ierr_flg)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    integer,                            intent(out)  :: ierr_flg\n    integer :: it,jew,zsn\n    real,             dimension(ix,jx), intent(out) :: pcp\n\n    character(len=256) :: units\n    integer :: ierr,i,j,i2,j2,varid\n    integer :: ncid,mmflag\n    real, dimension(ix,jx) :: temp\n#ifdef MPP_LAND\n    real, allocatable, dimension(:,:) :: buf2\n    if(my_id .eq. io_id) then\n       allocate(buf2(global_nx, global_ny))\n    else\n       allocate(buf2(1,1))\n    endif\n#endif\n\n    mmflag = 0   ! flag for units spec. (0=mm, 1=mm/s)\n\n\n!open NetCDF file...\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n#endif\n        ierr_flg = nf90_open(flnm, NF90_NOWRITE, ncid)\n#ifdef MPP_LAND\n      endif\n      call mpp_land_bcast_int1(ierr_flg)\n#endif\n        if (ierr_flg /= 0) then\n          write(*,'(\"READFORC_MDV Problem opening netcdf file: ''\",A,\"''\")') &\n                trim(flnm)\n#ifdef MPP_LAND\n           deallocate(buf2)\n#endif\n           return\n        end if\n\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n#endif\n        ierr = nf90_inq_varid(ncid,  \"precip\",  varid)\n#ifdef MPP_LAND\n      endif\n      call mpp_land_bcast_int1(ierr)\n#endif\n        if(ierr /= NF90_NOERR) ierr_flg = ierr\n        if (ierr /= NF90_NOERR) then\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n#endif\n          ierr = nf90_inq_varid(ncid,  \"precip_rate\",  varid)   !recheck variable name...\n#ifdef MPP_LAND\n      endif\n      call mpp_land_bcast_int1(ierr)\n#endif\n          if (ierr /= NF90_NOERR) then\n#ifdef MPP_LAND\n          if(my_id .eq. io_id) then\n#endif\n             ierr = nf90_inq_varid(ncid,  \"RAINRATE\",  varid)   !recheck variable name...\n#ifdef MPP_LAND\n          endif\n          call mpp_land_bcast_int1(ierr)\n#endif\n            if (ierr /= NF90_NOERR) then\n              write(*,'(\"READFORC_MDV Problem reading precip netcdf file: ''\", A,\"''\")') &\n                 trim(flnm)\n#ifdef MPP_LAND\n                deallocate(buf2)\n#endif\n                return\n            end if\n          end if\n          ierr_flg = ierr\n          mmflag = 1\n        end if\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n          ierr = nf90_get_var(ncid, varid, buf2)\n      endif\n      call mpp_land_bcast_int1(ierr)\n      if(ierr ==0) call decompose_data_real (buf2,pcp)\n      deallocate(buf2)\n#else\n        ierr = nf90_get_var(ncid, varid, pcp)\n#endif\n        if (ierr /= NF90_NOERR) then\n           write(*,'(\"READFORC_MDV Problem reading netcdf file: ''\", A,\"''\")') trim(flnm)\n        end if\n        ierr = nf90_close(ncid)\n\n  end subroutine READFORC_MDV_mpp\n\n  subroutine READSNOW_FORC_mpp(flnm,ix,jx,weasd,snodep)\n    implicit none\n\n    character(len=*),                   intent(in)  :: flnm\n    integer,                            intent(in)  :: ix\n    integer,                            intent(in)  :: jx\n    real,             dimension(ix,jx), intent(out) :: weasd\n    real,             dimension(ix,jx), intent(out) :: snodep\n    real, dimension(ix,jx) :: tmp\n\n    character(len=256) :: units\n    integer :: ierr\n    integer :: ncid,i,j\n#ifdef MPP_LAND\n    real, allocatable, dimension(:,:) :: buf2\n    if(my_id .eq. io_id) then\n       allocate(buf2(global_nx, global_ny))\n    else\n       allocate(buf2(1,1))\n    endif\n#endif\n\n    ! Open the NetCDF file.\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n#endif\n    ierr = nf90_open(flnm, NF90_NOWRITE, ncid)\n#ifdef MPP_LAND\n      endif\n      call mpp_land_bcast_int1(ierr)\n#endif\n    if (ierr /= NF90_NOERR) then\n       write(*,'(\"READSNOW Problem opening netcdf file: ''\", A, \"''\")') trim(flnm)\n       call hydro_stop(\"In READSNOW_FORC_mpp() - Problem opening netcdf file\")\n    endif\n\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n          call get_2d_netcdf(\"WEASD\",  ncid, buf2,   units, ix, jx, .FALSE., ierr)\n      endif\n      call mpp_land_bcast_int1(ierr)\n      if(ierr == 0) call decompose_data_real (buf2,tmp)\n#else\n    call get_2d_netcdf(\"WEASD\",  ncid, tmp,   units, ix, jx, .FALSE., ierr)\n#endif\n    if (ierr /= NF90_NOERR) then\n         call get_2d_netcdf(\"SNOW\",  ncid, tmp,   units, ix, jx, .FALSE., ierr)\n         if (ierr == 0) then\n            units = \"mm\"\n#ifdef HYDRO_D\n            print *, \"read WEASD from wrfoutput ...... \"\n#endif\n            weasd = tmp * 1.E-3\n         endif\n    else\n         weasd = tmp\n         if (trim(units) == \"m\") then\n            ! No conversion necessary\n         else if (trim(units) == \"mm\") then\n            ! convert WEASD from mm to m\n            weasd = weasd * 1.E-3\n         endif\n    endif\n\n    if (ierr /= NF90_NOERR) then\n       print *, \"!!!!! NO WEASD present in input file...initialize to 0.\"\n    endif\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n         call get_2d_netcdf(\"SNODEP\",     ncid, buf2,   units, ix, jx, .FALSE., ierr)\n      endif\n      call mpp_land_bcast_int1(ierr)\n      if(ierr == 0) call decompose_data_real (buf2,tmp)\n#else\n    call get_2d_netcdf(\"SNODEP\",     ncid, tmp,   units, ix, jx, .FALSE., ierr)\n#endif\n    if (ierr /= NF90_NOERR) then\n       ! Quick assumption regarding snow depth.\n\n#ifdef MPP_LAND\n      if(my_id .eq. io_id) then\n         call get_2d_netcdf(\"SNOWH\",     ncid, buf2,   units, ix, jx, .FALSE., ierr)\n      endif\n      call mpp_land_bcast_int1(ierr)\n      if(ierr == 0) call decompose_data_real (buf2,tmp)\n#else\n         call get_2d_netcdf(\"SNOWH\",     ncid, tmp,   units, ix, jx, .FALSE., ierr)\n#endif\n       if(ierr .eq. 0) then\n#ifdef HYDRO_D\n            print *, \"read snow depth from wrfoutput ... \"\n#endif\n            snodep = tmp\n       endif\n    else\n       snodep = tmp\n    endif\n\n    if (ierr /= NF90_NOERR) then\n       ! Quick assumption regarding snow depth.\n!yw       snodep = weasd * 10.\n       where(snodep .lt. weasd) snodep = weasd*10  !set lower bound to correct bi-lin interp err...\n    endif\n\n!DJG check for erroneous neg WEASD or SNOWD due to offline interpolation...\n       where(snodep .lt. 0) snodep = 0\n       where(weasd .lt. 0) weasd = 0\n    ierr = nf90_close(ncid)\n\n  end subroutine READSNOW_FORC_mpp\n\n  subroutine read_ldasout(olddate,hgrid, indir, dt,ix,jx,infxsrt,soldrain)\n\n      implicit none\n      logical :: fexist\n      integer :: ix,jx\n      character(len=*) :: olddate,hgrid,indir\n      character(len=19) :: outdate\n      character(len=256) :: inflnm, inflnm2\n      real :: dt\n      real, dimension(ix,jx):: infxsrt,infxsrt2,soldrain,soldrain2\n      integer :: ncid, ierr\n      character(len=256) :: units\n#ifdef MPP_LAND\n      real, dimension(global_nx,global_ny) :: gArr\n#endif\n\n        ! check for file with hours first\n        inflnm = trim(indir)//\"/\"//&\n             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n             \".LDASOUT_DOMAIN\"//hgrid\n        inquire (file=trim(inflnm), exist=fexist)\n\n        if(.not. fexist) then\n           ! check for file with minutes\n             inflnm = trim(indir)//\"/\"//&\n                  olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//olddate(15:16)//&\n                  \".LDASOUT_DOMAIN\"//hgrid\n             inquire (file=trim(inflnm), exist=fexist)\n        endif\n        if(.not. fexist) then\n            write(6,*) \"Error: input file does not exist. Check \", trim(olddate)\n            call hydro_stop( \"LDASOUT input Error\")\n        endif\n\n        call geth_newdate(outdate,olddate,nint(dt))\n        ! check file for next date\n        ! check for file with hours first\n        inflnm2 = trim(indir)//\"/\"//&\n             outdate(1:4)//outdate(6:7)//outdate(9:10)//outdate(12:13)//&\n             \".LDASOUT_DOMAIN\"//hgrid\n        inquire (file=trim(inflnm2), exist=fexist)\n\n        if(.not. fexist) then\n           ! check for file with minutes\n             inflnm2 = trim(indir)//\"/\"//&\n                  outdate(1:4)//outdate(6:7)//outdate(9:10)//outdate(12:13)//outdate(15:16)//&\n                  \".LDASOUT_DOMAIN\"//hgrid\n             inquire (file=trim(inflnm2), exist=fexist)\n        endif\n        if(.not. fexist) then\n            write(6,*) \"FATAL ERROR: input file does not exist. Check \", trim(outdate)\n            call hydro_stop( \"LDASOUT input Error\")\n        endif\n!       read file1\n#ifdef MPP_LAND\n        if(my_id .eq. io_id) then\n           ierr = nf90_open(trim(inflnm), NF90_NOWRITE, ncid)\n           call get_2d_netcdf(\"SFCRNOFF\",    ncid, gArr, units,  global_nx, global_ny, .TRUE., ierr)\n        endif\n        call decompose_data_real (gArr,infxsrt)\n        if(my_id .eq. io_id) then\n           call get_2d_netcdf(\"UGDRNOFF\",    ncid, gArr, units, global_nx, global_ny, .TRUE., ierr)\n        endif\n        call decompose_data_real (gArr,soldrain)\n        if(my_id .eq. io_id) then\n            ierr = nf90_close(ncid)\n        endif\n#else\n        ierr = nf90_open(trim(inflnm), NF90_NOWRITE, ncid)\n        call get_2d_netcdf(\"SFCRNOFF\",    ncid, infxsrt, units,  ix, jx, .TRUE., ierr)\n        call get_2d_netcdf(\"UGDRNOFF\",    ncid, soldrain, units,  ix, jx, .TRUE., ierr)\n        ierr = nf90_close(ncid)\n#endif\n!       read file2\n#ifdef MPP_LAND\n       if(my_id .eq. io_id) then\n           ierr = nf90_open(trim(inflnm2), NF90_NOWRITE, ncid)\n           call get_2d_netcdf(\"SFCRNOFF\",    ncid, gArr, units,  global_nx, global_ny, .TRUE., ierr)\n        endif\n        call decompose_data_real (gArr,infxsrt2)\n        if(my_id .eq. io_id) then\n           call get_2d_netcdf(\"UGDRNOFF\",    ncid, gArr, units, global_nx, global_ny, .TRUE., ierr)\n        endif\n        call decompose_data_real (gArr,soldrain2)\n        if(my_id .eq. io_id) then\n           ierr = nf90_close(ncid)\n        endif\n#else\n        ierr = nf90_open(trim(inflnm2), NF90_NOWRITE, ncid)\n        call get_2d_netcdf(\"SFCRNOFF\",    ncid, infxsrt2, units,  ix, jx, .TRUE., ierr)\n        call get_2d_netcdf(\"UGDRNOFF\",    ncid, soldrain2, units,  ix, jx, .TRUE., ierr)\n        ierr = nf90_close(ncid)\n#endif\n\n        infxsrt = infxsrt2 - infxsrt\n        soldrain = soldrain2 - soldrain\n\n   end subroutine read_ldasout\n\n!temporary for Noah model\n\n  subroutine read_ldasout_seq(olddate,hgrid, indir, dt,ix,jx,infxsrt,soldrain)\n      implicit none\n      logical :: fexist\n      integer :: ix,jx\n      character(len=*) :: olddate,hgrid,indir\n      character(len=19) :: outdate\n      character(len=256) :: inflnm, inflnm2\n      real :: dt\n      real, dimension(ix,jx):: infxsrt,infxsrt2,soldrain,soldrain2\n      integer :: ncid, ierr\n      character(len=256) :: units\n\n        ! check for file with hours first\n        inflnm = trim(indir)//\"/\"//&\n             olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//&\n             \".LDASOUT_DOMAIN\"//hgrid\n        inquire (file=trim(inflnm), exist=fexist)\n\n        if(.not. fexist) then\n           ! check for file with minutes\n             inflnm = trim(indir)//\"/\"//&\n                  olddate(1:4)//olddate(6:7)//olddate(9:10)//olddate(12:13)//olddate(15:16)//&\n                  \".LDASOUT_DOMAIN\"//hgrid\n             inquire (file=trim(inflnm), exist=fexist)\n        endif\n        if(.not. fexist) then\n            write(6,*) \"FATAL ERROR: input file does not exist. Check \", trim(olddate)\n            call hydro_stop( \"LDASOUT input Error\")\n        endif\n\n        call geth_newdate(outdate,olddate,nint(dt))\n        ! check file for next date\n        ! check for file with hours first\n        inflnm2 = trim(indir)//\"/\"//&\n             outdate(1:4)//outdate(6:7)//outdate(9:10)//outdate(12:13)//&\n             \".LDASOUT_DOMAIN\"//hgrid\n        inquire (file=trim(inflnm2), exist=fexist)\n\n        if(.not. fexist) then\n           ! check for file with minutes\n             inflnm2 = trim(indir)//\"/\"//&\n                  outdate(1:4)//outdate(6:7)//outdate(9:10)//outdate(12:13)//outdate(15:16)//&\n                  \".LDASOUT_DOMAIN\"//hgrid\n             inquire (file=trim(inflnm2), exist=fexist)\n        endif\n        if(.not. fexist) then\n            write(6,*) \"FATAL ERROR: input file does not exist. Check \", trim(outdate)\n            call hydro_stop( \"LDASOUT input Error\")\n        endif\n!       read file1\n        ierr = nf90_open(trim(inflnm), NF90_NOWRITE, ncid)\n        call get_2d_netcdf(\"SFCRNOFF\",    ncid, infxsrt, units,  ix, jx, .TRUE., ierr)\n        call get_2d_netcdf(\"UGDRNOFF\",    ncid, soldrain, units,  ix, jx, .TRUE., ierr)\n        ierr = nf90_close(ncid)\n!       read file2\n        ierr = nf90_open(trim(inflnm2), NF90_NOWRITE, ncid)\n        call get_2d_netcdf(\"SFCRNOFF\",    ncid, infxsrt2, units,  ix, jx, .TRUE., ierr)\n        call get_2d_netcdf(\"UGDRNOFF\",    ncid, soldrain2, units,  ix, jx, .TRUE., ierr)\n        ierr = nf90_close(ncid)\n\n        infxsrt = infxsrt2 - infxsrt\n        soldrain = soldrain2 - soldrain\n\n   end subroutine read_ldasout_seq\nend module module_lsm_forcing\n\n     subroutine read_forc_ldasout(olddate,hgrid, indir, dt,ix,jx,infxsrt,soldrain)\n      use module_lsm_forcing, only: read_ldasout\n      implicit none\n      integer :: ix,jx\n      character(len=*) :: olddate,hgrid,indir\n      real :: dt\n      real, dimension(ix,jx):: infxsrt,soldrain\n      call read_ldasout(olddate,hgrid, indir, dt,ix,jx,infxsrt,soldrain)\n    end subroutine read_forc_ldasout\n\n    subroutine read_forc_ldasout_seq(olddate,hgrid, indir, dt,ix,jx,infxsrt,soldrain)\n! temporary for Noah model\n      use module_lsm_forcing, only: read_ldasout_seq\n      implicit none\n      integer :: ix,jx\n      character(len=*) :: olddate,hgrid,indir\n      real :: dt\n      real, dimension(ix,jx):: infxsrt,soldrain\n      call read_ldasout_seq(olddate,hgrid, indir, dt,ix,jx,infxsrt,soldrain)\n    end subroutine read_forc_ldasout_seq\n"
  },
  {
    "path": "src/Routing/module_noah_chan_param_init_rt.F90",
    "content": "\n!  Author(s)/Contact(s):\n!  Abstract:\n!  History Log:\n!\n!  Usage:\n!  Parameters: <Specify typical arguments passed>\n!  Input Files:\n!        <list file names and briefly describe the data they include>\n!  Output Files:\n!        <list file names and briefly describe the information they include>\n!\n!  Condition codes:\n!        <list exit condition or error codes returned >\n!        If appropriate, descriptive troubleshooting instructions or\n!        likely causes for failures could be mentioned here with the\n!        appropriate error code\n!\n!  User controllable options: <if applicable>\n\nMODULE module_noah_chan_param_init_rt\n\n\nCONTAINS\n!\n!-----------------------------------------------------------------\n  SUBROUTINE CHAN_PARM_INIT (BOTWID,CHANN_K,HLINK_INIT,CHAN_SS,CHMann)\n!  SUBROUTINE CHAN_PARM_INIT (BOTWID,CHANN_K,TOPWID,HLINK_INIT,CHAN_SS,CHMann,TOPWIDCC,NCC)\n!-----------------------------------------------------------------\n\n    IMPLICIT NONE\n\n    integer :: IINDEX, CHANCATS\n    integer :: ORDER, IUNIT\n    integer, PARAMETER :: NCHANTYPES=50\n    real,dimension(NCHANTYPES)    :: BOTWID,CHANN_K,TOPWID,HLINK_INIT,CHAN_SS,CHMann\n    real,dimension(NCHANTYPES)    :: TOPWIDCC, NCC\n    character(LEN=11) :: DATATYPE\n\n!-----SPECIFY CHANNEL RELATED CHARACTERISTICS :\n!             ORDER: Strahler Stream Order\n!            BOTWID: Channel Bottom Width (meters)\n!            CHANNK: channel conductivity (m/s)\n!            TOPWID: Channel Top Width before becoming compound (meters)\n!          TOPWIDCC: Channel Top Width after becoming compound (meters)\n!            NCC   : mannings n of compound component\n!        HLINK_INIT: Initial depth of flow in channel (meters)\n!           CHAN_SS: Channel side slope (assuming trapezoidal channel geom)\n!            CHMann: Channel Manning's N roughness coefficient\n\n\n!-----READ IN CHANNEL PROPERTIES FROM CHANPARM.TBL :\n    IUNIT = 23\n    OPEN(IUNIT, &\n#ifndef NCEP_WCOSS\n    FILE='CHANPARM.TBL', &\n#endif\n    FORM='FORMATTED',STATUS='OLD')\n    READ (IUNIT,*)\n    READ (IUNIT,2000,END=2002) DATATYPE\n#ifdef HYDRO_D\n    PRINT *, DATATYPE\n#endif\n    READ (IUNIT,*)CHANCATS,IINDEX\n2000 FORMAT (A11)\n\n!-----Read in Channel Parameters as functions of stream order...\n\n    IF(DATATYPE.EQ.'StreamOrder')THEN\n#ifdef HYDRO_D\n       PRINT *, 'CHANNEL DATA SOURCE TYPE = ',DATATYPE,' FOUND',           &\n            CHANCATS,' CATEGORIES'\n#endif\n       do ORDER=1,CHANCATS\n\n          read (IUNIT,*)IINDEX, BOTWID(ORDER), HLINK_INIT(ORDER), CHAN_SS(ORDER), CHMann(ORDER)\n!          READ (IUNIT,*)IINDEX,BOTWID(ORDER),TOPWID(ORDER), &\n!               HLINK_INIT(ORDER),CHAN_SS(ORDER),CHMann(ORDER),&\n!               TOPWIDCC(ORDER),NCC(ORDER)\n\n#ifdef HYDRO_D\n          PRINT *, IINDEX, BOTWID(ORDER), HLINK_INIT(ORDER), CHAN_SS(ORDER),  &\n               &     CHMann(ORDER)\n!          PRINT *, IINDEX,BOTWID(ORDER),&\n!                HLINK_INIT(ORDER),CHAN_SS(ORDER),   &\n!                CHMann(ORDER),TOPWIDCC(ORDER),NCC(ORDER)\n#endif\n       ENDDO\n    ENDIF\n\n\n!-----Read in Channel Parameters as functions of ???other method??? (TBC)...\n\n\n2002 CONTINUE\n\n    CLOSE (IUNIT)\n  END SUBROUTINE CHAN_PARM_INIT\n\n\n\n#ifdef MPP_LAND\n  SUBROUTINE mpp_CHAN_PARM_INIT (BOTWID,CHANN_K,HLINK_INIT,CHAN_SS,CHMann)\n!  subroutine mpp_CHAN_PARM_INIT (BOTWID,CHANN_K,TOPWID,HLINK_INIT,CHAN_SS,CHMann,TOPWIDCC,NCC)\n    use module_mpp_land, only:  my_id, IO_id,mpp_land_bcast_int1, &\n       mpp_land_bcast_real,mpp_land_bcast_int,mpp_land_bcast_real1\n    implicit none\n    integer :: IINDEX, CHANCATS\n    integer :: ORDER\n    integer, PARAMETER :: NCHANTYPES=50\n    real,dimension(NCHANTYPES)    :: BOTWID,CHANN_K,HLINK_INIT,CHAN_SS,CHMann\n    !real,dimension(NCHANTYPES)    :: TOPWID, TOPWIDCC, NCC  ! compound components\n    character(LEN=11) :: DATATYPE\n\n    if(my_id.eq.io_id) then\n       call CHAN_PARM_INIT(BOTWID,CHANN_K,HLINK_INIT,CHAN_SS,CHMann)\n!       call CHAN_PARM_INIT(BOTWID,TOPWID,HLINK_INIT,CHAN_SS,CHMann,TOPWIDCC,NCC)\n    end if\n       call mpp_land_bcast_real(NCHANTYPES,BOTWID)\n       call mpp_land_bcast_real(NCHANTYPES,CHANN_K)\n       call mpp_land_bcast_real(NCHANTYPES,HLINK_INIT)\n       call mpp_land_bcast_real(NCHANTYPES,CHAN_SS)\n       call mpp_land_bcast_real(NCHANTYPES,CHMann)\n!       call mpp_land_bcast_real(NCHANTYPES,TOPWID)\n!       call mpp_land_bcast_real(NCHANTYPES,TOPWIDCC)\n!       call mpp_land_bcast_real(NCHANTYPES,NCC)\n\n    return\n    END SUBROUTINE mpp_CHAN_PARM_INIT\n#endif\n!-----------------------------------------------------------------\n!-----------------------------------------------------------------\n\n\nEND MODULE module_Noah_chan_param_init_rt\n"
  },
  {
    "path": "src/Routing/module_reservoir_routing.F90",
    "content": "! Intended purpose is to provide a module for all subroutines related to\n! reservoir routing, including active management, level pool, and integrating live\n! data feeds. As of NWMv2.0, this module stub can read in a timeslice file\n! to incorporate data from external sources, should a data service become available.\n\n! NOTE: THIS CODE IS NOT ACTIVE AND CANNOT BE ACTIVATED THROUGH\n!       NAMELIST OPTIONS AT THIS TIME - NWM Version 2.0.\n\n! Logan Karsten\n! National Center for Atmospheric Research\n! Research Applications Laboratory\n! karsten at ucar dot edu\n\nmodule module_reservoir_routing\nimplicit none\n\ncontains\n\nsubroutine read_reservoir_obs(domainId)\n  use config_base, only: nlst\n   use netcdf\n   use module_hydro_stop, only: HYDRO_stop\n#ifdef MPP_LAND\n   use module_mpp_land\n#endif\n   implicit none\n\n   ! Pass in domain ID value from parent calling program.\n   integer, intent(in) :: domainId\n\n   ! Local variables\n   integer :: ftn ! NetCDF file handle.\n   integer :: nLakesNc ! Number of lake objects in the input file.\n   real, allocatable, dimension(:) :: minRelease ! Specified minimum reservoir release (cms)\n   real, allocatable, dimension(:) :: poolElev ! Value of time-varying water surface elevation\n   real, allocatable, dimension(:) :: resFlow ! Reservoir discharge in cms\n   real, allocatable, dimension(:) :: qType ! Reservoir discharge type\n   real*8, allocatable, dimension(:) :: ifd ! Initial fractional depth\n   real*8, allocatable, dimension(:) :: lkArea ! Gridded lake area (sq. km)\n   real*8, allocatable, dimension(:) :: lkMxE ! Maximum lake elevation (m ASL)\n   real*8, allocatable, dimension(:) :: orificeA ! Orifice cross-sectional area (sq. m)\n   real*8, allocatable, dimension(:) :: orificeC ! Orifice coefficient\n   real*8, allocatable, dimension(:) :: orificeE ! Orifice elevation (m ASL)\n   real*8, allocatable, dimension(:) :: weirC ! Weir coefficient\n   real*8, allocatable, dimension(:) :: weirE ! Weir height (m ASL)\n   real*8, allocatable, dimension(:) :: weirL ! Weir length (m)\n   integer, allocatable, dimension(:) :: ascIndex ! Index to sort lake objects by ascending ID\n   integer, allocatable, dimension(:) :: lakeID ! Lake index value\n   real, allocatable, dimension(:) :: lakeLat ! Lake latitude values.\n   real, allocatable, dimension(:) :: lakeLon ! Lake longitude values\n   character(len=1024) :: inFlnm ! NetCDF file with discharge data.\n   integer :: myId ! MPI processor ID\n   integer :: ierr ! MPI return status\n   integer :: diagFlag\n   logical :: file_exists\n   integer :: missingFlag\n   integer :: varTmpId\n   integer :: mppFlag\n   integer :: iret\n   integer :: lakeDimId\n\n#ifdef HYDRO_D\n   diagFlag = 1\n#else\n   diagFlag = 0\n#endif\n\n   ! Sync up processes.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call mpp_land_sync()\n#endif\n   endif\n\n   ! Check to ensure the namelist option for reading in the reservoir discharge data\n   ! has been set to 1. If not, return back to the main calling program.\n   if(nlst(domainId)%reservoir_data_ingest .eq. 0) then\n       ! No reservoir realtime data requested.\n       return\n   endif\n\n   ! If we are running over MPI, determine which processor number we are on.\n   ! If not MPI, then default to 0, which is the I/O ID.\n   if(mppFlag .eq. 1) then\n#ifdef MPP_LAND\n      call MPI_Comm_rank( HYDRO_COMM_WORLD, myId, ierr )\n      call nwmCheck(diagFlag,ierr,'ERROR: Unable to determine MPI process ID.')\n#endif\n   else\n      myId = 0\n   endif\n\n   ! Open up and read in the NetCDF file containing disharge data.\n   if(myId .eq. 0) then\n      ! Initialize our missing flag to 0. If at any point we don't find a file,\n      ! the flag value will go to 1 to indicate no files were found.\n      missingFlag = 0\n\n      ! We are on the I/O processor.\n      write(inFlnm,'(A,\"/LAKEFILE_DISCHARGE_\",A12,\".nc\")') nlst(domainId)%reservoir_obs_dir,nlst(domainId)%olddate(1:4)//&\n            nlst(domainId)%olddate(6:7)//nlst(domainId)%olddate(9:10)//&\n            nlst(domainId)%olddate(12:13)//nlst(domainId)%olddate(15:16)\n\n      ! Check to see if the file exists.\n      INQUIRE(FILE=inFlnm,EXIST=file_exists)\n\n      if(file_exists) then\n         iret = nf90_open(trim(inFlnm),NF90_NOWRITE,ncid=ftn)\n         call nwmCheck(diagFlag,iret,\"ERROR: Unable to open LAKE reservoir discharge file.\")\n         iret = nf90_inq_dimid(ftn,'nlakes',lakeDimId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find nlakes dimension in LAKE reservoir discharge file.')\n         iret = nf90_inquire_dimension(ftn,lakeDimId,len=nLakesNc)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find nlakes size in LAKE reservoir discharge file.')\n\n         ! Allocate the lake variables based on the nlakes dimension\n         allocate(minRelease(nLakesNc))\n         allocate(poolElev(nLakesNc))\n         allocate(resFlow(nLakesNc))\n         allocate(qType(nLakesNc))\n         allocate(ifd(nLakesNc))\n         allocate(lkArea(nLakesNc))\n         allocate(lkMxE(nLakesNc))\n         allocate(orificeA(nLakesNc))\n         allocate(orificeC(nLakesNc))\n         allocate(orificeE(nLakesNc))\n         allocate(weirC(nLakesNc))\n         allocate(weirE(nLakesNc))\n         allocate(weirL(nLakesNc))\n         allocate(ascIndex(nLakesNc))\n         allocate(lakeId(nLakesNc))\n         allocate(lakeLat(nLakesNc))\n         allocate(lakeLon(nLakesNc))\n\n         ! Read in data.\n         iret = nf90_inq_varid(ftn,'MIN_RELEASE',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find MIN_RELEASE in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,minRelease)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract MIN_RELEASE in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'POOL_ELEV',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find POOL_ELEV in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,poolElev)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract POOL_ELEV in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'RES_FLOW',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find RES_FLOW in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,resFlow)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract RES_FLOW in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'Q_TYPE',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find Q_TYPE in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,qType)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract Q_TYPE in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'ifd',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find ifd in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,ifd)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract ifd in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'LkArea',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find lkArea in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,lkArea)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract lkArea in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'LkMxE',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find LkMxE in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,lkMxE)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract lkMxE in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'OrificeA',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find OrificeA in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,orificeA)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract OrificeA in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'OrificeC',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find OrificeC in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,orificeC)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract OrificeC in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'OrificeE',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find OrificeE in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,orificeE)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract OrificeE in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'WeirC',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find WeirC in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,weirC)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract WeirC in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'WeirE',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find WeirE in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,weirE)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract WeirE in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'WeirL',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find WeirL in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,weirL)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract WeirL in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'ascendingIndex',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find ascendingIndex in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,ascIndex)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract ascendingIndex in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'lake_id',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find lake_id in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,lakeId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract lake_id in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'lat',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find lat in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,lakeLat)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract lat in LAKE reservoir discharge file.')\n\n         iret = nf90_inq_varid(ftn,'lon',varTmpId)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to find lon in LAKE reservoir discharge file.')\n         iret = nf90_get_var(ftn,varTmpId,lakeLon)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to extract lon in LAKE reservoir discharge file.')\n\n         ! Close the NetCDF file\n         iret = nf90_close(ftn)\n         call nwmCheck(diagFlag,iret,'ERROR: Unable to close LAKE reservoir discharge file.')\n\n         ! Deallocate memory appropriately\n         deallocate(minRelease)\n         deallocate(poolElev)\n         deallocate(resFlow)\n         deallocate(qType)\n         deallocate(ifd)\n         deallocate(lkArea)\n         deallocate(lkMxE)\n         deallocate(orificeA)\n         deallocate(orificeC)\n         deallocate(orificeE)\n         deallocate(weirC)\n         deallocate(weirE)\n         deallocate(weirL)\n         deallocate(ascIndex)\n         deallocate(lakeId)\n         deallocate(lakeLat)\n         deallocate(lakeLon)\n\n      else\n         missingFlag = 1\n         return\n      endif\n   endif\n\nend subroutine read_reservoir_obs\n\nsubroutine postDiagMsg(diagFlag,diagMsg)\n   implicit none\n\n   ! Subroutine arguments.\n   integer, intent(in) :: diagFlag\n   character(len=*), intent(in) :: diagMsg\n\n   ! Only write out message if the diagnostic WRF_HYDRO_D flag was\n   ! set to 1\n   if (diagFlag .eq. 1) then\n      print*, trim(diagMsg)\n   end if\nend subroutine postDiagMsg\n\nsubroutine nwmCheck(diagFlag,iret,msg)\n   implicit none\n\n   ! Subroutine arguments.\n   integer, intent(in) :: diagFlag,iret\n   character(len=*), intent(in) :: msg\n\n   ! Check status. If status of command is not 0, then post the error message\n   ! if WRF_HYDRO_D was set to be 1.\n   if (iret .ne. 0) then\n      call hydro_stop(trim(msg))\n   end if\n\nend subroutine nwmCheck\n\n\nend module module_reservoir_routing\n"
  },
  {
    "path": "src/arc/Makefile.Noah",
    "content": "# Makefile\nCMD = Run/wrf_hydro\n\nall: $(CMD)\n\n$(CMD):\n\t@if [ ! -d \"Run\" ]; then \\\n\t\t(mkdir Run);\\\n\tfi\n\t(rm -f Run/wrf_hydro   )\n\t(make -f Makefile.comm BASIC)\n\t@if [ -d \"LandModel_cpl\" ]; then \\\n\t(cd LandModel_cpl; make) \\\n\tfi\n\tif [ $(WRF_HYDRO_RAPID) -eq 1 ]; then \\\n\t\t(cd lib;rm -f librapid.a); \\\n\tfi\n\tif [ $(WRF_HYDRO_RAPID) -eq 1 ]; then \\\n\t\t(cd Rapid_routing; make -f makefile.cpl rapid); \\\n\tfi\n\n\t@if [ -d \"LandModel\" ]; then \\\n\t(cd LandModel; make ) \\\n\tfi\n\ndebug::\n\t@echo 'F90FLAGS := $$(DEBUGFLAGS) $$(F90FLAGS)' >> ./macros\n\t@echo 'F90FLAGS := $$(DEBUGFLAGS) $$(F90FLAGS)' >> ./LandModel/user_build_options\ndebug:: $(CMD)\n\ninstall:\n\t-rm -f ./Run/wrf_hydro; \\\n\tmv ./Run/Noah_hrldas_beta ./Run/wrf_hydro\ntest:\n\t@echo \"No libraries or utilities are built, skip testing.\"\nclean:\n\t@if [ -d \"LandModel_cpl\" ]; then \\\n\t(cd LandModel_cpl; make clean) \\\n\tfi\n\t(make -f Makefile.comm clean)\n\t@if [ -d \"LandModel\" ]; then \\\n\t(cd LandModel; make clean) \\\n\tfi\n\tif [ $(WRF_HYDRO_RAPID) -eq 1 ]; then \\\n\t\t(cd Rapid_routing; make -f makefile.cpl clean); \\\n\tfi\n\t(rm -f */*.mod */*.o lib/*.a Run/wrf_hydro)\n"
  },
  {
    "path": "src/arc/Makefile.NoahMP",
    "content": "# Makefile\n#\nCMD = Run/wrf_hydro\n.PHONY: $(CMD)\n\nall: $(CMD)\n\n$(CMD):\n\t@if [ ! -d \"Run\" ]; then \\\n\t\t(mkdir Run);\\\n\tfi\n\t(rm -f Run/wrf_hydro   )\n\t(make -f Makefile.comm BASIC)\n\t@if [ -d \"LandModel_cpl\" ]; then \\\n\t(cd LandModel_cpl; make) \\\n\tfi\n\tif [ $(WRF_HYDRO_RAPID) -eq 1 ]; then \\\n\t\t(cd lib;rm -f librapid.a); \\\n\tfi\n\tif [ $(WRF_HYDRO_RAPID) -eq 1 ]; then \\\n\t\t(cd Rapid_routing; make -f makefile.cpl rapid); \\\n\tfi\n\n\t@if [ -d \"LandModel\" ]; then \\\n\t(cd LandModel; make ) \\\n\tfi\n\ndebug::\n\t@echo 'F90FLAGS := $$(DEBUGFLAGS) $$(F90FLAGS)' >> ./macros\n\t@echo 'F90FLAGS := $$(DEBUGFLAGS) $$(F90FLAGS)' >> ./LandModel/user_build_options\ndebug:: $(CMD)\n\ninstall:\n\t-rm -f ./Run/wrf_hydro\n\tmv LandModel/run/hrldas.exe  ./Run/wrf_hydro\ntest:\n\t@echo \"No libraries or utilities are built, skip testing.\"\nclean:\n\t@if [ -d \"LandModel_cpl\" ]; then \\\n\t(cd LandModel_cpl; make clean) \\\n\tfi\n\t(make -f Makefile.comm clean)\n\t@if [ -d \"LandModel\" ]; then \\\n\t(cd LandModel; make clean) \\\n\tfi\n\tif [ $(WRF_HYDRO_RAPID) -eq 1 ]; then \\\n\t\t(cd Rapid_routing; make -f makefile.cpl clean); \\\n\tfi\n\t(rm -f */*.mod */*.o lib/*.a Run/wrf_hydro)\n"
  },
  {
    "path": "src/arc/Makefile.mpp",
    "content": "# Makefile\n\nall:\n\t(make -f Makefile.comm BASIC)\n\nBASIC:\n\tmake -C MPP\n\tmake -C IO\n\tmake -C utils/fortglob\n\tmake -C utils\n\tmake -C OrchestratorLayer\n\tmake -C Routing/Diversions\n\tmake -C Routing/Overland\n\tmake -C Routing/Subsurface\n\tmake -C Routing/Reservoirs\n\tmake -C Data_Rec\n\tmake -C Debug_Utilities\n\tmake -C Routing\n\tmake -C HYDRO_drv\n\nclean:\n\tmake -C IO clean\n\tmake -C OrchestratorLayer clean\n\tmake -C utils clean\n\tmake -C utils/fortglob clean\n\tmake -C Routing/Diversions clean\n\tmake -C Routing/Overland clean\n\tmake -C Routing/Subsurface clean\n\tmake -C Routing/Reservoirs clean\n\tmake -C Data_Rec clean\n\tmake -C HYDRO_drv clean\n\tmake -C MPP clean\n\tmake -C Debug_Utilities/ clean\n\tmake -C Routing clean\n\t(rm -f lib/*.a */*.mod */*.o CPL/*/*.o CPL/*/*.mod)\n"
  },
  {
    "path": "src/arc/macros.gordon",
    "content": ".IGNORE:\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\n\nRMD             = rm -f\nCOMPILER90      = ftn\nFORMAT_FREE     = -FR\nBYTESWAPIO      = -convert big_endian\nF90FLAGS        = -w -c -ftz -align all -fno-alias -fp-model precise $(FORMAT_FREE) $(BYTESWAPIO)\nDEBUGFLAGS = -DHYDRO_D -g -traceback -debug all -check all\nMODFLAG         = -I./ -I../../MPP -I../MPP -I../mod\nLDFLAGS         =\nCPPINVOKE       = -fpp\nCPPFLAGS        = -DMPP_LAND -I../Data_Rec $(HYDRO_D) \nLIBS            =\nNETCDFINC       = $(NETCDF_INC)\nNETCDFLIB       = -L$(NETCDF_LIB) -lnetcdff -lnetcdf\nNETCDF_INC = /opt/cray/netcdf-hdf5parallel/4.3.2/INTEL/140/include\nNETCDF_LIB = /opt/cray/netcdf-hdf5parallel/4.3.2/INTEL/140/lib\n"
  },
  {
    "path": "src/arc/macros.gordon.debug",
    "content": ".IGNORE:\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\n\nRMD             = rm -f\nCOMPILER90      = ftn\nFORMAT_FREE     = -FR\nBYTESWAPIO      = -convert big_endian\nF90FLAGS        = -w -c -ftz -align all -fno-alias -fp-model precise $(FORMAT_FREE) $(BYTESWAPIO)\nF90FLAGS        += -g -traceback\nMODFLAG         = -I./ -I../../MPP -I../MPP -I../mod\nLDFLAGS         =\nCPPINVOKE       = -fpp\nCPPFLAGS        = -DMPP_LAND -I../Data_Rec $(HYDRO_D)\nLIBS            =\nNETCDFINC       = $(NETCDF_INC)\nNETCDFLIB       = -L$(NETCDF_LIB) -lnetcdff -lnetcdf\nNETCDF_INC = /opt/cray/netcdf-hdf5parallel/4.3.2/INTEL/140/include\nNETCDF_LIB = /opt/cray/netcdf-hdf5parallel/4.3.2/INTEL/140/lib\n"
  },
  {
    "path": "src/arc/macros.mpp.IBM.xlf90_r",
    "content": ".IGNORE:\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\nRM\t\t=\trm -f \nRMD\t\t=\trm -f \nCOMPILER90=\tmpxlf90_r\nF90FLAGS  =     -O2 -qfree=f90 -c -w -qspill=20000 -qmaxmem=64000\nDEBUGFLAGS = -DHYDRO_D -g \nLDFLAGS  =     -O2 -qfree=f90  -w -qspill=20000 -qmaxmem=64000\nMODFLAG\t=\t-I./ -I ../MPP -I../../MPP -I ../mod\nLDFLAGS\t=\t\nCPPINVOKE\t=   -qpreprocess\nLIBS \t=\t\nCPPFLAGS\t=\t-DMPP_LAND -I../Data_Rec $(HYDRO_D) \nNETCDFINC\t=\t$(NETCDF_INC) \nNETCDFLIB\t=\t-L$(NETCDF_LIB) -lnetcdff -lnetcdf\n\n"
  },
  {
    "path": "src/arc/macros.mpp.cray_fortran",
    "content": ".IGNORE:\n\nifeq ($(SPATIAL_SOIL),1)\nSPATIAL_SOIL = -DSPATIAL_SOIL\nelse\nSPATIAL_SOIL =\nendif\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\nifeq ($(WRF_HYDRO_NUDGING),1)\nWRF_HYDRO_NUDGING = -DWRF_HYDRO_NUDGING\nelse\nWRF_HYDRO_NUDGING =\nendif\n\nifeq ($(OUTPUT_CHAN_CONN),1)\nOUTPUT_CHAN_CONN = -DOUTPUT_CHAN_CONN\nelse\nOUTPUT_CHAN_CONN =\nendif\n\nifeq ($(PRECIP_DOUBLE),1)\nPRECIP_DOUBLE = -DPRECIP_DOUBLE\nelse\nPRECIP_DOUBLE =\nendif\n\nifeq ($(NWM_META),1)\nNWM_META = -DNWM_META\nelse\nNWM_META =\nendif\n\nifeq ($(NCEP_WCOSS),1)\nNCEP_WCOSS = -DNCEP_WCOSS\nelse\nNCEP_WCOSS =\nendif\n\nRMD\t        = rm -f\nCOMPILER90  = ftn\nCOMPILERCC  = cc\nFORMAT_FREE = -f free\nBYTESWAPIO  = -h byteswapio\nF90FLAGS    = -O2 -c -ef -h alias=none -h fp1 $(FORMAT_FREE) $(BYTESWAPIO)\n#F90FLAGS    = -O0 -eD -g -c -ef -h alias=tolerant $(FORMAT_FREE) $(BYTESWAPIO)   # CRAY DEBUG OPTIONS\nMODFLAG     = -I./ -I ../../MPP -I ../MPP -I ../mod\nLDFLAGS     =\nCPPINVOKE   = -eT\nCPPFLAGS    = -DMPP_LAND -I ../Data_Rec $(HYDRO_D) $(SPATIAL_SOIL) $(NWM_META) $(WRF_HYDRO_NUDGING) $(OUTPUT_CHAN_CONN) $(PRECIP_DOUBLE) $(NCEP_WCOSS)\nLIBS \t    =\nNETCDFINC   = $(NETCDF_INC)\nNETCDFLIB   = -L$(NETCDF_LIB) -lnetcdff -lnetcdf\n"
  },
  {
    "path": "src/arc/macros.mpp.gfort",
    "content": ".IGNORE:\n\nifeq ($(SPATIAL_SOIL),1)\nSPATIAL_SOIL = -DSPATIAL_SOIL\nelse\nSPATIAL_SOIL = \nendif\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\nifeq ($(NWM_META),1)\nNWM_META = -DNWM_META\nelse\nNWM_META =\nendif\n\nifeq ($(WRF_HYDRO_NUDGING),1)\nWRF_HYDRO_NUDGING = -DWRF_HYDRO_NUDGING\nelse\nWRF_HYDRO_NUDGING = \nendif\n\nifeq ($(OUTPUT_CHAN_CONN),1)\nOUTPUT_CHAN_CONN = -DOUTPUT_CHAN_CONN\nelse\nOUTPUT_CHAN_CONN = \nendif\n\nifeq ($(PRECIP_DOUBLE),1)\nPRECIP_DOUBLE = -DPRECIP_DOUBLE\nelse\nPRECIP_DOUBLE = \nendif\n\n\nRMD\t\t=\trm -f\nCOMPILER90      =\tmpif90\nCOMPILERCC      =       mpicc\nF90FLAGS        =       -w -c -O2 -ffree-form -ffree-line-length-none -fconvert=big-endian -frecord-marker=4 -std=legacy\nDEBUGFLAGS      = -DHYDRO_D -g -Wall -Wextra -Warray-temporaries -Wconversion -fimplicit-none -fbacktrace -ffree-line-length-0 -fcheck=all -ffpe-trap=invalid,zero,overflow,underflow -finit-real=nan\nMODFLAG      \t=\t-I\"./\" -I\"../../MPP\" -I\"../MPP\" -I\"../mod\"\nLDFLAGS\t        =\t\nCPPINVOKE\t=       -cpp\nCPPFLAGS\t=       -DMPP_LAND -I\"../Data_Rec\" $(HYDRO_D) $(SPATIAL_SOIL) $(NWM_META) $(WRF_HYDRO_NUDGING) $(OUTPUT_CHAN_CONN) $(PRECIP_DOUBLE)\n\nLIBS \t        =\t\nNETCDFINC       =       $(NETCDF_INC)\nNETCDFLIB       =       -L$(NETCDF_LIB) -lnetcdff -lnetcdf\n"
  },
  {
    "path": "src/arc/macros.mpp.ifort",
    "content": ".IGNORE:\n\nifeq ($(SPATIAL_SOIL),1)\nSPATIAL_SOIL = -DSPATIAL_SOIL\nelse\nSPATIAL_SOIL = \nendif\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\nifeq ($(WRF_HYDRO_NUDGING),1)\nWRF_HYDRO_NUDGING = -DWRF_HYDRO_NUDGING\nelse\nWRF_HYDRO_NUDGING = \nendif\n\nifeq ($(OUTPUT_CHAN_CONN),1)\nOUTPUT_CHAN_CONN = -DOUTPUT_CHAN_CONN\nelse\nOUTPUT_CHAN_CONN = \nendif\n\nifeq ($(PRECIP_DOUBLE),1)\nPRECIP_DOUBLE = -DPRECIP_DOUBLE\nelse\nPRECIP_DOUBLE = \nendif\n\nifeq ($(NWM_META),1)\nNWM_META = -DNWM_META\nelse\nNWM_META =\nendif\n\nifeq ($(NCEP_WCOSS),1)\nNCEP_WCOSS = -DNCEP_WCOSS\nelse\nNCEP_WCOSS =\nendif\n\nRMD\t        = rm -f\nCOMPILER90  = mpif90\nCOMPILERCC  = mpicc\nFORMAT_FREE = -FR\nBYTESWAPIO  = -convert big_endian\nF90FLAGS    = -O2 -g -w -c -ftz -align all -fno-alias -fp-model precise $(FORMAT_FREE) $(BYTESWAPIO)\nDEBUGFLAGS = -DHYDRO_D -g -traceback -debug all -check all\nMODFLAG\t    = -I./ -I ../../MPP -I ../MPP -I ../mod\nLDFLAGS\t    =\nCPPINVOKE   = -fpp\nCPPFLAGS    = -DMPP_LAND -I ../Data_Rec $(HYDRO_D) $(SPATIAL_SOIL) $(NWM_META) $(WRF_HYDRO_NUDGING) $(OUTPUT_CHAN_CONN) $(PRECIP_DOUBLE) $(NCEP_WCOSS)\nLIBS \t    =\t\nNETCDFINC   = $(NETCDF_INC)\nNETCDFLIB   = -L$(NETCDF_LIB) -lnetcdff -lnetcdf\n"
  },
  {
    "path": "src/arc/macros.mpp.ifort.omp",
    "content": ".IGNORE:\n\nifeq ($(SPATIAL_SOIL),1)\nSPATIAL_SOIL = -DSPATIAL_SOIL\nelse\nSPATIAL_SOIL = \nendif\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\nifeq ($(WRFIO_NCD_LARGE_FILE_SUPPORT),1)\nWRFIO_NCD_LARGE_FILE_SUPPORT = -DWRFIO_NCD_LARGE_FILE_SUPPORT\nelse\nWRFIO_NCD_LARGE_FILE_SUPPORT = \nendif\n\nifeq ($(WRF_HYDRO_NUDGING),1)\nWRF_HYDRO_NUDGING = -DWRF_HYDRO_NUDGING\nelse\nWRF_HYDRO_NUDGING = \nendif\n\nifeq ($(OUTPUT_CHAN_CONN),1)\nOUTPUT_CHAN_CONN = -DOUTPUT_CHAN_CONN\nelse\nOUTPUT_CHAN_CONN = \nendif\n\nifeq ($(PRECIP_DOUBLE),1)\nPRECIP_DOUBLE = -DPRECIP_DOUBLE\nelse\nPRECIP_DOUBLE = \nendif\n\nifeq ($(NCEP_WCOSS),1)\nNCEP_WCOSS = -DNCEP_WCOSS\nelse\nNCEP_WCOSS =\nendif\n\nifeq ($(NWM_META),1)\nNWM_META = -DNWM_META\nelse\nNWM_META =\nendif\n\nRMD\t    = rm -f\nCOMPILER90  = mpif90\nFORMAT_FREE = -FR\nBYTESWAPIO  = -convert big_endian\nF90FLAGS    = -xHost -qopenmp -g -w -c -ftz -align all -fno-alias -fp-model strict $(FORMAT_FREE) $(BYTESWAPIO)\nDEBUGFLAGS = -DHYDRO_D -g -traceback -debug all -check all\nMODFLAG\t    = -I./ -I ../../MPP -I ../MPP -I ../mod\nLDFLAGS\t    = -qopenmp\nCPPINVOKE   = -fpp\nCPPFLAGS    = -DMPP_LAND -I ../Data_Rec $(HYDRO_D) $(SPATIAL_SOIL) $(WRFIO_NCD_LARGE_FILE_SUPPORT) $(NWM_META) $(WRF_HYDRO_NUDGING) $(OUTPUT_CHAN_CONN) $(PRECIP_DOUBLE) $(NCEP_WCOSS)\nLIBS \t    = -qopenmp\nNETCDFINC   = $(NETCDF_INC)\nNETCDFLIB   = -L$(NETCDF_LIB) -lnetcdff -lnetcdf\n"
  },
  {
    "path": "src/arc/macros.mpp.intel.cray_xc",
    "content": ".IGNORE:\n\nifeq ($(SPATIAL_SOIL),1)\nSPATIAL_SOIL = -DSPATIAL_SOIL\nelse\nSPATIAL_SOIL = \nendif\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\nifeq ($(WRF_HYDRO_NUDGING),1)\nWRF_HYDRO_NUDGING = -DWRF_HYDRO_NUDGING\nelse\nWRF_HYDRO_NUDGING = \nendif\n\nifeq ($(OUTPUT_CHAN_CONN),1)\nOUTPUT_CHAN_CONN = -DOUTPUT_CHAN_CONN\nelse\nOUTPUT_CHAN_CONN = \nendif\n\nifeq ($(PRECIP_DOUBLE),1)\nPRECIP_DOUBLE = -DPRECIP_DOUBLE\nelse\nPRECIP_DOUBLE = \nendif\n\nifeq ($(NWM_META),1)\nNWM_META = -DNWM_META\nelse\nNWM_META =\nendif\n\nifeq ($(NCEP_WCOSS),1)\nNCEP_WCOSS = -DNCEP_WCOSS\nelse\nNCEP_WCOSS =\nendif\n\nRMD\t    = rm -f\nCOMPILER90  = ftn\nFORMAT_FREE = -FR\nBYTESWAPIO  = -convert big_endian\nF90FLAGS    = -w -c -ftz -align all -fno-alias -fp-model precise $(FORMAT_FREE) $(BYTESWAPIO)\nDEBUGFLAGS = -DHYDRO_D -g -traceback -debug all -check all\nMODFLAG\t    = -I./ -I ../../MPP -I ../MPP -I ../mod\nLDFLAGS\t    =\nCPPINVOKE   = -fpp\nCPPFLAGS    = -DMPP_LAND -I ../Data_Rec $(HYDRO_D) $(SPATIAL_SOIL) $(NWM_META) $(WRF_HYDRO_NUDGING) $(OUTPUT_CHAN_CONN) $(PRECIP_DOUBLE) $(NCEP_WCOSS)\nLIBS \t    =\t\nNETCDFINC   = $(NETCDF_INC)\nNETCDFLIB   = -L$(NETCDF_LIB) -lnetcdff -lnetcdf\n"
  },
  {
    "path": "src/arc/macros.mpp.linux",
    "content": ".IGNORE:\n\nifeq ($(SPATIAL_SOIL),1)\nSPATIAL_SOIL = -DSPATIAL_SOIL\nelse\nSPATIAL_SOIL =\nendif\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\nifeq ($(WRF_HYDRO_NUDGING),1)\nWRF_HYDRO_NUDGING = -DWRF_HYDRO_NUDGING\nelse\nWRF_HYDRO_NUDGING =\nendif\n\nifeq ($(OUTPUT_CHAN_CONN),1)\nOUTPUT_CHAN_CONN = -DOUTPUT_CHAN_CONN\nelse\nOUTPUT_CHAN_CONN =\nendif\n\nifeq ($(PRECIP_DOUBLE),1)\nPRECIP_DOUBLE = -DPRECIP_DOUBLE\nelse\nPRECIP_DOUBLE =\nendif\n\n\nRM\t\t=\trm -f\nRMD\t\t=\trm -f\nCOMPILER90=\tmpif90\nCOMPILERCC=\tmpicc\nF90FLAGS  =     -Mfree -c -byteswapio -O2 -Kieee\nDEBUGFLAGS =  -DHYDRO_D -g\nLDFLAGS  =      $(F90FLAGS)\nMODFLAG\t=\t-I./ -I ../../MPP -I ../MPP -I ../mod -I ../../mod -I ../../../mod\nLDFLAGS\t=\nCPPINVOKE\t= -Mpreprocess\nCPPFLAGS\t=  -DMPP_LAND -I../Data_Rec $(HYDRO_D) $(SPATIAL_SOIL) $(WRF_HYDRO_NUDGING) $(OUTPUT_CHAN_CONN) $(PRECIP_DOUBLE)\nLIBS \t=\nNETCDFINC\t=\t$(NETCDF_INC)\nNETCDFLIB\t=\t-L$(NETCDF_LIB) -lnetcdff -lnetcdf\n"
  },
  {
    "path": "src/arc/macros.mpp.mpiifort",
    "content": ".IGNORE:\n\nifeq ($(HYDRO_REALTIME),1)\nHYDRO_REALTIME = -DHYDRO_REALTIME\nelse\nHYDRO_REALTIME =\nendif\n\nifeq ($(WRF_HYDRO),1)\nWRF_HYDRO = -DWRF_HYDRO $(HYDRO_REALTIME)\nelse\nWRF_HYDRO =\nendif\n\nifeq ($(WRF_HYDRO_RAPID),1)\nWRF_HYDRO = -DWRF_HYDRO -DWRF_HYDRO_RAPID $(HYDRO_REALTIME)\nendif\n\nifeq ($(HYDRO_D),1)\nHYDRO_D = -DHYDRO_D $(WRF_HYDRO)\nelse\nHYDRO_D =  $(WRF_HYDRO)\nendif\n\n\n#################\n# NEMS Settings #\n#################\n\nFC          = mpiifort -g -openmp -mkl=sequential -align array32byte -lmkl_intel_lp64 -lmkl_core -lmkl_sequential -lpthread -openmp -convert big_endian -assume byterecl -mkl=sequential\n\n# -g\t: produce symbolic debug information in object file\n\n######################\n# WRF Hydro Settings #\n######################\n\nRMD\t\t= rm -f\nCOMPILER90\t= $(FC)\nF90FLAGS\t= -O2 -g -w -c -ftz -fno-alias -fp-model precise -FR\n# -w\t: disable all warnings\n# -c\t: compile to object (.o) only, do not link\n# -ftz\t: enable flush denormal results to zero\nDEBUGFLAGS = -DHYDRO_D -g -traceback -debug all -check all\nMODFLAG\t\t= -I./ -I../../MPP -I../MPP -I../mod\nLDFLAGS\t\t= \nCPPINVOKE\t= -fpp\nCPPFLAGS\t= -DMPP_LAND -I ../Data_Rec $(HYDRO_D)\nLIBS\t\t=\t\nNETCDFINC       = $(NETCDF)/include\nNETCDFLIB       = -L$(NETCDF)/lib -lnetcdff -lnetcdf\n"
  },
  {
    "path": "src/cmake-modules/FindESMF.cmake",
    "content": "# - Try to find ESMF\n#\n# Requires setting ESMFMKFILE to the filepath of esmf.mk. If this is NOT set,\n# then ESMF_FOUND will always be FALSE. If ESMFMKFILE exists, then ESMF_FOUND=TRUE\n# and all ESMF makefile variables will be set in the global scope. Optionally,\n# set ESMF_MKGLOBALS to a string list to filter makefile variables. For example,\n# to globally scope only ESMF_LIBSDIR and ESMF_APPSDIR variables, use this CMake\n# command in CMakeLists.txt:\n#\n#   set(ESMF_MKGLOBALS \"LIBSDIR\" \"APPSDIR\")\n\n\n# Add the ESMFMKFILE path to the cache if defined as system env variable\nif (DEFINED ENV{ESMFMKFILE} AND NOT DEFINED ESMFMKFILE)\n  set(ESMFMKFILE $ENV{ESMFMKFILE} CACHE FILEPATH \"Path to ESMF mk file\")\nendif ()\n\n# Found the mk file and ESMF exists on the system\nif (EXISTS ${ESMFMKFILE})\n  set(ESMF_FOUND TRUE CACHE BOOL \"ESMF mk file found\" FORCE)\n  # Did not find the ESMF mk file\nelse()\n  set(ESMF_FOUND FALSE CACHE BOOL \"ESMF mk file NOT found\" FORCE)\n  # Best to warn users that without the mk file there is no way to find ESMF\n  if (NOT DEFINED ESMFMKFILE)\n    message(FATAL_ERROR \"ESMFMKFILE not defined. This is the path to esmf.mk file. \\\nWithout this filepath, ESMF_FOUND will always be FALSE.\")\n  endif ()\nendif()\n\n# Only parse the mk file if it is found\nif (ESMF_FOUND)\n  # Read the mk file\n  file(STRINGS \"${ESMFMKFILE}\" esmfmkfile_contents)\n  # Parse each line in the mk file\n  foreach(str ${esmfmkfile_contents})\n    # Only consider uncommented lines\n    string(REGEX MATCH \"^[^#]\" def ${str})\n    # Line is not commented\n    if (def)\n      # Extract the variable name\n      string(REGEX MATCH \"^[^=]+\" esmf_varname ${str})\n      # Extract the variable's value\n      string(REGEX MATCH \"=.+$\" esmf_vardef ${str})\n      # Only for variables with a defined value\n      if (esmf_vardef)\n        # Get rid of the assignment string\n        string(SUBSTRING ${esmf_vardef} 1 -1 esmf_vardef)\n        # Remove whitespace\n        string(STRIP ${esmf_vardef} esmf_vardef)\n        # A string or single-valued list\n        if(NOT DEFINED ESMF_MKGLOBALS)\n          # Set in global scope\n          set(${esmf_varname} ${esmf_vardef})\n          # Don't display by default in GUI\n          mark_as_advanced(esmf_varname)\n        else() # Need to filter global promotion\n          foreach(m ${ESMF_MKGLOBALS})\n            string(FIND ${esmf_varname} ${m} match)\n            # Found the string\n            if(NOT ${match} EQUAL -1)\n              # Promote to global scope\n              set(${esmf_varname} ${esmf_vardef})\n              # Don't display by default in the GUI\n              mark_as_advanced (esmf_varname)\n              # No need to search for the current string filter\n              break()\n            endif()\n          endforeach()\n        endif()\n      endif()\n    endif()\n  endforeach()\n\n  separate_arguments(ESMF_F90COMPILEPATHS NATIVE_COMMAND ${ESMF_F90COMPILEPATHS})\n  foreach (ITEM ${ESMF_F90COMPILEPATHS})\n     string(REGEX REPLACE \"^-I\" \"\" ITEM \"${ITEM}\")\n     list(APPEND tmp ${ITEM})\n  endforeach()\n  set(ESMF_F90COMPILEPATHS ${tmp})\n\n  add_library(esmf UNKNOWN IMPORTED)\n  # Look for static library, if not found try dynamic library\n  find_library(esmf_lib NAMES libesmf.a PATHS ${ESMF_LIBSDIR})\n  if(esmf_lib MATCHES \"esmf_lib-NOTFOUND\")\n    message(STATUS \"Static ESMF library not found, searching for dynamic library instead\")\n    find_library(esmf_lib NAMES esmf_fullylinked PATHS ${ESMF_LIBSDIR})\n    if(esmf_lib MATCHES \"esmf_lib-NOTFOUND\")\n      message(FATAL_ERROR \"Neither the dynamic nor the static ESMF library was found\")\n    else()\n      message(STATUS \"Found ESMF library: ${esmf_lib}\")\n    endif()\n    set(ESMF_INTERFACE_LINK_LIBRARIES \"\")\n  else()\n    # When linking the static library, also need the ESMF linker flags; strip any leading/trailing whitespaces\n    string(STRIP \"${ESMF_F90ESMFLINKRPATHS} ${ESMF_F90ESMFLINKPATHS} ${ESMF_F90LINKPATHS} ${ESMF_F90LINKLIBS} ${ESMF_F90LINKOPTS}\" ESMF_INTERFACE_LINK_LIBRARIES)\n    message(STATUS \"Found ESMF library: ${esmf_lib}\")\n  endif()\n\n  set_target_properties(esmf PROPERTIES\n    IMPORTED_LOCATION ${esmf_lib}\n    INTERFACE_INCLUDE_DIRECTORIES \"${ESMF_F90COMPILEPATHS}\"\n    INTERFACE_LINK_LIBRARIES \"${ESMF_INTERFACE_LINK_LIBRARIES}\")\n\nendif()\n"
  },
  {
    "path": "src/cmake-modules/FindNetCDF.cmake",
    "content": "# - Find NetCDF\n# Find the native NetCDF includes and library\n#\n#  NETCDF_INCLUDES    - where to find netcdf.h, etc\n#  NETCDF_LIBRARIES   - Link these libraries when using NetCDF\n#  NETCDF_FOUND       - True if NetCDF found including required interfaces (see below)\n#\n# Your package can require certain interfaces to be FOUND by setting these\n#\n#  NETCDF_CXX         - require the C++ interface and link the C++ library\n#  NETCDF_F77         - require the F77 interface and link the fortran library\n#  NETCDF_F90         - require the F90 interface and link the fortran library\n#\n# The following are not for general use and are included in\n# NETCDF_LIBRARIES if the corresponding option above is set.\n#\n#  NETCDF_LIBRARIES_C    - Just the C interface\n#  NETCDF_LIBRARIES_CXX  - C++ interface, if available\n#  NETCDF_LIBRARIES_F77  - Fortran 77 interface, if available\n#  NETCDF_LIBRARIES_F90  - Fortran 90 interface, if available\n#\n# Normal usage would be:\n#  set (NETCDF_F90 \"YES\")\n#  find_package (NetCDF REQUIRED)\n#  target_link_libraries (uses_f90_interface ${NETCDF_LIBRARIES})\n#  target_link_libraries (only_uses_c_interface ${NETCDF_LIBRARIES_C})\n\nif (NETCDF_INCLUDES AND NETCDF_LIBRARIES)\n  # Already in cache, be silent\n  set (NETCDF_FIND_QUIETLY TRUE)\nendif (NETCDF_INCLUDES AND NETCDF_LIBRARIES)\n\nfind_path (NETCDF_INCLUDES netcdf.h HINTS NETCDF_DIR \"$ENV{NETCDF}/include\" ENV NETCDF_DIR ENV MPI_INCLUDE)\n\nfind_path (NETCDF_MODULES netcdf.mod HINTS NETCDF_DIR \"$ENV{NETCDF}/mod\" ENV NETCDF_MOD ENV MPI_FORTRAN_MOD_DIR \"/usr/lib64/gfortran/modules\")\n\nfind_library(NETCDF_LIBRARIES NAMES netcdff PATHS \"$ENV{NETCDF}\" PATH_SUFFIXES lib lib64 ENV NETCDF_LIB ENV MPI_LIB)\n\nfind_library (NETCDF_LIBRARIES_C NAMES netcdf PATHS \"$ENV{NETCDF}\" PATH_SUFFIXES lib lib64 ENV NETCDF_LIB ENV MPI_LIB)\n\nmark_as_advanced(NETCDF_LIBRARIES_C)\n\nset (NetCDF_has_interfaces \"YES\") # will be set to NO if we're missing any interfaces\nset (NetCDF_libs \"${NETCDF_LIBRARIES_C}\")\n\nget_filename_component(NETCDF_LIB_DIR \"${NETCDF_LIBRARIES}\" DIRECTORY)\nget_filename_component(NETCDF_LIB_DIR_C \"${NETCDF_LIBRARIES_C}\" DIRECTORY)\n\nmacro (NetCDF_check_interface lang header libs)\n  if (NETCDF_${lang})\n    find_path (NETCDF_INCLUDES_${lang} NAMES ${header}\n      HINTS \"${NETCDF_INCLUDES}\" \"${NETCDF_MODULES}\" NO_DEFAULT_PATH)\n    find_library (NETCDF_LIBRARIES_${lang} NAMES ${libs}\n      HINTS \"${NETCDF_LIB_DIR}\" \"${NETCDF_LIB_DIR_C}\" NO_DEFAULT_PATH)\n    mark_as_advanced (NETCDF_INCLUDES_${lang} NETCDF_LIBRARIES_${lang})\n    if (NETCDF_INCLUDES_${lang} AND NETCDF_LIBRARIES_${lang})\n      list (INSERT NetCDF_libs 0 ${NETCDF_LIBRARIES_${lang}}) # prepend so that -lnetcdf is last\n    else (NETCDF_INCLUDES_${lang} AND NETCDF_LIBRARIES_${lang})\n      set (NetCDF_has_interfaces \"NO\")\n      message (STATUS \"Failed to find NetCDF interface for ${lang}\")\n    endif (NETCDF_INCLUDES_${lang} AND NETCDF_LIBRARIES_${lang})\n  endif (NETCDF_${lang})\nendmacro (NetCDF_check_interface)\n\nNetCDF_check_interface (CXX netcdfcpp.h netcdf_c++)\nNetCDF_check_interface (F77 netcdf.inc  netcdff)\nNetCDF_check_interface (F90 netcdf.mod  netcdff)\n\n# Add links to library dependencies (e.g. -lhdf5 -lm -lz )\nfind_program (NETCDF_CONFIG_EXE NAMES nc-config PATHS \"$ENV{NETCDF}/bin\" ENV NETCDF_DIR)\nif (NETCDF_CONFIG_EXE)\n  execute_process( COMMAND ${NETCDF_CONFIG_EXE} --libs RESULT_VARIABLE nc_config_ret OUTPUT_VARIABLE nc_config_libs)\n  if (nc_config_ret EQUAL 0)\n    string( STRIP ${nc_config_libs} nc_config_libs )\n    list (APPEND NetCDF_libs ${nc_config_libs})\n    list (REMOVE_DUPLICATES NetCDF_libs)\n  else (nc_config_ret EQUAL 0)\n    message(WARNING \"nc-config --libs not found, library dependencies may not link.\")\n  endif (nc_config_ret EQUAL 0)\nelse (NETCDF_CONFIG_EXE)\n  message(WARNING \"nc-config not found, library dependencies may not link.\")\nendif (NETCDF_CONFIG_EXE)\n\nset (NETCDF_LIBRARIES ${NetCDF_libs} CACHE INTERNAL \"All NetCDF libraries required for interface level\")\n\n# handle the QUIETLY and REQUIRED arguments and set NETCDF_FOUND to TRUE if\n# all listed variables are TRUE\ninclude (FindPackageHandleStandardArgs)\nfind_package_handle_standard_args (NetCDF DEFAULT_MSG NETCDF_LIBRARIES NETCDF_INCLUDES NetCDF_has_interfaces)\n\nif (NETCDF_FOUND AND NOT TARGET netCDF::netcdf)\n  add_library(netCDF::netcdf UNKNOWN IMPORTED)\n  set_target_properties(\n    netCDF::netcdf\n    PROPERTIES\n    IMPORTED_LOCATION \"${NETCDF_LIBRARIES_C}\"\n    IMPORTED_LINK_INTERFACE_LANGUAGES C\n    INTERFACE_INCLUDE_DIRECTORIES \"${NETCDF_INCLUDES}\"\n    )\nendif()\nif (NETCDF_FOUND AND NOT TARGET netCDF::netcdff)\n  add_library(netCDF::netcdff UNKNOWN IMPORTED)\n  set_target_properties(\n    netCDF::netcdff\n    PROPERTIES\n    IMPORTED_LOCATION \"${NETCDF_LIBRARIES_F90}\"\n    IMPORTED_LINK_INTERFACE_LANGUAGES Fortran\n    INTERFACE_INCLUDE_DIRECTORIES \"${NETCDF_MODULES}\"\n    )\n  target_link_libraries(netCDF::netcdff INTERFACE netCDF::netcdf)\nendif()\n\nmark_as_advanced (NETCDF_LIBRARIES NETCDF_INCLUDES)\n"
  },
  {
    "path": "src/compile_offline_Noah.sh",
    "content": "#!/bin/bash\n\n## This script takes one optional argument:\n## a file which sets the environment variables\n## to use in the compile. The template for\n## this file is src/setEnvar.sh. Please\n## copy that file to src, make copies\n## for your favorite compile configurations, and\n## pass the appropriate file name to this script\n## as desired.\nenv_file=$1\n\nif [[ ! -z $env_file ]]; then\n\n    ## unset these in the env so we are not mixing\n    ## and matching env vars and the sourced file.\n    unset WRF_HYDRO\n    unset HYDRO_D\n    unset RESERVOIR_D\n    unset SPATIAL_SOIL\n    unset WRF_HYDRO_RAPID\n    unset NCEP_WCOSS\n    unset WRF_HYDRO_NUDGING\n\n    echo \"configure: Sourcing $env_file for the compile options.\"\n    source $env_file\nelse\n    echo \"configure: Using the compile options in the calling environment.\"\nfi\n\nif [[ \"$WRF_HYDRO\" -ne 1 ]]; then\n    echo\n    echo \"The WRF_HYDRO compile option is required to be 1 for compile_offline_Noah.sh\"\n    exit 1\nfi\n\nrm -f LandModel LandModel_cpl\ncp arc/Makefile.Noah Makefile\nln -sf CPL/Noah_cpl LandModel_cpl\nln -sf Land_models/Noah LandModel\ncat macros LandModel/user_build_options.bak  > LandModel/user_build_options\nmake clean ; rm -f Run/wrf_hydro_Noah ; rm -f Run/*TBL ; rm -f Run/*namelist*\n\ncat macros LandModel/user_build_options.bak > LandModel/user_build_options\n\nmake && make install\n\n\nif [[ $? -eq 0 ]]; then\n    echo\n    echo '*****************************************************************'\n    echo \"Make was successful\"\nelse\n    echo\n    echo '*****************************************************************'\n    echo \"Make NOT successful\"\n    exit 1\nfi\n\ncd Run\nmv wrf_hydro wrf_hydro_Noah ; ln -sf wrf_hydro_Noah wrf_hydro ; ln -sf wrf_hydro_Noah wrf_hydro\ncp ../Land_models/Noah/Run/GENPARM.TBL .\ncp ../Land_models/Noah/Run/SOILPARM.TBL .\ncp ../Land_models/Noah/Run/VEGPARM.TBL .\ncp ../template/Noah/namelist.hrldas .\ncp ../template/HYDRO/HYDRO.TBL .\ncp ../template/HYDRO/CHANPARM.TBL .\ncp ../template/HYDRO/hydro.namelist .\n\necho\necho '*****************************************************************'\necho \"The environment variables used in the compile:\"\ngrepStr=\"(WRF_HYDRO)|(HYDRO_D)|(SPATIAL_SOIL)|(WRF_HYDRO_RAPID)|(HYDRO_REALTIME)|(NCEP_WCOSS)|(WRF_HYDRO_NUDGING)|(NETCDF)\"\nprintenv | egrep -w \"${grepStr}\" | sort\n\nexit 0\n"
  },
  {
    "path": "src/compile_offline_NoahMP.sh",
    "content": "#!/bin/bash\n\n## This script takes one optional argument:\n## a file which sets the environment variables\n## to use in the compile (clearning any inherited\n## from the calling envionrment first). The template\n## fo this file is src/setEnvar.sh. Please\n## copy that file to src, make copies\n## for your favorite compile configurations, and\n## pass the appropriate file name to this script\n## as desired.\nenv_file=$1\n\nif [[ ! -z $env_file ]]; then\n\n    ## unset these in the env so we are not mixing\n    ## and matching env vars and the sourced file.\n    unset WRF_HYDRO\n    unset HYDRO_D\n    unset RESERVOIR_D\n    unset SPATIAL_SOIL\n    unset WRF_HYDRO_RAPID\n    unset NCEP_WCOSS\n    unset NWM_META\n    unset WRF_HYDRO_NUDGING\n\n    echo \"configure: Sourcing $env_file for the compile options.\"\n    source $env_file\n\nelse\n    echo \"configure: Using the compile options in the calling environment.\"\nfi\n\nif [[ \"$WRF_HYDRO\" -ne 1 ]]; then\n    echo\n    echo \"The WRF_HYDRO compile option is required to be 1 for compile_offline_NoahMP.sh\"\n    exit 1\nfi\n\nrm -f  LandModel LandModel_cpl\ncp arc/Makefile.NoahMP Makefile\ncd Land_models/NoahMP\ncp hydro/Makefile.hydro Makefile\nif [[ -e \"MPP\" ]]; then  rm -rf  MPP; fi\nln -sf ../../MPP .\ncd ../..\n\nln -sf Land_models/NoahMP LandModel\ncat macros LandModel/hydro/user_build_options.bak  > LandModel/user_build_options\nln -sf CPL/NoahMP_cpl LandModel_cpl\nmake clean; rm -f Run/wrf_hydro_NoahMP ; rm -f Run/*TBL ; rm -f Run/*namelist*\n\n#for debugging and testing\n#make debug; make install; make test\nmake && make install\n\nif [[ $? -eq 0 ]]; then\n    echo\n    echo '*****************************************************************'\n    echo \"Make was successful\"\nelse\n    echo\n    echo '*****************************************************************'\n    echo \"Make NOT successful\"\n    exit 1\nfi\n\ncd Run\nmv  wrf_hydro wrf_hydro_NoahMP; ln -sf wrf_hydro_NoahMP wrf_hydro\n\nif [ \"$NWM_META\" != \"1\" ]; then\n    # If it is not an nwm version, copy the stock namelists and tables.\n    cp ../template/NoahMP/namelist.hrldas .\n    cp ../template/HYDRO/hydro.namelist .\n    cp ../Land_models/NoahMP/run/*TBL .\n    cp ../template/HYDRO/HYDRO.TBL .\n    cp ../template/HYDRO/CHANPARM.TBL .\nelse\n    # If it's an nwm version (nwm release branch), grab the nwm versions from elsewhere.\n    echo 'NWM version: not populating with generic templates'\nfi\n\n\necho\necho '*****************************************************************'\necho \"The environment variables used in the compile:\"\ngrepStr=\"(WRF_HYDRO)|(HYDRO_D)|(SPATIAL_SOIL)|(WRF_HYDRO_RAPID)|(HYDRO_REALTIME)|(NCEP_WCOSS)|(WRF_HYDRO_NUDGING)|(NETCDF)\"\nprintenv | egrep -w \"${grepStr}\" | sort\n\nexit 0\n"
  },
  {
    "path": "src/compile_options.json",
    "content": "{\n    \"nwm\": {\n        \"WRF_HYDRO\": 1,\n        \"HYDRO_D\": 0,\n        \"SPATIAL_SOIL\": 1,\n        \"WRF_HYDRO_RAPID\": 0,\n        \"WRFIO_NCD_LARGE_FILE_SUPPORT\": 1,\n        \"NCEP_WCOSS\": 0,\n        \"WRF_HYDRO_NUDGING\": 1\n    },\n\n    \"gridded\": {\n        \"WRF_HYDRO\": 1,\n        \"HYDRO_D\": 0,\n        \"SPATIAL_SOIL\": 1,\n        \"WRF_HYDRO_RAPID\": 0,\n        \"WRFIO_NCD_LARGE_FILE_SUPPORT\": 1,\n        \"NCEP_WCOSS\": 0,\n        \"WRF_HYDRO_NUDGING\": 0\n    },\n\n    \"gridded_no_lakes\": {\n        \"WRF_HYDRO\": 1,\n        \"HYDRO_D\": 0,\n        \"SPATIAL_SOIL\": 1,\n        \"WRF_HYDRO_RAPID\": 0,\n        \"WRFIO_NCD_LARGE_FILE_SUPPORT\": 1,\n        \"NCEP_WCOSS\": 0,\n        \"WRF_HYDRO_NUDGING\": 0\n    },\n\n    \"reach\": {\n        \"WRF_HYDRO\": 1,\n        \"HYDRO_D\": 0,\n        \"SPATIAL_SOIL\": 1,\n        \"WRF_HYDRO_RAPID\": 0,\n        \"WRFIO_NCD_LARGE_FILE_SUPPORT\": 1,\n        \"NCEP_WCOSS\": 0,\n        \"WRF_HYDRO_NUDGING\": 0\n    }\n}\n"
  },
  {
    "path": "src/configure",
    "content": "#!/bin/bash\n\ntheArgument=$1\n\n###################################\n## Setup the HOSTNAME if not set\necho \"---------------------------------------------------\"\necho \"                  WARNING\"\necho \"---------------------------------------------------\"\necho \"WARNING: configure is being deprecated and removed in the future.\"\necho \"         See docs/BUILD.md for more detail on building.\"\necho \"         Please switch to using CMake from the top directory.\"\necho \"         $ mkdir build\"\necho \"         $ cd build\"\necho \"         $ cmake ..\"\necho \"         $ make -j 4\"\necho \"---------------------------------------------------\"\n\nif [ -z ${HOSTNAME+x} ]; then\n  HOSTNAME=`hostname`\n  echo \"Configured: hostname=$HOSTNAME\"\nfi\n\n###################################\n## Setup the NetCDF include and LIB variables.\n## If Neither is set and neither $NETCDF nor $NETCDF_DIR is not set,\n## then try nc-config. If that fails, all fails.\n\nif [[ -z $NETCDF ]]; then\n    if [[ -n $NETCDF_DIR ]]; then\n\tNETCDF=$NETCDF_DIR\n    fi\nfi\n\nif [[ -z $NETCDF_INC ]]; then\n    if [[ -z $NETCDF ]]; then\n\tNETCDF_INC=`nc-config --includedir 2> /dev/null`\n    else\n\tNETCDF_INC=${NETCDF}/include\n    fi\n    if [[ -z $NETCDF_INC ]]; then\n\techo \"Error: environment variable NETCDF_INC not defined.\"\n\texit 1\n    fi\n    echo \"NETCDF_INC = ${NETCDF_INC}\" > macros.tmp\nfi\n\nif [[ -z $NETCDF_LIB ]]; then\n    if [[ -z $NETCDF ]]; then\n\tNETCDF_LIB=`nc-config --libs | cut -c3- | cut -d' ' -f1`\n    else\n\tNETCDF_LIB=${NETCDF}/lib\n    fi\n    if [[ -z $NETCDF_LIB ]]; then\n\techo \"Error: environment variable NETCDF_LIB not defined.\"\n\texit 1\n     fi\n    echo \"NETCDF_LIB = ${NETCDF_LIB}\" >> macros.tmp\nfi\n\nif [[ ! -e ${NETCDF_LIB}/libnetcdff.a ]]; then\n    echo \"NETCDFLIB       =       -L${NETCDF_LIB} -lnetcdf\" >> macros.tmp\nfi\n\n# add any additional F90 flags that came out of nf-config (most likely separate module/library path)\nif command -v nf-config &> /dev/null; then             # ignore if nf-config isn't available\n    echo \"F90FLAGS        +=      $(nf-config --fflags)\" >> macros.tmp\n    echo \"NETCDFLIB       +=      $(nf-config --flibs)\" >> macros.tmp\nfi\n\n###################################\n## File/dir setups\nif [[ -e macros ]]; then rm -f macros; fi\nif [[ ! -e lib ]]; then mkdir lib; fi\nif [[ ! -e mod ]]; then mkdir mod; fi\n\n\n###################################\n## If no argument was supplied, get all interactive.\nif [[ -z $theArgument ]]; then\n    echo \"Please select from following supported linux compilers\"\n    echo \"using either the number or key (not case sensitive):\"\n    echo\n    echo \"Number           Key  Description\"\n    echo \"---------------------------------------------------\"\n    echo \"     1        nvfort  nvidia parallel\"\n    echo \"     2         gfort  gfortran parallel\"\n    echo \"     3     ifx|ifort  intel parallel\"\n    echo \"     4          cray  cray (ftn) parallel\"\n    echo \"     5     ifort_omp  intel openmp\"\n    echo \"     6 intel.cray_xc  intel parallel (cray_xc)\"\n    echo \"     0          exit  exit\"\n    echo\n    read -p \"Enter selection: \" theArgument\n    echo\nfi\n\n## remove case sensitivity\ntheArgument=`echo $theArgument | tr '[:upper:]' '[:lower:]'`\n\n\n###################################\n## What to do with the choice\n\nif [[ \"$theArgument\" == \"1\" ]] || [[ \"$theArgument\" == \"nvfort\" ]]; then\n    cp arc/macros.mpp.linux macros\n    cp arc/Makefile.mpp Makefile.comm\n    echo \"Configured: nvfort\"\nfi\n\nif [[ \"$theArgument\" == \"2\" ]] || [[ \"$theArgument\" == \"gfort\" ]]; then\n    cp arc/macros.mpp.gfort macros\n    cp arc/Makefile.mpp Makefile.comm\n    echo \"Configured: gfort\"\nfi\n\nif [[ \"$theArgument\" == \"3\" ]] || [[ \"$theArgument\" =~ ^(ifort|ifx|intel)$ ]]; then\n    cp arc/macros.mpp.ifort macros\n    echo \"Configured: Intel\"\n    cp arc/Makefile.mpp Makefile.comm\nfi\n\nif [[ \"$theArgument\" == \"4\" ]] || [[ \"$theArgument\" == \"cray\" ]]; then\n    cp arc/macros.mpp.cray_fortran macros\n    cp arc/Makefile.mpp Makefile.comm\n    echo \"Configured: Cray Fortran PrgEnv\"\nfi\n\n\nif [[ \"$theArgument\" == \"5\" ]] || [[ \"$theArgument\" == \"ifort_omp\" ]]; then\n    cp arc/macros.mpp.ifort.omp macros\n    echo \"Configured: ifort with OpenMP\"\n    cp arc/Makefile.mpp Makefile.comm\nfi\n\nif [[ \"$theArgument\" == \"6\" ]] || [[ \"$theArgument\" == \"intel.cray_xc\" ]]; then\n    cp arc/macros.mpp.intel.cray_xc macros\n    cp arc/Makefile.mpp Makefile.comm\n    echo \"Configured: ifort on cray_xc\"\nfi\n\n\n\n## The above result in a new macros file which was\n## previously deleted. If it does not exist, none\n## were chosen.\nif [[ ! -e macros ]]; then\n    echo \"No compiler selected. Exiting\"\n    if [[ -e macros.tmp ]]; then rm -f macros.tmp; fi\n    # failure\n    exit 1\nfi\n\nif [[ -e macros.tmp ]]; then\n    cat macros macros.tmp > macros.a\n    rm -f macros.tmp\n    mv macros.a macros\nfi\n\n## success\nexit 0\n"
  },
  {
    "path": "src/deprecated/README.build.txt",
    "content": "This file describes how to build WRF-Hydro both as a standalone modeling system\n(Section #1) and as a library coupled within the Weather Research and Forecasting\n(WRF) atmospheric modeling system (Section #2).\n\nSection #1: Building the standalone WRF-Hydro system\n\nThe following steps describe the process of building WRF-Hydro as a standalone\nmodeling system.\n\n1. Obtain the source code for WRF-Hydro\n\n   The source code for the latest WRF-Hydro release can be obtained here:\n   https://github.com/NCAR/wrf_hydro/releases/latest\n\n   Download and unpack the source code and navigate to the directory where you will\n   compile the code:\n\n   cd  wrf_hydro/src\n\n2. Set the required environment variables\n\n   First ensure the environment variables describing where your netCDF libraries live\n   are set appropriately so that the compiler can find them.  For a bash shell the\n   following should work with <PATH> replaced by the installation prefix for your\n   netCDF libraries.\n\n   export NETCDF_INC\"<PATH>/include\"\n   export NETCDF_LIB=\"<PATH>/lib\"\n\n   Then copy over the setEnvar.sh script from the 'template' directory and edit\n   the WRF-Hydro environment variables / compile time options in the file as needed.\n   This file can then be passed to the compile scripts below which will source the\n   environment variable for you or alternatively these environment variables can be set\n   by the user.\n\n3. Configure\n\n   To configure the model run the following and select the appropriate option for\n   your system / compiler:\n\n   ./configure\n\n4. Compile\n\n   To compile the model run the compile script with the name corresponding to the\n   land surface model (i.e. Noah or NoahMP) you would like to be utilized within\n   WRF-Hydro and pass the file containing the WRF-Hydro environment variables /\n   compile time options as an argument:\n\n   ./compile_offline_Noah.sh setEnvar.sh\n   OR\n   ./compile_offline_NoahMP.sh setEnvar.sh\n\n   This should result in the creation of a 'Run' directory populated with the\n   appropriate parameter tables and namelist for the land surface model selected\n   as well as the hydro namelist and a model executable that is then symlinked to\n   wrf_hydro.exe.\n\n   Note that as mentioned above passing the environment variable file as an argument\n   is optional. However, if this is not passed the desired environment variables\n   must be set prior to running the compile script.\n\n\nSection #2: Building the coupled WRF | WRF-Hydro system\n\nThe following steps describe the process of building WRF-Hydro as a library that is\ncoupled into the Weather Research and Forecasting (WRF) atmospheric modeling system.\nThe calling of WRF-Hydro within the WRF modeling system is controlled by a macro\ndefinition (WRF_HYDRO) that is specified as an environment variable prior to the\ncompilation process.  When WRF-Hydro is not activated via this setting, only the\nstandard WRF model will be built.\n\n1. Obtain the source code for WRF and WRF-Hydro\n\n   The source code for the latest WRF-Hydro release can be obtained here:\n   https://github.com/NCAR/wrf_hydro/releases/latest\n\n   The source code for WRF and WPS can be obtained here:\n   http://www2.mmm.ucar.edu/wrf/users/downloads.html\n\n2. Unpack the code and move the WRF-Hydro source code to the proper location within the\n   WRF directory structure\n\n   Unpack the code for WRF and WPS as you normally would to build the WRF model. Then\n   unpack the WRF-Hydro code and move the top directory into the WRFV3 directory.\n\n2. Set the required environment variables\n\n   Edit the WRF-Hydro environment variables as needed in a copy of the\n   wrf_hydro/src/template/setEnvar.sh script and source this script to set the\n   necessary variables:\n\n   source setEnvar.sh\n\n3. Build the coupled WRF | WRF-Hydro executable\n\n   Now build the WRF model as you normally would.\n\nNote that when running in coupled model you will need to copy the hydro.namelist and\nrequired parameter files into the WRF run directory.  More details are included in the\nTechnical Description and User's Guide that can be found on the project webpage:\nhttps://ral.ucar.edu/projects/wrf_hydro\n"
  },
  {
    "path": "src/deprecated/build_install.sh",
    "content": "#!/bin/sh\n\nSORCnwm=`pwd`\nEXECnwm=`pwd`/../../exec\nMODULEFILESnwm=`pwd`/../../modulefiles\nexport MODULEPATH=$MODULEPATH:$MODULEFILESnwm\n\nif [ ! -e $EXECnwm ]; then mkdir $EXECnwm; fi\n\n. $MODULESHOME/etc/modules.sh\nmodule purge\nmodule load nwm/v1.1 \nmodule list\n\nset -aux\n\ncd $SORCnwm\n\n# ============= wrf-hydro nudging  ===================\n# Turn on Nudging model\nexport WRF_HYDRO_NUDGING=1\n\n# Run configuration file\n./configure <<RUNME\n9\n\\r\nRUNME\n\n# Nudging compiling\nmake clean\n\n./compile_offline_NoahMP.sh\n\ncp -p Run/wrf_hydro.exe $EXECnwm/nwm.exe\n\nrm -f LandModel LandModel_cpl Land_models/NoahMP/MPP macros Makefile.comm\n\n"
  },
  {
    "path": "src/deprecated/build_install_theia.sh",
    "content": "#!/bin/sh\n\nSORCnwm=`pwd`\nEXECnwm=`pwd`/../../exec\n#MODULEFILESnwm=`pwd`/../../modulefiles\n#export MODULEPATH=$MODULEPATH:$MODULEFILESnwm\n#\n#. $MODULESHOME/etc/modules.sh\nmodule purge\nmodule load intel/15.3.187 impi\nmodule load netcdf/4.3.0\nmodule load hdf5\n\nexport NETCDF_INC=$NETCDF/include\nexport NETCDF_LIB=$NETCDF/lib\n\nset -aux\n\ncd $SORCnwm\n\n# ============= wrf-hydro ===================\n\n# Run configuration file\n./configure <<RUNME\n10\n\\r\nRUNME\n\n# Offline compiling\nmake clean\n\n./compile_offline_NoahMP.sh\n\ncp -p Run/wrf_hydro.exe $EXECnwm/nwm.exe\n\n\n# ============= wrf-hydro nudging  ===================\n# Turn on Nudging model\nexport WRF_HYDRO_NUDGING=1\n\n# Run configuration file\n./configure <<RUNME\n10\n\\r\nRUNME\n\n# Nudging compiling\nmake clean\n\n./compile_offline_NoahMP.sh\n\ncp -p Run/wrf_hydro.exe $EXECnwm/nwm_nudging.exe\n\nrm -f LandModel LandModel_cpl Land_models/NoahMP/MPP macros Makefile.comm\n\n"
  },
  {
    "path": "src/hrldas_namelists.json",
    "content": "{\n    \"base\": {\n        \"noahlsm_offline\": {\n            \"btr_option\": 1,\n            \"canopy_stomatal_resistance_option\": 1,\n            \"dynamic_veg_option\": 4,\n            \"forcing_timestep\": \"NULL_specified_in_domain.json\",\n            \"frozen_soil_option\": 1,\n            \"glacier_option\": 2,\n            \"hrldas_setup_file\": \"NULL_specified_in_domain.json\",\n            \"indir\": \"NULL_specified_in_domain.json\",\n            \"khour\": 144,\n            \"noah_timestep\": 3600,\n            \"nsoil\": 4,\n            \"outdir\": \"./\",\n            \"output_timestep\": 3600,\n            \"pcp_partition_option\": 1,\n            \"radiative_transfer_option\": 3,\n            \"restart_filename_requested\": \"NULL_specified_in_domain.json\",\n            \"restart_frequency_hours\": 24,\n            \"rst_bi_in\": 0,\n            \"rst_bi_out\": 0,\n            \"runoff_option\": 3,\n            \"snow_albedo_option\": 1,\n            \"soil_thick_input\": [0.1, 0.3, 0.6, 1.0],\n            \"spatial_filename\": \"NULL_specified_in_domain.json\",\n            \"split_output_count\": 1,\n            \"start_day\": \"NULL_specified_in_domain.json\",\n            \"start_hour\": \"NULL_specified_in_domain.json\",\n            \"start_min\": \"NULL_specified_in_domain.json\",\n            \"start_month\": \"NULL_specified_in_domain.json\",\n            \"start_year\": \"NULL_specified_in_domain.json\",\n            \"supercooled_water_option\": 1,\n            \"surface_drag_option\": 1,\n            \"surface_resistance_option\": 4,\n            \"tbot_option\": 2,\n            \"temp_time_scheme_option\": 3,\n            \"zlvl\": 10.0\n        },\n        \"wrf_hydro_offline\": {\n            \"forc_typ\": \"NULL_specified_in_domain.json\"\n        }\n    },\n\n    \"nwm_ana\": {\n        \"noahlsm_offline\": {\n            \"runoff_option\": 7\n        },\n        \"wrf_hydro_offline\": {}\n    },\n\n    \"nwm_long_range\" : {\n        \"noahlsm_offline\": {\n            \"runoff_option\": 7\n        },\n        \"wrf_hydro_offline\": {}\n    },\n\n    \"nwm_hi_ana\" : {\n        \"noahlsm_offline\": {\n            \"snow_albedo_option\": 2\n        },\n        \"wrf_hydro_offline\": {}\n    },\n\n    \"nwm_channel-only\" : {\n        \"noahlsm_offline\": {},\n        \"wrf_hydro_offline\": {}\n    },\n\n    \"nwm_output_ana\" : {\n        \"noahlsm_offline\": {\n            \"runoff_option\": 7,\n            \"khour\": 1,\n            \"restart_frequency_hours\": 1\n\t},\n        \"wrf_hydro_offline\": {}\n    },\n\n    \"nwm_output_long_range\" : {\n        \"noahlsm_offline\": {\n            \"runoff_option\": 7,\n            \"khour\": 1,\n            \"restart_frequency_hours\": 1\n\t},\n        \"wrf_hydro_offline\": {}\n    },\n\n    \"gridded\": {\n        \"noahlsm_offline\": {},\n        \"wrf_hydro_offline\": {}\n    },\n\n    \"gridded_no_lakes\": {\n        \"noahlsm_offline\": {},\n        \"wrf_hydro_offline\": {}\n    },\n\n    \"reach\": {\n        \"noahlsm_offline\": {},\n        \"wrf_hydro_offline\": {}\n    }\n}\n\n"
  },
  {
    "path": "src/hydro_namelists.json",
    "content": "{\n    \"base\": {\n        \"hydro_nlist\": {\n            \"aggfactrt\": 4,\n            \"channel_option\": 2,\n            \"channel_loss_option\": 0,\n            \"chanobs_domain\": 1,\n            \"chanrtswcrt\": 1,\n            \"chrtout_domain\": 1,\n            \"chrtout_grid\": 1,\n            \"compound_channel\": true,\n            \"dtrt_ch\": 300,\n            \"dtrt_ter\": 10,\n            \"dxrt\": 250,\n            \"frxst_pts_out\": 0,\n            \"geo_finegrid_flnm\": \"NULL_specified_in_domain.json\",\n            \"geo_static_flnm\": \"NULL_specified_in_domain.json\",\n            \"gw_restart\": 1,\n            \"gwbaseswcrt\": 4,\n            \"gwbuckparm_file\": \"NULL_specified_in_domain.json\",\n            \"hydrotbl_f\": \"NULL_specified_in_domain.json\",\n            \"igrid\": 1,\n            \"io_config_outputs\": 0,\n            \"io_form_outputs\": 4,\n            \"lake_option\": 1,\n            \"land_spatial_meta_flnm\": \"NULL_specified_in_domain.json\",\n            \"lsmout_domain\": 1,\n            \"nsoil\": 4,\n            \"order_to_write\": 1,\n            \"out_dt\": 60,\n            \"outlake\": 1,\n            \"output_channelbucket_influx\": 0,\n            \"output_gw\": 1,\n            \"ovrtswcrt\": 1,\n            \"restart_file\": \"NULL_specified_in_domain.json\",\n            \"route_lake_f\": \"NULL_specified_in_domain.json\",\n            \"route_link_f\": \"NULL_specified_in_domain.json\",\n            \"rst_bi_in\": 0,\n            \"rst_bi_out\": 0,\n            \"rst_dt\": 1440,\n            \"rst_typ\": 1,\n            \"rstrt_swc\": 0,\n            \"rt_option\": 1,\n            \"rtout_domain\": 1,\n            \"split_output_count\": 1,\n            \"subrtswcrt\": 1,\n            \"sys_cpl\": 1,\n            \"t0outputflag\": 1,\n            \"udmap_file\": \"NULL_specified_in_domain.json\",\n            \"udmp_opt\": 1,\n            \"zsoil8\": [-0.1, -0.4, -1.0, -2.0]\n        },\n        \"reservoir_nlist\": {\n            \"reservoir_persistence_usgs\": false\n        },\n        \"nudging_nlist\": {\n            \"biaswindowbeforet0\": false,\n            \"invdisttimeweightbias\": true,\n            \"maxagepairsbiaspersist\": 3,\n            \"minnumpairsbiaspersist\": 1,\n            \"nlastobs\": 480,\n            \"noconstinterfbias\": false,\n            \"nudginglastobsfile\": \"NULL_specified_in_domain.json\",\n            \"nudgingparamfile\": \"NULL_specified_in_domain.json\",\n            \"persistbias\": true,\n            \"readtimesliceparallel\": true,\n            \"temporalpersistence\": true,\n            \"timeslicepath\": \"NULL_specified_in_domain.json\"\n        }\n    },\n\n    \"nwm_ana\": {\n        \"hydro_nlist\": {},\n        \"nudging_nlist\": {}\n    },\n\n    \"nwm_long_range\": {\n        \"hydro_nlist\": {\n            \"aggfactrt\": 1,\n            \"dxrt\": 1000,\n            \"ovrtswcrt\": 0,\n            \"rst_typ\": 0,\n            \"rtout_domain\": 0,\n            \"subrtswcrt\": 0\n        },\n        \"nudging_nlist\": {\n            \"maxagepairsbiaspersist\": 24,\n            \"persistbias\": false\n        }\n    },\n\n    \"nwm_hi_ana\": {\n        \"hydro_nlist\": {\n            \"compound_channel\": false,\n            \"out_dt\": 60,\n            \"aggfactrt\": 10,\n            \"dxrt\": 100\n       },\n        \"nudging_nlist\": {}\n    },\n\n    \"nwm_channel-only\": {\n        \"hydro_nlist\": {\n            \"lsmout_domain\": 0,\n            \"output_gw\": 0,\n            \"output_channelbucket_influx\": 2\n        },\n        \"nudging_nlist\": {}\n    },\n\n    \"nwm_channel-only_forecasts\": {\n        \"hydro_nlist\": {\n            \"lsmout_domain\": 0,\n            \"output_gw\": 0,\n            \"output_channelbucket_influx\": 2\n        },\n        \"reservoir_nlist\": {\n            \"reservoir_persistence_usgs\": false\n        },\n        \"nudging_nlist\": {}\n    },\n\n    \"nwm_output_ana\": {\n        \"hydro_nlist\": {\n            \"chanobs_domain\": 0,\n            \"chrtout_grid\": 0,\n\t    \"io_config_outputs\": 1,\n            \"io_form_outputs\": 2,\n\t    \"lsmout_domain\": 0,\n\t    \"output_channelbucket_influx\": 2,\n\t    \"output_gw\": 0,\n\t    \"rst_dt\": 60\n\t},\n        \"nudging_nlist\": {}\n    },\n\n    \"nwm_output_long_range\": {\n        \"hydro_nlist\": {\n            \"aggfactrt\": 1,\n            \"chanobs_domain\": 0,\n            \"chrtout_grid\": 0,\n            \"dxrt\": 1000,\n            \"io_config_outputs\": 4,\n            \"io_form_outputs\": 2,\n            \"lsmout_domain\": 0,\n            \"out_dt\": 60,\n            \"output_gw\": 0,\n            \"ovrtswcrt\": 0,\n            \"rst_dt\": 60,\n            \"rst_typ\": 0,\n            \"rtout_domain\": 0,\n            \"subrtswcrt\": 0\n        },\n        \"nudging_nlist\": {\n            \"maxagepairsbiaspersist\": 24,\n            \"persistbias\": false\n        }\n    },\n\n    \"gridded\": {\n        \"hydro_nlist\": {\n            \"compound_channel\": false,\n            \"gwbaseswcrt\": 1,\n            \"gwbasmskfil\": \"NULL_specified_in_domain.json\",\n            \"channel_option\": 3,\n            \"dtrt_ch\": 10,\n            \"rstrt_swc\": 1,\n            \"udmp_opt\": 0\n        },\n        \"nudging_nlist\": {\n            \"biaswindowbeforet0\": \"\",\n            \"invdisttimeweightbias\": \"\",\n            \"maxagepairsbiaspersist\": \"\",\n            \"minnumpairsbiaspersist\": \"\",\n            \"nlastobs\": \"\",\n            \"noconstinterfbias\": \"\",\n            \"nudginglastobsfile\": \"\",\n            \"nudgingparamfile\": \"\",\n            \"persistbias\": \"\",\n            \"readtimesliceparallel\": \"\",\n            \"temporalpersistence\": \"\",\n            \"timeslicepath\": \"\"\n        }\n    },\n\n    \"gridded_no_lakes\": {\n        \"hydro_nlist\": {\n            \"compound_channel\": false,\n            \"gwbaseswcrt\": 1,\n            \"gwbasmskfil\": \"NULL_specified_in_domain.json\",\n            \"channel_option\": 3,\n            \"dtrt_ch\": 10,\n            \"rstrt_swc\": 1,\n            \"udmp_opt\": 0,\n            \"lake_option\": 0\n        },\n        \"nudging_nlist\": {\n            \"biaswindowbeforet0\": \"\",\n            \"invdisttimeweightbias\": \"\",\n            \"maxagepairsbiaspersist\": \"\",\n            \"minnumpairsbiaspersist\": \"\",\n            \"nlastobs\": \"\",\n            \"noconstinterfbias\": \"\",\n            \"nudginglastobsfile\": \"\",\n            \"nudgingparamfile\": \"\",\n            \"persistbias\": \"\",\n            \"readtimesliceparallel\": \"\",\n            \"temporalpersistence\": \"\",\n            \"timeslicepath\": \"\"\n        }\n    },\n\n    \"reach\": {\n        \"hydro_nlist\": {\n            \"compound_channel\": false,\n            \"gwbaseswcrt\": 1,\n            \"gwbasmskfil\": \"NULL_specified_in_domain.json\",\n            \"dtrt_ch\": 10,\n            \"outlake\": 0,\n            \"lake_option\": 0,\n            \"rstrt_swc\": 0,\n            \"t0outputflag\": 0,\n            \"udmp_opt\": 0\n        },\n        \"nudging_nlist\": {\n            \"biaswindowbeforet0\": \"\",\n            \"invdisttimeweightbias\": \"\",\n            \"maxagepairsbiaspersist\": \"\",\n            \"minnumpairsbiaspersist\": \"\",\n            \"nlastobs\": \"\",\n            \"noconstinterfbias\": \"\",\n            \"nudginglastobsfile\": \"\",\n            \"nudgingparamfile\": \"\",\n            \"persistbias\": \"\",\n            \"readtimesliceparallel\": \"\",\n            \"temporalpersistence\": \"\",\n            \"timeslicepath\": \"\"\n        }\n    }\n}\n"
  },
  {
    "path": "src/nudging/CMakeLists.txt",
    "content": "# build the version static library\nadd_library(hydro_nudging STATIC\n        module_date_utils_nudging.F90\n        module_nudging_utils.F90\n        module_stream_nudging.F90\n)\n\ntarget_link_libraries(hydro_nudging PRIVATE\n        hydro_nudging_io\n        hydro_mpp\n        hydro_data_rec\n        hydro_orchestrator\n)\n"
  },
  {
    "path": "src/nudging/Makefile",
    "content": "# Makefile\n#\n.SUFFIXES:\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nOBJS = \\\n\tmodule_date_utils_nudging.o \\\n\tmodule_stream_nudging.o \\\n\tmodule_nudging_io.o \\\n\tmodule_nudging_utils.o\n\n\nall:\t$(OBJS)\n\n#module_RT.o: module_RT.F90\n#\t@echo \"\"\n#\t$(CPP) $(CPPFLAGS) $(*).F90 > $(*).f90\n#\t$(COMPILER90) -o $(@) $(F90FLAGS) $(MODFLAG)  $(*).f90\n#\t$(RMD) $(*).f90\n#\t@echo \"\"\n#\tcp *.mod ../mod\n\n.F90.o:\n\t@echo \"\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -o $(@) $(F90FLAGS) $(MODFLAG) -I$(NETCDF_INC) $(*).F90\n\t@echo \"\"\n\tar -r ../lib/libHYDRO.a $(@)\n\tcp *.mod ../mod\n\n#\n# Dependencies:\n#\nmodule_nudging_io.o: ../Data_Rec/module_namelist.o \\\n\t             module_date_utils_nudging.o\n\nmodule_stream_nudging.o: module_nudging_utils.o \\\n\t      \t\t module_nudging_io.o\n\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/nudging/Nudging_frxst_gage.csv",
    "content": "!Header lines with ! comment are allowed. \n!Remaining lines are comma separated values\n!Only two columns are used, additional are ignored but might be helpful to you.\n!frxst_pts(as in Fulldom.*.nc), gageId (as in timeslice files), ignored....\n1,06730200,BOULDER_CREEK_AT_NORTH_75TH_ST._NEAR_BOULDER_CO\n2,06730160,FOURMILE_CANYON_CREEK_NEAR_SUNSHINE_CO\n3,06727410,FOURMILE_CREEK_AT_LOGAN_MILL_ROAD_NEAR_CRISMAN_CO\n4,06727500,FOURMILE_CREEK_AT_ORODELL_CO"
  },
  {
    "path": "src/nudging/io/CMakeLists.txt",
    "content": "# build the version static library\nadd_library(hydro_nudging_io STATIC\n        module_nudging_io.F90\n)\n\ntarget_link_libraries(hydro_nudging_io PRIVATE\n        hydro_orchestrator\n        hydro_data_rec\n        hydro_mpp\n)\n"
  },
  {
    "path": "src/nudging/io/module_nudging_io.F90",
    "content": "module module_nudging_io\n\nuse netcdf\nuse config_base, only: nlst\nuse module_RT_data,  only: rt_domain\nuse module_hydro_stop, only: HYDRO_stop\n\nimplicit none\n\n!========================\n! lastObs structure, corresponding to nudgingLastObs.YYYY-mm-dd_HH:MM:ss.nc\n! How observations from the past are carried forward.\n! This type is extended in module_stream_nudging\ntype lastObsStructure\n   character(len=15)                            :: usgsId\n   real,              allocatable, dimension(:) :: lastObsDischarge\n   real,              allocatable, dimension(:) :: lastObsModelDischarge\n   character(len=19), allocatable, dimension(:) :: lastObsTime\n   real,              allocatable, dimension(:) :: lastObsQuality\nend type lastObsStructure\n\ntype lastObsStructure_SoA\n   character(len=15), allocatable, dimension(:)   :: usgsId\n   real,              allocatable, dimension(:,:) :: lastObsDischarge\n   real,              allocatable, dimension(:,:) :: lastObsModelDischarge\n   character(len=19), allocatable, dimension(:,:) :: lastObsTime\n   real,              allocatable, dimension(:,:) :: lastObsQuality\nend type lastObsStructure_SoA\n\ninteger, parameter :: did = 1\n\ncontains\n\n!===================================================================================================\n! Program Name:\n!   subroutine find_timeslice_file\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Return a single file path/names of timeslice files given a single date.\n! History Log:\n!   6/4/15 - Created,\n! Usage:\n! Parameters:\n!   q\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: namelist option for nlst_rt(did)%timeSlicePath\n! Notes:\n\nfunction find_timeslice_file(date, obsResolution)\nimplicit none\ncharacter(len=256) :: find_timeslice_file      ! Output\ncharacter(len=19), intent(in) :: date          ! Input\ncharacter(len=2),  intent(in) :: obsResolution ! Input\n!Internals\ncharacter(len=256) :: tmpTimeSlice\nlogical :: fileExists\n\n#ifdef HYDRO_D\nprint*,'Ndg: start find_timeslice_file'\ncall flush(6)\n#endif\n\nfind_timeslice_file=''\n! is there a file with this name?\n! note files are not resolved below minutes.\ntmpTimeSlice = trim(nlst(did)%timeSlicePath) // '/' //date // \".\" // &\n                    obsResolution // 'min.usgsTimeSlice.ncdf'\ninquire(FILE=tmpTimeSlice, EXIST=fileExists)\nif (fileExists) find_timeslice_file = trim(tmpTimeSlice)\n\n#ifdef HYDRO_D\nprint*,'Ndg: timeSlice file: ', tmpTimeSlice\nprint*,'Ndg: file found: ', fileExists\nprint*,'Ndg: finish find_timeslice_file'\ncall flush(6)\n#endif\n\nend function find_timeslice_file\n\n!===================================================================================================\n! Program Name:\n!   subroutine read_timeslice_file\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Return the contents of a timeslice file.\n! History Log:\n!   6/4/15 - Created,\n! Usage:\n! Parameters:\n!\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: namelist option for nlst_rt(did)%timeSlicePath\n! Notes:\n\nsubroutine read_timeslice_file(  &\n     timeSliceFile,              &  !! IN: char, file path/name\n     sanityQcDischarge,          &  !! IN: perform sanity check qc?\n     sliceTime,                  &  !! OUT: the file time.\n     updateTime,                 &  !! OUT: the time the file was updated.\n     sliceResolution,            &  !! OUT: temporal resolution of the file in minutes.\n     gageId,                     &  !! OUT: integer, the USGS gage ID.\n     gageTime,                   &  !! OUT: output converted for comparision to model time??\n     gageQC,                     &  !! OUT: quality control flag for discharge\n     gageDischarge,              &  !! OUT: real, the m3/s observed discharge\n     fatalErr,                   &  !! IN:  logical, are IO errors fatal?\n     errStatus                   &  !! OUT: count of errors encountered\n                                 )\n\nimplicit none\ncharacter(len=256), intent(in)                :: timeSliceFile\nlogical,            intent(in)                :: sanityQcDischarge\ncharacter(len=19),  intent(out)               :: sliceTime\ncharacter(len=19),  intent(out)               :: updateTime\ncharacter(len=2),   intent(out)               :: sliceResolution\ncharacter(len=15),  intent(out), dimension(:) :: gageId\ncharacter(len=19),  intent(out), dimension(:) :: gageTime\nreal,               intent(out), dimension(:) :: gageQC\nreal,               intent(out), dimension(:) :: gageDischarge\nlogical,            intent(in)                :: fatalErr\ninteger,            intent(out)               :: errStatus\n\ninteger*2, allocatable, dimension(:) :: gageQCIn\ninteger :: iRet, ncId, fileNameLen, errStatusOut\ncharacter(len=19) :: caller\nreal, parameter :: zero = 0.0000000000000\nreal, parameter :: oneHundred = 100.0000000000000\n\n#ifdef HYDRO_D\nprint*,'Ndg: start read_timeslice_file'\nwrite(*,'(\"Ndg: read_timeslice_file: ''\", A, \"''\")') trim(timeSliceFile)\ncall flush(6)\n#endif\n\ncaller = 'read_timeslice_file'\nerrStatus=0\n\niRet = nf90_open(trim(timeSliceFile), nf90_nowrite, ncid)\nif (iRet /= nf90_NoErr) then\n   write(*,'(\"Problem opening timeSliceFile: ''\", A, \"''\")') trim(timeSliceFile)\n   if(fatalErr) call hydro_stop('read_timeslice_file')\n   errStatus=errStatus+1\nendif\n\n!! global atts\niRet = nf90_get_att(ncid, nf90_global, 'sliceCenterTimeUTC',         sliceTime)\nif (iRet /= nf90_NoErr) errStatus=errStatus+1\niRet = nf90_get_att(ncid, nf90_global, 'fileUpdateTimeUTC',          updateTime)\nif (iRet /= nf90_NoErr) errStatus=errStatus+1\niRet = nf90_get_att(ncid, nf90_global, 'sliceTimeResolutionMinutes', sliceResolution)\nif (iRet /= nf90_NoErr) errStatus=errStatus+1\n\n! variables\ncall get_1d_netcdf(ncid, 'stationId', gageId,        caller, &\n                        fatalErr, errStatusOut)\nerrStatus=errStatus+errStatusOut\ncall get_1d_netcdf(ncid, 'time',      gageTime,      caller, &\n                        fatalErr, errStatusOut)\nerrStatus=errStatus+errStatusOut\ncall get_1d_netcdf_real(ncid, 'discharge', gageDischarge, caller, &\n                        fatalErr, errStatusOut)\nerrStatus=errStatus+errStatusOut\n\n!! the quality short integer needs scaled\nallocate(gageQCIn(size(gageQC)))\ncall get_1d_netcdf_int2(ncid, 'discharge_quality', gageQCIn,        caller, &\n                        fatalErr, errStatusOut)\nerrStatus=errStatus+errStatusOut\ngageQC=gageQCIn/oneHundred\ndeallocate(gageQCIn)\n\n!! JLM TODO fix temporary hardwire QC sanity checks\nif (sanityQcDischarge) then\n   !! First, quality check on the quality flag!\n   where(gageQC .lt. 0 .or. gageQC .gt. 1) gageQC=0\n   !! Now flow QC.\n   where(gageDischarge .le. 0.000) gageQC=0\n   !! peak flow on MS river *2\n   !! http://nwis.waterdata.usgs.gov/nwis/peak?site_no=07374000&agency_cd=USGS&format=html\n   !! baton rouge 1945: 1,473,000cfs=41,711cms, multiply it roughly by 2\n   where(gageDischarge .ge. 90000.0) gageQC=0\n   if(any(gageQc .eq. 0)) then\n      write(6,*) 'Ndg: some gageQC set to zero'\n   endif\nendif\n\niRet = nf90_close(ncId)\nif (iRet /= nf90_NoErr) then\n   write(*,'(\"Problem closing timeSliceFile: ''\", A, \"''\")') trim(timeSliceFile)\n   if(fatalErr) call hydro_stop('read_timeslice_file')\n   errStatus=errStatus+1\nendif\n\n#ifdef HYDRO_D\nprint*,'Ndg: finish read_timeslice_file'\ncall flush(6)!\n#endif\n\nend subroutine read_timeslice_file\n\n!===================================================================================================\n! Program Name:\n!   subroutine read_reach_gage_collocation\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Read the gages column from the \"RouteLink.nc\" netcdf file specifing the channel topology.\n! History Log:\n!   7/20/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n!   netcdf file RouteLink.nc or other name ending with .nc.\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes: Currently no csv support, but basic code is in place though commented out.\n\nsubroutine read_reach_gage_collocation(gageIds)\n  use config_base, only: nlst\nimplicit none\ncharacter(len=15), dimension(:), intent(out) :: gageIds\n!integer, dimension(:), intent(out) :: gageIds\n\ninteger               :: ncid , iRet, varId\nlogical               :: fatal_if_error\ncharacter(len=256) :: route_link_f_r, route_link_f, varName\ninteger :: lenRouteLinkFR ! so the preceeding var chan be changed without changing code\nlogical :: routeLinkNetcdf\n\n#ifdef HYDRO_D\nprint*,'Ndg: Starting read_reach_gage_collocation'\n#endif\n\nvarName = 'gages'\n!! is RouteLink file netcdf (*.nc) or csv (*.csv)\nroute_link_f   = nlst(did)%route_link_f\nroute_link_f_r = adjustr(route_link_f)\nlenRouteLinkFR = len(route_link_f_r)\nrouteLinkNetcdf = route_link_f_r( (lenRouteLinkFR-2):lenRouteLinkFR) .eq. '.nc'\n\nif(routeLinkNetcdf) then\n\n!! part of this could become a get_1d_netcdf\n   iRet = nf90_open(trim(route_link_f), nf90_NoWrite, ncId)\n   if (iRet /= nf90_NoErr) then\n      write(6,'(\"read_reach_gage_collocation: Problem opening file ''\", A, \"''\")') trim(route_link_f)\n      call hydro_stop(\"read_reach_gage_collocation\")\n   endif\n\n   iRet = nf90_inq_varid(ncid, varName, varid)\n   if (iRet /= nf90_NoErr) then\n      print*,\"Ndg: read_reach_gage_collocation: variable: \" // trim(varName)\n      call hydro_stop(\"read_reach_gage_collocation\")\n   end if\n\n   iRet = nf90_get_var(ncid, varid, gageIds)\n   if (iRet /= nf90_NoErr) then\n      print*,\"Ndg: read_reach_gage_collocation: value: \" // trim(varName)\n      call hydro_stop(\"read_reach_gage_collocation\")\n   end if\n\n   iRet = nf90_close(ncid)\n   if (iRet /= nf90_NoErr) then\n      print*,\"Ndg: read_reach_gage_collocation: closing: \" // trim(varName)\n      call hydro_stop(\"read_reach_gage_collocation\")\n   end if\n\nelse\n   call hydro_stop('read_reach_gage_collocation: csv not currently supported.')\n   !! here's some code to start from if/when we do want to support csv for this.\n   !open(unit=79,file=trim(route_link_f),form='formatted',status='old')\n   !read(79,*)  header\n   !print *, \"header \", header, \"NLINKSL = \", NLINKSL, GNLINKSL\n   !call flush(6)\n   !do i=1,GNLINKSL\n   !   read (79,*) tmpLINKID(i),   tmpFROM_NODE(i), tmpTO_NODE(i), tmpCHLON(i),    &\n   !        tmpCHLAT(i),    tmpZELEV(i),     tmpTYPEL(i),   tmpORDER(i),    &\n   !        tmpQLINK(i,1),  tmpMUSK(i),      tmpMUSX(i),    tmpCHANLEN(i),  &\n   !        tmpMannN(i),    tmpSo(i),        tmpChSSlp(i),  tmpBw(i),       &\n   !        tmpChannK(i),                                                   &\n   !        tmpHRZAREA(i),  tmpLAKEMAXH(i),  tmpWEIRC(i),   tmpWEIRL(i),    &\n   !        tmpORIFICEC(i), tmpORIFICEA(i),  tmpORIFICEE(i)\n   !   ! if (So(i).lt.0.005) So(i) = 0.005  !-- impose a minimum slope requireement\n   !   if (tmpORDER(i) .gt. MAXORDER) MAXORDER = tmpORDER(i)\n   !end do\n   !close(79)\nend if ! routeLinkNetcdf\n\n#ifdef HYDRO_D\nprint*,'Ndg: Finish read_reach_gage_collocation'\ncall flush(6)\n#endif\n\nend subroutine read_reach_gage_collocation\n\n!===================================================================================================\n! Program Name:\n!   subroutine read_gridded_nudging_frxst_gage_csv\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   For gridded channel routine, the mechanism is to use forecast points to\n!   identify gages. This file determines the collocation of the two. See the\n!   file in the nudging/ directory for more info.\n! History Log:\n!   6/22/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files: Nudging_frxst_gage.csv\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine read_gridded_nudging_frxst_gage_csv(frxstId, gageId, nGages)\nimplicit none\ninteger,           dimension(:), intent(out) :: frxstId\ncharacter(len=15), dimension(:), intent(out) :: gageId\ninteger,                         intent(out) :: nGages\n\ncharacter(len=5000) :: line\ninteger :: ii, colCount, lineCount, lastCommaPos, tmpInt\n\n#ifdef HYDRO_D\nprint*,'Ndg: start read_gridded_nudging_frxst_gage_csv'\n#endif\nfrxstId=-9999\n\nlineCount = 0\n\n#ifndef NCEP_WCOSS\nopen(117, file = 'Nudging_frxst_gage.csv' )\n#else\nopen(26)\n#endif\ndo\n#ifndef NCEP_WCOSS\n   read(117, '( a )', end = 200 ) line\n#else\n   read(26, '( a )', end = 200 ) line\n#endif\n   if( line( 1:1 ) == '!' ) cycle\n   colCount = 1\n   lastCommaPos = 0\n   do ii = 1, len( line )\n\n      if( line( ii:ii ) == '!' ) exit\n\n      if (ii .eq. 1) lineCount = lineCount + 1\n\n      if( line( ii:ii ) == ',' ) then\n         if(colCount .eq. 1) then\n            read (line((lastCommaPos+1):(ii-1)),'(I5)') tmpInt\n            frxstId(lineCount) = tmpInt\n         end if\n         if(colCount .eq. 2) gageId(lineCount)  =  trim(line((lastCommaPos+1):(ii-1)))\n         colCount = colCount + 1\n         lastCommaPos = ii\n      end if\n\n      if(colCount .eq. 3) cycle\n\n   end do\nend do\n\n#ifndef NCEP_WCOSS\nclose(117)\n#else\nclose(26)\n#endif\n\n200 continue\n\n#ifdef HYDRO_D\nnGages = lineCount\nprint*,\"Ndg: nGages: \",  nGages\nprint*,\"Ndg: frxstId: \", frxstId(1:nGages)\nprint*,\"Ndg: gageId:\",   gageId(1:nGages)\nprint*,'Ndg: finish read_gridded_nudging_frxst_gage_csv'\ncall flush(6)\n#endif\n\nend subroutine read_gridded_nudging_frxst_gage_csv\n\n!===================================================================================================\n! Program Name:\n!   subroutine read_nudging_param_file\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Set up the default nudging parameters with the model initialization.\n! History Log:\n!   6/22/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files: Nudging_frxst_gage.csv\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine read_nudging_param_file(  &\n     paramFile,                      &  !! IN: char, file path/name\n     gageId,                         &  !! OUT: integer, the USGS gage ID.\n     gageR,                          &  !! OUT: output converted for comparision to model time??\n     gageG,                          &  !! OUT: quality control flag for discharge\n     gageTau,                        &  !! OUT: real the half-window for NN/IDW interp\n     gageQThresh,                    &  !! OUT: real the half-window for NN/IDW interp\n     gageExpCoeff                    &  !! OUT: real, params for exponent-based temporal persistence\n)\nimplicit none\ncharacter(len=256), intent(in)                    :: paramFile\ncharacter(len=15),  intent(out), dimension(:)     :: gageId\nreal,               intent(out), dimension(:)     :: gageR\nreal,               intent(out), dimension(:)     :: gageG\nreal,               intent(out), dimension(:)     :: gageTau\nreal,               intent(out), dimension(:,:,:) :: gageQThresh\nreal,               intent(out), dimension(:,:,:) :: gageExpCoeff\n\ninteger :: iRet, ncId, varId, dimId, fileNameLen, errStatus\ncharacter(len=23) :: caller\n\n#ifdef HYDRO_D\nprint*,'Ndg: start read_nudging_param_file'\nwrite(*,'(\"Ndg: paramFile: ''\", A, \"''\")') trim(paramFile)\ncall flush(6)\n#endif\n\ncaller='read_nudging_param_file'\n\niRet = nf90_open(trim(paramFile), nf90_NoWrite, ncid)\nif (iRet /= nf90_NoErr) then\n   write(6,'(\"read_nudging_param_file: Problem opening file ''\", A, \"''\")') trim(paramFile)\n   call hydro_stop(\"read_nudging_param_file\")\nendif\n\ncall get_1d_netcdf(ncid, 'stationId', gageId,  caller, .TRUE., errStatus)\ncall get_1d_netcdf_real(ncid, 'R',         gageR,   caller, .TRUE., errStatus)\ncall get_1d_netcdf_real(ncid, 'G',         gageG,   caller, .TRUE., errStatus)\ncall get_1d_netcdf_real(ncid, 'tau',       gageTau, caller, .TRUE., errStatus)\n\nif(size(gageExpCoeff,2) .ne. 0 .and. size(gageExpCoeff,3) .ne. 0) then\n   call get_3d_netcdf_real(ncid, 'qThresh',  gageQThresh,  caller, .true., errStatus)\n   call get_3d_netcdf_real(ncid, 'expCoeff', gageExpCoeff, caller, .true., errStatus)\nend if\n\niRet = nf90_close(ncId)\nif (iRet /= nf90_NoErr) then\n   write(*,'(\"Problem closing paramFile: ''\", A, \"''\")') trim(paramFile)\n   call hydro_stop('read_nudging_param_file')\nendif\n\n#ifdef HYDRO_D\nprint*,'Ndg: finish read_nudging_param_file'\ncall flush(6)\n#endif\n\nend subroutine read_nudging_param_file\n\n\n!===================================================================================================\n! Subroutine Name:\n!   subroutine write_nwis_not_in_RLAndParams\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Write a log file of gages supplied by NWIS but which are not found in\n!   the intersection of our Route_Link gages and our parameter file gages.\n!   Perhaps they were not picked up by us as available,\n!   or they are simply not in NHD+.\n! History Log:\n!   11/04/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\n\nsubroutine write_nwis_not_in_RLAndParams( gageId, count )\nimplicit none\ncharacter(len=15), dimension(:),  intent(in) :: gageId\ninteger,                          intent(in) :: count\ninteger :: cc\n\n#ifndef NCEP_WCOSS\nopen (unit=919,file='NWIS_gages_not_in_RLAndParams.txt',status='unknown',position='append')\n#else\nopen (unit=27,status='unknown',position='append')\n#endif\n\ndo cc=1,count\n\n#ifndef NCEP_WCOSS\n   write(919,'(A15)') gageId(cc)\n#else\n   write(27,'(A15)') gageId(cc)\n#endif\n\nend do\n\n#ifndef NCEP_WCOSS\nclose(919)\n#else\nclose(27)\n#endif\n\nend subroutine write_nwis_not_in_RLAndParams\n\n\n!===================================================================================================\n! Subroutine Name:\n!   subroutine write_nudging_last_obs\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Write out the last observations collected over time.\n! History Log:\n!   02/03/16 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:  Needs better error handling...\n\nsubroutine write_nudging_last_obs(lastObsStr, modelTime, g_nudge)\n\nimplicit none\n\n!Arugments\ntype(lastObsStructure), intent(in), dimension(:) :: lastObsStr\ncharacter(len=19),      intent(in)               :: modelTime\nreal,                   intent(in), dimension(:) :: g_nudge\n\n! Local\ncharacter(len=37) :: outFileName\ninteger :: nSpace, nTime, nFeature, tt, ss\ninteger :: ncid, iret, varid, dimIdTimeStr, dimIdStnStr, dimIdNTime, dimIdNStn, dimIdNFeature\ncharacter(len=15), allocatable, dimension(:) :: charArr15\ncharacter(len=19), allocatable, dimension(:,:) :: charArr19\nreal,      allocatable, dimension(:,:) :: tmpFloat\ninteger*2, allocatable, dimension(:,:) :: qualityInt2\n\n#ifdef HYDRO_D\nprint*,'Ndg: start write_nudging_last_obs'\nflush(6)\n#endif\n\nnSpace = size(lastObsStr)\nnTime  = size(lastObsStr(1)%lastObsDischarge)\nnFeature = size(g_nudge)\n\n!           !1234567891123456789212345678931234567\noutFileName='nudgingLastObs.' // modelTime // '.nc'\n\n! create file\niret = nf90_create(outFileName, nf90_clobber, ncid)\n\n! create dimensions\n! station id has length of the number of gages\n! feature id has length of the number of reaches/features.\niret = nf90_def_dim(ncid, \"timeStrLen\",      19,             dimIdTimeStr)\niret = nf90_def_dim(ncid, \"timeInd\",         nTime,          dimIdNTime)\niret = nf90_def_dim(ncid, \"stationIdStrLen\", 15,             dimIdStnStr)\niret = nf90_def_dim(ncid, \"stationIdInd\",    nf90_unlimited, dimIdNStn)\niret = nf90_def_dim(ncid, \"feature_id\",      nFeature,       dimIdNFeature)\n\n!! gageId def var\niret = nf90_def_var(ncid, \"stationId\", nf90_char, (/ dimIdStnStr, dimIdNstn /), varid)\niret = nf90_put_att(ncid, varid, 'long_name', \"USGS station identifer of length 15\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n!! time def var\niret = nf90_def_var(ncid, \"time\", nf90_char, (/ dimIdTimeStr, dimIdNTime, dimIdNStn /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"UTC\")\niret = nf90_put_att(ncid, varid, 'long_name', \"YYYY-mm-dd_HH:MM:SS UTC\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! discharge def var\niret = nf90_def_var(ncid, \"discharge\", nf90_float, (/ dimIdNTime, dimIdNstn /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"m^3/s\")\niret = nf90_put_att(ncid, varid, 'long_name', \"Discharge.cubic_meters_per_second\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! model discharge def var\niret = nf90_def_var(ncid, \"model_discharge\", nf90_float, (/ dimIdNTime, dimIdNstn /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"m^3/s\")\niret = nf90_put_att(ncid, varid, 'long_name', \"modelDischarge.cubic_meters_per_second\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! discharge quality def var\niret = nf90_def_var(ncid, \"discharge_quality\", nf90_short, (/ dimIdNTime, dimIdNstn /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"-\")\niret = nf90_put_att(ncid, varid, 'long_name', \"Discharge quality 0 to 100 to be scaled by 100.\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! nudge def var\niret = nf90_def_var(ncid, \"nudge\", nf90_float, (/ dimIdNFeature /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"m3 s-1\")\niret = nf90_put_att(ncid, varid, 'long_name', \"Amount of stream flow alteration\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n!! global attributes\niret = nf90_put_att(ncid, nf90_global, \"modelTimeAtOutput\", modelTime)\n\n!! end definition\niret = nf90_enddef(ncid)\n\n!! gageId write var\niret = nf90_inq_varid(ncid, \"stationId\", varid)\nallocate(charArr15(nSpace))\ncharArr15=lastObsStr(:)%usgsId\n\niret = nf90_put_var(ncid, varid, charArr15)\ndeallocate(charArr15)\n\n! time write var\niret = nf90_inq_varid(ncid, \"time\", varid)\nallocate(charArr19(nTime,nSpace))\ndo tt=1,nTime\n   do ss=1,nSpace\n      charArr19(tt,ss) = lastObsStr(ss)%lastObsTime(tt)\n   end do\nend do\niret = nf90_put_var(ncid, varid, charArr19)\ndeallocate(charArr19)\n\n! discharge write var\niret = nf90_inq_varid(ncid, \"discharge\", varid)\nallocate(tmpFloat(nTime,nSpace))\ndo tt=1,nTime\n   do ss=1,nSpace\n      tmpFloat(tt,ss) = lastObsStr(ss)%lastObsDischarge(tt)\n   end do\nend do\niret = nf90_put_var(ncid, varid, tmpFloat)\ndeallocate(tmpFloat)\n\n! model discharge write var\niret = nf90_inq_varid(ncid, \"model_discharge\", varid)\nallocate(tmpFloat(nTime,nSpace))\ndo tt=1,nTime\n   do ss=1,nSpace\n      tmpFloat(tt,ss) = lastObsStr(ss)%lastObsModelDischarge(tt)\n   end do\nend do\niret = nf90_put_var(ncid, varid, tmpFloat)\ndeallocate(tmpFloat)\n\n! discharge_quality write var\niret = nf90_inq_varid(ncid, \"discharge_quality\", varid)\nallocate(qualityInt2(nTime,nSpace))\ndo tt=1,nTime\n   do ss=1,nSpace\n   qualityInt2(tt,ss) = nint(100*lastObsStr(ss)%lastObsQuality(tt), kind=2)\nend do\nend do\niret = nf90_put_var(ncid, varid, qualityInt2)\ndeallocate(qualityInt2)\n\n! discharge_quality write var\niret = nf90_inq_varid(ncid, \"nudge\", varid)\niret = nf90_put_var(ncid, varid, g_nudge)\n\n!! close\niret= nf90_close(ncid)\n\n#ifdef HYDRO_D\nprint*,'Ndg: end write_nudging_last_obs'\nflush(6)\n#endif\n\nend subroutine write_nudging_last_obs\n\nsubroutine write_nudging_last_obs_soa(lastObsStr, modelTime, g_nudge)\n\nimplicit none\n\n!Arguments\ntype(lastObsStructure_SoA), intent(in) :: lastObsStr\ncharacter(len=19),      intent(in)               :: modelTime\nreal,                   intent(in), dimension(:) :: g_nudge\n\n! Local\ncharacter(len=37) :: outFileName\ninteger :: nSpace, nTime, nFeature, tt, ss\ninteger :: ncid, iret, varid, dimIdTimeStr, dimIdStnStr, dimIdNTime, dimIdNStn, dimIdNFeature\ncharacter(len=15), allocatable, dimension(:) :: charArr15\ncharacter(len=19), allocatable, dimension(:,:) :: charArr19\nreal,      allocatable, dimension(:,:) :: tmpFloat\ninteger*2, allocatable, dimension(:,:) :: qualityInt2\n\n#ifdef HYDRO_D\nprint*,'Ndg: start write_nudging_last_obs'\nflush(6)\n#endif\n\nnSpace = size(lastObsStr%usgsId)\nnTime  = size(lastObsStr%lastObsDischarge,1)\nnFeature = size(g_nudge)\n\n!           !1234567891123456789212345678931234567\noutFileName='nudgingLastObs.' // modelTime // '.nc'\n\n! create file\niret = nf90_create(outFileName, nf90_clobber, ncid)\n\n! create dimensions\n! station id has length of the number of gages\n! feature id has length of the number of reaches/features.\niret = nf90_def_dim(ncid, \"timeStrLen\",      19,             dimIdTimeStr)\niret = nf90_def_dim(ncid, \"timeInd\",         nTime,          dimIdNTime)\niret = nf90_def_dim(ncid, \"stationIdStrLen\", 15,             dimIdStnStr)\niret = nf90_def_dim(ncid, \"stationIdInd\",    nf90_unlimited, dimIdNStn)\niret = nf90_def_dim(ncid, \"feature_id\",      nFeature,       dimIdNFeature)\n\n! gageId def var\niret = nf90_def_var(ncid, \"stationId\", nf90_char, (/ dimIdStnStr, dimIdNstn /), varid)\niret = nf90_put_att(ncid, varid, 'long_name', \"USGS station identifer of length 15\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! time def var\niret = nf90_def_var(ncid, \"time\", nf90_char, (/ dimIdTimeStr, dimIdNTime, dimIdNStn /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"UTC\")\niret = nf90_put_att(ncid, varid, 'long_name', \"YYYY-mm-dd_HH:MM:SS UTC\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! discharge def var\niret = nf90_def_var(ncid, \"discharge\", nf90_float, (/ dimIdNTime, dimIdNstn /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"m^3/s\")\niret = nf90_put_att(ncid, varid, 'long_name', \"Discharge.cubic_meters_per_second\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! model discharge def var\niret = nf90_def_var(ncid, \"model_discharge\", nf90_float, (/ dimIdNTime, dimIdNstn /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"m^3/s\")\niret = nf90_put_att(ncid, varid, 'long_name', \"modelDischarge.cubic_meters_per_second\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! discharge quality def var\niret = nf90_def_var(ncid, \"discharge_quality\", nf90_short, (/ dimIdNTime, dimIdNstn /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"-\")\niret = nf90_put_att(ncid, varid, 'long_name', \"Discharge quality 0 to 100 to be scaled by 100.\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! nudge def var\niret = nf90_def_var(ncid, \"nudge\", nf90_float, (/ dimIdNFeature /), varid)\niret = nf90_put_att(ncid, varid, 'units', \"m3 s-1\")\niret = nf90_put_att(ncid, varid, 'long_name', \"Amount of stream flow alteration\")\niret = nf90_def_var_deflate(ncid, varid, 0, 1, 2)\n\n! global attributes\niret = nf90_put_att(ncid, nf90_global, \"modelTimeAtOutput\", modelTime)\n\n! end definition\niret = nf90_enddef(ncid)\n\n! gageId write var\niret = nf90_inq_varid(ncid, \"stationId\", varid)\n!allocate(charArr15(nSpace))\n!charArr15=lastObsStr%usgsId(:)\n\niret = nf90_put_var(ncid, varid, lastObsStr%usgsId)\n!deallocate(charArr15)\n\n! time write var\niret = nf90_inq_varid(ncid, \"time\", varid)\n!allocate(charArr19(nTime,nSpace))\n!do tt=1,nTime\n!   do ss=1,nSpace\n!      charArr19(tt,ss) = lastObsStr%lastObsTime(tt,ss)\n!   end do\n!end do\niret = nf90_put_var(ncid, varid, lastObsStr%lastObsTime)\n!deallocate(charArr19)\n\n! discharge write var\niret = nf90_inq_varid(ncid, \"discharge\", varid)\n!allocate(tmpFloat(nTime,nSpace))\n!do tt=1,nTime\n!   do ss=1,nSpace\n!      tmpFloat(tt,ss) = lastObsStr%lastObsDischarge(tt,ss)\n!   end do\n!end do\niret = nf90_put_var(ncid, varid, lastObsStr%lastObsDischarge)\n!deallocate(tmpFloat)\n\n! model discharge write var\niret = nf90_inq_varid(ncid, \"model_discharge\", varid)\n!allocate(tmpFloat(nTime,nSpace))\n!do tt=1,nTime\n!   do ss=1,nSpace\n!      tmpFloat(tt,ss) = lastObsStr%lastObsModelDischarge(tt,ss)\n!   end do\n!end do\niret = nf90_put_var(ncid, varid, lastObsStr%lastObsModelDischarge)\n!deallocate(tmpFloat)\n\n! discharge_quality write var\niret = nf90_inq_varid(ncid, \"discharge_quality\", varid)\nallocate(qualityInt2(nTime,nSpace))\ndo tt=1,nTime\n   do ss=1,nSpace\n   qualityInt2(tt,ss) = nint(100*lastObsStr%lastObsQuality(tt,ss), kind=2)\nend do\nend do\niret = nf90_put_var(ncid, varid, qualityInt2)\ndeallocate(qualityInt2)\n\n! discharge_quality write var\niret = nf90_inq_varid(ncid, \"nudge\", varid)\niret = nf90_put_var(ncid, varid, g_nudge)\n\n! close\niret= nf90_close(ncid)\n\n#ifdef HYDRO_D\nprint*,'Ndg: end write_nudging_last_obs_soa'\nflush(6)\n#endif\n\nend subroutine write_nudging_last_obs_soa\n\n\n!===================================================================================================\n! Program Name:\n!   subroutine find_nudging_last_obs_file\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Return a single file path/names of nudging last obs file given a single date.\n! History Log:\n!   2/9/16 - Created,\n! Usage:\n! Parameters:\n!   date\n! Input Files:  nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nfunction find_nudging_last_obs_file(fileName)\nimplicit none\ncharacter(len=256) :: find_nudging_last_obs_file  ! Output\ncharacter(len=256), intent(in) :: fileName\n!Internals\nlogical :: fileExists\n#ifdef HYDRO_D\nprint*,'Ndg: start find_nudging_last_obs_file'\nflush(6)\n#endif\n\nfind_nudging_last_obs_file=''\n! is there a file with this name?\n! note files are not resolved below minutes.\ninquire(FILE=fileName, EXIST=fileExists)\nif (fileExists) find_nudging_last_obs_file = trim(fileName)\n\n#ifdef HYDRO_D\nprint*,'Ndg: last obs file: ', trim(fileName)\nprint*,'Ndg: file found: ', fileExists\nprint*,'Ndg: finish find_nudging_last_obs_file'\nflush(6)\n#endif\n\nend function find_nudging_last_obs_file\n\n\n!===================================================================================================\n! Subroutine Name:\n!   subroutine read_nudging_last_obs\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   read in the last observations collected over time.\n! History Log:\n!   02/03/16 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes: Needs better error handling...\n\nsubroutine read_nudging_last_obs(fileName, lastObsStr, g_nudge)\n\nimplicit none\ncharacter(len=*),       intent(in)                  :: fileName\ntype(lastObsStructure), intent(inout), dimension(:) :: lastObsStr\nreal,                   intent(inout), dimension(:) :: g_nudge\n\ninteger :: nSpace, nTime, tt, ss\ninteger:: ncid, iret, varid\nreal,              allocatable, dimension(:,:) :: tmpFloat\ninteger*2,         allocatable, dimension(:,:) :: qualityInt2\ncharacter(len=19), allocatable, dimension(:,:) :: charArr19\ncharacter(len=15), allocatable, dimension(:)   :: charArr15\n\nprint*,'read_nudging_last_obs'\n\nnSpace = size(lastObsStr)\nnTime  = size(lastObsStr(1)%lastObsDischarge)\n\niret = nf90_open(fileName, nf90_nowrite, ncid)\n\n! gageId read var\nallocate(charArr15(nSpace))\niret = nf90_inq_varid(ncid, \"stationId\", varid)\niret = nf90_get_var(ncid, varid, charArr15)\nlastObsStr(:)%usgsId=charArr15\ndeallocate(charArr15)\n\n! time read var\niret = nf90_inq_varid(ncid, \"time\", varid)\nallocate(charArr19(nTime,nSpace))\niret = nf90_get_var(ncid, varid, charArr19)\ndo tt=1,nTime\n   do ss=1,nSpace\n      lastObsStr(ss)%lastObsTime(tt)=charArr19(tt,ss)\n   end do\nend do\ndeallocate(charArr19)\n\n! discharge read var\niret = nf90_inq_varid(ncid, \"discharge\", varid)\nallocate(tmpFloat(nTime,nSpace))\niret = nf90_get_var(ncid, varid, tmpFloat)\ndo tt=1,nTime\n   do ss=1,nSpace\n      lastObsStr(ss)%lastObsDischarge(tt) = tmpFloat(tt,ss)\n   end do\nend do\ndeallocate(tmpFloat)\n\n! model discharge read var\niret = nf90_inq_varid(ncid, \"model_discharge\", varid)\nallocate(tmpFloat(nTime,nSpace))\niret = nf90_get_var(ncid, varid, tmpFloat)\ndo tt=1,nTime\n   do ss=1,nSpace\n      lastObsStr(ss)%lastObsModelDischarge(tt) = tmpFloat(tt,ss)\n   end do\nend do\ndeallocate(tmpFloat)\n\n!discharge _quality read var\niret = nf90_inq_varid(ncid, \"discharge_quality\", varid)\nallocate(qualityInt2(nTime,nSpace))\niret = nf90_get_var(ncid, varid, qualityInt2)\ndo tt=1,nTime\n   do ss=1,nSpace\n      lastObsStr(ss)%lastObsQuality(tt) = qualityInt2(tt,ss)/real(100)\n   end do\nend do\ndeallocate(qualityInt2)\n\niret = nf90_inq_varid(ncid, \"nudge\", varid)\nif(iret .eq. nf90_noerr) then\n   iret = nf90_get_var(ncid, varid, g_nudge)\nelse\n   g_nudge=0.0000000000\nend if\n\n! close\niret= nf90_close(ncid)\n\n#ifdef HYDRO_D\nprint*,'Ndg: end read_nudging_last_obs'\nflush(6)\n#endif\n\nend subroutine read_nudging_last_obs\n\nsubroutine read_nudging_last_obs_soa(fileName, lastObsStr, g_nudge)\n\nimplicit none\ncharacter(len=*),       intent(in)                  :: fileName\ntype(lastObsStructure_Soa), intent(inout) :: lastObsStr\nreal,                   intent(inout), dimension(:) :: g_nudge\n\ninteger :: nSpace, nTime, tt, ss\ninteger:: ncid, iret, varid\nreal,              allocatable, dimension(:,:) :: tmpFloat\ninteger*2,         allocatable, dimension(:,:) :: qualityInt2\ncharacter(len=19), allocatable, dimension(:,:) :: charArr19\ncharacter(len=15), allocatable, dimension(:)   :: charArr15\n\nprint*,'read_nudging_last_obs_soa'\n\nnSpace = size(lastObsStr%usgsId)\nnTime  = size(lastObsStr%lastObsDischarge,1)\n\niret = nf90_open(fileName, nf90_nowrite, ncid)\n\n!! gageId read var\n!allocate(charArr15(nSpace))\niret = nf90_inq_varid(ncid, \"stationId\", varid)\niret = nf90_get_var(ncid, varid, lastObsStr%usgsId(:))\n!lastObsStr%usgsId(:) = charArr15\n!deallocate(charArr15)\n\n! time read var\niret = nf90_inq_varid(ncid, \"time\", varid)\n!allocate(charArr19(nTime,nSpace))\niret = nf90_get_var(ncid, varid, lastObsStr%lastObsTime)\n!do tt=1,nTime\n!   do ss=1,nSpace\n!      lastObsStr%lastObsTime(tt,ss)=charArr19(tt,ss)\n!   end do\n!end do\n!deallocate(charArr19)\n\n! discharge read var\niret = nf90_inq_varid(ncid, \"discharge\", varid)\n!allocate(tmpFloat(nTime,nSpace))\niret = nf90_get_var(ncid, varid, lastObsStr%lastObsDischarge)\n!do tt=1,nTime\n!   do ss=1,nSpace\n!      lastObsStr%lastObsDischarge(tt,ss) = tmpFloat(tt,ss)\n!   end do\n!end do\n!deallocate(tmpFloat)\n\n! model discharge read var\niret = nf90_inq_varid(ncid, \"model_discharge\", varid)\n!allocate(tmpFloat(nTime,nSpace))\niret = nf90_get_var(ncid, varid, lastObsStr%lastObsModelDischarge)\n!do tt=1,nTime\n!   do ss=1,nSpace\n!      lastObsStr%lastObsModelDischarge(tt,ss) = tmpFloat(tt,ss)\n!   end do\n!end do\n!deallocate(tmpFloat)\n\n!discharge _quality read var\niret = nf90_inq_varid(ncid, \"discharge_quality\", varid)\nallocate(qualityInt2(nTime,nSpace))\niret = nf90_get_var(ncid, varid, qualityInt2)\ndo tt=1,nTime\n   do ss=1,nSpace\n      lastObsStr%lastObsQuality(tt,ss) = qualityInt2(tt,ss)*0.01!/real(100)\n   end do\nend do\ndeallocate(qualityInt2)\n\niret = nf90_inq_varid(ncid, \"nudge\", varid)\nif(iret .eq. nf90_noerr) then\n   iret = nf90_get_var(ncid, varid, g_nudge)\nelse\n   g_nudge=0.0000000000\nend if\n\n!! close\niret= nf90_close(ncid)\n\n#ifdef HYDRO_D\nprint*,'Ndg: end read_nudging_last_obs'\nflush(6)\n#endif\n\nend subroutine read_nudging_last_obs_soa\n\n\n!===================================================================================================\n! Subroutine Name:\n!   subroutine read_network_reexpression\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Read the three netcdf files which allow the stream network to be traversed with\n!   indexing.\n! History Log:\n!   7/23/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\n\nsubroutine read_network_reexpression( &\n                           file,      & ! file with dims of the stream ntwk\n                           upGo,      & ! where each ind came from, upstream\n                           upStart,   & ! where each ind's upstream links start in upGo\n                           upEnd,     & ! where each ind's upstream links end   in upGo\n                           downGo,    & ! where each ind goes, downstream\n                           downStart, & ! where each ind's downstream links start in downGo\n                           downEnd    ) ! where each ind's downstream links end   in downGo\n\nimplicit none\n\ncharacter(len=*), intent(in) :: file\ninteger*4, dimension(:), intent(out) :: upGo\ninteger*4, dimension(:), intent(out) :: upStart\ninteger*4, dimension(:), intent(out) :: upEnd\ninteger*4, dimension(:), intent(out) :: downGo\ninteger*4, dimension(:), intent(out) :: downStart\ninteger*4, dimension(:), intent(out) :: downEnd\n\ncharacter(len=25) :: subroutineName\ninteger :: iRet, ncid, errStatus\n#ifdef HYDRO_D\nprint*,\"Ndg: start read_network_reexpression\"\nflush(6)\n#endif\n\nsubroutineName = 'read_network_reexpression'\n\niRet = nf90_open(trim(file), nf90_nowrite, ncid)\nif (iRet /= nf90_noerr) then\n   write(*,'(\"read_network_reexpression: Problem opening: ''\", A, \"''\")') trim(file)\n   call hydro_stop(subroutineName // \": Problem opening file: \" // file)\nendif\n\ncall get_1d_netcdf_int4(ncid, 'upGo',      upGo,      subroutineName, .TRUE., errStatus)\ncall get_1d_netcdf_int4(ncid, 'upStart',   upStart,   subroutineName, .TRUE., errStatus)\ncall get_1d_netcdf_int4(ncid, 'upEnd',     upEnd,     subroutineName, .TRUE., errStatus)\ncall get_1d_netcdf_int4(ncid, 'downGo',    downGo,    subroutineName, .TRUE., errStatus)\ncall get_1d_netcdf_int4(ncid, 'downStart', downStart, subroutineName, .TRUE., errStatus)\ncall get_1d_netcdf_int4(ncid, 'downEnd',   downEnd,   subroutineName, .TRUE., errStatus)\n\niRet = nf90_close(ncId)\nif (iRet /= nf90_noerr) then\n   write(*,'(\"read_network_reexpression: Problem closing: ''\", A, \"''\")') trim(file)\n   call hydro_stop(subroutineName // \": Problem closing file: \" // file)\nend if\n\n#ifdef HYDRO_D\nprint*,\"Ndg: finish read_network_reexpression\"\nflush(6)\n#endif\n\nend subroutine read_network_reexpression\n\n!===================================================================================================\n! Subroutine Name:\n!   subroutine output_chan_connectivity\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   For gridded channel routing, write the channel connectivity to a netcdf file\n!   so channel analyses can be performed offline. Do it here so any changes to the\n!   topology calculation are maintained without external code.\n! History Log:\n!   5/27/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes  :\n!   One day it might be worth writing code to read the files output by this code,\n!   depending on the time spent on the calculations when restarting a domain:\n!   is recalculation faster than reading in the file written by this routine?\n\nsubroutine output_chan_connectivity( &\n     inCHLAT,     inCHLON,             &   !! Channel grid lat, lon.\n     inCHANLEN,                        &   !! The distance between channel grid centers in m.\n     inFrom_node, inTo_node,           &   !! Index of a given cell and the index which it flows to.\n     inCHANXI,    inCHANYJ,            &   !! Index on fine/routing grid of grid cells.\n     inTYPEL,     inLakeNode           &   !! Lake type? and node? indications.\n)\n  use iso_fortran_env, only: int64\n\n#ifdef MPP_LAND\nuse module_mpp_land\n#endif\n\nimplicit none\n\n!! These are the names used in module_HYDRO_io.F: SUBROUTINE READ_CHROUTING1\nreal,    dimension(:),  intent(in) :: inCHLAT, inCHLON, inCHANLEN\ninteger, dimension(:),  intent(in) :: inCHANXI, inCHANYJ, inTYPEL\ninteger(kind=int64), dimension(:), intent(in) :: inFrom_node, inTo_node\ninteger(kind=int64), dimension(:), intent(in) :: inLakeNode\n\ninteger            :: nStreamCells, streamCellDimID\ninteger            :: iret, projInfo_flag\ninteger            :: ncid, ncstatic, varid\n\n\nreal               :: long_cm, lat_po, fe, fn\nreal, dimension(2) :: sp\n! JLM this could go to a namelist for flexibility\ncharacter(len=256), parameter :: output_flnm = \"CHANNEL_CONNECTIVITY.nc\"\n\nreal,    allocatable, dimension(:) :: CHLAT, CHLON, CHANLEN\ninteger, allocatable, dimension(:) :: CHANXI, CHANYJ, TYPEL\ninteger(kind=int64), allocatable, dimension(:) :: from_node, to_node\ninteger(kind=int64), allocatable, dimension(:) :: lakeNode\n\n!! handle the parallelization in this routine instead of in the main code.\n\n#ifdef MPP_LAND\n\nif(my_id .eq. io_id) then\n   allocate( chLat(rt_domain(did)%gnlinks),    chLon(rt_domain(did)%gnlinks)     )\n   allocate( chanLen(rt_domain(did)%gnlinks),  from_node(rt_domain(did)%gnlinks) )\n   allocate( to_node(rt_domain(did)%gnlinks),  chanXI(rt_domain(did)%gnlinks)    )\n   allocate( chanYJ(rt_domain(did)%gnlinks),   typeL(rt_domain(did)%gnlinks)     )\n   allocate( lakeNode(rt_domain(did)%gnlinks) )\nelse\n   allocate(chLat(1),  chLon(1),  chanLen(1), from_node(1), to_node(1) )\n   allocate(chanXI(1), chanYJ(1), typeL(1),  lakeNode(1))\nend if\n\ncall write_chanel_real(inChLat,     rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, chLat)\ncall write_chanel_real(inChLon,     rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, chLon)\ncall write_chanel_real(inChanLen,   rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, chanLen)\ncall write_chanel_int8(inFrom_node, rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, from_node)\ncall write_chanel_int8(inTo_node,   rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, to_node)\ncall write_chanel_int(inChanXI,    rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, chanXI)\ncall write_chanel_int(inChanYJ,    rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, chanYJ)\ncall write_chanel_int(inTypeL,     rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, typeL)\ncall write_chanel_int8(inLakeNode,  rt_domain(did)%map_l2g, &\n                       rt_domain(did)%gnlinks, rt_domain(did)%nlinks, lakeNode)\n\n#else\n\nallocate( chLat(rt_domain(did)%nlinks),    chLon(rt_domain(did)%nlinks)      )\nallocate( chanLen(rt_domain(did)%nlinks),  from_node(rt_domain(did)%nlinks)  )\nallocate( to_node(rt_domain(did)%nlinks),  chanXI(rt_domain(did)%nlinks)     )\nallocate( chanYJ(rt_domain(did)%nlinks),   typeL(rt_domain(did)%nlinks)      )\nallocate( lakeNode(rt_domain(did)%nlinks) )\n\nchLat     = inChLat\nchLon     = inChLon\nchanlen     = inChanlen\nfrom_node = inFrom_node\nto_node   = inTo_node\nchanXI    = inChanXI\nchanYJ    = inChanYJ\ntypeL     = inTypeL\nlakeNode  = inLakeNode\n\n#endif\n\n\n#ifdef MPP_LAND\nif(my_id .eq. io_id) then\n#endif\n\n   !! jlm: check that all the input variables have the same dimensions? Or will that happen\n   !! by defult when trying to write to ncdf?\n\n   ! Open the  finemesh static files to obtain projection information\n   ! jlm: this seems optional, might be nice if output is used for plotting/GIS.\n   ! jlm: set did:=1 in nlst_rt\n#ifdef HYDRO_D\n   write(*,'(\"geo_finegrid_flnm: ''\", A, \"''\")') trim(nlst(did)%geo_finegrid_flnm)\n#endif\n\n   iret = nf90_open(trim(nlst(1)%geo_finegrid_flnm), nf90_NOWRITE, ncstatic)\n\n   if (iret /= 0) then\n      write(*,'(\"Problem opening geo_finegrid file: ''\", A, \"''\")') &\n           trim(nlst(1)%geo_finegrid_flnm)\n      write(*,*) \"HIRES_OUTPUT will not be georeferenced...\"\n      projInfo_flag = 0\n   else\n      projInfo_flag = 1\n   endif\n\n   if(projInfo_flag.eq.1) then !if/then hires_georef\n      ! Get projection information from finegrid netcdf file\n      iret = nf90_inq_varid(ncstatic,'lambert_conformal_conic',varid)\n      if(iret .eq. 0) &\n           iret = nf90_get_att(ncstatic, varid, 'longitude_of_central_meridian', long_cm)\n      iret = nf90_get_att(ncstatic, varid, 'latitude_of_projection_origin', lat_po)\n      iret = nf90_get_att(ncstatic, varid, 'false_easting', fe)\n      iret = nf90_get_att(ncstatic, varid, 'false_northing', fn)\n      iret = nf90_get_att(ncstatic, varid, 'standard_parallel', sp)\n   end if  !endif hires_georef\n   iret = nf90_close(ncstatic)\n\n\n   ! Create the channel connectivity file\n#ifdef HYDRO_D\n   print*,'Ndg: output_flnm = \"'//trim(output_flnm)//'\"'\n   flush(6)\n#endif\n\n   iret = nf90_create(trim(output_flnm), OR(NF90_CLOBBER, NF90_NETCDF4), ncid)\n\n   if (iret /= 0) then\n      print*,\"Ndg: Problem nf90_create\"\n      call hydro_stop(\"output_channel_connectivity\")\n   endif\n\n   nStreamCells=size(CHLON,1)\n#ifdef HYDRO_D\n   print*,'Ndg: nStreamCells:', nStreamCells\n   flush(6)\n#endif\n\n   ! Dimension definitions\n   iret = nf90_def_dim(ncid, \"nStreamCells\", nStreamCells, streamCellDimID)\n\n   ! Variable definitions\n   ! LATITUDE - float\n   iret = nf90_def_var(ncid, \"LATITUDE\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid,varid, 'long_name', 'Upstream cell latitude')\n   iret = nf90_put_att(ncid,varid, 'standard_name', 'LATITUDE')\n   iret = nf90_put_att(ncid,varid, 'units', 'deg North')\n\n   ! LONGITUDE - float\n   iret = nf90_def_var(ncid, \"LONGITUDE\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid, varid, 'long_name', 'Upstream cell longitude')\n   iret = nf90_put_att(ncid, varid, 'standard_name', 'LONGITUDE')\n   iret = nf90_put_att(ncid, varid, 'units', 'deg East')\n\n   ! CHANLEN - float\n   ! JLM: should check if pour points have chanLen, should they?\n   iret = nf90_def_var(ncid, \"CHANLEN\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid, varid, 'units','m')\n   iret = nf90_put_att(ncid, varid, 'long_name', &\n        'distance between stream cell center points with downstream')\n   iret = nf90_put_att(ncid, varid, 'missing_value', -9E15)\n\n\n\n   ! FROM_NODE - integer\n   iret = nf90_def_var(ncid, \"FROM_NODE\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid, varid, 'units', 'index')\n   iret = nf90_put_att(ncid, varid, 'long_name', 'Upstream cell index')\n   iret = nf90_put_att(ncid, varid, 'missing_value', -9999)\n\n   ! TO_NODE - integer\n   iret = nf90_def_var(ncid, \"TO_NODE\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid, varid, 'units', 'index')\n   iret = nf90_put_att(ncid, varid, 'long_name', 'Downstream cell index')\n   iret = nf90_put_att(ncid, varid, 'missing_value', -9999)\n\n   ! CHANXI - integer\n   iret = nf90_def_var(ncid, \"CHANXI\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid, varid, 'units', 'index')\n   iret = nf90_put_att(ncid, varid, 'long_name', 'Upstream cell x index on fine grid')\n   iret = nf90_put_att(ncid, varid, 'missing_value', -9999)\n\n   ! CHANYJ - integer\n   iret = nf90_def_var(ncid, \"CHANYJ\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid, varid, 'units', 'index')\n   iret = nf90_put_att(ncid, varid, 'long_name', 'Upstream cell y index on fine grid')\n   iret = nf90_put_att(ncid, varid, 'missing_value', -9999)\n\n   ! TYPEL - integer\n   iret = nf90_def_var(ncid, \"TYPEL\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid, varid, 'units', 'code')\n   iret = nf90_put_att(ncid, varid, 'long_name', &\n        'Link Type 0 is channel 1 is pour point crit depth downstream 2 is reservoir lake')\n\n   ! LAKENODE - integer\n   iret = nf90_def_var(ncid, \"LAKENODE\", 1, (/ streamCellDimID /), varid)\n   iret = nf90_put_att(ncid, varid, 'units', 'index')\n   iret = nf90_put_att(ncid, varid, 'long_name', 'Index of lake in downstream cell')\n\n\n   ! Projection information\n   if(projInfo_flag .eq. 1) then\n      iret = nf90_def_var(ncid, \"lambert_conformal_conic\", 0, 0, varid)\n      iret = nf90_put_att(ncid, varid, 'grid_mapping_name', 'lambert_conformal_conic')\n      iret = nf90_put_att(ncid, varid, 'longitude_of_central_meridian', long_cm)\n      iret = nf90_put_att(ncid, varid, 'latitude_of_projection_origin', lat_po)\n      iret = nf90_put_att(ncid, varid, 'false_easting', fe)\n      iret = nf90_put_att(ncid, varid, 'false_northing', fn)\n      iret = nf90_put_att(ncid, varid, 'standard_parallel', sp)\n   end if\n\n   ! End NCDF definition section\n   iret = nf90_enddef(ncid)\n\n   ! Put data in to the file\n\n   ! Data for the dim? JLM: no, seems pointless index, if not necessary\n   !iret = nf90_inq_varid(ncid,\"nStreamCells\", varid)\n   !iret = nf90_put_vara_int(ncid, varid, (/1/), (/ nStreamCells /), 1:nStreamCells - or however you)\n\n   ! Reals\n   iret = nf90_inq_varid(ncid, \"LATITUDE\", varid)\n   iret = nf90_put_var(ncid, varid, CHLAT, (/1/), (/ nStreamCells /))\n\n   iret = nf90_inq_varid(ncid, \"LONGITUDE\", varid)\n   iret = nf90_put_var(ncid, varid, CHLON, (/1/), (/ nStreamCells /))\n\n   iret = nf90_inq_varid(ncid, \"CHANLEN\", varid)\n   iret = nf90_put_var(ncid, varid, CHANLEN, (/1/), (/ nStreamCells /))\n\n   ! Integers\n   iret = nf90_inq_varid(ncid, \"FROM_NODE\", varid)\n   iret = nf90_put_var(ncid, varid, FROM_NODE, (/1/), (/ nStreamCells /))\n\n   iret = nf90_inq_varid(ncid, \"TO_NODE\", varid)\n   iret = nf90_put_var(ncid, varid, TO_NODE, (/1/), (/ nStreamCells /))\n\n   iret = nf90_inq_varid(ncid, \"CHANXI\", varid)\n   iret = nf90_put_var(ncid, varid, CHANXI, (/1/), (/ nStreamCells /))\n\n   iret = nf90_inq_varid(ncid, \"CHANYJ\", varid)\n   iret = nf90_put_var(ncid, varid, CHANYJ, (/1/), (/ nStreamCells /))\n\n   iret = nf90_inq_varid(ncid, \"TYPEL\", varid)\n   iret = nf90_put_var(ncid, varid, TYPEL, (/1/), (/ nStreamCells /))\n\n   iret = nf90_inq_varid(ncid, \"LAKENODE\", varid)\n   iret = nf90_put_var(ncid, varid, LAKENODE, (/1/), (/ nStreamCells /))\n\n\n   ! Close the file\n   iret = nf90_close(ncid)\n\n#ifdef MPP_LAND\nendif\n\ndeallocate(chLat, chLon, chanLen, from_node, to_node, chanXI, chanYJ, typeL, lakeNode)\n\nif(my_id .eq. io_id) then\n#endif\n#ifdef HYDRO_D\n   write(6,*) \"end of output_chan_connectivity\"\n   flush(6)\n#endif\n#ifdef MPP_LAND\nendif\n#endif\n\nend subroutine output_chan_connectivity\n\n!===================================================================================================\n! Program Names:\n!   get_1d_netcdf_real, get_1d_netcdf_int4\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Read a variable of real or integer type from an open netcdf file, respectively.\n! History Log:\n!   7/17/15 -Created, JLM.\n! Usage:\n! Parameters:\n!   See definitions.\n! Input Files:\n!   This file is refered to by it's \"ncid\" obtained from nc_open\n!   prior to calling this routine.\n! Output Files:\n!   None.\n! Condition codes:\n!   hydro_stop is passed \"get_1d_netcdf\".\n! User controllable options:\n! Notes:\n!   Could define an interface for these.\n\nsubroutine get_1d_netcdf_int2(ncid, varName, var, callingRoutine, fatal_if_error, errStatus)\nimplicit none\ninteger*4,               intent(in)  :: ncid !! the file identifier\ncharacter(len=*),        intent(in)  :: varName\ninteger*2, dimension(:), intent(out) :: var\ncharacter(len=*),        intent(in)  :: callingRoutine\nlogical,                 intent(in)  :: fatal_if_error\ninteger,                 intent(out) :: errStatus\ninteger :: varid, iret\nerrStatus=0\niRet = nf90_inq_varid(ncid, varName, varid)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_int2: variable: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_int2\")\n   errStatus=errStatus+1\nend if\niRet = nf90_get_var(ncid, varid, var)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_int2: values: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_int2\")\n   errStatus=errStatus+1\nend if\nend subroutine get_1d_netcdf_int2\n\n\nsubroutine get_1d_netcdf_int4(ncid, varName, var, callingRoutine, fatal_if_error, errStatus)\nimplicit none\ninteger*4,             intent(in)  :: ncid !! the file identifier\ncharacter(len=*),      intent(in)  :: varName\ninteger, dimension(:), intent(out) :: var\ncharacter(len=*),      intent(in)  :: callingRoutine\nlogical,               intent(in)  :: fatal_if_error\ninteger,               intent(out) :: errStatus\ninteger :: varid, iret\nerrStatus=0\niRet = nf90_inq_varid(ncid, varName, varid)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_int4: variable: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_int4\")\n   errStatus=errStatus+1\nend if\niRet = nf90_get_var(ncid, varid, var)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_int4: values: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_int4\")\n   errStatus=errStatus+1\nend if\nend subroutine get_1d_netcdf_int4\n\n\nsubroutine get_1d_netcdf_real(ncid, varName, var, callingRoutine, fatal_if_error, errStatus)\nimplicit none\ninteger,            intent(in)  :: ncid !! the file identifier\ncharacter(len=*),   intent(in)  :: varName\nreal, dimension(:), intent(out) :: var\ncharacter(len=*),   intent(in)  :: callingRoutine\nlogical,            intent(in)  :: fatal_if_error\ninteger,            intent(out) :: errStatus\ninteger :: varId, iRet\nerrStatus=0\niRet = nf90_inq_varid(ncid, varName, varid)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_real: variable: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_real\")\n   errStatus=errStatus+1\nend if\niRet = nf90_get_var(ncid, varid, var)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf_real: values: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf_real\")\n   errStatus=errStatus+1\nend if\nend subroutine get_1d_netcdf_real\n\n\nsubroutine get_1d_netcdf(ncid, varName, var, callingRoutine, fatal_if_error, errStatus)\nimplicit none\ncharacter(len=*), dimension(:), intent(out) :: var\ninteger,                        intent(in)  :: ncid !! the file identifier\ncharacter(len=*),               intent(in)  :: varName\ncharacter(len=*),               intent(in)  :: callingRoutine\nlogical,                        intent(in)  :: fatal_if_error\ninteger,                        intent(out) :: errStatus\ninteger :: varId, iRet\nerrStatus=0\niRet = nf90_inq_varid(ncid, varName, varid)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf: variable: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf\")\n   errStatus=errStatus+1\nend if\niRet = nf90_get_var(ncid, varid, var)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_1d_netcdf: values: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_1d_netcdf\")\n   errStatus=errStatus+1\nend if\nend subroutine get_1d_netcdf\n\n\n!==============================================================================\n! 3D real\nsubroutine get_3d_netcdf_real(ncid, varName, var, callingRoutine, fatal_if_error, errStatus)\nimplicit none\ninteger,                intent(in)  :: ncid !! the file identifier\ncharacter(len=*),       intent(in)  :: varName\nreal, dimension(:,:,:), intent(out) :: var\ncharacter(len=*),       intent(in)  :: callingRoutine\nlogical,                intent(in)  :: fatal_if_error\ninteger,                intent(out) :: errStatus\ninteger :: varId, iRet\nerrStatus=0\niRet = nf90_inq_varid(ncid, varName, varid)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_3d_netcdf_real: variable: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_3d_netcdf_real\")\n   errStatus=errStatus+1\nend if\niRet = nf90_get_var(ncid, varid, var)\nif (iret /= nf90_NoErr) then\n   print*, trim(callingRoutine) // \": get_3d_netcdf_real: values: \" // trim(varName)\n   if (fatal_IF_ERROR) call hydro_stop(\"get_3d_netcdf_real\")\n   errStatus=errStatus+1\nend if\nend subroutine get_3d_netcdf_real\n\n!===================================================================================================\n! Program Names:\n!   get_netcdf_dim\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Get the length of a provided dimension.\n! History Log:\n!   7/23/15 -Created, JLM.\n! Usage:\n! Parameters:\n!   file: character, the file to query\n!   dimName: character, the name of the dimension\n!   callingRoutine: character, the name of the calling routine for error messages\n! Input Files:\n!   Specified argument.\n! Output Files:\n! Condition codes:\n!   hydro_stop is called. .\n! User controllable options:\n! Notes:\n\nfunction get_netcdf_dim(file, dimName, callingRoutine, fatalErr)\nimplicit none\ninteger :: get_netcdf_dim  !! return value, zero if failure\ncharacter(len=*), intent(in)   :: file, dimName, callingRoutine\nlogical, optional, intent(in) :: fatalErr\nlogical :: fatalErr_local\ninteger :: ncId, dimId, iRet\n\nfatalErr_local = .false.\nif(present(fatalErr)) fatalErr_local=fatalErr\n\n#ifdef HYDRO_D\nwrite(*,'(\"getting dimension from file: ''\", A, \"''\")') trim(file)\nflush(6)\n#endif\n\niRet = nf90_open(trim(file), nf90_NOWRITE, ncId)\nif (iret /= nf90_noerr) then\n   write(*,'(\"Problem opening file: ''\", A, \"''\")') trim(file)\n   if(fatalErr_local) call hydro_stop(trim(callingRoutine) // ': get_netcdf_dim')\n   get_netcdf_dim = 0\n   return\nendif\n\niRet = nf90_inq_dimid(ncId, trim(dimName), dimId)\nif (iret /= nf90_noerr) then\n   write(*,'(\"Problem getting the dimension ID: ''\", A, \"''\")') trim(file)\n   if(fatalErr_local) call hydro_stop(trim(callingRoutine) // ': get_netcdf_dim')\n   get_netcdf_dim = 0\n   return\nendif\n\niRet = nf90_inquire_dimension(ncId, dimId, len= get_netcdf_dim)\nif (iret /= nf90_noerr) then\n   write(*,'(\"Problem getting the dimension length: ''\", A, \"''\")') trim(file)\n   if(fatalErr_local) call hydro_stop(trim(callingRoutine) // ': get_netcdf_dim')\n   get_netcdf_dim = 0\n   return\nendif\n\niRet = nf90_close(ncId)\nif (iret /= nf90_noerr) then\n   write(*,'(\"Problem closing file: ''\", A, \"''\")') trim(file)\n   if(fatalErr_local) call hydro_stop(trim(callingRoutine) // ': get_netcdf_dim')\n   get_netcdf_dim = 0\n   return\nendif\nend function get_netcdf_dim\n\n\n!===================================================================================================\nend module module_nudging_io\n"
  },
  {
    "path": "src/nudging/module_date_utils_nudging.F90",
    "content": "module module_date_utils_nudging\n    use module_hydro_stop, only: HYDRO_stop\ncontains\n\n!===================================================================================================\n! Subroutine Name: geth_newdate\n! Author(s)/Contact(s):\n!   Wei Yu? or NoahMP developers?\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract:\n!   Calculate a time difference from two time strings: idts=newdate-olddate\n! History Log:\n!   7/22/15 -Header Created, JLM\n! Usage:\n!   call geth_newdate(ndate, odate, idt)\n! Parameters:\n!   newdate : the resulting date: odate+idt\n!   olddate : the start time for the sum: odate+id\n!   idts    : the time increment in seconds: odate+id\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!   call hydro_stop(\"geth_newdate\") is used.\n! User controllable options:\n!   None.\n! Notes:\n!   This routine was copied from ../LandModel/Utility_routines/module_date_utilities.F\n!   There are some advantages to having a separate copy here, both compiling and\n!   tailored needs.\n\nsubroutine geth_newdate (ndate, odate, idt)\nimplicit none\n\n!  From old date (\"YYYY-MM-DD HH:MM:SS.ffff\" or \"YYYYMMDDHHMMSSffff\") and\n!  delta-time, compute the new date.\n\n!  on entry     -  odate  -  the old hdate.\n!                  idt    -  the change in time\n\n!  on exit      -  ndate  -  the new hdate.\n\ninteger, intent(in)           :: idt\ncharacter (len=*), intent(out) :: ndate\ncharacter (len=*), intent(in)  :: odate\n\n!  Local Variables\n\n!  yrold    -  indicates the year associated with \"odate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scold    -  indicates the second associated with \"odate\"\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n\n!  mday     -  a list assigning the number of days in each month\n\n!  i        -  loop counter\n!  nday     -  the integer number of days represented by \"idt\"\n!  nhour    -  the integer number of hours in \"idt\" after taking out\n!              all the whole days\n!  nmin     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days and whole hours.\n!  nsec     -  the integer number of minutes in \"idt\" after taking out\n!              all the whole days, whole hours, and whole minutes.\n\ninteger :: newlen, oldlen\ninteger :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\ninteger :: yrold, moold, dyold, hrold, miold, scold, frold\ninteger :: nday, nhour, nmin, nsec, nfrac, i, ifrc\nlogical :: opass\ncharacter (len=10) :: hfrc\ncharacter (len=1) :: sp\nlogical :: punct\ninteger :: yrstart, yrend, mostart, moend, dystart, dyend\ninteger :: hrstart, hrend, mistart, miend, scstart, scend, frstart\ninteger :: units\ninteger, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\n\n! Determine if odate is \"YYYY-MM-DD_HH ... \" or \"YYYYMMDDHH....\"\nif (odate(5:5) == \"-\") then\n   punct = .TRUE.\nelse\n   punct = .FALSE.\nendif\n\n!  Break down old hdate into parts\n\nhrold = 0\nmiold = 0\nscold = 0\nfrold = 0\noldlen = LEN(odate)\nif (punct) then\n   yrstart = 1\n   yrend = 4\n   mostart = 6\n   moend = 7\n   dystart = 9\n   dyend = 10\n   hrstart = 12\n   hrend = 13\n   mistart = 15\n   miend = 16\n   scstart = 18\n   scend = 19\n   frstart = 21\n   select case (oldlen)\n   case (10)\n      ! Days\n      units = 1\n   case (13)\n      ! Hours\n      units = 2\n   case (16)\n      ! Minutes\n      units = 3\n   case (19)\n      ! Seconds\n      units = 4\n   case (21)\n      ! Tenths\n      units = 5\n   case (22)\n      ! Hundredths\n      units = 6\n   case (23)\n      ! Thousandths\n      units = 7\n   case (24)\n      ! Ten thousandths\n      units = 8\n   case default\n\n      write(*,*) 'FATAL ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n      call hydro_stop(\"geth_newdate\")\n\n   end select\n\n   if (oldlen.ge.11) then\n      sp = odate(11:11)\n   else\n      sp = ' '\n   end if\n\nelse\n\n   yrstart = 1\n   yrend = 4\n   mostart = 5\n   moend = 6\n   dystart = 7\n   dyend = 8\n   hrstart = 9\n   hrend = 10\n   mistart = 11\n   miend = 12\n   scstart = 13\n   scend = 14\n   frstart = 15\n\n   select case (oldlen)\n   case (8)\n      ! Days\n      units = 1\n   case (10)\n      ! Hours\n      units = 2\n   case (12)\n      ! Minutes\n      units = 3\n   case (14)\n      ! Seconds\n      units = 4\n   case (15)\n      ! Tenths\n      units = 5\n   case (16)\n      ! Hundredths\n      units = 6\n   case (17)\n      ! Thousandths\n      units = 7\n   case (18)\n      ! Ten thousandths\n      units = 8\n   case default\n\n      write(*,*) 'FATAL ERROR: geth_newdate:  odd length: #'//trim(odate)//'#'\n      call hydro_stop(\"geth_newdate\")\n\n   end select\nendif\n\n!  Use internal READ statements to convert the CHARACTER string\n!  date into INTEGER components.\n\nread(odate(yrstart:yrend),  '(i4)') yrold\nread(odate(mostart:moend),  '(i2)') moold\nread(odate(dystart:dyend), '(i2)') dyold\nif (units.ge.2) then\n   read(odate(hrstart:hrend),'(i2)') hrold\n   if (units.ge.3) then\n      read(odate(mistart:miend),'(i2)') miold\n      if (units.ge.4) then\n         read(odate(scstart:scend),'(i2)') scold\n         if (units.ge.5) then\n            read(odate(frstart:oldlen),*) frold\n         end if\n      end if\n   end if\nend if\n\n!  Set the number of days in February for that year.\n\nmday(2) = nfeb(yrold)\n\n!  Check that ODATE makes sense.\n\nopass = .TRUE.\n\n!  Check that the month of ODATE makes sense.\n\nif ((moold.gt.12).or.(moold.lt.1)) then\n#ifdef HYDRO_D\n   write(*,*) 'GETH_NEWDATE:  Month of ODATE = ', moold\n#endif\n   opass = .FALSE.\nend if\n\n!  Check that the day of ODATE makes sense.\n\nif ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n#ifdef HYDRO_D\n   write(*,*) 'GETH_NEWDATE:  Day of ODATE = ', dyold\n#endif\n   opass = .FALSE.\nend if\n\n!  Check that the hour of ODATE makes sense.\n\nif ((hrold.gt.23).or.(hrold.lt.0)) then\n#ifdef HYDRO_D\n   write(*,*) 'GETH_NEWDATE:  Hour of ODATE = ', hrold\n#endif\n   opass = .FALSE.\nend if\n\n!  Check that the minute of ODATE makes sense.\n\nif ((miold.gt.59).or.(miold.lt.0)) then\n#ifdef HYDRO_D\n   write(*,*) 'GETH_NEWDATE:  Minute of ODATE = ', miold\n#endif\n   opass = .FALSE.\nend if\n\n!  Check that the second of ODATE makes sense.\n\nif ((scold.gt.59).or.(scold.lt.0)) then\n#ifdef HYDRO_D\n   write(*,*) 'GETH_NEWDATE:  Second of ODATE = ', scold\n#endif\n   opass = .FALSE.\nend if\n\n!  Check that the fractional part  of ODATE makes sense.\n\n\nif (.not.opass) then\n\n   write(*,*) 'FATAL ERROR: Crazy ODATE: ', odate(1:oldlen), oldlen\n   stop\n\nend if\n\n!  Date Checks are completed.  Continue.\n\n\n!  Compute the number of days, hours, minutes, and seconds in idt\n\nif (units.ge.5) then !idt should be in fractions of seconds\n   ifrc = oldlen-(frstart)+1\n   ifrc = 10**ifrc\n   nday   = abs(idt)/(86400*ifrc)\n   nhour  = mod(abs(idt),86400*ifrc)/(3600*ifrc)\n   nmin   = mod(abs(idt),3600*ifrc)/(60*ifrc)\n   nsec   = mod(abs(idt),60*ifrc)/(ifrc)\n   nfrac = mod(abs(idt), ifrc)\nelse if (units.eq.4) then  !idt should be in seconds\n   ifrc = 1\n   nday   = abs(idt)/86400 ! integer number of days in delta-time\n   nhour  = mod(abs(idt),86400)/3600\n   nmin   = mod(abs(idt),3600)/60\n   nsec   = mod(abs(idt),60)\n   nfrac  = 0\nelse if (units.eq.3) then !idt should be in minutes\n   ifrc = 1\n   nday   = abs(idt)/1440 ! integer number of days in delta-time\n   nhour  = mod(abs(idt),1440)/60\n   nmin   = mod(abs(idt),60)\n   nsec   = 0\n   nfrac  = 0\nelse if (units.eq.2) then !idt should be in hours\n   ifrc = 1\n   nday   = abs(idt)/24 ! integer number of days in delta-time\n   nhour  = mod(abs(idt),24)\n   nmin   = 0\n   nsec   = 0\n   nfrac  = 0\nelse if (units.eq.1) then !idt should be in days\n   ifrc = 1\n   nday   = abs(idt)    ! integer number of days in delta-time\n   nhour  = 0\n   nmin   = 0\n   nsec   = 0\n   nfrac  = 0\nelse\n\n   write(*,'(''GETH_NEWDATE: Strange length for ODATE: '', i3)') &\n        oldlen\n   write(*,*) '#'//odate(1:oldlen)//'#'\n   call hydro_stop(\"geth_newdate\")\n\nend if\n\nif (idt.ge.0) then\n\n   frnew = frold + nfrac\n   if (frnew.ge.ifrc) then\n      frnew = frnew - ifrc\n      nsec = nsec + 1\n   end if\n\n   scnew = scold + nsec\n   if (scnew .ge. 60) then\n      scnew = scnew - 60\n      nmin  = nmin + 1\n   end if\n\n   minew = miold + nmin\n   if (minew .ge. 60) then\n      minew = minew - 60\n      nhour  = nhour + 1\n   end if\n\n   hrnew = hrold + nhour\n   if (hrnew .ge. 24) then\n      hrnew = hrnew - 24\n      nday  = nday + 1\n   end if\n\n   dynew = dyold\n   monew = moold\n   yrnew = yrold\n   do i = 1, nday\n      dynew = dynew + 1\n      if (dynew.gt.mday(monew)) then\n         dynew = dynew - mday(monew)\n         monew = monew + 1\n         if (monew .gt. 12) then\n            monew = 1\n            yrnew = yrnew + 1\n            ! If the year changes, recompute the number of days in February\n            mday(2) = nfeb(yrnew)\n         end if\n      end if\n   end do\n\nelse if (idt.lt.0) then\n\n   frnew = frold - nfrac\n   if (frnew .lt. 0) then\n      frnew = frnew + ifrc\n      nsec = nsec + 1\n   end if\n\n   scnew = scold - nsec\n   if (scnew .lt. 00) then\n      scnew = scnew + 60\n      nmin  = nmin + 1\n   end if\n\n   minew = miold - nmin\n   if (minew .lt. 00) then\n      minew = minew + 60\n      nhour  = nhour + 1\n   end if\n\n   hrnew = hrold - nhour\n   if (hrnew .lt. 00) then\n      hrnew = hrnew + 24\n      nday  = nday + 1\n   end if\n\n   dynew = dyold\n   monew = moold\n   yrnew = yrold\n   do i = 1, nday\n      dynew = dynew - 1\n      if (dynew.eq.0) then\n         monew = monew - 1\n         if (monew.eq.0) then\n            monew = 12\n            yrnew = yrnew - 1\n            ! If the year changes, recompute the number of days in February\n            mday(2) = nfeb(yrnew)\n         end if\n         dynew = mday(monew)\n      end if\n   end do\nend if\n\n!  Now construct the new mdate\n\nnewlen = LEN(ndate)\n\nif (punct) then\n\n   if (newlen.gt.frstart) then\n      write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n      write(hfrc,'(i10)') frnew+1000000000\n      ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n   else if (newlen.eq.scend) then\n      write(ndate(1:scend),19) yrnew, monew, dynew, hrnew, minew, scnew\n19    format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2,':',i2.2)\n\n   else if (newlen.eq.miend) then\n      write(ndate,16) yrnew, monew, dynew, hrnew, minew\n16    format(i4,'-',i2.2,'-',i2.2,'_',i2.2,':',i2.2)\n\n   else if (newlen.eq.hrend) then\n      write(ndate,13) yrnew, monew, dynew, hrnew\n13    format(i4,'-',i2.2,'-',i2.2,'_',i2.2)\n\n   else if (newlen.eq.dyend) then\n      write(ndate,10) yrnew, monew, dynew\n10    format(i4,'-',i2.2,'-',i2.2)\n\n   end if\n\nelse\n\n   if (newlen.gt.frstart) then\n      write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n      write(hfrc,'(i10)') frnew+1000000000\n      ndate = ndate(1:scend)//'.'//hfrc(31-newlen:10)\n\n   else if (newlen.eq.scend) then\n      write(ndate(1:scend),119) yrnew, monew, dynew, hrnew, minew, scnew\n119   format(i4,i2.2,i2.2,i2.2,i2.2,i2.2)\n\n   else if (newlen.eq.miend) then\n      write(ndate,116) yrnew, monew, dynew, hrnew, minew\n116   format(i4,i2.2,i2.2,i2.2,i2.2)\n\n   else if (newlen.eq.hrend) then\n      write(ndate,113) yrnew, monew, dynew, hrnew\n113   format(i4,i2.2,i2.2,i2.2)\n\n   else if (newlen.eq.dyend) then\n      write(ndate,110) yrnew, monew, dynew\n110   format(i4,i2.2,i2.2)\n\n   end if\n\nendif\n\nif (punct .and. (oldlen.ge.11) .and. (newlen.ge.11)) ndate(11:11) = sp\n\nend subroutine geth_newdate\n\n\n\n!===================================================================================================\n! Subroutine Name: geth_idts\n! Author(s)/Contact(s):\n!   Wei Yu? or NoahMP developers?\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract:\n!   Calculate a time difference from two time strings: idts=newdate-olddate\n! History Log:\n!   7/22/15 -Header Created, JLM\n! Usage:\n!   call geth_idts(newdate, olddate, idt)\n! Parameters:\n!   newdate : first date in difference  (newdate-olddate).\n!   olddate : second date in difference (newdate-olddate).\n!   idts    : difference with units dependent on input resolution.\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!   Currently incomplete error handling.\n! User controllable options:\n!   None.\n! Notes:\n!   This routine was copied from ../LandModel/Utility_routines/module_date_utilities.F\n!   There are some advantages to having a separate copy here, both compiling and\n!   tailored needs.\nsubroutine geth_idts(newdate, olddate, idt)\n\nimplicit none\n\n!  From 2 input mdates ('YYYY-MM-DD HH:MM:SS.ffff'),\n!  compute the time difference.\n!  on entry     -  newdate  -  the new hdate.\n!                  olddate  -  the old hdate.\n!  on exit      -  idt    -  the change in time.\n!                            Units depend on length of date strings.\n\ncharacter (len=*) , intent(in) :: newdate, olddate\ninteger           , intent(out)   :: idt\n\n!  Local Variables\n\n!  yrnew    -  indicates the year associated with \"ndate\"\n!  yrold    -  indicates the year associated with \"odate\"\n!  monew    -  indicates the month associated with \"ndate\"\n!  moold    -  indicates the month associated with \"odate\"\n!  dynew    -  indicates the day associated with \"ndate\"\n!  dyold    -  indicates the day associated with \"odate\"\n!  hrnew    -  indicates the hour associated with \"ndate\"\n!  hrold    -  indicates the hour associated with \"odate\"\n!  minew    -  indicates the minute associated with \"ndate\"\n!  miold    -  indicates the minute associated with \"odate\"\n!  scnew    -  indicates the second associated with \"ndate\"\n!  scold    -  indicates the second associated with \"odate\"\n!  i        -  loop counter\n!  mday     -  a list assigning the number of days in each month\n\n! ndate, odate: local values of newdate and olddate\ncharacter(len=24) :: ndate, odate\n\ninteger :: oldlen, newlen\ninteger :: yrnew, monew, dynew, hrnew, minew, scnew, frnew\ninteger :: yrold, moold, dyold, hrold, miold, scold, frold\ninteger :: i, newdys, olddys\nlogical :: npass, opass\ninteger :: timesign\ninteger :: ifrc\ninteger, dimension(12) :: mday = (/31,28,31,30,31,30,31,31,30,31,30,31/)\nlogical :: punct\ninteger :: yrstart, yrend, mostart, moend, dystart, dyend\ninteger :: hrstart, hrend, mistart, miend, scstart, scend, frstart\ninteger :: units\n\noldlen = len(olddate)\nnewlen = len(newdate)\nif (newlen.ne.oldlen) then\n#ifdef HYDRO_D\n   write(*,'(\"GETH_IDTS: NEWLEN /= OLDLEN: \", A, 3x, A)') newdate(1:newlen), olddate(1:oldlen)\n   call hydro_stop(\"geth_newdate\")\n#endif\nendif\n\nif (olddate.gt.newdate) then\n   timesign = -1\n\n   ifrc = oldlen\n   oldlen = newlen\n   newlen = ifrc\n\n   ndate = olddate\n   odate = newdate\nelse\n   timesign = 1\n   ndate = newdate\n   odate = olddate\nend if\n\n! Break down old hdate into parts\n\n! Determine if olddate is punctuated or not\nif (odate(5:5) == \"-\") then\n   punct = .TRUE.\n   if (ndate(5:5) /= \"-\") then\n\n      write(*,'(\"GETH_IDTS: Dates appear to be different formats: \", A, 3x, A)') &\n           ndate(1:newlen), odate(1:oldlen)\n      call hydro_stop(\"geth_idts utils_nudging -1\")\n\n   endif\nelse\n   punct = .FALSE.\n   if (ndate(5:5) == \"-\") then\n\n      write(*,'(\"GETH_IDTS: Dates appear to be different formats: \", A, 3x, A)') &\n           ndate(1:newlen), odate(1:oldlen)\n      call hydro_stop(\"geth_idts utils_nudging 0\")\n\n   endif\nendif\n\nif (punct) then\n   yrstart = 1\n   yrend = 4\n   mostart = 6\n   moend = 7\n   dystart = 9\n   dyend = 10\n   hrstart = 12\n   hrend = 13\n   mistart = 15\n   miend = 16\n   scstart = 18\n   scend = 19\n   frstart = 21\n   select case (oldlen)\n   case (10)\n      ! Days\n      units = 1\n   case (13)\n      ! Hours\n      units = 2\n   case (16)\n      ! Minutes\n      units = 3\n   case (19)\n      ! Seconds\n      units = 4\n   case (21)\n      ! Tenths\n      units = 5\n   case (22)\n      ! Hundredths\n      units = 6\n   case (23)\n      ! Thousandths\n      units = 7\n   case (24)\n      ! Ten thousandths\n      units = 8\n   case default\n\n      write(*,*) 'ERROR: geth_idts:  odd length: #'//trim(odate)//'#'\n      call hydro_stop(\"geth_idts utils_nudging 1\")\n\n   end select\nelse\n\n   yrstart = 1\n   yrend = 4\n   mostart = 5\n   moend = 6\n   dystart = 7\n   dyend = 8\n   hrstart = 9\n   hrend = 10\n   mistart = 11\n   miend = 12\n   scstart = 13\n   scend = 14\n   frstart = 15\n\n   select case (oldlen)\n   case (8)\n      ! Days\n      units = 1\n   case (10)\n      ! Hours\n      units = 2\n   case (12)\n      ! Minutes\n      units = 3\n   case (14)\n      ! Seconds\n      units = 4\n   case (15)\n      ! Tenths\n      units = 5\n   case (16)\n      ! Hundredths\n      units = 6\n   case (17)\n      ! Thousandths\n      units = 7\n   case (18)\n      ! Ten thousandths\n      units = 8\n   case default\n\n      write(*,*) 'ERROR: geth_idts:  odd length: #'//trim(odate)//'#'\n      call hydro_stop(\"geth_idts nudging_utils 2\")\n\n   end select\nendif\n\n\nhrold = 0\nmiold = 0\nscold = 0\nfrold = 0\n\nread(odate(yrstart:yrend), '(i4)') yrold\nread(odate(mostart:moend), '(i2)') moold\nread(odate(dystart:dyend), '(i2)') dyold\nif (units.ge.2) then\n   read(odate(hrstart:hrend),'(i2)') hrold\n   if (units.ge.3) then\n      read(odate(mistart:miend),'(i2)') miold\n      if (units.ge.4) then\n         read(odate(scstart:scend),'(i2)') scold\n         if (units.ge.5) then\n            read(odate(frstart:oldlen),*) frold\n         end if\n      end if\n   end if\nend if\n\n!  Break down new hdate into parts\n\nhrnew = 0\nminew = 0\nscnew = 0\nfrnew = 0\n\nread(ndate(yrstart:yrend), '(i4)') yrnew\nread(ndate(mostart:moend), '(i2)') monew\nread(ndate(dystart:dyend), '(i2)') dynew\nif (units.ge.2) then\n   read(ndate(hrstart:hrend),'(i2)') hrnew\n   if (units.ge.3) then\n      read(ndate(mistart:miend),'(i2)') minew\n      if (units.ge.4) then\n         read(ndate(scstart:scend),'(i2)') scnew\n         if (units.ge.5) then\n            read(ndate(frstart:newlen),*) frnew\n         end if\n      end if\n   end if\nend if\n\n!  Check that the dates make sense.\n\nnpass = .true.\nopass = .true.\n\n!  Check that the month of NDATE makes sense.\n\nif ((monew.gt.12).or.(monew.lt.1)) then\n#ifdef HYDRO_D\n   write(*,*) 'GETH_IDTS:  Month of NDATE = ', monew\n#endif\n   npass = .false.\nend if\n\n!  Check that the month of ODATE makes sense.\n\nif ((moold.gt.12).or.(moold.lt.1)) then\n#ifdef HYDRO_D\n   print*, 'GETH_IDTS:  Month of ODATE = ', moold\n#endif\n   opass = .false.\nend if\n\n!  Check that the day of NDATE makes sense.\n\nif (monew.ne.2) then\n   ! ...... For all months but February\n   if ((dynew.gt.mday(monew)).or.(dynew.lt.1)) then\n#ifdef HYDRO_D\n      print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n#endif\n      npass = .false.\n   end if\nelse if (monew.eq.2) then\n   ! ...... For February\n   if ((dynew > nfeb(yrnew)).or.(dynew < 1)) then\n#ifdef HYDRO_D\n      print*, 'GETH_IDTS:  Day of NDATE = ', dynew\n#endif\n      npass = .false.\n   end if\nendif\n\n!  Check that the day of ODATE makes sense.\n\nif (moold.ne.2) then\n   ! ...... For all months but February\n   if ((dyold.gt.mday(moold)).or.(dyold.lt.1)) then\n#ifdef HYDRO_D\n      print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n#endif\n      opass = .false.\n   end if\nelse if (moold.eq.2) then\n   ! ....... For February\n   if ((dyold > nfeb(yrold)).or.(dyold < 1)) then\n#ifdef HYDRO_D\n      print*, 'GETH_IDTS:  Day of ODATE = ', dyold\n#endif\n      opass = .false.\n   end if\nend if\n\n!  Check that the hour of NDATE makes sense.\n\nif ((hrnew.gt.23).or.(hrnew.lt.0)) then\n#ifdef HYDRO_D\n   print*, 'GETH_IDTS:  Hour of NDATE = ', hrnew\n#endif\n   npass = .false.\nend if\n\n!  Check that the hour of ODATE makes sense.\n\nif ((hrold.gt.23).or.(hrold.lt.0)) then\n#ifdef HYDRO_D\n   print*, 'GETH_IDTS:  Hour of ODATE = ', hrold\n#endif\n   opass = .false.\nend if\n\n!  Check that the minute of NDATE makes sense.\n\nif ((minew.gt.59).or.(minew.lt.0)) then\n#ifdef HYDRO_D\n   print*, 'GETH_IDTS:  Minute of NDATE = ', minew\n#endif\n   npass = .false.\nend if\n\n!  Check that the minute of ODATE makes sense.\n\nif ((miold.gt.59).or.(miold.lt.0)) then\n#ifdef HYDRO_D\n   print*, 'GETH_IDTS:  Minute of ODATE = ', miold\n#endif\n   opass = .false.\nend if\n\n!  Check that the second of NDATE makes sense.\n\nif ((scnew.gt.59).or.(scnew.lt.0)) then\n#ifdef HYDRO_D\n   print*, 'GETH_IDTS:  SECOND of NDATE = ', scnew\n#endif\n   npass = .false.\nend if\n\n!  Check that the second of ODATE makes sense.\n\nif ((scold.gt.59).or.(scold.lt.0)) then\n#ifdef HYDRO_D\n   print*, 'GETH_IDTS:  Second of ODATE = ', scold\n#endif\n   opass = .false.\nend if\n\nif (.not. npass) then\n#ifdef HYDRO_D\n   print*, 'Screwy NDATE: ', ndate(1:newlen)\n   call hydro_stop(\"geth_idts nudging_utils 3\")\n#endif\nend if\n\nif (.not. opass) then\n#ifdef HYDRO_D\n   print*, 'FATAL ERROR: Screwy ODATE: ', odate(1:oldlen)\n   call hydro_stop(\"geth_idts nudging_utils 4\")\n#endif\nend if\n\n!  Date Checks are completed.  Continue.\n\n!  Compute number of days from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of hours from 1 January ODATE, 00:00:00 until ndate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until ndate\n\nnewdys = 0\ndo i = yrold, yrnew - 1\n   newdys = newdys + 337 + nfeb(i)\nend do\n\nif (monew .gt. 1) then\n   mday(2) = nfeb(yrnew)\n   do i = 1, monew - 1\n      newdys = newdys + mday(i)\n   end do\n   mday(2) = 28\nend if\n\nnewdys = newdys + dynew - 1\n\n!  Compute number of hours from 1 January ODATE, 00:00:00 until odate\n!  Compute number of minutes from 1 January ODATE, 00:00:00 until odate\n\nolddys = 0\n\nif (moold .gt. 1) then\n   mday(2) = nfeb(yrold)\n   do i = 1, moold - 1\n      olddys = olddys + mday(i)\n   end do\n   mday(2) = 28\nend if\n\nolddys = olddys + dyold -1\n\n!  Determine the time difference\n\nidt = (newdys - olddys)\nif (units.ge.2) then\n   idt = idt*24 + (hrnew - hrold)\n   if (units.ge.3) then\n      idt = idt*60 + (minew - miold)\n      if (units.ge.4) then\n         idt = idt*60 + (scnew - scold)\n         if (units.ge.5) then\n            ifrc = oldlen-(frstart-1)\n            ifrc = 10**ifrc\n            idt = idt * ifrc + (frnew-frold)\n         endif\n      endif\n   endif\nendif\n\nif (timesign .eq. -1) then\n   idt = idt * timesign\nend if\n\nend subroutine geth_idts\n\n\n!===================================================================================================\n! Function Name: get_idts_elemental\n! Author(s)/Contact(s):\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract:\n!   get_idts on a vector.\n!\n! History Log:\n!   10/11/16 -Header Created, JLM\n! Usage:\n!\n! Parameters:\n!\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!\n! User controllable options:\n!   None.\n! Notes:\n!elemental subroutine geth_idts_elemental(newdate, olddate, idt)\n!end\n\n\n\n!===================================================================================================\n! Function Name: nfeb\n! Author(s)/Contact(s):\n!   Wei Yu? or NoahMP developers?\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract:\n!\n! History Log:\n!   7/22/15 -Header Created, JLM\n! Usage:\n!\n! Parameters:\n!\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!\n! User controllable options:\n!   None.\n! Notes:\n!   This routine was copied from ../LandModel/Utility_routines/module_date_utilities.F\n!   There are some advantages to having a separate copy here, both compiling and\n!   tailored needs.\n\ninteger function nfeb(year)\n!\n! Compute the number of days in February for the given year.\n!\nimplicit none\ninteger, intent(in) :: year ! Four-digit year\n\nnfeb = 28 ! By default, February has 28 days ...\nif (mod(year,4).eq.0) then\n   nfeb = 29  ! But every four years, it has 29 days ...\n   if (mod(year,100).eq.0) then\n      nfeb = 28  ! Except every 100 years, when it has 28 days ...\n      if (mod(year,400).eq.0) then\n         nfeb = 29  ! Except every 400 years, when it has 29 days ...\n         if (mod(year,3600).eq.0) then\n            nfeb = 28  ! Except every 3600 years, when it has 28 days.\n         endif\n      endif\n   endif\nendif\nend function nfeb\n\n!===================================================================================================\n! Function Name: nmdays\n! Author(s)/Contact(s):\n!   Wei Yu? or NoahMP developers?\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract:\n!\n! History Log:\n!   7/22/15 -Header Created, JLM\n! Usage:\n!\n! Parameters:\n!\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!\n! User controllable options:\n!   None.\n! Notes:\n!   This routine was copied from ../LandModel/Utility_routines/module_date_utilities.F\n!   There are some advantages to having a separate copy here, both compiling and\n!   tailored needs.\n\ninteger function nmdays(hdate)\n!\n! Compute the number of days in the month of given date hdate.\n!\nimplicit none\ncharacter(len=*), intent(in) :: hdate\n\ninteger :: year, month\ninteger, dimension(12), parameter :: ndays = (/ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 /)\n\nread(hdate(1:7), '(I4,1x,I2)') year, month\n\nif (month == 2) then\n   nmdays = nfeb(year)\nelse\n   nmdays = ndays(month)\nendif\nend function nmdays\n\n!===================================================================================================\n! Function Name: monthabbr_to_mm\n! Author(s)/Contact(s):\n!   Wei Yu? or NoahMP developers?\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract:\n!\n! History Log:\n!   7/22/15 -Header Created, JLM\n! Usage:\n!\n! Parameters:\n!\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!\n! User controllable options:\n!   None.\n! Notes:\n!   This routine was copied from ../LandModel/Utility_routines/module_date_utilities.F\n!   There are some advantages to having a separate copy here, both compiling and\n!   tailored needs.\n\nfunction monthabbr_to_mm(mon) result(mm)\nimplicit none\n\ncharacter(len=3), intent(in) :: mon\n\ninteger :: mm\n\nif (mon == \"Jan\") then\n   mm = 1\nelseif (mon == \"Feb\") then\n   mm = 2\nelseif (mon == \"Mar\") then\n   mm = 3\nelseif (mon == \"Apr\") then\n   mm = 4\nelseif (mon == \"May\") then\n   mm = 5\nelseif (mon == \"Jun\") then\n   mm = 6\nelseif (mon == \"Jul\") then\n   mm = 7\nelseif (mon == \"Aug\") then\n   mm = 8\nelseif (mon == \"Sep\") then\n   mm = 9\nelseif (mon == \"Oct\") then\n   mm = 10\nelseif (mon == \"Nov\") then\n   mm = 11\nelseif (mon == \"Dec\") then\n   mm = 12\nelse\n\n   write(*, '(\"Function monthabbr_to_mm:  mon = <\",A,\">\")') mon\n   print*,  \"FATAL ERROR: Function monthabbr_to_mm:  Unrecognized mon\"\n   call hydro_stop(\"monthabbr_to_mm\")\n\nendif\nend function monthabbr_to_mm\n\n!===================================================================================================\n! Subroutine Name: swap_date_format\n! Author(s)/Contact(s):\n!   Wei Yu? or NoahMP developers?\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract:\n!\n! History Log:\n!   7/22/15 -Header Created, JLM\n! Usage:\n!\n! Parameters:\n!\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!\n! User controllable options:\n!   None.\n! Notes:\n!   This routine was copied from ../LandModel/Utility_routines/module_date_utilities.F\n!   There are some advantages to having a separate copy here, both compiling and\n!   tailored needs.\n\nsubroutine swap_date_format(indate, outdate)\nimplicit none\ncharacter(len=*), intent(in)  :: indate\ncharacter(len=*), intent(out) :: outdate\ninteger :: inlen\n\ninlen = len(indate)\nif (indate(5:5) == \"-\") then\n   select case (inlen)\n   case (10)\n      ! YYYY-MM-DD\n      outdate = indate(1:4)//indate(6:7)//indate(9:10)\n   case (13)\n      ! YYYY-MM-DD_HH\n      outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)\n   case (16)\n      ! YYYY-MM-DD_HH:mm\n      outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)\n   case (19)\n      ! YYYY-MM-DD_HH:mm:ss\n      outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)//&\n           indate(18:19)\n   case (21,22,23,24)\n      ! YYYY-MM-DD_HH:mm:ss.f[f[f[f]]]\n      outdate = indate(1:4)//indate(6:7)//indate(9:10)//indate(12:13)//indate(15:16)//&\n           indate(18:19)//indate(21:inlen)\n   case default\n#ifdef HYDRO_D\n      write(*,'(\"Unrecognized length: <\", A,\">\")') indate\n      call hydro_stop(\"swap_date_format\")\n#endif\n   end select\nelse\n   select case (inlen)\n   case (8)\n      ! YYYYMMDD\n      outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)\n   case (10)\n      ! YYYYMMDDHH\n      outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n           indate(9:10)\n   case (12)\n      ! YYYYMMDDHHmm\n      outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n           indate(9:10)//\":\"//indate(11:12)\n   case (14)\n      ! YYYYMMDDHHmmss\n      outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n           indate(9:10)//\":\"//indate(11:12)//\":\"//indate(13:14)\n   case (15,16,17,18)\n      ! YYYYMMDDHHmmssf[f[f[f]]]\n      outdate = indate(1:4)//\"-\"//indate(5:6)//\"-\"//indate(7:8)//\"_\"//&\n           indate(9:10)//\":\"//indate(11:12)//\":\"//indate(13:14)//\".\"//indate(15:inlen)\n   case default\n\n      write(*,'(\"FATAL ERROR: Unrecognized length: <\", A,\">\")') indate\n      call hydro_stop(\"swap_date_format\")\n\n   end select\nendif\n\nend subroutine swap_date_format\n\n!===================================================================================================\n! Function Name: mm_to_monthabbr\n! Author(s)/Contact(s):\n!   Wei Yu? or NoahMP developers?\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract:\n!\n! History Log:\n!   7/22/15 -Header Created, JLM\n! Usage:\n!\n! Parameters:\n!\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!\n! User controllable options:\n!   None.\n! Notes:\n!   This routine was copied from ../LandModel/Utility_routines/module_date_utilities.F\n!   There are some advantages to having a separate copy here, both compiling and\n!   tailored needs.\n\ncharacter(len=3) function mm_to_monthabbr(ii) result(mon)\nimplicit none\ninteger, intent(in) :: ii\ncharacter(len=3), parameter, dimension(12) :: month = (/ &\n     \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", &\n     \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" /)\nif (ii > 0 .and. ii < 13 ) then\n   mon = month(ii)\nelse\n\n   print*, \"FATAL ERROR: mm_to_monthabbr\"\n   call hydro_stop(\"mm_to_monthabbr\")\n\nendif\nend function mm_to_monthabbr\n\n!===================================================================================================\n! Function Name: round_resolution_minute\n! Author(s)/Contact(s):\n!   James L McCreight, jamesmcc><ucar><edu\n! Abstract: Round a time to some time resolution specified in minutes:\n!           1) the resolution evenly divides 60\n!           2) the first time chunk in a hour is centered on 0 minutes and\n!              subesquent chunks are centered on N*resoluton (mod 60).\n! History Log:\n!   7/29/15 -Header Created, JLM\n! Usage:\n!\n! Parameters:\n!\n! Input Files:\n!   None.\n! Output Files:\n!   None.\n! Condition codes:\n!   None.\n! User controllable options:\n!   None.\n! Notes: Some tests:\n! print*,round_resolution_minute('2003-02-01_01:00:00', 5)\n! print*,round_resolution_minute('2003-02-01_01:02:29', 5)\n! print*,round_resolution_minute('2003-02-01_01:02:30', 5)\n! print*,round_resolution_minute('2003-02-01_01:57:29', 5)\n! print*,round_resolution_minute('2003-02-01_01:57:30', 5)\n! print*,''\n! print*,round_resolution_minute('2003-02-01_01:00:00', 15)\n! print*,round_resolution_minute('2003-02-01_01:07:29', 15)\n! print*,round_resolution_minute('2003-02-01_01:07:30', 15)\n! print*,round_resolution_minute('2003-02-01_01:52:29', 15)\n! print*,round_resolution_minute('2003-02-01_01:52:30', 15)\n\nfunction round_resolution_minute(time, resolution)\nimplicit none\ncharacter(len=19)             :: round_resolution_minute ! return value\ncharacter(len=19), intent(in) :: time         ! time to round\ninteger                       :: resolution   ! the time resolution in minutes\n\ninteger :: diffMin\nreal    :: resolutionInv, theMinute, theSecond, resMin\ncharacter(len=19) :: roundTime, timeCopy\n\n! nearest defines a time resolution\nresolutionInv = 1./resolution\n!1234567890123456789\n!YYYY-MM-DD_HH:mm:ss\nread(time(15:16),*) theMinute\nread(time(18:19),*) theSecond\ntheMinute = theMinute + (theSecond/60.)\n! What fraction of the time resolution is the current time?\nresMin = (theMinute * resolutionInv)\n! Round to the time resolution.\n! nint doesnt document its rounding rule on gfortran! boo.\nif(resMin - floor(resMin) .ge. .5) resMin=ceiling(resMin)\nif(resMin - floor(resMin) .lt. .5) resMin=floor(resMin)\n! Convert back to regular minutes.\nresMin = resMin / resolutionInv\n! To get the exact right time, some floor/ceil operations are helpful.\ntimeCopy = time\ntimeCopy(18:19) = '00' ! Floor of theMinute in string form\n! nint is needed b/c resMin is real and often slightly off integer,\n! and this is exacerbated by *60\ndiffMin = (nint(resMin) - floor(theMinute))*60\n!print*, nint(resMin), floor(theMinute), timeCopy, diffMin\ncall geth_newdate(round_resolution_minute, timeCopy, diffMin)\n\nend function round_resolution_minute\n\n\n\nend module module_date_utils_nudging\n"
  },
  {
    "path": "src/nudging/module_nudging_utils.F90",
    "content": "module module_nudging_utils\n\nreal :: totalNudgeTime\ninteger :: sysClockCountRate, sysClockCountMax\ncharacter(len=4) :: clockType\n\ncontains\n\n!===================================================================================================\n! NOTE for whichUtilites\n! whUniLoop was fastest for single index searches.\n! I still havent tested multiple index searches (which and whichLoop)\n\n\n!===================================================================================================\n! Program Names:\n!   functions: whichPack and whichLoop\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Identify indices in a vector which are TRUE, reutrns zero length vector\n!   if there are no matches.\n! History Log:\n!   6/04/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\n!   JLM: Recent catastrophic failure reported for pack on ifort, with work arround.\n!   JLM: https://software.intel.com/en-us/forums/topic/559308#comments\n\nsubroutine whichPack(theMask, which, nWhich)\nimplicit none\nlogical, allocatable, intent(in),  dimension(:) :: theMask\ninteger,              intent(out), dimension(:) :: which\ninteger,              intent(out)               :: nwhich\n\ninteger :: ii\nwhich = -9999\nnWhich = sum( (/ (1, ii=1,size(theMask)) /), mask=theMask)\nif(nWhich .gt. size(which)) then\n   which = -9999\n   return\nend if\nwhich(1:nWhich) = pack( (/ (ii, ii=1,size(theMask)) /), mask=theMask)\nend subroutine whichPack\n\nsubroutine whichLoop(theMask, which, nWhich)\nimplicit none\nlogical, intent(in),  dimension(:) :: theMask\ninteger, intent(out), dimension(:) :: which\ninteger, intent(out)               :: nwhich\n\ninteger :: ii\nwhich = -9999\nnWhich = 1\ndo ii=1,size(theMask)\n   if(nWhich .gt. size(which)) then\n      which = -9999\n      return\n   end if\n   if(theMask(ii)) then\n      which(nWhich)=ii\n      nWhich = nWhich + 1\n   endif\nend do\nnWhich = nWhich-1\nend subroutine whichLoop\n\n!===================================================================================================\n! Program Names:\n!   function: whUnique\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Identify THE index in a logical vector which is TRUE. Returns\n!   -1 if not unique or none are true.\n! History Log:\n!   6/04/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\n\nfunction whUnique(theMask, unsafe)\n  implicit none\n  integer                             :: whUnique !! return value\n  logical, allocatable, dimension(:), intent(in)  :: theMask\n  logical, optional, intent(in)  :: unsafe\n  integer, allocatable, dimension(:) :: whUniques\n  integer :: i, nMatches\n  if(present(unsafe)) then\n     !whUniques=pack( (/ (i, i=1,size(theMask)) /), mask= theMask)\n     !whUnique = whUniques(1)\n     whUnique=sum( (/ (i, i=1,size(theMask)) /), mask= theMask)\n  else\n     nMatches = sum( (/ (1, i=1,size(theMask)) /), mask= theMask )\n     if (nMatches .gt. 1 .OR. nMatches .eq. 0) then\n        whUnique=-1\n     else\n        whUnique=sum( (/ (i, i=1,size(theMask)) /), mask= theMask)\n     end if\n  end if\nend function whUnique\n\n\n!===================================================================================================\n! Program Names:\n!   function: whUnique\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Simply returns the first match, no check for uniques. On gfortran this\n!    was the fastest of the bunch even/especially for max indices on huge arrays.\n! History Log:\n!   6/04/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\n\nfunction whUniLoop(theMask)\n  implicit none\n  integer                                         :: whUniLoop !! return value\n  logical, allocatable, dimension(:), intent(in)  :: theMask\n  integer :: ii\n  whUniLoop = -9999\n  do ii=1,size(theMask)\n     if(theMask(ii)) then\n        whUniLoop = ii\n        return\n     end if\n  end do\nend function whUniLoop\n\n!===================================================================================================\n! Program Names:\n!   function: whInLoop\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Identify the indices of elements in a first vector which are present in the \n!   second vector, returns 0 for no matches. This can be slow, it's a double do/for loop.\n! History Log:\n!   6/04/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes: Can be slow, use with caution.\n\n! parallelize this? ||||||||||||||||||||||||||||||||||\nsubroutine whichInLoop(vecToSearch, vecToMatch, which, nWhich)\nimplicit none\ncharacter(len=15), intent(in),  dimension(:) :: vecToSearch\ncharacter(len=15), intent(in),  dimension(:) :: vecToMatch\ninteger, intent(out), dimension(:) :: which\ninteger, intent(out)               :: nWhich\ninteger :: ii, jj\nwhich = -9999\nnWhich = 0\ndo ii=1,size(vecToSearch)\n   do jj=1,size(vecToMatch)\n      if(trim(adjustl(vecToSearch(ii))) .eq. trim(adjustl(vecToMatch(jj)))) then\n         which(ii)=ii\n         nWhich = nWhich + 1\n         exit\n      end if\n   end do\nend do\nend subroutine whichInLoop\n\n\n! parallelize this? ||||||||||||||||||||||||||||||||||\nsubroutine whichInLoop2(vecToSearch, vecToMatch, which, nWhich)\nimplicit none\ncharacter(len=15), intent(in),  dimension(:) :: vecToSearch\ncharacter(len=15), intent(in),  dimension(:) :: vecToMatch\ninteger, intent(out), dimension(:) :: which\ninteger, intent(out)               :: nWhich\ninteger :: ii, jj\nwhich = -9999\nnWhich = 0\ndo ii=1,size(vecToSearch)\n   if(any(vecToMatch .eq. vecToSearch(ii))) then\n      which(ii)=ii\n      nWhich = nWhich + 1\n   end if\nend do\nend subroutine whichInLoop2\n\n\n!===================================================================================================\n! Program Names:\n!   accum_nudging_time\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Tally up the total cpu or wall time used by nudging.\n! History Log:\n!   8/20/15 -Created, JLM.\n! Usage:\n! Parameters:\n!   start, end: real times for end-diff timing & accumulation\n!   sectionLabel: prints a message with the timing for the section\n!      print*, 'Ndg: ' // sectionLabel // '(seconds ' // trim(clockType) // ' time):', diff\n!   optional - accum: accumulate this towards the overall time or simply print the above \n!      message? Do not accum for nested sections of code, but still give the diagnostic.\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\nsubroutine accum_nudging_time(start, end, sectionLabel, accum)\nimplicit none\nreal,              intent(in) :: start, end\ncharacter(len=*),  intent(in) :: sectionLabel\nlogical, optional, intent(in):: accum\nlogical :: accumLocal\nreal :: diff\naccumLocal=.TRUE.\nif(present(accum)) accumLocal = accum\ndiff=end-start\nif(clockType.eq.'wall') then\n   if(diff .lt. 0) diff = diff + sysClockCountMax\n   diff=diff/sysClockCountRate\nendif\nif (accumLocal) totalNudgeTime = totalNudgeTime + diff\n\nprint*,'Ndg: Timing: ' // sectionLabel // ' (' // trim(clockType) // ' time, seconds):', diff\n\nif(accumLocal) print*,'Ndg: Timing: accum totalNudgeTime: ',totalNudgeTime\nend subroutine accum_nudging_time\n\n\n!===================================================================================================\n! Program Names:\n!   nudging_timer\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Return your choice of cpu time or wall time\n! History Log:\n!   8/20/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:\nsubroutine nudging_timer(time)\nimplicit none\nreal, intent(inout) :: time\ninteger :: count\nif(clockType.eq.'cpu') call cpu_time(time)\nif(clockType.eq.'wall') then\n   call system_clock(count=count)\n   time=real(count)\nend if\nend subroutine nudging_timer\n\n\n!===================================================================================================\nend module module_nudging_utils\n"
  },
  {
    "path": "src/nudging/module_stream_nudging.F90",
    "content": "module module_stream_nudging\n\n  use config_base, only: nlst\n  use module_nudging_io,    only: lastObsStructure, lastObsStructure_SoA\n#ifdef MPP_LAND\n  use module_mpp_land\n  use module_mpp_reachls,  only: ReachLS_write_io\n#endif\n  use module_hydro_stop, only:HYDRO_stop\n\nimplicit none\n!===================================================================================================\n! Module Variables\n\n!========================\n! obs and obsTime data structures. Each entry in obsTime holds a timeslice file, with the\n! individual obs in the obsStr.\ntype obsStructure\n   character(len=15) :: usgsId        ! the 15 char USGS identifier.\n   character(len=19) :: obsTime       ! observation at gage dims: nGages\n   real              :: obsDischarge  ! observation at gage dims: nGages\n   real              :: obsQC         ! quality control factpr [0,1]\n   integer           :: obsStaticInd  ! the index to the obsStaticStr where static info is kept\n   real              :: innov         ! obs-modeled\nend type obsStructure\n\ntype obsTimeStructure\n   character(len=19) :: time\n   character(len=19) :: updateTime\n   integer, allocatable, dimension(:) :: allCellInds  ! cell indices affected at this time\n   integer, allocatable, dimension(:) :: nGageCell    ! number of gages for each affected cell ind\n   type(obsStructure),   allocatable, dimension(:) :: obsStr ! the obs at this file time / timeslice\nend type obsTimeStructure\n\n! The top level structure used to solve the nudges\ntype(obsTimeStructure), allocatable, dimension(:) :: obsTimeStr ! size=nObsTimes\n\n!========================\n! lastObs structure, corresponding to nudgingLastObs.YYYY-mm-dd_HH:MM:ss.nc\n! How observations from the past are carried forward.\n! Type defined in module_nudging_io.F\ntype(lastObsStructure), allocatable, dimension(:) :: lastObsStr\ntype(lastObsStructure_SoA) :: lastObsStr_SoA\n\n!========================\n! This holds static information for a given gage for a given cycle (when R, G, and tau) do not\n! change.\n! The \"lastObs\" variables are not exactly static... they were an afterthought and this was\n! by far the best place for them to live.\ntype, extends(lastObsStructure) :: obsStaticStructure\n   !! Inherited components\n   !!character(len=15) :: usgsId        ! the 15 char USGS identifier.\n   !!real              :: lastObsDischarge(:)       ! last observed discharge\n   !!character(len=19) :: lastObsTime(:)            ! time of last obs discharge (.le.hydroTime)\n   !!real              :: lastObsQuality(:)         ! quality of the last obs discharge\n   !!real              :: lastObsModelDischarge(:)  ! the modeled discharge value at the time of the last obs\n   !! New components\n   integer, allocatable, dimension(:) ::  cellsAffected  ! indices of cells affected\n   real,    allocatable, dimension(:) ::  dist           ! optional: dist to affected cells, optional\n   real,    allocatable, dimension(:) ::  ws             ! spatial cressman weights at affected cells discharge.\nend type obsStaticStructure\n\ntype, extends(lastObsStructure_SoA) :: obsStaticStructure_SoA\n   !! Inherited components\n   !!character(len=15) :: usgsId        ! the 15 char USGS identifier.\n   !!real              :: lastObsDischarge(:)       ! last observed discharge\n   !!character(len=19) :: lastObsTime(:)            ! time of last obs discharge (.le.hydroTime)\n   !!real              :: lastObsQuality(:)         ! quality of the last obs discharge\n   !!real              :: lastObsModelDischarge(:)  ! the modeled discharge value at the time of the last obs\n   !! New components\n   integer, allocatable :: obsCellInd(:)    ! index of obs on model channel network, for distance calc\n   real,allocatable    :: R(:), G(:), tau(:)     ! the nudging parameters at this gage.\nend type obsStaticStructure_SoA\n\n! The static obs/gage information - store here to perform calculations\n! only once per cycle.\n! Currently the dimensions of this are fixed to 10000 which should\n! work for the forseeable future. May want to consider some routine for\n! augmenting this size if necessary.\ntype(obsStaticStructure), allocatable, dimension(:) :: obsStaticStr\ntype(obsStaticStructure_SoA) :: obsStaticStr_Soa\n\n!! The number of up/down stream links which can be collected\n!! using R to solve which links are \"neighboring\".\n!! This value applies to both directions, it's the number\n!! of links per R.\ninteger, parameter :: maxNeighLinksDim=5000\n\n!========================\n! Node and gage collocation - For reach based routing, corresponds to the \"gage\" column\n! of RouteLink.nc.\ntype nodeGageStructure\n   integer,           allocatable, dimension(:) :: nodeId\n   character(len=15), allocatable, dimension(:) :: usgsId\nend type nodeGageStructure\ntype(nodeGageStructure) :: nodeGageTmp, nodeGageStr\ninteger :: nGagesDomain   ! the number of gages specified\n\n!========================\n! Nudging parameters structure, corresponding to NudgeParams.nc file.\n!! for dealloction purposes, might be better to put the dimension onthe derived type.\ntype nudgingParamStructure\n   character(len=15), allocatable, dimension(:)     :: usgsId\n   real,              allocatable, dimension(:)     :: R\n   real,              allocatable, dimension(:)     :: G\n   real,              allocatable, dimension(:)     :: tau\n   real,              allocatable, dimension(:,:,:) :: qThresh  !! gage, month, nThresh\n   real,              allocatable, dimension(:,:,:) :: expCoeff !! gage, month, nThresh\nend type nudgingParamStructure\ntype(nudgingParamStructure) :: nudgingParamsTmp, nudgingParamsStr\n\n!========================\n! Network reExpression structure, corresponding to netwkReExFile.nc\ntype netwkReExpStructure\n   integer*4, allocatable, dimension(:) :: go\n   integer*4, allocatable, dimension(:) :: start\n   integer*4, allocatable, dimension(:) :: end\nend type netwkReExpStructure\ntype(netwkReExpStructure) :: downNetwkStr, upNetwkStr\n\n!========================\n! Track gages from NWIS not in our param file and not in the intersection or\n! the Route_Link gages and the gages in the parameter file.\ninteger, parameter :: maxNwisNotRLAndParamsCount=20000\ncharacter(len=15), dimension(maxNwisNotRLAndParamsCount) :: nwisNotRLAndParams\ninteger :: nwisNotRLAndParamsCount\n\n!========================\n! Random data\nreal, allocatable, dimension(:) :: t0Discharge\n\n!========================\n! Control book keeping\nlogical :: nudgeThisLsmTimeStep\n\n!! JLM: these options are hardcoded/hardwired for now, evnt go in namelist\ninteger,            parameter :: obsResolutionInt = 15 ! minutes\nreal,               parameter :: obsCheckFreq     = 90 ! minutes\nlogical,            parameter :: filterObsToDom   = .TRUE.\ncharacter(len=15),  parameter :: missingGage = '               '\nlogical,            parameter :: nudgeWAdvance = .FALSE.\ncharacter(len=4),   parameter :: nudgingClockType = 'wall'\nlogical,            parameter :: sanityQcDischarge = .true.\nlogical,            parameter :: readTimesliceErrFatal = .false.\nlogical,            parameter :: futureLastObsFatal = .true.\nlogical,            parameter :: futureLastObsZero  = .false.\nreal,               parameter :: invDistTimeWeightExp = 5.000\nreal,               parameter :: noConstInterfCoeff   = 1.0 !0.500\n\n! hydro.namelist: &NUDGING_nlist  variables.\ncharacter(len=256) :: nudgingParamFile\ncharacter(len=256) :: netwkReExFile\ncharacter(len=256) :: nudgingLastObsFile    !! passed by namelist\ncharacter(len=256) :: nudgingLastObsFileTry !! either the passed or, if not passed, a default\nlogical            :: readTimesliceParallel\nlogical            :: temporalPersistence\nlogical            :: persistBias\nlogical            :: biasWindowBeforeT0\ninteger            :: nTimesLastObs   !! aka nlst_rt(did)%nLastObs\ninteger            :: minNumPairsBiasPersist\ninteger            :: maxAgePairsBiasPersist\nlogical            :: invDistTimeWeightBias\nlogical            :: noConstInterfBias\n\n!========================\n! Space book keeping\nlogical :: nudgeSpatial = .true.  !! is spatial interpolation of nudging active?\ninteger,   parameter :: did=1     !! 1 for WRF-uncoupled runs...\n\n!========================\n! Time book keeping\nreal    :: maxTau\ninteger :: nObsTimes\ncharacter(len=19) :: lsmTime, initTime\ninteger :: lsmDt                                   !1234567890123456789\ncharacter(len=19), parameter :: missingLastObsTime='9999999999999999999'\ncharacter(len=2) :: obsResolution\nlogical :: gotT0Discharge\n\n#ifdef HYDRO_D\ninteger, parameter :: flushUnit=6\nlogical, parameter :: flushAll=.true.\n#endif\n\n#ifdef MPP_LAND\n!========================\n! Parallel book keeping\nreal, allocatable, dimension(:) :: chanlen_image0    !A global version kept on image 0\n#endif\n\n\ncontains\n\n!===================================================================================================\n! Program Names:\n!   init_stream_nudging_clock\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   One-time initialization of diagnostic stream nuding clock.\n! History Log:\n!   10/08/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files: None.\n! Condition codes: this only gets called if #ifdef HYDRO_D?\n! User controllable options: None.\n! Notes:\n\nsubroutine init_stream_nudging_clock\nuse module_nudging_utils, only: totalNudgeTime,    &\n                                sysClockCountRate, &\n                                sysClockCountMax,  &\n                                clockType\n\nimplicit none\ntotalNudgeTime = 0. ! Nudging time accumulation init.\ncall system_clock(count_rate=sysClockCountRate, count_max=sysClockCountMax)\nclockType = trim(nudgingClockType)\n!!$#ifdef HYDRO_D  /* un-ifdef to get timing results */\n!!$print*,'Ndg: totalNudgeTime: ', totalNudgeTime\n!!$print*,'Ndg: sysClockCountRate: ', sysClockCountRate\n!!$print*,'Ndg: sysClockCountMax: ', sysClockCountMax\n!!$print*,'Ndg: clockType: ', trim(nudgingClockType)\n!!$if(flushAll) flush(flushUnit)\n!!$#endif /* HYDRO_D un-ifdef to get timing results */\nend subroutine init_stream_nudging_clock\n\n\n!===================================================================================================\n! Program Names:\n!   init_stream_nudging\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   One-time initialization of certain stream nuding information. Some of this infomation\n!   may be updated later in the run, but probably not frequently.\n! History Log:\n!   7/23/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files: currently hardwired module variables\n!   nudgingParamFile\n!   gageGageDistFile\n!   netwkReExFile\n! Output Files: None.\n! Condition codes:\n! User controllable options: None.\n! Notes:\n\nsubroutine init_stream_nudging\n\nuse module_RT_data,  only: rt_domain\nuse module_nudging_utils, only: whichInLoop2,       &\n                                nudging_timer,      &\n                                accum_nudging_time\nuse module_nudging_io,    only: get_netcdf_dim,                      &\n                                read_gridded_nudging_frxst_gage_csv, &\n                                read_reach_gage_collocation,         &\n                                read_nudging_param_file,             &\n                                read_network_reexpression,           &\n                                find_nudging_last_obs_file,          &\n                                read_nudging_last_obs, &\n                                read_nudging_last_obs_soa\nuse module_mpp_reachls,  only: ReachLS_decomp\n\nimplicit none\n\ninteger                    :: nLinks, nLinksL\n!integer, dimension(nlinks) :: strmFrxstPts\ninteger :: did=1\ninteger :: ii, kk, ll, tt, count, toSize, fromSize\ninteger :: nParamGages, nParamMonth, nParamThresh, nParamThreshCat, nGgDists, nGgDistsKeep\ninteger :: nWhGageDists1, nWhGageDists2, nGagesWParamsDom\ninteger, allocatable, dimension(:) ::  whParamsDom\nreal,    allocatable, dimension(:) :: g_nudge\ninteger :: downSize, upSize, baseSize, nStnLastObs\ncharacter(len=256) :: lastObsFile             !! confirms existence of a file\nlogical :: lastObsFileFound\n!!$#ifdef HYDRO_D  /* un-ifdef to get timing results */\n!!$real :: startCodeTimeAcc, endCodeTimeAcc\n!!$\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) &\n!!$#endif\n!!$     call nudging_timer(startCodeTimeAcc)\n!!$#endif /* HYDRO_D */  /* un-ifdef to get timing results */\n\n!!$#ifdef HYDRO_D\n!!$print*, \"Ndg: Start init_stream_nudging\"\n!!$#ifdef MPP_LAND\n!!$print*, 'Ndg: PARALLEL NUDGING!'\n!!$#endif\n!!$if(flushAll) flush(flushUnit)\n!!$#endif /* HYDRO_D */\n\n!! this ifdef is bizarre problem with pgf compiler\n!#ifdef WRF_HYDRO_NUDGING !JLM\nnudgingParamFile       = nlst(did)%nudgingParamFile\nnetwkReExFile          = nlst(did)%netwkReExFile\nreadTimesliceParallel  = nlst(did)%readTimesliceParallel\ntemporalPersistence    = nlst(did)%temporalPersistence\npersistBias            = nlst(did)%persistBias\nbiasWindowBeforeT0     = nlst(did)%biasWindowBeforeT0\nnudgingLastObsFile     = nlst(did)%nudgingLastObsFile\nnTimesLastObs          = nlst(did)%nLastObs\nminNumPairsBiasPersist = nlst(did)%minNumPairsBiasPersist\nmaxAgePairsBiasPersist = nlst(did)%maxAgePairsBiasPersist\ninvDistTimeWeightBias  = nlst(did)%invDistTimeWeightBias\nnoConstInterfBias      = nlst(did)%noConstInterfBias\n!#endif\n\nnLinks       = RT_DOMAIN(did)%NLINKS   ! For gridded channel routing\n#ifdef MPP_LAND\nnLinksL      = RT_DOMAIN(did)%gNLINKSL  ! For reach-based routing in parallel, no decomp for nudging\n#else\nnLinksL      = RT_DOMAIN(did)%NLINKSL   ! For reach-based routing\n#endif\n\n!Variable init\nnwisNotRLAndParams = missingGage\nnwisNotRLAndParamsCount=0\ngotT0Discharge = .false.\n\n!=================================================\n! 0. This routine is called with condition that chanrtswcrt.ne.0 in module_HYDRO_drv\n\n!=================================================\n! 1. Gage link/node collocation.\n! which gages are actually in the domain?\n! Musk routines: use routelink csv! New column for associated gage Id for each link.\n! Grid channel : frxst_pts layer in Fulldom, and a new Nudge_frxst_gage.csv file, which\n!                simply contains frxst_pts index and the associated gage ID, *** may be blank?***\n!========================\n!!$! Gridded channel routing is option 3\n!!$if (nlst_rt(did)%channel_option .eq. 3) then\n!!$   strmfrxstpts = RT_DOMAIN(did)%STRMFRXSTPTS\n!!$   ! For gridded channel routing, setup the relationship between frxst_pts and gage IDs via\n!!$   ! the Nudging_frxst_gage.csv.\n!!$   ! For now this is a csv, but it should be netcdf in the long run.\n!!$#ifdef HYDRO_D\n!!$   print*, 'Ndg: Start initializing Nudging_frxst_gage.csv'\n!!$#endif\n!!$   !! allocate the maximum number of gages, say 8000.\n!!$   allocate(nodeGageTmp%nodeId(maxGages), nodeGageTmp%usgsId(maxGages))\n!!$   ! This actually returns frxst point from the file...\n!!$   call read_gridded_nudging_frxst_gage_csv(nodeGageTmp%nodeId, nodeGageTmp%usgsId, nGagesDomain)\n!!$   ! ... we'll convert this to index on the stream network.\n!!$   allocate(nodeGageStr%nodeId(nGagesDomain), nodeGageStr%usgsId(nGagesDomain))\n!!$\n!!$   !! JLM: need to handle desired frxst points which are not gages.\n!!$   !! Need to make sure these are a complete set 1:nGages.\n!!$   do ll=1,nLinks\n!!$      if(strmFrxstPts(ll) .ne. -9999) then\n!!$         nodeGageStr%nodeId(strmFrxstPts(ll)) = ll\n!!$         nodeGageStr%usgsId(strmFrxstPts(ll)) = adjustr(nodeGageTmp%usgsId(strmFrxstPts(ll)))\n!!$      end if\n!!$   end do\n!!$\n!!$   deallocate(nodeGageTmp%nodeId, nodeGageTmp%usgsId)\n!!$\n!!$#ifdef HYDRO_D\n!!$   print*,nGagesDomain\n!!$   print*,nodeGageStr%nodeId\n!!$   print*,nodeGageStr%usgsId\n!!$   print*, 'Ndg: Finish initializing Nudging_frxst_gage.csv'\n!!$#endif\n!!$end if ! gridded channel models\n\n!========================\n! Muskingum routines are channel_options 1 and 2\nif (nlst(did)%channel_option .eq. 1 .or. &\n    nlst(did)%channel_option .eq. 2) then\n\n   ! For reach-based/muskingum routing methods, we are currently requiring\n   ! the netcdf file for input of gages.\n\n#ifdef MPP_LAND\n   if(my_id .eq. io_id) then\n#endif\n\n#ifdef HYDRO_D\n      print*, 'Ndg: Start initializing reach gages (netcdf)'\n      if(flushAll) flush(flushUnit)\n#endif\n\n      allocate(nodeGageTmp%usgsId(nLinksL))\n      call read_reach_gage_collocation(nodeGageTmp%usgsId)\n\n      nGagesDomain=0\n      !check: nLinksL .eq. size(nodeGageTmp%usgsId)\n      !do ll=1,nLinksL\n      do ll=1,size(nodeGageTmp%usgsId)\n         if(nodeGageTmp%usgsId(ll) .ne. missingGage) nGagesDomain=nGagesDomain+1\n      end do\n\n      if(nGagesDomain .gt. 0) then\n         allocate(nodeGageStr%nodeId(nGagesDomain), nodeGageStr%usgsId(nGagesDomain))\n         nodeGageStr%usgsId = pack(nodeGageTmp%usgsId, mask=nodeGageTmp%usgsId .ne. missingGage)\n         ! This just index, we are NOT using comIds in nudging.\n         ! nodeGageStr%nodeId = pack(rt_domain(did)%linkId, mask=nodeGageTmp%usgsId .ne. '')\n         nodeGageStr%nodeId = pack((/(ii, ii=1,nLinksL)/), mask=nodeGageTmp%usgsId .ne. missingGage)\n      end if\n      deallocate(nodeGageTmp%usgsId)\n\n#ifdef HYDRO_D\n      print*,'Ndg: nGagesDomain:',nGagesDomain\n      print*,'Ndg: nLinksL', nLinksL\n      print*,\"Ndg: size(nodeGageStr%nodeId):\", size(nodeGageStr%nodeId)\n      print*,&\n     'Ndg: nodeGageStr%usgsId((size(nodeGageStr%nodeId)-nGagesDomain+1):(size(nodeGageStr%nodeId))):',&\n           nodeGageStr%usgsId((size(nodeGageStr%nodeId)-nGagesDomain+1):(size(nodeGageStr%nodeId)))\n      print*,'Ndg: Finish initializing reach gages (netcdf)'\n      if(flushAll) flush(flushUnit)\n#endif\n\n#ifdef MPP_LAND\n   end if ! my_id .eq. io_id\n   !! Broadcast\n   call mpp_land_bcast_int1(nGagesDomain)\n   if(my_id .ne. io_id) then\n      allocate(nodeGageStr%nodeId(nGagesDomain))\n      allocate(nodeGageStr%usgsId(nGagesDomain))\n   endif\n   call mpp_land_bcast_char1d(nodeGageStr%usgsId)\n   call mpp_land_bcast_int1d(nodeGageStr%nodeId)\n#endif\n\nend if ! muskingum channel models\n\n!=================================================\n! 3. Read nudging parameter files and reduce to the gages in the domain (nGagesDomain, etc above).\n#ifdef MPP_LAND\nif(my_id .eq. IO_id) then\n#endif\n   nParamGages  = get_netcdf_dim(nudgingParamFile, 'stationIdInd', 'init_stream_nudging')\n\n   nParamMonth=0\n   nParamThresh=0\n   nParamThreshCat=0\n   if(temporalPersistence) then\n      nParamMonth     = get_netcdf_dim(nudgingParamFile, 'monthInd',     'init_stream_nudging')\n      nParamThresh    = get_netcdf_dim(nudgingParamFile, 'threshInd',    'init_stream_nudging')\n      nParamThreshCat = get_netcdf_dim(nudgingParamFile, 'threshCatInd', 'init_stream_nudging')\n\n#ifdef HYDRO_D\n      print*,'Ndg: nParamGages: ',   nParamGages\n      print*,'Ndg: nParamGages',     nParamGages\n      print*,'Ndg: nParamMonth',     nParamMonth\n      print*,'Ndg: nParamThresh',    nParamThresh\n      print*,'Ndg: nParamThreshCat', nParamThreshCat\n      if(flushAll) flush(flushUnit)\n#endif\n\n      if(nParamMonth.eq.0 .or. nParamThresh.eq.0 .or. nParamThreshCat.eq.0) then\n         temporalPersistence = .false.\n         nParamThresh=0\n         nParamMonth=0\n      else if((nParamThresh+1) .ne. nParamThreshCat) then\n         temporalPersistence = .false.\n         nParamThresh=0\n         nParamMonth=0\n      end if\n   endif !temporal persistence\n\n#ifdef HYDRO_D\n   print*,'Ndg: nParamGages: ',         nParamGages\n   print*,'Ndg: nParamMonth',           nParamMonth\n   print*,'Ndg: nParamThresh',          nParamThresh\n   print*,'Ndg: nParamThreshCat',       nParamThreshCat\n   print*,'Ndg: temporalPersistence: ', temporalPersistence\n   if(flushAll) flush(flushUnit)\n#endif\n\n   allocate(nudgingParamsTmp%usgsId(  nParamGages))\n   allocate(nudgingParamsTmp%R(       nParamGages))\n   allocate(nudgingParamsTmp%G(       nParamGages))\n   allocate(nudgingParamsTmp%tau(     nParamGages))\n   allocate(nudgingParamsTmp%qThresh( nParamThresh,   nParamMonth, nParamGages))\n   allocate(nudgingParamsTmp%expCoeff(nParamThresh+1, nParamMonth, nParamGages))\n\n   call read_nudging_param_file(nudgingParamFile,         &\n                                nudgingParamsTmp%usgsId,  &\n                                nudgingParamsTmp%R,       &\n                                nudgingParamsTmp%G,       &\n                                nudgingParamsTmp%tau,     &\n                                nudgingParamsTmp%qThresh, &\n                                nudgingParamsTmp%expCoeff )\n\n#ifdef HYDRO_D\n   do ii=1,nParamThresh\n      print*,'Ndg: minval( nudgingParamsTmp%qThresh(ii,:,:)), ii=', ii,': ', &\n           minval( nudgingParamsTmp%qThresh(ii,:,:))\n   end do\n   do ii=1,nParamThreshCat\n      print*,'Ndg: minval( nudgingParamsTmp%expCoeff(ii,:,:)), ii=', ii,': ', &\n           minval( nudgingParamsTmp%expCoeff(ii,:,:))\n   end do\n   if(flushAll) flush(flushUnit)\n#endif\n\n   ! Reduce the parameters to just the gages in the domain\n   allocate(whParamsDom(nParamGages))\n\n   call whichInLoop2(nudgingParamsTmp%usgsId, nodeGageStr%usgsId, whParamsDom, nGagesWParamsDom)\n\n#ifdef HYDRO_D\n   if(nGagesWParamsDom .ne. nGagesDomain) then\n      print*,'Ndg: WARNING Gages are apparently missing from the nudgingParams.nc file'\n      print*,'Ndg: WARNING nGagesWParamsDom: ', nGagesWParamsDom\n      print*,'Ndg: WARNING nGagesDomain: ', nGagesDomain\n      if(flushAll) flush(flushUnit)\n   end if\n#endif\n\n   allocate(nudgingParamsStr%usgsId(nGagesWParamsDom))\n   allocate(nudgingParamsStr%R(     nGagesWParamsDom))\n   allocate(nudgingParamsStr%G(     nGagesWParamsDom))\n   allocate(nudgingParamsStr%tau(   nGagesWParamsDom))\n   if(temporalPersistence) then\n      allocate(nudgingParamsStr%qThresh( nParamThresh,   nParamMonth, nGagesWParamsDom))\n      allocate(nudgingParamsStr%expCoeff(nParamThresh+1, nParamMonth, nGagesWParamsDom))\n   end if\n\n   count=1\n   do kk=1,nParamGages\n      if(whParamsDom(kk) .gt. 0) then\n         nudgingParamsStr%usgsId(count) = nudgingParamsTmp%usgsId(kk)\n         nudgingParamsStr%R(count)      = nudgingParamsTmp%R(kk)\n         nudgingParamsStr%G(count)      = nudgingParamsTmp%G(kk)\n         nudgingParamsStr%tau(count)    = nudgingParamsTmp%tau(kk)\n         if(temporalPersistence) then\n            nudgingParamsStr%qThresh( :,:,count) = nudgingParamsTmp%qThresh( :,:,kk)\n            nudgingParamsStr%expCoeff(:,:,count) = nudgingParamsTmp%expCoeff(:,:,kk)\n         endif\n         count=count+1\n      end if\n   end do\n\n   deallocate(whParamsDom)\n   deallocate(nudgingParamsTmp%usgsId,  nudgingParamsTmp%R  )\n   deallocate(nudgingParamsTmp%G,       nudgingParamsTmp%tau)\n   if(temporalPersistence) then\n      deallocate(nudgingParamsTmp%qThresh)\n      deallocate(nudgingParamsTmp%expCoeff)\n   end if\n\n#ifdef HYDRO_D\n   print*,'Ndg: nudgingParamsStr%usgsId', nudgingParamsStr%usgsId(size(nudgingParamsStr%usgsId))\n   print*,'Ndg: nudgingParamsStr%R',      nudgingParamsStr%R(size(nudgingParamsStr%R))\n   print*,'Ndg: nudgingParamsStr%G',      nudgingParamsStr%G(size(nudgingParamsStr%G))\n   print*,'Ndg: nudgingParamsStr%tau',    nudgingParamsStr%tau(size(nudgingParamsStr%tau))\n   if(temporalPersistence) then\n      print*,'Ndg: nudgingParamsStr%qThresh', nudgingParamsStr%qThresh(1,1,size(nudgingParamsStr%tau))\n      print*,'Ndg: nudgingParamsStr%expCoeff',nudgingParamsStr%expCoeff(1,1,size(nudgingParamsStr%tau))\n   end if\nif(flushAll) flush(flushUnit)\n#endif /* HYDRO_D */\n#ifdef MPP_LAND\nendif ! my_id .eq. io_id\n\n!! Broadcast\ncall mpp_land_bcast_int1(nGagesWParamsDom)\nif(my_id .ne. io_id) then\n   allocate(nudgingParamsStr%usgsId(nGagesWParamsDom))\n   allocate(nudgingParamsStr%R(nGagesWParamsDom))\n   allocate(nudgingParamsStr%G(nGagesWParamsDom))\n   allocate(nudgingParamsStr%tau(nGagesWParamsDom))\nendif\ncall mpp_land_bcast_char1d(nudgingParamsStr%usgsId)\ncall mpp_land_bcast_real_1d(nudgingParamsStr%R)\ncall mpp_land_bcast_real_1d(nudgingParamsStr%G)\ncall mpp_land_bcast_real_1d(nudgingParamsStr%tau)\ncall mpp_land_bcast_logical(temporalPersistence)\nif(temporalPersistence) then\n   call mpp_land_bcast_int1(nParamThresh)\n   call mpp_land_bcast_int1(nParamMonth)\n   if(my_id .ne. io_id) then\n      allocate(nudgingParamsStr%qThresh( nParamThresh,   nParamMonth, nGagesWParamsDom))\n      allocate(nudgingParamsStr%expCoeff(nParamThresh+1, nParamMonth, nGagesWParamsDom))\n   endif\n\n   call mpp_land_bcast_real3d(nudgingParamsStr%qThresh)\n   call mpp_land_bcast_real3d(nudgingParamsStr%expCoeff)\nend if ! temporalPersistence\n#endif /* MPP_LAND */\n\nallocate(obsStaticStr(size(nudgingParamsStr%usgsId)))\n\nallocate(obsStaticStr_SoA%usgsId(size(nudgingParamsStr%usgsId)))\nallocate(obsStaticStr_SoA%R(size(nudgingParamsStr%usgsId)))\nallocate(obsStaticStr_SoA%tau(size(nudgingParamsStr%usgsId)))\nallocate(obsStaticStr_SoA%G(size(nudgingParamsStr%usgsId)))\nallocate(obsStaticStr_SoA%obsCellInd(size(nudgingParamsStr%usgsId)))\n! This seems silly now that I'm solving the whole thing at init.\nobsStaticStr_SoA%R(:) = nudgingParamsStr%R(:)\nobsStaticStr_SoA%G(:) = nudgingParamsStr%G(:)\nobsStaticStr_SoA%tau(:) = nudgingParamsStr%tau(:)\nobsStaticStr_SoA%usgsId(:) = nudgingParamsStr%usgsId(:)\nobsStaticStr(:)%usgsId = nudgingParamsStr%usgsId\n\nallocate(obsStaticStr_SoA%lastObsDischarge(nlst(did)%nLastObs, size(nudgingParamsStr%usgsId)))\nallocate(obsStaticStr_SoA%lastObsModelDischarge(nlst(did)%nLastObs, size(nudgingParamsStr%usgsId)))\nallocate(obsStaticStr_SoA%lastObsTime(nlst(did)%nLastObs, size(nudgingParamsStr%usgsId)))\nallocate(obsStaticStr_SoA%lastObsQuality(nlst(did)%nLastObs, size(nudgingParamsStr%usgsId)))\n\n!=================================================\n! 4. Read in 'nudgingLastObs.nc' file (initialization and broadcasting come later)\n#ifdef MPP_LAND\nif(my_id .eq. io_id) then\n   if(temporalPersistence) then\n\n      !! Initalizing the structure is not contingent upon there\n      !! being a file on disk\n      obsStaticStr_SoA%lastObsDischarge      = real(-9999)\n      obsStaticStr_SoA%lastObsModelDischarge = real(-9999)\n      obsStaticStr_SoA%lastObsTime    = missingLastObsTime\n      obsStaticStr_SoA%lastObsQuality        = real(0) !! keep this zero\n\n      !! if blank, look for file at the current/init time\n      if(trim(nudgingLastObsFile) .eq. '') then\n         nudgingLastObsFileTry = 'nudgingLastObs.' // nlst(did)%olddate // '.nc'\n      else\n         nudgingLastObsFileTry = nudgingLastObsFile\n      end if\n      lastObsFile = find_nudging_last_obs_file(nudgingLastObsFileTry)\n      if(trim(lastObsFile) .ne. '') then\n         nStnLastObs = get_netcdf_dim(nudgingLastObsFileTry, 'stationIdInd', 'init_stream_nudging')\n         if(nStnLastObs .gt. 0) then\n            print*,'Reading in nudgingLastObsFileTry: ', trim(nudgingLastObsFileTry)\n            allocate(lastObsStr_SoA%usgsId(nStnLastObs))\n            allocate(lastObsStr_SoA%lastObsDischarge(nlst(did)%nLastObs,nStnLastObs))\n            allocate(lastObsStr_SoA%lastObsModelDischarge(nlst(did)%nLastObs,nStnLastObs))\n            allocate(lastObsStr_SoA%lastObsTime(nlst(did)%nLastObs,nStnLastObs))\n            allocate(lastObsStr_SoA%lastObsQuality(nlst(did)%nLastObs,nStnLastObs))\n\n            allocate(lastObsStr(nStnLastObs))\n\n            allocate(g_nudge(rt_domain(1)%gnlinksl))\n            call read_nudging_last_obs_soa(nudgingLastObsFileTry, lastObsStr_SoA, g_nudge)\n         end if ! nStnLastObs .gt. 0 -> read the file\n      endif! trim(lastObsFile).ne.''\n   end if ! temporalPersistence\nelse\n   allocate(g_nudge(1))\nendif\n\nif(my_id .eq. io_id) lastObsFileFound=allocated(g_nudge)\ncall mpp_land_bcast_logical(lastObsFileFound)\nif(lastObsFileFound) then\n   call ReachLS_decomp(g_nudge, RT_DOMAIN(1)%nudge)\n   if(my_id .eq. io_id) deallocate(g_nudge)\nendif\nif(my_id .NE. io_id) deallocate(g_nudge)\n#endif\n\n!=================================================\n! 5. Sort out which gages are actually in the domain.\n! JLM: there can be an inconsistency between the gages with parameters\n! JLM: and the gages with distances.\n! JLM: How to handle locations without parameters?\n! JLM: How to determine the functional list of gages in the domain?\n!\n\n!=================================================\n! 6. Set up the global time parameters\n#ifdef MPP_LAND\n! MPP need to broadcast the initial time and setup the dt\nif(my_id .eq. io_id) then\n   lsmDt = nlst(did)%dt\nendif\ncall mpp_land_bcast_int1(lsmDt)\n#else\nlsmDt = nlst(did)%dt\n#endif\n\n!S      - -+- -       !\n!E      !       - -+- -\n!  |- - - -L* * * *|- - - -|- - - -|\n!       t t w w w w t t\n! - time chunks of obsResolution\n! | separators denoting lsmDt chunks\n! * obsRresolution points in the current lsmDt/hydro time advance\n! + is the center of the assim window size = tau*2, at that the hydro time\n! ! are the bounds of all assim windows\n! L is LSM time\n! S-E The start and end times for hydro advance\n! t denotes times needed by size of tau\n! w denotes times needed by size of lsmDt\n! Regardless of tau, need window of size (2*tau+lsmDt)\n! which will have (2*tau+lsmDt)/obsResolution+1 observation times in it\n! the +1 is for the zeroth time.\n\nmaxTau = maxval(nudgingParamsStr%tau) ! This is fixed as tau does not change for a cycle.\nwrite(obsResolution, '(i0.2)') obsResolutionInt\nnObsTimes  = 2*ceiling(maxTau/obsResolutionInt) + ceiling(real(lsmDt)/(60.*obsResolutionInt)) + 1\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) then\n#endif\n   print*,'Ndg: obsResolution:',obsResolution\n   print*,'Ndg: maxTau: ', maxTau\n   print*,'Ndg: nObsTimes: ', nObsTimes\n   if(flushAll) flush(flushUnit)\n#ifdef MPP_LAND\nend if\n#endif\n#endif\n\nallocate(obsTimeStr(nObsTimes))\n!! initialize these as blanks and 'none'\nobsTimeStr(:)%time     = ''\nobsTimeStr(:)%updateTime = 'none'\n\n#ifdef MPP_LAND\n!=================================================\n! 8. MPP: Keep a copy of the full chanlen on image 0\n!! only necessary if doing spatial nudging interpolation\nif(my_id .eq. io_id) allocate(chanlen_image0(nLinksL))\nif(my_id .ne. io_id) allocate(chanlen_image0(1)) !! memory fix, the next call modifies it's second arg\ncall ReachLS_write_io(rt_domain(did)%chanlen, chanlen_image0)\n#endif\n\n\n!=================================================\n! 9. Solve obsStaticStr once and for all on image 0 (could parallelize)\n!    This also solves nudgeSpatial: is spatial nudging active? Needed in 10.\n! Remove lastObsStr (only needed for ingest of nudingLastObs/restart file).\ncall obs_static_to_struct()\n#ifdef MPP_LAND\nif(my_id .eq. io_id) then\n#endif\n   if(allocated(lastObsStr)) deallocate(lastObsStr)\n#ifdef MPP_LAND\nendif\n#endif\n\n!=================================================\n!10. Solve the bias terms for when biasWindowBeforeT0 = .TRUE. (in the forecast)\n\n!if(persistBias .and. biasWindowBeforeT0) then\n!   do gg=1,nGages.........\n!      ! solve the bias\n!   end do ! gg=1,nGages\n!end if ! if(persistBias) then\n\n!=================================================\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*, \"Ndg: Finish init_stream_nudging\"\nif(flushAll) flush(flushUnit)\n#endif\n\n!!$#ifdef HYDRO_D  /* un-ifdef to get timing results */\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) then\n!!$#endif\n!!$   call nudging_timer(endCodeTimeAcc)\n!!$   call accum_nudging_time(startCodeTimeAcc, endCodeTimeAcc, 'init_stream_nudging', .true.)\n!!$#ifdef MPP_LAND\n!!$end if\n!!$#endif\n!!$if(flushAll) flush(flushUnit)\n!!$#endif /* HYDRO_D */  /* un-ifdef to get timing results */\n\nend subroutine init_stream_nudging\n\n!===================================================================================================\n! Program Names:\n!   subroutine setup_stream_nudging\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Setup the nudging for the current hydroTime, only establishes the\n!   shared obsTimeStr above.\n! History Log:\n!   6/04/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine setup_stream_nudging(hydroDT)\n\nuse module_RT_data,       only: rt_domain\nuse module_nudging_utils, only: whichLoop,               &\n                                whUniLoop,               &\n                                accum_nudging_time,      &\n                                nudging_timer\n\nuse module_date_utils_nudging, only: geth_newdate,            &\n                                round_resolution_minute, &\n                                geth_idts\nimplicit none\n\ninteger,           intent(in) :: hydroDT ! the number of seconds of hydro advance from lsmTime\n!integer :: ff\ninteger :: ii, tt, oo\ncharacter(len=19) :: hydroTime, obsHydroTime ! hydro model time and corresponding observation\ncharacter(len=19), dimension(nObsTimes) :: obsTimes ! obs times in the current window\ninteger :: oldDiff, nShiftLeft\n\nlogical, allocatable, dimension(:) :: theMask\ninteger, allocatable, dimension(:) :: whObsMiss\nlogical, allocatable, dimension(:) :: obsTimeStrAllocated\n\ninteger :: nObsMiss\ninteger :: did=1  !! jlm: assuming did=1\ninteger :: nWhObsMiss\n\n#ifdef MPP_LAND\ninteger :: nGages, nCellsInR, cc, nLinkAff, nStatic, iiImage\n#endif\n\n!!$#ifdef HYDRO_D  /* un-ifdef to get timing results */\n!!$real :: startCodeTime, endCodeTime\n!!$real :: startCodeTimeOuter\n!!$\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) &\n!!$#endif\n!!$     call nudging_timer(startCodeTimeOuter)\n!!$if(flushAll) flush(flushUnit)\n!!$#endif  /* HYDRO_D :: un-ifdef to get timing results */\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\n   print*,'Ndg: start setup_stream_nudging'\nif(flushAll) flush(flushUnit)\n#endif  /* HYDRO_D */\n\n!!$#ifdef HYDRO_D\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) &\n!!$#endif\n!!$     call nudging_timer(startCodeTime)\n!!$if(flushAll) flush(flushUnit)\n!!$#endif /* HYDRO_D */\n\n!#ifdef MPP_LAND - just do this section on all images. There is no IO.\n! The hydro model time as a string.\n#ifdef MPP_LAND\n!update and broadcast the lsm time\nif(my_id .eq. io_id) lsmTime  = nlst(did)%olddate\nif(my_id .eq. io_id) initTime = nlst(did)%startdate\ncall mpp_land_bcast_char(19, lsmTime )\ncall mpp_land_bcast_char(19, initTime)\n# else\nlsmTime = nlst(did)%olddate\ninitTime = nlst(did)%startdate\n#endif\n\n! This is apparently fixed so that olddate is lsmTime and not\n! behind by 1 lsm timestep when the hydro model is run.\n!call geth_newdate(hydroTime, nlst(1)%olddate, hydroDT+nint(nlst(1)%dt))\n!call geth_newdate(hydroTime, lsmTimeMinusDt, hydroDT+lsmDt)\ncall geth_newdate(hydroTime, lsmTime, hydroDT)\n\n! Calculate the closest multiple of obsResolution to the hydroTime\nobsHydroTime = round_resolution_minute(hydroTime, obsResolutionInt)\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*,'Ndg: obsHydroTime: ', obsHydroTime\nif(flushAll) flush(flushUnit)\n#endif\n\n! Now solve all of the observation times in the current nudging window.\n! nObsTimes is set at init from maxTau and obsResolution.\n! These times correspond to the timestamps on the observation files, which\n! mark the center of the time period they represent with width obsResolution.\ndo tt=1,nObsTimes\n   call geth_newdate(obsTimes(tt), obsHydroTime,  &\n                     !obsResolutionInt*(tt - (nObsTimes+1)/2 )*60)\n                     (tt-1-ceiling(maxTau/obsResolutionInt))*60*obsResolutionInt )\nend do\n\n! If this is the first setup, these are all blank. This is their init value.\nif(all(obsTimeStr(:)%time .eq. '')) obsTimeStr(:)%time = obsTimes\n\n!print*,'Ndg: hydroTime: ', hydroTime\n!print*,'Ndg: obsHydroTime: ', obsHydroTime\n!print*,'Ndg: obsTimes: ', obsTimes\n!print*,'Ndg: obsTimeStr: before obsTimeStr(:)%time: ', obsTimeStr(:)%time\n\n! If there are existing observations older than the first obsTime for this\n! nudging window, shift them left. This should just shift one position left\n! with each advance in time resolution.\ncall geth_idts(obsTimeStr(1)%time, obsTimes(1), oldDiff)\n!print*,\"Ndg: olddiff:\", oldDiff\nif(oldDiff .eq. 0) then\n   nShiftLeft=0\nelse\n   ! nShiftLeft should not exceed nObsTimes\n   nShiftLeft = min( abs(oldDiff/obsResolutionInt/60), nObsTimes )\nend if\n!print*,\"Ndg: nShiftLeft:\", nShiftLeft\n\nif(nShiftLeft .gt. 0 .and. nShiftLeft .lt. nObsTimes) then\n   do tt=1,nObsTimes-nShiftLeft\n\n      obsTimeStr(tt)%time = obsTimeStr(tt+nShiftLeft)%time\n      obsTimeStr(tt)%updateTime = obsTimeStr(tt+nShiftLeft)%updateTime\n\n      if(allocated(obsTimeStr(tt)%allCellInds)) deallocate(obsTimeStr(tt)%allCellInds)\n      if(allocated(obsTimeStr(tt)%nGageCell))   deallocate(obsTimeStr(tt)%nGageCell)\n      if(allocated(obsTimeStr(tt)%obsStr))      deallocate(obsTimeStr(tt)%obsStr)\n\n      if(allocated(obsTimeStr(tt+nShiftLeft)%allCellInds)) then\n         allocate(obsTimeStr(tt)%allCellInds(size(obsTimeStr(tt+nShiftLeft)%allCellInds)))\n         obsTimeStr(tt)%allCellInds = obsTimeStr(tt+nShiftLeft)%allCellInds\n      end if\n\n      if(allocated(obsTimeStr(tt+nShiftLeft)%nGageCell))   then\n         allocate(obsTimeStr(tt)%nGageCell(size(obsTimeStr(tt+nShiftLeft)%nGageCell)))\n         obsTimeStr(tt)%nGageCell = obsTimeStr(tt+nShiftLeft)%nGageCell\n      end if\n\n      if(allocated(obsTimeStr(tt+nShiftLeft)%obsStr))      then\n         allocate(obsTimeStr(tt)%obsStr(size(obsTimeStr(tt+nShiftLeft)%obsStr)))\n         obsTimeStr(tt)%obsStr = obsTimeStr(tt+nShiftLeft)%obsStr\n      end if\n\n   end do\nendif\nif(nShiftLeft .gt. 0) then\n   ! here tt= nObsTimes\n   do tt=nObsTimes-nShiftLeft+1,nObsTimes\n      obsTimeStr(tt)%time = obsTimes(tt) !''  !! JLM is this a fix? why?\n      obsTimeStr(tt)%updateTime = 'none'\n      if(allocated(obsTimeStr(tt)%allCellInds)) deallocate(obsTimeStr(tt)%allCellInds)\n      if(allocated(obsTimeStr(tt)%nGageCell))   deallocate(obsTimeStr(tt)%nGageCell)\n      if(allocated(obsTimeStr(tt)%obsStr))      deallocate(obsTimeStr(tt)%obsStr)\n   end do\nend if\n\n!if(.NOT. all(obsTimeStr(:)%time .EQ. obsTimes)) &\n!     call hydro_stop(\"obsTimeStr(:)%times not what they should be. Please investigate.\")\n\n! Updates obs already in memory if flag is set.\n! Not going to be used for IOC. This will happen later.\n! Should the frequency be in model time or in real time? Probably real time\n! and will require a clock time of 'obsLast' checked in obsTimeStr?\n! call check_for_new_obs()\n\n! Read in obs at times not already checked, eg. new obs this window\n! Obs not already checked have updateTime='none'\n! Obs already checked for with:\n!  : a missing file have updateTime='no file'\n!  : no observations in the domain have updateTime='no obs'.\n#ifdef MPP_LAND\nif(my_id .eq. io_id) then\n#endif\n   nWhObsMiss = size(obsTimeStr(:)%updateTime)\n   allocate(theMask(nWhObsMiss), whObsMiss(nWhObsMiss) )\n   do ii=1,size(obsTimeStr(:)%updateTime)\n      theMask(ii) = trim(obsTimeStr(ii)%updateTime) .eq. 'none'\n   end do\n   call whichLoop(theMask, whObsMiss, nObsMiss)\n   deallocate(theMask)\n#ifdef MPP_LAND\nend if\n\n! Broadcast the basic info above.\ncall mpp_land_bcast_int1(nWhObsMiss)\nif(my_id .ne. io_id) then\n   if(allocated(whObsMiss)) deallocate(whObsMiss)\n   allocate(whObsMiss(nWhObsMiss))\nendif\ncall mpp_land_bcast_int1d(whObsMiss)\ncall mpp_land_bcast_int1(nObsMiss)\n#endif\n\n!!$#ifdef HYDRO_D\n!!$if(my_id .eq. io_id) then\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTime, endCodeTime, &\n!!$        'setup1: prelim', .false.)\n!!$   call nudging_timer(startCodeTime)\n!!$if(flushAll) flush(flushUnit)\n!!$endif\n!!$#endif\n\n!bring in timeslice files\nallocate(obsTimeStrAllocated(nObsMiss))\n\ndo ii=1,nObsMiss ! if nObsMiss is zero, this loop is skipped?\n#ifdef MPP_LAND\n   if(readTimesliceParallel) then\n      iiImage = mod(ii-1,numprocs)\n   else\n      iiImage = 0\n   end if\n   if(my_id .eq. iiImage) then  !! this would give parallel IO\n#endif\n      tt = whObsMiss(ii)\n      ! set/reset this obsTime\n      obsTimeStr(tt)%time = obsTimes(tt)\n      obsTimeStr(tt)%updateTime = 'none'\n      !! This might be paranoid/overkill...\n      if(allocated(obsTimeStr(tt)%allCellInds)) deallocate(obsTimeStr(tt)%allCellInds)\n      if(allocated(obsTimeStr(tt)%nGageCell))   deallocate(obsTimeStr(tt)%nGageCell)\n      if(allocated(obsTimeStr(tt)%obsStr))      deallocate(obsTimeStr(tt)%obsStr)\n      call timeslice_file_to_struct(tt) ! uses obsTimeStr%time to get file\n      obsTimeStrAllocated(ii) = allocated(obsTimeStr(tt)%obsStr)\n      !obsTimeStrAllocated = allocated(obsTimeStr(tt)%obsStr)\n#ifdef MPP_LAND\n   end if ! my_id .eq. iiImage\n#endif\nend do\n\n!!$#ifdef HYDRO_D\n!!$if(my_id .eq. io_id) then\n!!$   !print*,'Ndg: obsTimeStr(tt)%time: ',obsTimeStr(tt)%time\n!!$   !print*,'Ndg: obsTimeStrAllocated(ii), ii: ', obsTimeStrAllocated(ii), ii\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTime, endCodeTime, &\n!!$        'setup2.0: timeslice_file_to_struct before bcast', .false.)\n!!$   !call nudging_timer(startCodeTime) ! skip this b/c there's no mpi sync till after next section\n!!$   if(flushAll) flush(flushUnit)\n!!$endif\n!!$#endif\n\n#ifdef MPP_LAND\n! broadcast the IO from above\ndo ii=1,nObsMiss ! if nObsMiss is zero, this loop is skipped?\n   if(readTimesliceParallel) then\n      iiImage = mod(ii-1,numprocs)\n   else\n      iiImage = 0\n   end if\n   tt = whObsMiss(ii)\n   ! broadcast\n   ! Here have to expose some of the guts of timeslice_file_to_struct\n   ! Note nGages depends on ii/tt\n   call mpp_land_bcast_int1_root(tt, iiImage)\n   call mpp_land_bcast_logical_root(obsTimeStrAllocated(ii), iiImage)\n   if(obsTimeStrAllocated(ii)) then\n      if(my_id .eq. iiImage) nGages=size(obsTimeStr(tt)%obsStr)\n      call mpp_land_bcast_int1_root(nGages, iiImage)\n      if(my_id .ne. iiImage) then\n         if(allocated(obsTimeStr(tt)%obsStr))      deallocate(obsTimeStr(tt)%obsStr)\n         allocate(obsTimeStr(tt)%obsStr(nGages))\n      endif\n      ! Variables in order assigned in the call in timeslice_file_to_struct\n      call mpp_land_bcast_char_root(19,obsTimeStr(tt)%time, iiImage)\n      call mpp_land_bcast_char_root(19,obsTimeStr(tt)%updateTime, iiImage)\n      call mpp_land_bcast_char1d_root(obsTimeStr(tt)%obsStr(:)%usgsId, iiImage)\n      call mpp_land_bcast_char1d_root(obsTimeStr(tt)%obsStr(:)%obsTime, iiImage)\n      call mpp_land_bcast_real_1d_root(obsTimeStr(tt)%obsStr(:)%obsQC, iiImage)\n      call mpp_land_bcast_real_1d_root(obsTimeStr(tt)%obsStr(:)%obsDischarge, iiImage)\n   end if\nend do\n#endif\n\n!!$#ifdef HYDRO_D\n!!$if(my_id .eq. io_id) then\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTime, endCodeTime, &\n!!$        'setup2.1: timeslice_file_to_struct after bcast', .false.)\n!!$   call nudging_timer(startCodeTime) ! images are synched so reset timer\n!!$   if(flushAll) flush(flushUnit)\n!!$endif\n!!$#endif\n\n!! get index of static info in obsStaticStr\ndo ii=1,nObsMiss ! if nObsMiss is zero, this loop is skipped?\n#ifdef MPP_LAND\n   if(readTimesliceParallel) then\n      iiImage = mod(ii-1,numprocs)\n   else\n      iiImage = 0\n   end if\n   if(my_id .eq. iiImage) then\n      tt = whObsMiss(ii)\n#endif\n      if(obsTimeStrAllocated(ii)) then\n         allocate(theMask(size(nudgingParamsStr%usgsId)))\n         do oo=1,size(obsTimeStr(tt)%obsStr(:)%obsStaticInd)\n            ! If the gage is not in the parameter file, skip it\n            if(.not. any(nudgingParamsStr%usgsId .eq. obsTimeStr(tt)%obsStr(oo)%usgsId)) then\n               !! If you ended up here, then filterObsToDom should not be on...\n               if(filterObsToDom) call hydro_stop('obs_static_to_struct: logical clash with filterObsToDom')\n               call accumulate_nwis_not_in_RLAndParams(nwisNotRLAndParams,             &\n                                                       nwisNotRLAndParamsCount,        &\n                                                       obsTimeStr(tt)%obsStr(oo)%usgsId)\n               cycle !! skip this observation.\n            endif\n            theMask = obsStaticStr_SoA%usgsId .eq. obsTimeStr(tt)%obsStr(oo)%usgsId\n            !! This is a double (tripple?!) for loop... thanks to whUniLoop\n            obsTimeStr(tt)%obsStr(oo)%obsStaticInd = whUniLoop(theMask)\n         end do\n         deallocate(theMask)\n      end if ! oo\n#ifdef MPP_LAND\n   end if ! ii\n#endif\nend do\n\n!!$#ifdef HYDRO_D\n!!$if(my_id .eq. io_id) then\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTime, endCodeTime, &\n!!$        'setup3: obs_static_to_struct', .false.)\n!!$   call nudging_timer(startCodeTime)\n!!$   if(flushAll) flush(flushUnit)\n!!$endif\n!!$#endif\n\n#ifdef MPP_LAND\ndo ii=1,nObsMiss ! broadcast IO from above. (if nObsMiss is zero, this loop is skipped)\n   if(readTimesliceParallel) then\n      iiImage = mod(ii-1,numprocs)\n   else\n      iiImage = 0\n   end if\n   ! broadcast\n   if(obsTimeStrAllocated(ii)) then\n      tt = whObsMiss(ii)\n      ! Treat obs_static_to_strutct\n      call mpp_land_bcast_int1d_root(obsTimeStr(tt)%obsStr(:)%obsStaticInd, iiImage)\n      call mpp_land_bcast_char1d_root(obsStaticStr_SoA%usgsId(:), iiImage)\n      call mpp_land_bcast_int1d_root(obsStaticStr_SoA%obsCellInd(:), iiImage)\n      call mpp_land_bcast_real_1d_root(obsStaticStr_SoA%R(:), iiImage)\n      call mpp_land_bcast_real_1d_root(obsStaticStr_SoA%G(:), iiImage)\n      call mpp_land_bcast_real_1d_root(obsStaticStr_SoA%tau(:), iiImage)\n\n      nStatic = sum( (/ (1, cc=1,size(obsStaticStr_SoA%obsCellInd(:))) /), &\n                     mask=obsStaticStr_SoA%obsCellInd(:) .ne. 0            )\n      do cc=1,nStatic\n         if(my_id .eq. iiImage) nCellsInR = size(obsStaticStr(cc)%cellsAffected)\n         call mpp_land_bcast_int1_root(nCellsInR, iiImage)\n         if(my_id .ne. iiImage) then\n            if(allocated(obsStaticStr(cc)%cellsAffected)) deallocate(obsStaticStr(cc)%cellsAffected)\n            if(allocated(obsStaticStr(cc)%dist))          deallocate(obsStaticStr(cc)%dist)\n            if(allocated(obsStaticStr(cc)%ws))            deallocate(obsStaticStr(cc)%ws)\n            allocate(obsStaticStr(cc)%cellsAffected(nCellsInR))\n            allocate(obsStaticStr(cc)%dist(nCellsInR))\n            allocate(obsStaticStr(cc)%ws(nCellsInR))\n         end if\n         call mpp_land_bcast_int1d_root(obsStaticStr(cc)%cellsAffected, iiImage)\n         call mpp_land_bcast_real_1d_root(obsStaticStr(cc)%dist, iiImage)\n         call mpp_land_bcast_real_1d_root(obsStaticStr(cc)%ws, iiImage)\n      end do\n   end if\nend do\n#endif\n\n!!$#ifdef HYDRO_D\n!!$if(my_id .eq. io_id) then\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTime, endCodeTime, &\n!!$        'setup4: bcast obs_static_struct', .false.)\n!!$   call nudging_timer(startCodeTime)\n!!$   if(flushAll) flush(flushUnit)\n!!$endif\n!!$#endif\n\ndo ii=1,nObsMiss ! if nObsMiss is zero, this loop is skipped?\n#ifdef MPP_LAND\n   iiImage = 0! causes issues also refactor tally_affected_links? mod(ii-1,numprocs)\n   if(my_id .eq. iiImage) then\n#endif\n      tt = whObsMiss(ii)\n      if(obsTimeStrAllocated(ii)) call tally_affected_links(tt)\n   endif\n#ifdef MPP_LAND\nend do\n#endif\n\n!!$#ifdef HYDRO_D\n!!$if(my_id .eq. io_id) then\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTime, endCodeTime, &\n!!$        'setup5: tally_affected_links', .false.)\n!!$   call nudging_timer(startCodeTime)\n!!$   if(flushAll) flush(flushUnit)\n!!$endif\n!!$#endif\n\n#ifdef MPP_LAND\ndo ii=1,nObsMiss ! if nObsMiss is zero, this loop is skipped?\n   iiImage = 0 ! this must happen on the same images as the above two mod(ii-1,numprocs)\n   ! broadcast\n   if(obsTimeStrAllocated(ii)) then\n      tt = whObsMiss(ii)\n      ! Treat tally_affected_links\n      if(my_id .eq. iiImage) nLinkAff = size(obsTimeStr(tt)%allCellInds)\n      call mpp_land_bcast_int1_root(nLinkAff, iiImage)\n\n      if(my_id .ne. iiImage) then\n         if(allocated(obsTimeStr(tt)%allCellInds)) deallocate(obsTimeStr(tt)%allCellInds)\n         if(allocated(obsTimeStr(tt)%nGageCell))   deallocate(obsTimeStr(tt)%nGageCell)\n         allocate(obsTimeStr(tt)%allCellInds(nLinkAff))\n         allocate(obsTimeStr(tt)%nGageCell(nLinkAff))\n      end if\n      call mpp_land_bcast_int1d_root(obsTimeStr(tt)%allCellInds, iiImage)\n      call mpp_land_bcast_int1d_root(obsTimeStr(tt)%nGageCell, iiImage)\n   end if\nend do\n#endif\n\n!!$#ifdef HYDRO_D\n!!$if(my_id .eq. io_id) then\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTime, endCodeTime, &\n!!$        'setup6: after bcast tally_aff', .false.)\n!!$   call nudging_timer(startCodeTime)\n!!$   if(flushAll) flush(flushUnit)\n!!$endif\n!!$#endif\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\n!if(my_id .eq. io_id) then\nif(my_id .eq. -5) then\n#endif\n   print*,'Ndg: '\n   print*,'Ndg: !-------------------------------------------------'\n   print*,'Ndg: obsTimeStr(tt=',tt,')'\n   print*,'Ndg: obsTimeStr(tt)%time:',        obsTimeStr(tt)%time\n   print*,'Ndg: obsTimeStr(tt)%updateTime:',  obsTimeStr(tt)%updateTime\n   print*,'Ndg: obsTimeStr(tt)%allCellInds:', obsTimeStr(tt)%allCellInds\n   print*,'Ndg: obsTimeStr(tt)%nGageCell:',   obsTimeStr(tt)%nGageCell\n   if(trim(obsTimeStr(tt)%updateTime(1:7)) .ne. 'no file') then\n      print*,'Ndg: nobs:', size(obsTimeStr(tt)%obsStr)\n      print*,'Ndg: obsTimeStr(tt)%obsStr(1)%usgsId:',       obsTimeStr(tt)%obsStr(1)%usgsId\n      print*,'Ndg: obsTimeStr(tt)%obsStr(1)%obsTime:',      obsTimeStr(tt)%obsStr(1)%obsTime\n      print*,'Ndg: obsTimeStr(tt)%obsStr(1)%obsDischarge:', obsTimeStr(tt)%obsStr(1)%obsDischarge\n      print*,'Ndg: obsTimeStr(tt)%obsStr(1)%obsQC:',        obsTimeStr(tt)%obsStr(1)%obsQC\n      print*,'Ndg: obsTimeStr(tt)%obsStr(1)%obsStaticInd:', obsTimeStr(tt)%obsStr(1)%obsStaticInd\n   end if\n   print*,'Ndg: !-------------------------------------------------'\n   print*,'Ndg: '\n#ifdef MPP_LAND\nif(flushAll) flush(flushUnit)\nend if\n#endif\n#endif /* HYDRO_D */\n\n!!$#ifdef HYDRO_D\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) then\n!!$#endif\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTime, endCodeTime, &\n!!$        'setup6: diagnostics at end', .false.)\n!!$   if(flushAll) flush(flushUnit)\n!!$#ifdef MPP_LAND\n!!$endif\n!!$#endif\n!!$#endif /* HYDRO_D */\n\ndeallocate(obsTimeStrAllocated, whObsMiss)\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*,'Ndg: finish setup_stream_nudging'\n\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) then\n!!$#endif\n!!$   call nudging_timer(endCodeTime)\n!!$   call accum_nudging_time(startCodeTimeOuter, endCodeTime, &\n!!$        'setup7: finish/full setup_stream_nudging', .true. )\n!!$#ifdef MPP_LAND\n!!$endif\n!!$#endif\n\nif(flushAll) flush(flushUnit)\n#endif /* HYDRO_D */\n\nend subroutine setup_stream_nudging\n\n!===================================================================================================\n! Program Names:\n!   timeslice_file_to_struct\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Read a timeslice file, subset to observations in the domain, put into the\n!   obsTimeStr(timeIndex)%obsStr where obsTimeStr(timeIndex)%time impiles the\n!   file being read in and timeIndex is the only argument to this subroutine.\n! History Log:\n!   7/23/15 -Created, JLM.\n! Usage:\n! Parameters:\n!  timeIndex: the index corresponding to time in the obsTimeStr\n! Input Files:  Specified argument.\n! Output Files: None.\n! Condition codes:\n! User controllable options:\n!   Namelist option, logical \"filterObsToDom\". This removes observations which are not in the\n!   domain. May be useful for running small domains using large data files.\n! Notes:\n\nsubroutine timeslice_file_to_struct(structIndex)\nuse module_nudging_utils, only: whichInLoop2\n\nuse module_nudging_io,    only: find_timeslice_file, &\n                                read_timeslice_file, &\n                                get_netcdf_dim\n\nimplicit none\ninteger, intent(in) :: structIndex\n\ncharacter(len=19)  :: thisTime  !! the of this time/slice of the structure\ncharacter(len=256) :: fileName  !! the corresponding obs file.\n\ninteger :: nGages\ninteger, allocatable, dimension(:) :: whSliceInDom\ninteger :: nWhSliceInDom\ninteger :: count, ww, errStatus\n\ncharacter(len=19)  :: timeIn, updateTimeIn  !! the time of file/slice and when it was updated\ncharacter(len=2)   :: sliceResoIn           !! the temporal resolution of the slice\ncharacter(len=19), allocatable, dimension(:) :: gageTimeIn      !!\nreal,              allocatable, dimension(:) :: gageQCIn        !!\ncharacter(len=15), allocatable, dimension(:) :: usgsIdIn        !! USGS ID\nreal,              allocatable, dimension(:) :: gageDischargeIn !! m3/s\n\n! Is there a timeslice file?\nthisTime = obsTimeStr(structIndex)%time\nfileName = find_timeslice_file(thisTime, obsResolution)\n\n! If no file, note in updateTime and get out!\nif(fileName .eq. '') then\n   obsTimeStr(structIndex)%updateTime='no file'\n#ifdef HYDRO_D\n   print*,'Ndg: no timeSliceFile at this time: ', thisTime\n   if(flushAll) flush(flushUnit)\n#endif\n   return\nend if\n\n#ifdef HYDRO_D\nprint*,'Ndg: Found file:', fileName\nprint*,'Ndg: timeSlice: ',thisTime\nprint*,'Ndg: timeSliceFile:',trim(fileName), my_id\nif(flushAll) flush(flushUnit)\n#endif\n\nnGages=get_netcdf_dim(fileName, 'stationIdInd',   &\n                      'timeslice_file_to_struct', &\n                      readTimesliceErrFatal       )\n! If the dimension comes back zero, there's an issue with the file.\n! If the error is not fatal, then handle the file as missing & print an\n! additional message\nif(nGages .eq. 0) then\n   obsTimeStr(structIndex)%updateTime='no file'\n   print*,'Ndg: WARNING: issues with skipped timeSliceFile : ', thisTime\n   return\nend if\n\n!! Reduce to just the observations in the domain or not?\nif(filterObsToDom) then\n\n   ! Bring in the full file to intermediate local variables.\n   !! JLM:: it would probably be more efficient to do this when readingin the netcdf files.\n   !! This capability is probably not needed for IOC, so I'm not doing it now.\n   allocate(usgsIdIn(nGages))\n   allocate(gageTimeIn(nGages))\n   allocate(gageQCIn(nGages))\n   allocate(gageDischargeIn(nGages))\n\n   call read_timeslice_file(fileName,             &\n                            sanityQcDischarge,    &\n                            timeIn,               &\n                            updateTimeIn,         &\n                            sliceResoIn,          &\n                            usgsIdIn,             &\n                            gageTimeIn,           &\n                            gageQCIn,             &\n                            gageDischargeIn,      &\n                            readTimesliceErrFatal,&\n                            errStatus             )\n\n   if(errStatus .ne. 0) then\n      obsTimeStr(structIndex)%updateTime='no file'\n      print*,'Ndg: WARNING: issues with skipped timeSliceFile : ', thisTime\n      deallocate(usgsIdIn, gageTimeIn, gageQCIn, gageDischargeIn)\n      return\n   end if\n\n   if(timeIn .NE. obsTimeStr(structIndex)%time) &\n        call hydro_stop('timeslice_file_to_struct: file time does not match structure')\n   if(obsResolution .NE. sliceResoIn) &\n        call hydro_stop('timeslice_file_to_struct: model and file timeslice resolution do not match.')\n   !save when the file was updated\n   obsTimeStr(structIndex)%updateTime = updateTimeIn\n\n   allocate(whSliceInDom(size(usgsIdIn)))\n   call whichInLoop2(usgsIdIn, nodeGageStr%usgsId, whSliceInDom, nWhSliceInDom)\n\n#ifdef HYDRO_D\n!   print*,'Ndg: usgsIdIn: ',         usgsIdIn\n!   print*,'Ndg: nodeGageStr%usgsId', nodeGageStr%usgsId\n   print*,'Ndg: nWhSliceInDom:',      nWhSliceInDom\n   if(flushAll) flush(flushUnit)\n#endif\n   allocate(obsTimeStr(structIndex)%obsStr(nWhSliceInDom))\n   !! because these dont get set here, give them default values.\n   obsTimeStr(structIndex)%obsStr%obsStaticInd = 0\n   obsTimeStr(structIndex)%obsStr%innov = -9999\n\n   if(nWhSliceInDom .gt. 0) then\n      count=1\n      do ww=1,size(whSliceInDom)\n         if(whSliceInDom(ww) .gt. 0) then\n            obsTimeStr(structIndex)%obsStr(count)%usgsId       = usgsIdIn(ww)\n            obsTimeStr(structIndex)%obsStr(count)%obsTime      = gageTimeIn(ww)\n            obsTimeStr(structIndex)%obsStr(count)%obsQC        = gageQCIn(ww)\n            obsTimeStr(structIndex)%obsStr(count)%obsDischarge = gageDischargeIn(ww)\n            count=count+1\n         else\n            !! the gage is not in the domain/parameter file, record that this\n            !! gage is available but unable to be assimilated.\n            call accumulate_nwis_not_in_RLAndParams(nwisNotRLAndParams,    &\n                                                    nwisNotRLAndParamsCount, usgsIdIn(ww))\n         end if\n      end do\n   end if\n\n   deallocate(whSliceInDom)\n   deallocate(usgsIdIn, gageTimeIn, gageQCIn, gageDischargeIn)\n\nelse ! dont filterObsToDom\n\n   ! not reducing the obs file to the domain, can\n   ! bring in the full file directly to the structure.\n   allocate(obsTimeStr(structIndex)%obsStr(nGages))\n   obsTimeStr(structIndex)%obsStr%obsStaticInd = 0\n   obsTimeStr(structIndex)%obsStr%innov = -9999\n\n   call read_timeslice_file(fileName,                                       &\n                            sanityQcDischarge,                              &\n                            timeIn,                                         &\n                            obsTimeStr(structIndex)%updateTime,             &\n                            sliceResoIn,                                    &\n                            obsTimeStr(structIndex)%obsStr(:)%usgsId,       &\n                            obsTimeStr(structIndex)%obsStr(:)%obsTime,      &\n                            obsTimeStr(structIndex)%obsStr(:)%obsQC,        &\n                            obsTimeStr(structIndex)%obsStr(:)%obsDischarge, &\n                            readTimesliceErrFatal,                          &\n                            errStatus                                       )\n\n   if(errStatus .ne. 0) then\n      obsTimeStr(structIndex)%updateTime='no file'\n      print*,'Ndg: WARNING: issues with skipped timeSliceFile : ', thisTime\n      deallocate(obsTimeStr(structIndex)%obsStr)\n      return\n   end if\n\n   if(timeIn .NE. obsTimeStr(structIndex)%time) &\n        call hydro_stop('timeslice_file_to_struct: file time does not match that in obsTimeStr')\n   if(obsResolution .NE. sliceResoIn) &\n        call hydro_stop('timeslice_file_to_struct: model and file timeslice resolution do not match.')\n\nendif !filterObsToDom\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*,'Ndg: finish timeslice_file_to_struct'\nif(flushAll) flush(flushUnit)\n#endif\n\nend subroutine timeslice_file_to_struct\n\n!===================================================================================================\n! Program Name:\n!   obs_static_to_struct\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   For new obs read in from file, determine the associate static data:\n!   link index, parameters, cellsAffected, distances, and weights.\n! History Log:\n! 8/5/15 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:  Specified argument.\n! Output Files: None.\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine obs_static_to_struct()\nuse module_nudging_utils, only: whUniLoop\n\nimplicit none\nlogical, allocatable, dimension(:)   :: theMask\ninteger, dimension(maxNeighLinksDim) :: upAllInds,  downAllInds   ! the collected inds/links\nreal,    dimension(maxNeighLinksDim) :: upAllDists, downAllDists  ! distance at each collected ind\ninteger                              :: upLastInd,  downLastInd   ! # of inds/links collected so far\ninteger :: ll, whLastObsStr, tt\ninteger, allocatable, dimension(:) :: nCellsInR\nlogical :: setLastObsInfo\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*,'Ndg: start obs_static_to_struct'\nif(flushAll) flush(flushUnit)\n#endif\n\n! nudgingParamsStr was already reduced to the intersection of all the\n! gages in the parameter file and all those defined in nodeGageStr (Route_Link)\n! so this is minimal by construction.\n\n\n\n#ifdef MPP_LAND\nif(my_id .eq. io_id) then\n#endif\n   ! have to search for the corresponding nodeId/obsCellInd. seems like this\n   ! could have been done with making nudgingParamsStr, but it's not (necessary).\n   allocate(theMask(size(nodeGageStr%usgsId)))\n   ! loop over the entire structure and solve %obsCellind\n   nudgeSpatial=.false.\n   do ll=1,size(obsStaticStr_SoA%usgsId(:))\n      !! this will always have a match b/c all\n      !! obsStaticStr%usgsId=nudgingParamsStr$usgsId\n      !! are in nodeGageStr by construction\n      !! (if we were looping on nodeGageStr%usgsId this would not be assured)\n      theMask = nodeGageStr%usgsId .eq. obsStaticStr_SoA%usgsId(ll)\n      !! This is a double for loop... thanks to whUniLoop\n      obsStaticStr_SoA%obsCellInd(ll) = nodeGageStr%nodeId(whUniLoop(theMask))\n      if(obsStaticStr_SoA%R(ll) .ge. chanlen_image0(obsStaticStr_SoA%obsCellInd(ll))/2) &\n           nudgeSpatial=.true.\n   end do\n   deallocate(theMask)\n#ifdef MPP_LAND\nend if\n!broadcast\ncall mpp_land_bcast_logical(nudgeSpatial)\ncall mpp_land_bcast_int1d(obsStaticStr_SoA%obsCellInd(:))\n#endif\n\n\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\n     print*,'Ndg: nudgeSpatial = ', nudgeSpatial\n\n!! get the requsite files if necessary\n!! this solves/allocates upNetwkStr and downNetwkStr\nif(nudgeSpatial) call get_netwk_reexpression()\n\n! loop over the entire structure and solve\n! 1) the spatial info: %cellsAffected, %dist, %ws\n! 2) the lastObs info: %lastObsDischarge, %lastObsModelDischarge, %lastObsTime, %lastObsQuality\n! 3) print diagnostics with or witout spatial info\n\nallocate(nCellsInR(size(obsStaticStr_SoA%usgsId(:))))\n#ifdef MPP_LAND\nif(my_id .eq. io_id) then\n#endif\n   do ll=1,size(obsStaticStr_SoA%usgsId(:))\n\n      !! spatial static info\n      if(nudgeSpatial) then\n\n         !! Now solve the spaital part of obsStaticStr\n         !---------------------\n         ! Calculate cells affected by this gage\n         ! upstream to R keep distances\n         upLastInd = 0\n         call distance_along_channel(         &\n              upNetwkStr,                     & ! traversal structure in up/down direction\n              obsStaticStr_SoA%obsCellInd(ll),    & ! the starting link\n              0.0000000000,                   & ! distance (m) at the starting node (this iter.)\n              obsStaticStr_SoA%R(ll),             & ! to traverse, in meters.\n              upAllInds,                      & ! collected links/inds\n              upAllDists,                     & ! distance to collected links\n              upLastInd                       ) ! index of last collected link in above 2 arrays.\n\n         ! downstream to R keep distances\n         downLastInd = 0\n         call distance_along_channel(         &\n              downNetwkStr,                   & ! traversal structure in up/down direction\n              obsStaticStr_SoA%obsCellInd(ll),    & ! the starting link\n              0.0000000000,                   & ! distance (m) at the starting node (this iter.)\n              obsStaticStr_SoA%R(ll),             & ! to traverse, in meters.\n              downAllInds,                    & ! collected links/inds\n              downAllDists,                   & ! distance to collected links\n              downLastInd                     ) ! index of last collected link in above 2 arrays.\n\n         ! Collect the up and down stream cells\n         nCellsInR(ll) = 1 + upLastInd + downLastInd\n         allocate(obsStaticStr(ll)%cellsAffected(nCellsInR(ll)))\n         allocate(obsStaticStr(ll)%dist(nCellsInR(ll)))\n         allocate(obsStaticStr(ll)%ws(nCellsInR(ll)))\n\n         obsStaticStr(ll)%cellsAffected(1)                           = obsStaticStr_SoA%obsCellInd(ll)\n         obsStaticStr(ll)%cellsAffected(2:(upLastInd+1))             = upAllInds(1:upLastInd)\n         obsStaticStr(ll)%cellsAffected((upLastInd+2):nCellsInR(ll)) = downAllInds(1:downLastInd)\n\n         ! Distance is optional in obsStaticStr. Right now keeping it for diagnostic potential.\n         ! May replace with a local variable later when we dont want to keep it.\n         obsStaticStr(ll)%dist(1)                           = 0\n         obsStaticStr(ll)%dist(2:(upLastInd+1))             = -1. * upAllDists(1:upLastInd)\n         obsStaticStr(ll)%dist((upLastInd+2):nCellsInR(ll)) = downAllDists(1:downLastInd)\n\n         ! Calculate the cressman spatial weights\n         obsStaticStr(ll)%ws = &\n              ( obsStaticStr_SoA%R(ll)**2 - obsStaticStr(ll)%dist**2 ) / &\n              ( obsStaticStr_SoA%R(ll)**2 + obsStaticStr(ll)%dist**2 )\n\n      else\n\n         ! Collect the up and down stream cells\n         nCellsInR(ll) = 1\n         allocate(obsStaticStr(ll)%cellsAffected(nCellsInR(ll)))\n         allocate(obsStaticStr(ll)%dist(nCellsInR(ll)))\n         allocate(obsStaticStr(ll)%ws(nCellsInR(ll)))\n\n         obsStaticStr(ll)%cellsAffected(1) = obsStaticStr_SoA%obsCellInd(ll)\n         obsStaticStr(ll)%dist(1)          = 0\n         obsStaticStr(ll)%ws = 1\n\n      end if ! nudgeSpatial\n\n      if(temporalPersistence) then\n         ! the last obs \"static\" info\n         ! this puts in dummy values if none are found\n         setLastObsInfo = .false.\n         if(allocated(lastObsStr_SoA%usgsId)) then\n            if(any(lastObsStr_SoA%usgsId(:) .eq. obsStaticStr_SoA%usgsId(ll))) then\n               allocate(theMask(size(lastObsStr_SoA%usgsId(:))))\n               theMask = lastObsStr_SoA%usgsId(:) .eq. obsStaticStr_SoA%usgsId(ll)\n               whLastObsStr = whUniLoop(theMask)\n               deallocate(theMask)\n               !! Drop in the entire derived type for each array index! Very nice.\n               obsStaticStr_SoA%lastObsStructure_SoA%usgsId(ll) = lastObsStr_SoA%usgsId(whLastObsStr)\n               obsStaticStr_SoA%lastObsStructure_SoA%lastObsDischarge(:,ll) = lastObsStr_SoA%lastObsDischarge(:,whLastObsStr)\n               obsStaticStr_SoA%lastObsStructure_SoA%lastObsTime(:,ll) = lastObsStr_SoA%lastObsTime(:,whLastObsStr)\n               obsStaticStr_SoA%lastObsStructure_SoA%lastObsQuality(:,ll) = lastObsStr_SoA%lastObsQuality(:,whLastObsStr)\n               obsStaticStr_SoA%lastObsStructure_SoA%lastObsModelDischarge(:,ll) = lastObsStr_SoA%lastObsModelDischarge(:,whLastObsStr)\n\n               setLastObsInfo = .true.\n            endif\n         endif\n\n         if(.not. setLastObsInfo) then ! the gage did not have a last observation\n            obsStaticStr_SoA%lastObsDischarge(:,ll)      = real(-9999)\n            obsStaticStr_SoA%lastObsModelDischarge(:,ll) = real(-9999)\n            do tt=1,nTimesLastObs\n               obsStaticStr_SoA%lastObsTime(tt,ll)    = missingLastObsTime\n            end do\n            obsStaticStr_SoA%lastObsQuality(:,ll)        = real(0) !! keep this zero\n         end if\n      end if !temporalPersistence\n\n#ifdef HYDRO_D\n      ! diagnostics\n      if (my_id .eq. -5) then\n      !             1    2       3     4      5      6     7     8     9     10\n      !if( any( (/ 136, 981, 2242,  2845,  2946,  3014,  3066,  3068,  3072, 3158, 3228, &\n      !           3325, 3328,  3330,  3353,  3374,  3398,  3416,  3445, 3487, 3536, &\n      !           3621, 3667, 13554, 13651, 15062, 15311, 17450, 17394 /) &\n      !    .eq. obsStaticStr(ll)%obsCellInd ) )then\n         print*,'Ndg: '\n         print*,'Ndg: !----------------------------------'\n         print*,'Ndg: ! obsStaticStr(',ll,'):'\n         print*,'Ndg: obsStaticStr(ll)%usgsId: ',        obsStaticStr_SoA%usgsId(ll)\n         print*,'Ndg: obsStaticStr(ll)%obsCellInd: ',    obsStaticStr_SoA%obsCellInd(ll)\n         print*,'Ndg: obsStaticStr(ll)%R: ',             obsStaticStr_SoA%R(ll)\n         print*,'Ndg: obsStaticStr(ll)%G: ',             obsStaticStr_SoA%G(ll)\n         print*,'Ndg: obsStaticStr(ll)%tau: ',           obsStaticStr_SoA%tau(ll)\n         print*,'Ndg: obsStaticStr(ll)%cellsAffected: ', obsStaticStr(ll)%cellsAffected\n         print*,'Ndg: obsStaticStr(ll)%dist: ',          obsStaticStr(ll)%dist\n         print*,'Ndg: obsStaticStr(ll)%ws: ',            obsStaticStr(ll)%ws\n         if(temporalPersistence) then\n            print*,'Ndg: obsStaticStr(ll)%lastObsDischarge: ', obsStaticStr_SoA%lastObsDischarge(:,ll)\n            print*,'Ndg: obsStaticStr(ll)%lastObsDischarge: ', obsStaticStr_SoA%lastObsModelDischarge(:,ll)\n            print*,'Ndg: obsStaticStr(ll)%lastObsTime: ',      obsStaticStr_SoA%lastObsTime(:,ll)\n            print*,'Ndg: obsStaticStr(ll)%lastObsQuality: ',   obsStaticStr_SoA%lastObsQuality(:,ll)\n         endif\n         print*,'Ndg: !----------------------------------'\n         print*,'Ndg: '\n      endif ! my_id .eq. -5 (off) or any of the diagnostic inds - toggle the comments.\n      if(flushAll) flush(flushUnit)\n#endif /* HYDRO_D */\n\n   end do ! ll\n#ifdef MPP_LAND\nend if  !! my_id .eq. io_id\n\n!broadcast  %cellsAffected, %dist, %ws\ndo ll=1,size(obsStaticStr_SoA%usgsId)\n   call mpp_land_bcast_int1(nCellsInR(ll))\n   if(my_id .ne. io_id) then\n      allocate(obsStaticStr(ll)%cellsAffected(nCellsInR(ll)))\n      allocate(obsStaticStr(ll)%dist(nCellsInR(ll)))\n      allocate(obsStaticStr(ll)%ws(nCellsInR(ll)))\n   endif\n   call mpp_land_bcast_int1d(obsStaticStr(ll)%cellsAffected)\n   call mpp_land_bcast_real_1d(obsStaticStr(ll)%dist)\n   call mpp_land_bcast_real_1d(obsStaticStr(ll)%ws)\n\n   if(temporalPersistence) then\n      call mpp_land_bcast_real_1d(obsStaticStr_SoA%lastObsDischarge(:,ll))\n      call mpp_land_bcast_real_1d(obsStaticStr_SoA%lastObsModelDischarge(:,ll))\n      call mpp_land_bcast_char1d( obsStaticStr_SoA%lastObsTime(:,ll))\n      call mpp_land_bcast_real_1d(obsStaticStr_SoA%lastObsQuality(:,ll))\n   endif\nend do\n#endif /* MPP_LAND */\n\ndeallocate(nCellsInR)\n\n#ifdef HYDRO_D\nprint*,'Finnish obs_static_to_struct'\nif(flushAll) flush(flushUnit)\n#endif\n\nend subroutine obs_static_to_struct\n\n\n!===================================================================================================\n! Subroutine Name:\n!   subroutine output_nudging_last_obs\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Collect and Write out the last observations collected over time.\n! History Log:\n!   02/09/16 -Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options: None.\n! Notes:  Needs better error handling...\n\nsubroutine output_nudging_last_obs()\nuse module_RT_data,        only: rt_domain\nuse module_nudging_utils,  only: whUniLoop\nuse module_nudging_io,     only: write_nudging_last_obs, write_nudging_last_obs_soa\n#ifdef MPP_LAND\nuse MODULE_mpp_ReachLS,   only: linkls_s, linkls_e\nimplicit none\nreal,    allocatable, dimension(:) :: g_nudge\nlogical, allocatable, dimension(:) :: theMask\ninteger :: whImage, oo\n#endif\n\nif(.not. temporalPersistence) return\n\n#ifdef MPP_LAND\n!! if MPP: last obs are being written on different processors,\n!! get them back to image0 for output.\n!! 1. loop over obsStaticStr.\n!! 2. find the image holding obsCellInd\n!! 3. communicate it's last ob back to image0.\nallocate(theMask(size(linkls_s)))  ! number of processors\n\ndo oo=1, size(obsStaticStr_SoA%obsCellInd(:)) ! loop over the gages\n\n   ! Is this gage in the range for this image?\n   theMask = ( obsStaticStr_SoA%obsCellInd(oo) .ge. linkls_s .and. &\n               obsStaticStr_SoA%obsCellInd(oo) .le. linkls_e        )\n   ! The image where the gage info is located\n   whImage = whUniLoop(theMask) - 1\n\n   ! if the data is on this image or this image is the receiver, then communicate.\n   if(my_id .ne. whImage .and. my_id .ne. io_id) cycle\n   ! no communication necessary on the io image\n   if(whImage .eq. io_id) cycle\n\n   call mpp_comm_1d_real(obsStaticStr_SoA%lastObsDischarge(:,oo),      whImage, io_id)\n   call mpp_comm_1d_real(obsStaticStr_SoA%lastObsModelDischarge(:,oo), whImage, io_id)\n   call mpp_comm_1d_char(obsStaticStr_SoA%lastObsTime(:,oo),           whImage, io_id)\n   call mpp_comm_1d_real(obsStaticStr_SoA%lastObsQuality(:,oo),        whImage, io_id)\n\nend do\n\ndeallocate(theMask)\n\nif(my_id .eq. io_id) then\n   allocate(g_nudge(rt_domain(1)%gnlinksl))\nelse\n   allocate(g_nudge(1))\nend if\ncall ReachLS_write_io(RT_DOMAIN(1)%nudge,g_nudge)\n\nif(my_id .eq. io_id) &\n#endif /* MPP_LAND */\n     !! write out the last obs to file\n     call write_nudging_last_obs_soa(obsStaticStr_SoA%lastObsStructure_SoA, &\n                                 nlst(did)%olddate,          &\n                                 g_nudge                         )\n\ndeallocate(g_nudge)\n\nend subroutine output_nudging_last_obs\n\n\n!===================================================================================================\n! Program Name:\n!   accumulate_nwis_not_in_RLAndParams\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Keep a running, non-redundant log of gages seen in the forecast cycle\n!   (from nwis) which were not found in the intersection of the Route_Link\n!   gages and the parameter file gages.\n! History Log:\n!   11/4/15 - Created, JLM.\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine accumulate_nwis_not_in_RLAndParams(nwisNotRLAndParams_local,      &\n                                              nwisNotRLAndParamsCount_local, &\n                                              gageId )\nimplicit none\ncharacter(len=15), dimension(:), intent(inout) :: nwisNotRLAndParams_local\ninteger,                         intent(inout) :: nwisNotRLAndParamsCount_local\ncharacter(len=15),               intent(in)    :: gageId\nif(.not. any(nwisNotRLAndParams_local .eq. gageId)) then\n   nwisNotRLAndParamsCount_local=nwisNotRLAndParamsCount_local+1\n   if(nwisNotRLAndParamsCount .gt. size(nwisNotRLAndParams)) &\n        call hydro_stop('accumulate_nwis_not_in_RLAndParams: coutn of gages from NWIS not found '  // &\n                        'in intersection of RL and Param gages are exceeding the hardcoded limit:,'// &\n                        ' maxNwisNotRLAndParamsCount')\n   nwisNotRLAndParams_local(nwisNotRLAndParamsCount_local)=gageId\nend if\nend subroutine accumulate_nwis_not_in_RLAndParams\n\n\n!===================================================================================================\n! Program Name:\n!   distance_along_channel\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n!   Traverse the gridded channel network up or down stream, return the cumulative distance\n!   and indices of points visited. Going from one link to the next counts half the length\n!   of each as the distance. Conceptually that's midpoint to midpoint though there's really\n!   no midpoint. If half the length to the first midpoint exceeds R, no index is returned.\n!   That is, lastInd is zero.\n\n! History Log:\n!   6/4/15 - Created, JLM.\n!   8/7/15 - Heavily refactored to remove searching, JLM.\n! Usage:\n! Parameters:\n!   See formal arguments and their declarations\n! Input Files:  Specified argument.\n! Output Files: None.\n! Condition codes:\n! User controllable options:\n! Notes:\n!   The total number of links gathered is hardwired to 10,000 which is for both directions. In NHD+\n!   the shortest link is 1m. If you managed to traverse just the shortest 10,000 links then you only\n!   go [R language: > sum(head(sort(reInd$length),10000))/1000 = 60.0745] 60km. This is the minimum\n!   upper bound on R implied by the choice of 10,000. If lastInd ever becomes 10,001 a fatal error\n!   is issued.\n\nrecursive subroutine distance_along_channel(direction, & ! traversal structure in up/down direction\n                                            startInd,  & ! the starting link\n                                            startDist, & ! distance at the starting node (this iter.)\n                                            radius,    & ! to traverse, in meters.\n                                            allInds,   & ! collected links/inds\n                                            allDists,  & ! distance to collected links\n                                            lastInd    ) ! index of last collected link in above.\nuse module_RT_data,  only: rt_domain\n\nimplicit none\ntype(netwkReExpStructure), intent(in) :: direction ! up/down NtwkStr with tarversal inds, pass by ref!\ninteger, intent(in)    :: startInd  ! the starting link\nreal,    intent(in)    :: startDist ! distance at the starting node (for this iteration)\nreal,    intent(in)    :: radius    ! in meteres\ninteger, intent(inout), dimension(maxNeighLinksDim) :: allInds   ! the collected inds/links\nreal,    intent(inout), dimension(maxNeighLinksDim) :: allDists  ! the distance at each collected ind\ninteger, intent(inout) :: lastInd   ! the number of inds/links collected so far.\n\n! whGo is only > 1 upstream with a current max of 17 in NHD+\ninteger :: go, nGo\ninteger :: gg\nreal    :: newDist\ninteger, parameter :: did=1\n\n!! this routine is only called on io_id\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*,'Ndg: start distance_along_channel'\nif(flushAll) flush(flushUnit)\n#endif\n\nif(direction%end(startInd) .eq. 0) return ! a pour point (downstream) or a 1st order link (upstream)\n\nnGo = direction%end(startInd) - direction%start(startInd)\nnGo = nGo + 1  ! end-start+1 if end-start > 0\ndo gg=0,nGo-1\n   go = direction%go( direction%start(startInd) + gg )\n   allInds(lastInd+1) = go\n#ifdef MPP_LAND\n   newDist = ( chanlen_image0(startInd) + chanlen_image0(go) ) / 2.\n#else\n   newDist = ( rt_domain(did)%chanlen(startInd) + rt_domain(did)%chanlen(go) ) / 2.\n#endif\n   if(startDist + newDist .gt. radius) return  ! strictly greater than.\n   allDists(lastInd+1) = startDist + newDist\n   lastInd = lastInd+1\n   if(lastInd .ge. 10001) &\n        call hydro_stop('distance_along_channel: hardwired 10000 variable size exceeded. FIX.')\n   call distance_along_channel( &\n        direction,              &  ! the traversal structure, pass by reference.\n        go,                     &  ! the new startInd is where we go from the old startInd\n        startDist+newDist,      &  ! a little bit further is where we start the next call.\n        radius,                 &  ! static\n        allInds,                &  ! collected inds\n        allDists,               &  ! collected dists\n        lastInd                 )  ! the number collected so far\nend do\n\n#ifdef HYDRO_D\nprint*,'Ndg: end distance_along_channel'\nif(flushAll) flush(flushUnit)\n#endif\n\nend subroutine distance_along_channel\n\n!===================================================================================================\n! Program Name:\n!   tally_affected_links\n! Author(s)/Contact(s):\n!   James L McCreight <jamesmcc><ucar><edu>\n! Abstract:\n! History Log:\n!   8/11/15\n! Usage: call tally_affected_links(tt)\n! Parameters:\n! Input Files:  None.\n! Output Files: None.\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine tally_affected_links(timeIndex)\nuse module_RT_data,  only: rt_domain\n\nimplicit none\ninteger, intent(in) :: timeIndex\ninteger, allocatable, dimension(:) :: affectedInds, nGageAffect\ninteger :: nlinks, ii, oo, cc, nLinkAff, indAff, staticInd\ninteger, parameter :: did=1\n\nif (nlst(did)%channel_option .eq. 3) nLinks = RT_DOMAIN(did)%NLINKS ! For gridded channel routing\nif (nlst(did)%channel_option .eq. 1 .or.   &\n    nlst(did)%channel_option .eq. 2      ) &\n    nLinks = &\n#ifdef MPP_LAND\n             RT_DOMAIN(did)%gNLINKSL  ! For reach-based routing in parallel\n#else\n             RT_DOMAIN(did)%NLINKSL   ! For reach-based routing\n#endif\n\nallocate(affectedInds(nLinks), nGageAffect(nLinks))\n\naffectedInds = 0\nnGageAffect  = 0\n\n! parallelize this ||||||||||||||||||||||||||||||||||||||||\ndo oo=1,size(obsTimeStr(timeIndex)%obsStr)\n   staticInd = obsTimeStr(timeIndex)%obsStr(oo)%obsStaticInd\n   if(staticInd .eq. 0) cycle\n   nLinkAff = size(obsStaticStr(staticInd)%cellsAffected)\n   do cc=1, nLinkAff\n      indAff = obsStaticStr(staticInd)%cellsAffected(cc)\n      affectedInds(indAff) = indAff\n      nGageAffect(indAff) = nGageAffect(indAff) + 1\n   end do\nend do\n\n! how many total cells affected?\nnLinkAff = sum((/(1, ii=1,nLinks)/), mask=affectedInds .ne. 0)\n\nallocate(obsTimeStr(timeIndex)%allCellInds(nLinkAff))\nallocate(obsTimeStr(timeIndex)%nGageCell(nLinkAff))\n\nobsTimeStr(timeIndex)%allCellInds = pack(affectedInds, mask=affectedInds .ne. 0)\nobsTimeStr(timeIndex)%nGageCell   = pack(nGageAffect,  mask=nGageAffect .ne. 0)\n\ndeallocate(affectedInds, nGageAffect)\n\n#ifdef HYDRO_D\nprint*,'Ndg: end tally_affected_links'\nif(flushAll) flush(flushUnit)\n#endif\n\nend subroutine tally_affected_links\n\n\n!===================================================================================================\n! program name:\n!   time_wt\n! author(s)/contact(s):\n!   James McCreight\n! abstract:\n!   compute the temporal weight factor for an observation\n! history log:\n!   6/4/15 - created,\n!   12/1/15 - moved to inverse distance\n! usage:\n! parameters:\n!   q\n! input files:\n! output files:\n! condition codes:\n! user controllable options:\n! notes:\n\nreal function time_wt(modelTime, tau, obsTime)\nuse module_date_utils_nudging, only: geth_idts\nimplicit none\ncharacter(len=19), intent(in)  :: modelTime   ! model time string\nreal,              intent(in)  :: tau         ! tau half window (minutes)\ncharacter(len=19), intent(in)  :: obsTime     ! observation time string\n! local variables\ninteger :: timeDiff\nreal,    parameter :: ten  = 10.000000000\nreal,    parameter :: one  =  1.000000000\nreal,    parameter :: zero =  0.000000000\ninteger, parameter :: zeroInt = 0\n!! returned timeDiff is in seconds\ncall geth_idts(obsTime, modelTime, timeDiff)\ntimeDiff = timeDiff / 60. ! minutes to match tau\n\n!! this is the old, ramped, wrf-style time weighting.\n!time_wt = 0. ! = if(abs(timeDiff) .gt. tau)\n!if(abs(timeDiff) .lt. tau/2.)       time_wt = 1.\n!if(abs(timeDiff) .ge. tau/2. .and. &\n!   abs(timeDiff) .le. tau      ) time_wt = (tau - abs(timeDiff)) / (tau/2.)\n\n!this is the new, inverse distance weighting\nif(abs(timeDiff) .gt. tau) then\n   time_wt = zero\n   return\nend if\n!! this function has a range of [1, 10^10] so that\n!! the variable \"weighting\" in the function 'nudge_term_link' is\n!! assuredly greater than 1e-8 if weights are calculated.\ntime_wt = (ten ** ten) * ((one/ten) ** (abs(timeDiff)/(tau/ten)))\n\nend function time_wt\n\n!!$!===================================================================================================\n!!$! Program Name:\n!!$!   x\n!!$! Author(s)/Contact(s):\n!!$!   y\n!!$! Abstract:\n!!$!   z\n!!$! History Log:\n!!$!   6/4/15 - Created,\n!!$! Usage:\n!!$! Parameters:\n!!$!   q\n!!$! Input Files:\n!!$! Output Files:\n!!$! Condition codes:\n!!$! User controllable options:\n!!$! Notes:\n!!$real function cress(rr,rrmax)\n!!$implicit none\n!!$real,intent(in):: rr,rrmax\n!!$if(rr .ge. rrmax)then\n!!$   cress = 0.\n!!$else\n!!$   cress = (rrmax - rr)/(rrmax + rr)\n!!$endif\n!!$end function cress\n\n\n!===================================================================================================\n! Program Name:\n!   x\n! Author(s)/Contact(s):\n!   Wu YH\n!   James McCreight >jamesmcc<>at<>ucar<>dot<>edu<\n! Abstract:\n!   Calculate the innovations of obs.\n! History Log:\n!   2015.07.15 - Created.\n!   2015.09.19\n! Usage:\n! Parameters:\n!   q\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine nudge_innov(discharge)\nimplicit none\nreal, dimension(:,:), intent(in) :: discharge !! modeled discharge (m3/s)\ninteger :: tt, oo, nObsTt, linkInd, staticInd\nif(.not. allocated(obsTimeStr)) return\ndo tt=1,size(obsTimeStr)\n   if(.not. allocated(obsTimeStr(tt)%obsStr)) cycle\n   nObsTt = size(obsTimeStr(tt)%obsStr)\n   do oo=1,nObsTt\n      staticInd = obsTimeStr(tt)%obsStr(oo)%obsStaticInd\n      linkInd = obsStaticStr_SoA%obsCellInd(staticInd)\n      obsTimeStr(tt)%obsStr(oo)%innov =                                      &\n           ( obsTimeStr(tt)%obsStr(oo)%obsDischarge - discharge(linkInd,2) ) &\n           *obsTimeStr(tt)%obsStr(oo)%obsQC\n   enddo\nend do\nend subroutine nudge_innov\n\n!!$\n!===================================================================================================\n! Program Name:\n!   nudge_term_all\n! Author(s)/Contact(s):\n!   Wu YH, James McCreight\n! Abstract:\n!   Calculate the nudging term for one\n! History Log:\n!   2015.07.21 - Created,\n! Usage:\n! Parameters:\n!   q\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine nudge_term_all(discharge, nudgeAdj, hydroAdv)\nuse module_RT_data,  only: rt_domain\nuse module_nudging_utils, only: nudging_timer,   &\n                                accum_nudging_time\n#ifdef MPP_LAND\nuse MODULE_mpp_ReachLS, only: linkls_s, linkls_e, gNLinksL, ReachLS_write_io\n#endif\n\nimplicit none\nreal, dimension(:,:), intent(inout) :: discharge !! modeled discharge (m3/s)\nreal, dimension(:),   intent(out)   :: nudgeAdj  !! nudge to modeled discharge (m3/s)\ninteger,              intent(in)    :: hydroAdv  !! number of seconds the channel model has advanced\n\nreal, allocatable, dimension(:) :: global_discharge !! modeled discharge (m3/s)\n\ninteger :: ll, startInd, endInd, checkInd\nreal :: theNudge\n\n!!$#ifdef HYDRO_D  /* un-ifdef to get timing results */\n!!$real :: startCodeTimeAcc, endCodeTimeAcc\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) &\n!!$#endif /* MPP_LAND */\n!!$     call nudging_timer(startCodeTimeAcc)\n!!$if(flushAll) flush(flushUnit)\n!!$#endif /* HYDRO_D */  /* un-ifdef to get timing results */\n\n#ifdef MPP_LAND\n!! get global discharge. This is only needed if spatial interpolation.\n!! eventually logic: if spatialNudging determines use of global_discharge\nallocate(global_discharge(gNLinksL))\ncall ReachLS_write_io(discharge(:,2), global_discharge)\ncall mpp_land_bcast_real_1d(global_discharge)\n!! need to transform passed index to appropriate index for image\nstartInd=linkls_s(my_id+1)\nendInd  =linkls_e(my_id+1)\n#else\nstartInd=1\nendInd  =RT_DOMAIN(did)%NLINKSL\n#endif\n\nif(.not. gotT0Discharge) then\n   allocate(t0Discharge(size(discharge(:,1))))\n   t0Discharge = discharge(:,1)\n   gotT0Discharge = .true.\nend if\n\ndo ll=startInd, endInd  ! ll is in the index of the global Route_Link\n\n#ifdef HYDRO_D\n   checkInd = -9999  ! 136 !2569347 !2139306 !213095 ! 2211014 ! see below as well\n   if(ll .eq. checkInd) then\n      print*,'Ndg: checkInd: -------------------------'\n      print*,\"Ndg: checkInd: checkInd: \",checkInd\n      print*,'Ndg: checkInd: discharge(ll,2) before:',discharge(ll-startInd+1,2)\n      if(flushAll) flush(flushUnit)\n   end if\n#endif\n   theNudge = nudge_term_link(ll-startInd+1, hydroAdv, global_discharge)\n   discharge(ll-startInd+1,2) = discharge(ll-startInd+1,2) + theNudge\n#ifdef HYDRO_D\n   if(ll .eq. checkInd) then\n      print*,'Ndg: checkInd: theNudge:',theNudge\n      print*,'Ndg: checkInd: discharge(ll,2) after:',discharge(ll-startInd+1,2)\n      if(flushAll) flush(flushUnit)\n   endif\n#endif\nend do\n!! the following only valid since nudge_term_all is applied after the time step.\nnudgeAdj=discharge(:,2)-discharge(:,1)\ndischarge(:,1)=discharge(:,2)\ndeallocate(global_discharge)\n\n#ifdef HYDRO_D  /* un-ifdef to get timing results */\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) then\n!!$#endif\n!!$   call nudging_timer(endCodeTimeAcc)\n!!$   call accum_nudging_time(startCodeTimeAcc, endCodeTimeAcc, 'nudge_term_all', .true.)\n!!$#ifdef MPP_LAND\n!!$endif\n!!$#endif\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*,'Ndg: finish nudge_term_all'\nif(flushAll) flush(flushUnit)\n#endif /* HYDRO_D */  /* un-ifdef to get timing results */\n\nend subroutine nudge_term_all\n\n\n!===================================================================================================\n! Program Name:\n!   nudge_term_link\n! Author(s)/Contact(s):\n!   Wu YH,\n!   James L McCreight jamesmcc><at><ucar><dot><edu\n! Abstract:\n!   Calculate the nudging term for one model cell\n! History Log:\n!   2015.07.21 - Created,\n! Usage:\n! Parameters:\n!   q\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n!    note well that the weighting term has to sum to more than 1.E-8\n!    or the weighting is ignored.\n\nfunction nudge_term_link(linkIndIn, hydroAdv, discharge)\nuse module_nudging_utils,      only: whUniLoop\nuse module_date_utils_nudging, only: geth_newdate, geth_idts\n#ifdef MPP_LAND\nuse MODULE_mpp_ReachLS,   only: linkls_s, linkls_e\n#endif\n\nimplicit none\ninteger,              intent(in) :: linkIndIn !! stream cell index (local)\ninteger,              intent(in) :: hydroAdv  !! number of seconds the channel model has advanced\nreal, dimension(:),   intent(in) :: discharge !! modeled discharge (m3/s)\nreal :: nudge_term_link\n\nlogical :: persistBias_local\ninteger :: linkInd\ncharacter(len=19)  :: hydroTime !! actual time of the routing model\nreal :: theInnov, weighting, theBias\ninteger :: tt, oo, ll, jj, nObsTt, staticInd, obsInd\nreal,    parameter :: smallestWeight=1.e-8\n!! persistence related variables in following block\ninteger :: whGageId, flowMonth, whThresh, lastObsDt, prstDtErrInt, obsDtInt, pairCount\nlogical, dimension(nTimesLastObs) :: biasMask, whObsTooOld\nreal,    dimension(nTimesLastObs) :: biasWeights\nreal :: prstB, prstDtErr, prstErr, biasWeightSum, coefVarX, coefVarY\ncharacter(len=15) :: prstGageId\ninteger :: nCorr\nreal    :: corr, sumx, sumx2, sumxy, sumy, sumy2, xCorr, yCorr, deltaT0Discharge\ninteger, parameter :: sixty=60\nreal,    parameter :: smallestNudge=1.e-10\nreal,    parameter :: zero=1.e-37\nreal,    parameter :: zeroInt=0\nreal,    parameter :: one= 1.00000000000000000000000\n\ninteger :: whPrstParams\nlogical, allocatable, dimension(:) :: theMask\n#ifdef MPP_LAND\ninteger :: whImage, checkInd\n\n!! need to transform passed index to appropriate index for image\nlinkInd = linkIndIn + linkls_s(my_id+1) - 1\n#else\nlinkInd = linkIndIn\n#endif\ncheckInd = -9999 ! 136 !2569347 !2139306 !2565959 !213095!2211014  ! see above\n\ncall geth_newdate(hydroTime, lsmTime, hydroAdv)\n\nnudge_term_link = zero\nweighting = zero\n\n#ifdef HYDRO_D\nif(linkInd .eq. checkInd) then\n   print*,'Ndg: checkInd: hydroTime: ',hydroTime\n   print*,'Ndg: checkInd: linkInd', linkInd\n   if(flushAll) flush(flushUnit)\nend if\n#endif\n\n!! JLM: document what is this loop doing?\n!! 1) Moving the observation structure in to nudginLastObs struct.\n!! 2) Calculating the nudging terms & weights at different positions along the assim window.\ndo tt=1,size(obsTimeStr)\n\n   if(.not. allocated(obsTimeStr(tt)%allCellInds)) cycle\n   if(.not. any(obsTimeStr(tt)%allCellInds .eq. linkInd)) cycle\n   if(.not. allocated(obsTimeStr(tt)%obsStr)) cycle\n\n   do oo=1,size(obsTimeStr(tt)%obsStr)\n\n      !! if no spatial interp... this could be sped up, there's at most one match.\n      !! this might just be an exit statement at the end of the loop for non-spatial nudges.\n      staticInd = obsTimeStr(tt)%obsStr(oo)%obsStaticInd\n      if(.not. any(obsStaticStr(staticInd)%cellsAffected .eq. linkInd)) cycle\n\n      if(temporalPersistence) then\n         ! If the model time is greater than or at the obs time AND\n         ! the obs time is greater than the last written obs: then write to last obs.\n         call geth_idts(hydroTime, obsTimeStr(tt)%obsStr(oo)%obsTime, prstDtErrInt)\n\n         if(missingLastObsTime .eq.                           &\n            obsStaticStr_SoA%lastObsTime(nTimesLastObs,staticInd)) then\n            obsDtInt=1\n         else\n            call geth_idts(obsTimeStr(tt)%obsStr(oo)%obsTime,                          &\n                           obsStaticStr_SoA%lastObsTime(nTimesLastObs,staticInd), obsDtInt)\n         end if\n\n         if(prstDtErrInt .ge. 0 .and. &\n            obsDtInt     .gt. 0 .and. &\n            obsTimeStr(tt)%obsStr(oo)%obsQC .eq. 1) then\n            !! shift (note cshift does not work for all these)\n            obsStaticStr_SoA%lastObsTime(1:(nTimesLastObs-1),staticInd)           = &\n                 obsStaticStr_SoA%lastObsTime(2:nTimesLastObs,staticInd)\n            obsStaticStr_SoA%lastObsDischarge(1:(nTimesLastObs-1),staticInd)      = &\n                 obsStaticStr_SoA%lastObsDischarge(2:nTimesLastObs,staticInd)\n            obsStaticStr_SoA%lastObsModelDischarge(1:(nTimesLastObs-1),staticInd) = &\n                 obsStaticStr_SoA%lastObsModelDischarge(2:nTimesLastObs,staticInd)\n            obsStaticStr_SoA%lastObsQuality(1:(nTimesLastObs-1),staticInd)        = &\n                 obsStaticStr_SoA%lastObsQuality(2:nTimesLastObs,staticInd)\n\n            obsStaticStr_SoA%lastObsTime(nTimesLastObs,staticInd)           = &\n                 obsTimeStr(tt)%obsStr(oo)%obsTime\n            obsStaticStr_SoA%lastObsDischarge(nTimesLastObs,staticInd)      = &\n                 obsTimeStr(tt)%obsStr(oo)%obsDischarge\n            obsStaticStr_SoA%lastObsModelDischarge(nTimesLastObs,staticInd) = &\n                 discharge(obsStaticStr_SoA%obsCellInd(staticInd))\n            obsStaticStr_SoA%lastObsQuality(nTimesLastObs,staticInd)        = &\n                 obsTimeStr(tt)%obsStr(oo)%obsQC\n         end if\n      endif   !temporalPersistence\n\n      allocate(theMask(size(obsStaticStr(staticInd)%cellsAffected)))\n      theMask = obsStaticStr(staticInd)%cellsAffected .eq. linkInd\n      ll = whUniLoop(theMask)\n      deallocate(theMask)\n\n      obsInd = obsStaticStr_SoA%obsCellInd(staticInd)\n\n      theInnov =                                                            &\n           ( obsTimeStr(tt)%obsStr(oo)%obsDischarge - discharge(obsInd) ) &\n           *obsTimeStr(tt)%obsStr(oo)%obsQC\n\n      nudge_term_link = nudge_term_link                 &\n           +theInnov                                    &\n           *obsStaticStr_SoA%G(staticInd)                   &\n           *time_wt(hydroTime,                          &\n                    obsStaticStr_SoA%tau(staticInd),        &\n                    obsTimeStr(tt)%obsStr(oo)%obsTime)  &\n           *time_wt(hydroTime,                          &\n                    obsStaticStr_SoA%tau(staticInd),        &\n                    obsTimeStr(tt)%obsStr(oo)%obsTime)  &\n           *obsStaticStr(staticInd)%ws(ll)              &\n           *obsStaticStr(staticInd)%ws(ll)\n\n      !! note well that the weighting has to sum to more than 1.E-8\n      !! or the whole nudge is ignored.\n      weighting = weighting                             &\n           +time_wt(hydroTime,                          &\n                    obsStaticStr_SoA%tau(staticInd),        &\n                    obsTimeStr(tt)%obsStr(oo)%obsTime)  &\n           *time_wt(hydroTime,                          &\n                    obsStaticStr_SoA%tau(staticInd),        &\n                    obsTimeStr(tt)%obsStr(oo)%obsTime)  &\n           *obsStaticStr(staticInd)%ws(ll)              &\n           *obsStaticStr(staticInd)%ws(ll)\n\n#ifdef HYDRO_D\n      if(linkInd .eq. checkInd) then\n!if( (obsTimeStr(tt)%time .eq. obsTimeStr(tt)%obsStr(oo)%obsTime) .and. &\n!    ( abs(discharge(obsInd)+theInnov - obsTimeStr(tt)%obsStr(oo)%obsDischarge) .gt. .01) ) then\n         print*,'Ndg: checkInd: -*-*-*-*-*-*-*-*-*-*-*-*'\n         print*,'Ndg: checkInd: linkInd: ', linkInd\n         print*,'Ndg: checkInd: tt: ', tt\n         print*,'Ndg: checkInd: oo: ', oo\n         print*,'Ndg: checkInd: obsCellInd: ', obsInd\n\n         print*,'Ndg: checkInd: discharge: ',    discharge(obsInd)\n         print*,'Ndg: checkInd: theInnov: ',theInnov\n\n         print*,'Ndg: checkInd: obsDischarge: ', obsTimeStr(tt)%obsStr(oo)%obsDischarge\n\n         print*,'Ndg: checkInd: obsQC: ',        obsTimeStr(tt)%obsStr(oo)%obsQC\n         print*,'Ndg: checkInd: usgsId: ',       obsTimeStr(tt)%obsStr(oo)%usgsId\n\n         print*,'Ndg: checkInd: time_wt: ', time_wt(hydroTime,obsStaticStr_SoA%tau(staticInd), &\n              obsTimeStr(tt)%obsStr(oo)%obsTime      )\n         print*,'Ndg: checkInd: hydroTime          : ', hydroTime\n         print*,'Ndg: checkInd: obsTimeStr(tt)%time: ', obsTimeStr(tt)%time\n         print*,'Ndg: checkInd: obsTime: ', obsTimeStr(tt)%obsStr(oo)%obsTime\n         print*,'Ndg: checkInd: ws: ',      obsStaticStr(staticInd)%ws(ll)\n         print*,'Ndg: checkInd: nudge_term_link: ', nudge_term_link\n         print*,'Ndg: checkInd: weighting: ', weighting\n         if(flushAll) flush(flushUnit)\n      endif\n#endif /* HYDRO_D */\n\n   enddo ! oo\n\nenddo ! tt\n\n!!---------------------------------------------\n!! Was there a nudge in +-tau or do we apply persistence?\nif(abs(weighting) .gt. smallestWeight) then  !! 1.e-10\n\n!!$#ifdef HYDRO_D\n!!$   if(linkInd .eq. 4) then\n!!$      print*,'Ndg: nudge_term_link: ', nudge_term_link\n!!$      print*,'Ndg: weighting: ', weighting\n!!$      print*,'Ndg: nudge_term_link/weighting: ',nudge_term_link/weighting\n!!$   end if\n!!$#endif\n   ! normalize the nudge\n   nudge_term_link = nudge_term_link/weighting\n\nelse if (temporalPersistence) then\n\n   !! PERSISTENCE\n\n   !! -1) Make a local copy of the global/namelist setting persistBias so that\n   !!     if there are not enough observations available to persistBias, the\n   !!     standard observation persistence is applied.\n   persistBias_local = persistBias\n\n   !! if no nudge was applied then fall back on to persistence of last observation\n   !! 0) assume we dont find a solution so we can freely bail out.\n   nudge_term_link = zero\n\n   !! 1) what is the current link's gageId?\n   if(.not. any(obsStaticStr_SoA%obsCellInd(:) .eq. linkInd)) return\n\n   allocate(theMask(size(obsStaticStr_SoA%obsCellInd(:))))\n\n   theMask  = obsStaticStr_SoA%obsCellInd(:) .eq. linkInd\n   whGageId = whUniLoop(theMask)\n\n   deallocate(theMask)\n   prstGageId = obsStaticStr_SoA%usgsId(whGageId)\n   obsInd     = obsStaticStr_SoA%obsCellInd(whGageId)\n\n   !! 2) minimum number of observations\n   if(persistBias_local) then\n      !! This section creates a mask of usable values to use in the bias calculation\n      !! subject to two parameters of the method.\n\n      !!-----------------------------------\n      !! maxAgePairsBiasPersist\n      !! if greater than 0: apply an age-based filter\n      !! if zero          : apply no additional use all available obs.\n      !! if less than zero: apply an count-based filter\n\n\n      if(maxAgePairsBiasPersist .gt. 0) then\n         !! assume the obs are all too old, find the not so old ones\n         whObsTooOld = .true.\n         !! assume all weights are bad\n         if(persistBias_local .and. invDistTimeWeightBias) biasWeights = -9999\n         do tt=nTimesLastObs,1,-1\n            !! missing obs are not mixed with good obs. The first missing obs means the rest are missing.\n            if(obsStaticStr_SoA%lastObsTime(tt,whGageId) .eq. missingLastObsTime) exit\n            if(biasWindowBeforeT0) then\n               !! use the init time to define the end of the bias window\n               call geth_idts(initTime,  obsStaticStr_SoA%lastObsTime(tt,whGageId), obsDtInt)\n            else\n               !! use the hydro model time to define the end of the bias window\n               call geth_idts(hydroTime, obsStaticStr_SoA%lastObsTime(tt,whGageId), obsDtInt)\n            endif\n            if(persistBias_local .and. invDistTimeWeightBias) &\n                 !JLM OLD\n                 biasWeights(tt) = real(obsDtInt + nlst(did)%dtrt_ch)\n                 !JLM NEW\n                 !biasWeights(tt) = real(obsDtInt + obsResolutionInt)\n\n            if(obsDtInt .gt. (maxAgePairsBiasPersist*60*60)) exit\n            whObsTooOld(tt) = .false.\n         end do\n         biasMask= obsStaticStr_SoA%lastObsQuality(:,whGageId)  .eq. one                .and. &\n                   obsStaticStr_SoA%lastObsTime(:,whGageId)     .ne. missingLastObsTime .and. &\n                   obsStaticStr_SoA%lastObsModelDischarge(:,whGageId) .gt. zero               .and. &\n                   (.not. whObsTooOld)\n      end if\n\n      if(maxAgePairsBiasPersist .eq. 0) then\n         biasMask= obsStaticStr_SoA%lastObsQuality(:,whGageId)        .eq. one                .and. &\n                   obsStaticStr_SoA%lastObsTime(:,whGageId)     .ne. missingLastObsTime .and. &\n                   obsStaticStr_SoA%lastObsModelDischarge(:,whGageId) .gt. zero\n      endif\n\n      if(maxAgePairsBiasPersist .lt. 0) then\n         biasMask= obsStaticStr_SoA%lastObsQuality(:,whGageId)        .eq. one                .and. &\n                   obsStaticStr_SoA%lastObsTime(:,whGageId)     .ne. missingLastObsTime .and. &\n                   obsStaticStr_SoA%lastObsModelDischarge(:,whGageId) .gt. zero\n\n         !if((-1*maxAgePairs) .ge. nTimesLastObs) then there's nothing to do.\n         if((-1*maxAgePairsBiasPersist) .lt. nTimesLastObs) then\n            pairCount=0\n            do tt=nTimesLastObs,1,-1\n               if(biasMask(tt)) pairCount = pairCount + 1\n               if(pairCount .gt. (-1*maxAgePairsBiasPersist)) biasMask(tt) = .false.\n            end do\n         end if\n      end if\n\n\n      !!-----------------------------------\n      !! minNumPairsBiasPersist\n      !! If the pair count starts to dwindle during the forecast period, how does the transition\n      !! happen from bias correction to open loop?\n      !! Looks like it would get switched instantaneously. Avoid this problem with the\n      !! negative maxAgePairsBiasPersist which always use the last maxAgePairsBiasPersist count\n      !! of obs available. If there enough obs for bias correction at a site, this will ensure\n      !! that there's no transition away from bias correction in the forecast. If there are not\n      !! enough obs for bias correction, then observation persistence+decay will be applied as\n      !! in v1.0.\n      if(count(biasMask) .lt. minNumPairsBiasPersist) then\n         persistBias_local = .false.\n         !! JLM move this to hydro_d\n         !print*,'JLM: Ndg: not enough observations for bias persistence, using obs persistence', &\n         !     prstGageId\n      end if\n   end if ! if(persistBias_local)\n\n   !! Must check this for both cases obs and persistance nudging\n   !! JLM: currently not also checking the quality. May be ok, but not ideal.\n   if(obsStaticStr_SoA%lastObsTime(nTimesLastObs,whGageId) .eq. missingLastObsTime) return\n\n   !! 3) are there parameters for this link? no -> return\n   if(.not. any(nudgingParamsStr%usgsId .eq. prstGageId)) return\n\n#ifdef HYDRO_D\n   print*,'Ndg: Persistence nudging execution'\n   if(flushAll) flush(flushUnit)\n#endif\n\n   !! 4) what is the index of this link/gage in nudgingParamsStr?\n   allocate(theMask(size(nudgingParamsStr%usgsId)))\n   theMask = nudgingParamsStr%usgsId .eq. prstGageId\n   whPrstParams = whUniLoop(theMask)\n   deallocate(theMask)\n\n   !! --- Deal with the parameters ---\n   !! 5) what month is the flow in [1,12]\n   read(hydroTime(6:7),*) flowMonth\n\n   !! 6) what thereshold is the flow?\n   whThresh=1  !! init value\n   do tt=1,size(nudgingParamsStr%qThresh,1)\n      if(discharge(obsInd) .gt. nudgingParamsStr%qThresh(tt, flowMonth, whPrstParams)) &\n           whThresh=tt+1\n   end do\n\n   !!7) get the parameter of the exponential decay\n   prstB=nudgingParamsStr%expCoeff(whThresh, flowMonth, whPrstParams)\n\n   !! --- Deal with the last ob ---\n   !! 9) what is the time difference with the last ob/obs?\n   prstDtErrInt = -9999*60  ! JLM: magic value? set as a parameter above\n   do tt=nTimesLastObs,1,-1\n      ! Conditons for rejecting obs\n      if(persistBias_local) then\n         if(.not. biasMask(tt)) cycle\n      else\n         if(obsStaticStr_SoA%lastObsQuality(tt,whGageId) .eq. 0) cycle\n      end if\n      call geth_idts(hydroTime, obsStaticStr_SoA%lastObsTime(tt,whGageId), prstDtErrInt)\n      if(prstDtErrInt .lt. zeroInt) then\n         print*,'initTime:', hydroTime\n         print*,'obsStaticStr(whGageId)%lastObsTime(tt):', obsStaticStr_SoA%lastObsTime(tt,whGageId)\n         print*,'prstDtErrInt:',prstDtErrInt\n         print*,'Ndg: WARNING: lastObs times are in the future of the model time.'\n         if(futureLastObsFatal) then\n            call hydro_stop('nudge_term_link: negative prstDtErrInt: last obs in future')\n         else\n            prstDtErrInt=abs(prstDtErrInt)\n         end if\n      end if\n      exit\n   end do\n   ! By design, should not get here\n   if(prstDtErrInt .eq. -9999*60) then\n      persistBias_local=.false.\n      call hydro_stop('nudge_term_link: negative prstDtErrInt: still default value=-9999*60')\n   end if\n   prstDtErr = real(prstDtErrInt)/real(sixty)  !! second -> minutes\n\n   !! 10) what is the error or bias ?\n\n   !! Always calculate the observation nudge error.\n   prstErr = obsStaticStr_SoA%lastObsDischarge(nTimesLastObs,whGageId) - discharge(obsInd)\n\n   !! Bias term.\n   if(persistBias_local) then\n\n      if(invDistTimeWeightBias) then\n\n         if(count(biasMask .and. (biasWeights.gt.zero)) .lt. minNumPairsBiasPersist) then\n            persistBias_local=.false.\n         else\n\n            !! normalize to the latest (least) time difference and invert.\n            biasWeights=1./(biasWeights/minval(biasWeights, &\n                                               mask=biasMask .and. (biasWeights.gt.zero) ))\n            biasWeights=biasWeights**invDistTimeWeightExp !! = 5.000, hard coded above\n\n            !! The less than equal to one prevents division by huge/infinite\n            !! numbers which may result from zero time differences.\n\n            ! JLM OLD\n            biasWeightSum=sum(biasWeights, mask=biasMask .and. (biasWeights.gt.zero) )\n            ! JLM NEW\n            !biasWeightSum=sum(biasWeights, mask=biasMask              .and. &\n            !                                    (biasWeights.gt.zero) .and. &\n            !                                    (biasWeights.le.one)         )\n\n            theBias = sum( biasWeights *                                              &\n                           (obsStaticStr_SoA%lastObsDischarge(:,whGageId) -                 &\n                            obsStaticStr_SoA%lastObsModelDischarge(:,whGageId)),            &\n                                         mask=biasMask .and. (biasWeights.gt.zero)) / &\n                                         biasWeightSum\n\n         endif\n\n      else\n\n         !! Simple, straight average / unweighted,  way of calculating bias\n         theBias = sum( obsStaticStr_SoA%lastObsDischarge(:,whGageId) -                       &\n                        obsStaticStr_SoA%lastObsModelDischarge(:,whGageId), mask=biasMask ) / &\n                   max( 1, count(biasMask) )\n\n      end if\n\n      if(noConstInterfBias) then\n         !! Game to reduce bias issues.\n         !! Maybe make this an option later if it works.\n         !! do I need to stash the t0 flow? It is not the same as the last ob or the lastObsModelDischarge\n         deltaT0Discharge = discharge(obsInd) - t0Discharge(linkIndIn)\n\n         if(theBias                .lt. zero .and. &\n            deltaT0Discharge       .lt. zero        ) then\n\n            if(t0Discharge(linkIndIn) .gt. .01) then\n               !! Tweaks\n               !1!theBias=theBias - noConstInterfCoeff*(deltaT0Discharge)  ! negative - negative\n               !2!theBias=theBias*(1-(noConstInterfCoeff*abs(deltaT0Discharge)/t0Discharge(linkIndIn)))\n               !3\n               theBias = theBias*&\n                    (1.0-(noConstInterfCoeff* &\n                    ( (abs(deltaT0Discharge)/t0Discharge(linkIndIn)+.25)**2.5 - .25**2.5) ) )\n            else\n               !! if the toDischarge is really small, zero out the bias.\n               theBias = zero\n            end if\n            theBias = min( theBias, zero )             ! do not let the bias go positive\n            theBias = max( theBias, -1*discharge(obsInd)/2. ) ! do not let the bias to remove be more than half the total flow.\n\n         end if\n\n\n         if(theBias                .gt. zero .and. &\n              deltaT0Discharge       .gt. zero        ) then\n\n            if(t0Discharge(linkIndIn) .gt. .01) then\n               !! Tweaks\n               !1 !theBias = theBias - noConstInterfCoeff*(deltaT0Discharge)  ! positive - positive\n               !2!theBias=theBias*(1-(noConstInterfCoeff*abs(deltaT0Discharge)/t0Discharge(linkIndIn)))\n               !3\n               theBias = theBias*&\n                    (1.0-(noConstInterfCoeff* &\n                    ( (abs(deltaT0Discharge)/t0Discharge(linkIndIn)+.25)**2.5 - .25**2.5) ) )\n            else\n               !! if the toDischarge is really small, use a naminal t0Discharge of .01\n               theBias = theBias*&\n                    (1.0-(noConstInterfCoeff* &\n                    ( (abs(deltaT0Discharge)/.01+.25)**2.5 - .25**2.5) ) )\n            end if\n            theBias = max( theBias, zero )  ! do not let the bias go negative\n\n         end if\n      end if\n\n   endif ! if (persistBias_local)\n\n\n   !! 11) solution\n   if(.not. persistBias_local) then\n      nudge_term_link = &\n           obsStaticStr_SoA%lastObsQuality(nTimesLastObs,whGageId) * &\n           prstErr * exp(real(-1)*prstDtErr/prstB)\n   else\n      nudge_term_link = &\n           obsStaticStr_SoA%lastObsQuality(nTimesLastObs,whGageId) *   &\n           prstErr * exp(real(-1)*prstDtErr/prstB)                + &\n           theBias * (1.0 - exp(real(-1)*prstDtErr/prstB) )\n\n   endif !! if(.not. persistBias_local) then; else;\n\n   !! Currently cant get here...\n   if((prstDtErr .lt. zero) .and. futureLastObsZero) nudge_term_link = zero\n\n   !! Ensure the nudge does not make the streamflow less than zero.\n   !! This is particularly important if persistBias\n   !! Is this OK as ZERO?? Musk-cunge allows it (in theory).\n   if (discharge(obsInd)+nudge_term_link .lt. zero) then\n      nudge_term_link = zero - discharge(obsInd) + smallestNudge\n      !print*,'JLM setting nudge_term_link + observed discharge to zero (or very small)', prstGageId\n   endif\n\n\n#ifdef HYDRO_D\n   if(linkInd .eq. checkInd) then\n      print*,'Ndg: checkInd pst: -------------------'\n      print*,'Ndg: checkInd pst: usgsId: ', prstGageId\n      print*,'Ndg: checkInd pst: -------------------'\n      print*,'Ndg: checkInd pst: prstGageId: ',      prstGageId\n      print*,'Ndg: checkInd pst: obsInd: ',          obsInd\n      print*,'Ndg: checkInd pst: initTime:',         initTime\n      print*,'Ndg: checkInd pst: hydroTime: ',       hydroTime\n      print*,'Ndg: checkInd pst: flowmonth: ',       flowMonth\n      print*,'Ndg: checkInd pst: lastObsTime: ',     obsStaticStr_SoA%lastObsTime(nTimesLastObs,whGageId)\n      print*,'Ndg: checkInd pst: time difference mins: ', prstDtErr\n      print*,'Ndg: checkInd pst: obsStaticStr(whGageId)%lastObsQuality: ', &\n           obsStaticStr_SoA%lastObsQuality(nTimesLastObs,whGageId)\n      print*,'Ndg: checkInd pst: obsStaticStr(whGageId)%lastObsDischarge: ', &\n           obsStaticStr_SoA%lastObsDischarge(nTimesLastObs,whGageId)\n      print*,'Ndg: checkInd pst: modeled discharge(obsInd): ', discharge(obsInd)\n      print*,'Ndg: checkInd pst: qThresh: ',  nudgingParamsStr%qThresh(:, flowMonth, whPrstParams)\n      print*,'Ndg: checkInd pst: whThresh: ',  whThresh\n      print*,'Ndg: checkInd pst: discharge difference:', prstErr\n      print*,'Ndg: checkInd pst: prstB:', prstB\n      print*,'Ndg: checkInd pst: time difference mins prstDtErr: ', prstDtErr\n      print*,'Ndg: checkInd pst: exponent term: ', exp(real(-1)*prstDtErr/prstB)\n\n      if(persistBias_local) then\n         print*,'Ndg: checkInd pst: BIAS PERSISTENCE INFO'\n         do tt=1,nTimesLastObs\n            if(biasMask(tt)) then\n               print*,'checkInd:  ---- tt:', tt\n               print*,'checkInd: Diff: ', obsStaticStr_SoA%lastObsDischarge(tt,whGageId) -   &\n                    obsStaticStr_SoA%lastObsModelDischarge(tt,whGageId)\n               print*,'checkInd: o - : ', obsStaticStr_SoA%lastObsDischarge(tt,whGageId)\n               print*,'checkInd:    m: ', obsStaticStr_Soa%lastObsModelDischarge(tt,whGageId)\n               print*,'checkInd: biasWeights: ', biasWeights(tt)\n            end if\n         end do\n         print*,'Ndg: checkInd pst: max( 1, count(biasMask) ): ',max( 1, count(biasMask) )\n         print*,'Ndg: checkInd pst: biasWeightSum: ', biasWeightSum\n         print*,'Ndg: checkInd pst: corr: ', corr\n         print*,'Ndg: checkInd pst: nCorr: ', nCorr\n         print*,'Ndg: checkInd pst: theBias:', theBias\n         print*,'Ndg: checkInd pst: theBias/corr:', theBias/corr\n         print*,'Ndg: checkInd pst: obsStaticStr(whGageId)%lastObsQuality(nTimesLastObs) *'\n         print*,'Ndg: checkInd pst:  prstErr * exp(real(-1)*prstDtErr/prstB)', &\n              obsStaticStr_SoA%lastObsQuality(nTimesLastObs,whGageId) * &\n              prstErr * exp(real(-1)*prstDtErr/prstB)\n         print*,'Ndg: checkInd pst: theBias * (1-exp(real(-1)*prstDtErr/prstB)):', &\n              theBias * (1-exp(real(-1)*prstDtErr/prstB))\n      endif\n\n      print*,'Ndg: checkInd pst: nudge_term_link: ', nudge_term_link\n\n      if(flushAll) flush(flushUnit)\n   end if\n#endif /* HYDRO_D */\nendif !! if(abs(weighting) .gt. smallestWeight) then  !! 1.e-10\n\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*,'Ndg: finish nudge_term_link'\nif(flushAll) flush(flushUnit)\n#endif\n\n\nend function nudge_term_link\n\n\n!===================================================================================================\n! Program Name:\n!   nudge_apply_upstream_muskingumCunge\n! Author(s)/Contact(s):\n!   James L McCreight, <jamesmcc><ucar><edu>\n! Abstract:\n!   Gets the previous nudge into the collected upstream current and previous fluxes.\n! History Log:\n!   4/5/17 - Created, JLM\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine nudge_apply_upstream_muskingumCunge( qup,  quc,  np,  k )\nuse module_RT_data,  only: rt_domain\nimplicit none\nreal,    intent(inout) :: qup ! previous upstream   inflows\nreal,    intent(inout) :: quc ! current  upstream   inflows\nreal,    intent(in)    :: np  ! previous nudge\ninteger, intent(in)    :: k   ! index of flow/routlink on local image\n\n!! If not on a gage... get out.\nif(rt_domain(1)%gages(k) .eq. rt_domain(1)%gageMiss) return\n\nqup = qup + np\nquc = quc + np\n\nend subroutine nudge_apply_upstream_muskingumCunge\n\n!===================================================================================================\n! Program Name:\n!   get_netwk_reexpression\n! Author(s)/Contact(s):\n!   James L McCreight, <jamesmcc><ucar><edu>\n! Abstract:\n!   Bring in the network re-expression for indexed traversal\n!     of the stream network.\n! History Log:\n!   8/20/15 - Created, JLM\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes: Sets module derived type strs: upNetwkStr and downNetwkStr\nsubroutine get_netwk_reexpression\nuse module_RT_data,   only: rt_domain\nuse module_nudging_io,only: read_network_reexpression, get_netcdf_dim\n\nimplicit none\ninteger :: downSize, upSize, baseSize, nLinksL\n\n#ifdef MPP_LAND\nnLinksL      = RT_DOMAIN(did)%gNLINKSL  ! For reach-based routing in parallel, no decomp for nudging\n#else\nnLinksL      = RT_DOMAIN(did)%NLINKSL   ! For reach-based routing\n#endif\n\n#ifdef MPP_LAND\nif(my_id .eq. IO_id) then\n#endif\n   downSize = get_netcdf_dim(netwkReExFile, 'downDim', 'init_stream_nudging')\n   upSize   = get_netcdf_dim(netwkReExFile, 'upDim',   'init_stream_nudging')\n   baseSize = get_netcdf_dim(netwkReExFile, 'baseDim', 'init_stream_nudging')\n   !if(baseSize .ne. nLinksL) call hydro_stop('init_stream_nudging: baseSize .ne. nLinksL')\n\n   allocate(upNetwkStr%go(upSize))\n   allocate(upNetwkStr%start(nLinksL))\n   allocate(upNetwkStr%end(nLinksL))\n   allocate(downNetwkStr%go(downSize))\n   allocate(downNetwkStr%start(nLinksL))\n   allocate(downNetwkStr%end(nLinksL))\n\n   call read_network_reexpression( &\n               netwkReExFile,      & ! file with dims of the stream netwk\n               upNetwkStr%go,      & ! where each ind came from, upstream\n               upNetwkStr%start,   & ! where each ind's upstream links start in upGo\n               upNetwkStr%end,     & ! where each ind's upstream links end   in upGo\n               downNetwkStr%go,    & ! where each ind goes, downstream\n               downNetwkStr%start, & ! where each ind's downstream links start in downGo\n               downNetwkStr%end    ) ! where each ind's downstream links end   in downGo\n\n#ifdef MPP_LAND\nendif ! my_id .eq. io_id\n\n! Broadcast\ncall mpp_land_bcast_int1(upSize)\ncall mpp_land_bcast_int1(downSize)\nif(my_id .ne. io_id) then\n   allocate(upNetwkStr%go(upSize))\n   allocate(upNetwkStr%start(nLinksL))\n   allocate(upNetwkStr%end(nLinksL))\n   allocate(downNetwkStr%go(downSize))\n   allocate(downNetwkStr%start(nLinksL))\n   allocate(downNetwkStr%end(nLinksL))\nendif\ncall mpp_land_bcast_int1d(upNetwkStr%go)\ncall mpp_land_bcast_int1d(upNetwkStr%start)\ncall mpp_land_bcast_int1d(upNetwkStr%end)\ncall mpp_land_bcast_int1d(downNetwkStr%go)\ncall mpp_land_bcast_int1d(downNetwkStr%start)\ncall mpp_land_bcast_int1d(downNetwkStr%end)\n#endif\nend subroutine get_netwk_reexpression\n\n\n!===================================================================================================\n! Program Name:\n!   finish_stream_nudging\n! Author(s)/Contact(s):\n!   James L McCreight, <jamesmcc><ucar><edu>\n! Abstract:\n!   Finish off the nudging routines, memory and timing.\n! History Log:\n!   8/20/15 - Created, JLM\n! Usage:\n! Parameters:\n! Input Files:\n! Output Files:\n! Condition codes:\n! User controllable options:\n! Notes:\n\nsubroutine finish_stream_nudging\nuse module_nudging_utils, only: totalNudgeTime,  &\n                                nudging_timer,   &\n                                accum_nudging_time, &\n                                whUniLoop\nuse module_nudging_io,    only: write_nwis_not_in_RLAndParams\nimplicit none\n\ncharacter(len=15), allocatable, dimension(:) :: nwisNotRLAndParamsGathered\ncharacter(len=15), allocatable, dimension(:) :: nwisNotRLAndParamsConsolidated\ninteger, dimension(numprocs) :: nwisNotRLAndParamsCountVector\ninteger :: nwisNotRLAndParamsCountConsolidated, gg, ii\n\n#ifdef HYDRO_D  /* un-ifdef to get timing results */\n!!$real :: startCodeTimeAcc, endCodeTimeAcc\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\nprint*,'Ndg: start finish_stream_nudging'\nif(flushAll) flush(flushUnit)\n!!$#ifdef MPP_LAND\n!!$if(my_id .eq. io_id) &\n!!$#endif\n!!$     call nudging_timer(startCodeTimeAcc)\n#endif  /* HYDRO_D un-ifdef to get timing results */\n\n!! accumulate_nwis_not_in_RLAndParams\n!! because of parallel IO,  accumulation is happening on\n!! multiple images and these need to be consolidated before outputting.\n! get the total of nwisNotRLAndParam gages on all images\nnwisNotRLAndParamsCountVector(my_id+1) = nwisNotRLAndParamsCount\ndo ii=0,numprocs-1\n   call mpp_land_bcast_int1_root(nwisNotRLAndParamsCountVector(ii+1), ii)\nend do\n\nallocate(nwisNotRLAndParamsGathered(sum(nwisNotRLAndParamsCountVector)))\n\n#ifdef MPP_LAND\nif(my_id .eq. io_id) &\n#endif\n     allocate(nwisNotRLAndParamsConsolidated(sum(nwisNotRLAndParamsCountVector)))\n\ncall write_IO_char_head(nwisNotRLAndParams, nwisNotRLAndParamsGathered, nwisNotRLAndParamsCountVector)\n\nif(my_id .eq. io_id) then\n   ! now consolidate these again...\n   nwisNotRLAndParamsCountConsolidated=0\n   do gg=1,size(nwisNotRLAndParamsGathered)\n      call accumulate_nwis_not_in_RLAndParams(nwisNotRLAndParamsConsolidated,      &\n                                              nwisNotRLAndParamsCountConsolidated, &\n                                              nwisNotRLAndParamsGathered(gg)       )\n   end do\n   if(nwisNotRLAndParamsCountConsolidated .gt. 0) &\n        call write_nwis_not_in_RLAndParams(nwisNotRLAndParamsConsolidated,     &\n                                           nwisNotRLAndParamsCountConsolidated )\nendif\n\n!! deallocate local variables\nif(allocated(nwisNotRLAndParamsGathered))     deallocate(nwisNotRLAndParamsGathered)\nif(allocated(nwisNotRLAndParamsConsolidated)) deallocate(nwisNotRLAndParamsConsolidated)\n\n!! deallocate module variables here and time this\nif(allocated(obsTimeStr))                deallocate(obsTimeStr)\nif(allocated(obsStaticStr))              deallocate(obsStaticStr)\n!if(allocated(nodeGageTmp%nodeId))        deallocate(nodeGageTmp%nodeId)\nif(allocated(nodeGageTmp%usgsId))        deallocate(nodeGageTmp%usgsId) !redundant\nif(allocated(nodeGageStr%nodeId))        deallocate(nodeGageStr%nodeId)\nif(allocated(nodeGageStr%usgsId))        deallocate(nodeGageStr%usgsId)\nif(allocated(nudgingParamsTmp%usgsId))   deallocate(nudgingParamsTmp%usgsId) !redundant\nif(allocated(nudgingParamsTmp%R))        deallocate(nudgingParamsTmp%R)      !redundant\nif(allocated(nudgingParamsTmp%G))        deallocate(nudgingParamsTmp%G)      !redundant\nif(allocated(nudgingParamsTmp%tau))      deallocate(nudgingParamsTmp%tau)    !redundant\nif(allocated(nudgingParamsStr%usgsId))   deallocate(nudgingParamsStr%usgsId)\nif(allocated(nudgingParamsStr%R))        deallocate(nudgingParamsStr%R)\nif(allocated(nudgingParamsStr%G))        deallocate(nudgingParamsStr%G)\nif(allocated(nudgingParamsStr%tau))      deallocate(nudgingParamsStr%tau)\nif(allocated(nudgingParamsStr%qThresh))  deallocate(nudgingParamsStr%qThresh)\nif(allocated(nudgingParamsStr%expCoeff)) deallocate(nudgingParamsStr%expCoeff)\nif(allocated(upNetwkStr%go))             deallocate(upNetwkStr%go)\nif(allocated(upNetwkStr%start))          deallocate(upNetwkStr%start)\nif(allocated(upNetwkStr%end))            deallocate(upNetwkStr%end)\nif(allocated(downNetwkStr%go))           deallocate(downNetwkStr%go)\nif(allocated(downNetwkStr%start))        deallocate(downNetwkStr%start)\nif(allocated(downNetwkStr%end))          deallocate(downNetwkStr%end)\nif(allocated(chanlen_image0))            deallocate(chanlen_image0)\n\n!! print ouf the full timing results here.\n!! dont i need to make another accumultion call here?\n#ifdef HYDRO_D\n#ifdef MPP_LAND\nif(my_id .eq. io_id) then\n#endif\n!!$   call nudging_timer(endCodeTimeAcc)\n!!$   call accum_nudging_time(startCodeTimeAcc, endCodeTimeAcc, 'very end of nudging', .true.)\n!!$   print*,'Ndg: *nudge timing* TOTAL NUDGING TIME (seconds): ', totalNudgeTime\n   print*,'Ndg: end of finish_stream_nudging'\n   if(flushAll) flush(flushUnit)\n#ifdef MPP_LAND\nend if\n#endif\n#endif /* HYDRO_D */\n\nend subroutine finish_stream_nudging\n\n\n\nend module module_stream_nudging\n"
  },
  {
    "path": "src/nwm.md",
    "content": "Work is currently in progress to modularize the code base for the National Water Model.\n\nThese parts of the model are currently being changed\n    - [Routing/Overland](@ref md_Routing_Overland_overland)\n    - [Routing/Subsurface](@ref md_Routing_Subsurface_subsurface)\n    - [Routing/Groundwater](@ref md_Routing_Groundwater_groundwater)\n    - [Routing/Channels](@ref md_Routing_Channels_channels)\n"
  },
  {
    "path": "src/nwm_doxyfile",
    "content": "# Doxyfile 1.8.5\n\n# This file describes the settings to be used by the documentation system\n# doxygen (www.doxygen.org) for a project.\n#\n# All text after a double hash (##) is considered a comment and is placed in\n# front of the TAG it is preceding.\n#\n# All text after a single hash (#) is considered a comment and will be ignored.\n# The format is:\n# TAG = value [value, ...]\n# For lists, items can also be appended using:\n# TAG += value [value, ...]\n# Values that contain spaces should be placed between quotes (\\\" \\\").\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\n\n# This tag specifies the encoding used for all characters in the config file\n# that follow. The default is UTF-8 which is also the encoding used for all text\n# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv\n# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv\n# for the list of possible encodings.\n# The default value is: UTF-8.\n\nDOXYFILE_ENCODING      = UTF-8\n\n# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by\n# double-quotes, unless you are using Doxywizard) that should identify the\n# project for which the documentation is generated. This name is used in the\n# title of most generated pages and in a few other places.\n# The default value is: My Project.\n\nPROJECT_NAME           = \"National Water Model\"\n\n# The PROJECT_NUMBER tag can be used to enter a project or revision number. This\n# could be handy for archiving the generated documentation or if some version\n# control system is used.\n\nPROJECT_NUMBER         =\n\n# Using the PROJECT_BRIEF tag one can provide an optional one line description\n# for a project that appears at the top of each page and should give viewer a\n# quick idea about the purpose of the project. Keep the description short.\n\nPROJECT_BRIEF          =\n\n# With the PROJECT_LOGO tag one can specify an logo or icon that is included in\n# the documentation. The maximum height of the logo should not exceed 55 pixels\n# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo\n# to the output directory.\n\nPROJECT_LOGO           =\n\n# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path\n# into which the generated documentation will be written. If a relative path is\n# entered, it will be relative to the location where doxygen was started. If\n# left blank the current directory will be used.\n\nOUTPUT_DIRECTORY       = docs\n\n# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-\n# directories (in 2 levels) under the output directory of each output format and\n# will distribute the generated files over these directories. Enabling this\n# option can be useful when feeding doxygen a huge amount of source files, where\n# putting all generated files in the same directory would otherwise causes\n# performance problems for the file system.\n# The default value is: NO.\n\nCREATE_SUBDIRS         = NO\n\n# The OUTPUT_LANGUAGE tag is used to specify the language in which all\n# documentation generated by doxygen is written. Doxygen will use this\n# information to generate all constant output in the proper language.\n# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-\n# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi,\n# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en,\n# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish,\n# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish,\n# Turkish, Ukrainian and Vietnamese.\n# The default value is: English.\n\nOUTPUT_LANGUAGE        = English\n\n# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member\n# descriptions after the members that are listed in the file and class\n# documentation (similar to Javadoc). Set to NO to disable this.\n# The default value is: YES.\n\nBRIEF_MEMBER_DESC      = YES\n\n# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief\n# description of a member or function before the detailed description\n#\n# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the\n# brief descriptions will be completely suppressed.\n# The default value is: YES.\n\nREPEAT_BRIEF           = YES\n\n# This tag implements a quasi-intelligent brief description abbreviator that is\n# used to form the text in various listings. Each string in this list, if found\n# as the leading text of the brief description, will be stripped from the text\n# and the result, after processing the whole list, is used as the annotated\n# text. Otherwise, the brief description is used as-is. If left blank, the\n# following values are used ($name is automatically replaced with the name of\n# the entity):The $name class, The $name widget, The $name file, is, provides,\n# specifies, contains, represents, a, an and the.\n\nABBREVIATE_BRIEF       =\n\n# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then\n# doxygen will generate a detailed section even if there is only a brief\n# description.\n# The default value is: NO.\n\nALWAYS_DETAILED_SEC    = NO\n\n# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all\n# inherited members of a class in the documentation of that class as if those\n# members were ordinary class members. Constructors, destructors and assignment\n# operators of the base classes will not be shown.\n# The default value is: NO.\n\nINLINE_INHERITED_MEMB  = NO\n\n# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path\n# before files name in the file list and in the header files. If set to NO the\n# shortest path that makes the file name unique will be used\n# The default value is: YES.\n\nFULL_PATH_NAMES        = YES\n\n# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.\n# Stripping is only done if one of the specified strings matches the left-hand\n# part of the path. The tag can be used to show relative paths in the file list.\n# If left blank the directory from which doxygen is run is used as the path to\n# strip.\n#\n# Note that you can specify absolute paths here, but also relative paths, which\n# will be relative from the directory where doxygen is started.\n# This tag requires that the tag FULL_PATH_NAMES is set to YES.\n\nSTRIP_FROM_PATH        =\n\n# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the\n# path mentioned in the documentation of a class, which tells the reader which\n# header file to include in order to use a class. If left blank only the name of\n# the header file containing the class definition is used. Otherwise one should\n# specify the list of include paths that are normally passed to the compiler\n# using the -I flag.\n\nSTRIP_FROM_INC_PATH    =\n\n# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but\n# less readable) file names. This can be useful is your file systems doesn't\n# support long names like on DOS, Mac, or CD-ROM.\n# The default value is: NO.\n\nSHORT_NAMES            = NO\n\n# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the\n# first line (until the first dot) of a Javadoc-style comment as the brief\n# description. If set to NO, the Javadoc-style will behave just like regular Qt-\n# style comments (thus requiring an explicit @brief command for a brief\n# description.)\n# The default value is: NO.\n\nJAVADOC_AUTOBRIEF      = NO\n\n# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first\n# line (until the first dot) of a Qt-style comment as the brief description. If\n# set to NO, the Qt-style will behave just like regular Qt-style comments (thus\n# requiring an explicit \\brief command for a brief description.)\n# The default value is: NO.\n\nQT_AUTOBRIEF           = NO\n\n# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a\n# multi-line C++ special comment block (i.e. a block of //! or /// comments) as\n# a brief description. This used to be the default behavior. The new default is\n# to treat a multi-line C++ comment block as a detailed description. Set this\n# tag to YES if you prefer the old behavior instead.\n#\n# Note that setting this tag to YES also means that rational rose comments are\n# not recognized any more.\n# The default value is: NO.\n\nMULTILINE_CPP_IS_BRIEF = NO\n\n# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the\n# documentation from any documented member that it re-implements.\n# The default value is: YES.\n\nINHERIT_DOCS           = YES\n\n# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a\n# new page for each member. If set to NO, the documentation of a member will be\n# part of the file/class/namespace that contains it.\n# The default value is: NO.\n\nSEPARATE_MEMBER_PAGES  = NO\n\n# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen\n# uses this value to replace tabs by spaces in code fragments.\n# Minimum value: 1, maximum value: 16, default value: 4.\n\nTAB_SIZE               = 4\n\n# This tag can be used to specify a number of aliases that act as commands in\n# the documentation. An alias has the form:\n# name=value\n# For example adding\n# \"sideeffect=@par Side Effects:\\n\"\n# will allow you to put the command \\sideeffect (or @sideeffect) in the\n# documentation, which will result in a user-defined paragraph with heading\n# \"Side Effects:\". You can put \\n's in the value part of an alias to insert\n# newlines.\n\nALIASES                =\n\n# This tag can be used to specify a number of word-keyword mappings (TCL only).\n# A mapping has the form \"name=value\". For example adding \"class=itcl::class\"\n# will allow you to use the command class in the itcl::class meaning.\n\nTCL_SUBST              =\n\n# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources\n# only. Doxygen will then generate output that is more tailored for C. For\n# instance, some of the names that are used will be different. The list of all\n# members will be omitted, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_FOR_C  = NO\n\n# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or\n# Python sources only. Doxygen will then generate output that is more tailored\n# for that language. For instance, namespaces will be presented as packages,\n# qualified scopes will look different, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_JAVA   = NO\n\n# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran\n# sources. Doxygen will then generate output that is tailored for Fortran.\n# The default value is: NO.\n\nOPTIMIZE_FOR_FORTRAN   = YES\n\n# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL\n# sources. Doxygen will then generate output that is tailored for VHDL.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_VHDL   = NO\n\n# Doxygen selects the parser to use depending on the extension of the files it\n# parses. With this tag you can assign which parser to use for a given\n# extension. Doxygen has a built-in mapping, but you can override or extend it\n# using this tag. The format is ext=language, where ext is a file extension, and\n# language is one of the parsers supported by doxygen: IDL, Java, Javascript,\n# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make\n# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C\n# (default is Fortran), use: inc=Fortran f=C.\n#\n# Note For files without extension you can use no_extension as a placeholder.\n#\n# Note that for custom extensions you also need to set FILE_PATTERNS otherwise\n# the files are not read by doxygen.\n\nEXTENSION_MAPPING      =  \n\n# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments\n# according to the Markdown format, which allows for more readable\n# documentation. See http://daringfireball.net/projects/markdown/ for details.\n# The output of markdown processing is further processed by doxygen, so you can\n# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in\n# case of backward compatibilities issues.\n# The default value is: YES.\n\nMARKDOWN_SUPPORT       = YES\n\n# When enabled doxygen tries to link words that correspond to documented\n# classes, or namespaces to their corresponding documentation. Such a link can\n# be prevented in individual cases by by putting a % sign in front of the word\n# or globally by setting AUTOLINK_SUPPORT to NO.\n# The default value is: YES.\n\nAUTOLINK_SUPPORT       = YES\n\n# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want\n# to include (a tag file for) the STL sources as input, then you should set this\n# tag to YES in order to let doxygen match functions declarations and\n# definitions whose arguments contain STL classes (e.g. func(std::string);\n# versus func(std::string) {}). This also make the inheritance and collaboration\n# diagrams that involve STL classes more complete and accurate.\n# The default value is: NO.\n\nBUILTIN_STL_SUPPORT    = NO\n\n# If you use Microsoft's C++/CLI language, you should set this option to YES to\n# enable parsing support.\n# The default value is: NO.\n\nCPP_CLI_SUPPORT        = NO\n\n# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:\n# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen\n# will parse them like normal C++ but will assume all classes use public instead\n# of private inheritance when no explicit protection keyword is present.\n# The default value is: NO.\n\nSIP_SUPPORT            = NO\n\n# For Microsoft's IDL there are propget and propput attributes to indicate\n# getter and setter methods for a property. Setting this option to YES will make\n# doxygen to replace the get and set methods by a property in the documentation.\n# This will only work if the methods are indeed getting or setting a simple\n# type. If this is not the case, or you want to show the methods anyway, you\n# should set this option to NO.\n# The default value is: YES.\n\nIDL_PROPERTY_SUPPORT   = YES\n\n# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC\n# tag is set to YES, then doxygen will reuse the documentation of the first\n# member in the group (if any) for the other members of the group. By default\n# all members of a group must be documented explicitly.\n# The default value is: NO.\n\nDISTRIBUTE_GROUP_DOC   = NO\n\n# Set the SUBGROUPING tag to YES to allow class member groups of the same type\n# (for instance a group of public functions) to be put as a subgroup of that\n# type (e.g. under the Public Functions section). Set it to NO to prevent\n# subgrouping. Alternatively, this can be done per class using the\n# \\nosubgrouping command.\n# The default value is: YES.\n\nSUBGROUPING            = YES\n\n# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions\n# are shown inside the group in which they are included (e.g. using \\ingroup)\n# instead of on a separate page (for HTML and Man pages) or section (for LaTeX\n# and RTF).\n#\n# Note that this feature does not work in combination with\n# SEPARATE_MEMBER_PAGES.\n# The default value is: NO.\n\nINLINE_GROUPED_CLASSES = NO\n\n# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions\n# with only public data fields or simple typedef fields will be shown inline in\n# the documentation of the scope in which they are defined (i.e. file,\n# namespace, or group documentation), provided this scope is documented. If set\n# to NO, structs, classes, and unions are shown on a separate page (for HTML and\n# Man pages) or section (for LaTeX and RTF).\n# The default value is: NO.\n\nINLINE_SIMPLE_STRUCTS  = NO\n\n# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or\n# enum is documented as struct, union, or enum with the name of the typedef. So\n# typedef struct TypeS {} TypeT, will appear in the documentation as a struct\n# with name TypeT. When disabled the typedef will appear as a member of a file,\n# namespace, or class. And the struct will be named TypeS. This can typically be\n# useful for C code in case the coding convention dictates that all compound\n# types are typedef'ed and only the typedef is referenced, never the tag name.\n# The default value is: NO.\n\nTYPEDEF_HIDES_STRUCT   = NO\n\n# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This\n# cache is used to resolve symbols given their name and scope. Since this can be\n# an expensive process and often the same symbol appears multiple times in the\n# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small\n# doxygen will become slower. If the cache is too large, memory is wasted. The\n# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range\n# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536\n# symbols. At the end of a run doxygen will report the cache usage and suggest\n# the optimal cache size from a speed point of view.\n# Minimum value: 0, maximum value: 9, default value: 0.\n\nLOOKUP_CACHE_SIZE      = 0\n\n#---------------------------------------------------------------------------\n# Build related configuration options\n#---------------------------------------------------------------------------\n\n# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in\n# documentation are documented, even if no documentation was available. Private\n# class members and static file members will be hidden unless the\n# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.\n# Note: This will also disable the warnings about undocumented members that are\n# normally produced when WARNINGS is set to YES.\n# The default value is: NO.\n\nEXTRACT_ALL            = YES\n\n# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will\n# be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIVATE        = NO\n\n# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal\n# scope will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PACKAGE        = YES\n\n# If the EXTRACT_STATIC tag is set to YES all static members of a file will be\n# included in the documentation.\n# The default value is: NO.\n\nEXTRACT_STATIC         = YES\n\n# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined\n# locally in source files will be included in the documentation. If set to NO\n# only classes defined in header files are included. Does not have any effect\n# for Java sources.\n# The default value is: YES.\n\nEXTRACT_LOCAL_CLASSES  = YES\n\n# This flag is only useful for Objective-C code. When set to YES local methods,\n# which are defined in the implementation section but not in the interface are\n# included in the documentation. If set to NO only methods in the interface are\n# included.\n# The default value is: NO.\n\nEXTRACT_LOCAL_METHODS  = NO\n\n# If this flag is set to YES, the members of anonymous namespaces will be\n# extracted and appear in the documentation as a namespace called\n# 'anonymous_namespace{file}', where file will be replaced with the base name of\n# the file that contains the anonymous namespace. By default anonymous namespace\n# are hidden.\n# The default value is: NO.\n\nEXTRACT_ANON_NSPACES   = NO\n\n# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all\n# undocumented members inside documented classes or files. If set to NO these\n# members will be included in the various overviews, but no documentation\n# section is generated. This option has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_MEMBERS     = NO\n\n# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all\n# undocumented classes that are normally visible in the class hierarchy. If set\n# to NO these classes will be included in the various overviews. This option has\n# no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_CLASSES     = NO\n\n# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend\n# (class|struct|union) declarations. If set to NO these declarations will be\n# included in the documentation.\n# The default value is: NO.\n\nHIDE_FRIEND_COMPOUNDS  = NO\n\n# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any\n# documentation blocks found inside the body of a function. If set to NO these\n# blocks will be appended to the function's detailed documentation block.\n# The default value is: NO.\n\nHIDE_IN_BODY_DOCS      = NO\n\n# The INTERNAL_DOCS tag determines if documentation that is typed after a\n# \\internal command is included. If the tag is set to NO then the documentation\n# will be excluded. Set it to YES to include the internal documentation.\n# The default value is: NO.\n\nINTERNAL_DOCS          = NO\n\n# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file\n# names in lower-case letters. If set to YES upper-case letters are also\n# allowed. This is useful if you have classes or files whose names only differ\n# in case and if your file system supports case sensitive file names. Windows\n# and Mac users are advised to set this option to NO.\n# The default value is: system dependent.\n\nCASE_SENSE_NAMES       = YES\n\n# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with\n# their full class and namespace scopes in the documentation. If set to YES the\n# scope will be hidden.\n# The default value is: NO.\n\nHIDE_SCOPE_NAMES       = NO\n\n# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of\n# the files that are included by a file in the documentation of that file.\n# The default value is: YES.\n\nSHOW_INCLUDE_FILES     = YES\n\n# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include\n# files with double quotes in the documentation rather than with sharp brackets.\n# The default value is: NO.\n\nFORCE_LOCAL_INCLUDES   = NO\n\n# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the\n# documentation for inline members.\n# The default value is: YES.\n\nINLINE_INFO            = YES\n\n# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the\n# (detailed) documentation of file and class members alphabetically by member\n# name. If set to NO the members will appear in declaration order.\n# The default value is: YES.\n\nSORT_MEMBER_DOCS       = YES\n\n# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief\n# descriptions of file, namespace and class members alphabetically by member\n# name. If set to NO the members will appear in declaration order.\n# The default value is: NO.\n\nSORT_BRIEF_DOCS        = NO\n\n# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the\n# (brief and detailed) documentation of class members so that constructors and\n# destructors are listed first. If set to NO the constructors will appear in the\n# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.\n# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief\n# member documentation.\n# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting\n# detailed member documentation.\n# The default value is: NO.\n\nSORT_MEMBERS_CTORS_1ST = NO\n\n# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy\n# of group names into alphabetical order. If set to NO the group names will\n# appear in their defined order.\n# The default value is: NO.\n\nSORT_GROUP_NAMES       = NO\n\n# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by\n# fully-qualified names, including namespaces. If set to NO, the class list will\n# be sorted only by class name, not including the namespace part.\n# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.\n# Note: This option applies only to the class list, not to the alphabetical\n# list.\n# The default value is: NO.\n\nSORT_BY_SCOPE_NAME     = NO\n\n# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper\n# type resolution of all parameters of a function it will reject a match between\n# the prototype and the implementation of a member function even if there is\n# only one candidate or it is obvious which candidate to choose by doing a\n# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still\n# accept a match between prototype and implementation in such cases.\n# The default value is: NO.\n\nSTRICT_PROTO_MATCHING  = NO\n\n# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the\n# todo list. This list is created by putting \\todo commands in the\n# documentation.\n# The default value is: YES.\n\nGENERATE_TODOLIST      = YES\n\n# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the\n# test list. This list is created by putting \\test commands in the\n# documentation.\n# The default value is: YES.\n\nGENERATE_TESTLIST      = YES\n\n# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug\n# list. This list is created by putting \\bug commands in the documentation.\n# The default value is: YES.\n\nGENERATE_BUGLIST       = YES\n\n# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)\n# the deprecated list. This list is created by putting \\deprecated commands in\n# the documentation.\n# The default value is: YES.\n\nGENERATE_DEPRECATEDLIST= YES\n\n# The ENABLED_SECTIONS tag can be used to enable conditional documentation\n# sections, marked by \\if <section_label> ... \\endif and \\cond <section_label>\n# ... \\endcond blocks.\n\nENABLED_SECTIONS       =\n\n# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the\n# initial value of a variable or macro / define can have for it to appear in the\n# documentation. If the initializer consists of more lines than specified here\n# it will be hidden. Use a value of 0 to hide initializers completely. The\n# appearance of the value of individual variables and macros / defines can be\n# controlled using \\showinitializer or \\hideinitializer command in the\n# documentation regardless of this setting.\n# Minimum value: 0, maximum value: 10000, default value: 30.\n\nMAX_INITIALIZER_LINES  = 30\n\n# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at\n# the bottom of the documentation of classes and structs. If set to YES the list\n# will mention the files that were used to generate the documentation.\n# The default value is: YES.\n\nSHOW_USED_FILES        = YES\n\n# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This\n# will remove the Files entry from the Quick Index and from the Folder Tree View\n# (if specified).\n# The default value is: YES.\n\nSHOW_FILES             = YES\n\n# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces\n# page. This will remove the Namespaces entry from the Quick Index and from the\n# Folder Tree View (if specified).\n# The default value is: YES.\n\nSHOW_NAMESPACES        = YES\n\n# The FILE_VERSION_FILTER tag can be used to specify a program or script that\n# doxygen should invoke to get the current version for each file (typically from\n# the version control system). Doxygen will invoke the program by executing (via\n# popen()) the command command input-file, where command is the value of the\n# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided\n# by doxygen. Whatever the program writes to standard output is used as the file\n# version. For an example see the documentation.\n\nFILE_VERSION_FILTER    =\n\n# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed\n# by doxygen. The layout file controls the global structure of the generated\n# output files in an output format independent way. To create the layout file\n# that represents doxygen's defaults, run doxygen with the -l option. You can\n# optionally specify a file name after the option, if omitted DoxygenLayout.xml\n# will be used as the name of the layout file.\n#\n# Note that if you run doxygen from a directory containing a file called\n# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE\n# tag is left empty.\n\nLAYOUT_FILE            =\n\n# The CITE_BIB_FILES tag can be used to specify one or more bib files containing\n# the reference definitions. This must be a list of .bib files. The .bib\n# extension is automatically appended if omitted. This requires the bibtex tool\n# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.\n# For LaTeX the style of the bibliography can be controlled using\n# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the\n# search path. Do not use file names with spaces, bibtex cannot handle them. See\n# also \\cite for info how to create references.\n\nCITE_BIB_FILES         =\n\n#---------------------------------------------------------------------------\n# Configuration options related to warning and progress messages\n#---------------------------------------------------------------------------\n\n# The QUIET tag can be used to turn on/off the messages that are generated to\n# standard output by doxygen. If QUIET is set to YES this implies that the\n# messages are off.\n# The default value is: NO.\n\nQUIET                  = NO\n\n# The WARNINGS tag can be used to turn on/off the warning messages that are\n# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES\n# this implies that the warnings are on.\n#\n# Tip: Turn warnings on while writing the documentation.\n# The default value is: YES.\n\nWARNINGS               = YES\n\n# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate\n# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag\n# will automatically be disabled.\n# The default value is: YES.\n\nWARN_IF_UNDOCUMENTED   = YES\n\n# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for\n# potential errors in the documentation, such as not documenting some parameters\n# in a documented function, or documenting parameters that don't exist or using\n# markup commands wrongly.\n# The default value is: YES.\n\nWARN_IF_DOC_ERROR      = YES\n\n# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that\n# are documented, but have no documentation for their parameters or return\n# value. If set to NO doxygen will only warn about wrong or incomplete parameter\n# documentation, but not about the absence of documentation.\n# The default value is: NO.\n\nWARN_NO_PARAMDOC       = NO\n\n# The WARN_FORMAT tag determines the format of the warning messages that doxygen\n# can produce. The string should contain the $file, $line, and $text tags, which\n# will be replaced by the file and line number from which the warning originated\n# and the warning text. Optionally the format may contain $version, which will\n# be replaced by the version of the file (if it could be obtained via\n# FILE_VERSION_FILTER)\n# The default value is: $file:$line: $text.\n\nWARN_FORMAT            = \"$file:$line: $text\"\n\n# The WARN_LOGFILE tag can be used to specify a file to which warning and error\n# messages should be written. If left blank the output is written to standard\n# error (stderr).\n\nWARN_LOGFILE           =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the input files\n#---------------------------------------------------------------------------\n\n# The INPUT tag is used to specify the files and/or directories that contain\n# documented source files. You may enter file names like myfile.cpp or\n# directories like /usr/src/myproject. Separate the files or directories with\n# spaces.\n# Note: If this tag is empty the current directory is searched.\n\nINPUT                  = nwm.md Routing MPP Land_models HYDRO_drv Data_Rec CPL\n\n# This tag can be used to specify the character encoding of the source files\n# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses\n# libiconv (or the iconv built into libc) for the transcoding. See the libiconv\n# documentation (see: http://www.gnu.org/software/libiconv) for the list of\n# possible encodings.\n# The default value is: UTF-8.\n\nINPUT_ENCODING         = UTF-8\n\n# If the value of the INPUT tag contains directories, you can use the\n# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and\n# *.h) to filter out the source-files in the directories. If left blank the\n# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,\n# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,\n# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,\n# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,\n# *.qsf, *.as and *.js.\n\nFILE_PATTERNS          = *.F *.md\n\n# The RECURSIVE tag can be used to specify whether or not subdirectories should\n# be searched for input files as well.\n# The default value is: NO.\n\nRECURSIVE              = YES\n\n# The EXCLUDE tag can be used to specify files and/or directories that should be\n# excluded from the INPUT source files. This way you can easily exclude a\n# subdirectory from a directory tree whose root is specified with the INPUT tag.\n#\n# Note that relative paths are relative to the directory from which doxygen is\n# run.\n\nEXCLUDE                =\n\n# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or\n# directories that are symbolic links (a Unix file system feature) are excluded\n# from the input.\n# The default value is: NO.\n\nEXCLUDE_SYMLINKS       = NO\n\n# If the value of the INPUT tag contains directories, you can use the\n# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude\n# certain files from those directories.\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories for example use the pattern */test/*\n\nEXCLUDE_PATTERNS       =\n\n# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names\n# (namespaces, classes, functions, etc.) that should be excluded from the\n# output. The symbol name can be a fully qualified name, a word, or if the\n# wildcard * is used, a substring. Examples: ANamespace, AClass,\n# AClass::ANamespace, ANamespace::*Test\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories use the pattern */test/*\n\nEXCLUDE_SYMBOLS        =\n\n# The EXAMPLE_PATH tag can be used to specify one or more files or directories\n# that contain example code fragments that are included (see the \\include\n# command).\n\nEXAMPLE_PATH           =\n\n# If the value of the EXAMPLE_PATH tag contains directories, you can use the\n# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and\n# *.h) to filter out the source-files in the directories. If left blank all\n# files are included.\n\nEXAMPLE_PATTERNS       =\n\n# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be\n# searched for input files to be used with the \\include or \\dontinclude commands\n# irrespective of the value of the RECURSIVE tag.\n# The default value is: NO.\n\nEXAMPLE_RECURSIVE      = NO\n\n# The IMAGE_PATH tag can be used to specify one or more files or directories\n# that contain images that are to be included in the documentation (see the\n# \\image command).\n\nIMAGE_PATH             = Routing/Groundwater/images Routing/Channels/images\n\n# The INPUT_FILTER tag can be used to specify a program that doxygen should\n# invoke to filter for each input file. Doxygen will invoke the filter program\n# by executing (via popen()) the command:\n#\n# <filter> <input-file>\n#\n# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the\n# name of an input file. Doxygen will then use the output that the filter\n# program writes to standard output. If FILTER_PATTERNS is specified, this tag\n# will be ignored.\n#\n# Note that the filter must not add or remove lines; it is applied before the\n# code is scanned, but not when the output code is generated. If lines are added\n# or removed, the anchors will not be placed correctly.\n\nINPUT_FILTER           =\n\n# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern\n# basis. Doxygen will compare the file name with each pattern and apply the\n# filter if there is a match. The filters are a list of the form: pattern=filter\n# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how\n# filters are used. If the FILTER_PATTERNS tag is empty or if none of the\n# patterns match the file name, INPUT_FILTER is applied.\n\nFILTER_PATTERNS        =\n\n# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using\n# INPUT_FILTER ) will also be used to filter the input files that are used for\n# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).\n# The default value is: NO.\n\nFILTER_SOURCE_FILES    = NO\n\n# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file\n# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and\n# it is also possible to disable source filtering for a specific pattern using\n# *.ext= (so without naming a filter).\n# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.\n\nFILTER_SOURCE_PATTERNS =\n\n# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that\n# is part of the input, its contents will be placed on the main page\n# (index.html). This can be useful if you have a project on for instance GitHub\n# and want to reuse the introduction page also for the doxygen output.\n\nUSE_MDFILE_AS_MAINPAGE = nwm.md\n\n#---------------------------------------------------------------------------\n# Configuration options related to source browsing\n#---------------------------------------------------------------------------\n\n# If the SOURCE_BROWSER tag is set to YES then a list of source files will be\n# generated. Documented entities will be cross-referenced with these sources.\n#\n# Note: To get rid of all source code in the generated output, make sure that\n# also VERBATIM_HEADERS is set to NO.\n# The default value is: NO.\n\nSOURCE_BROWSER         = NO\n\n# Setting the INLINE_SOURCES tag to YES will include the body of functions,\n# classes and enums directly into the documentation.\n# The default value is: NO.\n\nINLINE_SOURCES         = NO\n\n# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any\n# special comment blocks from generated source code fragments. Normal C, C++ and\n# Fortran comments will always remain visible.\n# The default value is: YES.\n\nSTRIP_CODE_COMMENTS    = YES\n\n# If the REFERENCED_BY_RELATION tag is set to YES then for each documented\n# function all documented functions referencing it will be listed.\n# The default value is: NO.\n\nREFERENCED_BY_RELATION = NO\n\n# If the REFERENCES_RELATION tag is set to YES then for each documented function\n# all documented entities called/used by that function will be listed.\n# The default value is: NO.\n\nREFERENCES_RELATION    = NO\n\n# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set\n# to YES, then the hyperlinks from functions in REFERENCES_RELATION and\n# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will\n# link to the documentation.\n# The default value is: YES.\n\nREFERENCES_LINK_SOURCE = YES\n\n# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the\n# source code will show a tooltip with additional information such as prototype,\n# brief description and links to the definition and documentation. Since this\n# will make the HTML file larger and loading of large files a bit slower, you\n# can opt to disable this feature.\n# The default value is: YES.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nSOURCE_TOOLTIPS        = YES\n\n# If the USE_HTAGS tag is set to YES then the references to source code will\n# point to the HTML generated by the htags(1) tool instead of doxygen built-in\n# source browser. The htags tool is part of GNU's global source tagging system\n# (see http://www.gnu.org/software/global/global.html). You will need version\n# 4.8.6 or higher.\n#\n# To use it do the following:\n# - Install the latest version of global\n# - Enable SOURCE_BROWSER and USE_HTAGS in the config file\n# - Make sure the INPUT points to the root of the source tree\n# - Run doxygen as normal\n#\n# Doxygen will invoke htags (and that will in turn invoke gtags), so these\n# tools must be available from the command line (i.e. in the search path).\n#\n# The result: instead of the source browser generated by doxygen, the links to\n# source code will now point to the output of htags.\n# The default value is: NO.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nUSE_HTAGS              = NO\n\n# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a\n# verbatim copy of the header file for each class for which an include is\n# specified. Set to NO to disable this.\n# See also: Section \\class.\n# The default value is: YES.\n\nVERBATIM_HEADERS       = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to the alphabetical class index\n#---------------------------------------------------------------------------\n\n# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all\n# compounds will be generated. Enable this if the project contains a lot of\n# classes, structs, unions or interfaces.\n# The default value is: YES.\n\nALPHABETICAL_INDEX     = YES\n\n# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in\n# which the alphabetical index list will be split.\n# Minimum value: 1, maximum value: 20, default value: 5.\n# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.\n\nCOLS_IN_ALPHA_INDEX    = 5\n\n# In case all classes in a project start with a common prefix, all classes will\n# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag\n# can be used to specify a prefix (or a list of prefixes) that should be ignored\n# while generating the index headers.\n# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.\n\nIGNORE_PREFIX          =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the HTML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output\n# The default value is: YES.\n\nGENERATE_HTML          = YES\n\n# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_OUTPUT            = html\n\n# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each\n# generated HTML page (for example: .htm, .php, .asp).\n# The default value is: .html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FILE_EXTENSION    = .html\n\n# The HTML_HEADER tag can be used to specify a user-defined HTML header file for\n# each generated HTML page. If the tag is left blank doxygen will generate a\n# standard header.\n#\n# To get valid HTML the header file that includes any scripts and style sheets\n# that doxygen needs, which is dependent on the configuration options used (e.g.\n# the setting GENERATE_TREEVIEW). It is highly recommended to start with a\n# default header using\n# doxygen -w html new_header.html new_footer.html new_stylesheet.css\n# YourConfigFile\n# and then modify the file new_header.html. See also section \"Doxygen usage\"\n# for information on how to generate the default header that doxygen normally\n# uses.\n# Note: The header is subject to change so you typically have to regenerate the\n# default header when upgrading to a newer version of doxygen. For a description\n# of the possible markers and block names see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_HEADER            =\n\n# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each\n# generated HTML page. If the tag is left blank doxygen will generate a standard\n# footer. See HTML_HEADER for more information on how to generate a default\n# footer and what special commands can be used inside the footer. See also\n# section \"Doxygen usage\" for information on how to generate the default footer\n# that doxygen normally uses.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FOOTER            =\n\n# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style\n# sheet that is used by each HTML page. It can be used to fine-tune the look of\n# the HTML output. If left blank doxygen will generate a default style sheet.\n# See also section \"Doxygen usage\" for information on how to generate the style\n# sheet that doxygen normally uses.\n# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as\n# it is more robust and this tag (HTML_STYLESHEET) will in the future become\n# obsolete.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_STYLESHEET        =\n\n# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user-\n# defined cascading style sheet that is included after the standard style sheets\n# created by doxygen. Using this option one can overrule certain style aspects.\n# This is preferred over using HTML_STYLESHEET since it does not replace the\n# standard style sheet and is therefor more robust against future updates.\n# Doxygen will copy the style sheet file to the output directory. For an example\n# see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_STYLESHEET  =\n\n# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the HTML output directory. Note\n# that these files will be copied to the base HTML output directory. Use the\n# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these\n# files. In the HTML_STYLESHEET file, use the file name only. Also note that the\n# files will be copied as-is; there are no commands or markers available.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_FILES       =\n\n# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen\n# will adjust the colors in the stylesheet and background images according to\n# this color. Hue is specified as an angle on a colorwheel, see\n# http://en.wikipedia.org/wiki/Hue for more information. For instance the value\n# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300\n# purple, and 360 is red again.\n# Minimum value: 0, maximum value: 359, default value: 220.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_HUE    = 220\n\n# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors\n# in the HTML output. For a value of 0 the output will use grayscales only. A\n# value of 255 will produce the most vivid colors.\n# Minimum value: 0, maximum value: 255, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_SAT    = 100\n\n# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the\n# luminance component of the colors in the HTML output. Values below 100\n# gradually make the output lighter, whereas values above 100 make the output\n# darker. The value divided by 100 is the actual gamma applied, so 80 represents\n# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not\n# change the gamma.\n# Minimum value: 40, maximum value: 240, default value: 80.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_GAMMA  = 80\n\n# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML\n# page will contain the date and time when the page was generated. Setting this\n# to NO can help when comparing the output of multiple runs.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_TIMESTAMP         = NO\n\n# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML\n# documentation will contain sections that can be hidden and shown after the\n# page has loaded.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_SECTIONS  = NO\n\n# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries\n# shown in the various tree structured indices initially; the user can expand\n# and collapse entries dynamically later on. Doxygen will expand the tree to\n# such a level that at most the specified number of entries are visible (unless\n# a fully collapsed tree already exceeds this amount). So setting the number of\n# entries 1 will produce a full collapsed tree by default. 0 is a special value\n# representing an infinite number of entries and will result in a full expanded\n# tree by default.\n# Minimum value: 0, maximum value: 9999, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_INDEX_NUM_ENTRIES = 100\n\n# If the GENERATE_DOCSET tag is set to YES, additional index files will be\n# generated that can be used as input for Apple's Xcode 3 integrated development\n# environment (see: http://developer.apple.com/tools/xcode/), introduced with\n# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a\n# Makefile in the HTML output directory. Running make will produce the docset in\n# that directory and running make install will install the docset in\n# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at\n# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html\n# for more information.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_DOCSET        = NO\n\n# This tag determines the name of the docset feed. A documentation feed provides\n# an umbrella under which multiple documentation sets from a single provider\n# (such as a company or product suite) can be grouped.\n# The default value is: Doxygen generated docs.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_FEEDNAME        = \"Doxygen generated docs\"\n\n# This tag specifies a string that should uniquely identify the documentation\n# set bundle. This should be a reverse domain-name style string, e.g.\n# com.mycompany.MyDocSet. Doxygen will append .docset to the name.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_BUNDLE_ID       = org.doxygen.Project\n\n# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify\n# the documentation publisher. This should be a reverse domain-name style\n# string, e.g. com.mycompany.MyDocSet.documentation.\n# The default value is: org.doxygen.Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_ID    = org.doxygen.Publisher\n\n# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.\n# The default value is: Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_NAME  = Publisher\n\n# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three\n# additional HTML index files: index.hhp, index.hhc, and index.hhk. The\n# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop\n# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on\n# Windows.\n#\n# The HTML Help Workshop contains a compiler that can convert all HTML output\n# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML\n# files are now used as the Windows 98 help format, and will replace the old\n# Windows help format (.hlp) on all Windows platforms in the future. Compressed\n# HTML files also contain an index, a table of contents, and you can search for\n# words in the documentation. The HTML workshop also contains a viewer for\n# compressed HTML files.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_HTMLHELP      = NO\n\n# The CHM_FILE tag can be used to specify the file name of the resulting .chm\n# file. You can add a path in front of the file if the result should not be\n# written to the html output directory.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_FILE               =\n\n# The HHC_LOCATION tag can be used to specify the location (absolute path\n# including file name) of the HTML help compiler ( hhc.exe). If non-empty\n# doxygen will try to run the HTML help compiler on the generated index.hhp.\n# The file has to be specified with full path.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nHHC_LOCATION           =\n\n# The GENERATE_CHI flag controls if a separate .chi index file is generated (\n# YES) or that it should be included in the master .chm file ( NO).\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nGENERATE_CHI           = NO\n\n# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)\n# and project file content.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_INDEX_ENCODING     =\n\n# The BINARY_TOC flag controls whether a binary table of contents is generated (\n# YES) or a normal table of contents ( NO) in the .chm file.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nBINARY_TOC             = NO\n\n# The TOC_EXPAND flag can be set to YES to add extra items for group members to\n# the table of contents of the HTML help documentation and to the tree view.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nTOC_EXPAND             = NO\n\n# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and\n# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that\n# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help\n# (.qch) of the generated HTML documentation.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_QHP           = NO\n\n# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify\n# the file name of the resulting .qch file. The path specified is relative to\n# the HTML output folder.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQCH_FILE               =\n\n# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help\n# Project output. For more information please see Qt Help Project / Namespace\n# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_NAMESPACE          = org.doxygen.Project\n\n# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt\n# Help Project output. For more information please see Qt Help Project / Virtual\n# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-\n# folders).\n# The default value is: doc.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_VIRTUAL_FOLDER     = doc\n\n# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom\n# filter to add. For more information please see Qt Help Project / Custom\n# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-\n# filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_NAME   =\n\n# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the\n# custom filter to add. For more information please see Qt Help Project / Custom\n# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-\n# filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_ATTRS  =\n\n# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this\n# project's filter section matches. Qt Help Project / Filter Attributes (see:\n# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_SECT_FILTER_ATTRS  =\n\n# The QHG_LOCATION tag can be used to specify the location of Qt's\n# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the\n# generated .qhp file.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHG_LOCATION           =\n\n# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be\n# generated, together with the HTML files, they form an Eclipse help plugin. To\n# install this plugin and make it available under the help contents menu in\n# Eclipse, the contents of the directory containing the HTML and XML files needs\n# to be copied into the plugins directory of eclipse. The name of the directory\n# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.\n# After copying Eclipse needs to be restarted before the help appears.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_ECLIPSEHELP   = NO\n\n# A unique identifier for the Eclipse help plugin. When installing the plugin\n# the directory name containing the HTML and XML files should also have this\n# name. Each documentation set should have its own identifier.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.\n\nECLIPSE_DOC_ID         = org.doxygen.Project\n\n# If you want full control over the layout of the generated HTML pages it might\n# be necessary to disable the index and replace it with your own. The\n# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top\n# of each HTML page. A value of NO enables the index and the value YES disables\n# it. Since the tabs in the index contain the same information as the navigation\n# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nDISABLE_INDEX          = NO\n\n# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index\n# structure should be generated to display hierarchical information. If the tag\n# value is set to YES, a side panel will be generated containing a tree-like\n# index structure (just like the one that is generated for HTML Help). For this\n# to work a browser that supports JavaScript, DHTML, CSS and frames is required\n# (i.e. any modern browser). Windows users are probably better off using the\n# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can\n# further fine-tune the look of the index. As an example, the default style\n# sheet generated by doxygen has an example that shows how to put an image at\n# the root of the tree instead of the PROJECT_NAME. Since the tree basically has\n# the same information as the tab index, you could consider setting\n# DISABLE_INDEX to YES when enabling this option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_TREEVIEW      = NO\n\n# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that\n# doxygen will group on one line in the generated HTML documentation.\n#\n# Note that a value of 0 will completely suppress the enum values from appearing\n# in the overview section.\n# Minimum value: 0, maximum value: 20, default value: 4.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nENUM_VALUES_PER_LINE   = 4\n\n# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used\n# to set the initial width (in pixels) of the frame in which the tree is shown.\n# Minimum value: 0, maximum value: 1500, default value: 250.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nTREEVIEW_WIDTH         = 250\n\n# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to\n# external symbols imported via tag files in a separate window.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nEXT_LINKS_IN_WINDOW    = NO\n\n# Use this tag to change the font size of LaTeX formulas included as images in\n# the HTML documentation. When you change the font size after a successful\n# doxygen run you need to manually remove any form_*.png images from the HTML\n# output directory to force them to be regenerated.\n# Minimum value: 8, maximum value: 50, default value: 10.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_FONTSIZE       = 10\n\n# Use the FORMULA_TRANPARENT tag to determine whether or not the images\n# generated for formulas are transparent PNGs. Transparent PNGs are not\n# supported properly for IE 6.0, but are supported on all modern browsers.\n#\n# Note that when changing this option you need to delete any form_*.png files in\n# the HTML output directory before the changes have effect.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_TRANSPARENT    = YES\n\n# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see\n# http://www.mathjax.org) which uses client side Javascript for the rendering\n# instead of using prerendered bitmaps. Use this if you do not have LaTeX\n# installed or if you want to formulas look prettier in the HTML output. When\n# enabled you may also need to install MathJax separately and configure the path\n# to it using the MATHJAX_RELPATH option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nUSE_MATHJAX            = NO\n\n# When MathJax is enabled you can set the default output format to be used for\n# the MathJax output. See the MathJax site (see:\n# http://docs.mathjax.org/en/latest/output.html) for more details.\n# Possible values are: HTML-CSS (which is slower, but has the best\n# compatibility), NativeMML (i.e. MathML) and SVG.\n# The default value is: HTML-CSS.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_FORMAT         = HTML-CSS\n\n# When MathJax is enabled you need to specify the location relative to the HTML\n# output directory using the MATHJAX_RELPATH option. The destination directory\n# should contain the MathJax.js script. For instance, if the mathjax directory\n# is located at the same level as the HTML output directory, then\n# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax\n# Content Delivery Network so you can quickly see the result without installing\n# MathJax. However, it is strongly recommended to install a local copy of\n# MathJax from http://www.mathjax.org before deployment.\n# The default value is: http://cdn.mathjax.org/mathjax/latest.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest\n\n# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax\n# extension names that should be enabled during MathJax rendering. For example\n# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_EXTENSIONS     =\n\n# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces\n# of code that will be used on startup of the MathJax code. See the MathJax site\n# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an\n# example see the documentation.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_CODEFILE       =\n\n# When the SEARCHENGINE tag is enabled doxygen will generate a search box for\n# the HTML output. The underlying search engine uses javascript and DHTML and\n# should work on any modern browser. Note that when using HTML help\n# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)\n# there is already a search function so this one should typically be disabled.\n# For large projects the javascript based search engine can be slow, then\n# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to\n# search using the keyboard; to jump to the search box use <access key> + S\n# (what the <access key> is depends on the OS and browser, but it is typically\n# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down\n# key> to jump into the search results window, the results can be navigated\n# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel\n# the search. The filter options can be selected when the cursor is inside the\n# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>\n# to select a filter and <Enter> or <escape> to activate or cancel the filter\n# option.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nSEARCHENGINE           = YES\n\n# When the SERVER_BASED_SEARCH tag is enabled the search engine will be\n# implemented using a web server instead of a web client using Javascript. There\n# are two flavours of web server based searching depending on the\n# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for\n# searching and an index file used by the script. When EXTERNAL_SEARCH is\n# enabled the indexing and searching needs to be provided by external tools. See\n# the section \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSERVER_BASED_SEARCH    = NO\n\n# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP\n# script for searching. Instead the search results are written to an XML file\n# which needs to be processed by an external indexer. Doxygen will invoke an\n# external search engine pointed to by the SEARCHENGINE_URL option to obtain the\n# search results.\n#\n# Doxygen ships with an example indexer ( doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see: http://xapian.org/).\n#\n# See the section \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH        = NO\n\n# The SEARCHENGINE_URL should point to a search engine hosted by a web server\n# which will return the search results when EXTERNAL_SEARCH is enabled.\n#\n# Doxygen ships with an example indexer ( doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see: http://xapian.org/). See the section \"External Indexing and\n# Searching\" for details.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHENGINE_URL       =\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed\n# search data is written to a file for indexing by an external tool. With the\n# SEARCHDATA_FILE tag the name of this file can be specified.\n# The default file is: searchdata.xml.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHDATA_FILE        = searchdata.xml\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the\n# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is\n# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple\n# projects and redirect the results back to the right project.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH_ID     =\n\n# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen\n# projects other than the one defined by this configuration file, but that are\n# all added to the same external search index. Each project needs to have a\n# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of\n# to a relative location where the documentation can be found. The format is:\n# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTRA_SEARCH_MAPPINGS  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the LaTeX output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.\n# The default value is: YES.\n\nGENERATE_LATEX         = YES\n\n# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: latex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_OUTPUT           = latex\n\n# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be\n# invoked.\n#\n# Note that when enabling USE_PDFLATEX this option is only used for generating\n# bitmaps for formulas in the HTML output, but not in the Makefile that is\n# written to the output directory.\n# The default file is: latex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_CMD_NAME         = latex\n\n# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate\n# index for LaTeX.\n# The default file is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nMAKEINDEX_CMD_NAME     = makeindex\n\n# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nCOMPACT_LATEX          = NO\n\n# The PAPER_TYPE tag can be used to set the paper type that is used by the\n# printer.\n# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x\n# 14 inches) and executive (7.25 x 10.5 inches).\n# The default value is: a4.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPAPER_TYPE             = a4\n\n# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names\n# that should be included in the LaTeX output. To get the times font for\n# instance you can specify\n# EXTRA_PACKAGES=times\n# If left blank no extra packages will be included.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nEXTRA_PACKAGES         =\n\n# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the\n# generated LaTeX document. The header should contain everything until the first\n# chapter. If it is left blank doxygen will generate a standard header. See\n# section \"Doxygen usage\" for information on how to let doxygen write the\n# default header to a separate file.\n#\n# Note: Only use a user-defined header if you know what you are doing! The\n# following commands have a special meaning inside the header: $title,\n# $datetime, $date, $doxygenversion, $projectname, $projectnumber. Doxygen will\n# replace them by respectively the title of the page, the current date and time,\n# only the current date, the version number of doxygen, the project name (see\n# PROJECT_NAME), or the project number (see PROJECT_NUMBER).\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HEADER           =\n\n# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the\n# generated LaTeX document. The footer should contain everything after the last\n# chapter. If it is left blank doxygen will generate a standard footer.\n#\n# Note: Only use a user-defined footer if you know what you are doing!\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_FOOTER           =\n\n# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the LATEX_OUTPUT output\n# directory. Note that the files will be copied as-is; there are no commands or\n# markers available.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_FILES      =\n\n# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is\n# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will\n# contain links (just like the HTML output) instead of page references. This\n# makes the output suitable for online browsing using a PDF viewer.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPDF_HYPERLINKS         = YES\n\n# If the LATEX_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate\n# the PDF file directly from the LaTeX files. Set this option to YES to get a\n# higher quality PDF documentation.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nUSE_PDFLATEX           = YES\n\n# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode\n# command to the generated LaTeX files. This will instruct LaTeX to keep running\n# if errors occur, instead of asking the user for help. This option is also used\n# when generating formulas in HTML.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BATCHMODE        = NO\n\n# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the\n# index chapters (such as File Index, Compound Index, etc.) in the output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HIDE_INDICES     = NO\n\n# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source\n# code with syntax highlighting in the LaTeX output.\n#\n# Note that which sources are shown also depends on other settings such as\n# SOURCE_BROWSER.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_SOURCE_CODE      = NO\n\n# The LATEX_BIB_STYLE tag can be used to specify the style to use for the\n# bibliography, e.g. plainnat, or ieeetr. See\n# http://en.wikipedia.org/wiki/BibTeX and \\cite for more info.\n# The default value is: plain.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BIB_STYLE        = plain\n\n#---------------------------------------------------------------------------\n# Configuration options related to the RTF output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The\n# RTF output is optimized for Word 97 and may not look too pretty with other RTF\n# readers/editors.\n# The default value is: NO.\n\nGENERATE_RTF           = NO\n\n# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: rtf.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_OUTPUT             = rtf\n\n# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nCOMPACT_RTF            = NO\n\n# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will\n# contain hyperlink fields. The RTF file will contain links (just like the HTML\n# output) instead of page references. This makes the output suitable for online\n# browsing using Word or some other Word compatible readers that support those\n# fields.\n#\n# Note: WordPad (write) and others do not support links.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_HYPERLINKS         = NO\n\n# Load stylesheet definitions from file. Syntax is similar to doxygen's config\n# file, i.e. a series of assignments. You only have to provide replacements,\n# missing definitions are set to their default value.\n#\n# See also section \"Doxygen usage\" for information on how to generate the\n# default style sheet that doxygen normally uses.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_STYLESHEET_FILE    =\n\n# Set optional variables used in the generation of an RTF document. Syntax is\n# similar to doxygen's config file. A template extensions file can be generated\n# using doxygen -e rtf extensionFile.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_EXTENSIONS_FILE    =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the man page output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for\n# classes and files.\n# The default value is: NO.\n\nGENERATE_MAN           = NO\n\n# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it. A directory man3 will be created inside the directory specified by\n# MAN_OUTPUT.\n# The default directory is: man.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_OUTPUT             = man\n\n# The MAN_EXTENSION tag determines the extension that is added to the generated\n# man pages. In case the manual section does not start with a number, the number\n# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is\n# optional.\n# The default value is: .3.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_EXTENSION          = .3\n\n# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it\n# will generate one additional man file for each entity documented in the real\n# man page(s). These additional files only source the real man page, but without\n# them the man command would be unable to find the correct page.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_LINKS              = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the XML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that\n# captures the structure of the code including all documentation.\n# The default value is: NO.\n\nGENERATE_XML           = NO\n\n# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: xml.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_OUTPUT             = xml\n\n# The XML_SCHEMA tag can be used to specify a XML schema, which can be used by a\n# validating XML parser to check the syntax of the XML files.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_SCHEMA             =\n\n# The XML_DTD tag can be used to specify a XML DTD, which can be used by a\n# validating XML parser to check the syntax of the XML files.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_DTD                =\n\n# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program\n# listings (including syntax highlighting and cross-referencing information) to\n# the XML output. Note that enabling this will significantly increase the size\n# of the XML output.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_PROGRAMLISTING     = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to the DOCBOOK output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files\n# that can be used to generate PDF.\n# The default value is: NO.\n\nGENERATE_DOCBOOK       = NO\n\n# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in\n# front of it.\n# The default directory is: docbook.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_OUTPUT         = docbook\n\n#---------------------------------------------------------------------------\n# Configuration options for the AutoGen Definitions output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen\n# Definitions (see http://autogen.sf.net) file that captures the structure of\n# the code including all documentation. Note that this feature is still\n# experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_AUTOGEN_DEF   = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the Perl module output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module\n# file that captures the structure of the code including all documentation.\n#\n# Note that this feature is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_PERLMOD       = NO\n\n# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary\n# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI\n# output from the Perl module output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_LATEX          = NO\n\n# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely\n# formatted so it can be parsed by a human reader. This is useful if you want to\n# understand what is going on. On the other hand, if this tag is set to NO the\n# size of the Perl module output will be much smaller and Perl will parse it\n# just the same.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_PRETTY         = YES\n\n# The names of the make variables in the generated doxyrules.make file are\n# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful\n# so different doxyrules.make files included by the same Makefile don't\n# overwrite each other's variables.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_MAKEVAR_PREFIX =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the preprocessor\n#---------------------------------------------------------------------------\n\n# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all\n# C-preprocessor directives found in the sources and include files.\n# The default value is: YES.\n\nENABLE_PREPROCESSING   = YES\n\n# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names\n# in the source code. If set to NO only conditional compilation will be\n# performed. Macro expansion can be done in a controlled way by setting\n# EXPAND_ONLY_PREDEF to YES.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nMACRO_EXPANSION        = NO\n\n# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then\n# the macro expansion is limited to the macros specified with the PREDEFINED and\n# EXPAND_AS_DEFINED tags.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_ONLY_PREDEF     = NO\n\n# If the SEARCH_INCLUDES tag is set to YES the includes files in the\n# INCLUDE_PATH will be searched if a #include is found.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSEARCH_INCLUDES        = YES\n\n# The INCLUDE_PATH tag can be used to specify one or more directories that\n# contain include files that are not input files but should be processed by the\n# preprocessor.\n# This tag requires that the tag SEARCH_INCLUDES is set to YES.\n\nINCLUDE_PATH           =\n\n# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard\n# patterns (like *.h and *.hpp) to filter out the header-files in the\n# directories. If left blank, the patterns specified with FILE_PATTERNS will be\n# used.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nINCLUDE_FILE_PATTERNS  =\n\n# The PREDEFINED tag can be used to specify one or more macro names that are\n# defined before the preprocessor is started (similar to the -D option of e.g.\n# gcc). The argument of the tag is a list of macros of the form: name or\n# name=definition (no spaces). If the definition and the \"=\" are omitted, \"=1\"\n# is assumed. To prevent a macro definition from being undefined via #undef or\n# recursively expanded use the := operator instead of the = operator.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nPREDEFINED             =\n\n# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this\n# tag can be used to specify a list of macro names that should be expanded. The\n# macro definition that is found in the sources will be used. Use the PREDEFINED\n# tag if you want to use a different macro definition that overrules the\n# definition found in the source code.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_AS_DEFINED      =\n\n# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will\n# remove all refrences to function-like macros that are alone on a line, have an\n# all uppercase name, and do not end with a semicolon. Such function macros are\n# typically used for boiler-plate code, and will confuse the parser if not\n# removed.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSKIP_FUNCTION_MACROS   = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to external references\n#---------------------------------------------------------------------------\n\n# The TAGFILES tag can be used to specify one or more tag files. For each tag\n# file the location of the external documentation should be added. The format of\n# a tag file without this location is as follows:\n# TAGFILES = file1 file2 ...\n# Adding location for the tag files is done as follows:\n# TAGFILES = file1=loc1 \"file2 = loc2\" ...\n# where loc1 and loc2 can be relative or absolute paths or URLs. See the\n# section \"Linking to external documentation\" for more information about the use\n# of tag files.\n# Note: Each tag file must have an unique name (where the name does NOT include\n# the path). If a tag file is not located in the directory in which doxygen is\n# run, you must also specify the path to the tagfile here.\n\nTAGFILES               =\n\n# When a file name is specified after GENERATE_TAGFILE, doxygen will create a\n# tag file that is based on the input files it reads. See section \"Linking to\n# external documentation\" for more information about the usage of tag files.\n\nGENERATE_TAGFILE       =\n\n# If the ALLEXTERNALS tag is set to YES all external class will be listed in the\n# class index. If set to NO only the inherited external classes will be listed.\n# The default value is: NO.\n\nALLEXTERNALS           = NO\n\n# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in\n# the modules index. If set to NO, only the current project's groups will be\n# listed.\n# The default value is: YES.\n\nEXTERNAL_GROUPS        = YES\n\n# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in\n# the related pages index. If set to NO, only the current project's pages will\n# be listed.\n# The default value is: YES.\n\nEXTERNAL_PAGES         = YES\n\n# The PERL_PATH should be the absolute path and name of the perl script\n# interpreter (i.e. the result of 'which perl').\n# The default file (with absolute path) is: /usr/bin/perl.\n\nPERL_PATH              = /usr/bin/perl\n\n#---------------------------------------------------------------------------\n# Configuration options related to the dot tool\n#---------------------------------------------------------------------------\n\n# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram\n# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to\n# NO turns the diagrams off. Note that this option also works with HAVE_DOT\n# disabled, but it is recommended to install and use dot, since it yields more\n# powerful graphs.\n# The default value is: YES.\n\nCLASS_DIAGRAMS         = YES\n\n# You can define message sequence charts within doxygen comments using the \\msc\n# command. Doxygen will then run the mscgen tool (see:\n# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the\n# documentation. The MSCGEN_PATH tag allows you to specify the directory where\n# the mscgen tool resides. If left empty the tool is assumed to be found in the\n# default search path.\n\nMSCGEN_PATH            =\n\n# If set to YES, the inheritance and collaboration graphs will hide inheritance\n# and usage relations if the target is undocumented or is not a class.\n# The default value is: YES.\n\nHIDE_UNDOC_RELATIONS   = YES\n\n# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is\n# available from the path. This tool is part of Graphviz (see:\n# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent\n# Bell Labs. The other options in this section have no effect if this option is\n# set to NO\n# The default value is: NO.\n\nHAVE_DOT               = YES\n\n# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed\n# to run in parallel. When set to 0 doxygen will base this on the number of\n# processors available in the system. You can set it explicitly to a value\n# larger than 0 to get control over the balance between CPU load and processing\n# speed.\n# Minimum value: 0, maximum value: 32, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_NUM_THREADS        = 0\n\n# When you want a differently looking font n the dot files that doxygen\n# generates you can specify the font name using DOT_FONTNAME. You need to make\n# sure dot is able to find the font, which can be done by putting it in a\n# standard location or by setting the DOTFONTPATH environment variable or by\n# setting DOT_FONTPATH to the directory containing the font.\n# The default value is: Helvetica.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTNAME           = Helvetica\n\n# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of\n# dot graphs.\n# Minimum value: 4, maximum value: 24, default value: 10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTSIZE           = 10\n\n# By default doxygen will tell dot to use the default font as specified with\n# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set\n# the path where dot can find it using this tag.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTPATH           =\n\n# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for\n# each documented class showing the direct and indirect inheritance relations.\n# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCLASS_GRAPH            = YES\n\n# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a\n# graph for each documented class showing the direct and indirect implementation\n# dependencies (inheritance, containment, and class references variables) of the\n# class with other documented classes.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCOLLABORATION_GRAPH    = YES\n\n# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for\n# groups, showing the direct groups dependencies.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGROUP_GRAPHS           = YES\n\n# If the UML_LOOK tag is set to YES doxygen will generate inheritance and\n# collaboration diagrams in a style similar to the OMG's Unified Modeling\n# Language.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nUML_LOOK               = NO\n\n# If the UML_LOOK tag is enabled, the fields and methods are shown inside the\n# class node. If there are many fields or methods and many nodes the graph may\n# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the\n# number of items for each type to make the size more manageable. Set this to 0\n# for no limit. Note that the threshold may be exceeded by 50% before the limit\n# is enforced. So when you set the threshold to 10, up to 15 fields may appear,\n# but if the number exceeds 15, the total amount of fields shown is limited to\n# 10.\n# Minimum value: 0, maximum value: 100, default value: 10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nUML_LIMIT_NUM_FIELDS   = 10\n\n# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and\n# collaboration graphs will show the relations between templates and their\n# instances.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nTEMPLATE_RELATIONS     = NO\n\n# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to\n# YES then doxygen will generate a graph for each documented file showing the\n# direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDE_GRAPH          = YES\n\n# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are\n# set to YES then doxygen will generate a graph for each documented file showing\n# the direct and indirect include dependencies of the file with other documented\n# files.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDED_BY_GRAPH      = YES\n\n# If the CALL_GRAPH tag is set to YES then doxygen will generate a call\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable call graphs for selected\n# functions only using the \\callgraph command.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALL_GRAPH             = YES\n\n# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable caller graphs for selected\n# functions only using the \\callergraph command.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALLER_GRAPH           = YES\n\n# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical\n# hierarchy of all classes instead of a textual one.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGRAPHICAL_HIERARCHY    = YES\n\n# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the\n# dependencies a directory has on other directories in a graphical way. The\n# dependency relations are determined by the #include relations between the\n# files in the directories.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDIRECTORY_GRAPH        = YES\n\n# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images\n# generated by dot.\n# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order\n# to make the SVG files visible in IE 9+ (other browsers do not have this\n# requirement).\n# Possible values are: png, jpg, gif and svg.\n# The default value is: png.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_IMAGE_FORMAT       = png\n\n# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to\n# enable generation of interactive SVG images that allow zooming and panning.\n#\n# Note that this requires a modern browser other than Internet Explorer. Tested\n# and working are Firefox, Chrome, Safari, and Opera.\n# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make\n# the SVG files visible. Older versions of IE do not have SVG support.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINTERACTIVE_SVG        = NO\n\n# The DOT_PATH tag can be used to specify the path where the dot tool can be\n# found. If left blank, it is assumed the dot tool can be found in the path.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_PATH               =\n\n# The DOTFILE_DIRS tag can be used to specify one or more directories that\n# contain dot files that are included in the documentation (see the \\dotfile\n# command).\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOTFILE_DIRS           =\n\n# The MSCFILE_DIRS tag can be used to specify one or more directories that\n# contain msc files that are included in the documentation (see the \\mscfile\n# command).\n\nMSCFILE_DIRS           =\n\n# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes\n# that will be shown in the graph. If the number of nodes in a graph becomes\n# larger than this value, doxygen will truncate the graph, which is visualized\n# by representing a node as a red box. Note that doxygen if the number of direct\n# children of the root node in a graph is already larger than\n# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that\n# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.\n# Minimum value: 0, maximum value: 10000, default value: 50.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_GRAPH_MAX_NODES    = 50\n\n# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs\n# generated by dot. A depth value of 3 means that only nodes reachable from the\n# root by following a path via at most 3 edges will be shown. Nodes that lay\n# further from the root node will be omitted. Note that setting this option to 1\n# or 2 may greatly reduce the computation time needed for large code bases. Also\n# note that the size of a graph can be further restricted by\n# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.\n# Minimum value: 0, maximum value: 1000, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nMAX_DOT_GRAPH_DEPTH    = 0\n\n# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent\n# background. This is disabled by default, because dot on Windows does not seem\n# to support this out of the box.\n#\n# Warning: Depending on the platform used, enabling this option may lead to\n# badly anti-aliased labels on the edges of a graph (i.e. they become hard to\n# read).\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_TRANSPARENT        = NO\n\n# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output\n# files in one run (i.e. multiple -o and -T options on the command line). This\n# makes dot run faster, but since only newer versions of dot (>1.8.10) support\n# this, this feature is disabled by default.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_MULTI_TARGETS      = NO\n\n# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page\n# explaining the meaning of the various boxes and arrows in the dot generated\n# graphs.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGENERATE_LEGEND        = YES\n\n# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot\n# files that are used to generate the various graphs.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_CLEANUP            = YES\n"
  },
  {
    "path": "src/template/HYDRO/CHANPARM.TBL",
    "content": "Channel Parameters\nStreamOrder\n10,1,  'Bw     HLINK   ChSSlp   MannN'\n1,     1.6,    0.02,    0.03,      0.09\n2,     2.4,    0.02,    0.03,      0.07\n3,     3.5,    0.02,    0.03,      0.06\n4,     5.3,    0.03,    0.04,      0.05\n5,     7.4,    0.03,    0.04,      0.04\n6,     11.,    0.03,    0.04,      0.03\n7,     14.,    0.03,    0.04,      0.03\n8,     16.,    0.10,    0.04,      0.02\n9,     26.,    0.30,    0.05,      0.02\n10,    110.,    0.30,    0.10,      0.02\n"
  },
  {
    "path": "src/template/HYDRO/HYDRO.TBL",
    "content": "     28 USGS for OV_ROUGH\n   SFC_ROUGH'\n     0.025,    'Urban and Built-Up Land'  \n     0.035,    'Dryland Cropland and Pasture' \n     0.035,    'Irrigated Cropland and Pasture' \n     0.055,    'Mixed Dryland/Irrigated Cropland and Pasture' \n     0.035,    'Cropland/Grassland Mosaic'\n     0.068,    'Cropland/Woodland Mosaic' \n     0.055,    'Grassland' \n     0.055,    'Shrubland' \n     0.055,    'Mixed Shrubland/Grassland' \n     0.055,    'Savanna' \n     0.200,    'Deciduous Broadleaf Forest' \n     0.200,    'Deciduous Needleleaf Forest' \n     0.200,    'Evergreen Broadleaf Forest'\n     0.200,    'Evergreen Needleleaf Forest'  \n     0.200,    'Mixed Forest' \n     0.005,    'Water Bodies' \n     0.070,    'Herbaceous Wetland' \n     0.070,    'Wooded Wetland' \n     0.035,    'Barren or Sparsely Vegetated' \n     0.055,    'Herbaceous Tundra' \n     0.055,    'Wooded Tundra' \n     0.055,    'Mixed Tundra' \n     0.055,    'Bare Ground Tundra' \n     0.010,    'Snow or Ice' \n     0.010,    'Playa' \n     0.100,    'Lava'   \n     0.010,    'White Sand' \n     0.005,    'Non-Ocean Water Bodies'\n19, for SATDK\nSATDK     MAXSMC    REFSMC   WLTSMC  QTZ    '\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'SAND'\n1.41E-5,  0.421,    0.283,   0.028,  0.82, 'LOAMY SAND'\n5.23E-6,  0.434,    0.312,   0.047,  0.60, 'SANDY LOAM'\n2.81E-6,  0.476,    0.360,   0.084,  0.25, 'SILT LOAM'\n2.18E-6,  0.484,    0.347,   0.061,  0.10, 'SILT'\n3.38E-6,  0.439,    0.329,   0.066,  0.40, 'LOAM'\n4.45E-6,  0.404,    0.315,   0.069,  0.60, 'SANDY CLAY LOAM'\n2.03E-6,  0.464,    0.387,   0.120,  0.10, 'SILTY CLAY LOAM'\n2.45E-6,  0.465,    0.382,   0.103,  0.35, 'CLAY LOAM'\n7.22E-6,  0.406,    0.338,   0.100,  0.52, 'SANDY CLAY'\n1.34E-6,  0.468,    0.404,   0.126,  0.10, 'SILTY CLAY'\n9.74E-7,  0.468,    0.412,   0.138,  0.25, 'CLAY'\n3.38E-6,  0.439,    0.329,   0.066,  0.05, 'ORGANIC MATERIAL'\n    0.0,  1.0,      0.0,     0.0,    0.60, 'WATER'\n1.41E-4,  0.20,     0.170,   0.006,  0.07, 'BEDROCK'\n1.41E-5,  0.421,    0.283,   0.028,  0.25, 'OTHER(land-ice)'\n9.74E-7,  0.468,    0.454,   0.030,  0.60, 'PLAYA'\n1.41E-4,  0.200,    0.170,   0.006,  0.52, 'LAVA'\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'WHITE SAND'\n"
  },
  {
    "path": "src/template/HYDRO/HYDRO_MODIS.TBL",
    "content": "     20 MODIS for OV_ROUGH\n   SFC_ROUGH'\n     0.200,    'Evergreen Needleleaf Forest'\n     0.200,    'Evergreen Broadleaf Forest'\n     0.200,    'Deciduous Needleleaf Forest'\n     0.200,    'Deciduous Broadleaf Forest'\n     0.200,    'Mixed Forest'\n     0.055,    'Shrubland'\n     0.055,    'Mixed Shrubland/Grassland'\n     0.055,    'Shrubland'\n     0.055,    'Savanna'\n     0.055,    'Grassland'\n     0.070,    'Herbaceous Wetland'\n     0.035,    'Dryland Cropland and Pasture'\n     0.025,    'Urban and Built-Up Land'\n     0.035,    'Cropland/Grassland Mosaic'\n     0.010,    'Snow or Ice'\n     0.035,    'Barren or Sparsely Vegetated'\n     0.005,    'Water Bodies'\n     0.055,    'Wooded Tundra'\n     0.055,    'Mixed Tundra'\n     0.055,    'Bare Ground Tundra'\n19, for SATDK\nSATDK     MAXSMC    REFSMC   WLTSMC  QTZ    '\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'SAND'\n1.41E-5,  0.421,    0.283,   0.028,  0.82, 'LOAMY SAND'\n5.23E-6,  0.434,    0.312,   0.047,  0.60, 'SANDY LOAM'\n2.81E-6,  0.476,    0.360,   0.084,  0.25, 'SILT LOAM'\n2.18E-6,  0.484,    0.347,   0.061,  0.10, 'SILT'\n3.38E-6,  0.439,    0.329,   0.066,  0.40, 'LOAM'\n4.45E-6,  0.404,    0.315,   0.069,  0.60, 'SANDY CLAY LOAM'\n2.03E-6,  0.464,    0.387,   0.120,  0.10, 'SILTY CLAY LOAM'\n2.45E-6,  0.465,    0.382,   0.103,  0.35, 'CLAY LOAM'\n7.22E-6,  0.406,    0.338,   0.100,  0.52, 'SANDY CLAY'\n1.34E-6,  0.468,    0.404,   0.126,  0.10, 'SILTY CLAY'\n9.74E-7,  0.468,    0.412,   0.138,  0.25, 'CLAY'\n3.38E-6,  0.439,    0.329,   0.066,  0.05, 'ORGANIC MATERIAL'\n    0.0,  1.0,      0.0,     0.0,    0.60, 'WATER'\n1.41E-4,  0.20,     0.170,   0.006,  0.07, 'BEDROCK'\n1.41E-5,  0.421,    0.283,   0.028,  0.25, 'OTHER(land-ice)'\n9.74E-7,  0.468,    0.454,   0.030,  0.60, 'PLAYA'\n1.41E-4,  0.200,    0.170,   0.006,  0.52, 'LAVA'\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'WHITE SAND'\n"
  },
  {
    "path": "src/template/HYDRO/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = \"./DOMAIN/geo_em.d01.nc\"\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = \"./DOMAIN/Fulldom_hires.nc\"\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = \"./DOMAIN/hydro2dtbl.nc\"\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = \"./DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata.nc\"\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = 'RESTART/HYDRO_RST.2011-08-26_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 120\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 0\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 4\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 0\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 1                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 10\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded,\n! 5=Bypass channel routing (only active for UDMP=1 and reach configuration)\nchannel_option = 3\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\n!route_link_f = \"./DOMAIN/Route_Link.nc\"\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .FALSE.\n\n! Switch to activate channel-loss option (0=no, 1=yes) [Requires Kchan in RouteLink]\n! channel_loss_option = 0\n\n! Lake / Reservoir options (0=lakes off, 1=level pool (typical default),\n!                           2=passthrough, 3=reservoir DA [see &reservoir_nlist below])\nlake_option = 1\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = \"./DOMAIN/LAKEPARM.nc\"\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through,\n! 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 1\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n! Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\ngwbasmskfil = \"./DOMAIN/GWBASINS.nc\"\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = \"./DOMAIN/GWBUCKPARM.nc\"\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 0\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\n!udmap_file = \"./DOMAIN/spatialweights.nc\"\n\n/\n\n&reservoir_nlist\n\n! Specify the reservoir parameter file\nreservoir_parameter_file = \"./DOMAIN/persistence_parm.nc\"\n\n! If using USGS persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usgs = .FALSE.\n\n! Specify the path to the timeslice files to be used by USGS reservoirs\nreservoir_usgs_timeslice_path = \"./usgs_timeslices/\"\n\n! If using USACE persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usace = .FALSE.\n\n! Specify the path to the timeslice files to be used by USACE reservoirs\nreservoir_usace_timeslice_path = \"./usace_timeslices/\"\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 24\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day). Set to 3600 for standard and extended AnA simulations.\n! Set to 1000000000 for short range and medium range forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC forecast reservoirs, set to True. (default=.FALSE.)\nreservoir_rfc_forecasts = .FALSE.\n\n! Specify the path to the RFC time series files to be used by reservoirs\nreservoir_rfc_forecasts_time_series_path = \"./rfc_timeseries/\"\n\n! Specify lookback hours to read reservoir RFC forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = \"./nudgingTimeSliceObs/\"\n\nnudgingParamFile = \"DOMAIN/nudgingParams.nc\"\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\n!nudgingLastObsFile = '/a/nonexistent/file/gives/nudging/cold/start'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .FALSE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 960\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = -960\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 8\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .FALSE.\n\n/\n"
  },
  {
    "path": "src/template/Noah/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_CONSTANTS_FILE = \"DOMAIN/wrfinput_d01.nc\"\nINDIR  = \"./FORCING\"\nOUTDIR = \".\"\n\nSTART_YEAR   = 2013\nSTART_MONTH  = 09\nSTART_DAY    = 11\nSTART_HOUR   = 00\nSTART_MIN    = 00\n\n! Specification of the land surface model restart file\n! Comment out the option if not initializing from a restart file\nRESTART_FILENAME_REQUESTED = \"RESTART/RESTART.2011082600_DOMAIN1\"\n\n! Specification of simulation length in hours OR days\n! KDAY = 7 ! This option is deprecated and may be removed in a future version\nKHOUR = 24\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only\nRESTART_FREQUENCY_HOURS = 24\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nZSOIL(1) = -0.10\nZSOIL(2) = -0.40\nZSOIL(3) = -1.00\nZSOIL(4) = -2.00\n\n! Forcing data measurement heights\nZLVL = 2.0       ! for temp and humidity\nZLVL_WIND = 10.0 ! for wind variables\n\nIZ0TLND = 0\nSFCDIF_OPTION = 0\nUPDATE_SNOW_FROM_FORCING = .FALSE.\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ spec. precip.,\n!    6=HRLDAS-hr format w/ spec. precip., 7=WRF w/ spec. precip.,\nFORC_TYP = 1\n\n/\n"
  },
  {
    "path": "src/template/NoahMP/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = \"./DOMAIN/wrfinput_d01.nc\"\nINDIR = \"./FORCING\"\nSPATIAL_FILENAME = \"./DOMAIN/soil_properties.nc\"\nOUTDIR = \"./\"\n\nSTART_YEAR  = 2011\nSTART_MONTH = 08\nSTART_DAY   = 26\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\n! Specification of the land surface model restart file\n! Comment out the option if not initializing from a restart file\nRESTART_FILENAME_REQUESTED = \"RESTART/RESTART.2011082600_DOMAIN1\"\n\n! Specification of simulation length in hours OR days\n! KDAY = 7 ! This option is deprecated and may be removed in a future version\nKHOUR = 24\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 2\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only\nRESTART_FREQUENCY_HOURS = 24\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n! Forcing input variable names\nforcing_name_T = \"T2D\"\nforcing_name_Q = \"Q2D\"\nforcing_name_U = \"U2D\"\nforcing_name_V = \"V2D\"\nforcing_name_P = \"PSFC\"\nforcing_name_LW = \"LWDOWN\"\nforcing_name_SW = \"SWDOWN\"\nforcing_name_PR = \"RAINRATE\"\nforcing_name_SN = \"\"\nforcing_name_LF = \"LQFRAC\"\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ spec. precip.,\n!    6=HRLDAS-hr format w/ spec. precip., 7=WRF w/ spec. precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 1\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_250m.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_250m_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_ASM.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 3\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 3600 \n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 1\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/analysis_assim_extended/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_250m.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 240\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_250m_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/analysis_assim_extended/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_ASM.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 28\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 3600 \n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 4\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/analysis_assim_long_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_1km.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_1km_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/analysis_assim_long_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_LongRange.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 3\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600\n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 3600\n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 1\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/hi_analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-08-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/Route_Link.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .FALSE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-08-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/hi_analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_properties.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 08\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018080100_DOMAIN1'\n\n !KDAY = 1\n KHOUR = 3\n\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 2\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 3600 \n\n RESTART_FREQUENCY_HOURS = 1\n\n SPLIT_OUTPUT_COUNT = 1\n\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ZLVL = 10.0\n\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/hi_short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-08-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = -99999\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/Route_Link.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .FALSE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-08-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/hi_short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_properties.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 08\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018080100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 60\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 2\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 3600 \n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 600\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/long_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_1km.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 360\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 4\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_1km_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/long_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_LongRange.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n ! KDAY = 1\n KHOUR = 720 \n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 10800\n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 86400\n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 6000\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/medium_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_250m.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 180\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 3\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_250m_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/medium_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_ASM.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 240\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 10800 \n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 6000\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_250m.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_250m_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0/short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_ASM.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 18\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 3600 \n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 600\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_250m.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_250m_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_ASM.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 3\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 10800\n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 1\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/analysis_assim_extended/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_250m.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 240\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_250m_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/analysis_assim_extended/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_ASM.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 28\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 10800\n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 4\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/analysis_assim_long_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_1km.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_1km_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/analysis_assim_long_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_LongRange.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 3\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600\n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 3600\n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 1\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/long_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_1km.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 360\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 4\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_1km_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/long_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_LongRange.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n ! KDAY = 1\n KHOUR = 720 \n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 10800\n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 86400\n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 6000\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/medium_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_250m.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 180\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 3\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_250m_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/medium_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_ASM.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 240\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 86400\n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 6000\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: 'geo_em.d01.nc')\nGEO_STATIC_FLNM = './DOMAIN/geo_em.d01_1km.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: 'Fulldom_hires.nc')\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_hires_netcdf_250m.nc'\n\n! Specify the spatial hydro parameters file (e.g.: 'hydro2dtbl.nc')\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/HYDRO_TBL_2D.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: 'GEOGRID_LDASOUT_Spatial_Metadata.nc')\nLAND_SPATIAL_META_FLNM = './DOMAIN/WRF_Hydro_NWM_geospatial_data_template_land_GIS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-06-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression, \n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: 'Route_Link.nc')\nroute_link_f = './DOMAIN/RouteLink_NHDPLUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: 'LAKEPARM.nc').\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_NHDPLUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through)\nGWBASESWCRT = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: 'GWBASINS.nc')\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: 'GWBUCKPARM.nc')\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS.nc'\n\n! User defined mapping, such NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: 'spatialweights.nc')\nudmap_file = './DOMAIN/spatialweights_250m_all_basins.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the 'timeslice' observation files.\ntimeSlicePath = './nudgingTimeSliceObs/'\n\nnudgingParamFile = './DOMAIN/nudgingParams.nc'\n\n! Nudging restart file = 'nudgingLastObsFile'\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc'\n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for \n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default. \n! This option instead persists the bias after the last observation. \npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at \n! model init time (=t0)?\n! FALSE = window ends at model time (moving), \n! TRUE = window ends at init=t0(fcst) time. \n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: 'No constructive interference in bias correction?', Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.0_reforecasts/short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\n HRLDAS_SETUP_FILE = './DOMAIN/wrfinput_d01_1km.nc'\n INDIR = './forcing'\n SPATIAL_FILENAME = './DOMAIN/soil_veg_properties_ASM.nc'\n OUTDIR = './'\n\n START_YEAR  = 2018\n START_MONTH = 06\n START_DAY   = 01\n START_HOUR  = 00\n START_MIN   = 00\n\n RESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018060100_DOMAIN1'\n\n ! Specification of simulation length in days OR hours\n !KDAY = 1\n KHOUR = 18\n\n ! Physics options (see the documentation for details)\n DYNAMIC_VEG_OPTION                = 4\n CANOPY_STOMATAL_RESISTANCE_OPTION = 1\n BTR_OPTION                        = 1\n RUNOFF_OPTION                     = 3\n SURFACE_DRAG_OPTION               = 1\n FROZEN_SOIL_OPTION                = 1\n SUPERCOOLED_WATER_OPTION          = 1\n RADIATIVE_TRANSFER_OPTION         = 3\n SNOW_ALBEDO_OPTION                = 1\n PCP_PARTITION_OPTION              = 1\n TBOT_OPTION                       = 2\n TEMP_TIME_SCHEME_OPTION           = 3\n GLACIER_OPTION                    = 2\n SURFACE_RESISTANCE_OPTION         = 4\n\n ! Timesteps in units of seconds\n FORCING_TIMESTEP = 3600 \n NOAH_TIMESTEP    = 3600 \n OUTPUT_TIMESTEP  = 86400\n\n ! Land surface model restart file write frequency\n RESTART_FREQUENCY_HOURS = 600\n\n ! Split output after split_output_count output times.\n SPLIT_OUTPUT_COUNT = 1\n\n ! Soil layer specification\n NSOIL=4\n soil_thick_input(1) = 0.10\n soil_thick_input(2) = 0.30\n soil_thick_input(3) = 0.60\n soil_thick_input(4) = 1.00\n\n ! Forcing data measurement height for winds, temp, humidity\n ZLVL = 10.0\n\n ! Restart file format options\n rst_bi_in = 0      !0: use netcdf input restart file\n                    !1: use parallel io for reading multiple restart files (1 per core)\n rst_bi_out = 0     !0: use netcdf output restart file\n                    !1: use parallel io for outputting multiple restart files (1 per core)\n/\n\n&WRF_HYDRO_OFFLINE\n\n ! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF, \n !                                 4=Idealized, 5=Ideal w/ spec. precip, \n !                                 6=HRLDAS-hr format w/ spec. precip,\n !                                 7=WRF w/ spec. precip \n FORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-10-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_AnA.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 24\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 10\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018100100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/analysis_assim_extended/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-10-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 240\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_Extended_AnA.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .false.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .false.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 24\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nRESERVOIR_OBSERVATION_UPDATE_TIME_INTERVAL_SECONDS = 3600 \n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/analysis_assim_extended/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 10\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018100100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 28\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 4\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/analysis_assim_longrange/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_LongRange.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2018-10-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_LongRange.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2018-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/analysis_assim_longrange/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_LongRange.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 10\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2018100100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/hi_analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_HI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_HI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_HI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_HI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-08-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 15\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_HI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .FALSE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_HI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_HI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_HI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_HI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-08-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/hi_analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_HI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_HI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 08\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018080100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 900\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/hi_short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_HI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_HI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_HI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_HI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-08-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = -99999\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 15\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_HI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .FALSE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_HI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_HI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_HI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_HI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2019-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/hi_short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_HI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_HI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 08\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018080100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 48\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 900\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/long_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_LongRange.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2018-10-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 360\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 4\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_LongRange.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2018-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/long_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_LongRange.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 10\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2018100100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 720\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 10800\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 86400\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 6000\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/medium_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-10-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 3\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_Medium_Range.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 24\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 1000000000\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/medium_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 10\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018100100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 240\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 10800\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 6000\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/pr_analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_PRVI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_PRVI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_PRVI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_PRVI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-08-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_PRVI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_PRVI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_PRVI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_PRVI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_PRVI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/pr_analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_PRVI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_PRVI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 08\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018080100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/pr_short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_PRVI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_PRVI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_PRVI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_PRVI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-08-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = -99999\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_PRVI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_PRVI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_PRVI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_PRVI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_PRVI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/pr_short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_PRVI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_PRVI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 08\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018080100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 48\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2018-10-01_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_Short_Range.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 24\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 1000000000\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2018-06-01_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v2.1/short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2018\nSTART_MONTH = 10\nSTART_DAY   = 01\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2018100100_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 18\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 3\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_AK.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_AK_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_AK_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_AK.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2019-08-18_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_AK.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_AK.nc'\n\n! Specify the reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_GDL_AK.nc'\n\n! If using USGS persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usgs = .FALSE.\n\n! Specify the path to the timeslice files to be used by USGS reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usace = .FALSE.\n\n! Specify the path to the timeslice files to be used by USACE reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day). Set to 3600 for standard and extended AnA simulations.\n! Set to 1000000000 for short range and medium range forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC forecast reservoirs, set to True. (default=.FALSE.)\nreservoir_rfc_forecasts = .FALSE.\n\n! Specify the path to the RFC time series files to be used by reservoirs\nreservoir_rfc_forecasts_time_series_path = './gdl_files/'\n\n! Specify lookback hours to read reservoir RFC forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_AK_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_AK_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_AK.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2019-08-18_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_AK.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_AK_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2019\nSTART_MONTH = 08\nSTART_DAY   = 18\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2019081800_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 1   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_analysis_assim_extended/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_AK.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_AK_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_AK_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_AK.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2019-08-18_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 240\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_AK.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_AK.nc'\n\n! Specify the reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_GDL_AK.nc'\n\n! If using USGS persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usgs = .FALSE.\n\n! Specify the path to the timeslice files to be used by USGS reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usace = .FALSE.\n\n! Specify the path to the timeslice files to be used by USACE reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day). Set to 3600 for standard and extended AnA simulations.\n! Set to 1000000000 for short range and medium range forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC forecast reservoirs, set to True. (default=.FALSE.)\nreservoir_rfc_forecasts = .FALSE.\n\n! Specify the path to the RFC time series files to be used by reservoirs\nreservoir_rfc_forecasts_time_series_path = './gdl_files/'\n\n! Specify lookback hours to read reservoir RFC forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_AK_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_AK_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_AK.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2019-08-18_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_analysis_assim_extended/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_AK.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_AK_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2019\nSTART_MONTH = 08\nSTART_DAY   = 18\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2019081800_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 32\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 4\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 1   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_analysis_assim_extended_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_AK.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_AK_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_AK_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_AK.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2019-08-18_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 240\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_AK.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_AK.nc'\n\n! Specify the reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_GDL_AK.nc'\n\n! If using USGS persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usgs = .FALSE.\n\n! Specify the path to the timeslice files to be used by USGS reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usace = .FALSE.\n\n! Specify the path to the timeslice files to be used by USACE reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day). Set to 3600 for standard and extended AnA simulations.\n! Set to 1000000000 for short range and medium range forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC forecast reservoirs, set to True. (default=.FALSE.)\nreservoir_rfc_forecasts = .FALSE.\n\n! Specify the path to the RFC time series files to be used by reservoirs\nreservoir_rfc_forecasts_time_series_path = './gdl_files/'\n\n! Specify lookback hours to read reservoir RFC forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_AK_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_AK_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_AK.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2019-08-18_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_analysis_assim_extended_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_AK.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_AK_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2019\nSTART_MONTH = 08\nSTART_DAY   = 18\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2019081800_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 32\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 4\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 1   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_analysis_assim_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_AK.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_AK_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_AK_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_AK.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2019-08-18_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_AK.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_AK.nc'\n\n! Specify the reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_GDL_AK.nc'\n\n! If using USGS persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usgs = .FALSE.\n\n! Specify the path to the timeslice files to be used by USGS reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usace = .FALSE.\n\n! Specify the path to the timeslice files to be used by USACE reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day). Set to 3600 for standard and extended AnA simulations.\n! Set to 1000000000 for short range and medium range forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC forecast reservoirs, set to True. (default=.FALSE.)\nreservoir_rfc_forecasts = .FALSE.\n\n! Specify the path to the RFC time series files to be used by reservoirs\nreservoir_rfc_forecasts_time_series_path = './gdl_files/'\n\n! Specify lookback hours to read reservoir RFC forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_AK_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_AK_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/'\n\nnudgingParamFile = './DOMAIN/nudgingParams_AK.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2019-08-18_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_analysis_assim_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_AK.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_AK_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2019\nSTART_MONTH = 08\nSTART_DAY   = 18\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2019081800_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 1   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_medium_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_AK.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_AK_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_AK_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_AK.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2019-08-18_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 3\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_AK.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_AK.nc'\n\n! Specify the reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_GDL_AK.nc'\n\n! If using USGS persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usgs = .FALSE.\n\n! Specify the path to the timeslice files to be used by USGS reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usace = .FALSE.\n\n! Specify the path to the timeslice files to be used by USACE reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day). Set to 3600 for standard and extended AnA simulations.\n! Set to 1000000000 for short range and medium range forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC forecast reservoirs, set to True. (default=.FALSE.)\nreservoir_rfc_forecasts = .TRUE.\n\n! Specify the path to the RFC time series files to be used by reservoirs\nreservoir_rfc_forecasts_time_series_path = './gdl_files/'\n\n! Specify lookback hours to read reservoir RFC forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_AK_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_AK_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_AK.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2019-08-18_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_medium_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_AK.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_AK_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2019\nSTART_MONTH = 08\nSTART_DAY   = 18\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2019081800_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 240\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 10800\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 6000\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 1   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_medium_range_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_AK.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_AK_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_AK_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_AK.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2019-08-18_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 180\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 3\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_AK.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_AK.nc'\n\n! Specify the reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_GDL_AK.nc'\n\n! If using USGS persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usgs = .FALSE.\n\n! Specify the path to the timeslice files to be used by USGS reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usace = .FALSE.\n\n! Specify the path to the timeslice files to be used by USACE reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day). Set to 3600 for standard and extended AnA simulations.\n! Set to 1000000000 for short range and medium range forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC forecast reservoirs, set to True. (default=.FALSE.)\nreservoir_rfc_forecasts = .TRUE.\n\n! Specify the path to the RFC time series files to be used by reservoirs\nreservoir_rfc_forecasts_time_series_path = './gdl_files/'\n\n! Specify lookback hours to read reservoir RFC forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_AK_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_AK_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_AK.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2019-08-18_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_medium_range_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_AK.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_AK_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2019\nSTART_MONTH = 08\nSTART_DAY   = 18\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2019081800_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 240\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 10800\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 6000\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 1   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_AK.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_AK_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_AK_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_AK.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2019-08-18_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_AK.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_AK.nc'\n\n! Specify the reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_GDL_AK.nc'\n\n! If using USGS persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usgs = .FALSE.\n\n! Specify the path to the timeslice files to be used by USGS reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE persistence reservoirs, set to True. (default=.FALSE.)\nreservoir_persistence_usace = .FALSE.\n\n! Specify the path to the timeslice files to be used by USACE reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day). Set to 3600 for standard and extended AnA simulations.\n! Set to 1000000000 for short range and medium range forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC forecast reservoirs, set to True. (default=.FALSE.)\nreservoir_rfc_forecasts = .TRUE.\n\n! Specify the path to the RFC time series files to be used by reservoirs\nreservoir_rfc_forecasts_time_series_path = './gdl_files/'\n\n! Specify lookback hours to read reservoir RFC forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_AK_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_AK_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_AK.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2019-08-18_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/ak_short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_AK.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_AK_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2019\nSTART_MONTH = 08\nSTART_DAY   = 18\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2019081800_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 15\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 1   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_AnA.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_extended/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 240\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_Extended_AnA.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_extended/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 28\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 4\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_extended_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 240\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_Extended_AnA.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/'\n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_extended_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 28\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 4\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_longrange/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_LongRange.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_LongRange.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_longrange/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_LongRange.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 12\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_longrange_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_LongRange.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_LongRange.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/'\n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_longrange_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_LongRange.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 12\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_AnA.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 3600\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/'\n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/analysis_assim_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/hi_analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_HI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_HI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_HI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_HI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-03-09_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 15\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_HI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_HI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_HI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_HI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_HI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-03-09_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/hi_analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_HI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_HI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 03\nSTART_DAY   = 09\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021030900_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 900\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/hi_analysis_assim_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_HI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_HI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_HI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_HI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-03-09_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 15\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_HI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_HI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_HI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_HI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/'\n\nnudgingParamFile = './DOMAIN/nudgingParams_HI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-03-09_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/hi_analysis_assim_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_HI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_HI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 03\nSTART_DAY   = 09\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021030900_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 900\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/hi_short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_HI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_HI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_HI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_HI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-03-09_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = -99999\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 15\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_HI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_HI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_HI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_HI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_HI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-03-09_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/hi_short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_HI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_HI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 03\nSTART_DAY   = 09\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021030900_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 48\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 900\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/hi_short_range_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_HI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_HI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_HI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_HI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-03-09_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = -99999\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 15\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_HI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_HI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_HI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_HI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/'\n\nnudgingParamFile = './DOMAIN/nudgingParams_HI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-03-09_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/hi_short_range_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_HI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_HI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 03\nSTART_DAY   = 09\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021030900_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 48\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 9  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 900\nNOAH_TIMESTEP    = 900\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/long_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_LongRange.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_LongRange.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART_LR/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 0\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 360\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 4\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 0             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 1000.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 1\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 0\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 0\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 0\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_LongRange.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_LongRange.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART_LR/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/long_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_LongRange.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART_LR/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 720\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 10800\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 86400\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 6000\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/medium_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 3\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_Medium_Range.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 1000000000\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/medium_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 240\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 10800\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 6000\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/medium_range_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 180\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 3\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 0\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_Medium_Range.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 1000000000\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/'\n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/medium_range_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 240\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 10800\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 6000\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/pr_analysis_assim/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_PRVI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_PRVI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_PRVI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_PRVI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2022-02-04_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_PRVI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_PRVI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_PRVI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_PRVI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_PRVI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2022-02-04_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/pr_analysis_assim/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_PRVI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_PRVI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2022\nSTART_MONTH = 02\nSTART_DAY   = 04\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2022020400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/pr_analysis_assim_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_PRVI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_PRVI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_PRVI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_PRVI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2022-02-04_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 60\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 1\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_PRVI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_PRVI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_PRVI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_PRVI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_PRVI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2022-02-04_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .TRUE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .FALSE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 3\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/pr_analysis_assim_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_PRVI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_PRVI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2022\nSTART_MONTH = 02\nSTART_DAY   = 04\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2022020400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 3\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 1\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/pr_short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_PRVI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_PRVI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_PRVI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_PRVI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2022-02-04_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = -99999\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_PRVI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_PRVI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_PRVI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_PRVI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_PRVI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2022-02-04_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/pr_short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_PRVI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_PRVI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2022\nSTART_MONTH = 02\nSTART_DAY   = 04\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2022020400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 48\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/pr_short_range_no_da/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_PRVI.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_PRVI_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_PRVI_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_PRVI.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2022-02-04_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = -99999\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 100.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 10\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 6\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_PRVI.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_PRVI.nc'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 1\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_PRVI_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_PRVI_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './doesNotExistPath/'\n\nnudgingParamFile = './DOMAIN/nudgingParams_PRVI.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2022-02-04_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/pr_short_range_no_da/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_PRVI.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_PRVI_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2022\nSTART_MONTH = 02\nSTART_DAY   = 04\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2022020400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 48\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 9\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/short_range/hydro.namelist",
    "content": "&HYDRO_nlist\n!!!! ---------------------- SYSTEM COUPLING ----------------------- !!!!\n\n! Specify what is being coupled:  1=HRLDAS (offline Noah-LSM), 2=WRF, 3=NASA/LIS, 4=CLM\nsys_cpl = 1\n\n!!!! ------------------- MODEL INPUT DATA FILES ------------------- !!!!\n\n! Specify land surface model gridded input data file (e.g.: \"geo_em.d01.nc\")\nGEO_STATIC_FLNM = './DOMAIN/geo_em_CONUS.nc'\n\n! Specify the high-resolution routing terrain input data file (e.g.: \"Fulldom_hires.nc\")\nGEO_FINEGRID_FLNM = './DOMAIN/Fulldom_CONUS_FullRouting.nc'\n\n! Specify the spatial hydro parameters file (e.g.: \"hydro2dtbl.nc\")\n! If you specify a filename and the file does not exist, it will be created for you.\nHYDROTBL_F = './DOMAIN/hydro2dtbl_CONUS_FullRouting.nc'\n\n! Specify spatial metadata file for land surface grid. (e.g.: \"GEOGRID_LDASOUT_Spatial_Metadata.nc\")\nLAND_SPATIAL_META_FLNM = './DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_CONUS.nc'\n\n! Specify the name of the restart file if starting from restart...comment out with '!' if not...\nRESTART_FILE  = './RESTART/HYDRO_RST.2021-10-24_00:00_DOMAIN1'\n\n!!!! --------------------- MODEL SETUP OPTIONS -------------------- !!!!\n\n! Specify the domain or nest number identifier...(integer)\nIGRID = 1\n\n! Specify the restart file write frequency...(minutes)\n! A value of -99999 will output restarts on the first day of the month only.\nrst_dt = 999990\n\n! Reset the LSM soil states from the high-res routing restart file (1=overwrite, 0=no overwrite)\n! NOTE: Only turn this option on if overland or subsurface rotuing is active!\nrst_typ = 1\n\n! Restart file format control\nrst_bi_in = 0       !0: use netcdf input restart file (default)\n                    !1: use parallel io for reading multiple restart files, 1 per core\nrst_bi_out = 0      !0: use netcdf output restart file (default)\n                    !1: use parallel io for outputting multiple restart files, 1 per core\n\n! Restart switch to set restart accumulation variables to 0 (0=no reset, 1=yes reset to 0.0)\nRSTRT_SWC = 1\n\n! Specify baseflow/bucket model initialization...(0=cold start from table, 1=restart file)\nGW_RESTART = 1\n\n!!!! -------------------- MODEL OUTPUT CONTROL -------------------- !!!!\n\n! Specify the output file write frequency...(minutes)\nout_dt = 60\n\n! Specify the number of output times to be contained within each output history file...(integer)\n!   SET = 1 WHEN RUNNING CHANNEL ROUTING ONLY/CALIBRATION SIMS!!!\n!   SET = 1 WHEN RUNNING COUPLED TO WRF!!!\nSPLIT_OUTPUT_COUNT = 1\n\n! Specify the minimum stream order to output to netcdf point file...(integer)\n! Note: lower value of stream order produces more output.\norder_to_write = 1\n\n! Flag to turn on/off new I/O routines: 0 = deprecated output routines (use when running with Noah LSM),\n! 1 = with scale/offset/compression, ! 2 = with scale/offset/NO compression,\n! 3 = compression only, 4 = no scale/offset/compression (default)\nio_form_outputs = 2\n\n! Realtime run configuration option:\n! 0=all (default), 1=analysis, 2=short-range, 3=medium-range, 4=long-range, 5=retrospective,\n! 6=diagnostic (includes all of 1-4 outputs combined)\nio_config_outputs = 2\n\n! Option to write output files at time 0 (restart cold start time): 0=no, 1=yes (default)\nt0OutputFlag = 1\n\n! Options to output channel & bucket influxes. Only active for UDMP_OPT=1.\n! Nonzero choice requires that out_dt above matches NOAH_TIMESTEP in namelist.hrldas.\n! 0=None (default), 1=channel influxes (qSfcLatRunoff, qBucket)\n! 2=channel+bucket fluxes    (qSfcLatRunoff, qBucket, qBtmVertRunoff_toBucket)\n! 3=channel accumulations    (accSfcLatRunoff, accBucket) *** NOT TESTED ***\noutput_channelBucket_influx = 2\n\n! Output netcdf file control\nCHRTOUT_DOMAIN = 1           ! Netcdf point timeseries output at all channel points (1d)\n                             !      0 = no output, 1 = output\nCHANOBS_DOMAIN = 0           ! Netcdf point timeseries at forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output at forecast points or gage points.\nCHRTOUT_GRID = 0             ! Netcdf grid of channel streamflow values (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: Not available with reach-based routing\nLSMOUT_DOMAIN = 0            ! Netcdf grid of variables passed between LSM and routing components (2d)\n                             !      0 = no output, 1 = output\n                             !      NOTE: No scale_factor/add_offset available\nRTOUT_DOMAIN = 1             ! Netcdf grid of terrain routing variables on routing grid (2d)\n                             !      0 = no output, 1 = output\noutput_gw = 0                ! Netcdf GW output\n                             !      0 = no output, 1 = output\noutlake  = 1                 ! Netcdf grid of lake values (1d)\n                             !      0 = no output, 1 = output\nfrxst_pts_out = 0            ! ASCII text file of forecast points or gage points (defined in Routelink)\n                             !      0 = no output, 1 = output\n\n!!!! ------------ PHYSICS OPTIONS AND RELATED SETTINGS ------------ !!!!\n\n! Specify the number of soil layers (integer) and the depth of the bottom of each layer... (meters)\n! Notes: In Version 1 of WRF-Hydro these must be the same as in the namelist.input file.\n!      Future versions will permit this to be different.\nNSOIL=4\nZSOIL8(1) = -0.10\nZSOIL8(2) = -0.40\nZSOIL8(3) = -1.00\nZSOIL8(4) = -2.00\n\n! Specify the grid spacing of the terrain routing grid...(meters)\nDXRT = 250.0\n\n! Specify the integer multiple between the land model grid and the terrain routing grid...(integer)\nAGGFACTRT = 4\n\n! Specify the channel routing model timestep...(seconds)\nDTRT_CH = 300\n\n! Specify the terrain routing model timestep...(seconds)\nDTRT_TER = 10\n\n! Switch to activate subsurface routing...(0=no, 1=yes)\nSUBRTSWCRT = 1\n\n! Switch to activate surface overland flow routing...(0=no, 1=yes)\nOVRTSWCRT = 1\n\n! Specify overland flow routing option: 1=Seepest Descent (D8) 2=CASC2D (not active)\n! NOTE: Currently subsurface flow is only steepest descent\nrt_option = 1\n\n! Specify whether to adjust overland flow parameters based on imperviousness\nimperv_adj = 1\n\n! Switch to activate channel routing...(0=no, 1=yes)\nCHANRTSWCRT = 1\n\n! Specify channel routing option: 1=Muskingam-reach, 2=Musk.-Cunge-reach, 3=Diff.Wave-gridded\nchannel_option = 2\n\n! Specify the reach file for reach-based routing options (e.g.: \"Route_Link.nc\")\nroute_link_f = './DOMAIN/RouteLink_CONUS.nc'\n\n! If using channel_option=2, activate the compound channel formulation? (Default=.FALSE.)\n! This option is currently only supported if using reach-based routing with UDMP=1.\ncompound_channel = .TRUE.\n\n! Specify the lake parameter file (e.g.: \"LAKEPARM.nc\").\n! Note REQUIRED if lakes are on.\nroute_lake_f = './DOMAIN/LAKEPARM_CONUS.nc'\n\n! Specify the Reservoir parameter file\nreservoir_parameter_file = './DOMAIN/reservoir_index_Short_Range.nc'\n\n! If using USGS Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usgs = .true.\n\n! Specify the path to the USGS Timeslice files to be used by Reservoirs\nreservoir_usgs_timeslice_path = './usgs_timeslices/'\n\n! If using USACE Persistence Reservoirs, set to True. (Default=.FALSE.)\nreservoir_persistence_usace = .true.\n\n! Specify the path to the USACE Timeslice files to be used by Reservoirs\nreservoir_usace_timeslice_path = './usace_timeslices/'\n\n! Specify lookback hours to read reservoir observation data\nreservoir_observation_lookback_hours = 48\n\n! Specify update time interval in seconds to read new reservoir observation data\n! The default is 86400 (seconds per day).  Set to 3600 for Standard and Extended AnA simulations.\n! Set to 1000000000 for Short-Range and Medium-Range Forecasts.\nreservoir_observation_update_time_interval_seconds = 1000000000\n\n! If using RFC Forecast Reservoirs, set to True. (Default=.FALSE.)\nreservoir_rfc_forecasts = .true.\n\n! Specify lookback hours to read Reservoir RFC Forecasts\nreservoir_rfc_forecasts_lookback_hours = 28\n\n! Specify the path to the RFC Time Series files to be used by Reservoirs\nreservoir_rfc_forecasts_time_series_path = './rfc_timeseries/'\n\n! Switch to activate baseflow bucket model...(0=none, 1=exp. bucket, 2=pass-through, 4=exp. bucket with area normalized parameters)\n! Option 4 is currently only supported if using reach-based routing with UDMP=1.\nGWBASESWCRT = 4\n\n! Switch to activate bucket model loss (0=no, 1=yes)\n! This option is currently only supported if using reach-based routing with UDMP=1.\nbucket_loss = 0\n\n! Groundwater/baseflow 2d mask specified on land surface model grid (e.g.: \"GWBASINS.nc\")\n!Note: Only required if baseflow  model is active (1 or 2) and UDMP_OPT=0.\n!gwbasmskfil = './DOMAIN/GWBASINS.nc'\n\n! Groundwater bucket parameter file (e.g.: \"GWBUCKPARM.nc\")\nGWBUCKPARM_file = './DOMAIN/GWBUCKPARM_CONUS_FullRouting.nc'\n\n! User defined mapping, such as NHDPlus: 0=no (default), 1=yes\nUDMP_OPT = 1\n\n! If on, specify the user-defined mapping file (e.g.: \"spatialweights.nc\")\nudmap_file = './DOMAIN/spatialweights_CONUS_FullRouting.nc'\n\n/\n\n&NUDGING_nlist\n\n! Path to the \"timeslice\" observation files.\ntimeSlicePath = './nudgingTimeSliceObs/' \n\nnudgingParamFile = './DOMAIN/nudgingParams_CONUS.nc'\n\n! Nudging restart file = \"nudgingLastObsFile\"\n! nudgingLastObsFile defaults to '', which will look for nudgingLastObs.YYYY-mm-dd_HH:MM:SS.nc\n!   **AT THE INITALIZATION TIME OF THE RUN**. Set to a missing file to use no restart.\nnudgingLastObsFile = './RESTART/nudgingLastObs.2021-10-24_00:00:00.nc' \n\n!! Parallel input of nudging timeslice observation files?\nreadTimesliceParallel = .TRUE.\n\n! temporalPersistence defaults to true, only runs if necessary params present.\ntemporalPersistence = .TRUE.\n\n! The total number of last (obs, modeled) pairs to save in nudgingLastObs for\n! removal of bias. This is the maximum array length. (This option is active when persistBias=FALSE)\n! (Default=960=10days @15min obs resolution, if all the obs are present and longer if not.)\nnLastObs = 480\n\n! If using temporalPersistence the last observation persists by default.\n! This option instead persists the bias after the last observation.\npersistBias = .FALSE.\n\n! AnA (FALSE)  vs Forecast (TRUE) bias persistence.\n! If persistBias: Does the window for calculating the bias end at\n! model init time (=t0)?\n! FALSE = window ends at model time (moving),\n! TRUE = window ends at init=t0(fcst) time.\n! (If commented out, Default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nbiasWindowBeforeT0 = .TRUE.\n\n! If persistBias: Only use this many last (obs, modeled) pairs. (If Commented out, Default=-1*nLastObs)\n! > 0: apply an age-based filter, units=hours.\n! = 0: apply no additional filter, use all available/usable obs.\n! < 0: apply an count-based filter, units=count\nmaxAgePairsBiasPersist = 24\n\n! If persistBias: The minimum number of last (obs, modeled) pairs, with age less than\n! maxAgePairsBiasPersist, required to apply a bias correction. (default=8)\nminNumPairsBiasPersist = 1\n\n! If persistBias: give more weight to observations closer in time? (default=FALSE)\ninvDistTimeWeightBias = .TRUE.\n\n! If persistBias: \"No constructive interference in bias correction?\", Reduce the bias adjustment\n! when the model and the bias adjustment have the same sign relative to the modeled flow at t0?\n! (default=FALSE)\n! Note: Perfect restart tests require this option to be .FALSE.\nnoConstInterfBias = .TRUE.\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/namelists/v3.0/short_range/namelist.hrldas",
    "content": "&NOAHLSM_OFFLINE\n\nHRLDAS_SETUP_FILE = './DOMAIN/wrfinput_CONUS.nc'\nINDIR = './forcing'\nSPATIAL_FILENAME = './DOMAIN/soilproperties_CONUS_FullRouting.nc'\nOUTDIR = './'\n\nSTART_YEAR  = 2021\nSTART_MONTH = 10\nSTART_DAY   = 24\nSTART_HOUR  = 00\nSTART_MIN   = 00\n\nRESTART_FILENAME_REQUESTED = './RESTART/RESTART.2021102400_DOMAIN1'\n\n! Specification of simulation length in days OR hours\n! KDAY = 1\nKHOUR = 18\n\n! Physics options (see the documentation for details)\nDYNAMIC_VEG_OPTION                = 4\nCANOPY_STOMATAL_RESISTANCE_OPTION = 1\nBTR_OPTION                        = 1\nRUNOFF_OPTION                     = 7\nSURFACE_DRAG_OPTION               = 1\nFROZEN_SOIL_OPTION                = 1\nSUPERCOOLED_WATER_OPTION          = 1\nRADIATIVE_TRANSFER_OPTION         = 3\nSNOW_ALBEDO_OPTION                = 1\nPCP_PARTITION_OPTION              = 1\nTBOT_OPTION                       = 2\nTEMP_TIME_SCHEME_OPTION           = 3\nGLACIER_OPTION                    = 2\nSURFACE_RESISTANCE_OPTION         = 4\nIMPERV_OPTION                     = 2  !(0->none; 1->total; 2->Alley&Veenhuis; 9->orig)\n\n! Timesteps in units of seconds\nFORCING_TIMESTEP = 3600\nNOAH_TIMESTEP    = 3600\nOUTPUT_TIMESTEP  = 3600\n\n! Land surface model restart file write frequency\n! A value of -99999 will output restarts on the first day of the month only.\nRESTART_FREQUENCY_HOURS = 600\n\n! Split output after split_output_count output times.\nSPLIT_OUTPUT_COUNT = 1\n\n! Soil layer specification\nNSOIL=4\nsoil_thick_input(1) = 0.10\nsoil_thick_input(2) = 0.30\nsoil_thick_input(3) = 0.60\nsoil_thick_input(4) = 1.00\n\n! Forcing data measurement height for winds, temp, humidity\nZLVL = 10.0\n\n! Restart file format options\nrst_bi_in = 0      !0: use netcdf input restart file\n                   !1: use parallel io for reading multiple restart files (1 per core)\nrst_bi_out = 0     !0: use netcdf output restart file\n                   !1: use parallel io for outputting multiple restart files (1 per core)\n\n/\n\n&WRF_HYDRO_OFFLINE\n\n! Specification of forcing data:  1=HRLDAS-hr format, 2=HRLDAS-min format, 3=WRF,\n!    4=Idealized, 5=Idealized w/ Spec. Precip.,\n!    6=HRLDAS-hourly fomat w/ Spec. Precip., 7=WRF w/ Spec. Precip.,\n!    9=Channel-only forcing, see hydro.namelist output_channelBucket_influxes\n!    10=Channel+Bucket only forcing, see hydro.namelist output_channelBucket_influxes\nFORC_TYP = 2\n\n/\n\n&CROCUS_nlist\n  crocus_opt = 0   ! 0 model is off, 1 model is on\n  act_lev = 40     ! 20-40 normal range, 1-50 acceptable\n/\n\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.0/CHANPARM.TBL",
    "content": "Channel Parameters\nStreamOrder\n10,1,  'Bw     HLINK   ChSSlp   MannN'\n1,     1.5,    0.02,    3.0,      0.55\n2,     3.0,    0.02,    1.0,      0.35\n3,     5.0,    0.02,    0.5,      0.15\n4,     10.,    0.03,   0.18,      0.10\n5,     20.,    0.03,   0.05,      0.07\n6,     40.,    0.03,   0.05,      0.05\n7,     60.,    0.03,   0.05,      0.04\n8,     70.,    0.10,   0.05,      0.03\n9,     80.,    0.30,   0.05,      0.02\n10,    100.,    0.30,   0.05,      0.01\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.0/GENPARM.TBL",
    "content": "General Parameters\nSLOPE_DATA\n9\n0.3 \n0.3\n1.0\n0.35\n0.55\n0.8\n0.63\n0.0\n0.0\nSBETA_DATA\n-2.0\nFXEXP_DATA\n2.0\nCSOIL_DATA\n2.00E+6\nSALP_DATA\n2.6\nREFDK_DATA\n2.0E-6\nREFKDT_DATA\n1.0\nFRZK_DATA\n0.15\nZBOT_DATA\n-8.0\nCZIL_DATA\n0.1\nSMLOW_DATA\n0.5\nSMHIGH_DATA\n3.0\nLVCOEF_DATA\n0.5\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.0/HYDRO.TBL",
    "content": "     28 USGS for OV_ROUGH\n   SFC_ROUGH'\n     0.025,    'Urban and Built-Up Land'  \n     0.035,    'Dryland Cropland and Pasture' \n     0.035,    'Irrigated Cropland and Pasture' \n     0.055,    'Mixed Dryland/Irrigated Cropland and Pasture' \n     0.035,    'Cropland/Grassland Mosaic'\n     0.068,    'Cropland/Woodland Mosaic' \n     0.055,    'Grassland' \n     0.055,    'Shrubland' \n     0.055,    'Mixed Shrubland/Grassland' \n     0.055,    'Savanna' \n     0.200,    'Deciduous Broadleaf Forest' \n     0.200,    'Deciduous Needleleaf Forest' \n     0.200,    'Evergreen Broadleaf Forest'\n     0.200,    'Evergreen Needleleaf Forest'  \n     0.200,    'Mixed Forest' \n     0.005,    'Water Bodies' \n     0.070,    'Herbaceous Wetland' \n     0.070,    'Wooded Wetland' \n     0.035,    'Barren or Sparsely Vegetated' \n     0.055,    'Herbaceous Tundra' \n     0.055,    'Wooded Tundra' \n     0.055,    'Mixed Tundra' \n     0.055,    'Bare Ground Tundra' \n     0.010,    'Snow or Ice' \n     0.010,    'Playa' \n     0.100,    'Lava'   \n     0.010,    'White Sand' \n     0.005,    'Non-Ocean Water Bodies'\n19, for SATDK\nSATDK     MAXSMC    REFSMC   WLTSMC  QTZ    '\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'SAND'\n1.41E-5,  0.421,    0.283,   0.028,  0.82, 'LOAMY SAND'\n5.23E-6,  0.434,    0.312,   0.047,  0.60, 'SANDY LOAM'\n2.81E-6,  0.476,    0.360,   0.084,  0.25, 'SILT LOAM'\n2.18E-6,  0.484,    0.347,   0.061,  0.10, 'SILT'\n3.38E-6,  0.439,    0.329,   0.066,  0.40, 'LOAM'\n4.45E-6,  0.404,    0.315,   0.069,  0.60, 'SANDY CLAY LOAM'\n2.03E-6,  0.464,    0.387,   0.120,  0.10, 'SILTY CLAY LOAM'\n2.45E-6,  0.465,    0.382,   0.103,  0.35, 'CLAY LOAM'\n7.22E-6,  0.406,    0.338,   0.100,  0.52, 'SANDY CLAY'\n1.34E-6,  0.468,    0.404,   0.126,  0.10, 'SILTY CLAY'\n9.74E-7,  0.468,    0.412,   0.138,  0.25, 'CLAY'\n3.38E-6,  0.439,    0.329,   0.066,  0.05, 'ORGANIC MATERIAL'\n    0.0,  1.0,      0.0,     0.0,    0.60, 'WATER'\n1.41E-4,  0.20,     0.170,   0.006,  0.07, 'BEDROCK'\n1.41E-5,  0.421,    0.283,   0.028,  0.25, 'OTHER(land-ice)'\n9.74E-7,  0.468,    0.454,   0.030,  0.60, 'PLAYA'\n1.41E-4,  0.200,    0.170,   0.006,  0.52, 'LAVA'\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'WHITE SAND'\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.0/MPTABLE.TBL",
    "content": "&noahmp_usgs_veg_categories\n VEG_DATASET_DESCRIPTION = \"USGS\"\n NVEG = 27\n/\n&noahmp_usgs_parameters\n ! NVEG = 27\n !  1: Urban and Built-Up Land\n !  2: Dryland Cropland and Pasture\n !  3: Irrigated Cropland and Pasture\n !  4: Mixed Dryland/Irrigated Cropland and Pasture\n !  5: Cropland/Grassland Mosaic\n !  6: Cropland/Woodland Mosaic\n !  7: Grassland\n !  8: Shrubland\n !  9: Mixed Shrubland/Grassland\n ! 10: Savanna\n ! 11: Deciduous Broadleaf Forest\n ! 12: Deciduous Needleleaf Forest\n ! 13: Evergreen Broadleaf Forest\n ! 14: Evergreen Needleleaf Forest\n ! 15: Mixed Forest\n ! 16: Water Bodies\n ! 17: Herbaceous Wetland\n ! 18: Wooded Wetland\n ! 19: Barren or Sparsely Vegetated\n ! 20: Herbaceous Tundra\n ! 21: Wooded Tundra\n ! 22: Mixed Tundra\n ! 23: Bare Ground Tundra\n ! 24: Snow or Ice\n ! 25: Playa\n ! 26: Lava\n ! 27: White Sand\n\n ISURBAN   = 1\n ISWATER   = 16\n ISBARREN  = 19\n ISICE     = 24\n EBLFOREST = 13\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1      2      3      4      5      6      7      8      9      10     11     12     13     14     15     16     17     18     19     20     21     22     23     24     25     26    27\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,\n DLEAF =  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,\n Z0MVT =  1.00,  0.15,  0.15,  0.15,  0.14,  0.50,  0.12,  0.06,  0.09,  0.50,  0.80,  0.85,  1.10,  1.09,  0.80,  0.00,  0.12,  0.50,  0.00,  0.10,  0.30,  0.20,  0.03,  0.00,  0.01,  0.00,  0.00,\n HVT   =  15.0,  2.00,  2.00,  2.00,  1.50,  8.00,  1.00,  1.10,  1.10,  10.0,  16.0,  18.0,  20.0,  20.0,  16.0,  0.00,  0.50,  10.0,  0.00,  0.50,  4.00,  2.00,  0.50,  0.00,  0.10,  0.00,  0.00,\n HVB   =  1.00,  0.10,  0.10,  0.10,  0.10,  0.15,  0.05,  0.10,  0.10,  0.10,  11.5,  7.00,  8.00,  8.50,  10.0,  0.00,  0.05,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n DEN   =  0.01,  25.0,  25.0,  25.0,  25.0,  25.0,  100.,  10.0,  10.0,  0.02,  0.10,  0.28,  0.02,  0.28,  0.10,  0.01,  10.0,  0.10,  0.01,  1.00,  1.00,  1.00,  1.00,  0.00,  0.01,  0.01,  0.01,\n RC    =  1.00,  0.08,  0.08,  0.08,  0.08,  0.08,  0.03,  0.12,  0.12,  3.00,  1.40,  1.20,  3.60,  1.20,  1.40,  0.01,  0.10,  1.40,  0.01,  0.30,  0.30,  0.30,  0.30,  0.00,  0.01,  0.01,  0.01,\n MFSNO =  1.00,  3.00,  3.00,  3.00,  3.00,  3.00,  3.00,  3.00,  3.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  3.00,  3.00,  1.00,  3.00,  3.00,  3.00,  3.00,  3.00,  3.00,  3.00,  3.00,  3.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.00,  0.11,  0.11,  0.11,  0.11,  0.11,  0.11,  0.07,  0.10,  0.10,  0.10,  0.07,  0.10,  0.07,  0.10,  0.00,  0.11,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n RHOL_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.35,  0.45,  0.45,  0.45,  0.35,  0.45,  0.35,  0.45,  0.00,  0.58,  0.45,  0.00,  0.45,  0.45,  0.45,  0.45,  0.00,  0.45,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.00,  0.36,  0.36,  0.36,  0.36,  0.36,  0.36,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.00,  0.36,  0.16,  0.00,  0.16,  0.16,  0.16,  0.16,  0.00,  0.16,  0.00,  0.00,\n RHOS_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.00,  0.58,  0.39,  0.00,  0.39,  0.39,  0.39,  0.39,  0.00,  0.39,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.00,  0.07,  0.07,  0.07,  0.07,  0.07,  0.07,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.00,  0.07,  0.05,  0.00,  0.05,  0.05,  0.05,  0.05,  0.00,  0.05,  0.00,  0.00,\n TAUL_NIR=0.00,  0.25,  0.25,  0.25,  0.25,  0.25,  0.25,  0.10,  0.10,  0.25,  0.25,  0.10,  0.25,  0.10,  0.25,  0.00,  0.25,  0.25,  0.00,  0.25,  0.25,  0.25,  0.25,  0.00,  0.25,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.00, 0.220, 0.220, 0.220, 0.220, 0.220, 0.220, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.220, 0.001, 0.000, 0.220, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n TAUS_NIR=0.00, 0.380, 0.380, 0.380, 0.380, 0.380, 0.380, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.380, 0.001, 0.000, 0.380, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n\n XL    = 0.000, -0.30, -0.30, -0.30, -0.30, -0.30, -0.30, 0.010, 0.250, 0.010, 0.250, 0.010, 0.010, 0.010, 0.250, 0.000, -0.30, 0.250, 0.000, -0.30, 0.250, 0.250, 0.250, 0.000, 0.250, 0.000, 0.000,\n CWPVT =  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,\n C3PSN =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n KC25  =  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,\n AKC   =   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,\n KO25  =  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,\n AKO   =   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,\n AVCMX =   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,\n AQE   =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n\n LTOVRC=   0.0,   1.2,   1.2,   1.2,   1.2,  1.30,  0.50,  0.65,  0.70,  0.65,  0.55,   0.2,  0.55,   0.5,   0.5,   0.0,   1.4,   1.4,   0.0,   1.2,   1.3,   1.4,   1.0,   0.0,   1.0,   0.0,   0.0,\n DILEFC=  0.00,  0.50,  0.50,  0.50,  0.35,  0.20,  0.20,  0.20,  0.50,  0.50,  0.60,  1.80,  0.50,  1.20,  0.80,  0.00,  0.40,  0.40,  0.00,  0.40,  0.30,  0.40,  0.30,  0.00,  0.30,  0.00,  0.00,\n DILEFW=  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.20,  0.50,  0.20,  0.20,  4.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.20,  0.20,  0.00,  0.20,  0.00,  0.00,\n RMF25 =  0.00,  1.00,  1.40,  1.45,  1.45,  1.45,  1.80,  0.26,  0.26,  0.80,  3.00,  4.00,  0.65,  3.00,  3.00,  0.00,  3.20,  3.20,  0.00,  3.20,  3.00,  3.00,  3.00,  0.00,  3.00,  0.00,  0.00,\n SLA   =    60,    80,    80,    80,    80,    80,    60,    60,    60,    50,    80,    80,    80,    80,    80,     0,    80,    80,     0,    80,    80,    80,    80,     0,    80,     0,     0,\n FRAGR =  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n TMIN  =     0,   273,   273,   273,   273,   273,   273,   273,   273,   273,   273,   268,   273,   265,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n VCMX25=  0.00,  80.0,  80.0,  80.0,  60.0,  70.0,  40.0,  40.0,  40.0,  40.0,  60.0,  60.0,  60.0,  50.0,  55.0,  0.00,  50.0,  50.0,  0.00,  50.0,  50.0,  50.0,  50.0,  0.00,  50.0,  0.00,  0.00,\n TDLEF =   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   268,   278,   278,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n BP    = 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3, 1.E15, 1.E15,\n MP    =    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    6.,    9.,    6.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,\n QE25  =    0.,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.00,  0.00,\n RMS25 =  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.32,  0.10,  0.64,  0.30,  0.90,  0.80,  0.00,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.00,  0.00,  0.00,  0.00,  0.00,\n RMR25 =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.20,  0.00,  0.00,  0.01,  0.01,  0.05,  0.05,  0.36,  0.03,  0.00,  0.00,  0.00,  0.00,  2.11,  2.11,  2.11,  0.00,  0.00,  0.00,  0.00,  0.00,\n ARM   =   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,\n FOLNMX=  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,  0.00,  0.00,\n WDPOOL=  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  0.00,  0.00,  1.00,  0.00,  0.00,  1.00,  1.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n WRRAT =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  3.00,  3.00,  3.00,  30.0,  30.0,  30.0,  30.0,  30.0,  0.00,  0.00,  30.0,  0.00,  0.00,  3.00,  3.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n MRP   =  0.00,  0.23,  0.23,  0.23,  0.23,  0.23,  0.17,  0.19,  0.19,  0.40,  0.40,  0.37,  0.23,  0.37,  0.30,  0.00,  0.17,  0.40,  0.00,  0.17,  0.23,  0.20,  0.00,  0.00,  0.20,  0.00,  0.00,\n NROOT =     1,     3,     3,     3,     3,     3,     3,     3,     3,     3,     4,     4,     4,     4,     4,     0,     2,     2,     1,     3,     3,     3,     2,     1,     1,     0,     0,\n RGL   = 999.0, 100.0, 100.0, 100.0, 100.0,  65.0, 100.0, 100.0, 100.0,  65.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0, 100.0,  30.0, 999.0, 100.0, 100.0, 100.0, 100.0, 999.0, 100.0, 999.0, 999.0,\n RS    = 200.0,  40.0,  40.0,  40.0,  40.0,  70.0,  40.0, 300.0, 170.0,  70.0, 100.0, 150.0, 150.0, 125.0, 125.0, 100.0,  40.0, 100.0, 999.0, 150.0, 150.0, 150.0, 200.0, 999.0,  40.0, 999.0, 999.0,\n HS    = 999.0, 36.25, 36.25, 36.25, 36.25, 44.14, 36.35, 42.00, 39.18, 54.53, 54.53, 47.35, 41.69, 47.35, 51.93, 51.75, 60.00, 51.93, 999.0, 42.00, 42.00, 42.00, 42.00, 999.0, 36.25, 999.0, 999.0,\n TOPT  = 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0,\n RSMAX = 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_FEB = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_APR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.3,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAY = 0.0,   0.2,   0.2,   0.2,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.4,   0.4,   0.0,   0.3,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUN = 0.0,   0.3,   0.3,   0.3,   0.4,   0.4,   0.4,   0.2,   0.3,   0.4,   0.4,   0.7,   0.5,   0.5,   0.4,   0.0,   0.4,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUL = 0.0,   0.4,   0.4,   0.4,   0.6,   0.6,   0.8,   0.4,   0.6,   0.8,   0.9,   1.3,   0.5,   0.5,   0.7,   0.0,   0.6,   0.6,   0.0,   0.4,   0.4,   0.4,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_AUG = 0.0,   0.5,   0.5,   0.5,   0.9,   0.9,   1.3,   0.6,   0.9,   1.2,   1.2,   1.2,   0.5,   0.6,   0.8,   0.0,   0.9,   0.9,   0.0,   0.6,   0.6,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_SEP = 0.0,   0.4,   0.4,   0.4,   0.7,   1.0,   1.1,   0.8,   1.0,   1.3,   1.6,   1.0,   0.5,   0.6,   1.0,   0.0,   0.7,   1.0,   0.0,   0.7,   0.8,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_OCT = 0.0,   0.3,   0.3,   0.3,   0.3,   0.8,   0.4,   0.7,   0.6,   0.7,   1.4,   0.8,   0.5,   0.7,   1.0,   0.0,   0.3,   0.8,   0.0,   0.5,   0.7,   0.5,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_NOV = 0.0,   0.3,   0.3,   0.3,   0.3,   0.4,   0.4,   0.3,   0.3,   0.4,   0.6,   0.6,   0.5,   0.6,   0.5,   0.0,   0.3,   0.4,   0.0,   0.3,   0.3,   0.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_DEC = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.4,   0.2,   0.3,   0.4,   0.4,   0.5,   0.5,   0.5,   0.4,   0.0,   0.3,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n LAI_JAN = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_FEB = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.3,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAR = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.0,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_APR = 0.0,   0.0,   0.0,   0.0,   0.4,   0.6,   0.7,   0.6,   0.7,   0.8,   1.2,   0.6,   4.5,   4.0,   2.6,   0.0,   0.4,   0.6,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAY = 0.0,   1.0,   1.0,   1.0,   1.1,   2.0,   1.2,   1.5,   1.4,   1.8,   3.0,   1.2,   4.5,   4.0,   3.5,   0.0,   1.1,   2.0,   0.0,   0.6,   1.7,   1.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUN = 0.0,   2.0,   2.0,   2.0,   2.5,   3.3,   3.0,   2.3,   2.6,   3.6,   4.7,   2.0,   4.5,   4.0,   4.3,   0.0,   2.5,   3.3,   0.0,   1.5,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUL = 0.0,   3.0,   3.0,   3.0,   3.2,   3.7,   3.5,   2.3,   2.9,   3.8,   4.5,   2.6,   4.5,   4.0,   4.3,   0.0,   3.2,   3.7,   0.0,   1.7,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_AUG = 0.0,   3.0,   3.0,   3.0,   2.2,   3.2,   1.5,   1.7,   1.6,   2.1,   3.4,   1.7,   4.5,   4.0,   3.7,   0.0,   2.2,   3.2,   0.0,   0.8,   1.8,   1.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_SEP = 0.0,   1.5,   1.5,   1.5,   1.1,   1.3,   0.7,   0.6,   0.7,   0.9,   1.2,   1.0,   4.5,   4.0,   2.6,   0.0,   1.1,   1.3,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_OCT = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.5,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_NOV = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.2,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_DEC = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n SLAREA=0.0228,0.0200,0.0200,0.0295,0.0223,0.0277,0.0060,0.0227,0.0188,0.0236,0.0258,0.0200,0.0200,0.0090,0.0223,0.0422,0.0390,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1   = 41.87,  0.00,  0.00,  2.52,  0.04, 17.11,  0.02, 21.62,  0.11, 22.80, 46.86,  0.00,  0.00,  0.46, 30.98,  2.31,  1.63,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS2   =  0.98,  0.00,  0.00,  0.16,  0.09,  0.28,  0.05,  0.92,  0.22,  0.59,  0.38,  0.00,  0.00,  3.34,  0.96,  1.47,  1.07,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS3   =  1.82,  0.00,  0.00,  0.23,  0.05,  0.81,  0.03,  1.73,  1.26,  1.37,  1.84,  0.00,  0.00,  1.85,  1.84,  1.70,  1.21,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS4   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS5   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n/\n\n&noahmp_modis_veg_categories\n VEG_DATASET_DESCRIPTION = \"modified igbp modis noah\"\n NVEG = 20\n/\n\n&noahmp_modis_parameters\n! 1          'Evergreen Needleleaf Forest'                       -> USGS 14\n! 2,         'Evergreen Broadleaf Forest'                        -> USGS 13\n! 3,         'Deciduous Needleleaf Forest'                       -> USGS 12\n! 4,         'Deciduous Broadleaf Forest'                        -> USGS 11\n! 5,         'Mixed Forests'                                     -> USGS 15\n! 6,         'Closed Shrublands'                                 -> USGS  8 \"shrubland\"\n! 7,         'Open Shrublands'                                   -> USGS  9 \"shrubland/grassland\"\n! 8,         'Woody Savannas'                                    -> USGS  8 \"shrubland\"\n! 9,         'Savannas'                                          -> USGS 10\n! 10,        'Grasslands'                                        -> USGS  7\n! 11         'Permanent wetlands'                                -> avg of USGS 17 and 18 (herb. wooded wetland)\n! 12,        'Croplands'                                         -> USGS  2 \"dryland cropland\"\n! 13,        'Urban and Built-Up'                                -> USGS  1\n! 14         'cropland/natural vegetation mosaic'                -> USGS  5 \"cropland/grassland\"\n! 15,        'Snow and Ice'                                      -> USGS 24\n! 16,        'Barren or Sparsely Vegetated'                      -> USGS 19\n! 17,        'Water'                                             -> USGS 16\n! 18,        'Wooded Tundra'                                     -> USGS 21\n! 19,        'Mixed Tundra'                                      -> USGS 22\n! 20,        'Barren Tundra'                                     -> USGS 23\n\n ISURBAN   = 13\n ISWATER   = 17\n ISBARREN  = 16\n ISICE     = 15\n EBLFOREST =  2\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1       2       3       4       5       6       7       8       9      10      11      12      13      14      15      16      17      18      19      20\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,\n DLEAF =  0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,\n Z0MVT =  1.09,   1.10,   0.85,   0.80,   0.80,   0.20,   0.06,   0.60,   0.50,   0.12,   0.30,   0.15,   1.00,   0.14,   0.00,   0.00,   0.00,   0.30,   0.20,   0.03,\n HVT   =  20.0,   20.0,   18.0,   16.0,   16.0,   1.10,   1.10,   13.0,   10.0,   1.00,   5.00,   2.00,   15.0,   1.50,   0.00,   0.00,   0.00,   4.00,   2.00,   0.50,\n HVB   =  8.50,   8.00,   7.00,   11.5,   10.0,   0.10,   0.10,   0.10,   0.10,   0.05,   0.10,   0.10,   1.00,   0.10,   0.00,   0.00,   0.00,   0.30,   0.20,   0.10,\n DEN   =  0.28,   0.02,   0.28,   0.10,   0.10,   10.0,   10.0,   10.0,   0.02,   100.,   5.05,   25.0,   0.01,   25.0,   0.00,   0.01,   0.01,   1.00,   1.00,   1.00,\n RC    =  1.20,   3.60,   1.20,   1.40,   1.40,   0.12,   0.12,   0.12,   3.00,   0.03,   0.75,   0.08,   1.00,   0.08,   0.00,   0.01,   0.01,   0.30,   0.30,   0.30,\n MFSNO =  2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.07,   0.10,   0.07,   0.10,   0.10,   0.07,   0.07,   0.07,   0.10,   0.11,  0.105,   0.11,   0.00,   0.11,   0.00,   0.00,   0.00,   0.10,   0.10,   0.10,\n RHOL_NIR=0.35,   0.45,   0.35,   0.45,   0.45,   0.35,   0.35,   0.35,   0.45,   0.58,  0.515,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.45,   0.45,   0.45,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.36,   0.26,   0.36,   0.00,   0.36,   0.00,   0.00,   0.00,   0.16,   0.16,   0.16,\n RHOS_NIR=0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.58,  0.485,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.39,   0.39,   0.39,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.07,   0.06,   0.07,   0.00,   0.07,   0.00,   0.00,   0.00,   0.05,   0.05,   0.05,\n TAUL_NIR=0.10,   0.25,   0.10,   0.25,   0.25,   0.10,   0.10,   0.10,   0.25,   0.25,   0.25,   0.25,   0.00,   0.25,   0.00,   0.00,   0.00,   0.25,   0.25,   0.25,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.220, 0.1105,  0.220,  0.000,  0.220,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n TAUS_NIR=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.380, 0.1905,  0.380,  0.000,  0.380,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n\n XL    = 0.010,  0.010,  0.010,  0.250,  0.250,  0.010,  0.010,  0.010,  0.010,  -0.30, -0.025,  -0.30,  0.000,  -0.30,  0.000,  0.000,  0.000,  0.250,  0.250,  0.250,\n! CWPVT =   3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,\n CWPVT =  0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,\n C3PSN =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n KC25  =  30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,\n AKC   =   2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,\n KO25  =  3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,\n AKO   =   1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,\n AVCMX =   2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,\n AQE   =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n\n LTOVRC=   0.5,   0.55,    0.2,   0.55,    0.5,   0.65,   0.65,   0.65,   0.65,   0.50,    1.4,    1.6,    0.0,    1.2,    0.0,    0.0,    0.0,    1.3,    1.4,    1.0,\n DILEFC=  1.20,   0.50,   1.80,   0.60,   0.80,   0.20,   0.20,   0.20,   0.50,   0.20,    0.4,   0.50,   0.00,   0.35,   0.00,   0.00,   0.00,   0.30,   0.40,   0.30,\n DILEFW=  0.20,   4.00,   0.20,   0.20,   0.20,   0.20,   0.20,   0.20,   0.50,   0.10,    0.2,   0.20,   0.00,   0.20,   0.00,   0.00,   0.00,   0.20,   0.20,   0.20,\n RMF25 =  3.00,   0.65,   4.00,   3.00,   3.00,   0.26,   0.26,   0.26,   0.80,   1.80,    3.2,   1.00,   0.00,   1.45,   0.00,   0.00,   0.00,   3.00,   3.00,   3.00,\n SLA   =    80,     80,     80,     80,     80,     60,     60,     60,     50,     60,     80,     80,     60,     80,      0,      0,      0,     80,     80,     80,\n FRAGR =  0.10,   0.20,   0.10,   0.20,   0.10,   0.20,   0.20,   0.20,   0.20,   0.20,    0.1,   0.20,   0.00,   0.20,   0.00,   0.10,   0.00,   0.10,   0.10,   0.10,\n TMIN  =   265,    273,    268,    273,    268,    273,    273,    273,    273,    273,    268,    273,      0,    273,      0,      0,      0,    268,    268,    268,\n VCMX25=  50.0,   60.0,   60.0,   60.0,   55.0,   40.0,   40.0,   40.0,   40.0,   40.0,   50.0,   80.0,   0.00,   60.0,   0.00,   0.00,   0.00,   50.0,   50.0,   50.0,\n TDLEF =   278,    278,    268,    278,    268,    278,    278,    278,    278,    278,    268,    278,    278,    278,      0,      0,      0,    268,    268,    268,\n BP    =  2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,   2.E3,   2.E3,\n MP    =    6.,     9.,     6.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,\n QE25  =  0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.00,   0.06,   0.00,   0.06,   0.00,   0.06,   0.06,   0.06,\n RMS25 =  0.90,   0.30,   0.64,   0.10,   0.80,   0.10,   0.10,   0.10,   0.32,   0.10,   0.10,   0.10,   0.00,   0.10,   0.00,   0.00,   0.00,   0.10,   0.10,   0.00,\n RMR25 =  0.36,   0.05,   0.05,   0.01,   0.03,   0.00,   0.00,   0.00,   0.01,   1.20,    0.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   2.11,   2.11,   0.00,\n ARM   =   2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,\n FOLNMX=   1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,   0.00,    1.5,   0.00,    1.5,   0.00,    1.5,    1.5,    1.5,\n WDPOOL=  1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   0.00,    0.5,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   1.00,   1.00,   0.00,\n WRRAT =  30.0,   30.0,   30.0,   30.0,   30.0,   3.00,   3.00,   3.00,   3.00,   0.00,   15.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   3.00,   3.00,   0.00,\n MRP   =  0.37,   0.23,   0.37,   0.40,   0.30,   0.19,   0.19,   0.19,   0.40,   0.17,  0.285,   0.23,   0.00,   0.23,   0.00,   0.00,   0.00,   0.23,   0.20,   0.00,\n NROOT =     4,      4,      4,      4,      4,      3,      3,      3,      3,      3,      2,      3,      1,      3,      1,      1,      0,      3,      3,      2,     \n RGL   =  30.0,   30.0,   30.0,   30.0,   30.0,  100.0,  100.0,  100.0,   65.0,  100.0,   65.0,  100.0,  999.0,  100.0,  999.0,  999.0,   30.0,  100.0,  100.0,  100.0,\n RS    = 125.0,  150.0,  150.0,  100.0,  125.0,  300.0,  170.0,  300.0,   70.0,   40.0,   70.0,   40.0,  200.0,   40.0,  999.0,  999.0,  100.0,  150.0,  150.0,  200.0,\n HS    = 47.35,  41.69,  47.35,  54.53,  51.93,  42.00,  39.18,  42.00,  54.53,  36.35,  55.97,  36.25,  999.0,  36.25,  999.0,  999.0,  51.75,  42.00,  42.00,  42.00,\n TOPT  = 298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,\n RSMAX = 5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_FEB = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAR = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_APR = 0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAY = 0.4,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_JUN = 0.5,    0.5,    0.7,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.4,    0.3,    0.0,    0.4,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n SAI_JUL = 0.5,    0.5,    1.3,    0.9,    0.7,    0.6,    0.4,    0.7,    0.8,    0.8,    0.6,    0.4,    0.0,    0.6,    0.0,    0.0,    0.0,    0.4,    0.4,    0.0,\n SAI_AUG = 0.6,    0.5,    1.2,    1.2,    0.8,    0.9,    0.6,    1.2,    1.2,    1.3,    0.9,    0.5,    0.0,    0.9,    0.0,    0.0,    0.0,    0.6,    0.6,    0.0,\n SAI_SEP = 0.6,    0.5,    1.0,    1.6,    1.0,    1.2,    0.8,    1.4,    1.3,    1.1,    0.9,    0.4,    0.0,    0.7,    0.0,    0.0,    0.0,    0.8,    0.7,    0.0,\n SAI_OCT = 0.7,    0.5,    0.8,    1.4,    1.0,    0.9,    0.7,    1.1,    0.7,    0.4,    0.6,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.7,    0.5,    0.0,\n SAI_NOV = 0.6,    0.5,    0.6,    0.6,    0.5,    0.4,    0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.3,    0.3,    0.0,\n SAI_DEC = 0.5,    0.5,    0.5,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n\n LAI_JAN = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_FEB = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_MAR = 4.0,    4.5,    0.0,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_APR = 4.0,    4.5,    0.6,    1.2,    2.6,    0.9,    0.6,    1.0,    0.8,    0.7,    0.5,    0.0,    0.0,    0.4,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_MAY = 4.0,    4.5,    1.2,    3.0,    3.5,    2.2,    1.5,    2.4,    1.8,    1.2,    1.5,    1.0,    0.0,    1.1,    0.0,    0.0,    0.0,    1.7,    1.2,    0.0,\n LAI_JUN = 4.0,    4.5,    2.0,    4.7,    4.3,    3.5,    2.3,    4.1,    3.6,    3.0,    2.9,    2.0,    0.0,    2.5,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_JUL = 4.0,    4.5,    2.6,    4.5,    4.3,    3.5,    2.3,    4.1,    3.8,    3.5,    3.5,    3.0,    0.0,    3.2,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_AUG = 4.0,    4.5,    1.7,    3.4,    3.7,    2.5,    1.7,    2.7,    2.1,    1.5,    2.7,    3.0,    0.0,    2.2,    0.0,    0.0,    0.0,    1.8,    1.3,    0.0,\n LAI_SEP = 4.0,    4.5,    1.0,    1.2,    2.6,    0.9,    0.6,    1.0,    0.9,    0.7,    1.2,    1.5,    0.0,    1.1,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_OCT = 4.0,    4.5,    0.5,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_NOV = 4.0,    4.5,    0.2,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_DEC = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n\n SLAREA=0.0090, 0.0200, 0.0200, 0.0258, 0.0223, 0.0227, 0.0188, 0.0227, 0.0236, 0.0060, 0.0295, 0.0200, 0.0228, 0.0223,   0.02,   0.02, 0.0422,   0.02,   0.02,   0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1  =  0.46,   0.00,   0.00,  46.86,  30.98,  21.62,   0.11,  21.62,  22.80,   0.02,  0.815,   0.00,  41.87,   0.04,    0.0,    0.0,   2.31,    0.0,    0.0,    0.0,\n EPS2  =  3.34,   0.00,   0.00,   0.38,   0.96,   0.92,   0.22,   0.92,   0.59,   0.05,  0.535,   0.00,   0.98,   0.09,    0.0,    0.0,   1.47,    0.0,    0.0,    0.0,\n EPS3  =  1.85,   0.00,   0.00,   1.84,   1.84,   1.73,   1.26,   1.73,   1.37,   0.03,  0.605,   0.00,   1.82,   0.05,    0.0,    0.0,   1.70,    0.0,    0.0,    0.0,\n EPS4  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n EPS5  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n\n/\n\n&noahmp_rad_parameters\n !------------------------------------------------------------------------------\n !                1       2       3       4       5       6       7       8     soil color index for soil albedo\n !------------------------------------------------------------------------------\n ALBSAT_VIS =   0.15,   0.11,   0.10,   0.09,   0.08,   0.07,   0.06,   0.05   ! saturated soil albedos\n ALBSAT_NIR =   0.30,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! saturated soil albedos\n ALBDRY_VIS =   0.27,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! dry soil albedos\n ALBDRY_NIR =   0.54,   0.44,   0.40,   0.36,   0.32,   0.28,   0.24,   0.20   ! dry soil albedos\n ALBICE     =   0.80,   0.55                                                   ! albedo land ice: 1=vis, 2=nir\n ALBLAK     =   0.60,   0.40                                                   ! albedo frozen lakes: 1=vis, 2=nir\n OMEGAS     =   0.8 ,   0.4                                                    ! two-stream parameter omega for snow\n BETADS     =   0.5                                                            ! two-stream parameter betad for snow\n BETAIS     =   0.5                                                            ! two-stream parameter betaI for snow\n EG         =   0.97,   0.98                                                   ! emissivity soil surface 1-soil;2-lake\n\n/\n\n&noahmp_global_parameters\n\n! atmospheric constituants\n\n  CO2    = 395.e-06     !co2 partial pressure\n  O2     = 0.209        !o2 partial pressure\n\n! runoff parameters used for SIMTOP and SIMGM:\n\n  TIMEAN = 10.5         !gridcell mean topgraphic index (global mean)\n  FSATMX = 0.38         !maximum surface saturated fraction (global mean)\n\n! adjustable parameters for snow processes\n\n  Z0SNO  = 0.002        !snow surface roughness length (m) (0.002)\n  SSI    = 0.03         !liquid water holding capacity for snowpack (m3/m3) (0.03)\n  SNOW_RET_FAC  = 5.e-5 !snowpack water release timescale factor (1/s)\n  SWEMX  = 1.00         !new snow mass to fully cover old snow (mm)\n                        !equivalent to 10mm depth (density = 100 kg/m3)\n  TAU0          = 1.e6  !tau0 from Yang97 eqn. 10a\n  GRAIN_GROWTH  = 5000. !growth from vapor diffusion Yang97 eqn. 10b\n  EXTRA_GROWTH  = 10.   !extra growth near freezing Yang97 eqn. 10c\n  DIRT_SOOT     = 0.3   !dirt and soot term Yang97 eqn. 10d\n  BATS_COSZ     = 2.0   !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n  BATS_VIS_NEW  = 0.95  !new snow visible albedo\n  BATS_NIR_NEW  = 0.65  !new snow NIR albedo\n  BATS_VIS_AGE  = 0.2   !age factor for diffuse visible snow albedo Yang97 eqn. 17\n  BATS_NIR_AGE  = 0.5   !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n  BATS_VIS_DIR  = 0.4   !cosz factor for direct visible snow albedo Yang97 eqn. 15\n  BATS_NIR_DIR  = 0.4   !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n  RSURF_SNOW = 50.0     !surface resistence for snow [s/m]\n  RSURF_EXP = 5.0       !exponent in the shape parameter for soil resistance option 1\n\n/\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.0/SOILPARM.TBL",
    "content": "Soil Parameters\nSTAS\n19,1   'BB      DRYSMC      F11     MAXSMC   REFSMC   SATPSI  SATDK      SATDW     WLTSMC  QTZ    '\n1,     2.79,    0.010,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,   0.010,  0.92, 'SAND'\n2,     4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.82, 'LOAMY SAND'\n3,     4.74,    0.047,    -0.569,   0.434,   0.312,   0.141,  5.23E-6,  8.05E-6,   0.047,  0.60, 'SANDY LOAM'\n4,     5.33,    0.084,     0.162,   0.476,   0.360,   0.759,  2.81E-6,  2.39E-5,   0.084,  0.25, 'SILT LOAM'\n5,     3.86,    0.061,     0.162,   0.484,   0.347,   0.955,  2.18E-6,  1.66E-5,   0.061,  0.10, 'SILT'\n6,     5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.40, 'LOAM'\n7,     6.77,    0.069,    -1.491,   0.404,   0.315,   0.135,  4.45E-6,  1.01E-5,   0.069,  0.60, 'SANDY CLAY LOAM'\n8,     8.72,    0.120,    -1.118,   0.464,   0.387,   0.617,  2.03E-6,  2.35E-5,   0.120,  0.10, 'SILTY CLAY LOAM'\n9,     8.17,    0.103,    -1.297,   0.465,   0.382,   0.263,  2.45E-6,  1.13E-5,   0.103,  0.35, 'CLAY LOAM'\n10,   10.73,    0.100,    -3.209,   0.406,   0.338,   0.098,  7.22E-6,  1.87E-5,   0.100,  0.52, 'SANDY CLAY'\n11,   10.39,    0.126,    -1.916,   0.468,   0.404,   0.324,  1.34E-6,  9.64E-6,   0.126,  0.10, 'SILTY CLAY'\n12,   11.55,    0.138,    -2.138,   0.468,   0.412,   0.468,  9.74E-7,  1.12E-5,   0.138,  0.25, 'CLAY'\n13,    5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.05, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,       0.0,     1.0,     0.0,     0.0,      0.0,      0.0,     0.0,  0.60, 'WATER'\n15,    2.79,    0.006,    -1.111,    0.20,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.07, 'BEDROCK'\n16,    4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.25, 'OTHER(land-ice)'\n17,   11.55,    0.030,   -10.472,   0.468,   0.454,   0.468,  9.74E-7,  1.12E-5,   0.030,  0.60, 'PLAYA'\n18,    2.79,    0.006,    -0.472,   0.200,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.52, 'LAVA'\n19,    2.79,     0.01,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,    0.01,  0.92, 'WHITE SAND'\nSoil Parameters\nSTAS-RUC\n19,1   'BB      DRYSMC       HC     MAXSMC   REFSMC   SATPSI  SATDK       SATDW     WLTSMC  QTZ    '\n1,     4.05,    0.002,      1.47,   0.395,   0.174,   0.121,  1.76E-4,  0.608E-6,   0.033,  0.92, 'SAND'\n2,     4.38,    0.035,      1.41,   0.410,   0.179,   0.090,  1.56E-4,  0.514E-5,   0.055,  0.82, 'LOAMY SAND'\n3,     4.90,    0.041,      1.34,   0.435,   0.249,   0.218,  3.47E-5,  0.805E-5,   0.095,  0.60, 'SANDY LOAM'\n4,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.25, 'SILT LOAM'\n5,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.10, 'SILT'\n6,     5.39,    0.050,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.137,  0.40, 'LOAM'\n7,     7.12,    0.068,      1.18,   0.420,   0.299,   0.299,  6.30E-6,  0.990E-5,   0.148,  0.60, 'SANDY CLAY LOAM'\n8,     7.75,    0.060,      1.32,   0.477,   0.357,   0.356,  1.70E-6,  0.237E-4,   0.208,  0.10, 'SILTY CLAY LOAM'\n9,     8.52,    0.085,      1.23,   0.476,   0.391,   0.630,  2.45E-6,  0.113E-4,   0.230,  0.35, 'CLAY LOAM'\n10,   10.40,    0.100,      1.18,   0.426,   0.316,   0.153,  2.17E-6,  0.187E-4,   0.210,  0.52, 'SANDY CLAY'\n11,   10.40,    0.070,      1.15,   0.492,   0.409,   0.490,  1.03E-6,  0.964E-5,   0.250,  0.10, 'SILTY CLAY'\n12,   11.40,    0.068,      1.09,   0.482,   0.400,   0.405,  1.28E-6,  0.112E-4,   0.268,  0.25, 'CLAY'\n13,    5.39,    0.027,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.117,  0.05, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,      4.18,   1.0,     1.0,     0.0,      0.0,       0.0,     0.0,    0.00, 'WATER'\n15,    4.05,    0.004,      2.03,   0.200,   0.10 ,   0.121,  1.41E-4,  0.136E-3,   0.006,  0.60, 'BEDROCK'\n16,    4.90,    0.065,      2.10,   0.435,   0.249,   0.218,  3.47E-5,  0.514E-5,   0.114,  0.05, 'OTHER(land-ice)'\n17,   11.40,    0.030,      1.41,   0.468,   0.454,   0.468,  9.74E-7,  0.112E-4,   0.030,  0.60, 'PLAYA'\n18,    4.05,    0.006,      1.41,   0.200,   0.17,    0.069,  1.41E-4,  0.136E-3,   0.006,  0.52, 'LAVA'\n19,    4.05,     0.01,      1.47,   0.339,   0.236,   0.069,  1.76E-4,  0.608E-6,   0.060,  0.92, 'WHITE SAND'\n\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.1/CHANPARM.TBL",
    "content": "Channel Parameters\nStreamOrder\n10,1,  'Bw     HLINK   ChSSlp   MannN'\n1,     1.5,    0.02,    3.0,      0.55\n2,     3.0,    0.02,    1.0,      0.35\n3,     5.0,    0.02,    0.5,      0.15\n4,     10.,    0.03,   0.18,      0.10\n5,     20.,    0.03,   0.05,      0.07\n6,     40.,    0.03,   0.05,      0.05\n7,     60.,    0.03,   0.05,      0.04\n8,     70.,    0.10,   0.05,      0.03\n9,     80.,    0.30,   0.05,      0.02\n10,    100.,    0.30,   0.05,      0.01\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.1/GENPARM.TBL",
    "content": "General Parameters\nSLOPE_DATA\n9\n0.1 \n0.6\n1.0\n0.35\n0.55\n0.8\n0.63\n0.0\n0.0\nSBETA_DATA\n-2.0\nFXEXP_DATA\n2.0\nCSOIL_DATA\n2.00E+6\nSALP_DATA\n2.6\nREFDK_DATA\n2.0E-6\nREFKDT_DATA\n3.0\nFRZK_DATA\n0.15\nZBOT_DATA\n-8.0\nCZIL_DATA\n0.1\nSMLOW_DATA\n0.5\nSMHIGH_DATA\n3.0\nLVCOEF_DATA\n0.5\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.1/HYDRO.TBL",
    "content": "     28 USGS for OV_ROUGH\n   SFC_ROUGH'\n     0.025,    'Urban and Built-Up Land'  \n     0.035,    'Dryland Cropland and Pasture' \n     0.035,    'Irrigated Cropland and Pasture' \n     0.055,    'Mixed Dryland/Irrigated Cropland and Pasture' \n     0.035,    'Cropland/Grassland Mosaic'\n     0.068,    'Cropland/Woodland Mosaic' \n     0.055,    'Grassland' \n     0.055,    'Shrubland' \n     0.055,    'Mixed Shrubland/Grassland' \n     0.055,    'Savanna' \n     0.200,    'Deciduous Broadleaf Forest' \n     0.200,    'Deciduous Needleleaf Forest' \n     0.200,    'Evergreen Broadleaf Forest'\n     0.200,    'Evergreen Needleleaf Forest'  \n     0.200,    'Mixed Forest' \n     0.005,    'Water Bodies' \n     0.070,    'Herbaceous Wetland' \n     0.070,    'Wooded Wetland' \n     0.035,    'Barren or Sparsely Vegetated' \n     0.055,    'Herbaceous Tundra' \n     0.055,    'Wooded Tundra' \n     0.055,    'Mixed Tundra' \n     0.055,    'Bare Ground Tundra' \n     0.010,    'Snow or Ice' \n     0.010,    'Playa' \n     0.100,    'Lava'   \n     0.010,    'White Sand' \n     0.005,    'Non-Ocean Water Bodies'\n19, for SATDK\nSATDK     MAXSMC    REFSMC   WLTSMC  QTZ    '\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'SAND'\n1.41E-5,  0.421,    0.283,   0.028,  0.82, 'LOAMY SAND'\n5.23E-6,  0.434,    0.312,   0.047,  0.60, 'SANDY LOAM'\n2.81E-6,  0.476,    0.360,   0.084,  0.25, 'SILT LOAM'\n2.18E-6,  0.484,    0.347,   0.061,  0.10, 'SILT'\n3.38E-6,  0.439,    0.329,   0.066,  0.40, 'LOAM'\n4.45E-6,  0.404,    0.315,   0.069,  0.60, 'SANDY CLAY LOAM'\n2.03E-6,  0.464,    0.387,   0.120,  0.10, 'SILTY CLAY LOAM'\n2.45E-6,  0.465,    0.382,   0.103,  0.35, 'CLAY LOAM'\n7.22E-6,  0.406,    0.338,   0.100,  0.52, 'SANDY CLAY'\n1.34E-6,  0.468,    0.404,   0.126,  0.10, 'SILTY CLAY'\n9.74E-7,  0.468,    0.412,   0.138,  0.25, 'CLAY'\n3.38E-6,  0.439,    0.329,   0.066,  0.05, 'ORGANIC MATERIAL'\n    0.0,  1.0,      0.0,     0.0,    0.60, 'WATER'\n1.41E-4,  0.20,     0.170,   0.006,  0.07, 'BEDROCK'\n1.41E-5,  0.421,    0.283,   0.028,  0.25, 'OTHER(land-ice)'\n9.74E-7,  0.468,    0.454,   0.030,  0.60, 'PLAYA'\n1.41E-4,  0.200,    0.170,   0.006,  0.52, 'LAVA'\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'WHITE SAND'\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.1/MPTABLE.TBL",
    "content": "&noahmp_usgs_veg_categories\n VEG_DATASET_DESCRIPTION = \"USGS\"\n NVEG = 27\n/\n&noahmp_usgs_parameters\n ! NVEG = 27\n !  1: Urban and Built-Up Land\n !  2: Dryland Cropland and Pasture\n !  3: Irrigated Cropland and Pasture\n !  4: Mixed Dryland/Irrigated Cropland and Pasture\n !  5: Cropland/Grassland Mosaic\n !  6: Cropland/Woodland Mosaic\n !  7: Grassland\n !  8: Shrubland\n !  9: Mixed Shrubland/Grassland\n ! 10: Savanna\n ! 11: Deciduous Broadleaf Forest\n ! 12: Deciduous Needleleaf Forest\n ! 13: Evergreen Broadleaf Forest\n ! 14: Evergreen Needleleaf Forest\n ! 15: Mixed Forest\n ! 16: Water Bodies\n ! 17: Herbaceous Wetland\n ! 18: Wooded Wetland\n ! 19: Barren or Sparsely Vegetated\n ! 20: Herbaceous Tundra\n ! 21: Wooded Tundra\n ! 22: Mixed Tundra\n ! 23: Bare Ground Tundra\n ! 24: Snow or Ice\n ! 25: Playa\n ! 26: Lava\n ! 27: White Sand\n\n ISURBAN                   =  1\n ISWATER                   = 16\n ISBARREN                  = 19\n ISICE                     = 24\n ISCROP                    =  2\n EBLFOREST                 = 13\n NATURAL                   =  5\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1      2      3      4      5      6      7      8      9      10     11     12     13     14     15     16     17     18     19     20     21     22     23     24     25     26    27\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,\n DLEAF =  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,\n Z0MVT =  1.00,  0.15,  0.15,  0.15,  0.14,  0.50,  0.12,  0.06,  0.09,  0.50,  0.80,  0.85,  1.10,  1.09,  0.80,  0.00,  0.12,  0.50,  0.00,  0.10,  0.30,  0.20,  0.03,  0.00,  0.01,  0.00,  0.00,\n HVT   =  15.0,  2.00,  2.00,  2.00,  1.50,  8.00,  1.00,  1.10,  1.10,  10.0,  16.0,  18.0,  20.0,  20.0,  16.0,  0.00,  0.50,  10.0,  0.00,  0.50,  4.00,  2.00,  0.50,  0.00,  0.10,  0.00,  0.00,\n HVB   =  1.00,  0.10,  0.10,  0.10,  0.10,  0.15,  0.05,  0.10,  0.10,  0.10,  11.5,  7.00,  8.00,  8.50,  10.0,  0.00,  0.05,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n DEN   =  0.01,  25.0,  25.0,  25.0,  25.0,  25.0,  100.,  10.0,  10.0,  0.02,  0.10,  0.28,  0.02,  0.28,  0.10,  0.01,  10.0,  0.10,  0.01,  1.00,  1.00,  1.00,  1.00,  0.00,  0.01,  0.01,  0.01,\n RC    =  1.00,  0.08,  0.08,  0.08,  0.08,  0.08,  0.03,  0.12,  0.12,  3.00,  1.40,  1.20,  3.60,  1.20,  1.40,  0.01,  0.10,  1.40,  0.01,  0.30,  0.30,  0.30,  0.30,  0.00,  0.01,  0.01,  0.01,\n MFSNO =  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.00,  0.11,  0.11,  0.11,  0.11,  0.11,  0.11,  0.07,  0.10,  0.10,  0.10,  0.07,  0.10,  0.07,  0.10,  0.00,  0.11,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n RHOL_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.35,  0.45,  0.45,  0.45,  0.35,  0.45,  0.35,  0.45,  0.00,  0.58,  0.45,  0.00,  0.45,  0.45,  0.45,  0.45,  0.00,  0.45,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.00,  0.36,  0.36,  0.36,  0.36,  0.36,  0.36,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.00,  0.36,  0.16,  0.00,  0.16,  0.16,  0.16,  0.16,  0.00,  0.16,  0.00,  0.00,\n RHOS_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.00,  0.58,  0.39,  0.00,  0.39,  0.39,  0.39,  0.39,  0.00,  0.39,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.00,  0.07,  0.07,  0.07,  0.07,  0.07,  0.07,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.00,  0.07,  0.05,  0.00,  0.05,  0.05,  0.05,  0.05,  0.00,  0.05,  0.00,  0.00,\n TAUL_NIR=0.00,  0.25,  0.25,  0.25,  0.25,  0.25,  0.25,  0.10,  0.10,  0.25,  0.25,  0.10,  0.25,  0.10,  0.25,  0.00,  0.25,  0.25,  0.00,  0.25,  0.25,  0.25,  0.25,  0.00,  0.25,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.00, 0.220, 0.220, 0.220, 0.220, 0.220, 0.220, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.220, 0.001, 0.000, 0.220, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n TAUS_NIR=0.00, 0.380, 0.380, 0.380, 0.380, 0.380, 0.380, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.380, 0.001, 0.000, 0.380, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n\n XL    = 0.000, -0.30, -0.30, -0.30, -0.30, -0.30, -0.30, 0.010, 0.250, 0.010, 0.250, 0.010, 0.010, 0.010, 0.250, 0.000, -0.30, 0.250, 0.000, -0.30, 0.250, 0.250, 0.250, 0.000, 0.250, 0.000, 0.000,\n CWPVT =  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,\n C3PSN =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n KC25  =  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,\n AKC   =   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,\n KO25  =  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,\n AKO   =   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,\n AVCMX =   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,\n AQE   =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n\n LTOVRC=   0.0,   1.2,   1.2,   1.2,   1.2,  1.30,  0.50,  0.65,  0.70,  0.65,  0.55,   0.2,  0.55,   0.5,   0.5,   0.0,   1.4,   1.4,   0.0,   1.2,   1.3,   1.4,   1.0,   0.0,   1.0,   0.0,   0.0,\n DILEFC=  0.00,  0.50,  0.50,  0.50,  0.35,  0.20,  0.20,  0.20,  0.50,  0.50,  0.60,  1.80,  0.50,  1.20,  0.80,  0.00,  0.40,  0.40,  0.00,  0.40,  0.30,  0.40,  0.30,  0.00,  0.30,  0.00,  0.00,\n DILEFW=  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.20,  0.50,  0.20,  0.20,  4.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.20,  0.20,  0.00,  0.20,  0.00,  0.00,\n RMF25 =  0.00,  1.00,  1.40,  1.45,  1.45,  1.45,  1.80,  0.26,  0.26,  0.80,  3.00,  4.00,  0.65,  3.00,  3.00,  0.00,  3.20,  3.20,  0.00,  3.20,  3.00,  3.00,  3.00,  0.00,  3.00,  0.00,  0.00,\n SLA   =    60,    80,    80,    80,    80,    80,    60,    60,    60,    50,    80,    80,    80,    80,    80,     0,    80,    80,     0,    80,    80,    80,    80,     0,    80,     0,     0,\n FRAGR =  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n TMIN  =     0,   273,   273,   273,   273,   273,   273,   273,   273,   273,   273,   268,   273,   265,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n VCMX25=  0.00,  80.0,  80.0,  80.0,  60.0,  70.0,  40.0,  40.0,  40.0,  40.0,  60.0,  60.0,  60.0,  50.0,  55.0,  0.00,  50.0,  50.0,  0.00,  50.0,  50.0,  50.0,  50.0,  0.00,  50.0,  0.00,  0.00,\n TDLEF =   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   268,   278,   278,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n BP    = 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3, 1.E15, 1.E15,\n MP    =    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    6.,    9.,    6.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,\n QE25  =    0.,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.00,  0.00,\n RMS25 =  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.32,  0.10,  0.64,  0.30,  0.90,  0.80,  0.00,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.00,  0.00,  0.00,  0.00,  0.00,\n RMR25 =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.20,  0.00,  0.00,  0.01,  0.01,  0.05,  0.05,  0.36,  0.03,  0.00,  0.00,  0.00,  0.00,  2.11,  2.11,  2.11,  0.00,  0.00,  0.00,  0.00,  0.00,\n ARM   =   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,\n FOLNMX=  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,  0.00,  0.00,\n WDPOOL=  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  0.00,  0.00,  1.00,  0.00,  0.00,  1.00,  1.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n WRRAT =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  3.00,  3.00,  3.00,  30.0,  30.0,  30.0,  30.0,  30.0,  0.00,  0.00,  30.0,  0.00,  0.00,  3.00,  3.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n MRP   =  0.00,  0.23,  0.23,  0.23,  0.23,  0.23,  0.17,  0.19,  0.19,  0.40,  0.40,  0.37,  0.23,  0.37,  0.30,  0.00,  0.17,  0.40,  0.00,  0.17,  0.23,  0.20,  0.00,  0.00,  0.20,  0.00,  0.00,\n NROOT =     1,     3,     3,     3,     3,     3,     3,     3,     3,     3,     4,     4,     4,     4,     4,     0,     2,     2,     1,     3,     3,     3,     2,     1,     1,     0,     0,\n RGL   = 999.0, 100.0, 100.0, 100.0, 100.0,  65.0, 100.0, 100.0, 100.0,  65.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0, 100.0,  30.0, 999.0, 100.0, 100.0, 100.0, 100.0, 999.0, 100.0, 999.0, 999.0,\n RS    = 200.0,  40.0,  40.0,  40.0,  40.0,  70.0,  40.0, 300.0, 170.0,  70.0, 100.0, 150.0, 150.0, 125.0, 125.0, 100.0,  40.0, 100.0, 999.0, 150.0, 150.0, 150.0, 200.0, 999.0,  40.0, 999.0, 999.0,\n HS    = 999.0, 36.25, 36.25, 36.25, 36.25, 44.14, 36.35, 42.00, 39.18, 54.53, 54.53, 47.35, 41.69, 47.35, 51.93, 51.75, 60.00, 51.93, 999.0, 42.00, 42.00, 42.00, 42.00, 999.0, 36.25, 999.0, 999.0,\n TOPT  = 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0,\n RSMAX = 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_FEB = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_APR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.3,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAY = 0.0,   0.2,   0.2,   0.2,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.4,   0.4,   0.0,   0.3,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUN = 0.0,   0.3,   0.3,   0.3,   0.4,   0.4,   0.4,   0.2,   0.3,   0.4,   0.4,   0.7,   0.5,   0.5,   0.4,   0.0,   0.4,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUL = 0.0,   0.4,   0.4,   0.4,   0.6,   0.6,   0.8,   0.4,   0.6,   0.8,   0.9,   1.3,   0.5,   0.5,   0.7,   0.0,   0.6,   0.6,   0.0,   0.4,   0.4,   0.4,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_AUG = 0.0,   0.5,   0.5,   0.5,   0.9,   0.9,   1.3,   0.6,   0.9,   1.2,   1.2,   1.2,   0.5,   0.6,   0.8,   0.0,   0.9,   0.9,   0.0,   0.6,   0.6,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_SEP = 0.0,   0.4,   0.4,   0.4,   0.7,   1.0,   1.1,   0.8,   1.0,   1.3,   1.6,   1.0,   0.5,   0.6,   1.0,   0.0,   0.7,   1.0,   0.0,   0.7,   0.8,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_OCT = 0.0,   0.3,   0.3,   0.3,   0.3,   0.8,   0.4,   0.7,   0.6,   0.7,   1.4,   0.8,   0.5,   0.7,   1.0,   0.0,   0.3,   0.8,   0.0,   0.5,   0.7,   0.5,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_NOV = 0.0,   0.3,   0.3,   0.3,   0.3,   0.4,   0.4,   0.3,   0.3,   0.4,   0.6,   0.6,   0.5,   0.6,   0.5,   0.0,   0.3,   0.4,   0.0,   0.3,   0.3,   0.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_DEC = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.4,   0.2,   0.3,   0.4,   0.4,   0.5,   0.5,   0.5,   0.4,   0.0,   0.3,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n LAI_JAN = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_FEB = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.3,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAR = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.0,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_APR = 0.0,   0.0,   0.0,   0.0,   0.4,   0.6,   0.7,   0.6,   0.7,   0.8,   1.2,   0.6,   4.5,   4.0,   2.6,   0.0,   0.4,   0.6,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAY = 0.0,   1.0,   1.0,   1.0,   1.1,   2.0,   1.2,   1.5,   1.4,   1.8,   3.0,   1.2,   4.5,   4.0,   3.5,   0.0,   1.1,   2.0,   0.0,   0.6,   1.7,   1.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUN = 0.0,   2.0,   2.0,   2.0,   2.5,   3.3,   3.0,   2.3,   2.6,   3.6,   4.7,   2.0,   4.5,   4.0,   4.3,   0.0,   2.5,   3.3,   0.0,   1.5,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUL = 0.0,   3.0,   3.0,   3.0,   3.2,   3.7,   3.5,   2.3,   2.9,   3.8,   4.5,   2.6,   4.5,   4.0,   4.3,   0.0,   3.2,   3.7,   0.0,   1.7,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_AUG = 0.0,   3.0,   3.0,   3.0,   2.2,   3.2,   1.5,   1.7,   1.6,   2.1,   3.4,   1.7,   4.5,   4.0,   3.7,   0.0,   2.2,   3.2,   0.0,   0.8,   1.8,   1.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_SEP = 0.0,   1.5,   1.5,   1.5,   1.1,   1.3,   0.7,   0.6,   0.7,   0.9,   1.2,   1.0,   4.5,   4.0,   2.6,   0.0,   1.1,   1.3,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_OCT = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.5,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_NOV = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.2,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_DEC = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n SLAREA=0.0228,0.0200,0.0200,0.0295,0.0223,0.0277,0.0060,0.0227,0.0188,0.0236,0.0258,0.0200,0.0200,0.0090,0.0223,0.0422,0.0390,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1   = 41.87,  0.00,  0.00,  2.52,  0.04, 17.11,  0.02, 21.62,  0.11, 22.80, 46.86,  0.00,  0.00,  0.46, 30.98,  2.31,  1.63,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS2   =  0.98,  0.00,  0.00,  0.16,  0.09,  0.28,  0.05,  0.92,  0.22,  0.59,  0.38,  0.00,  0.00,  3.34,  0.96,  1.47,  1.07,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS3   =  1.82,  0.00,  0.00,  0.23,  0.05,  0.81,  0.03,  1.73,  1.26,  1.37,  1.84,  0.00,  0.00,  1.85,  1.84,  1.70,  1.21,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS4   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS5   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n/\n\n&noahmp_modis_veg_categories\n VEG_DATASET_DESCRIPTION = \"modified igbp modis noah\"\n NVEG = 20\n/\n\n&noahmp_modis_parameters\n! 1          'Evergreen Needleleaf Forest'                       -> USGS 14\n! 2,         'Evergreen Broadleaf Forest'                        -> USGS 13\n! 3,         'Deciduous Needleleaf Forest'                       -> USGS 12\n! 4,         'Deciduous Broadleaf Forest'                        -> USGS 11\n! 5,         'Mixed Forests'                                     -> USGS 15\n! 6,         'Closed Shrublands'                                 -> USGS  8 \"shrubland\"\n! 7,         'Open Shrublands'                                   -> USGS  9 \"shrubland/grassland\"\n! 8,         'Woody Savannas'                                    -> USGS  8 \"shrubland\"\n! 9,         'Savannas'                                          -> USGS 10\n! 10,        'Grasslands'                                        -> USGS  7\n! 11         'Permanent wetlands'                                -> avg of USGS 17 and 18 (herb. wooded wetland)\n! 12,        'Croplands'                                         -> USGS  2 \"dryland cropland\"\n! 13,        'Urban and Built-Up'                                -> USGS  1\n! 14         'cropland/natural vegetation mosaic'                -> USGS  5 \"cropland/grassland\"\n! 15,        'Snow and Ice'                                      -> USGS 24\n! 16,        'Barren or Sparsely Vegetated'                      -> USGS 19\n! 17,        'Water'                                             -> USGS 16\n! 18,        'Wooded Tundra'                                     -> USGS 21\n! 19,        'Mixed Tundra'                                      -> USGS 22\n! 20,        'Barren Tundra'                                     -> USGS 23\n\n ISURBAN                   = 13\n ISWATER                   = 17\n ISBARREN                  = 16\n ISICE                     = 15\n ISCROP                    = 12\n EBLFOREST                 =  2\n NATURAL                   = 14\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1       2       3       4       5       6       7       8       9      10      11      12      13      14      15      16      17      18      19      20\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,\n DLEAF =  0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,\n Z0MVT =  1.09,   1.10,   0.85,   0.80,   0.80,   0.20,   0.06,   0.60,   0.50,   0.12,   0.30,   0.15,   1.00,   0.14,   0.00,   0.00,   0.00,   0.30,   0.20,   0.03,\n HVT   =  20.0,   20.0,   18.0,   16.0,   16.0,   1.10,   1.10,   13.0,   10.0,   1.00,   5.00,   2.00,   15.0,   1.50,   0.00,   0.00,   0.00,   4.00,   2.00,   0.50,\n HVB   =  8.50,   8.00,   7.00,   11.5,   10.0,   0.10,   0.10,   0.10,   0.10,   0.05,   0.10,   0.10,   1.00,   0.10,   0.00,   0.00,   0.00,   0.30,   0.20,   0.10,\n DEN   =  0.28,   0.02,   0.28,   0.10,   0.10,   10.0,   10.0,   10.0,   0.02,   100.,   5.05,   25.0,   0.01,   25.0,   0.00,   0.01,   0.01,   1.00,   1.00,   1.00,\n RC    =  1.20,   3.60,   1.20,   1.40,   1.40,   0.12,   0.12,   0.12,   3.00,   0.03,   0.75,   0.08,   1.00,   0.08,   0.00,   0.01,   0.01,   0.30,   0.30,   0.30,\n MFSNO =  2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.07,   0.10,   0.07,   0.10,   0.10,   0.07,   0.07,   0.07,   0.10,   0.11,  0.105,   0.11,   0.00,   0.11,   0.00,   0.00,   0.00,   0.10,   0.10,   0.10,\n RHOL_NIR=0.35,   0.45,   0.35,   0.45,   0.45,   0.35,   0.35,   0.35,   0.45,   0.58,  0.515,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.45,   0.45,   0.45,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.36,   0.26,   0.36,   0.00,   0.36,   0.00,   0.00,   0.00,   0.16,   0.16,   0.16,\n RHOS_NIR=0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.58,  0.485,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.39,   0.39,   0.39,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.07,   0.06,   0.07,   0.00,   0.07,   0.00,   0.00,   0.00,   0.05,   0.05,   0.05,\n TAUL_NIR=0.10,   0.25,   0.10,   0.25,   0.25,   0.10,   0.10,   0.10,   0.25,   0.25,   0.25,   0.25,   0.00,   0.25,   0.00,   0.00,   0.00,   0.25,   0.25,   0.25,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.220, 0.1105,  0.220,  0.000,  0.220,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n TAUS_NIR=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.380, 0.1905,  0.380,  0.000,  0.380,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n\n XL    = 0.010,  0.010,  0.010,  0.250,  0.250,  0.010,  0.010,  0.010,  0.010,  -0.30, -0.025,  -0.30,  0.000,  -0.30,  0.000,  0.000,  0.000,  0.250,  0.250,  0.250,\n! CWPVT =   3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,\n CWPVT =  0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,\n C3PSN =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n KC25  =  30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,\n AKC   =   2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,\n KO25  =  3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,\n AKO   =   1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,\n AVCMX =   2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,\n AQE   =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n\n LTOVRC=   0.5,   0.55,    0.2,   0.55,    0.5,   0.65,   0.65,   0.65,   0.65,   0.50,    1.4,    1.6,    0.0,    1.2,    0.0,    0.0,    0.0,    1.3,    1.4,    1.0,\n DILEFC=  1.20,   0.50,   1.80,   0.60,   0.80,   0.20,   0.20,   0.20,   0.50,   0.20,    0.4,   0.50,   0.00,   0.35,   0.00,   0.00,   0.00,   0.30,   0.40,   0.30,\n DILEFW=  0.20,   4.00,   0.20,   0.20,   0.20,   0.20,   0.20,   0.20,   0.50,   0.10,    0.2,   0.20,   0.00,   0.20,   0.00,   0.00,   0.00,   0.20,   0.20,   0.20,\n RMF25 =  3.00,   0.65,   4.00,   3.00,   3.00,   0.26,   0.26,   0.26,   0.80,   1.80,    3.2,   1.00,   0.00,   1.45,   0.00,   0.00,   0.00,   3.00,   3.00,   3.00,\n SLA   =    80,     80,     80,     80,     80,     60,     60,     60,     50,     60,     80,     80,     60,     80,      0,      0,      0,     80,     80,     80,\n FRAGR =  0.10,   0.20,   0.10,   0.20,   0.10,   0.20,   0.20,   0.20,   0.20,   0.20,    0.1,   0.20,   0.00,   0.20,   0.00,   0.10,   0.00,   0.10,   0.10,   0.10,\n TMIN  =   265,    273,    268,    273,    268,    273,    273,    273,    273,    273,    268,    273,      0,    273,      0,      0,      0,    268,    268,    268,\n VCMX25=  50.0,   60.0,   60.0,   60.0,   55.0,   40.0,   40.0,   40.0,   40.0,   40.0,   50.0,   80.0,   0.00,   60.0,   0.00,   0.00,   0.00,   50.0,   50.0,   50.0,\n TDLEF =   278,    278,    268,    278,    268,    278,    278,    278,    278,    278,    268,    278,    278,    278,      0,      0,      0,    268,    268,    268,\n BP    =  2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,   2.E3,   2.E3,\n MP    =    6.,     9.,     6.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,\n QE25  =  0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.00,   0.06,   0.00,   0.06,   0.00,   0.06,   0.06,   0.06,\n RMS25 =  0.90,   0.30,   0.64,   0.10,   0.80,   0.10,   0.10,   0.10,   0.32,   0.10,   0.10,   0.10,   0.00,   0.10,   0.00,   0.00,   0.00,   0.10,   0.10,   0.00,\n RMR25 =  0.36,   0.05,   0.05,   0.01,   0.03,   0.00,   0.00,   0.00,   0.01,   1.20,    0.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   2.11,   2.11,   0.00,\n ARM   =   2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,\n FOLNMX=   1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,   0.00,    1.5,   0.00,    1.5,   0.00,    1.5,    1.5,    1.5,\n WDPOOL=  1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   0.00,    0.5,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   1.00,   1.00,   0.00,\n WRRAT =  30.0,   30.0,   30.0,   30.0,   30.0,   3.00,   3.00,   3.00,   3.00,   0.00,   15.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   3.00,   3.00,   0.00,\n MRP   =  0.37,   0.23,   0.37,   0.40,   0.30,   0.19,   0.19,   0.19,   0.40,   0.17,  0.285,   0.23,   0.00,   0.23,   0.00,   0.00,   0.00,   0.23,   0.20,   0.00,\n NROOT =     4,      4,      4,      4,      4,      3,      3,      3,      3,      3,      2,      3,      1,      3,      1,      1,      0,      3,      3,      2,     \n RGL   =  30.0,   30.0,   30.0,   30.0,   30.0,  100.0,  100.0,  100.0,   65.0,  100.0,   65.0,  100.0,  999.0,  100.0,  999.0,  999.0,   30.0,  100.0,  100.0,  100.0,\n RS    = 125.0,  150.0,  150.0,  100.0,  125.0,  300.0,  170.0,  300.0,   70.0,   40.0,   70.0,   40.0,  200.0,   40.0,  999.0,  999.0,  100.0,  150.0,  150.0,  200.0,\n HS    = 47.35,  41.69,  47.35,  54.53,  51.93,  42.00,  39.18,  42.00,  54.53,  36.35,  55.97,  36.25,  999.0,  36.25,  999.0,  999.0,  51.75,  42.00,  42.00,  42.00,\n TOPT  = 298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,\n RSMAX = 5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_FEB = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAR = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_APR = 0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAY = 0.4,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_JUN = 0.5,    0.5,    0.7,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.4,    0.3,    0.0,    0.4,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n SAI_JUL = 0.5,    0.5,    1.3,    0.9,    0.7,    0.6,    0.4,    0.7,    0.8,    0.8,    0.6,    0.4,    0.0,    0.6,    0.0,    0.0,    0.0,    0.4,    0.4,    0.0,\n SAI_AUG = 0.6,    0.5,    1.2,    1.2,    0.8,    0.9,    0.6,    1.2,    1.2,    1.3,    0.9,    0.5,    0.0,    0.9,    0.0,    0.0,    0.0,    0.6,    0.6,    0.0,\n SAI_SEP = 0.6,    0.5,    1.0,    1.6,    1.0,    1.2,    0.8,    1.4,    1.3,    1.1,    0.9,    0.4,    0.0,    0.7,    0.0,    0.0,    0.0,    0.8,    0.7,    0.0,\n SAI_OCT = 0.7,    0.5,    0.8,    1.4,    1.0,    0.9,    0.7,    1.1,    0.7,    0.4,    0.6,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.7,    0.5,    0.0,\n SAI_NOV = 0.6,    0.5,    0.6,    0.6,    0.5,    0.4,    0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.3,    0.3,    0.0,\n SAI_DEC = 0.5,    0.5,    0.5,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n\n LAI_JAN = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_FEB = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_MAR = 4.0,    4.5,    0.0,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_APR = 4.0,    4.5,    0.6,    1.2,    2.6,    0.9,    0.6,    1.0,    0.8,    0.7,    0.5,    0.0,    0.0,    0.4,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_MAY = 4.0,    4.5,    1.2,    3.0,    3.5,    2.2,    1.5,    2.4,    1.8,    1.2,    1.5,    1.0,    0.0,    1.1,    0.0,    0.0,    0.0,    1.7,    1.2,    0.0,\n LAI_JUN = 4.0,    4.5,    2.0,    4.7,    4.3,    3.5,    2.3,    4.1,    3.6,    3.0,    2.9,    2.0,    0.0,    2.5,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_JUL = 4.0,    4.5,    2.6,    4.5,    4.3,    3.5,    2.3,    4.1,    3.8,    3.5,    3.5,    3.0,    0.0,    3.2,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_AUG = 4.0,    4.5,    1.7,    3.4,    3.7,    2.5,    1.7,    2.7,    2.1,    1.5,    2.7,    3.0,    0.0,    2.2,    0.0,    0.0,    0.0,    1.8,    1.3,    0.0,\n LAI_SEP = 4.0,    4.5,    1.0,    1.2,    2.6,    0.9,    0.6,    1.0,    0.9,    0.7,    1.2,    1.5,    0.0,    1.1,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_OCT = 4.0,    4.5,    0.5,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_NOV = 4.0,    4.5,    0.2,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_DEC = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n\n SLAREA=0.0090, 0.0200, 0.0200, 0.0258, 0.0223, 0.0227, 0.0188, 0.0227, 0.0236, 0.0060, 0.0295, 0.0200, 0.0228, 0.0223,   0.02,   0.02, 0.0422,   0.02,   0.02,   0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1  =  0.46,   0.00,   0.00,  46.86,  30.98,  21.62,   0.11,  21.62,  22.80,   0.02,  0.815,   0.00,  41.87,   0.04,    0.0,    0.0,   2.31,    0.0,    0.0,    0.0,\n EPS2  =  3.34,   0.00,   0.00,   0.38,   0.96,   0.92,   0.22,   0.92,   0.59,   0.05,  0.535,   0.00,   0.98,   0.09,    0.0,    0.0,   1.47,    0.0,    0.0,    0.0,\n EPS3  =  1.85,   0.00,   0.00,   1.84,   1.84,   1.73,   1.26,   1.73,   1.37,   0.03,  0.605,   0.00,   1.82,   0.05,    0.0,    0.0,   1.70,    0.0,    0.0,    0.0,\n EPS4  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n EPS5  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n\n/\n\n&noahmp_rad_parameters\n !------------------------------------------------------------------------------\n !                1       2       3       4       5       6       7       8     soil color index for soil albedo\n !------------------------------------------------------------------------------\n ALBSAT_VIS =   0.15,   0.11,   0.10,   0.09,   0.08,   0.07,   0.06,   0.05   ! saturated soil albedos\n ALBSAT_NIR =   0.30,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! saturated soil albedos\n ALBDRY_VIS =   0.27,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! dry soil albedos\n ALBDRY_NIR =   0.54,   0.44,   0.40,   0.36,   0.32,   0.28,   0.24,   0.20   ! dry soil albedos\n ALBICE     =   0.80,   0.55                                                   ! albedo land ice: 1=vis, 2=nir\n ALBLAK     =   0.60,   0.40                                                   ! albedo frozen lakes: 1=vis, 2=nir\n OMEGAS     =   0.8 ,   0.4                                                    ! two-stream parameter omega for snow\n BETADS     =   0.5                                                            ! two-stream parameter betad for snow\n BETAIS     =   0.5                                                            ! two-stream parameter betaI for snow\n EG         =   0.97,   0.98                                                   ! emissivity soil surface 1-soil;2-lake\n\n/\n\n&noahmp_global_parameters\n\n! atmospheric constituants\n\n  CO2    = 395.e-06     !co2 partial pressure\n  O2     = 0.209        !o2 partial pressure\n\n! runoff parameters used for SIMTOP and SIMGM:\n\n  TIMEAN = 10.5         !gridcell mean topgraphic index (global mean)\n  FSATMX = 0.38         !maximum surface saturated fraction (global mean)\n\n! adjustable parameters for snow processes\n\n  Z0SNO  = 0.002        !snow surface roughness length (m) (0.002)\n  SSI    = 0.03         !liquid water holding capacity for snowpack (m3/m3) (0.03)\n  SNOW_RET_FAC  = 5.e-5 !snowpack water release timescale factor (1/s)\n  SWEMX  = 1.00         !new snow mass to fully cover old snow (mm)\n                        !equivalent to 10mm depth (density = 100 kg/m3)\n  TAU0          = 1.e6  !tau0 from Yang97 eqn. 10a\n  GRAIN_GROWTH  = 5000. !growth from vapor diffusion Yang97 eqn. 10b\n  EXTRA_GROWTH  = 10.   !extra growth near freezing Yang97 eqn. 10c\n  DIRT_SOOT     = 0.3   !dirt and soot term Yang97 eqn. 10d\n  BATS_COSZ     = 2.0   !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n  BATS_VIS_NEW  = 0.95  !new snow visible albedo\n  BATS_NIR_NEW  = 0.65  !new snow NIR albedo\n  BATS_VIS_AGE  = 0.2   !age factor for diffuse visible snow albedo Yang97 eqn. 17\n  BATS_NIR_AGE  = 0.5   !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n  BATS_VIS_DIR  = 0.4   !cosz factor for direct visible snow albedo Yang97 eqn. 15\n  BATS_NIR_DIR  = 0.4   !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n  RSURF_SNOW = 50.0     !surface resistence for snow [s/m]\n  RSURF_EXP = 5.0       !exponent in the shape parameter for soil resistance option 1\n\n/\n\n&noahmp_crop_parameters\n\n ! NCROP = 5\n !  1: Corn\n !  2: Soybean\n !  3: Sorghum\n !  4: Rice\n !  5: Winter wheat\n\nDEFAULT_CROP = 0                                      ! The default crop type(1-5); if zero, use generic dynamic vegetation \n\n!----------------------------------------------------------\n!                1       2       3       4       5\n!----------------------------------------------------------\n \nPLTDAY     =    130,    111,    111,    111,    111,  ! Planting date\nHSDAY      =    280,    300,    300,    300,    300,  ! Harvest date\nPLANTPOP   =   78.0,   78.0,   78.0,   78.0,   78.0,  ! Plant density [per ha] - used?\nIRRI       =    0.0,    0.0,    0.0,    0.0,    0.0,  ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n\nGDDTBASE   =   10.0,   10.0,   10.0,   10.0,   10.0,  ! Base temperature for GDD accumulation [C]\nGDDTCUT    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! Upper temperature for GDD accumulation [C]\nGDDS1      =   60.0,   50.0,   50.0,   50.0,   50.0,  ! GDD from seeding to emergence\nGDDS2      =  675.0,  718.0,  718.0,  718.0,  718.0,  ! GDD from seeding to initial vegetative \nGDDS3      = 1183.0,  933.0,  933.0,  933.0,  933.0,  ! GDD from seeding to post vegetative \nGDDS4      = 1253.0, 1103.0, 1103.0, 1103.0, 1103.0,  ! GDD from seeding to intial reproductive\nGDDS5      = 1605.0, 1555.0, 1555.0, 1555.0, 1555.0,  ! GDD from seeding to pysical maturity \n\nC3C4       =      2,      1,      2,      2,      2,  ! photosynthetic pathway:  1. = c3 2. = c4\nAref       =    7.0,    7.0,    7.0,    7.0,    7.0,  ! reference maximum CO2 assimulation rate \nPSNRF      =   0.85,   0.85,   0.85,   0.85,   0.85,  ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\nI2PAR      =    0.5,    0.5,    0.5,    0.5,    0.5,  ! Fraction of incoming solar radiation to photosynthetically active radiation\nTASSIM0    =    8.0,    8.0,    8.0,    8.0,    8.0,  ! Minimum temperature for CO2 assimulation [C]\nTASSIM1    =   18.0,   18.0,   18.0,   18.0,   18.0,  ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\nTASSIM2    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\nK          =   0.55,   0.55,   0.55,   0.55,   0.55,  ! light extinction coefficient\nEPSI       =   12.5,   12.5,   12.5,   12.5,   12.5,  ! initial light use efficiency\n\nQ10MR      =    2.0,    2.0,    2.0,    2.0,    2.0,  ! q10 for maintainance respiration\nFOLN_MX    =    1.5,    1.5,    1.5,    1.5,    1.5,  ! foliage nitrogen concentration when f(n)=1 (%)\nLEFREEZ    =    268,    268,    268,    268,    268,  ! characteristic T for leaf freezing [K]\n\nDILE_FC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for temperature leaf stress death [1/s]\nDILE_FC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0, \nDILE_FC_S5 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S6 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nDILE_FW_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for water leaf stress death [1/s]\nDILE_FW_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FW_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S5 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S6 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nFRA_GR     =    0.2,    0.2,    0.2,    0.2,    0.2,  ! fraction of growth respiration\n\nLF_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of leaf turnover  [1/s]\nLF_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLF_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S5 =    0.2,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S6 =    0.3,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nST_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of stem turnover  [1/s]\nST_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nST_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nST_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nST_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nRT_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of root tunrover  [1/s]\nRT_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRT_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nRT_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nRT_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n             \nLFMR25     =    1.0,    1.0,    1.0,    1.0,    1.0,  !  leaf maintenance respiration at 25C [umol CO2/m**2  /s]\nSTMR25     =   0.05,    0.1,    0.1,    0.1,    0.1,  !  stem maintenance respiration at 25C [umol CO2/kg bio/s]\nRTMR25     =   0.05,    0.0,    0.0,    0.0,    0.0,  !  root maintenance respiration at 25C [umol CO2/kg bio/s]\nGRAINMR25  =    0.0,    0.1,    0.1,    0.1,    0.1,  ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n\nLFPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to leaf\nLFPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLFPT_S3    =    0.4,    0.4,    0.4,    0.4,    0.4,\nLFPT_S4    =    0.2,    0.2,    0.2,    0.2,    0.2,\nLFPT_S5    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S6    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nSTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to stem\nSTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nSTPT_S3    =    0.2,    0.2,    0.2,    0.2,    0.2,\nSTPT_S4    =    0.5,    0.5,    0.5,    0.5,    0.5,\nSTPT_S5    =    0.0,   0.15,   0.15,   0.15,   0.15,\nSTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nSTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nSTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0, \n\nRTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to root\nRTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRTPT_S3    =   0.34,    0.4,    0.4,    0.4,    0.4,\nRTPT_S4    =    0.3,    0.3,    0.3,    0.3,    0.3,\nRTPT_S5    =   0.05,   0.05,   0.05,   0.05,   0.05,\nRTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nRTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nRTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n   \nGRAINPT_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to grain\nGRAINPT_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nGRAINPT_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S5 =   0.95,    0.8,    0.8,    0.8,    0.8,\nGRAINPT_S6 =    1.0,    0.9,    0.9,    0.9,    0.9,\nGRAINPT_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n\nBIO2LAI   =  0.035,  0.015,  0.015,  0.015,  0.015,  ! leaf are per living leaf biomass [m^2/kg]\n\n/\n\n&noahmp_optional_parameters\n\n !------------------------------------------------------------------------------\n ! Saxton and Rawls 2006 Pedo-transfer function coefficients\n !------------------------------------------------------------------------------\n\n sr2006_theta_1500t_a =   -0.024   ! sand coefficient\n sr2006_theta_1500t_b =    0.487   ! clay coefficient\n sr2006_theta_1500t_c =    0.006   ! orgm coefficient\n sr2006_theta_1500t_d =    0.005   ! sand*orgm coefficient\n sr2006_theta_1500t_e =   -0.013   ! clay*orgm coefficient\n sr2006_theta_1500t_f =    0.068   ! sand*clay coefficient\n sr2006_theta_1500t_g =    0.031   ! constant adjustment\n\n sr2006_theta_1500_a  =    0.14    ! theta_1500t coefficient\n sr2006_theta_1500_b  =   -0.02    ! constant adjustment\n\n sr2006_theta_33t_a   =   -0.251   ! sand coefficient\n sr2006_theta_33t_b   =    0.195   ! clay coefficient\n sr2006_theta_33t_c   =    0.011   ! orgm coefficient\n sr2006_theta_33t_d   =    0.006   ! sand*orgm coefficient\n sr2006_theta_33t_e   =   -0.027   ! clay*orgm coefficient\n sr2006_theta_33t_f   =    0.452   ! sand*clay coefficient\n sr2006_theta_33t_g   =    0.299   ! constant adjustment\n\n sr2006_theta_33_a    =    1.283   ! theta_33t*theta_33t coefficient\n sr2006_theta_33_b    =   -0.374   ! theta_33t coefficient\n sr2006_theta_33_c    =   -0.015   ! constant adjustment\n\n sr2006_theta_s33t_a  =    0.278   ! sand coefficient\n sr2006_theta_s33t_b  =    0.034   ! clay coefficient\n sr2006_theta_s33t_c  =    0.022   ! orgm coefficient\n sr2006_theta_s33t_d  =   -0.018   ! sand*orgm coefficient\n sr2006_theta_s33t_e  =   -0.027   ! clay*orgm coefficient\n sr2006_theta_s33t_f  =   -0.584   ! sand*clay coefficient\n sr2006_theta_s33t_g  =    0.078   ! constant adjustment\n\n sr2006_theta_s33_a   =    0.636   ! theta_s33t coefficient\n sr2006_theta_s33_b   =   -0.107   ! constant adjustment\n\n sr2006_psi_et_a      =  -21.67    ! sand coefficient\n sr2006_psi_et_b      =  -27.93    ! clay coefficient\n sr2006_psi_et_c      =  -81.97    ! theta_s33 coefficient\n sr2006_psi_et_d      =   71.12    ! sand*theta_s33 coefficient\n sr2006_psi_et_e      =    8.29    ! clay*theta_s33 coefficient\n sr2006_psi_et_f      =   14.05    ! sand*clay coefficient\n sr2006_psi_et_g      =   27.16    ! constant adjustment\n\n sr2006_psi_e_a       =    0.02    ! psi_et*psi_et coefficient\n sr2006_psi_e_b       =   -0.113   ! psi_et coefficient\n sr2006_psi_e_c       =   -0.7     ! constant adjustment\n\n sr2006_smcmax_a      =   -0.097   ! sand adjustment\n sr2006_smcmax_b      =    0.043   ! constant adjustment\n \n/\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v2.1/SOILPARM.TBL",
    "content": "Soil Parameters\nSTAS\n19,1   'BB      DRYSMC      F11     MAXSMC   REFSMC   SATPSI  SATDK      SATDW     WLTSMC  QTZ    '\n1,     2.79,    0.010,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,   0.010,  0.92, 'SAND'\n2,     4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.82, 'LOAMY SAND'\n3,     4.74,    0.047,    -0.569,   0.434,   0.312,   0.141,  5.23E-6,  8.05E-6,   0.047,  0.60, 'SANDY LOAM'\n4,     5.33,    0.084,     0.162,   0.476,   0.360,   0.759,  2.81E-6,  2.39E-5,   0.084,  0.25, 'SILT LOAM'\n5,     3.86,    0.061,     0.162,   0.484,   0.347,   0.955,  2.18E-6,  1.66E-5,   0.061,  0.10, 'SILT'\n6,     5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.40, 'LOAM'\n7,     6.77,    0.069,    -1.491,   0.404,   0.315,   0.135,  4.45E-6,  1.01E-5,   0.069,  0.60, 'SANDY CLAY LOAM'\n8,     8.72,    0.120,    -1.118,   0.464,   0.387,   0.617,  2.03E-6,  2.35E-5,   0.120,  0.10, 'SILTY CLAY LOAM'\n9,     8.17,    0.103,    -1.297,   0.465,   0.382,   0.263,  2.45E-6,  1.13E-5,   0.103,  0.35, 'CLAY LOAM'\n10,   10.73,    0.100,    -3.209,   0.406,   0.338,   0.098,  7.22E-6,  1.87E-5,   0.100,  0.52, 'SANDY CLAY'\n11,   10.39,    0.126,    -1.916,   0.468,   0.404,   0.324,  1.34E-6,  9.64E-6,   0.126,  0.10, 'SILTY CLAY'\n12,   11.55,    0.138,    -2.138,   0.468,   0.412,   0.468,  9.74E-7,  1.12E-5,   0.138,  0.25, 'CLAY'\n13,    5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.05, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,       0.0,     1.0,     0.0,     0.0,      0.0,      0.0,     0.0,  0.60, 'WATER'\n15,    2.79,    0.006,    -1.111,    0.20,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.07, 'BEDROCK'\n16,    4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.25, 'OTHER(land-ice)'\n17,   11.55,    0.030,   -10.472,   0.468,   0.454,   0.468,  9.74E-7,  1.12E-5,   0.030,  0.60, 'PLAYA'\n18,    2.79,    0.006,    -0.472,   0.200,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.52, 'LAVA'\n19,    2.79,     0.01,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,    0.01,  0.92, 'WHITE SAND'\nSoil Parameters\nSTAS-RUC\n19,1   'BB      DRYSMC       HC     MAXSMC   REFSMC   SATPSI  SATDK       SATDW     WLTSMC  QTZ    '\n1,     4.05,    0.002,      1.47,   0.395,   0.174,   0.121,  1.76E-4,  0.608E-6,   0.033,  0.92, 'SAND'\n2,     4.38,    0.035,      1.41,   0.410,   0.179,   0.090,  1.56E-4,  0.514E-5,   0.055,  0.82, 'LOAMY SAND'\n3,     4.90,    0.041,      1.34,   0.435,   0.249,   0.218,  3.47E-5,  0.805E-5,   0.095,  0.60, 'SANDY LOAM'\n4,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.25, 'SILT LOAM'\n5,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.10, 'SILT'\n6,     5.39,    0.050,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.137,  0.40, 'LOAM'\n7,     7.12,    0.068,      1.18,   0.420,   0.299,   0.299,  6.30E-6,  0.990E-5,   0.148,  0.60, 'SANDY CLAY LOAM'\n8,     7.75,    0.060,      1.32,   0.477,   0.357,   0.356,  1.70E-6,  0.237E-4,   0.208,  0.10, 'SILTY CLAY LOAM'\n9,     8.52,    0.085,      1.23,   0.476,   0.391,   0.630,  2.45E-6,  0.113E-4,   0.230,  0.35, 'CLAY LOAM'\n10,   10.40,    0.100,      1.18,   0.426,   0.316,   0.153,  2.17E-6,  0.187E-4,   0.210,  0.52, 'SANDY CLAY'\n11,   10.40,    0.070,      1.15,   0.492,   0.409,   0.490,  1.03E-6,  0.964E-5,   0.250,  0.10, 'SILTY CLAY'\n12,   11.40,    0.068,      1.09,   0.482,   0.400,   0.405,  1.28E-6,  0.112E-4,   0.268,  0.25, 'CLAY'\n13,    5.39,    0.027,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.117,  0.05, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,      4.18,   1.0,     1.0,     0.0,      0.0,       0.0,     0.0,    0.00, 'WATER'\n15,    4.05,    0.004,      2.03,   0.200,   0.10 ,   0.121,  1.41E-4,  0.136E-3,   0.006,  0.60, 'BEDROCK'\n16,    4.90,    0.065,      2.10,   0.435,   0.249,   0.218,  3.47E-5,  0.514E-5,   0.114,  0.05, 'OTHER(land-ice)'\n17,   11.40,    0.030,      1.41,   0.468,   0.454,   0.468,  9.74E-7,  0.112E-4,   0.030,  0.60, 'PLAYA'\n18,    4.05,    0.006,      1.41,   0.200,   0.17,    0.069,  1.41E-4,  0.136E-3,   0.006,  0.52, 'LAVA'\n19,    4.05,     0.01,      1.47,   0.339,   0.236,   0.069,  1.76E-4,  0.608E-6,   0.060,  0.92, 'WHITE SAND'\n\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Alaska/CHANPARM.TBL",
    "content": "Channel Parameters\nStreamOrder\n10,1,  'Bw     HLINK   ChSSlp   MannN'\n1,     1.6,    0.02,    0.03,      0.09\n2,     2.4,    0.02,    0.03,      0.07\n3,     3.5,    0.02,    0.03,      0.06\n4,     5.3,    0.03,    0.04,      0.05\n5,     7.4,    0.03,    0.04,      0.04\n6,     11.,    0.03,    0.04,      0.03\n7,     14.,    0.03,    0.04,      0.03\n8,     16.,    0.10,    0.04,      0.02\n9,     26.,    0.30,    0.05,      0.02\n10,    110.,    0.30,    0.10,      0.02\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Alaska/GENPARM.TBL",
    "content": "General Parameters\nSLOPE_DATA\n9\n0.1 \n0.6\n1.0\n0.35\n0.55\n0.8\n0.63\n0.0\n0.0\nSBETA_DATA\n-2.0\nFXEXP_DATA\n2.0\nCSOIL_DATA\n2.00E+6\nSALP_DATA\n2.6\nREFDK_DATA\n2.0E-6\nREFKDT_DATA\n3.0\nFRZK_DATA\n0.15\nZBOT_DATA\n-8.0\nCZIL_DATA\n0.1\nSMLOW_DATA\n0.5\nSMHIGH_DATA\n3.0\nLVCOEF_DATA\n0.5\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Alaska/HYDRO.TBL",
    "content": "     28 USGS for OV_ROUGH\n   SFC_ROUGH'\n     0.025,    'Urban and Built-Up Land'  \n     0.035,    'Dryland Cropland and Pasture' \n     0.035,    'Irrigated Cropland and Pasture' \n     0.055,    'Mixed Dryland/Irrigated Cropland and Pasture' \n     0.035,    'Cropland/Grassland Mosaic'\n     0.068,    'Cropland/Woodland Mosaic' \n     0.055,    'Grassland' \n     0.055,    'Shrubland' \n     0.055,    'Mixed Shrubland/Grassland' \n     0.055,    'Savanna' \n     0.200,    'Deciduous Broadleaf Forest' \n     0.200,    'Deciduous Needleleaf Forest' \n     0.200,    'Evergreen Broadleaf Forest'\n     0.200,    'Evergreen Needleleaf Forest'  \n     0.200,    'Mixed Forest' \n     0.005,    'Water Bodies' \n     0.070,    'Herbaceous Wetland' \n     0.070,    'Wooded Wetland' \n     0.035,    'Barren or Sparsely Vegetated' \n     0.055,    'Herbaceous Tundra' \n     0.055,    'Wooded Tundra' \n     0.055,    'Mixed Tundra' \n     0.055,    'Bare Ground Tundra' \n     0.010,    'Snow or Ice' \n     0.010,    'Playa' \n     0.100,    'Lava'   \n     0.010,    'White Sand' \n     0.005,    'Non-Ocean Water Bodies'\n19, for SATDK\nSATDK     MAXSMC    REFSMC   WLTSMC  QTZ    '\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'SAND'\n1.41E-5,  0.421,    0.283,   0.028,  0.82, 'LOAMY SAND'\n5.23E-6,  0.434,    0.312,   0.047,  0.60, 'SANDY LOAM'\n2.81E-6,  0.476,    0.360,   0.084,  0.25, 'SILT LOAM'\n2.18E-6,  0.484,    0.347,   0.061,  0.10, 'SILT'\n3.38E-6,  0.439,    0.329,   0.066,  0.40, 'LOAM'\n4.45E-6,  0.404,    0.315,   0.069,  0.60, 'SANDY CLAY LOAM'\n2.03E-6,  0.464,    0.387,   0.120,  0.10, 'SILTY CLAY LOAM'\n2.45E-6,  0.465,    0.382,   0.103,  0.35, 'CLAY LOAM'\n7.22E-6,  0.406,    0.338,   0.100,  0.52, 'SANDY CLAY'\n1.34E-6,  0.468,    0.404,   0.126,  0.10, 'SILTY CLAY'\n9.74E-7,  0.468,    0.412,   0.138,  0.25, 'CLAY'\n3.38E-6,  0.439,    0.329,   0.066,  0.05, 'ORGANIC MATERIAL'\n    0.0,  1.0,      0.0,     0.0,    0.60, 'WATER'\n1.41E-4,  0.20,     0.170,   0.006,  0.07, 'BEDROCK'\n1.41E-5,  0.421,    0.283,   0.028,  0.25, 'OTHER(land-ice)'\n9.74E-7,  0.468,    0.454,   0.030,  0.60, 'PLAYA'\n1.41E-4,  0.200,    0.170,   0.006,  0.52, 'LAVA'\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'WHITE SAND'\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Alaska/MPTABLE.TBL",
    "content": "&noahmp_usgs_veg_categories\n VEG_DATASET_DESCRIPTION = \"USGS\"\n NVEG = 27\n/\n&noahmp_usgs_parameters\n ! NVEG = 27\n !  1: Urban and Built-Up Land\n !  2: Dryland Cropland and Pasture\n !  3: Irrigated Cropland and Pasture\n !  4: Mixed Dryland/Irrigated Cropland and Pasture\n !  5: Cropland/Grassland Mosaic\n !  6: Cropland/Woodland Mosaic\n !  7: Grassland\n !  8: Shrubland\n !  9: Mixed Shrubland/Grassland\n ! 10: Savanna\n ! 11: Deciduous Broadleaf Forest\n ! 12: Deciduous Needleleaf Forest\n ! 13: Evergreen Broadleaf Forest\n ! 14: Evergreen Needleleaf Forest\n ! 15: Mixed Forest\n ! 16: Water Bodies\n ! 17: Herbaceous Wetland\n ! 18: Wooded Wetland\n ! 19: Barren or Sparsely Vegetated\n ! 20: Herbaceous Tundra\n ! 21: Wooded Tundra\n ! 22: Mixed Tundra\n ! 23: Bare Ground Tundra\n ! 24: Snow or Ice\n ! 25: Playa\n ! 26: Lava\n ! 27: White Sand\n\n ISURBAN                   =  1\n ISWATER                   = 16\n ISBARREN                  = 19\n ISICE                     = 24\n ISCROP                    =  2\n EBLFOREST                 = 13\n NATURAL                   =  5\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1      2      3      4      5      6      7      8      9      10     11     12     13     14     15     16     17     18     19     20     21     22     23     24     25     26    27\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,\n DLEAF =  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,\n Z0MVT =  1.00,  0.15,  0.15,  0.15,  0.14,  0.50,  0.12,  0.06,  0.09,  0.50,  0.80,  0.85,  1.10,  1.09,  0.80,  0.00,  0.12,  0.50,  0.00,  0.10,  0.30,  0.20,  0.03,  0.00,  0.01,  0.00,  0.00,\n HVT   =  15.0,  2.00,  2.00,  2.00,  1.50,  8.00,  1.00,  1.10,  1.10,  10.0,  16.0,  18.0,  20.0,  20.0,  16.0,  0.00,  0.50,  10.0,  0.00,  0.50,  4.00,  2.00,  0.50,  0.00,  0.10,  0.00,  0.00,\n HVB   =  1.00,  0.10,  0.10,  0.10,  0.10,  0.15,  0.05,  0.10,  0.10,  0.10,  11.5,  7.00,  8.00,  8.50,  10.0,  0.00,  0.05,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n DEN   =  0.01,  25.0,  25.0,  25.0,  25.0,  25.0,  100.,  10.0,  10.0,  0.02,  0.10,  0.28,  0.02,  0.28,  0.10,  0.01,  10.0,  0.10,  0.01,  1.00,  1.00,  1.00,  1.00,  0.00,  0.01,  0.01,  0.01,\n RC    =  1.00,  0.08,  0.08,  0.08,  0.08,  0.08,  0.03,  0.12,  0.12,  3.00,  1.40,  1.20,  3.60,  1.20,  1.40,  0.01,  0.10,  1.40,  0.01,  0.30,  0.30,  0.30,  0.30,  0.00,  0.01,  0.01,  0.01,\n MFSNO =  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.00,  0.11,  0.11,  0.11,  0.11,  0.11,  0.11,  0.07,  0.10,  0.10,  0.10,  0.07,  0.10,  0.07,  0.10,  0.00,  0.11,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n RHOL_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.35,  0.45,  0.45,  0.45,  0.35,  0.45,  0.35,  0.45,  0.00,  0.58,  0.45,  0.00,  0.45,  0.45,  0.45,  0.45,  0.00,  0.45,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.00,  0.36,  0.36,  0.36,  0.36,  0.36,  0.36,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.00,  0.36,  0.16,  0.00,  0.16,  0.16,  0.16,  0.16,  0.00,  0.16,  0.00,  0.00,\n RHOS_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.00,  0.58,  0.39,  0.00,  0.39,  0.39,  0.39,  0.39,  0.00,  0.39,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.00,  0.07,  0.07,  0.07,  0.07,  0.07,  0.07,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.00,  0.07,  0.05,  0.00,  0.05,  0.05,  0.05,  0.05,  0.00,  0.05,  0.00,  0.00,\n TAUL_NIR=0.00,  0.25,  0.25,  0.25,  0.25,  0.25,  0.25,  0.10,  0.10,  0.25,  0.25,  0.10,  0.25,  0.10,  0.25,  0.00,  0.25,  0.25,  0.00,  0.25,  0.25,  0.25,  0.25,  0.00,  0.25,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.00, 0.220, 0.220, 0.220, 0.220, 0.220, 0.220, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.220, 0.001, 0.000, 0.220, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n TAUS_NIR=0.00, 0.380, 0.380, 0.380, 0.380, 0.380, 0.380, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.380, 0.001, 0.000, 0.380, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n\n XL    = 0.000, -0.30, -0.30, -0.30, -0.30, -0.30, -0.30, 0.010, 0.250, 0.010, 0.250, 0.010, 0.010, 0.010, 0.250, 0.000, -0.30, 0.250, 0.000, -0.30, 0.250, 0.250, 0.250, 0.000, 0.250, 0.000, 0.000,\n CWPVT =  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,\n C3PSN =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n KC25  =  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,\n AKC   =   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,\n KO25  =  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,\n AKO   =   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,\n AVCMX =   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,\n AQE   =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n\n LTOVRC=   0.0,   1.2,   1.2,   1.2,   1.2,  1.30,  0.50,  0.65,  0.70,  0.65,  0.55,   0.2,  0.55,   0.5,   0.5,   0.0,   1.4,   1.4,   0.0,   1.2,   1.3,   1.4,   1.0,   0.0,   1.0,   0.0,   0.0,\n DILEFC=  0.00,  0.50,  0.50,  0.50,  0.35,  0.20,  0.20,  0.20,  0.50,  0.50,  0.60,  1.80,  0.50,  1.20,  0.80,  0.00,  0.40,  0.40,  0.00,  0.40,  0.30,  0.40,  0.30,  0.00,  0.30,  0.00,  0.00,\n DILEFW=  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.20,  0.50,  0.20,  0.20,  4.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.20,  0.20,  0.00,  0.20,  0.00,  0.00,\n RMF25 =  0.00,  1.00,  1.40,  1.45,  1.45,  1.45,  1.80,  0.26,  0.26,  0.80,  3.00,  4.00,  0.65,  3.00,  3.00,  0.00,  3.20,  3.20,  0.00,  3.20,  3.00,  3.00,  3.00,  0.00,  3.00,  0.00,  0.00,\n SLA   =    60,    80,    80,    80,    80,    80,    60,    60,    60,    50,    80,    80,    80,    80,    80,     0,    80,    80,     0,    80,    80,    80,    80,     0,    80,     0,     0,\n FRAGR =  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n TMIN  =     0,   273,   273,   273,   273,   273,   273,   273,   273,   273,   273,   268,   273,   265,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n VCMX25=  0.00,  80.0,  80.0,  80.0,  60.0,  70.0,  40.0,  40.0,  40.0,  40.0,  60.0,  60.0,  60.0,  50.0,  55.0,  0.00,  50.0,  50.0,  0.00,  50.0,  50.0,  50.0,  50.0,  0.00,  50.0,  0.00,  0.00,\n TDLEF =   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   268,   278,   278,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n BP    = 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3, 1.E15, 1.E15,\n MP    =    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    6.,    9.,    6.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,\n QE25  =    0.,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.00,  0.00,\n RMS25 =  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.32,  0.10,  0.64,  0.30,  0.90,  0.80,  0.00,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.00,  0.00,  0.00,  0.00,  0.00,\n RMR25 =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.20,  0.00,  0.00,  0.01,  0.01,  0.05,  0.05,  0.36,  0.03,  0.00,  0.00,  0.00,  0.00,  2.11,  2.11,  2.11,  0.00,  0.00,  0.00,  0.00,  0.00,\n ARM   =   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,\n FOLNMX=  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,  0.00,  0.00,\n WDPOOL=  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  0.00,  0.00,  1.00,  0.00,  0.00,  1.00,  1.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n WRRAT =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  3.00,  3.00,  3.00,  30.0,  30.0,  30.0,  30.0,  30.0,  0.00,  0.00,  30.0,  0.00,  0.00,  3.00,  3.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n MRP   =  0.00,  0.23,  0.23,  0.23,  0.23,  0.23,  0.17,  0.19,  0.19,  0.40,  0.40,  0.37,  0.23,  0.37,  0.30,  0.00,  0.17,  0.40,  0.00,  0.17,  0.23,  0.20,  0.00,  0.00,  0.20,  0.00,  0.00,\n NROOT =     1,     3,     3,     3,     3,     3,     3,     3,     3,     3,     4,     4,     4,     4,     4,     0,     2,     2,     1,     3,     3,     3,     2,     1,     1,     0,     0,\n RGL   = 999.0, 100.0, 100.0, 100.0, 100.0,  65.0, 100.0, 100.0, 100.0,  65.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0, 100.0,  30.0, 999.0, 100.0, 100.0, 100.0, 100.0, 999.0, 100.0, 999.0, 999.0,\n RS    = 200.0,  40.0,  40.0,  40.0,  40.0,  70.0,  40.0, 300.0, 170.0,  70.0, 100.0, 150.0, 150.0, 125.0, 125.0, 100.0,  40.0, 100.0, 999.0, 150.0, 150.0, 150.0, 200.0, 999.0,  40.0, 999.0, 999.0,\n HS    = 999.0, 36.25, 36.25, 36.25, 36.25, 44.14, 36.35, 42.00, 39.18, 54.53, 54.53, 47.35, 41.69, 47.35, 51.93, 51.75, 60.00, 51.93, 999.0, 42.00, 42.00, 42.00, 42.00, 999.0, 36.25, 999.0, 999.0,\n TOPT  = 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0,\n RSMAX = 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_FEB = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_APR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.3,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAY = 0.0,   0.2,   0.2,   0.2,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.4,   0.4,   0.0,   0.3,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUN = 0.0,   0.3,   0.3,   0.3,   0.4,   0.4,   0.4,   0.2,   0.3,   0.4,   0.4,   0.7,   0.5,   0.5,   0.4,   0.0,   0.4,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUL = 0.0,   0.4,   0.4,   0.4,   0.6,   0.6,   0.8,   0.4,   0.6,   0.8,   0.9,   1.3,   0.5,   0.5,   0.7,   0.0,   0.6,   0.6,   0.0,   0.4,   0.4,   0.4,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_AUG = 0.0,   0.5,   0.5,   0.5,   0.9,   0.9,   1.3,   0.6,   0.9,   1.2,   1.2,   1.2,   0.5,   0.6,   0.8,   0.0,   0.9,   0.9,   0.0,   0.6,   0.6,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_SEP = 0.0,   0.4,   0.4,   0.4,   0.7,   1.0,   1.1,   0.8,   1.0,   1.3,   1.6,   1.0,   0.5,   0.6,   1.0,   0.0,   0.7,   1.0,   0.0,   0.7,   0.8,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_OCT = 0.0,   0.3,   0.3,   0.3,   0.3,   0.8,   0.4,   0.7,   0.6,   0.7,   1.4,   0.8,   0.5,   0.7,   1.0,   0.0,   0.3,   0.8,   0.0,   0.5,   0.7,   0.5,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_NOV = 0.0,   0.3,   0.3,   0.3,   0.3,   0.4,   0.4,   0.3,   0.3,   0.4,   0.6,   0.6,   0.5,   0.6,   0.5,   0.0,   0.3,   0.4,   0.0,   0.3,   0.3,   0.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_DEC = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.4,   0.2,   0.3,   0.4,   0.4,   0.5,   0.5,   0.5,   0.4,   0.0,   0.3,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n LAI_JAN = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_FEB = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.3,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAR = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.0,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_APR = 0.0,   0.0,   0.0,   0.0,   0.4,   0.6,   0.7,   0.6,   0.7,   0.8,   1.2,   0.6,   4.5,   4.0,   2.6,   0.0,   0.4,   0.6,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAY = 0.0,   1.0,   1.0,   1.0,   1.1,   2.0,   1.2,   1.5,   1.4,   1.8,   3.0,   1.2,   4.5,   4.0,   3.5,   0.0,   1.1,   2.0,   0.0,   0.6,   1.7,   1.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUN = 0.0,   2.0,   2.0,   2.0,   2.5,   3.3,   3.0,   2.3,   2.6,   3.6,   4.7,   2.0,   4.5,   4.0,   4.3,   0.0,   2.5,   3.3,   0.0,   1.5,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUL = 0.0,   3.0,   3.0,   3.0,   3.2,   3.7,   3.5,   2.3,   2.9,   3.8,   4.5,   2.6,   4.5,   4.0,   4.3,   0.0,   3.2,   3.7,   0.0,   1.7,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_AUG = 0.0,   3.0,   3.0,   3.0,   2.2,   3.2,   1.5,   1.7,   1.6,   2.1,   3.4,   1.7,   4.5,   4.0,   3.7,   0.0,   2.2,   3.2,   0.0,   0.8,   1.8,   1.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_SEP = 0.0,   1.5,   1.5,   1.5,   1.1,   1.3,   0.7,   0.6,   0.7,   0.9,   1.2,   1.0,   4.5,   4.0,   2.6,   0.0,   1.1,   1.3,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_OCT = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.5,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_NOV = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.2,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_DEC = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n SLAREA=0.0228,0.0200,0.0200,0.0295,0.0223,0.0277,0.0060,0.0227,0.0188,0.0236,0.0258,0.0200,0.0200,0.0090,0.0223,0.0422,0.0390,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1   = 41.87,  0.00,  0.00,  2.52,  0.04, 17.11,  0.02, 21.62,  0.11, 22.80, 46.86,  0.00,  0.00,  0.46, 30.98,  2.31,  1.63,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS2   =  0.98,  0.00,  0.00,  0.16,  0.09,  0.28,  0.05,  0.92,  0.22,  0.59,  0.38,  0.00,  0.00,  3.34,  0.96,  1.47,  1.07,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS3   =  1.82,  0.00,  0.00,  0.23,  0.05,  0.81,  0.03,  1.73,  1.26,  1.37,  1.84,  0.00,  0.00,  1.85,  1.84,  1.70,  1.21,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS4   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS5   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n/\n\n&noahmp_modis_veg_categories\n VEG_DATASET_DESCRIPTION = \"modified igbp modis noah\"\n NVEG = 20\n/\n\n&noahmp_modis_parameters\n! 1          'Evergreen Needleleaf Forest'                       -> USGS 14\n! 2,         'Evergreen Broadleaf Forest'                        -> USGS 13\n! 3,         'Deciduous Needleleaf Forest'                       -> USGS 12\n! 4,         'Deciduous Broadleaf Forest'                        -> USGS 11\n! 5,         'Mixed Forests'                                     -> USGS 15\n! 6,         'Closed Shrublands'                                 -> USGS  8 \"shrubland\"\n! 7,         'Open Shrublands'                                   -> USGS  9 \"shrubland/grassland\"\n! 8,         'Woody Savannas'                                    -> USGS  8 \"shrubland\"\n! 9,         'Savannas'                                          -> USGS 10\n! 10,        'Grasslands'                                        -> USGS  7\n! 11         'Permanent wetlands'                                -> avg of USGS 17 and 18 (herb. wooded wetland)\n! 12,        'Croplands'                                         -> USGS  2 \"dryland cropland\"\n! 13,        'Urban and Built-Up'                                -> USGS  1\n! 14         'cropland/natural vegetation mosaic'                -> USGS  5 \"cropland/grassland\"\n! 15,        'Snow and Ice'                                      -> USGS 24\n! 16,        'Barren or Sparsely Vegetated'                      -> USGS 19\n! 17,        'Water'                                             -> USGS 16\n! 18,        'Wooded Tundra'                                     -> USGS 21\n! 19,        'Mixed Tundra'                                      -> USGS 22\n! 20,        'Barren Tundra'                                     -> USGS 23\n\n ISURBAN                   = 13\n ISWATER                   = 17\n ISBARREN                  = 16\n ISICE                     = 15\n ISCROP                    = 12\n EBLFOREST                 =  2\n NATURAL                   = 14\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1       2       3       4       5       6       7       8       9      10      11      12      13      14      15      16      17      18      19      20\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,\n DLEAF =  0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,\n Z0MVT =  1.09,   1.10,   0.85,   0.80,   0.80,   0.20,   0.06,   0.60,   0.50,   0.12,   0.30,   0.15,   1.00,   0.14,   0.00,   0.00,   0.00,   0.30,   0.20,   0.03,\n HVT   =  20.0,   20.0,   18.0,   16.0,   16.0,   1.10,   1.10,   13.0,   10.0,   1.00,   5.00,   2.00,   15.0,   1.50,   0.00,   0.00,   0.00,   4.00,   2.00,   0.50,\n HVB   =  8.50,   8.00,   7.00,   11.5,   10.0,   0.10,   0.10,   0.10,   0.10,   0.05,   0.10,   0.10,   1.00,   0.10,   0.00,   0.00,   0.00,   0.30,   0.20,   0.10,\n DEN   =  0.28,   0.02,   0.28,   0.10,   0.10,   10.0,   10.0,   10.0,   0.02,   100.,   5.05,   25.0,   0.01,   25.0,   0.00,   0.01,   0.01,   1.00,   1.00,   1.00,\n RC    =  1.20,   3.60,   1.20,   1.40,   1.40,   0.12,   0.12,   0.12,   3.00,   0.03,   0.75,   0.08,   1.00,   0.08,   0.00,   0.01,   0.01,   0.30,   0.30,   0.30,\n MFSNO =  2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.07,   0.10,   0.07,   0.10,   0.10,   0.07,   0.07,   0.07,   0.10,   0.11,  0.105,   0.11,   0.00,   0.11,   0.00,   0.00,   0.00,   0.10,   0.10,   0.10,\n RHOL_NIR=0.35,   0.45,   0.35,   0.45,   0.45,   0.35,   0.35,   0.35,   0.45,   0.58,  0.515,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.45,   0.45,   0.45,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.36,   0.26,   0.36,   0.00,   0.36,   0.00,   0.00,   0.00,   0.16,   0.16,   0.16,\n RHOS_NIR=0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.58,  0.485,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.39,   0.39,   0.39,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.07,   0.06,   0.07,   0.00,   0.07,   0.00,   0.00,   0.00,   0.05,   0.05,   0.05,\n TAUL_NIR=0.10,   0.25,   0.10,   0.25,   0.25,   0.10,   0.10,   0.10,   0.25,   0.25,   0.25,   0.25,   0.00,   0.25,   0.00,   0.00,   0.00,   0.25,   0.25,   0.25,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.220, 0.1105,  0.220,  0.000,  0.220,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n TAUS_NIR=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.380, 0.1905,  0.380,  0.000,  0.380,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n\n XL    = 0.010,  0.010,  0.010,  0.250,  0.250,  0.010,  0.010,  0.010,  0.010,  -0.30, -0.025,  -0.30,  0.000,  -0.30,  0.000,  0.000,  0.000,  0.250,  0.250,  0.250,\n! CWPVT =   3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,\n CWPVT =  0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,\n C3PSN =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n KC25  =  30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,\n AKC   =   2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,\n KO25  =  3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,\n AKO   =   1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,\n AVCMX =   2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,\n AQE   =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n\n LTOVRC=   0.5,   0.55,    0.2,   0.55,    0.5,   0.65,   0.65,   0.65,   0.65,   0.50,    1.4,    1.6,    0.0,    1.2,    0.0,    0.0,    0.0,    1.3,    1.4,    1.0,\n DILEFC=  1.20,   0.50,   1.80,   0.60,   0.80,   0.20,   0.20,   0.20,   0.50,   0.20,    0.4,   0.50,   0.00,   0.35,   0.00,   0.00,   0.00,   0.30,   0.40,   0.30,\n DILEFW=  0.20,   4.00,   0.20,   0.20,   0.20,   0.20,   0.20,   0.20,   0.50,   0.10,    0.2,   0.20,   0.00,   0.20,   0.00,   0.00,   0.00,   0.20,   0.20,   0.20,\n RMF25 =  3.00,   0.65,   4.00,   3.00,   3.00,   0.26,   0.26,   0.26,   0.80,   1.80,    3.2,   1.00,   0.00,   1.45,   0.00,   0.00,   0.00,   3.00,   3.00,   3.00,\n SLA   =    80,     80,     80,     80,     80,     60,     60,     60,     50,     60,     80,     80,     60,     80,      0,      0,      0,     80,     80,     80,\n FRAGR =  0.10,   0.20,   0.10,   0.20,   0.10,   0.20,   0.20,   0.20,   0.20,   0.20,    0.1,   0.20,   0.00,   0.20,   0.00,   0.10,   0.00,   0.10,   0.10,   0.10,\n TMIN  =   265,    273,    268,    273,    268,    273,    273,    273,    273,    273,    268,    273,      0,    273,      0,      0,      0,    268,    268,    268,\n VCMX25=  50.0,   60.0,   60.0,   60.0,   55.0,   40.0,   40.0,   40.0,   40.0,   40.0,   50.0,   80.0,   0.00,   60.0,   0.00,   0.00,   0.00,   50.0,   50.0,   50.0,\n TDLEF =   278,    278,    268,    278,    268,    278,    278,    278,    278,    278,    268,    278,    278,    278,      0,      0,      0,    268,    268,    268,\n BP    =  2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,   2.E3,   2.E3,\n MP    =    6.,     9.,     6.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,\n QE25  =  0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.00,   0.06,   0.00,   0.06,   0.00,   0.06,   0.06,   0.06,\n RMS25 =  0.90,   0.30,   0.64,   0.10,   0.80,   0.10,   0.10,   0.10,   0.32,   0.10,   0.10,   0.10,   0.00,   0.10,   0.00,   0.00,   0.00,   0.10,   0.10,   0.00,\n RMR25 =  0.36,   0.05,   0.05,   0.01,   0.03,   0.00,   0.00,   0.00,   0.01,   1.20,    0.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   2.11,   2.11,   0.00,\n ARM   =   2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,\n FOLNMX=   1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,   0.00,    1.5,   0.00,    1.5,   0.00,    1.5,    1.5,    1.5,\n WDPOOL=  1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   0.00,    0.5,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   1.00,   1.00,   0.00,\n WRRAT =  30.0,   30.0,   30.0,   30.0,   30.0,   3.00,   3.00,   3.00,   3.00,   0.00,   15.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   3.00,   3.00,   0.00,\n MRP   =  0.37,   0.23,   0.37,   0.40,   0.30,   0.19,   0.19,   0.19,   0.40,   0.17,  0.285,   0.23,   0.00,   0.23,   0.00,   0.00,   0.00,   0.23,   0.20,   0.00,\n NROOT =     4,      4,      4,      4,      4,      3,      3,      3,      3,      3,      2,      3,      1,      3,      1,      1,      0,      3,      3,      2,     \n RGL   =  30.0,   30.0,   30.0,   30.0,   30.0,  100.0,  100.0,  100.0,   65.0,  100.0,   65.0,  100.0,  999.0,  100.0,  999.0,  999.0,   30.0,  100.0,  100.0,  100.0,\n RS    = 125.0,  150.0,  150.0,  100.0,  125.0,  300.0,  170.0,  300.0,   70.0,   40.0,   70.0,   40.0,  200.0,   40.0,  999.0,  999.0,  100.0,  150.0,  150.0,  200.0,\n HS    = 47.35,  41.69,  47.35,  54.53,  51.93,  42.00,  39.18,  42.00,  54.53,  36.35,  55.97,  36.25,  999.0,  36.25,  999.0,  999.0,  51.75,  42.00,  42.00,  42.00,\n TOPT  = 298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,\n RSMAX = 5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_FEB = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAR = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_APR = 0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAY = 0.4,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_JUN = 0.5,    0.5,    0.7,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.4,    0.3,    0.0,    0.4,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n SAI_JUL = 0.5,    0.5,    1.3,    0.9,    0.7,    0.6,    0.4,    0.7,    0.8,    0.8,    0.6,    0.4,    0.0,    0.6,    0.0,    0.0,    0.0,    0.4,    0.4,    0.0,\n SAI_AUG = 0.6,    0.5,    1.2,    1.2,    0.8,    0.9,    0.6,    1.2,    1.2,    1.3,    0.9,    0.5,    0.0,    0.9,    0.0,    0.0,    0.0,    0.6,    0.6,    0.0,\n SAI_SEP = 0.6,    0.5,    1.0,    1.6,    1.0,    1.2,    0.8,    1.4,    1.3,    1.1,    0.9,    0.4,    0.0,    0.7,    0.0,    0.0,    0.0,    0.8,    0.7,    0.0,\n SAI_OCT = 0.7,    0.5,    0.8,    1.4,    1.0,    0.9,    0.7,    1.1,    0.7,    0.4,    0.6,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.7,    0.5,    0.0,\n SAI_NOV = 0.6,    0.5,    0.6,    0.6,    0.5,    0.4,    0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.3,    0.3,    0.0,\n SAI_DEC = 0.5,    0.5,    0.5,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n\n LAI_JAN = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_FEB = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_MAR = 4.0,    4.5,    0.0,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_APR = 4.0,    4.5,    0.6,    1.2,    2.6,    0.9,    0.6,    1.0,    0.8,    0.7,    0.5,    0.0,    0.0,    0.4,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_MAY = 4.0,    4.5,    1.2,    3.0,    3.5,    2.2,    1.5,    2.4,    1.8,    1.2,    1.5,    1.0,    0.0,    1.1,    0.0,    0.0,    0.0,    1.7,    1.2,    0.0,\n LAI_JUN = 4.0,    4.5,    2.0,    4.7,    4.3,    3.5,    2.3,    4.1,    3.6,    3.0,    2.9,    2.0,    0.0,    2.5,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_JUL = 4.0,    4.5,    2.6,    4.5,    4.3,    3.5,    2.3,    4.1,    3.8,    3.5,    3.5,    3.0,    0.0,    3.2,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_AUG = 4.0,    4.5,    1.7,    3.4,    3.7,    2.5,    1.7,    2.7,    2.1,    1.5,    2.7,    3.0,    0.0,    2.2,    0.0,    0.0,    0.0,    1.8,    1.3,    0.0,\n LAI_SEP = 4.0,    4.5,    1.0,    1.2,    2.6,    0.9,    0.6,    1.0,    0.9,    0.7,    1.2,    1.5,    0.0,    1.1,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_OCT = 4.0,    4.5,    0.5,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_NOV = 4.0,    4.5,    0.2,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_DEC = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n\n SLAREA=0.0090, 0.0200, 0.0200, 0.0258, 0.0223, 0.0227, 0.0188, 0.0227, 0.0236, 0.0060, 0.0295, 0.0200, 0.0228, 0.0223,   0.02,   0.02, 0.0422,   0.02,   0.02,   0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1  =  0.46,   0.00,   0.00,  46.86,  30.98,  21.62,   0.11,  21.62,  22.80,   0.02,  0.815,   0.00,  41.87,   0.04,    0.0,    0.0,   2.31,    0.0,    0.0,    0.0,\n EPS2  =  3.34,   0.00,   0.00,   0.38,   0.96,   0.92,   0.22,   0.92,   0.59,   0.05,  0.535,   0.00,   0.98,   0.09,    0.0,    0.0,   1.47,    0.0,    0.0,    0.0,\n EPS3  =  1.85,   0.00,   0.00,   1.84,   1.84,   1.73,   1.26,   1.73,   1.37,   0.03,  0.605,   0.00,   1.82,   0.05,    0.0,    0.0,   1.70,    0.0,    0.0,    0.0,\n EPS4  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n EPS5  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n\n/\n\n&noahmp_rad_parameters\n !------------------------------------------------------------------------------\n !                1       2       3       4       5       6       7       8     soil color index for soil albedo\n !------------------------------------------------------------------------------\n ALBSAT_VIS =   0.15,   0.11,   0.10,   0.09,   0.08,   0.07,   0.06,   0.05   ! saturated soil albedos\n ALBSAT_NIR =   0.30,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! saturated soil albedos\n ALBDRY_VIS =   0.27,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! dry soil albedos\n ALBDRY_NIR =   0.54,   0.44,   0.40,   0.36,   0.32,   0.28,   0.24,   0.20   ! dry soil albedos\n ALBICE     =   0.80,   0.55                                                   ! albedo land ice: 1=vis, 2=nir\n ALBLAK     =   0.60,   0.40                                                   ! albedo frozen lakes: 1=vis, 2=nir\n OMEGAS     =   0.8 ,   0.4                                                    ! two-stream parameter omega for snow\n BETADS     =   0.5                                                            ! two-stream parameter betad for snow\n BETAIS     =   0.5                                                            ! two-stream parameter betaI for snow\n EG         =   0.97,   0.98                                                   ! emissivity soil surface 1-soil;2-lake\n\n/\n\n&noahmp_global_parameters\n\n! atmospheric constituants\n\n  CO2    = 395.e-06     !co2 partial pressure\n  O2     = 0.209        !o2 partial pressure\n\n! runoff parameters used for SIMTOP and SIMGM:\n\n  TIMEAN = 10.5         !gridcell mean topgraphic index (global mean)\n  FSATMX = 0.38         !maximum surface saturated fraction (global mean)\n\n! adjustable parameters for snow processes\n\n  Z0SNO  = 0.002        !snow surface roughness length (m) (0.002)\n  SSI    = 0.03         !liquid water holding capacity for snowpack (m3/m3) (0.03)\n  SNOW_RET_FAC  = 5.e-5 !snowpack water release timescale factor (1/s)\n  SWEMX  = 1.00         !new snow mass to fully cover old snow (mm)\n                        !equivalent to 10mm depth (density = 100 kg/m3)\n  TAU0          = 1.e6  !tau0 from Yang97 eqn. 10a\n  GRAIN_GROWTH  = 5000. !growth from vapor diffusion Yang97 eqn. 10b\n  EXTRA_GROWTH  = 10.   !extra growth near freezing Yang97 eqn. 10c\n  DIRT_SOOT     = 0.3   !dirt and soot term Yang97 eqn. 10d\n  BATS_COSZ     = 2.0   !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n  BATS_VIS_NEW  = 0.95  !new snow visible albedo\n  BATS_NIR_NEW  = 0.65  !new snow NIR albedo\n  BATS_VIS_AGE  = 0.2   !age factor for diffuse visible snow albedo Yang97 eqn. 17\n  BATS_NIR_AGE  = 0.5   !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n  BATS_VIS_DIR  = 0.4   !cosz factor for direct visible snow albedo Yang97 eqn. 15\n  BATS_NIR_DIR  = 0.4   !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n  RSURF_SNOW = 50.0     !surface resistence for snow [s/m]\n  RSURF_EXP = 5.0       !exponent in the shape parameter for soil resistance option 1\n  IMPERV_URBAN = 0.95   !impervious fraction to use for urban type [0-1]\n  SCAMAX = 1.0          !maximum fractional snow covered area [0-1]\n  SWE_LIMIT = 5000000.0    !maximum SWE limit [mm]\n\n/\n\n&noahmp_crop_parameters\n\n ! NCROP = 5\n !  1: Corn\n !  2: Soybean\n !  3: Sorghum\n !  4: Rice\n !  5: Winter wheat\n\nDEFAULT_CROP = 0                                      ! The default crop type(1-5); if zero, use generic dynamic vegetation \n\n!----------------------------------------------------------\n!                1       2       3       4       5\n!----------------------------------------------------------\n \nPLTDAY     =    130,    111,    111,    111,    111,  ! Planting date\nHSDAY      =    280,    300,    300,    300,    300,  ! Harvest date\nPLANTPOP   =   78.0,   78.0,   78.0,   78.0,   78.0,  ! Plant density [per ha] - used?\nIRRI       =    0.0,    0.0,    0.0,    0.0,    0.0,  ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n\nGDDTBASE   =   10.0,   10.0,   10.0,   10.0,   10.0,  ! Base temperature for GDD accumulation [C]\nGDDTCUT    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! Upper temperature for GDD accumulation [C]\nGDDS1      =   60.0,   50.0,   50.0,   50.0,   50.0,  ! GDD from seeding to emergence\nGDDS2      =  675.0,  718.0,  718.0,  718.0,  718.0,  ! GDD from seeding to initial vegetative \nGDDS3      = 1183.0,  933.0,  933.0,  933.0,  933.0,  ! GDD from seeding to post vegetative \nGDDS4      = 1253.0, 1103.0, 1103.0, 1103.0, 1103.0,  ! GDD from seeding to intial reproductive\nGDDS5      = 1605.0, 1555.0, 1555.0, 1555.0, 1555.0,  ! GDD from seeding to pysical maturity \n\nC3C4       =      2,      1,      2,      2,      2,  ! photosynthetic pathway:  1. = c3 2. = c4\nAref       =    7.0,    7.0,    7.0,    7.0,    7.0,  ! reference maximum CO2 assimulation rate \nPSNRF      =   0.85,   0.85,   0.85,   0.85,   0.85,  ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\nI2PAR      =    0.5,    0.5,    0.5,    0.5,    0.5,  ! Fraction of incoming solar radiation to photosynthetically active radiation\nTASSIM0    =    8.0,    8.0,    8.0,    8.0,    8.0,  ! Minimum temperature for CO2 assimulation [C]\nTASSIM1    =   18.0,   18.0,   18.0,   18.0,   18.0,  ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\nTASSIM2    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\nK          =   0.55,   0.55,   0.55,   0.55,   0.55,  ! light extinction coefficient\nEPSI       =   12.5,   12.5,   12.5,   12.5,   12.5,  ! initial light use efficiency\n\nQ10MR      =    2.0,    2.0,    2.0,    2.0,    2.0,  ! q10 for maintainance respiration\nFOLN_MX    =    1.5,    1.5,    1.5,    1.5,    1.5,  ! foliage nitrogen concentration when f(n)=1 (%)\nLEFREEZ    =    268,    268,    268,    268,    268,  ! characteristic T for leaf freezing [K]\n\nDILE_FC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for temperature leaf stress death [1/s]\nDILE_FC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0, \nDILE_FC_S5 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S6 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nDILE_FW_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for water leaf stress death [1/s]\nDILE_FW_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FW_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S5 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S6 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nFRA_GR     =    0.2,    0.2,    0.2,    0.2,    0.2,  ! fraction of growth respiration\n\nLF_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of leaf turnover  [1/s]\nLF_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLF_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S5 =    0.2,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S6 =    0.3,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nST_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of stem turnover  [1/s]\nST_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nST_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nST_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nST_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nRT_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of root tunrover  [1/s]\nRT_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRT_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nRT_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nRT_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n             \nLFMR25     =    1.0,    1.0,    1.0,    1.0,    1.0,  !  leaf maintenance respiration at 25C [umol CO2/m**2  /s]\nSTMR25     =   0.05,    0.1,    0.1,    0.1,    0.1,  !  stem maintenance respiration at 25C [umol CO2/kg bio/s]\nRTMR25     =   0.05,    0.0,    0.0,    0.0,    0.0,  !  root maintenance respiration at 25C [umol CO2/kg bio/s]\nGRAINMR25  =    0.0,    0.1,    0.1,    0.1,    0.1,  ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n\nLFPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to leaf\nLFPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLFPT_S3    =    0.4,    0.4,    0.4,    0.4,    0.4,\nLFPT_S4    =    0.2,    0.2,    0.2,    0.2,    0.2,\nLFPT_S5    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S6    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nSTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to stem\nSTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nSTPT_S3    =    0.2,    0.2,    0.2,    0.2,    0.2,\nSTPT_S4    =    0.5,    0.5,    0.5,    0.5,    0.5,\nSTPT_S5    =    0.0,   0.15,   0.15,   0.15,   0.15,\nSTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nSTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nSTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0, \n\nRTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to root\nRTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRTPT_S3    =   0.34,    0.4,    0.4,    0.4,    0.4,\nRTPT_S4    =    0.3,    0.3,    0.3,    0.3,    0.3,\nRTPT_S5    =   0.05,   0.05,   0.05,   0.05,   0.05,\nRTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nRTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nRTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n   \nGRAINPT_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to grain\nGRAINPT_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nGRAINPT_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S5 =   0.95,    0.8,    0.8,    0.8,    0.8,\nGRAINPT_S6 =    1.0,    0.9,    0.9,    0.9,    0.9,\nGRAINPT_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n\nBIO2LAI   =  0.035,  0.015,  0.015,  0.015,  0.015,  ! leaf are per living leaf biomass [m^2/kg]\n\n/\n\n&noahmp_optional_parameters\n\n !------------------------------------------------------------------------------\n ! Saxton and Rawls 2006 Pedo-transfer function coefficients\n !------------------------------------------------------------------------------\n\n sr2006_theta_1500t_a =   -0.024   ! sand coefficient\n sr2006_theta_1500t_b =    0.487   ! clay coefficient\n sr2006_theta_1500t_c =    0.006   ! orgm coefficient\n sr2006_theta_1500t_d =    0.005   ! sand*orgm coefficient\n sr2006_theta_1500t_e =   -0.013   ! clay*orgm coefficient\n sr2006_theta_1500t_f =    0.068   ! sand*clay coefficient\n sr2006_theta_1500t_g =    0.031   ! constant adjustment\n\n sr2006_theta_1500_a  =    0.14    ! theta_1500t coefficient\n sr2006_theta_1500_b  =   -0.02    ! constant adjustment\n\n sr2006_theta_33t_a   =   -0.251   ! sand coefficient\n sr2006_theta_33t_b   =    0.195   ! clay coefficient\n sr2006_theta_33t_c   =    0.011   ! orgm coefficient\n sr2006_theta_33t_d   =    0.006   ! sand*orgm coefficient\n sr2006_theta_33t_e   =   -0.027   ! clay*orgm coefficient\n sr2006_theta_33t_f   =    0.452   ! sand*clay coefficient\n sr2006_theta_33t_g   =    0.299   ! constant adjustment\n\n sr2006_theta_33_a    =    1.283   ! theta_33t*theta_33t coefficient\n sr2006_theta_33_b    =   -0.374   ! theta_33t coefficient\n sr2006_theta_33_c    =   -0.015   ! constant adjustment\n\n sr2006_theta_s33t_a  =    0.278   ! sand coefficient\n sr2006_theta_s33t_b  =    0.034   ! clay coefficient\n sr2006_theta_s33t_c  =    0.022   ! orgm coefficient\n sr2006_theta_s33t_d  =   -0.018   ! sand*orgm coefficient\n sr2006_theta_s33t_e  =   -0.027   ! clay*orgm coefficient\n sr2006_theta_s33t_f  =   -0.584   ! sand*clay coefficient\n sr2006_theta_s33t_g  =    0.078   ! constant adjustment\n\n sr2006_theta_s33_a   =    0.636   ! theta_s33t coefficient\n sr2006_theta_s33_b   =   -0.107   ! constant adjustment\n\n sr2006_psi_et_a      =  -21.67    ! sand coefficient\n sr2006_psi_et_b      =  -27.93    ! clay coefficient\n sr2006_psi_et_c      =  -81.97    ! theta_s33 coefficient\n sr2006_psi_et_d      =   71.12    ! sand*theta_s33 coefficient\n sr2006_psi_et_e      =    8.29    ! clay*theta_s33 coefficient\n sr2006_psi_et_f      =   14.05    ! sand*clay coefficient\n sr2006_psi_et_g      =   27.16    ! constant adjustment\n\n sr2006_psi_e_a       =    0.02    ! psi_et*psi_et coefficient\n sr2006_psi_e_b       =   -0.113   ! psi_et coefficient\n sr2006_psi_e_c       =   -0.7     ! constant adjustment\n\n sr2006_smcmax_a      =   -0.097   ! sand adjustment\n sr2006_smcmax_b      =    0.043   ! constant adjustment\n \n/\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Alaska/SOILPARM.TBL",
    "content": "Soil Parameters\nSTAS\n19,1   'BB      DRYSMC      F11     MAXSMC   REFSMC   SATPSI  SATDK      SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     2.79,    0.010,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,   0.010,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.74,    0.047,    -0.569,   0.434,   0.312,   0.141,  5.23E-6,  8.05E-6,   0.047,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.33,    0.084,     0.162,   0.476,   0.360,   0.759,  2.81E-6,  2.39E-5,   0.084,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     3.86,    0.061,     0.162,   0.484,   0.347,   0.955,  2.18E-6,  1.66E-5,   0.061,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     6.77,    0.069,    -1.491,   0.404,   0.315,   0.135,  4.45E-6,  1.01E-5,   0.069,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     8.72,    0.120,    -1.118,   0.464,   0.387,   0.617,  2.03E-6,  2.35E-5,   0.120,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.17,    0.103,    -1.297,   0.465,   0.382,   0.263,  2.45E-6,  1.13E-5,   0.103,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.73,    0.100,    -3.209,   0.406,   0.338,   0.098,  7.22E-6,  1.87E-5,   0.100,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.39,    0.126,    -1.916,   0.468,   0.404,   0.324,  1.34E-6,  9.64E-6,   0.126,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.55,    0.138,    -2.138,   0.468,   0.412,   0.468,  9.74E-7,  1.12E-5,   0.138,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,       0.0,     1.0,     0.0,     0.0,      0.0,      0.0,     0.0,  0.60,  0.001,  0.00,  0.00, 'WATER'\n15,    2.79,    0.006,    -1.111,    0.20,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.07,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.25,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.55,    0.030,   -10.472,   0.468,   0.454,   0.468,  9.74E-7,  1.12E-5,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    2.79,    0.006,    -0.472,   0.200,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    2.79,     0.01,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,    0.01,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\nSoil Parameters\nSTAS-RUC\n19,1   'BB      DRYSMC       HC     MAXSMC   REFSMC   SATPSI  SATDK       SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     4.05,    0.002,      1.47,   0.395,   0.174,   0.121,  1.76E-4,  0.608E-6,   0.033,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.38,    0.035,      1.41,   0.410,   0.179,   0.090,  1.56E-4,  0.514E-5,   0.055,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.90,    0.041,      1.34,   0.435,   0.249,   0.218,  3.47E-5,  0.805E-5,   0.095,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.39,    0.050,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.137,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     7.12,    0.068,      1.18,   0.420,   0.299,   0.299,  6.30E-6,  0.990E-5,   0.148,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     7.75,    0.060,      1.32,   0.477,   0.357,   0.356,  1.70E-6,  0.237E-4,   0.208,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.52,    0.085,      1.23,   0.476,   0.391,   0.630,  2.45E-6,  0.113E-4,   0.230,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.40,    0.100,      1.18,   0.426,   0.316,   0.153,  2.17E-6,  0.187E-4,   0.210,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.40,    0.070,      1.15,   0.492,   0.409,   0.490,  1.03E-6,  0.964E-5,   0.250,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.40,    0.068,      1.09,   0.482,   0.400,   0.405,  1.28E-6,  0.112E-4,   0.268,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.39,    0.027,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.117,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,      4.18,   1.0,     1.0,     0.0,      0.0,       0.0,     0.0,    0.00,  0.001,  0.00,  0.00, 'WATER'\n15,    4.05,    0.004,      2.03,   0.200,   0.10 ,   0.121,  1.41E-4,  0.136E-3,   0.006,  0.60,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.90,    0.065,      2.10,   0.435,   0.249,   0.218,  3.47E-5,  0.514E-5,   0.114,  0.05,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.40,    0.030,      1.41,   0.468,   0.454,   0.468,  9.74E-7,  0.112E-4,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    4.05,    0.006,      1.41,   0.200,   0.17,    0.069,  1.41E-4,  0.136E-3,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    4.05,     0.01,      1.47,   0.339,   0.236,   0.069,  1.76E-4,  0.608E-6,   0.060,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\n\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/CONUS/CHANPARM.TBL",
    "content": "Channel Parameters\nStreamOrder\n10,1,  'Bw     HLINK   ChSSlp   MannN'\n1,     1.6,    0.02,    0.03,      0.09\n2,     2.4,    0.02,    0.03,      0.07\n3,     3.5,    0.02,    0.03,      0.06\n4,     5.3,    0.03,    0.04,      0.05\n5,     7.4,    0.03,    0.04,      0.04\n6,     11.,    0.03,    0.04,      0.03\n7,     14.,    0.03,    0.04,      0.03\n8,     16.,    0.10,    0.04,      0.02\n9,     26.,    0.30,    0.05,      0.02\n10,    110.,    0.30,    0.10,      0.02\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/CONUS/GENPARM.TBL",
    "content": "General Parameters\nSLOPE_DATA\n9\n0.1 \n0.6\n1.0\n0.35\n0.55\n0.8\n0.63\n0.0\n0.0\nSBETA_DATA\n-2.0\nFXEXP_DATA\n2.0\nCSOIL_DATA\n2.00E+6\nSALP_DATA\n2.6\nREFDK_DATA\n2.0E-6\nREFKDT_DATA\n3.0\nFRZK_DATA\n0.15\nZBOT_DATA\n-8.0\nCZIL_DATA\n0.1\nSMLOW_DATA\n0.5\nSMHIGH_DATA\n3.0\nLVCOEF_DATA\n0.5\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/CONUS/HYDRO.TBL",
    "content": "     28 USGS for OV_ROUGH\n   SFC_ROUGH'\n     0.025,    'Urban and Built-Up Land'  \n     0.035,    'Dryland Cropland and Pasture' \n     0.035,    'Irrigated Cropland and Pasture' \n     0.055,    'Mixed Dryland/Irrigated Cropland and Pasture' \n     0.035,    'Cropland/Grassland Mosaic'\n     0.068,    'Cropland/Woodland Mosaic' \n     0.055,    'Grassland' \n     0.055,    'Shrubland' \n     0.055,    'Mixed Shrubland/Grassland' \n     0.055,    'Savanna' \n     0.200,    'Deciduous Broadleaf Forest' \n     0.200,    'Deciduous Needleleaf Forest' \n     0.200,    'Evergreen Broadleaf Forest'\n     0.200,    'Evergreen Needleleaf Forest'  \n     0.200,    'Mixed Forest' \n     0.005,    'Water Bodies' \n     0.070,    'Herbaceous Wetland' \n     0.070,    'Wooded Wetland' \n     0.035,    'Barren or Sparsely Vegetated' \n     0.055,    'Herbaceous Tundra' \n     0.055,    'Wooded Tundra' \n     0.055,    'Mixed Tundra' \n     0.055,    'Bare Ground Tundra' \n     0.010,    'Snow or Ice' \n     0.010,    'Playa' \n     0.100,    'Lava'   \n     0.010,    'White Sand' \n     0.005,    'Non-Ocean Water Bodies'\n19, for SATDK\nSATDK     MAXSMC    REFSMC   WLTSMC  QTZ    '\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'SAND'\n1.41E-5,  0.421,    0.283,   0.028,  0.82, 'LOAMY SAND'\n5.23E-6,  0.434,    0.312,   0.047,  0.60, 'SANDY LOAM'\n2.81E-6,  0.476,    0.360,   0.084,  0.25, 'SILT LOAM'\n2.18E-6,  0.484,    0.347,   0.061,  0.10, 'SILT'\n3.38E-6,  0.439,    0.329,   0.066,  0.40, 'LOAM'\n4.45E-6,  0.404,    0.315,   0.069,  0.60, 'SANDY CLAY LOAM'\n2.03E-6,  0.464,    0.387,   0.120,  0.10, 'SILTY CLAY LOAM'\n2.45E-6,  0.465,    0.382,   0.103,  0.35, 'CLAY LOAM'\n7.22E-6,  0.406,    0.338,   0.100,  0.52, 'SANDY CLAY'\n1.34E-6,  0.468,    0.404,   0.126,  0.10, 'SILTY CLAY'\n9.74E-7,  0.468,    0.412,   0.138,  0.25, 'CLAY'\n3.38E-6,  0.439,    0.329,   0.066,  0.05, 'ORGANIC MATERIAL'\n    0.0,  1.0,      0.0,     0.0,    0.60, 'WATER'\n1.41E-4,  0.20,     0.170,   0.006,  0.07, 'BEDROCK'\n1.41E-5,  0.421,    0.283,   0.028,  0.25, 'OTHER(land-ice)'\n9.74E-7,  0.468,    0.454,   0.030,  0.60, 'PLAYA'\n1.41E-4,  0.200,    0.170,   0.006,  0.52, 'LAVA'\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'WHITE SAND'\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/CONUS/MPTABLE.TBL",
    "content": "&noahmp_usgs_veg_categories\n VEG_DATASET_DESCRIPTION = \"USGS\"\n NVEG = 27\n/\n&noahmp_usgs_parameters\n ! NVEG = 27\n !  1: Urban and Built-Up Land\n !  2: Dryland Cropland and Pasture\n !  3: Irrigated Cropland and Pasture\n !  4: Mixed Dryland/Irrigated Cropland and Pasture\n !  5: Cropland/Grassland Mosaic\n !  6: Cropland/Woodland Mosaic\n !  7: Grassland\n !  8: Shrubland\n !  9: Mixed Shrubland/Grassland\n ! 10: Savanna\n ! 11: Deciduous Broadleaf Forest\n ! 12: Deciduous Needleleaf Forest\n ! 13: Evergreen Broadleaf Forest\n ! 14: Evergreen Needleleaf Forest\n ! 15: Mixed Forest\n ! 16: Water Bodies\n ! 17: Herbaceous Wetland\n ! 18: Wooded Wetland\n ! 19: Barren or Sparsely Vegetated\n ! 20: Herbaceous Tundra\n ! 21: Wooded Tundra\n ! 22: Mixed Tundra\n ! 23: Bare Ground Tundra\n ! 24: Snow or Ice\n ! 25: Playa\n ! 26: Lava\n ! 27: White Sand\n\n ISURBAN                   =  1\n ISWATER                   = 16\n ISBARREN                  = 19\n ISICE                     = 24\n ISCROP                    =  2\n EBLFOREST                 = 13\n NATURAL                   =  5\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1      2      3      4      5      6      7      8      9      10     11     12     13     14     15     16     17     18     19     20     21     22     23     24     25     26    27\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,\n DLEAF =  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,\n Z0MVT =  1.00,  0.15,  0.15,  0.15,  0.14,  0.50,  0.12,  0.06,  0.09,  0.50,  0.80,  0.85,  1.10,  1.09,  0.80,  0.00,  0.12,  0.50,  0.00,  0.10,  0.30,  0.20,  0.03,  0.00,  0.01,  0.00,  0.00,\n HVT   =  15.0,  2.00,  2.00,  2.00,  1.50,  8.00,  1.00,  1.10,  1.10,  10.0,  16.0,  18.0,  20.0,  20.0,  16.0,  0.00,  0.50,  10.0,  0.00,  0.50,  4.00,  2.00,  0.50,  0.00,  0.10,  0.00,  0.00,\n HVB   =  1.00,  0.10,  0.10,  0.10,  0.10,  0.15,  0.05,  0.10,  0.10,  0.10,  11.5,  7.00,  8.00,  8.50,  10.0,  0.00,  0.05,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n DEN   =  0.01,  25.0,  25.0,  25.0,  25.0,  25.0,  100.,  10.0,  10.0,  0.02,  0.10,  0.28,  0.02,  0.28,  0.10,  0.01,  10.0,  0.10,  0.01,  1.00,  1.00,  1.00,  1.00,  0.00,  0.01,  0.01,  0.01,\n RC    =  1.00,  0.08,  0.08,  0.08,  0.08,  0.08,  0.03,  0.12,  0.12,  3.00,  1.40,  1.20,  3.60,  1.20,  1.40,  0.01,  0.10,  1.40,  0.01,  0.30,  0.30,  0.30,  0.30,  0.00,  0.01,  0.01,  0.01,\n MFSNO =  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.00,  0.11,  0.11,  0.11,  0.11,  0.11,  0.11,  0.07,  0.10,  0.10,  0.10,  0.07,  0.10,  0.07,  0.10,  0.00,  0.11,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n RHOL_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.35,  0.45,  0.45,  0.45,  0.35,  0.45,  0.35,  0.45,  0.00,  0.58,  0.45,  0.00,  0.45,  0.45,  0.45,  0.45,  0.00,  0.45,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.00,  0.36,  0.36,  0.36,  0.36,  0.36,  0.36,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.00,  0.36,  0.16,  0.00,  0.16,  0.16,  0.16,  0.16,  0.00,  0.16,  0.00,  0.00,\n RHOS_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.00,  0.58,  0.39,  0.00,  0.39,  0.39,  0.39,  0.39,  0.00,  0.39,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.00,  0.07,  0.07,  0.07,  0.07,  0.07,  0.07,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.00,  0.07,  0.05,  0.00,  0.05,  0.05,  0.05,  0.05,  0.00,  0.05,  0.00,  0.00,\n TAUL_NIR=0.00,  0.25,  0.25,  0.25,  0.25,  0.25,  0.25,  0.10,  0.10,  0.25,  0.25,  0.10,  0.25,  0.10,  0.25,  0.00,  0.25,  0.25,  0.00,  0.25,  0.25,  0.25,  0.25,  0.00,  0.25,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.00, 0.220, 0.220, 0.220, 0.220, 0.220, 0.220, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.220, 0.001, 0.000, 0.220, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n TAUS_NIR=0.00, 0.380, 0.380, 0.380, 0.380, 0.380, 0.380, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.380, 0.001, 0.000, 0.380, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n\n XL    = 0.000, -0.30, -0.30, -0.30, -0.30, -0.30, -0.30, 0.010, 0.250, 0.010, 0.250, 0.010, 0.010, 0.010, 0.250, 0.000, -0.30, 0.250, 0.000, -0.30, 0.250, 0.250, 0.250, 0.000, 0.250, 0.000, 0.000,\n CWPVT =  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,\n C3PSN =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n KC25  =  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,\n AKC   =   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,\n KO25  =  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,\n AKO   =   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,\n AVCMX =   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,\n AQE   =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n\n LTOVRC=   0.0,   1.2,   1.2,   1.2,   1.2,  1.30,  0.50,  0.65,  0.70,  0.65,  0.55,   0.2,  0.55,   0.5,   0.5,   0.0,   1.4,   1.4,   0.0,   1.2,   1.3,   1.4,   1.0,   0.0,   1.0,   0.0,   0.0,\n DILEFC=  0.00,  0.50,  0.50,  0.50,  0.35,  0.20,  0.20,  0.20,  0.50,  0.50,  0.60,  1.80,  0.50,  1.20,  0.80,  0.00,  0.40,  0.40,  0.00,  0.40,  0.30,  0.40,  0.30,  0.00,  0.30,  0.00,  0.00,\n DILEFW=  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.20,  0.50,  0.20,  0.20,  4.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.20,  0.20,  0.00,  0.20,  0.00,  0.00,\n RMF25 =  0.00,  1.00,  1.40,  1.45,  1.45,  1.45,  1.80,  0.26,  0.26,  0.80,  3.00,  4.00,  0.65,  3.00,  3.00,  0.00,  3.20,  3.20,  0.00,  3.20,  3.00,  3.00,  3.00,  0.00,  3.00,  0.00,  0.00,\n SLA   =    60,    80,    80,    80,    80,    80,    60,    60,    60,    50,    80,    80,    80,    80,    80,     0,    80,    80,     0,    80,    80,    80,    80,     0,    80,     0,     0,\n FRAGR =  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n TMIN  =     0,   273,   273,   273,   273,   273,   273,   273,   273,   273,   273,   268,   273,   265,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n VCMX25=  0.00,  80.0,  80.0,  80.0,  60.0,  70.0,  40.0,  40.0,  40.0,  40.0,  60.0,  60.0,  60.0,  50.0,  55.0,  0.00,  50.0,  50.0,  0.00,  50.0,  50.0,  50.0,  50.0,  0.00,  50.0,  0.00,  0.00,\n TDLEF =   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   268,   278,   278,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n BP    = 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3, 1.E15, 1.E15,\n MP    =    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    6.,    9.,    6.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,\n QE25  =    0.,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.00,  0.00,\n RMS25 =  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.32,  0.10,  0.64,  0.30,  0.90,  0.80,  0.00,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.00,  0.00,  0.00,  0.00,  0.00,\n RMR25 =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.20,  0.00,  0.00,  0.01,  0.01,  0.05,  0.05,  0.36,  0.03,  0.00,  0.00,  0.00,  0.00,  2.11,  2.11,  2.11,  0.00,  0.00,  0.00,  0.00,  0.00,\n ARM   =   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,\n FOLNMX=  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,  0.00,  0.00,\n WDPOOL=  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  0.00,  0.00,  1.00,  0.00,  0.00,  1.00,  1.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n WRRAT =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  3.00,  3.00,  3.00,  30.0,  30.0,  30.0,  30.0,  30.0,  0.00,  0.00,  30.0,  0.00,  0.00,  3.00,  3.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n MRP   =  0.00,  0.23,  0.23,  0.23,  0.23,  0.23,  0.17,  0.19,  0.19,  0.40,  0.40,  0.37,  0.23,  0.37,  0.30,  0.00,  0.17,  0.40,  0.00,  0.17,  0.23,  0.20,  0.00,  0.00,  0.20,  0.00,  0.00,\n NROOT =     1,     3,     3,     3,     3,     3,     3,     3,     3,     3,     4,     4,     4,     4,     4,     0,     2,     2,     1,     3,     3,     3,     2,     1,     1,     0,     0,\n RGL   = 999.0, 100.0, 100.0, 100.0, 100.0,  65.0, 100.0, 100.0, 100.0,  65.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0, 100.0,  30.0, 999.0, 100.0, 100.0, 100.0, 100.0, 999.0, 100.0, 999.0, 999.0,\n RS    = 200.0,  40.0,  40.0,  40.0,  40.0,  70.0,  40.0, 300.0, 170.0,  70.0, 100.0, 150.0, 150.0, 125.0, 125.0, 100.0,  40.0, 100.0, 999.0, 150.0, 150.0, 150.0, 200.0, 999.0,  40.0, 999.0, 999.0,\n HS    = 999.0, 36.25, 36.25, 36.25, 36.25, 44.14, 36.35, 42.00, 39.18, 54.53, 54.53, 47.35, 41.69, 47.35, 51.93, 51.75, 60.00, 51.93, 999.0, 42.00, 42.00, 42.00, 42.00, 999.0, 36.25, 999.0, 999.0,\n TOPT  = 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0,\n RSMAX = 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_FEB = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_APR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.3,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAY = 0.0,   0.2,   0.2,   0.2,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.4,   0.4,   0.0,   0.3,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUN = 0.0,   0.3,   0.3,   0.3,   0.4,   0.4,   0.4,   0.2,   0.3,   0.4,   0.4,   0.7,   0.5,   0.5,   0.4,   0.0,   0.4,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUL = 0.0,   0.4,   0.4,   0.4,   0.6,   0.6,   0.8,   0.4,   0.6,   0.8,   0.9,   1.3,   0.5,   0.5,   0.7,   0.0,   0.6,   0.6,   0.0,   0.4,   0.4,   0.4,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_AUG = 0.0,   0.5,   0.5,   0.5,   0.9,   0.9,   1.3,   0.6,   0.9,   1.2,   1.2,   1.2,   0.5,   0.6,   0.8,   0.0,   0.9,   0.9,   0.0,   0.6,   0.6,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_SEP = 0.0,   0.4,   0.4,   0.4,   0.7,   1.0,   1.1,   0.8,   1.0,   1.3,   1.6,   1.0,   0.5,   0.6,   1.0,   0.0,   0.7,   1.0,   0.0,   0.7,   0.8,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_OCT = 0.0,   0.3,   0.3,   0.3,   0.3,   0.8,   0.4,   0.7,   0.6,   0.7,   1.4,   0.8,   0.5,   0.7,   1.0,   0.0,   0.3,   0.8,   0.0,   0.5,   0.7,   0.5,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_NOV = 0.0,   0.3,   0.3,   0.3,   0.3,   0.4,   0.4,   0.3,   0.3,   0.4,   0.6,   0.6,   0.5,   0.6,   0.5,   0.0,   0.3,   0.4,   0.0,   0.3,   0.3,   0.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_DEC = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.4,   0.2,   0.3,   0.4,   0.4,   0.5,   0.5,   0.5,   0.4,   0.0,   0.3,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n LAI_JAN = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_FEB = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.3,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAR = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.0,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_APR = 0.0,   0.0,   0.0,   0.0,   0.4,   0.6,   0.7,   0.6,   0.7,   0.8,   1.2,   0.6,   4.5,   4.0,   2.6,   0.0,   0.4,   0.6,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAY = 0.0,   1.0,   1.0,   1.0,   1.1,   2.0,   1.2,   1.5,   1.4,   1.8,   3.0,   1.2,   4.5,   4.0,   3.5,   0.0,   1.1,   2.0,   0.0,   0.6,   1.7,   1.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUN = 0.0,   2.0,   2.0,   2.0,   2.5,   3.3,   3.0,   2.3,   2.6,   3.6,   4.7,   2.0,   4.5,   4.0,   4.3,   0.0,   2.5,   3.3,   0.0,   1.5,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUL = 0.0,   3.0,   3.0,   3.0,   3.2,   3.7,   3.5,   2.3,   2.9,   3.8,   4.5,   2.6,   4.5,   4.0,   4.3,   0.0,   3.2,   3.7,   0.0,   1.7,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_AUG = 0.0,   3.0,   3.0,   3.0,   2.2,   3.2,   1.5,   1.7,   1.6,   2.1,   3.4,   1.7,   4.5,   4.0,   3.7,   0.0,   2.2,   3.2,   0.0,   0.8,   1.8,   1.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_SEP = 0.0,   1.5,   1.5,   1.5,   1.1,   1.3,   0.7,   0.6,   0.7,   0.9,   1.2,   1.0,   4.5,   4.0,   2.6,   0.0,   1.1,   1.3,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_OCT = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.5,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_NOV = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.2,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_DEC = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n SLAREA=0.0228,0.0200,0.0200,0.0295,0.0223,0.0277,0.0060,0.0227,0.0188,0.0236,0.0258,0.0200,0.0200,0.0090,0.0223,0.0422,0.0390,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1   = 41.87,  0.00,  0.00,  2.52,  0.04, 17.11,  0.02, 21.62,  0.11, 22.80, 46.86,  0.00,  0.00,  0.46, 30.98,  2.31,  1.63,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS2   =  0.98,  0.00,  0.00,  0.16,  0.09,  0.28,  0.05,  0.92,  0.22,  0.59,  0.38,  0.00,  0.00,  3.34,  0.96,  1.47,  1.07,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS3   =  1.82,  0.00,  0.00,  0.23,  0.05,  0.81,  0.03,  1.73,  1.26,  1.37,  1.84,  0.00,  0.00,  1.85,  1.84,  1.70,  1.21,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS4   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS5   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n/\n\n&noahmp_modis_veg_categories\n VEG_DATASET_DESCRIPTION = \"modified igbp modis noah\"\n NVEG = 20\n/\n\n&noahmp_modis_parameters\n! 1          'Evergreen Needleleaf Forest'                       -> USGS 14\n! 2,         'Evergreen Broadleaf Forest'                        -> USGS 13\n! 3,         'Deciduous Needleleaf Forest'                       -> USGS 12\n! 4,         'Deciduous Broadleaf Forest'                        -> USGS 11\n! 5,         'Mixed Forests'                                     -> USGS 15\n! 6,         'Closed Shrublands'                                 -> USGS  8 \"shrubland\"\n! 7,         'Open Shrublands'                                   -> USGS  9 \"shrubland/grassland\"\n! 8,         'Woody Savannas'                                    -> USGS  8 \"shrubland\"\n! 9,         'Savannas'                                          -> USGS 10\n! 10,        'Grasslands'                                        -> USGS  7\n! 11         'Permanent wetlands'                                -> avg of USGS 17 and 18 (herb. wooded wetland)\n! 12,        'Croplands'                                         -> USGS  2 \"dryland cropland\"\n! 13,        'Urban and Built-Up'                                -> USGS  1\n! 14         'cropland/natural vegetation mosaic'                -> USGS  5 \"cropland/grassland\"\n! 15,        'Snow and Ice'                                      -> USGS 24\n! 16,        'Barren or Sparsely Vegetated'                      -> USGS 19\n! 17,        'Water'                                             -> USGS 16\n! 18,        'Wooded Tundra'                                     -> USGS 21\n! 19,        'Mixed Tundra'                                      -> USGS 22\n! 20,        'Barren Tundra'                                     -> USGS 23\n\n ISURBAN                   = 13\n ISWATER                   = 17\n ISBARREN                  = 16\n ISICE                     = 15\n ISCROP                    = 12\n EBLFOREST                 =  2\n NATURAL                   = 14\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1       2       3       4       5       6       7       8       9      10      11      12      13      14      15      16      17      18      19      20\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,\n DLEAF =  0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,\n Z0MVT =  1.09,   1.10,   0.85,   0.80,   0.80,   0.20,   0.06,   0.60,   0.50,   0.12,   0.30,   0.15,   1.00,   0.14,   0.00,   0.00,   0.00,   0.30,   0.20,   0.03,\n HVT   =  20.0,   20.0,   18.0,   16.0,   16.0,   1.10,   1.10,   13.0,   10.0,   1.00,   5.00,   2.00,   15.0,   1.50,   0.00,   0.00,   0.00,   4.00,   2.00,   0.50,\n HVB   =  8.50,   8.00,   7.00,   11.5,   10.0,   0.10,   0.10,   0.10,   0.10,   0.05,   0.10,   0.10,   1.00,   0.10,   0.00,   0.00,   0.00,   0.30,   0.20,   0.10,\n DEN   =  0.28,   0.02,   0.28,   0.10,   0.10,   10.0,   10.0,   10.0,   0.02,   100.,   5.05,   25.0,   0.01,   25.0,   0.00,   0.01,   0.01,   1.00,   1.00,   1.00,\n RC    =  1.20,   3.60,   1.20,   1.40,   1.40,   0.12,   0.12,   0.12,   3.00,   0.03,   0.75,   0.08,   1.00,   0.08,   0.00,   0.01,   0.01,   0.30,   0.30,   0.30,\n MFSNO =  2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.07,   0.10,   0.07,   0.10,   0.10,   0.07,   0.07,   0.07,   0.10,   0.11,  0.105,   0.11,   0.00,   0.11,   0.00,   0.00,   0.00,   0.10,   0.10,   0.10,\n RHOL_NIR=0.35,   0.45,   0.35,   0.45,   0.45,   0.35,   0.35,   0.35,   0.45,   0.58,  0.515,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.45,   0.45,   0.45,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.36,   0.26,   0.36,   0.00,   0.36,   0.00,   0.00,   0.00,   0.16,   0.16,   0.16,\n RHOS_NIR=0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.58,  0.485,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.39,   0.39,   0.39,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.07,   0.06,   0.07,   0.00,   0.07,   0.00,   0.00,   0.00,   0.05,   0.05,   0.05,\n TAUL_NIR=0.10,   0.25,   0.10,   0.25,   0.25,   0.10,   0.10,   0.10,   0.25,   0.25,   0.25,   0.25,   0.00,   0.25,   0.00,   0.00,   0.00,   0.25,   0.25,   0.25,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.220, 0.1105,  0.220,  0.000,  0.220,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n TAUS_NIR=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.380, 0.1905,  0.380,  0.000,  0.380,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n\n XL    = 0.010,  0.010,  0.010,  0.250,  0.250,  0.010,  0.010,  0.010,  0.010,  -0.30, -0.025,  -0.30,  0.000,  -0.30,  0.000,  0.000,  0.000,  0.250,  0.250,  0.250,\n! CWPVT =   3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,\n CWPVT =  0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,\n C3PSN =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n KC25  =  30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,\n AKC   =   2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,\n KO25  =  3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,\n AKO   =   1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,\n AVCMX =   2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,\n AQE   =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n\n LTOVRC=   0.5,   0.55,    0.2,   0.55,    0.5,   0.65,   0.65,   0.65,   0.65,   0.50,    1.4,    1.6,    0.0,    1.2,    0.0,    0.0,    0.0,    1.3,    1.4,    1.0,\n DILEFC=  1.20,   0.50,   1.80,   0.60,   0.80,   0.20,   0.20,   0.20,   0.50,   0.20,    0.4,   0.50,   0.00,   0.35,   0.00,   0.00,   0.00,   0.30,   0.40,   0.30,\n DILEFW=  0.20,   4.00,   0.20,   0.20,   0.20,   0.20,   0.20,   0.20,   0.50,   0.10,    0.2,   0.20,   0.00,   0.20,   0.00,   0.00,   0.00,   0.20,   0.20,   0.20,\n RMF25 =  3.00,   0.65,   4.00,   3.00,   3.00,   0.26,   0.26,   0.26,   0.80,   1.80,    3.2,   1.00,   0.00,   1.45,   0.00,   0.00,   0.00,   3.00,   3.00,   3.00,\n SLA   =    80,     80,     80,     80,     80,     60,     60,     60,     50,     60,     80,     80,     60,     80,      0,      0,      0,     80,     80,     80,\n FRAGR =  0.10,   0.20,   0.10,   0.20,   0.10,   0.20,   0.20,   0.20,   0.20,   0.20,    0.1,   0.20,   0.00,   0.20,   0.00,   0.10,   0.00,   0.10,   0.10,   0.10,\n TMIN  =   265,    273,    268,    273,    268,    273,    273,    273,    273,    273,    268,    273,      0,    273,      0,      0,      0,    268,    268,    268,\n VCMX25=  50.0,   60.0,   60.0,   60.0,   55.0,   40.0,   40.0,   40.0,   40.0,   40.0,   50.0,   80.0,   0.00,   60.0,   0.00,   0.00,   0.00,   50.0,   50.0,   50.0,\n TDLEF =   278,    278,    268,    278,    268,    278,    278,    278,    278,    278,    268,    278,    278,    278,      0,      0,      0,    268,    268,    268,\n BP    =  2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,   2.E3,   2.E3,\n MP    =    6.,     9.,     6.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,\n QE25  =  0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.00,   0.06,   0.00,   0.06,   0.00,   0.06,   0.06,   0.06,\n RMS25 =  0.90,   0.30,   0.64,   0.10,   0.80,   0.10,   0.10,   0.10,   0.32,   0.10,   0.10,   0.10,   0.00,   0.10,   0.00,   0.00,   0.00,   0.10,   0.10,   0.00,\n RMR25 =  0.36,   0.05,   0.05,   0.01,   0.03,   0.00,   0.00,   0.00,   0.01,   1.20,    0.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   2.11,   2.11,   0.00,\n ARM   =   2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,\n FOLNMX=   1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,   0.00,    1.5,   0.00,    1.5,   0.00,    1.5,    1.5,    1.5,\n WDPOOL=  1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   0.00,    0.5,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   1.00,   1.00,   0.00,\n WRRAT =  30.0,   30.0,   30.0,   30.0,   30.0,   3.00,   3.00,   3.00,   3.00,   0.00,   15.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   3.00,   3.00,   0.00,\n MRP   =  0.37,   0.23,   0.37,   0.40,   0.30,   0.19,   0.19,   0.19,   0.40,   0.17,  0.285,   0.23,   0.00,   0.23,   0.00,   0.00,   0.00,   0.23,   0.20,   0.00,\n NROOT =     4,      4,      4,      4,      4,      3,      3,      3,      3,      3,      2,      3,      1,      3,      1,      1,      0,      3,      3,      2,     \n RGL   =  30.0,   30.0,   30.0,   30.0,   30.0,  100.0,  100.0,  100.0,   65.0,  100.0,   65.0,  100.0,  999.0,  100.0,  999.0,  999.0,   30.0,  100.0,  100.0,  100.0,\n RS    = 125.0,  150.0,  150.0,  100.0,  125.0,  300.0,  170.0,  300.0,   70.0,   40.0,   70.0,   40.0,  200.0,   40.0,  999.0,  999.0,  100.0,  150.0,  150.0,  200.0,\n HS    = 47.35,  41.69,  47.35,  54.53,  51.93,  42.00,  39.18,  42.00,  54.53,  36.35,  55.97,  36.25,  999.0,  36.25,  999.0,  999.0,  51.75,  42.00,  42.00,  42.00,\n TOPT  = 298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,\n RSMAX = 5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_FEB = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAR = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_APR = 0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAY = 0.4,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_JUN = 0.5,    0.5,    0.7,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.4,    0.3,    0.0,    0.4,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n SAI_JUL = 0.5,    0.5,    1.3,    0.9,    0.7,    0.6,    0.4,    0.7,    0.8,    0.8,    0.6,    0.4,    0.0,    0.6,    0.0,    0.0,    0.0,    0.4,    0.4,    0.0,\n SAI_AUG = 0.6,    0.5,    1.2,    1.2,    0.8,    0.9,    0.6,    1.2,    1.2,    1.3,    0.9,    0.5,    0.0,    0.9,    0.0,    0.0,    0.0,    0.6,    0.6,    0.0,\n SAI_SEP = 0.6,    0.5,    1.0,    1.6,    1.0,    1.2,    0.8,    1.4,    1.3,    1.1,    0.9,    0.4,    0.0,    0.7,    0.0,    0.0,    0.0,    0.8,    0.7,    0.0,\n SAI_OCT = 0.7,    0.5,    0.8,    1.4,    1.0,    0.9,    0.7,    1.1,    0.7,    0.4,    0.6,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.7,    0.5,    0.0,\n SAI_NOV = 0.6,    0.5,    0.6,    0.6,    0.5,    0.4,    0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.3,    0.3,    0.0,\n SAI_DEC = 0.5,    0.5,    0.5,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n\n LAI_JAN = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_FEB = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_MAR = 4.0,    4.5,    0.0,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_APR = 4.0,    4.5,    0.6,    1.2,    2.6,    0.9,    0.6,    1.0,    0.8,    0.7,    0.5,    0.0,    0.0,    0.4,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_MAY = 4.0,    4.5,    1.2,    3.0,    3.5,    2.2,    1.5,    2.4,    1.8,    1.2,    1.5,    1.0,    0.0,    1.1,    0.0,    0.0,    0.0,    1.7,    1.2,    0.0,\n LAI_JUN = 4.0,    4.5,    2.0,    4.7,    4.3,    3.5,    2.3,    4.1,    3.6,    3.0,    2.9,    2.0,    0.0,    2.5,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_JUL = 4.0,    4.5,    2.6,    4.5,    4.3,    3.5,    2.3,    4.1,    3.8,    3.5,    3.5,    3.0,    0.0,    3.2,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_AUG = 4.0,    4.5,    1.7,    3.4,    3.7,    2.5,    1.7,    2.7,    2.1,    1.5,    2.7,    3.0,    0.0,    2.2,    0.0,    0.0,    0.0,    1.8,    1.3,    0.0,\n LAI_SEP = 4.0,    4.5,    1.0,    1.2,    2.6,    0.9,    0.6,    1.0,    0.9,    0.7,    1.2,    1.5,    0.0,    1.1,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_OCT = 4.0,    4.5,    0.5,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_NOV = 4.0,    4.5,    0.2,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_DEC = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n\n SLAREA=0.0090, 0.0200, 0.0200, 0.0258, 0.0223, 0.0227, 0.0188, 0.0227, 0.0236, 0.0060, 0.0295, 0.0200, 0.0228, 0.0223,   0.02,   0.02, 0.0422,   0.02,   0.02,   0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1  =  0.46,   0.00,   0.00,  46.86,  30.98,  21.62,   0.11,  21.62,  22.80,   0.02,  0.815,   0.00,  41.87,   0.04,    0.0,    0.0,   2.31,    0.0,    0.0,    0.0,\n EPS2  =  3.34,   0.00,   0.00,   0.38,   0.96,   0.92,   0.22,   0.92,   0.59,   0.05,  0.535,   0.00,   0.98,   0.09,    0.0,    0.0,   1.47,    0.0,    0.0,    0.0,\n EPS3  =  1.85,   0.00,   0.00,   1.84,   1.84,   1.73,   1.26,   1.73,   1.37,   0.03,  0.605,   0.00,   1.82,   0.05,    0.0,    0.0,   1.70,    0.0,    0.0,    0.0,\n EPS4  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n EPS5  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n\n/\n\n&noahmp_rad_parameters\n !------------------------------------------------------------------------------\n !                1       2       3       4       5       6       7       8     soil color index for soil albedo\n !------------------------------------------------------------------------------\n ALBSAT_VIS =   0.15,   0.11,   0.10,   0.09,   0.08,   0.07,   0.06,   0.05   ! saturated soil albedos\n ALBSAT_NIR =   0.30,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! saturated soil albedos\n ALBDRY_VIS =   0.27,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! dry soil albedos\n ALBDRY_NIR =   0.54,   0.44,   0.40,   0.36,   0.32,   0.28,   0.24,   0.20   ! dry soil albedos\n ALBICE     =   0.80,   0.55                                                   ! albedo land ice: 1=vis, 2=nir\n ALBLAK     =   0.60,   0.40                                                   ! albedo frozen lakes: 1=vis, 2=nir\n OMEGAS     =   0.8 ,   0.4                                                    ! two-stream parameter omega for snow\n BETADS     =   0.5                                                            ! two-stream parameter betad for snow\n BETAIS     =   0.5                                                            ! two-stream parameter betaI for snow\n EG         =   0.97,   0.98                                                   ! emissivity soil surface 1-soil;2-lake\n\n/\n\n&noahmp_global_parameters\n\n! atmospheric constituants\n\n  CO2    = 395.e-06     !co2 partial pressure\n  O2     = 0.209        !o2 partial pressure\n\n! runoff parameters used for SIMTOP and SIMGM:\n\n  TIMEAN = 10.5         !gridcell mean topgraphic index (global mean)\n  FSATMX = 0.38         !maximum surface saturated fraction (global mean)\n\n! adjustable parameters for snow processes\n\n  Z0SNO  = 0.002        !snow surface roughness length (m) (0.002)\n  SSI    = 0.03         !liquid water holding capacity for snowpack (m3/m3) (0.03)\n  SNOW_RET_FAC  = 5.e-5 !snowpack water release timescale factor (1/s)\n  SWEMX  = 1.00         !new snow mass to fully cover old snow (mm)\n                        !equivalent to 10mm depth (density = 100 kg/m3)\n  TAU0          = 1.e6  !tau0 from Yang97 eqn. 10a\n  GRAIN_GROWTH  = 5000. !growth from vapor diffusion Yang97 eqn. 10b\n  EXTRA_GROWTH  = 10.   !extra growth near freezing Yang97 eqn. 10c\n  DIRT_SOOT     = 0.3   !dirt and soot term Yang97 eqn. 10d\n  BATS_COSZ     = 2.0   !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n  BATS_VIS_NEW  = 0.95  !new snow visible albedo\n  BATS_NIR_NEW  = 0.65  !new snow NIR albedo\n  BATS_VIS_AGE  = 0.2   !age factor for diffuse visible snow albedo Yang97 eqn. 17\n  BATS_NIR_AGE  = 0.5   !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n  BATS_VIS_DIR  = 0.4   !cosz factor for direct visible snow albedo Yang97 eqn. 15\n  BATS_NIR_DIR  = 0.4   !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n  RSURF_SNOW = 50.0     !surface resistence for snow [s/m]\n  RSURF_EXP = 5.0       !exponent in the shape parameter for soil resistance option 1\n  IMPERV_URBAN = 0.95   !impervious fraction to use for urban type [0-1]\n  SCAMAX = 1.0          !maximum fractional snow covered area [0-1]\n  SWE_LIMIT = 5000.0    !maximum SWE limit [mm]\n\n/\n\n&noahmp_crop_parameters\n\n ! NCROP = 5\n !  1: Corn\n !  2: Soybean\n !  3: Sorghum\n !  4: Rice\n !  5: Winter wheat\n\nDEFAULT_CROP = 0                                      ! The default crop type(1-5); if zero, use generic dynamic vegetation \n\n!----------------------------------------------------------\n!                1       2       3       4       5\n!----------------------------------------------------------\n \nPLTDAY     =    130,    111,    111,    111,    111,  ! Planting date\nHSDAY      =    280,    300,    300,    300,    300,  ! Harvest date\nPLANTPOP   =   78.0,   78.0,   78.0,   78.0,   78.0,  ! Plant density [per ha] - used?\nIRRI       =    0.0,    0.0,    0.0,    0.0,    0.0,  ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n\nGDDTBASE   =   10.0,   10.0,   10.0,   10.0,   10.0,  ! Base temperature for GDD accumulation [C]\nGDDTCUT    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! Upper temperature for GDD accumulation [C]\nGDDS1      =   60.0,   50.0,   50.0,   50.0,   50.0,  ! GDD from seeding to emergence\nGDDS2      =  675.0,  718.0,  718.0,  718.0,  718.0,  ! GDD from seeding to initial vegetative \nGDDS3      = 1183.0,  933.0,  933.0,  933.0,  933.0,  ! GDD from seeding to post vegetative \nGDDS4      = 1253.0, 1103.0, 1103.0, 1103.0, 1103.0,  ! GDD from seeding to intial reproductive\nGDDS5      = 1605.0, 1555.0, 1555.0, 1555.0, 1555.0,  ! GDD from seeding to pysical maturity \n\nC3C4       =      2,      1,      2,      2,      2,  ! photosynthetic pathway:  1. = c3 2. = c4\nAref       =    7.0,    7.0,    7.0,    7.0,    7.0,  ! reference maximum CO2 assimulation rate \nPSNRF      =   0.85,   0.85,   0.85,   0.85,   0.85,  ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\nI2PAR      =    0.5,    0.5,    0.5,    0.5,    0.5,  ! Fraction of incoming solar radiation to photosynthetically active radiation\nTASSIM0    =    8.0,    8.0,    8.0,    8.0,    8.0,  ! Minimum temperature for CO2 assimulation [C]\nTASSIM1    =   18.0,   18.0,   18.0,   18.0,   18.0,  ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\nTASSIM2    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\nK          =   0.55,   0.55,   0.55,   0.55,   0.55,  ! light extinction coefficient\nEPSI       =   12.5,   12.5,   12.5,   12.5,   12.5,  ! initial light use efficiency\n\nQ10MR      =    2.0,    2.0,    2.0,    2.0,    2.0,  ! q10 for maintainance respiration\nFOLN_MX    =    1.5,    1.5,    1.5,    1.5,    1.5,  ! foliage nitrogen concentration when f(n)=1 (%)\nLEFREEZ    =    268,    268,    268,    268,    268,  ! characteristic T for leaf freezing [K]\n\nDILE_FC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for temperature leaf stress death [1/s]\nDILE_FC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0, \nDILE_FC_S5 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S6 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nDILE_FW_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for water leaf stress death [1/s]\nDILE_FW_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FW_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S5 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S6 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nFRA_GR     =    0.2,    0.2,    0.2,    0.2,    0.2,  ! fraction of growth respiration\n\nLF_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of leaf turnover  [1/s]\nLF_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLF_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S5 =    0.2,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S6 =    0.3,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nST_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of stem turnover  [1/s]\nST_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nST_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nST_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nST_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nRT_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of root tunrover  [1/s]\nRT_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRT_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nRT_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nRT_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n             \nLFMR25     =    1.0,    1.0,    1.0,    1.0,    1.0,  !  leaf maintenance respiration at 25C [umol CO2/m**2  /s]\nSTMR25     =   0.05,    0.1,    0.1,    0.1,    0.1,  !  stem maintenance respiration at 25C [umol CO2/kg bio/s]\nRTMR25     =   0.05,    0.0,    0.0,    0.0,    0.0,  !  root maintenance respiration at 25C [umol CO2/kg bio/s]\nGRAINMR25  =    0.0,    0.1,    0.1,    0.1,    0.1,  ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n\nLFPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to leaf\nLFPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLFPT_S3    =    0.4,    0.4,    0.4,    0.4,    0.4,\nLFPT_S4    =    0.2,    0.2,    0.2,    0.2,    0.2,\nLFPT_S5    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S6    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nSTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to stem\nSTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nSTPT_S3    =    0.2,    0.2,    0.2,    0.2,    0.2,\nSTPT_S4    =    0.5,    0.5,    0.5,    0.5,    0.5,\nSTPT_S5    =    0.0,   0.15,   0.15,   0.15,   0.15,\nSTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nSTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nSTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0, \n\nRTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to root\nRTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRTPT_S3    =   0.34,    0.4,    0.4,    0.4,    0.4,\nRTPT_S4    =    0.3,    0.3,    0.3,    0.3,    0.3,\nRTPT_S5    =   0.05,   0.05,   0.05,   0.05,   0.05,\nRTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nRTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nRTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n   \nGRAINPT_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to grain\nGRAINPT_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nGRAINPT_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S5 =   0.95,    0.8,    0.8,    0.8,    0.8,\nGRAINPT_S6 =    1.0,    0.9,    0.9,    0.9,    0.9,\nGRAINPT_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n\nBIO2LAI   =  0.035,  0.015,  0.015,  0.015,  0.015,  ! leaf are per living leaf biomass [m^2/kg]\n\n/\n\n&noahmp_optional_parameters\n\n !------------------------------------------------------------------------------\n ! Saxton and Rawls 2006 Pedo-transfer function coefficients\n !------------------------------------------------------------------------------\n\n sr2006_theta_1500t_a =   -0.024   ! sand coefficient\n sr2006_theta_1500t_b =    0.487   ! clay coefficient\n sr2006_theta_1500t_c =    0.006   ! orgm coefficient\n sr2006_theta_1500t_d =    0.005   ! sand*orgm coefficient\n sr2006_theta_1500t_e =   -0.013   ! clay*orgm coefficient\n sr2006_theta_1500t_f =    0.068   ! sand*clay coefficient\n sr2006_theta_1500t_g =    0.031   ! constant adjustment\n\n sr2006_theta_1500_a  =    0.14    ! theta_1500t coefficient\n sr2006_theta_1500_b  =   -0.02    ! constant adjustment\n\n sr2006_theta_33t_a   =   -0.251   ! sand coefficient\n sr2006_theta_33t_b   =    0.195   ! clay coefficient\n sr2006_theta_33t_c   =    0.011   ! orgm coefficient\n sr2006_theta_33t_d   =    0.006   ! sand*orgm coefficient\n sr2006_theta_33t_e   =   -0.027   ! clay*orgm coefficient\n sr2006_theta_33t_f   =    0.452   ! sand*clay coefficient\n sr2006_theta_33t_g   =    0.299   ! constant adjustment\n\n sr2006_theta_33_a    =    1.283   ! theta_33t*theta_33t coefficient\n sr2006_theta_33_b    =   -0.374   ! theta_33t coefficient\n sr2006_theta_33_c    =   -0.015   ! constant adjustment\n\n sr2006_theta_s33t_a  =    0.278   ! sand coefficient\n sr2006_theta_s33t_b  =    0.034   ! clay coefficient\n sr2006_theta_s33t_c  =    0.022   ! orgm coefficient\n sr2006_theta_s33t_d  =   -0.018   ! sand*orgm coefficient\n sr2006_theta_s33t_e  =   -0.027   ! clay*orgm coefficient\n sr2006_theta_s33t_f  =   -0.584   ! sand*clay coefficient\n sr2006_theta_s33t_g  =    0.078   ! constant adjustment\n\n sr2006_theta_s33_a   =    0.636   ! theta_s33t coefficient\n sr2006_theta_s33_b   =   -0.107   ! constant adjustment\n\n sr2006_psi_et_a      =  -21.67    ! sand coefficient\n sr2006_psi_et_b      =  -27.93    ! clay coefficient\n sr2006_psi_et_c      =  -81.97    ! theta_s33 coefficient\n sr2006_psi_et_d      =   71.12    ! sand*theta_s33 coefficient\n sr2006_psi_et_e      =    8.29    ! clay*theta_s33 coefficient\n sr2006_psi_et_f      =   14.05    ! sand*clay coefficient\n sr2006_psi_et_g      =   27.16    ! constant adjustment\n\n sr2006_psi_e_a       =    0.02    ! psi_et*psi_et coefficient\n sr2006_psi_e_b       =   -0.113   ! psi_et coefficient\n sr2006_psi_e_c       =   -0.7     ! constant adjustment\n\n sr2006_smcmax_a      =   -0.097   ! sand adjustment\n sr2006_smcmax_b      =    0.043   ! constant adjustment\n \n/\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/CONUS/SOILPARM.TBL",
    "content": "Soil Parameters\nSTAS\n19,1   'BB      DRYSMC      F11     MAXSMC   REFSMC   SATPSI  SATDK      SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     2.79,    0.010,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,   0.010,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.74,    0.047,    -0.569,   0.434,   0.312,   0.141,  5.23E-6,  8.05E-6,   0.047,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.33,    0.084,     0.162,   0.476,   0.360,   0.759,  2.81E-6,  2.39E-5,   0.084,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     3.86,    0.061,     0.162,   0.484,   0.347,   0.955,  2.18E-6,  1.66E-5,   0.061,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     6.77,    0.069,    -1.491,   0.404,   0.315,   0.135,  4.45E-6,  1.01E-5,   0.069,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     8.72,    0.120,    -1.118,   0.464,   0.387,   0.617,  2.03E-6,  2.35E-5,   0.120,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.17,    0.103,    -1.297,   0.465,   0.382,   0.263,  2.45E-6,  1.13E-5,   0.103,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.73,    0.100,    -3.209,   0.406,   0.338,   0.098,  7.22E-6,  1.87E-5,   0.100,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.39,    0.126,    -1.916,   0.468,   0.404,   0.324,  1.34E-6,  9.64E-6,   0.126,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.55,    0.138,    -2.138,   0.468,   0.412,   0.468,  9.74E-7,  1.12E-5,   0.138,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,       0.0,     1.0,     0.0,     0.0,      0.0,      0.0,     0.0,  0.60,  0.001,  0.00,  0.00, 'WATER'\n15,    2.79,    0.006,    -1.111,    0.20,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.07,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.25,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.55,    0.030,   -10.472,   0.468,   0.454,   0.468,  9.74E-7,  1.12E-5,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    2.79,    0.006,    -0.472,   0.200,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    2.79,     0.01,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,    0.01,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\nSoil Parameters\nSTAS-RUC\n19,1   'BB      DRYSMC       HC     MAXSMC   REFSMC   SATPSI  SATDK       SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     4.05,    0.002,      1.47,   0.395,   0.174,   0.121,  1.76E-4,  0.608E-6,   0.033,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.38,    0.035,      1.41,   0.410,   0.179,   0.090,  1.56E-4,  0.514E-5,   0.055,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.90,    0.041,      1.34,   0.435,   0.249,   0.218,  3.47E-5,  0.805E-5,   0.095,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.39,    0.050,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.137,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     7.12,    0.068,      1.18,   0.420,   0.299,   0.299,  6.30E-6,  0.990E-5,   0.148,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     7.75,    0.060,      1.32,   0.477,   0.357,   0.356,  1.70E-6,  0.237E-4,   0.208,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.52,    0.085,      1.23,   0.476,   0.391,   0.630,  2.45E-6,  0.113E-4,   0.230,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.40,    0.100,      1.18,   0.426,   0.316,   0.153,  2.17E-6,  0.187E-4,   0.210,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.40,    0.070,      1.15,   0.492,   0.409,   0.490,  1.03E-6,  0.964E-5,   0.250,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.40,    0.068,      1.09,   0.482,   0.400,   0.405,  1.28E-6,  0.112E-4,   0.268,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.39,    0.027,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.117,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,      4.18,   1.0,     1.0,     0.0,      0.0,       0.0,     0.0,    0.00,  0.001,  0.00,  0.00, 'WATER'\n15,    4.05,    0.004,      2.03,   0.200,   0.10 ,   0.121,  1.41E-4,  0.136E-3,   0.006,  0.60,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.90,    0.065,      2.10,   0.435,   0.249,   0.218,  3.47E-5,  0.514E-5,   0.114,  0.05,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.40,    0.030,      1.41,   0.468,   0.454,   0.468,  9.74E-7,  0.112E-4,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    4.05,    0.006,      1.41,   0.200,   0.17,    0.069,  1.41E-4,  0.136E-3,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    4.05,     0.01,      1.47,   0.339,   0.236,   0.069,  1.76E-4,  0.608E-6,   0.060,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\n\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Hawaii/CHANPARM.TBL",
    "content": "Channel Parameters\nStreamOrder\n10,1,  'Bw     HLINK   ChSSlp   MannN'\n1,     1.6,    0.02,    0.03,      0.09\n2,     2.4,    0.02,    0.03,      0.07\n3,     3.5,    0.02,    0.03,      0.06\n4,     5.3,    0.03,    0.04,      0.05\n5,     7.4,    0.03,    0.04,      0.04\n6,     11.,    0.03,    0.04,      0.03\n7,     14.,    0.03,    0.04,      0.03\n8,     16.,    0.10,    0.04,      0.02\n9,     26.,    0.30,    0.05,      0.02\n10,    110.,    0.30,    0.10,      0.02\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Hawaii/GENPARM.TBL",
    "content": "General Parameters\nSLOPE_DATA\n9\n0.1 \n0.6\n1.0\n0.35\n0.55\n0.8\n0.63\n0.0\n0.0\nSBETA_DATA\n-2.0\nFXEXP_DATA\n2.0\nCSOIL_DATA\n2.00E+6\nSALP_DATA\n2.6\nREFDK_DATA\n2.0E-6\nREFKDT_DATA\n3.0\nFRZK_DATA\n0.15\nZBOT_DATA\n-8.0\nCZIL_DATA\n0.1\nSMLOW_DATA\n0.5\nSMHIGH_DATA\n3.0\nLVCOEF_DATA\n0.5\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Hawaii/HYDRO.TBL",
    "content": "     28 USGS for OV_ROUGH\n   SFC_ROUGH'\n     0.025,    'Urban and Built-Up Land'  \n     0.035,    'Dryland Cropland and Pasture' \n     0.035,    'Irrigated Cropland and Pasture' \n     0.055,    'Mixed Dryland/Irrigated Cropland and Pasture' \n     0.035,    'Cropland/Grassland Mosaic'\n     0.068,    'Cropland/Woodland Mosaic' \n     0.055,    'Grassland' \n     0.055,    'Shrubland' \n     0.055,    'Mixed Shrubland/Grassland' \n     0.055,    'Savanna' \n     0.200,    'Deciduous Broadleaf Forest' \n     0.200,    'Deciduous Needleleaf Forest' \n     0.200,    'Evergreen Broadleaf Forest'\n     0.200,    'Evergreen Needleleaf Forest'  \n     0.200,    'Mixed Forest' \n     0.005,    'Water Bodies' \n     0.070,    'Herbaceous Wetland' \n     0.070,    'Wooded Wetland' \n     0.035,    'Barren or Sparsely Vegetated' \n     0.055,    'Herbaceous Tundra' \n     0.055,    'Wooded Tundra' \n     0.055,    'Mixed Tundra' \n     0.055,    'Bare Ground Tundra' \n     0.010,    'Snow or Ice' \n     0.010,    'Playa' \n     0.100,    'Lava'   \n     0.010,    'White Sand' \n     0.005,    'Non-Ocean Water Bodies'\n19, for SATDK\nSATDK     MAXSMC    REFSMC   WLTSMC  QTZ    '\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'SAND'\n1.41E-5,  0.421,    0.283,   0.028,  0.82, 'LOAMY SAND'\n5.23E-6,  0.434,    0.312,   0.047,  0.60, 'SANDY LOAM'\n2.81E-6,  0.476,    0.360,   0.084,  0.25, 'SILT LOAM'\n2.18E-6,  0.484,    0.347,   0.061,  0.10, 'SILT'\n3.38E-6,  0.439,    0.329,   0.066,  0.40, 'LOAM'\n4.45E-6,  0.404,    0.315,   0.069,  0.60, 'SANDY CLAY LOAM'\n2.03E-6,  0.464,    0.387,   0.120,  0.10, 'SILTY CLAY LOAM'\n2.45E-6,  0.465,    0.382,   0.103,  0.35, 'CLAY LOAM'\n7.22E-6,  0.406,    0.338,   0.100,  0.52, 'SANDY CLAY'\n1.34E-6,  0.468,    0.404,   0.126,  0.10, 'SILTY CLAY'\n9.74E-7,  0.468,    0.412,   0.138,  0.25, 'CLAY'\n3.38E-6,  0.439,    0.329,   0.066,  0.05, 'ORGANIC MATERIAL'\n    0.0,  1.0,      0.0,     0.0,    0.60, 'WATER'\n1.41E-4,  0.20,     0.170,   0.006,  0.07, 'BEDROCK'\n1.41E-5,  0.421,    0.283,   0.028,  0.25, 'OTHER(land-ice)'\n9.74E-7,  0.468,    0.454,   0.030,  0.60, 'PLAYA'\n1.41E-4,  0.200,    0.170,   0.006,  0.52, 'LAVA'\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'WHITE SAND'\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Hawaii/MPTABLE.TBL",
    "content": "&noahmp_usgs_veg_categories\n VEG_DATASET_DESCRIPTION = \"USGS\"\n NVEG = 27\n/\n&noahmp_usgs_parameters\n ! NVEG = 27\n !  1: Urban and Built-Up Land\n !  2: Dryland Cropland and Pasture\n !  3: Irrigated Cropland and Pasture\n !  4: Mixed Dryland/Irrigated Cropland and Pasture\n !  5: Cropland/Grassland Mosaic\n !  6: Cropland/Woodland Mosaic\n !  7: Grassland\n !  8: Shrubland\n !  9: Mixed Shrubland/Grassland\n ! 10: Savanna\n ! 11: Deciduous Broadleaf Forest\n ! 12: Deciduous Needleleaf Forest\n ! 13: Evergreen Broadleaf Forest\n ! 14: Evergreen Needleleaf Forest\n ! 15: Mixed Forest\n ! 16: Water Bodies\n ! 17: Herbaceous Wetland\n ! 18: Wooded Wetland\n ! 19: Barren or Sparsely Vegetated\n ! 20: Herbaceous Tundra\n ! 21: Wooded Tundra\n ! 22: Mixed Tundra\n ! 23: Bare Ground Tundra\n ! 24: Snow or Ice\n ! 25: Playa\n ! 26: Lava\n ! 27: White Sand\n\n ISURBAN                   =  1\n ISWATER                   = 16\n ISBARREN                  = 19\n ISICE                     = 24\n ISCROP                    =  2\n EBLFOREST                 = 13\n NATURAL                   =  5\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1      2      3      4      5      6      7      8      9      10     11     12     13     14     15     16     17     18     19     20     21     22     23     24     25     26    27\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,\n DLEAF =  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,\n Z0MVT =  1.00,  0.15,  0.15,  0.15,  0.14,  0.50,  0.12,  0.06,  0.09,  0.50,  0.80,  0.85,  1.10,  1.09,  0.80,  0.00,  0.12,  0.50,  0.00,  0.10,  0.30,  0.20,  0.03,  0.00,  0.01,  0.00,  0.00,\n HVT   =  15.0,  2.00,  2.00,  2.00,  1.50,  8.00,  1.00,  1.10,  1.10,  10.0,  16.0,  18.0,  20.0,  20.0,  16.0,  0.00,  0.50,  10.0,  0.00,  0.50,  4.00,  2.00,  0.50,  0.00,  0.10,  0.00,  0.00,\n HVB   =  1.00,  0.10,  0.10,  0.10,  0.10,  0.15,  0.05,  0.10,  0.10,  0.10,  11.5,  7.00,  8.00,  8.50,  10.0,  0.00,  0.05,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n DEN   =  0.01,  25.0,  25.0,  25.0,  25.0,  25.0,  100.,  10.0,  10.0,  0.02,  0.10,  0.28,  0.02,  0.28,  0.10,  0.01,  10.0,  0.10,  0.01,  1.00,  1.00,  1.00,  1.00,  0.00,  0.01,  0.01,  0.01,\n RC    =  1.00,  0.08,  0.08,  0.08,  0.08,  0.08,  0.03,  0.12,  0.12,  3.00,  1.40,  1.20,  3.60,  1.20,  1.40,  0.01,  0.10,  1.40,  0.01,  0.30,  0.30,  0.30,  0.30,  0.00,  0.01,  0.01,  0.01,\n MFSNO =  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.00,  0.11,  0.11,  0.11,  0.11,  0.11,  0.11,  0.07,  0.10,  0.10,  0.10,  0.07,  0.10,  0.07,  0.10,  0.00,  0.11,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n RHOL_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.35,  0.45,  0.45,  0.45,  0.35,  0.45,  0.35,  0.45,  0.00,  0.58,  0.45,  0.00,  0.45,  0.45,  0.45,  0.45,  0.00,  0.45,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.00,  0.36,  0.36,  0.36,  0.36,  0.36,  0.36,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.00,  0.36,  0.16,  0.00,  0.16,  0.16,  0.16,  0.16,  0.00,  0.16,  0.00,  0.00,\n RHOS_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.00,  0.58,  0.39,  0.00,  0.39,  0.39,  0.39,  0.39,  0.00,  0.39,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.00,  0.07,  0.07,  0.07,  0.07,  0.07,  0.07,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.00,  0.07,  0.05,  0.00,  0.05,  0.05,  0.05,  0.05,  0.00,  0.05,  0.00,  0.00,\n TAUL_NIR=0.00,  0.25,  0.25,  0.25,  0.25,  0.25,  0.25,  0.10,  0.10,  0.25,  0.25,  0.10,  0.25,  0.10,  0.25,  0.00,  0.25,  0.25,  0.00,  0.25,  0.25,  0.25,  0.25,  0.00,  0.25,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.00, 0.220, 0.220, 0.220, 0.220, 0.220, 0.220, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.220, 0.001, 0.000, 0.220, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n TAUS_NIR=0.00, 0.380, 0.380, 0.380, 0.380, 0.380, 0.380, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.380, 0.001, 0.000, 0.380, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n\n XL    = 0.000, -0.30, -0.30, -0.30, -0.30, -0.30, -0.30, 0.010, 0.250, 0.010, 0.250, 0.010, 0.010, 0.010, 0.250, 0.000, -0.30, 0.250, 0.000, -0.30, 0.250, 0.250, 0.250, 0.000, 0.250, 0.000, 0.000,\n CWPVT =  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,\n C3PSN =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n KC25  =  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,\n AKC   =   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,\n KO25  =  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,\n AKO   =   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,\n AVCMX =   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,\n AQE   =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n\n LTOVRC=   0.0,   1.2,   1.2,   1.2,   1.2,  1.30,  0.50,  0.65,  0.70,  0.65,  0.55,   0.2,  0.55,   0.5,   0.5,   0.0,   1.4,   1.4,   0.0,   1.2,   1.3,   1.4,   1.0,   0.0,   1.0,   0.0,   0.0,\n DILEFC=  0.00,  0.50,  0.50,  0.50,  0.35,  0.20,  0.20,  0.20,  0.50,  0.50,  0.60,  1.80,  0.50,  1.20,  0.80,  0.00,  0.40,  0.40,  0.00,  0.40,  0.30,  0.40,  0.30,  0.00,  0.30,  0.00,  0.00,\n DILEFW=  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.20,  0.50,  0.20,  0.20,  4.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.20,  0.20,  0.00,  0.20,  0.00,  0.00,\n RMF25 =  0.00,  1.00,  1.40,  1.45,  1.45,  1.45,  1.80,  0.26,  0.26,  0.80,  3.00,  4.00,  0.65,  3.00,  3.00,  0.00,  3.20,  3.20,  0.00,  3.20,  3.00,  3.00,  3.00,  0.00,  3.00,  0.00,  0.00,\n SLA   =    60,    80,    80,    80,    80,    80,    60,    60,    60,    50,    80,    80,    80,    80,    80,     0,    80,    80,     0,    80,    80,    80,    80,     0,    80,     0,     0,\n FRAGR =  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n TMIN  =     0,   273,   273,   273,   273,   273,   273,   273,   273,   273,   273,   268,   273,   265,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n VCMX25=  0.00,  80.0,  80.0,  80.0,  60.0,  70.0,  40.0,  40.0,  40.0,  40.0,  60.0,  60.0,  60.0,  50.0,  55.0,  0.00,  50.0,  50.0,  0.00,  50.0,  50.0,  50.0,  50.0,  0.00,  50.0,  0.00,  0.00,\n TDLEF =   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   268,   278,   278,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n BP    = 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3, 1.E15, 1.E15,\n MP    =    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    6.,    9.,    6.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,\n QE25  =    0.,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.00,  0.00,\n RMS25 =  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.32,  0.10,  0.64,  0.30,  0.90,  0.80,  0.00,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.00,  0.00,  0.00,  0.00,  0.00,\n RMR25 =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.20,  0.00,  0.00,  0.01,  0.01,  0.05,  0.05,  0.36,  0.03,  0.00,  0.00,  0.00,  0.00,  2.11,  2.11,  2.11,  0.00,  0.00,  0.00,  0.00,  0.00,\n ARM   =   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,\n FOLNMX=  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,  0.00,  0.00,\n WDPOOL=  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  0.00,  0.00,  1.00,  0.00,  0.00,  1.00,  1.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n WRRAT =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  3.00,  3.00,  3.00,  30.0,  30.0,  30.0,  30.0,  30.0,  0.00,  0.00,  30.0,  0.00,  0.00,  3.00,  3.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n MRP   =  0.00,  0.23,  0.23,  0.23,  0.23,  0.23,  0.17,  0.19,  0.19,  0.40,  0.40,  0.37,  0.23,  0.37,  0.30,  0.00,  0.17,  0.40,  0.00,  0.17,  0.23,  0.20,  0.00,  0.00,  0.20,  0.00,  0.00,\n NROOT =     1,     3,     3,     3,     3,     3,     3,     3,     3,     3,     4,     4,     4,     4,     4,     0,     2,     2,     1,     3,     3,     3,     2,     1,     1,     0,     0,\n RGL   = 999.0, 100.0, 100.0, 100.0, 100.0,  65.0, 100.0, 100.0, 100.0,  65.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0, 100.0,  30.0, 999.0, 100.0, 100.0, 100.0, 100.0, 999.0, 100.0, 999.0, 999.0,\n RS    = 200.0,  40.0,  40.0,  40.0,  40.0,  70.0,  40.0, 300.0, 170.0,  70.0, 100.0, 150.0, 150.0, 125.0, 125.0, 100.0,  40.0, 100.0, 999.0, 150.0, 150.0, 150.0, 200.0, 999.0,  40.0, 999.0, 999.0,\n HS    = 999.0, 36.25, 36.25, 36.25, 36.25, 44.14, 36.35, 42.00, 39.18, 54.53, 54.53, 47.35, 41.69, 47.35, 51.93, 51.75, 60.00, 51.93, 999.0, 42.00, 42.00, 42.00, 42.00, 999.0, 36.25, 999.0, 999.0,\n TOPT  = 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0,\n RSMAX = 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_FEB = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_APR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.3,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAY = 0.0,   0.2,   0.2,   0.2,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.4,   0.4,   0.0,   0.3,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUN = 0.0,   0.3,   0.3,   0.3,   0.4,   0.4,   0.4,   0.2,   0.3,   0.4,   0.4,   0.7,   0.5,   0.5,   0.4,   0.0,   0.4,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUL = 0.0,   0.4,   0.4,   0.4,   0.6,   0.6,   0.8,   0.4,   0.6,   0.8,   0.9,   1.3,   0.5,   0.5,   0.7,   0.0,   0.6,   0.6,   0.0,   0.4,   0.4,   0.4,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_AUG = 0.0,   0.5,   0.5,   0.5,   0.9,   0.9,   1.3,   0.6,   0.9,   1.2,   1.2,   1.2,   0.5,   0.6,   0.8,   0.0,   0.9,   0.9,   0.0,   0.6,   0.6,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_SEP = 0.0,   0.4,   0.4,   0.4,   0.7,   1.0,   1.1,   0.8,   1.0,   1.3,   1.6,   1.0,   0.5,   0.6,   1.0,   0.0,   0.7,   1.0,   0.0,   0.7,   0.8,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_OCT = 0.0,   0.3,   0.3,   0.3,   0.3,   0.8,   0.4,   0.7,   0.6,   0.7,   1.4,   0.8,   0.5,   0.7,   1.0,   0.0,   0.3,   0.8,   0.0,   0.5,   0.7,   0.5,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_NOV = 0.0,   0.3,   0.3,   0.3,   0.3,   0.4,   0.4,   0.3,   0.3,   0.4,   0.6,   0.6,   0.5,   0.6,   0.5,   0.0,   0.3,   0.4,   0.0,   0.3,   0.3,   0.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_DEC = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.4,   0.2,   0.3,   0.4,   0.4,   0.5,   0.5,   0.5,   0.4,   0.0,   0.3,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n LAI_JAN = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_FEB = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.3,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAR = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.0,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_APR = 0.0,   0.0,   0.0,   0.0,   0.4,   0.6,   0.7,   0.6,   0.7,   0.8,   1.2,   0.6,   4.5,   4.0,   2.6,   0.0,   0.4,   0.6,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAY = 0.0,   1.0,   1.0,   1.0,   1.1,   2.0,   1.2,   1.5,   1.4,   1.8,   3.0,   1.2,   4.5,   4.0,   3.5,   0.0,   1.1,   2.0,   0.0,   0.6,   1.7,   1.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUN = 0.0,   2.0,   2.0,   2.0,   2.5,   3.3,   3.0,   2.3,   2.6,   3.6,   4.7,   2.0,   4.5,   4.0,   4.3,   0.0,   2.5,   3.3,   0.0,   1.5,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUL = 0.0,   3.0,   3.0,   3.0,   3.2,   3.7,   3.5,   2.3,   2.9,   3.8,   4.5,   2.6,   4.5,   4.0,   4.3,   0.0,   3.2,   3.7,   0.0,   1.7,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_AUG = 0.0,   3.0,   3.0,   3.0,   2.2,   3.2,   1.5,   1.7,   1.6,   2.1,   3.4,   1.7,   4.5,   4.0,   3.7,   0.0,   2.2,   3.2,   0.0,   0.8,   1.8,   1.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_SEP = 0.0,   1.5,   1.5,   1.5,   1.1,   1.3,   0.7,   0.6,   0.7,   0.9,   1.2,   1.0,   4.5,   4.0,   2.6,   0.0,   1.1,   1.3,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_OCT = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.5,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_NOV = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.2,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_DEC = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n SLAREA=0.0228,0.0200,0.0200,0.0295,0.0223,0.0277,0.0060,0.0227,0.0188,0.0236,0.0258,0.0200,0.0200,0.0090,0.0223,0.0422,0.0390,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1   = 41.87,  0.00,  0.00,  2.52,  0.04, 17.11,  0.02, 21.62,  0.11, 22.80, 46.86,  0.00,  0.00,  0.46, 30.98,  2.31,  1.63,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS2   =  0.98,  0.00,  0.00,  0.16,  0.09,  0.28,  0.05,  0.92,  0.22,  0.59,  0.38,  0.00,  0.00,  3.34,  0.96,  1.47,  1.07,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS3   =  1.82,  0.00,  0.00,  0.23,  0.05,  0.81,  0.03,  1.73,  1.26,  1.37,  1.84,  0.00,  0.00,  1.85,  1.84,  1.70,  1.21,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS4   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS5   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n/\n\n&noahmp_modis_veg_categories\n VEG_DATASET_DESCRIPTION = \"modified igbp modis noah\"\n NVEG = 20\n/\n\n&noahmp_modis_parameters\n! 1          'Evergreen Needleleaf Forest'                       -> USGS 14\n! 2,         'Evergreen Broadleaf Forest'                        -> USGS 13\n! 3,         'Deciduous Needleleaf Forest'                       -> USGS 12\n! 4,         'Deciduous Broadleaf Forest'                        -> USGS 11\n! 5,         'Mixed Forests'                                     -> USGS 15\n! 6,         'Closed Shrublands'                                 -> USGS  8 \"shrubland\"\n! 7,         'Open Shrublands'                                   -> USGS  9 \"shrubland/grassland\"\n! 8,         'Woody Savannas'                                    -> USGS  8 \"shrubland\"\n! 9,         'Savannas'                                          -> USGS 10\n! 10,        'Grasslands'                                        -> USGS  7\n! 11         'Permanent wetlands'                                -> avg of USGS 17 and 18 (herb. wooded wetland)\n! 12,        'Croplands'                                         -> USGS  2 \"dryland cropland\"\n! 13,        'Urban and Built-Up'                                -> USGS  1\n! 14         'cropland/natural vegetation mosaic'                -> USGS  5 \"cropland/grassland\"\n! 15,        'Snow and Ice'                                      -> USGS 24\n! 16,        'Barren or Sparsely Vegetated'                      -> USGS 19\n! 17,        'Water'                                             -> USGS 16\n! 18,        'Wooded Tundra'                                     -> USGS 21\n! 19,        'Mixed Tundra'                                      -> USGS 22\n! 20,        'Barren Tundra'                                     -> USGS 23\n\n ISURBAN                   = 13\n ISWATER                   = 17\n ISBARREN                  = 16\n ISICE                     = 15\n ISCROP                    = 12\n EBLFOREST                 =  2\n NATURAL                   = 14\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1       2       3       4       5       6       7       8       9      10      11      12      13      14      15      16      17      18      19      20\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,\n DLEAF =  0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,\n Z0MVT =  1.09,   1.10,   0.85,   0.80,   0.80,   0.20,   0.06,   0.60,   0.50,   0.12,   0.30,   0.15,   1.00,   0.14,   0.00,   0.00,   0.00,   0.30,   0.20,   0.03,\n HVT   =  20.0,   20.0,   18.0,   16.0,   16.0,   1.10,   1.10,   13.0,   10.0,   1.00,   5.00,   2.00,   15.0,   1.50,   0.00,   0.00,   0.00,   4.00,   2.00,   0.50,\n HVB   =  8.50,   8.00,   7.00,   11.5,   10.0,   0.10,   0.10,   0.10,   0.10,   0.05,   0.10,   0.10,   1.00,   0.10,   0.00,   0.00,   0.00,   0.30,   0.20,   0.10,\n DEN   =  0.28,   0.02,   0.28,   0.10,   0.10,   10.0,   10.0,   10.0,   0.02,   100.,   5.05,   25.0,   0.01,   25.0,   0.00,   0.01,   0.01,   1.00,   1.00,   1.00,\n RC    =  1.20,   3.60,   1.20,   1.40,   1.40,   0.12,   0.12,   0.12,   3.00,   0.03,   0.75,   0.08,   1.00,   0.08,   0.00,   0.01,   0.01,   0.30,   0.30,   0.30,\n MFSNO =  2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.07,   0.10,   0.07,   0.10,   0.10,   0.07,   0.07,   0.07,   0.10,   0.11,  0.105,   0.11,   0.00,   0.11,   0.00,   0.00,   0.00,   0.10,   0.10,   0.10,\n RHOL_NIR=0.35,   0.45,   0.35,   0.45,   0.45,   0.35,   0.35,   0.35,   0.45,   0.58,  0.515,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.45,   0.45,   0.45,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.36,   0.26,   0.36,   0.00,   0.36,   0.00,   0.00,   0.00,   0.16,   0.16,   0.16,\n RHOS_NIR=0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.58,  0.485,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.39,   0.39,   0.39,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.07,   0.06,   0.07,   0.00,   0.07,   0.00,   0.00,   0.00,   0.05,   0.05,   0.05,\n TAUL_NIR=0.10,   0.25,   0.10,   0.25,   0.25,   0.10,   0.10,   0.10,   0.25,   0.25,   0.25,   0.25,   0.00,   0.25,   0.00,   0.00,   0.00,   0.25,   0.25,   0.25,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.220, 0.1105,  0.220,  0.000,  0.220,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n TAUS_NIR=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.380, 0.1905,  0.380,  0.000,  0.380,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n\n XL    = 0.010,  0.010,  0.010,  0.250,  0.250,  0.010,  0.010,  0.010,  0.010,  -0.30, -0.025,  -0.30,  0.000,  -0.30,  0.000,  0.000,  0.000,  0.250,  0.250,  0.250,\n! CWPVT =   3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,\n CWPVT =  0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,\n C3PSN =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n KC25  =  30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,\n AKC   =   2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,\n KO25  =  3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,\n AKO   =   1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,\n AVCMX =   2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,\n AQE   =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n\n LTOVRC=   0.5,   0.55,    0.2,   0.55,    0.5,   0.65,   0.65,   0.65,   0.65,   0.50,    1.4,    1.6,    0.0,    1.2,    0.0,    0.0,    0.0,    1.3,    1.4,    1.0,\n DILEFC=  1.20,   0.50,   1.80,   0.60,   0.80,   0.20,   0.20,   0.20,   0.50,   0.20,    0.4,   0.50,   0.00,   0.35,   0.00,   0.00,   0.00,   0.30,   0.40,   0.30,\n DILEFW=  0.20,   4.00,   0.20,   0.20,   0.20,   0.20,   0.20,   0.20,   0.50,   0.10,    0.2,   0.20,   0.00,   0.20,   0.00,   0.00,   0.00,   0.20,   0.20,   0.20,\n RMF25 =  3.00,   0.65,   4.00,   3.00,   3.00,   0.26,   0.26,   0.26,   0.80,   1.80,    3.2,   1.00,   0.00,   1.45,   0.00,   0.00,   0.00,   3.00,   3.00,   3.00,\n SLA   =    80,     80,     80,     80,     80,     60,     60,     60,     50,     60,     80,     80,     60,     80,      0,      0,      0,     80,     80,     80,\n FRAGR =  0.10,   0.20,   0.10,   0.20,   0.10,   0.20,   0.20,   0.20,   0.20,   0.20,    0.1,   0.20,   0.00,   0.20,   0.00,   0.10,   0.00,   0.10,   0.10,   0.10,\n TMIN  =   265,    273,    268,    273,    268,    273,    273,    273,    273,    273,    268,    273,      0,    273,      0,      0,      0,    268,    268,    268,\n VCMX25=  50.0,   60.0,   60.0,   60.0,   55.0,   40.0,   40.0,   40.0,   40.0,   40.0,   50.0,   80.0,   0.00,   60.0,   0.00,   0.00,   0.00,   50.0,   50.0,   50.0,\n TDLEF =   278,    278,    268,    278,    268,    278,    278,    278,    278,    278,    268,    278,    278,    278,      0,      0,      0,    268,    268,    268,\n BP    =  2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,   2.E3,   2.E3,\n MP    =    6.,     9.,     6.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,\n QE25  =  0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.00,   0.06,   0.00,   0.06,   0.00,   0.06,   0.06,   0.06,\n RMS25 =  0.90,   0.30,   0.64,   0.10,   0.80,   0.10,   0.10,   0.10,   0.32,   0.10,   0.10,   0.10,   0.00,   0.10,   0.00,   0.00,   0.00,   0.10,   0.10,   0.00,\n RMR25 =  0.36,   0.05,   0.05,   0.01,   0.03,   0.00,   0.00,   0.00,   0.01,   1.20,    0.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   2.11,   2.11,   0.00,\n ARM   =   2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,\n FOLNMX=   1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,   0.00,    1.5,   0.00,    1.5,   0.00,    1.5,    1.5,    1.5,\n WDPOOL=  1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   0.00,    0.5,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   1.00,   1.00,   0.00,\n WRRAT =  30.0,   30.0,   30.0,   30.0,   30.0,   3.00,   3.00,   3.00,   3.00,   0.00,   15.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   3.00,   3.00,   0.00,\n MRP   =  0.37,   0.23,   0.37,   0.40,   0.30,   0.19,   0.19,   0.19,   0.40,   0.17,  0.285,   0.23,   0.00,   0.23,   0.00,   0.00,   0.00,   0.23,   0.20,   0.00,\n NROOT =     4,      4,      4,      4,      4,      3,      3,      3,      3,      3,      2,      3,      1,      3,      1,      1,      0,      3,      3,      2,     \n RGL   =  30.0,   30.0,   30.0,   30.0,   30.0,  100.0,  100.0,  100.0,   65.0,  100.0,   65.0,  100.0,  999.0,  100.0,  999.0,  999.0,   30.0,  100.0,  100.0,  100.0,\n RS    = 125.0,  150.0,  150.0,  100.0,  125.0,  300.0,  170.0,  300.0,   70.0,   40.0,   70.0,   40.0,  200.0,   40.0,  999.0,  999.0,  100.0,  150.0,  150.0,  200.0,\n HS    = 47.35,  41.69,  47.35,  54.53,  51.93,  42.00,  39.18,  42.00,  54.53,  36.35,  55.97,  36.25,  999.0,  36.25,  999.0,  999.0,  51.75,  42.00,  42.00,  42.00,\n TOPT  = 298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,\n RSMAX = 5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_FEB = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAR = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_APR = 0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAY = 0.4,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_JUN = 0.5,    0.5,    0.7,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.4,    0.3,    0.0,    0.4,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n SAI_JUL = 0.5,    0.5,    1.3,    0.9,    0.7,    0.6,    0.4,    0.7,    0.8,    0.8,    0.6,    0.4,    0.0,    0.6,    0.0,    0.0,    0.0,    0.4,    0.4,    0.0,\n SAI_AUG = 0.6,    0.5,    1.2,    1.2,    0.8,    0.9,    0.6,    1.2,    1.2,    1.3,    0.9,    0.5,    0.0,    0.9,    0.0,    0.0,    0.0,    0.6,    0.6,    0.0,\n SAI_SEP = 0.6,    0.5,    1.0,    1.6,    1.0,    1.2,    0.8,    1.4,    1.3,    1.1,    0.9,    0.4,    0.0,    0.7,    0.0,    0.0,    0.0,    0.8,    0.7,    0.0,\n SAI_OCT = 0.7,    0.5,    0.8,    1.4,    1.0,    0.9,    0.7,    1.1,    0.7,    0.4,    0.6,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.7,    0.5,    0.0,\n SAI_NOV = 0.6,    0.5,    0.6,    0.6,    0.5,    0.4,    0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.3,    0.3,    0.0,\n SAI_DEC = 0.5,    0.5,    0.5,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n\n LAI_JAN = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_FEB = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_MAR = 4.0,    4.5,    0.0,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_APR = 4.0,    4.5,    0.6,    1.2,    2.6,    0.9,    0.6,    1.0,    0.8,    0.7,    0.5,    0.0,    0.0,    0.4,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_MAY = 4.0,    4.5,    1.2,    3.0,    3.5,    2.2,    1.5,    2.4,    1.8,    1.2,    1.5,    1.0,    0.0,    1.1,    0.0,    0.0,    0.0,    1.7,    1.2,    0.0,\n LAI_JUN = 4.0,    4.5,    2.0,    4.7,    4.3,    3.5,    2.3,    4.1,    3.6,    3.0,    2.9,    2.0,    0.0,    2.5,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_JUL = 4.0,    4.5,    2.6,    4.5,    4.3,    3.5,    2.3,    4.1,    3.8,    3.5,    3.5,    3.0,    0.0,    3.2,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_AUG = 4.0,    4.5,    1.7,    3.4,    3.7,    2.5,    1.7,    2.7,    2.1,    1.5,    2.7,    3.0,    0.0,    2.2,    0.0,    0.0,    0.0,    1.8,    1.3,    0.0,\n LAI_SEP = 4.0,    4.5,    1.0,    1.2,    2.6,    0.9,    0.6,    1.0,    0.9,    0.7,    1.2,    1.5,    0.0,    1.1,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_OCT = 4.0,    4.5,    0.5,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_NOV = 4.0,    4.5,    0.2,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_DEC = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n\n SLAREA=0.0090, 0.0200, 0.0200, 0.0258, 0.0223, 0.0227, 0.0188, 0.0227, 0.0236, 0.0060, 0.0295, 0.0200, 0.0228, 0.0223,   0.02,   0.02, 0.0422,   0.02,   0.02,   0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1  =  0.46,   0.00,   0.00,  46.86,  30.98,  21.62,   0.11,  21.62,  22.80,   0.02,  0.815,   0.00,  41.87,   0.04,    0.0,    0.0,   2.31,    0.0,    0.0,    0.0,\n EPS2  =  3.34,   0.00,   0.00,   0.38,   0.96,   0.92,   0.22,   0.92,   0.59,   0.05,  0.535,   0.00,   0.98,   0.09,    0.0,    0.0,   1.47,    0.0,    0.0,    0.0,\n EPS3  =  1.85,   0.00,   0.00,   1.84,   1.84,   1.73,   1.26,   1.73,   1.37,   0.03,  0.605,   0.00,   1.82,   0.05,    0.0,    0.0,   1.70,    0.0,    0.0,    0.0,\n EPS4  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n EPS5  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n\n/\n\n&noahmp_rad_parameters\n !------------------------------------------------------------------------------\n !                1       2       3       4       5       6       7       8     soil color index for soil albedo\n !------------------------------------------------------------------------------\n ALBSAT_VIS =   0.15,   0.11,   0.10,   0.09,   0.08,   0.07,   0.06,   0.05   ! saturated soil albedos\n ALBSAT_NIR =   0.30,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! saturated soil albedos\n ALBDRY_VIS =   0.27,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! dry soil albedos\n ALBDRY_NIR =   0.54,   0.44,   0.40,   0.36,   0.32,   0.28,   0.24,   0.20   ! dry soil albedos\n ALBICE     =   0.80,   0.55                                                   ! albedo land ice: 1=vis, 2=nir\n ALBLAK     =   0.60,   0.40                                                   ! albedo frozen lakes: 1=vis, 2=nir\n OMEGAS     =   0.8 ,   0.4                                                    ! two-stream parameter omega for snow\n BETADS     =   0.5                                                            ! two-stream parameter betad for snow\n BETAIS     =   0.5                                                            ! two-stream parameter betaI for snow\n EG         =   0.97,   0.98                                                   ! emissivity soil surface 1-soil;2-lake\n\n/\n\n&noahmp_global_parameters\n\n! atmospheric constituants\n\n  CO2    = 395.e-06     !co2 partial pressure\n  O2     = 0.209        !o2 partial pressure\n\n! runoff parameters used for SIMTOP and SIMGM:\n\n  TIMEAN = 10.5         !gridcell mean topgraphic index (global mean)\n  FSATMX = 0.38         !maximum surface saturated fraction (global mean)\n\n! adjustable parameters for snow processes\n\n  Z0SNO  = 0.002        !snow surface roughness length (m) (0.002)\n  SSI    = 0.03         !liquid water holding capacity for snowpack (m3/m3) (0.03)\n  SNOW_RET_FAC  = 5.e-5 !snowpack water release timescale factor (1/s)\n  SWEMX  = 1.00         !new snow mass to fully cover old snow (mm)\n                        !equivalent to 10mm depth (density = 100 kg/m3)\n  TAU0          = 1.e6  !tau0 from Yang97 eqn. 10a\n  GRAIN_GROWTH  = 5000. !growth from vapor diffusion Yang97 eqn. 10b\n  EXTRA_GROWTH  = 10.   !extra growth near freezing Yang97 eqn. 10c\n  DIRT_SOOT     = 0.3   !dirt and soot term Yang97 eqn. 10d\n  BATS_COSZ     = 2.0   !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n  BATS_VIS_NEW  = 0.95  !new snow visible albedo\n  BATS_NIR_NEW  = 0.65  !new snow NIR albedo\n  BATS_VIS_AGE  = 0.2   !age factor for diffuse visible snow albedo Yang97 eqn. 17\n  BATS_NIR_AGE  = 0.5   !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n  BATS_VIS_DIR  = 0.4   !cosz factor for direct visible snow albedo Yang97 eqn. 15\n  BATS_NIR_DIR  = 0.4   !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n  RSURF_SNOW = 50.0     !surface resistence for snow [s/m]\n  RSURF_EXP = 5.0       !exponent in the shape parameter for soil resistance option 1\n  IMPERV_URBAN = 0.95   !impervious fraction to use for urban type [0-1]\n  SCAMAX = 1.0          !maximum fractional snow covered area [0-1]\n  SWE_LIMIT = 5000.0    !maximum SWE limit [mm]\n\n/\n\n&noahmp_crop_parameters\n\n ! NCROP = 5\n !  1: Corn\n !  2: Soybean\n !  3: Sorghum\n !  4: Rice\n !  5: Winter wheat\n\nDEFAULT_CROP = 0                                      ! The default crop type(1-5); if zero, use generic dynamic vegetation \n\n!----------------------------------------------------------\n!                1       2       3       4       5\n!----------------------------------------------------------\n \nPLTDAY     =    130,    111,    111,    111,    111,  ! Planting date\nHSDAY      =    280,    300,    300,    300,    300,  ! Harvest date\nPLANTPOP   =   78.0,   78.0,   78.0,   78.0,   78.0,  ! Plant density [per ha] - used?\nIRRI       =    0.0,    0.0,    0.0,    0.0,    0.0,  ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n\nGDDTBASE   =   10.0,   10.0,   10.0,   10.0,   10.0,  ! Base temperature for GDD accumulation [C]\nGDDTCUT    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! Upper temperature for GDD accumulation [C]\nGDDS1      =   60.0,   50.0,   50.0,   50.0,   50.0,  ! GDD from seeding to emergence\nGDDS2      =  675.0,  718.0,  718.0,  718.0,  718.0,  ! GDD from seeding to initial vegetative \nGDDS3      = 1183.0,  933.0,  933.0,  933.0,  933.0,  ! GDD from seeding to post vegetative \nGDDS4      = 1253.0, 1103.0, 1103.0, 1103.0, 1103.0,  ! GDD from seeding to intial reproductive\nGDDS5      = 1605.0, 1555.0, 1555.0, 1555.0, 1555.0,  ! GDD from seeding to pysical maturity \n\nC3C4       =      2,      1,      2,      2,      2,  ! photosynthetic pathway:  1. = c3 2. = c4\nAref       =    7.0,    7.0,    7.0,    7.0,    7.0,  ! reference maximum CO2 assimulation rate \nPSNRF      =   0.85,   0.85,   0.85,   0.85,   0.85,  ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\nI2PAR      =    0.5,    0.5,    0.5,    0.5,    0.5,  ! Fraction of incoming solar radiation to photosynthetically active radiation\nTASSIM0    =    8.0,    8.0,    8.0,    8.0,    8.0,  ! Minimum temperature for CO2 assimulation [C]\nTASSIM1    =   18.0,   18.0,   18.0,   18.0,   18.0,  ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\nTASSIM2    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\nK          =   0.55,   0.55,   0.55,   0.55,   0.55,  ! light extinction coefficient\nEPSI       =   12.5,   12.5,   12.5,   12.5,   12.5,  ! initial light use efficiency\n\nQ10MR      =    2.0,    2.0,    2.0,    2.0,    2.0,  ! q10 for maintainance respiration\nFOLN_MX    =    1.5,    1.5,    1.5,    1.5,    1.5,  ! foliage nitrogen concentration when f(n)=1 (%)\nLEFREEZ    =    268,    268,    268,    268,    268,  ! characteristic T for leaf freezing [K]\n\nDILE_FC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for temperature leaf stress death [1/s]\nDILE_FC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0, \nDILE_FC_S5 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S6 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nDILE_FW_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for water leaf stress death [1/s]\nDILE_FW_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FW_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S5 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S6 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nFRA_GR     =    0.2,    0.2,    0.2,    0.2,    0.2,  ! fraction of growth respiration\n\nLF_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of leaf turnover  [1/s]\nLF_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLF_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S5 =    0.2,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S6 =    0.3,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nST_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of stem turnover  [1/s]\nST_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nST_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nST_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nST_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nRT_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of root tunrover  [1/s]\nRT_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRT_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nRT_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nRT_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n             \nLFMR25     =    1.0,    1.0,    1.0,    1.0,    1.0,  !  leaf maintenance respiration at 25C [umol CO2/m**2  /s]\nSTMR25     =   0.05,    0.1,    0.1,    0.1,    0.1,  !  stem maintenance respiration at 25C [umol CO2/kg bio/s]\nRTMR25     =   0.05,    0.0,    0.0,    0.0,    0.0,  !  root maintenance respiration at 25C [umol CO2/kg bio/s]\nGRAINMR25  =    0.0,    0.1,    0.1,    0.1,    0.1,  ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n\nLFPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to leaf\nLFPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLFPT_S3    =    0.4,    0.4,    0.4,    0.4,    0.4,\nLFPT_S4    =    0.2,    0.2,    0.2,    0.2,    0.2,\nLFPT_S5    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S6    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nSTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to stem\nSTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nSTPT_S3    =    0.2,    0.2,    0.2,    0.2,    0.2,\nSTPT_S4    =    0.5,    0.5,    0.5,    0.5,    0.5,\nSTPT_S5    =    0.0,   0.15,   0.15,   0.15,   0.15,\nSTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nSTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nSTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0, \n\nRTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to root\nRTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRTPT_S3    =   0.34,    0.4,    0.4,    0.4,    0.4,\nRTPT_S4    =    0.3,    0.3,    0.3,    0.3,    0.3,\nRTPT_S5    =   0.05,   0.05,   0.05,   0.05,   0.05,\nRTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nRTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nRTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n   \nGRAINPT_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to grain\nGRAINPT_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nGRAINPT_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S5 =   0.95,    0.8,    0.8,    0.8,    0.8,\nGRAINPT_S6 =    1.0,    0.9,    0.9,    0.9,    0.9,\nGRAINPT_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n\nBIO2LAI   =  0.035,  0.015,  0.015,  0.015,  0.015,  ! leaf are per living leaf biomass [m^2/kg]\n\n/\n\n&noahmp_optional_parameters\n\n !------------------------------------------------------------------------------\n ! Saxton and Rawls 2006 Pedo-transfer function coefficients\n !------------------------------------------------------------------------------\n\n sr2006_theta_1500t_a =   -0.024   ! sand coefficient\n sr2006_theta_1500t_b =    0.487   ! clay coefficient\n sr2006_theta_1500t_c =    0.006   ! orgm coefficient\n sr2006_theta_1500t_d =    0.005   ! sand*orgm coefficient\n sr2006_theta_1500t_e =   -0.013   ! clay*orgm coefficient\n sr2006_theta_1500t_f =    0.068   ! sand*clay coefficient\n sr2006_theta_1500t_g =    0.031   ! constant adjustment\n\n sr2006_theta_1500_a  =    0.14    ! theta_1500t coefficient\n sr2006_theta_1500_b  =   -0.02    ! constant adjustment\n\n sr2006_theta_33t_a   =   -0.251   ! sand coefficient\n sr2006_theta_33t_b   =    0.195   ! clay coefficient\n sr2006_theta_33t_c   =    0.011   ! orgm coefficient\n sr2006_theta_33t_d   =    0.006   ! sand*orgm coefficient\n sr2006_theta_33t_e   =   -0.027   ! clay*orgm coefficient\n sr2006_theta_33t_f   =    0.452   ! sand*clay coefficient\n sr2006_theta_33t_g   =    0.299   ! constant adjustment\n\n sr2006_theta_33_a    =    1.283   ! theta_33t*theta_33t coefficient\n sr2006_theta_33_b    =   -0.374   ! theta_33t coefficient\n sr2006_theta_33_c    =   -0.015   ! constant adjustment\n\n sr2006_theta_s33t_a  =    0.278   ! sand coefficient\n sr2006_theta_s33t_b  =    0.034   ! clay coefficient\n sr2006_theta_s33t_c  =    0.022   ! orgm coefficient\n sr2006_theta_s33t_d  =   -0.018   ! sand*orgm coefficient\n sr2006_theta_s33t_e  =   -0.027   ! clay*orgm coefficient\n sr2006_theta_s33t_f  =   -0.584   ! sand*clay coefficient\n sr2006_theta_s33t_g  =    0.078   ! constant adjustment\n\n sr2006_theta_s33_a   =    0.636   ! theta_s33t coefficient\n sr2006_theta_s33_b   =   -0.107   ! constant adjustment\n\n sr2006_psi_et_a      =  -21.67    ! sand coefficient\n sr2006_psi_et_b      =  -27.93    ! clay coefficient\n sr2006_psi_et_c      =  -81.97    ! theta_s33 coefficient\n sr2006_psi_et_d      =   71.12    ! sand*theta_s33 coefficient\n sr2006_psi_et_e      =    8.29    ! clay*theta_s33 coefficient\n sr2006_psi_et_f      =   14.05    ! sand*clay coefficient\n sr2006_psi_et_g      =   27.16    ! constant adjustment\n\n sr2006_psi_e_a       =    0.02    ! psi_et*psi_et coefficient\n sr2006_psi_e_b       =   -0.113   ! psi_et coefficient\n sr2006_psi_e_c       =   -0.7     ! constant adjustment\n\n sr2006_smcmax_a      =   -0.097   ! sand adjustment\n sr2006_smcmax_b      =    0.043   ! constant adjustment\n \n/\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/Hawaii/SOILPARM.TBL",
    "content": "Soil Parameters\nSTAS\n19,1   'BB      DRYSMC      F11     MAXSMC   REFSMC   SATPSI  SATDK      SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     2.79,    0.010,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,   0.010,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.74,    0.047,    -0.569,   0.434,   0.312,   0.141,  5.23E-6,  8.05E-6,   0.047,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.33,    0.084,     0.162,   0.476,   0.360,   0.759,  2.81E-6,  2.39E-5,   0.084,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     3.86,    0.061,     0.162,   0.484,   0.347,   0.955,  2.18E-6,  1.66E-5,   0.061,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     6.77,    0.069,    -1.491,   0.404,   0.315,   0.135,  4.45E-6,  1.01E-5,   0.069,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     8.72,    0.120,    -1.118,   0.464,   0.387,   0.617,  2.03E-6,  2.35E-5,   0.120,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.17,    0.103,    -1.297,   0.465,   0.382,   0.263,  2.45E-6,  1.13E-5,   0.103,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.73,    0.100,    -3.209,   0.406,   0.338,   0.098,  7.22E-6,  1.87E-5,   0.100,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.39,    0.126,    -1.916,   0.468,   0.404,   0.324,  1.34E-6,  9.64E-6,   0.126,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.55,    0.138,    -2.138,   0.468,   0.412,   0.468,  9.74E-7,  1.12E-5,   0.138,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,       0.0,     1.0,     0.0,     0.0,      0.0,      0.0,     0.0,  0.60,  0.001,  0.00,  0.00, 'WATER'\n15,    2.79,    0.006,    -1.111,    0.20,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.07,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.25,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.55,    0.030,   -10.472,   0.468,   0.454,   0.468,  9.74E-7,  1.12E-5,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    2.79,    0.006,    -0.472,   0.200,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    2.79,     0.01,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,    0.01,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\nSoil Parameters\nSTAS-RUC\n19,1   'BB      DRYSMC       HC     MAXSMC   REFSMC   SATPSI  SATDK       SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     4.05,    0.002,      1.47,   0.395,   0.174,   0.121,  1.76E-4,  0.608E-6,   0.033,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.38,    0.035,      1.41,   0.410,   0.179,   0.090,  1.56E-4,  0.514E-5,   0.055,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.90,    0.041,      1.34,   0.435,   0.249,   0.218,  3.47E-5,  0.805E-5,   0.095,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.39,    0.050,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.137,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     7.12,    0.068,      1.18,   0.420,   0.299,   0.299,  6.30E-6,  0.990E-5,   0.148,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     7.75,    0.060,      1.32,   0.477,   0.357,   0.356,  1.70E-6,  0.237E-4,   0.208,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.52,    0.085,      1.23,   0.476,   0.391,   0.630,  2.45E-6,  0.113E-4,   0.230,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.40,    0.100,      1.18,   0.426,   0.316,   0.153,  2.17E-6,  0.187E-4,   0.210,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.40,    0.070,      1.15,   0.492,   0.409,   0.490,  1.03E-6,  0.964E-5,   0.250,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.40,    0.068,      1.09,   0.482,   0.400,   0.405,  1.28E-6,  0.112E-4,   0.268,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.39,    0.027,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.117,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,      4.18,   1.0,     1.0,     0.0,      0.0,       0.0,     0.0,    0.00,  0.001,  0.00,  0.00, 'WATER'\n15,    4.05,    0.004,      2.03,   0.200,   0.10 ,   0.121,  1.41E-4,  0.136E-3,   0.006,  0.60,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.90,    0.065,      2.10,   0.435,   0.249,   0.218,  3.47E-5,  0.514E-5,   0.114,  0.05,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.40,    0.030,      1.41,   0.468,   0.454,   0.468,  9.74E-7,  0.112E-4,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    4.05,    0.006,      1.41,   0.200,   0.17,    0.069,  1.41E-4,  0.136E-3,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    4.05,     0.01,      1.47,   0.339,   0.236,   0.069,  1.76E-4,  0.608E-6,   0.060,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\n\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/PuertoRico/CHANPARM.TBL",
    "content": "Channel Parameters\nStreamOrder\n10,1,  'Bw     HLINK   ChSSlp   MannN'\n1,     1.6,    0.02,    0.03,      0.09\n2,     2.4,    0.02,    0.03,      0.07\n3,     3.5,    0.02,    0.03,      0.06\n4,     5.3,    0.03,    0.04,      0.05\n5,     7.4,    0.03,    0.04,      0.04\n6,     11.,    0.03,    0.04,      0.03\n7,     14.,    0.03,    0.04,      0.03\n8,     16.,    0.10,    0.04,      0.02\n9,     26.,    0.30,    0.05,      0.02\n10,    110.,    0.30,    0.10,      0.02\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/PuertoRico/GENPARM.TBL",
    "content": "General Parameters\nSLOPE_DATA\n9\n0.1 \n0.6\n1.0\n0.35\n0.55\n0.8\n0.63\n0.0\n0.0\nSBETA_DATA\n-2.0\nFXEXP_DATA\n2.0\nCSOIL_DATA\n2.00E+6\nSALP_DATA\n2.6\nREFDK_DATA\n2.0E-6\nREFKDT_DATA\n3.0\nFRZK_DATA\n0.15\nZBOT_DATA\n-8.0\nCZIL_DATA\n0.1\nSMLOW_DATA\n0.5\nSMHIGH_DATA\n3.0\nLVCOEF_DATA\n0.5\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/PuertoRico/HYDRO.TBL",
    "content": "     28 USGS for OV_ROUGH\n   SFC_ROUGH'\n     0.025,    'Urban and Built-Up Land'  \n     0.035,    'Dryland Cropland and Pasture' \n     0.035,    'Irrigated Cropland and Pasture' \n     0.055,    'Mixed Dryland/Irrigated Cropland and Pasture' \n     0.035,    'Cropland/Grassland Mosaic'\n     0.068,    'Cropland/Woodland Mosaic' \n     0.055,    'Grassland' \n     0.055,    'Shrubland' \n     0.055,    'Mixed Shrubland/Grassland' \n     0.055,    'Savanna' \n     0.200,    'Deciduous Broadleaf Forest' \n     0.200,    'Deciduous Needleleaf Forest' \n     0.200,    'Evergreen Broadleaf Forest'\n     0.200,    'Evergreen Needleleaf Forest'  \n     0.200,    'Mixed Forest' \n     0.005,    'Water Bodies' \n     0.070,    'Herbaceous Wetland' \n     0.070,    'Wooded Wetland' \n     0.035,    'Barren or Sparsely Vegetated' \n     0.055,    'Herbaceous Tundra' \n     0.055,    'Wooded Tundra' \n     0.055,    'Mixed Tundra' \n     0.055,    'Bare Ground Tundra' \n     0.010,    'Snow or Ice' \n     0.010,    'Playa' \n     0.100,    'Lava'   \n     0.010,    'White Sand' \n     0.005,    'Non-Ocean Water Bodies'\n19, for SATDK\nSATDK     MAXSMC    REFSMC   WLTSMC  QTZ    '\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'SAND'\n1.41E-5,  0.421,    0.283,   0.028,  0.82, 'LOAMY SAND'\n5.23E-6,  0.434,    0.312,   0.047,  0.60, 'SANDY LOAM'\n2.81E-6,  0.476,    0.360,   0.084,  0.25, 'SILT LOAM'\n2.18E-6,  0.484,    0.347,   0.061,  0.10, 'SILT'\n3.38E-6,  0.439,    0.329,   0.066,  0.40, 'LOAM'\n4.45E-6,  0.404,    0.315,   0.069,  0.60, 'SANDY CLAY LOAM'\n2.03E-6,  0.464,    0.387,   0.120,  0.10, 'SILTY CLAY LOAM'\n2.45E-6,  0.465,    0.382,   0.103,  0.35, 'CLAY LOAM'\n7.22E-6,  0.406,    0.338,   0.100,  0.52, 'SANDY CLAY'\n1.34E-6,  0.468,    0.404,   0.126,  0.10, 'SILTY CLAY'\n9.74E-7,  0.468,    0.412,   0.138,  0.25, 'CLAY'\n3.38E-6,  0.439,    0.329,   0.066,  0.05, 'ORGANIC MATERIAL'\n    0.0,  1.0,      0.0,     0.0,    0.60, 'WATER'\n1.41E-4,  0.20,     0.170,   0.006,  0.07, 'BEDROCK'\n1.41E-5,  0.421,    0.283,   0.028,  0.25, 'OTHER(land-ice)'\n9.74E-7,  0.468,    0.454,   0.030,  0.60, 'PLAYA'\n1.41E-4,  0.200,    0.170,   0.006,  0.52, 'LAVA'\n4.66E-5,  0.339,    0.192,   0.010,  0.92, 'WHITE SAND'\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/PuertoRico/MPTABLE.TBL",
    "content": "&noahmp_usgs_veg_categories\n VEG_DATASET_DESCRIPTION = \"USGS\"\n NVEG = 27\n/\n&noahmp_usgs_parameters\n ! NVEG = 27\n !  1: Urban and Built-Up Land\n !  2: Dryland Cropland and Pasture\n !  3: Irrigated Cropland and Pasture\n !  4: Mixed Dryland/Irrigated Cropland and Pasture\n !  5: Cropland/Grassland Mosaic\n !  6: Cropland/Woodland Mosaic\n !  7: Grassland\n !  8: Shrubland\n !  9: Mixed Shrubland/Grassland\n ! 10: Savanna\n ! 11: Deciduous Broadleaf Forest\n ! 12: Deciduous Needleleaf Forest\n ! 13: Evergreen Broadleaf Forest\n ! 14: Evergreen Needleleaf Forest\n ! 15: Mixed Forest\n ! 16: Water Bodies\n ! 17: Herbaceous Wetland\n ! 18: Wooded Wetland\n ! 19: Barren or Sparsely Vegetated\n ! 20: Herbaceous Tundra\n ! 21: Wooded Tundra\n ! 22: Mixed Tundra\n ! 23: Bare Ground Tundra\n ! 24: Snow or Ice\n ! 25: Playa\n ! 26: Lava\n ! 27: White Sand\n\n ISURBAN                   =  1\n ISWATER                   = 16\n ISBARREN                  = 19\n ISICE                     = 24\n ISCROP                    =  2\n EBLFOREST                 = 13\n NATURAL                   =  5\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1      2      3      4      5      6      7      8      9      10     11     12     13     14     15     16     17     18     19     20     21     22     23     24     25     26    27\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,   0.1,\n DLEAF =  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,  0.04,\n Z0MVT =  1.00,  0.15,  0.15,  0.15,  0.14,  0.50,  0.12,  0.06,  0.09,  0.50,  0.80,  0.85,  1.10,  1.09,  0.80,  0.00,  0.12,  0.50,  0.00,  0.10,  0.30,  0.20,  0.03,  0.00,  0.01,  0.00,  0.00,\n HVT   =  15.0,  2.00,  2.00,  2.00,  1.50,  8.00,  1.00,  1.10,  1.10,  10.0,  16.0,  18.0,  20.0,  20.0,  16.0,  0.00,  0.50,  10.0,  0.00,  0.50,  4.00,  2.00,  0.50,  0.00,  0.10,  0.00,  0.00,\n HVB   =  1.00,  0.10,  0.10,  0.10,  0.10,  0.15,  0.05,  0.10,  0.10,  0.10,  11.5,  7.00,  8.00,  8.50,  10.0,  0.00,  0.05,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n DEN   =  0.01,  25.0,  25.0,  25.0,  25.0,  25.0,  100.,  10.0,  10.0,  0.02,  0.10,  0.28,  0.02,  0.28,  0.10,  0.01,  10.0,  0.10,  0.01,  1.00,  1.00,  1.00,  1.00,  0.00,  0.01,  0.01,  0.01,\n RC    =  1.00,  0.08,  0.08,  0.08,  0.08,  0.08,  0.03,  0.12,  0.12,  3.00,  1.40,  1.20,  3.60,  1.20,  1.40,  0.01,  0.10,  1.40,  0.01,  0.30,  0.30,  0.30,  0.30,  0.00,  0.01,  0.01,  0.01,\n MFSNO =  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,  2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.00,  0.11,  0.11,  0.11,  0.11,  0.11,  0.11,  0.07,  0.10,  0.10,  0.10,  0.07,  0.10,  0.07,  0.10,  0.00,  0.11,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n RHOL_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.35,  0.45,  0.45,  0.45,  0.35,  0.45,  0.35,  0.45,  0.00,  0.58,  0.45,  0.00,  0.45,  0.45,  0.45,  0.45,  0.00,  0.45,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.00,  0.36,  0.36,  0.36,  0.36,  0.36,  0.36,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.16,  0.00,  0.36,  0.16,  0.00,  0.16,  0.16,  0.16,  0.16,  0.00,  0.16,  0.00,  0.00,\n RHOS_NIR=0.00,  0.58,  0.58,  0.58,  0.58,  0.58,  0.58,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.39,  0.00,  0.58,  0.39,  0.00,  0.39,  0.39,  0.39,  0.39,  0.00,  0.39,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.00,  0.07,  0.07,  0.07,  0.07,  0.07,  0.07,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.00,  0.07,  0.05,  0.00,  0.05,  0.05,  0.05,  0.05,  0.00,  0.05,  0.00,  0.00,\n TAUL_NIR=0.00,  0.25,  0.25,  0.25,  0.25,  0.25,  0.25,  0.10,  0.10,  0.25,  0.25,  0.10,  0.25,  0.10,  0.25,  0.00,  0.25,  0.25,  0.00,  0.25,  0.25,  0.25,  0.25,  0.00,  0.25,  0.00,  0.00,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.00, 0.220, 0.220, 0.220, 0.220, 0.220, 0.220, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.220, 0.001, 0.000, 0.220, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n TAUS_NIR=0.00, 0.380, 0.380, 0.380, 0.380, 0.380, 0.380, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.000, 0.380, 0.001, 0.000, 0.380, 0.001, 0.001, 0.001, 0.000, 0.001, 0.000, 0.000,\n\n XL    = 0.000, -0.30, -0.30, -0.30, -0.30, -0.30, -0.30, 0.010, 0.250, 0.010, 0.250, 0.010, 0.010, 0.010, 0.250, 0.000, -0.30, 0.250, 0.000, -0.30, 0.250, 0.250, 0.250, 0.000, 0.250, 0.000, 0.000,\n CWPVT =  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,  0.18,\n C3PSN =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n KC25  =  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0,\n AKC   =   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,   2.1,\n KO25  =  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,  3.E4,\n AKO   =   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,   1.2,\n AVCMX =   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,   2.4,\n AQE   =   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,   1.0,\n\n LTOVRC=   0.0,   1.2,   1.2,   1.2,   1.2,  1.30,  0.50,  0.65,  0.70,  0.65,  0.55,   0.2,  0.55,   0.5,   0.5,   0.0,   1.4,   1.4,   0.0,   1.2,   1.3,   1.4,   1.0,   0.0,   1.0,   0.0,   0.0,\n DILEFC=  0.00,  0.50,  0.50,  0.50,  0.35,  0.20,  0.20,  0.20,  0.50,  0.50,  0.60,  1.80,  0.50,  1.20,  0.80,  0.00,  0.40,  0.40,  0.00,  0.40,  0.30,  0.40,  0.30,  0.00,  0.30,  0.00,  0.00,\n DILEFW=  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.20,  0.50,  0.20,  0.20,  4.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.00,  0.20,  0.20,  0.20,  0.20,  0.00,  0.20,  0.00,  0.00,\n RMF25 =  0.00,  1.00,  1.40,  1.45,  1.45,  1.45,  1.80,  0.26,  0.26,  0.80,  3.00,  4.00,  0.65,  3.00,  3.00,  0.00,  3.20,  3.20,  0.00,  3.20,  3.00,  3.00,  3.00,  0.00,  3.00,  0.00,  0.00,\n SLA   =    60,    80,    80,    80,    80,    80,    60,    60,    60,    50,    80,    80,    80,    80,    80,     0,    80,    80,     0,    80,    80,    80,    80,     0,    80,     0,     0,\n FRAGR =  0.00,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.20,  0.10,  0.20,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.00,  0.10,  0.00,  0.00,\n TMIN  =     0,   273,   273,   273,   273,   273,   273,   273,   273,   273,   273,   268,   273,   265,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n VCMX25=  0.00,  80.0,  80.0,  80.0,  60.0,  70.0,  40.0,  40.0,  40.0,  40.0,  60.0,  60.0,  60.0,  50.0,  55.0,  0.00,  50.0,  50.0,  0.00,  50.0,  50.0,  50.0,  50.0,  0.00,  50.0,  0.00,  0.00,\n TDLEF =   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   278,   268,   278,   278,   268,     0,   268,   268,     0,   268,   268,   268,   268,     0,   268,     0,     0,\n BP    = 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3,  2.E3, 1.E15,  2.E3, 1.E15, 1.E15,\n MP    =    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    6.,    9.,    6.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,    9.,\n QE25  =    0.,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.06,  0.00,  0.06,  0.00,  0.00,\n RMS25 =  0.00,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.10,  0.32,  0.10,  0.64,  0.30,  0.90,  0.80,  0.00,  0.10,  0.10,  0.00,  0.10,  0.10,  0.10,  0.00,  0.00,  0.00,  0.00,  0.00,\n RMR25 =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.20,  0.00,  0.00,  0.01,  0.01,  0.05,  0.05,  0.36,  0.03,  0.00,  0.00,  0.00,  0.00,  2.11,  2.11,  2.11,  0.00,  0.00,  0.00,  0.00,  0.00,\n ARM   =   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,   2.0,\n FOLNMX=  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,   1.5,  0.00,   1.5,  0.00,  0.00,\n WDPOOL=  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  1.00,  0.00,  0.00,  1.00,  0.00,  0.00,  1.00,  1.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n WRRAT =  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  0.00,  3.00,  3.00,  3.00,  30.0,  30.0,  30.0,  30.0,  30.0,  0.00,  0.00,  30.0,  0.00,  0.00,  3.00,  3.00,  0.00,  0.00,  0.00,  0.00,  0.00,\n MRP   =  0.00,  0.23,  0.23,  0.23,  0.23,  0.23,  0.17,  0.19,  0.19,  0.40,  0.40,  0.37,  0.23,  0.37,  0.30,  0.00,  0.17,  0.40,  0.00,  0.17,  0.23,  0.20,  0.00,  0.00,  0.20,  0.00,  0.00,\n NROOT =     1,     3,     3,     3,     3,     3,     3,     3,     3,     3,     4,     4,     4,     4,     4,     0,     2,     2,     1,     3,     3,     3,     2,     1,     1,     0,     0,\n RGL   = 999.0, 100.0, 100.0, 100.0, 100.0,  65.0, 100.0, 100.0, 100.0,  65.0,  30.0,  30.0,  30.0,  30.0,  30.0,  30.0, 100.0,  30.0, 999.0, 100.0, 100.0, 100.0, 100.0, 999.0, 100.0, 999.0, 999.0,\n RS    = 200.0,  40.0,  40.0,  40.0,  40.0,  70.0,  40.0, 300.0, 170.0,  70.0, 100.0, 150.0, 150.0, 125.0, 125.0, 100.0,  40.0, 100.0, 999.0, 150.0, 150.0, 150.0, 200.0, 999.0,  40.0, 999.0, 999.0,\n HS    = 999.0, 36.25, 36.25, 36.25, 36.25, 44.14, 36.35, 42.00, 39.18, 54.53, 54.53, 47.35, 41.69, 47.35, 51.93, 51.75, 60.00, 51.93, 999.0, 42.00, 42.00, 42.00, 42.00, 999.0, 36.25, 999.0, 999.0,\n TOPT  = 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0, 298.0,\n RSMAX = 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000., 5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_FEB = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.3,   0.5,   0.4,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_APR = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.3,   0.4,   0.0,   0.2,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_MAY = 0.0,   0.2,   0.2,   0.2,   0.3,   0.3,   0.3,   0.2,   0.2,   0.3,   0.4,   0.4,   0.5,   0.4,   0.4,   0.0,   0.3,   0.3,   0.0,   0.1,   0.2,   0.1,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUN = 0.0,   0.3,   0.3,   0.3,   0.4,   0.4,   0.4,   0.2,   0.3,   0.4,   0.4,   0.7,   0.5,   0.5,   0.4,   0.0,   0.4,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_JUL = 0.0,   0.4,   0.4,   0.4,   0.6,   0.6,   0.8,   0.4,   0.6,   0.8,   0.9,   1.3,   0.5,   0.5,   0.7,   0.0,   0.6,   0.6,   0.0,   0.4,   0.4,   0.4,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_AUG = 0.0,   0.5,   0.5,   0.5,   0.9,   0.9,   1.3,   0.6,   0.9,   1.2,   1.2,   1.2,   0.5,   0.6,   0.8,   0.0,   0.9,   0.9,   0.0,   0.6,   0.6,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_SEP = 0.0,   0.4,   0.4,   0.4,   0.7,   1.0,   1.1,   0.8,   1.0,   1.3,   1.6,   1.0,   0.5,   0.6,   1.0,   0.0,   0.7,   1.0,   0.0,   0.7,   0.8,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_OCT = 0.0,   0.3,   0.3,   0.3,   0.3,   0.8,   0.4,   0.7,   0.6,   0.7,   1.4,   0.8,   0.5,   0.7,   1.0,   0.0,   0.3,   0.8,   0.0,   0.5,   0.7,   0.5,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_NOV = 0.0,   0.3,   0.3,   0.3,   0.3,   0.4,   0.4,   0.3,   0.3,   0.4,   0.6,   0.6,   0.5,   0.6,   0.5,   0.0,   0.3,   0.4,   0.0,   0.3,   0.3,   0.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n SAI_DEC = 0.0,   0.3,   0.3,   0.3,   0.3,   0.3,   0.4,   0.2,   0.3,   0.4,   0.4,   0.5,   0.5,   0.5,   0.4,   0.0,   0.3,   0.4,   0.0,   0.2,   0.2,   0.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n LAI_JAN = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_FEB = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.3,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAR = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.0,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_APR = 0.0,   0.0,   0.0,   0.0,   0.4,   0.6,   0.7,   0.6,   0.7,   0.8,   1.2,   0.6,   4.5,   4.0,   2.6,   0.0,   0.4,   0.6,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_MAY = 0.0,   1.0,   1.0,   1.0,   1.1,   2.0,   1.2,   1.5,   1.4,   1.8,   3.0,   1.2,   4.5,   4.0,   3.5,   0.0,   1.1,   2.0,   0.0,   0.6,   1.7,   1.2,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUN = 0.0,   2.0,   2.0,   2.0,   2.5,   3.3,   3.0,   2.3,   2.6,   3.6,   4.7,   2.0,   4.5,   4.0,   4.3,   0.0,   2.5,   3.3,   0.0,   1.5,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_JUL = 0.0,   3.0,   3.0,   3.0,   3.2,   3.7,   3.5,   2.3,   2.9,   3.8,   4.5,   2.6,   4.5,   4.0,   4.3,   0.0,   3.2,   3.7,   0.0,   1.7,   2.1,   1.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_AUG = 0.0,   3.0,   3.0,   3.0,   2.2,   3.2,   1.5,   1.7,   1.6,   2.1,   3.4,   1.7,   4.5,   4.0,   3.7,   0.0,   2.2,   3.2,   0.0,   0.8,   1.8,   1.3,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_SEP = 0.0,   1.5,   1.5,   1.5,   1.1,   1.3,   0.7,   0.6,   0.7,   0.9,   1.2,   1.0,   4.5,   4.0,   2.6,   0.0,   1.1,   1.3,   0.0,   0.4,   1.3,   0.8,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_OCT = 0.0,   0.0,   0.0,   0.0,   0.3,   0.2,   0.6,   0.2,   0.4,   0.5,   0.3,   0.5,   4.5,   4.0,   2.2,   0.0,   0.3,   0.3,   0.0,   0.3,   1.1,   0.7,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_NOV = 0.0,   0.0,   0.0,   0.0,   0.3,   0.0,   0.5,   0.0,   0.3,   0.3,   0.0,   0.2,   4.5,   4.0,   2.0,   0.0,   0.3,   0.3,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n LAI_DEC = 0.0,   0.0,   0.0,   0.0,   0.2,   0.0,   0.4,   0.0,   0.2,   0.3,   0.0,   0.0,   4.5,   4.0,   2.0,   0.0,   0.2,   0.2,   0.0,   0.2,   1.0,   0.6,   0.0,   0.0,   0.0,   0.0,   0.0,\n\n SLAREA=0.0228,0.0200,0.0200,0.0295,0.0223,0.0277,0.0060,0.0227,0.0188,0.0236,0.0258,0.0200,0.0200,0.0090,0.0223,0.0422,0.0390,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,  0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1   = 41.87,  0.00,  0.00,  2.52,  0.04, 17.11,  0.02, 21.62,  0.11, 22.80, 46.86,  0.00,  0.00,  0.46, 30.98,  2.31,  1.63,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS2   =  0.98,  0.00,  0.00,  0.16,  0.09,  0.28,  0.05,  0.92,  0.22,  0.59,  0.38,  0.00,  0.00,  3.34,  0.96,  1.47,  1.07,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS3   =  1.82,  0.00,  0.00,  0.23,  0.05,  0.81,  0.03,  1.73,  1.26,  1.37,  1.84,  0.00,  0.00,  1.85,  1.84,  1.70,  1.21,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS4   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n EPS5   =   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,   0.0,\n/\n\n&noahmp_modis_veg_categories\n VEG_DATASET_DESCRIPTION = \"modified igbp modis noah\"\n NVEG = 20\n/\n\n&noahmp_modis_parameters\n! 1          'Evergreen Needleleaf Forest'                       -> USGS 14\n! 2,         'Evergreen Broadleaf Forest'                        -> USGS 13\n! 3,         'Deciduous Needleleaf Forest'                       -> USGS 12\n! 4,         'Deciduous Broadleaf Forest'                        -> USGS 11\n! 5,         'Mixed Forests'                                     -> USGS 15\n! 6,         'Closed Shrublands'                                 -> USGS  8 \"shrubland\"\n! 7,         'Open Shrublands'                                   -> USGS  9 \"shrubland/grassland\"\n! 8,         'Woody Savannas'                                    -> USGS  8 \"shrubland\"\n! 9,         'Savannas'                                          -> USGS 10\n! 10,        'Grasslands'                                        -> USGS  7\n! 11         'Permanent wetlands'                                -> avg of USGS 17 and 18 (herb. wooded wetland)\n! 12,        'Croplands'                                         -> USGS  2 \"dryland cropland\"\n! 13,        'Urban and Built-Up'                                -> USGS  1\n! 14         'cropland/natural vegetation mosaic'                -> USGS  5 \"cropland/grassland\"\n! 15,        'Snow and Ice'                                      -> USGS 24\n! 16,        'Barren or Sparsely Vegetated'                      -> USGS 19\n! 17,        'Water'                                             -> USGS 16\n! 18,        'Wooded Tundra'                                     -> USGS 21\n! 19,        'Mixed Tundra'                                      -> USGS 22\n! 20,        'Barren Tundra'                                     -> USGS 23\n\n ISURBAN                   = 13\n ISWATER                   = 17\n ISBARREN                  = 16\n ISICE                     = 15\n ISCROP                    = 12\n EBLFOREST                 =  2\n NATURAL                   = 14\n LOW_DENSITY_RESIDENTIAL   = 31\n HIGH_DENSITY_RESIDENTIAL  = 32\n HIGH_INTENSITY_INDUSTRIAL = 33\n\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n !          1       2       3       4       5       6       7       8       9      10      11      12      13      14      15      16      17      18      19      20\n !---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n CH2OP =   0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,    0.1,\n DLEAF =  0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,\n Z0MVT =  1.09,   1.10,   0.85,   0.80,   0.80,   0.20,   0.06,   0.60,   0.50,   0.12,   0.30,   0.15,   1.00,   0.14,   0.00,   0.00,   0.00,   0.30,   0.20,   0.03,\n HVT   =  20.0,   20.0,   18.0,   16.0,   16.0,   1.10,   1.10,   13.0,   10.0,   1.00,   5.00,   2.00,   15.0,   1.50,   0.00,   0.00,   0.00,   4.00,   2.00,   0.50,\n HVB   =  8.50,   8.00,   7.00,   11.5,   10.0,   0.10,   0.10,   0.10,   0.10,   0.05,   0.10,   0.10,   1.00,   0.10,   0.00,   0.00,   0.00,   0.30,   0.20,   0.10,\n DEN   =  0.28,   0.02,   0.28,   0.10,   0.10,   10.0,   10.0,   10.0,   0.02,   100.,   5.05,   25.0,   0.01,   25.0,   0.00,   0.01,   0.01,   1.00,   1.00,   1.00,\n RC    =  1.20,   3.60,   1.20,   1.40,   1.40,   0.12,   0.12,   0.12,   3.00,   0.03,   0.75,   0.08,   1.00,   0.08,   0.00,   0.01,   0.01,   0.30,   0.30,   0.30,\n MFSNO =  2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,   2.50,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOL_VIS=0.07,   0.10,   0.07,   0.10,   0.10,   0.07,   0.07,   0.07,   0.10,   0.11,  0.105,   0.11,   0.00,   0.11,   0.00,   0.00,   0.00,   0.10,   0.10,   0.10,\n RHOL_NIR=0.35,   0.45,   0.35,   0.45,   0.45,   0.35,   0.35,   0.35,   0.45,   0.58,  0.515,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.45,   0.45,   0.45,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n RHOS_VIS=0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.16,   0.36,   0.26,   0.36,   0.00,   0.36,   0.00,   0.00,   0.00,   0.16,   0.16,   0.16,\n RHOS_NIR=0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.39,   0.58,  0.485,   0.58,   0.00,   0.58,   0.00,   0.00,   0.00,   0.39,   0.39,   0.39,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUL_VIS=0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.07,   0.06,   0.07,   0.00,   0.07,   0.00,   0.00,   0.00,   0.05,   0.05,   0.05,\n TAUL_NIR=0.10,   0.25,   0.10,   0.25,   0.25,   0.10,   0.10,   0.10,   0.25,   0.25,   0.25,   0.25,   0.00,   0.25,   0.00,   0.00,   0.00,   0.25,   0.25,   0.25,\n\n ! Row 1:  Vis\n ! Row 2:  Near IR\n TAUS_VIS=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.220, 0.1105,  0.220,  0.000,  0.220,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n TAUS_NIR=0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.001,  0.380, 0.1905,  0.380,  0.000,  0.380,  0.000,  0.000,  0.000,  0.001,  0.001,  0.001,\n\n XL    = 0.010,  0.010,  0.010,  0.250,  0.250,  0.010,  0.010,  0.010,  0.010,  -0.30, -0.025,  -0.30,  0.000,  -0.30,  0.000,  0.000,  0.000,  0.250,  0.250,  0.250,\n! CWPVT =   3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,    3.0,\n CWPVT =  0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,   0.18,\n C3PSN =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n KC25  =  30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,   30.0,\n AKC   =   2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,    2.1,\n KO25  =  3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,   3.E4,\n AKO   =   1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,    1.2,\n AVCMX =   2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,    2.4,\n AQE   =   1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,    1.0,\n\n LTOVRC=   0.5,   0.55,    0.2,   0.55,    0.5,   0.65,   0.65,   0.65,   0.65,   0.50,    1.4,    1.6,    0.0,    1.2,    0.0,    0.0,    0.0,    1.3,    1.4,    1.0,\n DILEFC=  1.20,   0.50,   1.80,   0.60,   0.80,   0.20,   0.20,   0.20,   0.50,   0.20,    0.4,   0.50,   0.00,   0.35,   0.00,   0.00,   0.00,   0.30,   0.40,   0.30,\n DILEFW=  0.20,   4.00,   0.20,   0.20,   0.20,   0.20,   0.20,   0.20,   0.50,   0.10,    0.2,   0.20,   0.00,   0.20,   0.00,   0.00,   0.00,   0.20,   0.20,   0.20,\n RMF25 =  3.00,   0.65,   4.00,   3.00,   3.00,   0.26,   0.26,   0.26,   0.80,   1.80,    3.2,   1.00,   0.00,   1.45,   0.00,   0.00,   0.00,   3.00,   3.00,   3.00,\n SLA   =    80,     80,     80,     80,     80,     60,     60,     60,     50,     60,     80,     80,     60,     80,      0,      0,      0,     80,     80,     80,\n FRAGR =  0.10,   0.20,   0.10,   0.20,   0.10,   0.20,   0.20,   0.20,   0.20,   0.20,    0.1,   0.20,   0.00,   0.20,   0.00,   0.10,   0.00,   0.10,   0.10,   0.10,\n TMIN  =   265,    273,    268,    273,    268,    273,    273,    273,    273,    273,    268,    273,      0,    273,      0,      0,      0,    268,    268,    268,\n VCMX25=  50.0,   60.0,   60.0,   60.0,   55.0,   40.0,   40.0,   40.0,   40.0,   40.0,   50.0,   80.0,   0.00,   60.0,   0.00,   0.00,   0.00,   50.0,   50.0,   50.0,\n TDLEF =   278,    278,    268,    278,    268,    278,    278,    278,    278,    278,    268,    278,    278,    278,      0,      0,      0,    268,    268,    268,\n BP    =  2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,  1.E15,   2.E3,   2.E3,   2.E3,\n MP    =    6.,     9.,     6.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,     9.,\n QE25  =  0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.00,   0.06,   0.00,   0.06,   0.00,   0.06,   0.06,   0.06,\n RMS25 =  0.90,   0.30,   0.64,   0.10,   0.80,   0.10,   0.10,   0.10,   0.32,   0.10,   0.10,   0.10,   0.00,   0.10,   0.00,   0.00,   0.00,   0.10,   0.10,   0.00,\n RMR25 =  0.36,   0.05,   0.05,   0.01,   0.03,   0.00,   0.00,   0.00,   0.01,   1.20,    0.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   2.11,   2.11,   0.00,\n ARM   =   2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,    2.0,\n FOLNMX=   1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,    1.5,   0.00,    1.5,   0.00,    1.5,   0.00,    1.5,    1.5,    1.5,\n WDPOOL=  1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   1.00,   0.00,    0.5,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   1.00,   1.00,   0.00,\n WRRAT =  30.0,   30.0,   30.0,   30.0,   30.0,   3.00,   3.00,   3.00,   3.00,   0.00,   15.0,   0.00,   0.00,   0.00,   0.00,   0.00,   0.00,   3.00,   3.00,   0.00,\n MRP   =  0.37,   0.23,   0.37,   0.40,   0.30,   0.19,   0.19,   0.19,   0.40,   0.17,  0.285,   0.23,   0.00,   0.23,   0.00,   0.00,   0.00,   0.23,   0.20,   0.00,\n NROOT =     4,      4,      4,      4,      4,      3,      3,      3,      3,      3,      2,      3,      1,      3,      1,      1,      0,      3,      3,      2,     \n RGL   =  30.0,   30.0,   30.0,   30.0,   30.0,  100.0,  100.0,  100.0,   65.0,  100.0,   65.0,  100.0,  999.0,  100.0,  999.0,  999.0,   30.0,  100.0,  100.0,  100.0,\n RS    = 125.0,  150.0,  150.0,  100.0,  125.0,  300.0,  170.0,  300.0,   70.0,   40.0,   70.0,   40.0,  200.0,   40.0,  999.0,  999.0,  100.0,  150.0,  150.0,  200.0,\n HS    = 47.35,  41.69,  47.35,  54.53,  51.93,  42.00,  39.18,  42.00,  54.53,  36.35,  55.97,  36.25,  999.0,  36.25,  999.0,  999.0,  51.75,  42.00,  42.00,  42.00,\n TOPT  = 298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,  298.0,\n RSMAX = 5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,  5000.,\n\n! Monthly values, one row for each month:\n SAI_JAN = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_FEB = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAR = 0.4,    0.5,    0.3,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_APR = 0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_MAY = 0.4,    0.5,    0.4,    0.4,    0.4,    0.3,    0.2,    0.4,    0.3,    0.3,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.1,    0.0,\n SAI_JUN = 0.5,    0.5,    0.7,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.4,    0.3,    0.0,    0.4,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n SAI_JUL = 0.5,    0.5,    1.3,    0.9,    0.7,    0.6,    0.4,    0.7,    0.8,    0.8,    0.6,    0.4,    0.0,    0.6,    0.0,    0.0,    0.0,    0.4,    0.4,    0.0,\n SAI_AUG = 0.6,    0.5,    1.2,    1.2,    0.8,    0.9,    0.6,    1.2,    1.2,    1.3,    0.9,    0.5,    0.0,    0.9,    0.0,    0.0,    0.0,    0.6,    0.6,    0.0,\n SAI_SEP = 0.6,    0.5,    1.0,    1.6,    1.0,    1.2,    0.8,    1.4,    1.3,    1.1,    0.9,    0.4,    0.0,    0.7,    0.0,    0.0,    0.0,    0.8,    0.7,    0.0,\n SAI_OCT = 0.7,    0.5,    0.8,    1.4,    1.0,    0.9,    0.7,    1.1,    0.7,    0.4,    0.6,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.7,    0.5,    0.0,\n SAI_NOV = 0.6,    0.5,    0.6,    0.6,    0.5,    0.4,    0.3,    0.5,    0.4,    0.4,    0.4,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.3,    0.3,    0.0,\n SAI_DEC = 0.5,    0.5,    0.5,    0.4,    0.4,    0.3,    0.2,    0.4,    0.4,    0.4,    0.3,    0.3,    0.0,    0.3,    0.0,    0.0,    0.0,    0.2,    0.2,    0.0,\n\n LAI_JAN = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_FEB = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_MAR = 4.0,    4.5,    0.0,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_APR = 4.0,    4.5,    0.6,    1.2,    2.6,    0.9,    0.6,    1.0,    0.8,    0.7,    0.5,    0.0,    0.0,    0.4,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_MAY = 4.0,    4.5,    1.2,    3.0,    3.5,    2.2,    1.5,    2.4,    1.8,    1.2,    1.5,    1.0,    0.0,    1.1,    0.0,    0.0,    0.0,    1.7,    1.2,    0.0,\n LAI_JUN = 4.0,    4.5,    2.0,    4.7,    4.3,    3.5,    2.3,    4.1,    3.6,    3.0,    2.9,    2.0,    0.0,    2.5,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_JUL = 4.0,    4.5,    2.6,    4.5,    4.3,    3.5,    2.3,    4.1,    3.8,    3.5,    3.5,    3.0,    0.0,    3.2,    0.0,    0.0,    0.0,    2.1,    1.8,    0.0,\n LAI_AUG = 4.0,    4.5,    1.7,    3.4,    3.7,    2.5,    1.7,    2.7,    2.1,    1.5,    2.7,    3.0,    0.0,    2.2,    0.0,    0.0,    0.0,    1.8,    1.3,    0.0,\n LAI_SEP = 4.0,    4.5,    1.0,    1.2,    2.6,    0.9,    0.6,    1.0,    0.9,    0.7,    1.2,    1.5,    0.0,    1.1,    0.0,    0.0,    0.0,    1.3,    0.8,    0.0,\n LAI_OCT = 4.0,    4.5,    0.5,    0.3,    2.2,    0.3,    0.2,    0.4,    0.5,    0.6,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.1,    0.7,    0.0,\n LAI_NOV = 4.0,    4.5,    0.2,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.5,    0.3,    0.0,    0.0,    0.3,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n LAI_DEC = 4.0,    4.5,    0.0,    0.0,    2.0,    0.0,    0.0,    0.2,    0.3,    0.4,    0.2,    0.0,    0.0,    0.2,    0.0,    0.0,    0.0,    1.0,    0.6,    0.0,\n\n SLAREA=0.0090, 0.0200, 0.0200, 0.0258, 0.0223, 0.0227, 0.0188, 0.0227, 0.0236, 0.0060, 0.0295, 0.0200, 0.0228, 0.0223,   0.02,   0.02, 0.0422,   0.02,   0.02,   0.02,\n\n! Five types, one row for each type (BVOC currently not active).\n EPS1  =  0.46,   0.00,   0.00,  46.86,  30.98,  21.62,   0.11,  21.62,  22.80,   0.02,  0.815,   0.00,  41.87,   0.04,    0.0,    0.0,   2.31,    0.0,    0.0,    0.0,\n EPS2  =  3.34,   0.00,   0.00,   0.38,   0.96,   0.92,   0.22,   0.92,   0.59,   0.05,  0.535,   0.00,   0.98,   0.09,    0.0,    0.0,   1.47,    0.0,    0.0,    0.0,\n EPS3  =  1.85,   0.00,   0.00,   1.84,   1.84,   1.73,   1.26,   1.73,   1.37,   0.03,  0.605,   0.00,   1.82,   0.05,    0.0,    0.0,   1.70,    0.0,    0.0,    0.0,\n EPS4  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n EPS5  =   0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,    0.0,\n\n/\n\n&noahmp_rad_parameters\n !------------------------------------------------------------------------------\n !                1       2       3       4       5       6       7       8     soil color index for soil albedo\n !------------------------------------------------------------------------------\n ALBSAT_VIS =   0.15,   0.11,   0.10,   0.09,   0.08,   0.07,   0.06,   0.05   ! saturated soil albedos\n ALBSAT_NIR =   0.30,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! saturated soil albedos\n ALBDRY_VIS =   0.27,   0.22,   0.20,   0.18,   0.16,   0.14,   0.12,   0.10   ! dry soil albedos\n ALBDRY_NIR =   0.54,   0.44,   0.40,   0.36,   0.32,   0.28,   0.24,   0.20   ! dry soil albedos\n ALBICE     =   0.80,   0.55                                                   ! albedo land ice: 1=vis, 2=nir\n ALBLAK     =   0.60,   0.40                                                   ! albedo frozen lakes: 1=vis, 2=nir\n OMEGAS     =   0.8 ,   0.4                                                    ! two-stream parameter omega for snow\n BETADS     =   0.5                                                            ! two-stream parameter betad for snow\n BETAIS     =   0.5                                                            ! two-stream parameter betaI for snow\n EG         =   0.97,   0.98                                                   ! emissivity soil surface 1-soil;2-lake\n\n/\n\n&noahmp_global_parameters\n\n! atmospheric constituants\n\n  CO2    = 395.e-06     !co2 partial pressure\n  O2     = 0.209        !o2 partial pressure\n\n! runoff parameters used for SIMTOP and SIMGM:\n\n  TIMEAN = 10.5         !gridcell mean topgraphic index (global mean)\n  FSATMX = 0.38         !maximum surface saturated fraction (global mean)\n\n! adjustable parameters for snow processes\n\n  Z0SNO  = 0.002        !snow surface roughness length (m) (0.002)\n  SSI    = 0.03         !liquid water holding capacity for snowpack (m3/m3) (0.03)\n  SNOW_RET_FAC  = 5.e-5 !snowpack water release timescale factor (1/s)\n  SWEMX  = 1.00         !new snow mass to fully cover old snow (mm)\n                        !equivalent to 10mm depth (density = 100 kg/m3)\n  TAU0          = 1.e6  !tau0 from Yang97 eqn. 10a\n  GRAIN_GROWTH  = 5000. !growth from vapor diffusion Yang97 eqn. 10b\n  EXTRA_GROWTH  = 10.   !extra growth near freezing Yang97 eqn. 10c\n  DIRT_SOOT     = 0.3   !dirt and soot term Yang97 eqn. 10d\n  BATS_COSZ     = 2.0   !zenith angle snow albedo adjustment; b in Yang97 eqn. 15\n  BATS_VIS_NEW  = 0.95  !new snow visible albedo\n  BATS_NIR_NEW  = 0.65  !new snow NIR albedo\n  BATS_VIS_AGE  = 0.2   !age factor for diffuse visible snow albedo Yang97 eqn. 17\n  BATS_NIR_AGE  = 0.5   !age factor for diffuse NIR snow albedo Yang97 eqn. 18\n  BATS_VIS_DIR  = 0.4   !cosz factor for direct visible snow albedo Yang97 eqn. 15\n  BATS_NIR_DIR  = 0.4   !cosz factor for direct NIR snow albedo Yang97 eqn. 16\n  RSURF_SNOW = 50.0     !surface resistence for snow [s/m]\n  RSURF_EXP = 5.0       !exponent in the shape parameter for soil resistance option 1\n  IMPERV_URBAN = 0.95   !impervious fraction to use for urban type [0-1]\n  SCAMAX = 1.0          !maximum fractional snow covered area [0-1]\n  SWE_LIMIT = 5000.0    !maximum SWE limit [mm]\n\n/\n\n&noahmp_crop_parameters\n\n ! NCROP = 5\n !  1: Corn\n !  2: Soybean\n !  3: Sorghum\n !  4: Rice\n !  5: Winter wheat\n\nDEFAULT_CROP = 0                                      ! The default crop type(1-5); if zero, use generic dynamic vegetation \n\n!----------------------------------------------------------\n!                1       2       3       4       5\n!----------------------------------------------------------\n \nPLTDAY     =    130,    111,    111,    111,    111,  ! Planting date\nHSDAY      =    280,    300,    300,    300,    300,  ! Harvest date\nPLANTPOP   =   78.0,   78.0,   78.0,   78.0,   78.0,  ! Plant density [per ha] - used?\nIRRI       =    0.0,    0.0,    0.0,    0.0,    0.0,  ! Irrigation strategy 0= non-irrigation 1=irrigation (no water-stress)\n\nGDDTBASE   =   10.0,   10.0,   10.0,   10.0,   10.0,  ! Base temperature for GDD accumulation [C]\nGDDTCUT    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! Upper temperature for GDD accumulation [C]\nGDDS1      =   60.0,   50.0,   50.0,   50.0,   50.0,  ! GDD from seeding to emergence\nGDDS2      =  675.0,  718.0,  718.0,  718.0,  718.0,  ! GDD from seeding to initial vegetative \nGDDS3      = 1183.0,  933.0,  933.0,  933.0,  933.0,  ! GDD from seeding to post vegetative \nGDDS4      = 1253.0, 1103.0, 1103.0, 1103.0, 1103.0,  ! GDD from seeding to intial reproductive\nGDDS5      = 1605.0, 1555.0, 1555.0, 1555.0, 1555.0,  ! GDD from seeding to pysical maturity \n\nC3C4       =      2,      1,      2,      2,      2,  ! photosynthetic pathway:  1. = c3 2. = c4\nAref       =    7.0,    7.0,    7.0,    7.0,    7.0,  ! reference maximum CO2 assimulation rate \nPSNRF      =   0.85,   0.85,   0.85,   0.85,   0.85,  ! CO2 assimulation reduction factor(0-1) (caused by non-modeling part,e.g.pest,weeds)\nI2PAR      =    0.5,    0.5,    0.5,    0.5,    0.5,  ! Fraction of incoming solar radiation to photosynthetically active radiation\nTASSIM0    =    8.0,    8.0,    8.0,    8.0,    8.0,  ! Minimum temperature for CO2 assimulation [C]\nTASSIM1    =   18.0,   18.0,   18.0,   18.0,   18.0,  ! CO2 assimulation linearly increasing until temperature reaches T1 [C]\nTASSIM2    =   30.0,   30.0,   30.0,   30.0,   30.0,  ! CO2 assmilation rate remain at Aref until temperature reaches T2 [C]\nK          =   0.55,   0.55,   0.55,   0.55,   0.55,  ! light extinction coefficient\nEPSI       =   12.5,   12.5,   12.5,   12.5,   12.5,  ! initial light use efficiency\n\nQ10MR      =    2.0,    2.0,    2.0,    2.0,    2.0,  ! q10 for maintainance respiration\nFOLN_MX    =    1.5,    1.5,    1.5,    1.5,    1.5,  ! foliage nitrogen concentration when f(n)=1 (%)\nLEFREEZ    =    268,    268,    268,    268,    268,  ! characteristic T for leaf freezing [K]\n\nDILE_FC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for temperature leaf stress death [1/s]\nDILE_FC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0, \nDILE_FC_S5 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S6 =    0.5,    0.5,    0.5,    0.5,    0.5,\nDILE_FC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nDILE_FW_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! coeficient for water leaf stress death [1/s]\nDILE_FW_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nDILE_FW_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S5 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S6 =    0.2,    0.2,    0.2,    0.2,    0.2,\nDILE_FW_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nDILE_FW_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nFRA_GR     =    0.2,    0.2,    0.2,    0.2,    0.2,  ! fraction of growth respiration\n\nLF_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of leaf turnover  [1/s]\nLF_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLF_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S5 =    0.2,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S6 =    0.3,   0.48,   0.48,   0.48,   0.48,\nLF_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nLF_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nST_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of stem turnover  [1/s]\nST_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nST_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nST_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nST_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nST_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nRT_OVRC_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of root tunrover  [1/s]\nRT_OVRC_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRT_OVRC_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S5 =   0.12,   0.12,   0.12,   0.12,   0.12,\nRT_OVRC_S6 =   0.06,   0.06,   0.06,   0.06,   0.06,\nRT_OVRC_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nRT_OVRC_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n             \nLFMR25     =    1.0,    1.0,    1.0,    1.0,    1.0,  !  leaf maintenance respiration at 25C [umol CO2/m**2  /s]\nSTMR25     =   0.05,    0.1,    0.1,    0.1,    0.1,  !  stem maintenance respiration at 25C [umol CO2/kg bio/s]\nRTMR25     =   0.05,    0.0,    0.0,    0.0,    0.0,  !  root maintenance respiration at 25C [umol CO2/kg bio/s]\nGRAINMR25  =    0.0,    0.1,    0.1,    0.1,    0.1,  ! grain maintenance respiration at 25C [umol CO2/kg bio/s]\n\nLFPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to leaf\nLFPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nLFPT_S3    =    0.4,    0.4,    0.4,    0.4,    0.4,\nLFPT_S4    =    0.2,    0.2,    0.2,    0.2,    0.2,\nLFPT_S5    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S6    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nLFPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n\nSTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to stem\nSTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nSTPT_S3    =    0.2,    0.2,    0.2,    0.2,    0.2,\nSTPT_S4    =    0.5,    0.5,    0.5,    0.5,    0.5,\nSTPT_S5    =    0.0,   0.15,   0.15,   0.15,   0.15,\nSTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nSTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nSTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0, \n\nRTPT_S1    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to root\nRTPT_S2    =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nRTPT_S3    =   0.34,    0.4,    0.4,    0.4,    0.4,\nRTPT_S4    =    0.3,    0.3,    0.3,    0.3,    0.3,\nRTPT_S5    =   0.05,   0.05,   0.05,   0.05,   0.05,\nRTPT_S6    =    0.0,   0.05,   0.05,   0.05,   0.05,\nRTPT_S7    =    0.0,    0.0,    0.0,    0.0,    0.0,\nRTPT_S8    =    0.0,    0.0,    0.0,    0.0,    0.0,\n   \nGRAINPT_S1 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! fraction of carbohydrate flux to grain\nGRAINPT_S2 =    0.0,    0.0,    0.0,    0.0,    0.0,  ! One row for each of 8 stages\nGRAINPT_S3 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S4 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S5 =   0.95,    0.8,    0.8,    0.8,    0.8,\nGRAINPT_S6 =    1.0,    0.9,    0.9,    0.9,    0.9,\nGRAINPT_S7 =    0.0,    0.0,    0.0,    0.0,    0.0,\nGRAINPT_S8 =    0.0,    0.0,    0.0,    0.0,    0.0,\n\n\nBIO2LAI   =  0.035,  0.015,  0.015,  0.015,  0.015,  ! leaf are per living leaf biomass [m^2/kg]\n\n/\n\n&noahmp_optional_parameters\n\n !------------------------------------------------------------------------------\n ! Saxton and Rawls 2006 Pedo-transfer function coefficients\n !------------------------------------------------------------------------------\n\n sr2006_theta_1500t_a =   -0.024   ! sand coefficient\n sr2006_theta_1500t_b =    0.487   ! clay coefficient\n sr2006_theta_1500t_c =    0.006   ! orgm coefficient\n sr2006_theta_1500t_d =    0.005   ! sand*orgm coefficient\n sr2006_theta_1500t_e =   -0.013   ! clay*orgm coefficient\n sr2006_theta_1500t_f =    0.068   ! sand*clay coefficient\n sr2006_theta_1500t_g =    0.031   ! constant adjustment\n\n sr2006_theta_1500_a  =    0.14    ! theta_1500t coefficient\n sr2006_theta_1500_b  =   -0.02    ! constant adjustment\n\n sr2006_theta_33t_a   =   -0.251   ! sand coefficient\n sr2006_theta_33t_b   =    0.195   ! clay coefficient\n sr2006_theta_33t_c   =    0.011   ! orgm coefficient\n sr2006_theta_33t_d   =    0.006   ! sand*orgm coefficient\n sr2006_theta_33t_e   =   -0.027   ! clay*orgm coefficient\n sr2006_theta_33t_f   =    0.452   ! sand*clay coefficient\n sr2006_theta_33t_g   =    0.299   ! constant adjustment\n\n sr2006_theta_33_a    =    1.283   ! theta_33t*theta_33t coefficient\n sr2006_theta_33_b    =   -0.374   ! theta_33t coefficient\n sr2006_theta_33_c    =   -0.015   ! constant adjustment\n\n sr2006_theta_s33t_a  =    0.278   ! sand coefficient\n sr2006_theta_s33t_b  =    0.034   ! clay coefficient\n sr2006_theta_s33t_c  =    0.022   ! orgm coefficient\n sr2006_theta_s33t_d  =   -0.018   ! sand*orgm coefficient\n sr2006_theta_s33t_e  =   -0.027   ! clay*orgm coefficient\n sr2006_theta_s33t_f  =   -0.584   ! sand*clay coefficient\n sr2006_theta_s33t_g  =    0.078   ! constant adjustment\n\n sr2006_theta_s33_a   =    0.636   ! theta_s33t coefficient\n sr2006_theta_s33_b   =   -0.107   ! constant adjustment\n\n sr2006_psi_et_a      =  -21.67    ! sand coefficient\n sr2006_psi_et_b      =  -27.93    ! clay coefficient\n sr2006_psi_et_c      =  -81.97    ! theta_s33 coefficient\n sr2006_psi_et_d      =   71.12    ! sand*theta_s33 coefficient\n sr2006_psi_et_e      =    8.29    ! clay*theta_s33 coefficient\n sr2006_psi_et_f      =   14.05    ! sand*clay coefficient\n sr2006_psi_et_g      =   27.16    ! constant adjustment\n\n sr2006_psi_e_a       =    0.02    ! psi_et*psi_et coefficient\n sr2006_psi_e_b       =   -0.113   ! psi_et coefficient\n sr2006_psi_e_c       =   -0.7     ! constant adjustment\n\n sr2006_smcmax_a      =   -0.097   ! sand adjustment\n sr2006_smcmax_b      =    0.043   ! constant adjustment\n \n/\n"
  },
  {
    "path": "src/template/examples/nwm/parameter_tables/v3.0/PuertoRico/SOILPARM.TBL",
    "content": "Soil Parameters\nSTAS\n19,1   'BB      DRYSMC      F11     MAXSMC   REFSMC   SATPSI  SATDK      SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     2.79,    0.010,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,   0.010,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.74,    0.047,    -0.569,   0.434,   0.312,   0.141,  5.23E-6,  8.05E-6,   0.047,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.33,    0.084,     0.162,   0.476,   0.360,   0.759,  2.81E-6,  2.39E-5,   0.084,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     3.86,    0.061,     0.162,   0.484,   0.347,   0.955,  2.18E-6,  1.66E-5,   0.061,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     6.77,    0.069,    -1.491,   0.404,   0.315,   0.135,  4.45E-6,  1.01E-5,   0.069,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     8.72,    0.120,    -1.118,   0.464,   0.387,   0.617,  2.03E-6,  2.35E-5,   0.120,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.17,    0.103,    -1.297,   0.465,   0.382,   0.263,  2.45E-6,  1.13E-5,   0.103,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.73,    0.100,    -3.209,   0.406,   0.338,   0.098,  7.22E-6,  1.87E-5,   0.100,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.39,    0.126,    -1.916,   0.468,   0.404,   0.324,  1.34E-6,  9.64E-6,   0.126,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.55,    0.138,    -2.138,   0.468,   0.412,   0.468,  9.74E-7,  1.12E-5,   0.138,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.25,    0.066,    -0.327,   0.439,   0.329,   0.355,  3.38E-6,  1.43E-5,   0.066,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,       0.0,     1.0,     0.0,     0.0,      0.0,      0.0,     0.0,  0.60,  0.001,  0.00,  0.00, 'WATER'\n15,    2.79,    0.006,    -1.111,    0.20,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.07,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.26,    0.028,    -1.044,   0.421,   0.283,   0.036,  1.41E-5,  5.14E-6,   0.028,  0.25,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.55,    0.030,   -10.472,   0.468,   0.454,   0.468,  9.74E-7,  1.12E-5,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    2.79,    0.006,    -0.472,   0.200,    0.17,   0.069,  1.41E-4,  1.36E-4,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    2.79,     0.01,    -0.472,   0.339,   0.192,   0.069,  4.66E-5,  2.65E-5,    0.01,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\nSoil Parameters\nSTAS-RUC\n19,1   'BB      DRYSMC       HC     MAXSMC   REFSMC   SATPSI  SATDK       SATDW     WLTSMC  QTZ    AXAJ   BXAJ   XXAJ  '\n1,     4.05,    0.002,      1.47,   0.395,   0.174,   0.121,  1.76E-4,  0.608E-6,   0.033,  0.92,  0.009,  0.05,  0.05, 'SAND'\n2,     4.38,    0.035,      1.41,   0.410,   0.179,   0.090,  1.56E-4,  0.514E-5,   0.055,  0.82,  0.010,  0.08,  0.08, 'LOAMY SAND'\n3,     4.90,    0.041,      1.34,   0.435,   0.249,   0.218,  3.47E-5,  0.805E-5,   0.095,  0.60,  0.009,  0.09,  0.09, 'SANDY LOAM'\n4,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.25,  0.010,  0.25,  0.25, 'SILT LOAM'\n5,     5.30,    0.034,      1.27,   0.485,   0.369,   0.786,  7.20E-6,  0.239E-4,   0.143,  0.10,  0.012,  0.15,  0.15, 'SILT'\n6,     5.39,    0.050,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.137,  0.40,  0.013,  0.18,  0.18, 'LOAM'\n7,     7.12,    0.068,      1.18,   0.420,   0.299,   0.299,  6.30E-6,  0.990E-5,   0.148,  0.60,  0.014,  0.20,  0.20, 'SANDY CLAY LOAM'\n8,     7.75,    0.060,      1.32,   0.477,   0.357,   0.356,  1.70E-6,  0.237E-4,   0.208,  0.10,  0.015,  0.22,  0.22, 'SILTY CLAY LOAM'\n9,     8.52,    0.085,      1.23,   0.476,   0.391,   0.630,  2.45E-6,  0.113E-4,   0.230,  0.35,  0.016,  0.23,  0.23, 'CLAY LOAM'\n10,   10.40,    0.100,      1.18,   0.426,   0.316,   0.153,  2.17E-6,  0.187E-4,   0.210,  0.52,  0.015,  0.25,  0.25, 'SANDY CLAY'\n11,   10.40,    0.070,      1.15,   0.492,   0.409,   0.490,  1.03E-6,  0.964E-5,   0.250,  0.10,  0.016,  0.28,  0.28, 'SILTY CLAY'\n12,   11.40,    0.068,      1.09,   0.482,   0.400,   0.405,  1.28E-6,  0.112E-4,   0.268,  0.25,  0.017,  0.30,  0.30, 'CLAY'\n13,    5.39,    0.027,      1.21,   0.451,   0.314,   0.478,  6.95E-6,  0.143E-4,   0.117,  0.05,  0.012,  0.26,  0.26, 'ORGANIC MATERIAL'\n14,     0.0,      0.0,      4.18,   1.0,     1.0,     0.0,      0.0,       0.0,     0.0,    0.00,  0.001,  0.00,  0.00, 'WATER'\n15,    4.05,    0.004,      2.03,   0.200,   0.10 ,   0.121,  1.41E-4,  0.136E-3,   0.006,  0.60,  0.017,  1.00,  1.00, 'BEDROCK'\n16,    4.90,    0.065,      2.10,   0.435,   0.249,   0.218,  3.47E-5,  0.514E-5,   0.114,  0.05,  0.017,  1.00,  1.00, 'OTHER(land-ice)'\n17,   11.40,    0.030,      1.41,   0.468,   0.454,   0.468,  9.74E-7,  0.112E-4,   0.030,  0.60,  0.017,  1.00,  1.00, 'PLAYA'\n18,    4.05,    0.006,      1.41,   0.200,   0.17,    0.069,  1.41E-4,  0.136E-3,   0.006,  0.52,  0.015,  0.35,  0.35, 'LAVA'\n19,    4.05,     0.01,      1.47,   0.339,   0.236,   0.069,  1.76E-4,  0.608E-6,   0.060,  0.92,  0.009,  0.15,  0.15, 'WHITE SAND'\n\n"
  },
  {
    "path": "src/template/setEnvar.sh",
    "content": "#!/bin/bash\n\n# WRF-Hydro compile time options\n\n# This is a WRF environment variable. Always set to 1=On for compiling WRF-Hydro.\nexport WRF_HYDRO=1\n\n# Enhanced diagnostic output for debugging: 0=Off, 1=On.\nexport HYDRO_D=0\n\n# Spatially distributed parameters for NoahMP: 0=Off, 1=On.\nexport SPATIAL_SOIL=0\n\n# RAPID model: 0=Off, 1=On.\nexport WRF_HYDRO_RAPID=0\n\n# WCOSS file units: 0=Off, 1=On.\nexport NCEP_WCOSS=0\n\n# NWM output metadata: 0=Off, 1=On.\nexport NWM_META=0\n\n# Streamflow nudging: 0=Off, 1=On.\nexport WRF_HYDRO_NUDGING=0\n"
  },
  {
    "path": "src/utils/CMakeLists.txt",
    "content": "# read version numbers for wrf_hydro_version and nwm_version from\n# ../.version and ../.nwm_version files\n\nfile(STRINGS \"../.version\" WRF_HYDRO_VERSION)\nif(NWM_META AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/../.nwm_version)\n        file (STRINGS \"../.nwm_version\"  NWM_VERSION)\nelse(NWM_META AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/../.nwm_version)\n        set(NWM_VERSION \"undefined\")\nendif()\n\n# add the preprocessor definitions for NWM_VERSION and WRF_HYDRO_VERSION\n# needed to compile module_version.F90\nadd_definitions(-DNWM_VERSION=\"${NWM_VERSION}\")\nadd_definitions(-DWRF_HYDRO_VERSION=\"${WRF_HYDRO_VERSION}\")\n\n# build the version static library\nadd_library(hydro_utils STATIC\n        module_version.F90\n        module_hydro_stop.F90\n)\ntarget_link_libraries(hydro_utils PRIVATE MPI::MPI_Fortran)\n\nadd_subdirectory(fortglob)\n"
  },
  {
    "path": "src/utils/Makefile",
    "content": "# Makefile\n\n.SUFFIXES: .o .F90\n\ninclude ../macros\n\nwh_version := $(shell cat ../.version)\nWRF_HYDRO_VERSION=\\\"$(wh_version)\\\"\n\nnwm_version  := $(shell cat ../.nwm_version)\nNWM_VERSION=\\\"$(nwm_version)\\\"\n\nF90FLAGS += -DNWM_VERSION=$(NWM_VERSION) -DWRF_HYDRO_VERSION=$(WRF_HYDRO_VERSION)\n\nOBJS = \\\n\tmodule_version.o \\\n\tmodule_hydro_stop.o\n\nall:\t$(OBJS)\n\n## The insertion of compile-time constants strangely requires the capital F in the extension.\n.F90.o:\n\t@echo \"Utils Makefile:\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -o $(@) $(F90FLAGS) $(LDFLAGS) $(MODFLAG) -I$(NETCDFINC) $(*).F90\n\t@echo \"\"\n\tar -r ../lib/libHYDRO.a $(@)\n\tcp *.mod ../mod\n\n#\n# Dependencies:\n#\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/utils/fortglob/CMakeLists.txt",
    "content": "add_library(fortglob STATIC\n    libfortglob.c\n    fortglob.F90\n)\n"
  },
  {
    "path": "src/utils/fortglob/Makefile",
    "content": "# Makefile\n\n.PHONY: cp *.F90 *.c\n\ninclude ../../macros\n\nOBJS = \\\n\tfortglob.o \\\n\tlibfortglob.o\n\nall:\t$(OBJS) cp\n\ncp:\n\tcp *.mod ../../mod\n\n%.o: %.F90\n\t@echo \"Utils fortglob Makefile: %.F90\"\n\t$(COMPILER90) $(CPPINVOKE) $(CPPFLAGS) -o $(@) $(F90FLAGS) $(LDFLAGS) -I../../ -I$(NETCDFINC) $(*).F90\n\t@echo \"\"\n\tar -r ../../lib/libHYDRO.a $(@)\n%.o: %.c\n\t@echo \"Utils fortglob Makefile: %.c\"\n\t$(COMPILERCC) -o $(@) -c $(*).c\n\tar -r ../../lib/libHYDRO.a $(@)\n\t@echo \"\"\n#\n# Dependencies:\n#\nfortglob.o: libfortglob.o\n\n\nclean:\n\trm -f *.o *.mod *.stb *~\n"
  },
  {
    "path": "src/utils/fortglob/fortglob.F90",
    "content": "module fortglob\n    use iso_c_binding\n    implicit none\n\n    private\n    public :: glob_t, globfiles\n\n    integer, parameter :: PATH_MAX = 4096\n\n    type :: glob_t\n        integer :: nfiles\n        character(len=PATH_MAX), allocatable :: filenames(:)\n    end type\n\n    type, bind(c) :: globrec_c\n        integer (c_size_t) :: nfiles\n        type(c_ptr) :: filenames\n        type(c_ptr) :: globptr\n    end type globrec_c\n\n    interface\n        function globfiles_c(pattern) bind(c)\n            use iso_c_binding\n            character(kind=c_char), dimension(*), intent(in) :: pattern\n            type(c_ptr) :: globfiles_c\n        end function globfiles_c\n\n        subroutine freeglobrec(recptr) bind (c)\n            use iso_c_binding\n            type(c_ptr), intent(in) :: recptr\n        end subroutine\n\n        function strlen(s) bind(c)\n            use iso_c_binding\n            type(c_ptr), intent(in), value :: s\n            integer(c_size_t) :: strlen\n        end function strlen\n    end interface\n\n    contains\n\n    function globfiles(pattern)\n        use iso_c_binding\n\n        type(glob_t) :: globfiles\n        character(len=*), intent(in) :: pattern\n\n        integer :: i, j, slen\n        character(len=PATH_MAX) :: pattern_c\n        type(c_ptr) :: glob_c_ptr\n        type(globrec_c), pointer :: glob_f_ptr\n        type(c_ptr), pointer :: c_strs(:)\n        character(kind=c_char), pointer, dimension(:) :: temp_fstrp\n\n        pattern_c = pattern\n        slen = len_trim(pattern_c)\n        pattern_c(slen+1:slen+1) = c_null_char\n        glob_c_ptr = globfiles_c(pattern_c)\n        call c_f_pointer(glob_c_ptr, glob_f_ptr)\n        globfiles%nfiles = glob_f_ptr%nfiles\n\n        allocate(globfiles%filenames(globfiles%nfiles))\n\n        call c_f_pointer(glob_f_ptr%filenames, c_strs, [glob_f_ptr%nfiles])\n        do i = 1, globfiles%nfiles\n            slen = strlen(c_strs(i))\n            call c_f_pointer(c_strs(i), temp_fstrp, [slen])\n            globfiles%filenames(i) = ''\n            do j = 1, slen\n                globfiles%filenames(i)(j:j) = temp_fstrp(j)\n            end do\n        end do\n\n        call freeglobrec(glob_f_ptr%globptr)\n    end function\nend module\n"
  },
  {
    "path": "src/utils/fortglob/libfortglob.c",
    "content": "#include \"libfortglob.h\"\n\nglobrec * globfiles_c(const char * pattern) {\n    globrec *record = malloc(sizeof(globrec));\n    glob_t *globbuf = malloc(sizeof(glob_t));\n\n    glob(pattern, 0, NULL, globbuf);\n    record->nfiles = globbuf->gl_pathc;\n    record->filenames = globbuf->gl_pathv;\n    record->__globptr = globbuf;\n\n    return record;\n}\n\nvoid freeglobrec(glob_t ** rec) {\n    glob_t *glob = *rec;\n    globfree(glob);\n    free(glob);\n}\n"
  },
  {
    "path": "src/utils/fortglob/libfortglob.h",
    "content": "#include <glob.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef struct globrec {\n    size_t nfiles;\n    char ** filenames;\n    glob_t * __globptr;\n} globrec;\n\nglobrec * globfiles_c(const char * pattern);\nvoid freeglobrec(glob_t **rec);\n"
  },
  {
    "path": "src/utils/module_hydro_stop.F90",
    "content": "module module_hydro_stop\n\nimplicit none\n\ncontains\n\n! stop the job due to the fatal error.\n      subroutine HYDRO_stop(msg)\n#ifdef MPP_LAND\n        use module_mpp_land\n#endif\n        character(len=*) :: msg\n        integer :: ierr\n        ierr = 1\n#ifndef NCEP_WCOSS\n!#ifdef HYDRO_D  !! PLEASE NEVER UNCOMMENT THIS IFDEF, it's just one incredibly useful string.\n      write(6,'(a)') \"The job has stopped due to a fatal error: \", trim(msg)\n      call flush(6)\n!#endif\n#else\n     write(*,*) \"FATAL ERROR: \", trim(msg)\n     write(78,*) \"FATAL ERROR: \", trim(msg)\n      call flush(78)\n      close(78)\n#endif\n#ifdef MPP_LAND\n#ifndef HYDRO_D\n      print*, \"---\"\n      print*, \"FATAL ERROR! Program stopped. Recompile with environment variable HYDRO_D set to 1 for enhanced debug information.\"\n      print*, \"\"\n#endif\n\n!        call mpp_land_sync()\n!        write(my_id+90,*) msg\n!        call flush(my_id+90)\n\n         call mpp_land_abort()\n         call MPI_Finalize(ierr)\n#else\n         stop \"FATAL ERROR: Program stopped. Recompile with environment variable HYDRO_D set to 1 for enhanced debug information.\"\n#endif\n\n     return\n     end  subroutine HYDRO_stop\n\nend module\n"
  },
  {
    "path": "src/utils/module_version.F90",
    "content": "module module_version\n\nimplicit none\n\ncharacter (len=512), parameter :: wrfHydroVersion=WRF_HYDRO_VERSION\ncharacter (len=512), parameter :: nwmVersion=NWM_VERSION\n\nprivate :: wrfHydroVersion, nwmVersion\npublic  :: get_model_version, get_code_version, get_nwm_version\n\ncontains\n\nfunction get_model_version()\ncharacter (len=512) :: get_model_version\n\n#ifdef NWM_META\n   get_model_version=\"NWM \" // NWM_VERSION\n#else\n   get_model_version=\"WRF-Hydro \" // WRF_HYDRO_VERSION\n#endif\n\nend function get_model_version\n\nfunction get_code_version()\ncharacter (len=512) :: get_code_version\n\nget_code_version=WRF_HYDRO_VERSION\n\nend function get_code_version\n\nfunction get_nwm_version()\ncharacter (len=512) :: get_nwm_version\n\nget_nwm_version=NWM_VERSION\n\nend function get_nwm_version\n\nend module module_version\n"
  },
  {
    "path": "src/wrf_hydro_config",
    "content": "#!/usr/bin/perl\n#input argument: Compiler/System sequential/parallel\n#This is called by WRF configuration only.\nif($#ARGV ne 1) {\n  print(\"Error: No such configuration for Hydro \\n\");\n  exit(1);\n}\n         $x = lc(shift(@ARGV));\n         $paropt = lc(shift(@ARGV));\n\n         print(\"Configure option for Hydro : $x  $paropt \\n\");\n          if($x =~ \"pgi\") {\n              if($paropt eq 'serial') {\n                 # system(\"./configure 1\");\n                 print \"Error : option not defined in WRF-Hyro. \\n\";\n                 exit(1);\n              }\n              else {system(\"./configure 1\"); exit(0);}\n          }\n          if($x =~ \"aix\") {\n              print \"Error : option not defined. \\n\";\n              exit(1);\n              if($paropt eq 'serial') { system(\"./configure 3\");}\n              else {system(\"./configure 4\");}\n          }\n          if($x =~ \"gfortran\") {\n              if($paropt eq 'serial') {\n                 # system(\"./configure 5\");\n                 print \"Error : option not defined in WRF-Hyro. \\n\";\n                 exit(1);\n              }\n              else {system(\"./configure 2\"); exit(0);}\n          }\n          if ($x =~ /(?:ifort|ifx|intel|oneapi)/i) {\n              if($paropt eq 'serial') {\n                   #system(\"./configure 7\");\n                 print \"Error : option not defined. \\n\";\n                 exit(1);\n              }\n              else {system(\"./configure 3\"); exit(0);}\n          }\n                 print \"Error : option not defined. \\n\";\n                 exit(1);\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/FORCING.md5",
    "content": "99a8c6447c0c9c0c5aca99c25e0869f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082600.LDASIN_DOMAIN1\na7ec3fac9bae35e691eb23efd96bd4bf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082601.LDASIN_DOMAIN1\n043d9b6378933dc6f2f11f513bd68a26  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082602.LDASIN_DOMAIN1\n7f08dd26dadca4dd2f49a501de42c584  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082603.LDASIN_DOMAIN1\n3b2dbff098887c10f82d847ba8359e0c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082604.LDASIN_DOMAIN1\n46837e3d47b7e989c2a911568b6d855a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082605.LDASIN_DOMAIN1\n4aca3beef639ac47f98c6c101d0430e3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082606.LDASIN_DOMAIN1\n7bb2d2d8340cf6c7f42127f2f523bc9a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082607.LDASIN_DOMAIN1\n7938a5207b66fbafb63b9a75c6537d03  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082608.LDASIN_DOMAIN1\n48e1e575c43044fd6e53bb0e356c4cbf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082609.LDASIN_DOMAIN1\n606f68fddfe74aa2f7df8ce8939bc430  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082610.LDASIN_DOMAIN1\n4127ef0a592efa219bd316a79e4da3ad  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082611.LDASIN_DOMAIN1\n6ea43af5b6d0e8470bbee99501dc58e2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082612.LDASIN_DOMAIN1\nc4976e2d3c2120eca05d8da0a3aa460f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082613.LDASIN_DOMAIN1\ne25a7fb95772bf88f34a537e357446a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082614.LDASIN_DOMAIN1\n03ac9b352d76885d6ac637697ee6b0d3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082615.LDASIN_DOMAIN1\n88b5a8477ec8bed99aee62f22614cc6d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082616.LDASIN_DOMAIN1\nf2c4b95dc217248eec44a1cbdfa4ffb4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082617.LDASIN_DOMAIN1\n2798daf701dbfedb2a64e5d342954665  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082618.LDASIN_DOMAIN1\n622e919b18db2d37fcf3c680d61c89ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082619.LDASIN_DOMAIN1\n897a6450d5f251e0e0487ff5f1f02884  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082620.LDASIN_DOMAIN1\n05722c6dcaf58fdbe88dddcf08d4a5c6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082621.LDASIN_DOMAIN1\n5a067a738ed9ff63c47ea204ab30a301  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082622.LDASIN_DOMAIN1\na3c3c5f5d89595e1107335a91c476330  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082623.LDASIN_DOMAIN1\nf9aa2a3dfbcbe06d720fb1ba3a19c758  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082700.LDASIN_DOMAIN1\ndc7b647dac35f1dc8ce28a9f898f4c8b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082701.LDASIN_DOMAIN1\nf5cf666e8db8bbbcfb05c0ca18c4796f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082702.LDASIN_DOMAIN1\n5ef840b37eace005da387e43767efc65  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082703.LDASIN_DOMAIN1\nac9d2186d75f7278d059a555ec58e481  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082704.LDASIN_DOMAIN1\nc2887fdaa503ff9718af2c38b18b9424  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082705.LDASIN_DOMAIN1\n6fffb7cdc5ab018c639f73d97e1463a1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082706.LDASIN_DOMAIN1\nb26e322e7c8e9b3f9c5cc9dfeb489fbd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082707.LDASIN_DOMAIN1\nb2f898ce5e4ede92262dca2ad38fdec2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082708.LDASIN_DOMAIN1\nf5f470bbfd206ef66aecdca695476b5e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082709.LDASIN_DOMAIN1\n0de09110d753d0e229c2557b58429ada  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082710.LDASIN_DOMAIN1\n2699c31125965d8be001812687821e9f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082711.LDASIN_DOMAIN1\n85d44fee9f432097660b63f89c60dbe7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082712.LDASIN_DOMAIN1\n7379a35eb28a5738081ab7419256b5fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082713.LDASIN_DOMAIN1\n4b6e09dd13686c5dfa10d786a5719060  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082714.LDASIN_DOMAIN1\n961c54de44ae4b59338814690517b477  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082715.LDASIN_DOMAIN1\nb395fa2fe5ebc53def279c1956cec3b8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082716.LDASIN_DOMAIN1\nd3cfde720203407c9abcc5f4cbfe3cf4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082717.LDASIN_DOMAIN1\n17cadbd78e6f37d016da7dfa77237ca7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082718.LDASIN_DOMAIN1\nac1d343818b41d43df11473b39e74acd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082719.LDASIN_DOMAIN1\nf795066b8432a404ff6600e1885e2587  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082720.LDASIN_DOMAIN1\n49a2865148c137414274949b122f7bbd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082721.LDASIN_DOMAIN1\neca4d48ad1911e014e9ee87e1e176a4a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082722.LDASIN_DOMAIN1\n6b6b54677644ee45ff7cb84026697ab2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082723.LDASIN_DOMAIN1\n94f04773a72f9324118b6402a5c7983f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082800.LDASIN_DOMAIN1\n20716745758534f5188733f4114a62c9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082801.LDASIN_DOMAIN1\nfb8404b70989297dde2c46828d9119a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082802.LDASIN_DOMAIN1\ne8a188e0355a4795a8663216f4afe2fb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082803.LDASIN_DOMAIN1\nde05c2b564ddc3e856fb53fea176a35b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082804.LDASIN_DOMAIN1\n4a12407d24391d8aa7fe3dc64f99afa5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082805.LDASIN_DOMAIN1\n3c2e87cfdb74551303ebe1c9aad01f7f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082806.LDASIN_DOMAIN1\na47772511a16ea0db767f6ecde797231  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082807.LDASIN_DOMAIN1\n7ccb5dad179b396874ac95b3065edb7f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082808.LDASIN_DOMAIN1\n99e743da1a400fd05fec9f70bcff165f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082809.LDASIN_DOMAIN1\n47383fb5aa70a79dfe3dad94fb710491  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082810.LDASIN_DOMAIN1\n464fdc143d790bbb3cd6bef62eb17a2f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082811.LDASIN_DOMAIN1\n01386a8dfe531d65d0678dda20a17cd6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082812.LDASIN_DOMAIN1\n5989e779a5b1d6a3d37cf447cedbe3f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082813.LDASIN_DOMAIN1\n86b6cb4c6e0cb7d9cd48ce56f7a75b24  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082814.LDASIN_DOMAIN1\n1efb80167e46e2d5da26363be87f0c33  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082815.LDASIN_DOMAIN1\neaed7529c11dca13c255de20e9b8fcab  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082816.LDASIN_DOMAIN1\n7a8f616cedf0a030068d3e812306bab2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082817.LDASIN_DOMAIN1\n5ab75846498cc9f9b04a1dd0650999c4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082818.LDASIN_DOMAIN1\n2b7b57458510b978cb912efedfbef3a4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082819.LDASIN_DOMAIN1\n119b11361c4c7007ab48e799a8f33466  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082820.LDASIN_DOMAIN1\n309f87c9aa163bc81de198cf366391da  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082821.LDASIN_DOMAIN1\naedc76c3fe739ef8c0a679af64d66373  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082822.LDASIN_DOMAIN1\n2099bc847c251bfaab889501eef79d4b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082823.LDASIN_DOMAIN1\nc73a1623c8c1e709e7be917e6b4139be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082900.LDASIN_DOMAIN1\nb03f08302dcd464eb6450e744354e52d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082901.LDASIN_DOMAIN1\n67dd130308c1b727c3ae64c919620ff7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082902.LDASIN_DOMAIN1\na60b00233f1a0b1890242d154d8ecebf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082903.LDASIN_DOMAIN1\nd6b800167cf67cc3b4968187f7de5db7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082904.LDASIN_DOMAIN1\n71c550bf0fcaeb793f84c20f74b7369d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082905.LDASIN_DOMAIN1\n151ee5cca8893672b437c3be8e235ffc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082906.LDASIN_DOMAIN1\n9b8ee27c04db34ebe251d3ab83c82c34  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082907.LDASIN_DOMAIN1\n85ea64ad2b1cf018a7369dfd004af04f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082908.LDASIN_DOMAIN1\n27f010063f59ca876eb814768b7acac7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082909.LDASIN_DOMAIN1\n3ba072f831a565c8bd26888e21c5ea69  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082910.LDASIN_DOMAIN1\ndbfee7d238399151d96d5f17ae5969e7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082911.LDASIN_DOMAIN1\n3a6f8d26d4f0616657d0117360ba6511  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082912.LDASIN_DOMAIN1\n31ed9be02de650dc4b32c5e775663a76  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082913.LDASIN_DOMAIN1\n07269089bb3bc34ea00466f010be9adb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082914.LDASIN_DOMAIN1\n7e5e28c49c7b5dc3604ff9da66084183  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082915.LDASIN_DOMAIN1\n93abe024b7b83f316faf5ffcc086da0f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082916.LDASIN_DOMAIN1\na7e2bcb0d3d44ed95f797d8e34fcda8e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082917.LDASIN_DOMAIN1\n73f1af91b039e2705cca0697234ca0fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082918.LDASIN_DOMAIN1\n5cc5b1a8aa04b7cace1a3a7c929fc9a8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082919.LDASIN_DOMAIN1\n3bccc6f3fb189411e21ae777b5255a67  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082920.LDASIN_DOMAIN1\nc2e2ded8c7b6ea99cb37565ee8cff1f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082921.LDASIN_DOMAIN1\n1473ec957fb67b7d8b04ea0f016af43c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082922.LDASIN_DOMAIN1\n7463caf0cf0d1e1eb83310a42360a765  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082923.LDASIN_DOMAIN1\nf90e0e05e760f2538c0b16f2317331b8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083000.LDASIN_DOMAIN1\n89c59488d5cab796493a66cd9e3e05ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083001.LDASIN_DOMAIN1\nbbc2e47966d8d0ce4240c0f21397d855  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083002.LDASIN_DOMAIN1\n5c9abf203fde3055e4670293323bb771  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083003.LDASIN_DOMAIN1\n423c5c3dd3fe1bd5cf3e9f5f727daf5d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083004.LDASIN_DOMAIN1\n133779e3625c5ccf6f8929d311fe8286  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083005.LDASIN_DOMAIN1\n7550cdfe6c3f023e0d319af8fe8d73bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083006.LDASIN_DOMAIN1\na7b95345bf58f6a2ed79d3523193cbdc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083007.LDASIN_DOMAIN1\nab07ec42371b4cc65e44f07c42793b78  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083008.LDASIN_DOMAIN1\na4a68ec39f741ae21d701044655f3fd9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083009.LDASIN_DOMAIN1\n5e8400fea1eacdb34a3c4a9e8ea68cbf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083010.LDASIN_DOMAIN1\nfd98b0933141b6e2cadaf6f83a2443c2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083011.LDASIN_DOMAIN1\n41afaf8a9a1a1f24dacb2b499f6961e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083012.LDASIN_DOMAIN1\nbbacb5590e69b1f2a826226bd5b02bf5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083013.LDASIN_DOMAIN1\nb9a42831c5fa1bf47fa7adee39b8ba2f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083014.LDASIN_DOMAIN1\nbd00d627d1994685eddc6584291c5703  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083015.LDASIN_DOMAIN1\n259b202e92f7b23ef15cdc23adf88afc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083016.LDASIN_DOMAIN1\n6280eb7d46da3b799253f47fa82414ec  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083017.LDASIN_DOMAIN1\n0959d9cdab1389b8fdcd325468ee40ec  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083018.LDASIN_DOMAIN1\n0aee383f608f148beee21090efc074c3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083019.LDASIN_DOMAIN1\n2559bbedd3800b1aa3a731fd7c4f1df6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083020.LDASIN_DOMAIN1\n746cf2ffa493910233bb66a04ce7df15  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083021.LDASIN_DOMAIN1\n39445dcd3fd5b4742d2dc5f3e456918b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083022.LDASIN_DOMAIN1\nba3d5da1401b3fb5b3f1f890146eae87  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083023.LDASIN_DOMAIN1\n332a5779ac01b77d18d13d45b16d731b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083100.LDASIN_DOMAIN1\n25a1e5a8fa6b165524f1eb38b61e02bb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083101.LDASIN_DOMAIN1\n7fa830e049c4154459f4971ad482600b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083102.LDASIN_DOMAIN1\n46b8014756b56ec665939bda573833cf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083103.LDASIN_DOMAIN1\n18f066ad10fb2a347102894e66be2d24  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083104.LDASIN_DOMAIN1\n12d3c11cc42fa27093f69db07f9ee765  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083105.LDASIN_DOMAIN1\na7a576e92e97a1db69db1c9503bc9888  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083106.LDASIN_DOMAIN1\naed0c94040b49626f3e6acd39f240d3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083107.LDASIN_DOMAIN1\n2c7fe4946d31922bea5bc3c24038e7b5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083108.LDASIN_DOMAIN1\n1de8c651e88fc6278e6e9258c277bac2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083109.LDASIN_DOMAIN1\n1cf16b50fd969e841be639acfbf04b20  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083110.LDASIN_DOMAIN1\n812e4c48b61d1153eaa504da5fab3c71  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083111.LDASIN_DOMAIN1\ne59a66da1d66d601878f875cf212ba94  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083112.LDASIN_DOMAIN1\n2d2d1f5a1526e96d8256fe234998f4fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083113.LDASIN_DOMAIN1\n68fbfe5963b5965d41f1abe363e2be85  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083114.LDASIN_DOMAIN1\nca28008a027712705e59320485073841  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083115.LDASIN_DOMAIN1\n15fb7890db613b322da8e66683a2436b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083116.LDASIN_DOMAIN1\n040366f4ea7c526433329121b7df3e89  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083117.LDASIN_DOMAIN1\na87ff7d51395e7c37a2176939d7421fb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083118.LDASIN_DOMAIN1\nb187c03674b7686bf861ef2e1a5405b7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083119.LDASIN_DOMAIN1\nc6926510ed58d35d2a2084e395a8bbb5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083120.LDASIN_DOMAIN1\n45e3faffa14ccda0d61304cf35712c44  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083121.LDASIN_DOMAIN1\n34d8a05a86bdfb8b1fbd86da002092f8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083122.LDASIN_DOMAIN1\nc237cde05fcb5d61c982d998629eb494  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083123.LDASIN_DOMAIN1\n6dc72b6fcebd47539729a2b003737f72  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090100.LDASIN_DOMAIN1\n0bd92afef70ccfea284d2064accbcf1c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090101.LDASIN_DOMAIN1\n05ca6e1997168a9081dcd15a7b41363e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090102.LDASIN_DOMAIN1\n1b69eed07ce7100877e73cab1a8e4e42  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090103.LDASIN_DOMAIN1\n11d997337a248d08e97353478cf154bc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090104.LDASIN_DOMAIN1\n82ee6915fb07555ea1911b6759c8202a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090105.LDASIN_DOMAIN1\n4bcbe23aed193b9ea716f4e2af27ede9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090106.LDASIN_DOMAIN1\n09237d4bf1b81113e78a64adda67f847  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090107.LDASIN_DOMAIN1\n515f9ae88b19b5dc6ce48e84d4931380  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090108.LDASIN_DOMAIN1\n26cec642877dbc76dbfa01800de238fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090109.LDASIN_DOMAIN1\ne10a842db6a1aaceb137e67efe203273  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090110.LDASIN_DOMAIN1\n08d74b96b90de56bc9a003a7ff997869  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090111.LDASIN_DOMAIN1\n80f12471d9e00e678897dd97e9eb4be4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090112.LDASIN_DOMAIN1\n31d95f778a1a39d7a94b7eb31595c3ee  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090113.LDASIN_DOMAIN1\ne4e0c7187d0c0e5754db762d28570cdb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090114.LDASIN_DOMAIN1\n13cf130153e67d94272d7badc9255d01  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090115.LDASIN_DOMAIN1\na1fb54acd3c91479ee9d954a5eb551d1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090116.LDASIN_DOMAIN1\n14f26d1d23ade8ce3f2840f5a107801b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090117.LDASIN_DOMAIN1\n53fb1aabf5ca50de1b09c4490b4ef0b5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090118.LDASIN_DOMAIN1\ndbacbd2f2dc7f90be5366f1a768f4579  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090119.LDASIN_DOMAIN1\n4a19798b8ee1392bf2652f50e2d90fa5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090120.LDASIN_DOMAIN1\n174ae0c519523c34f1ce1f3626c111c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090121.LDASIN_DOMAIN1\n45d480bdf81e9475ba1a987bad8e8404  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090122.LDASIN_DOMAIN1\nec8da8744cbcbef271e585fbf93195b9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090123.LDASIN_DOMAIN1\nc9caf170259cd0cf4a347bd36ede9d4d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090200.LDASIN_DOMAIN1\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/Fulldom_hires.cdl",
    "content": "netcdf Fulldom_hires {\ndimensions:\n\ty = 64 ;\n\tx = 60 ;\nvariables:\n\tshort CHANNELGRID(y, x) ;\n\t\tCHANNELGRID:grid_mapping = \"crs\" ;\n\t\tCHANNELGRID:coordinates = \"x y\" ;\n\t\tCHANNELGRID:long_name = \"CHANNELGRID\" ;\n\t\tCHANNELGRID:units = \"Meter\" ;\n\t\tCHANNELGRID:missing_value = -32768s ;\n\t\tCHANNELGRID:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tshort FLOWDIRECTION(y, x) ;\n\t\tFLOWDIRECTION:grid_mapping = \"crs\" ;\n\t\tFLOWDIRECTION:coordinates = \"x y\" ;\n\t\tFLOWDIRECTION:long_name = \"FLOWDIRECTION\" ;\n\t\tFLOWDIRECTION:units = \"Meter\" ;\n\t\tFLOWDIRECTION:missing_value = 0s ;\n\t\tFLOWDIRECTION:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tshort LAKEGRID(y, x) ;\n\t\tLAKEGRID:grid_mapping = \"crs\" ;\n\t\tLAKEGRID:coordinates = \"x y\" ;\n\t\tLAKEGRID:long_name = \"LAKEGRID\" ;\n\t\tLAKEGRID:units = \"Meter\" ;\n\t\tLAKEGRID:missing_value = -32768s ;\n\t\tLAKEGRID:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat LATITUDE(y, x) ;\n\t\tLATITUDE:grid_mapping = \"crs\" ;\n\t\tLATITUDE:_CoordinateSystems = \"crs\" ;\n\t\tLATITUDE:long_name = \"latitude coordinate\" ;\n\t\tLATITUDE:units = \"degrees_north\" ;\n\t\tLATITUDE:_CoordinateAxisType = \"Lat\" ;\n\t\tLATITUDE:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tdouble LKSATFAC(y, x) ;\n\t\tLKSATFAC:grid_mapping = \"crs\" ;\n\t\tLKSATFAC:coordinates = \"x y\" ;\n\t\tLKSATFAC:long_name = \"RETDEPRTFAC\" ;\n\t\tLKSATFAC:units = \"Meter\" ;\n\t\tLKSATFAC:missing_value = -3.402823e+38f ;\n\t\tLKSATFAC:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat LONGITUDE(y, x) ;\n\t\tLONGITUDE:grid_mapping = \"crs\" ;\n\t\tLONGITUDE:_CoordinateSystems = \"crs\" ;\n\t\tLONGITUDE:long_name = \"longitude coordinate\" ;\n\t\tLONGITUDE:units = \"degrees_east\" ;\n\t\tLONGITUDE:_CoordinateAxisType = \"Lon\" ;\n\t\tLONGITUDE:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat OVROUGHRTFAC(y, x) ;\n\t\tOVROUGHRTFAC:grid_mapping = \"crs\" ;\n\t\tOVROUGHRTFAC:coordinates = \"x y\" ;\n\t\tOVROUGHRTFAC:long_name = \"OVROUGHRTFAC\" ;\n\t\tOVROUGHRTFAC:units = \"Meter\" ;\n\t\tOVROUGHRTFAC:missing_value = -3.402823e+38f ;\n\t\tOVROUGHRTFAC:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tdouble RETDEPRTFAC(y, x) ;\n\t\tRETDEPRTFAC:grid_mapping = \"crs\" ;\n\t\tRETDEPRTFAC:coordinates = \"x y\" ;\n\t\tRETDEPRTFAC:long_name = \"RETDEPRTFAC\" ;\n\t\tRETDEPRTFAC:units = \"Meter\" ;\n\t\tRETDEPRTFAC:missing_value = -3.402823e+38f ;\n\t\tRETDEPRTFAC:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tshort STREAMORDER(y, x) ;\n\t\tSTREAMORDER:grid_mapping = \"crs\" ;\n\t\tSTREAMORDER:coordinates = \"x y\" ;\n\t\tSTREAMORDER:long_name = \"STREAMORDER\" ;\n\t\tSTREAMORDER:units = \"Meter\" ;\n\t\tSTREAMORDER:missing_value = -32768s ;\n\t\tSTREAMORDER:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat TOPOGRAPHY(y, x) ;\n\t\tTOPOGRAPHY:_FillValue = -9999.f ;\n\t\tTOPOGRAPHY:grid_mapping = \"crs\" ;\n\t\tTOPOGRAPHY:coordinates = \"x y\" ;\n\t\tTOPOGRAPHY:long_name = \"TOPOGRAPHY\" ;\n\t\tTOPOGRAPHY:units = \"Meter\" ;\n\t\tTOPOGRAPHY:missing_value = -3.402823e+38f ;\n\t\tTOPOGRAPHY:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tshort basn_msk(y, x) ;\n\t\tbasn_msk:grid_mapping = \"crs\" ;\n\t\tbasn_msk:coordinates = \"x y\" ;\n\t\tbasn_msk:long_name = \"basn_msk\" ;\n\t\tbasn_msk:units = \"Meter\" ;\n\t\tbasn_msk:missing_value = -32768s ;\n\t\tbasn_msk:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tchar crs ;\n\t\tcrs:transform_name = \"lambert_conformal_conic\" ;\n\t\tcrs:grid_mapping_name = \"lambert_conformal_conic\" ;\n\t\tcrs:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:spatial_ref = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:long_name = \"CRS definition\" ;\n\t\tcrs:longitude_of_prime_meridian = 0. ;\n\t\tcrs:GeoTransform = \"-2303999.17655 250.0 0 1919999.66329 0 -250.0 \" ;\n\t\tcrs:_CoordinateAxes = \"y x\" ;\n\t\tcrs:_CoordinateTransformType = \"Projection\" ;\n\t\tcrs:standard_parallel = 30., 60. ;\n\t\tcrs:longitude_of_central_meridian = -97. ;\n\t\tcrs:latitude_of_projection_origin = 40. ;\n\t\tcrs:false_easting = 0. ;\n\t\tcrs:false_northing = 0. ;\n\t\tcrs:earth_radius = 6370000. ;\n\t\tcrs:semi_major_axis = 6370000. ;\n\t\tcrs:inverse_flattening = 0. ;\n\tshort frxst_pts(y, x) ;\n\t\tfrxst_pts:grid_mapping = \"crs\" ;\n\t\tfrxst_pts:coordinates = \"x y\" ;\n\t\tfrxst_pts:long_name = \"frxst_pts\" ;\n\t\tfrxst_pts:units = \"Meter\" ;\n\t\tfrxst_pts:missing_value = -32768s ;\n\t\tfrxst_pts:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat landuse(y, x) ;\n\t\tlanduse:grid_mapping = \"crs\" ;\n\t\tlanduse:coordinates = \"x y\" ;\n\t\tlanduse:long_name = \"landuse\" ;\n\t\tlanduse:units = \"Meter\" ;\n\t\tlanduse:missing_value = -3.402823e+38f ;\n\t\tlanduse:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tdouble x(x) ;\n\t\tx:standard_name = \"projection_x_coordinate\" ;\n\t\tx:long_name = \"x coordinate of projection\" ;\n\t\tx:units = \"m\" ;\n\t\tx:_CoordinateAxisType = \"GeoX\" ;\n\t\tx:resolution = 250. ;\n\tdouble y(y) ;\n\t\ty:standard_name = \"projection_y_coordinate\" ;\n\t\ty:long_name = \"y coordinate of projection\" ;\n\t\ty:units = \"m\" ;\n\t\ty:_CoordinateAxisType = \"GeoY\" ;\n\t\ty:resolution = 250. ;\n\n// global attributes:\n\t\t:Conventions = \"CF-1.5\" ;\n\t\t:Source_Software = \"WRF-Hydro GIS Pre-processor v5 (03/2018)\" ;\n\t\t:history = \"Fri Aug 24 11:13:55 2018: ncks -O -d x,16584,16643 -d y,5932,5995 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/Fulldom_hires_netcdf_file_250m_FullRouting_NWMv2.0.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/Fulldom_hires.nc\\n\",\n\t\t\t\"Tue Jan 16 08:46:51 2018: ncap2 -O -s RETDEPRTFAC=RETDEPRTFAC*0.0+1.0 Fulldom_hires_netcdf_file_250m_NWMv1.2_DEFAULT.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Tue Jan 16 08:44:50 2018: ncap2 -s LKSATFAC=LKSATFAC*0.0+1000.0 Fulldom_hires_netcdf_file_250m_NWMv1.2_calib2_ADJFL.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Mon Mar 27 18:43:54 2017: ncap2 -O -s RETDEPRTFAC=1.0 Fulldom_hires_netcdf_file_250m_NWMv1.2_calib1.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_calib1.nc\\n\",\n\t\t\t\"Mon Mar 27 18:43:17 2017: ncap2 -O -s LKSATFAC=1000.0 Fulldom_hires_netcdf_file_250m_NWMv1.2_calib1.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_calib1.nc\\n\",\n\t\t\t\"Thu Mar 23 21:23:47 2017: ncks -A -v STREAMORDER KS_FILES/Harmonized_DEM_2/STREAMORDER.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc\\n\",\n\t\t\t\"Thu Mar 23 21:21:09 2017: ncks -A -v FLOWDIRECTION KS_FILES/Harmonized_DEM_2/FLOWDIRECTION.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc\\n\",\n\t\t\t\"Thu Mar 23 21:18:41 2017: ncks -A -v CHANNELGRID KS_FILES/Harmonized_DEM_2/CHANNELGRID.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc\\n\",\n\t\t\t\"Thu Mar 23 21:18:10 2017: ncks -A -v TOPOGRAPHY KS_FILES/Harmonized_DEM_2/TOPOGRAPHY.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc\\n\",\n\t\t\t\"Thu Mar 23 21:17:09 2017: ncks -O -x -v STREAMORDER Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc\\n\",\n\t\t\t\"Thu Mar 23 21:16:48 2017: ncks -O -x -v FLOWDIRECTION Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc\\n\",\n\t\t\t\"Thu Mar 23 21:15:50 2017: ncks -O -x -v CHANNELGRID Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc\\n\",\n\t\t\t\"Thu Mar 23 21:15:28 2017: ncks -O -x -v TOPOGRAPHY Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc Fulldom_hires_netcdf_file_250m_NWMv1.2_harmdem.nc\\n\",\n\t\t\t\"Tue Feb 14 17:12:51 2017: ncks -A -v TOPOGRAPHY TOPOGRAPHY.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_harmdem.nc\\n\",\n\t\t\t\"Tue Feb 14 17:08:11 2017: ncks -A -v STREAMORDER STREAMORDER.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_harmdem.nc\\n\",\n\t\t\t\"Tue Feb 14 17:07:24 2017: ncks -A -v FLOWDIRECTION FLOWDIRECTION.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_harmdem.nc\\n\",\n\t\t\t\"Tue Feb 14 17:06:59 2017: ncks -A -v CHANNELGRID CHANNELGRID.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_harmdem.nc\\n\",\n\t\t\t\"Tue Feb 14 17:06:10 2017: ncks -O -x -v CHANNELGRID,FLOWDIRECTION,STREAMORDER,TOPOGRAPHY Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_harmdem.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_harmdem.nc\\n\",\n\t\t\t\"Sun Nov  6 02:30:26 2016: ncks -A -v TOPOGRAPHY Fulldom_hires_netcdf_file_250m_NWMv1.1_calib1_newdem.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_newdem.nc\\n\",\n\t\t\t\"Sun Nov  6 02:28:58 2016: ncks -x -v TOPOGRAPHY Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_newdem.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib2_newdem.nc\\n\",\n\t\t\t\"Thu Sep 29 20:11:22 2016: ncap2 -O -s LKSATFAC=RETDEPRTFAC*0.0+1000.0 Fulldom_hires_netcdf_file_250m_CALIB3_lksatfac.nc Fulldom_hires_netcdf_file_250m_CALIB3_lksatfac.nc\\n\",\n\t\t\t\"Tue Oct 21 19:40:08 2014: ncks -4 -A landuse.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:40:00 2014: ncks -4 -A longitude.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:51 2014: ncks -4 -A latitude.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:44 2014: ncks -4 -A frxst_pts.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:38 2014: ncks -4 -A LAKEGRID.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:31 2014: ncks -4 -A ovroughrtfac.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:25 2014: ncks -4 -A retdeprtfac.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:21 2014: ncks -4 -A gw_basns.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:17 2014: ncks -4 -A str_order.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:13 2014: ncks -4 -A CHANNELGRID.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:10 2014: ncks -4 -A flowdirection.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:06 2014: ncks -4 topography.nc Fulldom_hires_netcdf_file.nc\" ;\n\t\t:history_of_appended_files = \"Thu Mar 23 21:23:47 2017: Appended file KS_FILES/Harmonized_DEM_2/STREAMORDER.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Created Wed Mar 22 19:25:27 2017\\n\",\n\t\t\t\"Thu Mar 23 21:21:09 2017: Appended file KS_FILES/Harmonized_DEM_2/FLOWDIRECTION.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Created Wed Mar 22 19:23:54 2017\\n\",\n\t\t\t\"Thu Mar 23 21:18:41 2017: Appended file KS_FILES/Harmonized_DEM_2/CHANNELGRID.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Created Wed Mar 22 19:45:02 2017\\n\",\n\t\t\t\"Thu Mar 23 21:18:10 2017: Appended file KS_FILES/Harmonized_DEM_2/TOPOGRAPHY.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Created Wed Mar 22 19:27:32 2017\\n\",\n\t\t\t\"Tue Feb 14 17:12:51 2017: Appended file TOPOGRAPHY.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Created Mon Feb 13 17:06:18 2017\\n\",\n\t\t\t\"Tue Feb 14 17:08:11 2017: Appended file STREAMORDER.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Created Tue Feb 14 12:12:22 2017\\n\",\n\t\t\t\"Tue Feb 14 17:07:24 2017: Appended file FLOWDIRECTION.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Created Tue Feb 14 12:40:41 2017\\n\",\n\t\t\t\"Tue Feb 14 17:06:59 2017: Appended file CHANNELGRID.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Created Tue Feb 14 08:49:21 2017\\n\",\n\t\t\t\"Sun Nov  6 02:30:26 2016: Appended file Fulldom_hires_netcdf_file_250m_NWMv1.1_calib1_newdem.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Wed Nov  2 18:10:08 2016: ncrename -v Band1,TOPOGRAPHY Fulldom_hires_netcdf_file_250m_NWMv1.1_calib1_newdem.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib1_newdem.nc\\n\",\n\t\t\t\"Wed Nov  2 18:08:49 2016: ncks -x -v TOPOGRAPHY Fulldom_hires_netcdf_file_250m_NWMv1.1_calib1.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib1_newdem.nc\\n\",\n\t\t\t\"Wed Nov  2 18:06:38 2016: ncks -A -v Band1 dem250_nodata_land_comb_0fill_dem250_arcfill1000_revy.nc Fulldom_hires_netcdf_file_250m_NWMv1.1_calib1.nc\\n\",\n\t\t\t\"Thu Sep 29 20:11:22 2016: ncap2 -O -s LKSATFAC=RETDEPRTFAC*0.0+1000.0 Fulldom_hires_netcdf_file_250m_CALIB3_lksatfac.nc Fulldom_hires_netcdf_file_250m_CALIB3_lksatfac.nc\\n\",\n\t\t\t\"Tue Oct 21 19:40:08 2014: ncks -4 -A landuse.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:40:00 2014: ncks -4 -A longitude.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:51 2014: ncks -4 -A latitude.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:44 2014: ncks -4 -A frxst_pts.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:38 2014: ncks -4 -A LAKEGRID.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:31 2014: ncks -4 -A ovroughrtfac.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:25 2014: ncks -4 -A retdeprtfac.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:21 2014: ncks -4 -A gw_basns.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:17 2014: ncks -4 -A str_order.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:13 2014: ncks -4 -A CHANNELGRID.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:10 2014: ncks -4 -A flowdirection.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Tue Oct 21 19:39:06 2014: ncks -4 topography.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"\" ;\n\t\t:proj4 = \"+proj=lcc +units=m +a=6370000.0 +b=6370000.0 +lat_1=30.0 +lat_2=60.0 +lat_0=40.0 +lon_0=-97.0 +x_0=0 +y_0=0 +k_0=1.0 +nadgrids=@null +wktext  +no_defs \" ;\n\t\t:processing_notes = \"Created: Thu Aug 02 09:31:47 2018\" ;\n\t\t:GDAL_DataType = \"Generic\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/Fulldom_hires.md5",
    "content": "6258947705219cfade2c7be7f014e5eb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/Fulldom_hires.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata.cdl",
    "content": "netcdf GEOGRID_LDASOUT_Spatial_Metadata {\ndimensions:\n\tx = 15 ;\n\ty = 16 ;\nvariables:\n\tchar crs ;\n\t\tcrs:transform_name = \"lambert_conformal_conic\" ;\n\t\tcrs:grid_mapping_name = \"lambert_conformal_conic\" ;\n\t\tcrs:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:spatial_ref = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:long_name = \"CRS definition\" ;\n\t\tcrs:longitude_of_prime_meridian = 0. ;\n\t\tcrs:GeoTransform = \"-2303999.17655 1000.0 0 1919999.66329 0 -1000.0 \" ;\n\t\tcrs:_CoordinateAxes = \"y x\" ;\n\t\tcrs:_CoordinateTransformType = \"Projection\" ;\n\t\tcrs:standard_parallel = 30., 60. ;\n\t\tcrs:longitude_of_central_meridian = -97. ;\n\t\tcrs:latitude_of_projection_origin = 40. ;\n\t\tcrs:false_easting = 0. ;\n\t\tcrs:false_northing = 0. ;\n\t\tcrs:earth_radius = 6370000. ;\n\t\tcrs:semi_major_axis = 6370000. ;\n\t\tcrs:inverse_flattening = 0. ;\n\tdouble x(x) ;\n\t\tx:standard_name = \"projection_x_coordinate\" ;\n\t\tx:long_name = \"x coordinate of projection\" ;\n\t\tx:units = \"m\" ;\n\t\tx:_CoordinateAxisType = \"GeoX\" ;\n\t\tx:resolution = 1000. ;\n\tdouble y(y) ;\n\t\ty:standard_name = \"projection_y_coordinate\" ;\n\t\ty:long_name = \"y coordinate of projection\" ;\n\t\ty:units = \"m\" ;\n\t\ty:_CoordinateAxisType = \"GeoY\" ;\n\t\ty:resolution = 1000. ;\n\n// global attributes:\n\t\t:Conventions = \"CF-1.5\" ;\n\t\t:GDAL_DataType = \"Generic\" ;\n\t\t:Source_Software = \"WRF-Hydro GIS Pre-processor v5 (03/2018)\" ;\n\t\t:proj4 = \"+proj=lcc +units=m +a=6370000.0 +b=6370000.0 +lat_1=30.0 +lat_2=60.0 +lat_0=40.0 +lon_0=-97.0 +x_0=0 +y_0=0 +k_0=1.0 +nadgrids=@null +wktext  +no_defs \" ;\n\t\t:history = \"Thu May 23 15:29:28 2019: ncks -O -d x,4146,4160 -d y,1483,1498 /glade/p/cisl/nwc/nwmv20_finals/CONUS/DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_1km_NWMv2.0.nc /glade/scratch/arezoo/rfc_cutout_basins/Cutout_Basins/Full_Physics//0137462010/GEOGRID_LDASOUT_Spatial_Metadata.nc\\n\",\n\t\t\t\"Created Thu Aug 02 19:39:09 2018\" ;\n\t\t:processing_notes = \"Created: Thu Aug 02 19:38:45 2018\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata.md5",
    "content": "fc264e56007475d0780b1f631985d166  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/GWBUCKPARM.cdl",
    "content": "netcdf GWBUCKPARM {\ndimensions:\n\tBasinDim = 183 ;\nvariables:\n\tfloat Area_sqkm(BasinDim) ;\n\t\tArea_sqkm:long_name = \"Basin area in square kilometers\" ;\n\tint Basin(BasinDim) ;\n\t\tBasin:long_name = \"Basin monotonic ID (1...n)\" ;\n\tfloat Coeff(BasinDim) ;\n\t\tCoeff:long_name = \"Coefficient\" ;\n\tint ComID(BasinDim) ;\n\t\tComID:long_name = \"NHDCatchment FEATUREID (NHDFlowline ComID)\" ;\n\tdouble Expon(BasinDim) ;\n\t\tExpon:long_name = \"Exponent\" ;\n\tfloat Zinit(BasinDim) ;\n\t\tZinit:long_name = \"Zinit\" ;\n\tdouble Zmax(BasinDim) ;\n\t\tZmax:long_name = \"Zmax\" ;\n\n// global attributes:\n\t\t:featureType = \"point\" ;\n\t\t:history = \"Fri Aug 24 11:14:53 2018: ncks -O -d BasinDim,1,183 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/GWBUCKPARM.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/GWBUCKPARM.nc\\n\",\n\t\t\t\"Fri Mar  2 09:34:12 2018: ncap2 -O -s Expon=Expon*0.0+3.0 GWBUCKPARM_NWMv1.2_DEFAULT.nc GWBUCKPARM_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Fri Mar  2 09:33:34 2018: ncap2 -O -s Zmax=Zmax*0.0+50.0 GWBUCKPARM_NWMv1.2_DEFAULT.nc GWBUCKPARM_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Tue Jan 16 09:10:53 2018: ncap2 -s Zmax=Zmax*0.0+50.0 GWBUCKPARM_NWMv1.2_DEFAULT.nc GWBUCKPARM_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Tue Jan 16 09:10:11 2018: ncap2 -s Expon=Expon*0.0+3.0 GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib2_ADJFL.nc GWBUCKPARM_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Mon Mar 27 18:47:12 2017: ncap2 -O -s Zmax=25.0 GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib1.nc GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib1.nc\\n\",\n\t\t\t\"Mon Mar 27 18:46:57 2017: ncap2 -O -s Expon=1.75 GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib1.nc GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib1.nc\\n\",\n\t\t\t\"Created Mon Mar 20 16:35:22 2017\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/GWBUCKPARM.md5",
    "content": "3ecb294d4fb9e6d235bec257e3d64ea1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/GWBUCKPARM.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/LAKEPARM.cdl",
    "content": "netcdf LAKEPARM {\ndimensions:\n\tfeature_id = 1 ;\nvariables:\n\tdouble LkArea(feature_id) ;\n\t\tLkArea:long_name = \"Gridded lake area (sq. km)\" ;\n\t\tLkArea:coordinates = \"lat lon\" ;\n\t\tLkArea:grid_mapping = \"crs\" ;\n\tdouble LkMxE(feature_id) ;\n\t\tLkMxE:long_name = \"Maximum lake elevation (m ASL)\" ;\n\t\tLkMxE:coordinates = \"lat lon\" ;\n\t\tLkMxE:grid_mapping = \"crs\" ;\n\tdouble OrificeA(feature_id) ;\n\t\tOrificeA:long_name = \"Orifice cross-sectional area (sq. m)\" ;\n\t\tOrificeA:coordinates = \"lat lon\" ;\n\t\tOrificeA:grid_mapping = \"crs\" ;\n\tdouble OrificeC(feature_id) ;\n\t\tOrificeC:long_name = \"Orifice coefficient\" ;\n\t\tOrificeC:coordinates = \"lat lon\" ;\n\t\tOrificeC:grid_mapping = \"crs\" ;\n\tdouble OrificeE(feature_id) ;\n\t\tOrificeE:long_name = \"Orifice elevation (m ASL)\" ;\n\t\tOrificeE:coordinates = \"lat lon\" ;\n\t\tOrificeE:grid_mapping = \"crs\" ;\n\tdouble WeirC(feature_id) ;\n\t\tWeirC:long_name = \"Weir coefficient\" ;\n\t\tWeirC:coordinates = \"lat lon\" ;\n\t\tWeirC:grid_mapping = \"crs\" ;\n\tdouble WeirE(feature_id) ;\n\t\tWeirE:long_name = \"Weir elevation (m ASL)\" ;\n\t\tWeirE:units = \"m\" ;\n\t\tWeirE:coordinates = \"lat lon\" ;\n\t\tWeirE:grid_mapping = \"crs\" ;\n\tdouble WeirL(feature_id) ;\n\t\tWeirL:coordinates = \"lat lon\" ;\n\t\tWeirL:grid_mapping = \"crs\" ;\n\t\tWeirL:long_name = \"Weir length (m)\" ;\n\tint ascendingIndex(feature_id) ;\n\t\tascendingIndex:long_name = \"Index to use for sorting IDs (ascending)\" ;\n\t\tascendingIndex:coordinates = \"lat lon\" ;\n\t\tascendingIndex:grid_mapping = \"crs\" ;\n\tchar crs ;\n\t\tcrs:transform_name = \"latitude_longitude\" ;\n\t\tcrs:grid_mapping_name = \"latitude_longitude\" ;\n\t\tcrs:esri_pe_string = \"GEOGCS[\\\"GCS_WGS_1984\\\",DATUM[\\\"D_WGS_1984\\\",SPHEROID[\\\"WGS_1984\\\",6378137.0,298.257223563]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:spatial_ref = \"GEOGCS[\\\"GCS_WGS_1984\\\",DATUM[\\\"D_WGS_1984\\\",SPHEROID[\\\"WGS_1984\\\",6378137.0,298.257223563]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:long_name = \"CRS definition\" ;\n\t\tcrs:longitude_of_prime_meridian = 0. ;\n\t\tcrs:_CoordinateAxes = \"lat lon\" ;\n\t\tcrs:semi_major_axis = 6378137. ;\n\t\tcrs:semi_minor_axis = 6356752.31424518 ;\n\t\tcrs:inverse_flattening = 298.257223563 ;\n\tfloat ifd(feature_id) ;\n\t\tifd:long_name = \"Initial fraction water depth\" ;\n\t\tifd:coordinates = \"lat lon\" ;\n\t\tifd:grid_mapping = \"crs\" ;\n\tint lake_id(feature_id) ;\n\t\tlake_id:long_name = \"Lake ID\" ;\n\t\tlake_id:cf_role = \"timeseries_id\" ;\n\t\tlake_id:coordinates = \"lat lon\" ;\n\t\tlake_id:grid_mapping = \"crs\" ;\n\tfloat lat(feature_id) ;\n\t\tlat:long_name = \"latitude of the lake centroid\" ;\n\t\tlat:units = \"degrees_north\" ;\n\t\tlat:standard_name = \"latitude\" ;\n\tfloat lon(feature_id) ;\n\t\tlon:long_name = \"longitude of the lake centroid\" ;\n\t\tlon:units = \"degrees_east\" ;\n\t\tlon:standard_name = \"longitude\" ;\n\tdouble time(feature_id) ;\n\t\ttime:standard_name = \"time\" ;\n\t\ttime:long_name = \"time of measurement\" ;\n\t\ttime:units = \"days since 2000-01-01 00:00:00\" ;\n\t\ttime:coordinates = \"lat lon\" ;\n\t\ttime:grid_mapping = \"crs\" ;\n\tdouble Dam_Length(feature_id) ;\n\n// global attributes:\n\t\t:Conventions = \"CF-1.5\" ;\n\t\t:featureType = \"timeSeries\" ;\n\t\t:history = \"Fri Aug 24 11:15:10 2018: ncks -O -d feature_id,1,1 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/LAKEPARM.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/LAKEPARM.nc\\n\",\n\t\t\t\"Tue Aug  7 10:00:32 2018: ncap2 -s WeirL=WeirL*0+10 LAKEPARM_20180227_v2_lakes_lowres_params.nc LAKEPARM_20180227_v2_lakes_lowres_params_WeirL_10.nc\\n\",\n\t\t\t\"Created Tue Feb 27 15:18:40 2018\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/LAKEPARM.md5",
    "content": "98ccc6b16e951b127cd1e7efd971c16c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/LAKEPARM.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/Route_Link.cdl",
    "content": "netcdf Route_Link {\ndimensions:\n\tfeature_id = 185 ;\n\tIDLength = 15 ;\nvariables:\n\tfloat BtmWdth(feature_id) ;\n\t\tBtmWdth:long_name = \"Bottom width of channel (m)\" ;\n\t\tBtmWdth:units = \"m\" ;\n\t\tBtmWdth:coordinates = \"lat lon\" ;\n\tfloat ChSlp(feature_id) ;\n\t\tChSlp:long_name = \"Channel side slope\" ;\n\t\tChSlp:coordinates = \"lat lon\" ;\n\tshort Kchan(feature_id) ;\n\t\tKchan:long_name = \"channel conductivity\" ;\n\t\tKchan:units = \"mm h-1\" ;\n\t\tKchan:coordinates = \"lat lon\" ;\n\tfloat Length(feature_id) ;\n\t\tLength:long_name = \"Stream length (m)\" ;\n\t\tLength:coordinates = \"lat lon\" ;\n\tfloat MusK(feature_id) ;\n\t\tMusK:long_name = \"Muskingum routing time (s)\" ;\n\t\tMusK:coordinates = \"lat lon\" ;\n\tfloat MusX(feature_id) ;\n\t\tMusX:long_name = \"Muskingum weighting coefficient\" ;\n\t\tMusX:coordinates = \"lat lon\" ;\n\tint NHDWaterbodyComID(feature_id) ;\n\t\tNHDWaterbodyComID:coordinates = \"lat lon\" ;\n\t\tNHDWaterbodyComID:long_name = \"ComID of NHDWaterbody feature associated using spatial join (intersection) between NHDFlowline_network and Waterbodies\" ;\n\tfloat Qi(feature_id) ;\n\t\tQi:long_name = \"Initial flow in link (CMS)\" ;\n\t\tQi:coordinates = \"lat lon\" ;\n\tfloat So(feature_id) ;\n\t\tSo:long_name = \"Slope (meters/meters from NHDFlowline_network.SLOPE)\" ;\n\t\tSo:coordinates = \"lat lon\" ;\n\tfloat TopWdth(feature_id) ;\n\t\tTopWdth:long_name = \"Top Width (m)\" ;\n\t\tTopWdth:units = \"m\" ;\n\t\tTopWdth:coordinates = \"lat lon\" ;\n\tfloat TopWdthCC(feature_id) ;\n\t\tTopWdthCC:long_name = \"Compound Channel Top Width (m)\" ;\n\t\tTopWdthCC:units = \"m\" ;\n\t\tTopWdthCC:coordinates = \"lat lon\" ;\n\tfloat alt(feature_id) ;\n\t\talt:long_name = \"Elevation in meters from the North American Vertical Datum 1988 (NADV88) at start node (MaxElevSmo)\" ;\n\t\talt:standard_name = \"height\" ;\n\t\talt:units = \"m\" ;\n\t\talt:positive = \"up\" ;\n\t\talt:axis = \"Z\" ;\n\t\talt:coordinates = \"lat lon\" ;\n\tint ascendingIndex(feature_id) ;\n\t\tascendingIndex:long_name = \"Index to use for sorting IDs (ascending)\" ;\n\tint from(feature_id) ;\n\t\tfrom:long_name = \"From Link ID (PlusFlow table FROMCOMID for every TOCOMID)\" ;\n\t\tfrom:coordinates = \"lat lon\" ;\n\tchar gages(feature_id, IDLength) ;\n\t\tgages:long_name = \"NHD Gage Event ID from SOURCE_FEA field in Gages feature class\" ;\n\t\tgages:coordinates = \"lat lon\" ;\n\tfloat lat(feature_id) ;\n\t\tlat:long_name = \"latitude of the segment midpoint\" ;\n\t\tlat:units = \"degrees_north\" ;\n\t\tlat:standard_name = \"latitude\" ;\n\t\tlat:coordinates = \"lat lon\" ;\n\tint link(feature_id) ;\n\t\tlink:long_name = \"Link ID (NHDFlowline_network COMID)\" ;\n\t\tlink:cf_role = \"timeseries_id\" ;\n\t\tlink:coordinates = \"lat lon\" ;\n\tfloat lon(feature_id) ;\n\t\tlon:long_name = \"longitude of the segment midpoint\" ;\n\t\tlon:units = \"degrees_east\" ;\n\t\tlon:standard_name = \"longitude\" ;\n\t\tlon:coordinates = \"lat lon\" ;\n\tfloat n(feature_id) ;\n\t\tn:long_name = \"Manning\\'s roughness\" ;\n\t\tn:coordinates = \"lat lon\" ;\n\tfloat nCC(feature_id) ;\n\t\tnCC:long_name = \"Compound Channel Manning\\'s n\" ;\n\t\tnCC:coordinates = \"lat lon\" ;\n\tint order(feature_id) ;\n\t\torder:long_name = \"Stream order (Strahler)\" ;\n\t\torder:coordinates = \"lat lon\" ;\n\tfloat time ;\n\t\ttime:standard_name = \"time\" ;\n\t\ttime:long_name = \"time of measurement\" ;\n\t\ttime:units = \"days since 2000-01-01 00:00:00\" ;\n\tint to(feature_id) ;\n\t\tto:long_name = \"To Link ID (PlusFlow table TOCOMID for every FROMCOMID)\" ;\n\t\tto:coordinates = \"lat lon\" ;\n\n// global attributes:\n\t\t:Convention = \"CF-1.6\" ;\n\t\t:featureType = \"timeSeries\" ;\n\t\t:history = \"Thu May 23 15:30:13 2019: ncks -O -d feature_id,1,185 /glade/scratch/arezoo/rfc_cutout_basins/Cutout_Basins/Full_Physics//0137462010/Route_Link.nc /glade/scratch/arezoo/rfc_cutout_basins/Cutout_Basins/Full_Physics//0137462010/Route_Link.nc\\n\",\n\t\t\t\"Created Wed Nov 07 23:45:44 2018\" ;\n\t\t:processing_notes = \"This file was produced Wed Nov 07 17:14:48 2018 by Kevin Sampson (NCAR) and has the following attributes: \\n\",\n\t\t\t\"   This file uses the NHDPlus v21 \\\"flattened\\\" geodatabase: NHDPlusV21_National_Flattened.gdb.\\n\",\n\t\t\t\"   This file excludes reaches in Puerto Rico and Hawaii.\\n\",\n\t\t\t\"   Routing using Arc-Hydro derived segments for Regions 01a, 02b, 09a, 10i, 10h, 13a, 13b, 13d, 15a, 15b, 17b, 18a.\\n\",\n\t\t\t\"   Topology fixes using: Topology_Fixer.csv.\\n\",\n\t\t\t\"   NHDFlowlines removed using: Remove_COMIDs_NHDFLowline_Network.csv.\\n\",\n\t\t\t\"   Gage preference list: numberOf100QualityObs.2017-03-15.csv.\\n\",\n\t\t\t\"   Gage subset list: numberOf100QualityObs.2017-03-15.csv.\\n\",\n\t\t\t\"   Gage additions made using: Add_Gage_Association.csv.\\n\",\n\t\t\t\"   Gage-to-flowline association changes made using: Bad_Gage_Associations.csv.\\n\",\n\t\t\t\"   Tidal-influenced gages removed using: TidalGageList_20170316.csv.\\n\",\n\t\t\t\"   Waterbody associations using spatial join with Lake feature class Waterbodies_V2_1km_plus_20181012.shp.\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/Route_Link.md5",
    "content": "e2bd085dd65ddf5a9fa45d735ffa6cfd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/Route_Link.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/geo_em.d01.cdl",
    "content": "netcdf geo_em.d01 {\ndimensions:\n\tTime = UNLIMITED ; // (1 currently)\n\tmonth = 12 ;\n\tsouth_north = 16 ;\n\twest_east = 15 ;\n\tland_cat = 24 ;\n\twest_east_stag = 16 ;\n\tsouth_north_stag = 17 ;\n\tsoil_cat = 16 ;\n\tDateStrLen = 19 ;\nvariables:\n\tfloat ALBEDO12M(Time, month, south_north, west_east) ;\n\t\tALBEDO12M:FieldType = 104 ;\n\t\tALBEDO12M:MemoryOrder = \"XYZ\" ;\n\t\tALBEDO12M:units = \"percent\" ;\n\t\tALBEDO12M:description = \"Monthly surface albedo\" ;\n\t\tALBEDO12M:stagger = \"M\" ;\n\t\tALBEDO12M:sr_x = 1 ;\n\t\tALBEDO12M:sr_y = 1 ;\n\tfloat CLAT(Time, south_north, west_east) ;\n\t\tCLAT:FieldType = 104 ;\n\t\tCLAT:MemoryOrder = \"XY \" ;\n\t\tCLAT:units = \"degrees latitude\" ;\n\t\tCLAT:description = \"Computational latitude on mass grid\" ;\n\t\tCLAT:stagger = \"M\" ;\n\t\tCLAT:sr_x = 1 ;\n\t\tCLAT:sr_y = 1 ;\n\tfloat CLONG(Time, south_north, west_east) ;\n\t\tCLONG:FieldType = 104 ;\n\t\tCLONG:MemoryOrder = \"XY \" ;\n\t\tCLONG:units = \"degrees longitude\" ;\n\t\tCLONG:description = \"Computational longitude on mass grid\" ;\n\t\tCLONG:stagger = \"M\" ;\n\t\tCLONG:sr_x = 1 ;\n\t\tCLONG:sr_y = 1 ;\n\tfloat CON(Time, south_north, west_east) ;\n\t\tCON:FieldType = 104 ;\n\t\tCON:MemoryOrder = \"XY \" ;\n\t\tCON:units = \"whoknows\" ;\n\t\tCON:description = \"something\" ;\n\t\tCON:stagger = \"M\" ;\n\t\tCON:sr_x = 1 ;\n\t\tCON:sr_y = 1 ;\n\tfloat COSALPHA(Time, south_north, west_east) ;\n\t\tCOSALPHA:FieldType = 104 ;\n\t\tCOSALPHA:MemoryOrder = \"XY \" ;\n\t\tCOSALPHA:units = \"none\" ;\n\t\tCOSALPHA:description = \"Cosine of rotation angle\" ;\n\t\tCOSALPHA:stagger = \"M\" ;\n\t\tCOSALPHA:sr_x = 1 ;\n\t\tCOSALPHA:sr_y = 1 ;\n\tfloat E(Time, south_north, west_east) ;\n\t\tE:FieldType = 104 ;\n\t\tE:MemoryOrder = \"XY \" ;\n\t\tE:units = \"-\" ;\n\t\tE:description = \"Coriolis E parameter\" ;\n\t\tE:stagger = \"M\" ;\n\t\tE:sr_x = 1 ;\n\t\tE:sr_y = 1 ;\n\tfloat F(Time, south_north, west_east) ;\n\t\tF:FieldType = 104 ;\n\t\tF:MemoryOrder = \"XY \" ;\n\t\tF:units = \"-\" ;\n\t\tF:description = \"Coriolis F parameter\" ;\n\t\tF:stagger = \"M\" ;\n\t\tF:sr_x = 1 ;\n\t\tF:sr_y = 1 ;\n\tfloat GREENFRAC(Time, month, south_north, west_east) ;\n\t\tGREENFRAC:FieldType = 104 ;\n\t\tGREENFRAC:MemoryOrder = \"XYZ\" ;\n\t\tGREENFRAC:units = \"fraction\" ;\n\t\tGREENFRAC:description = \"Monthly green fraction\" ;\n\t\tGREENFRAC:stagger = \"M\" ;\n\t\tGREENFRAC:sr_x = 1 ;\n\t\tGREENFRAC:sr_y = 1 ;\n\tfloat HGT_M(Time, south_north, west_east) ;\n\t\tHGT_M:FieldType = 104 ;\n\t\tHGT_M:MemoryOrder = \"XY \" ;\n\t\tHGT_M:units = \"meters MSL\" ;\n\t\tHGT_M:description = \"Topography height\" ;\n\t\tHGT_M:stagger = \"M\" ;\n\t\tHGT_M:sr_x = 1 ;\n\t\tHGT_M:sr_y = 1 ;\n\tfloat LAI12M(Time, month, south_north, west_east) ;\n\t\tLAI12M:FieldType = 104 ;\n\t\tLAI12M:MemoryOrder = \"XYZ\" ;\n\t\tLAI12M:units = \"m^2/m^2\" ;\n\t\tLAI12M:description = \"MODIS LAI\" ;\n\t\tLAI12M:stagger = \"M\" ;\n\t\tLAI12M:sr_x = 1 ;\n\t\tLAI12M:sr_y = 1 ;\n\tfloat LAKE_DEPTH(Time, south_north, west_east) ;\n\t\tLAKE_DEPTH:FieldType = 104 ;\n\t\tLAKE_DEPTH:MemoryOrder = \"XY \" ;\n\t\tLAKE_DEPTH:units = \"meters MSL\" ;\n\t\tLAKE_DEPTH:description = \"Topography height\" ;\n\t\tLAKE_DEPTH:stagger = \"M\" ;\n\t\tLAKE_DEPTH:sr_x = 1 ;\n\t\tLAKE_DEPTH:sr_y = 1 ;\n\tfloat LANDMASK(Time, south_north, west_east) ;\n\t\tLANDMASK:FieldType = 104 ;\n\t\tLANDMASK:MemoryOrder = \"XY \" ;\n\t\tLANDMASK:description = \"Landmask : 1=land, 0=water\" ;\n\t\tLANDMASK:sr_x = 1 ;\n\t\tLANDMASK:sr_y = 1 ;\n\t\tLANDMASK:stagger = \"M\" ;\n\t\tLANDMASK:units = \"none\" ;\n\tfloat LANDUSEF(Time, land_cat, south_north, west_east) ;\n\t\tLANDUSEF:FieldType = 104 ;\n\t\tLANDUSEF:MemoryOrder = \"XYZ\" ;\n\t\tLANDUSEF:units = \"category\" ;\n\t\tLANDUSEF:description = \"24-category USGS landuse\" ;\n\t\tLANDUSEF:stagger = \"M\" ;\n\t\tLANDUSEF:sr_x = 1 ;\n\t\tLANDUSEF:sr_y = 1 ;\n\tfloat LU_INDEX(Time, south_north, west_east) ;\n\t\tLU_INDEX:FieldType = 104 ;\n\t\tLU_INDEX:MemoryOrder = \"XY \" ;\n\t\tLU_INDEX:description = \"Dominant category\" ;\n\t\tLU_INDEX:sr_x = 1 ;\n\t\tLU_INDEX:sr_y = 1 ;\n\t\tLU_INDEX:stagger = \"M\" ;\n\t\tLU_INDEX:units = \"category\" ;\n\tfloat MAPFAC_M(Time, south_north, west_east) ;\n\t\tMAPFAC_M:FieldType = 104 ;\n\t\tMAPFAC_M:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_M:units = \"none\" ;\n\t\tMAPFAC_M:description = \"Mapfactor on mass grid\" ;\n\t\tMAPFAC_M:stagger = \"M\" ;\n\t\tMAPFAC_M:sr_x = 1 ;\n\t\tMAPFAC_M:sr_y = 1 ;\n\tfloat MAPFAC_MX(Time, south_north, west_east) ;\n\t\tMAPFAC_MX:FieldType = 104 ;\n\t\tMAPFAC_MX:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_MX:units = \"none\" ;\n\t\tMAPFAC_MX:description = \"Mapfactor (x-dir) on mass grid\" ;\n\t\tMAPFAC_MX:stagger = \"M\" ;\n\t\tMAPFAC_MX:sr_x = 1 ;\n\t\tMAPFAC_MX:sr_y = 1 ;\n\tfloat MAPFAC_MY(Time, south_north, west_east) ;\n\t\tMAPFAC_MY:FieldType = 104 ;\n\t\tMAPFAC_MY:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_MY:units = \"none\" ;\n\t\tMAPFAC_MY:description = \"Mapfactor (y-dir) on mass grid\" ;\n\t\tMAPFAC_MY:stagger = \"M\" ;\n\t\tMAPFAC_MY:sr_x = 1 ;\n\t\tMAPFAC_MY:sr_y = 1 ;\n\tfloat MAPFAC_U(Time, south_north, west_east_stag) ;\n\t\tMAPFAC_U:FieldType = 104 ;\n\t\tMAPFAC_U:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_U:units = \"none\" ;\n\t\tMAPFAC_U:description = \"Mapfactor on U grid\" ;\n\t\tMAPFAC_U:stagger = \"U\" ;\n\t\tMAPFAC_U:sr_x = 1 ;\n\t\tMAPFAC_U:sr_y = 1 ;\n\tfloat MAPFAC_UX(Time, south_north, west_east_stag) ;\n\t\tMAPFAC_UX:FieldType = 104 ;\n\t\tMAPFAC_UX:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_UX:units = \"none\" ;\n\t\tMAPFAC_UX:description = \"Mapfactor (x-dir) on U grid\" ;\n\t\tMAPFAC_UX:stagger = \"U\" ;\n\t\tMAPFAC_UX:sr_x = 1 ;\n\t\tMAPFAC_UX:sr_y = 1 ;\n\tfloat MAPFAC_UY(Time, south_north, west_east_stag) ;\n\t\tMAPFAC_UY:FieldType = 104 ;\n\t\tMAPFAC_UY:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_UY:units = \"none\" ;\n\t\tMAPFAC_UY:description = \"Mapfactor (y-dir) on U grid\" ;\n\t\tMAPFAC_UY:stagger = \"U\" ;\n\t\tMAPFAC_UY:sr_x = 1 ;\n\t\tMAPFAC_UY:sr_y = 1 ;\n\tfloat MAPFAC_V(Time, south_north_stag, west_east) ;\n\t\tMAPFAC_V:FieldType = 104 ;\n\t\tMAPFAC_V:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_V:units = \"none\" ;\n\t\tMAPFAC_V:description = \"Mapfactor on V grid\" ;\n\t\tMAPFAC_V:stagger = \"V\" ;\n\t\tMAPFAC_V:sr_x = 1 ;\n\t\tMAPFAC_V:sr_y = 1 ;\n\tfloat MAPFAC_VX(Time, south_north_stag, west_east) ;\n\t\tMAPFAC_VX:FieldType = 104 ;\n\t\tMAPFAC_VX:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_VX:units = \"none\" ;\n\t\tMAPFAC_VX:description = \"Mapfactor (x-dir) on V grid\" ;\n\t\tMAPFAC_VX:stagger = \"V\" ;\n\t\tMAPFAC_VX:sr_x = 1 ;\n\t\tMAPFAC_VX:sr_y = 1 ;\n\tfloat MAPFAC_VY(Time, south_north_stag, west_east) ;\n\t\tMAPFAC_VY:FieldType = 104 ;\n\t\tMAPFAC_VY:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_VY:units = \"none\" ;\n\t\tMAPFAC_VY:description = \"Mapfactor (y-dir) on V grid\" ;\n\t\tMAPFAC_VY:stagger = \"V\" ;\n\t\tMAPFAC_VY:sr_x = 1 ;\n\t\tMAPFAC_VY:sr_y = 1 ;\n\tfloat OA1(Time, south_north, west_east) ;\n\t\tOA1:FieldType = 104 ;\n\t\tOA1:MemoryOrder = \"XY \" ;\n\t\tOA1:units = \"whoknows\" ;\n\t\tOA1:description = \"something\" ;\n\t\tOA1:stagger = \"M\" ;\n\t\tOA1:sr_x = 1 ;\n\t\tOA1:sr_y = 1 ;\n\tfloat OA2(Time, south_north, west_east) ;\n\t\tOA2:FieldType = 104 ;\n\t\tOA2:MemoryOrder = \"XY \" ;\n\t\tOA2:units = \"whoknows\" ;\n\t\tOA2:description = \"something\" ;\n\t\tOA2:stagger = \"M\" ;\n\t\tOA2:sr_x = 1 ;\n\t\tOA2:sr_y = 1 ;\n\tfloat OA3(Time, south_north, west_east) ;\n\t\tOA3:FieldType = 104 ;\n\t\tOA3:MemoryOrder = \"XY \" ;\n\t\tOA3:units = \"whoknows\" ;\n\t\tOA3:description = \"something\" ;\n\t\tOA3:stagger = \"M\" ;\n\t\tOA3:sr_x = 1 ;\n\t\tOA3:sr_y = 1 ;\n\tfloat OA4(Time, south_north, west_east) ;\n\t\tOA4:FieldType = 104 ;\n\t\tOA4:MemoryOrder = \"XY \" ;\n\t\tOA4:units = \"whoknows\" ;\n\t\tOA4:description = \"something\" ;\n\t\tOA4:stagger = \"M\" ;\n\t\tOA4:sr_x = 1 ;\n\t\tOA4:sr_y = 1 ;\n\tfloat OL1(Time, south_north, west_east) ;\n\t\tOL1:FieldType = 104 ;\n\t\tOL1:MemoryOrder = \"XY \" ;\n\t\tOL1:units = \"whoknows\" ;\n\t\tOL1:description = \"something\" ;\n\t\tOL1:stagger = \"M\" ;\n\t\tOL1:sr_x = 1 ;\n\t\tOL1:sr_y = 1 ;\n\tfloat OL2(Time, south_north, west_east) ;\n\t\tOL2:FieldType = 104 ;\n\t\tOL2:MemoryOrder = \"XY \" ;\n\t\tOL2:units = \"whoknows\" ;\n\t\tOL2:description = \"something\" ;\n\t\tOL2:stagger = \"M\" ;\n\t\tOL2:sr_x = 1 ;\n\t\tOL2:sr_y = 1 ;\n\tfloat OL3(Time, south_north, west_east) ;\n\t\tOL3:FieldType = 104 ;\n\t\tOL3:MemoryOrder = \"XY \" ;\n\t\tOL3:units = \"whoknows\" ;\n\t\tOL3:description = \"something\" ;\n\t\tOL3:stagger = \"M\" ;\n\t\tOL3:sr_x = 1 ;\n\t\tOL3:sr_y = 1 ;\n\tfloat OL4(Time, south_north, west_east) ;\n\t\tOL4:FieldType = 104 ;\n\t\tOL4:MemoryOrder = \"XY \" ;\n\t\tOL4:units = \"whoknows\" ;\n\t\tOL4:description = \"something\" ;\n\t\tOL4:stagger = \"M\" ;\n\t\tOL4:sr_x = 1 ;\n\t\tOL4:sr_y = 1 ;\n\tfloat SCB_DOM(Time, south_north, west_east) ;\n\t\tSCB_DOM:FieldType = 104 ;\n\t\tSCB_DOM:MemoryOrder = \"XY \" ;\n\t\tSCB_DOM:description = \"Dominant category\" ;\n\t\tSCB_DOM:grid_mapping = \"lambert_conformal_conic\" ;\n\t\tSCB_DOM:sr_x = 1 ;\n\t\tSCB_DOM:sr_y = 1 ;\n\t\tSCB_DOM:stagger = \"M\" ;\n\t\tSCB_DOM:units = \"category\" ;\n\tfloat SCT_DOM(Time, south_north, west_east) ;\n\t\tSCT_DOM:FieldType = 104 ;\n\t\tSCT_DOM:MemoryOrder = \"XY \" ;\n\t\tSCT_DOM:description = \"Dominant category\" ;\n\t\tSCT_DOM:grid_mapping = \"lambert_conformal_conic\" ;\n\t\tSCT_DOM:sr_x = 1 ;\n\t\tSCT_DOM:sr_y = 1 ;\n\t\tSCT_DOM:stagger = \"M\" ;\n\t\tSCT_DOM:units = \"category\" ;\n\tfloat SINALPHA(Time, south_north, west_east) ;\n\t\tSINALPHA:FieldType = 104 ;\n\t\tSINALPHA:MemoryOrder = \"XY \" ;\n\t\tSINALPHA:units = \"none\" ;\n\t\tSINALPHA:description = \"Sine of rotation angle\" ;\n\t\tSINALPHA:stagger = \"M\" ;\n\t\tSINALPHA:sr_x = 1 ;\n\t\tSINALPHA:sr_y = 1 ;\n\tfloat SLOPECAT(Time, south_north, west_east) ;\n\t\tSLOPECAT:FieldType = 104 ;\n\t\tSLOPECAT:MemoryOrder = \"XY \" ;\n\t\tSLOPECAT:units = \"category\" ;\n\t\tSLOPECAT:description = \"Dominant category\" ;\n\t\tSLOPECAT:stagger = \"M\" ;\n\t\tSLOPECAT:sr_x = 1 ;\n\t\tSLOPECAT:sr_y = 1 ;\n\tfloat SNOALB(Time, south_north, west_east) ;\n\t\tSNOALB:FieldType = 104 ;\n\t\tSNOALB:MemoryOrder = \"XY \" ;\n\t\tSNOALB:units = \"percent\" ;\n\t\tSNOALB:description = \"Maximum snow albedo\" ;\n\t\tSNOALB:stagger = \"M\" ;\n\t\tSNOALB:sr_x = 1 ;\n\t\tSNOALB:sr_y = 1 ;\n\tfloat SOILCBOT(Time, soil_cat, south_north, west_east) ;\n\t\tSOILCBOT:FieldType = 104 ;\n\t\tSOILCBOT:MemoryOrder = \"XYZ\" ;\n\t\tSOILCBOT:units = \"category\" ;\n\t\tSOILCBOT:description = \"16-category bottom-layer soil type\" ;\n\t\tSOILCBOT:stagger = \"M\" ;\n\t\tSOILCBOT:sr_x = 1 ;\n\t\tSOILCBOT:sr_y = 1 ;\n\tfloat SOILCTOP(Time, soil_cat, south_north, west_east) ;\n\t\tSOILCTOP:FieldType = 104 ;\n\t\tSOILCTOP:MemoryOrder = \"XYZ\" ;\n\t\tSOILCTOP:units = \"category\" ;\n\t\tSOILCTOP:description = \"16-category top-layer soil type\" ;\n\t\tSOILCTOP:stagger = \"M\" ;\n\t\tSOILCTOP:sr_x = 1 ;\n\t\tSOILCTOP:sr_y = 1 ;\n\tfloat SOILTEMP(Time, south_north, west_east) ;\n\t\tSOILTEMP:FieldType = 104 ;\n\t\tSOILTEMP:MemoryOrder = \"XY \" ;\n\t\tSOILTEMP:units = \"Kelvin\" ;\n\t\tSOILTEMP:description = \"Annual mean deep soil temperature\" ;\n\t\tSOILTEMP:stagger = \"M\" ;\n\t\tSOILTEMP:sr_x = 1 ;\n\t\tSOILTEMP:sr_y = 1 ;\n\tchar Times(Time, DateStrLen) ;\n\tfloat VAR(Time, south_north, west_east) ;\n\t\tVAR:FieldType = 104 ;\n\t\tVAR:MemoryOrder = \"XY \" ;\n\t\tVAR:units = \"whoknows\" ;\n\t\tVAR:description = \"something\" ;\n\t\tVAR:stagger = \"M\" ;\n\t\tVAR:sr_x = 1 ;\n\t\tVAR:sr_y = 1 ;\n\tfloat VAR_SSO(Time, south_north, west_east) ;\n\t\tVAR_SSO:FieldType = 104 ;\n\t\tVAR_SSO:MemoryOrder = \"XY \" ;\n\t\tVAR_SSO:units = \"meters2 MSL\" ;\n\t\tVAR_SSO:description = \"Variance of Subgrid Scale Orography\" ;\n\t\tVAR_SSO:stagger = \"M\" ;\n\t\tVAR_SSO:sr_x = 1 ;\n\t\tVAR_SSO:sr_y = 1 ;\n\tfloat XLAT_C(Time, south_north_stag, west_east_stag) ;\n\t\tXLAT_C:FieldType = 104 ;\n\t\tXLAT_C:MemoryOrder = \"XY \" ;\n\t\tXLAT_C:units = \"degrees latitude\" ;\n\t\tXLAT_C:description = \"Latitude at grid cell corners\" ;\n\t\tXLAT_C:stagger = \"CORNER\" ;\n\t\tXLAT_C:sr_x = 1 ;\n\t\tXLAT_C:sr_y = 1 ;\n\tfloat XLAT_M(Time, south_north, west_east) ;\n\t\tXLAT_M:FieldType = 104 ;\n\t\tXLAT_M:MemoryOrder = \"XY \" ;\n\t\tXLAT_M:units = \"degrees latitude\" ;\n\t\tXLAT_M:description = \"Latitude on mass grid\" ;\n\t\tXLAT_M:stagger = \"M\" ;\n\t\tXLAT_M:sr_x = 1 ;\n\t\tXLAT_M:sr_y = 1 ;\n\tfloat XLAT_U(Time, south_north, west_east_stag) ;\n\t\tXLAT_U:FieldType = 104 ;\n\t\tXLAT_U:MemoryOrder = \"XY \" ;\n\t\tXLAT_U:units = \"degrees latitude\" ;\n\t\tXLAT_U:description = \"Latitude on U grid\" ;\n\t\tXLAT_U:stagger = \"U\" ;\n\t\tXLAT_U:sr_x = 1 ;\n\t\tXLAT_U:sr_y = 1 ;\n\tfloat XLAT_V(Time, south_north_stag, west_east) ;\n\t\tXLAT_V:FieldType = 104 ;\n\t\tXLAT_V:MemoryOrder = \"XY \" ;\n\t\tXLAT_V:units = \"degrees latitude\" ;\n\t\tXLAT_V:description = \"Latitude on V grid\" ;\n\t\tXLAT_V:stagger = \"V\" ;\n\t\tXLAT_V:sr_x = 1 ;\n\t\tXLAT_V:sr_y = 1 ;\n\tfloat XLONG_C(Time, south_north_stag, west_east_stag) ;\n\t\tXLONG_C:FieldType = 104 ;\n\t\tXLONG_C:MemoryOrder = \"XY \" ;\n\t\tXLONG_C:units = \"degrees longitude\" ;\n\t\tXLONG_C:description = \"Longitude at grid cell corners\" ;\n\t\tXLONG_C:stagger = \"CORNER\" ;\n\t\tXLONG_C:sr_x = 1 ;\n\t\tXLONG_C:sr_y = 1 ;\n\tfloat XLONG_M(Time, south_north, west_east) ;\n\t\tXLONG_M:FieldType = 104 ;\n\t\tXLONG_M:MemoryOrder = \"XY \" ;\n\t\tXLONG_M:units = \"degrees longitude\" ;\n\t\tXLONG_M:description = \"Longitude on mass grid\" ;\n\t\tXLONG_M:stagger = \"M\" ;\n\t\tXLONG_M:sr_x = 1 ;\n\t\tXLONG_M:sr_y = 1 ;\n\tfloat XLONG_U(Time, south_north, west_east_stag) ;\n\t\tXLONG_U:FieldType = 104 ;\n\t\tXLONG_U:MemoryOrder = \"XY \" ;\n\t\tXLONG_U:units = \"degrees longitude\" ;\n\t\tXLONG_U:description = \"Longitude on U grid\" ;\n\t\tXLONG_U:stagger = \"U\" ;\n\t\tXLONG_U:sr_x = 1 ;\n\t\tXLONG_U:sr_y = 1 ;\n\tfloat XLONG_V(Time, south_north_stag, west_east) ;\n\t\tXLONG_V:FieldType = 104 ;\n\t\tXLONG_V:MemoryOrder = \"XY \" ;\n\t\tXLONG_V:units = \"degrees longitude\" ;\n\t\tXLONG_V:description = \"Longitude on V grid\" ;\n\t\tXLONG_V:stagger = \"V\" ;\n\t\tXLONG_V:sr_x = 1 ;\n\t\tXLONG_V:sr_y = 1 ;\n\n// global attributes:\n\t\t:TITLE = \"OUTPUT FROM GEOGRID V3.6\" ;\n\t\t:SIMULATION_START_DATE = \"0000-00-00_00:00:00\" ;\n\t\t:WEST-EAST_GRID_DIMENSION = 16 ;\n\t\t:SOUTH-NORTH_GRID_DIMENSION = 17 ;\n\t\t:BOTTOM-TOP_GRID_DIMENSION = 0 ;\n\t\t:WEST-EAST_PATCH_START_UNSTAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_UNSTAG = 15 ;\n\t\t:SOUTH-NORTH_PATCH_START_UNSTAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_UNSTAG = 16 ;\n\t\t:GRIDTYPE = \"C\" ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:DYN_OPT = 2 ;\n\t\t:CEN_LAT = 40.00001f ;\n\t\t:CEN_LON = -97.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:MOAD_CEN_LAT = 40.00001f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:POLE_LAT = 90.f ;\n\t\t:POLE_LON = 0.f ;\n\t\t:corner_lats = 41.42281f, 41.55636f, 41.51907f, 41.3856f, 41.42413f, 41.55769f, 41.51774f, 41.38428f, 41.41836f, 41.56082f, 41.52353f, 41.38115f, 41.41969f, 41.56216f, 41.5222f, 41.37983f ;\n\t\t:corner_lons = -73.85333f, -73.80026f, -73.63379f, -73.68719f, -73.85928f, -73.80621f, -73.62784f, -73.68127f, -73.8551f, -73.79849f, -73.63202f, -73.689f, -73.86105f, -73.80444f, -73.62604f, -73.68304f ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:MMINLU = \"USGS\" ;\n\t\t:NUM_LAND_CAT = 24 ;\n\t\t:ISWATER = 16 ;\n\t\t:ISLAKE = -1 ;\n\t\t:ISICE = 24 ;\n\t\t:ISURBAN = 1 ;\n\t\t:ISOILWATER = 14 ;\n\t\t:grid_id = 1 ;\n\t\t:parent_id = 1 ;\n\t\t:i_parent_start = 1 ;\n\t\t:j_parent_start = 1 ;\n\t\t:i_parent_end = 16 ;\n\t\t:j_parent_end = 17 ;\n\t\t:parent_grid_ratio = 1 ;\n\t\t:sr_x = 1 ;\n\t\t:sr_y = 1 ;\n\t\t:FLAG_MF_XY = 1 ;\n\t\t:FLAG_LAI12M = 1 ;\n\t\t:FLAG_LAKE_DEPTH = 1 ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n\t\t:history = \"Fri Aug 24 11:14:03 2018: ncatted -O -a corner_lats,global,o,f,41.4228134155273,41.5563621520996,41.5190696716309,41.3856048583984,41.4241333007812,41.5576934814453,41.5177383422852,41.38427734375,41.4183578491211,41.5608215332031,41.5235252380371,41.3811531066895,41.4196891784668,41.5621604919434,41.5221977233887,41.3798332214355 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/geo_em.d0x.nc\\n\",\n\t\t\t\"Fri Aug 24 11:14:03 2018: ncatted -O -a corner_lons,global,o,f,-73.8533325195312,-73.8002624511719,-73.6337890625,-73.6871948242188,-73.8592834472656,-73.8062133789062,-73.6278381347656,-73.6812744140625,-73.8551025390625,-73.7984924316406,-73.6320190429688,-73.6889953613281,-73.8610534667969,-73.804443359375,-73.6260375976562,-73.6830444335938 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/geo_em.d0x.nc\\n\",\n\t\t\t\"Fri Aug 24 11:13:56 2018: ncks -d west_east,4146,4160 -d south_north,2341,2356 -d west_east_stag,4146,4161 -d south_north_stag,2341,2357 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/geo_em.d01.conus_1km_NWMv2.0_XLATC_XLONC.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/geo_em.d0x.nc\\n\",\n\t\t\t\"Wed Aug 22 18:05:18 2018: ncks -A -v XLONG_C ../../../nwmv12_finals/DOMAIN/geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC geo_em.d01.conus_1km_NWMv2.0_XLATC_XLONC.nc\\n\",\n\t\t\t\"Wed Aug 22 18:04:49 2018: ncks -A -v XLAT_C ../../../nwmv12_finals/DOMAIN/geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC geo_em.d01.conus_1km_NWMv2.0_XLATC_XLONC.nc\" ;\n\t\t:history_of_appended_files = \"Wed Aug 22 18:05:18 2018: Appended file ../../../nwmv12_finals/DOMAIN/geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Fri Dec 29 11:17:44 2017: ncks -A -v XLONG_C /glade/scratch/barlage/nwm/geo_em.d01.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC\\n\",\n\t\t\t\"Fri Dec 29 11:16:15 2017: ncks -A -v XLAT_C /glade/scratch/barlage/nwm/geo_em.d01.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC\\n\",\n\t\t\t\"Sat Apr 29 22:02:59 2017: ncks -A -v LANDUSEF landusef_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Apr 29 22:02:12 2017: ncks -A -v SOILCTOP soilctop_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Apr 29 21:59:20 2017: ncks -x -v SOILCTOP,LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\n\",\n\t\t\t\"Wed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\n\",\n\t\t\t\"Wed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\n\",\n\t\t\t\"Wed Aug 22 18:04:49 2018: Appended file ../../../nwmv12_finals/DOMAIN/geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Fri Dec 29 11:17:44 2017: ncks -A -v XLONG_C /glade/scratch/barlage/nwm/geo_em.d01.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC\\n\",\n\t\t\t\"Fri Dec 29 11:16:15 2017: ncks -A -v XLAT_C /glade/scratch/barlage/nwm/geo_em.d01.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC\\n\",\n\t\t\t\"Sat Apr 29 22:02:59 2017: ncks -A -v LANDUSEF landusef_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Apr 29 22:02:12 2017: ncks -A -v SOILCTOP soilctop_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Apr 29 21:59:20 2017: ncks -x -v SOILCTOP,LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\n\",\n\t\t\t\"Wed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\n\",\n\t\t\t\"Wed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\n\",\n\t\t\t\"\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/geo_em.d01.md5",
    "content": "f43e8dce508931db002e18fe3469fa26  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/geo_em.d01.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/hydro2dtbl.cdl",
    "content": "netcdf hydro2dtbl {\ndimensions:\n\tsouth_north = 16 ;\n\twest_east = 15 ;\nvariables:\n\tfloat LKSAT(south_north, west_east) ;\n\t\tLKSAT:_FillValue = -9999.f ;\n\tfloat OV_ROUGH2D(south_north, west_east) ;\n\t\tOV_ROUGH2D:_FillValue = -9999.f ;\n\tfloat SMCMAX1(south_north, west_east) ;\n\t\tSMCMAX1:_FillValue = -9999.f ;\n\tfloat SMCREF1(south_north, west_east) ;\n\t\tSMCREF1:_FillValue = -9999.f ;\n\tfloat SMCWLT1(south_north, west_east) ;\n\t\tSMCWLT1:_FillValue = -9999.f ;\n\n// global attributes:\n\t\t:TITLE = \"OUTPUT FROM GEOGRID V3.6\" ;\n\t\t:SIMULATION_START_DATE = \"0000-00-00_00:00:00\" ;\n\t\t:WEST-EAST_GRID_DIMENSION = 4609 ;\n\t\t:SOUTH-NORTH_GRID_DIMENSION = 3841 ;\n\t\t:BOTTOM-TOP_GRID_DIMENSION = 0 ;\n\t\t:WEST-EAST_PATCH_START_UNSTAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_UNSTAG = 4608 ;\n\t\t:WEST-EAST_PATCH_START_STAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_STAG = 4609 ;\n\t\t:SOUTH-NORTH_PATCH_START_UNSTAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_UNSTAG = 3840 ;\n\t\t:SOUTH-NORTH_PATCH_START_STAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_STAG = 3841 ;\n\t\t:GRIDTYPE = \"C\" ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:DYN_OPT = 2 ;\n\t\t:CEN_LAT = 40.00001f ;\n\t\t:CEN_LON = -97.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:MOAD_CEN_LAT = 40.00001f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:POLE_LAT = 90.f ;\n\t\t:POLE_LON = 0.f ;\n\t\t:corner_lats = 20.07781f, 52.87278f, 52.87278f, 20.07781f, 20.07671f, 52.87075f, 52.87075f, 20.07671f, 20.07371f, 52.87693f, 52.87693f, 20.07371f, 20.07259f, 52.87489f, 52.87489f, 20.07259f ;\n\t\t:corner_lons = -118.1045f, -133.5073f, -60.49268f, -75.89551f, -118.1089f, -133.5142f, -60.48578f, -75.89114f, -118.1033f, -133.5107f, -60.48929f, -75.8967f, -118.1077f, -133.5176f, -60.48242f, -75.89233f ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:MMINLU = \"USGS\" ;\n\t\t:NUM_LAND_CAT = 24 ;\n\t\t:ISWATER = 16 ;\n\t\t:ISLAKE = -1 ;\n\t\t:ISICE = 24 ;\n\t\t:ISURBAN = 1 ;\n\t\t:ISOILWATER = 14 ;\n\t\t:grid_id = 1 ;\n\t\t:parent_id = 1 ;\n\t\t:i_parent_start = 1 ;\n\t\t:j_parent_start = 1 ;\n\t\t:i_parent_end = 4609 ;\n\t\t:j_parent_end = 3841 ;\n\t\t:parent_grid_ratio = 1 ;\n\t\t:sr_x = 1 ;\n\t\t:sr_y = 1 ;\n\t\t:FLAG_MF_XY = 1 ;\n\t\t:FLAG_LAI12M = 1 ;\n\t\t:FLAG_LAKE_DEPTH = 1 ;\n\t\t:history = \"Fri Aug 24 11:14:03 2018: ncks -O -d west_east,4146,4160 -d south_north,2341,2356 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/hydro2dtbl_FullRouting_NWMv2.0.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/hydro2dtbl.nc\\nMon Jul 30 11:08:53 2018: ncks -O -x -v HGT_M hydro2dtbl_nwmv20_default_TEST.nc.ALL hydro2dtbl_nwmv20_default_TEST.nc.ALL\\nMon Jul 30 11:08:52 2018: ncks -O -4 -v HGT_M geo_em.d01.conus_1km_nlcd11_nwmv20_waterfixes_TEST.nc hydro2dtbl_nwmv20_default_TEST.nc.ALL\\nMon Apr  2 15:58:58 2018: ncks -A -v SCT_DOM /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/soltyp.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nMon Apr  2 15:32:45 2018: ncap2 -O -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.conus_1km_nlcd11_nwmv20.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nMon Apr  2 15:15:40 2018: ncks -A -v LU_INDEX /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/vegtyp.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nSat Apr 29 22:02:59 2017: ncks -A -v LANDUSEF landusef_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Apr 29 22:02:12 2017: ncks -A -v SOILCTOP soilctop_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Apr 29 21:59:20 2017: ncks -x -v SOILCTOP,LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n\t\t:history_of_appended_files = \"Mon Apr  2 15:58:58 2018: Appended file /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/soltyp.nc had following \\\"history\\\" attribute:\\nMon Apr  2 10:30:03 2018: ncap2 -O -s ISLTYP=int(Band1) soltyp.nc soltyp.nc\\nMon Apr  2 10:30:02 2018: ncap2 -O -s SCT_DOM=float(Band1) soltyp.nc soltyp.nc\\nMon Apr 02 10:29:34 2018: GDAL CreateCopy( soltyp.nc, ... )\\nMon Apr  2 15:15:40 2018: Appended file /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/vegtyp.nc had following \\\"history\\\" attribute:\\nMon Apr  2 10:29:46 2018: ncap2 -O -s IVGTYP=int(Band1) vegtyp.nc vegtyp.nc\\nMon Apr  2 10:29:45 2018: ncap2 -O -s LU_INDEX=float(Band1) vegtyp.nc vegtyp.nc\\nMon Apr 02 10:29:32 2018: GDAL CreateCopy( vegtyp.nc, ... )\\nSat Apr 29 22:02:59 2017: Appended file landusef_new.nc had following \\\"history\\\" attribute:\\nSat Apr 29 21:23:52 2017: ncks -v LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix landusef_orig.nc\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\nSat Apr 29 22:02:12 2017: Appended file soilctop_new.nc had following \\\"history\\\" attribute:\\nSat Apr 29 16:08:07 2017: ncks -v SOILCTOP geo_em.d01.nc.conus_1km_nlcd11_glacfix soilctop_orig.nc\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\n\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/hydro2dtbl.md5",
    "content": "67e9d704c5e7315ac6c947cc717196ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/hydro2dtbl.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/nudgingParams.cdl",
    "content": "netcdf nudgingParams {\ndimensions:\n\tstationIdInd = UNLIMITED ; // (4 currently)\n\tmonthInd = 12 ;\n\tthreshCatInd = 2 ;\n\tthreshInd = 1 ;\n\tstationIdStrLen = 15 ;\nvariables:\n\tfloat G(stationIdInd) ;\n\t\tG:units = \"-\" ;\n\t\tG:long_name = \"Amplitude of nudging\" ;\n\tfloat R(stationIdInd) ;\n\t\tR:units = \"meters\" ;\n\t\tR:long_name = \"Radius of influence in meters\" ;\n\tfloat expCoeff(stationIdInd, monthInd, threshCatInd) ;\n\t\texpCoeff:units = \"minutes\" ;\n\t\texpCoeff:long_name = \"Coefficient b in denominator e^(-dt/b)\" ;\n\tfloat qThresh(stationIdInd, monthInd, threshInd) ;\n\t\tqThresh:units = \"m^3/s\" ;\n\t\tqThresh:long_name = \"Discharge threshold category\" ;\n\tchar stationId(stationIdInd, stationIdStrLen) ;\n\t\tstationId:units = \"-\" ;\n\t\tstationId:long_name = \"USGS station identifer\" ;\n\tfloat tau(stationIdInd) ;\n\t\ttau:units = \"minutes\" ;\n\t\ttau:long_name = \"Time tapering parameter half window size in minutes\" ;\n\n// global attributes:\n\t\t:history = \"Mon Feb  5 13:36:43 2018: ncks -O -d stationIdInd,1,4 /glade/p/nwc/arezoo/test_case/0137462010/nudgingParams.nc /glade/p/nwc/arezoo/test_case/0137462010/nudgingParams.nc\" ;\n\t\t:NCO = \"\\\"4.6.2\\\"\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/nudgingParams.md5",
    "content": "0dd15ead2501e003d8f745735e71a808  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/nudgingParams.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/soil_properties.cdl",
    "content": "netcdf soil_properties {\ndimensions:\n\tTime = UNLIMITED ; // (1 currently)\n\tsoil_layers_stag = 4 ;\n\tsouth_north = 16 ;\n\twest_east = 15 ;\nvariables:\n\tfloat bexp(Time, soil_layers_stag, south_north, west_east) ;\n\t\tbexp:_FillValue = -9999.f ;\n\tfloat cwpvt(Time, south_north, west_east) ;\n\t\tcwpvt:_FillValue = -9999.f ;\n\tfloat dksat(Time, soil_layers_stag, south_north, west_east) ;\n\t\tdksat:_FillValue = -9999.f ;\n\tfloat dwsat(Time, soil_layers_stag, south_north, west_east) ;\n\t\tdwsat:_FillValue = -9999.f ;\n\tfloat hvt(Time, south_north, west_east) ;\n\t\thvt:_FillValue = -9999.f ;\n\tfloat mfsno(Time, south_north, west_east) ;\n\t\tmfsno:_FillValue = -9999.f ;\n\tfloat mp(Time, south_north, west_east) ;\n\t\tmp:_FillValue = -9999.f ;\n\tfloat psisat(Time, soil_layers_stag, south_north, west_east) ;\n\t\tpsisat:_FillValue = -9999.f ;\n\tfloat quartz(Time, soil_layers_stag, south_north, west_east) ;\n\t\tquartz:_FillValue = -9999.f ;\n\tfloat refdk(Time, south_north, west_east) ;\n\t\trefdk:_FillValue = -9999.f ;\n\tfloat refkdt(Time, south_north, west_east) ;\n\t\trefkdt:_FillValue = -9999.f ;\n\tfloat rsurfexp(Time, south_north, west_east) ;\n\t\trsurfexp:_FillValue = -9999.f ;\n\tfloat slope(Time, south_north, west_east) ;\n\t\tslope:_FillValue = -9999.f ;\n\tfloat smcdry(Time, soil_layers_stag, south_north, west_east) ;\n\t\tsmcdry:_FillValue = -9999.f ;\n\tfloat smcmax(Time, soil_layers_stag, south_north, west_east) ;\n\t\tsmcmax:_FillValue = -9999.f ;\n\tfloat smcref(Time, soil_layers_stag, south_north, west_east) ;\n\t\tsmcref:_FillValue = -9999.f ;\n\tfloat smcwlt(Time, soil_layers_stag, south_north, west_east) ;\n\t\tsmcwlt:_FillValue = -9999.f ;\n\tfloat vcmx25(Time, south_north, west_east) ;\n\t\tvcmx25:_FillValue = -9999.f ;\n\n// global attributes:\n\t\t:TITLE = \"OUTPUT FROM GEOGRID V3.6\" ;\n\t\t:SIMULATION_START_DATE = \"0000-00-00_00:00:00\" ;\n\t\t:WEST-EAST_GRID_DIMENSION = 4609 ;\n\t\t:SOUTH-NORTH_GRID_DIMENSION = 3841 ;\n\t\t:BOTTOM-TOP_GRID_DIMENSION = 0 ;\n\t\t:WEST-EAST_PATCH_START_UNSTAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_UNSTAG = 4608 ;\n\t\t:WEST-EAST_PATCH_START_STAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_STAG = 4609 ;\n\t\t:SOUTH-NORTH_PATCH_START_UNSTAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_UNSTAG = 3840 ;\n\t\t:SOUTH-NORTH_PATCH_START_STAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_STAG = 3841 ;\n\t\t:GRIDTYPE = \"C\" ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:DYN_OPT = 2 ;\n\t\t:CEN_LAT = 40.00001f ;\n\t\t:CEN_LON = -97.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:MOAD_CEN_LAT = 40.00001f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:POLE_LAT = 90.f ;\n\t\t:POLE_LON = 0.f ;\n\t\t:corner_lats = 20.07781f, 52.87278f, 52.87278f, 20.07781f, 20.07671f, 52.87075f, 52.87075f, 20.07671f, 20.07371f, 52.87693f, 52.87693f, 20.07371f, 20.07259f, 52.87489f, 52.87489f, 20.07259f ;\n\t\t:corner_lons = -118.1045f, -133.5073f, -60.49268f, -75.89551f, -118.1089f, -133.5142f, -60.48578f, -75.89114f, -118.1033f, -133.5107f, -60.48929f, -75.8967f, -118.1077f, -133.5176f, -60.48242f, -75.89233f ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:MMINLU = \"USGS\" ;\n\t\t:NUM_LAND_CAT = 24 ;\n\t\t:ISWATER = 16 ;\n\t\t:ISLAKE = -1 ;\n\t\t:ISICE = 24 ;\n\t\t:ISURBAN = 1 ;\n\t\t:ISOILWATER = 14 ;\n\t\t:grid_id = 1 ;\n\t\t:parent_id = 1 ;\n\t\t:i_parent_start = 1 ;\n\t\t:j_parent_start = 1 ;\n\t\t:i_parent_end = 4609 ;\n\t\t:j_parent_end = 3841 ;\n\t\t:parent_grid_ratio = 1 ;\n\t\t:sr_x = 1 ;\n\t\t:sr_y = 1 ;\n\t\t:FLAG_MF_XY = 1 ;\n\t\t:FLAG_LAI12M = 1 ;\n\t\t:FLAG_LAKE_DEPTH = 1 ;\n\t\t:history = \"Fri Aug 24 11:14:53 2018: ncks -O -d west_east,4146,4160 -d south_north,2341,2356 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/soil_properties_FullRouting_NWMv2.0.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/soil_properties.nc\\nMon Jul 30 11:08:43 2018: ncks -O -x -v HGT_M soil_properties_nwmv20_default_TEST.nc soil_properties_nwmv20_default_TEST.nc\\nMon Jul 30 11:08:42 2018: ncks -O -4 -v HGT_M geo_em.d01.conus_1km_nlcd11_nwmv20_waterfixes_TEST.nc soil_properties_nwmv20_default_TEST.nc\\nMon Apr  2 15:58:58 2018: ncks -A -v SCT_DOM /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/soltyp.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nMon Apr  2 15:32:45 2018: ncap2 -O -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.conus_1km_nlcd11_nwmv20.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nMon Apr  2 15:15:40 2018: ncks -A -v LU_INDEX /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/vegtyp.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nSat Apr 29 22:02:59 2017: ncks -A -v LANDUSEF landusef_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Apr 29 22:02:12 2017: ncks -A -v SOILCTOP soilctop_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Apr 29 21:59:20 2017: ncks -x -v SOILCTOP,LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n\t\t:history_of_appended_files = \"Mon Apr  2 15:58:58 2018: Appended file /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/soltyp.nc had following \\\"history\\\" attribute:\\nMon Apr  2 10:30:03 2018: ncap2 -O -s ISLTYP=int(Band1) soltyp.nc soltyp.nc\\nMon Apr  2 10:30:02 2018: ncap2 -O -s SCT_DOM=float(Band1) soltyp.nc soltyp.nc\\nMon Apr 02 10:29:34 2018: GDAL CreateCopy( soltyp.nc, ... )\\nMon Apr  2 15:15:40 2018: Appended file /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/vegtyp.nc had following \\\"history\\\" attribute:\\nMon Apr  2 10:29:46 2018: ncap2 -O -s IVGTYP=int(Band1) vegtyp.nc vegtyp.nc\\nMon Apr  2 10:29:45 2018: ncap2 -O -s LU_INDEX=float(Band1) vegtyp.nc vegtyp.nc\\nMon Apr 02 10:29:32 2018: GDAL CreateCopy( vegtyp.nc, ... )\\nSat Apr 29 22:02:59 2017: Appended file landusef_new.nc had following \\\"history\\\" attribute:\\nSat Apr 29 21:23:52 2017: ncks -v LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix landusef_orig.nc\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\nSat Apr 29 22:02:12 2017: Appended file soilctop_new.nc had following \\\"history\\\" attribute:\\nSat Apr 29 16:08:07 2017: ncks -v SOILCTOP geo_em.d01.nc.conus_1km_nlcd11_glacfix soilctop_orig.nc\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\n\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/soil_properties.md5",
    "content": "97e12ac3236c3bb394aac1992bfab768  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/soil_properties.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/spatialweights.cdl",
    "content": "netcdf spatialweights {\ndimensions:\n\tdata = 4980 ;\n\tpolyid = 183 ;\nvariables:\n\tint IDmask(data) ;\n\t\tIDmask:long_name = \"Polygon ID (polyid) associated with each record\" ;\n\tint i_index(data) ;\n\t\ti_index:long_name = \"Index in the x dimension of the raster grid (starting with 1,1 in LL corner)\" ;\n\tint j_index(data) ;\n\t\tj_index:long_name = \"Index in the y dimension of the raster grid (starting with 1,1 in LL corner)\" ;\n\tint overlaps(polyid) ;\n\t\toverlaps:long_name = \"Number of intersecting polygons\" ;\n\tint polyid(polyid) ;\n\t\tpolyid:long_name = \"ID of polygon\" ;\n\tdouble regridweight(data) ;\n\t\tregridweight:long_name = \"fraction of intersecting polyid(overlapper) intersected by polygon(polyid)\" ;\n\tdouble weight(data) ;\n\t\tweight:long_name = \"fraction of polygon(polyid) intersected by polygon identified by poly2\" ;\n\n// global attributes:\n\t\t:history = \"Fri Aug 24 11:14:49 2018: ncks -O -d polyid,1,183 -d data,1,4980 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/spatialweights.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/spatialweights.nc\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/spatialweights.md5",
    "content": "88f0333533dc94daf68faf84cf7956fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/spatialweights.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/wrfinput_d01.cdl",
    "content": "netcdf wrfinput_d01 {\ndimensions:\n\tTime = UNLIMITED ; // (1 currently)\n\tsouth_north = 16 ;\n\twest_east = 15 ;\n\tsoil_layers_stag = 4 ;\nvariables:\n\tfloat CANWAT(Time, south_north, west_east) ;\n\t\tCANWAT:units = \"kg/m^2\" ;\n\t\tCANWAT:_FillValue = -1.e+36f ;\n\tfloat DZS(Time, soil_layers_stag) ;\n\t\tDZS:units = \"m\" ;\n\t\tDZS:_FillValue = -1.e+36f ;\n\tfloat HGT(Time, south_north, west_east) ;\n\t\tHGT:FieldType = 104 ;\n\t\tHGT:MemoryOrder = \"XY \" ;\n\t\tHGT:units = \"meters MSL\" ;\n\t\tHGT:description = \"Topography height\" ;\n\t\tHGT:stagger = \"M\" ;\n\t\tHGT:sr_x = 1 ;\n\t\tHGT:sr_y = 1 ;\n\tint ISLTYP(Time, south_north, west_east) ;\n\t\tISLTYP:FieldType = 104 ;\n\t\tISLTYP:MemoryOrder = \"XY \" ;\n\t\tISLTYP:description = \"Dominant category\" ;\n\t\tISLTYP:grid_mapping = \"lambert_conformal_conic\" ;\n\t\tISLTYP:sr_x = 1 ;\n\t\tISLTYP:sr_y = 1 ;\n\t\tISLTYP:stagger = \"M\" ;\n\t\tISLTYP:units = \"category\" ;\n\tint IVGTYP(Time, south_north, west_east) ;\n\t\tIVGTYP:FieldType = 104 ;\n\t\tIVGTYP:MemoryOrder = \"XY \" ;\n\t\tIVGTYP:description = \"Dominant category\" ;\n\t\tIVGTYP:grid_mapping = \"lambert_conformal_conic\" ;\n\t\tIVGTYP:sr_x = 1 ;\n\t\tIVGTYP:sr_y = 1 ;\n\t\tIVGTYP:stagger = \"M\" ;\n\t\tIVGTYP:units = \"category\" ;\n\tfloat LAI(Time, south_north, west_east) ;\n\t\tLAI:units = \"m^2/m^2\" ;\n\t\tLAI:_FillValue = -1.e+36f ;\n\tfloat MAPFAC_MX(Time, south_north, west_east) ;\n\t\tMAPFAC_MX:FieldType = 104 ;\n\t\tMAPFAC_MX:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_MX:units = \"none\" ;\n\t\tMAPFAC_MX:description = \"Mapfactor (x-dir) on mass grid\" ;\n\t\tMAPFAC_MX:stagger = \"M\" ;\n\t\tMAPFAC_MX:sr_x = 1 ;\n\t\tMAPFAC_MX:sr_y = 1 ;\n\tfloat MAPFAC_MY(Time, south_north, west_east) ;\n\t\tMAPFAC_MY:FieldType = 104 ;\n\t\tMAPFAC_MY:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_MY:units = \"none\" ;\n\t\tMAPFAC_MY:description = \"Mapfactor (y-dir) on mass grid\" ;\n\t\tMAPFAC_MY:stagger = \"M\" ;\n\t\tMAPFAC_MY:sr_x = 1 ;\n\t\tMAPFAC_MY:sr_y = 1 ;\n\tfloat SEAICE(Time, south_north, west_east) ;\n\t\tSEAICE:_FillValue = -1.e+36f ;\n\tfloat SHDMAX(Time, south_north, west_east) ;\n\t\tSHDMAX:_FillValue = -1.e+36f ;\n\t\tSHDMAX:units = \"%\" ;\n\tfloat SHDMIN(Time, south_north, west_east) ;\n\t\tSHDMIN:units = \"%\" ;\n\t\tSHDMIN:_FillValue = -1.e+36f ;\n\tfloat SMOIS(Time, soil_layers_stag, south_north, west_east) ;\n\t\tSMOIS:units = \"m^3/m^3\" ;\n\t\tSMOIS:_FillValue = -1.e+36f ;\n\tfloat SNOW(Time, south_north, west_east) ;\n\t\tSNOW:units = \"kg/m^2\" ;\n\t\tSNOW:_FillValue = -1.e+36f ;\n\tfloat TMN(Time, south_north, west_east) ;\n\t\tTMN:units = \"K\" ;\n\t\tTMN:_FillValue = -1.e+36f ;\n\tfloat TSK(Time, south_north, west_east) ;\n\t\tTSK:units = \"K\" ;\n\t\tTSK:_FillValue = -1.e+36f ;\n\tfloat TSLB(Time, soil_layers_stag, south_north, west_east) ;\n\t\tTSLB:units = \"K\" ;\n\t\tTSLB:_FillValue = -1.e+36f ;\n\tint XLAND(Time, south_north, west_east) ;\n\t\tXLAND:_FillValue = -9999 ;\n\tfloat XLAT(Time, south_north, west_east) ;\n\t\tXLAT:FieldType = 104 ;\n\t\tXLAT:MemoryOrder = \"XY \" ;\n\t\tXLAT:units = \"degrees latitude\" ;\n\t\tXLAT:description = \"Latitude on mass grid\" ;\n\t\tXLAT:stagger = \"M\" ;\n\t\tXLAT:sr_x = 1 ;\n\t\tXLAT:sr_y = 1 ;\n\tfloat XLONG(Time, south_north, west_east) ;\n\t\tXLONG:FieldType = 104 ;\n\t\tXLONG:MemoryOrder = \"XY \" ;\n\t\tXLONG:units = \"degrees longitude\" ;\n\t\tXLONG:description = \"Longitude on mass grid\" ;\n\t\tXLONG:stagger = \"M\" ;\n\t\tXLONG:sr_x = 1 ;\n\t\tXLONG:sr_y = 1 ;\n\tfloat ZS(Time, soil_layers_stag) ;\n\t\tZS:units = \"m\" ;\n\t\tZS:_FillValue = -1.e+36f ;\n\n// global attributes:\n\t\t:TITLE = \"OUTPUT FROM GEOGRID V3.6\" ;\n\t\t:SIMULATION_START_DATE = \"0000-00-00_00:00:00\" ;\n\t\t:BOTTOM-TOP_GRID_DIMENSION = 0 ;\n\t\t:WEST-EAST_PATCH_START_UNSTAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_UNSTAG = 4608 ;\n\t\t:WEST-EAST_PATCH_START_STAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_STAG = 4609 ;\n\t\t:SOUTH-NORTH_PATCH_START_UNSTAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_UNSTAG = 3840 ;\n\t\t:SOUTH-NORTH_PATCH_START_STAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_STAG = 3841 ;\n\t\t:GRIDTYPE = \"C\" ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:DYN_OPT = 2 ;\n\t\t:CEN_LAT = 40.00001f ;\n\t\t:CEN_LON = -97.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:MOAD_CEN_LAT = 40.00001f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:POLE_LAT = 90.f ;\n\t\t:POLE_LON = 0.f ;\n\t\t:corner_lats = 20.07781f, 52.87278f, 52.87278f, 20.07781f, 20.07671f, 52.87075f, 52.87075f, 20.07671f, 20.07371f, 52.87693f, 52.87693f, 20.07371f, 20.07259f, 52.87489f, 52.87489f, 20.07259f ;\n\t\t:corner_lons = -118.1045f, -133.5073f, -60.49268f, -75.89551f, -118.1089f, -133.5142f, -60.48578f, -75.89114f, -118.1033f, -133.5107f, -60.48929f, -75.8967f, -118.1077f, -133.5176f, -60.48242f, -75.89233f ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:MMINLU = \"USGS\" ;\n\t\t:NUM_LAND_CAT = 24 ;\n\t\t:ISWATER = 16 ;\n\t\t:ISLAKE = -1 ;\n\t\t:ISICE = 24 ;\n\t\t:ISURBAN = 1 ;\n\t\t:ISOILWATER = 14 ;\n\t\t:grid_id = 1 ;\n\t\t:parent_id = 1 ;\n\t\t:i_parent_start = 1 ;\n\t\t:j_parent_start = 1 ;\n\t\t:i_parent_end = 4609 ;\n\t\t:j_parent_end = 3841 ;\n\t\t:parent_grid_ratio = 1 ;\n\t\t:sr_x = 1 ;\n\t\t:sr_y = 1 ;\n\t\t:FLAG_MF_XY = 1 ;\n\t\t:FLAG_LAI12M = 1 ;\n\t\t:FLAG_LAKE_DEPTH = 1 ;\n\t\t:nco_openmp_thread_number = 1 ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:history = \"Fri Aug 24 11:14:04 2018: ncks -O -d west_east,4146,4160 -d south_north,2341,2356 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/wrfinput.d01.conus_1km_NWMv2.0.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0//0137462010/wrfinput_d0x.nc\" ;\n\t\t:WEST-EAST_GRID_DIMENSION = 16 ;\n\t\t:SOUTH-NORTH_GRID_DIMENSION = 17 ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/DOMAIN/wrfinput_d01.md5",
    "content": "5ceacffb2663712c88b195f6cc29edd4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/wrfinput_d01.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/RESTART/HYDRO_RST.2011-08-26_00:00_DOMAIN1.cdl",
    "content": "netcdf HYDRO_RST {\ndimensions:\n\tdepth = 4 ;\n\tix = 15 ;\n\tiy = 16 ;\n\tixrt = 60 ;\n\tiyrt = 64 ;\n\tlinks = 185 ;\n\tbasns = 185 ;\n\tlakes = 1 ;\nvariables:\n\tfloat stc1(iy, ix) ;\n\tfloat smc1(iy, ix) ;\n\tfloat sh2ox1(iy, ix) ;\n\tfloat stc2(iy, ix) ;\n\tfloat smc2(iy, ix) ;\n\tfloat sh2ox2(iy, ix) ;\n\tfloat stc3(iy, ix) ;\n\tfloat smc3(iy, ix) ;\n\tfloat sh2ox3(iy, ix) ;\n\tfloat stc4(iy, ix) ;\n\tfloat smc4(iy, ix) ;\n\tfloat sh2ox4(iy, ix) ;\n\tfloat infxsrt(iy, ix) ;\n\tfloat soldrain(iy, ix) ;\n\tfloat sfcheadrt(iy, ix) ;\n\tfloat QBDRYRT(iyrt, ixrt) ;\n\tfloat infxswgt(iyrt, ixrt) ;\n\tfloat sfcheadsubrt(iyrt, ixrt) ;\n\tfloat sh2owgt1(iyrt, ixrt) ;\n\tfloat sh2owgt2(iyrt, ixrt) ;\n\tfloat sh2owgt3(iyrt, ixrt) ;\n\tfloat sh2owgt4(iyrt, ixrt) ;\n\tfloat qstrmvolrt(iyrt, ixrt) ;\n\tfloat hlink(links) ;\n\tfloat qlink1(links) ;\n\tfloat qlink2(links) ;\n\tfloat resht(lakes) ;\n\tfloat qlakeo(lakes) ;\n\tfloat qlakei(lakes) ;\n\tfloat lake_inflort(iyrt, ixrt) ;\n\tfloat z_gwsubbas(links) ;\n\n// global attributes:\n\t\t:his_out_counts = 41 ;\n\t\t:Restart_Time = \"2011-08-26_00:00:00\" ;\n\t\t:Since_Date = \"2007-01-01_00:00:00\" ;\n\t\t:DTCT = 300.f ;\n\t\t:channel_only = 0 ;\n\t\t:channelBucket_only = 0 ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/RESTART/HYDRO_RST.2011-08-26_00:00_DOMAIN1.md5",
    "content": "73b445b7451424cb89d60e6ec5b594e4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/RESTART/HYDRO_RST.2011-08-26_00:00_DOMAIN1\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/RESTART/RESTART.2011082600_DOMAIN1.cdl",
    "content": "netcdf RESTART {\ndimensions:\n\tTime = UNLIMITED ; // (1 currently)\n\tDateStrLen = 19 ;\n\twest_east = 15 ;\n\tsouth_north = 16 ;\n\twest_east_stag = 16 ;\n\tsouth_north_stag = 17 ;\n\tsoil_layers_stag = 4 ;\n\tsnow_layers = 3 ;\n\tsosn_layers = 7 ;\nvariables:\n\tchar Times(Time, DateStrLen) ;\n\tfloat SOIL_T(Time, south_north, soil_layers_stag, west_east) ;\n\t\tSOIL_T:MemoryOrder = \"XZY\" ;\n\t\tSOIL_T:description = \"\" ;\n\t\tSOIL_T:units = \"\" ;\n\tfloat SNOW_T(Time, south_north, snow_layers, west_east) ;\n\t\tSNOW_T:MemoryOrder = \"XZY\" ;\n\t\tSNOW_T:description = \"\" ;\n\t\tSNOW_T:units = \"\" ;\n\tfloat SMC(Time, south_north, soil_layers_stag, west_east) ;\n\t\tSMC:MemoryOrder = \"XZY\" ;\n\t\tSMC:description = \"\" ;\n\t\tSMC:units = \"\" ;\n\tfloat SH2O(Time, south_north, soil_layers_stag, west_east) ;\n\t\tSH2O:MemoryOrder = \"XZY\" ;\n\t\tSH2O:description = \"\" ;\n\t\tSH2O:units = \"\" ;\n\tfloat ZSNSO(Time, south_north, sosn_layers, west_east) ;\n\t\tZSNSO:MemoryOrder = \"XZY\" ;\n\t\tZSNSO:description = \"\" ;\n\t\tZSNSO:units = \"\" ;\n\tfloat SNICE(Time, south_north, snow_layers, west_east) ;\n\t\tSNICE:MemoryOrder = \"XZY\" ;\n\t\tSNICE:description = \"\" ;\n\t\tSNICE:units = \"\" ;\n\tfloat SNLIQ(Time, south_north, snow_layers, west_east) ;\n\t\tSNLIQ:MemoryOrder = \"XZY\" ;\n\t\tSNLIQ:description = \"\" ;\n\t\tSNLIQ:units = \"\" ;\n\tfloat QSNOW(Time, south_north, west_east) ;\n\t\tQSNOW:MemoryOrder = \"XY\" ;\n\t\tQSNOW:description = \"\" ;\n\t\tQSNOW:units = \"\" ;\n\tfloat FWET(Time, south_north, west_east) ;\n\t\tFWET:MemoryOrder = \"XY\" ;\n\t\tFWET:description = \"\" ;\n\t\tFWET:units = \"\" ;\n\tfloat SNEQVO(Time, south_north, west_east) ;\n\t\tSNEQVO:MemoryOrder = \"XY\" ;\n\t\tSNEQVO:description = \"\" ;\n\t\tSNEQVO:units = \"\" ;\n\tfloat EAH(Time, south_north, west_east) ;\n\t\tEAH:MemoryOrder = \"XY\" ;\n\t\tEAH:description = \"\" ;\n\t\tEAH:units = \"\" ;\n\tfloat TAH(Time, south_north, west_east) ;\n\t\tTAH:MemoryOrder = \"XY\" ;\n\t\tTAH:description = \"\" ;\n\t\tTAH:units = \"\" ;\n\tfloat ALBOLD(Time, south_north, west_east) ;\n\t\tALBOLD:MemoryOrder = \"XY\" ;\n\t\tALBOLD:description = \"\" ;\n\t\tALBOLD:units = \"\" ;\n\tfloat CM(Time, south_north, west_east) ;\n\t\tCM:MemoryOrder = \"XY\" ;\n\t\tCM:description = \"\" ;\n\t\tCM:units = \"\" ;\n\tfloat CH(Time, south_north, west_east) ;\n\t\tCH:MemoryOrder = \"XY\" ;\n\t\tCH:description = \"\" ;\n\t\tCH:units = \"\" ;\n\tint ISNOW(Time, south_north, west_east) ;\n\t\tISNOW:MemoryOrder = \"XY\" ;\n\t\tISNOW:description = \"\" ;\n\t\tISNOW:units = \"\" ;\n\tfloat CANLIQ(Time, south_north, west_east) ;\n\t\tCANLIQ:MemoryOrder = \"XY\" ;\n\t\tCANLIQ:description = \"\" ;\n\t\tCANLIQ:units = \"\" ;\n\tfloat CANICE(Time, south_north, west_east) ;\n\t\tCANICE:MemoryOrder = \"XY\" ;\n\t\tCANICE:description = \"\" ;\n\t\tCANICE:units = \"\" ;\n\tfloat SNEQV(Time, south_north, west_east) ;\n\t\tSNEQV:MemoryOrder = \"XY\" ;\n\t\tSNEQV:description = \"\" ;\n\t\tSNEQV:units = \"\" ;\n\tfloat SNOWH(Time, south_north, west_east) ;\n\t\tSNOWH:MemoryOrder = \"XY\" ;\n\t\tSNOWH:description = \"\" ;\n\t\tSNOWH:units = \"\" ;\n\tfloat TV(Time, south_north, west_east) ;\n\t\tTV:MemoryOrder = \"XY\" ;\n\t\tTV:description = \"\" ;\n\t\tTV:units = \"\" ;\n\tfloat TG(Time, south_north, west_east) ;\n\t\tTG:MemoryOrder = \"XY\" ;\n\t\tTG:description = \"\" ;\n\t\tTG:units = \"\" ;\n\tfloat ZWT(Time, south_north, west_east) ;\n\t\tZWT:MemoryOrder = \"XY\" ;\n\t\tZWT:description = \"\" ;\n\t\tZWT:units = \"\" ;\n\tfloat WA(Time, south_north, west_east) ;\n\t\tWA:MemoryOrder = \"XY\" ;\n\t\tWA:description = \"\" ;\n\t\tWA:units = \"\" ;\n\tfloat WT(Time, south_north, west_east) ;\n\t\tWT:MemoryOrder = \"XY\" ;\n\t\tWT:description = \"\" ;\n\t\tWT:units = \"\" ;\n\tfloat WSLAKE(Time, south_north, west_east) ;\n\t\tWSLAKE:MemoryOrder = \"XY\" ;\n\t\tWSLAKE:description = \"\" ;\n\t\tWSLAKE:units = \"\" ;\n\tfloat LFMASS(Time, south_north, west_east) ;\n\t\tLFMASS:MemoryOrder = \"XY\" ;\n\t\tLFMASS:description = \"\" ;\n\t\tLFMASS:units = \"\" ;\n\tfloat RTMASS(Time, south_north, west_east) ;\n\t\tRTMASS:MemoryOrder = \"XY\" ;\n\t\tRTMASS:description = \"\" ;\n\t\tRTMASS:units = \"\" ;\n\tfloat STMASS(Time, south_north, west_east) ;\n\t\tSTMASS:MemoryOrder = \"XY\" ;\n\t\tSTMASS:description = \"\" ;\n\t\tSTMASS:units = \"\" ;\n\tfloat WOOD(Time, south_north, west_east) ;\n\t\tWOOD:MemoryOrder = \"XY\" ;\n\t\tWOOD:description = \"\" ;\n\t\tWOOD:units = \"\" ;\n\tfloat STBLCP(Time, south_north, west_east) ;\n\t\tSTBLCP:MemoryOrder = \"XY\" ;\n\t\tSTBLCP:description = \"\" ;\n\t\tSTBLCP:units = \"\" ;\n\tfloat FASTCP(Time, south_north, west_east) ;\n\t\tFASTCP:MemoryOrder = \"XY\" ;\n\t\tFASTCP:description = \"\" ;\n\t\tFASTCP:units = \"\" ;\n\tfloat LAI(Time, south_north, west_east) ;\n\t\tLAI:MemoryOrder = \"XY\" ;\n\t\tLAI:description = \"\" ;\n\t\tLAI:units = \"\" ;\n\tfloat SAI(Time, south_north, west_east) ;\n\t\tSAI:MemoryOrder = \"XY\" ;\n\t\tSAI:description = \"\" ;\n\t\tSAI:units = \"\" ;\n\tfloat VEGFRA(Time, south_north, west_east) ;\n\t\tVEGFRA:MemoryOrder = \"XY\" ;\n\t\tVEGFRA:description = \"\" ;\n\t\tVEGFRA:units = \"\" ;\n\tfloat GVFMIN(Time, south_north, west_east) ;\n\t\tGVFMIN:MemoryOrder = \"XY\" ;\n\t\tGVFMIN:description = \"\" ;\n\t\tGVFMIN:units = \"\" ;\n\tfloat GVFMAX(Time, south_north, west_east) ;\n\t\tGVFMAX:MemoryOrder = \"XY\" ;\n\t\tGVFMAX:description = \"\" ;\n\t\tGVFMAX:units = \"\" ;\n\tfloat ACMELT(Time, south_north, west_east) ;\n\t\tACMELT:MemoryOrder = \"XY\" ;\n\t\tACMELT:description = \"\" ;\n\t\tACMELT:units = \"\" ;\n\tfloat ACSNOW(Time, south_north, west_east) ;\n\t\tACSNOW:MemoryOrder = \"XY\" ;\n\t\tACSNOW:description = \"\" ;\n\t\tACSNOW:units = \"\" ;\n\tfloat TAUSS(Time, south_north, west_east) ;\n\t\tTAUSS:MemoryOrder = \"XY\" ;\n\t\tTAUSS:description = \"\" ;\n\t\tTAUSS:units = \"\" ;\n\tfloat QSFC(Time, south_north, west_east) ;\n\t\tQSFC:MemoryOrder = \"XY\" ;\n\t\tQSFC:description = \"\" ;\n\t\tQSFC:units = \"\" ;\n\tfloat SFCRUNOFF(Time, south_north, west_east) ;\n\t\tSFCRUNOFF:MemoryOrder = \"XY\" ;\n\t\tSFCRUNOFF:description = \"\" ;\n\t\tSFCRUNOFF:units = \"\" ;\n\tfloat UDRUNOFF(Time, south_north, west_east) ;\n\t\tUDRUNOFF:MemoryOrder = \"XY\" ;\n\t\tUDRUNOFF:description = \"\" ;\n\t\tUDRUNOFF:units = \"\" ;\n\tfloat ACCPRCP(Time, south_north, west_east) ;\n\t\tACCPRCP:MemoryOrder = \"XY\" ;\n\t\tACCPRCP:description = \"\" ;\n\t\tACCPRCP:units = \"\" ;\n\tfloat ACCECAN(Time, south_north, west_east) ;\n\t\tACCECAN:MemoryOrder = \"XY\" ;\n\t\tACCECAN:description = \"\" ;\n\t\tACCECAN:units = \"\" ;\n\tfloat ACCEDIR(Time, south_north, west_east) ;\n\t\tACCEDIR:MemoryOrder = \"XY\" ;\n\t\tACCEDIR:description = \"\" ;\n\t\tACCEDIR:units = \"\" ;\n\tfloat ACCETRAN(Time, south_north, west_east) ;\n\t\tACCETRAN:MemoryOrder = \"XY\" ;\n\t\tACCETRAN:description = \"\" ;\n\t\tACCETRAN:units = \"\" ;\n\tfloat SMOISEQ(Time, south_north, soil_layers_stag, west_east) ;\n\t\tSMOISEQ:MemoryOrder = \"XZY\" ;\n\t\tSMOISEQ:description = \"\" ;\n\t\tSMOISEQ:units = \"\" ;\n\tfloat AREAXY(Time, south_north, west_east) ;\n\t\tAREAXY:MemoryOrder = \"XY\" ;\n\t\tAREAXY:description = \"\" ;\n\t\tAREAXY:units = \"\" ;\n\tfloat SMCWTDXY(Time, south_north, west_east) ;\n\t\tSMCWTDXY:MemoryOrder = \"XY\" ;\n\t\tSMCWTDXY:description = \"\" ;\n\t\tSMCWTDXY:units = \"\" ;\n\tfloat DEEPRECHXY(Time, south_north, west_east) ;\n\t\tDEEPRECHXY:MemoryOrder = \"XY\" ;\n\t\tDEEPRECHXY:description = \"\" ;\n\t\tDEEPRECHXY:units = \"\" ;\n\tfloat QSLATXY(Time, south_north, west_east) ;\n\t\tQSLATXY:MemoryOrder = \"XY\" ;\n\t\tQSLATXY:description = \"\" ;\n\t\tQSLATXY:units = \"\" ;\n\tfloat QRFSXY(Time, south_north, west_east) ;\n\t\tQRFSXY:MemoryOrder = \"XY\" ;\n\t\tQRFSXY:description = \"\" ;\n\t\tQRFSXY:units = \"\" ;\n\tfloat QSPRINGSXY(Time, south_north, west_east) ;\n\t\tQSPRINGSXY:MemoryOrder = \"XY\" ;\n\t\tQSPRINGSXY:description = \"\" ;\n\t\tQSPRINGSXY:units = \"\" ;\n\tfloat RECHXY(Time, south_north, west_east) ;\n\t\tRECHXY:MemoryOrder = \"XY\" ;\n\t\tRECHXY:description = \"\" ;\n\t\tRECHXY:units = \"\" ;\n\tfloat QRFXY(Time, south_north, west_east) ;\n\t\tQRFXY:MemoryOrder = \"XY\" ;\n\t\tQRFXY:description = \"\" ;\n\t\tQRFXY:units = \"\" ;\n\tfloat QSPRINGXY(Time, south_north, west_east) ;\n\t\tQSPRINGXY:MemoryOrder = \"XY\" ;\n\t\tQSPRINGXY:description = \"\" ;\n\t\tQSPRINGXY:units = \"\" ;\n\tfloat FDEPTHXY(Time, south_north, west_east) ;\n\t\tFDEPTHXY:MemoryOrder = \"XY\" ;\n\t\tFDEPTHXY:description = \"\" ;\n\t\tFDEPTHXY:units = \"\" ;\n\tfloat RIVERCONDXY(Time, south_north, west_east) ;\n\t\tRIVERCONDXY:MemoryOrder = \"XY\" ;\n\t\tRIVERCONDXY:description = \"\" ;\n\t\tRIVERCONDXY:units = \"\" ;\n\tfloat RIVERBEDXY(Time, south_north, west_east) ;\n\t\tRIVERBEDXY:MemoryOrder = \"XY\" ;\n\t\tRIVERBEDXY:description = \"\" ;\n\t\tRIVERBEDXY:units = \"\" ;\n\tfloat EQZWT(Time, south_north, west_east) ;\n\t\tEQZWT:MemoryOrder = \"XY\" ;\n\t\tEQZWT:description = \"\" ;\n\t\tEQZWT:units = \"\" ;\n\tfloat PEXPXY(Time, south_north, west_east) ;\n\t\tPEXPXY:MemoryOrder = \"XY\" ;\n\t\tPEXPXY:description = \"\" ;\n\t\tPEXPXY:units = \"\" ;\n\n// global attributes:\n\t\t:TITLE = \"RESTART FILE FROM HRLDAS v20150506\" ;\n\t\t:missing_value = -1.e+33f ;\n\t\t:START_DATE = \"2011-07-01_00:00:00\" ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:LAT1 = 41.42281f ;\n\t\t:LON1 = -73.85333f ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:MMINLU = \"USGS\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/RESTART/RESTART.2011082600_DOMAIN1.md5",
    "content": "0a1e9461016ebb1d301873c65ee6070a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/RESTART/RESTART.2011082600_DOMAIN1\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/RESTART/nudgingLastObs.2011-08-26_00:00:00.cdl",
    "content": "netcdf nudgingLastObs.2011-08-26_00\\:00\\:00 {\ndimensions:\n\ttimeStrLen = 19 ;\n\ttimeInd = 480 ;\n\tstationIdStrLen = 15 ;\n\tstationIdInd = UNLIMITED ; // (4 currently)\n\tfeature_id = 185 ;\nvariables:\n\tchar stationId(stationIdInd, stationIdStrLen) ;\n\t\tstationId:long_name = \"USGS station identifer of length 15\" ;\n\tchar time(stationIdInd, timeInd, timeStrLen) ;\n\t\ttime:units = \"UTC\" ;\n\t\ttime:long_name = \"YYYY-mm-dd_HH:MM:SS UTC\" ;\n\tfloat discharge(stationIdInd, timeInd) ;\n\t\tdischarge:units = \"m^3/s\" ;\n\t\tdischarge:long_name = \"Discharge.cubic_meters_per_second\" ;\n\tfloat model_discharge(stationIdInd, timeInd) ;\n\t\tmodel_discharge:units = \"m^3/s\" ;\n\t\tmodel_discharge:long_name = \"modelDischarge.cubic_meters_per_second\" ;\n\tshort discharge_quality(stationIdInd, timeInd) ;\n\t\tdischarge_quality:units = \"-\" ;\n\t\tdischarge_quality:long_name = \"Discharge quality 0 to 100 to be scaled by 100.\" ;\n\tfloat nudge(feature_id) ;\n\t\tnudge:units = \"m3 s-1\" ;\n\t\tnudge:long_name = \"Amount of stream flow alteration\" ;\n\n// global attributes:\n\t\t:modelTimeAtOutput = \"2011-08-26_00:00:00\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/RESTART/nudgingLastObs.2011-08-26_00:00:00.md5",
    "content": "f9423c42a02ebfb3535e5a1049d7a800  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/RESTART/nudgingLastObs.2011-08-26_00:00:00.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/NWM/nudgingTimeSliceObs.md5",
    "content": "383e7f5fbdbb1a9aaabb6bb2041a001d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_05:00:00.15min.usgsTimeSlice.ncdf\nb62f1271a6856fdbd0dca17f549f39bc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_05:15:00.15min.usgsTimeSlice.ncdf\nf442dc2ecc51b43dfc21e8dffbcbf3ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_05:30:00.15min.usgsTimeSlice.ncdf\nc0bb2841417566fa310daa08afcd03f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_05:45:00.15min.usgsTimeSlice.ncdf\n11b6e7ad442e41442b2e0f581025992b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_06:00:00.15min.usgsTimeSlice.ncdf\nc9e965710a1b6b4df10f633dd84b89d8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_06:15:00.15min.usgsTimeSlice.ncdf\nc6f113b873ba486d8dcea44e477051e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_06:30:00.15min.usgsTimeSlice.ncdf\n29e01cc9d39ff53140fa2ffd3b72f221  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_06:45:00.15min.usgsTimeSlice.ncdf\n6e3f1934a8252479b86b6f26cc7b5a99  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_07:00:00.15min.usgsTimeSlice.ncdf\n4b51e83ef8352ff7aa2ea18e75cfb449  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_07:15:00.15min.usgsTimeSlice.ncdf\nee6112b0829f11344edc3080cea0cf8b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_07:30:00.15min.usgsTimeSlice.ncdf\n50d113ee7b0e09966efa1b972d795b1a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_07:45:00.15min.usgsTimeSlice.ncdf\n4f2bd7eff1a8a9aab5ee5b380cfc207e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_08:00:00.15min.usgsTimeSlice.ncdf\n9c2acc7b97b4cb254fd9cb998336e79a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_08:15:00.15min.usgsTimeSlice.ncdf\n41bb410e4640d42421ef11542613e645  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_08:30:00.15min.usgsTimeSlice.ncdf\n0364a0284810b2ecb5363caba4957c52  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_08:45:00.15min.usgsTimeSlice.ncdf\n42031dd41473083cfe0cc461f3726236  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_09:00:00.15min.usgsTimeSlice.ncdf\n2b6bccd5152c986bc6533b0afebb6b50  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_09:15:00.15min.usgsTimeSlice.ncdf\n03597afb65d09161b443e26accb319d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_09:30:00.15min.usgsTimeSlice.ncdf\n7f8847a1849e803aebce493e08835ca3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_09:45:00.15min.usgsTimeSlice.ncdf\n0983a3fe871a924f47cd1feaa78c6dfd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_10:00:00.15min.usgsTimeSlice.ncdf\nb374c15336501680fbc54f4b62fb301e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_10:15:00.15min.usgsTimeSlice.ncdf\n948396b32bd855fd7393e81f54fb4edf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_10:30:00.15min.usgsTimeSlice.ncdf\n34ad4323b27d81d36834e71945c8d5bf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_10:45:00.15min.usgsTimeSlice.ncdf\n242820203a835ce8ee2ce47f65257b59  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_11:00:00.15min.usgsTimeSlice.ncdf\n47fd6875e47094b4751e8c051b78cd2c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_11:15:00.15min.usgsTimeSlice.ncdf\nb45017b2d98d757f579aee5625bdb04f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_11:30:00.15min.usgsTimeSlice.ncdf\n2b6b6e35700475bc774ea66a09fd9b56  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_11:45:00.15min.usgsTimeSlice.ncdf\n6f3080735ed898fea4dc6fc38e400c6d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_12:00:00.15min.usgsTimeSlice.ncdf\n14b745d705bb17e445be2eba0a365649  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_12:15:00.15min.usgsTimeSlice.ncdf\n3b56d3705fd414ed4d54e3143ea62aa8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_12:30:00.15min.usgsTimeSlice.ncdf\n720e09a7a19c09a8acb8f122a3610b68  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_12:45:00.15min.usgsTimeSlice.ncdf\naecb9d0ea55e209cc30515c5bf3ceef1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_13:00:00.15min.usgsTimeSlice.ncdf\n55e8a3492105c4246c8321f1bec068db  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_13:15:00.15min.usgsTimeSlice.ncdf\n9de7858bbc26f9007301df44f6c28bf1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_13:30:00.15min.usgsTimeSlice.ncdf\na338f27330aaca521a53c92bec9a9b27  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_13:45:00.15min.usgsTimeSlice.ncdf\ne57a80d0f898e6bd5c5c04415cbf51c4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_14:00:00.15min.usgsTimeSlice.ncdf\n92334ca874fbcafef1239ec4cb724e71  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_14:15:00.15min.usgsTimeSlice.ncdf\n30807ed02f69197427b8f52bdf4051b5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_14:30:00.15min.usgsTimeSlice.ncdf\n0082dd4819b5ffea7b9a06c60e06a5ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_14:45:00.15min.usgsTimeSlice.ncdf\n47bdc0ca5f68578dfa81bce224d3893f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_15:00:00.15min.usgsTimeSlice.ncdf\nd395cd2ad3b3624e1cf4e5b8820f6e7a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_15:15:00.15min.usgsTimeSlice.ncdf\nc6b2675d76bd52f22a40e7f4b98e9f8f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_15:30:00.15min.usgsTimeSlice.ncdf\n859461eb37f4b9fdca66b22efd394e20  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_15:45:00.15min.usgsTimeSlice.ncdf\n0beafd1f973ebd305ffe3ebbaf5fb724  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_16:00:00.15min.usgsTimeSlice.ncdf\n40189406e839d545b82ff43ca53b1e36  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_16:15:00.15min.usgsTimeSlice.ncdf\n3191b16ce03698040f26f7cc6a436eab  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_16:30:00.15min.usgsTimeSlice.ncdf\nb893769092eabbc43b17eaca1baf8679  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_16:45:00.15min.usgsTimeSlice.ncdf\n38710c3676a8c4c7d5a9f2de69777cbc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_17:00:00.15min.usgsTimeSlice.ncdf\n1430efbbb5b5d5a00d5ed8c3e1aba572  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_17:15:00.15min.usgsTimeSlice.ncdf\nf8dcf2e293cbc3e607cd53b80dda3009  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_17:30:00.15min.usgsTimeSlice.ncdf\n8212b54db0ad0ac268293e236900f03a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_17:45:00.15min.usgsTimeSlice.ncdf\nbc0819a4fa922e0d2f8aa0b3eb283f8b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_18:00:00.15min.usgsTimeSlice.ncdf\n7444b951ea1bb5ef242380ea6a06889f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_18:15:00.15min.usgsTimeSlice.ncdf\n60b188ca64eee557eb992bd3c478598c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_18:30:00.15min.usgsTimeSlice.ncdf\n8247e7d9284ee7c3d9cdd43e1b27d949  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_18:45:00.15min.usgsTimeSlice.ncdf\n4f418150ff3beee32081124aabfd1898  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_19:00:00.15min.usgsTimeSlice.ncdf\n452106dd1f6b4e1bdcdce8127edcc376  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_19:15:00.15min.usgsTimeSlice.ncdf\n5e8cd87a11ed97a15e06e0612460f5e9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_19:30:00.15min.usgsTimeSlice.ncdf\nbe08a323e181f2b7cfc8332be5a6c955  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_19:45:00.15min.usgsTimeSlice.ncdf\n3e5dc0904f2511b088c623f8631064a2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_20:00:00.15min.usgsTimeSlice.ncdf\nc96c90732b1b15c780ea36b43365cbad  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_20:15:00.15min.usgsTimeSlice.ncdf\n8af8885d4c3804f19a9aba9cd42926a3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_20:30:00.15min.usgsTimeSlice.ncdf\n1936bbc3b291f00a2bdb72feb8c8b223  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_20:45:00.15min.usgsTimeSlice.ncdf\n7dd7634f19f141234b2140c56f6e149e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_21:00:00.15min.usgsTimeSlice.ncdf\n38860512a9def8fe515c65a45d01b0cd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_21:15:00.15min.usgsTimeSlice.ncdf\n77589cafd7641857292987eb35e6c271  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_21:30:00.15min.usgsTimeSlice.ncdf\n1ec1f20805f8ed4471d948435a730328  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_21:45:00.15min.usgsTimeSlice.ncdf\n7fcd4ed28f83d6f341d797f2b55f2770  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_22:00:00.15min.usgsTimeSlice.ncdf\nd9f223849efb9f223241c27b943cfb92  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_22:15:00.15min.usgsTimeSlice.ncdf\nbf4cd6c7992e6d23239a37cd673ac86c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_22:30:00.15min.usgsTimeSlice.ncdf\n3e2070edcec4c01831e2a73bf7ec6a9f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_22:45:00.15min.usgsTimeSlice.ncdf\n6c297a99c6fea5043b66b46fa086c8a6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_23:00:00.15min.usgsTimeSlice.ncdf\n84ff9dcf9c61d1e46060486cd270241c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_23:15:00.15min.usgsTimeSlice.ncdf\n24640924b4663c0db07c402a505f561e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_23:30:00.15min.usgsTimeSlice.ncdf\n4d7005ed218a4c2cd54ac2e5a41bbad5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_23:45:00.15min.usgsTimeSlice.ncdf\ncd801fa8a0cfb650c3e5227a34544fd6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_00:00:00.15min.usgsTimeSlice.ncdf\n4ef6dae0ca1e9c1e4ffd8bb7de7ea3fa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_00:15:00.15min.usgsTimeSlice.ncdf\n85db87619a3902e084ba2edc5a57f09b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_00:30:00.15min.usgsTimeSlice.ncdf\n55ced80797d56ce6ab7a1f4266c9fc07  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_00:45:00.15min.usgsTimeSlice.ncdf\nb76585946bc68ccdad6efcee3ff3065d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_01:00:00.15min.usgsTimeSlice.ncdf\na1ec8daa852547d97bba2c66064dbd21  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_01:15:00.15min.usgsTimeSlice.ncdf\naa4fb37362ec120f933022f95cb99f6e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_01:30:00.15min.usgsTimeSlice.ncdf\n36672f0c276e9fe895fcc2d0e85655e7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_01:45:00.15min.usgsTimeSlice.ncdf\n759212084b9a80802f4d1ad50650c4ee  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_02:00:00.15min.usgsTimeSlice.ncdf\n27dce9032343c218a61946d1f9092e44  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_02:15:00.15min.usgsTimeSlice.ncdf\n25a298ecaacd528b861384ae3da091b2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_02:30:00.15min.usgsTimeSlice.ncdf\n956187776d82fc36ea7771bb80299169  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_02:45:00.15min.usgsTimeSlice.ncdf\n6025045092c5526f2a4772fd289f1c78  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_03:00:00.15min.usgsTimeSlice.ncdf\n02ef1951a8310b24a8ceaf23fce89df4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_03:15:00.15min.usgsTimeSlice.ncdf\n7c0f358698f0d43d3575eb315282f2f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_03:30:00.15min.usgsTimeSlice.ncdf\n80de472b55a5ccde291058c6f66e63ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_03:45:00.15min.usgsTimeSlice.ncdf\nf5892f7c1fc96caa536b3c22f61bde53  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_04:00:00.15min.usgsTimeSlice.ncdf\n291dd1bddfdd290c6a24224ba3cd60e7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_04:15:00.15min.usgsTimeSlice.ncdf\n649f71abff71f99a1ed85b0410c047c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_04:30:00.15min.usgsTimeSlice.ncdf\n1aad16156487ba6e59233b5755722c60  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_04:45:00.15min.usgsTimeSlice.ncdf\nce627d788c5ec937da27fe140eb6a634  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_05:00:00.15min.usgsTimeSlice.ncdf\n371b53ae3b0a9a4ef2336c6e5435c836  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_05:15:00.15min.usgsTimeSlice.ncdf\nff42aab9aae162225b154b51620671b0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_05:30:00.15min.usgsTimeSlice.ncdf\ne567a57aa20ad0417e0eaf7c0e44020d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_05:45:00.15min.usgsTimeSlice.ncdf\nc34f74697e4c4bf995bafcd4850456f0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_06:00:00.15min.usgsTimeSlice.ncdf\n7fd7a7014f7fe1ebe517f0314b974acf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_06:15:00.15min.usgsTimeSlice.ncdf\n3fe6cd3a2cd5006bf29b88c00226cda2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_06:30:00.15min.usgsTimeSlice.ncdf\n83247f6b46179daea71796209e30c932  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_06:45:00.15min.usgsTimeSlice.ncdf\ndfee95d270c03b72d3b573dc6cb1965c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_07:00:00.15min.usgsTimeSlice.ncdf\n2cc882dc933800b4fb9198b82ef3bc35  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_07:15:00.15min.usgsTimeSlice.ncdf\n978503eba24aaeae394eca79b444605d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_07:30:00.15min.usgsTimeSlice.ncdf\n870c8db8269b5cc8fcaec3d35467d99b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_07:45:00.15min.usgsTimeSlice.ncdf\n7bf558912833299b66bd1e2e723eef70  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_08:00:00.15min.usgsTimeSlice.ncdf\nd02972d1c351b0d0d7f163912f69950c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_08:15:00.15min.usgsTimeSlice.ncdf\nfc28983a13e0c2ff3463419c127b0740  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_08:30:00.15min.usgsTimeSlice.ncdf\n533617e03ce4a359562fd431f63ff0a4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_08:45:00.15min.usgsTimeSlice.ncdf\n7c0afde8242de56794365ac448d27128  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_09:00:00.15min.usgsTimeSlice.ncdf\nc3471155dd02d9cf795be4ab876fe204  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_09:15:00.15min.usgsTimeSlice.ncdf\nf040935c465b48a9c27822af48b49730  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_09:30:00.15min.usgsTimeSlice.ncdf\n70c9ea506dec4f6212609374081f3779  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_09:45:00.15min.usgsTimeSlice.ncdf\n6082dc86186b6f6422ff7345d2d84d5d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_10:00:00.15min.usgsTimeSlice.ncdf\n999e7d4b795610e8afa37860d2f358ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_10:15:00.15min.usgsTimeSlice.ncdf\n8cf018b77cb0e364eba2c6b7c6ff8e5e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_10:30:00.15min.usgsTimeSlice.ncdf\ne4dfe29158dda254ca3aa3c308bff2f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_10:45:00.15min.usgsTimeSlice.ncdf\n66754c464046ea2168fb7169a43344dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_11:00:00.15min.usgsTimeSlice.ncdf\n4e6a5b1ff3c9b5d4a67acf3f6d800e66  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_11:15:00.15min.usgsTimeSlice.ncdf\na914758415d4ed7a885412a73ace4895  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_11:30:00.15min.usgsTimeSlice.ncdf\n5d821ed7d647c820a0d30cbd7ce97c73  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_11:45:00.15min.usgsTimeSlice.ncdf\n2c56d4535cdb28af2153152f60577bf8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_12:00:00.15min.usgsTimeSlice.ncdf\nee6c0f4a7ada8be5009e9c6d74f1cbc0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_12:15:00.15min.usgsTimeSlice.ncdf\n18312bd0201f36a687e6e2b605bfe90e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_12:30:00.15min.usgsTimeSlice.ncdf\n7d58c16d483afeb219cd27c86a4105cc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_12:45:00.15min.usgsTimeSlice.ncdf\n00a0cd89f35de38942f1fd2cbac9109d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_13:00:00.15min.usgsTimeSlice.ncdf\n87c2eb9ef0116301486424dea4a43316  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_13:15:00.15min.usgsTimeSlice.ncdf\n0c533d18c40bda3b2a91b1343485e170  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_13:30:00.15min.usgsTimeSlice.ncdf\nb8d1bfa60b81cdc99f0231f19309995e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_13:45:00.15min.usgsTimeSlice.ncdf\n7cfa2b9ef2fb6cfa7212a02e729ed5c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_14:00:00.15min.usgsTimeSlice.ncdf\n852c0482000a922b69cde63023b78e8d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_14:15:00.15min.usgsTimeSlice.ncdf\n258cd8654dae33de56fb51d4a78ebe56  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_14:30:00.15min.usgsTimeSlice.ncdf\n146f523f8aa388c94d067913abd05788  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_14:45:00.15min.usgsTimeSlice.ncdf\n1783be9de34003758d425521e59803f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_15:00:00.15min.usgsTimeSlice.ncdf\n3d802a75ac44cef79c95e6b0d03125ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_15:15:00.15min.usgsTimeSlice.ncdf\n1982c52ad9cbe06910fc8f27109cfccd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_15:30:00.15min.usgsTimeSlice.ncdf\nd1fe50c28d173912efe6f21728d40370  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_15:45:00.15min.usgsTimeSlice.ncdf\n14cf1a4a600be69b70a60efb0c5087b2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_16:00:00.15min.usgsTimeSlice.ncdf\nb489d17c7f8ce561e1f44dbecb37449b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_16:15:00.15min.usgsTimeSlice.ncdf\ncff9016480e4d0ee5e994222d3fa2a1e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_16:30:00.15min.usgsTimeSlice.ncdf\nc21c2ec7ba2301fcab4d0bc543c3545a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_16:45:00.15min.usgsTimeSlice.ncdf\nf575bc5c42c663a285cf2c9dbd302fe5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_17:00:00.15min.usgsTimeSlice.ncdf\n81de530fc285156428951d8bf9b540bf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_17:15:00.15min.usgsTimeSlice.ncdf\na80ff90d67267dde8e9c1b86eb38b92a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_17:30:00.15min.usgsTimeSlice.ncdf\n1b2ea2bbeaa28d5d9731decc220b3002  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_17:45:00.15min.usgsTimeSlice.ncdf\na85e77d76e4b6efcabdf9d37de39d8f7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_18:00:00.15min.usgsTimeSlice.ncdf\nd1507b86404b4a12f81ab208a704b588  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_18:15:00.15min.usgsTimeSlice.ncdf\naf9172cd8e9a95f1f2a67ff9160577e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_18:30:00.15min.usgsTimeSlice.ncdf\n8d5f8e428811b6c15488b744080b9404  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_18:45:00.15min.usgsTimeSlice.ncdf\na5c4c805f42ed91fb8c20241d86ab458  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_19:00:00.15min.usgsTimeSlice.ncdf\nd0b41eca55a02601a367d30666fd6521  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_19:15:00.15min.usgsTimeSlice.ncdf\nd5f315c73f7581d5c7ac83bf4004d5dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_19:30:00.15min.usgsTimeSlice.ncdf\n1a680100760b41e542f9c112e1e186d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_19:45:00.15min.usgsTimeSlice.ncdf\nd194c0905266944cda5005b8f69e520c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_20:00:00.15min.usgsTimeSlice.ncdf\nc675ee4fcd3f5dfa9e0b059478e489fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_20:15:00.15min.usgsTimeSlice.ncdf\n797a55e0ecb905e3d01b7a1a9231ced3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_20:30:00.15min.usgsTimeSlice.ncdf\nc9fca2452c92f35a2d8b2fb3afd9da93  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_20:45:00.15min.usgsTimeSlice.ncdf\n135681089d34311b796494fc1d342668  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_21:00:00.15min.usgsTimeSlice.ncdf\nfe8682f782fc0ae868b9d4b6057053df  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_21:15:00.15min.usgsTimeSlice.ncdf\ncb09a4ab060881344c153b27fd8388f7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_21:30:00.15min.usgsTimeSlice.ncdf\nd562ec5d714bc663558aba9656c55697  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_21:45:00.15min.usgsTimeSlice.ncdf\ned99be7259942eb282935719b2c33b67  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_22:00:00.15min.usgsTimeSlice.ncdf\nfcc5c6f4bc322c17c20d8ec1f58899aa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_22:15:00.15min.usgsTimeSlice.ncdf\n13ea8197d5e8f66e85ab75ee7c703ec1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_22:30:00.15min.usgsTimeSlice.ncdf\n690d3b25c9fc6cee804bb2d2389a34b8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_22:45:00.15min.usgsTimeSlice.ncdf\nb110458ad61c65f96b5ddf6a997d2cd9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_23:00:00.15min.usgsTimeSlice.ncdf\n5f3080e78e48567cc969c62a5988dd1b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_23:15:00.15min.usgsTimeSlice.ncdf\n2130cb13810a77a1c401d960921b5815  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_23:30:00.15min.usgsTimeSlice.ncdf\n427e4fa743b381af09c3ae2737b5fa2a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_23:45:00.15min.usgsTimeSlice.ncdf\n9cc349a8aede24796e3d53b83d293a05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_00:00:00.15min.usgsTimeSlice.ncdf\n5f7cfddf97ccc2721e3519dbda04883b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_00:15:00.15min.usgsTimeSlice.ncdf\ndd58af95f637935b91c119421a309055  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_00:30:00.15min.usgsTimeSlice.ncdf\ne6bb1afd9f8165768a21257dbee60e8a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_00:45:00.15min.usgsTimeSlice.ncdf\n10a9a466f86dcddbb3d08057a4d3e05c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_01:00:00.15min.usgsTimeSlice.ncdf\n76b87ee8a61cb942d85b351001535098  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_01:15:00.15min.usgsTimeSlice.ncdf\n0099cc4d22ac00156244f080f2256ed0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_01:30:00.15min.usgsTimeSlice.ncdf\n82d97d104b3fb6e7415052d3710bac79  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_01:45:00.15min.usgsTimeSlice.ncdf\n806118efe4f82f5f4ed1ee96d3b5d446  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_02:00:00.15min.usgsTimeSlice.ncdf\nc05e3f157242e0cfb21b7c02686406fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_02:15:00.15min.usgsTimeSlice.ncdf\na0337b4ce832525e8dfe30f3cd2410dc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_02:30:00.15min.usgsTimeSlice.ncdf\ndb50d1673882ab0fe253f2aa2e652429  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_02:45:00.15min.usgsTimeSlice.ncdf\n286b78281f476724f97f037e883d5f7e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_03:00:00.15min.usgsTimeSlice.ncdf\n49d7a3bc6bac22c8dcc0f4acc420bf9e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_03:15:00.15min.usgsTimeSlice.ncdf\ncc874261d1b89123fc7e79eeb13ab141  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_03:30:00.15min.usgsTimeSlice.ncdf\n3c5721468c8e961ab285cae75ee690ce  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_03:45:00.15min.usgsTimeSlice.ncdf\nc90a42320e9c5dba5a16966ffba122dc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_04:00:00.15min.usgsTimeSlice.ncdf\n0d14f7fbaae069d0f6b112872d609f86  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_04:15:00.15min.usgsTimeSlice.ncdf\n1cb94ab8943948553ff85528c8ab071a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_04:30:00.15min.usgsTimeSlice.ncdf\n63307ce2a1985139292c6e5727eec027  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_04:45:00.15min.usgsTimeSlice.ncdf\n6ccc9c3659399b722b180444e3ad215f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_05:00:00.15min.usgsTimeSlice.ncdf\nc760ccad252eae7d67951b1c418d2af3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_05:15:00.15min.usgsTimeSlice.ncdf\nae2665152935169192bf96bd28ba1797  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_05:30:00.15min.usgsTimeSlice.ncdf\n156003a42ed40cfdc125fc9324977b06  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_05:45:00.15min.usgsTimeSlice.ncdf\n175e2e66c1e675f72aa7316c0d726b92  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_06:00:00.15min.usgsTimeSlice.ncdf\nab78a9d79f99961523da095b9f0cacb7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_06:15:00.15min.usgsTimeSlice.ncdf\n1c9cfe3d217c61e7184a7f420705fa12  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_06:30:00.15min.usgsTimeSlice.ncdf\nbf6e49851b481ded70e65d3a48aae7b7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_06:45:00.15min.usgsTimeSlice.ncdf\n858fcff5f162ee709a884f1dc7346e83  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_07:00:00.15min.usgsTimeSlice.ncdf\n72710d89aef091f219a403a3fe2fc411  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_07:15:00.15min.usgsTimeSlice.ncdf\n62031549bd705c45629e345a9ff853be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_07:30:00.15min.usgsTimeSlice.ncdf\ne50c08df9966c12d571b0cf4f7010048  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_07:45:00.15min.usgsTimeSlice.ncdf\n578a67618afe89098f1f2941b41c5157  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_08:00:00.15min.usgsTimeSlice.ncdf\nc957840e8d184686f586f5092c2402c8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_08:15:00.15min.usgsTimeSlice.ncdf\nfbf693e3c24a9e67198d81535d4107e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_08:30:00.15min.usgsTimeSlice.ncdf\neb7057217ea5608375cc5d215d6978c1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_08:45:00.15min.usgsTimeSlice.ncdf\n5391faa1c3f2164fe5c2abb24cc62c83  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_09:00:00.15min.usgsTimeSlice.ncdf\n784b086dd2bbda76cb3eaa207abb04e3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_09:15:00.15min.usgsTimeSlice.ncdf\n061abf3937ebccc3e86591d43cfef709  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_09:30:00.15min.usgsTimeSlice.ncdf\n20c3a7fcf9f94f45f051dceee21ae505  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_09:45:00.15min.usgsTimeSlice.ncdf\n47e06a186e7dbd08b8bea36d82bb239b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_10:00:00.15min.usgsTimeSlice.ncdf\nc12b2746a6f9a2dc93dc9a6132cb5927  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_10:15:00.15min.usgsTimeSlice.ncdf\n339bf91bf21e5ccdd040eff075811494  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_10:30:00.15min.usgsTimeSlice.ncdf\n61a17ce9e6b20ebc637f7bb2f020f6d1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_10:45:00.15min.usgsTimeSlice.ncdf\n58dda52ae687974aa64236b96162f298  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_11:00:00.15min.usgsTimeSlice.ncdf\nd372d3ae525d07ec8dfd07a2d24705fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_11:15:00.15min.usgsTimeSlice.ncdf\ndf26b106fed5a37e253f6394f1cbbf5e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_11:30:00.15min.usgsTimeSlice.ncdf\n23614e69521bc9e49099a34a8335b7c0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_11:45:00.15min.usgsTimeSlice.ncdf\n11d82095ba11d718a28d5a2cd88a11ee  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_12:00:00.15min.usgsTimeSlice.ncdf\n7096918abaf22b18246c208839731696  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_12:15:00.15min.usgsTimeSlice.ncdf\nee24c5b495387054fa04141a48eef999  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_12:30:00.15min.usgsTimeSlice.ncdf\nb1ef0f68d309a902c022e056ea4eed31  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_12:45:00.15min.usgsTimeSlice.ncdf\ncf8a42abd0061320039a1b33999644d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_13:00:00.15min.usgsTimeSlice.ncdf\ne359c029a10087090868833b6636c2bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_13:15:00.15min.usgsTimeSlice.ncdf\nbd3fc1fbebc69345b0188a1e6a75d0ce  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_13:30:00.15min.usgsTimeSlice.ncdf\nee1ba2e590c4eebe86b16374341df9b7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_13:45:00.15min.usgsTimeSlice.ncdf\n8395013b1ad1048b0616d02ba8878e7b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_14:00:00.15min.usgsTimeSlice.ncdf\ne9c8935fa85082ba5d0c89ffbef6adb5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_14:15:00.15min.usgsTimeSlice.ncdf\n3ff750e0df0232a292d066f998586c6c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_14:30:00.15min.usgsTimeSlice.ncdf\ndfb70e96abf84ed6303b0759f27948ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_14:45:00.15min.usgsTimeSlice.ncdf\n32f313d0ed7f4658520796a04f12e5ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_15:00:00.15min.usgsTimeSlice.ncdf\na234bcb8e48b28d7ff69a9d38f2e0757  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_15:15:00.15min.usgsTimeSlice.ncdf\n50c90e1030d94c6c88ae09e71f27899a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_15:30:00.15min.usgsTimeSlice.ncdf\n4ff3013935544c9d39a8fa91fc583bcf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_15:45:00.15min.usgsTimeSlice.ncdf\nbf662da762fa20d6a5b84b650de5e133  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_16:00:00.15min.usgsTimeSlice.ncdf\nd69527eea695a2cdccadac24a55d74dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_16:15:00.15min.usgsTimeSlice.ncdf\n85fddceca9229e32cdd6ebef91205110  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_16:30:00.15min.usgsTimeSlice.ncdf\nd8b65389ed286b29ee9337dcf289df61  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_16:45:00.15min.usgsTimeSlice.ncdf\ncea0526c78280f39b569dd30dae3772a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_17:00:00.15min.usgsTimeSlice.ncdf\n35eae5e431203bdc8142e0ef79586948  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_17:15:00.15min.usgsTimeSlice.ncdf\n3f189ed6b6a160f8000e737f067ea61a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_17:30:00.15min.usgsTimeSlice.ncdf\n419ed80f167e271f53f8609d96a59604  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_17:45:00.15min.usgsTimeSlice.ncdf\n794ae8218a3489a971f42847f3ca2353  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_18:00:00.15min.usgsTimeSlice.ncdf\n2833b6874bfa83041e8357158c85de38  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_18:15:00.15min.usgsTimeSlice.ncdf\nbf7c99b175ea67d121fb3e0cb278a3d8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_18:30:00.15min.usgsTimeSlice.ncdf\n6946470a8b308e45750122555799205e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_18:45:00.15min.usgsTimeSlice.ncdf\nfb7793418589dfe46973bffd273e4e88  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_19:00:00.15min.usgsTimeSlice.ncdf\n963e0a58b0f9fb99953873505621e0a0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_19:15:00.15min.usgsTimeSlice.ncdf\nd833c377b91ac4bb4cedde3f145617cd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_19:30:00.15min.usgsTimeSlice.ncdf\nc35ccb1d4ca497a007e03a093a96e316  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_19:45:00.15min.usgsTimeSlice.ncdf\n4c1c3d99e09eb9f2d1d6dee6f2c35dd7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_20:00:00.15min.usgsTimeSlice.ncdf\n52b19566ed25b38ed84272dbe65881bb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_20:15:00.15min.usgsTimeSlice.ncdf\nbf29b14c975175bfb57bf470ebf8cb0d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_20:30:00.15min.usgsTimeSlice.ncdf\n3861056cf44123936af1579e39dac3e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_20:45:00.15min.usgsTimeSlice.ncdf\n57f4da883ce80fb437d2508e445240d8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_21:00:00.15min.usgsTimeSlice.ncdf\n3ba4d149c3406d0064f192e4239971be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_21:15:00.15min.usgsTimeSlice.ncdf\n7d75717b0ecbb1eccfe75204c2ed013f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_21:30:00.15min.usgsTimeSlice.ncdf\n06c78eee47299870f7888bf1a0356a15  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_21:45:00.15min.usgsTimeSlice.ncdf\n4d95c0acaa08f3a8885f318d2c1a1e89  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_22:00:00.15min.usgsTimeSlice.ncdf\n2744fbca5e677026480c4af5a542e351  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_22:15:00.15min.usgsTimeSlice.ncdf\nd3b2179518c44ef2c477adbcfb63c8b6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_22:30:00.15min.usgsTimeSlice.ncdf\nb756f5c503be1dacf3d922970ac8aff5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_22:45:00.15min.usgsTimeSlice.ncdf\n21688e1485c3bdbb02a80b6c1d139dce  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_23:00:00.15min.usgsTimeSlice.ncdf\n62a6ffcedac8daba49a7ff3098fd5458  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_23:15:00.15min.usgsTimeSlice.ncdf\nfa096b1d877351f03cb44be7ee20f6d6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_23:30:00.15min.usgsTimeSlice.ncdf\nbb14d23151dfccee470a549e1c31e10b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_23:45:00.15min.usgsTimeSlice.ncdf\nbb9c3e9ea82edb787d4b40978807d8dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_00:00:00.15min.usgsTimeSlice.ncdf\nda0fdafb056caf6eefc44bcd9be54ca8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_00:15:00.15min.usgsTimeSlice.ncdf\nc0b5146137bba9de76d820bdb9c84663  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_00:30:00.15min.usgsTimeSlice.ncdf\n5beadb65d9f45f5c5cd1bf1dd6db5756  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_00:45:00.15min.usgsTimeSlice.ncdf\n746bbc9a12b83f55b5aabde57bbd93f5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_01:00:00.15min.usgsTimeSlice.ncdf\n1bea98afb1896917453d7053ef5c5181  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_01:15:00.15min.usgsTimeSlice.ncdf\ne6cc8c43ae4e257c5c56badcc7068814  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_01:30:00.15min.usgsTimeSlice.ncdf\nbfced8169fc66c864104ac06e1530c7b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_01:45:00.15min.usgsTimeSlice.ncdf\n554051a0d92b170c14bce3c6d8a5a97c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_02:00:00.15min.usgsTimeSlice.ncdf\nec1cb1d9ce406076d072f658da86e9f9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_02:15:00.15min.usgsTimeSlice.ncdf\nf47d1b45611782990bff92bb0214f89a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_02:30:00.15min.usgsTimeSlice.ncdf\n26c23b58951ca2be2b9d75c697c529b0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_02:45:00.15min.usgsTimeSlice.ncdf\nb1a26ab87e48334180edc281dcd9a1d1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_03:00:00.15min.usgsTimeSlice.ncdf\n7dbe297398638c7709cad5e64760e55d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_03:15:00.15min.usgsTimeSlice.ncdf\nf6ca5985cfd7ab5528a776b2159285d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_03:30:00.15min.usgsTimeSlice.ncdf\nda9982fdfb825dbb277104b800f38961  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_03:45:00.15min.usgsTimeSlice.ncdf\nd701e3eaf84f78056987e1291b82200b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_04:00:00.15min.usgsTimeSlice.ncdf\n0fa3804ba51d71056824c5447c34ea81  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_04:15:00.15min.usgsTimeSlice.ncdf\na1cf4da14ad5bb6cf13ffcde71d1719a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_04:30:00.15min.usgsTimeSlice.ncdf\nab6bde988da107bbad28c61ed11f2d85  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_04:45:00.15min.usgsTimeSlice.ncdf\n6240a58e08ea0c48005df7cd0d4d58e9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_05:00:00.15min.usgsTimeSlice.ncdf\n155b71a6c4f5697b1a32d61a56665487  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_05:15:00.15min.usgsTimeSlice.ncdf\nc694540df89def26749003af5e27436a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_05:30:00.15min.usgsTimeSlice.ncdf\ndbf97d87487c2bb90dc6c8c95c1e6e65  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_05:45:00.15min.usgsTimeSlice.ncdf\n7b2f48c5119adcfaffe35fd76eb424c2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_06:00:00.15min.usgsTimeSlice.ncdf\n35d187729a1975463cb7e91cc2f5c8c0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_06:15:00.15min.usgsTimeSlice.ncdf\n90cf169375ac4d7ea360f9a44da451d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_06:30:00.15min.usgsTimeSlice.ncdf\n150a484c40375494b15277921a5cd479  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_06:45:00.15min.usgsTimeSlice.ncdf\nabffef7b364cb4528fba88d83369f7dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_07:00:00.15min.usgsTimeSlice.ncdf\n94be1b2b8737fad6b77b9f2f095c978e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_07:15:00.15min.usgsTimeSlice.ncdf\n3359757694a4d60c32c7ebd83ff1b44c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_07:30:00.15min.usgsTimeSlice.ncdf\nfd6ff471c4cf157a2227bdff9f5297a0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_07:45:00.15min.usgsTimeSlice.ncdf\n5fe134926347b83d1b1ee67972b5eb02  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_08:00:00.15min.usgsTimeSlice.ncdf\nfff50cbef97bac52834c058e34f4d78a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_08:15:00.15min.usgsTimeSlice.ncdf\nac7ebafcbe697036af0ff0f4787c5e74  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_08:30:00.15min.usgsTimeSlice.ncdf\nd7ff4fd10016e1abeb5bd57519ab8797  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_08:45:00.15min.usgsTimeSlice.ncdf\na2b9cfd486eb43c3f7515798d699b21c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_09:00:00.15min.usgsTimeSlice.ncdf\n2aadbec2a6c8c3c34324e6091bcc5f33  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_09:15:00.15min.usgsTimeSlice.ncdf\n1be349f8c90cbbd4f59150f17b33fa61  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_09:30:00.15min.usgsTimeSlice.ncdf\n22c25c50e33629c58a48ec39418e5191  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_09:45:00.15min.usgsTimeSlice.ncdf\n1f45e570bcaf6f4656d67497cfca72a4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_10:00:00.15min.usgsTimeSlice.ncdf\na912f10fa6283414838701845079d467  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_10:15:00.15min.usgsTimeSlice.ncdf\n227dd80fa3b46dbb122f08a3274c7c94  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_10:30:00.15min.usgsTimeSlice.ncdf\n1b1537743e0baa1b92316ebb7bf5252e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_10:45:00.15min.usgsTimeSlice.ncdf\n525c3a3a64e7cc53508485890a3c78ab  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_11:00:00.15min.usgsTimeSlice.ncdf\n12625b0c3f36a1d65b4d300650df3ac7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_11:15:00.15min.usgsTimeSlice.ncdf\n1f442c2eac1664ca67e8bcd95478c0b9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_11:30:00.15min.usgsTimeSlice.ncdf\n07c77ae0d95ea21c3cad9eaf157a1771  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_11:45:00.15min.usgsTimeSlice.ncdf\n7f6a635f633f9cdc9bcb3f1e95aab02d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_12:00:00.15min.usgsTimeSlice.ncdf\n5c817ed29e04b695fd58add4879f82d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_12:15:00.15min.usgsTimeSlice.ncdf\nb4afb38f4ce8e072bf8356213c24f31a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_12:30:00.15min.usgsTimeSlice.ncdf\n725504ce4f4dc2ce870f6699208410b0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_12:45:00.15min.usgsTimeSlice.ncdf\nc75ae5bd1d7646b6b6e18d2539972d05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_13:00:00.15min.usgsTimeSlice.ncdf\n10a5a841d41198bb3d69d1dfa2ff2c59  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_13:15:00.15min.usgsTimeSlice.ncdf\n97f363496c1eb5d9d9dd3565c887d6af  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_13:30:00.15min.usgsTimeSlice.ncdf\ncb5c6c10ba341cfa4acac36a40dbc900  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_13:45:00.15min.usgsTimeSlice.ncdf\n100236246ef04bd4dbf89ce1ee124b7b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_14:00:00.15min.usgsTimeSlice.ncdf\n023852d4dd3abe6601041c2d855e4744  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_14:15:00.15min.usgsTimeSlice.ncdf\naa46ea2698babbb94c39c46837947403  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_14:30:00.15min.usgsTimeSlice.ncdf\n67cdcc192f45efcda0b0871a53f344ee  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_14:45:00.15min.usgsTimeSlice.ncdf\nec5e5d3c3edb8fe143ad44425434c9b3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_15:00:00.15min.usgsTimeSlice.ncdf\nfd1264df5ea93c21f7c6289ee8b67bdf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_15:15:00.15min.usgsTimeSlice.ncdf\n8ffc03d6eba8994785b14d46ada17689  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_15:30:00.15min.usgsTimeSlice.ncdf\nbfd7a13906c0cc8337671e6e5394d801  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_15:45:00.15min.usgsTimeSlice.ncdf\n11d0ab30cd95bfff850ff72d38bbbc66  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_16:00:00.15min.usgsTimeSlice.ncdf\nbc82dbd579dba0ce962cca5697d2abb2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_16:15:00.15min.usgsTimeSlice.ncdf\nb9b1c1cbc76cdcebcce57f9506ae1b7c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_16:30:00.15min.usgsTimeSlice.ncdf\n4fe6083b8ca34a65c075ada1262da179  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_16:45:00.15min.usgsTimeSlice.ncdf\nb0b36b0421441fb74c4a50ef28fdf989  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_17:00:00.15min.usgsTimeSlice.ncdf\n6f1fe70d03e478427b5bb572b006c0b4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_17:15:00.15min.usgsTimeSlice.ncdf\nf2a03e7b7a298f24e9876f6fb94800c3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_17:30:00.15min.usgsTimeSlice.ncdf\n152a8f77418f991b159efaa8e5f5b733  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_17:45:00.15min.usgsTimeSlice.ncdf\naf18013b7c13b77e1df3c87164ee5e05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_18:00:00.15min.usgsTimeSlice.ncdf\n310a984c8da96eb632af5ae2128f2c0b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_18:15:00.15min.usgsTimeSlice.ncdf\n939f75f2e31e7e538416bd81fc301de7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_18:30:00.15min.usgsTimeSlice.ncdf\n05f74348230daa6a273b93ea409d3b58  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_18:45:00.15min.usgsTimeSlice.ncdf\n61a316f53e1a9e1f320f41a751bd2986  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_19:00:00.15min.usgsTimeSlice.ncdf\n597bd82160ef5b375dc617b326475671  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_19:15:00.15min.usgsTimeSlice.ncdf\n47d5e8cad3532ee4a6f7ea704a4d2858  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_19:30:00.15min.usgsTimeSlice.ncdf\n045a68044adafc415b0df163c3ce1ee6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_19:45:00.15min.usgsTimeSlice.ncdf\n68deb9cb2c8e4546a2042735ce69421e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_20:00:00.15min.usgsTimeSlice.ncdf\n5f7502c612d1e75751acea7ce90e13d6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_20:15:00.15min.usgsTimeSlice.ncdf\nc2d0e89e57d9da0d89ae75193e2bc121  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_20:30:00.15min.usgsTimeSlice.ncdf\na87f0b976855197a0b4416a1d7db7ed6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_20:45:00.15min.usgsTimeSlice.ncdf\nf7e4ae8df1f1a7dfb9b8d2c38717d4be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_21:00:00.15min.usgsTimeSlice.ncdf\nf78b91604e9c507f72c2a5cacb3c3e38  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_21:15:00.15min.usgsTimeSlice.ncdf\ncf2adb2b074c5779f0dd41a7363cf68c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_21:30:00.15min.usgsTimeSlice.ncdf\n1f698660a73f69a633da7d860a9caa37  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_21:45:00.15min.usgsTimeSlice.ncdf\n7d958dbfcae7be4c14c96423410a8b82  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_22:00:00.15min.usgsTimeSlice.ncdf\n81337b86f0a6cce0d9eaa156b45b6f46  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_22:15:00.15min.usgsTimeSlice.ncdf\n1247083995cb9c440f2856292f041844  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_22:30:00.15min.usgsTimeSlice.ncdf\n24008d77ad2ff80495e7310e619ed302  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_22:45:00.15min.usgsTimeSlice.ncdf\n87acfd402dba1f136d81156a0e2eb8aa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_23:00:00.15min.usgsTimeSlice.ncdf\n560e15d9ea36168a792fcb71e02f2e86  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_23:15:00.15min.usgsTimeSlice.ncdf\n56257efcf12979899fc25c21690f5fdd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_23:30:00.15min.usgsTimeSlice.ncdf\nc3a1faf5d9897ed29c701611f5b935dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_23:45:00.15min.usgsTimeSlice.ncdf\ndc043d3c634e29a3246f72efaf79266a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_00:00:00.15min.usgsTimeSlice.ncdf\n7c1203d7ec855d09b4b4d660cef089a9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_00:15:00.15min.usgsTimeSlice.ncdf\naa07490402076de69b3768ba474954ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_00:30:00.15min.usgsTimeSlice.ncdf\ndc05f6060908ea0d03ce06c225cc319e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_00:45:00.15min.usgsTimeSlice.ncdf\n3404499aa3dc1eb4a9fb8809b4b3d466  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_01:00:00.15min.usgsTimeSlice.ncdf\n3357078cb4b87857bce498deb82504fb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_01:15:00.15min.usgsTimeSlice.ncdf\n31c9b67e5a2204eda623a19fe5c919e4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_01:30:00.15min.usgsTimeSlice.ncdf\na7aa284f557cf303340109ac861855d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_01:45:00.15min.usgsTimeSlice.ncdf\n274b98ddd478465042d8a9b2501f53fb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_02:00:00.15min.usgsTimeSlice.ncdf\n0019d471898c8bcb94e629c240d4cae7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_02:15:00.15min.usgsTimeSlice.ncdf\n51c2022d4b0bced4eebdd4f497c593dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_02:30:00.15min.usgsTimeSlice.ncdf\nda06cdf565a499b9779e9c4a031f4789  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_02:45:00.15min.usgsTimeSlice.ncdf\nbff1b1641b0dea12a77b335b66a4105d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_03:00:00.15min.usgsTimeSlice.ncdf\n376f9f36b557c8e2a1cade3891242c3c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_03:15:00.15min.usgsTimeSlice.ncdf\n59695594ca155612ae131419a38dd89c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_03:30:00.15min.usgsTimeSlice.ncdf\ne8e45d93e9f9f5c538d3d9275392bb20  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_03:45:00.15min.usgsTimeSlice.ncdf\n3c02719c93a488419b23160412251400  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_04:00:00.15min.usgsTimeSlice.ncdf\n9caf696b39734b985b989e5b6ca50840  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_04:15:00.15min.usgsTimeSlice.ncdf\n872af62808c3ceb92d419877ed5e2736  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_04:30:00.15min.usgsTimeSlice.ncdf\nb8f00dcaaeb966e1d07f9c745341195b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_04:45:00.15min.usgsTimeSlice.ncdf\n534b9213fba96e5b320808ff53b86bf7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_05:00:00.15min.usgsTimeSlice.ncdf\n49a3e4b36cbfa6d3677dfe9f301bbc10  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_05:15:00.15min.usgsTimeSlice.ncdf\n31177994b65b649eebf04b0b24c9b262  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_05:30:00.15min.usgsTimeSlice.ncdf\n5bbbca21714295970084f8f6c1ccca59  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_05:45:00.15min.usgsTimeSlice.ncdf\n37bcbff8ce5d045dd5ab78889cdc0186  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_06:00:00.15min.usgsTimeSlice.ncdf\nfc1cab03c5f6a9cc874ca37d54c252e2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_06:15:00.15min.usgsTimeSlice.ncdf\n638c92a85fccda10855d58560e3b5cda  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_06:30:00.15min.usgsTimeSlice.ncdf\n5549455a03001787390f7efeae49cf33  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_06:45:00.15min.usgsTimeSlice.ncdf\nb75f1ce08b4d61798868c5ac8d8c6eb4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_07:00:00.15min.usgsTimeSlice.ncdf\n666839c56479c1cd8c6c6eabcddc6645  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_07:15:00.15min.usgsTimeSlice.ncdf\n31febf02b132ec5997a4029bf56507d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_07:30:00.15min.usgsTimeSlice.ncdf\n3e42bd0fe86f5437ce37852a781446a2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_07:45:00.15min.usgsTimeSlice.ncdf\nf87f5b766b92ce0581d798d8434c038d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_08:00:00.15min.usgsTimeSlice.ncdf\n080adf8d5a19dbbc747c7045aef91771  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_08:15:00.15min.usgsTimeSlice.ncdf\n3bc0814a909fc075a20037dc7798ce09  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_08:30:00.15min.usgsTimeSlice.ncdf\n509fbc564fa0aa5f6863a9483d4d7ea3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_08:45:00.15min.usgsTimeSlice.ncdf\n87d1ca5b399be16821153fc40f1b50ae  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_09:00:00.15min.usgsTimeSlice.ncdf\n9cd90305ebb47b62db6cbd40b0e46d1d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_09:15:00.15min.usgsTimeSlice.ncdf\n72baafdfcdd1747a4f1be5a3b8582202  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_09:30:00.15min.usgsTimeSlice.ncdf\n3f5d9f83e8d296a3e00a675736d4d209  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_09:45:00.15min.usgsTimeSlice.ncdf\n78a1847c44777edf23ab03361ca61e53  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_10:00:00.15min.usgsTimeSlice.ncdf\nddea2e0c3f09772ab33c9fb4af8e9851  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_10:15:00.15min.usgsTimeSlice.ncdf\n67180f569753ab3dde36166272c6bcd9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_10:30:00.15min.usgsTimeSlice.ncdf\n039d002d214199708f4e27dbfc320584  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_10:45:00.15min.usgsTimeSlice.ncdf\n0333d129e33f2d044478e9a1cc8686dc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_11:00:00.15min.usgsTimeSlice.ncdf\n76855f2df6f9a09b290a0fa584e38746  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_11:15:00.15min.usgsTimeSlice.ncdf\n408337f2cfa593b97cbb956d80beb3ae  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_11:30:00.15min.usgsTimeSlice.ncdf\na89a3c487add2d794f93ada17d1ccaa5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_11:45:00.15min.usgsTimeSlice.ncdf\nbb36dc948d8ad8f15c26dd835ee73d2a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_12:00:00.15min.usgsTimeSlice.ncdf\n8093d29f972c967c42d58ac2002caace  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_12:15:00.15min.usgsTimeSlice.ncdf\n0d3c63fdcea3b26c5adc4ba81600da17  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_12:30:00.15min.usgsTimeSlice.ncdf\n3715049c698e24d56a3a2d9cf580b8a8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_12:45:00.15min.usgsTimeSlice.ncdf\n345dc7e83b9546a75c315d2697e42d13  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_13:00:00.15min.usgsTimeSlice.ncdf\n6076027c73a7a76187383d8a487957c2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_13:15:00.15min.usgsTimeSlice.ncdf\n023beacaf382f9d8caabc9c58da25776  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_13:30:00.15min.usgsTimeSlice.ncdf\n9eb6e64d586dc99eaefaf69070d14bf1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_13:45:00.15min.usgsTimeSlice.ncdf\nd99c8573d8df2383441b489a1d40fa2c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_14:00:00.15min.usgsTimeSlice.ncdf\nb7181bf8e4421565eb4b3528c7ff2be9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_14:15:00.15min.usgsTimeSlice.ncdf\nd40031ee77ccf481f38c660a1d0ced81  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_14:30:00.15min.usgsTimeSlice.ncdf\n2100039cf65b9b9e36bcd804f6620376  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_14:45:00.15min.usgsTimeSlice.ncdf\n399e24f097c5b498eef3d3ea79baadc3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_15:00:00.15min.usgsTimeSlice.ncdf\n40758b424f769dc0218a32c21f28377e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_15:15:00.15min.usgsTimeSlice.ncdf\nccbb7ac90489325c1a51af77bbd08943  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_15:30:00.15min.usgsTimeSlice.ncdf\n2bedb1823884e5aa2aa00b05cec837a8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_15:45:00.15min.usgsTimeSlice.ncdf\n07c367e0e2688a558b3ef0c2b24bb7aa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_16:00:00.15min.usgsTimeSlice.ncdf\ndd2b7b29017b1fd3fd1878a6ef4abd08  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_16:15:00.15min.usgsTimeSlice.ncdf\n002361bc634816179cd8b6f4fc84f7de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_16:30:00.15min.usgsTimeSlice.ncdf\ndec34d2d5381ede1c6267cb7cff72741  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_16:45:00.15min.usgsTimeSlice.ncdf\nc24ee3c5934488725771addec1915d63  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_17:00:00.15min.usgsTimeSlice.ncdf\nbe2d677f75c341973e7076b05cedae02  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_17:15:00.15min.usgsTimeSlice.ncdf\n8659698b65e56e58883f0e6d29e6012d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_17:30:00.15min.usgsTimeSlice.ncdf\nd1ea0bf7222d913d3a5302286a3b6dc3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_17:45:00.15min.usgsTimeSlice.ncdf\n600e9a878e8b26225941f6848cfe1549  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_18:00:00.15min.usgsTimeSlice.ncdf\n72b73f2dc5f04d48e5a71e0186b74616  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_18:15:00.15min.usgsTimeSlice.ncdf\nd0e3f1cc7a52922bc22bf1ce88241a3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_18:30:00.15min.usgsTimeSlice.ncdf\n069ecb32552395adf9593cbf1d1d4a77  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_18:45:00.15min.usgsTimeSlice.ncdf\n569dab0bb9bb56f9ebb9fce92c6af707  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_19:00:00.15min.usgsTimeSlice.ncdf\nac5799e6a9b13b746c03ccd6f4f00517  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_19:15:00.15min.usgsTimeSlice.ncdf\nde341b162a86523781abb6928c51156d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_19:30:00.15min.usgsTimeSlice.ncdf\n5451be707501636cc40f03fb12bbefbe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_19:45:00.15min.usgsTimeSlice.ncdf\na7fa793da3c242d2ef1171488d11e09c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_20:00:00.15min.usgsTimeSlice.ncdf\n3e1e0d669b165f2903ff59e043bf2140  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_20:15:00.15min.usgsTimeSlice.ncdf\n56ed95a232ca8e1095246bd280769bff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_20:30:00.15min.usgsTimeSlice.ncdf\nc78f60742f3b7bd200776d1d64f25a4c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_20:45:00.15min.usgsTimeSlice.ncdf\nfbdde76daca94d09ed16d245f79fb9bb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_21:00:00.15min.usgsTimeSlice.ncdf\n7333e360f6e812b9f0ee8400f744dfe0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_21:15:00.15min.usgsTimeSlice.ncdf\n049da88d1103e9dc5c52ba31a3d4efbf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_21:30:00.15min.usgsTimeSlice.ncdf\nfb1b1b3cf8603cec23feca18cd67ed37  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_21:45:00.15min.usgsTimeSlice.ncdf\n537845fa8b8508e9eea744296fe6cbdb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_22:00:00.15min.usgsTimeSlice.ncdf\n3e88c52370b2f299d73e476afdcf37df  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_22:15:00.15min.usgsTimeSlice.ncdf\nbbea20be0c40bb50a6d3c0f21d02a50f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_22:30:00.15min.usgsTimeSlice.ncdf\n1b24deb9c1f0e9f03aac6ffafeca59a4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_22:45:00.15min.usgsTimeSlice.ncdf\n98f4b74005b8d1ad48a5bcae7d78b676  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_23:00:00.15min.usgsTimeSlice.ncdf\n5863a3d56c50ac2790ebf9fb6a3a0ff4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_23:15:00.15min.usgsTimeSlice.ncdf\n7b937b1a84baebb284956d5523e454b1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_23:30:00.15min.usgsTimeSlice.ncdf\ne915d21199c94d7726f537b443d56b01  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_23:45:00.15min.usgsTimeSlice.ncdf\n06ba1fd5dce4e670c0d20e32fa758ff1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_00:00:00.15min.usgsTimeSlice.ncdf\neadeb440aaaae03cbbfc05280549f541  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_00:15:00.15min.usgsTimeSlice.ncdf\ne4e558970edfbf952be86425d2c006e4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_00:30:00.15min.usgsTimeSlice.ncdf\nbac2dd5d4b9a60b3e39caa6e7bcaf8de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_00:45:00.15min.usgsTimeSlice.ncdf\n8e4a891677c422e394258010792037d0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_01:00:00.15min.usgsTimeSlice.ncdf\nba96b0ee9c2a8eae7b7f53db39a9ff74  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_01:15:00.15min.usgsTimeSlice.ncdf\na84a828e462fd7cf6856c81c4f2b95e8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_01:30:00.15min.usgsTimeSlice.ncdf\nfbb40c7bd4f750c617427000448117fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_01:45:00.15min.usgsTimeSlice.ncdf\n2363309a4becb3713a7a7c872c8e472e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_02:00:00.15min.usgsTimeSlice.ncdf\n4a20ae83395087de50dcdfe64ae3b14c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_02:15:00.15min.usgsTimeSlice.ncdf\n6befc05ea598ab5b858f5a4032d89d57  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_02:30:00.15min.usgsTimeSlice.ncdf\nb57b951d735b592b44e031ae74c5d3e7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_02:45:00.15min.usgsTimeSlice.ncdf\n79691020b2085362f9c07805b67583ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_03:00:00.15min.usgsTimeSlice.ncdf\na16350b323079c3faf6b9494f2ef9388  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_03:15:00.15min.usgsTimeSlice.ncdf\nb84656d5e8afcf5782ea465a2d7d463b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_03:30:00.15min.usgsTimeSlice.ncdf\n9090ad461cd440fdb673c15d67f4fbc6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_03:45:00.15min.usgsTimeSlice.ncdf\na48096cfb33612d18ff38cea3b89923c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_04:00:00.15min.usgsTimeSlice.ncdf\n4f9c19de8be8e89bebc5d66548406637  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_04:15:00.15min.usgsTimeSlice.ncdf\nf3daa6c841b9f534d367883f647e6170  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_04:30:00.15min.usgsTimeSlice.ncdf\nb025ee44dda5394fc5d08cac5f00ac0c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_04:45:00.15min.usgsTimeSlice.ncdf\n5cb6896d0ca20a35942f1d02b73190b8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_05:00:00.15min.usgsTimeSlice.ncdf\n2479b6358e85f85137c2aa1a10b141de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_05:15:00.15min.usgsTimeSlice.ncdf\n960532c12948abb04fa49f5a26c8d664  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_05:30:00.15min.usgsTimeSlice.ncdf\nfdc1bf14faba29fd42c5f520bc385410  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_05:45:00.15min.usgsTimeSlice.ncdf\nb880af0800aab5e23ccc8d57432dba12  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_06:00:00.15min.usgsTimeSlice.ncdf\n745162f6b8bcab3e5ac04ddae8e9c5da  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_06:15:00.15min.usgsTimeSlice.ncdf\n0f9b7b78727232a83d2365bc8bc0e1d7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_06:30:00.15min.usgsTimeSlice.ncdf\nc5f8f3d3b8dfebd57f05137d231ea8bb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_06:45:00.15min.usgsTimeSlice.ncdf\nb36879288b54d356b6d8a80b0c652446  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_07:00:00.15min.usgsTimeSlice.ncdf\n94610184ad4d23753bcd5ef8f6db7927  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_07:15:00.15min.usgsTimeSlice.ncdf\n18a8fc47bb76fd03aebb623fd4debba4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_07:30:00.15min.usgsTimeSlice.ncdf\n3b311d5b881eacff5ab46d33382aed0e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_07:45:00.15min.usgsTimeSlice.ncdf\nc660b060158535193fbd41ffdd9cef4c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_08:00:00.15min.usgsTimeSlice.ncdf\n4a79395ed656869e3726a02f7701c499  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_08:15:00.15min.usgsTimeSlice.ncdf\nd0fe55c7b8b11db60910adf265311851  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_08:30:00.15min.usgsTimeSlice.ncdf\n2b41edd0550663267cc5a8aed47a8f21  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_08:45:00.15min.usgsTimeSlice.ncdf\nc9445ff32268f1fb822b697fe550600d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_09:00:00.15min.usgsTimeSlice.ncdf\nd7871d27f83ad8a8b96a17d090849929  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_09:15:00.15min.usgsTimeSlice.ncdf\na86f5dabd9d18f7140cff4c9887cc2f0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_09:30:00.15min.usgsTimeSlice.ncdf\nbfb7f1f721ec372a46e6c9413b7fbec3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_09:45:00.15min.usgsTimeSlice.ncdf\nbeb1e252573f33eb1a97380b67be1d20  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_10:00:00.15min.usgsTimeSlice.ncdf\n4abf47c4fc9c731e1da2827062a937d0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_10:15:00.15min.usgsTimeSlice.ncdf\n917ed389a2f894ae134340c5578e36eb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_10:30:00.15min.usgsTimeSlice.ncdf\n9880e142d02c9247fb768c25a5c66fa4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_10:45:00.15min.usgsTimeSlice.ncdf\n0852f264e86c5b6e41181d6971aa3013  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_11:00:00.15min.usgsTimeSlice.ncdf\n217360f1cef8970ed6b552ed59c7f9ef  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_11:15:00.15min.usgsTimeSlice.ncdf\n5756ea008cce66f6f7962da7541851ab  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_11:30:00.15min.usgsTimeSlice.ncdf\n6de864d320606d4a7c898551cdd36b40  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_11:45:00.15min.usgsTimeSlice.ncdf\nd153b5995f647a1ce42a8dca968ae399  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_12:00:00.15min.usgsTimeSlice.ncdf\nef4e36c54bd9272cb1a4d95b78875f58  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_12:15:00.15min.usgsTimeSlice.ncdf\nf6069ded04d5694482b6218fba981bc7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_12:30:00.15min.usgsTimeSlice.ncdf\n5a2d7b48ed8e9eae0dd57ef6fcd03b3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_12:45:00.15min.usgsTimeSlice.ncdf\nf719768b54cd91bcfd258e0e556c6b26  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_13:00:00.15min.usgsTimeSlice.ncdf\n42da4a9f1c45dded8cd29e3c92fb3696  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_13:15:00.15min.usgsTimeSlice.ncdf\n05ba5cee16b67cac5b8caee0689c05d7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_13:30:00.15min.usgsTimeSlice.ncdf\n39087e1d3f629d3de415e22eaaba5c82  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_13:45:00.15min.usgsTimeSlice.ncdf\n67ef82258682a5716f7db295f64b8742  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_14:00:00.15min.usgsTimeSlice.ncdf\n1ea6c1db6f6dfb516622916cd31f5af6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_14:15:00.15min.usgsTimeSlice.ncdf\n0394ee3c4db756dc67abef6807dfcd7f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_14:30:00.15min.usgsTimeSlice.ncdf\n3b3a0879d97d2b1e74d2679226c35155  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_14:45:00.15min.usgsTimeSlice.ncdf\nc49a59d827d41ac0835943ddbf447b4b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_15:00:00.15min.usgsTimeSlice.ncdf\ne4fdb38428a23b335d73bd1cbba8a661  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_15:15:00.15min.usgsTimeSlice.ncdf\n4ed7063a3290552153a5163c586425e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_15:30:00.15min.usgsTimeSlice.ncdf\n2eb4e6a1645133c4284873e908a03f0f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_15:45:00.15min.usgsTimeSlice.ncdf\n6139e698bb311480d516fbc45c81532d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_16:00:00.15min.usgsTimeSlice.ncdf\nb82f83ead8b0bdab8348a743aa54daa7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_16:15:00.15min.usgsTimeSlice.ncdf\n4fbb9f0d8223252a36d8b20158237db6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_16:30:00.15min.usgsTimeSlice.ncdf\n021ec256865c6bd75e2919f9d0ba4819  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_16:45:00.15min.usgsTimeSlice.ncdf\na76c081a73259148e3053e953bf7e774  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_17:00:00.15min.usgsTimeSlice.ncdf\n0dc7388a1fd49025a9450977de7b160b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_17:15:00.15min.usgsTimeSlice.ncdf\naa3101ed5626e30bd653cc1a3b831833  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_17:30:00.15min.usgsTimeSlice.ncdf\n4f64cf723332fc6cbaad7455e3f43abd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_17:45:00.15min.usgsTimeSlice.ncdf\n0356be3ffaeaebfd1c31b82c5fe2985f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_18:00:00.15min.usgsTimeSlice.ncdf\ncd3ada5c31942bd969b73c36e6f1a35d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_18:15:00.15min.usgsTimeSlice.ncdf\n6763b19d990afe7bd238d01990ab2542  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_18:30:00.15min.usgsTimeSlice.ncdf\nbc218dd809c52c7f070f6e87cf5fccd6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_18:45:00.15min.usgsTimeSlice.ncdf\nbf35619d726120989819e1cf0f1d95df  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_19:00:00.15min.usgsTimeSlice.ncdf\n1a17392c1248de7c1c247826fed9847e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_19:15:00.15min.usgsTimeSlice.ncdf\nc1efff477e5c4c2c2e6bb420db41bc7a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_19:30:00.15min.usgsTimeSlice.ncdf\n9825dc0d94533e21d87721750134c2b9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_19:45:00.15min.usgsTimeSlice.ncdf\n769664df35f74d2b86eb80210f2be141  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_20:00:00.15min.usgsTimeSlice.ncdf\n994d57d631d56b6422dad5ce64e65378  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_20:15:00.15min.usgsTimeSlice.ncdf\n94af9e19dbc3acca1f55e3a180e71b1d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_20:30:00.15min.usgsTimeSlice.ncdf\nac6c4c67d474289862257cc2dca1a79c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_20:45:00.15min.usgsTimeSlice.ncdf\n878ebf21827892b7b4d407799efb6622  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_21:00:00.15min.usgsTimeSlice.ncdf\ne9bf46b1c9e5894783ead4a931380eb9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_21:15:00.15min.usgsTimeSlice.ncdf\n2d479cf46ee0686ef787143fdb9adf17  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_21:30:00.15min.usgsTimeSlice.ncdf\n615aef0e1f4073a6938ad0f314fe8c69  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_21:45:00.15min.usgsTimeSlice.ncdf\n6651ebe878dfe54746d09fd812997ae3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_22:00:00.15min.usgsTimeSlice.ncdf\n5a01840af836e6b82ca56b985ec35695  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_22:15:00.15min.usgsTimeSlice.ncdf\nc6b8628820a03d004909f104ff46aab5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_22:30:00.15min.usgsTimeSlice.ncdf\n9fb384f9fbfafeb05c53970b3a82da9e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_22:45:00.15min.usgsTimeSlice.ncdf\n8f2861639b9a46410cf94fc582006345  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_23:00:00.15min.usgsTimeSlice.ncdf\nc6facfbec43cfd03efcadcc0f9423a3e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_23:15:00.15min.usgsTimeSlice.ncdf\n06159a783e1a3c9f0410b24089e6997e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_23:30:00.15min.usgsTimeSlice.ncdf\n3e4f39966d3cde17f7f1847905424c1f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_23:45:00.15min.usgsTimeSlice.ncdf\nf34b32c7efef5f2319b70500efa95402  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_00:00:00.15min.usgsTimeSlice.ncdf\nd73ae0e68ba1dfb3ac9e3c16548612fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_00:15:00.15min.usgsTimeSlice.ncdf\n8fe4e0638f6585d3f1790b6811ba71da  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_00:30:00.15min.usgsTimeSlice.ncdf\n0294f4e03437016578b8c72490360cbd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_00:45:00.15min.usgsTimeSlice.ncdf\nfbbc8adccf0467dbb34e8d43be3e0dbe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_01:00:00.15min.usgsTimeSlice.ncdf\n21a593a2e9b84c6c4b110658e7193a3a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_01:15:00.15min.usgsTimeSlice.ncdf\n6236e61b3628bf259bbbca622a06362a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_01:30:00.15min.usgsTimeSlice.ncdf\n501438d298c27041ed3a6963c5f44d84  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_01:45:00.15min.usgsTimeSlice.ncdf\n01c2a7a3d577149d905048dfaf467899  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_02:00:00.15min.usgsTimeSlice.ncdf\n6bae0cb4d3aec1c26e3aa518c6416e7a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_02:15:00.15min.usgsTimeSlice.ncdf\n0c01256083403595f0eab19df140e6a9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_02:30:00.15min.usgsTimeSlice.ncdf\n9d9e91751d31823e7b4f8a84afc1cca4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_02:45:00.15min.usgsTimeSlice.ncdf\nd680ca9310735e445775f502fdfd328f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_03:00:00.15min.usgsTimeSlice.ncdf\nf180b13259ef6424fb8c16116776a629  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_03:15:00.15min.usgsTimeSlice.ncdf\n6e872c4d35af6c6ff6c9605617b26a4e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_03:30:00.15min.usgsTimeSlice.ncdf\n1c50352e23c8d2e63f482e99bb09231d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_03:45:00.15min.usgsTimeSlice.ncdf\n1261cf81f47259447e6d92ba0ae924f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_04:00:00.15min.usgsTimeSlice.ncdf\n7618ede06ff28cd35a2eaac4a478427c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_04:15:00.15min.usgsTimeSlice.ncdf\n0a5307e03799203e55554dd03a30c7fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_04:30:00.15min.usgsTimeSlice.ncdf\n30e375f040c53a2e585adae9ec5fdfd4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_04:45:00.15min.usgsTimeSlice.ncdf\n2dcbfa1fc8260f4c438d237d3675039a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_05:00:00.15min.usgsTimeSlice.ncdf\n57e10f5c7949611c916a78a76bbb64a0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_05:15:00.15min.usgsTimeSlice.ncdf\n1d211b258db5affa8564952646a585f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_05:30:00.15min.usgsTimeSlice.ncdf\na03e4aeb1ad47436b1ce73ccc50d9c49  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_05:45:00.15min.usgsTimeSlice.ncdf\n67134cb5e6be16db2c16ccb108862f71  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_06:00:00.15min.usgsTimeSlice.ncdf\n888de94d5d1b0a31222d8062ded3a447  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_06:15:00.15min.usgsTimeSlice.ncdf\n9b0ae699dd7d890f1ed0a02d984284ca  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_06:30:00.15min.usgsTimeSlice.ncdf\n94a534e7211f3c961e21ae26a28120cc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_06:45:00.15min.usgsTimeSlice.ncdf\n9832f018a7ab21016e1e3c256e6b2cb4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_07:00:00.15min.usgsTimeSlice.ncdf\nfed95f49fdd0cc6202508659b278b437  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_07:15:00.15min.usgsTimeSlice.ncdf\nd17b3f5a3e857840b47a350f92a5fbb7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_07:30:00.15min.usgsTimeSlice.ncdf\nc12635a4418d55ea21dbf60a9f35afe4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_07:45:00.15min.usgsTimeSlice.ncdf\nd2365c124543e08a8e691959daff84df  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_08:00:00.15min.usgsTimeSlice.ncdf\n794166ae00df039390bf55cf4cc44e67  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_08:15:00.15min.usgsTimeSlice.ncdf\n809aeb9ba8acb4aca50dcd32d5c6eda8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_08:30:00.15min.usgsTimeSlice.ncdf\n729f4ca464223c591ae71a1869541a48  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_08:45:00.15min.usgsTimeSlice.ncdf\n2858c01d472d1e49143d6cac12bc54fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_09:00:00.15min.usgsTimeSlice.ncdf\n20d01bdfe064cded27157ad7350cff85  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_09:15:00.15min.usgsTimeSlice.ncdf\n2c5df9fa558d9a5fb79a3d2cd4ed2c0a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_09:30:00.15min.usgsTimeSlice.ncdf\n60589e975e9a7f150e522ac635049209  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_09:45:00.15min.usgsTimeSlice.ncdf\n96824eb7a8e339c1b989c5a4a87c28a6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_10:00:00.15min.usgsTimeSlice.ncdf\nae86fd4b3cb34f20ef01541afb506a72  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_10:15:00.15min.usgsTimeSlice.ncdf\nce1b81741f1d7a57da622ee11f73ac6a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_10:30:00.15min.usgsTimeSlice.ncdf\nf78c784c9d2748cf0d3d35eee7b438ad  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_10:45:00.15min.usgsTimeSlice.ncdf\ndedaf05da4a69405c2d7932be825a8b3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_11:00:00.15min.usgsTimeSlice.ncdf\n44a290a5d31e38f237ea3a82a54a07f7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_11:15:00.15min.usgsTimeSlice.ncdf\nf7ac38946c28cd602dc3161a524901ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_11:30:00.15min.usgsTimeSlice.ncdf\n77e8de0aabde135ecc32070e5d786108  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_11:45:00.15min.usgsTimeSlice.ncdf\n4320240e966d740c492865a0cc367904  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_12:00:00.15min.usgsTimeSlice.ncdf\n106fedf825b326303d1b648b04ac0ba3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_12:15:00.15min.usgsTimeSlice.ncdf\na67516d507d87260cccf856fd24b0e05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_12:30:00.15min.usgsTimeSlice.ncdf\na9fda41dfa560543a29129930e93ac93  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_12:45:00.15min.usgsTimeSlice.ncdf\nc0208881b74e35c64677f81289b721be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_13:00:00.15min.usgsTimeSlice.ncdf\n0e39b8615facbfffe58a8d502b5e3da7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_13:15:00.15min.usgsTimeSlice.ncdf\nc96765f18e5f6ebb09695ce7bdbf5516  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_13:30:00.15min.usgsTimeSlice.ncdf\n45317cdc6ef1907d5e253873b5cae4fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_13:45:00.15min.usgsTimeSlice.ncdf\n3da4941fea69fa55dce8f8460054aa5c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_14:00:00.15min.usgsTimeSlice.ncdf\naba053b54fb027f284da0d6b7878790b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_14:15:00.15min.usgsTimeSlice.ncdf\n7b499a86891ec1cb571bb01473c794f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_14:30:00.15min.usgsTimeSlice.ncdf\n311fe6dfa0f0a6cfae91f45f7397b737  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_14:45:00.15min.usgsTimeSlice.ncdf\n07250cd03203f7c4131f0e5eec2b69f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_15:00:00.15min.usgsTimeSlice.ncdf\n7f2982494cd217109c935015a0e72044  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_15:15:00.15min.usgsTimeSlice.ncdf\nf64887af3388db9700a27310a7617903  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_15:30:00.15min.usgsTimeSlice.ncdf\n83acf395009e08c509b23acebebea19c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_15:45:00.15min.usgsTimeSlice.ncdf\nafa915dc33bbe1cc4efbfcf3c1009c08  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_16:00:00.15min.usgsTimeSlice.ncdf\n1a4b79d855175ac5a599c6ac7848d646  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_16:15:00.15min.usgsTimeSlice.ncdf\n89b34f78e4886810676c9e4991a4b081  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_16:30:00.15min.usgsTimeSlice.ncdf\ncc49f1b6dc3a7977f0e27ca8951f829f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_16:45:00.15min.usgsTimeSlice.ncdf\n559a7874d4034c5c88c16a732453cffd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_17:00:00.15min.usgsTimeSlice.ncdf\nf27f05256c6625b43afdb21467e987fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_17:15:00.15min.usgsTimeSlice.ncdf\nac901cc4f6f310bb5a5e19679a73f9e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_17:30:00.15min.usgsTimeSlice.ncdf\n0193e6a9704283cd7b4b79f4b8fe6831  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_17:45:00.15min.usgsTimeSlice.ncdf\ncdc1c0729132ea9e867218b016404d9e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_18:00:00.15min.usgsTimeSlice.ncdf\n0a8d9ec3dc79d44f97197533a8189dff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_18:15:00.15min.usgsTimeSlice.ncdf\n678e547aec573e6f0714c82df2dcffc0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_18:30:00.15min.usgsTimeSlice.ncdf\na9896b62327596171f1e83856c65f09c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_18:45:00.15min.usgsTimeSlice.ncdf\n5bd43eca92a4aca97eb4c7cc5e18fe9c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_19:00:00.15min.usgsTimeSlice.ncdf\n581c6045e50ac714ab4b220e8279fd48  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_19:15:00.15min.usgsTimeSlice.ncdf\na7a1821a187d0a5d6fd6c228d6bec6f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_19:30:00.15min.usgsTimeSlice.ncdf\n3205078640261e515c97c45fe91c2a29  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_19:45:00.15min.usgsTimeSlice.ncdf\n5bbd12fab48b33ab173a73b338ed6d79  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_20:00:00.15min.usgsTimeSlice.ncdf\n1d6247153c5ac166a3f9372e026bb4d7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_20:15:00.15min.usgsTimeSlice.ncdf\n79b21c3e84c598cd3890615e2efefe63  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_20:30:00.15min.usgsTimeSlice.ncdf\n042fce9e89dbe4a42cb33dfda3f9e558  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_20:45:00.15min.usgsTimeSlice.ncdf\n808d5cf8cd130cc76a7919a45298b135  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_21:00:00.15min.usgsTimeSlice.ncdf\n1226d149ce28bae77aa4ecc8bd5cba3e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_21:15:00.15min.usgsTimeSlice.ncdf\n32c8aa34e9ff62d45df1a38957b7c68a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_21:30:00.15min.usgsTimeSlice.ncdf\nbc5cf591019aa7f2a7a4fed7211c9da9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_21:45:00.15min.usgsTimeSlice.ncdf\n28209ff0d8355582a1305448a28e5f45  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_22:00:00.15min.usgsTimeSlice.ncdf\n25ced6fdc8220827f1bbbff2bb10a5ec  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_22:15:00.15min.usgsTimeSlice.ncdf\nebb2987cdc47dd26f6fa76b0ad458289  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_22:30:00.15min.usgsTimeSlice.ncdf\n07183b3611054d339a667ccc1b890507  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_22:45:00.15min.usgsTimeSlice.ncdf\n1e7667a78e3bc3305d47b295bee22834  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_23:00:00.15min.usgsTimeSlice.ncdf\n4afe61151629ed8bf83313a77961ee44  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_23:15:00.15min.usgsTimeSlice.ncdf\ndd550ff58a67d0406d0e932932df8248  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_23:30:00.15min.usgsTimeSlice.ncdf\nf893277a5406b1d270604d0c4c5df4a9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_23:45:00.15min.usgsTimeSlice.ncdf\n6db806535f807be6265141164bfeccd7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_00:00:00.15min.usgsTimeSlice.ncdf\n51b84eee7f1bb5112ad750154ff33e5d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_00:15:00.15min.usgsTimeSlice.ncdf\n050b684b406b1fd5f0be3148d154146f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_00:30:00.15min.usgsTimeSlice.ncdf\nc04f40bc0b5dd518a46d799aa97cf5a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_00:45:00.15min.usgsTimeSlice.ncdf\nc0a7499570fc03eac4c9d41e5ee0b8a1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_01:00:00.15min.usgsTimeSlice.ncdf\n614d1b14c6f907f046ea0c15f2061408  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_01:15:00.15min.usgsTimeSlice.ncdf\ne18b018317fa608af108c0e9e12ca032  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_01:30:00.15min.usgsTimeSlice.ncdf\n008ef79296ea7106a9b58a93675bd444  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_01:45:00.15min.usgsTimeSlice.ncdf\n232b6bf6f1639376b131f1165876ed80  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_02:00:00.15min.usgsTimeSlice.ncdf\n529c1d73177f0ae5cf252d1295a3a95f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_02:15:00.15min.usgsTimeSlice.ncdf\neaa443e01094010b1acc80b285379924  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_02:30:00.15min.usgsTimeSlice.ncdf\n822905c51e26dbb9fd404d4491857a58  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_02:45:00.15min.usgsTimeSlice.ncdf\n157ab6b38bbda14935c6b8cffb790576  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_03:00:00.15min.usgsTimeSlice.ncdf\n1839bca9459ab9caf83d81c26c15ea74  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_03:15:00.15min.usgsTimeSlice.ncdf\nbe145fb9ed062277050308d3ea4281a2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_03:30:00.15min.usgsTimeSlice.ncdf\nad97723e2a81015674e8a2906310ba55  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_03:45:00.15min.usgsTimeSlice.ncdf\n0554d9c4c8db76215ecd94a0a8caf007  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_04:00:00.15min.usgsTimeSlice.ncdf\na858b5be69086b81dc572efa70ed4435  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_04:15:00.15min.usgsTimeSlice.ncdf\ne2a8658c31088466dea778a8746b34e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_04:30:00.15min.usgsTimeSlice.ncdf\na1c84a133631a63417ad500c7015473e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_04:45:00.15min.usgsTimeSlice.ncdf\nd453cfb6837d4887c9b0904fb90713a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_05:00:00.15min.usgsTimeSlice.ncdf\nc3376966054d6ea90d4f65bb518ee754  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_05:15:00.15min.usgsTimeSlice.ncdf\n70ddb1bd697eeb2860c51091f38c27d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_05:30:00.15min.usgsTimeSlice.ncdf\n2dc97d71763f7f73dcd224d4fd2cff64  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_05:45:00.15min.usgsTimeSlice.ncdf\nd0df89f35431c309af905d38e45a2cc3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_06:00:00.15min.usgsTimeSlice.ncdf\ne42bf231e84281056e7015ccd5686a5b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_06:15:00.15min.usgsTimeSlice.ncdf\ne64c47545eccf2f545a6ef79569f41b2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_06:30:00.15min.usgsTimeSlice.ncdf\n7b1e0797945effc235e1b95dc05f5e56  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_06:45:00.15min.usgsTimeSlice.ncdf\nd755df7513fa1e0dc8e74b10d40db97e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_07:00:00.15min.usgsTimeSlice.ncdf\n170ea7f81b3543a1b22f61ae44f695c1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_07:15:00.15min.usgsTimeSlice.ncdf\nad1ac3f4a89550514c4f07a35a83ad2d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_07:30:00.15min.usgsTimeSlice.ncdf\n10b0ebdf59b4b25b0d5c8340705518f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_07:45:00.15min.usgsTimeSlice.ncdf\n4889a349f2735b3f04a5f65c608530c0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_08:00:00.15min.usgsTimeSlice.ncdf\n08b6ab5952a559faa8db0afd0bb2575f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_08:15:00.15min.usgsTimeSlice.ncdf\n113ba39ba1da0e45f8913c0e2f1a8623  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_08:30:00.15min.usgsTimeSlice.ncdf\n2cf2a253d5244a579a7988e3d52d94c5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_08:45:00.15min.usgsTimeSlice.ncdf\nff9eed4afe66f6d45a188fd328567ad0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_09:00:00.15min.usgsTimeSlice.ncdf\n89dca3ee4ca371cf893b6c442fd9da17  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_09:15:00.15min.usgsTimeSlice.ncdf\n07db38f3e850e80a152e83658bc76495  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_09:30:00.15min.usgsTimeSlice.ncdf\nd4c1bae82e3acef47ebaab9282d73731  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_09:45:00.15min.usgsTimeSlice.ncdf\n206c30b4079c34cc43c2e0e07d71125a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_10:00:00.15min.usgsTimeSlice.ncdf\n03fff40a2ec6c7eabfd6e70f1fb99732  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_10:15:00.15min.usgsTimeSlice.ncdf\n2ce9d30ef6266f82c46042e2c63ea3fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_10:30:00.15min.usgsTimeSlice.ncdf\n34c81cae97a0010af2524143bdeb9bef  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_10:45:00.15min.usgsTimeSlice.ncdf\n20f2e26c0fe6506d2a2cbfa10453f670  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_11:00:00.15min.usgsTimeSlice.ncdf\n50de1a0c781d2d1755d167930535940c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_11:15:00.15min.usgsTimeSlice.ncdf\n32611cd4943fb72409d7b35442874a8b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_11:30:00.15min.usgsTimeSlice.ncdf\nc238a1161bc35aa3f422b00e7d9f4e2b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_11:45:00.15min.usgsTimeSlice.ncdf\n382cc95cf2882b17021f38905ff28fe8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_12:00:00.15min.usgsTimeSlice.ncdf\n2bd3bba7cdaa660cb036f13739d582c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_12:15:00.15min.usgsTimeSlice.ncdf\n402ab74d9b10a0785884f8d6bb8ea62d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_12:30:00.15min.usgsTimeSlice.ncdf\n8bfe93d9357380d34a924a89bcc360dc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_12:45:00.15min.usgsTimeSlice.ncdf\ne7ce22462d588a448a8047f27c2e37c8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_13:00:00.15min.usgsTimeSlice.ncdf\n483ee15a0622555448fb64a02f14aad4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_13:15:00.15min.usgsTimeSlice.ncdf\n7fb4fb845dfc67e114ce52c288921f1c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_13:30:00.15min.usgsTimeSlice.ncdf\ndacb0fecb01cbbdd2e770ae3f5ff5148  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_13:45:00.15min.usgsTimeSlice.ncdf\nb0f074a843ed6073edba51918e6db5f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_14:00:00.15min.usgsTimeSlice.ncdf\n86decd62084045d28410c2939084457c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_14:15:00.15min.usgsTimeSlice.ncdf\n441fbb92ff40ab3767b386cba36573d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_14:30:00.15min.usgsTimeSlice.ncdf\n367eec2d4e74dde1e86bf5bb18b6658b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_14:45:00.15min.usgsTimeSlice.ncdf\n18a27af4b9528174c0b5403a0cd164de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_15:00:00.15min.usgsTimeSlice.ncdf\n10856408f3d66585d9fa0ec263075416  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_15:15:00.15min.usgsTimeSlice.ncdf\nca8a99633aaad1c7d2fd0fc25afd5f0b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_15:30:00.15min.usgsTimeSlice.ncdf\nb1bfc984bf399953204cce74898e738d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_15:45:00.15min.usgsTimeSlice.ncdf\nac0f0b48b70fef43076e218631ac88c0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_16:00:00.15min.usgsTimeSlice.ncdf\n1bc2e378057e0ab9b7db670e910ed873  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_16:15:00.15min.usgsTimeSlice.ncdf\na21cc6557e5623b545ec16ee3b8b60cc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_16:30:00.15min.usgsTimeSlice.ncdf\nba27235724f10d615c158c5a63bed298  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_16:45:00.15min.usgsTimeSlice.ncdf\na7277019ecf5f845201793cd943675b6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_17:00:00.15min.usgsTimeSlice.ncdf\n40b94fa9fe76bf99303e42bdb2e3b228  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_17:15:00.15min.usgsTimeSlice.ncdf\nd658d3c9d13ad69b4f5cdf1947ab06f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_17:30:00.15min.usgsTimeSlice.ncdf\n2dc2ebe1dac7c990b7d0d3cab14b4c10  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_17:45:00.15min.usgsTimeSlice.ncdf\n121737b2bacaec686468a5990914f826  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_18:00:00.15min.usgsTimeSlice.ncdf\ne8256c307eb925be65ea64ee9ae859fa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_18:15:00.15min.usgsTimeSlice.ncdf\n3ec99135fe49dcab0ea28b04ce346494  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_18:30:00.15min.usgsTimeSlice.ncdf\n3744e2a4cd03cad07a225384527368f8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_18:45:00.15min.usgsTimeSlice.ncdf\n18e4c4e520459e9cd477ff4837749405  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_19:00:00.15min.usgsTimeSlice.ncdf\n138dd4beb338d94b79cd2726307e2660  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_19:15:00.15min.usgsTimeSlice.ncdf\n12a522fbc4fac5260ae72fc2fc9cc7d8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_19:30:00.15min.usgsTimeSlice.ncdf\n4dbc584ff2eb140455aa7e1e65b7989c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_19:45:00.15min.usgsTimeSlice.ncdf\n680101ba5ae1d1ed997e63c7c536e2bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_20:00:00.15min.usgsTimeSlice.ncdf\n436969960e9eb53be4d27969d79e0c43  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_20:15:00.15min.usgsTimeSlice.ncdf\nfcf54f8076da0b8c8c2f93f2f4387767  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_20:30:00.15min.usgsTimeSlice.ncdf\n47b6d9854fad95fe855fa2b9674c78b3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_20:45:00.15min.usgsTimeSlice.ncdf\nee045dc3f33aad6e200448e6d4d0763a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_21:00:00.15min.usgsTimeSlice.ncdf\n4526f890789689041909bc7ab81ea8bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_21:15:00.15min.usgsTimeSlice.ncdf\n5df28fe3a58f1cff8bac737a4ba31a31  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_21:30:00.15min.usgsTimeSlice.ncdf\n5ba4aac71497b3e5b1aad6d539259e55  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_21:45:00.15min.usgsTimeSlice.ncdf\nd6370706a506d8f63b9798a14137aab0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_22:00:00.15min.usgsTimeSlice.ncdf\n3cd3f7e0e76542f258245ca3b7b2c993  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_22:15:00.15min.usgsTimeSlice.ncdf\n4ec096a9583da18e80b64a3fc8ebbe88  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_22:30:00.15min.usgsTimeSlice.ncdf\n3f87dd13eaf5e535b626ad56beae27e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_22:45:00.15min.usgsTimeSlice.ncdf\n264e0ec6e66b858864ff048047933531  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_23:00:00.15min.usgsTimeSlice.ncdf\na8fb51a37ec989bfb6f06d75d981ce3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_23:15:00.15min.usgsTimeSlice.ncdf\n7772ed42ac03ec3f30f294ed72171f1e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_23:30:00.15min.usgsTimeSlice.ncdf\n3706ecb67c3f6960228f5c9a5dca55de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_23:45:00.15min.usgsTimeSlice.ncdf\n96a07342539f43953a8c0dd4c719b85a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_00:00:00.15min.usgsTimeSlice.ncdf\na7e5cab10f807a15d28fb2ddb09258c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_00:15:00.15min.usgsTimeSlice.ncdf\n24779041d1c0d069de85fa32d3435e13  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_00:30:00.15min.usgsTimeSlice.ncdf\n79c2003b69cd236be880f8ac74bf67ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_00:45:00.15min.usgsTimeSlice.ncdf\n654fba12fed89eb4c2efbc46f3b05e39  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_01:00:00.15min.usgsTimeSlice.ncdf\ne319934dc3d8ce2cc67028866a491c76  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_01:15:00.15min.usgsTimeSlice.ncdf\n6b44122ecc1954affee30b9dc4665a50  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_01:30:00.15min.usgsTimeSlice.ncdf\n1f34f1f82596b817bd74dbcb9a5f328d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_01:45:00.15min.usgsTimeSlice.ncdf\nf0781c88b2dfc1cb85178cea7348f4a0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_02:00:00.15min.usgsTimeSlice.ncdf\n3cc3a28e5cd03ac12f40d62453de186c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_02:15:00.15min.usgsTimeSlice.ncdf\n6d4f5071ea0cc68b880f5005adac3dbf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_02:30:00.15min.usgsTimeSlice.ncdf\n81001c505d442d86199d1dfbb5fe0648  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_02:45:00.15min.usgsTimeSlice.ncdf\n2185afda63a3b2d9fb91b15c45a7aa65  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_03:00:00.15min.usgsTimeSlice.ncdf\nb5ae6cc8970e9b41a40faafa7cb90f51  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_03:15:00.15min.usgsTimeSlice.ncdf\na8d3ed4f66c363e1d4c6737247d35ab2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_03:30:00.15min.usgsTimeSlice.ncdf\n6b5bb748dce767f25e121a2474222c64  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_03:45:00.15min.usgsTimeSlice.ncdf\n726b9a0641747c9859f0bb36e69a5df2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_04:00:00.15min.usgsTimeSlice.ncdf\nfdb40a4eca90cb78b257ebea56b6dcf5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_04:15:00.15min.usgsTimeSlice.ncdf\n958837e71469f93347c0d3df97234146  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_04:30:00.15min.usgsTimeSlice.ncdf\n0eb5b35c4504cb8bcffb0cb55efc77af  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_04:45:00.15min.usgsTimeSlice.ncdf\ncade16e394cabcce395c4e403f689844  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_05:00:00.15min.usgsTimeSlice.ncdf\nbf8e652053d720f2080666a51f97bbfa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_05:15:00.15min.usgsTimeSlice.ncdf\na59a1360c55b0da85ba63eb5f495cd59  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_05:30:00.15min.usgsTimeSlice.ncdf\n6ade0605a64bfcaa6edc64eb5d5b1066  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_05:45:00.15min.usgsTimeSlice.ncdf\n4db74f0e2f48788d427c7378ac8d48ba  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_06:00:00.15min.usgsTimeSlice.ncdf\n4313f16a3400ca4a828dc710f178149c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_06:15:00.15min.usgsTimeSlice.ncdf\n9e616140a70576e172e80840e5aae08c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_06:30:00.15min.usgsTimeSlice.ncdf\nc2a44d384fb9617a4a2b231b27f80719  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_06:45:00.15min.usgsTimeSlice.ncdf\ne29c7e9e8a909418eee967db4bcdec17  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_07:00:00.15min.usgsTimeSlice.ncdf\n12dc1c6955a0cd98af505305b5875c32  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_07:15:00.15min.usgsTimeSlice.ncdf\neef8af06da2df90908be9793f9c1bcea  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_07:30:00.15min.usgsTimeSlice.ncdf\n0752645a3c9fc3649d1102cf1aacd9a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_07:45:00.15min.usgsTimeSlice.ncdf\nd2730820586f1b813b2f8220d89f0786  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_08:00:00.15min.usgsTimeSlice.ncdf\n1b53b5d89ec775570982c9e32ee2be7f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_08:15:00.15min.usgsTimeSlice.ncdf\n839107137f70e173a5aaa10de18d5b82  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_08:30:00.15min.usgsTimeSlice.ncdf\n3c14ab562c7eef4702cc7e7a852a2fd7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_08:45:00.15min.usgsTimeSlice.ncdf\n55f7b37a07fc0b1b21550a01b5d20242  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_09:00:00.15min.usgsTimeSlice.ncdf\n077495c63f8370263d0046298f52dbd1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_09:15:00.15min.usgsTimeSlice.ncdf\nf463bdc1c69f5f8db6a750f3e653fadc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_09:30:00.15min.usgsTimeSlice.ncdf\n659b49a454521f0fd1bdeeaf2532dfe2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_09:45:00.15min.usgsTimeSlice.ncdf\n51317576a42f59601bef977536b60fa7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_10:00:00.15min.usgsTimeSlice.ncdf\n7376eb0c92d2581a136c1b06faeb60fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_10:15:00.15min.usgsTimeSlice.ncdf\n3f5b2afea32dd74ad3e329826e0cea2e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_10:30:00.15min.usgsTimeSlice.ncdf\nd2699278481df15440e7b3cc3eb929b4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_10:45:00.15min.usgsTimeSlice.ncdf\n4eccd1b8d740d489ae34ca671999127e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_11:00:00.15min.usgsTimeSlice.ncdf\n7d9072581db6b78a59e2c95a4b73178c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_11:15:00.15min.usgsTimeSlice.ncdf\ncf5cbd01499fb9fda91a04a14c4e5f2b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_11:30:00.15min.usgsTimeSlice.ncdf\n2f6560075f3c4988e11c2c4c5182cb78  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_11:45:00.15min.usgsTimeSlice.ncdf\n16df9dbb4de208236366be99d7314cca  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_12:00:00.15min.usgsTimeSlice.ncdf\n78670a07f66729aa9733f26ae8d3bfc3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_12:15:00.15min.usgsTimeSlice.ncdf\nf0095e347f1672005f074d9b5a83a79c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_12:30:00.15min.usgsTimeSlice.ncdf\n131bb6de40e6938a241b3532ac8e373b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_12:45:00.15min.usgsTimeSlice.ncdf\nb1934c6716c80ee55bfe9fde918cb915  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_13:00:00.15min.usgsTimeSlice.ncdf\n2ccbe86d1e4d45b56c26acf09f287184  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_13:15:00.15min.usgsTimeSlice.ncdf\n1b75f481103e13cc5ddb7d973f9fd8b6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_13:30:00.15min.usgsTimeSlice.ncdf\n758ca3e0f777ffcbdfa20e62c5b5b329  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_13:45:00.15min.usgsTimeSlice.ncdf\n129537dbabc1ad40d353d7d48bcb0f7c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_14:00:00.15min.usgsTimeSlice.ncdf\n8fc9859835c5a142c6069d52d388ed79  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_14:15:00.15min.usgsTimeSlice.ncdf\n7b95e4c244cf36d5609536c85e866386  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_14:30:00.15min.usgsTimeSlice.ncdf\n21231391fe687c607f1376b59c3fa517  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_14:45:00.15min.usgsTimeSlice.ncdf\n1f287e5436b60ac9e540806f2282eceb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_15:00:00.15min.usgsTimeSlice.ncdf\n724705634a1c5c8bd01c8c0c94f7f73d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_15:15:00.15min.usgsTimeSlice.ncdf\nc4e30f9db48ff03679722fba93c4d937  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_15:30:00.15min.usgsTimeSlice.ncdf\n2f4ba40b5cac1d65c04d9cf8e8edfe52  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_15:45:00.15min.usgsTimeSlice.ncdf\n7a3c7e13824ca59be193a07c3f2f0e63  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_16:00:00.15min.usgsTimeSlice.ncdf\nedf44ea77eeb0d14b07538d3dc03c35d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_16:15:00.15min.usgsTimeSlice.ncdf\nb8a36b8ce91e04c55f8b55628866c8b9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_16:30:00.15min.usgsTimeSlice.ncdf\nbe1f0be610d366518cc4c570167a2ce4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_16:45:00.15min.usgsTimeSlice.ncdf\ndee9cf6bda982f6dafc17b8da511cb13  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_17:00:00.15min.usgsTimeSlice.ncdf\n31b9aed199c354ac53f747769be80422  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_17:15:00.15min.usgsTimeSlice.ncdf\nca631d32bf809b093f7a5ff8b2b210d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_17:30:00.15min.usgsTimeSlice.ncdf\ne9905eda4195b8822dcf62ee0569d41f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_17:45:00.15min.usgsTimeSlice.ncdf\n97939803bb5be585f7222d4b1fd57e47  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_18:00:00.15min.usgsTimeSlice.ncdf\n67a21dab4de64e9db0a80a276ad03a8c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_18:15:00.15min.usgsTimeSlice.ncdf\na0db349f56e427fd1566a5b984027d90  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_18:30:00.15min.usgsTimeSlice.ncdf\ne6c31b4e473ef888798d1d1d41e7393a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_18:45:00.15min.usgsTimeSlice.ncdf\n413d46b0b0a4df1c1f7ac8d14befde54  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_19:00:00.15min.usgsTimeSlice.ncdf\n973f0fe9edbe3e5ff08ef5d676dffe6b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_19:15:00.15min.usgsTimeSlice.ncdf\n29ff2da2406d54f7bfa288f42e8303e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_19:30:00.15min.usgsTimeSlice.ncdf\nec1c07934ef4482d33908f098b5c274d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_19:45:00.15min.usgsTimeSlice.ncdf\n447e3c98462265079d20f258c61fa9f8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_20:00:00.15min.usgsTimeSlice.ncdf\n83b61dc5973e5ad1014717d0da9f7b3f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_20:15:00.15min.usgsTimeSlice.ncdf\n64bd769aaac01423c70235f3153c368b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_20:30:00.15min.usgsTimeSlice.ncdf\n847e2a2026a4e711424c2995185b1398  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_20:45:00.15min.usgsTimeSlice.ncdf\n1a2669942f186ae1273cd61bccea31f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_21:00:00.15min.usgsTimeSlice.ncdf\n095d529eedfec198f2fb0458de2cf4eb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_21:15:00.15min.usgsTimeSlice.ncdf\n31d32b17721c883c3fd6eb36ea84f9be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_21:30:00.15min.usgsTimeSlice.ncdf\ncc54a9b819388215ac7579f00f38bb3f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_21:45:00.15min.usgsTimeSlice.ncdf\nea91af6821991648521d3bc6a4ecea71  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_22:00:00.15min.usgsTimeSlice.ncdf\n4f5af10738568a149d32b331078586cd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_22:15:00.15min.usgsTimeSlice.ncdf\n6e3799ed3e85d63b9cfe011f711a044f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_22:30:00.15min.usgsTimeSlice.ncdf\nc2328c338af7f4ea2d32bd6e992dacbd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_22:45:00.15min.usgsTimeSlice.ncdf\nc19bdcea7f33f68c466b9fcc74451f05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_23:00:00.15min.usgsTimeSlice.ncdf\nd4074e7417a074ac1240fe68f92689d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_23:15:00.15min.usgsTimeSlice.ncdf\n65cb6fa10b4e8ded84f5bf86250159a6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_23:30:00.15min.usgsTimeSlice.ncdf\ndde8235736adc1313fe3feed3851e1f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_23:45:00.15min.usgsTimeSlice.ncdf\ndc44e8838cab0e45a4de8c2f21228a3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_00:00:00.15min.usgsTimeSlice.ncdf\ndfa88b9376261865898de285684c100c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_00:15:00.15min.usgsTimeSlice.ncdf\n2017f8142b7548c32354e90ceba6624c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_00:30:00.15min.usgsTimeSlice.ncdf\n59e537f84bec14de1932a66e7f098977  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_00:45:00.15min.usgsTimeSlice.ncdf\n97221f9d392c09d1a4f4b15c800ee498  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_01:00:00.15min.usgsTimeSlice.ncdf\nbe10207562470756ec874de82d0c5f00  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_01:15:00.15min.usgsTimeSlice.ncdf\neacb4dcdcbad44270ec4fa26779a0572  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_01:30:00.15min.usgsTimeSlice.ncdf\na5bb1bfbcf7662439029a8121e9f1a06  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_01:45:00.15min.usgsTimeSlice.ncdf\n623ea1954dc4b6eae66722cc799e04d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_02:00:00.15min.usgsTimeSlice.ncdf\n984187932c903bd4a3e7eaa7ba7f5235  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_02:15:00.15min.usgsTimeSlice.ncdf\ne97ff3250b5ee541145f7ef0992b3596  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_02:30:00.15min.usgsTimeSlice.ncdf\nac77ef2d9ff167586fb652bc2f6ff004  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_02:45:00.15min.usgsTimeSlice.ncdf\nb83771b656d050fc1b39ab70ce19ee42  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_03:00:00.15min.usgsTimeSlice.ncdf\nfb9ff4c3b15d5898794f035a9a7bb3d3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_03:15:00.15min.usgsTimeSlice.ncdf\n0fd64bc23326b5b00a6280ba742a7ab0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_03:30:00.15min.usgsTimeSlice.ncdf\nfd328a8f46cd592cb6e73d1159b223c4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_03:45:00.15min.usgsTimeSlice.ncdf\nb9a4a252decb657b2d99cc02a97f5bf7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_04:00:00.15min.usgsTimeSlice.ncdf\nee5a3c630538b82f4e4e24f0d68ca469  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_04:15:00.15min.usgsTimeSlice.ncdf\n8fd1d6af74c4410a766ddfc8c4e170ec  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_04:30:00.15min.usgsTimeSlice.ncdf\n27c3c14787b1403a610370aaa43b7e5f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_04:45:00.15min.usgsTimeSlice.ncdf\n6169c55f51d91634ef92a6b616e46739  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_05:00:00.15min.usgsTimeSlice.ncdf\n70a8ab71783ad7f9f3ec40aaeffc5a0d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_05:15:00.15min.usgsTimeSlice.ncdf\n3286c0d6f936bb9f5e631fa9a3f68995  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_05:30:00.15min.usgsTimeSlice.ncdf\n4cc525e3ff38c9079601039163a01cb7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_05:45:00.15min.usgsTimeSlice.ncdf\n4faf76d466409fda19ca90ea56e0b2b2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_06:00:00.15min.usgsTimeSlice.ncdf\ne0d4bbed0fa318ae8ce8a7f0f31aff11  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_06:15:00.15min.usgsTimeSlice.ncdf\nf4e7dad0ff32e91c56262c018aa57122  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_06:30:00.15min.usgsTimeSlice.ncdf\n09fecb739ee1905688bbdd811489d946  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_06:45:00.15min.usgsTimeSlice.ncdf\n8d9c8bde51467e4b083124ab53c991a1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_07:00:00.15min.usgsTimeSlice.ncdf\n1a19a65bbe0c66abc56a02be11edf23e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_07:15:00.15min.usgsTimeSlice.ncdf\n08620044e39a19e7d6331e1b1e890750  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_07:30:00.15min.usgsTimeSlice.ncdf\n5e451c010c1a87574f14863c32db421a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_07:45:00.15min.usgsTimeSlice.ncdf\n778612d94927329ef6fba8589b318c89  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_08:00:00.15min.usgsTimeSlice.ncdf\n0e24940dffac5f682d9a9e620075aa5f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_08:15:00.15min.usgsTimeSlice.ncdf\na48f36ee6fe0d85a91c13526ccdea9f9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_08:30:00.15min.usgsTimeSlice.ncdf\nb6eefdd6ccdc3dd215872ca5f72e60b1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_08:45:00.15min.usgsTimeSlice.ncdf\nec0f909df45b96bb0137d872b936e79e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_09:00:00.15min.usgsTimeSlice.ncdf\n3dd682b61640a66ea72bbceb1f9ba99b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_09:15:00.15min.usgsTimeSlice.ncdf\n2ab9a8abd852754096f627dcfed94668  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_09:30:00.15min.usgsTimeSlice.ncdf\n7293b8f38c3349d88d378e5a7d25be89  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_09:45:00.15min.usgsTimeSlice.ncdf\n230920721a611794cf77455a42524486  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_10:00:00.15min.usgsTimeSlice.ncdf\nf2d4affaa944a5ff0be0de50655771d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_10:15:00.15min.usgsTimeSlice.ncdf\ne87084619ba19e2d224af34bc3237ecd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_10:30:00.15min.usgsTimeSlice.ncdf\n193b22d8a6d9a56ac6cfa39a3fd411fa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_10:45:00.15min.usgsTimeSlice.ncdf\nb57d017086aca0cc3abf739c0355f0f8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_11:00:00.15min.usgsTimeSlice.ncdf\na79e08ccd0d1a9681962105a7436dc1c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_11:15:00.15min.usgsTimeSlice.ncdf\n58e93f309dde41a1babea28a46339a44  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_11:30:00.15min.usgsTimeSlice.ncdf\n3bd17c8545680af7f0fa8961ff41a428  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_11:45:00.15min.usgsTimeSlice.ncdf\nb63846e6ab178acdbd8ece77a905bc82  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_12:00:00.15min.usgsTimeSlice.ncdf\n27ac54b22731c9669524c38f7b406cc6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_12:15:00.15min.usgsTimeSlice.ncdf\nb9af2afda37e6a208941eb72e2e3f02b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_12:30:00.15min.usgsTimeSlice.ncdf\ndd1d96d81a2fca4f66af5af6cea89a6e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_12:45:00.15min.usgsTimeSlice.ncdf\n750d278338e68250cd10a2557d18abf2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_13:00:00.15min.usgsTimeSlice.ncdf\ned3676db0a3cc61cf7facbb15a5db25d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_13:15:00.15min.usgsTimeSlice.ncdf\nf434b55de7644be29592c891680abc38  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_13:30:00.15min.usgsTimeSlice.ncdf\nec78c19d28b06ca56142c2b2a043a537  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_13:45:00.15min.usgsTimeSlice.ncdf\n4583c87887c6c964b30901bea55b763f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_14:00:00.15min.usgsTimeSlice.ncdf\ne816e1cef03c501f10c18afd83d3ed8d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_14:15:00.15min.usgsTimeSlice.ncdf\n05d1b183a4bf09c8bbc7360885aa2146  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_14:30:00.15min.usgsTimeSlice.ncdf\n20c9f478cfddf79bb12fa9d5729fc78a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_14:45:00.15min.usgsTimeSlice.ncdf\n9a6e55dfc983c527fcba9df0bc3619d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_15:00:00.15min.usgsTimeSlice.ncdf\n7449e201d19a2589d299a8f9332e5eb7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_15:15:00.15min.usgsTimeSlice.ncdf\nec5834b17b6f018d626791a301cced8a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_15:30:00.15min.usgsTimeSlice.ncdf\ndf7e0f4ca52b126291b6699fb25ceb01  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_15:45:00.15min.usgsTimeSlice.ncdf\n2a5eb39eb55e555603c940a1c5d0d87c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_16:00:00.15min.usgsTimeSlice.ncdf\n4c0a11cc5757b07a28abb3e1205f0734  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_16:15:00.15min.usgsTimeSlice.ncdf\n36232b2cb3c657c78a54335b5bf09705  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_16:30:00.15min.usgsTimeSlice.ncdf\n048c83f531f8e2e93c010270f6df60f5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_16:45:00.15min.usgsTimeSlice.ncdf\n8c78f21c2ae68d884bd12331b00d4bb1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_17:00:00.15min.usgsTimeSlice.ncdf\n9492a97a747b70a0c75c792038560012  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_17:15:00.15min.usgsTimeSlice.ncdf\nbd68585d487627df5a8b67931343caba  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_17:30:00.15min.usgsTimeSlice.ncdf\nd154bf5792f5a84d64a5573f19349156  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_17:45:00.15min.usgsTimeSlice.ncdf\na97666715ed0a091548ef5670156d1a8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_18:00:00.15min.usgsTimeSlice.ncdf\nc7f97bebcf927da8229ab0ad1dd34c52  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_18:15:00.15min.usgsTimeSlice.ncdf\n5726269c46a6eb5f7c75d5b9b1dea3f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_18:30:00.15min.usgsTimeSlice.ncdf\ncff1cb4bf193f883a5b94f10049fcbed  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_18:45:00.15min.usgsTimeSlice.ncdf\nddb3e78000ccd59fbb6dc7dda8357eed  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_19:00:00.15min.usgsTimeSlice.ncdf\nb05776c567a41229415feb06ccb608c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_19:15:00.15min.usgsTimeSlice.ncdf\nd1705d8eebf0ac7ccb86e1cb9ec75927  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_19:30:00.15min.usgsTimeSlice.ncdf\n4056b56d16820db4d9994ac98cc4467c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_19:45:00.15min.usgsTimeSlice.ncdf\nb03aa9f9b6e16cdd8caa55fae597e5c3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_20:00:00.15min.usgsTimeSlice.ncdf\ndf3363ee819e0a67d4fe09291e844795  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_20:15:00.15min.usgsTimeSlice.ncdf\n8b77f0d3085ea67534e31bfb42846849  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_20:30:00.15min.usgsTimeSlice.ncdf\n7ccee0d0335aa05666e9412d74ccdaa4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_20:45:00.15min.usgsTimeSlice.ncdf\na6c568ef67a2e24622ff392d42377240  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_21:00:00.15min.usgsTimeSlice.ncdf\nd847bdc30559d60b8098c169f69e51f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_21:15:00.15min.usgsTimeSlice.ncdf\n3d40d10d665d891e9f7736aefe0c3d0a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_21:30:00.15min.usgsTimeSlice.ncdf\n1135ca9fb1e97478dfb29485ed2845ea  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_21:45:00.15min.usgsTimeSlice.ncdf\n1787490bfb0ec46aacc7cc1a835ef8f0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_22:00:00.15min.usgsTimeSlice.ncdf\n3a752c16ba354049dae762da57ef5c43  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_22:15:00.15min.usgsTimeSlice.ncdf\nb33691c43b7c85da524dedd288fe27ba  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_22:30:00.15min.usgsTimeSlice.ncdf\n69cf74c008b2cb93d0ad8a9e2086d3cb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_22:45:00.15min.usgsTimeSlice.ncdf\n57b7b9983b1c8baf02db8ff45e25cf70  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_23:00:00.15min.usgsTimeSlice.ncdf\n0cb6e5f0a85d12c52f4d0c023f583d16  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_23:15:00.15min.usgsTimeSlice.ncdf\n596f770b97dd7485f2942df44a67712d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_23:30:00.15min.usgsTimeSlice.ncdf\na33a0bf90265a353b35ee1551ccf9aa2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_23:45:00.15min.usgsTimeSlice.ncdf\n75f1519633266da6c1f78bc99feff06f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_00:00:00.15min.usgsTimeSlice.ncdf\n1ecdfc2d0e9a70a4cd68a246d8553286  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_00:15:00.15min.usgsTimeSlice.ncdf\n990a3546d33969011d4093b1b2e02ce7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_00:30:00.15min.usgsTimeSlice.ncdf\ncd6867f3632c7498c942533aeb3890d1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_00:45:00.15min.usgsTimeSlice.ncdf\n223897c03d0904e77f819444e9fcf530  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_01:00:00.15min.usgsTimeSlice.ncdf\n0222cad4c5e2f0911087a55e8614dbb2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_01:15:00.15min.usgsTimeSlice.ncdf\n23c62d83795bd511af9bacfe95009386  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_01:30:00.15min.usgsTimeSlice.ncdf\n609bbe93974c8ef19dd1924edcd4c8b3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_01:45:00.15min.usgsTimeSlice.ncdf\nd5dfeafc8bb374a851a69f57c03942f7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_02:00:00.15min.usgsTimeSlice.ncdf\n20e1cd41a76132939fc334ea919a5166  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_02:15:00.15min.usgsTimeSlice.ncdf\nacab9d4bc19e7dcb8e69644e95433553  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_02:30:00.15min.usgsTimeSlice.ncdf\n652a488c328d08aaa51d5844561642aa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_02:45:00.15min.usgsTimeSlice.ncdf\n705d29489503dfe4030fc2519c0fef76  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_03:00:00.15min.usgsTimeSlice.ncdf\nad8417cea332ed79c880a859ef020e3a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_03:15:00.15min.usgsTimeSlice.ncdf\ne67d74372e4e2a812404845e3d6e3d4e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_03:30:00.15min.usgsTimeSlice.ncdf\n5ad0b501e40696e2fd162fb485fcd170  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_03:45:00.15min.usgsTimeSlice.ncdf\n5ab62a12b5f7bae5f664e1334e1633d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_04:00:00.15min.usgsTimeSlice.ncdf\nf8bb1f2b7a44b3c985b21752fb9ec603  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_04:15:00.15min.usgsTimeSlice.ncdf\n38926d9369468f50f61a0ff2fe596de5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_04:30:00.15min.usgsTimeSlice.ncdf\n69d30ac1c418d55f08b0268788d54c58  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_04:45:00.15min.usgsTimeSlice.ncdf\n0652802caaa9ce45272fd9f8082be224  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_05:00:00.15min.usgsTimeSlice.ncdf\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/hydro.namelist",
    "content": "&hydro_nlist\n    aggfactrt = 4\n    channel_option = 2\n    chanobs_domain = 1\n    chanrtswcrt = 1\n    chrtout_domain = 1\n    chrtout_grid = 1\n    compound_channel = .true.\n    dtrt_ch = 300\n    dtrt_ter = 10\n    dxrt = 250\n    frxst_pts_out = 0\n    geo_finegrid_flnm = './NWM/DOMAIN/Fulldom_hires.nc'\n    geo_static_flnm = './NWM/DOMAIN/geo_em.d01.nc'\n    gw_restart = 1\n    gwbaseswcrt = 4\n    gwbuckparm_file = './NWM/DOMAIN/GWBUCKPARM.nc'\n    hydrotbl_f = './NWM/DOMAIN/hydro2dtbl.nc'\n    igrid = 1\n    io_config_outputs = 0\n    io_form_outputs = 4\n    land_spatial_meta_flnm = './NWM/DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata.nc'\n    lsmout_domain = 1\n    nsoil = 4\n    order_to_write = 1\n    out_dt = 60\n    outlake = 1\n    output_channelbucket_influx = 0\n    output_gw = 1\n    ovrtswcrt = 1\n    reservoir_persistence_usgs = .false.\n    restart_file = './NWM/RESTART/HYDRO_RST.2011-08-26_00:00_DOMAIN1'\n    route_lake_f = './NWM/DOMAIN/LAKEPARM.nc'\n    route_link_f = './NWM/DOMAIN/Route_Link.nc'\n    rst_bi_in = 0\n    rst_bi_out = 0\n    rst_dt = 1440\n    rst_typ = 1\n    rstrt_swc = 0\n    rt_option = 1\n    rtout_domain = 1\n    split_output_count = 1\n    subrtswcrt = 1\n    sys_cpl = 1\n    t0outputflag = 1\n    udmap_file = './NWM/DOMAIN/spatialweights.nc'\n    udmp_opt = 1\n    zsoil8 = -0.1, -0.4, -1.0, -2.0\n/\n\n&nudging_nlist\n    biaswindowbeforet0 = .false.\n    invdisttimeweightbias = .true.\n    maxagepairsbiaspersist = 3\n    minnumpairsbiaspersist = 1\n    nlastobs = 480\n    noconstinterfbias = .false.\n    nudginglastobsfile = './NWM/RESTART/nudgingLastObs.2011-08-26_00:00:00.nc'\n    nudgingparamfile = './NWM/DOMAIN/nudgingParams.nc'\n    persistbias = .true.\n    readtimesliceparallel = .true.\n    temporalpersistence = .true.\n    timeslicepath = './NWM/nudgingTimeSliceObs/'\n/\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_ana/namelist.hrldas",
    "content": "&noahlsm_offline\n    btr_option = 1\n    canopy_stomatal_resistance_option = 1\n    dynamic_veg_option = 4\n    forcing_timestep = 3600\n    frozen_soil_option = 1\n    glacier_option = 2\n    hrldas_setup_file = './NWM/DOMAIN/wrfinput_d01.nc'\n    indir = './FORCING'\n    khour = 144\n    noah_timestep = 3600\n    nsoil = 4\n    outdir = './'\n    output_timestep = 3600\n    pcp_partition_option = 1\n    radiative_transfer_option = 3\n    restart_filename_requested = './NWM/RESTART/RESTART.2011082600_DOMAIN1'\n    restart_frequency_hours = 24\n    rst_bi_in = 0\n    rst_bi_out = 0\n    runoff_option = 3\n    snow_albedo_option = 1\n    soil_thick_input = 0.1, 0.3, 0.6, 1.0\n    spatial_filename = './NWM/DOMAIN/soil_properties.nc'\n    split_output_count = 1\n    start_day = 26\n    start_hour = 0\n    start_min = 0\n    start_month = 8\n    start_year = 2011\n    supercooled_water_option = 1\n    surface_drag_option = 1\n    surface_resistance_option = 4\n    tbot_option = 2\n    temp_time_scheme_option = 3\n    zlvl = 10.0\n/\n\n&wrf_hydro_offline\n    forc_typ = 1\n/\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/FORCING.md5",
    "content": "99a8c6447c0c9c0c5aca99c25e0869f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082600.LDASIN_DOMAIN1\na7ec3fac9bae35e691eb23efd96bd4bf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082601.LDASIN_DOMAIN1\n043d9b6378933dc6f2f11f513bd68a26  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082602.LDASIN_DOMAIN1\n7f08dd26dadca4dd2f49a501de42c584  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082603.LDASIN_DOMAIN1\n3b2dbff098887c10f82d847ba8359e0c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082604.LDASIN_DOMAIN1\n46837e3d47b7e989c2a911568b6d855a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082605.LDASIN_DOMAIN1\n4aca3beef639ac47f98c6c101d0430e3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082606.LDASIN_DOMAIN1\n7bb2d2d8340cf6c7f42127f2f523bc9a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082607.LDASIN_DOMAIN1\n7938a5207b66fbafb63b9a75c6537d03  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082608.LDASIN_DOMAIN1\n48e1e575c43044fd6e53bb0e356c4cbf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082609.LDASIN_DOMAIN1\n606f68fddfe74aa2f7df8ce8939bc430  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082610.LDASIN_DOMAIN1\n4127ef0a592efa219bd316a79e4da3ad  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082611.LDASIN_DOMAIN1\n6ea43af5b6d0e8470bbee99501dc58e2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082612.LDASIN_DOMAIN1\nc4976e2d3c2120eca05d8da0a3aa460f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082613.LDASIN_DOMAIN1\ne25a7fb95772bf88f34a537e357446a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082614.LDASIN_DOMAIN1\n03ac9b352d76885d6ac637697ee6b0d3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082615.LDASIN_DOMAIN1\n88b5a8477ec8bed99aee62f22614cc6d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082616.LDASIN_DOMAIN1\nf2c4b95dc217248eec44a1cbdfa4ffb4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082617.LDASIN_DOMAIN1\n2798daf701dbfedb2a64e5d342954665  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082618.LDASIN_DOMAIN1\n622e919b18db2d37fcf3c680d61c89ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082619.LDASIN_DOMAIN1\n897a6450d5f251e0e0487ff5f1f02884  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082620.LDASIN_DOMAIN1\n05722c6dcaf58fdbe88dddcf08d4a5c6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082621.LDASIN_DOMAIN1\n5a067a738ed9ff63c47ea204ab30a301  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082622.LDASIN_DOMAIN1\na3c3c5f5d89595e1107335a91c476330  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082623.LDASIN_DOMAIN1\nf9aa2a3dfbcbe06d720fb1ba3a19c758  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082700.LDASIN_DOMAIN1\ndc7b647dac35f1dc8ce28a9f898f4c8b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082701.LDASIN_DOMAIN1\nf5cf666e8db8bbbcfb05c0ca18c4796f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082702.LDASIN_DOMAIN1\n5ef840b37eace005da387e43767efc65  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082703.LDASIN_DOMAIN1\nac9d2186d75f7278d059a555ec58e481  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082704.LDASIN_DOMAIN1\nc2887fdaa503ff9718af2c38b18b9424  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082705.LDASIN_DOMAIN1\n6fffb7cdc5ab018c639f73d97e1463a1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082706.LDASIN_DOMAIN1\nb26e322e7c8e9b3f9c5cc9dfeb489fbd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082707.LDASIN_DOMAIN1\nb2f898ce5e4ede92262dca2ad38fdec2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082708.LDASIN_DOMAIN1\nf5f470bbfd206ef66aecdca695476b5e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082709.LDASIN_DOMAIN1\n0de09110d753d0e229c2557b58429ada  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082710.LDASIN_DOMAIN1\n2699c31125965d8be001812687821e9f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082711.LDASIN_DOMAIN1\n85d44fee9f432097660b63f89c60dbe7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082712.LDASIN_DOMAIN1\n7379a35eb28a5738081ab7419256b5fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082713.LDASIN_DOMAIN1\n4b6e09dd13686c5dfa10d786a5719060  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082714.LDASIN_DOMAIN1\n961c54de44ae4b59338814690517b477  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082715.LDASIN_DOMAIN1\nb395fa2fe5ebc53def279c1956cec3b8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082716.LDASIN_DOMAIN1\nd3cfde720203407c9abcc5f4cbfe3cf4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082717.LDASIN_DOMAIN1\n17cadbd78e6f37d016da7dfa77237ca7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082718.LDASIN_DOMAIN1\nac1d343818b41d43df11473b39e74acd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082719.LDASIN_DOMAIN1\nf795066b8432a404ff6600e1885e2587  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082720.LDASIN_DOMAIN1\n49a2865148c137414274949b122f7bbd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082721.LDASIN_DOMAIN1\neca4d48ad1911e014e9ee87e1e176a4a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082722.LDASIN_DOMAIN1\n6b6b54677644ee45ff7cb84026697ab2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082723.LDASIN_DOMAIN1\n94f04773a72f9324118b6402a5c7983f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082800.LDASIN_DOMAIN1\n20716745758534f5188733f4114a62c9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082801.LDASIN_DOMAIN1\nfb8404b70989297dde2c46828d9119a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082802.LDASIN_DOMAIN1\ne8a188e0355a4795a8663216f4afe2fb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082803.LDASIN_DOMAIN1\nde05c2b564ddc3e856fb53fea176a35b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082804.LDASIN_DOMAIN1\n4a12407d24391d8aa7fe3dc64f99afa5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082805.LDASIN_DOMAIN1\n3c2e87cfdb74551303ebe1c9aad01f7f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082806.LDASIN_DOMAIN1\na47772511a16ea0db767f6ecde797231  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082807.LDASIN_DOMAIN1\n7ccb5dad179b396874ac95b3065edb7f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082808.LDASIN_DOMAIN1\n99e743da1a400fd05fec9f70bcff165f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082809.LDASIN_DOMAIN1\n47383fb5aa70a79dfe3dad94fb710491  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082810.LDASIN_DOMAIN1\n464fdc143d790bbb3cd6bef62eb17a2f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082811.LDASIN_DOMAIN1\n01386a8dfe531d65d0678dda20a17cd6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082812.LDASIN_DOMAIN1\n5989e779a5b1d6a3d37cf447cedbe3f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082813.LDASIN_DOMAIN1\n86b6cb4c6e0cb7d9cd48ce56f7a75b24  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082814.LDASIN_DOMAIN1\n1efb80167e46e2d5da26363be87f0c33  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082815.LDASIN_DOMAIN1\neaed7529c11dca13c255de20e9b8fcab  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082816.LDASIN_DOMAIN1\n7a8f616cedf0a030068d3e812306bab2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082817.LDASIN_DOMAIN1\n5ab75846498cc9f9b04a1dd0650999c4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082818.LDASIN_DOMAIN1\n2b7b57458510b978cb912efedfbef3a4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082819.LDASIN_DOMAIN1\n119b11361c4c7007ab48e799a8f33466  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082820.LDASIN_DOMAIN1\n309f87c9aa163bc81de198cf366391da  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082821.LDASIN_DOMAIN1\naedc76c3fe739ef8c0a679af64d66373  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082822.LDASIN_DOMAIN1\n2099bc847c251bfaab889501eef79d4b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082823.LDASIN_DOMAIN1\nc73a1623c8c1e709e7be917e6b4139be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082900.LDASIN_DOMAIN1\nb03f08302dcd464eb6450e744354e52d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082901.LDASIN_DOMAIN1\n67dd130308c1b727c3ae64c919620ff7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082902.LDASIN_DOMAIN1\na60b00233f1a0b1890242d154d8ecebf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082903.LDASIN_DOMAIN1\nd6b800167cf67cc3b4968187f7de5db7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082904.LDASIN_DOMAIN1\n71c550bf0fcaeb793f84c20f74b7369d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082905.LDASIN_DOMAIN1\n151ee5cca8893672b437c3be8e235ffc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082906.LDASIN_DOMAIN1\n9b8ee27c04db34ebe251d3ab83c82c34  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082907.LDASIN_DOMAIN1\n85ea64ad2b1cf018a7369dfd004af04f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082908.LDASIN_DOMAIN1\n27f010063f59ca876eb814768b7acac7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082909.LDASIN_DOMAIN1\n3ba072f831a565c8bd26888e21c5ea69  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082910.LDASIN_DOMAIN1\ndbfee7d238399151d96d5f17ae5969e7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082911.LDASIN_DOMAIN1\n3a6f8d26d4f0616657d0117360ba6511  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082912.LDASIN_DOMAIN1\n31ed9be02de650dc4b32c5e775663a76  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082913.LDASIN_DOMAIN1\n07269089bb3bc34ea00466f010be9adb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082914.LDASIN_DOMAIN1\n7e5e28c49c7b5dc3604ff9da66084183  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082915.LDASIN_DOMAIN1\n93abe024b7b83f316faf5ffcc086da0f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082916.LDASIN_DOMAIN1\na7e2bcb0d3d44ed95f797d8e34fcda8e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082917.LDASIN_DOMAIN1\n73f1af91b039e2705cca0697234ca0fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082918.LDASIN_DOMAIN1\n5cc5b1a8aa04b7cace1a3a7c929fc9a8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082919.LDASIN_DOMAIN1\n3bccc6f3fb189411e21ae777b5255a67  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082920.LDASIN_DOMAIN1\nc2e2ded8c7b6ea99cb37565ee8cff1f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082921.LDASIN_DOMAIN1\n1473ec957fb67b7d8b04ea0f016af43c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082922.LDASIN_DOMAIN1\n7463caf0cf0d1e1eb83310a42360a765  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011082923.LDASIN_DOMAIN1\nf90e0e05e760f2538c0b16f2317331b8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083000.LDASIN_DOMAIN1\n89c59488d5cab796493a66cd9e3e05ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083001.LDASIN_DOMAIN1\nbbc2e47966d8d0ce4240c0f21397d855  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083002.LDASIN_DOMAIN1\n5c9abf203fde3055e4670293323bb771  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083003.LDASIN_DOMAIN1\n423c5c3dd3fe1bd5cf3e9f5f727daf5d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083004.LDASIN_DOMAIN1\n133779e3625c5ccf6f8929d311fe8286  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083005.LDASIN_DOMAIN1\n7550cdfe6c3f023e0d319af8fe8d73bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083006.LDASIN_DOMAIN1\na7b95345bf58f6a2ed79d3523193cbdc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083007.LDASIN_DOMAIN1\nab07ec42371b4cc65e44f07c42793b78  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083008.LDASIN_DOMAIN1\na4a68ec39f741ae21d701044655f3fd9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083009.LDASIN_DOMAIN1\n5e8400fea1eacdb34a3c4a9e8ea68cbf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083010.LDASIN_DOMAIN1\nfd98b0933141b6e2cadaf6f83a2443c2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083011.LDASIN_DOMAIN1\n41afaf8a9a1a1f24dacb2b499f6961e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083012.LDASIN_DOMAIN1\nbbacb5590e69b1f2a826226bd5b02bf5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083013.LDASIN_DOMAIN1\nb9a42831c5fa1bf47fa7adee39b8ba2f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083014.LDASIN_DOMAIN1\nbd00d627d1994685eddc6584291c5703  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083015.LDASIN_DOMAIN1\n259b202e92f7b23ef15cdc23adf88afc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083016.LDASIN_DOMAIN1\n6280eb7d46da3b799253f47fa82414ec  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083017.LDASIN_DOMAIN1\n0959d9cdab1389b8fdcd325468ee40ec  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083018.LDASIN_DOMAIN1\n0aee383f608f148beee21090efc074c3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083019.LDASIN_DOMAIN1\n2559bbedd3800b1aa3a731fd7c4f1df6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083020.LDASIN_DOMAIN1\n746cf2ffa493910233bb66a04ce7df15  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083021.LDASIN_DOMAIN1\n39445dcd3fd5b4742d2dc5f3e456918b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083022.LDASIN_DOMAIN1\nba3d5da1401b3fb5b3f1f890146eae87  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083023.LDASIN_DOMAIN1\n332a5779ac01b77d18d13d45b16d731b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083100.LDASIN_DOMAIN1\n25a1e5a8fa6b165524f1eb38b61e02bb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083101.LDASIN_DOMAIN1\n7fa830e049c4154459f4971ad482600b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083102.LDASIN_DOMAIN1\n46b8014756b56ec665939bda573833cf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083103.LDASIN_DOMAIN1\n18f066ad10fb2a347102894e66be2d24  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083104.LDASIN_DOMAIN1\n12d3c11cc42fa27093f69db07f9ee765  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083105.LDASIN_DOMAIN1\na7a576e92e97a1db69db1c9503bc9888  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083106.LDASIN_DOMAIN1\naed0c94040b49626f3e6acd39f240d3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083107.LDASIN_DOMAIN1\n2c7fe4946d31922bea5bc3c24038e7b5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083108.LDASIN_DOMAIN1\n1de8c651e88fc6278e6e9258c277bac2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083109.LDASIN_DOMAIN1\n1cf16b50fd969e841be639acfbf04b20  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083110.LDASIN_DOMAIN1\n812e4c48b61d1153eaa504da5fab3c71  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083111.LDASIN_DOMAIN1\ne59a66da1d66d601878f875cf212ba94  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083112.LDASIN_DOMAIN1\n2d2d1f5a1526e96d8256fe234998f4fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083113.LDASIN_DOMAIN1\n68fbfe5963b5965d41f1abe363e2be85  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083114.LDASIN_DOMAIN1\nca28008a027712705e59320485073841  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083115.LDASIN_DOMAIN1\n15fb7890db613b322da8e66683a2436b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083116.LDASIN_DOMAIN1\n040366f4ea7c526433329121b7df3e89  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083117.LDASIN_DOMAIN1\na87ff7d51395e7c37a2176939d7421fb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083118.LDASIN_DOMAIN1\nb187c03674b7686bf861ef2e1a5405b7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083119.LDASIN_DOMAIN1\nc6926510ed58d35d2a2084e395a8bbb5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083120.LDASIN_DOMAIN1\n45e3faffa14ccda0d61304cf35712c44  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083121.LDASIN_DOMAIN1\n34d8a05a86bdfb8b1fbd86da002092f8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083122.LDASIN_DOMAIN1\nc237cde05fcb5d61c982d998629eb494  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011083123.LDASIN_DOMAIN1\n6dc72b6fcebd47539729a2b003737f72  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090100.LDASIN_DOMAIN1\n0bd92afef70ccfea284d2064accbcf1c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090101.LDASIN_DOMAIN1\n05ca6e1997168a9081dcd15a7b41363e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090102.LDASIN_DOMAIN1\n1b69eed07ce7100877e73cab1a8e4e42  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090103.LDASIN_DOMAIN1\n11d997337a248d08e97353478cf154bc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090104.LDASIN_DOMAIN1\n82ee6915fb07555ea1911b6759c8202a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090105.LDASIN_DOMAIN1\n4bcbe23aed193b9ea716f4e2af27ede9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090106.LDASIN_DOMAIN1\n09237d4bf1b81113e78a64adda67f847  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090107.LDASIN_DOMAIN1\n515f9ae88b19b5dc6ce48e84d4931380  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090108.LDASIN_DOMAIN1\n26cec642877dbc76dbfa01800de238fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090109.LDASIN_DOMAIN1\ne10a842db6a1aaceb137e67efe203273  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090110.LDASIN_DOMAIN1\n08d74b96b90de56bc9a003a7ff997869  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090111.LDASIN_DOMAIN1\n80f12471d9e00e678897dd97e9eb4be4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090112.LDASIN_DOMAIN1\n31d95f778a1a39d7a94b7eb31595c3ee  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090113.LDASIN_DOMAIN1\ne4e0c7187d0c0e5754db762d28570cdb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090114.LDASIN_DOMAIN1\n13cf130153e67d94272d7badc9255d01  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090115.LDASIN_DOMAIN1\na1fb54acd3c91479ee9d954a5eb551d1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090116.LDASIN_DOMAIN1\n14f26d1d23ade8ce3f2840f5a107801b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090117.LDASIN_DOMAIN1\n53fb1aabf5ca50de1b09c4490b4ef0b5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090118.LDASIN_DOMAIN1\ndbacbd2f2dc7f90be5366f1a768f4579  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090119.LDASIN_DOMAIN1\n4a19798b8ee1392bf2652f50e2d90fa5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090120.LDASIN_DOMAIN1\n174ae0c519523c34f1ce1f3626c111c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090121.LDASIN_DOMAIN1\n45d480bdf81e9475ba1a987bad8e8404  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090122.LDASIN_DOMAIN1\nec8da8744cbcbef271e585fbf93195b9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090123.LDASIN_DOMAIN1\nc9caf170259cd0cf4a347bd36ede9d4d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/FORCING/2011090200.LDASIN_DOMAIN1\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN/nudgingParams.cdl",
    "content": "netcdf nudgingParams {\ndimensions:\n\tstationIdInd = UNLIMITED ; // (4 currently)\n\tmonthInd = 12 ;\n\tthreshCatInd = 2 ;\n\tthreshInd = 1 ;\n\tstationIdStrLen = 15 ;\nvariables:\n\tfloat G(stationIdInd) ;\n\t\tG:units = \"-\" ;\n\t\tG:long_name = \"Amplitude of nudging\" ;\n\tfloat R(stationIdInd) ;\n\t\tR:units = \"meters\" ;\n\t\tR:long_name = \"Radius of influence in meters\" ;\n\tfloat expCoeff(stationIdInd, monthInd, threshCatInd) ;\n\t\texpCoeff:units = \"minutes\" ;\n\t\texpCoeff:long_name = \"Coefficient b in denominator e^(-dt/b)\" ;\n\tfloat qThresh(stationIdInd, monthInd, threshInd) ;\n\t\tqThresh:units = \"m^3/s\" ;\n\t\tqThresh:long_name = \"Discharge threshold category\" ;\n\tchar stationId(stationIdInd, stationIdStrLen) ;\n\t\tstationId:units = \"-\" ;\n\t\tstationId:long_name = \"USGS station identifer\" ;\n\tfloat tau(stationIdInd) ;\n\t\ttau:units = \"minutes\" ;\n\t\ttau:long_name = \"Time tapering parameter half window size in minutes\" ;\n\n// global attributes:\n\t\t:history = \"Mon Feb  5 13:36:43 2018: ncks -O -d stationIdInd,1,4 /glade/p/nwc/arezoo/test_case/0137462010/nudgingParams.nc /glade/p/nwc/arezoo/test_case/0137462010/nudgingParams.nc\" ;\n\t\t:NCO = \"\\\"4.6.2\\\"\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN/nudgingParams.md5",
    "content": "0dd15ead2501e003d8f745735e71a808  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN/nudgingParams.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/Fulldom_hires.cdl",
    "content": "netcdf Fulldom_hires {\ndimensions:\n\ty = 16 ;\n\tx = 15 ;\nvariables:\n\tshort CHANNELGRID(y, x) ;\n\t\tCHANNELGRID:grid_mapping = \"crs\" ;\n\t\tCHANNELGRID:coordinates = \"x y\" ;\n\t\tCHANNELGRID:long_name = \"CHANNELGRID\" ;\n\t\tCHANNELGRID:units = \"Meter\" ;\n\t\tCHANNELGRID:missing_value = -32768s ;\n\t\tCHANNELGRID:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tbyte FLOWDIRECTION(y, x) ;\n\t\tFLOWDIRECTION:grid_mapping = \"crs\" ;\n\t\tFLOWDIRECTION:coordinates = \"x y\" ;\n\t\tFLOWDIRECTION:long_name = \"FLOWDIRECTION\" ;\n\t\tFLOWDIRECTION:units = \"Meter\" ;\n\t\tFLOWDIRECTION:missing_value = 0b ;\n\t\tFLOWDIRECTION:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tshort LAKEGRID(y, x) ;\n\t\tLAKEGRID:grid_mapping = \"crs\" ;\n\t\tLAKEGRID:coordinates = \"x y\" ;\n\t\tLAKEGRID:long_name = \"LAKEGRID\" ;\n\t\tLAKEGRID:units = \"Meter\" ;\n\t\tLAKEGRID:missing_value = -32768s ;\n\t\tLAKEGRID:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat LATITUDE(y, x) ;\n\t\tLATITUDE:grid_mapping = \"crs\" ;\n\t\tLATITUDE:_CoordinateSystems = \"crs\" ;\n\t\tLATITUDE:long_name = \"latitude coordinate\" ;\n\t\tLATITUDE:units = \"degrees_north\" ;\n\t\tLATITUDE:_CoordinateAxisType = \"Lat\" ;\n\t\tLATITUDE:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tdouble LKSATFAC(y, x) ;\n\t\tLKSATFAC:grid_mapping = \"crs\" ;\n\t\tLKSATFAC:coordinates = \"x y\" ;\n\t\tLKSATFAC:long_name = \"OVROUGHRTFAC\" ;\n\t\tLKSATFAC:units = \"Meter\" ;\n\t\tLKSATFAC:missing_value = -3.402823e+38f ;\n\t\tLKSATFAC:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat LONGITUDE(y, x) ;\n\t\tLONGITUDE:grid_mapping = \"crs\" ;\n\t\tLONGITUDE:_CoordinateSystems = \"crs\" ;\n\t\tLONGITUDE:long_name = \"longitude coordinate\" ;\n\t\tLONGITUDE:units = \"degrees_east\" ;\n\t\tLONGITUDE:_CoordinateAxisType = \"Lon\" ;\n\t\tLONGITUDE:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat OVROUGHRTFAC(y, x) ;\n\t\tOVROUGHRTFAC:grid_mapping = \"crs\" ;\n\t\tOVROUGHRTFAC:coordinates = \"x y\" ;\n\t\tOVROUGHRTFAC:long_name = \"OVROUGHRTFAC\" ;\n\t\tOVROUGHRTFAC:units = \"Meter\" ;\n\t\tOVROUGHRTFAC:missing_value = -3.402823e+38f ;\n\t\tOVROUGHRTFAC:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat RETDEPRTFAC(y, x) ;\n\t\tRETDEPRTFAC:grid_mapping = \"crs\" ;\n\t\tRETDEPRTFAC:coordinates = \"x y\" ;\n\t\tRETDEPRTFAC:long_name = \"RETDEPRTFAC\" ;\n\t\tRETDEPRTFAC:units = \"Meter\" ;\n\t\tRETDEPRTFAC:missing_value = -3.402823e+38f ;\n\t\tRETDEPRTFAC:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tshort STREAMORDER(y, x) ;\n\t\tSTREAMORDER:grid_mapping = \"crs\" ;\n\t\tSTREAMORDER:coordinates = \"x y\" ;\n\t\tSTREAMORDER:long_name = \"STREAMORDER\" ;\n\t\tSTREAMORDER:units = \"Meter\" ;\n\t\tSTREAMORDER:missing_value = -32768s ;\n\t\tSTREAMORDER:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tfloat TOPOGRAPHY(y, x) ;\n\t\tTOPOGRAPHY:long_name = \"GDAL Band Number 1\" ;\n\t\tTOPOGRAPHY:grid_mapping = \"crs\" ;\n\t\tTOPOGRAPHY:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tTOPOGRAPHY:_FillValue = -9999.f ;\n\tshort basn_msk(y, x) ;\n\t\tbasn_msk:grid_mapping = \"crs\" ;\n\t\tbasn_msk:coordinates = \"x y\" ;\n\t\tbasn_msk:long_name = \"basn_msk\" ;\n\t\tbasn_msk:units = \"Meter\" ;\n\t\tbasn_msk:missing_value = -32768s ;\n\t\tbasn_msk:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tchar crs ;\n\t\tcrs:transform_name = \"lambert_conformal_conic\" ;\n\t\tcrs:grid_mapping_name = \"lambert_conformal_conic\" ;\n\t\tcrs:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:spatial_ref = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:long_name = \"CRS definition\" ;\n\t\tcrs:longitude_of_prime_meridian = 0. ;\n\t\tcrs:GeoTransform = \"-2303999.17655 1000.0 0 1919999.66329 0 -1000.0 \" ;\n\t\tcrs:_CoordinateAxes = \"y x\" ;\n\t\tcrs:_CoordinateTransformType = \"Projection\" ;\n\t\tcrs:standard_parallel = 30., 60. ;\n\t\tcrs:longitude_of_central_meridian = -97. ;\n\t\tcrs:latitude_of_projection_origin = 40. ;\n\t\tcrs:false_easting = 0. ;\n\t\tcrs:false_northing = 0. ;\n\t\tcrs:earth_radius = 6370000. ;\n\t\tcrs:semi_major_axis = 6370000. ;\n\t\tcrs:inverse_flattening = 0. ;\n\tshort frxst_pts(y, x) ;\n\t\tfrxst_pts:grid_mapping = \"crs\" ;\n\t\tfrxst_pts:coordinates = \"x y\" ;\n\t\tfrxst_pts:long_name = \"frxst_pts\" ;\n\t\tfrxst_pts:units = \"Meter\" ;\n\t\tfrxst_pts:missing_value = -32768s ;\n\t\tfrxst_pts:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\tdouble x(x) ;\n\t\tx:standard_name = \"projection_x_coordinate\" ;\n\t\tx:long_name = \"x coordinate of projection\" ;\n\t\tx:units = \"m\" ;\n\t\tx:_CoordinateAxisType = \"GeoX\" ;\n\t\tx:resolution = 1000. ;\n\tdouble y(y) ;\n\t\ty:standard_name = \"projection_y_coordinate\" ;\n\t\ty:long_name = \"y coordinate of projection\" ;\n\t\ty:units = \"m\" ;\n\t\ty:_CoordinateAxisType = \"GeoY\" ;\n\t\ty:resolution = 1000. ;\n\n// global attributes:\n\t\t:Conventions = \"CF-1.5\" ;\n\t\t:Source_Software = \"WRF-Hydro GIS Pre-processor v5 (03/2018)\" ;\n\t\t:history = \"Thu Sep  6 17:56:43 2018: ncks -O -d x,4146,4160 -d y,1483,1498 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/Fulldom_hires_netcdf_file_1km_LongRange_NWMv2.0.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/Fulldom_hires.nc\\n\",\n\t\t\t\"Tue Apr 10 15:20:44 2018: ncap2 -O -s LKSATFAC=OVROUGHRTFAC*0.0+1000.0 Fulldom_hires_netcdf_file_1km_NWMv1.1_DEFAULT.nc Fulldom_hires_netcdf_file_1km_NWMv1.1_DEFAULT.nc\\n\",\n\t\t\t\"Fri Nov 11 15:48:10 2016: ncrename -v Band1,TOPOGRAPHY Fulldom_hires_netcdf_file_1km_NWMv1.1_newdem.nc Fulldom_hires_netcdf_file_1km_NWMv1.1_newdem.nc\\n\",\n\t\t\t\"Fri Nov 11 15:47:37 2016: ncks -x -v TOPOGRAPHY Fulldom_hires_netcdf_file_1km_NWMv1.1_newdem.nc Fulldom_hires_netcdf_file_1km_NWMv1.1_newdem.nc\\n\",\n\t\t\t\"Fri Nov 11 15:46:53 2016: ncks -A -v Band1 DEM_working/DEM1km_rclass_Fillnodata_revy.nc Fulldom_hires_netcdf_file_1km_NWMv1.1_newdem.nc\\n\",\n\t\t\t\"Fri Sep 25 11:50:01 2015: ncks -A longitude.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:59 2015: ncks -A latitude.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:58 2015: ncks -A frxst_pts.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:57 2015: ncks -A LAKEGRID.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:56 2015: ncks -A ovroughrtfac.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:55 2015: ncks -A retdeprtfac.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:55 2015: ncks -A gw_basns.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:54 2015: ncks -A str_order.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:53 2015: ncks -A CHANNELGRID.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:53 2015: ncks -A flowdirection.nc Fulldom_hires_netcdf_file.nc\\n\",\n\t\t\t\"Fri Sep 25 11:49:53 2015: ncks topography.nc Fulldom_hires_netcdf_file.nc\" ;\n\t\t:history_of_appended_files = \"Fri Nov 11 15:46:53 2016: Appended file DEM_working/DEM1km_rclass_Fillnodata_revy.nc had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Fri Nov 11 15:44:13 2016: ncpdq -O -a -y DEM1km_rclass_Fillnodata.nc DEM1km_rclass_Fillnodata_revy.nc\\n\",\n\t\t\t\"Fri Nov 11 15:33:22 2016: GDAL CreateCopy( DEM1km_rclass_Fillnodata.nc, ... )\\n\",\n\t\t\t\"\" ;\n\t\t:proj4 = \"+proj=lcc +units=m +a=6370000.0 +b=6370000.0 +lat_1=30.0 +lat_2=60.0 +lat_0=40.0 +lon_0=-97.0 +x_0=0 +y_0=0 +k_0=1.0 +nadgrids=@null +wktext  +no_defs \" ;\n\t\t:processing_notes = \"Created: Tue Jul 31 15:12:16 2018\" ;\n\t\t:GDAL_DataType = \"Generic\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/Fulldom_hires.md5",
    "content": "e9505c9d024b0cebaa7019b609c60351  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/Fulldom_hires.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/GEOGRID_LDASOUT_Spatial_Metadata.cdl",
    "content": "netcdf GEOGRID_LDASOUT_Spatial_Metadata {\ndimensions:\n\tx = 15 ;\n\ty = 16 ;\nvariables:\n\tchar crs ;\n\t\tcrs:transform_name = \"lambert_conformal_conic\" ;\n\t\tcrs:grid_mapping_name = \"lambert_conformal_conic\" ;\n\t\tcrs:esri_pe_string = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:spatial_ref = \"PROJCS[\\\"Lambert_Conformal_Conic\\\",GEOGCS[\\\"GCS_Sphere\\\",DATUM[\\\"D_Sphere\\\",SPHEROID[\\\"Sphere\\\",6370000.0,0.0]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]],PROJECTION[\\\"Lambert_Conformal_Conic_2SP\\\"],PARAMETER[\\\"false_easting\\\",0.0],PARAMETER[\\\"false_northing\\\",0.0],PARAMETER[\\\"central_meridian\\\",-97.0],PARAMETER[\\\"standard_parallel_1\\\",30.0],PARAMETER[\\\"standard_parallel_2\\\",60.0],PARAMETER[\\\"latitude_of_origin\\\",40.0],UNIT[\\\"Meter\\\",1.0]];-35691800 -29075200 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:long_name = \"CRS definition\" ;\n\t\tcrs:longitude_of_prime_meridian = 0. ;\n\t\tcrs:GeoTransform = \"-2303999.17655 1000.0 0 1919999.66329 0 -1000.0 \" ;\n\t\tcrs:_CoordinateAxes = \"y x\" ;\n\t\tcrs:_CoordinateTransformType = \"Projection\" ;\n\t\tcrs:standard_parallel = 30., 60. ;\n\t\tcrs:longitude_of_central_meridian = -97. ;\n\t\tcrs:latitude_of_projection_origin = 40. ;\n\t\tcrs:false_easting = 0. ;\n\t\tcrs:false_northing = 0. ;\n\t\tcrs:earth_radius = 6370000. ;\n\t\tcrs:semi_major_axis = 6370000. ;\n\t\tcrs:inverse_flattening = 0. ;\n\tdouble x(x) ;\n\t\tx:standard_name = \"projection_x_coordinate\" ;\n\t\tx:long_name = \"x coordinate of projection\" ;\n\t\tx:units = \"m\" ;\n\t\tx:_CoordinateAxisType = \"GeoX\" ;\n\t\tx:resolution = 1000. ;\n\tdouble y(y) ;\n\t\ty:standard_name = \"projection_y_coordinate\" ;\n\t\ty:long_name = \"y coordinate of projection\" ;\n\t\ty:units = \"m\" ;\n\t\ty:_CoordinateAxisType = \"GeoY\" ;\n\t\ty:resolution = 1000. ;\n\n// global attributes:\n\t\t:Conventions = \"CF-1.5\" ;\n\t\t:GDAL_DataType = \"Generic\" ;\n\t\t:Source_Software = \"WRF-Hydro GIS Pre-processor v5 (03/2018)\" ;\n\t\t:proj4 = \"+proj=lcc +units=m +a=6370000.0 +b=6370000.0 +lat_1=30.0 +lat_2=60.0 +lat_0=40.0 +lon_0=-97.0 +x_0=0 +y_0=0 +k_0=1.0 +nadgrids=@null +wktext  +no_defs \" ;\n\t\t:history = \"Thu May 23 15:29:28 2019: ncks -O -d x,4146,4160 -d y,1483,1498 /glade/p/cisl/nwc/nwmv20_finals/CONUS/DOMAIN/GEOGRID_LDASOUT_Spatial_Metadata_1km_NWMv2.0.nc /glade/scratch/arezoo/rfc_cutout_basins/Cutout_Basins/Full_Physics//0137462010/GEOGRID_LDASOUT_Spatial_Metadata.nc\\n\",\n\t\t\t\"Created Thu Aug 02 19:39:09 2018\" ;\n\t\t:processing_notes = \"Created: Thu Aug 02 19:38:45 2018\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/GEOGRID_LDASOUT_Spatial_Metadata.md5",
    "content": "fc264e56007475d0780b1f631985d166  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/GEOGRID_LDASOUT_Spatial_Metadata.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/GWBUCKPARM.cdl",
    "content": "netcdf GWBUCKPARM {\ndimensions:\n\tBasinDim = 183 ;\nvariables:\n\tfloat Area_sqkm(BasinDim) ;\n\t\tArea_sqkm:long_name = \"Basin area in square kilometers\" ;\n\tint Basin(BasinDim) ;\n\t\tBasin:long_name = \"Basin monotonic ID (1...n)\" ;\n\tfloat Coeff(BasinDim) ;\n\t\tCoeff:long_name = \"Coefficient\" ;\n\tint ComID(BasinDim) ;\n\t\tComID:long_name = \"NHDCatchment FEATUREID (NHDFlowline ComID)\" ;\n\tdouble Expon(BasinDim) ;\n\t\tExpon:long_name = \"Exponent\" ;\n\tfloat Zinit(BasinDim) ;\n\t\tZinit:long_name = \"Zinit\" ;\n\tdouble Zmax(BasinDim) ;\n\t\tZmax:long_name = \"Zmax\" ;\n\n// global attributes:\n\t\t:featureType = \"point\" ;\n\t\t:history = \"Thu Sep  6 17:56:57 2018: ncks -O -d BasinDim,1,183 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/GWBUCKPARM.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/GWBUCKPARM.nc\\n\",\n\t\t\t\"Fri Mar  2 09:34:12 2018: ncap2 -O -s Expon=Expon*0.0+3.0 GWBUCKPARM_NWMv1.2_DEFAULT.nc GWBUCKPARM_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Fri Mar  2 09:33:34 2018: ncap2 -O -s Zmax=Zmax*0.0+50.0 GWBUCKPARM_NWMv1.2_DEFAULT.nc GWBUCKPARM_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Tue Jan 16 09:10:53 2018: ncap2 -s Zmax=Zmax*0.0+50.0 GWBUCKPARM_NWMv1.2_DEFAULT.nc GWBUCKPARM_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Tue Jan 16 09:10:11 2018: ncap2 -s Expon=Expon*0.0+3.0 GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib2_ADJFL.nc GWBUCKPARM_NWMv1.2_DEFAULT.nc\\n\",\n\t\t\t\"Mon Mar 27 18:47:12 2017: ncap2 -O -s Zmax=25.0 GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib1.nc GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib1.nc\\n\",\n\t\t\t\"Mon Mar 27 18:46:57 2017: ncap2 -O -s Expon=1.75 GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib1.nc GWBUCKPARM_NWM_v1_2_20170320_NWMv1.2_calib1.nc\\n\",\n\t\t\t\"Created Mon Mar 20 16:35:22 2017\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/GWBUCKPARM.md5",
    "content": "0980802d4a0dc229acf3630789ac5418  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/GWBUCKPARM.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/LAKEPARM.cdl",
    "content": "netcdf LAKEPARM {\ndimensions:\n\tfeature_id = 1 ;\nvariables:\n\tdouble LkArea(feature_id) ;\n\t\tLkArea:long_name = \"Gridded lake area (sq. km)\" ;\n\t\tLkArea:coordinates = \"lat lon\" ;\n\t\tLkArea:grid_mapping = \"crs\" ;\n\tdouble LkMxE(feature_id) ;\n\t\tLkMxE:long_name = \"Maximum lake elevation (m ASL)\" ;\n\t\tLkMxE:coordinates = \"lat lon\" ;\n\t\tLkMxE:grid_mapping = \"crs\" ;\n\tdouble OrificeA(feature_id) ;\n\t\tOrificeA:long_name = \"Orifice cross-sectional area (sq. m)\" ;\n\t\tOrificeA:coordinates = \"lat lon\" ;\n\t\tOrificeA:grid_mapping = \"crs\" ;\n\tdouble OrificeC(feature_id) ;\n\t\tOrificeC:long_name = \"Orifice coefficient\" ;\n\t\tOrificeC:coordinates = \"lat lon\" ;\n\t\tOrificeC:grid_mapping = \"crs\" ;\n\tdouble OrificeE(feature_id) ;\n\t\tOrificeE:long_name = \"Orifice elevation (m ASL)\" ;\n\t\tOrificeE:coordinates = \"lat lon\" ;\n\t\tOrificeE:grid_mapping = \"crs\" ;\n\tdouble WeirC(feature_id) ;\n\t\tWeirC:long_name = \"Weir coefficient\" ;\n\t\tWeirC:coordinates = \"lat lon\" ;\n\t\tWeirC:grid_mapping = \"crs\" ;\n\tdouble WeirE(feature_id) ;\n\t\tWeirE:long_name = \"Weir elevation (m ASL)\" ;\n\t\tWeirE:units = \"m\" ;\n\t\tWeirE:coordinates = \"lat lon\" ;\n\t\tWeirE:grid_mapping = \"crs\" ;\n\tdouble WeirL(feature_id) ;\n\t\tWeirL:coordinates = \"lat lon\" ;\n\t\tWeirL:grid_mapping = \"crs\" ;\n\t\tWeirL:long_name = \"Weir length (m)\" ;\n\tint ascendingIndex(feature_id) ;\n\t\tascendingIndex:long_name = \"Index to use for sorting IDs (ascending)\" ;\n\t\tascendingIndex:coordinates = \"lat lon\" ;\n\t\tascendingIndex:grid_mapping = \"crs\" ;\n\tchar crs ;\n\t\tcrs:transform_name = \"latitude_longitude\" ;\n\t\tcrs:grid_mapping_name = \"latitude_longitude\" ;\n\t\tcrs:esri_pe_string = \"GEOGCS[\\\"GCS_WGS_1984\\\",DATUM[\\\"D_WGS_1984\\\",SPHEROID[\\\"WGS_1984\\\",6378137.0,298.257223563]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:spatial_ref = \"GEOGCS[\\\"GCS_WGS_1984\\\",DATUM[\\\"D_WGS_1984\\\",SPHEROID[\\\"WGS_1984\\\",6378137.0,298.257223563]],PRIMEM[\\\"Greenwich\\\",0.0],UNIT[\\\"Degree\\\",0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision\" ;\n\t\tcrs:long_name = \"CRS definition\" ;\n\t\tcrs:longitude_of_prime_meridian = 0. ;\n\t\tcrs:_CoordinateAxes = \"lat lon\" ;\n\t\tcrs:semi_major_axis = 6378137. ;\n\t\tcrs:semi_minor_axis = 6356752.31424518 ;\n\t\tcrs:inverse_flattening = 298.257223563 ;\n\tfloat ifd(feature_id) ;\n\t\tifd:long_name = \"Initial fraction water depth\" ;\n\t\tifd:coordinates = \"lat lon\" ;\n\t\tifd:grid_mapping = \"crs\" ;\n\tint lake_id(feature_id) ;\n\t\tlake_id:long_name = \"Lake ID\" ;\n\t\tlake_id:cf_role = \"timeseries_id\" ;\n\t\tlake_id:coordinates = \"lat lon\" ;\n\t\tlake_id:grid_mapping = \"crs\" ;\n\tfloat lat(feature_id) ;\n\t\tlat:long_name = \"latitude of the lake centroid\" ;\n\t\tlat:units = \"degrees_north\" ;\n\t\tlat:standard_name = \"latitude\" ;\n\tfloat lon(feature_id) ;\n\t\tlon:long_name = \"longitude of the lake centroid\" ;\n\t\tlon:units = \"degrees_east\" ;\n\t\tlon:standard_name = \"longitude\" ;\n\tdouble time(feature_id) ;\n\t\ttime:standard_name = \"time\" ;\n\t\ttime:long_name = \"time of measurement\" ;\n\t\ttime:units = \"days since 2000-01-01 00:00:00\" ;\n\t\ttime:coordinates = \"lat lon\" ;\n\t\ttime:grid_mapping = \"crs\" ;\n\tdouble Dam_Length(feature_id) ;\n\n// global attributes:\n\t\t:Conventions = \"CF-1.5\" ;\n\t\t:featureType = \"timeSeries\" ;\n\t\t:history = \"Thu Sep  6 17:57:11 2018: ncks -O -d feature_id,1,1 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/LAKEPARM.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/LAKEPARM.nc\\n\",\n\t\t\t\"Tue Aug  7 10:00:32 2018: ncap2 -s WeirL=WeirL*0+10 LAKEPARM_20180227_v2_lakes_lowres_params.nc LAKEPARM_20180227_v2_lakes_lowres_params_WeirL_10.nc\\n\",\n\t\t\t\"Created Tue Feb 27 15:18:40 2018\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/LAKEPARM.md5",
    "content": "c2c5830e20dad59b583121079733f7bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/LAKEPARM.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/Route_Link.cdl",
    "content": "netcdf Route_Link {\ndimensions:\n\tfeature_id = 185 ;\n\tIDLength = 15 ;\nvariables:\n\tfloat BtmWdth(feature_id) ;\n\t\tBtmWdth:long_name = \"Bottom width of channel (m)\" ;\n\t\tBtmWdth:units = \"m\" ;\n\t\tBtmWdth:coordinates = \"lat lon\" ;\n\tfloat ChSlp(feature_id) ;\n\t\tChSlp:long_name = \"Channel side slope\" ;\n\t\tChSlp:coordinates = \"lat lon\" ;\n\tshort Kchan(feature_id) ;\n\t\tKchan:long_name = \"channel conductivity\" ;\n\t\tKchan:units = \"mm h-1\" ;\n\t\tKchan:coordinates = \"lat lon\" ;\n\tfloat Length(feature_id) ;\n\t\tLength:long_name = \"Stream length (m)\" ;\n\t\tLength:coordinates = \"lat lon\" ;\n\tfloat MusK(feature_id) ;\n\t\tMusK:long_name = \"Muskingum routing time (s)\" ;\n\t\tMusK:coordinates = \"lat lon\" ;\n\tfloat MusX(feature_id) ;\n\t\tMusX:long_name = \"Muskingum weighting coefficient\" ;\n\t\tMusX:coordinates = \"lat lon\" ;\n\tint NHDWaterbodyComID(feature_id) ;\n\t\tNHDWaterbodyComID:coordinates = \"lat lon\" ;\n\t\tNHDWaterbodyComID:long_name = \"ComID of NHDWaterbody feature associated using spatial join (intersection) between NHDFlowline_network and Waterbodies\" ;\n\tfloat Qi(feature_id) ;\n\t\tQi:long_name = \"Initial flow in link (CMS)\" ;\n\t\tQi:coordinates = \"lat lon\" ;\n\tfloat So(feature_id) ;\n\t\tSo:long_name = \"Slope (meters/meters from NHDFlowline_network.SLOPE)\" ;\n\t\tSo:coordinates = \"lat lon\" ;\n\tfloat TopWdth(feature_id) ;\n\t\tTopWdth:long_name = \"Top Width (m)\" ;\n\t\tTopWdth:units = \"m\" ;\n\t\tTopWdth:coordinates = \"lat lon\" ;\n\tfloat TopWdthCC(feature_id) ;\n\t\tTopWdthCC:long_name = \"Compound Channel Top Width (m)\" ;\n\t\tTopWdthCC:units = \"m\" ;\n\t\tTopWdthCC:coordinates = \"lat lon\" ;\n\tfloat alt(feature_id) ;\n\t\talt:long_name = \"Elevation in meters from the North American Vertical Datum 1988 (NADV88) at start node (MaxElevSmo)\" ;\n\t\talt:standard_name = \"height\" ;\n\t\talt:units = \"m\" ;\n\t\talt:positive = \"up\" ;\n\t\talt:axis = \"Z\" ;\n\t\talt:coordinates = \"lat lon\" ;\n\tint ascendingIndex(feature_id) ;\n\t\tascendingIndex:long_name = \"Index to use for sorting IDs (ascending)\" ;\n\tint from(feature_id) ;\n\t\tfrom:long_name = \"From Link ID (PlusFlow table FROMCOMID for every TOCOMID)\" ;\n\t\tfrom:coordinates = \"lat lon\" ;\n\tchar gages(feature_id, IDLength) ;\n\t\tgages:long_name = \"NHD Gage Event ID from SOURCE_FEA field in Gages feature class\" ;\n\t\tgages:coordinates = \"lat lon\" ;\n\tfloat lat(feature_id) ;\n\t\tlat:long_name = \"latitude of the segment midpoint\" ;\n\t\tlat:units = \"degrees_north\" ;\n\t\tlat:standard_name = \"latitude\" ;\n\t\tlat:coordinates = \"lat lon\" ;\n\tint link(feature_id) ;\n\t\tlink:long_name = \"Link ID (NHDFlowline_network COMID)\" ;\n\t\tlink:cf_role = \"timeseries_id\" ;\n\t\tlink:coordinates = \"lat lon\" ;\n\tfloat lon(feature_id) ;\n\t\tlon:long_name = \"longitude of the segment midpoint\" ;\n\t\tlon:units = \"degrees_east\" ;\n\t\tlon:standard_name = \"longitude\" ;\n\t\tlon:coordinates = \"lat lon\" ;\n\tfloat n(feature_id) ;\n\t\tn:long_name = \"Manning\\'s roughness\" ;\n\t\tn:coordinates = \"lat lon\" ;\n\tfloat nCC(feature_id) ;\n\t\tnCC:long_name = \"Compound Channel Manning\\'s n\" ;\n\t\tnCC:coordinates = \"lat lon\" ;\n\tint order(feature_id) ;\n\t\torder:long_name = \"Stream order (Strahler)\" ;\n\t\torder:coordinates = \"lat lon\" ;\n\tfloat time ;\n\t\ttime:standard_name = \"time\" ;\n\t\ttime:long_name = \"time of measurement\" ;\n\t\ttime:units = \"days since 2000-01-01 00:00:00\" ;\n\tint to(feature_id) ;\n\t\tto:long_name = \"To Link ID (PlusFlow table TOCOMID for every FROMCOMID)\" ;\n\t\tto:coordinates = \"lat lon\" ;\n\n// global attributes:\n\t\t:Convention = \"CF-1.6\" ;\n\t\t:featureType = \"timeSeries\" ;\n\t\t:history = \"Thu May 23 15:30:13 2019: ncks -O -d feature_id,1,185 /glade/scratch/arezoo/rfc_cutout_basins/Cutout_Basins/Full_Physics//0137462010/Route_Link.nc /glade/scratch/arezoo/rfc_cutout_basins/Cutout_Basins/Full_Physics//0137462010/Route_Link.nc\\n\",\n\t\t\t\"Created Wed Nov 07 23:45:44 2018\" ;\n\t\t:processing_notes = \"This file was produced Wed Nov 07 17:14:48 2018 by Kevin Sampson (NCAR) and has the following attributes: \\n\",\n\t\t\t\"   This file uses the NHDPlus v21 \\\"flattened\\\" geodatabase: NHDPlusV21_National_Flattened.gdb.\\n\",\n\t\t\t\"   This file excludes reaches in Puerto Rico and Hawaii.\\n\",\n\t\t\t\"   Routing using Arc-Hydro derived segments for Regions 01a, 02b, 09a, 10i, 10h, 13a, 13b, 13d, 15a, 15b, 17b, 18a.\\n\",\n\t\t\t\"   Topology fixes using: Topology_Fixer.csv.\\n\",\n\t\t\t\"   NHDFlowlines removed using: Remove_COMIDs_NHDFLowline_Network.csv.\\n\",\n\t\t\t\"   Gage preference list: numberOf100QualityObs.2017-03-15.csv.\\n\",\n\t\t\t\"   Gage subset list: numberOf100QualityObs.2017-03-15.csv.\\n\",\n\t\t\t\"   Gage additions made using: Add_Gage_Association.csv.\\n\",\n\t\t\t\"   Gage-to-flowline association changes made using: Bad_Gage_Associations.csv.\\n\",\n\t\t\t\"   Tidal-influenced gages removed using: TidalGageList_20170316.csv.\\n\",\n\t\t\t\"   Waterbody associations using spatial join with Lake feature class Waterbodies_V2_1km_plus_20181012.shp.\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/Route_Link.md5",
    "content": "e2bd085dd65ddf5a9fa45d735ffa6cfd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/Route_Link.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/geo_em.d01.cdl",
    "content": "netcdf geo_em.d01 {\ndimensions:\n\tTime = UNLIMITED ; // (1 currently)\n\tmonth = 12 ;\n\tsouth_north = 16 ;\n\twest_east = 15 ;\n\tland_cat = 24 ;\n\twest_east_stag = 16 ;\n\tsouth_north_stag = 17 ;\n\tsoil_cat = 16 ;\n\tDateStrLen = 19 ;\nvariables:\n\tfloat ALBEDO12M(Time, month, south_north, west_east) ;\n\t\tALBEDO12M:FieldType = 104 ;\n\t\tALBEDO12M:MemoryOrder = \"XYZ\" ;\n\t\tALBEDO12M:units = \"percent\" ;\n\t\tALBEDO12M:description = \"Monthly surface albedo\" ;\n\t\tALBEDO12M:stagger = \"M\" ;\n\t\tALBEDO12M:sr_x = 1 ;\n\t\tALBEDO12M:sr_y = 1 ;\n\tfloat CLAT(Time, south_north, west_east) ;\n\t\tCLAT:FieldType = 104 ;\n\t\tCLAT:MemoryOrder = \"XY \" ;\n\t\tCLAT:units = \"degrees latitude\" ;\n\t\tCLAT:description = \"Computational latitude on mass grid\" ;\n\t\tCLAT:stagger = \"M\" ;\n\t\tCLAT:sr_x = 1 ;\n\t\tCLAT:sr_y = 1 ;\n\tfloat CLONG(Time, south_north, west_east) ;\n\t\tCLONG:FieldType = 104 ;\n\t\tCLONG:MemoryOrder = \"XY \" ;\n\t\tCLONG:units = \"degrees longitude\" ;\n\t\tCLONG:description = \"Computational longitude on mass grid\" ;\n\t\tCLONG:stagger = \"M\" ;\n\t\tCLONG:sr_x = 1 ;\n\t\tCLONG:sr_y = 1 ;\n\tfloat CON(Time, south_north, west_east) ;\n\t\tCON:FieldType = 104 ;\n\t\tCON:MemoryOrder = \"XY \" ;\n\t\tCON:units = \"whoknows\" ;\n\t\tCON:description = \"something\" ;\n\t\tCON:stagger = \"M\" ;\n\t\tCON:sr_x = 1 ;\n\t\tCON:sr_y = 1 ;\n\tfloat COSALPHA(Time, south_north, west_east) ;\n\t\tCOSALPHA:FieldType = 104 ;\n\t\tCOSALPHA:MemoryOrder = \"XY \" ;\n\t\tCOSALPHA:units = \"none\" ;\n\t\tCOSALPHA:description = \"Cosine of rotation angle\" ;\n\t\tCOSALPHA:stagger = \"M\" ;\n\t\tCOSALPHA:sr_x = 1 ;\n\t\tCOSALPHA:sr_y = 1 ;\n\tfloat E(Time, south_north, west_east) ;\n\t\tE:FieldType = 104 ;\n\t\tE:MemoryOrder = \"XY \" ;\n\t\tE:units = \"-\" ;\n\t\tE:description = \"Coriolis E parameter\" ;\n\t\tE:stagger = \"M\" ;\n\t\tE:sr_x = 1 ;\n\t\tE:sr_y = 1 ;\n\tfloat F(Time, south_north, west_east) ;\n\t\tF:FieldType = 104 ;\n\t\tF:MemoryOrder = \"XY \" ;\n\t\tF:units = \"-\" ;\n\t\tF:description = \"Coriolis F parameter\" ;\n\t\tF:stagger = \"M\" ;\n\t\tF:sr_x = 1 ;\n\t\tF:sr_y = 1 ;\n\tfloat GREENFRAC(Time, month, south_north, west_east) ;\n\t\tGREENFRAC:FieldType = 104 ;\n\t\tGREENFRAC:MemoryOrder = \"XYZ\" ;\n\t\tGREENFRAC:units = \"fraction\" ;\n\t\tGREENFRAC:description = \"Monthly green fraction\" ;\n\t\tGREENFRAC:stagger = \"M\" ;\n\t\tGREENFRAC:sr_x = 1 ;\n\t\tGREENFRAC:sr_y = 1 ;\n\tfloat HGT_M(Time, south_north, west_east) ;\n\t\tHGT_M:FieldType = 104 ;\n\t\tHGT_M:MemoryOrder = \"XY \" ;\n\t\tHGT_M:units = \"meters MSL\" ;\n\t\tHGT_M:description = \"Topography height\" ;\n\t\tHGT_M:stagger = \"M\" ;\n\t\tHGT_M:sr_x = 1 ;\n\t\tHGT_M:sr_y = 1 ;\n\tfloat LAI12M(Time, month, south_north, west_east) ;\n\t\tLAI12M:FieldType = 104 ;\n\t\tLAI12M:MemoryOrder = \"XYZ\" ;\n\t\tLAI12M:units = \"m^2/m^2\" ;\n\t\tLAI12M:description = \"MODIS LAI\" ;\n\t\tLAI12M:stagger = \"M\" ;\n\t\tLAI12M:sr_x = 1 ;\n\t\tLAI12M:sr_y = 1 ;\n\tfloat LAKE_DEPTH(Time, south_north, west_east) ;\n\t\tLAKE_DEPTH:FieldType = 104 ;\n\t\tLAKE_DEPTH:MemoryOrder = \"XY \" ;\n\t\tLAKE_DEPTH:units = \"meters MSL\" ;\n\t\tLAKE_DEPTH:description = \"Topography height\" ;\n\t\tLAKE_DEPTH:stagger = \"M\" ;\n\t\tLAKE_DEPTH:sr_x = 1 ;\n\t\tLAKE_DEPTH:sr_y = 1 ;\n\tfloat LANDMASK(Time, south_north, west_east) ;\n\t\tLANDMASK:FieldType = 104 ;\n\t\tLANDMASK:MemoryOrder = \"XY \" ;\n\t\tLANDMASK:description = \"Landmask : 1=land, 0=water\" ;\n\t\tLANDMASK:sr_x = 1 ;\n\t\tLANDMASK:sr_y = 1 ;\n\t\tLANDMASK:stagger = \"M\" ;\n\t\tLANDMASK:units = \"none\" ;\n\tfloat LANDUSEF(Time, land_cat, south_north, west_east) ;\n\t\tLANDUSEF:FieldType = 104 ;\n\t\tLANDUSEF:MemoryOrder = \"XYZ\" ;\n\t\tLANDUSEF:units = \"category\" ;\n\t\tLANDUSEF:description = \"24-category USGS landuse\" ;\n\t\tLANDUSEF:stagger = \"M\" ;\n\t\tLANDUSEF:sr_x = 1 ;\n\t\tLANDUSEF:sr_y = 1 ;\n\tfloat LU_INDEX(Time, south_north, west_east) ;\n\t\tLU_INDEX:FieldType = 104 ;\n\t\tLU_INDEX:MemoryOrder = \"XY \" ;\n\t\tLU_INDEX:description = \"Dominant category\" ;\n\t\tLU_INDEX:sr_x = 1 ;\n\t\tLU_INDEX:sr_y = 1 ;\n\t\tLU_INDEX:stagger = \"M\" ;\n\t\tLU_INDEX:units = \"category\" ;\n\tfloat MAPFAC_M(Time, south_north, west_east) ;\n\t\tMAPFAC_M:FieldType = 104 ;\n\t\tMAPFAC_M:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_M:units = \"none\" ;\n\t\tMAPFAC_M:description = \"Mapfactor on mass grid\" ;\n\t\tMAPFAC_M:stagger = \"M\" ;\n\t\tMAPFAC_M:sr_x = 1 ;\n\t\tMAPFAC_M:sr_y = 1 ;\n\tfloat MAPFAC_MX(Time, south_north, west_east) ;\n\t\tMAPFAC_MX:FieldType = 104 ;\n\t\tMAPFAC_MX:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_MX:units = \"none\" ;\n\t\tMAPFAC_MX:description = \"Mapfactor (x-dir) on mass grid\" ;\n\t\tMAPFAC_MX:stagger = \"M\" ;\n\t\tMAPFAC_MX:sr_x = 1 ;\n\t\tMAPFAC_MX:sr_y = 1 ;\n\tfloat MAPFAC_MY(Time, south_north, west_east) ;\n\t\tMAPFAC_MY:FieldType = 104 ;\n\t\tMAPFAC_MY:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_MY:units = \"none\" ;\n\t\tMAPFAC_MY:description = \"Mapfactor (y-dir) on mass grid\" ;\n\t\tMAPFAC_MY:stagger = \"M\" ;\n\t\tMAPFAC_MY:sr_x = 1 ;\n\t\tMAPFAC_MY:sr_y = 1 ;\n\tfloat MAPFAC_U(Time, south_north, west_east_stag) ;\n\t\tMAPFAC_U:FieldType = 104 ;\n\t\tMAPFAC_U:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_U:units = \"none\" ;\n\t\tMAPFAC_U:description = \"Mapfactor on U grid\" ;\n\t\tMAPFAC_U:stagger = \"U\" ;\n\t\tMAPFAC_U:sr_x = 1 ;\n\t\tMAPFAC_U:sr_y = 1 ;\n\tfloat MAPFAC_UX(Time, south_north, west_east_stag) ;\n\t\tMAPFAC_UX:FieldType = 104 ;\n\t\tMAPFAC_UX:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_UX:units = \"none\" ;\n\t\tMAPFAC_UX:description = \"Mapfactor (x-dir) on U grid\" ;\n\t\tMAPFAC_UX:stagger = \"U\" ;\n\t\tMAPFAC_UX:sr_x = 1 ;\n\t\tMAPFAC_UX:sr_y = 1 ;\n\tfloat MAPFAC_UY(Time, south_north, west_east_stag) ;\n\t\tMAPFAC_UY:FieldType = 104 ;\n\t\tMAPFAC_UY:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_UY:units = \"none\" ;\n\t\tMAPFAC_UY:description = \"Mapfactor (y-dir) on U grid\" ;\n\t\tMAPFAC_UY:stagger = \"U\" ;\n\t\tMAPFAC_UY:sr_x = 1 ;\n\t\tMAPFAC_UY:sr_y = 1 ;\n\tfloat MAPFAC_V(Time, south_north_stag, west_east) ;\n\t\tMAPFAC_V:FieldType = 104 ;\n\t\tMAPFAC_V:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_V:units = \"none\" ;\n\t\tMAPFAC_V:description = \"Mapfactor on V grid\" ;\n\t\tMAPFAC_V:stagger = \"V\" ;\n\t\tMAPFAC_V:sr_x = 1 ;\n\t\tMAPFAC_V:sr_y = 1 ;\n\tfloat MAPFAC_VX(Time, south_north_stag, west_east) ;\n\t\tMAPFAC_VX:FieldType = 104 ;\n\t\tMAPFAC_VX:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_VX:units = \"none\" ;\n\t\tMAPFAC_VX:description = \"Mapfactor (x-dir) on V grid\" ;\n\t\tMAPFAC_VX:stagger = \"V\" ;\n\t\tMAPFAC_VX:sr_x = 1 ;\n\t\tMAPFAC_VX:sr_y = 1 ;\n\tfloat MAPFAC_VY(Time, south_north_stag, west_east) ;\n\t\tMAPFAC_VY:FieldType = 104 ;\n\t\tMAPFAC_VY:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_VY:units = \"none\" ;\n\t\tMAPFAC_VY:description = \"Mapfactor (y-dir) on V grid\" ;\n\t\tMAPFAC_VY:stagger = \"V\" ;\n\t\tMAPFAC_VY:sr_x = 1 ;\n\t\tMAPFAC_VY:sr_y = 1 ;\n\tfloat OA1(Time, south_north, west_east) ;\n\t\tOA1:FieldType = 104 ;\n\t\tOA1:MemoryOrder = \"XY \" ;\n\t\tOA1:units = \"whoknows\" ;\n\t\tOA1:description = \"something\" ;\n\t\tOA1:stagger = \"M\" ;\n\t\tOA1:sr_x = 1 ;\n\t\tOA1:sr_y = 1 ;\n\tfloat OA2(Time, south_north, west_east) ;\n\t\tOA2:FieldType = 104 ;\n\t\tOA2:MemoryOrder = \"XY \" ;\n\t\tOA2:units = \"whoknows\" ;\n\t\tOA2:description = \"something\" ;\n\t\tOA2:stagger = \"M\" ;\n\t\tOA2:sr_x = 1 ;\n\t\tOA2:sr_y = 1 ;\n\tfloat OA3(Time, south_north, west_east) ;\n\t\tOA3:FieldType = 104 ;\n\t\tOA3:MemoryOrder = \"XY \" ;\n\t\tOA3:units = \"whoknows\" ;\n\t\tOA3:description = \"something\" ;\n\t\tOA3:stagger = \"M\" ;\n\t\tOA3:sr_x = 1 ;\n\t\tOA3:sr_y = 1 ;\n\tfloat OA4(Time, south_north, west_east) ;\n\t\tOA4:FieldType = 104 ;\n\t\tOA4:MemoryOrder = \"XY \" ;\n\t\tOA4:units = \"whoknows\" ;\n\t\tOA4:description = \"something\" ;\n\t\tOA4:stagger = \"M\" ;\n\t\tOA4:sr_x = 1 ;\n\t\tOA4:sr_y = 1 ;\n\tfloat OL1(Time, south_north, west_east) ;\n\t\tOL1:FieldType = 104 ;\n\t\tOL1:MemoryOrder = \"XY \" ;\n\t\tOL1:units = \"whoknows\" ;\n\t\tOL1:description = \"something\" ;\n\t\tOL1:stagger = \"M\" ;\n\t\tOL1:sr_x = 1 ;\n\t\tOL1:sr_y = 1 ;\n\tfloat OL2(Time, south_north, west_east) ;\n\t\tOL2:FieldType = 104 ;\n\t\tOL2:MemoryOrder = \"XY \" ;\n\t\tOL2:units = \"whoknows\" ;\n\t\tOL2:description = \"something\" ;\n\t\tOL2:stagger = \"M\" ;\n\t\tOL2:sr_x = 1 ;\n\t\tOL2:sr_y = 1 ;\n\tfloat OL3(Time, south_north, west_east) ;\n\t\tOL3:FieldType = 104 ;\n\t\tOL3:MemoryOrder = \"XY \" ;\n\t\tOL3:units = \"whoknows\" ;\n\t\tOL3:description = \"something\" ;\n\t\tOL3:stagger = \"M\" ;\n\t\tOL3:sr_x = 1 ;\n\t\tOL3:sr_y = 1 ;\n\tfloat OL4(Time, south_north, west_east) ;\n\t\tOL4:FieldType = 104 ;\n\t\tOL4:MemoryOrder = \"XY \" ;\n\t\tOL4:units = \"whoknows\" ;\n\t\tOL4:description = \"something\" ;\n\t\tOL4:stagger = \"M\" ;\n\t\tOL4:sr_x = 1 ;\n\t\tOL4:sr_y = 1 ;\n\tfloat SCB_DOM(Time, south_north, west_east) ;\n\t\tSCB_DOM:FieldType = 104 ;\n\t\tSCB_DOM:MemoryOrder = \"XY \" ;\n\t\tSCB_DOM:description = \"Dominant category\" ;\n\t\tSCB_DOM:grid_mapping = \"lambert_conformal_conic\" ;\n\t\tSCB_DOM:sr_x = 1 ;\n\t\tSCB_DOM:sr_y = 1 ;\n\t\tSCB_DOM:stagger = \"M\" ;\n\t\tSCB_DOM:units = \"category\" ;\n\tfloat SCT_DOM(Time, south_north, west_east) ;\n\t\tSCT_DOM:FieldType = 104 ;\n\t\tSCT_DOM:MemoryOrder = \"XY \" ;\n\t\tSCT_DOM:description = \"Dominant category\" ;\n\t\tSCT_DOM:grid_mapping = \"lambert_conformal_conic\" ;\n\t\tSCT_DOM:sr_x = 1 ;\n\t\tSCT_DOM:sr_y = 1 ;\n\t\tSCT_DOM:stagger = \"M\" ;\n\t\tSCT_DOM:units = \"category\" ;\n\tfloat SINALPHA(Time, south_north, west_east) ;\n\t\tSINALPHA:FieldType = 104 ;\n\t\tSINALPHA:MemoryOrder = \"XY \" ;\n\t\tSINALPHA:units = \"none\" ;\n\t\tSINALPHA:description = \"Sine of rotation angle\" ;\n\t\tSINALPHA:stagger = \"M\" ;\n\t\tSINALPHA:sr_x = 1 ;\n\t\tSINALPHA:sr_y = 1 ;\n\tfloat SLOPECAT(Time, south_north, west_east) ;\n\t\tSLOPECAT:FieldType = 104 ;\n\t\tSLOPECAT:MemoryOrder = \"XY \" ;\n\t\tSLOPECAT:units = \"category\" ;\n\t\tSLOPECAT:description = \"Dominant category\" ;\n\t\tSLOPECAT:stagger = \"M\" ;\n\t\tSLOPECAT:sr_x = 1 ;\n\t\tSLOPECAT:sr_y = 1 ;\n\tfloat SNOALB(Time, south_north, west_east) ;\n\t\tSNOALB:FieldType = 104 ;\n\t\tSNOALB:MemoryOrder = \"XY \" ;\n\t\tSNOALB:units = \"percent\" ;\n\t\tSNOALB:description = \"Maximum snow albedo\" ;\n\t\tSNOALB:stagger = \"M\" ;\n\t\tSNOALB:sr_x = 1 ;\n\t\tSNOALB:sr_y = 1 ;\n\tfloat SOILCBOT(Time, soil_cat, south_north, west_east) ;\n\t\tSOILCBOT:FieldType = 104 ;\n\t\tSOILCBOT:MemoryOrder = \"XYZ\" ;\n\t\tSOILCBOT:units = \"category\" ;\n\t\tSOILCBOT:description = \"16-category bottom-layer soil type\" ;\n\t\tSOILCBOT:stagger = \"M\" ;\n\t\tSOILCBOT:sr_x = 1 ;\n\t\tSOILCBOT:sr_y = 1 ;\n\tfloat SOILCTOP(Time, soil_cat, south_north, west_east) ;\n\t\tSOILCTOP:FieldType = 104 ;\n\t\tSOILCTOP:MemoryOrder = \"XYZ\" ;\n\t\tSOILCTOP:units = \"category\" ;\n\t\tSOILCTOP:description = \"16-category top-layer soil type\" ;\n\t\tSOILCTOP:stagger = \"M\" ;\n\t\tSOILCTOP:sr_x = 1 ;\n\t\tSOILCTOP:sr_y = 1 ;\n\tfloat SOILTEMP(Time, south_north, west_east) ;\n\t\tSOILTEMP:FieldType = 104 ;\n\t\tSOILTEMP:MemoryOrder = \"XY \" ;\n\t\tSOILTEMP:units = \"Kelvin\" ;\n\t\tSOILTEMP:description = \"Annual mean deep soil temperature\" ;\n\t\tSOILTEMP:stagger = \"M\" ;\n\t\tSOILTEMP:sr_x = 1 ;\n\t\tSOILTEMP:sr_y = 1 ;\n\tchar Times(Time, DateStrLen) ;\n\tfloat VAR(Time, south_north, west_east) ;\n\t\tVAR:FieldType = 104 ;\n\t\tVAR:MemoryOrder = \"XY \" ;\n\t\tVAR:units = \"whoknows\" ;\n\t\tVAR:description = \"something\" ;\n\t\tVAR:stagger = \"M\" ;\n\t\tVAR:sr_x = 1 ;\n\t\tVAR:sr_y = 1 ;\n\tfloat VAR_SSO(Time, south_north, west_east) ;\n\t\tVAR_SSO:FieldType = 104 ;\n\t\tVAR_SSO:MemoryOrder = \"XY \" ;\n\t\tVAR_SSO:units = \"meters2 MSL\" ;\n\t\tVAR_SSO:description = \"Variance of Subgrid Scale Orography\" ;\n\t\tVAR_SSO:stagger = \"M\" ;\n\t\tVAR_SSO:sr_x = 1 ;\n\t\tVAR_SSO:sr_y = 1 ;\n\tfloat XLAT_C(Time, south_north_stag, west_east_stag) ;\n\t\tXLAT_C:FieldType = 104 ;\n\t\tXLAT_C:MemoryOrder = \"XY \" ;\n\t\tXLAT_C:units = \"degrees latitude\" ;\n\t\tXLAT_C:description = \"Latitude at grid cell corners\" ;\n\t\tXLAT_C:stagger = \"CORNER\" ;\n\t\tXLAT_C:sr_x = 1 ;\n\t\tXLAT_C:sr_y = 1 ;\n\tfloat XLAT_M(Time, south_north, west_east) ;\n\t\tXLAT_M:FieldType = 104 ;\n\t\tXLAT_M:MemoryOrder = \"XY \" ;\n\t\tXLAT_M:units = \"degrees latitude\" ;\n\t\tXLAT_M:description = \"Latitude on mass grid\" ;\n\t\tXLAT_M:stagger = \"M\" ;\n\t\tXLAT_M:sr_x = 1 ;\n\t\tXLAT_M:sr_y = 1 ;\n\tfloat XLAT_U(Time, south_north, west_east_stag) ;\n\t\tXLAT_U:FieldType = 104 ;\n\t\tXLAT_U:MemoryOrder = \"XY \" ;\n\t\tXLAT_U:units = \"degrees latitude\" ;\n\t\tXLAT_U:description = \"Latitude on U grid\" ;\n\t\tXLAT_U:stagger = \"U\" ;\n\t\tXLAT_U:sr_x = 1 ;\n\t\tXLAT_U:sr_y = 1 ;\n\tfloat XLAT_V(Time, south_north_stag, west_east) ;\n\t\tXLAT_V:FieldType = 104 ;\n\t\tXLAT_V:MemoryOrder = \"XY \" ;\n\t\tXLAT_V:units = \"degrees latitude\" ;\n\t\tXLAT_V:description = \"Latitude on V grid\" ;\n\t\tXLAT_V:stagger = \"V\" ;\n\t\tXLAT_V:sr_x = 1 ;\n\t\tXLAT_V:sr_y = 1 ;\n\tfloat XLONG_C(Time, south_north_stag, west_east_stag) ;\n\t\tXLONG_C:FieldType = 104 ;\n\t\tXLONG_C:MemoryOrder = \"XY \" ;\n\t\tXLONG_C:units = \"degrees longitude\" ;\n\t\tXLONG_C:description = \"Longitude at grid cell corners\" ;\n\t\tXLONG_C:stagger = \"CORNER\" ;\n\t\tXLONG_C:sr_x = 1 ;\n\t\tXLONG_C:sr_y = 1 ;\n\tfloat XLONG_M(Time, south_north, west_east) ;\n\t\tXLONG_M:FieldType = 104 ;\n\t\tXLONG_M:MemoryOrder = \"XY \" ;\n\t\tXLONG_M:units = \"degrees longitude\" ;\n\t\tXLONG_M:description = \"Longitude on mass grid\" ;\n\t\tXLONG_M:stagger = \"M\" ;\n\t\tXLONG_M:sr_x = 1 ;\n\t\tXLONG_M:sr_y = 1 ;\n\tfloat XLONG_U(Time, south_north, west_east_stag) ;\n\t\tXLONG_U:FieldType = 104 ;\n\t\tXLONG_U:MemoryOrder = \"XY \" ;\n\t\tXLONG_U:units = \"degrees longitude\" ;\n\t\tXLONG_U:description = \"Longitude on U grid\" ;\n\t\tXLONG_U:stagger = \"U\" ;\n\t\tXLONG_U:sr_x = 1 ;\n\t\tXLONG_U:sr_y = 1 ;\n\tfloat XLONG_V(Time, south_north_stag, west_east) ;\n\t\tXLONG_V:FieldType = 104 ;\n\t\tXLONG_V:MemoryOrder = \"XY \" ;\n\t\tXLONG_V:units = \"degrees longitude\" ;\n\t\tXLONG_V:description = \"Longitude on V grid\" ;\n\t\tXLONG_V:stagger = \"V\" ;\n\t\tXLONG_V:sr_x = 1 ;\n\t\tXLONG_V:sr_y = 1 ;\n\n// global attributes:\n\t\t:TITLE = \"OUTPUT FROM GEOGRID V3.6\" ;\n\t\t:SIMULATION_START_DATE = \"0000-00-00_00:00:00\" ;\n\t\t:WEST-EAST_GRID_DIMENSION = 16 ;\n\t\t:SOUTH-NORTH_GRID_DIMENSION = 17 ;\n\t\t:BOTTOM-TOP_GRID_DIMENSION = 0 ;\n\t\t:WEST-EAST_PATCH_START_UNSTAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_UNSTAG = 15 ;\n\t\t:SOUTH-NORTH_PATCH_START_UNSTAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_UNSTAG = 16 ;\n\t\t:GRIDTYPE = \"C\" ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:DYN_OPT = 2 ;\n\t\t:CEN_LAT = 40.00001f ;\n\t\t:CEN_LON = -97.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:MOAD_CEN_LAT = 40.00001f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:POLE_LAT = 90.f ;\n\t\t:POLE_LON = 0.f ;\n\t\t:corner_lats = 41.42281f, 41.55636f, 41.51907f, 41.3856f, 41.42413f, 41.55769f, 41.51774f, 41.38428f, 41.41836f, 41.56082f, 41.52353f, 41.38115f, 41.41969f, 41.56216f, 41.5222f, 41.37983f ;\n\t\t:corner_lons = -73.85333f, -73.80026f, -73.63379f, -73.68719f, -73.85928f, -73.80621f, -73.62784f, -73.68127f, -73.8551f, -73.79849f, -73.63202f, -73.689f, -73.86105f, -73.80444f, -73.62604f, -73.68304f ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:MMINLU = \"USGS\" ;\n\t\t:NUM_LAND_CAT = 24 ;\n\t\t:ISWATER = 16 ;\n\t\t:ISLAKE = -1 ;\n\t\t:ISICE = 24 ;\n\t\t:ISURBAN = 1 ;\n\t\t:ISOILWATER = 14 ;\n\t\t:grid_id = 1 ;\n\t\t:parent_id = 1 ;\n\t\t:i_parent_start = 1 ;\n\t\t:j_parent_start = 1 ;\n\t\t:i_parent_end = 16 ;\n\t\t:j_parent_end = 17 ;\n\t\t:parent_grid_ratio = 1 ;\n\t\t:sr_x = 1 ;\n\t\t:sr_y = 1 ;\n\t\t:FLAG_MF_XY = 1 ;\n\t\t:FLAG_LAI12M = 1 ;\n\t\t:FLAG_LAKE_DEPTH = 1 ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n\t\t:history = \"Thu Sep  6 17:56:47 2018: ncatted -O -a corner_lats,global,o,f,41.4228134155273,41.5563621520996,41.5190696716309,41.3856048583984,41.4241333007812,41.5576934814453,41.5177383422852,41.38427734375,41.4183578491211,41.5608215332031,41.5235252380371,41.3811531066895,41.4196891784668,41.5621604919434,41.5221977233887,41.3798332214355 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/geo_em.d0x.nc\\n\",\n\t\t\t\"Thu Sep  6 17:56:47 2018: ncatted -O -a corner_lons,global,o,f,-73.8533325195312,-73.8002624511719,-73.6337890625,-73.6871948242188,-73.8592834472656,-73.8062133789062,-73.6278381347656,-73.6812744140625,-73.8551025390625,-73.7984924316406,-73.6320190429688,-73.6889953613281,-73.8610534667969,-73.804443359375,-73.6260375976562,-73.6830444335938 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/geo_em.d0x.nc\\n\",\n\t\t\t\"Thu Sep  6 17:56:43 2018: ncks -d west_east,4146,4160 -d south_north,2341,2356 -d west_east_stag,4146,4161 -d south_north_stag,2341,2357 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/geo_em.d01.conus_1km_NWMv2.0_XLATC_XLONC.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/geo_em.d0x.nc\\n\",\n\t\t\t\"Wed Aug 22 18:05:18 2018: ncks -A -v XLONG_C ../../../nwmv12_finals/DOMAIN/geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC geo_em.d01.conus_1km_NWMv2.0_XLATC_XLONC.nc\\n\",\n\t\t\t\"Wed Aug 22 18:04:49 2018: ncks -A -v XLAT_C ../../../nwmv12_finals/DOMAIN/geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC geo_em.d01.conus_1km_NWMv2.0_XLATC_XLONC.nc\" ;\n\t\t:history_of_appended_files = \"Wed Aug 22 18:05:18 2018: Appended file ../../../nwmv12_finals/DOMAIN/geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Fri Dec 29 11:17:44 2017: ncks -A -v XLONG_C /glade/scratch/barlage/nwm/geo_em.d01.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC\\n\",\n\t\t\t\"Fri Dec 29 11:16:15 2017: ncks -A -v XLAT_C /glade/scratch/barlage/nwm/geo_em.d01.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC\\n\",\n\t\t\t\"Sat Apr 29 22:02:59 2017: ncks -A -v LANDUSEF landusef_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Apr 29 22:02:12 2017: ncks -A -v SOILCTOP soilctop_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Apr 29 21:59:20 2017: ncks -x -v SOILCTOP,LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\n\",\n\t\t\t\"Wed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\n\",\n\t\t\t\"Wed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\n\",\n\t\t\t\"Wed Aug 22 18:04:49 2018: Appended file ../../../nwmv12_finals/DOMAIN/geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC had following \\\"history\\\" attribute:\\n\",\n\t\t\t\"Fri Dec 29 11:17:44 2017: ncks -A -v XLONG_C /glade/scratch/barlage/nwm/geo_em.d01.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC\\n\",\n\t\t\t\"Fri Dec 29 11:16:15 2017: ncks -A -v XLAT_C /glade/scratch/barlage/nwm/geo_em.d01.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix_XLATC_XLONC\\n\",\n\t\t\t\"Sat Apr 29 22:02:59 2017: ncks -A -v LANDUSEF landusef_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Apr 29 22:02:12 2017: ncks -A -v SOILCTOP soilctop_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Apr 29 21:59:20 2017: ncks -x -v SOILCTOP,LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\n\",\n\t\t\t\"Sat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\n\",\n\t\t\t\"Wed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\n\",\n\t\t\t\"Wed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\n\",\n\t\t\t\"\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/geo_em.d01.md5",
    "content": "ca742f1130fe0bb50800ef4dc75cfaf6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/geo_em.d01.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/hydro2dtbl.cdl",
    "content": "netcdf hydro2dtbl {\ndimensions:\n\tsouth_north = 16 ;\n\twest_east = 15 ;\nvariables:\n\tfloat LKSAT(south_north, west_east) ;\n\t\tLKSAT:_FillValue = -9999.f ;\n\tfloat OV_ROUGH2D(south_north, west_east) ;\n\t\tOV_ROUGH2D:_FillValue = -9999.f ;\n\tfloat SMCMAX1(south_north, west_east) ;\n\t\tSMCMAX1:_FillValue = -9999.f ;\n\tfloat SMCREF1(south_north, west_east) ;\n\t\tSMCREF1:_FillValue = -9999.f ;\n\tfloat SMCWLT1(south_north, west_east) ;\n\t\tSMCWLT1:_FillValue = -9999.f ;\n\n// global attributes:\n\t\t:TITLE = \"OUTPUT FROM GEOGRID V3.6\" ;\n\t\t:SIMULATION_START_DATE = \"0000-00-00_00:00:00\" ;\n\t\t:WEST-EAST_GRID_DIMENSION = 4609 ;\n\t\t:SOUTH-NORTH_GRID_DIMENSION = 3841 ;\n\t\t:BOTTOM-TOP_GRID_DIMENSION = 0 ;\n\t\t:WEST-EAST_PATCH_START_UNSTAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_UNSTAG = 4608 ;\n\t\t:WEST-EAST_PATCH_START_STAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_STAG = 4609 ;\n\t\t:SOUTH-NORTH_PATCH_START_UNSTAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_UNSTAG = 3840 ;\n\t\t:SOUTH-NORTH_PATCH_START_STAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_STAG = 3841 ;\n\t\t:GRIDTYPE = \"C\" ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:DYN_OPT = 2 ;\n\t\t:CEN_LAT = 40.00001f ;\n\t\t:CEN_LON = -97.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:MOAD_CEN_LAT = 40.00001f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:POLE_LAT = 90.f ;\n\t\t:POLE_LON = 0.f ;\n\t\t:corner_lats = 20.07781f, 52.87278f, 52.87278f, 20.07781f, 20.07671f, 52.87075f, 52.87075f, 20.07671f, 20.07371f, 52.87693f, 52.87693f, 20.07371f, 20.07259f, 52.87489f, 52.87489f, 20.07259f ;\n\t\t:corner_lons = -118.1045f, -133.5073f, -60.49268f, -75.89551f, -118.1089f, -133.5142f, -60.48578f, -75.89114f, -118.1033f, -133.5107f, -60.48929f, -75.8967f, -118.1077f, -133.5176f, -60.48242f, -75.89233f ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:MMINLU = \"USGS\" ;\n\t\t:NUM_LAND_CAT = 24 ;\n\t\t:ISWATER = 16 ;\n\t\t:ISLAKE = -1 ;\n\t\t:ISICE = 24 ;\n\t\t:ISURBAN = 1 ;\n\t\t:ISOILWATER = 14 ;\n\t\t:grid_id = 1 ;\n\t\t:parent_id = 1 ;\n\t\t:i_parent_start = 1 ;\n\t\t:j_parent_start = 1 ;\n\t\t:i_parent_end = 4609 ;\n\t\t:j_parent_end = 3841 ;\n\t\t:parent_grid_ratio = 1 ;\n\t\t:sr_x = 1 ;\n\t\t:sr_y = 1 ;\n\t\t:FLAG_MF_XY = 1 ;\n\t\t:FLAG_LAI12M = 1 ;\n\t\t:FLAG_LAKE_DEPTH = 1 ;\n\t\t:history = \"Thu Sep  6 17:56:47 2018: ncks -O -d west_east,4146,4160 -d south_north,2341,2356 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/hydro2dtbl_LongRange_NWMv2.0.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/hydro2dtbl.nc\\nMon Jul 30 11:08:53 2018: ncks -O -x -v HGT_M hydro2dtbl_nwmv20_default_TEST.nc.ALL hydro2dtbl_nwmv20_default_TEST.nc.ALL\\nMon Jul 30 11:08:52 2018: ncks -O -4 -v HGT_M geo_em.d01.conus_1km_nlcd11_nwmv20_waterfixes_TEST.nc hydro2dtbl_nwmv20_default_TEST.nc.ALL\\nMon Apr  2 15:58:58 2018: ncks -A -v SCT_DOM /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/soltyp.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nMon Apr  2 15:32:45 2018: ncap2 -O -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.conus_1km_nlcd11_nwmv20.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nMon Apr  2 15:15:40 2018: ncks -A -v LU_INDEX /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/vegtyp.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nSat Apr 29 22:02:59 2017: ncks -A -v LANDUSEF landusef_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Apr 29 22:02:12 2017: ncks -A -v SOILCTOP soilctop_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Apr 29 21:59:20 2017: ncks -x -v SOILCTOP,LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n\t\t:history_of_appended_files = \"Mon Apr  2 15:58:58 2018: Appended file /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/soltyp.nc had following \\\"history\\\" attribute:\\nMon Apr  2 10:30:03 2018: ncap2 -O -s ISLTYP=int(Band1) soltyp.nc soltyp.nc\\nMon Apr  2 10:30:02 2018: ncap2 -O -s SCT_DOM=float(Band1) soltyp.nc soltyp.nc\\nMon Apr 02 10:29:34 2018: GDAL CreateCopy( soltyp.nc, ... )\\nMon Apr  2 15:15:40 2018: Appended file /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/vegtyp.nc had following \\\"history\\\" attribute:\\nMon Apr  2 10:29:46 2018: ncap2 -O -s IVGTYP=int(Band1) vegtyp.nc vegtyp.nc\\nMon Apr  2 10:29:45 2018: ncap2 -O -s LU_INDEX=float(Band1) vegtyp.nc vegtyp.nc\\nMon Apr 02 10:29:32 2018: GDAL CreateCopy( vegtyp.nc, ... )\\nSat Apr 29 22:02:59 2017: Appended file landusef_new.nc had following \\\"history\\\" attribute:\\nSat Apr 29 21:23:52 2017: ncks -v LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix landusef_orig.nc\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\nSat Apr 29 22:02:12 2017: Appended file soilctop_new.nc had following \\\"history\\\" attribute:\\nSat Apr 29 16:08:07 2017: ncks -v SOILCTOP geo_em.d01.nc.conus_1km_nlcd11_glacfix soilctop_orig.nc\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\n\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/hydro2dtbl.md5",
    "content": "f69649d1a32ef04c2650dac9ebc62f56  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/hydro2dtbl.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/soil_properties.cdl",
    "content": "netcdf soil_properties {\ndimensions:\n\tTime = UNLIMITED ; // (1 currently)\n\tsoil_layers_stag = 4 ;\n\tsouth_north = 16 ;\n\twest_east = 15 ;\nvariables:\n\tfloat bexp(Time, soil_layers_stag, south_north, west_east) ;\n\t\tbexp:_FillValue = -9999.f ;\n\tfloat cwpvt(Time, south_north, west_east) ;\n\t\tcwpvt:_FillValue = -9999.f ;\n\tfloat dksat(Time, soil_layers_stag, south_north, west_east) ;\n\t\tdksat:_FillValue = -9999.f ;\n\tfloat dwsat(Time, soil_layers_stag, south_north, west_east) ;\n\t\tdwsat:_FillValue = -9999.f ;\n\tfloat hvt(Time, south_north, west_east) ;\n\t\thvt:_FillValue = -9999.f ;\n\tfloat mfsno(Time, south_north, west_east) ;\n\t\tmfsno:_FillValue = -9999.f ;\n\tfloat mp(Time, south_north, west_east) ;\n\t\tmp:_FillValue = -9999.f ;\n\tfloat psisat(Time, soil_layers_stag, south_north, west_east) ;\n\t\tpsisat:_FillValue = -9999.f ;\n\tfloat quartz(Time, soil_layers_stag, south_north, west_east) ;\n\t\tquartz:_FillValue = -9999.f ;\n\tfloat refdk(Time, south_north, west_east) ;\n\t\trefdk:_FillValue = -9999.f ;\n\tdouble refkdt(Time, south_north, west_east) ;\n\t\trefkdt:_FillValue = -9999. ;\n\tfloat rsurfexp(Time, south_north, west_east) ;\n\t\trsurfexp:_FillValue = -9999.f ;\n\tfloat slope(Time, south_north, west_east) ;\n\t\tslope:_FillValue = -9999.f ;\n\tfloat smcdry(Time, soil_layers_stag, south_north, west_east) ;\n\t\tsmcdry:_FillValue = -9999.f ;\n\tfloat smcmax(Time, soil_layers_stag, south_north, west_east) ;\n\t\tsmcmax:_FillValue = -9999.f ;\n\tfloat smcref(Time, soil_layers_stag, south_north, west_east) ;\n\t\tsmcref:_FillValue = -9999.f ;\n\tfloat smcwlt(Time, soil_layers_stag, south_north, west_east) ;\n\t\tsmcwlt:_FillValue = -9999.f ;\n\tfloat vcmx25(Time, south_north, west_east) ;\n\t\tvcmx25:_FillValue = -9999.f ;\n\n// global attributes:\n\t\t:TITLE = \"OUTPUT FROM GEOGRID V3.6\" ;\n\t\t:SIMULATION_START_DATE = \"0000-00-00_00:00:00\" ;\n\t\t:WEST-EAST_GRID_DIMENSION = 4609 ;\n\t\t:SOUTH-NORTH_GRID_DIMENSION = 3841 ;\n\t\t:BOTTOM-TOP_GRID_DIMENSION = 0 ;\n\t\t:WEST-EAST_PATCH_START_UNSTAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_UNSTAG = 4608 ;\n\t\t:WEST-EAST_PATCH_START_STAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_STAG = 4609 ;\n\t\t:SOUTH-NORTH_PATCH_START_UNSTAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_UNSTAG = 3840 ;\n\t\t:SOUTH-NORTH_PATCH_START_STAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_STAG = 3841 ;\n\t\t:GRIDTYPE = \"C\" ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:DYN_OPT = 2 ;\n\t\t:CEN_LAT = 40.00001f ;\n\t\t:CEN_LON = -97.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:MOAD_CEN_LAT = 40.00001f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:POLE_LAT = 90.f ;\n\t\t:POLE_LON = 0.f ;\n\t\t:corner_lats = 20.07781f, 52.87278f, 52.87278f, 20.07781f, 20.07671f, 52.87075f, 52.87075f, 20.07671f, 20.07371f, 52.87693f, 52.87693f, 20.07371f, 20.07259f, 52.87489f, 52.87489f, 20.07259f ;\n\t\t:corner_lons = -118.1045f, -133.5073f, -60.49268f, -75.89551f, -118.1089f, -133.5142f, -60.48578f, -75.89114f, -118.1033f, -133.5107f, -60.48929f, -75.8967f, -118.1077f, -133.5176f, -60.48242f, -75.89233f ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:MMINLU = \"USGS\" ;\n\t\t:NUM_LAND_CAT = 24 ;\n\t\t:ISWATER = 16 ;\n\t\t:ISLAKE = -1 ;\n\t\t:ISICE = 24 ;\n\t\t:ISURBAN = 1 ;\n\t\t:ISOILWATER = 14 ;\n\t\t:grid_id = 1 ;\n\t\t:parent_id = 1 ;\n\t\t:i_parent_start = 1 ;\n\t\t:j_parent_start = 1 ;\n\t\t:i_parent_end = 4609 ;\n\t\t:j_parent_end = 3841 ;\n\t\t:parent_grid_ratio = 1 ;\n\t\t:sr_x = 1 ;\n\t\t:sr_y = 1 ;\n\t\t:FLAG_MF_XY = 1 ;\n\t\t:FLAG_LAI12M = 1 ;\n\t\t:FLAG_LAKE_DEPTH = 1 ;\n\t\t:history = \"Thu Sep  6 17:56:57 2018: ncks -O -d west_east,4146,4160 -d south_north,2341,2356 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/soil_properties_LongRange_NWMv2.0.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/soil_properties.nc\\nMon Jul 30 11:24:30 2018: ncap2 -O -s refkdt=refkdt*0.0+3.0 soil_properties_nwmv20_longrange_default.nc soil_properties_nwmv20_longrange_default.nc\\nMon Jul 30 11:08:43 2018: ncks -O -x -v HGT_M soil_properties_nwmv20_default_TEST.nc soil_properties_nwmv20_default_TEST.nc\\nMon Jul 30 11:08:42 2018: ncks -O -4 -v HGT_M geo_em.d01.conus_1km_nlcd11_nwmv20_waterfixes_TEST.nc soil_properties_nwmv20_default_TEST.nc\\nMon Apr  2 15:58:58 2018: ncks -A -v SCT_DOM /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/soltyp.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nMon Apr  2 15:32:45 2018: ncap2 -O -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.conus_1km_nlcd11_nwmv20.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nMon Apr  2 15:15:40 2018: ncks -A -v LU_INDEX /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/vegtyp.nc geo_em.d01.conus_1km_nlcd11_nwmv20.nc\\nSat Apr 29 22:02:59 2017: ncks -A -v LANDUSEF landusef_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Apr 29 22:02:12 2017: ncks -A -v SOILCTOP soilctop_new.nc geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Apr 29 21:59:20 2017: ncks -x -v SOILCTOP,LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix geo_em.d01.nc.conus_1km_nlcd11_glacfix_soilctopfix\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:nco_openmp_thread_number = 1 ;\n\t\t:history_of_appended_files = \"Mon Apr  2 15:58:58 2018: Appended file /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/soltyp.nc had following \\\"history\\\" attribute:\\nMon Apr  2 10:30:03 2018: ncap2 -O -s ISLTYP=int(Band1) soltyp.nc soltyp.nc\\nMon Apr  2 10:30:02 2018: ncap2 -O -s SCT_DOM=float(Band1) soltyp.nc soltyp.nc\\nMon Apr 02 10:29:34 2018: GDAL CreateCopy( soltyp.nc, ... )\\nMon Apr  2 15:15:40 2018: Appended file /d6/adugger/WRF_Hydro/NWM_V20/GISdata/FINALS4CALIB_OCONUS/vegtyp.nc had following \\\"history\\\" attribute:\\nMon Apr  2 10:29:46 2018: ncap2 -O -s IVGTYP=int(Band1) vegtyp.nc vegtyp.nc\\nMon Apr  2 10:29:45 2018: ncap2 -O -s LU_INDEX=float(Band1) vegtyp.nc vegtyp.nc\\nMon Apr 02 10:29:32 2018: GDAL CreateCopy( vegtyp.nc, ... )\\nSat Apr 29 22:02:59 2017: Appended file landusef_new.nc had following \\\"history\\\" attribute:\\nSat Apr 29 21:23:52 2017: ncks -v LANDUSEF geo_em.d01.nc.conus_1km_nlcd11_glacfix landusef_orig.nc\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\nSat Apr 29 22:02:12 2017: Appended file soilctop_new.nc had following \\\"history\\\" attribute:\\nSat Apr 29 16:08:07 2017: ncks -v SOILCTOP geo_em.d01.nc.conus_1km_nlcd11_glacfix soilctop_orig.nc\\nSat Dec  5 16:05:33 2015: ncap2 -s where(LU_INDEX==24) LU_INDEX=23 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11_glacfix\\nWed Dec  2 17:47:01 2015: ncap2 -s where(LU_INDEX==16) LANDMASK=0; elsewhere LANDMASK=1 geo_em.d01.nc.conus_1km_nlcd11 geo_em.d01.nc.conus_1km_nlcd11a\\nWed Dec  2 17:39:34 2015: ncks -A -v LU_INDEX out_tmp2.nc geo_em.d01.nc.conus_1km_nlcd11\\n\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/soil_properties.md5",
    "content": "d30b0f0911ce1707f4b1ee73b465892d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/soil_properties.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/spatialweights.cdl",
    "content": "netcdf spatialweights {\ndimensions:\n\tdata = 812 ;\n\tpolyid = 183 ;\nvariables:\n\tint IDmask(data) ;\n\t\tIDmask:long_name = \"Polygon ID (polyid) associated with each record\" ;\n\tint i_index(data) ;\n\t\ti_index:long_name = \"Index in the x dimension of the raster grid (starting with 1,1 in LL corner)\" ;\n\tint j_index(data) ;\n\t\tj_index:long_name = \"Index in the y dimension of the raster grid (starting with 1,1 in LL corner)\" ;\n\tint overlaps(polyid) ;\n\t\toverlaps:long_name = \"Number of intersecting polygons\" ;\n\tint polyid(polyid) ;\n\t\tpolyid:long_name = \"ID of polygon\" ;\n\tdouble regridweight(data) ;\n\t\tregridweight:long_name = \"fraction of intersecting polyid(overlapper) intersected by polygon(polyid)\" ;\n\tdouble weight(data) ;\n\t\tweight:long_name = \"fraction of polygon(polyid) intersected by polygon identified by poly2\" ;\n\n// global attributes:\n\t\t:history = \"Thu Sep  6 17:56:56 2018: ncks -O -d polyid,1,183 -d data,1,812 /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/spatialweights.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/spatialweights.nc\" ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/spatialweights.md5",
    "content": "de54817aa94f338fb39449451ba5becb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/spatialweights.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/wrfinput_d01.cdl",
    "content": "netcdf wrfinput_d01 {\ndimensions:\n\tTime = UNLIMITED ; // (1 currently)\n\tsouth_north = 16 ;\n\twest_east = 15 ;\n\tsoil_layers_stag = 4 ;\nvariables:\n\tfloat CANWAT(Time, south_north, west_east) ;\n\t\tCANWAT:units = \"kg/m^2\" ;\n\t\tCANWAT:_FillValue = -1.e+36f ;\n\tfloat DZS(Time, soil_layers_stag) ;\n\t\tDZS:units = \"m\" ;\n\t\tDZS:_FillValue = -1.e+36f ;\n\tfloat HGT(Time, south_north, west_east) ;\n\t\tHGT:FieldType = 104 ;\n\t\tHGT:MemoryOrder = \"XY \" ;\n\t\tHGT:units = \"meters MSL\" ;\n\t\tHGT:description = \"Topography height\" ;\n\t\tHGT:stagger = \"M\" ;\n\t\tHGT:sr_x = 1 ;\n\t\tHGT:sr_y = 1 ;\n\tint ISLTYP(Time, south_north, west_east) ;\n\t\tISLTYP:FieldType = 104 ;\n\t\tISLTYP:MemoryOrder = \"XY \" ;\n\t\tISLTYP:description = \"Dominant category\" ;\n\t\tISLTYP:grid_mapping = \"lambert_conformal_conic\" ;\n\t\tISLTYP:sr_x = 1 ;\n\t\tISLTYP:sr_y = 1 ;\n\t\tISLTYP:stagger = \"M\" ;\n\t\tISLTYP:units = \"category\" ;\n\tint IVGTYP(Time, south_north, west_east) ;\n\t\tIVGTYP:FieldType = 104 ;\n\t\tIVGTYP:MemoryOrder = \"XY \" ;\n\t\tIVGTYP:description = \"Dominant category\" ;\n\t\tIVGTYP:grid_mapping = \"lambert_conformal_conic\" ;\n\t\tIVGTYP:sr_x = 1 ;\n\t\tIVGTYP:sr_y = 1 ;\n\t\tIVGTYP:stagger = \"M\" ;\n\t\tIVGTYP:units = \"category\" ;\n\tfloat LAI(Time, south_north, west_east) ;\n\t\tLAI:units = \"m^2/m^2\" ;\n\t\tLAI:_FillValue = -1.e+36f ;\n\tfloat MAPFAC_MX(Time, south_north, west_east) ;\n\t\tMAPFAC_MX:FieldType = 104 ;\n\t\tMAPFAC_MX:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_MX:units = \"none\" ;\n\t\tMAPFAC_MX:description = \"Mapfactor (x-dir) on mass grid\" ;\n\t\tMAPFAC_MX:stagger = \"M\" ;\n\t\tMAPFAC_MX:sr_x = 1 ;\n\t\tMAPFAC_MX:sr_y = 1 ;\n\tfloat MAPFAC_MY(Time, south_north, west_east) ;\n\t\tMAPFAC_MY:FieldType = 104 ;\n\t\tMAPFAC_MY:MemoryOrder = \"XY \" ;\n\t\tMAPFAC_MY:units = \"none\" ;\n\t\tMAPFAC_MY:description = \"Mapfactor (y-dir) on mass grid\" ;\n\t\tMAPFAC_MY:stagger = \"M\" ;\n\t\tMAPFAC_MY:sr_x = 1 ;\n\t\tMAPFAC_MY:sr_y = 1 ;\n\tfloat SEAICE(Time, south_north, west_east) ;\n\t\tSEAICE:_FillValue = -1.e+36f ;\n\tfloat SHDMAX(Time, south_north, west_east) ;\n\t\tSHDMAX:_FillValue = -1.e+36f ;\n\t\tSHDMAX:units = \"%\" ;\n\tfloat SHDMIN(Time, south_north, west_east) ;\n\t\tSHDMIN:units = \"%\" ;\n\t\tSHDMIN:_FillValue = -1.e+36f ;\n\tfloat SMOIS(Time, soil_layers_stag, south_north, west_east) ;\n\t\tSMOIS:units = \"m^3/m^3\" ;\n\t\tSMOIS:_FillValue = -1.e+36f ;\n\tfloat SNOW(Time, south_north, west_east) ;\n\t\tSNOW:units = \"kg/m^2\" ;\n\t\tSNOW:_FillValue = -1.e+36f ;\n\tfloat TMN(Time, south_north, west_east) ;\n\t\tTMN:units = \"K\" ;\n\t\tTMN:_FillValue = -1.e+36f ;\n\tfloat TSK(Time, south_north, west_east) ;\n\t\tTSK:units = \"K\" ;\n\t\tTSK:_FillValue = -1.e+36f ;\n\tfloat TSLB(Time, soil_layers_stag, south_north, west_east) ;\n\t\tTSLB:units = \"K\" ;\n\t\tTSLB:_FillValue = -1.e+36f ;\n\tint XLAND(Time, south_north, west_east) ;\n\t\tXLAND:_FillValue = -9999 ;\n\tfloat XLAT(Time, south_north, west_east) ;\n\t\tXLAT:FieldType = 104 ;\n\t\tXLAT:MemoryOrder = \"XY \" ;\n\t\tXLAT:units = \"degrees latitude\" ;\n\t\tXLAT:description = \"Latitude on mass grid\" ;\n\t\tXLAT:stagger = \"M\" ;\n\t\tXLAT:sr_x = 1 ;\n\t\tXLAT:sr_y = 1 ;\n\tfloat XLONG(Time, south_north, west_east) ;\n\t\tXLONG:FieldType = 104 ;\n\t\tXLONG:MemoryOrder = \"XY \" ;\n\t\tXLONG:units = \"degrees longitude\" ;\n\t\tXLONG:description = \"Longitude on mass grid\" ;\n\t\tXLONG:stagger = \"M\" ;\n\t\tXLONG:sr_x = 1 ;\n\t\tXLONG:sr_y = 1 ;\n\tfloat ZS(Time, soil_layers_stag) ;\n\t\tZS:units = \"m\" ;\n\t\tZS:_FillValue = -1.e+36f ;\n\n// global attributes:\n\t\t:TITLE = \"OUTPUT FROM GEOGRID V3.6\" ;\n\t\t:SIMULATION_START_DATE = \"0000-00-00_00:00:00\" ;\n\t\t:BOTTOM-TOP_GRID_DIMENSION = 0 ;\n\t\t:WEST-EAST_PATCH_START_UNSTAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_UNSTAG = 4608 ;\n\t\t:WEST-EAST_PATCH_START_STAG = 1 ;\n\t\t:WEST-EAST_PATCH_END_STAG = 4609 ;\n\t\t:SOUTH-NORTH_PATCH_START_UNSTAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_UNSTAG = 3840 ;\n\t\t:SOUTH-NORTH_PATCH_START_STAG = 1 ;\n\t\t:SOUTH-NORTH_PATCH_END_STAG = 3841 ;\n\t\t:GRIDTYPE = \"C\" ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:DYN_OPT = 2 ;\n\t\t:CEN_LAT = 40.00001f ;\n\t\t:CEN_LON = -97.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:MOAD_CEN_LAT = 40.00001f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:POLE_LAT = 90.f ;\n\t\t:POLE_LON = 0.f ;\n\t\t:corner_lats = 20.07781f, 52.87278f, 52.87278f, 20.07781f, 20.07671f, 52.87075f, 52.87075f, 20.07671f, 20.07371f, 52.87693f, 52.87693f, 20.07371f, 20.07259f, 52.87489f, 52.87489f, 20.07259f ;\n\t\t:corner_lons = -118.1045f, -133.5073f, -60.49268f, -75.89551f, -118.1089f, -133.5142f, -60.48578f, -75.89114f, -118.1033f, -133.5107f, -60.48929f, -75.8967f, -118.1077f, -133.5176f, -60.48242f, -75.89233f ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:MMINLU = \"USGS\" ;\n\t\t:NUM_LAND_CAT = 24 ;\n\t\t:ISWATER = 16 ;\n\t\t:ISLAKE = -1 ;\n\t\t:ISICE = 24 ;\n\t\t:ISURBAN = 1 ;\n\t\t:ISOILWATER = 14 ;\n\t\t:grid_id = 1 ;\n\t\t:parent_id = 1 ;\n\t\t:i_parent_start = 1 ;\n\t\t:j_parent_start = 1 ;\n\t\t:i_parent_end = 4609 ;\n\t\t:j_parent_end = 3841 ;\n\t\t:parent_grid_ratio = 1 ;\n\t\t:sr_x = 1 ;\n\t\t:sr_y = 1 ;\n\t\t:FLAG_MF_XY = 1 ;\n\t\t:FLAG_LAI12M = 1 ;\n\t\t:FLAG_LAKE_DEPTH = 1 ;\n\t\t:nco_openmp_thread_number = 1 ;\n\t\t:NCO = \"netCDF Operators version 4.7.4 (http://nco.sf.net)\" ;\n\t\t:history = \"Thu Sep  6 17:56:48 2018: ncks -O -d west_east,4146,4160 -d south_north,2341,2356 /glade/p_old/nwc/nwmv20_finals/CONUS/DOMAIN/wrfinput.d01.conus_1km_NWMv2.0.nc /glade/scratch/adugger/TestCases/NY_Croton/DOMAIN_NWMv2.0_LongRange//0137462010/wrfinput_d0x.nc\" ;\n\t\t:WEST-EAST_GRID_DIMENSION = 16 ;\n\t\t:SOUTH-NORTH_GRID_DIMENSION = 17 ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/DOMAIN_LR/wrfinput_d01.md5",
    "content": "057813b044eb868d69125fe836fcacac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/DOMAIN_LR/wrfinput_d01.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/RESTART/nudgingLastObs.2011-08-26_00:00:00.cdl",
    "content": "netcdf nudgingLastObs.2011-08-26_00\\:00\\:00 {\ndimensions:\n\ttimeStrLen = 19 ;\n\ttimeInd = 480 ;\n\tstationIdStrLen = 15 ;\n\tstationIdInd = UNLIMITED ; // (4 currently)\n\tfeature_id = 185 ;\nvariables:\n\tchar stationId(stationIdInd, stationIdStrLen) ;\n\t\tstationId:long_name = \"USGS station identifer of length 15\" ;\n\tchar time(stationIdInd, timeInd, timeStrLen) ;\n\t\ttime:units = \"UTC\" ;\n\t\ttime:long_name = \"YYYY-mm-dd_HH:MM:SS UTC\" ;\n\tfloat discharge(stationIdInd, timeInd) ;\n\t\tdischarge:units = \"m^3/s\" ;\n\t\tdischarge:long_name = \"Discharge.cubic_meters_per_second\" ;\n\tfloat model_discharge(stationIdInd, timeInd) ;\n\t\tmodel_discharge:units = \"m^3/s\" ;\n\t\tmodel_discharge:long_name = \"modelDischarge.cubic_meters_per_second\" ;\n\tshort discharge_quality(stationIdInd, timeInd) ;\n\t\tdischarge_quality:units = \"-\" ;\n\t\tdischarge_quality:long_name = \"Discharge quality 0 to 100 to be scaled by 100.\" ;\n\tfloat nudge(feature_id) ;\n\t\tnudge:units = \"m3 s-1\" ;\n\t\tnudge:long_name = \"Amount of stream flow alteration\" ;\n\n// global attributes:\n\t\t:modelTimeAtOutput = \"2011-08-26_00:00:00\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/RESTART/nudgingLastObs.2011-08-26_00:00:00.md5",
    "content": "f9423c42a02ebfb3535e5a1049d7a800  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/RESTART/nudgingLastObs.2011-08-26_00:00:00.nc\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/RESTART_LR/HYDRO_RST.2011-08-26_00:00_DOMAIN1.cdl",
    "content": "netcdf HYDRO_RST {\ndimensions:\n\tdepth = 4 ;\n\tix = 15 ;\n\tiy = 16 ;\n\tixrt = 15 ;\n\tiyrt = 16 ;\n\tlinks = 185 ;\n\tbasns = 185 ;\n\tlakes = 1 ;\nvariables:\n\tfloat stc1(iy, ix) ;\n\tfloat smc1(iy, ix) ;\n\tfloat sh2ox1(iy, ix) ;\n\tfloat stc2(iy, ix) ;\n\tfloat smc2(iy, ix) ;\n\tfloat sh2ox2(iy, ix) ;\n\tfloat stc3(iy, ix) ;\n\tfloat smc3(iy, ix) ;\n\tfloat sh2ox3(iy, ix) ;\n\tfloat stc4(iy, ix) ;\n\tfloat smc4(iy, ix) ;\n\tfloat sh2ox4(iy, ix) ;\n\tfloat infxsrt(iy, ix) ;\n\tfloat soldrain(iy, ix) ;\n\tfloat sfcheadrt(iy, ix) ;\n\tfloat QBDRYRT(iyrt, ixrt) ;\n\tfloat infxswgt(iyrt, ixrt) ;\n\tfloat sfcheadsubrt(iyrt, ixrt) ;\n\tfloat sh2owgt1(iyrt, ixrt) ;\n\tfloat sh2owgt2(iyrt, ixrt) ;\n\tfloat sh2owgt3(iyrt, ixrt) ;\n\tfloat sh2owgt4(iyrt, ixrt) ;\n\tfloat qstrmvolrt(iyrt, ixrt) ;\n\tfloat hlink(links) ;\n\tfloat qlink1(links) ;\n\tfloat qlink2(links) ;\n\tfloat resht(lakes) ;\n\tfloat qlakeo(lakes) ;\n\tfloat qlakei(lakes) ;\n\tfloat lake_inflort(iyrt, ixrt) ;\n\tfloat z_gwsubbas(links) ;\n\n// global attributes:\n\t\t:his_out_counts = 13 ;\n\t\t:Restart_Time = \"2011-08-26_00:00:00\" ;\n\t\t:Since_Date = \"2010-08-01_00:00:00\" ;\n\t\t:DTCT = 300.f ;\n\t\t:channel_only = 0 ;\n\t\t:channelBucket_only = 0 ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/RESTART_LR/HYDRO_RST.2011-08-26_00:00_DOMAIN1.md5",
    "content": "a1d033410a3bec9db9c92e3ed5a16c26  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/RESTART_LR/HYDRO_RST.2011-08-26_00:00_DOMAIN1\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/RESTART_LR/RESTART.2011082600_DOMAIN1.cdl",
    "content": "netcdf RESTART {\ndimensions:\n\tTime = UNLIMITED ; // (1 currently)\n\tDateStrLen = 19 ;\n\twest_east = 15 ;\n\tsouth_north = 16 ;\n\twest_east_stag = 16 ;\n\tsouth_north_stag = 17 ;\n\tsoil_layers_stag = 4 ;\n\tsnow_layers = 3 ;\n\tsosn_layers = 7 ;\nvariables:\n\tchar Times(Time, DateStrLen) ;\n\tfloat SOIL_T(Time, south_north, soil_layers_stag, west_east) ;\n\t\tSOIL_T:MemoryOrder = \"XZY\" ;\n\t\tSOIL_T:description = \"\" ;\n\t\tSOIL_T:units = \"\" ;\n\tfloat SNOW_T(Time, south_north, snow_layers, west_east) ;\n\t\tSNOW_T:MemoryOrder = \"XZY\" ;\n\t\tSNOW_T:description = \"\" ;\n\t\tSNOW_T:units = \"\" ;\n\tfloat SMC(Time, south_north, soil_layers_stag, west_east) ;\n\t\tSMC:MemoryOrder = \"XZY\" ;\n\t\tSMC:description = \"\" ;\n\t\tSMC:units = \"\" ;\n\tfloat SH2O(Time, south_north, soil_layers_stag, west_east) ;\n\t\tSH2O:MemoryOrder = \"XZY\" ;\n\t\tSH2O:description = \"\" ;\n\t\tSH2O:units = \"\" ;\n\tfloat ZSNSO(Time, south_north, sosn_layers, west_east) ;\n\t\tZSNSO:MemoryOrder = \"XZY\" ;\n\t\tZSNSO:description = \"\" ;\n\t\tZSNSO:units = \"\" ;\n\tfloat SNICE(Time, south_north, snow_layers, west_east) ;\n\t\tSNICE:MemoryOrder = \"XZY\" ;\n\t\tSNICE:description = \"\" ;\n\t\tSNICE:units = \"\" ;\n\tfloat SNLIQ(Time, south_north, snow_layers, west_east) ;\n\t\tSNLIQ:MemoryOrder = \"XZY\" ;\n\t\tSNLIQ:description = \"\" ;\n\t\tSNLIQ:units = \"\" ;\n\tfloat QSNOW(Time, south_north, west_east) ;\n\t\tQSNOW:MemoryOrder = \"XY\" ;\n\t\tQSNOW:description = \"\" ;\n\t\tQSNOW:units = \"\" ;\n\tfloat FWET(Time, south_north, west_east) ;\n\t\tFWET:MemoryOrder = \"XY\" ;\n\t\tFWET:description = \"\" ;\n\t\tFWET:units = \"\" ;\n\tfloat SNEQVO(Time, south_north, west_east) ;\n\t\tSNEQVO:MemoryOrder = \"XY\" ;\n\t\tSNEQVO:description = \"\" ;\n\t\tSNEQVO:units = \"\" ;\n\tfloat EAH(Time, south_north, west_east) ;\n\t\tEAH:MemoryOrder = \"XY\" ;\n\t\tEAH:description = \"\" ;\n\t\tEAH:units = \"\" ;\n\tfloat TAH(Time, south_north, west_east) ;\n\t\tTAH:MemoryOrder = \"XY\" ;\n\t\tTAH:description = \"\" ;\n\t\tTAH:units = \"\" ;\n\tfloat ALBOLD(Time, south_north, west_east) ;\n\t\tALBOLD:MemoryOrder = \"XY\" ;\n\t\tALBOLD:description = \"\" ;\n\t\tALBOLD:units = \"\" ;\n\tfloat CM(Time, south_north, west_east) ;\n\t\tCM:MemoryOrder = \"XY\" ;\n\t\tCM:description = \"\" ;\n\t\tCM:units = \"\" ;\n\tfloat CH(Time, south_north, west_east) ;\n\t\tCH:MemoryOrder = \"XY\" ;\n\t\tCH:description = \"\" ;\n\t\tCH:units = \"\" ;\n\tint ISNOW(Time, south_north, west_east) ;\n\t\tISNOW:MemoryOrder = \"XY\" ;\n\t\tISNOW:description = \"\" ;\n\t\tISNOW:units = \"\" ;\n\tfloat CANLIQ(Time, south_north, west_east) ;\n\t\tCANLIQ:MemoryOrder = \"XY\" ;\n\t\tCANLIQ:description = \"\" ;\n\t\tCANLIQ:units = \"\" ;\n\tfloat CANICE(Time, south_north, west_east) ;\n\t\tCANICE:MemoryOrder = \"XY\" ;\n\t\tCANICE:description = \"\" ;\n\t\tCANICE:units = \"\" ;\n\tfloat SNEQV(Time, south_north, west_east) ;\n\t\tSNEQV:MemoryOrder = \"XY\" ;\n\t\tSNEQV:description = \"\" ;\n\t\tSNEQV:units = \"\" ;\n\tfloat SNOWH(Time, south_north, west_east) ;\n\t\tSNOWH:MemoryOrder = \"XY\" ;\n\t\tSNOWH:description = \"\" ;\n\t\tSNOWH:units = \"\" ;\n\tfloat TV(Time, south_north, west_east) ;\n\t\tTV:MemoryOrder = \"XY\" ;\n\t\tTV:description = \"\" ;\n\t\tTV:units = \"\" ;\n\tfloat TG(Time, south_north, west_east) ;\n\t\tTG:MemoryOrder = \"XY\" ;\n\t\tTG:description = \"\" ;\n\t\tTG:units = \"\" ;\n\tfloat ZWT(Time, south_north, west_east) ;\n\t\tZWT:MemoryOrder = \"XY\" ;\n\t\tZWT:description = \"\" ;\n\t\tZWT:units = \"\" ;\n\tfloat WA(Time, south_north, west_east) ;\n\t\tWA:MemoryOrder = \"XY\" ;\n\t\tWA:description = \"\" ;\n\t\tWA:units = \"\" ;\n\tfloat WT(Time, south_north, west_east) ;\n\t\tWT:MemoryOrder = \"XY\" ;\n\t\tWT:description = \"\" ;\n\t\tWT:units = \"\" ;\n\tfloat WSLAKE(Time, south_north, west_east) ;\n\t\tWSLAKE:MemoryOrder = \"XY\" ;\n\t\tWSLAKE:description = \"\" ;\n\t\tWSLAKE:units = \"\" ;\n\tfloat LFMASS(Time, south_north, west_east) ;\n\t\tLFMASS:MemoryOrder = \"XY\" ;\n\t\tLFMASS:description = \"\" ;\n\t\tLFMASS:units = \"\" ;\n\tfloat RTMASS(Time, south_north, west_east) ;\n\t\tRTMASS:MemoryOrder = \"XY\" ;\n\t\tRTMASS:description = \"\" ;\n\t\tRTMASS:units = \"\" ;\n\tfloat STMASS(Time, south_north, west_east) ;\n\t\tSTMASS:MemoryOrder = \"XY\" ;\n\t\tSTMASS:description = \"\" ;\n\t\tSTMASS:units = \"\" ;\n\tfloat WOOD(Time, south_north, west_east) ;\n\t\tWOOD:MemoryOrder = \"XY\" ;\n\t\tWOOD:description = \"\" ;\n\t\tWOOD:units = \"\" ;\n\tfloat STBLCP(Time, south_north, west_east) ;\n\t\tSTBLCP:MemoryOrder = \"XY\" ;\n\t\tSTBLCP:description = \"\" ;\n\t\tSTBLCP:units = \"\" ;\n\tfloat FASTCP(Time, south_north, west_east) ;\n\t\tFASTCP:MemoryOrder = \"XY\" ;\n\t\tFASTCP:description = \"\" ;\n\t\tFASTCP:units = \"\" ;\n\tfloat LAI(Time, south_north, west_east) ;\n\t\tLAI:MemoryOrder = \"XY\" ;\n\t\tLAI:description = \"\" ;\n\t\tLAI:units = \"\" ;\n\tfloat SAI(Time, south_north, west_east) ;\n\t\tSAI:MemoryOrder = \"XY\" ;\n\t\tSAI:description = \"\" ;\n\t\tSAI:units = \"\" ;\n\tfloat VEGFRA(Time, south_north, west_east) ;\n\t\tVEGFRA:MemoryOrder = \"XY\" ;\n\t\tVEGFRA:description = \"\" ;\n\t\tVEGFRA:units = \"\" ;\n\tfloat GVFMIN(Time, south_north, west_east) ;\n\t\tGVFMIN:MemoryOrder = \"XY\" ;\n\t\tGVFMIN:description = \"\" ;\n\t\tGVFMIN:units = \"\" ;\n\tfloat GVFMAX(Time, south_north, west_east) ;\n\t\tGVFMAX:MemoryOrder = \"XY\" ;\n\t\tGVFMAX:description = \"\" ;\n\t\tGVFMAX:units = \"\" ;\n\tfloat ACMELT(Time, south_north, west_east) ;\n\t\tACMELT:MemoryOrder = \"XY\" ;\n\t\tACMELT:description = \"\" ;\n\t\tACMELT:units = \"\" ;\n\tfloat ACSNOW(Time, south_north, west_east) ;\n\t\tACSNOW:MemoryOrder = \"XY\" ;\n\t\tACSNOW:description = \"\" ;\n\t\tACSNOW:units = \"\" ;\n\tfloat TAUSS(Time, south_north, west_east) ;\n\t\tTAUSS:MemoryOrder = \"XY\" ;\n\t\tTAUSS:description = \"\" ;\n\t\tTAUSS:units = \"\" ;\n\tfloat QSFC(Time, south_north, west_east) ;\n\t\tQSFC:MemoryOrder = \"XY\" ;\n\t\tQSFC:description = \"\" ;\n\t\tQSFC:units = \"\" ;\n\tfloat SFCRUNOFF(Time, south_north, west_east) ;\n\t\tSFCRUNOFF:MemoryOrder = \"XY\" ;\n\t\tSFCRUNOFF:description = \"\" ;\n\t\tSFCRUNOFF:units = \"\" ;\n\tfloat UDRUNOFF(Time, south_north, west_east) ;\n\t\tUDRUNOFF:MemoryOrder = \"XY\" ;\n\t\tUDRUNOFF:description = \"\" ;\n\t\tUDRUNOFF:units = \"\" ;\n\tfloat ACCPRCP(Time, south_north, west_east) ;\n\t\tACCPRCP:MemoryOrder = \"XY\" ;\n\t\tACCPRCP:description = \"\" ;\n\t\tACCPRCP:units = \"\" ;\n\tfloat ACCECAN(Time, south_north, west_east) ;\n\t\tACCECAN:MemoryOrder = \"XY\" ;\n\t\tACCECAN:description = \"\" ;\n\t\tACCECAN:units = \"\" ;\n\tfloat ACCEDIR(Time, south_north, west_east) ;\n\t\tACCEDIR:MemoryOrder = \"XY\" ;\n\t\tACCEDIR:description = \"\" ;\n\t\tACCEDIR:units = \"\" ;\n\tfloat ACCETRAN(Time, south_north, west_east) ;\n\t\tACCETRAN:MemoryOrder = \"XY\" ;\n\t\tACCETRAN:description = \"\" ;\n\t\tACCETRAN:units = \"\" ;\n\tfloat SMOISEQ(Time, south_north, soil_layers_stag, west_east) ;\n\t\tSMOISEQ:MemoryOrder = \"XZY\" ;\n\t\tSMOISEQ:description = \"\" ;\n\t\tSMOISEQ:units = \"\" ;\n\tfloat AREAXY(Time, south_north, west_east) ;\n\t\tAREAXY:MemoryOrder = \"XY\" ;\n\t\tAREAXY:description = \"\" ;\n\t\tAREAXY:units = \"\" ;\n\tfloat SMCWTDXY(Time, south_north, west_east) ;\n\t\tSMCWTDXY:MemoryOrder = \"XY\" ;\n\t\tSMCWTDXY:description = \"\" ;\n\t\tSMCWTDXY:units = \"\" ;\n\tfloat DEEPRECHXY(Time, south_north, west_east) ;\n\t\tDEEPRECHXY:MemoryOrder = \"XY\" ;\n\t\tDEEPRECHXY:description = \"\" ;\n\t\tDEEPRECHXY:units = \"\" ;\n\tfloat QSLATXY(Time, south_north, west_east) ;\n\t\tQSLATXY:MemoryOrder = \"XY\" ;\n\t\tQSLATXY:description = \"\" ;\n\t\tQSLATXY:units = \"\" ;\n\tfloat QRFSXY(Time, south_north, west_east) ;\n\t\tQRFSXY:MemoryOrder = \"XY\" ;\n\t\tQRFSXY:description = \"\" ;\n\t\tQRFSXY:units = \"\" ;\n\tfloat QSPRINGSXY(Time, south_north, west_east) ;\n\t\tQSPRINGSXY:MemoryOrder = \"XY\" ;\n\t\tQSPRINGSXY:description = \"\" ;\n\t\tQSPRINGSXY:units = \"\" ;\n\tfloat RECHXY(Time, south_north, west_east) ;\n\t\tRECHXY:MemoryOrder = \"XY\" ;\n\t\tRECHXY:description = \"\" ;\n\t\tRECHXY:units = \"\" ;\n\tfloat QRFXY(Time, south_north, west_east) ;\n\t\tQRFXY:MemoryOrder = \"XY\" ;\n\t\tQRFXY:description = \"\" ;\n\t\tQRFXY:units = \"\" ;\n\tfloat QSPRINGXY(Time, south_north, west_east) ;\n\t\tQSPRINGXY:MemoryOrder = \"XY\" ;\n\t\tQSPRINGXY:description = \"\" ;\n\t\tQSPRINGXY:units = \"\" ;\n\tfloat FDEPTHXY(Time, south_north, west_east) ;\n\t\tFDEPTHXY:MemoryOrder = \"XY\" ;\n\t\tFDEPTHXY:description = \"\" ;\n\t\tFDEPTHXY:units = \"\" ;\n\tfloat RIVERCONDXY(Time, south_north, west_east) ;\n\t\tRIVERCONDXY:MemoryOrder = \"XY\" ;\n\t\tRIVERCONDXY:description = \"\" ;\n\t\tRIVERCONDXY:units = \"\" ;\n\tfloat RIVERBEDXY(Time, south_north, west_east) ;\n\t\tRIVERBEDXY:MemoryOrder = \"XY\" ;\n\t\tRIVERBEDXY:description = \"\" ;\n\t\tRIVERBEDXY:units = \"\" ;\n\tfloat EQZWT(Time, south_north, west_east) ;\n\t\tEQZWT:MemoryOrder = \"XY\" ;\n\t\tEQZWT:description = \"\" ;\n\t\tEQZWT:units = \"\" ;\n\tfloat PEXPXY(Time, south_north, west_east) ;\n\t\tPEXPXY:MemoryOrder = \"XY\" ;\n\t\tPEXPXY:description = \"\" ;\n\t\tPEXPXY:units = \"\" ;\n\n// global attributes:\n\t\t:TITLE = \"RESTART FILE FROM HRLDAS v20150506\" ;\n\t\t:missing_value = -1.e+33f ;\n\t\t:START_DATE = \"2010-08-01_00:00:00\" ;\n\t\t:MAP_PROJ = 1 ;\n\t\t:LAT1 = 41.42281f ;\n\t\t:LON1 = -73.85333f ;\n\t\t:DX = 1000.f ;\n\t\t:DY = 1000.f ;\n\t\t:TRUELAT1 = 30.f ;\n\t\t:TRUELAT2 = 60.f ;\n\t\t:STAND_LON = -97.f ;\n\t\t:MMINLU = \"USGS\" ;\n}\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/RESTART_LR/RESTART.2011082600_DOMAIN1.md5",
    "content": "56cea45858b488bbaa3f03c464d589d5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/RESTART_LR/RESTART.2011082600_DOMAIN1\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/NWM/nudgingTimeSliceObs.md5",
    "content": "383e7f5fbdbb1a9aaabb6bb2041a001d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_05:00:00.15min.usgsTimeSlice.ncdf\nb62f1271a6856fdbd0dca17f549f39bc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_05:15:00.15min.usgsTimeSlice.ncdf\nf442dc2ecc51b43dfc21e8dffbcbf3ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_05:30:00.15min.usgsTimeSlice.ncdf\nc0bb2841417566fa310daa08afcd03f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_05:45:00.15min.usgsTimeSlice.ncdf\n11b6e7ad442e41442b2e0f581025992b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_06:00:00.15min.usgsTimeSlice.ncdf\nc9e965710a1b6b4df10f633dd84b89d8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_06:15:00.15min.usgsTimeSlice.ncdf\nc6f113b873ba486d8dcea44e477051e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_06:30:00.15min.usgsTimeSlice.ncdf\n29e01cc9d39ff53140fa2ffd3b72f221  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_06:45:00.15min.usgsTimeSlice.ncdf\n6e3f1934a8252479b86b6f26cc7b5a99  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_07:00:00.15min.usgsTimeSlice.ncdf\n4b51e83ef8352ff7aa2ea18e75cfb449  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_07:15:00.15min.usgsTimeSlice.ncdf\nee6112b0829f11344edc3080cea0cf8b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_07:30:00.15min.usgsTimeSlice.ncdf\n50d113ee7b0e09966efa1b972d795b1a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_07:45:00.15min.usgsTimeSlice.ncdf\n4f2bd7eff1a8a9aab5ee5b380cfc207e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_08:00:00.15min.usgsTimeSlice.ncdf\n9c2acc7b97b4cb254fd9cb998336e79a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_08:15:00.15min.usgsTimeSlice.ncdf\n41bb410e4640d42421ef11542613e645  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_08:30:00.15min.usgsTimeSlice.ncdf\n0364a0284810b2ecb5363caba4957c52  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_08:45:00.15min.usgsTimeSlice.ncdf\n42031dd41473083cfe0cc461f3726236  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_09:00:00.15min.usgsTimeSlice.ncdf\n2b6bccd5152c986bc6533b0afebb6b50  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_09:15:00.15min.usgsTimeSlice.ncdf\n03597afb65d09161b443e26accb319d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_09:30:00.15min.usgsTimeSlice.ncdf\n7f8847a1849e803aebce493e08835ca3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_09:45:00.15min.usgsTimeSlice.ncdf\n0983a3fe871a924f47cd1feaa78c6dfd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_10:00:00.15min.usgsTimeSlice.ncdf\nb374c15336501680fbc54f4b62fb301e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_10:15:00.15min.usgsTimeSlice.ncdf\n948396b32bd855fd7393e81f54fb4edf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_10:30:00.15min.usgsTimeSlice.ncdf\n34ad4323b27d81d36834e71945c8d5bf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_10:45:00.15min.usgsTimeSlice.ncdf\n242820203a835ce8ee2ce47f65257b59  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_11:00:00.15min.usgsTimeSlice.ncdf\n47fd6875e47094b4751e8c051b78cd2c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_11:15:00.15min.usgsTimeSlice.ncdf\nb45017b2d98d757f579aee5625bdb04f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_11:30:00.15min.usgsTimeSlice.ncdf\n2b6b6e35700475bc774ea66a09fd9b56  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_11:45:00.15min.usgsTimeSlice.ncdf\n6f3080735ed898fea4dc6fc38e400c6d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_12:00:00.15min.usgsTimeSlice.ncdf\n14b745d705bb17e445be2eba0a365649  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_12:15:00.15min.usgsTimeSlice.ncdf\n3b56d3705fd414ed4d54e3143ea62aa8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_12:30:00.15min.usgsTimeSlice.ncdf\n720e09a7a19c09a8acb8f122a3610b68  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_12:45:00.15min.usgsTimeSlice.ncdf\naecb9d0ea55e209cc30515c5bf3ceef1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_13:00:00.15min.usgsTimeSlice.ncdf\n55e8a3492105c4246c8321f1bec068db  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_13:15:00.15min.usgsTimeSlice.ncdf\n9de7858bbc26f9007301df44f6c28bf1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_13:30:00.15min.usgsTimeSlice.ncdf\na338f27330aaca521a53c92bec9a9b27  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_13:45:00.15min.usgsTimeSlice.ncdf\ne57a80d0f898e6bd5c5c04415cbf51c4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_14:00:00.15min.usgsTimeSlice.ncdf\n92334ca874fbcafef1239ec4cb724e71  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_14:15:00.15min.usgsTimeSlice.ncdf\n30807ed02f69197427b8f52bdf4051b5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_14:30:00.15min.usgsTimeSlice.ncdf\n0082dd4819b5ffea7b9a06c60e06a5ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_14:45:00.15min.usgsTimeSlice.ncdf\n47bdc0ca5f68578dfa81bce224d3893f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_15:00:00.15min.usgsTimeSlice.ncdf\nd395cd2ad3b3624e1cf4e5b8820f6e7a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_15:15:00.15min.usgsTimeSlice.ncdf\nc6b2675d76bd52f22a40e7f4b98e9f8f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_15:30:00.15min.usgsTimeSlice.ncdf\n859461eb37f4b9fdca66b22efd394e20  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_15:45:00.15min.usgsTimeSlice.ncdf\n0beafd1f973ebd305ffe3ebbaf5fb724  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_16:00:00.15min.usgsTimeSlice.ncdf\n40189406e839d545b82ff43ca53b1e36  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_16:15:00.15min.usgsTimeSlice.ncdf\n3191b16ce03698040f26f7cc6a436eab  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_16:30:00.15min.usgsTimeSlice.ncdf\nb893769092eabbc43b17eaca1baf8679  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_16:45:00.15min.usgsTimeSlice.ncdf\n38710c3676a8c4c7d5a9f2de69777cbc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_17:00:00.15min.usgsTimeSlice.ncdf\n1430efbbb5b5d5a00d5ed8c3e1aba572  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_17:15:00.15min.usgsTimeSlice.ncdf\nf8dcf2e293cbc3e607cd53b80dda3009  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_17:30:00.15min.usgsTimeSlice.ncdf\n8212b54db0ad0ac268293e236900f03a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_17:45:00.15min.usgsTimeSlice.ncdf\nbc0819a4fa922e0d2f8aa0b3eb283f8b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_18:00:00.15min.usgsTimeSlice.ncdf\n7444b951ea1bb5ef242380ea6a06889f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_18:15:00.15min.usgsTimeSlice.ncdf\n60b188ca64eee557eb992bd3c478598c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_18:30:00.15min.usgsTimeSlice.ncdf\n8247e7d9284ee7c3d9cdd43e1b27d949  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_18:45:00.15min.usgsTimeSlice.ncdf\n4f418150ff3beee32081124aabfd1898  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_19:00:00.15min.usgsTimeSlice.ncdf\n452106dd1f6b4e1bdcdce8127edcc376  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_19:15:00.15min.usgsTimeSlice.ncdf\n5e8cd87a11ed97a15e06e0612460f5e9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_19:30:00.15min.usgsTimeSlice.ncdf\nbe08a323e181f2b7cfc8332be5a6c955  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_19:45:00.15min.usgsTimeSlice.ncdf\n3e5dc0904f2511b088c623f8631064a2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_20:00:00.15min.usgsTimeSlice.ncdf\nc96c90732b1b15c780ea36b43365cbad  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_20:15:00.15min.usgsTimeSlice.ncdf\n8af8885d4c3804f19a9aba9cd42926a3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_20:30:00.15min.usgsTimeSlice.ncdf\n1936bbc3b291f00a2bdb72feb8c8b223  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_20:45:00.15min.usgsTimeSlice.ncdf\n7dd7634f19f141234b2140c56f6e149e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_21:00:00.15min.usgsTimeSlice.ncdf\n38860512a9def8fe515c65a45d01b0cd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_21:15:00.15min.usgsTimeSlice.ncdf\n77589cafd7641857292987eb35e6c271  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_21:30:00.15min.usgsTimeSlice.ncdf\n1ec1f20805f8ed4471d948435a730328  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_21:45:00.15min.usgsTimeSlice.ncdf\n7fcd4ed28f83d6f341d797f2b55f2770  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_22:00:00.15min.usgsTimeSlice.ncdf\nd9f223849efb9f223241c27b943cfb92  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_22:15:00.15min.usgsTimeSlice.ncdf\nbf4cd6c7992e6d23239a37cd673ac86c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_22:30:00.15min.usgsTimeSlice.ncdf\n3e2070edcec4c01831e2a73bf7ec6a9f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_22:45:00.15min.usgsTimeSlice.ncdf\n6c297a99c6fea5043b66b46fa086c8a6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_23:00:00.15min.usgsTimeSlice.ncdf\n84ff9dcf9c61d1e46060486cd270241c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_23:15:00.15min.usgsTimeSlice.ncdf\n24640924b4663c0db07c402a505f561e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_23:30:00.15min.usgsTimeSlice.ncdf\n4d7005ed218a4c2cd54ac2e5a41bbad5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-25_23:45:00.15min.usgsTimeSlice.ncdf\ncd801fa8a0cfb650c3e5227a34544fd6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_00:00:00.15min.usgsTimeSlice.ncdf\n4ef6dae0ca1e9c1e4ffd8bb7de7ea3fa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_00:15:00.15min.usgsTimeSlice.ncdf\n85db87619a3902e084ba2edc5a57f09b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_00:30:00.15min.usgsTimeSlice.ncdf\n55ced80797d56ce6ab7a1f4266c9fc07  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_00:45:00.15min.usgsTimeSlice.ncdf\nb76585946bc68ccdad6efcee3ff3065d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_01:00:00.15min.usgsTimeSlice.ncdf\na1ec8daa852547d97bba2c66064dbd21  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_01:15:00.15min.usgsTimeSlice.ncdf\naa4fb37362ec120f933022f95cb99f6e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_01:30:00.15min.usgsTimeSlice.ncdf\n36672f0c276e9fe895fcc2d0e85655e7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_01:45:00.15min.usgsTimeSlice.ncdf\n759212084b9a80802f4d1ad50650c4ee  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_02:00:00.15min.usgsTimeSlice.ncdf\n27dce9032343c218a61946d1f9092e44  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_02:15:00.15min.usgsTimeSlice.ncdf\n25a298ecaacd528b861384ae3da091b2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_02:30:00.15min.usgsTimeSlice.ncdf\n956187776d82fc36ea7771bb80299169  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_02:45:00.15min.usgsTimeSlice.ncdf\n6025045092c5526f2a4772fd289f1c78  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_03:00:00.15min.usgsTimeSlice.ncdf\n02ef1951a8310b24a8ceaf23fce89df4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_03:15:00.15min.usgsTimeSlice.ncdf\n7c0f358698f0d43d3575eb315282f2f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_03:30:00.15min.usgsTimeSlice.ncdf\n80de472b55a5ccde291058c6f66e63ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_03:45:00.15min.usgsTimeSlice.ncdf\nf5892f7c1fc96caa536b3c22f61bde53  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_04:00:00.15min.usgsTimeSlice.ncdf\n291dd1bddfdd290c6a24224ba3cd60e7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_04:15:00.15min.usgsTimeSlice.ncdf\n649f71abff71f99a1ed85b0410c047c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_04:30:00.15min.usgsTimeSlice.ncdf\n1aad16156487ba6e59233b5755722c60  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_04:45:00.15min.usgsTimeSlice.ncdf\nce627d788c5ec937da27fe140eb6a634  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_05:00:00.15min.usgsTimeSlice.ncdf\n371b53ae3b0a9a4ef2336c6e5435c836  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_05:15:00.15min.usgsTimeSlice.ncdf\nff42aab9aae162225b154b51620671b0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_05:30:00.15min.usgsTimeSlice.ncdf\ne567a57aa20ad0417e0eaf7c0e44020d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_05:45:00.15min.usgsTimeSlice.ncdf\nc34f74697e4c4bf995bafcd4850456f0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_06:00:00.15min.usgsTimeSlice.ncdf\n7fd7a7014f7fe1ebe517f0314b974acf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_06:15:00.15min.usgsTimeSlice.ncdf\n3fe6cd3a2cd5006bf29b88c00226cda2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_06:30:00.15min.usgsTimeSlice.ncdf\n83247f6b46179daea71796209e30c932  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_06:45:00.15min.usgsTimeSlice.ncdf\ndfee95d270c03b72d3b573dc6cb1965c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_07:00:00.15min.usgsTimeSlice.ncdf\n2cc882dc933800b4fb9198b82ef3bc35  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_07:15:00.15min.usgsTimeSlice.ncdf\n978503eba24aaeae394eca79b444605d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_07:30:00.15min.usgsTimeSlice.ncdf\n870c8db8269b5cc8fcaec3d35467d99b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_07:45:00.15min.usgsTimeSlice.ncdf\n7bf558912833299b66bd1e2e723eef70  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_08:00:00.15min.usgsTimeSlice.ncdf\nd02972d1c351b0d0d7f163912f69950c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_08:15:00.15min.usgsTimeSlice.ncdf\nfc28983a13e0c2ff3463419c127b0740  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_08:30:00.15min.usgsTimeSlice.ncdf\n533617e03ce4a359562fd431f63ff0a4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_08:45:00.15min.usgsTimeSlice.ncdf\n7c0afde8242de56794365ac448d27128  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_09:00:00.15min.usgsTimeSlice.ncdf\nc3471155dd02d9cf795be4ab876fe204  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_09:15:00.15min.usgsTimeSlice.ncdf\nf040935c465b48a9c27822af48b49730  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_09:30:00.15min.usgsTimeSlice.ncdf\n70c9ea506dec4f6212609374081f3779  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_09:45:00.15min.usgsTimeSlice.ncdf\n6082dc86186b6f6422ff7345d2d84d5d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_10:00:00.15min.usgsTimeSlice.ncdf\n999e7d4b795610e8afa37860d2f358ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_10:15:00.15min.usgsTimeSlice.ncdf\n8cf018b77cb0e364eba2c6b7c6ff8e5e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_10:30:00.15min.usgsTimeSlice.ncdf\ne4dfe29158dda254ca3aa3c308bff2f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_10:45:00.15min.usgsTimeSlice.ncdf\n66754c464046ea2168fb7169a43344dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_11:00:00.15min.usgsTimeSlice.ncdf\n4e6a5b1ff3c9b5d4a67acf3f6d800e66  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_11:15:00.15min.usgsTimeSlice.ncdf\na914758415d4ed7a885412a73ace4895  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_11:30:00.15min.usgsTimeSlice.ncdf\n5d821ed7d647c820a0d30cbd7ce97c73  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_11:45:00.15min.usgsTimeSlice.ncdf\n2c56d4535cdb28af2153152f60577bf8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_12:00:00.15min.usgsTimeSlice.ncdf\nee6c0f4a7ada8be5009e9c6d74f1cbc0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_12:15:00.15min.usgsTimeSlice.ncdf\n18312bd0201f36a687e6e2b605bfe90e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_12:30:00.15min.usgsTimeSlice.ncdf\n7d58c16d483afeb219cd27c86a4105cc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_12:45:00.15min.usgsTimeSlice.ncdf\n00a0cd89f35de38942f1fd2cbac9109d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_13:00:00.15min.usgsTimeSlice.ncdf\n87c2eb9ef0116301486424dea4a43316  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_13:15:00.15min.usgsTimeSlice.ncdf\n0c533d18c40bda3b2a91b1343485e170  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_13:30:00.15min.usgsTimeSlice.ncdf\nb8d1bfa60b81cdc99f0231f19309995e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_13:45:00.15min.usgsTimeSlice.ncdf\n7cfa2b9ef2fb6cfa7212a02e729ed5c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_14:00:00.15min.usgsTimeSlice.ncdf\n852c0482000a922b69cde63023b78e8d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_14:15:00.15min.usgsTimeSlice.ncdf\n258cd8654dae33de56fb51d4a78ebe56  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_14:30:00.15min.usgsTimeSlice.ncdf\n146f523f8aa388c94d067913abd05788  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_14:45:00.15min.usgsTimeSlice.ncdf\n1783be9de34003758d425521e59803f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_15:00:00.15min.usgsTimeSlice.ncdf\n3d802a75ac44cef79c95e6b0d03125ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_15:15:00.15min.usgsTimeSlice.ncdf\n1982c52ad9cbe06910fc8f27109cfccd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_15:30:00.15min.usgsTimeSlice.ncdf\nd1fe50c28d173912efe6f21728d40370  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_15:45:00.15min.usgsTimeSlice.ncdf\n14cf1a4a600be69b70a60efb0c5087b2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_16:00:00.15min.usgsTimeSlice.ncdf\nb489d17c7f8ce561e1f44dbecb37449b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_16:15:00.15min.usgsTimeSlice.ncdf\ncff9016480e4d0ee5e994222d3fa2a1e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_16:30:00.15min.usgsTimeSlice.ncdf\nc21c2ec7ba2301fcab4d0bc543c3545a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_16:45:00.15min.usgsTimeSlice.ncdf\nf575bc5c42c663a285cf2c9dbd302fe5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_17:00:00.15min.usgsTimeSlice.ncdf\n81de530fc285156428951d8bf9b540bf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_17:15:00.15min.usgsTimeSlice.ncdf\na80ff90d67267dde8e9c1b86eb38b92a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_17:30:00.15min.usgsTimeSlice.ncdf\n1b2ea2bbeaa28d5d9731decc220b3002  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_17:45:00.15min.usgsTimeSlice.ncdf\na85e77d76e4b6efcabdf9d37de39d8f7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_18:00:00.15min.usgsTimeSlice.ncdf\nd1507b86404b4a12f81ab208a704b588  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_18:15:00.15min.usgsTimeSlice.ncdf\naf9172cd8e9a95f1f2a67ff9160577e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_18:30:00.15min.usgsTimeSlice.ncdf\n8d5f8e428811b6c15488b744080b9404  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_18:45:00.15min.usgsTimeSlice.ncdf\na5c4c805f42ed91fb8c20241d86ab458  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_19:00:00.15min.usgsTimeSlice.ncdf\nd0b41eca55a02601a367d30666fd6521  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_19:15:00.15min.usgsTimeSlice.ncdf\nd5f315c73f7581d5c7ac83bf4004d5dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_19:30:00.15min.usgsTimeSlice.ncdf\n1a680100760b41e542f9c112e1e186d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_19:45:00.15min.usgsTimeSlice.ncdf\nd194c0905266944cda5005b8f69e520c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_20:00:00.15min.usgsTimeSlice.ncdf\nc675ee4fcd3f5dfa9e0b059478e489fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_20:15:00.15min.usgsTimeSlice.ncdf\n797a55e0ecb905e3d01b7a1a9231ced3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_20:30:00.15min.usgsTimeSlice.ncdf\nc9fca2452c92f35a2d8b2fb3afd9da93  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_20:45:00.15min.usgsTimeSlice.ncdf\n135681089d34311b796494fc1d342668  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_21:00:00.15min.usgsTimeSlice.ncdf\nfe8682f782fc0ae868b9d4b6057053df  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_21:15:00.15min.usgsTimeSlice.ncdf\ncb09a4ab060881344c153b27fd8388f7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_21:30:00.15min.usgsTimeSlice.ncdf\nd562ec5d714bc663558aba9656c55697  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_21:45:00.15min.usgsTimeSlice.ncdf\ned99be7259942eb282935719b2c33b67  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_22:00:00.15min.usgsTimeSlice.ncdf\nfcc5c6f4bc322c17c20d8ec1f58899aa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_22:15:00.15min.usgsTimeSlice.ncdf\n13ea8197d5e8f66e85ab75ee7c703ec1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_22:30:00.15min.usgsTimeSlice.ncdf\n690d3b25c9fc6cee804bb2d2389a34b8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_22:45:00.15min.usgsTimeSlice.ncdf\nb110458ad61c65f96b5ddf6a997d2cd9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_23:00:00.15min.usgsTimeSlice.ncdf\n5f3080e78e48567cc969c62a5988dd1b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_23:15:00.15min.usgsTimeSlice.ncdf\n2130cb13810a77a1c401d960921b5815  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_23:30:00.15min.usgsTimeSlice.ncdf\n427e4fa743b381af09c3ae2737b5fa2a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-26_23:45:00.15min.usgsTimeSlice.ncdf\n9cc349a8aede24796e3d53b83d293a05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_00:00:00.15min.usgsTimeSlice.ncdf\n5f7cfddf97ccc2721e3519dbda04883b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_00:15:00.15min.usgsTimeSlice.ncdf\ndd58af95f637935b91c119421a309055  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_00:30:00.15min.usgsTimeSlice.ncdf\ne6bb1afd9f8165768a21257dbee60e8a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_00:45:00.15min.usgsTimeSlice.ncdf\n10a9a466f86dcddbb3d08057a4d3e05c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_01:00:00.15min.usgsTimeSlice.ncdf\n76b87ee8a61cb942d85b351001535098  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_01:15:00.15min.usgsTimeSlice.ncdf\n0099cc4d22ac00156244f080f2256ed0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_01:30:00.15min.usgsTimeSlice.ncdf\n82d97d104b3fb6e7415052d3710bac79  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_01:45:00.15min.usgsTimeSlice.ncdf\n806118efe4f82f5f4ed1ee96d3b5d446  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_02:00:00.15min.usgsTimeSlice.ncdf\nc05e3f157242e0cfb21b7c02686406fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_02:15:00.15min.usgsTimeSlice.ncdf\na0337b4ce832525e8dfe30f3cd2410dc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_02:30:00.15min.usgsTimeSlice.ncdf\ndb50d1673882ab0fe253f2aa2e652429  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_02:45:00.15min.usgsTimeSlice.ncdf\n286b78281f476724f97f037e883d5f7e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_03:00:00.15min.usgsTimeSlice.ncdf\n49d7a3bc6bac22c8dcc0f4acc420bf9e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_03:15:00.15min.usgsTimeSlice.ncdf\ncc874261d1b89123fc7e79eeb13ab141  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_03:30:00.15min.usgsTimeSlice.ncdf\n3c5721468c8e961ab285cae75ee690ce  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_03:45:00.15min.usgsTimeSlice.ncdf\nc90a42320e9c5dba5a16966ffba122dc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_04:00:00.15min.usgsTimeSlice.ncdf\n0d14f7fbaae069d0f6b112872d609f86  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_04:15:00.15min.usgsTimeSlice.ncdf\n1cb94ab8943948553ff85528c8ab071a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_04:30:00.15min.usgsTimeSlice.ncdf\n63307ce2a1985139292c6e5727eec027  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_04:45:00.15min.usgsTimeSlice.ncdf\n6ccc9c3659399b722b180444e3ad215f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_05:00:00.15min.usgsTimeSlice.ncdf\nc760ccad252eae7d67951b1c418d2af3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_05:15:00.15min.usgsTimeSlice.ncdf\nae2665152935169192bf96bd28ba1797  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_05:30:00.15min.usgsTimeSlice.ncdf\n156003a42ed40cfdc125fc9324977b06  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_05:45:00.15min.usgsTimeSlice.ncdf\n175e2e66c1e675f72aa7316c0d726b92  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_06:00:00.15min.usgsTimeSlice.ncdf\nab78a9d79f99961523da095b9f0cacb7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_06:15:00.15min.usgsTimeSlice.ncdf\n1c9cfe3d217c61e7184a7f420705fa12  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_06:30:00.15min.usgsTimeSlice.ncdf\nbf6e49851b481ded70e65d3a48aae7b7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_06:45:00.15min.usgsTimeSlice.ncdf\n858fcff5f162ee709a884f1dc7346e83  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_07:00:00.15min.usgsTimeSlice.ncdf\n72710d89aef091f219a403a3fe2fc411  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_07:15:00.15min.usgsTimeSlice.ncdf\n62031549bd705c45629e345a9ff853be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_07:30:00.15min.usgsTimeSlice.ncdf\ne50c08df9966c12d571b0cf4f7010048  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_07:45:00.15min.usgsTimeSlice.ncdf\n578a67618afe89098f1f2941b41c5157  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_08:00:00.15min.usgsTimeSlice.ncdf\nc957840e8d184686f586f5092c2402c8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_08:15:00.15min.usgsTimeSlice.ncdf\nfbf693e3c24a9e67198d81535d4107e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_08:30:00.15min.usgsTimeSlice.ncdf\neb7057217ea5608375cc5d215d6978c1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_08:45:00.15min.usgsTimeSlice.ncdf\n5391faa1c3f2164fe5c2abb24cc62c83  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_09:00:00.15min.usgsTimeSlice.ncdf\n784b086dd2bbda76cb3eaa207abb04e3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_09:15:00.15min.usgsTimeSlice.ncdf\n061abf3937ebccc3e86591d43cfef709  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_09:30:00.15min.usgsTimeSlice.ncdf\n20c3a7fcf9f94f45f051dceee21ae505  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_09:45:00.15min.usgsTimeSlice.ncdf\n47e06a186e7dbd08b8bea36d82bb239b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_10:00:00.15min.usgsTimeSlice.ncdf\nc12b2746a6f9a2dc93dc9a6132cb5927  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_10:15:00.15min.usgsTimeSlice.ncdf\n339bf91bf21e5ccdd040eff075811494  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_10:30:00.15min.usgsTimeSlice.ncdf\n61a17ce9e6b20ebc637f7bb2f020f6d1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_10:45:00.15min.usgsTimeSlice.ncdf\n58dda52ae687974aa64236b96162f298  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_11:00:00.15min.usgsTimeSlice.ncdf\nd372d3ae525d07ec8dfd07a2d24705fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_11:15:00.15min.usgsTimeSlice.ncdf\ndf26b106fed5a37e253f6394f1cbbf5e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_11:30:00.15min.usgsTimeSlice.ncdf\n23614e69521bc9e49099a34a8335b7c0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_11:45:00.15min.usgsTimeSlice.ncdf\n11d82095ba11d718a28d5a2cd88a11ee  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_12:00:00.15min.usgsTimeSlice.ncdf\n7096918abaf22b18246c208839731696  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_12:15:00.15min.usgsTimeSlice.ncdf\nee24c5b495387054fa04141a48eef999  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_12:30:00.15min.usgsTimeSlice.ncdf\nb1ef0f68d309a902c022e056ea4eed31  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_12:45:00.15min.usgsTimeSlice.ncdf\ncf8a42abd0061320039a1b33999644d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_13:00:00.15min.usgsTimeSlice.ncdf\ne359c029a10087090868833b6636c2bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_13:15:00.15min.usgsTimeSlice.ncdf\nbd3fc1fbebc69345b0188a1e6a75d0ce  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_13:30:00.15min.usgsTimeSlice.ncdf\nee1ba2e590c4eebe86b16374341df9b7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_13:45:00.15min.usgsTimeSlice.ncdf\n8395013b1ad1048b0616d02ba8878e7b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_14:00:00.15min.usgsTimeSlice.ncdf\ne9c8935fa85082ba5d0c89ffbef6adb5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_14:15:00.15min.usgsTimeSlice.ncdf\n3ff750e0df0232a292d066f998586c6c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_14:30:00.15min.usgsTimeSlice.ncdf\ndfb70e96abf84ed6303b0759f27948ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_14:45:00.15min.usgsTimeSlice.ncdf\n32f313d0ed7f4658520796a04f12e5ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_15:00:00.15min.usgsTimeSlice.ncdf\na234bcb8e48b28d7ff69a9d38f2e0757  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_15:15:00.15min.usgsTimeSlice.ncdf\n50c90e1030d94c6c88ae09e71f27899a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_15:30:00.15min.usgsTimeSlice.ncdf\n4ff3013935544c9d39a8fa91fc583bcf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_15:45:00.15min.usgsTimeSlice.ncdf\nbf662da762fa20d6a5b84b650de5e133  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_16:00:00.15min.usgsTimeSlice.ncdf\nd69527eea695a2cdccadac24a55d74dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_16:15:00.15min.usgsTimeSlice.ncdf\n85fddceca9229e32cdd6ebef91205110  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_16:30:00.15min.usgsTimeSlice.ncdf\nd8b65389ed286b29ee9337dcf289df61  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_16:45:00.15min.usgsTimeSlice.ncdf\ncea0526c78280f39b569dd30dae3772a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_17:00:00.15min.usgsTimeSlice.ncdf\n35eae5e431203bdc8142e0ef79586948  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_17:15:00.15min.usgsTimeSlice.ncdf\n3f189ed6b6a160f8000e737f067ea61a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_17:30:00.15min.usgsTimeSlice.ncdf\n419ed80f167e271f53f8609d96a59604  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_17:45:00.15min.usgsTimeSlice.ncdf\n794ae8218a3489a971f42847f3ca2353  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_18:00:00.15min.usgsTimeSlice.ncdf\n2833b6874bfa83041e8357158c85de38  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_18:15:00.15min.usgsTimeSlice.ncdf\nbf7c99b175ea67d121fb3e0cb278a3d8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_18:30:00.15min.usgsTimeSlice.ncdf\n6946470a8b308e45750122555799205e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_18:45:00.15min.usgsTimeSlice.ncdf\nfb7793418589dfe46973bffd273e4e88  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_19:00:00.15min.usgsTimeSlice.ncdf\n963e0a58b0f9fb99953873505621e0a0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_19:15:00.15min.usgsTimeSlice.ncdf\nd833c377b91ac4bb4cedde3f145617cd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_19:30:00.15min.usgsTimeSlice.ncdf\nc35ccb1d4ca497a007e03a093a96e316  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_19:45:00.15min.usgsTimeSlice.ncdf\n4c1c3d99e09eb9f2d1d6dee6f2c35dd7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_20:00:00.15min.usgsTimeSlice.ncdf\n52b19566ed25b38ed84272dbe65881bb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_20:15:00.15min.usgsTimeSlice.ncdf\nbf29b14c975175bfb57bf470ebf8cb0d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_20:30:00.15min.usgsTimeSlice.ncdf\n3861056cf44123936af1579e39dac3e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_20:45:00.15min.usgsTimeSlice.ncdf\n57f4da883ce80fb437d2508e445240d8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_21:00:00.15min.usgsTimeSlice.ncdf\n3ba4d149c3406d0064f192e4239971be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_21:15:00.15min.usgsTimeSlice.ncdf\n7d75717b0ecbb1eccfe75204c2ed013f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_21:30:00.15min.usgsTimeSlice.ncdf\n06c78eee47299870f7888bf1a0356a15  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_21:45:00.15min.usgsTimeSlice.ncdf\n4d95c0acaa08f3a8885f318d2c1a1e89  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_22:00:00.15min.usgsTimeSlice.ncdf\n2744fbca5e677026480c4af5a542e351  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_22:15:00.15min.usgsTimeSlice.ncdf\nd3b2179518c44ef2c477adbcfb63c8b6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_22:30:00.15min.usgsTimeSlice.ncdf\nb756f5c503be1dacf3d922970ac8aff5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_22:45:00.15min.usgsTimeSlice.ncdf\n21688e1485c3bdbb02a80b6c1d139dce  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_23:00:00.15min.usgsTimeSlice.ncdf\n62a6ffcedac8daba49a7ff3098fd5458  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_23:15:00.15min.usgsTimeSlice.ncdf\nfa096b1d877351f03cb44be7ee20f6d6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_23:30:00.15min.usgsTimeSlice.ncdf\nbb14d23151dfccee470a549e1c31e10b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-27_23:45:00.15min.usgsTimeSlice.ncdf\nbb9c3e9ea82edb787d4b40978807d8dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_00:00:00.15min.usgsTimeSlice.ncdf\nda0fdafb056caf6eefc44bcd9be54ca8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_00:15:00.15min.usgsTimeSlice.ncdf\nc0b5146137bba9de76d820bdb9c84663  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_00:30:00.15min.usgsTimeSlice.ncdf\n5beadb65d9f45f5c5cd1bf1dd6db5756  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_00:45:00.15min.usgsTimeSlice.ncdf\n746bbc9a12b83f55b5aabde57bbd93f5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_01:00:00.15min.usgsTimeSlice.ncdf\n1bea98afb1896917453d7053ef5c5181  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_01:15:00.15min.usgsTimeSlice.ncdf\ne6cc8c43ae4e257c5c56badcc7068814  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_01:30:00.15min.usgsTimeSlice.ncdf\nbfced8169fc66c864104ac06e1530c7b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_01:45:00.15min.usgsTimeSlice.ncdf\n554051a0d92b170c14bce3c6d8a5a97c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_02:00:00.15min.usgsTimeSlice.ncdf\nec1cb1d9ce406076d072f658da86e9f9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_02:15:00.15min.usgsTimeSlice.ncdf\nf47d1b45611782990bff92bb0214f89a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_02:30:00.15min.usgsTimeSlice.ncdf\n26c23b58951ca2be2b9d75c697c529b0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_02:45:00.15min.usgsTimeSlice.ncdf\nb1a26ab87e48334180edc281dcd9a1d1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_03:00:00.15min.usgsTimeSlice.ncdf\n7dbe297398638c7709cad5e64760e55d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_03:15:00.15min.usgsTimeSlice.ncdf\nf6ca5985cfd7ab5528a776b2159285d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_03:30:00.15min.usgsTimeSlice.ncdf\nda9982fdfb825dbb277104b800f38961  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_03:45:00.15min.usgsTimeSlice.ncdf\nd701e3eaf84f78056987e1291b82200b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_04:00:00.15min.usgsTimeSlice.ncdf\n0fa3804ba51d71056824c5447c34ea81  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_04:15:00.15min.usgsTimeSlice.ncdf\na1cf4da14ad5bb6cf13ffcde71d1719a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_04:30:00.15min.usgsTimeSlice.ncdf\nab6bde988da107bbad28c61ed11f2d85  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_04:45:00.15min.usgsTimeSlice.ncdf\n6240a58e08ea0c48005df7cd0d4d58e9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_05:00:00.15min.usgsTimeSlice.ncdf\n155b71a6c4f5697b1a32d61a56665487  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_05:15:00.15min.usgsTimeSlice.ncdf\nc694540df89def26749003af5e27436a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_05:30:00.15min.usgsTimeSlice.ncdf\ndbf97d87487c2bb90dc6c8c95c1e6e65  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_05:45:00.15min.usgsTimeSlice.ncdf\n7b2f48c5119adcfaffe35fd76eb424c2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_06:00:00.15min.usgsTimeSlice.ncdf\n35d187729a1975463cb7e91cc2f5c8c0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_06:15:00.15min.usgsTimeSlice.ncdf\n90cf169375ac4d7ea360f9a44da451d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_06:30:00.15min.usgsTimeSlice.ncdf\n150a484c40375494b15277921a5cd479  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_06:45:00.15min.usgsTimeSlice.ncdf\nabffef7b364cb4528fba88d83369f7dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_07:00:00.15min.usgsTimeSlice.ncdf\n94be1b2b8737fad6b77b9f2f095c978e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_07:15:00.15min.usgsTimeSlice.ncdf\n3359757694a4d60c32c7ebd83ff1b44c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_07:30:00.15min.usgsTimeSlice.ncdf\nfd6ff471c4cf157a2227bdff9f5297a0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_07:45:00.15min.usgsTimeSlice.ncdf\n5fe134926347b83d1b1ee67972b5eb02  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_08:00:00.15min.usgsTimeSlice.ncdf\nfff50cbef97bac52834c058e34f4d78a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_08:15:00.15min.usgsTimeSlice.ncdf\nac7ebafcbe697036af0ff0f4787c5e74  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_08:30:00.15min.usgsTimeSlice.ncdf\nd7ff4fd10016e1abeb5bd57519ab8797  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_08:45:00.15min.usgsTimeSlice.ncdf\na2b9cfd486eb43c3f7515798d699b21c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_09:00:00.15min.usgsTimeSlice.ncdf\n2aadbec2a6c8c3c34324e6091bcc5f33  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_09:15:00.15min.usgsTimeSlice.ncdf\n1be349f8c90cbbd4f59150f17b33fa61  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_09:30:00.15min.usgsTimeSlice.ncdf\n22c25c50e33629c58a48ec39418e5191  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_09:45:00.15min.usgsTimeSlice.ncdf\n1f45e570bcaf6f4656d67497cfca72a4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_10:00:00.15min.usgsTimeSlice.ncdf\na912f10fa6283414838701845079d467  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_10:15:00.15min.usgsTimeSlice.ncdf\n227dd80fa3b46dbb122f08a3274c7c94  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_10:30:00.15min.usgsTimeSlice.ncdf\n1b1537743e0baa1b92316ebb7bf5252e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_10:45:00.15min.usgsTimeSlice.ncdf\n525c3a3a64e7cc53508485890a3c78ab  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_11:00:00.15min.usgsTimeSlice.ncdf\n12625b0c3f36a1d65b4d300650df3ac7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_11:15:00.15min.usgsTimeSlice.ncdf\n1f442c2eac1664ca67e8bcd95478c0b9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_11:30:00.15min.usgsTimeSlice.ncdf\n07c77ae0d95ea21c3cad9eaf157a1771  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_11:45:00.15min.usgsTimeSlice.ncdf\n7f6a635f633f9cdc9bcb3f1e95aab02d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_12:00:00.15min.usgsTimeSlice.ncdf\n5c817ed29e04b695fd58add4879f82d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_12:15:00.15min.usgsTimeSlice.ncdf\nb4afb38f4ce8e072bf8356213c24f31a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_12:30:00.15min.usgsTimeSlice.ncdf\n725504ce4f4dc2ce870f6699208410b0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_12:45:00.15min.usgsTimeSlice.ncdf\nc75ae5bd1d7646b6b6e18d2539972d05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_13:00:00.15min.usgsTimeSlice.ncdf\n10a5a841d41198bb3d69d1dfa2ff2c59  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_13:15:00.15min.usgsTimeSlice.ncdf\n97f363496c1eb5d9d9dd3565c887d6af  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_13:30:00.15min.usgsTimeSlice.ncdf\ncb5c6c10ba341cfa4acac36a40dbc900  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_13:45:00.15min.usgsTimeSlice.ncdf\n100236246ef04bd4dbf89ce1ee124b7b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_14:00:00.15min.usgsTimeSlice.ncdf\n023852d4dd3abe6601041c2d855e4744  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_14:15:00.15min.usgsTimeSlice.ncdf\naa46ea2698babbb94c39c46837947403  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_14:30:00.15min.usgsTimeSlice.ncdf\n67cdcc192f45efcda0b0871a53f344ee  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_14:45:00.15min.usgsTimeSlice.ncdf\nec5e5d3c3edb8fe143ad44425434c9b3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_15:00:00.15min.usgsTimeSlice.ncdf\nfd1264df5ea93c21f7c6289ee8b67bdf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_15:15:00.15min.usgsTimeSlice.ncdf\n8ffc03d6eba8994785b14d46ada17689  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_15:30:00.15min.usgsTimeSlice.ncdf\nbfd7a13906c0cc8337671e6e5394d801  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_15:45:00.15min.usgsTimeSlice.ncdf\n11d0ab30cd95bfff850ff72d38bbbc66  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_16:00:00.15min.usgsTimeSlice.ncdf\nbc82dbd579dba0ce962cca5697d2abb2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_16:15:00.15min.usgsTimeSlice.ncdf\nb9b1c1cbc76cdcebcce57f9506ae1b7c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_16:30:00.15min.usgsTimeSlice.ncdf\n4fe6083b8ca34a65c075ada1262da179  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_16:45:00.15min.usgsTimeSlice.ncdf\nb0b36b0421441fb74c4a50ef28fdf989  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_17:00:00.15min.usgsTimeSlice.ncdf\n6f1fe70d03e478427b5bb572b006c0b4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_17:15:00.15min.usgsTimeSlice.ncdf\nf2a03e7b7a298f24e9876f6fb94800c3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_17:30:00.15min.usgsTimeSlice.ncdf\n152a8f77418f991b159efaa8e5f5b733  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_17:45:00.15min.usgsTimeSlice.ncdf\naf18013b7c13b77e1df3c87164ee5e05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_18:00:00.15min.usgsTimeSlice.ncdf\n310a984c8da96eb632af5ae2128f2c0b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_18:15:00.15min.usgsTimeSlice.ncdf\n939f75f2e31e7e538416bd81fc301de7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_18:30:00.15min.usgsTimeSlice.ncdf\n05f74348230daa6a273b93ea409d3b58  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_18:45:00.15min.usgsTimeSlice.ncdf\n61a316f53e1a9e1f320f41a751bd2986  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_19:00:00.15min.usgsTimeSlice.ncdf\n597bd82160ef5b375dc617b326475671  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_19:15:00.15min.usgsTimeSlice.ncdf\n47d5e8cad3532ee4a6f7ea704a4d2858  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_19:30:00.15min.usgsTimeSlice.ncdf\n045a68044adafc415b0df163c3ce1ee6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_19:45:00.15min.usgsTimeSlice.ncdf\n68deb9cb2c8e4546a2042735ce69421e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_20:00:00.15min.usgsTimeSlice.ncdf\n5f7502c612d1e75751acea7ce90e13d6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_20:15:00.15min.usgsTimeSlice.ncdf\nc2d0e89e57d9da0d89ae75193e2bc121  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_20:30:00.15min.usgsTimeSlice.ncdf\na87f0b976855197a0b4416a1d7db7ed6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_20:45:00.15min.usgsTimeSlice.ncdf\nf7e4ae8df1f1a7dfb9b8d2c38717d4be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_21:00:00.15min.usgsTimeSlice.ncdf\nf78b91604e9c507f72c2a5cacb3c3e38  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_21:15:00.15min.usgsTimeSlice.ncdf\ncf2adb2b074c5779f0dd41a7363cf68c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_21:30:00.15min.usgsTimeSlice.ncdf\n1f698660a73f69a633da7d860a9caa37  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_21:45:00.15min.usgsTimeSlice.ncdf\n7d958dbfcae7be4c14c96423410a8b82  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_22:00:00.15min.usgsTimeSlice.ncdf\n81337b86f0a6cce0d9eaa156b45b6f46  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_22:15:00.15min.usgsTimeSlice.ncdf\n1247083995cb9c440f2856292f041844  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_22:30:00.15min.usgsTimeSlice.ncdf\n24008d77ad2ff80495e7310e619ed302  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_22:45:00.15min.usgsTimeSlice.ncdf\n87acfd402dba1f136d81156a0e2eb8aa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_23:00:00.15min.usgsTimeSlice.ncdf\n560e15d9ea36168a792fcb71e02f2e86  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_23:15:00.15min.usgsTimeSlice.ncdf\n56257efcf12979899fc25c21690f5fdd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_23:30:00.15min.usgsTimeSlice.ncdf\nc3a1faf5d9897ed29c701611f5b935dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-28_23:45:00.15min.usgsTimeSlice.ncdf\ndc043d3c634e29a3246f72efaf79266a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_00:00:00.15min.usgsTimeSlice.ncdf\n7c1203d7ec855d09b4b4d660cef089a9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_00:15:00.15min.usgsTimeSlice.ncdf\naa07490402076de69b3768ba474954ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_00:30:00.15min.usgsTimeSlice.ncdf\ndc05f6060908ea0d03ce06c225cc319e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_00:45:00.15min.usgsTimeSlice.ncdf\n3404499aa3dc1eb4a9fb8809b4b3d466  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_01:00:00.15min.usgsTimeSlice.ncdf\n3357078cb4b87857bce498deb82504fb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_01:15:00.15min.usgsTimeSlice.ncdf\n31c9b67e5a2204eda623a19fe5c919e4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_01:30:00.15min.usgsTimeSlice.ncdf\na7aa284f557cf303340109ac861855d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_01:45:00.15min.usgsTimeSlice.ncdf\n274b98ddd478465042d8a9b2501f53fb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_02:00:00.15min.usgsTimeSlice.ncdf\n0019d471898c8bcb94e629c240d4cae7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_02:15:00.15min.usgsTimeSlice.ncdf\n51c2022d4b0bced4eebdd4f497c593dd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_02:30:00.15min.usgsTimeSlice.ncdf\nda06cdf565a499b9779e9c4a031f4789  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_02:45:00.15min.usgsTimeSlice.ncdf\nbff1b1641b0dea12a77b335b66a4105d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_03:00:00.15min.usgsTimeSlice.ncdf\n376f9f36b557c8e2a1cade3891242c3c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_03:15:00.15min.usgsTimeSlice.ncdf\n59695594ca155612ae131419a38dd89c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_03:30:00.15min.usgsTimeSlice.ncdf\ne8e45d93e9f9f5c538d3d9275392bb20  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_03:45:00.15min.usgsTimeSlice.ncdf\n3c02719c93a488419b23160412251400  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_04:00:00.15min.usgsTimeSlice.ncdf\n9caf696b39734b985b989e5b6ca50840  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_04:15:00.15min.usgsTimeSlice.ncdf\n872af62808c3ceb92d419877ed5e2736  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_04:30:00.15min.usgsTimeSlice.ncdf\nb8f00dcaaeb966e1d07f9c745341195b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_04:45:00.15min.usgsTimeSlice.ncdf\n534b9213fba96e5b320808ff53b86bf7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_05:00:00.15min.usgsTimeSlice.ncdf\n49a3e4b36cbfa6d3677dfe9f301bbc10  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_05:15:00.15min.usgsTimeSlice.ncdf\n31177994b65b649eebf04b0b24c9b262  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_05:30:00.15min.usgsTimeSlice.ncdf\n5bbbca21714295970084f8f6c1ccca59  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_05:45:00.15min.usgsTimeSlice.ncdf\n37bcbff8ce5d045dd5ab78889cdc0186  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_06:00:00.15min.usgsTimeSlice.ncdf\nfc1cab03c5f6a9cc874ca37d54c252e2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_06:15:00.15min.usgsTimeSlice.ncdf\n638c92a85fccda10855d58560e3b5cda  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_06:30:00.15min.usgsTimeSlice.ncdf\n5549455a03001787390f7efeae49cf33  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_06:45:00.15min.usgsTimeSlice.ncdf\nb75f1ce08b4d61798868c5ac8d8c6eb4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_07:00:00.15min.usgsTimeSlice.ncdf\n666839c56479c1cd8c6c6eabcddc6645  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_07:15:00.15min.usgsTimeSlice.ncdf\n31febf02b132ec5997a4029bf56507d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_07:30:00.15min.usgsTimeSlice.ncdf\n3e42bd0fe86f5437ce37852a781446a2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_07:45:00.15min.usgsTimeSlice.ncdf\nf87f5b766b92ce0581d798d8434c038d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_08:00:00.15min.usgsTimeSlice.ncdf\n080adf8d5a19dbbc747c7045aef91771  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_08:15:00.15min.usgsTimeSlice.ncdf\n3bc0814a909fc075a20037dc7798ce09  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_08:30:00.15min.usgsTimeSlice.ncdf\n509fbc564fa0aa5f6863a9483d4d7ea3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_08:45:00.15min.usgsTimeSlice.ncdf\n87d1ca5b399be16821153fc40f1b50ae  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_09:00:00.15min.usgsTimeSlice.ncdf\n9cd90305ebb47b62db6cbd40b0e46d1d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_09:15:00.15min.usgsTimeSlice.ncdf\n72baafdfcdd1747a4f1be5a3b8582202  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_09:30:00.15min.usgsTimeSlice.ncdf\n3f5d9f83e8d296a3e00a675736d4d209  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_09:45:00.15min.usgsTimeSlice.ncdf\n78a1847c44777edf23ab03361ca61e53  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_10:00:00.15min.usgsTimeSlice.ncdf\nddea2e0c3f09772ab33c9fb4af8e9851  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_10:15:00.15min.usgsTimeSlice.ncdf\n67180f569753ab3dde36166272c6bcd9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_10:30:00.15min.usgsTimeSlice.ncdf\n039d002d214199708f4e27dbfc320584  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_10:45:00.15min.usgsTimeSlice.ncdf\n0333d129e33f2d044478e9a1cc8686dc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_11:00:00.15min.usgsTimeSlice.ncdf\n76855f2df6f9a09b290a0fa584e38746  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_11:15:00.15min.usgsTimeSlice.ncdf\n408337f2cfa593b97cbb956d80beb3ae  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_11:30:00.15min.usgsTimeSlice.ncdf\na89a3c487add2d794f93ada17d1ccaa5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_11:45:00.15min.usgsTimeSlice.ncdf\nbb36dc948d8ad8f15c26dd835ee73d2a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_12:00:00.15min.usgsTimeSlice.ncdf\n8093d29f972c967c42d58ac2002caace  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_12:15:00.15min.usgsTimeSlice.ncdf\n0d3c63fdcea3b26c5adc4ba81600da17  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_12:30:00.15min.usgsTimeSlice.ncdf\n3715049c698e24d56a3a2d9cf580b8a8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_12:45:00.15min.usgsTimeSlice.ncdf\n345dc7e83b9546a75c315d2697e42d13  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_13:00:00.15min.usgsTimeSlice.ncdf\n6076027c73a7a76187383d8a487957c2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_13:15:00.15min.usgsTimeSlice.ncdf\n023beacaf382f9d8caabc9c58da25776  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_13:30:00.15min.usgsTimeSlice.ncdf\n9eb6e64d586dc99eaefaf69070d14bf1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_13:45:00.15min.usgsTimeSlice.ncdf\nd99c8573d8df2383441b489a1d40fa2c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_14:00:00.15min.usgsTimeSlice.ncdf\nb7181bf8e4421565eb4b3528c7ff2be9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_14:15:00.15min.usgsTimeSlice.ncdf\nd40031ee77ccf481f38c660a1d0ced81  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_14:30:00.15min.usgsTimeSlice.ncdf\n2100039cf65b9b9e36bcd804f6620376  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_14:45:00.15min.usgsTimeSlice.ncdf\n399e24f097c5b498eef3d3ea79baadc3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_15:00:00.15min.usgsTimeSlice.ncdf\n40758b424f769dc0218a32c21f28377e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_15:15:00.15min.usgsTimeSlice.ncdf\nccbb7ac90489325c1a51af77bbd08943  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_15:30:00.15min.usgsTimeSlice.ncdf\n2bedb1823884e5aa2aa00b05cec837a8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_15:45:00.15min.usgsTimeSlice.ncdf\n07c367e0e2688a558b3ef0c2b24bb7aa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_16:00:00.15min.usgsTimeSlice.ncdf\ndd2b7b29017b1fd3fd1878a6ef4abd08  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_16:15:00.15min.usgsTimeSlice.ncdf\n002361bc634816179cd8b6f4fc84f7de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_16:30:00.15min.usgsTimeSlice.ncdf\ndec34d2d5381ede1c6267cb7cff72741  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_16:45:00.15min.usgsTimeSlice.ncdf\nc24ee3c5934488725771addec1915d63  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_17:00:00.15min.usgsTimeSlice.ncdf\nbe2d677f75c341973e7076b05cedae02  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_17:15:00.15min.usgsTimeSlice.ncdf\n8659698b65e56e58883f0e6d29e6012d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_17:30:00.15min.usgsTimeSlice.ncdf\nd1ea0bf7222d913d3a5302286a3b6dc3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_17:45:00.15min.usgsTimeSlice.ncdf\n600e9a878e8b26225941f6848cfe1549  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_18:00:00.15min.usgsTimeSlice.ncdf\n72b73f2dc5f04d48e5a71e0186b74616  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_18:15:00.15min.usgsTimeSlice.ncdf\nd0e3f1cc7a52922bc22bf1ce88241a3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_18:30:00.15min.usgsTimeSlice.ncdf\n069ecb32552395adf9593cbf1d1d4a77  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_18:45:00.15min.usgsTimeSlice.ncdf\n569dab0bb9bb56f9ebb9fce92c6af707  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_19:00:00.15min.usgsTimeSlice.ncdf\nac5799e6a9b13b746c03ccd6f4f00517  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_19:15:00.15min.usgsTimeSlice.ncdf\nde341b162a86523781abb6928c51156d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_19:30:00.15min.usgsTimeSlice.ncdf\n5451be707501636cc40f03fb12bbefbe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_19:45:00.15min.usgsTimeSlice.ncdf\na7fa793da3c242d2ef1171488d11e09c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_20:00:00.15min.usgsTimeSlice.ncdf\n3e1e0d669b165f2903ff59e043bf2140  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_20:15:00.15min.usgsTimeSlice.ncdf\n56ed95a232ca8e1095246bd280769bff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_20:30:00.15min.usgsTimeSlice.ncdf\nc78f60742f3b7bd200776d1d64f25a4c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_20:45:00.15min.usgsTimeSlice.ncdf\nfbdde76daca94d09ed16d245f79fb9bb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_21:00:00.15min.usgsTimeSlice.ncdf\n7333e360f6e812b9f0ee8400f744dfe0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_21:15:00.15min.usgsTimeSlice.ncdf\n049da88d1103e9dc5c52ba31a3d4efbf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_21:30:00.15min.usgsTimeSlice.ncdf\nfb1b1b3cf8603cec23feca18cd67ed37  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_21:45:00.15min.usgsTimeSlice.ncdf\n537845fa8b8508e9eea744296fe6cbdb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_22:00:00.15min.usgsTimeSlice.ncdf\n3e88c52370b2f299d73e476afdcf37df  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_22:15:00.15min.usgsTimeSlice.ncdf\nbbea20be0c40bb50a6d3c0f21d02a50f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_22:30:00.15min.usgsTimeSlice.ncdf\n1b24deb9c1f0e9f03aac6ffafeca59a4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_22:45:00.15min.usgsTimeSlice.ncdf\n98f4b74005b8d1ad48a5bcae7d78b676  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_23:00:00.15min.usgsTimeSlice.ncdf\n5863a3d56c50ac2790ebf9fb6a3a0ff4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_23:15:00.15min.usgsTimeSlice.ncdf\n7b937b1a84baebb284956d5523e454b1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_23:30:00.15min.usgsTimeSlice.ncdf\ne915d21199c94d7726f537b443d56b01  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-29_23:45:00.15min.usgsTimeSlice.ncdf\n06ba1fd5dce4e670c0d20e32fa758ff1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_00:00:00.15min.usgsTimeSlice.ncdf\neadeb440aaaae03cbbfc05280549f541  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_00:15:00.15min.usgsTimeSlice.ncdf\ne4e558970edfbf952be86425d2c006e4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_00:30:00.15min.usgsTimeSlice.ncdf\nbac2dd5d4b9a60b3e39caa6e7bcaf8de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_00:45:00.15min.usgsTimeSlice.ncdf\n8e4a891677c422e394258010792037d0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_01:00:00.15min.usgsTimeSlice.ncdf\nba96b0ee9c2a8eae7b7f53db39a9ff74  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_01:15:00.15min.usgsTimeSlice.ncdf\na84a828e462fd7cf6856c81c4f2b95e8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_01:30:00.15min.usgsTimeSlice.ncdf\nfbb40c7bd4f750c617427000448117fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_01:45:00.15min.usgsTimeSlice.ncdf\n2363309a4becb3713a7a7c872c8e472e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_02:00:00.15min.usgsTimeSlice.ncdf\n4a20ae83395087de50dcdfe64ae3b14c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_02:15:00.15min.usgsTimeSlice.ncdf\n6befc05ea598ab5b858f5a4032d89d57  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_02:30:00.15min.usgsTimeSlice.ncdf\nb57b951d735b592b44e031ae74c5d3e7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_02:45:00.15min.usgsTimeSlice.ncdf\n79691020b2085362f9c07805b67583ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_03:00:00.15min.usgsTimeSlice.ncdf\na16350b323079c3faf6b9494f2ef9388  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_03:15:00.15min.usgsTimeSlice.ncdf\nb84656d5e8afcf5782ea465a2d7d463b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_03:30:00.15min.usgsTimeSlice.ncdf\n9090ad461cd440fdb673c15d67f4fbc6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_03:45:00.15min.usgsTimeSlice.ncdf\na48096cfb33612d18ff38cea3b89923c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_04:00:00.15min.usgsTimeSlice.ncdf\n4f9c19de8be8e89bebc5d66548406637  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_04:15:00.15min.usgsTimeSlice.ncdf\nf3daa6c841b9f534d367883f647e6170  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_04:30:00.15min.usgsTimeSlice.ncdf\nb025ee44dda5394fc5d08cac5f00ac0c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_04:45:00.15min.usgsTimeSlice.ncdf\n5cb6896d0ca20a35942f1d02b73190b8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_05:00:00.15min.usgsTimeSlice.ncdf\n2479b6358e85f85137c2aa1a10b141de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_05:15:00.15min.usgsTimeSlice.ncdf\n960532c12948abb04fa49f5a26c8d664  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_05:30:00.15min.usgsTimeSlice.ncdf\nfdc1bf14faba29fd42c5f520bc385410  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_05:45:00.15min.usgsTimeSlice.ncdf\nb880af0800aab5e23ccc8d57432dba12  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_06:00:00.15min.usgsTimeSlice.ncdf\n745162f6b8bcab3e5ac04ddae8e9c5da  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_06:15:00.15min.usgsTimeSlice.ncdf\n0f9b7b78727232a83d2365bc8bc0e1d7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_06:30:00.15min.usgsTimeSlice.ncdf\nc5f8f3d3b8dfebd57f05137d231ea8bb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_06:45:00.15min.usgsTimeSlice.ncdf\nb36879288b54d356b6d8a80b0c652446  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_07:00:00.15min.usgsTimeSlice.ncdf\n94610184ad4d23753bcd5ef8f6db7927  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_07:15:00.15min.usgsTimeSlice.ncdf\n18a8fc47bb76fd03aebb623fd4debba4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_07:30:00.15min.usgsTimeSlice.ncdf\n3b311d5b881eacff5ab46d33382aed0e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_07:45:00.15min.usgsTimeSlice.ncdf\nc660b060158535193fbd41ffdd9cef4c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_08:00:00.15min.usgsTimeSlice.ncdf\n4a79395ed656869e3726a02f7701c499  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_08:15:00.15min.usgsTimeSlice.ncdf\nd0fe55c7b8b11db60910adf265311851  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_08:30:00.15min.usgsTimeSlice.ncdf\n2b41edd0550663267cc5a8aed47a8f21  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_08:45:00.15min.usgsTimeSlice.ncdf\nc9445ff32268f1fb822b697fe550600d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_09:00:00.15min.usgsTimeSlice.ncdf\nd7871d27f83ad8a8b96a17d090849929  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_09:15:00.15min.usgsTimeSlice.ncdf\na86f5dabd9d18f7140cff4c9887cc2f0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_09:30:00.15min.usgsTimeSlice.ncdf\nbfb7f1f721ec372a46e6c9413b7fbec3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_09:45:00.15min.usgsTimeSlice.ncdf\nbeb1e252573f33eb1a97380b67be1d20  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_10:00:00.15min.usgsTimeSlice.ncdf\n4abf47c4fc9c731e1da2827062a937d0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_10:15:00.15min.usgsTimeSlice.ncdf\n917ed389a2f894ae134340c5578e36eb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_10:30:00.15min.usgsTimeSlice.ncdf\n9880e142d02c9247fb768c25a5c66fa4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_10:45:00.15min.usgsTimeSlice.ncdf\n0852f264e86c5b6e41181d6971aa3013  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_11:00:00.15min.usgsTimeSlice.ncdf\n217360f1cef8970ed6b552ed59c7f9ef  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_11:15:00.15min.usgsTimeSlice.ncdf\n5756ea008cce66f6f7962da7541851ab  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_11:30:00.15min.usgsTimeSlice.ncdf\n6de864d320606d4a7c898551cdd36b40  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_11:45:00.15min.usgsTimeSlice.ncdf\nd153b5995f647a1ce42a8dca968ae399  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_12:00:00.15min.usgsTimeSlice.ncdf\nef4e36c54bd9272cb1a4d95b78875f58  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_12:15:00.15min.usgsTimeSlice.ncdf\nf6069ded04d5694482b6218fba981bc7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_12:30:00.15min.usgsTimeSlice.ncdf\n5a2d7b48ed8e9eae0dd57ef6fcd03b3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_12:45:00.15min.usgsTimeSlice.ncdf\nf719768b54cd91bcfd258e0e556c6b26  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_13:00:00.15min.usgsTimeSlice.ncdf\n42da4a9f1c45dded8cd29e3c92fb3696  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_13:15:00.15min.usgsTimeSlice.ncdf\n05ba5cee16b67cac5b8caee0689c05d7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_13:30:00.15min.usgsTimeSlice.ncdf\n39087e1d3f629d3de415e22eaaba5c82  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_13:45:00.15min.usgsTimeSlice.ncdf\n67ef82258682a5716f7db295f64b8742  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_14:00:00.15min.usgsTimeSlice.ncdf\n1ea6c1db6f6dfb516622916cd31f5af6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_14:15:00.15min.usgsTimeSlice.ncdf\n0394ee3c4db756dc67abef6807dfcd7f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_14:30:00.15min.usgsTimeSlice.ncdf\n3b3a0879d97d2b1e74d2679226c35155  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_14:45:00.15min.usgsTimeSlice.ncdf\nc49a59d827d41ac0835943ddbf447b4b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_15:00:00.15min.usgsTimeSlice.ncdf\ne4fdb38428a23b335d73bd1cbba8a661  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_15:15:00.15min.usgsTimeSlice.ncdf\n4ed7063a3290552153a5163c586425e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_15:30:00.15min.usgsTimeSlice.ncdf\n2eb4e6a1645133c4284873e908a03f0f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_15:45:00.15min.usgsTimeSlice.ncdf\n6139e698bb311480d516fbc45c81532d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_16:00:00.15min.usgsTimeSlice.ncdf\nb82f83ead8b0bdab8348a743aa54daa7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_16:15:00.15min.usgsTimeSlice.ncdf\n4fbb9f0d8223252a36d8b20158237db6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_16:30:00.15min.usgsTimeSlice.ncdf\n021ec256865c6bd75e2919f9d0ba4819  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_16:45:00.15min.usgsTimeSlice.ncdf\na76c081a73259148e3053e953bf7e774  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_17:00:00.15min.usgsTimeSlice.ncdf\n0dc7388a1fd49025a9450977de7b160b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_17:15:00.15min.usgsTimeSlice.ncdf\naa3101ed5626e30bd653cc1a3b831833  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_17:30:00.15min.usgsTimeSlice.ncdf\n4f64cf723332fc6cbaad7455e3f43abd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_17:45:00.15min.usgsTimeSlice.ncdf\n0356be3ffaeaebfd1c31b82c5fe2985f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_18:00:00.15min.usgsTimeSlice.ncdf\ncd3ada5c31942bd969b73c36e6f1a35d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_18:15:00.15min.usgsTimeSlice.ncdf\n6763b19d990afe7bd238d01990ab2542  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_18:30:00.15min.usgsTimeSlice.ncdf\nbc218dd809c52c7f070f6e87cf5fccd6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_18:45:00.15min.usgsTimeSlice.ncdf\nbf35619d726120989819e1cf0f1d95df  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_19:00:00.15min.usgsTimeSlice.ncdf\n1a17392c1248de7c1c247826fed9847e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_19:15:00.15min.usgsTimeSlice.ncdf\nc1efff477e5c4c2c2e6bb420db41bc7a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_19:30:00.15min.usgsTimeSlice.ncdf\n9825dc0d94533e21d87721750134c2b9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_19:45:00.15min.usgsTimeSlice.ncdf\n769664df35f74d2b86eb80210f2be141  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_20:00:00.15min.usgsTimeSlice.ncdf\n994d57d631d56b6422dad5ce64e65378  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_20:15:00.15min.usgsTimeSlice.ncdf\n94af9e19dbc3acca1f55e3a180e71b1d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_20:30:00.15min.usgsTimeSlice.ncdf\nac6c4c67d474289862257cc2dca1a79c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_20:45:00.15min.usgsTimeSlice.ncdf\n878ebf21827892b7b4d407799efb6622  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_21:00:00.15min.usgsTimeSlice.ncdf\ne9bf46b1c9e5894783ead4a931380eb9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_21:15:00.15min.usgsTimeSlice.ncdf\n2d479cf46ee0686ef787143fdb9adf17  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_21:30:00.15min.usgsTimeSlice.ncdf\n615aef0e1f4073a6938ad0f314fe8c69  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_21:45:00.15min.usgsTimeSlice.ncdf\n6651ebe878dfe54746d09fd812997ae3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_22:00:00.15min.usgsTimeSlice.ncdf\n5a01840af836e6b82ca56b985ec35695  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_22:15:00.15min.usgsTimeSlice.ncdf\nc6b8628820a03d004909f104ff46aab5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_22:30:00.15min.usgsTimeSlice.ncdf\n9fb384f9fbfafeb05c53970b3a82da9e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_22:45:00.15min.usgsTimeSlice.ncdf\n8f2861639b9a46410cf94fc582006345  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_23:00:00.15min.usgsTimeSlice.ncdf\nc6facfbec43cfd03efcadcc0f9423a3e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_23:15:00.15min.usgsTimeSlice.ncdf\n06159a783e1a3c9f0410b24089e6997e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_23:30:00.15min.usgsTimeSlice.ncdf\n3e4f39966d3cde17f7f1847905424c1f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-30_23:45:00.15min.usgsTimeSlice.ncdf\nf34b32c7efef5f2319b70500efa95402  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_00:00:00.15min.usgsTimeSlice.ncdf\nd73ae0e68ba1dfb3ac9e3c16548612fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_00:15:00.15min.usgsTimeSlice.ncdf\n8fe4e0638f6585d3f1790b6811ba71da  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_00:30:00.15min.usgsTimeSlice.ncdf\n0294f4e03437016578b8c72490360cbd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_00:45:00.15min.usgsTimeSlice.ncdf\nfbbc8adccf0467dbb34e8d43be3e0dbe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_01:00:00.15min.usgsTimeSlice.ncdf\n21a593a2e9b84c6c4b110658e7193a3a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_01:15:00.15min.usgsTimeSlice.ncdf\n6236e61b3628bf259bbbca622a06362a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_01:30:00.15min.usgsTimeSlice.ncdf\n501438d298c27041ed3a6963c5f44d84  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_01:45:00.15min.usgsTimeSlice.ncdf\n01c2a7a3d577149d905048dfaf467899  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_02:00:00.15min.usgsTimeSlice.ncdf\n6bae0cb4d3aec1c26e3aa518c6416e7a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_02:15:00.15min.usgsTimeSlice.ncdf\n0c01256083403595f0eab19df140e6a9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_02:30:00.15min.usgsTimeSlice.ncdf\n9d9e91751d31823e7b4f8a84afc1cca4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_02:45:00.15min.usgsTimeSlice.ncdf\nd680ca9310735e445775f502fdfd328f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_03:00:00.15min.usgsTimeSlice.ncdf\nf180b13259ef6424fb8c16116776a629  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_03:15:00.15min.usgsTimeSlice.ncdf\n6e872c4d35af6c6ff6c9605617b26a4e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_03:30:00.15min.usgsTimeSlice.ncdf\n1c50352e23c8d2e63f482e99bb09231d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_03:45:00.15min.usgsTimeSlice.ncdf\n1261cf81f47259447e6d92ba0ae924f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_04:00:00.15min.usgsTimeSlice.ncdf\n7618ede06ff28cd35a2eaac4a478427c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_04:15:00.15min.usgsTimeSlice.ncdf\n0a5307e03799203e55554dd03a30c7fe  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_04:30:00.15min.usgsTimeSlice.ncdf\n30e375f040c53a2e585adae9ec5fdfd4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_04:45:00.15min.usgsTimeSlice.ncdf\n2dcbfa1fc8260f4c438d237d3675039a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_05:00:00.15min.usgsTimeSlice.ncdf\n57e10f5c7949611c916a78a76bbb64a0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_05:15:00.15min.usgsTimeSlice.ncdf\n1d211b258db5affa8564952646a585f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_05:30:00.15min.usgsTimeSlice.ncdf\na03e4aeb1ad47436b1ce73ccc50d9c49  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_05:45:00.15min.usgsTimeSlice.ncdf\n67134cb5e6be16db2c16ccb108862f71  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_06:00:00.15min.usgsTimeSlice.ncdf\n888de94d5d1b0a31222d8062ded3a447  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_06:15:00.15min.usgsTimeSlice.ncdf\n9b0ae699dd7d890f1ed0a02d984284ca  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_06:30:00.15min.usgsTimeSlice.ncdf\n94a534e7211f3c961e21ae26a28120cc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_06:45:00.15min.usgsTimeSlice.ncdf\n9832f018a7ab21016e1e3c256e6b2cb4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_07:00:00.15min.usgsTimeSlice.ncdf\nfed95f49fdd0cc6202508659b278b437  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_07:15:00.15min.usgsTimeSlice.ncdf\nd17b3f5a3e857840b47a350f92a5fbb7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_07:30:00.15min.usgsTimeSlice.ncdf\nc12635a4418d55ea21dbf60a9f35afe4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_07:45:00.15min.usgsTimeSlice.ncdf\nd2365c124543e08a8e691959daff84df  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_08:00:00.15min.usgsTimeSlice.ncdf\n794166ae00df039390bf55cf4cc44e67  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_08:15:00.15min.usgsTimeSlice.ncdf\n809aeb9ba8acb4aca50dcd32d5c6eda8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_08:30:00.15min.usgsTimeSlice.ncdf\n729f4ca464223c591ae71a1869541a48  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_08:45:00.15min.usgsTimeSlice.ncdf\n2858c01d472d1e49143d6cac12bc54fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_09:00:00.15min.usgsTimeSlice.ncdf\n20d01bdfe064cded27157ad7350cff85  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_09:15:00.15min.usgsTimeSlice.ncdf\n2c5df9fa558d9a5fb79a3d2cd4ed2c0a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_09:30:00.15min.usgsTimeSlice.ncdf\n60589e975e9a7f150e522ac635049209  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_09:45:00.15min.usgsTimeSlice.ncdf\n96824eb7a8e339c1b989c5a4a87c28a6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_10:00:00.15min.usgsTimeSlice.ncdf\nae86fd4b3cb34f20ef01541afb506a72  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_10:15:00.15min.usgsTimeSlice.ncdf\nce1b81741f1d7a57da622ee11f73ac6a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_10:30:00.15min.usgsTimeSlice.ncdf\nf78c784c9d2748cf0d3d35eee7b438ad  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_10:45:00.15min.usgsTimeSlice.ncdf\ndedaf05da4a69405c2d7932be825a8b3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_11:00:00.15min.usgsTimeSlice.ncdf\n44a290a5d31e38f237ea3a82a54a07f7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_11:15:00.15min.usgsTimeSlice.ncdf\nf7ac38946c28cd602dc3161a524901ff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_11:30:00.15min.usgsTimeSlice.ncdf\n77e8de0aabde135ecc32070e5d786108  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_11:45:00.15min.usgsTimeSlice.ncdf\n4320240e966d740c492865a0cc367904  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_12:00:00.15min.usgsTimeSlice.ncdf\n106fedf825b326303d1b648b04ac0ba3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_12:15:00.15min.usgsTimeSlice.ncdf\na67516d507d87260cccf856fd24b0e05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_12:30:00.15min.usgsTimeSlice.ncdf\na9fda41dfa560543a29129930e93ac93  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_12:45:00.15min.usgsTimeSlice.ncdf\nc0208881b74e35c64677f81289b721be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_13:00:00.15min.usgsTimeSlice.ncdf\n0e39b8615facbfffe58a8d502b5e3da7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_13:15:00.15min.usgsTimeSlice.ncdf\nc96765f18e5f6ebb09695ce7bdbf5516  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_13:30:00.15min.usgsTimeSlice.ncdf\n45317cdc6ef1907d5e253873b5cae4fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_13:45:00.15min.usgsTimeSlice.ncdf\n3da4941fea69fa55dce8f8460054aa5c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_14:00:00.15min.usgsTimeSlice.ncdf\naba053b54fb027f284da0d6b7878790b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_14:15:00.15min.usgsTimeSlice.ncdf\n7b499a86891ec1cb571bb01473c794f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_14:30:00.15min.usgsTimeSlice.ncdf\n311fe6dfa0f0a6cfae91f45f7397b737  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_14:45:00.15min.usgsTimeSlice.ncdf\n07250cd03203f7c4131f0e5eec2b69f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_15:00:00.15min.usgsTimeSlice.ncdf\n7f2982494cd217109c935015a0e72044  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_15:15:00.15min.usgsTimeSlice.ncdf\nf64887af3388db9700a27310a7617903  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_15:30:00.15min.usgsTimeSlice.ncdf\n83acf395009e08c509b23acebebea19c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_15:45:00.15min.usgsTimeSlice.ncdf\nafa915dc33bbe1cc4efbfcf3c1009c08  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_16:00:00.15min.usgsTimeSlice.ncdf\n1a4b79d855175ac5a599c6ac7848d646  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_16:15:00.15min.usgsTimeSlice.ncdf\n89b34f78e4886810676c9e4991a4b081  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_16:30:00.15min.usgsTimeSlice.ncdf\ncc49f1b6dc3a7977f0e27ca8951f829f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_16:45:00.15min.usgsTimeSlice.ncdf\n559a7874d4034c5c88c16a732453cffd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_17:00:00.15min.usgsTimeSlice.ncdf\nf27f05256c6625b43afdb21467e987fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_17:15:00.15min.usgsTimeSlice.ncdf\nac901cc4f6f310bb5a5e19679a73f9e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_17:30:00.15min.usgsTimeSlice.ncdf\n0193e6a9704283cd7b4b79f4b8fe6831  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_17:45:00.15min.usgsTimeSlice.ncdf\ncdc1c0729132ea9e867218b016404d9e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_18:00:00.15min.usgsTimeSlice.ncdf\n0a8d9ec3dc79d44f97197533a8189dff  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_18:15:00.15min.usgsTimeSlice.ncdf\n678e547aec573e6f0714c82df2dcffc0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_18:30:00.15min.usgsTimeSlice.ncdf\na9896b62327596171f1e83856c65f09c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_18:45:00.15min.usgsTimeSlice.ncdf\n5bd43eca92a4aca97eb4c7cc5e18fe9c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_19:00:00.15min.usgsTimeSlice.ncdf\n581c6045e50ac714ab4b220e8279fd48  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_19:15:00.15min.usgsTimeSlice.ncdf\na7a1821a187d0a5d6fd6c228d6bec6f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_19:30:00.15min.usgsTimeSlice.ncdf\n3205078640261e515c97c45fe91c2a29  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_19:45:00.15min.usgsTimeSlice.ncdf\n5bbd12fab48b33ab173a73b338ed6d79  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_20:00:00.15min.usgsTimeSlice.ncdf\n1d6247153c5ac166a3f9372e026bb4d7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_20:15:00.15min.usgsTimeSlice.ncdf\n79b21c3e84c598cd3890615e2efefe63  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_20:30:00.15min.usgsTimeSlice.ncdf\n042fce9e89dbe4a42cb33dfda3f9e558  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_20:45:00.15min.usgsTimeSlice.ncdf\n808d5cf8cd130cc76a7919a45298b135  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_21:00:00.15min.usgsTimeSlice.ncdf\n1226d149ce28bae77aa4ecc8bd5cba3e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_21:15:00.15min.usgsTimeSlice.ncdf\n32c8aa34e9ff62d45df1a38957b7c68a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_21:30:00.15min.usgsTimeSlice.ncdf\nbc5cf591019aa7f2a7a4fed7211c9da9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_21:45:00.15min.usgsTimeSlice.ncdf\n28209ff0d8355582a1305448a28e5f45  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_22:00:00.15min.usgsTimeSlice.ncdf\n25ced6fdc8220827f1bbbff2bb10a5ec  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_22:15:00.15min.usgsTimeSlice.ncdf\nebb2987cdc47dd26f6fa76b0ad458289  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_22:30:00.15min.usgsTimeSlice.ncdf\n07183b3611054d339a667ccc1b890507  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_22:45:00.15min.usgsTimeSlice.ncdf\n1e7667a78e3bc3305d47b295bee22834  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_23:00:00.15min.usgsTimeSlice.ncdf\n4afe61151629ed8bf83313a77961ee44  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_23:15:00.15min.usgsTimeSlice.ncdf\ndd550ff58a67d0406d0e932932df8248  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_23:30:00.15min.usgsTimeSlice.ncdf\nf893277a5406b1d270604d0c4c5df4a9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-08-31_23:45:00.15min.usgsTimeSlice.ncdf\n6db806535f807be6265141164bfeccd7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_00:00:00.15min.usgsTimeSlice.ncdf\n51b84eee7f1bb5112ad750154ff33e5d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_00:15:00.15min.usgsTimeSlice.ncdf\n050b684b406b1fd5f0be3148d154146f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_00:30:00.15min.usgsTimeSlice.ncdf\nc04f40bc0b5dd518a46d799aa97cf5a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_00:45:00.15min.usgsTimeSlice.ncdf\nc0a7499570fc03eac4c9d41e5ee0b8a1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_01:00:00.15min.usgsTimeSlice.ncdf\n614d1b14c6f907f046ea0c15f2061408  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_01:15:00.15min.usgsTimeSlice.ncdf\ne18b018317fa608af108c0e9e12ca032  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_01:30:00.15min.usgsTimeSlice.ncdf\n008ef79296ea7106a9b58a93675bd444  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_01:45:00.15min.usgsTimeSlice.ncdf\n232b6bf6f1639376b131f1165876ed80  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_02:00:00.15min.usgsTimeSlice.ncdf\n529c1d73177f0ae5cf252d1295a3a95f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_02:15:00.15min.usgsTimeSlice.ncdf\neaa443e01094010b1acc80b285379924  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_02:30:00.15min.usgsTimeSlice.ncdf\n822905c51e26dbb9fd404d4491857a58  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_02:45:00.15min.usgsTimeSlice.ncdf\n157ab6b38bbda14935c6b8cffb790576  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_03:00:00.15min.usgsTimeSlice.ncdf\n1839bca9459ab9caf83d81c26c15ea74  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_03:15:00.15min.usgsTimeSlice.ncdf\nbe145fb9ed062277050308d3ea4281a2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_03:30:00.15min.usgsTimeSlice.ncdf\nad97723e2a81015674e8a2906310ba55  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_03:45:00.15min.usgsTimeSlice.ncdf\n0554d9c4c8db76215ecd94a0a8caf007  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_04:00:00.15min.usgsTimeSlice.ncdf\na858b5be69086b81dc572efa70ed4435  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_04:15:00.15min.usgsTimeSlice.ncdf\ne2a8658c31088466dea778a8746b34e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_04:30:00.15min.usgsTimeSlice.ncdf\na1c84a133631a63417ad500c7015473e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_04:45:00.15min.usgsTimeSlice.ncdf\nd453cfb6837d4887c9b0904fb90713a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_05:00:00.15min.usgsTimeSlice.ncdf\nc3376966054d6ea90d4f65bb518ee754  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_05:15:00.15min.usgsTimeSlice.ncdf\n70ddb1bd697eeb2860c51091f38c27d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_05:30:00.15min.usgsTimeSlice.ncdf\n2dc97d71763f7f73dcd224d4fd2cff64  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_05:45:00.15min.usgsTimeSlice.ncdf\nd0df89f35431c309af905d38e45a2cc3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_06:00:00.15min.usgsTimeSlice.ncdf\ne42bf231e84281056e7015ccd5686a5b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_06:15:00.15min.usgsTimeSlice.ncdf\ne64c47545eccf2f545a6ef79569f41b2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_06:30:00.15min.usgsTimeSlice.ncdf\n7b1e0797945effc235e1b95dc05f5e56  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_06:45:00.15min.usgsTimeSlice.ncdf\nd755df7513fa1e0dc8e74b10d40db97e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_07:00:00.15min.usgsTimeSlice.ncdf\n170ea7f81b3543a1b22f61ae44f695c1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_07:15:00.15min.usgsTimeSlice.ncdf\nad1ac3f4a89550514c4f07a35a83ad2d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_07:30:00.15min.usgsTimeSlice.ncdf\n10b0ebdf59b4b25b0d5c8340705518f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_07:45:00.15min.usgsTimeSlice.ncdf\n4889a349f2735b3f04a5f65c608530c0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_08:00:00.15min.usgsTimeSlice.ncdf\n08b6ab5952a559faa8db0afd0bb2575f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_08:15:00.15min.usgsTimeSlice.ncdf\n113ba39ba1da0e45f8913c0e2f1a8623  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_08:30:00.15min.usgsTimeSlice.ncdf\n2cf2a253d5244a579a7988e3d52d94c5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_08:45:00.15min.usgsTimeSlice.ncdf\nff9eed4afe66f6d45a188fd328567ad0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_09:00:00.15min.usgsTimeSlice.ncdf\n89dca3ee4ca371cf893b6c442fd9da17  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_09:15:00.15min.usgsTimeSlice.ncdf\n07db38f3e850e80a152e83658bc76495  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_09:30:00.15min.usgsTimeSlice.ncdf\nd4c1bae82e3acef47ebaab9282d73731  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_09:45:00.15min.usgsTimeSlice.ncdf\n206c30b4079c34cc43c2e0e07d71125a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_10:00:00.15min.usgsTimeSlice.ncdf\n03fff40a2ec6c7eabfd6e70f1fb99732  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_10:15:00.15min.usgsTimeSlice.ncdf\n2ce9d30ef6266f82c46042e2c63ea3fc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_10:30:00.15min.usgsTimeSlice.ncdf\n34c81cae97a0010af2524143bdeb9bef  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_10:45:00.15min.usgsTimeSlice.ncdf\n20f2e26c0fe6506d2a2cbfa10453f670  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_11:00:00.15min.usgsTimeSlice.ncdf\n50de1a0c781d2d1755d167930535940c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_11:15:00.15min.usgsTimeSlice.ncdf\n32611cd4943fb72409d7b35442874a8b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_11:30:00.15min.usgsTimeSlice.ncdf\nc238a1161bc35aa3f422b00e7d9f4e2b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_11:45:00.15min.usgsTimeSlice.ncdf\n382cc95cf2882b17021f38905ff28fe8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_12:00:00.15min.usgsTimeSlice.ncdf\n2bd3bba7cdaa660cb036f13739d582c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_12:15:00.15min.usgsTimeSlice.ncdf\n402ab74d9b10a0785884f8d6bb8ea62d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_12:30:00.15min.usgsTimeSlice.ncdf\n8bfe93d9357380d34a924a89bcc360dc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_12:45:00.15min.usgsTimeSlice.ncdf\ne7ce22462d588a448a8047f27c2e37c8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_13:00:00.15min.usgsTimeSlice.ncdf\n483ee15a0622555448fb64a02f14aad4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_13:15:00.15min.usgsTimeSlice.ncdf\n7fb4fb845dfc67e114ce52c288921f1c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_13:30:00.15min.usgsTimeSlice.ncdf\ndacb0fecb01cbbdd2e770ae3f5ff5148  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_13:45:00.15min.usgsTimeSlice.ncdf\nb0f074a843ed6073edba51918e6db5f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_14:00:00.15min.usgsTimeSlice.ncdf\n86decd62084045d28410c2939084457c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_14:15:00.15min.usgsTimeSlice.ncdf\n441fbb92ff40ab3767b386cba36573d4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_14:30:00.15min.usgsTimeSlice.ncdf\n367eec2d4e74dde1e86bf5bb18b6658b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_14:45:00.15min.usgsTimeSlice.ncdf\n18a27af4b9528174c0b5403a0cd164de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_15:00:00.15min.usgsTimeSlice.ncdf\n10856408f3d66585d9fa0ec263075416  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_15:15:00.15min.usgsTimeSlice.ncdf\nca8a99633aaad1c7d2fd0fc25afd5f0b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_15:30:00.15min.usgsTimeSlice.ncdf\nb1bfc984bf399953204cce74898e738d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_15:45:00.15min.usgsTimeSlice.ncdf\nac0f0b48b70fef43076e218631ac88c0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_16:00:00.15min.usgsTimeSlice.ncdf\n1bc2e378057e0ab9b7db670e910ed873  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_16:15:00.15min.usgsTimeSlice.ncdf\na21cc6557e5623b545ec16ee3b8b60cc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_16:30:00.15min.usgsTimeSlice.ncdf\nba27235724f10d615c158c5a63bed298  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_16:45:00.15min.usgsTimeSlice.ncdf\na7277019ecf5f845201793cd943675b6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_17:00:00.15min.usgsTimeSlice.ncdf\n40b94fa9fe76bf99303e42bdb2e3b228  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_17:15:00.15min.usgsTimeSlice.ncdf\nd658d3c9d13ad69b4f5cdf1947ab06f3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_17:30:00.15min.usgsTimeSlice.ncdf\n2dc2ebe1dac7c990b7d0d3cab14b4c10  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_17:45:00.15min.usgsTimeSlice.ncdf\n121737b2bacaec686468a5990914f826  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_18:00:00.15min.usgsTimeSlice.ncdf\ne8256c307eb925be65ea64ee9ae859fa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_18:15:00.15min.usgsTimeSlice.ncdf\n3ec99135fe49dcab0ea28b04ce346494  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_18:30:00.15min.usgsTimeSlice.ncdf\n3744e2a4cd03cad07a225384527368f8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_18:45:00.15min.usgsTimeSlice.ncdf\n18e4c4e520459e9cd477ff4837749405  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_19:00:00.15min.usgsTimeSlice.ncdf\n138dd4beb338d94b79cd2726307e2660  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_19:15:00.15min.usgsTimeSlice.ncdf\n12a522fbc4fac5260ae72fc2fc9cc7d8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_19:30:00.15min.usgsTimeSlice.ncdf\n4dbc584ff2eb140455aa7e1e65b7989c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_19:45:00.15min.usgsTimeSlice.ncdf\n680101ba5ae1d1ed997e63c7c536e2bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_20:00:00.15min.usgsTimeSlice.ncdf\n436969960e9eb53be4d27969d79e0c43  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_20:15:00.15min.usgsTimeSlice.ncdf\nfcf54f8076da0b8c8c2f93f2f4387767  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_20:30:00.15min.usgsTimeSlice.ncdf\n47b6d9854fad95fe855fa2b9674c78b3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_20:45:00.15min.usgsTimeSlice.ncdf\nee045dc3f33aad6e200448e6d4d0763a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_21:00:00.15min.usgsTimeSlice.ncdf\n4526f890789689041909bc7ab81ea8bd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_21:15:00.15min.usgsTimeSlice.ncdf\n5df28fe3a58f1cff8bac737a4ba31a31  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_21:30:00.15min.usgsTimeSlice.ncdf\n5ba4aac71497b3e5b1aad6d539259e55  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_21:45:00.15min.usgsTimeSlice.ncdf\nd6370706a506d8f63b9798a14137aab0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_22:00:00.15min.usgsTimeSlice.ncdf\n3cd3f7e0e76542f258245ca3b7b2c993  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_22:15:00.15min.usgsTimeSlice.ncdf\n4ec096a9583da18e80b64a3fc8ebbe88  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_22:30:00.15min.usgsTimeSlice.ncdf\n3f87dd13eaf5e535b626ad56beae27e1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_22:45:00.15min.usgsTimeSlice.ncdf\n264e0ec6e66b858864ff048047933531  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_23:00:00.15min.usgsTimeSlice.ncdf\na8fb51a37ec989bfb6f06d75d981ce3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_23:15:00.15min.usgsTimeSlice.ncdf\n7772ed42ac03ec3f30f294ed72171f1e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_23:30:00.15min.usgsTimeSlice.ncdf\n3706ecb67c3f6960228f5c9a5dca55de  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-01_23:45:00.15min.usgsTimeSlice.ncdf\n96a07342539f43953a8c0dd4c719b85a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_00:00:00.15min.usgsTimeSlice.ncdf\na7e5cab10f807a15d28fb2ddb09258c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_00:15:00.15min.usgsTimeSlice.ncdf\n24779041d1c0d069de85fa32d3435e13  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_00:30:00.15min.usgsTimeSlice.ncdf\n79c2003b69cd236be880f8ac74bf67ac  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_00:45:00.15min.usgsTimeSlice.ncdf\n654fba12fed89eb4c2efbc46f3b05e39  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_01:00:00.15min.usgsTimeSlice.ncdf\ne319934dc3d8ce2cc67028866a491c76  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_01:15:00.15min.usgsTimeSlice.ncdf\n6b44122ecc1954affee30b9dc4665a50  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_01:30:00.15min.usgsTimeSlice.ncdf\n1f34f1f82596b817bd74dbcb9a5f328d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_01:45:00.15min.usgsTimeSlice.ncdf\nf0781c88b2dfc1cb85178cea7348f4a0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_02:00:00.15min.usgsTimeSlice.ncdf\n3cc3a28e5cd03ac12f40d62453de186c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_02:15:00.15min.usgsTimeSlice.ncdf\n6d4f5071ea0cc68b880f5005adac3dbf  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_02:30:00.15min.usgsTimeSlice.ncdf\n81001c505d442d86199d1dfbb5fe0648  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_02:45:00.15min.usgsTimeSlice.ncdf\n2185afda63a3b2d9fb91b15c45a7aa65  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_03:00:00.15min.usgsTimeSlice.ncdf\nb5ae6cc8970e9b41a40faafa7cb90f51  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_03:15:00.15min.usgsTimeSlice.ncdf\na8d3ed4f66c363e1d4c6737247d35ab2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_03:30:00.15min.usgsTimeSlice.ncdf\n6b5bb748dce767f25e121a2474222c64  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_03:45:00.15min.usgsTimeSlice.ncdf\n726b9a0641747c9859f0bb36e69a5df2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_04:00:00.15min.usgsTimeSlice.ncdf\nfdb40a4eca90cb78b257ebea56b6dcf5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_04:15:00.15min.usgsTimeSlice.ncdf\n958837e71469f93347c0d3df97234146  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_04:30:00.15min.usgsTimeSlice.ncdf\n0eb5b35c4504cb8bcffb0cb55efc77af  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_04:45:00.15min.usgsTimeSlice.ncdf\ncade16e394cabcce395c4e403f689844  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_05:00:00.15min.usgsTimeSlice.ncdf\nbf8e652053d720f2080666a51f97bbfa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_05:15:00.15min.usgsTimeSlice.ncdf\na59a1360c55b0da85ba63eb5f495cd59  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_05:30:00.15min.usgsTimeSlice.ncdf\n6ade0605a64bfcaa6edc64eb5d5b1066  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_05:45:00.15min.usgsTimeSlice.ncdf\n4db74f0e2f48788d427c7378ac8d48ba  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_06:00:00.15min.usgsTimeSlice.ncdf\n4313f16a3400ca4a828dc710f178149c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_06:15:00.15min.usgsTimeSlice.ncdf\n9e616140a70576e172e80840e5aae08c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_06:30:00.15min.usgsTimeSlice.ncdf\nc2a44d384fb9617a4a2b231b27f80719  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_06:45:00.15min.usgsTimeSlice.ncdf\ne29c7e9e8a909418eee967db4bcdec17  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_07:00:00.15min.usgsTimeSlice.ncdf\n12dc1c6955a0cd98af505305b5875c32  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_07:15:00.15min.usgsTimeSlice.ncdf\neef8af06da2df90908be9793f9c1bcea  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_07:30:00.15min.usgsTimeSlice.ncdf\n0752645a3c9fc3649d1102cf1aacd9a7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_07:45:00.15min.usgsTimeSlice.ncdf\nd2730820586f1b813b2f8220d89f0786  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_08:00:00.15min.usgsTimeSlice.ncdf\n1b53b5d89ec775570982c9e32ee2be7f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_08:15:00.15min.usgsTimeSlice.ncdf\n839107137f70e173a5aaa10de18d5b82  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_08:30:00.15min.usgsTimeSlice.ncdf\n3c14ab562c7eef4702cc7e7a852a2fd7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_08:45:00.15min.usgsTimeSlice.ncdf\n55f7b37a07fc0b1b21550a01b5d20242  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_09:00:00.15min.usgsTimeSlice.ncdf\n077495c63f8370263d0046298f52dbd1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_09:15:00.15min.usgsTimeSlice.ncdf\nf463bdc1c69f5f8db6a750f3e653fadc  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_09:30:00.15min.usgsTimeSlice.ncdf\n659b49a454521f0fd1bdeeaf2532dfe2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_09:45:00.15min.usgsTimeSlice.ncdf\n51317576a42f59601bef977536b60fa7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_10:00:00.15min.usgsTimeSlice.ncdf\n7376eb0c92d2581a136c1b06faeb60fd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_10:15:00.15min.usgsTimeSlice.ncdf\n3f5b2afea32dd74ad3e329826e0cea2e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_10:30:00.15min.usgsTimeSlice.ncdf\nd2699278481df15440e7b3cc3eb929b4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_10:45:00.15min.usgsTimeSlice.ncdf\n4eccd1b8d740d489ae34ca671999127e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_11:00:00.15min.usgsTimeSlice.ncdf\n7d9072581db6b78a59e2c95a4b73178c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_11:15:00.15min.usgsTimeSlice.ncdf\ncf5cbd01499fb9fda91a04a14c4e5f2b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_11:30:00.15min.usgsTimeSlice.ncdf\n2f6560075f3c4988e11c2c4c5182cb78  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_11:45:00.15min.usgsTimeSlice.ncdf\n16df9dbb4de208236366be99d7314cca  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_12:00:00.15min.usgsTimeSlice.ncdf\n78670a07f66729aa9733f26ae8d3bfc3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_12:15:00.15min.usgsTimeSlice.ncdf\nf0095e347f1672005f074d9b5a83a79c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_12:30:00.15min.usgsTimeSlice.ncdf\n131bb6de40e6938a241b3532ac8e373b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_12:45:00.15min.usgsTimeSlice.ncdf\nb1934c6716c80ee55bfe9fde918cb915  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_13:00:00.15min.usgsTimeSlice.ncdf\n2ccbe86d1e4d45b56c26acf09f287184  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_13:15:00.15min.usgsTimeSlice.ncdf\n1b75f481103e13cc5ddb7d973f9fd8b6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_13:30:00.15min.usgsTimeSlice.ncdf\n758ca3e0f777ffcbdfa20e62c5b5b329  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_13:45:00.15min.usgsTimeSlice.ncdf\n129537dbabc1ad40d353d7d48bcb0f7c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_14:00:00.15min.usgsTimeSlice.ncdf\n8fc9859835c5a142c6069d52d388ed79  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_14:15:00.15min.usgsTimeSlice.ncdf\n7b95e4c244cf36d5609536c85e866386  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_14:30:00.15min.usgsTimeSlice.ncdf\n21231391fe687c607f1376b59c3fa517  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_14:45:00.15min.usgsTimeSlice.ncdf\n1f287e5436b60ac9e540806f2282eceb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_15:00:00.15min.usgsTimeSlice.ncdf\n724705634a1c5c8bd01c8c0c94f7f73d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_15:15:00.15min.usgsTimeSlice.ncdf\nc4e30f9db48ff03679722fba93c4d937  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_15:30:00.15min.usgsTimeSlice.ncdf\n2f4ba40b5cac1d65c04d9cf8e8edfe52  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_15:45:00.15min.usgsTimeSlice.ncdf\n7a3c7e13824ca59be193a07c3f2f0e63  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_16:00:00.15min.usgsTimeSlice.ncdf\nedf44ea77eeb0d14b07538d3dc03c35d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_16:15:00.15min.usgsTimeSlice.ncdf\nb8a36b8ce91e04c55f8b55628866c8b9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_16:30:00.15min.usgsTimeSlice.ncdf\nbe1f0be610d366518cc4c570167a2ce4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_16:45:00.15min.usgsTimeSlice.ncdf\ndee9cf6bda982f6dafc17b8da511cb13  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_17:00:00.15min.usgsTimeSlice.ncdf\n31b9aed199c354ac53f747769be80422  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_17:15:00.15min.usgsTimeSlice.ncdf\nca631d32bf809b093f7a5ff8b2b210d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_17:30:00.15min.usgsTimeSlice.ncdf\ne9905eda4195b8822dcf62ee0569d41f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_17:45:00.15min.usgsTimeSlice.ncdf\n97939803bb5be585f7222d4b1fd57e47  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_18:00:00.15min.usgsTimeSlice.ncdf\n67a21dab4de64e9db0a80a276ad03a8c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_18:15:00.15min.usgsTimeSlice.ncdf\na0db349f56e427fd1566a5b984027d90  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_18:30:00.15min.usgsTimeSlice.ncdf\ne6c31b4e473ef888798d1d1d41e7393a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_18:45:00.15min.usgsTimeSlice.ncdf\n413d46b0b0a4df1c1f7ac8d14befde54  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_19:00:00.15min.usgsTimeSlice.ncdf\n973f0fe9edbe3e5ff08ef5d676dffe6b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_19:15:00.15min.usgsTimeSlice.ncdf\n29ff2da2406d54f7bfa288f42e8303e0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_19:30:00.15min.usgsTimeSlice.ncdf\nec1c07934ef4482d33908f098b5c274d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_19:45:00.15min.usgsTimeSlice.ncdf\n447e3c98462265079d20f258c61fa9f8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_20:00:00.15min.usgsTimeSlice.ncdf\n83b61dc5973e5ad1014717d0da9f7b3f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_20:15:00.15min.usgsTimeSlice.ncdf\n64bd769aaac01423c70235f3153c368b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_20:30:00.15min.usgsTimeSlice.ncdf\n847e2a2026a4e711424c2995185b1398  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_20:45:00.15min.usgsTimeSlice.ncdf\n1a2669942f186ae1273cd61bccea31f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_21:00:00.15min.usgsTimeSlice.ncdf\n095d529eedfec198f2fb0458de2cf4eb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_21:15:00.15min.usgsTimeSlice.ncdf\n31d32b17721c883c3fd6eb36ea84f9be  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_21:30:00.15min.usgsTimeSlice.ncdf\ncc54a9b819388215ac7579f00f38bb3f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_21:45:00.15min.usgsTimeSlice.ncdf\nea91af6821991648521d3bc6a4ecea71  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_22:00:00.15min.usgsTimeSlice.ncdf\n4f5af10738568a149d32b331078586cd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_22:15:00.15min.usgsTimeSlice.ncdf\n6e3799ed3e85d63b9cfe011f711a044f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_22:30:00.15min.usgsTimeSlice.ncdf\nc2328c338af7f4ea2d32bd6e992dacbd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_22:45:00.15min.usgsTimeSlice.ncdf\nc19bdcea7f33f68c466b9fcc74451f05  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_23:00:00.15min.usgsTimeSlice.ncdf\nd4074e7417a074ac1240fe68f92689d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_23:15:00.15min.usgsTimeSlice.ncdf\n65cb6fa10b4e8ded84f5bf86250159a6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_23:30:00.15min.usgsTimeSlice.ncdf\ndde8235736adc1313fe3feed3851e1f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-02_23:45:00.15min.usgsTimeSlice.ncdf\ndc44e8838cab0e45a4de8c2f21228a3b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_00:00:00.15min.usgsTimeSlice.ncdf\ndfa88b9376261865898de285684c100c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_00:15:00.15min.usgsTimeSlice.ncdf\n2017f8142b7548c32354e90ceba6624c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_00:30:00.15min.usgsTimeSlice.ncdf\n59e537f84bec14de1932a66e7f098977  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_00:45:00.15min.usgsTimeSlice.ncdf\n97221f9d392c09d1a4f4b15c800ee498  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_01:00:00.15min.usgsTimeSlice.ncdf\nbe10207562470756ec874de82d0c5f00  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_01:15:00.15min.usgsTimeSlice.ncdf\neacb4dcdcbad44270ec4fa26779a0572  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_01:30:00.15min.usgsTimeSlice.ncdf\na5bb1bfbcf7662439029a8121e9f1a06  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_01:45:00.15min.usgsTimeSlice.ncdf\n623ea1954dc4b6eae66722cc799e04d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_02:00:00.15min.usgsTimeSlice.ncdf\n984187932c903bd4a3e7eaa7ba7f5235  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_02:15:00.15min.usgsTimeSlice.ncdf\ne97ff3250b5ee541145f7ef0992b3596  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_02:30:00.15min.usgsTimeSlice.ncdf\nac77ef2d9ff167586fb652bc2f6ff004  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_02:45:00.15min.usgsTimeSlice.ncdf\nb83771b656d050fc1b39ab70ce19ee42  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_03:00:00.15min.usgsTimeSlice.ncdf\nfb9ff4c3b15d5898794f035a9a7bb3d3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_03:15:00.15min.usgsTimeSlice.ncdf\n0fd64bc23326b5b00a6280ba742a7ab0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_03:30:00.15min.usgsTimeSlice.ncdf\nfd328a8f46cd592cb6e73d1159b223c4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_03:45:00.15min.usgsTimeSlice.ncdf\nb9a4a252decb657b2d99cc02a97f5bf7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_04:00:00.15min.usgsTimeSlice.ncdf\nee5a3c630538b82f4e4e24f0d68ca469  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_04:15:00.15min.usgsTimeSlice.ncdf\n8fd1d6af74c4410a766ddfc8c4e170ec  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_04:30:00.15min.usgsTimeSlice.ncdf\n27c3c14787b1403a610370aaa43b7e5f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_04:45:00.15min.usgsTimeSlice.ncdf\n6169c55f51d91634ef92a6b616e46739  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_05:00:00.15min.usgsTimeSlice.ncdf\n70a8ab71783ad7f9f3ec40aaeffc5a0d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_05:15:00.15min.usgsTimeSlice.ncdf\n3286c0d6f936bb9f5e631fa9a3f68995  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_05:30:00.15min.usgsTimeSlice.ncdf\n4cc525e3ff38c9079601039163a01cb7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_05:45:00.15min.usgsTimeSlice.ncdf\n4faf76d466409fda19ca90ea56e0b2b2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_06:00:00.15min.usgsTimeSlice.ncdf\ne0d4bbed0fa318ae8ce8a7f0f31aff11  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_06:15:00.15min.usgsTimeSlice.ncdf\nf4e7dad0ff32e91c56262c018aa57122  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_06:30:00.15min.usgsTimeSlice.ncdf\n09fecb739ee1905688bbdd811489d946  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_06:45:00.15min.usgsTimeSlice.ncdf\n8d9c8bde51467e4b083124ab53c991a1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_07:00:00.15min.usgsTimeSlice.ncdf\n1a19a65bbe0c66abc56a02be11edf23e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_07:15:00.15min.usgsTimeSlice.ncdf\n08620044e39a19e7d6331e1b1e890750  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_07:30:00.15min.usgsTimeSlice.ncdf\n5e451c010c1a87574f14863c32db421a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_07:45:00.15min.usgsTimeSlice.ncdf\n778612d94927329ef6fba8589b318c89  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_08:00:00.15min.usgsTimeSlice.ncdf\n0e24940dffac5f682d9a9e620075aa5f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_08:15:00.15min.usgsTimeSlice.ncdf\na48f36ee6fe0d85a91c13526ccdea9f9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_08:30:00.15min.usgsTimeSlice.ncdf\nb6eefdd6ccdc3dd215872ca5f72e60b1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_08:45:00.15min.usgsTimeSlice.ncdf\nec0f909df45b96bb0137d872b936e79e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_09:00:00.15min.usgsTimeSlice.ncdf\n3dd682b61640a66ea72bbceb1f9ba99b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_09:15:00.15min.usgsTimeSlice.ncdf\n2ab9a8abd852754096f627dcfed94668  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_09:30:00.15min.usgsTimeSlice.ncdf\n7293b8f38c3349d88d378e5a7d25be89  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_09:45:00.15min.usgsTimeSlice.ncdf\n230920721a611794cf77455a42524486  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_10:00:00.15min.usgsTimeSlice.ncdf\nf2d4affaa944a5ff0be0de50655771d9  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_10:15:00.15min.usgsTimeSlice.ncdf\ne87084619ba19e2d224af34bc3237ecd  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_10:30:00.15min.usgsTimeSlice.ncdf\n193b22d8a6d9a56ac6cfa39a3fd411fa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_10:45:00.15min.usgsTimeSlice.ncdf\nb57d017086aca0cc3abf739c0355f0f8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_11:00:00.15min.usgsTimeSlice.ncdf\na79e08ccd0d1a9681962105a7436dc1c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_11:15:00.15min.usgsTimeSlice.ncdf\n58e93f309dde41a1babea28a46339a44  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_11:30:00.15min.usgsTimeSlice.ncdf\n3bd17c8545680af7f0fa8961ff41a428  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_11:45:00.15min.usgsTimeSlice.ncdf\nb63846e6ab178acdbd8ece77a905bc82  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_12:00:00.15min.usgsTimeSlice.ncdf\n27ac54b22731c9669524c38f7b406cc6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_12:15:00.15min.usgsTimeSlice.ncdf\nb9af2afda37e6a208941eb72e2e3f02b  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_12:30:00.15min.usgsTimeSlice.ncdf\ndd1d96d81a2fca4f66af5af6cea89a6e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_12:45:00.15min.usgsTimeSlice.ncdf\n750d278338e68250cd10a2557d18abf2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_13:00:00.15min.usgsTimeSlice.ncdf\ned3676db0a3cc61cf7facbb15a5db25d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_13:15:00.15min.usgsTimeSlice.ncdf\nf434b55de7644be29592c891680abc38  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_13:30:00.15min.usgsTimeSlice.ncdf\nec78c19d28b06ca56142c2b2a043a537  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_13:45:00.15min.usgsTimeSlice.ncdf\n4583c87887c6c964b30901bea55b763f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_14:00:00.15min.usgsTimeSlice.ncdf\ne816e1cef03c501f10c18afd83d3ed8d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_14:15:00.15min.usgsTimeSlice.ncdf\n05d1b183a4bf09c8bbc7360885aa2146  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_14:30:00.15min.usgsTimeSlice.ncdf\n20c9f478cfddf79bb12fa9d5729fc78a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_14:45:00.15min.usgsTimeSlice.ncdf\n9a6e55dfc983c527fcba9df0bc3619d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_15:00:00.15min.usgsTimeSlice.ncdf\n7449e201d19a2589d299a8f9332e5eb7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_15:15:00.15min.usgsTimeSlice.ncdf\nec5834b17b6f018d626791a301cced8a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_15:30:00.15min.usgsTimeSlice.ncdf\ndf7e0f4ca52b126291b6699fb25ceb01  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_15:45:00.15min.usgsTimeSlice.ncdf\n2a5eb39eb55e555603c940a1c5d0d87c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_16:00:00.15min.usgsTimeSlice.ncdf\n4c0a11cc5757b07a28abb3e1205f0734  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_16:15:00.15min.usgsTimeSlice.ncdf\n36232b2cb3c657c78a54335b5bf09705  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_16:30:00.15min.usgsTimeSlice.ncdf\n048c83f531f8e2e93c010270f6df60f5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_16:45:00.15min.usgsTimeSlice.ncdf\n8c78f21c2ae68d884bd12331b00d4bb1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_17:00:00.15min.usgsTimeSlice.ncdf\n9492a97a747b70a0c75c792038560012  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_17:15:00.15min.usgsTimeSlice.ncdf\nbd68585d487627df5a8b67931343caba  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_17:30:00.15min.usgsTimeSlice.ncdf\nd154bf5792f5a84d64a5573f19349156  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_17:45:00.15min.usgsTimeSlice.ncdf\na97666715ed0a091548ef5670156d1a8  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_18:00:00.15min.usgsTimeSlice.ncdf\nc7f97bebcf927da8229ab0ad1dd34c52  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_18:15:00.15min.usgsTimeSlice.ncdf\n5726269c46a6eb5f7c75d5b9b1dea3f2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_18:30:00.15min.usgsTimeSlice.ncdf\ncff1cb4bf193f883a5b94f10049fcbed  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_18:45:00.15min.usgsTimeSlice.ncdf\nddb3e78000ccd59fbb6dc7dda8357eed  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_19:00:00.15min.usgsTimeSlice.ncdf\nb05776c567a41229415feb06ccb608c7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_19:15:00.15min.usgsTimeSlice.ncdf\nd1705d8eebf0ac7ccb86e1cb9ec75927  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_19:30:00.15min.usgsTimeSlice.ncdf\n4056b56d16820db4d9994ac98cc4467c  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_19:45:00.15min.usgsTimeSlice.ncdf\nb03aa9f9b6e16cdd8caa55fae597e5c3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_20:00:00.15min.usgsTimeSlice.ncdf\ndf3363ee819e0a67d4fe09291e844795  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_20:15:00.15min.usgsTimeSlice.ncdf\n8b77f0d3085ea67534e31bfb42846849  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_20:30:00.15min.usgsTimeSlice.ncdf\n7ccee0d0335aa05666e9412d74ccdaa4  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_20:45:00.15min.usgsTimeSlice.ncdf\na6c568ef67a2e24622ff392d42377240  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_21:00:00.15min.usgsTimeSlice.ncdf\nd847bdc30559d60b8098c169f69e51f6  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_21:15:00.15min.usgsTimeSlice.ncdf\n3d40d10d665d891e9f7736aefe0c3d0a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_21:30:00.15min.usgsTimeSlice.ncdf\n1135ca9fb1e97478dfb29485ed2845ea  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_21:45:00.15min.usgsTimeSlice.ncdf\n1787490bfb0ec46aacc7cc1a835ef8f0  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_22:00:00.15min.usgsTimeSlice.ncdf\n3a752c16ba354049dae762da57ef5c43  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_22:15:00.15min.usgsTimeSlice.ncdf\nb33691c43b7c85da524dedd288fe27ba  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_22:30:00.15min.usgsTimeSlice.ncdf\n69cf74c008b2cb93d0ad8a9e2086d3cb  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_22:45:00.15min.usgsTimeSlice.ncdf\n57b7b9983b1c8baf02db8ff45e25cf70  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_23:00:00.15min.usgsTimeSlice.ncdf\n0cb6e5f0a85d12c52f4d0c023f583d16  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_23:15:00.15min.usgsTimeSlice.ncdf\n596f770b97dd7485f2942df44a67712d  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_23:30:00.15min.usgsTimeSlice.ncdf\na33a0bf90265a353b35ee1551ccf9aa2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-03_23:45:00.15min.usgsTimeSlice.ncdf\n75f1519633266da6c1f78bc99feff06f  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_00:00:00.15min.usgsTimeSlice.ncdf\n1ecdfc2d0e9a70a4cd68a246d8553286  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_00:15:00.15min.usgsTimeSlice.ncdf\n990a3546d33969011d4093b1b2e02ce7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_00:30:00.15min.usgsTimeSlice.ncdf\ncd6867f3632c7498c942533aeb3890d1  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_00:45:00.15min.usgsTimeSlice.ncdf\n223897c03d0904e77f819444e9fcf530  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_01:00:00.15min.usgsTimeSlice.ncdf\n0222cad4c5e2f0911087a55e8614dbb2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_01:15:00.15min.usgsTimeSlice.ncdf\n23c62d83795bd511af9bacfe95009386  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_01:30:00.15min.usgsTimeSlice.ncdf\n609bbe93974c8ef19dd1924edcd4c8b3  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_01:45:00.15min.usgsTimeSlice.ncdf\nd5dfeafc8bb374a851a69f57c03942f7  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_02:00:00.15min.usgsTimeSlice.ncdf\n20e1cd41a76132939fc334ea919a5166  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_02:15:00.15min.usgsTimeSlice.ncdf\nacab9d4bc19e7dcb8e69644e95433553  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_02:30:00.15min.usgsTimeSlice.ncdf\n652a488c328d08aaa51d5844561642aa  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_02:45:00.15min.usgsTimeSlice.ncdf\n705d29489503dfe4030fc2519c0fef76  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_03:00:00.15min.usgsTimeSlice.ncdf\nad8417cea332ed79c880a859ef020e3a  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_03:15:00.15min.usgsTimeSlice.ncdf\ne67d74372e4e2a812404845e3d6e3d4e  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_03:30:00.15min.usgsTimeSlice.ncdf\n5ad0b501e40696e2fd162fb485fcd170  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_03:45:00.15min.usgsTimeSlice.ncdf\n5ab62a12b5f7bae5f664e1334e1633d2  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_04:00:00.15min.usgsTimeSlice.ncdf\nf8bb1f2b7a44b3c985b21752fb9ec603  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_04:15:00.15min.usgsTimeSlice.ncdf\n38926d9369468f50f61a0ff2fe596de5  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_04:30:00.15min.usgsTimeSlice.ncdf\n69d30ac1c418d55f08b0268788d54c58  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_04:45:00.15min.usgsTimeSlice.ncdf\n0652802caaa9ce45272fd9f8082be224  /glade/p/cisl/nwc/model_testing_domains/croton_NY/NWM/nudgingTimeSliceObs/2011-09-04_05:00:00.15min.usgsTimeSlice.ncdf\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/hydro.namelist",
    "content": "&hydro_nlist\n    aggfactrt = 1\n    channel_option = 2\n    chanobs_domain = 1\n    chanrtswcrt = 1\n    chrtout_domain = 1\n    chrtout_grid = 1\n    compound_channel = .true.\n    dtrt_ch = 300\n    dtrt_ter = 10\n    dxrt = 1000\n    frxst_pts_out = 0\n    geo_finegrid_flnm = './NWM/DOMAIN_LR/Fulldom_hires.nc'\n    geo_static_flnm = './NWM/DOMAIN_LR/geo_em.d01.nc'\n    gw_restart = 1\n    gwbaseswcrt = 4\n    gwbuckparm_file = './NWM/DOMAIN_LR/GWBUCKPARM.nc'\n    hydrotbl_f = './NWM/DOMAIN_LR/hydro2dtbl.nc'\n    igrid = 1\n    io_config_outputs = 0\n    io_form_outputs = 4\n    land_spatial_meta_flnm = './NWM/DOMAIN_LR/GEOGRID_LDASOUT_Spatial_Metadata.nc'\n    lsmout_domain = 1\n    nsoil = 4\n    order_to_write = 1\n    out_dt = 60\n    outlake = 1\n    output_channelbucket_influx = 0\n    output_gw = 1\n    ovrtswcrt = 0\n    reservoir_persistence_usgs = .false.\n    restart_file = './NWM/RESTART_LR/HYDRO_RST.2011-08-26_00:00_DOMAIN1'\n    route_lake_f = './NWM/DOMAIN_LR/LAKEPARM.nc'\n    route_link_f = './NWM/DOMAIN_LR/Route_Link.nc'\n    rst_bi_in = 0\n    rst_bi_out = 0\n    rst_dt = 1440\n    rst_typ = 0\n    rstrt_swc = 0\n    rt_option = 1\n    rtout_domain = 0\n    split_output_count = 1\n    subrtswcrt = 0\n    sys_cpl = 1\n    t0outputflag = 1\n    udmap_file = './NWM/DOMAIN_LR/spatialweights.nc'\n    udmp_opt = 1\n    zsoil8 = -0.1, -0.4, -1.0, -2.0\n/\n\n&nudging_nlist\n    biaswindowbeforet0 = .false.\n    invdisttimeweightbias = .true.\n    maxagepairsbiaspersist = 24\n    minnumpairsbiaspersist = 1\n    nlastobs = 480\n    noconstinterfbias = .false.\n    nudginglastobsfile = './NWM/RESTART/nudgingLastObs.2011-08-26_00:00:00.nc'\n    nudgingparamfile = './NWM/DOMAIN/nudgingParams.nc'\n    persistbias = .false.\n    readtimesliceparallel = .true.\n    temporalpersistence = .true.\n    timeslicepath = './NWM/nudgingTimeSliceObs/'\n/\n"
  },
  {
    "path": "tests/config_file_meta/croton_NY/nwm_long_range/namelist.hrldas",
    "content": "&noahlsm_offline\n    btr_option = 1\n    canopy_stomatal_resistance_option = 1\n    dynamic_veg_option = 4\n    forcing_timestep = 3600\n    frozen_soil_option = 1\n    glacier_option = 2\n    hrldas_setup_file = './NWM/DOMAIN_LR/wrfinput_d01.nc'\n    indir = './FORCING'\n    khour = 144\n    noah_timestep = 3600\n    nsoil = 4\n    outdir = './'\n    output_timestep = 3600\n    pcp_partition_option = 1\n    radiative_transfer_option = 3\n    restart_filename_requested = './NWM/RESTART_LR/RESTART.2011082600_DOMAIN1'\n    restart_frequency_hours = 24\n    rst_bi_in = 0\n    rst_bi_out = 0\n    runoff_option = 3\n    snow_albedo_option = 1\n    soil_thick_input = 0.1, 0.3, 0.6, 1.0\n    spatial_filename = './NWM/DOMAIN_LR/soil_properties.nc'\n    split_output_count = 1\n    start_day = 26\n    start_hour = 0\n    start_min = 0\n    start_month = 8\n    start_year = 2011\n    supercooled_water_option = 1\n    surface_drag_option = 1\n    surface_resistance_option = 4\n    tbot_option = 2\n    temp_time_scheme_option = 3\n    zlvl = 10.0\n/\n\n&wrf_hydro_offline\n    forc_typ = 1\n/\n"
  },
  {
    "path": "tests/config_file_meta/get_config_file_meta_data.py",
    "content": "from boltons import iterutils\nimport os\nimport pathlib\nimport subprocess\nfrom wrfhydropy import JSONNamelist\n\n# Example: python get_config_file_meta_data\n#\n# 1) Run script file in-place, in this directory, as above.\n# 2) Typically, this will be run on Derecho since that's where CONUS domain\n#    files will live.\n# 3) Configure the list of domains paths and configs below.\n# 4) The dirs in this directory must be removed to be refreshed.\n# 5) This script skips non-existent files and ignores timeslices.\n\ndomain_paths = [\n    \"/glade/p/cisl/nwc/model_testing_domains/croton_NY\"\n]\n\nconfigs = [\n    'nwm_ana',\n    'nwm_hi_ana',\n    'nwm_long_range'\n]\n\n# -----------------------------------\ndomain_paths = [pathlib.PosixPath(pp) for pp in domain_paths]\nthis_path = pathlib.PosixPath(os.getcwd())\ncode_path = this_path.parent.parent / 'src/'\n\ndef get_nlst_file_meta(\n    namelist: dict,\n    dom_dir: str\n):\n\n    def visit_file(path, key, value):\n\n        # Only treat strings\n        if type(value) is not str:\n            return False\n\n        # Convert to pathlib object, kee\n        the_file_rel = pathlib.PosixPath(value)\n        the_file_abs = dom_dir / the_file_rel\n\n        # Dirs: get the md5sum of every file inside\n        if the_file_abs.is_dir():\n            if the_file_abs.name not in ['FORCING','nudgingTimeSliceObs']:\n                return False\n\n            print('            ' + str(the_file_abs))\n            if the_file_abs.exists() is False:\n                raise ValueError(\"The file does not exist: \" + str(the_file_abs))\n\n            meta_path_rel = the_file_rel\n            the_cmd = 'meta_path=' + str(meta_path_rel) + \".md5\"\n            the_cmd += ' && data_path=' + str(the_file_abs)\n            the_cmd += ' && md5sum $data_path/* > $meta_path'\n            proc = subprocess.run(\n                the_cmd,\n                cwd=config_dir,\n                shell=True,\n                executable='/bin/bash'\n            )\n            return True\n\n        # Regular files...\n        print('            ' + str(the_file_abs))\n\n        if the_file_abs.exists() is False:\n            raise ValueError(\"The file does not exist: \" + str(the_file_abs))\n\n        # The sub process command is executed in the root of the meta path,\n        # use the relative data path/\n        meta_path_rel = the_file_rel\n        if meta_path_rel.suffix == '.nc':\n            meta_path_base = meta_path_rel.with_suffix(\"\")\n        else:\n            meta_path_base = meta_path_rel\n        the_cmd = 'meta_path=' + str(meta_path_rel)\n        the_cmd += ' && meta_path_md5=' + str(meta_path_base) + '.md5'\n        the_cmd += ' && meta_path_cdl=' + str(meta_path_base) + '.cdl'\n        the_cmd += ' && data_path=' + str(the_file_abs)\n        the_cmd += ' && mkdir -p $(dirname $meta_path)'\n        the_cmd += ' && md5sum $data_path > $meta_path_md5'\n        the_cmd += ' && ncdump -h $data_path > $meta_path_cdl'\n        proc = subprocess.run(\n            the_cmd,\n            cwd=config_dir,\n            shell=True,\n            executable='/bin/bash'\n        )\n\n        return True\n\n    _ = iterutils.remap(namelist, visit=visit_file)\n\n\nfor dd in domain_paths:\n\n    print('')\n    print('Domain: ' + str(dd))\n\n    domain_tag = dd.name\n\n    for cc in configs:\n\n        # Make a meta data output dir for each configuration.\n        config_dir = (this_path / domain_tag) / cc\n\n        # Create the namelists\n        domain_nlsts = ['hydro_namelists.json', 'hrldas_namelists.json']\n        code_nlsts = ['hydro_namelist_patches.json', 'hrldas_namelist_patches.json']\n        file_names = ['hydro.namelist', 'namelist.hrldas']\n\n        for code, dom, ff in zip(domain_nlsts, code_nlsts, file_names):\n\n            domain_namelists = JSONNamelist(dd / dom)\n\n            # If the configuartion is not found in the domain, skip it silently\n            try:\n                domain_config = domain_namelists.get_config(cc)\n            except KeyError:\n                continue\n\n            if not config_dir.exists() and ff == file_names[0]:\n                config_dir.mkdir(parents=True, exist_ok=False)\n                print('')\n                print('    Config: ' + str(cc))\n\n            print('        Namelist: ' + str(ff))\n\n            repo_namelists = JSONNamelist(code_path / code)\n            repo_config = repo_namelists.get_config(cc)\n            patched_namelist = repo_config.patch(domain_config)\n\n            # Write them out for completeness.\n            patched_namelist.write(str(config_dir / ff))\n\n            # This function does the work.\n            get_nlst_file_meta(patched_namelist, dd)\n"
  },
  {
    "path": "tests/conftest.py",
    "content": "import pathlib\nimport shutil\nimport pytest\nimport wrfhydropy\nimport json\n\n\ndef pytest_addoption(parser):\n\n    # Required args:\n\n    parser.addoption(\n        '--domain_dir',\n        required=True,\n        action='store',\n        help='domain directory'\n    )\n\n    parser.addoption(\n        '--output_dir',\n        required=True,\n        action='store',\n        help='test output directory'\n    )\n\n    parser.addoption(\n        '--candidate_dir',\n        required=True,\n        action='store',\n        help='candidate model directory'\n    )\n\n    parser.addoption(\n        '--reference_dir',\n        required=True,\n        action='store',\n        help='reference model directory'\n    )\n\n    parser.addoption(\n        \"--config\",\n        required=True,\n        action='store',\n        help=(\"The configuration to test, \"\n              \"must be one listed in src/hydro_namelist.json keys.\")\n    )\n\n    # Optional args\n\n    parser.addoption(\n        '--compiler',\n        default='gfort',\n        required=False,\n        action='store',\n        help='compiler, options are ifort or gfort'\n    )\n\n    parser.addoption(\n        \"--option_suite\",\n        required=False,\n        action='store',\n        help=(\"An option suite to test on top of the specified configuration,\"\n              \"must be one listed in hydro_option_suites.json\")\n    )\n\n    parser.addoption(\n        '--ncores',\n        default='2',\n        required=False,\n        action='store',\n        help='Number of cores to use for testing'\n    )\n\n    parser.addoption(\n        '--scheduler',\n        action='store_true',\n        help='Use PBS scheduler on Derecho'\n    )\n\n    parser.addoption(\n        '--nnodes',\n        default='2',\n        required=False,\n        help='Number of nodes to use for testing if running on scheduler'\n    )\n\n    parser.addoption(\n        '--account',\n        default='NRAL0017',\n        required=False,\n        action='store',\n        help='Account number to use if using a scheduler.'\n    )\n\n    parser.addoption(\n        '--walltime',\n        default='02:00:00',\n        required=False,\n        action='store',\n        help='Wall clock time for each test run in hh:mm:ss format'\n    )\n\n    parser.addoption(\n        '--queue',\n        default='regular',\n        required=False,\n        action='store',\n        help='Queue to use if running on NCAR Derecho, options are regular, '\n        'premium, or shared'\n    )\n\n    parser.addoption(\n        '--exe_cmd',\n        default='mpirun -np {0} ./wrf_hydro',\n        required=False,\n        action='store',\n        help='The MPI-dependent model execution command. Default is best guess. '\n        'The first/zeroth variable is set to the total number of cores. The '\n        'wrf_hydro_py convention is that the exe is always named wrf_hydro.'\n    )\n\n    parser.addoption(\n        '--use_existing_test_dir',\n        default=False,\n        required=False,\n        action='store_true',\n        help='Use existing compiles and runs, only perform output comparisons.'\n    )\n\n    parser.addoption(\n        '--xrcmp_n_cores',\n        default=0,\n        required=False,\n        help='Use xrcmp if > 0, and how many cores if so?'\n    )\n\n\ndef _make_sim(\n    domain_dir,\n    compiler,\n    source_dir,\n    configuration,\n    option_suite,\n    ncores,\n    nnodes,\n    scheduler,\n    account,\n    walltime,\n    queue\n):\n\n    model = wrfhydropy.Model(\n        compiler=compiler,\n        source_dir=source_dir,\n        model_config=configuration\n    )\n\n    domain = wrfhydropy.Domain(\n        domain_top_dir=domain_dir,\n        domain_config=configuration\n    )\n\n    sim = wrfhydropy.Simulation()\n    sim.add(model)\n    sim.add(domain)\n\n    # Update base namelists with option suite if specified\n    if option_suite is not None:\n        pass\n\n    if scheduler:\n        sim.add(\n            wrfhydropy.schedulers.PBSDerecho(\n                account=account,\n                nproc=int(ncores),\n                nnodes=int(nnodes),\n                walltime=walltime,\n                queue=queue\n            )\n        )\n\n    return sim\n\n\n@pytest.fixture(scope=\"session\")\ndef exe_cmd(request):\n    return request.config.getoption(\"--exe_cmd\")\n\n\n@pytest.fixture(scope=\"session\")\ndef candidate_sim(request):\n\n    domain_dir = request.config.getoption(\"--domain_dir\")\n    compiler = request.config.getoption(\"--compiler\")\n    candidate_dir = request.config.getoption(\"--candidate_dir\")\n    configuration = request.config.getoption(\"--config\")\n    option_suite = request.config.getoption(\"--option_suite\")\n    ncores = request.config.getoption(\"--ncores\")\n    nnodes = request.config.getoption(\"--nnodes\")\n    scheduler = request.config.getoption(\"--scheduler\")\n    account = request.config.getoption(\"--account\")\n    walltime = request.config.getoption(\"--walltime\")\n    queue = request.config.getoption(\"--queue\")\n\n    candidate_sim = _make_sim(\n        domain_dir=domain_dir,\n        compiler=compiler,\n        source_dir=candidate_dir,\n        configuration=configuration,\n        option_suite=option_suite,\n        ncores=ncores,\n        nnodes=nnodes,\n        scheduler=scheduler,\n        account=account,\n        walltime=walltime,\n        queue=queue\n    )\n\n    return candidate_sim\n\n\n# Since we want to leverage the NWM compiles (both candidate and reference, ptoentially),\n# we create additional simulation fixtures where we hard-code the alternate configurations,\n# those are \"channel-only\" and \"nwm_output_ana\", currently.\n@pytest.fixture(scope=\"session\")\ndef candidate_channel_only_sim(request):\n\n    domain_dir = request.config.getoption(\"--domain_dir\")\n    compiler = request.config.getoption(\"--compiler\")\n    candidate_dir = request.config.getoption(\"--candidate_dir\")\n    option_suite = request.config.getoption(\"--option_suite\")\n    ncores = request.config.getoption(\"--ncores\")\n    nnodes = request.config.getoption(\"--nnodes\")\n    scheduler = request.config.getoption(\"--scheduler\")\n    account = request.config.getoption(\"--account\")\n    walltime = request.config.getoption(\"--walltime\")\n    queue = request.config.getoption(\"--queue\")\n\n    configuration = \"nwm_channel-only\"\n\n    candidate_channel_only_sim = _make_sim(\n        domain_dir=domain_dir,\n        compiler=compiler,\n        source_dir=candidate_dir,\n        configuration=configuration,\n        option_suite=option_suite,\n        ncores=ncores,\n        nnodes=nnodes,\n        scheduler=scheduler,\n        account=account,\n        walltime=walltime,\n        queue=queue\n    )\n\n    return candidate_channel_only_sim\n\n\n@pytest.fixture(scope=\"session\")\ndef candidate_nwm_output_sim(request):\n\n    domain_dir = request.config.getoption(\"--domain_dir\")\n    compiler = request.config.getoption(\"--compiler\")\n    candidate_dir = request.config.getoption(\"--candidate_dir\")\n    option_suite = request.config.getoption(\"--option_suite\")\n    ncores = request.config.getoption(\"--ncores\")\n    nnodes = request.config.getoption(\"--nnodes\")\n    scheduler = request.config.getoption(\"--scheduler\")\n    account = request.config.getoption(\"--account\")\n    walltime = request.config.getoption(\"--walltime\")\n    queue = request.config.getoption(\"--queue\")\n\n    configuration = request.config.getoption(\"--config\")\n    if configuration == 'nwm_long_range':\n        configuration = \"nwm_output_long_range\"\n    else:\n        configuration = \"nwm_output_ana\"\n\n    candidate_nwm_output_sim = _make_sim(\n        domain_dir=domain_dir,\n        compiler=compiler,\n        source_dir=candidate_dir,\n        configuration=configuration,\n        option_suite=option_suite,\n        ncores=ncores,\n        nnodes=nnodes,\n        scheduler=scheduler,\n        account=account,\n        walltime=walltime,\n        queue=queue\n    )\n\n    return candidate_nwm_output_sim\n\n\n@pytest.fixture(scope=\"session\")\ndef reference_sim(request):\n\n    domain_dir = request.config.getoption(\"--domain_dir\")\n    compiler = request.config.getoption(\"--compiler\")\n    reference_dir = request.config.getoption(\"--reference_dir\")\n    configuration = request.config.getoption(\"--config\")\n    option_suite = request.config.getoption(\"--option_suite\")\n    ncores = request.config.getoption(\"--ncores\")\n    nnodes = request.config.getoption(\"--nnodes\")\n    scheduler = request.config.getoption(\"--scheduler\")\n    account = request.config.getoption(\"--account\")\n    walltime = request.config.getoption(\"--walltime\")\n    queue = request.config.getoption(\"--queue\")\n\n    reference_sim = _make_sim(\n        domain_dir=domain_dir,\n        compiler=compiler,\n        source_dir=reference_dir,\n        configuration=configuration,\n        option_suite=option_suite,\n        ncores=ncores,\n        nnodes=nnodes,\n        scheduler=scheduler,\n        account=account,\n        walltime=walltime,\n        queue=queue\n    )\n\n    return reference_sim\n\n\n# Since we want to leverage the NWM compiles (both candidate and reference, ptoentially),\n# we create additional simulation fixtures where we hard-code the alternate configurations,\n# those are \"channel-only\" and \"nwm_output_ana\", currently.\n@pytest.fixture(scope=\"session\")\ndef reference_nwm_output_sim(request):\n\n    domain_dir = request.config.getoption(\"--domain_dir\")\n    compiler = request.config.getoption(\"--compiler\")\n    reference_dir = request.config.getoption(\"--reference_dir\")\n    option_suite = request.config.getoption(\"--option_suite\")\n    ncores = request.config.getoption(\"--ncores\")\n    nnodes = request.config.getoption(\"--nnodes\")\n    scheduler = request.config.getoption(\"--scheduler\")\n    account = request.config.getoption(\"--account\")\n    walltime = request.config.getoption(\"--walltime\")\n    queue = request.config.getoption(\"--queue\")\n\n    configuration = request.config.getoption(\"--config\")\n    if configuration == 'nwm_long_range':\n        configuration = \"nwm_output_long_range\"\n    else:\n        configuration = \"nwm_output_ana\"\n\n    reference_nwm_output_sim = _make_sim(\n        domain_dir=domain_dir,\n        compiler=compiler,\n        source_dir=reference_dir,\n        configuration=configuration,\n        option_suite=option_suite,\n        ncores=ncores,\n        nnodes=nnodes,\n        scheduler=scheduler,\n        account=account,\n        walltime=walltime,\n        queue=queue\n    )\n\n    return reference_nwm_output_sim\n\n\n@pytest.fixture(scope=\"session\")\ndef output_dir(request):\n    configuration = request.config.getoption(\"--config\")\n    output_dir = request.config.getoption(\"--output_dir\")\n    use_existing_test_dir = request.config.getoption(\"--use_existing_test_dir\")\n\n    output_dir = pathlib.Path(output_dir)\n    output_dir = output_dir / configuration\n    if not use_existing_test_dir:\n        output_dir.mkdir(parents=True)\n\n    return output_dir\n\n\n@pytest.fixture(scope=\"session\")\ndef ncores(request):\n    return int(request.config.getoption(\"--ncores\"))\n\n\n@pytest.fixture(scope=\"session\")\ndef xrcmp_n_cores(request):\n    return int(request.config.getoption(\"--xrcmp_n_cores\"))\n\n\n@pytest.fixture(scope=\"session\")\ndef feature_ids(request):\n    domain_dir = request.config.getoption(\"--domain_dir\")\n\n    domain_dir = pathlib.Path(domain_dir)\n    domain_dir = domain_dir / \"testing_diff_feature_ids.json\"\n\n    try:\n        return json.loads(open(domain_dir).read())\n    except:\n        return None\n"
  },
  {
    "path": "tests/ctests/CMakeLists.txt",
    "content": "# add Makefile targets to setup test runs\n# Croton Test Options: {Gridded, Gridded_no_lakes, NWM, Reach, ReachLakes}\nset(croton_testcases \"gridded\" \"gridded_no_lakes\" \"nwm\" \"nwm_ana\"\n  \"nwm_long_range\" \"reach\" \"reach_lakes\")\n\n# set default croton setup and run target\nset(croton_default_testcase \"gridded\")\nadd_custom_target(croton\n  COMMAND bash\n  ${CMAKE_CURRENT_SOURCE_DIR}/setup_cmake_testcase.sh ${croton_default_testcase} ${CMAKE_BINARY_DIR})\nadd_custom_target(run-croton\n  COMMAND bash\n  ${CMAKE_CURRENT_SOURCE_DIR}/run_cmake_testcase.sh ${croton_default_testcase} ${CMAKE_BINARY_DIR} 1)\nadd_custom_target(run-croton-parallel\n  COMMAND bash\n  ${CMAKE_CURRENT_SOURCE_DIR}/run_cmake_testcase.sh ${croton_default_testcase} ${CMAKE_BINARY_DIR} 2)\n\n# generate commands for every croton testcase option\nforeach(croton_testcase ${croton_testcases})\n  string(TOLOWER ${croton_testcase} testcase)\n  add_custom_target(croton-${testcase}\n    COMMAND bash\n    ${CMAKE_CURRENT_SOURCE_DIR}/setup_cmake_testcase.sh ${croton_testcase} ${CMAKE_BINARY_DIR})\n  add_custom_target(run-croton-${testcase}\n    DEPENDS croton-${testcase}\n    COMMAND bash\n    ${CMAKE_CURRENT_SOURCE_DIR}/run_cmake_testcase.sh ${croton_testcase} ${CMAKE_BINARY_DIR} 1)\n  add_custom_target(run-croton-${testcase}-parallel\n    DEPENDS croton-${testcase}\n    COMMAND bash\n    ${CMAKE_CURRENT_SOURCE_DIR}/run_cmake_testcase.sh ${croton_testcase} ${CMAKE_BINARY_DIR} 2)\nendforeach()\n\n# generic ctests\nadd_executable(fortran_ctest_should_fail\n  should_fail.f90)\nadd_test(NAME fortran_ctest_should_fail\n  COMMAND fortran_ctest_should_fail)\nset_tests_properties(fortran_ctest_should_fail\n  PROPERTIES WILL_FAIL TRUE)\n\nadd_executable(fortran_ctest_should_not_fail\n  should_not_fail.f90)\nadd_test(NAME fortran_ctest_should_not_fail\n  COMMAND fortran_ctest_should_not_fail)\n"
  },
  {
    "path": "tests/ctests/run_cmake_testcase.sh",
    "content": "#!/bin/bash\n\n# Bash script is meant to be used by CMake. It runs the Croton testcases after\n# setup_cmake_testcase.sh uses them\n\n# setup directory variables in script\ntestcase_type=${1}\nbinary_dir=${2}\nnp=${3}\nrun_dir=${binary_dir}/Run\noutput_dir=output_${testcase_type}\n\nif [ \"$np\" -eq \"1\" ]; then\n    run_cmd=\"./wrf_hydro\"\nelse\n    run_cmd=\"mpiexec -np ${np} ./wrf_hydro\"\nfi\n\n# run testcase\ncd $run_dir\n${run_cmd}\n\n# collect output, and fail silently if files not outputted at this point\nmkdir -p ${output_dir}\nmv *.CHANOBS_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv *.CHRTOUT_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv *.CHRTOUT_GRID1 ${output_dir}/ 2>/dev/null\nmv *.GWOUT_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv *.LAKEOUT_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv *.LDASOUT_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv *.LSMOUT_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv *.RTOUT_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv HYDRO_RST.*_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv RESTART.*_DOMAIN1 ${output_dir}/ 2>/dev/null\nmv diag_hydro.* ${output_dir}/ 2>/dev/null\n"
  },
  {
    "path": "tests/ctests/run_dir_makefile.mk",
    "content": "# this file is to be copied into the CMake ${CMAKE_BINARY_DIR}/Run/ directory\nall: build\n\nbuild:\n\tmake -C ..\n\nrun:\n\t./wrf_hydro\n\n# download and extract Croton, NY test case to Run directory\n# testcase options: {Gridded, Gridded_no_lakes, NWM, Reach, ReachLakes}\ncroton:\n\tmake -C .. $@\ncroton-gridded:\n\tmake -C .. $@\ncroton-gridded-no-lakes:\n\tmake -C .. $@\ncroton-nwm:\n\tmake -C .. $@\ncroton-nwm_ana:\n\tmake -C .. $@\ncroton-nwm_long_range:\n\tmake -C .. $@\ncroton-reach:\n\tmake -C .. $@\ncroton-reach_lakes:\n\tmake -C .. $@\n# run croton targets\nrun-croton:\n\tmake -C .. $@\nrun-croton-gridded:\n\tmake -C .. $@\nrun-croton-gridded-no-lakes:\n\tmake -C .. $@\nrun-croton-nwm:\n\tmake -C .. $@\nrun-croton-nwm_ana:\n\tmake -C .. $@\nrun-croton-nwm_long_range:\n\tmake -C .. $@\nrun-croton-reach:\n\tmake -C .. $@\nrun-croton-reach_lakes:\n\tmake -C .. $@\n# run in parallel\nrun-croton-gridded-parallel:\n\tmake -C .. $@\nrun-croton-gridded-no-lakes-parallel:\n\tmake -C .. $@\nrun-croton-nwm-parallel:\n\tmake -C .. $@\nrun-croton-nwm_ana-parallel:\n\tmake -C .. $@\nrun-croton-nwm_long_range-parallel:\n\tmake -C .. $@\nrun-croton-reach-parallel:\n\tmake -C .. $@\nrun-croton-reach_lakes-parallel:\n\tmake -C .. $@\n\nclean:\n\trm -f *.CHANOBS_DOMAIN1 *.CHRTOUT_DOMAIN1 *.GWOUT_DOMAIN1\n\trm -f *.LAKEOUT_DOMAIN1 *.LDASOUT_DOMAIN1 *.LSMOUT_DOMAIN1\n\trm -f *.RTOUT_DOMAIN1 RESTART.*_DOMAIN1 HYDRO_RST.*_DOMAIN1\n\trm -f *.CHRTOUT_GRID1\n\trm -f diag_hydro.*\n"
  },
  {
    "path": "tests/ctests/setup_cmake_testcase.sh",
    "content": "#!/bin/bash\n\n# Bash script is meant to be used by CMake. It downloads and extracts the\n# Croton, NY testcase to the CMake build Run directory. It then setups up the\n# files so ctest can run wrf_hydro\n\n# setup directory variables in script\n# match the input case to valid testcase_dir\ncase ${1} in\n    gridded)\n        testcase_dir=\"Gridded\"\n        ;;\n    gridded_no_lakes)\n        testcase_dir=\"Gridded_no_lakes\"\n        ;;\n    nwm_ana)\n        testcase_dir=\"NWM\"\n        ;;\n    nwm_ana)\n        testcase_dir=\"NWM\"\n        ;;\n    nwm_long_range)\n        testcase_dir=\"NWM\"\n        ;;\n    reach)\n        testcase_dir=\"Reach\"\n        ;;\n    reach_lakes)\n        testcase_dir=\"ReachLakes\"\n        ;;\n    *)\n        echo \"setup_cmake_testcase.sh: first command line argument did not match\"\n        exit 1\n        ;;\nesac\nbinary_dir=${2}\ntest_file_dir=${binary_dir}/tests\nrun_dir=${binary_dir}/Run\n\n# download testcase if not present\nversion=5.4\ncroton_tarball=croton_NY_training_example_v${version}.tar.gz\nif [ ! -f ${test_file_dir}/${croton_tarball} ]\nthen\n    cd ${test_file_dir}\n    wget -nv https://github.com/NCAR/wrf_hydro_nwm_public/releases/download/v${version}.0/${croton_tarball}\nfi\n\n# extract testcase\ncd ${run_dir}\nif [ ! -d example_case ]\nthen\n   tar zxf ${test_file_dir}/${croton_tarball}\nfi\n\n# setup testcase\ntestcase=example_case/\ntestcase_dir=${testcase}/${testcase_dir}\ncp ${testcase_dir}/hydro.namelist .\ncp ${testcase_dir}/namelist.hrldas .\nln -sf ${testcase_dir}/DOMAIN .\nln -sf ${testcase_dir}/RESTART .\nln -sf ${testcase}/FORCING .\n\n# turn on all output. Done with sed instead of Python for performance\nsed -i 's/^\\( *CHRTOUT_DOMAIN *= *\\).*$/\\11/' hydro.namelist\nsed -i 's/^\\( *CHANOBS_DOMAIN *= *\\).*$/\\11/' hydro.namelist\nsed -i 's/^\\( *CHRTOUT_GRID *= *\\).*$/\\11/' hydro.namelist\nsed -i 's/^\\( *LSMOUT_DOMAIN *= *\\).*$/\\11/' hydro.namelist\nsed -i 's/^\\( *RTOUT_DOMAIN *= *\\).*$/\\11/' hydro.namelist\n\n# if NWM test fix for ana and long_range runs\ncase ${1} in\n    nwm_ana)\n        sed -i 's/^\\( *RUNOFF_OPTION *= *\\).*$/\\17/I' namelist.hrldas\n        ;;\n    nwm_longrange)\n        sed -i 's/^\\( *RUNOFF_OPTION *= *\\).*$/\\17/I' namelist.hrldas\n        sed -i 's/^\\( *AGGFACTRT *= *\\).*$/\\11/I' hydro.namelist\n        sed -i 's/^\\( *DXRT *= *\\).*$/\\11000/I' hydro.namelist\n        sed -i 's/^\\( *OVRTSWCRT *= *\\).*$/\\10/I' hydro.namelist\n        sed -i 's/^\\( *RST_TYP *= *\\).*$/\\10/I' hydro.namelist\n        sed -i 's/^\\( *RTOUT_DOMAIN *= *\\).*$/\\10/I' hydro.namelist\n        sed -i 's/^\\( *SUBRTSWCRT *= *\\).*$/\\10/I' hydro.namelist\n        sed -i 's/^\\( *maxagepairsbiaspersist *= *\\).*$/\\124/I' hydro.namelist\n        sed -i 's/^\\( *persistBias *= *\\).*$/\\1.false./I' hydro.namelist\n        ;;\n    *)\n        ;;\nesac\n"
  },
  {
    "path": "tests/ctests/should_fail.f90",
    "content": "program should_fail\n  implicit none\n  error stop 1\nend program should_fail\n"
  },
  {
    "path": "tests/ctests/should_not_fail.f90",
    "content": "program should_not_fail\n  implicit none\n  stop\nend program should_not_fail\n"
  },
  {
    "path": "tests/hrldas_option_suites.json",
    "content": "{\n  \"compound_channel_off\":{\n    \"noahlsm_offline\": {},\n    \"wrf_hydro_offline\": {}\n  }\n}\n"
  },
  {
    "path": "tests/hydro_option_suites.json",
    "content": "{\n  \"compound_channel_off\":{\n    \"hydro_nlist\": {\n      \"compound_channel\": false\n    },\n    \"nudging_nlist\":{}\n  }\n}"
  },
  {
    "path": "tests/local/derecho/example_croton_test.sh",
    "content": "#!/bin/bash\n\n./model_test.sh \\\n    -c  path/to/wrf_hydro_nwm_public \\\n    -r  path/to/wrf_hydro_nwm_public_REFERENCE \\\n    --compiler=ifort \\\n    --mpi=impi \\\n    --config='nwm_ana' \\\n    --ncores=6 --queue=share \\\n    --reference_update=false \\\n    --domain_dir path/to/croton_NY\n\n# Can be added\n#    --use_existing_test_dir\n#    --xrcmp_n_cores 4\n\nexit $?\n"
  },
  {
    "path": "tests/local/derecho/model_test.sh",
    "content": "#!/bin/bash\n# A first productiony test script for Derecho.\n# Why bash?\n#    1) might need to establish the python env from scratch,\n#    2) set the modules is much easier\n#    3) git is easier in bash.\nscript_dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\nthe_help=\"\\\nModel Testing\n\nRequired\n    -c:\n        Candidate directory path. The code to test.\n    -r:\n        Reference directory path. The code to test against.\n\nOptions:\n    --reference_update:\n       default=true\n       In the reference repo, fetch upstream (NCAR) and checkout branch matching\n       that of the candidate?\n    --compiler:\n        [default=ifort, gfort, <You can try whatever is available in modules>]\n        Currently:  ifort -> intel/17.0.1   and  gnu -> gnu/7.1.0\n        We should try to keep this update along with what is here:\n        https://github.com/NCAR/wrf_hydro_nwm_public/wiki/Compiler-requirements-by-version\n    --mpi:\n        [default=impi, <You can try whatever is available in modules.>]\n    --exe_cmd:\n        [default=\\\"mpirun -np \\\\\\$ncores ./wrf_hydro\\\", <Whatever you need for your mpi.>]\n        See examples for MPT in the shared queue (other MPI distros apparently dont need this).\n    --config:\n        [default=nwm_ana, nwm_long_range, <Whatever is available in the .json files for the domain.>]\n    ---ncores:\n        default=360\n    --nnodes:\n        default=ceiling ncores 36\n    --queue:\n        default=regular\n    --account:\n        default=NRAL0017\n    --walltime:\n        default=01:00:00\n    --domain_dir:\n        The domain must be properly constructed with domain-side json namelist patch files and a\n        .version file.\n    --use_existing_test_dir\n        default is not included. Lets testing proceede with existing output in place.\n    --xrcmp_n_cores\n        default is 0. Values < 2 mean \\\"use nccmp\\\", otherwise the number of cores xrcmp\n        and xrnan will use.\n\n\n\nUsage Examples:\n# A CONUS test of nwm_ana\n./model_test.sh -c /path/to/candidate_dir -r /path/to/reference_dir\n\n# A CONUS test of nwm_long_range\n./model_test.sh -c /path/to/candidate_dir -r /path/to/reference_dir \\\\\n    --compiler=ifort --mpi=mpt --config=nwm_long_range --ncores=288\n\n# A croton test of all test configurations. Could swap the domain.\n./model_test.sh \\\\\n    -c ~/WRF_Hydro/wrf_hydro_nwm_public \\\\\n    -r ~/WRF_Hydro/.wrf_hydro_nwm_public_REFERENCE \\\\\n    --compiler=ifort --mpi=impi \\\\\n    --config='nwm_ana nwm_long_range gridded reach' \\\\\n    --ncores=6 --queue=share \\\\\n    --domain_dir path/to/croton_NY\n\n# Non-standard mpi/exe_cmd example. A croton test of nwm_ana configuration.\n# An strenuous exercise in bash escaping.\n./model_test.sh \\\\\n    -c ~/WRF_Hydro/wrf_hydro_nwm_public \\\\\n    -r ~/WRF_Hydro/.wrf_hydro_nwm_public_REFERENCE \\\\\n    --compiler=ifort --mpi=mpt \\\\\n    --exe_cmd=\\\"mpiexec_mpt $'\\\\\\$(hostname)' -np \\\\\\$ncores ./wrf_hydro\\\" \\\\\n    --config='nwm_ana' \\\\\n    --ncores=6 --queue=share \\\\\n    --domain_dir path/to/croton_NY\n\"\n\n## Default options\ncompiler=ifort\nmpi=impi\nexe_cmd=\"mpirun -np \\$ncores ./wrf_hydro\"\nconfig=nwm_ana\nncores=360\nnnodes=to_calculate\nqueue=regular\naccount=NRAL0017\nwalltime=01:00:00\nreference_update=true\ndomain_dir=path/to/CONUS\nuse_existing_test_dir=''\nxrcmp_n_cores=0\n\n# Getops\nTEMP=\\\n`getopt \\\n    -o h,c:,r: \\\n    --long help,compiler:,mpi:,exe_cmd:,config:,ncores:,nnodes:,queue:,account:,walltime:,reference_update:,domain_dir:,use_existing_test_dir,xrcmp_n_cores: \\\n    -n 'Model Testing' -- \"$@\"`\n\nif [ $? != 0 ] ; then echo \"Terminating...\" >&2 ; exit 1 ; fi\n# Note the quotes around `$TEMP': they are essential!\neval set -- \"$TEMP\"\nwhile true; do\n    case \"$1\" in\n        -h | --help ) echo \"$the_help\"; exit 0 ;;\n        -c ) candidate_dir=\"$2\"; shift 2;;\n        -r ) reference_dir=\"$2\"; shift 2;;\n        --reference_update ) reference_update=\"$2\"; shift 2;;\n        --compiler ) compiler=\"$2\"; shift 2;;\n        --mpi ) mpi=\"$2\"; shift 2;;\n        --exe_cmd ) exe_cmd=\"$2\"; shift 2;;\n        --config ) config=\"$2\"; shift 2;;\n        --ncores ) ncores=\"$2\"; shift 2;;\n        --nnodes ) nnodes=\"$2\"; shift 2;;\n        --queue ) queue=\"$2\"; shift 2;;\n        --account ) account=\"$2\"; shift 2;;\n        --walltime ) walltime=\"$2\"; shift 2;;\n        --domain_dir ) domain_dir=\"$2\"; shift 2;;\n        --use_existing_test_dir ) use_existing_test_dir=\"--use_existing_test_dir \" ; shift 1;;\n        --xrcmp_n_cores ) xrcmp_n_cores=\"$2\"; shift 2;;\n        -- ) shift; break ;;\n        * ) break ;;\n    esac\ndone\n\n# Required variables.\nif [ -z $candidate_dir ] | [ -z $reference_dir ]; then\n    echo \"The candidate_dir and reference_dir arguments are both required but not found. Exiting.\"\n    exit 1\nfi\n\n# Perform any needed substitution/evaluation.\nif [[ \"$nnodes\" == to_calculate ]]; then\n    function ceiling() { echo \"($1 + $2 - 1)/$2\" | bc; }\n    nnodes=$(ceiling $ncores 36)\nfi\n\nexe_cmd=`eval \"echo $exe_cmd\"`\n\n\n#-------------------------------------------------------\n# Modules.\n# Default intel and gnu compiler versions if the generics are passed\nif [ \"$compiler\" == ifort ]; then\n    compiler_module=intel/18.0.5\nelif [ \"$compiler\" == gfort ]; then\n    compiler_module=gnu/8.3.0\nelse\n    compiler_module=$compiler\n    if [[ \"$compiler\" == *intel* ]]; then\n        compiler=ifort\n    elif [[ \"$compiler\" == *gnu* ]]; then\n        compiler=gfort\n    else\n        \"Unsure how to se the ./configure compiler from the selected compiler=$compiler\"\n    fi\nfi\n\necho\nprintf \"\\e[7;49;94mModule information\\e[0m\\n\"\nmodule purge\n# Is this strict enough in the sense that things might be changing?\nmodule load  $compiler_module  $mpi  ncarcompilers  netcdf  ncarenv nccmp || exit 4\nmodule list\n\n#-------------------------------------------------------\n# Python Env\ndeactivate > /dev/null 2>&1\nsource /glade/p/cisl/nwc/model_testing_env/wrf_hydro_nwm_test/bin/activate || exit 9\n\n#-------------------------------------------------------\n## Candidates branch to tag the test directory and optionally update the reference.\ncd $candidate_dir\nbranch_name=\"$(git symbolic-ref HEAD 2>/dev/null)\" || branch_name=\"$(git rev-parse --short HEAD)\"\nbranch_name=${branch_name##refs/heads/}\nprintf \"\\e[7;49;94mTesting branch: $branch_name in $candidate_dir\\e[0m\\n\"\noutput_dir=/glade/scratch/`whoami`/take_test_$(basename $domain_dir)_${branch_name}\n\n#-------------------------------------------------------\n# \"Update\" the reference dir? This makes the branch match that of\n# the candidate and it fetches the NCAR:branch_name\n# There are two potential pitfalls here,\n# 1) the branch name may not match\n# 2) you may not want to update. (take care of)\nif [[ $reference_update == 'true' ]]; then\n    echo; echo\n    printf \"\\e[7;49;94mUpdate the reference repository with NCAR/$branch_name\\e[0m\\n\"\n    cd $reference_dir || exit 9\n    if [[ `hostname` != *derecho* ]]; then\n        ssh derecho1 \"cd $reference_dir && git fetch upstream\" || exit 9\n    else\n        cd $reference_dir || exit 9\n        git fetch upstream || exit 9\n    fi\n    git checkout origin/$branch_name  || exit 9\n    cd - 2> /dev/null cd 1> /dev/null\nfi\n\n#-------------------------------------------------------\necho; echo\nprintf \"\\e[7;49;94mStarting tests in $output_dir\\e[0m\\n\"\necho\n\nrun_test_path=$(dirname $script_dir)\npython3 $run_test_path/run_tests.py \\\n       --config $config \\\n       --compiler $compiler \\\n       --exe_cmd=\"'$exe_cmd'\" \\\n       --scheduler \\\n       --output_dir $output_dir \\\n       --candidate_dir $candidate_dir \\\n       --reference_dir $reference_dir \\\n       --domain_dir $domain_dir \\\n       --ncores $ncores \\\n       --nnodes $nnodes \\\n       --account $account \\\n       --queue $queue \\\n       --walltime $walltime \\\n       --xrcmp_n_cores $xrcmp_n_cores \\\n       $use_existing_test_dir\n\nexit $?\n"
  },
  {
    "path": "tests/local/examples/ex1_run_croton_derecho.sh",
    "content": "#!/usr/bin/env bash\n\n# These paths point to a preconfigured conda environment. Likewise, you can install your own\n# using the utils/nwm_testing.yml conda environment file.\nexport PATH=\"/glade/work/jmills/nwm_testing/miniconda3/envs/nwm_testing/bin:$PATH\"\nexport PYTHONPATH=\"/glade/work/jmills/nwm_testing/miniconda3/envs/nwm_testing/lib/python3.7/site-packages\"\n\n# Run the tests interactively, no scheduler\npython /glade/scratch/$USER/wrf_hydro_nwm_public/tests/local/run_tests.py \\\n--config nwm_ana nwm_long_range gridded reach \\\n--compiler ifort \\\n--output_dir /glade/scratch/$USER/test_out \\\n--candidate_dir /glade/scratch/$USER/wrf_hydro_nwm_public/ \\\n--reference_dir /glade/scratch/$USER/wrf_hydro_nwm_public/ \\\n--domain_tag dev \\\n--ncores 3\n"
  },
  {
    "path": "tests/local/examples/ex2_run_conus_derecho.sh",
    "content": "#!/usr/bin/env bash\n\n# Load conda environment\n\n# Run the tests using a scheduler \npython /glade/scratch/$USER/wrf_hydro_nwm_public/tests/local/run_tests.py \\\n--config nwm_ana nwm_long_range gridded reach \\\n--compiler ifort \\\n--output_dir /glade/derecho/scratch/$USER/test_out \\\n--candidate_dir /glade/derecho/scratch/$USER/wrf_hydro_nwm_public/ \\\n--reference_dir /glade/derecho/scratch/$USER/wrf_hydro_nwm_public/ \\\n--domain_dir path/to/CONUS_domain \\\n--scheduler\n"
  },
  {
    "path": "tests/local/examples/ex3_run_croton_docker.sh",
    "content": "#!/usr/bin/env bash\n\n# Pull the docker container for model testing\ndocker pull wrfhydro/dev:modeltesting\n\n# Run testing\ndocker run -it \\\n-v /Volumes/d1/jmills/temp/wrf_hydro_nwm_public:/home/docker/candidate \\\n-v /Volumes/d1/jmills/temp/wrf_hydro_nwm_public_upstream:/home/docker/reference \\\nwrfhydro/dev:modeltesting \\\n--config nwm_ana nwm_long_range gridded reach \\\n--domain_tag dev\n\n# See https://hub.docker.com/r/wrfhydro/dev/ for more info\n# To get help on command line use 'docker run wrfhydro/dev:modeltesting --help'\n"
  },
  {
    "path": "tests/local/requirements.txt",
    "content": "atomicwrites==1.3.0\nattrs==19.1.0\nbeautifulsoup4==4.8.0\nboltons==20.2.1\nbs4==0.0.1\ncertifi==2024.7.4\ncftime==1.0.3.4\nchardet==3.0.4\ncloudpickle==1.2.1\nDateTime==4.3\ndeepdiff==8.6.2\nf90nml==1.2\ngdown==5.2.2\nidna==3.7\nimportlib-metadata==4.13.0\nlocket==0.2.0\nmore-itertools==7.2.0\nnetCDF4==1.6.0\nnumpy==1.22.4\npandas==1.3.5\npartd==1.0.0\npathlib==1.0.1\npluggy==0.12.0\npytest==9.0.3\npytest-html==3.0.0\npytest-metadata==1.8.0\npython-dateutil==2.8.0\npytz==2019.2\nrequests==2.33.0\nsetuptools==78.1.1\nsix==1.12.0\nsoupsieve==1.9.3\ntoolz==0.10.0\nurllib3==2.6.3\nwrfhydropy==0.0.19\nxarray==0.19\nzipp==3.19.1\nzope.interface==5.5.2\n"
  },
  {
    "path": "tests/local/run_tests.py",
    "content": "import pathlib\nimport shutil\nimport socket\nimport subprocess\nimport sys\nfrom argparse import ArgumentParser\nimport gdown\nimport os\n\nsys.path.insert(0, str(pathlib.Path(__file__).parent))\nfrom utils.releaseapi import get_release_asset\n\ndef run_tests(\n    config: str,\n    compiler: str,\n    domain_dir: str,\n    candidate_dir: str,\n    reference_dir: str,\n    output_dir: str,\n    scheduler: bool = False,\n    exe_cmd: str = None,\n    ncores: int = 216,\n    nnodes: int = 6,\n    account: str = 'NRAL0017',\n    walltime: str = '02:00:00',\n    queue: str = 'regular',\n    print_log: bool = False,\n    pdb: bool = False,\n    pdb_x: bool = False,\n    use_existing_test_dir: bool = False,\n    xrcmp_n_cores: int = 0\n):\n\n    \"\"\"Function to run wrf_hydro_nwm pytests\n        Args:\n            config: The config(s) to run, must be listed in hydro_namelist.json keys.\n            E.g. nwm_ana gridded\n            compiler: The compiler to use, options are 'ifort' or 'gfort'\n            domain_dir: The domain directory to use\n            candidate_dir: The wrf-hydro code candidate directory to use, e.g. wrf_hydro_nwm_public\n            reference_dir: The wrf-hydro code directory to use, e.g. wrf_hydro_nwm_public\n            output_dir: The directory to hold test outputs\n            scheduler: Use PBSDerecho scheduler?\n            exe_cmd: Optional. The MPI dependent run command which zeroth variable for ncores.\n            ncores: Optional. The number of cores to use if running on Derecho\n            nnodes: Optional. The number of nodes to use if running on Derecho\n            account: Options. The account number to use if running on Derecho\n            walltime: Optional. Walltime for scheduler\n            queue: Optional, queue to use for scheduler\n            print_log: Optional, print text logs instead of HTML logs\n            pdb: Drop down to python debugger in pytest?\n            pdb_x: Exit the debugger on success?\n            use_existing_test_dir: Run just output comparisions on existing test dir?\n    \"\"\"\n\n    # Pytest wants the actual source code directory, not the top level repo directory\n    candidate_source_dir = candidate_dir + '/src'\n    reference_source_dir = reference_dir + '/src'\n\n    # Load modules and override nnodes/ncores if running on Derecho\n    hostname = socket.gethostname()\n    module_cmd = ''\n    if 'Derecho' in hostname:\n        module_cmd = 'echo; echo \"Using the following modules for testing:\" ; module list; echo;'\n\n    # HTML report\n    html_report = 'wrfhydro_testing' + '-' + compiler + '-' + config + '.html'\n    html_report = str(pathlib.Path(output_dir).joinpath(html_report))\n\n    pytest_cmd = \"pytest -vv --tb=no --ignore=local -p no:cacheprovider \"\n\n    if pdb:\n        if pdb_x:\n            pytest_cmd += \" -x --pdb\"\n        else:\n            pytest_cmd += \" --pdb\"\n\n    if print_log:\n        pytest_cmd += \" -s\"\n\n    # Ignore section: for cleaner tests with less skipps!\n\n    # NWM Supplementals.\n    # If it is not NWM, ignore channel-only and nwm_output tests.\n    # (This is likely not the right way to do this.)\n    if config != 'nwm_ana':\n        pytest_cmd += \" --ignore=tests/test_supp_1_channel_only.py \"\n\n    if config.lower().find('nwm') < 0:\n        pytest_cmd += \" --ignore=tests/test_supp_2_nwm_output.py \"\n\n    pytest_cmd += \" --html=\" + str(html_report) + \" --self-contained-html\"\n    pytest_cmd += \" --config=\" + config.lower()\n    pytest_cmd += \" --compiler=\" + compiler.lower()\n    pytest_cmd += \" --domain_dir=\" + domain_dir\n    pytest_cmd += \" --candidate_dir=\" + candidate_source_dir\n    pytest_cmd += \" --reference_dir=\" + reference_source_dir\n    pytest_cmd += \" --output_dir=\" + output_dir\n    pytest_cmd += \" --exe_cmd=\" + exe_cmd\n    pytest_cmd += \" --ncores=\" + str(ncores)\n    pytest_cmd += \" --xrcmp_n_cores=\" + str(xrcmp_n_cores)\n\n    if scheduler:\n        pytest_cmd += \" --scheduler \"\n        pytest_cmd += \" --nnodes=\" + str(nnodes)\n        pytest_cmd += \" --account=\" + account\n        pytest_cmd += \" --walltime=\" + walltime\n        pytest_cmd += \" --queue=\" + queue\n\n    if use_existing_test_dir:\n        pytest_cmd += \" --use_existing_test_dir\"\n\n    subprocess_cmd = module_cmd + pytest_cmd\n    print(\"SUBPROCESS_CMD =\", subprocess_cmd)\n    tests = subprocess.run(subprocess_cmd, shell=True, cwd=candidate_dir)\n    print(\"POST SUBPROCESS CMD\")\n\n    return tests\n\n\ndef main():\n    parser = ArgumentParser(\n        description='Run WRF-Hydro test suite locally',\n        epilog='Example usage: python -B run_tests.py '\n        '--config nwm_ana nwm_long_range '\n        '--compiler gfort '\n        '--candidate_dir '\n        '/glade/scratch/jmills/wrf_hydro_nwm_public_origin '\n        '--reference_dir '\n        '/glade/scratch/jmills/wrf_hydro_nwm_public_upstream '\n        '--domain_dir /glade/scratch/jmills/CONUS_V2 '\n        '--scheduler '\n        '--output_dir /glade/scratch/jmills/conus_v2_testing_gfort'\n    )\n\n    parser.add_argument(\n        \"--config\",\n        required=True,\n        nargs='+',\n        help=\"<Required> The configuration(s) to test, \"\n        \"must be one listed in src/hydro_namelist.json keys.\"\n    )\n\n    parser.add_argument(\n        '--compiler',\n        required=True,\n        help='<Required> compiler, options are intel or gfort'\n    )\n\n    parser.add_argument(\n        '--output_dir',\n        required=True,\n        help='<Required> test output directory'\n    )\n\n    parser.add_argument(\n        '--candidate_dir',\n        required=True,\n        help='<Required> candidate model directory'\n    )\n\n    parser.add_argument(\n        '--reference_dir',\n        required=True,\n        help='<Required> reference model directory'\n    )\n\n    parser.add_argument(\n        '--domain_dir',\n        required=False,\n        help='optional domain directory'\n    )\n\n    parser.add_argument(\n        \"--domain_tag\",\n        required=False,\n        help=\"The release tag of the domain to retrieve, e.g. v5.0.1. or dev. If \"\n             \"specified, a small test domain will be retrieved and placed in the \"\n             \"specified output_dir and used for the testing domain\"\n    )\n\n    parser.add_argument(\n        '--exe_cmd',\n        default=\"'mpirun -np {0} ./wrf_hydro'\",\n        required=False,\n        help='The MPI-dependent model execution command. Default is best guess. '\n        'The first/zeroth variable is set to the total number of cores (ncores). The '\n        'wrf_hydro_py convention is that the exe is always named wrf_hydro.'\n    )\n\n    parser.add_argument(\n        '--ncores',\n        default='2',\n        required=False,\n        help='Number of cores to use for testing'\n    )\n\n    parser.add_argument(\n        '--scheduler',\n        required=False,\n        action='store_true',\n        help='Scheduler to use for testing, options are PBSDerecho or do not '\n        'specify for no scheduler'\n    )\n\n    parser.add_argument(\n        '--nnodes',\n        default='6',\n        required=False,\n        help='Number of nodes to use for testing if running on scheduler'\n    )\n\n    parser.add_argument(\n        '--account',\n        default='NRAL0017',\n        required=False,\n        action='store',\n        help='Account number to use if using a scheduler.'\n    )\n\n    parser.add_argument(\n        '--walltime',\n        default='02:00:00',\n        required=False,\n        action='store',\n        help='Account number to use if using a scheduler.'\n    )\n\n    parser.add_argument(\n        '--queue',\n        default='regular',\n        required=False,\n        action='store',\n        help='Queue to use if running on NCAR Derecho, options are regular, '\n        'premium, or shared'\n    )\n\n    parser.add_argument(\n        '--print',\n        required=False,\n        action='store_true',\n        help='Print log to stdout instead of html'\n    )\n\n    parser.add_argument(\n        '--pdb',\n        required=False,\n        action='store_true',\n        help='pdb (debug) in pytest')\n\n    parser.add_argument(\n        '-x',\n        required=False,\n        action='store_true',\n        help='Exit pdb on first failure.'\n    )\n\n    parser.add_argument(\n        '--use_existing_test_dir',\n        default=False,\n        required=False,\n        action='store_true',\n        help='Use existing compiles and runs, only perform output comparisons.'\n    )\n\n    parser.add_argument(\n        '--xrcmp_n_cores',\n        default=0,\n        required=False,\n        help='Use xrcmp if > 0, and how many cores if so?'\n    )\n\n    args = parser.parse_args()\n\n    # Make all directories pathlib objects\n    output_dir = pathlib.Path(args.output_dir)\n    candidate_dir = pathlib.Path(args.candidate_dir)\n    reference_dir = pathlib.Path(args.reference_dir)\n    domain_dir = args.domain_dir\n\n    if domain_dir is not None:\n        domain_dir = pathlib.Path(domain_dir)\n\n    # Get other args\n    config_list = args.config\n\n    compiler = args.compiler\n    domain_tag = args.domain_tag\n    exe_cmd = args.exe_cmd\n    ncores = int(args.ncores)\n    nnodes = int(args.nnodes)\n    scheduler = args.scheduler\n    account = args.account\n    walltime = args.walltime\n    queue = args.queue\n    print_log = args.print\n    pdb = args.pdb\n    pdb_x = args.x\n    use_existing_test_dir = args.use_existing_test_dir\n    xrcmp_n_cores = args.xrcmp_n_cores\n\n    # Make output dir if does not exist\n    if not use_existing_test_dir:\n        if output_dir.is_dir():\n            raise(IsADirectoryError('Output directory ' + str(output_dir) + ' already exists'))\n        else:\n            output_dir.mkdir(parents=True)\n\n    # Get the domain if asked for\n    if domain_tag is not None:\n        # Reset domain dir to be the downlaoded domain in the output dir\n        domain_dir = output_dir.joinpath('example_case')\n\n        if domain_tag == 'dev':\n            file_id = '1xFYB--zm9f8bFHESzgP5X5i7sZryQzJe'\n            url = 'https://drive.google.com/uc?id='+file_id\n            output_f = str(output_dir) + '/gdrive_testcase.tar.gz'\n            gdown.download(url, output_f, quiet=False)\n\n            # untar the test case\n            untar_cmd = 'tar -xf ' + output_f\n            subprocess.run(untar_cmd,\n                           shell=True,\n                           cwd=str(output_dir))\n        else:\n            get_release_asset(download_dir=str(output_dir),\n                              repo_name='NCAR/wrf_hydro_nwm_public',\n                              tag=domain_tag,\n                              asset_name='testcase')\n            # untar the test case\n            untar_cmd = 'tar -xf *testcase*.tar.gz'\n            subprocess.run(untar_cmd,\n                           shell=True,\n                           cwd=str(output_dir))\n\n    # Make copy paths\n    candidate_copy = output_dir.joinpath(candidate_dir.name + '_can_pytest')\n    reference_copy = output_dir.joinpath(reference_dir.name + '_ref_pytest')\n    # copy directories to avoid polluting user source code directories\n    if not candidate_copy.exists() or not use_existing_test_dir:\n        shutil.copytree(str(candidate_dir), str(candidate_copy), symlinks=True)\n    if not reference_copy.exists() or not use_existing_test_dir:\n        shutil.copytree(str(reference_dir), str(reference_copy), symlinks=True)\n\n    # run pytest for each supplied config\n    has_failure = False\n    print(\"\\n\\n---------------- Starting WRF-Hydro Testing ----------------\")\n    print(\"Testing the configs: \" + ', '.join(config_list), flush=True)\n    for config in config_list:\n        extra_spaces = 29\n        total_len = len(config) + extra_spaces\n        print('\\n\\n' + ('#' * total_len))\n        print('### TESTING:  ---  ' + config + '  ---  ###')\n        print(('#' * total_len) + '\\n', flush=True)\n\n        test_result = run_tests(\n            config=config,\n            compiler=compiler,\n            domain_dir=str(domain_dir),\n            candidate_dir=str(candidate_copy),\n            reference_dir=str(reference_copy),\n            output_dir=str(output_dir),\n            scheduler=scheduler,\n            exe_cmd=exe_cmd,\n            ncores=ncores,\n            nnodes=nnodes,\n            account=account,\n            walltime=walltime,\n            queue=queue,\n            print_log=print_log,\n            pdb=pdb,\n            pdb_x=pdb_x,\n            use_existing_test_dir=use_existing_test_dir,\n            xrcmp_n_cores=xrcmp_n_cores\n        )\n\n        if test_result.returncode != 0:\n            has_failure = True\n\n    # Exit with 1 if failure\n    if has_failure:\n        print('\\n\\n'\n              '##################################')\n        print('###  ---  TESTING FAILED  ---  ###')\n        print('##################################\\n\\n', flush=True)\n        exit(1)\n    else:\n        print('\\n\\n'\n              '##################################')\n        print('###  ---  TESTING PASSED  ---  ###')\n        print('##################################\\n\\n', flush=True)\n        exit(0)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "tests/local/utils/attach_all_plots.bash",
    "content": "#!/bin/bash\n\nPR=$1\nCONFIG=$2\nTEST_TYPE=$3\ncwd=`pwd`\ndiffs=$GITHUB_WORKSPACE/test_report/$CONFIG\n\nif [[ ! -d $diffs ]]; then\n    echo \"No diff plots to attach at ${diffs}\"\n    exit 0\nfi\n\ntitle=\"Difference plots for configuration '$CONFIG' and $TEST_TYPE test type\"\n\n# set for repo authentication\ngit config --global user.email \"model.tester@ucar.edu\"\ngit config --global user.name \"Model Tester\"\n\nTOKEN=`wget -q -O- https://hydro.rap.ucar.edu/HydroInspector/token.html`\nREPO=NCAR/wrf_hydro_nwm_public\n\ncd $diffs\n\n# if $diffs directory is not empty, attach files in it\nif [[ `ls -1 ./` ]]\nthen\n    python $cwd/attach_plots_to_pr.py -r $REPO -p $PR -d -t \"$TOKEN\" --title \"$title\" ./*\nfi\n"
  },
  {
    "path": "tests/local/utils/attach_plots_to_pr.py",
    "content": "##############################################\n#\n# This script takes a list of image files and uploads them as a comment\n# on the selected Github pull request.\n#\n# Images are added as a commit to an orphaned 'images' branch on the selected\n# repo, where they can be linked to using the commit hash. Images are stored\n# at the top level of the repo, under q directory 'images_{pull request number}'\n#\n# The 'images' branch is an orphaned branch - it is invisible to the Github UI\n# and isn't included in clone operations (unless the --mirror option is used)\n#\n#\n##############################################\n\n# check python version. 'f' formatting strings aren't available\n# until python v3.6\nimport sys\nif sys.version_info[0] < 3 or \\\n        (sys.version_info[0] == 3 and sys.version_info[1] < 6):\n    print(\"Requires python version 3.6 or later\")\n    exit(-1)\n\nimport os\nfrom github import Github\nimport argparse\nimport subprocess\n\n# set up logging for this module\nimport logging\nlogging.basicConfig(format=\"%(levelname)s, %(asctime)s %(message)s\")\nlogger = logging.getLogger(\"attach_plots_to_pr\")\nlogger.setLevel(logging.DEBUG)\n\n# location for writing temporary local files, e.g. the cloned repository\nTEMP_DIR = \"/tmp\"\n\n# The name of the images repository\nIMAGE_REPO = \"hydro-automerge/wrf_hydro_nwm_public_images\"\n\n# The name of the images branch and branch reference\nIMAGEREF = \"images/image-ref\"\n\n\ndef get_options():\n    \"\"\"\n    Get command line options\n    Returns: processed options, or None\n    \"\"\"\n\n    parser = argparse.ArgumentParser(description=\"Upload plot images as a Github PR comment\")\n\n    parser.add_argument('images', metavar='image', nargs='+', help='A list of image files to attach')\n    parser.add_argument(\"-t\", \"--token\", dest=\"token\", default=None, help=\"Github authentication token, or path to a\" \\\n                        + \" file containing a token\")\n    parser.add_argument(\"-r\", \"--repo\", dest=\"repo\", required=True, help=\"GHithub repository name\")\n    parser.add_argument(\"-p\", \"--pull\", dest=\"pull\", required=True, type=int, help=\"Pull request number\")\n    parser.add_argument(\"--title\", dest=\"title\", default=None, help=\"Title to give to this set of plots\")\n\n    parser.add_argument(\"-d\", dest=\"debug\", action=\"store_true\", default=False, help=\"Print debug messages\")\n\n    options = parser.parse_args()\n\n    if len(options.images) < 1:\n        print(\"ERROR: Must supply one or more image files!\")\n        return None\n\n    if options.token is not None and os.path.isfile(options.token):\n        try:\n            options.token = open(options.token).read()[:-1]\n        except Exception as e:\n            print(f\"Problem reading token file: {e}\")\n            return None\n\n    logger.setLevel(logging.DEBUG if options.debug is True else logging.INFO)\n\n    return options\n\n\ndef login(token=None):\n    \"\"\"\n    Login to the github API using the supplied token\n    @param token: The personal access token to use to read/write from Github, or None\n    @return: A logged-in pygithub object, or None\n    \"\"\"\n    try:\n        gh = Github(token)\n        return gh\n    except Exception as e:\n        logger.error(f\"Problem logging into github: {e}\")\n        return None\n\n\ndef runcmd(cmd, pwd=None, logError=True):\n    \"\"\"\n    Run a shell command using the subprocess module\n    @param cmd: The command to run\n    @param pwd: The working directory to issue the command from\n    @param logError: If True, log any exceptions\n    @return: The process output, or None on error\n    \"\"\"\n    logger.debug(f\"Executing command: {cmd}\")\n    try:\n        output = subprocess.check_output(cmd, shell=True, cwd=pwd, stderr=subprocess.STDOUT)\n        return output.decode(\"utf-8\")\n    except subprocess.CalledProcessError as e:\n        if logError:\n            logger.error(e)\n            logger.error(e.output)\n        return None\n\n\ndef clone_repo(repo, outdir, token=None):\n    \"\"\"\n    Clone the repository and check out the orphaned images branch\n    @param repo: The repository name on Github\n    @param outdir: The local path to the cloned repository\n    @param token: The personal access token to use to read/write from Github, or None\n    @return: True on success, False on error\n    \"\"\"\n    try:\n        if not os.path.isdir(outdir):\n            login = \"\" if token is None else f\"x-access-token:{token}@\"\n            runcmd(f\"git clone https://{login}github.com/{repo}\", TEMP_DIR, logError=False)\n\n        logging.debug(\"Checking out latest images commit\")\n\n        runcmd(f\"git pull origin {IMAGEREF}\", outdir, logError=False)\n        runcmd(\"git checkout FETCH_HEAD\", outdir, logError=False)\n        logs = runcmd(\"git log --format=%H\", outdir)\n        if not logs:\n            raise Exception(\"Unable to get commit history\")\n\n        latest = logs.split(\"\\n\")[0]\n        if runcmd(f\"git checkout {latest}\", outdir) is None:\n            raise Exception(\"Unable to checkout latest commit\")\n\n        return True\n\n    except Exception as e:\n        logger.error(f\"Unable to clone repository: {e}\")\n        return False\n\n\ndef add_images(images, outdir, pull):\n    \"\"\"\n    Add images to the images branch, commit them and push the\n    commit to github\n    @param images: A list of images to upload, including the local path to the images\n    @param outdir: The path to the locally-cloned repository\n    @param pull: The pull request number\n    @return: The image commit hash, or False on error\n    \"\"\"\n    logger.debug(\"Uploading images to github images branch\")\n\n    imagedir = f\"{outdir}/images_{pull}\"\n    os.makedirs(imagedir, exist_ok=True)\n\n    try:\n        # remove duplicate images first, then commit the deletion\n        # so they can get reattached to the new commit\n        removed = False\n        for img in images:\n            imgname = os.path.basename(img)\n            if os.path.isfile(f\"{imagedir}/{imgname}\"):\n                runcmd(f\"git rm {imgname}\", imagedir)\n                removed = True\n\n        if removed:\n            logger.debug(\"Removing duplicate images from repository\")\n            if runcmd(f\"git commit -m 'removing images'\", outdir) is None:\n                raise Exception(\"Problem committing removal of duplicate images\")\n\n        logger.debug(f\"Copying images to {imagedir}\")\n        for img in images:\n            if runcmd(f\"cp {img} {imagedir}/.\") is None:\n                raise Exception(\"Not all image files could be copied\")\n\n        logger.debug(\"Adding images to commit\")\n        if runcmd(f\"git add images_{pull}\", outdir) is None:\n            raise Exception(\"Problem committing new images\")\n\n        logger.debug(\"Commiting images\")\n        if runcmd(f\"git commit -m 'adding images'\", outdir) is None:\n            raise Exception(\"Problem committing new images\")\n\n        logger.debug(\"Pushing commit to github\")\n        if runcmd(f\"git push origin HEAD:refs/{IMAGEREF}\", outdir) is None:\n            raise Exception(\"Problem pushing commits\")\n\n        logger.debug(\"Getting commit hash\")\n        logs = runcmd(\"git log --format=%H\", outdir)\n        if logs is None:\n            raise Exception(\"Couldn't get latest commit hash after push\")\n\n        sha = logs.split(\"\\n\")[0]\n\n        logger.debug(\"Done uploading images\")\n\n        return sha\n\n    except Exception as e:\n        logger.error(f\"Problem uploading images: {e}\")\n        return False\n\n\ndef create_pull_comment(gh, repo, sha, images, pull, title=None):\n    \"\"\"\n    Add uploaded images to the pull request comments using the commit hash\n    @param gh: The logged-in pygithub object\n    @param repo: The name of the Github repository\n    @param sha: The commit hash from the uploaded image commit\n    @param images: A list of images to attach\n    @param pull: The pull request number\n    @param title: The title to give to this set of plots\n    @return: True on success, False on error\n    \"\"\"\n    try:\n        logger.debug(f\"Getting pull request #{pull}\")\n        pr = gh.get_repo(repo).get_pull(pull)\n\n        logger.debug(\"Assembling comment images\")\n        comment = \"\"\n\n        if title:\n            comment += \"## \" + title + \"\\n\"\n\n        for img in images:\n            img = os.path.basename(img)\n            path = f\"https://github.com/{IMAGE_REPO}/blob/{sha}/images_{pull}/{img}\"\n            comment += f\"![alt text]({path}?raw=true)\\n\"\n\n        logger.debug(\"Adding comment to pull request\")\n        pr.create_issue_comment(comment)\n\n        logger.debug(\"Comment added.\")\n        return True\n\n    except Exception as e:\n        logger.error(f\"Problem opening pull request: {e}\")\n        return False\n\n\ndef run():\n    \"\"\"\n    Get command line options and run the algorithm\n    @return: True on success, False on error\n    \"\"\"\n    options = get_options()\n    if not options: return False\n\n    gh = login(options.token)\n    if not gh: return False\n\n    reponame = IMAGE_REPO.split(\"/\")[-1]\n    outdir = f\"{TEMP_DIR}/{reponame}\"\n\n    if not clone_repo(IMAGE_REPO, outdir, token=options.token): return False\n\n    sha = add_images(options.images, outdir, options.pull)\n    if not sha: return False\n\n    if not create_pull_comment(gh, options.repo, sha, options.images, options.pull, options.title):\n        return False\n\n    logging.debug(\"Done\")\n\n    return True\n\n\nif __name__ == \"__main__\":\n    if run():\n        exit(0)\n    exit(-1)\n"
  },
  {
    "path": "tests/local/utils/generate_diff_plots.py",
    "content": "##########################################################\n#\n# This script concatenates all model output files for the given\n# file type(s), across the time dimension, and creates difference\n# statistics plots for each gridded point (heatmap) or feature\n# point (boxplot).\n#\n# Note this script assumes that gridded files have (at least)\n# x, y, and time dimensions (named as such), and point files\n# have a feature_id dimension\n#\n###########################################################\n\n# check python version. 'f' formatting strings aren't available\n# until python v3.6\nimport sys\nif sys.version_info[0] < 3 or \\\n        (sys.version_info[0] == 3 and sys.version_info[1] < 6):\n    print(\"Requires python version 3.6 or later\")\n    exit(-1)\n\n\nimport xarray as xr\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.cm as cm\nimport argparse\n\n\n# set up logging for this module\nimport logging\nlogging.basicConfig(format=\"%(levelname)s, %(asctime)s %(message)s\")\nlogger = logging.getLogger(\"generate_diff_plots\")\nlogger.setLevel(logging.DEBUG)\n\nimport warnings\nwarnings.filterwarnings(\"ignore\", message=\"All-NaN slice encountered\")\nwarnings.filterwarnings(\"ignore\", message=\"invalid value encountered in true_divide\")\nwarnings.filterwarnings(\"ignore\", message=\"invalid value encountered in divide\")\n\n\nGRIDDED = \"gridded\"\nFEATURE = \"feature\"\n\nFEATURE_ID = \"feature_id\"\nTIME = \"time\"\nXCOORD = \"x\"\nYCOORD= \"y\"\n\n# stats to calculate. Keys must be handled in get_stat() function below\nSTATS = {\n    'sum': \"Sum of model differences\",\n    'abssum': \"Sum of absolute model differences\",\n    'mean': \"Mean of model differences\",\n    'min': \"Minimum of model differences\",\n    'max': \"Maximum of model differences\",\n    'std': \"Standard deviation of model differences\"\n}\n\n# variables to diff from each model output file\nFILE_TYPES = {\n    'ldas': {\n        'datatype': GRIDDED,\n        'pattern': \".LDASOUT_\"\n    },\n    'chanobs': {\n        'datatype': FEATURE,\n        'pattern': \".CHANOBS_\"\n    },\n    'gwout': {\n        'datatype': FEATURE,\n        'pattern': \".GWOUT_\"\n    },\n    'chrtout': {\n        'datatype': FEATURE,\n        'pattern': \".CHRTOUT_\"\n    },\n    'lakeout': {\n        'datatype': FEATURE,\n        'pattern': \".LAKEOUT_\"\n    },\n    'rtout': {\n        'datatype': GRIDDED,\n        'pattern': \".RTOUT_\"\n    }\n}\n\n\ndef get_options():\n    \"\"\"\n    Get command line options\n    Returns: Filtered options, or None\n\n    \"\"\"\n    global FILE_TYPES\n\n    available_types = FILE_TYPES.keys()\n\n    parser = argparse.ArgumentParser(description=\"Create difference statistics plots for wrfhydro model output\")\n    parser.add_argument(\"-f\", \"--filetype\", dest=\"filetype\", required=True, action=\"append\", help=\"File type. One of \"\n                    + \",\".join(available_types) + \". Can be specified more than once. To select only specific variables \"\n                    + \"for a filetype, follow filetype with a colon and separate variable names with a comma, e.g. \"\n                      \"-f ldas:ACCET,SNOWH,FIRA\")\n    parser.add_argument(\"-o\", \"--output\", dest=\"outdir\", required=True, help=\"Write plot images to this directory.\")\n    parser.add_argument(\"-b\", \"--basepath\", dest=\"base_path\", required=True, help=\"Path to base model output files.\")\n    parser.add_argument(\"-B\", \"--baselabel\", dest=\"base_label\", default=\"Base Model\", help=\"Label for base model.\")\n    parser.add_argument(\"-c\", \"--comppath\", dest=\"comp_path\", required=True, help=\"Path to comparison model output files.\")\n    parser.add_argument(\"-C\", \"--complabel\", dest=\"comp_label\", default=\"Comp Model\", help=\"Label for comparison model.\")\n    parser.add_argument(\"-i\", \"--ids\", dest=\"ids\", default=None,\n                        help=\"Also plot timeseries comparisons for these feature ids (as a comma separated list)\")\n    parser.add_argument(\"-n\", \"--nodask\", dest=\"use_dask\", default=True, action=\"store_false\",\n                        help=\"Don't use dask. Useful to avoid HDF5 chunking errors for small datasets.\")\n\n    parser.add_argument(\"-t\", \"--thresholds\", dest=\"thresholds\", default=None, help=\"Use monimum thresholds from this file.\")\n\n    parser.add_argument(\"-d\", dest=\"debug\", action=\"store_true\", default=False, help=\"Print debug messages\")\n\n    options = parser.parse_args()\n\n    if not os.path.isdir(options.base_path):\n        print(f\"ERROR: {options.base_path} does not exist!\")\n        return False\n\n    if not os.path.isdir(options.comp_path):\n        print(f\"ERROR: {options.comp_path} does not exist!\")\n        return False\n\n    if options.thresholds:\n        try:\n            thresholds = {}\n            for line in open(options.thresholds).readlines():\n                (type, var, threshold) = line.replace(\"\\n\",\"\").split(\",\")\n\n                if type not in thresholds:\n                    thresholds[type] = {}\n\n                thresholds[type][var] = float(threshold)\n\n            options.thresholds = thresholds\n\n        except Exception as e:\n            print(f\"ERROR: Could not read thresholds file: {e}\")\n            return None\n\n    filetypes = {}\n    for ft in options.filetype:\n        toks = ft.split(\":\")\n        type = toks[0]\n        if type not in FILE_TYPES:\n            print(f\"ERROR: Unknown file type {type}\")\n            return None\n\n        try:\n            # find one file and pull out variables and long names\n            files = os.listdir(options.base_path)\n            found = False\n            for f in files:\n                if FILE_TYPES[type]['pattern'] not in f:\n                    continue\n                ds = xr.open_dataset(\"%s/%s\" % (options.base_path, f))\n                variables = {}\n                for v in ds.variables:\n                    if v in ds.coords or v == \"crs\":\n                        continue\n\n                    label = ds.variables[v].attrs['long_name'] if 'long_name' in ds.variables[v].attrs else v\n                    units = ds.variables[v].attrs['units'] if 'units' in ds.variables[v].attrs else \"\"\n\n                    variables[v] = {'label': label, 'units': units}\n\n                    if options.thresholds:\n                        if type in options.thresholds and v in options.thresholds[type]:\n                            variables[v]['threshold'] = options.thresholds[type][v]\n\n                FILE_TYPES[type]['variables'] = variables\n                found=True\n                break\n            if not found:\n                print(\"ERROR: No files of type '%s' found in '%s'\" % (type, options.base_path))\n                return None\n        except Exception as e:\n            print(\"Problem getting varnames from '%s' files: %s\" % (type, e))\n            return None\n\n        # now, get requested variables and match them against what we found in the file\n        vars = []\n        if len(toks) > 1:\n            toks = toks[1].split(\",\")\n            for v in toks:\n                if v not in FILE_TYPES[type]['variables']:\n                    print(f\"ERROR: Unknown variable {v} for file type {type}. Skipping.\")\n                else:\n                    vars.append(v)\n        else:\n            vars = FILE_TYPES[type]['variables']\n\n        filetypes[type] = vars\n\n    options.filetypes = filetypes\n\n    if options.ids is not None:\n        options.ids = options.ids.split(\",\")\n\n    if not os.path.isdir(options.outdir):\n        try:\n            os.makedirs(options.outdir, exist_ok=True)\n        except Exception as e:\n            print(f\"ERROR: Could not create output directory: {e}\")\n            return None\n\n    logger.setLevel(logging.DEBUG if options.debug is True else logging.INFO)\n    return options\n\n\ndef get_datasets(base_path, comp_path, filepattern, useDask=True):\n    \"\"\"\n    Get base and comparison datasets by concatenating all output files\n    across the time dimension. If a variable does not have a time dimension,\n    one is added before concatenation.\n\n    Args:\n        base_path: The path to the base model output\n        comp_path: The path to the comparison model output\n        filepattern: The type of file to compare (e.g. LDAS, CHANOBS). Must be a unique\n                     filenme pattern shared by these file types\n\n    Returns: A dict {'base': base_dataset, 'comp': comp_dataset}, or None\n\n    \"\"\"\n    logger.info(\"Opening datasets...\")\n\n    datasets = {}\n\n    for c in [base_path, comp_path]:\n        logger.debug(\"Opening %s\" % c)\n\n        if useDask:\n            try:\n                ds = xr.open_mfdataset(\"%s/*%s*\" % (c, filepattern), combine=\"nested\", concat_dim=TIME)\n            except:\n                ds = None\n        else:\n            a = []\n            for f in sorted(os.listdir(c)):\n                if filepattern not in f: continue\n                ds = xr.open_dataset('%s/%s' % (c, f))\n\n                for v in ds.variables:\n                    if v not in ds.coords:\n                        if TIME not in ds[v].dims:\n                            ds[v] = ds[v].expand_dims(dim=TIME)\n\n                a.append(ds)\n\n            # merge files along the time axis\n            try:\n                ds = xr.merge(a)\n            except:\n                ds = None\n\n        if ds is None:\n            logger.info(\"No datasets found\")\n            return None\n\n        if c == base_path and 'base' not in datasets:\n            datasets['base'] = ds\n        else:\n            datasets['comp'] = ds\n\n        logger.debug(\"Found %s times\" % len(ds[TIME]))\n\n    return datasets\n\n\ndef create_diff(datasets, variable, threshold=0):\n    \"\"\"\n    Subtract the comparison dataset from the base dataset\n    at each gridpoint, for the given variable,\n    Args:\n        datasets: A dict containing base and comp datasets\n        variable: The variable to diff\n        threshold: The minimum absolute difference to be considered a difference.\n             Diff values below the threshold will be considered equal (i.e. diff=0)\n\n    Returns: A dataset containing the diff\n             TODO also include projection info?\n\n    \"\"\"\n    logger.debug(f\"Getting diffs for {variable}\")\n\n    base = datasets['base']\n    comp = datasets['comp']\n    diff = base\n    basev = base[variable]\n    compv = comp[variable]\n\n    # choose top layer if there's an extra dimension\n    for dim in basev.dims:\n        if dim not in [TIME, XCOORD, YCOORD, FEATURE_ID]:\n            basev = basev.sel({dim:0})\n            compv = compv.sel({dim:0})\n\n    d = basev.data - compv.data\n    diff[f\"{variable}_diff\"] = basev\n    diff[f\"{variable}_diff\"].data = xr.where(np.abs(d) < threshold, 0, d)\n\n    return diff[[f\"{variable}_diff\"]]\n\n\ndef get_stat(dataset, variable, stat):\n    \"\"\"\n    Get the given statistic over all model differences at each gridpoint, across the time dimension\n    Args:\n        dataset: The dataset containing the calculated model difference\n        variable: The variable name to analyze\n        stat: The name of the stat to calculate. One of [ min, max, sum, abssum, mean, std ]\n    Returns:\n        A dataset containing the given statistic of all differences at each gridpoint, across the time dimension\n    \"\"\"\n    da = None\n    # minimum non-NAN values at a point required for sum statistics\n    times = dataset.dims[TIME]-1\n\n    if stat == \"min\":\n        da = dataset[variable].min(dim=TIME)\n    elif stat == \"max\":\n        da = dataset[variable].max(dim=TIME)\n    elif stat == \"sum\":\n        da = dataset[variable].sum(dim=TIME, min_count=times)\n    elif stat == \"abssum\":\n        da = dataset[variable]\n        da.data = np.abs(da.data)\n        da = da.sum(dim=TIME, min_count=times)\n    elif stat == \"mean\":\n        da = dataset[variable].mean(dim=TIME)\n    elif stat == \"std\":\n        da = dataset[variable].std(dim=TIME)\n    else:\n        logger.error(f\"Unknown statistic: {stat}\")\n\n    return da\n\n\ndef plot_diffs(dataset, file_type, variable, var_label, outpath, type=GRIDDED, base=\"Base Model\", comp=\"Comp Model\",\n               range=None, value_range=None):\n    \"\"\"\n    Plot statistics of the model differences, and save to disk as a PNG file\n    Args:\n        dataset: The dataset containing the diff of (base-comp).\n        file_type: The type of file (ldas, chrt, etc)\n        variable: The name of the analyzed variable, without '_diff' appended\n                  (Expects the dataset to contain {variable}_diff)\n        var_label: The long name of the variable\n        outpath: The path where the plots should be written (as a .png file)\n        type: The type of data (gridded, feature)\n        base: The long name of the base model, for plot labeling\n        comp: The long name of the comparison model, for plot labeling\n        range: The start/end times of the analysis, as strings. Optional\n        value_range: The min/max of the variable. Optional\n    Returns:\n\n    \"\"\"\n    varname = variable + \"_diff\"\n    logger.info(f\"Creating plots for {variable}\")\n\n    if type not in [ GRIDDED, FEATURE]:\n        logger.error(f\"Plots not implemented for datatype '{type}'\")\n        return False\n\n    # average across non-coordinate variables\n    for c in dataset.dims:\n        if c not in dataset.coords:\n            dataset = dataset.mean(dim=c)\n\n    plt.rcParams.update({'font.size': 22, 'axes.labelsize': 22})\n    cols = len(STATS)\n    if cols % 2 > 0:\n        cols += 1\n    cols = int(cols / 2)\n\n    if type == GRIDDED:\n        fig, axes = plt.subplots(2, cols, sharex=True, sharey=True)\n    elif type == FEATURE:\n        fig, axes = plt.subplots(2, cols)\n    else:\n        logger.error(f\"plot_diffs: Unknown type '{type}'\")\n        return False\n\n    fig.set_size_inches(20*cols, 35)\n    title = f\"{var_label}\\n{base} minus {comp}\"\n    if range:\n        start, end = (range[0], range[1])\n        title += f\"\\n{start} to {end}\"\n    if value_range and value_range[1] != value_range[0]:\n        df = float(dataset[varname].max().compute())\n        max_err = \"{0:.4f}\".format(df / (value_range[1] - value_range[0]) * 100)\n        title += f\"\\nValue range {value_range[0]} to {value_range[1]}, Max error {max_err}%\"\n    plt.suptitle(title, fontsize=40, weight='bold')\n\n    row = 0\n    col = 0\n    for stat in STATS.keys():\n        label = STATS[stat]\n\n        logger.debug(f\" --- Calculating {stat}\")\n        ds = get_stat(dataset, varname, stat)\n\n        if type == GRIDDED:\n            # plot the data as a heatmap\n            ds.plot(cmap=cm.coolwarm, ax=axes[row, col], cbar_kwargs={'label': \"\"}) # ,vmin=-1, vmax=1 )\n        elif type == FEATURE:\n            # drop NaN's so we can do a boxplot. Report # of NaN's (if there are any)\n            data = ds.where(~np.isnan(ds),drop=True)\n            axes[row, col].boxplot(data)\n            num_nans = len(ds) - len(data)\n\n            if num_nans > 0:\n                y = 0 if len(data) == 0 else data.min()\n                axes[row,col].text(1, y, f\"                   # NaNs: {num_nans}\")\n\n        axes[row,col].set_title(label, fontsize=30, weight='bold')\n\n        col += 1\n        if col >= cols:\n            col = 0\n            row += 1\n\n    if type == GRIDDED:\n        for ax in axes.flat:\n            ax.set(xlabel=\"X coordinate (m)\", ylabel=\"Y coordinate (m)\")\n        for ax in axes.flat:\n            ax.label_outer()\n\n    outf = f\"{outpath}/{file_type}_{variable}_diff_stats.png\"\n    logger.info(f\"Saving plot to {outf}\")\n    plt.savefig(outf, bbox_inches = 'tight')\n\n    return True\n\n\ndef get_range(datasets, variable):\n    \"\"\"\n    Get the min/max of the selected variable across both datasets\n    @param datasets: The loaded datasets1\n    @param variable: The variable to inspect\n    @return: (min, max)\n    \"\"\"\n    min1 = datasets['base'][variable].min()\n    max1 = datasets['base'][variable].max()\n    min2 = datasets['comp'][variable].min()\n    max2 = datasets['comp'][variable].max()\n\n    min = min1 if min1 < min2 else min2\n    max = max1 if max1 > max2 else max2\n\n    # round the values to two significant digits\n    range = []\n    for a in [min, max]:\n        a = float(a)\n        if 'e' in str(a):\n            (n,e) = str(a).split(\"e\")\n            n = \"{0:.2f}\".format(float(n))\n            a = float(f\"{n}e{e}\")\n        else:\n            a = float(\"{0:.2f}\".format(a))\n\n        range.append(a)\n\n    return range\n\n\ndef process_variable(type, variable, datasets, outdir, base_label, comp_label, ids=None):\n    \"\"\"\n    Create difference statistics for a single variable\n    Args:\n        type: The filetype containing the variable\n        variable: The variable name\n        datasets: The dict containing the base and comp model datasets\n        outdir: The directory to write plots to\n        base_label: The label of the base model, to use in the plots\n        comp_label: The label of the comparison model, to use in the plots\n        ids: A list of feature ids to plot timeseries for\n\n    Returns: True on success, false on error\n\n    \"\"\"\n    logger.info(f\"Processing type {type}, variable {variable}\")\n    tp = FILE_TYPES[type]\n\n    threshold = FILE_TYPES[type]['variables'][variable]['threshold'] \\\n        if 'threshold' in FILE_TYPES[type]['variables'][variable] else 0\n\n    diff = create_diff(datasets, variable, threshold)\n\n    df = diff[f\"{variable}_diff\"].max().compute()\n    if df == 0:\n        logger.info(f\"No differences found for type {type}, variable {variable}. Skipping plots\")\n        return True\n\n    range = get_range(datasets, variable)\n\n    start = str(diff[TIME].values[0])[:19]\n    end = str(diff[TIME].values[-1])[:19]\n    label = FILE_TYPES[type]['variables'][variable]['label']\n    units = FILE_TYPES[type]['variables'][variable]['units']\n\n    var_label = f\"{label} ({variable}) - {units}\"\n\n    datatype = tp['datatype']\n    success = plot_diffs(diff, type, variable, var_label, outdir, datatype, base=base_label, comp=comp_label,\n                                  range=[start, end], value_range=range)\n\n    if ids is not None and tp['datatype'] == FEATURE \\\n            and FEATURE_ID in datasets['base'].variables and FEATURE_ID in datasets['comp'].variables:\n        for i in ids:\n            if int(i) in datasets['base'][FEATURE_ID]:\n                plot_timeseries(datasets, int(i), outdir, type, variable, base_label, comp_label)\n\n    return success\n\n\ndef plot_timeseries(datasets, feature_id, outpath, file_type, variable, base_label, comp_label):\n    \"\"\"\n    Plot feature timeseries for base and comparison models\n    Args:\n        datasets: A dict containing base and comparison model datasets\n        feature_id: The integer feature id to plot\n        outpath: The path to write output images to\n        file_type: The file type, e.g. chanobs, gwout, etc.\n        variable: The name of the variable to plot\n        base_label: The label for the base model\n        comp_label: The label for the comparison model\n\n    Returns: True on success\n\n    \"\"\"\n    logger.debug(f\"Plotting timeseries for feature id '{feature_id}'\")\n\n    base = datasets['base'][variable].sel({FEATURE_ID: feature_id})\n    comp = datasets['comp'][variable].sel({FEATURE_ID: feature_id})\n\n    start = str(base[TIME].values[0])[:19]\n    end = str(base[TIME].values[-1])[:19]\n    label = FILE_TYPES[file_type]['variables'][variable]['label']\n    units = FILE_TYPES[file_type]['variables'][variable]['units']\n\n    var_label = f\"{label} ({variable}) - {units}\"\n\n    fig = plt.figure()\n    plt.clf()\n\n    fig.set_size_inches(30,20)\n\n    base.plot(label=base_label)\n    comp.plot(label=comp_label)\n    plt.legend()\n\n    title = f\"{var_label}\\n{base_label} minus {comp_label}\\nTimeseries {start} to {end}\" + \\\n        f\"\\nFeature id: {feature_id}\"\n    plt.title(title)\n\n    outf = f\"{outpath}/{file_type}_{variable}_timeseries_feature_id_{feature_id}.png\"\n    logger.debug(f\"Saving plot to {outf}\")\n    plt.savefig(outf, bbox_inches = 'tight')\n\n    return True\n\n\ndef run(options=None):\n    \"\"\"\n    Create plots based on the command line options\n    Returns: True on success, False on error\n\n    \"\"\"\n    if not options:\n        options = get_options()\n    if not options:\n        return False\n\n    for type in options.filetypes.keys():\n        datasets = get_datasets(options.base_path, options.comp_path, FILE_TYPES[type]['pattern'], useDask=options.use_dask)\n\n        if datasets is None:\n            continue\n\n        for variable in options.filetypes[type]:\n            success = process_variable(type, variable, datasets, options.outdir, options.base_label,\n                                       options.comp_label, options.ids)\n\n            if not success:\n                return False\n\n        datasets['base'].close()\n        datasets['comp'].close()\n\n    return True\n\n\nif __name__ == \"__main__\":\n    if run():\n        exit(0)\n    exit(-1)\n\n"
  },
  {
    "path": "tests/local/utils/nwm_testing.yml",
    "content": "name: nwm_testing\nchannels:\n  - defaults\ndependencies:\n  - asn1crypto=0.24.0\n  - blas=1.0\n  - bzip2=1.0.6\n  - ca-certificates=2018.03.07\n  - certifi=2018.8.24\n  - cffi=1.11.5\n  - cftime=1.0.0b1\n  - chardet=3.0.4\n  - cryptography=2.3.1\n  - curl=7.61.0\n  - hdf4=4.2.13\n  - hdf5=1.10.2\n  - idna=2.7\n  - intel-openmp=2019.0\n  - jpeg=9b\n  - libcurl=7.61.0\n  - libedit=3.1.20170329\n  - libffi=3.2.1\n  - libgcc-ng=8.2.0\n  - libgfortran-ng=7.3.0\n  - libnetcdf=4.6.1\n  - libssh2=1.8.0\n  - libstdcxx-ng=8.2.0\n  - mkl=2019.0\n  - mkl_fft=1.0.4\n  - mkl_random=1.0.1\n  - ncurses=6.1\n  - netcdf4=1.6.0\n  - numpy=1.22.4\n  - numpy-base=1.22.4\n  - openssl=1.0.2p\n  - pip=23.3.2\n  - pycparser=2.18\n  - pyopenssl=18.0.0\n  - pysocks=1.6.8\n  - python=3.7.0\n  - readline=7.0\n  - requests=2.31.0\n  - setuptools=44.1.0\n  - six=1.11.0\n  - sqlite=3.24.0\n  - tk=8.6.8\n  - urllib3=1.26.18\n  - wheel=0.31.1\n  - xz=5.2.4\n  - zlib=1.2.11\n  - pip:\n    - atomicwrites==1.3.0\n    - attrs==19.1.0\n    - boltons==20.2.1\n    - cython==0.28.5\n    - DateTime==4.3\n    - deepdiff==6.2.3\n    - f90nml==1.2\n    - more-itertools==7.2.0\n    - pandas==1.3.5\n    - pathlib==1.0.1\n    - pluggy==0.12.0\n    - py==1.11.0\n    - pytest==7.4.4\n    - pytest-datadir-ng==1.1.0\n    - pytest-html==1.19.0\n    - pytest-metadata==1.7.0\n    - python-dateutil==2.7.3\n    - pytz==2018.5\n    - wrfhydropy==0.0.19\n    - xarray==0.19\n    - zope.interface==4.6.0\n"
  },
  {
    "path": "tests/local/utils/releaseapi.py",
    "content": "import json\nimport urllib.request\nfrom argparse import ArgumentParser\n\n\ndef get_release_asset(download_dir: str,\n                      repo_name: str,\n                      tag: str,\n                      asset_name: str = 'testcase'):\n    \"\"\"Function to download an asset from a specified public github repository\n        Args:\n            download_dir: The local directory to hold downloaded assets\n            repo_name: The repository name, e.g. NCAR/wrf_hydro_nwm_public\n            tag: The release tag, e.g. v5.0.1\n            asset_name: The name of the asset, can be partial\n    \"\"\"\n    url = \"https://api.github.com/repos/\" + repo_name + \"/releases/tags/\" + tag\n\n    # Get json data from api as a string\n    fp = urllib.request.urlopen(url)\n    json_string = fp.read().decode(\"utf8\")\n    fp.close()\n\n    # load into list of dicts\n    asset_list = json.loads(json_string)['assets']\n\n    # Iterate over assets and find asset url from asset name matching\n    for asset in asset_list:\n        if asset_name in asset['name']:\n            asset_url = asset['browser_download_url']\n            full_asset_name = asset['name']\n\n            #download asset\n            print('downloading asset ' + full_asset_name + ' to ' + download_dir)\n            download_filepath = str(download_dir) + '/' + full_asset_name\n            urllib.request.urlretrieve(asset_url, download_filepath)\n\ndef main():\n    parser = ArgumentParser()\n    parser.add_argument(\"--download_dir\",\n                        dest=\"download_dir\",\n                        help=\"The local directory to hold downloaded assets\")\n    parser.add_argument(\"--repo_name\",\n                        dest=\"repo_name\",\n                        help=\"The repository name, e.g. NCAR/wrf_hydro_nwm_public\")\n    parser.add_argument(\"--tag\",\n                        dest=\"tag\",\n                        help=\"The release tag, e.g. v5.0.1\")\n    parser.add_argument(\"--asset_name\",\n                        dest=\"asset_name\",\n                        default='testcase',\n                        help=\"The name of the asset, can be partial\")\n\n    args = parser.parse_args()\n\n    get_release_asset(download_dir = args.download_dir,\n                      repo_name = args.repo_name,\n                      tag = args.tag,\n                      asset_name = args.asset_name)\n\nif __name__ == '__main__':\n    main()\n\n"
  },
  {
    "path": "tests/local/utils/requirements.txt",
    "content": "cftime==1.6.1\ncycler==0.11.0\ndask==2022.7.0\ndask-core==2022.7.0\nfonttools==4.61.0\nkiwisolver==1.4.3\nmatplotlib==3.5.2\nnetCDF4==1.6.0\nnumpy==1.23.1\npackaging==21.3\npandas==1.4.3\nPillow==12.2.0\npyparsing==3.0.9\npython-dateutil==2.8.2\npytz==2022.1\nsix==1.16.0\nxarray==2022.3.0\n"
  },
  {
    "path": "tests/local/utils/thresholds.csv",
    "content": "ldas,FVEG,0.01\nldas,LAI,0.1\nldas,SAI,0.1\nldas,SWFORC,0.1\nldas,COSZ,0.01\nldas,LWFORC,0.1\nldas,RAINRATE,0.000001\nldas,EMISS,0.01\nldas,FSA,0.1\nldas,FIRA,0.1\nldas,GRDFLX,0.1\nldas,HFX,0.1\nldas,LH,0.1\nldas,ECAN,0.000001\nldas,EDIR,0.000001\nldas,ALBEDO,0.01\nldas,ETRAN,0.000001\nldas,UGDRNOFF,0.01\nldas,SFCRNOFF,0.001\nldas,CANLIQ,0.01\nldas,CANICE,0.01\nldas,ZWT,0.00001\nldas,WA,0.01\nldas,WT,0.01\nldas,ACCPRCP,0.01\nldas,ACCECAN,0.01\nldas,ACCEDIR,0.01\nldas,ACCETRAN,0.01\nldas,SAV,0.1\nldas,TR,0.1\nldas,EVC,0.1\nldas,IRC,0.1\nldas,SHC,0.1\nldas,IRG,0.1\nldas,SHG,0.1\nldas,EVG,0.1\nldas,GHV,0.1\nldas,SAG,0.1\nldas,IRB,0.1\nldas,SHB,0.1\nldas,EVB,0.1\nldas,GHB,0.1\nldas,TRAD,0.1\nldas,TG,0.1\nldas,TV,0.1\nldas,TAH,0.1\nldas,TGV,0.1\nldas,TGB,0.1\nldas,T2MV,0.1\nldas,T2MB,0.1\nldas,Q2MV,0.0001\nldas,Q2MB,0.0001\nldas,EAH,0.1\nldas,FWET,0.01\nldas,ZSNSO_SN,0.00001\nldas,SNICE,0.01\nldas,SNLIQ,0.01\nldas,SOIL_T,0.1\nldas,SOIL_W,0.01\nldas,SNOW_T,0.1\nldas,SOIL_M,0.01\nldas,SNOWH,0.0001\nldas,SNEQV,0.1\nldas,QSNOW,0.000001\nldas,FSNO,0.001\nldas,ACSNOW,0.01\nldas,ACSNOM,0.01\nldas,CM,0.00001\nldas,CH,0.00001\nldas,CHV,0.00001\nldas,CHB,0.00001\nldas,CHLEAF,0.00001\nldas,CHUC,0.00001\nldas,CHV2,0.00001\nldas,CHB2,0.00001\nldas,LFMASS,0.01\nldas,RTMASS,0.01\nldas,STMASS,0.01\nldas,WOOD,0.01\nldas,STBLCP,0.01\nldas,FASTCP,0.01\nldas,NEE,0.01\nldas,GPP,0.01\nldas,NPP,0.01\nldas,PSN,0.01\nldas,APAR,0.01\nldas,ACCET,0.01\nldas,CANWAT,0.01\nldas,SOILICE,0.01\nldas,SOILSAT_TOP,0.001\nldas,SOILSAT,0.001\nldas,SNOWT_AVG,0.1\nchrtout,streamflow,0.01\nchrtout,nudge,0.01\nchrtout,q_lateral,0.1\nchrtout,velocity,0.01\nchrtout,Head,0.01\nchrtout,QSfcLatRunoff*,0.001\nchrtout,QBucket*,0.001\nchrtout,QBtmVertRunoff*,0.001\nchrtout,AccSfcLatRunoff*,0.01\nchrtout,accBucket*,0.01\nrtout,zwattablrt,0.1\nrtout,sfcheadsubrt,1.0\nrtout,QSTRMVOLRT,1.0\nrtout,QBDRYRT,1.0\nlakeout,inflow,0.01\nlakeout,outflow,0.01\n"
  },
  {
    "path": "tests/test_1_fundamental.py",
    "content": "import copy\nimport datetime as dt\nimport os\nimport pathlib\nimport pickle\nimport sys\nimport warnings\nimport pandas as pd\nimport pytest\nimport wrfhydropy\nimport xarray as xr\n\nsys.path.insert(0, str(pathlib.Path(__file__).parent))\nfrom utilities import wait_job, print_diffs, plot_diffs\n\n# #################################\n# Setup the test with a domain, a candidate, and a reference.\n# Get domain, reference, candidate, and optional output directory from command line arguments\n# Setup a domain\n\n#List variabls to ignore in tests, primarily accumulation variables\nEXCLUDE_VARS = [\n    'ACMELT',\n    'ACSNOW',\n    'SFCRUNOFF',\n    'UDRUNOFF',\n    'ACCPRCP',\n    'ACCECAN',\n    'ACCEDIR',\n    'ACCETRAN',\n    'qstrmvolrt',\n    'QSTRMVOLRT',\n    'reference_time',\n    'lake_inflort'\n]\n\n# #################################\n# Define tests\n\n\ndef test_compile_candidate(candidate_sim, output_dir):\n    print(\"\\nQuestion: The candidate compiles?\\n\", end='')\n    print('\\n')\n\n    compile_dir = output_dir / 'compile_candidate'\n    if compile_dir.exists():\n        pytest.skip('Candidate compile dir exists, skipping candidate compile test')\n\n    # Compile the model, catch warnings related to non-existant compile directory\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        candidate_sim.model.compile(compile_dir=compile_dir)\n\n    # Check compilation status\n    assert candidate_sim.model.compile_log.returncode == 0, \\\n        \"Candidate code did not compile correctly.\"\n\n\ndef test_compile_reference(reference_sim, output_dir):\n    print(\"\\nQuestion: The reference compiles?\\n\", end='')\n    print('\\n')\n\n    compile_dir = output_dir / 'compile_reference'\n    if compile_dir.exists():\n        pytest.skip('Reference compile dir exists, skipping reference compile')\n\n    # Compile the model, catch warnings related to non-existant compile directory\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        reference_sim.model.compile(compile_dir=compile_dir)\n\n    # Check compilation status\n    assert reference_sim.model.compile_log.returncode == 0, \\\n        \"Reference code did not compile correctly\"\n\n\ndef test_run_candidate(candidate_sim, output_dir, ncores, exe_cmd):\n    print(\"\\nQuestion: The candidate runs successfully?\\n\", end='')\n    print('\\n')\n\n    candidate_sim_copy = copy.deepcopy(candidate_sim)\n\n    # Set run directory and change working directory to run dir for simulation\n    run_dir = output_dir / 'run_candidate'\n    if run_dir.exists():\n        pytest.skip('Candidate run dir exists, skipping candidate run test')\n\n    run_dir.mkdir(parents=True)\n    os.chdir(str(run_dir))\n\n    # Job\n    exe_command = exe_cmd.format(str(ncores))\n    out_dt = 1 if 'channel' in candidate_sim.model.model_config else 24\n    job = wrfhydropy.Job(\n        job_id='run_candidate',\n        exe_cmd=exe_command,\n        restart_freq_hr=24,\n        output_freq_hr=out_dt\n    )\n    candidate_sim_copy.add(job)\n\n    # Run, catch warnings related to missing start and end job times\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        candidate_sim_copy.compose()\n\n    print('\\nwaiting for job to complete...', end='')\n    candidate_sim_copy.run()\n    # Wait to collect until job has finished. All test runs are performed on a single job with\n    # job_id='test_job'\n    wait_job(candidate_sim_copy)\n\n    candidate_sim_copy.collect()\n    candidate_sim_copy.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n    # Check job run statuses\n    for job in candidate_sim_copy.jobs:\n        assert job.exit_status == 0, \\\n            \"Candidate code run exited with non-zero status\"\n\n\n# Run questions\ndef test_run_reference(reference_sim, output_dir, ncores, exe_cmd):\n    print(\"\\nQuestion: The reference runs successfully?\\n\", end='')\n    print('\\n')\n\n    reference_sim_copy = copy.deepcopy(reference_sim)\n\n    # Set run directory and change working directory to run dir for simulation\n    run_dir = output_dir / 'run_reference'\n    if run_dir.exists():\n        pytest.skip('Reference run dir exists, skipping reference run')\n    run_dir.mkdir(parents=True)\n    os.chdir(str(run_dir))\n\n    # Job\n    exe_command = exe_cmd.format(str(ncores))\n    out_dt = 1 if 'channel' in reference_sim.model.model_config else 24\n    job = wrfhydropy.Job(\n        job_id='run_reference',\n        exe_cmd=exe_command,\n        restart_freq_hr=24,\n        output_freq_hr=out_dt\n    )\n    reference_sim_copy.add(job)\n\n    # Run, catch warnings related to missing start and end job times\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        reference_sim_copy.compose()\n\n    print('\\nwaiting for job to complete...', end='')\n    reference_sim_copy.run()\n\n    # Wait to collect until job has finished. All test runs are performed on a single job with\n    # job_id='test_job'\n    wait_job(reference_sim_copy)\n\n    reference_sim_copy.collect()\n    reference_sim_copy.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n    # Check job run statuses\n    for job in reference_sim_copy.jobs:\n        assert job.exit_status == 0, \\\n            \"Reference code run exited with non-zero status\"\n\n\ndef test_ncores_candidate(output_dir, exe_cmd, ncores, xrcmp_n_cores, feature_ids):\n    print(\"\\nQuestion: The candidate outputs from a ncores run match outputs from\"\n          \" ncores-1 run?\\n\", end='')\n    print('\\n')\n\n    candidate_sim_file = output_dir / 'run_candidate' / 'WrfHydroSim.pkl'\n    candidate_collected_file = output_dir / 'run_candidate' / 'WrfHydroSim_collected.pkl'\n    if candidate_collected_file.is_file() is False:\n        pytest.skip('Candidate run object not found, skipping test.')\n\n    # Load initial sim object, collect sim_object and copy for makign new sims\n    candidate_sim = pickle.load(candidate_sim_file.open(mode=\"rb\"))\n    candidate_sim_expected = pickle.load(candidate_collected_file.open(mode=\"rb\"))\n    candidate_sim_ncores = copy.deepcopy(candidate_sim)\n\n    # Set run directory\n    run_dir = output_dir.joinpath('ncores_candidate')\n    if not run_dir.exists():\n        run_dir.mkdir(parents=True)\n        os.chdir(str(run_dir))\n\n        # Make a new job based on the old job but with a new job ID\n        old_job = candidate_sim.jobs[0]\n        out_dt = 1 if 'channel' in candidate_sim.model.model_config else 24\n        new_job = wrfhydropy.Job(\n            job_id='ncores_candidate',\n            exe_cmd=exe_cmd,\n            restart_freq_hr=24,\n            output_freq_hr=out_dt\n        )\n\n        # Remove old job and add new job\n        candidate_sim_ncores.jobs.pop(0)\n        candidate_sim_ncores.add(new_job)\n\n        # Edit the sim object number of cores\n        if candidate_sim_ncores.scheduler is not None:\n            core_reduction = 36 if int(ncores) >= 72 else 1\n            candidate_sim_ncores.scheduler.nproc = candidate_sim_ncores.scheduler.nproc - core_reduction\n        else:\n            candidate_sim_ncores.jobs[0]._exe_cmd = exe_cmd.format(str(int(ncores)-1))\n\n        # Recompose into new directory and run\n        # catch warnings related to missing start and end job times\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            candidate_sim_ncores.compose(force=True)\n\n        print('\\nwaiting for job to complete...', end='')\n        candidate_sim_ncores.run()\n\n        # Wait to collect until job has finished. All test runs are performed on a single job with\n        # job_id='test_job'\n        wait_job(candidate_sim_ncores)\n\n        candidate_sim_ncores.collect()\n        candidate_sim_ncores.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n        # Check job run statuses\n        for job in candidate_sim_ncores.jobs:\n            assert job.exit_status == 0, \\\n                \"Candidate code run exited with non-zero status\"\n\n    else:\n        print('Candidate n_cores run dir exists, skipping n_cores candidate run...')\n        candidate_sim_ncores = pickle.load(\n            run_dir.joinpath('WrfHydroSim_collected.pkl').open(mode=\"rb\"))\n\n    # Check outputs\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        diffs = wrfhydropy.outputdiffs.OutputDataDiffs(\n            candidate_sim_ncores.output,\n            candidate_sim_expected.output,\n            exclude_vars=EXCLUDE_VARS,\n            xrcmp_n_cores=xrcmp_n_cores\n        )\n\n    # Assert all diff values are 0 and print diff stats if not\n    has_diffs = any(value != 0 for value in diffs.diff_counts.values())\n    if has_diffs:\n        print_diffs(diffs)\n        plot_diffs(output_dir, 'run_candidate', 'ncores_candidate', 'ncores', feature_ids)\n    assert has_diffs is False, \\\n        'Outputs for candidate run with ncores do not match outputs with ncores-1'\n\n\ndef test_perfrestart_candidate(output_dir, xrcmp_n_cores, feature_ids):\n    print(\"\\nQuestion: The candidate outputs from a restart run match the outputs from standard \"\n          \"run?\\n\", end='')\n    print('\\n')\n\n    candidate_sim_file = output_dir / 'run_candidate' / 'WrfHydroSim.pkl'\n    candidate_collected_file = output_dir / 'run_candidate' / 'WrfHydroSim_collected.pkl'\n    if candidate_collected_file.is_file() is False:\n        pytest.skip('Candidate run object not found, skipping test.')\n\n    # Load initial run model object and copy\n    candidate_sim = pickle.load(candidate_sim_file.open(mode=\"rb\"))\n    candidate_sim_expected = pickle.load(candidate_collected_file.open(mode=\"rb\"))\n\n    # Set run directory\n    run_dir = output_dir.joinpath('restart_candidate')\n    if not run_dir.exists():\n        candidate_sim_restart = copy.deepcopy(candidate_sim)\n        run_dir.mkdir(parents=True)\n        os.chdir(str(run_dir))\n\n        # Get a new start time halfway along the run, make sure the restart frequency accomodates\n        restart_job = candidate_sim_restart.jobs[0]\n        duration = restart_job.model_end_time - restart_job.model_start_time\n        delay_restart_hr = int((duration.total_seconds() / 3600)/2)\n\n        # Want matching restart frequencies for this test...\n        assert \\\n            candidate_sim_restart.jobs[0].restart_freq_hr_hydro == \\\n            candidate_sim_restart.jobs[0].restart_freq_hr_hrldas, \\\n            \"Hydro and HRLDAS components do not have the same restart frequencies.\"\n\n        assert delay_restart_hr % candidate_sim_restart.jobs[0].restart_freq_hr_hydro == 0, \\\n            \"The restart delay is not a multiple of the hydro restart frequency.\"\n        restart_job.model_start_time = \\\n            restart_job.model_start_time + dt.timedelta(hours=delay_restart_hr)\n\n        # Get restart files from previous run and symlink into restart sim dir\n        # (Remember that we are in the run/sim dir)\n        # Hydro: Use actual time listed in meta data, not filename or positional list index\n        # JLM: seems like these loops can be replaced with a pathlib.Path.glob(), the loop is confusing.\n        for restart_file in candidate_sim_expected.output.restart_hydro:\n            if isinstance(restart_file, pathlib.Path):\n                restart_time = xr.open_dataset(restart_file).Restart_Time\n            else:\n                restart_time = restart_file.open().Restart_Time  # backwards compatible wrfhydropy\n            restart_time = pd.to_datetime(restart_time, format='%Y-%m-%d_%H:%M:%S')\n            if restart_time == restart_job.model_start_time:\n                candidate_hydro_restart_file = pathlib.Path(restart_file.name)\n                candidate_hydro_restart_file.symlink_to(restart_file)\n                key1 = 'hydro_nlist'\n                key2 = 'restart_file'\n                restart_job._hydro_namelist[key1][key2] = str(candidate_hydro_restart_file)\n\n        # LSM: Use actual time listed in meta data, not filename or positional list index\n        for restart_file in candidate_sim_expected.output.restart_lsm:\n            if isinstance(restart_file, pathlib.Path):\n                restart_time = xr.open_dataset(restart_file).Times[0]\n            else:\n                restart_time = restart_file.open().Times[0]  # backwards compatible wrfhydropy\n            restart_time = restart_time.astype(str).item(0)\n            restart_time = pd.to_datetime(restart_time, format='%Y-%m-%d_%H:%M:%S')\n            if restart_time == restart_job.model_start_time:\n                candidate_lsm_restart_file = pathlib.Path(restart_file.name)\n                candidate_lsm_restart_file.symlink_to(restart_file)\n                key1 = 'noahlsm_offline'\n                key2 = 'restart_filename_requested'\n                restart_job._hrldas_namelist[key1][key2] = str(candidate_lsm_restart_file)\n\n        # Nudging: Use actual time listed in meta data, not filename or positional list index\n        if candidate_sim_expected.output.restart_nudging is not None:\n            for restart_file in candidate_sim_expected.output.restart_nudging:\n                if isinstance(restart_file, pathlib.Path):\n                    restart_time = xr.open_dataset(restart_file).modelTimeAtOutput\n                else:\n                    restart_time = restart_file.open().modelTimeAtOutput  # backwards compatible wrfhydropy\n                restart_time = pd.to_datetime(restart_time, format='%Y-%m-%d_%H:%M:%S')\n                if restart_time == restart_job.model_start_time:\n                    candidate_nudging_restart_file = pathlib.Path(restart_file.name)\n                    candidate_nudging_restart_file.symlink_to(restart_file)\n                    key1 = 'nudging_nlist'\n                    key2 = 'nudginglastobsfile'\n                    restart_job._hydro_namelist[key1][key2] = str(candidate_nudging_restart_file)\n\n        # Compose and run\n        # catch warnings related to missing start and end job times\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            candidate_sim_restart.compose(force=True)\n\n        print('\\nwaiting for job to complete...', end='')\n        candidate_sim_restart.run()\n\n        # Wait to collect until job has finished. All test runs are performed on a single job with\n        wait_job(candidate_sim_restart)\n\n        candidate_sim_restart.collect()\n        candidate_sim_restart.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n        # Check job run statuses\n        for job in candidate_sim_restart.jobs:\n            assert job.exit_status == 0, \\\n                \"Candidate restart run exited with non-zero status\"\n\n    else:\n        print('Candidate channel-only perfect restart run dir exists, '\n              'skipping perfect restart candidate channel-only run...')\n        candidate_sim_restart = pickle.load(\n            open(run_dir.joinpath('WrfHydroSim_collected.pkl'), 'rb'))\n\n    # Check outputs\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        diffs = wrfhydropy.outputdiffs.OutputDataDiffs(\n            candidate_sim_restart.output,\n            candidate_sim_expected.output,\n            exclude_vars=EXCLUDE_VARS,\n            xrcmp_n_cores=xrcmp_n_cores\n        )\n\n    # Assert all diff values are 0 and print diff stats if not\n    has_diffs = any(value != 0 for value in diffs.diff_counts.values())\n    if has_diffs:\n        print_diffs(diffs)\n        plot_diffs(output_dir, 'run_candidate', 'restart_candidate', 'restart', feature_ids )\n    assert has_diffs is False, \\\n        'Outputs for candidate run do not match outputs from candidate restart run'\n"
  },
  {
    "path": "tests/test_2_regression.py",
    "content": "import pathlib\nimport pickle\nimport sys\nimport warnings\n\nimport pytest\nimport wrfhydropy\n\nsys.path.insert(0, str(pathlib.Path(__file__).parent))\nfrom utilities import print_diffs, plot_diffs\n\n# Ignore reference time in regression test because it depends on wall time of model run\nEXCLUDE_VARS = ['reference_time']\n\n# regression question\ndef test_regression_data(output_dir, xrcmp_n_cores, feature_ids):\n    print(\"\\nQuestion: The candidate run data values match the reference run?\\n\", end=\"\")\n    print('\\n')\n\n    # Check for existence of sim objects\n    candidate_run_file = output_dir / 'run_candidate' / 'WrfHydroSim_collected.pkl'\n    reference_run_file = output_dir / 'run_reference' / 'WrfHydroSim_collected.pkl'\n\n    if candidate_run_file.is_file() is False:\n        pytest.skip('Candidate run object not found, skipping test')\n    if reference_run_file.is_file() is False:\n        pytest.skip('Reference run object not found, skipping test')\n\n    # Load run objects\n    candidate_run_expected = pickle.load(candidate_run_file.open(mode=\"rb\"))\n    reference_run_expected = pickle.load(reference_run_file.open(mode=\"rb\"))\n\n    # Check regression\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        data_diffs = wrfhydropy.outputdiffs.OutputDataDiffs(\n            candidate_output=candidate_run_expected.output,\n            reference_output=reference_run_expected.output,\n            exclude_vars=EXCLUDE_VARS,\n            xrcmp_n_cores=xrcmp_n_cores\n        )\n\n    # Assert all diff values are 0 and print diff stats if not\n    has_data_diffs = any(value != 0 for value in data_diffs.diff_counts.values())\n    if has_data_diffs:\n        print_diffs(data_diffs)\n        plot_diffs(output_dir, 'run_candidate', 'run_reference', 'regression_output', feature_ids)\n    assert has_data_diffs is False, \\\n        'Data values in outputs for candidate run do not match reference run'\n\n\n# regression question\ndef test_regression_metadata(output_dir, xrcmp_n_cores):\n    print(\"\\nQuestion: The candidate run output metadata match the reference run?\\n\", end=\"\")\n    print('\\n')\n\n    # Check for existence of sim objects\n    candidate_run_file = output_dir / 'run_candidate' / 'WrfHydroSim_collected.pkl'\n    reference_run_file = output_dir / 'run_reference' / 'WrfHydroSim_collected.pkl'\n\n    if candidate_run_file.is_file() is False:\n        pytest.skip('Candidate run object not found, skipping test')\n    if reference_run_file.is_file() is False:\n        pytest.skip('Reference run object not found, skipping test')\n\n    # Load run objects\n    candidate_run_expected = pickle.load(candidate_run_file.open(mode=\"rb\"))\n    reference_run_expected = pickle.load(reference_run_file.open(mode=\"rb\"))\n\n    # Check regression\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        meta_data_diffs = wrfhydropy.outputdiffs.OutputMetaDataDiffs(\n            candidate_run_expected.output,\n            reference_run_expected.output,\n            exclude_vars=EXCLUDE_VARS,\n            xrcmp_n_cores=xrcmp_n_cores\n        )\n\n    # Assert all diff values are 0 and print diff stats if not\n    has_metadata_diffs = any(value != 0 for value in meta_data_diffs.diff_counts.values())\n    if has_metadata_diffs:\n        print_diffs(meta_data_diffs)\n    assert has_metadata_diffs is False, \\\n        'Metadata and attributes in outputs for candidate run do not match reference run'\n"
  },
  {
    "path": "tests/test_3_outputs.py",
    "content": "import pathlib\nimport pickle\n\ncandidate_run_file = pathlib.Path('run_candidate/WrfHydroSim_collected.pkl')\n\n\n# regression question\ndef test_output_has_nans(output_dir, xrcmp_n_cores):\n    print(\"\\nQuestion: Outputs from all tests are free of nans in data and attributes\\n\", end=\"\")\n    print('\\n')\n\n    sim_files = output_dir.rglob('WrfHydroSim_collected.pkl')\n\n    for file in sim_files:\n        sim = pickle.load(file.open('rb'))\n        sim_nans = sim.output.check_output_nans(n_cores=xrcmp_n_cores)\n        assert sim_nans is None, \\\n            'nans found in the following files ' + sim_nans['file'].unique()\n"
  },
  {
    "path": "tests/test_supp_1_channel_only.py",
    "content": "import copy\nimport datetime as dt\nimport os\nimport pandas as pd\nimport pathlib\nimport pytest\nimport pickle\nimport sys\nimport warnings\nimport wrfhydropy\nimport xarray as xr\n\nsys.path.insert(0, str(pathlib.Path(__file__).parent))\nfrom utilities import print_diffs, wait_job, plot_diffs\n\nEXCLUDE_VARS_CHAN_ONLY = [\n    'stc1',\n    'smc1',\n    'sh2ox1',\n    'stc2',\n    'smc2',\n    'sh2ox2',\n    'stc3',\n    'smc3',\n    'sh2ox3',\n    'stc4',\n    'smc4',\n    'sh2ox4',\n    'infxsrt',\n    'soldrain',\n    'sfcheadrt',\n    'QBDRYRT',\n    'infxswgt',\n    'sfcheadsubrt',\n    'sh2owgt1',\n    'sh2owgt2',\n    'sh2owgt3',\n    'sh2owgt4',\n    'qstrmvolrt',\n    'hlink',\n    'lake_inflort'\n]\n\n#List variabls to ignore in tests, primarily accumulation variables\nEXCLUDE_VARS = ['ACMELT',\n                'ACSNOW',\n                'SFCRUNOFF',\n                'UDRUNOFF',\n                'ACCPRCP',\n                'ACCECAN',\n                'ACCEDIR',\n                'ACCETRAN',\n                'qstrmvolrt',\n                'reference_time',\n                'lake_inflort']\n\nEXCLUDE_VARS_CHAN_ONLY = [\n    'stc1',\n    'smc1',\n    'sh2ox1',\n    'stc2',\n    'smc2',\n    'sh2ox2',\n    'stc3',\n    'smc3',\n    'sh2ox3',\n    'stc4',\n    'smc4',\n    'sh2ox4',\n    'infxsrt',\n    'soldrain',\n    'sfcheadrt',\n    'QBDRYRT',\n    'infxswgt',\n    'sfcheadsubrt',\n    'sh2owgt1',\n    'sh2owgt2',\n    'sh2owgt3',\n    'sh2owgt4',\n    'qstrmvolrt',\n    'hlink',\n    'lake_inflort'\n]\n\n#List variabls to ignore in tests, primarily accumulation variables\nEXCLUDE_VARS = ['ACMELT',\n                'ACSNOW',\n                'SFCRUNOFF',\n                'UDRUNOFF',\n                'ACCPRCP',\n                'ACCECAN',\n                'ACCEDIR',\n                'ACCETRAN',\n                'qstrmvolrt',\n                'reference_time',\n                'lake_inflort']\n\n# Channel-only Run\ndef test_run_candidate_channel_only(\n        candidate_sim,\n        candidate_channel_only_sim,\n        output_dir,\n        ncores,\n        exe_cmd\n):\n\n    if candidate_sim.model.model_config.lower().find('nwm_ana') < 0:\n        pytest.skip('Channel-only test only applicable to nwm_ana config')\n\n    print(\"\\nQuestion: The candidate channel-only mode runs successfully?\\n\", end='')\n    print('\\n')\n\n    # re-run candidate at shorter duration since requires hourly outputs\n\n    # Set run directory and change working directory to run dir for simulation\n    run_dir = output_dir / 'channel_only_candidate_full_model_run'\n    if run_dir.exists():\n        pytest.skip('Candidate channel-only run dir exists, skipping candidate channel-only run')\n    run_dir.mkdir(parents=True)\n    os.chdir(str(run_dir))\n\n    candidate_sim_copy = copy.deepcopy(candidate_sim)\n    candidate_sim_copy.base_hydro_namelist['hydro_nlist']['output_channelbucket_influx'] = 2\n    candidate_channel_only_sim_copy = copy.deepcopy(candidate_channel_only_sim)\n\n    # Job\n    exe_command = exe_cmd.format(str(ncores))\n    job = wrfhydropy.Job(\n        job_id='run_candidate',\n        exe_cmd=exe_command,\n        restart_freq_hr=6,\n        output_freq_hr=1\n    )\n    candidate_sim_copy.add(job)\n\n    start_time, end_time = candidate_sim_copy.jobs[0]._solve_model_start_end_times()\n    candidate_sim_copy.jobs[0].model_start_time = start_time\n    candidate_sim_copy.jobs[0].model_end_time = start_time + dt.timedelta(hours=24)\n\n    # Run, catch warnings related to missing start and end job times\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        candidate_sim_copy.compose()\n\n    print('\\nwaiting for job to complete...', end='')\n    candidate_sim_copy.run()\n    # Wait to collect until job has finished. All test runs are performed on a single job with\n    # job_id='test_job'\n    wait_job(candidate_sim_copy)\n\n    candidate_sim_copy.collect()\n    candidate_sim_copy.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n    # Check job run statuses\n    for job in candidate_sim.jobs:\n        assert job.exit_status == 0, \\\n            \"Candidate code run (for channel-only reference) exited with non-zero status\"\n\n    #########################\n    # Run channel only\n\n    # Dont recompile the model, just use the candidate's model.\n    candidate_channel_only_sim_copy.model = copy.deepcopy(candidate_sim.model)\n\n    # Set run directory and go for execution.\n    run_dir = output_dir / 'channel_only_candidate_run'\n    run_dir.mkdir(parents=True)\n    os.chdir(str(run_dir))\n\n    # Set the forcing directory\n    candidate_channel_only_sim_copy.base_hrldas_namelist['noahlsm_offline']['indir'] = \\\n        str(output_dir / 'channel_only_candidate_full_model_run')\n\n    # Job\n    exe_command = exe_cmd.format(str(ncores))\n    job = wrfhydropy.Job(\n        job_id='run_candidate_channel_only',\n        exe_cmd=exe_command,\n        restart_freq_hr=6,\n        output_freq_hr=1\n    )\n    candidate_channel_only_sim_copy.add(job)\n\n    start_time, end_time = candidate_channel_only_sim_copy.jobs[0]._solve_model_start_end_times()\n    candidate_channel_only_sim_copy.jobs[0].model_start_time = start_time\n    candidate_channel_only_sim_copy.jobs[0].model_end_time = start_time + dt.timedelta(hours=24)\n\n    # Run\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        candidate_channel_only_sim_copy.compose()\n\n    print('\\nwaiting for job to complete...', end='')\n    candidate_channel_only_sim_copy.run()\n    # Wait to collect until job has finished. All test runs are performed on a single job with\n    # job_id='test_job'\n    wait_job(candidate_channel_only_sim_copy)\n\n    candidate_channel_only_sim_copy.collect()\n    candidate_channel_only_sim_copy.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n    # Check job run statuses\n    for job in candidate_channel_only_sim_copy.jobs:\n        assert job.exit_status == 0, \\\n            \"Candidate channel-only code run exited with non-zero status\"\n\n\n# Channel-only matches full-model?\ndef test_channel_only_matches_full(\n    candidate_channel_only_sim,\n    output_dir,\n    xrcmp_n_cores,\n    feature_ids\n):\n\n    if candidate_channel_only_sim.model.model_config.lower().find('nwm') < 0:\n        pytest.skip('Channel-only test only applicable to nwm_ana config')\n\n    print(\"\\nQuestion: The candidate channel-only run output files match those of the full \"\n          \"model?\\n\", end=\"\")\n    print('\\n')\n\n    # Check for existence of simobjects\n    candidate_run_file = \\\n        output_dir / 'channel_only_candidate_full_model_run' / 'WrfHydroSim_collected.pkl'\n    candidate_channel_only_run_file = \\\n        output_dir / 'channel_only_candidate_run' / 'WrfHydroSim_collected.pkl'\n\n    if candidate_run_file.is_file() is False:\n        pytest.skip('Candidate run object not found, skipping test')\n    if candidate_channel_only_run_file.is_file() is False:\n        pytest.skip('candidate_channel_only run object not found, skipping test')\n\n    # Load run objects\n    candidate_run_expected = pickle.load(candidate_run_file.open(\"rb\"))\n    candidate_channel_only_run_expected = pickle.load(candidate_channel_only_run_file.open(\"rb\"))\n\n    # We still compare these:\n    # 'qlink1'\n    # 'qlink2'\n    # 'resht'\n    # 'qlakeo'\n    # 'z_gwsubbas'\n\n    # Dont compare metadata in this case, there are different dimensions\n    # in the files that always result in a return code of 1.\n    nccmp_options = ['--data', '--force', '--quiet']  # , '--metadata']\n\n    # Check diffs\n    # Run\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        diffs = wrfhydropy.outputdiffs.OutputDataDiffs(\n            candidate_run_expected.output,\n            candidate_channel_only_run_expected.output,\n            nccmp_options=nccmp_options,\n            exclude_vars=EXCLUDE_VARS_CHAN_ONLY,\n            xrcmp_n_cores=xrcmp_n_cores\n        )\n\n    has_diffs = any(value != 0 for value in diffs.diff_counts.values())\n    if has_diffs:\n        print_diffs(diffs)\n        plot_diffs(output_dir, 'channel_only_candidate_full_model_run', \n                    'channel_only_candidate_run', 'channel_only', feature_ids)\n    assert has_diffs is False, \\\n        'Outputs for candidate_channel_only run do not match outputs from candidate run'\n\n\n# Channel-only ncores question\ndef test_ncores_candidate_channel_only(\n    output_dir,\n    ncores,\n    exe_cmd,\n    xrcmp_n_cores,\n    feature_ids\n):\n\n    candidate_channel_only_sim_file = \\\n        output_dir / 'channel_only_candidate_run' / 'WrfHydroSim.pkl'\n    candidate_channel_only_collected_file = \\\n        output_dir / 'channel_only_candidate_run' / 'WrfHydroSim_collected.pkl'\n\n    if candidate_channel_only_collected_file.is_file() is False:\n        pytest.skip('candidate_channel_only collected run object not found, skipping test.')\n\n    print(\"\\nQuestion: The candidate_channel-only output files from an ncores runmatch those \"\n          \"from an ncores-1 run?\\n\", end='')\n    print('\\n')\n\n    candidate_channel_only_sim_expected = pickle.load(\n        candidate_channel_only_collected_file.open(\"rb\"))\n\n    run_dir = output_dir / 'channel_only_candidate_ncores'\n\n    if not run_dir.exists():\n        run_dir.mkdir(parents=True)\n        os.chdir(str(run_dir))\n\n        candidate_channel_only_sim = \\\n            pickle.load(candidate_channel_only_sim_file.open(\"rb\"))\n        candidate_channel_only_sim_ncores = copy.deepcopy(candidate_channel_only_sim)\n        candidate_channel_only_sim_ncores. \\\n            base_hydro_namelist['hydro_nlist']['output_channelbucket_influx'] = 2\n\n        old_job = candidate_channel_only_sim.jobs[0]\n        new_job = wrfhydropy.Job(\n            job_id='ncores_candidate',\n            model_start_time=old_job._model_start_time,\n            model_end_time=old_job._model_end_time,\n            exe_cmd=old_job._exe_cmd,\n            restart_freq_hr=6,\n            output_freq_hr=1\n        )\n\n        # Remove old job and add new job\n        candidate_channel_only_sim_ncores.jobs.pop(0)\n        candidate_channel_only_sim_ncores.add(new_job)\n\n        # Edit the sim object number of cores\n        if candidate_channel_only_sim_ncores.scheduler is not None:\n            candidate_channel_only_sim_ncores.scheduler.nproc = \\\n                candidate_channel_only_sim_ncores.scheduler.nproc - 1\n        else:\n            candidate_channel_only_sim_ncores.jobs[0]._exe_cmd = exe_cmd.format(str(int(ncores)-1))\n\n        # Recompose into new directory and run\n        # catch warnings related to missing start and end job times\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            candidate_channel_only_sim_ncores.compose(force=True)\n\n        print('\\nwaiting for job to complete...', end='')\n        candidate_channel_only_sim_ncores.run()\n\n        wait_job(candidate_channel_only_sim_ncores)\n\n        candidate_channel_only_sim_ncores.collect()\n        candidate_channel_only_sim_ncores.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n    else:\n        print('Candidate channel-only n_cores run dir exists, '\n              'skipping n_cores candidate channel-only run...')\n        candidate_channel_only_sim_ncores = pickle.load(\n            open(run_dir.joinpath('WrfHydroSim_collected.pkl'), 'rb'))\n\n    for job in candidate_channel_only_sim_ncores.jobs:\n        assert job.exit_status == 0, \\\n            \"Candidate channel-only ncores run exited with non-zero status\"\n\n    # Check outputs\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        diffs = wrfhydropy.outputdiffs.OutputDataDiffs(\n            candidate_channel_only_sim_ncores.output,\n            candidate_channel_only_sim_expected.output,\n            exclude_vars=EXCLUDE_VARS,\n            xrcmp_n_cores=xrcmp_n_cores\n        )\n\n    # Assert all diff values are 0 and print diff stats if not\n    has_diffs = any(value != 0 for value in diffs.diff_counts.values())\n    if has_diffs:\n        print_diffs(diffs)\n        plot_diffs(output_dir, 'channel_only_candidate_ncores', \n                    'channel_only_candidate_run', 'channel_only_ncores', feature_ids)\n    assert has_diffs is False, \\\n        'Outputs for candidate_channel_only run with ncores do not match outputs with ncores-1'\n\n\ndef test_perfrestart_candidate_channel_only(output_dir, xrcmp_n_cores, feature_ids):\n\n    candidate_channel_only_sim_file = \\\n        output_dir / 'channel_only_candidate_run' / 'WrfHydroSim.pkl'\n    candidate_channel_only_collected_file = \\\n        output_dir / 'channel_only_candidate_run' / 'WrfHydroSim_collected.pkl'\n\n    if candidate_channel_only_collected_file.is_file() is False:\n        pytest.skip('candidate_channel_only run object not found, skipping test')\n\n    print(\"\\nQuestion: The candidate_channel_only outputs from a restart run match the outputs \"\n          \"from standard run?\\n\", end='')\n    print('\\n')\n\n    candidate_channel_only_sim_expected = \\\n        pickle.load(candidate_channel_only_collected_file.open(mode=\"rb\"))\n\n    run_dir = output_dir / 'channel_only_candidate_restart'\n\n    if not run_dir.exists():\n\n        run_dir.mkdir(parents=True)\n        os.chdir(str(run_dir))\n\n        candidate_channel_only_sim = \\\n            pickle.load(candidate_channel_only_sim_file.open(mode=\"rb\"))\n        candidate_channel_only_sim_restart = copy.deepcopy(candidate_channel_only_sim)\n\n        # Get a new start time halfway along the run, make sure the restart frequency accomodates\n        restart_job = candidate_channel_only_sim_restart.jobs[0]\n        duration = restart_job.model_end_time - restart_job.model_start_time\n        delay_restart_hr = int((duration.total_seconds() / 3600)/2)\n\n        # Want matching restart frequencies for this test...\n        assert \\\n            candidate_channel_only_sim.jobs[0].restart_freq_hr_hydro == \\\n            candidate_channel_only_sim.jobs[0].restart_freq_hr_hrldas, \\\n            \"Hydro and HRLDAS components do not have the same restart frequencies.\"\n\n        assert delay_restart_hr % candidate_channel_only_sim.jobs[0].restart_freq_hr_hydro == 0, \\\n            \"The restart delay is not a multiple of the restart frequency.\"\n        restart_job.model_start_time = \\\n            restart_job.model_start_time + dt.timedelta(hours=delay_restart_hr)\n\n        # Get restart files from previous run and symlink into restart sim dir\n        # Hydro: Use actual time listed in meta data not filename or positional list index\n        for restart_file in candidate_channel_only_sim_expected.output.restart_hydro:\n            if isinstance(restart_file, pathlib.Path):\n                restart_time = xr.open_dataset(restart_file).Restart_Time\n            else:\n                restart_time = restart_file.open().Restart_Time  # backwards compatible wrfhydropy\n            restart_time = pd.to_datetime(restart_time, format='%Y-%m-%d_%H:%M:%S')\n            if restart_time == restart_job.model_start_time:\n                candidate_hydro_restart_file = pathlib.Path(restart_file.name)\n                candidate_hydro_restart_file.symlink_to(restart_file)\n                key1 = 'hydro_nlist'\n                key2 = 'restart_file'\n                restart_job._hydro_namelist[key1][key2] = candidate_hydro_restart_file\n\n        # Nudging: Use actual time listed in meta data not filename or positional list index\n        if candidate_channel_only_sim_expected.output.restart_nudging is not None:\n            for restart_file in candidate_channel_only_sim_expected.output.restart_nudging:\n                if isinstance(restart_file, pathlib.Path):\n                    restart_time = xr.open_dataset(restart_file).modelTimeAtOutput\n                else:\n                    restart_time = restart_file.open().modelTimeAtOutput  # backwards compatible wrfhydropy\n                restart_time = pd.to_datetime(restart_time, format='%Y-%m-%d_%H:%M:%S')\n                if restart_time == restart_job.model_start_time:\n                    candidate_nudging_restart_file = pathlib.Path(restart_file.name)\n                    candidate_nudging_restart_file.symlink_to(restart_file)\n                    key1 = 'nudging_nlist'\n                    key2 = 'nudginglastobsfile'\n                    restart_job._hydro_namelist[key1][key2] = candidate_nudging_restart_file\n\n        # Compose and run\n        # Catch warnings related to missing start and end job times\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            candidate_channel_only_sim_restart.compose(force=True)\n\n        print('\\nwaiting for job to complete...', end='')\n        candidate_channel_only_sim_restart.run()\n\n        wait_job(candidate_channel_only_sim_restart)\n\n        candidate_channel_only_sim_restart.collect()\n        candidate_channel_only_sim_restart.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n    else:\n        candidate_channel_only_sim_restart = pickle.load(\n            open(run_dir.joinpath('WrfHydroSim_collected.pkl'), 'rb'))\n\n    for job in candidate_channel_only_sim_restart.jobs:\n        assert job.exit_status == 0, \\\n            \"Candidate channel-only ncores run exited with non-zero status\"\n\n    # Check outputs\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        diffs = wrfhydropy.outputdiffs.OutputDataDiffs(\n            candidate_channel_only_sim_restart.output,\n            candidate_channel_only_sim_expected.output,\n            exclude_vars=EXCLUDE_VARS,\n            xrcmp_n_cores=xrcmp_n_cores\n        )\n\n    # Assert all diff values are 0 and print diff stats if not\n    has_diffs = any(value != 0 for value in diffs.diff_counts.values())\n    if has_diffs:\n        print_diffs(diffs)\n        plot_diffs(output_dir, 'channel_only_candidate_run',\n                    'channel_only_candidate_restart', 'channel_only_restart', feature_ids )\n    assert has_diffs is False, \\\n        'Outputs for candidate run do not match outputs from candidate restart run'\n"
  },
  {
    "path": "tests/test_supp_2_nwm_output.py",
    "content": "import copy\nimport datetime as dt\nimport os\nimport pathlib\nimport pickle\nimport sys\nimport warnings\nimport pandas as pd\nimport pytest\nimport wrfhydropy\n\nsys.path.insert(0, str(pathlib.Path(__file__).parent))\nfrom utilities import print_diffs, wait_job\n\ndef test_run_reference_nwm_output_sim(\n    reference_sim,\n    reference_nwm_output_sim,\n    output_dir,\n    ncores\n):\n\n    if reference_nwm_output_sim.model.model_config.lower().find('nwm') < 0:\n        pytest.skip('NWM Output test only applicable to nwm configs')\n\n    print(\"\\nQuestion: The reference nwm ouput configuration runs successfully?\\n\", end='')\n    print('\\n')\n\n    # Set run directory and change working directory to run dir for simulation\n    run_dir = output_dir / 'nwm_output_reference'\n    if run_dir.exists():\n        pytest.skip('Reference nwm output run exists, skipping nwm reference output run.')\n    run_dir.mkdir(parents=True)\n    os.chdir(str(run_dir))\n\n    reference_nwm_output_sim_copy = copy.deepcopy(reference_nwm_output_sim)\n    # Dont recompile the model, just use the reference's model.\n    reference_nwm_output_sim_copy.model = copy.deepcopy(reference_sim.model)\n\n    # Job\n    exe_command = 'mpirun -np {0} ./wrf_hydro'.format(str(ncores))\n    job = wrfhydropy.Job(\n        job_id='run_reference',\n        exe_cmd=exe_command,\n        restart_freq_hr=1,\n        output_freq_hr=1\n    )\n    reference_nwm_output_sim_copy.add(job)\n\n    # start_time, end_time = reference_nwm_output_sim_copy.jobs[0]._solve_model_start_end_times()\n    # reference_nwm_output_sim_copy.jobs[0].model_start_time = start_time\n    # reference_nwm_output_sim_copy.jobs[0].model_end_time = start_time + dt.timedelta(hours=24)\n    # reference_nwm_output_sim_copy.jobs[0].restart_freq_hr = 1\n\n    # Run, catch warnings related to missing start and end job times\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        reference_nwm_output_sim_copy.compose()\n\n    print('\\nwaiting for job to complete...', end='')\n    reference_nwm_output_sim_copy.run()\n    # Wait to collect until job has finished. All test runs are performed on a single job with\n    # job_id='test_job'\n    wait_job(reference_nwm_output_sim_copy)\n\n    reference_nwm_output_sim_copy.collect()\n    reference_nwm_output_sim_copy.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n    # Check job run statuses\n    for job in reference_nwm_output_sim.jobs:\n        assert job.exit_status == 0, \\\n            \"Reference run exited with non-zero status\"\n\n\ndef test_run_candidate_nwm_output_sim(\n    candidate_sim,\n    candidate_nwm_output_sim,\n    output_dir,\n    ncores\n):\n\n    if candidate_nwm_output_sim.model.model_config.lower().find('nwm') < 0:\n        pytest.skip('NWM Output test only applicable to nwm configs')\n\n    print(\"\\nQuestion: The candidate nwm ouput configuration runs successfully?\\n\", end='')\n    print('\\n')\n\n    # Set run directory and change working directory to run dir for simulation\n    run_dir = output_dir / 'nwm_output_candidate'\n    if run_dir.exists():\n        pytest.skip('Candidate nwm output run exists, skipping nwm candidate output run.')\n    run_dir.mkdir(parents=True)\n    os.chdir(str(run_dir))\n\n    candidate_nwm_output_sim_copy = copy.deepcopy(candidate_nwm_output_sim)\n    # Dont recompile the model, just use the candidate's model.\n    candidate_nwm_output_sim_copy.model = copy.deepcopy(candidate_sim.model)\n\n    # Job\n    exe_command = 'mpirun -np {0} ./wrf_hydro'.format(str(ncores))\n    job = wrfhydropy.Job(\n        job_id='run_candidate',\n        exe_cmd=exe_command,\n        restart_freq_hr=1,\n        output_freq_hr=1\n    )\n    candidate_nwm_output_sim_copy.add(job)\n\n    # start_time, end_time = candidate_nwm_output_sim_copy.jobs[0]._solve_model_start_end_times()\n    # candidate_nwm_output_sim_copy.jobs[0].model_start_time = start_time\n    # candidate_nwm_output_sim_copy.jobs[0].model_end_time = start_time + dt.timedelta(hours=24)\n    # candidate_nwm_output_sim_copy.jobs[0].restart_freq_hr = 1\n\n    # Run, catch warnings related to missing start and end job times\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        candidate_nwm_output_sim_copy.compose()\n\n    print('\\nwaiting for job to complete...', end='')\n    candidate_nwm_output_sim_copy.run()\n    # Wait to collect until job has finished. All test runs are performed on a single job with\n    # job_id='test_job'\n    wait_job(candidate_nwm_output_sim_copy)\n\n    candidate_nwm_output_sim_copy.collect()\n    candidate_nwm_output_sim_copy.pickle(run_dir.joinpath('WrfHydroSim_collected.pkl'))\n\n    # Check job run statuses\n    for job in candidate_nwm_output_sim.jobs:\n        assert job.exit_status == 0, \\\n            \"Candidate run exited with non-zero status\"\n\n\n# regression question\ndef test_regression_metadata_nwm_output(output_dir):\n    print(\"\\nQuestion: The NWM output candidate metadata match those of the reference run?\\n\", end=\"\")\n    print('\\n')\n\n    # Check for existence of sim objects\n    candidate_run_file = output_dir / 'nwm_output_candidate' / 'WrfHydroSim_collected.pkl'\n    reference_run_file = output_dir / 'nwm_output_reference' / 'WrfHydroSim_collected.pkl'\n\n    if candidate_run_file.is_file() is False:\n        pytest.skip('Candidate run object not found, skipping test')\n    if reference_run_file.is_file() is False:\n        pytest.skip('Reference run object not found, skipping test')\n\n    # Load run objects\n    candidate_run_expected = pickle.load(candidate_run_file.open(mode=\"rb\"))\n    reference_run_expected = pickle.load(reference_run_file.open(mode=\"rb\"))\n\n    # Check regression\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        meta_data_diffs = wrfhydropy.outputdiffs.OutputMetaDataDiffs(\n            candidate_run_expected.output,\n            reference_run_expected.output\n        )\n\n    # Assert all diff values are 0 and print diff stats if not\n    has_metadata_diffs = any(value != 0 for value in meta_data_diffs.diff_counts.values())\n    if has_metadata_diffs:\n        print_diffs(meta_data_diffs)\n    assert has_metadata_diffs is False, \\\n        'NWM output metadata and attributes of candidate run do not match those of the reference run.'\n"
  },
  {
    "path": "tests/utilities.py",
    "content": "import sys\nimport time\nimport os\n\nfrom wrfhydropy import *\n\n\ndef wait_job(sim):\n    \"\"\"\n    Function to wait for job completion\n    Args:\n        sim: A wrfhydropy simulation object\n    \"\"\"\n    file = sim.jobs[0].job_dir.joinpath('WrfHydroJob_postrun.pkl')\n    while True:\n        if file.exists():\n            break\n        time.sleep(5)\n\n\ndef eprint(*args, **kwargs):\n    \"\"\"\n    Function to mimic print function but to standard error instead of standard out\n    Args:\n        args: Arguments to standard print function\n        kwargs: keyword arguments to standard print function\n    \"\"\"\n    print(*args, file=sys.stderr, **kwargs)\n\n\ndef print_diffs(diffs):\n    \"\"\"\n    Function to print all diffs to stderr in a log-friendly manner\n    Args:\n        diffs: A wrfhydropy.output.OutputDiffs object\n    \"\"\"\n    eprint(diffs.diff_counts)\n    for key, value in diffs.diff_counts.items():\n        if value != 0:\n            diff_set = getattr(diffs, key)\n            eprint('\\n' + key + '\\n')\n            for a_diff in diff_set:\n                eprint(a_diff)\n\n\ndef plot_diffs(output_dir, candidatename, referencename, testname, feature_ids=None):\n    \"\"\"\n    Function to create diff plots\n    Args:\n        output_dir: The output directory for this configuration\n        candidatename: The name of the candidate run. Must match the name of the \n                       model output directory\n        referencename: The name of the reference run. Must match the name of the \n                       model output directory\n        testname: The name of the test being run. Plots will be placed in this\n                       named directory\n        feature_ids: A dict containing a list of channels and lake ids to create diff\n                       plots for, or None. If defined, should be {'channels': [], 'lakes': []}\n    \"\"\"\n    candidate = output_dir / candidatename\n    reference = output_dir / referencename\n    plots = output_dir / \"diff_plots\" / testname\n    script_dir = output_dir / \"../candidate_can_pytest/tests/local/utils\"\n\n    gen_script = script_dir / \"generate_diff_plots.py\"\n    thresholds = script_dir / \"thresholds.csv\"\n\n\n    cmd = f\"python {gen_script} -o {plots} -d \" + \\\n        f\"-b {reference} -B {referencename} -c {candidate} -C {candidatename} \" + \\\n        f\"-n -t {thresholds}\"\n\n    ldas_vars = ['ACCET','SFCRNOF','UGDRNOFF','SOIL_M','SNEQV','FSA','FIRA','TRAD','GRDFLX','LH','HFX']\n\n    cmd_gridded = cmd + \" -f ldas:\" + (\",\".join(ldas_vars)) + \" -f rtout\"\n\n    print(\"\\nPlotting gridded model diffs...\")\n    os.system(cmd_gridded)\n\n    if feature_ids is None:\n        return\n\n    if 'channels' in feature_ids:\n        cmd_feature = cmd + \" -f chrtout -i '\" + \",\".join(feature_ids['channels']) + \"'\"\n        print(\"\\nPlotting channel model diffs...\")\n        os.system(cmd_feature)\n\n    if 'lakes' in feature_ids:\n        cmd_feature = cmd + \" -f lakeout -i '\" + \",\".join(feature_ids['lakes']) + \"'\"\n        print(\"\\nPlotting lake model diffs...\")\n        os.system(cmd_feature)\n\n    if 'gwout' in feature_ids:\n        cmd_feature = cmd + \" -f gwout -i '\" + \",\".join(feature_ids['gwout']) + \"'\"\n        print(\"\\nPlotting gwout model diffs...\")\n        os.system(cmd_feature)\n\n\ndef make_sim(domain_dir,\n             compiler,\n             source_dir,\n             configuration,\n             option_suite,\n             ncores,\n             nnodes,\n             scheduler,\n             account,\n             walltime,\n             queue,\n             channel_only = False):\n    # model\n    model = Model(\n        compiler=compiler,\n        source_dir=source_dir,\n        model_config=configuration\n    )\n\n    # domain\n    domain = Domain(\n        domain_top_dir=domain_dir,\n        domain_config=configuration\n    )\n\n    # simulation\n    sim = Simulation()\n    sim.add(model)\n    sim.add(domain)\n\n    # Update base namelists with option suite if specified\n    if option_suite is not None:\n        pass\n\n    if scheduler:\n        sim.add(schedulers.PBSDerecho(account=account,\n                                      nproc=int(ncores),\n                                      nnodes=int(nnodes),\n                                      walltime=walltime,\n                                      queue=queue))\n\n    # Channel and bucket mode is forc_typ = 10.\n    if channel_only:\n        sim.base_hrldas_namelist['wrf_hydro_offline']['forc_typ'] = 10\n\n    return sim\n"
  },
  {
    "path": "tests/utils/compare_output.py",
    "content": "import os\nfrom pathlib import Path\nimport time\n\n\ndef plot_diffs(output_dir, candidatename, referencename, testname, feature_ids=None):\n    \"\"\"\n    Function to create diff plots\n    Args:\n        output_dir: The output directory for this configuration\n        candidatename: The name of the candidate run. Must match the name of the\n                       model output directory\n        referencename: The name of the reference run. Must match the name of the\n                       model output directory\n        testname: The name of the test being run. Plots will be placed in this\n                       named directory\n        feature_ids: A dict containing a list of channels and lake ids to create diff\n                       plots for, or None. If defined, should be {'channels': [], 'lakes': []}\n    \"\"\"\n    output_dir = Path(output_dir)\n    candidatename = Path(candidatename)\n    referencename = Path(referencename)\n    testname = Path(testname)\n\n    candidate = output_dir / candidatename\n    reference = output_dir / referencename\n    plots = output_dir / \"diff_plots\" / testname\n    # script_dir = output_dir / \"../candidate_can_pytest/tests/local/utils\"\n    # output_dir is at build/Run/output\n    script_dir = output_dir / \"../../../tests/local/utils\"\n    if not script_dir.is_dir():\n        script_dir.mkdir(parents=True)\n\n    gen_script = script_dir / \"generate_diff_plots.py\"\n    thresholds = script_dir / \"thresholds.csv\"\n\n\n    cmd = f\"python {gen_script} -o {plots} -d \" + \\\n        f\"-b {reference} -B {referencename} -c {candidate} -C {candidatename} \" + \\\n        f\"-n -t {thresholds}\"\n\n    ldas_vars = ['ACCET','SFCRNOF','UGDRNOFF','SOIL_M','SNEQV','FSA','FIRA','TRAD','GRDFLX','LH','HFX']\n\n    cmd_gridded = cmd + \" -f ldas:\" + (\",\".join(ldas_vars)) + \" -f rtout\"\n\n    print(\"\\nPlotting gridded model diffs...\")\n    os.system(cmd_gridded)\n\n    if feature_ids is None:\n        return\n\n    if 'channels' in feature_ids:\n        cmd_feature = cmd + \" -f chrtout -i '\" + \",\".join(feature_ids['channels']) + \"'\"\n        print(\"\\nPlotting channel model diffs...\")\n        os.system(cmd_feature)\n\n    if 'lakes' in feature_ids:\n        cmd_feature = cmd + \" -f lakeout -i '\" + \",\".join(feature_ids['lakes']) + \"'\"\n        print(\"\\nPlotting lake model diffs...\")\n        os.system(cmd_feature)\n\n    if 'gwout' in feature_ids:\n        cmd_feature = cmd + \" -f gwout -i '\" + \",\".join(feature_ids['gwout']) + \"'\"\n        print(\"\\nPlotting gwout model diffs...\")\n        os.system(cmd_feature)\n"
  },
  {
    "path": "tests/utils/xrcmp.py",
    "content": "#!/usr/bin/env python3\n\n# tool copied from wrfhydropy\n\n# Example Usage\n# ipython --pdb  xrcmp.py -- \\\n#     --candidate conus_test/201806012300.RTOUT_DOMAIN1 \\\n#     --reference conus_test/201806020000.RTOUT_DOMAIN1 \\\n#     --n_cores 8 \\\n#     --log_file log.txt\n\nimport math\nfrom multiprocessing import Pool\nimport os\nimport pathlib\nimport sys\n# import time\nimport xarray as xr\n\n\n# A dictionary of chunks for various variables for CONUS testing\n# These are for the larger fields which need some control\nconus_chunks_dict = {\n    # RTOUT variables to control\n    'SOIL_M': {},  # with {} maxes out at < 18% memory when files do NOT match\n    # HYDRO_RST variables: None currently\n}\n\n\n# # A decorator/closure to check timings.\n# def stopwatch(the_func):\n#     def the_closure(*args, **kw):\n#         ts = time.time()\n#         result = the_func(*args, **kw)\n#         te = time.time()\n#         print('Timing: ' + the_func.__name__ + ' took ', round(te - ts, 2),' seconds.')\n#         return result\n#     return the_closure\n\n\ndef calc_stats(arg_tuple):\n    key = arg_tuple[0]\n    can_file = arg_tuple[1]\n    ref_file = arg_tuple[2]\n    chunks = arg_tuple[3]\n    exclude_vars = arg_tuple[4]\n\n    # ignore excluded vars\n    if key in exclude_vars:\n        return None\n\n    if chunks is None:\n        chunks = {}  # default is no chunks\n        if key in conus_chunks_dict:\n            chunks = conus_chunks_dict[key]\n\n    can_ds = xr.open_dataset(can_file, chunks=chunks, mask_and_scale=False)\n    ref_ds = xr.open_dataset(ref_file, chunks=chunks, mask_and_scale=False)\n\n    # Check for variables in reference and not in candidate?\n    # Check for variables in candidate and not in reference?\n\n    if can_ds[key].equals(ref_ds[key]):\n        return None\n\n    else:\n        cc = can_ds[key]\n        rr = ref_ds[key]\n\n        if '|S' in str(cc.dtype):\n\n            # Deal with strings\n            # Use boolean indexer with `where` function\n            indexer = (cc != rr).compute()\n            nz_xr = cc.where(indexer, drop=True)\n            if len(nz_xr) == 0:\n                return None\n            else:\n                the_count = nz_xr.count().load().item(0)\n                inf = float('inf')\n                result = {\n                    'Variable': key,\n                    'Count': the_count,\n                    'Sum': inf,\n                    'Min': inf,\n                    'Max': inf,\n                    'Range': inf,\n                    'Mean':  inf,\n                    'StdDev': inf\n                }\n                return result\n\n        else:\n            # All non-string types\n            cc = cc.astype(float)\n            rr = rr.astype(float)\n\n            # THIS NEEDS REMOVED AFTER TESTING IS COMPLETE\n            # FOR convenience of comparing two files at different times.\n            # if 'time' in rr.coords:\n            #    rr['time'] = cc.time\n            # if key == 'time':\n            #    rr.values = cc.values\n\n            diff_da = cc - rr\n            diff_xr = xr.DataArray(diff_da.compute())\n            # TODO: This threshold should be type dependent\n            nz_xr = diff_xr.where(abs(diff_xr) > 0.000000, drop=True)\n            if len(nz_xr) == 0:\n                return None\n\n            the_count = nz_xr.count().load().item(0)\n            the_sum = nz_xr.sum().load().item(0)\n            the_min = nz_xr.min().load().item(0)\n            the_max = nz_xr.max().load().item(0)\n            the_range = the_max - the_min\n            the_mean = the_sum / the_count\n            the_z = (nz_xr - the_mean)\n            the_std = math.sqrt((the_z * the_z).sum() / the_count)\n            del the_z\n\n            result = {\n                'Variable': key,\n                'Count': the_count,\n                'Sum': the_sum,\n                'Min': the_min,\n                'Max': the_max,\n                'Range': the_range,\n                'Mean':  the_mean,\n                'StdDev': the_std\n            }\n            return result\n\n\n# @stopwatch\ndef xrcmp(\n    can_file: str,\n    ref_file: str,\n    log_file: str,\n    n_cores: int = 1,\n    chunks={},\n    exclude_vars: list = [],\n    interactive: bool = False\n) -> int:\n\n    if exclude_vars is None:\n        exclude_vars = []\n\n    # Delete log file first\n    # Should write a log file that says nothing yet determined?\n    log_file = pathlib.Path(log_file)\n    if log_file.exists() and not interactive:\n        log_file.unlink()\n\n    # Dont chunk, this is just a meta-data read.\n    can_ds = xr.open_dataset(can_file)\n    ref_ds = xr.open_dataset(ref_file)\n\n    # May need to check that they have the same vars.\n    can_vars = set([kk for kk in can_ds.variables.keys()])\n    ref_vars = set([kk for kk in ref_ds.variables.keys()])\n    have_same_variables = can_vars.difference(ref_vars) == set([])\n    can_ds.close()  # These are likely critical to the success\n    ref_ds.close()  # of multiprocessing\n\n    # TODO: Check that the meta data matches\n\n    # This is quick if not true\n    # ds_equal = can_ds.equals(re_ds)\n    # if not ds_equal:\n\n    if n_cores == 1:\n        all_stats_list = []\n        for key, val in can_ds.items():\n            result = calc_stats(\n                (key, can_file, ref_file, chunks, exclude_vars))\n            all_stats_list.append(result)\n    else:\n        the_args = [\n            (key, can_file, ref_file, chunks, exclude_vars) for key in can_ds.keys()]\n        with Pool(n_cores) as pool:\n            all_stats_list = pool.map(calc_stats, the_args)\n\n    all_stats = {item['Variable']: item for item in all_stats_list if item is not None}\n\n    diff_var_names = sorted(all_stats.keys())\n    if not diff_var_names:\n        with open(log_file, 'a') as opened_file:\n            opened_file.write(f\"Files are identical: {os.path.basename(ref_file)}\\n\")\n        return 0\n\n    # Formatting:\n\n    # The goal is to print something like this which is what nccmp outputs.\n    # channel_rt\n    #      Variable Group  Count       Sum  ...       Max     Range      Mean    StdDev\n    # 0  streamflow     /    162  0.003022  ...  0.003832  0.004315  0.000019  0.000361\n    # 1       nudge     /      4 -0.001094  ...  0.000093  0.001272 -0.000274  0.000605\n    # 2   q_lateral     /    170  0.000345  ...  0.000700  0.001145  0.000002  0.000086\n    # 3    velocity     /    165  0.010788  ...  0.005488  0.006231  0.000065  0.000503\n    # 4        Head     /    177  0.002717  ...  0.002662  0.003292  0.000015  0.000258\n\n    stat_names = sorted(all_stats[diff_var_names[0]].keys())\n    stat_lens = {}  # the length/width of each column/stat\n    n_dec = 3  # number of decimals for floats\n    n_dec_p = n_dec + 1  # plus the decimal point\n\n    # The format for each type, where full_len sepcifices the width of the field.\n    type_fmt = {\n        str: '{{:{full_len}}}',\n        int: '{{:{full_len}}}',\n        float: '{{:{full_len}.' + str(n_dec) + 'f}}'\n    }\n\n    # Now solve the full_len field widths for all stats. Do this by\n    # just formatting each as it's type and finding the max (best way\n    # to handle negatives). For floats, take the integer part to find\n    # its length to the left of the decimal.\n    for stat_name in stat_names:\n        all_lens = []\n        for key, val in all_stats.items():\n            the_val = val[stat_name]\n            the_type = type(the_val)\n            the_fmt0 = type_fmt[the_type]\n            if the_type is str:\n                full_len = len(the_val)\n            elif not math.isfinite(the_val):\n                full_len = len(str(the_val))\n            else:\n                full_len = len(str(int(the_val)))\n                if the_type is float:\n                    full_len = full_len + n_dec_p\n            the_fmt = the_fmt0.format(**{'full_len': full_len})\n            the_string = the_fmt.format(*[the_val])\n            all_lens.append(len(the_string))\n\n        stat_lens[stat_name] = max(all_lens)\n\n    header_string = (\n        '{Variable:>' + str(stat_lens['Variable']) + '}  '\n        '{Count:>' + str(stat_lens['Count']) + '}  '\n        '{Sum:>' + str(stat_lens['Sum']) + '}  '\n        '{Min:>' + str(stat_lens['Min']) + '}  '\n        '{Max:>' + str(stat_lens['Max']) + '}  '\n        '{Range:>' + str(stat_lens['Range']) + '}  '\n        '{Mean:>' + str(stat_lens['Mean']) + '}  '\n        '{StdDev:>' + str(stat_lens['StdDev']) + '}  \\n'\n    )\n\n    var_string = (\n        '{Variable:>' + str(stat_lens['Variable']) + '}  '\n        '{Count:>' + str(stat_lens['Count']) + '}  '\n        '{Sum:>' + str(stat_lens['Sum']) + '.' + str(n_dec) + 'f}  '\n        '{Min:>' + str(stat_lens['Min']) + '.' + str(n_dec) + 'f}  '\n        '{Max:>' + str(stat_lens['Max']) + '.' + str(n_dec) + 'f}  '\n        '{Range:>' + str(stat_lens['Range']) + '.' + str(n_dec) + 'f}  '\n        '{Mean:>' + str(stat_lens['Mean']) + '.' + str(n_dec) + 'f}  '\n        '{StdDev:>' + str(stat_lens['StdDev']) + '.' + str(n_dec) + 'f}  \\n'\n    )\n\n    header_dict = {name: name for name in stat_names}\n    the_header = header_string.format(**header_dict)\n\n    if len(all_stats) > 0:\n        print(the_header, end='')\n    for key in all_stats.keys():\n        print(var_string.format(**all_stats[key]), end='')\n\n    with open(log_file, 'w') as opened_file:\n        opened_file.write(the_header)\n        for key in all_stats.keys():\n            opened_file.write(var_string.format(**all_stats[key]))\n\n    return 1\n\n\ndef parse_arguments():\n\n    import argparse\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--candidate\", metavar=\"FILE\", type=str, required=True,\n        help=\"Candidate file to compare.\"\n    )\n    parser.add_argument(\n        \"--reference\", metavar=\"FILE\", type=str, required=True,\n        help=\"Reference file to compare.\"\n    )\n    parser.add_argument(\n        \"--log_file\", metavar=\"FILE\", type=str, required=True,\n        help=\"File to log potential differences to. \"\n        \"Existing file is clobbered.\"\n    )\n    parser.add_argument(\n        \"--n_cores\", metavar=\"n_cores\", type=int, required=False,\n        default=1,\n        help=\"The number of processors to use.\"\n    )\n    parser.add_argument(\n        \"--chunks\", metavar=\"chunks\", type=int, required=False,\n        default=1,\n        help=\"Chunks as integer.\"\n    )\n    parser.add_argument(\n        \"-i\", \"--interactive\", action='store_true', default=False,\n        help=\"Run in interactive mode for local analysis.\"\n    )\n\n    args = parser.parse_args()\n    can_file = args.candidate\n    ref_file = args.reference\n    log_file = args.log_file\n    chunks = args.chunks\n    n_cores = args.n_cores\n    interactive = args.interactive\n\n    if chunks == 1:\n        chunks = {}    # No chunking\n    elif chunks == 0:\n        chunks = None  # This will use the conus_chunks_dict\n\n    return can_file, ref_file, log_file, chunks, n_cores, interactive\n\nif __name__ == \"__main__\":\n\n    can_file, ref_file, log_file, chunks, n_cores, inter = parse_arguments()\n    ret = xrcmp(\n        can_file=can_file,\n        ref_file=ref_file,\n        log_file=log_file,\n        n_cores=n_cores,\n        chunks=chunks,\n        interactive=inter\n    )\n    sys.exit(ret)\n"
  },
  {
    "path": "tests/utils/xrnan.py",
    "content": "# tool copied from wrfhydropy\n\nfrom multiprocessing import Pool\nimport pathlib\nimport sys\nfrom typing import Union\nimport xarray as xr\n\n\ndef check_nans(arg_dict):\n    var_name = arg_dict['var_name']\n    if 'path' in arg_dict.keys():\n        path = arg_dict['path']\n        ds = xr.open_dataset(path, mask_and_scale=False)\n    else:\n        ds = arg_dict['ds']\n    if ds[var_name].isnull().any().values:\n        return var_name\n    else:\n        return None\n\n\ndef xrnan(\n    dataset_or_path: Union[str, pathlib.Path, xr.Dataset],\n    log_file: str = None,\n    exclude_vars: list = [],\n    chunks=None,\n    n_cores: int = 1\n) -> int:\n    # Set filepath to strings\n    if not isinstance(dataset_or_path, xr.Dataset):\n        ds = xr.open_dataset(str(dataset_or_path), mask_and_scale=False, chunks=chunks)\n    else:\n        ds = dataset_or_path\n\n    # Looping on variables is much faster for small applications and parallelizable\n    # for larger ones.\n    if n_cores < 2 or isinstance(dataset_or_path, xr.Dataset):\n        nan_vars = []\n        for var_name in ds.variables:\n            nan_vars.append(check_nans({'var_name': var_name, 'ds': ds}))\n        ds.close()\n    else:\n        # The following ds.close() is CRITICAL to the correct results being returned by\n        # multiprocessing\n        ds.close()\n        the_args = [{'var_name': var_name, 'path': dataset_or_path}\n                    for var_name in ds.variables]\n        with Pool(n_cores) as pool:\n            nan_vars = pool.map(check_nans, the_args)\n\n    nan_vars_2 = [var for var in nan_vars if var is not None]\n\n    if len(nan_vars_2) == 0:\n        return None\n    else:\n        for var in nan_vars_2:\n            print(str(dataset_or_path), ': variable \"' + var + ''\n                  '' + '\" contains NaNs')\n        return {'vars': nan_vars_2}\n\n\ndef parse_arguments():\n\n    import argparse\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--path\", metavar=\"FILE\", type=str, required=True,\n        help=\"File to check for NaNs.\"\n    )\n    parser.add_argument(\n        \"--log_file\", metavar=\"FILE\", type=str, required=True,\n        help=\"File to log potential differences to. \"\n        \"Existing file is clobbered.\"\n    )\n    args = parser.parse_args()\n    path = args.path\n    log_file = args.log_file\n    return path, log_file\n\n\nif __name__ == \"__main__\":\n\n    path, log_file = parse_arguments()\n    ret = xrnan(path, log_file=log_file)\n    if ret is None:\n        exit_code = 0\n    else:\n        exit_code = 1\n    sys.exit(exit_code)\n"
  }
]